Repository navigation
Expand file tree
/
Copy pathfmrisim.py
More file actions
1590 lines (1174 loc) · 49.3 KB
/
Copy pathfmrisim.py
File metadata and controls
1590 lines (1174 loc) · 49.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2016 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""fMRI Simulator
Simulate fMRI data for a single subject.
This code provides a set of functions necessary to produce realistic
simulations of neural data.
Steps:
generate_signal
Specify the volume (or volumes) which represent the signal in the neural data.
generate_stimfunction
Create a function to describe the stimulus onsets/durations
export_stimfunction:
Generate a three column timing file that can be used with software like FSL
double_gamma_hrf
Convolve the stimulus function with the HRF to model when events are expected.
apply_signal
Combine the volume and the HRF
calc_noise
Estimate the noise properties of a given volume
generate_noise
Create the noise for this run. This creates temporal, task and white noise.
Various parameters can be tuned depending on need
mask_brain
Mask the volume to look like a volume. Based on MNI standard space
plot_brain
Show the brain as it unfolds over time with a given opacity.
Authors: Cameron Ellis (Princeton) 2016
"""
import logging
from itertools import product
import nitime.algorithms.autoregressive as ar
import math
import numpy as np
from pkg_resources import resource_stream
from scipy import stats
import scipy.ndimage as ndimage
__all__ = [
"generate_signal",
"generate_stimfunction",
"export_stimfunction",
"double_gamma_hrf",
"apply_signal",
"calc_noise",
"generate_noise",
"mask_brain",
"plot_brain",
]
logger = logging.getLogger(__name__)
def _generate_feature(feature_type,
feature_size,
signal_magnitude,
thickness=1):
"""Generate features corresponding to signal
Generate signal in specific regions of the brain with for a single
volume. This will then be convolved with the HRF across time
Parameters
----------
feature_type : str
What feature_type of signal is being inserted? Options are cube,
loop, cavity, sphere.
feature_size : int
How big is the signal?
signal_magnitude : float
Set the signal size, a value of 1 means the signal is one standard
deviation of the noise
thickness : int
How thick is the surface of the loop/cavity
Returns
----------
3 dimensional array
The volume representing the signal to be outputed
"""
# If the size is equal to or less than 2 then all features are the same
if feature_size <= 2:
feature_type = 'cube'
# What kind of signal is it?
if feature_type == 'cube':
# Preset the size of the signal
signal = np.ones(np.power(feature_size, 3))
# Reorganize the signal into a 3d matrix
signal = signal.reshape([feature_size,
feature_size,
feature_size])
elif feature_type == 'loop':
# First make a cube of zeros
signal = np.zeros(np.power(feature_size,
3)).reshape([feature_size,
feature_size,
feature_size])
# Make a mesh grid of the space
seq = np.linspace(0, feature_size - 1,
feature_size)
xx, yy = np.meshgrid(seq, seq)
# Make a disk corresponding to the whole mesh grid
xxmesh = (xx - ((feature_size - 1) / 2)) ** 2
yymesh = (yy - ((feature_size - 1) / 2)) ** 2
disk = xxmesh + yymesh
# What are the limits of the rings being made
outer_lim = disk[int((feature_size - 1) / 2), 0]
inner_lim = disk[int((feature_size - 1) / 2), thickness]
# What is the outer disk
outer = disk <= outer_lim
# What is the inner disk
inner = disk <= inner_lim
# Subtract the two disks to get a loop
loop = outer != inner
# If there is complete overlap then make the signal just the
# outer one
if np.all(loop is False):
loop = outer
# store the loop
signal[0:feature_size, 0:feature_size, int(np.round(feature_size /
2))] = loop
elif feature_type == 'sphere' or feature_type == 'cavity':
# Make a mesh grid of the space
seq = np.linspace(0, feature_size - 1,
feature_size)
xx, yy, zz = np.meshgrid(seq, seq, seq)
# Make a disk corresponding to the whole mesh grid
signal = ((xx - ((feature_size - 1) / 2)) ** 2 +
(yy - ((feature_size - 1) / 2)) ** 2 +
(zz - ((feature_size - 1) / 2)) ** 2)
# What are the limits of the rings being made
outer_lim = signal[int((feature_size - 1) / 2), int((feature_size -
1) / 2), 0]
inner_lim = signal[int((feature_size - 1) / 2), int((feature_size -
1) / 2),
thickness]
# Is the signal a sphere or a cavity?
if feature_type == 'sphere':
signal = signal <= outer_lim
else:
# Get the inner and outer sphere
outer = signal <= outer_lim
inner = signal <= inner_lim
# Subtract the two disks to get a loop
signal = outer != inner
# If there is complete overlap then make the signal just the
# outer one
if np.all(signal is False):
signal = outer
# Assign the signal magnitude
signal = signal * signal_magnitude
# Return the signal
return signal
def _insert_idxs(feature_centre, feature_size, dimensions):
"""Returns the indexes of where to put the signal into Volume_Static
Parameters
----------
feature_centre : list, int
List of coordinates for the centre location of the signal
feature_size : list, int
How big is the signal.
dimensions : 3 length array, int
What are the dimensions of the volume you wish to create
Returns
----------
x_idxs : tuple
The x coordinates of where the signal is to be inserted
y_idxs : tuple
The y coordinates of where the signal is to be inserted
z_idxs : tuple
The z coordinates of where the signal is to be inserted
"""
# Set up the indexes within which to insert the signal
x_idx = [int(feature_centre[0] - (feature_size / 2)) + 1,
int(feature_centre[0] - (feature_size / 2) +
feature_size) + 1]
y_idx = [int(feature_centre[1] - (feature_size / 2)) + 1,
int(feature_centre[1] - (feature_size / 2) +
feature_size) + 1]
z_idx = [int(feature_centre[2] - (feature_size / 2)) + 1,
int(feature_centre[2] - (feature_size / 2) +
feature_size) + 1]
# Check for out of bounds
# Min Boundary
if 0 > x_idx[0]:
x_idx[0] = 0
if 0 > y_idx[0]:
y_idx[0] = 0
if 0 > z_idx[0]:
z_idx[0] = 0
# Max Boundary
if dimensions[0] < x_idx[1]:
x_idx[1] = dimensions[0]
if dimensions[1] < y_idx[1]:
y_idx[1] = dimensions[1]
if dimensions[2] < z_idx[1]:
z_idx[1] = dimensions[2]
# Return the idxs for data
return x_idx, y_idx, z_idx
def generate_signal(dimensions,
feature_coordinates,
feature_size,
feature_type,
signal_magnitude=[1],
signal_constant=1,
):
"""Generate volume containing signal
Generate signal in specific regions of the brain with for a single
volume. This will then be convolved with the HRF across time
Parameters
----------
dimensions : 3 length array, int
What are the dimensions of the volume you wish to create
feature_coordinates : multidimensional array, int
What are the feature_coordinates of the signal being created.
Be aware of clipping: features far from the centre of the
brain will be clipped. If you wish to have multiple features
then list these as an features x 3 array. To create a signal of
a specific shape then supply all the individual
feature_coordinates and set the feature_size to 1.
feature_size : list, int
How big is the signal. If m=1 then only one value is accepted,
if m>1 then either one value must be supplied or m values
feature_type : list, string
What feature_type of signal is being inserted? Options are cube,
loop, cavity, sphere. If features = 1 then
only one value is accepted, if features > 1 then either one value
must be supplied or m values
signal_magnitude : list, float
What is the (average) magnitude of the signal being generated? A
value of 1 means that the signal is one standard deviation from the
noise
signal_constant : list, bool
Is the signal constant or is it a random pattern (with the same
average magnitude)
Returns
----------
volume_static : 3 dimensional array, float
Creates a single volume containing the signal
"""
# Preset the volume
volume_static = np.zeros(dimensions)
feature_quantity = round(feature_coordinates.shape[0])
# If there is only one feature_size value then make sure to duplicate it
# for all signals
if len(feature_size) == 1:
feature_size = feature_size * feature_quantity
# Do the same for feature_type
if len(feature_type) == 1:
feature_type = feature_type * feature_quantity
if len(signal_magnitude) == 1:
signal_magnitude = signal_magnitude * feature_quantity
# Iterate through the signals and insert in the data
for signal_counter in list(range(0, feature_quantity)):
# What is the centre of this signal
if len(feature_size) > 1:
feature_centre = np.asarray(feature_coordinates[signal_counter, ])
else:
feature_centre = np.asarray(feature_coordinates)[0]
# Generate the feature to be inserted in the volume
signal = _generate_feature(feature_type[signal_counter],
feature_size[signal_counter],
signal_magnitude[signal_counter],
)
# If the signal is a random noise pattern then multiply these ones by
# a noise mask
if signal_constant == 0:
signal = signal * np.random.random([feature_size[signal_counter],
feature_size[signal_counter],
feature_size[signal_counter]])
# Pull out the idxs for where to insert the data
x_idx, y_idx, z_idx = _insert_idxs(feature_centre,
feature_size[signal_counter],
dimensions)
# Insert the signal into the Volume
volume_static[x_idx[0]:x_idx[1], y_idx[0]:y_idx[1], z_idx[0]:z_idx[
1]] = signal
return volume_static
def generate_stimfunction(onsets,
event_durations,
total_time,
weights=[1],
timing_file=None,
):
"""Return the function for the onset of events
When do stimuli onset, how long for and to what extent should you
resolve the fMRI time course. There are two ways to create this, either
by supplying onset, duration and weight information or by supplying a
timing file (in the three column format)
Parameters
----------
onsets : list, int
What are the timestamps for when an event you want to generate
onsets?
event_durations : list, int
What are the durations of the events you want to generate? If
there is only one value then this will be assigned to all onsets
total_time : int
How long is the experiment in total.
weights : list, float
How large is the box car for each of the onsets. If there is
only one value then this will be assigned to all onsets
timing_file : string
The filename (with path) to a three column timing file (FSL) to
make the events. Still requires tr_duration and total_time
Returns
----------
Iterable[float]
The time course of stimulus related activation
"""
# If the timing file is supplied then use this to acquire the
if timing_file is not None:
# Read in text file line by line
with open(timing_file) as f:
text = f.readlines() # Pull out file as a an array
# Preset
onsets = list()
event_durations = list()
weights = list()
# Pull out the onsets, weights and durations, set as a float
for line in text:
onset, duration, weight = line.strip().split()
onsets.append(float(onset))
event_durations.append(float(duration))
weights.append(float(weight))
# If only one duration is supplied then duplicate it for the length of
# the onset variable
if len(event_durations) == 1:
event_durations = event_durations * len(onsets)
if len(weights) == 1:
weights = weights * len(onsets)
# How many elements per second are you modeling
temporal_resolution = 1000
# Generate the time course as empty, each element is a millisecond
stimfunction = [0] * round(total_time * temporal_resolution)
# Cycle through the onsets
for onset_counter in list(range(len(onsets))):
# Adjust for the resolution
onset_idx = int(np.floor(onsets[onset_counter] * temporal_resolution))
# Adjust for the resolution
offset_idx = int(np.floor((onsets[onset_counter] + event_durations[
onset_counter])) * temporal_resolution)
# For the appropriate number of indexes and duration, make this value 1
idx_n = round(event_durations[onset_counter] * temporal_resolution)
stimfunction[onset_idx:offset_idx] = [weights[onset_counter]] * idx_n
# Shorten the data if it's too long
if len(stimfunction) > total_time * temporal_resolution:
stimfunction = stimfunction[0:int(total_time * temporal_resolution)]
return stimfunction
def export_stimfunction(stimfunction,
filename,
):
""" Output a tab separated timing file
This produces a three column tab separated text file, with the three
columns representing onset time, event duration and weight, respectively
Useful if you want to run the simulated data through FEAT analyses
Parameters
----------
stimfunction : list
The stimulus function describing the time course of events
filename : str
The name of the three column text file to be output
"""
# Iterate through the stim function
stim_counter = 0
event_counter = 0
while stim_counter < len(stimfunction):
# Is it an event?
if stimfunction[stim_counter] != 0:
# When did the event start?
event_onset = str(stim_counter / 1000)
# The weight of the stimulus
weight = str(stimfunction[stim_counter])
# Reset
event_duration = 0
# Is the event still ongoing?
while stimfunction[stim_counter] != 0 & stim_counter <= len(
stimfunction):
# Add one millisecond to each duration
event_duration = event_duration + 1
# Increment
stim_counter = stim_counter + 1
# How long was the event in seconds
event_duration = str(event_duration / 1000)
# Append this row to the data file
with open(filename, "a") as file:
file.write(event_onset + '\t' + event_duration + '\t' +
weight + '\n')
# Increment the number of events
event_counter = event_counter + 1
# Increment
stim_counter = stim_counter + 1
def double_gamma_hrf(stimfunction,
tr_duration,
response_delay=6,
undershoot_delay=12,
response_dispersion=0.9,
undershoot_dispersion=0.9,
response_scale=1,
undershoot_scale=0.035):
"""Return a double gamma HRF
Parameters
----------
stimfunction : list, bool
What is the time course of events to be modelled in this
experiment
response_delay : float
How many seconds until the peak of the HRF
undershoot_delay : float
How many seconds until the trough of the HRF
response_dispersion : float
How wide is the rising peak dispersion
undershoot_dispersion : float
How wide is the undershoot dispersion
response_scale : float
How big is the response relative to the peak
undershoot_scale :float
How big is the undershoot relative to the trough
Returns
----------
one dimensional array
The time course of the HRF convolved with the stimulus function
"""
hrf_length = 30 # How long is the HRF being created
hrf = [0] * hrf_length # How many seconds of the HRF will you model?
for hrf_counter in list(range(0, hrf_length - 1)):
# When is the peak of the two aspects of the HRF
response_peak = response_delay * response_dispersion
undershoot_peak = undershoot_delay * undershoot_dispersion
# Specify the elements of the HRF for both the response and undershoot
resp_pow = math.pow(hrf_counter / response_peak, response_delay)
resp_exp = math.exp(-(hrf_counter - response_peak) /
response_dispersion)
response_model = response_scale * resp_pow * resp_exp
undershoot_pow = math.pow(hrf_counter / undershoot_peak,
undershoot_delay)
undershoot_exp = math.exp(-(hrf_counter - undershoot_peak /
undershoot_dispersion))
undershoot_model = undershoot_scale * undershoot_pow * undershoot_exp
# For this time point find the value of the HRF
hrf[hrf_counter] = response_model - undershoot_model
# Decimate the stim function so that it only has one element per TR
stimfunction = stimfunction[0::tr_duration * 1000]
# Convolve the hrf that was created with the boxcar input
signal_function = np.convolve(stimfunction, hrf)
# Cut off the HRF
signal_function = signal_function[0:len(stimfunction)]
# Scale the function so that the peak response is 1
signal_function = signal_function / np.max(signal_function)
return signal_function
def apply_signal(signal_function,
volume_static,
):
"""Apply the convolution and stimfunction
Apply the convolution of the HRF and stimulus time course to the
volume.
Parameters
----------
signal_function : list, float
The one dimensional timecourse of the signal over time.
Found by convolving the HRF with the stimulus time course.
volume_static : multi dimensional array, float
Returns
----------
multidimensional array, float
Generates the spatial noise volume for these parameters """
# Preset volume
signal = np.ndarray([volume_static.shape[0], volume_static.shape[
1], volume_static.shape[2], len(signal_function)])
# Iterate through the brain, multiplying the volume by the HRF
for tr_counter in list(range(0, len(signal_function))):
signal[0:volume_static.shape[0],
0:volume_static.shape[1],
0:volume_static.shape[2],
tr_counter] = signal_function[tr_counter] * volume_static
return signal
def _calc_fwhm(volume,
mask,
):
""" Calculate the FWHM of a volume
Takes in a volume and mask and outputs the FWHM of each TR of this
volume for the non-masked voxels
Parameters
----------
volume : multidimensional array
Functional data to have the FWHM measured. Can be 3d or 4d data
mask : 4 dimensional array
A mask of the voxels to have the FWHM measured from
Returns
-------
float, list
Returns the FWHM of each TR """
# What are the dimensions of the volume
dimensions = volume.shape
# Identify the number of TRs
if len(dimensions) == 3:
trs = 1
else:
trs = dimensions[3]
dimensions = dimensions[0:3]
volume_all = volume # Store for later
# Preset size
fwhm = np.zeros(trs)
# Iterate through the TRs, creating a FWHM for each TR
for tr_counter in list(range(0, trs)):
# Preset
sum_sq_der = [0.0, 0.0, 0.0]
countSqDer = [0, 0, 0]
# If there is more than one TR, just pull out that volume
if trs > 1:
volume = volume_all[:, :, :, tr_counter]
# Pull out all the voxel coordinates
coordinates = list(product(range(dimensions[0]),
range(dimensions[1]),
range(dimensions[2])))
# Find the sum of squared error for the non-masked voxels in the brain
for i in list(range(len(coordinates))):
# Pull out this coordinate
x, y, z = coordinates[i]
# Is this within the mask?
if mask[x, y, z, tr_counter] > 0:
# For each xyz dimension calculate the squared
# difference of this voxel and the next
if x < dimensions[0] - 1 and mask[x + 1, y, z,
tr_counter] > 0:
temp = (volume[x, y, z] - volume[x + 1, y, z]) ** 2
sum_sq_der[0] += temp
countSqDer[0] += + 1
if y < dimensions[1] - 1 and mask[x, y + 1, z,
tr_counter] > 0:
temp = (volume[x, y, z] - volume[x, y + 1, z]) ** 2
sum_sq_der[1] += temp
countSqDer[1] += + 1
if z < dimensions[2] - 1 and mask[x, y, z + 1,
tr_counter] > 0:
temp = (volume[x, y, z] - volume[x, y, z + 1]) ** 2
sum_sq_der[2] += temp
countSqDer[2] += 1
# What is the FWHM for each dimension
fwhm3 = np.sqrt(np.divide(4 * np.log(2), np.divide(sum_sq_der,
countSqDer)))
fwhm[tr_counter] = np.prod(fwhm3) ** (1 / 3) # Calculate the average
return fwhm
def _calc_snr(volume,
mask,
):
""" Calculate the SNR of a volume
This takes the middle of the volume and averages the signal within the
brain and compares to the std in the voxels outside the brain.
Parameters
----------
volume : 4d array, float
Take a volume time series to extract the middle slice from the middle TR
mask : 4d array, float
A mask the same size as the volume, specifying the mask (values=0 -> 1)
Returns
-------
float
The snr of the volume (how much greater in activity the brain is from
the background)
"""
# What are the midpoints to be extracted
mid_x_idx = int(np.ceil(volume.shape[0] / 2))
mid_tr_idx = int(np.ceil(volume.shape[3] / 2))
# Pull out the slices
slice_volume = volume[mid_x_idx, :, :, mid_tr_idx]
slice_mask = mask[mid_x_idx, :, :, mid_tr_idx]
# Divide by the mask (if the middle slice was low in grey matter mass
# then you would have a lower mean signal by default)
mean_signal = (slice_volume[slice_mask > 0] / slice_mask[slice_mask >
0]).mean()
# What is the overall noise
overall_noise = float(slice_volume[slice_mask == 0].std())
# Calculate snr
snr = mean_signal / overall_noise
# Convert from memmap
snr = float(snr)
return overall_noise, snr
def _calc_autoregression(volume,
mask,
ar_order=2,
):
""" Calculate the autoregressive sigma of the data.
Parameters
----------
volume : 4d masarray, float
Input data to be calculate the autoregression
mask : 4d array, float
What voxels of the input are within the brain
ar_order : int
What order of the autoregression do you want to pull out
Returns
-------
float
A sigma of the autoregression in the data
"""
# Calculate the time course
timecourse = np.mean(volume[mask[:, :, :, 0] > 0], 0)
# Pull out the AR values (depends on order)
auto_reg_sigma = ar.AR_est_YW(timecourse, ar_order)[0][1]
# What is the size of the change in the time course
drift_sigma = timecourse.std().tolist()
return auto_reg_sigma, drift_sigma
def calc_noise(volume,
mask=None,
):
""" Calculates the noise properties of the volume supplied.
This estimates what noise properties the volume has. For instance it
determines the spatial smoothness, the autoregressive noise, system
noise etc. Read the doc string for generate_noise to understand how
these different types of noise interact.
Parameters
----------
volume : 4d numpy array, float
Take in a functional volume (either the file name or the numpy
array) to be used to estimate the noise properties of this
mask : 4d numpy array, float
The mask to be used, the same size as the volume
Returns
-------
dict
Return a dictionary of the calculated noise parameters of the provided
dataset
"""
# Preset
noise_dict = {}
# Create the mask
if mask is None:
mask = np.ones(volume.shape)
# Since you are deriving the 'true' values then you want your noise to
# be set to that level
# Calculate the overall noise and SNR of the volume
noise_dict['overall'], noise_dict['snr'] = _calc_snr(volume, mask)
# Calculate the fwhm of the data and use the average as your spatial sigma
noise_dict['spatial_sigma'] = _calc_fwhm(volume, mask).mean()
# Calculate the autoregressive and drift noise
auto_reg_sigma, drift_sigma = _calc_autoregression(volume, mask)
noise_dict['auto_reg_sigma'] = auto_reg_sigma / noise_dict['overall']
noise_dict['drift_sigma'] = drift_sigma / noise_dict['overall']
# Calculate the white noise
noise_dict['system_sigma'] = float(volume[mask == 0].std() / noise_dict[
'overall'])
# Return the noise dictionary
return noise_dict
def _generate_noise_system(dimensions_tr,
):
"""Generate the scanner noise
Generate the noise that is typical of a scanner. This is comprised
of two types of noise, Rician and Gaussian
Parameters
----------
dimensions_tr : n length array, int
What are the dimensions of the volume you wish to insert
noise into. This can be a volume of any size
Returns
----------
system_noise : multidimensional array, float
Create a volume with system noise
"""
# Generate the Rician noise
noise_rician = stats.rice.rvs(1, 1, size=dimensions_tr)
# Apply the gaussian noise
noise_gaussian = np.random.normal(0, 1, size=dimensions_tr)
# Combine these two noise types
noise_system = noise_rician + noise_gaussian
# Normalize
noise_system = stats.zscore(noise_system)
return noise_system
def _generate_noise_temporal_task(stimfunction_tr,
motion_noise='gaussian',
):
"""Generate the signal dependent noise
This noise depends on things like the signal or the timing of the
experiment.
Parameters
----------
stimfunction_tr : 1 Dimensional array
This is the timecourse of the stimuli in this experiment,
each element represents a TR
motion_noise : str
What type of noise will you generate? Can be gaussian or rician
Returns
----------
one dimensional array, float
Generates the temporal task noise timecourse
"""
# Make the noise to be added
if motion_noise == 'gaussian':
noise = stimfunction_tr * np.random.normal(0, 1, size=len(
stimfunction_tr))
elif motion_noise == 'rician':
noise = stimfunction_tr * stats.rice.rvs(0, 1, size=len(
stimfunction_tr))
noise_task = stimfunction_tr + noise
# Normalize
noise_task = stats.zscore(noise_task)
return noise_task
def _generate_noise_temporal_drift(trs,
tr_duration,
):
"""Generate the drift noise
According to AFNI (https://afni.nimh.nih.gov/pub/dist/doc/
program_help/3dDeconvolve.html) the appropriate order of the
polynomial to fit for temporal drift is calculated as follows
Parameters
----------
trs : int
How many TRs are there
tr_duration : float
How long is each TR
Returns
----------
one dimensional array, float
Generates the autoregression noise timecourse
"""
# What time points are sampled by a TR?
timepoints = list(range(0, trs * tr_duration))[::tr_duration]
# Calculate the coefficients of the drift for a given function
degree = round(trs * tr_duration / 150) + 1
coefficients = np.random.normal(0, 1, size=degree)
# What are the values of this drift
noise_drift = np.polyval(coefficients, timepoints)