rapidtide 3.0.11__py3-none-any.whl → 3.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 (139) 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 +191 -40
  7. rapidtide/calcsimfunc.py +245 -42
  8. rapidtide/correlate.py +1210 -393
  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 +19 -1
  13. rapidtide/data/examples/src/testglmfilt +5 -5
  14. rapidtide/data/examples/src/testhappy +25 -3
  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 +2225 -108
  24. rapidtide/dlfiltertorch.py +4843 -0
  25. rapidtide/externaltools.py +327 -12
  26. rapidtide/fMRIData_class.py +79 -40
  27. rapidtide/filter.py +1899 -810
  28. rapidtide/fit.py +2004 -574
  29. rapidtide/genericmultiproc.py +93 -18
  30. rapidtide/happy_supportfuncs.py +2044 -171
  31. rapidtide/helper_classes.py +584 -43
  32. rapidtide/io.py +2363 -370
  33. rapidtide/linfitfiltpass.py +341 -75
  34. rapidtide/makelaggedtcs.py +211 -20
  35. rapidtide/maskutil.py +423 -53
  36. rapidtide/miscmath.py +827 -121
  37. rapidtide/multiproc.py +210 -22
  38. rapidtide/patchmatch.py +234 -33
  39. rapidtide/peakeval.py +32 -30
  40. rapidtide/ppgproc.py +2203 -0
  41. rapidtide/qualitycheck.py +352 -39
  42. rapidtide/refinedelay.py +422 -57
  43. rapidtide/refineregressor.py +498 -184
  44. rapidtide/resample.py +671 -185
  45. rapidtide/scripts/applyppgproc.py +28 -0
  46. rapidtide/simFuncClasses.py +1052 -77
  47. rapidtide/simfuncfit.py +260 -46
  48. rapidtide/stats.py +540 -238
  49. rapidtide/tests/happycomp +9 -0
  50. rapidtide/tests/test_dlfiltertorch.py +627 -0
  51. rapidtide/tests/test_findmaxlag.py +24 -8
  52. rapidtide/tests/test_fullrunhappy_v1.py +0 -2
  53. rapidtide/tests/test_fullrunhappy_v2.py +0 -2
  54. rapidtide/tests/test_fullrunhappy_v3.py +1 -0
  55. rapidtide/tests/test_fullrunhappy_v4.py +2 -2
  56. rapidtide/tests/test_fullrunrapidtide_v7.py +1 -1
  57. rapidtide/tests/test_simroundtrip.py +8 -8
  58. rapidtide/tests/utils.py +9 -8
  59. rapidtide/tidepoolTemplate.py +142 -38
  60. rapidtide/tidepoolTemplate_alt.py +165 -44
  61. rapidtide/tidepoolTemplate_big.py +189 -52
  62. rapidtide/util.py +1217 -118
  63. rapidtide/voxelData.py +684 -37
  64. rapidtide/wiener.py +19 -12
  65. rapidtide/wiener2.py +113 -7
  66. rapidtide/wiener_doc.py +255 -0
  67. rapidtide/workflows/adjustoffset.py +105 -3
  68. rapidtide/workflows/aligntcs.py +85 -2
  69. rapidtide/workflows/applydlfilter.py +87 -10
  70. rapidtide/workflows/applyppgproc.py +522 -0
  71. rapidtide/workflows/atlasaverage.py +210 -47
  72. rapidtide/workflows/atlastool.py +100 -3
  73. rapidtide/workflows/calcSimFuncMap.py +294 -64
  74. rapidtide/workflows/calctexticc.py +201 -9
  75. rapidtide/workflows/ccorrica.py +97 -4
  76. rapidtide/workflows/cleanregressor.py +168 -29
  77. rapidtide/workflows/delayvar.py +163 -10
  78. rapidtide/workflows/diffrois.py +81 -3
  79. rapidtide/workflows/endtidalproc.py +144 -4
  80. rapidtide/workflows/fdica.py +195 -15
  81. rapidtide/workflows/filtnifti.py +70 -3
  82. rapidtide/workflows/filttc.py +74 -3
  83. rapidtide/workflows/fitSimFuncMap.py +206 -48
  84. rapidtide/workflows/fixtr.py +73 -3
  85. rapidtide/workflows/gmscalc.py +113 -3
  86. rapidtide/workflows/happy.py +801 -199
  87. rapidtide/workflows/happy2std.py +144 -12
  88. rapidtide/workflows/happy_parser.py +138 -9
  89. rapidtide/workflows/histnifti.py +118 -2
  90. rapidtide/workflows/histtc.py +84 -3
  91. rapidtide/workflows/linfitfilt.py +117 -4
  92. rapidtide/workflows/localflow.py +328 -28
  93. rapidtide/workflows/mergequality.py +79 -3
  94. rapidtide/workflows/niftidecomp.py +322 -18
  95. rapidtide/workflows/niftistats.py +174 -4
  96. rapidtide/workflows/pairproc.py +88 -2
  97. rapidtide/workflows/pairwisemergenifti.py +85 -2
  98. rapidtide/workflows/parser_funcs.py +1421 -40
  99. rapidtide/workflows/physiofreq.py +137 -11
  100. rapidtide/workflows/pixelcomp.py +208 -5
  101. rapidtide/workflows/plethquality.py +103 -21
  102. rapidtide/workflows/polyfitim.py +151 -11
  103. rapidtide/workflows/proj2flow.py +75 -2
  104. rapidtide/workflows/rankimage.py +111 -4
  105. rapidtide/workflows/rapidtide.py +272 -15
  106. rapidtide/workflows/rapidtide2std.py +98 -2
  107. rapidtide/workflows/rapidtide_parser.py +109 -9
  108. rapidtide/workflows/refineDelayMap.py +143 -33
  109. rapidtide/workflows/refineRegressor.py +682 -93
  110. rapidtide/workflows/regressfrommaps.py +152 -31
  111. rapidtide/workflows/resamplenifti.py +85 -3
  112. rapidtide/workflows/resampletc.py +91 -3
  113. rapidtide/workflows/retrolagtcs.py +98 -6
  114. rapidtide/workflows/retroregress.py +165 -9
  115. rapidtide/workflows/roisummarize.py +173 -5
  116. rapidtide/workflows/runqualitycheck.py +71 -3
  117. rapidtide/workflows/showarbcorr.py +147 -4
  118. rapidtide/workflows/showhist.py +86 -2
  119. rapidtide/workflows/showstxcorr.py +160 -3
  120. rapidtide/workflows/showtc.py +159 -3
  121. rapidtide/workflows/showxcorrx.py +184 -4
  122. rapidtide/workflows/showxy.py +185 -15
  123. rapidtide/workflows/simdata.py +262 -36
  124. rapidtide/workflows/spatialfit.py +77 -2
  125. rapidtide/workflows/spatialmi.py +251 -27
  126. rapidtide/workflows/spectrogram.py +305 -32
  127. rapidtide/workflows/synthASL.py +154 -3
  128. rapidtide/workflows/tcfrom2col.py +76 -2
  129. rapidtide/workflows/tcfrom3col.py +74 -2
  130. rapidtide/workflows/tidepool.py +2969 -130
  131. rapidtide/workflows/utils.py +19 -14
  132. rapidtide/workflows/utils_doc.py +293 -0
  133. rapidtide/workflows/variabilityizer.py +116 -3
  134. {rapidtide-3.0.11.dist-info → rapidtide-3.1.dist-info}/METADATA +3 -2
  135. {rapidtide-3.0.11.dist-info → rapidtide-3.1.dist-info}/RECORD +139 -122
  136. {rapidtide-3.0.11.dist-info → rapidtide-3.1.dist-info}/entry_points.txt +1 -0
  137. {rapidtide-3.0.11.dist-info → rapidtide-3.1.dist-info}/WHEEL +0 -0
  138. {rapidtide-3.0.11.dist-info → rapidtide-3.1.dist-info}/licenses/LICENSE +0 -0
  139. {rapidtide-3.0.11.dist-info → rapidtide-3.1.dist-info}/top_level.txt +0 -0
