rapidtide 3.0a13__py3-none-any.whl → 3.0a15__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 (232) hide show
  1. rapidtide/Colortables.py +1 -1
  2. rapidtide/DerivativeDelay.py +4 -2
  3. rapidtide/OrthoImageItem.py +1 -1
  4. rapidtide/RapidtideDataset.py +3 -1
  5. rapidtide/RegressorRefiner.py +1 -1
  6. rapidtide/calcandfitcorrpairs.py +1 -1
  7. rapidtide/calccoherence.py +1 -1
  8. rapidtide/calcnullsimfunc.py +1 -1
  9. rapidtide/calcsimfunc.py +1 -1
  10. rapidtide/correlate.py +1 -1
  11. rapidtide/data/examples/src/test_findmaxlag.py +1 -1
  12. rapidtide/data/examples/src/testdelayvar +2 -1
  13. rapidtide/data/examples/src/testfmri +3 -2
  14. rapidtide/data/examples/src/testfuncs +1 -1
  15. rapidtide/data/examples/src/testhappy +12 -1
  16. rapidtide/data/examples/src/testmodels +33 -0
  17. rapidtide/data/models/model_cnn_w064_l13_fn20_fl08/loss.png +0 -0
  18. rapidtide/data/models/model_cnn_w064_l13_fn20_fl08/loss.txt +1 -0
  19. rapidtide/data/models/model_cnn_w064_l13_fn20_fl08/model.keras +0 -0
  20. rapidtide/data/models/model_cnn_w064_l13_fn20_fl08/model_meta.json +167 -0
  21. rapidtide/data/models/model_revised_tf2/model.keras +0 -0
  22. rapidtide/data/models/{model_serdar → model_revised_tf2}/model_meta.json +1 -1
  23. rapidtide/data/models/model_serdar2_tf2/model.keras +0 -0
  24. rapidtide/data/models/{model_serdar2 → model_serdar2_tf2}/model_meta.json +1 -1
  25. rapidtide/data/models/model_serdar_tf2/model.keras +0 -0
  26. rapidtide/data/models/{model_revised → model_serdar_tf2}/model_meta.json +1 -1
  27. rapidtide/dlfilter.py +325 -241
  28. rapidtide/externaltools.py +1 -1
  29. rapidtide/fMRIData_class.py +1 -1
  30. rapidtide/filter.py +1 -8
  31. rapidtide/fit.py +1 -8
  32. rapidtide/happy_supportfuncs.py +30 -1
  33. rapidtide/helper_classes.py +1 -1
  34. rapidtide/io.py +1 -1
  35. rapidtide/linfitfiltpass.py +3 -1
  36. rapidtide/makelaggedtcs.py +9 -6
  37. rapidtide/maskutil.py +1 -1
  38. rapidtide/miscmath.py +1 -8
  39. rapidtide/multiproc.py +9 -12
  40. rapidtide/patchmatch.py +1 -1
  41. rapidtide/peakeval.py +1 -1
  42. rapidtide/qualitycheck.py +1 -1
  43. rapidtide/refinedelay.py +174 -89
  44. rapidtide/refineregressor.py +1 -1
  45. rapidtide/resample.py +1 -1
  46. rapidtide/scripts/adjustoffset.py +1 -1
  47. rapidtide/scripts/aligntcs.py +1 -1
  48. rapidtide/scripts/applydlfilter.py +1 -1
  49. rapidtide/scripts/atlasaverage.py +1 -1
  50. rapidtide/scripts/atlastool.py +1 -1
  51. rapidtide/scripts/calcicc.py +1 -1
  52. rapidtide/scripts/calctexticc.py +1 -1
  53. rapidtide/scripts/calcttest.py +1 -1
  54. rapidtide/scripts/ccorrica.py +1 -1
  55. rapidtide/scripts/delayvar.py +2 -2
  56. rapidtide/scripts/diffrois.py +1 -1
  57. rapidtide/scripts/endtidalproc.py +1 -1
  58. rapidtide/scripts/fdica.py +1 -1
  59. rapidtide/scripts/filtnifti.py +1 -1
  60. rapidtide/scripts/filttc.py +1 -1
  61. rapidtide/scripts/fingerprint.py +1 -1
  62. rapidtide/scripts/fixtr.py +1 -1
  63. rapidtide/scripts/gmscalc.py +1 -1
  64. rapidtide/scripts/happy.py +1 -1
  65. rapidtide/scripts/happy2std.py +1 -1
  66. rapidtide/scripts/happywarp.py +1 -1
  67. rapidtide/scripts/histnifti.py +1 -1
  68. rapidtide/scripts/histtc.py +1 -1
  69. rapidtide/scripts/linfitfilt.py +1 -1
  70. rapidtide/scripts/localflow.py +1 -1
  71. rapidtide/scripts/mergequality.py +1 -1
  72. rapidtide/scripts/pairproc.py +1 -1
  73. rapidtide/scripts/pairwisemergenifti.py +1 -1
  74. rapidtide/scripts/physiofreq.py +1 -1
  75. rapidtide/scripts/pixelcomp.py +1 -1
  76. rapidtide/scripts/plethquality.py +1 -1
  77. rapidtide/scripts/polyfitim.py +1 -1
  78. rapidtide/scripts/proj2flow.py +1 -1
  79. rapidtide/scripts/rankimage.py +1 -1
  80. rapidtide/scripts/rapidtide.py +1 -1
  81. rapidtide/scripts/rapidtide2std.py +1 -1
  82. rapidtide/scripts/resamplenifti.py +1 -1
  83. rapidtide/scripts/resampletc.py +1 -1
  84. rapidtide/scripts/retrolagtcs.py +1 -1
  85. rapidtide/scripts/retroregress.py +1 -1
  86. rapidtide/scripts/roisummarize.py +1 -1
  87. rapidtide/scripts/runqualitycheck.py +1 -1
  88. rapidtide/scripts/showarbcorr.py +1 -1
  89. rapidtide/scripts/showhist.py +1 -1
  90. rapidtide/scripts/showstxcorr.py +1 -1
  91. rapidtide/scripts/showtc.py +1 -1
  92. rapidtide/scripts/showxcorr_legacy.py +1 -1
  93. rapidtide/scripts/showxcorrx.py +1 -1
  94. rapidtide/scripts/showxy.py +1 -1
  95. rapidtide/scripts/simdata.py +1 -1
  96. rapidtide/scripts/spatialdecomp.py +1 -1
  97. rapidtide/scripts/spatialfit.py +1 -1
  98. rapidtide/scripts/spatialmi.py +1 -1
  99. rapidtide/scripts/spectrogram.py +1 -1
  100. rapidtide/scripts/stupidramtricks.py +1 -1
  101. rapidtide/scripts/synthASL.py +1 -1
  102. rapidtide/scripts/tcfrom2col.py +1 -1
  103. rapidtide/scripts/tcfrom3col.py +1 -1
  104. rapidtide/scripts/temporaldecomp.py +1 -1
  105. rapidtide/scripts/testhrv.py +1 -1
  106. rapidtide/scripts/threeD.py +1 -1
  107. rapidtide/scripts/tidepool.py +1 -1
  108. rapidtide/scripts/variabilityizer.py +1 -1
  109. rapidtide/simfuncfit.py +1 -1
  110. rapidtide/stats.py +1 -8
  111. rapidtide/tests/cleanposttest +1 -1
  112. rapidtide/tests/resethappytargets +1 -1
  113. rapidtide/tests/resetrapidtidetargets +1 -1
  114. rapidtide/tests/resettargets +1 -1
  115. rapidtide/tests/runlocaltest +1 -1
  116. rapidtide/tests/showkernels +1 -1
  117. rapidtide/tests/test_aliasedcorrelate.py +1 -1
  118. rapidtide/tests/test_aligntcs.py +1 -1
  119. rapidtide/tests/test_calcicc.py +1 -1
  120. rapidtide/tests/test_congrid.py +1 -1
  121. rapidtide/tests/test_correlate.py +1 -1
  122. rapidtide/tests/test_corrpass.py +1 -1
  123. rapidtide/tests/test_delayestimation.py +1 -1
  124. rapidtide/tests/test_doresample.py +1 -1
  125. rapidtide/tests/test_fastresampler.py +1 -1
  126. rapidtide/tests/test_findmaxlag.py +1 -1
  127. rapidtide/tests/test_fullrunhappy_v1.py +15 -7
  128. rapidtide/tests/test_fullrunhappy_v2.py +18 -10
  129. rapidtide/tests/test_fullrunhappy_v3.py +18 -10
  130. rapidtide/tests/test_fullrunhappy_v4.py +18 -10
  131. rapidtide/tests/test_fullrunhappy_v5.py +15 -9
  132. rapidtide/tests/test_fullrunrapidtide_v1.py +19 -11
  133. rapidtide/tests/test_fullrunrapidtide_v2.py +24 -14
  134. rapidtide/tests/test_fullrunrapidtide_v3.py +15 -7
  135. rapidtide/tests/test_fullrunrapidtide_v4.py +15 -8
  136. rapidtide/tests/test_fullrunrapidtide_v5.py +13 -5
  137. rapidtide/tests/test_fullrunrapidtide_v6.py +24 -16
  138. rapidtide/tests/test_io.py +1 -1
  139. rapidtide/tests/test_linfitfiltpass.py +1 -1
  140. rapidtide/tests/test_mi.py +1 -1
  141. rapidtide/tests/test_miscmath.py +1 -1
  142. rapidtide/tests/test_motionregress.py +1 -1
  143. rapidtide/tests/test_nullcorr.py +1 -1
  144. rapidtide/tests/test_padvec.py +1 -1
  145. rapidtide/tests/test_phaseanalysis.py +1 -1
  146. rapidtide/tests/test_rapidtideparser.py +1 -1
  147. rapidtide/tests/test_refinedelay.py +4 -3
  148. rapidtide/tests/test_runmisc.py +1 -1
  149. rapidtide/tests/test_sharedmem.py +1 -1
  150. rapidtide/tests/test_simulate.py +1 -1
  151. rapidtide/tests/test_stcorrelate.py +1 -1
  152. rapidtide/tests/test_timeshift.py +1 -1
  153. rapidtide/tests/test_valtoindex.py +1 -1
  154. rapidtide/tests/test_zRapidtideDataset.py +1 -1
  155. rapidtide/tests/utils.py +1 -1
  156. rapidtide/transformerdlfilter.py +2 -4
  157. rapidtide/util.py +37 -14
  158. rapidtide/voxelData.py +278 -0
  159. rapidtide/wiener.py +1 -1
  160. rapidtide/wiener2.py +1 -1
  161. rapidtide/workflows/adjustoffset.py +1 -1
  162. rapidtide/workflows/aligntcs.py +1 -1
  163. rapidtide/workflows/applydlfilter.py +20 -65
  164. rapidtide/workflows/atlasaverage.py +41 -13
  165. rapidtide/workflows/atlastool.py +1 -1
  166. rapidtide/workflows/calctexticc.py +1 -1
  167. rapidtide/workflows/ccorrica.py +1 -1
  168. rapidtide/workflows/cleanregressor.py +243 -0
  169. rapidtide/workflows/delayestimation.py +488 -0
  170. rapidtide/workflows/delayvar.py +122 -34
  171. rapidtide/workflows/diffrois.py +1 -1
  172. rapidtide/workflows/endtidalproc.py +1 -1
  173. rapidtide/workflows/fdica.py +1 -1
  174. rapidtide/workflows/filtnifti.py +1 -1
  175. rapidtide/workflows/filttc.py +1 -1
  176. rapidtide/workflows/fixtr.py +1 -1
  177. rapidtide/workflows/gmscalc.py +1 -1
  178. rapidtide/workflows/happy.py +49 -3
  179. rapidtide/workflows/happy2std.py +1 -1
  180. rapidtide/workflows/happy_parser.py +30 -6
  181. rapidtide/workflows/histnifti.py +1 -1
  182. rapidtide/workflows/histtc.py +1 -1
  183. rapidtide/workflows/linfitfilt.py +1 -1
  184. rapidtide/workflows/localflow.py +1 -1
  185. rapidtide/workflows/mergequality.py +1 -1
  186. rapidtide/workflows/niftidecomp.py +1 -1
  187. rapidtide/workflows/niftistats.py +1 -1
  188. rapidtide/workflows/pairproc.py +1 -1
  189. rapidtide/workflows/pairwisemergenifti.py +1 -1
  190. rapidtide/workflows/parser_funcs.py +1 -1
  191. rapidtide/workflows/physiofreq.py +1 -1
  192. rapidtide/workflows/pixelcomp.py +1 -1
  193. rapidtide/workflows/plethquality.py +1 -1
  194. rapidtide/workflows/polyfitim.py +1 -1
  195. rapidtide/workflows/proj2flow.py +1 -1
  196. rapidtide/workflows/rankimage.py +1 -1
  197. rapidtide/workflows/rapidtide.py +174 -686
  198. rapidtide/workflows/rapidtide2std.py +1 -1
  199. rapidtide/workflows/rapidtide_parser.py +14 -113
  200. rapidtide/workflows/regressfrommaps.py +6 -48
  201. rapidtide/workflows/resamplenifti.py +1 -1
  202. rapidtide/workflows/resampletc.py +1 -1
  203. rapidtide/workflows/retrolagtcs.py +2 -1
  204. rapidtide/workflows/retroregress.py +26 -2
  205. rapidtide/workflows/roisummarize.py +1 -1
  206. rapidtide/workflows/runqualitycheck.py +1 -1
  207. rapidtide/workflows/showarbcorr.py +1 -1
  208. rapidtide/workflows/showhist.py +1 -1
  209. rapidtide/workflows/showstxcorr.py +1 -1
  210. rapidtide/workflows/showtc.py +1 -1
  211. rapidtide/workflows/showxcorrx.py +1 -1
  212. rapidtide/workflows/showxy.py +1 -1
  213. rapidtide/workflows/simdata.py +1 -1
  214. rapidtide/workflows/spatialfit.py +1 -1
  215. rapidtide/workflows/spatialmi.py +1 -1
  216. rapidtide/workflows/spectrogram.py +1 -1
  217. rapidtide/workflows/synthASL.py +1 -1
  218. rapidtide/workflows/tcfrom2col.py +1 -1
  219. rapidtide/workflows/tcfrom3col.py +1 -1
  220. rapidtide/workflows/tidepool.py +2 -1
  221. rapidtide/workflows/utils.py +1 -1
  222. rapidtide/workflows/variabilityizer.py +1 -1
  223. {rapidtide-3.0a13.dist-info → rapidtide-3.0a15.dist-info}/METADATA +1 -1
  224. rapidtide-3.0a15.dist-info/RECORD +353 -0
  225. {rapidtide-3.0a13.dist-info → rapidtide-3.0a15.dist-info}/WHEEL +1 -1
  226. rapidtide/data/models/model_revised/model.h5 +0 -0
  227. rapidtide/data/models/model_serdar/model.h5 +0 -0
  228. rapidtide/data/models/model_serdar2/model.h5 +0 -0
  229. rapidtide-3.0a13.dist-info/RECORD +0 -345
  230. {rapidtide-3.0a13.dist-info → rapidtide-3.0a15.dist-info}/entry_points.txt +0 -0
  231. {rapidtide-3.0a13.dist-info → rapidtide-3.0a15.dist-info}/licenses/LICENSE +0 -0
  232. {rapidtide-3.0a13.dist-info → rapidtide-3.0a15.dist-info}/top_level.txt +0 -0
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env python
2
2
  # -*- coding: utf-8 -*-
