pge2py 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.
pge2py/__init__.py ADDED
@@ -0,0 +1,33 @@
1
+ """pge2 (Pulseq on GE) for pypulseq sequences, with the calls of the MATLAB toolboxes.
2
+
3
+ import pge2py as pge2
4
+ from pge2py import pulseg
5
+
6
+ psq = pulseg.fromSeq(seq)
7
+ sys_ge = pge2.opts(100e-6, 100e-6, 0.25, 5, 20, "xrm")
8
+ params = pge2.check(psq, sys_ge)
9
+ pge2.validate(psq, sys_ge, seq)
10
+ pge2.serialize(psq, "sequence.pge", pislquant=10, params=params)
11
+
12
+ The official pulseg and pge2 MATLAB toolboxes run in GNU Octave: compiled to
13
+ WebAssembly and bundled, in the browser (Pyodide, JupyterLite); the computer's
14
+ GNU Octave through oct2py, elsewhere.
15
+ """
16
+
17
+ __version__ = "0.1.0"
18
+
19
+ from . import pulseg # noqa: E402
20
+ from ._api import Params, PulSeg, SystemGE, check, opts, serialize, validate # noqa: E402
21
+ from ._report import PGE2Error, Segment # noqa: E402
22
+
23
+
24
+ def __getattr__(name):
25
+ if name == "last_messages": # messages printed by the last call
26
+ from . import _api
27
+
28
+ return _api.last_messages
29
+ raise AttributeError(name)
30
+
31
+
32
+ __all__ = ["pulseg", "opts", "check", "validate", "serialize",
33
+ "PulSeg", "SystemGE", "Params", "PGE2Error", "Segment", "__version__"]
pge2py/_api.py ADDED
@@ -0,0 +1,357 @@
1
+ """pulseg.fromSeq, pge2.opts, pge2.check, pge2.validate, pge2.serialize, as in MATLAB.
2
+
3
+ Every call runs the official MATLAB function in GNU Octave. The MATLAB values
4
+ that pass from one call to the next (the PulSeg object ``psq``, the ``params``
5
+ returned by check) are Python objects that carry the Octave data with them.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import re
12
+ import tempfile
13
+ from dataclasses import dataclass, field
14
+ from pathlib import Path
15
+
16
+ from ._octave import IN_BROWSER
17
+ from ._report import PGE2Error, Segment, SegmentReport, check_instance_lengths, trid_instances
18
+
19
+ _PRELUDE = """
20
+ addpath('{tb}/pge2'); addpath('{tb}/pulseg/third_party'); addpath('{tb}/pulseg');
21
+ addpath('{tb}/pulseq'); addpath('{tb}/overlay');
22
+ for f__ = {{'DataHash', 'rmse', 'MException', 'throw'}}
23
+ if ~exist(f__{{1}}), addpath(['{tb}/shims/' f__{{1}}]); end
24
+ end
25
+ warning('off', 'Octave:possible-matlab-short-circuit-operator');
26
+ warning('off', 'Octave:language-extension');
27
+ """
28
+
29
+ _SYS_GE = "sys_ge = pge2.opts({psd_rf_wait!r}, {psd_grd_wait!r}, {b1_max!r}, {g_max!r}, {slew_max!r}, '{coil}');\n"
30
+
31
+ _FROM_SEQ = """
32
+ psq = pulseg.fromSeq('{work}/sequence.seq');
33
+ save('-binary', '{work}/psq.mat', 'psq');
34
+ fprintf('PGE2PY_NMAX %d\\nPGE2PY_NBASE %d\\n', psq.nMax, psq.nParentBlocks);
35
+ for i__ = 1:psq.nSegments
36
+ fprintf('PGE2PY_SEG %d %s\\n', psq.segments(i__).TRID, mat2str(psq.segments(i__).blockIDs(:)'));
37
+ end
38
+ """
39
+
40
+ _CHECK = """
41
+ load('{work}/psq.mat');
42
+ params = pge2.check(psq, sys_ge, 'PNSwt', [{pns}]);
43
+ save('-binary', '{work}/params.mat', 'params');
44
+ fprintf('PGE2PY_PARAMS %.17g %.17g %.17g\\n', params.b1max, params.gmax, params.smax);
45
+ """
46
+
47
+ _VALIDATE = """
48
+ load('{work}/psq.mat');
49
+ seq_ref = mr.Sequence(); seq_ref.read('{work}/reference.seq');
50
+ ok = pge2.validate(psq, sys_ge, seq_ref, [], 'row', {row}, 'plot', false);
51
+ fprintf('PGE2PY_OK %d\\n', ok);
52
+ """
53
+
54
+ _SERIALIZE = """
55
+ load('{work}/psq.mat');
56
+ {load_params}
57
+ pge2.serialize(psq, '{work}/out.pge', 'pislquant', {pislquant}{params_arg}, 'checkHash', false);
58
+ fprintf('PGE2PY_SERIALIZED\\n');
59
+ """
60
+
61
+ _PROGRESS = re.compile(r"\d+(\.\d+)?%\s*\[[ .*]*\]")
62
+
63
+ #: Messages (warnings, mismatches) printed by the last call.
64
+ last_messages: list[str] = []
65
+
66
+
67
+ # -- values passed between calls ----------------------------------------------
68
+ @dataclass(repr=False)
69
+ class PulSeg(SegmentReport):
70
+ """What ``pulseg.fromSeq`` returns: the PulSeg object ``psq``.
71
+
72
+ Shows as the list of virtual segments and their block layout; pass it to
73
+ :func:`check`, :func:`validate` and :func:`serialize`.
74
+ """
75
+
76
+ _mat: bytes = field(default=b"", repr=False)
77
+ _seq: bytes = field(default=b"", repr=False)
78
+
79
+ @property
80
+ def nSegments(self) -> int: # noqa: N802 (MATLAB name)
81
+ return len(self.segments)
82
+
83
+
84
+ @dataclass(frozen=True)
85
+ class SystemGE:
86
+ """What ``pge2.opts`` returns: the scanner description ``sys_ge``."""
87
+
88
+ psd_rf_wait: float = 100e-6
89
+ psd_grd_wait: float = 100e-6
90
+ b1_max: float = 0.25
91
+ g_max: float = 5.0
92
+ slew_max: float = 20.0
93
+ coil: str = "xrm"
94
+
95
+
96
+ class Params(dict):
97
+ """What ``pge2.check`` returns: ``params`` (peak B1 in G, peak gradient in
98
+ G/cm, peak slew rate in G/cm/ms over the scan), to pass to :func:`serialize`."""
99
+
100
+ _mat: bytes = b""
101
+
102
+
103
+ # -- running Octave ----------------------------------------------------------
104
+ _runner = None
105
+
106
+
107
+ def _get_runner():
108
+ global _runner
109
+ if _runner is None:
110
+ if IN_BROWSER:
111
+ from ._octave import BrowserOctave
112
+
113
+ _runner = BrowserOctave()
114
+ else:
115
+ from ._octave import DesktopOctave
116
+
117
+ _runner = DesktopOctave()
118
+ return _runner
119
+
120
+
121
+ def _parse(stdout: str, stderr: str) -> list[str]:
122
+ global last_messages
123
+ text = _PROGRESS.sub("", stdout.replace("\b", ""))
124
+ lines = [l.strip() for l in (text + "\n" + stderr).splitlines() if l.strip()]
125
+ for l in lines:
126
+ if l.startswith("__PGE_ERROR__"):
127
+ raise PGE2Error(l[len("__PGE_ERROR__"):].strip())
128
+ last_messages = [l for l in lines if not l.startswith("PGE2PY_")]
129
+ return lines
130
+
131
+
132
+ def _call(script: str, files: dict):
133
+ runner = _get_runner()
134
+ if IN_BROWSER:
135
+ from pyodide.ffi import can_run_sync, run_sync
136
+
137
+ if not can_run_sync():
138
+ raise RuntimeError(
139
+ "this browser cannot wait for Octave synchronously; use the coroutines "
140
+ "in pge2py.aio, e.g. `await aio.check(psq, sys_ge)`"
141
+ )
142
+ out, err, files_out = run_sync(runner.arun(script, files))
143
+ else:
144
+ out, err, files_out = runner.run(script, files)
145
+ return _parse(out, err), files_out
146
+
147
+
148
+ async def _acall(script: str, files: dict):
149
+ runner = _get_runner()
150
+ if IN_BROWSER:
151
+ out, err, files_out = await runner.arun(script, files)
152
+ else:
153
+ out, err, files_out = runner.run(script, files)
154
+ return _parse(out, err), files_out
155
+
156
+
157
+ def _seq_bytes(seq) -> bytes:
158
+ """A pypulseq Sequence, or the path of a .seq file, as .seq file content."""
159
+ if isinstance(seq, (str, os.PathLike)):
160
+ return Path(seq).read_bytes()
161
+ with tempfile.TemporaryDirectory() as d:
162
+ path = os.path.join(d, "sequence.seq")
163
+ seq.write(path)
164
+ return Path(path).read_bytes()
165
+
166
+
167
+ def _as_seq_object(seq):
168
+ if isinstance(seq, (str, os.PathLike)):
169
+ import pypulseq as pp
170
+
171
+ s = pp.Sequence()
172
+ s.read(str(seq))
173
+ return s
174
+ return seq
175
+
176
+
177
+ # -- the calls, each in a "plan" (script, files, finish) used sync and async ---
178
+ def _from_seq_plan(seq):
179
+ obj = _as_seq_object(seq)
180
+ if not trid_instances(obj):
181
+ raise PGE2Error("no TRID label in the sequence: pulseg needs one on the first block of every segment")
182
+ check_instance_lengths(obj)
183
+ data = _seq_bytes(seq)
184
+ r = _get_runner()
185
+
186
+ def finish(lines, files):
187
+ trids = trid_instances(obj)
188
+ segs, nmax, nbase = [], 0, 0
189
+ for l in lines:
190
+ if l.startswith("PGE2PY_SEG "):
191
+ _, trid, ids = l.split(" ", 2)
192
+ ids = [int(x) for x in ids.strip("[]").replace(";", " ").split()]
193
+ segs.append(Segment(trid=int(trid), block_ids=ids, n_instances=trids.get(int(trid), 0)))
194
+ elif l.startswith("PGE2PY_NMAX "):
195
+ nmax = int(l.split()[1])
196
+ elif l.startswith("PGE2PY_NBASE "):
197
+ nbase = int(l.split()[1])
198
+ warnings = [m for m in last_messages if m.lower().startswith("warning")]
199
+ return PulSeg(segments=segs, n_base_blocks=nbase, n_blocks=nmax, warnings=warnings,
200
+ _mat=files["psq.mat"], _seq=data)
201
+
202
+ return (_PRELUDE + _FROM_SEQ).format(work=r.work, tb=r.tb), {"sequence.seq": data}, finish
203
+
204
+
205
+ def _need_psq(psq):
206
+ if not isinstance(psq, PulSeg):
207
+ raise TypeError("psq must be the result of pulseg.fromSeq(seq)")
208
+
209
+
210
+ def _check_plan(psq, sys_ge, PNSwt): # noqa: N803
211
+ _need_psq(psq)
212
+ r = _get_runner()
213
+ script = (_PRELUDE + _SYS_GE.format(**sys_ge.__dict__) + _CHECK).format(
214
+ work=r.work, tb=r.tb, pns=" ".join(repr(float(w)) for w in PNSwt))
215
+
216
+ def finish(lines, files):
217
+ vals = next(l for l in lines if l.startswith("PGE2PY_PARAMS ")).split()[1:]
218
+ p = Params(zip(("b1max", "gmax", "smax"), map(float, vals)))
219
+ p._mat = files["params.mat"]
220
+ return p
221
+
222
+ return script, {"psq.mat": psq._mat}, finish
223
+
224
+
225
+ def _validate_plan(psq, sys_ge, seq, row):
226
+ _need_psq(psq)
227
+ r = _get_runner()
228
+ ref = psq._seq if seq is None else _seq_bytes(seq)
229
+ script = (_PRELUDE + _SYS_GE.format(**sys_ge.__dict__) + _VALIDATE).format(
230
+ work=r.work, tb=r.tb, row="[]" if row is None else int(row))
231
+
232
+ def finish(lines, files):
233
+ return next(l for l in lines if l.startswith("PGE2PY_OK ")).split()[1] == "1"
234
+
235
+ return script, {"psq.mat": psq._mat, "reference.seq": ref}, finish
236
+
237
+
238
+ def _serialize_plan(psq, filename, pislquant, params, sysGE): # noqa: N803
239
+ _need_psq(psq)
240
+ r = _get_runner()
241
+ files = {"psq.mat": psq._mat}
242
+ load, args = "", ""
243
+ if params is not None:
244
+ files["params.mat"] = params._mat
245
+ load += f"load('{r.work}/params.mat');"
246
+ args += ", 'params', params"
247
+ if sysGE is not None:
248
+ load += _SYS_GE.format(**sysGE.__dict__)
249
+ args += ", 'sysGE', sys_ge"
250
+ script = (_PRELUDE + _SERIALIZE).format(
251
+ work=r.work, tb=r.tb, pislquant=int(pislquant), load_params=load, params_arg=args)
252
+
253
+ def finish(lines, files_out):
254
+ path = Path(filename).resolve()
255
+ path.write_bytes(files_out["out.pge"])
256
+ return path
257
+
258
+ return script, files, finish
259
+
260
+
261
+ # -- public API ----------------------------------------------------------------
262
+ def fromSeq(seq) -> PulSeg: # noqa: N802 (MATLAB name)
263
+ """``pulseg.fromSeq``: convert a sequence to the PulSeg representation.
264
+
265
+ Parameters
266
+ ----------
267
+ seq : pypulseq.Sequence or path
268
+ The sequence, or its ``.seq`` file.
269
+
270
+ Returns
271
+ -------
272
+ PulSeg
273
+ ``psq``: the virtual segments, their block layout and any warnings.
274
+
275
+ Raises
276
+ ------
277
+ PGE2Error
278
+ If the sequence has no TRID label, if the instances of a segment differ
279
+ in number of blocks, or if ``pulseg.fromSeq`` stops.
280
+ """
281
+ script, files, finish = _from_seq_plan(seq)
282
+ return finish(*_call(script, files))
283
+
284
+
285
+ def opts(psd_rf_wait=100e-6, psd_grd_wait=100e-6, b1_max=0.25, g_max=5.0, slew_max=20.0, coil="xrm") -> SystemGE:
286
+ """``pge2.opts``: the scanner description, with the arguments of the MATLAB function.
287
+
288
+ Parameters
289
+ ----------
290
+ psd_rf_wait, psd_grd_wait : float
291
+ RF-gradient and ADC-gradient delays (s), scanner specific.
292
+ b1_max : float
293
+ Peak B1 (G).
294
+ g_max : float
295
+ Peak gradient (G/cm).
296
+ slew_max : float
297
+ Peak slew rate (G/cm/ms).
298
+ coil : str
299
+ Gradient coil, see ``pge2.opts``: 'xrm' (MR750), 'hrmw' (Premier), 'magnus', ...
300
+ """
301
+ return SystemGE(float(psd_rf_wait), float(psd_grd_wait), float(b1_max), float(g_max), float(slew_max), str(coil))
302
+
303
+
304
+ def check(psq: PulSeg, sys_ge: SystemGE, PNSwt=(1, 1, 1)) -> Params: # noqa: N803 (MATLAB name)
305
+ """``pge2.check``: timing, PNS, peak B1 and gradient limits.
306
+
307
+ Returns
308
+ -------
309
+ Params
310
+ ``params``: ``b1max`` (G), ``gmax`` (G/cm), ``smax`` (G/cm/ms).
311
+
312
+ Raises
313
+ ------
314
+ PGE2Error
315
+ If a block or segment instance breaks a hardware rule.
316
+ """
317
+ script, files, finish = _check_plan(psq, sys_ge, PNSwt)
318
+ return finish(*_call(script, files))
319
+
320
+
321
+ def validate(psq: PulSeg, sys_ge: SystemGE, seq=None, row=None) -> bool:
322
+ """``pge2.validate``: replay every segment instance and compare with the sequence.
323
+
324
+ Parameters
325
+ ----------
326
+ seq : pypulseq.Sequence or path, optional
327
+ Reference sequence; by default the one given to ``pulseg.fromSeq``.
328
+ row : int, optional
329
+ Check only segments starting at or after this block (MATLAB 'row').
330
+
331
+ Returns
332
+ -------
333
+ bool
334
+ True if every instance matches. Mismatches are in ``pge2py.last_messages``.
335
+ """
336
+ script, files, finish = _validate_plan(psq, sys_ge, seq, row)
337
+ return finish(*_call(script, files))
338
+
339
+
340
+ def serialize(psq: PulSeg, filename, pislquant: int = 10, params: Params | None = None,
341
+ sysGE: SystemGE | None = None) -> Path: # noqa: N803 (MATLAB name)
342
+ """``pge2.serialize``: write the ``.pge`` file for the scanner.
343
+
344
+ Parameters
345
+ ----------
346
+ filename : path
347
+ Output ``.pge`` file.
348
+ pislquant : int
349
+ Number of ADC events Auto Prescan uses to set the receive gain.
350
+ params : Params, optional
351
+ The result of :func:`check`.
352
+ sysGE : SystemGE, optional
353
+ The result of :func:`opts`, if ``params`` is not given (one of the two
354
+ is required, as in MATLAB).
355
+ """
356
+ script, files, finish = _serialize_plan(psq, filename, pislquant, params, sysGE)
357
+ return finish(*_call(script, files))
@@ -0,0 +1,23 @@
1
+ {
2
+ "octave": {
3
+ "version": "10.3.0",
4
+ "url": "https://prefix.dev/emscripten-forge-4x/emscripten-wasm32/octave-10.3.0-pl5321h996e327_3.tar.bz2",
5
+ "sha256": "51226adc11c3216878a3e3dd34cafaa5ae50844fe5707ad06ce30fd1739ee1bb",
6
+ "license": "GPL-3.0-or-later",
7
+ "source": "https://github.com/emscripten-forge/recipes (recipes/recipes_emscripten/octave), https://ftp.gnu.org/gnu/octave/octave-10.3.0.tar.gz"
8
+ },
9
+ "toolboxes": {
10
+ "pulseq": {
11
+ "url": "https://github.com/pulseq/pulseq",
12
+ "commit": "11e459d9b6b426aa6ea57a01153fb9afea332f6f"
13
+ },
14
+ "pulseg": {
15
+ "url": "https://github.com/HarmonizedMRI/pulseg",
16
+ "commit": "ca2a278a4160f859f1009812dcda86b783a3f3a1"
17
+ },
18
+ "pge2": {
19
+ "url": "https://github.com/HarmonizedMRI/pge2",
20
+ "commit": "9fa76e60e65a92325e51a0c98f0302e3a805d960"
21
+ }
22
+ }
23
+ }