rapidtide/refinedelay.py CHANGED
@@ -16,8 +16,11 @@
16
16
  # limitations under the License.
17
17
  #
18
18
  #
19
+ from typing import Any, Callable, Optional, Tuple, Union
20
+
19
21
  import numpy as np
20
22
  import numpy.polynomial.polynomial as poly
23
+ from numpy.typing import ArrayLike, NDArray
21
24
  from scipy.interpolate import CubicSpline, UnivariateSpline
22
25
  from scipy.ndimage import median_filter
23
26
  from statsmodels.robust import mad
@@ -29,31 +32,142 @@ import rapidtide.workflows.regressfrommaps as tide_regressfrommaps
29
32
  global ratiotooffsetfunc, funcoffsets, maplimits
30
33
 
31
34
 
32
- def smooth(y, box_pts):
35
+ def smooth(y: NDArray, box_pts: int) -> NDArray:
36
+ """Apply a simple moving average smooth to the input array.
37
+
38
+ This function performs convolution with a uniform boxcar filter to smooth
39
+ the input data. The smoothing is applied using the 'same' mode which
40
+ returns an array of the same length as the input.
41
+
42
+ Parameters
43
+ ----------
44
+ y : NDArray
45
+ Input array to be smoothed.
46
+ box_pts : int
47
+ Number of points in the smoothing window. Must be a positive integer.
48
+
49
+ Returns
50
+ -------
51
+ NDArray
52
+ Smoothed array of the same shape as input `y`.
53
+
54
+ Notes
55
+ -----
56
+ The smoothing is performed using numpy's convolve function with a boxcar
57
+ filter of uniform weights. The 'same' mode ensures the output has the
58
+ same length as the input, with edge effects handled by padding.
59
+
60
+ Examples
61
+ --------
62
+ >>> import numpy as np
63
+ >>> data = np.array([1, 2, 3, 4, 5])
64
+ >>> smooth(data, 3)
65
+ array([1.33333333, 2.33333333, 3.33333333, 4.33333333, 5.33333333])
66
+ """
33
67
  box = np.ones(box_pts) / box_pts
