Exemple #1
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"
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"
Exemple #3
0
    # 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,
                                           )

    # Multiply the HRF timecourse with the signal
    signal_cond = sim.apply_signal(signal_function=signal_function,
                                   volume_static=volume_static,
                                   )

    # Concatenate all the signal and function files
    if cond == 0:
        stimfunction = stimfunction_cond
        signal = signal_cond
    else:
        stimfunction = list(np.add(stimfunction, stimfunction_cond))
        signal += signal_cond

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

# Mask the signal to the shape of a brain (does not attenuate signal according
# to grey matter likelihood)
Exemple #4
0
    )

    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
    print('Creating signal volumes')
    signal_A = sim.apply_signal(signal_func_A, ROI_A)

    signal_B = sim.apply_signal(signal_func_B, ROI_B)

    # Combine the two signal timecourses
    signal = signal_A + signal_B

    # spare the true noise.
    #print('Generating noise')
    #noise = sim.generate_noise(dimensions=dimensions,
    #                           stimfunction_tr=np.zeros((numTRs, 1)),
    #                           tr_duration=int(trDuration),
    #                           template=template,
    #                           mask=mask_cherry,
    #                           noise_dict=noise_dict,
    #                           temporal_proportion = 0.5)
Exemple #5
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"
    # 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,
                                           )

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

    # Concatenate all the signal and function files
    if cond == 0:
        stimfunction = stimfunction_cond
        signal = signal_cond
    else:
        stimfunction = list(np.add(stimfunction, stimfunction_cond))
        signal += signal_cond

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

# Mask the signal to the shape of a brain (does not attenuate signal according
# to grey matter likelihood)
Exemple #7
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))
Exemple #8
0
                                           )

# 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,
                            )

# Combine the signals from the two conditions
signal = signal_A + signal_B

# Combine the stim functions
stimfunction = list(np.add(stimfunction_A, stimfunction_B))
stimfunction_tr = stimfunction[::int(tr_duration * temporal_res)]

# Generate the mask of the signal
mask, template = sim.mask_brain(signal, mask_threshold=0.2)
Exemple #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,
    )

    # 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,
        )
Exemple #10
0
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_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,
    ROI_A,
)

signal_B = sim.apply_signal(
    signal_func_B,
    ROI_B,
)

# Do you want to switch the location of the signal 75% of the way through through?
if switch_ROI > 0:

    # When does the switch occur?
    switch_point = int(numTRs * switch_ROI)

    part_1_A = sim.apply_signal(
        signal_func_A[:switch_point, :],
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],
                       )
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,
                         )
Exemple #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
Exemple #14
0
# Convolve the HRF with the stimulus sequence
signal_function_A = sim.double_gamma_hrf(
    stimfunction=stimfunction_A,
    tr_duration=tr_duration,
    temporal_resolution=temporal_res,
)

signal_function_B = sim.double_gamma_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_static=volume_static_A,
)

signal_B = sim.apply_signal(
    signal_function=signal_function_B,
    volume_static=volume_static_B,
)

# Combine the signals from the two conditions
signal = signal_A + signal_B

# Combine the stim functions
stimfunction = list(np.add(stimfunction_A, stimfunction_B))
stimfunction_tr = stimfunction[::int(tr_duration * temporal_res)]

# Generate the mask of the signal
Exemple #15
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, tr_duration=tr_duration
)

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

# Convolve the HRF with the stimulus sequence
signal_function_A = sim.double_gamma_hrf(stimfunction=stimfunction_A)

signal_function_B = sim.double_gamma_hrf(stimfunction=stimfunction_B)

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

signal_B = sim.apply_signal(signal_function=signal_function_B, volume_static=volume_static_B)

# Combine the signals from the two conditions
signal = signal_A + signal_B

# Combine the stim functions
stimfunction = list(np.add(stimfunction_A, stimfunction_B))

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

# Combine the signal and the noise
volume = signal + noise
Exemple #16
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"
    # 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
    signal_func_scaled = sim.compute_signal_change(signal_function=signal_func,
                                                   noise_function=noise_function,
                                                   noise_dict=noise_dict,
                                                   magnitude=[
                                                       scale_percentage],
                                                   method='PSC',
                                                   )
    
    # Multiply the voxels with signal by the HRF function
    brain_signal = sim.apply_signal(signal_function=signal_func_scaled,
                                    volume_signal=signal_mask,
                                    )

    # Convert any nans to 0s
    brain_signal[np.isnan(brain_signal)] = 0

    # Combine the signal and the noise
    brain = brain_signal + noise

    # Save the participant data
    if save_functional == 1 and resample == 0:

        print('Saving ' + nifti_save)
        brain_nifti = nibabel.Nifti1Image(brain, nii.affine)

        hdr = brain_nifti.header
Exemple #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],
    )
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
Exemple #20
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"
Exemple #21
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"
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"