Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@
the kernel's echo-by-echo recursion in forward mode, at the cost of one more
state vector per direction, and the shooting that pins a Busse train's three
angles takes its Newton Jacobian from them.
- **A largest refocusing angle for prescribed trains.** `prescribed_flips`
takes `maximum_flip`, one per train: every solved pulse is the angle in
`[0, maximum_flip]` whose echo comes nearest the prescription, so a train
whose prescription asks for more than the bound holds at it. A pulse held at
the bound has zero derivative.
- **Coarse-to-fine dictionary search.** `DictionaryMatcher(coarse=k)` places
the atoms on the lattice their parameters were simulated on, scores every
k-th value along each parameter, then the `2k + 1` values around the winner
Expand Down
48 changes: 29 additions & 19 deletions src/blochsim/_trains_cpu.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ struct States {

// How a solved angle moves with what it was solved from.
enum class Reached {
// An end of [0, pi]: it stays there under a small change.
// An end of [0, maximum]: it stays there under a small change.
END,
// The angle whose echo comes nearest an unreachable target: it follows
// the extremum of the echo, delta or delta + pi.
Expand All @@ -144,8 +144,8 @@ struct Solved {
Reached reached;
};

// The flip angle in [0, pi] whose echo is ``target``, from the first-order
// states the pulse is about to turn.
// The flip angle in [0, maximum] whose echo is ``target``, from the
// first-order states the pulse is about to turn; ``maximum`` is at most pi.
//
// The echo is the zeroth F- the pulse leaves, a + b cos(alpha) + c sin(alpha)
// = a + r cos(alpha - delta), scaled by the transverse relaxation ``e2`` of
Expand All @@ -156,7 +156,7 @@ struct Solved {
// distance from the target plus a term that orders equal scores by angle.
inline Solved refocusing_angle(
const double plus, const double minus, const double longitudinal,
const double target, const double e2
const double target, const double e2, const double maximum
) {
// A prescription that is not a number has no angle, and neither has
// any echo after it: the states it leaves are not numbers either.
Expand All @@ -174,17 +174,20 @@ inline Solved refocusing_angle(
const double met = a + radius * reach;
const bool within = wanted > -1.0 && wanted < 1.0;
const double angles[8] = {
0.0, PI, delta, delta + PI, delta - turn, delta + turn,
0.0, maximum, delta, delta + PI, delta - turn, delta + turn,
delta - turn + 2.0 * PI, delta + turn + 2.0 * PI,
};
const double at_maximum = maximum == PI
? a - b
: a + b * std::cos(maximum) + c * std::sin(maximum);
const double echoes[8] = {
a + b, a - b, a + radius, a - radius, met, met, met, met,
a + b, at_maximum, a + radius, a - radius, met, met, met, met,
};
Solved best{NAN, Reached::END};
double best_score = INFINITY;
for (int candidate = 0; candidate < 8; ++candidate) {
const double angle = angles[candidate];
if (!(angle >= 0.0 && angle <= PI)) {
if (!(angle >= 0.0 && angle <= maximum)) {
continue;
}
const double score =
Expand Down Expand Up @@ -237,6 +240,8 @@ struct Inverse {
// The first pulse's flip angle per train, or null for it to be solved
// like the others.
const double* first_flip;
// The largest angle a solved pulse may take, per train, or null for pi.
const double* maximum;
double* flip;
double* achieved;
};
Expand Down Expand Up @@ -272,7 +277,8 @@ void inverse_range(
? problem.first_flip[train]
: refocusing_angle(
along.plus[1], along.minus[1], along.longitudinal[1],
problem.target[row + echo], e2
problem.target[row + echo], e2,
problem.maximum == nullptr ? PI : problem.maximum[train]
).angle;
along.rotate(angle);
if (relaxing) {
Expand Down Expand Up @@ -402,6 +408,7 @@ struct InverseTangents {
Tangents along;
const double* target;
const double* first_flip;
const double* maximum;
const double* d_target;
// ``(trains, directions)``, or null when the first angle is solved too.
const double* d_first_flip;
Expand Down Expand Up @@ -437,7 +444,8 @@ void inverse_tangents_range(
? Solved{problem.first_flip[train], Reached::END}
: refocusing_angle(
along.plus[1], along.minus[1], along.longitudinal[1],
problem.target[row + echo], e2
problem.target[row + echo], e2,
problem.maximum == nullptr ? PI : problem.maximum[train]
);
for (std::int64_t direction = 0; direction < directions; ++direction) {
States& slope = slopes[direction];
Expand Down Expand Up @@ -614,13 +622,14 @@ PyObject* inverse(PyObject*, PyObject* arguments) {
return nullptr;
}
std::vector<void*> raw;
if (!unpack(pointers, 5, raw) || !describe(batch, count, echoes, raw[0])) {
if (!unpack(pointers, 6, raw) || !describe(batch, count, echoes, raw[0])) {
return nullptr;
}
problem.target = static_cast<const double*>(raw[1]);
problem.first_flip = static_cast<const double*>(raw[2]);
problem.flip = static_cast<double*>(raw[3]);
problem.achieved = static_cast<double*>(raw[4]);
problem.maximum = static_cast<const double*>(raw[3]);
problem.flip = static_cast<double*>(raw[4]);
problem.achieved = static_cast<double*>(raw[5]);
Py_BEGIN_ALLOW_THREADS
run(problem, threads, inverse_range);
Py_END_ALLOW_THREADS
Expand Down Expand Up @@ -671,18 +680,19 @@ PyObject* inverse_tangents(PyObject*, PyObject* arguments) {
return nullptr;
}
std::vector<void*> raw;
if (!unpack(pointers, 9, raw) || !describe(batch, count, echoes, raw[0])) {
if (!unpack(pointers, 10, raw) || !describe(batch, count, echoes, raw[0])) {
return nullptr;
}
problem.along.directions = directions;
problem.target = static_cast<const double*>(raw[1]);
problem.first_flip = static_cast<const double*>(raw[2]);
problem.d_target = static_cast<const double*>(raw[3]);
problem.d_first_flip = static_cast<const double*>(raw[4]);
problem.flip = static_cast<double*>(raw[5]);
problem.achieved = static_cast<double*>(raw[6]);
problem.d_flip = static_cast<double*>(raw[7]);
problem.d_achieved = static_cast<double*>(raw[8]);
problem.maximum = static_cast<const double*>(raw[3]);
problem.d_target = static_cast<const double*>(raw[4]);
problem.d_first_flip = static_cast<const double*>(raw[5]);
problem.flip = static_cast<double*>(raw[6]);
problem.achieved = static_cast<double*>(raw[7]);
problem.d_flip = static_cast<double*>(raw[8]);
problem.d_achieved = static_cast<double*>(raw[9]);
Py_BEGIN_ALLOW_THREADS
run(problem, threads, inverse_tangents_range);
Py_END_ALLOW_THREADS
Expand Down
35 changes: 30 additions & 5 deletions src/blochsim/trains/_prescribed.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,20 +70,27 @@ def inverse_rows(
first_rad: np.ndarray | None,
relax: tuple[float, float, float, float],
threads: int = AUTO_THREADS,
maximum_rad: np.ndarray | None = None,
) -> tuple[np.ndarray, np.ndarray]:
"""Flip angles (rad) and achieved echoes of ``(trains, echoes)`` targets."""
"""Flip angles (rad) and achieved echoes of ``(trains, echoes)`` targets.

``maximum_rad``, one per train, bounds every solved angle; none is pi.
"""
target = np.ascontiguousarray(target, dtype=np.float64)
lengths = np.ascontiguousarray(lengths, dtype=np.int64)
count, echoes = target.shape
flip = np.empty_like(target)
achieved = np.empty_like(target)
if first_rad is not None:
first_rad = np.ascontiguousarray(first_rad, dtype=np.float64)
if maximum_rad is not None:
maximum_rad = np.ascontiguousarray(maximum_rad, dtype=np.float64)
inverse(
(
lengths.ctypes.data,
target.ctypes.data,
0 if first_rad is None else first_rad.ctypes.data,
0 if maximum_rad is None else maximum_rad.ctypes.data,
flip.ctypes.data,
achieved.ctypes.data,
),
Expand All @@ -103,6 +110,7 @@ def inverse_rows_tangents(
d_first_rad: np.ndarray | None,
relax: tuple[float, float, float, float],
threads: int = AUTO_THREADS,
maximum_rad: np.ndarray | None = None,
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""What :func:`inverse_rows` returns, and its derivatives along directions.

Expand All @@ -127,11 +135,14 @@ def inverse_rows_tangents(
d_first_rad = np.ascontiguousarray(d_first_rad, dtype=np.float64)
if d_first_rad.shape != (count, directions):
raise ValueError("first-angle tangents must be (trains, directions)")
if maximum_rad is not None:
maximum_rad = np.ascontiguousarray(maximum_rad, dtype=np.float64)
inverse_tangents(
(
lengths.ctypes.data,
target.ctypes.data,
0 if first_rad is None else first_rad.ctypes.data,
0 if maximum_rad is None else maximum_rad.ctypes.data,
d_target.ctypes.data,
0 if d_first_rad is None else d_first_rad.ctypes.data,
flip.ctypes.data,
Expand Down Expand Up @@ -234,15 +245,17 @@ def prescribed_flips(
threads: int = AUTO_THREADS,
signal_tangents: npt.ArrayLike | None = None,
first_flip_tangents: npt.ArrayLike | None = None,
maximum_flip: npt.ArrayLike | None = None,
) -> tuple[np.ndarray, ...]:
"""Refocusing flip angles whose echoes take prescribed amplitudes.

The train is the CPMG arrangement: an ideal 90 degree excitation a quarter
turn from the refocusing pulses, each pulse midway between two echoes. The
extended phase graph is inverted one echo at a time: the states before a
pulse fix the echo after it as a function of its flip angle alone, and the
smallest angle in [0, 180] degrees giving the prescribed amplitude is
taken. An amplitude no angle reaches gets the angle that comes nearest,
smallest angle in [0, 180] degrees, or in [0, ``maximum_flip``], giving
the prescribed amplitude is taken. An amplitude no angle reaches gets the
angle that comes nearest,
so the returned echoes are the test of a prescription: they equal it
exactly where it can be met.

Expand Down Expand Up @@ -275,6 +288,11 @@ def prescribed_flips(
first_flip_tangents : array-like, default=None
The change of ``first_flip`` along each direction, in degrees, shape
``(directions, ...)``; none by default. Needs ``signal_tangents``.
maximum_flip : float or array-like, default=None
Largest flip angle a solved pulse may take, in degrees, in (0, 180],
one per train; 180 by default. A pulse held at it does not move with
the prescription, so its derivative is zero. ``first_flip`` is not
bounded by it.

Returns
-------
Expand Down Expand Up @@ -330,10 +348,17 @@ def prescribed_flips(
if not np.all(np.isfinite(first)):
raise ValueError("first_flip must be finite")
played = _lengths(lengths, shape, echoes)
maximum = None
if maximum_flip is not None:
maximum = np.deg2rad(
np.broadcast_to(np.asarray(maximum_flip, dtype=float), shape).reshape(count)
)
if not np.all((maximum > 0) & (maximum <= np.pi)):
raise ValueError("maximum_flip must lie in (0, 180] degrees")
if signal_tangents is None:
if first_flip_tangents is not None:
raise ValueError("first_flip_tangents needs signal_tangents")
flip, achieved = inverse_rows(target, played, first, relax, threads)
flip, achieved = inverse_rows(target, played, first, relax, threads, maximum)
return (
np.rad2deg(flip).reshape(*shape, echoes),
achieved.reshape(*shape, echoes),
Expand All @@ -357,7 +382,7 @@ def prescribed_flips(
):
raise ValueError("tangents must be finite")
flip, achieved, d_flip, d_achieved = inverse_rows_tangents(
target, d_target, played, first, d_first, relax, threads
target, d_target, played, first, d_first, relax, threads, maximum
)

def back(values: np.ndarray) -> np.ndarray:
Expand Down
85 changes: 85 additions & 0 deletions tests/trains/test_prescribed_flips.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,9 @@ def test_trains_of_a_batch_are_solved_as_they_are_alone():
{"ESP": 4.0, "first_ESP": np.inf},
{"lengths": 0},
{"lengths": 9},
{"maximum_flip": 0.0},
{"maximum_flip": 181.0},
{"maximum_flip": np.nan},
],
)
def test_an_invalid_prescription_is_refused(arguments):
Expand Down Expand Up @@ -185,3 +188,85 @@ def test_an_echo_out_of_reach_has_an_angle_that_ignores_its_target():
def test_tangents_not_shaped_as_the_signal_are_refused(arguments):
with pytest.raises(ValueError):
prescribed_flips(np.full(4, 0.5), **arguments)


def test_a_maximum_of_180_degrees_is_no_bound():
target = np.stack([np.linspace(0.9, 0.2, 40), np.full(40, 0.95)])
timing = {"ESP": 4.0, "T1": 900.0, "T2": 70.0, "first_flip": 150.0}
np.testing.assert_array_equal(
prescribed_flips(target, maximum_flip=180.0, **timing),
prescribed_flips(target, **timing),
)


def test_a_bounded_train_holds_at_its_maximum_and_echoes_what_it_plays():
# Unit echoes ask for 180 degree pulses; a bound of 150 degrees plays
# 150 degree pulses instead, and their echoes are what those give.
flip, achieved = prescribed_flips(np.ones(12), maximum_flip=150.0)
np.testing.assert_allclose(flip, 150.0, rtol=0, atol=1e-12)
np.testing.assert_allclose(achieved, cpmg_echoes(flip).real, atol=1e-6)


def test_each_train_of_a_batch_keeps_its_own_maximum():
target = np.full((2, 20), 0.97)
flip, _ = prescribed_flips(target, maximum_flip=[140.0, 160.0])
assert flip[0].max() <= 140.0 + 1e-12
assert flip[1].max() <= 160.0 + 1e-12
alone = prescribed_flips(target[1], maximum_flip=160.0)[0]
np.testing.assert_array_equal(flip[1], alone)


def test_a_bounded_angle_comes_nearest_its_target_within_the_bound():
# Within [0, maximum] the echo of the chosen angle is the nearest any
# angle gives after the same pulses, searched on a fine grid.
from blochsim.trains._prescribed import forward_rows

target = np.concatenate([[0.5], np.full(9, 0.99)])
flip, achieved = prescribed_flips(target, maximum_flip=130.0)
grid = np.linspace(0.0, 130.0, 2601)
free = (1.0, 1.0, 1.0, 1.0)
for echo in range(1, 10):
trials = np.column_stack([np.tile(flip[:echo], (len(grid), 1)), grid])
played = np.full(len(grid), echo + 1)
echoes = forward_rows(np.deg2rad(trials), played, free)[:, -1]
assert abs(achieved[echo] - target[echo]) <= (
abs(echoes - target[echo]).min() + 1e-9
)


@pytest.mark.parametrize(
"timing", [{}, {"ESP": 4.0, "first_ESP": 5.0, "T1": 900.0, "T2": 70.0}]
)
def test_bounded_flip_tangents_are_the_derivative_of_the_inversion(timing):
rng = np.random.default_rng(5)
target = np.stack([np.linspace(0.995, 0.35, 48), np.full(48, 0.6)])
first = np.array([110.0, 130.0])
maximum = np.array([140.0, 150.0])
signal_tangents = 0.01 * rng.standard_normal((3, *target.shape))
first_tangents = rng.standard_normal((3, 2))
flip, achieved, d_flip, d_achieved = prescribed_flips(
target,
first_flip=first,
maximum_flip=maximum,
signal_tangents=signal_tangents,
first_flip_tangents=first_tangents,
**timing,
)
held = np.isclose(flip[:, 1:], maximum[:, None], rtol=0, atol=1e-9)
assert held.any() and not held.all()
for direction in range(3):
moved = [
prescribed_flips(
target + sign * 1e-6 * signal_tangents[direction],
first_flip=first + sign * 1e-6 * first_tangents[direction],
maximum_flip=maximum,
**timing,
)
for sign in (1, -1)
]
np.testing.assert_allclose(
d_flip[direction], (moved[0][0] - moved[1][0]) / 2e-6, atol=1e-6
)
np.testing.assert_allclose(
d_achieved[direction], (moved[0][1] - moved[1][1]) / 2e-6, atol=1e-8
)
Loading