Example #1
0
def test_calc_noise():

    # Inputs for functions
    onsets = [10, 30, 50, 70, 90]
    event_durations = [6]
    tr_duration = 2
    duration = 200
    tr_number = int(np.floor(duration / tr_duration))
    dimensions_tr = np.array([10, 10, 10, tr_number])

    # Preset the noise dict
    nd_orig = {
        'auto_reg_sigma': 0.6,
        'drift_sigma': 0.4,
        'snr': 30,
        'sfnr': 30,
        'max_activity': 1000,
        'fwhm': 4,
    }

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

    # Mask the volume to be the same shape as a brain
    mask, template = sim.mask_brain(dimensions_tr, mask_threshold=0.2)
    stimfunction_tr = stimfunction[::int(tr_duration * 100)]
    noise = sim.generate_noise(
        dimensions=dimensions_tr[0:3],
        stimfunction_tr=stimfunction_tr,
        tr_duration=tr_duration,
        template=template,
        mask=mask,
        noise_dict=nd_orig,
    )

    # Check that noise_system is being calculated correctly
    spatial_sd = 5
    temporal_sd = 5
    noise_system = sim._generate_noise_system(dimensions_tr, spatial_sd,
                                              temporal_sd)

    precision = abs(noise_system[0, 0, 0, :].std() - spatial_sd)
    assert precision < spatial_sd, 'noise_system calculated incorrectly'

    precision = abs(noise_system[:, :, :, 0].std() - temporal_sd)
    assert precision < spatial_sd, 'noise_system calculated incorrectly'

    # Calculate the noise
    nd_calc = sim.calc_noise(volume=noise, mask=mask)

    # How precise are these estimates
    precision = abs(nd_calc['snr'] - nd_orig['snr'])
    assert precision < nd_orig['snr'], 'snr calculated incorrectly'

    precision = abs(nd_calc['sfnr'] - nd_orig['sfnr'])
    assert precision < nd_orig['sfnr'], 'sfnr calculated incorrectly'
Example #2
0
def test_calc_noise():

    # Inputs for functions
    onsets = [10, 30, 50, 70, 90]
    event_durations = [6]
    tr_duration = 2
    duration = 200
    tr_number = int(np.floor(duration / tr_duration))
    dimensions_tr = np.array([10, 10, 10, tr_number])

    # Preset the noise dict
    nd_orig = {'auto_reg_sigma': 0.6,
               'drift_sigma': 0.4,
               'snr': 30,
               'sfnr': 30,
               'max_activity': 1000,
               'fwhm': 4,
               }

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

    # Mask the volume to be the same shape as a brain
    mask, template = sim.mask_brain(dimensions_tr, mask_threshold=0.2)
    stimfunction_tr = stimfunction[::int(tr_duration * 100)]
    noise = sim.generate_noise(dimensions=dimensions_tr[0:3],
                               stimfunction_tr=stimfunction_tr,
                               tr_duration=tr_duration,
                               template=template,
                               mask=mask,
                               noise_dict=nd_orig,
                               )

    # Check that noise_system is being calculated correctly
    spatial_sd = 5
    temporal_sd = 5
    noise_system = sim._generate_noise_system(dimensions_tr,
                                              spatial_sd,
                                              temporal_sd)

    precision = abs(noise_system[0, 0, 0, :].std() - spatial_sd)
    assert precision < spatial_sd, 'noise_system calculated incorrectly'

    precision = abs(noise_system[:, :, :, 0].std() - temporal_sd)
    assert precision < spatial_sd, 'noise_system calculated incorrectly'

    # Calculate the noise
    nd_calc = sim.calc_noise(volume=noise,
                             mask=mask)

    # How precise are these estimates
    precision = abs(nd_calc['snr'] - nd_orig['snr'])
    assert precision < nd_orig['snr'], 'snr calculated incorrectly'

    precision = abs(nd_calc['sfnr'] - nd_orig['sfnr'])
    assert precision < nd_orig['sfnr'], 'sfnr calculated incorrectly'