34
68
  y_smooth = np.convolve(y, box, mode="same")
35
69
  return y_smooth
36
70
 
37
71
 
38
72
  def trainratiotooffset(
39
- lagtcgenerator,
40
- timeaxis,
41
- outputname,
42
- outputlevel,
43
- trainlagmin=0.0,
44
- trainlagmax=0.0,
45
- trainlagstep=0.5,
46
- mindelay=-3.0,
47
- maxdelay=3.0,
48
- numpoints=501,
49
- smoothpts=3,
50
- edgepad=5,
51
- regressderivs=1,
52
- LGR=None,
53
- TimingLGR=None,
54
- verbose=False,
55
- debug=False,
56
- ):
73
+ lagtcgenerator: Any,
74
+ timeaxis: NDArray,
75
+ outputname: str,
76
+ outputlevel: str,
77
+ trainlagmin: float = 0.0,
78
+ trainlagmax: float = 0.0,
79
+ trainlagstep: float = 0.5,
80
+ mindelay: float = -3.0,
81
+ maxdelay: float = 3.0,
82
+ numpoints: int = 501,
83
+ smoothpts: int = 3,
84
+ edgepad: int = 5,
85
+ regressderivs: int = 1,
86
+ LGR: Optional[Any] = None,
87
+ TimingLGR: Optional[Any] = None,
88
+ verbose: bool = False,
89
+ debug: bool = False,
90
+ ) -> None:
91
+ """
92
+ Train a mapping from derivative ratio to delay offset using lagged time courses.
93
+
94
+ This function generates synthetic fMRI data by applying time shifts to the
95
+ input lagged time course generator and computes derivative ratios to estimate
96
+ the relationship between the ratio of derivatives and the corresponding delay.
97
+ The resulting mapping is stored globally and optionally saved to BIDS-style
98
+ TSV files.
99
+
100
+ Parameters
101
+ ----------
102
+ lagtcgenerator : Any
103
+ An object that provides the `yfromx` method for generating lagged time courses.
104
+ timeaxis : numpy.ndarray
105
+ The time axis (in seconds) for the fMRI data.
106
+ outputname : str
107
+ Base name for output files (e.g., BIDS entity).
108
+ outputlevel : str
109
+ Determines level of output; valid values are "min", "onlyregressors", or others.
110
+ trainlagmin : float, optional
111
+ Minimum lag value for training offsets (default is 0.0).
112
+ trainlagmax : float, optional
113
+ Maximum lag value for training offsets (default is 0.0).
114
+ trainlagstep : float, optional
115
+ Step size for generating training offsets (default is 0.5).
116
+ mindelay : float, optional
117
+ Minimum delay to consider in the delay map (default is -3.0).
118
+ maxdelay : float, optional
119
+ Maximum delay to consider in the delay map (default is 3.0).
120
+ numpoints : int, optional
121
+ Number of points in the delay grid (default is 501).
122
+ smoothpts : int, optional
123
+ Number of points for smoothing (default is 3).
124
+ edgepad : int, optional
125
+ Padding applied to edges during processing (default is 5).
126
+ regressderivs : int, optional
127
+ Number of derivatives to regress (default is 1).
128
+ LGR : Optional[Any], optional
129
+ Logging object for verbose output (default is None).
130
+ TimingLGR : Optional[Any], optional
131
+ Timing logging object (default is None).
132
+ verbose : bool, optional
133
+ Enable verbose logging if True (default is False).
134
+ debug : bool, optional
135
+ Enable debug output if True (default is False).
136
+
137
+ Returns
138
+ -------
139
+ None
140
+ This function does not return any value but updates global variables:
141
+ - `ratiotooffsetfunc`: List of cubic spline interpolants mapping ratio to delay.
142
+ - `funcoffsets`: List of offset values used in training.
143
+ - `maplimits`: Tuple of minimum and maximum ratio values for the mapping.
144
+
145
+ Notes
146
+ -----
147
+ - The function uses `getderivratios` to compute derivative ratios.
148
+ - Output files are written in BIDS TSV format.
149
+ - The mapping function is saved globally for future use.
150
+
151
+ Examples
152
+ --------
153
+ >>> trainratiotooffset(
154
+ ... lagtcgenerator=generator,
155
+ ... timeaxis=time_axis,
156
+ ... outputname="sub-01",
157
+ ... outputlevel="full",
158
+ ... trainlagmin=-1.0,
159
+ ... trainlagmax=1.0,
160
+ ... trainlagstep=0.2,
161
+ ... mindelay=-2.0,
162
+ ... maxdelay=2.0,
163
+ ... numpoints=201,
164
+ ... smoothpts=5,
165
+ ... edgepad=3,
166
+ ... regressderivs=2,
167
+ ... verbose=True,
168
+ ... debug=False
169
+ ... )
170
+ """
57
171
  global ratiotooffsetfunc, funcoffsets, maplimits
