rapidtide 3.0.7.1__py3-none-any.whl → 3.0.9__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 (57) hide show
  1. rapidtide/RapidtideDataset.py +1 -1
  2. rapidtide/_version.py +3 -3
  3. rapidtide/calcnullsimfunc.py +1 -3
  4. rapidtide/data/examples/src/test_findmaxlag.py +1 -1
  5. rapidtide/data/examples/src/testfmri +19 -7
  6. rapidtide/data/examples/src/testnewrefine +0 -23
  7. rapidtide/fMRIData_class.py +29 -52
  8. rapidtide/fit.py +4 -4
  9. rapidtide/happy_supportfuncs.py +1 -1
  10. rapidtide/helper_classes.py +0 -1099
  11. rapidtide/linfitfiltpass.py +82 -4
  12. rapidtide/makelaggedtcs.py +10 -0
  13. rapidtide/refinedelay.py +11 -20
  14. rapidtide/refineregressor.py +1 -1
  15. rapidtide/resample.py +8 -8
  16. rapidtide/simFuncClasses.py +1132 -0
  17. rapidtide/simfuncfit.py +30 -30
  18. rapidtide/stats.py +5 -2
  19. rapidtide/tests/.coveragerc +6 -0
  20. rapidtide/tests/cleanposttest +1 -1
  21. rapidtide/tests/runlocaltest +2 -2
  22. rapidtide/tests/test_cleanregressor.py +3 -3
  23. rapidtide/tests/test_congrid.py +1 -1
  24. rapidtide/tests/test_corrpass.py +3 -3
  25. rapidtide/tests/test_delayestimation.py +9 -8
  26. rapidtide/tests/test_findmaxlag.py +2 -2
  27. rapidtide/tests/test_fullrunrapidtide_v3.py +2 -1
  28. rapidtide/tests/test_fullrunrapidtide_v8.py +66 -0
  29. rapidtide/tests/test_getparsers.py +14 -6
  30. rapidtide/tests/test_io.py +2 -6
  31. rapidtide/tests/test_nullcorr.py +3 -3
  32. rapidtide/tests/test_refinedelay.py +20 -5
  33. rapidtide/tidepoolTemplate_alt.py +1 -1
  34. rapidtide/util.py +7 -0
  35. rapidtide/voxelData.py +3 -6
  36. rapidtide/workflows/calcSimFuncMap.py +271 -0
  37. rapidtide/workflows/cleanregressor.py +2 -2
  38. rapidtide/workflows/delayvar.py +45 -59
  39. rapidtide/workflows/fitSimFuncMap.py +427 -0
  40. rapidtide/workflows/happy.py +1 -1
  41. rapidtide/workflows/rapidtide.py +499 -877
  42. rapidtide/workflows/rapidtide_parser.py +26 -38
  43. rapidtide/workflows/refineDelayMap.py +138 -0
  44. rapidtide/{RegressorRefiner.py → workflows/refineRegressor.py} +200 -28
  45. rapidtide/workflows/regressfrommaps.py +38 -30
  46. rapidtide/workflows/retrolagtcs.py +5 -6
  47. rapidtide/workflows/retroregress.py +73 -191
  48. rapidtide/workflows/showarbcorr.py +2 -2
  49. rapidtide/workflows/showxcorrx.py +5 -5
  50. rapidtide/workflows/tidepool.py +5 -5
  51. {rapidtide-3.0.7.1.dist-info → rapidtide-3.0.9.dist-info}/METADATA +2 -2
  52. {rapidtide-3.0.7.1.dist-info → rapidtide-3.0.9.dist-info}/RECORD +56 -52
  53. rapidtide/workflows/delayestimation.py +0 -483
  54. {rapidtide-3.0.7.1.dist-info → rapidtide-3.0.9.dist-info}/WHEEL +0 -0
  55. {rapidtide-3.0.7.1.dist-info → rapidtide-3.0.9.dist-info}/entry_points.txt +0 -0
  56. {rapidtide-3.0.7.1.dist-info → rapidtide-3.0.9.dist-info}/licenses/LICENSE +0 -0
  57. {rapidtide-3.0.7.1.dist-info → rapidtide-3.0.9.dist-info}/top_level.txt +0 -0
@@ -25,7 +25,6 @@ import warnings
25
25
  from pathlib import Path
26
26
 
27
27
  import numpy as np
28
- from scipy import ndimage
29
28
  from scipy.stats import rankdata
30
29
 
31
30
  import rapidtide.calccoherence as tide_calccoherence
@@ -40,17 +39,17 @@ import rapidtide.linfitfiltpass as tide_linfitfiltpass
40
39
  import rapidtide.maskutil as tide_mask
41
40
  import rapidtide.miscmath as tide_math
42
41
  import rapidtide.multiproc as tide_multiproc
43
- import rapidtide.patchmatch as tide_patch
44
- import rapidtide.peakeval as tide_peakeval
45
- import rapidtide.refinedelay as tide_refinedelay
46
- import rapidtide.RegressorRefiner as tide_regrefiner
47
42
  import rapidtide.resample as tide_resample
48
- import rapidtide.simfuncfit as tide_simfuncfit
43
+ import rapidtide.simFuncClasses as tide_simFuncClasses
49
44
  import rapidtide.stats as tide_stats
50
45
  import rapidtide.util as tide_util
51
46
  import rapidtide.voxelData as tide_voxelData
52
47
  import rapidtide.wiener as tide_wiener
48
+ import rapidtide.workflows.calcSimFuncMap as tide_calcSimFuncMap
53
49
  import rapidtide.workflows.cleanregressor as tide_cleanregressor
50
+ import rapidtide.workflows.fitSimFuncMap as tide_fitSimFuncMap
51
+ import rapidtide.workflows.refineDelayMap as tide_refineDelayMap
52
+ import rapidtide.workflows.refineRegressor as tide_refineRegressor
54
53
  import rapidtide.workflows.regressfrommaps as tide_regressfrommaps
55
54
 
56
55
  from .utils import setup_logger
@@ -117,8 +116,8 @@ def echocancel(thetimecourse, echooffset, thetimestep, outputname, padtimepoints
117
116
 
118
117
 
119
118
  def rapidtide_main(argparsingfunc):
120
- threaddebug = False
121
119
  optiondict, theprefilter = argparsingfunc
120
+ optiondict["threaddebug"] = False
122
121
 
123
122
  optiondict["nodename"] = platform.node()
124
123
 
@@ -277,7 +276,7 @@ def rapidtide_main(argparsingfunc):
277
276
  mklmaxthreads = mkl.get_max_threads()
278
277
  if not (1 <= optiondict["mklthreads"] <= mklmaxthreads):
279
278
  optiondict["mklthreads"] = mklmaxthreads
280
- tide_util.enablemkl(optiondict["mklthreads"], debug=threaddebug)
279
+ tide_util.enablemkl(optiondict["mklthreads"], debug=optiondict["threaddebug"])
281
280
  LGR.info(f"using {optiondict['mklthreads']} MKL threads")
282
281
 
283
282
  # Generate MemoryLGR output file with column names
@@ -298,15 +297,6 @@ def rapidtide_main(argparsingfunc):
298
297
  nativespaceshape = theinputdata.nativespaceshape
299
298
  fmritr = theinputdata.timestep
300
299
  optiondict["filetype"] = theinputdata.filetype
301
- if theinputdata.filetype == "cifti":
302
- fileiscifti = True
303
- optiondict["textio"] = False
304
- elif theinputdata.filetype == "text":
305
- fileiscifti = False
306
- optiondict["textio"] = True
307
- else:
308
- fileiscifti = False
309
- optiondict["textio"] = False
310
300
 
311
301
  # check to see if we need to adjust the oversample factor
312
302
  if optiondict["oversampfactor"] < 0:
@@ -583,7 +573,7 @@ def rapidtide_main(argparsingfunc):
583
573
  savename = f"{outputname}_desc-processed_mask"
584
574
  tide_io.savetonifti(corrmask.reshape(xsize, ysize, numslices), theheader, savename)
585
575
 
586
- LGR.verbose(f"image threshval = {threshval}")
576
+ LGR.verbose(f"image threshval = {threshval:.2f}")
587
577
  validvoxels = np.where(corrmask > 0)[0]
588
578
  if optiondict["debug"]:
589
579
  print(f"{validvoxels.shape=}")
@@ -700,7 +690,7 @@ def rapidtide_main(argparsingfunc):
700
690
  print(f"{fmritr=}")
701
691
  print(f"{validstart=}")
702
692
  print(f"{validend=}")
703
- tide_util.disablemkl(optiondict["nprocs_confoundregress"], debug=threaddebug)
693
+ tide_util.disablemkl(optiondict["nprocs_confoundregress"], debug=optiondict["threaddebug"])
704
694
  (
705
695
  mergedregressors,
706
696
  mergedregressorlabels,
@@ -717,7 +707,7 @@ def rapidtide_main(argparsingfunc):
717
707
  orthogonalize=optiondict["orthogonalize"],
718
708
  showprogressbar=optiondict["showprogressbar"],
719
709
  )
720
- tide_util.enablemkl(optiondict["mklthreads"], debug=threaddebug)
710
+ tide_util.enablemkl(optiondict["mklthreads"], debug=optiondict["threaddebug"])
721
711
  if confoundr2 is None:
722
712
  print("There are no nonzero confound regressors - exiting")
723
713
  sys.exit()
@@ -978,7 +968,7 @@ def rapidtide_main(argparsingfunc):
978
968
  )
979
969
  LGR.verbose("Input vector")
980
970
  LGR.verbose(f"length: {len(inputvec)}")
981
- LGR.verbose(f"input freq: {inputfreq}")
971
+ LGR.verbose(f"input freq: {inputfreq:.2f}")
982
972
  LGR.verbose(f"input start time: {inputstarttime:.3f}")
983
973
 
984
974
  if not optiondict["useinitregressorref"]:
@@ -1255,7 +1245,7 @@ def rapidtide_main(argparsingfunc):
1255
1245
  # Set up for the delay finding/refinement passes
1256
1246
  ####################################################
1257
1247
  # initialize the Correlator
