rapidtide 3.0a11__py3-none-any.whl → 3.0a12__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.
@@ -46,7 +46,7 @@ import rapidtide.multiproc as tide_multiproc
46
46
  import rapidtide.patchmatch as tide_patch
47
47
  import rapidtide.peakeval as tide_peakeval
48
48
  import rapidtide.refinedelay as tide_refinedelay
49
- import rapidtide.refineregressor as tide_refineregressor
49
+ import rapidtide.Refiner as tide_refiner
50
50
  import rapidtide.resample as tide_resample
51
51
  import rapidtide.simfuncfit as tide_simfuncfit
52
52
  import rapidtide.stats as tide_stats
@@ -1455,6 +1455,8 @@ def rapidtide_main(argparsingfunc):
1455
1455
  resampref_y *= tmaskos_y
1456
1456
  thefit, R2val = tide_fit.mlregress(tmaskos_y, resampref_y)
1457
1457
  resampref_y -= thefit[0, 1] * tmaskos_y
1458
+ else:
1459
+ tmaskos_y = None
1458
1460
 
1459
1461
  if optiondict["noisetimecoursespec"] is not None:
1460
1462
  tide_io.writebidstsv(
@@ -1730,38 +1732,49 @@ def rapidtide_main(argparsingfunc):
1730
1732
  if (
1731
1733
  optiondict["passes"] > 1
1732
1734
  or optiondict["globalpreselect"]
1735
+ or optiondict["dofinalrefine"]
1733
1736
  or optiondict["convergencethresh"] is not None
1734
1737
  ):
1735
- if optiondict["sharedmem"]:
1736
- shiftedtcs, shiftedtcs_shm = tide_util.allocshared(
1737
- internalvalidfmrishape, rt_floatset, name=f"shiftedtcs_{optiondict['pid']}"
1738
- )
1739
- weights, weights_shm = tide_util.allocshared(
1740
- internalvalidfmrishape, rt_floatset, name=f"weights_{optiondict['pid']}"
1741
- )
1742
- paddedshiftedtcs, paddedshiftedtcs_shm = tide_util.allocshared(
1743
- internalvalidpaddedfmrishape,
1744
- rt_floatset,
1745
- name=f"paddedshiftedtcs_{optiondict['pid']}",
1746
- )
1747
- paddedweights, paddedweights_shm = tide_util.allocshared(
1748
- internalvalidpaddedfmrishape,
1749
- rt_floatset,
1750
- name=f"paddedweights_{optiondict['pid']}",
1751
- )
1752
- ramlocation = "in shared memory"
1753
- else:
1754
- shiftedtcs = np.zeros(internalvalidfmrishape, dtype=rt_floattype)
1755
- weights = np.zeros(internalvalidfmrishape, dtype=rt_floattype)
1756
- paddedshiftedtcs = np.zeros(internalvalidpaddedfmrishape, dtype=rt_floattype)
1757
- paddedweights = np.zeros(internalvalidpaddedfmrishape, dtype=rt_floattype)
1758
- ramlocation = "locally"
1759
- optiondict["totalrefinementbytes"] = (
1760
- shiftedtcs.nbytes + weights.nbytes + paddedshiftedtcs.nbytes + paddedweights.nbytes
1738
+ # we will be doing regressor refinement, so set that up
1739
+ theRegressorRefiner = tide_refiner.Refiner(
1740
+ internalvalidfmrishape,
1741
+ internalvalidpaddedfmrishape,
1742
+ optiondict["pid"],
1743
+ optiondict["outputname"],
1744
+ initial_fmri_x,
1745
+ paddedinitial_fmri_x,
1746
+ os_fmri_x,
1747
+ sharedmem=optiondict["sharedmem"],
1748
+ offsettime=optiondict["offsettime"],
1749
+ ampthresh=optiondict["ampthresh"],
1750
+ lagminthresh=optiondict["lagminthresh"],
1751
+ lagmaxthresh=optiondict["lagmaxthresh"],
1752
+ sigmathresh=optiondict["sigmathresh"],
1753
+ cleanrefined=optiondict["cleanrefined"],
1754
+ bipolar=optiondict["bipolar"],
1755
+ fixdelay=optiondict["fixdelay"],
1756
+ LGR=LGR,
1757
+ nprocs=optiondict["nprocs_refine"],
1758
+ detrendorder=optiondict["detrendorder"],
1759
+ alwaysmultiproc=optiondict["alwaysmultiproc"],
1760
+ showprogressbar=optiondict["showprogressbar"],
1761
+ chunksize=optiondict["mp_chunksize"],
1762
+ padtrs=numpadtrs,
1763
+ refineprenorm=optiondict["refineprenorm"],
1764
+ refineweighting=optiondict["refineweighting"],
1765
+ refinetype=optiondict["refinetype"],
1766
+ pcacomponents=optiondict["pcacomponents"],
1767
+ windowfunc=optiondict["windowfunc"],
1768
+ passes=optiondict["passes"],
1769
+ maxpasses=optiondict["maxpasses"],
1770
+ convergencethresh=optiondict["convergencethresh"],
1771
+ interptype=optiondict["interptype"],
1772
+ usetmask=(optiondict["tincludemaskname"] is not None),
1773
+ tmask_y=tmask_y,
1774
+ tmaskos_y=tmaskos_y,
1775
+ fastresamplerpadtime=optiondict["fastresamplerpadtime"],
1776
+ debug=optiondict["debug"],
1761
1777
  )
1762
- thesize, theunit = tide_util.format_bytes(optiondict["totalrefinementbytes"])
1763
- print(f"allocated {thesize:.3f} {theunit} {ramlocation} for refinement")
1764
- tide_util.logmem("after refinement array allocation")
1765
1778
 
1766
1779
  outfmriarray = np.zeros(internalfmrishape, dtype=rt_floattype)
1767
1780
 
@@ -2779,6 +2792,7 @@ def rapidtide_main(argparsingfunc):
2779
2792
  thepass < optiondict["passes"]
2780
2793
  or optiondict["convergencethresh"] is not None
2781
2794
  or optiondict["globalpreselect"]
2795
+ or optiondict["dofinalrefine"]
2782
2796
  ):
2783
2797
  LGR.info(f"\n\nRegressor refinement, pass {thepass}")
2784
2798
  TimingLGR.info(f"Regressor refinement start, pass {thepass}")
@@ -2840,254 +2854,51 @@ def rapidtide_main(argparsingfunc):
2840
2854
  "NB: cannot exclude despeckled voxels from refinement - including for this pass"
2841
2855
  )