Example #3
0
def test_calc_noise():

    # Inputs for functions
    onsets = [10, 30, 50, 70, 90]
    event_durations = [6]
    tr_duration = 2
    duration = 100
    tr_number = int(np.floor(duration / tr_duration))
    dimensions_tr = np.array([10, 10, 10, tr_number])

    # Preset the noise dict
    nd_orig = {
        'auto_reg_sigma': 1,
        'drift_sigma': 0.5,
        'overall': 0.1,
        'snr': 30,
        'spatial_sigma': 0.15,
        'system_sigma': 1,
    }

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

    # Mask the volume to be the same shape as a brain
    mask = sim.mask_brain(dimensions_tr)
    noise = sim.generate_noise(
        dimensions=dimensions_tr[0:3],
        stimfunction=stimfunction,
        tr_duration=tr_duration,
        mask=mask,
        noise_dict=nd_orig,
    )

    # Calculate the noise
    nd_calc = sim.calc_noise(noise, mask)

    assert abs(nd_calc['overall'] - nd_orig['overall']) < 0.1, 'overall ' \
                                                               'calculated ' \
                                                               'incorrectly'

    assert abs(nd_calc['snr'] - nd_orig['snr']) < 10, 'snr calculated ' \
                                                      'incorrectly'

    assert abs(nd_calc['system_sigma'] - nd_orig['system_sigma']) < 1, \
        'snr calculated incorrectly'
Example #4
0
def test_calc_noise():

    # Inputs for functions
    onsets = [10, 30, 50, 70, 90]
    event_durations = [6]
    tr_duration = 2
    duration = 100
    tr_number = int(np.floor(duration / tr_duration))
    dimensions_tr = np.array([10, 10, 10, tr_number])

    # Preset the noise dict
    nd_orig = {
        'auto_reg_sigma': 0.6,
        'drift_sigma': 0.4,
        'temporal_noise': 5,
        'sfnr': 30,
        'max_activity': 1000,
        'fwhm': 4,
    }

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

    # Mask the volume to be the same shape as a brain
    mask = sim.mask_brain(dimensions_tr)
    stimfunction_tr = stimfunction[::int(tr_duration * 1000)]
    noise = sim.generate_noise(
        dimensions=dimensions_tr[0:3],
        stimfunction_tr=stimfunction_tr,
        tr_duration=tr_duration,
        mask=mask,
        noise_dict=nd_orig,
    )

    # Calculate the noise
    nd_calc = sim.calc_noise(noise, mask)

    # How precise are these estimates
    precision = abs(nd_calc['temporal_noise'] - nd_orig['temporal_noise'])
    assert precision < 1, 'temporal_noise calculated incorrectly'

    precision = abs(nd_calc['sfnr'] - nd_orig['sfnr'])
    assert precision < 5, 'sfnr calculated incorrectly'
Example #5
0
def test_calc_noise():

    # Inputs for functions
    onsets = [10, 30, 50, 70, 90]
    event_durations = [6]
    tr_duration = 2
    duration = 100
    tr_number = int(np.floor(duration / tr_duration))
    dimensions_tr = np.array([10, 10, 10, tr_number])

    # Preset the noise dict
    nd_orig = {'auto_reg_sigma': 1,
               'drift_sigma': 0.5,
               'overall': 0.1,
               'snr': 30,
               'spatial_sigma': 0.15,
               'system_sigma': 1,
               }

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

    # Mask the volume to be the same shape as a brain
    mask = sim.mask_brain(dimensions_tr)
    noise = sim.generate_noise(dimensions=dimensions_tr[0:3],
                               stimfunction=stimfunction,
                               tr_duration=tr_duration,
                               mask=mask,
                               noise_dict=nd_orig,
                               )

    # Calculate the noise
    nd_calc = sim.calc_noise(noise, mask)

    assert abs(nd_calc['overall'] - nd_orig['overall']) < 0.1, 'overall ' \
                                                               'calculated ' \
                                                               'incorrectly'

    assert abs(nd_calc['snr'] - nd_orig['snr']) < 10, 'snr calculated ' \
                                                      'incorrectly'

    assert abs(nd_calc['system_sigma'] - nd_orig['system_sigma']) < 1, \
        'snr calculated incorrectly'