3
3
  #
4
- # Copyright 2016-2024 Blaise Frederick
4
+ # Copyright 2016-2025 Blaise Frederick
5
5
  #
6
6
  # Licensed under the Apache License, Version 2.0 (the "License");
7
7
  # you may not use this file except in compliance with the License.
@@ -51,7 +51,9 @@ import rapidtide.resample as tide_resample
51
51
  import rapidtide.simfuncfit as tide_simfuncfit
52
52
  import rapidtide.stats as tide_stats
53
53
  import rapidtide.util as tide_util
54
+ import rapidtide.voxelData as tide_voxelData
54
55
  import rapidtide.wiener as tide_wiener
56
+ import rapidtide.workflows.cleanregressor as tide_cleanregressor
55
57
  import rapidtide.workflows.regressfrommaps as tide_regressfrommaps
56
58
  from rapidtide.tests.utils import mse
57
59
 
@@ -64,32 +66,11 @@ try:
64
66
  except ImportError:
65
67
  mklexists = False
66
68
 
67
- try:
68
- from memory_profiler import profile
69
-
70
- memprofilerexists = True
71
- except ImportError:
72
- memprofilerexists = False
73
-
74
69
  LGR = logging.getLogger("GENERAL")
75
70
  ErrorLGR = logging.getLogger("ERROR")
76
71
  TimingLGR = logging.getLogger("TIMING")
77
72
 
78
73
 
79
- def conditionalprofile():
80
- def resdec(f):
81
- if memprofilerexists:
82
- return profile(f)
83
- return f
84
-
85
- return resdec
86
-
87
-
88
- @conditionalprofile()
89
- def memcheckpoint(message):
90
- LGR.info(message)
91
-
92
-
93
74
  def getglobalsignal(
94
75
  indata, optiondict, includemask=None, excludemask=None, pcacomponents=0.8, debug=False
95
76
  ):
