Esempio n. 1
0
    def content(self):
        """ Return report data if already in memory, otherwise read from fs. 
        Content is assumed to be a dictionary with conditions as keys 
        and reports as values """
        if self._content:
            return self._content

        template = self.name + '_' + r'([a-zA-Z1-9_]+)\.json'
        for fname in os.listdir(self._path):
            match = re.match(template, fname)
            if match:
                try:
                    key = str(match.group(1))
                except Exception as exc:
                    raise Exception("Unknown file name format.")

                if 'conditions' in self._params:
                    if key not in [str(elem) for elem 
                                   in self._params['conditions']]:
                        continue

                logging.getLogger('ui_logger').debug(
                        'Reading FOOOF file: ' + str(fname))

                fg = FOOOFGroup()
                fg.load(fname, self._path)
                self._content[key] = fg
        return self._content
Esempio n. 2
0
def create_report(subject, params):
    """ Collect parameters from the dialog and creates an FOOOFReport item
    """

    report_name = params['name']
    spectrum_name = params['spectrum_name']

    peak_width_low = params['peak_width_low']
    peak_width_high = params['peak_width_high']
    peak_threshold = params['peak_threshold']
    max_n_peaks = params['max_n_peaks']
    aperiodic_mode = params['aperiodic_mode']
    minfreq = params['minfreq']
    maxfreq = params['maxfreq']

    spectrum = subject.spectrum.get(spectrum_name)

    peak_width_limits = [peak_width_low, peak_width_high]
    peak_threshold = peak_threshold
    max_n_peaks = max_n_peaks
    aperiodic_mode = aperiodic_mode
    freq_range = [minfreq, maxfreq]

    # As meggie spectrum items can contain data for multiple conditions,
    # reports are also created for all those conditions, and dict is used.
    report_content = {}

    for key, data in spectrum.content.items():

        fg = FOOOFGroup(peak_width_limits=peak_width_limits,
                        peak_threshold=peak_threshold,
                        max_n_peaks=max_n_peaks,
                        aperiodic_mode=aperiodic_mode,
                        verbose=False)

        fg.fit(spectrum.freqs, data, freq_range)

        logging.getLogger('ui_logger').info('FOOOF results for ' +
                                            subject.name + ', ' +
                                            'condition: ' + key)
        # Log the textual report
        logging.getLogger('ui_logger').info(
            gen_results_fg_str(fg, concise=True))

        report_content[key] = fg

    params['conditions'] = list(spectrum.content.keys())
    params['ch_names'] = spectrum.ch_names

    fooof_directory = subject.fooof_report_directory

    # Create a container item that meggie understands,
    # and which holds the report data
    report = FOOOFReport(report_name, fooof_directory, params, report_content)

    # save report data to fs
    report.save_content()

    # and add the report item to subject
    subject.add(report, 'fooof_report')
Esempio n. 3
0
def test_plot_fg(tfg, skip_if_no_mpl):

    plot_fg(tfg)

    # Test error if no data available to plot
    tfg = FOOOFGroup()
    with raises(NoModelError):
        tfg.plot()
Esempio n. 4
0
def get_tfg():
    """Get a FOOOFGroup object, with some fit power spectra, for testing."""

    n_spectra = 2
    xs, ys = gen_group_power_spectra(n_spectra, *default_group_params())

    tfg = FOOOFGroup()
    tfg.fit(xs, ys)

    return tfg
Esempio n. 5
0
def test_fg_report(skip_if_no_mpl):
    """Check that running the top level model method runs."""

    n_spectra = 2
    xs, ys = gen_group_power_spectra(n_spectra, *default_group_params())

    tfg = FOOOFGroup()
    tfg.report(xs, ys)

    assert tfg
