rapidtide 3.0.8__py3-none-any.whl → 3.0.10__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 (38) hide show
  1. rapidtide/OrthoImageItem.py +15 -6
  2. rapidtide/RapidtideDataset.py +22 -7
  3. rapidtide/_version.py +3 -3
  4. rapidtide/data/examples/src/testfmri +26 -20
  5. rapidtide/data/examples/src/testhappy +0 -1
  6. rapidtide/filter.py +60 -111
  7. rapidtide/fit.py +501 -108
  8. rapidtide/io.py +19 -8
  9. rapidtide/linfitfiltpass.py +44 -25
  10. rapidtide/refinedelay.py +2 -2
  11. rapidtide/refineregressor.py +1 -1
  12. rapidtide/resample.py +8 -8
  13. rapidtide/simFuncClasses.py +13 -7
  14. rapidtide/tests/.coveragerc +17 -11
  15. rapidtide/tests/test_delayestimation.py +1 -1
  16. rapidtide/tests/test_findmaxlag.py +31 -16
  17. rapidtide/tests/test_fullrunrapidtide_v8.py +66 -0
  18. rapidtide/tests/test_padvec.py +19 -1
  19. rapidtide/tests/test_simroundtrip.py +124 -0
  20. rapidtide/tidepoolTemplate.py +37 -37
  21. rapidtide/tidepoolTemplate_alt.py +40 -40
  22. rapidtide/tidepoolTemplate_big.py +56 -56
  23. rapidtide/workflows/calcSimFuncMap.py +271 -0
  24. rapidtide/workflows/delayvar.py +1 -1
  25. rapidtide/workflows/fitSimFuncMap.py +427 -0
  26. rapidtide/workflows/happy.py +2 -2
  27. rapidtide/workflows/parser_funcs.py +1 -1
  28. rapidtide/workflows/rapidtide.py +197 -48
  29. rapidtide/workflows/rapidtide_parser.py +23 -2
  30. rapidtide/workflows/regressfrommaps.py +7 -7
  31. rapidtide/workflows/tidepool.py +51 -15
  32. {rapidtide-3.0.8.dist-info → rapidtide-3.0.10.dist-info}/METADATA +3 -3
  33. {rapidtide-3.0.8.dist-info → rapidtide-3.0.10.dist-info}/RECORD +37 -34
  34. rapidtide/workflows/estimateDelayMap.py +0 -536
  35. {rapidtide-3.0.8.dist-info → rapidtide-3.0.10.dist-info}/WHEEL +0 -0
  36. {rapidtide-3.0.8.dist-info → rapidtide-3.0.10.dist-info}/entry_points.txt +0 -0
  37. {rapidtide-3.0.8.dist-info → rapidtide-3.0.10.dist-info}/licenses/LICENSE +0 -0
  38. {rapidtide-3.0.8.dist-info → rapidtide-3.0.10.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,427 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ #
4
+ # Copyright 2016-2025 Blaise Frederick
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+ #
19
+ import numpy as np
20
+ from scipy import ndimage
21
+
22
+ import rapidtide.io as tide_io
23
+ import rapidtide.patchmatch as tide_patch
24
+ import rapidtide.peakeval as tide_peakeval
25
+ import rapidtide.resample as tide_resample
26
+ import rapidtide.simfuncfit as tide_simfuncfit
27
+ import rapidtide.util as tide_util
28
+
29
+
30
+ def fitSimFunc(
31
+ fmri_data_valid,
32
+ validsimcalcstart,
33
+ validsimcalcend,
34
+ osvalidsimcalcstart,
35
+ osvalidsimcalcend,
36
+ initial_fmri_x,
37
+ os_fmri_x,
38
+ theMutualInformationator,
39
+ cleaned_referencetc,
40
+ corrout,
41
+ outputname,
42
+ validvoxels,
43
+ nativespaceshape,
44
+ bidsbasedict,
45
+ numspatiallocs,
46
+ gaussout,
47
+ theinitialdelay,
48
+ windowout,
49
+ R2,
50
+ thesizes,
51
+ internalspaceshape,
52
+ numvalidspatiallocs,
53
+ theinputdata,
54
+ theheader,
55
+ theFitter,
56
+ fitmask,
57
+ lagtimes,
58
+ lagstrengths,
59
+ lagsigma,
60
+ failreason,
61
+ outmaparray,
62
+ trimmedcorrscale,
63
+ similaritytype,
64
+ thepass,
65
+ optiondict,
66
+ LGR,
67
+ TimingLGR,
68
+ simplefit=False,
69
+ upsampfac=8,
70
+ rt_floatset=np.float64,
71
+ rt_floattype="float64",
72
+ ):
73
+ # Do a peak prefit if doing hybrid
74
+ if optiondict["similaritymetric"] == "hybrid":
75
+ LGR.info(f"\n\nPeak prefit calculation, pass {thepass}")
76
+ TimingLGR.info(f"Peak prefit calculation start, pass {thepass}")
77
+
78
+ tide_util.disablemkl(optiondict["nprocs_peakeval"], debug=optiondict["threaddebug"])
79
+ voxelsprocessed_pe, thepeakdict = tide_peakeval.peakevalpass(
80
+ fmri_data_valid[:, validsimcalcstart : validsimcalcend + 1],
81
+ cleaned_referencetc,
82
+ initial_fmri_x[validsimcalcstart : validsimcalcend + 1],
83
+ os_fmri_x[osvalidsimcalcstart : osvalidsimcalcend + 1],
84
+ theMutualInformationator,
85
+ trimmedcorrscale,
86
+ corrout,
87
+ nprocs=optiondict["nprocs_peakeval"],
88
+ alwaysmultiproc=optiondict["alwaysmultiproc"],
89
+ bipolar=optiondict["bipolar"],
90
+ oversampfactor=optiondict["oversampfactor"],
91
+ interptype=optiondict["interptype"],
92
+ showprogressbar=optiondict["showprogressbar"],
93
+ chunksize=optiondict["mp_chunksize"],
94
+ rt_floatset=rt_floatset,
95
+ rt_floattype=rt_floattype,
96
+ )
97
+ tide_util.enablemkl(optiondict["mklthreads"], debug=optiondict["threaddebug"])
98
+
99
+ TimingLGR.info(
100
+ f"Peak prefit end, pass {thepass}",
101
+ {
102
+ "message2": voxelsprocessed_pe,
103
+ "message3": "voxels",
104
+ },
105
+ )
106
+ mipeaks = lagtimes * 0.0
107
+ for i in range(numvalidspatiallocs):
108
+ if len(thepeakdict[str(i)]) > 0:
109
+ mipeaks[i] = thepeakdict[str(i)][0][0]
110
+ else:
111
+ thepeakdict = None
112
+
113
+ if simplefit:
114
+ basedelay = trimmedcorrscale[0]
115
+ delaystep = (trimmedcorrscale[1] - trimmedcorrscale[0]) / upsampfac
116
+ for thevox in range(numvalidspatiallocs):
117
+ fitmask[thevox] = 1
118
+ upsampcorrout = tide_resample.upsample(corrout[thevox,:],1, upsampfac, intfac=True, dofilt=False)
119
+ if optiondict["bipolar"]:
120
+ thismax = np.argmax(np.fabs(upsampcorrout))
121
+ else:
122
+ thismax = np.argmax(upsampcorrout)
123
+ lagtimes[thevox] = basedelay + thismax * delaystep
124
+ lagstrengths[thevox] = upsampcorrout[thismax]
125
+ lagsigma[thevox] = 1.0
126
+ internaldespeckleincludemask = None
127
+ else:
128
+ # Similarity function fitting and time lag estimation
129
+ # write out the current version of the run options
130
+ optiondict["currentstage"] = f"presimfuncfit_pass{thepass}"
131
+ tide_io.writedicttojson(optiondict, f"{outputname}_desc-runoptions_info.json")
132
+ LGR.info(f"\n\nTime lag estimation pass {thepass}")
133
+ TimingLGR.info(f"Time lag estimation start, pass {thepass}")
134
+
135
+ theFitter.setfunctype(optiondict["similaritymetric"])
136
+ theFitter.setcorrtimeaxis(trimmedcorrscale)
137
+
138
+ # use initial lags if this is a hybrid fit
139
+ if optiondict["similaritymetric"] == "hybrid" and thepeakdict is not None:
140
+ initlags = mipeaks
141
+ else:
142
+ initlags = None
143
+
144
+ tide_util.disablemkl(optiondict["nprocs_fitcorr"], debug=optiondict["threaddebug"])
145
+ voxelsprocessed_fc = tide_simfuncfit.fitcorr(
146
+ trimmedcorrscale,
147
+ theFitter,
148
+ corrout,
149
+ fitmask,
150
+ failreason,
151
+ lagtimes,
152
+ lagstrengths,
153
+ lagsigma,
154
+ gaussout,
155
+ windowout,
156
+ R2,
157
+ despeckling=False,
158
+ peakdict=thepeakdict,
159
+ nprocs=optiondict["nprocs_fitcorr"],
160
+ alwaysmultiproc=optiondict["alwaysmultiproc"],
161
+ fixdelay=optiondict["fixdelay"],
162
+ initialdelayvalue=theinitialdelay,
163
+ showprogressbar=optiondict["showprogressbar"],
164
+ chunksize=optiondict["mp_chunksize"],
165
+ despeckle_thresh=optiondict["despeckle_thresh"],
166
+ initiallags=initlags,
167
+ rt_floatset=rt_floatset,
168
+ rt_floattype=rt_floattype,
169
+ )
170
+ tide_util.enablemkl(optiondict["mklthreads"], debug=optiondict["threaddebug"])
171
+
172
+ TimingLGR.info(
173
+ f"Time lag estimation end, pass {thepass}",
174
+ {
175
+ "message2": voxelsprocessed_fc,
176
+ "message3": "voxels",
177
+ },
178
+ )
179
+
180
+ # Correlation time despeckle
181
+ if optiondict["despeckle_passes"] > 0:
182
+ LGR.info(f"\n\n{similaritytype} despeckling pass {thepass}")
183
+ LGR.info(f"\tUsing despeckle_thresh = {optiondict['despeckle_thresh']:.3f}")
184
+ TimingLGR.info(f"{similaritytype} despeckle start, pass {thepass}")
185
+
186
+ # find lags that are very different from their neighbors, and refit starting at the median lag for the point
187
+ voxelsprocessed_fc_ds = 0
188
+ despecklingdone = False
189
+ lastnumdespeckled = 1000000
190
+ for despecklepass in range(optiondict["despeckle_passes"]):
191
+ LGR.info(f"\n\n{similaritytype} despeckling subpass {despecklepass + 1}")
192
+ outmaparray *= 0.0
193
+ outmaparray[validvoxels] = eval("lagtimes")[:]
194
+
195
+ # find voxels to despeckle
196
+ medianlags = ndimage.median_filter(outmaparray.reshape(nativespaceshape), 3).reshape(
197
+ numspatiallocs
198
+ )
199
+ # voxels that we're happy with have initlags set to -1000000.0
200
+ initlags = np.where(
201
+ np.abs(outmaparray - medianlags) > optiondict["despeckle_thresh"],
202
+ medianlags,
203
+ -1000000.0,
204
+ )[validvoxels]
205
+
206
+ if len(initlags) > 0:
207
+ numdespeckled = len(np.where(initlags != -1000000.0)[0])
208
+ if lastnumdespeckled > numdespeckled > 0:
209
+ lastnumdespeckled = numdespeckled
210
+ tide_util.disablemkl(
211
+ optiondict["nprocs_fitcorr"], debug=optiondict["threaddebug"]
212
+ )
213
+ voxelsprocessed_thispass = tide_simfuncfit.fitcorr(
214
+ trimmedcorrscale,
215
+ theFitter,
216
+ corrout,
217
+ fitmask,
218
+ failreason,
219
+ lagtimes,
220
+ lagstrengths,
221
+ lagsigma,
222
+ gaussout,
223
+ windowout,
224
+ R2,
225
+ despeckling=True,
226
+ peakdict=thepeakdict,
227
+ nprocs=optiondict["nprocs_fitcorr"],
228
+ alwaysmultiproc=optiondict["alwaysmultiproc"],
229
+ fixdelay=optiondict["fixdelay"],
230
+ initialdelayvalue=theinitialdelay,
231
+ showprogressbar=optiondict["showprogressbar"],
232
+ chunksize=optiondict["mp_chunksize"],
233
+ despeckle_thresh=optiondict["despeckle_thresh"],
234
+ initiallags=initlags,
235
+ rt_floatset=rt_floatset,
236
+ rt_floattype=rt_floattype,
237
+ )
238
+ tide_util.enablemkl(optiondict["mklthreads"], debug=optiondict["threaddebug"])
239
+
240
+ voxelsprocessed_fc_ds += voxelsprocessed_thispass
241
+ optiondict[
242
+ "despecklemasksize_pass" + str(thepass) + "_d" + str(despecklepass + 1)
243
+ ] = voxelsprocessed_thispass
244
+ optiondict[
245
+ "despecklemaskpct_pass" + str(thepass) + "_d" + str(despecklepass + 1)
246
+ ] = (100.0 * voxelsprocessed_thispass / optiondict["corrmasksize"])
247
+ else:
248
+ despecklingdone = True
249
+ else:
250
+ despecklingdone = True
251
+ if despecklingdone:
252
+ LGR.info("Nothing left to do! Terminating despeckling")
253
+ break
254
+
255
+ internaldespeckleincludemask = np.where(
256
+ np.abs(outmaparray - medianlags) > optiondict["despeckle_thresh"],
257
+ medianlags,
258
+ 0.0,
259
+ )
260
+ if optiondict["savedespecklemasks"] and (optiondict["despeckle_passes"] > 0):
261
+ despecklesavemask = np.where(internaldespeckleincludemask[validvoxels] == 0.0, 0, 1)
262
+ if thepass == optiondict["passes"]:
263
+ if theinputdata.filetype != "text":
264
+ if theinputdata.filetype == "cifti":
265
+ timeindex = theheader["dim"][0] - 1
266
+ spaceindex = theheader["dim"][0]
267
+ theheader["dim"][timeindex] = 1
268
+ theheader["dim"][spaceindex] = numspatiallocs
269
+ else:
270
+ theheader["dim"][0] = 3
271
+ theheader["dim"][4] = 1
272
+ theheader["pixdim"][4] = 1.0
273
+ masklist = [
274
+ (
275
+ despecklesavemask,
276
+ "despeckle",
277
+ "mask",
278
+ None,
279
+ "Voxels that underwent despeckling in the final pass",
280
+ )
281
+ ]
282
+ tide_io.savemaplist(
283
+ outputname,
284
+ masklist,
285
+ validvoxels,
286
+ nativespaceshape,
287
+ theheader,
288
+ bidsbasedict,
289
+ filetype=theinputdata.filetype,
290
+ rt_floattype=rt_floattype,
291
+ cifti_hdr=theinputdata.cifti_hdr,
292
+ )
293
+ LGR.info(
294
+ f"\n\n{voxelsprocessed_fc_ds} voxels despeckled in "
295
+ f"{optiondict['despeckle_passes']} passes"
296
+ )
297
+ TimingLGR.info(
298
+ f"{similaritytype} despeckle end, pass {thepass}",
299
+ {
300
+ "message2": voxelsprocessed_fc_ds,
301
+ "message3": "voxels",
302
+ },
303
+ )
304
+ else:
305
+ internaldespeckleincludemask = None
306
+
307
+ # Patch shifting
308
+ if optiondict["patchshift"]:
309
+ outmaparray *= 0.0
310
+ outmaparray[validvoxels] = eval("lagtimes")[:]
311
+ # new method
312
+ masklist = [
313
+ (
314
+ outmaparray[validvoxels],
315
+ f"lagtimes_prepatch_pass{thepass}",
316
+ "map",
317
+ None,
318
+ f"Input lagtimes map prior to patch map generation pass {thepass}",
319
+ ),
320
+ ]
321
+ tide_io.savemaplist(
322
+ outputname,
323
+ masklist,
324
+ validvoxels,
325
+ nativespaceshape,
326
+ theheader,
327
+ bidsbasedict,
328
+ filetype=theinputdata.filetype,
329
+ rt_floattype=rt_floattype,
330
+ cifti_hdr=theinputdata.cifti_hdr,
331
+ )
332
+
333
+ # create list of anomalous 3D regions that don't match surroundings
334
+ if theinputdata.nim_affine is not None:
335
+ # make an atlas of anomalous patches - each patch shares the same integer value
336
+ step1 = tide_patch.calc_DoG(
337
+ outmaparray.reshape(nativespaceshape).copy(),
338
+ theinputdata.nim_affine,
339
+ thesizes,
340
+ fwhm=optiondict["patchfwhm"],
341
+ ratioopt=False,
342
+ debug=True,
343
+ )
344
+ masklist = [
345
+ (
346
+ step1.reshape(internalspaceshape)[validvoxels],
347
+ f"DoG_pass{thepass}",
348
+ "map",
349
+ None,
350
+ f"DoG map for pass {thepass}",
351
+ ),
352
+ ]
353
+ tide_io.savemaplist(
354
+ outputname,
355
+ masklist,
356
+ validvoxels,
357
+ nativespaceshape,
358
+ theheader,
359
+ bidsbasedict,
360
+ filetype=theinputdata.filetype,
361
+ rt_floattype=rt_floattype,
362
+ cifti_hdr=theinputdata.cifti_hdr,
363
+ )
364
+ step2 = tide_patch.invertedflood3D(
365
+ step1,
366
+ 1,
367
+ )
368
+ masklist = [
369
+ (
370
+ step2.reshape(internalspaceshape)[validvoxels],
371
+ f"invertflood_pass{thepass}",
372
+ "map",
373
+ None,
374
+ f"Inverted flood map for pass {thepass}",
375
+ ),
376
+ ]
377
+ tide_io.savemaplist(
378
+ outputname,
379
+ masklist,
380
+ validvoxels,
381
+ nativespaceshape,
382
+ theheader,
383
+ bidsbasedict,
384
+ filetype=theinputdata.filetype,
385
+ rt_floattype=rt_floattype,
386
+ cifti_hdr=theinputdata.cifti_hdr,
387
+ )
388
+
389
+ patchmap = tide_patch.separateclusters(
390
+ step2,
391
+ sizethresh=optiondict["patchminsize"],
392
+ debug=True,
393
+ )
394
+ # patchmap = tide_patch.getclusters(
395
+ # outmaparray.reshape(nativespaceshape),
396
+ # theinputdata.nim_affine,
397
+ # thesizes,
398
+ # fwhm=optiondict["patchfwhm"],
399
+ # ratioopt=True,
400
+ # sizethresh=optiondict["patchminsize"],
401
+ # debug=True,
402
+ # )
403
+ masklist = [
404
+ (
405
+ patchmap[validvoxels],
406
+ f"patch_pass{thepass}",
407
+ "map",
408
+ None,
409
+ f"Patch map for despeckling pass {thepass}",
410
+ ),
411
+ ]
412
+ tide_io.savemaplist(
413
+ outputname,
414
+ masklist,
415
+ validvoxels,
416
+ nativespaceshape,
417
+ theheader,
418
+ bidsbasedict,
419
+ filetype=theinputdata.filetype,
420
+ rt_floattype=rt_floattype,
421
+ cifti_hdr=theinputdata.cifti_hdr,
422
+ )
423
+
424
+ # now shift the patches to align with the majority of the image
425
+ tide_patch.interppatch(lagtimes, patchmap[validvoxels])
426
+
427
+ return internaldespeckleincludemask
@@ -1421,7 +1421,7 @@ def happy_main(argparsingfunc):
1421
1421
  # make a lowpass filter for the projected data. Limit frequency to 3 cycles per 2pi (1/6th Fs)
1422
1422
  phaseFs = 1.0 / phasestep
1423
1423
  phaseFc = phaseFs / 6.0
1424
- appsmoothingfilter = tide_filt.NoncausalFilter("arb", cyclic=True, padtime=0.0)
1424
+ appsmoothingfilter = tide_filt.NoncausalFilter("arb", padtime=0.0)
1425
1425
  appsmoothingfilter.setfreqs(0.0, 0.0, phaseFc, phaseFc)
1426
1426
 
1427
1427
  # setup for aliased correlation if we're going to do it
@@ -1763,7 +1763,7 @@ def happy_main(argparsingfunc):
1763
1763
  fitNorm,
1764
1764
  datatoremove[validlocs, :],
1765
1765
  filtereddata[validlocs, :],
1766
- mp_chunksize=10,
1766
+ chunksize=10,
1767
1767
  procbyvoxel=False,
1768
1768
  nprocs=args.nprocs,
1769
1769
  )
@@ -444,7 +444,7 @@ def addfilteropts(
444
444
  dest="ncfiltpadtype",
445
445
  action="store",
446
446
  type=str,
447
- choices=["reflect", "zero", "constant", "constant+"],
447
+ choices=["reflect", "zero", "cyclic", "constant", "constant+"],
448
448
  help=(
449
449
  f"The type of padding at each end of a "
450
450
  "timecourse to be filtered "