tm2d 0.2.1__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. tm2d-0.4.0/PKG-INFO +59 -0
  2. tm2d-0.4.0/README.md +39 -0
  3. {tm2d-0.2.1 → tm2d-0.4.0}/pyproject.toml +3 -1
  4. {tm2d-0.2.1 → tm2d-0.4.0}/tm2d/__init__.py +4 -0
  5. {tm2d-0.2.1 → tm2d-0.4.0}/tm2d/base_comparator.py +2 -2
  6. tm2d-0.4.0/tm2d/base_results.py +70 -0
  7. tm2d-0.4.0/tm2d/base_template.py +112 -0
  8. tm2d-0.4.0/tm2d/comparators/cross_correlation.py +664 -0
  9. tm2d-0.4.0/tm2d/comparators/fused_conv.py +114 -0
  10. tm2d-0.4.0/tm2d/ctf/ctf.py +269 -0
  11. {tm2d-0.2.1 → tm2d-0.4.0}/tm2d/ctf/ctf_params.py +27 -21
  12. {tm2d-0.2.1 → tm2d-0.4.0}/tm2d/ctf/ctf_set.py +13 -7
  13. tm2d-0.4.0/tm2d/limits.py +22 -0
  14. tm2d-0.4.0/tm2d/plan.py +423 -0
  15. tm2d-0.4.0/tm2d/prefilter.py +90 -0
  16. tm2d-0.4.0/tm2d/results/per_param.py +262 -0
  17. tm2d-0.4.0/tm2d/results/per_pixel.py +348 -0
  18. {tm2d-0.2.1 → tm2d-0.4.0}/tm2d/templates/atomic.py +64 -38
  19. {tm2d-0.2.1 → tm2d-0.4.0}/tm2d/templates/density.py +111 -55
  20. tm2d-0.4.0/tm2d/weights.py +64 -0
  21. tm2d-0.4.0/tm2d.egg-info/PKG-INFO +59 -0
  22. {tm2d-0.2.1 → tm2d-0.4.0}/tm2d.egg-info/SOURCES.txt +4 -0
  23. {tm2d-0.2.1 → tm2d-0.4.0}/tm2d.egg-info/requires.txt +1 -0
  24. tm2d-0.2.1/PKG-INFO +0 -91
  25. tm2d-0.2.1/README.md +0 -72
  26. tm2d-0.2.1/tm2d/base_results.py +0 -23
  27. tm2d-0.2.1/tm2d/base_template.py +0 -78
  28. tm2d-0.2.1/tm2d/comparators/cross_correlation.py +0 -141
  29. tm2d-0.2.1/tm2d/ctf/ctf.py +0 -207
  30. tm2d-0.2.1/tm2d/plan.py +0 -261
  31. tm2d-0.2.1/tm2d/results/per_param.py +0 -138
  32. tm2d-0.2.1/tm2d/results/per_pixel.py +0 -215
  33. tm2d-0.2.1/tm2d.egg-info/PKG-INFO +0 -91
  34. {tm2d-0.2.1 → tm2d-0.4.0}/LICENSE +0 -0
  35. {tm2d-0.2.1 → tm2d-0.4.0}/setup.cfg +0 -0
  36. {tm2d-0.2.1 → tm2d-0.4.0}/tm2d/param_set.py +0 -0
  37. {tm2d-0.2.1 → tm2d-0.4.0}/tm2d.egg-info/dependency_links.txt +0 -0
  38. {tm2d-0.2.1 → tm2d-0.4.0}/tm2d.egg-info/top_level.txt +0 -0
