Coverage for dynasor/modes/atoms.py: 99%
86 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-09 14:30 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-09 14:30 +0000
1import numpy as np
2from ase import Atoms
3from numpy.typing import NDArray
4from ..qpoints.lattice import Lattice
5from ..tools.structures import get_offset_index
6from ..units import Dalton_to_dmu
9class DynasorAtoms:
10 """Dynasor's representation of a structure."""
11 def __init__(self, atoms: Atoms):
12 """Initialized using an ASE Atoms object"""
13 if not isinstance(atoms, Atoms):
14 raise TypeError(f'atoms must be an ASE Atoms object, not {type(atoms).__name__}.')
15 self._atoms = atoms
17 @property
18 def pos(self) -> NDArray[float]:
19 """Cartesian positions."""
20 return self._atoms.positions.copy()
22 @property
23 def positions(self) -> NDArray[float]:
24 """Cartesian positions."""
25 return self.pos
27 @property
28 def spos(self) -> NDArray[float]:
29 """Reduced (or scaled) positions of atoms."""
30 return self._atoms.get_scaled_positions()
32 @property
33 def scaled_positions(self) -> NDArray[float]:
34 """Reduced (or scaled) positions of atoms."""
35 return self.spos
37 @property
38 def cell(self) -> NDArray[float]:
39 """Cell of atoms with cell vectors as rows."""
40 return self._atoms.cell.array.copy()
42 @property
43 def inv_cell(self) -> NDArray[float]:
44 """The inverse cell transpose so the inverse cell vectors are rows, no 2pi."""
45 return np.linalg.inv(self._atoms.cell.array).T
47 @property
48 def numbers(self) -> NDArray[int]:
49 """Chemical number for each atom, e.g., 1 for H, 2 for He etc."""
50 return self._atoms.numbers.copy()
52 @property
53 def masses(self) -> NDArray[float]:
54 """Masses of atoms in dmu."""
55 return self._atoms.get_masses() * Dalton_to_dmu # In eVfs²/Ų
57 @property
58 def volume(self) -> float:
59 """Volume of cell."""
60 return self._atoms.get_volume()
62 @property
63 def n_atoms(self) -> int:
64 """Number of atoms."""
65 return len(self._atoms)
67 @property
68 def symbols(self) -> list[str]:
69 """List of chemical symbol for each element."""
70 return list(self._atoms.symbols)
72 def to_ase(self) -> Atoms:
73 """Converts the internal Atoms to ASE :class:`~ase.Atoms`."""
74 return Atoms(cell=self.cell, numbers=self.numbers, positions=self.positions, pbc=True,
75 masses=self._atoms.get_masses())
77 def __str__(self) -> str:
78 return f'{self.__class__.__name__} with {self.n_atoms} atoms'
80 def __repr__(self) -> str:
81 return str(self)
84class Prim(DynasorAtoms):
85 """The primitive cell underlying a :class:`Supercell`."""
87 def __str__(self):
88 strings = [f"""Primitive cell:
89Number of atoms: {self.n_atoms}
90Volume: {self.volume:.3f}
91Atomic species present: {set(self.symbols)}
92Atomic numbers present: {set([int(n) for n in self.numbers])}
93Cell:
94[[{self.cell[0, 0]:<20}, {self.cell[0, 1]:<20}, {self.cell[0, 2]:<20}],
95 [{self.cell[1, 0]:<20}, {self.cell[1, 1]:<20}, {self.cell[1, 2]:<20}],
96 [{self.cell[2, 0]:<20}, {self.cell[2, 1]:<20}, {self.cell[2, 2]:<20}]]
97"""]
98 strings.append(f"{'Ind':<5}{'Sym':<5}{'Num':<5}{'Mass (Da)':<10}{'x':<10}{'y':<10}{'z':<10}"
99 f"{'a':<10}{'b':<10}{'c':<10}")
100 atom_s = []
101 for i, p, sp, m, n, s in zip(
102 range(self.n_atoms), self.positions, self.spos, self.masses / Dalton_to_dmu,
103 self.numbers, [a.symbol for a in self.to_ase()]):
104 atom_s.append(f'{i:<5}{s:<5}{n:<5}{m:<10.2f}{p[0]:<10.3f}{p[1]:<10.3f}{p[2]:<10.3f}'
105 f'{sp[0]:<10.3f}{sp[1]:<10.3f}{sp[2]:<10.3f}')
107 strings = strings + atom_s
109 string = '\n'.join(strings)
111 return string
114class Supercell(DynasorAtoms):
115 """The supercell takes care of some mappings between the primitive and repeated structure.
117 In particular the P-matrix connecting the cells as well as the offset-index of each atom is
118 calculated.
120 Note that the positions cannot be recovered as `offset x cell + basis` since the atoms get
121 wrapped.
123 Parameters
124 ----------
125 supercell
126 Some ideal repetition of the primitive structure and possible wrapping.
127 prim
128 Primitive structure.
129 """
131 def __init__(self, supercell: Atoms, prim: Atoms):
132 if not isinstance(supercell, Atoms):
133 raise TypeError(
134 f'supercell must be an ASE Atoms object, not {type(supercell).__name__}.')
135 if not isinstance(prim, Atoms):
136 raise TypeError(f'prim must be an ASE Atoms object, not {type(prim).__name__}.')
138 self.prim = Prim(prim.copy())
139 super().__init__(supercell)
141 self._lattice = Lattice(self.prim.cell, self.cell)
143 # find the index and offsets for supercell using primitive as base unit
144 self._offsets, self._indices = get_offset_index(prim, supercell)
146 @property
147 def lattice(self) -> Lattice:
148 """The lattice relating the primitive cell and the supercell."""
149 return self._lattice
151 @property
152 def P(self) -> NDArray[int]:
153 """P-matrix is defined as dot(P, prim.cell) = supercell.cell"""
154 return self._lattice.P
156 @property
157 def offsets(self) -> NDArray[int]:
158 """The offset of each atom."""
159 return self._offsets.copy()
161 @property
162 def indices(self) -> NDArray[int]:
163 """The basis index of each atom"""
164 return self._indices.copy()
166 @property
167 def n_cells(self) -> int:
168 """Number of unit cells"""
169 return self.n_atoms // self.prim.n_atoms
171 def __str__(self):
173 string = f"""Supercell:
174Number of atoms: {self.n_atoms}
175Volume: {self.volume:.3f}
176Number of unit cells: {self.n_cells}
177Cell:
178[[{self.cell[0, 0]:<20}, {self.cell[0, 1]:<20}, {self.cell[0, 2]:<20}],
179 [{self.cell[1, 0]:<20}, {self.cell[1, 1]:<20}, {self.cell[1, 2]:<20}],
180 [{self.cell[2, 0]:<20}, {self.cell[2, 1]:<20}, {self.cell[2, 2]:<20}]]
181P-matrix:
182[[{self.P[0, 0]:<20}, {self.P[0, 1]:<20}, {self.P[0, 2]:<20}],
183 [{self.P[1, 0]:<20}, {self.P[1, 1]:<20}, {self.P[1, 2]:<20}],
184 [{self.P[2, 0]:<20}, {self.P[2, 1]:<20}, {self.P[2, 2]:<20}]]
185{self.prim}
186"""
187 return string