Esempio n. 6
0
def main():

    # Initialize a FOOOFGroup object to use
    fg = FOOOFGroup()

    # Create dictionary to store results
    exponent_results = np.zeros(shape=[N_SUBJECTS, NUM_BLOCKS, N_CHANNELS, 2])
    results = {}

    for band_name in BANDS.labels:
        results[band_name] = np.zeros(
            shape=[N_SUBJECTS, NUM_BLOCKS, N_CHANNELS, N_FEATS])

    for sub_index, subj_num in enumerate(SUBJ_NUMS):
        print('Current Subject Results: ' + str(subj_num))

        # load rest results data
        for block in range(0, NUM_BLOCKS):

            subj_file = str(subj_num) + "fooof_group_results" + str(
                block) + ".json"

            full_path = pjoin(RES_PATH, subj_file)

            print(full_path)

            if Path(full_path).is_file():
                fg.load(file_name=subj_file, file_path=RES_PATH)

            if not fg.group_results:
                print('Current Subject Results: ' + str(subj_num) +
                      ' block: ' + str(block) + ' failed to load.')
            else:
                print('Current Subject Results: ' + str(subj_num) +
                      ' block: ' + str(block) + ' successfully loaded.')

            for ind, res in enumerate(fg):

                exponent_results[sub_index, block,
                                 ind, :] = res.aperiodic_params

                for band_label, band_range in BANDS:
                    results[band_label][sub_index, block, ind,  :] = \
                        get_band_peak(res.peak_params, band_range, True)

    # Save out processed results
    with open(pjoin(PATHS.results_path, GROUP + '_' + STATE + '_exp.pkl'),
              'wb') as exp_output:
        pickle.dump(exponent_results, exp_output)

    with open(pjoin(PATHS.results_path, GROUP + '_' + STATE + '_results.pkl'),
              'wb') as output:
        pickle.dump(results, output)

    print("File Saved.")
Esempio n. 7
0
def test_plot_fg(tfg, skip_if_no_mpl):

    plot_fg(tfg,
            save_fig=True,
            file_path=TEST_PLOTS_PATH,
            file_name='test_plot_fg.png')

    # Test error if no data available to plot
    tfg = FOOOFGroup()
    with raises(NoModelError):
        tfg.plot()
Esempio n. 8
0
def test_fg_fit_par():
    """Test FOOOFGroup fit, running in parallel."""

    n_spectra = 2
    xs, ys = gen_group_power_spectra(n_spectra, *default_group_params())

    tfg = FOOOFGroup()
    tfg.fit(xs, ys, n_jobs=2)
    out = tfg.get_results()

    assert out
    assert len(out) == n_spectra
    assert isinstance(out[0], FOOOFResult)
    assert np.all(out[1].background_params)
Esempio n. 9
0
def combine_fooofs(fooofs):
    """Combine a group of FOOOF and/or FOOOFGroup objects into a single FOOOFGroup object.

    Parameters
    ----------
    fooofs : list of FOOOF objects
        FOOOF objects to be concatenated into a FOOOFGroup.

    Returns
    -------
    fg : FOOOFGroup object
        Resultant FOOOFGroup object created from input FOOOFs.
    """

    # Compare settings
    if not compare_info(fooofs, 'settings') or not compare_info(
            fooofs, 'data_info'):
        raise ValueError("These objects have incompatible settings or data," \
                         "and so cannot be combined.")

    # Initialize FOOOFGroup object, with settings derived from input objects
    fg = FOOOFGroup(*fooofs[0].get_settings(), verbose=fooofs[0].verbose)

    # Use a temporary store to collect spectra, because we only add them if consistently present
    temp_power_spectra = np.empty([0, len(fooofs[0].freqs)])

    # Add FOOOF results from each FOOOF object to group
    for f_obj in fooofs:
        # Add FOOOFGroup object
        if isinstance(f_obj, FOOOFGroup):
            fg.group_results.extend(f_obj.group_results)
            if f_obj.power_spectra is not None:
                temp_power_spectra = np.vstack(
                    [temp_power_spectra, f_obj.power_spectra])
        # Add FOOOF object
        else:
            fg.group_results.append(f_obj.get_results())
            if f_obj.power_spectrum is not None:
                temp_power_spectra = np.vstack(
                    [temp_power_spectra, f_obj.power_spectrum])

    # If the number of collected power spectra is consistent, then add them to object
    if len(fg) == temp_power_spectra.shape[0]:
        fg.power_spectra = temp_power_spectra

    # Add data information information
    fg.add_data_info(fooofs[0].get_data_info())

    return fg
