pytme 0.3b0__cp311-cp311-macosx_15_0_arm64.whl → 0.3b0.post1__cp311-cp311-macosx_15_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. {pytme-0.3b0.data → pytme-0.3b0.post1.data}/scripts/estimate_memory_usage.py +1 -5
  2. {pytme-0.3b0.data → pytme-0.3b0.post1.data}/scripts/match_template.py +163 -201
  3. {pytme-0.3b0.data → pytme-0.3b0.post1.data}/scripts/postprocess.py +48 -39
  4. {pytme-0.3b0.data → pytme-0.3b0.post1.data}/scripts/preprocess.py +10 -23
  5. {pytme-0.3b0.data → pytme-0.3b0.post1.data}/scripts/preprocessor_gui.py +3 -4
  6. pytme-0.3b0.post1.data/scripts/pytme_runner.py +769 -0
  7. {pytme-0.3b0.dist-info → pytme-0.3b0.post1.dist-info}/METADATA +14 -14
  8. {pytme-0.3b0.dist-info → pytme-0.3b0.post1.dist-info}/RECORD +54 -50
  9. {pytme-0.3b0.dist-info → pytme-0.3b0.post1.dist-info}/entry_points.txt +1 -0
  10. pytme-0.3b0.post1.dist-info/licenses/LICENSE +339 -0
  11. scripts/estimate_memory_usage.py +1 -5
  12. scripts/eval.py +93 -0
  13. scripts/match_template.py +163 -201
  14. scripts/match_template_filters.py +1200 -0
  15. scripts/postprocess.py +48 -39
  16. scripts/preprocess.py +10 -23
  17. scripts/preprocessor_gui.py +3 -4
  18. scripts/pytme_runner.py +769 -0
  19. scripts/refine_matches.py +0 -1
  20. tests/preprocessing/test_frequency_filters.py +19 -10
  21. tests/test_analyzer.py +122 -122
  22. tests/test_backends.py +1 -0
  23. tests/test_matching_cli.py +30 -30
  24. tests/test_matching_data.py +5 -5
  25. tests/test_matching_utils.py +1 -1
  26. tme/__version__.py +1 -1
  27. tme/analyzer/__init__.py +1 -1
  28. tme/analyzer/_utils.py +1 -4
  29. tme/analyzer/aggregation.py +15 -6
  30. tme/analyzer/base.py +25 -36
  31. tme/analyzer/peaks.py +39 -113
  32. tme/analyzer/proxy.py +1 -0
  33. tme/backends/_jax_utils.py +16 -15
  34. tme/backends/cupy_backend.py +9 -13
  35. tme/backends/jax_backend.py +19 -16
  36. tme/backends/npfftw_backend.py +27 -25
  37. tme/backends/pytorch_backend.py +4 -0
  38. tme/density.py +5 -4
  39. tme/filters/__init__.py +2 -2
  40. tme/filters/_utils.py +32 -7
  41. tme/filters/bandpass.py +225 -186
  42. tme/filters/ctf.py +117 -67
  43. tme/filters/reconstruction.py +38 -9
  44. tme/filters/wedge.py +88 -105
  45. tme/filters/whitening.py +1 -6
  46. tme/matching_data.py +24 -36
  47. tme/matching_exhaustive.py +14 -11
  48. tme/matching_scores.py +21 -12
  49. tme/matching_utils.py +13 -6
  50. tme/orientations.py +13 -3
  51. tme/parser.py +109 -29
  52. tme/preprocessor.py +2 -2
  53. pytme-0.3b0.dist-info/licenses/LICENSE +0 -153
  54. {pytme-0.3b0.dist-info → pytme-0.3b0.post1.dist-info}/WHEEL +0 -0
  55. {pytme-0.3b0.dist-info → pytme-0.3b0.post1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1200 @@
1
+ #!python3
2
+ """ CLI interface for basic pyTME template matching functions.
3
+
4
+ Copyright (c) 2023 European Molecular Biology Laboratory
5
+
6
+ Author: Valentin Maurer <valentin.maurer@embl-hamburg.de>
7
+ """
8
+ import os
9
+ import argparse
10
+ import warnings
11
+ from sys import exit
12
+ from time import time
13
+ from typing import Tuple
14
+ from copy import deepcopy
15
+ from os.path import abspath, exists
16
+
17
+ import numpy as np
18
+
19
+ from tme import Density, __version__
20
+ from tme.matching_utils import (
21
+ get_rotation_matrices,
22
+ get_rotations_around_vector,
23
+ compute_parallelization_schedule,
24
+ scramble_phases,
25
+ generate_tempfile_name,
26
+ write_pickle,
27
+ )
28
+ from tme.matching_exhaustive import scan_subsets, MATCHING_EXHAUSTIVE_REGISTER
29
+ from tme.matching_data import MatchingData
30
+ from tme.analyzer import (
31
+ MaxScoreOverRotations,
32
+ PeakCallerMaximumFilter,
33
+ )
34
+ from tme.backends import backend as be
35
+ from tme.preprocessing import Compose
36
+ from tme.scoring import flc_scoring2
37
+
38
+ def get_func_fullname(func) -> str:
39
+ """Returns the full name of the given function, including its module."""
40
+ return f"<function '{func.__module__}.{func.__name__}'>"
41
+
42
+
43
+ def print_block(name: str, data: dict, label_width=20) -> None:
44
+ """Prints a formatted block of information."""
45
+ print(f"\n> {name}")
46
+ for key, value in data.items():
47
+ formatted_value = str(value)
48
+ print(f" - {key + ':':<{label_width}} {formatted_value}")
49
+
50
+
51
+ def print_entry() -> None:
52
+ width = 80
53
+ text = f" pytme v{__version__} "
54
+ padding_total = width - len(text) - 2
55
+ padding_left = padding_total // 2
56
+ padding_right = padding_total - padding_left
57
+
58
+ print("*" * width)
59
+ print(f"*{ ' ' * padding_left }{text}{ ' ' * padding_right }*")
60
+ print("*" * width)
61
+
62
+
63
+ def check_positive(value):
64
+ ivalue = float(value)
65
+ if ivalue <= 0:
66
+ raise argparse.ArgumentTypeError("%s is an invalid positive float." % value)
67
+ return ivalue
68
+
69
+
70
+ def load_and_validate_mask(mask_target: "Density", mask_path: str, **kwargs):
71
+ """
72
+ Loadsa mask in CCP4/MRC format and assess whether the sampling_rate
73
+ and shape matches its target.
74
+
75
+ Parameters
76
+ ----------
77
+ mask_target : Density
78
+ Object the mask should be applied to
79
+ mask_path : str
80
+ Path to the mask in CCP4/MRC format.
81
+ kwargs : dict, optional
82
+ Keyword arguments passed to :py:meth:`tme.density.Density.from_file`.
83
+ Raise
84
+ -----
85
+ ValueError
86
+ If shape or sampling rate do not match between mask_target and mask
87
+
88
+ Returns
89
+ -------
90
+ Density
91
+ A density instance if the mask was validated and loaded otherwise None
92
+ """
93
+ mask = mask_path
94
+ if mask is not None:
95
+ mask = Density.from_file(mask, **kwargs)
96
+ mask.origin = deepcopy(mask_target.origin)
97
+ if not np.allclose(mask.shape, mask_target.shape):
98
+ raise ValueError(
99
+ f"Expected shape of {mask_path} was {mask_target.shape},"
100
+ f" got f{mask.shape}"
101
+ )
102
+ if not np.allclose(mask.sampling_rate, mask_target.sampling_rate):
103
+ raise ValueError(
104
+ f"Expected sampling_rate of {mask_path} was {mask_target.sampling_rate}"
105
+ f", got f{mask.sampling_rate}"
106
+ )
107
+ return mask
108
+
109
+
110
+ def crop_data(data: Density, cutoff: float, data_mask: Density = None) -> bool:
111
+ """
112
+ Crop the provided data and mask to a smaller box based on a cutoff value.
113
+
114
+ Parameters
115
+ ----------
116
+ data : Density
117
+ The data that should be cropped.
118
+ cutoff : float
119
+ The threshold value to determine which parts of the data should be kept.
120
+ data_mask : Density, optional
121
+ A mask for the data that should be cropped.
122
+
123
+ Returns
124
+ -------
125
+ bool
126
+ Returns True if the data was adjusted (cropped), otherwise returns False.
127
+
128
+ Notes
129
+ -----
130
+ Cropping is performed in place.
131
+ """
132
+ if cutoff is None:
133
+ return False
134
+
135
+ box = data.trim_box(cutoff=cutoff)
136
+ box_mask = box
137
+ if data_mask is not None:
138
+ box_mask = data_mask.trim_box(cutoff=cutoff)
139
+ box = tuple(
140
+ slice(min(arr.start, mask.start), max(arr.stop, mask.stop))
141
+ for arr, mask in zip(box, box_mask)
142
+ )
143
+ if box == tuple(slice(0, x) for x in data.shape):
144
+ return False
145
+
146
+ data.adjust_box(box)
147
+
148
+ if data_mask:
149
+ data_mask.adjust_box(box)
150
+
151
+ return True
152
+
153
+
154
+ def parse_rotation_logic(args, ndim):
155
+ if args.angular_sampling is not None:
156
+ rotations = get_rotation_matrices(
157
+ angular_sampling=args.angular_sampling,
158
+ dim=ndim,
159
+ use_optimized_set=not args.no_use_optimized_set,
160
+ )
161
+ if args.angular_sampling >= 180:
162
+ rotations = np.eye(ndim).reshape(1, ndim, ndim)
163
+ return rotations
164
+
165
+ if args.axis_sampling is None:
166
+ args.axis_sampling = args.cone_sampling
167
+
168
+ rotations = get_rotations_around_vector(
169
+ cone_angle=args.cone_angle,
170
+ cone_sampling=args.cone_sampling,
171
+ axis_angle=args.axis_angle,
172
+ axis_sampling=args.axis_sampling,
173
+ n_symmetry=args.axis_symmetry,
174
+ )
175
+ return rotations
176
+
177
+
178
+ # TODO: Think about whether wedge mask should also be added to target
179
+ # For now leave it at the cost of incorrect upper bound on the scores
180
+ def setup_filter(args, template: Density, target: Density) -> Tuple[Compose, Compose]:
181
+ from tme.preprocessing import LinearWhiteningFilter, BandPassFilter
182
+ from tme.preprocessing.tilt_series import (
183
+ Wedge,
184
+ WedgeReconstructed,
185
+ ReconstructFromTilt,
186
+ )
187
+
188
+ template_filter, target_filter = [], []
189
+ if args.tilt_angles is not None:
190
+ try:
191
+ wedge = Wedge.from_file(args.tilt_angles)
192
+ wedge.weight_type = args.tilt_weighting
193
+ if args.tilt_weighting in ("angle", None) and args.ctf_file is None:
194
+ wedge = WedgeReconstructed(
195
+ angles=wedge.angles, weight_wedge=args.tilt_weighting == "angle"
196
+ )
197
+ except FileNotFoundError:
198
+ tilt_step, create_continuous_wedge = None, True
199
+ tilt_start, tilt_stop = args.tilt_angles.split(",")
200
+ if ":" in tilt_stop:
201
+ create_continuous_wedge = False
202
+ tilt_stop, tilt_step = tilt_stop.split(":")
203
+ tilt_start, tilt_stop = float(tilt_start), float(tilt_stop)
204
+ tilt_angles = (tilt_start, tilt_stop)
205
+ if tilt_step is not None:
206
+ tilt_step = float(tilt_step)
207
+ tilt_angles = np.arange(
208
+ -tilt_start, tilt_stop + tilt_step, tilt_step
209
+ ).tolist()
210
+
211
+ if args.tilt_weighting is not None and tilt_step is None:
212
+ raise ValueError(
213
+ "Tilt weighting is not supported for continuous wedges."
214
+ )
215
+ if args.tilt_weighting not in ("angle", None):
216
+ raise ValueError(
217
+ "Tilt weighting schemes other than 'angle' or 'None' require "
218
+ "a specification of electron doses via --tilt_angles."
219
+ )
220
+
221
+ wedge = Wedge(
222
+ angles=tilt_angles,
223
+ opening_axis=args.wedge_axes[0],
224
+ tilt_axis=args.wedge_axes[1],
225
+ shape=None,
226
+ weight_type=None,
227
+ weights=np.ones_like(tilt_angles),
228
+ )
229
+ if args.tilt_weighting in ("angle", None) and args.ctf_file is None:
230
+ wedge = WedgeReconstructed(
231
+ angles=tilt_angles,
232
+ weight_wedge=args.tilt_weighting == "angle",
233
+ create_continuous_wedge=create_continuous_wedge,
234
+ )
235
+
236
+ wedge.opening_axis = args.wedge_axes[0]
237
+ wedge.tilt_axis = args.wedge_axes[1]
238
+ wedge.sampling_rate = template.sampling_rate
239
+ template_filter.append(wedge)
240
+ if not isinstance(wedge, WedgeReconstructed):
241
+ template_filter.append(
242
+ ReconstructFromTilt(
243
+ reconstruction_filter=args.reconstruction_filter,
244
+ interpolation_order=args.reconstruction_interpolation_order,
245
+ )
246
+ )
247
+
248
+ if args.ctf_file is not None or args.defocus is not None:
249
+ from tme.preprocessing.tilt_series import CTF
250
+
251
+ needs_reconstruction = True
252
+ if args.ctf_file is not None:
253
+ ctf = CTF.from_file(args.ctf_file)
254
+ n_tilts_ctfs, n_tils_angles = len(ctf.defocus_x), len(wedge.angles)
255
+ if n_tilts_ctfs != n_tils_angles:
256
+ raise ValueError(
257
+ f"CTF file contains {n_tilts_ctfs} micrographs, but match_template "
258
+ f"recieved {n_tils_angles} tilt angles. Expected one angle "
259
+ "per micrograph."
260
+ )
261
+ ctf.angles = wedge.angles
262
+ ctf.opening_axis, ctf.tilt_axis = args.wedge_axes
263
+ else:
264
+ needs_reconstruction = False
265
+ ctf = CTF(
266
+ defocus_x=[args.defocus],
267
+ phase_shift=[args.phase_shift],
268
+ defocus_y=None,
269
+ angles=[0],
270
+ shape=None,
271
+ return_real_fourier=True,
272
+ )
273
+ ctf.sampling_rate = template.sampling_rate
274
+ ctf.flip_phase = args.no_flip_phase
275
+ ctf.amplitude_contrast = args.amplitude_contrast
276
+ ctf.spherical_aberration = args.spherical_aberration
277
+ ctf.acceleration_voltage = args.acceleration_voltage * 1e3
278
+ ctf.correct_defocus_gradient = args.correct_defocus_gradient
279
+
280
+ if not needs_reconstruction:
281
+ template_filter.append(ctf)
282
+ elif isinstance(template_filter[-1], ReconstructFromTilt):
283
+ template_filter.insert(-1, ctf)
284
+ else:
285
+ template_filter.insert(0, ctf)
286
+ template_filter.insert(
287
+ 1,
288
+ ReconstructFromTilt(
289
+ reconstruction_filter=args.reconstruction_filter,
290
+ interpolation_order=args.reconstruction_interpolation_order,
291
+ ),
292
+ )
293
+
294
+ if args.lowpass or args.highpass is not None:
295
+ lowpass, highpass = args.lowpass, args.highpass
296
+ if args.pass_format == "voxel":
297
+ if lowpass is not None:
298
+ lowpass = np.max(np.multiply(lowpass, template.sampling_rate))
299
+ if highpass is not None:
300
+ highpass = np.max(np.multiply(highpass, template.sampling_rate))
301
+ elif args.pass_format == "frequency":
302
+ if lowpass is not None:
303
+ lowpass = np.max(np.divide(template.sampling_rate, lowpass))
304
+ if highpass is not None:
305
+ highpass = np.max(np.divide(template.sampling_rate, highpass))
306
+
307
+ try:
308
+ if args.lowpass >= args.highpass:
309
+ warnings.warn("--lowpass should be smaller than --highpass.")
310
+ except Exception:
311
+ pass
312
+
313
+ bandpass = BandPassFilter(
314
+ use_gaussian=args.no_pass_smooth,
315
+ lowpass=lowpass,
316
+ highpass=highpass,
317
+ sampling_rate=template.sampling_rate,
318
+ )
319
+ template_filter.append(bandpass)
320
+
321
+ if not args.no_filter_target:
322
+ target_filter.append(bandpass)
323
+
324
+ if args.whiten_spectrum:
325
+ whitening_filter = LinearWhiteningFilter()
326
+ template_filter.append(whitening_filter)
327
+ target_filter.append(whitening_filter)
328
+
329
+ needs_reconstruction = any(
330
+ [isinstance(t, ReconstructFromTilt) for t in template_filter]
331
+ )
332
+ if needs_reconstruction and args.reconstruction_filter is None:
333
+ warnings.warn(
334
+ "Consider using a --reconstruction_filter such as 'ramp' to avoid artifacts."
335
+ )
336
+
337
+ template_filter = Compose(template_filter) if len(template_filter) else None
338
+ target_filter = Compose(target_filter) if len(target_filter) else None
339
+
340
+ return template_filter, target_filter
341
+
342
+
343
+ def parse_args():
344
+ parser = argparse.ArgumentParser(
345
+ description="Perform template matching.",
346
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter
347
+ )
348
+
349
+ io_group = parser.add_argument_group("Input / Output")
350
+ io_group.add_argument(
351
+ "-m",
352
+ "--target",
353
+ dest="target",
354
+ type=str,
355
+ required=True,
356
+ help="Path to a target in CCP4/MRC, EM, H5 or another format supported by "
357
+ "tme.density.Density.from_file "
358
+ "https://kosinskilab.github.io/pyTME/reference/api/tme.density.Density.from_file.html",
359
+ )
360
+ io_group.add_argument(
361
+ "--target_mask",
362
+ dest="target_mask",
363
+ type=str,
364
+ required=False,
365
+ help="Path to a mask for the target in a supported format (see target).",
366
+ )
367
+ io_group.add_argument(
368
+ "-i",
369
+ "--template",
370
+ dest="template",
371
+ type=str,
372
+ required=True,
373
+ help="Path to a template in PDB/MMCIF or other supported formats (see target).",
374
+ )
375
+ io_group.add_argument(
376
+ "--template_mask",
377
+ dest="template_mask",
378
+ type=str,
379
+ required=False,
380
+ help="Path to a mask for the template in a supported format (see target).",
381
+ )
382
+ io_group.add_argument(
383
+ "-o",
384
+ "--output",
385
+ dest="output",
386
+ type=str,
387
+ required=False,
388
+ default="output.pickle",
389
+ help="Path to the output pickle file.",
390
+ )
391
+ io_group.add_argument(
392
+ "--invert_target_contrast",
393
+ dest="invert_target_contrast",
394
+ action="store_true",
395
+ default=False,
396
+ help="Invert the target's contrast and rescale linearly between zero and one. "
397
+ "This option is intended for targets where templates to-be-matched have "
398
+ "negative values, e.g. tomograms.",
399
+ )
400
+ io_group.add_argument(
401
+ "--scramble_phases",
402
+ dest="scramble_phases",
403
+ action="store_true",
404
+ default=False,
405
+ help="Phase scramble the template to generate a noise score background.",
406
+ )
407
+
408
+ scoring_group = parser.add_argument_group("Scoring")
409
+ scoring_group.add_argument(
410
+ "-s",
411
+ dest="score",
412
+ type=str,
413
+ default="FLCSphericalMask",
414
+ choices=list(MATCHING_EXHAUSTIVE_REGISTER.keys()),
415
+ help="Template matching scoring function.",
416
+ )
417
+
418
+ angular_group = parser.add_argument_group("Angular Sampling")
419
+ angular_exclusive = angular_group.add_mutually_exclusive_group(required=True)
420
+
421
+ angular_exclusive.add_argument(
422
+ "-a",
423
+ dest="angular_sampling",
424
+ type=check_positive,
425
+ default=None,
426
+ help="Angular sampling rate using optimized rotational sets."
427
+ "A lower number yields more rotations. Values >= 180 sample only the identity.",
428
+ )
429
+ angular_exclusive.add_argument(
430
+ "--cone_angle",
431
+ dest="cone_angle",
432
+ type=check_positive,
433
+ default=None,
434
+ help="Half-angle of the cone to be sampled in degrees. Allows to sample a "
435
+ "narrow interval around a known orientation, e.g. for surface oversampling.",
436
+ )
437
+ angular_group.add_argument(
438
+ "--cone_sampling",
439
+ dest="cone_sampling",
440
+ type=check_positive,
441
+ default=None,
442
+ help="Sampling rate of the cone in degrees.",
443
+ )
444
+ angular_group.add_argument(
445
+ "--axis_angle",
446
+ dest="axis_angle",
447
+ type=check_positive,
448
+ default=360.0,
449
+ required=False,
450
+ help="Sampling angle along the z-axis of the cone.",
451
+ )
452
+ angular_group.add_argument(
453
+ "--axis_sampling",
454
+ dest="axis_sampling",
455
+ type=check_positive,
456
+ default=None,
457
+ required=False,
458
+ help="Sampling rate along the z-axis of the cone. Defaults to --cone_sampling.",
459
+ )
460
+ angular_group.add_argument(
461
+ "--axis_symmetry",
462
+ dest="axis_symmetry",
463
+ type=check_positive,
464
+ default=1,
465
+ required=False,
466
+ help="N-fold symmetry around z-axis of the cone.",
467
+ )
468
+ angular_group.add_argument(
469
+ "--no_use_optimized_set",
470
+ dest="no_use_optimized_set",
471
+ action="store_true",
472
+ default=False,
473
+ required=False,
474
+ help="Whether to use random uniform instead of optimized rotation sets.",
475
+ )
476
+
477
+ computation_group = parser.add_argument_group("Computation")
478
+ computation_group.add_argument(
479
+ "-n",
480
+ dest="cores",
481
+ required=False,
482
+ type=int,
483
+ default=4,
484
+ help="Number of cores used for template matching.",
485
+ )
486
+ computation_group.add_argument(
487
+ "--use_gpu",
488
+ dest="use_gpu",
489
+ action="store_true",
490
+ default=False,
491
+ help="Whether to perform computations on the GPU.",
492
+ )
493
+ computation_group.add_argument(
494
+ "--gpu_indices",
495
+ dest="gpu_indices",
496
+ type=str,
497
+ default=None,
498
+ help="Comma-separated list of GPU indices to use. For example,"
499
+ " 0,1 for the first and second GPU. Only used if --use_gpu is set."
500
+ " If not provided but --use_gpu is set, CUDA_VISIBLE_DEVICES will"
501
+ " be respected.",
502
+ )
503
+ computation_group.add_argument(
504
+ "-r",
505
+ "--ram",
506
+ dest="memory",
507
+ required=False,
508
+ type=int,
509
+ default=None,
510
+ help="Amount of memory that can be used in bytes.",
511
+ )
512
+ computation_group.add_argument(
513
+ "--memory_scaling",
514
+ dest="memory_scaling",
515
+ required=False,
516
+ type=float,
517
+ default=0.85,
518
+ help="Fraction of available memory to be used. Ignored if --ram is set."
519
+ )
520
+ computation_group.add_argument(
521
+ "--temp_directory",
522
+ dest="temp_directory",
523
+ default=None,
524
+ help="Directory for temporary objects. Faster I/O improves runtime.",
525
+ )
526
+ computation_group.add_argument(
527
+ "--backend",
528
+ dest="backend",
529
+ default=None,
530
+ choices=be.available_backends(),
531
+ help="[Expert] Overwrite default computation backend.",
532
+ )
533
+
534
+ filter_group = parser.add_argument_group("Filters")
535
+ filter_group.add_argument(
536
+ "--lowpass",
537
+ dest="lowpass",
538
+ type=float,
539
+ required=False,
540
+ help="Resolution to lowpass filter template and target to in the same unit "
541
+ "as the sampling rate of template and target (typically Ångstrom).",
542
+ )
543
+ filter_group.add_argument(
544
+ "--highpass",
545
+ dest="highpass",
546
+ type=float,
547
+ required=False,
548
+ help="Resolution to highpass filter template and target to in the same unit "
549
+ "as the sampling rate of template and target (typically Ångstrom).",
550
+ )
551
+ filter_group.add_argument(
552
+ "--no_pass_smooth",
553
+ dest="no_pass_smooth",
554
+ action="store_false",
555
+ default=True,
556
+ help="Whether a hard edge filter should be used for --lowpass and --highpass.",
557
+ )
558
+ filter_group.add_argument(
559
+ "--pass_format",
560
+ dest="pass_format",
561
+ type=str,
562
+ required=False,
563
+ default="sampling_rate",
564
+ choices=["sampling_rate", "voxel", "frequency"],
565
+ help="How values passed to --lowpass and --highpass should be interpreted. ",
566
+ )
567
+ filter_group.add_argument(
568
+ "--whiten_spectrum",
569
+ dest="whiten_spectrum",
570
+ action="store_true",
571
+ default=None,
572
+ help="Apply spectral whitening to template and target based on target spectrum.",
573
+ )
574
+ filter_group.add_argument(
575
+ "--wedge_axes",
576
+ dest="wedge_axes",
577
+ type=str,
578
+ required=False,
579
+ default=None,
580
+ help="Indices of wedge opening and tilt axis, e.g. 0,2 for a wedge that is open "
581
+ "in z-direction and tilted over the x axis.",
582
+ )
583
+ filter_group.add_argument(
584
+ "--tilt_angles",
585
+ dest="tilt_angles",
586
+ type=str,
587
+ required=False,
588
+ default=None,
589
+ help="Path to a tab-separated file containing the column angles and optionally "
590
+ " weights, or comma separated start and stop stage tilt angle, e.g. 50,45, which "
591
+ " yields a continuous wedge mask. Alternatively, a tilt step size can be "
592
+ "specified like 50,45:5.0 to sample 5.0 degree tilt angle steps.",
593
+ )
594
+ filter_group.add_argument(
595
+ "--tilt_weighting",
596
+ dest="tilt_weighting",
597
+ type=str,
598
+ required=False,
599
+ choices=["angle", "relion", "grigorieff"],
600
+ default=None,
601
+ help="Weighting scheme used to reweight individual tilts. Available options: "
602
+ "angle (cosine based weighting), "
603
+ "relion (relion formalism for wedge weighting) requires,"
604
+ "grigorieff (exposure filter as defined in Grant and Grigorieff 2015)."
605
+ "relion and grigorieff require electron doses in --tilt_angles weights column.",
606
+ )
607
+ filter_group.add_argument(
608
+ "--reconstruction_filter",
609
+ dest="reconstruction_filter",
610
+ type=str,
611
+ required=False,
612
+ choices=["ram-lak", "ramp", "ramp-cont", "shepp-logan", "cosine", "hamming"],
613
+ default=None,
614
+ help="Filter applied when reconstructing (N+1)-D from N-D filters.",
615
+ )
616
+ filter_group.add_argument(
617
+ "--reconstruction_interpolation_order",
618
+ dest="reconstruction_interpolation_order",
619
+ type=int,
620
+ default=1,
621
+ required=False,
622
+ help="Analogous to --interpolation_order but for reconstruction.",
623
+ )
624
+ filter_group.add_argument(
625
+ "--no_filter_target",
626
+ dest="no_filter_target",
627
+ action="store_true",
628
+ default=False,
629
+ help="Whether to not apply potential filters to the target.",
630
+ )
631
+
632
+ ctf_group = parser.add_argument_group("Contrast Transfer Function")
633
+ ctf_group.add_argument(
634
+ "--ctf_file",
635
+ dest="ctf_file",
636
+ type=str,
637
+ required=False,
638
+ default=None,
639
+ help="Path to a file with CTF parameters from CTFFIND4. Each line will be "
640
+ "interpreted as tilt obtained at the angle specified in --tilt_angles. ",
641
+ )
642
+ ctf_group.add_argument(
643
+ "--defocus",
644
+ dest="defocus",
645
+ type=float,
646
+ required=False,
647
+ default=None,
648
+ help="Defocus in units of sampling rate (typically Ångstrom). "
649
+ "Superseded by --ctf_file.",
650
+ )
651
+ ctf_group.add_argument(
652
+ "--phase_shift",
653
+ dest="phase_shift",
654
+ type=float,
655
+ required=False,
656
+ default=0,
657
+ help="Phase shift in degrees. Superseded by --ctf_file.",
658
+ )
659
+ ctf_group.add_argument(
660
+ "--acceleration_voltage",
661
+ dest="acceleration_voltage",
662
+ type=float,
663
+ required=False,
664
+ default=300,
665
+ help="Acceleration voltage in kV.",
666
+ )
667
+ ctf_group.add_argument(
668
+ "--spherical_aberration",
669
+ dest="spherical_aberration",
670
+ type=float,
671
+ required=False,
672
+ default=2.7e7,
673
+ help="Spherical aberration in units of sampling rate (typically Ångstrom).",
674
+ )
675
+ ctf_group.add_argument(
676
+ "--amplitude_contrast",
677
+ dest="amplitude_contrast",
678
+ type=float,
679
+ required=False,
680
+ default=0.07,
681
+ help="Amplitude contrast.",
682
+ )
683
+ ctf_group.add_argument(
684
+ "--no_flip_phase",
685
+ dest="no_flip_phase",
686
+ action="store_false",
687
+ required=False,
688
+ help="Perform phase-flipping CTF correction.",
689
+ )
690
+ ctf_group.add_argument(
691
+ "--correct_defocus_gradient",
692
+ dest="correct_defocus_gradient",
693
+ action="store_true",
694
+ required=False,
695
+ help="[Experimental] Whether to compute a more accurate 3D CTF incorporating "
696
+ "defocus gradients.",
697
+ )
698
+
699
+ performance_group = parser.add_argument_group("Performance")
700
+ performance_group.add_argument(
701
+ "--cutoff_target",
702
+ dest="cutoff_target",
703
+ type=float,
704
+ required=False,
705
+ default=None,
706
+ help="Target contour level (used for cropping).",
707
+ )
708
+ performance_group.add_argument(
709
+ "--cutoff_template",
710
+ dest="cutoff_template",
711
+ type=float,
712
+ required=False,
713
+ default=None,
714
+ help="Template contour level (used for cropping).",
715
+ )
716
+ performance_group.add_argument(
717
+ "--no_centering",
718
+ dest="no_centering",
719
+ action="store_true",
720
+ help="Assumes the template is already centered and omits centering.",
721
+ )
722
+ performance_group.add_argument(
723
+ "--no_edge_padding",
724
+ dest="no_edge_padding",
725
+ action="store_true",
726
+ default=False,
727
+ help="Whether to not pad the edges of the target. Can be set if the target"
728
+ " has a well defined bounding box, e.g. a masked reconstruction.",
729
+ )
730
+ performance_group.add_argument(
731
+ "--no_fourier_padding",
732
+ dest="no_fourier_padding",
733
+ action="store_true",
734
+ default=False,
735
+ help="Whether input arrays should not be zero-padded to full convolution shape "
736
+ "for numerical stability. When working with very large targets, e.g. tomograms, "
737
+ "it is safe to use this flag and benefit from the performance gain.",
738
+ )
739
+ performance_group.add_argument(
740
+ "--no_filter_padding",
741
+ dest="no_filter_padding",
742
+ action="store_true",
743
+ default=False,
744
+ help="Omits padding of optional template filters. Particularly effective when "
745
+ "the target is much larger than the template. However, for fast osciliating "
746
+ "filters setting this flag can introduce aliasing effects.",
747
+ )
748
+ performance_group.add_argument(
749
+ "--interpolation_order",
750
+ dest="interpolation_order",
751
+ required=False,
752
+ type=int,
753
+ default=3,
754
+ help="Spline interpolation used for rotations.",
755
+ )
756
+ performance_group.add_argument(
757
+ "--use_mixed_precision",
758
+ dest="use_mixed_precision",
759
+ action="store_true",
760
+ default=False,
761
+ help="Use float16 for real values operations where possible.",
762
+ )
763
+ performance_group.add_argument(
764
+ "--use_memmap",
765
+ dest="use_memmap",
766
+ action="store_true",
767
+ default=False,
768
+ help="Use memmaps to offload large data objects to disk. "
769
+ "Particularly useful for large inputs in combination with --use_gpu.",
770
+ )
771
+
772
+ analyzer_group = parser.add_argument_group("Analyzer")
773
+ analyzer_group.add_argument(
774
+ "--score_threshold",
775
+ dest="score_threshold",
776
+ required=False,
777
+ type=float,
778
+ default=0,
779
+ help="Minimum template matching scores to consider for analysis.",
780
+ )
781
+ analyzer_group.add_argument(
782
+ "-p",
783
+ dest="peak_calling",
784
+ action="store_true",
785
+ default=False,
786
+ help="Perform peak calling instead of score aggregation.",
787
+ )
788
+ analyzer_group.add_argument(
789
+ "--number_of_peaks",
790
+ dest="number_of_peaks",
791
+ action="store_true",
792
+ default=1000,
793
+ help="Number of peaks to call, 1000 by default..",
794
+ )
795
+ args = parser.parse_args()
796
+ args.version = __version__
797
+
798
+ if args.interpolation_order < 0:
799
+ args.interpolation_order = None
800
+
801
+ if args.temp_directory is None:
802
+ default = abspath(".")
803
+ if os.environ.get("TMPDIR", None) is not None:
804
+ default = os.environ.get("TMPDIR")
805
+ args.temp_directory = default
806
+
807
+ os.environ["TMPDIR"] = args.temp_directory
808
+
809
+ args.pad_target_edges = not args.no_edge_padding
810
+ args.pad_fourier = not args.no_fourier_padding
811
+
812
+ if args.score not in MATCHING_EXHAUSTIVE_REGISTER:
813
+ raise ValueError(
814
+ f"score has to be one of {', '.join(MATCHING_EXHAUSTIVE_REGISTER.keys())}"
815
+ )
816
+
817
+ gpu_devices = os.environ.get("CUDA_VISIBLE_DEVICES", None)
818
+ if args.gpu_indices is not None:
819
+ os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu_indices
820
+
821
+ if args.use_gpu:
822
+ gpu_devices = os.environ.get("CUDA_VISIBLE_DEVICES", None)
823
+ if gpu_devices is None:
824
+ print(
825
+ "No GPU indices provided and CUDA_VISIBLE_DEVICES is not set.",
826
+ "Assuming device 0.",
827
+ )
828
+ os.environ["CUDA_VISIBLE_DEVICES"] = "0"
829
+ args.gpu_indices = [
830
+ int(x) for x in os.environ["CUDA_VISIBLE_DEVICES"].split(",")
831
+ ]
832
+
833
+ if args.tilt_angles is not None:
834
+ if args.wedge_axes is None:
835
+ raise ValueError("Need to specify --wedge_axes when --tilt_angles is set.")
836
+ if not exists(args.tilt_angles):
837
+ try:
838
+ float(args.tilt_angles.split(",")[0])
839
+ except ValueError:
840
+ raise ValueError(f"{args.tilt_angles} is not a file nor a range.")
841
+
842
+ if args.ctf_file is not None and args.tilt_angles is None:
843
+ raise ValueError("Need to specify --tilt_angles when --ctf_file is set.")
844
+
845
+ if args.wedge_axes is not None:
846
+ args.wedge_axes = tuple(int(i) for i in args.wedge_axes.split(","))
847
+
848
+ return args
849
+
850
+
851
+ def main():
852
+ args = parse_args()
853
+ print_entry()
854
+
855
+ target = Density.from_file(args.target, use_memmap=True)
856
+
857
+ try:
858
+ template = Density.from_file(args.template)
859
+ except Exception:
860
+ drop = target.metadata.get("batch_dimension", ())
861
+ keep = [i not in drop for i in range(target.data.ndim)]
862
+ template = Density.from_structure(
863
+ filename_or_structure=args.template,
864
+ sampling_rate=target.sampling_rate[keep],
865
+ )
866
+
867
+ if target.sampling_rate.size == template.sampling_rate.size:
868
+ if not np.allclose(target.sampling_rate, template.sampling_rate):
869
+ print(
870
+ f"Resampling template to {target.sampling_rate}. "
871
+ "Consider providing a template with the same sampling rate as the target."
872
+ )
873
+ template = template.resample(target.sampling_rate, order=3)
874
+
875
+ template_mask = load_and_validate_mask(
876
+ mask_target=template, mask_path=args.template_mask
877
+ )
878
+ target_mask = load_and_validate_mask(
879
+ mask_target=target, mask_path=args.target_mask, use_memmap=True
880
+ )
881
+
882
+ initial_shape = target.shape
883
+ is_cropped = crop_data(
884
+ data=target, data_mask=target_mask, cutoff=args.cutoff_target
885
+ )
886
+ print_block(
887
+ name="Target",
888
+ data={
889
+ "Initial Shape": initial_shape,
890
+ "Sampling Rate": tuple(np.round(target.sampling_rate, 2)),
891
+ "Final Shape": target.shape,
892
+ },
893
+ )
894
+ if is_cropped:
895
+ args.target = generate_tempfile_name(suffix=".mrc")
896
+ target.to_file(args.target)
897
+
898
+ if target_mask:
899
+ args.target_mask = generate_tempfile_name(suffix=".mrc")
900
+ target_mask.to_file(args.target_mask)
901
+
902
+ if target_mask:
903
+ print_block(
904
+ name="Target Mask",
905
+ data={
906
+ "Initial Shape": initial_shape,
907
+ "Sampling Rate": tuple(np.round(target_mask.sampling_rate, 2)),
908
+ "Final Shape": target_mask.shape,
909
+ },
910
+ )
911
+
912
+ initial_shape = template.shape
913
+ _ = crop_data(data=template, data_mask=template_mask, cutoff=args.cutoff_template)
914
+
915
+ translation = np.zeros(len(template.shape), dtype=np.float32)
916
+ if not args.no_centering:
917
+ template, translation = template.centered(0)
918
+ print_block(
919
+ name="Template",
920
+ data={
921
+ "Initial Shape": initial_shape,
922
+ "Sampling Rate": tuple(np.round(template.sampling_rate, 2)),
923
+ "Final Shape": template.shape,
924
+ },
925
+ )
926
+
927
+ if template_mask is None:
928
+ template_mask = template.empty
929
+ if not args.no_centering:
930
+ enclosing_box = template.minimum_enclosing_box(
931
+ 0, use_geometric_center=False
932
+ )
933
+ template_mask.adjust_box(enclosing_box)
934
+
935
+ template_mask.data[:] = 1
936
+ translation = np.zeros_like(translation)
937
+
938
+ template_mask.pad(template.shape, center=False)
939
+ origin_translation = np.divide(
940
+ np.subtract(template.origin, template_mask.origin), template.sampling_rate
941
+ )
942
+ translation = np.add(translation, origin_translation)
943
+
944
+ template_mask = template_mask.rigid_transform(
945
+ rotation_matrix=np.eye(template_mask.data.ndim),
946
+ translation=-translation,
947
+ order=1,
948
+ )
949
+ template_mask.origin = template.origin.copy()
950
+ print_block(
951
+ name="Template Mask",
952
+ data={
953
+ "Inital Shape": initial_shape,
954
+ "Sampling Rate": tuple(np.round(template_mask.sampling_rate, 2)),
955
+ "Final Shape": template_mask.shape,
956
+ },
957
+ )
958
+ print("\n" + "-" * 80)
959
+
960
+ if args.scramble_phases:
961
+ template.data = scramble_phases(
962
+ template.data, noise_proportion=1.0, normalize_power=True
963
+ )
964
+
965
+ # Determine suitable backend for the selected operation
966
+ available_backends = be.available_backends()
967
+ if args.backend is not None:
968
+ req_backend = args.backend
969
+ if req_backend not in available_backends:
970
+ raise ValueError(
971
+ "Requested backend is not available."
972
+ )
973
+ available_backends = [req_backend,]
974
+
975
+ be_selection = ("numpyfftw", "pytorch", "jax", "mlx")
976
+ if args.use_gpu:
977
+ args.cores = len(args.gpu_indices)
978
+ be_selection = ("pytorch", "cupy", "jax")
979
+ if args.use_mixed_precision:
980
+ be_selection = tuple(x for x in be_selection if x in ("cupy", "numpyfftw"))
981
+
982
+ available_backends = [x for x in available_backends if x in be_selection]
983
+ if args.peak_calling:
984
+ if "jax" in available_backends:
985
+ available_backends.remove("jax")
986
+ if args.use_gpu and "pytorch" in available_backends:
987
+ available_backends = ("pytorch",)
988
+ if args.interpolation_order == 3:
989
+ raise NotImplementedError(
990
+ "Pytorch does not support --interpolation_order 3, 1 is supported."
991
+ )
992
+ ndim = len(template.shape)
993
+ if len(target.shape) == ndim and ndim <= 3 and args.use_gpu:
994
+ available_backends = ["jax", ]
995
+
996
+ backend_preference = ("numpyfftw", "pytorch", "jax", "mlx")
997
+ if args.use_gpu:
998
+ backend_preference = ("cupy", "jax", "pytorch")
999
+ for pref in backend_preference:
1000
+ if pref not in available_backends:
1001
+ continue
1002
+ be.change_backend(pref)
1003
+ if pref == "pytorch":
1004
+ be.change_backend(pref, device = "cuda" if args.use_gpu else "cpu")
1005
+
1006
+ if args.use_mixed_precision:
1007
+ be.change_backend(
1008
+ backend_name=pref,
1009
+ default_dtype=be._array_backend.float16,
1010
+ complex_dtype=be._array_backend.complex64,
1011
+ default_dtype_int=be._array_backend.int16,
1012
+ )
1013
+ break
1014
+
1015
+ available_memory = be.get_available_memory() * be.device_count()
1016
+ if args.memory is None:
1017
+ args.memory = int(args.memory_scaling * available_memory)
1018
+
1019
+ callback_class = MaxScoreOverRotations
1020
+ if args.peak_calling:
1021
+ callback_class = PeakCallerMaximumFilter
1022
+
1023
+ matching_data = MatchingData(
1024
+ target=target,
1025
+ template=template.data,
1026
+ target_mask=target_mask,
1027
+ template_mask=template_mask,
1028
+ invert_target=args.invert_target_contrast,
1029
+ rotations=parse_rotation_logic(args=args, ndim=template.data.ndim),
1030
+ )
1031
+
1032
+ matching_data.template_filter, matching_data.target_filter = setup_filter(
1033
+ args, template, target
1034
+ )
1035
+
1036
+ target_dims = target.metadata.get("batch_dimension", None)
1037
+ matching_data._set_matching_dimension(target_dims=target_dims, template_dims=None)
1038
+ args.score = "FLC" if target_dims is not None else args.score
1039
+ args.target_batch, args.template_batch = target_dims, None
1040
+
1041
+ template_box = matching_data._output_template_shape
1042
+ if not args.pad_fourier:
1043
+ template_box = tuple(0 for _ in range(len(template_box)))
1044
+
1045
+ target_padding = tuple(0 for _ in range(len(template_box)))
1046
+ if args.pad_target_edges:
1047
+ target_padding = matching_data._output_template_shape
1048
+
1049
+ splits, schedule = compute_parallelization_schedule(
1050
+ shape1=target.shape,
1051
+ shape2=tuple(int(x) for x in template_box),
1052
+ shape1_padding=tuple(int(x) for x in target_padding),
1053
+ max_cores=args.cores,
1054
+ max_ram=args.memory,
1055
+ split_only_outer=args.use_gpu,
1056
+ matching_method=args.score,
1057
+ analyzer_method=callback_class.__name__,
1058
+ backend=be._backend_name,
1059
+ float_nbytes=be.datatype_bytes(be._float_dtype),
1060
+ complex_nbytes=be.datatype_bytes(be._complex_dtype),
1061
+ integer_nbytes=be.datatype_bytes(be._int_dtype),
1062
+ split_axes=target_dims,
1063
+ )
1064
+
1065
+ if splits is None:
1066
+ print(
1067
+ "Found no suitable parallelization schedule. Consider increasing"
1068
+ " available RAM or decreasing number of cores."
1069
+ )
1070
+ exit(-1)
1071
+
1072
+ matching_setup, matching_score = MATCHING_EXHAUSTIVE_REGISTER[args.score]
1073
+ if target_dims is not None:
1074
+ matching_score = flc_scoring2
1075
+ n_splits = np.prod(list(splits.values()))
1076
+ target_split = ", ".join(
1077
+ [":".join([str(x) for x in axis]) for axis in splits.items()]
1078
+ )
1079
+ gpus_used = 0 if args.gpu_indices is None else len(args.gpu_indices)
1080
+ options = {
1081
+ "Angular Sampling": f"{args.angular_sampling}"
1082
+ f" [{matching_data.rotations.shape[0]} rotations]",
1083
+ "Center Template": not args.no_centering,
1084
+ "Scramble Template": args.scramble_phases,
1085
+ "Invert Contrast": args.invert_target_contrast,
1086
+ "Extend Fourier Grid": not args.no_fourier_padding,
1087
+ "Extend Target Edges": not args.no_edge_padding,
1088
+ "Interpolation Order": args.interpolation_order,
1089
+ "Setup Function": f"{get_func_fullname(matching_setup)}",
1090
+ "Scoring Function": f"{get_func_fullname(matching_score)}",
1091
+ }
1092
+
1093
+ print_block(
1094
+ name="Template Matching",
1095
+ data=options,
1096
+ label_width=max(len(key) for key in options.keys()) + 3,
1097
+ )
1098
+
1099
+ compute_options = {
1100
+ "Backend" :be._BACKEND_REGISTRY[be._backend_name],
1101
+ "Compute Devices" : f"CPU [{args.cores}], GPU [{gpus_used}]",
1102
+ "Use Mixed Precision": args.use_mixed_precision,
1103
+ "Assigned Memory [MB]": f"{args.memory // 1e6} [out of {available_memory//1e6}]",
1104
+ "Temporary Directory": args.temp_directory,
1105
+ "Target Splits": f"{target_split} [N={n_splits}]",
1106
+ }
1107
+ print_block(
1108
+ name="Computation",
1109
+ data=compute_options,
1110
+ label_width=max(len(key) for key in options.keys()) + 3,
1111
+ )
1112
+
1113
+ filter_args = {
1114
+ "Lowpass": args.lowpass,
1115
+ "Highpass": args.highpass,
1116
+ "Smooth Pass": args.no_pass_smooth,
1117
+ "Pass Format": args.pass_format,
1118
+ "Spectral Whitening": args.whiten_spectrum,
1119
+ "Wedge Axes": args.wedge_axes,
1120
+ "Tilt Angles": args.tilt_angles,
1121
+ "Tilt Weighting": args.tilt_weighting,
1122
+ "Reconstruction Filter": args.reconstruction_filter,
1123
+ }
1124
+ if args.ctf_file is not None or args.defocus is not None:
1125
+ filter_args["CTF File"] = args.ctf_file
1126
+ filter_args["Defocus"] = args.defocus
1127
+ filter_args["Phase Shift"] = args.phase_shift
1128
+ filter_args["Flip Phase"] = args.no_flip_phase
1129
+ filter_args["Acceleration Voltage"] = args.acceleration_voltage
1130
+ filter_args["Spherical Aberration"] = args.spherical_aberration
1131
+ filter_args["Amplitude Contrast"] = args.amplitude_contrast
1132
+ filter_args["Correct Defocus"] = args.correct_defocus_gradient
1133
+
1134
+ filter_args = {k: v for k, v in filter_args.items() if v is not None}
1135
+ if len(filter_args):
1136
+ print_block(
1137
+ name="Filters",
1138
+ data=filter_args,
1139
+ label_width=max(len(key) for key in options.keys()) + 3,
1140
+ )
1141
+
1142
+ analyzer_args = {
1143
+ "score_threshold": args.score_threshold,
1144
+ "number_of_peaks": args.number_of_peaks,
1145
+ "min_distance" : max(template.shape) // 2,
1146
+ "min_boundary_distance" : max(template.shape) // 2,
1147
+ "use_memmap": args.use_memmap,
1148
+ }
1149
+ print_block(
1150
+ name="Analyzer",
1151
+ data={"Analyzer": callback_class, **analyzer_args},
1152
+ label_width=max(len(key) for key in options.keys()) + 3,
1153
+ )
1154
+ print("\n" + "-" * 80)
1155
+
1156
+ outer_jobs = f"{schedule[0]} job{'s' if schedule[0] > 1 else ''}"
1157
+ inner_jobs = f"{schedule[1]} core{'s' if schedule[1] > 1 else ''}"
1158
+ n_splits = f"{n_splits} split{'s' if n_splits > 1 else ''}"
1159
+ print(f"\nDistributing {n_splits} on {outer_jobs} each using {inner_jobs}.")
1160
+
1161
+ start = time()
1162
+ print("Running Template Matching. This might take a while ...")
1163
+ candidates = scan_subsets(
1164
+ matching_data=matching_data,
1165
+ job_schedule=schedule,
1166
+ matching_score=matching_score,
1167
+ matching_setup=matching_setup,
1168
+ callback_class=callback_class,
1169
+ callback_class_args=analyzer_args,
1170
+ target_splits=splits,
1171
+ pad_target_edges=args.pad_target_edges,
1172
+ pad_fourier=args.pad_fourier,
1173
+ pad_template_filter=not args.no_filter_padding,
1174
+ interpolation_order=args.interpolation_order,
1175
+ )
1176
+
1177
+ candidates = list(candidates) if candidates is not None else []
1178
+ if callback_class == MaxScoreOverRotations:
1179
+ if target_mask is not None and args.score != "MCC":
1180
+ candidates[0] *= target_mask.data
1181
+ with warnings.catch_warnings():
1182
+ warnings.simplefilter("ignore", category=UserWarning)
1183
+ nbytes = be.datatype_bytes(be._float_dtype)
1184
+ dtype = np.float32 if nbytes == 4 else np.float16
1185
+ rot_dim = matching_data.rotations.shape[1]
1186
+ candidates[3] = {
1187
+ x: np.frombuffer(i, dtype=dtype).reshape(rot_dim, rot_dim)
1188
+ for i, x in candidates[3].items()
1189
+ }
1190
+ print(np.where(candidates[0] == candidates[0].max()), candidates[0].max())
1191
+ candidates.append((target.origin, template.origin, template.sampling_rate, args))
1192
+ write_pickle(data=candidates, filename=args.output)
1193
+
1194
+ runtime = time() - start
1195
+ print("\n" + "-" * 80)
1196
+ print(f"\nRuntime real: {runtime:.3f}s user: {(runtime * args.cores):.3f}s.")
1197
+
1198
+
1199
+ if __name__ == "__main__":
1200
+ main()