rapidtide 3.0.10__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 (141) hide show
  1. rapidtide/Colortables.py +492 -27
  2. rapidtide/OrthoImageItem.py +1053 -47
  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 +30 -1
  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/data/reference/JHU-ArterialTerritoriesNoVent-LVL1_space-MNI152NLin2009cAsym_2mm.nii.gz +0 -0
  23. rapidtide/data/reference/JHU-ArterialTerritoriesNoVent-LVL1_space-MNI152NLin2009cAsym_2mm_mask.nii.gz +0 -0
  24. rapidtide/decorators.py +91 -0
  25. rapidtide/dlfilter.py +2225 -108
  26. rapidtide/dlfiltertorch.py +4843 -0
  27. rapidtide/externaltools.py +327 -12
  28. rapidtide/fMRIData_class.py +79 -40
  29. rapidtide/filter.py +1899 -810
  30. rapidtide/fit.py +2004 -574
  31. rapidtide/genericmultiproc.py +93 -18
  32. rapidtide/happy_supportfuncs.py +2044 -171
  33. rapidtide/helper_classes.py +584 -43
  34. rapidtide/io.py +2363 -370
  35. rapidtide/linfitfiltpass.py +341 -75
  36. rapidtide/makelaggedtcs.py +211 -20
  37. rapidtide/maskutil.py +423 -53
  38. rapidtide/miscmath.py +827 -121
  39. rapidtide/multiproc.py +210 -22
  40. rapidtide/patchmatch.py +234 -33
  41. rapidtide/peakeval.py +32 -30
  42. rapidtide/ppgproc.py +2203 -0
  43. rapidtide/qualitycheck.py +352 -39
  44. rapidtide/refinedelay.py +422 -57
  45. rapidtide/refineregressor.py +498 -184
  46. rapidtide/resample.py +671 -185
  47. rapidtide/scripts/applyppgproc.py +28 -0
  48. rapidtide/simFuncClasses.py +1052 -77
  49. rapidtide/simfuncfit.py +260 -46
  50. rapidtide/stats.py +540 -238
  51. rapidtide/tests/happycomp +9 -0
  52. rapidtide/tests/test_dlfiltertorch.py +627 -0
  53. rapidtide/tests/test_findmaxlag.py +24 -8
  54. rapidtide/tests/test_fullrunhappy_v1.py +0 -2
  55. rapidtide/tests/test_fullrunhappy_v2.py +0 -2
  56. rapidtide/tests/test_fullrunhappy_v3.py +1 -0
  57. rapidtide/tests/test_fullrunhappy_v4.py +2 -2
  58. rapidtide/tests/test_fullrunrapidtide_v7.py +1 -1
  59. rapidtide/tests/test_simroundtrip.py +8 -8
  60. rapidtide/tests/utils.py +9 -8
  61. rapidtide/tidepoolTemplate.py +142 -38
  62. rapidtide/tidepoolTemplate_alt.py +165 -44
  63. rapidtide/tidepoolTemplate_big.py +189 -52
  64. rapidtide/util.py +1217 -118
  65. rapidtide/voxelData.py +684 -37
  66. rapidtide/wiener.py +19 -12
  67. rapidtide/wiener2.py +113 -7
  68. rapidtide/wiener_doc.py +255 -0
  69. rapidtide/workflows/adjustoffset.py +105 -3
  70. rapidtide/workflows/aligntcs.py +85 -2
  71. rapidtide/workflows/applydlfilter.py +87 -10
  72. rapidtide/workflows/applyppgproc.py +522 -0
  73. rapidtide/workflows/atlasaverage.py +210 -47
  74. rapidtide/workflows/atlastool.py +100 -3
  75. rapidtide/workflows/calcSimFuncMap.py +294 -64
  76. rapidtide/workflows/calctexticc.py +201 -9
  77. rapidtide/workflows/ccorrica.py +97 -4
  78. rapidtide/workflows/cleanregressor.py +168 -29
  79. rapidtide/workflows/delayvar.py +163 -10
  80. rapidtide/workflows/diffrois.py +81 -3
  81. rapidtide/workflows/endtidalproc.py +144 -4
  82. rapidtide/workflows/fdica.py +195 -15
  83. rapidtide/workflows/filtnifti.py +70 -3
  84. rapidtide/workflows/filttc.py +74 -3
  85. rapidtide/workflows/fitSimFuncMap.py +206 -48
  86. rapidtide/workflows/fixtr.py +73 -3
  87. rapidtide/workflows/gmscalc.py +113 -3
  88. rapidtide/workflows/happy.py +813 -201
  89. rapidtide/workflows/happy2std.py +144 -12
  90. rapidtide/workflows/happy_parser.py +149 -8
  91. rapidtide/workflows/histnifti.py +118 -2
  92. rapidtide/workflows/histtc.py +84 -3
  93. rapidtide/workflows/linfitfilt.py +117 -4
  94. rapidtide/workflows/localflow.py +328 -28
  95. rapidtide/workflows/mergequality.py +79 -3
  96. rapidtide/workflows/niftidecomp.py +322 -18
  97. rapidtide/workflows/niftistats.py +174 -4
  98. rapidtide/workflows/pairproc.py +88 -2
  99. rapidtide/workflows/pairwisemergenifti.py +85 -2
  100. rapidtide/workflows/parser_funcs.py +1421 -40
  101. rapidtide/workflows/physiofreq.py +137 -11
  102. rapidtide/workflows/pixelcomp.py +208 -5
  103. rapidtide/workflows/plethquality.py +103 -21
  104. rapidtide/workflows/polyfitim.py +151 -11
  105. rapidtide/workflows/proj2flow.py +75 -2
  106. rapidtide/workflows/rankimage.py +111 -4
  107. rapidtide/workflows/rapidtide.py +272 -15
  108. rapidtide/workflows/rapidtide2std.py +98 -2
  109. rapidtide/workflows/rapidtide_parser.py +109 -9
  110. rapidtide/workflows/refineDelayMap.py +143 -33
  111. rapidtide/workflows/refineRegressor.py +682 -93
  112. rapidtide/workflows/regressfrommaps.py +152 -31
  113. rapidtide/workflows/resamplenifti.py +85 -3
  114. rapidtide/workflows/resampletc.py +91 -3
  115. rapidtide/workflows/retrolagtcs.py +98 -6
  116. rapidtide/workflows/retroregress.py +165 -9
  117. rapidtide/workflows/roisummarize.py +173 -5
  118. rapidtide/workflows/runqualitycheck.py +71 -3
  119. rapidtide/workflows/showarbcorr.py +147 -4
  120. rapidtide/workflows/showhist.py +86 -2
  121. rapidtide/workflows/showstxcorr.py +160 -3
  122. rapidtide/workflows/showtc.py +159 -3
  123. rapidtide/workflows/showxcorrx.py +184 -4
  124. rapidtide/workflows/showxy.py +185 -15
  125. rapidtide/workflows/simdata.py +262 -36
  126. rapidtide/workflows/spatialfit.py +77 -2
  127. rapidtide/workflows/spatialmi.py +251 -27
  128. rapidtide/workflows/spectrogram.py +305 -32
  129. rapidtide/workflows/synthASL.py +154 -3
  130. rapidtide/workflows/tcfrom2col.py +76 -2
  131. rapidtide/workflows/tcfrom3col.py +74 -2
  132. rapidtide/workflows/tidepool.py +2972 -133
  133. rapidtide/workflows/utils.py +19 -14
  134. rapidtide/workflows/utils_doc.py +293 -0
  135. rapidtide/workflows/variabilityizer.py +116 -3
  136. {rapidtide-3.0.10.dist-info → rapidtide-3.1.dist-info}/METADATA +10 -9
  137. {rapidtide-3.0.10.dist-info → rapidtide-3.1.dist-info}/RECORD +141 -122
  138. {rapidtide-3.0.10.dist-info → rapidtide-3.1.dist-info}/entry_points.txt +1 -0
  139. {rapidtide-3.0.10.dist-info → rapidtide-3.1.dist-info}/WHEEL +0 -0
  140. {rapidtide-3.0.10.dist-info → rapidtide-3.1.dist-info}/licenses/LICENSE +0 -0
  141. {rapidtide-3.0.10.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,12 +586,49 @@ 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)
