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
@@ -21,11 +21,39 @@ import glob
21
21
  import os
22
22
  import subprocess
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 rapidtide.externaltools as tide_extern
26
28
 
27
29
 
28
- def _get_parser():
30
+ def _get_parser() -> Any:
31
+ """
32
+ Create and configure an argument parser for the rapidtide2std command-line tool.
33
+
34
+ This function sets up an `argparse.ArgumentParser` with specific arguments
35
+ required for registering happy output maps to standard space. It defines
36
+ positional and optional arguments for input file roots, output directories,
37
+ and various transformation options.
38
+
39
+ Returns
40
+ -------
41
+ argparse.ArgumentParser
42
+ Configured argument parser object with defined arguments for
43
+ the rapidtide2std tool.
44
+
45
+ Notes
46
+ -----
47
+ The parser is configured with a program name, description, and usage string
48
+ specific to the rapidtide2std tool. It expects three positional arguments:
49
+ inputfileroot, outputdir, and featdirectory, followed by several optional
50
+ flags that control the registration process.
51
+
52
+ Examples
53
+ --------
54
+ >>> parser = _get_parser()
55
+ >>> args = parser.parse_args()
56
+ """
29
57
  # get the command line parameters
30
58
  parser = argparse.ArgumentParser(
31
59
  prog="rapidtide2std",
@@ -84,16 +112,74 @@ def _get_parser():
84
112
 
85
113
 
86
114
  def transformmaps(
87
- thepath,
88
- theoutputdir,
89
- subjroot,
90
- reftarget,
91
- xformfuncmat,
92
- warpfuncfile,
93
- thefmrimaps=None,
94
- theanatmaps=None,
95
- preponly=False,
96
- ):
115
+ thepath: Any,
116
+ theoutputdir: Any,
117
+ subjroot: Any,
118
+ reftarget: Any,
119
+ xformfuncmat: Any,
120
+ warpfuncfile: Any,
121
+ thefmrimaps: Optional[Any] = None,
122
+ theanatmaps: Optional[Any] = None,
123
+ preponly: bool = False,
124
+ ) -> None:
125
+ """
126
+ Apply spatial transformations to fMRI and anatomical maps from a happy dataset using FLIRT and/or
127
+ copy commands.
128
+
129
+ This function applies rigid-body and non-linear transformations to a set of fMRI and/or
130
+ anatomical maps, based on provided transformation matrices and warp fields. It supports
131
+ both functional and anatomical image processing pipelines.
132
+
133
+ Parameters
134
+ ----------
135
+ thepath : Any
136
+ Path to the directory containing input fMRI maps.
137
+ theoutputdir : Any
138
+ Directory where transformed maps will be saved.
139
+ subjroot : Any
140
+ Subject identifier used to construct input and output file names.
141
+ reftarget : Any
142
+ Reference image to which maps are transformed.
143
+ xformfuncmat : Any
144
+ Transformation matrix for functional-to-standard space alignment.
145
+ warpfuncfile : Any
146
+ Warp field file for non-linear functional-to-standard space transformation.
147
+ thefmrimaps : Optional[Any], default=None
148
+ List of fMRI map names to transform. If None, no fMRI maps are processed.
149
+ theanatmaps : Optional[Any], default=None
150
+ List of anatomical map names to transform. If None, no anatomical maps are processed.
151
+ preponly : bool, default=False
152
+ If True, only print the commands without executing them.
153
+
154
+ Returns
155
+ -------
156
+ None
157
+ This function does not return any value; it performs file I/O operations.
158
+
159
+ Notes
160
+ -----
161
+ - For fMRI maps, the function uses `tide_extern.makeflirtcmd` to generate and execute
162
+ FLIRT commands for transformation.
163
+ - For anatomical maps, it either copies the file or applies a transformation using
164
+ `tide_extern.makeflirtcmd`, depending on the `aligntohires` flag.
165
+ - If `preponly` is True, the commands are printed but not executed.
166
+ - The function assumes that input files exist and are named according to the
167
+ pattern: ``{subjroot}_{mapname}.nii.gz``.
168
+
169
+ Examples
170
+ --------
171
+ >>> transformmaps(
172
+ ... thepath="/data/subj1",
173
+ ... theoutputdir="/data/subj1/transformed",
174
+ ... subjroot="subj1",
175
+ ... reftarget="/data/templates/MNI152_T1_2mm.nii.gz",
176
+ ... xformfuncmat="/data/subj1/reg/func2standard.mat",
177
+ ... warpfuncfile="/data/subj1/reg/warpfield.nii.gz",
178
+ ... thefmrimaps=["bold", "mask"],
179
+ ... theanatmaps=["brain"],
180
+ ... preponly=False
181
+ ... )
182
+ """
97
183
  print("entering transformmaps with:")
