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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
gem/oq-engine
openquake/hazardlib/sourcewriter.py
build_truncated_gr_mfd
def build_truncated_gr_mfd(mfd): """ Parses the truncated Gutenberg Richter MFD as a Node :param mfd: MFD as instance of :class: `openquake.hazardlib.mfd.truncated_gr.TruncatedGRMFD` :returns: Instance of :class:`openquake.baselib.node.Node` """ return Node("truncGutenbergRichterMFD", {"aValue": mfd.a_val, "bValue": mfd.b_val, "minMag": mfd.min_mag, "maxMag": mfd.max_mag})
python
def build_truncated_gr_mfd(mfd): """ Parses the truncated Gutenberg Richter MFD as a Node :param mfd: MFD as instance of :class: `openquake.hazardlib.mfd.truncated_gr.TruncatedGRMFD` :returns: Instance of :class:`openquake.baselib.node.Node` """ return Node("truncGutenbergRichterMFD", {"aValue": mfd.a_val, "bValue": mfd.b_val, "minMag": mfd.min_mag, "maxMag": mfd.max_mag})
[ "def", "build_truncated_gr_mfd", "(", "mfd", ")", ":", "return", "Node", "(", "\"truncGutenbergRichterMFD\"", ",", "{", "\"aValue\"", ":", "mfd", ".", "a_val", ",", "\"bValue\"", ":", "mfd", ".", "b_val", ",", "\"minMag\"", ":", "mfd", ".", "min_mag", ",", "\"maxMag\"", ":", "mfd", ".", "max_mag", "}", ")" ]
Parses the truncated Gutenberg Richter MFD as a Node :param mfd: MFD as instance of :class: `openquake.hazardlib.mfd.truncated_gr.TruncatedGRMFD` :returns: Instance of :class:`openquake.baselib.node.Node`
[ "Parses", "the", "truncated", "Gutenberg", "Richter", "MFD", "as", "a", "Node" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourcewriter.py#L173-L185
train
233,100
gem/oq-engine
openquake/hazardlib/sourcewriter.py
build_arbitrary_mfd
def build_arbitrary_mfd(mfd): """ Parses the arbitrary MFD as a Node :param mfd: MFD as instance of :class: `openquake.hazardlib.mfd.arbitrary.ArbitraryMFD` :returns: Instance of :class:`openquake.baselib.node.Node` """ magnitudes = Node("magnitudes", text=mfd.magnitudes) occur_rates = Node("occurRates", text=mfd.occurrence_rates) return Node("arbitraryMFD", nodes=[magnitudes, occur_rates])
python
def build_arbitrary_mfd(mfd): """ Parses the arbitrary MFD as a Node :param mfd: MFD as instance of :class: `openquake.hazardlib.mfd.arbitrary.ArbitraryMFD` :returns: Instance of :class:`openquake.baselib.node.Node` """ magnitudes = Node("magnitudes", text=mfd.magnitudes) occur_rates = Node("occurRates", text=mfd.occurrence_rates) return Node("arbitraryMFD", nodes=[magnitudes, occur_rates])
[ "def", "build_arbitrary_mfd", "(", "mfd", ")", ":", "magnitudes", "=", "Node", "(", "\"magnitudes\"", ",", "text", "=", "mfd", ".", "magnitudes", ")", "occur_rates", "=", "Node", "(", "\"occurRates\"", ",", "text", "=", "mfd", ".", "occurrence_rates", ")", "return", "Node", "(", "\"arbitraryMFD\"", ",", "nodes", "=", "[", "magnitudes", ",", "occur_rates", "]", ")" ]
Parses the arbitrary MFD as a Node :param mfd: MFD as instance of :class: `openquake.hazardlib.mfd.arbitrary.ArbitraryMFD` :returns: Instance of :class:`openquake.baselib.node.Node`
[ "Parses", "the", "arbitrary", "MFD", "as", "a", "Node" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourcewriter.py#L189-L201
train
233,101
gem/oq-engine
openquake/hazardlib/sourcewriter.py
build_youngs_coppersmith_mfd
def build_youngs_coppersmith_mfd(mfd): """ Parses the Youngs & Coppersmith MFD as a node. Note that the MFD does not hold the total moment rate, but only the characteristic rate. Therefore the node is written to the characteristic rate version regardless of whether or not it was originally created from total moment rate :param mfd: MFD as instance of :class: `openquake.hazardlib.mfd.youngs_coppersmith_1985. YoungsCoppersmith1985MFD` :returns: Instance of :class:`openquake.baselib.node.Node` """ return Node("YoungsCoppersmithMFD", {"minMag": mfd.min_mag, "bValue": mfd.b_val, "characteristicMag": mfd.char_mag, "characteristicRate": mfd.char_rate, "binWidth": mfd.bin_width})
python
def build_youngs_coppersmith_mfd(mfd): """ Parses the Youngs & Coppersmith MFD as a node. Note that the MFD does not hold the total moment rate, but only the characteristic rate. Therefore the node is written to the characteristic rate version regardless of whether or not it was originally created from total moment rate :param mfd: MFD as instance of :class: `openquake.hazardlib.mfd.youngs_coppersmith_1985. YoungsCoppersmith1985MFD` :returns: Instance of :class:`openquake.baselib.node.Node` """ return Node("YoungsCoppersmithMFD", {"minMag": mfd.min_mag, "bValue": mfd.b_val, "characteristicMag": mfd.char_mag, "characteristicRate": mfd.char_rate, "binWidth": mfd.bin_width})
[ "def", "build_youngs_coppersmith_mfd", "(", "mfd", ")", ":", "return", "Node", "(", "\"YoungsCoppersmithMFD\"", ",", "{", "\"minMag\"", ":", "mfd", ".", "min_mag", ",", "\"bValue\"", ":", "mfd", ".", "b_val", ",", "\"characteristicMag\"", ":", "mfd", ".", "char_mag", ",", "\"characteristicRate\"", ":", "mfd", ".", "char_rate", ",", "\"binWidth\"", ":", "mfd", ".", "bin_width", "}", ")" ]
Parses the Youngs & Coppersmith MFD as a node. Note that the MFD does not hold the total moment rate, but only the characteristic rate. Therefore the node is written to the characteristic rate version regardless of whether or not it was originally created from total moment rate :param mfd: MFD as instance of :class: `openquake.hazardlib.mfd.youngs_coppersmith_1985. YoungsCoppersmith1985MFD` :returns: Instance of :class:`openquake.baselib.node.Node`
[ "Parses", "the", "Youngs", "&", "Coppersmith", "MFD", "as", "a", "node", ".", "Note", "that", "the", "MFD", "does", "not", "hold", "the", "total", "moment", "rate", "but", "only", "the", "characteristic", "rate", ".", "Therefore", "the", "node", "is", "written", "to", "the", "characteristic", "rate", "version", "regardless", "of", "whether", "or", "not", "it", "was", "originally", "created", "from", "total", "moment", "rate" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourcewriter.py#L205-L223
train
233,102
gem/oq-engine
openquake/hazardlib/sourcewriter.py
build_multi_mfd
def build_multi_mfd(mfd): """ Parses the MultiMFD as a Node :param mfd: MFD as instance of :class: `openquake.hazardlib.mfd.multi_mfd.MultiMFD` :returns: Instance of :class:`openquake.baselib.node.Node` """ node = Node("multiMFD", dict(kind=mfd.kind, size=mfd.size)) for name in sorted(mfd.kwargs): values = mfd.kwargs[name] if name in ('magnitudes', 'occurRates'): if len(values[0]) > 1: # tested in multipoint_test.py values = list(numpy.concatenate(values)) else: values = sum(values, []) node.append(Node(name, text=values)) if 'occurRates' in mfd.kwargs: lengths = [len(rates) for rates in mfd.kwargs['occurRates']] node.append(Node('lengths', text=lengths)) return node
python
def build_multi_mfd(mfd): """ Parses the MultiMFD as a Node :param mfd: MFD as instance of :class: `openquake.hazardlib.mfd.multi_mfd.MultiMFD` :returns: Instance of :class:`openquake.baselib.node.Node` """ node = Node("multiMFD", dict(kind=mfd.kind, size=mfd.size)) for name in sorted(mfd.kwargs): values = mfd.kwargs[name] if name in ('magnitudes', 'occurRates'): if len(values[0]) > 1: # tested in multipoint_test.py values = list(numpy.concatenate(values)) else: values = sum(values, []) node.append(Node(name, text=values)) if 'occurRates' in mfd.kwargs: lengths = [len(rates) for rates in mfd.kwargs['occurRates']] node.append(Node('lengths', text=lengths)) return node
[ "def", "build_multi_mfd", "(", "mfd", ")", ":", "node", "=", "Node", "(", "\"multiMFD\"", ",", "dict", "(", "kind", "=", "mfd", ".", "kind", ",", "size", "=", "mfd", ".", "size", ")", ")", "for", "name", "in", "sorted", "(", "mfd", ".", "kwargs", ")", ":", "values", "=", "mfd", ".", "kwargs", "[", "name", "]", "if", "name", "in", "(", "'magnitudes'", ",", "'occurRates'", ")", ":", "if", "len", "(", "values", "[", "0", "]", ")", ">", "1", ":", "# tested in multipoint_test.py", "values", "=", "list", "(", "numpy", ".", "concatenate", "(", "values", ")", ")", "else", ":", "values", "=", "sum", "(", "values", ",", "[", "]", ")", "node", ".", "append", "(", "Node", "(", "name", ",", "text", "=", "values", ")", ")", "if", "'occurRates'", "in", "mfd", ".", "kwargs", ":", "lengths", "=", "[", "len", "(", "rates", ")", "for", "rates", "in", "mfd", ".", "kwargs", "[", "'occurRates'", "]", "]", "node", ".", "append", "(", "Node", "(", "'lengths'", ",", "text", "=", "lengths", ")", ")", "return", "node" ]
Parses the MultiMFD as a Node :param mfd: MFD as instance of :class: `openquake.hazardlib.mfd.multi_mfd.MultiMFD` :returns: Instance of :class:`openquake.baselib.node.Node`
[ "Parses", "the", "MultiMFD", "as", "a", "Node" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourcewriter.py#L227-L249
train
233,103
gem/oq-engine
openquake/hazardlib/sourcewriter.py
build_nodal_plane_dist
def build_nodal_plane_dist(npd): """ Returns the nodal plane distribution as a Node instance :param npd: Nodal plane distribution as instance of :class: `openquake.hazardlib.pmf.PMF` :returns: Instance of :class:`openquake.baselib.node.Node` """ npds = [] for prob, npd in npd.data: nodal_plane = Node( "nodalPlane", {"dip": npd.dip, "probability": prob, "strike": npd.strike, "rake": npd.rake}) npds.append(nodal_plane) return Node("nodalPlaneDist", nodes=npds)
python
def build_nodal_plane_dist(npd): """ Returns the nodal plane distribution as a Node instance :param npd: Nodal plane distribution as instance of :class: `openquake.hazardlib.pmf.PMF` :returns: Instance of :class:`openquake.baselib.node.Node` """ npds = [] for prob, npd in npd.data: nodal_plane = Node( "nodalPlane", {"dip": npd.dip, "probability": prob, "strike": npd.strike, "rake": npd.rake}) npds.append(nodal_plane) return Node("nodalPlaneDist", nodes=npds)
[ "def", "build_nodal_plane_dist", "(", "npd", ")", ":", "npds", "=", "[", "]", "for", "prob", ",", "npd", "in", "npd", ".", "data", ":", "nodal_plane", "=", "Node", "(", "\"nodalPlane\"", ",", "{", "\"dip\"", ":", "npd", ".", "dip", ",", "\"probability\"", ":", "prob", ",", "\"strike\"", ":", "npd", ".", "strike", ",", "\"rake\"", ":", "npd", ".", "rake", "}", ")", "npds", ".", "append", "(", "nodal_plane", ")", "return", "Node", "(", "\"nodalPlaneDist\"", ",", "nodes", "=", "npds", ")" ]
Returns the nodal plane distribution as a Node instance :param npd: Nodal plane distribution as instance of :class: `openquake.hazardlib.pmf.PMF` :returns: Instance of :class:`openquake.baselib.node.Node`
[ "Returns", "the", "nodal", "plane", "distribution", "as", "a", "Node", "instance" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourcewriter.py#L252-L268
train
233,104
gem/oq-engine
openquake/hazardlib/sourcewriter.py
build_hypo_depth_dist
def build_hypo_depth_dist(hdd): """ Returns the hypocentral depth distribution as a Node instance :param hdd: Hypocentral depth distribution as an instance of :class: `openquake.hzardlib.pmf.PMF` :returns: Instance of :class:`openquake.baselib.node.Node` """ hdds = [] for (prob, depth) in hdd.data: hdds.append( Node("hypoDepth", {"depth": depth, "probability": prob})) return Node("hypoDepthDist", nodes=hdds)
python
def build_hypo_depth_dist(hdd): """ Returns the hypocentral depth distribution as a Node instance :param hdd: Hypocentral depth distribution as an instance of :class: `openquake.hzardlib.pmf.PMF` :returns: Instance of :class:`openquake.baselib.node.Node` """ hdds = [] for (prob, depth) in hdd.data: hdds.append( Node("hypoDepth", {"depth": depth, "probability": prob})) return Node("hypoDepthDist", nodes=hdds)
[ "def", "build_hypo_depth_dist", "(", "hdd", ")", ":", "hdds", "=", "[", "]", "for", "(", "prob", ",", "depth", ")", "in", "hdd", ".", "data", ":", "hdds", ".", "append", "(", "Node", "(", "\"hypoDepth\"", ",", "{", "\"depth\"", ":", "depth", ",", "\"probability\"", ":", "prob", "}", ")", ")", "return", "Node", "(", "\"hypoDepthDist\"", ",", "nodes", "=", "hdds", ")" ]
Returns the hypocentral depth distribution as a Node instance :param hdd: Hypocentral depth distribution as an instance of :class: `openquake.hzardlib.pmf.PMF` :returns: Instance of :class:`openquake.baselib.node.Node`
[ "Returns", "the", "hypocentral", "depth", "distribution", "as", "a", "Node", "instance" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourcewriter.py#L271-L285
train
233,105
gem/oq-engine
openquake/hazardlib/sourcewriter.py
get_distributed_seismicity_source_nodes
def get_distributed_seismicity_source_nodes(source): """ Returns list of nodes of attributes common to all distributed seismicity source classes :param source: Seismic source as instance of :class: `openquake.hazardlib.source.area.AreaSource` or :class: `openquake.hazardlib.source.point.PointSource` :returns: List of instances of :class:`openquake.baselib.node.Node` """ source_nodes = [] # parse msr source_nodes.append( Node("magScaleRel", text=source.magnitude_scaling_relationship.__class__.__name__)) # Parse aspect ratio source_nodes.append( Node("ruptAspectRatio", text=source.rupture_aspect_ratio)) # Parse MFD source_nodes.append(obj_to_node(source.mfd)) # Parse nodal plane distribution source_nodes.append( build_nodal_plane_dist(source.nodal_plane_distribution)) # Parse hypocentral depth distribution source_nodes.append( build_hypo_depth_dist(source.hypocenter_distribution)) return source_nodes
python
def get_distributed_seismicity_source_nodes(source): """ Returns list of nodes of attributes common to all distributed seismicity source classes :param source: Seismic source as instance of :class: `openquake.hazardlib.source.area.AreaSource` or :class: `openquake.hazardlib.source.point.PointSource` :returns: List of instances of :class:`openquake.baselib.node.Node` """ source_nodes = [] # parse msr source_nodes.append( Node("magScaleRel", text=source.magnitude_scaling_relationship.__class__.__name__)) # Parse aspect ratio source_nodes.append( Node("ruptAspectRatio", text=source.rupture_aspect_ratio)) # Parse MFD source_nodes.append(obj_to_node(source.mfd)) # Parse nodal plane distribution source_nodes.append( build_nodal_plane_dist(source.nodal_plane_distribution)) # Parse hypocentral depth distribution source_nodes.append( build_hypo_depth_dist(source.hypocenter_distribution)) return source_nodes
[ "def", "get_distributed_seismicity_source_nodes", "(", "source", ")", ":", "source_nodes", "=", "[", "]", "# parse msr", "source_nodes", ".", "append", "(", "Node", "(", "\"magScaleRel\"", ",", "text", "=", "source", ".", "magnitude_scaling_relationship", ".", "__class__", ".", "__name__", ")", ")", "# Parse aspect ratio", "source_nodes", ".", "append", "(", "Node", "(", "\"ruptAspectRatio\"", ",", "text", "=", "source", ".", "rupture_aspect_ratio", ")", ")", "# Parse MFD", "source_nodes", ".", "append", "(", "obj_to_node", "(", "source", ".", "mfd", ")", ")", "# Parse nodal plane distribution", "source_nodes", ".", "append", "(", "build_nodal_plane_dist", "(", "source", ".", "nodal_plane_distribution", ")", ")", "# Parse hypocentral depth distribution", "source_nodes", ".", "append", "(", "build_hypo_depth_dist", "(", "source", ".", "hypocenter_distribution", ")", ")", "return", "source_nodes" ]
Returns list of nodes of attributes common to all distributed seismicity source classes :param source: Seismic source as instance of :class: `openquake.hazardlib.source.area.AreaSource` or :class: `openquake.hazardlib.source.point.PointSource` :returns: List of instances of :class:`openquake.baselib.node.Node`
[ "Returns", "list", "of", "nodes", "of", "attributes", "common", "to", "all", "distributed", "seismicity", "source", "classes" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourcewriter.py#L288-L316
train
233,106
gem/oq-engine
openquake/hazardlib/sourcewriter.py
get_fault_source_nodes
def get_fault_source_nodes(source): """ Returns list of nodes of attributes common to all fault source classes :param source: Fault source as instance of :class: `openquake.hazardlib.source.simple_fault.SimpleFaultSource` or :class: `openquake.hazardlib.source.complex_fault.ComplexFaultSource` :returns: List of instances of :class:`openquake.baselib.node.Node` """ source_nodes = [] # parse msr source_nodes.append( Node( "magScaleRel", text=source.magnitude_scaling_relationship.__class__.__name__)) # Parse aspect ratio source_nodes.append( Node("ruptAspectRatio", text=source.rupture_aspect_ratio)) # Parse MFD source_nodes.append(obj_to_node(source.mfd)) # Parse Rake source_nodes.append(Node("rake", text=source.rake)) if len(getattr(source, 'hypo_list', [])): source_nodes.append(build_hypo_list_node(source.hypo_list)) if len(getattr(source, 'slip_list', [])): source_nodes.append(build_slip_list_node(source.slip_list)) return source_nodes
python
def get_fault_source_nodes(source): """ Returns list of nodes of attributes common to all fault source classes :param source: Fault source as instance of :class: `openquake.hazardlib.source.simple_fault.SimpleFaultSource` or :class: `openquake.hazardlib.source.complex_fault.ComplexFaultSource` :returns: List of instances of :class:`openquake.baselib.node.Node` """ source_nodes = [] # parse msr source_nodes.append( Node( "magScaleRel", text=source.magnitude_scaling_relationship.__class__.__name__)) # Parse aspect ratio source_nodes.append( Node("ruptAspectRatio", text=source.rupture_aspect_ratio)) # Parse MFD source_nodes.append(obj_to_node(source.mfd)) # Parse Rake source_nodes.append(Node("rake", text=source.rake)) if len(getattr(source, 'hypo_list', [])): source_nodes.append(build_hypo_list_node(source.hypo_list)) if len(getattr(source, 'slip_list', [])): source_nodes.append(build_slip_list_node(source.slip_list)) return source_nodes
[ "def", "get_fault_source_nodes", "(", "source", ")", ":", "source_nodes", "=", "[", "]", "# parse msr", "source_nodes", ".", "append", "(", "Node", "(", "\"magScaleRel\"", ",", "text", "=", "source", ".", "magnitude_scaling_relationship", ".", "__class__", ".", "__name__", ")", ")", "# Parse aspect ratio", "source_nodes", ".", "append", "(", "Node", "(", "\"ruptAspectRatio\"", ",", "text", "=", "source", ".", "rupture_aspect_ratio", ")", ")", "# Parse MFD", "source_nodes", ".", "append", "(", "obj_to_node", "(", "source", ".", "mfd", ")", ")", "# Parse Rake", "source_nodes", ".", "append", "(", "Node", "(", "\"rake\"", ",", "text", "=", "source", ".", "rake", ")", ")", "if", "len", "(", "getattr", "(", "source", ",", "'hypo_list'", ",", "[", "]", ")", ")", ":", "source_nodes", ".", "append", "(", "build_hypo_list_node", "(", "source", ".", "hypo_list", ")", ")", "if", "len", "(", "getattr", "(", "source", ",", "'slip_list'", ",", "[", "]", ")", ")", ":", "source_nodes", ".", "append", "(", "build_slip_list_node", "(", "source", ".", "slip_list", ")", ")", "return", "source_nodes" ]
Returns list of nodes of attributes common to all fault source classes :param source: Fault source as instance of :class: `openquake.hazardlib.source.simple_fault.SimpleFaultSource` or :class: `openquake.hazardlib.source.complex_fault.ComplexFaultSource` :returns: List of instances of :class:`openquake.baselib.node.Node`
[ "Returns", "list", "of", "nodes", "of", "attributes", "common", "to", "all", "fault", "source", "classes" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourcewriter.py#L348-L376
train
233,107
gem/oq-engine
openquake/hazardlib/sourcewriter.py
get_source_attributes
def get_source_attributes(source): """ Retreives a dictionary of source attributes from the source class :param source: Seismic source as instance of :class: `openquake.hazardlib.source.base.BaseSeismicSource` :returns: Dictionary of source attributes """ attrs = {"id": source.source_id, "name": source.name, "tectonicRegion": source.tectonic_region_type} if isinstance(source, NonParametricSeismicSource): if source.data[0][0].weight is not None: weights = [] for data in source.data: weights.append(data[0].weight) attrs['rup_weights'] = numpy.array(weights) print(attrs) return attrs
python
def get_source_attributes(source): """ Retreives a dictionary of source attributes from the source class :param source: Seismic source as instance of :class: `openquake.hazardlib.source.base.BaseSeismicSource` :returns: Dictionary of source attributes """ attrs = {"id": source.source_id, "name": source.name, "tectonicRegion": source.tectonic_region_type} if isinstance(source, NonParametricSeismicSource): if source.data[0][0].weight is not None: weights = [] for data in source.data: weights.append(data[0].weight) attrs['rup_weights'] = numpy.array(weights) print(attrs) return attrs
[ "def", "get_source_attributes", "(", "source", ")", ":", "attrs", "=", "{", "\"id\"", ":", "source", ".", "source_id", ",", "\"name\"", ":", "source", ".", "name", ",", "\"tectonicRegion\"", ":", "source", ".", "tectonic_region_type", "}", "if", "isinstance", "(", "source", ",", "NonParametricSeismicSource", ")", ":", "if", "source", ".", "data", "[", "0", "]", "[", "0", "]", ".", "weight", "is", "not", "None", ":", "weights", "=", "[", "]", "for", "data", "in", "source", ".", "data", ":", "weights", ".", "append", "(", "data", "[", "0", "]", ".", "weight", ")", "attrs", "[", "'rup_weights'", "]", "=", "numpy", ".", "array", "(", "weights", ")", "print", "(", "attrs", ")", "return", "attrs" ]
Retreives a dictionary of source attributes from the source class :param source: Seismic source as instance of :class: `openquake.hazardlib.source.base.BaseSeismicSource` :returns: Dictionary of source attributes
[ "Retreives", "a", "dictionary", "of", "source", "attributes", "from", "the", "source", "class" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourcewriter.py#L379-L399
train
233,108
gem/oq-engine
openquake/hazardlib/sourcewriter.py
build_area_source_node
def build_area_source_node(area_source): """ Parses an area source to a Node class :param area_source: Area source as instance of :class: `openquake.hazardlib.source.area.AreaSource` :returns: Instance of :class:`openquake.baselib.node.Node` """ # parse geometry source_nodes = [build_area_source_geometry(area_source)] # parse common distributed attributes source_nodes.extend(get_distributed_seismicity_source_nodes(area_source)) return Node( "areaSource", get_source_attributes(area_source), nodes=source_nodes)
python
def build_area_source_node(area_source): """ Parses an area source to a Node class :param area_source: Area source as instance of :class: `openquake.hazardlib.source.area.AreaSource` :returns: Instance of :class:`openquake.baselib.node.Node` """ # parse geometry source_nodes = [build_area_source_geometry(area_source)] # parse common distributed attributes source_nodes.extend(get_distributed_seismicity_source_nodes(area_source)) return Node( "areaSource", get_source_attributes(area_source), nodes=source_nodes)
[ "def", "build_area_source_node", "(", "area_source", ")", ":", "# parse geometry", "source_nodes", "=", "[", "build_area_source_geometry", "(", "area_source", ")", "]", "# parse common distributed attributes", "source_nodes", ".", "extend", "(", "get_distributed_seismicity_source_nodes", "(", "area_source", ")", ")", "return", "Node", "(", "\"areaSource\"", ",", "get_source_attributes", "(", "area_source", ")", ",", "nodes", "=", "source_nodes", ")" ]
Parses an area source to a Node class :param area_source: Area source as instance of :class: `openquake.hazardlib.source.area.AreaSource` :returns: Instance of :class:`openquake.baselib.node.Node`
[ "Parses", "an", "area", "source", "to", "a", "Node", "class" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourcewriter.py#L403-L418
train
233,109
gem/oq-engine
openquake/hazardlib/sourcewriter.py
build_simple_fault_source_node
def build_simple_fault_source_node(fault_source): """ Parses a simple fault source to a Node class :param fault_source: Simple fault source as instance of :class: `openquake.hazardlib.source.simple_fault.SimpleFaultSource` :returns: Instance of :class:`openquake.baselib.node.Node` """ # Parse geometry source_nodes = [build_simple_fault_geometry(fault_source)] # Parse common fault source attributes source_nodes.extend(get_fault_source_nodes(fault_source)) return Node("simpleFaultSource", get_source_attributes(fault_source), nodes=source_nodes)
python
def build_simple_fault_source_node(fault_source): """ Parses a simple fault source to a Node class :param fault_source: Simple fault source as instance of :class: `openquake.hazardlib.source.simple_fault.SimpleFaultSource` :returns: Instance of :class:`openquake.baselib.node.Node` """ # Parse geometry source_nodes = [build_simple_fault_geometry(fault_source)] # Parse common fault source attributes source_nodes.extend(get_fault_source_nodes(fault_source)) return Node("simpleFaultSource", get_source_attributes(fault_source), nodes=source_nodes)
[ "def", "build_simple_fault_source_node", "(", "fault_source", ")", ":", "# Parse geometry", "source_nodes", "=", "[", "build_simple_fault_geometry", "(", "fault_source", ")", "]", "# Parse common fault source attributes", "source_nodes", ".", "extend", "(", "get_fault_source_nodes", "(", "fault_source", ")", ")", "return", "Node", "(", "\"simpleFaultSource\"", ",", "get_source_attributes", "(", "fault_source", ")", ",", "nodes", "=", "source_nodes", ")" ]
Parses a simple fault source to a Node class :param fault_source: Simple fault source as instance of :class: `openquake.hazardlib.source.simple_fault.SimpleFaultSource` :returns: Instance of :class:`openquake.baselib.node.Node`
[ "Parses", "a", "simple", "fault", "source", "to", "a", "Node", "class" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourcewriter.py#L524-L540
train
233,110
gem/oq-engine
openquake/hazardlib/sourcewriter.py
build_complex_fault_source_node
def build_complex_fault_source_node(fault_source): """ Parses a complex fault source to a Node class :param fault_source: Simple fault source as instance of :class: `openquake.hazardlib.source.complex_fault.ComplexFaultSource` :returns: Instance of :class:`openquake.baselib.node.Node` """ # Parse geometry source_nodes = [build_complex_fault_geometry(fault_source)] # Parse common fault source attributes source_nodes.extend(get_fault_source_nodes(fault_source)) return Node("complexFaultSource", get_source_attributes(fault_source), nodes=source_nodes)
python
def build_complex_fault_source_node(fault_source): """ Parses a complex fault source to a Node class :param fault_source: Simple fault source as instance of :class: `openquake.hazardlib.source.complex_fault.ComplexFaultSource` :returns: Instance of :class:`openquake.baselib.node.Node` """ # Parse geometry source_nodes = [build_complex_fault_geometry(fault_source)] # Parse common fault source attributes source_nodes.extend(get_fault_source_nodes(fault_source)) return Node("complexFaultSource", get_source_attributes(fault_source), nodes=source_nodes)
[ "def", "build_complex_fault_source_node", "(", "fault_source", ")", ":", "# Parse geometry", "source_nodes", "=", "[", "build_complex_fault_geometry", "(", "fault_source", ")", "]", "# Parse common fault source attributes", "source_nodes", ".", "extend", "(", "get_fault_source_nodes", "(", "fault_source", ")", ")", "return", "Node", "(", "\"complexFaultSource\"", ",", "get_source_attributes", "(", "fault_source", ")", ",", "nodes", "=", "source_nodes", ")" ]
Parses a complex fault source to a Node class :param fault_source: Simple fault source as instance of :class: `openquake.hazardlib.source.complex_fault.ComplexFaultSource` :returns: Instance of :class:`openquake.baselib.node.Node`
[ "Parses", "a", "complex", "fault", "source", "to", "a", "Node", "class" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourcewriter.py#L544-L560
train
233,111
gem/oq-engine
openquake/hazardlib/sourcewriter.py
write_source_model
def write_source_model(dest, sources_or_groups, name=None, investigation_time=None): """ Writes a source model to XML. :param dest: Destination path :param sources_or_groups: Source model in different formats :param name: Name of the source model (if missing, extracted from the filename) """ if isinstance(sources_or_groups, nrml.SourceModel): with open(dest, 'wb') as f: nrml.write([obj_to_node(sources_or_groups)], f, '%s') return if isinstance(sources_or_groups[0], sourceconverter.SourceGroup): groups = sources_or_groups else: # passed a list of sources srcs_by_trt = groupby( sources_or_groups, operator.attrgetter('tectonic_region_type')) groups = [sourceconverter.SourceGroup(trt, srcs_by_trt[trt]) for trt in srcs_by_trt] name = name or os.path.splitext(os.path.basename(dest))[0] nodes = list(map(obj_to_node, sorted(groups))) attrs = {"name": name} if investigation_time is not None: attrs['investigation_time'] = investigation_time source_model = Node("sourceModel", attrs, nodes=nodes) with open(dest, 'wb') as f: nrml.write([source_model], f, '%s') return dest
python
def write_source_model(dest, sources_or_groups, name=None, investigation_time=None): """ Writes a source model to XML. :param dest: Destination path :param sources_or_groups: Source model in different formats :param name: Name of the source model (if missing, extracted from the filename) """ if isinstance(sources_or_groups, nrml.SourceModel): with open(dest, 'wb') as f: nrml.write([obj_to_node(sources_or_groups)], f, '%s') return if isinstance(sources_or_groups[0], sourceconverter.SourceGroup): groups = sources_or_groups else: # passed a list of sources srcs_by_trt = groupby( sources_or_groups, operator.attrgetter('tectonic_region_type')) groups = [sourceconverter.SourceGroup(trt, srcs_by_trt[trt]) for trt in srcs_by_trt] name = name or os.path.splitext(os.path.basename(dest))[0] nodes = list(map(obj_to_node, sorted(groups))) attrs = {"name": name} if investigation_time is not None: attrs['investigation_time'] = investigation_time source_model = Node("sourceModel", attrs, nodes=nodes) with open(dest, 'wb') as f: nrml.write([source_model], f, '%s') return dest
[ "def", "write_source_model", "(", "dest", ",", "sources_or_groups", ",", "name", "=", "None", ",", "investigation_time", "=", "None", ")", ":", "if", "isinstance", "(", "sources_or_groups", ",", "nrml", ".", "SourceModel", ")", ":", "with", "open", "(", "dest", ",", "'wb'", ")", "as", "f", ":", "nrml", ".", "write", "(", "[", "obj_to_node", "(", "sources_or_groups", ")", "]", ",", "f", ",", "'%s'", ")", "return", "if", "isinstance", "(", "sources_or_groups", "[", "0", "]", ",", "sourceconverter", ".", "SourceGroup", ")", ":", "groups", "=", "sources_or_groups", "else", ":", "# passed a list of sources", "srcs_by_trt", "=", "groupby", "(", "sources_or_groups", ",", "operator", ".", "attrgetter", "(", "'tectonic_region_type'", ")", ")", "groups", "=", "[", "sourceconverter", ".", "SourceGroup", "(", "trt", ",", "srcs_by_trt", "[", "trt", "]", ")", "for", "trt", "in", "srcs_by_trt", "]", "name", "=", "name", "or", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "dest", ")", ")", "[", "0", "]", "nodes", "=", "list", "(", "map", "(", "obj_to_node", ",", "sorted", "(", "groups", ")", ")", ")", "attrs", "=", "{", "\"name\"", ":", "name", "}", "if", "investigation_time", "is", "not", "None", ":", "attrs", "[", "'investigation_time'", "]", "=", "investigation_time", "source_model", "=", "Node", "(", "\"sourceModel\"", ",", "attrs", ",", "nodes", "=", "nodes", ")", "with", "open", "(", "dest", ",", "'wb'", ")", "as", "f", ":", "nrml", ".", "write", "(", "[", "source_model", "]", ",", "f", ",", "'%s'", ")", "return", "dest" ]
Writes a source model to XML. :param dest: Destination path :param sources_or_groups: Source model in different formats :param name: Name of the source model (if missing, extracted from the filename)
[ "Writes", "a", "source", "model", "to", "XML", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourcewriter.py#L610-L641
train
233,112
gem/oq-engine
openquake/hazardlib/gsim/sharma_2009.py
SharmaEtAl2009._get_stddevs
def _get_stddevs(self, coeffs, stddev_types, num_sites): """ Return total sigma as reported in Table 2, p. 1202. """ stddevs = [] for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES stddevs.append(coeffs['sigma'] + np.zeros(num_sites)) return np.array(stddevs)
python
def _get_stddevs(self, coeffs, stddev_types, num_sites): """ Return total sigma as reported in Table 2, p. 1202. """ stddevs = [] for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES stddevs.append(coeffs['sigma'] + np.zeros(num_sites)) return np.array(stddevs)
[ "def", "_get_stddevs", "(", "self", ",", "coeffs", ",", "stddev_types", ",", "num_sites", ")", ":", "stddevs", "=", "[", "]", "for", "stddev_type", "in", "stddev_types", ":", "assert", "stddev_type", "in", "self", ".", "DEFINED_FOR_STANDARD_DEVIATION_TYPES", "stddevs", ".", "append", "(", "coeffs", "[", "'sigma'", "]", "+", "np", ".", "zeros", "(", "num_sites", ")", ")", "return", "np", ".", "array", "(", "stddevs", ")" ]
Return total sigma as reported in Table 2, p. 1202.
[ "Return", "total", "sigma", "as", "reported", "in", "Table", "2", "p", ".", "1202", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/sharma_2009.py#L121-L129
train
233,113
gem/oq-engine
openquake/hazardlib/gsim/sharma_2009.py
SharmaEtAl2009.get_fault_type_dummy_variables
def get_fault_type_dummy_variables(self, rup): """ Fault-type classification dummy variable based on rup.rake. "``H`` is 1 for a strike-slip mechanism and 0 for a reverse mechanism" (p. 1201). Note: UserWarning is raised if mechanism is determined to be normal faulting, since as summarized in Table 2 on p. 1197 the data used for regression included only reverse and stike-slip events. """ # normal faulting is_normal = np.array( self.RAKE_THRESH < -rup.rake < (180. - self.RAKE_THRESH)) # reverse raulting is_reverse = np.array( self.RAKE_THRESH < rup.rake < (180. - self.RAKE_THRESH)) if not self.ALREADY_WARNED and is_normal.any(): # make sure that the warning is printed only once to avoid # flooding the terminal msg = ('Normal faulting not supported by %s; ' 'treating as strike-slip' % type(self).__name__) warnings.warn(msg, UserWarning) self.ALREADY_WARNED = True is_strike_slip = ~is_reverse | is_normal is_strike_slip = is_strike_slip.astype(float) return is_strike_slip
python
def get_fault_type_dummy_variables(self, rup): """ Fault-type classification dummy variable based on rup.rake. "``H`` is 1 for a strike-slip mechanism and 0 for a reverse mechanism" (p. 1201). Note: UserWarning is raised if mechanism is determined to be normal faulting, since as summarized in Table 2 on p. 1197 the data used for regression included only reverse and stike-slip events. """ # normal faulting is_normal = np.array( self.RAKE_THRESH < -rup.rake < (180. - self.RAKE_THRESH)) # reverse raulting is_reverse = np.array( self.RAKE_THRESH < rup.rake < (180. - self.RAKE_THRESH)) if not self.ALREADY_WARNED and is_normal.any(): # make sure that the warning is printed only once to avoid # flooding the terminal msg = ('Normal faulting not supported by %s; ' 'treating as strike-slip' % type(self).__name__) warnings.warn(msg, UserWarning) self.ALREADY_WARNED = True is_strike_slip = ~is_reverse | is_normal is_strike_slip = is_strike_slip.astype(float) return is_strike_slip
[ "def", "get_fault_type_dummy_variables", "(", "self", ",", "rup", ")", ":", "# normal faulting", "is_normal", "=", "np", ".", "array", "(", "self", ".", "RAKE_THRESH", "<", "-", "rup", ".", "rake", "<", "(", "180.", "-", "self", ".", "RAKE_THRESH", ")", ")", "# reverse raulting", "is_reverse", "=", "np", ".", "array", "(", "self", ".", "RAKE_THRESH", "<", "rup", ".", "rake", "<", "(", "180.", "-", "self", ".", "RAKE_THRESH", ")", ")", "if", "not", "self", ".", "ALREADY_WARNED", "and", "is_normal", ".", "any", "(", ")", ":", "# make sure that the warning is printed only once to avoid", "# flooding the terminal", "msg", "=", "(", "'Normal faulting not supported by %s; '", "'treating as strike-slip'", "%", "type", "(", "self", ")", ".", "__name__", ")", "warnings", ".", "warn", "(", "msg", ",", "UserWarning", ")", "self", ".", "ALREADY_WARNED", "=", "True", "is_strike_slip", "=", "~", "is_reverse", "|", "is_normal", "is_strike_slip", "=", "is_strike_slip", ".", "astype", "(", "float", ")", "return", "is_strike_slip" ]
Fault-type classification dummy variable based on rup.rake. "``H`` is 1 for a strike-slip mechanism and 0 for a reverse mechanism" (p. 1201). Note: UserWarning is raised if mechanism is determined to be normal faulting, since as summarized in Table 2 on p. 1197 the data used for regression included only reverse and stike-slip events.
[ "Fault", "-", "type", "classification", "dummy", "variable", "based", "on", "rup", ".", "rake", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/sharma_2009.py#L176-L208
train
233,114
gem/oq-engine
openquake/hmtk/parsers/strain/strain_csv_parser.py
ReadStrainCsv.read_data
def read_data(self, scaling_factor=1E-9, strain_headers=None): ''' Reads the data from the csv file :param float scaling_factor: Scaling factor used for all strain values (default 1E-9 for nanostrain) :param list strain_headers: List of the variables in the file that correspond to strain parameters :returns: strain - Strain model as an instance of the :class: openquake.hmtk.strain.geodetic_strain.GeodeticStrain ''' if strain_headers: self.strain.data_variables = strain_headers else: self.strain.data_variables = STRAIN_VARIABLES datafile = open(self.filename, 'r') reader = csv.DictReader(datafile) self.strain.data = dict([(name, []) for name in reader.fieldnames]) for row in reader: for name in row.keys(): if 'region' in name.lower(): self.strain.data[name].append(row[name]) elif name in self.strain.data_variables: self.strain.data[name].append( scaling_factor * float(row[name])) else: self.strain.data[name].append(float(row[name])) for key in self.strain.data.keys(): if 'region' in key: self.strain.data[key] = np.array(self.strain.data[key], dtype='S13') else: self.strain.data[key] = np.array(self.strain.data[key]) self._check_invalid_longitudes() if 'region' not in self.strain.data: print('No tectonic regionalisation found in input file!') self.strain.data_variables = self.strain.data.keys() # Update data with secondary data (i.e. 2nd invariant, e1h, e2h etc. self.strain.get_secondary_strain_data() return self.strain
python
def read_data(self, scaling_factor=1E-9, strain_headers=None): ''' Reads the data from the csv file :param float scaling_factor: Scaling factor used for all strain values (default 1E-9 for nanostrain) :param list strain_headers: List of the variables in the file that correspond to strain parameters :returns: strain - Strain model as an instance of the :class: openquake.hmtk.strain.geodetic_strain.GeodeticStrain ''' if strain_headers: self.strain.data_variables = strain_headers else: self.strain.data_variables = STRAIN_VARIABLES datafile = open(self.filename, 'r') reader = csv.DictReader(datafile) self.strain.data = dict([(name, []) for name in reader.fieldnames]) for row in reader: for name in row.keys(): if 'region' in name.lower(): self.strain.data[name].append(row[name]) elif name in self.strain.data_variables: self.strain.data[name].append( scaling_factor * float(row[name])) else: self.strain.data[name].append(float(row[name])) for key in self.strain.data.keys(): if 'region' in key: self.strain.data[key] = np.array(self.strain.data[key], dtype='S13') else: self.strain.data[key] = np.array(self.strain.data[key]) self._check_invalid_longitudes() if 'region' not in self.strain.data: print('No tectonic regionalisation found in input file!') self.strain.data_variables = self.strain.data.keys() # Update data with secondary data (i.e. 2nd invariant, e1h, e2h etc. self.strain.get_secondary_strain_data() return self.strain
[ "def", "read_data", "(", "self", ",", "scaling_factor", "=", "1E-9", ",", "strain_headers", "=", "None", ")", ":", "if", "strain_headers", ":", "self", ".", "strain", ".", "data_variables", "=", "strain_headers", "else", ":", "self", ".", "strain", ".", "data_variables", "=", "STRAIN_VARIABLES", "datafile", "=", "open", "(", "self", ".", "filename", ",", "'r'", ")", "reader", "=", "csv", ".", "DictReader", "(", "datafile", ")", "self", ".", "strain", ".", "data", "=", "dict", "(", "[", "(", "name", ",", "[", "]", ")", "for", "name", "in", "reader", ".", "fieldnames", "]", ")", "for", "row", "in", "reader", ":", "for", "name", "in", "row", ".", "keys", "(", ")", ":", "if", "'region'", "in", "name", ".", "lower", "(", ")", ":", "self", ".", "strain", ".", "data", "[", "name", "]", ".", "append", "(", "row", "[", "name", "]", ")", "elif", "name", "in", "self", ".", "strain", ".", "data_variables", ":", "self", ".", "strain", ".", "data", "[", "name", "]", ".", "append", "(", "scaling_factor", "*", "float", "(", "row", "[", "name", "]", ")", ")", "else", ":", "self", ".", "strain", ".", "data", "[", "name", "]", ".", "append", "(", "float", "(", "row", "[", "name", "]", ")", ")", "for", "key", "in", "self", ".", "strain", ".", "data", ".", "keys", "(", ")", ":", "if", "'region'", "in", "key", ":", "self", ".", "strain", ".", "data", "[", "key", "]", "=", "np", ".", "array", "(", "self", ".", "strain", ".", "data", "[", "key", "]", ",", "dtype", "=", "'S13'", ")", "else", ":", "self", ".", "strain", ".", "data", "[", "key", "]", "=", "np", ".", "array", "(", "self", ".", "strain", ".", "data", "[", "key", "]", ")", "self", ".", "_check_invalid_longitudes", "(", ")", "if", "'region'", "not", "in", "self", ".", "strain", ".", "data", ":", "print", "(", "'No tectonic regionalisation found in input file!'", ")", "self", ".", "strain", ".", "data_variables", "=", "self", ".", "strain", ".", "data", ".", "keys", "(", ")", "# Update data with secondary data (i.e. 2nd invariant, e1h, e2h etc.", "self", ".", "strain", ".", "get_secondary_strain_data", "(", ")", "return", "self", ".", "strain" ]
Reads the data from the csv file :param float scaling_factor: Scaling factor used for all strain values (default 1E-9 for nanostrain) :param list strain_headers: List of the variables in the file that correspond to strain parameters :returns: strain - Strain model as an instance of the :class: openquake.hmtk.strain.geodetic_strain.GeodeticStrain
[ "Reads", "the", "data", "from", "the", "csv", "file" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/strain/strain_csv_parser.py#L82-L132
train
233,115
gem/oq-engine
openquake/hmtk/parsers/strain/strain_csv_parser.py
ReadStrainCsv._check_invalid_longitudes
def _check_invalid_longitudes(self): ''' Checks to ensure that all longitudes are in the range -180. to 180 ''' idlon = self.strain.data['longitude'] > 180. if np.any(idlon): self.strain.data['longitude'][idlon] = \ self.strain.data['longitude'][idlon] - 360.
python
def _check_invalid_longitudes(self): ''' Checks to ensure that all longitudes are in the range -180. to 180 ''' idlon = self.strain.data['longitude'] > 180. if np.any(idlon): self.strain.data['longitude'][idlon] = \ self.strain.data['longitude'][idlon] - 360.
[ "def", "_check_invalid_longitudes", "(", "self", ")", ":", "idlon", "=", "self", ".", "strain", ".", "data", "[", "'longitude'", "]", ">", "180.", "if", "np", ".", "any", "(", "idlon", ")", ":", "self", ".", "strain", ".", "data", "[", "'longitude'", "]", "[", "idlon", "]", "=", "self", ".", "strain", ".", "data", "[", "'longitude'", "]", "[", "idlon", "]", "-", "360." ]
Checks to ensure that all longitudes are in the range -180. to 180
[ "Checks", "to", "ensure", "that", "all", "longitudes", "are", "in", "the", "range", "-", "180", ".", "to", "180" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/strain/strain_csv_parser.py#L134-L141
train
233,116
gem/oq-engine
openquake/hmtk/parsers/strain/strain_csv_parser.py
WriteStrainCsv.write_file
def write_file(self, strain, scaling_factor=1E-9): ''' Main writer function for the csv file :param strain: Instance of :class: openquake.hmtk.strain.geodetic_strain.GeodeticStrain :param float scaling_factor: Scaling factor used for all strain values (default 1E-9 for nanostrain) ''' if not isinstance(strain, GeodeticStrain): raise ValueError('Strain data must be instance of GeodeticStrain') for key in strain.data.keys(): if key in strain.data_variables: # Return strain value back to original scaling if key in ['longitude', 'latitude']: continue strain.data[key] = strain.data[key] / scaling_factor # Slice seismicity rates into separate dictionary vectors strain, output_variables = self.slice_rates_to_data(strain) outfile = open(self.filename, 'wt') print('Writing strain data to file %s' % self.filename) writer = csv.DictWriter(outfile, fieldnames=output_variables) writer.writeheader() for iloc in range(0, strain.get_number_observations()): row_dict = {} for key in output_variables: if len(strain.data[key]) > 0: # Ignores empty dictionary attributes row_dict[key] = strain.data[key][iloc] writer.writerow(row_dict) outfile.close() print('done!')
python
def write_file(self, strain, scaling_factor=1E-9): ''' Main writer function for the csv file :param strain: Instance of :class: openquake.hmtk.strain.geodetic_strain.GeodeticStrain :param float scaling_factor: Scaling factor used for all strain values (default 1E-9 for nanostrain) ''' if not isinstance(strain, GeodeticStrain): raise ValueError('Strain data must be instance of GeodeticStrain') for key in strain.data.keys(): if key in strain.data_variables: # Return strain value back to original scaling if key in ['longitude', 'latitude']: continue strain.data[key] = strain.data[key] / scaling_factor # Slice seismicity rates into separate dictionary vectors strain, output_variables = self.slice_rates_to_data(strain) outfile = open(self.filename, 'wt') print('Writing strain data to file %s' % self.filename) writer = csv.DictWriter(outfile, fieldnames=output_variables) writer.writeheader() for iloc in range(0, strain.get_number_observations()): row_dict = {} for key in output_variables: if len(strain.data[key]) > 0: # Ignores empty dictionary attributes row_dict[key] = strain.data[key][iloc] writer.writerow(row_dict) outfile.close() print('done!')
[ "def", "write_file", "(", "self", ",", "strain", ",", "scaling_factor", "=", "1E-9", ")", ":", "if", "not", "isinstance", "(", "strain", ",", "GeodeticStrain", ")", ":", "raise", "ValueError", "(", "'Strain data must be instance of GeodeticStrain'", ")", "for", "key", "in", "strain", ".", "data", ".", "keys", "(", ")", ":", "if", "key", "in", "strain", ".", "data_variables", ":", "# Return strain value back to original scaling", "if", "key", "in", "[", "'longitude'", ",", "'latitude'", "]", ":", "continue", "strain", ".", "data", "[", "key", "]", "=", "strain", ".", "data", "[", "key", "]", "/", "scaling_factor", "# Slice seismicity rates into separate dictionary vectors", "strain", ",", "output_variables", "=", "self", ".", "slice_rates_to_data", "(", "strain", ")", "outfile", "=", "open", "(", "self", ".", "filename", ",", "'wt'", ")", "print", "(", "'Writing strain data to file %s'", "%", "self", ".", "filename", ")", "writer", "=", "csv", ".", "DictWriter", "(", "outfile", ",", "fieldnames", "=", "output_variables", ")", "writer", ".", "writeheader", "(", ")", "for", "iloc", "in", "range", "(", "0", ",", "strain", ".", "get_number_observations", "(", ")", ")", ":", "row_dict", "=", "{", "}", "for", "key", "in", "output_variables", ":", "if", "len", "(", "strain", ".", "data", "[", "key", "]", ")", ">", "0", ":", "# Ignores empty dictionary attributes", "row_dict", "[", "key", "]", "=", "strain", ".", "data", "[", "key", "]", "[", "iloc", "]", "writer", ".", "writerow", "(", "row_dict", ")", "outfile", ".", "close", "(", ")", "print", "(", "'done!'", ")" ]
Main writer function for the csv file :param strain: Instance of :class: openquake.hmtk.strain.geodetic_strain.GeodeticStrain :param float scaling_factor: Scaling factor used for all strain values (default 1E-9 for nanostrain)
[ "Main", "writer", "function", "for", "the", "csv", "file" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/strain/strain_csv_parser.py#L160-L196
train
233,117
gem/oq-engine
openquake/hmtk/parsers/strain/strain_csv_parser.py
WriteStrainCsv.slice_rates_to_data
def slice_rates_to_data(self, strain): ''' For the strain data, checks to see if seismicity rates have been calculated. If so, each column in the array is sliced and stored as a single vector in the strain.data dictionary with the corresponding magnitude as a key. :param strain: Instance of :class: openquake.hmtk.strain.geodetic_strain.GeodeticStrain :returns: strain - Instance of strain class with updated data dictionary output_variables - Updated list of headers ''' output_variables = list(strain.data) cond = (isinstance(strain.target_magnitudes, np.ndarray) or isinstance(strain.target_magnitudes, list)) if cond: magnitude_list = ['%.3f' % mag for mag in strain.target_magnitudes] else: return strain, output_variables # Ensure that the number of rows in the rate array corresponds to the # number of observations assert np.shape(strain.seismicity_rate)[0] == \ strain.get_number_observations() for iloc, magnitude in enumerate(magnitude_list): strain.data[magnitude] = strain.seismicity_rate[:, iloc] output_variables.extend(magnitude_list) return strain, output_variables
python
def slice_rates_to_data(self, strain): ''' For the strain data, checks to see if seismicity rates have been calculated. If so, each column in the array is sliced and stored as a single vector in the strain.data dictionary with the corresponding magnitude as a key. :param strain: Instance of :class: openquake.hmtk.strain.geodetic_strain.GeodeticStrain :returns: strain - Instance of strain class with updated data dictionary output_variables - Updated list of headers ''' output_variables = list(strain.data) cond = (isinstance(strain.target_magnitudes, np.ndarray) or isinstance(strain.target_magnitudes, list)) if cond: magnitude_list = ['%.3f' % mag for mag in strain.target_magnitudes] else: return strain, output_variables # Ensure that the number of rows in the rate array corresponds to the # number of observations assert np.shape(strain.seismicity_rate)[0] == \ strain.get_number_observations() for iloc, magnitude in enumerate(magnitude_list): strain.data[magnitude] = strain.seismicity_rate[:, iloc] output_variables.extend(magnitude_list) return strain, output_variables
[ "def", "slice_rates_to_data", "(", "self", ",", "strain", ")", ":", "output_variables", "=", "list", "(", "strain", ".", "data", ")", "cond", "=", "(", "isinstance", "(", "strain", ".", "target_magnitudes", ",", "np", ".", "ndarray", ")", "or", "isinstance", "(", "strain", ".", "target_magnitudes", ",", "list", ")", ")", "if", "cond", ":", "magnitude_list", "=", "[", "'%.3f'", "%", "mag", "for", "mag", "in", "strain", ".", "target_magnitudes", "]", "else", ":", "return", "strain", ",", "output_variables", "# Ensure that the number of rows in the rate array corresponds to the", "# number of observations", "assert", "np", ".", "shape", "(", "strain", ".", "seismicity_rate", ")", "[", "0", "]", "==", "strain", ".", "get_number_observations", "(", ")", "for", "iloc", ",", "magnitude", "in", "enumerate", "(", "magnitude_list", ")", ":", "strain", ".", "data", "[", "magnitude", "]", "=", "strain", ".", "seismicity_rate", "[", ":", ",", "iloc", "]", "output_variables", ".", "extend", "(", "magnitude_list", ")", "return", "strain", ",", "output_variables" ]
For the strain data, checks to see if seismicity rates have been calculated. If so, each column in the array is sliced and stored as a single vector in the strain.data dictionary with the corresponding magnitude as a key. :param strain: Instance of :class: openquake.hmtk.strain.geodetic_strain.GeodeticStrain :returns: strain - Instance of strain class with updated data dictionary output_variables - Updated list of headers
[ "For", "the", "strain", "data", "checks", "to", "see", "if", "seismicity", "rates", "have", "been", "calculated", ".", "If", "so", "each", "column", "in", "the", "array", "is", "sliced", "and", "stored", "as", "a", "single", "vector", "in", "the", "strain", ".", "data", "dictionary", "with", "the", "corresponding", "magnitude", "as", "a", "key", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/strain/strain_csv_parser.py#L198-L228
train
233,118
gem/oq-engine
openquake/baselib/__init__.py
read
def read(*paths, **validators): """ Load the configuration, make each section available in a separate dict. The configuration location can specified via an environment variable: - OQ_CONFIG_FILE In the absence of this environment variable the following paths will be used: - sys.prefix + /openquake.cfg when in a virtualenv - /etc/openquake/openquake.cfg outside of a virtualenv If those files are missing, the fallback is the source code: - openquake/engine/openquake.cfg Please note: settings in the site configuration file are overridden by settings with the same key names in the OQ_CONFIG_FILE openquake.cfg. """ paths = config.paths + list(paths) parser = configparser.ConfigParser() found = parser.read(os.path.normpath(os.path.expanduser(p)) for p in paths) if not found: raise IOError('No configuration file found in %s' % str(paths)) config.found = found config.clear() for section in parser.sections(): config[section] = sec = DotDict(parser.items(section)) for k, v in sec.items(): sec[k] = validators.get(k, lambda x: x)(v)
python
def read(*paths, **validators): """ Load the configuration, make each section available in a separate dict. The configuration location can specified via an environment variable: - OQ_CONFIG_FILE In the absence of this environment variable the following paths will be used: - sys.prefix + /openquake.cfg when in a virtualenv - /etc/openquake/openquake.cfg outside of a virtualenv If those files are missing, the fallback is the source code: - openquake/engine/openquake.cfg Please note: settings in the site configuration file are overridden by settings with the same key names in the OQ_CONFIG_FILE openquake.cfg. """ paths = config.paths + list(paths) parser = configparser.ConfigParser() found = parser.read(os.path.normpath(os.path.expanduser(p)) for p in paths) if not found: raise IOError('No configuration file found in %s' % str(paths)) config.found = found config.clear() for section in parser.sections(): config[section] = sec = DotDict(parser.items(section)) for k, v in sec.items(): sec[k] = validators.get(k, lambda x: x)(v)
[ "def", "read", "(", "*", "paths", ",", "*", "*", "validators", ")", ":", "paths", "=", "config", ".", "paths", "+", "list", "(", "paths", ")", "parser", "=", "configparser", ".", "ConfigParser", "(", ")", "found", "=", "parser", ".", "read", "(", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "expanduser", "(", "p", ")", ")", "for", "p", "in", "paths", ")", "if", "not", "found", ":", "raise", "IOError", "(", "'No configuration file found in %s'", "%", "str", "(", "paths", ")", ")", "config", ".", "found", "=", "found", "config", ".", "clear", "(", ")", "for", "section", "in", "parser", ".", "sections", "(", ")", ":", "config", "[", "section", "]", "=", "sec", "=", "DotDict", "(", "parser", ".", "items", "(", "section", ")", ")", "for", "k", ",", "v", "in", "sec", ".", "items", "(", ")", ":", "sec", "[", "k", "]", "=", "validators", ".", "get", "(", "k", ",", "lambda", "x", ":", "x", ")", "(", "v", ")" ]
Load the configuration, make each section available in a separate dict. The configuration location can specified via an environment variable: - OQ_CONFIG_FILE In the absence of this environment variable the following paths will be used: - sys.prefix + /openquake.cfg when in a virtualenv - /etc/openquake/openquake.cfg outside of a virtualenv If those files are missing, the fallback is the source code: - openquake/engine/openquake.cfg Please note: settings in the site configuration file are overridden by settings with the same key names in the OQ_CONFIG_FILE openquake.cfg.
[ "Load", "the", "configuration", "make", "each", "section", "available", "in", "a", "separate", "dict", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/__init__.py#L56-L84
train
233,119
gem/oq-engine
openquake/baselib/__init__.py
boolean
def boolean(flag): """ Convert string in boolean """ s = flag.lower() if s in ('1', 'yes', 'true'): return True elif s in ('0', 'no', 'false'): return False raise ValueError('Unknown flag %r' % s)
python
def boolean(flag): """ Convert string in boolean """ s = flag.lower() if s in ('1', 'yes', 'true'): return True elif s in ('0', 'no', 'false'): return False raise ValueError('Unknown flag %r' % s)
[ "def", "boolean", "(", "flag", ")", ":", "s", "=", "flag", ".", "lower", "(", ")", "if", "s", "in", "(", "'1'", ",", "'yes'", ",", "'true'", ")", ":", "return", "True", "elif", "s", "in", "(", "'0'", ",", "'no'", ",", "'false'", ")", ":", "return", "False", "raise", "ValueError", "(", "'Unknown flag %r'", "%", "s", ")" ]
Convert string in boolean
[ "Convert", "string", "in", "boolean" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/__init__.py#L90-L99
train
233,120
gem/oq-engine
openquake/hazardlib/gsim/atkinson_boore_2006.py
AtkinsonBoore2006._get_mean
def _get_mean(self, vs30, mag, rrup, imt, scale_fac): """ Compute and return mean """ C_HR, C_BC, C_SR, SC = self._extract_coeffs(imt) rrup = self._clip_distances(rrup) f0 = self._compute_f0_factor(rrup) f1 = self._compute_f1_factor(rrup) f2 = self._compute_f2_factor(rrup) pga_bc = self._get_pga_bc( f0, f1, f2, SC, mag, rrup, vs30, scale_fac ) # compute mean values for hard-rock sites (vs30 >= 2000), # and non-hard-rock sites (vs30 < 2000) and add soil amplification # term mean = np.zeros_like(vs30) self._compute_mean(C_HR, f0, f1, f2, SC, mag, rrup, vs30 >= 2000.0, mean, scale_fac) self._compute_mean(C_BC, f0, f1, f2, SC, mag, rrup, vs30 < 2000.0, mean, scale_fac) self._compute_soil_amplification(C_SR, vs30, pga_bc, mean) # convert from base 10 to base e if imt == PGV(): mean = np.log(10 ** mean) else: # convert from cm/s**2 to g mean = np.log((10 ** mean) * 1e-2 / g) return mean
python
def _get_mean(self, vs30, mag, rrup, imt, scale_fac): """ Compute and return mean """ C_HR, C_BC, C_SR, SC = self._extract_coeffs(imt) rrup = self._clip_distances(rrup) f0 = self._compute_f0_factor(rrup) f1 = self._compute_f1_factor(rrup) f2 = self._compute_f2_factor(rrup) pga_bc = self._get_pga_bc( f0, f1, f2, SC, mag, rrup, vs30, scale_fac ) # compute mean values for hard-rock sites (vs30 >= 2000), # and non-hard-rock sites (vs30 < 2000) and add soil amplification # term mean = np.zeros_like(vs30) self._compute_mean(C_HR, f0, f1, f2, SC, mag, rrup, vs30 >= 2000.0, mean, scale_fac) self._compute_mean(C_BC, f0, f1, f2, SC, mag, rrup, vs30 < 2000.0, mean, scale_fac) self._compute_soil_amplification(C_SR, vs30, pga_bc, mean) # convert from base 10 to base e if imt == PGV(): mean = np.log(10 ** mean) else: # convert from cm/s**2 to g mean = np.log((10 ** mean) * 1e-2 / g) return mean
[ "def", "_get_mean", "(", "self", ",", "vs30", ",", "mag", ",", "rrup", ",", "imt", ",", "scale_fac", ")", ":", "C_HR", ",", "C_BC", ",", "C_SR", ",", "SC", "=", "self", ".", "_extract_coeffs", "(", "imt", ")", "rrup", "=", "self", ".", "_clip_distances", "(", "rrup", ")", "f0", "=", "self", ".", "_compute_f0_factor", "(", "rrup", ")", "f1", "=", "self", ".", "_compute_f1_factor", "(", "rrup", ")", "f2", "=", "self", ".", "_compute_f2_factor", "(", "rrup", ")", "pga_bc", "=", "self", ".", "_get_pga_bc", "(", "f0", ",", "f1", ",", "f2", ",", "SC", ",", "mag", ",", "rrup", ",", "vs30", ",", "scale_fac", ")", "# compute mean values for hard-rock sites (vs30 >= 2000),", "# and non-hard-rock sites (vs30 < 2000) and add soil amplification", "# term", "mean", "=", "np", ".", "zeros_like", "(", "vs30", ")", "self", ".", "_compute_mean", "(", "C_HR", ",", "f0", ",", "f1", ",", "f2", ",", "SC", ",", "mag", ",", "rrup", ",", "vs30", ">=", "2000.0", ",", "mean", ",", "scale_fac", ")", "self", ".", "_compute_mean", "(", "C_BC", ",", "f0", ",", "f1", ",", "f2", ",", "SC", ",", "mag", ",", "rrup", ",", "vs30", "<", "2000.0", ",", "mean", ",", "scale_fac", ")", "self", ".", "_compute_soil_amplification", "(", "C_SR", ",", "vs30", ",", "pga_bc", ",", "mean", ")", "# convert from base 10 to base e", "if", "imt", "==", "PGV", "(", ")", ":", "mean", "=", "np", ".", "log", "(", "10", "**", "mean", ")", "else", ":", "# convert from cm/s**2 to g", "mean", "=", "np", ".", "log", "(", "(", "10", "**", "mean", ")", "*", "1e-2", "/", "g", ")", "return", "mean" ]
Compute and return mean
[ "Compute", "and", "return", "mean" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/atkinson_boore_2006.py#L109-L142
train
233,121
gem/oq-engine
openquake/hazardlib/gsim/atkinson_boore_2006.py
AtkinsonBoore2006._get_pga_bc
def _get_pga_bc(self, f0, f1, f2, SC, mag, rrup, vs30, scale_fac): """ Compute and return PGA on BC boundary """ pga_bc = np.zeros_like(vs30) self._compute_mean(self.COEFFS_BC[PGA()], f0, f1, f2, SC, mag, rrup, vs30 < 2000.0, pga_bc, scale_fac) return (10 ** pga_bc) * 1e-2 / g
python
def _get_pga_bc(self, f0, f1, f2, SC, mag, rrup, vs30, scale_fac): """ Compute and return PGA on BC boundary """ pga_bc = np.zeros_like(vs30) self._compute_mean(self.COEFFS_BC[PGA()], f0, f1, f2, SC, mag, rrup, vs30 < 2000.0, pga_bc, scale_fac) return (10 ** pga_bc) * 1e-2 / g
[ "def", "_get_pga_bc", "(", "self", ",", "f0", ",", "f1", ",", "f2", ",", "SC", ",", "mag", ",", "rrup", ",", "vs30", ",", "scale_fac", ")", ":", "pga_bc", "=", "np", ".", "zeros_like", "(", "vs30", ")", "self", ".", "_compute_mean", "(", "self", ".", "COEFFS_BC", "[", "PGA", "(", ")", "]", ",", "f0", ",", "f1", ",", "f2", ",", "SC", ",", "mag", ",", "rrup", ",", "vs30", "<", "2000.0", ",", "pga_bc", ",", "scale_fac", ")", "return", "(", "10", "**", "pga_bc", ")", "*", "1e-2", "/", "g" ]
Compute and return PGA on BC boundary
[ "Compute", "and", "return", "PGA", "on", "BC", "boundary" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/atkinson_boore_2006.py#L144-L152
train
233,122
gem/oq-engine
openquake/hazardlib/gsim/atkinson_boore_2006.py
AtkinsonBoore2006._extract_coeffs
def _extract_coeffs(self, imt): """ Extract dictionaries of coefficients specific to required intensity measure type. """ C_HR = self.COEFFS_HARD_ROCK[imt] C_BC = self.COEFFS_BC[imt] C_SR = self.COEFFS_SOIL_RESPONSE[imt] SC = self.COEFFS_STRESS[imt] return C_HR, C_BC, C_SR, SC
python
def _extract_coeffs(self, imt): """ Extract dictionaries of coefficients specific to required intensity measure type. """ C_HR = self.COEFFS_HARD_ROCK[imt] C_BC = self.COEFFS_BC[imt] C_SR = self.COEFFS_SOIL_RESPONSE[imt] SC = self.COEFFS_STRESS[imt] return C_HR, C_BC, C_SR, SC
[ "def", "_extract_coeffs", "(", "self", ",", "imt", ")", ":", "C_HR", "=", "self", ".", "COEFFS_HARD_ROCK", "[", "imt", "]", "C_BC", "=", "self", ".", "COEFFS_BC", "[", "imt", "]", "C_SR", "=", "self", ".", "COEFFS_SOIL_RESPONSE", "[", "imt", "]", "SC", "=", "self", ".", "COEFFS_STRESS", "[", "imt", "]", "return", "C_HR", ",", "C_BC", ",", "C_SR", ",", "SC" ]
Extract dictionaries of coefficients specific to required intensity measure type.
[ "Extract", "dictionaries", "of", "coefficients", "specific", "to", "required", "intensity", "measure", "type", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/atkinson_boore_2006.py#L154-L164
train
233,123
gem/oq-engine
openquake/calculators/getters.py
PmapGetter.init
def init(self): """ Read the poes and set the .data attribute with the hazard curves """ if hasattr(self, 'data'): # already initialized return if isinstance(self.dstore, str): self.dstore = hdf5.File(self.dstore, 'r') else: self.dstore.open('r') # if not if self.sids is None: self.sids = self.dstore['sitecol'].sids oq = self.dstore['oqparam'] self.imtls = oq.imtls self.poes = self.poes or oq.poes self.data = {} try: hcurves = self.get_hcurves(self.imtls) # shape (R, N) except IndexError: # no data return for sid, hcurve_by_rlz in zip(self.sids, hcurves.T): self.data[sid] = datadict = {} for rlzi, hcurve in enumerate(hcurve_by_rlz): datadict[rlzi] = lst = [None for imt in self.imtls] for imti, imt in enumerate(self.imtls): lst[imti] = hcurve[imt]
python
def init(self): """ Read the poes and set the .data attribute with the hazard curves """ if hasattr(self, 'data'): # already initialized return if isinstance(self.dstore, str): self.dstore = hdf5.File(self.dstore, 'r') else: self.dstore.open('r') # if not if self.sids is None: self.sids = self.dstore['sitecol'].sids oq = self.dstore['oqparam'] self.imtls = oq.imtls self.poes = self.poes or oq.poes self.data = {} try: hcurves = self.get_hcurves(self.imtls) # shape (R, N) except IndexError: # no data return for sid, hcurve_by_rlz in zip(self.sids, hcurves.T): self.data[sid] = datadict = {} for rlzi, hcurve in enumerate(hcurve_by_rlz): datadict[rlzi] = lst = [None for imt in self.imtls] for imti, imt in enumerate(self.imtls): lst[imti] = hcurve[imt]
[ "def", "init", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'data'", ")", ":", "# already initialized", "return", "if", "isinstance", "(", "self", ".", "dstore", ",", "str", ")", ":", "self", ".", "dstore", "=", "hdf5", ".", "File", "(", "self", ".", "dstore", ",", "'r'", ")", "else", ":", "self", ".", "dstore", ".", "open", "(", "'r'", ")", "# if not", "if", "self", ".", "sids", "is", "None", ":", "self", ".", "sids", "=", "self", ".", "dstore", "[", "'sitecol'", "]", ".", "sids", "oq", "=", "self", ".", "dstore", "[", "'oqparam'", "]", "self", ".", "imtls", "=", "oq", ".", "imtls", "self", ".", "poes", "=", "self", ".", "poes", "or", "oq", ".", "poes", "self", ".", "data", "=", "{", "}", "try", ":", "hcurves", "=", "self", ".", "get_hcurves", "(", "self", ".", "imtls", ")", "# shape (R, N)", "except", "IndexError", ":", "# no data", "return", "for", "sid", ",", "hcurve_by_rlz", "in", "zip", "(", "self", ".", "sids", ",", "hcurves", ".", "T", ")", ":", "self", ".", "data", "[", "sid", "]", "=", "datadict", "=", "{", "}", "for", "rlzi", ",", "hcurve", "in", "enumerate", "(", "hcurve_by_rlz", ")", ":", "datadict", "[", "rlzi", "]", "=", "lst", "=", "[", "None", "for", "imt", "in", "self", ".", "imtls", "]", "for", "imti", ",", "imt", "in", "enumerate", "(", "self", ".", "imtls", ")", ":", "lst", "[", "imti", "]", "=", "hcurve", "[", "imt", "]" ]
Read the poes and set the .data attribute with the hazard curves
[ "Read", "the", "poes", "and", "set", "the", ".", "data", "attribute", "with", "the", "hazard", "curves" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/getters.py#L66-L91
train
233,124
gem/oq-engine
openquake/calculators/getters.py
PmapGetter.get_mean
def get_mean(self, grp=None): """ Compute the mean curve as a ProbabilityMap :param grp: if not None must be a string of the form "grp-XX"; in that case returns the mean considering only the contribution for group XX """ self.init() if len(self.weights) == 1: # one realization # the standard deviation is zero pmap = self.get(0, grp) for sid, pcurve in pmap.items(): array = numpy.zeros(pcurve.array.shape[:-1] + (2,)) array[:, 0] = pcurve.array[:, 0] pcurve.array = array return pmap else: # multiple realizations dic = ({g: self.dstore['poes/' + g] for g in self.dstore['poes']} if grp is None else {grp: self.dstore['poes/' + grp]}) pmaps = self.rlzs_assoc.combine_pmaps(dic) return stats.compute_pmap_stats( pmaps, [stats.mean_curve, stats.std_curve], self.weights, self.imtls)
python
def get_mean(self, grp=None): """ Compute the mean curve as a ProbabilityMap :param grp: if not None must be a string of the form "grp-XX"; in that case returns the mean considering only the contribution for group XX """ self.init() if len(self.weights) == 1: # one realization # the standard deviation is zero pmap = self.get(0, grp) for sid, pcurve in pmap.items(): array = numpy.zeros(pcurve.array.shape[:-1] + (2,)) array[:, 0] = pcurve.array[:, 0] pcurve.array = array return pmap else: # multiple realizations dic = ({g: self.dstore['poes/' + g] for g in self.dstore['poes']} if grp is None else {grp: self.dstore['poes/' + grp]}) pmaps = self.rlzs_assoc.combine_pmaps(dic) return stats.compute_pmap_stats( pmaps, [stats.mean_curve, stats.std_curve], self.weights, self.imtls)
[ "def", "get_mean", "(", "self", ",", "grp", "=", "None", ")", ":", "self", ".", "init", "(", ")", "if", "len", "(", "self", ".", "weights", ")", "==", "1", ":", "# one realization", "# the standard deviation is zero", "pmap", "=", "self", ".", "get", "(", "0", ",", "grp", ")", "for", "sid", ",", "pcurve", "in", "pmap", ".", "items", "(", ")", ":", "array", "=", "numpy", ".", "zeros", "(", "pcurve", ".", "array", ".", "shape", "[", ":", "-", "1", "]", "+", "(", "2", ",", ")", ")", "array", "[", ":", ",", "0", "]", "=", "pcurve", ".", "array", "[", ":", ",", "0", "]", "pcurve", ".", "array", "=", "array", "return", "pmap", "else", ":", "# multiple realizations", "dic", "=", "(", "{", "g", ":", "self", ".", "dstore", "[", "'poes/'", "+", "g", "]", "for", "g", "in", "self", ".", "dstore", "[", "'poes'", "]", "}", "if", "grp", "is", "None", "else", "{", "grp", ":", "self", ".", "dstore", "[", "'poes/'", "+", "grp", "]", "}", ")", "pmaps", "=", "self", ".", "rlzs_assoc", ".", "combine_pmaps", "(", "dic", ")", "return", "stats", ".", "compute_pmap_stats", "(", "pmaps", ",", "[", "stats", ".", "mean_curve", ",", "stats", ".", "std_curve", "]", ",", "self", ".", "weights", ",", "self", ".", "imtls", ")" ]
Compute the mean curve as a ProbabilityMap :param grp: if not None must be a string of the form "grp-XX"; in that case returns the mean considering only the contribution for group XX
[ "Compute", "the", "mean", "curve", "as", "a", "ProbabilityMap" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/getters.py#L189-L212
train
233,125
gem/oq-engine
openquake/calculators/getters.py
GmfGetter.init
def init(self): """ Initialize the computers. Should be called on the workers """ if hasattr(self, 'computers'): # init already called return with hdf5.File(self.rupgetter.filename, 'r') as parent: self.weights = parent['weights'].value self.computers = [] for ebr in self.rupgetter.get_ruptures(self.srcfilter): sitecol = self.sitecol.filtered(ebr.sids) try: computer = calc.gmf.GmfComputer( ebr, sitecol, self.oqparam.imtls, self.cmaker, self.oqparam.truncation_level, self.correl_model) except FarAwayRupture: # due to numeric errors, ruptures within the maximum_distance # when written, can be outside when read; I found a case with # a distance of 99.9996936 km over a maximum distance of 100 km continue self.computers.append(computer)
python
def init(self): """ Initialize the computers. Should be called on the workers """ if hasattr(self, 'computers'): # init already called return with hdf5.File(self.rupgetter.filename, 'r') as parent: self.weights = parent['weights'].value self.computers = [] for ebr in self.rupgetter.get_ruptures(self.srcfilter): sitecol = self.sitecol.filtered(ebr.sids) try: computer = calc.gmf.GmfComputer( ebr, sitecol, self.oqparam.imtls, self.cmaker, self.oqparam.truncation_level, self.correl_model) except FarAwayRupture: # due to numeric errors, ruptures within the maximum_distance # when written, can be outside when read; I found a case with # a distance of 99.9996936 km over a maximum distance of 100 km continue self.computers.append(computer)
[ "def", "init", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'computers'", ")", ":", "# init already called", "return", "with", "hdf5", ".", "File", "(", "self", ".", "rupgetter", ".", "filename", ",", "'r'", ")", "as", "parent", ":", "self", ".", "weights", "=", "parent", "[", "'weights'", "]", ".", "value", "self", ".", "computers", "=", "[", "]", "for", "ebr", "in", "self", ".", "rupgetter", ".", "get_ruptures", "(", "self", ".", "srcfilter", ")", ":", "sitecol", "=", "self", ".", "sitecol", ".", "filtered", "(", "ebr", ".", "sids", ")", "try", ":", "computer", "=", "calc", ".", "gmf", ".", "GmfComputer", "(", "ebr", ",", "sitecol", ",", "self", ".", "oqparam", ".", "imtls", ",", "self", ".", "cmaker", ",", "self", ".", "oqparam", ".", "truncation_level", ",", "self", ".", "correl_model", ")", "except", "FarAwayRupture", ":", "# due to numeric errors, ruptures within the maximum_distance", "# when written, can be outside when read; I found a case with", "# a distance of 99.9996936 km over a maximum distance of 100 km", "continue", "self", ".", "computers", ".", "append", "(", "computer", ")" ]
Initialize the computers. Should be called on the workers
[ "Initialize", "the", "computers", ".", "Should", "be", "called", "on", "the", "workers" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/getters.py#L306-L326
train
233,126
gem/oq-engine
openquake/hazardlib/gsim/skarlatoudis_2013.py
SkarlatoudisEtAlSSlab2013._compute_forearc_backarc_term
def _compute_forearc_backarc_term(self, C, sites, dists, rup): """ Compute back-arc term of Equation 3 """ # flag 1 (R < 335 & R >= 205) flag1 = np.zeros(len(dists.rhypo)) ind1 = np.logical_and((dists.rhypo < 335), (dists.rhypo >= 205)) flag1[ind1] = 1.0 # flag 2 (R >= 335) flag2 = np.zeros(len(dists.rhypo)) ind2 = (dists.rhypo >= 335) flag2[ind2] = 1.0 # flag 3 (R < 240 & R >= 140) flag3 = np.zeros(len(dists.rhypo)) ind3 = np.logical_and((dists.rhypo < 240), (dists.rhypo >= 140)) flag3[ind3] = 1.0 # flag 4 (R >= 240) flag4 = np.zeros(len(dists.rhypo)) ind4 = (dists.rhypo >= 240) flag4[ind4] = 1.0 A = flag1 * ((205 - dists.rhypo)/150) + flag2 B = flag3 * ((140 - dists.rhypo)/100) + flag4 if (rup.hypo_depth < 80): FHR = A else: FHR = B H0 = 100 # Heaviside function if (rup.hypo_depth >= H0): H = 1 else: H = 0 # ARC = 0 for back-arc - ARC = 1 for forearc ARC = np.zeros(len(sites.backarc)) idxarc = (sites.backarc == 1) ARC[idxarc] = 1.0 return ((C['c41'] * (1 - ARC) * H) + (C['c42'] * (1 - ARC) * H * FHR) + (C['c51'] * ARC * H) + (C['c52'] * ARC * H * FHR))
python
def _compute_forearc_backarc_term(self, C, sites, dists, rup): """ Compute back-arc term of Equation 3 """ # flag 1 (R < 335 & R >= 205) flag1 = np.zeros(len(dists.rhypo)) ind1 = np.logical_and((dists.rhypo < 335), (dists.rhypo >= 205)) flag1[ind1] = 1.0 # flag 2 (R >= 335) flag2 = np.zeros(len(dists.rhypo)) ind2 = (dists.rhypo >= 335) flag2[ind2] = 1.0 # flag 3 (R < 240 & R >= 140) flag3 = np.zeros(len(dists.rhypo)) ind3 = np.logical_and((dists.rhypo < 240), (dists.rhypo >= 140)) flag3[ind3] = 1.0 # flag 4 (R >= 240) flag4 = np.zeros(len(dists.rhypo)) ind4 = (dists.rhypo >= 240) flag4[ind4] = 1.0 A = flag1 * ((205 - dists.rhypo)/150) + flag2 B = flag3 * ((140 - dists.rhypo)/100) + flag4 if (rup.hypo_depth < 80): FHR = A else: FHR = B H0 = 100 # Heaviside function if (rup.hypo_depth >= H0): H = 1 else: H = 0 # ARC = 0 for back-arc - ARC = 1 for forearc ARC = np.zeros(len(sites.backarc)) idxarc = (sites.backarc == 1) ARC[idxarc] = 1.0 return ((C['c41'] * (1 - ARC) * H) + (C['c42'] * (1 - ARC) * H * FHR) + (C['c51'] * ARC * H) + (C['c52'] * ARC * H * FHR))
[ "def", "_compute_forearc_backarc_term", "(", "self", ",", "C", ",", "sites", ",", "dists", ",", "rup", ")", ":", "# flag 1 (R < 335 & R >= 205)", "flag1", "=", "np", ".", "zeros", "(", "len", "(", "dists", ".", "rhypo", ")", ")", "ind1", "=", "np", ".", "logical_and", "(", "(", "dists", ".", "rhypo", "<", "335", ")", ",", "(", "dists", ".", "rhypo", ">=", "205", ")", ")", "flag1", "[", "ind1", "]", "=", "1.0", "# flag 2 (R >= 335)", "flag2", "=", "np", ".", "zeros", "(", "len", "(", "dists", ".", "rhypo", ")", ")", "ind2", "=", "(", "dists", ".", "rhypo", ">=", "335", ")", "flag2", "[", "ind2", "]", "=", "1.0", "# flag 3 (R < 240 & R >= 140)", "flag3", "=", "np", ".", "zeros", "(", "len", "(", "dists", ".", "rhypo", ")", ")", "ind3", "=", "np", ".", "logical_and", "(", "(", "dists", ".", "rhypo", "<", "240", ")", ",", "(", "dists", ".", "rhypo", ">=", "140", ")", ")", "flag3", "[", "ind3", "]", "=", "1.0", "# flag 4 (R >= 240)", "flag4", "=", "np", ".", "zeros", "(", "len", "(", "dists", ".", "rhypo", ")", ")", "ind4", "=", "(", "dists", ".", "rhypo", ">=", "240", ")", "flag4", "[", "ind4", "]", "=", "1.0", "A", "=", "flag1", "*", "(", "(", "205", "-", "dists", ".", "rhypo", ")", "/", "150", ")", "+", "flag2", "B", "=", "flag3", "*", "(", "(", "140", "-", "dists", ".", "rhypo", ")", "/", "100", ")", "+", "flag4", "if", "(", "rup", ".", "hypo_depth", "<", "80", ")", ":", "FHR", "=", "A", "else", ":", "FHR", "=", "B", "H0", "=", "100", "# Heaviside function", "if", "(", "rup", ".", "hypo_depth", ">=", "H0", ")", ":", "H", "=", "1", "else", ":", "H", "=", "0", "# ARC = 0 for back-arc - ARC = 1 for forearc", "ARC", "=", "np", ".", "zeros", "(", "len", "(", "sites", ".", "backarc", ")", ")", "idxarc", "=", "(", "sites", ".", "backarc", "==", "1", ")", "ARC", "[", "idxarc", "]", "=", "1.0", "return", "(", "(", "C", "[", "'c41'", "]", "*", "(", "1", "-", "ARC", ")", "*", "H", ")", "+", "(", "C", "[", "'c42'", "]", "*", "(", "1", "-", "ARC", ")", "*", "H", "*", "FHR", ")", "+", "(", "C", "[", "'c51'", "]", "*", "ARC", "*", "H", ")", "+", "(", "C", "[", "'c52'", "]", "*", "ARC", "*", "H", "*", "FHR", ")", ")" ]
Compute back-arc term of Equation 3
[ "Compute", "back", "-", "arc", "term", "of", "Equation", "3" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/skarlatoudis_2013.py#L177-L219
train
233,127
gem/oq-engine
openquake/hazardlib/gsim/gmpe_table.py
AmplificationTable._build_data
def _build_data(self, amplification_group): """ Creates the numpy array tables from the hdf5 tables """ # Determine shape of the tables n_levels = len(amplification_group) # Checks the first group in the amplification group and returns the # shape of the SA array - implicitly assumes the SA array in all # amplification groups is the same shape level = next(iter(amplification_group)) n_d, n_p, n_m = amplification_group[level]["IMLs/SA"].shape assert n_d == len(self.distances), (n_d, len(self.distances)) assert n_m == len(self.magnitudes), (n_m, len(self.magnitudes)) # Instantiate the arrays with ones self.mean = {"SA": numpy.ones([n_d, n_p, n_m, n_levels]), "PGA": numpy.ones([n_d, 1, n_m, n_levels]), "PGV": numpy.ones([n_d, 1, n_m, n_levels])} self.sigma = {} for stddev_type in [const.StdDev.TOTAL, const.StdDev.INTER_EVENT, const.StdDev.INTRA_EVENT]: level = next(iter(amplification_group)) if stddev_type in amplification_group[level]: self.sigma[stddev_type] = deepcopy(self.mean) for iloc, (level, amp_model) in enumerate(amplification_group.items()): if "SA" in amp_model["IMLs"]: if iloc == 0: self.periods = amp_model["IMLs/T"][:] else: assert numpy.allclose(self.periods, amp_model["IMLs/T"][:]) for imt in ["SA", "PGA", "PGV"]: if imt in amp_model["IMLs"]: self.mean[imt][:, :, :, self.argidx[iloc]] = \ amp_model["IMLs/" + imt][:] for stddev_type in self.sigma: self.sigma[stddev_type][imt][ :, :, :, self.argidx[iloc]] = \ amp_model["/".join([stddev_type, imt])][:] self.shape = (n_d, n_p, n_m, n_levels)
python
def _build_data(self, amplification_group): """ Creates the numpy array tables from the hdf5 tables """ # Determine shape of the tables n_levels = len(amplification_group) # Checks the first group in the amplification group and returns the # shape of the SA array - implicitly assumes the SA array in all # amplification groups is the same shape level = next(iter(amplification_group)) n_d, n_p, n_m = amplification_group[level]["IMLs/SA"].shape assert n_d == len(self.distances), (n_d, len(self.distances)) assert n_m == len(self.magnitudes), (n_m, len(self.magnitudes)) # Instantiate the arrays with ones self.mean = {"SA": numpy.ones([n_d, n_p, n_m, n_levels]), "PGA": numpy.ones([n_d, 1, n_m, n_levels]), "PGV": numpy.ones([n_d, 1, n_m, n_levels])} self.sigma = {} for stddev_type in [const.StdDev.TOTAL, const.StdDev.INTER_EVENT, const.StdDev.INTRA_EVENT]: level = next(iter(amplification_group)) if stddev_type in amplification_group[level]: self.sigma[stddev_type] = deepcopy(self.mean) for iloc, (level, amp_model) in enumerate(amplification_group.items()): if "SA" in amp_model["IMLs"]: if iloc == 0: self.periods = amp_model["IMLs/T"][:] else: assert numpy.allclose(self.periods, amp_model["IMLs/T"][:]) for imt in ["SA", "PGA", "PGV"]: if imt in amp_model["IMLs"]: self.mean[imt][:, :, :, self.argidx[iloc]] = \ amp_model["IMLs/" + imt][:] for stddev_type in self.sigma: self.sigma[stddev_type][imt][ :, :, :, self.argidx[iloc]] = \ amp_model["/".join([stddev_type, imt])][:] self.shape = (n_d, n_p, n_m, n_levels)
[ "def", "_build_data", "(", "self", ",", "amplification_group", ")", ":", "# Determine shape of the tables", "n_levels", "=", "len", "(", "amplification_group", ")", "# Checks the first group in the amplification group and returns the", "# shape of the SA array - implicitly assumes the SA array in all", "# amplification groups is the same shape", "level", "=", "next", "(", "iter", "(", "amplification_group", ")", ")", "n_d", ",", "n_p", ",", "n_m", "=", "amplification_group", "[", "level", "]", "[", "\"IMLs/SA\"", "]", ".", "shape", "assert", "n_d", "==", "len", "(", "self", ".", "distances", ")", ",", "(", "n_d", ",", "len", "(", "self", ".", "distances", ")", ")", "assert", "n_m", "==", "len", "(", "self", ".", "magnitudes", ")", ",", "(", "n_m", ",", "len", "(", "self", ".", "magnitudes", ")", ")", "# Instantiate the arrays with ones", "self", ".", "mean", "=", "{", "\"SA\"", ":", "numpy", ".", "ones", "(", "[", "n_d", ",", "n_p", ",", "n_m", ",", "n_levels", "]", ")", ",", "\"PGA\"", ":", "numpy", ".", "ones", "(", "[", "n_d", ",", "1", ",", "n_m", ",", "n_levels", "]", ")", ",", "\"PGV\"", ":", "numpy", ".", "ones", "(", "[", "n_d", ",", "1", ",", "n_m", ",", "n_levels", "]", ")", "}", "self", ".", "sigma", "=", "{", "}", "for", "stddev_type", "in", "[", "const", ".", "StdDev", ".", "TOTAL", ",", "const", ".", "StdDev", ".", "INTER_EVENT", ",", "const", ".", "StdDev", ".", "INTRA_EVENT", "]", ":", "level", "=", "next", "(", "iter", "(", "amplification_group", ")", ")", "if", "stddev_type", "in", "amplification_group", "[", "level", "]", ":", "self", ".", "sigma", "[", "stddev_type", "]", "=", "deepcopy", "(", "self", ".", "mean", ")", "for", "iloc", ",", "(", "level", ",", "amp_model", ")", "in", "enumerate", "(", "amplification_group", ".", "items", "(", ")", ")", ":", "if", "\"SA\"", "in", "amp_model", "[", "\"IMLs\"", "]", ":", "if", "iloc", "==", "0", ":", "self", ".", "periods", "=", "amp_model", "[", "\"IMLs/T\"", "]", "[", ":", "]", "else", ":", "assert", "numpy", ".", "allclose", "(", "self", ".", "periods", ",", "amp_model", "[", "\"IMLs/T\"", "]", "[", ":", "]", ")", "for", "imt", "in", "[", "\"SA\"", ",", "\"PGA\"", ",", "\"PGV\"", "]", ":", "if", "imt", "in", "amp_model", "[", "\"IMLs\"", "]", ":", "self", ".", "mean", "[", "imt", "]", "[", ":", ",", ":", ",", ":", ",", "self", ".", "argidx", "[", "iloc", "]", "]", "=", "amp_model", "[", "\"IMLs/\"", "+", "imt", "]", "[", ":", "]", "for", "stddev_type", "in", "self", ".", "sigma", ":", "self", ".", "sigma", "[", "stddev_type", "]", "[", "imt", "]", "[", ":", ",", ":", ",", ":", ",", "self", ".", "argidx", "[", "iloc", "]", "]", "=", "amp_model", "[", "\"/\"", ".", "join", "(", "[", "stddev_type", ",", "imt", "]", ")", "]", "[", ":", "]", "self", ".", "shape", "=", "(", "n_d", ",", "n_p", ",", "n_m", ",", "n_levels", ")" ]
Creates the numpy array tables from the hdf5 tables
[ "Creates", "the", "numpy", "array", "tables", "from", "the", "hdf5", "tables" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/gmpe_table.py#L112-L150
train
233,128
gem/oq-engine
openquake/hazardlib/gsim/gmpe_table.py
AmplificationTable.get_amplification_factors
def get_amplification_factors(self, imt, sctx, rctx, dists, stddev_types): """ Returns the amplification factors for the given rupture and site conditions. :param imt: Intensity measure type as an instance of the :class: `openquake.hazardlib.imt` :param sctx: SiteCollection instance :param rctx: Rupture instance :param dists: Source to site distances (km) :param stddev_types: List of required standard deviation types :returns: * mean_amp - Amplification factors applied to the median ground motion * sigma_amps - List of modification factors applied to the standard deviations of ground motion """ dist_level_table = self.get_mean_table(imt, rctx) sigma_tables = self.get_sigma_tables(imt, rctx, stddev_types) mean_interpolator = interp1d(self.values, numpy.log10(dist_level_table), axis=1) sigma_interpolators = [interp1d(self.values, sigma_table, axis=1) for sigma_table in sigma_tables] if self.element == "Rupture": mean_amp = 10.0 ** mean_interpolator( getattr(rctx, self.parameter))[0] * numpy.ones_like(dists) sigma_amps = [] for sig_interpolator in sigma_interpolators: sigma_amps.append(sig_interpolator( getattr(rctx, self.parameter))[0] * numpy.ones_like(dists)) else: mean_amp = 10.0 ** mean_interpolator( getattr(sctx, self.parameter))[0, :] sigma_amps = [] for sig_interpolator in sigma_interpolators: sigma_amps.append(sig_interpolator( getattr(sctx, self.parameter))[0, :] * numpy.ones_like(dists)) return mean_amp, sigma_amps
python
def get_amplification_factors(self, imt, sctx, rctx, dists, stddev_types): """ Returns the amplification factors for the given rupture and site conditions. :param imt: Intensity measure type as an instance of the :class: `openquake.hazardlib.imt` :param sctx: SiteCollection instance :param rctx: Rupture instance :param dists: Source to site distances (km) :param stddev_types: List of required standard deviation types :returns: * mean_amp - Amplification factors applied to the median ground motion * sigma_amps - List of modification factors applied to the standard deviations of ground motion """ dist_level_table = self.get_mean_table(imt, rctx) sigma_tables = self.get_sigma_tables(imt, rctx, stddev_types) mean_interpolator = interp1d(self.values, numpy.log10(dist_level_table), axis=1) sigma_interpolators = [interp1d(self.values, sigma_table, axis=1) for sigma_table in sigma_tables] if self.element == "Rupture": mean_amp = 10.0 ** mean_interpolator( getattr(rctx, self.parameter))[0] * numpy.ones_like(dists) sigma_amps = [] for sig_interpolator in sigma_interpolators: sigma_amps.append(sig_interpolator( getattr(rctx, self.parameter))[0] * numpy.ones_like(dists)) else: mean_amp = 10.0 ** mean_interpolator( getattr(sctx, self.parameter))[0, :] sigma_amps = [] for sig_interpolator in sigma_interpolators: sigma_amps.append(sig_interpolator( getattr(sctx, self.parameter))[0, :] * numpy.ones_like(dists)) return mean_amp, sigma_amps
[ "def", "get_amplification_factors", "(", "self", ",", "imt", ",", "sctx", ",", "rctx", ",", "dists", ",", "stddev_types", ")", ":", "dist_level_table", "=", "self", ".", "get_mean_table", "(", "imt", ",", "rctx", ")", "sigma_tables", "=", "self", ".", "get_sigma_tables", "(", "imt", ",", "rctx", ",", "stddev_types", ")", "mean_interpolator", "=", "interp1d", "(", "self", ".", "values", ",", "numpy", ".", "log10", "(", "dist_level_table", ")", ",", "axis", "=", "1", ")", "sigma_interpolators", "=", "[", "interp1d", "(", "self", ".", "values", ",", "sigma_table", ",", "axis", "=", "1", ")", "for", "sigma_table", "in", "sigma_tables", "]", "if", "self", ".", "element", "==", "\"Rupture\"", ":", "mean_amp", "=", "10.0", "**", "mean_interpolator", "(", "getattr", "(", "rctx", ",", "self", ".", "parameter", ")", ")", "[", "0", "]", "*", "numpy", ".", "ones_like", "(", "dists", ")", "sigma_amps", "=", "[", "]", "for", "sig_interpolator", "in", "sigma_interpolators", ":", "sigma_amps", ".", "append", "(", "sig_interpolator", "(", "getattr", "(", "rctx", ",", "self", ".", "parameter", ")", ")", "[", "0", "]", "*", "numpy", ".", "ones_like", "(", "dists", ")", ")", "else", ":", "mean_amp", "=", "10.0", "**", "mean_interpolator", "(", "getattr", "(", "sctx", ",", "self", ".", "parameter", ")", ")", "[", "0", ",", ":", "]", "sigma_amps", "=", "[", "]", "for", "sig_interpolator", "in", "sigma_interpolators", ":", "sigma_amps", ".", "append", "(", "sig_interpolator", "(", "getattr", "(", "sctx", ",", "self", ".", "parameter", ")", ")", "[", "0", ",", ":", "]", "*", "numpy", ".", "ones_like", "(", "dists", ")", ")", "return", "mean_amp", ",", "sigma_amps" ]
Returns the amplification factors for the given rupture and site conditions. :param imt: Intensity measure type as an instance of the :class: `openquake.hazardlib.imt` :param sctx: SiteCollection instance :param rctx: Rupture instance :param dists: Source to site distances (km) :param stddev_types: List of required standard deviation types :returns: * mean_amp - Amplification factors applied to the median ground motion * sigma_amps - List of modification factors applied to the standard deviations of ground motion
[ "Returns", "the", "amplification", "factors", "for", "the", "given", "rupture", "and", "site", "conditions", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/gmpe_table.py#L158-L202
train
233,129
gem/oq-engine
openquake/hazardlib/gsim/gmpe_table.py
AmplificationTable.get_mean_table
def get_mean_table(self, imt, rctx): """ Returns amplification factors for the mean, given the rupture and intensity measure type. :returns: amplification table as an array of [Number Distances, Number Levels] """ # Levels by Distances if imt.name in 'PGA PGV': interpolator = interp1d(self.magnitudes, numpy.log10(self.mean[imt.name]), axis=2) output_table = 10.0 ** ( interpolator(rctx.mag).reshape(self.shape[0], self.shape[3])) else: # For spectral accelerations - need two step process # Interpolate period - log-log space interpolator = interp1d(numpy.log10(self.periods), numpy.log10(self.mean["SA"]), axis=1) period_table = interpolator(numpy.log10(imt.period)) # Interpolate magnitude - linear-log space mag_interpolator = interp1d(self.magnitudes, period_table, axis=1) output_table = 10.0 ** mag_interpolator(rctx.mag) return output_table
python
def get_mean_table(self, imt, rctx): """ Returns amplification factors for the mean, given the rupture and intensity measure type. :returns: amplification table as an array of [Number Distances, Number Levels] """ # Levels by Distances if imt.name in 'PGA PGV': interpolator = interp1d(self.magnitudes, numpy.log10(self.mean[imt.name]), axis=2) output_table = 10.0 ** ( interpolator(rctx.mag).reshape(self.shape[0], self.shape[3])) else: # For spectral accelerations - need two step process # Interpolate period - log-log space interpolator = interp1d(numpy.log10(self.periods), numpy.log10(self.mean["SA"]), axis=1) period_table = interpolator(numpy.log10(imt.period)) # Interpolate magnitude - linear-log space mag_interpolator = interp1d(self.magnitudes, period_table, axis=1) output_table = 10.0 ** mag_interpolator(rctx.mag) return output_table
[ "def", "get_mean_table", "(", "self", ",", "imt", ",", "rctx", ")", ":", "# Levels by Distances", "if", "imt", ".", "name", "in", "'PGA PGV'", ":", "interpolator", "=", "interp1d", "(", "self", ".", "magnitudes", ",", "numpy", ".", "log10", "(", "self", ".", "mean", "[", "imt", ".", "name", "]", ")", ",", "axis", "=", "2", ")", "output_table", "=", "10.0", "**", "(", "interpolator", "(", "rctx", ".", "mag", ")", ".", "reshape", "(", "self", ".", "shape", "[", "0", "]", ",", "self", ".", "shape", "[", "3", "]", ")", ")", "else", ":", "# For spectral accelerations - need two step process", "# Interpolate period - log-log space", "interpolator", "=", "interp1d", "(", "numpy", ".", "log10", "(", "self", ".", "periods", ")", ",", "numpy", ".", "log10", "(", "self", ".", "mean", "[", "\"SA\"", "]", ")", ",", "axis", "=", "1", ")", "period_table", "=", "interpolator", "(", "numpy", ".", "log10", "(", "imt", ".", "period", ")", ")", "# Interpolate magnitude - linear-log space", "mag_interpolator", "=", "interp1d", "(", "self", ".", "magnitudes", ",", "period_table", ",", "axis", "=", "1", ")", "output_table", "=", "10.0", "**", "mag_interpolator", "(", "rctx", ".", "mag", ")", "return", "output_table" ]
Returns amplification factors for the mean, given the rupture and intensity measure type. :returns: amplification table as an array of [Number Distances, Number Levels]
[ "Returns", "amplification", "factors", "for", "the", "mean", "given", "the", "rupture", "and", "intensity", "measure", "type", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/gmpe_table.py#L204-L229
train
233,130
gem/oq-engine
openquake/hazardlib/gsim/gmpe_table.py
AmplificationTable.get_sigma_tables
def get_sigma_tables(self, imt, rctx, stddev_types): """ Returns modification factors for the standard deviations, given the rupture and intensity measure type. :returns: List of standard deviation modification tables, each as an array of [Number Distances, Number Levels] """ output_tables = [] for stddev_type in stddev_types: # For PGA and PGV only needs to apply magnitude interpolation if imt.name in 'PGA PGV': interpolator = interp1d(self.magnitudes, self.sigma[stddev_type][imt.name], axis=2) output_tables.append( interpolator(rctx.mag).reshape(self.shape[0], self.shape[3])) else: # For spectral accelerations - need two step process # Interpolate period interpolator = interp1d(numpy.log10(self.periods), self.sigma[stddev_type]["SA"], axis=1) period_table = interpolator(numpy.log10(imt.period)) mag_interpolator = interp1d(self.magnitudes, period_table, axis=1) output_tables.append(mag_interpolator(rctx.mag)) return output_tables
python
def get_sigma_tables(self, imt, rctx, stddev_types): """ Returns modification factors for the standard deviations, given the rupture and intensity measure type. :returns: List of standard deviation modification tables, each as an array of [Number Distances, Number Levels] """ output_tables = [] for stddev_type in stddev_types: # For PGA and PGV only needs to apply magnitude interpolation if imt.name in 'PGA PGV': interpolator = interp1d(self.magnitudes, self.sigma[stddev_type][imt.name], axis=2) output_tables.append( interpolator(rctx.mag).reshape(self.shape[0], self.shape[3])) else: # For spectral accelerations - need two step process # Interpolate period interpolator = interp1d(numpy.log10(self.periods), self.sigma[stddev_type]["SA"], axis=1) period_table = interpolator(numpy.log10(imt.period)) mag_interpolator = interp1d(self.magnitudes, period_table, axis=1) output_tables.append(mag_interpolator(rctx.mag)) return output_tables
[ "def", "get_sigma_tables", "(", "self", ",", "imt", ",", "rctx", ",", "stddev_types", ")", ":", "output_tables", "=", "[", "]", "for", "stddev_type", "in", "stddev_types", ":", "# For PGA and PGV only needs to apply magnitude interpolation", "if", "imt", ".", "name", "in", "'PGA PGV'", ":", "interpolator", "=", "interp1d", "(", "self", ".", "magnitudes", ",", "self", ".", "sigma", "[", "stddev_type", "]", "[", "imt", ".", "name", "]", ",", "axis", "=", "2", ")", "output_tables", ".", "append", "(", "interpolator", "(", "rctx", ".", "mag", ")", ".", "reshape", "(", "self", ".", "shape", "[", "0", "]", ",", "self", ".", "shape", "[", "3", "]", ")", ")", "else", ":", "# For spectral accelerations - need two step process", "# Interpolate period", "interpolator", "=", "interp1d", "(", "numpy", ".", "log10", "(", "self", ".", "periods", ")", ",", "self", ".", "sigma", "[", "stddev_type", "]", "[", "\"SA\"", "]", ",", "axis", "=", "1", ")", "period_table", "=", "interpolator", "(", "numpy", ".", "log10", "(", "imt", ".", "period", ")", ")", "mag_interpolator", "=", "interp1d", "(", "self", ".", "magnitudes", ",", "period_table", ",", "axis", "=", "1", ")", "output_tables", ".", "append", "(", "mag_interpolator", "(", "rctx", ".", "mag", ")", ")", "return", "output_tables" ]
Returns modification factors for the standard deviations, given the rupture and intensity measure type. :returns: List of standard deviation modification tables, each as an array of [Number Distances, Number Levels]
[ "Returns", "modification", "factors", "for", "the", "standard", "deviations", "given", "the", "rupture", "and", "intensity", "measure", "type", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/gmpe_table.py#L231-L263
train
233,131
gem/oq-engine
openquake/hazardlib/gsim/gmpe_table.py
GMPETable.init
def init(self, fle=None): """ Executes the preprocessing steps at the instantiation stage to read in the tables from hdf5 and hold them in memory. """ if fle is None: fname = self.kwargs.get('gmpe_table', self.GMPE_TABLE) if fname is None: raise ValueError('You forgot to set GMPETable.GMPE_TABLE!') elif os.path.isabs(fname): self.GMPE_TABLE = fname else: # NB: (hackish) GMPE_DIR must be set externally self.GMPE_TABLE = os.path.abspath( os.path.join(self.GMPE_DIR, fname)) fle = h5py.File(self.GMPE_TABLE, "r") try: # this is the format inside the datastore self.distance_type = fle["distance_type"].value except KeyError: # this is the original format outside the datastore self.distance_type = decode(fle["Distances"].attrs["metric"]) self.REQUIRES_DISTANCES = set([self.distance_type]) # Load in magnitude self.m_w = fle["Mw"][:] # Load in distances self.distances = fle["Distances"][:] # Load intensity measure types and levels self.imls = hdf_arrays_to_dict(fle["IMLs"]) self.DEFINED_FOR_INTENSITY_MEASURE_TYPES = set(self._supported_imts()) if "SA" in self.imls and "T" not in self.imls: raise ValueError("Spectral Acceleration must be accompanied by " "periods") # Get the standard deviations self._setup_standard_deviations(fle) if "Amplification" in fle: self._setup_amplification(fle)
python
def init(self, fle=None): """ Executes the preprocessing steps at the instantiation stage to read in the tables from hdf5 and hold them in memory. """ if fle is None: fname = self.kwargs.get('gmpe_table', self.GMPE_TABLE) if fname is None: raise ValueError('You forgot to set GMPETable.GMPE_TABLE!') elif os.path.isabs(fname): self.GMPE_TABLE = fname else: # NB: (hackish) GMPE_DIR must be set externally self.GMPE_TABLE = os.path.abspath( os.path.join(self.GMPE_DIR, fname)) fle = h5py.File(self.GMPE_TABLE, "r") try: # this is the format inside the datastore self.distance_type = fle["distance_type"].value except KeyError: # this is the original format outside the datastore self.distance_type = decode(fle["Distances"].attrs["metric"]) self.REQUIRES_DISTANCES = set([self.distance_type]) # Load in magnitude self.m_w = fle["Mw"][:] # Load in distances self.distances = fle["Distances"][:] # Load intensity measure types and levels self.imls = hdf_arrays_to_dict(fle["IMLs"]) self.DEFINED_FOR_INTENSITY_MEASURE_TYPES = set(self._supported_imts()) if "SA" in self.imls and "T" not in self.imls: raise ValueError("Spectral Acceleration must be accompanied by " "periods") # Get the standard deviations self._setup_standard_deviations(fle) if "Amplification" in fle: self._setup_amplification(fle)
[ "def", "init", "(", "self", ",", "fle", "=", "None", ")", ":", "if", "fle", "is", "None", ":", "fname", "=", "self", ".", "kwargs", ".", "get", "(", "'gmpe_table'", ",", "self", ".", "GMPE_TABLE", ")", "if", "fname", "is", "None", ":", "raise", "ValueError", "(", "'You forgot to set GMPETable.GMPE_TABLE!'", ")", "elif", "os", ".", "path", ".", "isabs", "(", "fname", ")", ":", "self", ".", "GMPE_TABLE", "=", "fname", "else", ":", "# NB: (hackish) GMPE_DIR must be set externally", "self", ".", "GMPE_TABLE", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "GMPE_DIR", ",", "fname", ")", ")", "fle", "=", "h5py", ".", "File", "(", "self", ".", "GMPE_TABLE", ",", "\"r\"", ")", "try", ":", "# this is the format inside the datastore", "self", ".", "distance_type", "=", "fle", "[", "\"distance_type\"", "]", ".", "value", "except", "KeyError", ":", "# this is the original format outside the datastore", "self", ".", "distance_type", "=", "decode", "(", "fle", "[", "\"Distances\"", "]", ".", "attrs", "[", "\"metric\"", "]", ")", "self", ".", "REQUIRES_DISTANCES", "=", "set", "(", "[", "self", ".", "distance_type", "]", ")", "# Load in magnitude", "self", ".", "m_w", "=", "fle", "[", "\"Mw\"", "]", "[", ":", "]", "# Load in distances", "self", ".", "distances", "=", "fle", "[", "\"Distances\"", "]", "[", ":", "]", "# Load intensity measure types and levels", "self", ".", "imls", "=", "hdf_arrays_to_dict", "(", "fle", "[", "\"IMLs\"", "]", ")", "self", ".", "DEFINED_FOR_INTENSITY_MEASURE_TYPES", "=", "set", "(", "self", ".", "_supported_imts", "(", ")", ")", "if", "\"SA\"", "in", "self", ".", "imls", "and", "\"T\"", "not", "in", "self", ".", "imls", ":", "raise", "ValueError", "(", "\"Spectral Acceleration must be accompanied by \"", "\"periods\"", ")", "# Get the standard deviations", "self", ".", "_setup_standard_deviations", "(", "fle", ")", "if", "\"Amplification\"", "in", "fle", ":", "self", ".", "_setup_amplification", "(", "fle", ")" ]
Executes the preprocessing steps at the instantiation stage to read in the tables from hdf5 and hold them in memory.
[ "Executes", "the", "preprocessing", "steps", "at", "the", "instantiation", "stage", "to", "read", "in", "the", "tables", "from", "hdf5", "and", "hold", "them", "in", "memory", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/gmpe_table.py#L306-L342
train
233,132
gem/oq-engine
openquake/hazardlib/gsim/gmpe_table.py
GMPETable._setup_amplification
def _setup_amplification(self, fle): """ If amplification data is specified then reads into memory and updates the required rupture and site parameters """ self.amplification = AmplificationTable(fle["Amplification"], self.m_w, self.distances) if self.amplification.element == "Sites": self.REQUIRES_SITES_PARAMETERS = set( [self.amplification.parameter]) elif self.amplification.element == "Rupture": # set the site and rupture parameters on the instance self.REQUIRES_SITES_PARAMETERS = set() self.REQUIRES_RUPTURE_PARAMETERS = ( self.REQUIRES_RUPTURE_PARAMETERS | {self.amplification.parameter})
python
def _setup_amplification(self, fle): """ If amplification data is specified then reads into memory and updates the required rupture and site parameters """ self.amplification = AmplificationTable(fle["Amplification"], self.m_w, self.distances) if self.amplification.element == "Sites": self.REQUIRES_SITES_PARAMETERS = set( [self.amplification.parameter]) elif self.amplification.element == "Rupture": # set the site and rupture parameters on the instance self.REQUIRES_SITES_PARAMETERS = set() self.REQUIRES_RUPTURE_PARAMETERS = ( self.REQUIRES_RUPTURE_PARAMETERS | {self.amplification.parameter})
[ "def", "_setup_amplification", "(", "self", ",", "fle", ")", ":", "self", ".", "amplification", "=", "AmplificationTable", "(", "fle", "[", "\"Amplification\"", "]", ",", "self", ".", "m_w", ",", "self", ".", "distances", ")", "if", "self", ".", "amplification", ".", "element", "==", "\"Sites\"", ":", "self", ".", "REQUIRES_SITES_PARAMETERS", "=", "set", "(", "[", "self", ".", "amplification", ".", "parameter", "]", ")", "elif", "self", ".", "amplification", ".", "element", "==", "\"Rupture\"", ":", "# set the site and rupture parameters on the instance", "self", ".", "REQUIRES_SITES_PARAMETERS", "=", "set", "(", ")", "self", ".", "REQUIRES_RUPTURE_PARAMETERS", "=", "(", "self", ".", "REQUIRES_RUPTURE_PARAMETERS", "|", "{", "self", ".", "amplification", ".", "parameter", "}", ")" ]
If amplification data is specified then reads into memory and updates the required rupture and site parameters
[ "If", "amplification", "data", "is", "specified", "then", "reads", "into", "memory", "and", "updates", "the", "required", "rupture", "and", "site", "parameters" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/gmpe_table.py#L364-L380
train
233,133
gem/oq-engine
openquake/hazardlib/gsim/gmpe_table.py
GMPETable._supported_imts
def _supported_imts(self): """ Updates the list of supported IMTs from the tables """ imt_list = [] for key in self.imls: if "SA" in key: imt_list.append(imt_module.SA) elif key == "T": continue else: try: factory = getattr(imt_module, key) except Exception: continue imt_list.append(factory) return imt_list
python
def _supported_imts(self): """ Updates the list of supported IMTs from the tables """ imt_list = [] for key in self.imls: if "SA" in key: imt_list.append(imt_module.SA) elif key == "T": continue else: try: factory = getattr(imt_module, key) except Exception: continue imt_list.append(factory) return imt_list
[ "def", "_supported_imts", "(", "self", ")", ":", "imt_list", "=", "[", "]", "for", "key", "in", "self", ".", "imls", ":", "if", "\"SA\"", "in", "key", ":", "imt_list", ".", "append", "(", "imt_module", ".", "SA", ")", "elif", "key", "==", "\"T\"", ":", "continue", "else", ":", "try", ":", "factory", "=", "getattr", "(", "imt_module", ",", "key", ")", "except", "Exception", ":", "continue", "imt_list", ".", "append", "(", "factory", ")", "return", "imt_list" ]
Updates the list of supported IMTs from the tables
[ "Updates", "the", "list", "of", "supported", "IMTs", "from", "the", "tables" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/gmpe_table.py#L382-L398
train
233,134
gem/oq-engine
openquake/hazardlib/gsim/gmpe_table.py
GMPETable.get_mean_and_stddevs
def get_mean_and_stddevs(self, sctx, rctx, dctx, imt, stddev_types): """ Returns the mean and standard deviations """ # Return Distance Tables imls = self._return_tables(rctx.mag, imt, "IMLs") # Get distance vector for the given magnitude idx = numpy.searchsorted(self.m_w, rctx.mag) dists = self.distances[:, 0, idx - 1] # Get mean and standard deviations mean = self._get_mean(imls, dctx, dists) stddevs = self._get_stddevs(dists, rctx.mag, dctx, imt, stddev_types) if self.amplification: # Apply amplification mean_amp, sigma_amp = self.amplification.get_amplification_factors( imt, sctx, rctx, getattr(dctx, self.distance_type), stddev_types) mean = numpy.log(mean) + numpy.log(mean_amp) for iloc in range(len(stddev_types)): stddevs[iloc] *= sigma_amp[iloc] return mean, stddevs else: return numpy.log(mean), stddevs
python
def get_mean_and_stddevs(self, sctx, rctx, dctx, imt, stddev_types): """ Returns the mean and standard deviations """ # Return Distance Tables imls = self._return_tables(rctx.mag, imt, "IMLs") # Get distance vector for the given magnitude idx = numpy.searchsorted(self.m_w, rctx.mag) dists = self.distances[:, 0, idx - 1] # Get mean and standard deviations mean = self._get_mean(imls, dctx, dists) stddevs = self._get_stddevs(dists, rctx.mag, dctx, imt, stddev_types) if self.amplification: # Apply amplification mean_amp, sigma_amp = self.amplification.get_amplification_factors( imt, sctx, rctx, getattr(dctx, self.distance_type), stddev_types) mean = numpy.log(mean) + numpy.log(mean_amp) for iloc in range(len(stddev_types)): stddevs[iloc] *= sigma_amp[iloc] return mean, stddevs else: return numpy.log(mean), stddevs
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sctx", ",", "rctx", ",", "dctx", ",", "imt", ",", "stddev_types", ")", ":", "# Return Distance Tables", "imls", "=", "self", ".", "_return_tables", "(", "rctx", ".", "mag", ",", "imt", ",", "\"IMLs\"", ")", "# Get distance vector for the given magnitude", "idx", "=", "numpy", ".", "searchsorted", "(", "self", ".", "m_w", ",", "rctx", ".", "mag", ")", "dists", "=", "self", ".", "distances", "[", ":", ",", "0", ",", "idx", "-", "1", "]", "# Get mean and standard deviations", "mean", "=", "self", ".", "_get_mean", "(", "imls", ",", "dctx", ",", "dists", ")", "stddevs", "=", "self", ".", "_get_stddevs", "(", "dists", ",", "rctx", ".", "mag", ",", "dctx", ",", "imt", ",", "stddev_types", ")", "if", "self", ".", "amplification", ":", "# Apply amplification", "mean_amp", ",", "sigma_amp", "=", "self", ".", "amplification", ".", "get_amplification_factors", "(", "imt", ",", "sctx", ",", "rctx", ",", "getattr", "(", "dctx", ",", "self", ".", "distance_type", ")", ",", "stddev_types", ")", "mean", "=", "numpy", ".", "log", "(", "mean", ")", "+", "numpy", ".", "log", "(", "mean_amp", ")", "for", "iloc", "in", "range", "(", "len", "(", "stddev_types", ")", ")", ":", "stddevs", "[", "iloc", "]", "*=", "sigma_amp", "[", "iloc", "]", "return", "mean", ",", "stddevs", "else", ":", "return", "numpy", ".", "log", "(", "mean", ")", ",", "stddevs" ]
Returns the mean and standard deviations
[ "Returns", "the", "mean", "and", "standard", "deviations" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/gmpe_table.py#L400-L425
train
233,135
gem/oq-engine
openquake/hazardlib/gsim/gmpe_table.py
GMPETable._get_stddevs
def _get_stddevs(self, dists, mag, dctx, imt, stddev_types): """ Returns the total standard deviation of the intensity measure level from the tables. :param fle: HDF5 data stream as instance of :class:`h5py.File` :param distances: The distance vector for the given magnitude and IMT :param key: The distance type :param mag: The rupture magnitude """ stddevs = [] for stddev_type in stddev_types: if stddev_type not in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES: raise ValueError("Standard Deviation type %s not supported" % stddev_type) sigma = self._return_tables(mag, imt, stddev_type) interpolator_std = interp1d(dists, sigma, bounds_error=False) stddev = interpolator_std(getattr(dctx, self.distance_type)) stddev[getattr(dctx, self.distance_type) < dists[0]] = sigma[0] stddev[getattr(dctx, self.distance_type) > dists[-1]] = sigma[-1] stddevs.append(stddev) return stddevs
python
def _get_stddevs(self, dists, mag, dctx, imt, stddev_types): """ Returns the total standard deviation of the intensity measure level from the tables. :param fle: HDF5 data stream as instance of :class:`h5py.File` :param distances: The distance vector for the given magnitude and IMT :param key: The distance type :param mag: The rupture magnitude """ stddevs = [] for stddev_type in stddev_types: if stddev_type not in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES: raise ValueError("Standard Deviation type %s not supported" % stddev_type) sigma = self._return_tables(mag, imt, stddev_type) interpolator_std = interp1d(dists, sigma, bounds_error=False) stddev = interpolator_std(getattr(dctx, self.distance_type)) stddev[getattr(dctx, self.distance_type) < dists[0]] = sigma[0] stddev[getattr(dctx, self.distance_type) > dists[-1]] = sigma[-1] stddevs.append(stddev) return stddevs
[ "def", "_get_stddevs", "(", "self", ",", "dists", ",", "mag", ",", "dctx", ",", "imt", ",", "stddev_types", ")", ":", "stddevs", "=", "[", "]", "for", "stddev_type", "in", "stddev_types", ":", "if", "stddev_type", "not", "in", "self", ".", "DEFINED_FOR_STANDARD_DEVIATION_TYPES", ":", "raise", "ValueError", "(", "\"Standard Deviation type %s not supported\"", "%", "stddev_type", ")", "sigma", "=", "self", ".", "_return_tables", "(", "mag", ",", "imt", ",", "stddev_type", ")", "interpolator_std", "=", "interp1d", "(", "dists", ",", "sigma", ",", "bounds_error", "=", "False", ")", "stddev", "=", "interpolator_std", "(", "getattr", "(", "dctx", ",", "self", ".", "distance_type", ")", ")", "stddev", "[", "getattr", "(", "dctx", ",", "self", ".", "distance_type", ")", "<", "dists", "[", "0", "]", "]", "=", "sigma", "[", "0", "]", "stddev", "[", "getattr", "(", "dctx", ",", "self", ".", "distance_type", ")", ">", "dists", "[", "-", "1", "]", "]", "=", "sigma", "[", "-", "1", "]", "stddevs", ".", "append", "(", "stddev", ")", "return", "stddevs" ]
Returns the total standard deviation of the intensity measure level from the tables. :param fle: HDF5 data stream as instance of :class:`h5py.File` :param distances: The distance vector for the given magnitude and IMT :param key: The distance type :param mag: The rupture magnitude
[ "Returns", "the", "total", "standard", "deviation", "of", "the", "intensity", "measure", "level", "from", "the", "tables", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/gmpe_table.py#L454-L480
train
233,136
gem/oq-engine
openquake/hazardlib/gsim/gmpe_table.py
GMPETable._return_tables
def _return_tables(self, mag, imt, val_type): """ Returns the vector of ground motions or standard deviations corresponding to the specific magnitude and intensity measure type. :param val_type: String indicating the type of data {"IMLs", "Total", "Inter" etc} """ if imt.name in 'PGA PGV': # Get scalar imt if val_type == "IMLs": iml_table = self.imls[imt.name][:] else: iml_table = self.stddevs[val_type][imt.name][:] n_d, n_s, n_m = iml_table.shape iml_table = iml_table.reshape([n_d, n_m]) else: if val_type == "IMLs": periods = self.imls["T"][:] iml_table = self.imls["SA"][:] else: periods = self.stddevs[val_type]["T"][:] iml_table = self.stddevs[val_type]["SA"][:] low_period = round(periods[0], 7) high_period = round(periods[-1], 7) if (round(imt.period, 7) < low_period) or ( round(imt.period, 7) > high_period): raise ValueError("Spectral period %.3f outside of valid range " "(%.3f to %.3f)" % (imt.period, periods[0], periods[-1])) # Apply log-log interpolation for spectral period interpolator = interp1d(numpy.log10(periods), numpy.log10(iml_table), axis=1) iml_table = 10. ** interpolator(numpy.log10(imt.period)) return self.apply_magnitude_interpolation(mag, iml_table)
python
def _return_tables(self, mag, imt, val_type): """ Returns the vector of ground motions or standard deviations corresponding to the specific magnitude and intensity measure type. :param val_type: String indicating the type of data {"IMLs", "Total", "Inter" etc} """ if imt.name in 'PGA PGV': # Get scalar imt if val_type == "IMLs": iml_table = self.imls[imt.name][:] else: iml_table = self.stddevs[val_type][imt.name][:] n_d, n_s, n_m = iml_table.shape iml_table = iml_table.reshape([n_d, n_m]) else: if val_type == "IMLs": periods = self.imls["T"][:] iml_table = self.imls["SA"][:] else: periods = self.stddevs[val_type]["T"][:] iml_table = self.stddevs[val_type]["SA"][:] low_period = round(periods[0], 7) high_period = round(periods[-1], 7) if (round(imt.period, 7) < low_period) or ( round(imt.period, 7) > high_period): raise ValueError("Spectral period %.3f outside of valid range " "(%.3f to %.3f)" % (imt.period, periods[0], periods[-1])) # Apply log-log interpolation for spectral period interpolator = interp1d(numpy.log10(periods), numpy.log10(iml_table), axis=1) iml_table = 10. ** interpolator(numpy.log10(imt.period)) return self.apply_magnitude_interpolation(mag, iml_table)
[ "def", "_return_tables", "(", "self", ",", "mag", ",", "imt", ",", "val_type", ")", ":", "if", "imt", ".", "name", "in", "'PGA PGV'", ":", "# Get scalar imt", "if", "val_type", "==", "\"IMLs\"", ":", "iml_table", "=", "self", ".", "imls", "[", "imt", ".", "name", "]", "[", ":", "]", "else", ":", "iml_table", "=", "self", ".", "stddevs", "[", "val_type", "]", "[", "imt", ".", "name", "]", "[", ":", "]", "n_d", ",", "n_s", ",", "n_m", "=", "iml_table", ".", "shape", "iml_table", "=", "iml_table", ".", "reshape", "(", "[", "n_d", ",", "n_m", "]", ")", "else", ":", "if", "val_type", "==", "\"IMLs\"", ":", "periods", "=", "self", ".", "imls", "[", "\"T\"", "]", "[", ":", "]", "iml_table", "=", "self", ".", "imls", "[", "\"SA\"", "]", "[", ":", "]", "else", ":", "periods", "=", "self", ".", "stddevs", "[", "val_type", "]", "[", "\"T\"", "]", "[", ":", "]", "iml_table", "=", "self", ".", "stddevs", "[", "val_type", "]", "[", "\"SA\"", "]", "[", ":", "]", "low_period", "=", "round", "(", "periods", "[", "0", "]", ",", "7", ")", "high_period", "=", "round", "(", "periods", "[", "-", "1", "]", ",", "7", ")", "if", "(", "round", "(", "imt", ".", "period", ",", "7", ")", "<", "low_period", ")", "or", "(", "round", "(", "imt", ".", "period", ",", "7", ")", ">", "high_period", ")", ":", "raise", "ValueError", "(", "\"Spectral period %.3f outside of valid range \"", "\"(%.3f to %.3f)\"", "%", "(", "imt", ".", "period", ",", "periods", "[", "0", "]", ",", "periods", "[", "-", "1", "]", ")", ")", "# Apply log-log interpolation for spectral period", "interpolator", "=", "interp1d", "(", "numpy", ".", "log10", "(", "periods", ")", ",", "numpy", ".", "log10", "(", "iml_table", ")", ",", "axis", "=", "1", ")", "iml_table", "=", "10.", "**", "interpolator", "(", "numpy", ".", "log10", "(", "imt", ".", "period", ")", ")", "return", "self", ".", "apply_magnitude_interpolation", "(", "mag", ",", "iml_table", ")" ]
Returns the vector of ground motions or standard deviations corresponding to the specific magnitude and intensity measure type. :param val_type: String indicating the type of data {"IMLs", "Total", "Inter" etc}
[ "Returns", "the", "vector", "of", "ground", "motions", "or", "standard", "deviations", "corresponding", "to", "the", "specific", "magnitude", "and", "intensity", "measure", "type", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/gmpe_table.py#L482-L518
train
233,137
gem/oq-engine
openquake/hazardlib/gsim/gmpe_table.py
GMPETable.apply_magnitude_interpolation
def apply_magnitude_interpolation(self, mag, iml_table): """ Interpolates the tables to the required magnitude level :param float mag: Magnitude :param iml_table: Intensity measure level table """ # do not allow "mag" to exceed maximum table magnitude if mag > self.m_w[-1]: mag = self.m_w[-1] # Get magnitude values if mag < self.m_w[0] or mag > self.m_w[-1]: raise ValueError("Magnitude %.2f outside of supported range " "(%.2f to %.2f)" % (mag, self.m_w[0], self.m_w[-1])) # It is assumed that log10 of the spectral acceleration scales # linearly (or approximately linearly) with magnitude m_interpolator = interp1d(self.m_w, numpy.log10(iml_table), axis=1) return 10.0 ** m_interpolator(mag)
python
def apply_magnitude_interpolation(self, mag, iml_table): """ Interpolates the tables to the required magnitude level :param float mag: Magnitude :param iml_table: Intensity measure level table """ # do not allow "mag" to exceed maximum table magnitude if mag > self.m_w[-1]: mag = self.m_w[-1] # Get magnitude values if mag < self.m_w[0] or mag > self.m_w[-1]: raise ValueError("Magnitude %.2f outside of supported range " "(%.2f to %.2f)" % (mag, self.m_w[0], self.m_w[-1])) # It is assumed that log10 of the spectral acceleration scales # linearly (or approximately linearly) with magnitude m_interpolator = interp1d(self.m_w, numpy.log10(iml_table), axis=1) return 10.0 ** m_interpolator(mag)
[ "def", "apply_magnitude_interpolation", "(", "self", ",", "mag", ",", "iml_table", ")", ":", "# do not allow \"mag\" to exceed maximum table magnitude", "if", "mag", ">", "self", ".", "m_w", "[", "-", "1", "]", ":", "mag", "=", "self", ".", "m_w", "[", "-", "1", "]", "# Get magnitude values", "if", "mag", "<", "self", ".", "m_w", "[", "0", "]", "or", "mag", ">", "self", ".", "m_w", "[", "-", "1", "]", ":", "raise", "ValueError", "(", "\"Magnitude %.2f outside of supported range \"", "\"(%.2f to %.2f)\"", "%", "(", "mag", ",", "self", ".", "m_w", "[", "0", "]", ",", "self", ".", "m_w", "[", "-", "1", "]", ")", ")", "# It is assumed that log10 of the spectral acceleration scales", "# linearly (or approximately linearly) with magnitude", "m_interpolator", "=", "interp1d", "(", "self", ".", "m_w", ",", "numpy", ".", "log10", "(", "iml_table", ")", ",", "axis", "=", "1", ")", "return", "10.0", "**", "m_interpolator", "(", "mag", ")" ]
Interpolates the tables to the required magnitude level :param float mag: Magnitude :param iml_table: Intensity measure level table
[ "Interpolates", "the", "tables", "to", "the", "required", "magnitude", "level" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/gmpe_table.py#L520-L542
train
233,138
gem/oq-engine
openquake/hazardlib/gsim/sadigh_1997.py
SadighEtAl1997._get_mean_deep_soil
def _get_mean_deep_soil(self, mag, rake, rrup, is_reverse, imt): """ Calculate and return the mean intensity for deep soil sites. Implements an equation from table 4. """ if mag <= self.NEAR_FIELD_SATURATION_MAG: c4 = self.COEFFS_SOIL_IMT_INDEPENDENT['c4lowmag'] c5 = self.COEFFS_SOIL_IMT_INDEPENDENT['c5lowmag'] else: c4 = self.COEFFS_SOIL_IMT_INDEPENDENT['c4himag'] c5 = self.COEFFS_SOIL_IMT_INDEPENDENT['c5himag'] c2 = self.COEFFS_SOIL_IMT_INDEPENDENT['c2'] c3 = self.COEFFS_SOIL_IMT_INDEPENDENT['c3'] C = self.COEFFS_SOIL[imt] if is_reverse: c1 = self.COEFFS_SOIL_IMT_INDEPENDENT['c1r'] c6 = C['c6r'] else: c1 = self.COEFFS_SOIL_IMT_INDEPENDENT['c1ss'] c6 = C['c6ss'] # clip mag if greater than 8.5. This is to avoid # ValueError: negative number cannot be raised to a fractional power mag = 8.5 if mag > 8.5 else mag return (c1 + c2 * mag + c6 + C['c7'] * ((8.5 - mag) ** 2.5) - c3 * numpy.log(rrup + c4 * numpy.exp(c5 * mag)))
python
def _get_mean_deep_soil(self, mag, rake, rrup, is_reverse, imt): """ Calculate and return the mean intensity for deep soil sites. Implements an equation from table 4. """ if mag <= self.NEAR_FIELD_SATURATION_MAG: c4 = self.COEFFS_SOIL_IMT_INDEPENDENT['c4lowmag'] c5 = self.COEFFS_SOIL_IMT_INDEPENDENT['c5lowmag'] else: c4 = self.COEFFS_SOIL_IMT_INDEPENDENT['c4himag'] c5 = self.COEFFS_SOIL_IMT_INDEPENDENT['c5himag'] c2 = self.COEFFS_SOIL_IMT_INDEPENDENT['c2'] c3 = self.COEFFS_SOIL_IMT_INDEPENDENT['c3'] C = self.COEFFS_SOIL[imt] if is_reverse: c1 = self.COEFFS_SOIL_IMT_INDEPENDENT['c1r'] c6 = C['c6r'] else: c1 = self.COEFFS_SOIL_IMT_INDEPENDENT['c1ss'] c6 = C['c6ss'] # clip mag if greater than 8.5. This is to avoid # ValueError: negative number cannot be raised to a fractional power mag = 8.5 if mag > 8.5 else mag return (c1 + c2 * mag + c6 + C['c7'] * ((8.5 - mag) ** 2.5) - c3 * numpy.log(rrup + c4 * numpy.exp(c5 * mag)))
[ "def", "_get_mean_deep_soil", "(", "self", ",", "mag", ",", "rake", ",", "rrup", ",", "is_reverse", ",", "imt", ")", ":", "if", "mag", "<=", "self", ".", "NEAR_FIELD_SATURATION_MAG", ":", "c4", "=", "self", ".", "COEFFS_SOIL_IMT_INDEPENDENT", "[", "'c4lowmag'", "]", "c5", "=", "self", ".", "COEFFS_SOIL_IMT_INDEPENDENT", "[", "'c5lowmag'", "]", "else", ":", "c4", "=", "self", ".", "COEFFS_SOIL_IMT_INDEPENDENT", "[", "'c4himag'", "]", "c5", "=", "self", ".", "COEFFS_SOIL_IMT_INDEPENDENT", "[", "'c5himag'", "]", "c2", "=", "self", ".", "COEFFS_SOIL_IMT_INDEPENDENT", "[", "'c2'", "]", "c3", "=", "self", ".", "COEFFS_SOIL_IMT_INDEPENDENT", "[", "'c3'", "]", "C", "=", "self", ".", "COEFFS_SOIL", "[", "imt", "]", "if", "is_reverse", ":", "c1", "=", "self", ".", "COEFFS_SOIL_IMT_INDEPENDENT", "[", "'c1r'", "]", "c6", "=", "C", "[", "'c6r'", "]", "else", ":", "c1", "=", "self", ".", "COEFFS_SOIL_IMT_INDEPENDENT", "[", "'c1ss'", "]", "c6", "=", "C", "[", "'c6ss'", "]", "# clip mag if greater than 8.5. This is to avoid", "# ValueError: negative number cannot be raised to a fractional power", "mag", "=", "8.5", "if", "mag", ">", "8.5", "else", "mag", "return", "(", "c1", "+", "c2", "*", "mag", "+", "c6", "+", "C", "[", "'c7'", "]", "*", "(", "(", "8.5", "-", "mag", ")", "**", "2.5", ")", "-", "c3", "*", "numpy", ".", "log", "(", "rrup", "+", "c4", "*", "numpy", ".", "exp", "(", "c5", "*", "mag", ")", ")", ")" ]
Calculate and return the mean intensity for deep soil sites. Implements an equation from table 4.
[ "Calculate", "and", "return", "the", "mean", "intensity", "for", "deep", "soil", "sites", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/sadigh_1997.py#L114-L139
train
233,139
gem/oq-engine
openquake/hazardlib/gsim/sadigh_1997.py
SadighEtAl1997._get_mean_rock
def _get_mean_rock(self, mag, _rake, rrup, is_reverse, imt): """ Calculate and return the mean intensity for rock sites. Implements an equation from table 2. """ if mag <= self.NEAR_FIELD_SATURATION_MAG: C = self.COEFFS_ROCK_LOWMAG[imt] else: C = self.COEFFS_ROCK_HIMAG[imt] # clip mag if greater than 8.5. This is to avoid # ValueError: negative number cannot be raised to a fractional power mag = 8.5 if mag > 8.5 else mag mean = ( C['c1'] + C['c2'] * mag + C['c3'] * ((8.5 - mag) ** 2.5) + C['c4'] * numpy.log(rrup + numpy.exp(C['c5'] + C['c6'] * mag)) + C['c7'] * numpy.log(rrup + 2) ) if is_reverse: # footnote in table 2 says that for reverse ruptures # the mean amplitude value should be multiplied by 1.2 mean += 0.1823215567939546 # == log(1.2) return mean
python
def _get_mean_rock(self, mag, _rake, rrup, is_reverse, imt): """ Calculate and return the mean intensity for rock sites. Implements an equation from table 2. """ if mag <= self.NEAR_FIELD_SATURATION_MAG: C = self.COEFFS_ROCK_LOWMAG[imt] else: C = self.COEFFS_ROCK_HIMAG[imt] # clip mag if greater than 8.5. This is to avoid # ValueError: negative number cannot be raised to a fractional power mag = 8.5 if mag > 8.5 else mag mean = ( C['c1'] + C['c2'] * mag + C['c3'] * ((8.5 - mag) ** 2.5) + C['c4'] * numpy.log(rrup + numpy.exp(C['c5'] + C['c6'] * mag)) + C['c7'] * numpy.log(rrup + 2) ) if is_reverse: # footnote in table 2 says that for reverse ruptures # the mean amplitude value should be multiplied by 1.2 mean += 0.1823215567939546 # == log(1.2) return mean
[ "def", "_get_mean_rock", "(", "self", ",", "mag", ",", "_rake", ",", "rrup", ",", "is_reverse", ",", "imt", ")", ":", "if", "mag", "<=", "self", ".", "NEAR_FIELD_SATURATION_MAG", ":", "C", "=", "self", ".", "COEFFS_ROCK_LOWMAG", "[", "imt", "]", "else", ":", "C", "=", "self", ".", "COEFFS_ROCK_HIMAG", "[", "imt", "]", "# clip mag if greater than 8.5. This is to avoid", "# ValueError: negative number cannot be raised to a fractional power", "mag", "=", "8.5", "if", "mag", ">", "8.5", "else", "mag", "mean", "=", "(", "C", "[", "'c1'", "]", "+", "C", "[", "'c2'", "]", "*", "mag", "+", "C", "[", "'c3'", "]", "*", "(", "(", "8.5", "-", "mag", ")", "**", "2.5", ")", "+", "C", "[", "'c4'", "]", "*", "numpy", ".", "log", "(", "rrup", "+", "numpy", ".", "exp", "(", "C", "[", "'c5'", "]", "+", "C", "[", "'c6'", "]", "*", "mag", ")", ")", "+", "C", "[", "'c7'", "]", "*", "numpy", ".", "log", "(", "rrup", "+", "2", ")", ")", "if", "is_reverse", ":", "# footnote in table 2 says that for reverse ruptures", "# the mean amplitude value should be multiplied by 1.2", "mean", "+=", "0.1823215567939546", "# == log(1.2)", "return", "mean" ]
Calculate and return the mean intensity for rock sites. Implements an equation from table 2.
[ "Calculate", "and", "return", "the", "mean", "intensity", "for", "rock", "sites", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/sadigh_1997.py#L141-L163
train
233,140
gem/oq-engine
openquake/hazardlib/gsim/sadigh_1997.py
SadighEtAl1997._get_stddev_rock
def _get_stddev_rock(self, mag, imt): """ Calculate and return total standard deviation for rock sites. Implements formulae from table 3. """ C = self.COEFFS_ROCK_STDDERR[imt] if mag > C['maxmag']: return C['maxsigma'] else: return C['sigma0'] + C['magfactor'] * mag
python
def _get_stddev_rock(self, mag, imt): """ Calculate and return total standard deviation for rock sites. Implements formulae from table 3. """ C = self.COEFFS_ROCK_STDDERR[imt] if mag > C['maxmag']: return C['maxsigma'] else: return C['sigma0'] + C['magfactor'] * mag
[ "def", "_get_stddev_rock", "(", "self", ",", "mag", ",", "imt", ")", ":", "C", "=", "self", ".", "COEFFS_ROCK_STDDERR", "[", "imt", "]", "if", "mag", ">", "C", "[", "'maxmag'", "]", ":", "return", "C", "[", "'maxsigma'", "]", "else", ":", "return", "C", "[", "'sigma0'", "]", "+", "C", "[", "'magfactor'", "]", "*", "mag" ]
Calculate and return total standard deviation for rock sites. Implements formulae from table 3.
[ "Calculate", "and", "return", "total", "standard", "deviation", "for", "rock", "sites", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/sadigh_1997.py#L165-L175
train
233,141
gem/oq-engine
openquake/hazardlib/gsim/sadigh_1997.py
SadighEtAl1997._get_stddev_deep_soil
def _get_stddev_deep_soil(self, mag, imt): """ Calculate and return total standard deviation for deep soil sites. Implements formulae from the last column of table 4. """ # footnote from table 4 says that stderr for magnitudes over 7 # is equal to one of magnitude 7. if mag > 7: mag = 7 C = self.COEFFS_SOIL[imt] return C['sigma0'] + C['magfactor'] * mag
python
def _get_stddev_deep_soil(self, mag, imt): """ Calculate and return total standard deviation for deep soil sites. Implements formulae from the last column of table 4. """ # footnote from table 4 says that stderr for magnitudes over 7 # is equal to one of magnitude 7. if mag > 7: mag = 7 C = self.COEFFS_SOIL[imt] return C['sigma0'] + C['magfactor'] * mag
[ "def", "_get_stddev_deep_soil", "(", "self", ",", "mag", ",", "imt", ")", ":", "# footnote from table 4 says that stderr for magnitudes over 7", "# is equal to one of magnitude 7.", "if", "mag", ">", "7", ":", "mag", "=", "7", "C", "=", "self", ".", "COEFFS_SOIL", "[", "imt", "]", "return", "C", "[", "'sigma0'", "]", "+", "C", "[", "'magfactor'", "]", "*", "mag" ]
Calculate and return total standard deviation for deep soil sites. Implements formulae from the last column of table 4.
[ "Calculate", "and", "return", "total", "standard", "deviation", "for", "deep", "soil", "sites", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/sadigh_1997.py#L177-L188
train
233,142
gem/oq-engine
openquake/commands/zip.py
zip
def zip(what, archive_zip='', risk_file=''): """ Zip into an archive one or two job.ini files with all related files """ if os.path.isdir(what): oqzip.zip_all(what) elif what.endswith('.xml') and '<logicTree' in open(what).read(512): # hack to see if the NRML file is of kind logicTree oqzip.zip_source_model(what, archive_zip) elif what.endswith('.xml') and '<exposureModel' in open(what).read(512): # hack to see if the NRML file is of kind exposureModel oqzip.zip_exposure(what, archive_zip) elif what.endswith('.ini'): # a job.ini oqzip.zip_job(what, archive_zip, risk_file) else: sys.exit('Cannot zip %s' % what)
python
def zip(what, archive_zip='', risk_file=''): """ Zip into an archive one or two job.ini files with all related files """ if os.path.isdir(what): oqzip.zip_all(what) elif what.endswith('.xml') and '<logicTree' in open(what).read(512): # hack to see if the NRML file is of kind logicTree oqzip.zip_source_model(what, archive_zip) elif what.endswith('.xml') and '<exposureModel' in open(what).read(512): # hack to see if the NRML file is of kind exposureModel oqzip.zip_exposure(what, archive_zip) elif what.endswith('.ini'): # a job.ini oqzip.zip_job(what, archive_zip, risk_file) else: sys.exit('Cannot zip %s' % what)
[ "def", "zip", "(", "what", ",", "archive_zip", "=", "''", ",", "risk_file", "=", "''", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "what", ")", ":", "oqzip", ".", "zip_all", "(", "what", ")", "elif", "what", ".", "endswith", "(", "'.xml'", ")", "and", "'<logicTree'", "in", "open", "(", "what", ")", ".", "read", "(", "512", ")", ":", "# hack to see if the NRML file is of kind logicTree", "oqzip", ".", "zip_source_model", "(", "what", ",", "archive_zip", ")", "elif", "what", ".", "endswith", "(", "'.xml'", ")", "and", "'<exposureModel'", "in", "open", "(", "what", ")", ".", "read", "(", "512", ")", ":", "# hack to see if the NRML file is of kind exposureModel", "oqzip", ".", "zip_exposure", "(", "what", ",", "archive_zip", ")", "elif", "what", ".", "endswith", "(", "'.ini'", ")", ":", "# a job.ini", "oqzip", ".", "zip_job", "(", "what", ",", "archive_zip", ",", "risk_file", ")", "else", ":", "sys", ".", "exit", "(", "'Cannot zip %s'", "%", "what", ")" ]
Zip into an archive one or two job.ini files with all related files
[ "Zip", "into", "an", "archive", "one", "or", "two", "job", ".", "ini", "files", "with", "all", "related", "files" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/zip.py#L25-L40
train
233,143
gem/oq-engine
openquake/commands/reduce.py
reduce
def reduce(fname, reduction_factor): """ Produce a submodel from `fname` by sampling the nodes randomly. Supports source models, site models and exposure models. As a special case, it is also able to reduce .csv files by sampling the lines. This is a debugging utility to reduce large computations to small ones. """ if fname.endswith('.csv'): with open(fname) as f: line = f.readline() # read the first line if csv.Sniffer().has_header(line): header = line all_lines = f.readlines() else: header = None f.seek(0) all_lines = f.readlines() lines = general.random_filter(all_lines, reduction_factor) shutil.copy(fname, fname + '.bak') print('Copied the original file in %s.bak' % fname) _save_csv(fname, lines, header) print('Extracted %d lines out of %d' % (len(lines), len(all_lines))) return elif fname.endswith('.npy'): array = numpy.load(fname) shutil.copy(fname, fname + '.bak') print('Copied the original file in %s.bak' % fname) arr = numpy.array(general.random_filter(array, reduction_factor)) numpy.save(fname, arr) print('Extracted %d rows out of %d' % (len(arr), len(array))) return node = nrml.read(fname) model = node[0] if model.tag.endswith('exposureModel'): total = len(model.assets) model.assets.nodes = general.random_filter( model.assets, reduction_factor) num_nodes = len(model.assets) elif model.tag.endswith('siteModel'): total = len(model) model.nodes = general.random_filter(model, reduction_factor) num_nodes = len(model) elif model.tag.endswith('sourceModel'): reduce_source_model(fname, reduction_factor) return elif model.tag.endswith('logicTree'): for smpath in logictree.collect_info(fname).smpaths: reduce_source_model(smpath, reduction_factor) return else: raise RuntimeError('Unknown model tag: %s' % model.tag) save_bak(fname, node, num_nodes, total)
python
def reduce(fname, reduction_factor): """ Produce a submodel from `fname` by sampling the nodes randomly. Supports source models, site models and exposure models. As a special case, it is also able to reduce .csv files by sampling the lines. This is a debugging utility to reduce large computations to small ones. """ if fname.endswith('.csv'): with open(fname) as f: line = f.readline() # read the first line if csv.Sniffer().has_header(line): header = line all_lines = f.readlines() else: header = None f.seek(0) all_lines = f.readlines() lines = general.random_filter(all_lines, reduction_factor) shutil.copy(fname, fname + '.bak') print('Copied the original file in %s.bak' % fname) _save_csv(fname, lines, header) print('Extracted %d lines out of %d' % (len(lines), len(all_lines))) return elif fname.endswith('.npy'): array = numpy.load(fname) shutil.copy(fname, fname + '.bak') print('Copied the original file in %s.bak' % fname) arr = numpy.array(general.random_filter(array, reduction_factor)) numpy.save(fname, arr) print('Extracted %d rows out of %d' % (len(arr), len(array))) return node = nrml.read(fname) model = node[0] if model.tag.endswith('exposureModel'): total = len(model.assets) model.assets.nodes = general.random_filter( model.assets, reduction_factor) num_nodes = len(model.assets) elif model.tag.endswith('siteModel'): total = len(model) model.nodes = general.random_filter(model, reduction_factor) num_nodes = len(model) elif model.tag.endswith('sourceModel'): reduce_source_model(fname, reduction_factor) return elif model.tag.endswith('logicTree'): for smpath in logictree.collect_info(fname).smpaths: reduce_source_model(smpath, reduction_factor) return else: raise RuntimeError('Unknown model tag: %s' % model.tag) save_bak(fname, node, num_nodes, total)
[ "def", "reduce", "(", "fname", ",", "reduction_factor", ")", ":", "if", "fname", ".", "endswith", "(", "'.csv'", ")", ":", "with", "open", "(", "fname", ")", "as", "f", ":", "line", "=", "f", ".", "readline", "(", ")", "# read the first line", "if", "csv", ".", "Sniffer", "(", ")", ".", "has_header", "(", "line", ")", ":", "header", "=", "line", "all_lines", "=", "f", ".", "readlines", "(", ")", "else", ":", "header", "=", "None", "f", ".", "seek", "(", "0", ")", "all_lines", "=", "f", ".", "readlines", "(", ")", "lines", "=", "general", ".", "random_filter", "(", "all_lines", ",", "reduction_factor", ")", "shutil", ".", "copy", "(", "fname", ",", "fname", "+", "'.bak'", ")", "print", "(", "'Copied the original file in %s.bak'", "%", "fname", ")", "_save_csv", "(", "fname", ",", "lines", ",", "header", ")", "print", "(", "'Extracted %d lines out of %d'", "%", "(", "len", "(", "lines", ")", ",", "len", "(", "all_lines", ")", ")", ")", "return", "elif", "fname", ".", "endswith", "(", "'.npy'", ")", ":", "array", "=", "numpy", ".", "load", "(", "fname", ")", "shutil", ".", "copy", "(", "fname", ",", "fname", "+", "'.bak'", ")", "print", "(", "'Copied the original file in %s.bak'", "%", "fname", ")", "arr", "=", "numpy", ".", "array", "(", "general", ".", "random_filter", "(", "array", ",", "reduction_factor", ")", ")", "numpy", ".", "save", "(", "fname", ",", "arr", ")", "print", "(", "'Extracted %d rows out of %d'", "%", "(", "len", "(", "arr", ")", ",", "len", "(", "array", ")", ")", ")", "return", "node", "=", "nrml", ".", "read", "(", "fname", ")", "model", "=", "node", "[", "0", "]", "if", "model", ".", "tag", ".", "endswith", "(", "'exposureModel'", ")", ":", "total", "=", "len", "(", "model", ".", "assets", ")", "model", ".", "assets", ".", "nodes", "=", "general", ".", "random_filter", "(", "model", ".", "assets", ",", "reduction_factor", ")", "num_nodes", "=", "len", "(", "model", ".", "assets", ")", "elif", "model", ".", "tag", ".", "endswith", "(", "'siteModel'", ")", ":", "total", "=", "len", "(", "model", ")", "model", ".", "nodes", "=", "general", ".", "random_filter", "(", "model", ",", "reduction_factor", ")", "num_nodes", "=", "len", "(", "model", ")", "elif", "model", ".", "tag", ".", "endswith", "(", "'sourceModel'", ")", ":", "reduce_source_model", "(", "fname", ",", "reduction_factor", ")", "return", "elif", "model", ".", "tag", ".", "endswith", "(", "'logicTree'", ")", ":", "for", "smpath", "in", "logictree", ".", "collect_info", "(", "fname", ")", ".", "smpaths", ":", "reduce_source_model", "(", "smpath", ",", "reduction_factor", ")", "return", "else", ":", "raise", "RuntimeError", "(", "'Unknown model tag: %s'", "%", "model", ".", "tag", ")", "save_bak", "(", "fname", ",", "node", ",", "num_nodes", ",", "total", ")" ]
Produce a submodel from `fname` by sampling the nodes randomly. Supports source models, site models and exposure models. As a special case, it is also able to reduce .csv files by sampling the lines. This is a debugging utility to reduce large computations to small ones.
[ "Produce", "a", "submodel", "from", "fname", "by", "sampling", "the", "nodes", "randomly", ".", "Supports", "source", "models", "site", "models", "and", "exposure", "models", ".", "As", "a", "special", "case", "it", "is", "also", "able", "to", "reduce", ".", "csv", "files", "by", "sampling", "the", "lines", ".", "This", "is", "a", "debugging", "utility", "to", "reduce", "large", "computations", "to", "small", "ones", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/reduce.py#L60-L111
train
233,144
gem/oq-engine
openquake/hazardlib/geo/surface/base.py
downsample_mesh
def downsample_mesh(mesh, tol=1.0): """ Returns a mesh sampled at a lower resolution - if the difference in azimuth is larger than the specified tolerance a turn is assumed :returns: Downsampled mesh as instance of :class: openquake.hazardlib.geo.mesh.RectangularMesh """ idx = _find_turning_points(mesh, tol) if mesh.depths is not None: return RectangularMesh(lons=mesh.lons[:, idx], lats=mesh.lats[:, idx], depths=mesh.depths[:, idx]) else: return RectangularMesh(lons=mesh.lons[:, idx], lats=mesh.lats[:, idx])
python
def downsample_mesh(mesh, tol=1.0): """ Returns a mesh sampled at a lower resolution - if the difference in azimuth is larger than the specified tolerance a turn is assumed :returns: Downsampled mesh as instance of :class: openquake.hazardlib.geo.mesh.RectangularMesh """ idx = _find_turning_points(mesh, tol) if mesh.depths is not None: return RectangularMesh(lons=mesh.lons[:, idx], lats=mesh.lats[:, idx], depths=mesh.depths[:, idx]) else: return RectangularMesh(lons=mesh.lons[:, idx], lats=mesh.lats[:, idx])
[ "def", "downsample_mesh", "(", "mesh", ",", "tol", "=", "1.0", ")", ":", "idx", "=", "_find_turning_points", "(", "mesh", ",", "tol", ")", "if", "mesh", ".", "depths", "is", "not", "None", ":", "return", "RectangularMesh", "(", "lons", "=", "mesh", ".", "lons", "[", ":", ",", "idx", "]", ",", "lats", "=", "mesh", ".", "lats", "[", ":", ",", "idx", "]", ",", "depths", "=", "mesh", ".", "depths", "[", ":", ",", "idx", "]", ")", "else", ":", "return", "RectangularMesh", "(", "lons", "=", "mesh", ".", "lons", "[", ":", ",", "idx", "]", ",", "lats", "=", "mesh", ".", "lats", "[", ":", ",", "idx", "]", ")" ]
Returns a mesh sampled at a lower resolution - if the difference in azimuth is larger than the specified tolerance a turn is assumed :returns: Downsampled mesh as instance of :class: openquake.hazardlib.geo.mesh.RectangularMesh
[ "Returns", "a", "mesh", "sampled", "at", "a", "lower", "resolution", "-", "if", "the", "difference", "in", "azimuth", "is", "larger", "than", "the", "specified", "tolerance", "a", "turn", "is", "assumed" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/base.py#L64-L80
train
233,145
gem/oq-engine
openquake/hazardlib/geo/surface/base.py
downsample_trace
def downsample_trace(mesh, tol=1.0): """ Downsamples the upper edge of a fault within a rectangular mesh, retaining node points only if changes in direction on the order of tol are found :returns: Downsampled edge as a numpy array of [long, lat, depth] """ idx = _find_turning_points(mesh, tol) if mesh.depths is not None: return numpy.column_stack([mesh.lons[0, idx], mesh.lats[0, idx], mesh.depths[0, idx]]) else: return numpy.column_stack([mesh.lons[0, idx], mesh.lats[0, idx]])
python
def downsample_trace(mesh, tol=1.0): """ Downsamples the upper edge of a fault within a rectangular mesh, retaining node points only if changes in direction on the order of tol are found :returns: Downsampled edge as a numpy array of [long, lat, depth] """ idx = _find_turning_points(mesh, tol) if mesh.depths is not None: return numpy.column_stack([mesh.lons[0, idx], mesh.lats[0, idx], mesh.depths[0, idx]]) else: return numpy.column_stack([mesh.lons[0, idx], mesh.lats[0, idx]])
[ "def", "downsample_trace", "(", "mesh", ",", "tol", "=", "1.0", ")", ":", "idx", "=", "_find_turning_points", "(", "mesh", ",", "tol", ")", "if", "mesh", ".", "depths", "is", "not", "None", ":", "return", "numpy", ".", "column_stack", "(", "[", "mesh", ".", "lons", "[", "0", ",", "idx", "]", ",", "mesh", ".", "lats", "[", "0", ",", "idx", "]", ",", "mesh", ".", "depths", "[", "0", ",", "idx", "]", "]", ")", "else", ":", "return", "numpy", ".", "column_stack", "(", "[", "mesh", ".", "lons", "[", "0", ",", "idx", "]", ",", "mesh", ".", "lats", "[", "0", ",", "idx", "]", "]", ")" ]
Downsamples the upper edge of a fault within a rectangular mesh, retaining node points only if changes in direction on the order of tol are found :returns: Downsampled edge as a numpy array of [long, lat, depth]
[ "Downsamples", "the", "upper", "edge", "of", "a", "fault", "within", "a", "rectangular", "mesh", "retaining", "node", "points", "only", "if", "changes", "in", "direction", "on", "the", "order", "of", "tol", "are", "found" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/base.py#L83-L97
train
233,146
gem/oq-engine
openquake/hazardlib/geo/surface/base.py
BaseSurface.get_ry0_distance
def get_ry0_distance(self, mesh): """ Compute the minimum distance between each point of a mesh and the great circle arcs perpendicular to the average strike direction of the fault trace and passing through the end-points of the trace. :param mesh: :class:`~openquake.hazardlib.geo.mesh.Mesh` of points to calculate Ry0-distance to. :returns: Numpy array of distances in km. """ # This computes ry0 by using an average strike direction top_edge = self.mesh[0:1] mean_strike = self.get_strike() dst1 = geodetic.distance_to_arc(top_edge.lons[0, 0], top_edge.lats[0, 0], (mean_strike + 90.) % 360, mesh.lons, mesh.lats) dst2 = geodetic.distance_to_arc(top_edge.lons[0, -1], top_edge.lats[0, -1], (mean_strike + 90.) % 360, mesh.lons, mesh.lats) # Find the points on the rupture # Get the shortest distance from the two lines idx = numpy.sign(dst1) == numpy.sign(dst2) dst = numpy.zeros_like(dst1) dst[idx] = numpy.fmin(numpy.abs(dst1[idx]), numpy.abs(dst2[idx])) return dst
python
def get_ry0_distance(self, mesh): """ Compute the minimum distance between each point of a mesh and the great circle arcs perpendicular to the average strike direction of the fault trace and passing through the end-points of the trace. :param mesh: :class:`~openquake.hazardlib.geo.mesh.Mesh` of points to calculate Ry0-distance to. :returns: Numpy array of distances in km. """ # This computes ry0 by using an average strike direction top_edge = self.mesh[0:1] mean_strike = self.get_strike() dst1 = geodetic.distance_to_arc(top_edge.lons[0, 0], top_edge.lats[0, 0], (mean_strike + 90.) % 360, mesh.lons, mesh.lats) dst2 = geodetic.distance_to_arc(top_edge.lons[0, -1], top_edge.lats[0, -1], (mean_strike + 90.) % 360, mesh.lons, mesh.lats) # Find the points on the rupture # Get the shortest distance from the two lines idx = numpy.sign(dst1) == numpy.sign(dst2) dst = numpy.zeros_like(dst1) dst[idx] = numpy.fmin(numpy.abs(dst1[idx]), numpy.abs(dst2[idx])) return dst
[ "def", "get_ry0_distance", "(", "self", ",", "mesh", ")", ":", "# This computes ry0 by using an average strike direction", "top_edge", "=", "self", ".", "mesh", "[", "0", ":", "1", "]", "mean_strike", "=", "self", ".", "get_strike", "(", ")", "dst1", "=", "geodetic", ".", "distance_to_arc", "(", "top_edge", ".", "lons", "[", "0", ",", "0", "]", ",", "top_edge", ".", "lats", "[", "0", ",", "0", "]", ",", "(", "mean_strike", "+", "90.", ")", "%", "360", ",", "mesh", ".", "lons", ",", "mesh", ".", "lats", ")", "dst2", "=", "geodetic", ".", "distance_to_arc", "(", "top_edge", ".", "lons", "[", "0", ",", "-", "1", "]", ",", "top_edge", ".", "lats", "[", "0", ",", "-", "1", "]", ",", "(", "mean_strike", "+", "90.", ")", "%", "360", ",", "mesh", ".", "lons", ",", "mesh", ".", "lats", ")", "# Find the points on the rupture", "# Get the shortest distance from the two lines", "idx", "=", "numpy", ".", "sign", "(", "dst1", ")", "==", "numpy", ".", "sign", "(", "dst2", ")", "dst", "=", "numpy", ".", "zeros_like", "(", "dst1", ")", "dst", "[", "idx", "]", "=", "numpy", ".", "fmin", "(", "numpy", ".", "abs", "(", "dst1", "[", "idx", "]", ")", ",", "numpy", ".", "abs", "(", "dst2", "[", "idx", "]", ")", ")", "return", "dst" ]
Compute the minimum distance between each point of a mesh and the great circle arcs perpendicular to the average strike direction of the fault trace and passing through the end-points of the trace. :param mesh: :class:`~openquake.hazardlib.geo.mesh.Mesh` of points to calculate Ry0-distance to. :returns: Numpy array of distances in km.
[ "Compute", "the", "minimum", "distance", "between", "each", "point", "of", "a", "mesh", "and", "the", "great", "circle", "arcs", "perpendicular", "to", "the", "average", "strike", "direction", "of", "the", "fault", "trace", "and", "passing", "through", "the", "end", "-", "points", "of", "the", "trace", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/base.py#L148-L180
train
233,147
gem/oq-engine
openquake/hazardlib/geo/surface/base.py
BaseSurface.get_rx_distance
def get_rx_distance(self, mesh): """ Compute distance between each point of mesh and surface's great circle arc. Distance is measured perpendicular to the rupture strike, from the surface projection of the updip edge of the rupture, with the down dip direction being positive (this distance is usually called ``Rx``). In other words, is the horizontal distance to top edge of rupture measured perpendicular to the strike. Values on the hanging wall are positive, values on the footwall are negative. :param mesh: :class:`~openquake.hazardlib.geo.mesh.Mesh` of points to calculate Rx-distance to. :returns: Numpy array of distances in km. """ top_edge = self.mesh[0:1] dists = [] if top_edge.lons.shape[1] < 3: i = 0 p1 = Point( top_edge.lons[0, i], top_edge.lats[0, i], top_edge.depths[0, i] ) p2 = Point( top_edge.lons[0, i + 1], top_edge.lats[0, i + 1], top_edge.depths[0, i + 1] ) azimuth = p1.azimuth(p2) dists.append( geodetic.distance_to_arc( p1.longitude, p1.latitude, azimuth, mesh.lons, mesh.lats ) ) else: for i in range(top_edge.lons.shape[1] - 1): p1 = Point( top_edge.lons[0, i], top_edge.lats[0, i], top_edge.depths[0, i] ) p2 = Point( top_edge.lons[0, i + 1], top_edge.lats[0, i + 1], top_edge.depths[0, i + 1] ) # Swapping if i == 0: pt = p1 p1 = p2 p2 = pt # Computing azimuth and distance if i == 0 or i == top_edge.lons.shape[1] - 2: azimuth = p1.azimuth(p2) tmp = geodetic.distance_to_semi_arc(p1.longitude, p1.latitude, azimuth, mesh.lons, mesh.lats) else: tmp = geodetic.min_distance_to_segment( numpy.array([p1.longitude, p2.longitude]), numpy.array([p1.latitude, p2.latitude]), mesh.lons, mesh.lats) # Correcting the sign of the distance if i == 0: tmp *= -1 dists.append(tmp) # Computing distances dists = numpy.array(dists) iii = abs(dists).argmin(axis=0) dst = dists[iii, list(range(dists.shape[1]))] return dst
python
def get_rx_distance(self, mesh): """ Compute distance between each point of mesh and surface's great circle arc. Distance is measured perpendicular to the rupture strike, from the surface projection of the updip edge of the rupture, with the down dip direction being positive (this distance is usually called ``Rx``). In other words, is the horizontal distance to top edge of rupture measured perpendicular to the strike. Values on the hanging wall are positive, values on the footwall are negative. :param mesh: :class:`~openquake.hazardlib.geo.mesh.Mesh` of points to calculate Rx-distance to. :returns: Numpy array of distances in km. """ top_edge = self.mesh[0:1] dists = [] if top_edge.lons.shape[1] < 3: i = 0 p1 = Point( top_edge.lons[0, i], top_edge.lats[0, i], top_edge.depths[0, i] ) p2 = Point( top_edge.lons[0, i + 1], top_edge.lats[0, i + 1], top_edge.depths[0, i + 1] ) azimuth = p1.azimuth(p2) dists.append( geodetic.distance_to_arc( p1.longitude, p1.latitude, azimuth, mesh.lons, mesh.lats ) ) else: for i in range(top_edge.lons.shape[1] - 1): p1 = Point( top_edge.lons[0, i], top_edge.lats[0, i], top_edge.depths[0, i] ) p2 = Point( top_edge.lons[0, i + 1], top_edge.lats[0, i + 1], top_edge.depths[0, i + 1] ) # Swapping if i == 0: pt = p1 p1 = p2 p2 = pt # Computing azimuth and distance if i == 0 or i == top_edge.lons.shape[1] - 2: azimuth = p1.azimuth(p2) tmp = geodetic.distance_to_semi_arc(p1.longitude, p1.latitude, azimuth, mesh.lons, mesh.lats) else: tmp = geodetic.min_distance_to_segment( numpy.array([p1.longitude, p2.longitude]), numpy.array([p1.latitude, p2.latitude]), mesh.lons, mesh.lats) # Correcting the sign of the distance if i == 0: tmp *= -1 dists.append(tmp) # Computing distances dists = numpy.array(dists) iii = abs(dists).argmin(axis=0) dst = dists[iii, list(range(dists.shape[1]))] return dst
[ "def", "get_rx_distance", "(", "self", ",", "mesh", ")", ":", "top_edge", "=", "self", ".", "mesh", "[", "0", ":", "1", "]", "dists", "=", "[", "]", "if", "top_edge", ".", "lons", ".", "shape", "[", "1", "]", "<", "3", ":", "i", "=", "0", "p1", "=", "Point", "(", "top_edge", ".", "lons", "[", "0", ",", "i", "]", ",", "top_edge", ".", "lats", "[", "0", ",", "i", "]", ",", "top_edge", ".", "depths", "[", "0", ",", "i", "]", ")", "p2", "=", "Point", "(", "top_edge", ".", "lons", "[", "0", ",", "i", "+", "1", "]", ",", "top_edge", ".", "lats", "[", "0", ",", "i", "+", "1", "]", ",", "top_edge", ".", "depths", "[", "0", ",", "i", "+", "1", "]", ")", "azimuth", "=", "p1", ".", "azimuth", "(", "p2", ")", "dists", ".", "append", "(", "geodetic", ".", "distance_to_arc", "(", "p1", ".", "longitude", ",", "p1", ".", "latitude", ",", "azimuth", ",", "mesh", ".", "lons", ",", "mesh", ".", "lats", ")", ")", "else", ":", "for", "i", "in", "range", "(", "top_edge", ".", "lons", ".", "shape", "[", "1", "]", "-", "1", ")", ":", "p1", "=", "Point", "(", "top_edge", ".", "lons", "[", "0", ",", "i", "]", ",", "top_edge", ".", "lats", "[", "0", ",", "i", "]", ",", "top_edge", ".", "depths", "[", "0", ",", "i", "]", ")", "p2", "=", "Point", "(", "top_edge", ".", "lons", "[", "0", ",", "i", "+", "1", "]", ",", "top_edge", ".", "lats", "[", "0", ",", "i", "+", "1", "]", ",", "top_edge", ".", "depths", "[", "0", ",", "i", "+", "1", "]", ")", "# Swapping", "if", "i", "==", "0", ":", "pt", "=", "p1", "p1", "=", "p2", "p2", "=", "pt", "# Computing azimuth and distance", "if", "i", "==", "0", "or", "i", "==", "top_edge", ".", "lons", ".", "shape", "[", "1", "]", "-", "2", ":", "azimuth", "=", "p1", ".", "azimuth", "(", "p2", ")", "tmp", "=", "geodetic", ".", "distance_to_semi_arc", "(", "p1", ".", "longitude", ",", "p1", ".", "latitude", ",", "azimuth", ",", "mesh", ".", "lons", ",", "mesh", ".", "lats", ")", "else", ":", "tmp", "=", "geodetic", ".", "min_distance_to_segment", "(", "numpy", ".", "array", "(", "[", "p1", ".", "longitude", ",", "p2", ".", "longitude", "]", ")", ",", "numpy", ".", "array", "(", "[", "p1", ".", "latitude", ",", "p2", ".", "latitude", "]", ")", ",", "mesh", ".", "lons", ",", "mesh", ".", "lats", ")", "# Correcting the sign of the distance", "if", "i", "==", "0", ":", "tmp", "*=", "-", "1", "dists", ".", "append", "(", "tmp", ")", "# Computing distances", "dists", "=", "numpy", ".", "array", "(", "dists", ")", "iii", "=", "abs", "(", "dists", ")", ".", "argmin", "(", "axis", "=", "0", ")", "dst", "=", "dists", "[", "iii", ",", "list", "(", "range", "(", "dists", ".", "shape", "[", "1", "]", ")", ")", "]", "return", "dst" ]
Compute distance between each point of mesh and surface's great circle arc. Distance is measured perpendicular to the rupture strike, from the surface projection of the updip edge of the rupture, with the down dip direction being positive (this distance is usually called ``Rx``). In other words, is the horizontal distance to top edge of rupture measured perpendicular to the strike. Values on the hanging wall are positive, values on the footwall are negative. :param mesh: :class:`~openquake.hazardlib.geo.mesh.Mesh` of points to calculate Rx-distance to. :returns: Numpy array of distances in km.
[ "Compute", "distance", "between", "each", "point", "of", "mesh", "and", "surface", "s", "great", "circle", "arc", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/base.py#L182-L266
train
233,148
gem/oq-engine
openquake/hazardlib/geo/surface/base.py
BaseSurface.get_top_edge_depth
def get_top_edge_depth(self): """ Return minimum depth of surface's top edge. :returns: Float value, the vertical distance between the earth surface and the shallowest point in surface's top edge in km. """ top_edge = self.mesh[0:1] if top_edge.depths is None: return 0 else: return numpy.min(top_edge.depths)
python
def get_top_edge_depth(self): """ Return minimum depth of surface's top edge. :returns: Float value, the vertical distance between the earth surface and the shallowest point in surface's top edge in km. """ top_edge = self.mesh[0:1] if top_edge.depths is None: return 0 else: return numpy.min(top_edge.depths)
[ "def", "get_top_edge_depth", "(", "self", ")", ":", "top_edge", "=", "self", ".", "mesh", "[", "0", ":", "1", "]", "if", "top_edge", ".", "depths", "is", "None", ":", "return", "0", "else", ":", "return", "numpy", ".", "min", "(", "top_edge", ".", "depths", ")" ]
Return minimum depth of surface's top edge. :returns: Float value, the vertical distance between the earth surface and the shallowest point in surface's top edge in km.
[ "Return", "minimum", "depth", "of", "surface", "s", "top", "edge", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/base.py#L268-L280
train
233,149
gem/oq-engine
openquake/hazardlib/geo/surface/base.py
BaseSurface.get_area
def get_area(self): """ Compute area as the sum of the mesh cells area values. """ mesh = self.mesh _, _, _, area = mesh.get_cell_dimensions() return numpy.sum(area)
python
def get_area(self): """ Compute area as the sum of the mesh cells area values. """ mesh = self.mesh _, _, _, area = mesh.get_cell_dimensions() return numpy.sum(area)
[ "def", "get_area", "(", "self", ")", ":", "mesh", "=", "self", ".", "mesh", "_", ",", "_", ",", "_", ",", "area", "=", "mesh", ".", "get_cell_dimensions", "(", ")", "return", "numpy", ".", "sum", "(", "area", ")" ]
Compute area as the sum of the mesh cells area values.
[ "Compute", "area", "as", "the", "sum", "of", "the", "mesh", "cells", "area", "values", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/base.py#L290-L297
train
233,150
gem/oq-engine
openquake/hazardlib/geo/surface/base.py
BaseSurface.get_surface_boundaries
def get_surface_boundaries(self): """ Returns the boundaries in the same format as a multiplanar surface, with two one-element lists of lons and lats """ mesh = self.mesh lons = numpy.concatenate((mesh.lons[0, :], mesh.lons[1:, -1], mesh.lons[-1, :-1][::-1], mesh.lons[:-1, 0][::-1])) lats = numpy.concatenate((mesh.lats[0, :], mesh.lats[1:, -1], mesh.lats[-1, :-1][::-1], mesh.lats[:-1, 0][::-1])) return [lons], [lats]
python
def get_surface_boundaries(self): """ Returns the boundaries in the same format as a multiplanar surface, with two one-element lists of lons and lats """ mesh = self.mesh lons = numpy.concatenate((mesh.lons[0, :], mesh.lons[1:, -1], mesh.lons[-1, :-1][::-1], mesh.lons[:-1, 0][::-1])) lats = numpy.concatenate((mesh.lats[0, :], mesh.lats[1:, -1], mesh.lats[-1, :-1][::-1], mesh.lats[:-1, 0][::-1])) return [lons], [lats]
[ "def", "get_surface_boundaries", "(", "self", ")", ":", "mesh", "=", "self", ".", "mesh", "lons", "=", "numpy", ".", "concatenate", "(", "(", "mesh", ".", "lons", "[", "0", ",", ":", "]", ",", "mesh", ".", "lons", "[", "1", ":", ",", "-", "1", "]", ",", "mesh", ".", "lons", "[", "-", "1", ",", ":", "-", "1", "]", "[", ":", ":", "-", "1", "]", ",", "mesh", ".", "lons", "[", ":", "-", "1", ",", "0", "]", "[", ":", ":", "-", "1", "]", ")", ")", "lats", "=", "numpy", ".", "concatenate", "(", "(", "mesh", ".", "lats", "[", "0", ",", ":", "]", ",", "mesh", ".", "lats", "[", "1", ":", ",", "-", "1", "]", ",", "mesh", ".", "lats", "[", "-", "1", ",", ":", "-", "1", "]", "[", ":", ":", "-", "1", "]", ",", "mesh", ".", "lats", "[", ":", "-", "1", ",", "0", "]", "[", ":", ":", "-", "1", "]", ")", ")", "return", "[", "lons", "]", ",", "[", "lats", "]" ]
Returns the boundaries in the same format as a multiplanar surface, with two one-element lists of lons and lats
[ "Returns", "the", "boundaries", "in", "the", "same", "format", "as", "a", "multiplanar", "surface", "with", "two", "one", "-", "element", "lists", "of", "lons", "and", "lats" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/base.py#L326-L340
train
233,151
gem/oq-engine
openquake/hazardlib/geo/surface/base.py
BaseSurface.get_resampled_top_edge
def get_resampled_top_edge(self, angle_var=0.1): """ This methods computes a simplified representation of a fault top edge by removing the points that are not describing a change of direction, provided a certain tolerance angle. :param float angle_var: Number representing the maximum deviation (in degrees) admitted without the creation of a new segment :returns: A :class:`~openquake.hazardlib.geo.line.Line` representing the rupture surface's top edge. """ mesh = self.mesh top_edge = [Point(mesh.lons[0][0], mesh.lats[0][0], mesh.depths[0][0])] for i in range(len(mesh.triangulate()[1][0]) - 1): v1 = numpy.asarray(mesh.triangulate()[1][0][i]) v2 = numpy.asarray(mesh.triangulate()[1][0][i + 1]) cosang = numpy.dot(v1, v2) sinang = numpy.linalg.norm(numpy.cross(v1, v2)) angle = math.degrees(numpy.arctan2(sinang, cosang)) if abs(angle) > angle_var: top_edge.append(Point(mesh.lons[0][i + 1], mesh.lats[0][i + 1], mesh.depths[0][i + 1])) top_edge.append(Point(mesh.lons[0][-1], mesh.lats[0][-1], mesh.depths[0][-1])) line_top_edge = Line(top_edge) return line_top_edge
python
def get_resampled_top_edge(self, angle_var=0.1): """ This methods computes a simplified representation of a fault top edge by removing the points that are not describing a change of direction, provided a certain tolerance angle. :param float angle_var: Number representing the maximum deviation (in degrees) admitted without the creation of a new segment :returns: A :class:`~openquake.hazardlib.geo.line.Line` representing the rupture surface's top edge. """ mesh = self.mesh top_edge = [Point(mesh.lons[0][0], mesh.lats[0][0], mesh.depths[0][0])] for i in range(len(mesh.triangulate()[1][0]) - 1): v1 = numpy.asarray(mesh.triangulate()[1][0][i]) v2 = numpy.asarray(mesh.triangulate()[1][0][i + 1]) cosang = numpy.dot(v1, v2) sinang = numpy.linalg.norm(numpy.cross(v1, v2)) angle = math.degrees(numpy.arctan2(sinang, cosang)) if abs(angle) > angle_var: top_edge.append(Point(mesh.lons[0][i + 1], mesh.lats[0][i + 1], mesh.depths[0][i + 1])) top_edge.append(Point(mesh.lons[0][-1], mesh.lats[0][-1], mesh.depths[0][-1])) line_top_edge = Line(top_edge) return line_top_edge
[ "def", "get_resampled_top_edge", "(", "self", ",", "angle_var", "=", "0.1", ")", ":", "mesh", "=", "self", ".", "mesh", "top_edge", "=", "[", "Point", "(", "mesh", ".", "lons", "[", "0", "]", "[", "0", "]", ",", "mesh", ".", "lats", "[", "0", "]", "[", "0", "]", ",", "mesh", ".", "depths", "[", "0", "]", "[", "0", "]", ")", "]", "for", "i", "in", "range", "(", "len", "(", "mesh", ".", "triangulate", "(", ")", "[", "1", "]", "[", "0", "]", ")", "-", "1", ")", ":", "v1", "=", "numpy", ".", "asarray", "(", "mesh", ".", "triangulate", "(", ")", "[", "1", "]", "[", "0", "]", "[", "i", "]", ")", "v2", "=", "numpy", ".", "asarray", "(", "mesh", ".", "triangulate", "(", ")", "[", "1", "]", "[", "0", "]", "[", "i", "+", "1", "]", ")", "cosang", "=", "numpy", ".", "dot", "(", "v1", ",", "v2", ")", "sinang", "=", "numpy", ".", "linalg", ".", "norm", "(", "numpy", ".", "cross", "(", "v1", ",", "v2", ")", ")", "angle", "=", "math", ".", "degrees", "(", "numpy", ".", "arctan2", "(", "sinang", ",", "cosang", ")", ")", "if", "abs", "(", "angle", ")", ">", "angle_var", ":", "top_edge", ".", "append", "(", "Point", "(", "mesh", ".", "lons", "[", "0", "]", "[", "i", "+", "1", "]", ",", "mesh", ".", "lats", "[", "0", "]", "[", "i", "+", "1", "]", ",", "mesh", ".", "depths", "[", "0", "]", "[", "i", "+", "1", "]", ")", ")", "top_edge", ".", "append", "(", "Point", "(", "mesh", ".", "lons", "[", "0", "]", "[", "-", "1", "]", ",", "mesh", ".", "lats", "[", "0", "]", "[", "-", "1", "]", ",", "mesh", ".", "depths", "[", "0", "]", "[", "-", "1", "]", ")", ")", "line_top_edge", "=", "Line", "(", "top_edge", ")", "return", "line_top_edge" ]
This methods computes a simplified representation of a fault top edge by removing the points that are not describing a change of direction, provided a certain tolerance angle. :param float angle_var: Number representing the maximum deviation (in degrees) admitted without the creation of a new segment :returns: A :class:`~openquake.hazardlib.geo.line.Line` representing the rupture surface's top edge.
[ "This", "methods", "computes", "a", "simplified", "representation", "of", "a", "fault", "top", "edge", "by", "removing", "the", "points", "that", "are", "not", "describing", "a", "change", "of", "direction", "provided", "a", "certain", "tolerance", "angle", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/base.py#L342-L375
train
233,152
gem/oq-engine
openquake/hazardlib/geo/surface/base.py
BaseSurface.get_hypo_location
def get_hypo_location(self, mesh_spacing, hypo_loc=None): """ The method determines the location of the hypocentre within the rupture :param mesh: :class:`~openquake.hazardlib.geo.mesh.Mesh` of points :param mesh_spacing: The desired distance between two adjacent points in source's ruptures' mesh, in km. Mainly this parameter allows to balance the trade-off between time needed to compute the distance between the rupture surface and a site and the precision of that computation. :param hypo_loc: Hypocentre location as fraction of rupture plane, as a tuple of (Along Strike, Down Dip), e.g. a hypocentre located in the centroid of the rupture would be input as (0.5, 0.5), whereas a hypocentre located in a position 3/4 along the length, and 1/4 of the way down dip of the rupture plane would be entered as (0.75, 0.25). :returns: Hypocentre location as instance of :class:`~openquake.hazardlib.geo.point.Point` """ mesh = self.mesh centroid = mesh.get_middle_point() if hypo_loc is None: return centroid total_len_y = (len(mesh.depths) - 1) * mesh_spacing y_distance = hypo_loc[1] * total_len_y y_node = int(numpy.round(y_distance / mesh_spacing)) total_len_x = (len(mesh.lons[y_node]) - 1) * mesh_spacing x_distance = hypo_loc[0] * total_len_x x_node = int(numpy.round(x_distance / mesh_spacing)) hypocentre = Point(mesh.lons[y_node][x_node], mesh.lats[y_node][x_node], mesh.depths[y_node][x_node]) return hypocentre
python
def get_hypo_location(self, mesh_spacing, hypo_loc=None): """ The method determines the location of the hypocentre within the rupture :param mesh: :class:`~openquake.hazardlib.geo.mesh.Mesh` of points :param mesh_spacing: The desired distance between two adjacent points in source's ruptures' mesh, in km. Mainly this parameter allows to balance the trade-off between time needed to compute the distance between the rupture surface and a site and the precision of that computation. :param hypo_loc: Hypocentre location as fraction of rupture plane, as a tuple of (Along Strike, Down Dip), e.g. a hypocentre located in the centroid of the rupture would be input as (0.5, 0.5), whereas a hypocentre located in a position 3/4 along the length, and 1/4 of the way down dip of the rupture plane would be entered as (0.75, 0.25). :returns: Hypocentre location as instance of :class:`~openquake.hazardlib.geo.point.Point` """ mesh = self.mesh centroid = mesh.get_middle_point() if hypo_loc is None: return centroid total_len_y = (len(mesh.depths) - 1) * mesh_spacing y_distance = hypo_loc[1] * total_len_y y_node = int(numpy.round(y_distance / mesh_spacing)) total_len_x = (len(mesh.lons[y_node]) - 1) * mesh_spacing x_distance = hypo_loc[0] * total_len_x x_node = int(numpy.round(x_distance / mesh_spacing)) hypocentre = Point(mesh.lons[y_node][x_node], mesh.lats[y_node][x_node], mesh.depths[y_node][x_node]) return hypocentre
[ "def", "get_hypo_location", "(", "self", ",", "mesh_spacing", ",", "hypo_loc", "=", "None", ")", ":", "mesh", "=", "self", ".", "mesh", "centroid", "=", "mesh", ".", "get_middle_point", "(", ")", "if", "hypo_loc", "is", "None", ":", "return", "centroid", "total_len_y", "=", "(", "len", "(", "mesh", ".", "depths", ")", "-", "1", ")", "*", "mesh_spacing", "y_distance", "=", "hypo_loc", "[", "1", "]", "*", "total_len_y", "y_node", "=", "int", "(", "numpy", ".", "round", "(", "y_distance", "/", "mesh_spacing", ")", ")", "total_len_x", "=", "(", "len", "(", "mesh", ".", "lons", "[", "y_node", "]", ")", "-", "1", ")", "*", "mesh_spacing", "x_distance", "=", "hypo_loc", "[", "0", "]", "*", "total_len_x", "x_node", "=", "int", "(", "numpy", ".", "round", "(", "x_distance", "/", "mesh_spacing", ")", ")", "hypocentre", "=", "Point", "(", "mesh", ".", "lons", "[", "y_node", "]", "[", "x_node", "]", ",", "mesh", ".", "lats", "[", "y_node", "]", "[", "x_node", "]", ",", "mesh", ".", "depths", "[", "y_node", "]", "[", "x_node", "]", ")", "return", "hypocentre" ]
The method determines the location of the hypocentre within the rupture :param mesh: :class:`~openquake.hazardlib.geo.mesh.Mesh` of points :param mesh_spacing: The desired distance between two adjacent points in source's ruptures' mesh, in km. Mainly this parameter allows to balance the trade-off between time needed to compute the distance between the rupture surface and a site and the precision of that computation. :param hypo_loc: Hypocentre location as fraction of rupture plane, as a tuple of (Along Strike, Down Dip), e.g. a hypocentre located in the centroid of the rupture would be input as (0.5, 0.5), whereas a hypocentre located in a position 3/4 along the length, and 1/4 of the way down dip of the rupture plane would be entered as (0.75, 0.25). :returns: Hypocentre location as instance of :class:`~openquake.hazardlib.geo.point.Point`
[ "The", "method", "determines", "the", "location", "of", "the", "hypocentre", "within", "the", "rupture" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/base.py#L377-L414
train
233,153
gem/oq-engine
openquake/engine/tools/viewlog.py
viewlog
def viewlog(calc_id, host='localhost', port=8000): """ Extract the log of the given calculation ID from the WebUI """ base_url = 'http://%s:%s/v1/calc/' % (host, port) start = 0 psize = 10 # page size try: while True: url = base_url + '%d/log/%d:%d' % (calc_id, start, start + psize) rows = json.load(urlopen(url)) for row in rows: print(' '.join(row)) start += len(rows) time.sleep(1) except: pass
python
def viewlog(calc_id, host='localhost', port=8000): """ Extract the log of the given calculation ID from the WebUI """ base_url = 'http://%s:%s/v1/calc/' % (host, port) start = 0 psize = 10 # page size try: while True: url = base_url + '%d/log/%d:%d' % (calc_id, start, start + psize) rows = json.load(urlopen(url)) for row in rows: print(' '.join(row)) start += len(rows) time.sleep(1) except: pass
[ "def", "viewlog", "(", "calc_id", ",", "host", "=", "'localhost'", ",", "port", "=", "8000", ")", ":", "base_url", "=", "'http://%s:%s/v1/calc/'", "%", "(", "host", ",", "port", ")", "start", "=", "0", "psize", "=", "10", "# page size", "try", ":", "while", "True", ":", "url", "=", "base_url", "+", "'%d/log/%d:%d'", "%", "(", "calc_id", ",", "start", ",", "start", "+", "psize", ")", "rows", "=", "json", ".", "load", "(", "urlopen", "(", "url", ")", ")", "for", "row", "in", "rows", ":", "print", "(", "' '", ".", "join", "(", "row", ")", ")", "start", "+=", "len", "(", "rows", ")", "time", ".", "sleep", "(", "1", ")", "except", ":", "pass" ]
Extract the log of the given calculation ID from the WebUI
[ "Extract", "the", "log", "of", "the", "given", "calculation", "ID", "from", "the", "WebUI" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/engine/tools/viewlog.py#L33-L49
train
233,154
gem/oq-engine
openquake/baselib/parallel.py
pickle_sequence
def pickle_sequence(objects): """ Convert an iterable of objects into a list of pickled objects. If the iterable contains copies, the pickling will be done only once. If the iterable contains objects already pickled, they will not be pickled again. :param objects: a sequence of objects to pickle """ cache = {} out = [] for obj in objects: obj_id = id(obj) if obj_id not in cache: if isinstance(obj, Pickled): # already pickled cache[obj_id] = obj else: # pickle the object cache[obj_id] = Pickled(obj) out.append(cache[obj_id]) return out
python
def pickle_sequence(objects): """ Convert an iterable of objects into a list of pickled objects. If the iterable contains copies, the pickling will be done only once. If the iterable contains objects already pickled, they will not be pickled again. :param objects: a sequence of objects to pickle """ cache = {} out = [] for obj in objects: obj_id = id(obj) if obj_id not in cache: if isinstance(obj, Pickled): # already pickled cache[obj_id] = obj else: # pickle the object cache[obj_id] = Pickled(obj) out.append(cache[obj_id]) return out
[ "def", "pickle_sequence", "(", "objects", ")", ":", "cache", "=", "{", "}", "out", "=", "[", "]", "for", "obj", "in", "objects", ":", "obj_id", "=", "id", "(", "obj", ")", "if", "obj_id", "not", "in", "cache", ":", "if", "isinstance", "(", "obj", ",", "Pickled", ")", ":", "# already pickled", "cache", "[", "obj_id", "]", "=", "obj", "else", ":", "# pickle the object", "cache", "[", "obj_id", "]", "=", "Pickled", "(", "obj", ")", "out", ".", "append", "(", "cache", "[", "obj_id", "]", ")", "return", "out" ]
Convert an iterable of objects into a list of pickled objects. If the iterable contains copies, the pickling will be done only once. If the iterable contains objects already pickled, they will not be pickled again. :param objects: a sequence of objects to pickle
[ "Convert", "an", "iterable", "of", "objects", "into", "a", "list", "of", "pickled", "objects", ".", "If", "the", "iterable", "contains", "copies", "the", "pickling", "will", "be", "done", "only", "once", ".", "If", "the", "iterable", "contains", "objects", "already", "pickled", "they", "will", "not", "be", "pickled", "again", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/parallel.py#L294-L313
train
233,155
gem/oq-engine
openquake/baselib/parallel.py
check_mem_usage
def check_mem_usage(soft_percent=None, hard_percent=None): """ Display a warning if we are running out of memory """ soft_percent = soft_percent or config.memory.soft_mem_limit hard_percent = hard_percent or config.memory.hard_mem_limit used_mem_percent = psutil.virtual_memory().percent if used_mem_percent > hard_percent: raise MemoryError('Using more memory than allowed by configuration ' '(Used: %d%% / Allowed: %d%%)! Shutting down.' % (used_mem_percent, hard_percent)) elif used_mem_percent > soft_percent: msg = 'Using over %d%% of the memory in %s!' return msg % (used_mem_percent, socket.gethostname())
python
def check_mem_usage(soft_percent=None, hard_percent=None): """ Display a warning if we are running out of memory """ soft_percent = soft_percent or config.memory.soft_mem_limit hard_percent = hard_percent or config.memory.hard_mem_limit used_mem_percent = psutil.virtual_memory().percent if used_mem_percent > hard_percent: raise MemoryError('Using more memory than allowed by configuration ' '(Used: %d%% / Allowed: %d%%)! Shutting down.' % (used_mem_percent, hard_percent)) elif used_mem_percent > soft_percent: msg = 'Using over %d%% of the memory in %s!' return msg % (used_mem_percent, socket.gethostname())
[ "def", "check_mem_usage", "(", "soft_percent", "=", "None", ",", "hard_percent", "=", "None", ")", ":", "soft_percent", "=", "soft_percent", "or", "config", ".", "memory", ".", "soft_mem_limit", "hard_percent", "=", "hard_percent", "or", "config", ".", "memory", ".", "hard_mem_limit", "used_mem_percent", "=", "psutil", ".", "virtual_memory", "(", ")", ".", "percent", "if", "used_mem_percent", ">", "hard_percent", ":", "raise", "MemoryError", "(", "'Using more memory than allowed by configuration '", "'(Used: %d%% / Allowed: %d%%)! Shutting down.'", "%", "(", "used_mem_percent", ",", "hard_percent", ")", ")", "elif", "used_mem_percent", ">", "soft_percent", ":", "msg", "=", "'Using over %d%% of the memory in %s!'", "return", "msg", "%", "(", "used_mem_percent", ",", "socket", ".", "gethostname", "(", ")", ")" ]
Display a warning if we are running out of memory
[ "Display", "a", "warning", "if", "we", "are", "running", "out", "of", "memory" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/parallel.py#L370-L383
train
233,156
gem/oq-engine
openquake/baselib/parallel.py
init_workers
def init_workers(): """Waiting function, used to wake up the process pool""" setproctitle('oq-worker') # unregister raiseMasterKilled in oq-workers to avoid deadlock # since processes are terminated via pool.terminate() signal.signal(signal.SIGTERM, signal.SIG_DFL) # prctl is still useful (on Linux) to terminate all spawned processes # when master is killed via SIGKILL try: import prctl except ImportError: pass else: # if the parent dies, the children die prctl.set_pdeathsig(signal.SIGKILL)
python
def init_workers(): """Waiting function, used to wake up the process pool""" setproctitle('oq-worker') # unregister raiseMasterKilled in oq-workers to avoid deadlock # since processes are terminated via pool.terminate() signal.signal(signal.SIGTERM, signal.SIG_DFL) # prctl is still useful (on Linux) to terminate all spawned processes # when master is killed via SIGKILL try: import prctl except ImportError: pass else: # if the parent dies, the children die prctl.set_pdeathsig(signal.SIGKILL)
[ "def", "init_workers", "(", ")", ":", "setproctitle", "(", "'oq-worker'", ")", "# unregister raiseMasterKilled in oq-workers to avoid deadlock", "# since processes are terminated via pool.terminate()", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "signal", ".", "SIG_DFL", ")", "# prctl is still useful (on Linux) to terminate all spawned processes", "# when master is killed via SIGKILL", "try", ":", "import", "prctl", "except", "ImportError", ":", "pass", "else", ":", "# if the parent dies, the children die", "prctl", ".", "set_pdeathsig", "(", "signal", ".", "SIGKILL", ")" ]
Waiting function, used to wake up the process pool
[ "Waiting", "function", "used", "to", "wake", "up", "the", "process", "pool" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/parallel.py#L567-L581
train
233,157
gem/oq-engine
openquake/baselib/parallel.py
Result.get
def get(self): """ Returns the underlying value or raise the underlying exception """ val = self.pik.unpickle() if self.tb_str: etype = val.__class__ msg = '\n%s%s: %s' % (self.tb_str, etype.__name__, val) if issubclass(etype, KeyError): raise RuntimeError(msg) # nicer message else: raise etype(msg) return val
python
def get(self): """ Returns the underlying value or raise the underlying exception """ val = self.pik.unpickle() if self.tb_str: etype = val.__class__ msg = '\n%s%s: %s' % (self.tb_str, etype.__name__, val) if issubclass(etype, KeyError): raise RuntimeError(msg) # nicer message else: raise etype(msg) return val
[ "def", "get", "(", "self", ")", ":", "val", "=", "self", ".", "pik", ".", "unpickle", "(", ")", "if", "self", ".", "tb_str", ":", "etype", "=", "val", ".", "__class__", "msg", "=", "'\\n%s%s: %s'", "%", "(", "self", ".", "tb_str", ",", "etype", ".", "__name__", ",", "val", ")", "if", "issubclass", "(", "etype", ",", "KeyError", ")", ":", "raise", "RuntimeError", "(", "msg", ")", "# nicer message", "else", ":", "raise", "etype", "(", "msg", ")", "return", "val" ]
Returns the underlying value or raise the underlying exception
[ "Returns", "the", "underlying", "value", "or", "raise", "the", "underlying", "exception" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/parallel.py#L337-L349
train
233,158
gem/oq-engine
openquake/baselib/parallel.py
IterResult.sum
def sum(cls, iresults): """ Sum the data transfer information of a set of results """ res = object.__new__(cls) res.received = [] res.sent = 0 for iresult in iresults: res.received.extend(iresult.received) res.sent += iresult.sent name = iresult.name.split('#', 1)[0] if hasattr(res, 'name'): assert res.name.split('#', 1)[0] == name, (res.name, name) else: res.name = iresult.name.split('#')[0] return res
python
def sum(cls, iresults): """ Sum the data transfer information of a set of results """ res = object.__new__(cls) res.received = [] res.sent = 0 for iresult in iresults: res.received.extend(iresult.received) res.sent += iresult.sent name = iresult.name.split('#', 1)[0] if hasattr(res, 'name'): assert res.name.split('#', 1)[0] == name, (res.name, name) else: res.name = iresult.name.split('#')[0] return res
[ "def", "sum", "(", "cls", ",", "iresults", ")", ":", "res", "=", "object", ".", "__new__", "(", "cls", ")", "res", ".", "received", "=", "[", "]", "res", ".", "sent", "=", "0", "for", "iresult", "in", "iresults", ":", "res", ".", "received", ".", "extend", "(", "iresult", ".", "received", ")", "res", ".", "sent", "+=", "iresult", ".", "sent", "name", "=", "iresult", ".", "name", ".", "split", "(", "'#'", ",", "1", ")", "[", "0", "]", "if", "hasattr", "(", "res", ",", "'name'", ")", ":", "assert", "res", ".", "name", ".", "split", "(", "'#'", ",", "1", ")", "[", "0", "]", "==", "name", ",", "(", "res", ".", "name", ",", "name", ")", "else", ":", "res", ".", "name", "=", "iresult", ".", "name", ".", "split", "(", "'#'", ")", "[", "0", "]", "return", "res" ]
Sum the data transfer information of a set of results
[ "Sum", "the", "data", "transfer", "information", "of", "a", "set", "of", "results" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/parallel.py#L532-L547
train
233,159
gem/oq-engine
openquake/baselib/parallel.py
Starmap.log_percent
def log_percent(self): """ Log the progress of the computation in percentage """ done = self.total - self.todo percent = int(float(done) / self.total * 100) if not hasattr(self, 'prev_percent'): # first time self.prev_percent = 0 self.progress('Sent %s of data in %d %s task(s)', humansize(self.sent.sum()), self.total, self.name) elif percent > self.prev_percent: self.progress('%s %3d%% [of %d tasks]', self.name, percent, len(self.tasks)) self.prev_percent = percent return done
python
def log_percent(self): """ Log the progress of the computation in percentage """ done = self.total - self.todo percent = int(float(done) / self.total * 100) if not hasattr(self, 'prev_percent'): # first time self.prev_percent = 0 self.progress('Sent %s of data in %d %s task(s)', humansize(self.sent.sum()), self.total, self.name) elif percent > self.prev_percent: self.progress('%s %3d%% [of %d tasks]', self.name, percent, len(self.tasks)) self.prev_percent = percent return done
[ "def", "log_percent", "(", "self", ")", ":", "done", "=", "self", ".", "total", "-", "self", ".", "todo", "percent", "=", "int", "(", "float", "(", "done", ")", "/", "self", ".", "total", "*", "100", ")", "if", "not", "hasattr", "(", "self", ",", "'prev_percent'", ")", ":", "# first time", "self", ".", "prev_percent", "=", "0", "self", ".", "progress", "(", "'Sent %s of data in %d %s task(s)'", ",", "humansize", "(", "self", ".", "sent", ".", "sum", "(", ")", ")", ",", "self", ".", "total", ",", "self", ".", "name", ")", "elif", "percent", ">", "self", ".", "prev_percent", ":", "self", ".", "progress", "(", "'%s %3d%% [of %d tasks]'", ",", "self", ".", "name", ",", "percent", ",", "len", "(", "self", ".", "tasks", ")", ")", "self", ".", "prev_percent", "=", "percent", "return", "done" ]
Log the progress of the computation in percentage
[ "Log", "the", "progress", "of", "the", "computation", "in", "percentage" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/parallel.py#L691-L705
train
233,160
gem/oq-engine
openquake/baselib/parallel.py
Starmap.submit
def submit(self, *args, func=None, monitor=None): """ Submit the given arguments to the underlying task """ monitor = monitor or self.monitor func = func or self.task_func if not hasattr(self, 'socket'): # first time self.__class__.running_tasks = self.tasks self.socket = Socket(self.receiver, zmq.PULL, 'bind').__enter__() monitor.backurl = 'tcp://%s:%s' % ( config.dbserver.host, self.socket.port) assert not isinstance(args[-1], Monitor) # sanity check dist = 'no' if self.num_tasks == 1 else self.distribute if dist != 'no': args = pickle_sequence(args) self.sent += numpy.array([len(p) for p in args]) res = submit[dist](self, func, args, monitor) self.tasks.append(res)
python
def submit(self, *args, func=None, monitor=None): """ Submit the given arguments to the underlying task """ monitor = monitor or self.monitor func = func or self.task_func if not hasattr(self, 'socket'): # first time self.__class__.running_tasks = self.tasks self.socket = Socket(self.receiver, zmq.PULL, 'bind').__enter__() monitor.backurl = 'tcp://%s:%s' % ( config.dbserver.host, self.socket.port) assert not isinstance(args[-1], Monitor) # sanity check dist = 'no' if self.num_tasks == 1 else self.distribute if dist != 'no': args = pickle_sequence(args) self.sent += numpy.array([len(p) for p in args]) res = submit[dist](self, func, args, monitor) self.tasks.append(res)
[ "def", "submit", "(", "self", ",", "*", "args", ",", "func", "=", "None", ",", "monitor", "=", "None", ")", ":", "monitor", "=", "monitor", "or", "self", ".", "monitor", "func", "=", "func", "or", "self", ".", "task_func", "if", "not", "hasattr", "(", "self", ",", "'socket'", ")", ":", "# first time", "self", ".", "__class__", ".", "running_tasks", "=", "self", ".", "tasks", "self", ".", "socket", "=", "Socket", "(", "self", ".", "receiver", ",", "zmq", ".", "PULL", ",", "'bind'", ")", ".", "__enter__", "(", ")", "monitor", ".", "backurl", "=", "'tcp://%s:%s'", "%", "(", "config", ".", "dbserver", ".", "host", ",", "self", ".", "socket", ".", "port", ")", "assert", "not", "isinstance", "(", "args", "[", "-", "1", "]", ",", "Monitor", ")", "# sanity check", "dist", "=", "'no'", "if", "self", ".", "num_tasks", "==", "1", "else", "self", ".", "distribute", "if", "dist", "!=", "'no'", ":", "args", "=", "pickle_sequence", "(", "args", ")", "self", ".", "sent", "+=", "numpy", ".", "array", "(", "[", "len", "(", "p", ")", "for", "p", "in", "args", "]", ")", "res", "=", "submit", "[", "dist", "]", "(", "self", ",", "func", ",", "args", ",", "monitor", ")", "self", ".", "tasks", ".", "append", "(", "res", ")" ]
Submit the given arguments to the underlying task
[ "Submit", "the", "given", "arguments", "to", "the", "underlying", "task" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/parallel.py#L707-L724
train
233,161
gem/oq-engine
openquake/baselib/parallel.py
Starmap.reduce
def reduce(self, agg=operator.add, acc=None): """ Submit all tasks and reduce the results """ return self.submit_all().reduce(agg, acc)
python
def reduce(self, agg=operator.add, acc=None): """ Submit all tasks and reduce the results """ return self.submit_all().reduce(agg, acc)
[ "def", "reduce", "(", "self", ",", "agg", "=", "operator", ".", "add", ",", "acc", "=", "None", ")", ":", "return", "self", ".", "submit_all", "(", ")", ".", "reduce", "(", "agg", ",", "acc", ")" ]
Submit all tasks and reduce the results
[ "Submit", "all", "tasks", "and", "reduce", "the", "results" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/parallel.py#L748-L752
train
233,162
gem/oq-engine
openquake/hazardlib/probability_map.py
ProbabilityCurve.convert
def convert(self, imtls, idx=0): """ Convert a probability curve into a record of dtype `imtls.dt`. :param imtls: DictArray instance :param idx: extract the data corresponding to the given inner index """ curve = numpy.zeros(1, imtls.dt) for imt in imtls: curve[imt] = self.array[imtls(imt), idx] return curve[0]
python
def convert(self, imtls, idx=0): """ Convert a probability curve into a record of dtype `imtls.dt`. :param imtls: DictArray instance :param idx: extract the data corresponding to the given inner index """ curve = numpy.zeros(1, imtls.dt) for imt in imtls: curve[imt] = self.array[imtls(imt), idx] return curve[0]
[ "def", "convert", "(", "self", ",", "imtls", ",", "idx", "=", "0", ")", ":", "curve", "=", "numpy", ".", "zeros", "(", "1", ",", "imtls", ".", "dt", ")", "for", "imt", "in", "imtls", ":", "curve", "[", "imt", "]", "=", "self", ".", "array", "[", "imtls", "(", "imt", ")", ",", "idx", "]", "return", "curve", "[", "0", "]" ]
Convert a probability curve into a record of dtype `imtls.dt`. :param imtls: DictArray instance :param idx: extract the data corresponding to the given inner index
[ "Convert", "a", "probability", "curve", "into", "a", "record", "of", "dtype", "imtls", ".", "dt", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/probability_map.py#L96-L106
train
233,163
gem/oq-engine
openquake/hazardlib/probability_map.py
ProbabilityMap.nbytes
def nbytes(self): """The size of the underlying array""" try: N, L, I = get_shape([self]) except AllEmptyProbabilityMaps: return 0 return BYTES_PER_FLOAT * N * L * I
python
def nbytes(self): """The size of the underlying array""" try: N, L, I = get_shape([self]) except AllEmptyProbabilityMaps: return 0 return BYTES_PER_FLOAT * N * L * I
[ "def", "nbytes", "(", "self", ")", ":", "try", ":", "N", ",", "L", ",", "I", "=", "get_shape", "(", "[", "self", "]", ")", "except", "AllEmptyProbabilityMaps", ":", "return", "0", "return", "BYTES_PER_FLOAT", "*", "N", "*", "L", "*", "I" ]
The size of the underlying array
[ "The", "size", "of", "the", "underlying", "array" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/probability_map.py#L194-L200
train
233,164
gem/oq-engine
openquake/hazardlib/probability_map.py
ProbabilityMap.convert
def convert(self, imtls, nsites, idx=0): """ Convert a probability map into a composite array of length `nsites` and dtype `imtls.dt`. :param imtls: DictArray instance :param nsites: the total number of sites :param idx: index on the z-axis (default 0) """ curves = numpy.zeros(nsites, imtls.dt) for imt in curves.dtype.names: curves_by_imt = curves[imt] for sid in self: curves_by_imt[sid] = self[sid].array[imtls(imt), idx] return curves
python
def convert(self, imtls, nsites, idx=0): """ Convert a probability map into a composite array of length `nsites` and dtype `imtls.dt`. :param imtls: DictArray instance :param nsites: the total number of sites :param idx: index on the z-axis (default 0) """ curves = numpy.zeros(nsites, imtls.dt) for imt in curves.dtype.names: curves_by_imt = curves[imt] for sid in self: curves_by_imt[sid] = self[sid].array[imtls(imt), idx] return curves
[ "def", "convert", "(", "self", ",", "imtls", ",", "nsites", ",", "idx", "=", "0", ")", ":", "curves", "=", "numpy", ".", "zeros", "(", "nsites", ",", "imtls", ".", "dt", ")", "for", "imt", "in", "curves", ".", "dtype", ".", "names", ":", "curves_by_imt", "=", "curves", "[", "imt", "]", "for", "sid", "in", "self", ":", "curves_by_imt", "[", "sid", "]", "=", "self", "[", "sid", "]", ".", "array", "[", "imtls", "(", "imt", ")", ",", "idx", "]", "return", "curves" ]
Convert a probability map into a composite array of length `nsites` and dtype `imtls.dt`. :param imtls: DictArray instance :param nsites: the total number of sites :param idx: index on the z-axis (default 0)
[ "Convert", "a", "probability", "map", "into", "a", "composite", "array", "of", "length", "nsites", "and", "dtype", "imtls", ".", "dt", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/probability_map.py#L203-L220
train
233,165
gem/oq-engine
openquake/hazardlib/probability_map.py
ProbabilityMap.filter
def filter(self, sids): """ Extracs a submap of self for the given sids. """ dic = self.__class__(self.shape_y, self.shape_z) for sid in sids: try: dic[sid] = self[sid] except KeyError: pass return dic
python
def filter(self, sids): """ Extracs a submap of self for the given sids. """ dic = self.__class__(self.shape_y, self.shape_z) for sid in sids: try: dic[sid] = self[sid] except KeyError: pass return dic
[ "def", "filter", "(", "self", ",", "sids", ")", ":", "dic", "=", "self", ".", "__class__", "(", "self", ".", "shape_y", ",", "self", ".", "shape_z", ")", "for", "sid", "in", "sids", ":", "try", ":", "dic", "[", "sid", "]", "=", "self", "[", "sid", "]", "except", "KeyError", ":", "pass", "return", "dic" ]
Extracs a submap of self for the given sids.
[ "Extracs", "a", "submap", "of", "self", "for", "the", "given", "sids", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/probability_map.py#L247-L257
train
233,166
gem/oq-engine
openquake/hazardlib/probability_map.py
ProbabilityMap.extract
def extract(self, inner_idx): """ Extracts a component of the underlying ProbabilityCurves, specified by the index `inner_idx`. """ out = self.__class__(self.shape_y, 1) for sid in self: curve = self[sid] array = curve.array[:, inner_idx].reshape(-1, 1) out[sid] = ProbabilityCurve(array) return out
python
def extract(self, inner_idx): """ Extracts a component of the underlying ProbabilityCurves, specified by the index `inner_idx`. """ out = self.__class__(self.shape_y, 1) for sid in self: curve = self[sid] array = curve.array[:, inner_idx].reshape(-1, 1) out[sid] = ProbabilityCurve(array) return out
[ "def", "extract", "(", "self", ",", "inner_idx", ")", ":", "out", "=", "self", ".", "__class__", "(", "self", ".", "shape_y", ",", "1", ")", "for", "sid", "in", "self", ":", "curve", "=", "self", "[", "sid", "]", "array", "=", "curve", ".", "array", "[", ":", ",", "inner_idx", "]", ".", "reshape", "(", "-", "1", ",", "1", ")", "out", "[", "sid", "]", "=", "ProbabilityCurve", "(", "array", ")", "return", "out" ]
Extracts a component of the underlying ProbabilityCurves, specified by the index `inner_idx`.
[ "Extracts", "a", "component", "of", "the", "underlying", "ProbabilityCurves", "specified", "by", "the", "index", "inner_idx", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/probability_map.py#L259-L269
train
233,167
gem/oq-engine
openquake/commands/compare.py
compare
def compare(what, imt, calc_ids, files, samplesites=100, rtol=.1, atol=1E-4): """ Compare the hazard curves or maps of two or more calculations """ sids, imtls, poes, arrays = getdata(what, calc_ids, samplesites) try: levels = imtls[imt] except KeyError: sys.exit( '%s not found. The available IMTs are %s' % (imt, list(imtls))) imt2idx = {imt: i for i, imt in enumerate(imtls)} head = ['site_id'] if files else ['site_id', 'calc_id'] if what == 'hcurves': array_imt = arrays[:, :, imtls(imt)] header = head + ['%.5f' % lvl for lvl in levels] else: # hmaps array_imt = arrays[:, :, imt2idx[imt]] header = head + [str(poe) for poe in poes] rows = collections.defaultdict(list) diff_idxs = get_diff_idxs(array_imt, rtol, atol) if len(diff_idxs) == 0: print('There are no differences within the tolerance of %d%%' % (rtol * 100)) return arr = array_imt.transpose(1, 0, 2) # shape (N, C, L) for sid, array in sorted(zip(sids[diff_idxs], arr[diff_idxs])): for calc_id, cols in zip(calc_ids, array): if files: rows[calc_id].append([sid] + list(cols)) else: rows['all'].append([sid, calc_id] + list(cols)) if files: fdict = {calc_id: open('%s.txt' % calc_id, 'w') for calc_id in calc_ids} for calc_id, f in fdict.items(): f.write(views.rst_table(rows[calc_id], header)) print('Generated %s' % f.name) else: print(views.rst_table(rows['all'], header))
python
def compare(what, imt, calc_ids, files, samplesites=100, rtol=.1, atol=1E-4): """ Compare the hazard curves or maps of two or more calculations """ sids, imtls, poes, arrays = getdata(what, calc_ids, samplesites) try: levels = imtls[imt] except KeyError: sys.exit( '%s not found. The available IMTs are %s' % (imt, list(imtls))) imt2idx = {imt: i for i, imt in enumerate(imtls)} head = ['site_id'] if files else ['site_id', 'calc_id'] if what == 'hcurves': array_imt = arrays[:, :, imtls(imt)] header = head + ['%.5f' % lvl for lvl in levels] else: # hmaps array_imt = arrays[:, :, imt2idx[imt]] header = head + [str(poe) for poe in poes] rows = collections.defaultdict(list) diff_idxs = get_diff_idxs(array_imt, rtol, atol) if len(diff_idxs) == 0: print('There are no differences within the tolerance of %d%%' % (rtol * 100)) return arr = array_imt.transpose(1, 0, 2) # shape (N, C, L) for sid, array in sorted(zip(sids[diff_idxs], arr[diff_idxs])): for calc_id, cols in zip(calc_ids, array): if files: rows[calc_id].append([sid] + list(cols)) else: rows['all'].append([sid, calc_id] + list(cols)) if files: fdict = {calc_id: open('%s.txt' % calc_id, 'w') for calc_id in calc_ids} for calc_id, f in fdict.items(): f.write(views.rst_table(rows[calc_id], header)) print('Generated %s' % f.name) else: print(views.rst_table(rows['all'], header))
[ "def", "compare", "(", "what", ",", "imt", ",", "calc_ids", ",", "files", ",", "samplesites", "=", "100", ",", "rtol", "=", ".1", ",", "atol", "=", "1E-4", ")", ":", "sids", ",", "imtls", ",", "poes", ",", "arrays", "=", "getdata", "(", "what", ",", "calc_ids", ",", "samplesites", ")", "try", ":", "levels", "=", "imtls", "[", "imt", "]", "except", "KeyError", ":", "sys", ".", "exit", "(", "'%s not found. The available IMTs are %s'", "%", "(", "imt", ",", "list", "(", "imtls", ")", ")", ")", "imt2idx", "=", "{", "imt", ":", "i", "for", "i", ",", "imt", "in", "enumerate", "(", "imtls", ")", "}", "head", "=", "[", "'site_id'", "]", "if", "files", "else", "[", "'site_id'", ",", "'calc_id'", "]", "if", "what", "==", "'hcurves'", ":", "array_imt", "=", "arrays", "[", ":", ",", ":", ",", "imtls", "(", "imt", ")", "]", "header", "=", "head", "+", "[", "'%.5f'", "%", "lvl", "for", "lvl", "in", "levels", "]", "else", ":", "# hmaps", "array_imt", "=", "arrays", "[", ":", ",", ":", ",", "imt2idx", "[", "imt", "]", "]", "header", "=", "head", "+", "[", "str", "(", "poe", ")", "for", "poe", "in", "poes", "]", "rows", "=", "collections", ".", "defaultdict", "(", "list", ")", "diff_idxs", "=", "get_diff_idxs", "(", "array_imt", ",", "rtol", ",", "atol", ")", "if", "len", "(", "diff_idxs", ")", "==", "0", ":", "print", "(", "'There are no differences within the tolerance of %d%%'", "%", "(", "rtol", "*", "100", ")", ")", "return", "arr", "=", "array_imt", ".", "transpose", "(", "1", ",", "0", ",", "2", ")", "# shape (N, C, L)", "for", "sid", ",", "array", "in", "sorted", "(", "zip", "(", "sids", "[", "diff_idxs", "]", ",", "arr", "[", "diff_idxs", "]", ")", ")", ":", "for", "calc_id", ",", "cols", "in", "zip", "(", "calc_ids", ",", "array", ")", ":", "if", "files", ":", "rows", "[", "calc_id", "]", ".", "append", "(", "[", "sid", "]", "+", "list", "(", "cols", ")", ")", "else", ":", "rows", "[", "'all'", "]", ".", "append", "(", "[", "sid", ",", "calc_id", "]", "+", "list", "(", "cols", ")", ")", "if", "files", ":", "fdict", "=", "{", "calc_id", ":", "open", "(", "'%s.txt'", "%", "calc_id", ",", "'w'", ")", "for", "calc_id", "in", "calc_ids", "}", "for", "calc_id", ",", "f", "in", "fdict", ".", "items", "(", ")", ":", "f", ".", "write", "(", "views", ".", "rst_table", "(", "rows", "[", "calc_id", "]", ",", "header", ")", ")", "print", "(", "'Generated %s'", "%", "f", ".", "name", ")", "else", ":", "print", "(", "views", ".", "rst_table", "(", "rows", "[", "'all'", "]", ",", "header", ")", ")" ]
Compare the hazard curves or maps of two or more calculations
[ "Compare", "the", "hazard", "curves", "or", "maps", "of", "two", "or", "more", "calculations" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/compare.py#L69-L107
train
233,168
gem/oq-engine
openquake/hmtk/plotting/seismicity/catalogue_plots.py
build_filename
def build_filename(filename, filetype='png', resolution=300): """ Uses the input properties to create the string of the filename :param str filename: Name of the file :param str filetype: Type of file :param int resolution: DPI resolution of the output figure """ filevals = os.path.splitext(filename) if filevals[1]: filetype = filevals[1][1:] if not filetype: filetype = 'png' filename = filevals[0] + '.' + filetype if not resolution: resolution = 300 return filename, filetype, resolution
python
def build_filename(filename, filetype='png', resolution=300): """ Uses the input properties to create the string of the filename :param str filename: Name of the file :param str filetype: Type of file :param int resolution: DPI resolution of the output figure """ filevals = os.path.splitext(filename) if filevals[1]: filetype = filevals[1][1:] if not filetype: filetype = 'png' filename = filevals[0] + '.' + filetype if not resolution: resolution = 300 return filename, filetype, resolution
[ "def", "build_filename", "(", "filename", ",", "filetype", "=", "'png'", ",", "resolution", "=", "300", ")", ":", "filevals", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "filevals", "[", "1", "]", ":", "filetype", "=", "filevals", "[", "1", "]", "[", "1", ":", "]", "if", "not", "filetype", ":", "filetype", "=", "'png'", "filename", "=", "filevals", "[", "0", "]", "+", "'.'", "+", "filetype", "if", "not", "resolution", ":", "resolution", "=", "300", "return", "filename", ",", "filetype", ",", "resolution" ]
Uses the input properties to create the string of the filename :param str filename: Name of the file :param str filetype: Type of file :param int resolution: DPI resolution of the output figure
[ "Uses", "the", "input", "properties", "to", "create", "the", "string", "of", "the", "filename" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/seismicity/catalogue_plots.py#L61-L81
train
233,169
gem/oq-engine
openquake/hmtk/plotting/seismicity/catalogue_plots.py
_get_catalogue_bin_limits
def _get_catalogue_bin_limits(catalogue, dmag): """ Returns the magnitude bins corresponing to the catalogue """ mag_bins = np.arange( float(np.floor(np.min(catalogue.data['magnitude']))) - dmag, float(np.ceil(np.max(catalogue.data['magnitude']))) + dmag, dmag) counter = np.histogram(catalogue.data['magnitude'], mag_bins)[0] idx = np.where(counter > 0)[0] mag_bins = mag_bins[idx[0]:(idx[-1] + 2)] return mag_bins
python
def _get_catalogue_bin_limits(catalogue, dmag): """ Returns the magnitude bins corresponing to the catalogue """ mag_bins = np.arange( float(np.floor(np.min(catalogue.data['magnitude']))) - dmag, float(np.ceil(np.max(catalogue.data['magnitude']))) + dmag, dmag) counter = np.histogram(catalogue.data['magnitude'], mag_bins)[0] idx = np.where(counter > 0)[0] mag_bins = mag_bins[idx[0]:(idx[-1] + 2)] return mag_bins
[ "def", "_get_catalogue_bin_limits", "(", "catalogue", ",", "dmag", ")", ":", "mag_bins", "=", "np", ".", "arange", "(", "float", "(", "np", ".", "floor", "(", "np", ".", "min", "(", "catalogue", ".", "data", "[", "'magnitude'", "]", ")", ")", ")", "-", "dmag", ",", "float", "(", "np", ".", "ceil", "(", "np", ".", "max", "(", "catalogue", ".", "data", "[", "'magnitude'", "]", ")", ")", ")", "+", "dmag", ",", "dmag", ")", "counter", "=", "np", ".", "histogram", "(", "catalogue", ".", "data", "[", "'magnitude'", "]", ",", "mag_bins", ")", "[", "0", "]", "idx", "=", "np", ".", "where", "(", "counter", ">", "0", ")", "[", "0", "]", "mag_bins", "=", "mag_bins", "[", "idx", "[", "0", "]", ":", "(", "idx", "[", "-", "1", "]", "+", "2", ")", "]", "return", "mag_bins" ]
Returns the magnitude bins corresponing to the catalogue
[ "Returns", "the", "magnitude", "bins", "corresponing", "to", "the", "catalogue" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/seismicity/catalogue_plots.py#L103-L114
train
233,170
gem/oq-engine
openquake/hmtk/plotting/seismicity/catalogue_plots.py
plot_depth_histogram
def plot_depth_histogram( catalogue, bin_width, normalisation=False, bootstrap=None, filename=None, figure_size=(8, 6), filetype='png', dpi=300, ax=None): """ Creates a histogram of the depths in the catalogue :param catalogue: Earthquake catalogue as instance of :class: openquake.hmtk.seismicity.catalogue.Catalogue :param float bin_width: Width of the histogram for the depth bins :param bool normalisation: Normalise the histogram to give output as PMF (True) or count (False) :param int bootstrap: To sample depth uncertainty choose number of samples """ if ax is None: fig, ax = plt.subplots(figsize=figure_size) else: fig = ax.get_figure() # Create depth range if len(catalogue.data['depth']) == 0: # pylint: disable=len-as-condition raise ValueError('No depths reported in catalogue!') depth_bins = np.arange(0., np.max(catalogue.data['depth']) + bin_width, bin_width) depth_hist = catalogue.get_depth_distribution(depth_bins, normalisation, bootstrap) ax.bar(depth_bins[:-1], depth_hist, width=0.95 * bin_width, edgecolor='k') ax.set_xlabel('Depth (km)') if normalisation: ax.set_ylabel('Probability Mass Function') else: ax.set_ylabel('Count') ax.set_title('Depth Histogram') _save_image(fig, filename, filetype, dpi)
python
def plot_depth_histogram( catalogue, bin_width, normalisation=False, bootstrap=None, filename=None, figure_size=(8, 6), filetype='png', dpi=300, ax=None): """ Creates a histogram of the depths in the catalogue :param catalogue: Earthquake catalogue as instance of :class: openquake.hmtk.seismicity.catalogue.Catalogue :param float bin_width: Width of the histogram for the depth bins :param bool normalisation: Normalise the histogram to give output as PMF (True) or count (False) :param int bootstrap: To sample depth uncertainty choose number of samples """ if ax is None: fig, ax = plt.subplots(figsize=figure_size) else: fig = ax.get_figure() # Create depth range if len(catalogue.data['depth']) == 0: # pylint: disable=len-as-condition raise ValueError('No depths reported in catalogue!') depth_bins = np.arange(0., np.max(catalogue.data['depth']) + bin_width, bin_width) depth_hist = catalogue.get_depth_distribution(depth_bins, normalisation, bootstrap) ax.bar(depth_bins[:-1], depth_hist, width=0.95 * bin_width, edgecolor='k') ax.set_xlabel('Depth (km)') if normalisation: ax.set_ylabel('Probability Mass Function') else: ax.set_ylabel('Count') ax.set_title('Depth Histogram') _save_image(fig, filename, filetype, dpi)
[ "def", "plot_depth_histogram", "(", "catalogue", ",", "bin_width", ",", "normalisation", "=", "False", ",", "bootstrap", "=", "None", ",", "filename", "=", "None", ",", "figure_size", "=", "(", "8", ",", "6", ")", ",", "filetype", "=", "'png'", ",", "dpi", "=", "300", ",", "ax", "=", "None", ")", ":", "if", "ax", "is", "None", ":", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", "figsize", "=", "figure_size", ")", "else", ":", "fig", "=", "ax", ".", "get_figure", "(", ")", "# Create depth range", "if", "len", "(", "catalogue", ".", "data", "[", "'depth'", "]", ")", "==", "0", ":", "# pylint: disable=len-as-condition", "raise", "ValueError", "(", "'No depths reported in catalogue!'", ")", "depth_bins", "=", "np", ".", "arange", "(", "0.", ",", "np", ".", "max", "(", "catalogue", ".", "data", "[", "'depth'", "]", ")", "+", "bin_width", ",", "bin_width", ")", "depth_hist", "=", "catalogue", ".", "get_depth_distribution", "(", "depth_bins", ",", "normalisation", ",", "bootstrap", ")", "ax", ".", "bar", "(", "depth_bins", "[", ":", "-", "1", "]", ",", "depth_hist", ",", "width", "=", "0.95", "*", "bin_width", ",", "edgecolor", "=", "'k'", ")", "ax", ".", "set_xlabel", "(", "'Depth (km)'", ")", "if", "normalisation", ":", "ax", ".", "set_ylabel", "(", "'Probability Mass Function'", ")", "else", ":", "ax", ".", "set_ylabel", "(", "'Count'", ")", "ax", ".", "set_title", "(", "'Depth Histogram'", ")", "_save_image", "(", "fig", ",", "filename", ",", "filetype", ",", "dpi", ")" ]
Creates a histogram of the depths in the catalogue :param catalogue: Earthquake catalogue as instance of :class: openquake.hmtk.seismicity.catalogue.Catalogue :param float bin_width: Width of the histogram for the depth bins :param bool normalisation: Normalise the histogram to give output as PMF (True) or count (False) :param int bootstrap: To sample depth uncertainty choose number of samples
[ "Creates", "a", "histogram", "of", "the", "depths", "in", "the", "catalogue" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/seismicity/catalogue_plots.py#L117-L158
train
233,171
gem/oq-engine
openquake/hmtk/plotting/seismicity/catalogue_plots.py
plot_magnitude_depth_density
def plot_magnitude_depth_density( catalogue, mag_int, depth_int, logscale=False, normalisation=False, bootstrap=None, filename=None, figure_size=(8, 6), filetype='png', dpi=300, ax=None): """ Creates a density plot of the magnitude and depth distribution :param catalogue: Earthquake catalogue as instance of :class: openquake.hmtk.seismicity.catalogue.Catalogue :param float mag_int: Width of the histogram for the magnitude bins :param float depth_int: Width of the histogram for the depth bins :param bool logscale: Choose to scale the colours in a log-scale (True) or linear (False) :param bool normalisation: Normalise the histogram to give output as PMF (True) or count (False) :param int bootstrap: To sample magnitude and depth uncertainties choose number of samples """ if len(catalogue.data['depth']) == 0: # pylint: disable=len-as-condition raise ValueError('No depths reported in catalogue!') depth_bins = np.arange(0., np.max(catalogue.data['depth']) + depth_int, depth_int) mag_bins = _get_catalogue_bin_limits(catalogue, mag_int) mag_depth_dist = catalogue.get_magnitude_depth_distribution(mag_bins, depth_bins, normalisation, bootstrap) vmin_val = np.min(mag_depth_dist[mag_depth_dist > 0.]) if ax is None: fig, ax = plt.subplots(figsize=figure_size) else: fig = ax.get_figure() if logscale: normaliser = LogNorm(vmin=vmin_val, vmax=np.max(mag_depth_dist)) else: normaliser = Normalize(vmin=0, vmax=np.max(mag_depth_dist)) im = ax.pcolor(mag_bins[:-1], depth_bins[:-1], mag_depth_dist.T, norm=normaliser) ax.set_xlabel('Magnitude') ax.set_ylabel('Depth (km)') ax.set_xlim(mag_bins[0], mag_bins[-1]) ax.set_ylim(depth_bins[0], depth_bins[-1]) fig.colorbar(im, ax=ax) if normalisation: ax.set_title('Magnitude-Depth Density') else: ax.set_title('Magnitude-Depth Count') _save_image(fig, filename, filetype, dpi)
python
def plot_magnitude_depth_density( catalogue, mag_int, depth_int, logscale=False, normalisation=False, bootstrap=None, filename=None, figure_size=(8, 6), filetype='png', dpi=300, ax=None): """ Creates a density plot of the magnitude and depth distribution :param catalogue: Earthquake catalogue as instance of :class: openquake.hmtk.seismicity.catalogue.Catalogue :param float mag_int: Width of the histogram for the magnitude bins :param float depth_int: Width of the histogram for the depth bins :param bool logscale: Choose to scale the colours in a log-scale (True) or linear (False) :param bool normalisation: Normalise the histogram to give output as PMF (True) or count (False) :param int bootstrap: To sample magnitude and depth uncertainties choose number of samples """ if len(catalogue.data['depth']) == 0: # pylint: disable=len-as-condition raise ValueError('No depths reported in catalogue!') depth_bins = np.arange(0., np.max(catalogue.data['depth']) + depth_int, depth_int) mag_bins = _get_catalogue_bin_limits(catalogue, mag_int) mag_depth_dist = catalogue.get_magnitude_depth_distribution(mag_bins, depth_bins, normalisation, bootstrap) vmin_val = np.min(mag_depth_dist[mag_depth_dist > 0.]) if ax is None: fig, ax = plt.subplots(figsize=figure_size) else: fig = ax.get_figure() if logscale: normaliser = LogNorm(vmin=vmin_val, vmax=np.max(mag_depth_dist)) else: normaliser = Normalize(vmin=0, vmax=np.max(mag_depth_dist)) im = ax.pcolor(mag_bins[:-1], depth_bins[:-1], mag_depth_dist.T, norm=normaliser) ax.set_xlabel('Magnitude') ax.set_ylabel('Depth (km)') ax.set_xlim(mag_bins[0], mag_bins[-1]) ax.set_ylim(depth_bins[0], depth_bins[-1]) fig.colorbar(im, ax=ax) if normalisation: ax.set_title('Magnitude-Depth Density') else: ax.set_title('Magnitude-Depth Count') _save_image(fig, filename, filetype, dpi)
[ "def", "plot_magnitude_depth_density", "(", "catalogue", ",", "mag_int", ",", "depth_int", ",", "logscale", "=", "False", ",", "normalisation", "=", "False", ",", "bootstrap", "=", "None", ",", "filename", "=", "None", ",", "figure_size", "=", "(", "8", ",", "6", ")", ",", "filetype", "=", "'png'", ",", "dpi", "=", "300", ",", "ax", "=", "None", ")", ":", "if", "len", "(", "catalogue", ".", "data", "[", "'depth'", "]", ")", "==", "0", ":", "# pylint: disable=len-as-condition", "raise", "ValueError", "(", "'No depths reported in catalogue!'", ")", "depth_bins", "=", "np", ".", "arange", "(", "0.", ",", "np", ".", "max", "(", "catalogue", ".", "data", "[", "'depth'", "]", ")", "+", "depth_int", ",", "depth_int", ")", "mag_bins", "=", "_get_catalogue_bin_limits", "(", "catalogue", ",", "mag_int", ")", "mag_depth_dist", "=", "catalogue", ".", "get_magnitude_depth_distribution", "(", "mag_bins", ",", "depth_bins", ",", "normalisation", ",", "bootstrap", ")", "vmin_val", "=", "np", ".", "min", "(", "mag_depth_dist", "[", "mag_depth_dist", ">", "0.", "]", ")", "if", "ax", "is", "None", ":", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", "figsize", "=", "figure_size", ")", "else", ":", "fig", "=", "ax", ".", "get_figure", "(", ")", "if", "logscale", ":", "normaliser", "=", "LogNorm", "(", "vmin", "=", "vmin_val", ",", "vmax", "=", "np", ".", "max", "(", "mag_depth_dist", ")", ")", "else", ":", "normaliser", "=", "Normalize", "(", "vmin", "=", "0", ",", "vmax", "=", "np", ".", "max", "(", "mag_depth_dist", ")", ")", "im", "=", "ax", ".", "pcolor", "(", "mag_bins", "[", ":", "-", "1", "]", ",", "depth_bins", "[", ":", "-", "1", "]", ",", "mag_depth_dist", ".", "T", ",", "norm", "=", "normaliser", ")", "ax", ".", "set_xlabel", "(", "'Magnitude'", ")", "ax", ".", "set_ylabel", "(", "'Depth (km)'", ")", "ax", ".", "set_xlim", "(", "mag_bins", "[", "0", "]", ",", "mag_bins", "[", "-", "1", "]", ")", "ax", ".", "set_ylim", "(", "depth_bins", "[", "0", "]", ",", "depth_bins", "[", "-", "1", "]", ")", "fig", ".", "colorbar", "(", "im", ",", "ax", "=", "ax", ")", "if", "normalisation", ":", "ax", ".", "set_title", "(", "'Magnitude-Depth Density'", ")", "else", ":", "ax", ".", "set_title", "(", "'Magnitude-Depth Count'", ")", "_save_image", "(", "fig", ",", "filename", ",", "filetype", ",", "dpi", ")" ]
Creates a density plot of the magnitude and depth distribution :param catalogue: Earthquake catalogue as instance of :class: openquake.hmtk.seismicity.catalogue.Catalogue :param float mag_int: Width of the histogram for the magnitude bins :param float depth_int: Width of the histogram for the depth bins :param bool logscale: Choose to scale the colours in a log-scale (True) or linear (False) :param bool normalisation: Normalise the histogram to give output as PMF (True) or count (False) :param int bootstrap: To sample magnitude and depth uncertainties choose number of samples
[ "Creates", "a", "density", "plot", "of", "the", "magnitude", "and", "depth", "distribution" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/seismicity/catalogue_plots.py#L161-L218
train
233,172
gem/oq-engine
openquake/hmtk/plotting/seismicity/catalogue_plots.py
plot_magnitude_time_scatter
def plot_magnitude_time_scatter( catalogue, plot_error=False, fmt_string='o', filename=None, figure_size=(8, 6), filetype='png', dpi=300, ax=None): """ Creates a simple scatter plot of magnitude with time :param catalogue: Earthquake catalogue as instance of :class: openquake.hmtk.seismicity.catalogue.Catalogue :param bool plot_error: Choose to plot error bars (True) or not (False) :param str fmt_string: Symbology of plot """ if ax is None: fig, ax = plt.subplots(figsize=figure_size) else: fig = ax.get_figure() dtime = catalogue.get_decimal_time() # pylint: disable=len-as-condition if len(catalogue.data['sigmaMagnitude']) == 0: print('Magnitude Error is missing - neglecting error bars!') plot_error = False if plot_error: ax.errorbar(dtime, catalogue.data['magnitude'], xerr=None, yerr=catalogue.data['sigmaMagnitude'], fmt=fmt_string) else: ax.plot(dtime, catalogue.data['magnitude'], fmt_string) ax.set_xlabel('Year') ax.set_ylabel('Magnitude') ax.set_title('Magnitude-Time Plot') _save_image(fig, filename, filetype, dpi)
python
def plot_magnitude_time_scatter( catalogue, plot_error=False, fmt_string='o', filename=None, figure_size=(8, 6), filetype='png', dpi=300, ax=None): """ Creates a simple scatter plot of magnitude with time :param catalogue: Earthquake catalogue as instance of :class: openquake.hmtk.seismicity.catalogue.Catalogue :param bool plot_error: Choose to plot error bars (True) or not (False) :param str fmt_string: Symbology of plot """ if ax is None: fig, ax = plt.subplots(figsize=figure_size) else: fig = ax.get_figure() dtime = catalogue.get_decimal_time() # pylint: disable=len-as-condition if len(catalogue.data['sigmaMagnitude']) == 0: print('Magnitude Error is missing - neglecting error bars!') plot_error = False if plot_error: ax.errorbar(dtime, catalogue.data['magnitude'], xerr=None, yerr=catalogue.data['sigmaMagnitude'], fmt=fmt_string) else: ax.plot(dtime, catalogue.data['magnitude'], fmt_string) ax.set_xlabel('Year') ax.set_ylabel('Magnitude') ax.set_title('Magnitude-Time Plot') _save_image(fig, filename, filetype, dpi)
[ "def", "plot_magnitude_time_scatter", "(", "catalogue", ",", "plot_error", "=", "False", ",", "fmt_string", "=", "'o'", ",", "filename", "=", "None", ",", "figure_size", "=", "(", "8", ",", "6", ")", ",", "filetype", "=", "'png'", ",", "dpi", "=", "300", ",", "ax", "=", "None", ")", ":", "if", "ax", "is", "None", ":", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", "figsize", "=", "figure_size", ")", "else", ":", "fig", "=", "ax", ".", "get_figure", "(", ")", "dtime", "=", "catalogue", ".", "get_decimal_time", "(", ")", "# pylint: disable=len-as-condition", "if", "len", "(", "catalogue", ".", "data", "[", "'sigmaMagnitude'", "]", ")", "==", "0", ":", "print", "(", "'Magnitude Error is missing - neglecting error bars!'", ")", "plot_error", "=", "False", "if", "plot_error", ":", "ax", ".", "errorbar", "(", "dtime", ",", "catalogue", ".", "data", "[", "'magnitude'", "]", ",", "xerr", "=", "None", ",", "yerr", "=", "catalogue", ".", "data", "[", "'sigmaMagnitude'", "]", ",", "fmt", "=", "fmt_string", ")", "else", ":", "ax", ".", "plot", "(", "dtime", ",", "catalogue", ".", "data", "[", "'magnitude'", "]", ",", "fmt_string", ")", "ax", ".", "set_xlabel", "(", "'Year'", ")", "ax", ".", "set_ylabel", "(", "'Magnitude'", ")", "ax", ".", "set_title", "(", "'Magnitude-Time Plot'", ")", "_save_image", "(", "fig", ",", "filename", ",", "filetype", ",", "dpi", ")" ]
Creates a simple scatter plot of magnitude with time :param catalogue: Earthquake catalogue as instance of :class: openquake.hmtk.seismicity.catalogue.Catalogue :param bool plot_error: Choose to plot error bars (True) or not (False) :param str fmt_string: Symbology of plot
[ "Creates", "a", "simple", "scatter", "plot", "of", "magnitude", "with", "time" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/seismicity/catalogue_plots.py#L221-L258
train
233,173
gem/oq-engine
openquake/hmtk/plotting/seismicity/catalogue_plots.py
plot_magnitude_time_density
def plot_magnitude_time_density( catalogue, mag_int, time_int, completeness=None, normalisation=False, logscale=True, bootstrap=None, xlim=[], ylim=[], filename=None, figure_size=(8, 6), filetype='png', dpi=300, ax=None): """ Creates a plot of magnitude-time density :param catalogue: Earthquake catalogue as instance of :class: openquake.hmtk.seismicity.catalogue.Catalogue :param float mag_int: Width of the histogram for the magnitude bins :param float time_int: Width of the histogram for the time bin (in decimal years) :param bool normalisation: Normalise the histogram to give output as PMF (True) or count (False) :param int bootstrap: To sample magnitude and depth uncertainties choose number of samples """ if ax is None: fig, ax = plt.subplots(figsize=figure_size) else: fig = ax.get_figure() # Create the magnitude bins if isinstance(mag_int, (np.ndarray, list)): mag_bins = mag_int else: mag_bins = np.arange( np.min(catalogue.data['magnitude']), np.max(catalogue.data['magnitude']) + mag_int / 2., mag_int) # Creates the time bins if isinstance(time_int, (np.ndarray, list)): time_bins = time_int else: time_bins = np.arange( float(np.min(catalogue.data['year'])), float(np.max(catalogue.data['year'])) + 1., float(time_int)) # Get magnitude-time distribution mag_time_dist = catalogue.get_magnitude_time_distribution( mag_bins, time_bins, normalisation, bootstrap) # Get smallest non-zero value vmin_val = np.min(mag_time_dist[mag_time_dist > 0.]) # Create plot if logscale: norm_data = LogNorm(vmin=vmin_val, vmax=np.max(mag_time_dist)) else: if normalisation: norm_data = Normalize(vmin=vmin_val, vmax=np.max(mag_time_dist)) else: norm_data = Normalize(vmin=1.0, vmax=np.max(mag_time_dist)) im = ax.pcolor(time_bins[:-1], mag_bins[:-1], mag_time_dist.T, norm=norm_data) ax.set_xlabel('Time (year)') ax.set_ylabel('Magnitude') if len(xlim) == 2: ax.set_xlim(xlim[0], xlim[1]) else: ax.set_xlim(time_bins[0], time_bins[-1]) if len(ylim) == 2: ax.set_ylim(ylim[0], ylim[1]) else: ax.set_ylim(mag_bins[0], mag_bins[-1] + (mag_bins[-1] - mag_bins[-2])) # Fix the title if normalisation: fig.colorbar(im, label='Event Density', shrink=0.9, ax=ax) else: fig.colorbar(im, label='Event Count', shrink=0.9, ax=ax) ax.grid(True) # Plot completeness if completeness is not None: _plot_completeness(ax, completeness, time_bins[0], time_bins[-1]) _save_image(fig, filename, filetype, dpi)
python
def plot_magnitude_time_density( catalogue, mag_int, time_int, completeness=None, normalisation=False, logscale=True, bootstrap=None, xlim=[], ylim=[], filename=None, figure_size=(8, 6), filetype='png', dpi=300, ax=None): """ Creates a plot of magnitude-time density :param catalogue: Earthquake catalogue as instance of :class: openquake.hmtk.seismicity.catalogue.Catalogue :param float mag_int: Width of the histogram for the magnitude bins :param float time_int: Width of the histogram for the time bin (in decimal years) :param bool normalisation: Normalise the histogram to give output as PMF (True) or count (False) :param int bootstrap: To sample magnitude and depth uncertainties choose number of samples """ if ax is None: fig, ax = plt.subplots(figsize=figure_size) else: fig = ax.get_figure() # Create the magnitude bins if isinstance(mag_int, (np.ndarray, list)): mag_bins = mag_int else: mag_bins = np.arange( np.min(catalogue.data['magnitude']), np.max(catalogue.data['magnitude']) + mag_int / 2., mag_int) # Creates the time bins if isinstance(time_int, (np.ndarray, list)): time_bins = time_int else: time_bins = np.arange( float(np.min(catalogue.data['year'])), float(np.max(catalogue.data['year'])) + 1., float(time_int)) # Get magnitude-time distribution mag_time_dist = catalogue.get_magnitude_time_distribution( mag_bins, time_bins, normalisation, bootstrap) # Get smallest non-zero value vmin_val = np.min(mag_time_dist[mag_time_dist > 0.]) # Create plot if logscale: norm_data = LogNorm(vmin=vmin_val, vmax=np.max(mag_time_dist)) else: if normalisation: norm_data = Normalize(vmin=vmin_val, vmax=np.max(mag_time_dist)) else: norm_data = Normalize(vmin=1.0, vmax=np.max(mag_time_dist)) im = ax.pcolor(time_bins[:-1], mag_bins[:-1], mag_time_dist.T, norm=norm_data) ax.set_xlabel('Time (year)') ax.set_ylabel('Magnitude') if len(xlim) == 2: ax.set_xlim(xlim[0], xlim[1]) else: ax.set_xlim(time_bins[0], time_bins[-1]) if len(ylim) == 2: ax.set_ylim(ylim[0], ylim[1]) else: ax.set_ylim(mag_bins[0], mag_bins[-1] + (mag_bins[-1] - mag_bins[-2])) # Fix the title if normalisation: fig.colorbar(im, label='Event Density', shrink=0.9, ax=ax) else: fig.colorbar(im, label='Event Count', shrink=0.9, ax=ax) ax.grid(True) # Plot completeness if completeness is not None: _plot_completeness(ax, completeness, time_bins[0], time_bins[-1]) _save_image(fig, filename, filetype, dpi)
[ "def", "plot_magnitude_time_density", "(", "catalogue", ",", "mag_int", ",", "time_int", ",", "completeness", "=", "None", ",", "normalisation", "=", "False", ",", "logscale", "=", "True", ",", "bootstrap", "=", "None", ",", "xlim", "=", "[", "]", ",", "ylim", "=", "[", "]", ",", "filename", "=", "None", ",", "figure_size", "=", "(", "8", ",", "6", ")", ",", "filetype", "=", "'png'", ",", "dpi", "=", "300", ",", "ax", "=", "None", ")", ":", "if", "ax", "is", "None", ":", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", "figsize", "=", "figure_size", ")", "else", ":", "fig", "=", "ax", ".", "get_figure", "(", ")", "# Create the magnitude bins", "if", "isinstance", "(", "mag_int", ",", "(", "np", ".", "ndarray", ",", "list", ")", ")", ":", "mag_bins", "=", "mag_int", "else", ":", "mag_bins", "=", "np", ".", "arange", "(", "np", ".", "min", "(", "catalogue", ".", "data", "[", "'magnitude'", "]", ")", ",", "np", ".", "max", "(", "catalogue", ".", "data", "[", "'magnitude'", "]", ")", "+", "mag_int", "/", "2.", ",", "mag_int", ")", "# Creates the time bins", "if", "isinstance", "(", "time_int", ",", "(", "np", ".", "ndarray", ",", "list", ")", ")", ":", "time_bins", "=", "time_int", "else", ":", "time_bins", "=", "np", ".", "arange", "(", "float", "(", "np", ".", "min", "(", "catalogue", ".", "data", "[", "'year'", "]", ")", ")", ",", "float", "(", "np", ".", "max", "(", "catalogue", ".", "data", "[", "'year'", "]", ")", ")", "+", "1.", ",", "float", "(", "time_int", ")", ")", "# Get magnitude-time distribution", "mag_time_dist", "=", "catalogue", ".", "get_magnitude_time_distribution", "(", "mag_bins", ",", "time_bins", ",", "normalisation", ",", "bootstrap", ")", "# Get smallest non-zero value", "vmin_val", "=", "np", ".", "min", "(", "mag_time_dist", "[", "mag_time_dist", ">", "0.", "]", ")", "# Create plot", "if", "logscale", ":", "norm_data", "=", "LogNorm", "(", "vmin", "=", "vmin_val", ",", "vmax", "=", "np", ".", "max", "(", "mag_time_dist", ")", ")", "else", ":", "if", "normalisation", ":", "norm_data", "=", "Normalize", "(", "vmin", "=", "vmin_val", ",", "vmax", "=", "np", ".", "max", "(", "mag_time_dist", ")", ")", "else", ":", "norm_data", "=", "Normalize", "(", "vmin", "=", "1.0", ",", "vmax", "=", "np", ".", "max", "(", "mag_time_dist", ")", ")", "im", "=", "ax", ".", "pcolor", "(", "time_bins", "[", ":", "-", "1", "]", ",", "mag_bins", "[", ":", "-", "1", "]", ",", "mag_time_dist", ".", "T", ",", "norm", "=", "norm_data", ")", "ax", ".", "set_xlabel", "(", "'Time (year)'", ")", "ax", ".", "set_ylabel", "(", "'Magnitude'", ")", "if", "len", "(", "xlim", ")", "==", "2", ":", "ax", ".", "set_xlim", "(", "xlim", "[", "0", "]", ",", "xlim", "[", "1", "]", ")", "else", ":", "ax", ".", "set_xlim", "(", "time_bins", "[", "0", "]", ",", "time_bins", "[", "-", "1", "]", ")", "if", "len", "(", "ylim", ")", "==", "2", ":", "ax", ".", "set_ylim", "(", "ylim", "[", "0", "]", ",", "ylim", "[", "1", "]", ")", "else", ":", "ax", ".", "set_ylim", "(", "mag_bins", "[", "0", "]", ",", "mag_bins", "[", "-", "1", "]", "+", "(", "mag_bins", "[", "-", "1", "]", "-", "mag_bins", "[", "-", "2", "]", ")", ")", "# Fix the title", "if", "normalisation", ":", "fig", ".", "colorbar", "(", "im", ",", "label", "=", "'Event Density'", ",", "shrink", "=", "0.9", ",", "ax", "=", "ax", ")", "else", ":", "fig", ".", "colorbar", "(", "im", ",", "label", "=", "'Event Count'", ",", "shrink", "=", "0.9", ",", "ax", "=", "ax", ")", "ax", ".", "grid", "(", "True", ")", "# Plot completeness", "if", "completeness", "is", "not", "None", ":", "_plot_completeness", "(", "ax", ",", "completeness", ",", "time_bins", "[", "0", "]", ",", "time_bins", "[", "-", "1", "]", ")", "_save_image", "(", "fig", ",", "filename", ",", "filetype", ",", "dpi", ")" ]
Creates a plot of magnitude-time density :param catalogue: Earthquake catalogue as instance of :class: openquake.hmtk.seismicity.catalogue.Catalogue :param float mag_int: Width of the histogram for the magnitude bins :param float time_int: Width of the histogram for the time bin (in decimal years) :param bool normalisation: Normalise the histogram to give output as PMF (True) or count (False) :param int bootstrap: To sample magnitude and depth uncertainties choose number of samples
[ "Creates", "a", "plot", "of", "magnitude", "-", "time", "density" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/seismicity/catalogue_plots.py#L261-L342
train
233,174
gem/oq-engine
openquake/hmtk/plotting/seismicity/catalogue_plots.py
_plot_completeness
def _plot_completeness(ax, comw, start_time, end_time): ''' Adds completeness intervals to a plot ''' comw = np.array(comw) comp = np.column_stack([np.hstack([end_time, comw[:, 0], start_time]), np.hstack([comw[0, 1], comw[:, 1], comw[-1, 1]])]) ax.step(comp[:-1, 0], comp[1:, 1], linestyle='-', where="post", linewidth=3, color='brown')
python
def _plot_completeness(ax, comw, start_time, end_time): ''' Adds completeness intervals to a plot ''' comw = np.array(comw) comp = np.column_stack([np.hstack([end_time, comw[:, 0], start_time]), np.hstack([comw[0, 1], comw[:, 1], comw[-1, 1]])]) ax.step(comp[:-1, 0], comp[1:, 1], linestyle='-', where="post", linewidth=3, color='brown')
[ "def", "_plot_completeness", "(", "ax", ",", "comw", ",", "start_time", ",", "end_time", ")", ":", "comw", "=", "np", ".", "array", "(", "comw", ")", "comp", "=", "np", ".", "column_stack", "(", "[", "np", ".", "hstack", "(", "[", "end_time", ",", "comw", "[", ":", ",", "0", "]", ",", "start_time", "]", ")", ",", "np", ".", "hstack", "(", "[", "comw", "[", "0", ",", "1", "]", ",", "comw", "[", ":", ",", "1", "]", ",", "comw", "[", "-", "1", ",", "1", "]", "]", ")", "]", ")", "ax", ".", "step", "(", "comp", "[", ":", "-", "1", ",", "0", "]", ",", "comp", "[", "1", ":", ",", "1", "]", ",", "linestyle", "=", "'-'", ",", "where", "=", "\"post\"", ",", "linewidth", "=", "3", ",", "color", "=", "'brown'", ")" ]
Adds completeness intervals to a plot
[ "Adds", "completeness", "intervals", "to", "a", "plot" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/seismicity/catalogue_plots.py#L345-L353
train
233,175
gem/oq-engine
openquake/hmtk/plotting/seismicity/catalogue_plots.py
get_completeness_adjusted_table
def get_completeness_adjusted_table(catalogue, completeness, dmag, offset=1.0E-5, end_year=None, plot=False, figure_size=(8, 6), filename=None, filetype='png', dpi=300, ax=None): """ Counts the number of earthquakes in each magnitude bin and normalises the rate to annual rates, taking into account the completeness """ if not end_year: end_year = catalogue.end_year # Find the natural bin limits mag_bins = _get_catalogue_bin_limits(catalogue, dmag) obs_time = end_year - completeness[:, 0] + 1. obs_rates = np.zeros_like(mag_bins) durations = np.zeros_like(mag_bins) n_comp = np.shape(completeness)[0] for iloc in range(n_comp): low_mag = completeness[iloc, 1] comp_year = completeness[iloc, 0] if iloc == (n_comp - 1): idx = np.logical_and( catalogue.data['magnitude'] >= low_mag - offset, catalogue.data['year'] >= comp_year) high_mag = mag_bins[-1] obs_idx = mag_bins >= (low_mag - offset) else: high_mag = completeness[iloc + 1, 1] mag_idx = np.logical_and( catalogue.data['magnitude'] >= low_mag - offset, catalogue.data['magnitude'] < (high_mag - offset)) idx = np.logical_and(mag_idx, catalogue.data['year'] >= (comp_year - offset)) obs_idx = np.logical_and(mag_bins >= (low_mag - offset), mag_bins < (high_mag + offset)) temp_rates = np.histogram(catalogue.data['magnitude'][idx], mag_bins[obs_idx])[0] temp_rates = temp_rates.astype(float) / obs_time[iloc] obs_rates[obs_idx[:-1]] = temp_rates durations[obs_idx[:-1]] = obs_time[iloc] selector = np.where(obs_rates > 0.)[0] mag_bins = mag_bins[selector] obs_rates = obs_rates[selector] durations = durations[selector] # Get cumulative rates cum_rates = np.array([sum(obs_rates[iloc:]) for iloc in range(0, len(obs_rates))]) if plot: plt.figure(figsize=figure_size) plt.semilogy(mag_bins + dmag / 2., obs_rates, "bo", label="Incremental") plt.semilogy(mag_bins + dmag / 2., cum_rates, "rs", label="Cumulative") plt.xlabel("Magnitude (M)", fontsize=16) plt.ylabel("Annual Rate", fontsize=16) plt.grid(True) plt.legend(fontsize=16) if filename: plt.savefig(filename, format=filetype, dpi=dpi, bbox_inches="tight") return np.column_stack([mag_bins, durations, obs_rates, cum_rates, np.log10(cum_rates)])
python
def get_completeness_adjusted_table(catalogue, completeness, dmag, offset=1.0E-5, end_year=None, plot=False, figure_size=(8, 6), filename=None, filetype='png', dpi=300, ax=None): """ Counts the number of earthquakes in each magnitude bin and normalises the rate to annual rates, taking into account the completeness """ if not end_year: end_year = catalogue.end_year # Find the natural bin limits mag_bins = _get_catalogue_bin_limits(catalogue, dmag) obs_time = end_year - completeness[:, 0] + 1. obs_rates = np.zeros_like(mag_bins) durations = np.zeros_like(mag_bins) n_comp = np.shape(completeness)[0] for iloc in range(n_comp): low_mag = completeness[iloc, 1] comp_year = completeness[iloc, 0] if iloc == (n_comp - 1): idx = np.logical_and( catalogue.data['magnitude'] >= low_mag - offset, catalogue.data['year'] >= comp_year) high_mag = mag_bins[-1] obs_idx = mag_bins >= (low_mag - offset) else: high_mag = completeness[iloc + 1, 1] mag_idx = np.logical_and( catalogue.data['magnitude'] >= low_mag - offset, catalogue.data['magnitude'] < (high_mag - offset)) idx = np.logical_and(mag_idx, catalogue.data['year'] >= (comp_year - offset)) obs_idx = np.logical_and(mag_bins >= (low_mag - offset), mag_bins < (high_mag + offset)) temp_rates = np.histogram(catalogue.data['magnitude'][idx], mag_bins[obs_idx])[0] temp_rates = temp_rates.astype(float) / obs_time[iloc] obs_rates[obs_idx[:-1]] = temp_rates durations[obs_idx[:-1]] = obs_time[iloc] selector = np.where(obs_rates > 0.)[0] mag_bins = mag_bins[selector] obs_rates = obs_rates[selector] durations = durations[selector] # Get cumulative rates cum_rates = np.array([sum(obs_rates[iloc:]) for iloc in range(0, len(obs_rates))]) if plot: plt.figure(figsize=figure_size) plt.semilogy(mag_bins + dmag / 2., obs_rates, "bo", label="Incremental") plt.semilogy(mag_bins + dmag / 2., cum_rates, "rs", label="Cumulative") plt.xlabel("Magnitude (M)", fontsize=16) plt.ylabel("Annual Rate", fontsize=16) plt.grid(True) plt.legend(fontsize=16) if filename: plt.savefig(filename, format=filetype, dpi=dpi, bbox_inches="tight") return np.column_stack([mag_bins, durations, obs_rates, cum_rates, np.log10(cum_rates)])
[ "def", "get_completeness_adjusted_table", "(", "catalogue", ",", "completeness", ",", "dmag", ",", "offset", "=", "1.0E-5", ",", "end_year", "=", "None", ",", "plot", "=", "False", ",", "figure_size", "=", "(", "8", ",", "6", ")", ",", "filename", "=", "None", ",", "filetype", "=", "'png'", ",", "dpi", "=", "300", ",", "ax", "=", "None", ")", ":", "if", "not", "end_year", ":", "end_year", "=", "catalogue", ".", "end_year", "# Find the natural bin limits", "mag_bins", "=", "_get_catalogue_bin_limits", "(", "catalogue", ",", "dmag", ")", "obs_time", "=", "end_year", "-", "completeness", "[", ":", ",", "0", "]", "+", "1.", "obs_rates", "=", "np", ".", "zeros_like", "(", "mag_bins", ")", "durations", "=", "np", ".", "zeros_like", "(", "mag_bins", ")", "n_comp", "=", "np", ".", "shape", "(", "completeness", ")", "[", "0", "]", "for", "iloc", "in", "range", "(", "n_comp", ")", ":", "low_mag", "=", "completeness", "[", "iloc", ",", "1", "]", "comp_year", "=", "completeness", "[", "iloc", ",", "0", "]", "if", "iloc", "==", "(", "n_comp", "-", "1", ")", ":", "idx", "=", "np", ".", "logical_and", "(", "catalogue", ".", "data", "[", "'magnitude'", "]", ">=", "low_mag", "-", "offset", ",", "catalogue", ".", "data", "[", "'year'", "]", ">=", "comp_year", ")", "high_mag", "=", "mag_bins", "[", "-", "1", "]", "obs_idx", "=", "mag_bins", ">=", "(", "low_mag", "-", "offset", ")", "else", ":", "high_mag", "=", "completeness", "[", "iloc", "+", "1", ",", "1", "]", "mag_idx", "=", "np", ".", "logical_and", "(", "catalogue", ".", "data", "[", "'magnitude'", "]", ">=", "low_mag", "-", "offset", ",", "catalogue", ".", "data", "[", "'magnitude'", "]", "<", "(", "high_mag", "-", "offset", ")", ")", "idx", "=", "np", ".", "logical_and", "(", "mag_idx", ",", "catalogue", ".", "data", "[", "'year'", "]", ">=", "(", "comp_year", "-", "offset", ")", ")", "obs_idx", "=", "np", ".", "logical_and", "(", "mag_bins", ">=", "(", "low_mag", "-", "offset", ")", ",", "mag_bins", "<", "(", "high_mag", "+", "offset", ")", ")", "temp_rates", "=", "np", ".", "histogram", "(", "catalogue", ".", "data", "[", "'magnitude'", "]", "[", "idx", "]", ",", "mag_bins", "[", "obs_idx", "]", ")", "[", "0", "]", "temp_rates", "=", "temp_rates", ".", "astype", "(", "float", ")", "/", "obs_time", "[", "iloc", "]", "obs_rates", "[", "obs_idx", "[", ":", "-", "1", "]", "]", "=", "temp_rates", "durations", "[", "obs_idx", "[", ":", "-", "1", "]", "]", "=", "obs_time", "[", "iloc", "]", "selector", "=", "np", ".", "where", "(", "obs_rates", ">", "0.", ")", "[", "0", "]", "mag_bins", "=", "mag_bins", "[", "selector", "]", "obs_rates", "=", "obs_rates", "[", "selector", "]", "durations", "=", "durations", "[", "selector", "]", "# Get cumulative rates", "cum_rates", "=", "np", ".", "array", "(", "[", "sum", "(", "obs_rates", "[", "iloc", ":", "]", ")", "for", "iloc", "in", "range", "(", "0", ",", "len", "(", "obs_rates", ")", ")", "]", ")", "if", "plot", ":", "plt", ".", "figure", "(", "figsize", "=", "figure_size", ")", "plt", ".", "semilogy", "(", "mag_bins", "+", "dmag", "/", "2.", ",", "obs_rates", ",", "\"bo\"", ",", "label", "=", "\"Incremental\"", ")", "plt", ".", "semilogy", "(", "mag_bins", "+", "dmag", "/", "2.", ",", "cum_rates", ",", "\"rs\"", ",", "label", "=", "\"Cumulative\"", ")", "plt", ".", "xlabel", "(", "\"Magnitude (M)\"", ",", "fontsize", "=", "16", ")", "plt", ".", "ylabel", "(", "\"Annual Rate\"", ",", "fontsize", "=", "16", ")", "plt", ".", "grid", "(", "True", ")", "plt", ".", "legend", "(", "fontsize", "=", "16", ")", "if", "filename", ":", "plt", ".", "savefig", "(", "filename", ",", "format", "=", "filetype", ",", "dpi", "=", "dpi", ",", "bbox_inches", "=", "\"tight\"", ")", "return", "np", ".", "column_stack", "(", "[", "mag_bins", ",", "durations", ",", "obs_rates", ",", "cum_rates", ",", "np", ".", "log10", "(", "cum_rates", ")", "]", ")" ]
Counts the number of earthquakes in each magnitude bin and normalises the rate to annual rates, taking into account the completeness
[ "Counts", "the", "number", "of", "earthquakes", "in", "each", "magnitude", "bin", "and", "normalises", "the", "rate", "to", "annual", "rates", "taking", "into", "account", "the", "completeness" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/seismicity/catalogue_plots.py#L356-L417
train
233,176
gem/oq-engine
openquake/hmtk/plotting/seismicity/catalogue_plots.py
plot_observed_recurrence
def plot_observed_recurrence( catalogue, completeness, dmag, end_year=None, filename=None, figure_size=(8, 6), filetype='png', dpi=300, ax=None): """ Plots the observed recurrence taking into account the completeness """ # Get completeness adjusted recurrence table if isinstance(completeness, float): # Unique completeness completeness = np.array([[np.min(catalogue.data['year']), completeness]]) if not end_year: end_year = catalogue.update_end_year() catalogue.data["dtime"] = catalogue.get_decimal_time() cent_mag, t_per, n_obs = get_completeness_counts(catalogue, completeness, dmag) obs_rates = n_obs / t_per cum_obs_rates = np.array([np.sum(obs_rates[i:]) for i in range(len(obs_rates))]) if ax is None: fig, ax = plt.subplots(figsize=figure_size) else: fig = ax.get_figure() ax.semilogy(cent_mag, obs_rates, 'bo', label="Incremental") ax.semilogy(cent_mag, cum_obs_rates, 'rs', label="Cumulative") ax.set_xlim([cent_mag[0] - 0.1, cent_mag[-1] + 0.1]) ax.set_xlabel('Magnitude') ax.set_ylabel('Annual Rate') ax.legend() _save_image(fig, filename, filetype, dpi)
python
def plot_observed_recurrence( catalogue, completeness, dmag, end_year=None, filename=None, figure_size=(8, 6), filetype='png', dpi=300, ax=None): """ Plots the observed recurrence taking into account the completeness """ # Get completeness adjusted recurrence table if isinstance(completeness, float): # Unique completeness completeness = np.array([[np.min(catalogue.data['year']), completeness]]) if not end_year: end_year = catalogue.update_end_year() catalogue.data["dtime"] = catalogue.get_decimal_time() cent_mag, t_per, n_obs = get_completeness_counts(catalogue, completeness, dmag) obs_rates = n_obs / t_per cum_obs_rates = np.array([np.sum(obs_rates[i:]) for i in range(len(obs_rates))]) if ax is None: fig, ax = plt.subplots(figsize=figure_size) else: fig = ax.get_figure() ax.semilogy(cent_mag, obs_rates, 'bo', label="Incremental") ax.semilogy(cent_mag, cum_obs_rates, 'rs', label="Cumulative") ax.set_xlim([cent_mag[0] - 0.1, cent_mag[-1] + 0.1]) ax.set_xlabel('Magnitude') ax.set_ylabel('Annual Rate') ax.legend() _save_image(fig, filename, filetype, dpi)
[ "def", "plot_observed_recurrence", "(", "catalogue", ",", "completeness", ",", "dmag", ",", "end_year", "=", "None", ",", "filename", "=", "None", ",", "figure_size", "=", "(", "8", ",", "6", ")", ",", "filetype", "=", "'png'", ",", "dpi", "=", "300", ",", "ax", "=", "None", ")", ":", "# Get completeness adjusted recurrence table", "if", "isinstance", "(", "completeness", ",", "float", ")", ":", "# Unique completeness", "completeness", "=", "np", ".", "array", "(", "[", "[", "np", ".", "min", "(", "catalogue", ".", "data", "[", "'year'", "]", ")", ",", "completeness", "]", "]", ")", "if", "not", "end_year", ":", "end_year", "=", "catalogue", ".", "update_end_year", "(", ")", "catalogue", ".", "data", "[", "\"dtime\"", "]", "=", "catalogue", ".", "get_decimal_time", "(", ")", "cent_mag", ",", "t_per", ",", "n_obs", "=", "get_completeness_counts", "(", "catalogue", ",", "completeness", ",", "dmag", ")", "obs_rates", "=", "n_obs", "/", "t_per", "cum_obs_rates", "=", "np", ".", "array", "(", "[", "np", ".", "sum", "(", "obs_rates", "[", "i", ":", "]", ")", "for", "i", "in", "range", "(", "len", "(", "obs_rates", ")", ")", "]", ")", "if", "ax", "is", "None", ":", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", "figsize", "=", "figure_size", ")", "else", ":", "fig", "=", "ax", ".", "get_figure", "(", ")", "ax", ".", "semilogy", "(", "cent_mag", ",", "obs_rates", ",", "'bo'", ",", "label", "=", "\"Incremental\"", ")", "ax", ".", "semilogy", "(", "cent_mag", ",", "cum_obs_rates", ",", "'rs'", ",", "label", "=", "\"Cumulative\"", ")", "ax", ".", "set_xlim", "(", "[", "cent_mag", "[", "0", "]", "-", "0.1", ",", "cent_mag", "[", "-", "1", "]", "+", "0.1", "]", ")", "ax", ".", "set_xlabel", "(", "'Magnitude'", ")", "ax", ".", "set_ylabel", "(", "'Annual Rate'", ")", "ax", ".", "legend", "(", ")", "_save_image", "(", "fig", ",", "filename", ",", "filetype", ",", "dpi", ")" ]
Plots the observed recurrence taking into account the completeness
[ "Plots", "the", "observed", "recurrence", "taking", "into", "account", "the", "completeness" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/seismicity/catalogue_plots.py#L420-L452
train
233,177
gem/oq-engine
openquake/hmtk/strain/geodetic_strain.py
GeodeticStrain.get_number_observations
def get_number_observations(self): ''' Returns the number of observations in the data file ''' if isinstance(self.data, dict) and ('exx' in self.data.keys()): return len(self.data['exx']) else: return 0
python
def get_number_observations(self): ''' Returns the number of observations in the data file ''' if isinstance(self.data, dict) and ('exx' in self.data.keys()): return len(self.data['exx']) else: return 0
[ "def", "get_number_observations", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "data", ",", "dict", ")", "and", "(", "'exx'", "in", "self", ".", "data", ".", "keys", "(", ")", ")", ":", "return", "len", "(", "self", ".", "data", "[", "'exx'", "]", ")", "else", ":", "return", "0" ]
Returns the number of observations in the data file
[ "Returns", "the", "number", "of", "observations", "in", "the", "data", "file" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/strain/geodetic_strain.py#L137-L144
train
233,178
gem/oq-engine
openquake/commands/plot_lc.py
plot_lc
def plot_lc(calc_id, aid=None): """ Plot loss curves given a calculation id and an asset ordinal. """ # read the hazard data dstore = util.read(calc_id) dset = dstore['agg_curves-rlzs'] if aid is None: # plot the global curves plt = make_figure(dset.attrs['return_periods'], dset.value) else: sys.exit('Not implemented yet') plt.show()
python
def plot_lc(calc_id, aid=None): """ Plot loss curves given a calculation id and an asset ordinal. """ # read the hazard data dstore = util.read(calc_id) dset = dstore['agg_curves-rlzs'] if aid is None: # plot the global curves plt = make_figure(dset.attrs['return_periods'], dset.value) else: sys.exit('Not implemented yet') plt.show()
[ "def", "plot_lc", "(", "calc_id", ",", "aid", "=", "None", ")", ":", "# read the hazard data", "dstore", "=", "util", ".", "read", "(", "calc_id", ")", "dset", "=", "dstore", "[", "'agg_curves-rlzs'", "]", "if", "aid", "is", "None", ":", "# plot the global curves", "plt", "=", "make_figure", "(", "dset", ".", "attrs", "[", "'return_periods'", "]", ",", "dset", ".", "value", ")", "else", ":", "sys", ".", "exit", "(", "'Not implemented yet'", ")", "plt", ".", "show", "(", ")" ]
Plot loss curves given a calculation id and an asset ordinal.
[ "Plot", "loss", "curves", "given", "a", "calculation", "id", "and", "an", "asset", "ordinal", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/plot_lc.py#L41-L52
train
233,179
gem/oq-engine
openquake/hazardlib/gsim/nshmp_2014.py
get_weighted_poes
def get_weighted_poes(gsim, sctx, rctx, dctx, imt, imls, truncation_level, weighting=DEFAULT_WEIGHTING): """ This function implements the NGA West 2 GMPE epistemic uncertainty adjustment factor without re-calculating the actual GMPE each time. :param gsim: Instance of the GMPE :param list weighting: Weightings as a list of tuples of (weight, number standard deviations of the epistemic uncertainty adjustment) """ if truncation_level is not None and truncation_level < 0: raise ValueError('truncation level must be zero, positive number ' 'or None') gsim._check_imt(imt) adjustment = nga_west2_epistemic_adjustment(rctx.mag, dctx.rrup) adjustment = adjustment.reshape(adjustment.shape + (1, )) if truncation_level == 0: # zero truncation mode, just compare imls to mean imls = gsim.to_distribution_values(imls) mean, _ = gsim.get_mean_and_stddevs(sctx, rctx, dctx, imt, []) mean = mean.reshape(mean.shape + (1, )) output = np.zeros([mean.shape[0], imls.shape[0]]) for (wgt, fct) in weighting: output += (wgt * (imls <= (mean + (fct * adjustment))).astype(float)) return output else: # use real normal distribution assert (const.StdDev.TOTAL in gsim.DEFINED_FOR_STANDARD_DEVIATION_TYPES) imls = gsim.to_distribution_values(imls) mean, [stddev] = gsim.get_mean_and_stddevs(sctx, rctx, dctx, imt, [const.StdDev.TOTAL]) mean = mean.reshape(mean.shape + (1, )) stddev = stddev.reshape(stddev.shape + (1, )) output = np.zeros([mean.shape[0], imls.shape[0]]) for (wgt, fct) in weighting: values = (imls - (mean + (fct * adjustment))) / stddev if truncation_level is None: output += (wgt * _norm_sf(values)) else: output += (wgt * _truncnorm_sf(truncation_level, values)) return output
python
def get_weighted_poes(gsim, sctx, rctx, dctx, imt, imls, truncation_level, weighting=DEFAULT_WEIGHTING): """ This function implements the NGA West 2 GMPE epistemic uncertainty adjustment factor without re-calculating the actual GMPE each time. :param gsim: Instance of the GMPE :param list weighting: Weightings as a list of tuples of (weight, number standard deviations of the epistemic uncertainty adjustment) """ if truncation_level is not None and truncation_level < 0: raise ValueError('truncation level must be zero, positive number ' 'or None') gsim._check_imt(imt) adjustment = nga_west2_epistemic_adjustment(rctx.mag, dctx.rrup) adjustment = adjustment.reshape(adjustment.shape + (1, )) if truncation_level == 0: # zero truncation mode, just compare imls to mean imls = gsim.to_distribution_values(imls) mean, _ = gsim.get_mean_and_stddevs(sctx, rctx, dctx, imt, []) mean = mean.reshape(mean.shape + (1, )) output = np.zeros([mean.shape[0], imls.shape[0]]) for (wgt, fct) in weighting: output += (wgt * (imls <= (mean + (fct * adjustment))).astype(float)) return output else: # use real normal distribution assert (const.StdDev.TOTAL in gsim.DEFINED_FOR_STANDARD_DEVIATION_TYPES) imls = gsim.to_distribution_values(imls) mean, [stddev] = gsim.get_mean_and_stddevs(sctx, rctx, dctx, imt, [const.StdDev.TOTAL]) mean = mean.reshape(mean.shape + (1, )) stddev = stddev.reshape(stddev.shape + (1, )) output = np.zeros([mean.shape[0], imls.shape[0]]) for (wgt, fct) in weighting: values = (imls - (mean + (fct * adjustment))) / stddev if truncation_level is None: output += (wgt * _norm_sf(values)) else: output += (wgt * _truncnorm_sf(truncation_level, values)) return output
[ "def", "get_weighted_poes", "(", "gsim", ",", "sctx", ",", "rctx", ",", "dctx", ",", "imt", ",", "imls", ",", "truncation_level", ",", "weighting", "=", "DEFAULT_WEIGHTING", ")", ":", "if", "truncation_level", "is", "not", "None", "and", "truncation_level", "<", "0", ":", "raise", "ValueError", "(", "'truncation level must be zero, positive number '", "'or None'", ")", "gsim", ".", "_check_imt", "(", "imt", ")", "adjustment", "=", "nga_west2_epistemic_adjustment", "(", "rctx", ".", "mag", ",", "dctx", ".", "rrup", ")", "adjustment", "=", "adjustment", ".", "reshape", "(", "adjustment", ".", "shape", "+", "(", "1", ",", ")", ")", "if", "truncation_level", "==", "0", ":", "# zero truncation mode, just compare imls to mean", "imls", "=", "gsim", ".", "to_distribution_values", "(", "imls", ")", "mean", ",", "_", "=", "gsim", ".", "get_mean_and_stddevs", "(", "sctx", ",", "rctx", ",", "dctx", ",", "imt", ",", "[", "]", ")", "mean", "=", "mean", ".", "reshape", "(", "mean", ".", "shape", "+", "(", "1", ",", ")", ")", "output", "=", "np", ".", "zeros", "(", "[", "mean", ".", "shape", "[", "0", "]", ",", "imls", ".", "shape", "[", "0", "]", "]", ")", "for", "(", "wgt", ",", "fct", ")", "in", "weighting", ":", "output", "+=", "(", "wgt", "*", "(", "imls", "<=", "(", "mean", "+", "(", "fct", "*", "adjustment", ")", ")", ")", ".", "astype", "(", "float", ")", ")", "return", "output", "else", ":", "# use real normal distribution", "assert", "(", "const", ".", "StdDev", ".", "TOTAL", "in", "gsim", ".", "DEFINED_FOR_STANDARD_DEVIATION_TYPES", ")", "imls", "=", "gsim", ".", "to_distribution_values", "(", "imls", ")", "mean", ",", "[", "stddev", "]", "=", "gsim", ".", "get_mean_and_stddevs", "(", "sctx", ",", "rctx", ",", "dctx", ",", "imt", ",", "[", "const", ".", "StdDev", ".", "TOTAL", "]", ")", "mean", "=", "mean", ".", "reshape", "(", "mean", ".", "shape", "+", "(", "1", ",", ")", ")", "stddev", "=", "stddev", ".", "reshape", "(", "stddev", ".", "shape", "+", "(", "1", ",", ")", ")", "output", "=", "np", ".", "zeros", "(", "[", "mean", ".", "shape", "[", "0", "]", ",", "imls", ".", "shape", "[", "0", "]", "]", ")", "for", "(", "wgt", ",", "fct", ")", "in", "weighting", ":", "values", "=", "(", "imls", "-", "(", "mean", "+", "(", "fct", "*", "adjustment", ")", ")", ")", "/", "stddev", "if", "truncation_level", "is", "None", ":", "output", "+=", "(", "wgt", "*", "_norm_sf", "(", "values", ")", ")", "else", ":", "output", "+=", "(", "wgt", "*", "_truncnorm_sf", "(", "truncation_level", ",", "values", ")", ")", "return", "output" ]
This function implements the NGA West 2 GMPE epistemic uncertainty adjustment factor without re-calculating the actual GMPE each time. :param gsim: Instance of the GMPE :param list weighting: Weightings as a list of tuples of (weight, number standard deviations of the epistemic uncertainty adjustment)
[ "This", "function", "implements", "the", "NGA", "West", "2", "GMPE", "epistemic", "uncertainty", "adjustment", "factor", "without", "re", "-", "calculating", "the", "actual", "GMPE", "each", "time", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/nshmp_2014.py#L102-L146
train
233,180
gem/oq-engine
openquake/commonlib/shapefileparser.py
register_fields
def register_fields(w): """ Register shapefile fields. """ PARAMS_LIST = [BASE_PARAMS, GEOMETRY_PARAMS, MFD_PARAMS] for PARAMS in PARAMS_LIST: for _, param, dtype in PARAMS: w.field(param, fieldType=dtype, size=FIELD_SIZE) PARAMS_LIST = [ RATE_PARAMS, STRIKE_PARAMS, DIP_PARAMS, RAKE_PARAMS, NPW_PARAMS, HDEPTH_PARAMS, HDW_PARAMS, PLANES_STRIKES_PARAM, PLANES_DIPS_PARAM] for PARAMS in PARAMS_LIST: for param, dtype in PARAMS: w.field(param, fieldType=dtype, size=FIELD_SIZE) # source typology w.field('sourcetype', 'C')
python
def register_fields(w): """ Register shapefile fields. """ PARAMS_LIST = [BASE_PARAMS, GEOMETRY_PARAMS, MFD_PARAMS] for PARAMS in PARAMS_LIST: for _, param, dtype in PARAMS: w.field(param, fieldType=dtype, size=FIELD_SIZE) PARAMS_LIST = [ RATE_PARAMS, STRIKE_PARAMS, DIP_PARAMS, RAKE_PARAMS, NPW_PARAMS, HDEPTH_PARAMS, HDW_PARAMS, PLANES_STRIKES_PARAM, PLANES_DIPS_PARAM] for PARAMS in PARAMS_LIST: for param, dtype in PARAMS: w.field(param, fieldType=dtype, size=FIELD_SIZE) # source typology w.field('sourcetype', 'C')
[ "def", "register_fields", "(", "w", ")", ":", "PARAMS_LIST", "=", "[", "BASE_PARAMS", ",", "GEOMETRY_PARAMS", ",", "MFD_PARAMS", "]", "for", "PARAMS", "in", "PARAMS_LIST", ":", "for", "_", ",", "param", ",", "dtype", "in", "PARAMS", ":", "w", ".", "field", "(", "param", ",", "fieldType", "=", "dtype", ",", "size", "=", "FIELD_SIZE", ")", "PARAMS_LIST", "=", "[", "RATE_PARAMS", ",", "STRIKE_PARAMS", ",", "DIP_PARAMS", ",", "RAKE_PARAMS", ",", "NPW_PARAMS", ",", "HDEPTH_PARAMS", ",", "HDW_PARAMS", ",", "PLANES_STRIKES_PARAM", ",", "PLANES_DIPS_PARAM", "]", "for", "PARAMS", "in", "PARAMS_LIST", ":", "for", "param", ",", "dtype", "in", "PARAMS", ":", "w", ".", "field", "(", "param", ",", "fieldType", "=", "dtype", ",", "size", "=", "FIELD_SIZE", ")", "# source typology", "w", ".", "field", "(", "'sourcetype'", ",", "'C'", ")" ]
Register shapefile fields.
[ "Register", "shapefile", "fields", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/shapefileparser.py#L86-L103
train
233,181
gem/oq-engine
openquake/commonlib/shapefileparser.py
extract_source_params
def extract_source_params(src): """ Extract params from source object. """ tags = get_taglist(src) data = [] for key, param, vtype in BASE_PARAMS: if key in src.attrib: if vtype == "c": data.append((param, src.attrib[key])) elif vtype == "f": data.append((param, float(src.attrib[key]))) else: data.append((param, None)) elif key in tags: if vtype == "c": data.append((param, src.nodes[tags.index(key)].text)) elif vtype == "f": data.append((param, float(src.nodes[tags.index(key)].text))) else: data.append((param, None)) else: data.append((param, None)) return dict(data)
python
def extract_source_params(src): """ Extract params from source object. """ tags = get_taglist(src) data = [] for key, param, vtype in BASE_PARAMS: if key in src.attrib: if vtype == "c": data.append((param, src.attrib[key])) elif vtype == "f": data.append((param, float(src.attrib[key]))) else: data.append((param, None)) elif key in tags: if vtype == "c": data.append((param, src.nodes[tags.index(key)].text)) elif vtype == "f": data.append((param, float(src.nodes[tags.index(key)].text))) else: data.append((param, None)) else: data.append((param, None)) return dict(data)
[ "def", "extract_source_params", "(", "src", ")", ":", "tags", "=", "get_taglist", "(", "src", ")", "data", "=", "[", "]", "for", "key", ",", "param", ",", "vtype", "in", "BASE_PARAMS", ":", "if", "key", "in", "src", ".", "attrib", ":", "if", "vtype", "==", "\"c\"", ":", "data", ".", "append", "(", "(", "param", ",", "src", ".", "attrib", "[", "key", "]", ")", ")", "elif", "vtype", "==", "\"f\"", ":", "data", ".", "append", "(", "(", "param", ",", "float", "(", "src", ".", "attrib", "[", "key", "]", ")", ")", ")", "else", ":", "data", ".", "append", "(", "(", "param", ",", "None", ")", ")", "elif", "key", "in", "tags", ":", "if", "vtype", "==", "\"c\"", ":", "data", ".", "append", "(", "(", "param", ",", "src", ".", "nodes", "[", "tags", ".", "index", "(", "key", ")", "]", ".", "text", ")", ")", "elif", "vtype", "==", "\"f\"", ":", "data", ".", "append", "(", "(", "param", ",", "float", "(", "src", ".", "nodes", "[", "tags", ".", "index", "(", "key", ")", "]", ".", "text", ")", ")", ")", "else", ":", "data", ".", "append", "(", "(", "param", ",", "None", ")", ")", "else", ":", "data", ".", "append", "(", "(", "param", ",", "None", ")", ")", "return", "dict", "(", "data", ")" ]
Extract params from source object.
[ "Extract", "params", "from", "source", "object", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/shapefileparser.py#L120-L143
train
233,182
gem/oq-engine
openquake/commonlib/shapefileparser.py
parse_complex_fault_geometry
def parse_complex_fault_geometry(node): """ Parses a complex fault geometry node returning both the attributes and parameters in a dictionary """ assert "complexFaultGeometry" in node.tag # Get general attributes geometry = {"intermediateEdges": []} for subnode in node: crds = subnode.nodes[0].nodes[0].text if "faultTopEdge" in subnode.tag: geometry["faultTopEdge"] = numpy.array( [[crds[i], crds[i + 1], crds[i + 2]] for i in range(0, len(crds), 3)]) geometry["upperSeismoDepth"] = numpy.min( geometry["faultTopEdge"][:, 2]) elif "faultBottomEdge" in subnode.tag: geometry["faultBottomEdge"] = numpy.array( [[crds[i], crds[i + 1], crds[i + 2]] for i in range(0, len(crds), 3)]) geometry["lowerSeismoDepth"] = numpy.max( geometry["faultBottomEdge"][:, 2]) elif "intermediateEdge" in subnode.tag: geometry["intermediateEdges"].append( numpy.array([[crds[i], crds[i + 1], crds[i + 2]] for i in range(0, len(crds), 3)])) else: pass geometry["dip"] = None return geometry
python
def parse_complex_fault_geometry(node): """ Parses a complex fault geometry node returning both the attributes and parameters in a dictionary """ assert "complexFaultGeometry" in node.tag # Get general attributes geometry = {"intermediateEdges": []} for subnode in node: crds = subnode.nodes[0].nodes[0].text if "faultTopEdge" in subnode.tag: geometry["faultTopEdge"] = numpy.array( [[crds[i], crds[i + 1], crds[i + 2]] for i in range(0, len(crds), 3)]) geometry["upperSeismoDepth"] = numpy.min( geometry["faultTopEdge"][:, 2]) elif "faultBottomEdge" in subnode.tag: geometry["faultBottomEdge"] = numpy.array( [[crds[i], crds[i + 1], crds[i + 2]] for i in range(0, len(crds), 3)]) geometry["lowerSeismoDepth"] = numpy.max( geometry["faultBottomEdge"][:, 2]) elif "intermediateEdge" in subnode.tag: geometry["intermediateEdges"].append( numpy.array([[crds[i], crds[i + 1], crds[i + 2]] for i in range(0, len(crds), 3)])) else: pass geometry["dip"] = None return geometry
[ "def", "parse_complex_fault_geometry", "(", "node", ")", ":", "assert", "\"complexFaultGeometry\"", "in", "node", ".", "tag", "# Get general attributes", "geometry", "=", "{", "\"intermediateEdges\"", ":", "[", "]", "}", "for", "subnode", "in", "node", ":", "crds", "=", "subnode", ".", "nodes", "[", "0", "]", ".", "nodes", "[", "0", "]", ".", "text", "if", "\"faultTopEdge\"", "in", "subnode", ".", "tag", ":", "geometry", "[", "\"faultTopEdge\"", "]", "=", "numpy", ".", "array", "(", "[", "[", "crds", "[", "i", "]", ",", "crds", "[", "i", "+", "1", "]", ",", "crds", "[", "i", "+", "2", "]", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "crds", ")", ",", "3", ")", "]", ")", "geometry", "[", "\"upperSeismoDepth\"", "]", "=", "numpy", ".", "min", "(", "geometry", "[", "\"faultTopEdge\"", "]", "[", ":", ",", "2", "]", ")", "elif", "\"faultBottomEdge\"", "in", "subnode", ".", "tag", ":", "geometry", "[", "\"faultBottomEdge\"", "]", "=", "numpy", ".", "array", "(", "[", "[", "crds", "[", "i", "]", ",", "crds", "[", "i", "+", "1", "]", ",", "crds", "[", "i", "+", "2", "]", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "crds", ")", ",", "3", ")", "]", ")", "geometry", "[", "\"lowerSeismoDepth\"", "]", "=", "numpy", ".", "max", "(", "geometry", "[", "\"faultBottomEdge\"", "]", "[", ":", ",", "2", "]", ")", "elif", "\"intermediateEdge\"", "in", "subnode", ".", "tag", ":", "geometry", "[", "\"intermediateEdges\"", "]", ".", "append", "(", "numpy", ".", "array", "(", "[", "[", "crds", "[", "i", "]", ",", "crds", "[", "i", "+", "1", "]", ",", "crds", "[", "i", "+", "2", "]", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "crds", ")", ",", "3", ")", "]", ")", ")", "else", ":", "pass", "geometry", "[", "\"dip\"", "]", "=", "None", "return", "geometry" ]
Parses a complex fault geometry node returning both the attributes and parameters in a dictionary
[ "Parses", "a", "complex", "fault", "geometry", "node", "returning", "both", "the", "attributes", "and", "parameters", "in", "a", "dictionary" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/shapefileparser.py#L201-L231
train
233,183
gem/oq-engine
openquake/commonlib/shapefileparser.py
parse_planar_fault_geometry
def parse_planar_fault_geometry(node): """ Parses a planar fault geometry node returning both the attributes and parameters in a dictionary """ assert "planarSurface" in node.tag geometry = {"strike": node.attrib["strike"], "dip": node.attrib["dip"]} upper_depth = numpy.inf lower_depth = 0.0 tags = get_taglist(node) corner_points = [] for locn in ["topLeft", "topRight", "bottomRight", "bottomLeft"]: plane = node.nodes[tags.index(locn)] upper_depth = plane["depth"] if plane["depth"] < upper_depth else\ upper_depth lower_depth = plane["depth"] if plane["depth"] > lower_depth else\ lower_depth corner_points.append([plane["lon"], plane["lat"], plane["depth"]]) geometry["upperSeismoDepth"] = upper_depth geometry["lowerSeismoDepth"] = lower_depth geometry["corners"] = numpy.array(corner_points) return geometry
python
def parse_planar_fault_geometry(node): """ Parses a planar fault geometry node returning both the attributes and parameters in a dictionary """ assert "planarSurface" in node.tag geometry = {"strike": node.attrib["strike"], "dip": node.attrib["dip"]} upper_depth = numpy.inf lower_depth = 0.0 tags = get_taglist(node) corner_points = [] for locn in ["topLeft", "topRight", "bottomRight", "bottomLeft"]: plane = node.nodes[tags.index(locn)] upper_depth = plane["depth"] if plane["depth"] < upper_depth else\ upper_depth lower_depth = plane["depth"] if plane["depth"] > lower_depth else\ lower_depth corner_points.append([plane["lon"], plane["lat"], plane["depth"]]) geometry["upperSeismoDepth"] = upper_depth geometry["lowerSeismoDepth"] = lower_depth geometry["corners"] = numpy.array(corner_points) return geometry
[ "def", "parse_planar_fault_geometry", "(", "node", ")", ":", "assert", "\"planarSurface\"", "in", "node", ".", "tag", "geometry", "=", "{", "\"strike\"", ":", "node", ".", "attrib", "[", "\"strike\"", "]", ",", "\"dip\"", ":", "node", ".", "attrib", "[", "\"dip\"", "]", "}", "upper_depth", "=", "numpy", ".", "inf", "lower_depth", "=", "0.0", "tags", "=", "get_taglist", "(", "node", ")", "corner_points", "=", "[", "]", "for", "locn", "in", "[", "\"topLeft\"", ",", "\"topRight\"", ",", "\"bottomRight\"", ",", "\"bottomLeft\"", "]", ":", "plane", "=", "node", ".", "nodes", "[", "tags", ".", "index", "(", "locn", ")", "]", "upper_depth", "=", "plane", "[", "\"depth\"", "]", "if", "plane", "[", "\"depth\"", "]", "<", "upper_depth", "else", "upper_depth", "lower_depth", "=", "plane", "[", "\"depth\"", "]", "if", "plane", "[", "\"depth\"", "]", ">", "lower_depth", "else", "lower_depth", "corner_points", ".", "append", "(", "[", "plane", "[", "\"lon\"", "]", ",", "plane", "[", "\"lat\"", "]", ",", "plane", "[", "\"depth\"", "]", "]", ")", "geometry", "[", "\"upperSeismoDepth\"", "]", "=", "upper_depth", "geometry", "[", "\"lowerSeismoDepth\"", "]", "=", "lower_depth", "geometry", "[", "\"corners\"", "]", "=", "numpy", ".", "array", "(", "corner_points", ")", "return", "geometry" ]
Parses a planar fault geometry node returning both the attributes and parameters in a dictionary
[ "Parses", "a", "planar", "fault", "geometry", "node", "returning", "both", "the", "attributes", "and", "parameters", "in", "a", "dictionary" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/shapefileparser.py#L234-L256
train
233,184
gem/oq-engine
openquake/commonlib/shapefileparser.py
extract_mfd_params
def extract_mfd_params(src): """ Extracts the MFD parameters from an object """ tags = get_taglist(src) if "incrementalMFD" in tags: mfd_node = src.nodes[tags.index("incrementalMFD")] elif "truncGutenbergRichterMFD" in tags: mfd_node = src.nodes[tags.index("truncGutenbergRichterMFD")] elif "arbitraryMFD" in tags: mfd_node = src.nodes[tags.index("arbitraryMFD")] elif "YoungsCoppersmithMFD" in tags: mfd_node = src.nodes[tags.index("YoungsCoppersmithMFD")] else: raise ValueError("Source %s contains no supported MFD type!" % src.tag) data = [] rates = [] for key, param, vtype in MFD_PARAMS: if key in mfd_node.attrib and mfd_node.attrib[key] is not None: data.append((param, mfd_node.attrib[key])) else: data.append((param, None)) if ("incrementalMFD" or "arbitraryMFD") in mfd_node.tag: # Extract Rates rates = ~mfd_node.occurRates n_r = len(rates) if n_r > MAX_RATES: raise ValueError("Number of rates in source %s too large " "to be placed into shapefile" % src.tag) rate_dict = dict([(key, rates[i] if i < n_r else None) for i, (key, _) in enumerate(RATE_PARAMS)]) elif "YoungsCoppersmithMFD" in mfd_node.tag: rate_dict = dict([(key, mfd_node.attrib['characteristicRate']) for i, (key, _) in enumerate(RATE_PARAMS)]) else: rate_dict = dict([(key, None) for i, (key, _) in enumerate(RATE_PARAMS)]) return dict(data), rate_dict
python
def extract_mfd_params(src): """ Extracts the MFD parameters from an object """ tags = get_taglist(src) if "incrementalMFD" in tags: mfd_node = src.nodes[tags.index("incrementalMFD")] elif "truncGutenbergRichterMFD" in tags: mfd_node = src.nodes[tags.index("truncGutenbergRichterMFD")] elif "arbitraryMFD" in tags: mfd_node = src.nodes[tags.index("arbitraryMFD")] elif "YoungsCoppersmithMFD" in tags: mfd_node = src.nodes[tags.index("YoungsCoppersmithMFD")] else: raise ValueError("Source %s contains no supported MFD type!" % src.tag) data = [] rates = [] for key, param, vtype in MFD_PARAMS: if key in mfd_node.attrib and mfd_node.attrib[key] is not None: data.append((param, mfd_node.attrib[key])) else: data.append((param, None)) if ("incrementalMFD" or "arbitraryMFD") in mfd_node.tag: # Extract Rates rates = ~mfd_node.occurRates n_r = len(rates) if n_r > MAX_RATES: raise ValueError("Number of rates in source %s too large " "to be placed into shapefile" % src.tag) rate_dict = dict([(key, rates[i] if i < n_r else None) for i, (key, _) in enumerate(RATE_PARAMS)]) elif "YoungsCoppersmithMFD" in mfd_node.tag: rate_dict = dict([(key, mfd_node.attrib['characteristicRate']) for i, (key, _) in enumerate(RATE_PARAMS)]) else: rate_dict = dict([(key, None) for i, (key, _) in enumerate(RATE_PARAMS)]) return dict(data), rate_dict
[ "def", "extract_mfd_params", "(", "src", ")", ":", "tags", "=", "get_taglist", "(", "src", ")", "if", "\"incrementalMFD\"", "in", "tags", ":", "mfd_node", "=", "src", ".", "nodes", "[", "tags", ".", "index", "(", "\"incrementalMFD\"", ")", "]", "elif", "\"truncGutenbergRichterMFD\"", "in", "tags", ":", "mfd_node", "=", "src", ".", "nodes", "[", "tags", ".", "index", "(", "\"truncGutenbergRichterMFD\"", ")", "]", "elif", "\"arbitraryMFD\"", "in", "tags", ":", "mfd_node", "=", "src", ".", "nodes", "[", "tags", ".", "index", "(", "\"arbitraryMFD\"", ")", "]", "elif", "\"YoungsCoppersmithMFD\"", "in", "tags", ":", "mfd_node", "=", "src", ".", "nodes", "[", "tags", ".", "index", "(", "\"YoungsCoppersmithMFD\"", ")", "]", "else", ":", "raise", "ValueError", "(", "\"Source %s contains no supported MFD type!\"", "%", "src", ".", "tag", ")", "data", "=", "[", "]", "rates", "=", "[", "]", "for", "key", ",", "param", ",", "vtype", "in", "MFD_PARAMS", ":", "if", "key", "in", "mfd_node", ".", "attrib", "and", "mfd_node", ".", "attrib", "[", "key", "]", "is", "not", "None", ":", "data", ".", "append", "(", "(", "param", ",", "mfd_node", ".", "attrib", "[", "key", "]", ")", ")", "else", ":", "data", ".", "append", "(", "(", "param", ",", "None", ")", ")", "if", "(", "\"incrementalMFD\"", "or", "\"arbitraryMFD\"", ")", "in", "mfd_node", ".", "tag", ":", "# Extract Rates", "rates", "=", "~", "mfd_node", ".", "occurRates", "n_r", "=", "len", "(", "rates", ")", "if", "n_r", ">", "MAX_RATES", ":", "raise", "ValueError", "(", "\"Number of rates in source %s too large \"", "\"to be placed into shapefile\"", "%", "src", ".", "tag", ")", "rate_dict", "=", "dict", "(", "[", "(", "key", ",", "rates", "[", "i", "]", "if", "i", "<", "n_r", "else", "None", ")", "for", "i", ",", "(", "key", ",", "_", ")", "in", "enumerate", "(", "RATE_PARAMS", ")", "]", ")", "elif", "\"YoungsCoppersmithMFD\"", "in", "mfd_node", ".", "tag", ":", "rate_dict", "=", "dict", "(", "[", "(", "key", ",", "mfd_node", ".", "attrib", "[", "'characteristicRate'", "]", ")", "for", "i", ",", "(", "key", ",", "_", ")", "in", "enumerate", "(", "RATE_PARAMS", ")", "]", ")", "else", ":", "rate_dict", "=", "dict", "(", "[", "(", "key", ",", "None", ")", "for", "i", ",", "(", "key", ",", "_", ")", "in", "enumerate", "(", "RATE_PARAMS", ")", "]", ")", "return", "dict", "(", "data", ")", ",", "rate_dict" ]
Extracts the MFD parameters from an object
[ "Extracts", "the", "MFD", "parameters", "from", "an", "object" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/shapefileparser.py#L322-L359
train
233,185
gem/oq-engine
openquake/commonlib/shapefileparser.py
extract_source_hypocentral_depths
def extract_source_hypocentral_depths(src): """ Extract source hypocentral depths. """ if "pointSource" not in src.tag and "areaSource" not in src.tag: hds = dict([(key, None) for key, _ in HDEPTH_PARAMS]) hdsw = dict([(key, None) for key, _ in HDW_PARAMS]) return hds, hdsw tags = get_taglist(src) hdd_nodeset = src.nodes[tags.index("hypoDepthDist")] if len(hdd_nodeset) > MAX_HYPO_DEPTHS: raise ValueError("Number of hypocentral depths %s exceeds stated " "maximum of %s" % (str(len(hdd_nodeset)), str(MAX_HYPO_DEPTHS))) if len(hdd_nodeset): hds = [] hdws = [] for hdd_node in hdd_nodeset: hds.append(float(hdd_node.attrib["depth"])) hdws.append(float(hdd_node.attrib["probability"])) hds = expand_src_param(hds, HDEPTH_PARAMS) hdsw = expand_src_param(hdws, HDW_PARAMS) else: hds = dict([(key, None) for key, _ in HDEPTH_PARAMS]) hdsw = dict([(key, None) for key, _ in HDW_PARAMS]) return hds, hdsw
python
def extract_source_hypocentral_depths(src): """ Extract source hypocentral depths. """ if "pointSource" not in src.tag and "areaSource" not in src.tag: hds = dict([(key, None) for key, _ in HDEPTH_PARAMS]) hdsw = dict([(key, None) for key, _ in HDW_PARAMS]) return hds, hdsw tags = get_taglist(src) hdd_nodeset = src.nodes[tags.index("hypoDepthDist")] if len(hdd_nodeset) > MAX_HYPO_DEPTHS: raise ValueError("Number of hypocentral depths %s exceeds stated " "maximum of %s" % (str(len(hdd_nodeset)), str(MAX_HYPO_DEPTHS))) if len(hdd_nodeset): hds = [] hdws = [] for hdd_node in hdd_nodeset: hds.append(float(hdd_node.attrib["depth"])) hdws.append(float(hdd_node.attrib["probability"])) hds = expand_src_param(hds, HDEPTH_PARAMS) hdsw = expand_src_param(hdws, HDW_PARAMS) else: hds = dict([(key, None) for key, _ in HDEPTH_PARAMS]) hdsw = dict([(key, None) for key, _ in HDW_PARAMS]) return hds, hdsw
[ "def", "extract_source_hypocentral_depths", "(", "src", ")", ":", "if", "\"pointSource\"", "not", "in", "src", ".", "tag", "and", "\"areaSource\"", "not", "in", "src", ".", "tag", ":", "hds", "=", "dict", "(", "[", "(", "key", ",", "None", ")", "for", "key", ",", "_", "in", "HDEPTH_PARAMS", "]", ")", "hdsw", "=", "dict", "(", "[", "(", "key", ",", "None", ")", "for", "key", ",", "_", "in", "HDW_PARAMS", "]", ")", "return", "hds", ",", "hdsw", "tags", "=", "get_taglist", "(", "src", ")", "hdd_nodeset", "=", "src", ".", "nodes", "[", "tags", ".", "index", "(", "\"hypoDepthDist\"", ")", "]", "if", "len", "(", "hdd_nodeset", ")", ">", "MAX_HYPO_DEPTHS", ":", "raise", "ValueError", "(", "\"Number of hypocentral depths %s exceeds stated \"", "\"maximum of %s\"", "%", "(", "str", "(", "len", "(", "hdd_nodeset", ")", ")", ",", "str", "(", "MAX_HYPO_DEPTHS", ")", ")", ")", "if", "len", "(", "hdd_nodeset", ")", ":", "hds", "=", "[", "]", "hdws", "=", "[", "]", "for", "hdd_node", "in", "hdd_nodeset", ":", "hds", ".", "append", "(", "float", "(", "hdd_node", ".", "attrib", "[", "\"depth\"", "]", ")", ")", "hdws", ".", "append", "(", "float", "(", "hdd_node", ".", "attrib", "[", "\"probability\"", "]", ")", ")", "hds", "=", "expand_src_param", "(", "hds", ",", "HDEPTH_PARAMS", ")", "hdsw", "=", "expand_src_param", "(", "hdws", ",", "HDW_PARAMS", ")", "else", ":", "hds", "=", "dict", "(", "[", "(", "key", ",", "None", ")", "for", "key", ",", "_", "in", "HDEPTH_PARAMS", "]", ")", "hdsw", "=", "dict", "(", "[", "(", "key", ",", "None", ")", "for", "key", ",", "_", "in", "HDW_PARAMS", "]", ")", "return", "hds", ",", "hdsw" ]
Extract source hypocentral depths.
[ "Extract", "source", "hypocentral", "depths", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/shapefileparser.py#L397-L425
train
233,186
gem/oq-engine
openquake/commonlib/shapefileparser.py
extract_source_planes_strikes_dips
def extract_source_planes_strikes_dips(src): """ Extract strike and dip angles for source defined by multiple planes. """ if "characteristicFaultSource" not in src.tag: strikes = dict([(key, None) for key, _ in PLANES_STRIKES_PARAM]) dips = dict([(key, None) for key, _ in PLANES_DIPS_PARAM]) return strikes, dips tags = get_taglist(src) surface_set = src.nodes[tags.index("surface")] strikes = [] dips = [] num_planes = 0 for surface in surface_set: if "planarSurface" in surface.tag: strikes.append(float(surface.attrib["strike"])) dips.append(float(surface.attrib["dip"])) num_planes += 1 if num_planes > MAX_PLANES: raise ValueError("Number of planes in sourcs %s exceededs maximum " "of %s" % (str(num_planes), str(MAX_PLANES))) if num_planes: strikes = expand_src_param(strikes, PLANES_STRIKES_PARAM) dips = expand_src_param(dips, PLANES_DIPS_PARAM) else: strikes = dict([(key, None) for key, _ in PLANES_STRIKES_PARAM]) dips = dict([(key, None) for key, _ in PLANES_DIPS_PARAM]) return strikes, dips
python
def extract_source_planes_strikes_dips(src): """ Extract strike and dip angles for source defined by multiple planes. """ if "characteristicFaultSource" not in src.tag: strikes = dict([(key, None) for key, _ in PLANES_STRIKES_PARAM]) dips = dict([(key, None) for key, _ in PLANES_DIPS_PARAM]) return strikes, dips tags = get_taglist(src) surface_set = src.nodes[tags.index("surface")] strikes = [] dips = [] num_planes = 0 for surface in surface_set: if "planarSurface" in surface.tag: strikes.append(float(surface.attrib["strike"])) dips.append(float(surface.attrib["dip"])) num_planes += 1 if num_planes > MAX_PLANES: raise ValueError("Number of planes in sourcs %s exceededs maximum " "of %s" % (str(num_planes), str(MAX_PLANES))) if num_planes: strikes = expand_src_param(strikes, PLANES_STRIKES_PARAM) dips = expand_src_param(dips, PLANES_DIPS_PARAM) else: strikes = dict([(key, None) for key, _ in PLANES_STRIKES_PARAM]) dips = dict([(key, None) for key, _ in PLANES_DIPS_PARAM]) return strikes, dips
[ "def", "extract_source_planes_strikes_dips", "(", "src", ")", ":", "if", "\"characteristicFaultSource\"", "not", "in", "src", ".", "tag", ":", "strikes", "=", "dict", "(", "[", "(", "key", ",", "None", ")", "for", "key", ",", "_", "in", "PLANES_STRIKES_PARAM", "]", ")", "dips", "=", "dict", "(", "[", "(", "key", ",", "None", ")", "for", "key", ",", "_", "in", "PLANES_DIPS_PARAM", "]", ")", "return", "strikes", ",", "dips", "tags", "=", "get_taglist", "(", "src", ")", "surface_set", "=", "src", ".", "nodes", "[", "tags", ".", "index", "(", "\"surface\"", ")", "]", "strikes", "=", "[", "]", "dips", "=", "[", "]", "num_planes", "=", "0", "for", "surface", "in", "surface_set", ":", "if", "\"planarSurface\"", "in", "surface", ".", "tag", ":", "strikes", ".", "append", "(", "float", "(", "surface", ".", "attrib", "[", "\"strike\"", "]", ")", ")", "dips", ".", "append", "(", "float", "(", "surface", ".", "attrib", "[", "\"dip\"", "]", ")", ")", "num_planes", "+=", "1", "if", "num_planes", ">", "MAX_PLANES", ":", "raise", "ValueError", "(", "\"Number of planes in sourcs %s exceededs maximum \"", "\"of %s\"", "%", "(", "str", "(", "num_planes", ")", ",", "str", "(", "MAX_PLANES", ")", ")", ")", "if", "num_planes", ":", "strikes", "=", "expand_src_param", "(", "strikes", ",", "PLANES_STRIKES_PARAM", ")", "dips", "=", "expand_src_param", "(", "dips", ",", "PLANES_DIPS_PARAM", ")", "else", ":", "strikes", "=", "dict", "(", "[", "(", "key", ",", "None", ")", "for", "key", ",", "_", "in", "PLANES_STRIKES_PARAM", "]", ")", "dips", "=", "dict", "(", "[", "(", "key", ",", "None", ")", "for", "key", ",", "_", "in", "PLANES_DIPS_PARAM", "]", ")", "return", "strikes", ",", "dips" ]
Extract strike and dip angles for source defined by multiple planes.
[ "Extract", "strike", "and", "dip", "angles", "for", "source", "defined", "by", "multiple", "planes", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/shapefileparser.py#L428-L456
train
233,187
gem/oq-engine
openquake/commonlib/shapefileparser.py
set_params
def set_params(w, src): """ Set source parameters. """ params = extract_source_params(src) # this is done because for characteristic sources geometry is in # 'surface' attribute params.update(extract_geometry_params(src)) mfd_pars, rate_pars = extract_mfd_params(src) params.update(mfd_pars) params.update(rate_pars) strikes, dips, rakes, np_weights = extract_source_nodal_planes(src) params.update(strikes) params.update(dips) params.update(rakes) params.update(np_weights) hds, hdsw = extract_source_hypocentral_depths(src) params.update(hds) params.update(hdsw) pstrikes, pdips = extract_source_planes_strikes_dips(src) params.update(pstrikes) params.update(pdips) params['sourcetype'] = striptag(src.tag) w.record(**params)
python
def set_params(w, src): """ Set source parameters. """ params = extract_source_params(src) # this is done because for characteristic sources geometry is in # 'surface' attribute params.update(extract_geometry_params(src)) mfd_pars, rate_pars = extract_mfd_params(src) params.update(mfd_pars) params.update(rate_pars) strikes, dips, rakes, np_weights = extract_source_nodal_planes(src) params.update(strikes) params.update(dips) params.update(rakes) params.update(np_weights) hds, hdsw = extract_source_hypocentral_depths(src) params.update(hds) params.update(hdsw) pstrikes, pdips = extract_source_planes_strikes_dips(src) params.update(pstrikes) params.update(pdips) params['sourcetype'] = striptag(src.tag) w.record(**params)
[ "def", "set_params", "(", "w", ",", "src", ")", ":", "params", "=", "extract_source_params", "(", "src", ")", "# this is done because for characteristic sources geometry is in", "# 'surface' attribute", "params", ".", "update", "(", "extract_geometry_params", "(", "src", ")", ")", "mfd_pars", ",", "rate_pars", "=", "extract_mfd_params", "(", "src", ")", "params", ".", "update", "(", "mfd_pars", ")", "params", ".", "update", "(", "rate_pars", ")", "strikes", ",", "dips", ",", "rakes", ",", "np_weights", "=", "extract_source_nodal_planes", "(", "src", ")", "params", ".", "update", "(", "strikes", ")", "params", ".", "update", "(", "dips", ")", "params", ".", "update", "(", "rakes", ")", "params", ".", "update", "(", "np_weights", ")", "hds", ",", "hdsw", "=", "extract_source_hypocentral_depths", "(", "src", ")", "params", ".", "update", "(", "hds", ")", "params", ".", "update", "(", "hdsw", ")", "pstrikes", ",", "pdips", "=", "extract_source_planes_strikes_dips", "(", "src", ")", "params", ".", "update", "(", "pstrikes", ")", "params", ".", "update", "(", "pdips", ")", "params", "[", "'sourcetype'", "]", "=", "striptag", "(", "src", ".", "tag", ")", "w", ".", "record", "(", "*", "*", "params", ")" ]
Set source parameters.
[ "Set", "source", "parameters", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/shapefileparser.py#L459-L486
train
233,188
gem/oq-engine
openquake/commonlib/shapefileparser.py
set_area_geometry
def set_area_geometry(w, src): """ Set area polygon as shapefile geometry """ assert "areaSource" in src.tag geometry_node = src.nodes[get_taglist(src).index("areaGeometry")] area_attrs = parse_area_geometry(geometry_node) w.poly(parts=[area_attrs["polygon"].tolist()])
python
def set_area_geometry(w, src): """ Set area polygon as shapefile geometry """ assert "areaSource" in src.tag geometry_node = src.nodes[get_taglist(src).index("areaGeometry")] area_attrs = parse_area_geometry(geometry_node) w.poly(parts=[area_attrs["polygon"].tolist()])
[ "def", "set_area_geometry", "(", "w", ",", "src", ")", ":", "assert", "\"areaSource\"", "in", "src", ".", "tag", "geometry_node", "=", "src", ".", "nodes", "[", "get_taglist", "(", "src", ")", ".", "index", "(", "\"areaGeometry\"", ")", "]", "area_attrs", "=", "parse_area_geometry", "(", "geometry_node", ")", "w", ".", "poly", "(", "parts", "=", "[", "area_attrs", "[", "\"polygon\"", "]", ".", "tolist", "(", ")", "]", ")" ]
Set area polygon as shapefile geometry
[ "Set", "area", "polygon", "as", "shapefile", "geometry" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/shapefileparser.py#L489-L496
train
233,189
gem/oq-engine
openquake/commonlib/shapefileparser.py
set_point_geometry
def set_point_geometry(w, src): """ Set point location as shapefile geometry. """ assert "pointSource" in src.tag geometry_node = src.nodes[get_taglist(src).index("pointGeometry")] point_attrs = parse_point_geometry(geometry_node) w.point(point_attrs["point"][0], point_attrs["point"][1])
python
def set_point_geometry(w, src): """ Set point location as shapefile geometry. """ assert "pointSource" in src.tag geometry_node = src.nodes[get_taglist(src).index("pointGeometry")] point_attrs = parse_point_geometry(geometry_node) w.point(point_attrs["point"][0], point_attrs["point"][1])
[ "def", "set_point_geometry", "(", "w", ",", "src", ")", ":", "assert", "\"pointSource\"", "in", "src", ".", "tag", "geometry_node", "=", "src", ".", "nodes", "[", "get_taglist", "(", "src", ")", ".", "index", "(", "\"pointGeometry\"", ")", "]", "point_attrs", "=", "parse_point_geometry", "(", "geometry_node", ")", "w", ".", "point", "(", "point_attrs", "[", "\"point\"", "]", "[", "0", "]", ",", "point_attrs", "[", "\"point\"", "]", "[", "1", "]", ")" ]
Set point location as shapefile geometry.
[ "Set", "point", "location", "as", "shapefile", "geometry", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/shapefileparser.py#L499-L506
train
233,190
gem/oq-engine
openquake/commonlib/shapefileparser.py
set_simple_fault_geometry
def set_simple_fault_geometry(w, src): """ Set simple fault trace coordinates as shapefile geometry. :parameter w: Writer :parameter src: source """ assert "simpleFaultSource" in src.tag geometry_node = src.nodes[get_taglist(src).index("simpleFaultGeometry")] fault_attrs = parse_simple_fault_geometry(geometry_node) w.line(parts=[fault_attrs["trace"].tolist()])
python
def set_simple_fault_geometry(w, src): """ Set simple fault trace coordinates as shapefile geometry. :parameter w: Writer :parameter src: source """ assert "simpleFaultSource" in src.tag geometry_node = src.nodes[get_taglist(src).index("simpleFaultGeometry")] fault_attrs = parse_simple_fault_geometry(geometry_node) w.line(parts=[fault_attrs["trace"].tolist()])
[ "def", "set_simple_fault_geometry", "(", "w", ",", "src", ")", ":", "assert", "\"simpleFaultSource\"", "in", "src", ".", "tag", "geometry_node", "=", "src", ".", "nodes", "[", "get_taglist", "(", "src", ")", ".", "index", "(", "\"simpleFaultGeometry\"", ")", "]", "fault_attrs", "=", "parse_simple_fault_geometry", "(", "geometry_node", ")", "w", ".", "line", "(", "parts", "=", "[", "fault_attrs", "[", "\"trace\"", "]", ".", "tolist", "(", ")", "]", ")" ]
Set simple fault trace coordinates as shapefile geometry. :parameter w: Writer :parameter src: source
[ "Set", "simple", "fault", "trace", "coordinates", "as", "shapefile", "geometry", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/shapefileparser.py#L509-L521
train
233,191
gem/oq-engine
openquake/commonlib/shapefileparser.py
set_simple_fault_geometry_3D
def set_simple_fault_geometry_3D(w, src): """ Builds a 3D polygon from a node instance """ assert "simpleFaultSource" in src.tag geometry_node = src.nodes[get_taglist(src).index("simpleFaultGeometry")] fault_attrs = parse_simple_fault_geometry(geometry_node) build_polygon_from_fault_attrs(w, fault_attrs)
python
def set_simple_fault_geometry_3D(w, src): """ Builds a 3D polygon from a node instance """ assert "simpleFaultSource" in src.tag geometry_node = src.nodes[get_taglist(src).index("simpleFaultGeometry")] fault_attrs = parse_simple_fault_geometry(geometry_node) build_polygon_from_fault_attrs(w, fault_attrs)
[ "def", "set_simple_fault_geometry_3D", "(", "w", ",", "src", ")", ":", "assert", "\"simpleFaultSource\"", "in", "src", ".", "tag", "geometry_node", "=", "src", ".", "nodes", "[", "get_taglist", "(", "src", ")", ".", "index", "(", "\"simpleFaultGeometry\"", ")", "]", "fault_attrs", "=", "parse_simple_fault_geometry", "(", "geometry_node", ")", "build_polygon_from_fault_attrs", "(", "w", ",", "fault_attrs", ")" ]
Builds a 3D polygon from a node instance
[ "Builds", "a", "3D", "polygon", "from", "a", "node", "instance" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/shapefileparser.py#L543-L550
train
233,192
gem/oq-engine
openquake/commonlib/shapefileparser.py
SourceModel.appraise_source_model
def appraise_source_model(self): """ Identify parameters defined in NRML source model file, so that shapefile contains only source model specific fields. """ for src in self.sources: # source params src_taglist = get_taglist(src) if "areaSource" in src.tag: self.has_area_source = True npd_node = src.nodes[src_taglist.index("nodalPlaneDist")] npd_size = len(npd_node) hdd_node = src.nodes[src_taglist.index("hypoDepthDist")] hdd_size = len(hdd_node) self.num_np = (npd_size if npd_size > self.num_np else self.num_np) self.num_hd = (hdd_size if hdd_size > self.num_hd else self.num_hd) elif "pointSource" in src.tag: self.has_point_source = True npd_node = src.nodes[src_taglist.index("nodalPlaneDist")] npd_size = len(npd_node) hdd_node = src.nodes[src_taglist.index("hypoDepthDist")] hdd_size = len(hdd_node) self.num_np = (npd_size if npd_size > self.num_np else self.num_np) self.num_hd = (hdd_size if hdd_size > self.num_hd else self.num_hd) elif "simpleFaultSource" in src.tag: self.has_simple_fault_geometry = True elif "complexFaultSource" in src.tag: self.has_complex_fault_geometry = True elif "characteristicFaultSource" in src.tag: # Get the surface node surface_node = src.nodes[src_taglist.index("surface")] p_size = 0 for surface in surface_node.nodes: if "simpleFaultGeometry" in surface.tag: self.has_simple_fault_geometry = True elif "complexFaultGeometry" in surface.tag: self.has_complex_fault_geometry = True elif "planarSurface" in surface.tag: self.has_planar_geometry = True p_size += 1 self.num_p = p_size if p_size > self.num_p else self.num_p else: pass # MFD params if "truncGutenbergRichterMFD" in src_taglist: self.has_mfd_gr = True elif "incrementalMFD" in src_taglist: self.has_mfd_incremental = True # Get rate size mfd_node = src.nodes[src_taglist.index("incrementalMFD")] r_size = len(mfd_node.nodes[0].text) self.num_r = r_size if r_size > self.num_r else self.num_r else: pass
python
def appraise_source_model(self): """ Identify parameters defined in NRML source model file, so that shapefile contains only source model specific fields. """ for src in self.sources: # source params src_taglist = get_taglist(src) if "areaSource" in src.tag: self.has_area_source = True npd_node = src.nodes[src_taglist.index("nodalPlaneDist")] npd_size = len(npd_node) hdd_node = src.nodes[src_taglist.index("hypoDepthDist")] hdd_size = len(hdd_node) self.num_np = (npd_size if npd_size > self.num_np else self.num_np) self.num_hd = (hdd_size if hdd_size > self.num_hd else self.num_hd) elif "pointSource" in src.tag: self.has_point_source = True npd_node = src.nodes[src_taglist.index("nodalPlaneDist")] npd_size = len(npd_node) hdd_node = src.nodes[src_taglist.index("hypoDepthDist")] hdd_size = len(hdd_node) self.num_np = (npd_size if npd_size > self.num_np else self.num_np) self.num_hd = (hdd_size if hdd_size > self.num_hd else self.num_hd) elif "simpleFaultSource" in src.tag: self.has_simple_fault_geometry = True elif "complexFaultSource" in src.tag: self.has_complex_fault_geometry = True elif "characteristicFaultSource" in src.tag: # Get the surface node surface_node = src.nodes[src_taglist.index("surface")] p_size = 0 for surface in surface_node.nodes: if "simpleFaultGeometry" in surface.tag: self.has_simple_fault_geometry = True elif "complexFaultGeometry" in surface.tag: self.has_complex_fault_geometry = True elif "planarSurface" in surface.tag: self.has_planar_geometry = True p_size += 1 self.num_p = p_size if p_size > self.num_p else self.num_p else: pass # MFD params if "truncGutenbergRichterMFD" in src_taglist: self.has_mfd_gr = True elif "incrementalMFD" in src_taglist: self.has_mfd_incremental = True # Get rate size mfd_node = src.nodes[src_taglist.index("incrementalMFD")] r_size = len(mfd_node.nodes[0].text) self.num_r = r_size if r_size > self.num_r else self.num_r else: pass
[ "def", "appraise_source_model", "(", "self", ")", ":", "for", "src", "in", "self", ".", "sources", ":", "# source params", "src_taglist", "=", "get_taglist", "(", "src", ")", "if", "\"areaSource\"", "in", "src", ".", "tag", ":", "self", ".", "has_area_source", "=", "True", "npd_node", "=", "src", ".", "nodes", "[", "src_taglist", ".", "index", "(", "\"nodalPlaneDist\"", ")", "]", "npd_size", "=", "len", "(", "npd_node", ")", "hdd_node", "=", "src", ".", "nodes", "[", "src_taglist", ".", "index", "(", "\"hypoDepthDist\"", ")", "]", "hdd_size", "=", "len", "(", "hdd_node", ")", "self", ".", "num_np", "=", "(", "npd_size", "if", "npd_size", ">", "self", ".", "num_np", "else", "self", ".", "num_np", ")", "self", ".", "num_hd", "=", "(", "hdd_size", "if", "hdd_size", ">", "self", ".", "num_hd", "else", "self", ".", "num_hd", ")", "elif", "\"pointSource\"", "in", "src", ".", "tag", ":", "self", ".", "has_point_source", "=", "True", "npd_node", "=", "src", ".", "nodes", "[", "src_taglist", ".", "index", "(", "\"nodalPlaneDist\"", ")", "]", "npd_size", "=", "len", "(", "npd_node", ")", "hdd_node", "=", "src", ".", "nodes", "[", "src_taglist", ".", "index", "(", "\"hypoDepthDist\"", ")", "]", "hdd_size", "=", "len", "(", "hdd_node", ")", "self", ".", "num_np", "=", "(", "npd_size", "if", "npd_size", ">", "self", ".", "num_np", "else", "self", ".", "num_np", ")", "self", ".", "num_hd", "=", "(", "hdd_size", "if", "hdd_size", ">", "self", ".", "num_hd", "else", "self", ".", "num_hd", ")", "elif", "\"simpleFaultSource\"", "in", "src", ".", "tag", ":", "self", ".", "has_simple_fault_geometry", "=", "True", "elif", "\"complexFaultSource\"", "in", "src", ".", "tag", ":", "self", ".", "has_complex_fault_geometry", "=", "True", "elif", "\"characteristicFaultSource\"", "in", "src", ".", "tag", ":", "# Get the surface node", "surface_node", "=", "src", ".", "nodes", "[", "src_taglist", ".", "index", "(", "\"surface\"", ")", "]", "p_size", "=", "0", "for", "surface", "in", "surface_node", ".", "nodes", ":", "if", "\"simpleFaultGeometry\"", "in", "surface", ".", "tag", ":", "self", ".", "has_simple_fault_geometry", "=", "True", "elif", "\"complexFaultGeometry\"", "in", "surface", ".", "tag", ":", "self", ".", "has_complex_fault_geometry", "=", "True", "elif", "\"planarSurface\"", "in", "surface", ".", "tag", ":", "self", ".", "has_planar_geometry", "=", "True", "p_size", "+=", "1", "self", ".", "num_p", "=", "p_size", "if", "p_size", ">", "self", ".", "num_p", "else", "self", ".", "num_p", "else", ":", "pass", "# MFD params", "if", "\"truncGutenbergRichterMFD\"", "in", "src_taglist", ":", "self", ".", "has_mfd_gr", "=", "True", "elif", "\"incrementalMFD\"", "in", "src_taglist", ":", "self", ".", "has_mfd_incremental", "=", "True", "# Get rate size", "mfd_node", "=", "src", ".", "nodes", "[", "src_taglist", ".", "index", "(", "\"incrementalMFD\"", ")", "]", "r_size", "=", "len", "(", "mfd_node", ".", "nodes", "[", "0", "]", ".", "text", ")", "self", ".", "num_r", "=", "r_size", "if", "r_size", ">", "self", ".", "num_r", "else", "self", ".", "num_r", "else", ":", "pass" ]
Identify parameters defined in NRML source model file, so that shapefile contains only source model specific fields.
[ "Identify", "parameters", "defined", "in", "NRML", "source", "model", "file", "so", "that", "shapefile", "contains", "only", "source", "model", "specific", "fields", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/shapefileparser.py#L826-L884
train
233,193
gem/oq-engine
openquake/commonlib/shapefileparser.py
SourceModelParser.write
def write(self, destination, source_model, name=None): """ Exports to NRML """ if os.path.exists(destination): os.remove(destination) self.destination = destination if name: source_model.name = name output_source_model = Node("sourceModel", {"name": name}) dic = groupby(source_model.sources, operator.itemgetter('tectonicRegion')) for i, (trt, srcs) in enumerate(dic.items(), 1): output_source_model.append( Node('sourceGroup', {'tectonicRegion': trt, 'name': 'group %d' % i}, nodes=srcs)) print("Exporting Source Model to %s" % self.destination) with open(self.destination, "wb") as f: nrml.write([output_source_model], f, "%s")
python
def write(self, destination, source_model, name=None): """ Exports to NRML """ if os.path.exists(destination): os.remove(destination) self.destination = destination if name: source_model.name = name output_source_model = Node("sourceModel", {"name": name}) dic = groupby(source_model.sources, operator.itemgetter('tectonicRegion')) for i, (trt, srcs) in enumerate(dic.items(), 1): output_source_model.append( Node('sourceGroup', {'tectonicRegion': trt, 'name': 'group %d' % i}, nodes=srcs)) print("Exporting Source Model to %s" % self.destination) with open(self.destination, "wb") as f: nrml.write([output_source_model], f, "%s")
[ "def", "write", "(", "self", ",", "destination", ",", "source_model", ",", "name", "=", "None", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "destination", ")", ":", "os", ".", "remove", "(", "destination", ")", "self", ".", "destination", "=", "destination", "if", "name", ":", "source_model", ".", "name", "=", "name", "output_source_model", "=", "Node", "(", "\"sourceModel\"", ",", "{", "\"name\"", ":", "name", "}", ")", "dic", "=", "groupby", "(", "source_model", ".", "sources", ",", "operator", ".", "itemgetter", "(", "'tectonicRegion'", ")", ")", "for", "i", ",", "(", "trt", ",", "srcs", ")", "in", "enumerate", "(", "dic", ".", "items", "(", ")", ",", "1", ")", ":", "output_source_model", ".", "append", "(", "Node", "(", "'sourceGroup'", ",", "{", "'tectonicRegion'", ":", "trt", ",", "'name'", ":", "'group %d'", "%", "i", "}", ",", "nodes", "=", "srcs", ")", ")", "print", "(", "\"Exporting Source Model to %s\"", "%", "self", ".", "destination", ")", "with", "open", "(", "self", ".", "destination", ",", "\"wb\"", ")", "as", "f", ":", "nrml", ".", "write", "(", "[", "output_source_model", "]", ",", "f", ",", "\"%s\"", ")" ]
Exports to NRML
[ "Exports", "to", "NRML" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/shapefileparser.py#L937-L956
train
233,194
gem/oq-engine
openquake/commonlib/shapefileparser.py
ShapefileParser.filter_params
def filter_params(self, src_mod): """ Remove params uneeded by source_model """ # point and area related params STRIKE_PARAMS[src_mod.num_np:] = [] DIP_PARAMS[src_mod.num_np:] = [] RAKE_PARAMS[src_mod.num_np:] = [] NPW_PARAMS[src_mod.num_np:] = [] HDEPTH_PARAMS[src_mod.num_hd:] = [] HDW_PARAMS[src_mod.num_hd:] = [] # planar rupture related params PLANES_STRIKES_PARAM[src_mod.num_p:] = [] PLANES_DIPS_PARAM[src_mod.num_p:] = [] # rate params RATE_PARAMS[src_mod.num_r:] = [] if src_mod.has_simple_fault_geometry is False: GEOMETRY_PARAMS.remove(('dip', 'dip', 'f')) if (src_mod.has_simple_fault_geometry is False and src_mod.has_complex_fault_geometry is False and src_mod.has_planar_geometry is False): BASE_PARAMS.remove(('rake', 'rake', 'f')) if (src_mod.has_simple_fault_geometry is False and src_mod.has_complex_fault_geometry is False and src_mod.has_area_source is False and src_mod.has_point_source is False): GEOMETRY_PARAMS[:] = [] if src_mod.has_mfd_incremental is False: MFD_PARAMS.remove(('binWidth', 'bin_width', 'f'))
python
def filter_params(self, src_mod): """ Remove params uneeded by source_model """ # point and area related params STRIKE_PARAMS[src_mod.num_np:] = [] DIP_PARAMS[src_mod.num_np:] = [] RAKE_PARAMS[src_mod.num_np:] = [] NPW_PARAMS[src_mod.num_np:] = [] HDEPTH_PARAMS[src_mod.num_hd:] = [] HDW_PARAMS[src_mod.num_hd:] = [] # planar rupture related params PLANES_STRIKES_PARAM[src_mod.num_p:] = [] PLANES_DIPS_PARAM[src_mod.num_p:] = [] # rate params RATE_PARAMS[src_mod.num_r:] = [] if src_mod.has_simple_fault_geometry is False: GEOMETRY_PARAMS.remove(('dip', 'dip', 'f')) if (src_mod.has_simple_fault_geometry is False and src_mod.has_complex_fault_geometry is False and src_mod.has_planar_geometry is False): BASE_PARAMS.remove(('rake', 'rake', 'f')) if (src_mod.has_simple_fault_geometry is False and src_mod.has_complex_fault_geometry is False and src_mod.has_area_source is False and src_mod.has_point_source is False): GEOMETRY_PARAMS[:] = [] if src_mod.has_mfd_incremental is False: MFD_PARAMS.remove(('binWidth', 'bin_width', 'f'))
[ "def", "filter_params", "(", "self", ",", "src_mod", ")", ":", "# point and area related params", "STRIKE_PARAMS", "[", "src_mod", ".", "num_np", ":", "]", "=", "[", "]", "DIP_PARAMS", "[", "src_mod", ".", "num_np", ":", "]", "=", "[", "]", "RAKE_PARAMS", "[", "src_mod", ".", "num_np", ":", "]", "=", "[", "]", "NPW_PARAMS", "[", "src_mod", ".", "num_np", ":", "]", "=", "[", "]", "HDEPTH_PARAMS", "[", "src_mod", ".", "num_hd", ":", "]", "=", "[", "]", "HDW_PARAMS", "[", "src_mod", ".", "num_hd", ":", "]", "=", "[", "]", "# planar rupture related params", "PLANES_STRIKES_PARAM", "[", "src_mod", ".", "num_p", ":", "]", "=", "[", "]", "PLANES_DIPS_PARAM", "[", "src_mod", ".", "num_p", ":", "]", "=", "[", "]", "# rate params", "RATE_PARAMS", "[", "src_mod", ".", "num_r", ":", "]", "=", "[", "]", "if", "src_mod", ".", "has_simple_fault_geometry", "is", "False", ":", "GEOMETRY_PARAMS", ".", "remove", "(", "(", "'dip'", ",", "'dip'", ",", "'f'", ")", ")", "if", "(", "src_mod", ".", "has_simple_fault_geometry", "is", "False", "and", "src_mod", ".", "has_complex_fault_geometry", "is", "False", "and", "src_mod", ".", "has_planar_geometry", "is", "False", ")", ":", "BASE_PARAMS", ".", "remove", "(", "(", "'rake'", ",", "'rake'", ",", "'f'", ")", ")", "if", "(", "src_mod", ".", "has_simple_fault_geometry", "is", "False", "and", "src_mod", ".", "has_complex_fault_geometry", "is", "False", "and", "src_mod", ".", "has_area_source", "is", "False", "and", "src_mod", ".", "has_point_source", "is", "False", ")", ":", "GEOMETRY_PARAMS", "[", ":", "]", "=", "[", "]", "if", "src_mod", ".", "has_mfd_incremental", "is", "False", ":", "MFD_PARAMS", ".", "remove", "(", "(", "'binWidth'", ",", "'bin_width'", ",", "'f'", ")", ")" ]
Remove params uneeded by source_model
[ "Remove", "params", "uneeded", "by", "source_model" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/shapefileparser.py#L960-L992
train
233,195
gem/oq-engine
openquake/baselib/node.py
tostring
def tostring(node, indent=4, nsmap=None): """ Convert a node into an XML string by using the StreamingXMLWriter. This is useful for testing purposes. :param node: a node object (typically an ElementTree object) :param indent: the indentation to use in the XML (default 4 spaces) """ out = io.BytesIO() writer = StreamingXMLWriter(out, indent, nsmap=nsmap) writer.serialize(node) return out.getvalue()
python
def tostring(node, indent=4, nsmap=None): """ Convert a node into an XML string by using the StreamingXMLWriter. This is useful for testing purposes. :param node: a node object (typically an ElementTree object) :param indent: the indentation to use in the XML (default 4 spaces) """ out = io.BytesIO() writer = StreamingXMLWriter(out, indent, nsmap=nsmap) writer.serialize(node) return out.getvalue()
[ "def", "tostring", "(", "node", ",", "indent", "=", "4", ",", "nsmap", "=", "None", ")", ":", "out", "=", "io", ".", "BytesIO", "(", ")", "writer", "=", "StreamingXMLWriter", "(", "out", ",", "indent", ",", "nsmap", "=", "nsmap", ")", "writer", ".", "serialize", "(", "node", ")", "return", "out", ".", "getvalue", "(", ")" ]
Convert a node into an XML string by using the StreamingXMLWriter. This is useful for testing purposes. :param node: a node object (typically an ElementTree object) :param indent: the indentation to use in the XML (default 4 spaces)
[ "Convert", "a", "node", "into", "an", "XML", "string", "by", "using", "the", "StreamingXMLWriter", ".", "This", "is", "useful", "for", "testing", "purposes", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L216-L227
train
233,196
gem/oq-engine
openquake/baselib/node.py
parse
def parse(source, remove_comments=True, **kw): """Thin wrapper around ElementTree.parse""" return ElementTree.parse(source, SourceLineParser(), **kw)
python
def parse(source, remove_comments=True, **kw): """Thin wrapper around ElementTree.parse""" return ElementTree.parse(source, SourceLineParser(), **kw)
[ "def", "parse", "(", "source", ",", "remove_comments", "=", "True", ",", "*", "*", "kw", ")", ":", "return", "ElementTree", ".", "parse", "(", "source", ",", "SourceLineParser", "(", ")", ",", "*", "*", "kw", ")" ]
Thin wrapper around ElementTree.parse
[ "Thin", "wrapper", "around", "ElementTree", ".", "parse" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L350-L352
train
233,197
gem/oq-engine
openquake/baselib/node.py
iterparse
def iterparse(source, events=('end',), remove_comments=True, **kw): """Thin wrapper around ElementTree.iterparse""" return ElementTree.iterparse(source, events, SourceLineParser(), **kw)
python
def iterparse(source, events=('end',), remove_comments=True, **kw): """Thin wrapper around ElementTree.iterparse""" return ElementTree.iterparse(source, events, SourceLineParser(), **kw)
[ "def", "iterparse", "(", "source", ",", "events", "=", "(", "'end'", ",", ")", ",", "remove_comments", "=", "True", ",", "*", "*", "kw", ")", ":", "return", "ElementTree", ".", "iterparse", "(", "source", ",", "events", ",", "SourceLineParser", "(", ")", ",", "*", "*", "kw", ")" ]
Thin wrapper around ElementTree.iterparse
[ "Thin", "wrapper", "around", "ElementTree", ".", "iterparse" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L355-L357
train
233,198
gem/oq-engine
openquake/baselib/node.py
_displayattrs
def _displayattrs(attrib, expandattrs): """ Helper function to display the attributes of a Node object in lexicographic order. :param attrib: dictionary with the attributes :param expandattrs: if True also displays the value of the attributes """ if not attrib: return '' if expandattrs: alist = ['%s=%r' % item for item in sorted(attrib.items())] else: alist = list(attrib) return '{%s}' % ', '.join(alist)
python
def _displayattrs(attrib, expandattrs): """ Helper function to display the attributes of a Node object in lexicographic order. :param attrib: dictionary with the attributes :param expandattrs: if True also displays the value of the attributes """ if not attrib: return '' if expandattrs: alist = ['%s=%r' % item for item in sorted(attrib.items())] else: alist = list(attrib) return '{%s}' % ', '.join(alist)
[ "def", "_displayattrs", "(", "attrib", ",", "expandattrs", ")", ":", "if", "not", "attrib", ":", "return", "''", "if", "expandattrs", ":", "alist", "=", "[", "'%s=%r'", "%", "item", "for", "item", "in", "sorted", "(", "attrib", ".", "items", "(", ")", ")", "]", "else", ":", "alist", "=", "list", "(", "attrib", ")", "return", "'{%s}'", "%", "', '", ".", "join", "(", "alist", ")" ]
Helper function to display the attributes of a Node object in lexicographic order. :param attrib: dictionary with the attributes :param expandattrs: if True also displays the value of the attributes
[ "Helper", "function", "to", "display", "the", "attributes", "of", "a", "Node", "object", "in", "lexicographic", "order", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L363-L377
train
233,199