rapidtide 3.0.9__py3-none-any.whl → 3.0.11__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.
rapidtide/io.py CHANGED
@@ -1263,6 +1263,10 @@ def readlabelledtsv(inputfilename, compressed=False):
1263
1263
  theext = ".tsv.gz"
1264
1264
  else:
1265
1265
  theext = ".tsv"
1266
+
1267
+ if not os.path.isfile(inputfilename + theext):
1268
+ raise FileNotFoundError(f"Labelled tsv file {inputfilename + theext} does not exist")
1269
+
1266
1270
  df = pd.read_csv(inputfilename + theext, sep="\t", quotechar='"')
1267
1271
 
1268
1272
  # replace nans with 0
@@ -1290,6 +1294,9 @@ def readcsv(inputfilename, debug=False):
1290
1294
  NOTE: If file does not exist or is not valid, return an empty dictionary
1291
1295
 
1292
1296
  """
1297
+ if not os.path.isfile(inputfilename + ".csv"):
1298
+ raise FileNotFoundError(f"csv file {inputfilename}.csv does not exist")
1299
+
1293
1300
  timeseriesdict = {}
1294
1301
 
1295
1302
  # Read the data in initially with no header
@@ -1341,6 +1348,9 @@ def readfslmat(inputfilename, debug=False):
1341
1348
  NOTE: If file does not exist or is not valid, return an empty dictionary
1342
1349
 
1343
1350
  """
1351
+ if not os.path.isfile(inputfilename + ".mat"):
1352
+ raise FileNotFoundError(f"FSL mat file {inputfilename}.mat does not exist")
1353
+
1344
1354
  timeseriesdict = {}
1345
1355
 
1346
1356
  # Read the data in with no header
@@ -1364,8 +1374,7 @@ def readoptionsfile(inputfileroot):
1364
1374
  # options saved as text
1365
1375
  thedict = readdict(inputfileroot + ".txt")
1366
1376
  else:
1367
- print("no valid options file found")
1368
- return {}
1377
+ raise FileNotFoundError(f"options file {inputfileroot}(.json/.txt) does not exist")
1369
1378
 
1370
1379
  # correct behavior for older options files
1371
1380
  try:
@@ -1476,7 +1485,7 @@ def writebidstsv(
1476
1485
  reshapeddata = data
1477
1486
  if append:
1478
1487
  insamplerate, instarttime, incolumns, indata, incompressed, incolsource = readbidstsv(
1479
- outputfileroot + ".json", debug=debug
1488
+ outputfileroot + ".json", neednotexist=True, debug=debug,
1480
1489
  )
1481
1490
  if debug:
1482
1491
  print("appending")
@@ -1723,7 +1732,7 @@ def readvectorsfromtextfile(fullfilespec, onecol=False, debug=False):
1723
1732
  return thesamplerate, thestarttime, thecolumns, thedata, compressed, filetype
1724
1733
 
1725
1734
 
1726
- def readbidstsv(inputfilename, colspec=None, warn=True, debug=False):
1735
+ def readbidstsv(inputfilename, colspec=None, warn=True, neednotexist=False, debug=False):
1727
1736
  r"""Read time series out of a BIDS tsv file
1728
1737
 
1729
1738
  Parameters
@@ -1890,11 +1899,13 @@ def readbidstsv(inputfilename, colspec=None, warn=True, debug=False):
1890
1899
  columnsource,
1891
1900
  )
1892
1901
  else:
1893
- print("file pair does not exist")
1894
- return [None, None, None, None, None, None]
1902
+ if neednotexist:
1903
+ return [None, None, None, None, None, None]
1904
+ else:
1905
+ raise FileNotFoundError(f"file pair {thefileroot}(.json/.tsv[.gz]) does not exist")
1895
1906
 
1896
1907
 
1897
- def readcolfrombidstsv(inputfilename, columnnum=0, columnname=None, debug=False):
1908
+ def readcolfrombidstsv(inputfilename, columnnum=0, columnname=None, neednotexist=False, debug=False):
1898
1909
  r"""
1899
1910
 
1900
1911
  Parameters
@@ -1908,7 +1919,7 @@ def readcolfrombidstsv(inputfilename, columnnum=0, columnname=None, debug=False)
1908
1919
 
1909
1920
  """
1910
1921
  samplerate, starttime, columns, data, compressed, colsource = readbidstsv(
1911
- inputfilename, debug=debug
1922
+ inputfilename, neednotexist=neednotexist, debug=debug
1912
1923
  )
1913
1924
  if data is None:
1914
1925
  print("no valid datafile found")
@@ -694,9 +694,9 @@ class SimilarityFunctionFitter:
694
694
  while peakpoints[peakstart - 1] == 1:
695
695
  peakstart -= 1
696
696
  else:
697
- while thegrad[peakend + 1] <= 0.0 and peakpoints[peakend + 1] == 1:
697
+ while thegrad[peakend + 1] <= 0.0 and peakpoints[peakend + 1] == 1 and peakend < len(self.corrtimeaxis) - 2:
698
698
  peakend += 1
699
- while thegrad[peakstart - 1] >= 0.0 and peakpoints[peakstart - 1] == 1:
699
+ while thegrad[peakstart - 1] >= 0.0 and peakpoints[peakstart - 1] == 1 and peakstart >= 1:
700
700
  peakstart -= 1
701
701
  if self.debug:
702
702
  print("final peakstart, peakend:", peakstart, peakend)
@@ -819,12 +819,18 @@ class SimilarityFunctionFitter:
819
819
  if self.debug:
820
820
  print("fit input array:", p0)
821
821
  try:
822
- plsq, dummy = sp.optimize.leastsq(
822
+ plsq, ier = sp.optimize.leastsq(
823
823
  tide_fit.gaussresiduals, p0, args=(data, X), maxfev=5000
824
824
  )
825
- maxval = plsq[0] + baseline
826
- maxlag = np.fmod((1.0 * plsq[1]), self.lagmod)
827
- maxsigma = plsq[2]
825
+ if ier not in [1, 2, 3, 4]: # Check for successful convergence
826
+ failreason |= self.FML_FITALGOFAIL
827
+ maxval = np.float64(0.0)
828
+ maxlag = np.float64(0.0)
829
+ maxsigma = np.float64(0.0)
830
+ else:
831
+ maxval = plsq[0] + baseline
832
+ maxlag = np.fmod((1.0 * plsq[1]), self.lagmod)
833
+ maxsigma = plsq[2]
828
834
  except:
829
835
  failreason |= self.FML_FITALGOFAIL
830
836
  maxval = np.float64(0.0)
@@ -929,7 +935,7 @@ class SimilarityFunctionFitter:
929
935
  # different rules for mutual information peaks
930
936
  if ((maxval - baseline) < self.lthreshval * baselinedev) or (maxval < baseline):
931
937
  failreason |= self.FML_FITAMPLOW
932
- maxval_init = 0.0
938
+ maxval = 0.0
933
939
  if self.debug:
934
940
  if (maxval - baseline) < self.lthreshval * baselinedev:
935
941
  print(
@@ -6,17 +6,23 @@ sigterm = true
6
6
  source = .
7
7
  omit =
8
8
  __init__.py
9
- ../__init__.py
10
- ../scripts/__init__.py
11
- ../OrthoImageItem.py
12
- ../wiener2.py
13
- ../tidepoolTemplate.py
14
- ../tidepoolTemplate_qt6.py
15
- ../tidepoolTemplate_alt.py
16
- ../tidepoolTemplate_alt_qt6.py
17
- ../tidepoolTemplate_big.py
18
- ../tidepoolTemplate_big_qt6.py
19
- ../notreadyforprimetime/*
9
+ scripts/__init__.py
10
+ OrthoImageItem.py
11
+ wiener2.py
12
+ fMRIData_class.py
13
+ tidepoolTemplate.py
14
+ tidepoolTemplate_qt6.py
15
+ tidepoolTemplate_alt.py
16
+ tidepoolTemplate_alt_qt6.py
17
+ tidepoolTemplate_big.py
18
+ tidepoolTemplate_big_qt6.py
19
+ */tidepool.py
20
+ */delayvar.py
21
+ */variabilityizer.py
22
+ */synthASL.py
23
+ */proj2flow.py
24
+ */adjustoffset.py
25
+ notreadyforprimetime/*
20
26
 
21
27
  [report]
22
28
  exclude_lines =
@@ -26,7 +26,7 @@ import numpy as np
26
26
  import rapidtide.fit as tide_fit
27
27
  import rapidtide.io as tide_io
28
28
  import rapidtide.simFuncClasses as tide_simFuncClasses
29
- from rapidtide.tests.utils import get_examples_path
29
+ from rapidtide.tests.utils import get_examples_path, get_test_temp_path
30
30
 
31
31
 
32
32
  def dumplists(results, targets, failflags):
@@ -39,7 +39,12 @@ def dumplists(results, targets, failflags):
39
39
  print(results[i], targets[i], failflags[i])
40
40
 
41
41
 
42
- def eval_fml_result(absmin, absmax, testvalues, foundvalues, failflags, tolerance=0.0001):
42
+ def eval_fml_result(absmin, absmax, testvalues, foundvalues, failflags, tolerance=0.0001, debug=False):
43
+ if debug:
44
+ print(f"{absmin=}, {absmax=}, {tolerance=}")
45
+ print(f"{testvalues=}")
46
+ print(f"{foundvalues=}")
47
+ print(f"{failflags=}")
43
48
  for i in range(len(testvalues)):
44
49
  if testvalues[i] < absmin:
45
50
  if foundvalues[i] != absmin:
@@ -61,12 +66,22 @@ def eval_fml_result(absmin, absmax, testvalues, foundvalues, failflags, toleranc
61
66
  return True
62
67
 
63
68
 
64
- def test_findmaxlag(displayplots=False, debug=False):
69
+ def test_findmaxlag(displayplots=False, local=False, debug=False):
70
+ # set input and output directories
71
+ if local:
72
+ exampleroot = "../data/examples/src"
73
+ testtemproot = "./tmp"
74
+ else:
75
+ exampleroot = get_examples_path()
76
+ testtemproot = get_test_temp_path()
77
+
78
+ if debug:
79
+ print("debug flag is set")
65
80
  # for fittype in ["gauss", "quad", "fastquad", "COM", "None", "fastgauss", "gausscf"]:
66
81
  for fittype in ["gauss"]:
67
82
  print("*************************************")
68
83
  print(f"testing fittype: {fittype}")
69
- textfilename = op.join(get_examples_path(), "lt_rt.txt")
84
+ textfilename = op.join(exampleroot, "lt_rt.txt")
70
85
 
71
86
  # set default variable values
72
87
  searchfrac = 0.75
@@ -172,16 +187,16 @@ def test_findmaxlag(displayplots=False, debug=False):
172
187
  for i in range(len(testlags)):
173
188
  print(testlags[i], fml_maxlags[i], fml_lfailreasons[i])
174
189
 
175
- assert eval_fml_result(lagmin, lagmax, testlags, fml_maxlags, fml_lfailreasons)
176
- assert eval_fml_result(absminval, absmaxval, testvals, fml_maxvals, fml_lfailreasons)
190
+ assert eval_fml_result(lagmin, lagmax, testlags, fml_maxlags, fml_lfailreasons, debug=debug)
191
+ assert eval_fml_result(absminval, absmaxval, testvals, fml_maxvals, fml_lfailreasons, debug=debug)
177
192
  assert eval_fml_result(
178
- absminsigma, absmaxsigma, testsigmas, fml_maxsigmas, fml_lfailreasons
193
+ absminsigma, absmaxsigma, testsigmas, fml_maxsigmas, fml_lfailreasons, debug=debug
179
194
  )
180
195
 
181
- assert eval_fml_result(lagmin, lagmax, testlags, fmlc_maxlags, fmlc_lfailreasons)
182
- assert eval_fml_result(absminval, absmaxval, testvals, fmlc_maxvals, fmlc_lfailreasons)
196
+ assert eval_fml_result(lagmin, lagmax, testlags, fmlc_maxlags, fmlc_lfailreasons, debug=debug)
197
+ assert eval_fml_result(absminval, absmaxval, testvals, fmlc_maxvals, fmlc_lfailreasons, debug=debug)
183
198
  assert eval_fml_result(
184
- absminsigma, absmaxsigma, testsigmas, fmlc_maxsigmas, fmlc_lfailreasons
199
+ absminsigma, absmaxsigma, testsigmas, fmlc_maxsigmas, fmlc_lfailreasons, debug=debug
185
200
  )
186
201
 
187
202
  if displayplots:
@@ -315,19 +330,19 @@ def test_findmaxlag(displayplots=False, debug=False):
315
330
  ax.legend(["findmaxlag_gauss", "classes"])
316
331
  plt.show()
317
332
 
318
- assert eval_fml_result(lagmin, lagmax, testlags, fml_maxlags, fml_wfailreasons)
333
+ assert eval_fml_result(lagmin, lagmax, testlags, fml_maxlags, fml_wfailreasons, debug=debug)
319
334
  # assert eval_fml_result(absminval, absmaxval, testvals, fml_maxvals, fml_wfailreasons)
320
335
  assert eval_fml_result(
321
- absminsigma, absmaxsigma, testsigmas, fml_maxsigmas, fml_wfailreasons
336
+ absminsigma, absmaxsigma, testsigmas, fml_maxsigmas, fml_wfailreasons, debug=debug
322
337
  )
323
338
 
324
- assert eval_fml_result(lagmin, lagmax, testlags, fmlc_maxlags, fmlc_wfailreasons)
325
- assert eval_fml_result(absminval, absmaxval, testvals, fmlc_maxvals, fmlc_wfailreasons)
339
+ assert eval_fml_result(lagmin, lagmax, testlags, fmlc_maxlags, fmlc_wfailreasons, debug=debug)
340
+ assert eval_fml_result(absminval, absmaxval, testvals, fmlc_maxvals, fmlc_wfailreasons, debug=debug)
326
341
  assert eval_fml_result(
327
- absminsigma, absmaxsigma, testsigmas, fmlc_maxsigmas, fmlc_wfailreasons
342
+ absminsigma, absmaxsigma, testsigmas, fmlc_maxsigmas, fmlc_wfailreasons, debug=debug
328
343
  )
329
344
 
330
345
 
331
346
  if __name__ == "__main__":
332
347
  mpl.use("TkAgg")
333
- test_findmaxlag(displayplots=True, debug=True)
348
+ test_findmaxlag(displayplots=True, local=True, debug=True)
@@ -63,6 +63,23 @@ def maketestwaves(timeaxis):
63
63
  "waveform": 1.0 * scratch,
64
64
  }
65
65
  )
66
+
67
+ scratch = np.exp(-timeaxis / timeaxis[2])
68
+ testwaves.append(
69
+ {
70
+ "name": "damped exponential regressor",
71
+ "timeaxis": 1.0 * timeaxis,
72
+ "waveform": 1.0 * scratch,
73
+ }
74
+ )
75
+
76
+ testwaves.append(
77
+ {
78
+ "name": "white noise plus exponential",
79
+ "timeaxis": 1.0 * timeaxis,
80
+ "waveform": 0.3 * np.random.normal(size=tclen) + scratch,
81
+ }
82
+ )
66
83
  return testwaves
67
84
 
68
85
 
@@ -89,7 +106,7 @@ def eval_padvecprops(
89
106
  nperseg = np.min([tclen, 2048])
90
107
  f, dummy = sp.signal.welch(overall, fs=1.0 / sampletime, nperseg=nperseg)
91
108
 
92
- padtypelist = ["reflect", "zero", "constant", "constant+"]
109
+ padtypelist = ["reflect", "zero", "cyclic", "constant", "constant+"]
93
110
  transferfunclist = ["brickwall", "trapezoidal", "butterworth"]
94
111
 
95
112
  # construct some test waveforms for end effects
@@ -184,6 +201,7 @@ def eval_padvecprops(
184
201
  legend.append(thewave["name"] + ": " + thefilter["name"])
185
202
  offset += 1.25
186
203
  plt.legend(legend)
204
+ plt.title(padtype)
187
205
  plt.show()
188
206
 
189
207
 
@@ -0,0 +1,124 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ #
4
+ # Copyright 2016-2025 Blaise Frederick
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+ #
19
+ import os
20
+
21
+ import matplotlib as mpl
22
+
23
+ import rapidtide.io as tide_io
24
+ import rapidtide.workflows.parser_funcs as pf
25
+ import rapidtide.workflows.rapidtide as rapidtide_workflow
26
+ import rapidtide.workflows.rapidtide_parser as rapidtide_parser
27
+ import rapidtide.workflows.simdata as rapidtide_simdata
28
+ from rapidtide.tests.utils import get_examples_path, get_test_temp_path
29
+
30
+
31
+ def test_simroundtrip(debug=False, local=False, displayplots=False):
32
+ # set input and output directories
33
+ if local:
34
+ exampleroot = "../data/examples/src"
35
+ testtemproot = "./tmp"
36
+ else:
37
+ exampleroot = get_examples_path()
38
+ testtemproot = get_test_temp_path()
39
+
40
+
41
+ # run initial rapidtide
42
+ inputargs = [
43
+ os.path.join(exampleroot, "sub-RAPIDTIDETEST.nii.gz"),
44
+ os.path.join(testtemproot, "sub-RAPIDTIDETESTSIM"),
45
+ "--spatialfilt",
46
+ "2",
47
+ "--simcalcrange",
48
+ "4",
49
+ "-1",
50
+ "--nprocs",
51
+ "-1",
52
+ "--passes",
53
+ "2",
54
+ "--despecklepasses",
55
+ "3",
56
+ "--delaypatchthresh",
57
+ "4.0",
58
+ ]
59
+ rapidtide_workflow.rapidtide_main(rapidtide_parser.process_args(inputargs=inputargs))
60
+
61
+ # now simulate data from maps
62
+ print(testtemproot)
63
+ inputargs = [
64
+ "1.5",
65
+ "260",
66
+ os.path.join( testtemproot, "sub-RAPIDTIDETESTSIM_desc-unfiltmean_map.nii.gz"),
67
+ os.path.join( testtemproot, "simulatedfmri_vn05"),
68
+ "--lfopctfile",
69
+ os.path.join( testtemproot, "sub-RAPIDTIDETESTSIM_desc-maxcorr_map.nii.gz"),
70
+ "--lfolagfile",
71
+ os.path.join( testtemproot, "sub-RAPIDTIDETESTSIM_desc-maxtimerefined_map.nii.gz"),
72
+ "--lforegressor",
73
+ os.path.join(testtemproot, "sub-RAPIDTIDETESTSIM_desc-movingregressor_timeseries.json:pass2"),
74
+ "--voxelnoiselevel",
75
+ "5.0"
76
+ ]
77
+
78
+ pf.generic_init(rapidtide_simdata._get_parser, rapidtide_simdata.simdata, inputargs=inputargs)
79
+
80
+ # run repeat rapidtide
81
+ inputargs = [
82
+ os.path.join(testtemproot, "simulatedfmri_vn05.nii.gz"),
83
+ os.path.join(testtemproot, "sub-RAPIDTIDETESTSIMRERUN"),
84
+ "--spatialfilt",
85
+ "2",
86
+ "--simcalcrange",
87
+ "4",
88
+ "-1",
89
+ "--nprocs",
90
+ "-1",
91
+ "--passes",
92
+ "2",
93
+ "--despecklepasses",
94
+ "3",
95
+ "--delaypatchthresh",
96
+ "4.0",
97
+ ]
98
+ rapidtide_workflow.rapidtide_main(rapidtide_parser.process_args(inputargs=inputargs))
99
+
100
+ absthresh = 1e-10
101
+ msethresh = 1e-12
102
+ spacetolerance = 1e-3
103
+ """for map in [
104
+ "maxtime",
105
+ "maxtimerefined",
106
+ "lfofilterCoeff",
107
+ ]:
108
+ print(f"Testing map={map}")
109
+ filename1 = os.path.join(testtemproot, f"sub-RAPIDTIDETESTSIM_desc-{map}_map.nii.gz")
110
+ filename2 = os.path.join(testtemproot, f"sub-RAPIDTIDETESTSIMRERUN_desc-{map}_map.nii.gz")
111
+ assert tide_io.checkniftifilematch(
112
+ filename1,
113
+ filename2,
114
+ absthresh=absthresh,
115
+ msethresh=msethresh,
116
+ spacetolerance=spacetolerance,
117
+ debug=debug,
118
+ )"""
119
+
120
+
121
+
122
+ if __name__ == "__main__":
123
+ mpl.use("TkAgg")
124
+ test_simroundtrip(debug=True, local=True, displayplots=True)