Example #1
0
def fooofmodel():
    import sys
    import numpy as np
    from scipy.io import loadmat, savemat

    from fooof import FOOOFGroup
    import matplotlib.pyplot as plt

    data = loadmat('ModelPowSpctraForFOOOF.mat')

    # Unpack data from dictionary, and squeeze numpy arrays
    freqs = np.squeeze(data['fx']).astype('float')
    psds = np.squeeze(data['avgpwr']).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

    # Transpose power spectra, to have the expected orientation for FOOOF
    #psds = psds.T
    fg = FOOOFGroup(peak_threshold=7,
                    peak_width_limits=[3, 14])  #, aperiodic_mode='knee'
    #fg.report(freqs, psds, [1, 290])
    #fg.fit(freqs,psds,[0.2,290])
    fg.fit(freqs, psds, [1, 290])
    fg.plot()
    fg.save_report('modelfits')

    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
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
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
Example #4
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
Example #5
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
Example #6
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
Example #7
0
def fooof_perps():
    import sys
    import numpy as np
    from scipy.io import loadmat, savemat

    from fooof import FOOOFGroup
    import matplotlib.pyplot as plt

    data = loadmat('perps_proper.mat')

    # Unpack data from dictionary, and squeeze numpy arrays
    freqs = np.squeeze(data['fx_regular']).astype('float')
    psds = np.squeeze(data['powa_regular']).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

    # Transpose power spectra, to have the expected orientation for FOOOF
    #psds = psds.T
    fg = FOOOFGroup(peak_threshold=4,peak_width_limits=[3, 14])#, aperiodic_mode='knee'
    #fg.report(freqs, psds, [1, 290])
    #fg.fit(freqs,psds,[0.2,290])
    fg.fit(freqs,psds,[float(sys.argv[1]),float(sys.argv[2])])
    fg.plot()
    fg.save_report('perps')

    #print(fg.group_results)


    r2 = fg.get_params('r_squared')
    savemat('p_r2.mat', {'p_r2' : r2})

    exps = fg.get_params('aperiodic_params', 'exponent')
    centerfrq = fg.get_params('peak_params','CF')
    peakheight = fg.get_params('peak_params','PW')
    savemat('p_exps.mat', {'p_exps' : exps})
    savemat('p_cfs.mat', {'p_cfs' : centerfrq})
    savemat('p_peakheight.mat',{'p_peakheight' : peakheight})

    offset = fg.get_params('aperiodic_params','offset')
    savemat('p_offs.mat', {'p_offs' : offset})
