Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
153 changes: 71 additions & 82 deletions pyxtal/symmetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -693,6 +693,11 @@ def get_lattice_dof(self):

return dof

def _get_general_ops(self):
if hasattr(self, "Wyckoff_positions") and len(self.Wyckoff_positions) > 0:
return self.Wyckoff_positions[0].ops
return get_wyckoffs(self.number, dim=self.dim)[0]

def is_valid_hkl(self, h, k, l):
"""
Check if the given (h, k, l) is allowed by the space group symmetry.
Expand All @@ -705,9 +710,14 @@ def is_valid_hkl(self, h, k, l):
Returns:
bool: True if (h, k, l) is allowed, False otherwise
"""
# Check if the (h, k, l) is allowed by the space group symmetry
# This is a placeholder implementation and should be replaced with the actual symmetry check
return is_hkl_allowed(h, k, l, self.number)
vec = np.array([h, k, l], dtype=int)
for op in self._get_general_ops():
rot = np.rint(op.rotation_matrix).astype(int)
if np.array_equal(vec @ rot, vec):
dot = float(vec @ op.translation_vector)
if abs(dot - round(dot)) > 1e-6:
return False
return True

def get_reflection_conditions(self):
"""
Expand Down Expand Up @@ -773,91 +783,70 @@ def generate_possible_hkls(self, h_max, k_max=None, l_max=None, max_square=12):
This function considers the extinction conditions to limit the hkls.

Args:
max_h: maximum absolute value for h, k, l
h_max: maximum absolute value for h
k_max: maximum absolute value for k (defaults to h_max)
l_max: maximum absolute value for l (defaults to h_max)
max_square: maximum h^2 + k^2 + l^2
"""
if k_max is None: k_max = h_max
if l_max is None: l_max = h_max
if k_max is None:
k_max = h_max
if l_max is None:
l_max = h_max

if self.number > 194: # cubic
base_signs = [(1, 1, 1)]
elif self.number >= 143: # hexagonal/trigonal
base_signs = [(1, 1, 1), (1, -1, 1)]
elif self.number >= 16: # orthorhombic
base_signs = [(1, 1, 1)]
elif self.number >= 3: # 2/m
base_signs = [(1, 1, 1), (1, 1, -1)]
#elif self.number >= 6: # m
# base_signs = [(1, 1, 1), (1, 1, -1), (-1, 1, 1), (-1, 1, -1)]
#elif self.number >= 3: # 2
# base_signs = [(1, 1, 1), (1, -1, 1), (-1, 1, 1), (1, -1, -1)]
#elif self.number >= 2: # -1
# base_signs = [(1, 1, 1), (1, 1, -1), (1, -1, 1), (-1, 1, 1)]
else: # 1
base_signs = [(1, 1, 1), (1, 1, -1), (1, -1, 1), (-1, 1, 1),
(1, -1, -1), (-1, 1, -1), (-1, -1, 1), (-1, -1, -1)]
# Generate all possible hkls and filter by extinction rules
possible_hkls = []
canonical_seen = set() # Track canonical forms to avoid duplicates
symmetry_seen = set() # Track symmetry-equivalent hkls
ops = self._get_general_ops()
rotations = np.array([np.rint(op.rotation_matrix).astype(int) for op in ops], dtype=int)
translations = np.array([op.translation_vector for op in ops], dtype=float)

# Build reciprocal-space rotation operators from the general Wyckoff position
reciprocal_ops = []
# Unique Laue rotation matrices acting on row vector h -> h @ R (including Friedel inversion)
laue_rots = []
op_seen = set()
if len(self.wyckoffs) > 0 and len(self.wyckoffs[0]) > 0:
for op in self.wyckoffs[0]:
try:
matrix = np.rint(np.linalg.inv(op.rotation_matrix).T).astype(int)
except np.linalg.LinAlgError:
continue
key = tuple(matrix.flatten().tolist())
for rot in rotations:
for sign in (1, -1):
mat = sign * rot
key = mat.tobytes()
if key not in op_seen:
op_seen.add(key)
reciprocal_ops.append(matrix)
if len(reciprocal_ops) == 0:
reciprocal_ops = [np.eye(3, dtype=int)]

def get_symmetry_key(hkl):
vec = np.array(hkl, dtype=int)
orbit = [tuple((matrix @ vec).tolist()) for matrix in reciprocal_ops]
return max(orbit)

for h in range(0, h_max + 1):
# add permutation
k_min = 0 #if self.number > 3 else h
for k in range(k_min, k_max + 1):
# add additional
l_min = 0 #if self.number > 15 else h
for l in range(l_min, l_max + 1):
if h == 0 and k == 0 and l == 0: # Exclude (0,0,0)
continue
if h*h + k*k + l*l > max_square:
continue

canonical = get_canonical_hkl(h, k, l, self.number)
if canonical in canonical_seen: continue

if h*h + k*k + l*l > 0: # exclude (0,0,0)
# Add all permutations and sign variations
valid_hkls = []
for signs in base_signs:
if 2 < self.number < 16 and h == 0 and signs[2]==-1: continue
sh, sk, sl = signs[0]*h, signs[1]*k, signs[2]*l
if is_hkl_allowed(sh, sk, sl, self.number):
if (sh, sk, sl) not in valid_hkls:
valid_hkls.append((sh, sk, sl))
#print('AAAAAAAAAAAAAAAAAAA', h, k, l, sh, sk, sl)
if valid_hkls:
canonical_seen.add(canonical)
for hkl in valid_hkls:
symmetry_key = get_symmetry_key(hkl)
if symmetry_key not in symmetry_seen:
symmetry_seen.add(symmetry_key)
possible_hkls.append(hkl)

