Search is not available for this dataset
text stringlengths 75 104k |
|---|
def _get_minmax_edges(self, edge):
'''
Updates the upper and lower depths based on the input edges
'''
if isinstance(edge, Line):
# For instance of line class need to loop over values
depth_vals = np.array([node.depth for node in edge.points])
else:
... |
def create_oqhazardlib_source(self, tom, mesh_spacing, use_defaults=False):
"""
Creates an instance of the source model as :class:
openquake.hazardlib.source.complex_fault.ComplexFaultSource
"""
if not self.mfd:
raise ValueError("Cannot write to hazardlib without MFD"... |
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_magnitude_term(self, C, mag):
"""
Returns the magnitude scaling term - equation 3
"""
if mag >= self.CONSTS["Mh"]:
return C["e1"] + C["b3"] * (mag - self.CONSTS["Mh"])
else:
return C["e1"] + (C["b1"] * (mag - self.CONSTS["Mh"])) +\
... |
def _get_distance_term(self, C, rjb, mag):
"""
Returns the general distance scaling term - equation 2
"""
c_3 = self._get_anelastic_coeff(C)
rval = np.sqrt(rjb ** 2. + C["h"] ** 2.)
return (C["c1"] + C["c2"] * (mag - self.CONSTS["Mref"])) *\
np.log(rval / self... |
def _get_site_term(self, C, vs30):
"""
Returns only a linear site amplification term
"""
dg1, dg2 = self._get_regional_site_term(C)
return (C["g1"] + dg1) + (C["g2"] + dg2) * np.log(vs30) |
def _get_stddevs(self, C, stddev_types, num_sites):
"""
Return standard deviations as defined in tables below
"""
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
for stddev_type in stddev_types)
stddevs = [np.zeros(num_sites) + C['SigmaTot'] for _ ... |
def _get_site_type_dummy_variables(self, sites):
"""
Get site type dummy variables, which classified the sites into
different site classes based on the shear wave velocity in the
upper 30 m (Vs30) according to the EC8 (CEN 2003):
class A: Vs30 > 800 m/s
class B: Vs30 = 36... |
def _compute_distance(self, rup, dists, C):
"""
Compute the distance function, equation (5).
"""
rval = np.sqrt(dists.repi ** 2 + C['h'] ** 2)
return C['c1'] * np.log10(rval) |
def _compute_distance(self, rup, dists, C):
"""
Compute the distance function, equation (9):
"""
mref = 3.6
rref = 1.0
rval = np.sqrt(dists.rhypo ** 2 + C['h'] ** 2)
return (C['c1'] + C['c2'] * (rup.mag - mref)) *\
np.log10(rval / rref) + C['c3'] * (rv... |
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 _compute_mean(self, C, mag, rrup, hypo_depth, delta_R, delta_S,
delta_V, delta_I, vs30):
"""
Compute MMI Intensity Value as per Equation in Table 5 and
Table 7 pag 198.
"""
# mean is calculated for all the 4 classes using the same equation.
# Fo... |
def _get_stddevs(self, C, stddev_types, num_sites):
"""
Return total standard deviation as described in paragraph 5.2 pag 200.
"""
# interevent stddev
sigma_inter = C['tau'] + np.zeros(num_sites)
# intraevent std
sigma_intra = C['sigma'] + np.zeros(num_sites)
... |
def _get_site_class(self, vs30, mmi_mean):
"""
Return site class flag for:
Class E - Very Soft Soil vs30 < 180
Class D - Deep or Soft Soil vs30 >= 180 and vs30 <= 360
Class C - Shallow Soil vs30 > 360 and vs30 <= 760
Class B - Rock vs3... |
def _get_deltas(self, rake):
"""
Return the value of deltas (delta_R, delta_S, delta_V, delta_I),
as defined in "Table 5: Model 1" pag 198
"""
# delta_R = 1 for reverse focal mechanism (45<rake<135)
# and for interface events, 0 for all other events
# delta_S = 1 ... |
def _get_deltas(self, rake):
"""
Return the value of deltas (delta_R, delta_S, delta_V, delta_I),
as defined in "Table 5: Model 1" pag 198
"""
# All deltas = 0 for DowrickRhoades2005SSlab Model 3: Deep Region,
# pag 198
delta_R, delta_S = 0, 0
delta_V, de... |
def plot_assets(calc_id=-1, site_model=False):
"""
Plot the sites and the assets
"""
# NB: matplotlib is imported inside since it is a costly import
import matplotlib.pyplot as p
from openquake.hmtk.plotting.patch import PolygonPatch
dstore = util.read(calc_id)
try:
region = dsto... |
def _get_adjustment(mag, year, mmin, completeness_year, t_f, mag_inc=0.1):
'''
If the magnitude is greater than the minimum in the completeness table
and the year is greater than the corresponding completeness year then
return the Weichert factor
:param float mag:
Magnitude of an earthquake... |
def get_catalogue_bounding_polygon(catalogue):
'''
Returns a polygon containing the bounding box of the catalogue
'''
upper_lon = np.max(catalogue.data['longitude'])
upper_lat = np.max(catalogue.data['latitude'])
lower_lon = np.min(catalogue.data['longitude'])
lower_lat = np.min(catalogue.da... |
def make_from_catalogue(cls, catalogue, spacing, dilate):
'''
Defines the grid on the basis of the catalogue
'''
new = cls()
cat_bbox = get_catalogue_bounding_polygon(catalogue)
if dilate > 0:
cat_bbox = cat_bbox.dilate(dilate)
# Define Grid spacing
... |
def run_analysis(self, catalogue, config, completeness_table=None,
smoothing_kernel=None):
'''
Runs an analysis of smoothed seismicity in the manner
originally implemented by Frankel (1995)
:param catalogue:
Instance of the openquake.hmtk.seismicity.cata... |
def create_2D_grid_simple(self, longitude, latitude, year, magnitude,
completeness_table, t_f=1., mag_inc=0.1):
'''
Generates the grid from the limits using an approach closer to that of
Frankel (1995)
:param numpy.ndarray longitude:
Vector of e... |
def create_3D_grid(self, catalogue, completeness_table, t_f=1.0,
mag_inc=0.1):
'''
Counts the earthquakes observed in a three dimensional grid
:param catalogue:
Instance of the openquake.hmtk.seismicity.catalogue.Catalogue class
catalogue.data dic... |
def write_to_csv(self, filename):
'''
Exports to simple csv
:param str filename:
Path to file for export
'''
fid = open(filename, 'wt')
# Create header list
header_info = ['Longitude', 'Latitude', 'Depth', 'Observed Count',
'Smo... |
def _validate_hazard_metadata(md):
"""
Validate metadata `dict` of attributes, which are more or less the same for
hazard curves, hazard maps, and disaggregation histograms.
:param dict md:
`dict` which can contain the following keys:
* statistics
* gsimlt_path
* smlt_p... |
def _set_metadata(element, metadata, attr_map, transform=str):
"""
Set metadata attributes on a given ``element``.
:param element:
:class:`xml.etree.ElementTree.Element` instance
:param metadata:
Dictionary of metadata items containing attribute data for ``element``.
:param attr_map... |
def gen_gmfs(gmf_set):
"""
Generate GMF nodes from a gmf_set
:param gmf_set: a sequence of GMF objects with attributes
imt, sa_period, sa_damping, event_id and containing a list
of GMF nodes with attributes gmv and location. The nodes
are sorted by lon/lat.
"""
for gmf in gmf_set:
... |
def rupture_to_element(rup, parent=None):
"""
Convert a rupture object into an Element object.
:param rup:
must have attributes .rupid, .events_by_ses and .seed
:param parent:
parent of the returned element, or None
"""
if parent is None:
parent = et.Element('root')
... |
def serialize(self, data):
"""
Write a sequence of hazard curves to the specified file.
:param data:
Iterable of hazard curve data. Each datum must be an object with
the following attributes:
* poes: A list of probability of exceedence values (floats).
... |
def add_hazard_curves(self, root, metadata, data):
"""
Add hazard curves stored into `data` as child of the `root`
element with `metadata`. See the documentation of the method
`serialize` and the constructor for a description of `data`
and `metadata`, respectively.
"""
... |
def serialize(self, data, fmt='%10.7E'):
"""
Serialize a collection of ground motion fields to XML.
:param data:
An iterable of "GMF set" objects.
Each "GMF set" object should:
* have an `investigation_time` attribute
* have an `stochastic_event_... |
def serialize(self, data, investigation_time):
"""
Serialize a collection of stochastic event sets to XML.
:param data:
A dictionary src_group_id -> list of
:class:`openquake.commonlib.calc.Rupture` objects.
Each Rupture should have the following attributes:
... |
def serialize(self, data):
"""
Serialize hazard map data to XML.
See :meth:`HazardMapWriter.serialize` for details about the expected
input.
"""
with open(self.dest, 'wb') as fh:
root = et.Element('nrml')
hazard_map = et.SubElement(root, 'hazardMa... |
def serialize(self, data):
"""
:param data:
A sequence of data where each datum has the following attributes:
* matrix: N-dimensional numpy array containing the disaggregation
histogram.
* dim_labels: A list of strings which label the dimensions of a
... |
def serialize(self, data):
"""
Write a sequence of uniform hazard spectra to the specified file.
:param data:
Iterable of UHS data. Each datum must be an object with the
following attributes:
* imls: A sequence of Intensity Measure Levels
* locat... |
def plot_cumulative_moment(year, mag, figure_size=(8, 6),
filename=None, filetype='png', dpi=300, ax=None):
'''Calculation of Mmax using aCumulative Moment approach, adapted from
the cumulative strain energy method of Makropoulos & Burton (1983)
:param year: Year of Earthquake
... |
def check_config(config, data):
'''Check config file inputs
:param dict config:
Configuration settings for the function
'''
essential_keys = ['input_mmin', 'b-value', 'sigma-b']
for key in essential_keys:
if not key in config.keys():
raise ValueError('For KijkoSellevol... |
def _compute_mean(self, C, mag, rjb):
"""
Compute ground motion mean value.
"""
# line 1686 in hazgridXnga2.f
ffc = self._compute_finite_fault_correction(mag)
d = np.sqrt(rjb ** 2 + (C['c7'] ** 2) * (ffc ** 2))
# lines 1663, 1694-1696 in hazgridXnga2.f
me... |
def _compute_finite_fault_correction(self, mag):
"""
Compute finite fault correction term as geometric mean of correction
terms obtained from Mw values calculated with Johnston 1996 and
Atkinson and Boore 1987 conversion equations.
Implement equations as in lines 1653 - 1658 in ... |
def get_vulnerability_functions_04(fname):
"""
Parse the vulnerability model in NRML 0.4 format.
:param fname:
path of the vulnerability file
:returns:
a dictionary imt, taxonomy -> vulnerability function + vset
"""
categories = dict(assetCategory=set(), lossCategory=set(),
... |
def upgrade_file(path, multipoint):
"""Upgrade to the latest NRML version"""
node0 = nrml.read(path, chatty=False)[0]
shutil.copy(path, path + '.bak') # make a backup of the original file
tag = striptag(node0.tag)
gml = True
if tag == 'vulnerabilityModel':
vf_dict, cat_dict = get_vulner... |
def upgrade_nrml(directory, dry_run, multipoint):
"""
Upgrade all the NRML files contained in the given directory to the latest
NRML version. Works by walking all subdirectories.
WARNING: there is no downgrade!
"""
for cwd, dirs, files in os.walk(directory):
for f in files:
p... |
def _compute_term_3(self, C, rrup, mag):
"""
This computes the third term in equation 2, page 2.
"""
return (C['a3'] *
np.log10(rrup + C['a4'] * np.power(10, C['a5'] * mag))) |
def mag_scale_rel_to_hazardlib(mag_scale_rel, use_default=False):
"""
Returns the magnitude scaling relation in a format readable by
openquake.hazardlib
"""
if isinstance(mag_scale_rel, BaseMSR):
return mag_scale_rel
elif isinstance(mag_scale_rel, str):
if not mag_scale_rel in SC... |
def npd_to_pmf(nodal_plane_dist, use_default=False):
"""
Returns the nodal plane distribution as an instance of the PMF class
"""
if isinstance(nodal_plane_dist, PMF):
# Aready in PMF format - return
return nodal_plane_dist
else:
if use_default:
return PMF([(1.0, ... |
def hdd_to_pmf(hypo_depth_dist, use_default=False):
"""
Returns the hypocentral depth distribtuion as an instance of the :class:
openquake.hazardlib.pmf.
"""
if isinstance(hypo_depth_dist, PMF):
# Is already instance of PMF
return hypo_depth_dist
else:
if use_default:
... |
def simple_trace_to_wkt_linestring(trace):
'''
Coverts a simple fault trace to well-known text format
:param trace:
Fault trace as instance of :class: openquake.hazardlib.geo.line.Line
:returns:
Well-known text (WKT) Linstring representation of the trace
'''
trace_str = ""
... |
def simple_edge_to_wkt_linestring(edge):
'''
Coverts a simple fault trace to well-known text format
:param trace:
Fault trace as instance of :class: openquake.hazardlib.geo.line.Line
:returns:
Well-known text (WKT) Linstring representation of the trace
'''
trace_str = ""
fo... |
def checksum(thing):
"""
Get the checksum of a calculation from the calculation ID (if already
done) or from the job.ini/job.zip file (if not done yet). If `thing`
is a source model logic tree file, get the checksum of the model by
ignoring the job.ini, the gmpe logic tree file and possibly other fi... |
def run_job(job_ini, log_level='info', log_file=None, exports='',
username=getpass.getuser(), **kw):
"""
Run a job using the specified config file and other options.
:param str job_ini:
Path to calculation config (INI-style) files.
:param str log_level:
'debug', 'info', 'war... |
def run_tile(job_ini, sites_slice):
"""
Used in tiling calculations
"""
return run_job(job_ini, sites_slice=(sites_slice.start, sites_slice.stop)) |
def del_calculation(job_id, confirmed=False):
"""
Delete a calculation and all associated outputs.
"""
if logs.dbcmd('get_job', job_id) is None:
print('There is no job %d' % job_id)
return
if confirmed or confirm(
'Are you sure you want to (abort and) delete this calcula... |
def smart_run(job_ini, oqparam, log_level, log_file, exports, reuse_hazard):
"""
Run calculations by storing their hazard checksum and reusing previous
calculations if requested.
"""
haz_checksum = readinput.get_checksum32(oqparam, hazard=True)
# retrieve an old calculation with the right checks... |
def engine(log_file, no_distribute, yes, config_file, make_html_report,
upgrade_db, db_version, what_if_I_upgrade, run,
list_hazard_calculations, list_risk_calculations,
delete_calculation, delete_uncompleted_calculations,
hazard_calculation_id, list_outputs, show_log,
... |
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 _compute_imt1100(self, C, sites, rup, dists, get_pga_site=False):
"""
Computes the PGA on reference (Vs30 = 1100 m/s) rock.
"""
# Calculates simple site response term assuming all sites 1100 m/s
fsite = (C['c10'] + (C['k2'] * C['n'])) * log(1100. / C['k1'])
# Calculat... |
def _compute_magnitude_term(self, C, mag):
"""
Returns the magnitude scaling factor (equation (2), page 144)
"""
fmag = C['c0'] + C['c1'] * mag
if mag <= 5.5:
return fmag
elif mag > 6.5:
return fmag + (C['c2'] * (mag - 5.5)) + (C['c3'] * (mag - 6.5... |
def _compute_distance_term(self, C, rup, dists):
"""
Returns the distance scaling factor (equation (3), page 145)
"""
return (C['c4'] + C['c5'] * rup.mag) * \
np.log(np.sqrt(dists.rrup ** 2. + C['c6'] ** 2.)) |
def _compute_style_of_faulting_term(self, C, rup):
"""
Returns the style of faulting factor, depending on the mechanism (rake)
and top of rupture depth (equations (4) and (5), pages 145 - 146)
"""
frv, fnm = self._get_fault_type_dummy_variables(rup.rake)
if frv > 0.:
... |
def _compute_hanging_wall_term(self, C, rup, dists):
"""
Returns the hanging wall scaling term, the product of the scaling
coefficient and four separate scaling terms for distance, magnitude,
rupture depth and dip (equations 6 - 10, page 146). Individual
scaling terms defined in ... |
def _get_hanging_wall_distance_term(self, dists, ztor):
"""
Returns the hanging wall distance scaling term (equation 7, page 146)
"""
fhngr = np.ones_like(dists.rjb, dtype=float)
idx = dists.rjb > 0.
if ztor < 1.:
temp_rjb = np.sqrt(dists.rjb[idx] ** 2. + 1.)
... |
def _compute_shallow_site_response(self, C, sites, pga1100):
"""
Returns the shallow site response term (equation 11, page 146)
"""
stiff_factor = C['c10'] + (C['k2'] * C['n'])
# Initially default all sites to intermediate rock value
fsite = stiff_factor * np.log(sites.vs... |
def _compute_basin_response_term(self, C, z2pt5):
"""
Returns the basin response term (equation 12, page 146)
"""
fsed = np.zeros_like(z2pt5, dtype=float)
idx = z2pt5 < 1.0
if np.any(idx):
fsed[idx] = C['c11'] * (z2pt5[idx] - 1.0)
idx = z2pt5 > 3.0
... |
def _get_stddevs(self, C, sites, pga1100, sigma_pga, stddev_types):
"""
Returns the standard deviations as described in the "ALEATORY
UNCERTAINTY MODEL" section of the paper. Equations 13 to 19, pages 147
to 151
"""
std_intra = self._compute_intra_event_std(C,
... |
def _compute_intra_event_std(self, C, vs30, pga1100, sigma_pga):
"""
Returns the intra-event standard deviation at the site, as defined in
equation 15, page 147
"""
# Get intra-event standard deviation at the base of the site profile
sig_lnyb = np.sqrt(C['s_lny'] ** 2. - ... |
def _compute_intra_event_alpha(self, C, vs30, pga1100):
"""
Returns the linearised functional relationship between fsite and
pga1100, determined from the partial derivative defined on equation 17
on page 148
"""
alpha = np.zeros_like(vs30, dtype=float)
idx = vs30 ... |
def _get_total_sigma(self, C, std_intra, std_inter):
"""
Returns the total sigma term for the arbitrary horizontal component of
ground motion defined by equation 18, page 150
"""
return np.sqrt(std_intra ** 2. + std_inter ** 2. + C['c_lny'] ** 2.) |
def generate_event_set(ucerf, background_sids, src_filter, ses_idx, seed):
"""
Generates the event set corresponding to a particular branch
"""
serial = seed + ses_idx * TWO16
# get rates from file
with h5py.File(ucerf.source_file, 'r') as hdf5:
occurrences = ucerf.tom.sample_number_of_o... |
def sample_background_model(
hdf5, branch_key, tom, seed, filter_idx, min_mag, npd, hdd,
upper_seismogenic_depth, lower_seismogenic_depth, msr=WC1994(),
aspect=1.5, trt=DEFAULT_TRT):
"""
Generates a rupture set from a sample of the background model
:param branch_key:
Key to ... |
def build_ruptures(sources, src_filter, param, monitor):
"""
:param sources: a list with a single UCERF source
:param param: extra parameters
:param monitor: a Monitor instance
:returns: an AccumDict grp_id -> EBRuptures
"""
[src] = sources
res = AccumDict()
res.calc_times = []
s... |
def get_median_area(self, mag, rake):
"""
The values are a function of both magnitude and rake.
Setting the rake to ``None`` causes their "All" rupture-types
to be applied.
"""
assert rake is None or -180 <= rake <= 180
if rake is None:
# their "All" ... |
def get_std_dev_area(self, mag, rake):
"""
Standard deviation for WC1994. Magnitude is ignored.
"""
assert rake is None or -180 <= rake <= 180
if rake is None:
# their "All" case
return 0.24
elif (-45 <= rake <= 45) or (rake >= 135) or (rake <= -13... |
def get_std_dev_mag(self, rake):
"""
Standard deviation on the magnitude for the WC1994 area relation.
"""
assert rake is None or -180 <= rake <= 180
if rake is None:
# their "All" case
return 0.24
elif (-45 <= rake <= 45) or (rake >= 135) or (rake... |
def get_median_mag(self, area, rake):
"""
Return magnitude (Mw) given the area and rake.
Setting the rake to ``None`` causes their "All" rupture-types
to be applied.
:param area:
Area in square km.
:param rake:
Rake angle (the rupture propagation... |
def set_parameters(self):
"""
Combines the parameters of the GMPE provided at the construction
level with the ones assigned to the average GMPE.
"""
for key in dir(self):
if key.startswith('REQUIRES_'):
setattr(self, key, getattr(self.gmpe, key))
... |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stds_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
mean_list = []
stddvs_list = []
# Loop over averaging ... |
def get_correlation(self, t1, t2):
"""
Computes the correlation coefficient for the specified periods.
:param float t1:
First period of interest.
:param float t2:
Second period of interest.
:return float rho:
The predicted correlation coeffi... |
def get_correlation(self, t1, t2):
"""
Computes the correlation coefficient for the specified periods.
:param float t1:
First period of interest.
:param float t2:
Second period of interest.
:return float:
The predicted correlation coefficien... |
def surface_to_array(surface):
"""
:param surface: a Surface object
:returns: a 3D array of shape (3, N, M)
"""
if hasattr(surface, 'surfaces'): # multiplanar surfaces
n = len(surface.surfaces)
arr = numpy.zeros((3, n, 4), F32)
for i, surf in enumerate(surface.surfaces):
... |
def from_coords(cls, coords, sort=True):
"""
Create a mesh object from a list of 3D coordinates (by sorting them)
:params coords: list of coordinates
:param sort: flag (default True)
:returns: a :class:`Mesh` instance
"""
coords = list(coords)
if sort:
... |
def from_points_list(cls, points):
"""
Create a mesh object from a collection of points.
:param point:
List of :class:`~openquake.hazardlib.geo.point.Point` objects.
:returns:
An instance of :class:`Mesh` with one-dimensional arrays
of coordinates fro... |
def xyz(self):
"""
:returns: an array of shape (N, 3) with the cartesian coordinates
"""
return geo_utils.spherical_to_cartesian(
self.lons.flat, self.lats.flat, self.depths.flat) |
def get_min_distance(self, mesh):
"""
Compute and return the minimum distance from the mesh to each point
in another mesh.
:returns:
numpy array of distances in km of shape (self.size, mesh.size)
Method doesn't make any assumptions on arrangement of the points
... |
def get_closest_points(self, mesh):
"""
Find closest point of this mesh for each point in the other mesh
:returns:
:class:`Mesh` object of the same shape as `mesh` with closest
points from this one at respective indices.
"""
min_idx = cdist(self.xyz, mesh... |
def get_distance_matrix(self):
"""
Compute and return distances between each pairs of points in the mesh.
This method requires that the coordinate arrays are one-dimensional.
NB: the depth of the points is ignored
.. warning::
Because of its quadratic space and time... |
def _get_proj_convex_hull(self):
"""
Create a projection centered in the center of this mesh and define
a convex polygon in that projection, enveloping all the points
of the mesh.
:returns:
Tuple of two items: projection function and shapely 2d polygon.
N... |
def get_joyner_boore_distance(self, mesh):
"""
Compute and return Joyner-Boore distance to each point of ``mesh``.
Point's depth is ignored.
See
:meth:`openquake.hazardlib.geo.surface.base.BaseSurface.get_joyner_boore_distance`
for definition of this distance.
:... |
def _get_proj_enclosing_polygon(self):
"""
See :meth:`Mesh._get_proj_enclosing_polygon`.
:class:`RectangularMesh` contains an information about relative
positions of points, so it allows to define the minimum polygon,
containing the projection of the mesh, which doesn't necessar... |
def get_convex_hull(self):
"""
Get a convex polygon object that contains projections of all the points
of the mesh.
:returns:
Instance of :class:`openquake.hazardlib.geo.polygon.Polygon` that
is a convex hull around all the points in this mesh. If the
... |
def from_points_list(cls, points):
"""
Create a rectangular mesh object from a list of lists of points.
Lists in a list are supposed to have the same length.
:param point:
List of lists of :class:`~openquake.hazardlib.geo.point.Point`
objects.
"""
... |
def get_middle_point(self):
"""
Return the middle point of the mesh.
:returns:
An instance of :class:`~openquake.hazardlib.geo.point.Point`.
The middle point is taken from the middle row and a middle column
of the mesh if there are odd number of both. Otherwise the ... |
def get_mean_inclination_and_azimuth(self):
"""
Calculate weighted average inclination and azimuth of the mesh surface.
:returns:
Tuple of two float numbers: inclination angle in a range [0, 90]
and azimuth in range [0, 360) (in decimal degrees).
The mesh is tri... |
def get_cell_dimensions(self):
"""
Calculate centroid, width, length and area of each mesh cell.
:returns:
Tuple of four elements, each being 2d numpy array.
Each array has both dimensions less by one the dimensions
of the mesh, since they represent cells, no... |
def triangulate(self):
"""
Convert mesh points to vectors in Cartesian space.
:returns:
Tuple of four elements, each being 2d numpy array of 3d vectors
(the same structure and shape as the mesh itself). Those arrays
are:
#. points vectors,
... |
def get_mean_width(self):
"""
Calculate and return (weighted) mean width (km) of a mesh surface.
The length of each mesh column is computed (summing up the cell widths
in a same column), and the mean value (weighted by the mean cell
length in each column) is returned.
""... |
def smooth_data(self, data, config, is_3d=False):
'''
Applies the smoothing kernel to the data
:param np.ndarray data:
Raw earthquake count in the form [Longitude, Latitude, Depth,
Count]
:param dict config:
Configuration parameters must contain:
... |
def _get_magnitude_term(self, C, mag):
"""
Returns the magnitude scaling term provided in Equation (5)
"""
dmag = mag - 8.0
return C["c0"] + C["c3"] * dmag + C["c4"] * (dmag ** 2.) |
def _get_distance_term(self, C, rrup, mag):
"""
Returns the distance scaling given in Equation (4), page 1569,
with distance adjusted by the magnitude-dependent depth scaling
factor given in Equation (6)
"""
r_adj = np.sqrt(rrup ** 2.0 + (mag ** 2.0 - 3.1 * mag - 14.55) *... |
def purge_one(calc_id, user):
"""
Remove one calculation ID from the database and remove its datastore
"""
filename = os.path.join(datadir, 'calc_%s.hdf5' % calc_id)
err = dbcmd('del_calc', calc_id, user)
if err:
print(err)
elif os.path.exists(filename): # not removed yet
os... |
def purge_all(user=None, fast=False):
"""
Remove all calculations of the given user
"""
user = user or getpass.getuser()
if os.path.exists(datadir):
if fast:
shutil.rmtree(datadir)
print('Removed %s' % datadir)
else:
for fname in os.listdir(datadir... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.