tm2d 0.2.0__tar.gz → 0.2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tm2d
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: A Python module for 2D template matching
5
5
  Author-email: Shahar Sandhaus <shahar.sandhaus@berkeley.edu>
6
6
  Project-URL: Homepage, https://github.com/sharhar/tm2d
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "tm2d"
7
- version = "0.2.0"
7
+ version = "0.2.1"
8
8
  authors = [
9
9
  { name="Shahar Sandhaus", email="shahar.sandhaus@berkeley.edu" },
10
10
  ]
@@ -1,6 +1,6 @@
1
1
  from .ctf.ctf_params import CTFParams
2
- from .ctf.ctf_set import CTFSet
3
- from .ctf.ctf import ctf_filter
2
+ from .ctf.ctf_set import CTFSet, make_ctf_set
3
+ from .ctf.ctf import ctf_filter, apply_ctfs_to_rfft_signals
4
4
 
5
5
  from .templates.atomic import TemplateAtomic
6
6
  from .templates.density import TemplateDensity
@@ -10,12 +10,16 @@ from .comparators.cross_correlation import ComparatorCrossCorrelation
10
10
  from .results.per_pixel import ResultsPixel
11
11
  from .results.per_param import ResultsParam
12
12
 
13
- from .plan import Plan, Template, Comparator, Results, ParamSet
13
+ from .param_set import ParamSet, make_param_set
14
+
15
+ from .plan import Plan, Template, Comparator, Results
14
16
 
15
17
  __all__ = [
16
18
  "CTFParams",
17
19
  "CTFSet",
20
+ "make_ctf_set",
18
21
  "ctf_filter",
22
+ "apply_ctfs_to_rfft_signals"
19
23
  "TemplateAtomic",
20
24
  "TemplateDensity",
21
25
  "ComparatorCrossCorrelation",
@@ -26,4 +30,5 @@ __all__ = [
26
30
  "Comparator",
27
31
  "Results",
28
32
  "ParamSet",
33
+ "make_param_set",
29
34
  ]
@@ -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, *indicies: vc.Var[vc.i32]):
8
+ def check_comparison(self, comparison_buffer: vd.RFFTBuffer, rotation_weights: vc.Var[vc.f32], *indicies: vc.Var[vc.i32]):
9
9
  raise NotImplementedError("check_comparison must be implemented in a subclass.")
10
10
 
11
11
  def reset(self):
@@ -60,7 +60,6 @@ def _zernike_cart(m: int, n: int, r: vc.ShaderVariable, th: vc.ShaderVariable) -
60
60
  return R * vc.cos(m * th)
61
61
  return R * vc.sin(abs(m) * th)
62
62
 
63
-
64
63
  def phase_from_even_zernike(params: CTFParams, Sx_eff: vc.ShaderVariable, Sy_eff: vc.ShaderVariable) -> vc.ShaderVariable:
65
64
  psi = vc.new_float_register()
66
65
  r = vc.sqrt(Sx_eff * Sx_eff + Sy_eff * Sy_eff).to_register()