Esempio n. 10
0
def test_fg():
    """Check FOOOFGroup object initializes properly."""

    # Note: doesn't assert fg itself, as it return false when group_results are empty
    #  This is due to the __len__ used in FOOOFGroup
    fg = FOOOFGroup()
    assert True
Esempio n. 11
0
def fit_fooof(freqs, powers, freq_range, init_kwargs, n_jobs):
    """A generalized FOOOF fit function to handle 1d, 2d, or 3d arrays.

    Parameters
    ----------
    powers : 1d, 2d, or 3d array
        Power values for a single spectrum, or group of power spectra.
        Power values are stored internally in log10 scale.
    freqs : 1d array
        Frequency values for the power spectra.
    freq_range : list of [float, float]
        Frequency range of the power spectra, as [lowest_freq, highest_freq].
    init_kwargs : dict
        FOOOF object initialization kwargs.
    n_jobs : int
        Specificy the number of jobs to run in parrallel for 2d or 3d arrays.

    Returns
    -------
    model : FOOOF, FOOOFGroup, or list of FOOOFGroup objects.
        A FOOOF object that has been fit. A 1d array will return a FOOOF objects, a 2d array will
        return a FOOOFGroup object, and a 3d array will return a list of FOOOFGroup objects.
    """

    if powers.ndim == 1:
        # Fit a 1d array
        model = FOOOF(**init_kwargs)
        model.fit(freqs, powers, freq_range=freq_range)

    elif powers.ndim == 2:
        # Fit a 2d array
        model = FOOOFGroup(**init_kwargs)
        model.fit(freqs, powers, freq_range=freq_range, n_jobs=n_jobs)

    elif powers.ndim == 3:
        # Fit a 3d array
        model = FOOOFGroup(**init_kwargs)
        model = fit_fooof_3d(model, freqs, powers, n_jobs=n_jobs)

    else:
        raise ValueError(
            'The power_spectrum argument must specify a 1d, 2d, or 3d array.')

    return model
def fit_fooof(epochs):
    # Estimate the PSD in the pre-stimulus window
    spectrum, freqs = psd_welch(epochs, tmin=-.5, tmax=0,
                                fmin=2, fmax=30, n_fft=126,
                                average='median',
                                n_per_seg=100, n_overlap=50)
    spectrum = np.mean(spectrum, axis=0)

    # Run FOOF
    fm = FOOOFGroup(peak_width_limits=(4.0, 12.0),
                    aperiodic_mode='fixed',
                    peak_threshold=1)

    # Set the frequency range to fit the model
    freq_range = [2, 30]

    # Fit the FOOOF model
    fm.fit(freqs, spectrum, freq_range)
    return fm.copy()
