Coverage for ase/spacegroup/xtal.py: 93.33%
75 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1# Copyright (C) 2010, Jesper Friis
2# (see accompanying license files for details).
4"""
5A module for ASE for simple creation of crystalline structures from
6knowledge of the space group.
8"""
10from typing import Any
12import numpy as np
13from scipy import spatial
15import ase
16from ase.geometry import cellpar_to_cell
17from ase.spacegroup import Spacegroup
18from ase.symbols import string2symbols
20__all__ = ['crystal']
23def crystal(
24 symbols=None,
25 basis=None,
26 occupancies=None,
27 spacegroup=1,
28 setting=1,
29 cell=None,
30 cellpar=None,
31 ab_normal=(0, 0, 1),
32 a_direction=None,
33 size=(1, 1, 1),
34 onduplicates='warn',
35 symprec=0.001,
36 pbc=True,
37 primitive_cell=False,
38 **kwargs,
39) -> ase.Atoms:
40 """Create an Atoms instance for a conventional unit cell of a
41 space group.
43 Parameters
44 ----------
46 symbols : str | sequence of str | sequence of Atom | Atoms
47 Element symbols of the unique sites. Can either be a string
48 formula or a sequence of element symbols. E.g. ('Na', 'Cl')
49 and 'NaCl' are equivalent. Can also be given as a sequence of
50 Atom objects or an Atoms object.
51 basis : list of scaled coordinates
52 Positions of the unique sites corresponding to symbols given
53 either as scaled positions or through an atoms instance. Not
54 needed if *symbols* is a sequence of Atom objects or an Atoms
55 object.
56 occupancies : list of site occupancies
57 Occupancies of the unique sites. Defaults to 1.0 and thus no mixed
58 occupancies are considered if not explicitly asked for. If occupancies
59 are given, the most dominant species will yield the atomic number.
60 The occupancies in the atoms.info['occupancy'] dictionary will have
61 integers keys converted to strings. The conversion is done in order
62 to avoid unexpected conversions when using the JSON serializer.
63 spacegroup : int | string | Spacegroup instance
64 Space group given either as its number in International Tables
65 or as its Hermann-Mauguin symbol.
66 setting : 1 | 2
67 Space group setting.
68 cell : 3x3 matrix
69 Unit cell vectors.
70 cellpar : [a, b, c, alpha, beta, gamma]
71 Cell parameters with angles in degree. Is not used when `cell`
72 is given.
73 ab_normal : vector
74 Is used to define the orientation of the unit cell relative
75 to the Cartesian system when `cell` is not given. It is the
76 normal vector of the plane spanned by a and b.
77 a_direction : vector
78 Defines the orientation of the unit cell a vector. a will be
79 parallel to the projection of `a_direction` onto the a-b plane.
80 size : 3 positive integers
81 How many times the conventional unit cell should be repeated
82 in each direction.
83 onduplicates : 'keep' | 'replace' | 'warn' | 'error'
84 Action if `basis` contain symmetry-equivalent positions:
85 'keep' - ignore additional symmetry-equivalent positions
86 'replace' - replace
87 'warn' - like 'keep', but issue an UserWarning
88 'error' - raises a SpacegroupValueError
89 symprec : float
90 Minimum "distance" betweed two sites in scaled coordinates
91 before they are counted as the same site.
92 pbc : one or three bools
93 Periodic boundary conditions flags. Examples: True,
94 False, 0, 1, (1, 1, 0), (True, False, False). Default
95 is True.
96 primitive_cell : bool
97 Whether to return the primitive instead of the conventional
98 unit cell.
100 Keyword arguments:
102 All additional keyword arguments are passed on to the Atoms
103 constructor. Currently, probably the most useful additional
104 keyword arguments are `info`, `constraint` and `calculator`.
106 Examples
107 --------
109 Two diamond unit cells (space group number 227)
111 >>> diamond = crystal('C', [(0,0,0)], spacegroup=227,
112 ... cellpar=[3.57, 3.57, 3.57, 90, 90, 90], size=(2,1,1))
113 >>> ase.view(diamond) # doctest: +SKIP
115 A CoSb3 skutterudite unit cell containing 32 atoms
117 >>> skutterudite = crystal(('Co', 'Sb'),
118 ... basis=[(0.25,0.25,0.25), (0.0, 0.335, 0.158)],
119 ... spacegroup=204, cellpar=[9.04, 9.04, 9.04, 90, 90, 90])
120 >>> len(skutterudite)
121 32
122 """
123 sg = Spacegroup(spacegroup, setting)
124 if (
125 not isinstance(symbols, str)
126 and hasattr(symbols, '__getitem__')
127 and len(symbols) > 0
128 and isinstance(symbols[0], ase.Atom)
129 ):
130 symbols = ase.Atoms(symbols)
131 if isinstance(symbols, ase.Atoms):
132 basis = symbols
133 symbols = basis.get_chemical_symbols()
134 if isinstance(basis, ase.Atoms):
135 basis_coords = basis.get_scaled_positions()
136 if cell is None and cellpar is None:
137 cell = basis.cell
138 if symbols is None:
139 symbols = basis.get_chemical_symbols()
140 else:
141 basis_coords = np.array(basis, dtype=float, ndmin=2)
143 if occupancies is not None:
144 occupancies_dict = {}
146 for index, coord in enumerate(basis_coords):
147 # Compute all distances and get indices of nearest atoms
148 dist = spatial.distance.cdist(coord.reshape(1, 3), basis_coords)
149 indices_dist = np.flatnonzero(dist < symprec)
151 occ = {symbols[index]: occupancies[index]}
153 # Check nearest and update occupancy
154 for index_dist in indices_dist:
155 if index == index_dist:
156 continue
157 else:
158 occ.update({symbols[index_dist]: occupancies[index_dist]})
160 occupancies_dict[str(index)] = occ.copy()
162 sites, kinds = sg.equivalent_sites(
163 basis_coords, onduplicates=onduplicates, symprec=symprec
164 )
166 # this is needed to handle deuterium masses
167 masses = None
168 if 'masses' in kwargs:
169 masses = kwargs['masses'][kinds]
170 del kwargs['masses']
172 symbols = parse_symbols(symbols)
174 if occupancies is None:
175 symbols = [symbols[i] for i in kinds]
176 else:
177 # make sure that we put the dominant species there
178 symbols = [
179 sorted(occupancies_dict[str(i)].items(), key=lambda x: x[1])[-1][0]
180 for i in kinds
181 ]
183 if cell is None:
184 cell = cellpar_to_cell(cellpar, ab_normal, a_direction)
186 info: dict[str, Any] = {}
187 info['spacegroup'] = sg
188 if primitive_cell:
189 info['unit_cell'] = 'primitive'
190 else:
191 info['unit_cell'] = 'conventional'
193 if 'info' in kwargs:
194 info.update(kwargs['info'])
196 if occupancies is not None:
197 info['occupancy'] = occupancies_dict
199 kwargs['info'] = info
201 atoms = ase.Atoms(
202 symbols,
203 scaled_positions=sites,
204 cell=cell,
205 pbc=pbc,
206 masses=masses,
207 **kwargs,
208 )
210 if isinstance(basis, ase.Atoms):
211 for name in basis.arrays:
212 if not atoms.has(name):
213 array = basis.get_array(name)
214 atoms.new_array(
215 name,
216 [array[i] for i in kinds],
217 dtype=array.dtype,
218 shape=array.shape[1:],
219 )
221 if kinds:
222 atoms.new_array('spacegroup_kinds', np.asarray(kinds, dtype=int))
224 if primitive_cell:
225 from ase.build import cut
227 prim_cell = sg.scaled_primitive_cell
229 # Preserve calculator if present:
230 calc = atoms.calc
231 atoms = cut(atoms, a=prim_cell[0], b=prim_cell[1], c=prim_cell[2])
232 atoms.calc = calc
234 if size != (1, 1, 1):
235 atoms = atoms.repeat(size)
236 return atoms
239def parse_symbols(symbols):
240 """Return `sumbols` as a sequence of element symbols."""
241 if isinstance(symbols, str):
242 symbols = string2symbols(symbols)
243 return symbols