@@ -173,3 +172,36 @@ def ctf_filter(
173
172
  CTF.imag = 0.0
174
173
 
175
174
  return CTF
175
+
176
+ def apply_ctfs_to_rfft_signals(
177
+ input_value: vc.ShaderVariable,
178
+ registers: list[vc.ShaderVariable],
179
+ indicies: list[int],
180
+ ind: vc.ShaderVariable,
181
+ signal_shape: tuple[int, int, int],
182
+ pix_size: vc.ShaderVariable,
183
+ ctf_params: CTFParams,
184
+ args: list[vc.ShaderVariable],
185
+ ):
186
+ iind = ind.to_dtype(vc.i32)
187
+
188
+ ipos_2d = vc.new_ivec2_register()
189
+ ipos_2d.x = iind % signal_shape[2]
190
+ ipos_2d.y = ((iind // signal_shape[2]) + signal_shape[1] // 2) % signal_shape[1]
191
+
192
+ pos_2d = ipos_2d.to_dtype(vc.v2).to_register()
193
+ pos_2d.y = pos_2d.y - signal_shape[1] // 2
194
+
195
+
196
+
197
+ ctf_param_list = ctf_params.assemble_params_list_from_args(args, signal_shape[0])
198
+
199
+ for i in range(len(registers)):
200
+ #index = ind + i * signal_shape[1] * signal_shape[2]
201
+
202
+ registers[i][:] = vc.mult_complex(input_value, ctf_filter(
203
+ signal_shape[1:],
204
+ pos_2d,
205
+ ctf_param_list[indicies[i]],
206
+ pix_size
207
+ ))
@@ -1,7 +1,5 @@
1
1
  import dataclasses
2
2
  import numpy as np
3
- import itertools
4
- from .ctf_set import CTFSet
5
3
 
6
4
  import vkdispatch as vd
7
5
  import vkdispatch.codegen as vc
@@ -191,147 +189,6 @@ class CTFParams:
191
189
 
192
190
  return base_obj
193
191
 
194
- @classmethod
195
- def like_titan(cls,
196
- HT: float = 300e3,
197
- Cs: float = 4.8e7,
198
- Cc: float = 7.6e7,
199
- energy_spread_fwhm: float = 0.9,
200
- accel_voltage_std: float = 0.07e-6,
201
- OL_current_std: float = 0.1e-6,
202
- beam_semiangle: float = 2.5e-6,
203
- johnson_std: float = 0.37,
204
- B: float = 0,
205
- amp_contrast: float = 0.07,
206
- zernike: float = 0,
207
- lpp: float = 90,
208
- NA: float = 0.05,
209
- f_OL: float = 20e7,
210
- lpp_rot: float = 18,
211
- defocus: float = 10000,
212
- A_mag: float = 0,
213
- A_ang: float = 0,
214
- mag_matrix: np.ndarray = None,
215
- even_zernike: list[float] = None,
216
- odd_zernike: list[float] = None):
217
- return cls(
218
- HT=HT,
219
- Cs=Cs,
220
- Cc=Cc,
221
- energy_spread_fwhm=energy_spread_fwhm,
222
- accel_voltage_std=accel_voltage_std,
223
- OL_current_std=OL_current_std,
224
- beam_semiangle=beam_semiangle,
225
- johnson_std=johnson_std,
226
- B=B,
227
- amp_contrast=amp_contrast,
228
- zernike=zernike,
229
- lpp=lpp,
230
- NA=NA,
231
- f_OL=f_OL,
232
- lpp_rot=lpp_rot,
233
- defocus=defocus,
234
- A_mag=A_mag,
235
- A_ang=A_ang,
236
- mag_matrix=mag_matrix,
237
- even_zernike=even_zernike,
238
- odd_zernike=odd_zernike
239
- )
240
-
241
- @classmethod
242
- def like_theia(cls,
243
- HT: float = 300e3,
244
- Cs: float = 0,
245
- Cc: float = 5.1e7,
246
- energy_spread_fwhm: float = 0.3,
247
- accel_voltage_std: float = 0.07e-6,
248
- OL_current_std: float = 0.1e-6,
249
- beam_semiangle: float = 2.5e-6,
250
- johnson_std: float = 0.33,
251
- B: float = 0,
252
- amp_contrast: float = 0.07,
253
- zernike: float = 0,
254
- lpp: float = 90,
255
- NA: float = 0.05,
256
- f_OL: float = 14.1e7,
257
- lpp_rot: float = 0,
258
- defocus: float = 10000,
259
- A_mag: float = 0,
260
- A_ang: float = 0,
261
- mag_matrix: np.ndarray = None,
262
- even_zernike: list[float] = None,
263
- odd_zernike: list[float] = None):
264
- return cls(
265
- HT=HT,
266
- Cs=Cs,
267
- Cc=Cc,
268
- energy_spread_fwhm=energy_spread_fwhm,
269
- accel_voltage_std=accel_voltage_std,
270
- OL_current_std=OL_current_std,
271
- beam_semiangle=beam_semiangle,
272
- johnson_std=johnson_std,
273
- B=B,
274
- amp_contrast=amp_contrast,
275
- zernike=zernike,
276
- lpp=lpp,
277
- NA=NA,
278
- f_OL=f_OL,
279
- lpp_rot=lpp_rot,
280
- defocus=defocus,
281
- A_mag=A_mag,
282
- A_ang=A_ang,
283
- mag_matrix=mag_matrix,
284
- even_zernike=even_zernike,
285
- odd_zernike=odd_zernike
286
- )
287
-
288
- @classmethod
289
- def like_krios(cls,
290
- HT: float = 300e3,
291
- Cs: float = 2.7e7,
292
- Cc: float = 2.7e7,
293
- energy_spread_fwhm: float = 0.3,
294
- accel_voltage_std: float = 0.07e-6,
295
- OL_current_std: float = 0.1e-6,
296
- beam_semiangle: float = 2.5e-6,
297
- johnson_std: float = 0,
298
- B: float = 0,
299
- amp_contrast: float = 0.07,
300
- zernike: float = 0,
301
- lpp: float = 0,
302
- NA: float = 0.05,
303
- f_OL: float = 20e7,
304
- lpp_rot: float = 0,
305
- defocus: float = 10000,
306
- A_mag: float = 0,
307
- A_ang: float = 0,
308
- mag_matrix: np.ndarray = None,
309
- even_zernike: list[float] = None,
310
- odd_zernike: list[float] = None):
311
- return cls(
312
- HT=HT,
313
- Cs=Cs,
314
- Cc=Cc,
315
- energy_spread_fwhm=energy_spread_fwhm,
316
- accel_voltage_std=accel_voltage_std,
317
- OL_current_std=OL_current_std,
318
- beam_semiangle=beam_semiangle,
319
- johnson_std=johnson_std,
320
- B=B,
321
- amp_contrast=amp_contrast,
322
- zernike=zernike,
323
- lpp=lpp,
324
- NA=NA,
325
- f_OL=f_OL,
326
- lpp_rot=lpp_rot,
327
- defocus=defocus,
328
- A_mag=A_mag,
329
- A_ang=A_ang,
330
- mag_matrix=mag_matrix,
331
- even_zernike=even_zernike,
332
- odd_zernike=odd_zernike
333
- )
334
-
335
192
  def get_even_coeff(self):
336
193
  return (
337
194
  self.e_zern_0,
@@ -433,30 +290,6 @@ class CTFParams:
433
290
 
434
291
  return result
435
292
 
436
- def make_ctf_set(self, **values_dict) -> CTFSet:
437
- fields = dataclasses.fields(self)
438
-
439
- dynamic_fields = [field for field in fields if self.__getattribute__(field.name) is None]
440
-
441
- dynamic_field_names = {field.name for field in dynamic_fields}
442
- values_dict_keys = set(values_dict.keys())
443
- if dynamic_field_names != values_dict_keys:
444
- raise ValueError(f"Dynamic field names {dynamic_field_names} do not match keys in values_dict {values_dict_keys}")
445
-
446
- dynamic_values = [values_dict[field.name] for field in dynamic_fields]
447
-
448
- for dyn_val, field in zip(dynamic_values, dynamic_fields):
449
- assert dyn_val.ndim == 1, f"Dynamic value for field {field.name} must be a 1D array, got {dyn_val.ndim}D array."
450
-
451
- combinations = list(itertools.product(*dynamic_values))
452
- combinations_array = np.array(combinations)
453
-
454
- return CTFSet.from_compiled_params(
455
- combinations_array=combinations_array,
456
- field_names=[field.name for field in dynamic_fields],
457
- lengths=[len(values_dict[field.name]) for field in dynamic_fields]
458
- )
459
-
460
293
  def print(self):
461
294
  fields = dataclasses.fields(self)
462
295
  max_len = max(len(f.name) for f in fields)
@@ -1,25 +1,42 @@
1
1
  import dataclasses
2
2
  import numpy as np
3
3
  import vkdispatch as vd
4
+ import itertools
5
+
6
+ from .ctf_params import CTFParams
4
7
 
5
8
  @dataclasses.dataclass
6
9
  class CTFSet:
10
+ ctf_params: CTFParams
7
11
  combinations_array: np.ndarray
8
12
  field_names: list[str]
9
13
  lengths: list[int]
10
14
 
11
- def __init__(self):
12
- raise TypeError("CTFSet is not meant to be instantiated directly. Use CTFParams.make_ctf_set() instead.")
15
+ def __init__(self,
16
+ ctf_params: CTFParams,
17
+ **values_dict):
18
+
19
+ self.ctf_params = ctf_params
20
+
21
+ fields = dataclasses.fields(ctf_params)
22
+
23
+ dynamic_fields = [field for field in fields if ctf_params.__getattribute__(field.name) is None]
13
24
 
14
- @classmethod
15
- def from_compiled_params(cls, combinations_array: np.ndarray, field_names: list[str], lengths: list[int]):
16
- instance = cls.__new__(cls)
25
+ dynamic_field_names = {field.name for field in dynamic_fields}
26
+ values_dict_keys = set(values_dict.keys())
27
+ if dynamic_field_names != values_dict_keys:
28
+ raise ValueError(f"Dynamic field names {dynamic_field_names} do not match keys in values_dict {values_dict_keys}")
17
29
 
18
- instance.combinations_array = combinations_array
19
- instance.field_names = field_names
20
- instance.lengths = lengths
30
+ dynamic_values = [values_dict[field.name] for field in dynamic_fields]
21
31
 
22
- return instance
32
+ for dyn_val, field in zip(dynamic_values, dynamic_fields):
33
+ assert dyn_val.ndim == 1, f"Dynamic value for field {field.name} must be a 1D array, got {dyn_val.ndim}D array."
34
+
35
+ combinations = list(itertools.product(*dynamic_values))
36
+
37
+ self.combinations_array = np.array(combinations)
38
+ self.field_names = [field.name for field in dynamic_fields]
39
+ self.lengths = [len(values_dict[field.name]) for field in dynamic_fields]
23
40
 
24
41
  def get_length(self):
25
42
  return self.combinations_array.shape[0]
@@ -61,4 +78,7 @@ class CTFSet:
61
78
  for i, field_name in enumerate(self.field_names):
62
79
  return_dict[field_name] = self.combinations_array[index, i]
63
80
 
64
- return return_dict
81
+ return return_dict
82
+
83
+ def make_ctf_set(ctf_params: CTFParams, **values_dict) -> CTFSet:
84
+ return CTFSet(ctf_params, **values_dict)
@@ -1,29 +1,16 @@
1
1
  import numpy as np
2
+ import dataclasses
2
3
  from typing import Optional
3
4
 
4
5
  from .ctf.ctf_set import CTFSet
5
6
 
7
+ @dataclasses.dataclass
6
8
  class ParamSet:
7
- rotations: Optional[np.ndarray] = None
8
- pixel_sizes: Optional[np.ndarray] = None
9
+ rotations: Optional[np.ndarray]
10
+ rotations_weights: Optional[np.ndarray]
11
+ pixel_sizes: Optional[np.ndarray]
9
12
  ctf_set: CTFSet
10
13
 
11
- def __init__(self):
12
- raise TypeError("CTFSet is not meant to be instantiated directly. Use CTFParams.make_ctf_set() instead.")
13
-
14
- @classmethod
15
- def from_params(cls,
16
- rotations: np.ndarray,
17
- pixel_sizes: np.ndarray,
18
- ctf_set: CTFSet) -> 'ParamSet':
19
- instance = cls.__new__(cls)
20
-
21
- instance.rotations = rotations
22
- instance.pixel_sizes = pixel_sizes
23
- instance.ctf_set = ctf_set
24
-
25
- return instance
26
-
27
14
  def get_rotation_count(self) -> int:
28
15
  if self.rotations is None:
29
16
  return 1
@@ -132,4 +119,22 @@ class ParamSet:
132
119
  axis_names_dict["rotation"] = 1
133
120
  axis_names_dict["pixel_size"] = 2
134
121
 
135
- return values_tensor.reshape(tensor_shape), axis_names_dict
122
+ return values_tensor.reshape(tensor_shape), axis_names_dict
123
+
124
+ def make_param_set(ctf_set: CTFSet,
125
+ rotations: Optional[np.ndarray] = None,
126
+ rotations_weights: Optional[np.ndarray] = None,
127
+ pixel_sizes: Optional[np.ndarray] = None) -> 'ParamSet':
128
+
129
+ if rotations is not None and rotations_weights is not None:
130
+ if rotations.shape[0] != rotations_weights.shape[0]:
131
+ raise ValueError("Rotations and rotations_weights must have the same number of entries.")
132
+ elif rotations_weights is not None:
133
+ raise ValueError("rotations_weights cannot be provided without rotations.")
134
+
135
+ return ParamSet(
136
+ rotations=rotations,
137
+ rotations_weights=rotations_weights,
138
+ pixel_sizes=pixel_sizes,
139
+ ctf_set=ctf_set
140
+ )
@@ -18,9 +18,11 @@ class Plan:
18
18
  pixel_size: Optional[float]
19
19
  ctf_params: CTFParams
20
20
  template_batch_size: int
21
+ enable_rotation_weights: bool
21
22
 
22
23
  _status_bar: Optional[tqdm.tqdm]
23
24
  _rotations_array: Optional[np.ndarray]
25
+ _rotation_weight_array: Optional[np.ndarray]
24
26
  _pixel_sizes_array: Optional[np.ndarray]
25
27
  _ctf_index_arrays: Optional[np.ndarray]
26
28
  _index_arrays: Optional[np.ndarray]
@@ -32,7 +34,8 @@ class Plan:
32
34
  rotation: Optional[np.ndarray] = None,
33
35
  pixel_size: Optional[float] = None,
34
36
  ctf_params: Optional[CTFParams] = None,
35
- template_batch_size: int = 2):
37
+ template_batch_size: int = 2,
38
+ enable_rotation_weights: bool = False):
36
39
 
37
40
  self.template_batch_size = template_batch_size
38
41
 
@@ -45,9 +48,11 @@ class Plan:
45
48
  self.rotation = rotation
46
49
  self.pixel_size = pixel_size
47
50
  self.ctf_params = ctf_params
51
+ self.enable_rotation_weights = enable_rotation_weights
48
52
 
49
53
  self._status_bar = None
50
54
  self._rotations_array = None
55
+ self._rotation_weight_array = None
51
56
  self._pixel_sizes_array = None
52
57
  self._ctf_index_arrays = None
53
58
  self._index_arrays = None
@@ -68,6 +73,7 @@ class Plan:
68
73
 
69
74
  self.results.check_comparison(
70
75
  self.comparison_buffer,
76
+ self.cmd_graph.bind_var("rotation_weight") if self.enable_rotation_weights else 1,
71
77
  *[self.cmd_graph.bind_var(f"index{i}") for i in range(self.template_batch_size)]
72
78
  )
73
79
 
@@ -100,6 +106,18 @@ class Plan:
100
106
  self.template.get_rotation_matricies(self._rotations_array[:full_batch_size, :])
101
107
  )
102
108
 
109
+ if self.enable_rotation_weights:
110
+ self._rotation_weight_array[:actual_rotation_batch_size * repeats] = np.repeat(
111
+ params.rotations_weights[rotation_index:rotation_index + actual_rotation_batch_size],
112
+ repeats=repeats,
113
+ axis=0
114
+ )
115
+
116
+ self.cmd_graph.set_var(
117
+ "rotation_weight",
118
+ self._rotation_weight_array[:full_batch_size]
119
+ )
120
+
103
121
  rotation_offset = params.get_ctf_count() * params.get_pixel_size_count() * rotation_index
104
122
 
105
123
  for k in range(self.template_batch_size):
@@ -212,7 +230,11 @@ class Plan:
212
230
  enable_progress_bar: bool = False,
213
231
  batch_size: int = 32):
