Search is not available for this dataset
text
stringlengths
75
104k
def ebr_data_transfer(token, dstore): """ Display the data transferred in an event based risk calculation """ attrs = dstore['losses_by_event'].attrs sent = humansize(attrs['sent']) received = humansize(attrs['tot_received']) return 'Event Based Risk: sent %s, received %s' % (sent, received)
def view_totlosses(token, dstore): """ This is a debugging view. You can use it to check that the total losses, i.e. the losses obtained by summing the average losses on all assets are indeed equal to the aggregate losses. This is a sanity check for the correctness of the implementation. """ ...
def view_portfolio_losses(token, dstore): """ The losses for the full portfolio, for each realization and loss type, extracted from the event loss table. """ oq = dstore['oqparam'] loss_dt = oq.loss_dt() data = portfolio_loss(dstore).view(loss_dt)[:, 0] rlzids = [str(r) for r in range(le...
def view_portfolio_loss(token, dstore): """ The mean and stddev loss for the full portfolio for each loss type, extracted from the event loss table, averaged over the realizations """ data = portfolio_loss(dstore) # shape (R, L) loss_types = list(dstore['oqparam'].loss_dt().names) header = ...
def sum_table(records): """ Used to compute summaries. The records are assumed to have numeric fields, except the first field which is ignored, since it typically contains a label. Here is an example: >>> sum_table([('a', 1), ('b', 2)]) ['total', 3] """ size = len(records[0]) result...
def view_exposure_info(token, dstore): """ Display info about the exposure model """ assetcol = dstore['assetcol/array'][:] taxonomies = sorted(set(dstore['assetcol'].taxonomies)) cc = dstore['assetcol/cost_calculator'] ra_flag = ['relative', 'absolute'] data = [('#assets', len(assetcol)...
def view_fullreport(token, dstore): """ Display an .rst report about the computation """ # avoid circular imports from openquake.calculators.reportwriter import ReportWriter return ReportWriter(dstore).make_report()
def performance_view(dstore): """ Returns the performance view as a numpy array. """ data = sorted(dstore['performance_data'], key=operator.itemgetter(0)) out = [] for operation, group in itertools.groupby(data, operator.itemgetter(0)): counts = 0 time = 0 mem = 0 ...
def stats(name, array, *extras): """ Returns statistics from an array of numbers. :param name: a descriptive string :returns: (name, mean, std, min, max, len) """ std = numpy.nan if len(array) == 1 else numpy.std(array, ddof=1) return (name, numpy.mean(array), std, numpy.min(arr...
def view_num_units(token, dstore): """ Display the number of units by taxonomy """ taxo = dstore['assetcol/tagcol/taxonomy'].value counts = collections.Counter() for asset in dstore['assetcol']: counts[taxo[asset['taxonomy']]] += asset['number'] data = sorted(counts.items()) data...
def view_assets_by_site(token, dstore): """ Display statistical information about the distribution of the assets """ taxonomies = dstore['assetcol/tagcol/taxonomy'].value assets_by_site = dstore['assetcol'].assets_by_site() data = ['taxonomy mean stddev min max num_sites num_assets'.split()] ...
def view_required_params_per_trt(token, dstore): """ Display the parameters needed by each tectonic region type """ csm_info = dstore['csm_info'] tbl = [] for grp_id, trt in sorted(csm_info.grp_by("trt").items()): gsims = csm_info.gsim_lt.get_gsims(trt) maker = ContextMaker(trt, ...
def view_task_info(token, dstore): """ Display statistical information about the tasks performance. It is possible to get full information about a specific task with a command like this one, for a classical calculation:: $ oq show task_info:classical """ args = token.split(':')[1:] # cal...
def view_task_durations(token, dstore): """ Display the raw task durations. Here is an example of usage:: $ oq show task_durations:classical """ task = token.split(':')[1] # called as task_duration:task_name array = dstore['task_info/' + task]['duration'] return '\n'.join(map(str, array)...
def view_task_hazard(token, dstore): """ Display info about a given task. Here are a few examples of usage:: $ oq show task_hazard:0 # the fastest task $ oq show task_hazard:-1 # the slowest task """ tasks = set(dstore['task_info']) if 'source_data' not in dstore: return 'Missin...
def view_task_risk(token, dstore): """ Display info about a given risk task. Here are a few examples of usage:: $ oq show task_risk:0 # the fastest task $ oq show task_risk:-1 # the slowest task """ [key] = dstore['task_info'] data = dstore['task_info/' + key].value data.sort(order=...
def view_hmap(token, dstore): """ Display the highest 20 points of the mean hazard map. Called as $ oq show hmap:0.1 # 10% PoE """ try: poe = valid.probability(token.split(':')[1]) except IndexError: poe = 0.1 mean = dict(extract(dstore, 'hcurves?kind=mean'))['mean'] oq ...
def view_global_hcurves(token, dstore): """ Display the global hazard curves for the calculation. They are used for debugging purposes when comparing the results of two calculations. They are the mean over the sites of the mean hazard curves. """ oq = dstore['oqparam'] nsites = len(dstor...
def view_dupl_sources_time(token, dstore): """ Display the time spent computing duplicated sources """ info = dstore['source_info'] items = sorted(group_array(info.value, 'source_id').items()) tbl = [] tot_time = 0 for source_id, records in items: if len(records) > 1: # dupl ...
def view_global_poes(token, dstore): """ Display global probabilities averaged on all sites and all GMPEs """ tbl = [] imtls = dstore['oqparam'].imtls header = ['grp_id'] + [str(poe) for poe in imtls.array] for grp in sorted(dstore['poes']): poes = dstore['poes/' + grp] nsite...
def view_global_hmaps(token, dstore): """ Display the global hazard maps for the calculation. They are used for debugging purposes when comparing the results of two calculations. They are the mean over the sites of the mean hazard maps. """ oq = dstore['oqparam'] dt = numpy.dtype([('%s-%...
def view_global_gmfs(token, dstore): """ Display GMFs averaged on everything for debugging purposes """ imtls = dstore['oqparam'].imtls row = dstore['gmf_data/data']['gmv'].mean(axis=0) return rst_table([row], header=imtls)
def view_mean_disagg(token, dstore): """ Display mean quantities for the disaggregation. Useful for checking differences between two calculations. """ tbl = [] for key, dset in sorted(dstore['disagg'].items()): vals = [ds.value.mean() for k, ds in sorted(dset.items())] tbl.append...
def view_elt(token, dstore): """ Display the event loss table averaged by event """ oq = dstore['oqparam'] R = len(dstore['csm_info'].rlzs) dic = group_array(dstore['losses_by_event'].value, 'rlzi') header = oq.loss_dt().names tbl = [] for rlzi in range(R): if rlzi in dic: ...
def view_pmap(token, dstore): """ Display the mean ProbabilityMap associated to a given source group name """ grp = token.split(':')[1] # called as pmap:grp pmap = {} rlzs_assoc = dstore['csm_info'].get_rlzs_assoc() pgetter = getters.PmapGetter(dstore, rlzs_assoc) pmap = pgetter.get_mea...
def view_act_ruptures_by_src(token, dstore): """ Display the actual number of ruptures by source in event based calculations """ data = dstore['ruptures'].value[['srcidx', 'serial']] counts = sorted(countby(data, 'srcidx').items(), key=operator.itemgetter(1), reverse=True) sr...
def view_dupl_sources(token, dstore): """ Show the sources with the same ID and the truly duplicated sources """ fields = ['source_id', 'code', 'gidx1', 'gidx2', 'num_ruptures'] dic = group_array(dstore['source_info'].value[fields], 'source_id') sameid = [] dupl = [] for source_id, group...
def view_extreme_groups(token, dstore): """ Show the source groups contributing the most to the highest IML """ data = dstore['disagg_by_grp'].value data.sort(order='extreme_poe') return rst_table(data[::-1])
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES ...
def zip_all(directory): """ Zip source models and exposures recursively """ zips = [] for cwd, dirs, files in os.walk(directory): if 'ssmLT.xml' in files: zips.append(zip_source_model(os.path.join(cwd, 'ssmLT.xml'))) for f in files: if f.endswith('.xml') and '...
def zip_source_model(ssmLT, archive_zip='', log=logging.info): """ Zip the source model files starting from the smmLT.xml file """ basedir = os.path.dirname(ssmLT) if os.path.basename(ssmLT) != 'ssmLT.xml': orig = ssmLT ssmLT = os.path.join(basedir, 'ssmLT.xml') with open(ssm...
def zip_exposure(exposure_xml, archive_zip='', log=logging.info): """ Zip an exposure.xml file with all its .csv subfiles (if any) """ archive_zip = archive_zip or exposure_xml[:-4] + '.zip' if os.path.exists(archive_zip): sys.exit('%s exists already' % archive_zip) [exp] = Exposure.read...
def zip_job(job_ini, archive_zip='', risk_ini='', oq=None, log=logging.info): """ Zip the given job.ini file into the given archive, together with all related files. """ if not os.path.exists(job_ini): sys.exit('%s does not exist' % job_ini) archive_zip = archive_zip or 'job.zip' if ...
def build_report(job_ini, output_dir=None): """ Write a `report.csv` file with information about the calculation without running it :param job_ini: full pathname of the job.ini file :param output_dir: the directory where the report is written (default the input directory) """ ...
def add(self, name, obj=None): """Add the view named `name` to the report text""" if obj: text = '\n::\n\n' + indent(str(obj)) else: text = views.view(name, self.dstore) if text: title = self.title[name] line = '-' * len(title) ...
def make_report(self): """Build the report and return a restructed text string""" oq, ds = self.oq, self.dstore for name in ('params', 'inputs'): self.add(name) if 'csm_info' in ds: self.add('csm_info') if ds['csm_info'].source_models[0].name != 'scena...
def save(self, fname): """Save the report""" with open(fname, 'wb') as f: f.write(encode(self.text))
def convert_to_LHC(imt): """ Converts from GMRotI50 to Larger of two horizontal components using global equation of: Boore, D and Kishida, T (2016). Relations between some horizontal- component ground-motion intensity measures used in practice. Bulletin of the Seismological Society of America, 1...
def _get_mean(self, sites, C, ln_y_ref, exp1, exp2, v1): """ Add site effects to an intensity. Implements eq. 5 """ # we do not support estimating of basin depth and instead # rely on it being available (since we require it). z1pt0 = sites.z1pt0 # we con...
def _get_v1(self, imt): """ Calculates Bradley's V1 term. Equation 2 (page 1814) and 6 (page 1816) based on SA period """ if imt == PGA(): v1 = 1800. else: T = imt.period v1a = np.clip((1130 * (T / 0.75)**-0.11), 1130, np.inf) ...
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # extracting dictionary of coefficients specific to required #...
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. :raises ValueError: if imt is instance of :class:`openquake.hazardlib...
def _compute_mean(self, imt, mag, rhypo): """ Compute mean value from lookup table. Lookup table defines log10(IMT) (in g) for combinations of Mw and log10(rhypo) values. ``mag`` is therefore converted from Mblg to Mw using Atkinson and Boore 1987 conversion equation. Mean value...
def _get_recurrence_model(input_model): """ Returns the annual and cumulative recurrence rates predicted by the recurrence model """ if not isinstance(input_model, (TruncatedGRMFD, EvenlyDiscretizedMFD, YoungsCoppersmith1985MFD)...
def _check_completeness_table(completeness, catalogue): """ Generates the completeness table according to different instances """ if isinstance(completeness, np.ndarray) and np.shape(completeness)[1] == 2: return completeness elif isinstance(completeness, float): return np.array([[fl...
def plot_recurrence_model( input_model, catalogue, completeness, dmag=0.1, filename=None, figure_size=(8, 6), filetype='png', dpi=300, ax=None): """ Plot a calculated recurrence model over an observed catalogue, adjusted for time-varying completeness """ annual_rates, cumulative_rate...
def plot_trunc_gr_model( aval, bval, min_mag, max_mag, dmag, catalogue=None, completeness=None, filename=None, figure_size=(8, 6), filetype='png', dpi=300, ax=None): """ Plots a Gutenberg-Richter model """ input_model = TruncatedGRMFD(min_mag, max_mag, dmag, aval, bval) if no...
def get_tag_version(nrml_node): """ Extract from a node of kind NRML the tag and the version. For instance from '{http://openquake.org/xmlns/nrml/0.4}fragilityModel' one gets the pair ('fragilityModel', 'nrml/0.4'). """ version, tag = re.search(r'(nrml/[\d\.]+)\}(\w+)', nrml_node.tag).groups() ...
def to_python(fname, *args): """ Parse a NRML file and return an associated Python object. It works by calling nrml.read() and node_to_obj() in sequence. """ [node] = read(fname) return node_to_obj(node, fname, *args)
def read_source_models(fnames, converter, monitor): """ :param fnames: list of source model files :param converter: a SourceConverter instance :param monitor: a :class:`openquake.performance.Monitor` instance :yields: SourceModel instances """ for fname in fna...
def read(source, chatty=True, stop=None): """ Convert a NRML file into a validated Node object. Keeps the entire tree in memory. :param source: a file name or file object open for reading """ vparser = ValidatingXmlParser(validators, stop) nrml = vparser.parse_file(source) if st...
def write(nodes, output=sys.stdout, fmt='%.7E', gml=True, xmlns=None): """ Convert nodes into a NRML file. output must be a file object open in write mode. If you want to perform a consistency check, open it in read-write mode, then it will be read after creation and validated. :params nodes: a...
def to_string(node): """ Convert a node into a string in NRML format """ with io.BytesIO() as f: write([node], f) return f.getvalue().decode('utf-8')
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ C = self.COEFFS[imt] # Get the mean mean = self.get_me...
def get_mean(self, C, rup, sites, dists): """ Returns the mean ground motion in terms of log10 m/s/s, implementing equation 2 (page 502) """ # W2 needs to be a 1 by 5 matrix (not a vector w_2 = np.array([ [C["W_21"], C["W_22"], C["W_23"], C["W_24"], C["W_25"]]...
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # extracting dictionary of coefficients specific to required #...
def _compute_distance_scaling(self, rjb, C): """ Compute distance-scaling term (Page 141, Eq 1) """ # Calculate distance according to Page 141, Eq 2. rdist = np.sqrt((rjb ** 2.) + (C['h'] ** 2.)) return C['B5'] * np.log(rdist)
def _compute_magnitude_scaling(self, mag, C): """ Compute magnitude-scaling term (Page 141, Eq 1) """ dmag = mag - 6. return (C['B2'] * dmag) + (C['B3'] * (dmag ** 2.))
def _compute_style_of_faulting_term(self, rup, C): """ Computes the coefficient to scale for reverse or strike-slip events Fault type (Strike-slip, Normal, Thrust/reverse) is derived from rake angle. Rakes angles within 30 of horizontal are strike-slip, angles from 30 to ...
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # extract dictionaries of coefficients specific to required # ...
def get_mean_values(self, C, sites, rup, dists, a1100): """ Returns the mean values for a specific IMT """ if isinstance(a1100, np.ndarray): # Site model defined temp_vs30 = sites.vs30 temp_z2pt5 = sites.z2pt5 else: # Default site a...
def _get_magnitude_term(self, C, mag): """ Returns the magnitude scaling term defined in equation 2 """ f_mag = C["c0"] + C["c1"] * mag if (mag > 4.5) and (mag <= 5.5): return f_mag + (C["c2"] * (mag - 4.5)) elif (mag > 5.5) and (mag <= 6.5): retur...
def _get_geometric_attenuation_term(self, C, mag, rrup): """ Returns the geometric attenuation term defined in equation 3 """ return (C["c5"] + C["c6"] * mag) * np.log(np.sqrt((rrup ** 2.) + (C["c7"] ** 2.)))
def _get_style_of_faulting_term(self, C, rup): """ Returns the style-of-faulting scaling term defined in equations 4 to 6 """ if (rup.rake > 30.0) and (rup.rake < 150.): frv = 1.0 fnm = 0.0 elif (rup.rake > -150.0) and (rup.rake < -30.0): fnm =...
def _get_hanging_wall_term(self, C, rup, dists): """ Returns the hanging wall scaling term defined in equations 7 to 16 """ return (C["c10"] * self._get_hanging_wall_coeffs_rx(C, rup, dists.rx) * self._get_hanging_wall_coeffs_rrup(dists) * ...
def _get_hanging_wall_coeffs_rx(self, C, rup, r_x): """ Returns the hanging wall r-x caling term defined in equation 7 to 12 """ # Define coefficients R1 and R2 r_1 = rup.width * cos(radians(rup.dip)) r_2 = 62.0 * rup.mag - 350.0 fhngrx = np.zeros(len(r_x)) ...
def _get_f1rx(self, C, r_x, r_1): """ Defines the f1 scaling coefficient defined in equation 9 """ rxr1 = r_x / r_1 return C["h1"] + (C["h2"] * rxr1) + (C["h3"] * (rxr1 ** 2.))
def _get_f2rx(self, C, r_x, r_1, r_2): """ Defines the f2 scaling coefficient defined in equation 10 """ drx = (r_x - r_1) / (r_2 - r_1) return self.CONSTS["h4"] + (C["h5"] * drx) + (C["h6"] * (drx ** 2.))
def _get_hanging_wall_coeffs_rrup(self, dists): """ Returns the hanging wall rrup term defined in equation 13 """ fhngrrup = np.ones(len(dists.rrup)) idx = dists.rrup > 0.0 fhngrrup[idx] = (dists.rrup[idx] - dists.rjb[idx]) / dists.rrup[idx] return fhngrrup
def _get_hanging_wall_coeffs_mag(self, C, mag): """ Returns the hanging wall magnitude term defined in equation 14 """ if mag < 5.5: return 0.0 elif mag > 6.5: return 1.0 + C["a2"] * (mag - 6.5) else: return (mag - 5.5) * (1.0 + C["a2"]...
def _get_hypocentral_depth_term(self, C, rup): """ Returns the hypocentral depth scaling term defined in equations 21 - 23 """ if rup.hypo_depth <= 7.0: fhyp_h = 0.0 elif rup.hypo_depth > 20.0: fhyp_h = 13.0 else: fhyp_h = rup.hypo_dept...
def _get_fault_dip_term(self, C, rup): """ Returns the fault dip term, defined in equation 24 """ if rup.mag < 4.5: return C["c19"] * rup.dip elif rup.mag > 5.5: return 0.0 else: return C["c19"] * (5.5 - rup.mag) * rup.dip
def _get_anelastic_attenuation_term(self, C, rrup): """ Returns the anelastic attenuation term defined in equation 25 """ f_atn = np.zeros(len(rrup)) idx = rrup >= 80.0 f_atn[idx] = (C["c20"] + C["Dc20"]) * (rrup[idx] - 80.0) return f_atn
def _select_basin_model(self, vs30): """ Select the preferred basin model (California or Japan) to scale basin depth with respect to Vs30 """ if self.CONSTS["SJ"]: # Japan Basin Model - Equation 34 of Campbell & Bozorgnia (2014) return np.exp(5.359 - 1.102...
def _get_basin_response_term(self, C, z2pt5): """ Returns the basin response term defined in equation 20 """ f_sed = np.zeros(len(z2pt5)) idx = z2pt5 < 1.0 f_sed[idx] = (C["c14"] + C["c15"] * float(self.CONSTS["SJ"])) *\ (z2pt5[idx] - 1.0) idx = z2pt5 ...
def _get_shallow_site_response_term(self, C, vs30, pga_rock): """ Returns the shallow site response term defined in equations 17, 18 and 19 """ vs_mod = vs30 / C["k1"] # Get linear global site response term f_site_g = C["c11"] * np.log(vs_mod) idx = vs30 >...
def _get_stddevs(self, C, C_PGA, rup, sites, pga1100, stddev_types): """ Returns the inter- and intra-event and total standard deviations """ # Get stddevs for PGA on basement rock tau_lnpga_b, phi_lnpga_b = self._get_stddevs_pga(C_PGA, rup) num_sites = len(sites.vs30) ...
def _get_stddevs_pga(self, C, rup): """ Returns the inter- and intra-event coefficients for PGA """ tau_lnpga_b = self._get_taulny(C, rup.mag) phi_lnpga_b = np.sqrt(self._get_philny(C, rup.mag) ** 2. - self.CONSTS["philnAF"] ** 2.) return tau...
def _get_taulny(self, C, mag): """ Returns the inter-event random effects coefficient (tau) Equation 28. """ if mag <= 4.5: return C["tau1"] elif mag >= 5.5: return C["tau2"] else: return C["tau2"] + (C["tau1"] - C["tau2"]) * (5...
def _get_philny(self, C, mag): """ Returns the intra-event random effects coefficient (phi) Equation 28. """ if mag <= 4.5: return C["phi1"] elif mag >= 5.5: return C["phi2"] else: return C["phi2"] + (C["phi1"] - C["phi2"]) * (5...
def _get_alpha(self, C, vs30, pga_rock): """ Returns the alpha, the linearised functional relationship between the site amplification and the PGA on rock. Equation 31. """ alpha = np.zeros(len(pga_rock)) idx = vs30 < C["k1"] if np.any(idx): af1 = pga_r...
def decimal_year(year, month, day): """ Allows to calculate the decimal year for a vector of dates (TODO this is legacy code kept to maintain comparability with previous declustering algorithms!) :param year: year column from catalogue matrix :type year: numpy.ndarray :param month: month co...
def decimal_time(year, month, day, hour, minute, second): """ Returns the full time as a decimal value :param year: Year of events (integer numpy.ndarray) :param month: Month of events (integer numpy.ndarray) :param day: Days of event (integer numpy.ndarray) :param hour:...
def haversine(lon1, lat1, lon2, lat2, radians=False, earth_rad=6371.227): """ Allows to calculate geographical distance using the haversine formula. :param lon1: longitude of the first set of locations :type lon1: numpy.ndarray :param lat1: latitude of the frist set of locations :type lat1:...
def greg2julian(year, month, day, hour, minute, second): """ Function to convert a date from Gregorian to Julian format :param year: Year of events (integer numpy.ndarray) :param month: Month of events (integer numpy.ndarray) :param day: Days of event (integer numpy.ndarray)...
def piecewise_linear_scalar(params, xval): '''Piecewise linear function for a scalar variable xval (float). :param params: Piecewise linear parameters (numpy.ndarray) in the following form: [slope_i,... slope_n, turning_point_i, ..., turning_point_n, intercept] Length params === 2 * num...
def sample_truncated_gaussian_vector(data, uncertainties, bounds=None): ''' Samples a Gaussian distribution subject to boundaries on the data :param numpy.ndarray data: Vector of N data values :param numpy.ndarray uncertainties: Vector of N data uncertainties :param int number_boots...
def hmtk_histogram_1D(values, intervals, offset=1.0E-10): """ So, here's the problem. We tend to refer to certain data (like magnitudes) rounded to the nearest 0.1 (or similar, i.e. 4.1, 5.7, 8.3 etc.). We also like our tables to fall on on the same interval, i.e. 3.1, 3.2, 3.3 etc. We usually assum...
def hmtk_histogram_2D(xvalues, yvalues, bins, x_offset=1.0E-10, y_offset=1.0E-10): """ See the explanation for the 1D case - now applied to 2D. :param numpy.ndarray xvalues: Values of x-data :param numpy.ndarray yvalues: Values of y-data :param tuple bins: ...
def bootstrap_histogram_1D( values, intervals, uncertainties=None, normalisation=False, number_bootstraps=None, boundaries=None): ''' Bootstrap samples a set of vectors :param numpy.ndarray values: The data values :param numpy.ndarray intervals: The bin edges :param ...
def bootstrap_histogram_2D( xvalues, yvalues, xbins, ybins, boundaries=[None, None], xsigma=None, ysigma=None, normalisation=False, number_bootstraps=None): ''' Calculates a 2D histogram of data, allowing for normalisation and bootstrap sampling :param numpy.ndarray xvalues: ...
def lonlat_to_laea(lon, lat, lon0, lat0, f_e=0.0, f_n=0.0): """ Converts vectors of longitude and latitude into Lambert Azimuthal Equal Area projection (km), with respect to an origin point :param numpy.ndarray lon: Longitudes :param numpy.ndarray lat: Latitude :param float lon0...
def area_of_polygon(polygon): """ Returns the area of an OpenQuake polygon in square kilometres """ lon0 = np.mean(polygon.lons) lat0 = np.mean(polygon.lats) # Transform to lamber equal area projection x, y = lonlat_to_laea(polygon.lons, polygon.lats, lon0, lat0) # Build shapely polygons...
def input_dir(self): """ :returns: absolute path to where the job.ini is """ return os.path.abspath(os.path.dirname(self.inputs['job_ini']))
def get_reqv(self): """ :returns: an instance of class:`RjbEquivalent` if reqv_hdf5 is set """ if 'reqv' not in self.inputs: return return {key: valid.RjbEquivalent(value) for key, value in self.inputs['reqv'].items()}
def check_gsims(self, gsims): """ :param gsims: a sequence of GSIM instances """ imts = set(from_string(imt).name for imt in self.imtls) for gsim in gsims: restrict_imts = gsim.DEFINED_FOR_INTENSITY_MEASURE_TYPES if restrict_imts: names = s...
def ses_ratio(self): """ The ratio risk_investigation_time / investigation_time / ses_per_logic_tree_path """ if self.investigation_time is None: raise ValueError('Missing investigation_time in the .ini file') return (self.risk_investigation_time or self.inve...
def all_cost_types(self): """ Return the cost types of the computation (including `occupants` if it is there) in order. """ # rt has the form 'vulnerability/structural', 'fragility/...', ... costtypes = sorted(rt.rsplit('/')[1] for rt in self.risk_files) if not co...
def min_iml(self): """ :returns: a numpy array of intensities, one per IMT """ mini = self.minimum_intensity if mini: for imt in self.imtls: try: mini[imt] = calc.filters.getdefault(mini, imt) except KeyError: ...
def set_risk_imtls(self, risk_models): """ :param risk_models: a dictionary taxonomy -> loss_type -> risk_function Set the attribute risk_imtls. """ # NB: different loss types may have different IMLs for the same IMT # in that case we merge the IMLs i...