Ejemplo n.º 1
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake.  If not, see <http://www.gnu.org/licenses/>.

import logging
import numpy

from openquake.baselib.general import CallableDict
from openquake.hazardlib import geo, site
from openquake.hazardlib.shakemap.parsers import get_array

F32 = numpy.float32

get_sitecol_shakemap = CallableDict()


@get_sitecol_shakemap.add('shapefile')
def get_sitecol_shapefile(kind,
                          uridict,
                          required_imts,
                          sitecol=None,
                          assoc_dist=None,
                          mode='filter'):
    """
    :param uridict: a dictionary specifying the ShakeMap resource
    :param imts: required IMTs as a list of strings
    :param sitecol: SiteCollection used to reduce the shakemap
    :param assoc_dist: unused for shapefiles
    :param mode: 'strict', 'warn' or 'filter'
Ejemplo n.º 2
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
"""
Source model XML Writer
"""

import os
import operator
from openquake.baselib.general import CallableDict, groupby
from openquake.baselib.node import Node, node_to_dict
from openquake.hazardlib import nrml, sourceconverter

obj_to_node = CallableDict(lambda obj: obj.__class__.__name__)


def build_area_source_geometry(area_source):
    """
    Returns the area source geometry as a Node

    :param area_source:
        Area source model as an instance of the :class:
        `openquake.hazardlib.source.area.AreaSource`
    :returns:
        Instance of :class:`openquake.baselib.node.Node`
    """
    geom = []
    for lon_lat in zip(area_source.polygon.lons, area_source.polygon.lats):
        geom.extend(lon_lat)
Ejemplo n.º 3
0
from openquake.baselib.hdf5 import FLOAT, INT, get_shape_descr
from openquake.baselib.performance import performance_view
from openquake.baselib.python3compat import encode, decode
from openquake.hazardlib.gsim.base import ContextMaker
from openquake.commonlib import util
from openquake.risklib.scientific import losses_by_period, return_periods
from openquake.baselib.writers import build_header, scientificformat
from openquake.calculators.getters import get_rupture_getters
from openquake.calculators.extract import extract

F32 = numpy.float32
U32 = numpy.uint32
U8 = numpy.uint8

# a dictionary of views datastore -> array
view = CallableDict(keyfunc=lambda s: s.split(':', 1)[0])

# ########################## utility functions ############################## #


def form(value):
    """
    Format numbers in a nice way.

    >>> form(0)
    '0'
    >>> form(0.0)
    '0.0'
    >>> form(0.0001)
    '1.000E-04'
    >>> form(1003.4)
Ejemplo n.º 4
0
Module exports :class:`SilvaEtAl2002MblgAB1987NSHMP2008`,
:class:`SilvaEtAl2002MblgJ1996NSHMP2008`, :class:`SilvaEtAl2002MwNSHMP2008`,
:class:`SilvaEtAl2002SingleCornerSaturation`,
:class:`SilvaEtAl2002DoubleCornerSaturation`.
"""

import numpy as np

from openquake.hazardlib.gsim.base import CoeffsTable, GMPE
from openquake.hazardlib.gsim.utils import (mblg_to_mw_atkinson_boore_87,
                                            mblg_to_mw_johnston_96, clip_mean)
from openquake.hazardlib import const
from openquake.hazardlib.imt import PGA, SA
from openquake.baselib.general import CallableDict

_convert_magnitude = CallableDict()


@_convert_magnitude.add("Mblg87")
def _convert_magnitude87(kind, mag):
    """
    Convert magnitude from Mblg to Mw using Atkinson and Boore 1987
    equation
    """
    return mblg_to_mw_atkinson_boore_87(mag)


@_convert_magnitude.add("Mblg96")
def _convert_magnitude96(kind, mag):
    """
    Convert magnitude from Mblg to Mw using Johnston 1996 equation
Ejemplo n.º 5
0
import numpy
try:
    import h5py
except ImportError:
    # there is no need of h5py in the workers
    class mock_h5py(object):
        def __getattr__(self, name):
            raise ImportError('Could not import h5py.%s' % name)

    h5py = mock_h5py()

from openquake.baselib.general import CallableDict
from openquake.commonlib.writers import write_csv

# a dictionary of views datastore -> array
view = CallableDict()

DATADIR = os.environ.get('OQ_DATADIR', os.path.expanduser('~/oqdata'))


def get_nbytes(dset):
    """
    If the dataset has an attribute 'nbytes', return it. Otherwise get the size
    of the underlying array. Returns None if the dataset is actually a group.
    """
    if 'nbytes' in dset.attrs:
        # look if the dataset has an attribute nbytes
        return dset.attrs['nbytes']
    elif hasattr(dset, 'value'):
        # else extract nbytes from the underlying array
        return dset.value.nbytes
Ejemplo n.º 6
0
    the pair ('fragilityModel', 'nrml/0.4').
    """
    version, tag = re.search(r'(nrml/[\d\.]+)\}(\w+)', nrml_node.tag).groups()
    return tag, version


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)


node_to_obj = CallableDict(keyfunc=get_tag_version, keymissing=lambda n, f: n)
# dictionary of functions with at least two arguments, node and fname

default = sourceconverter.SourceConverter(area_source_discretization=10,
                                          rupture_mesh_spacing=10)


@node_to_obj.add(('ruptureCollection', 'nrml/0.5'))
def get_rupture_collection(node, fname, converter):
    return converter.convert_node(node)


@node_to_obj.add(('geometryModel', 'nrml/0.5'))
def get_geometry_model(node, fname, converter):
    return GeometryModel(converter.convert_node(node))
Ejemplo n.º 7
0
def path2url(url):
    """
    If a relative path is given for the file, parse it so it can be
    read with 'urlopen'.
    :param url: path/url to be parsed
    """
    if not url.startswith('file:') and not url.startswith('http'):
        file = pathlib.Path(url)
        if file.is_file():
            return 'file:{}'.format(pathname2url(str(file.absolute())))
        raise FileNotFoundError('The following path could not be found: %s' %
                                url)
    return url


get_array = CallableDict()


@get_array.add('shapefile')
def get_array_shapefile(kind, fname):
    """
    Download and parse data saved as a shapefile.
    :param fname: url or filepath for the shapefiles,
    either a zip or the location of one of the files,
    *.shp and *.dbf are necessary, *.prj and *.shx optional
    """
    fname = path2url(fname)

    extensions = ['shp', 'dbf', 'prj', 'shx']
    f_dict = {}
Ejemplo n.º 8
0
# Copyright (c) 2010-2015, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake.  If not, see <http://www.gnu.org/licenses/>.
"""This package contains Hazard and Risk calculator classes."""

from openquake.baselib.general import CallableDict, import_all

# an ordered dictionary of calculator classes
calculators = CallableDict(lambda job: job.get_param('calculation_mode'))

import_all('openquake.engine.calculators')
Ejemplo n.º 9
0
    return C['pd'] * np.log10(np.maximum(tmp, z1pt4) / d0)


def _get_intensity_correction_term(C, region, xvf, focal_depth):
    if region == 'NE':
        gamma = C['gNE']
    elif region == 'SW':
        gamma = C['gEW']
    elif region is None:
        gamma = 0.
    else:
        raise ValueError('Unsupported region')
    return (gamma * np.minimum(xvf, 75.0) * np.maximum(focal_depth - 30., 0.))


_get_magnitude_term = CallableDict()


@_get_magnitude_term.add(const.TRT.ACTIVE_SHALLOW_CRUST)
def _get_magnitude_term_1(trt, region, C, rrup, mw1prime, mw1, rhypo):
    return (C['a'] * (mw1prime - mw1)**2 + C['b1'] * rrup + C['c1'] -
            np.log10(rrup + C['d'] * 10.**(CONSTS['e'] * mw1prime)))


@_get_magnitude_term.add(const.TRT.SUBDUCTION_INTERFACE)
def _get_magnitude_term_2(trt, region, C, rrup, mw1prime, mw1, rhypo):
    return (C['a'] * (mw1prime - mw1)**2 + C['b2'] * rrup + C['c2'] -
            np.log10(rrup + C['d'] * 10.**(CONSTS['e'] * mw1prime)))


@_get_magnitude_term.add(const.TRT.SUBDUCTION_INTRASLAB)
Ejemplo n.º 10
0
    """
    Table 3 and equation 19 of 2013 report.
    """
    if imt_per < 0.18:
        dL2L = -0.06
    elif 0.18 <= imt_per < 0.35:
        dL2L = _interp_function(0.12, -0.06, 0.35, 0.18, imt_per)
    elif 0.35 <= imt_per <= 10:
        dL2L = _interp_function(0.65, 0.12, 10, 0.35, imt_per)
    else:
        dL2L = 0

    return dL2L


_get_dS2S = CallableDict()


@_get_dS2S.add("CBD")
def _get_dS2S_1(region, imt_per):
    """
    Table 4 of 2013 report
    """
    if imt_per == 0:
        dS2S = 0.05
    elif 0 < imt_per < 0.15:
        dS2S = _interp_function(-0.15, 0.05, 0.15, 0, imt_per)
    elif 0.15 <= imt_per < 0.45:
        dS2S = _interp_function(0.4, -0.15, 0.45, 0.15, imt_per)
    elif 0.45 <= imt_per < 3.2:
        dS2S = 0.4
Ejemplo n.º 11
0
from openquake.baselib.general import CallableDict
from openquake.hazardlib import const
from openquake.hazardlib.gsim.base import GMPE, CoeffsTable, add_alias
from openquake.hazardlib.imt import PGA, SA, PGV

CONSTANTS = {
    "b4": 0.1,
    "f3": 0.05,
    "Vb": 200,
    "vref_fnl": 760,
    "V1": 270,
    "vref": 760
}

_a0 = CallableDict()


@_a0.add(const.TRT.SUBDUCTION_INTERFACE)
def _a0_1(trt, region, basin, C, C_PGA):
    """
    Regional anelastic coefficient, a0
    """
    if region is None or region == "Cascadia":
        a0 = C["a0"]
        a0_pga = C_PGA["a0"]
    else:
        a0 = C[region + "_a0"]
        a0_pga = C_PGA[region + "_a0"]

    return a0, a0_pga
Ejemplo n.º 12
0
    returns lnSA_ABCD
    """
    # Stage 1: compute PGA_ABCD and PGA'_ABCD which are then used in
    # equation 6
    # Equation 1 PGA unprimed version
    lnSA_AB = _compute_mean_on_rock(kind, C, mag, rrup, rvol, hypo_depth,
                                    CN, CR, f4HW)

    # Equation 4 PGA unprimed version
    lnSA_ABCD = lnSA_AB + S * _compute_nonlinear_soil_term(
        C, lnSA_AB, delta_C, delta_D)

    return lnSA_ABCD


