예제 #1
0
def test_generate_signal():

    # Inputs for generate_signal
    dimensions = np.array([10, 10, 10])  # What is the size of the brain
    feature_size = [3]
    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,
    )

    assert np.all(volume.shape == dimensions), "Check signal shape"
    assert np.max(volume) == signal_magnitude, "Check signal magnitude"
    assert np.sum(volume > 0) == math.pow(feature_size[0],
                                          3), ("Check feature size")
    assert volume[5, 5, 5] == signal_magnitude, "Check signal location"
    assert volume[5, 5, 1] == 0, "Check noise location"

    feature_coordinates = np.array([[5, 5, 5], [3, 3, 3], [7, 7, 7]])

    volume = sim.generate_signal(dimensions=dimensions,
                                 feature_coordinates=feature_coordinates,
                                 feature_type=['loop', 'cavity', 'sphere'],
                                 feature_size=[3],
                                 signal_magnitude=signal_magnitude)
    assert volume[5, 5, 5] == 0, "Loop is empty"
    assert volume[3, 3, 3] == 0, "Cavity is empty"
    assert volume[7, 7, 7] != 0, "Sphere is not empty"
예제 #2
0
def test_mask_brain():

    # Inputs for generate_signal
    dimensions = np.array([10, 10, 10])  # What is the size of the brain
    feature_size = [2]
    feature_type = ['cube']
    feature_coordinates = np.array(
        [[4, 4, 4]])
    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,
                                 )

    # Mask the volume to be the same shape as a brain
    mask, _ = sim.mask_brain(dimensions, mask_self=None,)
    brain = volume * mask

    assert np.sum(brain != 0) == np.sum(volume != 0), "Masking did not work"
    assert brain[0, 0, 0] == 0, "Masking did not work"
    assert brain[4, 4, 4] != 0, "Masking did not work"

    feature_coordinates = np.array(
        [[1, 1, 1]])

    volume = sim.generate_signal(dimensions=dimensions,
                                 feature_coordinates=feature_coordinates,
                                 feature_type=feature_type,
                                 feature_size=feature_size,
                                 signal_magnitude=signal_magnitude,
                                 )

    # Mask the volume to be the same shape as a brain
    mask, _ = sim.mask_brain(dimensions, mask_self=None, )
    brain = volume * mask

    assert np.sum(brain != 0) < np.sum(volume != 0), "Masking did not work"

    # Test that you can load the default
    dimensions = np.array([100, 100, 100])
    mask, template = sim.mask_brain(dimensions, mask_self=False)

    assert mask[20, 80, 50] == 0, 'Masking didn''t work'
    assert mask[25, 80, 50] == 1, 'Masking didn''t work'
    assert int(template[25, 80, 50] * 100) == 57, 'Template not correct'

    # Check that you can mask self
    mask_self, template_self = sim.mask_brain(template, mask_self=True)

    assert (template_self - template).sum() < 1e2, 'Mask self error'
    assert (mask_self - mask).sum() == 0, 'Mask self error'
예제 #3
0
def test_mask_brain():

    # Inputs for generate_signal
    dimensions = np.array([10, 10, 10])  # What is the size of the brain
    feature_size = [2]
    feature_type = ['cube']
    feature_coordinates = np.array([[4, 4, 4]])
    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,
    )

    # Mask the volume to be the same shape as a brain
    mask = sim.mask_brain(volume)[:, :, :, 0]
    brain = volume * (mask > 0)

    assert np.sum(brain != 0) == np.sum(volume != 0), "Masking did not work"
    assert brain[0, 0, 0] == 0, "Masking did not work"
    assert brain[4, 4, 4] != 0, "Masking did not work"

    feature_coordinates = np.array([[1, 1, 1]])

    volume = sim.generate_signal(
        dimensions=dimensions,
        feature_coordinates=feature_coordinates,
        feature_type=feature_type,
        feature_size=feature_size,
        signal_magnitude=signal_magnitude,
    )

    # Mask the volume to be the same shape as a brain
    mask = sim.mask_brain(volume)[:, :, :, 0]
    brain = volume * (mask > 0)

    assert np.sum(brain != 0) < np.sum(volume != 0), "Masking did not work"
