:param oqparam:
        an :class:`openquake.commonlib.oqvalidation.OqParam` instance
    :param fnames:
        a space-separated list of .csv relative filenames
    :returns:
        the site mesh and the hazard curves read by the .csv files
552245
def get_pmap_from_csv(oqparam, fnames):
    
    if not oqparam.imtls:
        oqparam.set_risk_imtls(get_risk_models(oqparam))
    if not oqparam.imtls:
        raise ValueError('Missing intensity_measure_types_and_levels in %s'
                         % oqparam.inputs['job_ini'])

    dic = {wrapper.imt: wrapper.array
           for wrapper in map(writers.read_composite_array, fnames)}
    array = dic[next(iter(dic))]
    mesh = geo.Mesh(array['lon'], array['lat'])
    num_levels = sum(len(imls) for imls in oqparam.imtls.values())
    data = numpy.zeros((len(mesh), num_levels))
    level = 0
    for im in oqparam.imtls:
        arr = dic[im]
        for poe in arr.dtype.names[3:]:
            data[:, level] = arr[poe]
            level += 1
        for field in ('lon', 'lat', 'depth'):  # sanity check
            numpy.testing.assert_equal(arr[field], array[field])
    return mesh, ProbabilityMap.from_array(data, range(len(mesh)))
538104
def iofunctions(self):
        """"""
        lines = Lines()
        for func in ('open_files', 'close_files', 'load_data', 'save_data'):
            if ((func == 'load_data') and
                    (getattr(self.model.sequences, 'inputs', None) is None)):
                continue
            if ((func == 'save_data') and
                ((getattr(self.model.sequences, 'fluxes', None) is None) and
                 (getattr(self.model.sequences, 'states', None) is None))):
                continue
            print('            . %s' % func)
            nogil = func in ('load_data', 'save_data')
            idx_as_arg = func == 'save_data'
            lines.add(1, method_header(
                func, nogil=nogil, idx_as_arg=idx_as_arg))
            for subseqs in self.model.sequences:
                if func == 'load_data':
                    applyfuncs = ('inputs',)
                elif func == 'save_data':
                    applyfuncs = ('fluxes', 'states')
                else:
                    applyfuncs = ('inputs', 'fluxes', 'states')
                if subseqs.name in applyfuncs:
                    if func == 'close_files':
                        lines.add(2, 'self.sequences.%s.%s()'
                                     % (subseqs.name, func))
                    else:
                        lines.add(2, 'self.sequences.%s.%s(self.idx_sim)'
                                     % (subseqs.name, func))
        return lines
1197045
def getparams(self, param):
        

        return list(cparam for cparam in self.values() if cparam == param)
396167
def parse_afterqc_log(self, f):
        
        try:
            parsed_json = json.load(f['f'])
        except:
            log.warn("Could not parse AfterQC JSON: '{}'".format(f['fn']))
            return None

        # AfterQC changed the name of their summary key at some point
        if 'summary' in parsed_json:
            summaryk = 'summary'
        elif 'afterqc_main_summary' in parsed_json:
            summaryk = 'afterqc_main_summary'
        else:
            log.warn("AfterQC JSON did not have a 'summary' or 'afterqc_main_summary' key, skipping: '{}'".format(f['fn']))
            return None

        s_name = f['s_name']
        self.add_data_source(f, s_name)
        self.afterqc_data[s_name] = {}
        for k in parsed_json[summaryk]:
            try:
                self.afterqc_data[s_name][k] = float(parsed_json[summaryk][k])
            except ValueError:
                self.afterqc_data[s_name][k] = parsed_json[summaryk][k]
        try:
            self.afterqc_data[s_name]['pct_good_bases'] = (self.afterqc_data[s_name]['good_bases'] / self.afterqc_data[s_name]['total_bases']) * 100.0
        except KeyError:
            pass
780572
def get_params(self, name, param_list):
        '''

        '''
        self.add_cmd_output("lctl get_param %s" % " ".join(param_list),
                            suggest_filename="params-%s" % name,
                            stderr=False)
108563
def get_fragility_model(node, fname):
    
    with context(fname, node):
        fid = node['id']
        asset_category = node['assetCategory']
        loss_type = node['lossCategory']
        description = ~node.description
        limit_states = ~node.limitStates
        ffs = node[2:]
    fmodel = scientific.FragilityModel(
        fid, asset_category, loss_type, description, limit_states)
    for ff in ffs:
        array, attrs = ffconvert(fname, limit_states, ff)
        attrs['id'] = ff['id']
        ffl = scientific.FragilityFunctionList(array, **attrs)
        fmodel[ff.imls['imt'], ff['id']] = ffl
    return fmodel
902515
def fqn(o):
    
    parts = []
    if isinstance(o, (str, bytes)):
        return o
    if not hasattr(o, '__module__'):
        raise ValueError('Invalid argument `%s`' % o)
    parts.append(o.__module__)
    if isclass(o):
        parts.append(o.__name__)
    elif isinstance(o, types.FunctionType):
        parts.append(o.__name__)
    else:
        parts.append(o.__class__.__name__)
    return '.'.join(parts)