Esempio n. 13
0
def main():
	#Create dictionary to store results
	slope_results = np.zeros(shape=[n_subjects, num_blocks, n_channels, 2])
	results = {}
	for band_name in bands.keys():
		results[band_name] = np.zeros(shape=[n_subjects, num_blocks, n_channels, n_feats])

	# START LOOP
	# DATASET: PBA 
	for sub_index, sub_num in enumerate(subj_dat_num):
		print('Current Subject Results: ' + str(sub_num))
		
		# load rest results data
		for block in range(0, num_blocks):
			subj_file = str(sub_num) + "fooof_group_results" + str(block) + ".json"
			fg = FOOOFGroup()
			full_path = os.path.join(results_path, subj_file)
			path_check = Path(full_path)
			if path_check.is_file():
				fg.load(file_name=subj_file, file_path=results_path)
			if not fg.group_results:
				print('Current Subject Results: ' + str(sub_num) + " block:" + str(block) + " failed to load")
			else:
				print('Current Subject Results: ' +  str(sub_num) + " block" + str(block) + " successfully loaded")

			for ind, res in enumerate(fg):
				slope_results[sub_index, block, ind, :] = res.background_params
				for band_label, band_range in bands.items():
					results[band_label][sub_index, block, ind,  :] = get_band_peak(res.peak_params, band_range, True)

			
	# Save out matrices
	# Update to save out files using DATASET and STATE
	slope_output = open('..\\data\\analysis\\' + DATASET + "_" + STATE + "_slope_results.pkl" ,'wb')
	pickle.dump(slope_results, slope_output)
	slope_output.close()

	output = open('..\\data\\analysis\\' + DATASET + "_" + STATE + "_results.pkl" ,'wb')
	pickle.dump(results, output)
	output.close()
	print("File SAVED")
Esempio n. 14
0
def test_fit_fooof_3d(tfg):

    n_spectra = 2
    xs, ys = gen_group_power_spectra(n_spectra, *default_group_params())
    ys = np.stack([ys, ys], axis=0)

    tfg = FOOOFGroup()
    fgs = fit_fooof_3d(tfg, xs, ys)

    assert len(fgs) == 2
    for fg in fgs:
        assert fg
Esempio n. 15
0
def fooof_channel_rejection(eeg, psds, freqs, f_low, f_high, participant,
                            session_name):
    from scipy.stats import bayes_mvs

    n_bads = 0

    fooof_group = FOOOFGroup(max_n_peaks=6,
                             min_peak_amplitude=0.1,
                             peak_width_limits=[1, 12],
                             background_mode='knee')
    fooof_group.fit(freqs, psds, freq_range=[f_low, f_high / 2], n_jobs=-1)
    fooof_group_fig = fooof_group.plot(save_fig=True,
                                       file_name='FOOOF_group_' + participant +
                                       '_' + session_name,
                                       file_path=data_dir + '/results/')

    bg_slope = fooof_group.get_all_data('background_params', col='slope')

    mean_cntr, var_cntr, std_cntr = bayes_mvs(bg_slope, alpha=0.9)

    lower_slope = mean_cntr[1][0] - std_cntr[1][1]
    upper_slope = mean_cntr[1][1] + std_cntr[1][1]

    print('upper and lower slope range (mean, std)', lower_slope, upper_slope,
          np.mean(bg_slope), np.std(bg_slope))

    for channel_idx, slope in enumerate(bg_slope):
        if slope < lower_slope or slope > upper_slope:
            eeg.info['bads'].append(eeg.ch_names[channel_idx])
            n_bads += 1

    eeg.interpolate_bads(reset_bads=True)

    return eeg, n_bads
Esempio n. 16
0
def test_average_fg(tfg, tbands):

    nfm = average_fg(tfg, tbands)
    assert nfm

    # Test bad average method error
    with raises(ValueError):
        average_fg(tfg, tbands, avg_method='BAD')

    # Test no data available error
    ntfg = FOOOFGroup()
    with raises(NoModelError):
        average_fg(ntfg, tbands)
Esempio n. 17
0
def _load_fgs(data_path, folder, side, load):
    """Helper to load FOOOFGroups."""

    # Load the FOOOF analyses of the average
    pre, early, late = FOOOFGroup(), FOOOFGroup(), FOOOFGroup()
    pre.load('Group_' + load + '_' + side + '_Pre', pjoin(data_path, folder))
    early.load('Group_' + load + '_' + side +  '_Early', pjoin(data_path, folder))
    late.load('Group_' + load + '_' + side + '_Late', pjoin(data_path, folder))

    return pre, early, late