214
232
 
233
+ if params.rotations_weights is None and self.enable_rotation_weights:
234
+ raise ValueError("enable_rotation_weights is True, but no rotation weights provided in params.")
235
+
215
236
  self._rotations_array = np.zeros(shape=(batch_size, 3), dtype=np.float32)
237
+ self._rotation_weight_array = np.zeros(shape=(batch_size,), dtype=np.float32) if self.enable_rotation_weights else None
216
238
  self._pixel_sizes_array = np.zeros(shape=(batch_size,), dtype=np.float32)
217
239
  self._ctf_index_arrays = [np.ones(shape=(batch_size,), dtype=np.int32) * -1 for _ in range(self.template_batch_size)]
218
240
  self._index_arrays = [np.ones(shape=(batch_size,), dtype=np.int32) * -1 for _ in range(self.template_batch_size)]
@@ -232,29 +254,8 @@ class Plan:
232
254
  self._status_bar = None
233
255
 
234
256
  self._rotations_array = None
257
+ self._rotation_weight_array = None
235
258
  self._pixel_sizes_array = None
236
259
  self._ctf_index_arrays = None
237
260
  self._index_arrays = None
238
261
 
239
- def make_param_set(self,
240
- rotations: Optional[np.ndarray] = None,
241
- pixel_sizes: Optional[np.ndarray] = None,
242
- **kwargs) -> ParamSet:
243
- if rotations is None:
244
- assert self.rotation is not None, "If rotations are not provided, the rotation attribute must be set."
245
- else:
246
- assert self.rotation is None, "If rotations are provided, the rotation attribute must not be set."
247
-
248
- if pixel_sizes is None:
249
- assert self.pixel_size is not None, "If pixel sizes are not provided, the pixel_size attribute must be set."
250
- else:
251
- assert self.pixel_size is None, "If pixel sizes are provided, the pixel_size attribute must not be set."
252
-
253
- """
254
- Create a ParamSet with the given rotations, pixel sizes, and CTF parameters.
255
- """
256
- return ParamSet.from_params(
257
- rotations=rotations,
258
- pixel_sizes=pixel_sizes,
259
- ctf_set=self.ctf_params.make_ctf_set(**kwargs)
260
- )
@@ -48,7 +48,8 @@ class ResultsParam(Results):
48
48
  (np.ones(shape=self.best_mip_values_buffer.shape) * -1000000).astype(np.float32)
