tm2d 0.3.0__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 (34) hide show
  1. {tm2d-0.3.0 → tm2d-0.4.0}/PKG-INFO +4 -2
  2. {tm2d-0.3.0 → tm2d-0.4.0}/README.md +1 -0
  3. {tm2d-0.3.0 → tm2d-0.4.0}/pyproject.toml +3 -1
  4. {tm2d-0.3.0 → tm2d-0.4.0}/tm2d/__init__.py +4 -0
  5. {tm2d-0.3.0 → tm2d-0.4.0}/tm2d/base_comparator.py +1 -1
  6. tm2d-0.4.0/tm2d/base_results.py +70 -0
  7. {tm2d-0.3.0 → tm2d-0.4.0}/tm2d/base_template.py +40 -6
  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.3.0 → tm2d-0.4.0}/tm2d/ctf/ctf_params.py +24 -18
  12. {tm2d-0.3.0 → tm2d-0.4.0}/tm2d/ctf/ctf_set.py +2 -1
  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.3.0 → tm2d-0.4.0}/tm2d/templates/atomic.py +42 -13
  19. {tm2d-0.3.0 → tm2d-0.4.0}/tm2d/templates/density.py +67 -57
  20. tm2d-0.4.0/tm2d/weights.py +64 -0
  21. {tm2d-0.3.0 → tm2d-0.4.0}/tm2d.egg-info/PKG-INFO +4 -2
  22. {tm2d-0.3.0 → tm2d-0.4.0}/tm2d.egg-info/SOURCES.txt +4 -0
  23. {tm2d-0.3.0 → tm2d-0.4.0}/tm2d.egg-info/requires.txt +1 -0
  24. tm2d-0.3.0/tm2d/base_results.py +0 -23
  25. tm2d-0.3.0/tm2d/comparators/cross_correlation.py +0 -232
  26. tm2d-0.3.0/tm2d/ctf/ctf.py +0 -207
  27. tm2d-0.3.0/tm2d/plan.py +0 -271
  28. tm2d-0.3.0/tm2d/results/per_param.py +0 -183
  29. tm2d-0.3.0/tm2d/results/per_pixel.py +0 -225
  30. {tm2d-0.3.0 → tm2d-0.4.0}/LICENSE +0 -0
  31. {tm2d-0.3.0 → tm2d-0.4.0}/setup.cfg +0 -0
  32. {tm2d-0.3.0 → tm2d-0.4.0}/tm2d/param_set.py +0 -0
  33. {tm2d-0.3.0 → tm2d-0.4.0}/tm2d.egg-info/dependency_links.txt +0 -0
  34. {tm2d-0.3.0 → tm2d-0.4.0}/tm2d.egg-info/top_level.txt +0 -0
@@ -1,8 +1,8 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tm2d
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: A Python module for 2D template matching
5
- Author-email: Shahar Sandhaus <shahar.sandhaus@berkeley.edu>
5
+ Author-email: Shahar Sandhaus <shahar.sandhaus@berkeley.edu>, Petar Petrov <ppetrov@berkeley.edu>
6
6
  Project-URL: Homepage, https://github.com/sharhar/tm2d
7
7
  Project-URL: Issues, https://github.com/sharhar/tm2d/issues
8
8
  Classifier: Programming Language :: Python :: 3
@@ -14,6 +14,7 @@ Description-Content-Type: text/markdown
14
14
  License-File: LICENSE
15
15
  Requires-Dist: setuptools>=59.0
16
16
  Requires-Dist: numpy
17
+ Requires-Dist: tqdm
17
18
  Requires-Dist: vkdispatch==0.1.0
18
19
  Dynamic: license-file
19
20
 
@@ -29,6 +30,7 @@ Runtime dependencies are listed in `pyproject.toml`:
29
30
 
30
31
  - Python >= 3.9
31
32
  - `numpy`
33
+ - `tqdm`
32
34
  - `vkdispatch==0.1.0`
33
35
  - `setuptools>=59.0`
34
36
 
@@ -10,6 +10,7 @@ Runtime dependencies are listed in `pyproject.toml`:
10
10
 
11
11
  - Python >= 3.9
12
12
  - `numpy`
13
+ - `tqdm`
13
14
  - `vkdispatch==0.1.0`
14
15
  - `setuptools>=59.0`
15
16
 
@@ -4,9 +4,10 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "tm2d"
7
- version = "0.3.0"
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,7 +5,7 @@ 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
  """
@@ -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.")
@@ -5,7 +5,33 @@ import numpy as np
5
5
  from typing import Union, List, Tuple
6
6
  from .ctf.ctf import CTFParams
7
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
+
8
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
+
9
35
  def __init__(self):
10
36
  raise NotImplementedError("Template is an abstract class. Please implement it in a subclass.")
11
37
 
@@ -15,7 +41,7 @@ class Template:
15
41
  ctf_params: CTFParams,
16
42
  template_count: int = 1,
17
43
  cmd_graph: vd.CommandGraph = None,
18
- disable_ctf: bool = False) -> vd.RFFTBuffer:
44
+ apply_ctf: bool = True) -> vd.RFFTBuffer:
19
45
  """
20
46
  This abstract method should return a buffer containing the sampled and filtered template in real space.
21
47
  """
@@ -27,15 +53,22 @@ class Template:
27
53
  pixel_size: float,
28
54
  ctf_params: CTFParams = None,
29
55
  template_count: int = 1,
30
- cmd_graph: vd.CommandGraph = None) -> vd.RFFTBuffer:
31
- """
32
- This abstract method should return a buffer containing the sampled and filtered template in real space.
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.
33
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)")
34
66
 
35
67
  if ctf_params is None:
36
68
  ctf_params = CTFParams()
37
69
 
38
- if isinstance(rotations, list):
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):
39
72
  rotations = np.array(rotations, dtype=np.float32)
40
73
 
41
74
  if isinstance(rotations, np.ndarray):
@@ -55,7 +88,8 @@ class Template:
55
88
  pixel_size=pixel_size,
56
89
  ctf_params=ctf_params,
57
90
  template_count=template_count,
58
- cmd_graph=cmd_graph
91
+ cmd_graph=cmd_graph,
92
+ **({} if apply_ctf else {"apply_ctf": False}) # subclasses without the flag keep working
59
93
  )
60
94
 
61
95
  def _get_rotation_matrices(self, rotations: np.ndarray) -> np.ndarray: