Run the GFP analysis.
166914
def eeg_gfp(raws, gflp_method="GFPL1", scale=True, normalize=True, smoothing=None):
    

    # Load data if necessary
#    if isinstance(raws, str):
#        raws = load_object(filename=raws)

    # Initialize empty dict
    gfp = {}
    for participant in raws:

        gfp[participant] = {}
        for run in raws[participant]:

            # Generate empty dic
            gfp[participant][run] = {}

            # Assign raw object to raw
            raw = raws[participant][run].copy()

            # Check if MEG or EEG data
            if True in set(["MEG" in ch for ch in raw.info["ch_names"]]):
                meg = True
                eeg = False
            else:
                meg = False
                eeg = True

            # Save ECG channel
            try:
                gfp[participant][run]["ecg"] = np.array(raw.copy().pick_types(meg=False, eeg=False, ecg=True).to_data_frame())
            except ValueError:
                gfp[participant][run]["ecg"] = np.nan

            # Select appropriate channels
            data = raw.copy().pick_types(meg=meg, eeg=eeg)
            gfp[participant][run]["data_info"] = data.info
            gfp[participant][run]["data_freq"] = data.info["sfreq"]
            gfp[participant][run]["run_duration"] = len(data) / data.info["sfreq"]

            # Convert to numpy array
            data = np.array(data.to_data_frame())

            # find GFP peaks
            data, gfp_curve, gfp_peaks = eeg_gfp_peaks(data,
                                                 gflp_method=gflp_method,
                                                 smoothing=smoothing,
                                                 smoothing_window=100,
                                                 peak_method="wavelet",
                                                 normalize=normalize)
            # Store them
            gfp[participant][run]["microstates_times"] = gfp_peaks


            # Select brain state at peaks
            data_peaks = data[gfp_peaks]

            # Store the data and scale parameters
            if scale is True:
                gfp[participant][run]["data"] = z_score(data_peaks)
            else:
                gfp[participant][run]["data"] = data_peaks

            gfp[participant][run]["data_scale"] = scale
            gfp[participant][run]["data_normalize"] = normalize
            gfp[participant][run]["data_smoothing"] = smoothing



    return(gfp)
424881
def run(self):
        """"""
        if self.target_eff_nsamples and self.checkpoint_interval is None:
            raise ValueError("A checkpoint interval must be set if "
                             "targetting an effective number of samples")
        # get the starting number of samples:
        # "nsamples" keeps track of the number of samples we've obtained (if
        # target_eff_nsamples is not None, this is the effective number of
        # samples; otherwise, this is the total number of samples).
        # _lastclear is the number of iterations that the file already
        # contains (either due to sampler burn-in, or a previous checkpoint)
        if self.new_checkpoint:
            self._lastclear = 0
        else:
            with self.io(self.checkpoint_file, "r") as fp:
                self._lastclear = fp.niterations
        if self.target_eff_nsamples is not None:
            target_nsamples = self.target_eff_nsamples
            with self.io(self.checkpoint_file, "r") as fp:
                nsamples = fp.effective_nsamples
        elif self.target_niterations is not None:
            # the number of samples is the number of iterations times the
            # number of walkers
            target_nsamples = self.nwalkers * self.target_niterations
            nsamples = self._lastclear * self.nwalkers
        else:
            raise ValueError("must set either target_eff_nsamples or "
                             "target_niterations; see set_target")
        self._itercounter = 0
        # figure out the interval to use
        iterinterval = self.checkpoint_interval
        if iterinterval is None:
            iterinterval = self.target_niterations
        # run sampler until we have the desired number of samples
        while nsamples < target_nsamples:
            # adjust the interval if we would go past the number of iterations
            if self.target_niterations is not None and (
                    self.niterations + iterinterval > self.target_niterations):
                iterinterval = self.target_niterations - self.niterations
            # run sampler and set initial values to None so that sampler
            # picks up from where it left off next call
            logging.info("Running sampler for {} to {} iterations".format(
                self.niterations, self.niterations + iterinterval))
            # run the underlying sampler for the desired interval
            self.run_mcmc(iterinterval)
            # update the itercounter
            self._itercounter = self._itercounter + iterinterval
            # dump the current results
            self.checkpoint()
            # update nsamples for next loop
            if self.target_eff_nsamples is not None:
                nsamples = self.effective_nsamples
                logging.info("Have {} effective samples post burn in".format(
                    nsamples))
            else:
                nsamples += iterinterval * self.nwalkers
592893
def run(arguments):
    """"""
    parser = argparse.ArgumentParser(
        description="Exports font icons as PNG images."
    )
    parser.add_argument(
        '--list',
        action='store_true',
        help="list all available icon names and exit"
    )
    parser.add_argument(
        '--download',
        choices=[x for x in AVAILABLE_ICON_FONTS.keys()],
        help="download latest icon font and exit"
    )

    required_group = parser.add_argument_group("required arguments")
    required_group.add_argument(
        '--ttf',
        metavar='TTF-FILE',
        type=open,
        help='path to TTF file'
    )
    required_group.add_argument(
        '--css',
        metavar='CSS-FILE',
        type=open,
        help="path to CSS file"
    )

    exp_group = parser.add_argument_group("exporting icons")
    exp_group.add_argument(
        'icons',
        type=str,
        nargs='*',
        help="names of the icons to export (or 'ALL' for all icons)"
    )
    exp_group.add_argument(
        '--size',
        type=int,
        default=16,
        help="icon size in pixels (default: 16)"
    )
    exp_group.add_argument(
        '--scale',
        type=str,
        default='auto',
        help="scaling factor between 0 and 1, or 'auto' for automatic scaling "
             "(default: auto); be careful, as setting it may lead to icons "
             "being cropped"
    )
    exp_group.add_argument(
        '--color',
        type=str,
        default='black',
        help="color name or hex value (default: black)"
    )
    exp_group.add_argument(
        '--filename',
        type=str,
        help="name of the output file (without '.png' extension); "
             "it's used as a prefix if multiple icons are exported"
    )
    exp_group.add_argument(
        '--keep_prefix',
        default=False,
        action='store_true',
        help="do not remove common icon prefix "
             "(i.e. 'fa-arrow-right' instead of 'arrow-right')"
    )

    args = parser.parse_args(arguments)

    # Parse '--download' argument first
    if args.download:
        downloader = download_icon_font(args.download, os.getcwd())
        downloader.download_files()
        print("Icon font '{name}' successfully downloaded".format(
            name=args.download)
        )
        parser.exit()

    # If not '--download', then css and tff files are required
    if not args.css or not args.ttf:
        parser.error("You have to provide CSS and TTF files")

    icon_font = IconFont(css_file=args.css.name,
                         ttf_file=args.ttf.name,
                         keep_prefix=args.keep_prefix)
    args.css.close()
    args.ttf.close()

    # Then '--list'
    if args.list:
        for icon in icon_font.css_icons.keys():
            print(icon)
        parser.exit()

    # If not '--list' or '--download', parse passed icons
    selected_icons = list()
    if not args.icons:
        parser.error("You have to pass at least one icon name")
    elif args.icons == ['ALL']:
        selected_icons = icon_font.css_icons.keys()
    else:
        for icon in args.icons:
            if (args.keep_prefix and
                    not icon.startswith(icon_font.common_prefix)):
                # Prepend icon name with prefix
                icon = icon_font.common_prefix + icon
            elif (not args.keep_prefix and
                  icon.startswith(icon_font.common_prefix)):
                # Remove prefix from icon name
                icon = icon[len(icon_font.common_prefix):]

            # Check if given icon names exist
            if icon in icon_font.css_icons:
                selected_icons.append(icon)
            else:
                parser.error("Unknown icon name '{icon}'".format(icon=icon))

    # Parse filename and remove the extension if necessary
    given_filename = args.filename or ''
    if given_filename.lower().endswith('.png'):
        given_filename = given_filename[:-4]

    # Some fonts have empty values
    # (prefix only - which we remove - for common styles)
    selected_icons = list(filter(None, selected_icons))

    # Commence exporting
    for icon in selected_icons:
        if len(selected_icons) > 1:
            # Multiple icons - treat the filename option as name prefix
            filename = '{prefix}{icon}.png'.format(
                prefix=given_filename, icon=icon,
            )
        else:
            if given_filename:
                # Use the specified filename
                filename = given_filename + '.png'
            else:
                # Use icon name as filename
                filename = str(icon) + '.png'

        print("Exporting icon '{icon}' as '{filename}'"
              "({size}x{size} pixels)".format(icon=icon,
                                              filename=filename,
                                              size=args.size))

        icon_font.export_icon(icon=icon, filename=filename, size=args.size,
                              color=args.color, scale=args.scale)

    print()
    print("All done")
1322572
def setup_and_run_analysis(self):
        
        self.show_busy()
        # Read user's settings
        self.read_settings()
        # Prepare impact function from wizard dialog user input
        self.impact_function = self.prepare_impact_function()

        # Prepare impact function
        status, message = self.impact_function.prepare()
        message = basestring_to_message(message)
        # Check status
        if status == PREPARE_FAILED_BAD_INPUT:
            self.hide_busy()
            LOGGER.warning(tr(
                'The impact function will not be able to run because of the '
                'inputs.'))
            LOGGER.warning(message.to_text())
            send_error_message(self, message)
            return status, message
        if status == PREPARE_FAILED_BAD_CODE:
            self.hide_busy()
            LOGGER.warning(tr(
                'The impact function was not able to be prepared because of a '
                'bug.'))
            LOGGER.exception(message.to_text())
            send_error_message(self, message)
            return status, message

        # Start the analysis
        status, message = self.impact_function.run()
        message = basestring_to_message(message)
        # Check status
        if status == ANALYSIS_FAILED_BAD_INPUT:
            self.hide_busy()
            LOGGER.warning(tr(
                'The impact function could not run because of the inputs.'))
            LOGGER.warning(message.to_text())
            send_error_message(self, message)
            return status, message
        elif status == ANALYSIS_FAILED_BAD_CODE:
            self.hide_busy()
            LOGGER.warning(tr(
                'The impact function could not run because of a bug.'))
            LOGGER.exception(message.to_text())
            send_error_message(self, message)
            return status, message

        LOGGER.info(tr('The impact function could run without errors.'))

        # Add result layer to QGIS
        add_impact_layers_to_canvas(
            self.impact_function, iface=self.parent.iface)

        # Some if-s i.e. zoom, debug, hide exposure
        if self.zoom_to_impact_flag:
            self.iface.zoomToActiveLayer()

        qgis_exposure = (
            QgsProject.instance().mapLayer(
                self.parent.exposure_layer.id()))
        if self.hide_exposure_flag and qgis_exposure is not None:
            treeroot = QgsProject.instance().layerTreeRoot()
            treelayer = treeroot.findLayer(qgis_exposure.id())
            if treelayer:
                treelayer.setItemVisibilityChecked(False)

        # we only want to generate non pdf/qpt report
        html_components = [standard_impact_report_metadata_html]
        error_code, message = self.impact_function.generate_report(
            html_components)
        message = basestring_to_message(message)
        if error_code == ImpactReport.REPORT_GENERATION_FAILED:
            self.hide_busy()
            LOGGER.info(tr(
                'The impact report could not be generated.'))
            send_error_message(self, message)
            LOGGER.exception(message.to_text())
            return ANALYSIS_FAILED_BAD_CODE, message

        self.extent.set_last_analysis_extent(
            self.impact_function.analysis_extent,
            qgis_exposure.crs())

        # Hide busy
        self.hide_busy()
        # Setup gui if analysis is done
        self.setup_gui_analysis_done()
        return ANALYSIS_SUCCESS, None
782225
def run_analysis(args):
  """"""

  # Read the schema and input feature types
  schema_list = json.loads(
      file_io.read_file_to_string(args.schema_file))

  run_numerical_categorical_analysis(args, schema_list)

  # Also save a copy of the schema in the output folder.
  file_io.copy(args.schema_file,
               os.path.join(args.output_dir, SCHEMA_FILE),
               overwrite=True)
355120
def run(dataset):
    """"""
    config = _get_config()

    if dataset:
        _print("getting dataset from brains...")
        cprint("done", 'green')

        # check dataset cache for dataset
        # if not exists
        # r = requests.get('https://api.github.com/events', stream=True)
        # with open(filename, 'wb') as fd:
        #     for chunk in r.iter_content(chunk_size):
        #         fd.write(chunk)

    cprint('Running "%s"' % config["run"], 'green', attrs=("underline",))
    call(config["run"].split())
551456
def run(self, **kwargs):
        """"""
        if 'timestamp' not in kwargs:
            kwargs['timestamp'] = datetime.datetime.utcnow().isoformat()
        if 'version' not in kwargs:
            kwargs['version'] = "Not Defined" #bibcat.__version__
        # log.debug("kwargs: %s", pprint.pformat({k:v for k, v in kwargs.items()
        #                                         if k != "dataset"}))
        # log.debug("parents: %s", self.parents)
        for map_key, triple_map in self.triple_maps.items():
            if map_key not in self.parents:
                self.execute(triple_map, **kwargs)
235036
def analyze(self, analysis_set = '', analysis_directory = None):
        ''''''
        self.calculate_metrics(analysis_set, analysis_directory = analysis_directory)
        if self.generate_plots:
            self.plot(analysis_set, analysis_directory = analysis_directory)
724591
def run_analysis(self, argv):
        """"""
        args = self._parser.parse_args(argv)


        sedfile = args.sed_file

        if is_not_null(args.config):
            configfile = os.path.join(os.path.dirname(sedfile), args.config)
        else:
            configfile = os.path.join(os.path.dirname(sedfile), 'config.yaml')

        nbins = _get_enum_bins(configfile)

        first = args.seed
        last = first + args.nsims
        flist = [sedfile.replace("_SEED.fits", "_%06i.fits" % seed)
                 for seed in range(first, last)]
        outfile = args.outfile
        summaryfile = args.summaryfile


        outtable = fill_output_table(
            flist, "SED", CollectSED.collist, nbins=nbins)

        if is_not_null(outfile):
            outtable.write(outfile)

        if is_not_null(summaryfile):
            summary = summarize_sed_results(outtable)
            summary.write(summaryfile)
822718
def Main():
  
  argument_parser = argparse.ArgumentParser(description=(
      'Plots memory usage from profiling data.'))

  argument_parser.add_argument(
      '--output', dest='output_file', type=str, help=(
          'path of the output file to write the graph to instead of using '
          'interactive mode. The output format deduced from the extension '
          'of the filename.'))

  argument_parser.add_argument(
      'profile_path', type=str, help=(
          'path to the directory containing the profiling data.'))

  options = argument_parser.parse_args()

  if not os.path.isdir(options.profile_path):
    print('No such directory: {0:s}'.format(options.profile_path))
    return False

  names = ['time', 'queued', 'processing', 'to_merge', 'abandoned', 'total']

  glob_expression = os.path.join(options.profile_path, 'task_queue-*.csv.gz')
  for csv_file_name in glob.glob(glob_expression):
    data = numpy.genfromtxt(
        csv_file_name, delimiter='\t', dtype=None, encoding='utf-8',
        names=names, skip_header=1)

    pyplot.plot(data['time'], data['queued'], label='queued')
    pyplot.plot(data['time'], data['processing'], label='processing')
    pyplot.plot(data['time'], data['to_merge'], label='to merge')
    pyplot.plot(data['time'], data['abandoned'], label='abandoned')

  pyplot.title('Number of tasks over time')

  pyplot.xlabel('Time')
  pyplot.xscale('linear')

  pyplot.ylabel('Number of tasks')
  pyplot.yscale('linear')

  pyplot.legend()

  if options.output_file:
    pyplot.savefig(options.output_file)
  else:
    pyplot.show()

  return True
