# -*- coding: utf-8 -*-# vim: tabstop=4 shiftwidth=4 softtabstop=4## Copyright (C) 2012-2025 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 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/>."""Module :mod:`openquake.hazardlib.gsim.base` defines base classes fordifferent kinds of :class:`ground shaking intensity models<GroundShakingIntensityModel>`."""importsysimportabcimportinspectimportwarningsimportfunctoolsimporttomlimportnumpyfromopenquake.baselib.generalimportDeprecationWarningfromopenquake.hazardlibimportconstfromopenquake.hazardlib.gsim.coeffs_tableimportCoeffsTablefromopenquake.hazardlib.contextsimport(KNOWN_DISTANCES,full_context,simple_cmaker)ADMITTED_STR_PARAMETERS=['DEFINED_FOR_TECTONIC_REGION_TYPE','DEFINED_FOR_INTENSITY_MEASURE_COMPONENT']ADMITTED_FLOAT_PARAMETERS=['DEFINED_FOR_REFERENCE_VELOCITY']ADMITTED_SET_PARAMETERS=['DEFINED_FOR_INTENSITY_MEASURE_TYPES','DEFINED_FOR_STANDARD_DEVIATION_TYPES','REQUIRES_DISTANCES','REQUIRES_ATTRIBUTES','REQUIRES_SITES_PARAMETERS','REQUIRES_RUPTURE_PARAMETERS']F32=numpy.float32F64=numpy.float64registry={}# GSIM name -> GSIM classgsim_aliases={}# GSIM alias -> TOML representation
[docs]defadd_alias(name,cls,**kw):""" Add a GSIM alias to both gsim_aliases and the registry. """gsim_aliases[name]=toml.dumps({cls.__name__:kw})registry[name]=cls
[docs]classNotVerifiedWarning(UserWarning):""" Raised when a non verified GSIM is instantiated """
[docs]classExperimentalWarning(UserWarning):""" Raised for GMPEs that are intended for experimental use or maybe subject to changes in future version. """
[docs]classAdaptedWarning(UserWarning):""" Raised for GMPEs that are intended for experimental use or maybe subject to changes in future version. """
[docs]defbad_methods(clsdict):""" :returns: list of not acceptable method names """bad=[]forname,valueinclsdict.items():ifnameinOK_METHODSorname.startswith('__')andname.endswith('__'):pass# not badelifinspect.isfunction(value)orhasattr(value,'__func__'):bad.append(name)returnbad
[docs]classMetaGSIM(abc.ABCMeta):""" A metaclass converting set class attributes into frozensets, to avoid mutability bugs without having to change already written GSIMs. Moreover it performs some checks against typos. """def__new__(meta,name,bases,dic):iflen(bases)>1:raiseTypeError('Multiple inheritance is forbidden: %s(%s)'%(name,', '.join(b.__name__forbinbases)))if'get_mean_and_stddevs'indicand'compute'indic:raiseTypeError('You cannot define both get_mean_and_stddevs ''and compute in %s'%name)bad=bad_methods(dic)ifbad:sys.exit('%s cannot contain the methods %s'%(name,bad))fork,vindic.items():if(k=='compute'andv.__annotations__.get("ctx")isnotnumpy.recarray):raiseTypeError('%s.compute is not vectorized'%name)elifisinstance(v,set):dic[k]=frozenset(v)ifk=='REQUIRES_DISTANCES':missing=v-KNOWN_DISTANCESifmissing:raiseValueError('Unknown distance %s in %s'%(missing,name))cls=super().__new__(meta,name,bases,dic)returnclsdef__call__(cls,**kwargs):mixture_model=kwargs.pop('mixture_model',None)self=type.__call__(cls,**kwargs)ifnothasattr(self,'kwargs'):self.kwargs=kwargsifhasattr(self,'gmpe_table'):# used in NGAEast to set the full pathnameself.kwargs['gmpe_table']=self.gmpe_tableifmixture_modelisnotNone:self.mixture_model=mixture_modelreturnself
[docs]@functools.total_orderingclassGroundShakingIntensityModel(metaclass=MetaGSIM):""" Base class for all the ground shaking intensity models. A Ground Shaking Intensity Model (GSIM) defines a set of equations for computing mean and standard deviation of a normal distribution representing the variability of an intensity measure (or of its logarithm) at a site given an earthquake rupture. This class is not intended to be subclassed directly, instead the actual GSIMs should subclass :class:`GMPE`. Subclasses of both must implement :meth:`get_mean_and_stddevs` and all the class attributes with names starting from ``DEFINED_FOR`` and ``REQUIRES``. """#: Reference to a#: :class:`tectonic region type <openquake.hazardlib.const.TRT>` this GSIM#: is defined for. One GSIM can implement only one tectonic region type.DEFINED_FOR_TECTONIC_REGION_TYPE=abc.abstractproperty()#: Set of :mod:`intensity measure types <openquake.hazardlib.imt>`#: this GSIM can#: calculate. A set should contain classes from module#: :mod:`openquake.hazardlib.imt`.DEFINED_FOR_INTENSITY_MEASURE_TYPES=abc.abstractproperty()#: Reference to a :class:`intensity measure component type#: <openquake.hazardlib.const.IMC>` this GSIM can calculate mean#: and standard#: deviation for.DEFINED_FOR_INTENSITY_MEASURE_COMPONENT=abc.abstractproperty()#: Set of#: :class:`standard deviation types <openquake.hazardlib.const.StdDev>`#: this GSIM can calculate.DEFINED_FOR_STANDARD_DEVIATION_TYPES=abc.abstractproperty()#: Set of required GSIM attributesREQUIRES_ATTRIBUTES=set()#: Set of site parameters names this GSIM needs. The set should include#: strings that match names of the attributes of a :class:`site#: <openquake.hazardlib.site.Site>` object.#: Those attributes are then available in the#: :class:`SitesContext` object with the same names.REQUIRES_SITES_PARAMETERS=abc.abstractproperty()#: Set of rupture parameters (excluding distance information) required#: by GSIM. Supported parameters are:#:#: ``mag``#: Magnitude of the rupture.#: ``dip``#: Rupture's surface dip angle in decimal degrees.#: ``rake``#: Angle describing the slip propagation on the rupture surface,#: in decimal degrees. See :mod:`~openquake.hazardlib.geo.nodalplane`#: for more detailed description of dip and rake.#: ``ztor``#: Depth of rupture's top edge in km. See#: :meth:`~openquake.hazardlib.geo.surface.base.BaseSurface.get_top_edge_depth`.#:#: These parameters are available from the :class:`RuptureContext` object#: attributes with same names.REQUIRES_RUPTURE_PARAMETERS=abc.abstractproperty()#: Set of types of distance measures between rupture and sites. Possible#: values are:#:#: ``rrup``#: Closest distance to rupture surface. See#: :meth:`~openquake.hazardlib.geo.surface.base.BaseSurface.get_min_distance`.#: ``rjb``#: Distance to rupture's surface projection. See#: :meth:`~openquake.hazardlib.geo.surface.base.BaseSurface.get_joyner_boore_distance`.#: ``rx``#: Perpendicular distance to rupture top edge projection.#: See :meth:`~openquake.hazardlib.geo.surface.base.BaseSurface.get_rx_distance`.#: ``ry0``#: Horizontal distance off the end of the rupture measured parallel to#: strike.#: See :meth:`~openquake.hazardlib.geo.surface.base.BaseSurface.get_ry0_distance`.#: ``rcdpp``#: Direct point parameter for directivity effect centered on the site- and earthquake-specific#: average DPP used. See#: :meth:`~openquake.hazardlib.source.rupture.ParametricProbabilisticRupture.get_dppvalue`.#: ``rvolc``#: Source to site distance passing through surface projection of volcanic zone.#:#: All the distances are available from the :class:`DistancesContext`#: object attributes with same names. Values are in kilometers.REQUIRES_DISTANCES=abc.abstractproperty()_toml=''# set by valid.gsimsuperseded_by=Nonenon_verified=Falseexperimental=Falseadapted=False@classmethoddef__init_subclass__(cls):stddevtypes=cls.DEFINED_FOR_STANDARD_DEVIATION_TYPESifisinstance(stddevtypes,abc.abstractproperty):# in GMPEreturnelifconst.StdDev.TOTALnotinstddevtypes:raiseValueError('%s.DEFINED_FOR_STANDARD_DEVIATION_TYPES is ''not defined for const.StdDev.TOTAL'%cls.__name__)forattr,ctableinvars(cls).items():ifisinstance(ctable,CoeffsTable):ifnotattr.startswith('COEFFS'):raiseNameError('%s does not start with COEFFS'%attr)registry[cls.__name__]=cls
[docs]defrequires(self):""" :returns: ordered tuple with the required parameters except the mag """tot=set(self.REQUIRES_DISTANCES|self.REQUIRES_RUPTURE_PARAMETERS|self.REQUIRES_SITES_PARAMETERS)returntuple(sorted(tot))
def__init__(self,**kwargs):cls=self.__class__ifcls.superseded_by:msg='%s is deprecated - use %s instead'%(cls.__name__,cls.superseded_by.__name__)warnings.warn(msg,DeprecationWarning)ifcls.non_verified:msg=('%s is not independently verified - the user is liable ''for their application')%cls.__name__warnings.warn(msg,NotVerifiedWarning)ifcls.experimental:msg=('%s is experimental and may change in future versions - ''the user is liable for their application')%cls.__name__warnings.warn(msg,ExperimentalWarning)ifcls.adapted:msg=('%s is not intended for general use and the behaviour ''may not be as expected - ''the user is liable for their application')%cls.__name__warnings.warn(msg,AdaptedWarning)
[docs]defget_mean_and_stddevs(self,sites,rup,dists,imt,stddev_types):""" Calculate and return mean value of intensity distribution and it's standard deviation. Method must be implemented by subclasses. :param sites: Instance of :class:`openquake.hazardlib.site.SiteCollection` with parameters of sites collection assigned to respective values as numpy arrays. Only those attributes that are listed in class' :attr:`REQUIRES_SITES_PARAMETERS` set are available. :param rup: Instance of :class:`openquake.hazardlib.source.rupture.BaseRupture` with parameters of a rupture assigned to respective values. Only those attributes that are listed in class' :attr:`REQUIRES_RUPTURE_PARAMETERS` set are available. :param dists: Instance of :class:`DistancesContext` with values of distance measures between the rupture and each site of the collection assigned to respective values as numpy arrays. Only those attributes that are listed in class' :attr:`REQUIRES_DISTANCES` set are available. :param imt: An instance (not a class) of intensity measure type. See :mod:`openquake.hazardlib.imt`. :param stddev_types: List of standard deviation types, constants from :class:`openquake.hazardlib.const.StdDev`. Method result value should include standard deviation values for each of types in this list. :returns: Method should return a tuple of two items. First item should be a numpy array of floats -- mean values of respective component of a chosen intensity measure type, and the second should be a list of numpy arrays of standard deviation values for the same single component of the same single intensity measure type, one array for each type in ``stddev_types`` parameter, preserving the order. Combining interface to mean and standard deviation values in a single method allows to avoid redoing the same intermediate calculations if there are some shared between stddev and mean formulae without resorting to keeping any sort of internal state (and effectively making GSIM not reenterable). However it is advised to split calculation of mean and stddev values and make ``get_mean_and_stddevs()`` just combine both (and possibly compute interim steps). """# mean and stddevs by calling the underlying .compute methodN=len(sites)mean=numpy.zeros((1,N))sig=numpy.zeros((1,N))tau=numpy.zeros((1,N))phi=numpy.zeros((1,N))ifsitesisnotrupordistsisnotrup:# convert three old-style contexts to a single new-style contextctx=full_context(sites,rup,dists)else:ctx=rup# rup is already a good objectassertself.compute.__annotations__.get("ctx")isnumpy.recarrayifisinstance(rup.mag,float):# in old-fashioned testsmags=['%.2f'%rup.mag]else:# arraymags=['%.2f'%magformaginrup.mag]cmaker=simple_cmaker([self],[imt.string],mags=mags)ifnotisinstance(ctx,numpy.ndarray):ctx=cmaker.recarray([ctx])self.compute(ctx,[imt],mean,sig,tau,phi)stddevs=[]forstddev_typeinstddev_types:ifstddev_type==const.StdDev.TOTAL:stddevs.append(sig[0])elifstddev_type==const.StdDev.INTER_EVENT:stddevs.append(tau[0])elifstddev_type==const.StdDev.INTRA_EVENT:stddevs.append(phi[0])returnmean[0],stddevs
def__lt__(self,other):""" The GSIMs are ordered according to string representation """returnstr(self)<str(other)def__eq__(self,other):""" The GSIMs are equal if their string representations are equal """returnstr(self)==str(other)def__hash__(self):""" We use the __str__ representation as hash: it means that we can use equivalently GSIM instances or strings as dictionary keys. """returnhash(str(self))def__repr__(self):""" String representation for GSIM instances in TOML format. """ifself._toml:returnself._tomlreturn'[%s]'%self.__class__.__name__
[docs]defto_distribution_values(vals,imt):""" :returns: the logarithm of the values unless the IMT is MMI """ifstr(imt)=='MMI':returnvalswithwarnings.catch_warnings():warnings.simplefilter("ignore")returnnumpy.log(vals)
[docs]classGMPE(GroundShakingIntensityModel):""" Ground-Motion Prediction Equation is a subclass of generic :class:`GroundShakingIntensityModel` with a distinct feature that the intensity values are log-normally distributed. """
[docs]defset_parameters(self):""" Combines the parameters of the GMPE provided at the construction level with the ones originally assigned to the backbone modified GMPE. """forkeyin(ADMITTED_STR_PARAMETERS+ADMITTED_FLOAT_PARAMETERS+ADMITTED_SET_PARAMETERS):try:val=getattr(self.gmpe,key)exceptAttributeError:passelse:setattr(self,key,val)
[docs]defcompute(self,ctx:numpy.recarray,imts,mean,sig,tau,phi):""" :param ctx: a RuptureContext object or a numpy recarray of size N :param imts: a list of M Intensity Measure Types :param mean: an array of shape (M, N) for the means :param sig: an array of shape (M, N) for the TOTAL stddevs :param tau: an array of shape (M, N) for the INTER_EVENT stddevs :param phi: an array of shape (M, N) for the INTRA_EVENT stddevs To be overridden in subclasses with a procedure filling the arrays and returning None. """raiseNotImplementedError