Search is not available for this dataset
text stringlengths 75 104k |
|---|
def get_executing_jobs(db):
"""
:param db:
a :class:`openquake.server.dbapi.Db` instance
:returns:
(id, pid, user_name, start_time) tuples
"""
fields = 'id,pid,user_name,start_time'
running = List()
running._fields = fields.split(',')
query = ('''-- executing jobs
SELECT... |
def calculate_z1pt0(vs30):
'''
Reads an array of vs30 values (in m/s) and
returns the depth to the 1.0 km/s velocity horizon (in m)
Ref: Chiou & Youngs (2014) California model
:param vs30: the shear wave velocity (in m/s) at a depth of 30m
'''
c1 = 571 ** 4.
c2 = 1360.0 ** 4.
return ... |
def calculate_z2pt5_ngaw2(vs30):
'''
Reads an array of vs30 values (in m/s) and
returns the depth to the 2.5 km/s velocity horizon (in km)
Ref: Campbell, K.W. & Bozorgnia, Y., 2014.
'NGA-West2 ground motion model for the average horizontal components of
PGA, PGV, and 5pct damped linear accelerat... |
def read_vs30(fnames):
"""
:param fnames: a list of CSV files with fields lon,lat,vs30
:returns: a vs30 array of dtype vs30dt
"""
data = []
for fname in fnames:
for line in open(fname, encoding='utf-8-sig'):
data.append(tuple(line.split(',')))
return numpy.array(data, vs3... |
def prepare_site_model(exposure_xml, sites_csv, vs30_csv,
z1pt0, z2pt5, vs30measured, grid_spacing=0,
assoc_distance=5, output='site_model.csv'):
"""
Prepare a site_model.csv file from exposure xml files/site csv files,
vs30 csv files and a grid spacing which ca... |
def webui(cmd, hostport='127.0.0.1:8800', skip_browser=False):
"""
start the webui server in foreground or perform other operation on the
django application
"""
dbpath = os.path.realpath(os.path.expanduser(config.dbserver.file))
if os.path.isfile(dbpath) and not os.access(dbpath, os.W_OK):
... |
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.
"""
# get the necessary set of coefficients
C = self.COEFFS[imt]
... |
def _get_sa_at_1180(self, C, imt, sites, rup, dists):
"""
Compute and return mean imt value for rock conditions
(vs30 = 1100 m/s)
"""
# reference vs30 = 1180 m/s
vs30_1180 = np.ones_like(sites.vs30) * 1180.
# reference shaking intensity = 0
ref_iml = np.ze... |
def _get_basic_term(self, C, rup, dists):
"""
Compute and return basic form, see page 1030.
"""
# Fictitious depth calculation
if rup.mag > 5.:
c4m = C['c4']
elif rup.mag > 4.:
c4m = C['c4'] - (C['c4']-1.) * (5. - rup.mag)
else:
... |
def _get_faulting_style_term(self, C, rup):
"""
Compute and return faulting style term, that is the sum of the second
and third terms in equation 1, page 74.
"""
# this implements equations 5 and 6 at page 1032. f7 is the
# coefficient for reverse mechanisms while f8 is t... |
def _get_vs30star(self, vs30, imt):
"""
This computes equations 8 and 9 at page 1034
"""
# compute the v1 value (see eq. 9, page 1034)
if imt.name == "SA":
t = imt.period
if t <= 0.50:
v1 = 1500.0
elif t < 3.0:
v... |
def _get_site_response_term(self, C, imt, vs30, sa1180):
"""
Compute and return site response model term see page 1033
"""
# vs30 star
vs30_star = self._get_vs30star(vs30, imt)
# compute the site term
site_resp_term = np.zeros_like(vs30)
gt_vlin = vs30 >= ... |
def _get_hanging_wall_term(self, C, dists, rup):
"""
Compute and return hanging wall model term, see page 1038.
"""
if rup.dip == 90.0:
return np.zeros_like(dists.rx)
else:
Fhw = np.zeros_like(dists.rx)
Fhw[dists.rx > 0] = 1.
# Comp... |
def _get_top_of_rupture_depth_term(self, C, imt, rup):
"""
Compute and return top of rupture depth term. See paragraph
'Depth-to-Top of Rupture Model', page 1042.
"""
if rup.ztor >= 20.0:
return C['a15']
else:
return C['a15'] * rup.ztor / 20.0 |
def _get_soil_depth_term(self, C, z1pt0, vs30):
"""
Compute and return soil depth term. See page 1042.
"""
# Get reference z1pt0
z1ref = self._get_z1pt0ref(vs30)
# Get z1pt0
z10 = copy.deepcopy(z1pt0)
# This is used for the calculation of the motion on re... |
def _get_stddevs(self, C, imt, rup, sites, stddev_types, sa1180, dists):
"""
Return standard deviations as described in paragraph 'Equations for
standard deviation', page 1046.
"""
std_intra = self._get_intra_event_std(C, rup.mag, sa1180, sites.vs30,
... |
def _get_intra_event_std(self, C, mag, sa1180, vs30, vs30measured,
rrup):
"""
Returns Phi as described at pages 1046 and 1047
"""
phi_al = self._get_phi_al_regional(C, mag, vs30measured, rrup)
derAmp = self._get_derivative(C, sa1180, vs30)
phi... |
def _get_derivative(self, C, sa1180, vs30):
"""
Returns equation 30 page 1047
"""
derAmp = np.zeros_like(vs30)
n = self.CONSTS['n']
c = C['c']
b = C['b']
idx = vs30 < C['vlin']
derAmp[idx] = (b * sa1180[idx] * (-1./(sa1180[idx]+c) +
... |
def _get_phi_al_regional(self, C, mag, vs30measured, rrup):
"""
Returns intra-event (Phi) standard deviation (equation 24, page 1046)
"""
phi_al = np.ones((len(vs30measured)))
s1 = np.ones_like(phi_al) * C['s1e']
s2 = np.ones_like(phi_al) * C['s2e']
s1[vs30measure... |
def _get_inter_event_std(self, C, mag, sa1180, vs30):
"""
Returns inter event (tau) standard deviation (equation 25, page 1046)
"""
if mag < 5:
tau_al = C['s3']
elif mag <= 7:
tau_al = C['s3'] + (C['s4'] - C['s3']) / 2. * (mag - 5.)
else:
... |
def _get_regional_term(self, C, imt, vs30, rrup):
"""
In accordance with Abrahamson et al. (2014) we assume as the default
region California
"""
vs30star = self._get_vs30star(vs30, imt)
return C['a31'] * np.log(vs30star/C['vlin']) + C['a25'] * rrup |
def _get_regional_term(self, C, imt, vs30, rrup):
"""
Compute regional term for Japan. See page 1043
"""
f3 = interpolate.interp1d(
[150, 250, 350, 450, 600, 850, 1150, 2000],
[C['a36'], C['a37'], C['a38'], C['a39'], C['a40'], C['a41'],
C['a42'], C['a... |
def _get_phi_al_regional(self, C, mag, vs30measured, rrup):
"""
Returns intra-event (Tau) standard deviation (equation 26, page 1046)
"""
phi_al = np.ones((len(vs30measured)))
idx = rrup < 30
phi_al[idx] *= C['s5']
idx = ((rrup <= 80) & (rrup >= 30.))
ph... |
def gc(coeff, mag):
"""
Returns the set of coefficients to be used for the calculation of GM
as a function of earthquake magnitude
:param coeff:
A dictionary of parameters for the selected IMT
:param mag:
Magnitude value
:returns:
The set of coefficients
"""
if m... |
def rbf(ra, coeff, mag):
"""
Calculate the median ground motion for a given magnitude and distance
:param ra:
Distance value [km]
:param coeff:
The set of coefficients
:param mag:
Magnitude value
:returns:
"""
a1ca, a1cb, a1cc, a1cd, a1ce, a2ca, a2cb, a2cc, a2cd... |
def fnc(ra, *args):
"""
Function used in the minimisation problem.
:param ra:
Semi-axis of the ellipses used in the Yu et al.
:returns:
The absolute difference between the epicentral distance and the
adjusted distance
"""
#
# epicentral distance
repi = args[0]
... |
def get_ras(repi, theta, mag, coeff):
"""
Computes equivalent distance
:param repi:
Epicentral distance
:param theta:
Azimuth value
:param mag:
Magnitude
:param coeff:
GMPE coefficients
"""
rx = 100.
ras = 200.
#
# calculate the difference bet... |
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.
"""
# Check that the requested standard deviation type is available
... |
def _get_stddevs(self, C, stddev_types, rup, imt, num_sites):
"""
Return standard deviations as defined in eq. 4 and 5, page 744,
based on table 8, page 744.
Eq. 5 yields std dev in natural log, so convert to log10
"""
stddevs = []
for stddev_type in stddev_types:... |
def _compute_standard_dev(self, rup, imt, C):
"""
Compute the the standard deviation in terms of magnitude
described on page 744, eq. 4
"""
sigma_mean = 0.
if imt.name in "SA PGA":
psi = -6.898E-3
else:
psi = -3.054E-5
if rup.mag <=... |
def _compute_pga_rock(self, C, dc1, sites, rup, dists):
"""
Compute and return mean imt value for rock conditions
(vs30 = 1000 m/s)
"""
mean = (self._compute_magnitude_term(C, dc1, rup.mag) +
self._compute_distance_term(C, rup.mag, dists) +
self._c... |
def _compute_magnitude_term(self, C, dc1, mag):
"""
Computes the magnitude scaling term given by equation (2)
"""
base = C['theta1'] + (self.CONSTS['theta4'] * dc1)
dmag = self.CONSTS["C1"] + dc1
if mag > dmag:
f_mag = (self.CONSTS['theta5'] * (mag - dmag)) +\... |
def _compute_site_response_term(self, C, sites, pga1000):
"""
Compute and return site response model term
This GMPE adopts the same site response scaling model of
Walling et al (2008) as implemented in the Abrahamson & Silva (2008)
GMPE. The functional form is retained here.
... |
def _compute_focal_depth_term(self, C, rup):
"""
Computes the hypocentral depth scaling term - as indicated by
equation (3)
"""
if rup.hypo_depth > 120.0:
z_h = 120.0
else:
z_h = rup.hypo_depth
return C['theta11'] * (z_h - 60.) |
def _compute_forearc_backarc_term(self, C, sites, dists):
"""
Computes the forearc/backarc scaling term given by equation (4).
"""
f_faba = np.zeros_like(dists.rhypo)
# Term only applies to backarc sites (F_FABA = 0. for forearc)
max_dist = dists.rhypo[sites.backarc]
... |
def match(m_templ, *m_args):
"""
:param m_templ: a meta template string
:param m_args: all arguments
:returns: template, args
Here is an example of usage:
>>> match('SELECT * FROM job WHERE id=?x', 1)
('SELECT * FROM job WHERE id=?', (1,))
"""
# strip commented lines
m_templ = ... |
def insert(self, table, columns, rows):
"""
Insert several rows with executemany. Return a cursor.
"""
cursor = self.conn.cursor()
if len(rows):
templ, _args = match('INSERT INTO ?s (?S) VALUES (?X)',
table, columns, rows[0])
... |
def _cluster(param, tom, imtls, gsims, grp_ids, pmap):
"""
Computes the probability map in case of a cluster group
"""
pmapclu = AccumDict({grp_id: ProbabilityMap(len(imtls.array), len(gsims))
for grp_id in grp_ids})
# Get temporal occurrence model
# Number of occurrence... |
def classical(group, src_filter, gsims, param, monitor=Monitor()):
"""
Compute the hazard curves for a set of sources belonging to the same
tectonic region type for all the GSIMs associated to that TRT.
The arguments are the same as in :func:`calc_hazard_curves`, except
for ``gsims``, which is a lis... |
def calc_hazard_curves(
groups, ss_filter, imtls, gsim_by_trt, truncation_level=None,
apply=sequential_apply, filter_distance='rjb', reqv=None):
"""
Compute hazard curves on a list of sites, given a set of seismic source
groups and a dictionary of ground shaking intensity models (one per
... |
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.
Implement equation 1, page 20.
"""
# compute median PGA on rock, ... |
def _compute_faulting_style_term(self, C, rake):
"""
Compute and return fifth and sixth terms in equations (2a)
and (2b), pages 20.
"""
Fn = float(rake > -135.0 and rake < -45.0)
Fr = float(rake > 45.0 and rake < 135.0)
return C['a8'] * Fn + C['a9'] * Fr |
def _compute_non_linear_term(self, C, pga_only, sites):
"""
Compute non-linear term, equation (3a) to (3c), page 20.
"""
Vref = 750.0
Vcon = 1000.0
lnS = np.zeros_like(sites.vs30)
# equation (3a)
idx = sites.vs30 < Vref
lnS[idx] = (
C[... |
def _compute_mean(self, C, mag, dists, rake):
"""
Compute and return mean value without site conditions,
that is equations (1a) and (1b), p.2981-2982.
"""
mean = (
C['a1'] +
self._compute_linear_magnitude_term(C, mag) +
self._compute_quadratic_... |
def _compute_logarithmic_distance_term(self, C, mag, dists):
"""
Compute and return fourth term in equations (2a)
and (2b), page 20.
"""
return (
(C['a4'] + C['a5'] * (mag - self.c1)) *
np.log(np.sqrt(dists.rhypo ** 2 + C['a6'] ** 2))
) |
def _get_stddevs(self, C, rup, shape, stddev_types):
"""
Return standard deviations as defined in p. 971.
"""
weight = self._compute_weight_std(C, rup.mag)
std_intra = weight * C["sd1"] * np.ones(shape)
std_inter = weight * C["sd2"] * np.ones(shape)
... |
def _compute_weight_std(self, C, mag):
"""
Common part of equations 8 and 9, page 971.
"""
if mag < 6.0:
return C['a1']
elif mag >= 6.0 and mag < 6.5:
return C['a1'] + (C['a2'] - C['a1']) * ((mag - 6.0) / 0.5)
else:
return C['a... |
def _compute_magnitude_scaling_term(self, C, mag):
"""
Compute and return magnitude scaling term in equation 2,
page 970.
"""
c1 = self.CONSTS['c1']
if mag <= c1:
return C['b1'] + C['b2'] * (mag - c1) + C['b3'] * (8.5 - mag) ** 2
else:
... |
def _compute_geometric_decay_term(self, C, mag, dists):
"""
Compute and return geometric decay term in equation 3,
page 970.
"""
c1 = self.CONSTS['c1']
return (
(C['b4'] + C['b5'] * (mag - c1)) *
np.log(np.sqrt(dists.rjb ** 2.0 + C['b6'] **... |
def _compute_anelestic_attenuation_term(self, C, dists):
"""
Compute and return anelastic attenuation term in equation 5,
page 970.
"""
f_aat = np.zeros_like(dists.rjb)
idx = dists.rjb > 80.0
f_aat[idx] = C["b10"] * (dists.rjb[idx] - 80.0)
return f... |
def _compute_non_linear_term(self, C, pga_only, sites):
"""
Compute non-linear term, equation 6, page 970.
"""
Vref = self.CONSTS['Vref']
Vcon = self.CONSTS['Vcon']
c = self.CONSTS['c']
n = self.CONSTS['n']
lnS = np.zeros_like(sites.vs30)
... |
def _compute_mean(self, C, mag, dists, rake):
"""
Compute and return mean value without site conditions,
that is equations 2-5, page 970.
"""
mean = (
self._compute_magnitude_scaling_term(C, mag) +
self._compute_geometric_decay_term(C, mag, dists) +... |
def count_ruptures(self):
"""
See
:meth:`openquake.hazardlib.source.base.BaseSeismicSource.count_ruptures`
for description of parameters and return value.
"""
return (len(self.get_annual_occurrence_rates()) *
len(self.nodal_plane_distribution.data) *
... |
def get_bounding_box(self, maxdist):
"""
Bounding box containing all the point sources, enlarged by the
maximum distance.
"""
return utils.get_bounding_box([ps.location for ps in self], maxdist) |
def geom(self):
"""
:returns: the geometry as an array of shape (N, 3)
"""
return numpy.array([(p.x, p.y, p.z) for p in self.mesh],
numpy.float32) |
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_attenuation(self, rup, dists, imt, C):
"""
Compute the second term of the equation described on p. 1866:
" [(c4 + c5 * M) * min{ log10(R), log10(70.) }] +
[(c4 + c5 * M) * max{ min{ log10(R/70.), log10(140./70.) }, 0.}] +
[(c8 + c9 * M) * max{ log10(R/140.), 0}] "
... |
def _compute_standard_dev(self, rup, imt, C):
"""
Compute the the standard deviation in terms of magnitude
described on p. 1866, eq. 6
"""
sigma_mean = 0.
if rup.mag <= 7.0:
sigma_mean = (C['c12'] * rup.mag) + C['c13']
elif rup.mag > 7.0:
s... |
def _get_base_rates(self, base_params):
'''
Defines the base moment rate that should be assigned to places of
zero strain (i.e. Intraplate regions). In Bird et al (2010) this is
taken as basic rate of Intraplate events in GCMT catalogue above the
threshold magnitude
:par... |
def calculate_activity_rate(self, strain_data, cumulative=False,
in_seconds=False):
'''
Main function to calculate the activity rate (for each of the
magnitudes in target_magnitudes) for all of the cells specified in
the input strain model file
:p... |
def get_rate_osr_normal_transform(self, threshold_moment, id0):
'''
Gets seismicity rate for special case of the ridge condition with
spreading and transform component
:param float threshold_moment:
Moment required for calculating activity rate
:param np.ndarray id0... |
def get_rate_osr_convergent_transform(self, threshold_moment, id0):
'''
Calculates seismicity rate for special case of the ridge condition
with convergence and transform
:param float threshold_moment:
Moment required for calculating activity rate
:param np.ndarray i... |
def continuum_seismicity(self, threshold_moment, e1h, e2h, err,
region_params):
'''
Function to implement the continuum seismicity calculation given
vectors of input rates e1h, e2h [np.ndarray] and a dictionary of
the corresponding regionalisation params
... |
def _reclassify_Bird_regions_with_data(self):
'''
The SHIFT regionalisation defines only 'C','R','S','O' - need to
use strain data to reclassify to sub-categories according to the
definition in Bird & Liu (2007)
'''
# Treat trivial cases of subduction zones and oceanic ty... |
def _get_ln_y_ref(self, rup, dists, C):
"""
Get an intensity on a reference soil.
Implements eq. 13a.
"""
# reverse faulting flag
Frv = 1 if 30 <= rup.rake <= 150 else 0
# normal faulting flag
Fnm = 1 if -120 <= rup.rake <= -60 else 0
# hanging wa... |
def get_median_area(self, mag, rake):
"""
Calculates median fault area from magnitude.
"""
if rake is None:
# Return average of strike-slip and dip-slip curves
return power(10.0, (mag - 4.185))
elif (-45 <= rake <= 45) or (rake >= 135) or (rake <= -135):
... |
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]
# clip rhypo at 10 (this is the minimum ... |
def _get_base_url(request):
"""
Construct a base URL, given a request object.
This comprises the protocol prefix (http:// or https://) and the host,
which can include the port number. For example:
http://www.openquake.org or https://www.openquake.org:8000.
"""
if request.is_secure():
... |
def _prepare_job(request, candidates):
"""
Creates a temporary directory, move uploaded files there and
select the job file by looking at the candidate names.
:returns: full path of the job_file
"""
temp_dir = tempfile.mkdtemp()
inifiles = []
arch = request.FILES.get('archive')
if a... |
def ajax_login(request):
"""
Accept a POST request to login.
:param request:
`django.http.HttpRequest` object, containing mandatory parameters
username and password required.
"""
username = request.POST['username']
password = request.POST['password']
user = authenticate(user... |
def get_available_gsims(request):
"""
Return a list of strings with the available GSIMs
"""
gsims = list(gsim.get_available_gsims())
return HttpResponse(content=json.dumps(gsims), content_type=JSON) |
def validate_nrml(request):
"""
Leverage oq-risklib to check if a given XML text is a valid NRML
:param request:
a `django.http.HttpRequest` object containing the mandatory
parameter 'xml_text': the text of the XML to be validated as NRML
:returns: a JSON object, containing:
* ... |
def calc(request, calc_id):
"""
Get a JSON blob containing all of parameters for the given calculation
(specified by ``calc_id``). Also includes the current job status (
executing, complete, etc.).
"""
try:
info = logs.dbcmd('calc_info', calc_id)
if not utils.user_has_permission(... |
def calc_list(request, id=None):
# view associated to the endpoints /v1/calc/list and /v1/calc/:id/status
"""
Get a list of calculations and report their id, status, calculation_mode,
is_running, description, and a url where more detailed information
can be accessed. This is called several times by ... |
def calc_abort(request, calc_id):
"""
Abort the given calculation, it is it running
"""
job = logs.dbcmd('get_job', calc_id)
if job is None:
message = {'error': 'Unknown job %s' % calc_id}
return HttpResponse(content=json.dumps(message), content_type=JSON)
if job.status not in (... |
def calc_remove(request, calc_id):
"""
Remove the calculation id
"""
# Only the owner can remove a job
user = utils.get_user(request)
try:
message = logs.dbcmd('del_calc', calc_id, user)
except dbapi.NotFound:
return HttpResponseNotFound()
if 'success' in message:
... |
def log_to_json(log):
"""Convert a log record into a list of strings"""
return [log.timestamp.isoformat()[:22],
log.level, log.process, log.message] |
def calc_log(request, calc_id, start, stop):
"""
Get a slice of the calculation log as a JSON list of rows
"""
start = start or 0
stop = stop or 0
try:
response_data = logs.dbcmd('get_log_slice', calc_id, start, stop)
except dbapi.NotFound:
return HttpResponseNotFound()
r... |
def calc_log_size(request, calc_id):
"""
Get the current number of lines in the log
"""
try:
response_data = logs.dbcmd('get_log_size', calc_id)
except dbapi.NotFound:
return HttpResponseNotFound()
return HttpResponse(content=json.dumps(response_data), content_type=JSON) |
def calc_run(request):
"""
Run a calculation.
:param request:
a `django.http.HttpRequest` object.
If the request has the attribute `hazard_job_id`, the results of the
specified hazard calculations will be re-used as input by the risk
calculation.
The request also nee... |
def submit_job(job_ini, username, hazard_job_id=None):
"""
Create a job object from the given job.ini file in the job directory
and run it in a new process. Returns the job ID and PID.
"""
job_id = logs.init('job')
oq = engine.job_from_file(
job_ini, job_id, username, hazard_calculation_... |
def calc_results(request, calc_id):
"""
Get a summarized list of calculation results for a given ``calc_id``.
Result is a JSON array of objects containing the following attributes:
* id
* name
* type (hazard_curve, hazard_map, etc.)
* url (the exact url where the full result... |
def calc_result(request, result_id):
"""
Download a specific result, by ``result_id``.
The common abstracted functionality for getting hazard or risk results.
:param request:
`django.http.HttpRequest` object. Can contain a `export_type` GET
param (the default is 'xml' if no param is sp... |
def extract(request, calc_id, what):
"""
Wrapper over the `oq extract` command. If `setting.LOCKDOWN` is true
only calculations owned by the current user can be retrieved.
"""
job = logs.dbcmd('get_job', int(calc_id))
if job is None:
return HttpResponseNotFound()
if not utils.user_ha... |
def calc_datastore(request, job_id):
"""
Download a full datastore file.
:param request:
`django.http.HttpRequest` object.
:param job_id:
The id of the requested datastore
:returns:
A `django.http.HttpResponse` containing the content
of the requested artifact, if pre... |
def calc_oqparam(request, job_id):
"""
Return the calculation parameters as a JSON
"""
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 datasto... |
def on_same_fs(request):
"""
Accept a POST request to check access to a FS available by a client.
:param request:
`django.http.HttpRequest` object, containing mandatory parameters
filename and checksum.
"""
filename = request.POST['filename']
checksum_in = request.POST['checksum... |
def classical_damage(riskinputs, riskmodel, param, monitor):
"""
Core function for a classical damage computation.
:param riskinputs:
:class:`openquake.risklib.riskinput.RiskInput` objects
:param riskmodel:
a :class:`openquake.risklib.riskinput.CompositeRiskModel` instance
:param pa... |
def make_figure(losses_by_rlzi, loss_types, nbins):
"""
:param losses_by_event: composite array (eid, rlzi, losses)
:param loss_types: list of loss types
"""
# NB: matplotlib is imported inside since it is a costly import
import matplotlib.pyplot as plt
R = len(losses_by_rlzi)
L = len(lo... |
def plot_losses(calc_id, bins=7):
"""
losses_by_event plotter
"""
# read the hazard data
dstore = util.read(calc_id)
losses_by_rlzi = dict(extract(dstore, 'losses_by_event'))
oq = dstore['oqparam']
plt = make_figure(losses_by_rlzi, oq.loss_dt().names, bins)
plt.show() |
def cmp_mat(a, b):
"""
Sorts two matrices returning a positive or zero value
"""
c = 0
for x, y in zip(a.flat, b.flat):
c = cmp(abs(x), abs(y))
if c != 0:
return c
return c |
def _get_centroid_time(self, time_diff):
"""
Calculates the time difference between the date-time classes
"""
source_time = datetime.datetime.combine(self.date, self.time)
second_diff = floor(fabs(time_diff))
microsecond_diff = int(1000. * (time_diff - second_diff))
... |
def normalise_tensor(self):
"""
Normalise the tensor by dividing it by its norm, defined such that
np.sqrt(X:X)
"""
self.tensor, tensor_norm = utils.normalise_tensor(self.tensor)
return self.tensor / tensor_norm, tensor_norm |
def _to_ned(self):
"""
Switches the reference frame to NED
"""
if self.ref_frame is 'USE':
# Rotate
return utils.use_to_ned(self.tensor), \
utils.use_to_ned(self.tensor_sigma)
elif self.ref_frame is 'NED':
# Alreadt NED
... |
def _to_use(self):
"""
Returns a tensor in the USE reference frame
"""
if self.ref_frame is 'NED':
# Rotate
return utils.ned_to_use(self.tensor), \
utils.ned_to_use(self.tensor_sigma)
elif self.ref_frame is 'USE':
# Already USE
... |
def eigendecompose(self, normalise=False):
"""
Performs and eigendecomposition of the tensor and orders into
descending eigenvalues
"""
self.eigenvalues, self.eigenvectors = utils.eigendecompose(self.tensor,
norm... |
def get_nodal_planes(self):
"""
Returns the nodal planes by eigendecomposition of the moment tensor
"""
# Convert reference frame to NED
self.tensor, self.tensor_sigma = self._to_ned()
self.ref_frame = 'NED'
# Eigenvalue decomposition
# Tensor
_, e... |
def get_principal_axes(self):
"""
Uses the eigendecomposition to extract the principal axes from the
moment tensor - returning an instance of the GCMTPrincipalAxes class
"""
# Perform eigendecomposition - returns in order P, B, T
_ = self.eigendecompose(normalise=True)
... |
def get_f_clvd(self):
"""
Returns the statistic f_clvd: the signed ratio of the sizes of the
intermediate and largest principal moments::
f_clvd = -b_axis_eigenvalue / max(|t_axis_eigenvalue|,|p_axis_eigenvalue|)
"""
if not self.principal_axes:
# Principal a... |
def get_relative_error(self):
"""
Returns the relative error statistic (e_rel), defined by Frohlich &
Davis (1999): `e_rel = sqrt((U:U) / (M:M))` where M is the moment
tensor, U is the uncertainty tensor and : is the tensor dot product
"""
if not self.moment_tensor:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.