# Sort by h²+k²+l² in ascending order
possible_hkls.sort(key=lambda hkl: hkl[0]**2 + hkl[1]**2 + hkl[2]**2)

return possible_hkls # remove duplicates
laue_rots.append(mat)
laue_rots = np.array(laue_rots, dtype=int)

# Scan the half-space h >= 0 (covers all reflections up to Friedel inversion)
hs = np.arange(0, h_max + 1, dtype=int)
ks = np.arange(-k_max, k_max + 1, dtype=int)
ls = np.arange(-l_max, l_max + 1, dtype=int)
grid = np.stack(np.meshgrid(hs, ks, ls, indexing="ij"), axis=-1).reshape(-1, 3)
sq = np.sum(grid * grid, axis=1)
mask = (sq > 0) & (sq <= max_square)
h0 = grid[:, 0] == 0
mask &= (~h0) | (grid[:, 1] > 0) | ((grid[:, 1] == 0) & (grid[:, 2] > 0))
candidates = grid[mask]
if len(candidates) == 0:
return []

# Order by ascending h^2+k^2+l^2, preferring fewer negative indices
neg_count = np.sum(candidates < 0, axis=1)
order = np.lexsort((candidates[:, 2], candidates[:, 1], candidates[:, 0], neg_count, sq[mask]))
candidates = candidates[order]

# Filter systematic absences: h is absent when some (R, t) gives h @ R == h and h @ t not integer
rotated = np.einsum("ni,mij->nmj", candidates, rotations)
fixed = np.all(rotated == candidates[:, None, :], axis=2)
dots = candidates @ translations.T
non_int = np.abs(dots - np.rint(dots)) > 1e-6
candidates = candidates[~np.any(fixed & non_int, axis=1)]
if len(candidates) == 0:
return []

# Deduplicate by Laue symmetry orbit
orbits = np.einsum("ni,lij->nlj", candidates, laue_rots)
possible_hkls = []
symmetry_seen = set()
for idx, hkl in enumerate(candidates):
key = max(map(tuple, orbits[idx].tolist()))
if key not in symmetry_seen:
symmetry_seen.add(key)
possible_hkls.append((int(hkl[0]), int(hkl[1]), int(hkl[2])))

return possible_hkls

def generate_hkl_guesses(self, h_max=2, k_max=None, l_max=None, max_square=12,
total_square=100, max_size=2000000, reduce=True,
Expand Down
65 changes: 65 additions & 0 deletions tests/test_symmetry.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
# python -m unittest pyxtal/test_all.py
import importlib.util
import itertools
import os
import unittest

import numpy as np

from pyxtal.lattice import Lattice
from pyxtal.symmetry import Group, Wyckoff_position, get_canonical_hkl, get_canonical_hkl_series

Expand Down Expand Up @@ -166,6 +169,68 @@ def test_site_symms(self):
wp.get_site_symmetry()
assert wp.site_symm == d[i]

def test_is_valid_hkl_matches_symops(self):
cases = [
(14, 1, 0, 1, False),
(14, 1, 0, -1, False),
(14, 1, 0, 2, True),
(109, 1, 1, 0, False),
(113, 0, 0, 1, True),
(138, 1, 1, 1, True),
(167, 0, -1, 1, False),
(194, 1, 1, 1, False),
(223, 1, 2, 2, False),
]
for spg, h, k, l, expected in cases:
assert Group(spg).is_valid_hkl(h, k, l) == expected

# Non-standard Hall setting P21/n (82): h0l has h + l = 2n
assert Group(81, use_hall=True).is_valid_hkl(1, 0, 1) is False
assert Group(82, use_hall=True).is_valid_hkl(1, 0, 1) is True

def test_generate_possible_hkls_all_space_groups(self):
probe_hkls = [
hkl
for hkl in itertools.product(range(-3, 4), repeat=3)
if any(hkl) and sum(x * x for x in hkl) <= 9
]
for number in range(1, 231):
group = Group(number)
ops = group.Wyckoff_positions[0].ops
rots = [np.rint(op.rotation_matrix).astype(int) for op in ops]
trans = [op.translation_vector for op in ops]

def is_absent(h):
vec = np.array(h, dtype=int)
for rot, tran in zip(rots, trans):
if np.array_equal(vec @ rot, vec):
phase = (vec @ tran) % 1
if min(phase, 1 - phase) > 1e-6:
return True
return False

def laue_family(h):
vec = np.array(h, dtype=int)
return {
tuple(int(x) for x in s * (vec @ rot))
for rot in rots
for s in (1, -1)
}

listed_list = group.generate_possible_hkls(h_max=3, max_square=27)
listed = set(listed_list)
assert all(not is_absent(hkl) for hkl in listed), f"SG {number} listed absent reflection"

seen_families = set()
for hkl in listed_list:
key = max(laue_family(hkl))
assert key not in seen_families, f"SG {number} duplicated Laue family {key}"
seen_families.add(key)

for hkl in probe_hkls:
if not is_absent(hkl):
assert laue_family(hkl) & listed, f"SG {number} dropped family of {hkl}"


if __name__ == "__main__":
unittest.main()