49
49
  )
50
50
 
51
- def check_comparison(self, comparison_buffer: vd.RFFTBuffer, *indicies: vc.Var[vc.i32]):
51
+ def check_comparison(self, comparison_buffer: vd.RFFTBuffer, rotation_weights: vc.Var[vc.f32], *indicies: vc.Var[vc.i32]):
52
+
52
53
  template_count = comparison_buffer.shape[0] // self.best_values_buffer.shape[0]
53
54
 
54
55
  assert comparison_buffer.shape[0] % self.best_values_buffer.shape[0] == 0, \
@@ -59,19 +60,25 @@ class ResultsParam(Results):
59
60
 
60
61
  pixel_count = comparison_buffer.shape[1] * (comparison_buffer.shape[2] - 1) * 2
61
62
 
63
+ rotation_weights_type = vc.Const[vc.f32] if isinstance(rotation_weights, int) else vc.Var[vc.f32]
64
+
62
65
  @vd.shader(
63
66
  exec_size=self.best_values_buffer.shape[0],
64
67
  arg_type_annotations=[
65
68
  vc.Buff[vc.f32], # zscore_buff
66
69
  vc.Buff[vc.f32], # mip_buff
67
70
  vc.Buff[vc.v3], # reduced_values_buff
71
+ rotation_weights_type, # rotation_weights
68
72
  ] + [vc.Var[vc.i32]] * len(indicies)
69
73
  )