58
172
 
59
173
  if debug:
@@ -270,7 +384,49 @@ def trainratiotooffset(
270
384
  )
271
385
 
272
386
 
273
- def ratiotodelay(theratio, offset=0.0, debug=False):
387
+ def ratiotodelay(theratio: float, offset: float = 0.0, debug: bool = False) -> Tuple[float, float]:
388
+ """
389
+ Convert a ratio to a delay value using lookup tables and offset compensation.
390
+
391
+ This function maps a given ratio to a corresponding delay value by interpolating
392
+ between pre-calculated offset values. It handles boundary conditions by clamping
393
+ the ratio to predefined limits and applies offset compensation for accurate
394
+ delay calculation.
395
+
396
+ Parameters
397
+ ----------
398
+ theratio : float
399
+ The input ratio value to be converted to delay. This value is used as input
400
+ to the lookup function after being clamped to the valid range.
401
+ offset : float, optional
402
+ Offset value used for compensation and lookup table selection. Default is 0.0.
403
+ debug : bool, optional
404
+ Flag to enable debug output. Default is False.
405
+
406
+ Returns
407
+ -------
408
+ Tuple[float, float]
409
+ A tuple containing:
410
+ - The calculated delay value based on the ratio and offset
411
+ - The closest offset value used for the lookup
412
+
413
+ Notes
414
+ -----
415
+ The function uses global variables `ratiotooffsetfunc`, `funcoffsets`, and `maplimits`:
416
+ - `ratiotooffsetfunc`: List of lookup functions for different offset values
417
+ - `funcoffsets`: List of pre-calculated offset values
418
+ - `maplimits`: Tuple containing minimum and maximum valid ratio limits
419
+
420
+ Examples
421
+ --------
422
+ >>> result = ratiotodelay(0.5, offset=0.1)
423
+ >>> print(result)
424
+ (0.48, 0.1)
425
+
426
+ >>> result = ratiotodelay(1.5, offset=0.0)
427
+ >>> print(result)
428
+ (0.95, 0.0)
429
+ """
274
430
  global ratiotooffsetfunc, funcoffsets, maplimits