Esempio n. 18
0
def return_fg_fits(fg_file, fg_folder):
    """
    Return fitted parameters from FOOOFGroup, in the following order:
    aperiodic, peaks, error, r-squared.
    """
    fg = FOOOFGroup()
    fg.load(fg_file, fg_folder)
    aps = fg.get_params('aperiodic_params')  # get aperiodic parameters
    # need to resave the old fooof files for this loading to work
    #pks = fg.get_params('peak_params')
    pks = []
    err = fg.get_params('error')
    r2s = fg.get_params('r_squared')
    return aps, pks, err, r2s
Esempio n. 19
0
def test_fit_fooof_3d(tfg):

    n_groups = 2
    n_spectra = 3
    xs, ys = gen_group_power_spectra(n_spectra, *default_group_params())
    ys = np.stack([ys] * n_groups, axis=0)
    spectra_shape = np.shape(ys)

    tfg = FOOOFGroup()
    fgs = fit_fooof_3d(tfg, xs, ys)

    assert len(fgs) == n_groups == spectra_shape[0]
    for fg in fgs:
        assert fg
        assert len(fg) == n_spectra
        assert fg.power_spectra.shape == spectra_shape[1:]
Esempio n. 20
0
def fooofy(components, spectra, x_range, group=True):
    """
    fit FOOOF model on given spectrum and return params
        components: frequencies or PC dimensions
        spectra: PSDs or variance explained
        x_range: range for x axis of spectrum to fit
        group: whether to use FOOOFGroup or not
    """
    if group:
        fg = FOOOFGroup(max_n_peaks=0, aperiodic_mode='fixed', verbose=False) #initialize FOOOF object
    else:
        fg = FOOOF(max_n_peaks=0, aperiodic_mode='fixed', verbose=False) #initialize FOOOF object
    #print(spectra.shape, components.shape) #Use this line if things go weird

    fg.fit(components, spectra, x_range)
    exponents = fg.get_params('aperiodic_params', 'exponent')
    errors    = fg.get_params('error') # MAE
    offsets   = fg.get_params('aperiodic_params', 'offset')
    return exponents, errors, offsets
Esempio n. 21
0
def foof2mat_model():
    import sys
    from scipy.io import loadmat, savemat

    import sklearn
    from scipy import io
    import scipy
    import numpy as np
    from fooof import FOOOF
    import neurodsp
    import matplotlib.pyplot as plt
    import pacpy
    import h5py
    import matplotlib
    from matplotlib import lines

    import math

    from neurodsp import spectral

    # FOOOF imports: get FOOOF & FOOOFGroup objects
    from fooof import FOOOFGroup

    dat = hdf5storage.loadmat(str(sys.argv[1]))
    frq_ax = np.linspace(0, 500, 5001)  #dat["fx"][0]
    pwr_spectra = dat['avgpwr']  #dat["powall"]

    #pwr_spectra=x['x']
    # Initialize a FOOOFGroup object - it accepts all the same settings as FOOOF
    fg = FOOOFGroup(peak_threshold=7,
                    peak_width_limits=[3, 14])  #, aperiodic_mode='knee'

    frange = (1, 290)

    # Fit a group of power spectra with the .fit() method# Fit a
    #  The key difference (compared to FOOOF) is that it takes a 2D array of spectra
    #     This matrix should have the shape of [n_spectra, n_freqs]
    fg.fit(frq_ax, pwr_spectra, frange)

    slp = fg.get_params('aperiodic_params', 'exponent')
    off = fg.get_params('aperiodic_params', 'offset')
    r = fg.get_params('r_squared')

    savemat('slp.mat', {'slp': slp})
    savemat('off.mat', {'off': off})
    savemat('r.mat', {'r': r})
    return