1201400
function getParameterNames(fn){
  const COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  const code = fn.toString().replace(COMMENTS, '');
  const arrowIndex = code.indexOf('=>');
  const parenLeftIndex = code.indexOf('(');
  const parenRightIndex = code.indexOf(')');
  const parenLess = (!fn.prototype && ~arrowIndex && (
    parenLeftIndex === -1 || // a => a
    parenLeftIndex > arrowIndex // a => (1+2)
  ));
  var parameter = parenLess ?
    code.slice(0, arrowIndex) : // single parameter
    code.slice(parenLeftIndex+1, parenRightIndex);
  if(parenLess && ~parameter.trim().indexOf(' ')) 
    parameter = parameter.split(' ')[1]; // async a
  return parameter.match(/([^\s,]+)/g) || [];
}
1303139
def read(calc_id, mode='r', datadir=None):
    
    datadir = datadir or get_datadir()
    dstore = DataStore(calc_id, datadir, mode=mode)
    try:
        hc_id = dstore['oqparam'].hazard_calculation_id
    except KeyError:  # no oqparam
        hc_id = None
    if hc_id:
        dstore.parent = read(hc_id, datadir=os.path.dirname(dstore.filename))
    return dstore
100325
def hazard_stats(self):
        
        names = []  # name of statistical functions
        funcs = []  # statistical functions of kind func(values, weights)
        if self.mean_hazard_curves:
            names.append('mean')
            funcs.append(stats.mean_curve)
        if self.std_hazard_curves:
            names.append('std')
            funcs.append(stats.std_curve)
        for q in self.quantiles:
            names.append('quantile-%s' % q)
            funcs.append(functools.partial(stats.quantile_curve, q))
        if self.max_hazard_curves:
            names.append('max')
            funcs.append(stats.max_curve)
        return dict(zip(names, funcs))
1142558
def getParam(self, name=None):
        
        if 'parameters' in self.keys():
            l = {x['name']: x['value'] for x in self['parameters'].values()}
            if name:
                if name in l.keys():
                    return l[name]
                else:
                    return False
            else:
                return l
961420
def print_csm_info(fname):
    
    oqparam = readinput.get_oqparam(fname)
    csm = readinput.get_composite_source_model(oqparam, in_memory=False)
    print(csm.info)
    print('See http://docs.openquake.org/oq-engine/stable/'
          'effective-realizations.html for an explanation')
    rlzs_assoc = csm.info.get_rlzs_assoc()
    print(rlzs_assoc)
    dupl = [(srcs[0]['id'], len(srcs)) for srcs in csm.check_dupl_sources()]
    if dupl:
        print(rst_table(dupl, ['source_id', 'multiplicity']))
    tot, pairs = get_pickled_sizes(rlzs_assoc)
    print(rst_table(pairs, ['attribute', 'nbytes']))
274382
def calc_oqparam(request, job_id):
    
    job = logs.dbcmd('get_job', int(job_id))
    if job is None:
        return HttpResponseNotFound()
    if not utils.user_has_permission(request, job.user_name):
        return HttpResponseForbidden()

    with datastore.read(job.ds_calc_dir + '.hdf5') as ds:
        oq = ds['oqparam']
    return HttpResponse(content=json.dumps(vars(oq)), content_type=JSON)
182203
def make_param_dict_from_file(self,path_to_params):
        
        # then we were given a path to a parameter file
        param_list = list(csv.reader(open(path_to_params,"rb")))
        # delete empty elements (if any)
        param_file = [x for x in param_list if x != []]
        # make dict of [wavenames] = raw_params
        name_list = []
        param_list = []
        # get header names for each param (names of param_list columns)
        param_colnames = param_file[0][1:] # 0th element is "Name" or "Wavename"
        # start from 1.  (row 0 is the header)
        for i in np.arange(1, len(param_file)):
            name_list.append(param_file[i][0])
            param_list.append(param_file[i][1:])
        # remove ' ' blank spaces from param_list
        param_list = [[x.strip() for x in y] for y in param_list]
        param_dict = {}
        # i loops through param_colnames, j loops thru param values per wave
        for i in np.arange(0, len(param_colnames)):
            param_dict[param_colnames[i]] = []
            for j in np.arange(0,len(name_list)):
                param_dict[param_colnames[i]].append(param_list[j][i])
        # now we have param_dict, and name_list
        self._param_dict = param_dict
        self._row_names = name_list
