xrdkit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
xrdkit/structure.py ADDED
@@ -0,0 +1,470 @@
1
+ """Interatomic distances in a crystal structure.
2
+
3
+ :func:`interatomic_distances` finds every distance from chosen atoms to
4
+ chosen others, across all symmetry operators and neighbouring cells, in a
5
+ cell of any symmetry, with esds from those of the fractional coordinates.
6
+ The atoms and operators are in the form the GSAS-II driver reports them:
7
+ each atom a mapping with ``label``, ``xyz`` and optionally ``xyz_esd``, each
8
+ operator a mapping with a 3 x 3 ``rotation`` and a ``translation``, both
9
+ acting on fractional coordinates. :func:`bond_lengths` takes a whole phase
10
+ as the driver reports it and gives every cation to anion distance, site by
11
+ site.
12
+
13
+ :func:`site_setup` finds the sites of a structure table of a settings file
14
+ (see :mod:`xrdkit.config`) among a phase's atoms, and
15
+ :func:`composition_edits` gives the atom edits that put a nominal
16
+ composition on them by the table's rule.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import itertools
22
+ import re
23
+ from collections.abc import Iterable, Mapping, Sequence
24
+ from dataclasses import dataclass
25
+
26
+ import numpy as np
27
+
28
+ from xrdkit.config import wyckoff_multiplicity
29
+
30
+ __all__ = [
31
+ "Distance",
32
+ "bond_lengths",
33
+ "cell_contents",
34
+ "composition_edits",
35
+ "interatomic_distances",
36
+ "metric_tensor",
37
+ "site_setup",
38
+ ]
39
+
40
+ # Images of an atom closer than this, in angstroms, are the same image
41
+ # reached by two operators.
42
+ SAME_IMAGE = 1.0e-4
43
+
44
+ # Atoms closer than this in every fractional coordinate share a site, and
45
+ # distances from one site to another equal to within this many angstroms
46
+ # are the same bond.
47
+ SAME_SITE = 1.0e-4
48
+ SAME_DISTANCE = 1.0e-4
49
+
50
+ # A GSAS-II cell's lengths and angles, in its keys.
51
+ CELL_KEYS = (
52
+ "length_a",
53
+ "length_b",
54
+ "length_c",
55
+ "angle_alpha",
56
+ "angle_beta",
57
+ "angle_gamma",
58
+ )
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class Distance:
63
+ """A distance from atom ``centre`` to an image of atom ``target``.
64
+
65
+ ``operator`` is the index of the symmetry operator that made the image
66
+ and ``translation`` the whole cell shift added to it. ``esd`` is
67
+ propagated from the coordinate esds of the two atoms alone, as if
68
+ uncorrelated, with the cell taken as exact; None if neither atom has
69
+ any.
70
+ """
71
+
72
+ centre: str
73
+ target: str
74
+ distance: float
75
+ esd: float | None
76
+ operator: int
77
+ translation: tuple[int, int, int]
78
+
79
+
80
+ def metric_tensor(cell: Sequence[float]) -> np.ndarray:
81
+ """The real space metric tensor G of ``cell``, ``(a, b, c, alpha, beta,
82
+ gamma)`` in angstroms and degrees, so that a fractional vector v has
83
+ length sqrt(v . G v)."""
84
+ a, b, c = (float(value) for value in cell[:3])
85
+ alpha, beta, gamma = np.radians([float(value) for value in cell[3:6]])
86
+ return np.array(
87
+ [
88
+ [a * a, a * b * np.cos(gamma), a * c * np.cos(beta)],
89
+ [a * b * np.cos(gamma), b * b, b * c * np.cos(alpha)],
90
+ [a * c * np.cos(beta), b * c * np.cos(alpha), c * c],
91
+ ]
92
+ )
93
+
94
+
95
+ def _esd(atom: Mapping) -> np.ndarray:
96
+ values = atom.get("xyz_esd") or [None, None, None]
97
+ return np.array([0.0 if value is None else float(value) for value in values])
98
+
99
+
100
+ def interatomic_distances(
101
+ cell: Sequence[float],
102
+ atoms: Sequence[Mapping],
103
+ operators: Sequence[Mapping],
104
+ centres: Iterable[str],
105
+ targets: Iterable[str],
106
+ dmax: float,
107
+ dmin: float = 0.5,
108
+ ) -> list[Distance]:
109
+ """Every distance from each atom in ``centres`` to images of the atoms in
110
+ ``targets`` between ``dmin`` and ``dmax`` angstroms, shortest first for
111
+ each centre, centres in the order given.
112
+
113
+ The images are those of every operator, shifted into the cells around
114
+ the centre; the same image reached by two operators, as on a special
115
+ position, is counted once.
116
+
117
+ The esd of a distance d = |x_t' - x_c|, with x_t' = R x_t + t, is
118
+ propagated from the esds of the fractional coordinates of both atoms,
119
+ through the derivatives -G(x_t' - x_c)/d for the centre and
120
+ R^T G(x_t' - x_c)/d for the target; a distance from an atom to an image
121
+ of itself moves with (R^T - I) G(x_t' - x_c)/d. Correlations between
122
+ coordinates, and the esds of the cell, are not included.
123
+
124
+ Raises
125
+ ------
126
+ ValueError
127
+ If a centre or target is not an atom's label, or ``dmax`` is not
128
+ above ``dmin``.
129
+ """
130
+ if not dmax > dmin:
131
+ raise ValueError(f"dmax must exceed dmin, got {dmax} and {dmin}")
132
+ by_label = {str(atom["label"]): atom for atom in atoms}
133
+ centres, targets = list(centres), list(targets)
134
+ missing = sorted(set(centres + targets) - set(by_label))
135
+ if missing:
136
+ raise ValueError(f"no atoms labelled {missing}")
137
+ metric = metric_tensor(cell)
138
+ rotations = [np.asarray(op["rotation"], dtype=float) for op in operators]
139
+ shifts = [np.asarray(op["translation"], dtype=float) for op in operators]
140
+ cells = [np.array(n) for n in itertools.product((-1, 0, 1), repeat=3)]
141
+
142
+ found = []
143
+ for centre in centres:
144
+ atom = by_label[centre]
145
+ x_c, esd_c = np.asarray(atom["xyz"], dtype=float), _esd(atom)
146
+ near = []
147
+ for target in targets:
148
+ other = by_label[target]
149
+ x_t, esd_t = np.asarray(other["xyz"], dtype=float), _esd(other)
150
+ images = []
151
+ for index, (rotation, shift) in enumerate(zip(rotations, shifts)):
152
+ image = rotation @ x_t + shift
153
+ nearest = np.round(image - x_c)
154
+ for extra in cells:
155
+ offset = extra - nearest
156
+ delta = image + offset - x_c
157
+ distance = float(np.sqrt(delta @ metric @ delta))
158
+ if not dmin <= distance <= dmax:
159
+ continue
160
+ position = x_c + delta
161
+ if any(
162
+ np.sqrt((position - seen) @ metric @ (position - seen))
163
+ < SAME_IMAGE
164
+ for seen in images
165
+ ):
166
+ continue
167
+ images.append(position)
168
+ gradient = metric @ delta / distance
169
+ if target == centre:
170
+ variance = np.sum(
171
+ ((rotation.T - np.eye(3)) @ gradient * esd_c) ** 2
172
+ )
173
+ else:
174
+ variance = np.sum((gradient * esd_c) ** 2) + np.sum(
175
+ (rotation.T @ gradient * esd_t) ** 2
176
+ )
177
+ has_esd = esd_c.any() or esd_t.any()
178
+ near.append(
179
+ Distance(
180
+ centre=centre,
181
+ target=target,
182
+ distance=distance,
183
+ esd=float(np.sqrt(variance)) if has_esd else None,
184
+ operator=index,
185
+ translation=tuple(int(n) for n in offset),
186
+ )
187
+ )
188
+ found += sorted(near, key=lambda item: item.distance)
189
+ return found
190
+
191
+
192
+ def _element(atom_type: str) -> str:
193
+ match = re.match(r"[A-Z][a-z]?", str(atom_type))
194
+ return match.group(0) if match else str(atom_type)
195
+
196
+
197
+ def _sites(atoms: Sequence[Mapping]) -> list[list[int]]:
198
+ """The indices of ``atoms`` grouped by the site they share."""
199
+ groups: list[list[int]] = []
200
+ for index, atom in enumerate(atoms):
201
+ for group in groups:
202
+ delta = np.asarray(atom["xyz"], float) - np.asarray(
203
+ atoms[group[0]]["xyz"], float
204
+ )
205
+ if np.all(np.abs(delta - np.round(delta)) < SAME_SITE):
206
+ group.append(index)
207
+ break
208
+ else:
209
+ groups.append([index])
210
+ return groups
211
+
212
+
213
+ def bond_lengths(
214
+ phase: Mapping,
215
+ anions: Iterable[str] = ("O",),
216
+ dmax: float = 3.0,
217
+ dmin: float = 0.5,
218
+ ) -> list[dict]:
219
+ """Every distance from a cation site of ``phase`` to an anion site
220
+ between ``dmin`` and ``dmax`` angstroms.
221
+
222
+ ``phase`` is a phase as the GSAS-II driver reports it: ``cell``, a
223
+ mapping with GSAS-II's ``length_a`` to ``angle_gamma`` or the six values
224
+ themselves, ``atoms``, each with ``label``, ``type`` and ``xyz`` and
225
+ optionally ``xyz_esd``, and ``operators``. Atoms that share a site count
226
+ once, as the first of them; a site is an anion site if its first atom
227
+ is of an element in ``anions``, and a cation site otherwise. Distances
228
+ from one cation site to images of one anion site that are equal to
229
+ within SAME_DISTANCE are the same bond, counted.
230
+
231
+ Returns a list of ``{"centre", "centre_site", "target", "target_site",
232
+ "distance", "esd", "count"}``: the labels of the first atoms and of
233
+ every atom on each site, joined by "/", the distance and its esd as
234
+ :func:`interatomic_distances` gives them, and how many such bonds the
235
+ cation site has; by cation site in the phase's order, then by distance.
236
+
237
+ Raises
238
+ ------
239
+ ValueError
240
+ If ``dmax`` is not above ``dmin``.
241
+ """
242
+ cell = phase["cell"]
243
+ if isinstance(cell, Mapping):
244
+ cell = [cell[key] for key in CELL_KEYS]
245
+ atoms = list(phase["atoms"])
246
+ anions = set(anions)
247
+ site_labels, centres, targets = {}, [], []
248
+ for group in _sites(atoms):
249
+ first = atoms[group[0]]
250
+ site_labels[first["label"]] = "/".join(atoms[i]["label"] for i in group)
251
+ chosen = targets if _element(first["type"]) in anions else centres
252
+ chosen.append(first["label"])
253
+ bonds: dict[tuple, dict] = {}
254
+ for found in interatomic_distances(
255
+ cell, atoms, phase["operators"], centres, targets, dmax, dmin
256
+ ):
257
+ key = (
258
+ found.centre,
259
+ found.target,
260
+ round(found.distance / SAME_DISTANCE),
261
+ )
262
+ if key in bonds:
263
+ bonds[key]["count"] += 1
264
+ continue
265
+ bonds[key] = {
266
+ "centre": found.centre,
267
+ "centre_site": site_labels[found.centre],
268
+ "target": found.target,
269
+ "target_site": site_labels[found.target],
270
+ "distance": found.distance,
271
+ "esd": found.esd,
272
+ "count": 1,
273
+ }
274
+ order = {label: position for position, label in enumerate(centres)}
275
+ return sorted(
276
+ bonds.values(), key=lambda bond: (order[bond["centre"]], bond["distance"])
277
+ )
278
+
279
+
280
+ def cell_contents(atoms: Iterable[Mapping]) -> dict[str, float]:
281
+ """Atoms of each element per cell, multiplicity times occupancy, from
282
+ atoms with ``type``, ``multiplicity`` and ``occupancy``."""
283
+ contents: dict[str, float] = {}
284
+ for atom in atoms:
285
+ kind = _element(atom["type"])
286
+ contents[kind] = (
287
+ contents.get(kind, 0.0) + atom["multiplicity"] * atom["occupancy"]
288
+ )
289
+ return contents
290
+
291
+
292
+ def composition_edits(
293
+ atoms: Sequence[Mapping], composition: Mapping[str, float], structure: Mapping
294
+ ) -> list[dict]:
295
+ """Atom edits that give a cell of ``atoms`` the nominal ``composition``,
296
+ atoms of each element per formula unit, by the rule of ``structure``, a
297
+ structure table as :func:`xrdkit.config.load_config` returns it.
298
+
299
+ ``atoms`` are the structure's as read from its CIF, each with
300
+ ``label``, ``type``, ``multiplicity`` and ``occupancy``, and the cell
301
+ holds ``structure["formula_units"]`` formula units. Every element the
302
+ atoms hold is scaled by one factor on every site it occupies, which
303
+ keeps the CIF's distribution of it over the sites; an atom whose
304
+ occupancy that leaves unchanged gets no edit. Each element of
305
+ ``structure["composition"]["added"]``, which maps it to a host element,
306
+ is put on every atom of its host at one fraction of that atom's CIF
307
+ occupancy, so that it goes where the host is, as an atom labelled by the
308
+ added element and the rest of the host's label (La1 on Sr1); an added
309
+ element whose content is 0 is not added. The edits are in the form the
310
+ GSAS-II driver takes: ``{"label", "occupancy"}``, and ``{"label",
311
+ "type", "copy", "occupancy"}`` for an added atom.
312
+
313
+ Raises
314
+ ------
315
+ ValueError
316
+ If the atoms hold an element the composition lacks, the composition
317
+ has one the atoms lack that the rule does not add, an added element
318
+ is on the atoms already, or a label for an added atom is taken.
319
+ """
320
+ added_on = structure["composition"]["added"]
321
+ cif = cell_contents(atoms)
322
+ per_cell = {
323
+ kind: structure["formula_units"] * value for kind, value in composition.items()
324
+ }
325
+ missing = sorted(set(cif) - set(per_cell))
326
+ if missing:
327
+ raise ValueError(f"the atoms hold {missing}, which the composition lacks")
328
+ lacking = sorted(
329
+ kind for kind in set(per_cell) - set(cif) - set(added_on) if per_cell[kind]
330
+ )
331
+ if lacking:
332
+ raise ValueError(
333
+ f"the composition has {lacking}, which the atoms lack and the rule "
334
+ "does not add"
335
+ )
336
+ for kind, host in added_on.items():
337
+ if kind in cif:
338
+ raise ValueError(f"{kind} is to be added on {host} but is there already")
339
+ if per_cell.get(kind) and not cif.get(host):
340
+ raise ValueError(f"{kind} is to be added on {host}, which the atoms lack")
341
+ labels = {atom["label"] for atom in atoms}
342
+ edits = []
343
+ for atom in atoms:
344
+ kind = _element(atom["type"])
345
+ if cif[kind]:
346
+ occupancy = atom["occupancy"] * per_cell[kind] / cif[kind]
347
+ if occupancy != atom["occupancy"]:
348
+ edits.append({"label": atom["label"], "occupancy": occupancy})
349
+ for added, host in added_on.items():
350
+ if host != kind or not per_cell.get(added):
351
+ continue
352
+ label = added + atom["label"][len(kind) :]
353
+ if label in labels:
354
+ raise ValueError(
355
+ f"label {label!r} for {added} on {atom['label']} is taken"
356
+ )
357
+ labels.add(label)
358
+ edits.append(
359
+ {
360
+ "label": label,
361
+ "type": added,
362
+ "copy": atom["label"],
363
+ "occupancy": atom["occupancy"] * per_cell[added] / cif[kind],
364
+ }
365
+ )
366
+ return edits
367
+
368
+
369
+ def site_setup(structure: Mapping, atoms: Sequence[Mapping]) -> dict:
370
+ """The sites of ``structure``, a structure table as
371
+ :func:`xrdkit.config.load_config` returns it, found among ``atoms``, a
372
+ phase's atoms as the GSAS-II driver reports them (``label``, ``type``,
373
+ ``xyz`` and optionally ``multiplicity``).
374
+
375
+ Each configured site is the position of its atoms; any other atom on
376
+ that position, such as one added by :func:`composition_edits`, is on
377
+ the site too. Returns a dict with
378
+
379
+ - ``sites``: in the structure's order, each ``{"name", "kind",
380
+ "wyckoff", "multiplicity", "free", "atoms"}``, ``free`` the
381
+ coordinates to refine from the table's ``free_coordinates`` ("all"
382
+ for a position it does not name) and ``atoms`` those on the position,
383
+ in the order of ``atoms``;
384
+ - ``kinds``: the sites of each kind, in that order;
385
+ - ``uiso_groups`` and ``group_names``: the site names of each Uiso
386
+ group, and its name;
387
+ - ``origin``: the site that fixes the origin, and ``origin_axis``;
388
+ - ``coordinates``: by kind, the coordinates to refine on each site but
389
+ the origin's, ``{kind: {site name: free}}``;
390
+ - ``exchange``: ``{"elements", "sites"}``.
391
+
392
+ Raises
393
+ ------
394
+ ValueError
395
+ If a configured atom is not among ``atoms``, a site's atoms are not
396
+ on one position or two sites on the same one, an atom is not of the
397
+ element given for it, a site's multiplicity is not that of its
398
+ Wyckoff position, or an atom is on no configured site.
399
+ """
400
+ groups = _sites(atoms)
401
+ group_of = {index: number for number, group in enumerate(groups) for index in group}
402
+ index_of = {str(atom["label"]): index for index, atom in enumerate(atoms)}
403
+ free = structure.get("free_coordinates", {})
404
+ sites, used = [], {}
405
+ for site in structure["sites"]:
406
+ name = site["name"]
407
+ absent = [label for label in site["atoms"] if label not in index_of]
408
+ if absent:
409
+ raise ValueError(f"site {name}: no atom labelled {absent} in the structure")
410
+ numbers = {group_of[index_of[label]] for label in site["atoms"]}
411
+ if len(numbers) > 1:
412
+ raise ValueError(
413
+ f"site {name}: atoms {list(site['atoms'])} are not on one position"
414
+ )
415
+ (number,) = numbers
416
+ if number in used:
417
+ raise ValueError(f"sites {used[number]} and {name} are on one position")
418
+ used[number] = name
419
+ for label, element in site["atoms"].items():
420
+ found = _element(atoms[index_of[label]]["type"])
421
+ if found != element:
422
+ raise ValueError(
423
+ f"site {name}: atom {label} is {found}, not {element} as given"
424
+ )
425
+ members = [atoms[index] for index in groups[number]]
426
+ multiplicity = wyckoff_multiplicity(site["wyckoff"])
427
+ if "multiplicity" in members[0] and members[0]["multiplicity"] != multiplicity:
428
+ raise ValueError(
429
+ f"site {name}: multiplicity {members[0]['multiplicity']}, not "
430
+ f"{multiplicity} as on {site['wyckoff']}"
431
+ )
432
+ sites.append(
433
+ {
434
+ "name": name,
435
+ "kind": site["kind"],
436
+ "wyckoff": site["wyckoff"],
437
+ "multiplicity": multiplicity,
438
+ "free": free.get(site["wyckoff"], "all"),
439
+ "atoms": members,
440
+ }
441
+ )
442
+ unplaced = [
443
+ str(atoms[index]["label"])
444
+ for number, group in enumerate(groups)
445
+ if number not in used
446
+ for index in group
447
+ ]
448
+ if unplaced:
449
+ raise ValueError(f"atoms {unplaced} are on no configured site")
450
+ by_name = {site["name"]: site for site in sites}
451
+ kinds: dict[str, list[dict]] = {}
452
+ for site in sites:
453
+ kinds.setdefault(site["kind"], []).append(site)
454
+ origin = by_name[structure["origin"]["site"]]
455
+ return {
456
+ "sites": sites,
457
+ "kinds": kinds,
458
+ "uiso_groups": [list(group["sites"]) for group in structure["uiso_groups"]],
459
+ "group_names": [group["name"] for group in structure["uiso_groups"]],
460
+ "origin": origin,
461
+ "origin_axis": structure["origin"]["axis"],
462
+ "coordinates": {
463
+ kind: {site["name"]: site["free"] for site in found if site is not origin}
464
+ for kind, found in kinds.items()
465
+ },
466
+ "exchange": {
467
+ "elements": list(structure["exchange"]["elements"]),
468
+ "sites": list(structure["exchange"]["sites"]),
469
+ },
470
+ }