796898
def run():
    """"""
    import optparse

    parser = optparse.OptionParser(usage=r"%prog [<options>] [file ...]")
    parser.add_option(
        "-p", "--spread", type="float", default=3.0, help="Rainbow spread"
    )
    parser.add_option(
        "-F", "--freq", type="float", default=0.1, help="Rainbow frequency"
    )
    parser.add_option("-S", "--seed", type="int", default=0, help="Rainbow seed")
    parser.add_option(
        "-a",
        "--animate",
        action="store_true",
        default=False,
        help="Enable psychedelics",
    )
    parser.add_option(
        "-d", "--duration", type="int", default=12, help="Animation duration"
    )
    parser.add_option(
        "-s", "--speed", type="float", default=20.0, help="Animation speed"
    )
    parser.add_option(
        "-f",
        "--force",
        action="store_true",
        default=False,
        help="Force colour even when stdout is not a tty",
    )

    parser.add_option(
        "-3", action="store_const", dest="mode", const=8, help="Force 3 bit colour mode"
    )
    parser.add_option(
        "-4",
        action="store_const",
        dest="mode",
        const=16,
        help="Force 4 bit colour mode",
    )
    parser.add_option(
        "-8",
        action="store_const",
        dest="mode",
        const=256,
        help="Force 8 bit colour mode",
    )

    parser.add_option(
        "-c",
        "--charset-py2",
        default="utf-8",
        help="Manually set a charset to convert from, for python 2.7",
    )

    options, args = parser.parse_args()
    options.os = random.randint(0, 256) if options.seed == 0 else options.seed
    options.mode = options.mode or detect_mode()

    lolcat = LolCat(mode=options.mode)

    if not args:
        args = ["-"]

    for filename in args:
        if filename == "-":
            lolcat.cat(sys.stdin, options)
        else:
            try:
                with open(filename, "r") as handle:
                    lolcat.cat(handle, options)
            except IOError as error:
                sys.stderr.write(str(error) + "\n")
441504
def main():
    """"""
    # Load study, population, associations, and GoDag. Run GOEA.
    obj = GoeaCliFnc(GoeaCliArgs().args)
    # Reduce results to significant results (pval<value)
    results_specified = obj.get_results()
    # Print results in a flat list
    obj.prt_results(results_specified)
245612
def run_analysis(self, argv):
        """"""
        args = self._parser.parse_args(argv)

        if is_null(args.config):
            raise ValueError("Config yaml file must be specified")
        if is_null(args.rand_config):
            raise ValueError(
                "Random direction config yaml file must be specified")
        config = load_yaml(args.config)
        rand_config = load_yaml(args.rand_config)

        wcsgeom = self._make_wcsgeom_from_config(config)
        dir_dict = self._build_skydir_dict(wcsgeom, rand_config)

        if is_not_null(args.outfile):
            write_yaml(dir_dict, args.outfile)
1241072
def run_analysis(self, argv):
        """"""
        args = self._parser.parse_args(argv)

        if not HAVE_ST:
            raise RuntimeError(
                "Trying to run fermipy analysis, but don't have ST")

        if is_null(args.skydirs):
            skydir_dict = None
        else:
            skydir_dict = load_yaml(args.skydirs)

        gta = GTAnalysis(args.config,
                         logging={'verbosity': 3},
                         fileio={'workdir_regex': '\.xml$|\.npy$'})
        #gta.setup(overwrite=False)
        gta.load_roi(args.roi_baseline)
        gta.print_roi()

        basedir = os.path.dirname(args.config)
        # This should be a no-op, b/c it was done in the baseline analysis

        for profile in args.profiles:
            if skydir_dict is None:
                skydir_keys = [None]
            else:
                skydir_keys = sorted(skydir_dict.keys())

            for skydir_key in skydir_keys:
                if skydir_key is None:
                    pkey, psrc_name, pdict = build_profile_dict(basedir, profile)
                else:
                    skydir_val = skydir_dict[skydir_key]
                    pkey, psrc_name, pdict = build_profile_dict(basedir, profile)
                    pdict['ra'] = skydir_val['ra']
                    pdict['dec'] = skydir_val['dec']
                    pkey += "_%06i" % skydir_key

                outfile = "sed_%s.fits" % pkey

                # Add the source and get the list of correlated soruces
                correl_dict, test_src_name = add_source_get_correlated(gta, psrc_name, 
                                                                       pdict, correl_thresh=0.25, 
                                                                       non_null_src=args.non_null_src)

                # Write the list of correlated sources
                correl_yaml = os.path.join(basedir, "correl_%s.yaml" % pkey)
                write_yaml(correl_dict, correl_yaml)

                gta.free_sources(False)
                for src_name in correl_dict.keys():
                    gta.free_source(src_name, pars='norm')

                # build the SED
                if args.non_null_src:
                    gta.update_source(test_src_name, reoptimize=True)
                    gta.write_roi("base_%s"% pkey, make_plots=False)
                gta.sed(test_src_name, prefix=pkey, outfile=outfile, make_plots=args.make_plots)

                # remove the source
                gta.delete_source(test_src_name)
                # put the ROI back to how it was
                gta.load_xml(args.roi_baseline)

        return gta
1145740
def run(self):
        
        if self.stdout:
            sys.stdout.write("extracted json data:\n" + json.dumps(
                self.metadata, default=to_str) + "\n")
        else:
            extract_dist.class_metadata = self.metadata
166228
def run(self):
        """"""
        self.logger.info("Running with Python %s", sys.version.replace("\n", ""))
        self.logger.info("Running on platform %s", platform.platform())
        self.logger.info("Current cpu count is %d", multiprocessing.cpu_count())

        configuration = self.load_configuration()
        paths = [os.path.abspath(path) for path in Adapter(self.options).path]
        supported_extension = [
            ext.strip() for entry in configuration for ext in Adapter(entry).extension.split()]

        for path, path_and_filename, extension in Application.walk_files_for(paths, supported_extension):
            entry = Select(*configuration) \
                .where(lambda entry: extension in Adapter(entry).extension.split()) \
                .transform(lambda entry: Adapter(entry)) \
                .build()[0]
            # parsing file with regex to get loc and com values
            # 100 lines of code (total) with 50 lines of comments means: loc=50, com=50
            # the ratio would be then: 1.0
            loc, com = self.analyse(path_and_filename, entry.regex)
            ratio = float(com) / float(loc) if loc > 0 and com < loc else 1.0

            self.results.append({
                'type': entry.type,
                'file': path_and_filename.replace(path + '/', ''),
                'loc': loc,
                'com': com,
                'ratio': "%.2f" % ratio
            })
        # for the table we are mainly interested in ratio below defined threshold
        # (except you want to see all of your code: --show-all)
        ppresults = Select(*self.results).where(
            lambda entry: float(Adapter(entry).ratio) < Adapter(self.options).threshold or
            Adapter(self.options).show_all).build()

        # print out results in table format
        pprint(ppresults, keys=['ratio', 'loc', 'com', 'file', 'type'])

        if Adapter(self.options).average:
            all_ratio = Select(*self.results).transform(lambda entry: float(Adapter(entry).ratio)).build()
            avg_ratio = float(sum(all_ratio)) / float(len(all_ratio)) if len(all_ratio) > 0 else 1.0
            self.logger.info('average ratio is %.2f for %d files', avg_ratio, len(all_ratio))
            return avg_ratio >= Adapter(self.options).threshold

        # providing results (mainly for unittesting)
        return len(Select(*self.results).where(
            lambda entry: float(Adapter(entry).ratio) < Adapter(self.options).threshold).build()) == 0
18428
def main(fast=False):
    """"""
    print('Running benchmarks...\n')
    results = bench_run(fast=fast)
    bench_report(results)