1258
- theCorrelator = tide_classes.Correlator(
1248
+ theCorrelator = tide_simFuncClasses.Correlator(
1259
1249
  Fs=oversampfreq,
1260
1250
  ncprefilter=theprefilter,
1261
1251
  negativegradient=optiondict["negativegradient"],
@@ -1288,7 +1278,7 @@ def rapidtide_main(argparsingfunc):
1288
1278
  dummy, trimmedcorrscale, dummy = theCorrelator.getfunction()
1289
1279
 
1290
1280
  # initialize the MutualInformationator
1291
- theMutualInformationator = tide_classes.MutualInformationator(
1281
+ theMutualInformationator = tide_simFuncClasses.MutualInformationator(
1292
1282
  Fs=oversampfreq,
1293
1283
  smoothingtime=optiondict["smoothingtime"],
1294
1284
  ncprefilter=theprefilter,
@@ -1356,6 +1346,29 @@ def rapidtide_main(argparsingfunc):
1356
1346
  append=False,
1357
1347
  )
1358
1348
 
1349
+ # prepare for fast resampling
1350
+ optiondict["fastresamplerpadtime"] = (
1351
+ max((-optiondict["lagmin"], optiondict["lagmax"]))
1352
+ + 30.0
1353
+ + np.abs(optiondict["offsettime"])
1354
+ )
1355
+ numpadtrs = int(optiondict["fastresamplerpadtime"] // fmritr)
1356
+ optiondict["fastresamplerpadtime"] = fmritr * numpadtrs
1357
+ LGR.info(f"setting up fast resampling with padtime = {optiondict['fastresamplerpadtime']}")
1358
+
1359
+ genlagtc = tide_resample.FastResampler(
1360
+ reference_x, reference_y, padtime=optiondict["fastresamplerpadtime"]
1361
+ )
1362
+ genlagtc.save(f"{outputname}_desc-lagtcgenerator_timeseries")
1363
+ if optiondict["debug"]:
1364
+ genlagtc.info()
1365
+ totalpadlen = validtimepoints + 2 * numpadtrs
1366
+ paddedinitial_fmri_x = (
1367
+ np.linspace(0.0, totalpadlen * fmritr, num=totalpadlen, endpoint=False)
1368
+ + skiptime
1369
+ - fmritr * numpadtrs
1370
+ )
1371
+
1359
1372
  # allocate all the data arrays
1360
1373
  tide_util.logmem("before main array allocation")
1361
1374
  internalspaceshape = numspatiallocs
@@ -1370,7 +1383,30 @@ def rapidtide_main(argparsingfunc):
1370
1383
  outmaparray = np.zeros(internalspaceshape, dtype=rt_floattype)
1371
1384
  tide_util.logmem("after main array allocation")
1372
1385
 
1373
- corroutlen = np.shape(trimmedcorrscale)[0]
1386
+ if optiondict["similaritymetric"] == "riptide":
1387
+ riptideregressorset, riptidedelays = tide_calcSimFuncMap.makeRIPTiDeRegressors(
1388
+ initial_fmri_x,
1389
+ optiondict["lagmin"],
1390
+ optiondict["lagmax"],
1391
+ genlagtc,
1392
+ LGR,
1393
+ targetstep=optiondict["riptidestep"],
1394
+ edgepad=0,
1395
+ showprogressbar=optiondict["showprogressbar"],
1396
+ chunksize=optiondict["mp_chunksize"],
1397
+ nprocs=optiondict["nprocs"],
1398
+ alwaysmultiproc=optiondict["alwaysmultiproc"],
1399
+ rt_floatset=rt_floatset,
1400
+ rt_floattype=rt_floattype,
1401
+ debug=optiondict["debug"],
1402
+ )
1403
+ numriptideregressors = riptideregressorset.shape[0]
1404
+ corroutlen = numriptideregressors
1405
+ else:
1406
+ riptideregressorset = None
1407
+ riptidedelays = None
1408
+ corroutlen = np.shape(trimmedcorrscale)[0]
1409
+
1374
1410
  if theinputdata.filetype == "text":
1375
1411
  nativecorrshape = (xsize, corroutlen)
1376
1412
  else:
@@ -1383,26 +1419,36 @@ def rapidtide_main(argparsingfunc):
1383
1419
  LGR.debug(
1384
1420
  f"allocating memory for correlation arrays {internalcorrshape} {internalvalidcorrshape}"
1385
1421
  )
1422
+
1423
+ corrout, corrout_shm = tide_util.allocarray(
1424
+ internalvalidcorrshape,
1425
+ rt_floatset,
1426
+ shared=optiondict["sharedmem"],
1427
+ name=f"corrout_{optiondict['pid']}",
1428
+ )
1429
+ gaussout, gaussout_shm = tide_util.allocarray(
1430
+ internalvalidcorrshape,
1431
+ rt_floatset,
1432
+ shared=optiondict["sharedmem"],
1433
+ name=f"gaussout_{optiondict['pid']}",
1434
+ )
1435
+ windowout, windowout_shm = tide_util.allocarray(
1436
+ internalvalidcorrshape,
1437
+ rt_floatset,
1438
+ shared=optiondict["sharedmem"],
1439
+ name=f"windowout_{optiondict['pid']}",
1440
+ )
1441
+ outcorrarray, outcorrarray_shm = tide_util.allocarray(
1442
+ internalcorrshape,
1443
+ rt_floatset,
1444
+ shared=optiondict["sharedmem"],
1445
+ name=f"outcorrarray_{optiondict['pid']}",
1446
+ )
1386
1447
  if optiondict["sharedmem"]:
1387
- corrout, corrout_shm = tide_util.allocshared(
1388
- internalvalidcorrshape, rt_floatset, name=f"corrout_{optiondict['pid']}"
1389
- )
1390
- gaussout, gaussout_shm = tide_util.allocshared(
1391
- internalvalidcorrshape, rt_floatset, name=f"gaussout_{optiondict['pid']}"
1392
- )
1393
- windowout, windowout_shm = tide_util.allocshared(
1394
- internalvalidcorrshape, rt_floatset, name=f"windowout_{optiondict['pid']}"
1395
- )
1396
- outcorrarray, outcorrarray_shm = tide_util.allocshared(
1397
- internalcorrshape, rt_floatset, name=f"outcorrarray_{optiondict['pid']}"
1398
- )
1399
1448
  ramlocation = "in shared memory"
1400
1449
  else:
1401
- corrout = np.zeros(internalvalidcorrshape, dtype=rt_floattype)
1402
- gaussout = np.zeros(internalvalidcorrshape, dtype=rt_floattype)
1403
- windowout = np.zeros(internalvalidcorrshape, dtype=rt_floattype)
1404
- outcorrarray = np.zeros(internalcorrshape, dtype=rt_floattype)
1405
1450
  ramlocation = "locally"
1451
+
1406
1452
  optiondict["totalcorrelationbytes"] = (
1407
1453
  corrout.nbytes + gaussout.nbytes + windowout.nbytes + outcorrarray.nbytes
1408
1454
  )
@@ -1429,29 +1475,6 @@ def rapidtide_main(argparsingfunc):
1429
1475
  else:
1430
1476
  theinitialdelay = None
1431
1477
 
1432
- # prepare for fast resampling
1433
- optiondict["fastresamplerpadtime"] = (
1434
- max((-optiondict["lagmin"], optiondict["lagmax"]))
1435
- + 30.0
1436
- + np.abs(optiondict["offsettime"])
1437
- )
1438
- numpadtrs = int(optiondict["fastresamplerpadtime"] // fmritr)
1439
- optiondict["fastresamplerpadtime"] = fmritr * numpadtrs
1440
- LGR.info(f"setting up fast resampling with padtime = {optiondict['fastresamplerpadtime']}")
1441
-
1442
- genlagtc = tide_resample.FastResampler(
1443
- reference_x, reference_y, padtime=optiondict["fastresamplerpadtime"]
1444
- )
1445
- genlagtc.save(f"{outputname}_desc-lagtcgenerator_timeseries")
1446
- if optiondict["debug"]:
1447
- genlagtc.info()
1448
- totalpadlen = validtimepoints + 2 * numpadtrs
1449
- paddedinitial_fmri_x = (
1450
- np.linspace(0.0, totalpadlen * fmritr, num=totalpadlen, endpoint=False)
1451
- + skiptime
1452
- - fmritr * numpadtrs
1453
- )
1454
-
1455
1478
  if theinputdata.filetype == "text":
1456
1479
  nativefmrishape = (xsize, np.shape(initial_fmri_x)[0])
1457
1480
  elif theinputdata.filetype == "cifti":
@@ -1466,6 +1489,76 @@ def rapidtide_main(argparsingfunc):
1466
1489
  2 * numpadtrs + np.shape(initial_fmri_x)[0],
1467
1490
  )
1468
1491
 
1492
+ # now do the arrays for delay refinement
1493
+ if optiondict["dolinfitfilt"] or optiondict["docvrmap"] or optiondict["refinedelay"] or (optiondict["similaritymetric"] == "riptide"):
1494
+ if optiondict["refinedelay"]:
1495
+ derivaxissize = np.max([2, optiondict["regressderivs"] + 1])
1496
+ else:
1497
+ derivaxissize = optiondict["regressderivs"] + 1
1498
+ internalvalidspaceshapederivs = (
1499
+ internalvalidspaceshape,
1500
+ derivaxissize,
1501
+ )
1502
+ sLFOfitmean, sLFOfitmean_shm = tide_util.allocarray(
1503
+ internalvalidspaceshape,
1504
+ rt_outfloattype,
1505
+ shared=optiondict["sharedmem"],
1506
+ name=f"sLFOfitmean_{optiondict['pid']}",
1507
+ )
1508
+ rvalue, rvalue_shm = tide_util.allocarray(
1509
+ internalvalidspaceshape,
1510
+ rt_outfloattype,
1511
+ shared=optiondict["sharedmem"],
1512
+ name=f"rvalue_{optiondict['pid']}",
1513
+ )
1514
+ r2value, r2value_shm = tide_util.allocarray(
1515
+ internalvalidspaceshape,
1516
+ rt_outfloattype,
1517
+ shared=optiondict["sharedmem"],
1518
+ name=f"r2value_{optiondict['pid']}",
1519
+ )
1520
+ fitNorm, fitNorm_shm = tide_util.allocarray(
1521
+ internalvalidspaceshapederivs,
1522
+ rt_outfloattype,
1523
+ shared=optiondict["sharedmem"],
1524
+ name=f"fitNorm_{optiondict['pid']}",
1525
+ )
1526
+ fitcoeff, fitcoeff_shm = tide_util.allocarray(
1527
+ internalvalidspaceshapederivs,
1528
+ rt_outfloattype,
1529
+ shared=optiondict["sharedmem"],
1530
+ name=f"fitcoeff_{optiondict['pid']}",
1531
+ )
1532
+ lagtc, lagtc_shm = tide_util.allocarray(
1533
+ internalvalidfmrishape,
1534
+ rt_floattype,
1535
+ shared=optiondict["sharedmem"],
1536
+ name=f"lagtc_{optiondict['pid']}",
1537
+ )
1538
+ if optiondict["sharedmem"]:
1539
+ ramlocation = "in shared memory"
1540
+ else:
1541
+ ramlocation = "locally"
1542
+
1543
+ optiondict["totalRefineDelaybytes"] = (
1544
+ sLFOfitmean.nbytes
1545
+ + rvalue.nbytes
1546
+ + r2value.nbytes
1547
+ + fitNorm.nbytes
1548
+ + fitcoeff.nbytes
1549
+ + lagtc.nbytes
1550
+ )
1551
+ thesize, theunit = tide_util.format_bytes(optiondict["totalRefineDelaybytes"])
1552
+ print(f"allocated {thesize:.3f} {theunit} {ramlocation} for delay refinement")
1553
+ tide_util.logmem("after derivative delay/sLFO filter array allocation")
1554
+ else:
1555
+ sLFOfitmean = None
1556
+ rvalue = None
1557
+ r2value = None
1558
+ fitNorm = None
1559
+ fitcoeff = None
1560
+ lagtc = None
1561
+
1469
1562
  # prepare for regressor refinement, if we're doing it
1470
1563
  if (
1471
1564
  optiondict["passes"] > 1
@@ -1474,7 +1567,7 @@ def rapidtide_main(argparsingfunc):
1474
1567
  or optiondict["convergencethresh"] is not None
1475
1568
  ):
1476
1569
  # we will be doing regressor refinement, so configure the refiner
1477
- theRegressorRefiner = tide_regrefiner.RegressorRefiner(
1570
+ theRegressorRefiner = tide_refineRegressor.RegressorRefiner(
1478
1571
  internalvalidfmrishape,
1479
1572
  internalvalidpaddedfmrishape,
1480
1573
  optiondict["pid"],
@@ -1523,7 +1616,7 @@ def rapidtide_main(argparsingfunc):
1523
1616
  LGR.verbose(f"edgebufferfrac set to {optiondict['edgebufferfrac']}")
1524
1617
 
1525
1618
  # initialize the correlation fitter
1526
- theFitter = tide_classes.SimilarityFunctionFitter(
1619
+ theFitter = tide_simFuncClasses.SimilarityFunctionFitter(
1527
1620
  lagmod=optiondict["lagmod"],
1528
1621
  lthreshval=optiondict["lthreshval"],
1529
1622
  uthreshval=optiondict["uthreshval"],
@@ -1551,7 +1644,7 @@ def rapidtide_main(argparsingfunc):
1551
1644
  windowfunc=optiondict["windowfunc"],
1552
1645
  )
1553
1646
 
1554
- tide_util.disablemkl(optiondict["nprocs_calcsimilarity"], debug=threaddebug)
1647
+ tide_util.disablemkl(optiondict["nprocs_calcsimilarity"], debug=optiondict["threaddebug"])
1555
1648
  (
1556
1649
  voxelsprocessed_echo,
1557
1650
  theglobalmaxlist,
@@ -1575,7 +1668,7 @@ def rapidtide_main(argparsingfunc):
1575
1668
  rt_floatset=rt_floatset,
1576
1669
  rt_floattype=rt_floattype,
1577
1670
  )
1578
- tide_util.enablemkl(optiondict["mklthreads"], debug=threaddebug)
1671
+ tide_util.enablemkl(optiondict["mklthreads"], debug=optiondict["threaddebug"])
1579
1672
 
1580
1673
  for i in range(len(theglobalmaxlist)):
1581
1674
  theglobalmaxlist[i] = corrscale[theglobalmaxlist[i]] - optiondict["simcalcoffset"]
@@ -1730,7 +1823,7 @@ def rapidtide_main(argparsingfunc):
1730
1823
  theSimFunc = theMutualInformationator
1731
1824
  else:
1732
1825
  theSimFunc = theCorrelator
1733
- tide_util.disablemkl(optiondict["nprocs_getNullDist"], debug=threaddebug)
1826
+ tide_util.disablemkl(optiondict["nprocs_getNullDist"], debug=optiondict["threaddebug"])
1734
1827
  simdistdata = tide_nullsimfunc.getNullDistributionData(
1735
1828
  oversampfreq,
1736
1829
  theSimFunc,
@@ -1745,7 +1838,7 @@ def rapidtide_main(argparsingfunc):
1745
1838
  rt_floatset=np.float64,
1746
1839
  rt_floattype="float64",
1747
1840
  )
1748
- tide_util.enablemkl(optiondict["mklthreads"], debug=threaddebug)
1841
+ tide_util.enablemkl(optiondict["mklthreads"], debug=optiondict["threaddebug"])
1749
1842
 
1750
1843
  tide_io.writebidstsv(
1751
1844
  f"{outputname}_desc-simdistdata_info",
@@ -1785,6 +1878,8 @@ def rapidtide_main(argparsingfunc):
1785
1878
  twotail=optiondict["bipolar"],
1786
1879
  nozero=optiondict["nohistzero"],
1787
1880
  )
1881
+ if sigfit is None:
1882
+ optiondict["ampthreshfromsig"] = False
1788
1883
  if pcts is not None:
1789
1884
  for i in range(len(thepvalnames)):
1790
1885
  optiondict[
@@ -1840,350 +1935,72 @@ def rapidtide_main(argparsingfunc):
1840
1935
  optiondict["currentstage"] = f"precorrelation_pass{thepass}"
1841
1936
  tide_io.writedicttojson(optiondict, f"{outputname}_desc-runoptions_info.json")
1842
1937
 
1843
- # tide_delayestimate.estimateDelay(
1844
- # fmri_data_valid[:, validsimcalcstart : validsimcalcend + 1],
1845
- # initial_fmri_x[validsimcalcstart : validsimcalcend + 1],
1846
- # os_fmri_x[osvalidsimcalcstart : osvalidsimcalcend + 1],
1847
- # theMutualInformationator,
1848
- # thepass,
1849
- # )
1850
- ########################
1851
- # Delay estimation start
1852
- ########################
1853
- # Step 1 - Correlation step
1854
- if optiondict["similaritymetric"] == "mutualinfo":
1855
- similaritytype = "Mutual information"
1856
- elif optiondict["similaritymetric"] == "correlation":
1857
- similaritytype = "Correlation"
1858
- else:
1859
- similaritytype = "MI enhanced correlation"
1860
- LGR.info(f"\n\n{similaritytype} calculation, pass {thepass}")
1861
- TimingLGR.info(f"{similaritytype} calculation start, pass {thepass}")
1862
-
1863
- tide_util.disablemkl(optiondict["nprocs_calcsimilarity"], debug=threaddebug)
1864
- if optiondict["similaritymetric"] == "mutualinfo":
1865
- theMutualInformationator.setlimits(lagmininpts, lagmaxinpts)
1866
- (
1867
- voxelsprocessed_cp,
1868
- theglobalmaxlist,
1869
- trimmedcorrscale,
1870
- ) = tide_calcsimfunc.correlationpass(
1871
- fmri_data_valid[:, validsimcalcstart : validsimcalcend + 1],
1872
- cleaned_referencetc,
1873
- theMutualInformationator,
1874
- initial_fmri_x[validsimcalcstart : validsimcalcend + 1],
1875
- os_fmri_x[osvalidsimcalcstart : osvalidsimcalcend + 1],
1876
- lagmininpts,
1877
- lagmaxinpts,
1878
- corrout,
1879
- meanval,
1880
- nprocs=optiondict["nprocs_calcsimilarity"],
1881
- alwaysmultiproc=optiondict["alwaysmultiproc"],
1882
- oversampfactor=optiondict["oversampfactor"],
1883
- interptype=optiondict["interptype"],
1884
- showprogressbar=optiondict["showprogressbar"],
1885
- chunksize=optiondict["mp_chunksize"],
1886
- rt_floatset=rt_floatset,
1887
- rt_floattype=rt_floattype,
1888
- debug=optiondict["focaldebug"],
1889
- )
1890
- else:
1891
- (
1892
- voxelsprocessed_cp,
1893
- theglobalmaxlist,
1894
- trimmedcorrscale,
1895
- ) = tide_calcsimfunc.correlationpass(
1896
- fmri_data_valid[:, validsimcalcstart : validsimcalcend + 1],
1897
- cleaned_referencetc,
1898
- theCorrelator,
1899
- initial_fmri_x[validsimcalcstart : validsimcalcend + 1],
1900
- os_fmri_x[osvalidsimcalcstart : osvalidsimcalcend + 1],
1901
- lagmininpts,
1902
- lagmaxinpts,
1903
- corrout,
1904
- meanval,
1905
- nprocs=optiondict["nprocs_calcsimilarity"],
1906
- alwaysmultiproc=optiondict["alwaysmultiproc"],
1907
- oversampfactor=optiondict["oversampfactor"],
1908
- interptype=optiondict["interptype"],
1909
- showprogressbar=optiondict["showprogressbar"],
1910
- chunksize=optiondict["mp_chunksize"],
1911
- rt_floatset=rt_floatset,
1912
- rt_floattype=rt_floattype,
1913
- debug=optiondict["focaldebug"],
1914
- )
1915
- tide_util.enablemkl(optiondict["mklthreads"], debug=threaddebug)
1916
-
1917
- for i in range(len(theglobalmaxlist)):
1918
- theglobalmaxlist[i] = corrscale[theglobalmaxlist[i]] - optiondict["simcalcoffset"]
1919
- namesuffix = "_desc-globallag_hist"
1920
- tide_stats.makeandsavehistogram(
1921
- np.asarray(theglobalmaxlist),
1922
- len(corrscale),
1923
- 0,
1924
- outputname + namesuffix,
1925
- displaytitle="Histogram of lag times from global lag calculation",
1926
- therange=(corrscale[0], corrscale[-1]),
1927
- refine=False,
1928
- dictvarname="globallaghist_pass" + str(thepass),
1929
- append=(optiondict["echocancel"] or (thepass > 1)),
1930
- thedict=optiondict,
1931
- )
1932
-
1933
- if optiondict["checkpoint"]:
1934
- outcorrarray[:, :] = 0.0
1935
- outcorrarray[validvoxels, :] = corrout[:, :]
1936
- if theinputdata.filetype == "text":
1937
- tide_io.writenpvecs(
1938
- outcorrarray.reshape(nativecorrshape),
1939
- f"{outputname}_corrout_prefit_pass" + str(thepass) + ".txt",
1940
- )
1941
- else:
1942
- savename = f"{outputname}_desc-corroutprefit_pass-" + str(thepass)
1943
- tide_io.savetonifti(outcorrarray.reshape(nativecorrshape), theheader, savename)
1944
-
1945
- TimingLGR.info(
1946
- f"{similaritytype} calculation end, pass {thepass}",
1947
- {
1948
- "message2": voxelsprocessed_cp,
1949
- "message3": "voxels",
1950
- },
1951
- )
1952
-
1953
- # Step 1b. Do a peak prefit
1954
- if optiondict["similaritymetric"] == "hybrid":
1955
- LGR.info(f"\n\nPeak prefit calculation, pass {thepass}")
1956
- TimingLGR.info(f"Peak prefit calculation start, pass {thepass}")
1957
-
1958
- tide_util.disablemkl(optiondict["nprocs_peakeval"], debug=threaddebug)
1959
- voxelsprocessed_pe, thepeakdict = tide_peakeval.peakevalpass(
1960
- fmri_data_valid[:, validsimcalcstart : validsimcalcend + 1],
1961
- cleaned_referencetc,
1962
- initial_fmri_x[validsimcalcstart : validsimcalcend + 1],
1963
- os_fmri_x[osvalidsimcalcstart : osvalidsimcalcend + 1],
1964
- theMutualInformationator,
1965
- trimmedcorrscale,
1966
- corrout,
1967
- nprocs=optiondict["nprocs_peakeval"],
1968
- alwaysmultiproc=optiondict["alwaysmultiproc"],
1969
- bipolar=optiondict["bipolar"],
1970
- oversampfactor=optiondict["oversampfactor"],
1971
- interptype=optiondict["interptype"],
1972
- showprogressbar=optiondict["showprogressbar"],
1973
- chunksize=optiondict["mp_chunksize"],
1974
- rt_floatset=rt_floatset,
1975
- rt_floattype=rt_floattype,
1976
- )
1977
- tide_util.enablemkl(optiondict["mklthreads"], debug=threaddebug)
1978
-
1979
- TimingLGR.info(
1980
- f"Peak prefit end, pass {thepass}",
1981
- {
1982
- "message2": voxelsprocessed_pe,
1983
- "message3": "voxels",
1984
- },
1985
- )
1986
- mipeaks = lagtimes * 0.0
1987
- for i in range(numvalidspatiallocs):
1988
- if len(thepeakdict[str(i)]) > 0:
1989
- mipeaks[i] = thepeakdict[str(i)][0][0]
1990
- else:
1991
- thepeakdict = None
1992
-
1993
- # Step 2 - similarity function fitting and time lag estimation
1994
- # write out the current version of the run options
1995
- optiondict["currentstage"] = f"presimfuncfit_pass{thepass}"
1996
- tide_io.writedicttojson(optiondict, f"{outputname}_desc-runoptions_info.json")
1997
- LGR.info(f"\n\nTime lag estimation pass {thepass}")
1998
- TimingLGR.info(f"Time lag estimation start, pass {thepass}")
1999
-
2000
- theFitter.setfunctype(optiondict["similaritymetric"])
2001
- theFitter.setcorrtimeaxis(trimmedcorrscale)
2002
-
2003
- # use initial lags if this is a hybrid fit
2004
- if optiondict["similaritymetric"] == "hybrid" and thepeakdict is not None:
2005
- initlags = mipeaks
2006
- else:
2007
- initlags = None
2008
-
2009
- tide_util.disablemkl(optiondict["nprocs_fitcorr"], debug=threaddebug)
2010
- voxelsprocessed_fc = tide_simfuncfit.fitcorr(
2011
- trimmedcorrscale,
2012
- theFitter,
1938
+ # Step 1a - do the initial delay estimation
1939
+ similaritytype = tide_calcSimFuncMap.calcSimFunc(
1940
+ numvalidspatiallocs,
1941
+ fmri_data_valid,
1942
+ validsimcalcstart,
1943
+ validsimcalcend,
1944
+ osvalidsimcalcstart,
1945
+ osvalidsimcalcend,
1946
+ initial_fmri_x,
1947
+ os_fmri_x,
1948
+ theCorrelator,
1949
+ theMutualInformationator,
1950
+ cleaned_referencetc,
2013
1951
  corrout,
2014
- fitmask,
2015
- failreason,
2016
- lagtimes,
2017
- lagstrengths,
2018
- lagsigma,
2019
- gaussout,
2020
- windowout,
2021
- R2,
2022
- despeckling=False,
2023
- peakdict=thepeakdict,
2024
- nprocs=optiondict["nprocs_fitcorr"],
1952
+ riptideregressorset,
1953
+ riptidedelays,
1954
+ sLFOfitmean,
1955
+ r2value,
1956
+ fitcoeff,
1957
+ fitNorm,
1958
+ meanval,
1959
+ corrscale,
1960
+ outputname,
1961
+ outcorrarray,
1962
+ validvoxels,
1963
+ nativecorrshape,
1964
+ theinputdata,
1965
+ theheader,
1966
+ lagmininpts,
1967
+ lagmaxinpts,
1968
+ thepass,
1969
+ optiondict,
1970
+ LGR,
1971
+ TimingLGR,
1972
+ similaritymetric=optiondict["similaritymetric"],
1973
+ simcalcoffset=optiondict["simcalcoffset"],
1974
+ echocancel=optiondict["echocancel"],
1975
+ checkpoint=optiondict["checkpoint"],
1976
+ mklthreads=optiondict["mklthreads"],
1977
+ nprocs=optiondict["nprocs_calcsimilarity"],
2025
1978
  alwaysmultiproc=optiondict["alwaysmultiproc"],
2026
- fixdelay=optiondict["fixdelay"],
2027
- initialdelayvalue=theinitialdelay,
1979
+ oversampfactor=optiondict["oversampfactor"],
1980
+ interptype=optiondict["interptype"],
2028
1981
  showprogressbar=optiondict["showprogressbar"],
2029
1982
  chunksize=optiondict["mp_chunksize"],
2030
- despeckle_thresh=optiondict["despeckle_thresh"],
2031
- initiallags=initlags,
2032
1983
  rt_floatset=rt_floatset,
2033
1984
  rt_floattype=rt_floattype,
1985
+ threaddebug=optiondict["threaddebug"],
1986
+ debug=optiondict["focaldebug"],
2034
1987
  )
2035
- tide_util.enablemkl(optiondict["mklthreads"], debug=threaddebug)
2036
-
2037
- TimingLGR.info(
2038
- f"Time lag estimation end, pass {thepass}",
2039
- {
2040
- "message2": voxelsprocessed_fc,
2041
- "message3": "voxels",
2042
- },
2043
- )
2044
-
2045
- # Step 2b - Correlation time despeckle
2046
- if optiondict["despeckle_passes"] > 0:
2047
- LGR.info(f"\n\n{similaritytype} despeckling pass {thepass}")
2048
- LGR.info(f"\tUsing despeckle_thresh = {optiondict['despeckle_thresh']:.3f}")
2049
- TimingLGR.info(f"{similaritytype} despeckle start, pass {thepass}")
2050
-
2051
- # find lags that are very different from their neighbors, and refit starting at the median lag for the point
2052
- voxelsprocessed_fc_ds = 0
2053
- despecklingdone = False
2054
- lastnumdespeckled = 1000000
2055
- for despecklepass in range(optiondict["despeckle_passes"]):
2056
- LGR.info(f"\n\n{similaritytype} despeckling subpass {despecklepass + 1}")
2057
- outmaparray *= 0.0
2058
- outmaparray[validvoxels] = eval("lagtimes")[:]
2059
-
2060
- # find voxels to despeckle
2061
- medianlags = ndimage.median_filter(
2062
- outmaparray.reshape(nativespaceshape), 3
2063
- ).reshape(numspatiallocs)
2064
- # voxels that we're happy with have initlags set to -1000000.0
2065
- initlags = np.where(
2066
- np.abs(outmaparray - medianlags) > optiondict["despeckle_thresh"],
2067
- medianlags,
2068
- -1000000.0,
2069
- )[validvoxels]
2070
-
2071
- if len(initlags) > 0:
2072
- numdespeckled = len(np.where(initlags != -1000000.0)[0])
2073
- if lastnumdespeckled > numdespeckled > 0:
2074
- lastnumdespeckled = numdespeckled
2075
- tide_util.disablemkl(optiondict["nprocs_fitcorr"], debug=threaddebug)
2076
- voxelsprocessed_thispass = tide_simfuncfit.fitcorr(
2077
- trimmedcorrscale,
2078
- theFitter,
2079
- corrout,
2080
- fitmask,
2081
- failreason,
2082
- lagtimes,
2083
- lagstrengths,
2084
- lagsigma,
2085
- gaussout,
2086
- windowout,
2087
- R2,
2088
- despeckling=True,
2089
- peakdict=thepeakdict,
2090
- nprocs=optiondict["nprocs_fitcorr"],
2091
- alwaysmultiproc=optiondict["alwaysmultiproc"],
2092
- fixdelay=optiondict["fixdelay"],
2093
- initialdelayvalue=theinitialdelay,
2094
- showprogressbar=optiondict["showprogressbar"],
2095
- chunksize=optiondict["mp_chunksize"],
2096
- despeckle_thresh=optiondict["despeckle_thresh"],
2097
- initiallags=initlags,
2098
- rt_floatset=rt_floatset,
2099
- rt_floattype=rt_floattype,
2100
- )
2101
- tide_util.enablemkl(optiondict["mklthreads"], debug=threaddebug)
2102
-
2103
- voxelsprocessed_fc_ds += voxelsprocessed_thispass
2104
- optiondict[
2105
- "despecklemasksize_pass" + str(thepass) + "_d" + str(despecklepass + 1)
2106
- ] = voxelsprocessed_thispass
2107
- optiondict[
2108
- "despecklemaskpct_pass" + str(thepass) + "_d" + str(despecklepass + 1)
2109
- ] = (100.0 * voxelsprocessed_thispass / optiondict["corrmasksize"])
2110
- else:
2111
- despecklingdone = True
2112
- else:
2113
- despecklingdone = True
2114
- if despecklingdone:
2115
- LGR.info("Nothing left to do! Terminating despeckling")
2116
- break
2117
-
2118
- internaldespeckleincludemask = np.where(
2119
- np.abs(outmaparray - medianlags) > optiondict["despeckle_thresh"],
2120
- medianlags,
2121
- 0.0,
2122
- )
2123
- if optiondict["savedespecklemasks"] and (optiondict["despeckle_passes"] > 0):
2124
- despecklesavemask = np.where(
2125
- internaldespeckleincludemask[validvoxels] == 0.0, 0, 1
2126
- )
2127
- if thepass == optiondict["passes"]:
2128
- if theinputdata.filetype != "text":
2129
- if theinputdata.filetype == "cifti":
2130
- timeindex = theheader["dim"][0] - 1
2131
- spaceindex = theheader["dim"][0]
2132
- theheader["dim"][timeindex] = 1
2133
- theheader["dim"][spaceindex] = numspatiallocs
2134
- else:
2135
- theheader["dim"][0] = 3
2136
- theheader["dim"][4] = 1
2137
- theheader["pixdim"][4] = 1.0
2138
- masklist = [
2139
- (
2140
- despecklesavemask,
2141
- "despeckle",
2142
- "mask",
2143
- None,
2144
- "Voxels that underwent despeckling in the final pass",
2145
- )
2146
- ]
2147
- tide_io.savemaplist(
2148
- outputname,
2149
- masklist,
2150
- validvoxels,
2151
- nativespaceshape,
2152
- theheader,
2153
- bidsbasedict,
2154
- filetype=theinputdata.filetype,
2155
- rt_floattype=rt_floattype,
2156
- cifti_hdr=theinputdata.cifti_hdr,
2157
- )
2158
- LGR.info(
2159
- f"\n\n{voxelsprocessed_fc_ds} voxels despeckled in "
2160
- f"{optiondict['despeckle_passes']} passes"
2161
- )
2162
- TimingLGR.info(
2163
- f"{similaritytype} despeckle end, pass {thepass}",
2164
- {
2165
- "message2": voxelsprocessed_fc_ds,
2166
- "message3": "voxels",
2167
- },
2168
- )
1988
+ if optiondict["similaritymetric"] == "riptide":
1989
+ optiondict["despeckle_passes"] = 0
1990
+ fitcorrscale = riptidedelays
1991
+ else:
1992
+ fitcorrscale = trimmedcorrscale
2169
1993
 
2170
- # Step 2c - patch shifting
2171
- if optiondict["patchshift"]:
2172
- outmaparray *= 0.0
2173
- outmaparray[validvoxels] = eval("lagtimes")[:]
2174
- # new method
2175
- masklist = [
2176
- (
2177
- outmaparray[validvoxels],
2178
- f"lagtimes_prepatch_pass{thepass}",
2179
- "map",
2180
- None,
2181
- f"Input lagtimes map prior to patch map generation pass {thepass}",
2182
- ),
1994
+ if optiondict["saveintermediatemaps"]:
1995
+ theheader = theinputdata.copyheader(numtimepoints=1)
1996
+ bidspasssuffix = f"_intermediatedata-pass{thepass}"
1997
+ maplist = [
1998
+ (lagtimes, "maxtimecoarse", "map", "second", "Lag time in seconds"),
1999
+ (lagstrengths, "maxcorrcoarse", "map", None, "Maximum correlation strength"),
2183
2000
  ]
2184
2001
  tide_io.savemaplist(
2185
- outputname,
2186
- masklist,
2002
+ f"{outputname}{bidspasssuffix}",
2003
+ maplist,
2187
2004
  validvoxels,
2188
2005
  nativespaceshape,
2189
2006
  theheader,
@@ -2193,88 +2010,117 @@ def rapidtide_main(argparsingfunc):
2193
2010
  cifti_hdr=theinputdata.cifti_hdr,
2194
2011
  )
2195
2012
 
2196
- # create list of anomalous 3D regions that don't match surroundings
2197
- if theinputdata.nim_affine is not None:
2198
- # make an atlas of anomalous patches - each patch shares the same integer value
2199
- step1 = tide_patch.calc_DoG(
2200
- outmaparray.reshape(nativespaceshape).copy(),
2201
- theinputdata.nim_affine,
2202
- thesizes,
2203
- fwhm=optiondict["patchfwhm"],
2204
- ratioopt=False,
2205
- debug=True,
2206
- )
2207
- masklist = [
2208
- (
2209
- step1.reshape(internalspaceshape)[validvoxels],
2210
- f"DoG_pass{thepass}",
2211
- "map",
2212
- None,
2213
- f"DoG map for pass {thepass}",
2214
- ),
2215
- ]
2216
- tide_io.savemaplist(
2217
- outputname,
2218
- masklist,
2219
- validvoxels,
2220
- nativespaceshape,
2221
- theheader,
2222
- bidsbasedict,
2223
- filetype=theinputdata.filetype,
2224
- rt_floattype=rt_floattype,
2225
- cifti_hdr=theinputdata.cifti_hdr,
2226
- )
2227
- step2 = tide_patch.invertedflood3D(
2228
- step1,
2229
- 1,
2230
- )
2231
- masklist = [
2232
- (
2233
- step2.reshape(internalspaceshape)[validvoxels],
2234
- f"invertflood_pass{thepass}",
2235
- "map",
2236
- None,
2237
- f"Inverted flood map for pass {thepass}",
2238
- ),
2239
- ]
2240
- tide_io.savemaplist(
2241
- outputname,
2242
- masklist,
2243
- validvoxels,
2244
- nativespaceshape,
2245
- theheader,
2246
- bidsbasedict,
2247
- filetype=theinputdata.filetype,
2248
- rt_floattype=rt_floattype,
2249
- cifti_hdr=theinputdata.cifti_hdr,
2250
- )
2251
2013
 
2252
- patchmap = tide_patch.separateclusters(
2253
- step2,
2254
- sizethresh=optiondict["patchminsize"],
2255
- debug=True,
2256
- )
2257
- # patchmap = tide_patch.getclusters(
2258
- # outmaparray.reshape(nativespaceshape),
2259
- # theinputdata.nim_affine,
2260
- # thesizes,
2261
- # fwhm=optiondict["patchfwhm"],
2262
- # ratioopt=True,
2263
- # sizethresh=optiondict["patchminsize"],
2264
- # debug=True,
2265
- # )
2266
- masklist = [
2267
- (
2268
- patchmap[validvoxels],
2269
- f"patch_pass{thepass}",
2270
- "map",
2271
- None,
2272
- f"Patch map for despeckling pass {thepass}",
2273
- ),
2014
+
2015
+ # Step 2a - fit the delay function
2016
+ internaldespeckleincludemask = tide_fitSimFuncMap.fitSimFunc(
2017
+ fmri_data_valid,
2018
+ validsimcalcstart,
2019
+ validsimcalcend,
2020
+ osvalidsimcalcstart,
2021
+ osvalidsimcalcend,
2022
+ initial_fmri_x,
2023
+ os_fmri_x,
2024
+ theMutualInformationator,
2025
+ cleaned_referencetc,
2026
+ corrout,
2027
+ outputname,
2028
+ validvoxels,
2029
+ nativespaceshape,
2030
+ bidsbasedict,
2031
+ numspatiallocs,
2032
+ gaussout,
2033
+ theinitialdelay,
2034
+ windowout,
2035
+ R2,
2036
+ thesizes,
2037
+ internalspaceshape,
2038
+ numvalidspatiallocs,
2039
+ theinputdata,
2040
+ theheader,
2041
+ theFitter,
2042
+ fitmask,
2043
+ lagtimes,
2044
+ lagstrengths,
2045
+ lagsigma,
2046
+ failreason,
2047
+ outmaparray,
2048
+ fitcorrscale,
2049
+ similaritytype,
2050
+ thepass,
2051
+ optiondict,
2052
+ LGR,
2053
+ TimingLGR,
2054
+ simplefit=(optiondict["similaritymetric"] == "riptide"),
2055
+ rt_floatset=np.float64,
2056
+ rt_floattype="float64",
2057
+ )
2058
+
2059
+ # Step 2b - refine delay (optional)
2060
+ if optiondict["refinedelayeachpass"]:
2061
+ if optiondict["delayoffsetgausssigma"] < 0.0 and theinputdata.filetype != "text":
2062
+ # set gausssigma automatically
2063
+ optiondict["delayoffsetgausssigma"] = np.mean([xdim, ydim, slicethickness]) / 2.0
2064
+
2065
+ if optiondict["sLFOfiltmask"]:
2066
+ sLFOfiltmask = fitmask + 0.0
2067
+ else:
2068
+ sLFOfiltmask = fitmask * 0.0 + 1.0
2069
+
2070
+ optiondict["regressfiltthreshval"] = 0.0
2071
+
2072
+ (
2073
+ delayoffset,
2074
+ regressderivratios,
2075
+ medfiltregressderivratios,
2076
+ filteredregressderivratios,
2077
+ optiondict["delayoffsetMAD"],
2078
+ ) = tide_refineDelayMap.refineDelay(
2079
+ fmri_data_valid,
2080
+ initial_fmri_x,
2081
+ xdim,
2082
+ ydim,
2083
+ slicethickness,
2084
+ sLFOfiltmask,
2085
+ genlagtc,
2086
+ oversamptr,
2087
+ sLFOfitmean,
2088
+ rvalue,
2089
+ r2value,
2090
+ fitNorm,
2091
+ fitcoeff,
2092
+ lagtc,
2093
+ outputname,
2094
+ validvoxels,
2095
+ nativespaceshape,
2096
+ theinputdata,
2097
+ lagtimes,
2098
+ optiondict,
2099
+ LGR,
2100
+ TimingLGR,
2101
+ outputlevel=optiondict["outputlevel"],
2102
+ gausssigma=optiondict["delayoffsetgausssigma"],
2103
+ patchthresh=optiondict["delaypatchthresh"],
2104
+ mindelay=optiondict["mindelay"],
2105
+ maxdelay=optiondict["maxdelay"],
2106
+ numpoints=optiondict["numpoints"],
2107
+ histlen=optiondict["histlen"],
2108
+ rt_floatset=rt_floatset,
2109
+ rt_floattype=rt_floattype,
2110
+ debug=optiondict["debug"],
2111
+ )
2112
+ lagtimes[:] = lagtimes + delayoffset
2113
+
2114
+ if optiondict["saveintermediatemaps"]:
2115
+ theheader = theinputdata.copyheader(numtimepoints=1)
2116
+ bidspasssuffix = f"_intermediatedata-pass{thepass}"
2117
+ maplist = [
2118
+ (lagtimes, "maxtimerefined", "map", "second", "Lag time in seconds"),
2119
+ (lagstrengths, "maxcorrrefined", "map", None, "Maximum correlation strength"),
2274
2120
  ]
2275
2121
  tide_io.savemaplist(
2276
- outputname,
2277
- masklist,
2122
+ f"{outputname}{bidspasssuffix}",
2123
+ maplist,
2278
2124
  validvoxels,
2279
2125
  nativespaceshape,
2280
2126
  theheader,
@@ -2284,13 +2130,7 @@ def rapidtide_main(argparsingfunc):
2284
2130
  cifti_hdr=theinputdata.cifti_hdr,
2285
2131
  )
2286
2132
 
2287
- # now shift the patches to align with the majority of the image
2288
- tide_patch.interppatch(lagtimes, patchmap[validvoxels])
2289
- ########################
2290
- # Delay estimation end
2291
- ########################
2292
-
2293
- # Step 2d - make a rank order map
2133
+ # Step 2b - make a rank order map
2294
2134
  timepercentile = (
2295
2135
  100.0 * (rankdata(lagtimes, method="dense") - 1) / (numvalidspatiallocs - 1)
2296
2136
  )
@@ -2332,147 +2172,37 @@ def rapidtide_main(argparsingfunc):
2332
2172
  or optiondict["initregressorpreselect"]
2333
2173
  or optiondict["dofinalrefine"]
2334
2174
  ):
2335
- LGR.info(f"\n\nRegressor refinement, pass {thepass}")
2336
- TimingLGR.info(f"Regressor refinement start, pass {thepass}")
2337
- if optiondict["refineoffset"]:
2338
- # check that we won't end up excluding all voxels from offset calculation before accepting mask
2339
- offsetmask = np.uint16(fitmask)
2340
- if internaloffsetincludemask_valid is not None:
2341
- offsetmask[np.where(internaloffsetincludemask_valid == 0)] = 0
2342
- if internaloffsetexcludemask_valid is not None:
2343
- offsetmask[np.where(internaloffsetexcludemask_valid != 0.0)] = 0
2344
- if tide_stats.getmasksize(offsetmask) == 0:
2345
- LGR.warning(
2346
- "NB: cannot exclude voxels from offset calculation mask - including for this pass"
2347
- )
2348
- offsetmask = fitmask + 0
2349
-
2350
- peaklag, dummy, dummy = tide_stats.gethistprops(
2351
- lagtimes[np.where(offsetmask > 0)],
2352
- optiondict["histlen"],
2353
- pickleft=optiondict["pickleft"],
2354
- peakthresh=optiondict["pickleftthresh"],
2355
- )
2356
- optiondict["offsettime"] = peaklag
2357
- optiondict["offsettime_total"] += peaklag
2358
- optiondict[f"offsettime_pass{thepass}"] = optiondict["offsettime"]
2359
- optiondict[f"offsettime_total_pass{thepass}"] = optiondict["offsettime_total"]
2360
- LGR.info(
2361
- f"offset time set to {optiondict['offsettime']:.3f}, "
2362
- f"total is {optiondict['offsettime_total']:.3f}"
2363
- )
2364
-
2365
- if optiondict["refinedespeckled"] or (optiondict["despeckle_passes"] == 0):
2366
- # if refinedespeckled is true, or there is no despeckling, masks are unaffected
2367
- thisinternalrefineexcludemask_valid = internalrefineexcludemask_valid
2368
- else:
2369
- # if refinedespeckled is false and there is despeckling, need to make a proper mask
2370
- if internalrefineexcludemask_valid is None:
2371
- # if there is currently no exclude mask, set exclude mask = despeckle mask
2372
- thisinternalrefineexcludemask_valid = np.where(
2373
- internaldespeckleincludemask[validvoxels] == 0.0, 0, 1
2374
- )
2375
- else:
2376
- # if there is a current exclude mask, add any voxels that are being despeckled
2377
- thisinternalrefineexcludemask_valid = np.where(
2378
- internalrefineexcludemask_valid > 0, 1, 0
2379
- )
2380
- thisinternalrefineexcludemask_valid[
2381
- np.where(internaldespeckleincludemask[validvoxels] != 0.0)
2382
- ] = 1
2383
-
2384
- # now check that we won't end up excluding all voxels from refinement before accepting mask
2385
- overallmask = np.uint16(fitmask)
2386
- if internalrefineincludemask_valid is not None:
2387
- overallmask[np.where(internalrefineincludemask_valid == 0)] = 0
2388
- if thisinternalrefineexcludemask_valid is not None:
2389
- overallmask[np.where(thisinternalrefineexcludemask_valid != 0.0)] = 0
2390
- if tide_stats.getmasksize(overallmask) == 0:
2391
- LGR.warning(
2392
- "NB: cannot exclude despeckled voxels from refinement - including for this pass"
2393
- )
2394
- thisinternalrefineexcludemask_valid = internalrefineexcludemask_valid
2395
- theRegressorRefiner.setmasks(
2396
- internalrefineincludemask_valid, thisinternalrefineexcludemask_valid
2397
- )
2398
-
2399
- # regenerate regressor for next pass
2400
- # create the refinement mask
2401
- LGR.info("making refine mask")
2402
- createdmask = theRegressorRefiner.makemask(lagstrengths, lagtimes, lagsigma, fitmask)
2403
- print(f"Refine mask has {theRegressorRefiner.refinemaskvoxels} voxels")
2404
- if not createdmask:
2405
- print("no voxels qualify for refinement - exiting")
2406
- sys.exit()
2407
-
2408
- # align timecourses to prepare for refinement
2409
- LGR.info("aligning timecourses")
2410
- tide_util.disablemkl(optiondict["nprocs_refine"], debug=threaddebug)
2411
- voxelsprocessed_rra = theRegressorRefiner.alignvoxels(
2412
- fmri_data_valid, fmritr, lagtimes
2413
- )
2414
- tide_util.enablemkl(optiondict["mklthreads"], debug=threaddebug)
2415
- LGR.info(f"align complete: {voxelsprocessed_rra=}")
2416
-
2417
- # prenormalize
2418
- LGR.info("prenormalizing timecourses")
2419
- theRegressorRefiner.prenormalize(lagtimes, lagstrengths, R2)
2420
-
2421
- # now doing the refinement
2422
- (
2423
- voxelsprocessed_rr,
2424
- outputdict,
2425
- previousnormoutputdata,
2426
- resampref_y,
2427
- resampnonosref_y,
2428
- stoprefining,
2429
- refinestopreason,
2430
- genlagtc,
2431
- ) = theRegressorRefiner.refine(
2432
- theprefilter,
2433
- fmritr,
2434
- thepass,
2435
- lagstrengths,
2436
- lagtimes,
2437
- previousnormoutputdata,
2438
- optiondict["corrmasksize"],
2439
- )
2440
- TimingLGR.info(
2441
- f"Regressor refinement end, pass {thepass}",
2442
- {
2443
- "message2": voxelsprocessed_rr,
2444
- "message3": "voxels",
2445
- },
2446
- )
2447
- for key, value in outputdict.items():
2448
- optiondict[key] = value
2449
-
2450
- # Save shifted timecourses for César
2451
- if optiondict["saveintermediatemaps"] and optiondict["savelagregressors"]:
2452
- theheader = theinputdata.copyheader()
2453
- bidspasssuffix = f"_intermediatedata-pass{thepass}"
2454
- maplist = [
2455
- (
2456
- (theRegressorRefiner.getpaddedshiftedtcs())[:, numpadtrs:-numpadtrs],
2457
- "shiftedtcs",
2458
- "bold",
2459
- None,
2460
- "The filtered input fMRI data, in voxels used for refinement, time shifted by the negated delay in every voxel so that the moving blood component is aligned.",
2461
- ),
2462
- ]
2463
- tide_io.savemaplist(
2464
- f"{outputname}{bidspasssuffix}",
2465
- maplist,
2175
+ (resampref_y, resampnonosref_y, stoprefining, refinestopreason, genlagtc) = (
2176
+ tide_refineRegressor.refineRegressor(
2177
+ LGR,
2178
+ TimingLGR,
2179
+ thepass,
2180
+ optiondict,
2181
+ fitmask,
2182
+ internaloffsetincludemask_valid,
2183
+ internaloffsetexcludemask_valid,
2184
+ internalrefineincludemask_valid,
2185
+ internalrefineexcludemask_valid,
2186
+ internaldespeckleincludemask,
2466
2187
  validvoxels,
2188
+ theRegressorRefiner,
2189
+ lagtimes,
2190
+ lagstrengths,
2191
+ lagsigma,
2192
+ fmri_data_valid,
2193
+ fmritr,
2194
+ R2,
2195
+ theprefilter,
2196
+ previousnormoutputdata,
2197
+ theinputdata,
2198
+ numpadtrs,
2199
+ outputname,
2467
2200
  nativefmrishape,
2468
- theheader,
2469
2201
  bidsbasedict,
2470
- filetype=theinputdata.filetype,
2471
- rt_floattype=rt_floattype,
2472
- cifti_hdr=theinputdata.cifti_hdr,
2473
- debug=True,
2202
+ rt_floatset=np.float64,
2203
+ rt_floattype="float64",
2474
2204
  )
2475
- # We are done with refinement.
2205
+ )
2476
2206
  # End of main pass loop
2477
2207
 
2478
2208
  if optiondict["convergencethresh"] is None:
@@ -2535,23 +2265,27 @@ def rapidtide_main(argparsingfunc):
2535
2265
  internalvalidcoherenceshape = (numvalidspatiallocs, coherencefreqaxissize)
2536
2266
 
2537
2267
  # now allocate the arrays needed for the coherence calculation
2268
+ coherencefunc, coherencefunc_shm = tide_util.allocarray(
2269
+ internalvalidcoherenceshape,
2270
+ rt_outfloatset,
2271
+ shared=optiondict["sharedmem"],
2272
+ name=f"coherencefunc_{optiondict['pid']}",
2273
+ )
2274
+ coherencepeakval, coherencepeakval_shm = tide_util.allocarray(
2275
+ numvalidspatiallocs,
2276
+ rt_outfloatset,
2277
+ shared=optiondict["sharedmem"],
2278
+ name=f"coherencepeakval_{optiondict['pid']}",
2279
+ )
2280
+ coherencepeakfreq, coherencepeakfreq_shm = tide_util.allocarray(
2281
+ numvalidspatiallocs,
2282
+ rt_outfloatset,
2283
+ shared=optiondict["sharedmem"],
2284
+ name=f"coherencepeakfreq_{optiondict['pid']}",
2285
+ )
2538
2286
  if optiondict["sharedmem"]:
2539
- coherencefunc, coherencefunc_shm = tide_util.allocshared(
2540
- internalvalidcoherenceshape,
2541
- rt_outfloatset,
2542
- name=f"coherencefunc_{optiondict['pid']}",
2543
- )
2544
- coherencepeakval, coherencepeakval_shm = tide_util.allocshared(
2545
- numvalidspatiallocs, rt_outfloatset, name=f"coherencepeakval_{optiondict['pid']}"
2546
- )
2547
- coherencepeakfreq, coherencepeakfreq_shm = tide_util.allocshared(
2548
- numvalidspatiallocs, rt_outfloatset, name=f"coherencepeakfreq_{optiondict['pid']}"
2549
- )
2550
2287
  ramlocation = "in shared memory"
2551
2288
  else:
2552
- coherencefunc = np.zeros(internalvalidcoherenceshape, dtype=rt_outfloattype)
2553
- coherencepeakval = np.zeros(numvalidspatiallocs, dtype=rt_outfloattype)
2554
- coherencepeakfreq = np.zeros(numvalidspatiallocs, dtype=rt_outfloattype)
2555
2289
  ramlocation = "locally"
2556
2290
  optiondict["totalcoherencebytes"] = (
2557
2291
  coherencefunc.nbytes + coherencepeakval.nbytes + coherencepeakfreq.nbytes
@@ -2559,7 +2293,7 @@ def rapidtide_main(argparsingfunc):
2559
2293
  thesize, theunit = tide_util.format_bytes(optiondict["totalcoherencebytes"])
2560
2294
  print(f"allocated {thesize:.3f} {theunit} {ramlocation} for coherence calculation")
2561
2295
 
2562
- tide_util.disablemkl(1, debug=threaddebug)
2296
+ tide_util.disablemkl(1, debug=optiondict["threaddebug"])
2563
2297
  voxelsprocessed_coherence = tide_calccoherence.coherencepass(
2564
2298
  fmri_data_valid,
2565
2299
  theCoherer,
@@ -2569,10 +2303,10 @@ def rapidtide_main(argparsingfunc):
2569
2303
  alt=True,
2570
2304
  showprogressbar=optiondict["showprogressbar"],
2571
2305
  chunksize=optiondict["mp_chunksize"],
2572
- nprocs=1,
2306
+ nprocs=optiondict["nprocs"],
2573
2307
  alwaysmultiproc=optiondict["alwaysmultiproc"],
2574
2308
  )
2575
- tide_util.enablemkl(optiondict["mklthreads"], debug=threaddebug)
2309
+ tide_util.enablemkl(optiondict["mklthreads"], debug=optiondict["threaddebug"])
2576
2310
 
2577
2311
  # save the results of the calculations
2578
2312
  theheader = theinputdata.copyheader(
@@ -2607,17 +2341,21 @@ def rapidtide_main(argparsingfunc):
2607
2341
  LGR.info("\n\nWiener deconvolution")
2608
2342
 
2609
2343
  # now allocate the arrays needed for Wiener deconvolution
2344
+ wienerdeconv, wienerdeconv_shm = tide_util.allocarray(
2345
+ internalvalidspaceshape,
2346
+ rt_outfloatset,
2347
+ shared=optiondict["sharedmem"],
2348
+ name=f"wienerdeconv_{optiondict['pid']}",
2349
+ )
2350
+ wpeak, wpeak_shm = tide_util.allocarray(
2351
+ internalvalidspaceshape,
2352
+ rt_outfloatset,
2353
+ shared=optiondict["sharedmem"],
2354
+ name=f"wpeak_{optiondict['pid']}",
2355
+ )
2610
2356
  if optiondict["sharedmem"]:
2611
- wienerdeconv, wienerdeconv_shm = tide_util.allocshared(
2612
- internalvalidspaceshape, rt_outfloatset, name=f"wienerdeconv_{optiondict['pid']}"
2613
- )
2614
- wpeak, wpeak_shm = tide_util.allocshared(
2615
- internalvalidspaceshape, rt_outfloatset, name=f"wpeak_{optiondict['pid']}"
2616
- )
2617
2357
  ramlocation = "in shared memory"
2618
2358
  else:
2619
- wienerdeconv = np.zeros(internalvalidspaceshape, dtype=rt_outfloattype)
2620
- wpeak = np.zeros(internalvalidspaceshape, dtype=rt_outfloattype)
2621
2359
  ramlocation = "locally"
2622
2360
  optiondict["totalwienerbytes"] = wienerdeconv.nbytes + wpeak.nbytes
2623
2361
  thesize, theunit = tide_util.format_bytes(optiondict["totalwienerbytes"])
@@ -2627,6 +2365,7 @@ def rapidtide_main(argparsingfunc):
2627
2365
  numspatiallocs,
2628
2366
  fmri_data_valid,
2629
2367
  threshval,
2368
+ lagtc,
2630
2369
  optiondict,
2631
2370
  wienerdeconv,
2632
2371
  wpeak,
@@ -2721,66 +2460,27 @@ def rapidtide_main(argparsingfunc):
2721
2460
  TimingLGR.info("End moving fmri_data to shared memory")
2722
2461
  theinputdata.unload()
2723
2462
 
2724
- # now allocate the arrays needed for sLFO filtering
2725
- if optiondict["refinedelay"]:
2726
- derivaxissize = np.max(
2727
- [optiondict["refineregressderivs"] + 1, optiondict["regressderivs"] + 1]
2728
- )
2729
- else:
2730
- derivaxissize = optiondict["regressderivs"] + 1
2731
- internalvalidspaceshapederivs = (
2732
- internalvalidspaceshape,
2733
- derivaxissize,
2463
+ # allocate the arrays needed for sLFO filtering
2464
+ movingsignal, movingsignal_shm = tide_util.allocarray(
2465
+ internalvalidfmrishape,
2466
+ rt_outfloattype,
2467
+ shared=optiondict["sharedmem"],
2468
+ name=f"movingsignal_{optiondict['pid']}",
2469
+ )
2470
+ filtereddata, filtereddata_shm = tide_util.allocarray(
2471
+ internalvalidfmrishape,
2472
+ rt_outfloattype,
2473
+ shared=optiondict["sharedmem"],
2474
+ name=f"filtereddata_{optiondict['pid']}",
2734
2475
  )
2735
2476
  if optiondict["sharedmem"]:
2736
- sLFOfitmean, sLFOfitmean_shm = tide_util.allocshared(
2737
- internalvalidspaceshape, rt_outfloatset, name=f"sLFOfitmean_{optiondict['pid']}"
2738
- )
2739
- rvalue, rvalue_shm = tide_util.allocshared(
2740
- internalvalidspaceshape, rt_outfloatset, name=f"rvalue_{optiondict['pid']}"
2741
- )
2742
- r2value, r2value_shm = tide_util.allocshared(
2743
- internalvalidspaceshape, rt_outfloatset, name=f"r2value_{optiondict['pid']}"
2744
- )
2745
- fitNorm, fitNorm_shm = tide_util.allocshared(
2746
- internalvalidspaceshapederivs, rt_outfloatset, name=f"fitNorm_{optiondict['pid']}"
2747
- )
2748
- fitcoeff, fitcoeff_shm = tide_util.allocshared(
2749
- internalvalidspaceshapederivs, rt_outfloatset, name=f"fitcoeff_{optiondict['pid']}"
2750
- )
2751
- movingsignal, movingsignal_shm = tide_util.allocshared(
2752
- internalvalidfmrishape, rt_outfloatset, name=f"movingsignal_{optiondict['pid']}"
2753
- )
2754
- lagtc, lagtc_shm = tide_util.allocshared(
2755
- internalvalidfmrishape, rt_floatset, name=f"lagtc_{optiondict['pid']}"
2756
- )
2757
- filtereddata, filtereddata_shm = tide_util.allocshared(
2758
- internalvalidfmrishape, rt_outfloatset, name=f"filtereddata_{optiondict['pid']}"
2759
- )
2760
2477
  ramlocation = "in shared memory"
2761
2478
  else:
2762
- sLFOfitmean = np.zeros(internalvalidspaceshape, dtype=rt_outfloattype)
2763
- rvalue = np.zeros(internalvalidspaceshape, dtype=rt_outfloattype)
2764
- r2value = np.zeros(internalvalidspaceshape, dtype=rt_outfloattype)
2765
- fitNorm = np.zeros(internalvalidspaceshapederivs, dtype=rt_outfloattype)
2766
- fitcoeff = np.zeros(internalvalidspaceshapederivs, dtype=rt_outfloattype)
2767
- movingsignal = np.zeros(internalvalidfmrishape, dtype=rt_outfloattype)
2768
- lagtc = np.zeros(internalvalidfmrishape, dtype=rt_floattype)
2769
- filtereddata = np.zeros(internalvalidfmrishape, dtype=rt_outfloattype)
2770
2479
  ramlocation = "locally"
2771
2480
 
2772
- optiondict["totalsLFOfilterbytes"] = (
2773
- sLFOfitmean.nbytes
2774
- + rvalue.nbytes
2775
- + r2value.nbytes
2776
- + fitNorm.nbytes
2777
- + fitcoeff.nbytes
2778
- + movingsignal.nbytes
2779
- + lagtc.nbytes
2780
- + filtereddata.nbytes
2781
- )
2481
+ optiondict["totalsLFOfilterbytes"] = movingsignal.nbytes + filtereddata.nbytes
2782
2482
  thesize, theunit = tide_util.format_bytes(optiondict["totalsLFOfilterbytes"])
2783
- print(f"allocated {thesize:.3f} {theunit} {ramlocation} for sLFO filter/delay refinement")
2483
+ print(f"allocated {thesize:.3f} {theunit} {ramlocation} for sLFO filter")
2784
2484
  tide_util.logmem("before sLFO filter")
2785
2485
 
2786
2486
  if optiondict["dolinfitfilt"]:
@@ -2829,121 +2529,52 @@ def rapidtide_main(argparsingfunc):
2829
2529
  if optiondict["refinedelay"]:
2830
2530
  TimingLGR.info("Delay refinement start")
2831
2531
  LGR.info("\n\nDelay refinement")
2532
+
2832
2533
  if optiondict["delayoffsetgausssigma"] < 0.0 and theinputdata.filetype != "text":
2833
2534
  # set gausssigma automatically
2834
2535
  optiondict["delayoffsetgausssigma"] = np.mean([xdim, ydim, slicethickness]) / 2.0
2835
2536
 
2836
- regressderivratios, regressrvalues = tide_refinedelay.getderivratios(
2537
+ (
2538
+ delayoffset,
2539
+ regressderivratios,
2540
+ medfiltregressderivratios,
2541
+ filteredregressderivratios,
2542
+ optiondict["delayoffsetMAD"],
2543
+ ) = tide_refineDelayMap.refineDelay(
2837
2544
  fmri_data_valid,
2838
- validvoxels,
2839
2545
  initial_fmri_x,
2840
- lagtimes,
2546
+ xdim,
2547
+ ydim,
2548
+ slicethickness,
2841
2549
  sLFOfiltmask,
2842
2550
  genlagtc,
2843
- mode,
2844
- outputname,
2845
2551
  oversamptr,
2846
2552
  sLFOfitmean,
2847
2553
  rvalue,
2848
2554
  r2value,
2849
- fitNorm[:, : (optiondict["refineregressderivs"] + 1)],
2850
- fitcoeff[:, : (optiondict["refineregressderivs"] + 1)],
2851
- movingsignal,
2555
+ fitNorm,
2556
+ fitcoeff,
2852
2557
  lagtc,
2853
- filtereddata,
2558
+ outputname,
2559
+ validvoxels,
2560
+ nativespaceshape,
2561
+ theinputdata,
2562
+ lagtimes,
2563
+ optiondict,
2854
2564
  LGR,
2855
2565
  TimingLGR,
2856
- optiondict,
2857
- regressderivs=optiondict["refineregressderivs"],
2566
+ outputlevel=optiondict["outputlevel"],
2567
+ gausssigma=optiondict["delayoffsetgausssigma"],
2568
+ patchthresh=optiondict["delaypatchthresh"],
2569
+ mindelay=optiondict["mindelay"],
2570
+ maxdelay=optiondict["maxdelay"],
2571
+ numpoints=optiondict["numpoints"],
2572
+ histlen=optiondict["histlen"],
2573
+ rt_floatset=rt_floatset,
2574
+ rt_floattype=rt_floattype,
2858
2575
  debug=optiondict["debug"],
2859
2576
  )
2860
-
2861
- if optiondict["refineregressderivs"] == 1:
2862
- medfiltregressderivratios, filteredregressderivratios, delayoffsetMAD = (
2863
- tide_refinedelay.filterderivratios(
2864
- regressderivratios,
2865
- nativespaceshape,
2866
- validvoxels,
2867
- (xdim, ydim, slicethickness),
2868
- gausssigma=optiondict["delayoffsetgausssigma"],
2869
- patchthresh=optiondict["delaypatchthresh"],
2870
- filetype=theinputdata.filetype,
2871
- rt_floattype="float64",
2872
- debug=optiondict["debug"],
2873
- )
2874
- )
2875
- optiondict["delayoffsetMAD"] = delayoffsetMAD
2876
-
2877
- # find the mapping of derivative ratios to delays
2878
- tide_refinedelay.trainratiotooffset(
2879
- genlagtc,
2880
- initial_fmri_x,
2881
- outputname,
2882
- optiondict["outputlevel"],
2883
- mindelay=optiondict["mindelay"],
2884
- maxdelay=optiondict["maxdelay"],
2885
- numpoints=optiondict["numpoints"],
2886
- debug=optiondict["debug"],
2887
- )
2888
-
2889
- # now calculate the delay offsets
2890
- delayoffset = np.zeros_like(filteredregressderivratios)
2891
- if optiondict["debug"]:
2892
- print(
2893
- f"calculating delayoffsets for {filteredregressderivratios.shape[0]} voxels"
2894
- )
2895
- for i in range(filteredregressderivratios.shape[0]):
2896
- delayoffset[i], closestoffset = tide_refinedelay.ratiotodelay(
2897
- filteredregressderivratios[i]
2898
- )
2899
- else:
2900
- medfiltregressderivratios = np.zeros_like(regressderivratios)
2901
- filteredregressderivratios = np.zeros_like(regressderivratios)
2902
- delayoffsetMAD = np.zeros(optiondict["refineregressderivs"], dtype=float)
2903
- for i in range(optiondict["refineregressderivs"]):
2904
- (
2905
- medfiltregressderivratios[i, :],
2906
- filteredregressderivratios[i, :],
2907
- delayoffsetMAD[i],
2908
- ) = tide_refinedelay.filterderivratios(
2909
- regressderivratios[i, :],
2910
- (xsize, ysize, numslices),
2911
- validvoxels,
2912
- (xdim, ydim, slicethickness),
2913
- gausssigma=optiondict["delayoffsetgausssigma"],
2914
- patchthresh=optiondict["delaypatchthresh"],
2915
- filetype=theinputdata.filetype,
2916
- rt_floattype=rt_floattype,
2917
- debug=optiondict["debug"],
2918
- )
2919
- optiondict[f"delayoffsetMAD_{i + 1}"] = delayoffsetMAD[i]
2920
-
2921
- # now calculate the delay offsets
2922
- delayoffset = np.zeros_like(filteredregressderivratios[0, :])
2923
- if optiondict["debug"]:
2924
- print(
2925
- f"calculating delayoffsets for {filteredregressderivratios.shape[1]} voxels"
2926
- )
2927
- for i in range(filteredregressderivratios.shape[1]):
2928
- delayoffset[i] = tide_refinedelay.coffstodelay(
2929
- filteredregressderivratios[:, i],
2930
- mindelay=optiondict["mindelay"],
2931
- maxdelay=optiondict["maxdelay"],
2932
- )
2933
-
2934
- namesuffix = "_desc-delayoffset_hist"
2935
- if optiondict["dolinfitfilt"]:
2936
- tide_stats.makeandsavehistogram(
2937
- delayoffset[np.where(sLFOfiltmask > 0)],
2938
- optiondict["histlen"],
2939
- 1,
2940
- outputname + namesuffix,
2941
- displaytitle="Histogram of delay offsets calculated from regression coefficients",
2942
- dictvarname="delayoffsethist",
2943
- thedict=optiondict,
2944
- )
2945
2577
  lagtimesrefined = lagtimes + delayoffset
2946
-
2947
2578
  ####################################################
2948
2579
  # Delay refinement end
2949
2580
  ####################################################
@@ -2992,7 +2623,7 @@ def rapidtide_main(argparsingfunc):
2992
2623
  nprocs_makelaggedtcs=optiondict["nprocs_makelaggedtcs"],
2993
2624
  nprocs_regressionfilt=optiondict["nprocs_regressionfilt"],
2994
2625
  regressderivs=optiondict["regressderivs"],
2995
- mp_chunksize=optiondict["mp_chunksize"],
2626
+ chunksize=optiondict["mp_chunksize"],
2996
2627
  showprogressbar=optiondict["showprogressbar"],
2997
2628
  alwaysmultiproc=optiondict["alwaysmultiproc"],
2998
2629
  debug=optiondict["debug"],
@@ -3176,6 +2807,10 @@ def rapidtide_main(argparsingfunc):
3176
2807
  lagstrengths[np.where(fitmask > 0)], histpcts, nozero=False
3177
2808
  )
3178
2809
  thesigmapcts = tide_stats.getfracvals(lagsigma[np.where(fitmask > 0)], histpcts, nozero=False)
2810
+ if optiondict["refinedelay"]:
2811
+ therefinedtimepcts = tide_stats.getfracvals(
2812
+ lagtimesrefined[np.where(fitmask > 0)], histpcts, nozero=False
2813
+ )
3179
2814
  for i in range(len(histpcts)):
3180
2815
  optiondict[f"lagtimes_{str(int(np.round(100 * histpcts[i], 0))).zfill(2)}pct"] = (
3181
2816
  thetimepcts[i]
@@ -3186,6 +2821,10 @@ def rapidtide_main(argparsingfunc):
3186
2821
  optiondict[f"lagsigma_{str(int(np.round(100 * histpcts[i], 0))).zfill(2)}pct"] = (
3187
2822
  thesigmapcts[i]
3188
2823
  )
2824
+ if optiondict["refinedelay"]:
2825
+ optiondict[
2826
+ f"lagtimesrefined_{str(int(np.round(100 * histpcts[i], 0))).zfill(2)}pct"
2827
+ ] = therefinedtimepcts[i]
3189
2828
  optiondict["fitmasksize"] = np.sum(fitmask)
3190
2829
  optiondict["fitmaskpct"] = 100.0 * optiondict["fitmasksize"] / optiondict["corrmasksize"]
3191
2830
 
@@ -3239,55 +2878,29 @@ def rapidtide_main(argparsingfunc):
3239
2878
  ),
3240
2879
  ]
3241
2880
  if (optiondict["outputlevel"] != "min") and (optiondict["outputlevel"] != "less"):
3242
- if optiondict["refineregressderivs"] > 1:
3243
- for i in range(optiondict["refineregressderivs"]):
3244
- savelist += [
3245
- (
3246
- regressderivratios[i, :],
3247
- f"regressderivratios_{i}",
3248
- "map",
3249
- None,
3250
- f"Ratio of derivative {i + 1} of delayed sLFO to the delayed sLFO",
3251
- ),
3252
- (
3253
- medfiltregressderivratios[i, :],
3254
- f"medfiltregressderivratios_{i}",
3255
- "map",
3256
- None,
3257
- f"Median filtered version of the regressderivratios_{i} map",
3258
- ),
3259
- (
3260
- filteredregressderivratios[i, :],
3261
- f"filteredregressderivratios_{i}",
3262
- "map",
3263
- None,
3264
- f"regressderivratios_{i}, with outliers patched using median filtered data",
3265
- ),
3266
- ]
3267
- else:
3268
- savelist += [
3269
- (
3270
- regressderivratios,
3271
- "regressderivratios",
3272
- "map",
3273
- None,
3274
- "Ratio of the first derivative of delayed sLFO to the delayed sLFO",
3275
- ),
3276
- (
3277
- medfiltregressderivratios,
3278
- "medfiltregressderivratios",
3279
- "map",
3280
- None,
3281
- "Median filtered version of the regressderivratios map",
3282
- ),
3283
- (
3284
- filteredregressderivratios,
3285
- "filteredregressderivratios",
3286
- "map",
3287
- None,
3288
- "regressderivratios, with outliers patched using median filtered data",
3289
- ),
3290
- ]
2881
+ savelist += [
2882
+ (
2883
+ regressderivratios,
2884
+ "regressderivratios",
2885
+ "map",
2886
+ None,
2887
+ "Ratio of the first derivative of delayed sLFO to the delayed sLFO",
2888
+ ),
2889
+ (
2890
+ medfiltregressderivratios,
2891
+ "medfiltregressderivratios",
2892
+ "map",
2893
+ None,
2894
+ "Median filtered version of the regressderivratios map",
2895
+ ),
2896
+ (
2897
+ filteredregressderivratios,
2898
+ "filteredregressderivratios",
2899
+ "map",
2900
+ None,
2901
+ "regressderivratios, with outliers patched using median filtered data",
2902
+ ),
2903
+ ]
3291
2904
  if optiondict["calccoherence"]:
3292
2905
  savelist += [
3293
2906
  (coherencepeakval, "coherencepeakval", "map", None, "Coherence peak value"),
@@ -3498,7 +3111,7 @@ def rapidtide_main(argparsingfunc):
3498
3111
  nprocs_makelaggedtcs=optiondict["nprocs_makelaggedtcs"],
3499
3112
  nprocs_regressionfilt=optiondict["nprocs_regressionfilt"],
3500
3113
  regressderivs=optiondict["regressderivs"],
3501
- mp_chunksize=optiondict["mp_chunksize"],
3114
+ chunksize=optiondict["mp_chunksize"],
3502
3115
  showprogressbar=optiondict["showprogressbar"],
3503
3116
  alwaysmultiproc=optiondict["alwaysmultiproc"],
3504
3117
  debug=optiondict["debug"],
@@ -3585,27 +3198,28 @@ def rapidtide_main(argparsingfunc):
3585
3198
  if optiondict["numestreps"] > 0:
3586
3199
  masklist = []
3587
3200
 
3588
- # we can only calculate this map if we have enough data for a good fit
3201
+ # we can only calculate this map if we have enough data for a good fit, and the fit succeeded
3589
3202
  if optiondict["numestreps"] >= 1000:
3590
- neglogpmax = np.log10(optiondict["numestreps"])
3591
- # generate a neglogp map
3592
- neglog10pmap = lagstrengths * 0.0
3593
- for voxel in range(neglog10pmap.shape[0]):
3594
- neglog10pmap[voxel] = tide_stats.neglog10pfromr(
3595
- lagstrengths[voxel],
3596
- sigfit,
3597
- neglogpmax=neglogpmax,
3598
- debug=optiondict["debug"],
3599
- )
3600
- masklist += [
3601
- (
3602
- neglog10pmap.copy(),
3603
- "neglog10p",
3604
- "map",
3605
- None,
3606
- f"Negative log(10) of the p value of the r at each voxel",
3607
- )
3608
- ]
3203
+ if sigfit is not None:
3204
+ neglogpmax = np.log10(optiondict["numestreps"])
3205
+ # generate a neglogp map
3206
+ neglog10pmap = lagstrengths * 0.0
3207
+ for voxel in range(neglog10pmap.shape[0]):
3208
+ neglog10pmap[voxel] = tide_stats.neglog10pfromr(
3209
+ lagstrengths[voxel],
3210
+ sigfit,
3211
+ neglogpmax=neglogpmax,
3212
+ debug=optiondict["debug"],
3213
+ )
3214
+ masklist += [
3215
+ (
3216
+ neglog10pmap.copy(),
3217
+ "neglog10p",
3218
+ "map",
3219
+ None,
3220
+ f"Negative log(10) of the p value of the r at each voxel",
3221
+ )
3222
+ ]
3609
3223
 
3610
3224
  tide_io.savemaplist(
3611
3225
  outputname,
@@ -3657,11 +3271,19 @@ def rapidtide_main(argparsingfunc):
3657
3271
  del fitmask
3658
3272
 
3659
3273
  # now do the 4D maps of the similarity function and friends
3660
- theheader = theinputdata.copyheader(
3661
- numtimepoints=np.shape(outcorrarray)[1],
3662
- tr=corrtr,
3663
- toffset=(corrscale[corrorigin - lagmininpts]),
3664
- )
3274
+ if optiondict["similaritymetric"] == "riptide":
3275
+ theheader = theinputdata.copyheader(
3276
+ numtimepoints=np.shape(outcorrarray)[1],
3277
+ tr=riptidedelays[1] - riptidedelays[0],
3278
+ toffset=(riptidedelays[0]),
3279
+ )
3280
+ else:
3281
+ theheader = theinputdata.copyheader(
3282
+ numtimepoints=np.shape(outcorrarray)[1],
3283
+ tr=corrtr,
3284
+ toffset=(corrscale[corrorigin - lagmininpts]),
3285
+ )
3286
+
3665
3287
  if (
3666
3288
  optiondict["savecorrout"]
3667
3289
  or (optiondict["outputlevel"] != "min")