tm2d-0.4.0/PKG-INFO ADDED
@@ -0,0 +1,59 @@
1
+ Metadata-Version: 2.4
2
+ Name: tm2d
3
+ Version: 0.4.0
4
+ Summary: A Python module for 2D template matching
5
+ Author-email: Shahar Sandhaus <shahar.sandhaus@berkeley.edu>, Petar Petrov <ppetrov@berkeley.edu>
6
+ Project-URL: Homepage, https://github.com/sharhar/tm2d
7
+ Project-URL: Issues, https://github.com/sharhar/tm2d/issues
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Development Status :: 2 - Pre-Alpha
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: setuptools>=59.0
16
+ Requires-Dist: numpy
17
+ Requires-Dist: tqdm
18
+ Requires-Dist: vkdispatch==0.1.0
19
+ Dynamic: license-file
20
+
21
+ # tm2d
22
+
23
+ `tm2d` is a Python package for GPU-accelerated 2D template matching. It contains the core algorithmic pieces: templates, CTF parameter handling, parameter grids, comparators, result containers, and execution plans.
24
+
25
+ Higher-level workflow code, file loading helpers, plotting utilities, and analysis scripts belong in `tm2d-utils` or downstream project code.
26
+
27
+ ## Dependencies
28
+
29
+ Runtime dependencies are listed in `pyproject.toml`:
30
+
31
+ - Python >= 3.9
32
+ - `numpy`
33
+ - `tqdm`
34
+ - `vkdispatch==0.1.0`
35
+ - `setuptools>=59.0`
36
+
37
+ A working Vulkan/vkdispatch setup is required to run template matching.
38
+
39
+ ## Installation
40
+
41
+ From a local checkout:
42
+
43
+ ```bash
44
+ cd /path/to/tm2d
45
+ python -m pip install .
46
+ ```
47
+
48
+ For development, install in editable mode:
49
+
50
+ ```bash
51
+ cd /path/to/tm2d
52
+ python -m pip install -e .
53
+ ```
54
+
55
+ To verify the installed package version:
56
+
57
+ ```bash
58
+ python -m pip show tm2d
59
+ ```
tm2d-0.4.0/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # tm2d
2
+
3
+ `tm2d` is a Python package for GPU-accelerated 2D template matching. It contains the core algorithmic pieces: templates, CTF parameter handling, parameter grids, comparators, result containers, and execution plans.
4
+
5
+ Higher-level workflow code, file loading helpers, plotting utilities, and analysis scripts belong in `tm2d-utils` or downstream project code.
6
+
7
+ ## Dependencies
8
+
9
+ Runtime dependencies are listed in `pyproject.toml`:
10
+
11
+ - Python >= 3.9
12
+ - `numpy`
13
+ - `tqdm`
14
+ - `vkdispatch==0.1.0`
15
+ - `setuptools>=59.0`
16
+
17
+ A working Vulkan/vkdispatch setup is required to run template matching.
18
+
19
+ ## Installation
20
+
21
+ From a local checkout:
22
+
23
+ ```bash
24
+ cd /path/to/tm2d
25
+ python -m pip install .
26
+ ```
27
+
28
+ For development, install in editable mode:
29
+
30
+ ```bash
31
+ cd /path/to/tm2d
32
+ python -m pip install -e .
33
+ ```
34
+
35
+ To verify the installed package version:
36
+
37
+ ```bash
38
+ python -m pip show tm2d
39
+ ```
@@ -4,9 +4,10 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "tm2d"
7
- version = "0.2.1"
7
+ version = "0.4.0"
8
8
  authors = [
9
9
  { name="Shahar Sandhaus", email="shahar.sandhaus@berkeley.edu" },
10
+ { name="Petar Petrov", email="ppetrov@berkeley.edu" },
10
11
  ]
11
12
  description = "A Python module for 2D template matching"
12
13
  readme = "README.md"
@@ -20,6 +21,7 @@ classifiers = [
20
21
  dependencies = [
21
22
  "setuptools>=59.0",
22
23
  "numpy",
24
+ "tqdm",
23
25
  "vkdispatch==0.1.0"
24
26
  ]
25
27
 
@@ -6,11 +6,13 @@ from .templates.atomic import TemplateAtomic
6
6
  from .templates.density import TemplateDensity
7
7
 
8
8
  from .comparators.cross_correlation import ComparatorCrossCorrelation
9
+ from .weights import RadialWeights
9
10
 
10
11
  from .results.per_pixel import ResultsPixel
11
12
  from .results.per_param import ResultsParam
12
13
 
13
14
  from .param_set import ParamSet, make_param_set
15
+ from . import prefilter
14
16
 
15
17
  from .plan import Plan, Template, Comparator, Results
16
18
 
@@ -23,6 +25,7 @@ __all__ = [
23
25
  "TemplateAtomic",
24
26
  "TemplateDensity",
25
27
  "ComparatorCrossCorrelation",
28
+ "RadialWeights",
26
29
  "ResultsPixel",
27
30
  "ResultsParam",
28
31
  "Plan",
@@ -31,4 +34,5 @@ __all__ = [
31
34
  "Results",
32
35
  "ParamSet",
33
36
  "make_param_set",
37
+ "prefilter",
34
38
  ]
@@ -5,11 +5,11 @@ class Comparator:
5
5
  def __init__(self):
6
6
  raise NotImplementedError("Comparator is an abstract class. Please implement it in a subclass.")
7
7
 
8
- def set_data(self, data: np.ndarray):
8
+ def set_data(self, data: np.ndarray, weights: np.ndarray = None):
9
9
  """
10
10
  This method should set the data buffer that will be used for comparison.
11
11
  """
12
12
  raise NotImplementedError("set_data must be implemented in a subclass.")
13
13
 
14
- def compare_template(self, template: vd.RFFTBuffer, normalize: bool = True) -> vd.RFFTBuffer:
14
+ def compare_template(self, template: vd.RFFTBuffer, normalize: bool = True, output_radius: int = None) -> vd.RFFTBuffer:
15
15
  raise NotImplementedError("compare_template must be implemented in a subclass.")
@@ -0,0 +1,70 @@
1
+ import numpy as np
2
+ import vkdispatch as vd
3
+ import vkdispatch.codegen as vc
4
+
5
+ def valid_center_range(n: int, m: int) -> tuple:
6
+ """Inclusive range of map indices (results maps, centered convention) at which a template of size m lies fully
7
+ inside an image of size n. A template with top-left corner at t peaks at index t + m // 2 (the micrograph pixel
8
+ under the template's center, for even and odd n), and t runs over 0 .. n - m (a "valid" correlation: the template lies fully inside the image).
9
+ Results maps are the raw circular correlation fftshifted: map index i = (raw index + n // 2) % n."""
10
+ lo = m // 2
11
+ return lo, lo + n - m
12
+
13
+ class Results:
14
+ def __init__(self):
15
+ raise NotImplementedError("Results is an abstract class. Please implement it in a subclass.")
16
+
17
+ def check_comparison(self, comparison_buffer: vd.RFFTBuffer, rotation_weights: vc.Var[vc.f32], *indices: vc.Var[vc.i32]):
18
+ raise NotImplementedError("check_comparison must be implemented in a subclass.")
19
+
20
+ def reset(self):
21
+ """
22
+ Reset the results to their initial state.
23
+ This method should be implemented in subclasses to reset any internal state.
24
+ """
25
+ raise NotImplementedError("reset must be implemented in a subclass.")
26
+
27
+ template_shape = None
28
+ output_radius = None
29
+ exclude_edges_setting = "auto"
30
+ score_norms = None
31
+ score_norm_inv_n = 1.0
32
+
33
+ def set_score_norms(self, score_norms, inv_n: float = 1.0):
34
+ """Called by Plan before check_comparison: a (micrographs * templates,) float buffer of sum_s w |T|^2 that the
35
+ comparator left to the results stage (fused norms): each score is multiplied by 1 / sqrt(norm * inv_n).
36
+ None if the maps are already scaled."""
37
+ self.score_norms = score_norms
38
+ self.score_norm_inv_n = float(inv_n)
39
+
40
+ def set_template_shape(self, template_shape: tuple):
41
+ """Called by Plan before check_comparison: the (h, w) template box, used to mark map positions where the
42
+ template crosses the image edge (and so wraps around onto the opposite edge) as invalid."""
43
+ self.template_shape = (int(template_shape[0]), int(template_shape[1]))
44
+
45
+ @staticmethod
46
+ def _check_edge_setting(exclude_edges):
47
+ if exclude_edges == "auto" or isinstance(exclude_edges, (bool, np.bool_)):
48
+ return exclude_edges if exclude_edges == "auto" else bool(exclude_edges)
49
+ raise ValueError(f"exclude_edges must be True, False or 'auto', not {exclude_edges!r}")
50
+
51
+ def edges_excluded(self, image_shape: tuple) -> bool:
52
+ """Whether positions where the template crosses the image edge are excluded, for an (H, W) image.
53
+ exclude_edges=True / False as given; "auto" (default): excluded for micrograph searches (template smaller than
54
+ the image in both dimensions, no output_radius; valid positions only), not for particle boxes (template as
55
+ large as the image, or a local search with output_radius: every position is scored, the circular
56
+ correlation)."""
57
+ if self.exclude_edges_setting is True and self.template_shape is None:
58
+ raise ValueError("exclude_edges=True needs the template shape: call set_template_shape() (Plan does)")
59
+ if self.exclude_edges_setting != "auto":
60
+ return bool(self.exclude_edges_setting)
61
+ if self.template_shape is None or self.output_radius is not None:
62
+ return False
63
+ return self.template_shape[0] < int(image_shape[0]) and self.template_shape[1] < int(image_shape[1])
64
+
65
+ def compile_results(self, templates_count: int, total_weight: float = None):
66
+ """
67
+ Compile the results after all comparisons have been made.
68
+ This method should be implemented in subclasses to compile the results into a final form that can be easily accessed.
69
+ """
70
+ raise NotImplementedError("compile_results must be implemented in a subclass.")
@@ -0,0 +1,112 @@
1
+ import vkdispatch as vd
2
+ import vkdispatch.codegen as vc
3
+ import numpy as np
4
+
5
+ from typing import Union, List, Tuple
6
+ from .ctf.ctf import CTFParams
7
+
8
+ def per_slot_rotations(rotations, template_count: int) -> list:
9
+ """The rotation of each of the template_count slots of a template batch, as a list.
10
+
11
+ rotations: a list with one entry (graph variable or 4x4 matrix) per slot; a single graph variable or 4x4
12
+ matrix (all slots share it); or an (N, 4, 4) array with N == 1 (shared) or N == template_count (one each)."""
13
+ if isinstance(rotations, (list, tuple)):
14
+ if len(rotations) != template_count:
15
+ raise ValueError(f"{len(rotations)} rotations given for {template_count} template slots")
16
+ return list(rotations)
17
+ if isinstance(rotations, np.ndarray):
18
+ if rotations.ndim == 2:
19
+ return [rotations] * template_count
20
+ if rotations.shape[0] == 1:
21
+ return [rotations[0]] * template_count
22
+ if rotations.shape[0] == template_count:
23
+ return [rotations[k] for k in range(template_count)]
24
+ raise ValueError(f"{rotations.shape[0]} rotation matrices given for {template_count} template slots")
25
+ return [rotations] * template_count
26
+
27
+ class Template:
28
+ """Base class of tm2d templates. A subclass implements _make_template, _get_rotation_matrices and get_shape.
29
+
30
+ supports_ctf_free: True if _make_template takes apply_ctf=False and then renders projections without the CTF
31
+ (the image-side CTF and prefiltered searches need them). A subclass that sets it must honor the flag; Plan
32
+ never uses the image side for a template without it."""
33
+ supports_ctf_free: bool = False
34
+
35
+ def __init__(self):
36
+ raise NotImplementedError("Template is an abstract class. Please implement it in a subclass.")
37
+
38
+ def _make_template(self,
39
+ rotations: Union[vc.Var[vc.m4], np.ndarray],
40
+ pixel_size: float,
41
+ ctf_params: CTFParams,
42
+ template_count: int = 1,
43
+ cmd_graph: vd.CommandGraph = None,
44
+ apply_ctf: bool = True) -> vd.RFFTBuffer:
45
+ """
46
+ This abstract method should return a buffer containing the sampled and filtered template in real space.
47
+ """
48
+
49
+ raise NotImplementedError("make_template must be implemented in a subclass.")
50
+
51
+ def make_template(self,
52
+ rotations: Union[vc.Var[vc.m4], List[int], np.ndarray],
53
+ pixel_size: float,
54
+ ctf_params: CTFParams = None,
55
+ template_count: int = 1,
56
+ cmd_graph: vd.CommandGraph = None,
57
+ apply_ctf: bool = True) -> vd.RFFTBuffer:
58
+ """Record the rendering of template_count templates (real space, (template_count, h, w) RFFTBuffer).
59
+
60
+ apply_ctf=False: projections without the CTF (other filters, e.g. the atomic template's Gaussian, still
61
+ apply). Only for templates with supports_ctf_free; the template's own disable_ctf setting is not changed.
62
+ """
63
+ if not apply_ctf and not self.supports_ctf_free:
64
+ raise NotImplementedError(f"{type(self).__name__} cannot render CTF-free projections "
65
+ "(supports_ctf_free is False)")
66
+
67
+ if ctf_params is None:
68
+ ctf_params = CTFParams()
69
+
70
+ # a list of angles / matrices becomes an array; a list of graph variables (one per slot) passes through
71
+ if isinstance(rotations, list) and all(isinstance(r, (int, float, np.number, list, tuple, np.ndarray)) for r in rotations):
72
+ rotations = np.array(rotations, dtype=np.float32)
73
+
74
+ if isinstance(rotations, np.ndarray):
75
+ if rotations.ndim == 1:
76
+ rotations = rotations.reshape(1, 3)
77
+
78
+ if rotations.ndim == 2:
79
+ if rotations.shape[1] == 4 and rotations.shape[0] == 4:
80
+ rotations = rotations.reshape(1, 4, 4)
81
+ else:
82
+ assert rotations.shape[1] == 3 , "Rotations must be a 2D array with shape (N, 3)."
83
+
84
+ rotations = self.get_rotation_matrices(rotations)
85
+
86
+ return self._make_template(
87
+ rotations=rotations,
88
+ pixel_size=pixel_size,
89
+ ctf_params=ctf_params,
90
+ template_count=template_count,
91
+ cmd_graph=cmd_graph,
92
+ **({} if apply_ctf else {"apply_ctf": False}) # subclasses without the flag keep working
93
+ )
94
+
95
+ def _get_rotation_matrices(self, rotations: np.ndarray) -> np.ndarray:
96
+ raise NotImplementedError("get_rotation_matrices must be implemented in a subclass.")
97
+
98
+ def get_rotation_matrices(self, rotations: Union[np.ndarray, Tuple[float, float, float]]) -> np.ndarray:
99
+ if not isinstance(rotations, np.ndarray):
100
+ rotations = np.array(rotations, dtype=np.float32).reshape(1, 3)
101
+
102
+ if rotations.ndim == 1:
103
+ rotations = rotations.reshape(1, 3)
104
+
105
+ return self._get_rotation_matrices(rotations)
106
+
107
+ def get_shape(self) -> tuple:
108
+ """
109
+ Return the shape of the template.
110
+ This method should be implemented in subclasses to return the correct shape.
111
+ """
112
+ raise NotImplementedError("get_shape must be implemented in a subclass.")