Example #6
0
dimensions = volume.shape[0:3]
total_time = volume.shape[3] * tr_duration
stimfunction = sim.generate_stimfunction(onsets=[],
                                         event_durations=[0],
                                         total_time=total_time,
                                         )
stimfunction_tr = stimfunction[::int(tr_duration * temporal_res)]

# Calculate the mask
mask, template = sim.mask_brain(volume=volume,
                                mask_self=True,
                                )

# Calculate the noise parameters
noise_dict = sim.calc_noise(volume=volume,
                            mask=mask,
                            )

# Create the noise volumes (using the default parameters
noise = sim.generate_noise(dimensions=dimensions,
                           tr_duration=tr_duration,
                           stimfunction_tr=stimfunction_tr,
                           template=template,
                           mask=mask,
                           noise_dict=noise_dict,
                           )

# Create a nifti brain
brain_noise = nibabel.Nifti1Image(noise, affine_matrix)
nibabel.save(brain_noise, 'examples/utils/example2.nii')  # Save
Example #7
0
# Save the mask if the name is given
if output_mask_name is not None:
    print('Saving ' + output_mask_name)
    nibabel.save(nii, output_mask_name)

# Calculate the noise parameters
if input_noise_dict_name is None or path.exists(input_noise_dict_name) == \
        False:
    print('Making ' + input_noise_dict_name)
    noise_dict = {
        'voxel_size': [dimsize[0], dimsize[1], dimsize[2]],
        'matched': match_noise
    }
    noise_dict = sim.calc_noise(
        volume=real_brain,
        mask=mask,
        template=template,
        noise_dict=noise_dict,
    )

    # Save the file
    if input_noise_dict_name is not None:
        with open(input_noise_dict_name, 'w') as f:
            f.write(str(noise_dict))

else:

    # Load the file name instead
    with open(input_noise_dict_name, 'r') as f:
        noise_dict = f.read()

    print('Loading ' + input_noise_dict_name)