556
617
 
557
618
  # Add miscellaneous options
558
619
  misc_opts = parser.add_argument_group("Miscellaneous options.")
620
+ misc_opts.add_argument(
621
+ "--processmask",
622
+ dest="processmask",
623
+ action="store",
624
+ metavar="MASKNAME",
625
+ help=(
626
+ "Instead of dynamically generating a processing mask from the data, use "
627
+ "the mask specified in the file MASKNAME. "
628
+ "The mask must be a 3D NIFTI file with x, y, z dimensions matching the fMRI data. "
629
+ ),
630
+ default=None,
631
+ )
559
632
  misc_opts.add_argument(
560
633
  "--aliasedcorrelation",
561
634
  dest="doaliasedcorrelation",
@@ -601,6 +674,13 @@ def _get_parser():
601
674
  help="Number of iterations for calculating Wright map. Set to 0 to disable.",
602
675
  default=0,
603
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
+ )
604
684
  pf.addtagopts(
605
685
  misc_opts,
606
686
  helptext="Additional key, value pairs to add to the info json file (useful for tracking analyses).",
@@ -623,6 +703,13 @@ def _get_parser():
623
703
  help="Disable data detrending. ",
624
704
  default=3,
625
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
+ )
626
713
  debug_opts.add_argument(
627
714
  "--noorthog",
628
715
  dest="orthogonalize",
@@ -728,13 +815,57 @@ def _get_parser():
728
815
  help="Disable the congrid value cache completely.",
729
816
  default=True,
730
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
+ )
731
832
 
