pytme 0.1.5__cp311-cp311-macosx_14_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 (63) hide show
  1. pytme-0.1.5.data/scripts/estimate_ram_usage.py +81 -0
  2. pytme-0.1.5.data/scripts/match_template.py +744 -0
  3. pytme-0.1.5.data/scripts/postprocess.py +279 -0
  4. pytme-0.1.5.data/scripts/preprocess.py +93 -0
  5. pytme-0.1.5.data/scripts/preprocessor_gui.py +729 -0
  6. pytme-0.1.5.dist-info/LICENSE +153 -0
  7. pytme-0.1.5.dist-info/METADATA +69 -0
  8. pytme-0.1.5.dist-info/RECORD +63 -0
  9. pytme-0.1.5.dist-info/WHEEL +5 -0
  10. pytme-0.1.5.dist-info/entry_points.txt +6 -0
  11. pytme-0.1.5.dist-info/top_level.txt +2 -0
  12. scripts/__init__.py +0 -0
  13. scripts/estimate_ram_usage.py +81 -0
  14. scripts/match_template.py +744 -0
  15. scripts/match_template_devel.py +788 -0
  16. scripts/postprocess.py +279 -0
  17. scripts/preprocess.py +93 -0
  18. scripts/preprocessor_gui.py +729 -0
  19. tme/__init__.py +6 -0
  20. tme/__version__.py +1 -0
  21. tme/analyzer.py +1144 -0
  22. tme/backends/__init__.py +134 -0
  23. tme/backends/cupy_backend.py +309 -0
  24. tme/backends/matching_backend.py +1154 -0
  25. tme/backends/npfftw_backend.py +763 -0
  26. tme/backends/pytorch_backend.py +526 -0
  27. tme/data/__init__.py +0 -0
  28. tme/data/c48n309.npy +0 -0
  29. tme/data/c48n527.npy +0 -0
  30. tme/data/c48n9.npy +0 -0
  31. tme/data/c48u1.npy +0 -0
  32. tme/data/c48u1153.npy +0 -0
  33. tme/data/c48u1201.npy +0 -0
  34. tme/data/c48u1641.npy +0 -0
  35. tme/data/c48u181.npy +0 -0
  36. tme/data/c48u2219.npy +0 -0
  37. tme/data/c48u27.npy +0 -0
  38. tme/data/c48u2947.npy +0 -0
  39. tme/data/c48u3733.npy +0 -0
  40. tme/data/c48u4749.npy +0 -0
  41. tme/data/c48u5879.npy +0 -0
  42. tme/data/c48u7111.npy +0 -0
  43. tme/data/c48u815.npy +0 -0
  44. tme/data/c48u83.npy +0 -0
  45. tme/data/c48u8649.npy +0 -0
  46. tme/data/c600v.npy +0 -0
  47. tme/data/c600vc.npy +0 -0
  48. tme/data/metadata.yaml +80 -0
  49. tme/data/quat_to_numpy.py +42 -0
  50. tme/data/scattering_factors.pickle +0 -0
  51. tme/density.py +2314 -0
  52. tme/extensions.cpython-311-darwin.so +0 -0
  53. tme/helpers.py +881 -0
  54. tme/matching_data.py +377 -0
  55. tme/matching_exhaustive.py +1553 -0
  56. tme/matching_memory.py +382 -0
  57. tme/matching_optimization.py +1123 -0
  58. tme/matching_utils.py +1180 -0
  59. tme/parser.py +429 -0
  60. tme/preprocessor.py +1291 -0
  61. tme/scoring.py +866 -0
  62. tme/structure.py +1428 -0
  63. tme/types.py +10 -0