Example #8
0
def test_calc_noise():

    # Inputs for functions
    onsets = [10, 30, 50, 70, 90]
    event_durations = [6]
    tr_duration = 2
    duration = 200
    temporal_res = 100
    tr_number = int(np.floor(duration / tr_duration))
    dimensions_tr = np.array([10, 10, 10, tr_number])

    # Preset the noise dict
    nd_orig = sim._noise_dict_update({})

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

    # Mask the volume to be the same shape as a brain
    mask, template = sim.mask_brain(dimensions_tr, mask_self=None)
    stimfunction_tr = stimfunction[::int(tr_duration * temporal_res)]

    nd_orig['matched'] = 0
    noise = sim.generate_noise(
        dimensions=dimensions_tr[0:3],
        stimfunction_tr=stimfunction_tr,
        tr_duration=tr_duration,
        template=template,
        mask=mask,
        noise_dict=nd_orig,
    )

    # Check the spatial noise match
    nd_orig['matched'] = 1
    noise_matched = sim.generate_noise(dimensions=dimensions_tr[0:3],
                                       stimfunction_tr=stimfunction_tr,
                                       tr_duration=tr_duration,
                                       template=template,
                                       mask=mask,
                                       noise_dict=nd_orig,
                                       iterations=[50, 0])

    # Calculate the noise parameters from this newly generated volume
    nd_new = sim.calc_noise(noise, mask, template)
    nd_matched = sim.calc_noise(noise_matched, mask, template)

    # Check the values are reasonable"
    assert nd_new['snr'] > 0, 'snr out of range'
    assert nd_new['sfnr'] > 0, 'sfnr out of range'
    assert nd_new['auto_reg_rho'][0] > 0, 'ar out of range'

    # Check that the dilation increases SNR
    no_dilation_snr = sim._calc_snr(
        noise_matched,
        mask,
        dilation=0,
        reference_tr=tr_duration,
    )

    assert nd_new['snr'] > no_dilation_snr, "Dilation did not increase SNR"

    # Check that template size is in bounds
    with pytest.raises(ValueError):
        sim.calc_noise(noise, mask, template * 2)

    # Check that Mask is set is checked
    with pytest.raises(ValueError):
        sim.calc_noise(noise, None, template)

    # Check that it can deal with missing noise parameters
    temp_nd = sim.calc_noise(noise, mask, template, noise_dict={})
    assert temp_nd['voxel_size'][0] == 1, 'Default voxel size not set'

    temp_nd = sim.calc_noise(noise, mask, template, noise_dict=None)
    assert temp_nd['voxel_size'][0] == 1, 'Default voxel size not set'

    # Check that the fitting worked
    snr_diff = abs(nd_orig['snr'] - nd_new['snr'])
    snr_diff_match = abs(nd_orig['snr'] - nd_matched['snr'])
    assert snr_diff > snr_diff_match, 'snr fit incorrectly'

    # Test that you can generate rician and exponential noise
    sim._generate_noise_system(
        dimensions_tr,
        1,
        1,
        spatial_noise_type='exponential',
        temporal_noise_type='rician',
    )

    # Check the temporal noise match
    nd_orig['matched'] = 1
    noise_matched = sim.generate_noise(dimensions=dimensions_tr[0:3],
                                       stimfunction_tr=stimfunction_tr,
                                       tr_duration=tr_duration,
                                       template=template,
                                       mask=mask,
                                       noise_dict=nd_orig,
                                       iterations=[0, 50])

    nd_matched = sim.calc_noise(noise_matched, mask, template)

    sfnr_diff = abs(nd_orig['sfnr'] - nd_new['sfnr'])
    sfnr_diff_match = abs(nd_orig['sfnr'] - nd_matched['sfnr'])
    assert sfnr_diff > sfnr_diff_match, 'sfnr fit incorrectly'

    ar1_diff = abs(nd_orig['auto_reg_rho'][0] - nd_new['auto_reg_rho'][0])
    ar1_diff_match = abs(nd_orig['auto_reg_rho'][0] -
                         nd_matched['auto_reg_rho'][0])
    assert ar1_diff > ar1_diff_match, 'AR1 fit incorrectly'

    # Check that you can calculate ARMA for a single voxel
    vox = noise[5, 5, 5, :]
    arma = sim._calc_ARMA_noise(
        vox,
        None,
        sample_num=2,
    )
    assert len(arma) == 2, "Two outputs not given by ARMA"