1241617
def compute_gmfs_curves(self, monitor):
        
        oq = self.oqparam
        with monitor('GmfGetter.init', measuremem=True):
            self.init()
        hcurves = {}  # key -> poes
        if oq.hazard_curves_from_gmfs:
            hc_mon = monitor('building hazard curves', measuremem=False)
            duration = oq.investigation_time * oq.ses_per_logic_tree_path
            with monitor('building hazard', measuremem=True):
                gmfdata = self.get_gmfdata()  # returned later
                hazard = self.get_hazard(data=gmfdata)
            for sid, hazardr in hazard.items():
                dic = general.group_array(hazardr, 'rlzi')
                for rlzi, array in dic.items():
                    with hc_mon:
                        gmvs = array['gmv']
                        for imti, imt in enumerate(oq.imtls):
                            poes = _gmvs_to_haz_curve(
                                gmvs[:, imti], oq.imtls[imt],
                                oq.investigation_time, duration)
                            hcurves[rsi2str(rlzi, sid, imt)] = poes
        elif oq.ground_motion_fields:  # fast lane
            with monitor('building hazard', measuremem=True):
                gmfdata = self.get_gmfdata()
        else:
            return {}
        if len(gmfdata) == 0:
            return dict(gmfdata=[])
        indices = []
        gmfdata.sort(order=('sid', 'rlzi', 'eid'))
        start = stop = 0
        for sid, rows in itertools.groupby(gmfdata['sid']):
            for row in rows:
                stop += 1
            indices.append((sid, start, stop))
            start = stop
        res = dict(gmfdata=gmfdata, hcurves=hcurves,
                   sig_eps=numpy.array(self.sig_eps, self.sig_eps_dt),
                   indices=numpy.array(indices, (U32, 3)))
        return res
986207
def export_hcurves_csv(ekey, dstore):
    
    oq = dstore['oqparam']
    info = get_info(dstore)
    rlzs_assoc = dstore['csm_info'].get_rlzs_assoc()
    R = len(rlzs_assoc.realizations)
    sitecol = dstore['sitecol']
    sitemesh = get_mesh(sitecol)
    key, kind, fmt = get_kkf(ekey)
    fnames = []
    checksum = dstore.get_attr('/', 'checksum32')
    hmap_dt = oq.hmap_dt()
    for kind in oq.get_kinds(kind, R):
        fname = hazard_curve_name(dstore, (key, fmt), kind, rlzs_assoc)
        comment = _comment(rlzs_assoc, kind, oq.investigation_time)
        if (key in ('hmaps', 'uhs') and oq.uniform_hazard_spectra or
                oq.hazard_maps):
            hmap = extract(dstore, 'hmaps?kind=' + kind)[kind]
        if key == 'uhs' and oq.poes and oq.uniform_hazard_spectra:
            uhs_curves = calc.make_uhs(hmap, info)
            writers.write_csv(
                fname, util.compose_arrays(sitemesh, uhs_curves),
                comment=comment + ', checksum=%d' % checksum)
            fnames.append(fname)
        elif key == 'hmaps' and oq.poes and oq.hazard_maps:
            fnames.extend(
                export_hmaps_csv(ekey, fname, sitemesh,
                                 hmap.flatten().view(hmap_dt),
                                 comment + ', checksum=%d' % checksum))
        elif key == 'hcurves':
            hcurves = extract(dstore, 'hcurves?kind=' + kind)[kind]
            fnames.extend(
                export_hcurves_by_imt_csv(
                    ekey, kind, rlzs_assoc, fname, sitecol, hcurves, oq,
                    checksum))
    return sorted(fnames)
205920
def read_parameters(infile='../parameters/EQcorrscan_parameters.txt'):
    
    try:
        import ConfigParser
    except ImportError:
        import configparser as ConfigParser
    import ast
    f = open(infile, 'r')
    print('Reading parameters with the following header:')
    for line in f:
        if line[0] == '#':
            print(line.rstrip('\n').lstrip('\n'))
    f.close()
    config = ConfigParser.ConfigParser()
    config.read(infile)
    # Slightly tricky list reading
    template_names = list(ast.literal_eval(config.get("eqcorrscan_pars",
                                                      "template_names")))
    parameters = \
        EQcorrscanParameters(template_names=template_names,
                             lowcut=config.get("eqcorrscan_pars", "lowcut"),
                             highcut=config.get("eqcorrscan_pars", "highcut"),
                             filt_order=config.get("eqcorrscan_pars",
                                                   "filt_order"),
                             samp_rate=config.get("eqcorrscan_pars",
                                                  "samp_rate"),
                             debug=config.get("eqcorrscan_pars", "debug"),
                             startdate=config.get("eqcorrscan_pars",
                                                  "startdate"),
                             enddate=config.get("eqcorrscan_pars", "enddate"),
                             archive=config.get("eqcorrscan_pars", "archive"),
                             arc_type=config.get("eqcorrscan_pars",
                                                 "arc_type"),
                             cores=config.get("eqcorrscan_pars", "cores"),
                             plotvar=config.getboolean("eqcorrscan_pars",
                                                       "plotvar"),
                             plotdir=config.get("eqcorrscan_pars", "plotdir"),
                             plot_format=config.get("eqcorrscan_pars",
                                                    "plot_format"),
                             tempdir=ast.literal_eval(config.
                                                      get("eqcorrscan_pars",
                                                          "tempdir")),
                             threshold=config.get("eqcorrscan_pars",
                                                  "threshold"),
                             threshold_type=config.get("eqcorrscan_pars",
                                                       "threshold_type"),
                             trigger_interval=config.get("eqcorrscan_pars",
                                                         "trigger_interval")
                             )

    return parameters