70
74
  def update_best_value(
71
75
  zscore_buff: vc.Buff[vc.f32],
72
76
  mip_buff: vc.Buff[vc.f32],
73
77
  reduced_values_buff: vc.Buff[vc.v3],
78
+ rot_weights: vc.Var[vc.f32],
74
79
  *indicies: vc.Var[vc.i32]):
80
+ _ = rot_weights
81
+
75
82
  ind = vc.global_invocation_id().x.to_dtype(vc.i32).to_register()
76
83
 
77
84
  reduced_values = vc.new_vec3_register()
@@ -97,6 +104,7 @@ class ResultsParam(Results):
97
104
  self.best_values_buffer,
98
105
  self.best_mip_values_buffer,
99
106
  reduced_values_buff,
107
+ rotation_weights,
100
108
  *indicies
101
109
  )
102
110
 
@@ -30,6 +30,7 @@ def accumulate(
30
30
  cross_correlation: vc.Buff[vc.f32],
31
31
  cross_corr_index: vc.Var[vc.i32],
32
32
  micrograph_span_rfft: int,
33
+ rotation_weights: vc.Var[vc.f32],
33
34
  *index_values: vc.Var[vc.i32]):
34
35
 
35
36
  mip = vc.new_float_register(0, var_name="mip")
@@ -47,8 +48,8 @@ def accumulate(
47
48
  with vc.if_block(index_values[i] >= 0):
48
49
  mip[:] = cross_correlation[cross_corr_index]
49
50
 
50
- sum_cross[:] = double_precision_add_f32(sum_cross, mip)
51
- sum2_cross[:] = double_precision_add_f32(sum2_cross, mip * mip)
51
+ sum_cross[:] = double_precision_add_f32(sum_cross, mip * rotation_weights)
52
+ sum2_cross[:] = double_precision_add_f32(sum2_cross, mip * mip * rotation_weights)
52
53
 
53
54
  with vc.if_block(mip > best_mip):
54
55
  best_mip[:] = mip
@@ -150,12 +151,14 @@ class ResultsPixel(Results):
150
151
  assert self.compiled, "Results must be compiled before accessing the templates count."
151
152
  return self.templates_count
152
153
 
153
- def check_comparison(self, comparison_buffer: vd.Buffer, *indicies: vc.Var[vc.i32]):
154
+ def check_comparison(self, comparison_buffer: vd.Buffer, rotation_weights: vc.Var[vc.f32], *indicies: vc.Var[vc.i32]):
154
155
  assert comparison_buffer.shape[0] % self.max_cross.shape[0] == 0, "Comparison buffer size must be a multiple of the number of templates."
155
156
 
156
157
  template_count = comparison_buffer.shape[0] // self.max_cross.shape[0]
157
158
  template_offset = self.max_cross.shape[1] * (self.max_cross.shape[2] + 2) * template_count
158
159
 
160
+ rotation_weights_type = vc.Const[vc.f32] if isinstance(rotation_weights, int) else vc.Var[vc.f32]
161
+
159
162
  @vd.shader(
160
163
  exec_size=self.max_cross.size,
161
164
  arg_type_annotations=[
@@ -164,12 +167,14 @@ class ResultsPixel(Results):
164
167
  vc.Buff[vc.v2], # sum_cross
165
168
  vc.Buff[vc.v2], # sum2_cross
166
169
  vc.Buff[vc.f32], # cross_correlation
170
+ rotation_weights_type, # rotation_weights
167
171
  ] + [vc.Var[vc.i32]] * len(indicies))
168
172
  def update_max(max_cross: vc.Buff[vc.f32],
169
173
  best_index: vc.Buff[vc.i32],
170
174
  sum_cross: vc.Buff[vc.v2],
171
175
  sum2_cross: vc.Buff[vc.v2],
172
176
  cross_correlation: vc.Buff[vc.f32],
177
+ rot_weights: vc.Var[vc.f32],
173
178
  *index_values: vc.Var[vc.i32]):
174
179
  ind = vc.global_invocation_id().x.to_dtype(vc.i32).to_register()
175
180
 
@@ -187,6 +192,7 @@ class ResultsPixel(Results):
187
192
  cross_correlation,
188
193
  cross_corr_index,
189
194
  micrograph_span_rfft,
195
+ rot_weights,
190
196
  *index_values
191
197
  )