예제 #4
0
def test_mask_brain():

    # Inputs for generate_signal
    dimensions = np.array([10, 10, 10])  # What is the size of the brain
    feature_size = [2]
    feature_type = ['cube']
    feature_coordinates = np.array(
        [[4, 4, 4]])
    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,
                                 )

    # Mask the volume to be the same shape as a brain
    mask, _ = sim.mask_brain(volume)
    brain = volume * mask

    assert np.sum(brain != 0) == np.sum(volume != 0), "Masking did not work"
    assert brain[0, 0, 0] == 0, "Masking did not work"
    assert brain[4, 4, 4] != 0, "Masking did not work"

    feature_coordinates = np.array(
        [[1, 1, 1]])

    volume = sim.generate_signal(dimensions=dimensions,
                                 feature_coordinates=feature_coordinates,
                                 feature_type=feature_type,
                                 feature_size=feature_size,
                                 signal_magnitude=signal_magnitude,
                                 )

    # Mask the volume to be the same shape as a brain
    mask, _ = sim.mask_brain(volume)
    brain = volume * mask

    assert np.sum(brain != 0) < np.sum(volume != 0), "Masking did not work"
예제 #5
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.double_gamma_hrf(
        stimfunction=stimfunction,
        tr_duration=tr_duration,
    )

    # Convolve the HRF with the stimulus sequence
    signal = sim.apply_signal(
        signal_function=signal_function,
        volume_static=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_static=volume,
    )

    assert np.any(signal == signal_magnitude), "The stimfunction is not binary"
예제 #6
0
def test_generate_signal():

    # Inputs for generate_signal
    dimensions = np.array([64, 64, 36])  # What is the size of the brain
    feature_size = [2]
    feature_type = ['cube']
    feature_coordinates = np.array([[32, 32, 18]])
    signal_magnitude = [30]

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

    assert np.all(volume_static.shape == dimensions), "Check signal shape"
    assert np.max(volume_static) == signal_magnitude, "Check signal magnitude"
    assert np.sum(volume_static>0) == math.pow(feature_size[0], 3), "Check " \
                                                                    "feature size"
    assert volume_static[32, 32,
                         18] == signal_magnitude, "Check signal location"
    assert volume_static[32, 32, 10] == 0, "Check noise location"

    feature_coordinates = np.array([[32, 32, 18], [32, 28, 18], [28, 32, 18]])

    volume_static = sim.generate_signal(
        dimensions=dimensions,
        feature_coordinates=feature_coordinates,
        feature_type=['loop', 'cavity', 'sphere'],
        feature_size=[9],
        signal_magnitude=signal_magnitude,
    )
    assert volume_static[32, 32, 18] == 0, "Loop is empty"
    assert volume_static[32, 28, 18] == 0, "Cavity is empty"
    assert volume_static[28, 32, 18] != 0, "Sphere is not empty"
예제 #7
0
def test_generate_signal():

    # Inputs for generate_signal
    dimensions = np.array([64, 64, 36]) # What is the size of the brain
    feature_size = [2]
    feature_type = ['cube']
    feature_coordinates = np.array(
        [[32, 32, 18]])
    signal_magnitude = [30]

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

    assert np.all(volume_static.shape == dimensions), "Check signal shape"
    assert np.max(volume_static) == signal_magnitude, "Check signal magnitude"
    assert np.sum(volume_static>0) == math.pow(feature_size[0], 3), "Check " \
                                                                    "feature size"
    assert volume_static[32,32,18] == signal_magnitude, "Check signal location"
    assert volume_static[32,32,10] == 0, "Check noise location"

    feature_coordinates = np.array(
        [[32, 32, 18], [32, 28, 18], [28, 32, 18]])

    volume_static = sim.generate_signal(dimensions=dimensions,
                                        feature_coordinates=feature_coordinates,
                                        feature_type=['loop', 'cavity', 'sphere'],
                                        feature_size=[9],
                                        signal_magnitude=signal_magnitude,
                                        )
    assert volume_static[32, 32, 18] == 0, "Loop is empty"
    assert volume_static[32, 28, 18] == 0, "Cavity is empty"
    assert volume_static[28, 32, 18] != 0, "Sphere is not empty"
예제 #8
0
def test_generate_signal():

    # Inputs for generate_signal
    dimensions = np.array([10, 10, 10])  # What is the size of the brain
    feature_size = [3]
    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,
                                 )

    assert np.all(volume.shape == dimensions), "Check signal shape"
    assert np.max(volume) == signal_magnitude, "Check signal magnitude"
    assert np.sum(volume>0) == math.pow(feature_size[0], 3), "Check feature " \
                                                             "size"
    assert volume[5, 5, 5] == signal_magnitude, "Check signal location"
    assert volume[5, 5, 1] == 0, "Check noise location"

    feature_coordinates = np.array(
        [[5, 5, 5], [3, 3, 3], [7, 7, 7]])

    volume = sim.generate_signal(dimensions=dimensions,
                                 feature_coordinates=feature_coordinates,
                                 feature_type=['loop', 'cavity', 'sphere'],
                                 feature_size=[3],
                                 signal_magnitude=signal_magnitude,
                                )
    assert volume[5, 5, 5] == 0, "Loop is empty"
    assert volume[3, 3, 3] == 0, "Cavity is empty"
    assert volume[7, 7, 7] != 0, "Sphere is not empty"
예제 #9
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"
예제 #10
0
# Inputs for generate_stimfunction
onsets_A = [10, 30, 50, 70, 90]
onsets_B = [0, 20, 40, 60, 80]
event_durations = [6]
tr_duration = 2
temporal_res = 1000.0  # How many elements per second are there
duration = 100

# Specify a name to save this generated volume.
savename = 'examples/utils/example.nii'

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

volume_signal_B = sim.generate_signal(dimensions=dimensions,
                                      feature_coordinates=coordinates_B,
                                      feature_type=feature_type,
                                      feature_size=feature_size,
                                      signal_magnitude=signal_magnitude,
                                      )

# Visualize the signal that was generated for condition A
fig = plt.figure()
sim.plot_brain(fig,
               volume_signal_A)
plt.show()
예제 #11
0
# Inputs for generate_stimfunction
onsets_A = [10, 30, 50, 70, 90]
onsets_B = [0, 20, 40, 60, 80]
event_durations = [6]
tr_duration = 2
temporal_res = 1000.0  # How many elements per second are there
duration = 100

# Specify a name to save this generated volume.
savename = 'examples/utils/example.nii'

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

volume_static_B = sim.generate_signal(
    dimensions=dimensions,
    feature_coordinates=coordinates_B,
    feature_type=feature_type,
    feature_size=feature_size,
    signal_magnitude=signal_magnitude,
)

# Visualize the signal that was generated for condition A
fig = plt.figure()
sim.plot_brain(fig, volume_static_A)
예제 #12
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"
예제 #13
0
        # Store these start and end times
        onsets[cond_counter] += list(range(start_idx, end_idx, tr_duration))
        epoch[cond_counter, idx * conds + cond_counter, start_idx:end_idx] = 1

        # The pattern of activity for each trial
        weight = ([1] * int(np.floor(stim_dur / 2))) + ([-1]*int(np.ceil(
            stim_dur / 2)))
        weights[cond_counter] += weight

# Iterate through the conditions to make the necessary functions
for cond in list(range(conds)):

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

    # Create the time course for the signal to be generated
    stimfunction_cond = sim.generate_stimfunction(onsets=onsets[cond],
                                                  event_durations=
                                                  event_durations,
                                                  total_time=duration,
                                                  weights=weights[cond],
                                                  )

    # Convolve the HRF with the stimulus sequence
    signal_function = sim.double_gamma_hrf(stimfunction=stimfunction_cond,
                                           tr_duration=tr_duration,
                                           )
