repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
39
1.84M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
gem/oq-engine
openquake/hazardlib/gsim/tavakoli_pezeshk_2005.py
TavakoliPezeshk2005._compute_anelastic_attenuation_term
def _compute_anelastic_attenuation_term(self, C, rrup, mag): """ Compute magnitude-distance scaling term as defined in equation 21, page 2291 (Tavakoli and Pezeshk, 2005) """ r = (rrup**2. + (C['c5'] * np.exp(C['c6'] * mag + C['c7'] * (8....
python
def _compute_anelastic_attenuation_term(self, C, rrup, mag): r = (rrup**2. + (C['c5'] * np.exp(C['c6'] * mag + C['c7'] * (8.5 - mag)**2.5))**2.)**.5 f3 = ((C['c4'] + C['c13'] * mag) * np.log(r) + (C['c8'] + C['c12'] * mag) * r) ret...
[ "def", "_compute_anelastic_attenuation_term", "(", "self", ",", "C", ",", "rrup", ",", "mag", ")", ":", "r", "=", "(", "rrup", "**", "2.", "+", "(", "C", "[", "'c5'", "]", "*", "np", ".", "exp", "(", "C", "[", "'c6'", "]", "*", "mag", "+", "C",...
Compute magnitude-distance scaling term as defined in equation 21, page 2291 (Tavakoli and Pezeshk, 2005)
[ "Compute", "magnitude", "-", "distance", "scaling", "term", "as", "defined", "in", "equation", "21", "page", "2291", "(", "Tavakoli", "and", "Pezeshk", "2005", ")" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/tavakoli_pezeshk_2005.py#L157-L166
gem/oq-engine
openquake/hazardlib/geo/surface/complex_fault.py
edge_node
def edge_node(name, points): """ :param name: 'faultTopEdge', 'intermediateEdge' or 'faultBottomEdge' :param points: a list of Point objects :returns: a Node of kind faultTopEdge, intermediateEdge or faultBottomEdge """ line = [] for point in points: line.append(point.longitude) ...
python
def edge_node(name, points): line = [] for point in points: line.append(point.longitude) line.append(point.latitude) line.append(point.depth) pos = Node('gml:posList', {}, line) node = Node(name, nodes=[Node('gml:LineString', nodes=[pos])]) return node
[ "def", "edge_node", "(", "name", ",", "points", ")", ":", "line", "=", "[", "]", "for", "point", "in", "points", ":", "line", ".", "append", "(", "point", ".", "longitude", ")", "line", ".", "append", "(", "point", ".", "latitude", ")", "line", "."...
:param name: 'faultTopEdge', 'intermediateEdge' or 'faultBottomEdge' :param points: a list of Point objects :returns: a Node of kind faultTopEdge, intermediateEdge or faultBottomEdge
[ ":", "param", "name", ":", "faultTopEdge", "intermediateEdge", "or", "faultBottomEdge", ":", "param", "points", ":", "a", "list", "of", "Point", "objects", ":", "returns", ":", "a", "Node", "of", "kind", "faultTopEdge", "intermediateEdge", "or", "faultBottomEdge...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/complex_fault.py#L36-L49
gem/oq-engine
openquake/hazardlib/geo/surface/complex_fault.py
complex_fault_node
def complex_fault_node(edges): """ :param edges: a list of lists of points :returns: a Node of kind complexFaultGeometry """ node = Node('complexFaultGeometry') node.append(edge_node('faultTopEdge', edges[0])) for edge in edges[1:-1]: node.append(edge_node('intermediateEdge', edge)) ...
python
def complex_fault_node(edges): node = Node('complexFaultGeometry') node.append(edge_node('faultTopEdge', edges[0])) for edge in edges[1:-1]: node.append(edge_node('intermediateEdge', edge)) node.append(edge_node('faultBottomEdge', edges[-1])) return node
[ "def", "complex_fault_node", "(", "edges", ")", ":", "node", "=", "Node", "(", "'complexFaultGeometry'", ")", "node", ".", "append", "(", "edge_node", "(", "'faultTopEdge'", ",", "edges", "[", "0", "]", ")", ")", "for", "edge", "in", "edges", "[", "1", ...
:param edges: a list of lists of points :returns: a Node of kind complexFaultGeometry
[ ":", "param", "edges", ":", "a", "list", "of", "lists", "of", "points", ":", "returns", ":", "a", "Node", "of", "kind", "complexFaultGeometry" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/complex_fault.py#L52-L62
gem/oq-engine
openquake/hazardlib/geo/surface/complex_fault.py
ComplexFaultSurface.get_dip
def get_dip(self): """ Return the fault dip as the average dip over the mesh. The average dip is defined as the weighted mean inclination of all the mesh cells. See :meth:`openquake.hazardlib.geo.mesh.RectangularMesh.get_mean_inclination_and_azimuth` :returns: ...
python
def get_dip(self): if self.dip is None: mesh = self.mesh self.dip, self.strike = mesh.get_mean_inclination_and_azimuth() return self.dip
[ "def", "get_dip", "(", "self", ")", ":", "# uses the same approach as in simple fault surface", "if", "self", ".", "dip", "is", "None", ":", "mesh", "=", "self", ".", "mesh", "self", ".", "dip", ",", "self", ".", "strike", "=", "mesh", ".", "get_mean_inclina...
Return the fault dip as the average dip over the mesh. The average dip is defined as the weighted mean inclination of all the mesh cells. See :meth:`openquake.hazardlib.geo.mesh.RectangularMesh.get_mean_inclination_and_azimuth` :returns: The average dip, in decimal degrees.
[ "Return", "the", "fault", "dip", "as", "the", "average", "dip", "over", "the", "mesh", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/complex_fault.py#L96-L111
gem/oq-engine
openquake/hazardlib/geo/surface/complex_fault.py
ComplexFaultSurface.check_aki_richards_convention
def check_aki_richards_convention(cls, edges): """ Verify that surface (as defined by corner points) conforms with Aki and Richard convention (i.e. surface dips right of surface strike) This method doesn't have to be called by hands before creating the surface object, because it...
python
def check_aki_richards_convention(cls, edges): ul = edges[0].points[0] ur = edges[0].points[-1] bl = edges[-1].points[0] br = edges[-1].points[-1] ul, ur, bl, br = spherical_to_cartesian( [ul.long...
[ "def", "check_aki_richards_convention", "(", "cls", ",", "edges", ")", ":", "# 1) extract 4 corner points of surface mesh", "# 2) compute cross products between left and right edges and top edge", "# (these define vectors normal to the surface)", "# 3) compute dot products between cross produc...
Verify that surface (as defined by corner points) conforms with Aki and Richard convention (i.e. surface dips right of surface strike) This method doesn't have to be called by hands before creating the surface object, because it is called from :meth:`from_fault_data`.
[ "Verify", "that", "surface", "(", "as", "defined", "by", "corner", "points", ")", "conforms", "with", "Aki", "and", "Richard", "convention", "(", "i", ".", "e", ".", "surface", "dips", "right", "of", "surface", "strike", ")" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/complex_fault.py#L129-L179
gem/oq-engine
openquake/hazardlib/geo/surface/complex_fault.py
ComplexFaultSurface.check_surface_validity
def check_surface_validity(cls, edges): """ Check validity of the surface. Project edge points to vertical plane anchored to surface upper left edge and with strike equal to top edge strike. Check that resulting polygon is valid. This method doesn't have to be called by...
python
def check_surface_validity(cls, edges): full_boundary = [] left_boundary = [] right_boundary = [] for i in range(1, len(edges) - 1): left_boundary.append(edges[i].points[0]) right_boundary.append(edges[i].points[-1]) full_boundary.exten...
[ "def", "check_surface_validity", "(", "cls", ",", "edges", ")", ":", "# extract coordinates of surface boundary (as defined from edges)", "full_boundary", "=", "[", "]", "left_boundary", "=", "[", "]", "right_boundary", "=", "[", "]", "for", "i", "in", "range", "(",...
Check validity of the surface. Project edge points to vertical plane anchored to surface upper left edge and with strike equal to top edge strike. Check that resulting polygon is valid. This method doesn't have to be called by hands before creating the surface object, because i...
[ "Check", "validity", "of", "the", "surface", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/complex_fault.py#L182-L230
gem/oq-engine
openquake/hazardlib/geo/surface/complex_fault.py
ComplexFaultSurface.check_fault_data
def check_fault_data(cls, edges, mesh_spacing): """ Verify the fault data and raise ``ValueError`` if anything is wrong. This method doesn't have to be called by hands before creating the surface object, because it is called from :meth:`from_fault_data`. """ if not len(e...
python
def check_fault_data(cls, edges, mesh_spacing): if not len(edges) >= 2: raise ValueError("at least two edges are required") if not all(len(edge) >= 2 for edge in edges): raise ValueError("at least two points must be defined " "in each edge") ...
[ "def", "check_fault_data", "(", "cls", ",", "edges", ",", "mesh_spacing", ")", ":", "if", "not", "len", "(", "edges", ")", ">=", "2", ":", "raise", "ValueError", "(", "\"at least two edges are required\"", ")", "if", "not", "all", "(", "len", "(", "edge", ...
Verify the fault data and raise ``ValueError`` if anything is wrong. This method doesn't have to be called by hands before creating the surface object, because it is called from :meth:`from_fault_data`.
[ "Verify", "the", "fault", "data", "and", "raise", "ValueError", "if", "anything", "is", "wrong", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/complex_fault.py#L233-L249
gem/oq-engine
openquake/hazardlib/geo/surface/complex_fault.py
ComplexFaultSurface.from_fault_data
def from_fault_data(cls, edges, mesh_spacing): """ Create and return a fault surface using fault source data. :param edges: A list of at least two horizontal edges of the surface as instances of :class:`openquake.hazardlib.geo.line.Line`. The list should be i...
python
def from_fault_data(cls, edges, mesh_spacing): cls.check_fault_data(edges, mesh_spacing) surface_nodes = [complex_fault_node(edges)] mean_length = numpy.mean([edge.get_length() for edge in edges]) num_hor_points = int(round(mean_length / mesh_spacing)) + 1 if num_hor_poi...
[ "def", "from_fault_data", "(", "cls", ",", "edges", ",", "mesh_spacing", ")", ":", "cls", ".", "check_fault_data", "(", "edges", ",", "mesh_spacing", ")", "surface_nodes", "=", "[", "complex_fault_node", "(", "edges", ")", "]", "mean_length", "=", "numpy", "...
Create and return a fault surface using fault source data. :param edges: A list of at least two horizontal edges of the surface as instances of :class:`openquake.hazardlib.geo.line.Line`. The list should be in top-to-bottom order (the shallowest edge first). :param m...
[ "Create", "and", "return", "a", "fault", "surface", "using", "fault", "source", "data", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/complex_fault.py#L252-L299
gem/oq-engine
openquake/hazardlib/geo/surface/complex_fault.py
ComplexFaultSurface.surface_projection_from_fault_data
def surface_projection_from_fault_data(cls, edges): """ Get a surface projection of the complex fault surface. :param edges: A list of horizontal edges of the surface as instances of :class:`openquake.hazardlib.geo.line.Line`. :returns: Instance of :c...
python
def surface_projection_from_fault_data(cls, edges): lons = [] lats = [] for edge in edges: for point in edge: lons.append(point.longitude) lats.append(point.latitude) lons = numpy.array(lons, dtype=float) lats = numpy....
[ "def", "surface_projection_from_fault_data", "(", "cls", ",", "edges", ")", ":", "# collect lons and lats of all the vertices of all the edges", "lons", "=", "[", "]", "lats", "=", "[", "]", "for", "edge", "in", "edges", ":", "for", "point", "in", "edge", ":", "...
Get a surface projection of the complex fault surface. :param edges: A list of horizontal edges of the surface as instances of :class:`openquake.hazardlib.geo.line.Line`. :returns: Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon` describing t...
[ "Get", "a", "surface", "projection", "of", "the", "complex", "fault", "surface", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/complex_fault.py#L302-L323
gem/oq-engine
openquake/calculators/base.py
fix_ones
def fix_ones(pmap): """ Physically, an extremely small intensity measure level can have an extremely large probability of exceedence, however that probability cannot be exactly 1 unless the level is exactly 0. Numerically, the PoE can be 1 and this give issues when calculating the damage (there ...
python
def fix_ones(pmap): for sid in pmap: array = pmap[sid].array array[array == 1.] = .9999999999999999 return pmap
[ "def", "fix_ones", "(", "pmap", ")", ":", "for", "sid", "in", "pmap", ":", "array", "=", "pmap", "[", "sid", "]", ".", "array", "array", "[", "array", "==", "1.", "]", "=", ".9999999999999999", "return", "pmap" ]
Physically, an extremely small intensity measure level can have an extremely large probability of exceedence, however that probability cannot be exactly 1 unless the level is exactly 0. Numerically, the PoE can be 1 and this give issues when calculating the damage (there is a log(0) in :class:`openq...
[ "Physically", "an", "extremely", "small", "intensity", "measure", "level", "can", "have", "an", "extremely", "large", "probability", "of", "exceedence", "however", "that", "probability", "cannot", "be", "exactly", "1", "unless", "the", "level", "is", "exactly", ...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L65-L79
gem/oq-engine
openquake/calculators/base.py
build_weights
def build_weights(realizations, imt_dt): """ :returns: an array with the realization weights of shape (R, M) """ arr = numpy.zeros((len(realizations), len(imt_dt.names))) for m, imt in enumerate(imt_dt.names): arr[:, m] = [rlz.weight[imt] for rlz in realizations] return arr
python
def build_weights(realizations, imt_dt): arr = numpy.zeros((len(realizations), len(imt_dt.names))) for m, imt in enumerate(imt_dt.names): arr[:, m] = [rlz.weight[imt] for rlz in realizations] return arr
[ "def", "build_weights", "(", "realizations", ",", "imt_dt", ")", ":", "arr", "=", "numpy", ".", "zeros", "(", "(", "len", "(", "realizations", ")", ",", "len", "(", "imt_dt", ".", "names", ")", ")", ")", "for", "m", ",", "imt", "in", "enumerate", "...
:returns: an array with the realization weights of shape (R, M)
[ ":", "returns", ":", "an", "array", "with", "the", "realization", "weights", "of", "shape", "(", "R", "M", ")" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L82-L89
gem/oq-engine
openquake/calculators/base.py
set_array
def set_array(longarray, shortarray): """ :param longarray: a numpy array of floats of length L >= l :param shortarray: a numpy array of floats of length l Fill `longarray` with the values of `shortarray`, starting from the left. If `shortarry` is shorter than `longarray`, then the remaining elemen...
python
def set_array(longarray, shortarray): longarray[:len(shortarray)] = shortarray longarray[len(shortarray):] = numpy.nan
[ "def", "set_array", "(", "longarray", ",", "shortarray", ")", ":", "longarray", "[", ":", "len", "(", "shortarray", ")", "]", "=", "shortarray", "longarray", "[", "len", "(", "shortarray", ")", ":", "]", "=", "numpy", ".", "nan" ]
:param longarray: a numpy array of floats of length L >= l :param shortarray: a numpy array of floats of length l Fill `longarray` with the values of `shortarray`, starting from the left. If `shortarry` is shorter than `longarray`, then the remaining elements on the right are filled with `numpy.nan` va...
[ ":", "param", "longarray", ":", "a", "numpy", "array", "of", "floats", "of", "length", "L", ">", "=", "l", ":", "param", "shortarray", ":", "a", "numpy", "array", "of", "floats", "of", "length", "l" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L92-L102
gem/oq-engine
openquake/calculators/base.py
check_time_event
def check_time_event(oqparam, occupancy_periods): """ Check the `time_event` parameter in the datastore, by comparing with the periods found in the exposure. """ time_event = oqparam.time_event if time_event and time_event not in occupancy_periods: raise ValueError( 'time_eve...
python
def check_time_event(oqparam, occupancy_periods): time_event = oqparam.time_event if time_event and time_event not in occupancy_periods: raise ValueError( 'time_event is %s in %s, but the exposure contains %s' % (time_event, oqparam.inputs['job_ini'], ', '.join(...
[ "def", "check_time_event", "(", "oqparam", ",", "occupancy_periods", ")", ":", "time_event", "=", "oqparam", ".", "time_event", "if", "time_event", "and", "time_event", "not", "in", "occupancy_periods", ":", "raise", "ValueError", "(", "'time_event is %s in %s, but th...
Check the `time_event` parameter in the datastore, by comparing with the periods found in the exposure.
[ "Check", "the", "time_event", "parameter", "in", "the", "datastore", "by", "comparing", "with", "the", "periods", "found", "in", "the", "exposure", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L321-L331
gem/oq-engine
openquake/calculators/base.py
build_hmaps
def build_hmaps(hcurves_by_kind, slice_, imtls, poes, monitor): """ Build hazard maps from a slice of hazard curves. :returns: a pair ({kind: hmaps}, slice) """ dic = {} for kind, hcurves in hcurves_by_kind.items(): dic[kind] = calc.make_hmap_array(hcurves, imtls, poes, len(hcurves)) ...
python
def build_hmaps(hcurves_by_kind, slice_, imtls, poes, monitor): dic = {} for kind, hcurves in hcurves_by_kind.items(): dic[kind] = calc.make_hmap_array(hcurves, imtls, poes, len(hcurves)) return dic, slice_
[ "def", "build_hmaps", "(", "hcurves_by_kind", ",", "slice_", ",", "imtls", ",", "poes", ",", "monitor", ")", ":", "dic", "=", "{", "}", "for", "kind", ",", "hcurves", "in", "hcurves_by_kind", ".", "items", "(", ")", ":", "dic", "[", "kind", "]", "=",...
Build hazard maps from a slice of hazard curves. :returns: a pair ({kind: hmaps}, slice)
[ "Build", "hazard", "maps", "from", "a", "slice", "of", "hazard", "curves", ".", ":", "returns", ":", "a", "pair", "(", "{", "kind", ":", "hmaps", "}", "slice", ")" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L749-L757
gem/oq-engine
openquake/calculators/base.py
get_gmv_data
def get_gmv_data(sids, gmfs, events): """ Convert an array of shape (N, E, M) into an array of type gmv_data_dt """ N, E, M = gmfs.shape gmv_data_dt = numpy.dtype( [('rlzi', U16), ('sid', U32), ('eid', U64), ('gmv', (F32, (M,)))]) # NB: ordering of the loops: first site, then event l...
python
def get_gmv_data(sids, gmfs, events): N, E, M = gmfs.shape gmv_data_dt = numpy.dtype( [('rlzi', U16), ('sid', U32), ('eid', U64), ('gmv', (F32, (M,)))]) lst = [(event['rlz'], sids[s], ei, gmfs[s, ei]) for s in numpy.arange(N, dtype=U32) for ei, event in enumerate(even...
[ "def", "get_gmv_data", "(", "sids", ",", "gmfs", ",", "events", ")", ":", "N", ",", "E", ",", "M", "=", "gmfs", ".", "shape", "gmv_data_dt", "=", "numpy", ".", "dtype", "(", "[", "(", "'rlzi'", ",", "U16", ")", ",", "(", "'sid'", ",", "U32", ")...
Convert an array of shape (N, E, M) into an array of type gmv_data_dt
[ "Convert", "an", "array", "of", "shape", "(", "N", "E", "M", ")", "into", "an", "array", "of", "type", "gmv_data_dt" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L884-L895
gem/oq-engine
openquake/calculators/base.py
save_gmfs
def save_gmfs(calculator): """ :param calculator: a scenario_risk/damage or event_based_risk calculator :returns: a pair (eids, R) where R is the number of realizations """ dstore = calculator.datastore oq = calculator.oqparam logging.info('Reading gmfs from file') if oq.inputs['gmfs'].e...
python
def save_gmfs(calculator): dstore = calculator.datastore oq = calculator.oqparam logging.info('Reading gmfs from file') if oq.inputs['gmfs'].endswith('.csv'): eids = import_gmfs( dstore, oq.inputs['gmfs'], calculator.sitecol.complete.sids) else: eids, gmfs...
[ "def", "save_gmfs", "(", "calculator", ")", ":", "dstore", "=", "calculator", ".", "datastore", "oq", "=", "calculator", ".", "oqparam", "logging", ".", "info", "(", "'Reading gmfs from file'", ")", "if", "oq", ".", "inputs", "[", "'gmfs'", "]", ".", "ends...
:param calculator: a scenario_risk/damage or event_based_risk calculator :returns: a pair (eids, R) where R is the number of realizations
[ ":", "param", "calculator", ":", "a", "scenario_risk", "/", "damage", "or", "event_based_risk", "calculator", ":", "returns", ":", "a", "pair", "(", "eids", "R", ")", "where", "R", "is", "the", "number", "of", "realizations" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L898-L928
gem/oq-engine
openquake/calculators/base.py
save_gmf_data
def save_gmf_data(dstore, sitecol, gmfs, imts, events=()): """ :param dstore: a :class:`openquake.baselib.datastore.DataStore` instance :param sitecol: a :class:`openquake.hazardlib.site.SiteCollection` instance :param gmfs: an array of shape (N, E, M) :param imts: a list of IMT strings :param e...
python
def save_gmf_data(dstore, sitecol, gmfs, imts, events=()): if len(events) == 0: E = gmfs.shape[1] events = numpy.zeros(E, rupture.events_dt) events['eid'] = numpy.arange(E, dtype=U64) dstore['events'] = events offset = 0 gmfa = get_gmv_data(sitecol.sids, gmfs, events) ds...
[ "def", "save_gmf_data", "(", "dstore", ",", "sitecol", ",", "gmfs", ",", "imts", ",", "events", "=", "(", ")", ")", ":", "if", "len", "(", "events", ")", "==", "0", ":", "E", "=", "gmfs", ".", "shape", "[", "1", "]", "events", "=", "numpy", "."...
:param dstore: a :class:`openquake.baselib.datastore.DataStore` instance :param sitecol: a :class:`openquake.hazardlib.site.SiteCollection` instance :param gmfs: an array of shape (N, E, M) :param imts: a list of IMT strings :param events: E event IDs or the empty tuple
[ ":", "param", "dstore", ":", "a", ":", "class", ":", "openquake", ".", "baselib", ".", "datastore", ".", "DataStore", "instance", ":", "param", "sitecol", ":", "a", ":", "class", ":", "openquake", ".", "hazardlib", ".", "site", ".", "SiteCollection", "in...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L931-L956
gem/oq-engine
openquake/calculators/base.py
get_idxs
def get_idxs(data, eid2idx): """ Convert from event IDs to event indices. :param data: an array with a field eid :param eid2idx: a dictionary eid -> idx :returns: the array of event indices """ uniq, inv = numpy.unique(data['eid'], return_inverse=True) idxs = numpy.array([eid2idx[eid] f...
python
def get_idxs(data, eid2idx): uniq, inv = numpy.unique(data['eid'], return_inverse=True) idxs = numpy.array([eid2idx[eid] for eid in uniq])[inv] return idxs
[ "def", "get_idxs", "(", "data", ",", "eid2idx", ")", ":", "uniq", ",", "inv", "=", "numpy", ".", "unique", "(", "data", "[", "'eid'", "]", ",", "return_inverse", "=", "True", ")", "idxs", "=", "numpy", ".", "array", "(", "[", "eid2idx", "[", "eid",...
Convert from event IDs to event indices. :param data: an array with a field eid :param eid2idx: a dictionary eid -> idx :returns: the array of event indices
[ "Convert", "from", "event", "IDs", "to", "event", "indices", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L959-L969
gem/oq-engine
openquake/calculators/base.py
import_gmfs
def import_gmfs(dstore, fname, sids): """ Import in the datastore a ground motion field CSV file. :param dstore: the datastore :param fname: the CSV file :param sids: the site IDs (complete) :returns: event_ids, num_rlzs """ array = writers.read_composite_array(fname).array # has he...
python
def import_gmfs(dstore, fname, sids): array = writers.read_composite_array(fname).array imts = [name[4:] for name in array.dtype.names[3:]] n_imts = len(imts) gmf_data_dt = numpy.dtype( [('rlzi', U16), ('sid', U32), ('eid', U64), ('gmv', (F32, (n_imts,)))]) eids = numpy.unique...
[ "def", "import_gmfs", "(", "dstore", ",", "fname", ",", "sids", ")", ":", "array", "=", "writers", ".", "read_composite_array", "(", "fname", ")", ".", "array", "# has header rlzi, sid, eid, gmv_PGA, ...", "imts", "=", "[", "name", "[", "4", ":", "]", "for",...
Import in the datastore a ground motion field CSV file. :param dstore: the datastore :param fname: the CSV file :param sids: the site IDs (complete) :returns: event_ids, num_rlzs
[ "Import", "in", "the", "datastore", "a", "ground", "motion", "field", "CSV", "file", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L972-L1013
gem/oq-engine
openquake/calculators/base.py
BaseCalculator.monitor
def monitor(self, operation='', **kw): """ :returns: a new Monitor instance """ mon = self._monitor(operation, hdf5=self.datastore.hdf5) self._monitor.calc_id = mon.calc_id = self.datastore.calc_id vars(mon).update(kw) return mon
python
def monitor(self, operation='', **kw): mon = self._monitor(operation, hdf5=self.datastore.hdf5) self._monitor.calc_id = mon.calc_id = self.datastore.calc_id vars(mon).update(kw) return mon
[ "def", "monitor", "(", "self", ",", "operation", "=", "''", ",", "*", "*", "kw", ")", ":", "mon", "=", "self", ".", "_monitor", "(", "operation", ",", "hdf5", "=", "self", ".", "datastore", ".", "hdf5", ")", "self", ".", "_monitor", ".", "calc_id",...
:returns: a new Monitor instance
[ ":", "returns", ":", "a", "new", "Monitor", "instance" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L133-L140
gem/oq-engine
openquake/calculators/base.py
BaseCalculator.save_params
def save_params(self, **kw): """ Update the current calculation parameters and save engine_version """ if ('hazard_calculation_id' in kw and kw['hazard_calculation_id'] is None): del kw['hazard_calculation_id'] vars(self.oqparam).update(**kw) s...
python
def save_params(self, **kw): if ('hazard_calculation_id' in kw and kw['hazard_calculation_id'] is None): del kw['hazard_calculation_id'] vars(self.oqparam).update(**kw) self.datastore['oqparam'] = self.oqparam attrs = self.datastore['/'].attrs ...
[ "def", "save_params", "(", "self", ",", "*", "*", "kw", ")", ":", "if", "(", "'hazard_calculation_id'", "in", "kw", "and", "kw", "[", "'hazard_calculation_id'", "]", "is", "None", ")", ":", "del", "kw", "[", "'hazard_calculation_id'", "]", "vars", "(", "...
Update the current calculation parameters and save engine_version
[ "Update", "the", "current", "calculation", "parameters", "and", "save", "engine_version" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L142-L156
gem/oq-engine
openquake/calculators/base.py
BaseCalculator.check_precalc
def check_precalc(self, precalc_mode): """ Defensive programming against users providing an incorrect pre-calculation ID (with ``--hazard-calculation-id``). :param precalc_mode: calculation_mode of the previous calculation """ calc_mode = self.oqparam.calcula...
python
def check_precalc(self, precalc_mode): calc_mode = self.oqparam.calculation_mode ok_mode = self.accept_precalc if calc_mode != precalc_mode and precalc_mode not in ok_mode: raise InvalidCalculationID( 'In order to run a calculation of kind %r, ' ...
[ "def", "check_precalc", "(", "self", ",", "precalc_mode", ")", ":", "calc_mode", "=", "self", ".", "oqparam", ".", "calculation_mode", "ok_mode", "=", "self", ".", "accept_precalc", "if", "calc_mode", "!=", "precalc_mode", "and", "precalc_mode", "not", "in", "...
Defensive programming against users providing an incorrect pre-calculation ID (with ``--hazard-calculation-id``). :param precalc_mode: calculation_mode of the previous calculation
[ "Defensive", "programming", "against", "users", "providing", "an", "incorrect", "pre", "-", "calculation", "ID", "(", "with", "--", "hazard", "-", "calculation", "-", "id", ")", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L158-L173
gem/oq-engine
openquake/calculators/base.py
BaseCalculator.run
def run(self, pre_execute=True, concurrent_tasks=None, close=True, **kw): """ Run the calculation and return the exported outputs. """ with self._monitor: self._monitor.username = kw.get('username', '') self._monitor.hdf5 = self.datastore.hdf5 if concu...
python
def run(self, pre_execute=True, concurrent_tasks=None, close=True, **kw): with self._monitor: self._monitor.username = kw.get('username', '') self._monitor.hdf5 = self.datastore.hdf5 if concurrent_tasks is None: ct = self.oqparam.concurrent_tasks ...
[ "def", "run", "(", "self", ",", "pre_execute", "=", "True", ",", "concurrent_tasks", "=", "None", ",", "close", "=", "True", ",", "*", "*", "kw", ")", ":", "with", "self", ".", "_monitor", ":", "self", ".", "_monitor", ".", "username", "=", "kw", "...
Run the calculation and return the exported outputs.
[ "Run", "the", "calculation", "and", "return", "the", "exported", "outputs", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L175-L231
gem/oq-engine
openquake/calculators/base.py
BaseCalculator.export
def export(self, exports=None): """ Export all the outputs in the datastore in the given export formats. Individual outputs are not exported if there are multiple realizations. """ self.exported = getattr(self.precalc, 'exported', {}) if isinstance(exports, tuple): ...
python
def export(self, exports=None): self.exported = getattr(self.precalc, 'exported', {}) if isinstance(exports, tuple): fmts = exports elif exports: fmts = exports.split(',') elif isinstance(self.oqparam.exports, tuple): fmts = self.oqparam.exp...
[ "def", "export", "(", "self", ",", "exports", "=", "None", ")", ":", "self", ".", "exported", "=", "getattr", "(", "self", ".", "precalc", ",", "'exported'", ",", "{", "}", ")", "if", "isinstance", "(", "exports", ",", "tuple", ")", ":", "fmts", "=...
Export all the outputs in the datastore in the given export formats. Individual outputs are not exported if there are multiple realizations.
[ "Export", "all", "the", "outputs", "in", "the", "datastore", "in", "the", "given", "export", "formats", ".", "Individual", "outputs", "are", "not", "exported", "if", "there", "are", "multiple", "realizations", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L260-L289
gem/oq-engine
openquake/calculators/base.py
BaseCalculator.before_export
def before_export(self): """ Set the attributes nbytes """ # sanity check that eff_ruptures have been set, i.e. are not -1 try: csm_info = self.datastore['csm_info'] except KeyError: csm_info = self.datastore['csm_info'] = self.csm.info for...
python
def before_export(self): try: csm_info = self.datastore['csm_info'] except KeyError: csm_info = self.datastore['csm_info'] = self.csm.info for sm in csm_info.source_models: for sg in sm.src_groups: assert sg.eff_ruptures != -1...
[ "def", "before_export", "(", "self", ")", ":", "# sanity check that eff_ruptures have been set, i.e. are not -1", "try", ":", "csm_info", "=", "self", ".", "datastore", "[", "'csm_info'", "]", "except", "KeyError", ":", "csm_info", "=", "self", ".", "datastore", "["...
Set the attributes nbytes
[ "Set", "the", "attributes", "nbytes" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L303-L318
gem/oq-engine
openquake/calculators/base.py
HazardCalculator.block_splitter
def block_splitter(self, sources, weight=get_weight, key=lambda src: 1): """ :param sources: a list of sources :param weight: a weight function (default .weight) :param key: None or 'src_group_id' :returns: an iterator over blocks of sources """ ct = self.oqparam....
python
def block_splitter(self, sources, weight=get_weight, key=lambda src: 1): ct = self.oqparam.concurrent_tasks or 1 maxweight = self.csm.get_maxweight(weight, ct, source.MINWEIGHT) if not hasattr(self, 'logged'): if maxweight == source.MINWEIGHT: logging.info('U...
[ "def", "block_splitter", "(", "self", ",", "sources", ",", "weight", "=", "get_weight", ",", "key", "=", "lambda", "src", ":", "1", ")", ":", "ct", "=", "self", ".", "oqparam", ".", "concurrent_tasks", "or", "1", "maxweight", "=", "self", ".", "csm", ...
:param sources: a list of sources :param weight: a weight function (default .weight) :param key: None or 'src_group_id' :returns: an iterator over blocks of sources
[ ":", "param", "sources", ":", "a", "list", "of", "sources", ":", "param", "weight", ":", "a", "weight", "function", "(", "default", ".", "weight", ")", ":", "param", "key", ":", "None", "or", "src_group_id", ":", "returns", ":", "an", "iterator", "over...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L338-L353
gem/oq-engine
openquake/calculators/base.py
HazardCalculator.src_filter
def src_filter(self): """ :returns: a SourceFilter/UcerfFilter """ oq = self.oqparam self.hdf5cache = self.datastore.hdf5cache() sitecol = self.sitecol.complete if self.sitecol else None if 'ucerf' in oq.calculation_mode: return UcerfFilter(sitecol, oq...
python
def src_filter(self): oq = self.oqparam self.hdf5cache = self.datastore.hdf5cache() sitecol = self.sitecol.complete if self.sitecol else None if 'ucerf' in oq.calculation_mode: return UcerfFilter(sitecol, oq.maximum_distance, self.hdf5cache) return SourceFilt...
[ "def", "src_filter", "(", "self", ")", ":", "oq", "=", "self", ".", "oqparam", "self", ".", "hdf5cache", "=", "self", ".", "datastore", ".", "hdf5cache", "(", ")", "sitecol", "=", "self", ".", "sitecol", ".", "complete", "if", "self", ".", "sitecol", ...
:returns: a SourceFilter/UcerfFilter
[ ":", "returns", ":", "a", "SourceFilter", "/", "UcerfFilter" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L356-L365
gem/oq-engine
openquake/calculators/base.py
HazardCalculator.rtree_filter
def rtree_filter(self): """ :returns: an RtreeFilter """ return RtreeFilter(self.src_filter.sitecol, self.oqparam.maximum_distance, self.src_filter.filename)
python
def rtree_filter(self): return RtreeFilter(self.src_filter.sitecol, self.oqparam.maximum_distance, self.src_filter.filename)
[ "def", "rtree_filter", "(", "self", ")", ":", "return", "RtreeFilter", "(", "self", ".", "src_filter", ".", "sitecol", ",", "self", ".", "oqparam", ".", "maximum_distance", ",", "self", ".", "src_filter", ".", "filename", ")" ]
:returns: an RtreeFilter
[ ":", "returns", ":", "an", "RtreeFilter" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L368-L374
gem/oq-engine
openquake/calculators/base.py
HazardCalculator.N
def N(self): """ :returns: the total number of sites """ if hasattr(self, 'sitecol'): return len(self.sitecol.complete) if self.sitecol else None return len(self.datastore['sitecol/array'])
python
def N(self): if hasattr(self, 'sitecol'): return len(self.sitecol.complete) if self.sitecol else None return len(self.datastore['sitecol/array'])
[ "def", "N", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'sitecol'", ")", ":", "return", "len", "(", "self", ".", "sitecol", ".", "complete", ")", "if", "self", ".", "sitecol", "else", "None", "return", "len", "(", "self", ".", "datas...
:returns: the total number of sites
[ ":", "returns", ":", "the", "total", "number", "of", "sites" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L387-L393
gem/oq-engine
openquake/calculators/base.py
HazardCalculator.read_inputs
def read_inputs(self): """ Read risk data and sources if any """ oq = self.oqparam self._read_risk_data() self.check_overflow() # check if self.sitecol is too large if ('source_model_logic_tree' in oq.inputs and oq.hazard_calculation_id is None): ...
python
def read_inputs(self): oq = self.oqparam self._read_risk_data() self.check_overflow() if ('source_model_logic_tree' in oq.inputs and oq.hazard_calculation_id is None): self.csm = readinput.get_composite_source_model( oq, self.monitor...
[ "def", "read_inputs", "(", "self", ")", ":", "oq", "=", "self", ".", "oqparam", "self", ".", "_read_risk_data", "(", ")", "self", ".", "check_overflow", "(", ")", "# check if self.sitecol is too large", "if", "(", "'source_model_logic_tree'", "in", "oq", ".", ...
Read risk data and sources if any
[ "Read", "risk", "data", "and", "sources", "if", "any" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L406-L417
gem/oq-engine
openquake/calculators/base.py
HazardCalculator.pre_execute
def pre_execute(self): """ Check if there is a previous calculation ID. If yes, read the inputs by retrieving the previous calculation; if not, read the inputs directly. """ oq = self.oqparam if 'gmfs' in oq.inputs or 'multi_peril' in oq.inputs: # read...
python
def pre_execute(self): oq = self.oqparam if 'gmfs' in oq.inputs or 'multi_peril' in oq.inputs: assert not oq.hazard_calculation_id, ( 'You cannot use --hc together with gmfs_file') self.read_inputs() if 'gmfs' in oq.inputs: ...
[ "def", "pre_execute", "(", "self", ")", ":", "oq", "=", "self", ".", "oqparam", "if", "'gmfs'", "in", "oq", ".", "inputs", "or", "'multi_peril'", "in", "oq", ".", "inputs", ":", "# read hazard from files", "assert", "not", "oq", ".", "hazard_calculation_id",...
Check if there is a previous calculation ID. If yes, read the inputs by retrieving the previous calculation; if not, read the inputs directly.
[ "Check", "if", "there", "is", "a", "previous", "calculation", "ID", ".", "If", "yes", "read", "the", "inputs", "by", "retrieving", "the", "previous", "calculation", ";", "if", "not", "read", "the", "inputs", "directly", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L422-L496
gem/oq-engine
openquake/calculators/base.py
HazardCalculator.init
def init(self): """ To be overridden to initialize the datasets needed by the calculation """ oq = self.oqparam if not oq.risk_imtls: if self.datastore.parent: oq.risk_imtls = ( self.datastore.parent['oqparam'].risk_imtls) i...
python
def init(self): oq = self.oqparam if not oq.risk_imtls: if self.datastore.parent: oq.risk_imtls = ( self.datastore.parent['oqparam'].risk_imtls) if 'precalc' in vars(self): self.rlzs_assoc = self.precalc.rlzs_assoc elif...
[ "def", "init", "(", "self", ")", ":", "oq", "=", "self", ".", "oqparam", "if", "not", "oq", ".", "risk_imtls", ":", "if", "self", ".", "datastore", ".", "parent", ":", "oq", ".", "risk_imtls", "=", "(", "self", ".", "datastore", ".", "parent", "[",...
To be overridden to initialize the datasets needed by the calculation
[ "To", "be", "overridden", "to", "initialize", "the", "datasets", "needed", "by", "the", "calculation" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L498-L522
gem/oq-engine
openquake/calculators/base.py
HazardCalculator.R
def R(self): """ :returns: the number of realizations """ try: return self.csm.info.get_num_rlzs() except AttributeError: # no self.csm return self.datastore['csm_info'].get_num_rlzs()
python
def R(self): try: return self.csm.info.get_num_rlzs() except AttributeError: return self.datastore['csm_info'].get_num_rlzs()
[ "def", "R", "(", "self", ")", ":", "try", ":", "return", "self", ".", "csm", ".", "info", ".", "get_num_rlzs", "(", ")", "except", "AttributeError", ":", "# no self.csm", "return", "self", ".", "datastore", "[", "'csm_info'", "]", ".", "get_num_rlzs", "(...
:returns: the number of realizations
[ ":", "returns", ":", "the", "number", "of", "realizations" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L525-L532
gem/oq-engine
openquake/calculators/base.py
HazardCalculator.read_exposure
def read_exposure(self, haz_sitecol=None): # after load_risk_model """ Read the exposure, the riskmodel and update the attributes .sitecol, .assetcol """ with self.monitor('reading exposure', autoflush=True): self.sitecol, self.assetcol, discarded = ( ...
python
def read_exposure(self, haz_sitecol=None): with self.monitor('reading exposure', autoflush=True): self.sitecol, self.assetcol, discarded = ( readinput.get_sitecol_assetcol( self.oqparam, haz_sitecol, self.riskmodel.loss_types)) if len(discar...
[ "def", "read_exposure", "(", "self", ",", "haz_sitecol", "=", "None", ")", ":", "# after load_risk_model", "with", "self", ".", "monitor", "(", "'reading exposure'", ",", "autoflush", "=", "True", ")", ":", "self", ".", "sitecol", ",", "self", ".", "assetcol...
Read the exposure, the riskmodel and update the attributes .sitecol, .assetcol
[ "Read", "the", "exposure", "the", "riskmodel", "and", "update", "the", "attributes", ".", "sitecol", ".", "assetcol" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L534-L566
gem/oq-engine
openquake/calculators/base.py
HazardCalculator.load_riskmodel
def load_riskmodel(self): # to be called before read_exposure # NB: this is called even if there is no risk model """ Read the risk model and set the attribute .riskmodel. The riskmodel can be empty for hazard calculations. Save the loss ratios (if any) in the datastore. ...
python
def load_riskmodel(self): logging.info('Reading the risk model if present') self.riskmodel = readinput.get_risk_model(self.oqparam) if not self.riskmodel: parent = self.datastore.parent if 'risk_model' in parent: self.riskmodel =...
[ "def", "load_riskmodel", "(", "self", ")", ":", "# to be called before read_exposure", "# NB: this is called even if there is no risk model", "logging", ".", "info", "(", "'Reading the risk model if present'", ")", "self", ".", "riskmodel", "=", "readinput", ".", "get_risk_mo...
Read the risk model and set the attribute .riskmodel. The riskmodel can be empty for hazard calculations. Save the loss ratios (if any) in the datastore.
[ "Read", "the", "risk", "model", "and", "set", "the", "attribute", ".", "riskmodel", ".", "The", "riskmodel", "can", "be", "empty", "for", "hazard", "calculations", ".", "Save", "the", "loss", "ratios", "(", "if", "any", ")", "in", "the", "datastore", "."...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L568-L586
gem/oq-engine
openquake/calculators/base.py
HazardCalculator.save_riskmodel
def save_riskmodel(self): """ Save the risk models in the datastore """ self.datastore['risk_model'] = rm = self.riskmodel self.datastore['taxonomy_mapping'] = self.riskmodel.tmap attrs = self.datastore.getitem('risk_model').attrs attrs['min_iml'] = hdf5.array_of_...
python
def save_riskmodel(self): self.datastore['risk_model'] = rm = self.riskmodel self.datastore['taxonomy_mapping'] = self.riskmodel.tmap attrs = self.datastore.getitem('risk_model').attrs attrs['min_iml'] = hdf5.array_of_vstr(sorted(rm.min_iml.items())) self.datastore.set_n...
[ "def", "save_riskmodel", "(", "self", ")", ":", "self", ".", "datastore", "[", "'risk_model'", "]", "=", "rm", "=", "self", ".", "riskmodel", "self", ".", "datastore", "[", "'taxonomy_mapping'", "]", "=", "self", ".", "riskmodel", ".", "tmap", "attrs", "...
Save the risk models in the datastore
[ "Save", "the", "risk", "models", "in", "the", "datastore" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L588-L596
gem/oq-engine
openquake/calculators/base.py
HazardCalculator.store_rlz_info
def store_rlz_info(self, eff_ruptures=None): """ Save info about the composite source model inside the csm_info dataset """ if hasattr(self, 'csm'): # no scenario self.csm.info.update_eff_ruptures(eff_ruptures) self.rlzs_assoc = self.csm.info.get_rlzs_assoc( ...
python
def store_rlz_info(self, eff_ruptures=None): if hasattr(self, 'csm'): self.csm.info.update_eff_ruptures(eff_ruptures) self.rlzs_assoc = self.csm.info.get_rlzs_assoc( self.oqparam.sm_lt_path) if not self.rlzs_assoc: raise RuntimeError...
[ "def", "store_rlz_info", "(", "self", ",", "eff_ruptures", "=", "None", ")", ":", "if", "hasattr", "(", "self", ",", "'csm'", ")", ":", "# no scenario", "self", ".", "csm", ".", "info", ".", "update_eff_ruptures", "(", "eff_ruptures", ")", "self", ".", "...
Save info about the composite source model inside the csm_info dataset
[ "Save", "info", "about", "the", "composite", "source", "model", "inside", "the", "csm_info", "dataset" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L701-L730
gem/oq-engine
openquake/calculators/base.py
HazardCalculator.store_source_info
def store_source_info(self, calc_times): """ Save (weight, num_sites, calc_time) inside the source_info dataset """ if calc_times: source_info = self.datastore['source_info'] arr = numpy.zeros((len(source_info), 3), F32) ids, vals = zip(*sorted(calc_ti...
python
def store_source_info(self, calc_times): if calc_times: source_info = self.datastore['source_info'] arr = numpy.zeros((len(source_info), 3), F32) ids, vals = zip(*sorted(calc_times.items())) arr[numpy.array(ids)] = vals source_info['weight'] +...
[ "def", "store_source_info", "(", "self", ",", "calc_times", ")", ":", "if", "calc_times", ":", "source_info", "=", "self", ".", "datastore", "[", "'source_info'", "]", "arr", "=", "numpy", ".", "zeros", "(", "(", "len", "(", "source_info", ")", ",", "3",...
Save (weight, num_sites, calc_time) inside the source_info dataset
[ "Save", "(", "weight", "num_sites", "calc_time", ")", "inside", "the", "source_info", "dataset" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L732-L743
gem/oq-engine
openquake/calculators/base.py
RiskCalculator.read_shakemap
def read_shakemap(self, haz_sitecol, assetcol): """ Enabled only if there is a shakemap_id parameter in the job.ini. Download, unzip, parse USGS shakemap files and build a corresponding set of GMFs which are then filtered with the hazard site collection and stored in the datastor...
python
def read_shakemap(self, haz_sitecol, assetcol): oq = self.oqparam E = oq.number_of_ground_motion_fields oq.risk_imtls = oq.imtls or self.datastore.parent['oqparam'].imtls extra = self.riskmodel.get_extra_imts(oq.risk_imtls) if extra: logging.warning('There ar...
[ "def", "read_shakemap", "(", "self", ",", "haz_sitecol", ",", "assetcol", ")", ":", "oq", "=", "self", ".", "oqparam", "E", "=", "oq", ".", "number_of_ground_motion_fields", "oq", ".", "risk_imtls", "=", "oq", ".", "imtls", "or", "self", ".", "datastore", ...
Enabled only if there is a shakemap_id parameter in the job.ini. Download, unzip, parse USGS shakemap files and build a corresponding set of GMFs which are then filtered with the hazard site collection and stored in the datastore.
[ "Enabled", "only", "if", "there", "is", "a", "shakemap_id", "parameter", "in", "the", "job", ".", "ini", ".", "Download", "unzip", "parse", "USGS", "shakemap", "files", "and", "build", "a", "corresponding", "set", "of", "GMFs", "which", "are", "then", "fil...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L766-L800
gem/oq-engine
openquake/calculators/base.py
RiskCalculator.build_riskinputs
def build_riskinputs(self, kind): """ :param kind: kind of hazard getter, can be 'poe' or 'gmf' :returns: a list of RiskInputs objects, sorted by IMT. """ logging.info('Building risk inputs from %d realization(s)', self.R) imtls = self.oqparam.imtl...
python
def build_riskinputs(self, kind): logging.info('Building risk inputs from %d realization(s)', self.R) imtls = self.oqparam.imtls if not set(self.oqparam.risk_imtls) & set(imtls): rsk = ', '.join(self.oqparam.risk_imtls) haz = ', '.join(imtls) raise Va...
[ "def", "build_riskinputs", "(", "self", ",", "kind", ")", ":", "logging", ".", "info", "(", "'Building risk inputs from %d realization(s)'", ",", "self", ".", "R", ")", "imtls", "=", "self", ".", "oqparam", ".", "imtls", "if", "not", "set", "(", "self", "....
:param kind: kind of hazard getter, can be 'poe' or 'gmf' :returns: a list of RiskInputs objects, sorted by IMT.
[ ":", "param", "kind", ":", "kind", "of", "hazard", "getter", "can", "be", "poe", "or", "gmf", ":", "returns", ":", "a", "list", "of", "RiskInputs", "objects", "sorted", "by", "IMT", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L802-L821
gem/oq-engine
openquake/calculators/base.py
RiskCalculator.get_getter
def get_getter(self, kind, sid): """ :param kind: 'poe' or 'gmf' :param sid: a site ID :returns: a PmapGetter or GmfDataGetter """ hdf5cache = getattr(self, 'hdf5cache', None) if hdf5cache: dstore = hdf5cache elif (self.oqparam.hazard_calculati...
python
def get_getter(self, kind, sid): hdf5cache = getattr(self, 'hdf5cache', None) if hdf5cache: dstore = hdf5cache elif (self.oqparam.hazard_calculation_id and 'gmf_data' not in self.datastore): self.datastore.parent.close() d...
[ "def", "get_getter", "(", "self", ",", "kind", ",", "sid", ")", ":", "hdf5cache", "=", "getattr", "(", "self", ",", "'hdf5cache'", ",", "None", ")", "if", "hdf5cache", ":", "dstore", "=", "hdf5cache", "elif", "(", "self", ".", "oqparam", ".", "hazard_c...
:param kind: 'poe' or 'gmf' :param sid: a site ID :returns: a PmapGetter or GmfDataGetter
[ ":", "param", "kind", ":", "poe", "or", "gmf", ":", "param", "sid", ":", "a", "site", "ID", ":", "returns", ":", "a", "PmapGetter", "or", "GmfDataGetter" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L823-L845
gem/oq-engine
openquake/calculators/base.py
RiskCalculator.execute
def execute(self): """ Parallelize on the riskinputs and returns a dictionary of results. Require a `.core_task` to be defined with signature (riskinputs, riskmodel, rlzs_assoc, monitor). """ if not hasattr(self, 'riskinputs'): # in the reportwriter return ...
python
def execute(self): if not hasattr(self, 'riskinputs'): return res = Starmap.apply( self.core_task.__func__, (self.riskinputs, self.riskmodel, self.param, self.monitor()), concurrent_tasks=self.oqparam.concurrent_tasks or 1, weight=ge...
[ "def", "execute", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'riskinputs'", ")", ":", "# in the reportwriter", "return", "res", "=", "Starmap", ".", "apply", "(", "self", ".", "core_task", ".", "__func__", ",", "(", "self", ".", ...
Parallelize on the riskinputs and returns a dictionary of results. Require a `.core_task` to be defined with signature (riskinputs, riskmodel, rlzs_assoc, monitor).
[ "Parallelize", "on", "the", "riskinputs", "and", "returns", "a", "dictionary", "of", "results", ".", "Require", "a", ".", "core_task", "to", "be", "defined", "with", "signature", "(", "riskinputs", "riskmodel", "rlzs_assoc", "monitor", ")", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L864-L878
gem/oq-engine
openquake/baselib/zeromq.py
bind
def bind(end_point, socket_type): """ Bind to a zmq URL; raise a proper error if the URL is invalid; return a zmq socket. """ sock = context.socket(socket_type) try: sock.bind(end_point) except zmq.error.ZMQError as exc: sock.close() raise exc.__class__('%s: %s' % (ex...
python
def bind(end_point, socket_type): sock = context.socket(socket_type) try: sock.bind(end_point) except zmq.error.ZMQError as exc: sock.close() raise exc.__class__('%s: %s' % (exc, end_point)) return sock
[ "def", "bind", "(", "end_point", ",", "socket_type", ")", ":", "sock", "=", "context", ".", "socket", "(", "socket_type", ")", "try", ":", "sock", ".", "bind", "(", "end_point", ")", "except", "zmq", ".", "error", ".", "ZMQError", "as", "exc", ":", "...
Bind to a zmq URL; raise a proper error if the URL is invalid; return a zmq socket.
[ "Bind", "to", "a", "zmq", "URL", ";", "raise", "a", "proper", "error", "if", "the", "URL", "is", "invalid", ";", "return", "a", "zmq", "socket", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/zeromq.py#L30-L41
gem/oq-engine
openquake/baselib/zeromq.py
Socket.send
def send(self, obj): """ Send an object to the remote server; block and return the reply if the socket type is REQ. :param obj: the Python object to send """ self.zsocket.send_pyobj(obj) self.num_sent += 1 if self.socket_type == zmq.REQ: ...
python
def send(self, obj): self.zsocket.send_pyobj(obj) self.num_sent += 1 if self.socket_type == zmq.REQ: return self.zsocket.recv_pyobj()
[ "def", "send", "(", "self", ",", "obj", ")", ":", "self", ".", "zsocket", ".", "send_pyobj", "(", "obj", ")", "self", ".", "num_sent", "+=", "1", "if", "self", ".", "socket_type", "==", "zmq", ".", "REQ", ":", "return", "self", ".", "zsocket", ".",...
Send an object to the remote server; block and return the reply if the socket type is REQ. :param obj: the Python object to send
[ "Send", "an", "object", "to", "the", "remote", "server", ";", "block", "and", "return", "the", "reply", "if", "the", "socket", "type", "is", "REQ", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/zeromq.py#L139-L150
gem/oq-engine
openquake/hazardlib/geo/utils.py
angular_distance
def angular_distance(km, lat, lat2=None): """ Return the angular distance of two points at the given latitude. >>> '%.3f' % angular_distance(100, lat=40) '1.174' >>> '%.3f' % angular_distance(100, lat=80) '5.179' """ if lat2 is not None: # use the largest latitude to compute the...
python
def angular_distance(km, lat, lat2=None): if lat2 is not None: lat = max(abs(lat), abs(lat2)) return km * KM_TO_DEGREES / math.cos(lat * DEGREES_TO_RAD)
[ "def", "angular_distance", "(", "km", ",", "lat", ",", "lat2", "=", "None", ")", ":", "if", "lat2", "is", "not", "None", ":", "# use the largest latitude to compute the angular distance", "lat", "=", "max", "(", "abs", "(", "lat", ")", ",", "abs", "(", "la...
Return the angular distance of two points at the given latitude. >>> '%.3f' % angular_distance(100, lat=40) '1.174' >>> '%.3f' % angular_distance(100, lat=80) '5.179'
[ "Return", "the", "angular", "distance", "of", "two", "points", "at", "the", "given", "latitude", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L45-L57
gem/oq-engine
openquake/hazardlib/geo/utils.py
assoc
def assoc(objects, sitecol, assoc_dist, mode, asset_refs=()): """ Associate geographic objects to a site collection. :param objects: something with .lons, .lats or ['lon'] ['lat'], or a list of lists of objects with a .location attribute (i.e. assets_by_site) :param assoc_dist: ...
python
def assoc(objects, sitecol, assoc_dist, mode, asset_refs=()): if isinstance(objects, numpy.ndarray) or hasattr(objects, 'lons'): return _GeographicObjects(objects).assoc(sitecol, assoc_dist, mode) else: return _GeographicObjects(sitecol).assoc2( objects, assoc_dist, m...
[ "def", "assoc", "(", "objects", ",", "sitecol", ",", "assoc_dist", ",", "mode", ",", "asset_refs", "=", "(", ")", ")", ":", "if", "isinstance", "(", "objects", ",", "numpy", ".", "ndarray", ")", "or", "hasattr", "(", "objects", ",", "'lons'", ")", ":...
Associate geographic objects to a site collection. :param objects: something with .lons, .lats or ['lon'] ['lat'], or a list of lists of objects with a .location attribute (i.e. assets_by_site) :param assoc_dist: the maximum distance for association :param mode: if 'strict' ...
[ "Associate", "geographic", "objects", "to", "a", "site", "collection", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L177-L196
gem/oq-engine
openquake/hazardlib/geo/utils.py
clean_points
def clean_points(points): """ Given a list of :class:`~openquake.hazardlib.geo.point.Point` objects, return a new list with adjacent duplicate points removed. """ if not points: return points result = [points[0]] for point in points: if point != result[-1]: resul...
python
def clean_points(points): if not points: return points result = [points[0]] for point in points: if point != result[-1]: result.append(point) return result
[ "def", "clean_points", "(", "points", ")", ":", "if", "not", "points", ":", "return", "points", "result", "=", "[", "points", "[", "0", "]", "]", "for", "point", "in", "points", ":", "if", "point", "!=", "result", "[", "-", "1", "]", ":", "result",...
Given a list of :class:`~openquake.hazardlib.geo.point.Point` objects, return a new list with adjacent duplicate points removed.
[ "Given", "a", "list", "of", ":", "class", ":", "~openquake", ".", "hazardlib", ".", "geo", ".", "point", ".", "Point", "objects", "return", "a", "new", "list", "with", "adjacent", "duplicate", "points", "removed", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L199-L211
gem/oq-engine
openquake/hazardlib/geo/utils.py
line_intersects_itself
def line_intersects_itself(lons, lats, closed_shape=False): """ Return ``True`` if line of points intersects itself. Line with the last point repeating the first one considered intersecting itself. The line is defined by lists (or numpy arrays) of points' longitudes and latitudes (depth is not ...
python
def line_intersects_itself(lons, lats, closed_shape=False): assert len(lons) == len(lats) if len(lons) <= 3: return False west, east, north, south = get_spherical_bounding_box(lons, lats) proj = OrthographicProjection(west, east, north, south) xx, yy = proj(lons, la...
[ "def", "line_intersects_itself", "(", "lons", ",", "lats", ",", "closed_shape", "=", "False", ")", ":", "assert", "len", "(", "lons", ")", "==", "len", "(", "lats", ")", "if", "len", "(", "lons", ")", "<=", "3", ":", "# line can not intersect itself unless...
Return ``True`` if line of points intersects itself. Line with the last point repeating the first one considered intersecting itself. The line is defined by lists (or numpy arrays) of points' longitudes and latitudes (depth is not taken into account). :param closed_shape: If ``True`` the l...
[ "Return", "True", "if", "line", "of", "points", "intersects", "itself", ".", "Line", "with", "the", "last", "point", "repeating", "the", "first", "one", "considered", "intersecting", "itself", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L214-L250
gem/oq-engine
openquake/hazardlib/geo/utils.py
get_bounding_box
def get_bounding_box(obj, maxdist): """ Return the dilated bounding box of a geometric object. :param obj: an object with method .get_bounding_box, or with an attribute .polygon or a list of locations :param maxdist: maximum distance in km """ if hasattr(obj, 'get_bounding_box')...
python
def get_bounding_box(obj, maxdist): if hasattr(obj, 'get_bounding_box'): return obj.get_bounding_box(maxdist) elif hasattr(obj, 'polygon'): bbox = obj.polygon.get_bbox() else: if isinstance(obj, list): lons = numpy.array([loc.longitude for loc in obj]) ...
[ "def", "get_bounding_box", "(", "obj", ",", "maxdist", ")", ":", "if", "hasattr", "(", "obj", ",", "'get_bounding_box'", ")", ":", "return", "obj", ".", "get_bounding_box", "(", "maxdist", ")", "elif", "hasattr", "(", "obj", ",", "'polygon'", ")", ":", "...
Return the dilated bounding box of a geometric object. :param obj: an object with method .get_bounding_box, or with an attribute .polygon or a list of locations :param maxdist: maximum distance in km
[ "Return", "the", "dilated", "bounding", "box", "of", "a", "geometric", "object", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L267-L292
gem/oq-engine
openquake/hazardlib/geo/utils.py
get_spherical_bounding_box
def get_spherical_bounding_box(lons, lats): """ Given a collection of points find and return the bounding box, as a pair of longitudes and a pair of latitudes. Parameters define longitudes and latitudes of a point collection respectively in a form of lists or numpy arrays. :return: A t...
python
def get_spherical_bounding_box(lons, lats): north, south = numpy.max(lats), numpy.min(lats) west, east = numpy.min(lons), numpy.max(lons) assert (-180 <= west <= 180) and (-180 <= east <= 180), (west, east) if get_longitudinal_extent(west, east) < 0: if hasattr(lo...
[ "def", "get_spherical_bounding_box", "(", "lons", ",", "lats", ")", ":", "north", ",", "south", "=", "numpy", ".", "max", "(", "lats", ")", ",", "numpy", ".", "min", "(", "lats", ")", "west", ",", "east", "=", "numpy", ".", "min", "(", "lons", ")",...
Given a collection of points find and return the bounding box, as a pair of longitudes and a pair of latitudes. Parameters define longitudes and latitudes of a point collection respectively in a form of lists or numpy arrays. :return: A tuple of four items. These items represent western, easte...
[ "Given", "a", "collection", "of", "points", "find", "and", "return", "the", "bounding", "box", "as", "a", "pair", "of", "longitudes", "and", "a", "pair", "of", "latitudes", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L295-L329
gem/oq-engine
openquake/hazardlib/geo/utils.py
get_middle_point
def get_middle_point(lon1, lat1, lon2, lat2): """ Given two points return the point exactly in the middle lying on the same great circle arc. Parameters are point coordinates in degrees. :returns: Tuple of longitude and latitude of the point in the middle. """ if lon1 == lon2 and l...
python
def get_middle_point(lon1, lat1, lon2, lat2): if lon1 == lon2 and lat1 == lat2: return lon1, lat1 dist = geodetic.geodetic_distance(lon1, lat1, lon2, lat2) azimuth = geodetic.azimuth(lon1, lat1, lon2, lat2) return geodetic.point_at(lon1, lat1, azimuth, dist / 2.0)
[ "def", "get_middle_point", "(", "lon1", ",", "lat1", ",", "lon2", ",", "lat2", ")", ":", "if", "lon1", "==", "lon2", "and", "lat1", "==", "lat2", ":", "return", "lon1", ",", "lat1", "dist", "=", "geodetic", ".", "geodetic_distance", "(", "lon1", ",", ...
Given two points return the point exactly in the middle lying on the same great circle arc. Parameters are point coordinates in degrees. :returns: Tuple of longitude and latitude of the point in the middle.
[ "Given", "two", "points", "return", "the", "point", "exactly", "in", "the", "middle", "lying", "on", "the", "same", "great", "circle", "arc", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L428-L442
gem/oq-engine
openquake/hazardlib/geo/utils.py
cartesian_to_spherical
def cartesian_to_spherical(vectors): """ Return the spherical coordinates for coordinates in Cartesian space. This function does an opposite to :func:`spherical_to_cartesian`. :param vectors: Array of 3d vectors in Cartesian space of shape (..., 3) :returns: Tuple of three arrays o...
python
def cartesian_to_spherical(vectors): rr = numpy.sqrt(numpy.sum(vectors * vectors, axis=-1)) xx, yy, zz = vectors.T lats = numpy.degrees(numpy.arcsin((zz / rr).clip(-1., 1.))) lons = numpy.degrees(numpy.arctan2(yy, xx)) depths = EARTH_RADIUS - rr return lons.T, lats.T, depths
[ "def", "cartesian_to_spherical", "(", "vectors", ")", ":", "rr", "=", "numpy", ".", "sqrt", "(", "numpy", ".", "sum", "(", "vectors", "*", "vectors", ",", "axis", "=", "-", "1", ")", ")", "xx", ",", "yy", ",", "zz", "=", "vectors", ".", "T", "lat...
Return the spherical coordinates for coordinates in Cartesian space. This function does an opposite to :func:`spherical_to_cartesian`. :param vectors: Array of 3d vectors in Cartesian space of shape (..., 3) :returns: Tuple of three arrays of the same shape as ``vectors`` representing ...
[ "Return", "the", "spherical", "coordinates", "for", "coordinates", "in", "Cartesian", "space", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L445-L463
gem/oq-engine
openquake/hazardlib/geo/utils.py
triangle_area
def triangle_area(e1, e2, e3): """ Get the area of triangle formed by three vectors. Parameters are three three-dimensional numpy arrays representing vectors of triangle's edges in Cartesian space. :returns: Float number, the area of the triangle in squared units of coordinates, or...
python
def triangle_area(e1, e2, e3): e1_length = numpy.sqrt(numpy.sum(e1 * e1, axis=-1)) e2_length = numpy.sqrt(numpy.sum(e2 * e2, axis=-1)) e3_length = numpy.sqrt(numpy.sum(e3 * e3, axis=-1)) s = (e1_length + e2_length + e3_length) / 2.0 return numpy.sqrt(s * (s - e1_length) * (s - e2...
[ "def", "triangle_area", "(", "e1", ",", "e2", ",", "e3", ")", ":", "# calculating edges length", "e1_length", "=", "numpy", ".", "sqrt", "(", "numpy", ".", "sum", "(", "e1", "*", "e1", ",", "axis", "=", "-", "1", ")", ")", "e2_length", "=", "numpy", ...
Get the area of triangle formed by three vectors. Parameters are three three-dimensional numpy arrays representing vectors of triangle's edges in Cartesian space. :returns: Float number, the area of the triangle in squared units of coordinates, or numpy array of shape of edges with one dim...
[ "Get", "the", "area", "of", "triangle", "formed", "by", "three", "vectors", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L466-L486
gem/oq-engine
openquake/hazardlib/geo/utils.py
normalized
def normalized(vector): """ Get unit vector for a given one. :param vector: Numpy vector as coordinates in Cartesian space, or an array of such. :returns: Numpy array of the same shape and structure where all vectors are normalized. That is, each coordinate component is divided ...
python
def normalized(vector): length = numpy.sum(vector * vector, axis=-1) length = numpy.sqrt(length.reshape(length.shape + (1, ))) return vector / length
[ "def", "normalized", "(", "vector", ")", ":", "length", "=", "numpy", ".", "sum", "(", "vector", "*", "vector", ",", "axis", "=", "-", "1", ")", "length", "=", "numpy", ".", "sqrt", "(", "length", ".", "reshape", "(", "length", ".", "shape", "+", ...
Get unit vector for a given one. :param vector: Numpy vector as coordinates in Cartesian space, or an array of such. :returns: Numpy array of the same shape and structure where all vectors are normalized. That is, each coordinate component is divided by its vector's length.
[ "Get", "unit", "vector", "for", "a", "given", "one", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L489-L502
gem/oq-engine
openquake/hazardlib/geo/utils.py
point_to_polygon_distance
def point_to_polygon_distance(polygon, pxx, pyy): """ Calculate the distance to polygon for each point of the collection on the 2d Cartesian plane. :param polygon: Shapely "Polygon" geometry object. :param pxx: List or numpy array of abscissae values of points to calculate t...
python
def point_to_polygon_distance(polygon, pxx, pyy): pxx = numpy.array(pxx) pyy = numpy.array(pyy) assert pxx.shape == pyy.shape if pxx.ndim == 0: pxx = pxx.reshape((1, )) pyy = pyy.reshape((1, )) result = numpy.array([ polygon.distance(shapely.geometry.Point(pxx.item(i), p...
[ "def", "point_to_polygon_distance", "(", "polygon", ",", "pxx", ",", "pyy", ")", ":", "pxx", "=", "numpy", ".", "array", "(", "pxx", ")", "pyy", "=", "numpy", ".", "array", "(", "pyy", ")", "assert", "pxx", ".", "shape", "==", "pyy", ".", "shape", ...
Calculate the distance to polygon for each point of the collection on the 2d Cartesian plane. :param polygon: Shapely "Polygon" geometry object. :param pxx: List or numpy array of abscissae values of points to calculate the distance from. :param pyy: Same structure as ``...
[ "Calculate", "the", "distance", "to", "polygon", "for", "each", "point", "of", "the", "collection", "on", "the", "2d", "Cartesian", "plane", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L505-L531
gem/oq-engine
openquake/hazardlib/geo/utils.py
cross_idl
def cross_idl(lon1, lon2, *lons): """ Return True if two longitude values define line crossing international date line. >>> cross_idl(-45, 45) False >>> cross_idl(-180, -179) False >>> cross_idl(180, 179) False >>> cross_idl(45, -45) False >>> cross_idl(0, 0) False ...
python
def cross_idl(lon1, lon2, *lons): lons = (lon1, lon2) + lons l1, l2 = min(lons), max(lons) return l1 * l2 < 0 and abs(l1 - l2) > 180
[ "def", "cross_idl", "(", "lon1", ",", "lon2", ",", "*", "lons", ")", ":", "lons", "=", "(", "lon1", ",", "lon2", ")", "+", "lons", "l1", ",", "l2", "=", "min", "(", "lons", ")", ",", "max", "(", "lons", ")", "# a line crosses the international date l...
Return True if two longitude values define line crossing international date line. >>> cross_idl(-45, 45) False >>> cross_idl(-180, -179) False >>> cross_idl(180, 179) False >>> cross_idl(45, -45) False >>> cross_idl(0, 0) False >>> cross_idl(-170, 170) True >>> c...
[ "Return", "True", "if", "two", "longitude", "values", "define", "line", "crossing", "international", "date", "line", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L548-L574
gem/oq-engine
openquake/hazardlib/geo/utils.py
normalize_lons
def normalize_lons(l1, l2): """ An international date line safe way of returning a range of longitudes. >>> normalize_lons(20, 30) # no IDL within the range [(20, 30)] >>> normalize_lons(-17, +17) # no IDL within the range [(-17, 17)] >>> normalize_lons(-178, +179) [(-180, -178), (179...
python
def normalize_lons(l1, l2): if l1 > l2: l1, l2 = l2, l1 delta = l2 - l1 if l1 < 0 and l2 > 0 and delta > 180: return [(-180, l1), (l2, 180)] elif l1 > 0 and l2 > 180 and delta < 180: return [(l1, 180), (-180, l2 - 360)] elif l1 < -180 and l2 < 0 and delta < 180: ...
[ "def", "normalize_lons", "(", "l1", ",", "l2", ")", ":", "if", "l1", ">", "l2", ":", "# exchange lons", "l1", ",", "l2", "=", "l2", ",", "l1", "delta", "=", "l2", "-", "l1", "if", "l1", "<", "0", "and", "l2", ">", "0", "and", "delta", ">", "1...
An international date line safe way of returning a range of longitudes. >>> normalize_lons(20, 30) # no IDL within the range [(20, 30)] >>> normalize_lons(-17, +17) # no IDL within the range [(-17, 17)] >>> normalize_lons(-178, +179) [(-180, -178), (179, 180)] >>> normalize_lons(178, -179...
[ "An", "international", "date", "line", "safe", "way", "of", "returning", "a", "range", "of", "longitudes", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L577-L603
gem/oq-engine
openquake/hazardlib/geo/utils.py
within
def within(bbox, lonlat_index): """ :param bbox: a bounding box in lon, lat :param lonlat_index: an rtree index in lon, lat :returns: array of indices within the bounding box """ lon1, lat1, lon2, lat2 = bbox set_ = set() for l1, l2 in normalize_lons(lon1, lon2): box = (l1, lat1,...
python
def within(bbox, lonlat_index): lon1, lat1, lon2, lat2 = bbox set_ = set() for l1, l2 in normalize_lons(lon1, lon2): box = (l1, lat1, l2, lat2) set_ |= set(lonlat_index.intersection(box)) return numpy.array(sorted(set_), numpy.uint32)
[ "def", "within", "(", "bbox", ",", "lonlat_index", ")", ":", "lon1", ",", "lat1", ",", "lon2", ",", "lat2", "=", "bbox", "set_", "=", "set", "(", ")", "for", "l1", ",", "l2", "in", "normalize_lons", "(", "lon1", ",", "lon2", ")", ":", "box", "=",...
:param bbox: a bounding box in lon, lat :param lonlat_index: an rtree index in lon, lat :returns: array of indices within the bounding box
[ ":", "param", "bbox", ":", "a", "bounding", "box", "in", "lon", "lat", ":", "param", "lonlat_index", ":", "an", "rtree", "index", "in", "lon", "lat", ":", "returns", ":", "array", "of", "indices", "within", "the", "bounding", "box" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L606-L617
gem/oq-engine
openquake/hazardlib/geo/utils.py
plane_fit
def plane_fit(points): """ This fits an n-dimensional plane to a set of points. See http://stackoverflow.com/questions/12299540/plane-fitting-to-4-or-more-xyz-points :parameter points: An instance of :class:~numpy.ndarray. The number of columns must be equal to three. :return: ...
python
def plane_fit(points): points = numpy.transpose(points) points = numpy.reshape(points, (numpy.shape(points)[0], -1)) assert points.shape[0] < points.shape[1], points.shape ctr = points.mean(axis=1) x = points - ctr[:, None] M = numpy.dot(x, x.T) return ctr, numpy.linalg.svd(M)[0][:, -1]
[ "def", "plane_fit", "(", "points", ")", ":", "points", "=", "numpy", ".", "transpose", "(", "points", ")", "points", "=", "numpy", ".", "reshape", "(", "points", ",", "(", "numpy", ".", "shape", "(", "points", ")", "[", "0", "]", ",", "-", "1", "...
This fits an n-dimensional plane to a set of points. See http://stackoverflow.com/questions/12299540/plane-fitting-to-4-or-more-xyz-points :parameter points: An instance of :class:~numpy.ndarray. The number of columns must be equal to three. :return: A point on the plane and the no...
[ "This", "fits", "an", "n", "-", "dimensional", "plane", "to", "a", "set", "of", "points", ".", "See", "http", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "12299540", "/", "plane", "-", "fitting", "-", "to", "-", "4", "-", "or", "...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L620-L637
gem/oq-engine
openquake/hazardlib/geo/utils.py
_GeographicObjects.get_closest
def get_closest(self, lon, lat, depth=0): """ Get the closest object to the given longitude and latitude and its distance. :param lon: longitude in degrees :param lat: latitude in degrees :param depth: depth in km (default 0) :returns: (object, distance) ...
python
def get_closest(self, lon, lat, depth=0): xyz = spherical_to_cartesian(lon, lat, depth) min_dist, idx = self.kdtree.query(xyz) return self.objects[idx], min_dist
[ "def", "get_closest", "(", "self", ",", "lon", ",", "lat", ",", "depth", "=", "0", ")", ":", "xyz", "=", "spherical_to_cartesian", "(", "lon", ",", "lat", ",", "depth", ")", "min_dist", ",", "idx", "=", "self", ".", "kdtree", ".", "query", "(", "xy...
Get the closest object to the given longitude and latitude and its distance. :param lon: longitude in degrees :param lat: latitude in degrees :param depth: depth in km (default 0) :returns: (object, distance)
[ "Get", "the", "closest", "object", "to", "the", "given", "longitude", "and", "latitude", "and", "its", "distance", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L85-L97
gem/oq-engine
openquake/hazardlib/geo/utils.py
_GeographicObjects.assoc
def assoc(self, sitecol, assoc_dist, mode): """ :param sitecol: a (filtered) site collection :param assoc_dist: the maximum distance for association :param mode: 'strict', 'warn' or 'filter' :returns: filtered site collection, filtered objects, discarded """ asser...
python
def assoc(self, sitecol, assoc_dist, mode): assert mode in 'strict warn filter', mode dic = {} discarded = [] for sid, lon, lat in zip(sitecol.sids, sitecol.lons, sitecol.lats): obj, distance = self.get_closest(lon, lat) if assoc_dist is None: ...
[ "def", "assoc", "(", "self", ",", "sitecol", ",", "assoc_dist", ",", "mode", ")", ":", "assert", "mode", "in", "'strict warn filter'", ",", "mode", "dic", "=", "{", "}", "discarded", "=", "[", "]", "for", "sid", ",", "lon", ",", "lat", "in", "zip", ...
:param sitecol: a (filtered) site collection :param assoc_dist: the maximum distance for association :param mode: 'strict', 'warn' or 'filter' :returns: filtered site collection, filtered objects, discarded
[ ":", "param", "sitecol", ":", "a", "(", "filtered", ")", "site", "collection", ":", "param", "assoc_dist", ":", "the", "maximum", "distance", "for", "association", ":", "param", "mode", ":", "strict", "warn", "or", "filter", ":", "returns", ":", "filtered"...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L99-L132
gem/oq-engine
openquake/hazardlib/geo/utils.py
_GeographicObjects.assoc2
def assoc2(self, assets_by_site, assoc_dist, mode, asset_refs): """ Associated a list of assets by site to the site collection used to instantiate GeographicObjects. :param assets_by_sites: a list of lists of assets :param assoc_dist: the maximum distance for association ...
python
def assoc2(self, assets_by_site, assoc_dist, mode, asset_refs): assert mode in 'strict filter', mode self.objects.filtered asset_dt = numpy.dtype( [('asset_ref', vstr), ('lon', F32), ('lat', F32)]) assets_by_sid = collections.defaultdict(list) discarded = [...
[ "def", "assoc2", "(", "self", ",", "assets_by_site", ",", "assoc_dist", ",", "mode", ",", "asset_refs", ")", ":", "assert", "mode", "in", "'strict filter'", ",", "mode", "self", ".", "objects", ".", "filtered", "# self.objects must be a SiteCollection", "asset_dt"...
Associated a list of assets by site to the site collection used to instantiate GeographicObjects. :param assets_by_sites: a list of lists of assets :param assoc_dist: the maximum distance for association :param mode: 'strict', 'warn' or 'filter' :param asset_ref: ID of the asset...
[ "Associated", "a", "list", "of", "assets", "by", "site", "to", "the", "site", "collection", "used", "to", "instantiate", "GeographicObjects", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L134-L174
gem/oq-engine
openquake/risklib/read_nrml.py
get_vulnerability_functions_04
def get_vulnerability_functions_04(node, fname): """ :param node: a vulnerabilityModel node :param fname: path to the vulnerability file :returns: a dictionary imt, vf_id -> vulnerability function """ logging.warning('Please upgrade %s to NRML 0.5', fname) # NB: the I...
python
def get_vulnerability_functions_04(node, fname): logging.warning('Please upgrade %s to NRML 0.5', fname) imts = set() vf_ids = set() vmodel = scientific.VulnerabilityModel(**node.attrib) for vset in node: imt_str = vset.IML['IMT'] imls = ~vset.IML imts.add...
[ "def", "get_vulnerability_functions_04", "(", "node", ",", "fname", ")", ":", "logging", ".", "warning", "(", "'Please upgrade %s to NRML 0.5'", ",", "fname", ")", "# NB: the IMTs can be duplicated and with different levels, each", "# vulnerability function in a set will get its ow...
:param node: a vulnerabilityModel node :param fname: path to the vulnerability file :returns: a dictionary imt, vf_id -> vulnerability function
[ ":", "param", "node", ":", "a", "vulnerabilityModel", "node", ":", "param", "fname", ":", "path", "to", "the", "vulnerability", "file", ":", "returns", ":", "a", "dictionary", "imt", "vf_id", "-", ">", "vulnerability", "function" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/read_nrml.py#L34-L78
gem/oq-engine
openquake/risklib/read_nrml.py
get_vulnerability_functions_05
def get_vulnerability_functions_05(node, fname): """ :param node: a vulnerabilityModel node :param fname: path of the vulnerability filter :returns: a dictionary imt, vf_id -> vulnerability function """ # NB: the IMTs can be duplicated and with different levels, each ...
python
def get_vulnerability_functions_05(node, fname): vf_ids = set() vmodel = scientific.VulnerabilityModel(**node.attrib) for vfun in node.getnodes('vulnerabilityFunction'): with context(fname, vfun): imt = vfun.imls['imt'] imls = numpy.array(~vfun.imls) ...
[ "def", "get_vulnerability_functions_05", "(", "node", ",", "fname", ")", ":", "# NB: the IMTs can be duplicated and with different levels, each", "# vulnerability function in a set will get its own levels", "vf_ids", "=", "set", "(", ")", "vmodel", "=", "scientific", ".", "Vuln...
:param node: a vulnerabilityModel node :param fname: path of the vulnerability filter :returns: a dictionary imt, vf_id -> vulnerability function
[ ":", "param", "node", ":", "a", "vulnerabilityModel", "node", ":", "param", "fname", ":", "path", "of", "the", "vulnerability", "filter", ":", "returns", ":", "a", "dictionary", "imt", "vf_id", "-", ">", "vulnerability", "function" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/read_nrml.py#L82-L146
gem/oq-engine
openquake/risklib/read_nrml.py
ffconvert
def ffconvert(fname, limit_states, ff, min_iml=1E-10): """ Convert a fragility function into a numpy array plus a bunch of attributes. :param fname: path to the fragility model file :param limit_states: expected limit states :param ff: fragility function node :returns: a pair (array, dictio...
python
def ffconvert(fname, limit_states, ff, min_iml=1E-10): with context(fname, ff): ffs = ff[1:] imls = ff.imls nodamage = imls.attrib.get('noDamageLimit') if nodamage == 0: logging.warning('Found a noDamageLimit=0 in %s, line %s, ' 'using %g instead...
[ "def", "ffconvert", "(", "fname", ",", "limit_states", ",", "ff", ",", "min_iml", "=", "1E-10", ")", ":", "with", "context", "(", "fname", ",", "ff", ")", ":", "ffs", "=", "ff", "[", "1", ":", "]", "imls", "=", "ff", ".", "imls", "nodamage", "=",...
Convert a fragility function into a numpy array plus a bunch of attributes. :param fname: path to the fragility model file :param limit_states: expected limit states :param ff: fragility function node :returns: a pair (array, dictionary)
[ "Convert", "a", "fragility", "function", "into", "a", "numpy", "array", "plus", "a", "bunch", "of", "attributes", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/read_nrml.py#L152-L217
gem/oq-engine
openquake/risklib/read_nrml.py
get_fragility_model
def get_fragility_model(node, fname): """ :param node: a vulnerabilityModel node :param fname: path to the vulnerability file :returns: a dictionary imt, ff_id -> fragility function list """ with context(fname, node): fid = node['id'] asset_category = node...
python
def get_fragility_model(node, fname): with context(fname, node): fid = node['id'] asset_category = node['assetCategory'] loss_type = node['lossCategory'] description = ~node.description limit_states = ~node.limitStates ffs = node[2:] fmodel = scientific.Fragi...
[ "def", "get_fragility_model", "(", "node", ",", "fname", ")", ":", "with", "context", "(", "fname", ",", "node", ")", ":", "fid", "=", "node", "[", "'id'", "]", "asset_category", "=", "node", "[", "'assetCategory'", "]", "loss_type", "=", "node", "[", ...
:param node: a vulnerabilityModel node :param fname: path to the vulnerability file :returns: a dictionary imt, ff_id -> fragility function list
[ ":", "param", "node", ":", "a", "vulnerabilityModel", "node", ":", "param", "fname", ":", "path", "to", "the", "vulnerability", "file", ":", "returns", ":", "a", "dictionary", "imt", "ff_id", "-", ">", "fragility", "function", "list" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/read_nrml.py#L221-L244
gem/oq-engine
openquake/risklib/read_nrml.py
convert_fragility_model_04
def convert_fragility_model_04(node, fname, fmcounter=itertools.count(1)): """ :param node: an :class:`openquake.commonib.node.Node` in NRML 0.4 :param fname: path of the fragility file :returns: an :class:`openquake.commonib.node.Node` in NRML 0.5 """ convert_type = {"lo...
python
def convert_fragility_model_04(node, fname, fmcounter=itertools.count(1)): convert_type = {"lognormal": "logncdf"} new = Node('fragilityModel', dict(assetCategory='building', lossCategory='structural', id='fm_%d_converted_from_NRML_04' % ...
[ "def", "convert_fragility_model_04", "(", "node", ",", "fname", ",", "fmcounter", "=", "itertools", ".", "count", "(", "1", ")", ")", ":", "convert_type", "=", "{", "\"lognormal\"", ":", "\"logncdf\"", "}", "new", "=", "Node", "(", "'fragilityModel'", ",", ...
:param node: an :class:`openquake.commonib.node.Node` in NRML 0.4 :param fname: path of the fragility file :returns: an :class:`openquake.commonib.node.Node` in NRML 0.5
[ ":", "param", "node", ":", "an", ":", "class", ":", "openquake", ".", "commonib", ".", "node", ".", "Node", "in", "NRML", "0", ".", "4", ":", "param", "fname", ":", "path", "of", "the", "fragility", "file", ":", "returns", ":", "an", ":", "class", ...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/read_nrml.py#L282-L338
gem/oq-engine
openquake/risklib/read_nrml.py
get_fragility_model_04
def get_fragility_model_04(fmodel, fname): """ :param fmodel: a fragilityModel node :param fname: path of the fragility file :returns: an :class:`openquake.risklib.scientific.FragilityModel` instance """ logging.warning('Please upgrade %s to NRML 0.5', fname) node05 =...
python
def get_fragility_model_04(fmodel, fname): logging.warning('Please upgrade %s to NRML 0.5', fname) node05 = convert_fragility_model_04(fmodel, fname) node05.limitStates.text = node05.limitStates.text.split() return get_fragility_model(node05, fname)
[ "def", "get_fragility_model_04", "(", "fmodel", ",", "fname", ")", ":", "logging", ".", "warning", "(", "'Please upgrade %s to NRML 0.5'", ",", "fname", ")", "node05", "=", "convert_fragility_model_04", "(", "fmodel", ",", "fname", ")", "node05", ".", "limitStates...
:param fmodel: a fragilityModel node :param fname: path of the fragility file :returns: an :class:`openquake.risklib.scientific.FragilityModel` instance
[ ":", "param", "fmodel", ":", "a", "fragilityModel", "node", ":", "param", "fname", ":", "path", "of", "the", "fragility", "file", ":", "returns", ":", "an", ":", "class", ":", "openquake", ".", "risklib", ".", "scientific", ".", "FragilityModel", "instance...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/read_nrml.py#L342-L354
gem/oq-engine
openquake/risklib/read_nrml.py
taxonomy
def taxonomy(value): """ Any ASCII character goes into a taxonomy, except spaces. """ try: value.encode('ascii') except UnicodeEncodeError: raise ValueError('tag %r is not ASCII' % value) if re.search(r'\s', value): raise ValueError('The taxonomy %r contains whitespace ch...
python
def taxonomy(value): try: value.encode('ascii') except UnicodeEncodeError: raise ValueError('tag %r is not ASCII' % value) if re.search(r'\s', value): raise ValueError('The taxonomy %r contains whitespace chars' % value) return value
[ "def", "taxonomy", "(", "value", ")", ":", "try", ":", "value", ".", "encode", "(", "'ascii'", ")", "except", "UnicodeEncodeError", ":", "raise", "ValueError", "(", "'tag %r is not ASCII'", "%", "value", ")", "if", "re", ".", "search", "(", "r'\\s'", ",", ...
Any ASCII character goes into a taxonomy, except spaces.
[ "Any", "ASCII", "character", "goes", "into", "a", "taxonomy", "except", "spaces", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/read_nrml.py#L371-L381
gem/oq-engine
openquake/risklib/read_nrml.py
update_validators
def update_validators(): """ Call this to updade the global nrml.validators """ validators.update({ 'fragilityFunction.id': valid.utf8, # taxonomy 'vulnerabilityFunction.id': valid.utf8, # taxonomy 'consequenceFunction.id': valid.utf8, # taxonomy 'asset.id': valid.asse...
python
def update_validators(): validators.update({ 'fragilityFunction.id': valid.utf8, 'vulnerabilityFunction.id': valid.utf8, 'consequenceFunction.id': valid.utf8, 'asset.id': valid.asset_id, 'costType.name': valid.cost_type, 'costType.type': valid.cost_type_typ...
[ "def", "update_validators", "(", ")", ":", "validators", ".", "update", "(", "{", "'fragilityFunction.id'", ":", "valid", ".", "utf8", ",", "# taxonomy", "'vulnerabilityFunction.id'", ":", "valid", ".", "utf8", ",", "# taxonomy", "'consequenceFunction.id'", ":", "...
Call this to updade the global nrml.validators
[ "Call", "this", "to", "updade", "the", "global", "nrml", ".", "validators" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/read_nrml.py#L384-L437
gem/oq-engine
openquake/calculators/extract.py
get_info
def get_info(dstore): """ :returns: {'stats': dic, 'loss_types': dic, 'num_rlzs': R} """ oq = dstore['oqparam'] stats = {stat: s for s, stat in enumerate(oq.hazard_stats())} loss_types = {lt: l for l, lt in enumerate(oq.loss_dt().names)} imt = {imt: i for i, imt in enumerate(oq.imtls)} n...
python
def get_info(dstore): oq = dstore['oqparam'] stats = {stat: s for s, stat in enumerate(oq.hazard_stats())} loss_types = {lt: l for l, lt in enumerate(oq.loss_dt().names)} imt = {imt: i for i, imt in enumerate(oq.imtls)} num_rlzs = dstore['csm_info'].get_num_rlzs() return dict(stats=stats, n...
[ "def", "get_info", "(", "dstore", ")", ":", "oq", "=", "dstore", "[", "'oqparam'", "]", "stats", "=", "{", "stat", ":", "s", "for", "s", ",", "stat", "in", "enumerate", "(", "oq", ".", "hazard_stats", "(", ")", ")", "}", "loss_types", "=", "{", "...
:returns: {'stats': dic, 'loss_types': dic, 'num_rlzs': R}
[ ":", "returns", ":", "{", "stats", ":", "dic", "loss_types", ":", "dic", "num_rlzs", ":", "R", "}" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L56-L67
gem/oq-engine
openquake/calculators/extract.py
parse
def parse(query_string, info={}): """ :returns: a normalized query_dict as in the following examples: >>> parse('kind=stats', {'stats': {'mean': 0, 'max': 1}}) {'kind': ['mean', 'max'], 'k': [0, 1], 'rlzs': False} >>> parse('kind=rlzs', {'stats': {}, 'num_rlzs': 3}) {'kind': ['rlz-000', 'rlz-00...
python
def parse(query_string, info={}): qdic = parse_qs(query_string) loss_types = info.get('loss_types', []) for key, val in qdic.items(): if key == 'loss_type': qdic[key] = [loss_types[k] for k in val] else: qdic[key] = [lit_eval(v) for v in val] if info: ...
[ "def", "parse", "(", "query_string", ",", "info", "=", "{", "}", ")", ":", "qdic", "=", "parse_qs", "(", "query_string", ")", "loss_types", "=", "info", ".", "get", "(", "'loss_types'", ",", "[", "]", ")", "for", "key", ",", "val", "in", "qdic", "....
:returns: a normalized query_dict as in the following examples: >>> parse('kind=stats', {'stats': {'mean': 0, 'max': 1}}) {'kind': ['mean', 'max'], 'k': [0, 1], 'rlzs': False} >>> parse('kind=rlzs', {'stats': {}, 'num_rlzs': 3}) {'kind': ['rlz-000', 'rlz-001', 'rlz-002'], 'k': [0, 1, 2], 'rlzs': True} ...
[ ":", "returns", ":", "a", "normalized", "query_dict", "as", "in", "the", "following", "examples", ":" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L93-L115
gem/oq-engine
openquake/calculators/extract.py
barray
def barray(iterlines): """ Array of bytes """ lst = [line.encode('utf-8') for line in iterlines] arr = numpy.array(lst) return arr
python
def barray(iterlines): lst = [line.encode('utf-8') for line in iterlines] arr = numpy.array(lst) return arr
[ "def", "barray", "(", "iterlines", ")", ":", "lst", "=", "[", "line", ".", "encode", "(", "'utf-8'", ")", "for", "line", "in", "iterlines", "]", "arr", "=", "numpy", ".", "array", "(", "lst", ")", "return", "arr" ]
Array of bytes
[ "Array", "of", "bytes" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L130-L136
gem/oq-engine
openquake/calculators/extract.py
extract_
def extract_(dstore, dspath): """ Extracts an HDF5 path object from the datastore, for instance extract(dstore, 'sitecol'). """ obj = dstore[dspath] if isinstance(obj, Dataset): return ArrayWrapper(obj.value, obj.attrs) elif isinstance(obj, Group): return ArrayWrapper(numpy.a...
python
def extract_(dstore, dspath): obj = dstore[dspath] if isinstance(obj, Dataset): return ArrayWrapper(obj.value, obj.attrs) elif isinstance(obj, Group): return ArrayWrapper(numpy.array(list(obj)), obj.attrs) else: return obj
[ "def", "extract_", "(", "dstore", ",", "dspath", ")", ":", "obj", "=", "dstore", "[", "dspath", "]", "if", "isinstance", "(", "obj", ",", "Dataset", ")", ":", "return", "ArrayWrapper", "(", "obj", ".", "value", ",", "obj", ".", "attrs", ")", "elif", ...
Extracts an HDF5 path object from the datastore, for instance extract(dstore, 'sitecol').
[ "Extracts", "an", "HDF5", "path", "object", "from", "the", "datastore", "for", "instance", "extract", "(", "dstore", "sitecol", ")", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L139-L150
gem/oq-engine
openquake/calculators/extract.py
extract_realizations
def extract_realizations(dstore, dummy): """ Extract an array of realizations. Use it as /extract/realizations """ rlzs = dstore['csm_info'].rlzs dt = [('ordinal', U32), ('weight', F32), ('gsims', '<S64')] arr = numpy.zeros(len(rlzs), dt) arr['ordinal'] = rlzs['ordinal'] arr['weight'] = ...
python
def extract_realizations(dstore, dummy): rlzs = dstore['csm_info'].rlzs dt = [('ordinal', U32), ('weight', F32), ('gsims', '<S64')] arr = numpy.zeros(len(rlzs), dt) arr['ordinal'] = rlzs['ordinal'] arr['weight'] = rlzs['weight'] arr['gsims'] = rlzs['branch_path'] return arr
[ "def", "extract_realizations", "(", "dstore", ",", "dummy", ")", ":", "rlzs", "=", "dstore", "[", "'csm_info'", "]", ".", "rlzs", "dt", "=", "[", "(", "'ordinal'", ",", "U32", ")", ",", "(", "'weight'", ",", "F32", ")", ",", "(", "'gsims'", ",", "'...
Extract an array of realizations. Use it as /extract/realizations
[ "Extract", "an", "array", "of", "realizations", ".", "Use", "it", "as", "/", "extract", "/", "realizations" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L188-L198
gem/oq-engine
openquake/calculators/extract.py
extract_exposure_metadata
def extract_exposure_metadata(dstore, what): """ Extract the loss categories and the tags of the exposure. Use it as /extract/exposure_metadata """ dic = {} dic1, dic2 = dstore['assetcol/tagcol'].__toh5__() dic.update(dic1) dic.update(dic2) if 'asset_risk' in dstore: dic['mul...
python
def extract_exposure_metadata(dstore, what): dic = {} dic1, dic2 = dstore['assetcol/tagcol'].__toh5__() dic.update(dic1) dic.update(dic2) if 'asset_risk' in dstore: dic['multi_risk'] = sorted( set(dstore['asset_risk'].dtype.names) - set(dstore['assetcol/array'].d...
[ "def", "extract_exposure_metadata", "(", "dstore", ",", "what", ")", ":", "dic", "=", "{", "}", "dic1", ",", "dic2", "=", "dstore", "[", "'assetcol/tagcol'", "]", ".", "__toh5__", "(", ")", "dic", ".", "update", "(", "dic1", ")", "dic", ".", "update", ...
Extract the loss categories and the tags of the exposure. Use it as /extract/exposure_metadata
[ "Extract", "the", "loss", "categories", "and", "the", "tags", "of", "the", "exposure", ".", "Use", "it", "as", "/", "extract", "/", "exposure_metadata" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L202-L218
gem/oq-engine
openquake/calculators/extract.py
extract_assets
def extract_assets(dstore, what): """ Extract an array of assets, optionally filtered by tag. Use it as /extract/assets?taxonomy=RC&taxonomy=MSBC&occupancy=RES """ qdict = parse(what) dic = {} dic1, dic2 = dstore['assetcol/tagcol'].__toh5__() dic.update(dic1) dic.update(dic2) arr...
python
def extract_assets(dstore, what): qdict = parse(what) dic = {} dic1, dic2 = dstore['assetcol/tagcol'].__toh5__() dic.update(dic1) dic.update(dic2) arr = dstore['assetcol/array'].value for tag, vals in qdict.items(): cond = numpy.zeros(len(arr), bool) for val in vals: ...
[ "def", "extract_assets", "(", "dstore", ",", "what", ")", ":", "qdict", "=", "parse", "(", "what", ")", "dic", "=", "{", "}", "dic1", ",", "dic2", "=", "dstore", "[", "'assetcol/tagcol'", "]", ".", "__toh5__", "(", ")", "dic", ".", "update", "(", "...
Extract an array of assets, optionally filtered by tag. Use it as /extract/assets?taxonomy=RC&taxonomy=MSBC&occupancy=RES
[ "Extract", "an", "array", "of", "assets", "optionally", "filtered", "by", "tag", ".", "Use", "it", "as", "/", "extract", "/", "assets?taxonomy", "=", "RC&taxonomy", "=", "MSBC&occupancy", "=", "RES" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L222-L239
gem/oq-engine
openquake/calculators/extract.py
extract_asset_values
def extract_asset_values(dstore, sid): """ Extract an array of asset values for the given sid. Use it as /extract/asset_values/0 :returns: (aid, loss_type1, ..., loss_typeN) composite array """ if sid: return extract(dstore, 'asset_values')[int(sid)] assetcol = extract(dstor...
python
def extract_asset_values(dstore, sid): if sid: return extract(dstore, 'asset_values')[int(sid)] assetcol = extract(dstore, 'assetcol') asset_refs = assetcol.asset_refs assets_by_site = assetcol.assets_by_site() lts = assetcol.loss_types dt = numpy.dtype([('aref', asset_refs.dtype), ...
[ "def", "extract_asset_values", "(", "dstore", ",", "sid", ")", ":", "if", "sid", ":", "return", "extract", "(", "dstore", ",", "'asset_values'", ")", "[", "int", "(", "sid", ")", "]", "assetcol", "=", "extract", "(", "dstore", ",", "'assetcol'", ")", "...
Extract an array of asset values for the given sid. Use it as /extract/asset_values/0 :returns: (aid, loss_type1, ..., loss_typeN) composite array
[ "Extract", "an", "array", "of", "asset", "values", "for", "the", "given", "sid", ".", "Use", "it", "as", "/", "extract", "/", "asset_values", "/", "0" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L264-L289
gem/oq-engine
openquake/calculators/extract.py
extract_asset_tags
def extract_asset_tags(dstore, tagname): """ Extract an array of asset tags for the given tagname. Use it as /extract/asset_tags or /extract/asset_tags/taxonomy """ tagcol = dstore['assetcol/tagcol'] if tagname: yield tagname, barray(tagcol.gen_tags(tagname)) for tagname in tagcol.ta...
python
def extract_asset_tags(dstore, tagname): tagcol = dstore['assetcol/tagcol'] if tagname: yield tagname, barray(tagcol.gen_tags(tagname)) for tagname in tagcol.tagnames: yield tagname, barray(tagcol.gen_tags(tagname))
[ "def", "extract_asset_tags", "(", "dstore", ",", "tagname", ")", ":", "tagcol", "=", "dstore", "[", "'assetcol/tagcol'", "]", "if", "tagname", ":", "yield", "tagname", ",", "barray", "(", "tagcol", ".", "gen_tags", "(", "tagname", ")", ")", "for", "tagname...
Extract an array of asset tags for the given tagname. Use it as /extract/asset_tags or /extract/asset_tags/taxonomy
[ "Extract", "an", "array", "of", "asset", "tags", "for", "the", "given", "tagname", ".", "Use", "it", "as", "/", "extract", "/", "asset_tags", "or", "/", "extract", "/", "asset_tags", "/", "taxonomy" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L293-L302
gem/oq-engine
openquake/calculators/extract.py
get_mesh
def get_mesh(sitecol, complete=True): """ :returns: a lon-lat or lon-lat-depth array depending if the site collection is at sea level or not """ sc = sitecol.complete if complete else sitecol if sc.at_sea_level(): mesh = numpy.zeros(len(sc), [('lon', F64), ('lat', F64)]) ...
python
def get_mesh(sitecol, complete=True): sc = sitecol.complete if complete else sitecol if sc.at_sea_level(): mesh = numpy.zeros(len(sc), [('lon', F64), ('lat', F64)]) mesh['lon'] = sc.lons mesh['lat'] = sc.lats else: mesh = numpy.zeros(len(sc), [('lon', F64), ('lat', F64),...
[ "def", "get_mesh", "(", "sitecol", ",", "complete", "=", "True", ")", ":", "sc", "=", "sitecol", ".", "complete", "if", "complete", "else", "sitecol", "if", "sc", ".", "at_sea_level", "(", ")", ":", "mesh", "=", "numpy", ".", "zeros", "(", "len", "("...
:returns: a lon-lat or lon-lat-depth array depending if the site collection is at sea level or not
[ ":", "returns", ":", "a", "lon", "-", "lat", "or", "lon", "-", "lat", "-", "depth", "array", "depending", "if", "the", "site", "collection", "is", "at", "sea", "level", "or", "not" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L305-L322
gem/oq-engine
openquake/calculators/extract.py
hazard_items
def hazard_items(dic, mesh, *extras, **kw): """ :param dic: dictionary of arrays of the same shape :param mesh: a mesh array with lon, lat fields of the same length :param extras: optional triples (field, dtype, values) :param kw: dictionary of parameters (like investigation_time) :returns: a li...
python
def hazard_items(dic, mesh, *extras, **kw): for item in kw.items(): yield item arr = dic[next(iter(dic))] dtlist = [(str(field), arr.dtype) for field in sorted(dic)] for field, dtype, values in extras: dtlist.append((str(field), dtype)) array = numpy.zeros(arr.shape, dtlist) ...
[ "def", "hazard_items", "(", "dic", ",", "mesh", ",", "*", "extras", ",", "*", "*", "kw", ")", ":", "for", "item", "in", "kw", ".", "items", "(", ")", ":", "yield", "item", "arr", "=", "dic", "[", "next", "(", "iter", "(", "dic", ")", ")", "]"...
:param dic: dictionary of arrays of the same shape :param mesh: a mesh array with lon, lat fields of the same length :param extras: optional triples (field, dtype, values) :param kw: dictionary of parameters (like investigation_time) :returns: a list of pairs (key, value) suitable for storage in .npz fo...
[ ":", "param", "dic", ":", "dictionary", "of", "arrays", "of", "the", "same", "shape", ":", "param", "mesh", ":", "a", "mesh", "array", "with", "lon", "lat", "fields", "of", "the", "same", "length", ":", "param", "extras", ":", "optional", "triples", "(...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L325-L344
gem/oq-engine
openquake/calculators/extract.py
extract_hcurves
def extract_hcurves(dstore, what): """ Extracts hazard curves. Use it as /extract/hcurves?kind=mean or /extract/hcurves?kind=rlz-0, /extract/hcurves?kind=stats, /extract/hcurves?kind=rlzs etc """ info = get_info(dstore) if what == '': # npz exports for QGIS sitecol = dstore['sitecol...
python
def extract_hcurves(dstore, what): info = get_info(dstore) if what == '': sitecol = dstore['sitecol'] mesh = get_mesh(sitecol, complete=False) dic = _get_dict(dstore, 'hcurves-stats', info['imtls'], info['stats']) yield from hazard_items( dic, mesh, investigati...
[ "def", "extract_hcurves", "(", "dstore", ",", "what", ")", ":", "info", "=", "get_info", "(", "dstore", ")", "if", "what", "==", "''", ":", "# npz exports for QGIS", "sitecol", "=", "dstore", "[", "'sitecol'", "]", "mesh", "=", "get_mesh", "(", "sitecol", ...
Extracts hazard curves. Use it as /extract/hcurves?kind=mean or /extract/hcurves?kind=rlz-0, /extract/hcurves?kind=stats, /extract/hcurves?kind=rlzs etc
[ "Extracts", "hazard", "curves", ".", "Use", "it", "as", "/", "extract", "/", "hcurves?kind", "=", "mean", "or", "/", "extract", "/", "hcurves?kind", "=", "rlz", "-", "0", "/", "extract", "/", "hcurves?kind", "=", "stats", "/", "extract", "/", "hcurves?ki...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L359-L389
gem/oq-engine
openquake/calculators/extract.py
extract_hmaps
def extract_hmaps(dstore, what): """ Extracts hazard maps. Use it as /extract/hmaps?imt=PGA """ info = get_info(dstore) if what == '': # npz exports for QGIS sitecol = dstore['sitecol'] mesh = get_mesh(sitecol, complete=False) dic = _get_dict(dstore, 'hmaps-stats', ...
python
def extract_hmaps(dstore, what): info = get_info(dstore) if what == '': sitecol = dstore['sitecol'] mesh = get_mesh(sitecol, complete=False) dic = _get_dict(dstore, 'hmaps-stats', {imt: info['poes'] for imt in info['imtls']}, info['s...
[ "def", "extract_hmaps", "(", "dstore", ",", "what", ")", ":", "info", "=", "get_info", "(", "dstore", ")", "if", "what", "==", "''", ":", "# npz exports for QGIS", "sitecol", "=", "dstore", "[", "'sitecol'", "]", "mesh", "=", "get_mesh", "(", "sitecol", ...
Extracts hazard maps. Use it as /extract/hmaps?imt=PGA
[ "Extracts", "hazard", "maps", ".", "Use", "it", "as", "/", "extract", "/", "hmaps?imt", "=", "PGA" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L393-L423
gem/oq-engine
openquake/calculators/extract.py
extract_uhs
def extract_uhs(dstore, what): """ Extracts uniform hazard spectra. Use it as /extract/uhs?kind=mean or /extract/uhs?kind=rlz-0, etc """ info = get_info(dstore) if what == '': # npz exports for QGIS sitecol = dstore['sitecol'] mesh = get_mesh(sitecol, complete=False) dic...
python
def extract_uhs(dstore, what): info = get_info(dstore) if what == '': sitecol = dstore['sitecol'] mesh = get_mesh(sitecol, complete=False) dic = {} for stat, s in info['stats'].items(): hmap = dstore['hmaps-stats'][:, s] dic[stat] = calc.make_uhs(hm...
[ "def", "extract_uhs", "(", "dstore", ",", "what", ")", ":", "info", "=", "get_info", "(", "dstore", ")", "if", "what", "==", "''", ":", "# npz exports for QGIS", "sitecol", "=", "dstore", "[", "'sitecol'", "]", "mesh", "=", "get_mesh", "(", "sitecol", ",...
Extracts uniform hazard spectra. Use it as /extract/uhs?kind=mean or /extract/uhs?kind=rlz-0, etc
[ "Extracts", "uniform", "hazard", "spectra", ".", "Use", "it", "as", "/", "extract", "/", "uhs?kind", "=", "mean", "or", "/", "extract", "/", "uhs?kind", "=", "rlz", "-", "0", "etc" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L427-L462
gem/oq-engine
openquake/calculators/extract.py
extract_agg_curves
def extract_agg_curves(dstore, what): """ Aggregate loss curves of the given loss type and tags for event based risk calculations. Use it as /extract/agg_curves/structural?taxonomy=RC&zipcode=20126 :returns: array of shape (S, P), being P the number of return periods and S the number...
python
def extract_agg_curves(dstore, what): from openquake.calculators.export.loss_curves import get_loss_builder oq = dstore['oqparam'] loss_type, tags = get_loss_type_tags(what) if 'curves-stats' in dstore: losses = _get_curves(dstore['curves-stats'], oq.lti[loss_type]) stats = dstore...
[ "def", "extract_agg_curves", "(", "dstore", ",", "what", ")", ":", "from", "openquake", ".", "calculators", ".", "export", ".", "loss_curves", "import", "get_loss_builder", "oq", "=", "dstore", "[", "'oqparam'", "]", "loss_type", ",", "tags", "=", "get_loss_ty...
Aggregate loss curves of the given loss type and tags for event based risk calculations. Use it as /extract/agg_curves/structural?taxonomy=RC&zipcode=20126 :returns: array of shape (S, P), being P the number of return periods and S the number of statistics
[ "Aggregate", "loss", "curves", "of", "the", "given", "loss", "type", "and", "tags", "for", "event", "based", "risk", "calculations", ".", "Use", "it", "as", "/", "extract", "/", "agg_curves", "/", "structural?taxonomy", "=", "RC&zipcode", "=", "20126", ":", ...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L522-L547
gem/oq-engine
openquake/calculators/extract.py
extract_agg_losses
def extract_agg_losses(dstore, what): """ Aggregate losses of the given loss type and tags. Use it as /extract/agg_losses/structural?taxonomy=RC&zipcode=20126 /extract/agg_losses/structural?taxonomy=RC&zipcode=* :returns: an array of shape (T, R) if one of the tag names has a `*` value ...
python
def extract_agg_losses(dstore, what): loss_type, tags = get_loss_type_tags(what) if not loss_type: raise ValueError('loss_type not passed in agg_losses/<loss_type>') l = dstore['oqparam'].lti[loss_type] if 'losses_by_asset' in dstore: stats = None losses = dstore['losses_b...
[ "def", "extract_agg_losses", "(", "dstore", ",", "what", ")", ":", "loss_type", ",", "tags", "=", "get_loss_type_tags", "(", "what", ")", "if", "not", "loss_type", ":", "raise", "ValueError", "(", "'loss_type not passed in agg_losses/<loss_type>'", ")", "l", "=", ...
Aggregate losses of the given loss type and tags. Use it as /extract/agg_losses/structural?taxonomy=RC&zipcode=20126 /extract/agg_losses/structural?taxonomy=RC&zipcode=* :returns: an array of shape (T, R) if one of the tag names has a `*` value an array of shape (R,), being R the number of ...
[ "Aggregate", "losses", "of", "the", "given", "loss", "type", "and", "tags", ".", "Use", "it", "as", "/", "extract", "/", "agg_losses", "/", "structural?taxonomy", "=", "RC&zipcode", "=", "20126", "/", "extract", "/", "agg_losses", "/", "structural?taxonomy", ...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L551-L577
gem/oq-engine
openquake/calculators/extract.py
extract_agg_damages
def extract_agg_damages(dstore, what): """ Aggregate damages of the given loss type and tags. Use it as /extract/agg_damages/structural?taxonomy=RC&zipcode=20126 :returns: array of shape (R, D), being R the number of realizations and D the number of damage states, or an array of length ...
python
def extract_agg_damages(dstore, what): loss_type, tags = get_loss_type_tags(what) if 'dmg_by_asset' in dstore: lti = dstore['oqparam'].lti[loss_type] losses = dstore['dmg_by_asset'][:, :, lti, 0] else: raise KeyError('No damages found in %s' % dstore) return _filter_agg(ds...
[ "def", "extract_agg_damages", "(", "dstore", ",", "what", ")", ":", "loss_type", ",", "tags", "=", "get_loss_type_tags", "(", "what", ")", "if", "'dmg_by_asset'", "in", "dstore", ":", "# scenario_damage", "lti", "=", "dstore", "[", "'oqparam'", "]", ".", "lt...
Aggregate damages of the given loss type and tags. Use it as /extract/agg_damages/structural?taxonomy=RC&zipcode=20126 :returns: array of shape (R, D), being R the number of realizations and D the number of damage states, or an array of length 0 if there is no data for the given tags
[ "Aggregate", "damages", "of", "the", "given", "loss", "type", "and", "tags", ".", "Use", "it", "as", "/", "extract", "/", "agg_damages", "/", "structural?taxonomy", "=", "RC&zipcode", "=", "20126" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L581-L597
gem/oq-engine
openquake/calculators/extract.py
extract_aggregate
def extract_aggregate(dstore, what): """ /extract/aggregate/avg_losses? kind=mean&loss_type=structural&tag=taxonomy&tag=occupancy """ name, qstring = what.split('?', 1) info = get_info(dstore) qdic = parse(qstring, info) suffix = '-rlzs' if qdic['rlzs'] else '-stats' tagnames = qdic....
python
def extract_aggregate(dstore, what): name, qstring = what.split('?', 1) info = get_info(dstore) qdic = parse(qstring, info) suffix = '-rlzs' if qdic['rlzs'] else '-stats' tagnames = qdic.get('tag', []) assetcol = dstore['assetcol'] ltypes = qdic.get('loss_type', []) if ltypes: ...
[ "def", "extract_aggregate", "(", "dstore", ",", "what", ")", ":", "name", ",", "qstring", "=", "what", ".", "split", "(", "'?'", ",", "1", ")", "info", "=", "get_info", "(", "dstore", ")", "qdic", "=", "parse", "(", "qstring", ",", "info", ")", "su...
/extract/aggregate/avg_losses? kind=mean&loss_type=structural&tag=taxonomy&tag=occupancy
[ "/", "extract", "/", "aggregate", "/", "avg_losses?", "kind", "=", "mean&loss_type", "=", "structural&tag", "=", "taxonomy&tag", "=", "occupancy" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L601-L623
gem/oq-engine
openquake/calculators/extract.py
build_damage_dt
def build_damage_dt(dstore, mean_std=True): """ :param dstore: a datastore instance :param mean_std: a flag (default True) :returns: a composite dtype loss_type -> (mean_ds1, stdv_ds1, ...) or loss_type -> (ds1, ds2, ...) depending on the flag mean_std """ oq = dstore['oqparam'] ...
python
def build_damage_dt(dstore, mean_std=True): oq = dstore['oqparam'] damage_states = ['no_damage'] + list( dstore.get_attr('risk_model', 'limit_states')) dt_list = [] for ds in damage_states: ds = str(ds) if mean_std: dt_list.append(('%s_mean' % ds, F32)) ...
[ "def", "build_damage_dt", "(", "dstore", ",", "mean_std", "=", "True", ")", ":", "oq", "=", "dstore", "[", "'oqparam'", "]", "damage_states", "=", "[", "'no_damage'", "]", "+", "list", "(", "dstore", ".", "get_attr", "(", "'risk_model'", ",", "'limit_state...
:param dstore: a datastore instance :param mean_std: a flag (default True) :returns: a composite dtype loss_type -> (mean_ds1, stdv_ds1, ...) or loss_type -> (ds1, ds2, ...) depending on the flag mean_std
[ ":", "param", "dstore", ":", "a", "datastore", "instance", ":", "param", "mean_std", ":", "a", "flag", "(", "default", "True", ")", ":", "returns", ":", "a", "composite", "dtype", "loss_type", "-", ">", "(", "mean_ds1", "stdv_ds1", "...", ")", "or", "l...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L686-L707
gem/oq-engine
openquake/calculators/extract.py
build_damage_array
def build_damage_array(data, damage_dt): """ :param data: an array of shape (A, L, 1, D) or (A, L, 2, D) :param damage_dt: a damage composite data type loss_type -> states :returns: a composite array of length N and dtype damage_dt """ A, L, MS, D = data.shape dmg = numpy.zeros(A, damage_dt)...
python
def build_damage_array(data, damage_dt): A, L, MS, D = data.shape dmg = numpy.zeros(A, damage_dt) for a in range(A): for l, lt in enumerate(damage_dt.names): std = any(f for f in damage_dt[lt].names if f.endswith('_stdv')) if MS == 1 or not std: dmg[lt]...
[ "def", "build_damage_array", "(", "data", ",", "damage_dt", ")", ":", "A", ",", "L", ",", "MS", ",", "D", "=", "data", ".", "shape", "dmg", "=", "numpy", ".", "zeros", "(", "A", ",", "damage_dt", ")", "for", "a", "in", "range", "(", "A", ")", "...
:param data: an array of shape (A, L, 1, D) or (A, L, 2, D) :param damage_dt: a damage composite data type loss_type -> states :returns: a composite array of length N and dtype damage_dt
[ ":", "param", "data", ":", "an", "array", "of", "shape", "(", "A", "L", "1", "D", ")", "or", "(", "A", "L", "2", "D", ")", ":", "param", "damage_dt", ":", "a", "damage", "composite", "data", "type", "loss_type", "-", ">", "states", ":", "returns"...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L710-L726
gem/oq-engine
openquake/calculators/extract.py
extract_mfd
def extract_mfd(dstore, what): """ Display num_ruptures by magnitude for event based calculations. Example: http://127.0.0.1:8800/v1/calc/30/extract/event_based_mfd """ dd = collections.defaultdict(int) for rup in dstore['ruptures'].value: dd[rup['mag']] += 1 dt = numpy.dtype([('mag'...
python
def extract_mfd(dstore, what): dd = collections.defaultdict(int) for rup in dstore['ruptures'].value: dd[rup['mag']] += 1 dt = numpy.dtype([('mag', float), ('freq', int)]) magfreq = numpy.array(sorted(dd.items(), key=operator.itemgetter(0)), dt) return magfreq
[ "def", "extract_mfd", "(", "dstore", ",", "what", ")", ":", "dd", "=", "collections", ".", "defaultdict", "(", "int", ")", "for", "rup", "in", "dstore", "[", "'ruptures'", "]", ".", "value", ":", "dd", "[", "rup", "[", "'mag'", "]", "]", "+=", "1",...
Display num_ruptures by magnitude for event based calculations. Example: http://127.0.0.1:8800/v1/calc/30/extract/event_based_mfd
[ "Display", "num_ruptures", "by", "magnitude", "for", "event", "based", "calculations", ".", "Example", ":", "http", ":", "//", "127", ".", "0", ".", "0", ".", "1", ":", "8800", "/", "v1", "/", "calc", "/", "30", "/", "extract", "/", "event_based_mfd" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L742-L752
gem/oq-engine
openquake/calculators/extract.py
extract_src_loss_table
def extract_src_loss_table(dstore, loss_type): """ Extract the source loss table for a give loss type, ordered in decreasing order. Example: http://127.0.0.1:8800/v1/calc/30/extract/src_loss_table/structural """ oq = dstore['oqparam'] li = oq.lti[loss_type] source_ids = dstore['source_in...
python
def extract_src_loss_table(dstore, loss_type): oq = dstore['oqparam'] li = oq.lti[loss_type] source_ids = dstore['source_info']['source_id'] idxs = dstore['ruptures'].value[['srcidx', 'grp_id']] losses = dstore['rup_loss_table'][:, li] slt = numpy.zeros(len(source_ids), [('grp_id', U32), (l...
[ "def", "extract_src_loss_table", "(", "dstore", ",", "loss_type", ")", ":", "oq", "=", "dstore", "[", "'oqparam'", "]", "li", "=", "oq", ".", "lti", "[", "loss_type", "]", "source_ids", "=", "dstore", "[", "'source_info'", "]", "[", "'source_id'", "]", "...
Extract the source loss table for a give loss type, ordered in decreasing order. Example: http://127.0.0.1:8800/v1/calc/30/extract/src_loss_table/structural
[ "Extract", "the", "source", "loss", "table", "for", "a", "give", "loss", "type", "ordered", "in", "decreasing", "order", ".", "Example", ":", "http", ":", "//", "127", ".", "0", ".", "0", ".", "1", ":", "8800", "/", "v1", "/", "calc", "/", "30", ...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L756-L773
gem/oq-engine
openquake/calculators/extract.py
extract_mean_std_curves
def extract_mean_std_curves(dstore, what): """ Yield imls/IMT and poes/IMT containg mean and stddev for all sites """ getter = getters.PmapGetter(dstore) arr = getter.get_mean().array for imt in getter.imtls: yield 'imls/' + imt, getter.imtls[imt] yield 'poes/' + imt, arr[:, gett...
python
def extract_mean_std_curves(dstore, what): getter = getters.PmapGetter(dstore) arr = getter.get_mean().array for imt in getter.imtls: yield 'imls/' + imt, getter.imtls[imt] yield 'poes/' + imt, arr[:, getter.imtls(imt)]
[ "def", "extract_mean_std_curves", "(", "dstore", ",", "what", ")", ":", "getter", "=", "getters", ".", "PmapGetter", "(", "dstore", ")", "arr", "=", "getter", ".", "get_mean", "(", ")", ".", "array", "for", "imt", "in", "getter", ".", "imtls", ":", "yi...
Yield imls/IMT and poes/IMT containg mean and stddev for all sites
[ "Yield", "imls", "/", "IMT", "and", "poes", "/", "IMT", "containg", "mean", "and", "stddev", "for", "all", "sites" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L777-L785
gem/oq-engine
openquake/calculators/extract.py
losses_by_tag
def losses_by_tag(dstore, tag): """ Statistical average losses by tag. For instance call $ oq extract losses_by_tag/occupancy """ dt = [(tag, vstr)] + dstore['oqparam'].loss_dt_list() aids = dstore['assetcol/array'][tag] dset, stats = _get(dstore, 'avg_losses') arr = dset.value tagv...
python
def losses_by_tag(dstore, tag): dt = [(tag, vstr)] + dstore['oqparam'].loss_dt_list() aids = dstore['assetcol/array'][tag] dset, stats = _get(dstore, 'avg_losses') arr = dset.value tagvalues = dstore['assetcol/tagcol/' + tag][1:] for s, stat in enumerate(stats): out = numpy.zeros(...
[ "def", "losses_by_tag", "(", "dstore", ",", "tag", ")", ":", "dt", "=", "[", "(", "tag", ",", "vstr", ")", "]", "+", "dstore", "[", "'oqparam'", "]", ".", "loss_dt_list", "(", ")", "aids", "=", "dstore", "[", "'assetcol/array'", "]", "[", "tag", "]...
Statistical average losses by tag. For instance call $ oq extract losses_by_tag/occupancy
[ "Statistical", "average", "losses", "by", "tag", ".", "For", "instance", "call" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L808-L827
gem/oq-engine
openquake/calculators/extract.py
extract_rupture
def extract_rupture(dstore, serial): """ Extract information about the given event index. Example: http://127.0.0.1:8800/v1/calc/30/extract/rupture/1066 """ ridx = list(dstore['ruptures']['serial']).index(int(serial)) [getter] = getters.gen_rupture_getters(dstore, slice(ridx, ridx + 1)) ...
python
def extract_rupture(dstore, serial): ridx = list(dstore['ruptures']['serial']).index(int(serial)) [getter] = getters.gen_rupture_getters(dstore, slice(ridx, ridx + 1)) yield from getter.get_rupdict().items()
[ "def", "extract_rupture", "(", "dstore", ",", "serial", ")", ":", "ridx", "=", "list", "(", "dstore", "[", "'ruptures'", "]", "[", "'serial'", "]", ")", ".", "index", "(", "int", "(", "serial", ")", ")", "[", "getter", "]", "=", "getters", ".", "ge...
Extract information about the given event index. Example: http://127.0.0.1:8800/v1/calc/30/extract/rupture/1066
[ "Extract", "information", "about", "the", "given", "event", "index", ".", "Example", ":", "http", ":", "//", "127", ".", "0", ".", "0", ".", "1", ":", "8800", "/", "v1", "/", "calc", "/", "30", "/", "extract", "/", "rupture", "/", "1066" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L831-L839
gem/oq-engine
openquake/calculators/extract.py
extract_event_info
def extract_event_info(dstore, eidx): """ Extract information about the given event index. Example: http://127.0.0.1:8800/v1/calc/30/extract/event_info/0 """ event = dstore['events'][int(eidx)] serial = int(event['eid'] // TWO32) ridx = list(dstore['ruptures']['serial']).index(serial) ...
python
def extract_event_info(dstore, eidx): event = dstore['events'][int(eidx)] serial = int(event['eid'] // TWO32) ridx = list(dstore['ruptures']['serial']).index(serial) [getter] = getters.gen_rupture_getters(dstore, slice(ridx, ridx + 1)) rupdict = getter.get_rupdict() rlzi = event['rlz'] ...
[ "def", "extract_event_info", "(", "dstore", ",", "eidx", ")", ":", "event", "=", "dstore", "[", "'events'", "]", "[", "int", "(", "eidx", ")", "]", "serial", "=", "int", "(", "event", "[", "'eid'", "]", "//", "TWO32", ")", "ridx", "=", "list", "(",...
Extract information about the given event index. Example: http://127.0.0.1:8800/v1/calc/30/extract/event_info/0
[ "Extract", "information", "about", "the", "given", "event", "index", ".", "Example", ":", "http", ":", "//", "127", ".", "0", ".", "0", ".", "1", ":", "8800", "/", "v1", "/", "calc", "/", "30", "/", "extract", "/", "event_info", "/", "0" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L843-L860
gem/oq-engine
openquake/calculators/extract.py
get_ruptures_within
def get_ruptures_within(dstore, bbox): """ Extract the ruptures within the given bounding box, a string minlon,minlat,maxlon,maxlat. Example: http://127.0.0.1:8800/v1/calc/30/extract/ruptures_with/8,44,10,46 """ minlon, minlat, maxlon, maxlat = map(float, bbox.split(',')) hypo = dstore['...
python
def get_ruptures_within(dstore, bbox): minlon, minlat, maxlon, maxlat = map(float, bbox.split(',')) hypo = dstore['ruptures']['hypo'].T mask = ((minlon <= hypo[0]) * (minlat <= hypo[1]) * (maxlon >= hypo[0]) * (maxlat >= hypo[1])) return dstore['ruptures'][mask]
[ "def", "get_ruptures_within", "(", "dstore", ",", "bbox", ")", ":", "minlon", ",", "minlat", ",", "maxlon", ",", "maxlat", "=", "map", "(", "float", ",", "bbox", ".", "split", "(", "','", ")", ")", "hypo", "=", "dstore", "[", "'ruptures'", "]", "[", ...
Extract the ruptures within the given bounding box, a string minlon,minlat,maxlon,maxlat. Example: http://127.0.0.1:8800/v1/calc/30/extract/ruptures_with/8,44,10,46
[ "Extract", "the", "ruptures", "within", "the", "given", "bounding", "box", "a", "string", "minlon", "minlat", "maxlon", "maxlat", ".", "Example", ":", "http", ":", "//", "127", ".", "0", ".", "0", ".", "1", ":", "8800", "/", "v1", "/", "calc", "/", ...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L864-L875
gem/oq-engine
openquake/calculators/extract.py
extract_source_geom
def extract_source_geom(dstore, srcidxs): """ Extract the geometry of a given sources Example: http://127.0.0.1:8800/v1/calc/30/extract/source_geom/1,2,3 """ for i in srcidxs.split(','): rec = dstore['source_info'][int(i)] geom = dstore['source_geom'][rec['gidx1']:rec['gidx2']] ...
python
def extract_source_geom(dstore, srcidxs): for i in srcidxs.split(','): rec = dstore['source_info'][int(i)] geom = dstore['source_geom'][rec['gidx1']:rec['gidx2']] yield rec['source_id'], geom
[ "def", "extract_source_geom", "(", "dstore", ",", "srcidxs", ")", ":", "for", "i", "in", "srcidxs", ".", "split", "(", "','", ")", ":", "rec", "=", "dstore", "[", "'source_info'", "]", "[", "int", "(", "i", ")", "]", "geom", "=", "dstore", "[", "'s...
Extract the geometry of a given sources Example: http://127.0.0.1:8800/v1/calc/30/extract/source_geom/1,2,3
[ "Extract", "the", "geometry", "of", "a", "given", "sources", "Example", ":", "http", ":", "//", "127", ".", "0", ".", "0", ".", "1", ":", "8800", "/", "v1", "/", "calc", "/", "30", "/", "extract", "/", "source_geom", "/", "1", "2", "3" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L879-L888
gem/oq-engine
openquake/calculators/extract.py
WebExtractor.get
def get(self, what): """ :param what: what to extract :returns: an ArrayWrapper instance """ url = '%s/v1/calc/%d/extract/%s' % (self.server, self.calc_id, what) logging.info('GET %s', url) resp = self.sess.get(url) if resp.status_code != 200: ...
python
def get(self, what): url = '%s/v1/calc/%d/extract/%s' % (self.server, self.calc_id, what) logging.info('GET %s', url) resp = self.sess.get(url) if resp.status_code != 200: raise WebAPIError(resp.text) npz = numpy.load(io.BytesIO(resp.content)) attrs =...
[ "def", "get", "(", "self", ",", "what", ")", ":", "url", "=", "'%s/v1/calc/%d/extract/%s'", "%", "(", "self", ".", "server", ",", "self", ".", "calc_id", ",", "what", ")", "logging", ".", "info", "(", "'GET %s'", ",", "url", ")", "resp", "=", "self",...
:param what: what to extract :returns: an ArrayWrapper instance
[ ":", "param", "what", ":", "what", "to", "extract", ":", "returns", ":", "an", "ArrayWrapper", "instance" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L970-L986
gem/oq-engine
openquake/calculators/extract.py
WebExtractor.dump
def dump(self, fname): """ Dump the remote datastore on a local path. """ url = '%s/v1/calc/%d/datastore' % (self.server, self.calc_id) resp = self.sess.get(url, stream=True) down = 0 with open(fname, 'wb') as f: logging.info('Saving %s', fname) ...
python
def dump(self, fname): url = '%s/v1/calc/%d/datastore' % (self.server, self.calc_id) resp = self.sess.get(url, stream=True) down = 0 with open(fname, 'wb') as f: logging.info('Saving %s', fname) for chunk in resp.iter_content(CHUNKSIZE): f...
[ "def", "dump", "(", "self", ",", "fname", ")", ":", "url", "=", "'%s/v1/calc/%d/datastore'", "%", "(", "self", ".", "server", ",", "self", ".", "calc_id", ")", "resp", "=", "self", ".", "sess", ".", "get", "(", "url", ",", "stream", "=", "True", ")...
Dump the remote datastore on a local path.
[ "Dump", "the", "remote", "datastore", "on", "a", "local", "path", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L988-L1001