732
833
  return parser
733
834
 
734
835
 
735
- def process_args(inputargs=None):
836
+ def process_args(inputargs: Optional[Any] = None) -> None:
736
837
  """
737
- 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)
738
869
  """
739
870
  args, argstowrite = pf.setargs(_get_parser, inputargs=inputargs)
740
871
 
@@ -761,6 +892,14 @@ def process_args(inputargs=None):
761
892
  formattedcommandline[i] = prefix + formattedcommandline[i] + suffix
762
893
  tide_io.writevec(formattedcommandline, args.outputroot + "_formattedcommandline.txt")
763
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
+
764
903
  if args.debug:
765
904
  print()
766
905
  print("before postprocessing")
@@ -776,12 +915,12 @@ def process_args(inputargs=None):
776
915
  args.upsamplefac = 100
777
916
  args.centric = True
778
917
  args.pulsereconstepsize = 0.01
779
- args.unnormvesselmap = True
780
918
  args.histlen = 100
781
919
  args.softvesselfrac = 0.4
782
920
  args.savecardiacnoise = True
783
921
  args.colnum = None
784
922
  args.colname = None
923
+ args.notchrolloff = 0.5
785
924
 
786
925
  # Additional argument parsing not handled by argparse
787
926
  # deal with notch filter logic
@@ -795,6 +934,8 @@ def process_args(inputargs=None):
795
934
  args.motionfilename = None
796
935
 
797
936
  # set the number of worker processes if multiprocessing
937
+ # Multiprocessing is very broken atm. Hard disable it.
938
+ # args.nprocs = 1
798
939
  if args.nprocs < 1:
799
940
  args.nprocs = tide_multiproc.maxcpus()
800
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 = []