@@ -159,14 +140,6 @@ def getglobalsignal(
159
140
  return tide_math.stdnormalize(globalmean), themask
160
141
 
161
142
 
162
- def addmemprofiling(thefunc, memprofile, themessage):
163
- tide_util.logmem(themessage)
164
- if memprofile:
165
- return profile(thefunc, precision=2)
166
- else:
167
- return thefunc
168
-
169
-
170
143
  def checkforzeromean(thedataset):
171
144
  themean = np.mean(thedataset, axis=1)
172
145
  thestd = np.std(thedataset, axis=1)
@@ -216,21 +189,6 @@ def echocancel(thetimecourse, echooffset, thetimestep, outputname, padtimepoints
216
189
  return outputtimecourse, echofit, echoR2
217
190
 
218
191
 
219
- def disablemkl(numprocs, debug=False):
220
- if mklexists:
221
- if numprocs > 1:
222
- if debug:
223
- print("disablemkl: setting threads to 1")
224
- mkl.set_num_threads(1)
225
-
226
-
227
- def enablemkl(numthreads, debug=False):
228
- if mklexists:
229
- if debug:
230
- print(f"enablemkl: setting threads to {numthreads}")
231
- mkl.set_num_threads(numthreads)
232
-
233
-
234
192
  def rapidtide_main(argparsingfunc):
235
193
  threaddebug = False
236
194
  optiondict, theprefilter = argparsingfunc
@@ -249,7 +207,7 @@ def rapidtide_main(argparsingfunc):
249
207
  optiondict["Description"] = (
250
208
  "A detailed dump of all internal variables in the program. Useful for debugging and data provenance."
251
209
  )
252
- fmrifilename = optiondict["in_file"]
210
+ inputdatafilename = optiondict["in_file"]
253
211
  outputname = optiondict["outputname"]
254
212
  regressorfilename = optiondict["regressorfile"]
255
213
 
@@ -392,7 +350,7 @@ def rapidtide_main(argparsingfunc):
392
350
  mklmaxthreads = mkl.get_max_threads()
393
351
  if not (1 <= optiondict["mklthreads"] <= mklmaxthreads):
394
352
  optiondict["mklthreads"] = mklmaxthreads
395
- enablemkl(optiondict["mklthreads"], debug=threaddebug)
353
+ tide_util.enablemkl(optiondict["mklthreads"], debug=threaddebug)
396
354
  LGR.info(f"using {optiondict['mklthreads']} MKL threads")
397
355
 
398
356
  # Generate MemoryLGR output file with column names
@@ -401,77 +359,30 @@ def rapidtide_main(argparsingfunc):
401
359
  ####################################################
402
360
  # Read data
403
361
  ####################################################
404
- # open the fmri datafile
405
- tide_util.logmem("before reading in fmri data")
406
- if tide_io.checkiftext(fmrifilename):
407
- LGR.debug("input file is text - all I/O will be to text files")
408
- optiondict["textio"] = True
409
- if optiondict["gausssigma"] > 0.0:
410
- optiondict["gausssigma"] = 0.0
411
- LGR.info("gaussian spatial filter disabled for text input files")
412
- else:
362
+ # read the fmri datafile
363
+ tide_util.logmem("before reading in input data")
364
+ theinputdata = tide_voxelData.VoxelData(inputdatafilename, timestep=optiondict["realtr"])
365
+ if optiondict["debug"]:
366
+ theinputdata.summarize()
367
+ nim = theinputdata.nim
368
+ nim_hdr = theinputdata.nim_hdr
369
+ nim_affine = theinputdata.nim_affine
370
+ xsize, ysize, numslices, timepoints = theinputdata.getdims()
371
+ thesizes = theinputdata.thesizes
372
+ xdim, ydim, slicethickness, fmritr = theinputdata.getsizes()
373
+ numspatiallocs = theinputdata.numspatiallocs
374
+ nativespaceshape = theinputdata.nativespaceshape
375
+ cifti_hdr = theinputdata.cifti_hdr
376
+ fmritr = theinputdata.timestep
377
+ if theinputdata.filetype == "cifti":
378
+ fileiscifti = True
413
379
  optiondict["textio"] = False
414
-
415
- if optiondict["textio"]:
416
- nim_data = tide_io.readvecs(fmrifilename)
417
- nim_hdr = None
418
- nim_affine = None
419
- theshape = np.shape(nim_data)
420
- xsize = theshape[0]
421
- ysize = 1
422
- numslices = 1
380
+ elif theinputdata.filetype == "text":
423
381
  fileiscifti = False
424
- timepoints = theshape[1]
425
- thesizes = [0, int(xsize), 1, 1, int(timepoints)]
426
- numspatiallocs = int(xsize)
427
- nativespaceshape = xsize
428
- cifti_hdr = None
429
- else:
430
- fileiscifti = tide_io.checkifcifti(fmrifilename)
431
- if fileiscifti:
432
- LGR.debug("input file is CIFTI")
433
- (
434
- dummy,
435
- cifti_hdr,
436
- nim_data,
437
- nim_hdr,
438
- thedims,
439
- thesizes,
440
- dummy,
441
- ) = tide_io.readfromcifti(fmrifilename)
442
- nim_affine = None
443
- optiondict["isgrayordinate"] = True
444
- timepoints = nim_data.shape[1]
445
- numspatiallocs = nim_data.shape[0]
446
- LGR.debug(f"cifti file has {timepoints} timepoints, {numspatiallocs} numspatiallocs")
447
- nativespaceshape = (1, 1, 1, 1, numspatiallocs)
448
- else:
449
- LGR.debug("input file is NIFTI")
450
- nim, nim_data, nim_hdr, thedims, thesizes = tide_io.readfromnifti(fmrifilename)
451
- nim_affine = nim.affine
452
- optiondict["isgrayordinate"] = False
453
- xsize, ysize, numslices, timepoints = tide_io.parseniftidims(thedims)
454
- numspatiallocs = int(xsize) * int(ysize) * int(numslices)
455
- cifti_hdr = None
456
- nativespaceshape = (xsize, ysize, numslices)
457
- xdim, ydim, slicethickness, dummy = tide_io.parseniftisizes(thesizes)
458
-
459
- # correct some fields if necessary
460
- if fileiscifti:
461
- fmritr = 0.72 # this is wrong and is a hack until I can parse CIFTI XML
382
+ optiondict["textio"] = True
462
383
  else:
463
- if optiondict["textio"]:
464
- if optiondict["realtr"] <= 0.0:
465
- raise ValueError(
466
- "for text file data input, you must use the -t option to set the timestep"
467
- )
468
- else:
469
- if nim_hdr.get_xyzt_units()[1] == "msec":
470
- fmritr = thesizes[4] / 1000.0
471
- else:
472
- fmritr = thesizes[4]
473
- if optiondict["realtr"] > 0.0:
474
- fmritr = optiondict["realtr"]
384
+ fileiscifti = False
385
+ optiondict["textio"] = False
475
386
 
476
387
  # check to see if we need to adjust the oversample factor
477
388
  if optiondict["oversampfactor"] < 0:
@@ -498,6 +409,8 @@ def rapidtide_main(argparsingfunc):
498
409
  raise ValueError(
499
410
  f"magnitude of lagmax exceeds {(validend - validstart + 1) * fmritr / 2.0} - invalid"
500
411
  )
412
+ # trim the fmri data to the limits
413
+ theinputdata.setvalidtimes(validstart, validend)
501
414
 
502
415
  # determine the valid timepoints
503
416
  validtimepoints = validend - validstart + 1
@@ -551,70 +464,33 @@ def rapidtide_main(argparsingfunc):
551
464
  whitemask = anatomicmasks[2]
552
465
 
553
466
  # do spatial filtering if requested
554
- if fileiscifti:
555
- optiondict["gausssigma"] = 0.0
556
- if optiondict["gausssigma"] < 0.0 and not optiondict["textio"]:
557
- # set gausssigma automatically
558
- optiondict["gausssigma"] = np.mean([xdim, ydim, slicethickness]) / 2.0
467
+ optiondict["gausssigma"] = theinputdata.smooth(
468
+ optiondict["gausssigma"],
469
+ brainmask=brainmask,
470
+ graymask=graymask,
471
+ whitemask=whitemask,
472
+ premask=optiondict["premask"],
473
+ premasktissueonly=optiondict["premasktissueonly"],
474
+ showprogressbar=optiondict["showprogressbar"],
475
+ )
559
476
  if optiondict["gausssigma"] > 0.0:
560
- # premask data if requested
561
- if optiondict["premask"]:
562
- if optiondict["premasktissueonly"]:
563
- if (graymask is not None) and (whitemask is not None):
564
- multmask = graymask + whitemask
565
- else:
566
- raise ValueError(
567
- "ERROR: graymask and whitemask must be defined to use premasktissueonly - exiting"
568
- )
569
- else:
570
- if brainmask is not None:
571
- multmask = brainmask
572
- else:
573
- raise ValueError("ERROR: brainmask must be defined to use premask - exiting")
574
- LGR.info(f"premasking timepoints {validstart} to {validend}")
575
- for i in tqdm(
576
- range(validstart, validend + 1),
577
- desc="Timepoint",
578
- unit="timepoints",
579
- disable=(not optiondict["showprogressbar"]),
580
- ):
581
- nim_data[:, :, :, i] *= multmask
582
-
583
- # this is where you'd slice time correct
584
- # but we don't anymore
585
-
586
- # now apply the filter
587
- LGR.info(
588
- f"applying gaussian spatial filter to timepoints {validstart} "
589
- f"to {validend} with sigma={optiondict['gausssigma']}"
590
- )
591
- for i in tqdm(
592
- range(validstart, validend + 1),
593
- desc="Timepoint",
594
- unit="timepoints",
595
- disable=(not optiondict["showprogressbar"]),
596
- ):
597
- nim_data[:, :, :, i] = tide_filt.ssmooth(
598
- xdim,
599
- ydim,
600
- slicethickness,
601
- optiondict["gausssigma"],
602
- nim_data[:, :, :, i],
603
- )
604
477
  TimingLGR.info("End 3D smoothing")
605
478
 
606
479
  # reshape the data and trim to a time range, if specified. Check for special case of no trimming to save RAM
607
- fmri_data = nim_data.reshape((numspatiallocs, timepoints))[:, validstart : validend + 1]
480
+ fmri_data = theinputdata.voxelbytime()
481
+ print(f"{fmri_data.shape=}")
608
482
 
609
483
  # detect zero mean data
610
- optiondict["dataiszeromean"] = checkforzeromean(fmri_data)
484
+ if not optiondict["dataiszeromean"]:
485
+ # check anyway
486
+ optiondict["dataiszeromean"] = checkforzeromean(fmri_data)
487
+
611
488
  if optiondict["dataiszeromean"]:
612
489
  LGR.warning(
613
490
  "WARNING: dataset is zero mean - forcing variance masking and no refine prenormalization. "
614
491
  "Consider specifying a global mean and correlation mask."
615
492
  )
616
493
  optiondict["refineprenorm"] = "None"
617
- optiondict["globalmaskmethod"] = "variance"
618
494
 
619
495
  # reformat the brain mask, if it exists
620
496
  if brainmask is None:
@@ -716,18 +592,18 @@ def rapidtide_main(argparsingfunc):
716
592
  corrmask[np.where(datarange == 0)] = 0.0
717
593
  else:
718
594
  # check to see if the data has been demeaned
719
- meanim = np.mean(fmri_data, axis=1)
720
- stdim = np.std(fmri_data, axis=1)
721
- if fileiscifti:
722
- corrmask = np.uint(nim_data[:, 0] * 0 + 1)
595
+ if fileiscifti or optiondict["textio"]:
596
+ corrmask = np.uint(theinputdata.voxelbytime()[:, 0] * 0 + 1)
723
597
  else:
724
- if (np.mean(stdim) < np.mean(meanim)) and not optiondict["nirs"]:
598
+ if not optiondict["dataiszeromean"]:
725
599
  LGR.verbose("generating correlation mask from mean image")
726
600
  corrmask = np.uint16(tide_mask.makeepimask(nim).dataobj.reshape(numspatiallocs))
727
601
  else:
728
602
  LGR.verbose("generating correlation mask from std image")
729
603
  corrmask = np.uint16(
730
- tide_stats.makemask(stdim, threshpct=optiondict["corrmaskthreshpct"])
604
+ tide_stats.makemask(
605
+ np.std(fmri_data, axis=1), threshpct=optiondict["corrmaskthreshpct"]
606
+ )
731
607
  )
732
608
  if internalbrainmask is not None:
733
609
  corrmask = internalbrainmask
@@ -777,7 +653,8 @@ def rapidtide_main(argparsingfunc):
777
653
  np.savetxt(f"{outputname}_validvoxels.txt", validvoxels)
778
654
  numvalidspatiallocs = np.shape(validvoxels)[0]
779
655
  LGR.debug(f"validvoxels shape = {numvalidspatiallocs}")
780
- fmri_data_valid = fmri_data[validvoxels, :] + 0.0
656
+ theinputdata.setvalidvoxels(validvoxels)
657
+ fmri_data_valid = theinputdata.getvalidvoxels() + 0.0
781
658
  LGR.verbose(
782
659
  f"original size = {np.shape(fmri_data)}, trimmed size = {np.shape(fmri_data_valid)}"
783
660
  )
@@ -822,10 +699,7 @@ def rapidtide_main(argparsingfunc):
822
699
  if optiondict["sharedmem"]:
823
700
  LGR.info("moving fmri data to shared memory")
824
701
  TimingLGR.verbose("Start moving fmri_data to shared memory")
825
- numpy2shared_func = addmemprofiling(
826
- tide_util.numpy2shared, optiondict["memprofile"], "before fmri data move"
827
- )
828
- fmri_data_valid, fmri_data_valid_shm = numpy2shared_func(
702
+ fmri_data_valid, fmri_data_valid_shm = tide_util.numpy2shared(
829
703
  fmri_data_valid, rt_floatset, name=f"fmri_data_valid_{optiondict['pid']}"
830
704
  )
831
705
  TimingLGR.verbose("End moving fmri_data to shared memory")
@@ -857,7 +731,7 @@ def rapidtide_main(argparsingfunc):
857
731
  else:
858
732
  doconfounds = False
859
733
 
860
- # now actually do the filtering
734
+ # now actually do the confound filtering
861
735
  if domotion or doconfounds:
862
736
  LGR.info("Doing confound filtering")
863
737
  TimingLGR.verbose("Confound filtering start")
@@ -883,7 +757,14 @@ def rapidtide_main(argparsingfunc):
883
757
  append=False,
884
758
  )
885
759
 
886
- disablemkl(optiondict["nprocs_confoundregress"], debug=threaddebug)
760
+ if optiondict["focaldebug"]:
761
+ print(f"{mergedregressors.shape=}")
762
+ print(f"{mergedregressorlabels}")
763
+ print(f"{fmri_data_valid.shape=}")
764
+ print(f"{fmritr=}")
765
+ print(f"{validstart=}")
766
+ print(f"{validend=}")
767
+ tide_util.disablemkl(optiondict["nprocs_confoundregress"], debug=threaddebug)
887
768
  (
888
769
  mergedregressors,
889
770
  mergedregressorlabels,
@@ -900,7 +781,7 @@ def rapidtide_main(argparsingfunc):
900
781
  orthogonalize=optiondict["orthogonalize"],
901
782
  showprogressbar=optiondict["showprogressbar"],
902
783
  )
903
- enablemkl(optiondict["mklthreads"], debug=threaddebug)
784
+ tide_util.enablemkl(optiondict["mklthreads"], debug=threaddebug)
904
785
  if confoundr2 is None:
905
786
  print("There are no nonzero confound regressors - exiting")
906
787
  sys.exit()
@@ -959,8 +840,6 @@ def rapidtide_main(argparsingfunc):
959
840
  },
960
841
  append=False,
961
842
  )
