picometer 0.3.0__tar.gz → 0.4.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: picometer
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Precisely define and calculate measurements across multiple crystal structures
5
5
  License: MIT
6
6
  Author: Daniel Tchoń
@@ -9,7 +9,7 @@ import pandas as pd
9
9
 
10
10
  from picometer.shapes import (are_synparallel, degrees_between, Line,
11
11
  Plane, Shape, Vector3)
12
- from picometer.utility import ustr2float
12
+ from picometer.utility import ustr2float, ustr2floats
13
13
 
14
14
 
15
15
  try:
@@ -83,29 +83,32 @@ class AtomSet(Shape):
83
83
  al=ustr2float(cb['_cell_angle_alpha']),
84
84
  be=ustr2float(cb['_cell_angle_beta']),
85
85
  ga=ustr2float(cb['_cell_angle_gamma']))
86
- try:
87
- atoms_dict = {
88
- 'label': cb['_atom_site_label'],
89
- 'fract_x': [ustr2float(v) for v in cb['_atom_site_fract_x']],
90
- 'fract_y': [ustr2float(v) for v in cb['_atom_site_fract_y']],
91
- 'fract_z': [ustr2float(v) for v in cb['_atom_site_fract_z']],
92
- }
93
- try:
94
- atoms_dict['Uiso'] = [ustr2float(v) for v in cb['_atom_site_U_iso_or_equiv']]
95
- except KeyError:
96
- pass
97
- try:
98
- atoms_dict['U11'] = [ustr2float(v) for v in cb['_atom_site_aniso_U_11']]
99
- atoms_dict['U22'] = [ustr2float(v) for v in cb['_atom_site_aniso_U_22']]
100
- atoms_dict['U33'] = [ustr2float(v) for v in cb['_atom_site_aniso_U_33']]
101
- atoms_dict['U23'] = [ustr2float(v) for v in cb['_atom_site_aniso_U_23']]
102
- atoms_dict['U13'] = [ustr2float(v) for v in cb['_atom_site_aniso_U_13']]
103
- atoms_dict['U12'] = [ustr2float(v) for v in cb['_atom_site_aniso_U_12']]
104
- except KeyError:
105
- pass
106
- atoms = pd.DataFrame.from_records(atoms_dict).set_index('label')
107
- except KeyError:
108
- atoms = pd.DataFrame()
86
+
87
+ atoms = pd.DataFrame()
88
+
89
+ atom_labels = cb.get('_atom_site_label', [])
90
+ atom_xs = ustr2floats(cb.get('_atom_site_fract_x', []))
91
+ atom_ys = ustr2floats(cb.get('_atom_site_fract_y', []))
92
+ atom_zs = ustr2floats(cb.get('_atom_site_fract_z', []))
93
+ atom_u_isos = ustr2floats(cb.get('_atom_site_U_iso_or_equiv', []))
94
+ for label, x, y, z in zip(atom_labels, atom_xs, atom_ys, atom_zs):
95
+ atoms.loc[label, ['fract_x', 'fract_y', 'fract_z']] = [x, y, z]
96
+ for label, u_iso in zip(atom_labels, atom_u_isos):
97
+ atoms.loc[label, 'Uiso'] = u_iso
98
+
99
+ atom_labels = cb.get('_atom_site_aniso_label', [])
100
+ atom_u11s = ustr2floats(cb.get('_atom_site_aniso_U_11', []))
101
+ atom_u22s = ustr2floats(cb.get('_atom_site_aniso_U_22', []))
102
+ atom_u33s = ustr2floats(cb.get('_atom_site_aniso_U_33', []))
103
+ atom_u12s = ustr2floats(cb.get('_atom_site_aniso_U_12', []))
104
+ atom_u13s = ustr2floats(cb.get('_atom_site_aniso_U_13', []))
105
+ atom_u23s = ustr2floats(cb.get('_atom_site_aniso_U_23', []))
106
+ atom_us = zip(atom_u11s, atom_u22s, atom_u33s, atom_u12s, atom_u13s, atom_u23s)
107
+ for label, us in zip(atom_labels, atom_us):
108
+ atoms.loc[label, ['U11', 'U22', 'U33', 'U12', 'U13', 'U23']] = list(us)
109
+
110
+ for col in atoms.columns:
111
+ atoms[col] = pd.to_numeric(atoms[col], errors='coerce')
109
112
  return AtomSet(bf, atoms)
110
113
 
111
114
  @property
@@ -116,6 +119,20 @@ class AtomSet(Shape):
116
119
  def cart_xyz(self) -> np.ndarray:
117
120
  return self.orthogonalise(self.fract_xyz)
118
121
 
122
+ @property
123
+ def fract_uij(self) -> np.ndarray:
124
+ """Return a 3D array i.e. stack of 3x3 fract. displacement tensors."""
125
+ t = self.table
126
+ default = pd.Series([np.nan] * len(t), index=t.index)
127
+ uij = np.zeros((len(t), 3, 3), dtype=np.float64)
128
+ uij[:, 0, 0] = t.get('U11', default).to_numpy(dtype=np.float64)
129
+ uij[:, 1, 1] = t.get('U22', default).to_numpy(dtype=np.float64)
130
+ uij[:, 2, 2] = t.get('U33', default).to_numpy(dtype=np.float64)
131
+ uij[:, 0, 1] = uij[:, 1, 0] = t.get('U12', default).to_numpy(dtype=np.float64)
132
+ uij[:, 0, 2] = uij[:, 2, 0] = t.get('U13', default).to_numpy(dtype=np.float64)
133
+ uij[:, 1, 2] = uij[:, 2, 1] = t.get('U23', default).to_numpy(dtype=np.float64)
134
+ return uij
135
+
119
136
  def fractionalise(self, cart_xyz: np.ndarray) -> np.ndarray:
120
137
  """Multiply 3xN vector by crystallographic matrix to get fract coord"""
121
138
  return np.linalg.inv(self.base.A_d.T) @ cart_xyz
@@ -155,6 +172,17 @@ class AtomSet(Shape):
155
172
  data['fract_x'] = fract_xyz[:, 0]
156
173
  data['fract_y'] = fract_xyz[:, 1]
157
174
  data['fract_z'] = fract_xyz[:, 2]
175
+ if {'U11', 'U22', 'U33', 'U12', 'U13', 'U23'}.issubset(data.columns):
176
+ uij = self.fract_uij # shape: (n_atoms, 3, 3)
177
+ mask = ~np.isnan(uij).all(axis=(1, 2)) # atoms with defined Uij
178
+ if np.any(mask):
179
+ uij_rot = (s := symm_op.tf) @ uij[mask] @ s.T
180
+ data.loc[mask, 'U11'] = uij_rot[:, 0, 0]
181
+ data.loc[mask, 'U22'] = uij_rot[:, 1, 1]
182
+ data.loc[mask, 'U33'] = uij_rot[:, 2, 2]
183
+ data.loc[mask, 'U12'] = uij_rot[:, 0, 1]
184
+ data.loc[mask, 'U13'] = uij_rot[:, 0, 2]
185
+ data.loc[mask, 'U23'] = uij_rot[:, 1, 2]
158
186
  return self.__class__(self.base, data)
159
187
 
160
188
  @property
@@ -15,6 +15,7 @@ from pathlib import Path
15
15
  from typing import Any, Union, Protocol
16
16
 
17
17
  from numpy import rad2deg
18
+ import numpy as np
18
19
  import pandas as pd
19
20
  import yaml
20
21
 
@@ -218,6 +219,31 @@ class LoadInstructionHandler(BaseInstructionHandler):
218
219
  label = cif_path + (':' + block_name if block_name else '')
219
220
  self.processor.model_states[label] = ModelState(atoms=atoms)
220
221
  logger.info(f'Loaded model state {label}')
222
+
223
+ if self.processor.settings['complete_uiso_from_umatrix']:
224
+ if 'U11' in atoms.table.columns:
225
+ if 'Uiso' not in atoms.table.columns:
226
+ atoms.table['Uiso'] = pd.NA
227
+ u_equiv = atoms.table[['U11', 'U22', 'U33']].mean(axis=1)
228
+ atoms.table['Uiso'].fillna(u_equiv, inplace=True)
229
+
230
+ if self.processor.settings['complete_umatrix_from_uiso']:
231
+ u_columns = ['U11', 'U12', 'U13', 'U22', 'U23', 'U33']
232
+ if 'Uiso' in atoms.table.columns:
233
+ for col in u_columns:
234
+ if col not in atoms.table.columns:
235
+ atoms.table[col] = pd.NA
236
+ mask1 = atoms.table['Uiso'].notna()
237
+ mask2 = atoms.table[['U11', 'U22', 'U33']].isna().all(axis=1)
238
+ # based on http://dx.doi.org/10.1107/S0021889802008580
239
+ n_mat = np.diag([atoms.base.a_r, atoms.base.b_r, atoms.base.c_r])
240
+ n_inv = np.linalg.inv(n_mat)
241
+ u_star = (m := np.linalg.inv(atoms.base.A_d.T)) @ m.T
242
+ u_cif = n_inv @ u_star @ n_inv.T
243
+ for atom_label in atoms.table.index[mask1 & mask2]:
244
+ u_atom = atoms.table.at[atom_label, 'Uiso'] * u_cif
245
+ atoms.table.loc[atom_label, u_columns] = u_atom[np.triu_indices(3)]
246
+
221
247
  if not self.processor.settings['auto_write_unit_cell']:
222
248
  return
223
249
  et = self.processor.evaluation_table
@@ -326,6 +352,7 @@ class DisplacementInstructionHandler(SerialInstructionHandler):
326
352
 
327
353
  def handle_one(self, instruction: Instruction, ms_key: str, ms: ModelState) -> None:
328
354
  focus = ms.nodes.locate(self.processor.selection)
355
+ assert len(focus) > 0
329
356
  for label, displacements in focus.table.iterrows():
330
357
  for suffix in 'Uiso U11 U22 U33 U23 U13 U12'.split():
331
358
  label_ = label + '_' + suffix
@@ -19,6 +19,8 @@ class DefaultSettings:
19
19
  """Store default values of all settings. Use `AnyValue` if no default."""
20
20
  auto_write_unit_cell: bool = True
21
21
  clear_selection_after_use: bool = True
22
+ complete_uiso_from_umatrix: bool = False
23
+ complete_umatrix_from_uiso: bool = False
22
24
 
23
25
  @classmethod
24
26
  def get_field(cls, key: str) -> Field:
@@ -1,3 +1,5 @@
1
1
  settings:
2
2
  auto_write_unit_cell: True
3
3
  clear_selection_after_use: True
4
+ complete_uiso_from_umatrix: False
5
+ complete_umatrix_from_uiso: False
@@ -0,0 +1,13 @@
1
+ from typing import Iterable, List
2
+
3
+ import uncertainties as uc
4
+
5
+
6
+ def ustr2float(s: str) -> float:
7
+ """Convert a string "1.23(4)" to float `1.23`, stripping uncertainty."""
8
+ return uc.ufloat_fromstr(s).nominal_value
9
+
10
+
11
+ def ustr2floats(s: Iterable[str]) -> List[float]:
12
+ """Convenience function to convert an iterable of u-strings to floats."""
13
+ return [ustr2float(s) for s in s]
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "picometer"
3
- version = "0.3.0"
3
+ version = "0.4.0"
4
4
  description = "Precisely define and calculate measurements across multiple crystal structures"
5
5
  authors = ["Daniel Tchoń"]
6
6
  license = "MIT"
@@ -1,5 +0,0 @@
1
- import uncertainties as uc
2
-
3
-
4
- def ustr2float(s: str) -> float:
5
- return uc.ufloat_fromstr(s).nominal_value
File without changes
File without changes
File without changes
File without changes