Esempio n. 22
0
def fooofy(components, spectra, freq_range):
    """
    A FOOOF Function, gets exponent parameters
    """
    fg = FOOOFGroup(max_n_peaks=0, aperiodic_mode='fixed', verbose = False) #initialize FOOOF object

    #print(spectra.shape, components.shape) #Use this line if things go weird

    fg.fit(components, spectra, freq_range) # THIS IS WHERE YOU SAY WHICH FREQ RANGE TO FIT
    m_array = fg.get_params('aperiodic_params', 'exponent')
    r2_array = fg.get_params('r_squared') #correlation between components (freqs or PCs) and spectra (powers or eigvals)
    #fg.r_squared_
    return m_array, r2_array
Esempio n. 23
0
def foof2mat():
    import sys
    import hdf5storage

    import sklearn
    from scipy import io
    import scipy
    import numpy as np
    from fooof import FOOOF
    import neurodsp
    import matplotlib.pyplot as plt
    import pacpy
    import h5py
    import matplotlib
    from matplotlib import lines

    import math

    from neurodsp import spectral

    # FOOOF imports: get FOOOF & FOOOFGroup objects
    from fooof import FOOOFGroup

    dat = hdf5storage.loadmat(str(sys.argv[1]))
    frq_ax = np.linspace(0, 1000, 10001)  #dat["fx"][0]
    pwr_spectra = dat['avgpwr']  #dat["powall"]

    #pwr_spectra=x['x']
    # Initialize a FOOOFGroup object - it accepts all the same settings as FOOOF
    fg = FOOOFGroup(max_n_peaks=6, peak_threshold=4)

    frange = (30, 290)

    # Fit a group of power spectra with the .fit() method# Fit a
    #  The key difference (compared to FOOOF) is that it takes a 2D array of spectra
    #     This matrix should have the shape of [n_spectra, n_freqs]
    fg.fit(frq_ax, pwr_spectra, frange)

    slp = fg.get_all_data('background_params', 'slope')
    off = fg.get_all_data('background_params', 'intercept')
    r = fg.get_all_data('r_squared')

    scipy.io.savemat('slp.mat', {'slp': slp})
    scipy.io.savemat('off.mat', {'off': off})
    scipy.io.savemat('r.mat', {'r': r})
    return
Esempio n. 24
0
def test_fg_load():
    """Test load into FOOOFGroup. Note: loads files from test_core_io."""

    set_file_name = 'test_fooof_group_set'
    res_file_name = 'test_fooof_group_res'
    file_path = pkg.resource_filename(__name__, 'test_files')

    tfg = FOOOFGroup()

    tfg.load(set_file_name, file_path)
    assert tfg

    tfg.load(res_file_name, file_path)
    assert tfg
Esempio n. 25
0
def combine_fooofs(fooofs):
    """Combine a group of FOOOF and/or FOOOFGroup objects into a single FOOOFGroup object.

    Parameters
    ----------
    fooofs : list of FOOOF objects
        FOOOF objects to be concatenated into a FOOOFGroup.

    Returns
    -------
    fg : FOOOFGroup object
        Resultant FOOOFGroup object created from input FOOOFs.
    """

    # Compare settings
    if not compare_settings(fooofs) or not compare_data_info(fooofs):
        raise ValueError("These objects have incompatible settings or data," \
                         "and so cannot be combined.")

    # Initialize FOOOFGroup object, with settings derived from input objects
    #  Note: FOOOFGroup imported here to avoid an import circularity if imported at the top
    from fooof import FOOOFGroup
    fg = FOOOFGroup(**get_settings(fooofs[0]), verbose=fooofs[0].verbose)
    fg.power_spectra = np.empty([0, len(fooofs[0].freqs)])

    # Add FOOOF results from each FOOOF object to group
    for f_obj in fooofs:
        # Add FOOOFGroup object
        if isinstance(f_obj, FOOOFGroup):
            fg.group_results.extend(f_obj.group_results)
            fg.power_spectra = np.vstack(
                [fg.power_spectra, f_obj.power_spectra])
        # Add FOOOF object
        else:
            fg.group_results.append(f_obj.get_results())
            fg.power_spectra = np.vstack(
                [fg.power_spectra, f_obj.power_spectrum])

    # Add data information information
    for data_info in get_obj_desc()['freq_info']:
        setattr(fg, data_info, getattr(fooofs[0], data_info))
    fg.freqs = gen_freqs(fg.freq_range, fg.freq_res)

    return fg