98
184
  print(thepath)
99
185
  print(subjroot)
@@ -151,7 +237,53 @@ def transformmaps(
151
237
  print("no hires anatomic found - skipping")
152
238
 
153
239
 
154
- def happy2std(args):
240
+ def happy2std(args: Any) -> None:
241
+ """
242
+ Apply FSL-based spatial transformation to fMRI data and anatomical maps.
243
+
244
+ This function performs spatial normalization of fMRI data to either high-resolution
245
+ or standard MNI152 space, using FSL transformation matrices and warp fields. It supports
246
+ both linear and nonlinear transformations, and can process either a single file or
247
+ a set of files based on input arguments.
248
+
249
+ Parameters
250
+ ----------
251
+ args : Any
252
+ An object containing command-line arguments. Expected attributes include:
253
+ - featdirectory : str
254
+ Path to the FEAT directory containing registration files.
255
+ - aligntohires : bool
256
+ If True, align to high-resolution anatomical space; otherwise to standard MNI152.
257
+ - forcelinear : bool
258
+ If True, forces use of a linear transformation even if warp files are present.
259
+ - onefilename : str or None
260
+ If provided, process only this single file.
261
+ - preponly : bool
262
+ If True, print the FSL command without executing it.
263
+ - inputfileroot : str
264
+ Root path to input files for batch processing.
265
+ - outputdir : str
266
+ Output directory for transformed files.
267
+ - all : bool
268
+ If True, include additional fMRI maps in processing.
269
+
270
+ Returns
271
+ -------
272
+ None
273
+ This function does not return a value but may exit the program on error.
274
+
275
+ Notes
276
+ -----
277
+ This function requires the FSL environment variable ``FSLDIR`` to be set.
278
+ It relies on FSL tools like `applywarp` and `flirt` for transformations.
279
+ The function supports processing of both single files and batches of files
280
+ using glob patterns.
281
+
282
+ Examples
283
+ --------
284
+ >>> args = parse_args() # Assume args is parsed from command line
285
+ >>> happy2std(args)
286
+ """
155
287
  # make sure the appropriate transformation matrix and targets exist
156
288
  fsldir = os.environ.get("FSLDIR")
157
289
  if fsldir is None:
@@ -17,20 +17,56 @@
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 numpy as np
24
+ from numpy.typing import NDArray
22
25
 
23
26
  import rapidtide.io as tide_io
24
27
  import rapidtide.multiproc as tide_multiproc
25
28
  import rapidtide.workflows.parser_funcs as pf
26
29
 
27
30
  DEFAULT_ALIASEDCORRELATIONWIDTH = 5.0
28
- DEFAULT_DL_MODEL = "model_revised_tf2"
31
+ DEFAULT_PULSATILITYSIGMA = 6.0
32
+ DEFAULT_PULSATILITYTHRESHOLD = 0.5
33
+ DEFAULT_TF_DL_MODEL = "model_revised_tf2"
34
+ DEFAULT_PT_DL_MODEL = "model_cnn_pytorch"
29
35
 
30
36
 
31
- def _get_parser():
37
+ def _get_parser() -> Any:
32
38
  """
33
- Argument parser for happy
39
+ Create and configure an argument parser for the happy command-line tool.
40
+
41
+ This function sets up an `argparse.ArgumentParser` with numerous options for
42
+ configuring the hypersampling by analytic phase projection (HAPPY) pipeline.
43
+ It includes arguments for input files, processing steps, performance tuning,
44
+ preprocessing, cardiac and respiration estimation, output handling, and debugging.
45
+
46
+ Returns
47
+ -------
48
+ argparse.ArgumentParser
49
+ Configured argument parser with all supported command-line options.
50
+
51
+ Notes
52
+ -----
53
+ The parser includes multiple argument groups for different functional areas:
54
+ - Processing steps
55
+ - Performance
56
+ - Preprocessing
57
+ - Cardiac estimation tuning
58
+ - External cardiac waveform options
59
+ - External respiration waveform options
60
+ - Output processing
61
+ - Output options
62
+ - Phase projection tuning
63
+ - Miscellaneous options
64
+ - Debugging options
65
+
66
+ Examples
67
+ --------
68
+ >>> parser = _get_parser()
69
+ >>> args = parser.parse_args()
34
70
  """
35
71
  parser = argparse.ArgumentParser(
36
72
  prog="happy",
@@ -101,10 +137,10 @@ def _get_parser():
101
137
  dest="modelname",
102
138
  metavar="MODELNAME",
103
139
  help=(
104
- f"Use model MODELNAME for dl filter (default is {DEFAULT_DL_MODEL} - "
140
+ f"Use model MODELNAME for dl filter (default is {DEFAULT_PT_DL_MODEL} - "
105
141
  "from the revised NeuroImage paper.) "
106
142
  ),
107
- default=DEFAULT_DL_MODEL,
143
+ default=None,
108
144
  )
109
145
 
110
146
  # Performance
@@ -550,6 +586,31 @@ def _get_parser():
550
586
  help="Restrict cardiac waveform estimation to putative arteries only.",
551
587
  default=False,
552
588
  )
