spynach 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. ctps/__init__.py +37 -0
  2. ctps/engine/__init__.py +1 -0
  3. ctps/engine/gradient.py +81 -0
  4. ctps/engine/paths.py +122 -0
  5. ctps/engine/phase.py +37 -0
  6. ctps/engine/pulse.py +176 -0
  7. ctps/engine/rank.py +23 -0
  8. ctps/io.py +86 -0
  9. ctps/model.py +617 -0
  10. ctps/optimize.py +495 -0
  11. ctps/plot.py +479 -0
  12. ctps/simulate.py +112 -0
  13. spynach/__init__.py +65 -0
  14. spynach/_isotope_data.py +304 -0
  15. spynach/assume.py +72 -0
  16. spynach/backend.py +133 -0
  17. spynach/basis.py +408 -0
  18. spynach/contexts.py +336 -0
  19. spynach/conventions.py +147 -0
  20. spynach/filters.py +174 -0
  21. spynach/grids/icos_2ang_10242pts.npz +0 -0
  22. spynach/grids/icos_2ang_12pts.npz +0 -0
  23. spynach/grids/icos_2ang_162pts.npz +0 -0
  24. spynach/grids/icos_2ang_163842pts.npz +0 -0
  25. spynach/grids/icos_2ang_2562pts.npz +0 -0
  26. spynach/grids/icos_2ang_40962pts.npz +0 -0
  27. spynach/grids/icos_2ang_42pts.npz +0 -0
  28. spynach/grids/icos_2ang_642pts.npz +0 -0
  29. spynach/grids/leb_1ang_rank_1023.npz +0 -0
  30. spynach/grids/leb_1ang_rank_127.npz +0 -0
  31. spynach/grids/leb_1ang_rank_15.npz +0 -0
  32. spynach/grids/leb_1ang_rank_2047.npz +0 -0
  33. spynach/grids/leb_1ang_rank_255.npz +0 -0
  34. spynach/grids/leb_1ang_rank_3.npz +0 -0
  35. spynach/grids/leb_1ang_rank_31.npz +0 -0
  36. spynach/grids/leb_1ang_rank_4095.npz +0 -0
  37. spynach/grids/leb_1ang_rank_511.npz +0 -0
  38. spynach/grids/leb_1ang_rank_63.npz +0 -0
  39. spynach/grids/leb_1ang_rank_7.npz +0 -0
  40. spynach/grids/leb_1ang_rank_8191.npz +0 -0
  41. spynach/grids/leb_2ang_rank_101.npz +0 -0
  42. spynach/grids/leb_2ang_rank_107.npz +0 -0
  43. spynach/grids/leb_2ang_rank_11.npz +0 -0
  44. spynach/grids/leb_2ang_rank_113.npz +0 -0
  45. spynach/grids/leb_2ang_rank_119.npz +0 -0
  46. spynach/grids/leb_2ang_rank_125.npz +0 -0
  47. spynach/grids/leb_2ang_rank_131.npz +0 -0
  48. spynach/grids/leb_2ang_rank_17.npz +0 -0
  49. spynach/grids/leb_2ang_rank_23.npz +0 -0
  50. spynach/grids/leb_2ang_rank_29.npz +0 -0
  51. spynach/grids/leb_2ang_rank_35.npz +0 -0
  52. spynach/grids/leb_2ang_rank_41.npz +0 -0
  53. spynach/grids/leb_2ang_rank_47.npz +0 -0
  54. spynach/grids/leb_2ang_rank_5.npz +0 -0
  55. spynach/grids/leb_2ang_rank_53.npz +0 -0
  56. spynach/grids/leb_2ang_rank_59.npz +0 -0
  57. spynach/grids/leb_2ang_rank_65.npz +0 -0
  58. spynach/grids/leb_2ang_rank_71.npz +0 -0
  59. spynach/grids/leb_2ang_rank_77.npz +0 -0
  60. spynach/grids/leb_2ang_rank_83.npz +0 -0
  61. spynach/grids/leb_2ang_rank_89.npz +0 -0
  62. spynach/grids/leb_2ang_rank_95.npz +0 -0
  63. spynach/grids/leb_3ang_rank_101.npz +0 -0
  64. spynach/grids/leb_3ang_rank_107.npz +0 -0
  65. spynach/grids/leb_3ang_rank_11.npz +0 -0
  66. spynach/grids/leb_3ang_rank_113.npz +0 -0
  67. spynach/grids/leb_3ang_rank_119.npz +0 -0
  68. spynach/grids/leb_3ang_rank_125.npz +0 -0
  69. spynach/grids/leb_3ang_rank_131.npz +0 -0
  70. spynach/grids/leb_3ang_rank_17.npz +0 -0
  71. spynach/grids/leb_3ang_rank_23.npz +0 -0
  72. spynach/grids/leb_3ang_rank_29.npz +0 -0
  73. spynach/grids/leb_3ang_rank_35.npz +0 -0
  74. spynach/grids/leb_3ang_rank_41.npz +0 -0
  75. spynach/grids/leb_3ang_rank_47.npz +0 -0
  76. spynach/grids/leb_3ang_rank_5.npz +0 -0
  77. spynach/grids/leb_3ang_rank_53.npz +0 -0
  78. spynach/grids/leb_3ang_rank_59.npz +0 -0
  79. spynach/grids/leb_3ang_rank_65.npz +0 -0
  80. spynach/grids/leb_3ang_rank_71.npz +0 -0
  81. spynach/grids/leb_3ang_rank_77.npz +0 -0
  82. spynach/grids/leb_3ang_rank_83.npz +0 -0
  83. spynach/grids/leb_3ang_rank_89.npz +0 -0
  84. spynach/grids/leb_3ang_rank_95.npz +0 -0
  85. spynach/grids/rep_1ang_100pts.npz +0 -0
  86. spynach/grids/rep_1ang_1600pts.npz +0 -0
  87. spynach/grids/rep_1ang_200pts.npz +0 -0
  88. spynach/grids/rep_1ang_3200pts.npz +0 -0
  89. spynach/grids/rep_1ang_400pts.npz +0 -0
  90. spynach/grids/rep_1ang_6400pts.npz +0 -0
  91. spynach/grids/rep_1ang_800pts.npz +0 -0
  92. spynach/grids/rep_2ang_100pts_hem.npz +0 -0
  93. spynach/grids/rep_2ang_100pts_oct.npz +0 -0
  94. spynach/grids/rep_2ang_100pts_sph.npz +0 -0
  95. spynach/grids/rep_2ang_12800pts_hem.npz +0 -0
  96. spynach/grids/rep_2ang_12800pts_oct.npz +0 -0
  97. spynach/grids/rep_2ang_12800pts_sph.npz +0 -0
  98. spynach/grids/rep_2ang_1600pts_hem.npz +0 -0
  99. spynach/grids/rep_2ang_1600pts_oct.npz +0 -0
  100. spynach/grids/rep_2ang_1600pts_sph.npz +0 -0
  101. spynach/grids/rep_2ang_200pts_hem.npz +0 -0
  102. spynach/grids/rep_2ang_200pts_oct.npz +0 -0
  103. spynach/grids/rep_2ang_200pts_sph.npz +0 -0
  104. spynach/grids/rep_2ang_25600pts_hem.npz +0 -0
  105. spynach/grids/rep_2ang_25600pts_oct.npz +0 -0
  106. spynach/grids/rep_2ang_25600pts_sph.npz +0 -0
  107. spynach/grids/rep_2ang_3200pts_hem.npz +0 -0
  108. spynach/grids/rep_2ang_3200pts_oct.npz +0 -0
  109. spynach/grids/rep_2ang_3200pts_sph.npz +0 -0
  110. spynach/grids/rep_2ang_400pts_hem.npz +0 -0
  111. spynach/grids/rep_2ang_400pts_oct.npz +0 -0
  112. spynach/grids/rep_2ang_400pts_sph.npz +0 -0
  113. spynach/grids/rep_2ang_6400pts_hem.npz +0 -0
  114. spynach/grids/rep_2ang_6400pts_oct.npz +0 -0
  115. spynach/grids/rep_2ang_6400pts_sph.npz +0 -0
  116. spynach/grids/rep_2ang_800pts_hem.npz +0 -0
  117. spynach/grids/rep_2ang_800pts_oct.npz +0 -0
  118. spynach/grids/rep_2ang_800pts_sph.npz +0 -0
  119. spynach/grids/rep_3ang_100pts.npz +0 -0
  120. spynach/grids/rep_3ang_12800pts.npz +0 -0
  121. spynach/grids/rep_3ang_1600pts.npz +0 -0
  122. spynach/grids/rep_3ang_200pts.npz +0 -0
  123. spynach/grids/rep_3ang_3200pts.npz +0 -0
  124. spynach/grids/rep_3ang_400pts.npz +0 -0
  125. spynach/grids/rep_3ang_6400pts.npz +0 -0
  126. spynach/grids/rep_3ang_800pts.npz +0 -0
  127. spynach/grids/single_crystal.npz +0 -0
  128. spynach/hamiltonian.py +289 -0
  129. spynach/isotopes.py +47 -0
  130. spynach/kernels.py +345 -0
  131. spynach/kinetics.py +95 -0
  132. spynach/molecules.py +133 -0
  133. spynach/operators.py +408 -0
  134. spynach/oracle/__init__.py +14 -0
  135. spynach/oracle/compare.py +102 -0
  136. spynach/oracle/fixture.py +142 -0
  137. spynach/pathways.py +778 -0
  138. spynach/plotting.py +1286 -0
  139. spynach/processing.py +76 -0
  140. spynach/propagation.py +479 -0
  141. spynach/reduction.py +171 -0
  142. spynach/relaxation.py +524 -0
  143. spynach/sequences.py +237 -0
  144. spynach/states.py +178 -0
  145. spynach/system.py +722 -0
  146. spynach/tolerances.py +58 -0
  147. spynach/utilities.py +133 -0
  148. spynach-0.5.0.dist-info/METADATA +387 -0
  149. spynach-0.5.0.dist-info/RECORD +152 -0
  150. spynach-0.5.0.dist-info/WHEEL +5 -0
  151. spynach-0.5.0.dist-info/licenses/LICENSE +71 -0
  152. spynach-0.5.0.dist-info/top_level.txt +2 -0