@@ -0,0 +1,744 @@
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
+ import importlib.util
12
+ from sys import exit
13
+ from time import time
14
+ from copy import deepcopy
15
+ from os.path import abspath
16
+
17
+ import numpy as np
18
+
19
+ from tme import Density, Preprocessor, __version__
20
+ from tme.matching_utils import (
21
+ get_rotation_matrices,
22
+ compute_parallelization_schedule,
23
+ euler_from_rotationmatrix,
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
35
+
36
+
37
+ def get_func_fullname(func) -> str:
38
+ """Returns the full name of the given function, including its module."""
39
+ return f"<function '{func.__module__}.{func.__name__}'>"
40
+
41
+
42
+ def print_block(name: str, data: dict, label_width=20) -> None:
43
+ """Prints a formatted block of information."""
44
+ print(f"\n> {name}")
45
+ for key, value in data.items():
46
+ formatted_value = str(value)
47
+ print(f" - {key + ':':<{label_width}} {formatted_value}")
48
+
49
+
50
+ def print_entry() -> None:
51
+ width = 80
52
+ text = f" pyTME v{__version__} "
53
+ padding_total = width - len(text) - 2
54
+ padding_left = padding_total // 2
55
+ padding_right = padding_total - padding_left
56
+
57
+ print("*" * width)
58
+ print(f"*{ ' ' * padding_left }{text}{ ' ' * padding_right }*")
59
+ print("*" * width)
60
+
61
+
62
+ def check_positive(value):
63
+ ivalue = float(value)
64
+ if ivalue <= 0:
65
+ raise argparse.ArgumentTypeError("%s is an invalid positive float." % value)
66
+ return ivalue
67
+
68
+
69
+ def load_and_validate_mask(mask_target: "Density", mask_path: str, **kwargs):
70
+ """
71
+ Loadsa mask in CCP4/MRC format and assess whether the sampling_rate
72
+ and shape matches its target.
73
+
74
+ Parameters
75
+ ----------
76
+ mask_target : Density
77
+ Object the mask should be applied to
78
+ mask_path : str
79
+ Path to the mask in CCP4/MRC format.
80
+ kwargs : dict, optional
81
+ Keyword arguments passed to :py:meth:`tme.density.Density.from_file`.
82
+ Raise
83
+ -----
84
+ ValueError
85
+ If shape or sampling rate do not match between mask_target and mask
86
+
87
+ Returns
88
+ -------
89
+ Density
90
+ A density instance if the mask was validated and loaded otherwise None
91
+ """
92
+ mask = mask_path
93
+ if mask is not None:
94
+ mask = Density.from_file(mask, **kwargs)
95
+ mask.origin = deepcopy(mask_target.origin)
96
+ if not np.allclose(mask.shape, mask_target.shape):
97
+ raise ValueError(
98
+ f"Expected shape of {mask_path} was {mask_target.shape},"
99
+ f" got f{mask.shape}"
100
+ )
101
+ if not np.allclose(mask.sampling_rate, mask_target.sampling_rate):
102
+ raise ValueError(
103
+ f"Expected sampling_rate of {mask_path} was {mask_target.sampling_rate}"
104
+ f", got f{mask.sampling_rate}"
105
+ )
106
+ return mask
107
+
108
+
109
+ def crop_data(data: Density, cutoff: float, data_mask: Density = None) -> bool:
110
+ """
111
+ Crop the provided data and mask to a smaller box based on a cutoff value.
112
+
113
+ Parameters
114
+ ----------
115
+ data : Density
116
+ The data that should be cropped.
117
+ cutoff : float
118
+ The threshold value to determine which parts of the data should be kept.
119
+ data_mask : Density, optional
120
+ A mask for the data that should be cropped.
121
+
122
+ Returns
123
+ -------
124
+ bool
125
+ Returns True if the data was adjusted (cropped), otherwise returns False.
126
+
127
+ Notes
128
+ -----
129
+ Cropping is performed in place.
130
+ """
131
+ if cutoff is None:
132
+ return False
133
+
134
+ box = data.trim_box(cutoff=cutoff)
135
+ box_mask = box
136
+ if data_mask is not None:
137
+ box_mask = data_mask.trim_box(cutoff=cutoff)
138
+ box = tuple(
139
+ slice(min(arr.start, mask.start), max(arr.stop, mask.stop))
140
+ for arr, mask in zip(box, box_mask)
141
+ )
142
+ if box == tuple(slice(0, x) for x in data.shape):
143
+ return False
144
+
145
+ data.adjust_box(box)
146
+
147
+ if data_mask:
148
+ data_mask.adjust_box(box)
149
+
150
+ return True
151
+
152
+
153
+ def parse_args():
154
+ parser = argparse.ArgumentParser(description="Perform template matching.")
155
+ parser.add_argument(
156
+ "-m",
157
+ "--target",
158
+ dest="target",
159
+ type=str,
160
+ required=True,
161
+ help="Path to a target in CCP4/MRC format.",
162
+ )
163
+ parser.add_argument(
164
+ "--target_mask",
165
+ dest="target_mask",
166
+ type=str,
167
+ required=False,
168
+ help="Path to a mask for the target target in CCP4/MRC format.",
169
+ )
170
+ parser.add_argument(
171
+ "--cutoff_target",
172
+ dest="cutoff_target",
173
+ type=float,
174
+ required=False,
175
+ help="Target contour level (used for cropping).",
176
+ default=None,
177
+ )
178
+ parser.add_argument(
179
+ "--cutoff_template",
180
+ dest="cutoff_template",
181
+ type=float,
182
+ required=False,
183
+ help="Template contour level (used for cropping).",
184
+ default=None,
185
+ )
186
+ parser.add_argument(
187
+ "-i",
188
+ "--template",
189
+ dest="template",
190
+ type=str,
191
+ required=True,
192
+ help="Path to a template in PDB/MMCIF or CCP4/MRC format.",
193
+ )
194
+ parser.add_argument(
195
+ "--template_mask",
196
+ dest="template_mask",
197
+ type=str,
198
+ required=False,
199
+ help="Path to a mask for the template in CCP4/MRC format.",
200
+ )
201
+ parser.add_argument(
202
+ "-o",
203
+ dest="output",
204
+ type=str,
205
+ required=False,
206
+ default="output.pickle",
207
+ help="Path to output pickle file.",
208
+ )
209
+ parser.add_argument(
210
+ "-s",
211
+ dest="score",
212
+ type=str,
213
+ default="FLCSphericalMask",
214
+ help="Template matching scoring function.",
215
+ choices=MATCHING_EXHAUSTIVE_REGISTER.keys(),
216
+ )
217
+ parser.add_argument(
218
+ "-n",
219
+ dest="cores",
220
+ required=False,
221
+ type=int,
222
+ default=4,
223
+ help="Number of cores used for template matching.",
224
+ )
225
+ parser.add_argument(
226
+ "-r",
227
+ "--ram",
228
+ dest="memory",
229
+ required=False,
230
+ type=int,
231
+ default=None,
232
+ help="Amount of memory that can be used in bytes.",
233
+ )
234
+ parser.add_argument(
235
+ "--memory_scaling",
236
+ dest="memory_scaling",
237
+ required=False,
238
+ type=check_positive,
239
+ default=0.85,
240
+ help="Fraction of available memory that can be used."
241
+ "Defaults to 0.85. Ignored if --ram is set",
242
+ )
243
+ parser.add_argument(
244
+ "-a",
245
+ dest="angular_sampling",
246
+ type=check_positive,
247
+ default=40.0,
248
+ help="Angular sampling rate for template matching. "
249
+ "A lower number yields more rotations.",
250
+ )
251
+ parser.add_argument(
252
+ "-p",
253
+ dest="peak_calling",
254
+ action="store_true",
255
+ default=False,
256
+ help="When set perform peak calling instead of score aggregation.",
257
+ )
258
+ parser.add_argument(
259
+ "--use_gpu",
260
+ dest="use_gpu",
261
+ action="store_true",
262
+ default=False,
263
+ help="Whether to perform computations on the GPU.",
264
+ )
265
+ parser.add_argument(
266
+ "--gpu_indices",
267
+ dest="gpu_indices",
268
+ type=str,
269
+ default=None,
270
+ help="Comma-separated list of GPU indices to use. For example,"
271
+ " 0,1 for the first and second GPU. Only used if --use_gpu is set."
272
+ " If not provided but --use_gpu is set, CUDA_VISIBLE_DEVICES will"
273
+ " be respected.",
274
+ )
275
+ parser.add_argument(
276
+ "--invert_target_contrast",
277
+ dest="invert_target_contrast",
278
+ action="store_true",
279
+ default=False,
280
+ help="Invert the target contrast via multiplication with negative one and"
281
+ " linear rescaling between zero and one. Note that this might lead to"
282
+ " different baseline scores of individual target splits when using"
283
+ " unnormalized scores. This option is intended for targets, where the"
284
+ " object to-be-matched has negative values, i.e. tomograms.",
285
+ )
286
+ parser.add_argument(
287
+ "--no_edge_padding",
288
+ dest="no_edge_padding",
289
+ action="store_true",
290
+ default=False,
291
+ help="Whether to pad the edges of the target. This is useful, if the target"
292
+ " has a well defined bounding box, e.g. a density map.",
293
+ )
294
+ parser.add_argument(
295
+ "--no_fourier_padding",
296
+ dest="no_fourier_padding",
297
+ action="store_true",
298
+ default=False,
299
+ help="Whether input arrays should be zero-padded to the full convolution shape"
300
+ " for numerical stability. When working with very large targets such as"
301
+ " tomograms it is safe to use this flag and benefit from the performance gain.",
302
+ )
303
+ parser.add_argument(
304
+ "--scramble_phases",
305
+ dest="scramble_phases",
306
+ action="store_true",
307
+ default=False,
308
+ help="Whether to phase scramble the template for subsequent normalization.",
309
+ )
310
+ parser.add_argument(
311
+ "--interpolation_order",
312
+ dest="interpolation_order",
313
+ required=False,
314
+ type=int,
315
+ default=3,
316
+ help="Spline interpolation used during rotations. If less than zero"
317
+ " no interpolation is performed.",
318
+ )
319
+ parser.add_argument(
320
+ "--use_mixed_precision",
321
+ dest="use_mixed_precision",
322
+ action="store_true",
323
+ default=False,
324
+ help="Use float16 for real values operations where possible.",
325
+ )
326
+ parser.add_argument(
327
+ "--use_memmap",
328
+ dest="use_memmap",
329
+ action="store_true",
330
+ default=False,
331
+ help="Use memmaps to offload large data objects to disk. This is"
332
+ " particularly useful for large inputs when using --use_gpu..",
333
+ )
334
+ parser.add_argument(
335
+ "--temp_directory",
336
+ dest="temp_directory",
337
+ default=None,
338
+ help="Directory for temporary objects. Faster I/O typically improves runtime.",
339
+ )
340
+ parser.add_argument(
341
+ "--gaussian_sigma",
342
+ dest="gaussian_sigma",
343
+ type=float,
344
+ required=False,
345
+ help="Sigma parameter for Gaussian filtering the template.",
346
+ )
347
+ parser.add_argument(
348
+ "--bandpass_band",
349
+ dest="bandpass_band",
350
+ type=str,
351
+ required=False,
352
+ help="Comma separated start and stop frequency for bandpass filtering the"
353
+ " template, e.g. 0.1, 0.5",
354
+ )
355
+ parser.add_argument(
356
+ "--bandpass_smooth",
357
+ dest="bandpass_smooth",
358
+ type=float,
359
+ required=False,
360
+ default=None,
361
+ help="Smooth parameter for the bandpass filter.",
362
+ )
363
+
364
+ parser.add_argument(
365
+ "--tilt_range",
366
+ dest="tilt_range",
367
+ type=str,
368
+ required=False,
369
+ help="Comma separated start and stop stage tilt angle, e.g. '50,45'. Used"
370
+ " to create a wedge mask to be applied to the template.",
371
+ )
372
+ parser.add_argument(
373
+ "--tilt_step",
374
+ dest="tilt_step",
375
+ type=float,
376
+ required=False,
377
+ default=None,
378
+ help="Step size between tilts, e.g. '5'. When set a more accurate"
379
+ " wedge mask will be computed.",
380
+ )
381
+ parser.add_argument(
382
+ "--wedge_smooth",
383
+ dest="wedge_smooth",
384
+ type=float,
385
+ required=False,
386
+ default=None,
387
+ help="Gaussian sigma used to smooth the wedge mask.",
388
+ )
389
+
390
+ args = parser.parse_args()
391
+
392
+ if args.interpolation_order < 0:
393
+ args.interpolation_order = None
394
+
395
+ if args.temp_directory is None:
396
+ default = abspath(".")
397
+ if os.environ.get("TMPDIR", None) is not None:
398
+ default = os.environ.get("TMPDIR")
399
+ args.temp_directory = default
400
+
401
+ os.environ["TMPDIR"] = args.temp_directory
402
+
403
+ args.pad_target_edges = not args.no_edge_padding
404
+ args.pad_fourier = not args.no_fourier_padding
405
+
406
+ if args.score not in MATCHING_EXHAUSTIVE_REGISTER:
407
+ raise ValueError(
408
+ f"score has to be one of {', '.join(MATCHING_EXHAUSTIVE_REGISTER.keys())}"
409
+ )
410
+
411
+ gpu_devices = os.environ.get("CUDA_VISIBLE_DEVICES", None)
412
+ if args.gpu_indices is not None:
413
+ os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu_indices
414
+
415
+ if args.use_gpu:
416
+ gpu_devices = os.environ.get("CUDA_VISIBLE_DEVICES", None)
417
+ if gpu_devices is None:
418
+ print(
419
+ "No GPU indices provided and CUDA_VISIBLE_DEVICES is not set.",
420
+ "Assuming device 0.",
421
+ )
422
+ os.environ["CUDA_VISIBLE_DEVICES"] = "0"
423
+ args.gpu_indices = [
424
+ int(x) for x in os.environ["CUDA_VISIBLE_DEVICES"].split(",")
425
+ ]
426
+
427
+ return args
428
+
429
+
430
+ def main():
431
+ args = parse_args()
432
+ print_entry()
433
+
434
+ target = Density.from_file(args.target, use_memmap=True)
435
+
436
+ try:
437
+ template = Density.from_file(args.template)
438
+ except Exception:
439
+ template = Density.from_structure(
440
+ filename_or_structure=args.template,
441
+ sampling_rate=target.sampling_rate,
442
+ )
443
+
444
+ if not np.allclose(target.sampling_rate, template.sampling_rate):
445
+ print(
446
+ f"Resampling template to {target.sampling_rate}. "
447
+ "Consider providing a template with the same sampling rate as the target."
448
+ )
449
+ template = template.resample(target.sampling_rate, order=3)
450
+
451
+ template_mask = load_and_validate_mask(
452
+ mask_target=template, mask_path=args.template_mask
453
+ )
454
+ target_mask = load_and_validate_mask(
455
+ mask_target=target, mask_path=args.target_mask, use_memmap=True
456
+ )
457
+
458
+ initial_shape = target.shape
459
+ is_cropped = crop_data(
460
+ data=target, data_mask=target_mask, cutoff=args.cutoff_target
461
+ )
462
+ print_block(
463
+ name="Target",
464
+ data={
465
+ "Initial Shape": initial_shape,
466
+ "Sampling Rate": tuple(np.round(target.sampling_rate, 2)),
467
+ "Final Shape": target.shape,
468
+ },
469
+ )
470
+ if is_cropped:
471
+ args.target = generate_tempfile_name(suffix=".mrc")
472
+ target.to_file(args.target)
473
+
474
+ if target_mask:
475
+ args.target_mask = generate_tempfile_name(suffix=".mrc")
476
+ target_mask.to_file(args.target_mask)
477
+ print_block(
478
+ name="Target Mask",
479
+ data={
480
+ "Initial Shape": initial_shape,
481
+ "Sampling Rate": tuple(np.round(target_mask.sampling_rate, 2)),
482
+ "Final Shape": target_mask.shape,
483
+ },
484
+ )
485
+
486
+ initial_shape = template.shape
487
+ _ = crop_data(data=template, data_mask=template_mask, cutoff=args.cutoff_template)
488
+ template, translation = template.centered(0)
489
+ print_block(
490
+ name="Template",
491
+ data={
492
+ "Initial Shape": initial_shape,
493
+ "Sampling Rate": tuple(np.round(template.sampling_rate, 2)),
494
+ "Final Shape": template.shape,
495
+ },
496
+ )
497
+
498
+ template_filter = {}
499
+ if args.gaussian_sigma is not None:
500
+ template.data = Preprocessor().gaussian_filter(
501
+ sigma=args.gaussian_sigma, template=template.data
502
+ )
503
+
504
+ if args.bandpass_band is not None:
505
+ bandpass_start, bandpass_stop = [
506
+ float(x) for x in args.bandpass_band.split(",")
507
+ ]
508
+ if args.bandpass_smooth is None:
509
+ args.bandpass_smooth = 0
510
+
511
+ template_filter["bandpass_mask"] = {
512
+ "minimum_frequency": bandpass_start,
513
+ "maximum_frequency": bandpass_stop,
514
+ "gaussian_sigma": args.bandpass_smooth,
515
+ }
516
+
517
+ if args.tilt_range is not None:
518
+ args.wedge_smooth if args.wedge_smooth is not None else 0
519
+ tilt_start, tilt_stop = [float(x) for x in args.tilt_range.split(",")]
520
+
521
+ if args.tilt_step is not None:
522
+ tilt_angles = np.arange(
523
+ -tilt_start, tilt_stop + args.tilt_step, args.tilt_step
524
+ )
525
+ angles = np.zeros((template.data.ndim, tilt_angles.size))
526
+ angles[2, :] = tilt_angles
527
+ template_filter["wedge_mask"] = {
528
+ "tilt_angles": angles,
529
+ "sigma": args.wedge_smooth,
530
+ }
531
+ else:
532
+ template_filter["continuous_wedge_mask"] = {
533
+ "start_tilt": tilt_start,
534
+ "stop_tilt": tilt_stop,
535
+ "tilt_axis": 1,
536
+ "infinite_plane": True,
537
+ "sigma": args.wedge_smooth,
538
+ }
539
+
540
+ if template_mask is None:
541
+ enclosing_box = template.minimum_enclosing_box(0, use_geometric_center=False)
542
+ template_mask = template.empty
543
+ template_mask.adjust_box(enclosing_box)
544
+ template_mask.data[:] = 1
545
+ translation = np.zeros_like(translation)
546
+
547
+ template_mask.pad(template.shape, center=False)
548
+ origin_translation = np.divide(
549
+ np.subtract(template.origin, template_mask.origin), template.sampling_rate
550
+ )
551
+ translation = np.add(translation, origin_translation)
552
+
553
+ template_mask = template_mask.rigid_transform(
554
+ rotation_matrix=np.eye(template_mask.data.ndim),
555
+ translation=-translation,
556
+ )
557
+
558
+ print_block(
559
+ name="Template Mask",
560
+ data={
561
+ "Inital Shape": initial_shape,
562
+ "Sampling Rate": tuple(np.round(template_mask.sampling_rate, 2)),
563
+ "Final Shape": template_mask.shape,
564
+ },
565
+ )
566
+ print("\n" + "-" * 80)
567
+
568
+ if args.scramble_phases:
569
+ template.data = scramble_phases(template.data, noise_proportion=1.0)
570
+
571
+ available_memory = backend.get_available_memory()
572
+ if args.use_gpu:
573
+ args.cores = len(args.gpu_indices)
574
+ has_torch = importlib.util.find_spec("torch") is not None
575
+ has_cupy = importlib.util.find_spec("cupy") is not None
576
+
577
+ if not has_torch and not has_cupy:
578
+ raise ValueError(
579
+ "Found neither CuPy nor PyTorch installation. You need to install"
580
+ " either to enable GPU support."
581
+ )
582
+
583
+ if args.peak_calling:
584
+ preferred_backend = "pytorch"
585
+ if not has_torch:
586
+ preferred_backend = "cupy"
587
+ backend.change_backend(backend_name=preferred_backend, device="cuda")
588
+ else:
589
+ preferred_backend = "cupy"
590
+ if not has_cupy:
591
+ preferred_backend = "pytorch"
592
+ backend.change_backend(backend_name=preferred_backend, device="cuda")
593
+ if args.use_mixed_precision and preferred_backend == "pytorch":
594
+ raise NotImplementedError(
595
+ "pytorch backend does not yet support mixed precision."
596
+ " Consider installing CuPy to enable this feature."
597
+ )
598
+ elif args.use_mixed_precision:
599
+ backend.change_backend(
600
+ backend_name="cupy",
601
+ default_dtype=backend._array_backend.float16,
602
+ complex_dtype=backend._array_backend.complex64,
603
+ default_dtype_int=backend._array_backend.int16,
604
+ )
605
+ available_memory = backend.get_available_memory() * args.cores
606
+
607
+ if args.memory is None:
608
+ args.memory = int(args.memory_scaling * available_memory)
609
+
610
+ target_padding = np.zeros_like(template.shape)
611
+ if args.pad_target_edges:
612
+ target_padding = template.shape
613
+
614
+ template_box = template.shape
615
+ if not args.pad_fourier:
616
+ template_box = np.ones(len(template_box), dtype=int)
617
+
618
+ callback_class = MaxScoreOverRotations
619
+ if args.peak_calling:
620
+ callback_class = PeakCallerMaximumFilter
621
+
622
+ splits, schedule = compute_parallelization_schedule(
623
+ shape1=target.shape,
624
+ shape2=template_box,
625
+ shape1_padding=target_padding,
626
+ max_cores=args.cores,
627
+ max_ram=args.memory,
628
+ split_only_outer=args.use_gpu,
629
+ matching_method=args.score,
630
+ analyzer_method=callback_class.__name__,
631
+ backend=backend._backend_name,
632
+ float_nbytes=backend.datatype_bytes(backend._default_dtype),
633
+ complex_nbytes=backend.datatype_bytes(backend._complex_dtype),
634
+ integer_nbytes=backend.datatype_bytes(backend._default_dtype_int),
635
+ )
636
+
637
+ if splits is None:
638
+ print(
639
+ "Found no suitable parallelization schedule. Consider increasing"
640
+ " available RAM or decreasing number of cores."
641
+ )
642
+ exit(-1)
643
+
644
+ analyzer_args = {
645
+ "score_threshold": 0.0,
646
+ "number_of_peaks": 1000,
647
+ "convolution_mode": "valid",
648
+ "use_memmap": args.use_memmap,
649
+ }
650
+
651
+ matching_setup, matching_score = MATCHING_EXHAUSTIVE_REGISTER[args.score]
652
+ matching_data = MatchingData(target=target, template=template.data)
653
+ matching_data.rotations = get_rotation_matrices(
654
+ angular_sampling=args.angular_sampling, dim=target.data.ndim
655
+ )
656
+
657
+ matching_data.template_filter = template_filter
658
+ matching_data._invert_target = args.invert_target_contrast
659
+ if target_mask is not None:
660
+ matching_data.target_mask = target_mask
661
+ if template_mask is not None:
662
+ matching_data.template_mask = template_mask.data
663
+
664
+ n_splits = np.prod(list(splits.values()))
665
+ target_split = ", ".join(
666
+ [":".join([str(x) for x in axis]) for axis in splits.items()]
667
+ )
668
+ gpus_used = 0 if args.gpu_indices is None else len(args.gpu_indices)
669
+ options = {
670
+ "CPU Cores": args.cores,
671
+ "Run on GPU": f"{args.use_gpu} [N={gpus_used}]",
672
+ "Use Mixed Precision": args.use_mixed_precision,
673
+ "Assigned Memory [MB]": f"{args.memory // 1e6} [out of {available_memory//1e6}]",
674
+ "Temporary Directory": args.temp_directory,
675
+ "Extend Fourier Grid": not args.no_fourier_padding,
676
+ "Extend Target Edges": not args.no_edge_padding,
677
+ "Interpolation Order": args.interpolation_order,
678
+ "Score": f"{args.score}",
679
+ "Setup Function": f"{get_func_fullname(matching_setup)}",
680
+ "Scoring Function": f"{get_func_fullname(matching_score)}",
681
+ "Angular Sampling": f"{args.angular_sampling}"
682
+ f" [{matching_data.rotations.shape[0]} rotations]",
683
+ "Scramble Template": args.scramble_phases,
684
+ "Target Splits": f"{target_split} [N={n_splits}]",
685
+ }
686
+
687
+ print_block(
688
+ name="Template Matching Options",
689
+ data=options,
690
+ label_width=max(len(key) for key in options.keys()) + 2,
691
+ )
692
+
693
+ options = {"Analyzer": callback_class, **analyzer_args}
694
+ print_block(
695
+ name="Score Analysis Options",
696
+ data=options,
697
+ label_width=max(len(key) for key in options.keys()) + 2,
698
+ )
699
+ print("\n" + "-" * 80)
700
+
701
+ outer_jobs = f"{schedule[0]} job{'s' if schedule[0] > 1 else ''}"
702
+ inner_jobs = f"{schedule[1]} core{'s' if schedule[1] > 1 else ''}"
703
+ n_splits = f"{n_splits} split{'s' if n_splits > 1 else ''}"
704
+ print(f"\nDistributing {n_splits} on {outer_jobs} each using {inner_jobs}.")
705
+
706
+ start = time()
707
+ print("Running Template Matching. This might take a while ...")
708
+ candidates = scan_subsets(
709
+ matching_data=matching_data,
710
+ job_schedule=schedule,
711
+ matching_score=matching_score,
712
+ matching_setup=matching_setup,
713
+ callback_class=callback_class,
714
+ callback_class_args=analyzer_args,
715
+ target_splits=splits,
716
+ pad_target_edges=args.pad_target_edges,
717
+ pad_fourier=args.pad_fourier,
718
+ interpolation_order=args.interpolation_order,
719
+ )
720
+
721
+ candidates = list(candidates) if candidates is not None else []
722
+ if callback_class == MaxScoreOverRotations:
723
+ if target_mask is not None and args.score != "MCC":
724
+ candidates[0] *= target_mask.data
725
+ with warnings.catch_warnings():
726
+ warnings.simplefilter("ignore", category=UserWarning)
727
+ candidates[3] = {
728
+ x: euler_from_rotationmatrix(
729
+ np.frombuffer(i, dtype=matching_data.rotations.dtype).reshape(
730
+ candidates[0].ndim, candidates[0].ndim
731
+ )
732
+ )
733
+ for i, x in candidates[3].items()
734
+ }
735
+
736
+ candidates.append((target.origin, template.origin, target.sampling_rate, args))
737
+ write_pickle(data=candidates, filename=args.output)
738
+
739
+ runtime = time() - start
740
+ print(f"\nRuntime real: {runtime:.3f}s user: {(runtime * args.cores):.3f}s.")
741
+
742
+
743
+ if __name__ == "__main__":
744
+ main()