589
+ phase_proj_tuning.add_argument(
590
+ "--pulsatilitysigma",
591
+ dest="pulsatilitysigma",
592
+ action="store",
593
+ metavar="SIGMAINMM",
594
+ type=lambda x: pf.is_float(parser, x),
595
+ help=(
596
+ "Split pulsatility map spatial frequencies with a gaussian filter with sigma=SIGMAINMM. "
597
+ f"Default is {DEFAULT_PULSATILITYSIGMA}mm. "
598
+ ),
599
+ default=DEFAULT_PULSATILITYSIGMA,
600
+ )
601
+ phase_proj_tuning.add_argument(
602
+ "--pulsatilitythreshold",
603
+ dest="pulsatilitythreshold",
604
+ action="store",
605
+ metavar="THRESHPCT",
606
+ type=lambda x: pf.is_float(parser, x),
607
+ help=(
608
+ "Consider voxels with a high spatial frequency pulsatility above THRESHPCT percent "
609
+ "to be vessels. "
610
+ f"Default is {DEFAULT_PULSATILITYTHRESHOLD}mm. "
611
+ ),
612
+ default=DEFAULT_PULSATILITYSIGMA,
613
+ )
553
614
 
554
615
  # Add version options
555
616
  pf.addversionopts(parser)
@@ -563,7 +624,7 @@ def _get_parser():
563
624
  metavar="MASKNAME",
564
625
  help=(
565
626
  "Instead of dynamically generating a processing mask from the data, use "
566
- "the mask specified in the file MASKNAME. "
627
+ "the mask specified in the file MASKNAME. "
567
628
  "The mask must be a 3D NIFTI file with x, y, z dimensions matching the fMRI data. "
568
629
  ),
569
630
  default=None,
@@ -613,6 +674,13 @@ def _get_parser():
613
674
  help="Number of iterations for calculating Wright map. Set to 0 to disable.",
614
675
  default=0,
615
676
  )
677
+ misc_opts.add_argument(
678
+ "--usenewvesselmethod",
679
+ dest="useoriginalvesselmethod",
680
+ action="store_false",
681
+ help="Will use the new pulsatility method to find blood vessels. ",
682
+ default=True,
683
+ )
616
684
  pf.addtagopts(
617
685
  misc_opts,
618
686
  helptext="Additional key, value pairs to add to the info json file (useful for tracking analyses).",
@@ -635,6 +703,13 @@ def _get_parser():
635
703
  help="Disable data detrending. ",
636
704
  default=3,
637
705
  )
706
+ debug_opts.add_argument(
707
+ "--normvesselmap",
708
+ dest="unnormvesselmap",
709
+ action="store_false",
710
+ help="Find vessels using normalized phase projection. ",
711
+ default=True,
712
+ )
638
713
  debug_opts.add_argument(
639
714
  "--noorthog",
640
715
  dest="orthogonalize",
@@ -740,13 +815,57 @@ def _get_parser():
740
815
  help="Disable the congrid value cache completely.",
741
816
  default=True,
742
817
  )
