frmony 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.
- frmony/__init__.py +48 -0
- frmony/__main__.py +8 -0
- frmony/_device.py +31 -0
- frmony/_progress.py +52 -0
- frmony/_transfers.py +231 -0
- frmony/averaging.py +308 -0
- frmony/blocks.py +418 -0
- frmony/cli.py +670 -0
- frmony/engine.py +283 -0
- frmony/geometry.py +260 -0
- frmony/graph.py +309 -0
- frmony/harmonics/__init__.py +38 -0
- frmony/harmonics/legendre.py +208 -0
- frmony/harmonics/shells.py +171 -0
- frmony/harmonics/transform.py +186 -0
- frmony/harmonics/wigner.py +123 -0
- frmony/io/__init__.py +31 -0
- frmony/io/maps.py +50 -0
- frmony/io/registry.py +143 -0
- frmony/io/star.py +259 -0
- frmony/io/volumes.py +143 -0
- frmony/io/wedge.py +179 -0
- frmony/matching/__init__.py +75 -0
- frmony/matching/correlation.py +178 -0
- frmony/matching/frm5d.py +417 -0
- frmony/matching/pairwise.py +716 -0
- frmony/matching/peaks.py +137 -0
- frmony/matching/refine.py +211 -0
- frmony/matching/rotation.py +190 -0
- frmony/matching/translation.py +169 -0
- frmony/particles.py +656 -0
- frmony/pipeline.py +530 -0
- frmony/py.typed +0 -0
- frmony/reconstruction.py +290 -0
- frmony/reference.py +107 -0
- frmony/symmetry.py +484 -0
- frmony/synchronization/__init__.py +32 -0
- frmony/synchronization/power_method.py +236 -0
- frmony/synchronization/rotations.py +470 -0
- frmony/synchronization/translations.py +169 -0
- frmony-0.1.0.dist-info/METADATA +1039 -0
- frmony-0.1.0.dist-info/RECORD +45 -0
- frmony-0.1.0.dist-info/WHEEL +4 -0
- frmony-0.1.0.dist-info/entry_points.txt +2 -0
- frmony-0.1.0.dist-info/licenses/LICENSE +674 -0
frmony/__init__.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Ab-initio subtomogram averaging for cryo-electron tomography.
|
|
2
|
+
|
|
3
|
+
Subtomograms are aligned to each other in pairs, each pair giving a noisy
|
|
4
|
+
relative rotation and shift. Orthogonal group synchronization then finds the
|
|
5
|
+
one set of orientations that agrees best with all of those measurements at
|
|
6
|
+
once, and the shifts follow from a linear least-squares problem. No initial
|
|
7
|
+
reference is needed, so the result does not carry a reference's bias. When
|
|
8
|
+
there is one, `align_to_reference` aligns each particle to it instead.
|
|
9
|
+
|
|
10
|
+
The missing wedge, and the contrast transfer function of a pseudo-subtomogram,
|
|
11
|
+
are carried as a non-negative weight in Fourier space. That weight only ever
|
|
12
|
+
multiplies, so nothing is divided by a value that the microscope left at zero.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from importlib.metadata import version
|
|
18
|
+
|
|
19
|
+
from .averaging import average, fourier_shell_correlation, resolution_at
|
|
20
|
+
from .engine import Search
|
|
21
|
+
from .geometry import euler_to_matrix, matrix_to_euler
|
|
22
|
+
from .graph import build_pairs
|
|
23
|
+
from .particles import Subtomograms, load_reference, load_subtomograms
|
|
24
|
+
from .pipeline import Design, Result, run
|
|
25
|
+
from .reference import align_to_reference
|
|
26
|
+
from .symmetry import detect_symmetry, point_group
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
'Design',
|
|
30
|
+
'Result',
|
|
31
|
+
'Search',
|
|
32
|
+
'Subtomograms',
|
|
33
|
+
'__version__',
|
|
34
|
+
'align_to_reference',
|
|
35
|
+
'average',
|
|
36
|
+
'build_pairs',
|
|
37
|
+
'detect_symmetry',
|
|
38
|
+
'euler_to_matrix',
|
|
39
|
+
'fourier_shell_correlation',
|
|
40
|
+
'load_reference',
|
|
41
|
+
'load_subtomograms',
|
|
42
|
+
'matrix_to_euler',
|
|
43
|
+
'point_group',
|
|
44
|
+
'resolution_at',
|
|
45
|
+
'run',
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
__version__ = version('frmony')
|
frmony/__main__.py
ADDED
frmony/_device.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Choosing where JAX computes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import jax
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def resolve_device(device: str | jax.Device | None = None) -> jax.Device:
|
|
9
|
+
"""Find a device of JAX by name.
|
|
10
|
+
|
|
11
|
+
Args:
|
|
12
|
+
device: ``'cpu'``, ``'gpu'`` or, for a given one, ``'gpu:1'``. The
|
|
13
|
+
default device of JAX when none is named.
|
|
14
|
+
|
|
15
|
+
Raises:
|
|
16
|
+
ValueError: If there is no such device.
|
|
17
|
+
"""
|
|
18
|
+
if device is None:
|
|
19
|
+
return jax.devices()[0]
|
|
20
|
+
if not isinstance(device, str):
|
|
21
|
+
return device
|
|
22
|
+
|
|
23
|
+
kind, _, number = device.lower().partition(':')
|
|
24
|
+
try:
|
|
25
|
+
index = int(number) if number else 0
|
|
26
|
+
backend = {'cuda': 'gpu'}.get(kind, kind)
|
|
27
|
+
return jax.devices(backend)[index]
|
|
28
|
+
except (RuntimeError, IndexError, ValueError) as error:
|
|
29
|
+
raise ValueError(
|
|
30
|
+
f'There is no device {device!r} for JAX to compute on.'
|
|
31
|
+
) from error
|
frmony/_progress.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Progress bars, shown when the log is.
|
|
2
|
+
|
|
3
|
+
The long steps of a run are silent otherwise: reading ten thousand
|
|
4
|
+
particles takes minutes, and a pass of the pairs tens of them, and a run
|
|
5
|
+
that prints nothing in that time looks stuck. A bar goes to standard error
|
|
6
|
+
when the package logs at the level of information, which is what
|
|
7
|
+
``--verbose`` sets, and stays out of the way otherwise, in tests and in
|
|
8
|
+
scripts that did not ask for it.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import logging
|
|
14
|
+
from collections.abc import Iterable
|
|
15
|
+
|
|
16
|
+
from tqdm.auto import tqdm
|
|
17
|
+
|
|
18
|
+
__all__ = ['progress']
|
|
19
|
+
|
|
20
|
+
_LOGGER = logging.getLogger('frmony')
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def progress[T](
|
|
24
|
+
items: Iterable[T],
|
|
25
|
+
description: str,
|
|
26
|
+
total: int | None = None,
|
|
27
|
+
unit: str = 'it',
|
|
28
|
+
scale: int = 1,
|
|
29
|
+
disable: bool = False,
|
|
30
|
+
) -> tqdm[T]:
|
|
31
|
+
"""Wrap an iterable in a bar, shown only if frmony logs information.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
items: What to go through.
|
|
35
|
+
description: What the bar says it is doing.
|
|
36
|
+
total: How many there are, if ``items`` cannot say.
|
|
37
|
+
unit: What one of them is called.
|
|
38
|
+
scale: How many units each item stands for, so that a bar over
|
|
39
|
+
chunks of pairs can count pairs.
|
|
40
|
+
disable: Hide it whatever the log says.
|
|
41
|
+
"""
|
|
42
|
+
bar: tqdm[T] = tqdm(
|
|
43
|
+
items,
|
|
44
|
+
desc=description,
|
|
45
|
+
total=total,
|
|
46
|
+
unit=unit,
|
|
47
|
+
unit_scale=scale if scale != 1 else False,
|
|
48
|
+
disable=disable or not _LOGGER.isEnabledFor(logging.INFO),
|
|
49
|
+
dynamic_ncols=True,
|
|
50
|
+
leave=True,
|
|
51
|
+
)
|
|
52
|
+
return bar
|
frmony/_transfers.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
"""Moving data between the host and the device, on purpose.
|
|
2
|
+
|
|
3
|
+
JAX will copy an array across on its own whenever one is needed on the
|
|
4
|
+
other side. That is convenient and it hides the two things worth watching
|
|
5
|
+
in a run of any size: how much is crossing, and how often.
|
|
6
|
+
|
|
7
|
+
Both of the quiet ways are easy to write by accident. ``jnp.asarray`` on a
|
|
8
|
+
NumPy array copies it to the device. ``np.asarray`` on a device array
|
|
9
|
+
copies it back. Neither looks like a transfer, and a loop that does one per
|
|
10
|
+
particle will sit idle behind the copies while a device waits.
|
|
11
|
+
|
|
12
|
+
So every crossing in this package goes through `to_device` or `to_host`,
|
|
13
|
+
which say what they do, and `no_implicit_transfers` turns anything else
|
|
14
|
+
into an error.
|
|
15
|
+
|
|
16
|
+
One thing to know before reading the counts. A constant that a traced
|
|
17
|
+
function closes over, such as the quarter-turn table or the grid of
|
|
18
|
+
frequencies, is folded into the compiled program and uploaded by the
|
|
19
|
+
runtime rather than by a ``device_put``, so it is reported as an implicit
|
|
20
|
+
copy however it was written. That happens once per compiled function and
|
|
21
|
+
not once per pair, so the number to watch is whether it grows with the
|
|
22
|
+
work, not whether it is zero. It will not be zero.
|
|
23
|
+
|
|
24
|
+
The guard distinguishes the two kinds: an explicit ``device_put`` or
|
|
25
|
+
``device_get`` is allowed, and only the quiet kind raises.
|
|
26
|
+
`tests/test_transfers.py` counts both over a run and over twice the
|
|
27
|
+
particles, so a copy that is made once per particle fails a test rather
|
|
28
|
+
than quietly slowing a run.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import contextlib
|
|
34
|
+
import os
|
|
35
|
+
import re
|
|
36
|
+
import tempfile
|
|
37
|
+
from collections.abc import Generator
|
|
38
|
+
from dataclasses import dataclass
|
|
39
|
+
from typing import Any
|
|
40
|
+
|
|
41
|
+
import jax
|
|
42
|
+
import jax.numpy as jnp
|
|
43
|
+
import numpy as np
|
|
44
|
+
from numpy.typing import DTypeLike, NDArray
|
|
45
|
+
|
|
46
|
+
__all__ = [
|
|
47
|
+
'Transfer',
|
|
48
|
+
'log_implicit_transfers',
|
|
49
|
+
'no_implicit_transfers',
|
|
50
|
+
'on_device',
|
|
51
|
+
'record_transfers',
|
|
52
|
+
'to_device',
|
|
53
|
+
'to_host',
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def on_device(value: Any) -> bool:
|
|
58
|
+
"""Whether a value already lives on a device."""
|
|
59
|
+
return isinstance(value, jax.Array) and not isinstance(value, np.ndarray)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def to_device(
|
|
63
|
+
value: Any,
|
|
64
|
+
dtype: DTypeLike | None = None,
|
|
65
|
+
device: jax.Device | None = None,
|
|
66
|
+
) -> jax.Array:
|
|
67
|
+
"""Put host data on a device, saying so.
|
|
68
|
+
|
|
69
|
+
A value that is already there is left where it is, and only cast if a
|
|
70
|
+
dtype asks for it. Casting on the host first would copy it back and
|
|
71
|
+
forth for nothing.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
value: Anything array-like, on the host or already on a device.
|
|
75
|
+
dtype: What to store it as. Its own type if not given.
|
|
76
|
+
device: Where to put it. The default device if not given.
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
The value, on the device.
|
|
80
|
+
"""
|
|
81
|
+
if on_device(value):
|
|
82
|
+
array: jax.Array = value
|
|
83
|
+
if dtype is not None:
|
|
84
|
+
wanted = jnp.dtype(dtype)
|
|
85
|
+
if array.dtype != wanted:
|
|
86
|
+
array = array.astype(wanted)
|
|
87
|
+
return array if device is None else jax.device_put(array, device)
|
|
88
|
+
# np.asarray keeps this on the host, so the one copy is the device_put.
|
|
89
|
+
host = np.asarray(value, dtype=dtype)
|
|
90
|
+
moved: jax.Array = jax.device_put(host, device)
|
|
91
|
+
return moved
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def to_host(value: Any, dtype: DTypeLike | None = None) -> NDArray[Any]:
|
|
95
|
+
"""Bring device data back to the host, saying so.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
value: A device array, or anything already on the host.
|
|
99
|
+
dtype: What to return it as. Its own type if not given.
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
A NumPy array.
|
|
103
|
+
"""
|
|
104
|
+
fetched = jax.device_get(value) if on_device(value) else value
|
|
105
|
+
return np.asarray(fetched, dtype=dtype)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@contextlib.contextmanager
|
|
109
|
+
def no_implicit_transfers() -> Generator[None]:
|
|
110
|
+
"""Make a quiet copy between host and device an error.
|
|
111
|
+
|
|
112
|
+
Explicit ones, through `to_device` and `to_host`, still work. Only the
|
|
113
|
+
copies nobody asked for raise.
|
|
114
|
+
|
|
115
|
+
Wrap a run in this when a device looks busier than the work should
|
|
116
|
+
make it. The traceback points at the line that copies.
|
|
117
|
+
"""
|
|
118
|
+
with jax.transfer_guard('disallow'):
|
|
119
|
+
yield
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@contextlib.contextmanager
|
|
123
|
+
def log_implicit_transfers() -> Generator[None]:
|
|
124
|
+
"""Report quiet copies instead of refusing them.
|
|
125
|
+
|
|
126
|
+
For finding out how many there are before deciding what to do about
|
|
127
|
+
them.
|
|
128
|
+
"""
|
|
129
|
+
with jax.transfer_guard('log'):
|
|
130
|
+
yield
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@dataclass(frozen=True)
|
|
134
|
+
class Transfer:
|
|
135
|
+
"""One copy between the host and a device."""
|
|
136
|
+
|
|
137
|
+
direction: str
|
|
138
|
+
"""``'host-to-device'`` or ``'device-to-host'``."""
|
|
139
|
+
dtype: str
|
|
140
|
+
"""What was copied."""
|
|
141
|
+
shape: tuple[int, ...]
|
|
142
|
+
"""How much of it. Empty for a scalar."""
|
|
143
|
+
|
|
144
|
+
@property
|
|
145
|
+
def count(self) -> int:
|
|
146
|
+
"""How many values crossed."""
|
|
147
|
+
total = 1
|
|
148
|
+
for extent in self.shape:
|
|
149
|
+
total *= extent
|
|
150
|
+
return total
|
|
151
|
+
|
|
152
|
+
@property
|
|
153
|
+
def nbytes(self) -> int:
|
|
154
|
+
"""Roughly how many bytes crossed."""
|
|
155
|
+
return self.count * int(np.dtype(self.dtype).itemsize)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
_LOGGED = re.compile(
|
|
159
|
+
r'(host-to-device|device-to-host) transfer: '
|
|
160
|
+
r'aval=ShapedArray\(([a-z0-9_]+)\[([^\]]*)\]'
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
@contextlib.contextmanager
|
|
165
|
+
def record_transfers(
|
|
166
|
+
kind: str = 'implicit',
|
|
167
|
+
smallest: int = 64,
|
|
168
|
+
) -> Generator[list[Transfer]]:
|
|
169
|
+
"""Collect the copies of one kind that happen inside the block.
|
|
170
|
+
|
|
171
|
+
JAX separates the two kinds and will report one or the other, never
|
|
172
|
+
both at once, so this does too. They answer different questions.
|
|
173
|
+
``'implicit'`` says whether anything is crossing by accident, and the
|
|
174
|
+
answer for this package should be nothing of any size. ``'explicit'``
|
|
175
|
+
says how much deliberate traffic there is, and the answer should not
|
|
176
|
+
grow with the number of particles.
|
|
177
|
+
|
|
178
|
+
A strict guard is too blunt to assert either, because every Python
|
|
179
|
+
number used in an expression counts as an implicit copy to the device:
|
|
180
|
+
``x * 2`` trips it. Counting, with the scalars filtered out, is what a
|
|
181
|
+
test can actually say something about.
|
|
182
|
+
|
|
183
|
+
JAX reports copies from C++, on the standard error stream rather than
|
|
184
|
+
through logging, so this redirects that stream for the length of the
|
|
185
|
+
block. Anything else written there is swallowed, and it does not nest.
|
|
186
|
+
It is a diagnostic, not something to leave switched on.
|
|
187
|
+
|
|
188
|
+
Args:
|
|
189
|
+
kind: ``'implicit'`` for the copies nobody asked for, or
|
|
190
|
+
``'explicit'`` for the ones through `to_device` and `to_host`.
|
|
191
|
+
smallest: Ignore copies of fewer values than this, which is what
|
|
192
|
+
keeps the scalars out.
|
|
193
|
+
|
|
194
|
+
Yields:
|
|
195
|
+
A list, filled in once the block ends.
|
|
196
|
+
|
|
197
|
+
Raises:
|
|
198
|
+
ValueError: If the kind is neither of the two.
|
|
199
|
+
"""
|
|
200
|
+
modes = {'implicit': 'log', 'explicit': 'log_explicit'}
|
|
201
|
+
if kind not in modes:
|
|
202
|
+
raise ValueError(
|
|
203
|
+
f"A kind of copy is 'implicit' or 'explicit', not {kind!r}."
|
|
204
|
+
)
|
|
205
|
+
found: list[Transfer] = []
|
|
206
|
+
with tempfile.TemporaryFile(mode='w+') as sink:
|
|
207
|
+
saved = os.dup(2)
|
|
208
|
+
os.dup2(sink.fileno(), 2)
|
|
209
|
+
try:
|
|
210
|
+
with jax.transfer_guard(modes[kind]):
|
|
211
|
+
yield found
|
|
212
|
+
finally:
|
|
213
|
+
os.dup2(saved, 2)
|
|
214
|
+
os.close(saved)
|
|
215
|
+
sink.seek(0)
|
|
216
|
+
for line in sink:
|
|
217
|
+
found_line = _LOGGED.search(line)
|
|
218
|
+
if found_line is None:
|
|
219
|
+
continue
|
|
220
|
+
shape = tuple(
|
|
221
|
+
int(extent)
|
|
222
|
+
for extent in found_line.group(3).split(',')
|
|
223
|
+
if extent.strip()
|
|
224
|
+
)
|
|
225
|
+
crossing = Transfer(
|
|
226
|
+
direction=found_line.group(1),
|
|
227
|
+
dtype=found_line.group(2),
|
|
228
|
+
shape=shape,
|
|
229
|
+
)
|
|
230
|
+
if crossing.count >= smallest:
|
|
231
|
+
found.append(crossing)
|
frmony/averaging.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
"""Putting the aligned subtomograms back together.
|
|
2
|
+
|
|
3
|
+
Once every particle has an orientation and a centre, the structure is the
|
|
4
|
+
average of them -- but not the average of the volumes. Each particle
|
|
5
|
+
measured a different part of Fourier space, and turning it turns its
|
|
6
|
+
missing wedge with it, so a plain mean in real space adds the gaps together
|
|
7
|
+
instead of filling them.
|
|
8
|
+
|
|
9
|
+
What fills them is a weighted average in Fourier space:
|
|
10
|
+
|
|
11
|
+
S(k) = sum_i Lambda_i[D_i](k) / (sum_i Lambda_i[W_i](k) + epsilon),
|
|
12
|
+
|
|
13
|
+
where each particle contributes what it measured, weighted by how well it
|
|
14
|
+
measured it. A frequency one particle never saw is supplied by the others,
|
|
15
|
+
because they were pointing elsewhere. Where no particle saw a frequency at
|
|
16
|
+
all, the numerator and the denominator are both nothing and the
|
|
17
|
+
regularizer leaves it empty, which is the honest answer.
|
|
18
|
+
|
|
19
|
+
The resolution is reported by Fourier shell correlation between two halves
|
|
20
|
+
of the data, each averaged on its own, which is the usual gold standard.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import jax
|
|
26
|
+
import jax.numpy as jnp
|
|
27
|
+
import numpy as np
|
|
28
|
+
from jax.typing import ArrayLike
|
|
29
|
+
from numpy.typing import NDArray
|
|
30
|
+
|
|
31
|
+
from ._transfers import to_device
|
|
32
|
+
from .matching.translation import frequency_grid, rotate_spectrum
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
'accumulate',
|
|
36
|
+
'average',
|
|
37
|
+
'average_sums',
|
|
38
|
+
'contribution',
|
|
39
|
+
'empty_sums',
|
|
40
|
+
'fourier_shell_correlation',
|
|
41
|
+
'ratio',
|
|
42
|
+
'resolution_at',
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _phase_ramp(size: int, shift: ArrayLike) -> jax.Array:
|
|
47
|
+
"""``exp(-2 pi i k . a)``, which moves a volume by ``a``.
|
|
48
|
+
|
|
49
|
+
The shift is ``(x, y, z)`` while the volume is indexed ``[z, y, x]``.
|
|
50
|
+
"""
|
|
51
|
+
axis = (jnp.arange(size) - size // 2) / size
|
|
52
|
+
offset = jnp.asarray(shift)
|
|
53
|
+
phase = (
|
|
54
|
+
axis[:, None, None] * offset[2]
|
|
55
|
+
+ axis[None, :, None] * offset[1]
|
|
56
|
+
+ axis[None, None, :] * offset[0]
|
|
57
|
+
)
|
|
58
|
+
return jnp.exp(-2j * jnp.pi * phase)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def contribution(
|
|
62
|
+
spectrum: jax.Array,
|
|
63
|
+
weight: jax.Array,
|
|
64
|
+
rotation: jax.Array,
|
|
65
|
+
shift: jax.Array,
|
|
66
|
+
grid: jax.Array,
|
|
67
|
+
) -> tuple[jax.Array, jax.Array]:
|
|
68
|
+
"""One particle's share of the two sums of an average.
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
spectrum: Its centred spectrum ``(n, n, n)``.
|
|
72
|
+
weight: Its Fourier weight, the same shape.
|
|
73
|
+
rotation: Its orientation ``(3, 3)``.
|
|
74
|
+
shift: Its centre ``(3,)`` in voxels, ordered ``(x, y, z)``.
|
|
75
|
+
grid: `frmony.matching.translation.frequency_grid` of ``n``.
|
|
76
|
+
"""
|
|
77
|
+
size = spectrum.shape[-1]
|
|
78
|
+
# Undo the particle's own shift, then bring it into the common
|
|
79
|
+
# frame. Turning by the inverse is what takes a particle onto the
|
|
80
|
+
# structure rather than the other way about.
|
|
81
|
+
centred = spectrum * _phase_ramp(size, -shift)
|
|
82
|
+
turned = rotate_spectrum(centred, rotation.T, grid)
|
|
83
|
+
turned_weight = rotate_spectrum(weight, rotation.T, grid)
|
|
84
|
+
covered = jnp.maximum(turned_weight, 0.0)
|
|
85
|
+
return turned * covered, covered * covered
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def average_sums(
|
|
89
|
+
data: ArrayLike,
|
|
90
|
+
weight: ArrayLike,
|
|
91
|
+
rotations: ArrayLike,
|
|
92
|
+
shifts: ArrayLike,
|
|
93
|
+
) -> tuple[jax.Array, jax.Array]:
|
|
94
|
+
"""The two sums an average is the ratio of.
|
|
95
|
+
|
|
96
|
+
Kept apart from the division so that particles can be averaged a
|
|
97
|
+
chunk at a time: the sums of two chunks are the sums of both, and the
|
|
98
|
+
ratio is taken once, at the end.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
data: Centred spectra ``(particles, n, n, n)``.
|
|
102
|
+
weight: Their Fourier weights, the same shape.
|
|
103
|
+
rotations: The orientation of each particle ``(particles, 3, 3)``.
|
|
104
|
+
shifts: Its centre ``(particles, 3)``, in voxels of the spectra
|
|
105
|
+
and ordered ``(x, y, z)``.
|
|
106
|
+
|
|
107
|
+
Returns:
|
|
108
|
+
``sum Lambda[W D]`` and ``sum Lambda[W**2]``, each ``(n, n, n)``.
|
|
109
|
+
"""
|
|
110
|
+
data = to_device(data)
|
|
111
|
+
weight = to_device(weight)
|
|
112
|
+
rotations = to_device(rotations)
|
|
113
|
+
shifts = to_device(shifts)
|
|
114
|
+
size = data.shape[-1]
|
|
115
|
+
grid = to_device(frequency_grid(size))
|
|
116
|
+
|
|
117
|
+
def one(inputs: tuple[jax.Array, ...]) -> tuple[jax.Array, jax.Array]:
|
|
118
|
+
spectrum, mask, rotation, shift = inputs
|
|
119
|
+
return contribution(spectrum, mask, rotation, shift, grid)
|
|
120
|
+
|
|
121
|
+
def accumulate(
|
|
122
|
+
carry: tuple[jax.Array, jax.Array], inputs: tuple[jax.Array, ...]
|
|
123
|
+
) -> tuple[tuple[jax.Array, jax.Array], None]:
|
|
124
|
+
top, bottom = carry
|
|
125
|
+
share, support = one(inputs)
|
|
126
|
+
return (top + share, bottom + support), None
|
|
127
|
+
|
|
128
|
+
start = (
|
|
129
|
+
jnp.zeros(data.shape[1:], dtype=jnp.complex64),
|
|
130
|
+
jnp.zeros(data.shape[1:], dtype=jnp.float32),
|
|
131
|
+
)
|
|
132
|
+
(top, bottom), _ = jax.lax.scan(
|
|
133
|
+
accumulate, start, (data, weight, rotations, shifts)
|
|
134
|
+
)
|
|
135
|
+
return top, bottom
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@jax.jit
|
|
139
|
+
def accumulate(
|
|
140
|
+
sums: tuple[jax.Array, jax.Array],
|
|
141
|
+
data: jax.Array,
|
|
142
|
+
weight: jax.Array,
|
|
143
|
+
rotations: jax.Array,
|
|
144
|
+
shifts: jax.Array,
|
|
145
|
+
halves: jax.Array,
|
|
146
|
+
grid: jax.Array,
|
|
147
|
+
) -> tuple[jax.Array, jax.Array]:
|
|
148
|
+
"""Add a block of particles to the sums of two half averages.
|
|
149
|
+
|
|
150
|
+
The sums are ``(2, n, n, n)``, one for each half. ``halves`` says
|
|
151
|
+
which half each particle goes to, and a particle whose half is
|
|
152
|
+
neither nought nor one -- padding, which keeps every block the same
|
|
153
|
+
shape and so compiles this once -- goes to neither. The average of all
|
|
154
|
+
of them is the ratio of the two halves' sums added.
|
|
155
|
+
|
|
156
|
+
Args:
|
|
157
|
+
sums: What the blocks before added up to.
|
|
158
|
+
data: Centred spectra ``(particles, n, n, n)``.
|
|
159
|
+
weight: Their weights, the same shape.
|
|
160
|
+
rotations: Orientations ``(particles, 3, 3)``.
|
|
161
|
+
shifts: Centres ``(particles, 3)``, in voxels of the spectra.
|
|
162
|
+
halves: ``(particles,)``, nought, one, or anything else for none.
|
|
163
|
+
grid: `frmony.matching.translation.frequency_grid` of ``n``, on
|
|
164
|
+
the device. An argument and not built here, where it would be
|
|
165
|
+
folded into the program and uploaded under no name.
|
|
166
|
+
"""
|
|
167
|
+
|
|
168
|
+
def one(
|
|
169
|
+
carry: tuple[jax.Array, jax.Array], inputs: tuple[jax.Array, ...]
|
|
170
|
+
) -> tuple[tuple[jax.Array, jax.Array], None]:
|
|
171
|
+
spectrum, mask, rotation, shift, half = inputs
|
|
172
|
+
share, support = contribution(spectrum, mask, rotation, shift, grid)
|
|
173
|
+
top, bottom = carry
|
|
174
|
+
select = (jnp.arange(2) == half)[:, None, None, None]
|
|
175
|
+
return (top + select * share, bottom + select * support), None
|
|
176
|
+
|
|
177
|
+
result, _ = jax.lax.scan(
|
|
178
|
+
one, sums, (data, weight, rotations, shifts, halves)
|
|
179
|
+
)
|
|
180
|
+
return result
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def empty_sums(size: int) -> tuple[jax.Array, jax.Array]:
|
|
184
|
+
"""Sums of two half averages with nothing added yet."""
|
|
185
|
+
return (
|
|
186
|
+
jnp.zeros((2, size, size, size), dtype=jnp.complex64),
|
|
187
|
+
jnp.zeros((2, size, size, size), dtype=jnp.float32),
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def ratio(
|
|
192
|
+
top: ArrayLike, bottom: ArrayLike, epsilon: float = 1e-3
|
|
193
|
+
) -> jax.Array:
|
|
194
|
+
"""The average from its sums; see `average`."""
|
|
195
|
+
top = to_device(top)
|
|
196
|
+
bottom = to_device(bottom)
|
|
197
|
+
floor = epsilon * jnp.maximum(jnp.max(bottom), 1e-20)
|
|
198
|
+
divided: jax.Array = top / (bottom + floor)
|
|
199
|
+
return divided
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def average(
|
|
203
|
+
data: ArrayLike,
|
|
204
|
+
weight: ArrayLike,
|
|
205
|
+
rotations: ArrayLike,
|
|
206
|
+
shifts: ArrayLike,
|
|
207
|
+
epsilon: float = 1e-3,
|
|
208
|
+
) -> tuple[jax.Array, jax.Array]:
|
|
209
|
+
"""The structure the aligned particles agree on.
|
|
210
|
+
|
|
211
|
+
Args:
|
|
212
|
+
data: Centred spectra ``(particles, n, n, n)``.
|
|
213
|
+
weight: Their Fourier weights, the same shape.
|
|
214
|
+
rotations: The orientation of each particle ``(particles, 3, 3)``.
|
|
215
|
+
shifts: Its centre ``(particles, 3)``, in voxels of the spectra
|
|
216
|
+
and ordered ``(x, y, z)``.
|
|
217
|
+
epsilon: Added to the denominator, as a fraction of its largest
|
|
218
|
+
value, so that frequencies nobody measured stay empty instead
|
|
219
|
+
of being amplified out of nothing.
|
|
220
|
+
|
|
221
|
+
Returns:
|
|
222
|
+
The structure's centred spectrum and the total weight behind each
|
|
223
|
+
of its frequencies. The second is worth keeping: it says which
|
|
224
|
+
parts of the answer are supported and which are guesses.
|
|
225
|
+
"""
|
|
226
|
+
top, bottom = average_sums(data, weight, rotations, shifts)
|
|
227
|
+
return ratio(top, bottom, epsilon), bottom
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def fourier_shell_correlation(
|
|
231
|
+
first: ArrayLike, second: ArrayLike, shells: int | None = None
|
|
232
|
+
) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
|
|
233
|
+
"""How far two structures agree, frequency by frequency.
|
|
234
|
+
|
|
235
|
+
Args:
|
|
236
|
+
first: A centred spectrum ``(n, n, n)``.
|
|
237
|
+
second: Another of the same shape.
|
|
238
|
+
shells: How many shells to report. Half the box by default.
|
|
239
|
+
|
|
240
|
+
Returns:
|
|
241
|
+
The frequency of each shell, as a fraction of the sampling rate,
|
|
242
|
+
and the correlation there.
|
|
243
|
+
"""
|
|
244
|
+
left = np.asarray(first)
|
|
245
|
+
right = np.asarray(second)
|
|
246
|
+
if left.shape != right.shape:
|
|
247
|
+
raise ValueError('Two structures to compare have the same shape.')
|
|
248
|
+
size = left.shape[-1]
|
|
249
|
+
count = shells if shells is not None else size // 2
|
|
250
|
+
|
|
251
|
+
axis = np.arange(size) - size // 2
|
|
252
|
+
radius = np.sqrt(
|
|
253
|
+
axis[:, None, None] ** 2
|
|
254
|
+
+ axis[None, :, None] ** 2
|
|
255
|
+
+ axis[None, None, :] ** 2
|
|
256
|
+
)
|
|
257
|
+
index = np.clip(
|
|
258
|
+
np.floor(radius * count / (size / 2)).astype(np.int64), 0, count
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
def total(values: NDArray[np.floating]) -> NDArray[np.float64]:
|
|
262
|
+
summed: NDArray[np.float64] = np.bincount(
|
|
263
|
+
index.ravel(), weights=values.ravel(), minlength=count + 1
|
|
264
|
+
)[:count].astype(np.float64)
|
|
265
|
+
return summed
|
|
266
|
+
|
|
267
|
+
cross = total((left * np.conjugate(right)).real)
|
|
268
|
+
power = np.sqrt(total(np.abs(left) ** 2) * total(np.abs(right) ** 2))
|
|
269
|
+
# A shell with nothing in it has no correlation, which is not the
|
|
270
|
+
# same as a correlation of zero. The innermost shell is always such a
|
|
271
|
+
# one here, since the zero frequency is cleared on loading, and
|
|
272
|
+
# calling it zero made every resolution come out infinite.
|
|
273
|
+
correlation = np.where(
|
|
274
|
+
power > 0.0, cross.real / np.maximum(power, 1e-30), np.nan
|
|
275
|
+
)
|
|
276
|
+
frequency = (np.arange(count) + 0.5) / (2.0 * count)
|
|
277
|
+
return frequency, correlation
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def resolution_at(
|
|
281
|
+
frequency: NDArray[np.float64],
|
|
282
|
+
correlation: NDArray[np.float64],
|
|
283
|
+
pixel_size: float,
|
|
284
|
+
threshold: float = 0.143,
|
|
285
|
+
) -> float:
|
|
286
|
+
"""Where a shell correlation first falls below a threshold [A].
|
|
287
|
+
|
|
288
|
+
Returns infinity if it never does, which means the data ran out before
|
|
289
|
+
the agreement did. Shells with no correlation to speak of, which are
|
|
290
|
+
not a number, are passed over.
|
|
291
|
+
"""
|
|
292
|
+
defined = np.isfinite(correlation)
|
|
293
|
+
frequency = frequency[defined]
|
|
294
|
+
correlation = correlation[defined]
|
|
295
|
+
below = np.flatnonzero(correlation < threshold)
|
|
296
|
+
if len(below) == 0:
|
|
297
|
+
return float('inf')
|
|
298
|
+
first = int(below[0])
|
|
299
|
+
if first == 0:
|
|
300
|
+
return float('inf')
|
|
301
|
+
# Straight line between the two shells that straddle the threshold.
|
|
302
|
+
before, after = correlation[first - 1], correlation[first]
|
|
303
|
+
span = before - after
|
|
304
|
+
fraction = (before - threshold) / span if span > 0 else 0.0
|
|
305
|
+
crossing = frequency[first - 1] + fraction * (
|
|
306
|
+
frequency[first] - frequency[first - 1]
|
|
307
|
+
)
|
|
308
|
+
return float(pixel_size / crossing) if crossing > 0 else float('inf')
|