cryojax 0.2.2__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 (75) hide show
  1. cryojax/__init__.py +12 -0
  2. cryojax/constants/__init__.py +4 -0
  3. cryojax/constants/_load_atoms.py +57 -0
  4. cryojax/constants/element_params.npy +0 -0
  5. cryojax/coordinates/__init__.py +10 -0
  6. cryojax/coordinates/_coordinates.py +287 -0
  7. cryojax/core/__init__.py +12 -0
  8. cryojax/core/_errors.py +35 -0
  9. cryojax/core/_filter_specs.py +28 -0
  10. cryojax/core/_filtered_transformations.py +105 -0
  11. cryojax/core/_serialization.py +0 -0
  12. cryojax/cryojax_version.py +16 -0
  13. cryojax/data/__init__.py +11 -0
  14. cryojax/data/_dataset.py +91 -0
  15. cryojax/data/_particle_stack.py +36 -0
  16. cryojax/data/_relion.py +424 -0
  17. cryojax/image/__init__.py +26 -0
  18. cryojax/image/_average.py +126 -0
  19. cryojax/image/_edges.py +185 -0
  20. cryojax/image/_fft.py +120 -0
  21. cryojax/image/_map_coordinates.py +254 -0
  22. cryojax/image/_normalize.py +120 -0
  23. cryojax/image/_rescale_pixel_size.py +66 -0
  24. cryojax/image/_spectrum.py +136 -0
  25. cryojax/image/operators/__init__.py +36 -0
  26. cryojax/image/operators/_filters.py +250 -0
  27. cryojax/image/operators/_fourier_operator.py +203 -0
  28. cryojax/image/operators/_masks.py +136 -0
  29. cryojax/image/operators/_operator.py +194 -0
  30. cryojax/image/operators/_real_operator.py +89 -0
  31. cryojax/inference/__init__.py +1 -0
  32. cryojax/inference/distributions/__init__.py +7 -0
  33. cryojax/inference/distributions/_distribution.py +56 -0
  34. cryojax/inference/distributions/_gaussian_distributions.py +104 -0
  35. cryojax/inference/transforms/__init__.py +14 -0
  36. cryojax/inference/transforms/_lie_group_transforms.py +131 -0
  37. cryojax/inference/transforms/_transforms.py +236 -0
  38. cryojax/io/__init__.py +20 -0
  39. cryojax/io/_cif.py +50 -0
  40. cryojax/io/_gemmi.py +122 -0
  41. cryojax/io/_mdtraj.py +43 -0
  42. cryojax/io/_mrc.py +238 -0
  43. cryojax/io/_pdb.py +61 -0
  44. cryojax/io/_starfile.py +28 -0
  45. cryojax/rotations/__init__.py +6 -0
  46. cryojax/rotations/_lie_group.py +527 -0
  47. cryojax/rotations/_rotation.py +67 -0
  48. cryojax/simulator/__init__.py +70 -0
  49. cryojax/simulator/_assembly/__init__.py +6 -0
  50. cryojax/simulator/_assembly/_assembly.py +107 -0
  51. cryojax/simulator/_assembly/_helix.py +277 -0
  52. cryojax/simulator/_config.py +167 -0
  53. cryojax/simulator/_conformation.py +27 -0
  54. cryojax/simulator/_detector.py +188 -0
  55. cryojax/simulator/_dose.py +22 -0
  56. cryojax/simulator/_ice.py +94 -0
  57. cryojax/simulator/_instrument.py +138 -0
  58. cryojax/simulator/_integrators/__init__.py +12 -0
  59. cryojax/simulator/_integrators/_fourier_slice_extract.py +178 -0
  60. cryojax/simulator/_integrators/_gaussian_mixture.py +120 -0
  61. cryojax/simulator/_integrators/_nufft_project.py +113 -0
  62. cryojax/simulator/_integrators/_potential_integrator.py +37 -0
  63. cryojax/simulator/_optics.py +232 -0
  64. cryojax/simulator/_pipeline.py +491 -0
  65. cryojax/simulator/_pose.py +347 -0
  66. cryojax/simulator/_potential/__init__.py +14 -0
  67. cryojax/simulator/_potential/_atom_potential.py +48 -0
  68. cryojax/simulator/_potential/_scattering_potential.py +24 -0
  69. cryojax/simulator/_potential/_voxel_potential.py +623 -0
  70. cryojax/simulator/_specimen.py +164 -0
  71. cryojax/typing/__init__.py +70 -0
  72. cryojax-0.2.2.dist-info/METADATA +671 -0
  73. cryojax-0.2.2.dist-info/RECORD +75 -0
  74. cryojax-0.2.2.dist-info/WHEEL +4 -0
  75. cryojax-0.2.2.dist-info/licenses/LICENSE +504 -0
cryojax/__init__.py ADDED
@@ -0,0 +1,12 @@
1
+ from . import (
2
+ coordinates as coordinates,
3
+ core as core,
4
+ data as data,
5
+ image as image,
6
+ inference as inference,
7
+ io as io,
8
+ rotations as rotations,
9
+ simulator as simulator,
10
+ typing as typing,
11
+ )
12
+ from .cryojax_version import __version__ as __version__
@@ -0,0 +1,4 @@
1
+ from ._load_atoms import (
2
+ default_form_factor_params as default_form_factor_params,
3
+ get_form_factor_params as get_form_factor_params,
4
+ )
@@ -0,0 +1,57 @@
1
+ """
2
+ Routines for loading atomic structures.
3
+ Large amounts of the code are adapted from the ioSPI package
4
+ """
5
+
6
+ import importlib.resources as pkg_resources
7
+ import os
8
+ from functools import partial
9
+ from typing import Optional
10
+
11
+ import jax
12
+ import jax.numpy as jnp
13
+ from jaxtyping import Array, Float
14
+
15
+ from ..typing import IntegerPointCloud
16
+
17
+
18
+ def _load_element_form_factor_params():
19
+ """
20
+ Internal function to load the atomic form factor parameters.
21
+ """
22
+ with pkg_resources.as_file(
23
+ pkg_resources.files("cryojax").joinpath("constants")
24
+ ) as path:
25
+ atom_form_factor_params = jnp.load(os.path.join(path, "element_params.npy"))
26
+
27
+ return jnp.asarray(atom_form_factor_params)
28
+
29
+
30
+ default_form_factor_params = _load_element_form_factor_params()
31
+
32
+
33
+ @partial(jax.jit, static_argnums=(1,))
34
+ def get_form_factor_params(
35
+ atom_names: IntegerPointCloud,
36
+ form_factor_params: Optional[Float[Array, "2 N k"]] = None,
37
+ ):
38
+ """
39
+ Gets the parameters for the form factor for each atom in atom_names.
40
+
41
+ Parameters
42
+ ----------
43
+ atom_names : npt.NDArray[int]
44
+ Array containing the index of the one-hot encoded atom names.
45
+ By default, Hydrogen is "1", Carbon is "6", Nitrogen is "7", etc.
46
+ a_params : npt.NDArray[float], optional
47
+ Array containing the strength of the Gaussian for each form factor
48
+ b_params : npt.NDArray[float], optional
49
+ Array containing the scaling of the Gaussian for each form factor
50
+ """
51
+
52
+ if form_factor_params is None:
53
+ data = default_form_factor_params[:, atom_names]
54
+ return data[0], data[1]
55
+ else:
56
+ data = form_factor_params[:, atom_names]
57
+ return data[0], data[1]
Binary file
@@ -0,0 +1,10 @@
1
+ from ._coordinates import (
2
+ AbstractCoordinates as AbstractCoordinates,
3
+ cartesian_to_polar as cartesian_to_polar,
4
+ CoordinateGrid as CoordinateGrid,
5
+ CoordinateList as CoordinateList,
6
+ FrequencyGrid as FrequencyGrid,
7
+ FrequencySlice as FrequencySlice,
8
+ make_coordinates as make_coordinates,
9
+ make_frequencies as make_frequencies,
10
+ )
@@ -0,0 +1,287 @@
1
+ """
2
+ Coordinate functionality in cryojax.
3
+ """
4
+
5
+ from abc import abstractmethod
6
+ from typing import Any, Optional
7
+ from typing_extensions import Self
8
+
9
+ import equinox as eqx
10
+ import jax
11
+ import jax.numpy as jnp
12
+ from equinox import AbstractVar
13
+ from jaxtyping import Array, ArrayLike, Float
14
+
15
+ from ..typing import (
16
+ Image,
17
+ ImageCoords,
18
+ PointCloudCoords2D,
19
+ PointCloudCoords3D,
20
+ VolumeCoords,
21
+ VolumeSliceCoords,
22
+ )
23
+
24
+
25
+ class AbstractCoordinates(eqx.Module, strict=True):
26
+ """
27
+ A base class that wraps a coordinate array.
28
+ """
29
+
30
+ array: AbstractVar[Any]
31
+
32
+ @abstractmethod
33
+ def get(self) -> Any:
34
+ """Get the coordinates."""
35
+ raise NotImplementedError
36
+
37
+ def __mul__(self, arr: ArrayLike) -> Self:
38
+ # The following line seems to be required for differentiability with
39
+ # respect to arr
40
+ rescaled_array = jnp.where(
41
+ self.array != 0.0, self.array * jnp.asarray(arr), 0.0
42
+ )
43
+ return eqx.tree_at(lambda x: x.array, self, rescaled_array)
44
+
45
+ def __rmul__(self, arr: ArrayLike) -> Self:
46
+ rescaled_array = jnp.where(
47
+ self.array != 0.0, jnp.asarray(arr) * self.array, 0.0
48
+ )
49
+ return eqx.tree_at(lambda x: x.array, self, rescaled_array)
50
+
51
+ def __truediv__(self, arr: ArrayLike) -> Self:
52
+ rescaled_array = jnp.where(
53
+ self.array != 0.0, self.array / jnp.asarray(arr), 0.0
54
+ )
55
+ return eqx.tree_at(lambda x: x.array, self, rescaled_array)
56
+
57
+
58
+ class CoordinateList(AbstractCoordinates, strict=True):
59
+ """
60
+ A Pytree that wraps a coordinate list.
61
+ """
62
+
63
+ array: PointCloudCoords3D | PointCloudCoords2D = eqx.field(converter=jnp.asarray)
64
+
65
+ def __init__(self, coordinate_list: PointCloudCoords2D | PointCloudCoords3D):
66
+ self.array = coordinate_list
67
+
68
+ def get(self) -> PointCloudCoords3D | PointCloudCoords2D:
69
+ return self.array
70
+
71
+
72
+ class CoordinateGrid(AbstractCoordinates, strict=True):
73
+ """
74
+ A Pytree that wraps a coordinate grid.
75
+ """
76
+
77
+ array: ImageCoords | VolumeCoords = eqx.field(converter=jnp.asarray)
78
+
79
+ def __init__(
80
+ self,
81
+ shape: tuple[int, ...],
82
+ grid_spacing: float | ArrayLike = 1.0,
83
+ ):
84
+ self.array = make_coordinates(shape, grid_spacing)
85
+
86
+ def get(self) -> ImageCoords | VolumeCoords:
87
+ return jax.lax.stop_gradient(self.array)
88
+
89
+
90
+ class FrequencyGrid(AbstractCoordinates, strict=True):
91
+ """
92
+ A Pytree that wraps a frequency grid.
93
+ """
94
+
95
+ array: ImageCoords | VolumeCoords = eqx.field(converter=jnp.asarray)
96
+
97
+ def __init__(
98
+ self,
99
+ shape: tuple[int, ...],
100
+ grid_spacing: float | ArrayLike = 1.0,
101
+ half_space: bool = True,
102
+ ):
103
+ self.array = make_frequencies(shape, grid_spacing, half_space=half_space)
104
+
105
+ def get(self) -> ImageCoords | VolumeCoords:
106
+ return jax.lax.stop_gradient(self.array)
107
+
108
+
109
+ class FrequencySlice(AbstractCoordinates, strict=True):
110
+ """
111
+ A Pytree that wraps a frequency slice.
112
+
113
+ Unlike a `FrequencyGrid`, a `FrequencySlice` has the zero frequency
114
+ component in the center.
115
+ """
116
+
117
+ array: VolumeSliceCoords = eqx.field(converter=jnp.asarray)
118
+
119
+ def __init__(
120
+ self,
121
+ shape: tuple[int, int],
122
+ grid_spacing: float | ArrayLike = 1.0,
123
+ half_space: bool = True,
124
+ ):
125
+ frequency_slice = make_frequencies(shape, grid_spacing, half_space=half_space)
126
+ if half_space:
127
+ frequency_slice = jnp.fft.fftshift(frequency_slice, axes=(0,))
128
+ else:
129
+ frequency_slice = jnp.fft.fftshift(frequency_slice, axes=(0, 1))
130
+ frequency_slice = jnp.expand_dims(
131
+ jnp.pad(
132
+ frequency_slice,
133
+ ((0, 0), (0, 0), (0, 1)),
134
+ mode="constant",
135
+ constant_values=0.0,
136
+ ),
137
+ axis=0,
138
+ )
139
+ self.array = frequency_slice
140
+
141
+ def get(self) -> VolumeSliceCoords:
142
+ return jax.lax.stop_gradient(self.array)
143
+
144
+
145
+ def make_coordinates(
146
+ shape: tuple[int, ...], grid_spacing: float | ArrayLike = 1.0
147
+ ) -> Float[Array, "*shape len(shape)"]:
148
+ """
149
+ Create a real-space cartesian coordinate system on a grid.
150
+
151
+ Arguments
152
+ ---------
153
+ shape :
154
+ Shape of the voxel grid, with
155
+ ``ndim = len(shape)``.
156
+ grid_spacing :
157
+ The grid spacing, in units of length.
158
+
159
+ Returns
160
+ -------
161
+ coordinate_grid :
162
+ Cartesian coordinate system in real space.
163
+ """
164
+ coordinate_grid = _make_coordinates_or_frequencies(
165
+ shape, grid_spacing=grid_spacing, real_space=True
166
+ )
167
+ return coordinate_grid
168
+
169
+
170
+ def make_frequencies(
171
+ shape: tuple[int, ...],
172
+ grid_spacing: float | ArrayLike = 1.0,
173
+ half_space: bool = True,
174
+ ) -> Float[Array, "*shape len(shape)"]:
175
+ """
176
+ Create a fourier-space cartesian coordinate system on a grid.
177
+ The zero-frequency component is in the beginning.
178
+
179
+ Arguments
180
+ ---------
181
+ shape :
182
+ Shape of the voxel grid, with
183
+ ``ndim = len(shape)``.
184
+ grid_spacing :
185
+ The grid spacing, in units of length.
186
+ half_space :
187
+ Return a frequency grid on the half space.
188
+ ``shape[-1]`` is the axis on which the negative
189
+ frequencies are omitted.
190
+
191
+ Returns
192
+ -------
193
+ frequency_grid :
194
+ Cartesian coordinate system in frequency space.
195
+ """
196
+ frequency_grid = _make_coordinates_or_frequencies(
197
+ shape,
198
+ grid_spacing=grid_spacing,
199
+ real_space=False,
200
+ half_space=half_space,
201
+ )
202
+ return frequency_grid
203
+
204
+
205
+ def cartesian_to_polar(freqs: ImageCoords, square: bool = False) -> tuple[Image, Image]:
206
+ """
207
+ Convert from cartesian to polar coordinates.
208
+
209
+ Arguments
210
+ ---------
211
+ freqs :
212
+ The cartesian coordinate system.
213
+ square :
214
+ If ``True``, return the square of the
215
+ radial coordinate :math:`|r|^2`. Otherwise,
216
+ return :math:`|r|`.
217
+ """
218
+ theta = jnp.arctan2(freqs[..., 0], freqs[..., 1])
219
+ k_sqr = jnp.sum(jnp.square(freqs), axis=-1)
220
+ if square:
221
+ return k_sqr, theta
222
+ else:
223
+ kr = jnp.sqrt(k_sqr)
224
+ return kr, theta
225
+
226
+
227
+ def _make_coordinates_or_frequencies(
228
+ shape: tuple[int, ...],
229
+ grid_spacing: float | ArrayLike = 1.0,
230
+ real_space: bool = False,
231
+ half_space: bool = True,
232
+ ) -> Float[Array, "*shape len(shape)"]:
233
+ ndim = len(shape)
234
+ coords1D = []
235
+ for idx in range(ndim):
236
+ if real_space:
237
+ c1D = _make_coordinates_or_frequencies_1d(
238
+ shape[idx], grid_spacing, real_space
239
+ )
240
+ else:
241
+ if not half_space:
242
+ rfftfreq = False
243
+ else:
244
+ rfftfreq = False if idx < ndim - 1 else True
245
+ c1D = _make_coordinates_or_frequencies_1d(
246
+ shape[idx], grid_spacing, real_space, rfftfreq
247
+ )
248
+ coords1D.append(c1D)
249
+ if ndim == 2:
250
+ y, x = coords1D
251
+ xv, yv = jnp.meshgrid(x, y, indexing="xy")
252
+ coords = jnp.stack([xv, yv], axis=-1)
253
+ elif ndim == 3:
254
+ z, y, x = coords1D
255
+ xv, yv, zv = jnp.meshgrid(x, y, z, indexing="xy")
256
+ xv, yv, zv = [
257
+ jnp.transpose(rv, axes=[2, 0, 1]) for rv in [xv, yv, zv]
258
+ ] # Change axis ordering to [z, y, x]
259
+ coords = jnp.stack([xv, yv, zv], axis=-1)
260
+ else:
261
+ raise ValueError(
262
+ "Only 2D and 3D coordinate grids are supported. "
263
+ f"Tried to create a grid of shape {shape}."
264
+ )
265
+
266
+ return coords
267
+
268
+
269
+ def _make_coordinates_or_frequencies_1d(
270
+ size: int,
271
+ grid_spacing: float | ArrayLike,
272
+ real_space: bool = False,
273
+ rfftfreq: Optional[bool] = None,
274
+ ) -> Float[Array, " size"]:
275
+ """One-dimensional coordinates in real or fourier space"""
276
+ if real_space:
277
+ make_1d = (
278
+ lambda size, dx: jnp.fft.fftshift(jnp.fft.fftfreq(size, 1 / dx)) * size
279
+ )
280
+ else:
281
+ if rfftfreq is None:
282
+ raise ValueError("Argument rfftfreq cannot be None if real_space=False.")
283
+ else:
284
+ fn = jnp.fft.rfftfreq if rfftfreq else jnp.fft.fftfreq
285
+ make_1d = lambda size, dx: fn(size, grid_spacing)
286
+
287
+ return make_1d(size, grid_spacing)
@@ -0,0 +1,12 @@
1
+ from ._errors import (
2
+ error_if_negative as error_if_negative,
3
+ error_if_not_fractional as error_if_not_fractional,
4
+ error_if_not_positive as error_if_not_positive,
5
+ error_if_zero as error_if_zero,
6
+ )
7
+ from ._filter_specs import get_filter_spec as get_filter_spec
8
+ from ._filtered_transformations import (
9
+ filter_grad_with_spec as filter_grad_with_spec,
10
+ filter_value_and_grad_with_spec as filter_value_and_grad_with_spec,
11
+ filter_vmap_with_spec as filter_vmap_with_spec,
12
+ )
@@ -0,0 +1,35 @@
1
+ """
2
+ Utilities for runtime errors, wrapping `equinox.error_if`.
3
+ """
4
+
5
+ import equinox as eqx
6
+ import jax.numpy as jnp
7
+ from jaxtyping import Array, ArrayLike
8
+
9
+
10
+ def error_if_negative(x: ArrayLike) -> Array:
11
+ x = jnp.asarray(x)
12
+ return eqx.error_if(x, x < 0, "A non-negative quantity was found to be negative!")
13
+
14
+
15
+ def error_if_not_positive(x: ArrayLike) -> Array:
16
+ x = jnp.asarray(x)
17
+ return eqx.error_if(
18
+ x, x <= 0, "A positive quantity was found to be negative or zero!"
19
+ )
20
+
21
+
22
+ def error_if_zero(x: ArrayLike) -> Array:
23
+ x = jnp.asarray(x)
24
+ return eqx.error_if(
25
+ x, jnp.isclose(x, 0.0), "A non-zero quantity was found to be zero!"
26
+ )
27
+
28
+
29
+ def error_if_not_fractional(x: ArrayLike) -> Array:
30
+ x = jnp.asarray(x)
31
+ return eqx.error_if(
32
+ x,
33
+ ~jnp.logical_and(x >= 0.0, x <= 1.0),
34
+ "A fractional quantity was found to not be between 0 and 1!",
35
+ )
@@ -0,0 +1,28 @@
1
+ """
2
+ Utilities for creating equinox filter_specs.
3
+ """
4
+
5
+ from typing import Any, Callable, Optional, Sequence, Union
6
+
7
+ import equinox as eqx
8
+ import jax.tree_util as jtu
9
+ from jaxtyping import PyTree
10
+
11
+
12
+ def get_filter_spec(
13
+ pytree: PyTree,
14
+ where: Callable[[PyTree], Union[Any, Sequence[Any]]],
15
+ *,
16
+ inverse: bool = False,
17
+ is_leaf: Optional[Callable[[Any], bool]] = None,
18
+ ) -> PyTree[bool]:
19
+ if not inverse:
20
+ false_pytree = jtu.tree_map(lambda _: False, pytree)
21
+ return eqx.tree_at(
22
+ where, false_pytree, replace_fn=lambda _: True, is_leaf=is_leaf
23
+ )
24
+ else:
25
+ true_pytree = jtu.tree_map(lambda _: True, pytree)
26
+ return eqx.tree_at(
27
+ where, true_pytree, replace_fn=lambda _: False, is_leaf=is_leaf
28
+ )
@@ -0,0 +1,105 @@
1
+ """
2
+ Utilities for creating equinox filtered transformations. These routines
3
+ are modified from [`zodiax`](https://github.com/LouisDesdoigts/zodiax), which
4
+ was created for the project [`dLux`](https://louisdesdoigts.github.io/dLux/).
5
+ """
6
+
7
+ from functools import partial, wraps
8
+ from typing import Any, Callable, Hashable, Optional, Union
9
+
10
+ import equinox as eqx
11
+ from jaxtyping import PyTree
12
+
13
+
14
+ def filter_grad_with_spec(
15
+ func: Callable,
16
+ filter_spec: PyTree[Union[bool, Callable[[Any], bool]]],
17
+ is_leaf: Optional[Callable[[Any], bool]] = None,
18
+ *,
19
+ has_aux: bool = False,
20
+ ) -> Callable:
21
+ @wraps(func)
22
+ def partition_and_recombine_fn(pytree: PyTree, *args: Any, **kwargs: Any):
23
+ @partial(
24
+ eqx.filter_grad,
25
+ has_aux=has_aux,
26
+ )
27
+ def recombine_fn(
28
+ pytree_if_true: PyTree, pytree_if_false: PyTree, *args: Any, **kwargs: Any
29
+ ):
30
+ pytree = eqx.combine(pytree_if_true, pytree_if_false, is_leaf=is_leaf)
31
+ return func(pytree, *args, **kwargs)
32
+
33
+ pytree_if_true, pytree_if_false = eqx.partition(
34
+ pytree, filter_spec, is_leaf=is_leaf
35
+ )
36
+ return recombine_fn(pytree_if_true, pytree_if_false, *args, **kwargs)
37
+
38
+ return partition_and_recombine_fn
39
+
40
+
41
+ def filter_value_and_grad_with_spec(
42
+ func: Callable,
43
+ filter_spec: PyTree[Union[bool, Callable[[Any], bool]]],
44
+ is_leaf: Optional[Callable[[Any], bool]] = None,
45
+ *,
46
+ has_aux: bool = False,
47
+ ) -> Callable:
48
+ @wraps(func)
49
+ def partition_and_recombine_fn(pytree: PyTree, *args: Any, **kwargs: Any):
50
+ @partial(
51
+ eqx.filter_value_and_grad,
52
+ has_aux=has_aux,
53
+ )
54
+ def recombine_fn(
55
+ pytree_if_true: PyTree, pytree_if_false: PyTree, *args: Any, **kwargs: Any
56
+ ):
57
+ pytree = eqx.combine(pytree_if_true, pytree_if_false, is_leaf=is_leaf)
58
+ return func(pytree, *args, **kwargs)
59
+
60
+ pytree_if_true, pytree_if_false = eqx.partition(
61
+ pytree, filter_spec, is_leaf=is_leaf
62
+ )
63
+ return recombine_fn(pytree_if_true, pytree_if_false, *args, **kwargs)
64
+
65
+ return partition_and_recombine_fn
66
+
67
+
68
+ def filter_vmap_with_spec(
69
+ func: Callable,
70
+ filter_spec: PyTree[Union[bool, Callable[[Any], bool]]],
71
+ is_leaf: Optional[Callable[[Any], bool]] = None,
72
+ *,
73
+ in_axes: PyTree[Union[int, None, Callable[[Any], Optional[int]]]] = eqx.if_array(
74
+ axis=0
75
+ ),
76
+ out_axes: PyTree[Union[int, None, Callable[[Any], Optional[int]]]] = eqx.if_array(
77
+ axis=0
78
+ ),
79
+ axis_name: Hashable = None,
80
+ axis_size: Optional[int] = None,
81
+ ) -> Callable:
82
+ @wraps(func)
83
+ def partition_and_recombine_fn(pytree: PyTree, *args: Any):
84
+ @partial(
85
+ eqx.filter_vmap,
86
+ in_axes=(in_axes, None),
87
+ out_axes=out_axes,
88
+ axis_name=axis_name,
89
+ axis_size=axis_size,
90
+ )
91
+ def recombine_fn(
92
+ pytree_if_true_with_args: tuple[PyTree, ...],
93
+ pytree_if_false: PyTree,
94
+ ):
95
+ pytree_if_true, *args = pytree_if_true_with_args
96
+
97
+ pytree = eqx.combine(pytree_if_true, pytree_if_false, is_leaf=is_leaf)
98
+ return func(pytree, *args)
99
+
100
+ pytree_if_true, pytree_if_false = eqx.partition(
101
+ pytree, filter_spec, is_leaf=is_leaf
102
+ )
103
+ return recombine_fn((pytree_if_true, *args), pytree_if_false)
104
+
105
+ return partition_and_recombine_fn
File without changes
@@ -0,0 +1,16 @@
1
+ # file generated by setuptools_scm
2
+ # don't change, don't track in version control
3
+ TYPE_CHECKING = False
4
+ if TYPE_CHECKING:
5
+ from typing import Tuple, Union
6
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
7
+ else:
8
+ VERSION_TUPLE = object
9
+
10
+ version: str
11
+ __version__: str
12
+ __version_tuple__: VERSION_TUPLE
13
+ version_tuple: VERSION_TUPLE
14
+
15
+ __version__ = version = '0.2.2'
16
+ __version_tuple__ = version_tuple = (0, 2, 2)
@@ -0,0 +1,11 @@
1
+ from ._dataset import AbstractDataset as AbstractDataset
2
+ from ._particle_stack import (
3
+ AbstractParticleStack as AbstractParticleStack,
4
+ CryojaxParticleStack as CryojaxParticleStack,
5
+ )
6
+ from ._relion import (
7
+ default_relion_make_config as default_relion_make_config,
8
+ HelicalRelionDataset as HelicalRelionDataset,
9
+ RelionDataset as RelionDataset,
10
+ RelionParticleStack as RelionParticleStack,
11
+ )
@@ -0,0 +1,91 @@
1
+ """Functionality in `cryojax` for representing datasets."""
2
+
3
+ import abc
4
+ import dataclasses
5
+ from typing import Any
6
+
7
+ from ._particle_stack import AbstractParticleStack
8
+
9
+
10
+ @dataclasses.dataclass(frozen=True)
11
+ class AbstractDataset(metaclass=abc.ABCMeta):
12
+ """An abstraction of a dataset in `cryojax`. To create an
13
+ `AbstractDataset`, implement its `__init__`, `__getitem__`, and
14
+ `__len__` methods.
15
+
16
+ This follows the
17
+ [`torch.utils.data.Dataset`](https://pytorch.org/docs/stable/data.html#torch.utils.data.Dataset)
18
+ API and can easily be wrapped into a pytorch `Dataset` with the
19
+ following pattern:
20
+
21
+ ```python
22
+ from torch.utils.data import Dataset
23
+
24
+ class CustomTorchDataset(Dataset):
25
+
26
+ def __init__(cryojax_dataset: AbstractDataset):
27
+ self.cryojax_dataset = cryojax_dataset
28
+
29
+ def __getitem___(self, index) -> AbstractParticleStack:
30
+ return self.cryojax_dataset[index]
31
+
32
+ def __len__(self) -> int:
33
+ return len(self.cryojax_dataset)
34
+ ```
35
+
36
+ !!! question "How do I implement an `AbstractDataset`?"
37
+
38
+ Implementing an `AbstractDataset` is not like implementing
39
+ most other classes in `cryojax`, which are `equinox.Module`s.
40
+ An `equinox.Module` is just a pytree, so it can be safely
41
+ passed to `jax` transformations. However, an `AbstractDataset`
42
+ can *not* be passed to `jax` transformations. Therefore, it is
43
+ not a pytree. Rather, it is a [frozen dataclass](https://docs.python.org/3/library/dataclasses.html#frozen-instances).
44
+
45
+ There are gotchas when implementing frozen dataclasses. For example,
46
+ the following will result in a `FrozenInstanceError`:
47
+
48
+ ```python
49
+ import dataclasses
50
+
51
+ @dataclasses.dataclass(frozen=True)
52
+ class BuggyFrozenDataclass:
53
+
54
+ a: int
55
+
56
+ def __init__(self, a: int):
57
+ self.a = a
58
+
59
+ BuggyFrozenDataclass(10) # Will raise the FrozenInstanceError
60
+ ```
61
+
62
+ As of the time of writing this, frozen dataclasses must use the following
63
+ syntax to set attributes in a custom `__init__`:
64
+
65
+ ```python
66
+ import dataclasses
67
+
68
+ @dataclasses.dataclass(frozen=True)
69
+ class CorrectFrozenDataclass:
70
+
71
+ a: int
72
+
73
+ def __init__(self, a: int):
74
+ object.__setattr__(self, "a", a)
75
+
76
+ example = CorrectFrozenDataclass(10) # Will not raise a FrozenInstanceError
77
+ print(example.a) # This will print a, which here was 10
78
+ ```
79
+ """
80
+
81
+ @abc.abstractmethod
82
+ def __init__(self, *args: Any, **kwargs: Any):
83
+ raise NotImplementedError
84
+
85
+ @abc.abstractmethod
86
+ def __getitem__(self, index) -> AbstractParticleStack:
87
+ raise NotImplementedError
88
+
89
+ @abc.abstractmethod
90
+ def __len__(self) -> int:
91
+ raise NotImplementedError