275
431
 
276
432
  # find the closest calculated offset
@@ -300,7 +456,56 @@ def ratiotodelay(theratio, offset=0.0, debug=False):
300
456
  )
301
457
 
302
458
 
303
- def coffstodelay(thecoffs, mindelay=-3.0, maxdelay=3.0, debug=False):
459
+ def coffstodelay(
460
+ thecoffs: NDArray, mindelay: float = -3.0, maxdelay: float = 3.0, debug: bool = False
461
+ ) -> float:
462
+ """
463
+ Convert polynomial coefficients to delay value by finding roots within specified bounds.
464
+
465
+ This function constructs a polynomial from the given coefficients and finds its roots
466
+ within the specified delay range. It returns the root closest to zero that lies
467
+ within the valid range, or 0.0 if no valid roots are found.
468
+
469
+ Parameters
470
+ ----------
471
+ thecoffs : NDArray
472
+ Array of polynomial coefficients (excluding the leading 1.0 term).
473
+ mindelay : float, optional
474
+ Minimum allowed delay value, default is -3.0.
475
+ maxdelay : float, optional
476
+ Maximum allowed delay value, default is 3.0.
477
+ debug : bool, optional
478
+ If True, prints debugging information about root selection process,
479
+ default is False.
480
+
481
+ Returns
482
+ -------
483
+ float
484
+ The selected delay value (root closest to zero within bounds),
485
+ or 0.0 if no valid roots are found.
486
+
487
+ Notes
488
+ -----
489
+ The function constructs a polynomial with coefficients [1.0, *thecoffs] and
490
+ finds all roots within the interval [mindelay, maxdelay]. Only real roots
491
+ within the specified bounds are considered valid candidates.
492
+
493
+ Examples
494
+ --------
495
+ >>> import numpy as np
496
+ >>> coeffs = np.array([0.5, -1.0])
497
+ >>> delay = coffstodelay(coeffs, mindelay=-2.0, maxdelay=2.0)
498
+ >>> print(delay)
499
+ 0.5
500
+
501
+ >>> coeffs = np.array([1.0, 0.0, -1.0])
502
+ >>> delay = coffstodelay(coeffs, mindelay=-1.0, maxdelay=1.0, debug=True)
503
+ keeping root 0 (1.0)
504
+ keeping root 1 (-1.0)
505
+ chosen = -1.0
506
+ >>> print(delay)
507
+ -1.0
508
+ """
304
509
  justaone = np.array([1.0], dtype=thecoffs.dtype)
305
510
  allcoffs = np.concatenate((justaone, thecoffs))
306
511
  theroots = (poly.Polynomial(allcoffs, domain=(mindelay, maxdelay))).roots()
@@ -329,31 +534,132 @@ def coffstodelay(thecoffs, mindelay=-3.0, maxdelay=3.0, debug=False):
329
534
 
330
535
 
