picometer 0.1.3__tar.gz → 0.2.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.2.0}/PKG-INFO +3 -3
- {picometer-0.1.3 → picometer-0.2.0}/README.md +2 -2
- {picometer-0.1.3 → picometer-0.2.0}/picometer/__main__.py +3 -1
- {picometer-0.1.3 → picometer-0.2.0}/picometer/atom.py +31 -24
- picometer-0.2.0/picometer/instructions.py +374 -0
- picometer-0.2.0/picometer/logging.py +48 -0
- {picometer-0.1.3 → picometer-0.2.0}/picometer/models.py +11 -6
- picometer-0.2.0/picometer/process.py +47 -0
- {picometer-0.1.3 → picometer-0.2.0}/picometer/settings.py +10 -2
- {picometer-0.1.3 → picometer-0.2.0}/picometer/settings.yaml +1 -0
- {picometer-0.1.3 → picometer-0.2.0}/picometer/shapes.py +3 -3
- {picometer-0.1.3 → picometer-0.2.0}/pyproject.toml +1 -1
- picometer-0.1.3/picometer/process.py +0 -199
- picometer-0.1.3/picometer/routine.py +0 -45
- {picometer-0.1.3 → picometer-0.2.0}/LICENSE +0 -0
- {picometer-0.1.3 → picometer-0.2.0}/picometer/__init__.py +0 -0
- {picometer-0.1.3 → picometer-0.2.0}/picometer/utility.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: picometer
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Precisely define and calculate measurements across multiple crystal structures
|
|
5
5
|
License: MIT
|
|
6
6
|
Author: Daniel Tchoń
|
|
@@ -142,8 +142,8 @@ The following instructions are currently supported by picometer:
|
|
|
142
142
|
- **Evaluation instructions**
|
|
143
143
|
- measure `distance` between 2 selected objects; if the selection includes
|
|
144
144
|
groups of atoms, measure closes distance to the group of atoms.
|
|
145
|
-
- measure `angle` between 2–
|
|
146
|
-
|
|
145
|
+
- measure `angle` between 2–3 selected objects: planes, lines, or (ordered) atoms.
|
|
146
|
+
- measure `dihedral` andle between 4 individually-selected ordered centroids/atoms.
|
|
147
147
|
|
|
148
148
|
|
|
149
149
|
## Contributing
|
|
@@ -122,8 +122,8 @@ The following instructions are currently supported by picometer:
|
|
|
122
122
|
- **Evaluation instructions**
|
|
123
123
|
- measure `distance` between 2 selected objects; if the selection includes
|
|
124
124
|
groups of atoms, measure closes distance to the group of atoms.
|
|
125
|
-
- measure `angle` between 2–
|
|
126
|
-
|
|
125
|
+
- measure `angle` between 2–3 selected objects: planes, lines, or (ordered) atoms.
|
|
126
|
+
- measure `dihedral` andle between 4 individually-selected ordered centroids/atoms.
|
|
127
127
|
|
|
128
128
|
|
|
129
129
|
## 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
|
|
@@ -8,11 +8,12 @@ import numpy as np
|
|
|
8
8
|
from numpy.linalg import norm
|
|
9
9
|
import pandas as pd
|
|
10
10
|
|
|
11
|
-
from picometer.shapes import degrees_between, Line,
|
|
11
|
+
from picometer.shapes import (are_synparallel, degrees_between, Line,
|
|
12
|
+
Plane, Shape, Vector3)
|
|
12
13
|
from picometer.utility import ustr2float
|
|
13
14
|
|
|
14
15
|
|
|
15
|
-
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
16
17
|
|
|
17
18
|
|
|
18
19
|
class Locator(NamedTuple):
|
|
@@ -29,7 +30,7 @@ class Locator(NamedTuple):
|
|
|
29
30
|
at=at if at else None)
|
|
30
31
|
|
|
31
32
|
def __bool__(self):
|
|
32
|
-
return self.label
|
|
33
|
+
return self.label is not None
|
|
33
34
|
|
|
34
35
|
|
|
35
36
|
group_registry: Dict[str, List[Locator]] = {}
|
|
@@ -44,25 +45,28 @@ class AtomSet(Shape):
|
|
|
44
45
|
bf: BaseFrame = None,
|
|
45
46
|
table: pd.DataFrame = None,
|
|
46
47
|
) -> None:
|
|
47
|
-
|
|
48
|
+
|
|
49
|
+
logger.debug(f'Created atom set with {bf!r} and '
|
|
50
|
+
f'{len(table) if table is not None else 0}-element table')
|
|
48
51
|
self.base = bf
|
|
49
52
|
self.table = table
|
|
50
53
|
|
|
51
|
-
def __len__(self):
|
|
54
|
+
def __len__(self) -> int:
|
|
52
55
|
return len(self.table) if self.table is not None else 0
|
|
53
56
|
|
|
54
|
-
def __add__(self, other):
|
|
57
|
+
def __add__(self, other) -> 'AtomSet':
|
|
55
58
|
if not (self.base or self.table):
|
|
56
59
|
return other
|
|
57
60
|
elif not (other.base or other.table):
|
|
58
61
|
return self
|
|
59
|
-
return
|
|
62
|
+
return self.__class__(self.base, pd.concat([self.table, other.table], axis=0))
|
|
60
63
|
|
|
61
64
|
def __getitem__(self, item) -> 'AtomSet':
|
|
62
65
|
return self.__class__(bf=self.base, table=self.table[item])
|
|
63
66
|
|
|
64
67
|
@classmethod
|
|
65
68
|
def from_cif(cls, cif_path: str, block_name: str = None) -> 'AtomSet':
|
|
69
|
+
"""Initialize from cif file using hikari's `BaseFrame` and `CifFrame`"""
|
|
66
70
|
bf = BaseFrame()
|
|
67
71
|
cf = CifFrame()
|
|
68
72
|
cf.read(cif_path)
|
|
@@ -87,11 +91,11 @@ class AtomSet(Shape):
|
|
|
87
91
|
return AtomSet(bf, atoms)
|
|
88
92
|
|
|
89
93
|
@property
|
|
90
|
-
def fract_xyz(self):
|
|
94
|
+
def fract_xyz(self) -> np.ndarray:
|
|
91
95
|
return np.vstack([self.table['fract_' + k].to_numpy() for k in 'xyz'])
|
|
92
96
|
|
|
93
97
|
@property
|
|
94
|
-
def cart_xyz(self):
|
|
98
|
+
def cart_xyz(self) -> np.ndarray:
|
|
95
99
|
return self.orthogonalise(self.fract_xyz)
|
|
96
100
|
|
|
97
101
|
def fractionalise(self, cart_xyz: np.ndarray) -> np.ndarray:
|
|
@@ -105,7 +109,7 @@ class AtomSet(Shape):
|
|
|
105
109
|
def locate(self, locators: Sequence[Locator]) -> 'AtomSet':
|
|
106
110
|
"""Convenience method to select multiple fragments from locators
|
|
107
111
|
while interpreting and extending groups if necessary"""
|
|
108
|
-
|
|
112
|
+
logger.debug(f'Locate {locators} in {self}')
|
|
109
113
|
new = AtomSet()
|
|
110
114
|
assert len(locators) == 0 or isinstance(locators[0], Locator)
|
|
111
115
|
for label, symm_op_code, at in locators:
|
|
@@ -121,9 +125,9 @@ class AtomSet(Shape):
|
|
|
121
125
|
|
|
122
126
|
def select_atom(self, label_regex: str) -> 'AtomSet':
|
|
123
127
|
mask = self.table.index == label_regex
|
|
124
|
-
if not any(mask):
|
|
128
|
+
if not any(mask): # noqa: mask will in fact be Iterable
|
|
125
129
|
mask = self.table.index.str.match(label_regex)
|
|
126
|
-
|
|
130
|
+
logger.debug(f'Selected {sum(mask)} atoms with {label_regex=}')
|
|
127
131
|
return self.__class__(self.base, deepcopy(self.table[mask]))
|
|
128
132
|
|
|
129
133
|
def transform(self, symm_op_code: str) -> 'AtomSet':
|
|
@@ -136,7 +140,7 @@ class AtomSet(Shape):
|
|
|
136
140
|
return self.__class__(self.base, data)
|
|
137
141
|
|
|
138
142
|
@property
|
|
139
|
-
def centroid(self):
|
|
143
|
+
def centroid(self) -> np.ndarray:
|
|
140
144
|
"""A 3-vector with average atom position."""
|
|
141
145
|
return self.cart_xyz.T.mean(axis=0)
|
|
142
146
|
|
|
@@ -165,7 +169,7 @@ class AtomSet(Shape):
|
|
|
165
169
|
return self.centroid
|
|
166
170
|
|
|
167
171
|
@origin.setter
|
|
168
|
-
def origin(self, new_origin):
|
|
172
|
+
def origin(self, new_origin) -> None:
|
|
169
173
|
"""Change origin to the new one provided in cartesian coordinates"""
|
|
170
174
|
new_origin_fract = self.fractionalise(new_origin)
|
|
171
175
|
delta = new_origin_fract - self.fractionalise(self.centroid)
|
|
@@ -178,16 +182,8 @@ class AtomSet(Shape):
|
|
|
178
182
|
assert all(o.kind is o.Kind.spatial for o in [self, *others])
|
|
179
183
|
combined = sum(others, self)
|
|
180
184
|
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'
|
|
185
|
+
assert len(combined) == 3, 'Input AtomSet must contain exactly 3 atoms'
|
|
186
|
+
return degrees_between(xyz[0] - xyz[1], xyz[2] - xyz[1])
|
|
191
187
|
|
|
192
188
|
def _distance(self, other: 'Shape') -> float:
|
|
193
189
|
if other.kind is self.Kind.spatial:
|
|
@@ -205,3 +201,14 @@ class AtomSet(Shape):
|
|
|
205
201
|
norms = norm(deltas, axis=1)
|
|
206
202
|
along = np.abs(np.dot(deltas, other.direction))
|
|
207
203
|
return min(norms ** 2 - along ** 2)
|
|
204
|
+
|
|
205
|
+
def dihedral(self, *others: 'AtomSet') -> float:
|
|
206
|
+
assert all(o.kind is o.Kind.spatial for o in [self, *others])
|
|
207
|
+
combined = sum(others, self)
|
|
208
|
+
xyz = combined.cart_xyz.T
|
|
209
|
+
assert len(combined) == 4, 'Input AtomSet must contain exactly 4 atoms'
|
|
210
|
+
plane1_dir = np.cross(xyz[0] - xyz[1], xyz[2] - xyz[1])
|
|
211
|
+
plane2_dir = np.cross(xyz[-3] - xyz[-2], xyz[-1] - xyz[-2])
|
|
212
|
+
twist_dir = np.cross(plane1_dir, plane2_dir)
|
|
213
|
+
sign = +1 if are_synparallel(twist_dir, xyz[2] - xyz[1]) else -1
|
|
214
|
+
return sign * degrees_between(plane1_dir, plane2_dir, normalize=False)
|
|
@@ -0,0 +1,374 @@
|
|
|
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 DistanceInstructionHandler(SerialInstructionHandler):
|
|
311
|
+
name = 'distance'
|
|
312
|
+
kwargs = dict(label=str)
|
|
313
|
+
|
|
314
|
+
def handle_one(self, instruction: Instruction, ms_key: str, ms: ModelState) -> None:
|
|
315
|
+
label = instruction.kwargs['label']
|
|
316
|
+
shapes = self._collect_shapes(ms)
|
|
317
|
+
assert len(shapes) == 2
|
|
318
|
+
distance = shapes[0].distance(shapes[1])
|
|
319
|
+
self.processor.evaluation_table.loc[ms_key, label] = distance
|
|
320
|
+
logger.info(f'Evaluated distance {label}: {distance} for model state {ms_key}')
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
class AngleInstructionHandler(SerialInstructionHandler):
|
|
324
|
+
name = 'angle'
|
|
325
|
+
kwargs = dict(label=str)
|
|
326
|
+
|
|
327
|
+
def handle_one(self, instruction: Instruction, ms_key: str, ms: ModelState) -> None:
|
|
328
|
+
label = instruction.kwargs['label']
|
|
329
|
+
shapes = self._collect_shapes(ms)
|
|
330
|
+
assert len(shapes)
|
|
331
|
+
angle = shapes[0].angle(*shapes[1:])
|
|
332
|
+
self.processor.evaluation_table.loc[ms_key, label] = angle
|
|
333
|
+
logger.info(f'Evaluated angle {label}: {angle} for model state {ms_key}')
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
class DihedralInstructionHandler(SerialInstructionHandler):
|
|
337
|
+
name = 'dihedral'
|
|
338
|
+
kwargs = dict(label=str)
|
|
339
|
+
|
|
340
|
+
def handle_one(self, instruction: Instruction, ms_key: str, ms: ModelState) -> None:
|
|
341
|
+
label = instruction.kwargs['label']
|
|
342
|
+
shapes = self._collect_shapes(ms)
|
|
343
|
+
assert len(shapes) == 4 and all(s.kind is s.Kind.spatial for s in shapes)
|
|
344
|
+
dihedral = shapes[0].dihedral(*shapes[1:]) # noqa: shapes: list[AtomSet]
|
|
345
|
+
self.processor.evaluation_table.loc[ms_key, label] = dihedral
|
|
346
|
+
logger.info(f'Evaluated dihedral {label}: {dihedral} for model state {ms_key}')
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
class WriteInstructionHandler(BaseInstructionHandler):
|
|
350
|
+
name = 'write'
|
|
351
|
+
kwargs = dict(path=Path)
|
|
352
|
+
|
|
353
|
+
def handle(self, instruction: Instruction) -> None:
|
|
354
|
+
path = instruction.kwargs['path']
|
|
355
|
+
self.processor.evaluation_table.to_csv(path_or_buf=path)
|
|
356
|
+
logger.info(f'Saved current evaluation table to {path}')
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
class ClearInstructionHandler(BaseInstructionHandler):
|
|
360
|
+
name = 'clear'
|
|
361
|
+
kwargs = dict()
|
|
362
|
+
|
|
363
|
+
def handle(self, instruction: Instruction) -> None:
|
|
364
|
+
self.processor.__init__()
|
|
365
|
+
logger.info('Reinitialized processor')
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
class SetInstructionHandler(BaseInstructionHandler):
|
|
369
|
+
name = 'set'
|
|
370
|
+
kwargs = None # any kwarg is acceptable
|
|
371
|
+
|
|
372
|
+
def handle(self, instruction: Instruction) -> None:
|
|
373
|
+
new_settings = instruction.raw_kwargs
|
|
374
|
+
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,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
|