Beispiel #1
0
def test_generate_stimfunction():

    # Inputs for generate_stimfunction
    onsets = [10, 30, 50, 70, 90]
    event_durations = [6]
    tr_duration = 2
    duration = 100

    # Create the time course for the signal to be generated
    stimfunction = sim.generate_stimfunction(
        onsets=onsets,
        event_durations=event_durations,
        total_time=duration,
    )

    assert stimfunction.shape[0] == duration * 100, "stimfunc incorrect length"
    eventNumber = np.sum(event_durations * len(onsets)) * 100
    assert np.sum(stimfunction) == eventNumber, "Event number"

    # Create the signal function
    signal_function = sim.convolve_hrf(
        stimfunction=stimfunction,
        tr_duration=tr_duration,
    )

    stim_dur = stimfunction.shape[0] / (tr_duration * 100)
    assert signal_function.shape[0] == stim_dur, "The length did not change"

    # Test
    onsets = [0]
    tr_duration = 1
    event_durations = [1]
    stimfunction = sim.generate_stimfunction(
        onsets=onsets,
        event_durations=event_durations,
        total_time=duration,
    )

    signal_function = sim.convolve_hrf(
        stimfunction=stimfunction,
        tr_duration=tr_duration,
    )

    max_response = np.where(signal_function != 0)[0].max()
    assert 25 < max_response <= 30, "HRF has the incorrect length"
    assert np.sum(signal_function < 0) > 0, "No values below zero"
Beispiel #2
0
def test_generate_stimfunction():

    # Inputs for generate_stimfunction
    onsets = [10, 30, 50, 70, 90]
    event_durations = [6]
    tr_duration = 2
    duration = 100

    # Create the time course for the signal to be generated
    stimfunction = sim.generate_stimfunction(onsets=onsets,
                                             event_durations=event_durations,
                                             total_time=duration,
                                             )

    assert stimfunction.shape[0] == duration * 100, "stimfunc incorrect length"
    eventNumber = np.sum(event_durations * len(onsets)) * 100
    assert np.sum(stimfunction) == eventNumber, "Event number"

    # Create the signal function
    signal_function = sim.convolve_hrf(stimfunction=stimfunction,
                                       tr_duration=tr_duration,
                                       )

    stim_dur = stimfunction.shape[0] / (tr_duration * 100)
    assert signal_function.shape[0] == stim_dur, "The length did not change"

    # Test
    onsets = [0]
    tr_duration = 1
    event_durations = [1]
    stimfunction = sim.generate_stimfunction(onsets=onsets,
                                             event_durations=event_durations,
                                             total_time=duration,
                                             )

    signal_function = sim.convolve_hrf(stimfunction=stimfunction,
                                       tr_duration=tr_duration,
                                       )

    max_response = np.where(signal_function != 0)[0].max()
    assert 25 < max_response <= 30, "HRF has the incorrect length"
    assert np.sum(signal_function < 0) > 0, "No values below zero"
Beispiel #3
0
def test_apply_signal():

    dimensions = np.array([10, 10, 10])  # What is the size of the brain
    feature_size = [2]
    feature_type = ['cube']
    feature_coordinates = np.array([[5, 5, 5]])
    signal_magnitude = [30]

    # Generate a volume representing the location and quality of the signal
    volume = sim.generate_signal(
        dimensions=dimensions,
        feature_coordinates=feature_coordinates,
        feature_type=feature_type,
        feature_size=feature_size,
        signal_magnitude=signal_magnitude,
    )

    # Inputs for generate_stimfunction
    onsets = [10, 30, 50, 70, 90]
    event_durations = [6]
    tr_duration = 2
    duration = 100

    # Create the time course for the signal to be generated
    stimfunction = sim.generate_stimfunction(
        onsets=onsets,
        event_durations=event_durations,
        total_time=duration,
    )

    signal_function = sim.convolve_hrf(
        stimfunction=stimfunction,
        tr_duration=tr_duration,
    )

    # Convolve the HRF with the stimulus sequence
    signal = sim.apply_signal(
        signal_function=signal_function,
        volume_signal=volume,
    )

    assert signal.shape == (dimensions[0], dimensions[1], dimensions[2],
                            duration / tr_duration), "The output is the " \
                                                     "wrong size"

    signal = sim.apply_signal(
        signal_function=stimfunction,
        volume_signal=volume,
    )

    assert np.any(signal == signal_magnitude), "The stimfunction is not binary"
Beispiel #4
0
def test_apply_signal():

    dimensions = np.array([10, 10, 10])  # What is the size of the brain
    feature_size = [2]
    feature_type = ['cube']
    feature_coordinates = np.array(
        [[5, 5, 5]])
    signal_magnitude = [30]

    # Generate a volume representing the location and quality of the signal
    volume = sim.generate_signal(dimensions=dimensions,
                                 feature_coordinates=feature_coordinates,
                                 feature_type=feature_type,
                                 feature_size=feature_size,
                                 signal_magnitude=signal_magnitude,
                                 )

    # Inputs for generate_stimfunction
    onsets = [10, 30, 50, 70, 90]
    event_durations = [6]
    tr_duration = 2
    duration = 100

    # Create the time course for the signal to be generated
    stimfunction = sim.generate_stimfunction(onsets=onsets,
                                             event_durations=event_durations,
                                             total_time=duration,
                                             )

    signal_function = sim.convolve_hrf(stimfunction=stimfunction,
                                       tr_duration=tr_duration,
                                       )

    # Convolve the HRF with the stimulus sequence
    signal = sim.apply_signal(signal_function=signal_function,
                              volume_signal=volume,
                              )

    assert signal.shape == (dimensions[0], dimensions[1], dimensions[2],
                            duration / tr_duration), "The output is the " \
                                                     "wrong size"

    signal = sim.apply_signal(signal_function=stimfunction,
                              volume_signal=volume,
                              )

    assert np.any(signal == signal_magnitude), "The stimfunction is not binary"
Beispiel #5
0
def test_generate_noise():

    dimensions = np.array([10, 10, 10])  # What is the size of the brain
    feature_size = [2]
    feature_type = ['cube']
    feature_coordinates = np.array(
        [[5, 5, 5]])
    signal_magnitude = [1]

    # Generate a volume representing the location and quality of the signal
    volume = sim.generate_signal(dimensions=dimensions,
                                 feature_coordinates=feature_coordinates,
                                 feature_type=feature_type,
                                 feature_size=feature_size,
                                 signal_magnitude=signal_magnitude,
                                 )

    # Inputs for generate_stimfunction
    onsets = [10, 30, 50, 70, 90]
    event_durations = [6]
    tr_duration = 2
    duration = 200

    # Create the time course for the signal to be generated
    stimfunction = sim.generate_stimfunction(onsets=onsets,
                                             event_durations=event_durations,
                                             total_time=duration,
                                             )

    signal_function = sim.convolve_hrf(stimfunction=stimfunction,
                                       tr_duration=tr_duration,
                                       )

    # Convolve the HRF with the stimulus sequence
    signal = sim.apply_signal(signal_function=signal_function,
                              volume_signal=volume,
                              )

    # Generate the mask of the signal
    mask, template = sim.mask_brain(signal, mask_threshold=0.1)

    assert min(mask[mask > 0]) > 0.1, "Mask thresholding did not work"
    assert len(np.unique(template) > 2), "Template creation did not work"

    stimfunction_tr = stimfunction[::int(tr_duration * 100)]
    # Create the noise volumes (using the default parameters)
    noise = sim.generate_noise(dimensions=dimensions,
                               stimfunction_tr=stimfunction_tr,
                               tr_duration=tr_duration,
                               template=template,
                               mask=mask,
                               )

    assert signal.shape == noise.shape, "The dimensions of signal and noise " \
                                        "the same"

    assert np.std(signal) < np.std(noise), "Noise was not created"

    noise = sim.generate_noise(dimensions=dimensions,
                               stimfunction_tr=stimfunction_tr,
                               tr_duration=tr_duration,
                               template=template,
                               mask=mask,
                               noise_dict={'sfnr': 10000, 'snr': 10000},
                               )

    system_noise = np.std(noise[mask > 0], 1).mean()

    assert system_noise <= 0.1, "Noise strength could not be manipulated"