2842
2856
  thisinternalrefineexcludemask_valid = internalrefineexcludemask_valid
2857
+ theRegressorRefiner.setmasks(
2858
+ internalrefineincludemask_valid, thisinternalrefineexcludemask_valid
2859
+ )
2843
2860
 
2844
2861
  # regenerate regressor for next pass
2845
2862
  # create the refinement mask
2846
2863
  LGR.info("making refine mask")
2847
- (
2848
- dummy,
2849
- refinemask,
2850
- locationfails,
2851
- ampfails,
2852
- lagfails,
2853
- sigmafails,
2854
- numinmask,
2855
- ) = tide_refineregressor.makerefinemask(
2856
- lagstrengths,
2857
- lagtimes,
2858
- lagsigma,
2859
- fitmask,
2860
- offsettime=optiondict["offsettime"],
2861
- ampthresh=optiondict["ampthresh"],
2862
- lagmaskside=optiondict["lagmaskside"],
2863
- lagminthresh=optiondict["lagminthresh"],
2864
- lagmaxthresh=optiondict["lagmaxthresh"],
2865
- sigmathresh=optiondict["sigmathresh"],
2866
- cleanrefined=optiondict["cleanrefined"],
2867
- bipolar=optiondict["bipolar"],
2868
- includemask=internalrefineincludemask_valid,
2869
- excludemask=thisinternalrefineexcludemask_valid,
2870
- )
2871
-
2872
- if numinmask == 0:
2873
- LGR.critical("No voxels in refine mask - adjust thresholds or external masks")
2864
+ createdmask = theRegressorRefiner.makemask(lagstrengths, lagtimes, lagsigma, fitmask)
2865
+ print(f"Refine mask has {theRegressorRefiner.refinemaskvoxels} voxels")
2866
+ if not createdmask:
2867
+ print("no voxels qualify for refinement - exiting")
2874
2868
  sys.exit()
