tm2d 0.2.1__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.
- tm2d-0.3.0/PKG-INFO +57 -0
- tm2d-0.3.0/README.md +38 -0
- {tm2d-0.2.1 → tm2d-0.3.0}/pyproject.toml +1 -1
- {tm2d-0.2.1 → tm2d-0.3.0}/tm2d/base_comparator.py +1 -1
- {tm2d-0.2.1 → tm2d-0.3.0}/tm2d/base_results.py +1 -1
- {tm2d-0.2.1 → tm2d-0.3.0}/tm2d/base_template.py +5 -5
- {tm2d-0.2.1 → tm2d-0.3.0}/tm2d/comparators/cross_correlation.py +96 -5
- {tm2d-0.2.1 → tm2d-0.3.0}/tm2d/ctf/ctf.py +2 -2
- {tm2d-0.2.1 → tm2d-0.3.0}/tm2d/ctf/ctf_params.py +3 -3
- {tm2d-0.2.1 → tm2d-0.3.0}/tm2d/ctf/ctf_set.py +12 -7
- {tm2d-0.2.1 → tm2d-0.3.0}/tm2d/plan.py +17 -7
- {tm2d-0.2.1 → tm2d-0.3.0}/tm2d/results/per_param.py +57 -12
- {tm2d-0.2.1 → tm2d-0.3.0}/tm2d/results/per_pixel.py +28 -18
- {tm2d-0.2.1 → tm2d-0.3.0}/tm2d/templates/atomic.py +22 -25
- {tm2d-0.2.1 → tm2d-0.3.0}/tm2d/templates/density.py +60 -14
- tm2d-0.3.0/tm2d.egg-info/PKG-INFO +57 -0
- tm2d-0.2.1/PKG-INFO +0 -91
- tm2d-0.2.1/README.md +0 -72
- tm2d-0.2.1/tm2d.egg-info/PKG-INFO +0 -91
- {tm2d-0.2.1 → tm2d-0.3.0}/LICENSE +0 -0
- {tm2d-0.2.1 → tm2d-0.3.0}/setup.cfg +0 -0
- {tm2d-0.2.1 → tm2d-0.3.0}/tm2d/__init__.py +0 -0
- {tm2d-0.2.1 → tm2d-0.3.0}/tm2d/param_set.py +0 -0
- {tm2d-0.2.1 → tm2d-0.3.0}/tm2d.egg-info/SOURCES.txt +0 -0
- {tm2d-0.2.1 → tm2d-0.3.0}/tm2d.egg-info/dependency_links.txt +0 -0
- {tm2d-0.2.1 → tm2d-0.3.0}/tm2d.egg-info/requires.txt +0 -0
- {tm2d-0.2.1 → tm2d-0.3.0}/tm2d.egg-info/top_level.txt +0 -0
tm2d-0.3.0/PKG-INFO
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tm2d
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: A Python module for 2D template matching
|
|
5
|
+
Author-email: Shahar Sandhaus <shahar.sandhaus@berkeley.edu>
|
|
6
|
+
Project-URL: Homepage, https://github.com/sharhar/tm2d
|
|
7
|
+
Project-URL: Issues, https://github.com/sharhar/tm2d/issues
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
12
|
+
Requires-Python: >=3.9
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: setuptools>=59.0
|
|
16
|
+
Requires-Dist: numpy
|
|
17
|
+
Requires-Dist: vkdispatch==0.1.0
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# tm2d
|
|
21
|
+
|
|
22
|
+
`tm2d` is a Python package for GPU-accelerated 2D template matching. It contains the core algorithmic pieces: templates, CTF parameter handling, parameter grids, comparators, result containers, and execution plans.
|
|
23
|
+
|
|
24
|
+
Higher-level workflow code, file loading helpers, plotting utilities, and analysis scripts belong in `tm2d-utils` or downstream project code.
|
|
25
|
+
|
|
26
|
+
## Dependencies
|
|
27
|
+
|
|
28
|
+
Runtime dependencies are listed in `pyproject.toml`:
|
|
29
|
+
|
|
30
|
+
- Python >= 3.9
|
|
31
|
+
- `numpy`
|
|
32
|
+
- `vkdispatch==0.1.0`
|
|
33
|
+
- `setuptools>=59.0`
|
|
34
|
+
|
|
35
|
+
A working Vulkan/vkdispatch setup is required to run template matching.
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
From a local checkout:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
cd /path/to/tm2d
|
|
43
|
+
python -m pip install .
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
For development, install in editable mode:
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
cd /path/to/tm2d
|
|
50
|
+
python -m pip install -e .
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
To verify the installed package version:
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
python -m pip show tm2d
|
|
57
|
+
```
|
tm2d-0.3.0/README.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# tm2d
|
|
2
|
+
|
|
3
|
+
`tm2d` is a Python package for GPU-accelerated 2D template matching. It contains the core algorithmic pieces: templates, CTF parameter handling, parameter grids, comparators, result containers, and execution plans.
|
|
4
|
+
|
|
5
|
+
Higher-level workflow code, file loading helpers, plotting utilities, and analysis scripts belong in `tm2d-utils` or downstream project code.
|
|
6
|
+
|
|
7
|
+
## Dependencies
|
|
8
|
+
|
|
9
|
+
Runtime dependencies are listed in `pyproject.toml`:
|
|
10
|
+
|
|
11
|
+
- Python >= 3.9
|
|
12
|
+
- `numpy`
|
|
13
|
+
- `vkdispatch==0.1.0`
|
|
14
|
+
- `setuptools>=59.0`
|
|
15
|
+
|
|
16
|
+
A working Vulkan/vkdispatch setup is required to run template matching.
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
From a local checkout:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
cd /path/to/tm2d
|
|
24
|
+
python -m pip install .
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
For development, install in editable mode:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
cd /path/to/tm2d
|
|
31
|
+
python -m pip install -e .
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
To verify the installed package version:
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
python -m pip show tm2d
|
|
38
|
+
```
|
|
@@ -11,5 +11,5 @@ class Comparator:
|
|
|
11
11
|
"""
|
|
12
12
|
raise NotImplementedError("set_data must be implemented in a subclass.")
|
|
13
13
|
|
|
14
|
-
def compare_template(self, template: vd.RFFTBuffer, normalize: bool = True) -> vd.RFFTBuffer:
|
|
14
|
+
def compare_template(self, template: vd.RFFTBuffer, normalize: bool = True, output_radius: int = None) -> vd.RFFTBuffer:
|
|
15
15
|
raise NotImplementedError("compare_template must be implemented in a subclass.")
|
|
@@ -5,7 +5,7 @@ class Results:
|
|
|
5
5
|
def __init__(self):
|
|
6
6
|
raise NotImplementedError("Results is an abstract class. Please implement it in a subclass.")
|
|
7
7
|
|
|
8
|
-
def check_comparison(self, comparison_buffer: vd.RFFTBuffer, rotation_weights: vc.Var[vc.f32], *
|
|
8
|
+
def check_comparison(self, comparison_buffer: vd.RFFTBuffer, rotation_weights: vc.Var[vc.f32], *indices: vc.Var[vc.i32]):
|
|
9
9
|
raise NotImplementedError("check_comparison must be implemented in a subclass.")
|
|
10
10
|
|
|
11
11
|
def reset(self):
|
|
@@ -48,7 +48,7 @@ class Template:
|
|
|
48
48
|
else:
|
|
49
49
|
assert rotations.shape[1] == 3 , "Rotations must be a 2D array with shape (N, 3)."
|
|
50
50
|
|
|
51
|
-
rotations = self.
|
|
51
|
+
rotations = self.get_rotation_matrices(rotations)
|
|
52
52
|
|
|
53
53
|
return self._make_template(
|
|
54
54
|
rotations=rotations,
|
|
@@ -58,17 +58,17 @@ class Template:
|
|
|
58
58
|
cmd_graph=cmd_graph
|
|
59
59
|
)
|
|
60
60
|
|
|
61
|
-
def
|
|
62
|
-
raise NotImplementedError("
|
|
61
|
+
def _get_rotation_matrices(self, rotations: np.ndarray) -> np.ndarray:
|
|
62
|
+
raise NotImplementedError("get_rotation_matrices must be implemented in a subclass.")
|
|
63
63
|
|
|
64
|
-
def
|
|
64
|
+
def get_rotation_matrices(self, rotations: Union[np.ndarray, Tuple[float, float, float]]) -> np.ndarray:
|
|
65
65
|
if not isinstance(rotations, np.ndarray):
|
|
66
66
|
rotations = np.array(rotations, dtype=np.float32).reshape(1, 3)
|
|
67
67
|
|
|
68
68
|
if rotations.ndim == 1:
|
|
69
69
|
rotations = rotations.reshape(1, 3)
|
|
70
70
|
|
|
71
|
-
return self.
|
|
71
|
+
return self._get_rotation_matrices(rotations)
|
|
72
72
|
|
|
73
73
|
def get_shape(self) -> tuple:
|
|
74
74
|
"""
|
|
@@ -77,7 +77,7 @@ class ComparatorCrossCorrelation(Comparator):
|
|
|
77
77
|
data = np.fft.rfft2(data).astype(np.complex64)
|
|
78
78
|
self.micrographs_buffer.write_fourier(data)
|
|
79
79
|
|
|
80
|
-
def compare_template(self, template_buffer: vd.RFFTBuffer, normalize: bool = True) -> vd.RFFTBuffer:
|
|
80
|
+
def compare_template(self, template_buffer: vd.RFFTBuffer, normalize: bool = True, output_radius: int = None) -> vd.RFFTBuffer:
|
|
81
81
|
assert normalize, "Normalization is mandatory for cross-correlation."
|
|
82
82
|
|
|
83
83
|
correlation_shape = (
|
|
@@ -87,6 +87,7 @@ class ComparatorCrossCorrelation(Comparator):
|
|
|
87
87
|
)
|
|
88
88
|
|
|
89
89
|
correlation_signal = vd.RFFTBuffer(correlation_shape)
|
|
90
|
+
correlation_signal_out = vd.RFFTBuffer(correlation_shape)
|
|
90
91
|
|
|
91
92
|
template_sum = calc_sums(template_buffer)
|
|
92
93
|
|
|
@@ -108,6 +109,16 @@ class ComparatorCrossCorrelation(Comparator):
|
|
|
108
109
|
self.micrographs_buffer.shape[1] * self.micrographs_buffer.shape[2]
|
|
109
110
|
)
|
|
110
111
|
|
|
112
|
+
@vd.map
|
|
113
|
+
def conv_input_map(input_buffer: vc.Buffer[c64]):
|
|
114
|
+
with vc.if_block(vc.all(
|
|
115
|
+
vd.fft.read_op().fft_index >= self.micrographs_buffer.shape[1] // 2 - template_buffer.shape[1]// 2,
|
|
116
|
+
vd.fft.read_op().fft_index < self.micrographs_buffer.shape[1] // 2 + template_buffer.shape[1] // 2)):
|
|
117
|
+
vd.fft.read_op().read_from_buffer(input_buffer)
|
|
118
|
+
with vc.else_block():
|
|
119
|
+
vd.fft.read_op().register.real = 0.0
|
|
120
|
+
vd.fft.read_op().register.imag = 0.0
|
|
121
|
+
|
|
111
122
|
@vd.map
|
|
112
123
|
def convolution_map(kernel_buffer: vc.Buffer[c64]):
|
|
113
124
|
img_val = vd.fft.read_op().register
|
|
@@ -118,11 +129,20 @@ class ComparatorCrossCorrelation(Comparator):
|
|
|
118
129
|
|
|
119
130
|
@vd.map
|
|
120
131
|
def output_map_func(output_buffer: vc.Buffer[c64]):
|
|
121
|
-
|
|
122
|
-
|
|
132
|
+
if output_radius is None:
|
|
133
|
+
out_reg = vd.fft.write_op().register
|
|
134
|
+
output_buffer[vd.fft.write_op().io_index + kernel_offset * template_buffer.shape[0] * vd.fft.mapped_kernel_index()] = out_reg
|
|
135
|
+
return
|
|
136
|
+
|
|
137
|
+
with vc.if_block(vc.any(
|
|
138
|
+
vd.fft.write_op().fft_index < output_radius,
|
|
139
|
+
vd.fft.write_op().fft_index >= self.micrographs_buffer.shape[1] - output_radius)):
|
|
140
|
+
|
|
141
|
+
out_reg = vd.fft.write_op().register
|
|
142
|
+
output_buffer[vd.fft.write_op().io_index + kernel_offset * template_buffer.shape[0] * vd.fft.mapped_kernel_index()] = out_reg
|
|
123
143
|
|
|
124
144
|
vd.fft.convolve(
|
|
125
|
-
|
|
145
|
+
correlation_signal_out,
|
|
126
146
|
correlation_signal,
|
|
127
147
|
self.micrographs_buffer,
|
|
128
148
|
kernel_num=self.micrographs_buffer.shape[0],
|
|
@@ -132,10 +152,81 @@ class ComparatorCrossCorrelation(Comparator):
|
|
|
132
152
|
self.micrographs_buffer.shape[1],
|
|
133
153
|
self.micrographs_buffer.shape[2]
|
|
134
154
|
),
|
|
155
|
+
input_map=conv_input_map,
|
|
135
156
|
kernel_map=convolution_map,
|
|
136
157
|
output_map=output_map_func
|
|
137
158
|
)
|
|
138
159
|
|
|
139
|
-
|
|
160
|
+
if output_radius is None:
|
|
161
|
+
vd.fft.irfft(correlation_signal_out)
|
|
162
|
+
return correlation_signal_out
|
|
163
|
+
|
|
164
|
+
trimmed_shape = (
|
|
165
|
+
correlation_signal.real_shape[0],
|
|
166
|
+
output_radius * 2,
|
|
167
|
+
correlation_signal.real_shape[2]
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
trimmed_shape_2 = (
|
|
171
|
+
correlation_signal.shape[0],
|
|
172
|
+
output_radius * 2,
|
|
173
|
+
correlation_signal.shape[2] * 2
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
trimmed_shape_3 = (
|
|
177
|
+
correlation_signal.shape[0],
|
|
178
|
+
output_radius * 2,
|
|
179
|
+
correlation_signal.shape[2]
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
corr_shape_2 = (
|
|
183
|
+
correlation_signal.shape[0],
|
|
184
|
+
correlation_signal.shape[1],
|
|
185
|
+
correlation_signal.shape[2] * 2,
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
@vd.map
|
|
189
|
+
def irfft_map_input(input_buffer: vc.Buffer[c64]):
|
|
190
|
+
io_index = vd.fft.read_op().io_index
|
|
191
|
+
|
|
192
|
+
with vc.if_block(vd.fft.read_op().fft_index >= (vd.fft.read_op().fft_size // 2) + 1):
|
|
193
|
+
io_index[:] = vd.fft.read_op().r2c_inverse_offset - io_index
|
|
194
|
+
|
|
195
|
+
coord3d = vc.ravel_index(vd.fft.read_op().io_index, trimmed_shape_3).to_register()
|
|
196
|
+
|
|
197
|
+
with vc.if_block(coord3d.y >= output_radius):
|
|
198
|
+
coord3d.y += correlation_signal.shape[1] - output_radius * 2
|
|
199
|
+
|
|
200
|
+
new_io_index = vc.unravel_index(coord3d, correlation_signal.shape).to_register()
|
|
201
|
+
|
|
202
|
+
vd.fft.read_op().register[:] = input_buffer[new_io_index]
|
|
203
|
+
|
|
204
|
+
with vc.if_block(vd.fft.read_op().fft_index >= (vd.fft.read_op().fft_size // 2) + 1):
|
|
205
|
+
vd.fft.read_op().register.imag = -vd.fft.read_op().register.imag
|
|
206
|
+
|
|
207
|
+
@vd.map
|
|
208
|
+
def irfft_map_output(output_buffer: vc.Buffer[c64]):
|
|
209
|
+
coord3d = vc.ravel_index(vd.fft.write_op().io_index, trimmed_shape_2).to_register()
|
|
210
|
+
|
|
211
|
+
with vc.if_block(vc.any(
|
|
212
|
+
coord3d.z < output_radius,
|
|
213
|
+
coord3d.z >= self.micrographs_buffer.real_shape[2] - output_radius)):
|
|
214
|
+
|
|
215
|
+
with vc.if_block(coord3d.y >= output_radius):
|
|
216
|
+
coord3d.y += correlation_signal.shape[1] - output_radius * 2
|
|
217
|
+
|
|
218
|
+
new_io_index = vc.unravel_index(coord3d, corr_shape_2).to_register()
|
|
219
|
+
|
|
220
|
+
vd.fft.write_op().write_to_buffer(output_buffer, io_index=new_io_index)
|
|
221
|
+
|
|
222
|
+
vd.fft.fft(
|
|
223
|
+
correlation_signal,
|
|
224
|
+
correlation_signal_out,
|
|
225
|
+
buffer_shape=trimmed_shape,
|
|
226
|
+
input_map=irfft_map_input,
|
|
227
|
+
output_map=irfft_map_output,
|
|
228
|
+
r2c=True,
|
|
229
|
+
inverse=True
|
|
230
|
+
)
|
|
140
231
|
|
|
141
232
|
return correlation_signal
|
|
@@ -176,7 +176,7 @@ def ctf_filter(
|
|
|
176
176
|
def apply_ctfs_to_rfft_signals(
|
|
177
177
|
input_value: vc.ShaderVariable,
|
|
178
178
|
registers: list[vc.ShaderVariable],
|
|
179
|
-
|
|
179
|
+
indices: list[int],
|
|
180
180
|
ind: vc.ShaderVariable,
|
|
181
181
|
signal_shape: tuple[int, int, int],
|
|
182
182
|
pix_size: vc.ShaderVariable,
|
|
@@ -202,6 +202,6 @@ def apply_ctfs_to_rfft_signals(
|
|
|
202
202
|
registers[i][:] = vc.mult_complex(input_value, ctf_filter(
|
|
203
203
|
signal_shape[1:],
|
|
204
204
|
pos_2d,
|
|
205
|
-
ctf_param_list[
|
|
205
|
+
ctf_param_list[indices[i]],
|
|
206
206
|
pix_size
|
|
207
207
|
))
|
|
@@ -264,7 +264,7 @@ class CTFParams:
|
|
|
264
264
|
static_count = 0
|
|
265
265
|
dynamic_count = 0
|
|
266
266
|
static_values = [None] * len(fields)
|
|
267
|
-
|
|
267
|
+
dynamic_indices = []
|
|
268
268
|
|
|
269
269
|
for ii, field in enumerate(fields):
|
|
270
270
|
value = self.__getattribute__(field.name)
|
|
@@ -274,7 +274,7 @@ class CTFParams:
|
|
|
274
274
|
static_count += 1
|
|
275
275
|
else:
|
|
276
276
|
dynamic_count += 1
|
|
277
|
-
|
|
277
|
+
dynamic_indices.append(ii)
|
|
278
278
|
|
|
279
279
|
assert len(args_list) == static_count + dynamic_count * template_count, f"Expected {static_count} + {dynamic_count} * {template_count} args, got {len(args_list)}"
|
|
280
280
|
|
|
@@ -283,7 +283,7 @@ class CTFParams:
|
|
|
283
283
|
result = []
|
|
284
284
|
|
|
285
285
|
for i in range(template_count):
|
|
286
|
-
for ii, dyn_ind in enumerate(
|
|
286
|
+
for ii, dyn_ind in enumerate(dynamic_indices):
|
|
287
287
|
static_values[dyn_ind] = dynamic_args_list[i * dynamic_count + ii]
|
|
288
288
|
|
|
289
289
|
result.append(CTFParams.from_arg_list(*static_values))
|
|
@@ -62,13 +62,18 @@ class CTFSet:
|
|
|
62
62
|
|
|
63
63
|
last_index = end_index - start_index
|
|
64
64
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
65
|
+
input_array[:ctf_batch_size] = 0
|
|
66
|
+
index_arrays[batch_id][:ctf_batch_size] = -self.get_length() * rotations_pixels_count
|
|
67
|
+
|
|
68
|
+
if last_index > 0:
|
|
69
|
+
for ii, field in enumerate(self.field_names):
|
|
70
|
+
input_array[:last_index] = self.combinations_array[start_index:end_index, ii]
|
|
71
|
+
cmd_graph.set_var(f"{field}_{batch_id}", np.tile(input_array[:ctf_batch_size], rotations_pixels_batch_size))
|
|
72
|
+
|
|
73
|
+
index_arrays[batch_id][0:last_index] = np.arange(start_index, end_index)
|
|
74
|
+
else:
|
|
75
|
+
for field in self.field_names:
|
|
76
|
+
cmd_graph.set_var(f"{field}_{batch_id}", np.tile(input_array[:ctf_batch_size], rotations_pixels_batch_size))
|
|
72
77
|
|
|
73
78
|
for j in range(1, rotations_pixels_batch_size):
|
|
74
79
|
index_arrays[batch_id][ctf_batch_size*j:ctf_batch_size*(j+1)] = index_arrays[batch_id][:ctf_batch_size] + self.get_length() * j
|
|
@@ -35,6 +35,7 @@ class Plan:
|
|
|
35
35
|
pixel_size: Optional[float] = None,
|
|
36
36
|
ctf_params: Optional[CTFParams] = None,
|
|
37
37
|
template_batch_size: int = 2,
|
|
38
|
+
output_radius: Optional[int] = None,
|
|
38
39
|
enable_rotation_weights: bool = False):
|
|
39
40
|
|
|
40
41
|
self.template_batch_size = template_batch_size
|
|
@@ -62,14 +63,17 @@ class Plan:
|
|
|
62
63
|
prev_graph = vd.set_global_graph(self.cmd_graph)
|
|
63
64
|
|
|
64
65
|
self.template_buffer = self.template.make_template(
|
|
65
|
-
self.cmd_graph.bind_var("rotation_matrix") if self.rotation is None else self.template.
|
|
66
|
+
self.cmd_graph.bind_var("rotation_matrix") if self.rotation is None else self.template.get_rotation_matrices(self.rotation),
|
|
66
67
|
self.cmd_graph.bind_var("pixel_size") if self.pixel_size is None else self.pixel_size,
|
|
67
68
|
template_count=self.template_batch_size,
|
|
68
69
|
cmd_graph=self.cmd_graph,
|
|
69
70
|
ctf_params=ctf_params
|
|
70
71
|
)
|
|
71
72
|
|
|
72
|
-
self.comparison_buffer = self.comparator.compare_template(
|
|
73
|
+
self.comparison_buffer = self.comparator.compare_template(
|
|
74
|
+
self.template_buffer,
|
|
75
|
+
output_radius=output_radius
|
|
76
|
+
)
|
|
73
77
|
|
|
74
78
|
self.results.check_comparison(
|
|
75
79
|
self.comparison_buffer,
|
|
@@ -103,7 +107,7 @@ class Plan:
|
|
|
103
107
|
|
|
104
108
|
self.cmd_graph.set_var(
|
|
105
109
|
"rotation_matrix",
|
|
106
|
-
self.template.
|
|
110
|
+
self.template.get_rotation_matrices(self._rotations_array[:full_batch_size, :])
|
|
107
111
|
)
|
|
108
112
|
|
|
109
113
|
if self.enable_rotation_weights:
|
|
@@ -121,9 +125,13 @@ class Plan:
|
|
|
121
125
|
rotation_offset = params.get_ctf_count() * params.get_pixel_size_count() * rotation_index
|
|
122
126
|
|
|
123
127
|
for k in range(self.template_batch_size):
|
|
128
|
+
index_array = self._index_arrays[k][:full_batch_size].copy()
|
|
129
|
+
valid_indices = index_array >= 0
|
|
130
|
+
index_array[valid_indices] += rotation_offset
|
|
131
|
+
index_array[~valid_indices] = -1
|
|
124
132
|
self.cmd_graph.set_var(
|
|
125
133
|
f"index{k}",
|
|
126
|
-
|
|
134
|
+
index_array
|
|
127
135
|
)
|
|
128
136
|
|
|
129
137
|
self.cmd_graph.submit_any(full_batch_size)
|
|
@@ -228,7 +236,8 @@ class Plan:
|
|
|
228
236
|
def run(self,
|
|
229
237
|
params: ParamSet,
|
|
230
238
|
enable_progress_bar: bool = False,
|
|
231
|
-
batch_size: int = 32
|
|
239
|
+
batch_size: int = 32,
|
|
240
|
+
compile_results: bool = True):
|
|
232
241
|
|
|
233
242
|
if params.rotations_weights is None and self.enable_rotation_weights:
|
|
234
243
|
raise ValueError("enable_rotation_weights is True, but no rotation weights provided in params.")
|
|
@@ -240,14 +249,15 @@ class Plan:
|
|
|
240
249
|
self._index_arrays = [np.ones(shape=(batch_size,), dtype=np.int32) * -1 for _ in range(self.template_batch_size)]
|
|
241
250
|
|
|
242
251
|
if params.get_ctf_count() == 1 and self.template_batch_size > 1:
|
|
243
|
-
print("Warning: Only one ctf parameter combination provided, but template_batch_size is greater than 1. This will result in
|
|
252
|
+
print("Warning: Only one ctf parameter combination provided, but template_batch_size is greater than 1. This will result in suboptimal performance.")
|
|
244
253
|
|
|
245
254
|
if enable_progress_bar:
|
|
246
255
|
self._status_bar = tqdm.tqdm(total=params.get_total_count(), dynamic_ncols=True)
|
|
247
256
|
|
|
248
257
|
self._iter_ctf_params(params, batch_size)
|
|
249
258
|
|
|
250
|
-
|
|
259
|
+
if compile_results:
|
|
260
|
+
self.results.compile_results(params.get_total_count())
|
|
251
261
|
|
|
252
262
|
if self._status_bar is not None:
|
|
253
263
|
self._status_bar.close()
|
|
@@ -5,9 +5,48 @@ import numpy as np
|
|
|
5
5
|
|
|
6
6
|
from ..plan import Results, ParamSet
|
|
7
7
|
|
|
8
|
+
@vd.map
|
|
9
|
+
def reduction_map_radius(buf: vc.Buff[vc.c64], output_radius: vc.Const[vc.i32]) -> vc.v3:
|
|
10
|
+
ind = vd.reduce.mapped_io_index()
|
|
11
|
+
|
|
12
|
+
coord3d = vc.ravel_index(ind, buf.shape).to_register()
|
|
13
|
+
|
|
14
|
+
result = vc.new_vec3_register(0, 0, 0)
|
|
15
|
+
|
|
16
|
+
within_y_range = vc.any(
|
|
17
|
+
coord3d.y < output_radius,
|
|
18
|
+
coord3d.y >= buf.shape.y - output_radius
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
within_z_range = vc.any(
|
|
22
|
+
coord3d.z < output_radius // 2,
|
|
23
|
+
vc.all(
|
|
24
|
+
coord3d.z >= buf.shape.z - output_radius // 2 - 1,
|
|
25
|
+
coord3d.z < buf.shape.z - 1
|
|
26
|
+
)
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
with vc.if_block(vc.all(within_y_range, within_z_range)):
|
|
30
|
+
val = buf[ind].to_register()
|
|
31
|
+
|
|
32
|
+
result.x = vc.max(val.real, val.imag)
|
|
33
|
+
result.y = val.real + val.imag
|
|
34
|
+
result.z = val.real * val.real + val.imag * val.imag
|
|
35
|
+
|
|
36
|
+
return result
|
|
37
|
+
|
|
38
|
+
@vd.reduce.reduce(0, axes=[1, 2], mapping_function=reduction_map_radius)
|
|
39
|
+
def calculate_sums_and_max_radius(a: vc.Const[vc.v3], b: vc.Const[vc.v3]) -> vc.v3:
|
|
40
|
+
return vc.new_vec3_register(
|
|
41
|
+
vc.max(a.x, b.x),
|
|
42
|
+
a.y + b.y,
|
|
43
|
+
a.z + b.z
|
|
44
|
+
)
|
|
45
|
+
|
|
8
46
|
@vd.map
|
|
9
47
|
def reduction_map(buf: vc.Buff[vc.c64]) -> vc.v3:
|
|
10
48
|
ind = vd.reduce.mapped_io_index()
|
|
49
|
+
|
|
11
50
|
result = vc.new_vec3_register(0, 0, 0)
|
|
12
51
|
|
|
13
52
|
with vc.if_block(ind % buf.shape.z < buf.shape.z - 1):
|
|
@@ -27,16 +66,19 @@ def calculate_sums_and_max(a: vc.Const[vc.v3], b: vc.Const[vc.v3]) -> vc.v3:
|
|
|
27
66
|
a.z + b.z
|
|
28
67
|
)
|
|
29
68
|
|
|
69
|
+
|
|
30
70
|
class ResultsParam(Results):
|
|
31
71
|
best_values_buffer: vd.Buffer
|
|
32
72
|
best_mip_values_buffer: vd.Buffer
|
|
33
73
|
compiled: bool
|
|
34
74
|
compiled_best_values: np.ndarray
|
|
35
75
|
compiled_best_mip_values: np.ndarray
|
|
76
|
+
output_radius: int
|
|
36
77
|
|
|
37
|
-
def __init__(self, batch_count: int,
|
|
38
|
-
self.best_values_buffer = vd.Buffer((batch_count,
|
|
39
|
-
self.best_mip_values_buffer = vd.Buffer((batch_count,
|
|
78
|
+
def __init__(self, batch_count: int, total_indices: int, output_radius: int = None) -> None:
|
|
79
|
+
self.best_values_buffer = vd.Buffer((batch_count, total_indices, ), vd.float32)
|
|
80
|
+
self.best_mip_values_buffer = vd.Buffer((batch_count, total_indices, ), vd.float32)
|
|
81
|
+
self.output_radius = output_radius
|
|
40
82
|
self.compiled = False
|
|
41
83
|
self.reset()
|
|
42
84
|
|
|
@@ -48,15 +90,15 @@ class ResultsParam(Results):
|
|
|
48
90
|
(np.ones(shape=self.best_mip_values_buffer.shape) * -1000000).astype(np.float32)
|
|
49
91
|
)
|
|
50
92
|
|
|
51
|
-
def check_comparison(self, comparison_buffer: vd.RFFTBuffer, rotation_weights: vc.Var[vc.f32], *
|
|
93
|
+
def check_comparison(self, comparison_buffer: vd.RFFTBuffer, rotation_weights: vc.Var[vc.f32], *indices: vc.Var[vc.i32]):
|
|
52
94
|
|
|
53
95
|
template_count = comparison_buffer.shape[0] // self.best_values_buffer.shape[0]
|
|
54
96
|
|
|
55
97
|
assert comparison_buffer.shape[0] % self.best_values_buffer.shape[0] == 0, \
|
|
56
98
|
"The comparison buffer shape must be divisible by the best values buffer shape."
|
|
57
99
|
|
|
58
|
-
assert len(
|
|
59
|
-
f"The number of
|
|
100
|
+
assert len(indices) == template_count, \
|
|
101
|
+
f"The number of indices ({len(indices)}) must match the number of templates"
|
|
60
102
|
|
|
61
103
|
pixel_count = comparison_buffer.shape[1] * (comparison_buffer.shape[2] - 1) * 2
|
|
62
104
|
|
|
@@ -69,14 +111,14 @@ class ResultsParam(Results):
|
|
|
69
111
|
vc.Buff[vc.f32], # mip_buff
|
|
70
112
|
vc.Buff[vc.v3], # reduced_values_buff
|
|
71
113
|
rotation_weights_type, # rotation_weights
|
|
72
|
-
] + [vc.Var[vc.i32]] * len(
|
|
114
|
+
] + [vc.Var[vc.i32]] * len(indices)
|
|
73
115
|
)
|
|
74
116
|
def update_best_value(
|
|
75
117
|
zscore_buff: vc.Buff[vc.f32],
|
|
76
118
|
mip_buff: vc.Buff[vc.f32],
|
|
77
119
|
reduced_values_buff: vc.Buff[vc.v3],
|
|
78
120
|
rot_weights: vc.Var[vc.f32],
|
|
79
|
-
*
|
|
121
|
+
*indices: vc.Var[vc.i32]):
|
|
80
122
|
_ = rot_weights
|
|
81
123
|
|
|
82
124
|
ind = vc.global_invocation_id().x.to_dtype(vc.i32).to_register()
|
|
@@ -84,12 +126,12 @@ class ResultsParam(Results):
|
|
|
84
126
|
reduced_values = vc.new_vec3_register()
|
|
85
127
|
|
|
86
128
|
for i in range(template_count):
|
|
87
|
-
output_index = ind * self.best_values_buffer.shape[1] +
|
|
129
|
+
output_index = ind * self.best_values_buffer.shape[1] + indices[i]
|
|
88
130
|
input_index = ind * template_count + i
|
|
89
131
|
|
|
90
132
|
reduced_values[:] = reduced_values_buff[input_index]
|
|
91
133
|
|
|
92
|
-
with vc.if_block(
|
|
134
|
+
with vc.if_block(indices[i] >= 0):
|
|
93
135
|
mean_val = (reduced_values.y / float(pixel_count)).to_register()
|
|
94
136
|
var_val = vc.max(reduced_values.z / float(pixel_count) - mean_val * mean_val, 0.0).to_register()
|
|
95
137
|
z_score = ((reduced_values.x - mean_val) / vc.sqrt(var_val + 1e-6)).to_register()
|
|
@@ -98,14 +140,17 @@ class ResultsParam(Results):
|
|
|
98
140
|
zscore_buff[output_index] = z_score
|
|
99
141
|
mip_buff[output_index] = reduced_values.x
|
|
100
142
|
|
|
101
|
-
|
|
143
|
+
if self.output_radius is not None:
|
|
144
|
+
reduced_values_buff = calculate_sums_and_max_radius(comparison_buffer, self.output_radius)
|
|
145
|
+
else:
|
|
146
|
+
reduced_values_buff = calculate_sums_and_max(comparison_buffer)
|
|
102
147
|
|
|
103
148
|
update_best_value(
|
|
104
149
|
self.best_values_buffer,
|
|
105
150
|
self.best_mip_values_buffer,
|
|
106
151
|
reduced_values_buff,
|
|
107
152
|
rotation_weights,
|
|
108
|
-
*
|
|
153
|
+
*indices
|
|
109
154
|
)
|
|
110
155
|
|
|
111
156
|
def compile_results(self, template_count: int):
|
|
@@ -64,6 +64,8 @@ class ResultsPixel(Results):
|
|
|
64
64
|
sum_cross: vd.Buffer # running mean
|
|
65
65
|
sum2_cross: vd.Buffer # running variance
|
|
66
66
|
|
|
67
|
+
output_radius: int
|
|
68
|
+
|
|
67
69
|
micrograph_count: int
|
|
68
70
|
|
|
69
71
|
compiled: bool
|
|
@@ -75,12 +77,14 @@ class ResultsPixel(Results):
|
|
|
75
77
|
|
|
76
78
|
templates_count: int
|
|
77
79
|
|
|
78
|
-
def __init__(self, shape: tuple) -> None:
|
|
80
|
+
def __init__(self, shape: tuple, output_radius: int = None) -> None:
|
|
79
81
|
assert len(shape) == 3, "Shape must be a 3D tuple (L, H, W)."
|
|
80
82
|
|
|
81
83
|
micrograph_count = int(shape[0])
|
|
82
|
-
width = int(shape[1])
|
|
83
|
-
height = int(shape[2])
|
|
84
|
+
width = int(shape[1]) if output_radius is None else int(output_radius * 2)
|
|
85
|
+
height = int(shape[2]) if output_radius is None else int(output_radius * 2)
|
|
86
|
+
|
|
87
|
+
self.output_radius = output_radius
|
|
84
88
|
|
|
85
89
|
self.micrograph_count = micrograph_count
|
|
86
90
|
|
|
@@ -106,7 +110,7 @@ class ResultsPixel(Results):
|
|
|
106
110
|
|
|
107
111
|
def compile_results(self, templates_count: int):
|
|
108
112
|
max_crosses = self.max_cross.read()
|
|
109
|
-
|
|
113
|
+
best_indices = self.best_index.read()
|
|
110
114
|
sum_crosses = self.sum_cross.read()
|
|
111
115
|
sum2_crosses = self.sum2_cross.read()
|
|
112
116
|
|
|
@@ -114,7 +118,7 @@ class ResultsPixel(Results):
|
|
|
114
118
|
|
|
115
119
|
for i in range(len(max_crosses)):
|
|
116
120
|
final_results[i][:, :, :, 0] = np.fft.ifftshift(max_crosses[i], axes=(1, 2))
|
|
117
|
-
final_results[i][:, :, :, 1] = np.fft.ifftshift(
|
|
121
|
+
final_results[i][:, :, :, 1] = np.fft.ifftshift(best_indices[i], axes=(1, 2))
|
|
118
122
|
|
|
119
123
|
true_final_result = final_results[0]
|
|
120
124
|
|
|
@@ -151,12 +155,9 @@ class ResultsPixel(Results):
|
|
|
151
155
|
assert self.compiled, "Results must be compiled before accessing the templates count."
|
|
152
156
|
return self.templates_count
|
|
153
157
|
|
|
154
|
-
def check_comparison(self, comparison_buffer: vd.
|
|
158
|
+
def check_comparison(self, comparison_buffer: vd.RFFTBuffer, rotation_weights: vc.Var[vc.f32], *indices: vc.Var[vc.i32]):
|
|
155
159
|
assert comparison_buffer.shape[0] % self.max_cross.shape[0] == 0, "Comparison buffer size must be a multiple of the number of templates."
|
|
156
160
|
|
|
157
|
-
template_count = comparison_buffer.shape[0] // self.max_cross.shape[0]
|
|
158
|
-
template_offset = self.max_cross.shape[1] * (self.max_cross.shape[2] + 2) * template_count
|
|
159
|
-
|
|
160
161
|
rotation_weights_type = vc.Const[vc.f32] if isinstance(rotation_weights, int) else vc.Var[vc.f32]
|
|
161
162
|
|
|
162
163
|
@vd.shader(
|
|
@@ -168,7 +169,7 @@ class ResultsPixel(Results):
|
|
|
168
169
|
vc.Buff[vc.v2], # sum2_cross
|
|
169
170
|
vc.Buff[vc.f32], # cross_correlation
|
|
170
171
|
rotation_weights_type, # rotation_weights
|
|
171
|
-
] + [vc.Var[vc.i32]] * len(
|
|
172
|
+
] + [vc.Var[vc.i32]] * len(indices))
|
|
172
173
|
def update_max(max_cross: vc.Buff[vc.f32],
|
|
173
174
|
best_index: vc.Buff[vc.i32],
|
|
174
175
|
sum_cross: vc.Buff[vc.v2],
|
|
@@ -176,16 +177,25 @@ class ResultsPixel(Results):
|
|
|
176
177
|
cross_correlation: vc.Buff[vc.f32],
|
|
177
178
|
rot_weights: vc.Var[vc.f32],
|
|
178
179
|
*index_values: vc.Var[vc.i32]):
|
|
179
|
-
ind = vc.global_invocation_id().x
|
|
180
|
+
ind = vc.global_invocation_id().x
|
|
181
|
+
|
|
182
|
+
coord_3 = vc.ravel_index(ind, self.max_cross.shape).to_register()
|
|
183
|
+
|
|
184
|
+
coord_2 = coord_3.swizzle("yz").to_dtype(vc.iv2).to_register()
|
|
185
|
+
coord_2 += vc.new_ivec2_register(self.max_cross.shape[1] // 2, self.max_cross.shape[2] // 2)
|
|
186
|
+
coord_2[:] = vc.mod(coord_2, vc.new_ivec2_register(self.max_cross.shape[1], self.max_cross.shape[2])).to_dtype(vc.iv2)
|
|
187
|
+
coord_2 -= vc.new_ivec2_register(self.max_cross.shape[1] // 2, self.max_cross.shape[2] // 2)
|
|
188
|
+
coord_2[:] = vc.mod(coord_2, vc.new_ivec2_register(comparison_buffer.real_shape[1], comparison_buffer.real_shape[2])).to_dtype(vc.iv2)
|
|
189
|
+
|
|
190
|
+
micrograph_inner_index = vc.unravel_index(coord_2, (comparison_buffer.real_shape[1], comparison_buffer.real_shape[2])).to_dtype(vc.i32).to_register()
|
|
180
191
|
|
|
181
|
-
|
|
182
|
-
micrograph_span_rfft = self.max_cross.shape[1] * (self.max_cross.shape[2] + 2)
|
|
192
|
+
cross_corr_index = (micrograph_inner_index + 2 * (micrograph_inner_index // (comparison_buffer.real_shape[2]))).to_register()
|
|
183
193
|
|
|
184
|
-
|
|
185
|
-
|
|
194
|
+
template_count = comparison_buffer.shape[0] // self.max_cross.shape[0]
|
|
195
|
+
template_offset = comparison_buffer.shape[1] * comparison_buffer.shape[2] * 2 * template_count
|
|
196
|
+
cross_corr_index[:] = cross_corr_index + coord_3.x.to_dtype(vc.i32) * template_offset
|
|
186
197
|
|
|
187
|
-
|
|
188
|
-
cross_corr_index[:] = cross_corr_index + micrograph_index * template_offset
|
|
198
|
+
micrograph_span_rfft = comparison_buffer.shape[1] * comparison_buffer.shape[2] * 2
|
|
189
199
|
|
|
190
200
|
best_mip_val, best_index_val, sum_cross_val, sum2_cross_val = accumulate(
|
|
191
201
|
template_count,
|
|
@@ -210,6 +220,6 @@ class ResultsPixel(Results):
|
|
|
210
220
|
self.sum2_cross,
|
|
211
221
|
comparison_buffer,
|
|
212
222
|
rotation_weights,
|
|
213
|
-
*
|
|
223
|
+
*indices
|
|
214
224
|
)
|
|
215
225
|
|
|
@@ -10,38 +10,35 @@ from ..plan import Template
|
|
|
10
10
|
from ..ctf.ctf import CTFParams, apply_ctfs_to_rfft_signals
|
|
11
11
|
|
|
12
12
|
def make_atomic_template_rotation_matrix(angles: np.ndarray) -> np.ndarray:
|
|
13
|
-
|
|
13
|
+
in_matrices = np.zeros(shape=(4, 4, angles.shape[0]), dtype=np.float32)
|
|
14
14
|
|
|
15
15
|
cos_phi = np.cos(np.deg2rad(angles[:, 0]))
|
|
16
16
|
sin_phi = np.sin(np.deg2rad(angles[:, 0]))
|
|
17
17
|
cos_theta = np.cos(np.deg2rad(angles[:, 1]))
|
|
18
18
|
sin_theta = np.sin(np.deg2rad(angles[:, 1]))
|
|
19
|
+
cos_psi = np.cos(np.deg2rad(angles[:, 2]))
|
|
20
|
+
sin_psi = np.sin(np.deg2rad(angles[:, 2]))
|
|
19
21
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
+
r00 = cos_phi * cos_theta * cos_psi - sin_phi * sin_psi
|
|
23
|
+
r10 = sin_phi * cos_theta * cos_psi + cos_phi * sin_psi
|
|
24
|
+
r20 = -sin_theta * cos_psi
|
|
22
25
|
|
|
23
|
-
|
|
24
|
-
|
|
26
|
+
r01 = -cos_phi * cos_theta * sin_psi - sin_phi * cos_psi
|
|
27
|
+
r11 = -sin_phi * cos_theta * sin_psi + cos_phi * cos_psi
|
|
28
|
+
r21 = sin_theta * sin_psi
|
|
25
29
|
|
|
26
|
-
|
|
30
|
+
# project_atoms stores atom coordinates internally as (-y, x, z) and writes
|
|
31
|
+
# image pixels as (row=-pos.x, col=pos.y). These rows convert the RELION /
|
|
32
|
+
# density.py Euler basis into that internal coordinate system.
|
|
33
|
+
in_matrices[0, 0] = r11
|
|
34
|
+
in_matrices[0, 1] = -r01
|
|
35
|
+
in_matrices[0, 2] = -r21
|
|
27
36
|
|
|
28
|
-
|
|
29
|
-
|
|
37
|
+
in_matrices[1, 0] = -r10
|
|
38
|
+
in_matrices[1, 1] = r00
|
|
39
|
+
in_matrices[1, 2] = r20
|
|
30
40
|
|
|
31
|
-
|
|
32
|
-
m01 = sin_psi_in_plane
|
|
33
|
-
m10 = -sin_psi_in_plane
|
|
34
|
-
m11 = cos_psi_in_plane
|
|
35
|
-
|
|
36
|
-
in_matricies[0, 0] = m00 * M00 + m10 * M01
|
|
37
|
-
in_matricies[0, 1] = m00 * M10 + m10 * M11
|
|
38
|
-
in_matricies[0, 2] = m00 * M20
|
|
39
|
-
|
|
40
|
-
in_matricies[1, 0] = m01 * M00 + m11 * M01
|
|
41
|
-
in_matricies[1, 1] = m01 * M10 + m11 * M11
|
|
42
|
-
in_matricies[1, 2] = m01 * M20
|
|
43
|
-
|
|
44
|
-
return in_matricies.T
|
|
41
|
+
return in_matrices.T
|
|
45
42
|
|
|
46
43
|
@vd.shader(exec_size=lambda args: args.buf.size)
|
|
47
44
|
def fill_buffer(buf: Buff[c64], val: Const[c64] = 0):
|
|
@@ -99,7 +96,7 @@ def apply_ctf_params(ctf_params: CTFParams,
|
|
|
99
96
|
apply_ctfs_to_rfft_signals(
|
|
100
97
|
value,
|
|
101
98
|
[value], # registers to apply the ctf to
|
|
102
|
-
[ctf_index], #
|
|
99
|
+
[ctf_index], # indices for which ctf params to use for each register
|
|
103
100
|
tid,
|
|
104
101
|
template_shape,
|
|
105
102
|
pixel_size,
|
|
@@ -348,8 +345,8 @@ class TemplateAtomic(Template):
|
|
|
348
345
|
|
|
349
346
|
return template_buffer
|
|
350
347
|
|
|
351
|
-
def
|
|
348
|
+
def _get_rotation_matrices(self, rotations: np.ndarray) -> np.ndarray:
|
|
352
349
|
return make_atomic_template_rotation_matrix(rotations).astype(np.float32)
|
|
353
350
|
|
|
354
351
|
def get_shape(self) -> tuple:
|
|
355
|
-
return self.shape
|
|
352
|
+
return self.shape
|
|
@@ -8,6 +8,21 @@ from ..ctf.ctf import CTFParams, apply_ctfs_to_rfft_signals
|
|
|
8
8
|
|
|
9
9
|
import numpy as np
|
|
10
10
|
|
|
11
|
+
def center_pad_density(density_array: np.ndarray, padding_factor: int) -> np.ndarray:
|
|
12
|
+
if padding_factor == 1:
|
|
13
|
+
return density_array
|
|
14
|
+
|
|
15
|
+
padded_shape = tuple(int(dim * padding_factor) for dim in density_array.shape)
|
|
16
|
+
padded = np.zeros(padded_shape, dtype=density_array.dtype)
|
|
17
|
+
|
|
18
|
+
slices = []
|
|
19
|
+
for input_dim, padded_dim in zip(density_array.shape, padded_shape):
|
|
20
|
+
start = (padded_dim - input_dim) // 2
|
|
21
|
+
slices.append(slice(start, start + input_dim))
|
|
22
|
+
|
|
23
|
+
padded[tuple(slices)] = density_array
|
|
24
|
+
return padded
|
|
25
|
+
|
|
11
26
|
@vd.shader(exec_size=lambda args: args.input_buff.size * 2)
|
|
12
27
|
def fftshift(output: vc.Buff[vc.f32], input_buff: vc.Buff[vc.f32]):
|
|
13
28
|
ind = vc.global_invocation_id().x.to_dtype(vd.int32).to_register()
|
|
@@ -90,9 +105,11 @@ def extract_fft_slices(
|
|
|
90
105
|
template_buffer: vd.RFFTBuffer,
|
|
91
106
|
sampler: vd.Sampler,
|
|
92
107
|
image_size: int,
|
|
108
|
+
density_image_size: int,
|
|
93
109
|
rotations: np.ndarray,
|
|
94
110
|
pixel_size: float,
|
|
95
111
|
base_pixel_size: float,
|
|
112
|
+
fourier_oversampling_factor: float,
|
|
96
113
|
ctf_params: CTFParams,
|
|
97
114
|
disable_ctf: bool,
|
|
98
115
|
cmd_graph: vd.CommandGraph
|
|
@@ -107,6 +124,7 @@ def extract_fft_slices(
|
|
|
107
124
|
vc.Buff[vc.c64], # output buffer
|
|
108
125
|
vc.Img3[vc.f32], # input image
|
|
109
126
|
vc.Const[vc.i32], # input image dim
|
|
127
|
+
vc.Const[vc.i32], # padded density image dim
|
|
110
128
|
rotation_type, # rotation matrix
|
|
111
129
|
pixel_size_type, # pixel size
|
|
112
130
|
*ctf_params.get_type_list(template_buffer.shape[0]) # ctf params
|
|
@@ -116,6 +134,7 @@ def extract_fft_slices(
|
|
|
116
134
|
buff: vc.Buff[vc.c64],
|
|
117
135
|
img: vc.Img3[vc.f32],
|
|
118
136
|
img_dim: vc.Const[vc.i32],
|
|
137
|
+
density_img_dim: vc.Const[vc.i32],
|
|
119
138
|
rotation,
|
|
120
139
|
pix_size,
|
|
121
140
|
*in_args):
|
|
@@ -131,18 +150,31 @@ def extract_fft_slices(
|
|
|
131
150
|
ipos.y[:] = vc.mod(ipos.y, img_dim).to_dtype(vc.i32)
|
|
132
151
|
ipos.y -= img_dim // 2
|
|
133
152
|
|
|
153
|
+
r_max = vc.new_int_register()
|
|
154
|
+
r_max[:] = img_dim // 2
|
|
155
|
+
|
|
156
|
+
r2 = vc.new_int_register()
|
|
157
|
+
r2[:] = ipos.x * ipos.x + ipos.y * ipos.y
|
|
158
|
+
|
|
159
|
+
with vc.if_block(r2 > r_max * r_max):
|
|
160
|
+
for i in range(template_buffer.shape[0]):
|
|
161
|
+
index = ind + i * template_buffer.shape[1] * template_buffer.shape[2]
|
|
162
|
+
buff[index].real = 0
|
|
163
|
+
buff[index].imag = 0
|
|
164
|
+
vc.return_statement()
|
|
165
|
+
|
|
134
166
|
my_pos = ipos.to_dtype(vc.v4).to_register()
|
|
135
167
|
|
|
136
168
|
# rotate the position to 3D template space
|
|
137
|
-
my_pos[:] = rotation * my_pos * (base_pixel_size / pix_size)
|
|
169
|
+
my_pos[:] = rotation * my_pos * (base_pixel_size / pix_size) * fourier_oversampling_factor
|
|
138
170
|
|
|
139
171
|
with vc.if_block(vc.any(
|
|
140
|
-
my_pos.x < -
|
|
141
|
-
my_pos.x > (
|
|
142
|
-
my_pos.y < -
|
|
143
|
-
my_pos.y > (
|
|
144
|
-
my_pos.z < -
|
|
145
|
-
my_pos.z > (
|
|
172
|
+
my_pos.x < -(density_img_dim // 2),
|
|
173
|
+
my_pos.x > (density_img_dim // 2 - 1),
|
|
174
|
+
my_pos.y < -(density_img_dim // 2),
|
|
175
|
+
my_pos.y > (density_img_dim // 2 - 1),
|
|
176
|
+
my_pos.z < -(density_img_dim // 2),
|
|
177
|
+
my_pos.z > (density_img_dim // 2 - 1))):
|
|
146
178
|
|
|
147
179
|
for i in range(template_buffer.shape[0]):
|
|
148
180
|
index = ind + i * template_buffer.shape[1] * template_buffer.shape[2]
|
|
@@ -180,6 +212,7 @@ def extract_fft_slices(
|
|
|
180
212
|
template_buffer,
|
|
181
213
|
sampler,
|
|
182
214
|
image_size,
|
|
215
|
+
density_image_size,
|
|
183
216
|
rotations,
|
|
184
217
|
pixel_size,
|
|
185
218
|
*ctf_params.get_args(cmd_graph, template_buffer.shape[0])
|
|
@@ -189,6 +222,7 @@ class TemplateDensity(Template):
|
|
|
189
222
|
shape: Tuple[int, int]
|
|
190
223
|
density_array: np.ndarray
|
|
191
224
|
density_pixel_size: float
|
|
225
|
+
density_padding_factor: int
|
|
192
226
|
density_image: vd.Image3D
|
|
193
227
|
disable_ctf: bool
|
|
194
228
|
|
|
@@ -196,15 +230,27 @@ class TemplateDensity(Template):
|
|
|
196
230
|
density_array: np.ndarray,
|
|
197
231
|
density_pixel_size: float,
|
|
198
232
|
transformed: bool = False,
|
|
199
|
-
disable_ctf: bool = False
|
|
233
|
+
disable_ctf: bool = False,
|
|
234
|
+
padding_factor: int = 1):
|
|
200
235
|
assert density_array.ndim == 3, "Density array must be a 3D array."
|
|
236
|
+
assert padding_factor >= 1, "Padding factor must be at least 1."
|
|
201
237
|
|
|
202
238
|
self.disable_ctf = disable_ctf
|
|
203
|
-
self.
|
|
239
|
+
self.density_padding_factor = int(padding_factor)
|
|
240
|
+
self.shape = (density_array.shape[0], density_array.shape[1])
|
|
204
241
|
self.density_pixel_size = density_pixel_size
|
|
205
242
|
|
|
243
|
+
if transformed:
|
|
244
|
+
assert self.density_padding_factor == 1, "Padding is only supported for real-space density arrays."
|
|
245
|
+
self.density_array = density_array.astype(np.complex64)
|
|
246
|
+
else:
|
|
247
|
+
self.density_array = center_pad_density(
|
|
248
|
+
density_array,
|
|
249
|
+
self.density_padding_factor
|
|
250
|
+
)
|
|
251
|
+
|
|
206
252
|
if not transformed:
|
|
207
|
-
self.density_array = np.fft.fftn(np.fft.fftshift(density_array)).astype(np.complex64)
|
|
253
|
+
self.density_array = np.fft.fftn(np.fft.fftshift(self.density_array)).astype(np.complex64)
|
|
208
254
|
|
|
209
255
|
self.density_array = self.density_array.astype(np.complex64)
|
|
210
256
|
|
|
@@ -215,8 +261,6 @@ class TemplateDensity(Template):
|
|
|
215
261
|
|
|
216
262
|
self.density_image.sample
|
|
217
263
|
|
|
218
|
-
self.shape = (self.density_array.shape[0], self.density_array.shape[1])
|
|
219
|
-
|
|
220
264
|
def _make_template(self,
|
|
221
265
|
rotations: vc.Var[vc.m4],
|
|
222
266
|
pixel_size: float,
|
|
@@ -232,10 +276,12 @@ class TemplateDensity(Template):
|
|
|
232
276
|
self.density_image.sample(
|
|
233
277
|
address_mode=vd.AddressMode.REPEAT,
|
|
234
278
|
),
|
|
279
|
+
self.shape[1],
|
|
235
280
|
self.density_array.shape[1],
|
|
236
281
|
rotations,
|
|
237
282
|
pixel_size,
|
|
238
283
|
self.density_pixel_size,
|
|
284
|
+
float(self.density_padding_factor),
|
|
239
285
|
ctf_params,
|
|
240
286
|
self.disable_ctf,
|
|
241
287
|
cmd_graph
|
|
@@ -250,8 +296,8 @@ class TemplateDensity(Template):
|
|
|
250
296
|
|
|
251
297
|
return template_buffer
|
|
252
298
|
|
|
253
|
-
def
|
|
299
|
+
def _get_rotation_matrices(self, rotations: np.ndarray) -> np.ndarray:
|
|
254
300
|
return make_density_template_rotation_matrix(rotations).astype(np.float32)
|
|
255
301
|
|
|
256
302
|
def get_shape(self) -> tuple:
|
|
257
|
-
return self.shape
|
|
303
|
+
return self.shape
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tm2d
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: A Python module for 2D template matching
|
|
5
|
+
Author-email: Shahar Sandhaus <shahar.sandhaus@berkeley.edu>
|
|
6
|
+
Project-URL: Homepage, https://github.com/sharhar/tm2d
|
|
7
|
+
Project-URL: Issues, https://github.com/sharhar/tm2d/issues
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
12
|
+
Requires-Python: >=3.9
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: setuptools>=59.0
|
|
16
|
+
Requires-Dist: numpy
|
|
17
|
+
Requires-Dist: vkdispatch==0.1.0
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# tm2d
|
|
21
|
+
|
|
22
|
+
`tm2d` is a Python package for GPU-accelerated 2D template matching. It contains the core algorithmic pieces: templates, CTF parameter handling, parameter grids, comparators, result containers, and execution plans.
|
|
23
|
+
|
|
24
|
+
Higher-level workflow code, file loading helpers, plotting utilities, and analysis scripts belong in `tm2d-utils` or downstream project code.
|
|
25
|
+
|
|
26
|
+
## Dependencies
|
|
27
|
+
|
|
28
|
+
Runtime dependencies are listed in `pyproject.toml`:
|
|
29
|
+
|
|
30
|
+
- Python >= 3.9
|
|
31
|
+
- `numpy`
|
|
32
|
+
- `vkdispatch==0.1.0`
|
|
33
|
+
- `setuptools>=59.0`
|
|
34
|
+
|
|
35
|
+
A working Vulkan/vkdispatch setup is required to run template matching.
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
From a local checkout:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
cd /path/to/tm2d
|
|
43
|
+
python -m pip install .
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
For development, install in editable mode:
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
cd /path/to/tm2d
|
|
50
|
+
python -m pip install -e .
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
To verify the installed package version:
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
python -m pip show tm2d
|
|
57
|
+
```
|
tm2d-0.2.1/PKG-INFO
DELETED
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: tm2d
|
|
3
|
-
Version: 0.2.1
|
|
4
|
-
Summary: A Python module for 2D template matching
|
|
5
|
-
Author-email: Shahar Sandhaus <shahar.sandhaus@berkeley.edu>
|
|
6
|
-
Project-URL: Homepage, https://github.com/sharhar/tm2d
|
|
7
|
-
Project-URL: Issues, https://github.com/sharhar/tm2d/issues
|
|
8
|
-
Classifier: Programming Language :: Python :: 3
|
|
9
|
-
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
-
Classifier: Operating System :: OS Independent
|
|
11
|
-
Classifier: Development Status :: 2 - Pre-Alpha
|
|
12
|
-
Requires-Python: >=3.9
|
|
13
|
-
Description-Content-Type: text/markdown
|
|
14
|
-
License-File: LICENSE
|
|
15
|
-
Requires-Dist: setuptools>=59.0
|
|
16
|
-
Requires-Dist: numpy
|
|
17
|
-
Requires-Dist: vkdispatch==0.1.0
|
|
18
|
-
Dynamic: license-file
|
|
19
|
-
|
|
20
|
-
# tm2d
|
|
21
|
-
A 2D template matcher written using the vkdispatch library.
|
|
22
|
-
|
|
23
|
-
## Installation
|
|
24
|
-
|
|
25
|
-
You can install the application using the command:
|
|
26
|
-
|
|
27
|
-
```
|
|
28
|
-
pip3 install .
|
|
29
|
-
```
|
|
30
|
-
|
|
31
|
-
## Imaging model
|
|
32
|
-
|
|
33
|
-
The projected potential $v_z(x,y)$ is modeled in one of two ways. It can be calculated from a slice through the Fourier transform of a density map (3D volume) or from a set of (3D) atomic coordinates. In the former case, different orientations are obtained by extracting different slices through the Fourier transform, while in the latter they are obtained by rotating the atomic coordinates, projecting along the $\hat{\mathbf{z}}$ (electron beam propagation) axis, and finally convolving the resulting 2D histogram of coordinates with a gaussian blur. The normalization of the gaussian kernel is set to approximately match a more rigorous calculation of the atomic projected potential in units of VÅ ([Kirkland 2020](https://doi.org/10.1007/978-3-030-33260-0)).
|
|
34
|
-
|
|
35
|
-
From the projected potential, the phase $\phi(x,y)=\sigma_ev_z(x,y)$ that is imparted to the exit wave function is calculated by scaling the projected potential by the interaction parameter $\sigma_e$, which for 300 kV accelerating voltage is approximately 0.652 mrad/VÅ. More generally, it is equal to $me\lambda_e/2\pi\hbar^2$, where $m$ is the electron mass, $e$ is the elementary charge, $\lambda_e$ is the wavelength of the electron, and $\hbar$ is the reduced Planck constant.
|
|
36
|
-
|
|
37
|
-
It is assumed that the projected potential $\phi$ is real and non-negative, with its 2D Fourier transform corresponding to the structure factor, denoted by $\Phi$:
|
|
38
|
-
```math
|
|
39
|
-
\Phi(s_x, s_y) = \mathcal{F}[\phi](s_x, s_y).
|
|
40
|
-
```
|
|
41
|
-
Here, the coordinates $(s_x, s_y)$ denote (non-angular) spatial frequency. A spatial frequency $\mathbf{s}=(s_x,s_y)$ intersects the back focal plane at the physical coordinate $(f_\mathrm{OL}\lambda_e s_x, f_\mathrm{OL}\lambda_e s_y)$, where $f_\mathrm{OL}$ is the effective focal length of the objective lens.
|
|
42
|
-
|
|
43
|
-
The calculation of an image from the projected potential requires a contrast transfer function (CTF), denoted $\mathcal{C}$. The key relationship that enables calculation of an image $\mathfrak{m}(x, y)$ from the structure factor $\Phi$ and the CTF $\mathcal{C}$ is
|
|
44
|
-
```math
|
|
45
|
-
\mathfrak{m}(x, y) \propto \mathcal{F}^{-1} [\Phi \cdot \mathcal{C}](x, y).
|
|
46
|
-
```
|
|
47
|
-
The CTF is assumed to have the form
|
|
48
|
-
```math
|
|
49
|
-
\mathcal{C}(\mathbf{s}) = E_\mathrm{TC}(\mathbf{s}) E_\mathrm{SC}(\mathbf{s}) E_\mathrm{JN}(\mathbf{s}) E_\mathrm{B}(\mathbf{s}) \sin[\chi(\mathbf{s}) - \chi(\mathbf{0}) - \kappa].
|
|
50
|
-
```
|
|
51
|
-
In the above, the terms $E_j$ are various envelope functions, $\chi$ is the wavefront aberration, and $\kappa$ is the amplitude contrast, taken to be a small constant such as 0.07.
|
|
52
|
-
|
|
53
|
-
The temporal coherence envelope function is given by
|
|
54
|
-
```math
|
|
55
|
-
E_\mathrm{TC}(\mathbf{s}) = \exp \left(-\frac{1}{2}\sigma_f^2\pi^2\lambda_e ^2|\mathbf{s}|^4\right)
|
|
56
|
-
```
|
|
57
|
-
where $\sigma_f$ is the "defocus spread," which is given by
|
|
58
|
-
```math
|
|
59
|
-
\sigma_f = C_c\sqrt{ \left(\epsilon \frac{\sigma_{V_0}}{V_0}\right)^2 + \left(\epsilon \frac{\sigma_{E_0}}{E_0}\right)^2 + \left(2\frac{\sigma_{I_0}}{I_0}\right)^2}
|
|
60
|
-
```
|
|
61
|
-
where $\Delta E_0 = 2\sqrt{2\ln 2}\sigma_{E_0}$ is the "energy spread" (typically quoted in FWHM, as opposed to the standard deviation $\sigma_{E_0}$), $C_c$ is the chromatic aberration coefficient, and $E_0$ is the electron energy. Relevant also are the objective lens current fluctuation $\sigma_{I_0}/I_0$ and accelerating voltage fluctation $\sigma_{V_0}/V_0$, which respectively have typical values of 0.1 ppm and 0.07 ppm. All the terms of the $\sigma_j$ denote standard deviations. The parameter $\epsilon$ is a relativistic correction factor given by
|
|
62
|
-
```math
|
|
63
|
-
\epsilon = \frac{1 + \frac{E_0}{511 \text{ keV}}}{1 + \frac{E_0}{2\cdot 511 \text{ keV}}}
|
|
64
|
-
```
|
|
65
|
-
which is approximately 1.227 at 300 keV.
|
|
66
|
-
|
|
67
|
-
The spatial coherence envelope is given by
|
|
68
|
-
```math
|
|
69
|
-
E_\mathrm{SC}(\mathbf{s}) = \exp\left[-2\sigma_\beta^2\pi^2|\mathbf{s}|^2\left( C_s\lambda_e ^2|\mathbf{s}|^2 - f_0 \right)^2 \right],
|
|
70
|
-
```
|
|
71
|
-
in which $C_s$ is the spherical aberration coefficient, $f_0$ is the mean defocus value, and $\sigma_\beta$ is the standard deviation of the distribution of beam angles (assumed to be gaussian, with a typical value of ~2.5 microradian) emerging from the gun.
|
|
72
|
-
|
|
73
|
-
The Johnson noise envelope is a gaussian envelope due to thermal magnetic field noise in the microscope column, with an associated variance $\sigma_\mathrm{J}^2$. This term is incorporated due to its potentially non-negligible values when using microscopes with relay optics ([Axelrod et al., Ultramicroscopy 2023](https://doi.org/10.1016/j.ultramic.2023.113730)). The functional form of this envelope is
|
|
74
|
-
```math
|
|
75
|
-
E_\mathrm{JN}(\mathbf{s}) = \exp \left( -2\pi^2\sigma_J^2 |\mathbf{s}|^2 \right).
|
|
76
|
-
```
|
|
77
|
-
|
|
78
|
-
A generic B-factor envelope is added for convenience. It has the functional form
|
|
79
|
-
```math
|
|
80
|
-
E_\mathrm{B}(\mathbf{s}) = \exp\left(-\frac{1}{4}B|\mathbf{s}|^2\right).
|
|
81
|
-
```
|
|
82
|
-
|
|
83
|
-
The wavefront aberration is given by
|
|
84
|
-
```math
|
|
85
|
-
\chi(\mathbf{s}) = \frac{2\pi}{\lambda_e}\left( \frac{1}{4}C_s\lambda_e^4|\mathbf{s}|^4 - \frac{1}{2}f_0\lambda_e^2|\mathbf{s}|^2 \right) + \eta(\mathbf{s}),
|
|
86
|
-
```
|
|
87
|
-
where $f_0>0$ denotes _underfocus_. The term $\eta(\mathbf{s})$ is the phase shift due to a phase plate. For instance, an ideal Zernike phase plate imparts the phase shift
|
|
88
|
-
```math
|
|
89
|
-
\eta(\mathbf{s}) = \frac{\pi}{2}\delta(\mathbf{s})
|
|
90
|
-
```
|
|
91
|
-
where $\delta(\mathbf{s})$ is the Dirac delta function.
|
tm2d-0.2.1/README.md
DELETED
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
# tm2d
|
|
2
|
-
A 2D template matcher written using the vkdispatch library.
|
|
3
|
-
|
|
4
|
-
## Installation
|
|
5
|
-
|
|
6
|
-
You can install the application using the command:
|
|
7
|
-
|
|
8
|
-
```
|
|
9
|
-
pip3 install .
|
|
10
|
-
```
|
|
11
|
-
|
|
12
|
-
## Imaging model
|
|
13
|
-
|
|
14
|
-
The projected potential $v_z(x,y)$ is modeled in one of two ways. It can be calculated from a slice through the Fourier transform of a density map (3D volume) or from a set of (3D) atomic coordinates. In the former case, different orientations are obtained by extracting different slices through the Fourier transform, while in the latter they are obtained by rotating the atomic coordinates, projecting along the $\hat{\mathbf{z}}$ (electron beam propagation) axis, and finally convolving the resulting 2D histogram of coordinates with a gaussian blur. The normalization of the gaussian kernel is set to approximately match a more rigorous calculation of the atomic projected potential in units of VÅ ([Kirkland 2020](https://doi.org/10.1007/978-3-030-33260-0)).
|
|
15
|
-
|
|
16
|
-
From the projected potential, the phase $\phi(x,y)=\sigma_ev_z(x,y)$ that is imparted to the exit wave function is calculated by scaling the projected potential by the interaction parameter $\sigma_e$, which for 300 kV accelerating voltage is approximately 0.652 mrad/VÅ. More generally, it is equal to $me\lambda_e/2\pi\hbar^2$, where $m$ is the electron mass, $e$ is the elementary charge, $\lambda_e$ is the wavelength of the electron, and $\hbar$ is the reduced Planck constant.
|
|
17
|
-
|
|
18
|
-
It is assumed that the projected potential $\phi$ is real and non-negative, with its 2D Fourier transform corresponding to the structure factor, denoted by $\Phi$:
|
|
19
|
-
```math
|
|
20
|
-
\Phi(s_x, s_y) = \mathcal{F}[\phi](s_x, s_y).
|
|
21
|
-
```
|
|
22
|
-
Here, the coordinates $(s_x, s_y)$ denote (non-angular) spatial frequency. A spatial frequency $\mathbf{s}=(s_x,s_y)$ intersects the back focal plane at the physical coordinate $(f_\mathrm{OL}\lambda_e s_x, f_\mathrm{OL}\lambda_e s_y)$, where $f_\mathrm{OL}$ is the effective focal length of the objective lens.
|
|
23
|
-
|
|
24
|
-
The calculation of an image from the projected potential requires a contrast transfer function (CTF), denoted $\mathcal{C}$. The key relationship that enables calculation of an image $\mathfrak{m}(x, y)$ from the structure factor $\Phi$ and the CTF $\mathcal{C}$ is
|
|
25
|
-
```math
|
|
26
|
-
\mathfrak{m}(x, y) \propto \mathcal{F}^{-1} [\Phi \cdot \mathcal{C}](x, y).
|
|
27
|
-
```
|
|
28
|
-
The CTF is assumed to have the form
|
|
29
|
-
```math
|
|
30
|
-
\mathcal{C}(\mathbf{s}) = E_\mathrm{TC}(\mathbf{s}) E_\mathrm{SC}(\mathbf{s}) E_\mathrm{JN}(\mathbf{s}) E_\mathrm{B}(\mathbf{s}) \sin[\chi(\mathbf{s}) - \chi(\mathbf{0}) - \kappa].
|
|
31
|
-
```
|
|
32
|
-
In the above, the terms $E_j$ are various envelope functions, $\chi$ is the wavefront aberration, and $\kappa$ is the amplitude contrast, taken to be a small constant such as 0.07.
|
|
33
|
-
|
|
34
|
-
The temporal coherence envelope function is given by
|
|
35
|
-
```math
|
|
36
|
-
E_\mathrm{TC}(\mathbf{s}) = \exp \left(-\frac{1}{2}\sigma_f^2\pi^2\lambda_e ^2|\mathbf{s}|^4\right)
|
|
37
|
-
```
|
|
38
|
-
where $\sigma_f$ is the "defocus spread," which is given by
|
|
39
|
-
```math
|
|
40
|
-
\sigma_f = C_c\sqrt{ \left(\epsilon \frac{\sigma_{V_0}}{V_0}\right)^2 + \left(\epsilon \frac{\sigma_{E_0}}{E_0}\right)^2 + \left(2\frac{\sigma_{I_0}}{I_0}\right)^2}
|
|
41
|
-
```
|
|
42
|
-
where $\Delta E_0 = 2\sqrt{2\ln 2}\sigma_{E_0}$ is the "energy spread" (typically quoted in FWHM, as opposed to the standard deviation $\sigma_{E_0}$), $C_c$ is the chromatic aberration coefficient, and $E_0$ is the electron energy. Relevant also are the objective lens current fluctuation $\sigma_{I_0}/I_0$ and accelerating voltage fluctation $\sigma_{V_0}/V_0$, which respectively have typical values of 0.1 ppm and 0.07 ppm. All the terms of the $\sigma_j$ denote standard deviations. The parameter $\epsilon$ is a relativistic correction factor given by
|
|
43
|
-
```math
|
|
44
|
-
\epsilon = \frac{1 + \frac{E_0}{511 \text{ keV}}}{1 + \frac{E_0}{2\cdot 511 \text{ keV}}}
|
|
45
|
-
```
|
|
46
|
-
which is approximately 1.227 at 300 keV.
|
|
47
|
-
|
|
48
|
-
The spatial coherence envelope is given by
|
|
49
|
-
```math
|
|
50
|
-
E_\mathrm{SC}(\mathbf{s}) = \exp\left[-2\sigma_\beta^2\pi^2|\mathbf{s}|^2\left( C_s\lambda_e ^2|\mathbf{s}|^2 - f_0 \right)^2 \right],
|
|
51
|
-
```
|
|
52
|
-
in which $C_s$ is the spherical aberration coefficient, $f_0$ is the mean defocus value, and $\sigma_\beta$ is the standard deviation of the distribution of beam angles (assumed to be gaussian, with a typical value of ~2.5 microradian) emerging from the gun.
|
|
53
|
-
|
|
54
|
-
The Johnson noise envelope is a gaussian envelope due to thermal magnetic field noise in the microscope column, with an associated variance $\sigma_\mathrm{J}^2$. This term is incorporated due to its potentially non-negligible values when using microscopes with relay optics ([Axelrod et al., Ultramicroscopy 2023](https://doi.org/10.1016/j.ultramic.2023.113730)). The functional form of this envelope is
|
|
55
|
-
```math
|
|
56
|
-
E_\mathrm{JN}(\mathbf{s}) = \exp \left( -2\pi^2\sigma_J^2 |\mathbf{s}|^2 \right).
|
|
57
|
-
```
|
|
58
|
-
|
|
59
|
-
A generic B-factor envelope is added for convenience. It has the functional form
|
|
60
|
-
```math
|
|
61
|
-
E_\mathrm{B}(\mathbf{s}) = \exp\left(-\frac{1}{4}B|\mathbf{s}|^2\right).
|
|
62
|
-
```
|
|
63
|
-
|
|
64
|
-
The wavefront aberration is given by
|
|
65
|
-
```math
|
|
66
|
-
\chi(\mathbf{s}) = \frac{2\pi}{\lambda_e}\left( \frac{1}{4}C_s\lambda_e^4|\mathbf{s}|^4 - \frac{1}{2}f_0\lambda_e^2|\mathbf{s}|^2 \right) + \eta(\mathbf{s}),
|
|
67
|
-
```
|
|
68
|
-
where $f_0>0$ denotes _underfocus_. The term $\eta(\mathbf{s})$ is the phase shift due to a phase plate. For instance, an ideal Zernike phase plate imparts the phase shift
|
|
69
|
-
```math
|
|
70
|
-
\eta(\mathbf{s}) = \frac{\pi}{2}\delta(\mathbf{s})
|
|
71
|
-
```
|
|
72
|
-
where $\delta(\mathbf{s})$ is the Dirac delta function.
|
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: tm2d
|
|
3
|
-
Version: 0.2.1
|
|
4
|
-
Summary: A Python module for 2D template matching
|
|
5
|
-
Author-email: Shahar Sandhaus <shahar.sandhaus@berkeley.edu>
|
|
6
|
-
Project-URL: Homepage, https://github.com/sharhar/tm2d
|
|
7
|
-
Project-URL: Issues, https://github.com/sharhar/tm2d/issues
|
|
8
|
-
Classifier: Programming Language :: Python :: 3
|
|
9
|
-
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
-
Classifier: Operating System :: OS Independent
|
|
11
|
-
Classifier: Development Status :: 2 - Pre-Alpha
|
|
12
|
-
Requires-Python: >=3.9
|
|
13
|
-
Description-Content-Type: text/markdown
|
|
14
|
-
License-File: LICENSE
|
|
15
|
-
Requires-Dist: setuptools>=59.0
|
|
16
|
-
Requires-Dist: numpy
|
|
17
|
-
Requires-Dist: vkdispatch==0.1.0
|
|
18
|
-
Dynamic: license-file
|
|
19
|
-
|
|
20
|
-
# tm2d
|
|
21
|
-
A 2D template matcher written using the vkdispatch library.
|
|
22
|
-
|
|
23
|
-
## Installation
|
|
24
|
-
|
|
25
|
-
You can install the application using the command:
|
|
26
|
-
|
|
27
|
-
```
|
|
28
|
-
pip3 install .
|
|
29
|
-
```
|
|
30
|
-
|
|
31
|
-
## Imaging model
|
|
32
|
-
|
|
33
|
-
The projected potential $v_z(x,y)$ is modeled in one of two ways. It can be calculated from a slice through the Fourier transform of a density map (3D volume) or from a set of (3D) atomic coordinates. In the former case, different orientations are obtained by extracting different slices through the Fourier transform, while in the latter they are obtained by rotating the atomic coordinates, projecting along the $\hat{\mathbf{z}}$ (electron beam propagation) axis, and finally convolving the resulting 2D histogram of coordinates with a gaussian blur. The normalization of the gaussian kernel is set to approximately match a more rigorous calculation of the atomic projected potential in units of VÅ ([Kirkland 2020](https://doi.org/10.1007/978-3-030-33260-0)).
|
|
34
|
-
|
|
35
|
-
From the projected potential, the phase $\phi(x,y)=\sigma_ev_z(x,y)$ that is imparted to the exit wave function is calculated by scaling the projected potential by the interaction parameter $\sigma_e$, which for 300 kV accelerating voltage is approximately 0.652 mrad/VÅ. More generally, it is equal to $me\lambda_e/2\pi\hbar^2$, where $m$ is the electron mass, $e$ is the elementary charge, $\lambda_e$ is the wavelength of the electron, and $\hbar$ is the reduced Planck constant.
|
|
36
|
-
|
|
37
|
-
It is assumed that the projected potential $\phi$ is real and non-negative, with its 2D Fourier transform corresponding to the structure factor, denoted by $\Phi$:
|
|
38
|
-
```math
|
|
39
|
-
\Phi(s_x, s_y) = \mathcal{F}[\phi](s_x, s_y).
|
|
40
|
-
```
|
|
41
|
-
Here, the coordinates $(s_x, s_y)$ denote (non-angular) spatial frequency. A spatial frequency $\mathbf{s}=(s_x,s_y)$ intersects the back focal plane at the physical coordinate $(f_\mathrm{OL}\lambda_e s_x, f_\mathrm{OL}\lambda_e s_y)$, where $f_\mathrm{OL}$ is the effective focal length of the objective lens.
|
|
42
|
-
|
|
43
|
-
The calculation of an image from the projected potential requires a contrast transfer function (CTF), denoted $\mathcal{C}$. The key relationship that enables calculation of an image $\mathfrak{m}(x, y)$ from the structure factor $\Phi$ and the CTF $\mathcal{C}$ is
|
|
44
|
-
```math
|
|
45
|
-
\mathfrak{m}(x, y) \propto \mathcal{F}^{-1} [\Phi \cdot \mathcal{C}](x, y).
|
|
46
|
-
```
|
|
47
|
-
The CTF is assumed to have the form
|
|
48
|
-
```math
|
|
49
|
-
\mathcal{C}(\mathbf{s}) = E_\mathrm{TC}(\mathbf{s}) E_\mathrm{SC}(\mathbf{s}) E_\mathrm{JN}(\mathbf{s}) E_\mathrm{B}(\mathbf{s}) \sin[\chi(\mathbf{s}) - \chi(\mathbf{0}) - \kappa].
|
|
50
|
-
```
|
|
51
|
-
In the above, the terms $E_j$ are various envelope functions, $\chi$ is the wavefront aberration, and $\kappa$ is the amplitude contrast, taken to be a small constant such as 0.07.
|
|
52
|
-
|
|
53
|
-
The temporal coherence envelope function is given by
|
|
54
|
-
```math
|
|
55
|
-
E_\mathrm{TC}(\mathbf{s}) = \exp \left(-\frac{1}{2}\sigma_f^2\pi^2\lambda_e ^2|\mathbf{s}|^4\right)
|
|
56
|
-
```
|
|
57
|
-
where $\sigma_f$ is the "defocus spread," which is given by
|
|
58
|
-
```math
|
|
59
|
-
\sigma_f = C_c\sqrt{ \left(\epsilon \frac{\sigma_{V_0}}{V_0}\right)^2 + \left(\epsilon \frac{\sigma_{E_0}}{E_0}\right)^2 + \left(2\frac{\sigma_{I_0}}{I_0}\right)^2}
|
|
60
|
-
```
|
|
61
|
-
where $\Delta E_0 = 2\sqrt{2\ln 2}\sigma_{E_0}$ is the "energy spread" (typically quoted in FWHM, as opposed to the standard deviation $\sigma_{E_0}$), $C_c$ is the chromatic aberration coefficient, and $E_0$ is the electron energy. Relevant also are the objective lens current fluctuation $\sigma_{I_0}/I_0$ and accelerating voltage fluctation $\sigma_{V_0}/V_0$, which respectively have typical values of 0.1 ppm and 0.07 ppm. All the terms of the $\sigma_j$ denote standard deviations. The parameter $\epsilon$ is a relativistic correction factor given by
|
|
62
|
-
```math
|
|
63
|
-
\epsilon = \frac{1 + \frac{E_0}{511 \text{ keV}}}{1 + \frac{E_0}{2\cdot 511 \text{ keV}}}
|
|
64
|
-
```
|
|
65
|
-
which is approximately 1.227 at 300 keV.
|
|
66
|
-
|
|
67
|
-
The spatial coherence envelope is given by
|
|
68
|
-
```math
|
|
69
|
-
E_\mathrm{SC}(\mathbf{s}) = \exp\left[-2\sigma_\beta^2\pi^2|\mathbf{s}|^2\left( C_s\lambda_e ^2|\mathbf{s}|^2 - f_0 \right)^2 \right],
|
|
70
|
-
```
|
|
71
|
-
in which $C_s$ is the spherical aberration coefficient, $f_0$ is the mean defocus value, and $\sigma_\beta$ is the standard deviation of the distribution of beam angles (assumed to be gaussian, with a typical value of ~2.5 microradian) emerging from the gun.
|
|
72
|
-
|
|
73
|
-
The Johnson noise envelope is a gaussian envelope due to thermal magnetic field noise in the microscope column, with an associated variance $\sigma_\mathrm{J}^2$. This term is incorporated due to its potentially non-negligible values when using microscopes with relay optics ([Axelrod et al., Ultramicroscopy 2023](https://doi.org/10.1016/j.ultramic.2023.113730)). The functional form of this envelope is
|
|
74
|
-
```math
|
|
75
|
-
E_\mathrm{JN}(\mathbf{s}) = \exp \left( -2\pi^2\sigma_J^2 |\mathbf{s}|^2 \right).
|
|
76
|
-
```
|
|
77
|
-
|
|
78
|
-
A generic B-factor envelope is added for convenience. It has the functional form
|
|
79
|
-
```math
|
|
80
|
-
E_\mathrm{B}(\mathbf{s}) = \exp\left(-\frac{1}{4}B|\mathbf{s}|^2\right).
|
|
81
|
-
```
|
|
82
|
-
|
|
83
|
-
The wavefront aberration is given by
|
|
84
|
-
```math
|
|
85
|
-
\chi(\mathbf{s}) = \frac{2\pi}{\lambda_e}\left( \frac{1}{4}C_s\lambda_e^4|\mathbf{s}|^4 - \frac{1}{2}f_0\lambda_e^2|\mathbf{s}|^2 \right) + \eta(\mathbf{s}),
|
|
86
|
-
```
|
|
87
|
-
where $f_0>0$ denotes _underfocus_. The term $\eta(\mathbf{s})$ is the phase shift due to a phase plate. For instance, an ideal Zernike phase plate imparts the phase shift
|
|
88
|
-
```math
|
|
89
|
-
\eta(\mathbf{s}) = \frac{\pi}{2}\delta(\mathbf{s})
|
|
90
|
-
```
|
|
91
|
-
where $\delta(\mathbf{s})$ is the Dirac delta function.
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|