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
@@ -18,17 +18,42 @@
18
18
  #
19
19
  import argparse
20
20
  import sys
21
+ from argparse import Namespace
22
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
21
23
 
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.miscmath as tide_math
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 filttc
34
+ Argument parser for filttc.
35
+
36
+ This function constructs and returns an `argparse.ArgumentParser` object configured
37
+ for parsing command-line arguments for the `filttc` tool, which filters timecourse
38
+ data in text files. It includes support for specifying sampling rate or timestep,
39
+ filter options, normalization methods, and miscellaneous flags.
40
+
41
+ Returns
42
+ -------
43
+ argparse.ArgumentParser
44
+ Configured argument parser for the filttc tool.
45
+
46
+ Notes
47
+ -----
48
+ The `--samplerate` and `--sampletstep` arguments are mutually exclusive and define
49
+ the sampling frequency of the input timecourses. The sampling frequency can be
50
+ specified either as a frequency (Hz) or as a timestep (seconds), with the latter
51
+ being the inverse of the former.
52
+
53
+ Examples
54
+ --------
55
+ >>> parser = _get_parser()
56
+ >>> args = parser.parse_args(['--inputfile', 'input.txt', '--outputfile', 'output.txt'])
32
57
  """
33
58
  parser = argparse.ArgumentParser(
34
59
  prog="filttc",
@@ -104,7 +129,53 @@ def _get_parser():
104
129
  return parser
105
130
 
106
131
 
107
- def filttc(args):
132
+ def filttc(args: Any) -> None:
133
+ """
134
+ Apply a filter to timecourse data read from a text file and write the filtered output.
135
+
136
+ This function reads timecourse data from a specified input file, applies a filter
137
+ to each timecourse, and writes the filtered data to an output file. It supports
138
+ normalization, demeaning, and automatic sampling rate detection from the input file
139
+ or command-line arguments.
140
+
141
+ Parameters
142
+ ----------
143
+ args : Any
144
+ An object containing command-line arguments. Expected attributes include:
145
+ - `inputfile`: Path to the input text file containing timecourse data.
146
+ - `outputfile`: Path to the output text file where filtered data will be written.
147
+ - `samplerate`: Sampling rate of the data, or 'auto' to detect from file.
148
+ - `normfirst`: Boolean indicating whether to normalize before filtering.
149
+ - `normmethod`: Normalization method to use (e.g., 'zscore', 'minmax').
150
+ - `demean`: Boolean indicating whether to remove the mean from the filtered data.
151
+
152
+ Returns
153
+ -------
154
+ None
155
+ This function does not return a value. It writes the filtered timecourse data
156
+ to the specified output file.
157
+
158
+ Notes
159
+ -----
160
+ - The input file must contain a header specifying the sampling rate, or the
161
+ sampling rate must be provided via command-line arguments.
162
+ - The filtering and normalization are applied independently to each timecourse.
163
+ - If `normfirst` is True, normalization is applied before filtering; otherwise,
164
+ filtering is applied before normalization.
165
+
166
+ Examples
167
+ --------
168
+ >>> import argparse
169
+ >>> args = argparse.Namespace(
170
+ ... inputfile='input.txt',
171
+ ... outputfile='output.txt',
172
+ ... samplerate='auto',
173
+ ... normfirst=False,
174
+ ... normmethod='zscore',
175
+ ... demean=True
176
+ ... )
177
+ >>> filttc(args)
178
+ """
108
179
  args, thefilter = pf.postprocessfilteropts(args)
109
180
 
110
181
  # read in data
@@ -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
  from scipy import ndimage
21
24
 
22
25
  import rapidtide.io as tide_io
@@ -28,48 +31,193 @@ import rapidtide.util as tide_util
28
31
 
29
32
 
30
33
  def fitSimFunc(
31
- fmri_data_valid,
32
- validsimcalcstart,
33
- validsimcalcend,
34
- osvalidsimcalcstart,
35
- osvalidsimcalcend,
36
- initial_fmri_x,
37
- os_fmri_x,
38
- theMutualInformationator,
39
- cleaned_referencetc,
40
- corrout,
41
- outputname,
42
- validvoxels,
43
- nativespaceshape,
44
- bidsbasedict,
45
- numspatiallocs,
46
- gaussout,
47
- theinitialdelay,
48
- windowout,
49
- R2,
50
- thesizes,
51
- internalspaceshape,
52
- numvalidspatiallocs,
53
- theinputdata,
54
- theheader,
55
- theFitter,
56
- fitmask,
57
- lagtimes,
58
- lagstrengths,
59
- lagsigma,
60
- failreason,
61
- outmaparray,
62
- trimmedcorrscale,
63
- similaritytype,
64
- thepass,
65
- optiondict,
66
- LGR,
67
- TimingLGR,
68
- simplefit=False,
69
- upsampfac=8,
70
- rt_floatset=np.float64,
71
- rt_floattype="float64",
72
- ):
34
+ fmri_data_valid: NDArray[np.floating[Any]],
35
+ validsimcalcstart: int,
36
+ validsimcalcend: int,
37
+ osvalidsimcalcstart: int,
38
+ osvalidsimcalcend: int,
39
+ initial_fmri_x: NDArray[np.floating[Any]],
40
+ os_fmri_x: NDArray[np.floating[Any]],
41
+ theMutualInformationator: Any,
42
+ cleaned_referencetc: Any,
43
+ corrout: NDArray[np.floating[Any]],
44
+ outputname: str,
45
+ validvoxels: Any,
46
+ nativespaceshape: Any,
47
+ bidsbasedict: Any,
48
+ numspatiallocs: Any,
49
+ gaussout: Any,
50
+ theinitialdelay: Any,
51
+ windowout: Any,
52
+ R2: Any,
53
+ thesizes: Any,
54
+ internalspaceshape: Any,
55
+ numvalidspatiallocs: Any,
56
+ theinputdata: Any,
57
+ theheader: Any,
58
+ theFitter: Any,
59
+ fitmask: Any,
60
+ lagtimes: Any,
61
+ lagstrengths: Any,
62
+ lagsigma: Any,
63
+ failreason: Any,
64
+ outmaparray: Any,
65
+ trimmedcorrscale: Any,
66
+ similaritytype: Any,
67
+ thepass: Any,
68
+ optiondict: Any,
69
+ LGR: Any,
70
+ TimingLGR: Any,
71
+ simplefit: bool = False,
72
+ upsampfac: int = 8,
73
+ rt_floattype: np.dtype = np.float64,
74
+ ) -> NDArray | None:
75
+ """
76
+ Perform similarity function fitting and time lag estimation for fMRI data.
77
+
78
+ This function conducts either a simple or full fitting process for estimating time lags
79
+ between fMRI signals and a reference time course. It supports hybrid similarity metrics
80
+ and includes optional despeckling and patch shifting steps.
81
+
82
+ Parameters
83
+ ----------
84
+ fmri_data_valid : NDArray[np.floating[Any]]
85
+ Valid fMRI data for processing.
86
+ validsimcalcstart : int
87
+ Start index for valid similarity calculation.
88
+ validsimcalcend : int
89
+ End index for valid similarity calculation.
90
+ osvalidsimcalcstart : int
91
+ Start index for oversampled valid similarity calculation.
92
+ osvalidsimcalcend : int
93
+ End index for oversampled valid similarity calculation.
94
+ initial_fmri_x : NDArray[np.floating[Any]]
95
+ Initial fMRI x values.
96
+ os_fmri_x : NDArray[np.floating[Any]]
97
+ Oversampled fMRI x values.
98
+ theMutualInformationator : object
99
+ Mutual information calculator.
100
+ cleaned_referencetc : array_like
101
+ Cleaned reference time course.
102
+ corrout : NDArray[np.floating[Any]]
103
+ Correlation output array.
104
+ outputname : str
105
+ Output filename prefix.
106
+ validvoxels : array_like
107
+ Indices of valid voxels.
108
+ nativespaceshape : tuple
109
+ Native space shape of the data.
110
+ bidsbasedict : dict
111
+ BIDS-based dictionary for output metadata.
112
+ numspatiallocs : int
113
+ Number of spatial locations.
114
+ gaussout : array_like
115
+ Gaussian output array.
116
+ theinitialdelay : float
117
+ Initial delay value.
118
+ windowout : array_like
119
+ Window output array.
120
+ R2 : array_like
121
+ R-squared values.
122
+ thesizes : array_like
123
+ Sizes for processing.
124
+ internalspaceshape : tuple
125
+ Internal space shape.
126
+ numvalidspatiallocs : int
127
+ Number of valid spatial locations.
128
+ theinputdata : object
129
+ Input data object.
130
+ theheader : dict
131
+ Header information.
132
+ theFitter : object
133
+ Fitter object for similarity function fitting.
134
+ fitmask : array_like
135
+ Mask for fitting.
136
+ lagtimes : array_like
137
+ Array to store estimated lag times.
138
+ lagstrengths : array_like
139
+ Array to store lag strengths.
140
+ lagsigma : array_like
141
+ Array to store sigma values for lags.
142
+ failreason : array_like
143
+ Array to store failure reasons.
144
+ outmaparray : array_like
145
+ Output map array.
146
+ trimmedcorrscale : array_like
147
+ Trimmed correlation scale.
148
+ similaritytype : str
149
+ Type of similarity metric used.
150
+ thepass : int
151
+ Current pass number.
152
+ optiondict : dict
153
+ Dictionary of options for processing.
154
+ LGR : object
155
+ Logger for general messages.
156
+ TimingLGR : object
157
+ Logger for timing information.
158
+ simplefit : bool, optional
159
+ If True, perform simple fitting using upsampling. Default is False.
160
+ upsampfac : int, optional
161
+ Upsampling factor for simple fitting. Default is 8.
162
+ rt_floattype : np.dtype, optional
163
+ Real-time floating-point data type. Default is np.float64.
164
+
165
+ Returns
166
+ -------
167
+ internaldespeckleincludemask : NDArray[np.floating[Any]] or None
168
+ Mask indicating which voxels were included in despeckling, or None if no despeckling was performed.
169
+
170
+ Notes
171
+ -----
172
+ - This function supports both simple and hybrid similarity metrics.
173
+ - Despeckling and patch shifting steps are optional and controlled by `optiondict`.
174
+ - The function modifies `lagtimes`, `lagstrengths`, `lagsigma`, and `fitmask` in-place.
175
+
176
+ Examples
177
+ --------
178
+ >>> fitSimFunc(
179
+ ... fmri_data_valid,
180
+ ... validsimcalcstart,
181
+ ... validsimcalcend,
182
+ ... osvalidsimcalcstart,
183
+ ... osvalidsimcalcend,
184
+ ... initial_fmri_x,
185
+ ... os_fmri_x,
186
+ ... theMutualInformationator,
187
+ ... cleaned_referencetc,
188
+ ... corrout,
189
+ ... outputname,
190
+ ... validvoxels,
191
+ ... nativespaceshape,
192
+ ... bidsbasedict,
193
+ ... numspatiallocs,
194
+ ... gaussout,
195
+ ... theinitialdelay,
196
+ ... windowout,
197
+ ... R2,
198
+ ... thesizes,
199
+ ... internalspaceshape,
200
+ ... numvalidspatiallocs,
201
+ ... theinputdata,
202
+ ... theheader,
203
+ ... theFitter,
204
+ ... fitmask,
205
+ ... lagtimes,
206
+ ... lagstrengths,
207
+ ... lagsigma,
208
+ ... failreason,
209
+ ... outmaparray,
210
+ ... trimmedcorrscale,
211
+ ... similaritytype,
212
+ ... thepass,
213
+ ... optiondict,
214
+ ... LGR,
215
+ ... TimingLGR,
216
+ ... simplefit=False,
217
+ ... upsampfac=8,
218
+ ... rt_floattype="float64",
219
+ ... )
220
+ """
73
221
  # Do a peak prefit if doing hybrid
74
222
  if optiondict["similaritymetric"] == "hybrid":
75
223
  LGR.info(f"\n\nPeak prefit calculation, pass {thepass}")
@@ -91,7 +239,6 @@ def fitSimFunc(
91
239
  interptype=optiondict["interptype"],
92
240
  showprogressbar=optiondict["showprogressbar"],
93
241
  chunksize=optiondict["mp_chunksize"],
94
- rt_floatset=rt_floatset,
95
242
  rt_floattype=rt_floattype,
96
243
  )
97
244
  tide_util.enablemkl(optiondict["mklthreads"], debug=optiondict["threaddebug"])
@@ -115,7 +262,9 @@ def fitSimFunc(
115
262
  delaystep = (trimmedcorrscale[1] - trimmedcorrscale[0]) / upsampfac
116
263
  for thevox in range(numvalidspatiallocs):
117
264
  fitmask[thevox] = 1
118
- upsampcorrout = tide_resample.upsample(corrout[thevox,:],1, upsampfac, intfac=True, dofilt=False)
265
+ upsampcorrout = tide_resample.upsample(
266
+ corrout[thevox, :], 1, upsampfac, intfac=True, dofilt=False
267
+ )
119
268
  if optiondict["bipolar"]:
120
269
  thismax = np.argmax(np.fabs(upsampcorrout))
121
270
  else:
@@ -164,7 +313,6 @@ def fitSimFunc(
164
313
  chunksize=optiondict["mp_chunksize"],
165
314
  despeckle_thresh=optiondict["despeckle_thresh"],
166
315
  initiallags=initlags,
167
- rt_floatset=rt_floatset,
168
316
  rt_floattype=rt_floattype,
169
317
  )
170
318
  tide_util.enablemkl(optiondict["mklthreads"], debug=optiondict["threaddebug"])
@@ -193,9 +341,9 @@ def fitSimFunc(
193
341
  outmaparray[validvoxels] = eval("lagtimes")[:]
194
342
 
195
343
  # find voxels to despeckle
196
- medianlags = ndimage.median_filter(outmaparray.reshape(nativespaceshape), 3).reshape(
197
- numspatiallocs
198
- )
344
+ medianlags = ndimage.median_filter(
345
+ outmaparray.reshape(nativespaceshape), 3
346
+ ).reshape(numspatiallocs)
199
347
  # voxels that we're happy with have initlags set to -1000000.0
200
348
  initlags = np.where(
201
349
  np.abs(outmaparray - medianlags) > optiondict["despeckle_thresh"],
@@ -232,10 +380,11 @@ def fitSimFunc(
232
380
  chunksize=optiondict["mp_chunksize"],
233
381
  despeckle_thresh=optiondict["despeckle_thresh"],
234
382
  initiallags=initlags,
235
- rt_floatset=rt_floatset,
236
383
  rt_floattype=rt_floattype,
237
384
  )
238
- tide_util.enablemkl(optiondict["mklthreads"], debug=optiondict["threaddebug"])
385
+ tide_util.enablemkl(
386
+ optiondict["mklthreads"], debug=optiondict["threaddebug"]
387
+ )
239
388
 
240
389
  voxelsprocessed_fc_ds += voxelsprocessed_thispass
241
390
  optiondict[
@@ -258,7 +407,9 @@ def fitSimFunc(
258
407
  0.0,
259
408
  )
260
409
  if optiondict["savedespecklemasks"] and (optiondict["despeckle_passes"] > 0):
261
- despecklesavemask = np.where(internaldespeckleincludemask[validvoxels] == 0.0, 0, 1)
410
+ despecklesavemask = np.where(
411
+ internaldespeckleincludemask[validvoxels] == 0.0, 0, 1
412
+ )
262
413
  if thepass == optiondict["passes"]:
263
414
  if theinputdata.filetype != "text":
264
415
  if theinputdata.filetype == "cifti":
@@ -17,13 +17,39 @@
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 rapidtide.io as tide_io
22
24
 
23
25
 
24
- def _get_parser():
26
+ def _get_parser() -> Any:
25
27
  """
26
- Argument parser for resamplenifti
28
+ Argument parser for resamplenifti.
29
+
30
+ Creates and configures an argument parser for the resamplenifti command-line tool
31
+ that changes the TR (repetition time) in a NIFTI header.
32
+
33
+ Returns
34
+ -------
35
+ argparse.ArgumentParser
36
+ Configured argument parser object with all required and optional arguments
37
+ for the resamplenifti tool.
38
+
39
+ Notes
40
+ -----
41
+ The parser is configured with:
42
+ - Required positional arguments: inputfile, outputfile, and outputtr
43
+ - Optional debug flag for additional output
44
+ - Program name set to "fixtr"
45
+ - Description explaining the purpose of changing TR in NIFTI headers
46
+
47
+ Examples
48
+ --------
49
+ >>> parser = _get_parser()
50
+ >>> args = parser.parse_args(['input.nii', 'output', '2.0'])
51
+ >>> print(args.inputfile)
52
+ 'input.nii'
27
53
  """
28
54
  parser = argparse.ArgumentParser(
29
55
  prog="fixtr",
@@ -45,7 +71,51 @@ def _get_parser():
45
71
  return parser
46
72
 
47
73
 
48
- def fixtr(args):
74
+ def fixtr(args: Any) -> None:
75
+ """
76
+ Fix the temporal resolution (TR) of a NIfTI file.
77
+
78
+ This function reads a NIfTI file and modifies its header to change the
79
+ temporal resolution (TR) while preserving the original data. The output
80
+ file is saved with the new TR value in the header.
81
+
82
+ Parameters
83
+ ----------
84
+ args : Any
85
+ An object containing the following attributes:
86
+ - inputfile : str
87
+ Path to the input NIfTI file
88
+ - outputfile : str
89
+ Path to the output NIfTI file
90
+ - outputtr : float
91
+ Desired output temporal resolution in seconds
92
+ - debug : bool, optional
93
+ If True, print debug information including input timepoints and TR
94
+
95
+ Returns
96
+ -------
97
+ None
98
+ This function does not return a value but saves the modified NIfTI file
99
+ to the specified output path.
100
+
101
+ Notes
102
+ -----
103
+ The function preserves the original data type and spatial dimensions of the
104
+ input file. The temporal dimension (t) in the output header is updated based
105
+ on the units specified in the input header. If the input header specifies
106
+ millisecond units, the output TR is converted from seconds to milliseconds.
107
+
108
+ Examples
109
+ --------
110
+ >>> class Args:
111
+ ... def __init__(self):
112
+ ... self.inputfile = "input.nii"
113
+ ... self.outputfile = "output.nii"
114
+ ... self.outputtr = 2.0
115
+ ... self.debug = False
116
+ >>> args = Args()
117
+ >>> fixtr(args)
118
+ """
49
119
  # get the input TR
50
120
  inputtr, numinputtrs = tide_io.fmritimeinfo(args.inputfile)
51
121
  if args.debug:
@@ -20,8 +20,11 @@ import argparse
20
20
  import platform
21
21
  import sys
22
22
  import time
23
+ from argparse import Namespace
24
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
23
25
 
24
26
  import numpy as np
27
+ from numpy.typing import NDArray
25
28
 
26
29
  import rapidtide.filter as tide_filt
27
30
  import rapidtide.io as tide_io
@@ -30,7 +33,33 @@ import rapidtide.util as tide_util
30
33
  import rapidtide.workflows.parser_funcs as pf
31
34
 
32
35
 
33
- def _get_parser():
36
+ def _get_parser() -> Any:
37
+ """
38
+ Construct and return an argument parser for the gmscalc tool.
39
+
40
+ This function sets up an `argparse.ArgumentParser` with required and optional
41
+ arguments needed to run the global mean signal calculation and filtering
42
+ pipeline. It includes support for specifying input data, output root, data mask,
43
+ normalization options, smoothing, and debugging.
44
+
45
+ Returns
46
+ -------
47
+ argparse.ArgumentParser
48
+ Configured argument parser with all required and optional arguments
49
+ for the gmscalc tool.
50
+
51
+ Notes
52
+ -----
53
+ The parser is configured with `allow_abbrev=False` to enforce full argument
54
+ names and avoid ambiguity.
55
+
56
+ Examples
57
+ --------
58
+ >>> parser = _get_parser()
59
+ >>> args = parser.parse_args(['data.nii', 'output_root'])
60
+ >>> print(args.datafile)
61
+ 'data.nii'
62
+ """
34
63
  parser = argparse.ArgumentParser(
35
64
  prog="gmscalc",
36
65
  description="Calculate the global mean signal, and filtered versions",
@@ -86,7 +115,54 @@ def _get_parser():
86
115
  return parser
87
116
 
88
117
 
89
- def makecommandlinelist(arglist, starttime, endtime, extra=None):
118
+ def makecommandlinelist(
119
+ arglist: Any, starttime: Any, endtime: Any, extra: Optional[Any] = None
120
+ ) -> None:
121
+ """
122
+ Create a list of command line information for logging purposes.
123
+
124
+ This function generates a list of descriptive strings containing processing
125
+ information including date, duration, version details, and the actual command
126
+ that was executed.
127
+
128
+ Parameters
129
+ ----------
130
+ arglist : Any
131
+ List of command line arguments to be joined into a command string.
132
+ starttime : Any
133
+ Start time of the process, typically a timestamp.
134
+ endtime : Any
135
+ End time of the process, typically a timestamp.
136
+ extra : Any, optional
137
+ Additional descriptive text to include in the output list. Default is None.
138
+
139
+ Returns
140
+ -------
141
+ list of str
142
+ List containing the following elements in order:
143
+ - Processing date and time
144
+ - Processing duration
145
+ - Node and version information
146
+ - Extra information (if provided)
147
+ - The actual command line string
148
+
149
+ Notes
150
+ -----
151
+ The function uses `time.strftime` to format the start time and `tide_util.version()`
152
+ to retrieve version information. The command line is constructed by joining
153
+ the `arglist` elements with spaces.
154
+
155
+ Examples
156
+ --------
157
+ >>> import time
158
+ >>> args = ['python', 'script.py', '--input', 'data.txt']
159
+ >>> start = time.time()
160
+ >>> # ... some processing ...
161
+ >>> end = time.time()
162
+ >>> info = makecommandlinelist(args, start, end)
163
+ >>> print(info[0])
164
+ '# Processed on Mon, 01 Jan 2024 12:00:00 UTC.'
165
+ """
90
166
  # get the processing date
91
167
  dateline = (
92
168
  "# Processed on "
@@ -123,7 +199,41 @@ def makecommandlinelist(arglist, starttime, endtime, extra=None):
123
199
  return [dateline, timeline, nodeline, commandline]
124
200
 
125
201
 
126
- def gmscalc_main():
202
+ def gmscalc_main() -> None:
203
+ """
204
+ Main function to calculate global mean signal (GMS) from fMRI data.
205
+
206
+ This function reads NIfTI-formatted fMRI data, applies optional smoothing,
207
+ masks the data if a mask is provided, and computes the global mean signal
208
+ across valid voxels. It then applies low-frequency (LFO) and high-frequency
209
+ (HF) filtering to the global signal and writes the results to text files.
210
+
211
+ The function uses the `tide_io` module for reading and writing data, and
212
+ `tide_filt` and `tide_math` for filtering and normalization.
213
+
214
+ Notes
215
+ -----
216
+ The function expects a command-line interface to be set up with `_get_parser()`
217
+ and uses `sys.argv` to parse arguments. It prints diagnostic information
218
+ during execution.
219
+
220
+ Examples
221
+ --------
222
+ Assuming the script is called as `gmscalc_main.py` and properly configured:
223
+
224
+ >>> gmscalc_main()
225
+
226
+ This will read the input data, perform processing, and write output files
227
+ with names based on the `outputroot` argument.
228
+
229
+ See Also
230
+ --------
231
+ tide_io.readfromnifti : Reads NIfTI files.
232
+ tide_io.writevec : Writes vectors to text files.
233
+ tide_filt.ssmooth : Applies spatial smoothing.
234
+ tide_filt.NoncausalFilter : Applies non-causal filtering.
235
+ tide_math.normalize : Normalizes a signal.
236
+ """
127
237
  try:
128
238
  args = _get_parser().parse_args()
129
239
  except SystemExit: