picometer 0.1.3__tar.gz → 0.3.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.
- {picometer-0.1.3 → picometer-0.3.0}/PKG-INFO +7 -4
- {picometer-0.1.3 → picometer-0.3.0}/README.md +5 -2
- {picometer-0.1.3 → picometer-0.3.0}/picometer/__main__.py +3 -1
- {picometer-0.1.3 → picometer-0.3.0}/picometer/atom.py +52 -27
- picometer-0.3.0/picometer/instructions.py +402 -0
- picometer-0.3.0/picometer/logging.py +48 -0
- {picometer-0.1.3 → picometer-0.3.0}/picometer/models.py +11 -6
- picometer-0.3.0/picometer/process.py +47 -0
- {picometer-0.1.3 → picometer-0.3.0}/picometer/settings.py +10 -2
- {picometer-0.1.3 → picometer-0.3.0}/picometer/settings.yaml +1 -0
- {picometer-0.1.3 → picometer-0.3.0}/picometer/shapes.py +3 -3
- {picometer-0.1.3 → picometer-0.3.0}/pyproject.toml +2 -2
- picometer-0.1.3/picometer/process.py +0 -199
- picometer-0.1.3/picometer/routine.py +0 -45
- {picometer-0.1.3 → picometer-0.3.0}/LICENSE +0 -0
- {picometer-0.1.3 → picometer-0.3.0}/picometer/__init__.py +0 -0
- {picometer-0.1.3 → picometer-0.3.0}/picometer/utility.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
2
|
Name: picometer
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Precisely define and calculate measurements across multiple crystal structures
|
|
5
5
|
License: MIT
|
|
6
6
|
Author: Daniel Tchoń
|
|
@@ -140,10 +140,13 @@ The following instructions are currently supported by picometer:
|
|
|
140
140
|
- fit `line` to the current atom / centroid selection;
|
|
141
141
|
- fit `plane` to the currect atom / centroid selection;
|
|
142
142
|
- **Evaluation instructions**
|
|
143
|
+
- write out fractional `coordinates` of currently selected centroids or atoms.
|
|
144
|
+
- write out `displacement` parameters of currently selected centroids or atoms
|
|
145
|
+
(note: currently does not correctly handle symmetry transformations).
|
|
143
146
|
- measure `distance` between 2 selected objects; if the selection includes
|
|
144
147
|
groups of atoms, measure closes distance to the group of atoms.
|
|
145
|
-
- measure `angle` between 2–
|
|
146
|
-
|
|
148
|
+
- measure `angle` between 2–3 selected objects: planes, lines, or (ordered) atoms.
|
|
149
|
+
- measure `dihedral` andle between 4 individually-selected ordered centroids/atoms.
|
|
147
150
|
|
|
148
151
|
|
|
149
152
|
## Contributing
|
|
@@ -120,10 +120,13 @@ The following instructions are currently supported by picometer:
|
|
|
120
120
|
- fit `line` to the current atom / centroid selection;
|
|
121
121
|
- fit `plane` to the currect atom / centroid selection;
|
|
122
122
|
- **Evaluation instructions**
|
|
123
|
+
- write out fractional `coordinates` of currently selected centroids or atoms.
|
|
124
|
+
- write out `displacement` parameters of currently selected centroids or atoms
|
|
125
|
+
(note: currently does not correctly handle symmetry transformations).
|
|
123
126
|
- measure `distance` between 2 selected objects; if the selection includes
|
|
124
127
|
groups of atoms, measure closes distance to the group of atoms.
|
|
125
|
-
- measure `angle` between 2–
|
|
126
|
-
|
|
128
|
+
- measure `angle` between 2–3 selected objects: planes, lines, or (ordered) atoms.
|
|
129
|
+
- measure `dihedral` andle between 4 individually-selected ordered centroids/atoms.
|
|
127
130
|
|
|
128
131
|
|
|
129
132
|
## Contributing
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
from argparse import ArgumentParser, Namespace
|
|
2
|
-
from picometer.
|
|
2
|
+
from picometer.instructions import Routine
|
|
3
|
+
from picometer.logging import add_file_handler
|
|
3
4
|
from picometer.process import process
|
|
4
5
|
import sys
|
|
5
6
|
|
|
@@ -20,6 +21,7 @@ def parse_args() -> Namespace:
|
|
|
20
21
|
def main() -> int:
|
|
21
22
|
args = parse_args()
|
|
22
23
|
if filename := args.filename:
|
|
24
|
+
add_file_handler('picometer.log')
|
|
23
25
|
routine = Routine.from_yaml(filename)
|
|
24
26
|
process(routine)
|
|
25
27
|
return 0
|
|
@@ -2,17 +2,23 @@ from copy import deepcopy
|
|
|
2
2
|
import logging
|
|
3
3
|
from typing import Dict, NamedTuple, List, Sequence
|
|
4
4
|
|
|
5
|
-
import hikari.symmetry
|
|
6
5
|
from hikari.dataframes import BaseFrame, CifFrame
|
|
7
|
-
import numpy as np
|
|
8
6
|
from numpy.linalg import norm
|
|
7
|
+
import numpy as np
|
|
9
8
|
import pandas as pd
|
|
10
9
|
|
|
11
|
-
from picometer.shapes import degrees_between, Line,
|
|
10
|
+
from picometer.shapes import (are_synparallel, degrees_between, Line,
|
|
11
|
+
Plane, Shape, Vector3)
|
|
12
12
|
from picometer.utility import ustr2float
|
|
13
13
|
|
|
14
14
|
|
|
15
|
-
|
|
15
|
+
try:
|
|
16
|
+
from hikari.symmetry import Operation
|
|
17
|
+
except ImportError: # hikari version < 0.3.0
|
|
18
|
+
from hikari.symmetry import SymmOp as Operation
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
16
22
|
|
|
17
23
|
|
|
18
24
|
class Locator(NamedTuple):
|
|
@@ -29,7 +35,7 @@ class Locator(NamedTuple):
|
|
|
29
35
|
at=at if at else None)
|
|
30
36
|
|
|
31
37
|
def __bool__(self):
|
|
32
|
-
return self.label
|
|
38
|
+
return self.label is not None
|
|
33
39
|
|
|
34
40
|
|
|
35
41
|
group_registry: Dict[str, List[Locator]] = {}
|
|
@@ -44,25 +50,28 @@ class AtomSet(Shape):
|
|
|
44
50
|
bf: BaseFrame = None,
|
|
45
51
|
table: pd.DataFrame = None,
|
|
46
52
|
) -> None:
|
|
47
|
-
|
|
53
|
+
|
|
54
|
+
logger.debug(f'Created atom set with {bf!r} and '
|
|
55
|
+
f'{len(table) if table is not None else 0}-element table')
|
|
48
56
|
self.base = bf
|
|
49
57
|
self.table = table
|
|
50
58
|
|
|
51
|
-
def __len__(self):
|
|
59
|
+
def __len__(self) -> int:
|
|
52
60
|
return len(self.table) if self.table is not None else 0
|
|
53
61
|
|
|
54
|
-
def __add__(self, other):
|
|
62
|
+
def __add__(self, other) -> 'AtomSet':
|
|
55
63
|
if not (self.base or self.table):
|
|
56
64
|
return other
|
|
57
65
|
elif not (other.base or other.table):
|
|
58
66
|
return self
|
|
59
|
-
return
|
|
67
|
+
return self.__class__(self.base, pd.concat([self.table, other.table], axis=0))
|
|
60
68
|
|
|
61
69
|
def __getitem__(self, item) -> 'AtomSet':
|
|
62
70
|
return self.__class__(bf=self.base, table=self.table[item])
|
|
63
71
|
|
|
64
72
|
@classmethod
|
|
65
73
|
def from_cif(cls, cif_path: str, block_name: str = None) -> 'AtomSet':
|
|
74
|
+
"""Initialize from cif file using hikari's `BaseFrame` and `CifFrame`"""
|
|
66
75
|
bf = BaseFrame()
|
|
67
76
|
cf = CifFrame()
|
|
68
77
|
cf.read(cif_path)
|
|
@@ -81,17 +90,30 @@ class AtomSet(Shape):
|
|
|
81
90
|
'fract_y': [ustr2float(v) for v in cb['_atom_site_fract_y']],
|
|
82
91
|
'fract_z': [ustr2float(v) for v in cb['_atom_site_fract_z']],
|
|
83
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
|
|
84
106
|
atoms = pd.DataFrame.from_records(atoms_dict).set_index('label')
|
|
85
107
|
except KeyError:
|
|
86
108
|
atoms = pd.DataFrame()
|
|
87
109
|
return AtomSet(bf, atoms)
|
|
88
110
|
|
|
89
111
|
@property
|
|
90
|
-
def fract_xyz(self):
|
|
112
|
+
def fract_xyz(self) -> np.ndarray:
|
|
91
113
|
return np.vstack([self.table['fract_' + k].to_numpy() for k in 'xyz'])
|
|
92
114
|
|
|
93
115
|
@property
|
|
94
|
-
def cart_xyz(self):
|
|
116
|
+
def cart_xyz(self) -> np.ndarray:
|
|
95
117
|
return self.orthogonalise(self.fract_xyz)
|
|
96
118
|
|
|
97
119
|
def fractionalise(self, cart_xyz: np.ndarray) -> np.ndarray:
|
|
@@ -105,7 +127,7 @@ class AtomSet(Shape):
|
|
|
105
127
|
def locate(self, locators: Sequence[Locator]) -> 'AtomSet':
|
|
106
128
|
"""Convenience method to select multiple fragments from locators
|
|
107
129
|
while interpreting and extending groups if necessary"""
|
|
108
|
-
|
|
130
|
+
logger.debug(f'Locate {locators} in {self}')
|
|
109
131
|
new = AtomSet()
|
|
110
132
|
assert len(locators) == 0 or isinstance(locators[0], Locator)
|
|
111
133
|
for label, symm_op_code, at in locators:
|
|
@@ -121,13 +143,13 @@ class AtomSet(Shape):
|
|
|
121
143
|
|
|
122
144
|
def select_atom(self, label_regex: str) -> 'AtomSet':
|
|
123
145
|
mask = self.table.index == label_regex
|
|
124
|
-
if not any(mask):
|
|
146
|
+
if not any(mask): # noqa: mask will in fact be Iterable
|
|
125
147
|
mask = self.table.index.str.match(label_regex)
|
|
126
|
-
|
|
148
|
+
logger.debug(f'Selected {sum(mask)} atoms with {label_regex=}')
|
|
127
149
|
return self.__class__(self.base, deepcopy(self.table[mask]))
|
|
128
150
|
|
|
129
151
|
def transform(self, symm_op_code: str) -> 'AtomSet':
|
|
130
|
-
symm_op =
|
|
152
|
+
symm_op = Operation.from_code(symm_op_code)
|
|
131
153
|
fract_xyz = symm_op.transform(self.fract_xyz.T)
|
|
132
154
|
data = deepcopy(self.table)
|
|
133
155
|
data['fract_x'] = fract_xyz[:, 0]
|
|
@@ -136,7 +158,7 @@ class AtomSet(Shape):
|
|
|
136
158
|
return self.__class__(self.base, data)
|
|
137
159
|
|
|
138
160
|
@property
|
|
139
|
-
def centroid(self):
|
|
161
|
+
def centroid(self) -> np.ndarray:
|
|
140
162
|
"""A 3-vector with average atom position."""
|
|
141
163
|
return self.cart_xyz.T.mean(axis=0)
|
|
142
164
|
|
|
@@ -165,7 +187,7 @@ class AtomSet(Shape):
|
|
|
165
187
|
return self.centroid
|
|
166
188
|
|
|
167
189
|
@origin.setter
|
|
168
|
-
def origin(self, new_origin):
|
|
190
|
+
def origin(self, new_origin) -> None:
|
|
169
191
|
"""Change origin to the new one provided in cartesian coordinates"""
|
|
170
192
|
new_origin_fract = self.fractionalise(new_origin)
|
|
171
193
|
delta = new_origin_fract - self.fractionalise(self.centroid)
|
|
@@ -178,16 +200,8 @@ class AtomSet(Shape):
|
|
|
178
200
|
assert all(o.kind is o.Kind.spatial for o in [self, *others])
|
|
179
201
|
combined = sum(others, self)
|
|
180
202
|
xyz = combined.cart_xyz.T
|
|
181
|
-
|
|
182
|
-
|
|
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
|
-
twist_dir = np.cross(plane1_dir, plane2_dir)
|
|
187
|
-
sign = +1 if are_synparallel(twist_dir, xyz[2] - xyz[1]) else -1
|
|
188
|
-
return sign * degrees_between(plane1_dir, plane2_dir, normalize=False)
|
|
189
|
-
else:
|
|
190
|
-
return 'Input AtomSet must contain between 3 and 6 atoms'
|
|
203
|
+
assert len(combined) == 3, 'Input AtomSet must contain exactly 3 atoms'
|
|
204
|
+
return degrees_between(xyz[0] - xyz[1], xyz[2] - xyz[1])
|
|
191
205
|
|
|
192
206
|
def _distance(self, other: 'Shape') -> float:
|
|
193
207
|
if other.kind is self.Kind.spatial:
|
|
@@ -205,3 +219,14 @@ class AtomSet(Shape):
|
|
|
205
219
|
norms = norm(deltas, axis=1)
|
|
206
220
|
along = np.abs(np.dot(deltas, other.direction))
|
|
207
221
|
return min(norms ** 2 - along ** 2)
|
|
222
|
+
|
|
223
|
+
def dihedral(self, *others: 'AtomSet') -> float:
|
|
224
|
+
assert all(o.kind is o.Kind.spatial for o in [self, *others])
|
|
225
|
+
combined = sum(others, self)
|
|
226
|
+
xyz = combined.cart_xyz.T
|
|
227
|
+
assert len(combined) == 4, 'Input AtomSet must contain exactly 4 atoms'
|
|
228
|
+
plane1_dir = np.cross(xyz[0] - xyz[1], xyz[2] - xyz[1])
|
|
229
|
+
plane2_dir = np.cross(xyz[-3] - xyz[-2], xyz[-1] - xyz[-2])
|
|
230
|
+
twist_dir = np.cross(plane1_dir, plane2_dir)
|
|
231
|
+
sign = +1 if are_synparallel(twist_dir, xyz[2] - xyz[1]) else -1
|
|
232
|
+
return sign * degrees_between(plane1_dir, plane2_dir, normalize=False)
|
|
@@ -0,0 +1,402 @@
|
|
|
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
|
+
import abc
|
|
10
|
+
from collections import deque
|
|
11
|
+
from copy import deepcopy
|
|
12
|
+
from glob import glob
|
|
13
|
+
import logging
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any, Union, Protocol
|
|
16
|
+
|
|
17
|
+
from numpy import rad2deg
|
|
18
|
+
import pandas as pd
|
|
19
|
+
import yaml
|
|
20
|
+
|
|
21
|
+
from picometer.atom import group_registry, AtomSet, Locator
|
|
22
|
+
from picometer.models import ModelState, ModelStates
|
|
23
|
+
from picometer.shapes import ExplicitShape
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# ~~~~~~~~~~~~~~~~~~~ INSTRUCTION AND ROUTINE DECLARATIONS ~~~~~~~~~~~~~~~~~~~ #
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Instruction:
|
|
32
|
+
"""An individual atomic instruction to be processed by the processor"""
|
|
33
|
+
def __init__(self, raw_instruction: Union[dict, str] = None, /, **kwargs):
|
|
34
|
+
input_ = {}
|
|
35
|
+
if raw_instruction is not None:
|
|
36
|
+
if isinstance(raw_instruction, str):
|
|
37
|
+
input_.update({raw_instruction: {}})
|
|
38
|
+
else: # if isinstance(raw_instruction, dict)
|
|
39
|
+
input_.update(raw_instruction)
|
|
40
|
+
if kwargs:
|
|
41
|
+
input_.update(kwargs)
|
|
42
|
+
if len(input_) != 1:
|
|
43
|
+
raise ValueError(f'{input_=} must contain exactly one key:value pair')
|
|
44
|
+
self.keyword: str = next(iter(input_.keys()))
|
|
45
|
+
self.raw_kwargs: Union[str, dict[str, Any]] = next(iter(input_.values()))
|
|
46
|
+
|
|
47
|
+
def __eq__(self, other):
|
|
48
|
+
if isinstance(other, Instruction):
|
|
49
|
+
return self.handler == other.handler and self.kwargs == other.kwargs
|
|
50
|
+
return NotImplemented
|
|
51
|
+
|
|
52
|
+
def __repr__(self) -> str:
|
|
53
|
+
return f'{self.__class__.__name__}({self.as_dict()})'
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def handler(self) -> 'type(BaseInstructionHandler)':
|
|
57
|
+
return BaseInstructionHandlerType.REGISTRY[self.keyword]
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def kwargs(self) -> dict[str, Any]:
|
|
61
|
+
expected_kwargs = self.handler.kwargs
|
|
62
|
+
if expected_kwargs is None:
|
|
63
|
+
return self.raw_kwargs
|
|
64
|
+
kwargs_ = {ek_key: None for ek_key in expected_kwargs.keys()}
|
|
65
|
+
if isinstance(self.raw_kwargs, dict):
|
|
66
|
+
for raw_kwarg_key, raw_kwarg_value in self.raw_kwargs.items():
|
|
67
|
+
if raw_kwarg_key not in expected_kwargs.keys():
|
|
68
|
+
raise KeyError(f'Unknown instruction argument: {raw_kwarg_key}')
|
|
69
|
+
expected_kwarg_type = expected_kwargs[raw_kwarg_key]
|
|
70
|
+
kwargs_[raw_kwarg_key] = expected_kwarg_type(raw_kwarg_value)
|
|
71
|
+
else: # if isinstance(self.raw_kwargs, str)
|
|
72
|
+
expected_kwarg_key = list(expected_kwargs.keys())[0]
|
|
73
|
+
expected_kwarg_type = list(expected_kwargs.values())[0]
|
|
74
|
+
kwargs_[expected_kwarg_key] = expected_kwarg_type(self.raw_kwargs)
|
|
75
|
+
return kwargs_
|
|
76
|
+
|
|
77
|
+
def as_dict(self) -> dict[str: Union[str, dict]]:
|
|
78
|
+
return {self.keyword: self.raw_kwargs}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class Routine(deque[Instruction]):
|
|
82
|
+
"""
|
|
83
|
+
A queue of subsequent `Instruction`s to be executed by the processor.
|
|
84
|
+
It can be created either in a single step from an input file,
|
|
85
|
+
or by iteratively right-appending individual instructions.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
@classmethod
|
|
89
|
+
def concatenate(cls, routines: list['Routine']):
|
|
90
|
+
new_routine = routines.pop(0) if routines else Routine()
|
|
91
|
+
while routines:
|
|
92
|
+
new_routine.append(Instruction('clear'))
|
|
93
|
+
new_routine.extend(routines.pop(0))
|
|
94
|
+
return cls(new_routine)
|
|
95
|
+
|
|
96
|
+
@classmethod
|
|
97
|
+
def from_dict(cls, dict_: dict) -> 'Routine':
|
|
98
|
+
new_routine = []
|
|
99
|
+
if settings := dict_.get('settings'):
|
|
100
|
+
for k, v in settings.items():
|
|
101
|
+
new_routine.append(Instruction(set={k: v}))
|
|
102
|
+
if instructions := dict_.get('instructions'):
|
|
103
|
+
for raw_instruction in instructions:
|
|
104
|
+
new_routine.append(Instruction(raw_instruction))
|
|
105
|
+
return cls(new_routine)
|
|
106
|
+
|
|
107
|
+
@classmethod
|
|
108
|
+
def from_string(cls, text: str) -> 'Routine':
|
|
109
|
+
yaml_segments = yaml.load_all(text, yaml.SafeLoader)
|
|
110
|
+
return cls.concatenate([cls.from_dict(y) for y in yaml_segments])
|
|
111
|
+
|
|
112
|
+
@classmethod
|
|
113
|
+
def from_yaml(cls, path: Union[str, Path]) -> 'Routine':
|
|
114
|
+
with open(path, 'r') as yaml_file:
|
|
115
|
+
return cls.from_string(yaml_file.read())
|
|
116
|
+
|
|
117
|
+
def as_dict(self) -> dict[str, list[dict]]:
|
|
118
|
+
return {'instructions': [i.as_dict() for i in self]}
|
|
119
|
+
|
|
120
|
+
def to_yaml(self, path: Union[str, Path]) -> None:
|
|
121
|
+
with open(path, 'w') as yaml_file:
|
|
122
|
+
yaml.dump(self.as_dict(), yaml_file)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
# ~~~~~~~~~~~~~~~~~~~ INSTRUCTION REGISTRY AND BASE CLASSES ~~~~~~~~~~~~~~~~~~ #
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class ProcessorProtocol(Protocol):
|
|
129
|
+
evaluation_table: pd.DataFrame
|
|
130
|
+
history: Routine
|
|
131
|
+
model_states: ModelStates
|
|
132
|
+
selection: list[Locator]
|
|
133
|
+
settings: dict[str, Any]
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class BaseInstructionHandlerType(type):
|
|
137
|
+
"""Metaclass that automatically registers new handlers in `REGISTRY`"""
|
|
138
|
+
REGISTRY = {}
|
|
139
|
+
|
|
140
|
+
def __new__(mcs, *args, **kwargs) -> 'BaseInstructionHandlerType':
|
|
141
|
+
new_cls = type.__new__(mcs, *args, **kwargs)
|
|
142
|
+
if name := getattr(new_cls, 'name', ''):
|
|
143
|
+
mcs.REGISTRY[name] = new_cls
|
|
144
|
+
return new_cls
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class BaseInstructionHandler(metaclass=BaseInstructionHandlerType):
|
|
148
|
+
"""
|
|
149
|
+
Base `InstructionHandler` class to be used for managing all instructions.
|
|
150
|
+
Must define the following attributes and methods:
|
|
151
|
+
- `name`: if given, auto-registers handler in the REGISTRY
|
|
152
|
+
- `kwargs`: if given, auto-converts string arguments into dict
|
|
153
|
+
- `handle()`: the method called be processor to handle instruction
|
|
154
|
+
"""
|
|
155
|
+
|
|
156
|
+
# Abstract class attributes and methods to be defined by all child handlers
|
|
157
|
+
|
|
158
|
+
name: str = None
|
|
159
|
+
kwargs: dict[str: type] = None
|
|
160
|
+
|
|
161
|
+
@abc.abstractmethod
|
|
162
|
+
def handle(self, instruction: Instruction) -> None:
|
|
163
|
+
"""Alter the state of the processor according to the instruction"""
|
|
164
|
+
|
|
165
|
+
# Common base methods accessible to all child handlers
|
|
166
|
+
|
|
167
|
+
def __init__(self, processor: ProcessorProtocol) -> None:
|
|
168
|
+
self.processor = processor
|
|
169
|
+
|
|
170
|
+
def clear_selection(self):
|
|
171
|
+
self.processor.selection = []
|
|
172
|
+
logger.info('Cleared selection')
|
|
173
|
+
|
|
174
|
+
def clear_selection_after_use(self) -> None:
|
|
175
|
+
if self.processor.settings.get('clear_selection_after_use'):
|
|
176
|
+
self.clear_selection()
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
class SerialInstructionHandler(BaseInstructionHandler):
|
|
180
|
+
"""Handlers that handle model states independently and exhausts selection"""
|
|
181
|
+
def handle(self, instruction: Instruction) -> None:
|
|
182
|
+
for ms_key, ms in self.processor.model_states.items():
|
|
183
|
+
self.handle_one(instruction, ms_key, ms)
|
|
184
|
+
self.clear_selection_after_use()
|
|
185
|
+
|
|
186
|
+
@abc.abstractmethod
|
|
187
|
+
def handle_one(self, instruction: Instruction, ms_key: str, ms: ModelState) -> None:
|
|
188
|
+
"""Abstract function to handle a process a single model state"""
|
|
189
|
+
|
|
190
|
+
def _collect_shapes(self, ms: ModelState) -> list[ExplicitShape]:
|
|
191
|
+
shapes = []
|
|
192
|
+
for locator in self.processor.selection:
|
|
193
|
+
if (shape_label := locator.label) in ms.shapes:
|
|
194
|
+
shapes.append(ms.shapes[shape_label])
|
|
195
|
+
else:
|
|
196
|
+
shapes.append(ms.nodes.locate([locator]))
|
|
197
|
+
return shapes
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
# ~~~~~~~~~~~~~~~~~~~~ CONCRETE INSTRUCTIONS DECLARATIONS ~~~~~~~~~~~~~~~~~~~~ #
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
class LoadInstructionHandler(BaseInstructionHandler):
|
|
204
|
+
name = 'load'
|
|
205
|
+
kwargs = dict(path=str, block=str)
|
|
206
|
+
|
|
207
|
+
def handle(self, instruction: Instruction) -> None:
|
|
208
|
+
cif_path = instruction.kwargs['path']
|
|
209
|
+
block_name = instruction.kwargs['block']
|
|
210
|
+
if Path(cif_path).is_file():
|
|
211
|
+
self._load_model_state(cif_path, block_name)
|
|
212
|
+
else:
|
|
213
|
+
for cif_path in sorted(glob(cif_path)):
|
|
214
|
+
self._load_model_state(cif_path, block_name)
|
|
215
|
+
|
|
216
|
+
def _load_model_state(self, cif_path, block_name):
|
|
217
|
+
atoms = AtomSet.from_cif(cif_path=cif_path, block_name=block_name)
|
|
218
|
+
label = cif_path + (':' + block_name if block_name else '')
|
|
219
|
+
self.processor.model_states[label] = ModelState(atoms=atoms)
|
|
220
|
+
logger.info(f'Loaded model state {label}')
|
|
221
|
+
if not self.processor.settings['auto_write_unit_cell']:
|
|
222
|
+
return
|
|
223
|
+
et = self.processor.evaluation_table
|
|
224
|
+
et.loc[label, 'unit_cell_a'] = atoms.base.a_d
|
|
225
|
+
et.loc[label, 'unit_cell_b'] = atoms.base.b_d
|
|
226
|
+
et.loc[label, 'unit_cell_c'] = atoms.base.c_d
|
|
227
|
+
et.loc[label, 'unit_cell_al'] = rad2deg(atoms.base.al_d)
|
|
228
|
+
et.loc[label, 'unit_cell_be'] = rad2deg(atoms.base.be_d)
|
|
229
|
+
et.loc[label, 'unit_cell_ga'] = rad2deg(atoms.base.ga_d)
|
|
230
|
+
et.loc[label, 'unit_cell_v'] = atoms.base.v_d
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
class SelectInstructionHandler(BaseInstructionHandler):
|
|
234
|
+
name = 'select'
|
|
235
|
+
kwargs = dict(label=str, symm=str, at=Locator)
|
|
236
|
+
|
|
237
|
+
def handle(self, instruction: Instruction) -> None:
|
|
238
|
+
loc = Locator.from_dict(instruction.kwargs)
|
|
239
|
+
if loc:
|
|
240
|
+
self.processor.selection.append(loc)
|
|
241
|
+
logger.info(f'Added {loc} to current selection')
|
|
242
|
+
else:
|
|
243
|
+
self.clear_selection()
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
class RecenterInstructionHandler(BaseInstructionHandler):
|
|
247
|
+
name = 'recenter'
|
|
248
|
+
kwargs = dict(label=str, symm=str, at=Locator)
|
|
249
|
+
|
|
250
|
+
def handle(self, instruction: Instruction) -> None:
|
|
251
|
+
new_center = [Locator.from_dict(instruction.kwargs)]
|
|
252
|
+
new_locators = [Locator.from_dict(dict(loc._asdict(), at=new_center))
|
|
253
|
+
for loc in self.processor.selection]
|
|
254
|
+
self.processor.selection = new_locators
|
|
255
|
+
logger.info(f'Recentered selection, current: {self.processor.selection}')
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
class GroupInstructionHandler(BaseInstructionHandler):
|
|
259
|
+
name = 'group'
|
|
260
|
+
kwargs = dict(label=str)
|
|
261
|
+
|
|
262
|
+
def handle(self, instruction: Instruction) -> None:
|
|
263
|
+
group = deepcopy(self.processor.selection)
|
|
264
|
+
label = instruction.kwargs['label']
|
|
265
|
+
group_registry[label] = group
|
|
266
|
+
logger.info(f'Defined new group {label} from selection {group}')
|
|
267
|
+
self.clear_selection_after_use()
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
class CentroidInstructionHandler(SerialInstructionHandler):
|
|
271
|
+
name = 'centroid'
|
|
272
|
+
kwargs = dict(label=str)
|
|
273
|
+
|
|
274
|
+
def handle_one(self, instruction: Instruction, ms_key: str, ms: ModelState) -> None:
|
|
275
|
+
label = instruction.kwargs['label']
|
|
276
|
+
focus = ms.nodes.locate(self.processor.selection)
|
|
277
|
+
c_fract = focus.fractionalise(focus.centroid)
|
|
278
|
+
c_atoms = {'label': [label], 'fract_x': [c_fract[0]],
|
|
279
|
+
'fract_y': [c_fract[1]], 'fract_z': [c_fract[2]], }
|
|
280
|
+
atoms = pd.DataFrame.from_records(c_atoms).set_index('label')
|
|
281
|
+
centroid = AtomSet(focus.base, atoms)
|
|
282
|
+
ms.centroids += centroid
|
|
283
|
+
logger.info(f'Defined centroid {label}: {centroid} for model state {ms_key}')
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
class LineInstructionHandler(SerialInstructionHandler):
|
|
287
|
+
name = 'line'
|
|
288
|
+
kwargs = dict(label=str)
|
|
289
|
+
|
|
290
|
+
def handle_one(self, instruction: Instruction, ms_key: str, ms: ModelState) -> None:
|
|
291
|
+
label = instruction.kwargs['label']
|
|
292
|
+
focus = ms.nodes.locate(self.processor.selection)
|
|
293
|
+
line = focus.line
|
|
294
|
+
ms.shapes[label] = line
|
|
295
|
+
logger.info(f'Defined line {label}: {line} for model state {ms_key}')
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
class PlaneInstructionsHandler(SerialInstructionHandler):
|
|
299
|
+
name = 'plane'
|
|
300
|
+
kwargs = dict(label=str)
|
|
301
|
+
|
|
302
|
+
def handle_one(self, instruction: Instruction, ms_key: str, ms: ModelState) -> None:
|
|
303
|
+
label = instruction.kwargs['label']
|
|
304
|
+
focus = ms.nodes.locate(self.processor.selection)
|
|
305
|
+
plane = focus.plane
|
|
306
|
+
ms.shapes[label] = plane
|
|
307
|
+
logger.info(f'Defined plane {label}: {plane} for model state {ms_key}')
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
class CoordinatesInstructionHandler(SerialInstructionHandler):
|
|
311
|
+
name = 'coordinates'
|
|
312
|
+
kwargs = None
|
|
313
|
+
|
|
314
|
+
def handle_one(self, instruction: Instruction, ms_key: str, ms: ModelState) -> None:
|
|
315
|
+
focus = ms.nodes.locate(self.processor.selection)
|
|
316
|
+
for label, coords in focus.table.iterrows():
|
|
317
|
+
self.processor.evaluation_table.loc[ms_key, label + '_x'] = coords.fract_x
|
|
318
|
+
self.processor.evaluation_table.loc[ms_key, label + '_y'] = coords.fract_y
|
|
319
|
+
self.processor.evaluation_table.loc[ms_key, label + '_z'] = coords.fract_z
|
|
320
|
+
logger.info(f'Noted coordinates for current selection in model state {ms_key}')
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
class DisplacementInstructionHandler(SerialInstructionHandler):
|
|
324
|
+
name = 'displacement'
|
|
325
|
+
kwargs = None
|
|
326
|
+
|
|
327
|
+
def handle_one(self, instruction: Instruction, ms_key: str, ms: ModelState) -> None:
|
|
328
|
+
focus = ms.nodes.locate(self.processor.selection)
|
|
329
|
+
for label, displacements in focus.table.iterrows():
|
|
330
|
+
for suffix in 'Uiso U11 U22 U33 U23 U13 U12'.split():
|
|
331
|
+
label_ = label + '_' + suffix
|
|
332
|
+
value = getattr(displacements, suffix, None)
|
|
333
|
+
if value is not None:
|
|
334
|
+
self.processor.evaluation_table.loc[ms_key, label_] = value
|
|
335
|
+
logger.info(f'Noted displacement for current selection in model state {ms_key}')
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
class DistanceInstructionHandler(SerialInstructionHandler):
|
|
339
|
+
name = 'distance'
|
|
340
|
+
kwargs = dict(label=str)
|
|
341
|
+
|
|
342
|
+
def handle_one(self, instruction: Instruction, ms_key: str, ms: ModelState) -> None:
|
|
343
|
+
label = instruction.kwargs['label']
|
|
344
|
+
shapes = self._collect_shapes(ms)
|
|
345
|
+
assert len(shapes) == 2
|
|
346
|
+
distance = shapes[0].distance(shapes[1])
|
|
347
|
+
self.processor.evaluation_table.loc[ms_key, label] = distance
|
|
348
|
+
logger.info(f'Evaluated distance {label}: {distance} for model state {ms_key}')
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
class AngleInstructionHandler(SerialInstructionHandler):
|
|
352
|
+
name = 'angle'
|
|
353
|
+
kwargs = dict(label=str)
|
|
354
|
+
|
|
355
|
+
def handle_one(self, instruction: Instruction, ms_key: str, ms: ModelState) -> None:
|
|
356
|
+
label = instruction.kwargs['label']
|
|
357
|
+
shapes = self._collect_shapes(ms)
|
|
358
|
+
assert len(shapes)
|
|
359
|
+
angle = shapes[0].angle(*shapes[1:])
|
|
360
|
+
self.processor.evaluation_table.loc[ms_key, label] = angle
|
|
361
|
+
logger.info(f'Evaluated angle {label}: {angle} for model state {ms_key}')
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
class DihedralInstructionHandler(SerialInstructionHandler):
|
|
365
|
+
name = 'dihedral'
|
|
366
|
+
kwargs = dict(label=str)
|
|
367
|
+
|
|
368
|
+
def handle_one(self, instruction: Instruction, ms_key: str, ms: ModelState) -> None:
|
|
369
|
+
label = instruction.kwargs['label']
|
|
370
|
+
shapes = self._collect_shapes(ms)
|
|
371
|
+
assert len(shapes) == 4 and all(s.kind is s.Kind.spatial for s in shapes)
|
|
372
|
+
dihedral = shapes[0].dihedral(*shapes[1:]) # noqa: shapes: list[AtomSet]
|
|
373
|
+
self.processor.evaluation_table.loc[ms_key, label] = dihedral
|
|
374
|
+
logger.info(f'Evaluated dihedral {label}: {dihedral} for model state {ms_key}')
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
class WriteInstructionHandler(BaseInstructionHandler):
|
|
378
|
+
name = 'write'
|
|
379
|
+
kwargs = dict(path=Path)
|
|
380
|
+
|
|
381
|
+
def handle(self, instruction: Instruction) -> None:
|
|
382
|
+
path = instruction.kwargs['path']
|
|
383
|
+
self.processor.evaluation_table.to_csv(path_or_buf=path)
|
|
384
|
+
logger.info(f'Saved current evaluation table to {path}')
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
class ClearInstructionHandler(BaseInstructionHandler):
|
|
388
|
+
name = 'clear'
|
|
389
|
+
kwargs = dict()
|
|
390
|
+
|
|
391
|
+
def handle(self, instruction: Instruction) -> None:
|
|
392
|
+
self.processor.__init__()
|
|
393
|
+
logger.info('Reinitialized processor')
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
class SetInstructionHandler(BaseInstructionHandler):
|
|
397
|
+
name = 'set'
|
|
398
|
+
kwargs = None # any kwarg is acceptable
|
|
399
|
+
|
|
400
|
+
def handle(self, instruction: Instruction) -> None:
|
|
401
|
+
new_settings = instruction.raw_kwargs
|
|
402
|
+
self.processor.settings.update(new_settings)
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
import logging
|
|
3
|
+
from typing import Any, Callable, Union
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _get_logger() -> logging.Logger:
|
|
10
|
+
"""Set up logging, but don't log yet in case picometer is used as package"""
|
|
11
|
+
logger_ = logging.getLogger('picometer')
|
|
12
|
+
logger_.setLevel(logging.DEBUG)
|
|
13
|
+
logger_.addHandler(logging.NullHandler())
|
|
14
|
+
return logger_
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
logger = _get_logger()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def add_file_handler(path: Union[str, Path]) -> logging.FileHandler:
|
|
21
|
+
"""If used as program, allow logging directly to a file using `FileHandler`"""
|
|
22
|
+
# now = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
|
|
23
|
+
# path = str((p := Path(path)).with_suffix('')) + '_' + now + p.suffix
|
|
24
|
+
file_handler = logging.FileHandler(path)
|
|
25
|
+
file_handler.setLevel(logging.DEBUG)
|
|
26
|
+
file_handler.setFormatter(formatter)
|
|
27
|
+
logger.addHandler(file_handler)
|
|
28
|
+
return file_handler
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class LogEventHandler(logging.Handler):
|
|
32
|
+
"""Custom handler for external log processing, see `register_log_listener`"""
|
|
33
|
+
def __init__(self, log_callback) -> None:
|
|
34
|
+
super().__init__()
|
|
35
|
+
self.log_callback = log_callback # A callback to process log events
|
|
36
|
+
|
|
37
|
+
def emit(self, record) -> None:
|
|
38
|
+
log_entry = self.format(record)
|
|
39
|
+
self.log_callback(log_entry) # Send log entry to the callback
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def register_log_listener(log_callback: Callable[[str], Any]) -> LogEventHandler:
|
|
43
|
+
"""A simple implementation, register function to call it for each log entry"""
|
|
44
|
+
log_event_handler = LogEventHandler(log_callback)
|
|
45
|
+
log_event_handler.setLevel(logging.DEBUG)
|
|
46
|
+
log_event_handler.setFormatter(formatter)
|
|
47
|
+
logger.addHandler(log_event_handler)
|
|
48
|
+
return log_event_handler
|
|
@@ -1,22 +1,27 @@
|
|
|
1
|
-
|
|
1
|
+
import logging
|
|
2
|
+
|
|
2
3
|
from picometer.atom import AtomSet
|
|
3
4
|
from picometer.shapes import ExplicitShape
|
|
4
5
|
|
|
5
6
|
|
|
7
|
+
logger = logging.getLogger(__name__)
|
|
8
|
+
|
|
9
|
+
|
|
6
10
|
class ModelState:
|
|
7
11
|
"""Class describing atomsets, selections, and shapes in one structure"""
|
|
8
12
|
def __init__(self,
|
|
9
13
|
atoms: AtomSet,
|
|
10
14
|
centroids: AtomSet = AtomSet(),
|
|
11
|
-
shapes:
|
|
15
|
+
shapes: dict[str, ExplicitShape] = None):
|
|
12
16
|
self.atoms: AtomSet = atoms
|
|
13
17
|
self.centroids: AtomSet = centroids
|
|
14
|
-
self.shapes:
|
|
18
|
+
self.shapes: dict[str, ExplicitShape] = shapes if shapes else {}
|
|
19
|
+
logger.debug(f'Initialized {self}')
|
|
15
20
|
|
|
16
21
|
@property
|
|
17
|
-
def nodes(self):
|
|
22
|
+
def nodes(self) -> AtomSet:
|
|
18
23
|
return self.atoms + self.centroids
|
|
19
24
|
|
|
20
25
|
|
|
21
|
-
class ModelStates(
|
|
22
|
-
|
|
26
|
+
class ModelStates(dict[str, ModelState]):
|
|
27
|
+
"""A simple dictionary that stores `ModelState`s under their path"""
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import Callable, Dict, List
|
|
3
|
+
|
|
4
|
+
import pandas as pd
|
|
5
|
+
|
|
6
|
+
from picometer.atom import Locator
|
|
7
|
+
from picometer.models import ModelStates
|
|
8
|
+
from picometer.instructions import Instruction, Routine
|
|
9
|
+
from picometer.settings import Settings
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Processor:
|
|
16
|
+
"""
|
|
17
|
+
This is the main class responsible for controlling, processing,
|
|
18
|
+
storing current state, importing, exporting the current state
|
|
19
|
+
of work performed in picometer via `process`ing `Instruction`s.
|
|
20
|
+
"""
|
|
21
|
+
instructions: Dict[str, Callable] = {}
|
|
22
|
+
|
|
23
|
+
def __init__(self, settings: Settings = None) -> None:
|
|
24
|
+
self.evaluation_table = pd.DataFrame()
|
|
25
|
+
self.history = Routine()
|
|
26
|
+
self.model_states: ModelStates = ModelStates()
|
|
27
|
+
self.selection: List[Locator] = []
|
|
28
|
+
self.settings = Settings.from_yaml()
|
|
29
|
+
if settings:
|
|
30
|
+
self.settings.update(settings)
|
|
31
|
+
logger.info(f'Initialized processor {self}')
|
|
32
|
+
|
|
33
|
+
def process(self, instruction: Instruction) -> None:
|
|
34
|
+
"""Process one instruction by handling it by dedicated `InstructionHandle`"""
|
|
35
|
+
handler = instruction.handler(self)
|
|
36
|
+
handler.handle(instruction)
|
|
37
|
+
self.history.append(instruction)
|
|
38
|
+
logger.info(f'{self} processed {instruction}')
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def process(routine: Routine) -> Processor:
|
|
42
|
+
"""Shorthand function to process a full `Routine` of `Instruction`s"""
|
|
43
|
+
logger.info(f'Bulk-processing {routine}')
|
|
44
|
+
processor = Processor()
|
|
45
|
+
for instruction in routine:
|
|
46
|
+
processor.process(instruction)
|
|
47
|
+
return processor
|
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
from collections import UserDict
|
|
2
2
|
from dataclasses import asdict, dataclass, fields, Field
|
|
3
3
|
from importlib import resources
|
|
4
|
+
import logging
|
|
4
5
|
from typing import Union
|
|
5
6
|
|
|
6
7
|
import yaml
|
|
7
8
|
|
|
8
9
|
|
|
10
|
+
logger = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
9
13
|
class SettingsError(KeyError):
|
|
10
14
|
"""Custom `KeyError` raised when there are issues with `DefaultSettings`"""
|
|
11
15
|
|
|
@@ -13,6 +17,7 @@ class SettingsError(KeyError):
|
|
|
13
17
|
@dataclass
|
|
14
18
|
class DefaultSettings:
|
|
15
19
|
"""Store default values of all settings. Use `AnyValue` if no default."""
|
|
20
|
+
auto_write_unit_cell: bool = True
|
|
16
21
|
clear_selection_after_use: bool = True
|
|
17
22
|
|
|
18
23
|
@classmethod
|
|
@@ -36,14 +41,17 @@ class Settings(UserDict):
|
|
|
36
41
|
super().__init__(asdict(DefaultSettings())) # noqa
|
|
37
42
|
if data:
|
|
38
43
|
self.update(data)
|
|
44
|
+
logger.debug(f'Initialized {self}')
|
|
39
45
|
|
|
40
46
|
def __setitem__(self, key, value, /) -> None:
|
|
41
47
|
field = DefaultSettings.get_field(key)
|
|
42
|
-
super().__setitem__(key, field.type(value))
|
|
48
|
+
super().__setitem__(key, value := field.type(value))
|
|
49
|
+
logger.debug(f'Changed setting {key} to {value}')
|
|
43
50
|
|
|
44
51
|
def __delitem__(self, key, /) -> None:
|
|
45
52
|
field = DefaultSettings.get_field(key)
|
|
46
|
-
super().__setitem__(key, field.default)
|
|
53
|
+
super().__setitem__(key, default := field.default)
|
|
54
|
+
logger.debug(f'Reset setting {key} to {default}')
|
|
47
55
|
|
|
48
56
|
def update(self, other: Union[dict, UserDict] = None, /, **kwargs) -> None:
|
|
49
57
|
other = {**other, **kwargs} if other else kwargs
|
|
@@ -9,7 +9,7 @@ import numpy.typing as npt
|
|
|
9
9
|
from numpy.linalg import norm
|
|
10
10
|
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
13
|
|
|
14
14
|
|
|
15
15
|
Vector3 = Annotated[npt.NDArray[float], Literal[3]]
|
|
@@ -91,7 +91,7 @@ class Shape:
|
|
|
91
91
|
assert isinstance(self, Shape) and isinstance(other, Shape)
|
|
92
92
|
if not self.kind.value >= other.kind.value: # let self.kind >= other
|
|
93
93
|
return other.distance(self)
|
|
94
|
-
|
|
94
|
+
logger.debug(f'Calculating distance between {self} and {other}')
|
|
95
95
|
return self._distance(other) # delegate to concrete implementation
|
|
96
96
|
|
|
97
97
|
@abc.abstractmethod
|
|
@@ -104,7 +104,7 @@ class Shape:
|
|
|
104
104
|
For Explicit shape, accept two parameters; for AtomSets, any size.
|
|
105
105
|
"""
|
|
106
106
|
assert all(isinstance(o, Shape) for o in [self, *others])
|
|
107
|
-
|
|
107
|
+
logger.debug(f'Calculating angle between {self} and {others}')
|
|
108
108
|
return self._angle(*others) # delegate to concrete implementation
|
|
109
109
|
|
|
110
110
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[tool.poetry]
|
|
2
2
|
name = "picometer"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.3.0"
|
|
4
4
|
description = "Precisely define and calculate measurements across multiple crystal structures"
|
|
5
5
|
authors = ["Daniel Tchoń"]
|
|
6
6
|
license = "MIT"
|
|
@@ -33,7 +33,7 @@ branch = "master" # branch to make releas
|
|
|
33
33
|
changelog_file = "CHANGELOG.md" # changelog file
|
|
34
34
|
build_command = "pip install poetry && poetry build" # build dists
|
|
35
35
|
commit_parser = "emoji" # default EmojiCommitParser
|
|
36
|
-
major_on_zero = true
|
|
36
|
+
major_on_zero = false # change to "true" only if you are sure you want version 1
|
|
37
37
|
commit_message = ":bookmark: v{version}\n\nAutomatically generated by python-semantic-release"
|
|
38
38
|
|
|
39
39
|
[tool.semantic_release.branches]
|
|
@@ -1,199 +0,0 @@
|
|
|
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'}))
|
|
@@ -1,45 +0,0 @@
|
|
|
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())
|
|
File without changes
|
|
File without changes
|
|
File without changes
|