Esempio n. 26
0
def compute_intsc(ts, numtps, srate, freq_range=(2, 50)):
    """
    Compute intrinsic neural timescale
    """

    # figure out tr in seconds
    tr = 1 / srate

    # grab electrode names
    colnames2use = ts.columns
    colnames2use = colnames2use.to_list()

    # normalize (divide all elements of the timeseries by the first value in the timeseries)
    ts = np.array(ts)
    for col_index, ts2use in enumerate(ts.T):
        ts[:, col_index] = np.divide(ts2use, ts2use[0])

    # compute spectrum via FFT
    f_axis = np.fft.fftfreq(numtps, tr)[:int(np.floor(numtps / 2))]
    psds = (np.abs(sp.fft(ts, axis=0))**2)[:len(f_axis)]

    # fit FOOOF & get knee parameter & convert to timescale
    fooof = FOOOFGroup(aperiodic_mode='knee', max_n_peaks=0, verbose=False)
    fooof.fit(freqs=f_axis, power_spectra=psds.T, freq_range=freq_range)
    fit_knee = fooof.get_params('aperiodic_params', 'knee')
    fit_exp = fooof.get_params('aperiodic_params', 'exponent')
    knee_freq, taus = convert_knee_val(fit_knee, fit_exp)

    # convert timescale into ms
    taus = taus * 1000

    # convert taus into a data frame
    taus_df = pd.DataFrame(taus.tolist(),
                           index=colnames2use,
                           columns=["intsc"])
    taus_df = taus_df.T

    return (taus_df)
Esempio n. 27
0
        psds)  #this lowers the frequency of loading .mat's, anyway..

for i in range(1, 290, 50):
    for j in range(1, 290, 50):
        allexps = []
        alloffset = []
        if not (j > (i + 2)):
            pass
        else:
            for k in range(1, patientcount + 1):
                freqs = freq_nparray[k - 1]
                psds = psds_nparray[k - 1]
                # ^Note: this also explicitly enforces type as float (type casts to float64, instead of float32)
                #  This is not strictly necessary for fitting, but is for saving out as json from FOOOF, if you want to do that
                fg = FOOOFGroup(peak_threshold=15,
                                peak_width_limits=[3.0, 14.0
                                                   ])  #, aperiodic_mode='knee'
                #fg.report(freqs, psds, [1, 290])
                #fg.fit(freqs,psds,[0.2,290])
                fg.fit(freqs, psds,
                       [i, j])  #this was all i could think of... ;_;
                #fg.plot()

                #reportname = str(k) + '_indiv result'
                #fg.save_report(reportname)

                #print(fg.group_results)

                exps = fg.get_params('aperiodic_params', 'exponent')
                allexps.append(exps)
Esempio n. 28
0
            first_half = np.mean(dat['pxx'][:, :,
                                            0:int(np.floor(sorted.size / 3))],
                                 axis=2)
            second_half = np.mean(
                dat['pxx'][:, :,
                           int(np.floor(sorted.size / 3)) + 1:sorted.size -
                           int(np.floor(sorted.size / 3))],
                axis=2)
            third_half = np.mean(
                dat['pxx'][:, :,
                           sorted.size - int(np.floor(sorted.size / 3)) + 1:],
                axis=2)

            fm = FOOOFGroup(peak_width_limits=[1, 8],
                            min_peak_height=0.05,
                            max_n_peaks=6)
            fm._maxfev = 30000

            freq_range = [3, 40]

            freqs = np.squeeze(dat['fxx'])
            aperiodic = np.zeros([2, np.shape(dat['pxx'])[1], 2])

            fm.fit(freqs, np.transpose(first_half), freq_range)
            fm.save(
                '/home/tpfeffer/pp/proc/src/pp_hh_task_fooof_result_lo_s%d_b%d_v%d'
                % (isubj, iblock, v),
                save_results=True,
                save_settings=False,
                save_data=True)
