rapidtide 3.0.11__py3-none-any.whl → 3.1.1__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 (144) hide show
  1. rapidtide/Colortables.py +492 -27
  2. rapidtide/OrthoImageItem.py +1049 -46
  3. rapidtide/RapidtideDataset.py +1533 -86
  4. rapidtide/_version.py +3 -3
  5. rapidtide/calccoherence.py +196 -29
  6. rapidtide/calcnullsimfunc.py +188 -40
  7. rapidtide/calcsimfunc.py +242 -42
  8. rapidtide/correlate.py +1203 -383
  9. rapidtide/data/examples/src/testLD +56 -0
  10. rapidtide/data/examples/src/testalign +1 -1
  11. rapidtide/data/examples/src/testdelayvar +0 -1
  12. rapidtide/data/examples/src/testfmri +53 -3
  13. rapidtide/data/examples/src/testglmfilt +5 -5
  14. rapidtide/data/examples/src/testhappy +29 -7
  15. rapidtide/data/examples/src/testppgproc +17 -0
  16. rapidtide/data/examples/src/testrolloff +11 -0
  17. rapidtide/data/models/model_cnn_pytorch/best_model.pth +0 -0
  18. rapidtide/data/models/model_cnn_pytorch/loss.png +0 -0
  19. rapidtide/data/models/model_cnn_pytorch/loss.txt +1 -0
  20. rapidtide/data/models/model_cnn_pytorch/model.pth +0 -0
  21. rapidtide/data/models/model_cnn_pytorch/model_meta.json +68 -0
  22. rapidtide/decorators.py +91 -0
  23. rapidtide/dlfilter.py +2226 -110
  24. rapidtide/dlfiltertorch.py +4842 -0
  25. rapidtide/externaltools.py +327 -12
  26. rapidtide/fMRIData_class.py +79 -40
  27. rapidtide/filter.py +1899 -810
  28. rapidtide/fit.py +2011 -581
  29. rapidtide/genericmultiproc.py +93 -18
  30. rapidtide/happy_supportfuncs.py +2047 -172
  31. rapidtide/helper_classes.py +584 -43
  32. rapidtide/io.py +2370 -372
  33. rapidtide/linfitfiltpass.py +346 -99
  34. rapidtide/makelaggedtcs.py +210 -24
  35. rapidtide/maskutil.py +448 -62
  36. rapidtide/miscmath.py +827 -121
  37. rapidtide/multiproc.py +210 -22
  38. rapidtide/patchmatch.py +242 -42
  39. rapidtide/peakeval.py +31 -31
  40. rapidtide/ppgproc.py +2203 -0
  41. rapidtide/qualitycheck.py +352 -39
  42. rapidtide/refinedelay.py +431 -57
  43. rapidtide/refineregressor.py +494 -189
  44. rapidtide/resample.py +671 -185
  45. rapidtide/scripts/applyppgproc.py +28 -0
  46. rapidtide/scripts/showxcorr_legacy.py +7 -7
  47. rapidtide/scripts/stupidramtricks.py +15 -17
  48. rapidtide/simFuncClasses.py +1052 -77
  49. rapidtide/simfuncfit.py +269 -69
  50. rapidtide/stats.py +540 -238
  51. rapidtide/tests/happycomp +9 -0
  52. rapidtide/tests/test_cleanregressor.py +1 -2
  53. rapidtide/tests/test_dlfiltertorch.py +627 -0
  54. rapidtide/tests/test_findmaxlag.py +24 -8
  55. rapidtide/tests/test_fullrunhappy_v1.py +0 -2
  56. rapidtide/tests/test_fullrunhappy_v2.py +0 -2
  57. rapidtide/tests/test_fullrunhappy_v3.py +11 -4
  58. rapidtide/tests/test_fullrunhappy_v4.py +10 -2
  59. rapidtide/tests/test_fullrunrapidtide_v7.py +1 -1
  60. rapidtide/tests/test_getparsers.py +11 -3
  61. rapidtide/tests/test_refinedelay.py +0 -1
  62. rapidtide/tests/test_simroundtrip.py +16 -8
  63. rapidtide/tests/test_stcorrelate.py +3 -1
  64. rapidtide/tests/utils.py +9 -8
  65. rapidtide/tidepoolTemplate.py +142 -38
  66. rapidtide/tidepoolTemplate_alt.py +165 -44
  67. rapidtide/tidepoolTemplate_big.py +189 -52
  68. rapidtide/util.py +1217 -118
  69. rapidtide/voxelData.py +684 -37
  70. rapidtide/wiener.py +136 -23
  71. rapidtide/wiener2.py +113 -7
  72. rapidtide/workflows/adjustoffset.py +105 -3
  73. rapidtide/workflows/aligntcs.py +85 -2
  74. rapidtide/workflows/applydlfilter.py +87 -10
  75. rapidtide/workflows/applyppgproc.py +540 -0
  76. rapidtide/workflows/atlasaverage.py +210 -47
  77. rapidtide/workflows/atlastool.py +100 -3
  78. rapidtide/workflows/calcSimFuncMap.py +288 -69
  79. rapidtide/workflows/calctexticc.py +201 -9
  80. rapidtide/workflows/ccorrica.py +101 -6
  81. rapidtide/workflows/cleanregressor.py +165 -31
  82. rapidtide/workflows/delayvar.py +171 -23
  83. rapidtide/workflows/diffrois.py +81 -3
  84. rapidtide/workflows/endtidalproc.py +144 -4
  85. rapidtide/workflows/fdica.py +195 -15
  86. rapidtide/workflows/filtnifti.py +70 -3
  87. rapidtide/workflows/filttc.py +74 -3
  88. rapidtide/workflows/fitSimFuncMap.py +202 -51
  89. rapidtide/workflows/fixtr.py +73 -3
  90. rapidtide/workflows/gmscalc.py +113 -3
  91. rapidtide/workflows/happy.py +801 -199
  92. rapidtide/workflows/happy2std.py +144 -12
  93. rapidtide/workflows/happy_parser.py +163 -23
  94. rapidtide/workflows/histnifti.py +118 -2
  95. rapidtide/workflows/histtc.py +84 -3
  96. rapidtide/workflows/linfitfilt.py +117 -4
  97. rapidtide/workflows/localflow.py +328 -28
  98. rapidtide/workflows/mergequality.py +79 -3
  99. rapidtide/workflows/niftidecomp.py +322 -18
  100. rapidtide/workflows/niftistats.py +174 -4
  101. rapidtide/workflows/pairproc.py +98 -4
  102. rapidtide/workflows/pairwisemergenifti.py +85 -2
  103. rapidtide/workflows/parser_funcs.py +1421 -40
  104. rapidtide/workflows/physiofreq.py +137 -11
  105. rapidtide/workflows/pixelcomp.py +207 -5
  106. rapidtide/workflows/plethquality.py +103 -21
  107. rapidtide/workflows/polyfitim.py +151 -11
  108. rapidtide/workflows/proj2flow.py +75 -2
  109. rapidtide/workflows/rankimage.py +111 -4
  110. rapidtide/workflows/rapidtide.py +368 -76
  111. rapidtide/workflows/rapidtide2std.py +98 -2
  112. rapidtide/workflows/rapidtide_parser.py +109 -9
  113. rapidtide/workflows/refineDelayMap.py +144 -33
  114. rapidtide/workflows/refineRegressor.py +675 -96
  115. rapidtide/workflows/regressfrommaps.py +161 -37
  116. rapidtide/workflows/resamplenifti.py +85 -3
  117. rapidtide/workflows/resampletc.py +91 -3
  118. rapidtide/workflows/retrolagtcs.py +99 -9
  119. rapidtide/workflows/retroregress.py +176 -26
  120. rapidtide/workflows/roisummarize.py +174 -5
  121. rapidtide/workflows/runqualitycheck.py +71 -3
  122. rapidtide/workflows/showarbcorr.py +149 -6
  123. rapidtide/workflows/showhist.py +86 -2
  124. rapidtide/workflows/showstxcorr.py +160 -3
  125. rapidtide/workflows/showtc.py +159 -3
  126. rapidtide/workflows/showxcorrx.py +190 -10
  127. rapidtide/workflows/showxy.py +185 -15
  128. rapidtide/workflows/simdata.py +264 -38
  129. rapidtide/workflows/spatialfit.py +77 -2
  130. rapidtide/workflows/spatialmi.py +250 -27
  131. rapidtide/workflows/spectrogram.py +305 -32
  132. rapidtide/workflows/synthASL.py +154 -3
  133. rapidtide/workflows/tcfrom2col.py +76 -2
  134. rapidtide/workflows/tcfrom3col.py +74 -2
  135. rapidtide/workflows/tidepool.py +2971 -130
  136. rapidtide/workflows/utils.py +19 -14
  137. rapidtide/workflows/utils_doc.py +293 -0
  138. rapidtide/workflows/variabilityizer.py +116 -3
  139. {rapidtide-3.0.11.dist-info → rapidtide-3.1.1.dist-info}/METADATA +10 -8
  140. {rapidtide-3.0.11.dist-info → rapidtide-3.1.1.dist-info}/RECORD +144 -128
  141. {rapidtide-3.0.11.dist-info → rapidtide-3.1.1.dist-info}/entry_points.txt +1 -0
  142. {rapidtide-3.0.11.dist-info → rapidtide-3.1.1.dist-info}/WHEEL +0 -0
  143. {rapidtide-3.0.11.dist-info → rapidtide-3.1.1.dist-info}/licenses/LICENSE +0 -0
  144. {rapidtide-3.0.11.dist-info → rapidtide-3.1.1.dist-info}/top_level.txt +0 -0
@@ -21,9 +21,12 @@ import warnings
21
21
  warnings.simplefilter(action="ignore", category=FutureWarning)
22
22
  import argparse
23
23
  import sys
24
+ from argparse import Namespace
25
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
24
26
 
25
27
  import nibabel as nib
26
28
  import numpy as np
29
+ from numpy.typing import NDArray
27
30
  from scipy.stats import pearsonr
28
31
 
29
32
  import rapidtide.correlate as tide_corr
@@ -38,9 +41,29 @@ DEFAULT_DETREND_ORDER = 3
38
41
  DEFAULT_CORRWEIGHTING = "phat"
39
42
 
40
43
 
41
- def _get_parser():
44
+ def _get_parser() -> Any:
42
45
  """
43
- Argument parser for ccorrica
46
+ Argument parser for ccorrica.
47
+
48
+ This function constructs and returns an `argparse.ArgumentParser` object configured
49
+ with all required and optional arguments for the `ccorrica` tool, which computes
50
+ temporal cross-correlations between timecourses.
51
+
52
+ Returns
53
+ -------
54
+ argparse.ArgumentParser
55
+ Configured argument parser for the ccorrica tool.
56
+
57
+ Notes
58
+ -----
59
+ The parser includes support for specifying sample rate or timestep, windowing options,
60
+ search range parameters, filtering, correlation weighting methods, detrending, and
61
+ oversampling factors. It also supports debugging output.
62
+
63
+ Examples
64
+ --------
65
+ >>> parser = _get_parser()
66
+ >>> args = parser.parse_args(['--timecoursefile', 'data.txt', '--outputroot', 'out'])
44
67
  """
45
68
  parser = argparse.ArgumentParser(
46
69
  prog="ccorrica",
@@ -134,7 +157,77 @@ def _get_parser():
134
157
  return parser
135
158
 
136
159
 
137
- def ccorrica(args):
160
+ def ccorrica(args: Any) -> None:
161
+ """
162
+ Compute cross-correlations between time series components and save results in NIfTI and text formats.
163
+
164
+ This function reads time course data from a text file, applies preprocessing including
165
+ filtering, resampling, detrending, and windowing, then computes cross-correlations
166
+ between all pairs of components. The results are saved as NIfTI files and text vectors
167
+ for further analysis.
168
+
169
+ Parameters
170
+ ----------
171
+ args : argparse.Namespace
172
+ Command-line arguments containing configuration options such as:
173
+ - timecoursefile : str
174
+ Path to the input time course file.
175
+ - samplerate : float or str
176
+ Sampling rate of the data. If "auto", it must be specified in the file header.
177
+ - oversampfactor : int
178
+ Oversampling factor for upsampling the data. If less than 0, it is auto-computed.
179
+ - detrendorder : int
180
+ Order of detrending to apply.
181
+ - windowfunc : str
182
+ Windowing function to apply.
183
+ - corrweighting : str
184
+ Type of weighting to use in correlation computation.
185
+ - debug : bool
186
+ If True, display plots during correlation computation.
187
+ - outputroot : str
188
+ Root name for output files.
189
+
190
+ Returns
191
+ -------
192
+ None
193
+ This function does not return a value but saves multiple output files:
194
+ - `_filtereddata.txt`: Filtered time series.
195
+ - `_xcorr.nii.gz`: Cross-correlation data as 4D NIfTI.
196
+ - `_pxcorr.nii.gz`: Pearson correlation coefficients.
197
+ - `_corrmax.nii.gz`: Maximum correlation values.
198
+ - `_corrlag.nii.gz`: Lag at maximum correlation.
199
+ - `_corrwidth.nii.gz`: Width of the correlation peak.
200
+ - `_corrmask.nii.gz`: Mask indicating correlation significance.
201
+ - `_reformdata.txt`: Final reformatted and normalized data.
202
+
203
+ Notes
204
+ -----
205
+ The function performs the following steps:
206
+ 1. Reads input data from a text file.
207
+ 2. Applies post-processing filter options.
208
+ 3. Resamples data if necessary.
209
+ 4. Filters data using a specified prefilter.
210
+ 5. Normalizes data using standard and correlation normalization.
211
+ 6. Computes cross-correlations using fast FFT-based methods.
212
+ 7. Fits Gaussian peaks to find maximum correlation lag and width.
213
+ 8. Saves symmetric matrices for correlation maxima, lags, widths, and masks.
214
+ 9. Outputs results in both NIfTI and text formats.
215
+
216
+ Examples
217
+ --------
218
+ >>> import argparse
219
+ >>> args = argparse.Namespace(
220
+ ... timecoursefile='data.txt',
221
+ ... samplerate=2.0,
222
+ ... oversampfactor=1,
223
+ ... detrendorder=1,
224
+ ... windowfunc='hanning',
225
+ ... corrweighting='none',
226
+ ... debug=False,
227
+ ... outputroot='output'
228
+ ... )
229
+ >>> ccorrica(args)
230
+ """
138
231
  args, theprefilter = pf.postprocessfilteropts(args)
139
232
 
140
233
  # read in data
@@ -172,7 +265,7 @@ def ccorrica(args):
172
265
  if args.oversampfactor == 1:
173
266
  print("data array shape is ", reformdata.shape)
174
267
  else:
175
- resampdata = np.zeros((numcomponents, tclen * args.oversampfactor), dtype=np.float)
268
+ resampdata = np.zeros((numcomponents, tclen * args.oversampfactor), dtype=float)
176
269
  for component in range(0, numcomponents):
177
270
  resampdata[component, :] = tide_resample.upsample(
178
271
  reformdata[component, :], Fs, Fs * args.oversampfactor, intfac=True
@@ -227,9 +320,11 @@ def ccorrica(args):
227
320
  zeropadding=0,
228
321
  displayplots=args.debug,
229
322
  )
230
- thepxcorr = pearsonr(reformdata[component1, :] / tclen, reformdata[component2, :])
323
+ thepxcorr = pearsonr(
324
+ reformdata[component1, :] / tclen, reformdata[component2, :]
325
+ ).statistic
231
326
  outputdata[component1, component2, 0, :] = thexcorr
232
- outputpdata[component1, component2, 0, :] = thepxcorr[0]
327
+ outputpdata[component1, component2, 0, :] = thepxcorr
233
328
  (
234
329
  maxindex,
235
330
  maxlag,
@@ -16,7 +16,10 @@
16
16
  # limitations under the License.
17
17
  #
18
18
  #
19
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
20
+
19
21
  import numpy as np
22
+ from numpy.typing import NDArray
20
23
 
21
24
  import rapidtide.correlate as tide_corr
22
25
  import rapidtide.filter as tide_filt
@@ -27,35 +30,168 @@ import rapidtide.simfuncfit as tide_simfuncfit
27
30
 
28
31
 
29
32
  def cleanregressor(
30
- outputname,
31
- thepass,
32
- referencetc,
33
- resampref_y,
34
- resampnonosref_y,
35
- fmrifreq,
36
- oversampfreq,
37
- osvalidsimcalcstart,
38
- osvalidsimcalcend,
39
- lagmininpts,
40
- lagmaxinpts,
41
- theFitter,
42
- theCorrelator,
43
- lagmin,
44
- lagmax,
45
- LGR=None,
46
- check_autocorrelation=True,
47
- fix_autocorrelation=True,
48
- despeckle_thresh=5.0,
49
- lthreshval=0.0,
50
- fixdelay=False,
51
- detrendorder=3,
52
- windowfunc="hamming",
53
- respdelete=False,
54
- displayplots=False,
55
- debug=False,
56
- rt_floattype="float64",
57
- rt_floatset=np.float64,
58
- ):
33
+ outputname: Any,
34
+ thepass: Any,
35
+ referencetc: Any,
36
+ resampref_y: Any,
37
+ resampnonosref_y: Any,
38
+ fmrifreq: Any,
39
+ oversampfreq: Any,
40
+ osvalidsimcalcstart: Any,
41
+ osvalidsimcalcend: Any,
42
+ lagmininpts: Any,
43
+ lagmaxinpts: Any,
44
+ theFitter: Any,
45
+ theCorrelator: Any,
46
+ lagmin: Any,
47
+ lagmax: Any,
48
+ LGR: Optional[Any] = None,
49
+ check_autocorrelation: bool = True,
50
+ fix_autocorrelation: bool = True,
51
+ despeckle_thresh: float = 5.0,
52
+ lthreshval: float = 0.0,
53
+ fixdelay: bool = False,
54
+ detrendorder: int = 3,
55
+ windowfunc: str = "hamming",
56
+ respdelete: bool = False,
57
+ displayplots: bool = False,
58
+ debug: bool = False,
59
+ rt_floattype: np.dtype = np.float64,
60
+ ) -> Tuple[
61
+ NDArray,
62
+ NDArray,
63
+ NDArray,
64
+ float,
65
+ float | None,
66
+ float | None,
67
+ float,
68
+ float | None,
69
+ float | None,
70
+ ]:
71
+ """
72
+ Clean and preprocess a regressor signal by checking and correcting autocorrelation properties.
73
+
74
+ This function performs several operations on the input regressor signal, including:
75
+ detrending, normalization, optional filtering to remove periodic components, and
76
+ autocorrelation analysis to detect and correct sidelobes. It returns cleaned versions
77
+ of the regressor and associated metadata for further use in time series analysis.
78
+
79
+ Parameters
80
+ ----------
81
+ outputname : Any
82
+ Base name for output files.
83
+ thepass : Any
84
+ Pass identifier, used for labeling output files.
85
+ referencetc : Any
86
+ Reference time course data (normalized).
87
+ resampref_y : Any
88
+ Resampled reference signal.
89
+ resampnonosref_y : Any
90
+ Non-oversampled reference signal.
91
+ fmrifreq : Any
92
+ fMRI sampling frequency.
93
+ oversampfreq : Any
94
+ Oversampled frequency.
95
+ osvalidsimcalcstart : Any
96
+ Start index for valid data in oversampled signal.
97
+ osvalidsimcalcend : Any
98
+ End index for valid data in oversampled signal.
99
+ lagmininpts : Any
100
+ Minimum lag in samples for autocorrelation calculation.
101
+ lagmaxinpts : Any
102
+ Maximum lag in samples for autocorrelation calculation.
103
+ theFitter : Any
104
+ Fitter object for fitting autocorrelation data.
105
+ theCorrelator : Any
106
+ Correlator object for computing cross-correlations.
107
+ lagmin : Any
108
+ Minimum lag in seconds.
109
+ lagmax : Any
110
+ Maximum lag in seconds.
111
+ LGR : Optional[Any], optional
112
+ Logger object for logging messages. Default is None.
113
+ check_autocorrelation : bool, optional
114
+ If True, perform autocorrelation checks. Default is True.
115
+ fix_autocorrelation : bool, optional
116
+ If True, attempt to fix detected autocorrelation issues. Default is True.
117
+ despeckle_thresh : float, optional
118
+ Threshold for despeckling autocorrelation data. Default is 5.0.
119
+ lthreshval : float, optional
120
+ Low threshold value for fitting. Default is 0.0.
121
+ fixdelay : bool, optional
122
+ If True, fix delay in fitting. Default is False.
123
+ detrendorder : int, optional
124
+ Order of detrending polynomial. Default is 3.
125
+ windowfunc : str, optional
126
+ Window function to use for normalization. Default is "hamming".
127
+ respdelete : bool, optional
128
+ If True, remove periodic components from the reference signal. Default is False.
129
+ displayplots : bool, optional
130
+ If True, display plots during processing. Default is False.
131
+ debug : bool, optional
132
+ If True, print debugging information. Default is False.
133
+ rt_floattype : np.dtype, optional
134
+ Float type setting for rapidtide processing. Default is np.float64.
135
+
136
+ Returns
137
+ -------
138
+ tuple
139
+ A tuple containing:
140
+ - cleaned_resampref_y : NDArray
141
+ Cleaned resampled reference signal.
142
+ - cleaned_referencetc : NDArray
143
+ Cleaned reference time course.
144
+ - cleaned_nonosreferencetc : NDArray
145
+ Cleaned non-oversampled reference signal.
146
+ - despeckle_thresh : float
147
+ Updated despeckle threshold.
148
+ - sidelobeamp : float or None
149
+ Amplitude of detected sidelobe, or None if not found.
150
+ - sidelobetime : float or None
151
+ Time of detected sidelobe in seconds, or None if not found.
152
+ - lagmod : float
153
+ Lag modulus value used for correction.
154
+ - acwidth : float or None
155
+ Width of autocorrelation function, or None if not computed.
156
+ - absmaxsigma : float or None
157
+ Absolute maximum sigma value, or None if not computed.
158
+
159
+ Notes
160
+ -----
161
+ - If `respdelete` is True, the function applies frequency tracking and filtering to remove
162
+ periodic components from the reference signal.
163
+ - Autocorrelation analysis is performed using `tide_corr.check_autocorrelation` to detect
164
+ sidelobes that may affect the regressor quality.
165
+ - If `fix_autocorrelation` is True, detected sidelobes are corrected by applying a notch filter
166
+ and adjusting the lag modulus.
167
+
168
+ Examples
169
+ --------
170
+ >>> cleanregressor(
171
+ ... outputname="test_output",
172
+ ... thepass=1,
173
+ ... referencetc=ref_tc,
174
+ ... resampref_y=resamp_ref,
175
+ ... resampnonosref_y=resamp_nonos_ref,
176
+ ... fmrifreq=2.0,
177
+ ... oversampfreq=10.0,
178
+ ... osvalidsimcalcstart=0,
179
+ ... osvalidsimcalcend=100,
180
+ ... lagmininpts=5,
181
+ ... lagmaxinpts=20,
182
+ ... theFitter=fitter,
183
+ ... theCorrelator=correlator,
184
+ ... lagmin=-10,
185
+ ... lagmax=10,
186
+ ... check_autocorrelation=True,
187
+ ... fix_autocorrelation=True,
188
+ ... detrendorder=3,
189
+ ... windowfunc="hamming",
190
+ ... respdelete=False,
191
+ ... displayplots=False,
192
+ ... debug=False,
193
+ ... )
194
+ """
59
195
  # print debugging info
60
196
  if debug:
61
197
  print("cleanregressor:")
@@ -75,7 +211,6 @@ def cleanregressor(
75
211
  print(f"\t{check_autocorrelation=}")
76
212
  print(f"\t{displayplots=}")
77
213
  print(f"\t{rt_floattype=}")
78
- print(f"\t{rt_floatset=}")
79
214
 
80
215
  # check the regressor for periodic components in the passband
81
216
  dolagmod = True
@@ -123,7 +258,6 @@ def cleanregressor(
123
258
  despeckle_thresh=despeckle_thresh,
124
259
  lthreshval=lthreshval,
125
260
  fixdelay=fixdelay,
126
- rt_floatset=rt_floatset,
127
261
  rt_floattype=rt_floattype,
128
262
  )
129
263
  tide_io.writebidstsv(
@@ -22,12 +22,14 @@ import logging
22
22
  import os
23
23
  import sys
24
24
  import time
25
+ from argparse import Namespace
25
26
  from pathlib import Path
27
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
26
28
 
27
29
  import numpy as np
30
+ from numpy.typing import NDArray
28
31
  from scipy.stats import pearsonr
29
32
  from sklearn.decomposition import PCA
30
- from tf_keras.src.dtensor.integration_test_utils import train_step
31
33
 
32
34
  import rapidtide.filter as tide_filt
33
35
  import rapidtide.io as tide_io
@@ -63,14 +65,34 @@ DEFAULT_DELAYOFFSETSPATIALFILT = -1
63
65
  DEFAULT_WINDOWSIZE = 30.0
64
66
  DEFAULT_SYSTEMICFITTYPE = "pca"
65
67
  DEFAULT_PCACOMPONENTS = 1
66
- DEFAULT_LAGMIN = 0.0
67
- DEFAULT_LAGMAX = 0.0
68
+ DEFAULT_LAGMIN = -999
69
+ DEFAULT_LAGMAX = -999
68
70
  DEFAULT_TRAINSTEP = 0.5
69
71
 
70
72
 
71
- def _get_parser():
73
+ def _get_parser() -> Any:
72
74
  """
73
- Argument parser for glmfilt
75
+ Argument parser for glmfilt.
76
+
77
+ This function constructs and returns an `argparse.ArgumentParser` object configured
78
+ for parsing command-line arguments used by the `glmfilt` tool. It defines required
79
+ and optional arguments for processing fMRI data, including file paths, filtering
80
+ options, output settings, and experimental parameters.
81
+
82
+ Returns
83
+ -------
84
+ argparse.ArgumentParser
85
+ Configured argument parser for the glmfilt tool.
86
+
87
+ Notes
88
+ -----
89
+ The parser includes both standard and experimental options. Experimental options
90
+ are marked as such and may not be fully tested or stable.
91
+
92
+ Examples
93
+ --------
94
+ >>> parser = _get_parser()
95
+ >>> args = parser.parse_args()
74
96
  """
75
97
  parser = argparse.ArgumentParser(
76
98
  prog="delayvar",
@@ -265,7 +287,102 @@ def _get_parser():
265
287
  return parser
266
288
 
267
289
 
268
- def delayvar(args):
290
+ def delayvar(args: Any) -> None:
291
+ """
292
+ Perform windowed delay variance analysis on fMRI data.
293
+
294
+ This function conducts a comprehensive delay variance analysis on fMRI data,
295
+ computing delay offsets for each voxel across temporal windows. It supports
296
+ various filtering options, PCA-based systemic component removal, and outputs
297
+ detailed timing information and processed maps.
298
+
299
+ Parameters
300
+ ----------
301
+ args : Any
302
+ Namespace object containing all required arguments for the analysis.
303
+ Expected attributes include:
304
+ - fmrifile : str
305
+ Path to the input fMRI NIfTI file.
306
+ - datafileroot : str
307
+ Root name for output files.
308
+ - lag_extrema : tuple of int
309
+ Minimum and maximum lag values for analysis.
310
+ - alternateoutput : str, optional
311
+ Alternate output name.
312
+ - debug : bool
313
+ Enable debug mode.
314
+ - outputlevel : str
315
+ Level of output files to save ('min', 'less', 'normal', 'more', 'max').
316
+ - nprocs : int
317
+ Number of processes to use.
318
+ - hpf : bool
319
+ Apply highpass filtering.
320
+ - windowsize : float
321
+ Size of temporal windows in seconds.
322
+ - windelayoffsetgausssigma : float
323
+ Sigma for Gaussian smoothing of delay offsets.
324
+ - delaypatchthresh : float
325
+ Threshold for patch-based delay correction.
326
+ - systemicfittype : str
327
+ Type of systemic component removal ('pca' or 'mean').
328
+ - pcacomponents : float
329
+ Number of PCA components to use.
330
+ - trainstep : float
331
+ Step size for training the delay model.
332
+ - numskip : int
333
+ Number of initial timepoints to skip.
334
+ - focaldebug : bool
335
+ Enable focal debugging mode.
336
+ - verbose : bool
337
+ Enable verbose output.
338
+ - showprogressbar : bool
339
+ Show progress bar during processing.
340
+
341
+ Returns
342
+ -------
343
+ None
344
+ This function does not return a value but writes multiple output files
345
+ including:
346
+ - Delay offset maps in temporal windows
347
+ - Systemic component timeseries
348
+ - PCA component information
349
+ - Timing and runoptions files
350
+ - Histograms of delay offsets
351
+ - Various intermediate processing results
352
+
353
+ Notes
354
+ -----
355
+ The function performs the following key steps:
356
+ 1. Windowed processing of fMRI data
357
+ 2. Derivative ratio calculation and filtering
358
+ 3. Delay offset training and calculation
359
+ 4. Systemic component removal (PCA or mean)
360
+ 5. Output generation and cleanup
361
+
362
+ Examples
363
+ --------
364
+ >>> import argparse
365
+ >>> args = argparse.Namespace(
366
+ ... fmrifile='data.nii.gz',
367
+ ... datafileroot='output',
368
+ ... lag_extrema=(0, 10),
369
+ ... debug=False,
370
+ ... outputlevel='normal',
371
+ ... nprocs=4,
372
+ ... hpf=True,
373
+ ... windowsize=30.0,
374
+ ... windelayoffsetgausssigma=2.0,
375
+ ... delaypatchthresh=0.5,
376
+ ... systemicfittype='pca',
377
+ ... pcacomponents=0.8,
378
+ ... trainstep=0.1,
379
+ ... numskip=5,
380
+ ... focaldebug=False,
381
+ ... verbose=True,
382
+ ... showprogressbar=True
383
+ ... )
384
+ >>> delayvar(args)
385
+ """
269
386
  # get the pid of the parent process
270
387
  args.pid = os.getpid()
271
388
 
@@ -289,7 +406,7 @@ def delayvar(args):
289
406
  logger_filename=f"{outputname}_retrolog.txt",
290
407
  timing_filename=f"{outputname}_retroruntimings.tsv",
291
408
  error_filename=f"{outputname}_retroerrorlog.txt",
292
- verbose=False,
409
+ isverbose=False,
293
410
  debug=args.debug,
294
411
  )
295
412
  TimingLGR.info("Start")
@@ -365,19 +482,15 @@ def delayvar(args):
365
482
  sys.exit()
366
483
 
367
484
  if therunoptions["internalprecision"] == "double":
368
- rt_floattype = "float64"
369
- rt_floatset = np.float64
485
+ rt_floattype = np.float64
370
486
  else:
371
- rt_floattype = "float32"
372
- rt_floatset = np.float32
487
+ rt_floattype = np.float32
373
488
 
374
489
  # set the output precision
375
490
  if therunoptions["outputprecision"] == "double":
376
- rt_outfloattype = "float64"
377
- rt_outfloatset = np.float64
491
+ rt_outfloattype = np.float64
378
492
  else:
379
- rt_outfloattype = "float32"
380
- rt_outfloatset = np.float32
493
+ rt_outfloattype = np.float32
381
494
  therunoptions["saveminimumsLFOfiltfiles"] = args.saveminimumsLFOfiltfiles
382
495
 
383
496
  # read the fmri input files
@@ -618,8 +731,12 @@ def delayvar(args):
618
731
  winsLFOfitmean, winsLFOfitmean_shm = tide_util.allocarray(
619
732
  internalwinspaceshape, rt_outfloattype, shared=usesharedmem
620
733
  )
621
- winrvalue, winrvalue_shm = tide_util.allocarray(internalwinspaceshape, rt_outfloattype, shared=usesharedmem)
622
- winr2value, winr2value_shm = tide_util.allocarray(internalwinspaceshape, rt_outfloattype, shared=usesharedmem)
734
+ winrvalue, winrvalue_shm = tide_util.allocarray(
735
+ internalwinspaceshape, rt_outfloattype, shared=usesharedmem
736
+ )
737
+ winr2value, winr2value_shm = tide_util.allocarray(
738
+ internalwinspaceshape, rt_outfloattype, shared=usesharedmem
739
+ )
623
740
  winfitNorm, winfitNorm_shm = tide_util.allocarray(
624
741
  internalwinspaceshapederivs, rt_outfloattype, shared=usesharedmem
625
742
  )
@@ -629,7 +746,9 @@ def delayvar(args):
629
746
  winmovingsignal, winmovingsignal_shm = tide_util.allocarray(
630
747
  internalwinfmrishape, rt_outfloattype, shared=usesharedmem
631
748
  )
632
- winlagtc, winlagtc_shm = tide_util.allocarray(internalwinfmrishape, rt_floattype, shared=usesharedmem)
749
+ winlagtc, winlagtc_shm = tide_util.allocarray(
750
+ internalwinfmrishape, rt_floattype, shared=usesharedmem
751
+ )
633
752
  winfiltereddata, winfiltereddata_shm = tide_util.allocarray(
634
753
  internalwinfmrishape, rt_outfloattype, shared=usesharedmem
635
754
  )
@@ -836,7 +955,7 @@ def delayvar(args):
836
955
  # pcadata = np.mean(reduceddata, axis=0)
837
956
  pcadata = thefit.components_[0]
838
957
  averagedata = np.mean(windoweddelayoffset, axis=0)
839
- thepxcorr = pearsonr(averagedata, pcadata)[0]
958
+ thepxcorr = pearsonr(averagedata, pcadata).statistic
840
959
  LGR.info(f"pca/avg correlation = {thepxcorr}")
841
960
  if thepxcorr > 0.0:
842
961
  systemiccomp = 1.0 * pcadata
@@ -978,21 +1097,21 @@ def delayvar(args):
978
1097
  "systemicsLFOfitmean",
979
1098
  "info",
980
1099
  None,
981
- f"Constant coefficient for systemic filter",
1100
+ "Constant coefficient for systemic filter",
982
1101
  ),
983
1102
  (
984
1103
  systemicfitcoeff[:, 0],
985
1104
  "systemiccoffEV0",
986
1105
  "info",
987
1106
  None,
988
- f"Coefficient 0 for systemic filter",
1107
+ "Coefficient 0 for systemic filter",
989
1108
  ),
990
1109
  (
991
1110
  systemicfitcoeff[:, 1],
992
1111
  "systemiccoffEV1",
993
1112
  "info",
994
1113
  None,
995
- f"Coefficient 1 for systemic filter",
1114
+ "Coefficient 1 for systemic filter",
996
1115
  ),
997
1116
  ]
998
1117
  if reduceddata is not None:
@@ -1112,9 +1231,38 @@ def delayvar(args):
1112
1231
  Path(f"{outputname}_DELAYVARDONE.txt").touch()
1113
1232
 
1114
1233
 
1115
- def process_args(inputargs=None):
1234
+ def process_args(inputargs: Optional[Any] = None) -> None:
1116
1235
  """
1117
1236
  Compile arguments for delayvar workflow.
1237
+
1238
+ This function processes input arguments for the delayvar workflow by parsing
1239
+ command line arguments or provided input arguments using a predefined parser.
1240
+
1241
+ Parameters
1242
+ ----------
1243
+ inputargs : Any, optional
1244
+ Input arguments to be processed. Can be None (default) to use command line
1245
+ arguments, or a list of arguments to parse. Default is None.
1246
+
1247
+ Returns
1248
+ -------
1249
+ dict
1250
+ Parsed arguments as a dictionary. The exact structure depends on the
1251
+ argument parser (_get_parser) used internally.
1252
+
1253
+ Notes
1254
+ -----
1255
+ This function internally calls `pf.setargs` with the `_get_parser` function
1256
+ and the provided input arguments. The returned arguments are typically used
1257
+ to configure the delayvar workflow parameters.
1258
+
1259
+ Examples
1260
+ --------
1261
+ >>> # Using default command line arguments
1262
+ >>> args = process_args()
1263
+
1264
+ >>> # Using custom arguments
1265
+ >>> args = process_args(['--input', 'data.txt', '--output', 'result.txt'])
1118
1266
  """
1119
1267
  args, argstowrite = pf.setargs(_get_parser, inputargs=inputargs)
1120
1268
  return args