Example #9
0
def test_calc_noise():

    # Inputs for functions
    onsets = [10, 30, 50, 70, 90]
    event_durations = [6]
    tr_duration = 2
    duration = 200
    temporal_res = 100
    tr_number = int(np.floor(duration / tr_duration))
    dimensions_tr = np.array([10, 10, 10, tr_number])

    # Preset the noise dict
    nd_orig = sim._noise_dict_update({})

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

    # Mask the volume to be the same shape as a brain
    mask, template = sim.mask_brain(dimensions_tr, mask_self=None)
    stimfunction_tr = stimfunction[::int(tr_duration * temporal_res)]

    nd_orig['matched'] = 0
    noise = sim.generate_noise(dimensions=dimensions_tr[0:3],
                               stimfunction_tr=stimfunction_tr,
                               tr_duration=tr_duration,
                               template=template,
                               mask=mask,
                               noise_dict=nd_orig,
                               )

    # Check the spatial noise match
    nd_orig['matched'] = 1
    noise_matched = sim.generate_noise(dimensions=dimensions_tr[0:3],
                                       stimfunction_tr=stimfunction_tr,
                                       tr_duration=tr_duration,
                                       template=template,
                                       mask=mask,
                                       noise_dict=nd_orig,
                                       iterations=[50, 0]
                                       )

    # Calculate the noise parameters from this newly generated volume
    nd_new = sim.calc_noise(noise, mask, template)
    nd_matched = sim.calc_noise(noise_matched, mask, template)

    # Check the values are reasonable"
    assert nd_new['snr'] > 0, 'snr out of range'
    assert nd_new['sfnr'] > 0, 'sfnr out of range'
    assert nd_new['auto_reg_rho'][0] > 0, 'ar out of range'

    # Check that the dilation increases SNR
    no_dilation_snr = sim._calc_snr(noise_matched,
                                    mask,
                                    dilation=0,
                                    reference_tr=tr_duration,
                                    )

    assert nd_new['snr'] > no_dilation_snr, "Dilation did not increase SNR"

    # Check that template size is in bounds
    with pytest.raises(ValueError):
        sim.calc_noise(noise, mask, template * 2)

    # Check that Mask is set is checked
    with pytest.raises(ValueError):
        sim.calc_noise(noise, None, template)

    # Check that it can deal with missing noise parameters
    temp_nd = sim.calc_noise(noise, mask, template, noise_dict={})
    assert temp_nd['voxel_size'][0] == 1, 'Default voxel size not set'

    temp_nd = sim.calc_noise(noise, mask, template, noise_dict=None)
    assert temp_nd['voxel_size'][0] == 1, 'Default voxel size not set'

    # Check that the fitting worked
    snr_diff = abs(nd_orig['snr'] - nd_new['snr'])
    snr_diff_match = abs(nd_orig['snr'] - nd_matched['snr'])
    assert snr_diff > snr_diff_match, 'snr fit incorrectly'

    # Test that you can generate rician and exponential noise
    sim._generate_noise_system(dimensions_tr,
                               1,
                               1,
                               spatial_noise_type='exponential',
                               temporal_noise_type='rician',
                               )

    # Check the temporal noise match
    nd_orig['matched'] = 1
    noise_matched = sim.generate_noise(dimensions=dimensions_tr[0:3],
                                       stimfunction_tr=stimfunction_tr,
                                       tr_duration=tr_duration,
                                       template=template,
                                       mask=mask,
                                       noise_dict=nd_orig,
                                       iterations=[0, 50]
                                       )

    nd_matched = sim.calc_noise(noise_matched, mask, template)

    sfnr_diff = abs(nd_orig['sfnr'] - nd_new['sfnr'])
    sfnr_diff_match = abs(nd_orig['sfnr'] - nd_matched['sfnr'])
    assert sfnr_diff > sfnr_diff_match, 'sfnr fit incorrectly'

    ar1_diff = abs(nd_orig['auto_reg_rho'][0] - nd_new['auto_reg_rho'][0])
    ar1_diff_match = abs(nd_orig['auto_reg_rho'][0] - nd_matched[
        'auto_reg_rho'][0])
    assert ar1_diff > ar1_diff_match, 'AR1 fit incorrectly'

    # Check that you can calculate ARMA for a single voxel
    vox = noise[5, 5, 5, :]
    arma = sim._calc_ARMA_noise(vox,
                                None,
                                sample_num=2,
                                )
    assert len(arma) == 2, "Two outputs not given by ARMA"
Example #10
0
stimfunction = sim.generate_stimfunction(
    onsets=[],
    event_durations=[0],
    total_time=total_time,
)
stimfunction_tr = stimfunction[::int(tr_duration * temporal_res)]

# Calculate the mask
mask = sim.mask_brain(
    volume=volume,
    mask_self=True,
)

# Calculate the noise parameters
noise_dict = sim.calc_noise(
    volume=volume,
    mask=mask,
)

# Create the noise volumes (using the default parameters
noise = sim.generate_noise(
    dimensions=dimensions,
    tr_duration=tr_duration,
    stimfunction_tr=stimfunction_tr,
    mask=mask,
    noise_dict=noise_dict,
)

# Create a nifti brain
brain_noise = nibabel.Nifti1Image(noise, affine_matrix)
nibabel.save(brain_noise, 'examples/utils/example2.nii')  # Save