331
536
  def getderivratios(
332
- fmri_data_valid,
333
- validvoxels,
334
- initial_fmri_x,
335
- lagtimes,
336
- fitmask,
337
- genlagtc,
338
- mode,
339
- outputname,
340
- oversamptr,
341
- sLFOfitmean,
342
- rvalue,
343
- r2value,
344
- fitNorm,
345
- fitcoeff,
346
- movingsignal,
347
- lagtc,
348
- filtereddata,
349
- LGR,
350
- TimingLGR,
351
- optiondict,
352
- regressderivs=1,
353
- starttr=None,
354
- endtr=None,
355
- debug=False,
356
- ):
537
+ fmri_data_valid: NDArray,
538
+ validvoxels: NDArray,
539
+ initial_fmri_x: NDArray,
540
+ lagtimes: NDArray,
541
+ fitmask: NDArray,
542
+ genlagtc: Any,
543
+ mode: str,
544
+ outputname: str,
545
+ oversamptr: float,
546
+ sLFOfitmean: NDArray,
547
+ rvalue: NDArray,
548
+ r2value: NDArray,
549
+ fitNorm: NDArray,
550
+ fitcoeff: NDArray,
551
+ movingsignal: NDArray,
552
+ lagtc: NDArray,
553
+ filtereddata: NDArray,
554
+ LGR: Optional[Any],
555
+ TimingLGR: Optional[Any],
556
+ optiondict: dict,
557
+ regressderivs: int = 1,
558
+ starttr: Optional[int] = None,
559
+ endtr: Optional[int] = None,
560
+ debug: bool = False,
561
+ ) -> Tuple[NDArray, NDArray]:
562
+ """
563
+ Compute the ratio of the first (or higher-order) derivative of regressors to the main regressor.
564
+
565
+ This function performs regression analysis on fMRI data using lagged timecourses and
566
+ calculates the ratio of each derivative regressor to the main (zeroth-order) regressor.
567
+ It is typically used in the context of hemodynamic response function (HRF) modeling and
568
+ temporal filtering.
569
+
570
+ Parameters
571
+ ----------
572
+ fmri_data_valid : NDArray
573
+ Valid fMRI data (voxels x timepoints).
574
+ validvoxels : NDArray
575
+ Boolean mask indicating valid voxels.
576
+ initial_fmri_x : NDArray
577
+ Initial fMRI design matrix (timepoints x regressors).
578
+ lagtimes : NDArray
579
+ Array of lag times for generating lagged regressors.
580
+ fitmask : NDArray
581
+ Mask for fitting regressors.
582
+ genlagtc : Any
583
+ Function or object for generating lagged timecourses.
584
+ mode : str
585
+ Regression mode (e.g., 'ols', 'wls').
586
+ outputname : str
587
+ Name of the output file or identifier.
588
+ oversamptr : float
589
+ Oversampling factor for temporal resolution.
590
+ sLFOfitmean : NDArray
591
+ Mean of the low-frequency fit.
592
+ rvalue : NDArray
593
+ R-values from regression.
594
+ r2value : NDArray
595
+ R-squared values from regression.
596
+ fitNorm : NDArray
597
+ Normalization factors from regression.
598
+ fitcoeff : NDArray
599
+ Regression coefficients (voxels x regressors).
600
+ movingsignal : NDArray
601
+ Moving signal data.
602
+ lagtc : NDArray
603
+ Lagged timecourses.
604
+ filtereddata : NDArray
605
+ Filtered fMRI data.
606
+ LGR : Optional[Any]
607
+ LGR object for temporal filtering.
608
+ TimingLGR : Optional[Any]
609
+ Timing LGR object for temporal filtering.
610
+ optiondict : dict
611
+ Dictionary of options for regression and processing.
612
+ regressderivs : int, optional
613
+ Number of derivative regressors to include (default is 1).
614
+ starttr : Optional[int], optional
615
+ Start timepoint for processing (default is 0).
616
+ endtr : Optional[int], optional
617
+ End timepoint for processing (default is number of timepoints).
618
+ debug : bool, optional
619
+ If True, print debug information (default is False).
620
+
621
+ Returns
622
+ -------
623
+ Tuple[NDArray, NDArray]
624
+ A tuple containing:
625
+ - `regressderivratios`: Array of derivative-to-main regressor ratios (regressors x voxels).
626
+ - `rvalue`: R-values from regression (same as input `rvalue`).
627
+
628
+ Notes
629
+ -----
630
+ - The function uses `tide_regressfrommaps.regressfrommaps` internally for regression.
631
+ - Derivative ratios are computed as `fitcoeff[:, i+1] / fitcoeff[:, 0]` for i in 0 to `regressderivs-1`.
632
+ - NaN values are replaced with 0 using `np.nan_to_num`.
633
+
634
+ Examples
635
+ --------
636
+ >>> ratios, rvals = getderivratios(
637
+ ... fmri_data_valid,
638
+ ... validvoxels,
639
+ ... initial_fmri_x,
640
+ ... lagtimes,
641
+ ... fitmask,
642
+ ... genlagtc,
643
+ ... 'ols',
644
+ ... 'output',
645
+ ... 2.0,
646
+ ... sLFOfitmean,
647
+ ... rvalue,
648
+ ... r2value,
649
+ ... fitNorm,
650
+ ... fitcoeff,
651
+ ... movingsignal,
652
+ ... lagtc,
653
+ ... filtereddata,
654
+ ... None,
655
+ ... None,
656
+ ... optiondict,
657
+ ... regressderivs=2,
658
+ ... starttr=0,
659
+ ... endtr=100,
660
+ ... debug=False
661
+ ... )
662
+ """
357
663
  if starttr is None:
358
664
  starttr = 0
359
665
  if endtr is None:
@@ -413,17 +719,76 @@ def getderivratios(
413
719
 
414
720
 
415
721
  def filterderivratios(
416
- regressderivratios,
417
- nativespaceshape,
418
- validvoxels,
419
- thedims,
420
- patchthresh=3.0,
421
- gausssigma=0,
422
- filetype="nifti",
423
- rt_floattype="float64",
424
- verbose=True,
425
- debug=False,
426
- ):
722
+ regressderivratios: NDArray,
723
+ nativespaceshape: Tuple[int, ...],
724
+ validvoxels: NDArray,
725
+ thedims: Tuple[float, ...],
726
+ patchthresh: float = 3.0,
727
+ gausssigma: float = 0,
728
+ filetype: str = "nifti",
729
+ rt_floattype: str = "float64",
730
+ verbose: bool = True,
731
+ debug: bool = False,
732
+ ) -> Tuple[NDArray, NDArray, float]:
733
+ """
734
+ Filter derivative ratios using median absolute deviation (MAD) and optional smoothing.
735
+
736
+ This function applies a filtering procedure to regression derivative ratios to
737
+ identify and correct outliers. It uses median filtering and compares deviations
738
+ from the median using the median absolute deviation (MAD). Optionally, Gaussian
739
+ smoothing is applied to the filtered data.
740
+
741
+ Parameters
742
+ ----------
743
+ regressderivratios : ndarray
744
+ Array of regression derivative ratios to be filtered.
745
+ nativespaceshape : tuple of int
746
+ Shape of the native space (e.g., (nx, ny, nz)).
747
+ validvoxels : ndarray
748
+ Boolean or integer array indicating valid voxels in the data.
749
+ thedims : tuple of float
750
+ Voxel dimensions (dx, dy, dz) used for Gaussian smoothing.
751
+ patchthresh : float, optional
752
+ Threshold for outlier detection in units of MAD. Default is 3.0.
753
+ gausssigma : float, optional
754
+ Standard deviation for Gaussian smoothing. If 0, no smoothing is applied.
755
+ Default is 0.
756
+ filetype : str, optional
757
+ File type for output mapping. If not "nifti", no median filtering is applied.
758
+ Default is "nifti".
759
+ rt_floattype : str, optional
760
+ Data type for the output arrays. Default is "float64".
761
+ verbose : bool, optional
762
+ If True, print diagnostic information. Default is True.
763
+ debug : bool, optional
764
+ If True, enable debug printing. Default is False.
765
+
766
+ Returns
767
+ -------
768
+ medfilt : ndarray
769
+ Median-filtered version of the input `regressderivratios`.
770
+ filteredarray : ndarray
771
+ Final filtered array with outliers replaced by median values.
772
+ themad : float
773
+ Median absolute deviation of the input `regressderivratios`.
774
+
775
+ Notes
776
+ -----
777
+ - The function uses `median_filter` from `scipy.ndimage` for spatial filtering.
778
+ - If `filetype` is "nifti", the input data is first mapped to a destination array
779
+ using `tide_io.makedestarray` and `tide_io.populatemap`.
780
+ - Gaussian smoothing is applied using `tide_filt.ssmooth` if `gausssigma > 0`.
781
+
782
+ Examples
783
+ --------
784
+ >>> import numpy as np
785
+ >>> from scipy.ndimage import median_filter
786
+ >>> # Assume inputs are prepared
787
+ >>> medfilt, filtered, mad_val = filterderivratios(
788
+ ... regressderivratios, nativespaceshape, validvoxels, thedims,
789
+ ... patchthresh=3.0, gausssigma=1.0, verbose=True
790
+ ... )
791
+ """
427
792
 
428
793
  if debug:
429
794
  print("filterderivratios:")