Search is not available for this dataset
text stringlengths 75 104k |
|---|
def hmap_dt(self): # used for CSV export
"""
:returns: a composite dtype (imt, poe)
"""
return numpy.dtype([('%s-%s' % (imt, poe), F32)
for imt in self.imtls for poe in self.poes]) |
def uhs_dt(self): # used for CSV and NPZ export
"""
:returns: a composity dtype (poe, imt)
"""
imts_dt = numpy.dtype([(imt, F32) for imt in self.imtls
if imt.startswith(('PGA', 'SA'))])
return numpy.dtype([(str(poe), imts_dt) for poe in self.poes]) |
def imt_periods(self):
"""
:returns: the IMTs with a period, as objects
"""
imts = []
for im in self.imtls:
imt = from_string(im)
if hasattr(imt, 'period'):
imts.append(imt)
return imts |
def imt_dt(self, dtype=F64):
"""
:returns: a numpy dtype {imt: float}
"""
return numpy.dtype([(imt, dtype) for imt in self.imtls]) |
def lti(self):
"""
Dictionary extended_loss_type -> extended_loss_type index
"""
return {lt: i for i, (lt, dt) in enumerate(self.loss_dt_list())} |
def loss_dt_list(self, dtype=F32):
"""
Return a data type list [(loss_name, dtype), ...]
"""
loss_types = self.all_cost_types
dts = [(str(lt), dtype) for lt in loss_types]
return dts |
def loss_maps_dt(self, dtype=F32):
"""
Return a composite data type for loss maps
"""
ltypes = self.loss_dt(dtype).names
lst = [('poe-%s' % poe, dtype) for poe in self.conditional_loss_poes]
return numpy.dtype([(lt, lst) for lt in ltypes]) |
def gmf_data_dt(self):
"""
Return a composite data type for the GMFs
"""
return numpy.dtype(
[('rlzi', U16), ('sid', U32),
('eid', U64), ('gmv', (F32, (len(self.imtls),)))]) |
def no_imls(self):
"""
Return True if there are no intensity measure levels
"""
return all(numpy.isnan(ls).any() for ls in self.imtls.values()) |
def correl_model(self):
"""
Return a correlation object. See :mod:`openquake.hazardlib.correlation`
for more info.
"""
correl_name = self.ground_motion_correlation_model
if correl_name is None: # no correlation model
return
correl_model_cls = getattr(... |
def get_kinds(self, kind, R):
"""
Yield 'rlz-000', 'rlz-001', ...', 'mean', 'quantile-0.1', ...
"""
stats = self.hazard_stats()
if kind == 'stats':
yield from stats
return
elif kind == 'rlzs':
for r in range(R):
yield 'r... |
def hazard_stats(self):
"""
Return a list of item with the statistical functions defined for the
hazard calculation
"""
names = [] # name of statistical functions
funcs = [] # statistical functions of kind func(values, weights)
if self.mean_hazard_curves:
... |
def is_valid_geometry(self):
"""
It is possible to infer the geometry only if exactly
one of sites, sites_csv, hazard_curves_csv, gmfs_csv,
region is set. You did set more than one, or nothing.
"""
has_sites = (self.sites is not None or 'sites' in self.inputs
... |
def is_valid_poes(self):
"""
When computing hazard maps and/or uniform hazard spectra,
the poes list must be non-empty.
"""
if self.hazard_maps or self.uniform_hazard_spectra:
return bool(self.poes)
else:
return True |
def is_valid_maximum_distance(self):
"""
Invalid maximum_distance={maximum_distance}: {error}
"""
if 'gsim_logic_tree' not in self.inputs:
return True # don't apply validation
gsim_lt = self.inputs['gsim_logic_tree']
trts = set(self.maximum_distance)
... |
def is_valid_intensity_measure_types(self):
"""
If the IMTs and levels are extracted from the risk models,
they must not be set directly. Moreover, if
`intensity_measure_types_and_levels` is set directly,
`intensity_measure_types` must not be set.
"""
if self.grou... |
def is_valid_intensity_measure_levels(self):
"""
In order to compute hazard curves, `intensity_measure_types_and_levels`
must be set or extracted from the risk models.
"""
invalid = self.no_imls() and not self.risk_files and (
self.hazard_curves_from_gmfs or self.calc... |
def is_valid_export_dir(self):
"""
export_dir={export_dir} must refer to a directory,
and the user must have the permission to write on it.
"""
if self.export_dir and not os.path.isabs(self.export_dir):
self.export_dir = os.path.normpath(
os.path.join(... |
def is_valid_sites(self):
"""
The sites are overdetermined
"""
if 'site_model' in self.inputs and 'sites' in self.inputs:
return False
elif 'site_model' in self.inputs and self.sites:
return False
elif 'sites' in self.inputs and self.sites:
... |
def is_valid_complex_fault_mesh_spacing(self):
"""
The `complex_fault_mesh_spacing` parameter can be None only if
`rupture_mesh_spacing` is set. In that case it is identified with it.
"""
rms = getattr(self, 'rupture_mesh_spacing', None)
if rms and not getattr(self, 'comp... |
def is_valid_optimize_same_id_sources(self):
"""
The `optimize_same_id_sources` can be true only in the classical
calculators.
"""
if (self.optimize_same_id_sources and
'classical' in self.calculation_mode or
'disagg' in self.calculation_mode):
... |
def check_missing(self, param, action):
"""
Make sure the given parameter is missing in the job.ini file
"""
assert action in ('debug', 'info', 'warn', 'error'), action
if self.inputs.get(param):
msg = '%s_file in %s is ignored in %s' % (
param, self.i... |
def hazard_precomputed(self):
"""
:returns: True if the hazard is precomputed
"""
if 'gmfs' in self.inputs or 'hazard_curves' in self.inputs:
return True
elif self.hazard_calculation_id:
parent = list(util.read(self.hazard_calculation_id))
retu... |
def get_set_num_ruptures(src):
"""
Extract the number of ruptures and set it
"""
if not src.num_ruptures:
t0 = time.time()
src.num_ruptures = src.count_ruptures()
dt = time.time() - t0
clsname = src.__class__.__name__
if dt > 10:
if 'Area' in clsname:
... |
def split_coords_2d(seq):
"""
:param seq: a flat list with lons and lats
:returns: a validated list of pairs (lon, lat)
>>> split_coords_2d([1.1, 2.1, 2.2, 2.3])
[(1.1, 2.1), (2.2, 2.3)]
"""
lons, lats = [], []
for i, el in enumerate(seq):
if i % 2 == 0:
lons.append(... |
def split_coords_3d(seq):
"""
:param seq: a flat list with lons, lats and depths
:returns: a validated list of (lon, lat, depths) triplets
>>> split_coords_3d([1.1, 2.1, 0.1, 2.3, 2.4, 0.1])
[(1.1, 2.1, 0.1), (2.3, 2.4, 0.1)]
"""
lons, lats, depths = [], [], []
for i, el in enumerate(se... |
def dists(node):
"""
:returns: hpdist, npdist and magScaleRel from the given pointSource node
"""
hd = tuple((node['probability'], node['depth'])
for node in node.hypoDepthDist)
npd = tuple(
((node['probability'], node['rake'], node['strike'], node['dip']))
for node in... |
def mfds2multimfd(mfds):
"""
Convert a list of MFD nodes into a single MultiMFD node
"""
_, kind = mfds[0].tag.split('}')
node = Node('multiMFD', dict(kind=kind, size=len(mfds)))
lengths = None
for field in mfd.multi_mfd.ASSOC[kind][1:]:
alias = mfd.multi_mfd.ALIAS.get(field, field)
... |
def update_source_model(sm_node, fname):
"""
:param sm_node: a sourceModel Node object containing sourceGroups
"""
i = 0
for group in sm_node:
if 'srcs_weights' in group.attrib:
raise InvalidFile('srcs_weights must be removed in %s' % fname)
if not group.tag.endswith('sou... |
def to_python(fname, converter):
"""
Convert a source model .hdf5 file into a :class:`SourceModel` object
"""
with hdf5.File(fname, 'r') as f:
source_model = f['/']
for sg in source_model:
for src in sg:
if hasattr(src, 'mfd'):
# multipoint source
... |
def collect(cls, sources):
"""
:param sources: dictionaries with a key 'tectonicRegion'
:returns: an ordered list of SourceGroup instances
"""
source_stats_dict = {}
for src in sources:
trt = src['tectonicRegion']
if trt not in source_stats_dict:
... |
def update(self, src):
"""
Update the attributes sources, min_mag, max_mag
according to the given source.
:param src:
an instance of :class:
`openquake.hazardlib.source.base.BaseSeismicSource`
"""
assert src.tectonic_region_type == self.trt, (
... |
def convert_node(self, node):
"""
Convert the given rupture node into a hazardlib rupture, depending
on the node tag.
:param node: a node representing a rupture
"""
convert = getattr(self, 'convert_' + striptag(node.tag))
return convert(node) |
def geo_line(self, edge):
"""
Utility function to convert a node of kind edge
into a :class:`openquake.hazardlib.geo.Line` instance.
:param edge: a node describing an edge
"""
with context(self.fname, edge.LineString.posList) as plist:
coords = split_coords_2... |
def geo_lines(self, edges):
"""
Utility function to convert a list of edges into a list of
:class:`openquake.hazardlib.geo.Line` instances.
:param edge: a node describing an edge
"""
lines = []
for edge in edges:
with context(self.fname, edge):
... |
def geo_planar(self, surface):
"""
Utility to convert a PlanarSurface node with subnodes
topLeft, topRight, bottomLeft, bottomRight into a
:class:`openquake.hazardlib.geo.PlanarSurface` instance.
:param surface: PlanarSurface node
"""
with context(self.fname, sur... |
def convert_surfaces(self, surface_nodes):
"""
Utility to convert a list of surface nodes into a single hazardlib
surface. There are four possibilities:
1. there is a single simpleFaultGeometry node; returns a
:class:`openquake.hazardlib.geo.simpleFaultSurface` instance
... |
def convert_simpleFaultRupture(self, node):
"""
Convert a simpleFaultRupture node.
:param node: the rupture node
"""
mag, rake, hypocenter = self.get_mag_rake_hypo(node)
with context(self.fname, node):
surfaces = [node.simpleFaultGeometry]
rupt = sour... |
def convert_multiPlanesRupture(self, node):
"""
Convert a multiPlanesRupture node.
:param node: the rupture node
"""
mag, rake, hypocenter = self.get_mag_rake_hypo(node)
with context(self.fname, node):
surfaces = list(node.getnodes('planarSurface'))
r... |
def convert_ruptureCollection(self, node):
"""
:param node: a ruptureCollection node
:returns: a dictionary grp_id -> EBRuptures
"""
coll = {}
for grpnode in node:
grp_id = int(grpnode['id'])
coll[grp_id] = ebrs = []
for node in grpnode... |
def get_tom(self, node):
"""
Convert the given node into a Temporal Occurrence Model object.
:param node: a node of kind poissonTOM or brownianTOM
:returns: a :class:`openquake.hazardlib.mfd.EvenlyDiscretizedMFD.` or
:class:`openquake.hazardlib.mfd.TruncatedGRMFD` inst... |
def convert_mfdist(self, node):
"""
Convert the given node into a Magnitude-Frequency Distribution
object.
:param node: a node of kind incrementalMFD or truncGutenbergRichterMFD
:returns: a :class:`openquake.hazardlib.mfd.EvenlyDiscretizedMFD.` or
:class:`openq... |
def convert_npdist(self, node):
"""
Convert the given node into a Nodal Plane Distribution.
:param node: a nodalPlaneDist node
:returns: a :class:`openquake.hazardlib.geo.NodalPlane` instance
"""
with context(self.fname, node):
npdist = []
for np ... |
def convert_hpdist(self, node):
"""
Convert the given node into a probability mass function for the
hypo depth distribution.
:param node: a hypoDepthDist node
:returns: a :class:`openquake.hazardlib.pmf.PMF` instance
"""
with context(self.fname, node):
... |
def convert_areaSource(self, node):
"""
Convert the given node into an area source object.
:param node: a node with tag areaGeometry
:returns: a :class:`openquake.hazardlib.source.AreaSource` instance
"""
geom = node.areaGeometry
coords = split_coords_2d(~geom.Po... |
def convert_pointSource(self, node):
"""
Convert the given node into a point source object.
:param node: a node with tag pointGeometry
:returns: a :class:`openquake.hazardlib.source.PointSource` instance
"""
geom = node.pointGeometry
lon_lat = ~geom.Point.pos
... |
def convert_multiPointSource(self, node):
"""
Convert the given node into a MultiPointSource object.
:param node: a node with tag multiPointGeometry
:returns: a :class:`openquake.hazardlib.source.MultiPointSource`
"""
geom = node.multiPointGeometry
lons, lats = z... |
def convert_simpleFaultSource(self, node):
"""
Convert the given node into a simple fault object.
:param node: a node with tag areaGeometry
:returns: a :class:`openquake.hazardlib.source.SimpleFaultSource`
instance
"""
geom = node.simpleFaultGeometry
... |
def convert_complexFaultSource(self, node):
"""
Convert the given node into a complex fault object.
:param node: a node with tag areaGeometry
:returns: a :class:`openquake.hazardlib.source.ComplexFaultSource`
instance
"""
geom = node.complexFaultGeometr... |
def convert_characteristicFaultSource(self, node):
"""
Convert the given node into a characteristic fault object.
:param node:
a node with tag areaGeometry
:returns:
a :class:`openquake.hazardlib.source.CharacteristicFaultSource`
instance
"""
... |
def convert_nonParametricSeismicSource(self, node):
"""
Convert the given node into a non parametric source object.
:param node:
a node with tag areaGeometry
:returns:
a :class:`openquake.hazardlib.source.NonParametricSeismicSource`
instance
"... |
def convert_sourceGroup(self, node):
"""
Convert the given node into a SourceGroup object.
:param node:
a node with tag sourceGroup
:returns:
a :class:`SourceGroup` instance
"""
trt = node['tectonicRegion']
srcs_weights = node.attrib.get('... |
def _check_list_weights(parameter, name):
'''
Checks that the weights in a list of tuples sums to 1.0
'''
if not isinstance(parameter, list):
raise ValueError('%s must be formatted with a list of tuples' % name)
weight = np.sum([val[1] for val in parameter])
if fabs(weight - 1.) > 1E-8:
... |
def populate_regions(self, tectonic_region_dict):
'''
Populates the tectonic region from the list of dictionaries, where each
region is a dictionary of with the following format::
region = {'Shear_Modulus': [(val1, weight1), (val2, weight2), ...],
'Displacement_Lengt... |
def build_fault_model(self, collapse=False, rendered_msr=WC1994(),
mfd_config=None):
'''
Constructs a full fault model with epistemic uncertainty by
enumerating all the possible recurrence models of each fault as
separate faults, with the recurrence rates multip... |
def _read_date_from_string(str1):
"""
Reads the date from a string in the format YYYY/MM/DD and returns
:class: datetime.date
"""
full_date = [int(x) for x in str1.split('/')]
return datetime.date(full_date[0], full_date[1], full_date[2]) |
def _read_time_from_string(str1):
"""
Reads the time from a string in the format HH:MM:SS.S and returns
:class: datetime.time
"""
full_time = [float(x) for x in str1.split(':')]
hour = int(full_time[0])
minute = int(full_time[1])
if full_time[2] > 59.99:
minute += 1
secon... |
def _read_moment_tensor_from_ndk_string(ndk_string, system='USE'):
"""
Reads the moment tensor from the ndk_string representation
ndk_string = [Mrr, sigMrr, Mtt, sigMtt, Mpp, sigMpp, Mrt, sigMrt, Mrp,
sigMrp, Mtp, sigMtp]
Output tensors should be of format:
expected = [[Mtt, Mt... |
def read_file(self, start_year=None, end_year=None, use_centroid=None):
"""
Reads the file
"""
raw_data = getlines(self.filename)
num_lines = len(raw_data)
if ((float(num_lines) / 5.) - float(num_lines / 5)) > 1E-9:
raise IOError('GCMT represented by 5 lines -... |
def read_ndk_event(self, raw_data, id0):
"""
Reads a 5-line batch of data into a set of GCMTs
"""
gcmt = GCMTEvent()
# Get hypocentre
ndkstring = raw_data[id0].rstrip('\n')
gcmt.hypocentre = self._read_hypocentre_from_ndk_string(ndkstring)
# GCMT metadata... |
def to_hmtk(self, use_centroid=True):
'''
Convert the content of the GCMT catalogue to a HMTK
catalogue.
'''
self._preallocate_data_dict()
for iloc, gcmt in enumerate(self.catalogue.gcmts):
self.catalogue.data['eventID'][iloc] = iloc
if use_centro... |
def _read_hypocentre_from_ndk_string(self, linestring):
"""
Reads the hypocentre data from the ndk string to return an
instance of the GCMTHypocentre class
"""
hypo = GCMTHypocentre()
hypo.source = linestring[0:4]
hypo.date = _read_date_from_string(linestring[5:15... |
def _get_metadata_from_ndk_string(self, gcmt, ndk_string):
"""
Reads the GCMT metadata from line 2 of the ndk batch
"""
gcmt.identifier = ndk_string[:16]
inversion_data = re.split('[A-Z:]+', ndk_string[17:61])
gcmt.metadata['BODY'] = [float(x) for x in inversion_data[1].s... |
def _read_centroid_from_ndk_string(self, ndk_string, hypocentre):
"""
Reads the centroid data from the ndk string to return an
instance of the GCMTCentroid class
:param str ndk_string:
String of data (line 3 of ndk format)
:param hypocentre:
Instance of th... |
def _get_moment_tensor_from_ndk_string(self, ndk_string):
"""
Reads the moment tensor from the ndk_string and returns an instance of
the GCMTMomentTensor class.
By default the ndk format uses the Up, South, East (USE) reference
system.
"""
moment_tensor = GCMTMome... |
def _get_principal_axes_from_ndk_string(self, ndk_string, exponent):
"""
Gets the principal axes from the ndk string and returns an instance
of the GCMTPrincipalAxes class
"""
axes = GCMTPrincipalAxes()
# The principal axes is defined in characters 3:48 of the 5th line
... |
def _get_nodal_planes_from_ndk_string(self, ndk_string):
"""
Reads the nodal plane information (represented by 5th line [57:] of the
tensor representation) and returns an instance of the GCMTNodalPlanes
class
"""
planes = GCMTNodalPlanes()
planes.nodal_plane_1 = {... |
def _get_moment_from_ndk_string(self, ndk_string, exponent):
"""
Returns the moment and the moment magnitude
"""
moment = float(ndk_string[49:56]) * (10. ** exponent)
version = ndk_string[:3]
magnitude = utils.moment_magnitude_scalar(moment)
return moment, version... |
def serialise_to_nrml(self, filename, use_defaults=False):
'''
Writes the source model to a nrml source model file given by the
filename
:param str filename:
Path to output file
:param bool use_defaults:
Boolean to indicate whether to use default values ... |
def convert_to_oqhazardlib(
self, tom, simple_mesh_spacing=1.0,
complex_mesh_spacing=2.0, area_discretisation=10.0,
use_defaults=False):
"""
Converts the source model to an iterator of sources of :class:
openquake.hazardlib.source.base.BaseSeismicSource
... |
def recurrence_table(mag, dmag, year, time_interval=None):
"""
Table of recurrence statistics for each magnitude
[Magnitude, Number of Observations, Cumulative Number
of Observations >= M, Number of Observations
(normalised to annual value), Cumulative Number of
Observations (normalised to annua... |
def input_checks(catalogue, config, completeness):
""" Performs a basic set of input checks on the data
"""
if isinstance(completeness, np.ndarray):
# completeness table is a numpy array (i.e. [year, magnitude])
if np.shape(completeness)[1] != 2:
raise ValueError('Completeness T... |
def generate_trunc_gr_magnitudes(bval, mmin, mmax, nsamples):
'''
Generate a random list of magnitudes distributed according to a
truncated Gutenberg-Richter model
:param float bval:
b-value
:param float mmin:
Minimum Magnitude
:param float mmax:
Maximum Magnitude
:p... |
def generate_synthetic_magnitudes(aval, bval, mmin, mmax, nyears):
'''
Generates a synthetic catalogue for a specified number of years, with
magnitudes distributed according to a truncated Gutenberg-Richter
distribution
:param float aval:
a-value
:param float bval:
b-value
:... |
def downsample_completeness_table(comp_table, sample_width=0.1, mmax=None):
"""
Re-sample the completeness table to a specified sample_width
"""
new_comp_table = []
for i in range(comp_table.shape[0] - 1):
mvals = np.arange(comp_table[i, 1],
comp_table[i + 1, 1], d_... |
def get_completeness_counts(catalogue, completeness, d_m):
"""
Returns the number of earthquakes in a set of magnitude bins of specified
with, along with the corresponding completeness duration (in years) of the
bin
:param catalogue:
Earthquake catalogue as instance of
:class: openq... |
def reset(yes):
"""
Remove all the datastores and the database of the current user
"""
ok = yes or confirm('Do you really want to destroy all your data? (y/n) ')
if not ok:
return
dbpath = os.path.realpath(os.path.expanduser(config.dbserver.file))
# user must be able to access and ... |
def _compute_mean(self, C, mag, r):
"""
Compute mean value according to equation 30, page 1021.
"""
mean = (C['c1'] +
self._compute_term1(C, mag) +
self._compute_term2(C, mag, r))
return mean |
def _compute_term2(self, C, mag, r):
"""
This computes the term f2 equation 8 Drouet & Cotton (2015)
"""
return (C['c4'] + C['c5'] * mag) * \
np.log(np.sqrt(r**2 + C['c6']**2)) + C['c7'] * r |
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 set_status(db, job_id, status):
"""
Set the status 'created', 'executing', 'complete', 'failed', 'aborted'
consistently with `is_running`.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: ID of the current job
:param status: status string
"""
assert status in ... |
def create_job(db, datadir):
"""
Create job for the given user, return it.
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param datadir:
Data directory of the user who owns/started this job.
:returns:
the job ID
"""
calc_id = get_calc_id(db, datadir) + 1
... |
def import_job(db, calc_id, calc_mode, description, user_name, status,
hc_id, datadir):
"""
Insert a calculation inside the database, if calc_id is not taken
"""
job = dict(id=calc_id,
calculation_mode=calc_mode,
description=description,
user_n... |
def get_job(db, job_id, username=None):
"""
If job_id is negative, return the last calculation of the current
user, otherwise returns the job_id unchanged.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: a job ID (can be negative and can be nonexisting)
:param username: ... |
def get_calc_id(db, datadir, job_id=None):
"""
Return the latest calc_id by looking both at the datastore
and the database.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param datadir: the directory containing the datastores
:param job_id: a job ID; if None, returns the latest job I... |
def list_calculations(db, job_type, user_name):
"""
Yield a summary of past calculations.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_type: 'hazard' or 'risk'
:param user_name: an user name
"""
jobs = db('SELECT *, %s FROM job WHERE user_name=?x '
'AND ... |
def list_outputs(db, job_id, full=True):
"""
List the outputs for a given
:class:`~openquake.server.db.models.OqJob`.
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
ID of a calculation.
:param bool full:
If True produce a full listing, otherwise ... |
def create_outputs(db, job_id, keysize, ds_size):
"""
Build a correspondence between the outputs in the datastore and the
ones in the database. Also, update the datastore size in the job table.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: ID of the current job
:param ... |
def finish(db, job_id, status):
"""
Set the job columns `is_running`, `status`, and `stop_time`.
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
ID of the current job
:param status:
a string such as 'successful' or 'failed'
"""
db('UPDATE job ... |
def del_calc(db, job_id, user):
"""
Delete a calculation and all associated outputs, if possible.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: job ID, can be an integer or a string
:param user: username
:returns: None if everything went fine or an error message
""... |
def log(db, job_id, timestamp, level, process, message):
"""
Write a log record in the database.
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
a job ID
:param timestamp:
timestamp to store in the log record
:param level:
logging level to... |
def get_log(db, job_id):
"""
Extract the logs as a big string
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: a job ID
"""
logs = db('SELECT * FROM log WHERE job_id=?x ORDER BY id', job_id)
out = []
for log in logs:
time = str(log.timestamp)[:-4] # strip... |
def get_output(db, output_id):
"""
:param db: a :class:`openquake.server.dbapi.Db` instance
:param output_id: ID of an Output object
:returns: (ds_key, calc_id, dirname)
"""
out = db('SELECT output.*, ds_calc_dir FROM output, job '
'WHERE oq_job_id=job.id AND output.id=?x', output_i... |
def save_performance(db, job_id, records):
"""
Save in the database the performance information about the given job.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: a job ID
:param records: a list of performance records
"""
# NB: rec['counts'] is a numpy.uint64 which... |
def calc_info(db, calc_id):
"""
:param db: a :class:`openquake.server.dbapi.Db` instance
:param calc_id: calculation ID
:returns: dictionary of info about the given calculation
"""
job = db('SELECT * FROM job WHERE id=?x', calc_id, one=True)
response_data = {}
response_data['user_name'] ... |
def get_calcs(db, request_get_dict, allowed_users, user_acl_on=False, id=None):
"""
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param request_get_dict:
a dictionary
:param allowed_users:
a list of users
:param user_acl_on:
if True, returns only the calcu... |
def get_log_slice(db, job_id, start, stop):
"""
Get a slice of the calculation log as a JSON list of rows
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
a job ID
:param start:
start of the slice
:param stop:
end of the slice (the last ele... |
def get_traceback(db, job_id):
"""
Return the traceback of the given calculation as a list of lines.
The list is empty if the calculation was successful.
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
a job ID
"""
# strange: understand why the filter... |
def get_result(db, result_id):
"""
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param result_id:
a result ID
:returns: (job_id, job_status, datadir, datastore_key)
"""
job = db('SELECT job.*, ds_key FROM job, output WHERE '
'oq_job_id=job.id AND output.i... |
def get_results(db, job_id):
"""
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
a job ID
:returns: (datadir, datastore_keys)
"""
ds_calc_dir = db('SELECT ds_calc_dir FROM job WHERE id=?x', job_id,
scalar=True)
datadir = os.path.di... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.