Beispiel #6
0
    pattern_A = np.random.rand(voxels_A).reshape((voxels_A, 1))
    pattern_B = np.random.rand(voxels_B).reshape((voxels_B, 1))

    # Multiply each pattern by each voxel time course
    # Noise was added to the design matrix, to make the correlation pattern noise, so FCMA could be challenging.
    weights_A = np.tile(stimfunc_A, voxels_A) * pattern_A.T + np.random.normal(
        0, 1, size=np.tile(stimfunc_A, voxels_A).shape)
    weights_B = np.tile(stimfunc_B, voxels_B) * pattern_B.T + np.random.normal(
        0, 1, size=np.tile(stimfunc_B, voxels_B).shape)

    # Convolve the onsets with the HRF
    # TR less than feature is not good, but b/c this is simulated data, can ignore this concer.
    print('Creating signal time course')
    signal_func_A = sim.convolve_hrf(
        stimfunction=weights_A,
        tr_duration=trDuration,
        temporal_resolution=temporal_res,
        scale_function=1,
    )

    signal_func_B = sim.convolve_hrf(
        stimfunction=weights_B,
        tr_duration=trDuration,
        temporal_resolution=temporal_res,
        scale_function=1,
    )

    # Multiply the signal by the signal change
    signal_func_A = signal_func_A * signal_change  #+ signal_func_B * signal_change
    signal_func_B = signal_func_B * signal_change  #+ signal_func_A * signal_change

    # Combine the signal time course with the signal volume
Beispiel #7
0
def test_generate_stimfunction():

    # Inputs for generate_stimfunction
    onsets = [10, 30, 50, 70, 90]
    event_durations = [6]
    tr_duration = 2
    duration = 100

    # Create the time course for the signal to be generated
    stimfunction = sim.generate_stimfunction(
        onsets=onsets,
        event_durations=event_durations,
        total_time=duration,
    )

    assert stimfunction.shape[0] == duration * 100, "stimfunc incorrect length"
    eventNumber = np.sum(event_durations * len(onsets)) * 100
    assert np.sum(stimfunction) == eventNumber, "Event number"

    # Create the signal function
    signal_function = sim.convolve_hrf(
        stimfunction=stimfunction,
        tr_duration=tr_duration,
    )

    stim_dur = stimfunction.shape[0] / (tr_duration * 100)
    assert signal_function.shape[0] == stim_dur, "The length did not change"

    # Test
    onsets = [0]
    tr_duration = 1
    event_durations = [1]
    stimfunction = sim.generate_stimfunction(
        onsets=onsets,
        event_durations=event_durations,
        total_time=duration,
    )

    signal_function = sim.convolve_hrf(
        stimfunction=stimfunction,
        tr_duration=tr_duration,
    )

    max_response = np.where(signal_function != 0)[0].max()
    assert 25 < max_response <= 30, "HRF has the incorrect length"
    assert np.sum(signal_function < 0) > 0, "No values below zero"

    # Export a stimfunction
    sim.export_3_column(
        stimfunction,
        'temp.txt',
    )

    # Load in the stimfunction
    stimfunc_new = sim.generate_stimfunction(
        onsets=None,
        event_durations=None,
        total_time=duration,
        timing_file='temp.txt',
    )

    assert np.all(stimfunc_new == stimfunction), "Export/import failed"

    # Break the timing precision of the generation
    stimfunc_new = sim.generate_stimfunction(
        onsets=None,
        event_durations=None,
        total_time=duration,
        timing_file='temp.txt',
        temporal_resolution=0.5,
    )

    assert stimfunc_new.sum() == 0, "Temporal resolution not working right"

    # Set the duration to be too short so you should get an error
    onsets = [10, 30, 50, 70, 90]
    event_durations = [5]
    with pytest.raises(ValueError):
        sim.generate_stimfunction(
            onsets=onsets,
            event_durations=event_durations,
            total_time=89,
        )

    # Clip the event offset
    stimfunc_new = sim.generate_stimfunction(
        onsets=onsets,
        event_durations=event_durations,
        total_time=95,
    )
    assert stimfunc_new[-1] == 1, 'Event offset was not clipped'

    # Test exporting a group of participants to an epoch file
    cond_a = sim.generate_stimfunction(
        onsets=onsets,
        event_durations=event_durations,
        total_time=110,
    )

    cond_b = sim.generate_stimfunction(
        onsets=[x + 5 for x in onsets],
        event_durations=event_durations,
        total_time=110,
    )

    stimfunction_group = [np.hstack((cond_a, cond_b))] * 2
    sim.export_epoch_file(
        stimfunction_group,
        'temp.txt',
        tr_duration,
    )

    # Check that convolve throws a warning when the shape is wrong
    sim.convolve_hrf(
        stimfunction=np.hstack((cond_a, cond_b)).T,
        tr_duration=tr_duration,
        temporal_resolution=1,
    )
Beispiel #8
0
    event_durations=event_durations,
    total_time=duration,
    temporal_resolution=temporal_res,
)

stimfunction_B = sim.generate_stimfunction(
    onsets=onsets_B,
    event_durations=event_durations,
    total_time=duration,
    temporal_resolution=temporal_res,
)

# Convolve the HRF with the stimulus sequence
signal_function_A = sim.convolve_hrf(
    stimfunction=stimfunction_A,
    tr_duration=tr_duration,
    temporal_resolution=temporal_res,
)

signal_function_B = sim.convolve_hrf(
    stimfunction=stimfunction_B,
    tr_duration=tr_duration,
    temporal_resolution=temporal_res,
)

# Multiply the HRF timecourse with the signal
signal_A = sim.apply_signal(
    signal_function=signal_function_A,
    volume_signal=volume_signal_A,
)
def generate_ROIs(ROI_file, stimfunc, noise, scale_percentage, data_dict):
    # Create the signal in the ROI as specified.

    print('Loading', ROI_file)

    nii = nibabel.load(ROI_file)
    ROI = nii.get_data()

    # Find all the indices that contain signal
    idx_list = np.where(ROI == 1)

    idxs = np.zeros([len(idx_list[0]), 3])
    for idx_counter in list(range(0, len(idx_list[0]))):
        idxs[idx_counter, 0] = int(idx_list[0][idx_counter])
        idxs[idx_counter, 1] = int(idx_list[1][idx_counter])
        idxs[idx_counter, 2] = int(idx_list[2][idx_counter])

    idxs = idxs.astype('int8')

    # How many voxels per ROI
    voxels = int(ROI.sum())

    # Create a pattern of activity across the two voxels
    if data_dict['multivariate_pattern'] is True:
        pattern = np.random.rand(voxels).reshape((voxels, 1))
    else:  # Just make a univariate increase
        pattern = np.tile(1, voxels).reshape((voxels, 1))

    # Multiply each pattern by each voxel time course
    weights = np.tile(stimfunc, voxels) * pattern.T

    # Convolve the onsets with the HRF
    temporal_res = 1 / data_dict['trDuration']
    signal_func = sim.convolve_hrf(
        stimfunction=weights,
        tr_duration=data_dict['trDuration'],
        temporal_resolution=temporal_res,
        scale_function=1,
    )

    # Change the type of noise
    noise = noise.astype('double')

    # Create a noise function (same voxels for signal function as for noise)
    noise_function = noise[idxs[:, 0], idxs[:, 1], idxs[:, 2], :].T

    # Compute the signal magnitude for the data
    sf_scaled = sim.compute_signal_change(
        signal_function=signal_func,
        noise_function=noise_function,
        noise_dict=data_dict['noise_dict'],
        magnitude=[scale_percentage],
        method='PSC',
    )

    # Combine the signal time course with the signal volume
    signal = sim.apply_signal(
        sf_scaled,
        ROI,
    )

    # Return signal needed
    return signal
