id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
500
gem/oq-engine
openquake/hazardlib/sourceconverter.py
RuptureConverter.convert_node
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)
python
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", "convert_node", "(", "self", ",", "node", ")", ":", "convert", "=", "getattr", "(", "self", ",", "'convert_'", "+", "striptag", "(", "node", ".", "tag", ")", ")", "return", "convert", "(", "node", ")" ]
Convert the given rupture node into a hazardlib rupture, depending on the node tag. :param node: a node representing a rupture
[ "Convert", "the", "given", "rupture", "node", "into", "a", "hazardlib", "rupture", "depending", "on", "the", "node", "tag", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L321-L329
501
gem/oq-engine
openquake/hazardlib/sourceconverter.py
RuptureConverter.convert_simpleFaultRupture
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 = source.rupture.BaseRupture( mag=mag, rake=rake, tectonic_region_type=None, hypocenter=hypocenter, surface=self.convert_surfaces(surfaces)) return rupt
python
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 = source.rupture.BaseRupture( mag=mag, rake=rake, tectonic_region_type=None, hypocenter=hypocenter, surface=self.convert_surfaces(surfaces)) return rupt
[ "def", "convert_simpleFaultRupture", "(", "self", ",", "node", ")", ":", "mag", ",", "rake", ",", "hypocenter", "=", "self", ".", "get_mag_rake_hypo", "(", "node", ")", "with", "context", "(", "self", ".", "fname", ",", "node", ")", ":", "surfaces", "=", "[", "node", ".", "simpleFaultGeometry", "]", "rupt", "=", "source", ".", "rupture", ".", "BaseRupture", "(", "mag", "=", "mag", ",", "rake", "=", "rake", ",", "tectonic_region_type", "=", "None", ",", "hypocenter", "=", "hypocenter", ",", "surface", "=", "self", ".", "convert_surfaces", "(", "surfaces", ")", ")", "return", "rupt" ]
Convert a simpleFaultRupture node. :param node: the rupture node
[ "Convert", "a", "simpleFaultRupture", "node", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L414-L427
502
gem/oq-engine
openquake/hazardlib/sourceconverter.py
RuptureConverter.convert_multiPlanesRupture
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')) rupt = source.rupture.BaseRupture( mag=mag, rake=rake, tectonic_region_type=None, hypocenter=hypocenter, surface=self.convert_surfaces(surfaces)) return rupt
python
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')) rupt = source.rupture.BaseRupture( mag=mag, rake=rake, tectonic_region_type=None, hypocenter=hypocenter, surface=self.convert_surfaces(surfaces)) return rupt
[ "def", "convert_multiPlanesRupture", "(", "self", ",", "node", ")", ":", "mag", ",", "rake", ",", "hypocenter", "=", "self", ".", "get_mag_rake_hypo", "(", "node", ")", "with", "context", "(", "self", ".", "fname", ",", "node", ")", ":", "surfaces", "=", "list", "(", "node", ".", "getnodes", "(", "'planarSurface'", ")", ")", "rupt", "=", "source", ".", "rupture", ".", "BaseRupture", "(", "mag", "=", "mag", ",", "rake", "=", "rake", ",", "tectonic_region_type", "=", "None", ",", "hypocenter", "=", "hypocenter", ",", "surface", "=", "self", ".", "convert_surfaces", "(", "surfaces", ")", ")", "return", "rupt" ]
Convert a multiPlanesRupture node. :param node: the rupture node
[ "Convert", "a", "multiPlanesRupture", "node", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L460-L474
503
gem/oq-engine
openquake/hazardlib/sourceconverter.py
SourceConverter.get_tom
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` instance """ if 'tom' in node.attrib: tom_cls = tom.registry[node['tom']] else: tom_cls = tom.registry['PoissonTOM'] return tom_cls(time_span=self.investigation_time, occurrence_rate=node.get('occurrence_rate'))
python
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` instance """ if 'tom' in node.attrib: tom_cls = tom.registry[node['tom']] else: tom_cls = tom.registry['PoissonTOM'] return tom_cls(time_span=self.investigation_time, occurrence_rate=node.get('occurrence_rate'))
[ "def", "get_tom", "(", "self", ",", "node", ")", ":", "if", "'tom'", "in", "node", ".", "attrib", ":", "tom_cls", "=", "tom", ".", "registry", "[", "node", "[", "'tom'", "]", "]", "else", ":", "tom_cls", "=", "tom", ".", "registry", "[", "'PoissonTOM'", "]", "return", "tom_cls", "(", "time_span", "=", "self", ".", "investigation_time", ",", "occurrence_rate", "=", "node", ".", "get", "(", "'occurrence_rate'", ")", ")" ]
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` instance
[ "Convert", "the", "given", "node", "into", "a", "Temporal", "Occurrence", "Model", "object", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L533-L546
504
gem/oq-engine
openquake/hazardlib/sourceconverter.py
SourceConverter.convert_mfdist
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:`openquake.hazardlib.mfd.TruncatedGRMFD` instance """ with context(self.fname, node): [mfd_node] = [subnode for subnode in node if subnode.tag.endswith( ('incrementalMFD', 'truncGutenbergRichterMFD', 'arbitraryMFD', 'YoungsCoppersmithMFD', 'multiMFD'))] if mfd_node.tag.endswith('incrementalMFD'): return mfd.EvenlyDiscretizedMFD( min_mag=mfd_node['minMag'], bin_width=mfd_node['binWidth'], occurrence_rates=~mfd_node.occurRates) elif mfd_node.tag.endswith('truncGutenbergRichterMFD'): return mfd.TruncatedGRMFD( a_val=mfd_node['aValue'], b_val=mfd_node['bValue'], min_mag=mfd_node['minMag'], max_mag=mfd_node['maxMag'], bin_width=self.width_of_mfd_bin) elif mfd_node.tag.endswith('arbitraryMFD'): return mfd.ArbitraryMFD( magnitudes=~mfd_node.magnitudes, occurrence_rates=~mfd_node.occurRates) elif mfd_node.tag.endswith('YoungsCoppersmithMFD'): if "totalMomentRate" in mfd_node.attrib.keys(): # Return Youngs & Coppersmith from the total moment rate return mfd.YoungsCoppersmith1985MFD.from_total_moment_rate( min_mag=mfd_node["minMag"], b_val=mfd_node["bValue"], char_mag=mfd_node["characteristicMag"], total_moment_rate=mfd_node["totalMomentRate"], bin_width=mfd_node["binWidth"]) elif "characteristicRate" in mfd_node.attrib.keys(): # Return Youngs & Coppersmith from the total moment rate return mfd.YoungsCoppersmith1985MFD.\ from_characteristic_rate( min_mag=mfd_node["minMag"], b_val=mfd_node["bValue"], char_mag=mfd_node["characteristicMag"], char_rate=mfd_node["characteristicRate"], bin_width=mfd_node["binWidth"]) elif mfd_node.tag.endswith('multiMFD'): return mfd.multi_mfd.MultiMFD.from_node( mfd_node, self.width_of_mfd_bin)
python
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:`openquake.hazardlib.mfd.TruncatedGRMFD` instance """ with context(self.fname, node): [mfd_node] = [subnode for subnode in node if subnode.tag.endswith( ('incrementalMFD', 'truncGutenbergRichterMFD', 'arbitraryMFD', 'YoungsCoppersmithMFD', 'multiMFD'))] if mfd_node.tag.endswith('incrementalMFD'): return mfd.EvenlyDiscretizedMFD( min_mag=mfd_node['minMag'], bin_width=mfd_node['binWidth'], occurrence_rates=~mfd_node.occurRates) elif mfd_node.tag.endswith('truncGutenbergRichterMFD'): return mfd.TruncatedGRMFD( a_val=mfd_node['aValue'], b_val=mfd_node['bValue'], min_mag=mfd_node['minMag'], max_mag=mfd_node['maxMag'], bin_width=self.width_of_mfd_bin) elif mfd_node.tag.endswith('arbitraryMFD'): return mfd.ArbitraryMFD( magnitudes=~mfd_node.magnitudes, occurrence_rates=~mfd_node.occurRates) elif mfd_node.tag.endswith('YoungsCoppersmithMFD'): if "totalMomentRate" in mfd_node.attrib.keys(): # Return Youngs & Coppersmith from the total moment rate return mfd.YoungsCoppersmith1985MFD.from_total_moment_rate( min_mag=mfd_node["minMag"], b_val=mfd_node["bValue"], char_mag=mfd_node["characteristicMag"], total_moment_rate=mfd_node["totalMomentRate"], bin_width=mfd_node["binWidth"]) elif "characteristicRate" in mfd_node.attrib.keys(): # Return Youngs & Coppersmith from the total moment rate return mfd.YoungsCoppersmith1985MFD.\ from_characteristic_rate( min_mag=mfd_node["minMag"], b_val=mfd_node["bValue"], char_mag=mfd_node["characteristicMag"], char_rate=mfd_node["characteristicRate"], bin_width=mfd_node["binWidth"]) elif mfd_node.tag.endswith('multiMFD'): return mfd.multi_mfd.MultiMFD.from_node( mfd_node, self.width_of_mfd_bin)
[ "def", "convert_mfdist", "(", "self", ",", "node", ")", ":", "with", "context", "(", "self", ".", "fname", ",", "node", ")", ":", "[", "mfd_node", "]", "=", "[", "subnode", "for", "subnode", "in", "node", "if", "subnode", ".", "tag", ".", "endswith", "(", "(", "'incrementalMFD'", ",", "'truncGutenbergRichterMFD'", ",", "'arbitraryMFD'", ",", "'YoungsCoppersmithMFD'", ",", "'multiMFD'", ")", ")", "]", "if", "mfd_node", ".", "tag", ".", "endswith", "(", "'incrementalMFD'", ")", ":", "return", "mfd", ".", "EvenlyDiscretizedMFD", "(", "min_mag", "=", "mfd_node", "[", "'minMag'", "]", ",", "bin_width", "=", "mfd_node", "[", "'binWidth'", "]", ",", "occurrence_rates", "=", "~", "mfd_node", ".", "occurRates", ")", "elif", "mfd_node", ".", "tag", ".", "endswith", "(", "'truncGutenbergRichterMFD'", ")", ":", "return", "mfd", ".", "TruncatedGRMFD", "(", "a_val", "=", "mfd_node", "[", "'aValue'", "]", ",", "b_val", "=", "mfd_node", "[", "'bValue'", "]", ",", "min_mag", "=", "mfd_node", "[", "'minMag'", "]", ",", "max_mag", "=", "mfd_node", "[", "'maxMag'", "]", ",", "bin_width", "=", "self", ".", "width_of_mfd_bin", ")", "elif", "mfd_node", ".", "tag", ".", "endswith", "(", "'arbitraryMFD'", ")", ":", "return", "mfd", ".", "ArbitraryMFD", "(", "magnitudes", "=", "~", "mfd_node", ".", "magnitudes", ",", "occurrence_rates", "=", "~", "mfd_node", ".", "occurRates", ")", "elif", "mfd_node", ".", "tag", ".", "endswith", "(", "'YoungsCoppersmithMFD'", ")", ":", "if", "\"totalMomentRate\"", "in", "mfd_node", ".", "attrib", ".", "keys", "(", ")", ":", "# Return Youngs & Coppersmith from the total moment rate", "return", "mfd", ".", "YoungsCoppersmith1985MFD", ".", "from_total_moment_rate", "(", "min_mag", "=", "mfd_node", "[", "\"minMag\"", "]", ",", "b_val", "=", "mfd_node", "[", "\"bValue\"", "]", ",", "char_mag", "=", "mfd_node", "[", "\"characteristicMag\"", "]", ",", "total_moment_rate", "=", "mfd_node", "[", "\"totalMomentRate\"", "]", ",", "bin_width", "=", "mfd_node", "[", "\"binWidth\"", "]", ")", "elif", "\"characteristicRate\"", "in", "mfd_node", ".", "attrib", ".", "keys", "(", ")", ":", "# Return Youngs & Coppersmith from the total moment rate", "return", "mfd", ".", "YoungsCoppersmith1985MFD", ".", "from_characteristic_rate", "(", "min_mag", "=", "mfd_node", "[", "\"minMag\"", "]", ",", "b_val", "=", "mfd_node", "[", "\"bValue\"", "]", ",", "char_mag", "=", "mfd_node", "[", "\"characteristicMag\"", "]", ",", "char_rate", "=", "mfd_node", "[", "\"characteristicRate\"", "]", ",", "bin_width", "=", "mfd_node", "[", "\"binWidth\"", "]", ")", "elif", "mfd_node", ".", "tag", ".", "endswith", "(", "'multiMFD'", ")", ":", "return", "mfd", ".", "multi_mfd", ".", "MultiMFD", ".", "from_node", "(", "mfd_node", ",", "self", ".", "width_of_mfd_bin", ")" ]
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:`openquake.hazardlib.mfd.TruncatedGRMFD` instance
[ "Convert", "the", "given", "node", "into", "a", "Magnitude", "-", "Frequency", "Distribution", "object", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L548-L595
505
gem/oq-engine
openquake/hazardlib/sourceconverter.py
SourceConverter.convert_npdist
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 in node.nodalPlaneDist: prob, strike, dip, rake = ( np['probability'], np['strike'], np['dip'], np['rake']) npdist.append((prob, geo.NodalPlane(strike, dip, rake))) if not self.spinning_floating: npdist = [(1, npdist[0][1])] # consider the first nodal plane return pmf.PMF(npdist)
python
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 in node.nodalPlaneDist: prob, strike, dip, rake = ( np['probability'], np['strike'], np['dip'], np['rake']) npdist.append((prob, geo.NodalPlane(strike, dip, rake))) if not self.spinning_floating: npdist = [(1, npdist[0][1])] # consider the first nodal plane return pmf.PMF(npdist)
[ "def", "convert_npdist", "(", "self", ",", "node", ")", ":", "with", "context", "(", "self", ".", "fname", ",", "node", ")", ":", "npdist", "=", "[", "]", "for", "np", "in", "node", ".", "nodalPlaneDist", ":", "prob", ",", "strike", ",", "dip", ",", "rake", "=", "(", "np", "[", "'probability'", "]", ",", "np", "[", "'strike'", "]", ",", "np", "[", "'dip'", "]", ",", "np", "[", "'rake'", "]", ")", "npdist", ".", "append", "(", "(", "prob", ",", "geo", ".", "NodalPlane", "(", "strike", ",", "dip", ",", "rake", ")", ")", ")", "if", "not", "self", ".", "spinning_floating", ":", "npdist", "=", "[", "(", "1", ",", "npdist", "[", "0", "]", "[", "1", "]", ")", "]", "# consider the first nodal plane", "return", "pmf", ".", "PMF", "(", "npdist", ")" ]
Convert the given node into a Nodal Plane Distribution. :param node: a nodalPlaneDist node :returns: a :class:`openquake.hazardlib.geo.NodalPlane` instance
[ "Convert", "the", "given", "node", "into", "a", "Nodal", "Plane", "Distribution", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L597-L612
506
gem/oq-engine
openquake/hazardlib/sourceconverter.py
SourceConverter.convert_hpdist
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): hcdist = [(hd['probability'], hd['depth']) for hd in node.hypoDepthDist] if not self.spinning_floating: # consider the first hypocenter hcdist = [(1, hcdist[0][1])] return pmf.PMF(hcdist)
python
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): hcdist = [(hd['probability'], hd['depth']) for hd in node.hypoDepthDist] if not self.spinning_floating: # consider the first hypocenter hcdist = [(1, hcdist[0][1])] return pmf.PMF(hcdist)
[ "def", "convert_hpdist", "(", "self", ",", "node", ")", ":", "with", "context", "(", "self", ".", "fname", ",", "node", ")", ":", "hcdist", "=", "[", "(", "hd", "[", "'probability'", "]", ",", "hd", "[", "'depth'", "]", ")", "for", "hd", "in", "node", ".", "hypoDepthDist", "]", "if", "not", "self", ".", "spinning_floating", ":", "# consider the first hypocenter", "hcdist", "=", "[", "(", "1", ",", "hcdist", "[", "0", "]", "[", "1", "]", ")", "]", "return", "pmf", ".", "PMF", "(", "hcdist", ")" ]
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
[ "Convert", "the", "given", "node", "into", "a", "probability", "mass", "function", "for", "the", "hypo", "depth", "distribution", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L614-L627
507
gem/oq-engine
openquake/hazardlib/sourceconverter.py
SourceConverter.convert_areaSource
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.Polygon.exterior.LinearRing.posList) polygon = geo.Polygon([geo.Point(*xy) for xy in coords]) msr = valid.SCALEREL[~node.magScaleRel]() area_discretization = geom.attrib.get( 'discretization', self.area_source_discretization) if area_discretization is None: raise ValueError( 'The source %r has no `discretization` parameter and the job.' 'ini file has no `area_source_discretization` parameter either' % node['id']) return source.AreaSource( source_id=node['id'], name=node['name'], tectonic_region_type=node.attrib.get('tectonicRegion'), mfd=self.convert_mfdist(node), rupture_mesh_spacing=self.rupture_mesh_spacing, magnitude_scaling_relationship=msr, rupture_aspect_ratio=~node.ruptAspectRatio, upper_seismogenic_depth=~geom.upperSeismoDepth, lower_seismogenic_depth=~geom.lowerSeismoDepth, nodal_plane_distribution=self.convert_npdist(node), hypocenter_distribution=self.convert_hpdist(node), polygon=polygon, area_discretization=area_discretization, temporal_occurrence_model=self.get_tom(node))
python
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.Polygon.exterior.LinearRing.posList) polygon = geo.Polygon([geo.Point(*xy) for xy in coords]) msr = valid.SCALEREL[~node.magScaleRel]() area_discretization = geom.attrib.get( 'discretization', self.area_source_discretization) if area_discretization is None: raise ValueError( 'The source %r has no `discretization` parameter and the job.' 'ini file has no `area_source_discretization` parameter either' % node['id']) return source.AreaSource( source_id=node['id'], name=node['name'], tectonic_region_type=node.attrib.get('tectonicRegion'), mfd=self.convert_mfdist(node), rupture_mesh_spacing=self.rupture_mesh_spacing, magnitude_scaling_relationship=msr, rupture_aspect_ratio=~node.ruptAspectRatio, upper_seismogenic_depth=~geom.upperSeismoDepth, lower_seismogenic_depth=~geom.lowerSeismoDepth, nodal_plane_distribution=self.convert_npdist(node), hypocenter_distribution=self.convert_hpdist(node), polygon=polygon, area_discretization=area_discretization, temporal_occurrence_model=self.get_tom(node))
[ "def", "convert_areaSource", "(", "self", ",", "node", ")", ":", "geom", "=", "node", ".", "areaGeometry", "coords", "=", "split_coords_2d", "(", "~", "geom", ".", "Polygon", ".", "exterior", ".", "LinearRing", ".", "posList", ")", "polygon", "=", "geo", ".", "Polygon", "(", "[", "geo", ".", "Point", "(", "*", "xy", ")", "for", "xy", "in", "coords", "]", ")", "msr", "=", "valid", ".", "SCALEREL", "[", "~", "node", ".", "magScaleRel", "]", "(", ")", "area_discretization", "=", "geom", ".", "attrib", ".", "get", "(", "'discretization'", ",", "self", ".", "area_source_discretization", ")", "if", "area_discretization", "is", "None", ":", "raise", "ValueError", "(", "'The source %r has no `discretization` parameter and the job.'", "'ini file has no `area_source_discretization` parameter either'", "%", "node", "[", "'id'", "]", ")", "return", "source", ".", "AreaSource", "(", "source_id", "=", "node", "[", "'id'", "]", ",", "name", "=", "node", "[", "'name'", "]", ",", "tectonic_region_type", "=", "node", ".", "attrib", ".", "get", "(", "'tectonicRegion'", ")", ",", "mfd", "=", "self", ".", "convert_mfdist", "(", "node", ")", ",", "rupture_mesh_spacing", "=", "self", ".", "rupture_mesh_spacing", ",", "magnitude_scaling_relationship", "=", "msr", ",", "rupture_aspect_ratio", "=", "~", "node", ".", "ruptAspectRatio", ",", "upper_seismogenic_depth", "=", "~", "geom", ".", "upperSeismoDepth", ",", "lower_seismogenic_depth", "=", "~", "geom", ".", "lowerSeismoDepth", ",", "nodal_plane_distribution", "=", "self", ".", "convert_npdist", "(", "node", ")", ",", "hypocenter_distribution", "=", "self", ".", "convert_hpdist", "(", "node", ")", ",", "polygon", "=", "polygon", ",", "area_discretization", "=", "area_discretization", ",", "temporal_occurrence_model", "=", "self", ".", "get_tom", "(", "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
[ "Convert", "the", "given", "node", "into", "an", "area", "source", "object", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L629-L661
508
gem/oq-engine
openquake/hazardlib/sourceconverter.py
SourceConverter.convert_pointSource
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 msr = valid.SCALEREL[~node.magScaleRel]() return source.PointSource( source_id=node['id'], name=node['name'], tectonic_region_type=node.attrib.get('tectonicRegion'), mfd=self.convert_mfdist(node), rupture_mesh_spacing=self.rupture_mesh_spacing, magnitude_scaling_relationship=msr, rupture_aspect_ratio=~node.ruptAspectRatio, upper_seismogenic_depth=~geom.upperSeismoDepth, lower_seismogenic_depth=~geom.lowerSeismoDepth, location=geo.Point(*lon_lat), nodal_plane_distribution=self.convert_npdist(node), hypocenter_distribution=self.convert_hpdist(node), temporal_occurrence_model=self.get_tom(node))
python
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 msr = valid.SCALEREL[~node.magScaleRel]() return source.PointSource( source_id=node['id'], name=node['name'], tectonic_region_type=node.attrib.get('tectonicRegion'), mfd=self.convert_mfdist(node), rupture_mesh_spacing=self.rupture_mesh_spacing, magnitude_scaling_relationship=msr, rupture_aspect_ratio=~node.ruptAspectRatio, upper_seismogenic_depth=~geom.upperSeismoDepth, lower_seismogenic_depth=~geom.lowerSeismoDepth, location=geo.Point(*lon_lat), nodal_plane_distribution=self.convert_npdist(node), hypocenter_distribution=self.convert_hpdist(node), temporal_occurrence_model=self.get_tom(node))
[ "def", "convert_pointSource", "(", "self", ",", "node", ")", ":", "geom", "=", "node", ".", "pointGeometry", "lon_lat", "=", "~", "geom", ".", "Point", ".", "pos", "msr", "=", "valid", ".", "SCALEREL", "[", "~", "node", ".", "magScaleRel", "]", "(", ")", "return", "source", ".", "PointSource", "(", "source_id", "=", "node", "[", "'id'", "]", ",", "name", "=", "node", "[", "'name'", "]", ",", "tectonic_region_type", "=", "node", ".", "attrib", ".", "get", "(", "'tectonicRegion'", ")", ",", "mfd", "=", "self", ".", "convert_mfdist", "(", "node", ")", ",", "rupture_mesh_spacing", "=", "self", ".", "rupture_mesh_spacing", ",", "magnitude_scaling_relationship", "=", "msr", ",", "rupture_aspect_ratio", "=", "~", "node", ".", "ruptAspectRatio", ",", "upper_seismogenic_depth", "=", "~", "geom", ".", "upperSeismoDepth", ",", "lower_seismogenic_depth", "=", "~", "geom", ".", "lowerSeismoDepth", ",", "location", "=", "geo", ".", "Point", "(", "*", "lon_lat", ")", ",", "nodal_plane_distribution", "=", "self", ".", "convert_npdist", "(", "node", ")", ",", "hypocenter_distribution", "=", "self", ".", "convert_hpdist", "(", "node", ")", ",", "temporal_occurrence_model", "=", "self", ".", "get_tom", "(", "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
[ "Convert", "the", "given", "node", "into", "a", "point", "source", "object", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L663-L686
509
gem/oq-engine
openquake/hazardlib/sourceconverter.py
SourceConverter.convert_multiPointSource
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 = zip(*split_coords_2d(~geom.posList)) msr = valid.SCALEREL[~node.magScaleRel]() return source.MultiPointSource( source_id=node['id'], name=node['name'], tectonic_region_type=node.attrib.get('tectonicRegion'), mfd=self.convert_mfdist(node), magnitude_scaling_relationship=msr, rupture_aspect_ratio=~node.ruptAspectRatio, upper_seismogenic_depth=~geom.upperSeismoDepth, lower_seismogenic_depth=~geom.lowerSeismoDepth, nodal_plane_distribution=self.convert_npdist(node), hypocenter_distribution=self.convert_hpdist(node), mesh=geo.Mesh(F32(lons), F32(lats)), temporal_occurrence_model=self.get_tom(node))
python
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 = zip(*split_coords_2d(~geom.posList)) msr = valid.SCALEREL[~node.magScaleRel]() return source.MultiPointSource( source_id=node['id'], name=node['name'], tectonic_region_type=node.attrib.get('tectonicRegion'), mfd=self.convert_mfdist(node), magnitude_scaling_relationship=msr, rupture_aspect_ratio=~node.ruptAspectRatio, upper_seismogenic_depth=~geom.upperSeismoDepth, lower_seismogenic_depth=~geom.lowerSeismoDepth, nodal_plane_distribution=self.convert_npdist(node), hypocenter_distribution=self.convert_hpdist(node), mesh=geo.Mesh(F32(lons), F32(lats)), temporal_occurrence_model=self.get_tom(node))
[ "def", "convert_multiPointSource", "(", "self", ",", "node", ")", ":", "geom", "=", "node", ".", "multiPointGeometry", "lons", ",", "lats", "=", "zip", "(", "*", "split_coords_2d", "(", "~", "geom", ".", "posList", ")", ")", "msr", "=", "valid", ".", "SCALEREL", "[", "~", "node", ".", "magScaleRel", "]", "(", ")", "return", "source", ".", "MultiPointSource", "(", "source_id", "=", "node", "[", "'id'", "]", ",", "name", "=", "node", "[", "'name'", "]", ",", "tectonic_region_type", "=", "node", ".", "attrib", ".", "get", "(", "'tectonicRegion'", ")", ",", "mfd", "=", "self", ".", "convert_mfdist", "(", "node", ")", ",", "magnitude_scaling_relationship", "=", "msr", ",", "rupture_aspect_ratio", "=", "~", "node", ".", "ruptAspectRatio", ",", "upper_seismogenic_depth", "=", "~", "geom", ".", "upperSeismoDepth", ",", "lower_seismogenic_depth", "=", "~", "geom", ".", "lowerSeismoDepth", ",", "nodal_plane_distribution", "=", "self", ".", "convert_npdist", "(", "node", ")", ",", "hypocenter_distribution", "=", "self", ".", "convert_hpdist", "(", "node", ")", ",", "mesh", "=", "geo", ".", "Mesh", "(", "F32", "(", "lons", ")", ",", "F32", "(", "lats", ")", ")", ",", "temporal_occurrence_model", "=", "self", ".", "get_tom", "(", "node", ")", ")" ]
Convert the given node into a MultiPointSource object. :param node: a node with tag multiPointGeometry :returns: a :class:`openquake.hazardlib.source.MultiPointSource`
[ "Convert", "the", "given", "node", "into", "a", "MultiPointSource", "object", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L688-L710
510
gem/oq-engine
openquake/hazardlib/sourceconverter.py
SourceConverter.convert_simpleFaultSource
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 msr = valid.SCALEREL[~node.magScaleRel]() fault_trace = self.geo_line(geom) mfd = self.convert_mfdist(node) with context(self.fname, node): try: hypo_list = valid.hypo_list(node.hypoList) except AttributeError: hypo_list = () try: slip_list = valid.slip_list(node.slipList) except AttributeError: slip_list = () simple = source.SimpleFaultSource( source_id=node['id'], name=node['name'], tectonic_region_type=node.attrib.get('tectonicRegion'), mfd=mfd, rupture_mesh_spacing=self.rupture_mesh_spacing, magnitude_scaling_relationship=msr, rupture_aspect_ratio=~node.ruptAspectRatio, upper_seismogenic_depth=~geom.upperSeismoDepth, lower_seismogenic_depth=~geom.lowerSeismoDepth, fault_trace=fault_trace, dip=~geom.dip, rake=~node.rake, temporal_occurrence_model=self.get_tom(node), hypo_list=hypo_list, slip_list=slip_list) return simple
python
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 msr = valid.SCALEREL[~node.magScaleRel]() fault_trace = self.geo_line(geom) mfd = self.convert_mfdist(node) with context(self.fname, node): try: hypo_list = valid.hypo_list(node.hypoList) except AttributeError: hypo_list = () try: slip_list = valid.slip_list(node.slipList) except AttributeError: slip_list = () simple = source.SimpleFaultSource( source_id=node['id'], name=node['name'], tectonic_region_type=node.attrib.get('tectonicRegion'), mfd=mfd, rupture_mesh_spacing=self.rupture_mesh_spacing, magnitude_scaling_relationship=msr, rupture_aspect_ratio=~node.ruptAspectRatio, upper_seismogenic_depth=~geom.upperSeismoDepth, lower_seismogenic_depth=~geom.lowerSeismoDepth, fault_trace=fault_trace, dip=~geom.dip, rake=~node.rake, temporal_occurrence_model=self.get_tom(node), hypo_list=hypo_list, slip_list=slip_list) return simple
[ "def", "convert_simpleFaultSource", "(", "self", ",", "node", ")", ":", "geom", "=", "node", ".", "simpleFaultGeometry", "msr", "=", "valid", ".", "SCALEREL", "[", "~", "node", ".", "magScaleRel", "]", "(", ")", "fault_trace", "=", "self", ".", "geo_line", "(", "geom", ")", "mfd", "=", "self", ".", "convert_mfdist", "(", "node", ")", "with", "context", "(", "self", ".", "fname", ",", "node", ")", ":", "try", ":", "hypo_list", "=", "valid", ".", "hypo_list", "(", "node", ".", "hypoList", ")", "except", "AttributeError", ":", "hypo_list", "=", "(", ")", "try", ":", "slip_list", "=", "valid", ".", "slip_list", "(", "node", ".", "slipList", ")", "except", "AttributeError", ":", "slip_list", "=", "(", ")", "simple", "=", "source", ".", "SimpleFaultSource", "(", "source_id", "=", "node", "[", "'id'", "]", ",", "name", "=", "node", "[", "'name'", "]", ",", "tectonic_region_type", "=", "node", ".", "attrib", ".", "get", "(", "'tectonicRegion'", ")", ",", "mfd", "=", "mfd", ",", "rupture_mesh_spacing", "=", "self", ".", "rupture_mesh_spacing", ",", "magnitude_scaling_relationship", "=", "msr", ",", "rupture_aspect_ratio", "=", "~", "node", ".", "ruptAspectRatio", ",", "upper_seismogenic_depth", "=", "~", "geom", ".", "upperSeismoDepth", ",", "lower_seismogenic_depth", "=", "~", "geom", ".", "lowerSeismoDepth", ",", "fault_trace", "=", "fault_trace", ",", "dip", "=", "~", "geom", ".", "dip", ",", "rake", "=", "~", "node", ".", "rake", ",", "temporal_occurrence_model", "=", "self", ".", "get_tom", "(", "node", ")", ",", "hypo_list", "=", "hypo_list", ",", "slip_list", "=", "slip_list", ")", "return", "simple" ]
Convert the given node into a simple fault object. :param node: a node with tag areaGeometry :returns: a :class:`openquake.hazardlib.source.SimpleFaultSource` instance
[ "Convert", "the", "given", "node", "into", "a", "simple", "fault", "object", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L712-L749
511
gem/oq-engine
openquake/hazardlib/sourceconverter.py
SourceConverter.convert_complexFaultSource
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.complexFaultGeometry edges = self.geo_lines(geom) mfd = self.convert_mfdist(node) msr = valid.SCALEREL[~node.magScaleRel]() with context(self.fname, node): cmplx = source.ComplexFaultSource( source_id=node['id'], name=node['name'], tectonic_region_type=node.attrib.get('tectonicRegion'), mfd=mfd, rupture_mesh_spacing=self.complex_fault_mesh_spacing, magnitude_scaling_relationship=msr, rupture_aspect_ratio=~node.ruptAspectRatio, edges=edges, rake=~node.rake, temporal_occurrence_model=self.get_tom(node)) return cmplx
python
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.complexFaultGeometry edges = self.geo_lines(geom) mfd = self.convert_mfdist(node) msr = valid.SCALEREL[~node.magScaleRel]() with context(self.fname, node): cmplx = source.ComplexFaultSource( source_id=node['id'], name=node['name'], tectonic_region_type=node.attrib.get('tectonicRegion'), mfd=mfd, rupture_mesh_spacing=self.complex_fault_mesh_spacing, magnitude_scaling_relationship=msr, rupture_aspect_ratio=~node.ruptAspectRatio, edges=edges, rake=~node.rake, temporal_occurrence_model=self.get_tom(node)) return cmplx
[ "def", "convert_complexFaultSource", "(", "self", ",", "node", ")", ":", "geom", "=", "node", ".", "complexFaultGeometry", "edges", "=", "self", ".", "geo_lines", "(", "geom", ")", "mfd", "=", "self", ".", "convert_mfdist", "(", "node", ")", "msr", "=", "valid", ".", "SCALEREL", "[", "~", "node", ".", "magScaleRel", "]", "(", ")", "with", "context", "(", "self", ".", "fname", ",", "node", ")", ":", "cmplx", "=", "source", ".", "ComplexFaultSource", "(", "source_id", "=", "node", "[", "'id'", "]", ",", "name", "=", "node", "[", "'name'", "]", ",", "tectonic_region_type", "=", "node", ".", "attrib", ".", "get", "(", "'tectonicRegion'", ")", ",", "mfd", "=", "mfd", ",", "rupture_mesh_spacing", "=", "self", ".", "complex_fault_mesh_spacing", ",", "magnitude_scaling_relationship", "=", "msr", ",", "rupture_aspect_ratio", "=", "~", "node", ".", "ruptAspectRatio", ",", "edges", "=", "edges", ",", "rake", "=", "~", "node", ".", "rake", ",", "temporal_occurrence_model", "=", "self", ".", "get_tom", "(", "node", ")", ")", "return", "cmplx" ]
Convert the given node into a complex fault object. :param node: a node with tag areaGeometry :returns: a :class:`openquake.hazardlib.source.ComplexFaultSource` instance
[ "Convert", "the", "given", "node", "into", "a", "complex", "fault", "object", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L751-L775
512
gem/oq-engine
openquake/hazardlib/sourceconverter.py
SourceConverter.convert_characteristicFaultSource
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 """ char = source.CharacteristicFaultSource( source_id=node['id'], name=node['name'], tectonic_region_type=node.attrib.get('tectonicRegion'), mfd=self.convert_mfdist(node), surface=self.convert_surfaces(node.surface), rake=~node.rake, temporal_occurrence_model=self.get_tom(node)) return char
python
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 """ char = source.CharacteristicFaultSource( source_id=node['id'], name=node['name'], tectonic_region_type=node.attrib.get('tectonicRegion'), mfd=self.convert_mfdist(node), surface=self.convert_surfaces(node.surface), rake=~node.rake, temporal_occurrence_model=self.get_tom(node)) return char
[ "def", "convert_characteristicFaultSource", "(", "self", ",", "node", ")", ":", "char", "=", "source", ".", "CharacteristicFaultSource", "(", "source_id", "=", "node", "[", "'id'", "]", ",", "name", "=", "node", "[", "'name'", "]", ",", "tectonic_region_type", "=", "node", ".", "attrib", ".", "get", "(", "'tectonicRegion'", ")", ",", "mfd", "=", "self", ".", "convert_mfdist", "(", "node", ")", ",", "surface", "=", "self", ".", "convert_surfaces", "(", "node", ".", "surface", ")", ",", "rake", "=", "~", "node", ".", "rake", ",", "temporal_occurrence_model", "=", "self", ".", "get_tom", "(", "node", ")", ")", "return", "char" ]
Convert the given node into a characteristic fault object. :param node: a node with tag areaGeometry :returns: a :class:`openquake.hazardlib.source.CharacteristicFaultSource` instance
[ "Convert", "the", "given", "node", "into", "a", "characteristic", "fault", "object", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L777-L795
513
gem/oq-engine
openquake/hazardlib/sourceconverter.py
SourceConverter.convert_nonParametricSeismicSource
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 """ trt = node.attrib.get('tectonicRegion') rup_pmf_data = [] rups_weights = None if 'rup_weights' in node.attrib: tmp = node.attrib.get('rup_weights') rups_weights = numpy.array([float(s) for s in tmp.split()]) for i, rupnode in enumerate(node): probs = pmf.PMF(valid.pmf(rupnode['probs_occur'])) rup = RuptureConverter.convert_node(self, rupnode) rup.tectonic_region_type = trt rup.weight = None if rups_weights is None else rups_weights[i] rup_pmf_data.append((rup, probs)) nps = source.NonParametricSeismicSource( node['id'], node['name'], trt, rup_pmf_data) nps.splittable = 'rup_weights' not in node.attrib return nps
python
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 """ trt = node.attrib.get('tectonicRegion') rup_pmf_data = [] rups_weights = None if 'rup_weights' in node.attrib: tmp = node.attrib.get('rup_weights') rups_weights = numpy.array([float(s) for s in tmp.split()]) for i, rupnode in enumerate(node): probs = pmf.PMF(valid.pmf(rupnode['probs_occur'])) rup = RuptureConverter.convert_node(self, rupnode) rup.tectonic_region_type = trt rup.weight = None if rups_weights is None else rups_weights[i] rup_pmf_data.append((rup, probs)) nps = source.NonParametricSeismicSource( node['id'], node['name'], trt, rup_pmf_data) nps.splittable = 'rup_weights' not in node.attrib return nps
[ "def", "convert_nonParametricSeismicSource", "(", "self", ",", "node", ")", ":", "trt", "=", "node", ".", "attrib", ".", "get", "(", "'tectonicRegion'", ")", "rup_pmf_data", "=", "[", "]", "rups_weights", "=", "None", "if", "'rup_weights'", "in", "node", ".", "attrib", ":", "tmp", "=", "node", ".", "attrib", ".", "get", "(", "'rup_weights'", ")", "rups_weights", "=", "numpy", ".", "array", "(", "[", "float", "(", "s", ")", "for", "s", "in", "tmp", ".", "split", "(", ")", "]", ")", "for", "i", ",", "rupnode", "in", "enumerate", "(", "node", ")", ":", "probs", "=", "pmf", ".", "PMF", "(", "valid", ".", "pmf", "(", "rupnode", "[", "'probs_occur'", "]", ")", ")", "rup", "=", "RuptureConverter", ".", "convert_node", "(", "self", ",", "rupnode", ")", "rup", ".", "tectonic_region_type", "=", "trt", "rup", ".", "weight", "=", "None", "if", "rups_weights", "is", "None", "else", "rups_weights", "[", "i", "]", "rup_pmf_data", ".", "append", "(", "(", "rup", ",", "probs", ")", ")", "nps", "=", "source", ".", "NonParametricSeismicSource", "(", "node", "[", "'id'", "]", ",", "node", "[", "'name'", "]", ",", "trt", ",", "rup_pmf_data", ")", "nps", ".", "splittable", "=", "'rup_weights'", "not", "in", "node", ".", "attrib", "return", "nps" ]
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
[ "Convert", "the", "given", "node", "into", "a", "non", "parametric", "source", "object", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L797-L822
514
gem/oq-engine
openquake/hazardlib/sourceconverter.py
SourceConverter.convert_sourceGroup
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('srcs_weights') grp_attrs = {k: v for k, v in node.attrib.items() if k not in ('name', 'src_interdep', 'rup_interdep', 'srcs_weights')} sg = SourceGroup(trt, min_mag=self.minimum_magnitude) sg.temporal_occurrence_model = self.get_tom(node) sg.name = node.attrib.get('name') # Set attributes related to occurrence sg.src_interdep = node.attrib.get('src_interdep', 'indep') sg.rup_interdep = node.attrib.get('rup_interdep', 'indep') sg.grp_probability = node.attrib.get('grp_probability') # Set the cluster attribute sg.cluster = node.attrib.get('cluster') == 'true' # Filter admitted cases # 1. The source group is a cluster. In this case the cluster must have # the attributes required to define its occurrence in time. if sg.cluster: msg = 'A cluster group requires the definition of a temporal' msg += ' occurrence model' assert 'tom' in node.attrib, msg if isinstance(tom, PoissonTOM): assert hasattr(sg, 'occurrence_rate') # for src_node in node: if self.source_id and self.source_id != src_node['id']: continue # filter by source_id src = self.convert_node(src_node) # transmit the group attributes to the underlying source for attr, value in grp_attrs.items(): if attr == 'tectonicRegion': src_trt = src_node.get('tectonicRegion') if src_trt and src_trt != trt: with context(self.fname, src_node): raise ValueError('Found %s, expected %s' % (src_node['tectonicRegion'], trt)) src.tectonic_region_type = trt elif attr == 'grp_probability': pass # do not transmit else: # transmit as it is setattr(src, attr, node[attr]) sg.update(src) if srcs_weights is not None: if len(node) and len(srcs_weights) != len(node): raise ValueError( 'There are %d srcs_weights but %d source(s) in %s' % (len(srcs_weights), len(node), self.fname)) for src, sw in zip(sg, srcs_weights): src.mutex_weight = sw # check that, when the cluster option is set, the group has a temporal # occurrence model properly defined if sg.cluster and not hasattr(sg, 'temporal_occurrence_model'): msg = 'The Source Group is a cluster but does not have a ' msg += 'temporal occurrence model' raise ValueError(msg) return sg
python
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('srcs_weights') grp_attrs = {k: v for k, v in node.attrib.items() if k not in ('name', 'src_interdep', 'rup_interdep', 'srcs_weights')} sg = SourceGroup(trt, min_mag=self.minimum_magnitude) sg.temporal_occurrence_model = self.get_tom(node) sg.name = node.attrib.get('name') # Set attributes related to occurrence sg.src_interdep = node.attrib.get('src_interdep', 'indep') sg.rup_interdep = node.attrib.get('rup_interdep', 'indep') sg.grp_probability = node.attrib.get('grp_probability') # Set the cluster attribute sg.cluster = node.attrib.get('cluster') == 'true' # Filter admitted cases # 1. The source group is a cluster. In this case the cluster must have # the attributes required to define its occurrence in time. if sg.cluster: msg = 'A cluster group requires the definition of a temporal' msg += ' occurrence model' assert 'tom' in node.attrib, msg if isinstance(tom, PoissonTOM): assert hasattr(sg, 'occurrence_rate') # for src_node in node: if self.source_id and self.source_id != src_node['id']: continue # filter by source_id src = self.convert_node(src_node) # transmit the group attributes to the underlying source for attr, value in grp_attrs.items(): if attr == 'tectonicRegion': src_trt = src_node.get('tectonicRegion') if src_trt and src_trt != trt: with context(self.fname, src_node): raise ValueError('Found %s, expected %s' % (src_node['tectonicRegion'], trt)) src.tectonic_region_type = trt elif attr == 'grp_probability': pass # do not transmit else: # transmit as it is setattr(src, attr, node[attr]) sg.update(src) if srcs_weights is not None: if len(node) and len(srcs_weights) != len(node): raise ValueError( 'There are %d srcs_weights but %d source(s) in %s' % (len(srcs_weights), len(node), self.fname)) for src, sw in zip(sg, srcs_weights): src.mutex_weight = sw # check that, when the cluster option is set, the group has a temporal # occurrence model properly defined if sg.cluster and not hasattr(sg, 'temporal_occurrence_model'): msg = 'The Source Group is a cluster but does not have a ' msg += 'temporal occurrence model' raise ValueError(msg) return sg
[ "def", "convert_sourceGroup", "(", "self", ",", "node", ")", ":", "trt", "=", "node", "[", "'tectonicRegion'", "]", "srcs_weights", "=", "node", ".", "attrib", ".", "get", "(", "'srcs_weights'", ")", "grp_attrs", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "node", ".", "attrib", ".", "items", "(", ")", "if", "k", "not", "in", "(", "'name'", ",", "'src_interdep'", ",", "'rup_interdep'", ",", "'srcs_weights'", ")", "}", "sg", "=", "SourceGroup", "(", "trt", ",", "min_mag", "=", "self", ".", "minimum_magnitude", ")", "sg", ".", "temporal_occurrence_model", "=", "self", ".", "get_tom", "(", "node", ")", "sg", ".", "name", "=", "node", ".", "attrib", ".", "get", "(", "'name'", ")", "# Set attributes related to occurrence", "sg", ".", "src_interdep", "=", "node", ".", "attrib", ".", "get", "(", "'src_interdep'", ",", "'indep'", ")", "sg", ".", "rup_interdep", "=", "node", ".", "attrib", ".", "get", "(", "'rup_interdep'", ",", "'indep'", ")", "sg", ".", "grp_probability", "=", "node", ".", "attrib", ".", "get", "(", "'grp_probability'", ")", "# Set the cluster attribute", "sg", ".", "cluster", "=", "node", ".", "attrib", ".", "get", "(", "'cluster'", ")", "==", "'true'", "# Filter admitted cases", "# 1. The source group is a cluster. In this case the cluster must have", "# the attributes required to define its occurrence in time.", "if", "sg", ".", "cluster", ":", "msg", "=", "'A cluster group requires the definition of a temporal'", "msg", "+=", "' occurrence model'", "assert", "'tom'", "in", "node", ".", "attrib", ",", "msg", "if", "isinstance", "(", "tom", ",", "PoissonTOM", ")", ":", "assert", "hasattr", "(", "sg", ",", "'occurrence_rate'", ")", "#", "for", "src_node", "in", "node", ":", "if", "self", ".", "source_id", "and", "self", ".", "source_id", "!=", "src_node", "[", "'id'", "]", ":", "continue", "# filter by source_id", "src", "=", "self", ".", "convert_node", "(", "src_node", ")", "# transmit the group attributes to the underlying source", "for", "attr", ",", "value", "in", "grp_attrs", ".", "items", "(", ")", ":", "if", "attr", "==", "'tectonicRegion'", ":", "src_trt", "=", "src_node", ".", "get", "(", "'tectonicRegion'", ")", "if", "src_trt", "and", "src_trt", "!=", "trt", ":", "with", "context", "(", "self", ".", "fname", ",", "src_node", ")", ":", "raise", "ValueError", "(", "'Found %s, expected %s'", "%", "(", "src_node", "[", "'tectonicRegion'", "]", ",", "trt", ")", ")", "src", ".", "tectonic_region_type", "=", "trt", "elif", "attr", "==", "'grp_probability'", ":", "pass", "# do not transmit", "else", ":", "# transmit as it is", "setattr", "(", "src", ",", "attr", ",", "node", "[", "attr", "]", ")", "sg", ".", "update", "(", "src", ")", "if", "srcs_weights", "is", "not", "None", ":", "if", "len", "(", "node", ")", "and", "len", "(", "srcs_weights", ")", "!=", "len", "(", "node", ")", ":", "raise", "ValueError", "(", "'There are %d srcs_weights but %d source(s) in %s'", "%", "(", "len", "(", "srcs_weights", ")", ",", "len", "(", "node", ")", ",", "self", ".", "fname", ")", ")", "for", "src", ",", "sw", "in", "zip", "(", "sg", ",", "srcs_weights", ")", ":", "src", ".", "mutex_weight", "=", "sw", "# check that, when the cluster option is set, the group has a temporal", "# occurrence model properly defined", "if", "sg", ".", "cluster", "and", "not", "hasattr", "(", "sg", ",", "'temporal_occurrence_model'", ")", ":", "msg", "=", "'The Source Group is a cluster but does not have a '", "msg", "+=", "'temporal occurrence model'", "raise", "ValueError", "(", "msg", ")", "return", "sg" ]
Convert the given node into a SourceGroup object. :param node: a node with tag sourceGroup :returns: a :class:`SourceGroup` instance
[ "Convert", "the", "given", "node", "into", "a", "SourceGroup", "object", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L827-L891
515
gem/oq-engine
openquake/hmtk/faults/tectonic_regionalisation.py
_check_list_weights
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: raise ValueError('%s weights do not sum to 1.0!' % name) return parameter
python
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: raise ValueError('%s weights do not sum to 1.0!' % name) return parameter
[ "def", "_check_list_weights", "(", "parameter", ",", "name", ")", ":", "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", ":", "raise", "ValueError", "(", "'%s weights do not sum to 1.0!'", "%", "name", ")", "return", "parameter" ]
Checks that the weights in a list of tuples sums to 1.0
[ "Checks", "that", "the", "weights", "in", "a", "list", "of", "tuples", "sums", "to", "1", ".", "0" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/tectonic_regionalisation.py#L63-L72
516
gem/oq-engine
openquake/hmtk/faults/active_fault_model.py
mtkActiveFaultModel.build_fault_model
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 multiplied by the corresponding weights. :param bool collapse: Determines whether or not to collapse the branches :param rendered_msr: If the option is taken to collapse the branches then a recurrence model for rendering must be defined :param list/dict mfd_config: Universal list or dictionay of configuration parameters for the magnitude frequency distribution - will overwrite whatever is previously defined for the fault! ''' self.source_model = mtkSourceModel(self.id, self.name) for fault in self.faults: fault.generate_recurrence_models(collapse, config=mfd_config, rendered_msr=rendered_msr) src_model, src_weight = fault.generate_fault_source_model() for iloc, model in enumerate(src_model): new_model = deepcopy(model) new_model.id = str(model.id) + '_%g' % (iloc + 1) new_model.mfd.occurrence_rates = \ (np.array(new_model.mfd.occurrence_rates) * src_weight[iloc]).tolist() self.source_model.sources.append(new_model)
python
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 multiplied by the corresponding weights. :param bool collapse: Determines whether or not to collapse the branches :param rendered_msr: If the option is taken to collapse the branches then a recurrence model for rendering must be defined :param list/dict mfd_config: Universal list or dictionay of configuration parameters for the magnitude frequency distribution - will overwrite whatever is previously defined for the fault! ''' self.source_model = mtkSourceModel(self.id, self.name) for fault in self.faults: fault.generate_recurrence_models(collapse, config=mfd_config, rendered_msr=rendered_msr) src_model, src_weight = fault.generate_fault_source_model() for iloc, model in enumerate(src_model): new_model = deepcopy(model) new_model.id = str(model.id) + '_%g' % (iloc + 1) new_model.mfd.occurrence_rates = \ (np.array(new_model.mfd.occurrence_rates) * src_weight[iloc]).tolist() self.source_model.sources.append(new_model)
[ "def", "build_fault_model", "(", "self", ",", "collapse", "=", "False", ",", "rendered_msr", "=", "WC1994", "(", ")", ",", "mfd_config", "=", "None", ")", ":", "self", ".", "source_model", "=", "mtkSourceModel", "(", "self", ".", "id", ",", "self", ".", "name", ")", "for", "fault", "in", "self", ".", "faults", ":", "fault", ".", "generate_recurrence_models", "(", "collapse", ",", "config", "=", "mfd_config", ",", "rendered_msr", "=", "rendered_msr", ")", "src_model", ",", "src_weight", "=", "fault", ".", "generate_fault_source_model", "(", ")", "for", "iloc", ",", "model", "in", "enumerate", "(", "src_model", ")", ":", "new_model", "=", "deepcopy", "(", "model", ")", "new_model", ".", "id", "=", "str", "(", "model", ".", "id", ")", "+", "'_%g'", "%", "(", "iloc", "+", "1", ")", "new_model", ".", "mfd", ".", "occurrence_rates", "=", "(", "np", ".", "array", "(", "new_model", ".", "mfd", ".", "occurrence_rates", ")", "*", "src_weight", "[", "iloc", "]", ")", ".", "tolist", "(", ")", "self", ".", "source_model", ".", "sources", ".", "append", "(", "new_model", ")" ]
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 multiplied by the corresponding weights. :param bool collapse: Determines whether or not to collapse the branches :param rendered_msr: If the option is taken to collapse the branches then a recurrence model for rendering must be defined :param list/dict mfd_config: Universal list or dictionay of configuration parameters for the magnitude frequency distribution - will overwrite whatever is previously defined for the fault!
[ "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", "multiplied", "by", "the", "corresponding", "weights", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/active_fault_model.py#L94-L125
517
gem/oq-engine
openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py
ParseNDKtoGCMT.read_file
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 - number in file not' ' a multiple of 5!') self.catalogue.number_gcmts = num_lines // 5 self.catalogue.gcmts = [None] * self.catalogue.number_gcmts # Pre-allocates list id0 = 0 print('Parsing catalogue ...') for iloc in range(0, self.catalogue.number_gcmts): self.catalogue.gcmts[iloc] = self.read_ndk_event(raw_data, id0) id0 += 5 print('complete. Contains %s moment tensors' % self.catalogue.get_number_tensors()) if not start_year: min_years = [] min_years = [cent.centroid.date.year for cent in self.catalogue.gcmts] self.catalogue.start_year = np.min(min_years) if not end_year: max_years = [] max_years = [cent.centroid.date.year for cent in self.catalogue.gcmts] self.catalogue.end_year = np.max(max_years) self.to_hmtk(use_centroid) return self.catalogue
python
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 - number in file not' ' a multiple of 5!') self.catalogue.number_gcmts = num_lines // 5 self.catalogue.gcmts = [None] * self.catalogue.number_gcmts # Pre-allocates list id0 = 0 print('Parsing catalogue ...') for iloc in range(0, self.catalogue.number_gcmts): self.catalogue.gcmts[iloc] = self.read_ndk_event(raw_data, id0) id0 += 5 print('complete. Contains %s moment tensors' % self.catalogue.get_number_tensors()) if not start_year: min_years = [] min_years = [cent.centroid.date.year for cent in self.catalogue.gcmts] self.catalogue.start_year = np.min(min_years) if not end_year: max_years = [] max_years = [cent.centroid.date.year for cent in self.catalogue.gcmts] self.catalogue.end_year = np.max(max_years) self.to_hmtk(use_centroid) return self.catalogue
[ "def", "read_file", "(", "self", ",", "start_year", "=", "None", ",", "end_year", "=", "None", ",", "use_centroid", "=", "None", ")", ":", "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 - number in file not'", "' a multiple of 5!'", ")", "self", ".", "catalogue", ".", "number_gcmts", "=", "num_lines", "//", "5", "self", ".", "catalogue", ".", "gcmts", "=", "[", "None", "]", "*", "self", ".", "catalogue", ".", "number_gcmts", "# Pre-allocates list", "id0", "=", "0", "print", "(", "'Parsing catalogue ...'", ")", "for", "iloc", "in", "range", "(", "0", ",", "self", ".", "catalogue", ".", "number_gcmts", ")", ":", "self", ".", "catalogue", ".", "gcmts", "[", "iloc", "]", "=", "self", ".", "read_ndk_event", "(", "raw_data", ",", "id0", ")", "id0", "+=", "5", "print", "(", "'complete. Contains %s moment tensors'", "%", "self", ".", "catalogue", ".", "get_number_tensors", "(", ")", ")", "if", "not", "start_year", ":", "min_years", "=", "[", "]", "min_years", "=", "[", "cent", ".", "centroid", ".", "date", ".", "year", "for", "cent", "in", "self", ".", "catalogue", ".", "gcmts", "]", "self", ".", "catalogue", ".", "start_year", "=", "np", ".", "min", "(", "min_years", ")", "if", "not", "end_year", ":", "max_years", "=", "[", "]", "max_years", "=", "[", "cent", ".", "centroid", ".", "date", ".", "year", "for", "cent", "in", "self", ".", "catalogue", ".", "gcmts", "]", "self", ".", "catalogue", ".", "end_year", "=", "np", ".", "max", "(", "max_years", ")", "self", ".", "to_hmtk", "(", "use_centroid", ")", "return", "self", ".", "catalogue" ]
Reads the file
[ "Reads", "the", "file" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py#L145-L176
518
gem/oq-engine
openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py
ParseNDKtoGCMT.read_ndk_event
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 ndkstring = raw_data[id0 + 1].rstrip('\n') gcmt = self._get_metadata_from_ndk_string(gcmt, ndkstring) # Get Centroid ndkstring = raw_data[id0 + 2].rstrip('\n') gcmt.centroid = self._read_centroid_from_ndk_string(ndkstring, gcmt.hypocentre) # Get Moment Tensor ndkstring = raw_data[id0 + 3].rstrip('\n') gcmt.moment_tensor = self._get_moment_tensor_from_ndk_string(ndkstring) # Get principal axes ndkstring = raw_data[id0 + 4].rstrip('\n') gcmt.principal_axes = self._get_principal_axes_from_ndk_string( ndkstring[3:48], exponent=gcmt.moment_tensor.exponent) # Get Nodal Planes gcmt.nodal_planes = self._get_nodal_planes_from_ndk_string( ndkstring[57:]) # Get Moment and Magnitude gcmt.moment, gcmt.version, gcmt.magnitude = \ self._get_moment_from_ndk_string( ndkstring, gcmt.moment_tensor.exponent) return gcmt
python
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 ndkstring = raw_data[id0 + 1].rstrip('\n') gcmt = self._get_metadata_from_ndk_string(gcmt, ndkstring) # Get Centroid ndkstring = raw_data[id0 + 2].rstrip('\n') gcmt.centroid = self._read_centroid_from_ndk_string(ndkstring, gcmt.hypocentre) # Get Moment Tensor ndkstring = raw_data[id0 + 3].rstrip('\n') gcmt.moment_tensor = self._get_moment_tensor_from_ndk_string(ndkstring) # Get principal axes ndkstring = raw_data[id0 + 4].rstrip('\n') gcmt.principal_axes = self._get_principal_axes_from_ndk_string( ndkstring[3:48], exponent=gcmt.moment_tensor.exponent) # Get Nodal Planes gcmt.nodal_planes = self._get_nodal_planes_from_ndk_string( ndkstring[57:]) # Get Moment and Magnitude gcmt.moment, gcmt.version, gcmt.magnitude = \ self._get_moment_from_ndk_string( ndkstring, gcmt.moment_tensor.exponent) return gcmt
[ "def", "read_ndk_event", "(", "self", ",", "raw_data", ",", "id0", ")", ":", "gcmt", "=", "GCMTEvent", "(", ")", "# Get hypocentre", "ndkstring", "=", "raw_data", "[", "id0", "]", ".", "rstrip", "(", "'\\n'", ")", "gcmt", ".", "hypocentre", "=", "self", ".", "_read_hypocentre_from_ndk_string", "(", "ndkstring", ")", "# GCMT metadata", "ndkstring", "=", "raw_data", "[", "id0", "+", "1", "]", ".", "rstrip", "(", "'\\n'", ")", "gcmt", "=", "self", ".", "_get_metadata_from_ndk_string", "(", "gcmt", ",", "ndkstring", ")", "# Get Centroid", "ndkstring", "=", "raw_data", "[", "id0", "+", "2", "]", ".", "rstrip", "(", "'\\n'", ")", "gcmt", ".", "centroid", "=", "self", ".", "_read_centroid_from_ndk_string", "(", "ndkstring", ",", "gcmt", ".", "hypocentre", ")", "# Get Moment Tensor", "ndkstring", "=", "raw_data", "[", "id0", "+", "3", "]", ".", "rstrip", "(", "'\\n'", ")", "gcmt", ".", "moment_tensor", "=", "self", ".", "_get_moment_tensor_from_ndk_string", "(", "ndkstring", ")", "# Get principal axes", "ndkstring", "=", "raw_data", "[", "id0", "+", "4", "]", ".", "rstrip", "(", "'\\n'", ")", "gcmt", ".", "principal_axes", "=", "self", ".", "_get_principal_axes_from_ndk_string", "(", "ndkstring", "[", "3", ":", "48", "]", ",", "exponent", "=", "gcmt", ".", "moment_tensor", ".", "exponent", ")", "# Get Nodal Planes", "gcmt", ".", "nodal_planes", "=", "self", ".", "_get_nodal_planes_from_ndk_string", "(", "ndkstring", "[", "57", ":", "]", ")", "# Get Moment and Magnitude", "gcmt", ".", "moment", ",", "gcmt", ".", "version", ",", "gcmt", ".", "magnitude", "=", "self", ".", "_get_moment_from_ndk_string", "(", "ndkstring", ",", "gcmt", ".", "moment_tensor", ".", "exponent", ")", "return", "gcmt" ]
Reads a 5-line batch of data into a set of GCMTs
[ "Reads", "a", "5", "-", "line", "batch", "of", "data", "into", "a", "set", "of", "GCMTs" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py#L178-L214
519
gem/oq-engine
openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py
ParseNDKtoGCMT._read_hypocentre_from_ndk_string
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]) hypo.time = _read_time_from_string(linestring[16:26]) hypo.latitude = float(linestring[27:33]) hypo.longitude = float(linestring[34:41]) hypo.depth = float(linestring[42:47]) magnitudes = [float(x) for x in linestring[48:55].split(' ')] if magnitudes[0] > 0.: hypo.m_b = magnitudes[0] if magnitudes[1] > 0.: hypo.m_s = magnitudes[1] hypo.location = linestring[56:] return hypo
python
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]) hypo.time = _read_time_from_string(linestring[16:26]) hypo.latitude = float(linestring[27:33]) hypo.longitude = float(linestring[34:41]) hypo.depth = float(linestring[42:47]) magnitudes = [float(x) for x in linestring[48:55].split(' ')] if magnitudes[0] > 0.: hypo.m_b = magnitudes[0] if magnitudes[1] > 0.: hypo.m_s = magnitudes[1] hypo.location = linestring[56:] return hypo
[ "def", "_read_hypocentre_from_ndk_string", "(", "self", ",", "linestring", ")", ":", "hypo", "=", "GCMTHypocentre", "(", ")", "hypo", ".", "source", "=", "linestring", "[", "0", ":", "4", "]", "hypo", ".", "date", "=", "_read_date_from_string", "(", "linestring", "[", "5", ":", "15", "]", ")", "hypo", ".", "time", "=", "_read_time_from_string", "(", "linestring", "[", "16", ":", "26", "]", ")", "hypo", ".", "latitude", "=", "float", "(", "linestring", "[", "27", ":", "33", "]", ")", "hypo", ".", "longitude", "=", "float", "(", "linestring", "[", "34", ":", "41", "]", ")", "hypo", ".", "depth", "=", "float", "(", "linestring", "[", "42", ":", "47", "]", ")", "magnitudes", "=", "[", "float", "(", "x", ")", "for", "x", "in", "linestring", "[", "48", ":", "55", "]", ".", "split", "(", "' '", ")", "]", "if", "magnitudes", "[", "0", "]", ">", "0.", ":", "hypo", ".", "m_b", "=", "magnitudes", "[", "0", "]", "if", "magnitudes", "[", "1", "]", ">", "0.", ":", "hypo", ".", "m_s", "=", "magnitudes", "[", "1", "]", "hypo", ".", "location", "=", "linestring", "[", "56", ":", "]", "return", "hypo" ]
Reads the hypocentre data from the ndk string to return an instance of the GCMTHypocentre class
[ "Reads", "the", "hypocentre", "data", "from", "the", "ndk", "string", "to", "return", "an", "instance", "of", "the", "GCMTHypocentre", "class" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py#L315-L333
520
gem/oq-engine
openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py
ParseNDKtoGCMT._get_metadata_from_ndk_string
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].split()] gcmt.metadata['SURFACE'] = [ float(x) for x in inversion_data[2].split()] gcmt.metadata['MANTLE'] = [float(x) for x in inversion_data[3].split()] further_meta = re.split('[: ]+', ndk_string[62:]) gcmt.metadata['CMT'] = int(further_meta[1]) gcmt.metadata['FUNCTION'] = {'TYPE': further_meta[2], 'DURATION': float(further_meta[3])} return gcmt
python
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].split()] gcmt.metadata['SURFACE'] = [ float(x) for x in inversion_data[2].split()] gcmt.metadata['MANTLE'] = [float(x) for x in inversion_data[3].split()] further_meta = re.split('[: ]+', ndk_string[62:]) gcmt.metadata['CMT'] = int(further_meta[1]) gcmt.metadata['FUNCTION'] = {'TYPE': further_meta[2], 'DURATION': float(further_meta[3])} return gcmt
[ "def", "_get_metadata_from_ndk_string", "(", "self", ",", "gcmt", ",", "ndk_string", ")", ":", "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", "]", ".", "split", "(", ")", "]", "gcmt", ".", "metadata", "[", "'SURFACE'", "]", "=", "[", "float", "(", "x", ")", "for", "x", "in", "inversion_data", "[", "2", "]", ".", "split", "(", ")", "]", "gcmt", ".", "metadata", "[", "'MANTLE'", "]", "=", "[", "float", "(", "x", ")", "for", "x", "in", "inversion_data", "[", "3", "]", ".", "split", "(", ")", "]", "further_meta", "=", "re", ".", "split", "(", "'[: ]+'", ",", "ndk_string", "[", "62", ":", "]", ")", "gcmt", ".", "metadata", "[", "'CMT'", "]", "=", "int", "(", "further_meta", "[", "1", "]", ")", "gcmt", ".", "metadata", "[", "'FUNCTION'", "]", "=", "{", "'TYPE'", ":", "further_meta", "[", "2", "]", ",", "'DURATION'", ":", "float", "(", "further_meta", "[", "3", "]", ")", "}", "return", "gcmt" ]
Reads the GCMT metadata from line 2 of the ndk batch
[ "Reads", "the", "GCMT", "metadata", "from", "line", "2", "of", "the", "ndk", "batch" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py#L335-L349
521
gem/oq-engine
openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py
ParseNDKtoGCMT._get_principal_axes_from_ndk_string
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 exponent = 10. ** exponent axes.t_axis = {'eigenvalue': exponent * float(ndk_string[0:8]), 'plunge': float(ndk_string[8:11]), 'azimuth': float(ndk_string[11:15])} axes.b_axis = {'eigenvalue': exponent * float(ndk_string[15:23]), 'plunge': float(ndk_string[23:26]), 'azimuth': float(ndk_string[26:30])} axes.p_axis = {'eigenvalue': exponent * float(ndk_string[30:38]), 'plunge': float(ndk_string[38:41]), 'azimuth': float(ndk_string[41:])} return axes
python
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 exponent = 10. ** exponent axes.t_axis = {'eigenvalue': exponent * float(ndk_string[0:8]), 'plunge': float(ndk_string[8:11]), 'azimuth': float(ndk_string[11:15])} axes.b_axis = {'eigenvalue': exponent * float(ndk_string[15:23]), 'plunge': float(ndk_string[23:26]), 'azimuth': float(ndk_string[26:30])} axes.p_axis = {'eigenvalue': exponent * float(ndk_string[30:38]), 'plunge': float(ndk_string[38:41]), 'azimuth': float(ndk_string[41:])} return axes
[ "def", "_get_principal_axes_from_ndk_string", "(", "self", ",", "ndk_string", ",", "exponent", ")", ":", "axes", "=", "GCMTPrincipalAxes", "(", ")", "# The principal axes is defined in characters 3:48 of the 5th line", "exponent", "=", "10.", "**", "exponent", "axes", ".", "t_axis", "=", "{", "'eigenvalue'", ":", "exponent", "*", "float", "(", "ndk_string", "[", "0", ":", "8", "]", ")", ",", "'plunge'", ":", "float", "(", "ndk_string", "[", "8", ":", "11", "]", ")", ",", "'azimuth'", ":", "float", "(", "ndk_string", "[", "11", ":", "15", "]", ")", "}", "axes", ".", "b_axis", "=", "{", "'eigenvalue'", ":", "exponent", "*", "float", "(", "ndk_string", "[", "15", ":", "23", "]", ")", ",", "'plunge'", ":", "float", "(", "ndk_string", "[", "23", ":", "26", "]", ")", ",", "'azimuth'", ":", "float", "(", "ndk_string", "[", "26", ":", "30", "]", ")", "}", "axes", ".", "p_axis", "=", "{", "'eigenvalue'", ":", "exponent", "*", "float", "(", "ndk_string", "[", "30", ":", "38", "]", ")", ",", "'plunge'", ":", "float", "(", "ndk_string", "[", "38", ":", "41", "]", ")", ",", "'azimuth'", ":", "float", "(", "ndk_string", "[", "41", ":", "]", ")", "}", "return", "axes" ]
Gets the principal axes from the ndk string and returns an instance of the GCMTPrincipalAxes class
[ "Gets", "the", "principal", "axes", "from", "the", "ndk", "string", "and", "returns", "an", "instance", "of", "the", "GCMTPrincipalAxes", "class" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py#L394-L413
522
gem/oq-engine
openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py
ParseNDKtoGCMT._get_moment_from_ndk_string
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, magnitude
python
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, magnitude
[ "def", "_get_moment_from_ndk_string", "(", "self", ",", "ndk_string", ",", "exponent", ")", ":", "moment", "=", "float", "(", "ndk_string", "[", "49", ":", "56", "]", ")", "*", "(", "10.", "**", "exponent", ")", "version", "=", "ndk_string", "[", ":", "3", "]", "magnitude", "=", "utils", ".", "moment_magnitude_scalar", "(", "moment", ")", "return", "moment", ",", "version", ",", "magnitude" ]
Returns the moment and the moment magnitude
[ "Returns", "the", "moment", "and", "the", "moment", "magnitude" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py#L430-L437
523
gem/oq-engine
openquake/hmtk/sources/source_model.py
mtkSourceModel.serialise_to_nrml
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 (True) or not. If set to False, ValueErrors will be raised when an essential attribute is missing. ''' source_model = self.convert_to_oqhazardlib( PoissonTOM(1.0), 2.0, 2.0, 10.0, use_defaults=use_defaults) write_source_model(filename, source_model, name=self.name)
python
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 (True) or not. If set to False, ValueErrors will be raised when an essential attribute is missing. ''' source_model = self.convert_to_oqhazardlib( PoissonTOM(1.0), 2.0, 2.0, 10.0, use_defaults=use_defaults) write_source_model(filename, source_model, name=self.name)
[ "def", "serialise_to_nrml", "(", "self", ",", "filename", ",", "use_defaults", "=", "False", ")", ":", "source_model", "=", "self", ".", "convert_to_oqhazardlib", "(", "PoissonTOM", "(", "1.0", ")", ",", "2.0", ",", "2.0", ",", "10.0", ",", "use_defaults", "=", "use_defaults", ")", "write_source_model", "(", "filename", ",", "source_model", ",", "name", "=", "self", ".", "name", ")" ]
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 (True) or not. If set to False, ValueErrors will be raised when an essential attribute is missing.
[ "Writes", "the", "source", "model", "to", "a", "nrml", "source", "model", "file", "given", "by", "the", "filename" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/sources/source_model.py#L95-L110
524
gem/oq-engine
openquake/hmtk/seismicity/occurrence/utils.py
input_checks
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 Table incorrectly configured') else: cmag = completeness[:, 1] ctime = completeness[:, 0] elif isinstance(completeness, float): # Completeness corresponds to a single magnitude (i.e. applies to # the entire catalogue) cmag = np.array(completeness) ctime = np.array(np.min(catalogue.data['year'])) else: # Everything is valid - i.e. no completeness magnitude cmag = np.array(np.min(catalogue.data['magnitude'])) ctime = np.array(np.min(catalogue.data['year'])) # Set reference magnitude - if not in config then default to M = 0. if not config: # use default reference magnitude of 0.0 and magnitude interval of 0.1 ref_mag = 0.0 dmag = 0.1 config = {'reference_magnitude': None, 'magnitude_interval': 0.1} else: if (not 'reference_magnitude' in config.keys()) or\ (config['reference_magnitude'] is None): ref_mag = 0. config['reference_magnitude'] = None else: ref_mag = config['reference_magnitude'] if (not 'magnitude_interval' in config.keys()) or \ not config['magnitude_interval']: dmag = 0.1 else: dmag = config['magnitude_interval'] return cmag, ctime, ref_mag, dmag, config
python
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 Table incorrectly configured') else: cmag = completeness[:, 1] ctime = completeness[:, 0] elif isinstance(completeness, float): # Completeness corresponds to a single magnitude (i.e. applies to # the entire catalogue) cmag = np.array(completeness) ctime = np.array(np.min(catalogue.data['year'])) else: # Everything is valid - i.e. no completeness magnitude cmag = np.array(np.min(catalogue.data['magnitude'])) ctime = np.array(np.min(catalogue.data['year'])) # Set reference magnitude - if not in config then default to M = 0. if not config: # use default reference magnitude of 0.0 and magnitude interval of 0.1 ref_mag = 0.0 dmag = 0.1 config = {'reference_magnitude': None, 'magnitude_interval': 0.1} else: if (not 'reference_magnitude' in config.keys()) or\ (config['reference_magnitude'] is None): ref_mag = 0. config['reference_magnitude'] = None else: ref_mag = config['reference_magnitude'] if (not 'magnitude_interval' in config.keys()) or \ not config['magnitude_interval']: dmag = 0.1 else: dmag = config['magnitude_interval'] return cmag, ctime, ref_mag, dmag, config
[ "def", "input_checks", "(", "catalogue", ",", "config", ",", "completeness", ")", ":", "if", "isinstance", "(", "completeness", ",", "np", ".", "ndarray", ")", ":", "# completeness table is a numpy array (i.e. [year, magnitude])", "if", "np", ".", "shape", "(", "completeness", ")", "[", "1", "]", "!=", "2", ":", "raise", "ValueError", "(", "'Completeness Table incorrectly configured'", ")", "else", ":", "cmag", "=", "completeness", "[", ":", ",", "1", "]", "ctime", "=", "completeness", "[", ":", ",", "0", "]", "elif", "isinstance", "(", "completeness", ",", "float", ")", ":", "# Completeness corresponds to a single magnitude (i.e. applies to", "# the entire catalogue)", "cmag", "=", "np", ".", "array", "(", "completeness", ")", "ctime", "=", "np", ".", "array", "(", "np", ".", "min", "(", "catalogue", ".", "data", "[", "'year'", "]", ")", ")", "else", ":", "# Everything is valid - i.e. no completeness magnitude", "cmag", "=", "np", ".", "array", "(", "np", ".", "min", "(", "catalogue", ".", "data", "[", "'magnitude'", "]", ")", ")", "ctime", "=", "np", ".", "array", "(", "np", ".", "min", "(", "catalogue", ".", "data", "[", "'year'", "]", ")", ")", "# Set reference magnitude - if not in config then default to M = 0.", "if", "not", "config", ":", "# use default reference magnitude of 0.0 and magnitude interval of 0.1", "ref_mag", "=", "0.0", "dmag", "=", "0.1", "config", "=", "{", "'reference_magnitude'", ":", "None", ",", "'magnitude_interval'", ":", "0.1", "}", "else", ":", "if", "(", "not", "'reference_magnitude'", "in", "config", ".", "keys", "(", ")", ")", "or", "(", "config", "[", "'reference_magnitude'", "]", "is", "None", ")", ":", "ref_mag", "=", "0.", "config", "[", "'reference_magnitude'", "]", "=", "None", "else", ":", "ref_mag", "=", "config", "[", "'reference_magnitude'", "]", "if", "(", "not", "'magnitude_interval'", "in", "config", ".", "keys", "(", ")", ")", "or", "not", "config", "[", "'magnitude_interval'", "]", ":", "dmag", "=", "0.1", "else", ":", "dmag", "=", "config", "[", "'magnitude_interval'", "]", "return", "cmag", ",", "ctime", ",", "ref_mag", ",", "dmag", ",", "config" ]
Performs a basic set of input checks on the data
[ "Performs", "a", "basic", "set", "of", "input", "checks", "on", "the", "data" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/occurrence/utils.py#L100-L142
525
gem/oq-engine
openquake/hmtk/seismicity/occurrence/utils.py
generate_trunc_gr_magnitudes
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 :param int nsamples: Number of samples :returns: Vector of generated magnitudes ''' sampler = np.random.uniform(0., 1., nsamples) beta = bval * np.log(10.) return (-1. / beta) * ( np.log(1. - sampler * (1 - np.exp(-beta * (mmax - mmin))))) + mmin
python
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 :param int nsamples: Number of samples :returns: Vector of generated magnitudes ''' sampler = np.random.uniform(0., 1., nsamples) beta = bval * np.log(10.) return (-1. / beta) * ( np.log(1. - sampler * (1 - np.exp(-beta * (mmax - mmin))))) + mmin
[ "def", "generate_trunc_gr_magnitudes", "(", "bval", ",", "mmin", ",", "mmax", ",", "nsamples", ")", ":", "sampler", "=", "np", ".", "random", ".", "uniform", "(", "0.", ",", "1.", ",", "nsamples", ")", "beta", "=", "bval", "*", "np", ".", "log", "(", "10.", ")", "return", "(", "-", "1.", "/", "beta", ")", "*", "(", "np", ".", "log", "(", "1.", "-", "sampler", "*", "(", "1", "-", "np", ".", "exp", "(", "-", "beta", "*", "(", "mmax", "-", "mmin", ")", ")", ")", ")", ")", "+", "mmin" ]
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 :param int nsamples: Number of samples :returns: Vector of generated magnitudes
[ "Generate", "a", "random", "list", "of", "magnitudes", "distributed", "according", "to", "a", "truncated", "Gutenberg", "-", "Richter", "model" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/occurrence/utils.py#L145-L165
526
gem/oq-engine
openquake/hmtk/seismicity/occurrence/utils.py
generate_synthetic_magnitudes
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 :param float mmin: Minimum Magnitude :param float mmax: Maximum Magnitude :param int nyears: Number of years :returns: Synthetic catalogue (dict) with year and magnitude attributes ''' nsamples = int(np.round(nyears * (10. ** (aval - bval * mmin)), 0)) year = np.random.randint(0, nyears, nsamples) # Get magnitudes mags = generate_trunc_gr_magnitudes(bval, mmin, mmax, nsamples) return {'magnitude': mags, 'year': np.sort(year)}
python
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 :param float mmin: Minimum Magnitude :param float mmax: Maximum Magnitude :param int nyears: Number of years :returns: Synthetic catalogue (dict) with year and magnitude attributes ''' nsamples = int(np.round(nyears * (10. ** (aval - bval * mmin)), 0)) year = np.random.randint(0, nyears, nsamples) # Get magnitudes mags = generate_trunc_gr_magnitudes(bval, mmin, mmax, nsamples) return {'magnitude': mags, 'year': np.sort(year)}
[ "def", "generate_synthetic_magnitudes", "(", "aval", ",", "bval", ",", "mmin", ",", "mmax", ",", "nyears", ")", ":", "nsamples", "=", "int", "(", "np", ".", "round", "(", "nyears", "*", "(", "10.", "**", "(", "aval", "-", "bval", "*", "mmin", ")", ")", ",", "0", ")", ")", "year", "=", "np", ".", "random", ".", "randint", "(", "0", ",", "nyears", ",", "nsamples", ")", "# Get magnitudes", "mags", "=", "generate_trunc_gr_magnitudes", "(", "bval", ",", "mmin", ",", "mmax", ",", "nsamples", ")", "return", "{", "'magnitude'", ":", "mags", ",", "'year'", ":", "np", ".", "sort", "(", "year", ")", "}" ]
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 :param float mmin: Minimum Magnitude :param float mmax: Maximum Magnitude :param int nyears: Number of years :returns: Synthetic catalogue (dict) with year and magnitude attributes
[ "Generates", "a", "synthetic", "catalogue", "for", "a", "specified", "number", "of", "years", "with", "magnitudes", "distributed", "according", "to", "a", "truncated", "Gutenberg", "-", "Richter", "distribution" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/occurrence/utils.py#L168-L191
527
gem/oq-engine
openquake/hmtk/seismicity/occurrence/utils.py
downsample_completeness_table
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_m) # FIXME: d_m is undefined! new_comp_table.extend([[comp_table[i, 0], mval] for mval in mvals]) # If mmax > last magnitude in completeness table if mmax and (mmax > comp_table[-1, 1]): new_comp_table.extend( [[comp_table[-1, 0], mval] for mval in np.arange(comp_table[-1, 1], mmax + d_m, d_m)]) return np.array(new_comp_table)
python
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_m) # FIXME: d_m is undefined! new_comp_table.extend([[comp_table[i, 0], mval] for mval in mvals]) # If mmax > last magnitude in completeness table if mmax and (mmax > comp_table[-1, 1]): new_comp_table.extend( [[comp_table[-1, 0], mval] for mval in np.arange(comp_table[-1, 1], mmax + d_m, d_m)]) return np.array(new_comp_table)
[ "def", "downsample_completeness_table", "(", "comp_table", ",", "sample_width", "=", "0.1", ",", "mmax", "=", "None", ")", ":", "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_m", ")", "# FIXME: d_m is undefined!", "new_comp_table", ".", "extend", "(", "[", "[", "comp_table", "[", "i", ",", "0", "]", ",", "mval", "]", "for", "mval", "in", "mvals", "]", ")", "# If mmax > last magnitude in completeness table", "if", "mmax", "and", "(", "mmax", ">", "comp_table", "[", "-", "1", ",", "1", "]", ")", ":", "new_comp_table", ".", "extend", "(", "[", "[", "comp_table", "[", "-", "1", ",", "0", "]", ",", "mval", "]", "for", "mval", "in", "np", ".", "arange", "(", "comp_table", "[", "-", "1", ",", "1", "]", ",", "mmax", "+", "d_m", ",", "d_m", ")", "]", ")", "return", "np", ".", "array", "(", "new_comp_table", ")" ]
Re-sample the completeness table to a specified sample_width
[ "Re", "-", "sample", "the", "completeness", "table", "to", "a", "specified", "sample_width" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/occurrence/utils.py#L194-L208
528
gem/oq-engine
openquake/commands/reset.py
reset
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 write the databse file to remove it if os.path.isfile(dbpath) and os.access(dbpath, os.W_OK): if dbserver.get_status() == 'running': if config.dbserver.multi_user: sys.exit('The oq dbserver must be stopped ' 'before proceeding') else: pid = logs.dbcmd('getpid') os.kill(pid, signal.SIGTERM) time.sleep(.5) # give time to stop assert dbserver.get_status() == 'not-running' print('dbserver stopped') try: os.remove(dbpath) print('Removed %s' % dbpath) except OSError as exc: print(exc, file=sys.stderr) # fast way of removing everything purge_all(fast=True)
python
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 write the databse file to remove it if os.path.isfile(dbpath) and os.access(dbpath, os.W_OK): if dbserver.get_status() == 'running': if config.dbserver.multi_user: sys.exit('The oq dbserver must be stopped ' 'before proceeding') else: pid = logs.dbcmd('getpid') os.kill(pid, signal.SIGTERM) time.sleep(.5) # give time to stop assert dbserver.get_status() == 'not-running' print('dbserver stopped') try: os.remove(dbpath) print('Removed %s' % dbpath) except OSError as exc: print(exc, file=sys.stderr) # fast way of removing everything purge_all(fast=True)
[ "def", "reset", "(", "yes", ")", ":", "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 write the databse file to remove it", "if", "os", ".", "path", ".", "isfile", "(", "dbpath", ")", "and", "os", ".", "access", "(", "dbpath", ",", "os", ".", "W_OK", ")", ":", "if", "dbserver", ".", "get_status", "(", ")", "==", "'running'", ":", "if", "config", ".", "dbserver", ".", "multi_user", ":", "sys", ".", "exit", "(", "'The oq dbserver must be stopped '", "'before proceeding'", ")", "else", ":", "pid", "=", "logs", ".", "dbcmd", "(", "'getpid'", ")", "os", ".", "kill", "(", "pid", ",", "signal", ".", "SIGTERM", ")", "time", ".", "sleep", "(", ".5", ")", "# give time to stop", "assert", "dbserver", ".", "get_status", "(", ")", "==", "'not-running'", "print", "(", "'dbserver stopped'", ")", "try", ":", "os", ".", "remove", "(", "dbpath", ")", "print", "(", "'Removed %s'", "%", "dbpath", ")", "except", "OSError", "as", "exc", ":", "print", "(", "exc", ",", "file", "=", "sys", ".", "stderr", ")", "# fast way of removing everything", "purge_all", "(", "fast", "=", "True", ")" ]
Remove all the datastores and the database of the current user
[ "Remove", "all", "the", "datastores", "and", "the", "database", "of", "the", "current", "user" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/reset.py#L30-L59
529
gem/oq-engine
openquake/server/db/actions.py
set_status
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 ( 'created', 'submitted', 'executing', 'complete', 'aborted', 'failed' ), status if status in ('created', 'complete', 'failed', 'aborted'): is_running = 0 else: # 'executing' is_running = 1 if job_id < 0: rows = db('SELECT id FROM job ORDER BY id DESC LIMIT ?x', -job_id) if not rows: return 0 job_id = rows[-1].id cursor = db('UPDATE job SET status=?x, is_running=?x WHERE id=?x', status, is_running, job_id) return cursor.rowcount
python
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 ( 'created', 'submitted', 'executing', 'complete', 'aborted', 'failed' ), status if status in ('created', 'complete', 'failed', 'aborted'): is_running = 0 else: # 'executing' is_running = 1 if job_id < 0: rows = db('SELECT id FROM job ORDER BY id DESC LIMIT ?x', -job_id) if not rows: return 0 job_id = rows[-1].id cursor = db('UPDATE job SET status=?x, is_running=?x WHERE id=?x', status, is_running, job_id) return cursor.rowcount
[ "def", "set_status", "(", "db", ",", "job_id", ",", "status", ")", ":", "assert", "status", "in", "(", "'created'", ",", "'submitted'", ",", "'executing'", ",", "'complete'", ",", "'aborted'", ",", "'failed'", ")", ",", "status", "if", "status", "in", "(", "'created'", ",", "'complete'", ",", "'failed'", ",", "'aborted'", ")", ":", "is_running", "=", "0", "else", ":", "# 'executing'", "is_running", "=", "1", "if", "job_id", "<", "0", ":", "rows", "=", "db", "(", "'SELECT id FROM job ORDER BY id DESC LIMIT ?x'", ",", "-", "job_id", ")", "if", "not", "rows", ":", "return", "0", "job_id", "=", "rows", "[", "-", "1", "]", ".", "id", "cursor", "=", "db", "(", "'UPDATE job SET status=?x, is_running=?x WHERE id=?x'", ",", "status", ",", "is_running", ",", "job_id", ")", "return", "cursor", ".", "rowcount" ]
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
[ "Set", "the", "status", "created", "executing", "complete", "failed", "aborted", "consistently", "with", "is_running", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L62-L85
530
gem/oq-engine
openquake/server/db/actions.py
create_job
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 job = dict(id=calc_id, is_running=1, description='just created', user_name='openquake', calculation_mode='to be set', ds_calc_dir=os.path.join('%s/calc_%s' % (datadir, calc_id))) return db('INSERT INTO job (?S) VALUES (?X)', job.keys(), job.values()).lastrowid
python
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 job = dict(id=calc_id, is_running=1, description='just created', user_name='openquake', calculation_mode='to be set', ds_calc_dir=os.path.join('%s/calc_%s' % (datadir, calc_id))) return db('INSERT INTO job (?S) VALUES (?X)', job.keys(), job.values()).lastrowid
[ "def", "create_job", "(", "db", ",", "datadir", ")", ":", "calc_id", "=", "get_calc_id", "(", "db", ",", "datadir", ")", "+", "1", "job", "=", "dict", "(", "id", "=", "calc_id", ",", "is_running", "=", "1", ",", "description", "=", "'just created'", ",", "user_name", "=", "'openquake'", ",", "calculation_mode", "=", "'to be set'", ",", "ds_calc_dir", "=", "os", ".", "path", ".", "join", "(", "'%s/calc_%s'", "%", "(", "datadir", ",", "calc_id", ")", ")", ")", "return", "db", "(", "'INSERT INTO job (?S) VALUES (?X)'", ",", "job", ".", "keys", "(", ")", ",", "job", ".", "values", "(", ")", ")", ".", "lastrowid" ]
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
[ "Create", "job", "for", "the", "given", "user", "return", "it", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L88-L104
531
gem/oq-engine
openquake/server/db/actions.py
import_job
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_name=user_name, hazard_calculation_id=hc_id, is_running=0, status=status, ds_calc_dir=os.path.join('%s/calc_%s' % (datadir, calc_id))) db('INSERT INTO job (?S) VALUES (?X)', job.keys(), job.values())
python
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_name=user_name, hazard_calculation_id=hc_id, is_running=0, status=status, ds_calc_dir=os.path.join('%s/calc_%s' % (datadir, calc_id))) db('INSERT INTO job (?S) VALUES (?X)', job.keys(), job.values())
[ "def", "import_job", "(", "db", ",", "calc_id", ",", "calc_mode", ",", "description", ",", "user_name", ",", "status", ",", "hc_id", ",", "datadir", ")", ":", "job", "=", "dict", "(", "id", "=", "calc_id", ",", "calculation_mode", "=", "calc_mode", ",", "description", "=", "description", ",", "user_name", "=", "user_name", ",", "hazard_calculation_id", "=", "hc_id", ",", "is_running", "=", "0", ",", "status", "=", "status", ",", "ds_calc_dir", "=", "os", ".", "path", ".", "join", "(", "'%s/calc_%s'", "%", "(", "datadir", ",", "calc_id", ")", ")", ")", "db", "(", "'INSERT INTO job (?S) VALUES (?X)'", ",", "job", ".", "keys", "(", ")", ",", "job", ".", "values", "(", ")", ")" ]
Insert a calculation inside the database, if calc_id is not taken
[ "Insert", "a", "calculation", "inside", "the", "database", "if", "calc_id", "is", "not", "taken" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L107-L120
532
gem/oq-engine
openquake/server/db/actions.py
get_job
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: an user name (if None, ignore it) :returns: a valid job or None if the original job ID was invalid """ job_id = int(job_id) if job_id > 0: dic = dict(id=job_id) if username: dic['user_name'] = username try: return db('SELECT * FROM job WHERE ?A', dic, one=True) except NotFound: return # else negative job_id if username: joblist = db('SELECT * FROM job WHERE user_name=?x ' 'ORDER BY id DESC LIMIT ?x', username, -job_id) else: joblist = db('SELECT * FROM job ORDER BY id DESC LIMIT ?x', -job_id) if not joblist: # no jobs return else: return joblist[-1]
python
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: an user name (if None, ignore it) :returns: a valid job or None if the original job ID was invalid """ job_id = int(job_id) if job_id > 0: dic = dict(id=job_id) if username: dic['user_name'] = username try: return db('SELECT * FROM job WHERE ?A', dic, one=True) except NotFound: return # else negative job_id if username: joblist = db('SELECT * FROM job WHERE user_name=?x ' 'ORDER BY id DESC LIMIT ?x', username, -job_id) else: joblist = db('SELECT * FROM job ORDER BY id DESC LIMIT ?x', -job_id) if not joblist: # no jobs return else: return joblist[-1]
[ "def", "get_job", "(", "db", ",", "job_id", ",", "username", "=", "None", ")", ":", "job_id", "=", "int", "(", "job_id", ")", "if", "job_id", ">", "0", ":", "dic", "=", "dict", "(", "id", "=", "job_id", ")", "if", "username", ":", "dic", "[", "'user_name'", "]", "=", "username", "try", ":", "return", "db", "(", "'SELECT * FROM job WHERE ?A'", ",", "dic", ",", "one", "=", "True", ")", "except", "NotFound", ":", "return", "# else negative job_id", "if", "username", ":", "joblist", "=", "db", "(", "'SELECT * FROM job WHERE user_name=?x '", "'ORDER BY id DESC LIMIT ?x'", ",", "username", ",", "-", "job_id", ")", "else", ":", "joblist", "=", "db", "(", "'SELECT * FROM job ORDER BY id DESC LIMIT ?x'", ",", "-", "job_id", ")", "if", "not", "joblist", ":", "# no jobs", "return", "else", ":", "return", "joblist", "[", "-", "1", "]" ]
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: an user name (if None, ignore it) :returns: a valid job or None if the original job ID was invalid
[ "If", "job_id", "is", "negative", "return", "the", "last", "calculation", "of", "the", "current", "user", "otherwise", "returns", "the", "job_id", "unchanged", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L133-L163
533
gem/oq-engine
openquake/server/db/actions.py
get_calc_id
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 ID """ calcs = datastore.get_calc_ids(datadir) calc_id = 0 if not calcs else calcs[-1] if job_id is None: try: job_id = db('SELECT seq FROM sqlite_sequence WHERE name="job"', scalar=True) except NotFound: job_id = 0 return max(calc_id, job_id)
python
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 ID """ calcs = datastore.get_calc_ids(datadir) calc_id = 0 if not calcs else calcs[-1] if job_id is None: try: job_id = db('SELECT seq FROM sqlite_sequence WHERE name="job"', scalar=True) except NotFound: job_id = 0 return max(calc_id, job_id)
[ "def", "get_calc_id", "(", "db", ",", "datadir", ",", "job_id", "=", "None", ")", ":", "calcs", "=", "datastore", ".", "get_calc_ids", "(", "datadir", ")", "calc_id", "=", "0", "if", "not", "calcs", "else", "calcs", "[", "-", "1", "]", "if", "job_id", "is", "None", ":", "try", ":", "job_id", "=", "db", "(", "'SELECT seq FROM sqlite_sequence WHERE name=\"job\"'", ",", "scalar", "=", "True", ")", "except", "NotFound", ":", "job_id", "=", "0", "return", "max", "(", "calc_id", ",", "job_id", ")" ]
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 ID
[ "Return", "the", "latest", "calc_id", "by", "looking", "both", "at", "the", "datastore", "and", "the", "database", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L166-L183
534
gem/oq-engine
openquake/server/db/actions.py
list_calculations
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 job_type=?x ORDER BY start_time' % JOB_TYPE, user_name, job_type) out = [] if len(jobs) == 0: out.append('None') else: out.append('job_id | status | start_time | ' ' description') for job in jobs: descr = job.description start_time = job.start_time out.append('%6d | %10s | %s | %s' % ( job.id, job.status, start_time, descr)) return out
python
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 job_type=?x ORDER BY start_time' % JOB_TYPE, user_name, job_type) out = [] if len(jobs) == 0: out.append('None') else: out.append('job_id | status | start_time | ' ' description') for job in jobs: descr = job.description start_time = job.start_time out.append('%6d | %10s | %s | %s' % ( job.id, job.status, start_time, descr)) return out
[ "def", "list_calculations", "(", "db", ",", "job_type", ",", "user_name", ")", ":", "jobs", "=", "db", "(", "'SELECT *, %s FROM job WHERE user_name=?x '", "'AND job_type=?x ORDER BY start_time'", "%", "JOB_TYPE", ",", "user_name", ",", "job_type", ")", "out", "=", "[", "]", "if", "len", "(", "jobs", ")", "==", "0", ":", "out", ".", "append", "(", "'None'", ")", "else", ":", "out", ".", "append", "(", "'job_id | status | start_time | '", "' description'", ")", "for", "job", "in", "jobs", ":", "descr", "=", "job", ".", "description", "start_time", "=", "job", ".", "start_time", "out", ".", "append", "(", "'%6d | %10s | %s | %s'", "%", "(", "job", ".", "id", ",", "job", ".", "status", ",", "start_time", ",", "descr", ")", ")", "return", "out" ]
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
[ "Yield", "a", "summary", "of", "past", "calculations", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L186-L208
535
gem/oq-engine
openquake/server/db/actions.py
create_outputs
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 keysize: a list of pairs (key, size_mb) :param ds_size: total datastore size in MB """ rows = [(job_id, DISPLAY_NAME.get(key, key), key, size) for key, size in keysize] db('UPDATE job SET size_mb=?x WHERE id=?x', ds_size, job_id) db.insert('output', 'oq_job_id display_name ds_key size_mb'.split(), rows)
python
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 keysize: a list of pairs (key, size_mb) :param ds_size: total datastore size in MB """ rows = [(job_id, DISPLAY_NAME.get(key, key), key, size) for key, size in keysize] db('UPDATE job SET size_mb=?x WHERE id=?x', ds_size, job_id) db.insert('output', 'oq_job_id display_name ds_key size_mb'.split(), rows)
[ "def", "create_outputs", "(", "db", ",", "job_id", ",", "keysize", ",", "ds_size", ")", ":", "rows", "=", "[", "(", "job_id", ",", "DISPLAY_NAME", ".", "get", "(", "key", ",", "key", ")", ",", "key", ",", "size", ")", "for", "key", ",", "size", "in", "keysize", "]", "db", "(", "'UPDATE job SET size_mb=?x WHERE id=?x'", ",", "ds_size", ",", "job_id", ")", "db", ".", "insert", "(", "'output'", ",", "'oq_job_id display_name ds_key size_mb'", ".", "split", "(", ")", ",", "rows", ")" ]
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 keysize: a list of pairs (key, size_mb) :param ds_size: total datastore size in MB
[ "Build", "a", "correspondence", "between", "the", "outputs", "in", "the", "datastore", "and", "the", "ones", "in", "the", "database", ".", "Also", "update", "the", "datastore", "size", "in", "the", "job", "table", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L299-L312
536
gem/oq-engine
openquake/server/db/actions.py
finish
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 SET ?D WHERE id=?x', dict(is_running=False, status=status, stop_time=datetime.utcnow()), job_id)
python
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 SET ?D WHERE id=?x', dict(is_running=False, status=status, stop_time=datetime.utcnow()), job_id)
[ "def", "finish", "(", "db", ",", "job_id", ",", "status", ")", ":", "db", "(", "'UPDATE job SET ?D WHERE id=?x'", ",", "dict", "(", "is_running", "=", "False", ",", "status", "=", "status", ",", "stop_time", "=", "datetime", ".", "utcnow", "(", ")", ")", ",", "job_id", ")" ]
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'
[ "Set", "the", "job", "columns", "is_running", "status", "and", "stop_time", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L315-L328
537
gem/oq-engine
openquake/server/db/actions.py
del_calc
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 """ job_id = int(job_id) dependent = db( 'SELECT id FROM job WHERE hazard_calculation_id=?x', job_id) if dependent: return {"error": 'Cannot delete calculation %d: there ' 'are calculations ' 'dependent from it: %s' % (job_id, [j.id for j in dependent])} try: owner, path = db('SELECT user_name, ds_calc_dir FROM job WHERE id=?x', job_id, one=True) except NotFound: return {"error": 'Cannot delete calculation %d:' ' ID does not exist' % job_id} deleted = db('DELETE FROM job WHERE id=?x AND user_name=?x', job_id, user).rowcount if not deleted: return {"error": 'Cannot delete calculation %d: it belongs to ' '%s and you are %s' % (job_id, owner, user)} # try to delete datastore and associated file # path has typically the form /home/user/oqdata/calc_XXX fname = path + ".hdf5" try: os.remove(fname) except OSError as exc: # permission error return {"error": 'Could not remove %s: %s' % (fname, exc)} return {"success": fname}
python
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 """ job_id = int(job_id) dependent = db( 'SELECT id FROM job WHERE hazard_calculation_id=?x', job_id) if dependent: return {"error": 'Cannot delete calculation %d: there ' 'are calculations ' 'dependent from it: %s' % (job_id, [j.id for j in dependent])} try: owner, path = db('SELECT user_name, ds_calc_dir FROM job WHERE id=?x', job_id, one=True) except NotFound: return {"error": 'Cannot delete calculation %d:' ' ID does not exist' % job_id} deleted = db('DELETE FROM job WHERE id=?x AND user_name=?x', job_id, user).rowcount if not deleted: return {"error": 'Cannot delete calculation %d: it belongs to ' '%s and you are %s' % (job_id, owner, user)} # try to delete datastore and associated file # path has typically the form /home/user/oqdata/calc_XXX fname = path + ".hdf5" try: os.remove(fname) except OSError as exc: # permission error return {"error": 'Could not remove %s: %s' % (fname, exc)} return {"success": fname}
[ "def", "del_calc", "(", "db", ",", "job_id", ",", "user", ")", ":", "job_id", "=", "int", "(", "job_id", ")", "dependent", "=", "db", "(", "'SELECT id FROM job WHERE hazard_calculation_id=?x'", ",", "job_id", ")", "if", "dependent", ":", "return", "{", "\"error\"", ":", "'Cannot delete calculation %d: there '", "'are calculations '", "'dependent from it: %s'", "%", "(", "job_id", ",", "[", "j", ".", "id", "for", "j", "in", "dependent", "]", ")", "}", "try", ":", "owner", ",", "path", "=", "db", "(", "'SELECT user_name, ds_calc_dir FROM job WHERE id=?x'", ",", "job_id", ",", "one", "=", "True", ")", "except", "NotFound", ":", "return", "{", "\"error\"", ":", "'Cannot delete calculation %d:'", "' ID does not exist'", "%", "job_id", "}", "deleted", "=", "db", "(", "'DELETE FROM job WHERE id=?x AND user_name=?x'", ",", "job_id", ",", "user", ")", ".", "rowcount", "if", "not", "deleted", ":", "return", "{", "\"error\"", ":", "'Cannot delete calculation %d: it belongs to '", "'%s and you are %s'", "%", "(", "job_id", ",", "owner", ",", "user", ")", "}", "# try to delete datastore and associated file", "# path has typically the form /home/user/oqdata/calc_XXX", "fname", "=", "path", "+", "\".hdf5\"", "try", ":", "os", ".", "remove", "(", "fname", ")", "except", "OSError", "as", "exc", ":", "# permission error", "return", "{", "\"error\"", ":", "'Could not remove %s: %s'", "%", "(", "fname", ",", "exc", ")", "}", "return", "{", "\"success\"", ":", "fname", "}" ]
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
[ "Delete", "a", "calculation", "and", "all", "associated", "outputs", "if", "possible", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L331-L367
538
gem/oq-engine
openquake/server/db/actions.py
log
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 store in the log record :param process: process ID to store in the log record :param message: message to store in the log record """ db('INSERT INTO log (job_id, timestamp, level, process, message) ' 'VALUES (?X)', (job_id, timestamp, level, process, message))
python
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 store in the log record :param process: process ID to store in the log record :param message: message to store in the log record """ db('INSERT INTO log (job_id, timestamp, level, process, message) ' 'VALUES (?X)', (job_id, timestamp, level, process, message))
[ "def", "log", "(", "db", ",", "job_id", ",", "timestamp", ",", "level", ",", "process", ",", "message", ")", ":", "db", "(", "'INSERT INTO log (job_id, timestamp, level, process, message) '", "'VALUES (?X)'", ",", "(", "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 store in the log record :param process: process ID to store in the log record :param message: message to store in the log record
[ "Write", "a", "log", "record", "in", "the", "database", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L370-L388
539
gem/oq-engine
openquake/server/db/actions.py
get_log
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 decimals out.append('[%s #%d %s] %s' % (time, job_id, log.level, log.message)) return out
python
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 decimals out.append('[%s #%d %s] %s' % (time, job_id, log.level, log.message)) return out
[ "def", "get_log", "(", "db", ",", "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 decimals", "out", ".", "append", "(", "'[%s #%d %s] %s'", "%", "(", "time", ",", "job_id", ",", "log", ".", "level", ",", "log", ".", "message", ")", ")", "return", "out" ]
Extract the logs as a big string :param db: a :class:`openquake.server.dbapi.Db` instance :param job_id: a job ID
[ "Extract", "the", "logs", "as", "a", "big", "string" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L391-L403
540
gem/oq-engine
openquake/server/db/actions.py
save_performance
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 is not automatically converted # into an int in Ubuntu 12.04, so we convert it manually below rows = [(job_id, rec['operation'], rec['time_sec'], rec['memory_mb'], int(rec['counts'])) for rec in records] db.insert('performance', 'job_id operation time_sec memory_mb counts'.split(), rows)
python
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 is not automatically converted # into an int in Ubuntu 12.04, so we convert it manually below rows = [(job_id, rec['operation'], rec['time_sec'], rec['memory_mb'], int(rec['counts'])) for rec in records] db.insert('performance', 'job_id operation time_sec memory_mb counts'.split(), rows)
[ "def", "save_performance", "(", "db", ",", "job_id", ",", "records", ")", ":", "# NB: rec['counts'] is a numpy.uint64 which is not automatically converted", "# into an int in Ubuntu 12.04, so we convert it manually below", "rows", "=", "[", "(", "job_id", ",", "rec", "[", "'operation'", "]", ",", "rec", "[", "'time_sec'", "]", ",", "rec", "[", "'memory_mb'", "]", ",", "int", "(", "rec", "[", "'counts'", "]", ")", ")", "for", "rec", "in", "records", "]", "db", ".", "insert", "(", "'performance'", ",", "'job_id operation time_sec memory_mb counts'", ".", "split", "(", ")", ",", "rows", ")" ]
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
[ "Save", "in", "the", "database", "the", "performance", "information", "about", "the", "given", "job", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L417-L430
541
gem/oq-engine
openquake/server/db/actions.py
get_traceback
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 returns two lines or zero lines log = db("SELECT * FROM log WHERE job_id=?x AND level='CRITICAL'", job_id) if not log: return [] response_data = log[-1].message.splitlines() return response_data
python
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 returns two lines or zero lines log = db("SELECT * FROM log WHERE job_id=?x AND level='CRITICAL'", job_id) if not log: return [] response_data = log[-1].message.splitlines() return response_data
[ "def", "get_traceback", "(", "db", ",", "job_id", ")", ":", "# strange: understand why the filter returns two lines or zero lines", "log", "=", "db", "(", "\"SELECT * FROM log WHERE job_id=?x AND level='CRITICAL'\"", ",", "job_id", ")", "if", "not", "log", ":", "return", "[", "]", "response_data", "=", "log", "[", "-", "1", "]", ".", "message", ".", "splitlines", "(", ")", "return", "response_data" ]
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
[ "Return", "the", "traceback", "of", "the", "given", "calculation", "as", "a", "list", "of", "lines", ".", "The", "list", "is", "empty", "if", "the", "calculation", "was", "successful", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L626-L642
542
gem/oq-engine
openquake/commands/webui.py
webui
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): sys.exit('This command must be run by the proper user: ' 'see the documentation for details') if cmd == 'start': dbserver.ensure_on() # start the dbserver in a subprocess rundjango('runserver', hostport, skip_browser) elif cmd in commands: rundjango(cmd)
python
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): sys.exit('This command must be run by the proper user: ' 'see the documentation for details') if cmd == 'start': dbserver.ensure_on() # start the dbserver in a subprocess rundjango('runserver', hostport, skip_browser) elif cmd in commands: rundjango(cmd)
[ "def", "webui", "(", "cmd", ",", "hostport", "=", "'127.0.0.1:8800'", ",", "skip_browser", "=", "False", ")", ":", "dbpath", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "expanduser", "(", "config", ".", "dbserver", ".", "file", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "dbpath", ")", "and", "not", "os", ".", "access", "(", "dbpath", ",", "os", ".", "W_OK", ")", ":", "sys", ".", "exit", "(", "'This command must be run by the proper user: '", "'see the documentation for details'", ")", "if", "cmd", "==", "'start'", ":", "dbserver", ".", "ensure_on", "(", ")", "# start the dbserver in a subprocess", "rundjango", "(", "'runserver'", ",", "hostport", ",", "skip_browser", ")", "elif", "cmd", "in", "commands", ":", "rundjango", "(", "cmd", ")" ]
start the webui server in foreground or perform other operation on the django application
[ "start", "the", "webui", "server", "in", "foreground", "or", "perform", "other", "operation", "on", "the", "django", "application" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/webui.py#L51-L64
543
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_2014.py
AbrahamsonEtAl2014._get_basic_term
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: c4m = 1. R = np.sqrt(dists.rrup**2. + c4m**2.) # basic form base_term = C['a1'] * np.ones_like(dists.rrup) + C['a17'] * dists.rrup # equation 2 at page 1030 if rup.mag >= C['m1']: base_term += (C['a5'] * (rup.mag - C['m1']) + C['a8'] * (8.5 - rup.mag)**2. + (C['a2'] + C['a3'] * (rup.mag - C['m1'])) * np.log(R)) elif rup.mag >= self.CONSTS['m2']: base_term += (C['a4'] * (rup.mag - C['m1']) + C['a8'] * (8.5 - rup.mag)**2. + (C['a2'] + C['a3'] * (rup.mag - C['m1'])) * np.log(R)) else: base_term += (C['a4'] * (self.CONSTS['m2'] - C['m1']) + C['a8'] * (8.5 - self.CONSTS['m2'])**2. + C['a6'] * (rup.mag - self.CONSTS['m2']) + C['a7'] * (rup.mag - self.CONSTS['m2'])**2. + (C['a2'] + C['a3'] * (self.CONSTS['m2'] - C['m1'])) * np.log(R)) return base_term
python
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: c4m = 1. R = np.sqrt(dists.rrup**2. + c4m**2.) # basic form base_term = C['a1'] * np.ones_like(dists.rrup) + C['a17'] * dists.rrup # equation 2 at page 1030 if rup.mag >= C['m1']: base_term += (C['a5'] * (rup.mag - C['m1']) + C['a8'] * (8.5 - rup.mag)**2. + (C['a2'] + C['a3'] * (rup.mag - C['m1'])) * np.log(R)) elif rup.mag >= self.CONSTS['m2']: base_term += (C['a4'] * (rup.mag - C['m1']) + C['a8'] * (8.5 - rup.mag)**2. + (C['a2'] + C['a3'] * (rup.mag - C['m1'])) * np.log(R)) else: base_term += (C['a4'] * (self.CONSTS['m2'] - C['m1']) + C['a8'] * (8.5 - self.CONSTS['m2'])**2. + C['a6'] * (rup.mag - self.CONSTS['m2']) + C['a7'] * (rup.mag - self.CONSTS['m2'])**2. + (C['a2'] + C['a3'] * (self.CONSTS['m2'] - C['m1'])) * np.log(R)) return base_term
[ "def", "_get_basic_term", "(", "self", ",", "C", ",", "rup", ",", "dists", ")", ":", "# Fictitious depth calculation", "if", "rup", ".", "mag", ">", "5.", ":", "c4m", "=", "C", "[", "'c4'", "]", "elif", "rup", ".", "mag", ">", "4.", ":", "c4m", "=", "C", "[", "'c4'", "]", "-", "(", "C", "[", "'c4'", "]", "-", "1.", ")", "*", "(", "5.", "-", "rup", ".", "mag", ")", "else", ":", "c4m", "=", "1.", "R", "=", "np", ".", "sqrt", "(", "dists", ".", "rrup", "**", "2.", "+", "c4m", "**", "2.", ")", "# basic form", "base_term", "=", "C", "[", "'a1'", "]", "*", "np", ".", "ones_like", "(", "dists", ".", "rrup", ")", "+", "C", "[", "'a17'", "]", "*", "dists", ".", "rrup", "# equation 2 at page 1030", "if", "rup", ".", "mag", ">=", "C", "[", "'m1'", "]", ":", "base_term", "+=", "(", "C", "[", "'a5'", "]", "*", "(", "rup", ".", "mag", "-", "C", "[", "'m1'", "]", ")", "+", "C", "[", "'a8'", "]", "*", "(", "8.5", "-", "rup", ".", "mag", ")", "**", "2.", "+", "(", "C", "[", "'a2'", "]", "+", "C", "[", "'a3'", "]", "*", "(", "rup", ".", "mag", "-", "C", "[", "'m1'", "]", ")", ")", "*", "np", ".", "log", "(", "R", ")", ")", "elif", "rup", ".", "mag", ">=", "self", ".", "CONSTS", "[", "'m2'", "]", ":", "base_term", "+=", "(", "C", "[", "'a4'", "]", "*", "(", "rup", ".", "mag", "-", "C", "[", "'m1'", "]", ")", "+", "C", "[", "'a8'", "]", "*", "(", "8.5", "-", "rup", ".", "mag", ")", "**", "2.", "+", "(", "C", "[", "'a2'", "]", "+", "C", "[", "'a3'", "]", "*", "(", "rup", ".", "mag", "-", "C", "[", "'m1'", "]", ")", ")", "*", "np", ".", "log", "(", "R", ")", ")", "else", ":", "base_term", "+=", "(", "C", "[", "'a4'", "]", "*", "(", "self", ".", "CONSTS", "[", "'m2'", "]", "-", "C", "[", "'m1'", "]", ")", "+", "C", "[", "'a8'", "]", "*", "(", "8.5", "-", "self", ".", "CONSTS", "[", "'m2'", "]", ")", "**", "2.", "+", "C", "[", "'a6'", "]", "*", "(", "rup", ".", "mag", "-", "self", ".", "CONSTS", "[", "'m2'", "]", ")", "+", "C", "[", "'a7'", "]", "*", "(", "rup", ".", "mag", "-", "self", ".", "CONSTS", "[", "'m2'", "]", ")", "**", "2.", "+", "(", "C", "[", "'a2'", "]", "+", "C", "[", "'a3'", "]", "*", "(", "self", ".", "CONSTS", "[", "'m2'", "]", "-", "C", "[", "'m1'", "]", ")", ")", "*", "np", ".", "log", "(", "R", ")", ")", "return", "base_term" ]
Compute and return basic form, see page 1030.
[ "Compute", "and", "return", "basic", "form", "see", "page", "1030", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L130-L162
544
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_2014.py
AbrahamsonEtAl2014._get_vs30star
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: v1 = np.exp(-0.35 * np.log(t / 0.5) + np.log(1500.)) else: v1 = 800.0 elif imt.name == "PGA": v1 = 1500.0 else: # This covers the PGV case v1 = 1500.0 # set the vs30 star value (see eq. 8, page 1034) vs30_star = np.ones_like(vs30) * vs30 vs30_star[vs30 >= v1] = v1 return vs30_star
python
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: v1 = np.exp(-0.35 * np.log(t / 0.5) + np.log(1500.)) else: v1 = 800.0 elif imt.name == "PGA": v1 = 1500.0 else: # This covers the PGV case v1 = 1500.0 # set the vs30 star value (see eq. 8, page 1034) vs30_star = np.ones_like(vs30) * vs30 vs30_star[vs30 >= v1] = v1 return vs30_star
[ "def", "_get_vs30star", "(", "self", ",", "vs30", ",", "imt", ")", ":", "# 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", ":", "v1", "=", "np", ".", "exp", "(", "-", "0.35", "*", "np", ".", "log", "(", "t", "/", "0.5", ")", "+", "np", ".", "log", "(", "1500.", ")", ")", "else", ":", "v1", "=", "800.0", "elif", "imt", ".", "name", "==", "\"PGA\"", ":", "v1", "=", "1500.0", "else", ":", "# This covers the PGV case", "v1", "=", "1500.0", "# set the vs30 star value (see eq. 8, page 1034)", "vs30_star", "=", "np", ".", "ones_like", "(", "vs30", ")", "*", "vs30", "vs30_star", "[", "vs30", ">=", "v1", "]", "=", "v1", "return", "vs30_star" ]
This computes equations 8 and 9 at page 1034
[ "This", "computes", "equations", "8", "and", "9", "at", "page", "1034" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L186-L207
545
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_2014.py
AbrahamsonEtAl2014._get_site_response_term
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 >= C['vlin'] lw_vlin = vs30 < C['vlin'] # compute site response term for sites with vs30 greater than vlin vs30_rat = vs30_star / C['vlin'] site_resp_term[gt_vlin] = ((C['a10'] + C['b'] * self.CONSTS['n']) * np.log(vs30_rat[gt_vlin])) # compute site response term for sites with vs30 lower than vlin site_resp_term[lw_vlin] = (C['a10'] * np.log(vs30_rat[lw_vlin]) - C['b'] * np.log(sa1180[lw_vlin] + C['c']) + C['b'] * np.log(sa1180[lw_vlin] + C['c'] * vs30_rat[lw_vlin] ** self.CONSTS['n'])) return site_resp_term
python
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 >= C['vlin'] lw_vlin = vs30 < C['vlin'] # compute site response term for sites with vs30 greater than vlin vs30_rat = vs30_star / C['vlin'] site_resp_term[gt_vlin] = ((C['a10'] + C['b'] * self.CONSTS['n']) * np.log(vs30_rat[gt_vlin])) # compute site response term for sites with vs30 lower than vlin site_resp_term[lw_vlin] = (C['a10'] * np.log(vs30_rat[lw_vlin]) - C['b'] * np.log(sa1180[lw_vlin] + C['c']) + C['b'] * np.log(sa1180[lw_vlin] + C['c'] * vs30_rat[lw_vlin] ** self.CONSTS['n'])) return site_resp_term
[ "def", "_get_site_response_term", "(", "self", ",", "C", ",", "imt", ",", "vs30", ",", "sa1180", ")", ":", "# vs30 star", "vs30_star", "=", "self", ".", "_get_vs30star", "(", "vs30", ",", "imt", ")", "# compute the site term", "site_resp_term", "=", "np", ".", "zeros_like", "(", "vs30", ")", "gt_vlin", "=", "vs30", ">=", "C", "[", "'vlin'", "]", "lw_vlin", "=", "vs30", "<", "C", "[", "'vlin'", "]", "# compute site response term for sites with vs30 greater than vlin", "vs30_rat", "=", "vs30_star", "/", "C", "[", "'vlin'", "]", "site_resp_term", "[", "gt_vlin", "]", "=", "(", "(", "C", "[", "'a10'", "]", "+", "C", "[", "'b'", "]", "*", "self", ".", "CONSTS", "[", "'n'", "]", ")", "*", "np", ".", "log", "(", "vs30_rat", "[", "gt_vlin", "]", ")", ")", "# compute site response term for sites with vs30 lower than vlin", "site_resp_term", "[", "lw_vlin", "]", "=", "(", "C", "[", "'a10'", "]", "*", "np", ".", "log", "(", "vs30_rat", "[", "lw_vlin", "]", ")", "-", "C", "[", "'b'", "]", "*", "np", ".", "log", "(", "sa1180", "[", "lw_vlin", "]", "+", "C", "[", "'c'", "]", ")", "+", "C", "[", "'b'", "]", "*", "np", ".", "log", "(", "sa1180", "[", "lw_vlin", "]", "+", "C", "[", "'c'", "]", "*", "vs30_rat", "[", "lw_vlin", "]", "**", "self", ".", "CONSTS", "[", "'n'", "]", ")", ")", "return", "site_resp_term" ]
Compute and return site response model term see page 1033
[ "Compute", "and", "return", "site", "response", "model", "term", "see", "page", "1033" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L209-L229
546
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_2014.py
AbrahamsonEtAl2014._get_hanging_wall_term
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. # Compute taper t1 T1 = np.ones_like(dists.rx) T1 *= 60./45. if rup.dip <= 30. else (90.-rup.dip)/45.0 # Compute taper t2 (eq 12 at page 1039) - a2hw set to 0.2 as # indicated at page 1041 T2 = np.zeros_like(dists.rx) a2hw = 0.2 if rup.mag > 6.5: T2 += (1. + a2hw * (rup.mag - 6.5)) elif rup.mag > 5.5: T2 += (1. + a2hw * (rup.mag - 6.5) - (1. - a2hw) * (rup.mag - 6.5)**2) else: T2 *= 0. # Compute taper t3 (eq. 13 at page 1039) - r1 and r2 specified at # page 1040 T3 = np.zeros_like(dists.rx) r1 = rup.width * np.cos(np.radians(rup.dip)) r2 = 3. * r1 # idx = dists.rx < r1 T3[idx] = (np.ones_like(dists.rx)[idx] * self.CONSTS['h1'] + self.CONSTS['h2'] * (dists.rx[idx] / r1) + self.CONSTS['h3'] * (dists.rx[idx] / r1)**2) # idx = ((dists.rx >= r1) & (dists.rx <= r2)) T3[idx] = 1. - (dists.rx[idx] - r1) / (r2 - r1) # Compute taper t4 (eq. 14 at page 1040) T4 = np.zeros_like(dists.rx) # if rup.ztor <= 10.: T4 += (1. - rup.ztor**2. / 100.) # Compute T5 (eq 15a at page 1040) - ry1 computed according to # suggestions provided at page 1040 T5 = np.zeros_like(dists.rx) ry1 = dists.rx * np.tan(np.radians(20.)) # idx = (dists.ry0 - ry1) <= 0.0 T5[idx] = 1. # idx = (((dists.ry0 - ry1) > 0.0) & ((dists.ry0 - ry1) < 5.0)) T5[idx] = 1. - (dists.ry0[idx] - ry1[idx]) / 5.0 # Finally, compute the hanging wall term return Fhw*C['a13']*T1*T2*T3*T4*T5
python
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. # Compute taper t1 T1 = np.ones_like(dists.rx) T1 *= 60./45. if rup.dip <= 30. else (90.-rup.dip)/45.0 # Compute taper t2 (eq 12 at page 1039) - a2hw set to 0.2 as # indicated at page 1041 T2 = np.zeros_like(dists.rx) a2hw = 0.2 if rup.mag > 6.5: T2 += (1. + a2hw * (rup.mag - 6.5)) elif rup.mag > 5.5: T2 += (1. + a2hw * (rup.mag - 6.5) - (1. - a2hw) * (rup.mag - 6.5)**2) else: T2 *= 0. # Compute taper t3 (eq. 13 at page 1039) - r1 and r2 specified at # page 1040 T3 = np.zeros_like(dists.rx) r1 = rup.width * np.cos(np.radians(rup.dip)) r2 = 3. * r1 # idx = dists.rx < r1 T3[idx] = (np.ones_like(dists.rx)[idx] * self.CONSTS['h1'] + self.CONSTS['h2'] * (dists.rx[idx] / r1) + self.CONSTS['h3'] * (dists.rx[idx] / r1)**2) # idx = ((dists.rx >= r1) & (dists.rx <= r2)) T3[idx] = 1. - (dists.rx[idx] - r1) / (r2 - r1) # Compute taper t4 (eq. 14 at page 1040) T4 = np.zeros_like(dists.rx) # if rup.ztor <= 10.: T4 += (1. - rup.ztor**2. / 100.) # Compute T5 (eq 15a at page 1040) - ry1 computed according to # suggestions provided at page 1040 T5 = np.zeros_like(dists.rx) ry1 = dists.rx * np.tan(np.radians(20.)) # idx = (dists.ry0 - ry1) <= 0.0 T5[idx] = 1. # idx = (((dists.ry0 - ry1) > 0.0) & ((dists.ry0 - ry1) < 5.0)) T5[idx] = 1. - (dists.ry0[idx] - ry1[idx]) / 5.0 # Finally, compute the hanging wall term return Fhw*C['a13']*T1*T2*T3*T4*T5
[ "def", "_get_hanging_wall_term", "(", "self", ",", "C", ",", "dists", ",", "rup", ")", ":", "if", "rup", ".", "dip", "==", "90.0", ":", "return", "np", ".", "zeros_like", "(", "dists", ".", "rx", ")", "else", ":", "Fhw", "=", "np", ".", "zeros_like", "(", "dists", ".", "rx", ")", "Fhw", "[", "dists", ".", "rx", ">", "0", "]", "=", "1.", "# Compute taper t1", "T1", "=", "np", ".", "ones_like", "(", "dists", ".", "rx", ")", "T1", "*=", "60.", "/", "45.", "if", "rup", ".", "dip", "<=", "30.", "else", "(", "90.", "-", "rup", ".", "dip", ")", "/", "45.0", "# Compute taper t2 (eq 12 at page 1039) - a2hw set to 0.2 as", "# indicated at page 1041", "T2", "=", "np", ".", "zeros_like", "(", "dists", ".", "rx", ")", "a2hw", "=", "0.2", "if", "rup", ".", "mag", ">", "6.5", ":", "T2", "+=", "(", "1.", "+", "a2hw", "*", "(", "rup", ".", "mag", "-", "6.5", ")", ")", "elif", "rup", ".", "mag", ">", "5.5", ":", "T2", "+=", "(", "1.", "+", "a2hw", "*", "(", "rup", ".", "mag", "-", "6.5", ")", "-", "(", "1.", "-", "a2hw", ")", "*", "(", "rup", ".", "mag", "-", "6.5", ")", "**", "2", ")", "else", ":", "T2", "*=", "0.", "# Compute taper t3 (eq. 13 at page 1039) - r1 and r2 specified at", "# page 1040", "T3", "=", "np", ".", "zeros_like", "(", "dists", ".", "rx", ")", "r1", "=", "rup", ".", "width", "*", "np", ".", "cos", "(", "np", ".", "radians", "(", "rup", ".", "dip", ")", ")", "r2", "=", "3.", "*", "r1", "#", "idx", "=", "dists", ".", "rx", "<", "r1", "T3", "[", "idx", "]", "=", "(", "np", ".", "ones_like", "(", "dists", ".", "rx", ")", "[", "idx", "]", "*", "self", ".", "CONSTS", "[", "'h1'", "]", "+", "self", ".", "CONSTS", "[", "'h2'", "]", "*", "(", "dists", ".", "rx", "[", "idx", "]", "/", "r1", ")", "+", "self", ".", "CONSTS", "[", "'h3'", "]", "*", "(", "dists", ".", "rx", "[", "idx", "]", "/", "r1", ")", "**", "2", ")", "#", "idx", "=", "(", "(", "dists", ".", "rx", ">=", "r1", ")", "&", "(", "dists", ".", "rx", "<=", "r2", ")", ")", "T3", "[", "idx", "]", "=", "1.", "-", "(", "dists", ".", "rx", "[", "idx", "]", "-", "r1", ")", "/", "(", "r2", "-", "r1", ")", "# Compute taper t4 (eq. 14 at page 1040)", "T4", "=", "np", ".", "zeros_like", "(", "dists", ".", "rx", ")", "#", "if", "rup", ".", "ztor", "<=", "10.", ":", "T4", "+=", "(", "1.", "-", "rup", ".", "ztor", "**", "2.", "/", "100.", ")", "# Compute T5 (eq 15a at page 1040) - ry1 computed according to", "# suggestions provided at page 1040", "T5", "=", "np", ".", "zeros_like", "(", "dists", ".", "rx", ")", "ry1", "=", "dists", ".", "rx", "*", "np", ".", "tan", "(", "np", ".", "radians", "(", "20.", ")", ")", "#", "idx", "=", "(", "dists", ".", "ry0", "-", "ry1", ")", "<=", "0.0", "T5", "[", "idx", "]", "=", "1.", "#", "idx", "=", "(", "(", "(", "dists", ".", "ry0", "-", "ry1", ")", ">", "0.0", ")", "&", "(", "(", "dists", ".", "ry0", "-", "ry1", ")", "<", "5.0", ")", ")", "T5", "[", "idx", "]", "=", "1.", "-", "(", "dists", ".", "ry0", "[", "idx", "]", "-", "ry1", "[", "idx", "]", ")", "/", "5.0", "# Finally, compute the hanging wall term", "return", "Fhw", "*", "C", "[", "'a13'", "]", "*", "T1", "*", "T2", "*", "T3", "*", "T4", "*", "T5" ]
Compute and return hanging wall model term, see page 1038.
[ "Compute", "and", "return", "hanging", "wall", "model", "term", "see", "page", "1038", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L231-L283
547
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_2014.py
AbrahamsonEtAl2014._get_top_of_rupture_depth_term
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
python
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_top_of_rupture_depth_term", "(", "self", ",", "C", ",", "imt", ",", "rup", ")", ":", "if", "rup", ".", "ztor", ">=", "20.0", ":", "return", "C", "[", "'a15'", "]", "else", ":", "return", "C", "[", "'a15'", "]", "*", "rup", ".", "ztor", "/", "20.0" ]
Compute and return top of rupture depth term. See paragraph 'Depth-to-Top of Rupture Model', page 1042.
[ "Compute", "and", "return", "top", "of", "rupture", "depth", "term", ".", "See", "paragraph", "Depth", "-", "to", "-", "Top", "of", "Rupture", "Model", "page", "1042", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L285-L293
548
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_2014.py
AbrahamsonEtAl2014._get_soil_depth_term
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 reference rock idx = z1pt0 < 0 z10[idx] = z1ref[idx] factor = np.log((z10 + 0.01) / (z1ref + 0.01)) # Here we use a linear interpolation as suggested in the 'Application # guidelines' at page 1044 # Above 700 m/s the trend is flat, but we extend the Vs30 range to # 6,000 m/s (basically the upper limit for mantle shear wave velocity # on earth) to allow extrapolation without throwing an error. f2 = interpolate.interp1d( [0.0, 150, 250, 400, 700, 1000, 6000], [C['a43'], C['a43'], C['a44'], C['a45'], C['a46'], C['a46'], C['a46']], kind='linear') return f2(vs30) * factor
python
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 reference rock idx = z1pt0 < 0 z10[idx] = z1ref[idx] factor = np.log((z10 + 0.01) / (z1ref + 0.01)) # Here we use a linear interpolation as suggested in the 'Application # guidelines' at page 1044 # Above 700 m/s the trend is flat, but we extend the Vs30 range to # 6,000 m/s (basically the upper limit for mantle shear wave velocity # on earth) to allow extrapolation without throwing an error. f2 = interpolate.interp1d( [0.0, 150, 250, 400, 700, 1000, 6000], [C['a43'], C['a43'], C['a44'], C['a45'], C['a46'], C['a46'], C['a46']], kind='linear') return f2(vs30) * factor
[ "def", "_get_soil_depth_term", "(", "self", ",", "C", ",", "z1pt0", ",", "vs30", ")", ":", "# Get reference z1pt0", "z1ref", "=", "self", ".", "_get_z1pt0ref", "(", "vs30", ")", "# Get z1pt0", "z10", "=", "copy", ".", "deepcopy", "(", "z1pt0", ")", "# This is used for the calculation of the motion on reference rock", "idx", "=", "z1pt0", "<", "0", "z10", "[", "idx", "]", "=", "z1ref", "[", "idx", "]", "factor", "=", "np", ".", "log", "(", "(", "z10", "+", "0.01", ")", "/", "(", "z1ref", "+", "0.01", ")", ")", "# Here we use a linear interpolation as suggested in the 'Application", "# guidelines' at page 1044", "# Above 700 m/s the trend is flat, but we extend the Vs30 range to", "# 6,000 m/s (basically the upper limit for mantle shear wave velocity", "# on earth) to allow extrapolation without throwing an error.", "f2", "=", "interpolate", ".", "interp1d", "(", "[", "0.0", ",", "150", ",", "250", ",", "400", ",", "700", ",", "1000", ",", "6000", "]", ",", "[", "C", "[", "'a43'", "]", ",", "C", "[", "'a43'", "]", ",", "C", "[", "'a44'", "]", ",", "C", "[", "'a45'", "]", ",", "C", "[", "'a46'", "]", ",", "C", "[", "'a46'", "]", ",", "C", "[", "'a46'", "]", "]", ",", "kind", "=", "'linear'", ")", "return", "f2", "(", "vs30", ")", "*", "factor" ]
Compute and return soil depth term. See page 1042.
[ "Compute", "and", "return", "soil", "depth", "term", ".", "See", "page", "1042", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L303-L325
549
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_2014.py
AbrahamsonEtAl2014._get_stddevs
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, sites.vs30measured, dists.rrup) std_inter = self._get_inter_event_std(C, rup.mag, sa1180, sites.vs30) stddevs = [] for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const.StdDev.TOTAL: stddevs.append(np.sqrt(std_intra ** 2 + std_inter ** 2)) elif stddev_type == const.StdDev.INTRA_EVENT: stddevs.append(std_intra) elif stddev_type == const.StdDev.INTER_EVENT: stddevs.append(std_inter) return stddevs
python
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, sites.vs30measured, dists.rrup) std_inter = self._get_inter_event_std(C, rup.mag, sa1180, sites.vs30) stddevs = [] for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const.StdDev.TOTAL: stddevs.append(np.sqrt(std_intra ** 2 + std_inter ** 2)) elif stddev_type == const.StdDev.INTRA_EVENT: stddevs.append(std_intra) elif stddev_type == const.StdDev.INTER_EVENT: stddevs.append(std_inter) return stddevs
[ "def", "_get_stddevs", "(", "self", ",", "C", ",", "imt", ",", "rup", ",", "sites", ",", "stddev_types", ",", "sa1180", ",", "dists", ")", ":", "std_intra", "=", "self", ".", "_get_intra_event_std", "(", "C", ",", "rup", ".", "mag", ",", "sa1180", ",", "sites", ".", "vs30", ",", "sites", ".", "vs30measured", ",", "dists", ".", "rrup", ")", "std_inter", "=", "self", ".", "_get_inter_event_std", "(", "C", ",", "rup", ".", "mag", ",", "sa1180", ",", "sites", ".", "vs30", ")", "stddevs", "=", "[", "]", "for", "stddev_type", "in", "stddev_types", ":", "assert", "stddev_type", "in", "self", ".", "DEFINED_FOR_STANDARD_DEVIATION_TYPES", "if", "stddev_type", "==", "const", ".", "StdDev", ".", "TOTAL", ":", "stddevs", ".", "append", "(", "np", ".", "sqrt", "(", "std_intra", "**", "2", "+", "std_inter", "**", "2", ")", ")", "elif", "stddev_type", "==", "const", ".", "StdDev", ".", "INTRA_EVENT", ":", "stddevs", ".", "append", "(", "std_intra", ")", "elif", "stddev_type", "==", "const", ".", "StdDev", ".", "INTER_EVENT", ":", "stddevs", ".", "append", "(", "std_inter", ")", "return", "stddevs" ]
Return standard deviations as described in paragraph 'Equations for standard deviation', page 1046.
[ "Return", "standard", "deviations", "as", "described", "in", "paragraph", "Equations", "for", "standard", "deviation", "page", "1046", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L334-L352
550
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_2014.py
AbrahamsonEtAl2014._get_intra_event_std
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_amp = 0.4 idx = phi_al < phi_amp if np.any(idx): # In the case of small magnitudes and long periods it is possible # for phi_al to take a value less than phi_amp, which would return # a complex value. According to the GMPE authors in this case # phi_amp should be reduced such that it is fractionally smaller # than phi_al phi_amp = 0.4 * np.ones_like(phi_al) phi_amp[idx] = 0.99 * phi_al[idx] phi_b = np.sqrt(phi_al**2 - phi_amp**2) phi = np.sqrt(phi_b**2 * (1 + derAmp)**2 + phi_amp**2) return phi
python
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_amp = 0.4 idx = phi_al < phi_amp if np.any(idx): # In the case of small magnitudes and long periods it is possible # for phi_al to take a value less than phi_amp, which would return # a complex value. According to the GMPE authors in this case # phi_amp should be reduced such that it is fractionally smaller # than phi_al phi_amp = 0.4 * np.ones_like(phi_al) phi_amp[idx] = 0.99 * phi_al[idx] phi_b = np.sqrt(phi_al**2 - phi_amp**2) phi = np.sqrt(phi_b**2 * (1 + derAmp)**2 + phi_amp**2) return phi
[ "def", "_get_intra_event_std", "(", "self", ",", "C", ",", "mag", ",", "sa1180", ",", "vs30", ",", "vs30measured", ",", "rrup", ")", ":", "phi_al", "=", "self", ".", "_get_phi_al_regional", "(", "C", ",", "mag", ",", "vs30measured", ",", "rrup", ")", "derAmp", "=", "self", ".", "_get_derivative", "(", "C", ",", "sa1180", ",", "vs30", ")", "phi_amp", "=", "0.4", "idx", "=", "phi_al", "<", "phi_amp", "if", "np", ".", "any", "(", "idx", ")", ":", "# In the case of small magnitudes and long periods it is possible", "# for phi_al to take a value less than phi_amp, which would return", "# a complex value. According to the GMPE authors in this case", "# phi_amp should be reduced such that it is fractionally smaller", "# than phi_al", "phi_amp", "=", "0.4", "*", "np", ".", "ones_like", "(", "phi_al", ")", "phi_amp", "[", "idx", "]", "=", "0.99", "*", "phi_al", "[", "idx", "]", "phi_b", "=", "np", ".", "sqrt", "(", "phi_al", "**", "2", "-", "phi_amp", "**", "2", ")", "phi", "=", "np", ".", "sqrt", "(", "phi_b", "**", "2", "*", "(", "1", "+", "derAmp", ")", "**", "2", "+", "phi_amp", "**", "2", ")", "return", "phi" ]
Returns Phi as described at pages 1046 and 1047
[ "Returns", "Phi", "as", "described", "at", "pages", "1046", "and", "1047" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L354-L373
551
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_2014.py
AbrahamsonEtAl2014._get_derivative
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) + 1./(sa1180[idx] + c*(vs30[idx]/C['vlin'])**n))) return derAmp
python
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) + 1./(sa1180[idx] + c*(vs30[idx]/C['vlin'])**n))) return derAmp
[ "def", "_get_derivative", "(", "self", ",", "C", ",", "sa1180", ",", "vs30", ")", ":", "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", ")", "+", "1.", "/", "(", "sa1180", "[", "idx", "]", "+", "c", "*", "(", "vs30", "[", "idx", "]", "/", "C", "[", "'vlin'", "]", ")", "**", "n", ")", ")", ")", "return", "derAmp" ]
Returns equation 30 page 1047
[ "Returns", "equation", "30", "page", "1047" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L375-L386
552
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_2014.py
AbrahamsonEtAl2014RegJPN._get_regional_term
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['a42']], kind='linear') return f3(vs30) + C['a29'] * rrup
python
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['a42']], kind='linear') return f3(vs30) + C['a29'] * rrup
[ "def", "_get_regional_term", "(", "self", ",", "C", ",", "imt", ",", "vs30", ",", "rrup", ")", ":", "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", "[", "'a42'", "]", "]", ",", "kind", "=", "'linear'", ")", "return", "f3", "(", "vs30", ")", "+", "C", "[", "'a29'", "]", "*", "rrup" ]
Compute regional term for Japan. See page 1043
[ "Compute", "regional", "term", "for", "Japan", ".", "See", "page", "1043" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L511-L520
553
gem/oq-engine
openquake/hazardlib/gsim/yu_2013.py
gc
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 mag > 6.5: a1ca = coeff['ua'] a1cb = coeff['ub'] a1cc = coeff['uc'] a1cd = coeff['ud'] a1ce = coeff['ue'] a2ca = coeff['ia'] a2cb = coeff['ib'] a2cc = coeff['ic'] a2cd = coeff['id'] a2ce = coeff['ie'] else: a1ca = coeff['a'] a1cb = coeff['b'] a1cc = coeff['c'] a1cd = coeff['d'] a1ce = coeff['e'] a2ca = coeff['ma'] a2cb = coeff['mb'] a2cc = coeff['mc'] a2cd = coeff['md'] a2ce = coeff['me'] return a1ca, a1cb, a1cc, a1cd, a1ce, a2ca, a2cb, a2cc, a2cd, a2ce
python
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 mag > 6.5: a1ca = coeff['ua'] a1cb = coeff['ub'] a1cc = coeff['uc'] a1cd = coeff['ud'] a1ce = coeff['ue'] a2ca = coeff['ia'] a2cb = coeff['ib'] a2cc = coeff['ic'] a2cd = coeff['id'] a2ce = coeff['ie'] else: a1ca = coeff['a'] a1cb = coeff['b'] a1cc = coeff['c'] a1cd = coeff['d'] a1ce = coeff['e'] a2ca = coeff['ma'] a2cb = coeff['mb'] a2cc = coeff['mc'] a2cd = coeff['md'] a2ce = coeff['me'] return a1ca, a1cb, a1cc, a1cd, a1ce, a2ca, a2cb, a2cc, a2cd, a2ce
[ "def", "gc", "(", "coeff", ",", "mag", ")", ":", "if", "mag", ">", "6.5", ":", "a1ca", "=", "coeff", "[", "'ua'", "]", "a1cb", "=", "coeff", "[", "'ub'", "]", "a1cc", "=", "coeff", "[", "'uc'", "]", "a1cd", "=", "coeff", "[", "'ud'", "]", "a1ce", "=", "coeff", "[", "'ue'", "]", "a2ca", "=", "coeff", "[", "'ia'", "]", "a2cb", "=", "coeff", "[", "'ib'", "]", "a2cc", "=", "coeff", "[", "'ic'", "]", "a2cd", "=", "coeff", "[", "'id'", "]", "a2ce", "=", "coeff", "[", "'ie'", "]", "else", ":", "a1ca", "=", "coeff", "[", "'a'", "]", "a1cb", "=", "coeff", "[", "'b'", "]", "a1cc", "=", "coeff", "[", "'c'", "]", "a1cd", "=", "coeff", "[", "'d'", "]", "a1ce", "=", "coeff", "[", "'e'", "]", "a2ca", "=", "coeff", "[", "'ma'", "]", "a2cb", "=", "coeff", "[", "'mb'", "]", "a2cc", "=", "coeff", "[", "'mc'", "]", "a2cd", "=", "coeff", "[", "'md'", "]", "a2ce", "=", "coeff", "[", "'me'", "]", "return", "a1ca", ",", "a1cb", ",", "a1cc", ",", "a1cd", ",", "a1ce", ",", "a2ca", ",", "a2cb", ",", "a2cc", ",", "a2cd", ",", "a2ce" ]
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
[ "Returns", "the", "set", "of", "coefficients", "to", "be", "used", "for", "the", "calculation", "of", "GM", "as", "a", "function", "of", "earthquake", "magnitude" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/yu_2013.py#L34-L68
554
gem/oq-engine
openquake/hazardlib/gsim/yu_2013.py
rbf
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, a2ce = gc(coeff, mag) term1 = a1ca + a1cb * mag + a1cc * np.log(ra + a1cd*np.exp(a1ce*mag)) term2 = a2ca + a2cb * mag term3 = a2cd*np.exp(a2ce*mag) return np.exp((term1 - term2) / a2cc) - term3
python
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, a2ce = gc(coeff, mag) term1 = a1ca + a1cb * mag + a1cc * np.log(ra + a1cd*np.exp(a1ce*mag)) term2 = a2ca + a2cb * mag term3 = a2cd*np.exp(a2ce*mag) return np.exp((term1 - term2) / a2cc) - term3
[ "def", "rbf", "(", "ra", ",", "coeff", ",", "mag", ")", ":", "a1ca", ",", "a1cb", ",", "a1cc", ",", "a1cd", ",", "a1ce", ",", "a2ca", ",", "a2cb", ",", "a2cc", ",", "a2cd", ",", "a2ce", "=", "gc", "(", "coeff", ",", "mag", ")", "term1", "=", "a1ca", "+", "a1cb", "*", "mag", "+", "a1cc", "*", "np", ".", "log", "(", "ra", "+", "a1cd", "*", "np", ".", "exp", "(", "a1ce", "*", "mag", ")", ")", "term2", "=", "a2ca", "+", "a2cb", "*", "mag", "term3", "=", "a2cd", "*", "np", ".", "exp", "(", "a2ce", "*", "mag", ")", "return", "np", ".", "exp", "(", "(", "term1", "-", "term2", ")", "/", "a2cc", ")", "-", "term3" ]
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:
[ "Calculate", "the", "median", "ground", "motion", "for", "a", "given", "magnitude", "and", "distance" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/yu_2013.py#L71-L88
555
gem/oq-engine
openquake/hazardlib/gsim/yu_2013.py
fnc
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] # # azimuth theta = args[1] # # magnitude mag = args[2] # # coefficients coeff = args[3] # # compute the difference between epicentral distances rb = rbf(ra, coeff, mag) t1 = ra**2 * (np.sin(np.radians(theta)))**2 t2 = rb**2 * (np.cos(np.radians(theta)))**2 xx = ra * rb / (t1+t2)**0.5 return xx-repi
python
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] # # azimuth theta = args[1] # # magnitude mag = args[2] # # coefficients coeff = args[3] # # compute the difference between epicentral distances rb = rbf(ra, coeff, mag) t1 = ra**2 * (np.sin(np.radians(theta)))**2 t2 = rb**2 * (np.cos(np.radians(theta)))**2 xx = ra * rb / (t1+t2)**0.5 return xx-repi
[ "def", "fnc", "(", "ra", ",", "*", "args", ")", ":", "#", "# epicentral distance", "repi", "=", "args", "[", "0", "]", "#", "# azimuth", "theta", "=", "args", "[", "1", "]", "#", "# magnitude", "mag", "=", "args", "[", "2", "]", "#", "# coefficients", "coeff", "=", "args", "[", "3", "]", "#", "# compute the difference between epicentral distances", "rb", "=", "rbf", "(", "ra", ",", "coeff", ",", "mag", ")", "t1", "=", "ra", "**", "2", "*", "(", "np", ".", "sin", "(", "np", ".", "radians", "(", "theta", ")", ")", ")", "**", "2", "t2", "=", "rb", "**", "2", "*", "(", "np", ".", "cos", "(", "np", ".", "radians", "(", "theta", ")", ")", ")", "**", "2", "xx", "=", "ra", "*", "rb", "/", "(", "t1", "+", "t2", ")", "**", "0.5", "return", "xx", "-", "repi" ]
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
[ "Function", "used", "in", "the", "minimisation", "problem", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/yu_2013.py#L91-L119
556
gem/oq-engine
openquake/hazardlib/gsim/yu_2013.py
get_ras
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 between epicentral distances dff = fnc(ras, repi, theta, mag, coeff) while abs(dff) > 1e-3: # update the value of distance computed if dff > 0.: ras = ras - rx else: ras = ras + rx dff = fnc(ras, repi, theta, mag, coeff) rx = rx / 2. if rx < 1e-3: break return ras
python
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 between epicentral distances dff = fnc(ras, repi, theta, mag, coeff) while abs(dff) > 1e-3: # update the value of distance computed if dff > 0.: ras = ras - rx else: ras = ras + rx dff = fnc(ras, repi, theta, mag, coeff) rx = rx / 2. if rx < 1e-3: break return ras
[ "def", "get_ras", "(", "repi", ",", "theta", ",", "mag", ",", "coeff", ")", ":", "rx", "=", "100.", "ras", "=", "200.", "#", "# calculate the difference between epicentral distances", "dff", "=", "fnc", "(", "ras", ",", "repi", ",", "theta", ",", "mag", ",", "coeff", ")", "while", "abs", "(", "dff", ")", ">", "1e-3", ":", "# update the value of distance computed", "if", "dff", ">", "0.", ":", "ras", "=", "ras", "-", "rx", "else", ":", "ras", "=", "ras", "+", "rx", "dff", "=", "fnc", "(", "ras", ",", "repi", ",", "theta", ",", "mag", ",", "coeff", ")", "rx", "=", "rx", "/", "2.", "if", "rx", "<", "1e-3", ":", "break", "return", "ras" ]
Computes equivalent distance :param repi: Epicentral distance :param theta: Azimuth value :param mag: Magnitude :param coeff: GMPE coefficients
[ "Computes", "equivalent", "distance" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/yu_2013.py#L122-L150
557
gem/oq-engine
openquake/hazardlib/gsim/shahjouei_pezeshk_2016.py
ShahjoueiPezeshk2016._get_stddevs
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: sigma_mean = self._compute_standard_dev(rup, imt, C) sigma_tot = np.sqrt((sigma_mean ** 2) + (C['SigmaReg'] ** 2)) sigma_tot = np.log10(np.exp(sigma_tot)) stddevs.append(sigma_tot + np.zeros(num_sites)) return stddevs
python
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: sigma_mean = self._compute_standard_dev(rup, imt, C) sigma_tot = np.sqrt((sigma_mean ** 2) + (C['SigmaReg'] ** 2)) sigma_tot = np.log10(np.exp(sigma_tot)) stddevs.append(sigma_tot + np.zeros(num_sites)) return stddevs
[ "def", "_get_stddevs", "(", "self", ",", "C", ",", "stddev_types", ",", "rup", ",", "imt", ",", "num_sites", ")", ":", "stddevs", "=", "[", "]", "for", "stddev_type", "in", "stddev_types", ":", "sigma_mean", "=", "self", ".", "_compute_standard_dev", "(", "rup", ",", "imt", ",", "C", ")", "sigma_tot", "=", "np", ".", "sqrt", "(", "(", "sigma_mean", "**", "2", ")", "+", "(", "C", "[", "'SigmaReg'", "]", "**", "2", ")", ")", "sigma_tot", "=", "np", ".", "log10", "(", "np", ".", "exp", "(", "sigma_tot", ")", ")", "stddevs", ".", "append", "(", "sigma_tot", "+", "np", ".", "zeros", "(", "num_sites", ")", ")", "return", "stddevs" ]
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
[ "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" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/shahjouei_pezeshk_2016.py#L103-L115
558
gem/oq-engine
openquake/hazardlib/gsim/shahjouei_pezeshk_2016.py
ShahjoueiPezeshk2016._compute_standard_dev
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 <= 6.5: sigma_mean = (C['c12'] * rup.mag) + C['c13'] elif rup.mag > 6.5: sigma_mean = (psi * rup.mag) + C['c14'] return sigma_mean
python
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 <= 6.5: sigma_mean = (C['c12'] * rup.mag) + C['c13'] elif rup.mag > 6.5: sigma_mean = (psi * rup.mag) + C['c14'] return sigma_mean
[ "def", "_compute_standard_dev", "(", "self", ",", "rup", ",", "imt", ",", "C", ")", ":", "sigma_mean", "=", "0.", "if", "imt", ".", "name", "in", "\"SA PGA\"", ":", "psi", "=", "-", "6.898E-3", "else", ":", "psi", "=", "-", "3.054E-5", "if", "rup", ".", "mag", "<=", "6.5", ":", "sigma_mean", "=", "(", "C", "[", "'c12'", "]", "*", "rup", ".", "mag", ")", "+", "C", "[", "'c13'", "]", "elif", "rup", ".", "mag", ">", "6.5", ":", "sigma_mean", "=", "(", "psi", "*", "rup", ".", "mag", ")", "+", "C", "[", "'c14'", "]", "return", "sigma_mean" ]
Compute the the standard deviation in terms of magnitude described on page 744, eq. 4
[ "Compute", "the", "the", "standard", "deviation", "in", "terms", "of", "magnitude", "described", "on", "page", "744", "eq", ".", "4" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/shahjouei_pezeshk_2016.py#L164-L178
559
gem/oq-engine
openquake/server/dbapi.py
Db.insert
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]) cursor.executemany(templ, rows) return cursor
python
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]) cursor.executemany(templ, rows) return cursor
[ "def", "insert", "(", "self", ",", "table", ",", "columns", ",", "rows", ")", ":", "cursor", "=", "self", ".", "conn", ".", "cursor", "(", ")", "if", "len", "(", "rows", ")", ":", "templ", ",", "_args", "=", "match", "(", "'INSERT INTO ?s (?S) VALUES (?X)'", ",", "table", ",", "columns", ",", "rows", "[", "0", "]", ")", "cursor", ".", "executemany", "(", "templ", ",", "rows", ")", "return", "cursor" ]
Insert several rows with executemany. Return a cursor.
[ "Insert", "several", "rows", "with", "executemany", ".", "Return", "a", "cursor", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/dbapi.py#L362-L371
560
gem/oq-engine
openquake/hazardlib/calc/hazard_curve.py
_cluster
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 occurrences for the cluster first = True for nocc in range(0, 50): # TODO fix this once the occurrence rate will be used just as # an object attribute ocr = tom.occurrence_rate prob_n_occ = tom.get_probability_n_occurrences(ocr, nocc) if first: pmapclu = prob_n_occ * (~pmap)**nocc first = False else: pmapclu += prob_n_occ * (~pmap)**nocc pmap = ~pmapclu return pmap
python
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 occurrences for the cluster first = True for nocc in range(0, 50): # TODO fix this once the occurrence rate will be used just as # an object attribute ocr = tom.occurrence_rate prob_n_occ = tom.get_probability_n_occurrences(ocr, nocc) if first: pmapclu = prob_n_occ * (~pmap)**nocc first = False else: pmapclu += prob_n_occ * (~pmap)**nocc pmap = ~pmapclu return pmap
[ "def", "_cluster", "(", "param", ",", "tom", ",", "imtls", ",", "gsims", ",", "grp_ids", ",", "pmap", ")", ":", "pmapclu", "=", "AccumDict", "(", "{", "grp_id", ":", "ProbabilityMap", "(", "len", "(", "imtls", ".", "array", ")", ",", "len", "(", "gsims", ")", ")", "for", "grp_id", "in", "grp_ids", "}", ")", "# Get temporal occurrence model", "# Number of occurrences for the cluster", "first", "=", "True", "for", "nocc", "in", "range", "(", "0", ",", "50", ")", ":", "# TODO fix this once the occurrence rate will be used just as", "# an object attribute", "ocr", "=", "tom", ".", "occurrence_rate", "prob_n_occ", "=", "tom", ".", "get_probability_n_occurrences", "(", "ocr", ",", "nocc", ")", "if", "first", ":", "pmapclu", "=", "prob_n_occ", "*", "(", "~", "pmap", ")", "**", "nocc", "first", "=", "False", "else", ":", "pmapclu", "+=", "prob_n_occ", "*", "(", "~", "pmap", ")", "**", "nocc", "pmap", "=", "~", "pmapclu", "return", "pmap" ]
Computes the probability map in case of a cluster group
[ "Computes", "the", "probability", "map", "in", "case", "of", "a", "cluster", "group" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/hazard_curve.py#L71-L91
561
gem/oq-engine
openquake/hazardlib/gsim/kale_2015.py
KaleEtAl2015Turkey._get_stddevs
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) stddevs = [] for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const.StdDev.TOTAL: stddevs.append(np.sqrt(std_intra ** 2. + std_inter ** 2.)) elif stddev_type == const.StdDev.INTRA_EVENT: stddevs.append(std_intra) elif stddev_type == const.StdDev.INTER_EVENT: stddevs.append(std_inter) return stddevs
python
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) stddevs = [] for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const.StdDev.TOTAL: stddevs.append(np.sqrt(std_intra ** 2. + std_inter ** 2.)) elif stddev_type == const.StdDev.INTRA_EVENT: stddevs.append(std_intra) elif stddev_type == const.StdDev.INTER_EVENT: stddevs.append(std_inter) return stddevs
[ "def", "_get_stddevs", "(", "self", ",", "C", ",", "rup", ",", "shape", ",", "stddev_types", ")", ":", "weight", "=", "self", ".", "_compute_weight_std", "(", "C", ",", "rup", ".", "mag", ")", "std_intra", "=", "weight", "*", "C", "[", "\"sd1\"", "]", "*", "np", ".", "ones", "(", "shape", ")", "std_inter", "=", "weight", "*", "C", "[", "\"sd2\"", "]", "*", "np", ".", "ones", "(", "shape", ")", "stddevs", "=", "[", "]", "for", "stddev_type", "in", "stddev_types", ":", "assert", "stddev_type", "in", "self", ".", "DEFINED_FOR_STANDARD_DEVIATION_TYPES", "if", "stddev_type", "==", "const", ".", "StdDev", ".", "TOTAL", ":", "stddevs", ".", "append", "(", "np", ".", "sqrt", "(", "std_intra", "**", "2.", "+", "std_inter", "**", "2.", ")", ")", "elif", "stddev_type", "==", "const", ".", "StdDev", ".", "INTRA_EVENT", ":", "stddevs", ".", "append", "(", "std_intra", ")", "elif", "stddev_type", "==", "const", ".", "StdDev", ".", "INTER_EVENT", ":", "stddevs", ".", "append", "(", "std_inter", ")", "return", "stddevs" ]
Return standard deviations as defined in p. 971.
[ "Return", "standard", "deviations", "as", "defined", "in", "p", ".", "971", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/kale_2015.py#L99-L116
562
gem/oq-engine
openquake/hazardlib/gsim/kale_2015.py
KaleEtAl2015Turkey._compute_weight_std
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['a2']
python
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['a2']
[ "def", "_compute_weight_std", "(", "self", ",", "C", ",", "mag", ")", ":", "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", "[", "'a2'", "]" ]
Common part of equations 8 and 9, page 971.
[ "Common", "part", "of", "equations", "8", "and", "9", "page", "971", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/kale_2015.py#L118-L127
563
gem/oq-engine
openquake/hazardlib/gsim/kale_2015.py
KaleEtAl2015Turkey._compute_magnitude_scaling_term
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: return C['b1'] + C['b7'] * (mag - c1) + C['b3'] * (8.5 - mag) ** 2
python
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: return C['b1'] + C['b7'] * (mag - c1) + C['b3'] * (8.5 - mag) ** 2
[ "def", "_compute_magnitude_scaling_term", "(", "self", ",", "C", ",", "mag", ")", ":", "c1", "=", "self", ".", "CONSTS", "[", "'c1'", "]", "if", "mag", "<=", "c1", ":", "return", "C", "[", "'b1'", "]", "+", "C", "[", "'b2'", "]", "*", "(", "mag", "-", "c1", ")", "+", "C", "[", "'b3'", "]", "*", "(", "8.5", "-", "mag", ")", "**", "2", "else", ":", "return", "C", "[", "'b1'", "]", "+", "C", "[", "'b7'", "]", "*", "(", "mag", "-", "c1", ")", "+", "C", "[", "'b3'", "]", "*", "(", "8.5", "-", "mag", ")", "**", "2" ]
Compute and return magnitude scaling term in equation 2, page 970.
[ "Compute", "and", "return", "magnitude", "scaling", "term", "in", "equation", "2", "page", "970", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/kale_2015.py#L129-L138
564
gem/oq-engine
openquake/hazardlib/gsim/kale_2015.py
KaleEtAl2015Turkey._compute_geometric_decay_term
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'] ** 2.0)) )
python
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'] ** 2.0)) )
[ "def", "_compute_geometric_decay_term", "(", "self", ",", "C", ",", "mag", ",", "dists", ")", ":", "c1", "=", "self", ".", "CONSTS", "[", "'c1'", "]", "return", "(", "(", "C", "[", "'b4'", "]", "+", "C", "[", "'b5'", "]", "*", "(", "mag", "-", "c1", ")", ")", "*", "np", ".", "log", "(", "np", ".", "sqrt", "(", "dists", ".", "rjb", "**", "2.0", "+", "C", "[", "'b6'", "]", "**", "2.0", ")", ")", ")" ]
Compute and return geometric decay term in equation 3, page 970.
[ "Compute", "and", "return", "geometric", "decay", "term", "in", "equation", "3", "page", "970", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/kale_2015.py#L140-L149
565
gem/oq-engine
openquake/hazardlib/gsim/kale_2015.py
KaleEtAl2015Turkey._compute_anelestic_attenuation_term
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_aat
python
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_aat
[ "def", "_compute_anelestic_attenuation_term", "(", "self", ",", "C", ",", "dists", ")", ":", "f_aat", "=", "np", ".", "zeros_like", "(", "dists", ".", "rjb", ")", "idx", "=", "dists", ".", "rjb", ">", "80.0", "f_aat", "[", "idx", "]", "=", "C", "[", "\"b10\"", "]", "*", "(", "dists", ".", "rjb", "[", "idx", "]", "-", "80.0", ")", "return", "f_aat" ]
Compute and return anelastic attenuation term in equation 5, page 970.
[ "Compute", "and", "return", "anelastic", "attenuation", "term", "in", "equation", "5", "page", "970", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/kale_2015.py#L161-L169
566
gem/oq-engine
openquake/hazardlib/gsim/kale_2015.py
KaleEtAl2015Turkey._compute_non_linear_term
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) # equation (6a) idx = sites.vs30 < Vref lnS[idx] = ( C['sb1'] * np.log(sites.vs30[idx] / Vref) + C['sb2'] * np.log( (pga_only[idx] + c * (sites.vs30[idx] / Vref) ** n) / ((pga_only[idx] + c) * (sites.vs30[idx] / Vref) ** n) ) ) # equation (6b) idx = sites.vs30 >= Vref new_sites = sites.vs30[idx] new_sites[new_sites > Vcon] = Vcon lnS[idx] = C['sb1'] * np.log(new_sites / Vref) return lnS
python
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) # equation (6a) idx = sites.vs30 < Vref lnS[idx] = ( C['sb1'] * np.log(sites.vs30[idx] / Vref) + C['sb2'] * np.log( (pga_only[idx] + c * (sites.vs30[idx] / Vref) ** n) / ((pga_only[idx] + c) * (sites.vs30[idx] / Vref) ** n) ) ) # equation (6b) idx = sites.vs30 >= Vref new_sites = sites.vs30[idx] new_sites[new_sites > Vcon] = Vcon lnS[idx] = C['sb1'] * np.log(new_sites / Vref) return lnS
[ "def", "_compute_non_linear_term", "(", "self", ",", "C", ",", "pga_only", ",", "sites", ")", ":", "Vref", "=", "self", ".", "CONSTS", "[", "'Vref'", "]", "Vcon", "=", "self", ".", "CONSTS", "[", "'Vcon'", "]", "c", "=", "self", ".", "CONSTS", "[", "'c'", "]", "n", "=", "self", ".", "CONSTS", "[", "'n'", "]", "lnS", "=", "np", ".", "zeros_like", "(", "sites", ".", "vs30", ")", "# equation (6a)\r", "idx", "=", "sites", ".", "vs30", "<", "Vref", "lnS", "[", "idx", "]", "=", "(", "C", "[", "'sb1'", "]", "*", "np", ".", "log", "(", "sites", ".", "vs30", "[", "idx", "]", "/", "Vref", ")", "+", "C", "[", "'sb2'", "]", "*", "np", ".", "log", "(", "(", "pga_only", "[", "idx", "]", "+", "c", "*", "(", "sites", ".", "vs30", "[", "idx", "]", "/", "Vref", ")", "**", "n", ")", "/", "(", "(", "pga_only", "[", "idx", "]", "+", "c", ")", "*", "(", "sites", ".", "vs30", "[", "idx", "]", "/", "Vref", ")", "**", "n", ")", ")", ")", "# equation (6b)\r", "idx", "=", "sites", ".", "vs30", ">=", "Vref", "new_sites", "=", "sites", ".", "vs30", "[", "idx", "]", "new_sites", "[", "new_sites", ">", "Vcon", "]", "=", "Vcon", "lnS", "[", "idx", "]", "=", "C", "[", "'sb1'", "]", "*", "np", ".", "log", "(", "new_sites", "/", "Vref", ")", "return", "lnS" ]
Compute non-linear term, equation 6, page 970.
[ "Compute", "non", "-", "linear", "term", "equation", "6", "page", "970", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/kale_2015.py#L171-L197
567
gem/oq-engine
openquake/hazardlib/gsim/kale_2015.py
KaleEtAl2015Turkey._compute_mean
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) + self._compute_faulting_style_term(C, rake) + self._compute_anelestic_attenuation_term(C, dists) ) return mean
python
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) + self._compute_faulting_style_term(C, rake) + self._compute_anelestic_attenuation_term(C, dists) ) return mean
[ "def", "_compute_mean", "(", "self", ",", "C", ",", "mag", ",", "dists", ",", "rake", ")", ":", "mean", "=", "(", "self", ".", "_compute_magnitude_scaling_term", "(", "C", ",", "mag", ")", "+", "self", ".", "_compute_geometric_decay_term", "(", "C", ",", "mag", ",", "dists", ")", "+", "self", ".", "_compute_faulting_style_term", "(", "C", ",", "rake", ")", "+", "self", ".", "_compute_anelestic_attenuation_term", "(", "C", ",", "dists", ")", ")", "return", "mean" ]
Compute and return mean value without site conditions, that is equations 2-5, page 970.
[ "Compute", "and", "return", "mean", "value", "without", "site", "conditions", "that", "is", "equations", "2", "-", "5", "page", "970", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/kale_2015.py#L199-L211
568
gem/oq-engine
openquake/hazardlib/source/multi.py
MultiPointSource.get_bounding_box
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)
python
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", "get_bounding_box", "(", "self", ",", "maxdist", ")", ":", "return", "utils", ".", "get_bounding_box", "(", "[", "ps", ".", "location", "for", "ps", "in", "self", "]", ",", "maxdist", ")" ]
Bounding box containing all the point sources, enlarged by the maximum distance.
[ "Bounding", "box", "containing", "all", "the", "point", "sources", "enlarged", "by", "the", "maximum", "distance", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/source/multi.py#L109-L114
569
gem/oq-engine
openquake/hazardlib/gsim/pezeshk_2011.py
PezeshkEtAl2011._compute_standard_dev
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: sigma_mean = (-0.00695 * rup.mag) + C['c14'] return sigma_mean
python
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: sigma_mean = (-0.00695 * rup.mag) + C['c14'] return sigma_mean
[ "def", "_compute_standard_dev", "(", "self", ",", "rup", ",", "imt", ",", "C", ")", ":", "sigma_mean", "=", "0.", "if", "rup", ".", "mag", "<=", "7.0", ":", "sigma_mean", "=", "(", "C", "[", "'c12'", "]", "*", "rup", ".", "mag", ")", "+", "C", "[", "'c13'", "]", "elif", "rup", ".", "mag", ">", "7.0", ":", "sigma_mean", "=", "(", "-", "0.00695", "*", "rup", ".", "mag", ")", "+", "C", "[", "'c14'", "]", "return", "sigma_mean" ]
Compute the the standard deviation in terms of magnitude described on p. 1866, eq. 6
[ "Compute", "the", "the", "standard", "deviation", "in", "terms", "of", "magnitude", "described", "on", "p", ".", "1866", "eq", ".", "6" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/pezeshk_2011.py#L158-L168
570
gem/oq-engine
openquake/hmtk/strain/shift.py
Shift.get_rate_osr_normal_transform
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: Logical vector indicating the cells to which this condition applies :returns: Activity rates for cells corresponding to the hybrid ocean spreading ridge and oceanic transform condition ''' # Get normal component e1h_ridge = np.zeros(np.sum(id0), dtype=float) e2h_ridge = self.strain.data['e1h'][id0] + self.strain.data['e2h'][id0] err_ridge = -(e1h_ridge + e2h_ridge) calculated_rate_ridge = self.continuum_seismicity( threshold_moment, e1h_ridge, e2h_ridge, err_ridge, self.regionalisation['OSRnor']) # Get transform e1h_trans = self.strain.data['e1h'][id0] e2h_trans = -e1h_trans err_trans = np.zeros(np.sum(id0), dtype=float) calculated_rate_transform = self.continuum_seismicity( threshold_moment, e1h_trans, e2h_trans, err_trans, self.regionalisation['OTFmed']) return ( self.regionalisation['OSRnor']['adjustment_factor'] * (calculated_rate_ridge + calculated_rate_transform))
python
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: Logical vector indicating the cells to which this condition applies :returns: Activity rates for cells corresponding to the hybrid ocean spreading ridge and oceanic transform condition ''' # Get normal component e1h_ridge = np.zeros(np.sum(id0), dtype=float) e2h_ridge = self.strain.data['e1h'][id0] + self.strain.data['e2h'][id0] err_ridge = -(e1h_ridge + e2h_ridge) calculated_rate_ridge = self.continuum_seismicity( threshold_moment, e1h_ridge, e2h_ridge, err_ridge, self.regionalisation['OSRnor']) # Get transform e1h_trans = self.strain.data['e1h'][id0] e2h_trans = -e1h_trans err_trans = np.zeros(np.sum(id0), dtype=float) calculated_rate_transform = self.continuum_seismicity( threshold_moment, e1h_trans, e2h_trans, err_trans, self.regionalisation['OTFmed']) return ( self.regionalisation['OSRnor']['adjustment_factor'] * (calculated_rate_ridge + calculated_rate_transform))
[ "def", "get_rate_osr_normal_transform", "(", "self", ",", "threshold_moment", ",", "id0", ")", ":", "# Get normal component", "e1h_ridge", "=", "np", ".", "zeros", "(", "np", ".", "sum", "(", "id0", ")", ",", "dtype", "=", "float", ")", "e2h_ridge", "=", "self", ".", "strain", ".", "data", "[", "'e1h'", "]", "[", "id0", "]", "+", "self", ".", "strain", ".", "data", "[", "'e2h'", "]", "[", "id0", "]", "err_ridge", "=", "-", "(", "e1h_ridge", "+", "e2h_ridge", ")", "calculated_rate_ridge", "=", "self", ".", "continuum_seismicity", "(", "threshold_moment", ",", "e1h_ridge", ",", "e2h_ridge", ",", "err_ridge", ",", "self", ".", "regionalisation", "[", "'OSRnor'", "]", ")", "# Get transform", "e1h_trans", "=", "self", ".", "strain", ".", "data", "[", "'e1h'", "]", "[", "id0", "]", "e2h_trans", "=", "-", "e1h_trans", "err_trans", "=", "np", ".", "zeros", "(", "np", ".", "sum", "(", "id0", ")", ",", "dtype", "=", "float", ")", "calculated_rate_transform", "=", "self", ".", "continuum_seismicity", "(", "threshold_moment", ",", "e1h_trans", ",", "e2h_trans", ",", "err_trans", ",", "self", ".", "regionalisation", "[", "'OTFmed'", "]", ")", "return", "(", "self", ".", "regionalisation", "[", "'OSRnor'", "]", "[", "'adjustment_factor'", "]", "*", "(", "calculated_rate_ridge", "+", "calculated_rate_transform", ")", ")" ]
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: Logical vector indicating the cells to which this condition applies :returns: Activity rates for cells corresponding to the hybrid ocean spreading ridge and oceanic transform condition
[ "Gets", "seismicity", "rate", "for", "special", "case", "of", "the", "ridge", "condition", "with", "spreading", "and", "transform", "component" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/strain/shift.py#L369-L411
571
gem/oq-engine
openquake/hmtk/strain/shift.py
Shift.get_rate_osr_convergent_transform
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 id0: Logical vector indicating the cells to which this condition applies :returns: Activity rates for cells corresponding to the hybrid ocean convergent boundary and oceanic transform condition ''' # Get convergent component e1h_ocb = self.strain.data['e1h'][id0] + self.strain.data['e2h'][id0] e2h_ocb = np.zeros(np.sum(id0), dtype=float) err_ocb = -(e1h_ocb + e2h_ocb) calculated_rate_ocb = self.continuum_seismicity( threshold_moment, e1h_ocb, e2h_ocb, err_ocb, self.regionalisation['OCB']) # Get transform e2h_trans = self.strain.data['e2h'][id0] e1h_trans = -e2h_trans err_trans = np.zeros(np.sum(id0), dtype=float) calculated_rate_transform = self.continuum_seismicity( threshold_moment, e1h_trans, e2h_trans, err_trans, self.regionalisation['OTFmed']) return (self.regionalisation['OSRnor']['adjustment_factor'] * (calculated_rate_ocb + calculated_rate_transform))
python
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 id0: Logical vector indicating the cells to which this condition applies :returns: Activity rates for cells corresponding to the hybrid ocean convergent boundary and oceanic transform condition ''' # Get convergent component e1h_ocb = self.strain.data['e1h'][id0] + self.strain.data['e2h'][id0] e2h_ocb = np.zeros(np.sum(id0), dtype=float) err_ocb = -(e1h_ocb + e2h_ocb) calculated_rate_ocb = self.continuum_seismicity( threshold_moment, e1h_ocb, e2h_ocb, err_ocb, self.regionalisation['OCB']) # Get transform e2h_trans = self.strain.data['e2h'][id0] e1h_trans = -e2h_trans err_trans = np.zeros(np.sum(id0), dtype=float) calculated_rate_transform = self.continuum_seismicity( threshold_moment, e1h_trans, e2h_trans, err_trans, self.regionalisation['OTFmed']) return (self.regionalisation['OSRnor']['adjustment_factor'] * (calculated_rate_ocb + calculated_rate_transform))
[ "def", "get_rate_osr_convergent_transform", "(", "self", ",", "threshold_moment", ",", "id0", ")", ":", "# Get convergent component", "e1h_ocb", "=", "self", ".", "strain", ".", "data", "[", "'e1h'", "]", "[", "id0", "]", "+", "self", ".", "strain", ".", "data", "[", "'e2h'", "]", "[", "id0", "]", "e2h_ocb", "=", "np", ".", "zeros", "(", "np", ".", "sum", "(", "id0", ")", ",", "dtype", "=", "float", ")", "err_ocb", "=", "-", "(", "e1h_ocb", "+", "e2h_ocb", ")", "calculated_rate_ocb", "=", "self", ".", "continuum_seismicity", "(", "threshold_moment", ",", "e1h_ocb", ",", "e2h_ocb", ",", "err_ocb", ",", "self", ".", "regionalisation", "[", "'OCB'", "]", ")", "# Get transform", "e2h_trans", "=", "self", ".", "strain", ".", "data", "[", "'e2h'", "]", "[", "id0", "]", "e1h_trans", "=", "-", "e2h_trans", "err_trans", "=", "np", ".", "zeros", "(", "np", ".", "sum", "(", "id0", ")", ",", "dtype", "=", "float", ")", "calculated_rate_transform", "=", "self", ".", "continuum_seismicity", "(", "threshold_moment", ",", "e1h_trans", ",", "e2h_trans", ",", "err_trans", ",", "self", ".", "regionalisation", "[", "'OTFmed'", "]", ")", "return", "(", "self", ".", "regionalisation", "[", "'OSRnor'", "]", "[", "'adjustment_factor'", "]", "*", "(", "calculated_rate_ocb", "+", "calculated_rate_transform", ")", ")" ]
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 id0: Logical vector indicating the cells to which this condition applies :returns: Activity rates for cells corresponding to the hybrid ocean convergent boundary and oceanic transform condition
[ "Calculates", "seismicity", "rate", "for", "special", "case", "of", "the", "ridge", "condition", "with", "convergence", "and", "transform" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/strain/shift.py#L413-L453
572
gem/oq-engine
openquake/hazardlib/scalerel/leonard2014.py
Leonard2014_SCR.get_median_area
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): # strike-slip return power(10.0, (mag - 4.18)) else: # Dip-slip (thrust or normal), and undefined rake return power(10.0, (mag - 4.19))
python
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): # strike-slip return power(10.0, (mag - 4.18)) else: # Dip-slip (thrust or normal), and undefined rake return power(10.0, (mag - 4.19))
[ "def", "get_median_area", "(", "self", ",", "mag", ",", "rake", ")", ":", "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", ")", ":", "# strike-slip", "return", "power", "(", "10.0", ",", "(", "mag", "-", "4.18", ")", ")", "else", ":", "# Dip-slip (thrust or normal), and undefined rake", "return", "power", "(", "10.0", ",", "(", "mag", "-", "4.19", ")", ")" ]
Calculates median fault area from magnitude.
[ "Calculates", "median", "fault", "area", "from", "magnitude", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/scalerel/leonard2014.py#L36-L48
573
gem/oq-engine
openquake/server/views.py
_get_base_url
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(): base_url = 'https://%s' else: base_url = 'http://%s' base_url %= request.META['HTTP_HOST'] return base_url
python
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(): base_url = 'https://%s' else: base_url = 'http://%s' base_url %= request.META['HTTP_HOST'] return base_url
[ "def", "_get_base_url", "(", "request", ")", ":", "if", "request", ".", "is_secure", "(", ")", ":", "base_url", "=", "'https://%s'", "else", ":", "base_url", "=", "'http://%s'", "base_url", "%=", "request", ".", "META", "[", "'HTTP_HOST'", "]", "return", "base_url" ]
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.
[ "Construct", "a", "base", "URL", "given", "a", "request", "object", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L108-L121
574
gem/oq-engine
openquake/server/views.py
_prepare_job
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 arch is None: # move each file to a new temp dir, using the upload file names, # not the temporary ones for each_file in request.FILES.values(): new_path = os.path.join(temp_dir, each_file.name) shutil.move(each_file.temporary_file_path(), new_path) if each_file.name in candidates: inifiles.append(new_path) return inifiles # else extract the files from the archive into temp_dir return readinput.extract_from_zip(arch, candidates)
python
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 arch is None: # move each file to a new temp dir, using the upload file names, # not the temporary ones for each_file in request.FILES.values(): new_path = os.path.join(temp_dir, each_file.name) shutil.move(each_file.temporary_file_path(), new_path) if each_file.name in candidates: inifiles.append(new_path) return inifiles # else extract the files from the archive into temp_dir return readinput.extract_from_zip(arch, candidates)
[ "def", "_prepare_job", "(", "request", ",", "candidates", ")", ":", "temp_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "inifiles", "=", "[", "]", "arch", "=", "request", ".", "FILES", ".", "get", "(", "'archive'", ")", "if", "arch", "is", "None", ":", "# move each file to a new temp dir, using the upload file names,", "# not the temporary ones", "for", "each_file", "in", "request", ".", "FILES", ".", "values", "(", ")", ":", "new_path", "=", "os", ".", "path", ".", "join", "(", "temp_dir", ",", "each_file", ".", "name", ")", "shutil", ".", "move", "(", "each_file", ".", "temporary_file_path", "(", ")", ",", "new_path", ")", "if", "each_file", ".", "name", "in", "candidates", ":", "inifiles", ".", "append", "(", "new_path", ")", "return", "inifiles", "# else extract the files from the archive into temp_dir", "return", "readinput", ".", "extract_from_zip", "(", "arch", ",", "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
[ "Creates", "a", "temporary", "directory", "move", "uploaded", "files", "there", "and", "select", "the", "job", "file", "by", "looking", "at", "the", "candidate", "names", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L124-L144
575
gem/oq-engine
openquake/server/views.py
ajax_login
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(username=username, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponse(content='Successful login', content_type='text/plain', status=200) else: return HttpResponse(content='Disabled account', content_type='text/plain', status=403) else: return HttpResponse(content='Invalid login', content_type='text/plain', status=403)
python
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(username=username, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponse(content='Successful login', content_type='text/plain', status=200) else: return HttpResponse(content='Disabled account', content_type='text/plain', status=403) else: return HttpResponse(content='Invalid login', content_type='text/plain', status=403)
[ "def", "ajax_login", "(", "request", ")", ":", "username", "=", "request", ".", "POST", "[", "'username'", "]", "password", "=", "request", ".", "POST", "[", "'password'", "]", "user", "=", "authenticate", "(", "username", "=", "username", ",", "password", "=", "password", ")", "if", "user", "is", "not", "None", ":", "if", "user", ".", "is_active", ":", "login", "(", "request", ",", "user", ")", "return", "HttpResponse", "(", "content", "=", "'Successful login'", ",", "content_type", "=", "'text/plain'", ",", "status", "=", "200", ")", "else", ":", "return", "HttpResponse", "(", "content", "=", "'Disabled account'", ",", "content_type", "=", "'text/plain'", ",", "status", "=", "403", ")", "else", ":", "return", "HttpResponse", "(", "content", "=", "'Invalid login'", ",", "content_type", "=", "'text/plain'", ",", "status", "=", "403", ")" ]
Accept a POST request to login. :param request: `django.http.HttpRequest` object, containing mandatory parameters username and password required.
[ "Accept", "a", "POST", "request", "to", "login", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L150-L171
576
gem/oq-engine
openquake/server/views.py
get_available_gsims
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)
python
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", "get_available_gsims", "(", "request", ")", ":", "gsims", "=", "list", "(", "gsim", ".", "get_available_gsims", "(", ")", ")", "return", "HttpResponse", "(", "content", "=", "json", ".", "dumps", "(", "gsims", ")", ",", "content_type", "=", "JSON", ")" ]
Return a list of strings with the available GSIMs
[ "Return", "a", "list", "of", "strings", "with", "the", "available", "GSIMs" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L207-L212
577
gem/oq-engine
openquake/server/views.py
validate_nrml
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: * 'valid': a boolean indicating if the provided text is a valid NRML * 'error_msg': the error message, if any error was found (None otherwise) * 'error_line': line of the given XML where the error was found (None if no error was found or if it was not a validation error) """ xml_text = request.POST.get('xml_text') if not xml_text: return HttpResponseBadRequest( 'Please provide the "xml_text" parameter') xml_file = gettemp(xml_text, suffix='.xml') try: nrml.to_python(xml_file) except ExpatError as exc: return _make_response(error_msg=str(exc), error_line=exc.lineno, valid=False) except Exception as exc: # get the exception message exc_msg = exc.args[0] if isinstance(exc_msg, bytes): exc_msg = exc_msg.decode('utf-8') # make it a unicode object elif isinstance(exc_msg, str): pass else: # if it is another kind of object, it is not obvious a priori how # to extract the error line from it return _make_response( error_msg=str(exc_msg), error_line=None, valid=False) # if the line is not mentioned, the whole message is taken error_msg = exc_msg.split(', line')[0] # check if the exc_msg contains a line number indication search_match = re.search(r'line \d+', exc_msg) if search_match: error_line = int(search_match.group(0).split()[1]) else: error_line = None return _make_response( error_msg=error_msg, error_line=error_line, valid=False) else: return _make_response(error_msg=None, error_line=None, valid=True)
python
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: * 'valid': a boolean indicating if the provided text is a valid NRML * 'error_msg': the error message, if any error was found (None otherwise) * 'error_line': line of the given XML where the error was found (None if no error was found or if it was not a validation error) """ xml_text = request.POST.get('xml_text') if not xml_text: return HttpResponseBadRequest( 'Please provide the "xml_text" parameter') xml_file = gettemp(xml_text, suffix='.xml') try: nrml.to_python(xml_file) except ExpatError as exc: return _make_response(error_msg=str(exc), error_line=exc.lineno, valid=False) except Exception as exc: # get the exception message exc_msg = exc.args[0] if isinstance(exc_msg, bytes): exc_msg = exc_msg.decode('utf-8') # make it a unicode object elif isinstance(exc_msg, str): pass else: # if it is another kind of object, it is not obvious a priori how # to extract the error line from it return _make_response( error_msg=str(exc_msg), error_line=None, valid=False) # if the line is not mentioned, the whole message is taken error_msg = exc_msg.split(', line')[0] # check if the exc_msg contains a line number indication search_match = re.search(r'line \d+', exc_msg) if search_match: error_line = int(search_match.group(0).split()[1]) else: error_line = None return _make_response( error_msg=error_msg, error_line=error_line, valid=False) else: return _make_response(error_msg=None, error_line=None, valid=True)
[ "def", "validate_nrml", "(", "request", ")", ":", "xml_text", "=", "request", ".", "POST", ".", "get", "(", "'xml_text'", ")", "if", "not", "xml_text", ":", "return", "HttpResponseBadRequest", "(", "'Please provide the \"xml_text\" parameter'", ")", "xml_file", "=", "gettemp", "(", "xml_text", ",", "suffix", "=", "'.xml'", ")", "try", ":", "nrml", ".", "to_python", "(", "xml_file", ")", "except", "ExpatError", "as", "exc", ":", "return", "_make_response", "(", "error_msg", "=", "str", "(", "exc", ")", ",", "error_line", "=", "exc", ".", "lineno", ",", "valid", "=", "False", ")", "except", "Exception", "as", "exc", ":", "# get the exception message", "exc_msg", "=", "exc", ".", "args", "[", "0", "]", "if", "isinstance", "(", "exc_msg", ",", "bytes", ")", ":", "exc_msg", "=", "exc_msg", ".", "decode", "(", "'utf-8'", ")", "# make it a unicode object", "elif", "isinstance", "(", "exc_msg", ",", "str", ")", ":", "pass", "else", ":", "# if it is another kind of object, it is not obvious a priori how", "# to extract the error line from it", "return", "_make_response", "(", "error_msg", "=", "str", "(", "exc_msg", ")", ",", "error_line", "=", "None", ",", "valid", "=", "False", ")", "# if the line is not mentioned, the whole message is taken", "error_msg", "=", "exc_msg", ".", "split", "(", "', line'", ")", "[", "0", "]", "# check if the exc_msg contains a line number indication", "search_match", "=", "re", ".", "search", "(", "r'line \\d+'", ",", "exc_msg", ")", "if", "search_match", ":", "error_line", "=", "int", "(", "search_match", ".", "group", "(", "0", ")", ".", "split", "(", ")", "[", "1", "]", ")", "else", ":", "error_line", "=", "None", "return", "_make_response", "(", "error_msg", "=", "error_msg", ",", "error_line", "=", "error_line", ",", "valid", "=", "False", ")", "else", ":", "return", "_make_response", "(", "error_msg", "=", "None", ",", "error_line", "=", "None", ",", "valid", "=", "True", ")" ]
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: * 'valid': a boolean indicating if the provided text is a valid NRML * 'error_msg': the error message, if any error was found (None otherwise) * 'error_line': line of the given XML where the error was found (None if no error was found or if it was not a validation error)
[ "Leverage", "oq", "-", "risklib", "to", "check", "if", "a", "given", "XML", "text", "is", "a", "valid", "NRML" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L226-L276
578
gem/oq-engine
openquake/server/views.py
calc_list
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 the Javascript. Responses are in JSON. """ base_url = _get_base_url(request) calc_data = logs.dbcmd('get_calcs', request.GET, utils.get_valid_users(request), utils.get_acl_on(request), id) response_data = [] username = psutil.Process(os.getpid()).username() for (hc_id, owner, status, calculation_mode, is_running, desc, pid, parent_id, size_mb) in calc_data: url = urlparse.urljoin(base_url, 'v1/calc/%d' % hc_id) abortable = False if is_running: try: if psutil.Process(pid).username() == username: abortable = True except psutil.NoSuchProcess: pass response_data.append( dict(id=hc_id, owner=owner, calculation_mode=calculation_mode, status=status, is_running=bool(is_running), description=desc, url=url, parent_id=parent_id, abortable=abortable, size_mb=size_mb)) # if id is specified the related dictionary is returned instead the list if id is not None: [response_data] = response_data return HttpResponse(content=json.dumps(response_data), content_type=JSON)
python
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 the Javascript. Responses are in JSON. """ base_url = _get_base_url(request) calc_data = logs.dbcmd('get_calcs', request.GET, utils.get_valid_users(request), utils.get_acl_on(request), id) response_data = [] username = psutil.Process(os.getpid()).username() for (hc_id, owner, status, calculation_mode, is_running, desc, pid, parent_id, size_mb) in calc_data: url = urlparse.urljoin(base_url, 'v1/calc/%d' % hc_id) abortable = False if is_running: try: if psutil.Process(pid).username() == username: abortable = True except psutil.NoSuchProcess: pass response_data.append( dict(id=hc_id, owner=owner, calculation_mode=calculation_mode, status=status, is_running=bool(is_running), description=desc, url=url, parent_id=parent_id, abortable=abortable, size_mb=size_mb)) # if id is specified the related dictionary is returned instead the list if id is not None: [response_data] = response_data return HttpResponse(content=json.dumps(response_data), content_type=JSON)
[ "def", "calc_list", "(", "request", ",", "id", "=", "None", ")", ":", "# view associated to the endpoints /v1/calc/list and /v1/calc/:id/status", "base_url", "=", "_get_base_url", "(", "request", ")", "calc_data", "=", "logs", ".", "dbcmd", "(", "'get_calcs'", ",", "request", ".", "GET", ",", "utils", ".", "get_valid_users", "(", "request", ")", ",", "utils", ".", "get_acl_on", "(", "request", ")", ",", "id", ")", "response_data", "=", "[", "]", "username", "=", "psutil", ".", "Process", "(", "os", ".", "getpid", "(", ")", ")", ".", "username", "(", ")", "for", "(", "hc_id", ",", "owner", ",", "status", ",", "calculation_mode", ",", "is_running", ",", "desc", ",", "pid", ",", "parent_id", ",", "size_mb", ")", "in", "calc_data", ":", "url", "=", "urlparse", ".", "urljoin", "(", "base_url", ",", "'v1/calc/%d'", "%", "hc_id", ")", "abortable", "=", "False", "if", "is_running", ":", "try", ":", "if", "psutil", ".", "Process", "(", "pid", ")", ".", "username", "(", ")", "==", "username", ":", "abortable", "=", "True", "except", "psutil", ".", "NoSuchProcess", ":", "pass", "response_data", ".", "append", "(", "dict", "(", "id", "=", "hc_id", ",", "owner", "=", "owner", ",", "calculation_mode", "=", "calculation_mode", ",", "status", "=", "status", ",", "is_running", "=", "bool", "(", "is_running", ")", ",", "description", "=", "desc", ",", "url", "=", "url", ",", "parent_id", "=", "parent_id", ",", "abortable", "=", "abortable", ",", "size_mb", "=", "size_mb", ")", ")", "# if id is specified the related dictionary is returned instead the list", "if", "id", "is", "not", "None", ":", "[", "response_data", "]", "=", "response_data", "return", "HttpResponse", "(", "content", "=", "json", ".", "dumps", "(", "response_data", ")", ",", "content_type", "=", "JSON", ")" ]
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 the Javascript. Responses are in JSON.
[ "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", "the", "Javascript", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L298-L335
579
gem/oq-engine
openquake/server/views.py
calc_abort
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 ('submitted', 'executing'): message = {'error': 'Job %s is not running' % job.id} return HttpResponse(content=json.dumps(message), content_type=JSON) if not utils.user_has_permission(request, job.user_name): message = {'error': ('User %s has no permission to abort job %s' % (job.user_name, job.id))} return HttpResponse(content=json.dumps(message), content_type=JSON, status=403) if job.pid: # is a spawned job try: os.kill(job.pid, signal.SIGTERM) except Exception as exc: logging.error(exc) else: logging.warning('Aborting job %d, pid=%d', job.id, job.pid) logs.dbcmd('set_status', job.id, 'aborted') message = {'success': 'Killing job %d' % job.id} return HttpResponse(content=json.dumps(message), content_type=JSON) message = {'error': 'PID for job %s not found' % job.id} return HttpResponse(content=json.dumps(message), content_type=JSON)
python
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 ('submitted', 'executing'): message = {'error': 'Job %s is not running' % job.id} return HttpResponse(content=json.dumps(message), content_type=JSON) if not utils.user_has_permission(request, job.user_name): message = {'error': ('User %s has no permission to abort job %s' % (job.user_name, job.id))} return HttpResponse(content=json.dumps(message), content_type=JSON, status=403) if job.pid: # is a spawned job try: os.kill(job.pid, signal.SIGTERM) except Exception as exc: logging.error(exc) else: logging.warning('Aborting job %d, pid=%d', job.id, job.pid) logs.dbcmd('set_status', job.id, 'aborted') message = {'success': 'Killing job %d' % job.id} return HttpResponse(content=json.dumps(message), content_type=JSON) message = {'error': 'PID for job %s not found' % job.id} return HttpResponse(content=json.dumps(message), content_type=JSON)
[ "def", "calc_abort", "(", "request", ",", "calc_id", ")", ":", "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", "(", "'submitted'", ",", "'executing'", ")", ":", "message", "=", "{", "'error'", ":", "'Job %s is not running'", "%", "job", ".", "id", "}", "return", "HttpResponse", "(", "content", "=", "json", ".", "dumps", "(", "message", ")", ",", "content_type", "=", "JSON", ")", "if", "not", "utils", ".", "user_has_permission", "(", "request", ",", "job", ".", "user_name", ")", ":", "message", "=", "{", "'error'", ":", "(", "'User %s has no permission to abort job %s'", "%", "(", "job", ".", "user_name", ",", "job", ".", "id", ")", ")", "}", "return", "HttpResponse", "(", "content", "=", "json", ".", "dumps", "(", "message", ")", ",", "content_type", "=", "JSON", ",", "status", "=", "403", ")", "if", "job", ".", "pid", ":", "# is a spawned job", "try", ":", "os", ".", "kill", "(", "job", ".", "pid", ",", "signal", ".", "SIGTERM", ")", "except", "Exception", "as", "exc", ":", "logging", ".", "error", "(", "exc", ")", "else", ":", "logging", ".", "warning", "(", "'Aborting job %d, pid=%d'", ",", "job", ".", "id", ",", "job", ".", "pid", ")", "logs", ".", "dbcmd", "(", "'set_status'", ",", "job", ".", "id", ",", "'aborted'", ")", "message", "=", "{", "'success'", ":", "'Killing job %d'", "%", "job", ".", "id", "}", "return", "HttpResponse", "(", "content", "=", "json", ".", "dumps", "(", "message", ")", ",", "content_type", "=", "JSON", ")", "message", "=", "{", "'error'", ":", "'PID for job %s not found'", "%", "job", ".", "id", "}", "return", "HttpResponse", "(", "content", "=", "json", ".", "dumps", "(", "message", ")", ",", "content_type", "=", "JSON", ")" ]
Abort the given calculation, it is it running
[ "Abort", "the", "given", "calculation", "it", "is", "it", "running" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L341-L372
580
gem/oq-engine
openquake/server/views.py
calc_remove
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: return HttpResponse(content=json.dumps(message), content_type=JSON, status=200) elif 'error' in message: logging.error(message['error']) return HttpResponse(content=json.dumps(message), content_type=JSON, status=403) else: # This is an untrapped server error logging.error(message) return HttpResponse(content=message, content_type='text/plain', status=500)
python
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: return HttpResponse(content=json.dumps(message), content_type=JSON, status=200) elif 'error' in message: logging.error(message['error']) return HttpResponse(content=json.dumps(message), content_type=JSON, status=403) else: # This is an untrapped server error logging.error(message) return HttpResponse(content=message, content_type='text/plain', status=500)
[ "def", "calc_remove", "(", "request", ",", "calc_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", ":", "return", "HttpResponse", "(", "content", "=", "json", ".", "dumps", "(", "message", ")", ",", "content_type", "=", "JSON", ",", "status", "=", "200", ")", "elif", "'error'", "in", "message", ":", "logging", ".", "error", "(", "message", "[", "'error'", "]", ")", "return", "HttpResponse", "(", "content", "=", "json", ".", "dumps", "(", "message", ")", ",", "content_type", "=", "JSON", ",", "status", "=", "403", ")", "else", ":", "# This is an untrapped server error", "logging", ".", "error", "(", "message", ")", "return", "HttpResponse", "(", "content", "=", "message", ",", "content_type", "=", "'text/plain'", ",", "status", "=", "500", ")" ]
Remove the calculation id
[ "Remove", "the", "calculation", "id" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L378-L400
581
gem/oq-engine
openquake/server/views.py
log_to_json
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]
python
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", "log_to_json", "(", "log", ")", ":", "return", "[", "log", ".", "timestamp", ".", "isoformat", "(", ")", "[", ":", "22", "]", ",", "log", ".", "level", ",", "log", ".", "process", ",", "log", ".", "message", "]" ]
Convert a log record into a list of strings
[ "Convert", "a", "log", "record", "into", "a", "list", "of", "strings" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L403-L406
582
gem/oq-engine
openquake/server/views.py
calc_log_size
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)
python
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_log_size", "(", "request", ",", "calc_id", ")", ":", "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", ")" ]
Get the current number of lines in the log
[ "Get", "the", "current", "number", "of", "lines", "in", "the", "log" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L426-L434
583
gem/oq-engine
openquake/server/views.py
submit_job
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_id=hazard_job_id) pik = pickle.dumps(oq, protocol=0) # human readable protocol code = RUNCALC % dict(job_id=job_id, hazard_job_id=hazard_job_id, pik=pik, username=username) tmp_py = gettemp(code, suffix='.py') # print(code, tmp_py) # useful when debugging devnull = subprocess.DEVNULL popen = subprocess.Popen([sys.executable, tmp_py], stdin=devnull, stdout=devnull, stderr=devnull) threading.Thread(target=popen.wait).start() logs.dbcmd('update_job', job_id, {'pid': popen.pid}) return job_id, popen.pid
python
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_id=hazard_job_id) pik = pickle.dumps(oq, protocol=0) # human readable protocol code = RUNCALC % dict(job_id=job_id, hazard_job_id=hazard_job_id, pik=pik, username=username) tmp_py = gettemp(code, suffix='.py') # print(code, tmp_py) # useful when debugging devnull = subprocess.DEVNULL popen = subprocess.Popen([sys.executable, tmp_py], stdin=devnull, stdout=devnull, stderr=devnull) threading.Thread(target=popen.wait).start() logs.dbcmd('update_job', job_id, {'pid': popen.pid}) return job_id, popen.pid
[ "def", "submit_job", "(", "job_ini", ",", "username", ",", "hazard_job_id", "=", "None", ")", ":", "job_id", "=", "logs", ".", "init", "(", "'job'", ")", "oq", "=", "engine", ".", "job_from_file", "(", "job_ini", ",", "job_id", ",", "username", ",", "hazard_calculation_id", "=", "hazard_job_id", ")", "pik", "=", "pickle", ".", "dumps", "(", "oq", ",", "protocol", "=", "0", ")", "# human readable protocol", "code", "=", "RUNCALC", "%", "dict", "(", "job_id", "=", "job_id", ",", "hazard_job_id", "=", "hazard_job_id", ",", "pik", "=", "pik", ",", "username", "=", "username", ")", "tmp_py", "=", "gettemp", "(", "code", ",", "suffix", "=", "'.py'", ")", "# print(code, tmp_py) # useful when debugging", "devnull", "=", "subprocess", ".", "DEVNULL", "popen", "=", "subprocess", ".", "Popen", "(", "[", "sys", ".", "executable", ",", "tmp_py", "]", ",", "stdin", "=", "devnull", ",", "stdout", "=", "devnull", ",", "stderr", "=", "devnull", ")", "threading", ".", "Thread", "(", "target", "=", "popen", ".", "wait", ")", ".", "start", "(", ")", "logs", ".", "dbcmd", "(", "'update_job'", ",", "job_id", ",", "{", "'pid'", ":", "popen", ".", "pid", "}", ")", "return", "job_id", ",", "popen", ".", "pid" ]
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.
[ "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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L502-L520
584
gem/oq-engine
openquake/server/views.py
calc_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 specified). :param result_id: The id of the requested artifact. :returns: If the requested ``result_id`` is not available in the format designated by the `export_type`. Otherwise, return a `django.http.HttpResponse` containing the content of the requested artifact. Parameters for the GET request can include an `export_type`, such as 'xml', 'geojson', 'csv', etc. """ # If the result for the requested ID doesn't exist, OR # the job which it is related too is not complete, # throw back a 404. try: job_id, job_status, job_user, datadir, ds_key = logs.dbcmd( 'get_result', result_id) if not utils.user_has_permission(request, job_user): return HttpResponseForbidden() except dbapi.NotFound: return HttpResponseNotFound() etype = request.GET.get('export_type') export_type = etype or DEFAULT_EXPORT_TYPE tmpdir = tempfile.mkdtemp() try: exported = core.export_from_db( (ds_key, export_type), job_id, datadir, tmpdir) except DataStoreExportError as exc: # TODO: there should be a better error page return HttpResponse(content='%s: %s' % (exc.__class__.__name__, exc), content_type='text/plain', status=500) if not exported: # Throw back a 404 if the exact export parameters are not supported return HttpResponseNotFound( 'Nothing to export for export_type=%s, %s' % (export_type, ds_key)) elif len(exported) > 1: # Building an archive so that there can be a single file download archname = ds_key + '-' + export_type + '.zip' zipfiles(exported, os.path.join(tmpdir, archname)) exported = os.path.join(tmpdir, archname) else: # single file exported = exported[0] content_type = EXPORT_CONTENT_TYPE_MAP.get( export_type, DEFAULT_CONTENT_TYPE) fname = 'output-%s-%s' % (result_id, os.path.basename(exported)) stream = FileWrapper(open(exported, 'rb')) # 'b' is needed on Windows stream.close = lambda: ( FileWrapper.close(stream), shutil.rmtree(tmpdir)) response = FileResponse(stream, content_type=content_type) response['Content-Disposition'] = ( 'attachment; filename=%s' % os.path.basename(fname)) response['Content-Length'] = str(os.path.getsize(exported)) return response
python
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 specified). :param result_id: The id of the requested artifact. :returns: If the requested ``result_id`` is not available in the format designated by the `export_type`. Otherwise, return a `django.http.HttpResponse` containing the content of the requested artifact. Parameters for the GET request can include an `export_type`, such as 'xml', 'geojson', 'csv', etc. """ # If the result for the requested ID doesn't exist, OR # the job which it is related too is not complete, # throw back a 404. try: job_id, job_status, job_user, datadir, ds_key = logs.dbcmd( 'get_result', result_id) if not utils.user_has_permission(request, job_user): return HttpResponseForbidden() except dbapi.NotFound: return HttpResponseNotFound() etype = request.GET.get('export_type') export_type = etype or DEFAULT_EXPORT_TYPE tmpdir = tempfile.mkdtemp() try: exported = core.export_from_db( (ds_key, export_type), job_id, datadir, tmpdir) except DataStoreExportError as exc: # TODO: there should be a better error page return HttpResponse(content='%s: %s' % (exc.__class__.__name__, exc), content_type='text/plain', status=500) if not exported: # Throw back a 404 if the exact export parameters are not supported return HttpResponseNotFound( 'Nothing to export for export_type=%s, %s' % (export_type, ds_key)) elif len(exported) > 1: # Building an archive so that there can be a single file download archname = ds_key + '-' + export_type + '.zip' zipfiles(exported, os.path.join(tmpdir, archname)) exported = os.path.join(tmpdir, archname) else: # single file exported = exported[0] content_type = EXPORT_CONTENT_TYPE_MAP.get( export_type, DEFAULT_CONTENT_TYPE) fname = 'output-%s-%s' % (result_id, os.path.basename(exported)) stream = FileWrapper(open(exported, 'rb')) # 'b' is needed on Windows stream.close = lambda: ( FileWrapper.close(stream), shutil.rmtree(tmpdir)) response = FileResponse(stream, content_type=content_type) response['Content-Disposition'] = ( 'attachment; filename=%s' % os.path.basename(fname)) response['Content-Length'] = str(os.path.getsize(exported)) return response
[ "def", "calc_result", "(", "request", ",", "result_id", ")", ":", "# If the result for the requested ID doesn't exist, OR", "# the job which it is related too is not complete,", "# throw back a 404.", "try", ":", "job_id", ",", "job_status", ",", "job_user", ",", "datadir", ",", "ds_key", "=", "logs", ".", "dbcmd", "(", "'get_result'", ",", "result_id", ")", "if", "not", "utils", ".", "user_has_permission", "(", "request", ",", "job_user", ")", ":", "return", "HttpResponseForbidden", "(", ")", "except", "dbapi", ".", "NotFound", ":", "return", "HttpResponseNotFound", "(", ")", "etype", "=", "request", ".", "GET", ".", "get", "(", "'export_type'", ")", "export_type", "=", "etype", "or", "DEFAULT_EXPORT_TYPE", "tmpdir", "=", "tempfile", ".", "mkdtemp", "(", ")", "try", ":", "exported", "=", "core", ".", "export_from_db", "(", "(", "ds_key", ",", "export_type", ")", ",", "job_id", ",", "datadir", ",", "tmpdir", ")", "except", "DataStoreExportError", "as", "exc", ":", "# TODO: there should be a better error page", "return", "HttpResponse", "(", "content", "=", "'%s: %s'", "%", "(", "exc", ".", "__class__", ".", "__name__", ",", "exc", ")", ",", "content_type", "=", "'text/plain'", ",", "status", "=", "500", ")", "if", "not", "exported", ":", "# Throw back a 404 if the exact export parameters are not supported", "return", "HttpResponseNotFound", "(", "'Nothing to export for export_type=%s, %s'", "%", "(", "export_type", ",", "ds_key", ")", ")", "elif", "len", "(", "exported", ")", ">", "1", ":", "# Building an archive so that there can be a single file download", "archname", "=", "ds_key", "+", "'-'", "+", "export_type", "+", "'.zip'", "zipfiles", "(", "exported", ",", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "archname", ")", ")", "exported", "=", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "archname", ")", "else", ":", "# single file", "exported", "=", "exported", "[", "0", "]", "content_type", "=", "EXPORT_CONTENT_TYPE_MAP", ".", "get", "(", "export_type", ",", "DEFAULT_CONTENT_TYPE", ")", "fname", "=", "'output-%s-%s'", "%", "(", "result_id", ",", "os", ".", "path", ".", "basename", "(", "exported", ")", ")", "stream", "=", "FileWrapper", "(", "open", "(", "exported", ",", "'rb'", ")", ")", "# 'b' is needed on Windows", "stream", ".", "close", "=", "lambda", ":", "(", "FileWrapper", ".", "close", "(", "stream", ")", ",", "shutil", ".", "rmtree", "(", "tmpdir", ")", ")", "response", "=", "FileResponse", "(", "stream", ",", "content_type", "=", "content_type", ")", "response", "[", "'Content-Disposition'", "]", "=", "(", "'attachment; filename=%s'", "%", "os", ".", "path", ".", "basename", "(", "fname", ")", ")", "response", "[", "'Content-Length'", "]", "=", "str", "(", "os", ".", "path", ".", "getsize", "(", "exported", ")", ")", "return", "response" ]
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 specified). :param result_id: The id of the requested artifact. :returns: If the requested ``result_id`` is not available in the format designated by the `export_type`. Otherwise, return a `django.http.HttpResponse` containing the content of the requested artifact. Parameters for the GET request can include an `export_type`, such as 'xml', 'geojson', 'csv', etc.
[ "Download", "a", "specific", "result", "by", "result_id", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L587-L653
585
gem/oq-engine
openquake/server/views.py
extract
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_has_permission(request, job.user_name): return HttpResponseForbidden() try: # read the data and save them on a temporary .npz file with datastore.read(job.ds_calc_dir + '.hdf5') as ds: fd, fname = tempfile.mkstemp( prefix=what.replace('/', '-'), suffix='.npz') os.close(fd) n = len(request.path_info) query_string = unquote_plus(request.get_full_path()[n:]) aw = _extract(ds, what + query_string) a = {} for key, val in vars(aw).items(): key = str(key) # can be a numpy.bytes_ if isinstance(val, str): # without this oq extract would fail a[key] = numpy.array(val.encode('utf-8')) elif isinstance(val, dict): # this is hack: we are losing the values a[key] = list(val) else: a[key] = val numpy.savez_compressed(fname, **a) except Exception as exc: tb = ''.join(traceback.format_tb(exc.__traceback__)) return HttpResponse( content='%s: %s\n%s' % (exc.__class__.__name__, exc, tb), content_type='text/plain', status=500) # stream the data back stream = FileWrapper(open(fname, 'rb')) stream.close = lambda: (FileWrapper.close(stream), os.remove(fname)) response = FileResponse(stream, content_type='application/octet-stream') response['Content-Disposition'] = ( 'attachment; filename=%s' % os.path.basename(fname)) response['Content-Length'] = str(os.path.getsize(fname)) return response
python
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_has_permission(request, job.user_name): return HttpResponseForbidden() try: # read the data and save them on a temporary .npz file with datastore.read(job.ds_calc_dir + '.hdf5') as ds: fd, fname = tempfile.mkstemp( prefix=what.replace('/', '-'), suffix='.npz') os.close(fd) n = len(request.path_info) query_string = unquote_plus(request.get_full_path()[n:]) aw = _extract(ds, what + query_string) a = {} for key, val in vars(aw).items(): key = str(key) # can be a numpy.bytes_ if isinstance(val, str): # without this oq extract would fail a[key] = numpy.array(val.encode('utf-8')) elif isinstance(val, dict): # this is hack: we are losing the values a[key] = list(val) else: a[key] = val numpy.savez_compressed(fname, **a) except Exception as exc: tb = ''.join(traceback.format_tb(exc.__traceback__)) return HttpResponse( content='%s: %s\n%s' % (exc.__class__.__name__, exc, tb), content_type='text/plain', status=500) # stream the data back stream = FileWrapper(open(fname, 'rb')) stream.close = lambda: (FileWrapper.close(stream), os.remove(fname)) response = FileResponse(stream, content_type='application/octet-stream') response['Content-Disposition'] = ( 'attachment; filename=%s' % os.path.basename(fname)) response['Content-Length'] = str(os.path.getsize(fname)) return response
[ "def", "extract", "(", "request", ",", "calc_id", ",", "what", ")", ":", "job", "=", "logs", ".", "dbcmd", "(", "'get_job'", ",", "int", "(", "calc_id", ")", ")", "if", "job", "is", "None", ":", "return", "HttpResponseNotFound", "(", ")", "if", "not", "utils", ".", "user_has_permission", "(", "request", ",", "job", ".", "user_name", ")", ":", "return", "HttpResponseForbidden", "(", ")", "try", ":", "# read the data and save them on a temporary .npz file", "with", "datastore", ".", "read", "(", "job", ".", "ds_calc_dir", "+", "'.hdf5'", ")", "as", "ds", ":", "fd", ",", "fname", "=", "tempfile", ".", "mkstemp", "(", "prefix", "=", "what", ".", "replace", "(", "'/'", ",", "'-'", ")", ",", "suffix", "=", "'.npz'", ")", "os", ".", "close", "(", "fd", ")", "n", "=", "len", "(", "request", ".", "path_info", ")", "query_string", "=", "unquote_plus", "(", "request", ".", "get_full_path", "(", ")", "[", "n", ":", "]", ")", "aw", "=", "_extract", "(", "ds", ",", "what", "+", "query_string", ")", "a", "=", "{", "}", "for", "key", ",", "val", "in", "vars", "(", "aw", ")", ".", "items", "(", ")", ":", "key", "=", "str", "(", "key", ")", "# can be a numpy.bytes_", "if", "isinstance", "(", "val", ",", "str", ")", ":", "# without this oq extract would fail", "a", "[", "key", "]", "=", "numpy", ".", "array", "(", "val", ".", "encode", "(", "'utf-8'", ")", ")", "elif", "isinstance", "(", "val", ",", "dict", ")", ":", "# this is hack: we are losing the values", "a", "[", "key", "]", "=", "list", "(", "val", ")", "else", ":", "a", "[", "key", "]", "=", "val", "numpy", ".", "savez_compressed", "(", "fname", ",", "*", "*", "a", ")", "except", "Exception", "as", "exc", ":", "tb", "=", "''", ".", "join", "(", "traceback", ".", "format_tb", "(", "exc", ".", "__traceback__", ")", ")", "return", "HttpResponse", "(", "content", "=", "'%s: %s\\n%s'", "%", "(", "exc", ".", "__class__", ".", "__name__", ",", "exc", ",", "tb", ")", ",", "content_type", "=", "'text/plain'", ",", "status", "=", "500", ")", "# stream the data back", "stream", "=", "FileWrapper", "(", "open", "(", "fname", ",", "'rb'", ")", ")", "stream", ".", "close", "=", "lambda", ":", "(", "FileWrapper", ".", "close", "(", "stream", ")", ",", "os", ".", "remove", "(", "fname", ")", ")", "response", "=", "FileResponse", "(", "stream", ",", "content_type", "=", "'application/octet-stream'", ")", "response", "[", "'Content-Disposition'", "]", "=", "(", "'attachment; filename=%s'", "%", "os", ".", "path", ".", "basename", "(", "fname", ")", ")", "response", "[", "'Content-Length'", "]", "=", "str", "(", "os", ".", "path", ".", "getsize", "(", "fname", ")", ")", "return", "response" ]
Wrapper over the `oq extract` command. If `setting.LOCKDOWN` is true only calculations owned by the current user can be retrieved.
[ "Wrapper", "over", "the", "oq", "extract", "command", ".", "If", "setting", ".", "LOCKDOWN", "is", "true", "only", "calculations", "owned", "by", "the", "current", "user", "can", "be", "retrieved", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L658-L703
586
gem/oq-engine
openquake/server/views.py
calc_datastore
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 present, else throws a 404 """ 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() fname = job.ds_calc_dir + '.hdf5' response = FileResponse( FileWrapper(open(fname, 'rb')), content_type=HDF5) response['Content-Disposition'] = ( 'attachment; filename=%s' % os.path.basename(fname)) response['Content-Length'] = str(os.path.getsize(fname)) return response
python
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 present, else throws a 404 """ 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() fname = job.ds_calc_dir + '.hdf5' response = FileResponse( FileWrapper(open(fname, 'rb')), content_type=HDF5) response['Content-Disposition'] = ( 'attachment; filename=%s' % os.path.basename(fname)) response['Content-Length'] = str(os.path.getsize(fname)) return response
[ "def", "calc_datastore", "(", "request", ",", "job_id", ")", ":", "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", "(", ")", "fname", "=", "job", ".", "ds_calc_dir", "+", "'.hdf5'", "response", "=", "FileResponse", "(", "FileWrapper", "(", "open", "(", "fname", ",", "'rb'", ")", ")", ",", "content_type", "=", "HDF5", ")", "response", "[", "'Content-Disposition'", "]", "=", "(", "'attachment; filename=%s'", "%", "os", ".", "path", ".", "basename", "(", "fname", ")", ")", "response", "[", "'Content-Length'", "]", "=", "str", "(", "os", ".", "path", ".", "getsize", "(", "fname", ")", ")", "return", "response" ]
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 present, else throws a 404
[ "Download", "a", "full", "datastore", "file", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L708-L732
587
gem/oq-engine
openquake/server/views.py
calc_oqparam
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 datastore.read(job.ds_calc_dir + '.hdf5') as ds: oq = ds['oqparam'] return HttpResponse(content=json.dumps(vars(oq)), content_type=JSON)
python
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 datastore.read(job.ds_calc_dir + '.hdf5') as ds: oq = ds['oqparam'] return HttpResponse(content=json.dumps(vars(oq)), content_type=JSON)
[ "def", "calc_oqparam", "(", "request", ",", "job_id", ")", ":", "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", "datastore", ".", "read", "(", "job", ".", "ds_calc_dir", "+", "'.hdf5'", ")", "as", "ds", ":", "oq", "=", "ds", "[", "'oqparam'", "]", "return", "HttpResponse", "(", "content", "=", "json", ".", "dumps", "(", "vars", "(", "oq", ")", ")", ",", "content_type", "=", "JSON", ")" ]
Return the calculation parameters as a JSON
[ "Return", "the", "calculation", "parameters", "as", "a", "JSON" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L737-L749
588
gem/oq-engine
openquake/server/views.py
on_same_fs
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'] checksum = 0 try: data = open(filename, 'rb').read(32) checksum = zlib.adler32(data, checksum) & 0xffffffff if checksum == int(checksum_in): return HttpResponse(content=json.dumps({'success': True}), content_type=JSON, status=200) except (IOError, ValueError): pass return HttpResponse(content=json.dumps({'success': False}), content_type=JSON, status=200)
python
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'] checksum = 0 try: data = open(filename, 'rb').read(32) checksum = zlib.adler32(data, checksum) & 0xffffffff if checksum == int(checksum_in): return HttpResponse(content=json.dumps({'success': True}), content_type=JSON, status=200) except (IOError, ValueError): pass return HttpResponse(content=json.dumps({'success': False}), content_type=JSON, status=200)
[ "def", "on_same_fs", "(", "request", ")", ":", "filename", "=", "request", ".", "POST", "[", "'filename'", "]", "checksum_in", "=", "request", ".", "POST", "[", "'checksum'", "]", "checksum", "=", "0", "try", ":", "data", "=", "open", "(", "filename", ",", "'rb'", ")", ".", "read", "(", "32", ")", "checksum", "=", "zlib", ".", "adler32", "(", "data", ",", "checksum", ")", "&", "0xffffffff", "if", "checksum", "==", "int", "(", "checksum_in", ")", ":", "return", "HttpResponse", "(", "content", "=", "json", ".", "dumps", "(", "{", "'success'", ":", "True", "}", ")", ",", "content_type", "=", "JSON", ",", "status", "=", "200", ")", "except", "(", "IOError", ",", "ValueError", ")", ":", "pass", "return", "HttpResponse", "(", "content", "=", "json", ".", "dumps", "(", "{", "'success'", ":", "False", "}", ")", ",", "content_type", "=", "JSON", ",", "status", "=", "200", ")" ]
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.
[ "Accept", "a", "POST", "request", "to", "check", "access", "to", "a", "FS", "available", "by", "a", "client", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L769-L791
589
gem/oq-engine
openquake/calculators/classical_damage.py
classical_damage
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 param: dictionary of extra parameters :param monitor: :class:`openquake.baselib.performance.Monitor` instance :returns: a nested dictionary lt_idx, rlz_idx -> asset_idx -> <damage array> """ result = AccumDict(accum=AccumDict()) for ri in riskinputs: for out in riskmodel.gen_outputs(ri, monitor): for l, loss_type in enumerate(riskmodel.loss_types): ordinals = ri.assets['ordinal'] result[l, out.rlzi] += dict(zip(ordinals, out[loss_type])) return result
python
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 param: dictionary of extra parameters :param monitor: :class:`openquake.baselib.performance.Monitor` instance :returns: a nested dictionary lt_idx, rlz_idx -> asset_idx -> <damage array> """ result = AccumDict(accum=AccumDict()) for ri in riskinputs: for out in riskmodel.gen_outputs(ri, monitor): for l, loss_type in enumerate(riskmodel.loss_types): ordinals = ri.assets['ordinal'] result[l, out.rlzi] += dict(zip(ordinals, out[loss_type])) return result
[ "def", "classical_damage", "(", "riskinputs", ",", "riskmodel", ",", "param", ",", "monitor", ")", ":", "result", "=", "AccumDict", "(", "accum", "=", "AccumDict", "(", ")", ")", "for", "ri", "in", "riskinputs", ":", "for", "out", "in", "riskmodel", ".", "gen_outputs", "(", "ri", ",", "monitor", ")", ":", "for", "l", ",", "loss_type", "in", "enumerate", "(", "riskmodel", ".", "loss_types", ")", ":", "ordinals", "=", "ri", ".", "assets", "[", "'ordinal'", "]", "result", "[", "l", ",", "out", ".", "rlzi", "]", "+=", "dict", "(", "zip", "(", "ordinals", ",", "out", "[", "loss_type", "]", ")", ")", "return", "result" ]
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 param: dictionary of extra parameters :param monitor: :class:`openquake.baselib.performance.Monitor` instance :returns: a nested dictionary lt_idx, rlz_idx -> asset_idx -> <damage array>
[ "Core", "function", "for", "a", "classical", "damage", "computation", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/classical_damage.py#L26-L47
590
gem/oq-engine
openquake/hmtk/seismicity/gcmt_catalogue.py
cmp_mat
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
python
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", "cmp_mat", "(", "a", ",", "b", ")", ":", "c", "=", "0", "for", "x", ",", "y", "in", "zip", "(", "a", ".", "flat", ",", "b", ".", "flat", ")", ":", "c", "=", "cmp", "(", "abs", "(", "x", ")", ",", "abs", "(", "y", ")", ")", "if", "c", "!=", "0", ":", "return", "c", "return", "c" ]
Sorts two matrices returning a positive or zero value
[ "Sorts", "two", "matrices", "returning", "a", "positive", "or", "zero", "value" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_catalogue.py#L62-L71
591
gem/oq-engine
openquake/hmtk/seismicity/gcmt_catalogue.py
GCMTCentroid._get_centroid_time
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)) if time_diff < 0.: source_time = source_time - datetime.timedelta( seconds=int(second_diff), microseconds=microsecond_diff) else: source_time = source_time + datetime.timedelta( seconds=int(second_diff), microseconds=microsecond_diff) self.time = source_time.time() self.date = source_time.date()
python
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)) if time_diff < 0.: source_time = source_time - datetime.timedelta( seconds=int(second_diff), microseconds=microsecond_diff) else: source_time = source_time + datetime.timedelta( seconds=int(second_diff), microseconds=microsecond_diff) self.time = source_time.time() self.date = source_time.date()
[ "def", "_get_centroid_time", "(", "self", ",", "time_diff", ")", ":", "source_time", "=", "datetime", ".", "datetime", ".", "combine", "(", "self", ".", "date", ",", "self", ".", "time", ")", "second_diff", "=", "floor", "(", "fabs", "(", "time_diff", ")", ")", "microsecond_diff", "=", "int", "(", "1000.", "*", "(", "time_diff", "-", "second_diff", ")", ")", "if", "time_diff", "<", "0.", ":", "source_time", "=", "source_time", "-", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "second_diff", ")", ",", "microseconds", "=", "microsecond_diff", ")", "else", ":", "source_time", "=", "source_time", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "second_diff", ")", ",", "microseconds", "=", "microsecond_diff", ")", "self", ".", "time", "=", "source_time", ".", "time", "(", ")", "self", ".", "date", "=", "source_time", ".", "date", "(", ")" ]
Calculates the time difference between the date-time classes
[ "Calculates", "the", "time", "difference", "between", "the", "date", "-", "time", "classes" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_catalogue.py#L120-L134
592
gem/oq-engine
openquake/hmtk/seismicity/gcmt_catalogue.py
GCMTMomentTensor._to_ned
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 return self.tensor, self.tensor_sigma else: raise ValueError('Reference frame %s not recognised - cannot ' 'transform to NED!' % self.ref_frame)
python
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 return self.tensor, self.tensor_sigma else: raise ValueError('Reference frame %s not recognised - cannot ' 'transform to NED!' % self.ref_frame)
[ "def", "_to_ned", "(", "self", ")", ":", "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", "return", "self", ".", "tensor", ",", "self", ".", "tensor_sigma", "else", ":", "raise", "ValueError", "(", "'Reference frame %s not recognised - cannot '", "'transform to NED!'", "%", "self", ".", "ref_frame", ")" ]
Switches the reference frame to NED
[ "Switches", "the", "reference", "frame", "to", "NED" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_catalogue.py#L193-L206
593
gem/oq-engine
openquake/hmtk/seismicity/gcmt_catalogue.py
GCMTMomentTensor._to_use
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 return self.tensor, self.tensor_sigma else: raise ValueError('Reference frame %s not recognised - cannot ' 'transform to USE!' % self.ref_frame)
python
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 return self.tensor, self.tensor_sigma else: raise ValueError('Reference frame %s not recognised - cannot ' 'transform to USE!' % self.ref_frame)
[ "def", "_to_use", "(", "self", ")", ":", "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", "return", "self", ".", "tensor", ",", "self", ".", "tensor_sigma", "else", ":", "raise", "ValueError", "(", "'Reference frame %s not recognised - cannot '", "'transform to USE!'", "%", "self", ".", "ref_frame", ")" ]
Returns a tensor in the USE reference frame
[ "Returns", "a", "tensor", "in", "the", "USE", "reference", "frame" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_catalogue.py#L208-L221
594
gem/oq-engine
openquake/hmtk/seismicity/gcmt_catalogue.py
GCMTMomentTensor.get_nodal_planes
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 _, evect = utils.eigendecompose(self.tensor) # Rotation matrix _, rot_vec = utils.eigendecompose(np.matrix([[0., 0., -1], [0., 0., 0.], [-1., 0., 0.]])) rotation_matrix = (np.matrix(evect * rot_vec.T)).T if np.linalg.det(rotation_matrix) < 0.: rotation_matrix *= -1. flip_dc = np.matrix([[0., 0., -1.], [0., -1., 0.], [-1., 0., 0.]]) rotation_matrices = sorted( [rotation_matrix, flip_dc * rotation_matrix], cmp=cmp_mat) nodal_planes = GCMTNodalPlanes() dip, strike, rake = [(180. / pi) * angle for angle in utils.matrix_to_euler(rotation_matrices[0])] # 1st Nodal Plane nodal_planes.nodal_plane_1 = {'strike': strike % 360, 'dip': dip, 'rake': -rake} # 2nd Nodal Plane dip, strike, rake = [(180. / pi) * angle for angle in utils.matrix_to_euler(rotation_matrices[1])] nodal_planes.nodal_plane_2 = {'strike': strike % 360., 'dip': dip, 'rake': -rake} return nodal_planes
python
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 _, evect = utils.eigendecompose(self.tensor) # Rotation matrix _, rot_vec = utils.eigendecompose(np.matrix([[0., 0., -1], [0., 0., 0.], [-1., 0., 0.]])) rotation_matrix = (np.matrix(evect * rot_vec.T)).T if np.linalg.det(rotation_matrix) < 0.: rotation_matrix *= -1. flip_dc = np.matrix([[0., 0., -1.], [0., -1., 0.], [-1., 0., 0.]]) rotation_matrices = sorted( [rotation_matrix, flip_dc * rotation_matrix], cmp=cmp_mat) nodal_planes = GCMTNodalPlanes() dip, strike, rake = [(180. / pi) * angle for angle in utils.matrix_to_euler(rotation_matrices[0])] # 1st Nodal Plane nodal_planes.nodal_plane_1 = {'strike': strike % 360, 'dip': dip, 'rake': -rake} # 2nd Nodal Plane dip, strike, rake = [(180. / pi) * angle for angle in utils.matrix_to_euler(rotation_matrices[1])] nodal_planes.nodal_plane_2 = {'strike': strike % 360., 'dip': dip, 'rake': -rake} return nodal_planes
[ "def", "get_nodal_planes", "(", "self", ")", ":", "# Convert reference frame to NED", "self", ".", "tensor", ",", "self", ".", "tensor_sigma", "=", "self", ".", "_to_ned", "(", ")", "self", ".", "ref_frame", "=", "'NED'", "# Eigenvalue decomposition", "# Tensor", "_", ",", "evect", "=", "utils", ".", "eigendecompose", "(", "self", ".", "tensor", ")", "# Rotation matrix", "_", ",", "rot_vec", "=", "utils", ".", "eigendecompose", "(", "np", ".", "matrix", "(", "[", "[", "0.", ",", "0.", ",", "-", "1", "]", ",", "[", "0.", ",", "0.", ",", "0.", "]", ",", "[", "-", "1.", ",", "0.", ",", "0.", "]", "]", ")", ")", "rotation_matrix", "=", "(", "np", ".", "matrix", "(", "evect", "*", "rot_vec", ".", "T", ")", ")", ".", "T", "if", "np", ".", "linalg", ".", "det", "(", "rotation_matrix", ")", "<", "0.", ":", "rotation_matrix", "*=", "-", "1.", "flip_dc", "=", "np", ".", "matrix", "(", "[", "[", "0.", ",", "0.", ",", "-", "1.", "]", ",", "[", "0.", ",", "-", "1.", ",", "0.", "]", ",", "[", "-", "1.", ",", "0.", ",", "0.", "]", "]", ")", "rotation_matrices", "=", "sorted", "(", "[", "rotation_matrix", ",", "flip_dc", "*", "rotation_matrix", "]", ",", "cmp", "=", "cmp_mat", ")", "nodal_planes", "=", "GCMTNodalPlanes", "(", ")", "dip", ",", "strike", ",", "rake", "=", "[", "(", "180.", "/", "pi", ")", "*", "angle", "for", "angle", "in", "utils", ".", "matrix_to_euler", "(", "rotation_matrices", "[", "0", "]", ")", "]", "# 1st Nodal Plane", "nodal_planes", ".", "nodal_plane_1", "=", "{", "'strike'", ":", "strike", "%", "360", ",", "'dip'", ":", "dip", ",", "'rake'", ":", "-", "rake", "}", "# 2nd Nodal Plane", "dip", ",", "strike", ",", "rake", "=", "[", "(", "180.", "/", "pi", ")", "*", "angle", "for", "angle", "in", "utils", ".", "matrix_to_euler", "(", "rotation_matrices", "[", "1", "]", ")", "]", "nodal_planes", ".", "nodal_plane_2", "=", "{", "'strike'", ":", "strike", "%", "360.", ",", "'dip'", ":", "dip", ",", "'rake'", ":", "-", "rake", "}", "return", "nodal_planes" ]
Returns the nodal planes by eigendecomposition of the moment tensor
[ "Returns", "the", "nodal", "planes", "by", "eigendecomposition", "of", "the", "moment", "tensor" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_catalogue.py#L239-L276
595
gem/oq-engine
openquake/hmtk/seismicity/gcmt_catalogue.py
GCMTMomentTensor.get_principal_axes
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) principal_axes = GCMTPrincipalAxes() # Eigenvalues principal_axes.p_axis = {'eigenvalue': self.eigenvalues[0]} principal_axes.b_axis = {'eigenvalue': self.eigenvalues[1]} principal_axes.t_axis = {'eigenvalue': self.eigenvalues[2]} # Eigen vectors # 1) P axis azim, plun = utils.get_azimuth_plunge(self.eigenvectors[:, 0], True) principal_axes.p_axis['azimuth'] = azim principal_axes.p_axis['plunge'] = plun # 2) B axis azim, plun = utils.get_azimuth_plunge(self.eigenvectors[:, 1], True) principal_axes.b_axis['azimuth'] = azim principal_axes.b_axis['plunge'] = plun # 3) T axis azim, plun = utils.get_azimuth_plunge(self.eigenvectors[:, 2], True) principal_axes.t_axis['azimuth'] = azim principal_axes.t_axis['plunge'] = plun return principal_axes
python
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) principal_axes = GCMTPrincipalAxes() # Eigenvalues principal_axes.p_axis = {'eigenvalue': self.eigenvalues[0]} principal_axes.b_axis = {'eigenvalue': self.eigenvalues[1]} principal_axes.t_axis = {'eigenvalue': self.eigenvalues[2]} # Eigen vectors # 1) P axis azim, plun = utils.get_azimuth_plunge(self.eigenvectors[:, 0], True) principal_axes.p_axis['azimuth'] = azim principal_axes.p_axis['plunge'] = plun # 2) B axis azim, plun = utils.get_azimuth_plunge(self.eigenvectors[:, 1], True) principal_axes.b_axis['azimuth'] = azim principal_axes.b_axis['plunge'] = plun # 3) T axis azim, plun = utils.get_azimuth_plunge(self.eigenvectors[:, 2], True) principal_axes.t_axis['azimuth'] = azim principal_axes.t_axis['plunge'] = plun return principal_axes
[ "def", "get_principal_axes", "(", "self", ")", ":", "# Perform eigendecomposition - returns in order P, B, T", "_", "=", "self", ".", "eigendecompose", "(", "normalise", "=", "True", ")", "principal_axes", "=", "GCMTPrincipalAxes", "(", ")", "# Eigenvalues", "principal_axes", ".", "p_axis", "=", "{", "'eigenvalue'", ":", "self", ".", "eigenvalues", "[", "0", "]", "}", "principal_axes", ".", "b_axis", "=", "{", "'eigenvalue'", ":", "self", ".", "eigenvalues", "[", "1", "]", "}", "principal_axes", ".", "t_axis", "=", "{", "'eigenvalue'", ":", "self", ".", "eigenvalues", "[", "2", "]", "}", "# Eigen vectors", "# 1) P axis", "azim", ",", "plun", "=", "utils", ".", "get_azimuth_plunge", "(", "self", ".", "eigenvectors", "[", ":", ",", "0", "]", ",", "True", ")", "principal_axes", ".", "p_axis", "[", "'azimuth'", "]", "=", "azim", "principal_axes", ".", "p_axis", "[", "'plunge'", "]", "=", "plun", "# 2) B axis", "azim", ",", "plun", "=", "utils", ".", "get_azimuth_plunge", "(", "self", ".", "eigenvectors", "[", ":", ",", "1", "]", ",", "True", ")", "principal_axes", ".", "b_axis", "[", "'azimuth'", "]", "=", "azim", "principal_axes", ".", "b_axis", "[", "'plunge'", "]", "=", "plun", "# 3) T axis", "azim", ",", "plun", "=", "utils", ".", "get_azimuth_plunge", "(", "self", ".", "eigenvectors", "[", ":", ",", "2", "]", ",", "True", ")", "principal_axes", ".", "t_axis", "[", "'azimuth'", "]", "=", "azim", "principal_axes", ".", "t_axis", "[", "'plunge'", "]", "=", "plun", "return", "principal_axes" ]
Uses the eigendecomposition to extract the principal axes from the moment tensor - returning an instance of the GCMTPrincipalAxes class
[ "Uses", "the", "eigendecomposition", "to", "extract", "the", "principal", "axes", "from", "the", "moment", "tensor", "-", "returning", "an", "instance", "of", "the", "GCMTPrincipalAxes", "class" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_catalogue.py#L278-L303
596
gem/oq-engine
openquake/hmtk/seismicity/gcmt_catalogue.py
GCMTCatalogue.select_catalogue_events
def select_catalogue_events(self, id0): ''' Orders the events in the catalogue according to an indexing vector :param np.ndarray id0: Pointer array indicating the locations of selected events ''' for key in self.data.keys(): if isinstance( self.data[key], np.ndarray) and len(self.data[key]) > 0: # Dictionary element is numpy array - use logical indexing self.data[key] = self.data[key][id0] elif isinstance( self.data[key], list) and len(self.data[key]) > 0: # Dictionary element is list self.data[key] = [self.data[key][iloc] for iloc in id0] else: continue if len(self.gcmts) > 0: self.gcmts = [self.gcmts[iloc] for iloc in id0] self.number_gcmts = self.get_number_tensors()
python
def select_catalogue_events(self, id0): ''' Orders the events in the catalogue according to an indexing vector :param np.ndarray id0: Pointer array indicating the locations of selected events ''' for key in self.data.keys(): if isinstance( self.data[key], np.ndarray) and len(self.data[key]) > 0: # Dictionary element is numpy array - use logical indexing self.data[key] = self.data[key][id0] elif isinstance( self.data[key], list) and len(self.data[key]) > 0: # Dictionary element is list self.data[key] = [self.data[key][iloc] for iloc in id0] else: continue if len(self.gcmts) > 0: self.gcmts = [self.gcmts[iloc] for iloc in id0] self.number_gcmts = self.get_number_tensors()
[ "def", "select_catalogue_events", "(", "self", ",", "id0", ")", ":", "for", "key", "in", "self", ".", "data", ".", "keys", "(", ")", ":", "if", "isinstance", "(", "self", ".", "data", "[", "key", "]", ",", "np", ".", "ndarray", ")", "and", "len", "(", "self", ".", "data", "[", "key", "]", ")", ">", "0", ":", "# Dictionary element is numpy array - use logical indexing", "self", ".", "data", "[", "key", "]", "=", "self", ".", "data", "[", "key", "]", "[", "id0", "]", "elif", "isinstance", "(", "self", ".", "data", "[", "key", "]", ",", "list", ")", "and", "len", "(", "self", ".", "data", "[", "key", "]", ")", ">", "0", ":", "# Dictionary element is list", "self", ".", "data", "[", "key", "]", "=", "[", "self", ".", "data", "[", "key", "]", "[", "iloc", "]", "for", "iloc", "in", "id0", "]", "else", ":", "continue", "if", "len", "(", "self", ".", "gcmts", ")", ">", "0", ":", "self", ".", "gcmts", "=", "[", "self", ".", "gcmts", "[", "iloc", "]", "for", "iloc", "in", "id0", "]", "self", ".", "number_gcmts", "=", "self", ".", "get_number_tensors", "(", ")" ]
Orders the events in the catalogue according to an indexing vector :param np.ndarray id0: Pointer array indicating the locations of selected events
[ "Orders", "the", "events", "in", "the", "catalogue", "according", "to", "an", "indexing", "vector" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_catalogue.py#L424-L445
597
gem/oq-engine
openquake/hazardlib/geo/surface/multi.py
MultiSurface._get_edge_set
def _get_edge_set(self, tol=0.1): """ Retrieve set of top edges from all of the individual surfaces, downsampling the upper edge based on the specified tolerance """ edges = [] for surface in self.surfaces: if isinstance(surface, GriddedSurface): return edges.append(surface.mesh) elif isinstance(surface, PlanarSurface): # Top edge determined from two end points edge = [] for pnt in [surface.top_left, surface.top_right]: edge.append([pnt.longitude, pnt.latitude, pnt.depth]) edges.append(numpy.array(edge)) elif isinstance(surface, (ComplexFaultSurface, SimpleFaultSurface)): # Rectangular meshes are downsampled to reduce their # overall size edges.append(downsample_trace(surface.mesh, tol)) else: raise ValueError("Surface %s not recognised" % str(surface)) return edges
python
def _get_edge_set(self, tol=0.1): """ Retrieve set of top edges from all of the individual surfaces, downsampling the upper edge based on the specified tolerance """ edges = [] for surface in self.surfaces: if isinstance(surface, GriddedSurface): return edges.append(surface.mesh) elif isinstance(surface, PlanarSurface): # Top edge determined from two end points edge = [] for pnt in [surface.top_left, surface.top_right]: edge.append([pnt.longitude, pnt.latitude, pnt.depth]) edges.append(numpy.array(edge)) elif isinstance(surface, (ComplexFaultSurface, SimpleFaultSurface)): # Rectangular meshes are downsampled to reduce their # overall size edges.append(downsample_trace(surface.mesh, tol)) else: raise ValueError("Surface %s not recognised" % str(surface)) return edges
[ "def", "_get_edge_set", "(", "self", ",", "tol", "=", "0.1", ")", ":", "edges", "=", "[", "]", "for", "surface", "in", "self", ".", "surfaces", ":", "if", "isinstance", "(", "surface", ",", "GriddedSurface", ")", ":", "return", "edges", ".", "append", "(", "surface", ".", "mesh", ")", "elif", "isinstance", "(", "surface", ",", "PlanarSurface", ")", ":", "# Top edge determined from two end points", "edge", "=", "[", "]", "for", "pnt", "in", "[", "surface", ".", "top_left", ",", "surface", ".", "top_right", "]", ":", "edge", ".", "append", "(", "[", "pnt", ".", "longitude", ",", "pnt", ".", "latitude", ",", "pnt", ".", "depth", "]", ")", "edges", ".", "append", "(", "numpy", ".", "array", "(", "edge", ")", ")", "elif", "isinstance", "(", "surface", ",", "(", "ComplexFaultSurface", ",", "SimpleFaultSurface", ")", ")", ":", "# Rectangular meshes are downsampled to reduce their", "# overall size", "edges", ".", "append", "(", "downsample_trace", "(", "surface", ".", "mesh", ",", "tol", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Surface %s not recognised\"", "%", "str", "(", "surface", ")", ")", "return", "edges" ]
Retrieve set of top edges from all of the individual surfaces, downsampling the upper edge based on the specified tolerance
[ "Retrieve", "set", "of", "top", "edges", "from", "all", "of", "the", "individual", "surfaces", "downsampling", "the", "upper", "edge", "based", "on", "the", "specified", "tolerance" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/multi.py#L137-L159
598
gem/oq-engine
openquake/hazardlib/geo/surface/multi.py
MultiSurface.get_min_distance
def get_min_distance(self, mesh): """ For each point in ``mesh`` compute the minimum distance to each surface element and return the smallest value. See :meth:`superclass method <.base.BaseSurface.get_min_distance>` for spec of input and result values. """ dists = [surf.get_min_distance(mesh) for surf in self.surfaces] return numpy.min(dists, axis=0)
python
def get_min_distance(self, mesh): """ For each point in ``mesh`` compute the minimum distance to each surface element and return the smallest value. See :meth:`superclass method <.base.BaseSurface.get_min_distance>` for spec of input and result values. """ dists = [surf.get_min_distance(mesh) for surf in self.surfaces] return numpy.min(dists, axis=0)
[ "def", "get_min_distance", "(", "self", ",", "mesh", ")", ":", "dists", "=", "[", "surf", ".", "get_min_distance", "(", "mesh", ")", "for", "surf", "in", "self", ".", "surfaces", "]", "return", "numpy", ".", "min", "(", "dists", ",", "axis", "=", "0", ")" ]
For each point in ``mesh`` compute the minimum distance to each surface element and return the smallest value. See :meth:`superclass method <.base.BaseSurface.get_min_distance>` for spec of input and result values.
[ "For", "each", "point", "in", "mesh", "compute", "the", "minimum", "distance", "to", "each", "surface", "element", "and", "return", "the", "smallest", "value", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/multi.py#L161-L172
599
gem/oq-engine
openquake/hazardlib/geo/surface/multi.py
MultiSurface.get_closest_points
def get_closest_points(self, mesh): """ For each point in ``mesh`` find the closest surface element, and return the corresponding closest point. See :meth:`superclass method <.base.BaseSurface.get_closest_points>` for spec of input and result values. """ # first, for each point in mesh compute minimum distance to each # surface. The distance matrix is flattend, because mesh can be of # an arbitrary shape. By flattening we obtain a ``distances`` matrix # for which the first dimension represents the different surfaces # and the second dimension the mesh points. dists = numpy.array( [surf.get_min_distance(mesh).flatten() for surf in self.surfaces] ) # find for each point in mesh the index of closest surface idx = dists == numpy.min(dists, axis=0) # loop again over surfaces. For each surface compute the closest # points, and associate them to the mesh points for which the surface # is the closest. Note that if a surface is not the closest to any of # the mesh points then the calculation is skipped lons = numpy.empty_like(mesh.lons.flatten()) lats = numpy.empty_like(mesh.lats.flatten()) depths = None if mesh.depths is None else \ numpy.empty_like(mesh.depths.flatten()) for i, surf in enumerate(self.surfaces): if not idx[i, :].any(): continue cps = surf.get_closest_points(mesh) lons[idx[i, :]] = cps.lons.flatten()[idx[i, :]] lats[idx[i, :]] = cps.lats.flatten()[idx[i, :]] if depths is not None: depths[idx[i, :]] = cps.depths.flatten()[idx[i, :]] lons = lons.reshape(mesh.lons.shape) lats = lats.reshape(mesh.lats.shape) if depths is not None: depths = depths.reshape(mesh.depths.shape) return Mesh(lons, lats, depths)
python
def get_closest_points(self, mesh): """ For each point in ``mesh`` find the closest surface element, and return the corresponding closest point. See :meth:`superclass method <.base.BaseSurface.get_closest_points>` for spec of input and result values. """ # first, for each point in mesh compute minimum distance to each # surface. The distance matrix is flattend, because mesh can be of # an arbitrary shape. By flattening we obtain a ``distances`` matrix # for which the first dimension represents the different surfaces # and the second dimension the mesh points. dists = numpy.array( [surf.get_min_distance(mesh).flatten() for surf in self.surfaces] ) # find for each point in mesh the index of closest surface idx = dists == numpy.min(dists, axis=0) # loop again over surfaces. For each surface compute the closest # points, and associate them to the mesh points for which the surface # is the closest. Note that if a surface is not the closest to any of # the mesh points then the calculation is skipped lons = numpy.empty_like(mesh.lons.flatten()) lats = numpy.empty_like(mesh.lats.flatten()) depths = None if mesh.depths is None else \ numpy.empty_like(mesh.depths.flatten()) for i, surf in enumerate(self.surfaces): if not idx[i, :].any(): continue cps = surf.get_closest_points(mesh) lons[idx[i, :]] = cps.lons.flatten()[idx[i, :]] lats[idx[i, :]] = cps.lats.flatten()[idx[i, :]] if depths is not None: depths[idx[i, :]] = cps.depths.flatten()[idx[i, :]] lons = lons.reshape(mesh.lons.shape) lats = lats.reshape(mesh.lats.shape) if depths is not None: depths = depths.reshape(mesh.depths.shape) return Mesh(lons, lats, depths)
[ "def", "get_closest_points", "(", "self", ",", "mesh", ")", ":", "# first, for each point in mesh compute minimum distance to each", "# surface. The distance matrix is flattend, because mesh can be of", "# an arbitrary shape. By flattening we obtain a ``distances`` matrix", "# for which the first dimension represents the different surfaces", "# and the second dimension the mesh points.", "dists", "=", "numpy", ".", "array", "(", "[", "surf", ".", "get_min_distance", "(", "mesh", ")", ".", "flatten", "(", ")", "for", "surf", "in", "self", ".", "surfaces", "]", ")", "# find for each point in mesh the index of closest surface", "idx", "=", "dists", "==", "numpy", ".", "min", "(", "dists", ",", "axis", "=", "0", ")", "# loop again over surfaces. For each surface compute the closest", "# points, and associate them to the mesh points for which the surface", "# is the closest. Note that if a surface is not the closest to any of", "# the mesh points then the calculation is skipped", "lons", "=", "numpy", ".", "empty_like", "(", "mesh", ".", "lons", ".", "flatten", "(", ")", ")", "lats", "=", "numpy", ".", "empty_like", "(", "mesh", ".", "lats", ".", "flatten", "(", ")", ")", "depths", "=", "None", "if", "mesh", ".", "depths", "is", "None", "else", "numpy", ".", "empty_like", "(", "mesh", ".", "depths", ".", "flatten", "(", ")", ")", "for", "i", ",", "surf", "in", "enumerate", "(", "self", ".", "surfaces", ")", ":", "if", "not", "idx", "[", "i", ",", ":", "]", ".", "any", "(", ")", ":", "continue", "cps", "=", "surf", ".", "get_closest_points", "(", "mesh", ")", "lons", "[", "idx", "[", "i", ",", ":", "]", "]", "=", "cps", ".", "lons", ".", "flatten", "(", ")", "[", "idx", "[", "i", ",", ":", "]", "]", "lats", "[", "idx", "[", "i", ",", ":", "]", "]", "=", "cps", ".", "lats", ".", "flatten", "(", ")", "[", "idx", "[", "i", ",", ":", "]", "]", "if", "depths", "is", "not", "None", ":", "depths", "[", "idx", "[", "i", ",", ":", "]", "]", "=", "cps", ".", "depths", ".", "flatten", "(", ")", "[", "idx", "[", "i", ",", ":", "]", "]", "lons", "=", "lons", ".", "reshape", "(", "mesh", ".", "lons", ".", "shape", ")", "lats", "=", "lats", ".", "reshape", "(", "mesh", ".", "lats", ".", "shape", ")", "if", "depths", "is", "not", "None", ":", "depths", "=", "depths", ".", "reshape", "(", "mesh", ".", "depths", ".", "shape", ")", "return", "Mesh", "(", "lons", ",", "lats", ",", "depths", ")" ]
For each point in ``mesh`` find the closest surface element, and return the corresponding closest point. See :meth:`superclass method <.base.BaseSurface.get_closest_points>` for spec of input and result values.
[ "For", "each", "point", "in", "mesh", "find", "the", "closest", "surface", "element", "and", "return", "the", "corresponding", "closest", "point", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/multi.py#L174-L216