_compute_mean_on_rock = CallableDict()


@_compute_mean_on_rock.add("asc", "asc_sc", "vol", "vol_sc", "chch", "drop")
def _compute_mean_on_rock_1(kind, C, mag, rrup, rvol, hypo_depth, CN, CR,
                            f4HW):
    """
    Compute mean value on site class A/B (equation 1 on page 22)
    """
    lnSA_AB = (
        # line 1 of equation 1
        C['c1'] + C['c4as'] * (mag - 6) +
        # line 2
        C['c3as'] * (8.5 - mag) ** 2 +
        # line 3
        C['c5'] * rrup +
Ejemplo n.º 13
0
        return C["e1"] + (C["b1"] * dmag) + (C["b2"] * (dmag ** 2.0))
    else:
        return C["e1"] + (C["b3"] * dmag)


def _get_mean(kind, sof, C, ctx, dists):
    """
    Returns the mean ground motion
    """
    sof_term = _get_style_of_faulting_term(C, ctx) if sof else 0.
    return (_get_magnitude_scaling_term(C, ctx.mag) +
            _get_distance_scaling_term(C, dists, ctx.mag) +
            _get_site_amplification_term(kind, C, ctx.vs30) + sof_term)


_get_site_amplification_term = CallableDict()


@_get_site_amplification_term.add("base")
def _get_site_amplification_term_1(kind, C, vs30):
    """
    Returns the site amplification term for the case in which Vs30
    is used directly
    """
    return C["gamma"] * np.log10(vs30 / CONSTS["Vref"])


@_get_site_amplification_term.add("EC8")
def _get_site_amplification_term_2(kind, C, vs30):
    """
    Returns the site amplification given Eurocode 8 site classification
Ejemplo n.º 14
0
def _fc(C, imt, vs30, sa1180):
    """
    C value factor [23].
    """
    s = CONSTANTS
    if imt.string in ["PGD", "PGV"]:
        c = 2400
    else:
        c = 2.4

    return (-1.5 * np.log(vs30 / s['vs30_ref']) - np.log(sa1180 + c)
            + np.log(sa1180 + c * (vs30 / s['vs30_ref']) ** 1.5)) \
        * np.heaviside(s['vs30_ref'] - vs30, 0.5) * C['c23']


_ffault = CallableDict()


@_ffault.add(const.TRT.SUBDUCTION_INTERFACE, const.TRT.SUBDUCTION_INTRASLAB)
def _ffault_1(trt, MC, SUFFIX, C, mag):
    """
    Other fault specific factors.
    """
    return (6 - mag) * np.heaviside(6 - mag, 0.5) * C['c13'] \
        + (mag - MC) * np.heaviside(mag - MC, 0.5) \
        * C['c29' + SUFFIX]


@_ffault.add(const.TRT.ACTIVE_SHALLOW_CRUST)
def _ffault_2(trt, MC, SUFFIX, C, mag):
    """
Ejemplo n.º 15
0
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.

"""
Module exports :class:'AllenEtAl2012',
                      'AllenEtAl2012Rhypo'
"""
import numpy as np

from openquake.hazardlib.gsim.base import GMPE, CoeffsTable
from openquake.hazardlib import const
from openquake.hazardlib.imt import MMI
from openquake.baselib.general import CallableDict


_compute_distance_term = CallableDict()


@_compute_distance_term.add('rrup')
def _compute_distance_term_rrup(kind, C, rrup, mag):
    """
    Returns the distance scaling term
    """
    exponent_term = (1.0 + C["c3"] * np.exp(mag - 5.)) ** 2.
    return C["c2"] * np.log(np.sqrt(rrup ** 2. + exponent_term))


@_compute_distance_term.add('rhypo')
def _compute_distance_term_rhypo(kind, C, rhypo, mag):
    """
    Returns the distance scaling term
Ejemplo n.º 16
0
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake.  If not, see <http://www.gnu.org/licenses/>.
"""Functions for getting information about completed jobs and
calculation outputs, as well as exporting outputs from the database to various
file formats."""

import os
from openquake.engine.db import models
from openquake.engine.logs import LOG
from openquake.baselib.general import CallableDict

export_output = CallableDict()


def export(output_id, target, export_type='xml,geojson,csv'):
    """
    Export the given calculation `output_id` from the database to the
    specified `target` directory in the specified `export_type`.
    """
    output = models.Output.objects.get(id=output_id)
    if isinstance(target, basestring):  # create target directory
        makedirs(target)
    for exptype in export_type.split(','):
        key = (output.output_type, exptype)
        if key in export_output:
            return export_output(key, output, target)
    LOG.warn('No "%(fmt)s" exporter is available for "%(output_type)s"'
Ejemplo n.º 17
0
    version, tag = re.search(r'(nrml/[\d\.]+)\}(\w+)', nrml_node.tag).groups()
    return tag, version


def parse(fname, *args):
    """
    Parse a NRML file and return an associated Python object. It works by
    calling nrml.read() and build() in sequence.
    """
    [node] = read(fname)
    return build(node, fname, *args)


# ######################### build definitions ############################ #

build = CallableDict(keyfunc=get_tag_version)
# dictionary of functions with at least two arguments, node and fname


# TODO: add proper validation for exposureModel; this requires knowledge
# of the job.ini files
@build.add(('exposureModel', 'nrml/0.4'), ('exposureModel', 'nrml/0.5'),
           ('siteModel', 'nrml/0.4'), ('siteModel', 'nrml/0.5'),)
def build_exposure(node, fname):
    return node


@build.add(('vulnerabilityModel', 'nrml/0.4'))
def get_vulnerability_functions_04(node, fname):
    """
    :param node:
Ejemplo n.º 18
0
# Pitilakis GMPE Wrapper
uppernames = '''
DEFINED_FOR_INTENSITY_MEASURE_TYPES
DEFINED_FOR_STANDARD_DEVIATION_TYPES
REQUIRES_SITES_PARAMETERS
REQUIRES_RUPTURE_PARAMETERS
REQUIRES_DISTANCES
'''.split()

CONSTANTS = {"F0": 2.5, "kappa": 5.0, "TA": 0.03}

IMLS = [0., 0.25, 0.5, 0.75, 1., 1.25]

MEAN, SIGMA, INTER, INTRA = 0, 1, 2, 3

get_amplification_factor = CallableDict()


@get_amplification_factor.add("base")
def get_amplification_factor_1(kind, F1, FS, s_s, s_1, sctx, ec8=None):
    """
    Returns the short and long-period amplification factors given the
    input Pitilakis et al. (2018) site class and the short and long-period
    input accelerations
    """
    f_s = np.ones(sctx.ec8_p18.shape, dtype=float)
    f_l = np.ones(sctx.ec8_p18.shape, dtype=float)
    for ec8b in np.unique(sctx.ec8_p18):
        ec8 = ec8b.decode('ascii')
        if ec8 == "A":
            # Amplification factors are 1
Ejemplo n.º 19
0
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.

"""
Module exports :class:`ToroEtAl1997MblgNSHMP2008`,
:class:`ToroEtAl1997MwNSHMP2008`
"""
import numpy as np

from openquake.hazardlib.gsim.base import CoeffsTable, GMPE
from openquake.hazardlib.gsim.utils import (
    mblg_to_mw_johnston_96, mblg_to_mw_atkinson_boore_87, clip_mean)
from openquake.hazardlib import const
from openquake.hazardlib.imt import PGA, SA
from openquake.baselib.general import CallableDict

_compute_finite_fault_correction = CallableDict()


@_compute_finite_fault_correction.add("Mblg")
def _compute_finite_fault_correction_Mblg(kind, 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 hazgridXnga2.f
    """
    mw_j96 = mblg_to_mw_johnston_96(mag)
    mw_ab87 = mblg_to_mw_atkinson_boore_87(mag)

    t1 = np.exp(-1.25 + 0.227 * mw_j96)
Ejemplo n.º 20
0
    def __str__(self):
        return "filename '%s', line %s: %s" % (self.filename, self.lineno,
                                               self.message)


#                           parse_uncertainty                              #


def unknown(utype, node, filename):
    try:
        return float(node.text)
    except (TypeError, ValueError):
        raise LogicTreeError(node, filename, 'expected single float value')


parse_uncertainty = CallableDict(keymissing=unknown)


@parse_uncertainty.add('sourceModel', 'extendModel')
def smodel(utype, node, filename):
    return node.text.strip()


@parse_uncertainty.add('abGRAbsolute')
def abGR(utype, node, filename):
    try:
        [a, b] = node.text.split()
        return float(a), float(b)
    except ValueError:
        raise LogicTreeError(node, filename,
                             'expected a pair of floats separated by space')
Ejemplo n.º 21
0
        array = dstore[ekey[0]].value
    except AttributeError:
        # this happens if the key correspond to a HDF5 group
        return []  # write a custom exporter in this case
    if len(array.shape) == 1:  # vector
        array = array.reshape((len(array), 1))
    return [write_csv(dstore.export_path(name), array)]


def dispatch_on_colon(ekey, dstore):
    """
    If the datastore key contains a colon, i.e. it is of the form
    dskey:spec, then call `export(('<dskey>:', fmt), dstore, spec)`.

    :param ekey:
        export key of the form (k0, ext) with k0 of the form <dskey>:<spec>
    :param dstore:
        datastore instance

    This function is called only for ekey not present in the datastore.
    """
    if ':' not in ekey[0]:
        raise MissingExporter(ekey)
    dkey, spec = ekey[0].split(':', 1)
    return export((dkey + ':', ekey[1]), dstore, spec)


export = CallableDict(keymissing=dispatch_on_colon)

import_all('openquake.commonlib.export')
Ejemplo n.º 22
0
    Decompose the spatial covariance and cross correlation matrices.

    :param spatial_cov: array of shape (M, N, N)
    :param cross_corr: array of shape (M, M)
    :returns: a triangular matrix of shape (M * N, M * N)
    """
    M, N = spatial_cov.shape[:2]
    L = numpy.array([numpy.linalg.cholesky(spatial_cov[i]) for i in range(M)])
    LLT = []
    for i in range(M):
        row = [L[i] @ L[j].T * cross_corr[i, j] for j in range(M)]
        LLT.extend(numpy.array(row).transpose(1, 0, 2).reshape(N, M * N))
    return numpy.linalg.cholesky(numpy.array(LLT))


calculate_gmfs = CallableDict()

CORRELATION_MATRIX_TOO_LARGE = '''\
You have a correlation matrix which is too large: %s > %d.
To avoid that, set a proper `region_grid_spacing` so that your exposure
involves less sites.'''


@calculate_gmfs.add('Silva&Horspool')
def calculate_gmfs_sh(kind, shakemap, imts, Z, mu, spatialcorr, crosscorr,
                      cholesky_limit):
    """
    Implementation of paper by Silva and Horspool 2019
    https://onlinelibrary.wiley.com/doi/abs/10.1002/eqe.3154?af=R

    :param shakemap: site coordinates with shakemap values
Ejemplo n.º 23
0
# You should have received a copy of the GNU Affero General Public
# License along with OpenQuake Risklib. If not, see
# <http://www.gnu.org/licenses/>.
from __future__ import division
import sys
import inspect
import functools
import collections
import mock
import numpy

from openquake.baselib.general import CallableDict
from openquake.commonlib import valid
from openquake.risklib import utils, scientific

registry = CallableDict()


class CostCalculator(object):
    """
    Return the value of an asset for the given loss type depending
    on the cost types declared in the exposure, as follows:

        case 1: cost type: aggregated:
            cost = economic value
        case 2: cost type: per asset:
            cost * number (of assets) = economic value
        case 3: cost type: per area and area type: aggregated:
            cost * area = economic value
        case 4: cost type: per area and area type: per asset:
            cost * area * number = economic value
Ejemplo n.º 24
0
from scipy.constants import g

from openquake.baselib.general import CallableDict
from openquake.hazardlib.gsim.base import GMPE, CoeffsTable
from openquake.hazardlib import const
from openquake.hazardlib.imt import PGA, PGV


def _compute_distance_term(C, rhypo):
    """
    Returns the distance scaling term
    """
    return (C["c2"] * rhypo) + (C["c3"] * np.log10(rhypo))


_compute_magnitude_term = CallableDict()


@_compute_magnitude_term.add("base")
def _compute_magnitude_term_1(kind, C, mag):
    """
    Returns the magnitude scaling term
    """
    return C["c0"] + (C["c1"] * mag)


@_compute_magnitude_term.add("bommer")
def _compute_magnitude_term_2(kind, C, mag):
    """
    Returns the magnitude scaling term
    """
Ejemplo n.º 25
0
    mean = (
        # 1st term
        C['c1'] + C['c2'] * mag +
        # 2nd term
        C['c3'] * hypo_depth +
        # 3rd term
        C['c4'] * R -
        # 4th term
        g * np.log10(R) +
        # 5th, 6th and 7th terms
        s_amp)

    return mean


_compute_site_class_dummy_variables = CallableDict()


@_compute_site_class_dummy_variables.add('SInter')
def _compute_site_class_dummy_variables_SInter(kind, vs30):
    """
    Compute site class dummy variables as explained in paragraph
    'Functional Form', page 1706.
    """
    Sc = np.zeros_like(vs30)
    Sd = np.zeros_like(vs30)
    Se = np.zeros_like(vs30)

    Sc[(vs30 > 360) & (vs30 <= 760)] = 1
    Sd[(vs30 >= 180) & (vs30 <= 360)] = 1
    Se[vs30 < 180] = 1
Ejemplo n.º 26
0
def keyfunc(ekey):
    """
    Extract the name before the colons:

    >>> keyfunc(('agg_loss_table', 'csv'))
    ('agg_loss_table', 'csv')
    >>> keyfunc(('agg_loss_table/1', 'csv'))
    ('agg_loss_table', 'csv')
    >>> keyfunc(('agg_loss_table/1/0', 'csv'))
    ('agg_loss_table', 'csv')
    """
    fullname, ext = ekey
    return (fullname.split('/', 1)[0], ext)


export = CallableDict(keyfunc)

export.from_db = False  # overridden when exporting from db

import_all('openquake.calculators.export')


@export.add(('input_zip', 'zip'))
def export_input_zip(ekey, dstore):
    """
    Export the data in the `input_zip` dataset as a .zip file
    """
    dest = dstore.export_path('input.zip')
    nbytes = dstore.get_attr('input_zip', 'nbytes')
    zbytes = dstore['input_zip'].value
    # when reading input_zip some terminating null bytes are truncated (for
Ejemplo n.º 27
0
"""
Module exports :class:`TusaLanger2016RepiBA08SE`,
               :class:`TusaLanger2016RepiBA08DE`,
               :class:`TusaLanger2016RepiSP87SE`,
               :class:`TusaLanger2016RepiSP87DE`,
               :class:`TusaLanger2016Rhypo`
"""
import numpy as np
from scipy.constants import g

from openquake.hazardlib.gsim.base import GMPE, CoeffsTable
from openquake.hazardlib import const
from openquake.hazardlib.imt import PGA, SA
from openquake.baselib.general import CallableDict

_compute_distance = CallableDict()


@_compute_distance.add("BA08SE", "BA08DE")
def _compute_distance1(kind, ctx, C):
    """
    Compute the distance function, equation (9):
    """
    mref = 3.6
    rref = 1.0
    rval = np.sqrt(ctx.repi ** 2 + C['h'] ** 2)
    return (C['c1'] + C['c2'] * (ctx.mag - mref)) *\
        np.log10(rval / rref) + C['c3'] * (rval - rref)


@_compute_distance.add("SP87SE", "SP87DE")
Ejemplo n.º 28
0
def keyfunc(ekey):
    """
    Extract the name before the slash:

    >>> keyfunc(('risk_by_event', 'csv'))
    ('risk_by_event', 'csv')
    >>> keyfunc(('risk_by_event/1', 'csv'))
    ('risk_by_event', 'csv')
    >>> keyfunc(('risk_by_event/1/0', 'csv'))
    ('risk_by_event', 'csv')
    """
    fullname, ext = ekey
    return (fullname.split('/', 1)[0], ext)


export = CallableDict(keyfunc)
export.sanity_check = False  # overridden in the tests
export.from_db = False  # overridden when exporting from db


@export.add(('input', 'zip'))
def export_input_zip(ekey, dstore):
    """
    Export the data in the `input` datagroup as a .zip file
    """
    dest = dstore.export_path('input.zip')
    with zipfile.ZipFile(
            dest, 'w', zipfile.ZIP_DEFLATED, allowZip64=True) as z:
        for k, data in dstore.retrieve_files():
            logging.info('Archiving %s' % k)
            z.writestr(k, data)
Ejemplo n.º 29
0
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
# The GEM Foundation, and the authors of the software, assume no
# liability for use of the software.

# -*- coding: utf-8 -*-
"""
"""

import abc
import numpy as np
from openquake.baselib.general import CallableDict

TIME_DISTANCE_WINDOW_FUNCTIONS = CallableDict()


class BaseDistanceTimeWindow(object):
    """
    Defines the space and time windows, within which an event is identified
    as a cluster.
    """
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def calc(self, magnitude):
        """
        Allows to calculate distance and time windows (sw_space, sw_time)
        see reference: `Van Stiphout et al (2011)`.
Ejemplo n.º 30
0
    mean = (C['A1'] +
            (C['A2'] + C['A2R'] * delta_R + C['A2V'] * delta_V) * mag +
            (C['A3'] + C['A3S'] * delta_S + C['A3V'] * delta_V) *
            np.log10(np.power((rrup**3 + C['d']**3), 1.0 / 3.0)) +
            C['A4'] * hypo_depth + C['A5'] * delta_I)

    # Get S site class term
    S = _get_site_class(vs30, mean)

    # Add S amplification term to mean value
    mean = mean + S

    return mean


_get_deltas = CallableDict()


@_get_deltas.add(const.TRT.ACTIVE_SHALLOW_CRUST)
def _get_deltas_1(trt, 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 for Strike-slip focal mechanisms (0<=rake<=45) or
    # (135<=rake<=180) or (-45<=rake<=0), 0 for all other events
    # delta_V = 1 for TVZ events, 0 for all other events
    # delta_I = 1 for interface events, 0 for all other events