Beispiel #10
0
def test_generate_stimfunction():

    # Inputs for generate_stimfunction
    onsets = [10, 30, 50, 70, 90]
    event_durations = [6]
    tr_duration = 2
    duration = 100

    # Create the time course for the signal to be generated
    stimfunction = sim.generate_stimfunction(onsets=onsets,
                                             event_durations=event_durations,
                                             total_time=duration,
                                             )

    assert stimfunction.shape[0] == duration * 100, "stimfunc incorrect length"
    eventNumber = np.sum(event_durations * len(onsets)) * 100
    assert np.sum(stimfunction) == eventNumber, "Event number"

    # Create the signal function
    signal_function = sim.convolve_hrf(stimfunction=stimfunction,
                                       tr_duration=tr_duration,
                                       )

    stim_dur = stimfunction.shape[0] / (tr_duration * 100)
    assert signal_function.shape[0] == stim_dur, "The length did not change"

    # Test
    onsets = [0]
    tr_duration = 1
    event_durations = [1]
    stimfunction = sim.generate_stimfunction(onsets=onsets,
                                             event_durations=event_durations,
                                             total_time=duration,
                                             )

    signal_function = sim.convolve_hrf(stimfunction=stimfunction,
                                       tr_duration=tr_duration,
                                       )

    max_response = np.where(signal_function != 0)[0].max()
    assert 25 < max_response <= 30, "HRF has the incorrect length"
    assert np.sum(signal_function < 0) > 0, "No values below zero"

    # Export a stimfunction
    sim.export_3_column(stimfunction,
                        'temp.txt',
                        )

    # Load in the stimfunction
    stimfunc_new = sim.generate_stimfunction(onsets=None,
                                             event_durations=None,
                                             total_time=duration,
                                             timing_file='temp.txt',
                                             )

    assert np.all(stimfunc_new == stimfunction), "Export/import failed"

    # Break the timing precision of the generation
    stimfunc_new = sim.generate_stimfunction(onsets=None,
                                             event_durations=None,
                                             total_time=duration,
                                             timing_file='temp.txt',
                                             temporal_resolution=0.5,
                                             )

    assert stimfunc_new.sum() == 0, "Temporal resolution not working right"

    # Set the duration to be too short so you should get an error
    onsets = [10, 30, 50, 70, 90]
    event_durations = [5]
    with pytest.raises(ValueError):
        sim.generate_stimfunction(onsets=onsets,
                                  event_durations=event_durations,
                                  total_time=89,
                                  )

    # Clip the event offset
    stimfunc_new = sim.generate_stimfunction(onsets=onsets,
                                             event_durations=event_durations,
                                             total_time=95,
                                             )
    assert stimfunc_new[-1] == 1, 'Event offset was not clipped'

    # Test exporting a group of participants to an epoch file
    cond_a = sim.generate_stimfunction(onsets=onsets,
                                       event_durations=event_durations,
                                       total_time=110,
                                       )

    cond_b = sim.generate_stimfunction(onsets=[x + 5 for x in onsets],
                                       event_durations=event_durations,
                                       total_time=110,
                                       )

    stimfunction_group = [np.hstack((cond_a, cond_b))] * 2
    sim.export_epoch_file(stimfunction_group,
                          'temp.txt',
                          tr_duration,
                          )

    # Check that convolve throws a warning when the shape is wrong
    sim.convolve_hrf(stimfunction=np.hstack((cond_a, cond_b)).T,
                     tr_duration=tr_duration,
                     temporal_resolution=1,
                     )