192
198
 
@@ -203,6 +209,7 @@ class ResultsPixel(Results):
203
209
  self.sum_cross,
204
210
  self.sum2_cross,
205
211
  comparison_buffer,
212
+ rotation_weights,
206
213
  *indicies
207
214
  )
208
215
 
@@ -7,7 +7,7 @@ from typing import Tuple
7
7
  import numpy as np
8
8
 
9
9
  from ..plan import Template
10
- from ..ctf.ctf import CTFParams, ctf_filter
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_matricies = np.zeros(shape=(4, 4, angles.shape[0]), dtype=np.float32)
@@ -96,24 +96,17 @@ def apply_ctf_params(ctf_params: CTFParams,
96
96
  if disable_ctf:
97
97
  return
98
98
 
99
- upos_2d = vc.new_uvec2_register()
100
- upos_2d.x = tid % template_shape[2]
101
- upos_2d.y = ((tid // template_shape[2]) + template_shape[1] // 2) % template_shape[1]
102
-
103
- pos_2d = upos_2d.to_dtype(vc.v2).to_register()
104
- pos_2d.y = pos_2d.y - template_shape[1] // 2
105
-
106
- ctf_param_list = ctf_params.assemble_params_list_from_args(in_args, template_shape[0])
107
-
108
- ctf = ctf_filter(
109
- template_shape[1:],
110
- pos_2d,
111
- ctf_param_list[ctf_index],
112
- pixel_size
99
+ apply_ctfs_to_rfft_signals(
100
+ value,
101
+ [value], # registers to apply the ctf to
102
+ [ctf_index], # indicies for which ctf params to use for each register
103
+ tid,
104
+ template_shape,
105
+ pixel_size,
106
+ ctf_params,
107
+ in_args
113
108
  )
114
109
 
115
- value[:] = vc.mult_complex(value, ctf)
116
-
117
110
  e_mass = 0.511e6 # electron mass [eV/c^2]
118
111
  e_compton = 2.42631023867e-2 # compton wavelength [A]
119
112
  e_charge_SI = 1.602176634e-19 # elementary charge [C]
@@ -198,6 +191,23 @@ def map_int_to_float(buff: Buff[f32], sigma_e: vc.Const[vc.f32]):
198
191
  read_op.register.real = value
199
192
  read_op.register.imag = 0.0
200
193
 
194
+ @vd.shader(exec_size=lambda args: args.buff.shape[0] * args.buff.shape[1] * (args.buff.shape[2] * 2 - 2))
195
+ def reinterpret_int_bits_to_float(buff: Buff[f32]):
196
+ tid = vc.global_invocation_id().x.to_dtype(vd.int32).to_register()
197
+
198
+ width = (buff.shape[2] * 2 - 2).to_dtype(vd.int32).to_register()
199
+ row_stride = (buff.shape[2] * 2).to_dtype(vd.int32).to_register()
200
+ plane_stride = (buff.shape[1] * row_stride).to_dtype(vd.int32).to_register()
201
+
202
+ y = (tid % width).to_register()
203
+ row_linear = (tid // width).to_register()
204
+ x = (row_linear % buff.shape[1].to_dtype(vd.int32)).to_register()
205
+ k = (row_linear // buff.shape[1].to_dtype(vd.int32)).to_register()
206
+
207
+ # project_atoms writes counts into the real-layout rows of RFFT storage.
208
+ index = (k * plane_stride + x * row_stride + y).to_register()
209
+ buff[index] = vc.float_bits_to_int(buff[index]).to_dtype(vd.float32)
210
+
201
211
  def fused_strided_convolution(
202
212
  template_buffer: vd.Buffer,
203
213
  pixel_size,
@@ -241,7 +251,7 @@ def fused_strided_convolution(
241
251
  )
242
252
  )
243
253
 
244
- def seperate_strided_convolution(template_buffer: vd.Buffer, pixel_size, ctf_params: CTFParams, template_count, ctf_args, disable_ctf):
254
+ def separate_strided_convolution(template_buffer: vd.Buffer, pixel_size, ctf_params: CTFParams, template_count, ctf_args, disable_ctf):
245
255
  vd.fft.fft(template_buffer, axis=1, buffer_shape=(1, *template_buffer.shape[1:]))
246
256
 
247
257
  @vd.shader(
@@ -272,7 +282,7 @@ def seperate_strided_convolution(template_buffer: vd.Buffer, pixel_size, ctf_par
272
282
 
273
283
  convolution_shader(template_buffer, pixel_size, *ctf_args)
274
284
 
275
- vd.fft.ifft(template_buffer, axis=1)
285
+ vd.fft.ifft(template_buffer, axis=1, normalize=False)
276
286
 
277
287
  class TemplateAtomic(Template):
278
288
  shape: Tuple[int, int]
@@ -281,19 +291,22 @@ class TemplateAtomic(Template):
281
291
  disable_ctf: bool
282
292
  disable_sigma_e: bool
283
293
  fuse_ctf_convolution: bool
294
+ count_atoms: bool
284
295
 
285
296
  def __init__(self,
286
297
  shape: Tuple[int, int],
287
298
  atomic_coords: np.ndarray,
288
- disable_ctf: bool = False,
289
- disable_sigma_e: bool = False,
290
- fuse_ctf_convolution: bool = False):
299
+ disable_ctf: bool = False, # True disables ctf (still applies gaussian filter)
300
+ disable_sigma_e: bool = False, # True skips scaling by sigma_e, keeping [V] instead of [rad]
301
+ fuse_ctf_convolution: bool = False, # True fuses convolution
302
+ count_atoms: bool = False): # True ONLY counts atoms
291
303
  assert len(shape) == 2, "Shape must be a tuple of two integers (height, width)."
292
304
  assert atomic_coords.ndim == 2 and atomic_coords.shape[1] == 3, "Atomic coordinates must be a 2D array with shape (N, 3)."
293
305
 
294
306
  self.disable_ctf = disable_ctf
295
307
  self.disable_sigma_e = disable_sigma_e
296
308
  self.fuse_ctf_convolution = fuse_ctf_convolution
309
+ self.count_atoms = count_atoms
297
310
 
298
311
  self.shape = (shape[0], shape[1])
299
312
  self.atomic_coords = atomic_coords.astype(np.float32)
@@ -311,6 +324,10 @@ class TemplateAtomic(Template):
311
324
  fill_buffer(template_buffer)
312
325
  project_atoms(template_buffer, self.atomic_coords_buffer, rotations, pixel_size)
313
326
 
327
+ if self.count_atoms:
328
+ reinterpret_int_bits_to_float(template_buffer)
329
+ return template_buffer
330
+
314
331
  vd.fft.fft(
315
332
  template_buffer,
316
333
  template_buffer,
@@ -325,7 +342,7 @@ class TemplateAtomic(Template):
325
342
  if self.fuse_ctf_convolution:
326
343
  fused_strided_convolution(template_buffer, pixel_size, ctf_params, template_count, ctf_args, self.disable_ctf)
327
344
  else:
328
- seperate_strided_convolution(template_buffer, pixel_size, ctf_params, template_count, ctf_args, self.disable_ctf)
345
+ separate_strided_convolution(template_buffer, pixel_size, ctf_params, template_count, ctf_args, self.disable_ctf)
329
346
 
330
347
  vd.fft.irfft(template_buffer, normalize=False)
331
348
 
@@ -4,7 +4,7 @@ import vkdispatch.codegen as vc
4
4
  from typing import Tuple
5
5
 
6
6
  from ..plan import Template
7
- from ..ctf.ctf import CTFParams, ctf_filter
7
+ from ..ctf.ctf import CTFParams, apply_ctfs_to_rfft_signals
8
8
 
9
9
  import numpy as np
10
10
 
@@ -152,26 +152,29 @@ def extract_fft_slices(
152
152
 
153
153
  value = img.sample(my_pos.swizzle("xyz")).swizzle("xy").to_dtype(vc.c64).to_register()
154
154
 
155
- ipos_2d = vc.new_ivec2_register()
156
- ipos_2d.x = ind % template_buffer.shape[2]
157
- ipos_2d.y = ((ind // template_buffer.shape[2]) + template_buffer.shape[1] // 2) % template_buffer.shape[1]
155
+ if disable_ctf:
156
+ for i in range(template_buffer.shape[0]):
157
+ index = ind + i * template_buffer.shape[1] * template_buffer.shape[2]
158
+ buff[index] = value
158
159
 
159
- pos_2d = ipos_2d.to_dtype(vc.v2).to_register()
160
- pos_2d.y = pos_2d.y - template_buffer.shape[1] // 2
160
+ return
161
161
 
162
- ctf_param_list = ctf_params.assemble_params_list_from_args(in_args, template_buffer.shape[0])
162
+ template_area = template_buffer.shape[1] * template_buffer.shape[2]
163
163
 
164
- for i in range(template_buffer.shape[0]):
165
- index = ind + i * template_buffer.shape[1] * template_buffer.shape[2]
166
- if disable_ctf:
167
- buff[index] = value
168
- else:
169
- buff[index] = vc.mult_complex(value, ctf_filter(
170
- template_buffer.shape[1:],
171
- pos_2d,
172
- ctf_param_list[i],
173
- pix_size
174
- ))
164
+ out_values = [
165
+ buff[ind + i * template_area] for i in range(template_buffer.shape[0])
166
+ ]
167
+
168
+ apply_ctfs_to_rfft_signals(
169
+ value,
170
+ out_values,
171
+ [i for i in range(template_buffer.shape[0])],
172
+ ind,
173
+ template_buffer.shape,
174
+ pix_size,
175
+ ctf_params,
176
+ in_args
177
+ )
175
178
 
176
179
  extract_fft_slices_shader(
177
180
  template_buffer,
@@ -239,7 +242,7 @@ class TemplateDensity(Template):
239
242
  )
240
243
 
241
244
 
242
- vd.fft.irfft2(template_buffer_temp, normalize=False)
245
+ vd.fft.irfft2(template_buffer_temp, normalize=True)
243
246
 
244
247
  template_buffer = vd.RFFTBuffer((template_count, *self.shape))
245
248
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tm2d
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: A Python module for 2D template matching
5
5
  Author-email: Shahar Sandhaus <shahar.sandhaus@berkeley.edu>
6
6
  Project-URL: Homepage, https://github.com/sharhar/tm2d
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes