cryojax 0.3.3__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.
- cryojax/__init__.py +10 -0
- cryojax/constants/__init__.py +7 -0
- cryojax/constants/_scattering_factor_parameters.py +67 -0
- cryojax/constants/_unit_conversions.py +25 -0
- cryojax/constants/peng1996_element_params.npy +0 -0
- cryojax/coordinates/__init__.py +8 -0
- cryojax/coordinates/_geometry.py +26 -0
- cryojax/coordinates/_make_coordinate_grids.py +246 -0
- cryojax/cryojax_version.py +16 -0
- cryojax/data/__init__.py +15 -0
- cryojax/data/_dataset.py +95 -0
- cryojax/data/_particle_stack.py +15 -0
- cryojax/data/_relion/__init__.py +13 -0
- cryojax/data/_relion/_starfile_reading.py +788 -0
- cryojax/data/_relion/_starfile_writing.py +578 -0
- cryojax/experimental/__init__.py +16 -0
- cryojax/image/__init__.py +34 -0
- cryojax/image/_average.py +88 -0
- cryojax/image/_downsample.py +132 -0
- cryojax/image/_edges.py +192 -0
- cryojax/image/_fft.py +99 -0
- cryojax/image/_map_coordinates.py +255 -0
- cryojax/image/_normalize.py +99 -0
- cryojax/image/_rescale_pixel_size.py +138 -0
- cryojax/image/_spectrum.py +60 -0
- cryojax/image/operators/__init__.py +42 -0
- cryojax/image/operators/_filters.py +338 -0
- cryojax/image/operators/_fourier_operator.py +202 -0
- cryojax/image/operators/_masks.py +420 -0
- cryojax/image/operators/_operator.py +207 -0
- cryojax/image/operators/_real_operator.py +86 -0
- cryojax/inference/__init__.py +20 -0
- cryojax/inference/_grid_search/__init__.py +17 -0
- cryojax/inference/_grid_search/custom_types.py +10 -0
- cryojax/inference/_grid_search/pytree_manipulation.py +205 -0
- cryojax/inference/_grid_search/search_loop.py +158 -0
- cryojax/inference/_grid_search/search_method.py +309 -0
- cryojax/inference/_lie_group_transforms.py +138 -0
- cryojax/inference/distributions/__init__.py +9 -0
- cryojax/inference/distributions/_base_distribution.py +58 -0
- cryojax/inference/distributions/_gaussian_distributions.py +321 -0
- cryojax/internal/__init__.py +7 -0
- cryojax/internal/_errors.py +35 -0
- cryojax/internal/_loop.py +114 -0
- cryojax/io/__init__.py +23 -0
- cryojax/io/_gemmi.py +182 -0
- cryojax/io/_mdtraj.py +43 -0
- cryojax/io/_mrc.py +240 -0
- cryojax/io/_pdb_and_cif.py +224 -0
- cryojax/io/_starfile.py +28 -0
- cryojax/rotations/__init__.py +9 -0
- cryojax/rotations/_lie_group.py +522 -0
- cryojax/rotations/_rotation.py +67 -0
- cryojax/rotations/_utils.py +61 -0
- cryojax/simulator/__init__.py +69 -0
- cryojax/simulator/_detector.py +218 -0
- cryojax/simulator/_imaging_pipeline.py +423 -0
- cryojax/simulator/_instrument_config.py +261 -0
- cryojax/simulator/_multislice_integrator/__init__.py +4 -0
- cryojax/simulator/_multislice_integrator/base_multislice_integrator.py +24 -0
- cryojax/simulator/_multislice_integrator/fft_multislice_integrator.py +221 -0
- cryojax/simulator/_pose.py +279 -0
- cryojax/simulator/_potential_integrator/__init__.py +14 -0
- cryojax/simulator/_potential_integrator/atom_potential_integrator.py +159 -0
- cryojax/simulator/_potential_integrator/base_potential_integrator.py +82 -0
- cryojax/simulator/_potential_integrator/fourier_voxel_extract.py +513 -0
- cryojax/simulator/_potential_integrator/nufft_project.py +134 -0
- cryojax/simulator/_potential_representation/__init__.py +17 -0
- cryojax/simulator/_potential_representation/atom_potential.py +584 -0
- cryojax/simulator/_potential_representation/base_potential.py +26 -0
- cryojax/simulator/_potential_representation/voxel_potential.py +435 -0
- cryojax/simulator/_scattering_theory/__init__.py +18 -0
- cryojax/simulator/_scattering_theory/base_scattering_theory.py +120 -0
- cryojax/simulator/_scattering_theory/common_functions.py +44 -0
- cryojax/simulator/_scattering_theory/high_energy_scattering_theory.py +110 -0
- cryojax/simulator/_scattering_theory/multislice_scattering_theory.py +53 -0
- cryojax/simulator/_scattering_theory/weak_phase_scattering_theory.py +337 -0
- cryojax/simulator/_solvent.py +123 -0
- cryojax/simulator/_structural_ensemble/__init__.py +18 -0
- cryojax/simulator/_structural_ensemble/assembly/__init__.py +9 -0
- cryojax/simulator/_structural_ensemble/assembly/base_assembly.py +199 -0
- cryojax/simulator/_structural_ensemble/assembly/helix.py +280 -0
- cryojax/simulator/_structural_ensemble/base_conformation.py +19 -0
- cryojax/simulator/_structural_ensemble/base_ensemble.py +63 -0
- cryojax/simulator/_structural_ensemble/discrete_ensemble.py +60 -0
- cryojax/simulator/_transfer_theory/__init__.py +12 -0
- cryojax/simulator/_transfer_theory/base_transfer_theory.py +53 -0
- cryojax/simulator/_transfer_theory/common_functions.py +63 -0
- cryojax/simulator/_transfer_theory/contrast_transfer_theory.py +150 -0
- cryojax/simulator/_transfer_theory/wave_transfer_theory.py +139 -0
- cryojax/utils/__init__.py +17 -0
- cryojax/utils/_filter_specs.py +46 -0
- cryojax/utils/_filtered_transformations.py +117 -0
- cryojax/utils/_transforms.py +130 -0
- cryojax-0.3.3.dist-info/METADATA +666 -0
- cryojax-0.3.3.dist-info/RECORD +98 -0
- cryojax-0.3.3.dist-info/WHEEL +4 -0
- cryojax-0.3.3.dist-info/licenses/LICENSE +504 -0
cryojax/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
from ._scattering_factor_parameters import (
|
|
2
|
+
get_tabulated_scattering_factor_parameters as get_tabulated_scattering_factor_parameters, # noqa: E501
|
|
3
|
+
read_peng_element_scattering_factor_parameter_table as read_peng_element_scattering_factor_parameter_table, # noqa: E501
|
|
4
|
+
)
|
|
5
|
+
from ._unit_conversions import (
|
|
6
|
+
convert_keV_to_angstroms as convert_keV_to_angstroms,
|
|
7
|
+
)
|
|
@@ -0,0 +1,67 @@
|
|
|
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 typing import Optional
|
|
9
|
+
|
|
10
|
+
import jax.numpy as jnp
|
|
11
|
+
import numpy as np
|
|
12
|
+
from jaxtyping import Array, Float, Int
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def get_tabulated_scattering_factor_parameters(
|
|
16
|
+
atom_identities: Int[Array, " n_atoms"] | Int[np.ndarray, " n_atoms"],
|
|
17
|
+
scattering_factor_parameter_table: Optional[
|
|
18
|
+
Float[Array, "n_params n_elements n_scattering_factors"]
|
|
19
|
+
| Float[np.ndarray, "n_params n_elements n_scattering_factors"]
|
|
20
|
+
] = None,
|
|
21
|
+
) -> Float[Array, "n_params n_atoms n_scattering_factors"]:
|
|
22
|
+
"""Gets the parameters for the scattering factor for each atom in
|
|
23
|
+
`atom_identities`.
|
|
24
|
+
|
|
25
|
+
**Arguments:**
|
|
26
|
+
|
|
27
|
+
- `atom_identitites`:
|
|
28
|
+
Array containing the index of the one-hot encoded atom names.
|
|
29
|
+
By default, Hydrogen is "1", Carbon is "6", Nitrogen is "7", etc.
|
|
30
|
+
- `scattering_factor_parameter_table`:
|
|
31
|
+
Array containing the table of scattering factors. By default, this
|
|
32
|
+
is the tabulation from "Robust Parameterization of Elastic and
|
|
33
|
+
Absorptive Electron Atomic Scattering Factors" by Peng et al. (1996),
|
|
34
|
+
given by `load_peng_element_scattering_factor_parameter_table`.
|
|
35
|
+
|
|
36
|
+
**Returns:**
|
|
37
|
+
|
|
38
|
+
The particular scattering factor parameters stored in
|
|
39
|
+
`scattering_factor_parameter_table` for `atom_identities`.
|
|
40
|
+
"""
|
|
41
|
+
if scattering_factor_parameter_table is None:
|
|
42
|
+
scattering_factor_parameter_table = (
|
|
43
|
+
read_peng_element_scattering_factor_parameter_table()
|
|
44
|
+
)
|
|
45
|
+
return jnp.asarray(scattering_factor_parameter_table)[:, jnp.asarray(atom_identities)]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def read_peng_element_scattering_factor_parameter_table() -> (
|
|
49
|
+
Float[np.ndarray, "2 n_elements 5"]
|
|
50
|
+
):
|
|
51
|
+
r"""Function to load the atomic scattering factor parameter
|
|
52
|
+
table from "Robust Parameterization of Elastic and Absorptive
|
|
53
|
+
Electron Atomic Scattering Factors" by Peng et al. (1996).
|
|
54
|
+
|
|
55
|
+
**Returns:**
|
|
56
|
+
|
|
57
|
+
The parameter table for parameters $\{a_i\}_{i = 1}^5$ and $\{b_i\}_{i = 1}^5$
|
|
58
|
+
for each atom, described in the above reference.
|
|
59
|
+
"""
|
|
60
|
+
with pkg_resources.as_file(
|
|
61
|
+
pkg_resources.files("cryojax").joinpath("constants")
|
|
62
|
+
) as path:
|
|
63
|
+
atom_scattering_factor_params = jnp.load(
|
|
64
|
+
os.path.join(path, "peng1996_element_params.npy")
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
return np.asarray(atom_scattering_factor_params)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Unit conversions."""
|
|
2
|
+
|
|
3
|
+
import jax.numpy as jnp
|
|
4
|
+
from jaxtyping import Array, Float
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def convert_keV_to_angstroms(
|
|
8
|
+
energy_in_keV: Float[Array, ""] | float,
|
|
9
|
+
) -> Float[Array, ""]:
|
|
10
|
+
"""Get the relativistic electron wavelength at a given accelerating voltage. For
|
|
11
|
+
reference, see Equation 2.5 in Section 2.1 from *Spence, John CH. High-resolution
|
|
12
|
+
electron microscopy. OUP Oxford, 2013.*.
|
|
13
|
+
|
|
14
|
+
**Arguments:**
|
|
15
|
+
|
|
16
|
+
- `energy_in_keV`:
|
|
17
|
+
The energy in kiloelectron volts.
|
|
18
|
+
|
|
19
|
+
**Returns:**
|
|
20
|
+
|
|
21
|
+
The relativistically corrected electron wavelength in Angstroms corresponding to the
|
|
22
|
+
energy `energy_in_keV`.
|
|
23
|
+
"""
|
|
24
|
+
energy_in_eV = 1000.0 * energy_in_keV # keV to eV
|
|
25
|
+
return jnp.asarray(12.2639 / (energy_in_eV + 0.97845e-6 * energy_in_eV**2) ** 0.5)
|
|
Binary file
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
from ._geometry import cartesian_to_polar as cartesian_to_polar
|
|
2
|
+
from ._make_coordinate_grids import (
|
|
3
|
+
make_1d_coordinate_grid as make_1d_coordinate_grid,
|
|
4
|
+
make_1d_frequency_grid as make_1d_frequency_grid,
|
|
5
|
+
make_coordinate_grid as make_coordinate_grid,
|
|
6
|
+
make_frequency_grid as make_frequency_grid,
|
|
7
|
+
make_frequency_slice as make_frequency_slice,
|
|
8
|
+
)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import jax.numpy as jnp
|
|
2
|
+
from jaxtyping import Array, Float, Inexact
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def cartesian_to_polar(
|
|
6
|
+
coordinate_or_frequency_grid: Float[Array, "y_dim x_dim 2"], square: bool = False
|
|
7
|
+
) -> tuple[Inexact[Array, "y_dim x_dim"], Inexact[Array, "y_dim x_dim"]]:
|
|
8
|
+
"""Convert from cartesian to polar coordinates.
|
|
9
|
+
|
|
10
|
+
**Arguments:**
|
|
11
|
+
|
|
12
|
+
- `coordinate_or_frequency_grid`:
|
|
13
|
+
The cartesian coordinate system in real or fourier space.
|
|
14
|
+
- `square`:
|
|
15
|
+
If `True`, return the square of the radial coordinate
|
|
16
|
+
$|r|^2$. Otherwise, return $|r|$.
|
|
17
|
+
"""
|
|
18
|
+
theta = jnp.arctan2(
|
|
19
|
+
coordinate_or_frequency_grid[..., 0], coordinate_or_frequency_grid[..., 1]
|
|
20
|
+
)
|
|
21
|
+
k_sqr = jnp.sum(jnp.square(coordinate_or_frequency_grid), axis=-1)
|
|
22
|
+
if square:
|
|
23
|
+
return k_sqr, theta
|
|
24
|
+
else:
|
|
25
|
+
kr = jnp.sqrt(k_sqr)
|
|
26
|
+
return kr, theta
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Functions for creating coordinate systems.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
import jax.numpy as jnp
|
|
8
|
+
import numpy as np
|
|
9
|
+
from jaxtyping import Array, Float
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def make_coordinate_grid(
|
|
13
|
+
shape: tuple[int, ...],
|
|
14
|
+
grid_spacing: float | Float[np.ndarray, ""] | Float[Array, ""] = 1.0,
|
|
15
|
+
) -> Float[Array, "*shape ndim"]:
|
|
16
|
+
"""
|
|
17
|
+
Create a real-space cartesian coordinate system on a grid.
|
|
18
|
+
|
|
19
|
+
**Arguments:**
|
|
20
|
+
|
|
21
|
+
- `shape`:
|
|
22
|
+
Shape of the grid, with `ndim = len(shape)`.
|
|
23
|
+
- `grid_spacing`:
|
|
24
|
+
The grid spacing (i.e. pixel/voxel size),
|
|
25
|
+
in units of length.
|
|
26
|
+
|
|
27
|
+
**Returns:**
|
|
28
|
+
|
|
29
|
+
A cartesian coordinate system in real space.
|
|
30
|
+
"""
|
|
31
|
+
coordinate_grid = _make_coordinates_or_frequencies(
|
|
32
|
+
shape, grid_spacing=grid_spacing, real_space=True
|
|
33
|
+
)
|
|
34
|
+
return coordinate_grid
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def make_frequency_grid(
|
|
38
|
+
shape: tuple[int, ...],
|
|
39
|
+
grid_spacing: float | Float[np.ndarray, ""] | Float[Array, ""] = 1.0,
|
|
40
|
+
half_space: bool = True,
|
|
41
|
+
) -> Float[Array, "*shape ndim"]:
|
|
42
|
+
"""Create a fourier-space cartesian coordinate system on a grid.
|
|
43
|
+
The zero-frequency component is in the corner.
|
|
44
|
+
|
|
45
|
+
**Arguments:**
|
|
46
|
+
|
|
47
|
+
- `shape`:
|
|
48
|
+
Shape of the grid, with `ndim = len(shape)`.
|
|
49
|
+
- `grid_spacing`:
|
|
50
|
+
The grid spacing (i.e. pixel/voxel size),
|
|
51
|
+
in units of length.
|
|
52
|
+
- `half_space`:
|
|
53
|
+
Return a frequency grid on the half space.
|
|
54
|
+
`shape[-1]` is the axis on which the negative
|
|
55
|
+
frequencies are omitted.
|
|
56
|
+
|
|
57
|
+
**Returns:**
|
|
58
|
+
|
|
59
|
+
A cartesian coordinate system in frequency space.
|
|
60
|
+
"""
|
|
61
|
+
frequency_grid = _make_coordinates_or_frequencies(
|
|
62
|
+
shape,
|
|
63
|
+
grid_spacing=grid_spacing,
|
|
64
|
+
real_space=False,
|
|
65
|
+
half_space=half_space,
|
|
66
|
+
)
|
|
67
|
+
return frequency_grid
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def make_frequency_slice(
|
|
71
|
+
shape: tuple[int, int],
|
|
72
|
+
grid_spacing: float | Float[np.ndarray, ""] | Float[Array, ""] = 1.0,
|
|
73
|
+
half_space: bool = True,
|
|
74
|
+
) -> Float[Array, "1 {shape[0]} {shape[1]} 3"]:
|
|
75
|
+
"""Create a fourier-space cartesian coordinate system on a grid, where
|
|
76
|
+
zero-frequency component is in the *center* of the grid.
|
|
77
|
+
|
|
78
|
+
!!! warning
|
|
79
|
+
In the function `make_frequency_grid`, the convention is that
|
|
80
|
+
the grid is returned with the zero frequency component is in the
|
|
81
|
+
corner. In this function, as mentioned above, frequency slices are
|
|
82
|
+
returned with the zero frequency component in the center. To convert
|
|
83
|
+
between the two conventions, run
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
import jax.numpy as jnp
|
|
87
|
+
from cryojax.coordinates import make_frequency_slice
|
|
88
|
+
|
|
89
|
+
frequency_slice_with_zero_in_center = make_frequency_slice((100, 100)) # Shape (1, 100, 100, 3)
|
|
90
|
+
frequency_slice_with_zero_in_corner = jnp.fft.ifftshift(frequency_slice_with_zero_in_center, axes=(1, 2))
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
The reason for the difference is so that this function can be used to
|
|
94
|
+
directly pass a `frequency_slice` to the `cryojax.simulator.FourierVoxelGridPotential`,
|
|
95
|
+
which requires that the zero is in the center of the grid.
|
|
96
|
+
|
|
97
|
+
**Arguments:**
|
|
98
|
+
|
|
99
|
+
- `shape`:
|
|
100
|
+
Shape of the frequency slice, e.g. `shape = (100, 100)`.
|
|
101
|
+
- `grid_spacing`:
|
|
102
|
+
The grid spacing (i.e. voxel size), in units of length.
|
|
103
|
+
- `half_space`:
|
|
104
|
+
Return a frequency slice on the half space.
|
|
105
|
+
`shape[-1]` is the axis on which the negative
|
|
106
|
+
frequencies are omitted.
|
|
107
|
+
|
|
108
|
+
**Returns:**
|
|
109
|
+
|
|
110
|
+
The central, $q_z = 0$ slice of a 3D frequency grid $(q_x, q_y, q_z)$, where
|
|
111
|
+
zero-frequency component is in the *center* of the grid.
|
|
112
|
+
""" # noqa: E501
|
|
113
|
+
frequency_slice = make_frequency_grid(shape, grid_spacing, half_space=half_space)
|
|
114
|
+
if half_space:
|
|
115
|
+
frequency_slice = jnp.fft.fftshift(frequency_slice, axes=(0,))
|
|
116
|
+
else:
|
|
117
|
+
frequency_slice = jnp.fft.fftshift(frequency_slice, axes=(0, 1))
|
|
118
|
+
frequency_slice = jnp.expand_dims(
|
|
119
|
+
jnp.pad(
|
|
120
|
+
frequency_slice,
|
|
121
|
+
((0, 0), (0, 0), (0, 1)),
|
|
122
|
+
mode="constant",
|
|
123
|
+
constant_values=0.0,
|
|
124
|
+
),
|
|
125
|
+
axis=0,
|
|
126
|
+
)
|
|
127
|
+
return frequency_slice
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def make_1d_coordinate_grid(
|
|
131
|
+
size: int,
|
|
132
|
+
grid_spacing: float | Float[np.ndarray, ""] | Float[Array, ""] = 1.0,
|
|
133
|
+
) -> Float[Array, "*shape ndim"]:
|
|
134
|
+
"""
|
|
135
|
+
Create a 1D real-space cartesian coordinate array.
|
|
136
|
+
|
|
137
|
+
**Arguments:**
|
|
138
|
+
|
|
139
|
+
- `size`:
|
|
140
|
+
Size of the coordinate array.
|
|
141
|
+
- `grid_spacing`:
|
|
142
|
+
The grid spacing (i.e. pixel/voxel size),
|
|
143
|
+
in units of length.
|
|
144
|
+
|
|
145
|
+
**Returns:**
|
|
146
|
+
|
|
147
|
+
A 1D cartesian coordinate array in real space.
|
|
148
|
+
"""
|
|
149
|
+
coordinate_array = _make_coordinates_or_frequencies_1d(
|
|
150
|
+
size, grid_spacing=grid_spacing, real_space=True
|
|
151
|
+
)
|
|
152
|
+
return coordinate_array
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def make_1d_frequency_grid(
|
|
156
|
+
size: int,
|
|
157
|
+
grid_spacing: float | Float[np.ndarray, ""] | Float[Array, ""] = 1.0,
|
|
158
|
+
half_space: bool = True,
|
|
159
|
+
) -> Float[Array, "*shape ndim"]:
|
|
160
|
+
"""Create a 1D fourier-space cartesian coordinate array.
|
|
161
|
+
If `half_space = False`, the zero-frequency component is in the beginning.
|
|
162
|
+
|
|
163
|
+
Arguments
|
|
164
|
+
---------
|
|
165
|
+
- `size`:
|
|
166
|
+
Size of the coordinate array.
|
|
167
|
+
- `grid_spacing`:
|
|
168
|
+
The grid spacing (i.e. pixel/voxel size),
|
|
169
|
+
in units of length.
|
|
170
|
+
- `half_space`:
|
|
171
|
+
Return a frequency grid on the half space.
|
|
172
|
+
`shape[-1]` is the axis on which the negative
|
|
173
|
+
frequencies are omitted.
|
|
174
|
+
|
|
175
|
+
**Returns:**
|
|
176
|
+
|
|
177
|
+
A 1D cartesian coordinate array in frequency space.
|
|
178
|
+
"""
|
|
179
|
+
frequency_array = _make_coordinates_or_frequencies_1d(
|
|
180
|
+
size,
|
|
181
|
+
grid_spacing=grid_spacing,
|
|
182
|
+
real_space=False,
|
|
183
|
+
rfftfreq=half_space,
|
|
184
|
+
)
|
|
185
|
+
return frequency_array
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _make_coordinates_or_frequencies(
|
|
189
|
+
shape: tuple[int, ...],
|
|
190
|
+
grid_spacing: float | Float[np.ndarray, ""] | Float[Array, ""] = 1.0,
|
|
191
|
+
real_space: bool = False,
|
|
192
|
+
half_space: bool = True,
|
|
193
|
+
) -> Float[Array, "*shape ndim"]:
|
|
194
|
+
ndim = len(shape)
|
|
195
|
+
coords1D = []
|
|
196
|
+
for idx in range(ndim):
|
|
197
|
+
if real_space:
|
|
198
|
+
c1D = _make_coordinates_or_frequencies_1d(
|
|
199
|
+
shape[idx], grid_spacing, real_space
|
|
200
|
+
)
|
|
201
|
+
else:
|
|
202
|
+
if not half_space:
|
|
203
|
+
rfftfreq = False
|
|
204
|
+
else:
|
|
205
|
+
rfftfreq = False if idx < ndim - 1 else True
|
|
206
|
+
c1D = _make_coordinates_or_frequencies_1d(
|
|
207
|
+
shape[idx], grid_spacing, real_space, rfftfreq
|
|
208
|
+
)
|
|
209
|
+
coords1D.append(c1D)
|
|
210
|
+
if ndim == 2:
|
|
211
|
+
y, x = coords1D
|
|
212
|
+
xv, yv = jnp.meshgrid(x, y, indexing="xy")
|
|
213
|
+
coords = jnp.stack([xv, yv], axis=-1)
|
|
214
|
+
elif ndim == 3:
|
|
215
|
+
z, y, x = coords1D
|
|
216
|
+
xv, yv, zv = jnp.meshgrid(x, y, z, indexing="xy")
|
|
217
|
+
xv, yv, zv = [
|
|
218
|
+
jnp.transpose(rv, axes=[2, 0, 1]) for rv in [xv, yv, zv]
|
|
219
|
+
] # Change axis ordering to [z, y, x]
|
|
220
|
+
coords = jnp.stack([xv, yv, zv], axis=-1)
|
|
221
|
+
else:
|
|
222
|
+
raise ValueError(
|
|
223
|
+
"Only 2D and 3D coordinate grids are supported. "
|
|
224
|
+
f"Tried to create a grid of shape {shape}."
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
return coords
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _make_coordinates_or_frequencies_1d(
|
|
231
|
+
size: int,
|
|
232
|
+
grid_spacing: float | Float[np.ndarray, ""] | Float[Array, ""],
|
|
233
|
+
real_space: bool = False,
|
|
234
|
+
rfftfreq: Optional[bool] = None,
|
|
235
|
+
) -> Float[Array, " size"]:
|
|
236
|
+
"""One-dimensional coordinates in real or fourier space"""
|
|
237
|
+
if real_space:
|
|
238
|
+
make_1d = lambda size, dx: jnp.fft.fftshift(jnp.fft.fftfreq(size, 1 / dx)) * size
|
|
239
|
+
else:
|
|
240
|
+
if rfftfreq is None:
|
|
241
|
+
raise ValueError("Argument rfftfreq cannot be None if real_space=False.")
|
|
242
|
+
else:
|
|
243
|
+
fn = jnp.fft.rfftfreq if rfftfreq else jnp.fft.fftfreq
|
|
244
|
+
make_1d = lambda size, dx: fn(size, grid_spacing)
|
|
245
|
+
|
|
246
|
+
return make_1d(size, grid_spacing)
|
|
@@ -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.3.3'
|
|
16
|
+
__version_tuple__ = version_tuple = (0, 3, 3)
|
cryojax/data/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from ._dataset import AbstractDataset as AbstractDataset
|
|
2
|
+
from ._particle_stack import (
|
|
3
|
+
AbstractParticleStack as AbstractParticleStack,
|
|
4
|
+
)
|
|
5
|
+
from ._relion import (
|
|
6
|
+
AbstractRelionDataset as AbstractRelionDataset,
|
|
7
|
+
RelionHelicalDataset as RelionHelicalDataset,
|
|
8
|
+
RelionHelicalMetadata as RelionHelicalMetadata,
|
|
9
|
+
RelionParticleDataset as RelionParticleDataset,
|
|
10
|
+
RelionParticleMetadata as RelionParticleMetadata,
|
|
11
|
+
RelionParticleParameters as RelionParticleParameters,
|
|
12
|
+
RelionParticleStack as RelionParticleStack,
|
|
13
|
+
write_simulated_image_stack_from_starfile as write_simulated_image_stack_from_starfile, # noqa
|
|
14
|
+
write_starfile_with_particle_parameters as write_starfile_with_particle_parameters,
|
|
15
|
+
)
|
cryojax/data/_dataset.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Functionality in `cryojax` for representing datasets."""
|
|
2
|
+
|
|
3
|
+
import abc
|
|
4
|
+
import dataclasses
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclasses.dataclass(frozen=True)
|
|
9
|
+
class AbstractDataset(metaclass=abc.ABCMeta):
|
|
10
|
+
"""An abstraction of a dataset in `cryojax`. To create an
|
|
11
|
+
`AbstractDataset`, implement its `__init__`, `__getitem__`, and
|
|
12
|
+
`__len__` methods.
|
|
13
|
+
|
|
14
|
+
This follows the
|
|
15
|
+
[`torch.utils.data.Dataset`](https://pytorch.org/docs/stable/data.html#torch.utils.data.Dataset)
|
|
16
|
+
API and can easily be wrapped into a pytorch `Dataset` with the
|
|
17
|
+
following pattern:
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
import numpy as np
|
|
21
|
+
from torch.utils.data import Dataset
|
|
22
|
+
|
|
23
|
+
class CustomTorchDataset(Dataset):
|
|
24
|
+
|
|
25
|
+
def __init__(cryojax_dataset: AbstractDataset):
|
|
26
|
+
self.cryojax_dataset = cryojax_dataset
|
|
27
|
+
|
|
28
|
+
def __getitem___(self, index) -> dict[str, Array]:
|
|
29
|
+
particle_stack = self.cryojax_dataset[index]
|
|
30
|
+
return dict(index=index, image_stack=np.asarray(particle_stack.image_stack))
|
|
31
|
+
|
|
32
|
+
def __len__(self) -> int:
|
|
33
|
+
return len(self.cryojax_dataset)
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
JAX also includes packages for dataloaders, such as
|
|
37
|
+
[`jax-dataloaders`](https://github.com/BirkhoffG/jax-dataloader/tree/main) and
|
|
38
|
+
[`grain`](https://github.com/google/grain).
|
|
39
|
+
|
|
40
|
+
!!! question "How do I implement an `AbstractDataset`?"
|
|
41
|
+
|
|
42
|
+
Implementing an `AbstractDataset` is not like implementing
|
|
43
|
+
most other classes in `cryojax`, which are `equinox.Module`s.
|
|
44
|
+
An `equinox.Module` is just a pytree, so it can be safely
|
|
45
|
+
passed to `jax` transformations. However, an `AbstractDataset`
|
|
46
|
+
can *not* be passed to `jax` transformations. Therefore, it is
|
|
47
|
+
not a pytree. Rather, it is a [frozen dataclass](https://docs.python.org/3/library/dataclasses.html#frozen-instances).
|
|
48
|
+
|
|
49
|
+
There are gotchas when implementing frozen dataclasses. For example,
|
|
50
|
+
the following will result in a `FrozenInstanceError`:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
import dataclasses
|
|
54
|
+
|
|
55
|
+
@dataclasses.dataclass(frozen=True)
|
|
56
|
+
class BuggyFrozenDataclass:
|
|
57
|
+
|
|
58
|
+
a: int
|
|
59
|
+
|
|
60
|
+
def __init__(self, a: int):
|
|
61
|
+
self.a = a
|
|
62
|
+
|
|
63
|
+
BuggyFrozenDataclass(10) # Will raise the FrozenInstanceError
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
As of the time of writing this, frozen dataclasses must use the following
|
|
67
|
+
syntax to set attributes in a custom `__init__`:
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
import dataclasses
|
|
71
|
+
|
|
72
|
+
@dataclasses.dataclass(frozen=True)
|
|
73
|
+
class CorrectFrozenDataclass:
|
|
74
|
+
|
|
75
|
+
a: int
|
|
76
|
+
|
|
77
|
+
def __init__(self, a: int):
|
|
78
|
+
object.__setattr__(self, "a", a)
|
|
79
|
+
|
|
80
|
+
example = CorrectFrozenDataclass(10) # Will not raise a FrozenInstanceError
|
|
81
|
+
print(example.a) # This will print a, which here was 10
|
|
82
|
+
```
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
@abc.abstractmethod
|
|
86
|
+
def __init__(self, *args: Any, **kwargs: Any):
|
|
87
|
+
raise NotImplementedError
|
|
88
|
+
|
|
89
|
+
@abc.abstractmethod
|
|
90
|
+
def __getitem__(self, index) -> Any:
|
|
91
|
+
raise NotImplementedError
|
|
92
|
+
|
|
93
|
+
@abc.abstractmethod
|
|
94
|
+
def __len__(self) -> int:
|
|
95
|
+
raise NotImplementedError
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Pytrees that represent particle stacks."""
|
|
2
|
+
|
|
3
|
+
from equinox import AbstractVar, Module
|
|
4
|
+
from jaxtyping import Array, Inexact
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class AbstractParticleStack(Module, strict=True):
|
|
8
|
+
"""An abstraction of a particle stack, represented by a pytree
|
|
9
|
+
that stores an image stack.
|
|
10
|
+
|
|
11
|
+
Subclasses should also include parameters included in the
|
|
12
|
+
image formation model, typically represented with `cryojax` objects.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
image_stack: AbstractVar[Inexact[Array, "... y_dim x_dim"]]
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from ._starfile_reading import (
|
|
2
|
+
AbstractRelionDataset as AbstractRelionDataset,
|
|
3
|
+
RelionHelicalDataset as RelionHelicalDataset,
|
|
4
|
+
RelionHelicalMetadata as RelionHelicalMetadata,
|
|
5
|
+
RelionParticleDataset as RelionParticleDataset,
|
|
6
|
+
RelionParticleMetadata as RelionParticleMetadata,
|
|
7
|
+
RelionParticleParameters as RelionParticleParameters,
|
|
8
|
+
RelionParticleStack as RelionParticleStack,
|
|
9
|
+
)
|
|
10
|
+
from ._starfile_writing import (
|
|
11
|
+
write_simulated_image_stack_from_starfile as write_simulated_image_stack_from_starfile, # noqa: E501
|
|
12
|
+
write_starfile_with_particle_parameters as write_starfile_with_particle_parameters,
|
|
13
|
+
)
|