818
+ debug_opts.add_argument(
819
+ "--usetensorflow",
820
+ dest="usepytorch",
821
+ action="store_false",
822
+ help=("Switch to the old style tensorflow deep learning filter"),
823
+ default=True,
824
+ )
825
+ debug_opts.add_argument(
826
+ "--focaldebug",
827
+ dest="focaldebug",
828
+ action="store_true",
829
+ help=("Enable targeted additional debugging output (used during development)."),
830
+ default=False,
831
+ )
743
832
 
744
833
  return parser
745
834
 
746
835
 
747
- def process_args(inputargs=None):
836
+ def process_args(inputargs: Optional[Any] = None) -> None:
748
837
  """
749
- Compile arguments for rapidtide workflow.
838
+ Compile arguments for happy workflow.
839
+
840
+ This function processes input arguments for the happy workflow, handling
841
+ argument parsing, command line formatting, default model selection, and post-processing
842
+ of various parameters. It also manages motion file specifications, multiprocessing
843
+ settings, and output level calculations.
844
+
845
+ Parameters
846
+ ----------
847
+ inputargs : optional
848
+ Input arguments to be processed. If None, arguments are parsed from the command line.
849
+ Default is None.
850
+
851
+ Returns
852
+ -------
853
+ args : argparse.Namespace
854
+ Processed arguments namespace containing all parsed and defaulted values.
855
+
856
+ Notes
857
+ -----
858
+ - If no model is specified, the function sets a default based on whether PyTorch or TensorFlow
859
+ is being used.
860
+ - The function writes formatted command line arguments to files for logging purposes.
861
+ - Multiprocessing is currently disabled due to instability.
862
+ - The output level is adjusted based on user-provided increments and decrements.
863
+
864
+ Examples
865
+ --------
866
+ >>> args = process_args()
867
+ >>> print(args.outputroot)
868
+ >>> print(args.modelname)
750
869
  """
751
870
  args, argstowrite = pf.setargs(_get_parser, inputargs=inputargs)
752
871
 
@@ -773,6 +892,14 @@ def process_args(inputargs=None):
773
892
  formattedcommandline[i] = prefix + formattedcommandline[i] + suffix
774
893
  tide_io.writevec(formattedcommandline, args.outputroot + "_formattedcommandline.txt")
775
894
 
895
+ # if user did not specify a model, set the default, depending on DL library
896
+ if args.modelname is None:
897
+ if args.usepytorch:
898
+ args.modelname = DEFAULT_PT_DL_MODEL
899
+ else:
900
+ args.modelname = DEFAULT_TF_DL_MODEL
901
+ print(f"No model specified. {args.usepytorch=}, so using {args.modelname}")
902
+
776
903
  if args.debug:
777
904
  print()
778
905
  print("before postprocessing")
@@ -788,12 +915,12 @@ def process_args(inputargs=None):
788
915
  args.upsamplefac = 100
789
916
  args.centric = True
790
917
  args.pulsereconstepsize = 0.01
791
- args.unnormvesselmap = True
792
918
  args.histlen = 100
793
919
  args.softvesselfrac = 0.4
794
920
  args.savecardiacnoise = True
795
921
  args.colnum = None
796
922
  args.colname = None
923
+ args.notchrolloff = 0.5
797
924
 
798
925
  # Additional argument parsing not handled by argparse
799
926
  # deal with notch filter logic
@@ -807,6 +934,8 @@ def process_args(inputargs=None):
807
934
  args.motionfilename = None
808
935
 
809
936
  # set the number of worker processes if multiprocessing
937
+ # Multiprocessing is very broken atm. Hard disable it.
938
+ # args.nprocs = 1
810
939
  if args.nprocs < 1:
811
940
  args.nprocs = tide_multiproc.maxcpus()
812
941
 
@@ -19,8 +19,11 @@
19
19
  import argparse
20
20
  import copy
21
21
  import sys
22
+ from argparse import Namespace
23
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
22
24
 
23
25
  import numpy as np
26
+ from numpy.typing import NDArray
24
27
  from tqdm import tqdm
25
28
 
26
29
  import rapidtide.io as tide_io
@@ -29,7 +32,47 @@ import rapidtide.util as tide_util
29
32
  import rapidtide.workflows.parser_funcs as pf
30
33
 
31
34
 
32
- def _get_parser():
35
+ def _get_parser() -> Any:
36
+ """
37
+ Generate and return an argument parser for the histnifti command-line tool.
38
+
39
+ This function constructs an `argparse.ArgumentParser` object configured with
40
+ all necessary arguments for processing NIFTI files and generating histograms
41
+ of their voxel values. It supports various options for controlling binning,
42
+ masking, normalization, and display behavior.
43
+
44
+ Returns
45
+ -------
46
+ argparse.ArgumentParser
47
+ Configured argument parser object ready to parse command-line arguments.
48
+
49
+ Notes
50
+ -----
51
+ The parser includes the following positional and optional arguments:
52
+
53
+ - Positional arguments:
54
+ - inputfile: Path to the input NIFTI file.
55
+ - outputroot: Root name for output files.
56
+
57
+ - Optional arguments:
58
+ - --histlen: Set histogram length to LEN (default: auto).
59
+ - --minval: Minimum bin value in histogram.
60
+ - --maxval: Maximum bin value in histogram.
61
+ - --robustrange: Use robust range (2nd to 98th percentile) for histogram limits.
62
+ - --transform: Replace data values with their percentile scores.
63
+ - --nozero: Exclude zero values from histogram.
64
+ - --nozerothresh: Threshold for considering values as zero (default: 0.01).
65
+ - --normhist: Return probability density instead of raw counts.
66
+ - --maskfile: Only process voxels within a 3D mask.
67
+ - --nodisplay: Do not display histogram.
68
+
69
+ Examples
70
+ --------
71
+ >>> parser = _get_parser()
72
+ >>> args = parser.parse_args(['input.nii', 'output_root'])
73
+ >>> print(args.inputfile)
74
+ 'input.nii'
75
+ """
33
76
  # get the command line parameters