Esempio n. 29
0
def indiv_fooofcode():
    import sys
    import numpy as np
    from scipy.io import loadmat, savemat

    from fooof import FOOOFGroup
    import matplotlib.pyplot as plt

    patientcount = 16

    alloffset = []
    allr2 = []
    allexps = []
    allcfs = []

    for k in range(1,patientcount+1):
        matfile = 'indiv_' + str(k) + '.mat'
        data = loadmat(matfile)

        # Unpack data from dictionary, and squeeze numpy arrays
        freqs = np.squeeze(data['indiv_frq']).astype('float')
        psds = np.squeeze(data['indiv_pow']).astype('float')
        # ^Note: this also explicitly enforces type as float (type casts to float64, instead of float32)
        #  This is not strictly necessary for fitting, but is for saving out as json from FOOOF, if you want to do that
        fg = FOOOFGroup(peak_threshold=7,peak_width_limits=[3, 14])#, aperiodic_mode='knee'
        #fg.report(freqs, psds, [30, 300])
        #fg.fit(freqs,psds,[float(sys.argv[1]),float(sys.argv[2])])
        fg.fit(freqs,psds,[float(sys.argv[1]),float(sys.argv[2])])
        fg.plot()

        reportname = str(k) + '_indiv result'
        fg.save_report(reportname)

        #print(fg.group_results)

        r2 = fg.get_params('r_squared')
        allr2.append(r2)

        exps = fg.get_params('aperiodic_params', 'exponent')
        allexps.append(exps)

        centerfrq = fg.get_params('peak_params','CF')
        allcfs.append(centerfrq)

        offset = fg.get_params('aperiodic_params','offset')
        alloffset.append(offset)

        #knee = fg.get_params('aperiodic_params','knee')
        #savemat('knee_allpeeps.mat', {'knee' : knee})

    #NOW OUTSIDE OF BIG FORLOOP!
    #concat everythin.
    savemat('all_offset.mat',{'all_offset' : alloffset})
    savemat('all_r2.mat', {'all_r2' : allr2})
    savemat('all_exps.mat', {'all_exps' : allexps})
    savemat('all_cfs.mat',{'all_cfs' : allcfs}) #these are cell arrays! I didn't even mean for them to be but heck yea useful
Esempio n. 30
0
                dat = {}
                dat['fxx'] = tmp['outp'][0]['fxx'][0]
                dat['pxx'] = tmp['outp'][0]['pxx'][0]
            except:
                print("Error: File not found!")
                continue

            print('Processing S%d B%d M%d ...' % (isubj, iblock, m))

            freqs = np.squeeze(dat['fxx'])
            aper = np.empty([2, dat['pxx'].shape[1]])
            only_gauss = np.zeros([dat['pxx'].shape[0], dat['pxx'].shape[1]])
            full_gauss = np.zeros([dat['pxx'].shape[0], dat['pxx'].shape[1]])

            fm = FOOOFGroup(peak_width_limits=[1, 8],
                            min_peak_height=0.05,
                            max_n_peaks=6)
            fm._maxfev = 30000
            freq_range = [3, 40]
            fm.fit(freqs, np.transpose(dat['pxx']), freq_range)
            tmp = fm.get_results()

            for isens in range(0, dat['pxx'].shape[1]):
                aper[:, isens] = tmp[isens].aperiodic_params

            F = fm.freqs

            for isens in range(0, dat['pxx'].shape[1]):
                for i in range(0, len(tmp[isens].gaussian_params)):
                    c = tmp[isens].gaussian_params[i][0]
                    w = tmp[isens].gaussian_params[i][2]