Beispiel #11
0
def test_generate_noise():

    dimensions = np.array([10, 10, 10])  # What is the size of the brain
    feature_size = [2]
    feature_type = ['cube']
    feature_coordinates = np.array(
        [[5, 5, 5]])
    signal_magnitude = [1]

    # Generate a volume representing the location and quality of the signal
    volume = sim.generate_signal(dimensions=dimensions,
                                 feature_coordinates=feature_coordinates,
                                 feature_type=feature_type,
                                 feature_size=feature_size,
                                 signal_magnitude=signal_magnitude,
                                 )

    # Inputs for generate_stimfunction
    onsets = [10, 30, 50, 70, 90]
    event_durations = [6]
    tr_duration = 2
    duration = 200

    # Create the time course for the signal to be generated
    stimfunction = sim.generate_stimfunction(onsets=onsets,
                                             event_durations=event_durations,
                                             total_time=duration,
                                             )

    signal_function = sim.convolve_hrf(stimfunction=stimfunction,
                                       tr_duration=tr_duration,
                                       )

    # Convolve the HRF with the stimulus sequence
    signal = sim.apply_signal(signal_function=signal_function,
                              volume_signal=volume,
                              )

    # Generate the mask of the signal
    mask, template = sim.mask_brain(signal,
                                    mask_self=None)

    assert min(mask[mask > 0]) > 0.1, "Mask thresholding did not work"
    assert len(np.unique(template) > 2), "Template creation did not work"

    stimfunction_tr = stimfunction[::int(tr_duration * 100)]

    # Create the noise volumes (using the default parameters)
    noise = sim.generate_noise(dimensions=dimensions,
                               stimfunction_tr=stimfunction_tr,
                               tr_duration=tr_duration,
                               template=template,
                               mask=mask,
                               iterations=[1, 0],
                               )

    assert signal.shape == noise.shape, "The dimensions of signal and noise " \
                                        "the same"

    noise_high = sim.generate_noise(dimensions=dimensions,
                                    stimfunction_tr=stimfunction_tr,
                                    tr_duration=tr_duration,
                                    template=template,
                                    mask=mask,
                                    noise_dict={'sfnr': 50, 'snr': 25},
                                    iterations=[1, 0],
                                    )

    noise_low = sim.generate_noise(dimensions=dimensions,
                                   stimfunction_tr=stimfunction_tr,
                                   tr_duration=tr_duration,
                                   template=template,
                                   mask=mask,
                                   noise_dict={'sfnr': 100, 'snr': 25},
                                   iterations=[1, 0],
                                   )

    system_high = np.std(noise_high[mask > 0], 1).mean()
    system_low = np.std(noise_low[mask > 0], 1).mean()

    assert system_low < system_high, "SFNR noise could not be manipulated"

    # Check that you check for the appropriate template values
    with pytest.raises(ValueError):
        sim.generate_noise(dimensions=dimensions,
                           stimfunction_tr=stimfunction_tr,
                           tr_duration=tr_duration,
                           template=template * 2,
                           mask=mask,
                           noise_dict={},
                           )

    # Check that iterations does what it should
    sim.generate_noise(dimensions=dimensions,
                       stimfunction_tr=stimfunction_tr,
                       tr_duration=tr_duration,
                       template=template,
                       mask=mask,
                       noise_dict={},
                       iterations=[0, 0],
                       )

    sim.generate_noise(dimensions=dimensions,
                       stimfunction_tr=stimfunction_tr,
                       tr_duration=tr_duration,
                       template=template,
                       mask=mask,
                       noise_dict={},
                       iterations=None,
                       )

    # Test drift noise
    trs = 1000
    period = 100
    drift = sim._generate_noise_temporal_drift(trs,
                                               tr_duration,
                                               'sine',
                                               period,
                                               )

    # Check that the max frequency is the appropriate frequency
    power = abs(np.fft.fft(drift))[1:trs // 2]
    freq = np.linspace(1, trs // 2 - 1, trs // 2 - 1) / trs
    period_freq = np.where(freq == 1 / (period // tr_duration))
    max_freq = np.argmax(power)

    assert period_freq == max_freq, 'Max frequency is not where it should be'

    # Do the same but now with cosine basis functions, answer should be close
    drift = sim._generate_noise_temporal_drift(trs,
                                               tr_duration,
                                               'discrete_cos',
                                               period,
                                               )

    # Check that the appropriate frequency is peaky (may not be the max)
    power = abs(np.fft.fft(drift))[1:trs // 2]
    freq = np.linspace(1, trs // 2 - 1, trs // 2 - 1) / trs
    period_freq = np.where(freq == 1 / (period // tr_duration))[0][0]

    assert power[period_freq] > power[period_freq + 1], 'Power is low'
    assert power[period_freq] > power[period_freq - 1], 'Power is low'

    # Check it gives a warning if the duration is too short
    drift = sim._generate_noise_temporal_drift(50,
                                               tr_duration,
                                               'discrete_cos',
                                               period,
                                               )

    # Test physiological noise (using unrealistic parameters so that it's easy)
    timepoints = list(np.linspace(0, (trs - 1) * tr_duration, trs))
    resp_freq = 0.2
    heart_freq = 1.17
    phys = sim._generate_noise_temporal_phys(timepoints,
                                             resp_freq,
                                             heart_freq,
                                             )

    # Check that the max frequency is the appropriate frequency
    power = abs(np.fft.fft(phys))[1:trs // 2]
    freq = np.linspace(1, trs // 2 - 1, trs // 2 - 1) / (trs * tr_duration)
    peaks = (power > (power.mean() + power.std()))  # Where are the peaks
    peak_freqs = freq[peaks]

    assert np.any(resp_freq == peak_freqs), 'Resp frequency not found'
    assert len(peak_freqs) == 2, 'Two peaks not found'

    # Test task noise
    sim._generate_noise_temporal_task(stimfunction_tr,
                                      motion_noise='gaussian',
                                      )
    sim._generate_noise_temporal_task(stimfunction_tr,
                                      motion_noise='rician',
                                      )

    # Test ARMA noise
    with pytest.raises(ValueError):
        noise_dict = {'fwhm': 4, 'auto_reg_rho': [1], 'ma_rho': [1, 1]}
        sim._generate_noise_temporal_autoregression(stimfunction_tr,
                                                    noise_dict,
                                                    dimensions,
                                                    mask,
                                                    )

    # Generate spatial noise
    vol = sim._generate_noise_spatial(np.array([10, 10, 10, trs]))
    assert len(vol.shape) == 3, 'Volume was not reshaped to ignore TRs'

    # Switch some of the noise types on
    noise_dict = dict(physiological_sigma=1, drift_sigma=1, task_sigma=1,
                      auto_reg_sigma=0)
    sim.generate_noise(dimensions=dimensions,
                       stimfunction_tr=stimfunction_tr,
                       tr_duration=tr_duration,
                       template=template,
                       mask=mask,
                       noise_dict=noise_dict,
                       iterations=[0, 0],
                       )
Beispiel #12
0
def test_apply_signal():

    dimensions = np.array([10, 10, 10])  # What is the size of the brain
    feature_size = [2]
    feature_type = ['cube']
    feature_coordinates = np.array(
        [[5, 5, 5]])
    signal_magnitude = [30]

    # Generate a volume representing the location and quality of the signal
    volume = sim.generate_signal(dimensions=dimensions,
                                 feature_coordinates=feature_coordinates,
                                 feature_type=feature_type,
                                 feature_size=feature_size,
                                 signal_magnitude=signal_magnitude,
                                 )

    # Inputs for generate_stimfunction
    onsets = [10, 30, 50, 70, 90]
    event_durations = [6]
    tr_duration = 2
    duration = 100

    # Create the time course for the signal to be generated
    stimfunction = sim.generate_stimfunction(onsets=onsets,
                                             event_durations=event_durations,
                                             total_time=duration,
                                             )

    signal_function = sim.convolve_hrf(stimfunction=stimfunction,
                                       tr_duration=tr_duration,
                                       )

    # Check that you can compute signal change appropriately
    # Preset a bunch of things
    stimfunction_tr = stimfunction[::int(tr_duration * 100)]
    mask, template = sim.mask_brain(dimensions, mask_self=False)
    noise_dict = sim._noise_dict_update({})
    noise = sim.generate_noise(dimensions=dimensions,
                               stimfunction_tr=stimfunction_tr,
                               tr_duration=tr_duration,
                               template=template,
                               mask=mask,
                               noise_dict=noise_dict,
                               iterations=[0, 0]
                               )
    coords = feature_coordinates[0]
    noise_function_a = noise[coords[0], coords[1], coords[2], :]
    noise_function_a = noise_function_a.reshape(duration // tr_duration, 1)

    noise_function_b = noise[coords[0] + 1, coords[1], coords[2], :]
    noise_function_b = noise_function_b.reshape(duration // tr_duration, 1)

    # Create the calibrated signal with PSC
    method = 'PSC'
    sig_a = sim.compute_signal_change(signal_function,
                                      noise_function_a,
                                      noise_dict,
                                      [0.5],
                                      method,
                                      )
    sig_b = sim.compute_signal_change(signal_function,
                                      noise_function_a,
                                      noise_dict,
                                      [1.0],
                                      method,
                                      )

    assert sig_b.max() / sig_a.max() == 2, 'PSC modulation failed'

    # Create the calibrated signal with SFNR
    method = 'SFNR'
    sig_a = sim.compute_signal_change(signal_function,
                                      noise_function_a,
                                      noise_dict,
                                      [0.5],
                                      method,
                                      )
    scaled_a = sig_a / (noise_function_a.mean() / noise_dict['sfnr'])
    sig_b = sim.compute_signal_change(signal_function,
                                      noise_function_b,
                                      noise_dict,
                                      [1.0],
                                      method,
                                      )
    scaled_b = sig_b / (noise_function_b.mean() / noise_dict['sfnr'])

    assert scaled_b.max() / scaled_a.max() == 2, 'SFNR modulation failed'

    # Create the calibrated signal with CNR_Amp/Noise-SD
    method = 'CNR_Amp/Noise-SD'
    sig_a = sim.compute_signal_change(signal_function,
                                      noise_function_a,
                                      noise_dict,
                                      [0.5],
                                      method,
                                      )
    scaled_a = sig_a / noise_function_a.std()
    sig_b = sim.compute_signal_change(signal_function,
                                      noise_function_b,
                                      noise_dict,
                                      [1.0],
                                      method,
                                      )
    scaled_b = sig_b / noise_function_b.std()

    assert scaled_b.max() / scaled_a.max() == 2, 'CNR_Amp modulation failed'

    # Create the calibrated signal with CNR_Amp/Noise-Var_dB
    method = 'CNR_Amp2/Noise-Var_dB'
    sig_a = sim.compute_signal_change(signal_function,
                                      noise_function_a,
                                      noise_dict,
                                      [0.5],
                                      method,
                                      )
    scaled_a = np.log(sig_a.max() / noise_function_a.std())
    sig_b = sim.compute_signal_change(signal_function,
                                      noise_function_b,
                                      noise_dict,
                                      [1.0],
                                      method,
                                      )
    scaled_b = np.log(sig_b.max() / noise_function_b.std())

    assert np.round(scaled_b / scaled_a) == 2, 'CNR_Amp dB modulation failed'

    # Create the calibrated signal with CNR_Signal-SD/Noise-SD
    method = 'CNR_Signal-SD/Noise-SD'
    sig_a = sim.compute_signal_change(signal_function,
                                      noise_function_a,
                                      noise_dict,
                                      [0.5],
                                      method,
                                      )
    scaled_a = sig_a.std() / noise_function_a.std()
    sig_b = sim.compute_signal_change(signal_function,
                                      noise_function_a,
                                      noise_dict,
                                      [1.0],
                                      method,
                                      )
    scaled_b = sig_b.std() / noise_function_a.std()

    assert (scaled_b / scaled_a) == 2, 'CNR signal modulation failed'

    # Create the calibrated signal with CNR_Amp/Noise-Var_dB
    method = 'CNR_Signal-Var/Noise-Var_dB'
    sig_a = sim.compute_signal_change(signal_function,
                                      noise_function_a,
                                      noise_dict,
                                      [0.5],
                                      method,
                                      )

    scaled_a = np.log(sig_a.std() / noise_function_a.std())
    sig_b = sim.compute_signal_change(signal_function,
                                      noise_function_b,
                                      noise_dict,
                                      [1.0],
                                      method,
                                      )
    scaled_b = np.log(sig_b.std() / noise_function_b.std())

    assert np.round(scaled_b / scaled_a) == 2, 'CNR signal dB modulation ' \
                                               'failed'

    # Convolve the HRF with the stimulus sequence
    signal = sim.apply_signal(signal_function=signal_function,
                              volume_signal=volume,
                              )

    assert signal.shape == (dimensions[0], dimensions[1], dimensions[2],
                            duration / tr_duration), "The output is the " \
                                                     "wrong size"

    signal = sim.apply_signal(signal_function=stimfunction,
                              volume_signal=volume,
                              )

    assert np.any(signal == signal_magnitude), "The stimfunction is not binary"

    # Check that there is an error if the number of signal voxels doesn't
    # match the number of non zero brain voxels
    with pytest.raises(IndexError):
        sig_vox = (volume > 0).sum()
        vox_pattern = np.tile(stimfunction, (1, sig_vox - 1))
        sim.apply_signal(signal_function=vox_pattern,
                         volume_signal=volume,
                         )
Beispiel #13
0
def _generate_ROIs(ROI_file, stimfunc, noise, scale_percentage, data_dict):
    """Make signal activity for an ROI of data
        Creates the specified evoked response time course, calibrated to the
        expected signal change, for a given ROI

    Parameters
    ----------

    ROI_file : str
        Path to the file of the ROI being loaded in

    stimfunc : 1 dimensional array
        Time course of evoked response. Output from
        fmrisim.generate_stimfunction

    noise : 4 dimensional array
        Volume of noise generated from fmrisim.generate_noise. Although this
        is needed as an input, this is only so that the percent signal change
        can be calibrated. This is not combined with the signal generated.

    scale_percentage : float
        What is the percent signal change for the evoked response

    data_dict : dict
        A dictionary to specify the parameters used for making data,
        specifying the following keys
        numTRs - int - Specify the number of time points
        multivariate_patterns - bool - Is the difference between conditions
        univariate (0) or multivariate (1)
        different_ROIs - bool - Are there different ROIs for each condition (
        1) or is it in the same ROI (0). If it is the same ROI and you are
        using univariate differences, the second condition will have a
        smaller evoked response than the other.
        event_duration - int - How long, in seconds, is each event
        scale_percentage - float - What is the percent signal change
        trDuration - float - How many seconds per volume
        save_dicom - bool - Save to data as a dicom (1) or numpy (0)
        save_realtime - bool - Do you want to save the data in real time (1)
        or as fast as possible (0)?
        isi - float - What is the time between each event (in seconds)
        burn_in - int - How long before the first event (in seconds)

    Returns
    ----------

    signal : 4 dimensional array
    Volume of signal in the specified ROI (noise has not yet been added)

    """

    # Create the signal in the ROI as specified.

    # Load in the template data (it may already be loaded if doing a test)
    if isinstance(ROI_file, str):
        logger.info('Loading', ROI_file)
        nii = nibabel.load(ROI_file)
        ROI = nii.get_data()
    else:
        ROI = ROI_file

    # Find all the indices that contain signal
    idx_list = np.where(ROI == 1)

    idxs = np.zeros([len(idx_list[0]), 3])
    for idx_counter in list(range(0, len(idx_list[0]))):
        idxs[idx_counter, 0] = int(idx_list[0][idx_counter])
        idxs[idx_counter, 1] = int(idx_list[1][idx_counter])
        idxs[idx_counter, 2] = int(idx_list[2][idx_counter])

    idxs = idxs.astype('int8')

    # How many voxels per ROI
    voxels = int(ROI.sum())

    # Create a pattern of activity across the two voxels
    if data_dict['multivariate_pattern'] is True:
        pattern = np.random.rand(voxels).reshape((voxels, 1))
    else:  # Just make a univariate increase
        pattern = np.tile(1, voxels).reshape((voxels, 1))

    # Multiply each pattern by each voxel time course
    weights = np.tile(stimfunc, voxels) * pattern.T

    # Convolve the onsets with the HRF
    temporal_res = 1 / data_dict['trDuration']
    signal_func = sim.convolve_hrf(
        stimfunction=weights,
        tr_duration=data_dict['trDuration'],
        temporal_resolution=temporal_res,
        scale_function=1,
    )

    # Change the type of noise
    noise = noise.astype('double')

    # Create a noise function (same voxels for signal function as for noise)
    noise_function = noise[idxs[:, 0], idxs[:, 1], idxs[:, 2], :].T

    # Compute the signal magnitude for the data
    sf_scaled = sim.compute_signal_change(
        signal_function=signal_func,
        noise_function=noise_function,
        noise_dict=data_dict['noise_dict'],
        magnitude=[scale_percentage],
        method='PSC',
    )

    # Combine the signal time course with the signal volume
    signal = sim.apply_signal(
        sf_scaled,
        ROI,
    )

    # Return signal needed
    return signal
Beispiel #14
0
def test_generate_noise():

    dimensions = np.array([10, 10, 10])  # What is the size of the brain
    feature_size = [2]
    feature_type = ['cube']
    feature_coordinates = np.array(
        [[5, 5, 5]])
    signal_magnitude = [1]

    # Generate a volume representing the location and quality of the signal
    volume = sim.generate_signal(dimensions=dimensions,
                                 feature_coordinates=feature_coordinates,
                                 feature_type=feature_type,
                                 feature_size=feature_size,
                                 signal_magnitude=signal_magnitude,
                                 )

    # Inputs for generate_stimfunction
    onsets = [10, 30, 50, 70, 90]
    event_durations = [6]
    tr_duration = 2
    duration = 100

    # Create the time course for the signal to be generated
    stimfunction = sim.generate_stimfunction(onsets=onsets,
                                             event_durations=event_durations,
                                             total_time=duration,
                                             )

    signal_function = sim.convolve_hrf(stimfunction=stimfunction,
                                       tr_duration=tr_duration,
                                       )

    # Convolve the HRF with the stimulus sequence
    signal = sim.apply_signal(signal_function=signal_function,
                              volume_signal=volume,
                              )

    # Generate the mask of the signal
    mask, template = sim.mask_brain(signal, mask_threshold=0.1)

    assert min(mask[mask > 0]) > 0.1, "Mask thresholding did not work"
    assert len(np.unique(template) > 2), "Template creation did not work"

    stimfunction_tr = stimfunction[::int(tr_duration * 1000)]
    # Create the noise volumes (using the default parameters)
    noise = sim.generate_noise(dimensions=dimensions,
                               stimfunction_tr=stimfunction_tr,
                               tr_duration=tr_duration,
                               template=template,
                               mask=mask,
                               )

    assert signal.shape == noise.shape, "The dimensions of signal and noise " \
                                        "the same"

    assert np.std(signal) < np.std(noise), "Noise was not created"

    noise = sim.generate_noise(dimensions=dimensions,
                               stimfunction_tr=stimfunction_tr,
                               tr_duration=tr_duration,
                               template=template,
                               mask=mask,
                               noise_dict={'sfnr': 10000, 'snr': 10000},
                               )

    system_noise = np.std(noise[mask > 0], 1).mean()

    assert system_noise <= 0.1, "Noise strength could not be manipulated"
                        stimfunc).transpose() * signal_pattern[voxel_counter]
            else:

                # Add these elements together
                temp = np.zeros((len(stimfunc), vector_size))
                for voxel_counter in list(range(0, vector_size)):
                    temp[:, voxel_counter] = np.asarray(stimfunc).transpose() * \
                                             signal_pattern[voxel_counter]

                stimfunc_all += temp

    # After you have gone through all the nodes, convolve the HRF and
    # stimulation for each voxel
    print('Convolving HRF')
    signal_func = sim.convolve_hrf(stimfunction=stimfunc_all,
                                   tr_duration=tr_duration,
                                   temporal_resolution=temporal_res,
                                   )

    if save_signal_func == 1 and resample == 0 and run_counter == 0:
        plt.plot(stimfunc_all[::int(temporal_res * tr_duration), 0])
        plt.plot(signal_func[:,0])
        plt.xlim((0, 200))
        plt.ylim((-1, 5))
        plt.savefig(signal_func_save)

    # Convert the stim func into a binary vector of dim 1
    stimfunc_binary = np.mean(np.abs(stimfunc_all)>0, 1) > 0
    stimfunc_binary = stimfunc_binary[::int(tr_duration * temporal_res)]

    # Bound, can happen if the duration is not rounded to a TR
    stimfunc_binary = stimfunc_binary[0:signal_func.shape[0]]
Beispiel #16
0
def test_apply_signal():

    dimensions = np.array([10, 10, 10])  # What is the size of the brain
    feature_size = [2]
    feature_type = ['cube']
    feature_coordinates = np.array([[5, 5, 5]])
    signal_magnitude = [30]

    # Generate a volume representing the location and quality of the signal
    volume = sim.generate_signal(
        dimensions=dimensions,
        feature_coordinates=feature_coordinates,
        feature_type=feature_type,
        feature_size=feature_size,
        signal_magnitude=signal_magnitude,
    )

    # Inputs for generate_stimfunction
    onsets = [10, 30, 50, 70, 90]
    event_durations = [6]
    tr_duration = 2
    duration = 100

    # Create the time course for the signal to be generated
    stimfunction = sim.generate_stimfunction(
        onsets=onsets,
        event_durations=event_durations,
        total_time=duration,
    )

    signal_function = sim.convolve_hrf(
        stimfunction=stimfunction,
        tr_duration=tr_duration,
    )

    # Check that you can compute signal change appropriately
    # Preset a bunch of things
    stimfunction_tr = stimfunction[::int(tr_duration * 100)]
    mask, template = sim.mask_brain(dimensions, mask_self=False)
    noise_dict = sim._noise_dict_update({})
    noise = sim.generate_noise(dimensions=dimensions,
                               stimfunction_tr=stimfunction_tr,
                               tr_duration=tr_duration,
                               template=template,
                               mask=mask,
                               noise_dict=noise_dict,
                               iterations=[0, 0])
    coords = feature_coordinates[0]
    noise_function_a = noise[coords[0], coords[1], coords[2], :]
    noise_function_a = noise_function_a.reshape(duration // tr_duration, 1)

    noise_function_b = noise[coords[0] + 1, coords[1], coords[2], :]
    noise_function_b = noise_function_b.reshape(duration // tr_duration, 1)

    # Create the calibrated signal with PSC
    method = 'PSC'
    sig_a = sim.compute_signal_change(
        signal_function,
        noise_function_a,
        noise_dict,
        [0.5],
        method,
    )
    sig_b = sim.compute_signal_change(
        signal_function,
        noise_function_a,
        noise_dict,
        [1.0],
        method,
    )

    assert sig_b.max() / sig_a.max() == 2, 'PSC modulation failed'

    # Create the calibrated signal with SFNR
    method = 'SFNR'
    sig_a = sim.compute_signal_change(
        signal_function,
        noise_function_a,
        noise_dict,
        [0.5],
        method,
    )
    scaled_a = sig_a / (noise_function_a.mean() / noise_dict['sfnr'])
    sig_b = sim.compute_signal_change(
        signal_function,
        noise_function_b,
        noise_dict,
        [1.0],
        method,
    )
    scaled_b = sig_b / (noise_function_b.mean() / noise_dict['sfnr'])

    assert scaled_b.max() / scaled_a.max() == 2, 'SFNR modulation failed'

    # Create the calibrated signal with CNR_Amp/Noise-SD
    method = 'CNR_Amp/Noise-SD'
    sig_a = sim.compute_signal_change(
        signal_function,
        noise_function_a,
        noise_dict,
        [0.5],
        method,
    )
    scaled_a = sig_a / noise_function_a.std()
    sig_b = sim.compute_signal_change(
        signal_function,
        noise_function_b,
        noise_dict,
        [1.0],
        method,
    )
    scaled_b = sig_b / noise_function_b.std()

    assert scaled_b.max() / scaled_a.max() == 2, 'CNR_Amp modulation failed'

    # Create the calibrated signal with CNR_Amp/Noise-Var_dB
    method = 'CNR_Amp2/Noise-Var_dB'
    sig_a = sim.compute_signal_change(
        signal_function,
        noise_function_a,
        noise_dict,
        [0.5],
        method,
    )
    scaled_a = np.log(sig_a.max() / noise_function_a.std())
    sig_b = sim.compute_signal_change(
        signal_function,
        noise_function_b,
        noise_dict,
        [1.0],
        method,
    )
    scaled_b = np.log(sig_b.max() / noise_function_b.std())

    assert np.round(scaled_b / scaled_a) == 2, 'CNR_Amp dB modulation failed'

    # Create the calibrated signal with CNR_Signal-SD/Noise-SD
    method = 'CNR_Signal-SD/Noise-SD'
    sig_a = sim.compute_signal_change(
        signal_function,
        noise_function_a,
        noise_dict,
        [0.5],
        method,
    )
    scaled_a = sig_a.std() / noise_function_a.std()
    sig_b = sim.compute_signal_change(
        signal_function,
        noise_function_a,
        noise_dict,
        [1.0],
        method,
    )
    scaled_b = sig_b.std() / noise_function_a.std()

    assert (scaled_b / scaled_a) == 2, 'CNR signal modulation failed'

    # Create the calibrated signal with CNR_Amp/Noise-Var_dB
    method = 'CNR_Signal-Var/Noise-Var_dB'
    sig_a = sim.compute_signal_change(
        signal_function,
        noise_function_a,
        noise_dict,
        [0.5],
        method,
    )

    scaled_a = np.log(sig_a.std() / noise_function_a.std())
    sig_b = sim.compute_signal_change(
        signal_function,
        noise_function_b,
        noise_dict,
        [1.0],
        method,
    )
    scaled_b = np.log(sig_b.std() / noise_function_b.std())

    assert np.round(scaled_b / scaled_a) == 2, 'CNR signal dB modulation ' \
                                               'failed'

    # Convolve the HRF with the stimulus sequence
    signal = sim.apply_signal(
        signal_function=signal_function,
        volume_signal=volume,
    )

    assert signal.shape == (dimensions[0], dimensions[1], dimensions[2],
                            duration / tr_duration), "The output is the " \
                                                     "wrong size"

    signal = sim.apply_signal(
        signal_function=stimfunction,
        volume_signal=volume,
    )

    assert np.any(signal == signal_magnitude), "The stimfunction is not binary"

    # Check that there is an error if the number of signal voxels doesn't
    # match the number of non zero brain voxels
    with pytest.raises(IndexError):
        sig_vox = (volume > 0).sum()
        vox_pattern = np.tile(stimfunction, (1, sig_vox - 1))
        sim.apply_signal(
            signal_function=vox_pattern,
            volume_signal=volume,
        )
Beispiel #17
0
# Create the time course for the signal to be generated
stimfunction_A = sim.generate_stimfunction(onsets=onsets_A,
                                           event_durations=event_durations,
                                           total_time=duration,
                                           temporal_resolution=temporal_res,
                                           )

stimfunction_B = sim.generate_stimfunction(onsets=onsets_B,
                                           event_durations=event_durations,
                                           total_time=duration,
                                           temporal_resolution=temporal_res,
                                           )

# Convolve the HRF with the stimulus sequence
signal_function_A = sim.convolve_hrf(stimfunction=stimfunction_A,
                                     tr_duration=tr_duration,
                                     temporal_resolution=temporal_res,
                                     )

signal_function_B = sim.convolve_hrf(stimfunction=stimfunction_B,
                                     tr_duration=tr_duration,
                                     temporal_resolution=temporal_res,
                                     )

# Multiply the HRF timecourse with the signal
signal_A = sim.apply_signal(signal_function=signal_function_A,
                            volume_signal=volume_signal_A,
                            )

signal_B = sim.apply_signal(signal_function=signal_function_B,
                            volume_signal=volume_signal_B,
                            )
Beispiel #18
0
def test_generate_noise():

    dimensions = np.array([10, 10, 10])  # What is the size of the brain
    feature_size = [2]
    feature_type = ['cube']
    feature_coordinates = np.array([[5, 5, 5]])
    signal_magnitude = [1]

    # Generate a volume representing the location and quality of the signal
    volume = sim.generate_signal(
        dimensions=dimensions,
        feature_coordinates=feature_coordinates,
        feature_type=feature_type,
        feature_size=feature_size,
        signal_magnitude=signal_magnitude,
    )

    # Inputs for generate_stimfunction
    onsets = [10, 30, 50, 70, 90]
    event_durations = [6]
    tr_duration = 2
    duration = 200

    # Create the time course for the signal to be generated
    stimfunction = sim.generate_stimfunction(
        onsets=onsets,
        event_durations=event_durations,
        total_time=duration,
    )

    signal_function = sim.convolve_hrf(
        stimfunction=stimfunction,
        tr_duration=tr_duration,
    )

    # Convolve the HRF with the stimulus sequence
    signal = sim.apply_signal(
        signal_function=signal_function,
        volume_signal=volume,
    )

    # Generate the mask of the signal
    mask, template = sim.mask_brain(signal, mask_self=None)

    assert min(mask[mask > 0]) > 0.1, "Mask thresholding did not work"
    assert len(np.unique(template) > 2), "Template creation did not work"

    stimfunction_tr = stimfunction[::int(tr_duration * 100)]

    # Create the noise volumes (using the default parameters)
    noise = sim.generate_noise(
        dimensions=dimensions,
        stimfunction_tr=stimfunction_tr,
        tr_duration=tr_duration,
        template=template,
        mask=mask,
        iterations=[1, 0],
    )

    assert signal.shape == noise.shape, "The dimensions of signal and noise " \
                                        "the same"

    noise_high = sim.generate_noise(
        dimensions=dimensions,
        stimfunction_tr=stimfunction_tr,
        tr_duration=tr_duration,
        template=template,
        mask=mask,
        noise_dict={
            'sfnr': 50,
            'snr': 25
        },
        iterations=[1, 0],
    )

    noise_low = sim.generate_noise(
        dimensions=dimensions,
        stimfunction_tr=stimfunction_tr,
        tr_duration=tr_duration,
        template=template,
        mask=mask,
        noise_dict={
            'sfnr': 100,
            'snr': 25
        },
        iterations=[1, 0],
    )

    system_high = np.std(noise_high[mask > 0], 1).mean()
    system_low = np.std(noise_low[mask > 0], 1).mean()

    assert system_low < system_high, "SFNR noise could not be manipulated"

    # Check that you check for the appropriate template values
    with pytest.raises(ValueError):
        sim.generate_noise(
            dimensions=dimensions,
            stimfunction_tr=stimfunction_tr,
            tr_duration=tr_duration,
            template=template * 2,
            mask=mask,
            noise_dict={},
        )

    # Check that iterations does what it should
    sim.generate_noise(
        dimensions=dimensions,
        stimfunction_tr=stimfunction_tr,
        tr_duration=tr_duration,
        template=template,
        mask=mask,
        noise_dict={},
        iterations=[0, 0],
    )

    sim.generate_noise(
        dimensions=dimensions,
        stimfunction_tr=stimfunction_tr,
        tr_duration=tr_duration,
        template=template,
        mask=mask,
        noise_dict={},
        iterations=None,
    )

    # Test drift noise
    trs = 1000
    period = 100
    drift = sim._generate_noise_temporal_drift(
        trs,
        tr_duration,
        'sine',
        period,
    )

    # Check that the max frequency is the appropriate frequency
    power = abs(np.fft.fft(drift))[1:trs // 2]
    freq = np.linspace(1, trs // 2 - 1, trs // 2 - 1) / trs
    period_freq = np.where(freq == 1 / (period // tr_duration))
    max_freq = np.argmax(power)

    assert period_freq == max_freq, 'Max frequency is not where it should be'

    # Do the same but now with cosine basis functions, answer should be close
    drift = sim._generate_noise_temporal_drift(
        trs,
        tr_duration,
        'discrete_cos',
        period,
    )

    # Check that the appropriate frequency is peaky (may not be the max)
    power = abs(np.fft.fft(drift))[1:trs // 2]
    freq = np.linspace(1, trs // 2 - 1, trs // 2 - 1) / trs
    period_freq = np.where(freq == 1 / (period // tr_duration))[0][0]

    assert power[period_freq] > power[period_freq + 1], 'Power is low'
    assert power[period_freq] > power[period_freq - 1], 'Power is low'

    # Check it runs fine
    drift = sim._generate_noise_temporal_drift(
        50,
        tr_duration,
        'discrete_cos',
        period,
    )

    # Check it runs fine
    drift = sim._generate_noise_temporal_drift(
        300,
        tr_duration,
        'cos_power_drop',
        period,
    )

    # Check that when the TR is greater than the period it errors
    with pytest.raises(ValueError):
        sim._generate_noise_temporal_drift(30, 10, 'cos_power_drop', 5)

    # Test physiological noise (using unrealistic parameters so that it's easy)
    timepoints = list(np.linspace(0, (trs - 1) * tr_duration, trs))
    resp_freq = 0.2
    heart_freq = 1.17
    phys = sim._generate_noise_temporal_phys(
        timepoints,
        resp_freq,
        heart_freq,
    )

    # Check that the max frequency is the appropriate frequency
    power = abs(np.fft.fft(phys))[1:trs // 2]
    freq = np.linspace(1, trs // 2 - 1, trs // 2 - 1) / (trs * tr_duration)
    peaks = (power > (power.mean() + power.std()))  # Where are the peaks
    peak_freqs = freq[peaks]

    assert np.any(resp_freq == peak_freqs), 'Resp frequency not found'
    assert len(peak_freqs) == 2, 'Two peaks not found'

    # Test task noise
    sim._generate_noise_temporal_task(
        stimfunction_tr,
        motion_noise='gaussian',
    )
    sim._generate_noise_temporal_task(
        stimfunction_tr,
        motion_noise='rician',
    )

    # Test ARMA noise
    with pytest.raises(ValueError):
        noise_dict = {'fwhm': 4, 'auto_reg_rho': [1], 'ma_rho': [1, 1]}
        sim._generate_noise_temporal_autoregression(
            stimfunction_tr,
            noise_dict,
            dimensions,
            mask,
        )

    # Generate spatial noise
    vol = sim._generate_noise_spatial(np.array([10, 10, 10, trs]))
    assert len(vol.shape) == 3, 'Volume was not reshaped to ignore TRs'

    # Switch some of the noise types on
    noise_dict = dict(physiological_sigma=1,
                      drift_sigma=1,
                      task_sigma=1,
                      auto_reg_sigma=0)
    sim.generate_noise(
        dimensions=dimensions,
        stimfunction_tr=stimfunction_tr,
        tr_duration=tr_duration,
        template=template,
        mask=mask,
        noise_dict=noise_dict,
        iterations=[0, 0],
    )
Beispiel #19
0
def generate_data(cfgFile):
    cfg = loadConfigFile(cfgFile)
    frame = inspect.currentframe()
    moduleFile = typing.cast(str, frame.f_code.co_filename)  # type: ignore
    moduleDir = os.path.dirname(moduleFile)
    cfgDate = parser.parse(cfg.session.date).strftime("%Y%m%d")
    dataDir = os.path.join(
        cfg.session.dataDir, "subject{}/day{}".format(cfg.session.subjectNum,
                                                      cfg.session.subjectDay))
    imgDir = os.path.join(
        cfg.session.imgDir, "{}.{}.{}".format(cfgDate, cfg.session.subjectName,
                                              cfg.session.subjectName))
    if os.path.exists(dataDir) and os.path.exists(imgDir):
        print(
            "output data and imgage directory already exist, skippig data generation"
        )
        return
    runPatterns = [
        'patternsdesign_1_20180101T000000.mat',
        'patternsdesign_2_20180101T000000.mat',
        'patternsdesign_3_20180101T000000.mat'
    ]
    template_filename = os.path.join(moduleDir, 'sub_template.nii.gz')
    noise_dict_filename = os.path.join(moduleDir, 'sub_noise_dict.txt')
    roiA_filename = os.path.join(moduleDir, 'ROI_A.nii.gz')
    roiB_filename = os.path.join(moduleDir, 'ROI_B.nii.gz')
    output_file_pattern = '001_0000{}_000{}.mat'
    if not os.path.exists(imgDir):
        os.makedirs(imgDir)
    if not os.path.exists(dataDir):
        os.makedirs(dataDir)

    print('Load data')
    template_nii = nibabel.load(template_filename)
    template = template_nii.get_data()
    # dimsize = template_nii.header.get_zooms()

    roiA_nii = nibabel.load(roiA_filename)
    roiB_nii = nibabel.load(roiB_filename)
    roiA = roiA_nii.get_data()
    roiB = roiB_nii.get_data()

    dimensions = np.array(template.shape[0:3])  # What is the size of the brain

    print('Create mask')
    # Generate the continuous mask from the voxels
    mask, template = sim.mask_brain(
        volume=template,
        mask_self=True,
    )
    # Write out the mask as matlab
    mask_uint8 = mask.astype(np.uint8)
    maskfilename = os.path.join(
        dataDir, 'mask_{}_{}.mat'.format(cfg.session.subjectNum,
                                         cfg.session.subjectDay))
    sio.savemat(maskfilename, {'mask': mask_uint8})

    # Load the noise dictionary
    with open(noise_dict_filename, 'r') as f:
        noise_dict = f.read()

    print('Loading ' + noise_dict_filename)
    noise_dict = eval(noise_dict)
    noise_dict['matched'] = 0

    runNum = 1
    scanNum = 0
    for patfile in runPatterns:
        fullPatfile = os.path.join(moduleDir, patfile)
        # make dataDir run directory
        runDir = os.path.join(dataDir, "run{}".format(runNum))
        if not os.path.exists(runDir):
            os.makedirs(runDir)
        shutil.copy(fullPatfile, runDir)
        runNum += 1

        pat = sio.loadmat(fullPatfile)
        scanNum += 1
        # shifted labels are in regressor field
        shiftedLabels = pat['patterns']['regressor'][0][0]
        # non-shifted labels are in attCateg field and whether stimulus applied in the stim field
        nsLabels = pat['patterns']['attCateg'][0][0] * pat['patterns']['stim'][
            0][0]
        labels_A = (nsLabels == 1).astype(int)
        labels_B = (nsLabels == 2).astype(int)

        # trialType = pat['patterns']['type'][0][0]
        tr_duration = pat['TR'][0][0]
        disdaqs = pat['disdaqs'][0][0]
        begTrOffset = disdaqs // tr_duration
        nTRs = pat['nTRs'][0][0]
        # nTestTRs = np.count_nonzero(trialType == 2)

        # Preset some of the parameters
        total_trs = nTRs + begTrOffset  # How many time points are there?

        print('Generating data')
        start = time.time()
        noiseVols = sim.generate_noise(
            dimensions=dimensions,
            stimfunction_tr=np.zeros((total_trs, 1)),
            tr_duration=int(tr_duration),
            template=template,
            mask=mask,
            noise_dict=noise_dict,
        )
        print("Time: generate noise vols {} sec".format(time.time() - start))

        nVoxelsA = int(roiA.sum())
        nVoxelsB = int(roiB.sum())
        # Multiply each pattern by each voxel time course
        weights_A = np.tile(labels_A.reshape(-1, 1), nVoxelsA)
        weights_B = np.tile(labels_B.reshape(-1, 1), nVoxelsB)

        print('Creating signal time course')
        signal_func_A = sim.convolve_hrf(
            stimfunction=weights_A,
            tr_duration=tr_duration,
            temporal_resolution=(1 / tr_duration),
            scale_function=1,
        )

        signal_func_B = sim.convolve_hrf(
            stimfunction=weights_B,
            tr_duration=tr_duration,
            temporal_resolution=(1 / tr_duration),
            scale_function=1,
        )

        max_activity = noise_dict['max_activity']
        signal_change = 10  # .01 * max_activity
        signal_func_A *= signal_change
        signal_func_B *= signal_change

        # Combine the signal time course with the signal volume
        print('Creating signal volumes')
        signal_A = sim.apply_signal(
            signal_func_A,
            roiA,
        )

        signal_B = sim.apply_signal(
            signal_func_B,
            roiB,
        )
        # Combine the two signal timecourses
        signal = signal_A + signal_B

        # testTrId = 0
        numVols = noiseVols.shape[3]
        for idx in range(numVols):
            start = time.time()
            brain = noiseVols[:, :, :, idx]
            if idx >= begTrOffset:
                # some initial scans are skipped as only instructions and not stimulus are shown
                signalIdx = idx - begTrOffset
                brain += signal[:, :, :, signalIdx]

            # TODO: how to create a varying combined percentage of A and B signals
            #     if trialType[0][idx] == 1:
            #         # training TR, so create pure A or B signal
            #         if labels_A[idx] != 0:
            #             brain = brain + roiA
            #         elif labels_B[idx] != 0:
            #             brain = brain + roiB
            #     elif trialType[0][idx] == 2:
            #         # testing TR, so create a mixture of A and B signal
            #         testTrId += 1
            #         testPercent = testTrId / nTestTRs
            #         brain = brain + testPercent * roiA + (1-testPercent) * roiB

            # Save the volume as a matlab file
            filenum = idx + 1
            filename = output_file_pattern.format(
                str(scanNum).zfill(2),
                str(filenum).zfill(3))
            outputfile = os.path.join(imgDir, filename)
            brain_float32 = brain.astype(np.float32)
            sio.savemat(outputfile, {'vol': brain_float32})
            print("Time: generate vol {}: {} sec".format(
                filenum,
                time.time() - start))
Beispiel #20
0
def toy_simulation(community_density=1,
                   added_isi=0,
                   rand=0,
                   signal_magnitude=1,
                   noise_type='coordinates',
                   noise_parameter=0,
                   restrict_overall_duration=0,
                   ):

    # Default these values
    nodes = 15
    runs = 5
    vector_size = 2  # How many voxels did you make
    all_pos = 1
    ppt = '1'  # What participant would you like to simulate
    tr_duration = 2
    event_durations = [1]
    hrf_lag = 2
    temporal_res = 100  # How many samples per second are there for timing files

    # Select what the noise is applied to
    noise_coordinates = 0  # How much noise are you adding to the coordinates
    noise_timecourse = 0  # How many random noise are you adding to the timecourse
    if noise_type == 'coordinates':
        noise_coordinates = noise_parameter
    elif noise_type == 'timecourse':
        noise_timecourse = noise_parameter

    # Load the timing information
    timing_path = '../../community_structure/simulator_parameters/timing/'
    #timing_path = '/Volumes/pniintel/ntb/TDA/Validation/code/community_structure/simulator_parameters/timing/'
    onsets_runs = np.load(timing_path + 'sub-' + ppt + '.npy')
    
    # Generate the graph structure (based on the ratio)
    signal_coords = community_structure(1 - community_density,
                                        )

    # Add noise to these coordinates
    noise = np.random.randn(np.prod(signal_coords.shape)).reshape(
        signal_coords.shape) * noise_coordinates

    signal_coords += noise

    # Perform an orthonormal transformation of the data
    if vector_size > signal_coords.shape[1]:
        signal_coords = orthonormal_transform(vector_size,
                                              signal_coords,
                                              )

    # Do you want these coordinates to be all positive? This means that
    # these coordinates are represented as different magnitudes of
    # activation
    if all_pos == 1:
        mins = np.abs(np.min(signal_coords, 0))
        for voxel_counter in list(range(0, len(mins))):
            signal_coords[:, voxel_counter] += mins[voxel_counter]

    # Bound the value to have a max of 1 so that the signal magnitude is more interpretable
    signal_coords /= np.max(signal_coords)

    # Determine the size of the signal
    signal_coords *= signal_magnitude

    # Cycle through the runs and generate the data

    node_brain = np.zeros([vector_size, nodes, runs], dtype='double')  # Preset
    for run_counter in list(range(1, runs + 1)):

        # Pull out the onsets for this participant (reload it each time to deal with copying issues)
        onsets_runs = np.load(timing_path + 'sub-' + ppt + '.npy')
        onsets_run = onsets_runs[run_counter - 1]

        # What is the original max duration of the onsets
        max_duration_orig = np.max([np.max(onsets_run[x]) for x in range(onsets_run.size)])
        max_duration_orig += 10 # Add some wiggle room

        # Do you want to randomise the onsets (so that the events do not have a
        # fixed order)
        if rand == 1:
            onsets_run = randomise_timing(onsets_runs[run_counter - 1],
                                      )

        # If you want to use different timing then take the order of the data
        # and then create a new timecourse
        onsets_run = extra_isi(onsets_run,
                           added_isi,
                           )
        
        # If necessary, remove all the values greater than the max
        if restrict_overall_duration == 1:
            onsets_run = [onsets_run[x][onsets_run[x] < max_duration_orig] for x in range(
                onsets_run.size)]
            onsets_run = np.asarray(onsets_run)

        # Determine how long the simulated time course is by finding the max of maxs
        last_event = 0
        for node_counter in range(len(onsets_run)):
            if len(onsets_run[node_counter]) > 0 and onsets_run[node_counter].max() > last_event:
                last_event = onsets_run[node_counter].max()    
                
        # How long should you model
        duration = int(last_event + 10)  # Add a decay buffer

        # Preset brain size
        brain_signal = np.zeros([2, int(duration / tr_duration)], dtype='double')
        stimfunc_all = []
        for node_counter in list(range(0, nodes)):

            # Preset the signal
            signal_pattern = np.ones(vector_size)

            # Take the coordinates from the signal template
            for coord_counter in list(range(0, signal_coords.shape[1])):
                signal_pattern[coord_counter] = signal_coords[node_counter,
                                                              coord_counter]

            onsets_node = onsets_run[node_counter]
            
            # Only do it if there are onsets
            if len(onsets_node) > 0:

                # Create the time course for the signal to be generated
                stimfunc = sim.generate_stimfunction(onsets=onsets_node,
                                                     event_durations=event_durations,
                                                     total_time=duration,
                                                     temporal_resolution=temporal_res,
                                                     )

                # Aggregate the timecourse
                if len(stimfunc_all) == 0:
                    stimfunc_all = np.zeros((len(stimfunc), vector_size))
                    for voxel_counter in list(range(0, vector_size)):
                        stimfunc_all[:, voxel_counter] = np.asarray(
                            stimfunc).transpose() * signal_coords[node_counter, voxel_counter]
                else:

                    # Add these elements together
                    temp = np.zeros((len(stimfunc), vector_size))
                    for voxel_counter in list(range(0, vector_size)):
                        temp[:, voxel_counter] = np.asarray(stimfunc).transpose() * \
                                                 signal_coords[node_counter,
                                                               voxel_counter]

                    stimfunc_all += temp

        # After you have gone through all the nodes, convolve the HRF and
        # stimulation for each voxel
        signal_func = sim.convolve_hrf(stimfunction=stimfunc_all,
                                       tr_duration=tr_duration,
                                       temporal_resolution=temporal_res,
                                       )

        # Multiply the convolved responses with their magnitudes (after being
        # scaled)
        for voxel_counter in list(range(0, vector_size)):
            # Reset the range of the function to be appropriate for the
            # stimfunc
            signal_func[:, voxel_counter] *= stimfunc_all[:,
                                             voxel_counter].max()

        # Create the noise
        noise = np.random.randn(np.prod(signal_func.shape)).reshape(
            signal_func.shape) * noise_timecourse

        # Combine the signal and the noise
        brain = signal_func + noise
        # Z score the data
        #brain = zscore(brain.astype('float'), 0)

        # Loop through the nodes
        for node in list(range(0, nodes)):

            node_trs = onsets_run[node]
            if len(node_trs) > 0:
                temp = np.zeros((vector_size, len(node_trs) - 1))
                for tr_counter in list(range(1, len(node_trs))):

                    # When does it onset (first TR is zero so minus 1)
                    onset = int(np.round(node_trs[tr_counter] / tr_duration) +
                                hrf_lag)

                    # Add the TR if it is included when considering the hrf lag
                    if onset < brain.shape[0]:
                        temp[:, tr_counter - 1] = brain[onset, :]

                # Average the TRs
                node_brain[:, node, run_counter - 1] = np.mean(temp, 1)

    # average the brains across runs
    node_brain = np.mean(node_brain, 2)

    return node_brain