962
- if optiondict["memprofile"]:
963
- memcheckpoint("...done")
964
843
  tide_util.logmem("after confound sLFO filter")
965
844
 
966
845
  if optiondict["saveconfoundfiltered"]:
@@ -1006,11 +885,11 @@ def rapidtide_main(argparsingfunc):
1006
885
  # get rid of memory we aren't using
1007
886
  tide_util.logmem("before purging full sized fmri data")
1008
887
  meanvalue = np.mean(
1009
- nim_data.reshape((numspatiallocs, timepoints))[:, validstart : validend + 1],
888
+ theinputdata.voxelbytime(),
1010
889
  axis=1,
1011
890
  )
1012
891
  stddevvalue = np.std(
1013
- nim_data.reshape((numspatiallocs, timepoints))[:, validstart : validend + 1],
892
+ theinputdata.voxelbytime(),
1014
893
  axis=1,
1015
894
  )
1016
895
  covvalue = np.where(meanvalue > 0.0, stddevvalue / meanvalue, 0.0)
@@ -1033,8 +912,7 @@ def rapidtide_main(argparsingfunc):
1033
912
  )
1034
913
 
1035
914
  # get rid of more memory we aren't using
1036
- del fmri_data
1037
- del nim_data
915
+ theinputdata.unload()
1038
916
  uncollected = gc.collect()
1039
917
  if uncollected != 0:
1040
918
  print(f"garbage collected - unable to collect {uncollected} objects")
@@ -1147,59 +1025,6 @@ def rapidtide_main(argparsingfunc):
1147
1025
  LGR.verbose(f"the timepoint spacing is {1.0 / inputfreq}")
1148
1026
  LGR.verbose(f"the input timecourse start time is {inputstarttime}")
1149
1027
 
1150
- # if there is an externally specified noise regressor, read it in here
1151
- if optiondict["noisetimecoursespec"] is not None:
1152
- noisetimecoursespec = optiondict["noisetimecoursespec"]
1153
- LGR.info(f"using externally supplied noise regressor {noisetimecoursespec}")
1154
- (
1155
- filenoisefreq,
1156
- filenoisestarttime,
1157
- dummy,
1158
- noisevec,
1159
- dummy,
1160
- dummy,
1161
- ) = tide_io.readvectorsfromtextfile(optiondict["noisetimecoursespec"], onecol=True)
1162
- if optiondict["noiseinvert"]:
1163
- noisevec = noisevec * -1.0
1164
- noisefreq = optiondict["noisefreq"]
1165
- noisestarttime = optiondict["noisestarttime"]
1166
- if noisefreq is None:
1167
- if filenoisefreq is not None:
1168
- noisefreq = filenoisefreq
1169
- else:
1170
- noisefreq = 1.0 / fmritr
1171
- LGR.warning(f"no regressor frequency specified - defaulting to {noisefreq} (1/tr)")
1172
- if noisestarttime is None:
1173
- if filenoisestarttime is not None:
1174
- noisestarttime = filenoisestarttime
1175
- else:
1176
- LGR.warning("no regressor start time specified - defaulting to 0.0")
1177
- noisestarttime = 0.0
1178
- noiseperiod = 1.0 / noisefreq
1179
- numnoise = len(noisevec)
1180
- optiondict["noisefreq"] = noisefreq
1181
- optiondict["noisestarttime"] = noisestarttime
1182
- LGR.debug(
1183
- "Noise timecourse start time, end time, and step: {:.3f}, {:.3f}, {:.3f}".format(
1184
- -noisestarttime, noisestarttime + numnoise * noiseperiod, noiseperiod
1185
- )
1186
- )
1187
- noise_x = np.arange(0.0, numnoise) * noiseperiod - noisestarttime
1188
- noise_y = noisevec[0:numnoise] - np.mean(noisevec[0:numnoise])
1189
- # write out the noise regressor as read
1190
- tide_io.writebidstsv(
1191
- f"{outputname}_desc-initialnoiseregressor_timeseries",
1192
- noise_y,
1193
- noisefreq,
1194
- starttime=-noisestarttime,
1195
- columns=["prefilt"],
1196
- append=False,
1197
- )
1198
- LGR.verbose("noise vector")
1199
- LGR.verbose(f"length: {len(noisevec)}")
1200
- LGR.verbose(f"noise freq: {noisefreq}")
1201
- LGR.verbose(f"noise start time: {noisestarttime:.3f}")
1202
-
1203
1028
  # generate the time axes
1204
1029
  fmrifreq = 1.0 / fmritr
1205
1030
  optiondict["fmrifreq"] = fmrifreq
@@ -1276,8 +1101,6 @@ def rapidtide_main(argparsingfunc):
1276
1101
  reference_y = -np.gradient(reference_y_classfilter)
1277
1102
  else:
1278
1103
  reference_y = reference_y_classfilter
1279
- if optiondict["noisetimecoursespec"] is not None:
1280
- noise_y = theprefilter.apply(noisefreq, noise_y)
1281
1104
 
1282
1105
  # write out the reference regressor used
1283
1106
  tide_io.writebidstsv(
@@ -1304,26 +1127,6 @@ def rapidtide_main(argparsingfunc):
1304
1127
  debug=optiondict["debug"],
1305
1128
  )
1306
1129
  reference_y = rt_floatset(reference_y_filt.real)
1307
- if optiondict["noisetimecoursespec"] is not None:
1308
- noise_y_filt = tide_filt.dolptrapfftfilt(
1309
- noisefreq,
1310
- 0.25 * fmrifreq,
1311
- 0.5 * fmrifreq,
1312
- noise_y,
1313
- padlen=int(noisefreq * optiondict["padseconds"]),
1314
- debug=optiondict["debug"],
1315
- )
1316
- noise_y = rt_floatset(noise_y_filt.real)
1317
-
1318
- # write out the noise regressor after filtering
1319
- tide_io.writebidstsv(
1320
- f"{outputname}_desc-initialnoiseregressor_timeseries",
1321
- noise_y,
1322
- noisefreq,
1323
- starttime=-noisestarttime,
1324
- columns=["postfilt"],
1325
- append=True,
1326
- )
1327
1130
 
1328
1131
  warnings.filterwarnings("ignore", "Casting*")
1329
1132
 
@@ -1357,22 +1160,6 @@ def rapidtide_main(argparsingfunc):
1357
1160
  order=optiondict["detrendorder"],
1358
1161
  demean=optiondict["dodemean"],
1359
1162
  )
1360
- if optiondict["noisetimecoursespec"] is not None:
1361
- if optiondict["detrendorder"] > 0:
1362
- resampnoise_y = tide_fit.detrend(
1363
- tide_resample.doresample(
1364
- noise_x,
1365
- noise_y,
1366
- os_fmri_x,
1367
- padlen=int(oversampfreq * optiondict["padseconds"]),
1368
- padtype="zero",
1369
- method=optiondict["interptype"],
1370
- debug=optiondict["debug"],
1371
- ),
1372
- order=optiondict["detrendorder"],
1373
- demean=optiondict["dodemean"],
1374
- )
1375
-
1376
1163
  else:
1377
1164
  resampnonosref_y = tide_resample.doresample(
1378
1165
  reference_x,
@@ -1388,15 +1175,6 @@ def rapidtide_main(argparsingfunc):
1388
1175
  padlen=int(oversampfreq * optiondict["padseconds"]),
1389
1176
  method=optiondict["interptype"],
1390
1177
  )
1391
- if optiondict["noisetimecoursespec"] is not None:
1392
- resampnoise_y = tide_resample.doresample(
1393
- noise_x,
1394
- noise_y,
1395
- os_fmri_x,
1396
- padlen=int(oversampfreq * optiondict["padseconds"]),
1397
- padtype="zero",
1398
- method=optiondict["interptype"],
1399
- )
1400
1178
 
1401
1179
  LGR.debug(
1402
1180
  f"{len(os_fmri_x)} "
@@ -1458,22 +1236,6 @@ def rapidtide_main(argparsingfunc):
1458
1236
  else:
1459
1237
  tmaskos_y = None
1460
1238
 
1461
- if optiondict["noisetimecoursespec"] is not None:
1462
- tide_io.writebidstsv(
1463
- f"{outputname}_desc-noiseregressor_timeseries",
1464
- tide_math.stdnormalize(resampnonosref_y),
1465
- 1.0 / fmritr,
1466
- columns=["resampled"],
1467
- append=False,
1468
- )
1469
- tide_io.writebidstsv(
1470
- f"{outputname}_desc-oversamplednoiseregressor_timeseries",
1471
- tide_math.stdnormalize(resampref_y),
1472
- oversampfreq,
1473
- columns=["oversampled"],
1474
- append=False,
1475
- )
1476
-
1477
1239
  (
1478
1240
  optiondict["kurtosis_reference_pass1"],
1479
1241
  optiondict["kurtosisz_reference_pass1"],
@@ -1664,7 +1426,7 @@ def rapidtide_main(argparsingfunc):
1664
1426
  print(f"allocated {thesize:.3f} {theunit} {ramlocation} for correlation")
1665
1427
  tide_util.logmem("after correlation array allocation")
1666
1428
 
1667
- # if there is a fixed delay map, read it in
1429
+ # if there is an initial delay map, read it in
1668
1430
  if optiondict["initialdelayvalue"] is not None:
1669
1431
  try:
1670
1432
  theinitialdelay = float(optiondict["initialdelayvalue"])
@@ -1699,9 +1461,10 @@ def rapidtide_main(argparsingfunc):
1699
1461
  + 30.0
1700
1462
  + np.abs(optiondict["offsettime"])
1701
1463
  )
1702
- LGR.info(f"setting up fast resampling with padtime = {optiondict['fastresamplerpadtime']}")
1703
1464
  numpadtrs = int(optiondict["fastresamplerpadtime"] // fmritr)
1704
1465
  optiondict["fastresamplerpadtime"] = fmritr * numpadtrs
1466
+ LGR.info(f"setting up fast resampling with padtime = {optiondict['fastresamplerpadtime']}")
1467
+
1705
1468
  genlagtc = tide_resample.FastResampler(
1706
1469
  reference_x, reference_y, padtime=optiondict["fastresamplerpadtime"]
1707
1470
  )
@@ -1729,13 +1492,14 @@ def rapidtide_main(argparsingfunc):
1729
1492
  2 * numpadtrs + np.shape(initial_fmri_x)[0],
1730
1493
  )
1731
1494
 
1495
+ # prepare for regressor refinement, if we're doing it
1732
1496
  if (
1733
1497
  optiondict["passes"] > 1
1734
1498
  or optiondict["globalpreselect"]
1735
1499
  or optiondict["dofinalrefine"]
1736
1500
  or optiondict["convergencethresh"] is not None
1737
1501
  ):
1738
- # we will be doing regressor refinement, so set that up
1502
+ # we will be doing regressor refinement, so configure the refiner
1739
1503
  theRegressorRefiner = tide_regrefiner.RegressorRefiner(
1740
1504
  internalvalidfmrishape,
1741
1505
  internalvalidpaddedfmrishape,
@@ -1776,8 +1540,6 @@ def rapidtide_main(argparsingfunc):
1776
1540
  debug=optiondict["debug"],
1777
1541
  )
1778
1542
 
1779
- outfmriarray = np.zeros(internalfmrishape, dtype=rt_floattype)
1780
-
1781
1543
  # cycle over all voxels
1782
1544
  refine = True
1783
1545
  LGR.verbose(f"refine is set to {refine}")
@@ -1787,7 +1549,7 @@ def rapidtide_main(argparsingfunc):
1787
1549
  LGR.verbose(f"edgebufferfrac set to {optiondict['edgebufferfrac']}")
1788
1550
 
1789
1551
  # initialize the correlation fitter
1790
- thefitter = tide_classes.SimilarityFunctionFitter(
1552
+ theFitter = tide_classes.SimilarityFunctionFitter(
1791
1553
  lagmod=optiondict["lagmod"],
1792
1554
  lthreshval=optiondict["lthreshval"],
1793
1555
  uthreshval=optiondict["uthreshval"],
@@ -1808,11 +1570,6 @@ def rapidtide_main(argparsingfunc):
1808
1570
  if optiondict["echocancel"]:
1809
1571
  LGR.info("\n\nEcho cancellation")
1810
1572
  TimingLGR.info("Echo cancellation start")
1811
- calcsimilaritypass_func = addmemprofiling(
1812
- tide_calcsimfunc.correlationpass,
1813
- optiondict["memprofile"],
1814
- "before correlationpass",
1815
- )
1816
1573
 
1817
1574
  referencetc = tide_math.corrnormalize(
1818
1575
  resampref_y[osvalidsimcalcstart : osvalidsimcalcend + 1],
@@ -1820,12 +1577,12 @@ def rapidtide_main(argparsingfunc):
1820
1577
  windowfunc=optiondict["windowfunc"],
1821
1578
  )
1822
1579
 
1823
- disablemkl(optiondict["nprocs_calcsimilarity"], debug=threaddebug)
1580
+ tide_util.disablemkl(optiondict["nprocs_calcsimilarity"], debug=threaddebug)
1824
1581
  (
1825
1582
  voxelsprocessed_echo,
1826
1583
  theglobalmaxlist,
1827
1584
  trimmedcorrscale,
1828
- ) = calcsimilaritypass_func(
1585
+ ) = tide_calcsimfunc.correlationpass(
1829
1586
  fmri_data_valid[:, validsimcalcstart : validsimcalcend + 1],
1830
1587
  referencetc,
1831
1588
  theCorrelator,
@@ -1844,7 +1601,7 @@ def rapidtide_main(argparsingfunc):
1844
1601
  rt_floatset=rt_floatset,
1845
1602
  rt_floattype=rt_floattype,
1846
1603
  )
1847
- enablemkl(optiondict["mklthreads"], debug=threaddebug)
1604
+ tide_util.enablemkl(optiondict["mklthreads"], debug=threaddebug)
1848
1605
 
1849
1606
  for i in range(len(theglobalmaxlist)):
1850
1607
  theglobalmaxlist[i] = corrscale[theglobalmaxlist[i]] - optiondict["simcalcoffset"]
@@ -1913,237 +1670,51 @@ def rapidtide_main(argparsingfunc):
1913
1670
  )
1914
1671
 
1915
1672
  # Step -1 - check the regressor for periodic components in the passband
1916
- dolagmod = True
1917
- doreferencenotch = True
1918
- if optiondict["respdelete"]:
1919
- resptracker = tide_classes.FrequencyTracker(nperseg=64)
1920
- thetimes, thefreqs = resptracker.track(resampref_y, 1.0 / oversamptr)
1921
- tide_io.writevec(thefreqs, f"{outputname}_peakfreaks_pass{thepass}.txt")
1922
- resampref_y = resptracker.clean(resampref_y, 1.0 / oversamptr, thetimes, thefreqs)
1923
- tide_io.writevec(resampref_y, f"{outputname}_respfilt_pass{thepass}.txt")
1924
- referencetc = tide_math.corrnormalize(
1925
- resampref_y[osvalidsimcalcstart : osvalidsimcalcend + 1],
1926
- detrendorder=optiondict["detrendorder"],
1927
- windowfunc=optiondict["windowfunc"],
1928
- )
1929
- if optiondict["noisetimecoursespec"] is not None:
1930
- # align the noise signal with referencetc
1931
- (
1932
- shiftednoise,
1933
- optiondict[f"noisedelay_pass{thepass}"],
1934
- optiondict[f"noisecorr_pass{thepass}"],
1935
- dummy,
1936
- ) = tide_corr.aligntcwithref(
1937
- resampref_y,
1938
- resampnoise_y,
1939
- oversampfreq,
1940
- zerooutbadfit=False,
1941
- verbose=True,
1942
- )
1943
- LGR.info(
1944
- "Maximum correlation amplitude with noise regressor is "
1945
- + str(optiondict[f"noisecorr_pass{thepass}"])
1946
- + " at "
1947
- + str(optiondict[f"noisedelay_pass{thepass}"])
1948
- )
1949
-
1950
- # regress out
1951
- resampref_y, datatoremove, R, dummy = tide_fit.linfitfilt(
1952
- resampref_y, shiftednoise, debug=True
1953
- )
1954
-
1955
- # save
1956
- tide_io.writebidstsv(
1957
- f"{outputname}_desc-regressornoiseremoval_timeseries",
1958
- shiftednoise,
1959
- 1.0 / oversamptr,
1960
- starttime=0.0,
1961
- columns=[f"shiftednoise_pass{thepass}"],
1962
- append=(thepass > 1),
1963
- )
1964
- tide_io.writebidstsv(
1965
- f"{outputname}_desc-regressornoiseremoval_timeseries",
1966
- datatoremove,
1967
- 1.0 / oversamptr,
1968
- starttime=0.0,
1969
- columns=[f"removed_pass{thepass}"],
1970
- append=True,
1971
- )
1972
- tide_io.writebidstsv(
1973
- f"{outputname}_desc-regressornoiseremoval_timeseries",
1974
- resampref_y,
1975
- 1.0 / oversamptr,
1976
- starttime=0.0,
1977
- columns=[f"filtered_pass{thepass}"],
1978
- append=True,
1979
- )
1980
-
1981
- if optiondict["check_autocorrelation"]:
1982
- LGR.info("checking reference regressor autocorrelation properties")
1983
- optiondict["lagmod"] = 1000.0
1984
- lagindpad = np.max((lagmininpts, lagmaxinpts))
1985
- acmininpts = lagindpad
1986
- acmaxinpts = lagindpad
1987
- theCorrelator.setreftc(referencetc)
1988
- theCorrelator.setlimits(acmininpts, acmaxinpts)
1989
- # theCorrelator.setlimits(lagmininpts, lagmaxinpts)
1990
- print("check_autocorrelation:", acmininpts, acmaxinpts, lagmininpts, lagmaxinpts)
1991
- thexcorr, accheckcorrscale, dummy = theCorrelator.run(
1992
- resampref_y[osvalidsimcalcstart : osvalidsimcalcend + 1]
1993
- )
1994
- thefitter.setcorrtimeaxis(accheckcorrscale)
1995
- (
1996
- dummy,
1997
- dummy,
1998
- dummy,
1999
- acwidth,
2000
- dummy,
2001
- dummy,
2002
- dummy,
2003
- dummy,
2004
- ) = tide_simfuncfit.onesimfuncfit(
2005
- thexcorr,
2006
- thefitter,
2007
- despeckle_thresh=optiondict["despeckle_thresh"],
2008
- lthreshval=optiondict["lthreshval"],
2009
- fixdelay=optiondict["fixdelay"],
2010
- rt_floatset=rt_floatset,
2011
- rt_floattype=rt_floattype,
2012
- )
2013
- tide_io.writebidstsv(
2014
- f"{outputname}_desc-autocorr_timeseries",
2015
- thexcorr,
2016
- 1.0 / (accheckcorrscale[1] - accheckcorrscale[0]),
2017
- starttime=accheckcorrscale[0],
2018
- extraheaderinfo={
2019
- "Description": "Autocorrelation of the probe regressor for each pass"
2020
- },
2021
- columns=[f"pass{thepass}"],
2022
- append=(thepass > 1),
2023
- )
2024
- thelagthresh = np.max((abs(optiondict["lagmin"]), abs(optiondict["lagmax"])))
2025
- theampthresh = 0.1
2026
- LGR.info(
2027
- f"searching for sidelobes with amplitude > {theampthresh} "
2028
- f"with abs(lag) < {thelagthresh} s"
2029
- )
2030
- sidelobetime, sidelobeamp = tide_corr.check_autocorrelation(
2031
- accheckcorrscale,
2032
- thexcorr,
2033
- acampthresh=theampthresh,
2034
- aclagthresh=thelagthresh,
2035
- detrendorder=optiondict["detrendorder"],
2036
- )
2037
- optiondict["acwidth"] = acwidth + 0.0
2038
- optiondict["absmaxsigma"] = acwidth * 10.0
2039
- passsuffix = "_pass" + str(thepass)
2040
- if sidelobetime is not None:
2041
- optiondict["acsidelobelag" + passsuffix] = sidelobetime
2042
- optiondict["despeckle_thresh"] = np.max(
2043
- [optiondict["despeckle_thresh"], sidelobetime / 2.0]
2044
- )
2045
- optiondict["acsidelobeamp" + passsuffix] = sidelobeamp
2046
- LGR.warning(
2047
- f"\n\nWARNING: check_autocorrelation found bad sidelobe at {sidelobetime} "
2048
- f"seconds ({1.0 / sidelobetime} Hz)..."
2049
- )
2050
- # bidsify
2051
- """tide_io.writebidstsv(
2052
- f"{outputname}_desc-movingregressor_timeseries",
2053
- tide_math.stdnormalize(resampnonosref_y),
2054
- 1.0 / fmritr,
2055
- columns=["pass1"],
2056
- append=False,
2057
- )"""
2058
- tide_io.writenpvecs(
2059
- np.array([sidelobetime]),
2060
- f"{outputname}_autocorr_sidelobetime" + passsuffix + ".txt",
2061
- )
2062
- if optiondict["fix_autocorrelation"]:
2063
- LGR.info("Removing sidelobe")
2064
- if dolagmod:
2065
- LGR.info("subjecting lag times to modulus")
2066
- optiondict["lagmod"] = sidelobetime / 2.0
2067
- if doreferencenotch:
2068
- LGR.info("removing spectral component at sidelobe frequency")
2069
- acstopfreq = 1.0 / sidelobetime
2070
- acfixfilter = tide_filt.NoncausalFilter(
2071
- debug=optiondict["debug"],
2072
- )
2073
- acfixfilter.settype("arb_stop")
2074
- acfixfilter.setfreqs(
2075
- acstopfreq * 0.9,
2076
- acstopfreq * 0.95,
2077
- acstopfreq * 1.05,
2078
- acstopfreq * 1.1,
2079
- )
2080
- cleaned_resampref_y = tide_math.corrnormalize(
2081
- acfixfilter.apply(1.0 / oversamptr, resampref_y),
2082
- windowfunc="None",
2083
- detrendorder=optiondict["detrendorder"],
2084
- )
2085
- cleaned_referencetc = tide_math.corrnormalize(
2086
- cleaned_resampref_y,
2087
- detrendorder=optiondict["detrendorder"],
2088
- windowfunc=optiondict["windowfunc"],
2089
- )
2090
- cleaned_nonosreferencetc = tide_math.stdnormalize(
2091
- acfixfilter.apply(fmrifreq, resampnonosref_y)
2092
- )
2093
- tide_io.writebidstsv(
2094
- f"{outputname}_desc-cleanedreferencefmrires_info",
2095
- cleaned_nonosreferencetc,
2096
- fmrifreq,
2097
- columns=[f"pass{thepass}"],
2098
- append=(thepass > 1),
2099
- )
2100
- tide_io.writebidstsv(
2101
- f"{outputname}_desc-cleanedreference_info",
2102
- cleaned_referencetc,
2103
- 1.0 / oversamptr,
2104
- columns=[f"pass{thepass}"],
2105
- append=(thepass > 1),
2106
- )
2107
- tide_io.writebidstsv(
2108
- f"{outputname}_desc-cleanedresamprefy_info",
2109
- cleaned_resampref_y,
2110
- 1.0 / oversamptr,
2111
- columns=[f"pass{thepass}"],
2112
- append=(thepass > 1),
2113
- )
2114
- else:
2115
- cleaned_resampref_y = 1.0 * tide_math.corrnormalize(
2116
- resampref_y,
2117
- windowfunc="None",
2118
- detrendorder=optiondict["detrendorder"],
2119
- )
2120
- cleaned_referencetc = 1.0 * referencetc
2121
- cleaned_nonosreferencetc = 1.0 * resampnonosref_y
2122
- else:
2123
- LGR.info("no sidelobes found in range")
2124
- cleaned_resampref_y = 1.0 * tide_math.corrnormalize(
2125
- resampref_y,
2126
- windowfunc="None",
2127
- detrendorder=optiondict["detrendorder"],
2128
- )
2129
- cleaned_referencetc = 1.0 * referencetc
2130
- cleaned_nonosreferencetc = 1.0 * resampnonosref_y
2131
- else:
2132
- cleaned_resampref_y = 1.0 * tide_math.corrnormalize(
2133
- resampref_y, windowfunc="None", detrendorder=optiondict["detrendorder"]
2134
- )
2135
- cleaned_referencetc = 1.0 * referencetc
2136
- cleaned_nonosreferencetc = 1.0 * resampnonosref_y
1673
+ passsuffix = "_pass" + str(thepass)
1674
+ (
1675
+ cleaned_resampref_y,
1676
+ cleaned_referencetc,
1677
+ cleaned_nonosreferencetc,
1678
+ optiondict["despeckle_thresh"],
1679
+ optiondict["acsidelobeamp" + passsuffix],
1680
+ optiondict["acsidelobelag" + passsuffix],
1681
+ optiondict["lagmod"],
1682
+ optiondict["acwidth"],
1683
+ optiondict["absmaxsigma"],
1684
+ ) = tide_cleanregressor.cleanregressor(
1685
+ outputname,
1686
+ thepass,
1687
+ referencetc,
1688
+ resampref_y,
1689
+ resampnonosref_y,
1690
+ fmrifreq,
1691
+ oversampfreq,
1692
+ osvalidsimcalcstart,
1693
+ osvalidsimcalcend,
1694
+ lagmininpts,
1695
+ lagmaxinpts,
1696
+ theFitter,
1697
+ theCorrelator,
1698
+ optiondict["lagmin"],
1699
+ optiondict["lagmax"],
1700
+ LGR=LGR,
1701
+ check_autocorrelation=optiondict["check_autocorrelation"],
1702
+ fix_autocorrelation=optiondict["fix_autocorrelation"],
1703
+ despeckle_thresh=optiondict["despeckle_thresh"],
1704
+ lthreshval=optiondict["lthreshval"],
1705
+ fixdelay=optiondict["fixdelay"],
1706
+ detrendorder=optiondict["detrendorder"],
1707
+ windowfunc=optiondict["windowfunc"],
1708
+ respdelete=optiondict["respdelete"],
1709
+ debug=optiondict["debug"],
1710
+ rt_floattype=rt_floattype,
1711
+ rt_floatset=rt_floatset,
1712
+ )
2137
1713
 
2138
1714
  # Step 0 - estimate significance
2139
1715
  if optiondict["numestreps"] > 0:
2140
1716
  TimingLGR.info(f"Significance estimation start, pass {thepass}")
2141
1717
  LGR.info(f"\n\nSignificance estimation, pass {thepass}")
2142
- getNullDistributionData_func = addmemprofiling(
2143
- tide_nullsimfunc.getNullDistributionDatax,
2144
- optiondict["memprofile"],
2145
- "before getnulldistristributiondata",
2146
- )
2147
1718
  if optiondict["checkpoint"]:
2148
1719
  # bidsify
2149
1720
  """tide_io.writebidstsv(
@@ -2170,19 +1741,19 @@ def rapidtide_main(argparsingfunc):
2170
1741
  theMutualInformationator.setlimits(lagmininpts, lagmaxinpts)
2171
1742
  theMutualInformationator.setreftc(cleaned_resampref_y)
2172
1743
  dummy, trimmedcorrscale, dummy = theCorrelator.getfunction()
2173
- thefitter.setcorrtimeaxis(trimmedcorrscale)
1744
+ theFitter.setcorrtimeaxis(trimmedcorrscale)
2174
1745
 
2175
1746
  # parallel path for mutual information
2176
1747
  if optiondict["similaritymetric"] == "mutualinfo":
2177
1748
  theSimFunc = theMutualInformationator
2178
1749
  else:
2179
1750
  theSimFunc = theCorrelator
2180
- disablemkl(optiondict["nprocs_getNullDist"], debug=threaddebug)
2181
- simdistdata = getNullDistributionData_func(
1751
+ tide_util.disablemkl(optiondict["nprocs_getNullDist"], debug=threaddebug)
1752
+ simdistdata = tide_nullsimfunc.getNullDistributionDatax(
2182
1753
  cleaned_resampref_y,
2183
1754
  oversampfreq,
2184
1755
  theSimFunc,
2185
- thefitter,
1756
+ theFitter,
2186
1757
  numestreps=optiondict["numestreps"],
2187
1758
  nprocs=optiondict["nprocs_getNullDist"],
2188
1759
  alwaysmultiproc=optiondict["alwaysmultiproc"],
@@ -2193,7 +1764,7 @@ def rapidtide_main(argparsingfunc):
2193
1764
  rt_floatset=np.float64,
2194
1765
  rt_floattype="float64",
2195
1766
  )
2196
- enablemkl(optiondict["mklthreads"], debug=threaddebug)
1767
+ tide_util.enablemkl(optiondict["mklthreads"], debug=threaddebug)
2197
1768
 
2198
1769
  tide_io.writebidstsv(
2199
1770
  f"{outputname}_desc-simdistdata_info",
@@ -2284,11 +1855,20 @@ def rapidtide_main(argparsingfunc):
2284
1855
  "message3": "repetitions",
2285
1856
  },
2286
1857
  )
2287
-
2288
1858
  # write out the current version of the run options
2289
1859
  optiondict["currentstage"] = f"precorrelation_pass{thepass}"
2290
1860
  tide_io.writedicttojson(optiondict, f"{outputname}_desc-runoptions_info.json")
2291
1861
 
1862
+ # tide_delayestimate.estimateDelay(
1863
+ # fmri_data_valid[:, validsimcalcstart : validsimcalcend + 1],
1864
+ # initial_fmri_x[validsimcalcstart : validsimcalcend + 1],
1865
+ # os_fmri_x[osvalidsimcalcstart : osvalidsimcalcend + 1],
1866
+ # theMutualInformationator,
1867
+ # thepass,
1868
+ # )
1869
+ ########################
1870
+ # Delay estimation start
1871
+ ########################
2292
1872
  # Step 1 - Correlation step
2293
1873
  if optiondict["similaritymetric"] == "mutualinfo":
2294
1874
  similaritytype = "Mutual information"
@@ -2298,20 +1878,15 @@ def rapidtide_main(argparsingfunc):
2298
1878
  similaritytype = "MI enhanced correlation"
2299
1879
  LGR.info(f"\n\n{similaritytype} calculation, pass {thepass}")
2300
1880
  TimingLGR.info(f"{similaritytype} calculation start, pass {thepass}")
2301
- calcsimilaritypass_func = addmemprofiling(
2302
- tide_calcsimfunc.correlationpass,
2303
- optiondict["memprofile"],
2304
- "before correlationpass",
2305
- )
2306
1881
 
2307
- disablemkl(optiondict["nprocs_calcsimilarity"], debug=threaddebug)
1882
+ tide_util.disablemkl(optiondict["nprocs_calcsimilarity"], debug=threaddebug)
2308
1883
  if optiondict["similaritymetric"] == "mutualinfo":
2309
1884
  theMutualInformationator.setlimits(lagmininpts, lagmaxinpts)
2310
1885
  (
2311
1886
  voxelsprocessed_cp,
2312
1887
  theglobalmaxlist,
2313
1888
  trimmedcorrscale,
2314
- ) = calcsimilaritypass_func(
1889
+ ) = tide_calcsimfunc.correlationpass(
2315
1890
  fmri_data_valid[:, validsimcalcstart : validsimcalcend + 1],
2316
1891
  cleaned_referencetc,
2317
1892
  theMutualInformationator,
@@ -2335,7 +1910,7 @@ def rapidtide_main(argparsingfunc):
2335
1910
  voxelsprocessed_cp,
2336
1911
  theglobalmaxlist,
2337
1912
  trimmedcorrscale,
2338
- ) = calcsimilaritypass_func(
1913
+ ) = tide_calcsimfunc.correlationpass(
2339
1914
  fmri_data_valid[:, validsimcalcstart : validsimcalcend + 1],
2340
1915
  cleaned_referencetc,
2341
1916
  theCorrelator,
@@ -2354,7 +1929,7 @@ def rapidtide_main(argparsingfunc):
2354
1929
  rt_floatset=rt_floatset,
2355
1930
  rt_floattype=rt_floattype,
2356
1931
  )
2357
- enablemkl(optiondict["mklthreads"], debug=threaddebug)
1932
+ tide_util.enablemkl(optiondict["mklthreads"], debug=threaddebug)
2358
1933
 
2359
1934
  for i in range(len(theglobalmaxlist)):
2360
1935
  theglobalmaxlist[i] = corrscale[theglobalmaxlist[i]] - optiondict["simcalcoffset"]
@@ -2396,14 +1971,9 @@ def rapidtide_main(argparsingfunc):
2396
1971
  if optiondict["similaritymetric"] == "hybrid":
2397
1972
  LGR.info(f"\n\nPeak prefit calculation, pass {thepass}")
2398
1973
  TimingLGR.info(f"Peak prefit calculation start, pass {thepass}")
2399
- peakevalpass_func = addmemprofiling(
2400
- tide_peakeval.peakevalpass,
2401
- optiondict["memprofile"],
2402
- "before peakevalpass",
2403
- )
2404
1974
 
2405
- disablemkl(optiondict["nprocs_peakeval"], debug=threaddebug)
2406
- voxelsprocessed_pe, thepeakdict = peakevalpass_func(
1975
+ tide_util.disablemkl(optiondict["nprocs_peakeval"], debug=threaddebug)
1976
+ voxelsprocessed_pe, thepeakdict = tide_peakeval.peakevalpass(
2407
1977
  fmri_data_valid[:, validsimcalcstart : validsimcalcend + 1],
2408
1978
  cleaned_referencetc,
2409
1979
  initial_fmri_x[validsimcalcstart : validsimcalcend + 1],
@@ -2421,7 +1991,7 @@ def rapidtide_main(argparsingfunc):
2421
1991
  rt_floatset=rt_floatset,
2422
1992
  rt_floattype=rt_floattype,
2423
1993
  )
2424
- enablemkl(optiondict["mklthreads"], debug=threaddebug)
1994
+ tide_util.enablemkl(optiondict["mklthreads"], debug=threaddebug)
2425
1995
 
2426
1996
  TimingLGR.info(
2427
1997
  f"Peak prefit end, pass {thepass}",
@@ -2443,11 +2013,9 @@ def rapidtide_main(argparsingfunc):
2443
2013
  tide_io.writedicttojson(optiondict, f"{outputname}_desc-runoptions_info.json")
2444
2014
  LGR.info(f"\n\nTime lag estimation pass {thepass}")
2445
2015
  TimingLGR.info(f"Time lag estimation start, pass {thepass}")
2446
- fitcorr_func = addmemprofiling(
2447
- tide_simfuncfit.fitcorr, optiondict["memprofile"], "before fitcorr"
2448
- )
2449
- thefitter.setfunctype(optiondict["similaritymetric"])
2450
- thefitter.setcorrtimeaxis(trimmedcorrscale)
2016
+
2017
+ theFitter.setfunctype(optiondict["similaritymetric"])
2018
+ theFitter.setcorrtimeaxis(trimmedcorrscale)
2451
2019
 
2452
2020
  # use initial lags if this is a hybrid fit
2453
2021
  if optiondict["similaritymetric"] == "hybrid" and thepeakdict is not None:
@@ -2455,10 +2023,10 @@ def rapidtide_main(argparsingfunc):
2455
2023
  else:
2456
2024
  initlags = None
2457
2025
 
2458
- disablemkl(optiondict["nprocs_fitcorr"], debug=threaddebug)
2459
- voxelsprocessed_fc = fitcorr_func(
2026
+ tide_util.disablemkl(optiondict["nprocs_fitcorr"], debug=threaddebug)
2027
+ voxelsprocessed_fc = tide_simfuncfit.fitcorr(
2460
2028
  trimmedcorrscale,
2461
- thefitter,
2029
+ theFitter,
2462
2030
  corrout,
2463
2031
  fitmask,
2464
2032
  failreason,
@@ -2481,7 +2049,7 @@ def rapidtide_main(argparsingfunc):
2481
2049
  rt_floatset=rt_floatset,
2482
2050
  rt_floattype=rt_floattype,
2483
2051
  )
2484
- enablemkl(optiondict["mklthreads"], debug=threaddebug)
2052
+ tide_util.enablemkl(optiondict["mklthreads"], debug=threaddebug)
2485
2053
 
2486
2054
  TimingLGR.info(
2487
2055
  f"Time lag estimation end, pass {thepass}",
@@ -2521,10 +2089,10 @@ def rapidtide_main(argparsingfunc):
2521
2089
  numdespeckled = len(np.where(initlags != -1000000.0)[0])
2522
2090
  if lastnumdespeckled > numdespeckled > 0:
2523
2091
  lastnumdespeckled = numdespeckled
2524
- disablemkl(optiondict["nprocs_fitcorr"], debug=threaddebug)
2525
- voxelsprocessed_thispass = fitcorr_func(
2092
+ tide_util.disablemkl(optiondict["nprocs_fitcorr"], debug=threaddebug)
2093
+ voxelsprocessed_thispass = tide_simfuncfit.fitcorr(
2526
2094
  trimmedcorrscale,
2527
- thefitter,
2095
+ theFitter,
2528
2096
  corrout,
2529
2097
  fitmask,
2530
2098
  failreason,
@@ -2547,7 +2115,7 @@ def rapidtide_main(argparsingfunc):
2547
2115
  rt_floatset=rt_floatset,
2548
2116
  rt_floattype=rt_floattype,
2549
2117
  )
2550
- enablemkl(optiondict["mklthreads"], debug=threaddebug)
2118
+ tide_util.enablemkl(optiondict["mklthreads"], debug=threaddebug)
2551
2119
 
2552
2120
  voxelsprocessed_fc_ds += voxelsprocessed_thispass
2553
2121
  optiondict[
@@ -2740,6 +2308,9 @@ def rapidtide_main(argparsingfunc):
2740
2308
 
2741
2309
  # now shift the patches to align with the majority of the image
2742
2310
  tide_patch.interppatch(lagtimes, patchmap[validvoxels])
2311
+ ########################
2312
+ # Delay estimation end
2313
+ ########################
2743
2314
 
2744
2315
  # Step 2d - make a rank order map
2745
2316
  timepercentile = (
@@ -2869,11 +2440,11 @@ def rapidtide_main(argparsingfunc):
2869
2440
 
2870
2441
  # align timecourses to prepare for refinement
2871
2442
  LGR.info("aligning timecourses")
2872
- disablemkl(optiondict["nprocs_refine"], debug=threaddebug)
2443
+ tide_util.disablemkl(optiondict["nprocs_refine"], debug=threaddebug)
2873
2444
  voxelsprocessed_rra = theRegressorRefiner.alignvoxels(
2874
2445
  fmri_data_valid, fmritr, lagtimes
2875
2446
  )
2876
- enablemkl(optiondict["mklthreads"], debug=threaddebug)
2447
+ tide_util.enablemkl(optiondict["mklthreads"], debug=threaddebug)
2877
2448
  LGR.info(f"align complete: {voxelsprocessed_rra=}")
2878
2449
 
2879
2450
  # prenormalize
@@ -2908,57 +2479,6 @@ def rapidtide_main(argparsingfunc):
2908
2479
  )
2909
2480
  for key, value in outputdict.items():
2910
2481
  optiondict[key] = value
2911
-
2912
- """if optiondict["saveintermediatemaps"]:
2913
- if not optiondict["textio"]:
2914
- theheader = copy.deepcopy(nim_hdr)
2915
- if fileiscifti:
2916
- timeindex = theheader["dim"][0] - 1
2917
- spaceindex = theheader["dim"][0]
2918
- theheader["dim"][timeindex] = 1
2919
- theheader["dim"][spaceindex] = numspatiallocs
2920
- else:
2921
- theheader["dim"][0] = 3
2922
- theheader["dim"][4] = 1
2923
- theheader["pixdim"][4] = 1.0
2924
- bidspasssuffix = f"_intermediatedata-pass{thepass}"
2925
- maplist = [
2926
- (fitmask, "corrfit", "mask", None, "Voxels where correlation value was fit"),
2927
- (
2928
- failreason,
2929
- "corrfitfailreason",
2930
- "info",
2931
- None,
2932
- "Result codes for correlation fit",
2933
- ),
2934
- ]
2935
- if optiondict["savedespecklemasks"] and (optiondict["despeckle_passes"] > 0):
2936
- maplist.append(
2937
- (
2938
- despecklesavemask,
2939
- "despecklemask",
2940
- "map",
2941
- None,
2942
- "Voxels that underwent despeckling",
2943
- )
2944
- )
2945
- if thepass < optiondict["passes"]:
2946
- maplist.append(
2947
- (refinemask, "refinemask", "map", None, "Voxels used for regressor refinement")
2948
- )
2949
- tide_io.savemaplist(
2950
- f"{outputname}{bidspasssuffix}",
2951
- maplist,
2952
- validvoxels,
2953
- nativespaceshape,
2954
- theheader,
2955
- bidsbasedict,
2956
- textio=optiondict["textio"],
2957
- fileiscifti=fileiscifti,
2958
- rt_floattype=rt_floattype,
2959
- cifti_hdr=cifti_hdr,
2960
- )"""
2961
-
2962
2482
  # We are done with refinement.
2963
2483
 
2964
2484
  if optiondict["convergencethresh"] is None:
@@ -3045,13 +2565,8 @@ def rapidtide_main(argparsingfunc):
3045
2565
  thesize, theunit = tide_util.format_bytes(optiondict["totalcoherencebytes"])
3046
2566
  print(f"allocated {thesize:.3f} {theunit} {ramlocation} for coherence calculation")
3047
2567
 
3048
- coherencepass_func = addmemprofiling(
3049
- tide_calccoherence.coherencepass,
3050
- optiondict["memprofile"],
3051
- "before coherencepass",
3052
- )
3053
- disablemkl(1, debug=threaddebug)
3054
- voxelsprocessed_coherence = coherencepass_func(
2568
+ tide_util.disablemkl(1, debug=threaddebug)
2569
+ voxelsprocessed_coherence = tide_calccoherence.coherencepass(
3055
2570
  fmri_data_valid,
3056
2571
  theCoherer,
3057
2572
  coherencefunc,
@@ -3065,7 +2580,7 @@ def rapidtide_main(argparsingfunc):
3065
2580
  rt_floatset=rt_floatset,
3066
2581
  rt_floattype=rt_floattype,
3067
2582
  )
3068
- enablemkl(optiondict["mklthreads"], debug=threaddebug)
2583
+ tide_util.enablemkl(optiondict["mklthreads"], debug=threaddebug)
3069
2584
 
3070
2585
  # save the results of the calculations
3071
2586
  if not optiondict["textio"]:
@@ -3125,12 +2640,7 @@ def rapidtide_main(argparsingfunc):
3125
2640
  thesize, theunit = tide_util.format_bytes(optiondict["totalwienerbytes"])
3126
2641
  print(f"allocated {thesize:.3f} {theunit} {ramlocation} for wiener deconvolution")
3127
2642
 
3128
- wienerpass_func = addmemprofiling(
3129
- tide_wiener.wienerpass,
3130
- optiondict["memprofile"],
3131
- "before wienerpass",
3132
- )
3133
- voxelsprocessed_wiener = wienerpass_func(
2643
+ voxelsprocessed_wiener = tide_wiener.wienerpass(
3134
2644
  numspatiallocs,
3135
2645
  fmri_data_valid,
3136
2646
  threshval,
@@ -3189,29 +2699,11 @@ def rapidtide_main(argparsingfunc):
3189
2699
  f"reading in {optiondict['denoisesourcefile']} for sLFO filter, please wait"
3190
2700
  )
3191
2701
  sourcename = optiondict["denoisesourcefile"]
3192
- else:
3193
- LGR.info(f"rereading {fmrifilename} for sLFO filter, please wait")
3194
- sourcename = fmrifilename
3195
- if fileiscifti:
3196
- LGR.info("input file is CIFTI")
3197
- (
3198
- dummy,
3199
- cifti_hdr,
3200
- nim_data,
3201
- nim_hdr,
3202
- thedims,
3203
- thesizes,
3204
- dummy,
3205
- ) = tide_io.readfromcifti(sourcename)
3206
- else:
3207
- if optiondict["textio"]:
3208
- nim_data = tide_io.readvecs(sourcename)
3209
- else:
3210
- nim, nim_data, nim_hdr, thedims, thesizes = tide_io.readfromnifti(sourcename)
2702
+ theinputdata = tide_voxelData.VoxelData(sourcename, timestep=optiondict["realtr"])
2703
+ theinputdata.setvalidtimes(validstart, validend)
2704
+ theinputdata.setvalidvoxels(validvoxels)
3211
2705
 
3212
- fmri_data_valid = (
3213
- nim_data.reshape((numspatiallocs, timepoints))[:, validstart : validend + 1]
3214
- )[validvoxels, :] + 0.0
2706
+ fmri_data_valid = theinputdata.getvalidvoxels() + 0.0
3215
2707
 
3216
2708
  if optiondict["docvrmap"]:
3217
2709
  # percent normalize the fmri data
@@ -3234,18 +2726,13 @@ def rapidtide_main(argparsingfunc):
3234
2726
  tide_util.cleanup_shm(fmri_data_valid_shm)
3235
2727
  LGR.info("moving fmri data to shared memory")
3236
2728
  TimingLGR.info("Start moving fmri_data to shared memory")
3237
- numpy2shared_func = addmemprofiling(
3238
- tide_util.numpy2shared,
3239
- optiondict["memprofile"],
3240
- "before movetoshared (sLFO filter)",
3241
- )
3242
- fmri_data_valid, fmri_data_valid_shm = numpy2shared_func(
2729
+ fmri_data_valid, fmri_data_valid_shm = tide_util.numpy2shared(
3243
2730
  fmri_data_valid,
3244
2731
  rt_floatset,
3245
2732
  name=f"fmri_data_valid_regressionfilt_{optiondict['pid']}",
3246
2733
  )
3247
2734
  TimingLGR.info("End moving fmri_data to shared memory")
3248
- del nim_data
2735
+ theinputdata.unload()
3249
2736
 
3250
2737
  # now allocate the arrays needed for sLFO filtering
3251
2738
  if optiondict["refinedelay"]:
@@ -3307,12 +2794,6 @@ def rapidtide_main(argparsingfunc):
3307
2794
  )
3308
2795
  thesize, theunit = tide_util.format_bytes(optiondict["totalsLFOfilterbytes"])
3309
2796
  print(f"allocated {thesize:.3f} {theunit} {ramlocation} for sLFO filter/delay refinement")
3310
-
3311
- if optiondict["memprofile"]:
3312
- if optiondict["dolinfitfilt"]:
3313
- memcheckpoint("about to start sLFO noise removal...")
3314
- else:
3315
- memcheckpoint("about to start CVR magnitude estimation...")
3316
2797
  tide_util.logmem("before sLFO filter")
3317
2798
 
3318
2799
  if optiondict["dolinfitfilt"]:
@@ -3322,9 +2803,11 @@ def rapidtide_main(argparsingfunc):
3322
2803
  # set the threshval to zero
3323
2804
  mode = "cvrmap"
3324
2805
  optiondict["regressfiltthreshval"] = 0.0
2806
+
3325
2807
  if optiondict["debug"]:
3326
2808
  # dump the fmri input file going to sLFO filter
3327
2809
  if not optiondict["textio"]:
2810
+ outfmriarray = np.zeros(internalfmrishape, dtype=rt_floattype)
3328
2811
  theheader = copy.deepcopy(nim_hdr)
3329
2812
  if fileiscifti:
3330
2813
  timeindex = theheader["dim"][0] - 1
@@ -3337,6 +2820,7 @@ def rapidtide_main(argparsingfunc):
3337
2820
  else:
3338
2821
  theheader = None
3339
2822
  cifti_hdr = None
2823
+ outfmriarray = None
3340
2824
 
3341
2825
  maplist = [
3342
2826
  (
@@ -3359,6 +2843,8 @@ def rapidtide_main(argparsingfunc):
3359
2843
  rt_floattype=rt_floattype,
3360
2844
  cifti_hdr=cifti_hdr,
3361
2845
  )
2846
+ else:
2847
+ outfmriarray = None
3362
2848
 
3363
2849
  # refine the delay value prior to calculating the sLFO filter
3364
2850
  if optiondict["refinedelay"]:
@@ -3429,7 +2915,9 @@ def rapidtide_main(argparsingfunc):
3429
2915
  f"calculating delayoffsets for {filteredregressderivratios.shape[0]} voxels"
3430
2916
  )
3431
2917
  for i in range(filteredregressderivratios.shape[0]):
3432
- delayoffset[i] = tide_refinedelay.ratiotodelay(filteredregressderivratios[i])
2918
+ delayoffset[i], closestoffset = tide_refinedelay.ratiotodelay(
2919
+ filteredregressderivratios[i]
2920
+ )
3433
2921
  else:
3434
2922
  medfiltregressderivratios = np.zeros_like(regressderivratios)
3435
2923
  filteredregressderivratios = np.zeros_like(regressderivratios)
@@ -3530,7 +3018,6 @@ def rapidtide_main(argparsingfunc):
3530
3018
  mp_chunksize=optiondict["mp_chunksize"],
3531
3019
  showprogressbar=optiondict["showprogressbar"],
3532
3020
  alwaysmultiproc=optiondict["alwaysmultiproc"],
3533
- memprofile=optiondict["memprofile"],
3534
3021
  debug=optiondict["debug"],
3535
3022
  )
3536
3023
  )
@@ -3565,10 +3052,10 @@ def rapidtide_main(argparsingfunc):
3565
3052
  "message3": "voxels",
3566
3053
  },
3567
3054
  )
3568
- if optiondict["memprofile"]:
3569
- memcheckpoint("...done")
3570
3055
  tide_util.logmem("after sLFO filter")
3571
3056
  LGR.info("")
3057
+ else:
3058
+ outfmriarray = None
3572
3059
  ####################################################
3573
3060
  # sLFO filtering end
3574
3061
  ####################################################
@@ -3980,7 +3467,6 @@ def rapidtide_main(argparsingfunc):
3980
3467
  mp_chunksize=optiondict["mp_chunksize"],
3981
3468
  showprogressbar=optiondict["showprogressbar"],
3982
3469
  alwaysmultiproc=optiondict["alwaysmultiproc"],
3983
- memprofile=optiondict["memprofile"],
3984
3470
  debug=optiondict["debug"],
3985
3471
  )
3986
3472
 
@@ -4180,6 +3666,8 @@ def rapidtide_main(argparsingfunc):
4180
3666
  tide_util.cleanup_shm(outcorrarray_shm)
4181
3667
 
4182
3668
  # now save all the files that are of the same length as the input data file and masked
3669
+ if outfmriarray is None:
3670
+ outfmriarray = np.zeros(internalfmrishape, dtype=rt_floattype)
4183
3671
  if not optiondict["textio"]:
4184
3672
  theheader = copy.deepcopy(nim_hdr)
4185
3673
  if fileiscifti: