lcmodel-wrapper 0.3.1__tar.gz → 0.3.2__tar.gz

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 (26) hide show
  1. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/PKG-INFO +1 -1
  2. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/lcmodel_wrapper/_version.py +1 -1
  3. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/lcmodel_wrapper/binaries.py +1 -1
  4. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/lcmodel_wrapper/convert.py +27 -10
  5. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/lcmodel_wrapper.egg-info/PKG-INFO +1 -1
  6. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/lcmodel_wrapper.egg-info/SOURCES.txt +1 -0
  7. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/tests/test_binaries.py +15 -0
  8. lcmodel_wrapper-0.3.2/tests/test_convert.py +74 -0
  9. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/tests/test_lcm.py +3 -1
  10. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/LICENSE +0 -0
  11. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/LICENSE.lcmodel +0 -0
  12. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/MANIFEST.in +0 -0
  13. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/NOTICE +0 -0
  14. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/README.md +0 -0
  15. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/lcmodel_wrapper/__init__.py +0 -0
  16. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/lcmodel_wrapper/basis.py +0 -0
  17. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/lcmodel_wrapper/container.py +0 -0
  18. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/lcmodel_wrapper/control.py +0 -0
  19. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/lcmodel_wrapper/coord.py +0 -0
  20. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/lcmodel_wrapper/core.py +0 -0
  21. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/lcmodel_wrapper/io.py +0 -0
  22. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/lcmodel_wrapper.egg-info/dependency_links.txt +0 -0
  23. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/lcmodel_wrapper.egg-info/requires.txt +0 -0
  24. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/lcmodel_wrapper.egg-info/top_level.txt +0 -0
  25. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/pyproject.toml +0 -0
  26. {lcmodel_wrapper-0.3.1 → lcmodel_wrapper-0.3.2}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lcmodel_wrapper
3
- Version: 0.3.1
3
+ Version: 0.3.2
4
4
  Summary: Lightweight Python wrapper for LCModel MRS fitting
5
5
  Author-email: Julian Merkofer <j.p.merkofer@tue.nl>
6
6
  License: Apache-2.0
@@ -1,4 +1,4 @@
1
1
  # Single source of truth for the package version. pyproject.toml reads it at build time,
2
2
  # and binaries.py derives the GitHub release / container image tag ("v<version>") from
3
3
  # it, so every wheel pairs with the LCModel artifacts built alongside it.
4
- __version__ = "0.3.1"
4
+ __version__ = "0.3.2"
@@ -295,7 +295,7 @@ def verify_executable(path, timeout: Optional[float] = None) -> Tuple[bool, str]
295
295
  if os.environ.get("LCMODEL_SKIP_VERIFY"):
296
296
  return True, "skipped via LCMODEL_SKIP_VERIFY"
297
297
 
298
- path = Path(path)
298
+ path = Path(path).expanduser().resolve() # the probe runs in a temporary directory
299
299
  try:
300
300
  st = path.stat()
301
301
  key = (str(path.resolve()), st.st_mtime_ns, st.st_size)
@@ -39,9 +39,20 @@ def _fmt_block(values: np.ndarray) -> str:
39
39
 
40
40
 
41
41
  def write_basis(out_path: str, names: List[str], fids: List[np.ndarray],
42
- dwell: float, central_freq: float, echo_time: float = -1.0) -> str:
43
- """Write metabolite FIDs to an LCModel ".basis" file (experimental)."""
44
- n_points = len(fids[0])
42
+ dwell: float, central_freq: float, echo_time: float = -1.0,
43
+ centre_ppm: float = 4.65) -> str:
44
+ """Write metabolite FIDs to an LCModel ".basis" file (experimental).
45
+
46
+ LCModel reads the data block of a ".basis" as the frequency-domain spectrum
47
+ (BASISF in LCModel.f), which MakeBasis writes as the orthonormal FFT of the FID
48
+ zero-filled to twice its length (NDATAB = 2 * NUNFIL). The FIDs are expected in
49
+ LCModel's ".RAW" orientation.
50
+
51
+ Like MakeBasis, every metabolite is preceded by a $NMUSED block stating the ppm at
52
+ the centre (PPMSEP). LCModel skips it, but Osprey's reader takes its ppm axis from
53
+ it and falls back to 3 ppm without it.
54
+ """
55
+ n_points = 2 * len(fids[0])
45
56
  with open(out_path, "w") as fh:
46
57
  fh.write(" $SEQPAR\n")
47
58
  fh.write(" FWHMBA = -1.,\n")
@@ -57,6 +68,9 @@ def write_basis(out_path: str, names: List[str], fids: List[np.ndarray],
57
68
  fh.write(" $END\n")
58
69
 
59
70
  for name, fid in zip(names, fids):
71
+ fh.write(" $NMUSED\n")
72
+ fh.write(f" PPMSEP = {centre_ppm},\n")
73
+ fh.write(" $END\n")
60
74
  fh.write(" $BASIS\n")
61
75
  fh.write(f" ID = '{name}',\n")
62
76
  fh.write(f" METABO = '{name}',\n")
@@ -65,9 +79,10 @@ def write_basis(out_path: str, names: List[str], fids: List[np.ndarray],
65
79
  fh.write(" VOLUME = 1.,\n")
66
80
  fh.write(" ISHIFT = 0\n")
67
81
  fh.write(" $END\n")
82
+ spec = np.fft.fft(np.asarray(fid, dtype=complex), n=n_points, norm="ortho")
68
83
  interleaved = np.empty(2 * n_points, dtype=np.float64)
69
- interleaved[0::2] = np.real(fid)
70
- interleaved[1::2] = np.imag(fid)
84
+ interleaved[0::2] = np.real(spec)
85
+ interleaved[1::2] = np.imag(spec)
71
86
  fh.write(_fmt_block(interleaved) + "\n")
72
87
  return out_path
73
88
 
@@ -115,7 +130,8 @@ def _read_jmrui_folder(folder: str) -> ParsedBasis:
115
130
  dwell = dwell if dwell is not None else d
116
131
  central = central if central is not None else c
117
132
  names.append(os.path.splitext(f)[0])
118
- fids.append(fid)
133
+ # jMRUI stores the conjugate of LCModel's .RAW orientation
134
+ fids.append(np.conj(fid))
119
135
  return ParsedBasis(names, fids, dwell, central, None)
120
136
 
121
137
 
@@ -155,7 +171,7 @@ _NUM_RE = re.compile(r"[-+]?\d*\.?\d+(?:[eEdD][-+]?\d+)?")
155
171
 
156
172
  def _read_raw_file(path: str) -> Tuple[np.ndarray, Dict[str, str]]:
157
173
  keys: Dict[str, str] = {}
158
- rows = []
174
+ values = []
159
175
  with open(path, "r", errors="ignore") as fh:
160
176
  for line in fh:
161
177
  s = line.strip()
@@ -165,10 +181,11 @@ def _read_raw_file(path: str) -> Tuple[np.ndarray, Dict[str, str]]:
165
181
  key, _, val = s.partition("=")
166
182
  keys[key.strip().upper()] = val.strip().rstrip(",").strip().strip("'")
167
183
  continue
184
+ # FMTDAT may put several (real, imag) pairs on a line, e.g. '(8E13.5)'
168
185
  nums = _NUM_RE.findall(s.replace("D", "E").replace("d", "e"))
169
- if len(nums) >= 2:
170
- rows.append(float(nums[0]) + 1j * float(nums[1]))
171
- return np.asarray(rows, dtype=np.complex128), keys
186
+ values.extend(float(v) for v in nums)
187
+ values = np.asarray(values[:len(values) // 2 * 2], dtype=np.float64)
188
+ return values[0::2] + 1j * values[1::2], keys
172
189
 
173
190
 
174
191
  def _read_raw_folder(folder: str) -> ParsedBasis:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lcmodel_wrapper
3
- Version: 0.3.1
3
+ Version: 0.3.2
4
4
  Summary: Lightweight Python wrapper for LCModel MRS fitting
5
5
  Author-email: Julian Merkofer <j.p.merkofer@tue.nl>
6
6
  License: Apache-2.0
@@ -30,4 +30,5 @@ lcmodel_wrapper.egg-info/dependency_links.txt
30
30
  lcmodel_wrapper.egg-info/requires.txt
31
31
  lcmodel_wrapper.egg-info/top_level.txt
32
32
  tests/test_binaries.py
33
+ tests/test_convert.py
33
34
  tests/test_lcm.py
@@ -11,6 +11,7 @@
11
11
 
12
12
  import os
13
13
  import platform
14
+ import shutil
14
15
  import sys
15
16
 
16
17
  import pytest
@@ -118,6 +119,19 @@ def test_probe_accepts_the_real_binary():
118
119
  assert ok is True, why
119
120
 
120
121
 
122
+ def test_probe_accepts_a_relative_path(tmp_path, monkeypatch):
123
+ """The probe runs the candidate in a temporary directory, so a path relative to the
124
+ caller's directory (a relative cache_dir or LCMODEL_EXEC) has to be resolved first."""
125
+ real = os.environ.get("LCMODEL_EXEC") or _cached_binary()
126
+ if not real:
127
+ pytest.skip("no LCModel binary to copy")
128
+ (tmp_path / "bin").mkdir()
129
+ shutil.copy2(real, tmp_path / "bin" / "lcmodel")
130
+ monkeypatch.chdir(tmp_path)
131
+ ok, why = binaries.verify_executable(os.path.join("bin", "lcmodel"))
132
+ assert ok is True, why
133
+
134
+
121
135
  #************************#
122
136
  # platform detection #
123
137
  #************************#
@@ -450,6 +464,7 @@ def test_quarantine_moves_rather_than_deletes(monkeypatch, tmp_path):
450
464
 
451
465
  def test_resolve_reports_every_source_it_tried(monkeypatch, tmp_path):
452
466
  monkeypatch.setenv("LCMODEL_CACHE_DIR", str(tmp_path))
467
+ monkeypatch.delenv("LCMODEL_EXEC", raising=False) # an explicit binary would be used as is
453
468
  with pytest.raises(RuntimeError) as excinfo:
454
469
  binaries.resolve_executable(allow_download=False, allow_build=False,
455
470
  allow_docker=False)
@@ -0,0 +1,74 @@
1
+ ####################################################################################################
2
+ # test_convert.py #
3
+ ####################################################################################################
4
+ # #
5
+ # Purpose: Basis conversion against LCModel's own MakeBasis output. The ISMRM 2016 fitting #
6
+ # challenge ships one basis set as per-metabolite LCModel .RAW files, as jMRUI text #
7
+ # files, and as the .BASIS that MakeBasis made from those .RAW files; converting either #
8
+ # of the first two must reproduce the data blocks of the third. #
9
+ # #
10
+ ####################################################################################################
11
+
12
+ import os
13
+ import re
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ import numpy as np
18
+ import pytest
19
+
20
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
21
+
22
+ from lcmodel_wrapper import convert_to_basis
23
+
24
+ _REPO = Path(__file__).resolve().parent.parent
25
+ _CHALLENGE = _REPO / "example_data" / "2016_fitting_challenge"
26
+ _MAKEBASIS = _CHALLENGE / "basisset_LCModel" / "press3T_30ms.BASIS"
27
+
28
+ pytestmark = pytest.mark.skipif(not _MAKEBASIS.is_file(),
29
+ reason="challenge data missing (git submodule update --init)")
30
+
31
+
32
+ def read_basis_spectra(path) -> dict:
33
+ """The data block of every metabolite in a ".basis" file, by metabolite name."""
34
+ text = Path(path).read_text()
35
+ spectra = {}
36
+ for m in re.finditer(r"\$BASIS\s(.*?)\$END(.*?)(?=\$|\Z)", text, re.S):
37
+ name = re.search(r"METABO\s*=\s*'([^']*)'", m.group(1)).group(1).strip()
38
+ values = np.array(m.group(2).split(), dtype=float)
39
+ spectra[name] = values[0::2] + 1j * values[1::2]
40
+ return spectra
41
+
42
+
43
+ @pytest.mark.parametrize("fmt, folder", [("raw", "basisset_LCModel"),
44
+ ("jmrui", "basisset_JMRUI")])
45
+ def test_conversion_matches_makebasis(tmp_path, fmt, folder):
46
+ reference = read_basis_spectra(_MAKEBASIS)
47
+ out = convert_to_basis(str(_CHALLENGE / folder), out_path=str(tmp_path / "converted.basis"),
48
+ fmt=fmt, dwell=2.5e-4, central_freq=123.261703)
49
+ converted = read_basis_spectra(out)
50
+
51
+ assert set(reference) <= set(converted)
52
+ for name, spectrum in reference.items():
53
+ assert converted[name].shape == spectrum.shape, name
54
+ err = np.abs(converted[name] - spectrum).max() / np.abs(spectrum).max()
55
+ assert err < 1e-3, f"{name}: {err:.2e}"
56
+
57
+
58
+ def read_ppmsep(path) -> list:
59
+ """The PPMSEP stated before every metabolite, in file order."""
60
+ text = Path(path).read_text()
61
+ return [float(v) for v in re.findall(r"PPMSEP\s*=\s*([-+.\dEe]+)", text)]
62
+
63
+
64
+ def test_every_metabolite_states_its_centre_like_makebasis(tmp_path):
65
+ """MakeBasis puts PPMSEP in a $NMUSED block before each metabolite; Osprey's reader
66
+ takes its ppm axis from it."""
67
+ reference = read_ppmsep(_MAKEBASIS)
68
+ out = convert_to_basis(str(_CHALLENGE / "basisset_LCModel"),
69
+ out_path=str(tmp_path / "converted.basis"), fmt="raw",
70
+ dwell=2.5e-4, central_freq=123.261703)
71
+
72
+ assert len(set(reference)) == 1
73
+ assert read_ppmsep(out) == pytest.approx(reference[:1] * len(read_basis_spectra(out)))
74
+
@@ -81,7 +81,9 @@ def challenge_mae(test_size: int = 5) -> float:
81
81
  return float(lcm.concsLoss(concs, thetas, type="ae").mean())
82
82
 
83
83
 
84
- @pytest.mark.skipif(not _CHALLENGE.is_dir() or not _TRUTH.is_dir(),
84
+ # an uninitialised submodule is an empty directory, so look for its content
85
+ @pytest.mark.skipif(not (_CHALLENGE / "basisset_LCModel" / "press3T_30ms.BASIS").is_file()
86
+ or not any(_TRUTH.glob("*.xlsx")),
85
87
  reason="challenge data not checked out (git submodule update --init)")
86
88
  def test_challenge_fit_matches_reference():
87
89
  mae = challenge_mae()
File without changes
File without changes