예제 #14
0
def test_generate_noise():


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

    # Generate a volume representing the location and quality of the signal
    volume_static = 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,
                                             tr_duration=tr_duration,
                                             )

    signal_function = sim.double_gamma_hrf(stimfunction=stimfunction,
                                           )

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

    # Create the noise volumes (using the default parameters)

    noise = sim.generate_noise(dimensions=dimensions,
                               stimfunction=stimfunction,
                               tr_duration=tr_duration,
                               )

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

    Z_noise = sim._generate_noise_temporal(stimfunction, tr_duration, 1)
    noise = sim._generate_noise_temporal(stimfunction, tr_duration, 0)

    assert np.std(Z_noise) < np.std(noise), "Z scoring is not working"

    # Combine the signal and the noise
    volume = signal + noise

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

    noise = sim.generate_noise(dimensions=dimensions,
                               stimfunction=stimfunction,
                               tr_duration=tr_duration,
                               noise_strength=[0, 0, 0]
                               )

    assert np.sum(noise) == 0, "Noise strength could not be manipulated"
    assert np.std(noise) == 0, "Noise strength could not be manipulated"
예제 #15
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,
                         )
예제 #16
0
def test_generate_signal():

    # Inputs for generate_signal
    dimensions = np.array([10, 10, 10])  # What is the size of the brain
    feature_size = [3]
    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,
                                 )

    assert np.all(volume.shape == dimensions), "Check signal shape"
    assert np.max(volume) == signal_magnitude, "Check signal magnitude"
    assert np.sum(volume > 0) == math.pow(feature_size[0], 3), (
        "Check feature size")
    assert volume[5, 5, 5] == signal_magnitude, "Check signal location"
    assert volume[5, 5, 1] == 0, "Check noise location"

    feature_coordinates = np.array(
        [[5, 5, 5], [3, 3, 3], [7, 7, 7]])

    # Check feature size is correct
    volume = sim.generate_signal(dimensions=dimensions,
                                 feature_coordinates=feature_coordinates,
                                 feature_type=['loop', 'cavity', 'sphere'],
                                 feature_size=[3],
                                 signal_magnitude=signal_magnitude)
    assert volume[5, 5, 5] == 0, "Loop is empty"
    assert volume[3, 3, 3] == 0, "Cavity is empty"
    assert volume[7, 7, 7] != 0, "Sphere is not empty"

    # Check feature size manipulation
    volume = sim.generate_signal(dimensions=dimensions,
                                 feature_coordinates=feature_coordinates,
                                 feature_type=['loop', 'cavity', 'sphere'],
                                 feature_size=[1],
                                 signal_magnitude=signal_magnitude)
    assert volume[5, 6, 6] == 0, "Loop is too big"
    assert volume[3, 5, 5] == 0, "Cavity is too big"
    assert volume[7, 9, 9] == 0, "Sphere is too big"

    # Check that out of bounds feature coordinates are corrected
    feature_coordinates = np.array([0, 2, dimensions[2]])
    x, y, z = sim._insert_idxs(feature_coordinates, feature_size[0],
                               dimensions)
    assert x[1] - x[0] == 2, "x min not corrected"
    assert y[1] - y[0] == 3, "y was corrected when it shouldn't be"
    assert z[1] - z[0] == 1, "z max not corrected"

    # Check that signal patterns are created
    feature_coordinates = np.array([[5, 5, 5]])
    volume = sim.generate_signal(dimensions=dimensions,
                                 feature_coordinates=feature_coordinates,
                                 feature_type=feature_type,
                                 feature_size=feature_size,
                                 signal_magnitude=signal_magnitude,
                                 signal_constant=0,
                                 )
    assert volume[4:7, 4:7, 4:7].std() > 0, "Signal is constant"
예제 #17
0
def test_generate_noise():

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

    # Generate a volume representing the location and quality of the signal
    volume_static = 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,
        tr_duration=tr_duration,
    )

    signal_function = sim.double_gamma_hrf(stimfunction=stimfunction, )

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

    # Create the noise volumes (using the default parameters)

    noise = sim.generate_noise(
        dimensions=dimensions,
        stimfunction=stimfunction,
        tr_duration=tr_duration,
    )

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

    Z_noise = sim._generate_noise_temporal(stimfunction, tr_duration, 1)
    noise = sim._generate_noise_temporal(stimfunction, tr_duration, 0)

    assert np.std(Z_noise) < np.std(noise), "Z scoring is not working"

    # Combine the signal and the noise
    volume = signal + noise

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

    noise = sim.generate_noise(dimensions=dimensions,
                               stimfunction=stimfunction,
                               tr_duration=tr_duration,
                               noise_strength=[0, 0, 0])

    assert np.sum(noise) == 0, "Noise strength could not be manipulated"
    assert np.std(noise) == 0, "Noise strength could not be manipulated"
예제 #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],
    )
예제 #19
0
def test_generate_signal():

    # Inputs for generate_signal
    dimensions = np.array([10, 10, 10])  # What is the size of the brain
    feature_size = [3]
    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,
    )

    assert np.all(volume.shape == dimensions), "Check signal shape"
    assert np.max(volume) == signal_magnitude, "Check signal magnitude"
    assert np.sum(volume > 0) == math.pow(feature_size[0],
                                          3), ("Check feature size")
    assert volume[5, 5, 5] == signal_magnitude, "Check signal location"
    assert volume[5, 5, 1] == 0, "Check noise location"

    feature_coordinates = np.array([[5, 5, 5], [3, 3, 3], [7, 7, 7]])

    # Check feature size is correct
    volume = sim.generate_signal(dimensions=dimensions,
                                 feature_coordinates=feature_coordinates,
                                 feature_type=['loop', 'cavity', 'sphere'],
                                 feature_size=[3],
                                 signal_magnitude=signal_magnitude)
    assert volume[5, 5, 5] == 0, "Loop is empty"
    assert volume[3, 3, 3] == 0, "Cavity is empty"
    assert volume[7, 7, 7] != 0, "Sphere is not empty"

    # Check feature size manipulation
    volume = sim.generate_signal(dimensions=dimensions,
                                 feature_coordinates=feature_coordinates,
                                 feature_type=['loop', 'cavity', 'sphere'],
                                 feature_size=[1],
                                 signal_magnitude=signal_magnitude)
    assert volume[5, 6, 6] == 0, "Loop is too big"
    assert volume[3, 5, 5] == 0, "Cavity is too big"
    assert volume[7, 9, 9] == 0, "Sphere is too big"

    # Check that out of bounds feature coordinates are corrected
    feature_coordinates = np.array([0, 2, dimensions[2]])
    x, y, z = sim._insert_idxs(feature_coordinates, feature_size[0],
                               dimensions)
    assert x[1] - x[0] == 2, "x min not corrected"
    assert y[1] - y[0] == 3, "y was corrected when it shouldn't be"
    assert z[1] - z[0] == 1, "z max not corrected"

    # Check that signal patterns are created
    feature_coordinates = np.array([[5, 5, 5]])
    volume = sim.generate_signal(
        dimensions=dimensions,
        feature_coordinates=feature_coordinates,
        feature_type=feature_type,
        feature_size=feature_size,
        signal_magnitude=signal_magnitude,
        signal_constant=0,
    )
    assert volume[4:7, 4:7, 4:7].std() > 0, "Signal is constant"
예제 #20
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,
        )
예제 #21
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],
                       )
예제 #22
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.double_gamma_hrf(
        stimfunction=stimfunction,
        tr_duration=tr_duration,
    )

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

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

    assert min(mask[mask > 0]) > 0.1, "Mask thresholding 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,
        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,
        mask=mask,
        noise_dict={
            'temporal_noise': 0,
            'sfnr': 10000
        },
    )

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

    assert temporal_noise <= 0.1, "Noise strength could not be manipulated"
예제 #23
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.double_gamma_hrf(stimfunction=stimfunction,
                                           tr_duration=tr_duration,
                                           )

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

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

    assert min(mask[mask > 0]) > 0.1, "Mask thresholding did not work"

    # Create the noise volumes (using the default parameters)
    noise = sim.generate_noise(dimensions=dimensions,
                               stimfunction=stimfunction,
                               tr_duration=tr_duration,
                               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=stimfunction,
                               tr_duration=tr_duration,
                               mask=mask,
                               noise_dict={'overall': 0},
                               )

    assert np.sum(noise) == 0, "Noise strength could not be manipulated"
    assert np.std(noise) == 0, "Noise strength could not be manipulated"