cryoPARES 0.1.0__py3-none-any.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 (146) hide show
  1. cryoPARES/__init__.py +2 -0
  2. cryoPARES/cacheManager.py +66 -0
  3. cryoPARES/cli.py +46 -0
  4. cryoPARES/configManager/__init__.py +0 -0
  5. cryoPARES/configs/__init__.py +0 -0
  6. cryoPARES/configs/datamanager_config/__init__.py +0 -0
  7. cryoPARES/configs/datamanager_config/augmentations_config.py +91 -0
  8. cryoPARES/configs/datamanager_config/datamanager_config.py +31 -0
  9. cryoPARES/configs/datamanager_config/particlesDataset_config.py +41 -0
  10. cryoPARES/configs/inference_config/__init__.py +0 -0
  11. cryoPARES/configs/inference_config/inference_config.py +59 -0
  12. cryoPARES/configs/inference_config/nnetInference_config.py +8 -0
  13. cryoPARES/configs/mainConfig.py +66 -0
  14. cryoPARES/configs/models_config/__init__.py +0 -0
  15. cryoPARES/configs/models_config/directionalnormalizer_config/__init__.py +0 -0
  16. cryoPARES/configs/models_config/directionalnormalizer_config/directionalnormalizer_config.py +18 -0
  17. cryoPARES/configs/models_config/image2sphere_config/__init__.py +0 -0
  18. cryoPARES/configs/models_config/image2sphere_config/gaussianFilters_config.py +16 -0
  19. cryoPARES/configs/models_config/image2sphere_config/image2sphere_config.py +36 -0
  20. cryoPARES/configs/models_config/image2sphere_config/imageEncoder_config/__init__.py +0 -0
  21. cryoPARES/configs/models_config/image2sphere_config/imageEncoder_config/convMixer_config.py +14 -0
  22. cryoPARES/configs/models_config/image2sphere_config/imageEncoder_config/imageEncoder_config.py +25 -0
  23. cryoPARES/configs/models_config/image2sphere_config/imageEncoder_config/resNet_config.py +9 -0
  24. cryoPARES/configs/models_config/image2sphere_config/imageEncoder_config/unet_config.py +17 -0
  25. cryoPARES/configs/models_config/image2sphere_config/so3Components_config.py +89 -0
  26. cryoPARES/configs/models_config/models_config.py +11 -0
  27. cryoPARES/configs/projmatching_config/__init__.py +0 -0
  28. cryoPARES/configs/projmatching_config/projmatching_config.py +99 -0
  29. cryoPARES/configs/reconstruct_config/__init__.py +0 -0
  30. cryoPARES/configs/reconstruct_config/reconstruct_config.py +52 -0
  31. cryoPARES/configs/train_config/__init__.py +0 -0
  32. cryoPARES/configs/train_config/train_config.py +102 -0
  33. cryoPARES/constants.py +28 -0
  34. cryoPARES/datamanager/__init__.py +1 -0
  35. cryoPARES/datamanager/augmentations.py +353 -0
  36. cryoPARES/datamanager/ctf/__init__.py +0 -0
  37. cryoPARES/datamanager/ctf/_test.py +195 -0
  38. cryoPARES/datamanager/ctf/common.py +81 -0
  39. cryoPARES/datamanager/ctf/fft_ctf.py +72 -0
  40. cryoPARES/datamanager/ctf/rfft_ctf.py +209 -0
  41. cryoPARES/datamanager/datamanager.py +283 -0
  42. cryoPARES/datamanager/particlesDataset.py +391 -0
  43. cryoPARES/datamanager/rawParticlesDataset.py +233 -0
  44. cryoPARES/datamanager/relionStarDataset.py +122 -0
  45. cryoPARES/experimental/__init__.py +0 -0
  46. cryoPARES/experimental/_rotateWigners.py +107 -0
  47. cryoPARES/experimental/escnn_groups_and_irreps.py +15 -0
  48. cryoPARES/experimental/rotateWigners.py +156 -0
  49. cryoPARES/geometry/__init__.py +0 -0
  50. cryoPARES/geometry/convert_angles.py +146 -0
  51. cryoPARES/geometry/grids.py +157 -0
  52. cryoPARES/geometry/metrics_angles.py +204 -0
  53. cryoPARES/geometry/nearest_neigs_sphere.py +57 -0
  54. cryoPARES/geometry/symmetry.py +15 -0
  55. cryoPARES/geometry/utilsGrid.py +491 -0
  56. cryoPARES/inference/__init__.py +0 -0
  57. cryoPARES/inference/daemon/__init__.py +0 -0
  58. cryoPARES/inference/daemon/_test_pickleFiller.py +64 -0
  59. cryoPARES/inference/daemon/daemonInference.py +245 -0
  60. cryoPARES/inference/daemon/materializePartialResults.py +168 -0
  61. cryoPARES/inference/daemon/queueManager.py +247 -0
  62. cryoPARES/inference/daemon/spoolingFiller.py +91 -0
  63. cryoPARES/inference/infer.py +705 -0
  64. cryoPARES/inference/inferencer.py +825 -0
  65. cryoPARES/inference/nnetWorkers/__init__.py +0 -0
  66. cryoPARES/inference/nnetWorkers/inferenceModel.py +239 -0
  67. cryoPARES/inference/nnetWorkers/tensorDataBuffer.py +74 -0
  68. cryoPARES/models/__init__.py +4 -0
  69. cryoPARES/models/directionalNormalizer/__init__.py +0 -0
  70. cryoPARES/models/directionalNormalizer/directionalNormalizer.py +320 -0
  71. cryoPARES/models/image2sphere/__init__.py +0 -0
  72. cryoPARES/models/image2sphere/gaussianFilters.py +258 -0
  73. cryoPARES/models/image2sphere/image2sphere.py +661 -0
  74. cryoPARES/models/image2sphere/imageEncoder/__init__.py +0 -0
  75. cryoPARES/models/image2sphere/imageEncoder/_monai_unet.py +76 -0
  76. cryoPARES/models/image2sphere/imageEncoder/convMixer.py +87 -0
  77. cryoPARES/models/image2sphere/imageEncoder/imageEncoder.py +50 -0
  78. cryoPARES/models/image2sphere/imageEncoder/resNet.py +41 -0
  79. cryoPARES/models/image2sphere/imageEncoder/unet.py +532 -0
  80. cryoPARES/models/image2sphere/so3Components.py +541 -0
  81. cryoPARES/models/model.py +410 -0
  82. cryoPARES/postprocessing/__init__.py +0 -0
  83. cryoPARES/postprocessing/fsc_utils.py +282 -0
  84. cryoPARES/postprocessing/guinier.py +192 -0
  85. cryoPARES/postprocessing/mask_utils.py +171 -0
  86. cryoPARES/postprocessing/methods/__init__.py +0 -0
  87. cryoPARES/postprocessing/methods/base.py +233 -0
  88. cryoPARES/postprocessing/methods/standard_bfactor.py +159 -0
  89. cryoPARES/postprocessing/postprocess.py +47 -0
  90. cryoPARES/postprocessing/sharpening.py +135 -0
  91. cryoPARES/projmatching/__init__.py +0 -0
  92. cryoPARES/projmatching/projMatcher.py +1183 -0
  93. cryoPARES/projmatching/projmatching.py +439 -0
  94. cryoPARES/projmatching/projmatchingUtils/__init__.py +0 -0
  95. cryoPARES/projmatching/projmatchingUtils/extract_central_slices_as_real.py +290 -0
  96. cryoPARES/projmatching/projmatchingUtils/filterToResolution.py +118 -0
  97. cryoPARES/projmatching/projmatchingUtils/fourierOperations.py +226 -0
  98. cryoPARES/projmatching/projmatchingUtils/loggers.py +48 -0
  99. cryoPARES/projmatching/projmatchingUtils/myProgressBar.py +27 -0
  100. cryoPARES/reconstruction/__init__.py +0 -0
  101. cryoPARES/reconstruction/insert_central_slices_rfft_3d.py +325 -0
  102. cryoPARES/reconstruction/reconstruct.py +275 -0
  103. cryoPARES/reconstruction/reconstructor.py +790 -0
  104. cryoPARES/scripts/__init__.py +0 -0
  105. cryoPARES/scripts/compactify_checkpoint.py +251 -0
  106. cryoPARES/scripts/compare_poses.py +607 -0
  107. cryoPARES/scripts/computeFsc.py +561 -0
  108. cryoPARES/scripts/consensus_alignment.py +748 -0
  109. cryoPARES/scripts/consensus_picking.py +321 -0
  110. cryoPARES/scripts/gmm_hists.py +1248 -0
  111. cryoPARES/scripts/hists_from_starfile.py +140 -0
  112. cryoPARES/scripts/manageStarfile.py +247 -0
  113. cryoPARES/scripts/plot_learning_curve.py +172 -0
  114. cryoPARES/scripts/regroup_starfile.py +297 -0
  115. cryoPARES/scripts/utils/create_noise_images.py +274 -0
  116. cryoPARES/scripts/utils/pred_calibration_estimation.py +898 -0
  117. cryoPARES/scripts/utils/randomize_particle_params.py +182 -0
  118. cryoPARES/scripts/utils/simulate_pref_orient.py +362 -0
  119. cryoPARES/simulation/__init__.py +0 -0
  120. cryoPARES/simulation/generateRandomStar.py +133 -0
  121. cryoPARES/simulation/simulateParticles.py +363 -0
  122. cryoPARES/simulation/simulateParticlesHelper.py +1032 -0
  123. cryoPARES/train/__init__.py +0 -0
  124. cryoPARES/train/runTrainOnePartition.py +403 -0
  125. cryoPARES/train/train.py +737 -0
  126. cryoPARES/utils/__init__.py +0 -0
  127. cryoPARES/utils/checkpointReader.py +140 -0
  128. cryoPARES/utils/checkpointUtils.py +155 -0
  129. cryoPARES/utils/errorFormatting.py +302 -0
  130. cryoPARES/utils/paths.py +102 -0
  131. cryoPARES/utils/plUtils.py +30 -0
  132. cryoPARES/utils/reconstructionUtils.py +47 -0
  133. cryoPARES/utils/reproducibility.py +21 -0
  134. cryoPARES/utils/subprocessUtils.py +411 -0
  135. cryoPARES/utils/systemUtils.py +192 -0
  136. cryoPARES/utils/torchUtils.py +44 -0
  137. cryoPARES/utils/torch_fourier_shift_compat.py +64 -0
  138. cryoPARES/utils/torch_fourier_slice_compat.py +46 -0
  139. cryoPARES/utils/torch_grid_utils_compat.py +21 -0
  140. cryoPARES/utils/torch_image_interpolation_compat.py +14 -0
  141. cryopares-0.1.0.dist-info/METADATA +791 -0
  142. cryopares-0.1.0.dist-info/RECORD +146 -0
  143. cryopares-0.1.0.dist-info/WHEEL +5 -0
  144. cryopares-0.1.0.dist-info/entry_points.txt +6 -0
  145. cryopares-0.1.0.dist-info/licenses/LICENSE +226 -0
  146. cryopares-0.1.0.dist-info/top_level.txt +1 -0
cryoPARES/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ __version__ = "0.1.0"
2
+ __author__ = "Ruben Sanchez-Garcia"
@@ -0,0 +1,66 @@
1
+ import functools
2
+ import hashlib
3
+ import json
4
+ import os
5
+ import tempfile
6
+ import warnings
7
+
8
+ import joblib
9
+
10
+ from cryoPARES.configs.mainConfig import main_config
11
+
12
+
13
+ def get_cache(cache_name, cachedir=None, verbose=0):
14
+
15
+ if cachedir is None:
16
+ cachedir = main_config.cachedir
17
+ if cache_name is not None:
18
+ try:
19
+ cache = joblib.Memory(location=os.path.join(cachedir, cache_name + ".joblib"),
20
+ verbose=verbose)
21
+ return cache
22
+ except (FileNotFoundError, IOError, PermissionError) as e:
23
+ print(e)
24
+ warnings.warn(f"The CACHE_DIR {main_config.cachedir} is not available ({e}), skipping cache. "
25
+ f"Some weights will be recomputed in each execution, wasting compute")
26
+ cache = joblib.Memory(location=None, verbose=verbose)
27
+ return cache
28
+
29
+
30
+ def hashVars(name, vars_to_hash):
31
+ _txt = json.dumps(vars_to_hash)
32
+ _hash = hashlib.sha256(_txt.encode(encoding='utf-8')).hexdigest()
33
+ _name = name + f"_{_hash}"
34
+ return _name
35
+
36
+ class SharedTemporaryDirectory(tempfile.TemporaryDirectory):
37
+ def __init__(self, name, vars_to_hash, rootdir=None):
38
+ """
39
+
40
+ This class behaves like TemporaryDirectory but only the process that creates the folder can remove it.
41
+ Useful to use in the rank_0 process in torch.distributed.
42
+
43
+ :param name: Root name for the tempfolder that will hang after /rootdir/{name}_HASH
44
+ :param vars_to_hash: A list of hashable vars to create a unique name
45
+ :param rootdir: If not provided, it will use /tmp
46
+ """
47
+ super().__init__()
48
+ import weakref as _weakref
49
+ _name = hashVars(name, vars_to_hash)
50
+ assert _name, "Error, name is empty"
51
+ if rootdir is None:
52
+ rootdir = tempfile.gettempdir()
53
+ self.name = os.path.join(rootdir, _name)
54
+ try:
55
+ os.makedirs(self.name)
56
+ self.should_remove = True
57
+ self._finalizer = _weakref.finalize(
58
+ self, self._cleanup, self.name,
59
+ warn_message="Implicitly cleaning up {!r}".format(self))
60
+ except OSError:
61
+ self.should_remove = False
62
+
63
+ def cleanup(self) -> None:
64
+ if self.should_remove:
65
+ super().cleanup()
66
+ # print(f"Directory {self.name} has been deleted by {os.getpid()}!")
cryoPARES/cli.py ADDED
@@ -0,0 +1,46 @@
1
+ import os
2
+ import warnings
3
+
4
+ _PYTHONWARNINGS = "ignore::FutureWarning,ignore::DeprecationWarning,ignore::PendingDeprecationWarning,ignore::UserWarning"
5
+
6
+
7
+ def _suppress_user_warnings():
8
+ # Set env var so spawned subprocesses (e.g. DDP workers) inherit the filters
9
+ os.environ.setdefault("PYTHONWARNINGS", _PYTHONWARNINGS)
10
+ # Broad suppression for the current process (lower priority — added first, checked second)
11
+ warnings.filterwarnings("ignore", category=UserWarning)
12
+ warnings.filterwarnings("ignore", category=FutureWarning)
13
+ warnings.filterwarnings("ignore", category=DeprecationWarning)
14
+ warnings.filterwarnings("ignore", category=PendingDeprecationWarning)
15
+ # Re-enable UserWarnings from cryoPARES itself (higher priority — added last, checked first)
16
+ warnings.filterwarnings("always", category=UserWarning, module="cryoPARES.*")
17
+
18
+
19
+ def train():
20
+ _suppress_user_warnings()
21
+ from cryoPARES.train.train import main
22
+ main()
23
+
24
+
25
+ def infer():
26
+ _suppress_user_warnings()
27
+ from cryoPARES.inference.infer import main
28
+ main()
29
+
30
+
31
+ def reconstruct():
32
+ _suppress_user_warnings()
33
+ from cryoPARES.reconstruction.reconstruct import main
34
+ main()
35
+
36
+
37
+ def projmatching():
38
+ _suppress_user_warnings()
39
+ from cryoPARES.projmatching.projmatching import main
40
+ main()
41
+
42
+
43
+ def postprocess():
44
+ _suppress_user_warnings()
45
+ from cryoPARES.postprocessing.postprocess import main
46
+ main()
File without changes
File without changes
File without changes
@@ -0,0 +1,91 @@
1
+ from dataclasses import dataclass, field
2
+ from typing import List, Optional, Tuple
3
+
4
+ #Note that Individual operation configs are not named *_config not to be added at the same level as augmentator_config. #TODO: move them to submodule
5
+ @dataclass
6
+ class RandomGaussNoiseConfig:
7
+ scale: float = 0.5
8
+ p: float = 0.1
9
+
10
+ @dataclass
11
+ class RandomUnifNoiseConfig:
12
+ scale: float = 2.0
13
+ p: float = 0.2
14
+
15
+ @dataclass
16
+ class GaussianBlurConfig:
17
+ scale: float = 2
18
+ p: float = 0.2 #TODO: change it to .1, not to make things too easy. Or perhaps add a scheduler here. .2 seems to work better
19
+
20
+ @dataclass
21
+ class SizePerturbationConfig:
22
+ maxSizeFraction: float = 0.05
23
+ p: float = 0.2 #TODO: change it to .1, since this is not a naturally ocurring problem
24
+
25
+
26
+ @dataclass
27
+ class ErasingConfig:
28
+ ratio: Tuple[float, float] = (0.3, 2.3)
29
+ scale: Tuple[float, float] = (0.01, 0.02)
30
+ p: float = 0.1
31
+
32
+ @dataclass
33
+ class RandomElasticConfig:
34
+ kernel_size_fraction: float = 0.2
35
+ sigma_fraction: float = 0.1
36
+ alpha: float = 0.1
37
+ p: float = 0.1
38
+
39
+
40
+ @dataclass
41
+ class InPlaneRotations90Config:
42
+ p: float = 1.0
43
+
44
+ @dataclass
45
+ class InPlaneRotationsConfig:
46
+ maxDegrees: float = 20
47
+ p: float = 0.5
48
+
49
+ @dataclass
50
+ class InPlaneShiftsConfig:
51
+ maxShiftFraction: float = 0.05
52
+ p: float = 0.5
53
+
54
+
55
+
56
+ """
57
+ This is an example for a probScheduler:
58
+ "probScheduler": {"type": "linear_down",
59
+ "kwargs": {
60
+ "scheduler_steps": int(3e6), # 1e6 is ~10 epochs assuming 1e5 particles
61
+ "min_prob": .1}
62
+ }
63
+ """
64
+
65
+ @dataclass
66
+ class Operations:
67
+ randomGaussNoise: RandomGaussNoiseConfig = field(default_factory=RandomGaussNoiseConfig)
68
+ randomUnifNoise: RandomUnifNoiseConfig = field(default_factory=RandomUnifNoiseConfig)
69
+ sizePerturbation: SizePerturbationConfig = field(default_factory=SizePerturbationConfig)
70
+ gaussianBlur: GaussianBlurConfig = field(default_factory=GaussianBlurConfig)
71
+ erasing: ErasingConfig = field(default_factory=ErasingConfig)
72
+ randomElastic: RandomElasticConfig = field(default_factory=RandomElasticConfig)
73
+ inPlaneRotations90: InPlaneRotations90Config = field(default_factory=InPlaneRotations90Config)
74
+ inPlaneRotations: InPlaneRotationsConfig = field(default_factory=InPlaneRotationsConfig)
75
+ inPlaneShifts: InPlaneShiftsConfig = field(default_factory=InPlaneShiftsConfig)
76
+
77
+ @dataclass
78
+ class Augmenter_config:
79
+ """Data augmentation configuration parameters."""
80
+
81
+ # Centralized parameter documentation
82
+ PARAM_DOCS = {
83
+ 'min_n_augm_per_img': 'Minimum number of augmentation operations to apply per image',
84
+ 'max_n_augm_per_img': 'Maximum number of augmentation operations to apply per image',
85
+ 'prob_augment_each_image': 'Probability of applying augmentation to each image (0.0 to 1.0)',
86
+ }
87
+
88
+ min_n_augm_per_img: int = 1
89
+ max_n_augm_per_img: int = 8 #TODO: We probably want to do 4 since, in the original code we have the swap between particle and proj
90
+ prob_augment_each_image: float = 0.95
91
+ operations: Operations = field(default_factory=Operations)
@@ -0,0 +1,31 @@
1
+ from dataclasses import dataclass, field
2
+ from enum import Enum
3
+ from typing import Tuple
4
+
5
+ from cryoPARES.configs.datamanager_config.augmentations_config import Augmenter_config
6
+ from cryoPARES.configs.datamanager_config.particlesDataset_config import ParticlesDataset_config
7
+
8
+
9
+ @dataclass
10
+ class DataManager_config:
11
+ """Data management configuration parameters."""
12
+
13
+ # Centralized parameter documentation
14
+ PARAM_DOCS = {
15
+ 'num_dataworkers': 'Number of parallel data loading workers per GPU. Each worker is a separate CPU process. Set to 0 to load data in the main thread (useful only for debugging). Try not to oversubscribe by asking more workers than CPUs',
16
+ 'num_augmented_copies_per_batch': 'Number of augmented copies per particle in each batch. Each copy undergoes different data augmentation. Batch size must be divisible by this value',
17
+ 'train_validation_split_seed': 'Random seed for splitting data into training and validation sets',
18
+ 'train_validation_split': 'Fraction of data to use for training and validation (tuple of two floats that sum to 1.0)',
19
+ 'augment_train': 'Apply data augmentation to training set',
20
+ 'only_first_dataset_for_validation': 'If multiple datasets provided, use only the first one for validation (useful when combining datasets)',
21
+ }
22
+
23
+ num_augmented_copies_per_batch: int = 4
24
+ train_validation_split_seed: int = 113
25
+ train_validation_split: Tuple[float, float] = (0.7, 0.3)
26
+ num_dataworkers: int = 8
27
+ augment_train: bool = True
28
+ only_first_dataset_for_validation: bool = True
29
+
30
+ augmenter: Augmenter_config = field(default_factory=Augmenter_config)
31
+ particlesdataset: ParticlesDataset_config = field(default_factory=ParticlesDataset_config)
@@ -0,0 +1,41 @@
1
+ from dataclasses import dataclass
2
+ from enum import Enum
3
+ from typing import Optional
4
+
5
+ class ImgNormalizationType(str, Enum):
6
+ none = "none"
7
+ noiseStats = "noiseStats"
8
+ subtractMean = "subtractMean"
9
+
10
+ class CtfCorrectionType(str, Enum):
11
+ none = "none"
12
+ phase_flip = "phase_flip"
13
+ concat_phase_flip = "concat_phase_flip"
14
+ ctf_multiply = "ctf_multiply"
15
+
16
+ @dataclass
17
+ class ParticlesDataset_config():
18
+ """Particle dataset configuration parameters."""
19
+
20
+ # Centralized parameter documentation
21
+ PARAM_DOCS = {
22
+ 'sampling_rate_angs_for_nnet': 'Target sampling rate in Angstroms/pixel for neural network input. Particle images are first rescaled to this sampling rate before processing',
23
+ 'image_size_px_for_nnet': 'Target image size in pixels for neural network input. After rescaling to target sampling rate, images are cropped or padded to this size. We recommend tight box-sizes',
24
+ 'mask_radius_angs': 'Radius of circular mask in Angstroms applied to particle images. If not provided, defaults to half the box size',
25
+ 'store_data_in_memory': 'Cache particle images in RAM for faster data loading (requires sufficient memory)',
26
+ 'apply_mask_to_img': 'Apply circular mask to particle images. If False, mask is only used for computing normalization statistics',
27
+ 'min_maxProb': 'Minimum maximum probability threshold for filtering particles. Particles with maxProb below this value are excluded',
28
+ 'perImg_normalization': 'Per-image normalization method: "none", "noiseStats" (normalize using noise region statistics), or "subtractMean"',
29
+ 'ctf_correction': 'CTF correction method: "none", "phase_flip", "concat_phase_flip" (concatenate original and phase-flipped), or "ctf_multiply"',
30
+ 'reduce_symmetry_in_label': 'When using symmetric molecules, map rotation labels to the fundamental domain (canonical symmetry representative) before training. Ensures consistent training targets by collapsing equivalent orientations under the symmetry group',
31
+ }
32
+
33
+ sampling_rate_angs_for_nnet: float = 1.5
34
+ image_size_px_for_nnet: Optional[int] = None
35
+ store_data_in_memory: bool = True
36
+ mask_radius_angs: Optional[float] = None #If None, use a circular mask of radius Box/2
37
+ apply_mask_to_img: bool = True # If True, apply the mask to the the image, otherwise, use it only for computing normalization stats
38
+ min_maxProb: Optional[float] = None #Particles with maxProb smaller than this number will be ruled out
39
+ perImg_normalization: ImgNormalizationType = ImgNormalizationType.noiseStats
40
+ ctf_correction: CtfCorrectionType = CtfCorrectionType.concat_phase_flip
41
+ reduce_symmetry_in_label: bool = True
File without changes
@@ -0,0 +1,59 @@
1
+ from dataclasses import dataclass, field
2
+ from typing import Optional, Literal
3
+
4
+
5
+ @dataclass
6
+ class Inference_config:
7
+ """Inference configuration parameters."""
8
+
9
+ # Centralized parameter documentation
10
+ PARAM_DOCS = {
11
+ # Config parameters
12
+ 'batch_size': 'Number of particles per batch for inference',
13
+ 'use_cuda': 'Enable GPU acceleration for inference. If False, runs on CPU only',
14
+ 'n_cpus_if_no_cuda': 'Maximum CPU threads per worker when CUDA is disabled',
15
+ 'random_seed': 'Random seed for reproducibility during inference',
16
+ 'top_k_poses_nnet': 'Number of top pose predictions to retrieve from neural network before local refinement',
17
+ 'pl_plugin': 'PyTorch Lightning plugin: "LightningEnvironment" or "none" (try "none" for Slurm submission)',
18
+ 'num_computer_nodes': 'Number of compute nodes for distributed inference (only tested with 1)',
19
+ 'skip_localrefinement': 'Skip local pose refinement step and use only neural network predictions',
20
+ 'skip_reconstruction': 'Skip 3D reconstruction step and output only predicted poses',
21
+ 'update_progressbar_n_batches': 'Update progress bar every N batches',
22
+ 'directional_zscore_thr': 'Confidence z-score threshold for filtering particles. Particles with scores below this are discarded as low-confidence',
23
+ 'before_refiner_buffer_size': 'If directional_zscore_thr is enabled, wait until before_refiner_buffer_size have been accumulated before executing the projection matching and reconstruction. If None, before_refiner_buffer_size=batch_size//4',
24
+ 'float32_matmul_precision': 'PyTorch float32 matrix multiplication precision mode ("highest", "high", or "medium")',
25
+
26
+ # CLI-exposed parameters (not in config, but used in distributed_inference)
27
+ 'particles_star_fname': 'Path to input RELION particles .star file',
28
+ 'checkpoint_dir': 'Path to training directory (or .zip file) containing half-set models with checkpoints and hyperparameters. By default they are called version_0, version_1, etc.',
29
+ 'results_dir': 'Output directory for inference results including predicted poses and optional reconstructions',
30
+ 'data_halfset': 'Which particle half-set(s) to process: "half1", "half2", or "allParticles"',
31
+ 'model_halfset': 'Model half-set selection policy: "half1", "half2", "allCombinations", or "matchingHalf" (uses matching data/model pairs)',
32
+ 'particles_dir': 'Root directory for particle image paths. If provided, overrides paths in the .star file',
33
+ 'n_jobs': 'Number of worker processes. Defaults to number of GPUs if CUDA enabled, otherwise 1',
34
+ 'compile_model': 'Compile model with torch.compile for faster inference (experimental, requires PyTorch 2.0+)',
35
+ 'reference_map': 'Path to reference map (.mrc) for FSC computation during validation',
36
+ 'reference_mask': 'Path to reference mask (.mrc) for masked FSC calculation',
37
+ 'subset_idxs': 'List of particle indices to process (for debugging or partial processing)',
38
+ 'n_first_particles': 'Process only the first N particles from dataset (debug feature)',
39
+ 'check_interval_secs': 'Polling interval in seconds for parent loop in distributed processing',
40
+ }
41
+
42
+ batch_size: int = 32
43
+ use_cuda: bool = True
44
+ n_cpus_if_no_cuda: int = 4
45
+ random_seed: int = 12313
46
+
47
+ top_k_poses_nnet: int = 1
48
+
49
+ pl_plugin: Literal["LightningEnvironment", "none"] = "LightningEnvironment" #Try none to submit to slurm
50
+ num_computer_nodes: int = 1 #It has not been tried with values different from 1
51
+
52
+ skip_localrefinement: bool = False
53
+ skip_reconstruction: bool = False
54
+ update_progressbar_n_batches: int = 20
55
+ directional_zscore_thr: Optional[float] = None
56
+
57
+ before_refiner_buffer_size: Optional[int] = None
58
+
59
+ float32_matmul_precision: str = "high"
@@ -0,0 +1,8 @@
1
+ from dataclasses import dataclass, field
2
+ from typing import Optional, Literal
3
+
4
+
5
+ @dataclass
6
+ class NnetInference_config:
7
+ n_dataworkers: int = 0
8
+ batch_size: int = 32
@@ -0,0 +1,66 @@
1
+ import importlib
2
+ import inspect
3
+ import os
4
+ import tempfile
5
+ from dataclasses import field, dataclass
6
+ from pathlib import Path
7
+
8
+ from cryoPARES.configs.datamanager_config.datamanager_config import DataManager_config
9
+ from cryoPARES.configs.inference_config.inference_config import Inference_config
10
+ from cryoPARES.configs.models_config.models_config import Models_config
11
+ from cryoPARES.configs.projmatching_config.projmatching_config import Projmatching_config
12
+ from cryoPARES.configs.reconstruct_config.reconstruct_config import Reconstruct_config
13
+ from cryoPARES.configs.train_config.train_config import Train_config
14
+ from cryoPARES.utils.paths import find_project_root
15
+
16
+
17
+ def pyObjectFromStr(full_name, prefix=""):
18
+
19
+ if prefix is None:
20
+ prefix = ""
21
+
22
+ splitName = full_name.split(".")
23
+ *moduleBits, className = splitName
24
+ moduleName = ""
25
+
26
+ if prefix and moduleBits:
27
+ moduleName = prefix + "."
28
+ elif prefix:
29
+ moduleName = prefix
30
+ if moduleBits:
31
+ moduleName += ".".join(moduleBits)
32
+
33
+ package = None
34
+ if moduleName.startswith("."):
35
+ stack = inspect.stack()
36
+ # stack[0] is this function
37
+ # stack[1] is the function calling this one
38
+ # stack[2] is the parent/caller we want
39
+ caller_frame = stack[2]
40
+ # Get the file path
41
+ filepath = Path(caller_frame.filename)
42
+ root = find_project_root()
43
+ # Get relative path from project root to module
44
+ package = str(filepath.relative_to(root).parent).replace(os.path.sep, ".").removesuffix(".py")
45
+
46
+ module = importlib.import_module(moduleName, package=package)
47
+ c = getattr(module, className)
48
+ return c
49
+
50
+ configs_root = Path(__file__).parent.parent / "configs"
51
+
52
+
53
+ @dataclass
54
+ class MainConfig:
55
+ cachedir: Path = Path(tempfile.gettempdir()) / "cryoPARES_cache"
56
+ models: Models_config = field(default_factory=Models_config)
57
+ datamanager: DataManager_config = field(default_factory=DataManager_config)
58
+ train: Train_config = field(default_factory=Train_config)
59
+ inference: Inference_config = field(default_factory=Inference_config)
60
+ projmatching: Projmatching_config = field(default_factory=Projmatching_config)
61
+ reconstruct: Reconstruct_config = field(default_factory=Reconstruct_config)
62
+
63
+ # Create an instance
64
+ main_config = MainConfig()
65
+ # print(main_config)
66
+ # print(f"Config ({id(main_config)}) was initiated for PID {os.getpid()}")
File without changes
@@ -0,0 +1,18 @@
1
+ from dataclasses import dataclass, field
2
+
3
+
4
+
5
+ @dataclass
6
+ class Directionalnormalizer_config:
7
+ """Directional normalizer configuration for confidence scoring."""
8
+
9
+ # Centralized parameter documentation
10
+ PARAM_DOCS = {
11
+ 'hp_order': 'HEALPix order for spherical grid resolution used in directional normalization. Higher values give finer resolution',
12
+ 'good_particles_percentile': 'When ground truth is unavailable, only particles scoring above this percentile are used to estimate normalization statistics',
13
+ 'min_particles_per_cone': 'Minimum number of particles required per orientation cone for reliable statistics. Cones with fewer particles fall back to global statistics',
14
+ }
15
+
16
+ hp_order: int = 2
17
+ good_particles_percentile: float = 95.0
18
+ min_particles_per_cone: int = 10
@@ -0,0 +1,16 @@
1
+ from dataclasses import dataclass
2
+ from typing import List, Optional
3
+
4
+
5
+ @dataclass
6
+ class GaussianFilters_config:
7
+ """Gaussian filter bank configuration for multi-scale image processing."""
8
+
9
+ # Centralized parameter documentation
10
+ PARAM_DOCS = {
11
+ 'sigma_values': 'List of Gaussian blur sigma values for multi-scale processing. Higher values create stronger blur',
12
+ 'kernel_sizes': 'Optional list of kernel sizes for each Gaussian filter. If None, automatically computed from sigma values',
13
+ }
14
+
15
+ sigma_values: List[float] = (0., 1., 3., 5., 10., 15.)
16
+ kernel_sizes: Optional[List[int]] = None
@@ -0,0 +1,36 @@
1
+ from dataclasses import dataclass, field
2
+
3
+ from cryoPARES.configs.models_config.image2sphere_config.gaussianFilters_config import GaussianFilters_config
4
+ from cryoPARES.configs.models_config.image2sphere_config.imageEncoder_config.imageEncoder_config import \
5
+ ImageEncoder_config
6
+ from cryoPARES.configs.models_config.image2sphere_config.so3Components_config import So3Components_config
7
+
8
+
9
+ @dataclass
10
+ class Image2Sphere_config:
11
+ """Image to SO(3) sphere configuration parameters."""
12
+
13
+ # Centralized parameter documentation
14
+ PARAM_DOCS = {
15
+ 'lmax': 'Maximum spherical harmonic degree for SO(3) representation. Higher values allow finer angular resolution but increase memory and computation',
16
+ 'label_smoothing': 'Label smoothing factor for loss function to prevent overconfidence',
17
+ 'enforce_symmetry': 'Apply point group symmetry constraints during pose prediction',
18
+ 'use_simCLR': 'Enable SimCLR contrastive learning loss for improved representation learning',
19
+ 'simCLR_temperature': 'Temperature parameter for SimCLR contrastive loss (controls distribution sharpness)',
20
+ 'simCLR_loss_weight': 'Weight for SimCLR contrastive loss relative to main pose prediction loss',
21
+ 'average_neigs_for_pred': 'Average predictions from neighboring orientations for smoother results (slightly slower but more accurate)',
22
+ 'n_neigs_to_compute': 'Number of neighboring orientations to use for averaging when average_neigs_for_pred is True',
23
+ }
24
+
25
+ lmax: int = 12
26
+ label_smoothing: float = 0.05 #TODO: Move this to a future loss config
27
+ enforce_symmetry: bool = True
28
+ use_simCLR: bool = False
29
+ simCLR_temperature: float = 0.5 # Temperature parameter for contrastive loss
30
+ simCLR_loss_weight: float = 0.1 # Weight for contrastive loss relative to main loss
31
+ average_neigs_for_pred: bool = False #slightly more accurate but slower
32
+ n_neigs_to_compute: int = 10 #Number of neigs used for averaging
33
+
34
+ imageencoder: ImageEncoder_config = field(default_factory=ImageEncoder_config)
35
+ so3components: So3Components_config = field(default_factory=So3Components_config)
36
+ gaussianfilters: GaussianFilters_config = field(default_factory=GaussianFilters_config)
@@ -0,0 +1,14 @@
1
+ from dataclasses import dataclass
2
+ from typing import Literal, Optional
3
+
4
+
5
+ @dataclass
6
+ class ConvMixer_config:
7
+ hidden_dim: int = 512
8
+ n_blocks: int = 12
9
+ kernel_size: int= 9
10
+ patch_size: int= 7
11
+ add_stem : bool = False
12
+ out_channels: int = 512
13
+ dropout_rate: float = 0.
14
+ normalization: Literal["Batch"] = "Batch"
@@ -0,0 +1,25 @@
1
+ from dataclasses import dataclass, field
2
+ from enum import Enum
3
+ from typing import Optional, Literal
4
+
5
+ from cryoPARES.configs.models_config.image2sphere_config.imageEncoder_config.convMixer_config import ConvMixer_config
6
+ from cryoPARES.configs.models_config.image2sphere_config.imageEncoder_config.resNet_config import ResNet_config
7
+ from cryoPARES.configs.models_config.image2sphere_config.imageEncoder_config.unet_config import Unet_config
8
+
9
+
10
+ class EncoderArchitecture(str, Enum):
11
+ ResNet = "resNet"
12
+ ConvMixer = "convMixer"
13
+ Unet = "unet"
14
+
15
+
16
+ @dataclass
17
+ class ImageEncoder_config:
18
+ encoderArtchitecture: EncoderArchitecture = EncoderArchitecture.Unet #EncoderArchitecture.ResNet
19
+ out_channels: Optional[int] = 512
20
+
21
+ convmixer: ConvMixer_config = field(default_factory=ConvMixer_config)
22
+ resnet: ResNet_config = field(default_factory=ResNet_config)
23
+ unet: Unet_config = field(default_factory=Unet_config)
24
+
25
+
@@ -0,0 +1,9 @@
1
+ from dataclasses import dataclass
2
+ from typing import Literal, Optional
3
+
4
+
5
+ @dataclass
6
+ class ResNet_config:
7
+ resnetName: str = "resnet50"
8
+ load_imagenetweights: bool = True
9
+ out_channels: int = 512
@@ -0,0 +1,17 @@
1
+ from dataclasses import dataclass
2
+ from typing import Literal, Optional
3
+
4
+
5
+ @dataclass
6
+ class Unet_config:
7
+ n_blocks: int = 5
8
+ out_channels: Optional[int] = None #It was 512
9
+ out_channels_first: int= 16 #TODO: It was 64
10
+ n_decoder_blocks_removed: Optional[int] = 1
11
+ kernel_size: int = 5
12
+ pooling: Literal["max", "avg"] = 'max'
13
+ padding: str = "same"
14
+ activation: str = "LeakyReLU"
15
+ normalization: str = "Batch"
16
+ upsampling_type: str = 'bilinear' # 'conv'
17
+ dropout: float = 0.