2875
2869
 
2876
2870
  # align timecourses to prepare for refinement
2877
- alignvoxels_func = addmemprofiling(
2878
- tide_refineregressor.alignvoxels,
2879
- optiondict["memprofile"],
2880
- "before aligning voxel timecourses",
2881
- )
2882
2871
  LGR.info("aligning timecourses")
2883
2872
  disablemkl(optiondict["nprocs_refine"], debug=threaddebug)
2884
- voxelsprocessed_rra = alignvoxels_func(
2885
- fmri_data_valid,
2886
- fmritr,
2887
- shiftedtcs,
2888
- weights,
2889
- paddedshiftedtcs,
2890
- paddedweights,
2891
- lagtimes,
2892
- refinemask,
2893
- nprocs=optiondict["nprocs_refine"],
2894
- detrendorder=optiondict["detrendorder"],
2895
- offsettime=optiondict["offsettime"],
2896
- alwaysmultiproc=optiondict["alwaysmultiproc"],
2897
- showprogressbar=optiondict["showprogressbar"],
2898
- chunksize=optiondict["mp_chunksize"],
2899
- padtrs=numpadtrs,
2900
- rt_floatset=rt_floatset,
2901
- rt_floattype=rt_floattype,
2873
+ voxelsprocessed_rra = theRegressorRefiner.alignvoxels(
2874
+ fmri_data_valid, fmritr, lagtimes
2902
2875
  )
2903
2876
  enablemkl(optiondict["mklthreads"], debug=threaddebug)
2904
2877
  LGR.info(f"align complete: {voxelsprocessed_rra=}")
2905
2878
 
2879
+ # prenormalize
2906
2880
  LGR.info("prenormalizing timecourses")
2907
- tide_refineregressor.prenorm(
2908
- paddedshiftedtcs,
2909
- refinemask,
2910
- lagtimes,
2911
- optiondict["lagmaxthresh"],
2912
- lagstrengths,
2913
- R2,
2914
- optiondict["refineprenorm"],
2915
- optiondict["refineweighting"],
2916
- )
2881
+ theRegressorRefiner.prenormalize(lagtimes, lagstrengths, R2)
2917
2882
 
2883
+ # now doing the refinement
2918
2884
  (
2919
2885
  voxelsprocessed_rr,
2920
- paddedoutputdata,
2921
- ) = tide_refineregressor.dorefine(
2922
- paddedshiftedtcs,
2923
- refinemask,
2924
- weights,
2886
+ outputdict,
2887
+ previousnormoutputdata,
2888
+ resampref_y,
2889
+ resampnonosref_y,
2890
+ stoprefining,
2891
+ refinestopreason,
2892
+ genlagtc,
2893
+ ) = theRegressorRefiner.refine(
2925
2894
  theprefilter,
2926
2895
  fmritr,
2927
2896
  thepass,
2928
2897
  lagstrengths,
2929
2898
  lagtimes,
2930
- optiondict["refinetype"],
2931
- optiondict["fmrifreq"],
2932
- optiondict["outputname"],
2933
- detrendorder=optiondict["detrendorder"],
2934
- pcacomponents=optiondict["pcacomponents"],
2935
- dodispersioncalc=optiondict["dodispersioncalc"],
2936
- dispersioncalc_lower=optiondict["dispersioncalc_lower"],
2937
- dispersioncalc_upper=optiondict["dispersioncalc_upper"],
2938
- dispersioncalc_step=optiondict["dispersioncalc_step"],
2939
- windowfunc=optiondict["windowfunc"],
2940
- cleanrefined=optiondict["cleanrefined"],
2941
- bipolar=optiondict["bipolar"],
2942
- debug=optiondict["debug"],
2943
- rt_floatset=rt_floatset,
2944
- rt_floattype=rt_floattype,
2945
- )
2946
- optiondict["refinemasksize_pass" + str(thepass)] = voxelsprocessed_rr
2947
- optiondict["refinemaskpct_pass" + str(thepass)] = (
2948
- 100.0 * voxelsprocessed_rr / optiondict["corrmasksize"]
2899
+ previousnormoutputdata,
2900
+ optiondict["corrmasksize"],
2949
2901
  )
2950
- optiondict["refinelocationfails_pass" + str(thepass)] = locationfails
2951
- optiondict["refineampfails_pass" + str(thepass)] = ampfails
2952
- optiondict["refinelagfails_pass" + str(thepass)] = lagfails
2953
- optiondict["refinesigmafails_pass" + str(thepass)] = sigmafails
2954
- if voxelsprocessed_rr > 0:
2955
- paddednormoutputdata = tide_math.stdnormalize(
2956
- theprefilter.apply(fmrifreq, paddedoutputdata)
2957
- )
2958
- outputdata = paddedoutputdata[numpadtrs:-numpadtrs]
2959
- normoutputdata = tide_math.stdnormalize(theprefilter.apply(fmrifreq, outputdata))
2960
- normunfilteredoutputdata = tide_math.stdnormalize(outputdata)
2961
- tide_io.writebidstsv(
2962
- f"{outputname}_desc-refinedmovingregressor_timeseries",
2963
- normunfilteredoutputdata,
2964
- 1.0 / fmritr,
2965
- columns=["unfiltered_pass" + str(thepass)],
2966
- extraheaderinfo={
2967
- "Description": "The raw and filtered probe regressor produced by the refinement procedure, at the time resolution of the data"
2968
- },
2969
- append=(thepass > 1),
2970
- )
2971
- tide_io.writebidstsv(
2972
- f"{outputname}_desc-refinedmovingregressor_timeseries",
2973
- normoutputdata,
2974
- 1.0 / fmritr,
2975
- columns=["filtered_pass" + str(thepass)],
2976
- extraheaderinfo={
2977
- "Description": "The raw and filtered probe regressor produced by the refinement procedure, at the time resolution of the data"
2978
- },
2979
- append=True,
2980
- )
2981
-
2982
- # check for convergence
2983
- regressormse = mse(normoutputdata, previousnormoutputdata)
2984
- optiondict["regressormse_pass" + str(thepass).zfill(2)] = regressormse
2985
- LGR.info(f"regressor difference at end of pass {thepass:d} is {regressormse:.6f}")
2986
- if optiondict["convergencethresh"] is not None:
2987
- if thepass >= optiondict["maxpasses"]:
2988
- LGR.info("refinement ended (maxpasses reached)")
2989
- stoprefining = True
2990
- refinestopreason = "maxpassesreached"
2991
- elif regressormse < optiondict["convergencethresh"]:
2992
- LGR.info("refinement ended (refinement has converged")
2993
- stoprefining = True
2994
- refinestopreason = "convergence"
2995
- else:
2996
- stoprefining = False
2997
- elif thepass >= optiondict["passes"]:
2998
- stoprefining = True
2999
- refinestopreason = "passesreached"
3000
- else:
3001
- stoprefining = False
3002
-
3003
- if optiondict["detrendorder"] > 0:
3004
- resampnonosref_y = tide_fit.detrend(
3005
- tide_resample.doresample(
3006
- paddedinitial_fmri_x,
3007
- paddednormoutputdata,
3008
- initial_fmri_x,
3009
- method=optiondict["interptype"],
3010
- ),
3011
- order=optiondict["detrendorder"],
3012
- demean=optiondict["dodemean"],
3013
- )
3014
- resampref_y = tide_fit.detrend(
3015
- tide_resample.doresample(
3016
- paddedinitial_fmri_x,
3017
- paddednormoutputdata,
3018
- os_fmri_x,
3019
- method=optiondict["interptype"],
3020
- ),
3021
- order=optiondict["detrendorder"],
3022
- demean=optiondict["dodemean"],
3023
- )
3024
- else:
3025
- resampnonosref_y = tide_resample.doresample(
3026
- paddedinitial_fmri_x,
3027
- paddednormoutputdata,
3028
- initial_fmri_x,
3029
- method=optiondict["interptype"],
3030
- )
3031
- resampref_y = tide_resample.doresample(
3032
- paddedinitial_fmri_x,
3033
- paddednormoutputdata,
3034
- os_fmri_x,
3035
- method=optiondict["interptype"],
3036
- )
3037
- if optiondict["tincludemaskname"] is not None:
3038
- resampnonosref_y *= tmask_y
3039
- thefit, R2val = tide_fit.mlregress(tmask_y, resampnonosref_y)
3040
- resampnonosref_y -= thefit[0, 1] * tmask_y
3041
- resampref_y *= tmaskos_y
3042
- thefit, R2val = tide_fit.mlregress(tmaskos_y, resampref_y)
3043
- resampref_y -= thefit[0, 1] * tmaskos_y
3044
-
3045
- # reinitialize genlagtc for resampling
3046
- previousnormoutputdata = normoutputdata + 0.0
3047
- genlagtc = tide_resample.FastResampler(
3048
- paddedinitial_fmri_x,
3049
- paddednormoutputdata,
3050
- padtime=optiondict["fastresamplerpadtime"],
3051
- )
3052
- genlagtc.save(f"{outputname}_desc-lagtcgenerator_timeseries")
3053
- if optiondict["debug"]:
3054
- genlagtc.info()
3055
- (
3056
- optiondict[f"kurtosis_reference_pass{thepass + 1}"],
3057
- optiondict[f"kurtosisz_reference_pass{thepass + 1}"],
3058
- optiondict[f"kurtosisp_reference_pass{thepass + 1}"],
3059
- ) = tide_stats.kurtosisstats(resampref_y)
3060
- (
3061
- optiondict[f"skewness_reference_pass{thepass + 1}"],
3062
- optiondict[f"skewnessz_reference_pass{thepass + 1}"],
3063
- optiondict[f"skewnessp_reference_pass{thepass + 1}"],
3064
- ) = tide_stats.skewnessstats(resampref_y)
3065
- if not stoprefining:
3066
- tide_io.writebidstsv(
3067
- f"{outputname}_desc-movingregressor_timeseries",
3068
- tide_math.stdnormalize(resampnonosref_y),
3069
- 1.0 / fmritr,
3070
- columns=["pass" + str(thepass + 1)],
3071
- extraheaderinfo={
3072
- "Description": "The probe regressor used in each pass, at the time resolution of the data"
3073
- },
3074
- append=True,
3075
- )
3076
- tide_io.writebidstsv(
3077
- f"{outputname}_desc-oversampledmovingregressor_timeseries",
3078
- tide_math.stdnormalize(resampref_y),
3079
- oversampfreq,
3080
- columns=["pass" + str(thepass + 1)],
3081
- extraheaderinfo={
3082
- "Description": "The probe regressor used in each pass, at the time resolution used for calculating the similarity function"
3083
- },
3084
- append=True,
3085
- )
3086
- else:
3087
- LGR.warning(f"refinement failed - terminating at end of pass {thepass}")
3088
- stoprefining = True
3089
- refinestopreason = "emptymask"
3090
-
3091
2902
  TimingLGR.info(
3092
2903
  f"Regressor refinement end, pass {thepass}",
3093
2904
  {
@@ -3095,7 +2906,10 @@ def rapidtide_main(argparsingfunc):
3095
2906
  "message3": "voxels",
3096
2907
  },
3097
2908
  )
3098
- if optiondict["saveintermediatemaps"]:
2909
+ for key, value in outputdict.items():
2910
+ optiondict[key] = value
2911
+
2912
+ """if optiondict["saveintermediatemaps"]:
3099
2913
  if not optiondict["textio"]:
3100
2914
  theheader = copy.deepcopy(nim_hdr)
3101
2915
  if fileiscifti:
@@ -3143,9 +2957,10 @@ def rapidtide_main(argparsingfunc):
3143
2957
  fileiscifti=fileiscifti,
3144
2958
  rt_floattype=rt_floattype,
3145
2959
  cifti_hdr=cifti_hdr,
3146
- )
2960
+ )"""
2961
+
2962
+ # We are done with refinement.
3147
2963
 
3148
- # We are done with refinement.
3149
2964
  if optiondict["convergencethresh"] is None:
3150
2965
  optiondict["actual_passes"] = optiondict["passes"]
3151
2966
  else:
@@ -3430,7 +3245,9 @@ def rapidtide_main(argparsingfunc):
3430
3245
 
3431
3246
  # now allocate the arrays needed for GLM filtering
3432
3247
  if optiondict["refinedelay"]:
3433
- derivaxissize = np.max([2, optiondict["glmderivs"] + 1])
3248
+ derivaxissize = np.max(
3249
+ [optiondict["refineglmderivs"] + 1, optiondict["glmderivs"] + 1]
3250
+ )
3434
3251
  else:
3435
3252
  derivaxissize = optiondict["glmderivs"] + 1
3436
3253
  internalvalidspaceshapederivs = (
@@ -3560,51 +3377,87 @@ def rapidtide_main(argparsingfunc):
3560
3377
  glmmean,
3561
3378
  rvalue,
3562
3379
  r2value,
3563
- fitNorm[:, :2],
3564
- fitcoeff[:, :2],
3380
+ fitNorm[:, : (optiondict["refineglmderivs"] + 1)],
3381
+ fitcoeff[:, : (optiondict["refineglmderivs"] + 1)],
3565
3382
  movingsignal,
3566
3383
  lagtc,
3567
3384
  filtereddata,
3568
3385
  LGR,
3569
3386
  TimingLGR,
3570
3387
  optiondict,
3388
+ glmderivs=optiondict["refineglmderivs"],
3571
3389
  debug=optiondict["debug"],
3572
3390
  )
3573
3391
 
3574
- medfiltglmderivratios, filteredglmderivratios, delayoffsetMAD = (
3575
- tide_refinedelay.filterderivratios(
3576
- glmderivratios,
3577
- nativespaceshape,
3578
- validvoxels,
3579
- (xdim, ydim, slicethickness),
3580
- gausssigma=optiondict["delayoffsetgausssigma"],
3581
- patchthresh=optiondict["delaypatchthresh"],
3582
- fileiscifti=fileiscifti,
3583
- textio=optiondict["textio"],
3584
- rt_floattype="float64",
3392
+ if optiondict["refineglmderivs"] == 1:
3393
+ medfiltglmderivratios, filteredglmderivratios, delayoffsetMAD = (
3394
+ tide_refinedelay.filterderivratios(
3395
+ glmderivratios,
3396
+ nativespaceshape,
3397
+ validvoxels,
3398
+ (xdim, ydim, slicethickness),
3399
+ gausssigma=optiondict["delayoffsetgausssigma"],
3400
+ patchthresh=optiondict["delaypatchthresh"],
3401
+ fileiscifti=fileiscifti,
3402
+ textio=optiondict["textio"],
3403
+ rt_floattype="float64",
3404
+ debug=optiondict["debug"],
3405
+ )
3406
+ )
3407
+ optiondict["delayoffsetMAD"] = delayoffsetMAD
3408
+
3409
+ # find the mapping of glm ratios to delays
3410
+ tide_refinedelay.trainratiotooffset(
3411
+ genlagtc,
3412
+ initial_fmri_x,
3413
+ outputname,
3414
+ optiondict["outputlevel"],
3415
+ mindelay=optiondict["mindelay"],
3416
+ maxdelay=optiondict["maxdelay"],
3417
+ numpoints=optiondict["numpoints"],
3585
3418
  debug=optiondict["debug"],
3586
3419
  )
3587
- )
3588
- optiondict["delayoffsetMAD"] = delayoffsetMAD
3589
3420
 
3590
- # find the mapping of glm ratios to delays
3591
- tide_refinedelay.trainratiotooffset(
3592
- genlagtc,
3593
- initial_fmri_x,
3594
- outputname,
3595
- optiondict["outputlevel"],
3596
- mindelay=optiondict["mindelay"],
3597
- maxdelay=optiondict["maxdelay"],
3598
- numpoints=optiondict["numpoints"],
3599
- debug=optiondict["debug"],
3600
- )
3421
+ # now calculate the delay offsets
3422
+ delayoffset = np.zeros_like(filteredglmderivratios)
3423
+ if optiondict["debug"]:
3424
+ print(f"calculating delayoffsets for {filteredglmderivratios.shape[0]} voxels")
3425
+ for i in range(filteredglmderivratios.shape[0]):
3426
+ delayoffset[i] = tide_refinedelay.ratiotodelay(filteredglmderivratios[i])
3427
+ else:
3428
+ medfiltglmderivratios = np.zeros_like(glmderivratios)
3429
+ filteredglmderivratios = np.zeros_like(glmderivratios)
3430
+ delayoffsetMAD = np.zeros(optiondict["refineglmderivs"], dtype=float)
3431
+ for i in range(args.refineglmderivs):
3432
+ (
3433
+ medfiltglmderivratios[i, :],
3434
+ filteredglmderivratios[i, :],
3435
+ delayoffsetMAD[i],
3436
+ ) = tide_refinedelay.filterderivratios(
3437
+ glmderivratios[i, :],
3438
+ (xsize, ysize, numslices),
3439
+ validvoxels,
3440
+ (xdim, ydim, slicedim),
3441
+ gausssigma=optiondict["delayoffsetgausssigma"],
3442
+ patchthresh=optiondict["delaypatchthresh"],
3443
+ fileiscifti=False,
3444
+ textio=False,
3445
+ rt_floattype=rt_floattype,
3446
+ debug=optiondict["debug"],
3447
+ )
3448
+ optiondict[f"delayoffsetMAD_{i + 1}"] = delayoffsetMAD[i]
3449
+
3450
+ # now calculate the delay offsets
3451
+ delayoffset = np.zeros_like(filteredglmderivratios[0, :])
3452
+ if optiondict["debug"]:
3453
+ print(f"calculating delayoffsets for {filteredglmderivratios.shape[1]} voxels")
3454
+ for i in range(filteredglmderivratios.shape[1]):
3455
+ delayoffset[i] = tide_refinedelay.coffstodelay(
3456
+ filteredglmderivratios[:, i],
3457
+ mindelay=optiondict["mindelay"],
3458
+ maxdelay=optiondict["maxdelay"],
3459
+ )
3601
3460
 
3602
- # now calculate the delay offsets
3603
- delayoffset = filteredglmderivratios * 0.0
3604
- if optiondict["debug"]:
3605
- print(f"calculating delayoffsets for {filteredglmderivratios.shape[0]} voxels")
3606
- for i in range(filteredglmderivratios.shape[0]):
3607
- delayoffset[i] = tide_refinedelay.ratiotodelay(filteredglmderivratios[i])
3608
3461
  namesuffix = "_desc-delayoffset_hist"
3609
3462
  if optiondict["doglmfilt"]:
3610
3463
  tide_stats.makeandsavehistogram(
@@ -3864,29 +3717,55 @@ def rapidtide_main(argparsingfunc):
3864
3717
  (np.fabs(rvalue), "maxcorralt", "map", None, "R value of the GLM fit, with sign"),
3865
3718
  ]
3866
3719
  if (optiondict["outputlevel"] != "min") and (optiondict["outputlevel"] != "less"):
3867
- savelist += [
3868
- (
3869
- glmderivratios,
3870
- "glmderivratios",
3871
- "map",
3872
- None,
3873
- "Ratio of the first derivative of delayed sLFO to the delayed sLFO",
3874
- ),
3875
- (
3876
- medfiltglmderivratios,
3877
- "medfiltglmderivratios",
3878
- "map",
3879
- None,
3880
- "Median filtered version of the glmderivratios map",
3881
- ),
3882
- (
3883
- filteredglmderivratios,
3884
- "filteredglmderivratios",
3885
- "map",
3886
- None,
3887
- "glmderivratios, with outliers patched using median filtered data",
3888
- ),
3889
- ]
3720
+ if optiondict["refineglmderivs"] > 1:
3721
+ for i in range(optiondict["refineglmderivs"]):
3722
+ savelist += [
3723
+ (
3724
+ glmderivratios[i, :],
3725
+ f"glmderivratios_{i}",
3726
+ "map",
3727
+ None,
3728
+ f"Ratio of derivative {i + 1} of delayed sLFO to the delayed sLFO",
3729
+ ),
3730
+ (
3731
+ medfiltglmderivratios[i, :],
3732
+ f"medfiltglmderivratios_{i}",
3733
+ "map",
3734
+ None,
3735
+ f"Median filtered version of the glmderivratios_{i} map",
3736
+ ),
3737
+ (
3738
+ filteredglmderivratios[i, :],
3739
+ f"filteredglmderivratios_{i}",
3740
+ "map",
3741
+ None,
3742
+ f"glmderivratios_{i}, with outliers patched using median filtered data",
3743
+ ),
3744
+ ]
3745
+ else:
3746
+ savelist += [
3747
+ (
3748
+ glmderivratios,
3749
+ "glmderivratios",
3750
+ "map",
3751
+ None,
3752
+ "Ratio of the first derivative of delayed sLFO to the delayed sLFO",
3753
+ ),
3754
+ (
3755
+ medfiltglmderivratios,
3756
+ "medfiltglmderivratios",
3757
+ "map",
3758
+ None,
3759
+ "Median filtered version of the glmderivratios map",
3760
+ ),
3761
+ (
3762
+ filteredglmderivratios,
3763
+ "filteredglmderivratios",
3764
+ "map",
3765
+ None,
3766
+ "glmderivratios, with outliers patched using median filtered data",
3767
+ ),
3768
+ ]
3890
3769
  if optiondict["calccoherence"]:
3891
3770
  savelist += [
3892
3771
  (coherencepeakval, "coherencepeakval", "map", None, "Coherence peak value"),
@@ -4118,7 +3997,7 @@ def rapidtide_main(argparsingfunc):
4118
3997
  lagstrengths[voxel],
4119
3998
  sigfit,
4120
3999
  neglogpmax=neglogpmax,
4121
- debug=optiondict["focaldebug"],
4000
+ debug=optiondict["debug"],
4122
4001
  )
4123
4002
  masklist += [
4124
4003
  (
@@ -4147,6 +4026,7 @@ def rapidtide_main(argparsingfunc):
4147
4026
  if (optiondict["passes"] > 1 or optiondict["globalpreselect"]) and optiondict[
4148
4027
  "refinestopreason"
4149
4028
  ] != "emptymask":
4029
+ refinemask = theRegressorRefiner.getrefinemask()
4150
4030
  if optiondict["globalpreselect"]:
4151
4031
  masklist = [
4152
4032
  (
@@ -4283,7 +4163,7 @@ def rapidtide_main(argparsingfunc):
4283
4163
  if optiondict["savelagregressors"]:
4284
4164
  maplist += [
4285
4165
  (
4286
- paddedshiftedtcs[:, numpadtrs:-numpadtrs],
4166
+ (theRegressorRefiner.getpaddedshiftedtcs())[:, numpadtrs:-numpadtrs],
4287
4167
  "shiftedtcs",
4288
4168
  "bold",
4289
4169
  None,
@@ -4351,15 +4231,7 @@ def rapidtide_main(argparsingfunc):
4351
4231
 
4352
4232
  # clean up
4353
4233
  if optiondict["passes"] > 1:
4354
- del paddedshiftedtcs
4355
- del paddedweights
4356
- del shiftedtcs
4357
- del weights
4358
- if optiondict["sharedmem"]:
4359
- tide_util.cleanup_shm(paddedshiftedtcs_shm)
4360
- tide_util.cleanup_shm(paddedweights_shm)
4361
- tide_util.cleanup_shm(shiftedtcs_shm)
4362
- tide_util.cleanup_shm(weights_shm)
4234
+ theRegressorRefiner.cleanup()
4363
4235
  if optiondict["doglmfilt"]:
4364
4236
  del lagtc
4365
4237
  del filtereddata