picometer 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.
picometer/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ # read version from installed package
2
+ from importlib.metadata import version
3
+
4
+ __version__ = version("picometer")
picometer/atom.py ADDED
@@ -0,0 +1,205 @@
1
+ from copy import deepcopy
2
+ import logging
3
+ from typing import Dict, NamedTuple, List, Sequence
4
+
5
+ import hikari.symmetry
6
+ from hikari.dataframes import BaseFrame, CifFrame
7
+ import numpy as np
8
+ from numpy.linalg import norm
9
+ import pandas as pd
10
+
11
+ from picometer.shapes import degrees_between, Line, Plane, Shape, Vector3
12
+ from picometer.utility import ustr2float
13
+
14
+
15
+ log = logging.getLogger(__name__)
16
+
17
+
18
+ class Locator(NamedTuple):
19
+ label: str
20
+ symm: str = 'x,y,z'
21
+ at: 'Sequence[Locator]' = None
22
+
23
+ @classmethod
24
+ def from_dict(cls, d: dict) -> 'Locator':
25
+ symm = d.get('symm')
26
+ at = d.get('at')
27
+ return Locator(label=d['label'],
28
+ symm=symm if symm else 'x,y,z',
29
+ at=at if at else None)
30
+
31
+ def __bool__(self):
32
+ return self.label and self.label != 'None'
33
+
34
+
35
+ group_registry: Dict[str, List[Locator]] = {}
36
+
37
+
38
+ class AtomSet(Shape):
39
+ """Container class w/ atoms stored in pd.Dataframe & convenience methods"""
40
+
41
+ kind = Shape.Kind.spatial
42
+
43
+ def __init__(self,
44
+ bf: BaseFrame = None,
45
+ table: pd.DataFrame = None,
46
+ ) -> None:
47
+ log.debug(f'Init AtomSet with {bf!r} and {table!r}')
48
+ self.base = bf
49
+ self.table = table
50
+
51
+ def __len__(self):
52
+ return len(self.table) if self.table is not None else 0
53
+
54
+ def __add__(self, other):
55
+ if not (self.base or self.table):
56
+ return other
57
+ elif not (other.base or other.table):
58
+ return self
59
+ return AtomSet(self.base, pd.concat([self.table, other.table], axis=0))
60
+
61
+ def __getitem__(self, item) -> 'AtomSet':
62
+ return self.__class__(bf=self.base, table=self.table[item])
63
+
64
+ @classmethod
65
+ def from_cif(cls, cif_path: str, block_name: str = None) -> 'AtomSet':
66
+ bf = BaseFrame()
67
+ cf = CifFrame()
68
+ cf.read(cif_path)
69
+ block_name = block_name if block_name else list(cf.keys())[0]
70
+ cb = cf[block_name]
71
+ bf.edit_cell(a=ustr2float(cb['_cell_length_a']),
72
+ b=ustr2float(cb['_cell_length_b']),
73
+ c=ustr2float(cb['_cell_length_c']),
74
+ al=ustr2float(cb['_cell_angle_alpha']),
75
+ be=ustr2float(cb['_cell_angle_beta']),
76
+ ga=ustr2float(cb['_cell_angle_gamma']))
77
+ try:
78
+ atoms_dict = {
79
+ 'label': cb['_atom_site_label'],
80
+ 'fract_x': [ustr2float(v) for v in cb['_atom_site_fract_x']],
81
+ 'fract_y': [ustr2float(v) for v in cb['_atom_site_fract_y']],
82
+ 'fract_z': [ustr2float(v) for v in cb['_atom_site_fract_z']],
83
+ }
84
+ atoms = pd.DataFrame.from_records(atoms_dict).set_index('label')
85
+ except KeyError:
86
+ atoms = pd.DataFrame()
87
+ return AtomSet(bf, atoms)
88
+
89
+ @property
90
+ def fract_xyz(self):
91
+ return np.vstack([self.table['fract_' + k].to_numpy() for k in 'xyz'])
92
+
93
+ @property
94
+ def cart_xyz(self):
95
+ return self.orthogonalise(self.fract_xyz)
96
+
97
+ def fractionalise(self, cart_xyz: np.ndarray) -> np.ndarray:
98
+ """Multiply 3xN vector by crystallographic matrix to get fract coord"""
99
+ return np.linalg.inv(self.base.A_d.T) @ cart_xyz
100
+
101
+ def orthogonalise(self, fract_xyz: np.ndarray) -> np.ndarray:
102
+ """Multiply 3xN vector by crystallographic matrix to get Cart. coord"""
103
+ return self.base.A_d.T @ fract_xyz
104
+
105
+ def locate(self, locators: Sequence[Locator]) -> 'AtomSet':
106
+ """Convenience method to select multiple fragments from locators
107
+ while interpreting and extending groups if necessary"""
108
+ log.debug(f'Locate {locators} in {self}')
109
+ new = AtomSet()
110
+ assert len(locators) == 0 or isinstance(locators[0], Locator)
111
+ for label, symm_op_code, at in locators:
112
+ if label in group_registry:
113
+ new2 = self.locate(locators=group_registry[label])
114
+ else:
115
+ new2 = self.select_atom(label_regex=label)
116
+ new2 = new2.transform(symm_op_code)
117
+ if at:
118
+ new2.origin = self.locate(at).origin
119
+ new += new2
120
+ return new
121
+
122
+ def select_atom(self, label_regex: str) -> 'AtomSet':
123
+ mask = self.table.index == label_regex
124
+ if not any(mask):
125
+ mask = self.table.index.str.match(label_regex)
126
+ log.debug(f'Selected {sum(mask)} atoms with {label_regex=}')
127
+ return self.__class__(self.base, deepcopy(self.table[mask]))
128
+
129
+ def transform(self, symm_op_code: str) -> 'AtomSet':
130
+ symm_op = hikari.symmetry.SymmOp.from_code(symm_op_code)
131
+ fract_xyz = symm_op.transform(self.fract_xyz.T)
132
+ data = deepcopy(self.table)
133
+ data['fract_x'] = fract_xyz[:, 0]
134
+ data['fract_y'] = fract_xyz[:, 1]
135
+ data['fract_z'] = fract_xyz[:, 2]
136
+ return self.__class__(self.base, data)
137
+
138
+ @property
139
+ def centroid(self):
140
+ """A 3-vector with average atom position."""
141
+ return self.cart_xyz.T.mean(axis=0)
142
+
143
+ @property
144
+ def direction(self) -> Vector3:
145
+ return None
146
+
147
+ @property
148
+ def line(self) -> Line:
149
+ """A 3-vector describing line that best fits the cartesian
150
+ coordinates of atoms. Based on https://stackoverflow.com/q/2298390/"""
151
+ cart_xyz = self.cart_xyz.T
152
+ uu, dd, vv = np.linalg.svd(cart_xyz - self.centroid)
153
+ return Line(direction=vv[0], origin=self.centroid)
154
+
155
+ @property
156
+ def plane(self) -> Plane:
157
+ """A 3-vector normal to plane that best fits atoms' cartesian coords.
158
+ Based on https://gist.github.com/amroamroamro/1db8d69b4b65e8bc66a6"""
159
+ cart_xyz = self.cart_xyz.T
160
+ uu, dd, vv = np.linalg.svd((cart_xyz - self.centroid).T)
161
+ return Plane(direction=uu[:, -1], origin=self.centroid)
162
+
163
+ @property
164
+ def origin(self) -> Vector3:
165
+ return self.centroid
166
+
167
+ @origin.setter
168
+ def origin(self, new_origin):
169
+ """Change origin to the new one provided in cartesian coordinates"""
170
+ new_origin_fract = self.fractionalise(new_origin)
171
+ delta = new_origin_fract - self.fractionalise(self.centroid)
172
+ self.table['fract_x'] += delta[0]
173
+ self.table['fract_y'] += delta[1]
174
+ self.table['fract_z'] += delta[2]
175
+ assert np.allclose(new_origin, self.centroid)
176
+
177
+ def _angle(self, *others: 'Shape') -> float:
178
+ assert all(o.kind is o.Kind.spatial for o in [self, *others])
179
+ combined = sum(others, self)
180
+ xyz = combined.cart_xyz.T
181
+ if len(combined) == 3: # interior angle
182
+ return degrees_between(xyz[0] - xyz[1], xyz[2] - xyz[1])
183
+ elif 4 <= len(combined) <= 6: # dihedral angle
184
+ plane1_dir = np.cross(xyz[0] - xyz[1], xyz[2] - xyz[1])
185
+ plane2_dir = np.cross(xyz[-3] - xyz[-2], xyz[-1] - xyz[-2])
186
+ return degrees_between(plane1_dir, plane2_dir, normalize=False)
187
+ else:
188
+ return 'Input AtomSet must contain between 3 and 6 atoms'
189
+
190
+ def _distance(self, other: 'Shape') -> float:
191
+ if other.kind is self.Kind.spatial:
192
+ # https://stackoverflow.com/a/43359192/8279065 bloody brilliant
193
+ other: 'AtomSet'
194
+ xy1, xy2 = self.cart_xyz.T, other.cart_xyz.T
195
+ p = np.add.outer(np.sum(xy1**2, axis=1), np.sum(xy2**2, axis=1))
196
+ n = np.dot(xy1, xy2.T)
197
+ return np.min(np.sqrt(p - 2 * n))
198
+ elif other.kind is self.Kind.planar:
199
+ deltas = self.cart_xyz.T - other.origin
200
+ return min(np.abs(np.dot(deltas, other.direction)))
201
+ else: # if other.kind is self.Kind.axial:
202
+ deltas = self.cart_xyz.T - other.origin
203
+ norms = norm(deltas, axis=1)
204
+ along = np.abs(np.dot(deltas, other.direction))
205
+ return min(norms ** 2 - along ** 2)
picometer/models.py ADDED
@@ -0,0 +1,22 @@
1
+ from typing import Dict
2
+ from picometer.atom import AtomSet
3
+ from picometer.shapes import ExplicitShape
4
+
5
+
6
+ class ModelState:
7
+ """Class describing atomsets, selections, and shapes in one structure"""
8
+ def __init__(self,
9
+ atoms: AtomSet,
10
+ centroids: AtomSet = AtomSet(),
11
+ shapes: Dict[str, ExplicitShape] = None):
12
+ self.atoms: AtomSet = atoms
13
+ self.centroids: AtomSet = centroids
14
+ self.shapes: Dict[str, ExplicitShape] = shapes if shapes else {}
15
+
16
+ @property
17
+ def nodes(self):
18
+ return self.atoms + self.centroids
19
+
20
+
21
+ class ModelStates(Dict[str, ModelState]):
22
+ pass
picometer/process.py ADDED
@@ -0,0 +1,199 @@
1
+ from copy import deepcopy
2
+ from collections import UserDict
3
+ from typing import Callable, Dict, List, Union
4
+
5
+ import pandas as pd
6
+
7
+ from picometer.atom import group_registry, AtomSet, Locator
8
+ from picometer.models import ModelState, ModelStates
9
+ from picometer.routine import Routine
10
+ from picometer.settings import Settings
11
+
12
+
13
+ ImplicitInstructionArgument = Union[str, Dict[str, str]]
14
+
15
+
16
+ def explicit_kwargs(**expected_kwargs: type) -> type:
17
+ class ExplicitInstructionArgs(UserDict):
18
+ def __init__(self, arg):
19
+ new = {}
20
+ if isinstance(arg, dict):
21
+ for key, value in arg.items():
22
+ assert key in expected_kwargs.keys(), f'Unknown key: {key}'
23
+ new[key] = expected_kwargs[key](value)
24
+ else:
25
+ expected_key, expected_type = list(expected_kwargs.items())[0]
26
+ new[expected_key] = expected_type(arg)
27
+ for expected_key in expected_kwargs.keys():
28
+ if expected_key not in new.keys():
29
+ new[expected_key] = None
30
+ super().__init__(**new)
31
+ return ExplicitInstructionArgs
32
+
33
+
34
+ CifInstructionsDict = explicit_kwargs(path=str, block=str)
35
+ LocatorInstructionsDict = explicit_kwargs(label=str, symm=str, at=Locator)
36
+
37
+
38
+ Instruction: Dict
39
+
40
+
41
+ def registers_instructions(cls):
42
+ """Class decorator that registers class methods in `cls.instructions`"""
43
+ cls.instructions = {}
44
+ for method_name in dir(cls):
45
+ method = getattr(cls, method_name)
46
+ if hasattr(method, '_name'):
47
+ name = getattr(method, '_name')
48
+ cls.instructions.update({name: method})
49
+ return cls
50
+
51
+
52
+ def register_instruction(name: str) -> Callable:
53
+ """Method decorator that registers this method in `cls.instructions`"""
54
+ def decorator(processor_method: Callable) -> Callable:
55
+ processor_method._name = name
56
+ return processor_method
57
+ return decorator
58
+
59
+
60
+ @registers_instructions
61
+ class Processor:
62
+ """
63
+ This is the main class responsible for controlling, processing,
64
+ storing current state, importing, exporting the current state
65
+ of work performed in picometer.
66
+ """
67
+ instructions: Dict[str, Callable] = {}
68
+
69
+ def __init__(self, settings: Settings = None) -> None:
70
+ self.evaluation_table = pd.DataFrame()
71
+ self.model_states: ModelStates = ModelStates()
72
+ self.selection: List[Locator] = []
73
+ self.settings = Settings.from_yaml()
74
+ if settings:
75
+ self.settings.update(settings)
76
+
77
+ def process(self, instruction: Union[Dict, str]) -> None:
78
+ if isinstance(instruction, dict):
79
+ if len(instruction) != 1:
80
+ raise ValueError('Only singular instructions are accepted')
81
+ instruction_name = list(instruction.keys())[0]
82
+ instruction_argument = list(instruction.values())[0]
83
+ else:
84
+ instruction_name, instruction_argument = instruction, None
85
+ self.instructions[instruction_name](self, instruction_argument)
86
+
87
+ def clear_selection_after_use(self) -> None:
88
+ if self.settings.get('clear_selection_after_use'):
89
+ self.selection = []
90
+
91
+ @register_instruction('load')
92
+ def load(self, arg: ImplicitInstructionArgument) -> None:
93
+ arg = CifInstructionsDict(arg)
94
+ cif_path = arg['path']
95
+ block_name = arg['block']
96
+ atoms = AtomSet.from_cif(cif_path=cif_path, block_name=block_name)
97
+ label = cif_path + (':' + block_name if block_name else '')
98
+ self.model_states[label] = ModelState(atoms=atoms)
99
+
100
+ @register_instruction('select')
101
+ def select(self, arg: ImplicitInstructionArgument) -> None:
102
+ arg = LocatorInstructionsDict(arg)
103
+ loc = Locator.from_dict(arg)
104
+ if loc:
105
+ self.selection.append(loc)
106
+ else:
107
+ self.selection = []
108
+
109
+ @register_instruction('recenter')
110
+ def recenter(self, arg: ImplicitInstructionArgument) -> None:
111
+ arg = LocatorInstructionsDict(arg)
112
+ new_center = [Locator.from_dict(arg)]
113
+ new_locators = [Locator.from_dict(dict(loc._asdict(), at=new_center))
114
+ for loc in self.selection]
115
+ self.selection = new_locators
116
+
117
+ @register_instruction('group')
118
+ def group(self, label: str) -> None:
119
+ group_registry[label] = deepcopy(self.selection)
120
+ self.clear_selection_after_use()
121
+
122
+ @register_instruction('centroid')
123
+ def centroid(self, label: str) -> None:
124
+ for ms_key, ms in self.model_states.items():
125
+ focus = ms.nodes.locate(self.selection)
126
+ c_fract = focus.fractionalise(focus.centroid)
127
+ c_atoms = {'label': [label], 'fract_x': [c_fract[0]],
128
+ 'fract_y': [c_fract[1]], 'fract_z': [c_fract[2]], }
129
+ atoms = pd.DataFrame.from_records(c_atoms).set_index('label')
130
+ ms.centroids += AtomSet(focus.base, atoms)
131
+ self.clear_selection_after_use()
132
+
133
+ @register_instruction('line')
134
+ def line(self, label: str) -> None:
135
+ for ms_key, ms in self.model_states.items():
136
+ focus = ms.nodes.locate(self.selection)
137
+ ms.shapes[label] = focus.line
138
+ self.clear_selection_after_use()
139
+
140
+ @register_instruction('plane')
141
+ def plane(self, label: str) -> None:
142
+ for ms_key, ms in self.model_states.items():
143
+ focus = ms.nodes.locate(self.selection)
144
+ ms.shapes[label] = focus.plane
145
+ self.clear_selection_after_use()
146
+
147
+ @register_instruction('distance')
148
+ def distance(self, label: str) -> None:
149
+ for ms_key, ms in self.model_states.items():
150
+ shapes = []
151
+ for locator in self.selection:
152
+ if (shape_label := locator.label) in ms.shapes:
153
+ shapes.append(ms.shapes[shape_label])
154
+ else:
155
+ shapes.append(ms.nodes.locate([locator]))
156
+ assert len(shapes) == 2
157
+ distance = shapes[0].distance(shapes[1])
158
+ self.evaluation_table.loc[ms_key, label] = distance
159
+ self.clear_selection_after_use()
160
+
161
+ @register_instruction('angle')
162
+ def angle(self, label: str) -> None:
163
+ for ms_key, ms in self.model_states.items():
164
+ shapes = []
165
+ for locator in self.selection:
166
+ if (shape_label := locator.label) in ms.shapes:
167
+ shapes.append(ms.shapes[shape_label])
168
+ else:
169
+ shapes.append(ms.nodes.locate([locator]))
170
+ assert len(shapes)
171
+ angle = shapes[0].angle(*shapes[1:])
172
+ self.evaluation_table.loc[ms_key, label] = angle
173
+ self.clear_selection_after_use()
174
+
175
+ @register_instruction('write')
176
+ def write(self, csv_name: str) -> None:
177
+ self.evaluation_table.to_csv(path_or_buf=csv_name)
178
+
179
+ @register_instruction('clear')
180
+ def clear(self, *_):
181
+ self.__init__()
182
+
183
+ @register_instruction('set')
184
+ def set(self, new_settings: dict) -> None:
185
+ self.settings.update(new_settings)
186
+
187
+
188
+ def process(routine: Routine) -> Processor:
189
+ processor = Processor()
190
+ for instruction in routine:
191
+ processor.process(instruction)
192
+ return processor
193
+
194
+
195
+ if __name__ == '__main__':
196
+ p = Processor()
197
+ print(p.instructions)
198
+ print(p.instructions['load'])
199
+ print(p.instructions['load'](p, {'block': '123'}))
picometer/routine.py ADDED
@@ -0,0 +1,45 @@
1
+ """
2
+ Picometer routine file in a yaml file that contains a list of settings
3
+ and instructions to be sequentially executed by the parser.
4
+ In accordance with the yaml format, the file can comprise several
5
+ "yaml files" / "picometer routines" seperated by "\n---".
6
+ However, these "files"/"routines" are ultimately concatenated
7
+ and converted into a list of instructions.
8
+ """
9
+
10
+
11
+ from collections import UserList
12
+ from pathlib import Path
13
+ from typing import Union
14
+ import yaml
15
+
16
+
17
+ class Routine(UserList):
18
+ """A list of subsequent instructions originating from a single yaml file"""
19
+
20
+ @classmethod
21
+ def concatenate(cls, routines: list['Routine']):
22
+ new_routine = routines.pop(0) if routines else Routine()
23
+ while routines:
24
+ new_routine.append('clear')
25
+ new_routine.extend(routines.pop(0))
26
+ return cls(new_routine)
27
+
28
+ @classmethod
29
+ def from_dict(cls, dict_: dict) -> 'Routine':
30
+ new_routine = []
31
+ if settings := dict_.get('settings'):
32
+ new_routine.append({'set': settings})
33
+ if instructions := dict_.get('instructions'):
34
+ new_routine.extend(instructions)
35
+ return cls(new_routine)
36
+
37
+ @classmethod
38
+ def from_string(cls, text: str) -> 'Routine':
39
+ yaml_segments = yaml.load_all(text, yaml.SafeLoader)
40
+ return cls.concatenate([cls.from_dict(y) for y in yaml_segments])
41
+
42
+ @classmethod
43
+ def from_yaml(cls, path: Union[str, Path]) -> 'Routine':
44
+ with open(path, 'r') as yaml_file:
45
+ return cls.from_string(yaml_file.read())
picometer/settings.py ADDED
@@ -0,0 +1,51 @@
1
+ from collections import UserDict
2
+ from dataclasses import asdict, dataclass, fields, Field
3
+ from importlib import resources
4
+ from typing import Union
5
+
6
+ import yaml
7
+
8
+
9
+ class SettingsError(KeyError):
10
+ """Custom `KeyError` raised when there are issues with `DefaultSettings`"""
11
+
12
+
13
+ @dataclass
14
+ class DefaultSettings:
15
+ """Store default values of all settings. Use `AnyValue` if no default."""
16
+ clear_selection_after_use: bool = True
17
+
18
+ @classmethod
19
+ def get_field(cls, key: str) -> Field:
20
+ if fields_ := [f for f in fields(cls) if f.name == key]: # noqa
21
+ return fields_[0]
22
+ raise SettingsError(f'Unknown setting name {key!r}')
23
+
24
+
25
+ class Settings(UserDict):
26
+ """Automatically set self from `DefaultSettings` on init, handle settings"""
27
+
28
+ @classmethod
29
+ def from_yaml(cls, path=None) -> 'Settings':
30
+ settings_stream = open(path, 'r') if path \
31
+ else resources.open_text('picometer', 'settings.yaml')
32
+ with settings_stream:
33
+ return cls(yaml.safe_load(settings_stream)['settings'])
34
+
35
+ def __init__(self, data: dict = None) -> None:
36
+ super().__init__(asdict(DefaultSettings())) # noqa
37
+ if data:
38
+ self.update(data)
39
+
40
+ def __setitem__(self, key, value, /) -> None:
41
+ field = DefaultSettings.get_field(key)
42
+ super().__setitem__(key, field.type(value))
43
+
44
+ def __delitem__(self, key, /) -> None:
45
+ field = DefaultSettings.get_field(key)
46
+ super().__setitem__(key, field.default)
47
+
48
+ def update(self, other: Union[dict, UserDict] = None, /, **kwargs) -> None:
49
+ other = {**other, **kwargs} if other else kwargs
50
+ for key, value in other.items():
51
+ self[key] = value
@@ -0,0 +1,2 @@
1
+ settings:
2
+ clear_selection_after_use: True
picometer/shapes.py ADDED
@@ -0,0 +1,140 @@
1
+ import abc
2
+ import copy
3
+ import enum
4
+ import logging
5
+ from typing import Annotated, Literal, Protocol, Union
6
+
7
+ import numpy as np
8
+ import numpy.typing as npt
9
+ from numpy.linalg import norm
10
+
11
+
12
+ log = logging.getLogger(__name__)
13
+
14
+
15
+ Vector3 = Annotated[npt.NDArray[float], Literal[3]]
16
+ Versor3 = Annotated[npt.NDArray[float], Literal[3]]
17
+ zero3: Vector3 = np.array([0., 0., 0.], dtype=float)
18
+
19
+
20
+ class AtomSet(Protocol):
21
+ cart_xyz: np.ndarray
22
+
23
+
24
+ def are_parallel(v: Vector3, w: Vector3) -> bool:
25
+ return 1 - abs(np.dot(v / norm(v), w / norm(w))) < 1E-8
26
+
27
+
28
+ def are_perpendicular(v: Vector3, w: Vector3) -> bool:
29
+ return abs(norm(v) * norm(w) - norm(np.cross(v, w))) < 1E-8
30
+
31
+
32
+ def versorize(v: Vector3) -> Versor3:
33
+ """Normalize and choose lexicographically-larger of two possible results"""
34
+ assert isinstance(v, np.ndarray) and np.shape(v) == (3, )
35
+ assert (v_norm := np.linalg.norm(v)) > 0
36
+ neg = v[0] < 0 or (v[0] == 0 and (v[1] < 0 or (v[1] == 0 and v[2] < 0)))
37
+ return (-v if neg else v) / v_norm
38
+
39
+
40
+ def degrees_between(v: Vector3, w: Vector3, normalize: bool = False) -> float:
41
+ """Calculate angle between two vectors in degrees"""
42
+ assert v.shape == w.shape
43
+ rad = np.arccos(
44
+ sum(v * w) / (np.sqrt(sum(v * v)) * np.sqrt(sum(w * w))))
45
+ deg = np.rad2deg(rad)
46
+ return 180. - deg if deg > 90. and normalize else deg
47
+
48
+
49
+ class Shape:
50
+ class Kind(enum.Enum):
51
+ axial = 1 # spans in 1D along direction
52
+ planar = 2 # spans in 2D perpendicular to direction
53
+ spatial = 3 # spans in 0D or 3D, irrelevant direction
54
+
55
+ kind: Kind
56
+ direction: Versor3
57
+ origin: Vector3
58
+
59
+ def __repr__(self):
60
+ name = self.__class__.__name__
61
+ return f'{name}(direction={self.direction}, origin={self.origin})'
62
+
63
+ def at(self, origin: Vector3) -> 'Shape':
64
+ """Return a copy of self with centroid at new origin"""
65
+ new = copy.deepcopy(self)
66
+ new.origin = np.array(origin, dtype=float)
67
+ return new
68
+
69
+ @abc.abstractmethod
70
+ def _distance(self, other: 'Shape') -> float:
71
+ pass
72
+
73
+ def distance(self, other: 'Shape') -> float:
74
+ """
75
+ Delegated to a concrete implementation.
76
+ Since self.kind >= other.kind, concrete implementations need only
77
+ to handle shapes of equal of lower kind.
78
+ """
79
+ assert isinstance(self, Shape) and isinstance(other, Shape)
80
+ if not self.kind.value >= other.kind.value: # let self.kind >= other
81
+ return other.distance(self)
82
+ log.debug(f'Calculating distance between {self} and {other}')
83
+ return self._distance(other) # delegate to concrete implementation
84
+
85
+ @abc.abstractmethod
86
+ def _angle(self, other: 'Shape') -> float:
87
+ pass
88
+
89
+ def angle(self, *others: 'Shape') -> float:
90
+ """
91
+ Delegated to a concrete implementation.
92
+ For Explicit shape, accept two parameters; for AtomSets, any size.
93
+ """
94
+ assert all(isinstance(o, Shape) for o in [self, *others])
95
+ log.debug(f'Calculating angle between {self} and {others}')
96
+ return self._angle(*others) # delegate to concrete implementation
97
+
98
+
99
+ class ExplicitShape(Shape, abc.ABC):
100
+ def __init__(self, direction: Vector3, origin: Vector3 = zero3):
101
+ self.direction = direction
102
+ self.origin = origin
103
+
104
+ @property
105
+ def direction(self) -> Versor3:
106
+ return self._direction
107
+
108
+ @direction.setter
109
+ def direction(self, vector: Vector3) -> None:
110
+ self._direction = versorize(vector)
111
+
112
+ def _angle(self, *others: 'Shape') -> float:
113
+ assert len(others) == 1, 'Handle only angles between 2 ExplicitShapes'
114
+ other = others[0]
115
+ deg = degrees_between(self.direction, other.direction, normalize=True)
116
+ return deg if self.kind is others[0].kind else 90.0 - deg
117
+
118
+
119
+ class Line(ExplicitShape):
120
+ kind = Shape.Kind.axial
121
+
122
+ def _distance(self, other: 'Line'):
123
+ delta = other.origin - self.origin
124
+ if are_parallel(self.direction, other.direction):
125
+ d = self.direction
126
+ return np.linalg.norm(delta - (np.dot(d, delta) * d))
127
+ else:
128
+ shortest_direction = np.cross(self.direction, other.direction)
129
+ return abs(np.dot(delta, shortest_direction))
130
+
131
+
132
+ class Plane(ExplicitShape):
133
+ kind = Shape.Kind.planar
134
+
135
+ def _distance(self, other: Union[Line, 'Plane']) -> float:
136
+ delta = other.origin - self.origin
137
+ dont_intersect_cond = are_parallel \
138
+ if other.kind is self.Kind.planar else are_perpendicular
139
+ dont_intersect = dont_intersect_cond(self.direction, other.direction)
140
+ return abs(np.dot(delta, self.direction)) if dont_intersect else 0.0
picometer/utility.py ADDED
@@ -0,0 +1,5 @@
1
+ import uncertainties as uc
2
+
3
+
4
+ def ustr2float(s: str) -> float:
5
+ return uc.ufloat_fromstr(s).nominal_value
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Daniel Tchoń
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,148 @@
1
+ Metadata-Version: 2.1
2
+ Name: picometer
3
+ Version: 0.1.0
4
+ Summary: Precisely define and calculate measurements across multiple crystal structures
5
+ License: MIT
6
+ Author: Daniel Tchoń
7
+ Requires-Python: >=3.10
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Requires-Dist: hikari-toolkit (==0.2.3)
14
+ Requires-Dist: numpy (>=2.1.2)
15
+ Requires-Dist: pandas (>=2.2.3)
16
+ Requires-Dist: pyyaml (>=6.0.2)
17
+ Requires-Dist: uncertainties (>=3.2.2)
18
+ Description-Content-Type: text/markdown
19
+
20
+ # picometer
21
+
22
+ [![codecov](https://codecov.io/gh/Baharis/picometer/graph/badge.svg?token=bWGMArFAR8)](https://codecov.io/gh/Baharis/picometer)
23
+ [![CodeFactor](https://www.codefactor.io/repository/github/baharis/picometer/badge)](https://www.codefactor.io/repository/github/baharis/picometer)
24
+ [![Documentation Status](https://readthedocs.org/projects/picometer/badge/?version=stable)](https://picometer.readthedocs.io/en/stable/?badge=stable)
25
+
26
+ This is a little Python 3.10+ suite which aims to precisely define
27
+ and calculate measurements across multiple crystal structures.
28
+ This is a software for you if you have ever:
29
+ - Misclicked an atom and lost your 250-atom selection in Olex2,
30
+ - Tried to fit or calculate distances to a line in Mercury,
31
+ - Spent a day measuring distances and angles in tens of similar structures,
32
+ - Had to redo measurements because of a offensively minor change,
33
+
34
+ Instead of relying on a graphical interface and evaluating a single structure
35
+ at a time, picometer uses an input yaml file with individual settings
36
+ and consecutive instructions to probe multiple structures concurrently.
37
+ The results are output in a form of a csv file,
38
+ which can be then opened in a spreadsheet editor for further analysis.
39
+ Because of that, picometer is a handy tool to save time
40
+ on dumb repeatable labor and focus on what really matters.
41
+
42
+
43
+ ## Installation
44
+
45
+ In order to use picometer:
46
+ 1) Clone (download) the git repository to your computer;
47
+ 2) Make sure you have Python version 3.10+ installed;
48
+ 3) Create a virtual environment using i.e. venv:
49
+ `python -m venv /path/to/virtual_environment`
50
+ 4) Activate your virtual environment:
51
+ use `/path/to/virtual_environment` on Windows or
52
+ `source /path/to/virtual_environment` on Linux/MacOS;
53
+ 5) Install required python packages: `pip install -r requirements.txt`
54
+ 6) Test your installation by running `python -m unittest`
55
+
56
+ The code is currently updated with an intention to be available for download
57
+ directly from pip:
58
+ ```bash
59
+ $ pip install picometer
60
+ ```
61
+
62
+
63
+ ## Usage
64
+
65
+ Whenever you want to use picometer, first re-activate the virtual environment
66
+ created during installation following instructions therein.
67
+ Running the program with no arguments produces the help string.
68
+
69
+ ```shell
70
+ python picometer_process.py
71
+ ```
72
+ ```text
73
+ usage: picometer [-h] filename
74
+
75
+ Precisely define and measure across multiple crystal structures
76
+
77
+ positional arguments:
78
+ filename Path to yaml file with routine settings and instructions
79
+
80
+ options:
81
+ -h, --help show this help message and exit
82
+
83
+ Author: Daniel Tchoń, baharis @ GitHub
84
+ ```
85
+
86
+ In order to know what to do, picometer requires an input file
87
+ with (settings and) instructions. This file should follow yaml format
88
+ and the list of instructions, called "routine", must include
89
+ only single-element maps in the `instruction: details` format.
90
+ An example of instruction file is available in `tests` directory.
91
+ The easiest way to generate your file is to manually write it based
92
+ on the example provided.
93
+
94
+
95
+ ## Instructions
96
+
97
+ The following instructions are currently supported by picometer:
98
+ - **Input/output instructions**
99
+ - `load` model from a cif file, given `filename` or mapping syntax:
100
+ `{path: filename.cif, block: cif_block}`.
101
+ - `write` table with all evaluations to a csv file.
102
+ - **Selection instructions**
103
+ - `select` atoms, groups, or shapes to be used; use raw element names
104
+ or provide symmetry relation / recenter using mapping syntax, for example:
105
+ `{label: C(11), symm: x;-y;z+1/2, at: Fe(1)}`.
106
+ By default, selection is cleared after calling `select` with no arguments
107
+ or calling an aggregating or evaluating instruction.
108
+ - `recenter` selection around a new centroid;
109
+ this action is applied to every selected item individually,
110
+ so to recenter fixed group of atoms, `group` them first and recenter
111
+ this group - otherwise you will recenter individual atoms instead.
112
+ - **Aggregation instructions**
113
+ - `group` current selection into a new object with fixed elements.
114
+ - fit `centroid` to the current atom / centroid selection;
115
+ - fit `line` to the current atom / centroid selection;
116
+ - fit `plane` to the currect atom / centroid selection;
117
+ - **Evaluation instructions**
118
+ - measure `distance` between 2 selected objects; if the selection includes
119
+ groups of atoms, measure closes distance to the group of atoms.
120
+ - measure `angle` between 2–6 selected objects; if the selection includes
121
+ (ordered) atoms, calculate direct or dihedral angle between presumed bonds.
122
+
123
+
124
+ ## Contributing
125
+
126
+ Interested in contributing? Check out the contributing guidelines.
127
+ Please note that this project is released with a Code of Conduct.
128
+ By contributing to this project, you agree to abide by its terms.
129
+
130
+
131
+ ## License
132
+
133
+ `picometer` was created by Daniel Tchoń.
134
+ It is licensed under the terms of the MIT license.
135
+
136
+
137
+ ## Credits
138
+
139
+ This software has been written as a hobby project of Daniel Tchoń
140
+ (email: dtchon at lbl dot gov, or other address currectly available on
141
+ https://dtools.pl/about/).
142
+ All contributions and suggestions are heartily welcome!
143
+
144
+ `picometer` was created with the help of
145
+ [`cookiecutter`](https://cookiecutter.readthedocs.io/en/latest/)
146
+ and the `py-pkgs-cookiecutter` [template](https://github.com/py-pkgs/py-pkgs-cookiecutter).
147
+ It is published with the help of [`poetry`](https://python-poetry.org/).
148
+
@@ -0,0 +1,13 @@
1
+ picometer/__init__.py,sha256=TMKjwvzoWjAEsmbLpuN3Xwxz9H3mAPaun4bGoT4qdA0,117
2
+ picometer/atom.py,sha256=wyLUorHOxUIUNWqLSoJpAbrZ54mGrc36I5_3xdrmTak,8024
3
+ picometer/models.py,sha256=xk_3BYvKuf5ix8KdqOogRk2EugBE8cGUmua9KWwPdlI,670
4
+ picometer/process.py,sha256=NQyTVOvumMejLyytSeDQhy4qb23GtimO4YNazr-67EI,7526
5
+ picometer/routine.py,sha256=qFXSMok_Y8W3yLm-gOD-TXL_Hri_Y9wCole6MGCMCBo,1595
6
+ picometer/settings.py,sha256=Zv2sNNE4-QPOSmUpT66tfQPfwbyY04izoEilsz499WY,1756
7
+ picometer/settings.yaml,sha256=mcclncZwakXjX-CO6tIhjsNCS824DbwfqWkKr2dlKqk,46
8
+ picometer/shapes.py,sha256=K_X7slC0T8ODCNm9yzAKcRfpdlNPR_GzowKt1OowTLs,4816
9
+ picometer/utility.py,sha256=JXRSSG9u8kNw5fkShEOUa3W3rhSagZq-iJDSIkKD9ok,113
10
+ picometer-0.1.0.dist-info/LICENSE,sha256=DQ2qtVUJD1_6ZJZ--xwvxJGMbIYc2Hnia4mRmUWaQIk,1091
11
+ picometer-0.1.0.dist-info/METADATA,sha256=JU544eYXu1aOqjm3r5D6j4C8kXkwGxDtjFyzutbwwD0,5994
12
+ picometer-0.1.0.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
13
+ picometer-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 1.9.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any