34
77
  parser = argparse.ArgumentParser(
35
78
  prog="histnifti",
@@ -119,7 +162,80 @@ def _get_parser():
119
162
  return parser
120
163
 
121
164
 
122
- def histnifti(args):
165
+ def histnifti(args: Any) -> None:
166
+ """
167
+ Compute and save histograms, sorted data, and percentiles from NIfTI image data.
168
+
169
+ This function reads input NIfTI data and optionally a mask, computes histograms
170
+ for each voxel (or across all voxels if 3D), and saves sorted data, percentiles,
171
+ and histogram results as NIfTI files. It supports both 3D and 4D data processing.
172
+
173
+ Parameters
174
+ ----------
175
+ args : argparse.Namespace
176
+ Command-line arguments containing:
177
+ - inputfile : str
178
+ Path to the input NIfTI file.
179
+ - maskfile : str, optional
180
+ Path to the mask NIfTI file. If None, a full mask is generated.
181
+ - outputroot : str
182
+ Root name for output files.
183
+ - robustrange : bool
184
+ If True, use 2nd and 98th percentiles for histogram range.
185
+ - minval : float, optional
186
+ Minimum value for histogram range.
187
+ - maxval : float, optional
188
+ Maximum value for histogram range.
189
+ - histlen : int, optional
190
+ Number of histogram bins. If None, computed based on data size.
191
+ - nozero : bool
192
+ If True, exclude zero values from histogram calculation.
193
+ - nozerothresh : float
194
+ Threshold for excluding zero-like values when `nozero` is True.
195
+ - transform : bool
196
+ If True, apply a transformation to the data.
197
+ - display : bool
198
+ If True, display histogram plots.
199
+ - normhist : bool
200
+ If True, normalize histogram values.
201
+
202
+ Returns
203
+ -------
204
+ None
205
+ This function does not return a value but saves multiple NIfTI files:
206
+ - `<outputroot>_sorted.nii.gz`: Sorted time series data.
207
+ - `<outputroot>_pcts.nii.gz`: Percentile values.
208
+ - `<outputroot>_hists.nii.gz`: Histogram data per voxel.
209
+ - `<outputroot>_transformed.nii.gz`: Transformed data (if `transform` is True).
210
+ - `<outputroot>_hist.txt`: Histogram plot (if `display` is True).
211
+
212
+ Notes
213
+ -----
214
+ - For 4D data, the function computes histograms, sorted arrays, and percentiles
215
+ for each voxel.
216
+ - For 3D data, the function can compute a global histogram or apply a transformation.
217
+ - The function uses `tide_io` for reading/writing NIfTI files and `tide_stats` for
218
+ statistical operations.
219
+
220
+ Examples
221
+ --------
222
+ >>> import argparse
223
+ >>> args = argparse.Namespace(
224
+ ... inputfile='data.nii.gz',
225
+ ... maskfile=None,
226
+ ... outputroot='output',
227
+ ... robustrange=False,
228
+ ... minval=None,
229
+ ... maxval=None,
230
+ ... histlen=None,
231
+ ... nozero=False,
232
+ ... nozerothresh=0.0,
233
+ ... transform=False,
234
+ ... display=False,
235
+ ... normhist=False
236
+ ... )
237
+ >>> histnifti(args)
238
+ """
123
239
  # set default variable values
124
240
  thepercentiles = [0.2, 0.25, 0.5, 0.75, 0.98]
125
241
  thepvalnames = []
@@ -17,17 +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 numpy as np
24
+ from numpy.typing import NDArray
22
25
 
23
26
  import rapidtide.io as tide_io
24
27
  import rapidtide.stats as tide_stats
25
28
  import rapidtide.workflows.parser_funcs as pf
26
29
 
27
30
 
28
- def _get_parser():
31
+ def _get_parser() -> Any:
29
32
  """
30
- Argument parser for histtc
33
+ Argument parser for histtc.
34
+
35
+ This function constructs and returns an `argparse.ArgumentParser` object configured
36
+ for parsing command-line arguments for the `histtc` tool, which generates histograms
37
+ from timecourse data.
38
+
39
+ Returns
40
+ -------
41
+ argparse.ArgumentParser
42
+ Configured argument parser for histtc.
43
+
44
+ Notes
45
+ -----
46
+ The parser includes both required and optional arguments for specifying input/output
47
+ files, histogram bin settings, and various data filtering options.
48
+
49
+ Examples
50
+ --------
51
+ >>> parser = _get_parser()
52
+ >>> args = parser.parse_args(['--inputfilename', 'data.txt', '--outputroot', 'output'])
31
53
  """
32
54
  parser = argparse.ArgumentParser(
33
55
  prog="histtc",
@@ -108,7 +130,66 @@ def _get_parser():
108
130
  return parser
109
131
 
110
132
 
111
- def histtc(args):
133
+ def histtc(args: Any) -> None:
134
+ """
135
+ Compute and save a histogram of input data, optionally filtered and normalized.
136
+
137
+ This function reads input data from a text file, computes specified percentiles,
138
+ and generates a histogram with optional normalization and range settings.
139
+
140
+ Parameters
141
+ ----------
142
+ args : argparse.Namespace
143
+ An object containing the following attributes:
144
+ - inputfilename : str
145
+ Path to the input text file containing the data.
146
+ - debug : bool
147
+ If True, print debug information during execution.
148
+ - nozero : bool
149
+ If True, exclude values with absolute magnitude less than or equal to `nozerothresh`.
150
+ - nozerothresh : float
151
+ Threshold for excluding zero-like values when `nozero` is True.
152
+ - histlen : int
153
+ Number of bins for the histogram.
154
+ - outputroot : str
155
+ Root name for output files.
156
+ - robustrange : bool
157
+ If True, use robust range (2nd and 98th percentiles) for histogram.
158
+ - minval : float, optional
159
+ Minimum value for histogram range. If None, use data minimum.
160
+ - maxval : float, optional
161
+ Maximum value for histogram range. If None, use data maximum.
162
+ - normhist : bool
163
+ If True, normalize the histogram.
164
+
165
+ Returns
166
+ -------
167
+ None
168
+ This function does not return a value but saves a histogram to disk.
169
+
170
+ Notes
171
+ -----
172
+ The function uses `tide_io.readvectorsfromtextfile` to read input data and
173
+ `tide_stats.getfracvals` to compute percentiles. It then calls
174
+ `tide_stats.makeandsavehistogram` to generate and save the histogram.
175
+
176
+ Examples
177
+ --------
178
+ >>> import argparse
179
+ >>> args = argparse.Namespace(
180
+ ... inputfilename='data.txt',
181
+ ... debug=False,
182
+ ... nozero=True,
183
+ ... nozerothresh=1e-6,
184
+ ... histlen=50,
185
+ ... outputroot='output',
186
+ ... robustrange=False,
187
+ ... minval=None,
188
+ ... maxval=None,
189
+ ... normhist=True
190
+ ... )
191
+ >>> histtc(args)
192
+ """
112
193
  # set default variable values
113
194
  thepercentiles = [0.2, 0.25, 0.5, 0.75, 0.98]
114
195
  thepvalnames = []