ctps/__init__.py ADDED
@@ -0,0 +1,37 @@
1
+ """ctps: coherence transfer pathway selection by phase cycling and pulsed field gradients.
2
+
3
+ A port of CCCP.m (Jerschow & Müller, J. Magn. Reson. 134, 17 (1998)) and CCCP++ (Jerschow &
4
+ Kumar, J. Magn. Reson. 160, 59 (2003)) with the non-ideal pulse treatment of Jerschow, J. Chem.
5
+ Phys. 113, 979 (2000) and an optimiser for phase cycles. Independent of ``spynach``.
6
+ """
7
+
8
+ from ctps.model import (
9
+ AllowedOrders,
10
+ Nucleus,
11
+ PathwayResult,
12
+ Period,
13
+ PhaseCycle,
14
+ Pulse,
15
+ Sample,
16
+ Sequence,
17
+ )
18
+ from ctps.optimize import CycleSolution, SearchResult, coverage, find_cycle, hcl_cycle
19
+ from ctps.simulate import simulate
20
+
21
+ __all__ = [
22
+ "AllowedOrders",
23
+ "CycleSolution",
24
+ "SearchResult",
25
+ "coverage",
26
+ "find_cycle",
27
+ "hcl_cycle",
28
+ "Nucleus",
29
+ "PathwayResult",
30
+ "Period",
31
+ "PhaseCycle",
32
+ "Pulse",
33
+ "Sample",
34
+ "Sequence",
35
+ "simulate",
36
+ ]
37
+ __version__ = "0.5.0"
@@ -0,0 +1 @@
1
+ """Engine: enumeration, phase-cycle, gradient, diffusion and pulse weights, ranking."""
@@ -0,0 +1,81 @@
1
+ """Gradient, diffusion and flow attenuation (1998 Sections 3 and 4 and the Appendix).
2
+
3
+ ``γ*_i = Σ_nuclei p_i γ`` per period (Eq. 22), ``K_q = Σ_{i≤q} γ*_i h_i`` the k-vector after the
4
+ gradient of period ``q`` (Eq. 28/37), with the gradient a delta function at the start of the
5
+ period. Attenuation at detection from the final k-vector: the program uses the envelopes
6
+ of Eq. 31 and 34, ``|sinc u|`` for ``|u| < π/2`` else ``1/|u|`` along z (``u = k_z z_max``, slab of
7
+ half-length ``z_max``) and ``|2J₁(u)/u|`` for ``|u| < 2.44`` else ``2√(2/π)|u|^(-3/2)`` transverse
8
+ (``u = |k_xy| x_max``, cylinder of radius ``x_max``); ``envelope=False`` gives the exact forms
9
+ (Eq. 30, 32). Deviation from CCCP.m: its small-argument transverse branch is unreachable
10
+ (a dead condition in the code); this port implements Eq. 34 as printed. Diffusion:
11
+ ``F = exp[-D Σ_q |K_q|² Δ_q]`` (Eq. 41/42) with ``Δ_q`` the duration of period ``q``. Flow along z
12
+ with a uniform velocity distribution over ``±v_max``: ``F = sinc(v_max Σ_i γ*_i h_iz t_i)``
13
+ (Eq. 46/48), ``t_i`` the start time of period ``i``.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import numpy as np
19
+ from scipy.special import j1
20
+
21
+ from ctps.model import Sample, Sequence
22
+
23
+
24
+ def effective_gamma(sequence: Sequence, per_nucleus: dict[str, np.ndarray]) -> np.ndarray:
25
+ """``(k, n_periods)`` effective gyromagnetic ratio ``γ*`` (rad/s/T)."""
26
+ gamma_star = None
27
+ for nucleus in sequence.nuclei:
28
+ term = per_nucleus[nucleus.name].astype(float) * nucleus.gamma
29
+ gamma_star = term if gamma_star is None else gamma_star + term
30
+ return gamma_star
31
+
32
+
33
+ def k_vectors(gamma_star: np.ndarray, areas: np.ndarray) -> np.ndarray:
34
+ """``(k, n_periods, 3)`` cumulative k-vectors ``K_q`` in rad/m."""
35
+ # GPU: broadcast multiply and cumulative sum along the period axis
36
+ return np.cumsum(gamma_star[:, :, None] * areas[None, :, :], axis=1)
37
+
38
+
39
+ def _sinc_envelope(u: np.ndarray, envelope: bool) -> np.ndarray:
40
+ u = np.abs(u)
41
+ exact = np.abs(np.sinc(u / np.pi)) # numpy's sinc is sin(pi x) / (pi x)
42
+ if not envelope:
43
+ return exact
44
+ return np.where(u < np.pi / 2, exact, 1 / np.maximum(u, 1e-300))
45
+
46
+
47
+ def _bessel_envelope(u: np.ndarray, envelope: bool) -> np.ndarray:
48
+ u = np.abs(u)
49
+ safe = np.where(u > 0, u, 1.0)
50
+ exact = np.where(u > 0, np.abs(2 * j1(safe) / safe), 1.0)
51
+ if not envelope:
52
+ return exact
53
+ return np.where(u < 2.44, exact, 2 * np.sqrt(2 / np.pi) * safe ** (-1.5))
54
+
55
+
56
+ def gradient_attenuation(k_final: np.ndarray, sample: Sample, envelope: bool = True) -> np.ndarray:
57
+ """Attenuation ``f_z · f_xy`` from the k-vector at detection, ``(k, 3)`` -> ``(k,)``."""
58
+ f_z = _sinc_envelope(k_final[:, 2] * sample.z_max, envelope)
59
+ f_xy = _bessel_envelope(np.hypot(k_final[:, 0], k_final[:, 1]) * sample.x_max, envelope)
60
+ return f_z * f_xy
61
+
62
+
63
+ def diffusion_attenuation(K: np.ndarray, durations: np.ndarray, diffusion: float) -> np.ndarray:
64
+ """``exp[-D Σ_q |K_q|² Δ_q]`` over periods, ``K`` as from :func:`k_vectors`."""
65
+ if diffusion == 0:
66
+ return np.ones(len(K))
67
+ moment = np.einsum("kqa,kqa,q->k", K, K, durations) # GPU: fused square-sum
68
+ return np.exp(-diffusion * moment)
69
+
70
+
71
+ def flow_attenuation(gamma_star: np.ndarray, areas: np.ndarray, start_times: np.ndarray, v_max: float) -> np.ndarray:
72
+ """``sinc(ψ(v_max))`` with ``ψ(v) = v Σ_i γ*_i h_iz t_i`` (1998 Eq. 46/48), flow along z."""
73
+ if v_max == 0:
74
+ return np.ones(len(gamma_star))
75
+ psi = v_max * (gamma_star * (areas[None, :, 2] * start_times[None, :])).sum(axis=1)
76
+ return np.abs(np.sinc(psi / np.pi))
77
+
78
+
79
+ def kspace_radius(k_final: np.ndarray, gamma: float) -> np.ndarray:
80
+ """DOTCOPS dephasing measure ``D = |k| / γ`` (MRM 81, 2209 (2019) Eq. 4), geometry-free, in T·s/m."""
81
+ return np.linalg.norm(k_final, axis=1) / gamma
ctps/engine/paths.py ADDED
@@ -0,0 +1,122 @@
1
+ """Pathway enumeration: per nucleus, then combined across nuclei in chunks.
2
+
3
+ The order of a nucleus changes only at pulses acting on it (CCCP.m build loop: columns of
4
+ the other nuclei carry the previous order forward), so each nucleus is enumerated over its
5
+ own pulses as a mixed-radix product of the allowed orders, with the period masks of the
6
+ periods a segment spans intersected and their weights multiplied. A ``perfect_180`` pulse
7
+ forces ``p -> -p``. Nuclei are combined lazily by index grids over chunks (the outer sum of
8
+ CCCP.m without materialising it).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Iterator
14
+ from dataclasses import dataclass
15
+
16
+ import numpy as np
17
+
18
+ from ctps.model import AllowedOrders, Sequence
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class NucleusPathways:
23
+ """All pathways of one nucleus: ``orders (k, n_periods)`` int8 and the product of allowed-order weights."""
24
+
25
+ name: str
26
+ orders: np.ndarray
27
+ weights: np.ndarray
28
+
29
+
30
+ def nucleus_pathways(sequence: Sequence, name: str) -> NucleusPathways:
31
+ allowed: AllowedOrders = sequence.allowed[name]
32
+ n_periods = sequence.n_periods
33
+ own = [j for j, pulse in enumerate(sequence.pulses) if pulse.nucleus == name]
34
+ # Segments: periods [0, own[0]], [own[0] + 1, own[1]], ..., [own[-1] + 1, n_periods - 1]
35
+ bounds = [0, *[j + 1 for j in own], n_periods]
36
+ segments = [range(bounds[i], bounds[i + 1]) for i in range(len(bounds) - 1)]
37
+
38
+ def segment_orders(periods: range) -> tuple[np.ndarray, np.ndarray]:
39
+ weights = np.ones(2 * allowed.p_max + 1)
40
+ for period in periods:
41
+ weights = weights * allowed.weights[:, period]
42
+ keep = np.flatnonzero(weights)
43
+ return keep - allowed.p_max, weights[keep]
44
+
45
+ orders_so_far = np.zeros((1, 0), dtype=np.int8)
46
+ weight_so_far = np.ones(1)
47
+ for s, periods in enumerate(segments):
48
+ values, values_weight = segment_orders(periods)
49
+ if values.size == 0:
50
+ return NucleusPathways(name, np.zeros((0, n_periods), dtype=np.int8), np.zeros(0))
51
+ if s == 0:
52
+ new = values[:, None].astype(np.int8)
53
+ weight = values_weight
54
+ else:
55
+ pulse = sequence.pulses[own[s - 1]]
56
+ previous = orders_so_far[:, -1]
57
+ if pulse.kind == "perfect_180":
58
+ # p -> -p only: keep rows whose inverted order is allowed in the next segment
59
+ index = {int(v): i for i, v in enumerate(values)}
60
+ target = np.array([index.get(int(-p), -1) for p in previous])
61
+ rows = np.flatnonzero(target >= 0)
62
+ new = np.hstack([orders_so_far[rows], (-previous[rows])[:, None].astype(np.int8)])
63
+ weight = weight_so_far[rows] * values_weight[target[rows]]
64
+ else:
65
+ k = len(orders_so_far)
66
+ new = np.hstack(
67
+ [np.repeat(orders_so_far, len(values), axis=0), np.tile(values, k)[:, None].astype(np.int8)]
68
+ )
69
+ weight = np.repeat(weight_so_far, len(values)) * np.tile(values_weight, k)
70
+ # expand the segment's single order over all its periods
71
+ width = len(periods)
72
+ orders_so_far = np.hstack([new[:, :-1], np.repeat(new[:, -1:], width, axis=1)]) if width != 1 else new
73
+ weight_so_far = weight
74
+ return NucleusPathways(name, np.ascontiguousarray(orders_so_far), weight_so_far)
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class Chunk:
79
+ """A block of combined pathways: total orders, per-nucleus orders, allowed-order weight, and the row index."""
80
+
81
+ orders: np.ndarray
82
+ per_nucleus: dict[str, np.ndarray]
83
+ weight: np.ndarray
84
+ start: int
85
+
86
+
87
+ def combined_count(parts: list[NucleusPathways]) -> int:
88
+ return int(np.prod([len(p.orders) for p in parts]))
89
+
90
+
91
+ def combine(parts: list[NucleusPathways], chunk: int = 1 << 20) -> Iterator[Chunk]:
92
+ """Yield chunks of the Cartesian product of the per-nucleus pathway sets (row-major, last nucleus fastest)."""
93
+ counts = [len(p.orders) for p in parts]
94
+ total = combined_count(parts)
95
+ for start in range(0, total, chunk):
96
+ yield chunk_at(parts, start, min(chunk, total - start), counts)
97
+
98
+
99
+ def chunk_at(parts: list[NucleusPathways], start: int, size: int, counts: list[int] | None = None) -> Chunk:
100
+ counts = counts or [len(p.orders) for p in parts]
101
+ flat = np.arange(start, start + size)
102
+ indices = []
103
+ for count in reversed(counts):
104
+ flat, index = np.divmod(flat, count)
105
+ indices.append(index)
106
+ indices.reverse()
107
+ per_nucleus = {part.name: part.orders[index] for part, index in zip(parts, indices)}
108
+ orders = np.zeros_like(next(iter(per_nucleus.values())), dtype=np.int16)
109
+ weight = np.ones(size)
110
+ for part, index in zip(parts, indices):
111
+ orders += part.orders[index]
112
+ weight *= part.weights[index]
113
+ return Chunk(orders.astype(np.int8), per_nucleus, weight, start)
114
+
115
+
116
+ def delta_p(sequence: Sequence, per_nucleus: dict[str, np.ndarray]) -> np.ndarray:
117
+ """``(k, n_pulses)`` order jumps ``Δp_j = p_j - p_{j-1}`` of the nucleus each pulse acts on (1998 Eq. 12)."""
118
+ columns = []
119
+ for j, pulse in enumerate(sequence.pulses):
120
+ orders = per_nucleus[pulse.nucleus]
121
+ columns.append(orders[:, j + 1].astype(np.int16) - orders[:, j].astype(np.int16))
122
+ return np.stack(columns, axis=1) if columns else np.zeros((len(next(iter(per_nucleus.values()))), 0), np.int16)
ctps/engine/phase.py ADDED
@@ -0,0 +1,37 @@
1
+ """Phase-cycle factor and cogwheel selection.
2
+
3
+ 1998 Eq. 12/16/17: ``ψ_m = -Δp·φ_m - φ_rec,m`` and ``s = Σ_m exp(-iψ_m)``; the tables report
4
+ ``|s| / N``. The integer form evaluates the same sum through a table of the ``fullbase``
5
+ roots of unity, so that exact zeros are exact (a design choice of this port; CCCP++ uses
6
+ precomputed sines and cosines per pathway). Cogwheel cycles ``COG_N(ν; ν_rec)`` select a
7
+ pathway iff ``Σ_j ν_j Δp_j + ν_rec ≡ 0 (mod N)`` (Jerschow & Kumar 2003 Eq. 4), the receiver of
8
+ a wanted pathway being ``ν_rec = -Σ ν_j Δp⁰_j mod N``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import numpy as np
14
+
15
+ from ctps.model import PhaseCycle
16
+
17
+
18
+ def phase_cycle_factor(dp: np.ndarray, cycle: PhaseCycle, integer: bool = True) -> np.ndarray:
19
+ """Complex ``s / N`` for every row of ``dp`` (``(k, n_pulses)`` order jumps)."""
20
+ if integer:
21
+ phases, receiver, fullbase = cycle.integer_matrix()
22
+ # GPU: integer GEMM, modulo, gather, row mean
23
+ index = (dp.astype(np.int64) @ phases + receiver[None, :]) % fullbase
24
+ table = np.exp(-2j * np.pi * np.arange(fullbase) / fullbase)
25
+ return table[index].mean(axis=1)
26
+ psi = dp.astype(float) @ cycle.phase_matrix() + cycle.receiver_phases()[None, :]
27
+ return np.exp(-1j * psi).mean(axis=1) # GPU: complex exp and row mean
28
+
29
+
30
+ def cogwheel_selects(dp: np.ndarray, N: int, nu: np.ndarray, nu_rec: int) -> np.ndarray:
31
+ """True where ``Σ ν_j Δp_j + ν_rec ≡ 0 (mod N)``: the pathway survives the cogwheel cycle."""
32
+ return (dp.astype(np.int64) @ np.asarray(nu, dtype=np.int64) + int(nu_rec)) % int(N) == 0
33
+
34
+
35
+ def receiver_winding(dp_wanted: np.ndarray, N: int, nu: np.ndarray) -> int:
36
+ """``ν_rec`` that lets the wanted pathway (``(n_pulses,)`` jumps) through: ``-Σ ν_j Δp⁰_j mod N``."""
37
+ return int((-np.asarray(dp_wanted, dtype=np.int64) @ np.asarray(nu, dtype=np.int64)) % int(N))
ctps/engine/pulse.py ADDED
@@ -0,0 +1,176 @@
1
+ """Coherence transfer weights of non-ideal pulses, after Jerschow, J. Chem. Phys. 113, 979 (2000).
2
+
3
+ A rotation keeps the rank ``l`` of a spherical tensor and mixes its order ``m`` (Eq. 2); a
4
+ single spin ``j`` has ``l ≤ 2j``, and the largest rank gives the upper bound on every transfer
5
+ (Eq. 19, verified here for ``l ≤ 8``). Leading-order transfer weights for ``p -> p'``:
6
+
7
+ * small flip angle ``β`` (Eq. 11-13): ``U = |f^l_{p'p}| (β/2)^|p - p'|`` with the coefficients
8
+ ``f`` of Eq. 13;
9
+ * near ``π``, ``β`` the deviation from ``π`` and ``ε`` the axis tilt (``tan ε = Δω/ω₁``, Eq. 10),
10
+ Eq. 14-16 and 20: ``U = |f^l_{p', -p}| |u|^|p + p'|`` with ``|u| = sqrt((β/2)² + ε²)``, so an
11
+ inverted order passes with weight 1, a non-inverted one with ``f |u|^(2|p|)``, and ``p -> 0``
12
+ leaks at first order;
13
+ * coupled spins (Eq. 21/22, Table III): the maximum over partitions of ``p`` and ``p'`` among the
14
+ spins, all jumps of one sign, of the product of single-spin coefficients;
15
+ * a perfect ``π`` pulse inverts exactly (Eq. 3).
16
+
17
+ ``exact=True`` replaces the leading terms by the full rotation matrix ``exp(-iβ n·J)`` with
18
+ ``n = (0, cos ε, sin ε)`` (Eq. 8), the paper's convention (its Cayley-Klein form was checked
19
+ against this matrix to 1e-15). Errata of the paper noted while verifying it: after Eq. 2 the
20
+ last phase factor is ``exp(-imγ)``; below Eq. 7 the pairing is ``t' = l + m' - t``; in Section V
21
+ ``Δm`` means ``Σ_i |m_i - m_{i-1}|`` as Table IV uses it. The legacy CCCP.m model
22
+ (``kind="cccp_1998"``: ``(1 - ε²/2)^|p|`` inverted, ``ε^|p|`` non-inverted) is kept for parity
23
+ with the MATLAB program only.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import itertools
29
+ from functools import cache
30
+ from math import factorial, sqrt
31
+
32
+ import numpy as np
33
+
34
+ from ctps.model import Sequence
35
+
36
+
37
+ def f_coefficient(l: int, mp: int, m: int) -> float:
38
+ """``f^l_{m'm}`` of Eq. 13: the coefficient of ``(β/2)^|m - m'|`` in ``d^l_{m'm}(β)`` at small ``β``."""
39
+ l, mp, m = int(l), int(mp), int(m)
40
+ if abs(m) > l or abs(mp) > l:
41
+ return 0.0
42
+ if m >= mp:
43
+ return sqrt(factorial(l - mp) * factorial(l + m) / (factorial(l + mp) * factorial(l - m))) / factorial(m - mp)
44
+ sign = -1.0 if (mp - m) % 2 else 1.0
45
+ return (
46
+ sign * sqrt(factorial(l + mp) * factorial(l - m) / (factorial(l - mp) * factorial(l + m))) / factorial(mp - m)
47
+ )
48
+
49
+
50
+ def wigner_d(l: int, beta: float) -> np.ndarray:
51
+ """``d^l_{m'm}(β)`` as a ``(2l+1, 2l+1)`` array indexed ``[m' + l, m + l]`` (Wigner's formula, ``exp(-iβJ_y)``)."""
52
+ d = np.zeros((2 * l + 1, 2 * l + 1))
53
+ c, s = np.cos(beta / 2), np.sin(beta / 2)
54
+ for mp in range(-l, l + 1):
55
+ for m in range(-l, l + 1):
56
+ total = 0.0
57
+ for k in range(max(0, m - mp), min(l + m, l - mp) + 1):
58
+ total += (
59
+ (-1) ** (k - m + mp)
60
+ * c ** (2 * l + m - mp - 2 * k)
61
+ * s ** (mp - m + 2 * k)
62
+ / (factorial(l + m - k) * factorial(k) * factorial(mp - m + k) * factorial(l - mp - k))
63
+ )
64
+ d[mp + l, m + l] = total * sqrt(factorial(l + mp) * factorial(l - mp) * factorial(l + m) * factorial(l - m))
65
+ return d
66
+
67
+
68
+ def rotation_matrix(l: int, beta: float, epsilon: float = 0.0) -> np.ndarray:
69
+ """``|<l m'| exp(-iβ n·J) |l m>|`` with ``n = (0, cos ε, sin ε)`` (Eq. 8).
70
+
71
+ A ``(2l+1, 2l+1)`` array indexed ``[m' + l, m + l]``.
72
+ """
73
+ from scipy.linalg import expm
74
+
75
+ m = np.arange(l, -l - 1, -1, dtype=float) # basis order l, l-1, ..., -l
76
+ jz = np.diag(m)
77
+ jp = np.zeros((2 * l + 1, 2 * l + 1))
78
+ for i in range(1, 2 * l + 1): # J+ |m> = sqrt(l(l+1) - m(m+1)) |m+1>
79
+ jp[i - 1, i] = sqrt(l * (l + 1) - m[i] * (m[i] + 1))
80
+ jy = (jp - jp.T) / 2j
81
+ u = expm(-1j * beta * (np.cos(epsilon) * jy + np.sin(epsilon) * jz))
82
+ return np.abs(u)[::-1, ::-1] # reindex to [m' + l, m + l]
83
+
84
+
85
+ @cache
86
+ def _partition_bound(l: int, n_spins: int, mp: int, m: int) -> float:
87
+ """Eq. 21/22: the largest ``Π |f|`` over partitions of ``m`` and ``m'`` among ``n_spins`` spins of rank ``l``.
88
+
89
+ Only partitions whose single-spin jumps all have one sign count.
90
+ """
91
+ if n_spins == 1:
92
+ return abs(f_coefficient(l, mp, m))
93
+ best = 0.0
94
+ values = range(-l, l + 1)
95
+ for parts in itertools.product(values, repeat=n_spins):
96
+ if sum(parts) != m:
97
+ continue
98
+ for parts_p in itertools.product(values, repeat=n_spins):
99
+ if sum(parts_p) != mp:
100
+ continue
101
+ jumps = [b - a for a, b in zip(parts, parts_p)]
102
+ if any(j > 0 for j in jumps) and any(j < 0 for j in jumps):
103
+ continue
104
+ product = 1.0
105
+ for a, b in zip(parts, parts_p):
106
+ product *= abs(f_coefficient(l, b, a))
107
+ best = max(best, product)
108
+ return best
109
+
110
+
111
+ def transfer_matrix(
112
+ kind: str, p_max: int, *, l: int = 1, n_spins: int = 1, beta: float = 0.0, epsilon: float = 0.0, exact: bool = False
113
+ ) -> np.ndarray:
114
+ """Weights ``U[p' + p_max, p + p_max]`` of the transfer ``p -> p'`` for one pulse of the given kind."""
115
+ size = 2 * p_max + 1
116
+ orders = np.arange(-p_max, p_max + 1)
117
+ U = np.zeros((size, size))
118
+ if kind == "free":
119
+ U[:] = 1.0
120
+ elif kind == "perfect_180":
121
+ for i, p in enumerate(orders):
122
+ if abs(p) <= p_max:
123
+ U[p_max - p, i] = 1.0
124
+ elif kind == "cccp_1998":
125
+ for i, p in enumerate(orders):
126
+ U[p_max - p, i] = (1 - epsilon**2 / 2) ** abs(p)
127
+ if p != 0:
128
+ U[i, i] = epsilon ** abs(p)
129
+ elif kind in ("small_flip", "imperfect_180"):
130
+ if exact:
131
+ if n_spins != 1:
132
+ raise ValueError(
133
+ "exact rotation matrices are for a single spin; use the leading-order bound for coupled spins."
134
+ )
135
+ angle = beta if kind == "small_flip" else np.pi + beta
136
+ R = rotation_matrix(l, angle, epsilon)
137
+ for i, p in enumerate(orders):
138
+ for k, pp in enumerate(orders):
139
+ if abs(p) <= l and abs(pp) <= l:
140
+ U[k, i] = R[pp + l, p + l]
141
+ else:
142
+ u = beta / 2 if kind == "small_flip" else sqrt((beta / 2) ** 2 + epsilon**2)
143
+ for i, p in enumerate(orders):
144
+ for k, pp in enumerate(orders):
145
+ source = p if kind == "small_flip" else -p
146
+ power = abs(source - pp)
147
+ coefficient = _partition_bound(l, n_spins, pp, source)
148
+ U[k, i] = coefficient * u**power if coefficient else 0.0
149
+ else:
150
+ raise ValueError(f"unknown pulse kind {kind!r}.")
151
+ return U
152
+
153
+
154
+ def pulse_factor(sequence: Sequence, per_nucleus: dict[str, np.ndarray], exact: bool = False) -> np.ndarray:
155
+ """Product over pulses of the transfer weight of the order jump each pathway makes (Eq. 23)."""
156
+ k = len(next(iter(per_nucleus.values())))
157
+ factor = np.ones(k)
158
+ for j, pulse in enumerate(sequence.pulses):
159
+ if pulse.kind in ("free", "perfect_180"):
160
+ continue
161
+ nucleus = sequence.nucleus(pulse.nucleus)
162
+ allowed = sequence.allowed[pulse.nucleus]
163
+ U = transfer_matrix(
164
+ pulse.kind,
165
+ allowed.p_max,
166
+ l=nucleus.p_max,
167
+ n_spins=nucleus.n_spins,
168
+ beta=pulse.beta,
169
+ epsilon=pulse.epsilon,
170
+ exact=exact,
171
+ )
172
+ orders = per_nucleus[pulse.nucleus]
173
+ before = orders[:, j].astype(int) + allowed.p_max
174
+ after = orders[:, j + 1].astype(int) + allowed.p_max
175
+ factor *= U[after, before] # GPU: gather
176
+ return factor
ctps/engine/rank.py ADDED
@@ -0,0 +1,23 @@
1
+ """Thresholds and ranking, in CCCP.m's order: discard after the phase cycle, after the gradients, after diffusion."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+
8
+ def survivors(
9
+ pc: np.ndarray, grad: np.ndarray, diff: np.ndarray, pulse: np.ndarray, epsilon: float, cutoff: float
10
+ ) -> np.ndarray:
11
+ """Row indices that pass ``|pc| >= epsilon``, ``|pc| grad >= cutoff`` and ``|pc| grad diff pulse >= cutoff``."""
12
+ a = np.abs(pc)
13
+ keep = a >= epsilon
14
+ keep &= a * grad >= cutoff
15
+ keep &= a * grad * diff * pulse >= cutoff
16
+ return np.flatnonzero(keep)
17
+
18
+
19
+ def ranking(amplitude: np.ndarray, wanted: np.ndarray | None = None) -> np.ndarray:
20
+ """Indices by decreasing amplitude; among equal amplitudes wanted pathways first, then enumeration order."""
21
+ if wanted is None:
22
+ return np.argsort(-amplitude, kind="stable")
23
+ return np.lexsort((~wanted, -amplitude))
ctps/io.py ADDED
@@ -0,0 +1,86 @@
1
+ """Input and output: COG notation, spectrometer phase lists, result files.
2
+
3
+ The legacy loaders for CCCP.m example scripts and CCCP++ ``.par`` files are added once the
4
+ original sources are available in the container (they define the exact formats).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import csv
10
+ import json
11
+ import re
12
+ from pathlib import Path
13
+
14
+ from ctps.model import PathwayResult, PhaseCycle
15
+
16
+ _COG = re.compile(r"^\s*COG\s*(\d+)\s*[\(\{]\s*([-\d,\s]+?)\s*;\s*(-?\d+)\s*[\)\}]\s*$")
17
+
18
+
19
+ def parse_cog(text: str) -> PhaseCycle:
20
+ """``COG23(0,3,4;14)`` or ``COG23{0,3,4;14}`` -> the cogwheel cycle (pulse winding numbers, then the receiver)."""
21
+ match = _COG.match(text)
22
+ if not match:
23
+ raise ValueError(f"not a COG string: {text!r}; expected like COG23(0,3,4;14)")
24
+ N = int(match.group(1))
25
+ nu = [int(v) for v in match.group(2).replace(" ", "").split(",") if v != ""]
26
+ return PhaseCycle.cogwheel(N, nu, int(match.group(3)))
27
+
28
+
29
+ def bruker_phase_program(cycle: PhaseCycle, *, receiver: int = 31, start: int = 1) -> str:
30
+ """Phase lists in Bruker pulse-program syntax: ``ph1=(base) 0 1 2 3`` per pulse and ``ph31`` for the receiver.
31
+
32
+ A base other than 4 is written with the ``(n)`` prefix Bruker uses for ``n`` steps per turn.
33
+ """
34
+ n = cycle.steps
35
+ prefix = "" if cycle.base == 4 else f"({cycle.base}) "
36
+ lines = []
37
+ for i, ph in enumerate(cycle.phases):
38
+ values = " ".join(str(v) for v in (list(ph) * (n // len(ph)))[:n])
39
+ lines.append(f"ph{start + i}={prefix}{values}")
40
+ base_rec = cycle.receiver_base or cycle.base
41
+ prefix_rec = "" if base_rec == 4 else f"({base_rec}) "
42
+ values = " ".join(str(v) for v in (list(cycle.receiver) * (n // len(cycle.receiver)))[:n])
43
+ lines.append(f"ph{receiver}={prefix_rec}{values}")
44
+ return "\n".join(lines) + "\n"
45
+
46
+
47
+ def phase_table(cycle: PhaseCycle, *, degrees: bool = True) -> list[dict]:
48
+ """One row per step with every pulse phase and the receiver, in degrees (or base units), for any console."""
49
+ n = cycle.steps
50
+ rows = []
51
+ phases = cycle.phase_matrix()
52
+ receiver = cycle.receiver_phases()
53
+ for m in range(n):
54
+ row = {"step": m}
55
+ for i in range(cycle.n_pulses):
56
+ row[f"pulse_{i + 1}"] = (
57
+ round(float(phases[i, m]) * 180 / 3.141592653589793, 6)
58
+ if degrees
59
+ else int(cycle.phases[i][m % len(cycle.phases[i])])
60
+ )
61
+ row["receiver"] = (
62
+ round(float(receiver[m]) * 180 / 3.141592653589793, 6)
63
+ if degrees
64
+ else int(cycle.receiver[m % len(cycle.receiver)])
65
+ )
66
+ rows.append(row)
67
+ return rows
68
+
69
+
70
+ def write_csv(result: PathwayResult, path: str | Path) -> None:
71
+ rows = result.table()
72
+ with open(path, "w", newline="", encoding="utf-8") as handle:
73
+ writer = csv.DictWriter(handle, fieldnames=list(rows[0].keys()) if rows else ["rank"])
74
+ writer.writeheader()
75
+ for row in rows:
76
+ writer.writerow({**row, "pathway": " ".join(str(p) for p in row["pathway"])})
77
+
78
+
79
+ def write_json(result: PathwayResult, path: str | Path) -> None:
80
+ payload = {
81
+ "sequence": result.sequence.to_dict(),
82
+ "cycle": result.cycle.to_dict(),
83
+ "n_enumerated": result.n_enumerated,
84
+ "pathways": result.table(),
85
+ }
86
+ Path(path).write_text(json.dumps(payload, indent=1), encoding="utf-8")