Example #8
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)
Example #9
0
                #  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)

                offset = fg.get_params('aperiodic_params', 'offset')
                alloffset.append(offset)
            #ok, so for each range, we have 16 sets ofx exponents and 16 sets of y offsets.
            exp_r2 = 0
            off_r2 = 0
            for w in range(0, 19):
                #print(w)
                expy = allexps[w]
                offy = alloffset[w]
                slope, intercept, exp_r, p_value, std_err = stats.linregress(
                    dp[0, w], expy)
                exp_r2 += exp_r**2
                slope, intercept, off_r, p_value, std_err = stats.linregress(
Example #10
0
#
# This method works the same as in the :class:`~fooof.FOOOF` object, and lets you extract
# specific results by specifying a field, as a string, and (optionally) a specific column
# to extract.
#
# Since the :class:`~fooof.FOOOFGroup` object collects results from across multiple model fits,
# you should always use :func:`~fooof.FOOOFGroup.get_params` to access model parameters.
# The results attributes introduced with the FOOOF object (such as `aperiodic_params_` or
# `peak_params_`) do not store results across the group, as they are defined for individual
# model fits (and used internally as such by the FOOOFGroup object).
#

###################################################################################################

# Extract aperiodic parameters
aps = fg.get_params('aperiodic_params')
exps = fg.get_params('aperiodic_params', 'exponent')

# Extract peak parameters
peaks = fg.get_params('peak_params')
cfs = fg.get_params('peak_params', 'CF')

# Extract goodness-of-fit metrics
errors = fg.get_params('error')
r2s = fg.get_params('r_squared')

###################################################################################################

# The full list of parameters you can extract is available in the documentation of `get_params`
print(fg.get_params.__doc__)
# In the :class:`~fooof.FOOOFGroup` report we can get a sense of the overall performance
# by looking at the information about the goodness of fit metrics, and also things like
# the distribution of peaks.
#
# However, while these metrics can help identify if fits are, on average, going well (or not)
# they don't necessarily indicate the source of any problems.
#
# To do so, we will typically still want to visualize some example fits, to see
# what is happening. To do so, next we will find which fits have the most error,
# and select these fits from the :class:`~fooof.FOOOFGroup` object to visualize.
#

###################################################################################################

# Find the index of the worst model fit from the group
worst_fit_ind = np.argmax(fg.get_params('error'))

# Extract this model fit from the group
fm = fg.get_fooof(worst_fit_ind, regenerate=True)

###################################################################################################

# Check results and visualize the extracted model
fm.print_results()
fm.plot()

###################################################################################################
#
# You can also loop through all the results in a :class:`~fooof.FOOOFGroup`, extracting
# all fits that meet some criterion that makes them worth checking.
#
Example #12
0
###################################################################################################

# Compare the peak fits of alpha peaks between groups
plot_peak_fits([g1_alphas, g2_alphas], labels=labels, colors=colors)

###################################################################################################
# Aperiodic Components
# --------------------
#
# Next, let's have a look at the aperiodic components.
#

###################################################################################################

# Extract the aperiodic parameters for each group
aps1 = fg1.get_params('aperiodic_params')
aps2 = fg2.get_params('aperiodic_params')

###################################################################################################
# Plotting Aperiodic Parameters
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# The :func:`~.plot_aperiodic_params` function takes in
# aperiodic parameters, and visualizes them, as:
#
# - Offset on the x-axis
# - Exponent on the y-axis
#

###################################################################################################
Example #13
0
###################################################################################################

# Fit the 3D matrix of power spectra
fgs = fit_fooof_group_3d(fg, fs, spectra)

###################################################################################################

# This returns a list of FOOOFGRoup objects
print(fgs)

###################################################################################################

# Compare the aperiodic exponent results across conditions
for ind, fg in enumerate(fgs):
    print("Aperiodic exponent for condition {} is {:1.4f}".format(
        ind, np.mean(fg.get_params('aperiodic_params', 'exponent'))))

###################################################################################################
# combine_fooofs
# --------------
#
# Depending what the organization of the data is, you might also want to collapse
# FOOOF models dimensions that have been fit.
#
#
# To do so, you can use the :func:`combine_fooofs` function, which takes
# a list of FOOOF or FOOOFGroup objects, and combines them together into
# a single FOOOFGroup object (assuming the settings and data definitions
# are consistent to do so).

###################################################################################################
Example #14
0
    axes[ind].set_title('biggest ' + label + ' peak', {'fontsize': 16})

###################################################################################################
# Plotting Aperiodic Topographies
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Next up, let's plot the topography of the aperiodic exponent.
#
# To do so, we can simply extract the aperiodic parameters from our power spectrum models,
# and plot them.
#

###################################################################################################

# Extract aperiodic exponent values
exps = fg.get_params('aperiodic_params', 'exponent')

###################################################################################################

# Plot the topography of aperiodic exponents
plot_topomap(exps, raw.info, cmap=cm.viridis, contours=0)

###################################################################################################
#
# In the topography above, we can see that there is a fair amount of variation
# across the scalp in terms of aperiodic exponent value, and there seems to be some
# spatial structure to it.
#
# To visualize how much the exponent values vary, we can again plot some example power
# spectra, in this case extracting those with the highest and lower exponent values.
#
Example #15
0
    aperiodic_params=param_sampler([[20, 2], [35, 1.5]]),
    gaussian_params=param_sampler([[], [10, 0.5, 2]]))

###################################################################################################

# Fit FOOOF models across the group of simulated power spectra
fg = FOOOFGroup(peak_width_limits=[1, 8],
                min_peak_height=0.05,
                max_n_peaks=6,
                verbose=False)
fg.fit(freqs, spectra)

###################################################################################################

# Get all alpha oscillations from a FOOOFGroup object
alphas = get_band_peak_group(fg.get_params('peak_params'), alpha_band, len(fg))

###################################################################################################

# Check out some of the alpha data
print(alphas[0:5, :])

###################################################################################################
#
# Note that the design of :func:`get_band_peak_group` is such that it will retain
# information regarding which oscillation came from with model fit.
#
# To do so, it's output is organized such that each row corresponds to a specific
# model fit, such that the matrix returned is size [n_fits, 3].
#
# For this to work, at most 1 peak is extracted for each model fit within the specified band.