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
Beispiel #2
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
Beispiel #3
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.")
Beispiel #4
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
Beispiel #5
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
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")
import os
import matplotlib.pyplot as plt

v = 2
all_subj = [
    4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 19, 20, 21, 22, 23, 24, 25, 26,
    27, 28, 29, 30, 31, 32, 33, 34
]

for isubj in all_subj:
    for iblock in range(1, 3):

        try:
            fm = FOOOFGroup()
            fm.load(
                '/home/tpfeffer/pp/proc/src/pp_hh_fooof_result_lo_s%d_b%d_v%d.json'
                % (isubj, iblock, v))
            res_lo = fm.get_results()
            fm.load(
                '/home/tpfeffer/pp/proc/src/pp_hh_fooof_result_me_s%d_b%d_v%d.json'
                % (isubj, iblock, v))
            res_me = fm.get_results()
            fm.load(
                '/home/tpfeffer/pp/proc/src/pp_hh_fooof_result_hi_s%d_b%d_v%d.json'
                % (isubj, iblock, v))
            res_hi = fm.get_results()
        except:
            print('Could not find data...')
            continue

        # Frequencies: 0 - 40 Hz in steps of 0.25 Hz
#
# The only difference in saving FOOOFGroup, is that it saves out a 'jsonlines' file,
# in which each line is a JSON object, saving the specified data, settings, and results for
# a single power spectrum.
#

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

# Save out FOOOFGroup settings & results
fg.save('FG_results', save_settings=True, save_results=True)

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

# You can then reload this group
nfg = FOOOFGroup()
nfg.load('FG_results')

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

# Print results to check that the loaded group
nfg.print_results()

###################################################################################################
# Parallel Support
# ~~~~~~~~~~~~~~~~
#
# FOOOFGroup also has support for running in parallel, which can speed things up, since
# each power spectrum can be fit independently.
#
# The fit method includes an optional parameter ``n_jobs``, which if set at 1 (as default),
# will fit models linearly (one at a time, in order). If you set this parameter to some other