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
@@ -17,7 +17,10 @@
17
17
  #
18
18
  #
19
19
 
20
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
21
+
20
22
  import numpy as np
23
+ from numpy.typing import NDArray
21
24
 
22
25
  import rapidtide.io as tide_io
23
26
  import rapidtide.linfitfiltpass as tide_linfitfiltpass
@@ -25,37 +28,158 @@ import rapidtide.makelaggedtcs as tide_makelagged
25
28
 
26
29
 
27
30
  def regressfrommaps(
28
- fmri_data_valid,
29
- validvoxels,
30
- initial_fmri_x,
31
- lagtimes,
32
- fitmask,
33
- genlagtc,
34
- mode,
35
- outputname,
36
- oversamptr,
37
- sLFOfitmean,
38
- rvalue,
39
- r2value,
40
- fitNorm,
41
- fitcoeff,
42
- movingsignal,
43
- lagtc,
44
- filtereddata,
45
- LGR,
46
- TimingLGR,
47
- regressfiltthreshval,
48
- saveminimumsLFOfiltfiles,
49
- nprocs_makelaggedtcs=1,
50
- nprocs_regressionfilt=1,
51
- regressderivs=0,
52
- chunksize=50000,
53
- showprogressbar=True,
54
- alwaysmultiproc=False,
55
- saveEVsandquit=False,
56
- coefficientsonly=False,
57
- debug=False,
58
- ):
31
+ fmri_data_valid: Any,
32
+ validvoxels: Any,
33
+ initial_fmri_x: Any,
34
+ lagtimes: Any,
35
+ fitmask: Any,
36
+ genlagtc: Any,
37
+ mode: Any,
38
+ outputname: Any,
39
+ oversamptr: Any,
40
+ sLFOfitmean: Any,
41
+ rvalue: Any,
42
+ r2value: Any,
43
+ fitNorm: Any,
44
+ fitcoeff: Any,
45
+ movingsignal: Any,
46
+ lagtc: Any,
47
+ filtereddata: Any,
48
+ LGR: Any,
49
+ TimingLGR: Any,
50
+ regressfiltthreshval: Any,
51
+ saveminimumsLFOfiltfiles: Any,
52
+ nprocs_makelaggedtcs: int = 1,
53
+ nprocs_regressionfilt: int = 1,
54
+ regressderivs: int = 0,
55
+ chunksize: int = 50000,
56
+ showprogressbar: bool = True,
57
+ alwaysmultiproc: bool = False,
58
+ saveEVsandquit: bool = False,
59
+ coefficientsonly: bool = False,
60
+ timemask: Optional[NDArray] = None,
61
+ debug: bool = False,
62
+ ) -> None:
63
+ """
64
+ Perform regression analysis on fMRI data using lagged timecourses.
65
+
66
+ This function generates voxel-specific regressors from lagged timecourses,
67
+ applies filtering, and performs regression to estimate model coefficients.
68
+ It supports various modes including cross-validation regression (cvrmap),
69
+ and can optionally save intermediate results or quit early.
70
+
71
+ Parameters
72
+ ----------
73
+ fmri_data_valid : array-like
74
+ Valid fMRI data to be processed.
75
+ validvoxels : array-like
76
+ Indices or mask of valid voxels.
77
+ initial_fmri_x : array-like
78
+ Initial fMRI timecourse (e.g., stimulus timing).
79
+ lagtimes : array-like
80
+ Time lags to be used for generating lagged regressors.
81
+ fitmask : array-like
82
+ Mask for selecting voxels to fit.
83
+ genlagtc : object
84
+ Generator for lagged timecourses.
85
+ mode : str
86
+ Processing mode (e.g., 'cvrmap').
87
+ outputname : str
88
+ Base name for output files.
89
+ oversamptr : float
90
+ Oversampling rate for timecourse generation.
91
+ sLFOfitmean : array-like
92
+ Mean of sLFO fit values.
93
+ rvalue : array-like
94
+ R-values from regression.
95
+ r2value : array-like
96
+ R-squared values from regression.
97
+ fitNorm : array-like
98
+ Normalization values for fit.
99
+ fitcoeff : array-like
100
+ Coefficients from the fit.
101
+ movingsignal : array-like
102
+ Moving signal components.
103
+ lagtc : array-like
104
+ Lagged timecourses.
105
+ filtereddata : array-like
106
+ Filtered fMRI data.
107
+ LGR : object, optional
108
+ Logger for general logging.
109
+ TimingLGR : object, optional
110
+ Logger for timing information.
111
+ regressfiltthreshval : float
112
+ Threshold for regression filtering.
113
+ saveminimumsLFOfiltfiles : bool
114
+ Whether to save noise removed timeseries.
115
+ nprocs_makelaggedtcs : int, optional
116
+ Number of processes for making lagged timecourses (default is 1).
117
+ nprocs_regressionfilt : int, optional
118
+ Number of processes for regression filtering (default is 1).
119
+ regressderivs : int, optional
120
+ Order of derivatives to include in regressors (default is 0).
121
+ chunksize : int, optional
122
+ Size of chunks for processing (default is 50000).
123
+ showprogressbar : bool, optional
124
+ Whether to show progress bar (default is True).
125
+ alwaysmultiproc : bool, optional
126
+ Force multiprocessing even for small tasks (default is False).
127
+ saveEVsandquit : bool, optional
128
+ Save EVs and quit early (default is False).
129
+ coefficientsonly : bool, optional
130
+ Return only coefficients (default is False).
131
+ timemask : NDArray, optional
132
+ Mask of timepoints to include in regression filtering.
133
+ debug : bool, optional
134
+ Enable debug output (default is False).
135
+
136
+ Returns
137
+ -------
138
+ tuple
139
+ If `saveEVsandquit` is True, returns (0, regressorset, evset).
140
+ Otherwise, returns (voxelsprocessed_regressionfilt, regressorset, evset).
141
+
142
+ Notes
143
+ -----
144
+ - The function modifies `fitcoeff` in-place when `mode == "cvrmap"` by multiplying by 100.
145
+ - The function uses multiprocessing if `alwaysmultiproc` is True or if `nprocs > 1`.
146
+ - Filtering is performed using `tide_linfitfiltpass.linfitfiltpass`.
147
+
148
+ Examples
149
+ --------
150
+ >>> regressfrommaps(
151
+ ... fmri_data_valid=data,
152
+ ... validvoxels=voxels,
153
+ ... initial_fmri_x=stimulus,
154
+ ... lagtimes=lags,
155
+ ... fitmask=mask,
156
+ ... genlagtc=gen,
157
+ ... mode="cvrmap",
158
+ ... outputname="output",
159
+ ... oversamptr=2.0,
160
+ ... sLFOfitmean=mean,
161
+ ... rvalue=r_vals,
162
+ ... r2value=r2_vals,
163
+ ... fitNorm=norm,
164
+ ... fitcoeff=coeffs,
165
+ ... movingsignal=moving,
166
+ ... lagtc=lagged_tc,
167
+ ... filtereddata=filtered,
168
+ ... LGR=logger,
169
+ ... TimingLGR=timing_logger,
170
+ ... regressfiltthreshval=0.5,
171
+ ... saveminimumsLFOfiltfiles=True,
172
+ ... nprocs_makelaggedtcs=4,
173
+ ... nprocs_regressionfilt=2,
174
+ ... regressderivs=2,
175
+ ... chunksize=10000,
176
+ ... showprogressbar=True,
177
+ ... alwaysmultiproc=False,
178
+ ... saveEVsandquit=False,
179
+ ... coefficientsonly=False,
180
+ ... debug=False,
181
+ ... )
182
+ """
59
183
  if debug:
60
184
  print("regressfrommaps: Starting")
61
185
  print(f"\t{nprocs_makelaggedtcs=}")
@@ -68,8 +192,7 @@ def regressfrommaps(
68
192
  print(f"\t{outputname=}")
69
193
  print(f"\t{oversamptr=}")
70
194
  print(f"\t{regressfiltthreshval=}")
71
- rt_floatset = np.float64
72
- rt_floattype = "float64"
195
+ rt_floattype = np.float64
73
196
  numvalidspatiallocs = np.shape(validvoxels)[0]
74
197
 
75
198
  # generate the voxel specific regressors
@@ -89,10 +212,12 @@ def regressfrommaps(
89
212
  alwaysmultiproc=alwaysmultiproc,
90
213
  showprogressbar=showprogressbar,
91
214
  chunksize=chunksize,
92
- rt_floatset=rt_floatset,
93
215
  rt_floattype=rt_floattype,
94
216
  debug=debug,
95
217
  )
218
+ if timemask is not None:
219
+ lagtc = lagtc * timemask[None, :]
220
+
96
221
  if debug:
97
222
  print(f"\t{lagtimes.shape=}")
98
223
  threshmask = np.where(fitmask > 0, 1, 0)
@@ -113,7 +238,7 @@ def regressfrommaps(
113
238
  if debug:
114
239
  print(f"adding derivatives up to order {regressderivs} prior to regression")
115
240
  regressorset = tide_linfitfiltpass.makevoxelspecificderivs(lagtc, regressderivs)
116
- baseev = rt_floatset(genlagtc.yfromx(initial_fmri_x))
241
+ baseev = (genlagtc.yfromx(initial_fmri_x)).astype(rt_floattype)
117
242
  evset = tide_linfitfiltpass.makevoxelspecificderivs(
118
243
  baseev.reshape((1, -1)), regressderivs
119
244
  ).reshape((-1, 2))
@@ -121,7 +246,7 @@ def regressfrommaps(
121
246
  if debug:
122
247
  print(f"using raw lagged regressors for regression")
123
248
  regressorset = lagtc
124
- evset = rt_floatset(genlagtc.yfromx(initial_fmri_x))
249
+ evset = (genlagtc.yfromx(initial_fmri_x)).astype(rt_floattype)
125
250
  if debug:
126
251
  print(f"{regressorset.shape=}")
127
252
 
@@ -152,7 +277,6 @@ def regressfrommaps(
152
277
  showprogressbar=showprogressbar,
153
278
  verbose=(LGR is not None),
154
279
  chunksize=chunksize,
155
- rt_floatset=rt_floatset,
156
280
  rt_floattype=rt_floattype,
157
281
  debug=debug,
158
282
  )
@@ -30,6 +30,10 @@ with warnings.catch_warnings():
30
30
  else:
31
31
  pyfftwpresent = True
32
32
 
33
+ from argparse import Namespace
34
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
35
+
36
+ from numpy.typing import NDArray
33
37
  from scipy import fftpack
34
38
 
35
39
  import rapidtide.io as tide_io
@@ -40,9 +44,37 @@ if pyfftwpresent:
40
44
  pyfftw.interfaces.cache.enable()
41
45
 
42
46
 
43
- def _get_parser():
47
+ def _get_parser() -> Any:
44
48
  """
45
- Argument parser for resamplenifti
49
+ Argument parser for resamplenifti.
50
+
51
+ Creates and configures an argument parser for the resamplenifti command-line tool
52
+ that resamples NIfTI files to a different temporal resolution (TR).
53
+
54
+ Returns
55
+ -------
56
+ argparse.ArgumentParser
57
+ Configured argument parser object with all required and optional arguments
58
+ for the resamplenifti tool.
59
+
60
+ Notes
61
+ -----
62
+ The returned parser includes the following positional arguments:
63
+ - inputfile: Path to the input NIfTI file
64
+ - outputfile: Path to the output NIfTI file
65
+ - outputtr: Target temporal resolution in seconds
66
+
67
+ And the following optional arguments:
68
+ - --noantialias: Disable antialiasing filter (enabled by default)
69
+ - --normalize: Normalize data and save as UINT16 (disabled by default)
70
+ - --debug: Print debugging information (disabled by default)
71
+
72
+ Examples
73
+ --------
74
+ >>> parser = _get_parser()
75
+ >>> args = parser.parse_args(['input.nii', 'output.nii', '2.0'])
76
+ >>> print(args.inputfile)
77
+ 'input.nii'
46
78
  """
47
79
  parser = argparse.ArgumentParser(
48
80
  prog="resamplenifti",
@@ -78,7 +110,57 @@ def _get_parser():
78
110
  return parser
79
111
 
80
112
 
81
- def resamplenifti(args):
113
+ def resamplenifti(args: Any) -> None:
114
+ """
115
+ Resample a 4D NIfTI file to a specified temporal resolution.
116
+
117
+ This function reads a 4D NIfTI file, resamples its time series data to a
118
+ new temporal resolution specified by `args.outputtr`, and saves the
119
+ resampled data to a new NIfTI file. The resampling is performed using
120
+ spline interpolation, and optional antialiasing is applied based on the
121
+ input and output temporal resolutions.
122
+
123
+ Parameters
124
+ ----------
125
+ args : argparse.Namespace
126
+ An object containing the following attributes:
127
+ - inputfile : str
128
+ Path to the input NIfTI file.
129
+ - outputfile : str
130
+ Path to the output NIfTI file.
131
+ - outputtr : float
132
+ Desired output temporal resolution (TR) in seconds.
133
+ - antialias : bool, optional
134
+ Whether to apply antialiasing during resampling. Default is True.
135
+ - debug : bool, optional
136
+ If True, print debugging information. Default is False.
137
+
138
+ Returns
139
+ -------
140
+ None
141
+ This function does not return a value but saves the resampled NIfTI
142
+ file to the specified output path.
143
+
144
+ Notes
145
+ -----
146
+ - If the input TR is greater than the output TR (i.e., upsampling), antialiasing
147
+ is automatically disabled.
148
+ - The function processes each voxel individually, which may be time-consuming
149
+ for large datasets.
150
+ - The output NIfTI header is updated to reflect the new temporal resolution.
151
+
152
+ Examples
153
+ --------
154
+ >>> import argparse
155
+ >>> args = argparse.Namespace(
156
+ ... inputfile='input.nii.gz',
157
+ ... outputfile='output.nii.gz',
158
+ ... outputtr=1.0,
159
+ ... antialias=True,
160
+ ... debug=False
161
+ ... )
162
+ >>> resamplenifti(args)
163
+ """
82
164
  # get the input TR
83
165
  inputtr, numinputtrs = tide_io.fmritimeinfo(args.inputfile)
84
166
  if args.debug:
@@ -17,18 +17,49 @@
17
17
  #
18
18
  #
19
19
  import argparse
20
+ from argparse import Namespace
21
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
20
22
 
21
23
  import matplotlib.pyplot as plt
22
24
  import numpy as np
25
+ from numpy.typing import NDArray
23
26
 
24
27
  import rapidtide.io as tide_io
25
28
  import rapidtide.resample as tide_resample
26
29
  import rapidtide.workflows.parser_funcs as pf
27
30
 
28
31
 
29
- def _get_parser():
32
+ def _get_parser() -> Any:
30
33
  """
31
- Argument parser for resamp1tc
34
+ Argument parser for resamp1tc.
35
+
36
+ This function constructs and returns an `argparse.ArgumentParser` object configured
37
+ for parsing command-line arguments for the `resamp1tc` utility. It defines required
38
+ and optional arguments needed to resample a timeseries file.
39
+
40
+ Returns
41
+ -------
42
+ argparse.ArgumentParser
43
+ Configured argument parser for the resamp1tc utility.
44
+
45
+ Notes
46
+ -----
47
+ The parser includes the following required arguments:
48
+
49
+ - ``inputfile``: Path to the input timeseries file.
50
+ - ``insamplerate``: Input sample rate in Hz.
51
+ - ``outputfile``: Path to the output resampled file.
52
+ - ``outsamplerate``: Output sample rate in Hz.
53
+
54
+ Optional arguments include:
55
+
56
+ - ``--nodisplay``: Do not display data.
57
+ - ``--noantialias``: Disable antialiasing.
58
+
59
+ Examples
60
+ --------
61
+ >>> parser = _get_parser()
62
+ >>> args = parser.parse_args()
32
63
  """
33
64
  parser = argparse.ArgumentParser(
34
65
  prog="resampletc",
@@ -91,7 +122,64 @@ def _get_parser():
91
122
  return parser
92
123
 
93
124
 
94
- def resampletc(args):
125
+ def resampletc(args: Any) -> None:
126
+ """
127
+ Resample a time series signal from an input file to a specified output sampling rate.
128
+
129
+ This function reads a time series from a text file, resamples it to a new sampling rate,
130
+ and writes the resampled data to an output file. Optionally, it displays the original
131
+ and resampled signals for visual comparison.
132
+
133
+ Parameters
134
+ ----------
135
+ args : Any
136
+ An object containing the following attributes:
137
+ - `inputfile` : str
138
+ Path to the input text file containing the time series data.
139
+ - `outputfile` : str
140
+ Path to the output text file where resampled data will be written.
141
+ - `insamplerate` : float
142
+ Input sampling rate (Hz) of the data in the input file.
143
+ - `outsamplerate` : float
144
+ Desired output sampling rate (Hz) for the resampled data.
145
+ - `antialias` : bool
146
+ Whether to apply anti-aliasing during resampling.
147
+ - `display` : bool
148
+ If True, plots the original and resampled signals.
149
+ - `starttime` : float, optional
150
+ Start time for the output signal. If None, uses the start time from input.
151
+ - `endtime` : float, optional
152
+ End time for the output signal. If None, uses the end time from input.
153
+
154
+ Returns
155
+ -------
156
+ None
157
+ This function does not return a value. It writes the resampled data to a file
158
+ and optionally displays a plot.
159
+
160
+ Notes
161
+ -----
162
+ - The input file is expected to contain a single column of time series data.
163
+ - If the sampling rate specified in the input file does not match `args.insamplerate`,
164
+ a warning is printed.
165
+ - The function uses `tide_resample.arbresample` for resampling with configurable
166
+ anti-aliasing.
167
+ - If `args.display` is True, the original and resampled signals are plotted
168
+ with the original in black and the resampled in red.
169
+
170
+ Examples
171
+ --------
172
+ >>> import argparse
173
+ >>> args = argparse.Namespace(
174
+ ... inputfile='input.txt',
175
+ ... outputfile='output.txt',
176
+ ... insamplerate=10.0,
177
+ ... outsamplerate=5.0,
178
+ ... antialias=True,
179
+ ... display=False
180
+ ... )
181
+ >>> resampletc(args)
182
+ """
95
183
  intimestep = 1.0 / args.insamplerate
96
184
  outtimestep = 1.0 / args.outsamplerate
97
185
  (
@@ -21,8 +21,11 @@ import copy
21
21
  import logging
22
22
  import os
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 numpy as np
28
+ from numpy.typing import NDArray
26
29
 
27
30
  import rapidtide.io as tide_io
28
31
  import rapidtide.linfitfiltpass as tide_linfitfiltpass
@@ -39,9 +42,32 @@ TimingLGR = logging.getLogger("TIMING")
39
42
  DEFAULT_REGRESSIONFILTDERIVS = 0
40
43
 
41
44
 
42
- def _get_parser():
45
+ def _get_parser() -> Any:
43
46
  """
44
- Argument parser for retrolagtcs
47
+ Argument parser for retrolagtcs.
48
+
49
+ This function constructs and returns an `argparse.ArgumentParser` object configured
50
+ for the `retrolagtcs` command-line tool. It defines all required and optional
51
+ arguments needed to generate voxel-specific lagged timecourses from rapidtide
52
+ analysis maps.
53
+
54
+ Returns
55
+ -------
56
+ argparse.ArgumentParser
57
+ Configured argument parser for retrolagtcs.
58
+
59
+ Notes
60
+ -----
61
+ The parser expects several input files and parameters to define the processing
62
+ pipeline. The function uses `pf.is_valid_file` to validate the existence of
63
+ the input 4D NIfTI file.
64
+
65
+ Examples
66
+ --------
67
+ >>> parser = _get_parser()
68
+ >>> args = parser.parse_args()
69
+ >>> print(args.fmrifile)
70
+ 'sub-01_task-rest_bold.nii.gz'
45
71
  """
46
72
  parser = argparse.ArgumentParser(
47
73
  prog="retrolagtcs",
@@ -126,11 +152,71 @@ def _get_parser():
126
152
  return parser
127
153
 
128
154
 
129
- def retrolagtcs(args):
130
- rt_floatset = np.float64
131
- rt_floattype = "float64"
132
- rt_outfloatset = np.float64
133
- rt_outfloattype = "float64"
155
+ def retrolagtcs(args: Any) -> None:
156
+ """
157
+ Generate lagged time series regressors from fMRI data using a lag-time map and a generator file.
158
+
159
+ This function reads fMRI data, a mask, and a lag-time map to compute lagged time series
160
+ regressors for each voxel in the mask. It supports both single-process and multi-process
161
+ execution using shared memory. The computed regressors are saved as NIfTI files.
162
+
163
+ Parameters
164
+ ----------
165
+ args : Any
166
+ An object containing the following attributes:
167
+ - fmrifile : str
168
+ Path to the input fMRI NIfTI file.
169
+ - maskfile : str
170
+ Path to the processing mask NIfTI file.
171
+ - lagtimesfile : str
172
+ Path to the lag times NIfTI file.
173
+ - lagtcgeneratorfile : str
174
+ Path to the lagtc generator file (used for resampling).
175
+ - outputroot : str
176
+ Root path for output files.
177
+ - nprocs : int
178
+ Number of processes to use for parallel execution. If less than 1, defaults to max CPU count.
179
+ - numskip : int
180
+ Number of initial time points to skip.
181
+ - regressderivs : int
182
+ Number of time derivatives to include in the regressor set.
183
+ - showprogressbar : bool
184
+ Whether to display a progress bar during processing.
185
+ - debug : bool
186
+ Whether to enable debug mode for additional logging.
187
+
188
+ Returns
189
+ -------
190
+ None
191
+ This function does not return a value but writes output files to disk.
192
+
193
+ Notes
194
+ -----
195
+ - The function requires the input files to have matching spatial dimensions.
196
+ - Shared memory is used for multi-process execution to improve performance.
197
+ - Output files include:
198
+ - Regressor time series (4D NIfTI)
199
+ - Optional mask and lag time maps (3D NIfTI)
200
+
201
+ Examples
202
+ --------
203
+ >>> import argparse
204
+ >>> args = argparse.Namespace(
205
+ ... fmrifile='fmri.nii.gz',
206
+ ... maskfile='mask.nii.gz',
207
+ ... lagtimesfile='lagtimes.nii.gz',
208
+ ... lagtcgeneratorfile='generator.txt',
209
+ ... outputroot='output',
210
+ ... nprocs=4,
211
+ ... numskip=5,
212
+ ... regressderivs=2,
213
+ ... showprogressbar=True,
214
+ ... debug=False
215
+ ... )
216
+ >>> retrolagtcs(args)
217
+ """
218
+ rt_floattype = np.float64
219
+ rt_outfloattype = np.float64
134
220
 
135
221
  # get the pid of the parent process
136
222
  args.pid = os.getpid()
@@ -229,11 +315,15 @@ def retrolagtcs(args):
229
315
  else:
230
316
  if args.debug:
231
317
  print("allocating memory")
232
- fitNorm, fitNorm_shm = tide_util.allocarray(internalvalidspaceshapederivs, rt_outfloattype, shared=usesharedmem)
318
+ fitNorm, fitNorm_shm = tide_util.allocarray(
319
+ internalvalidspaceshapederivs, rt_outfloattype, shared=usesharedmem
320
+ )
233
321
  fitcoeff, fitcoeff_shm = tide_util.allocarray(
234
322
  internalvalidspaceshapederivs, rt_outfloattype, shared=usesharedmem
235
323
  )
236
- lagtc, lagtc_shm = tide_util.allocarray(internalvalidfmrishape, rt_floattype, shared=usesharedmem)
324
+ lagtc, lagtc_shm = tide_util.allocarray(
325
+ internalvalidfmrishape, rt_floattype, shared=usesharedmem
326
+ )
237
327
 
238
328
  outputpath = os.path.dirname(args.outputroot)
239
329
  rawsources = [