repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
gem/oq-engine | openquake/baselib/node.py | _display | def _display(node, indent, expandattrs, expandvals, output):
"""Core function to display a Node object"""
attrs = _displayattrs(node.attrib, expandattrs)
if node.text is None or not expandvals:
val = ''
elif isinstance(node.text, str):
val = ' %s' % repr(node.text.strip())
else:
val = ' %s' % repr(node.text) # node.text can be a tuple
output.write(encode(indent + striptag(node.tag) + attrs + val + '\n'))
for sub_node in node:
_display(sub_node, indent + ' ', expandattrs, expandvals, output) | python | def _display(node, indent, expandattrs, expandvals, output):
"""Core function to display a Node object"""
attrs = _displayattrs(node.attrib, expandattrs)
if node.text is None or not expandvals:
val = ''
elif isinstance(node.text, str):
val = ' %s' % repr(node.text.strip())
else:
val = ' %s' % repr(node.text) # node.text can be a tuple
output.write(encode(indent + striptag(node.tag) + attrs + val + '\n'))
for sub_node in node:
_display(sub_node, indent + ' ', expandattrs, expandvals, output) | [
"def",
"_display",
"(",
"node",
",",
"indent",
",",
"expandattrs",
",",
"expandvals",
",",
"output",
")",
":",
"attrs",
"=",
"_displayattrs",
"(",
"node",
".",
"attrib",
",",
"expandattrs",
")",
"if",
"node",
".",
"text",
"is",
"None",
"or",
"not",
"expandvals",
":",
"val",
"=",
"''",
"elif",
"isinstance",
"(",
"node",
".",
"text",
",",
"str",
")",
":",
"val",
"=",
"' %s'",
"%",
"repr",
"(",
"node",
".",
"text",
".",
"strip",
"(",
")",
")",
"else",
":",
"val",
"=",
"' %s'",
"%",
"repr",
"(",
"node",
".",
"text",
")",
"# node.text can be a tuple",
"output",
".",
"write",
"(",
"encode",
"(",
"indent",
"+",
"striptag",
"(",
"node",
".",
"tag",
")",
"+",
"attrs",
"+",
"val",
"+",
"'\\n'",
")",
")",
"for",
"sub_node",
"in",
"node",
":",
"_display",
"(",
"sub_node",
",",
"indent",
"+",
"' '",
",",
"expandattrs",
",",
"expandvals",
",",
"output",
")"
] | Core function to display a Node object | [
"Core",
"function",
"to",
"display",
"a",
"Node",
"object"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L380-L391 | train | 233,200 |
gem/oq-engine | openquake/baselib/node.py | to_literal | def to_literal(self):
"""
Convert the node into a literal Python object
"""
if not self.nodes:
return (self.tag, self.attrib, self.text, [])
else:
return (self.tag, self.attrib, self.text,
list(map(to_literal, self.nodes))) | python | def to_literal(self):
"""
Convert the node into a literal Python object
"""
if not self.nodes:
return (self.tag, self.attrib, self.text, [])
else:
return (self.tag, self.attrib, self.text,
list(map(to_literal, self.nodes))) | [
"def",
"to_literal",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"nodes",
":",
"return",
"(",
"self",
".",
"tag",
",",
"self",
".",
"attrib",
",",
"self",
".",
"text",
",",
"[",
"]",
")",
"else",
":",
"return",
"(",
"self",
".",
"tag",
",",
"self",
".",
"attrib",
",",
"self",
".",
"text",
",",
"list",
"(",
"map",
"(",
"to_literal",
",",
"self",
".",
"nodes",
")",
")",
")"
] | Convert the node into a literal Python object | [
"Convert",
"the",
"node",
"into",
"a",
"literal",
"Python",
"object"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L574-L582 | train | 233,201 |
gem/oq-engine | openquake/baselib/node.py | pprint | def pprint(self, stream=None, indent=1, width=80, depth=None):
"""
Pretty print the underlying literal Python object
"""
pp.pprint(to_literal(self), stream, indent, width, depth) | python | def pprint(self, stream=None, indent=1, width=80, depth=None):
"""
Pretty print the underlying literal Python object
"""
pp.pprint(to_literal(self), stream, indent, width, depth) | [
"def",
"pprint",
"(",
"self",
",",
"stream",
"=",
"None",
",",
"indent",
"=",
"1",
",",
"width",
"=",
"80",
",",
"depth",
"=",
"None",
")",
":",
"pp",
".",
"pprint",
"(",
"to_literal",
"(",
"self",
")",
",",
"stream",
",",
"indent",
",",
"width",
",",
"depth",
")"
] | Pretty print the underlying literal Python object | [
"Pretty",
"print",
"the",
"underlying",
"literal",
"Python",
"object"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L585-L589 | train | 233,202 |
gem/oq-engine | openquake/baselib/node.py | read_nodes | def read_nodes(fname, filter_elem, nodefactory=Node, remove_comments=True):
"""
Convert an XML file into a lazy iterator over Node objects
satifying the given specification, i.e. a function element -> boolean.
:param fname: file name of file object
:param filter_elem: element specification
In case of errors, add the file name to the error message.
"""
try:
for _, el in iterparse(fname, remove_comments=remove_comments):
if filter_elem(el):
yield node_from_elem(el, nodefactory)
el.clear() # save memory
except Exception:
etype, exc, tb = sys.exc_info()
msg = str(exc)
if not str(fname) in msg:
msg = '%s in %s' % (msg, fname)
raise_(etype, msg, tb) | python | def read_nodes(fname, filter_elem, nodefactory=Node, remove_comments=True):
"""
Convert an XML file into a lazy iterator over Node objects
satifying the given specification, i.e. a function element -> boolean.
:param fname: file name of file object
:param filter_elem: element specification
In case of errors, add the file name to the error message.
"""
try:
for _, el in iterparse(fname, remove_comments=remove_comments):
if filter_elem(el):
yield node_from_elem(el, nodefactory)
el.clear() # save memory
except Exception:
etype, exc, tb = sys.exc_info()
msg = str(exc)
if not str(fname) in msg:
msg = '%s in %s' % (msg, fname)
raise_(etype, msg, tb) | [
"def",
"read_nodes",
"(",
"fname",
",",
"filter_elem",
",",
"nodefactory",
"=",
"Node",
",",
"remove_comments",
"=",
"True",
")",
":",
"try",
":",
"for",
"_",
",",
"el",
"in",
"iterparse",
"(",
"fname",
",",
"remove_comments",
"=",
"remove_comments",
")",
":",
"if",
"filter_elem",
"(",
"el",
")",
":",
"yield",
"node_from_elem",
"(",
"el",
",",
"nodefactory",
")",
"el",
".",
"clear",
"(",
")",
"# save memory",
"except",
"Exception",
":",
"etype",
",",
"exc",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"str",
"(",
"exc",
")",
"if",
"not",
"str",
"(",
"fname",
")",
"in",
"msg",
":",
"msg",
"=",
"'%s in %s'",
"%",
"(",
"msg",
",",
"fname",
")",
"raise_",
"(",
"etype",
",",
"msg",
",",
"tb",
")"
] | Convert an XML file into a lazy iterator over Node objects
satifying the given specification, i.e. a function element -> boolean.
:param fname: file name of file object
:param filter_elem: element specification
In case of errors, add the file name to the error message. | [
"Convert",
"an",
"XML",
"file",
"into",
"a",
"lazy",
"iterator",
"over",
"Node",
"objects",
"satifying",
"the",
"given",
"specification",
"i",
".",
"e",
".",
"a",
"function",
"element",
"-",
">",
"boolean",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L666-L686 | train | 233,203 |
gem/oq-engine | openquake/baselib/node.py | node_from_xml | def node_from_xml(xmlfile, nodefactory=Node):
"""
Convert a .xml file into a Node object.
:param xmlfile: a file name or file object open for reading
"""
root = parse(xmlfile).getroot()
return node_from_elem(root, nodefactory) | python | def node_from_xml(xmlfile, nodefactory=Node):
"""
Convert a .xml file into a Node object.
:param xmlfile: a file name or file object open for reading
"""
root = parse(xmlfile).getroot()
return node_from_elem(root, nodefactory) | [
"def",
"node_from_xml",
"(",
"xmlfile",
",",
"nodefactory",
"=",
"Node",
")",
":",
"root",
"=",
"parse",
"(",
"xmlfile",
")",
".",
"getroot",
"(",
")",
"return",
"node_from_elem",
"(",
"root",
",",
"nodefactory",
")"
] | Convert a .xml file into a Node object.
:param xmlfile: a file name or file object open for reading | [
"Convert",
"a",
".",
"xml",
"file",
"into",
"a",
"Node",
"object",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L689-L696 | train | 233,204 |
gem/oq-engine | openquake/baselib/node.py | node_from_ini | def node_from_ini(ini_file, nodefactory=Node, root_name='ini'):
"""
Convert a .ini file into a Node object.
:param ini_file: a filename or a file like object in read mode
"""
fileobj = open(ini_file) if isinstance(ini_file, str) else ini_file
cfp = configparser.RawConfigParser()
cfp.read_file(fileobj)
root = nodefactory(root_name)
sections = cfp.sections()
for section in sections:
params = dict(cfp.items(section))
root.append(Node(section, params))
return root | python | def node_from_ini(ini_file, nodefactory=Node, root_name='ini'):
"""
Convert a .ini file into a Node object.
:param ini_file: a filename or a file like object in read mode
"""
fileobj = open(ini_file) if isinstance(ini_file, str) else ini_file
cfp = configparser.RawConfigParser()
cfp.read_file(fileobj)
root = nodefactory(root_name)
sections = cfp.sections()
for section in sections:
params = dict(cfp.items(section))
root.append(Node(section, params))
return root | [
"def",
"node_from_ini",
"(",
"ini_file",
",",
"nodefactory",
"=",
"Node",
",",
"root_name",
"=",
"'ini'",
")",
":",
"fileobj",
"=",
"open",
"(",
"ini_file",
")",
"if",
"isinstance",
"(",
"ini_file",
",",
"str",
")",
"else",
"ini_file",
"cfp",
"=",
"configparser",
".",
"RawConfigParser",
"(",
")",
"cfp",
".",
"read_file",
"(",
"fileobj",
")",
"root",
"=",
"nodefactory",
"(",
"root_name",
")",
"sections",
"=",
"cfp",
".",
"sections",
"(",
")",
"for",
"section",
"in",
"sections",
":",
"params",
"=",
"dict",
"(",
"cfp",
".",
"items",
"(",
"section",
")",
")",
"root",
".",
"append",
"(",
"Node",
"(",
"section",
",",
"params",
")",
")",
"return",
"root"
] | Convert a .ini file into a Node object.
:param ini_file: a filename or a file like object in read mode | [
"Convert",
"a",
".",
"ini",
"file",
"into",
"a",
"Node",
"object",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L719-L733 | train | 233,205 |
gem/oq-engine | openquake/baselib/node.py | node_to_ini | def node_to_ini(node, output=sys.stdout):
"""
Convert a Node object with the right structure into a .ini file.
:params node: a Node object
:params output: a file-like object opened in write mode
"""
for subnode in node:
output.write(u'\n[%s]\n' % subnode.tag)
for name, value in sorted(subnode.attrib.items()):
output.write(u'%s=%s\n' % (name, value))
output.flush() | python | def node_to_ini(node, output=sys.stdout):
"""
Convert a Node object with the right structure into a .ini file.
:params node: a Node object
:params output: a file-like object opened in write mode
"""
for subnode in node:
output.write(u'\n[%s]\n' % subnode.tag)
for name, value in sorted(subnode.attrib.items()):
output.write(u'%s=%s\n' % (name, value))
output.flush() | [
"def",
"node_to_ini",
"(",
"node",
",",
"output",
"=",
"sys",
".",
"stdout",
")",
":",
"for",
"subnode",
"in",
"node",
":",
"output",
".",
"write",
"(",
"u'\\n[%s]\\n'",
"%",
"subnode",
".",
"tag",
")",
"for",
"name",
",",
"value",
"in",
"sorted",
"(",
"subnode",
".",
"attrib",
".",
"items",
"(",
")",
")",
":",
"output",
".",
"write",
"(",
"u'%s=%s\\n'",
"%",
"(",
"name",
",",
"value",
")",
")",
"output",
".",
"flush",
"(",
")"
] | Convert a Node object with the right structure into a .ini file.
:params node: a Node object
:params output: a file-like object opened in write mode | [
"Convert",
"a",
"Node",
"object",
"with",
"the",
"right",
"structure",
"into",
"a",
".",
"ini",
"file",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L736-L747 | train | 233,206 |
gem/oq-engine | openquake/baselib/node.py | node_copy | def node_copy(node, nodefactory=Node):
"""Make a deep copy of the node"""
return nodefactory(node.tag, node.attrib.copy(), node.text,
[node_copy(n, nodefactory) for n in node]) | python | def node_copy(node, nodefactory=Node):
"""Make a deep copy of the node"""
return nodefactory(node.tag, node.attrib.copy(), node.text,
[node_copy(n, nodefactory) for n in node]) | [
"def",
"node_copy",
"(",
"node",
",",
"nodefactory",
"=",
"Node",
")",
":",
"return",
"nodefactory",
"(",
"node",
".",
"tag",
",",
"node",
".",
"attrib",
".",
"copy",
"(",
")",
",",
"node",
".",
"text",
",",
"[",
"node_copy",
"(",
"n",
",",
"nodefactory",
")",
"for",
"n",
"in",
"node",
"]",
")"
] | Make a deep copy of the node | [
"Make",
"a",
"deep",
"copy",
"of",
"the",
"node"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L750-L753 | train | 233,207 |
gem/oq-engine | openquake/baselib/node.py | context | def context(fname, node):
"""
Context manager managing exceptions and adding line number of the
current node and name of the current file to the error message.
:param fname: the current file being processed
:param node: the current node being processed
"""
try:
yield node
except Exception:
etype, exc, tb = sys.exc_info()
msg = 'node %s: %s, line %s of %s' % (
striptag(node.tag), exc, getattr(node, 'lineno', '?'), fname)
raise_(etype, msg, tb) | python | def context(fname, node):
"""
Context manager managing exceptions and adding line number of the
current node and name of the current file to the error message.
:param fname: the current file being processed
:param node: the current node being processed
"""
try:
yield node
except Exception:
etype, exc, tb = sys.exc_info()
msg = 'node %s: %s, line %s of %s' % (
striptag(node.tag), exc, getattr(node, 'lineno', '?'), fname)
raise_(etype, msg, tb) | [
"def",
"context",
"(",
"fname",
",",
"node",
")",
":",
"try",
":",
"yield",
"node",
"except",
"Exception",
":",
"etype",
",",
"exc",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'node %s: %s, line %s of %s'",
"%",
"(",
"striptag",
"(",
"node",
".",
"tag",
")",
",",
"exc",
",",
"getattr",
"(",
"node",
",",
"'lineno'",
",",
"'?'",
")",
",",
"fname",
")",
"raise_",
"(",
"etype",
",",
"msg",
",",
"tb",
")"
] | Context manager managing exceptions and adding line number of the
current node and name of the current file to the error message.
:param fname: the current file being processed
:param node: the current node being processed | [
"Context",
"manager",
"managing",
"exceptions",
"and",
"adding",
"line",
"number",
"of",
"the",
"current",
"node",
"and",
"name",
"of",
"the",
"current",
"file",
"to",
"the",
"error",
"message",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L757-L771 | train | 233,208 |
gem/oq-engine | openquake/baselib/node.py | StreamingXMLWriter.shorten | def shorten(self, tag):
"""
Get the short representation of a fully qualified tag
:param str tag: a (fully qualified or not) XML tag
"""
if tag.startswith('{'):
ns, _tag = tag.rsplit('}')
tag = self.nsmap.get(ns[1:], '') + _tag
return tag | python | def shorten(self, tag):
"""
Get the short representation of a fully qualified tag
:param str tag: a (fully qualified or not) XML tag
"""
if tag.startswith('{'):
ns, _tag = tag.rsplit('}')
tag = self.nsmap.get(ns[1:], '') + _tag
return tag | [
"def",
"shorten",
"(",
"self",
",",
"tag",
")",
":",
"if",
"tag",
".",
"startswith",
"(",
"'{'",
")",
":",
"ns",
",",
"_tag",
"=",
"tag",
".",
"rsplit",
"(",
"'}'",
")",
"tag",
"=",
"self",
".",
"nsmap",
".",
"get",
"(",
"ns",
"[",
"1",
":",
"]",
",",
"''",
")",
"+",
"_tag",
"return",
"tag"
] | Get the short representation of a fully qualified tag
:param str tag: a (fully qualified or not) XML tag | [
"Get",
"the",
"short",
"representation",
"of",
"a",
"fully",
"qualified",
"tag"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L254-L263 | train | 233,209 |
gem/oq-engine | openquake/baselib/node.py | StreamingXMLWriter._write | def _write(self, text):
"""Write text by respecting the current indentlevel"""
spaces = ' ' * (self.indent * self.indentlevel)
t = spaces + text.strip() + '\n'
if hasattr(t, 'encode'):
t = t.encode(self.encoding, 'xmlcharrefreplace')
self.stream.write(t) | python | def _write(self, text):
"""Write text by respecting the current indentlevel"""
spaces = ' ' * (self.indent * self.indentlevel)
t = spaces + text.strip() + '\n'
if hasattr(t, 'encode'):
t = t.encode(self.encoding, 'xmlcharrefreplace')
self.stream.write(t) | [
"def",
"_write",
"(",
"self",
",",
"text",
")",
":",
"spaces",
"=",
"' '",
"*",
"(",
"self",
".",
"indent",
"*",
"self",
".",
"indentlevel",
")",
"t",
"=",
"spaces",
"+",
"text",
".",
"strip",
"(",
")",
"+",
"'\\n'",
"if",
"hasattr",
"(",
"t",
",",
"'encode'",
")",
":",
"t",
"=",
"t",
".",
"encode",
"(",
"self",
".",
"encoding",
",",
"'xmlcharrefreplace'",
")",
"self",
".",
"stream",
".",
"write",
"(",
"t",
")"
] | Write text by respecting the current indentlevel | [
"Write",
"text",
"by",
"respecting",
"the",
"current",
"indentlevel"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L265-L271 | train | 233,210 |
gem/oq-engine | openquake/baselib/node.py | StreamingXMLWriter.start_tag | def start_tag(self, name, attrs=None):
"""Open an XML tag"""
if not attrs:
self._write('<%s>' % name)
else:
self._write('<' + name)
for (name, value) in sorted(attrs.items()):
self._write(
' %s=%s' % (name, quoteattr(scientificformat(value))))
self._write('>')
self.indentlevel += 1 | python | def start_tag(self, name, attrs=None):
"""Open an XML tag"""
if not attrs:
self._write('<%s>' % name)
else:
self._write('<' + name)
for (name, value) in sorted(attrs.items()):
self._write(
' %s=%s' % (name, quoteattr(scientificformat(value))))
self._write('>')
self.indentlevel += 1 | [
"def",
"start_tag",
"(",
"self",
",",
"name",
",",
"attrs",
"=",
"None",
")",
":",
"if",
"not",
"attrs",
":",
"self",
".",
"_write",
"(",
"'<%s>'",
"%",
"name",
")",
"else",
":",
"self",
".",
"_write",
"(",
"'<'",
"+",
"name",
")",
"for",
"(",
"name",
",",
"value",
")",
"in",
"sorted",
"(",
"attrs",
".",
"items",
"(",
")",
")",
":",
"self",
".",
"_write",
"(",
"' %s=%s'",
"%",
"(",
"name",
",",
"quoteattr",
"(",
"scientificformat",
"(",
"value",
")",
")",
")",
")",
"self",
".",
"_write",
"(",
"'>'",
")",
"self",
".",
"indentlevel",
"+=",
"1"
] | Open an XML tag | [
"Open",
"an",
"XML",
"tag"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L279-L289 | train | 233,211 |
gem/oq-engine | openquake/baselib/node.py | Node.getnodes | def getnodes(self, name):
"Return the direct subnodes with name 'name'"
for node in self.nodes:
if striptag(node.tag) == name:
yield node | python | def getnodes(self, name):
"Return the direct subnodes with name 'name'"
for node in self.nodes:
if striptag(node.tag) == name:
yield node | [
"def",
"getnodes",
"(",
"self",
",",
"name",
")",
":",
"for",
"node",
"in",
"self",
".",
"nodes",
":",
"if",
"striptag",
"(",
"node",
".",
"tag",
")",
"==",
"name",
":",
"yield",
"node"
] | Return the direct subnodes with name 'name | [
"Return",
"the",
"direct",
"subnodes",
"with",
"name",
"name"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L458-L462 | train | 233,212 |
gem/oq-engine | openquake/baselib/node.py | Node.append | def append(self, node):
"Append a new subnode"
if not isinstance(node, self.__class__):
raise TypeError('Expected Node instance, got %r' % node)
self.nodes.append(node) | python | def append(self, node):
"Append a new subnode"
if not isinstance(node, self.__class__):
raise TypeError('Expected Node instance, got %r' % node)
self.nodes.append(node) | [
"def",
"append",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"self",
".",
"__class__",
")",
":",
"raise",
"TypeError",
"(",
"'Expected Node instance, got %r'",
"%",
"node",
")",
"self",
".",
"nodes",
".",
"append",
"(",
"node",
")"
] | Append a new subnode | [
"Append",
"a",
"new",
"subnode"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L464-L468 | train | 233,213 |
gem/oq-engine | openquake/baselib/node.py | ValidatingXmlParser.parse_bytes | def parse_bytes(self, bytestr, isfinal=True):
"""
Parse a byte string. If the string is very large, split it in chuncks
and parse each chunk with isfinal=False, then parse an empty chunk
with isfinal=True.
"""
with self._context():
self.filename = None
self.p.Parse(bytestr, isfinal)
return self._root | python | def parse_bytes(self, bytestr, isfinal=True):
"""
Parse a byte string. If the string is very large, split it in chuncks
and parse each chunk with isfinal=False, then parse an empty chunk
with isfinal=True.
"""
with self._context():
self.filename = None
self.p.Parse(bytestr, isfinal)
return self._root | [
"def",
"parse_bytes",
"(",
"self",
",",
"bytestr",
",",
"isfinal",
"=",
"True",
")",
":",
"with",
"self",
".",
"_context",
"(",
")",
":",
"self",
".",
"filename",
"=",
"None",
"self",
".",
"p",
".",
"Parse",
"(",
"bytestr",
",",
"isfinal",
")",
"return",
"self",
".",
"_root"
] | Parse a byte string. If the string is very large, split it in chuncks
and parse each chunk with isfinal=False, then parse an empty chunk
with isfinal=True. | [
"Parse",
"a",
"byte",
"string",
".",
"If",
"the",
"string",
"is",
"very",
"large",
"split",
"it",
"in",
"chuncks",
"and",
"parse",
"each",
"chunk",
"with",
"isfinal",
"=",
"False",
"then",
"parse",
"an",
"empty",
"chunk",
"with",
"isfinal",
"=",
"True",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L815-L824 | train | 233,214 |
gem/oq-engine | openquake/baselib/node.py | ValidatingXmlParser.parse_file | def parse_file(self, file_or_fname):
"""
Parse a file or a filename
"""
with self._context():
if hasattr(file_or_fname, 'read'):
self.filename = getattr(
file_or_fname, 'name', file_or_fname.__class__.__name__)
self.p.ParseFile(file_or_fname)
else:
self.filename = file_or_fname
with open(file_or_fname, 'rb') as f:
self.p.ParseFile(f)
return self._root | python | def parse_file(self, file_or_fname):
"""
Parse a file or a filename
"""
with self._context():
if hasattr(file_or_fname, 'read'):
self.filename = getattr(
file_or_fname, 'name', file_or_fname.__class__.__name__)
self.p.ParseFile(file_or_fname)
else:
self.filename = file_or_fname
with open(file_or_fname, 'rb') as f:
self.p.ParseFile(f)
return self._root | [
"def",
"parse_file",
"(",
"self",
",",
"file_or_fname",
")",
":",
"with",
"self",
".",
"_context",
"(",
")",
":",
"if",
"hasattr",
"(",
"file_or_fname",
",",
"'read'",
")",
":",
"self",
".",
"filename",
"=",
"getattr",
"(",
"file_or_fname",
",",
"'name'",
",",
"file_or_fname",
".",
"__class__",
".",
"__name__",
")",
"self",
".",
"p",
".",
"ParseFile",
"(",
"file_or_fname",
")",
"else",
":",
"self",
".",
"filename",
"=",
"file_or_fname",
"with",
"open",
"(",
"file_or_fname",
",",
"'rb'",
")",
"as",
"f",
":",
"self",
".",
"p",
".",
"ParseFile",
"(",
"f",
")",
"return",
"self",
".",
"_root"
] | Parse a file or a filename | [
"Parse",
"a",
"file",
"or",
"a",
"filename"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L826-L839 | train | 233,215 |
gem/oq-engine | openquake/hmtk/plotting/seismicity/completeness/cumulative_rate_analysis.py | SimpleCumulativeRate._get_magnitudes_from_spacing | def _get_magnitudes_from_spacing(self, magnitudes, delta_m):
'''If a single magnitude spacing is input then create the bins
:param numpy.ndarray magnitudes:
Vector of earthquake magnitudes
:param float delta_m:
Magnitude bin width
:returns: Vector of magnitude bin edges (numpy.ndarray)
'''
min_mag = np.min(magnitudes)
max_mag = np.max(magnitudes)
if (max_mag - min_mag) < delta_m:
raise ValueError('Bin width greater than magnitude range!')
mag_bins = np.arange(np.floor(min_mag), np.ceil(max_mag), delta_m)
# Check to see if there are magnitudes in lower and upper bins
is_mag = np.logical_and(mag_bins - max_mag < delta_m,
min_mag - mag_bins < delta_m)
mag_bins = mag_bins[is_mag]
return mag_bins | python | def _get_magnitudes_from_spacing(self, magnitudes, delta_m):
'''If a single magnitude spacing is input then create the bins
:param numpy.ndarray magnitudes:
Vector of earthquake magnitudes
:param float delta_m:
Magnitude bin width
:returns: Vector of magnitude bin edges (numpy.ndarray)
'''
min_mag = np.min(magnitudes)
max_mag = np.max(magnitudes)
if (max_mag - min_mag) < delta_m:
raise ValueError('Bin width greater than magnitude range!')
mag_bins = np.arange(np.floor(min_mag), np.ceil(max_mag), delta_m)
# Check to see if there are magnitudes in lower and upper bins
is_mag = np.logical_and(mag_bins - max_mag < delta_m,
min_mag - mag_bins < delta_m)
mag_bins = mag_bins[is_mag]
return mag_bins | [
"def",
"_get_magnitudes_from_spacing",
"(",
"self",
",",
"magnitudes",
",",
"delta_m",
")",
":",
"min_mag",
"=",
"np",
".",
"min",
"(",
"magnitudes",
")",
"max_mag",
"=",
"np",
".",
"max",
"(",
"magnitudes",
")",
"if",
"(",
"max_mag",
"-",
"min_mag",
")",
"<",
"delta_m",
":",
"raise",
"ValueError",
"(",
"'Bin width greater than magnitude range!'",
")",
"mag_bins",
"=",
"np",
".",
"arange",
"(",
"np",
".",
"floor",
"(",
"min_mag",
")",
",",
"np",
".",
"ceil",
"(",
"max_mag",
")",
",",
"delta_m",
")",
"# Check to see if there are magnitudes in lower and upper bins",
"is_mag",
"=",
"np",
".",
"logical_and",
"(",
"mag_bins",
"-",
"max_mag",
"<",
"delta_m",
",",
"min_mag",
"-",
"mag_bins",
"<",
"delta_m",
")",
"mag_bins",
"=",
"mag_bins",
"[",
"is_mag",
"]",
"return",
"mag_bins"
] | If a single magnitude spacing is input then create the bins
:param numpy.ndarray magnitudes:
Vector of earthquake magnitudes
:param float delta_m:
Magnitude bin width
:returns: Vector of magnitude bin edges (numpy.ndarray) | [
"If",
"a",
"single",
"magnitude",
"spacing",
"is",
"input",
"then",
"create",
"the",
"bins"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/seismicity/completeness/cumulative_rate_analysis.py#L132-L152 | train | 233,216 |
gem/oq-engine | openquake/hmtk/seismicity/catalogue.py | _merge_data | def _merge_data(dat1, dat2):
"""
Merge two data dictionaries containing catalogue data
:parameter dictionary dat1:
Catalogue data dictionary
:parameter dictionary dat2:
Catalogue data dictionary
:returns:
A catalogue data dictionary containing the information originally
included in dat1 and dat2
"""
cnt = 0
for key in dat1:
flg1 = len(dat1[key]) > 0
flg2 = len(dat2[key]) > 0
if flg1 != flg2:
cnt += 1
if cnt:
raise Warning('Cannot merge catalogues with different' +
' attributes')
return None
else:
for key in dat1:
if isinstance(dat1[key], np.ndarray):
dat1[key] = np.concatenate((dat1[key], dat2[key]), axis=0)
elif isinstance(dat1[key], list):
dat1[key] += dat2[key]
else:
raise ValueError('Unknown type')
return dat1 | python | def _merge_data(dat1, dat2):
"""
Merge two data dictionaries containing catalogue data
:parameter dictionary dat1:
Catalogue data dictionary
:parameter dictionary dat2:
Catalogue data dictionary
:returns:
A catalogue data dictionary containing the information originally
included in dat1 and dat2
"""
cnt = 0
for key in dat1:
flg1 = len(dat1[key]) > 0
flg2 = len(dat2[key]) > 0
if flg1 != flg2:
cnt += 1
if cnt:
raise Warning('Cannot merge catalogues with different' +
' attributes')
return None
else:
for key in dat1:
if isinstance(dat1[key], np.ndarray):
dat1[key] = np.concatenate((dat1[key], dat2[key]), axis=0)
elif isinstance(dat1[key], list):
dat1[key] += dat2[key]
else:
raise ValueError('Unknown type')
return dat1 | [
"def",
"_merge_data",
"(",
"dat1",
",",
"dat2",
")",
":",
"cnt",
"=",
"0",
"for",
"key",
"in",
"dat1",
":",
"flg1",
"=",
"len",
"(",
"dat1",
"[",
"key",
"]",
")",
">",
"0",
"flg2",
"=",
"len",
"(",
"dat2",
"[",
"key",
"]",
")",
">",
"0",
"if",
"flg1",
"!=",
"flg2",
":",
"cnt",
"+=",
"1",
"if",
"cnt",
":",
"raise",
"Warning",
"(",
"'Cannot merge catalogues with different'",
"+",
"' attributes'",
")",
"return",
"None",
"else",
":",
"for",
"key",
"in",
"dat1",
":",
"if",
"isinstance",
"(",
"dat1",
"[",
"key",
"]",
",",
"np",
".",
"ndarray",
")",
":",
"dat1",
"[",
"key",
"]",
"=",
"np",
".",
"concatenate",
"(",
"(",
"dat1",
"[",
"key",
"]",
",",
"dat2",
"[",
"key",
"]",
")",
",",
"axis",
"=",
"0",
")",
"elif",
"isinstance",
"(",
"dat1",
"[",
"key",
"]",
",",
"list",
")",
":",
"dat1",
"[",
"key",
"]",
"+=",
"dat2",
"[",
"key",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"'Unknown type'",
")",
"return",
"dat1"
] | Merge two data dictionaries containing catalogue data
:parameter dictionary dat1:
Catalogue data dictionary
:parameter dictionary dat2:
Catalogue data dictionary
:returns:
A catalogue data dictionary containing the information originally
included in dat1 and dat2 | [
"Merge",
"two",
"data",
"dictionaries",
"containing",
"catalogue",
"data"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/catalogue.py#L566-L600 | train | 233,217 |
gem/oq-engine | openquake/hmtk/seismicity/catalogue.py | Catalogue._get_row_str | def _get_row_str(self, i):
"""
Returns a string representation of the key information in a row
"""
row_data = ["{:s}".format(self.data['eventID'][i]),
"{:g}".format(self.data['year'][i]),
"{:g}".format(self.data['month'][i]),
"{:g}".format(self.data['day'][i]),
"{:g}".format(self.data['hour'][i]),
"{:g}".format(self.data['minute'][i]),
"{:.1f}".format(self.data['second'][i]),
"{:.3f}".format(self.data['longitude'][i]),
"{:.3f}".format(self.data['latitude'][i]),
"{:.1f}".format(self.data['depth'][i]),
"{:.1f}".format(self.data['magnitude'][i])]
return " ".join(row_data) | python | def _get_row_str(self, i):
"""
Returns a string representation of the key information in a row
"""
row_data = ["{:s}".format(self.data['eventID'][i]),
"{:g}".format(self.data['year'][i]),
"{:g}".format(self.data['month'][i]),
"{:g}".format(self.data['day'][i]),
"{:g}".format(self.data['hour'][i]),
"{:g}".format(self.data['minute'][i]),
"{:.1f}".format(self.data['second'][i]),
"{:.3f}".format(self.data['longitude'][i]),
"{:.3f}".format(self.data['latitude'][i]),
"{:.1f}".format(self.data['depth'][i]),
"{:.1f}".format(self.data['magnitude'][i])]
return " ".join(row_data) | [
"def",
"_get_row_str",
"(",
"self",
",",
"i",
")",
":",
"row_data",
"=",
"[",
"\"{:s}\"",
".",
"format",
"(",
"self",
".",
"data",
"[",
"'eventID'",
"]",
"[",
"i",
"]",
")",
",",
"\"{:g}\"",
".",
"format",
"(",
"self",
".",
"data",
"[",
"'year'",
"]",
"[",
"i",
"]",
")",
",",
"\"{:g}\"",
".",
"format",
"(",
"self",
".",
"data",
"[",
"'month'",
"]",
"[",
"i",
"]",
")",
",",
"\"{:g}\"",
".",
"format",
"(",
"self",
".",
"data",
"[",
"'day'",
"]",
"[",
"i",
"]",
")",
",",
"\"{:g}\"",
".",
"format",
"(",
"self",
".",
"data",
"[",
"'hour'",
"]",
"[",
"i",
"]",
")",
",",
"\"{:g}\"",
".",
"format",
"(",
"self",
".",
"data",
"[",
"'minute'",
"]",
"[",
"i",
"]",
")",
",",
"\"{:.1f}\"",
".",
"format",
"(",
"self",
".",
"data",
"[",
"'second'",
"]",
"[",
"i",
"]",
")",
",",
"\"{:.3f}\"",
".",
"format",
"(",
"self",
".",
"data",
"[",
"'longitude'",
"]",
"[",
"i",
"]",
")",
",",
"\"{:.3f}\"",
".",
"format",
"(",
"self",
".",
"data",
"[",
"'latitude'",
"]",
"[",
"i",
"]",
")",
",",
"\"{:.1f}\"",
".",
"format",
"(",
"self",
".",
"data",
"[",
"'depth'",
"]",
"[",
"i",
"]",
")",
",",
"\"{:.1f}\"",
".",
"format",
"(",
"self",
".",
"data",
"[",
"'magnitude'",
"]",
"[",
"i",
"]",
")",
"]",
"return",
"\" \"",
".",
"join",
"(",
"row_data",
")"
] | Returns a string representation of the key information in a row | [
"Returns",
"a",
"string",
"representation",
"of",
"the",
"key",
"information",
"in",
"a",
"row"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/catalogue.py#L138-L153 | train | 233,218 |
gem/oq-engine | openquake/hmtk/seismicity/catalogue.py | Catalogue.load_to_array | def load_to_array(self, keys):
"""
This loads the data contained in the catalogue into a numpy array. The
method works only for float data
:param keys:
A list of keys to be uploaded into the array
:type list:
"""
# Preallocate the numpy array
data = np.empty((len(self.data[keys[0]]), len(keys)))
for i in range(0, len(self.data[keys[0]])):
for j, key in enumerate(keys):
data[i, j] = self.data[key][i]
return data | python | def load_to_array(self, keys):
"""
This loads the data contained in the catalogue into a numpy array. The
method works only for float data
:param keys:
A list of keys to be uploaded into the array
:type list:
"""
# Preallocate the numpy array
data = np.empty((len(self.data[keys[0]]), len(keys)))
for i in range(0, len(self.data[keys[0]])):
for j, key in enumerate(keys):
data[i, j] = self.data[key][i]
return data | [
"def",
"load_to_array",
"(",
"self",
",",
"keys",
")",
":",
"# Preallocate the numpy array",
"data",
"=",
"np",
".",
"empty",
"(",
"(",
"len",
"(",
"self",
".",
"data",
"[",
"keys",
"[",
"0",
"]",
"]",
")",
",",
"len",
"(",
"keys",
")",
")",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"data",
"[",
"keys",
"[",
"0",
"]",
"]",
")",
")",
":",
"for",
"j",
",",
"key",
"in",
"enumerate",
"(",
"keys",
")",
":",
"data",
"[",
"i",
",",
"j",
"]",
"=",
"self",
".",
"data",
"[",
"key",
"]",
"[",
"i",
"]",
"return",
"data"
] | This loads the data contained in the catalogue into a numpy array. The
method works only for float data
:param keys:
A list of keys to be uploaded into the array
:type list: | [
"This",
"loads",
"the",
"data",
"contained",
"in",
"the",
"catalogue",
"into",
"a",
"numpy",
"array",
".",
"The",
"method",
"works",
"only",
"for",
"float",
"data"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/catalogue.py#L223-L237 | train | 233,219 |
gem/oq-engine | openquake/hmtk/seismicity/catalogue.py | Catalogue.load_from_array | def load_from_array(self, keys, data_array):
"""
This loads the data contained in an array into the catalogue object
:param keys:
A list of keys explaining the content of the columns in the array
:type list:
"""
if len(keys) != np.shape(data_array)[1]:
raise ValueError('Key list does not match shape of array!')
for i, key in enumerate(keys):
if key in self.INT_ATTRIBUTE_LIST:
self.data[key] = data_array[:, i].astype(int)
else:
self.data[key] = data_array[:, i]
if key not in self.TOTAL_ATTRIBUTE_LIST:
print('Key %s not a recognised catalogue attribute' % key)
self.update_end_year() | python | def load_from_array(self, keys, data_array):
"""
This loads the data contained in an array into the catalogue object
:param keys:
A list of keys explaining the content of the columns in the array
:type list:
"""
if len(keys) != np.shape(data_array)[1]:
raise ValueError('Key list does not match shape of array!')
for i, key in enumerate(keys):
if key in self.INT_ATTRIBUTE_LIST:
self.data[key] = data_array[:, i].astype(int)
else:
self.data[key] = data_array[:, i]
if key not in self.TOTAL_ATTRIBUTE_LIST:
print('Key %s not a recognised catalogue attribute' % key)
self.update_end_year() | [
"def",
"load_from_array",
"(",
"self",
",",
"keys",
",",
"data_array",
")",
":",
"if",
"len",
"(",
"keys",
")",
"!=",
"np",
".",
"shape",
"(",
"data_array",
")",
"[",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"'Key list does not match shape of array!'",
")",
"for",
"i",
",",
"key",
"in",
"enumerate",
"(",
"keys",
")",
":",
"if",
"key",
"in",
"self",
".",
"INT_ATTRIBUTE_LIST",
":",
"self",
".",
"data",
"[",
"key",
"]",
"=",
"data_array",
"[",
":",
",",
"i",
"]",
".",
"astype",
"(",
"int",
")",
"else",
":",
"self",
".",
"data",
"[",
"key",
"]",
"=",
"data_array",
"[",
":",
",",
"i",
"]",
"if",
"key",
"not",
"in",
"self",
".",
"TOTAL_ATTRIBUTE_LIST",
":",
"print",
"(",
"'Key %s not a recognised catalogue attribute'",
"%",
"key",
")",
"self",
".",
"update_end_year",
"(",
")"
] | This loads the data contained in an array into the catalogue object
:param keys:
A list of keys explaining the content of the columns in the array
:type list: | [
"This",
"loads",
"the",
"data",
"contained",
"in",
"an",
"array",
"into",
"the",
"catalogue",
"object"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/catalogue.py#L239-L259 | train | 233,220 |
gem/oq-engine | openquake/hmtk/seismicity/catalogue.py | Catalogue.catalogue_mt_filter | def catalogue_mt_filter(self, mt_table, flag=None):
"""
Filter the catalogue using a magnitude-time table. The table has
two columns and n-rows.
:param nump.ndarray mt_table:
Magnitude time table with n-rows where column 1 is year and column
2 is magnitude
"""
if flag is None:
# No flag defined, therefore all events are initially valid
flag = np.ones(self.get_number_events(), dtype=bool)
for comp_val in mt_table:
id0 = np.logical_and(self.data['year'].astype(float) < comp_val[0],
self.data['magnitude'] < comp_val[1])
print(id0)
flag[id0] = False
if not np.all(flag):
self.purge_catalogue(flag) | python | def catalogue_mt_filter(self, mt_table, flag=None):
"""
Filter the catalogue using a magnitude-time table. The table has
two columns and n-rows.
:param nump.ndarray mt_table:
Magnitude time table with n-rows where column 1 is year and column
2 is magnitude
"""
if flag is None:
# No flag defined, therefore all events are initially valid
flag = np.ones(self.get_number_events(), dtype=bool)
for comp_val in mt_table:
id0 = np.logical_and(self.data['year'].astype(float) < comp_val[0],
self.data['magnitude'] < comp_val[1])
print(id0)
flag[id0] = False
if not np.all(flag):
self.purge_catalogue(flag) | [
"def",
"catalogue_mt_filter",
"(",
"self",
",",
"mt_table",
",",
"flag",
"=",
"None",
")",
":",
"if",
"flag",
"is",
"None",
":",
"# No flag defined, therefore all events are initially valid",
"flag",
"=",
"np",
".",
"ones",
"(",
"self",
".",
"get_number_events",
"(",
")",
",",
"dtype",
"=",
"bool",
")",
"for",
"comp_val",
"in",
"mt_table",
":",
"id0",
"=",
"np",
".",
"logical_and",
"(",
"self",
".",
"data",
"[",
"'year'",
"]",
".",
"astype",
"(",
"float",
")",
"<",
"comp_val",
"[",
"0",
"]",
",",
"self",
".",
"data",
"[",
"'magnitude'",
"]",
"<",
"comp_val",
"[",
"1",
"]",
")",
"print",
"(",
"id0",
")",
"flag",
"[",
"id0",
"]",
"=",
"False",
"if",
"not",
"np",
".",
"all",
"(",
"flag",
")",
":",
"self",
".",
"purge_catalogue",
"(",
"flag",
")"
] | Filter the catalogue using a magnitude-time table. The table has
two columns and n-rows.
:param nump.ndarray mt_table:
Magnitude time table with n-rows where column 1 is year and column
2 is magnitude | [
"Filter",
"the",
"catalogue",
"using",
"a",
"magnitude",
"-",
"time",
"table",
".",
"The",
"table",
"has",
"two",
"columns",
"and",
"n",
"-",
"rows",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/catalogue.py#L282-L302 | train | 233,221 |
gem/oq-engine | openquake/hmtk/seismicity/catalogue.py | Catalogue.get_bounding_box | def get_bounding_box(self):
"""
Returns the bounding box of the catalogue
:returns: (West, East, South, North)
"""
return (np.min(self.data["longitude"]),
np.max(self.data["longitude"]),
np.min(self.data["latitude"]),
np.max(self.data["latitude"])) | python | def get_bounding_box(self):
"""
Returns the bounding box of the catalogue
:returns: (West, East, South, North)
"""
return (np.min(self.data["longitude"]),
np.max(self.data["longitude"]),
np.min(self.data["latitude"]),
np.max(self.data["latitude"])) | [
"def",
"get_bounding_box",
"(",
"self",
")",
":",
"return",
"(",
"np",
".",
"min",
"(",
"self",
".",
"data",
"[",
"\"longitude\"",
"]",
")",
",",
"np",
".",
"max",
"(",
"self",
".",
"data",
"[",
"\"longitude\"",
"]",
")",
",",
"np",
".",
"min",
"(",
"self",
".",
"data",
"[",
"\"latitude\"",
"]",
")",
",",
"np",
".",
"max",
"(",
"self",
".",
"data",
"[",
"\"latitude\"",
"]",
")",
")"
] | Returns the bounding box of the catalogue
:returns: (West, East, South, North) | [
"Returns",
"the",
"bounding",
"box",
"of",
"the",
"catalogue"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/catalogue.py#L304-L313 | train | 233,222 |
gem/oq-engine | openquake/hmtk/seismicity/catalogue.py | Catalogue.get_decimal_time | def get_decimal_time(self):
'''
Returns the time of the catalogue as a decimal
'''
return decimal_time(self.data['year'],
self.data['month'],
self.data['day'],
self.data['hour'],
self.data['minute'],
self.data['second']) | python | def get_decimal_time(self):
'''
Returns the time of the catalogue as a decimal
'''
return decimal_time(self.data['year'],
self.data['month'],
self.data['day'],
self.data['hour'],
self.data['minute'],
self.data['second']) | [
"def",
"get_decimal_time",
"(",
"self",
")",
":",
"return",
"decimal_time",
"(",
"self",
".",
"data",
"[",
"'year'",
"]",
",",
"self",
".",
"data",
"[",
"'month'",
"]",
",",
"self",
".",
"data",
"[",
"'day'",
"]",
",",
"self",
".",
"data",
"[",
"'hour'",
"]",
",",
"self",
".",
"data",
"[",
"'minute'",
"]",
",",
"self",
".",
"data",
"[",
"'second'",
"]",
")"
] | Returns the time of the catalogue as a decimal | [
"Returns",
"the",
"time",
"of",
"the",
"catalogue",
"as",
"a",
"decimal"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/catalogue.py#L326-L335 | train | 233,223 |
gem/oq-engine | openquake/hmtk/seismicity/catalogue.py | Catalogue.sort_catalogue_chronologically | def sort_catalogue_chronologically(self):
'''
Sorts the catalogue into chronological order
'''
dec_time = self.get_decimal_time()
idx = np.argsort(dec_time)
if np.all((idx[1:] - idx[:-1]) > 0.):
# Catalogue was already in chronological order
return
self.select_catalogue_events(idx) | python | def sort_catalogue_chronologically(self):
'''
Sorts the catalogue into chronological order
'''
dec_time = self.get_decimal_time()
idx = np.argsort(dec_time)
if np.all((idx[1:] - idx[:-1]) > 0.):
# Catalogue was already in chronological order
return
self.select_catalogue_events(idx) | [
"def",
"sort_catalogue_chronologically",
"(",
"self",
")",
":",
"dec_time",
"=",
"self",
".",
"get_decimal_time",
"(",
")",
"idx",
"=",
"np",
".",
"argsort",
"(",
"dec_time",
")",
"if",
"np",
".",
"all",
"(",
"(",
"idx",
"[",
"1",
":",
"]",
"-",
"idx",
"[",
":",
"-",
"1",
"]",
")",
">",
"0.",
")",
":",
"# Catalogue was already in chronological order",
"return",
"self",
".",
"select_catalogue_events",
"(",
"idx",
")"
] | Sorts the catalogue into chronological order | [
"Sorts",
"the",
"catalogue",
"into",
"chronological",
"order"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/catalogue.py#L353-L362 | train | 233,224 |
gem/oq-engine | openquake/hmtk/seismicity/catalogue.py | Catalogue.purge_catalogue | def purge_catalogue(self, flag_vector):
'''
Purges present catalogue with invalid events defined by flag_vector
:param numpy.ndarray flag_vector:
Boolean vector showing if events are selected (True) or not (False)
'''
id0 = np.where(flag_vector)[0]
self.select_catalogue_events(id0)
self.get_number_events() | python | def purge_catalogue(self, flag_vector):
'''
Purges present catalogue with invalid events defined by flag_vector
:param numpy.ndarray flag_vector:
Boolean vector showing if events are selected (True) or not (False)
'''
id0 = np.where(flag_vector)[0]
self.select_catalogue_events(id0)
self.get_number_events() | [
"def",
"purge_catalogue",
"(",
"self",
",",
"flag_vector",
")",
":",
"id0",
"=",
"np",
".",
"where",
"(",
"flag_vector",
")",
"[",
"0",
"]",
"self",
".",
"select_catalogue_events",
"(",
"id0",
")",
"self",
".",
"get_number_events",
"(",
")"
] | Purges present catalogue with invalid events defined by flag_vector
:param numpy.ndarray flag_vector:
Boolean vector showing if events are selected (True) or not (False) | [
"Purges",
"present",
"catalogue",
"with",
"invalid",
"events",
"defined",
"by",
"flag_vector"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/catalogue.py#L364-L374 | train | 233,225 |
gem/oq-engine | openquake/hmtk/seismicity/catalogue.py | Catalogue.select_catalogue_events | def select_catalogue_events(self, id0):
'''
Orders the events in the catalogue according to an indexing vector.
:param np.ndarray id0:
Pointer array indicating the locations of selected events
'''
for key in self.data:
if isinstance(
self.data[key], np.ndarray) and len(self.data[key]) > 0:
# Dictionary element is numpy array - use logical indexing
self.data[key] = self.data[key][id0]
elif isinstance(
self.data[key], list) and len(self.data[key]) > 0:
# Dictionary element is list
self.data[key] = [self.data[key][iloc] for iloc in id0]
else:
continue | python | def select_catalogue_events(self, id0):
'''
Orders the events in the catalogue according to an indexing vector.
:param np.ndarray id0:
Pointer array indicating the locations of selected events
'''
for key in self.data:
if isinstance(
self.data[key], np.ndarray) and len(self.data[key]) > 0:
# Dictionary element is numpy array - use logical indexing
self.data[key] = self.data[key][id0]
elif isinstance(
self.data[key], list) and len(self.data[key]) > 0:
# Dictionary element is list
self.data[key] = [self.data[key][iloc] for iloc in id0]
else:
continue | [
"def",
"select_catalogue_events",
"(",
"self",
",",
"id0",
")",
":",
"for",
"key",
"in",
"self",
".",
"data",
":",
"if",
"isinstance",
"(",
"self",
".",
"data",
"[",
"key",
"]",
",",
"np",
".",
"ndarray",
")",
"and",
"len",
"(",
"self",
".",
"data",
"[",
"key",
"]",
")",
">",
"0",
":",
"# Dictionary element is numpy array - use logical indexing",
"self",
".",
"data",
"[",
"key",
"]",
"=",
"self",
".",
"data",
"[",
"key",
"]",
"[",
"id0",
"]",
"elif",
"isinstance",
"(",
"self",
".",
"data",
"[",
"key",
"]",
",",
"list",
")",
"and",
"len",
"(",
"self",
".",
"data",
"[",
"key",
"]",
")",
">",
"0",
":",
"# Dictionary element is list",
"self",
".",
"data",
"[",
"key",
"]",
"=",
"[",
"self",
".",
"data",
"[",
"key",
"]",
"[",
"iloc",
"]",
"for",
"iloc",
"in",
"id0",
"]",
"else",
":",
"continue"
] | Orders the events in the catalogue according to an indexing vector.
:param np.ndarray id0:
Pointer array indicating the locations of selected events | [
"Orders",
"the",
"events",
"in",
"the",
"catalogue",
"according",
"to",
"an",
"indexing",
"vector",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/catalogue.py#L376-L393 | train | 233,226 |
gem/oq-engine | openquake/hmtk/seismicity/catalogue.py | Catalogue.get_depth_distribution | def get_depth_distribution(self, depth_bins, normalisation=False,
bootstrap=None):
'''
Gets the depth distribution of the earthquake catalogue to return a
single histogram. Depths may be normalised. If uncertainties are found
in the catalogue the distrbution may be bootstrap sampled
:param numpy.ndarray depth_bins:
getBin edges for the depths
:param bool normalisation:
Choose to normalise the results such that the total contributions
sum to 1.0 (True) or not (False)
:param int bootstrap:
Number of bootstrap samples
:returns:
Histogram of depth values
'''
if len(self.data['depth']) == 0:
# If depth information is missing
raise ValueError('Depths missing in catalogue')
if len(self.data['depthError']) == 0:
self.data['depthError'] = np.zeros(self.get_number_events(),
dtype=float)
return bootstrap_histogram_1D(self.data['depth'],
depth_bins,
self.data['depthError'],
normalisation=normalisation,
number_bootstraps=bootstrap,
boundaries=(0., None)) | python | def get_depth_distribution(self, depth_bins, normalisation=False,
bootstrap=None):
'''
Gets the depth distribution of the earthquake catalogue to return a
single histogram. Depths may be normalised. If uncertainties are found
in the catalogue the distrbution may be bootstrap sampled
:param numpy.ndarray depth_bins:
getBin edges for the depths
:param bool normalisation:
Choose to normalise the results such that the total contributions
sum to 1.0 (True) or not (False)
:param int bootstrap:
Number of bootstrap samples
:returns:
Histogram of depth values
'''
if len(self.data['depth']) == 0:
# If depth information is missing
raise ValueError('Depths missing in catalogue')
if len(self.data['depthError']) == 0:
self.data['depthError'] = np.zeros(self.get_number_events(),
dtype=float)
return bootstrap_histogram_1D(self.data['depth'],
depth_bins,
self.data['depthError'],
normalisation=normalisation,
number_bootstraps=bootstrap,
boundaries=(0., None)) | [
"def",
"get_depth_distribution",
"(",
"self",
",",
"depth_bins",
",",
"normalisation",
"=",
"False",
",",
"bootstrap",
"=",
"None",
")",
":",
"if",
"len",
"(",
"self",
".",
"data",
"[",
"'depth'",
"]",
")",
"==",
"0",
":",
"# If depth information is missing",
"raise",
"ValueError",
"(",
"'Depths missing in catalogue'",
")",
"if",
"len",
"(",
"self",
".",
"data",
"[",
"'depthError'",
"]",
")",
"==",
"0",
":",
"self",
".",
"data",
"[",
"'depthError'",
"]",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"get_number_events",
"(",
")",
",",
"dtype",
"=",
"float",
")",
"return",
"bootstrap_histogram_1D",
"(",
"self",
".",
"data",
"[",
"'depth'",
"]",
",",
"depth_bins",
",",
"self",
".",
"data",
"[",
"'depthError'",
"]",
",",
"normalisation",
"=",
"normalisation",
",",
"number_bootstraps",
"=",
"bootstrap",
",",
"boundaries",
"=",
"(",
"0.",
",",
"None",
")",
")"
] | Gets the depth distribution of the earthquake catalogue to return a
single histogram. Depths may be normalised. If uncertainties are found
in the catalogue the distrbution may be bootstrap sampled
:param numpy.ndarray depth_bins:
getBin edges for the depths
:param bool normalisation:
Choose to normalise the results such that the total contributions
sum to 1.0 (True) or not (False)
:param int bootstrap:
Number of bootstrap samples
:returns:
Histogram of depth values | [
"Gets",
"the",
"depth",
"distribution",
"of",
"the",
"earthquake",
"catalogue",
"to",
"return",
"a",
"single",
"histogram",
".",
"Depths",
"may",
"be",
"normalised",
".",
"If",
"uncertainties",
"are",
"found",
"in",
"the",
"catalogue",
"the",
"distrbution",
"may",
"be",
"bootstrap",
"sampled"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/catalogue.py#L395-L429 | train | 233,227 |
gem/oq-engine | openquake/hmtk/seismicity/catalogue.py | Catalogue.get_depth_pmf | def get_depth_pmf(self, depth_bins, default_depth=5.0, bootstrap=None):
"""
Returns the depth distribution of the catalogue as a probability mass
function
"""
if len(self.data['depth']) == 0:
# If depth information is missing
return PMF([(1.0, default_depth)])
# Get the depth distribution
depth_hist = self.get_depth_distribution(depth_bins,
normalisation=True,
bootstrap=bootstrap)
# If the histogram does not sum to 1.0 then remove the difference
# from the lowest bin
depth_hist = np.around(depth_hist, 3)
while depth_hist.sum() - 1.0:
depth_hist[-1] -= depth_hist.sum() - 1.0
depth_hist = np.around(depth_hist, 3)
pmf_list = []
for iloc, prob in enumerate(depth_hist):
pmf_list.append((prob,
(depth_bins[iloc] + depth_bins[iloc + 1]) / 2.0))
return PMF(pmf_list) | python | def get_depth_pmf(self, depth_bins, default_depth=5.0, bootstrap=None):
"""
Returns the depth distribution of the catalogue as a probability mass
function
"""
if len(self.data['depth']) == 0:
# If depth information is missing
return PMF([(1.0, default_depth)])
# Get the depth distribution
depth_hist = self.get_depth_distribution(depth_bins,
normalisation=True,
bootstrap=bootstrap)
# If the histogram does not sum to 1.0 then remove the difference
# from the lowest bin
depth_hist = np.around(depth_hist, 3)
while depth_hist.sum() - 1.0:
depth_hist[-1] -= depth_hist.sum() - 1.0
depth_hist = np.around(depth_hist, 3)
pmf_list = []
for iloc, prob in enumerate(depth_hist):
pmf_list.append((prob,
(depth_bins[iloc] + depth_bins[iloc + 1]) / 2.0))
return PMF(pmf_list) | [
"def",
"get_depth_pmf",
"(",
"self",
",",
"depth_bins",
",",
"default_depth",
"=",
"5.0",
",",
"bootstrap",
"=",
"None",
")",
":",
"if",
"len",
"(",
"self",
".",
"data",
"[",
"'depth'",
"]",
")",
"==",
"0",
":",
"# If depth information is missing",
"return",
"PMF",
"(",
"[",
"(",
"1.0",
",",
"default_depth",
")",
"]",
")",
"# Get the depth distribution",
"depth_hist",
"=",
"self",
".",
"get_depth_distribution",
"(",
"depth_bins",
",",
"normalisation",
"=",
"True",
",",
"bootstrap",
"=",
"bootstrap",
")",
"# If the histogram does not sum to 1.0 then remove the difference",
"# from the lowest bin",
"depth_hist",
"=",
"np",
".",
"around",
"(",
"depth_hist",
",",
"3",
")",
"while",
"depth_hist",
".",
"sum",
"(",
")",
"-",
"1.0",
":",
"depth_hist",
"[",
"-",
"1",
"]",
"-=",
"depth_hist",
".",
"sum",
"(",
")",
"-",
"1.0",
"depth_hist",
"=",
"np",
".",
"around",
"(",
"depth_hist",
",",
"3",
")",
"pmf_list",
"=",
"[",
"]",
"for",
"iloc",
",",
"prob",
"in",
"enumerate",
"(",
"depth_hist",
")",
":",
"pmf_list",
".",
"append",
"(",
"(",
"prob",
",",
"(",
"depth_bins",
"[",
"iloc",
"]",
"+",
"depth_bins",
"[",
"iloc",
"+",
"1",
"]",
")",
"/",
"2.0",
")",
")",
"return",
"PMF",
"(",
"pmf_list",
")"
] | Returns the depth distribution of the catalogue as a probability mass
function | [
"Returns",
"the",
"depth",
"distribution",
"of",
"the",
"catalogue",
"as",
"a",
"probability",
"mass",
"function"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/catalogue.py#L431-L454 | train | 233,228 |
gem/oq-engine | openquake/hmtk/seismicity/catalogue.py | Catalogue.get_magnitude_depth_distribution | def get_magnitude_depth_distribution(self, magnitude_bins, depth_bins,
normalisation=False, bootstrap=None):
'''
Returns a 2-D magnitude-depth histogram for the catalogue
:param numpy.ndarray magnitude_bins:
Bin edges for the magnitudes
:param numpy.ndarray depth_bins:
Bin edges for the depths
:param bool normalisation:
Choose to normalise the results such that the total contributions
sum to 1.0 (True) or not (False)
:param int bootstrap:
Number of bootstrap samples
:returns:
2D histogram of events in magnitude-depth bins
'''
if len(self.data['depth']) == 0:
# If depth information is missing
raise ValueError('Depths missing in catalogue')
if len(self.data['depthError']) == 0:
self.data['depthError'] = np.zeros(self.get_number_events(),
dtype=float)
if len(self.data['sigmaMagnitude']) == 0:
self.data['sigmaMagnitude'] = np.zeros(self.get_number_events(),
dtype=float)
return bootstrap_histogram_2D(self.data['magnitude'],
self.data['depth'],
magnitude_bins,
depth_bins,
boundaries=[(0., None), (None, None)],
xsigma=self.data['sigmaMagnitude'],
ysigma=self.data['depthError'],
normalisation=normalisation,
number_bootstraps=bootstrap) | python | def get_magnitude_depth_distribution(self, magnitude_bins, depth_bins,
normalisation=False, bootstrap=None):
'''
Returns a 2-D magnitude-depth histogram for the catalogue
:param numpy.ndarray magnitude_bins:
Bin edges for the magnitudes
:param numpy.ndarray depth_bins:
Bin edges for the depths
:param bool normalisation:
Choose to normalise the results such that the total contributions
sum to 1.0 (True) or not (False)
:param int bootstrap:
Number of bootstrap samples
:returns:
2D histogram of events in magnitude-depth bins
'''
if len(self.data['depth']) == 0:
# If depth information is missing
raise ValueError('Depths missing in catalogue')
if len(self.data['depthError']) == 0:
self.data['depthError'] = np.zeros(self.get_number_events(),
dtype=float)
if len(self.data['sigmaMagnitude']) == 0:
self.data['sigmaMagnitude'] = np.zeros(self.get_number_events(),
dtype=float)
return bootstrap_histogram_2D(self.data['magnitude'],
self.data['depth'],
magnitude_bins,
depth_bins,
boundaries=[(0., None), (None, None)],
xsigma=self.data['sigmaMagnitude'],
ysigma=self.data['depthError'],
normalisation=normalisation,
number_bootstraps=bootstrap) | [
"def",
"get_magnitude_depth_distribution",
"(",
"self",
",",
"magnitude_bins",
",",
"depth_bins",
",",
"normalisation",
"=",
"False",
",",
"bootstrap",
"=",
"None",
")",
":",
"if",
"len",
"(",
"self",
".",
"data",
"[",
"'depth'",
"]",
")",
"==",
"0",
":",
"# If depth information is missing",
"raise",
"ValueError",
"(",
"'Depths missing in catalogue'",
")",
"if",
"len",
"(",
"self",
".",
"data",
"[",
"'depthError'",
"]",
")",
"==",
"0",
":",
"self",
".",
"data",
"[",
"'depthError'",
"]",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"get_number_events",
"(",
")",
",",
"dtype",
"=",
"float",
")",
"if",
"len",
"(",
"self",
".",
"data",
"[",
"'sigmaMagnitude'",
"]",
")",
"==",
"0",
":",
"self",
".",
"data",
"[",
"'sigmaMagnitude'",
"]",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"get_number_events",
"(",
")",
",",
"dtype",
"=",
"float",
")",
"return",
"bootstrap_histogram_2D",
"(",
"self",
".",
"data",
"[",
"'magnitude'",
"]",
",",
"self",
".",
"data",
"[",
"'depth'",
"]",
",",
"magnitude_bins",
",",
"depth_bins",
",",
"boundaries",
"=",
"[",
"(",
"0.",
",",
"None",
")",
",",
"(",
"None",
",",
"None",
")",
"]",
",",
"xsigma",
"=",
"self",
".",
"data",
"[",
"'sigmaMagnitude'",
"]",
",",
"ysigma",
"=",
"self",
".",
"data",
"[",
"'depthError'",
"]",
",",
"normalisation",
"=",
"normalisation",
",",
"number_bootstraps",
"=",
"bootstrap",
")"
] | Returns a 2-D magnitude-depth histogram for the catalogue
:param numpy.ndarray magnitude_bins:
Bin edges for the magnitudes
:param numpy.ndarray depth_bins:
Bin edges for the depths
:param bool normalisation:
Choose to normalise the results such that the total contributions
sum to 1.0 (True) or not (False)
:param int bootstrap:
Number of bootstrap samples
:returns:
2D histogram of events in magnitude-depth bins | [
"Returns",
"a",
"2",
"-",
"D",
"magnitude",
"-",
"depth",
"histogram",
"for",
"the",
"catalogue"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/catalogue.py#L456-L497 | train | 233,229 |
gem/oq-engine | openquake/hmtk/seismicity/catalogue.py | Catalogue.get_magnitude_time_distribution | def get_magnitude_time_distribution(self, magnitude_bins, time_bins,
normalisation=False, bootstrap=None):
'''
Returns a 2-D histogram indicating the number of earthquakes in a
set of time-magnitude bins. Time is in decimal years!
:param numpy.ndarray magnitude_bins:
Bin edges for the magnitudes
:param numpy.ndarray time_bins:
Bin edges for the times
:param bool normalisation:
Choose to normalise the results such that the total contributions
sum to 1.0 (True) or not (False)
:param int bootstrap:
Number of bootstrap samples
:returns:
2D histogram of events in magnitude-year bins
'''
return bootstrap_histogram_2D(
self.get_decimal_time(),
self.data['magnitude'],
time_bins,
magnitude_bins,
xsigma=np.zeros(self.get_number_events()),
ysigma=self.data['sigmaMagnitude'],
normalisation=normalisation,
number_bootstraps=bootstrap) | python | def get_magnitude_time_distribution(self, magnitude_bins, time_bins,
normalisation=False, bootstrap=None):
'''
Returns a 2-D histogram indicating the number of earthquakes in a
set of time-magnitude bins. Time is in decimal years!
:param numpy.ndarray magnitude_bins:
Bin edges for the magnitudes
:param numpy.ndarray time_bins:
Bin edges for the times
:param bool normalisation:
Choose to normalise the results such that the total contributions
sum to 1.0 (True) or not (False)
:param int bootstrap:
Number of bootstrap samples
:returns:
2D histogram of events in magnitude-year bins
'''
return bootstrap_histogram_2D(
self.get_decimal_time(),
self.data['magnitude'],
time_bins,
magnitude_bins,
xsigma=np.zeros(self.get_number_events()),
ysigma=self.data['sigmaMagnitude'],
normalisation=normalisation,
number_bootstraps=bootstrap) | [
"def",
"get_magnitude_time_distribution",
"(",
"self",
",",
"magnitude_bins",
",",
"time_bins",
",",
"normalisation",
"=",
"False",
",",
"bootstrap",
"=",
"None",
")",
":",
"return",
"bootstrap_histogram_2D",
"(",
"self",
".",
"get_decimal_time",
"(",
")",
",",
"self",
".",
"data",
"[",
"'magnitude'",
"]",
",",
"time_bins",
",",
"magnitude_bins",
",",
"xsigma",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"get_number_events",
"(",
")",
")",
",",
"ysigma",
"=",
"self",
".",
"data",
"[",
"'sigmaMagnitude'",
"]",
",",
"normalisation",
"=",
"normalisation",
",",
"number_bootstraps",
"=",
"bootstrap",
")"
] | Returns a 2-D histogram indicating the number of earthquakes in a
set of time-magnitude bins. Time is in decimal years!
:param numpy.ndarray magnitude_bins:
Bin edges for the magnitudes
:param numpy.ndarray time_bins:
Bin edges for the times
:param bool normalisation:
Choose to normalise the results such that the total contributions
sum to 1.0 (True) or not (False)
:param int bootstrap:
Number of bootstrap samples
:returns:
2D histogram of events in magnitude-year bins | [
"Returns",
"a",
"2",
"-",
"D",
"histogram",
"indicating",
"the",
"number",
"of",
"earthquakes",
"in",
"a",
"set",
"of",
"time",
"-",
"magnitude",
"bins",
".",
"Time",
"is",
"in",
"decimal",
"years!"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/catalogue.py#L499-L529 | train | 233,230 |
gem/oq-engine | openquake/hmtk/seismicity/catalogue.py | Catalogue.concatenate | def concatenate(self, catalogue):
"""
This method attaches one catalogue to the current one
:parameter catalogue:
An instance of :class:`htmk.seismicity.catalogue.Catalogue`
"""
atts = getattr(self, 'data')
attn = getattr(catalogue, 'data')
data = _merge_data(atts, attn)
if data is not None:
setattr(self, 'data', data)
for attrib in vars(self):
atts = getattr(self, attrib)
attn = getattr(catalogue, attrib)
if attrib is 'end_year':
setattr(self, attrib, max(atts, attn))
elif attrib is 'start_year':
setattr(self, attrib, min(atts, attn))
elif attrib is 'data':
pass
elif attrib is 'number_earthquakes':
setattr(self, attrib, atts + attn)
elif attrib is 'processes':
if atts != attn:
raise ValueError('The catalogues cannot be merged' +
' since the they have' +
' a different processing history')
else:
raise ValueError('unknown attribute: %s' % attrib)
self.sort_catalogue_chronologically() | python | def concatenate(self, catalogue):
"""
This method attaches one catalogue to the current one
:parameter catalogue:
An instance of :class:`htmk.seismicity.catalogue.Catalogue`
"""
atts = getattr(self, 'data')
attn = getattr(catalogue, 'data')
data = _merge_data(atts, attn)
if data is not None:
setattr(self, 'data', data)
for attrib in vars(self):
atts = getattr(self, attrib)
attn = getattr(catalogue, attrib)
if attrib is 'end_year':
setattr(self, attrib, max(atts, attn))
elif attrib is 'start_year':
setattr(self, attrib, min(atts, attn))
elif attrib is 'data':
pass
elif attrib is 'number_earthquakes':
setattr(self, attrib, atts + attn)
elif attrib is 'processes':
if atts != attn:
raise ValueError('The catalogues cannot be merged' +
' since the they have' +
' a different processing history')
else:
raise ValueError('unknown attribute: %s' % attrib)
self.sort_catalogue_chronologically() | [
"def",
"concatenate",
"(",
"self",
",",
"catalogue",
")",
":",
"atts",
"=",
"getattr",
"(",
"self",
",",
"'data'",
")",
"attn",
"=",
"getattr",
"(",
"catalogue",
",",
"'data'",
")",
"data",
"=",
"_merge_data",
"(",
"atts",
",",
"attn",
")",
"if",
"data",
"is",
"not",
"None",
":",
"setattr",
"(",
"self",
",",
"'data'",
",",
"data",
")",
"for",
"attrib",
"in",
"vars",
"(",
"self",
")",
":",
"atts",
"=",
"getattr",
"(",
"self",
",",
"attrib",
")",
"attn",
"=",
"getattr",
"(",
"catalogue",
",",
"attrib",
")",
"if",
"attrib",
"is",
"'end_year'",
":",
"setattr",
"(",
"self",
",",
"attrib",
",",
"max",
"(",
"atts",
",",
"attn",
")",
")",
"elif",
"attrib",
"is",
"'start_year'",
":",
"setattr",
"(",
"self",
",",
"attrib",
",",
"min",
"(",
"atts",
",",
"attn",
")",
")",
"elif",
"attrib",
"is",
"'data'",
":",
"pass",
"elif",
"attrib",
"is",
"'number_earthquakes'",
":",
"setattr",
"(",
"self",
",",
"attrib",
",",
"atts",
"+",
"attn",
")",
"elif",
"attrib",
"is",
"'processes'",
":",
"if",
"atts",
"!=",
"attn",
":",
"raise",
"ValueError",
"(",
"'The catalogues cannot be merged'",
"+",
"' since the they have'",
"+",
"' a different processing history'",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'unknown attribute: %s'",
"%",
"attrib",
")",
"self",
".",
"sort_catalogue_chronologically",
"(",
")"
] | This method attaches one catalogue to the current one
:parameter catalogue:
An instance of :class:`htmk.seismicity.catalogue.Catalogue` | [
"This",
"method",
"attaches",
"one",
"catalogue",
"to",
"the",
"current",
"one"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/catalogue.py#L531-L563 | train | 233,231 |
gem/oq-engine | openquake/engine/engine.py | expose_outputs | def expose_outputs(dstore, owner=getpass.getuser(), status='complete'):
"""
Build a correspondence between the outputs in the datastore and the
ones in the database.
:param dstore: datastore
"""
oq = dstore['oqparam']
exportable = set(ekey[0] for ekey in export.export)
calcmode = oq.calculation_mode
dskeys = set(dstore) & exportable # exportable datastore keys
dskeys.add('fullreport')
rlzs = dstore['csm_info'].rlzs
if len(rlzs) > 1:
dskeys.add('realizations')
if len(dstore['csm_info/sg_data']) > 1: # export sourcegroups.csv
dskeys.add('sourcegroups')
hdf5 = dstore.hdf5
if 'hcurves-stats' in hdf5 or 'hcurves-rlzs' in hdf5:
if oq.hazard_stats() or oq.individual_curves or len(rlzs) == 1:
dskeys.add('hcurves')
if oq.uniform_hazard_spectra:
dskeys.add('uhs') # export them
if oq.hazard_maps:
dskeys.add('hmaps') # export them
if 'avg_losses-stats' in dstore or (
'avg_losses-rlzs' in dstore and len(rlzs)):
dskeys.add('avg_losses-stats')
if 'curves-rlzs' in dstore and len(rlzs) == 1:
dskeys.add('loss_curves-rlzs')
if 'curves-stats' in dstore and len(rlzs) > 1:
dskeys.add('loss_curves-stats')
if oq.conditional_loss_poes: # expose loss_maps outputs
if 'loss_curves-stats' in dstore:
dskeys.add('loss_maps-stats')
if 'all_loss_ratios' in dskeys:
dskeys.remove('all_loss_ratios') # export only specific IDs
if 'ruptures' in dskeys and 'scenario' in calcmode:
exportable.remove('ruptures') # do not export, as requested by Vitor
if 'rup_loss_table' in dskeys: # keep it hidden for the moment
dskeys.remove('rup_loss_table')
if 'hmaps' in dskeys and not oq.hazard_maps:
dskeys.remove('hmaps') # do not export the hazard maps
if logs.dbcmd('get_job', dstore.calc_id) is None:
# the calculation has not been imported in the db yet
logs.dbcmd('import_job', dstore.calc_id, oq.calculation_mode,
oq.description + ' [parent]', owner, status,
oq.hazard_calculation_id, dstore.datadir)
keysize = []
for key in sorted(dskeys & exportable):
try:
size_mb = dstore.get_attr(key, 'nbytes') / MB
except (KeyError, AttributeError):
size_mb = None
keysize.append((key, size_mb))
ds_size = os.path.getsize(dstore.filename) / MB
logs.dbcmd('create_outputs', dstore.calc_id, keysize, ds_size) | python | def expose_outputs(dstore, owner=getpass.getuser(), status='complete'):
"""
Build a correspondence between the outputs in the datastore and the
ones in the database.
:param dstore: datastore
"""
oq = dstore['oqparam']
exportable = set(ekey[0] for ekey in export.export)
calcmode = oq.calculation_mode
dskeys = set(dstore) & exportable # exportable datastore keys
dskeys.add('fullreport')
rlzs = dstore['csm_info'].rlzs
if len(rlzs) > 1:
dskeys.add('realizations')
if len(dstore['csm_info/sg_data']) > 1: # export sourcegroups.csv
dskeys.add('sourcegroups')
hdf5 = dstore.hdf5
if 'hcurves-stats' in hdf5 or 'hcurves-rlzs' in hdf5:
if oq.hazard_stats() or oq.individual_curves or len(rlzs) == 1:
dskeys.add('hcurves')
if oq.uniform_hazard_spectra:
dskeys.add('uhs') # export them
if oq.hazard_maps:
dskeys.add('hmaps') # export them
if 'avg_losses-stats' in dstore or (
'avg_losses-rlzs' in dstore and len(rlzs)):
dskeys.add('avg_losses-stats')
if 'curves-rlzs' in dstore and len(rlzs) == 1:
dskeys.add('loss_curves-rlzs')
if 'curves-stats' in dstore and len(rlzs) > 1:
dskeys.add('loss_curves-stats')
if oq.conditional_loss_poes: # expose loss_maps outputs
if 'loss_curves-stats' in dstore:
dskeys.add('loss_maps-stats')
if 'all_loss_ratios' in dskeys:
dskeys.remove('all_loss_ratios') # export only specific IDs
if 'ruptures' in dskeys and 'scenario' in calcmode:
exportable.remove('ruptures') # do not export, as requested by Vitor
if 'rup_loss_table' in dskeys: # keep it hidden for the moment
dskeys.remove('rup_loss_table')
if 'hmaps' in dskeys and not oq.hazard_maps:
dskeys.remove('hmaps') # do not export the hazard maps
if logs.dbcmd('get_job', dstore.calc_id) is None:
# the calculation has not been imported in the db yet
logs.dbcmd('import_job', dstore.calc_id, oq.calculation_mode,
oq.description + ' [parent]', owner, status,
oq.hazard_calculation_id, dstore.datadir)
keysize = []
for key in sorted(dskeys & exportable):
try:
size_mb = dstore.get_attr(key, 'nbytes') / MB
except (KeyError, AttributeError):
size_mb = None
keysize.append((key, size_mb))
ds_size = os.path.getsize(dstore.filename) / MB
logs.dbcmd('create_outputs', dstore.calc_id, keysize, ds_size) | [
"def",
"expose_outputs",
"(",
"dstore",
",",
"owner",
"=",
"getpass",
".",
"getuser",
"(",
")",
",",
"status",
"=",
"'complete'",
")",
":",
"oq",
"=",
"dstore",
"[",
"'oqparam'",
"]",
"exportable",
"=",
"set",
"(",
"ekey",
"[",
"0",
"]",
"for",
"ekey",
"in",
"export",
".",
"export",
")",
"calcmode",
"=",
"oq",
".",
"calculation_mode",
"dskeys",
"=",
"set",
"(",
"dstore",
")",
"&",
"exportable",
"# exportable datastore keys",
"dskeys",
".",
"add",
"(",
"'fullreport'",
")",
"rlzs",
"=",
"dstore",
"[",
"'csm_info'",
"]",
".",
"rlzs",
"if",
"len",
"(",
"rlzs",
")",
">",
"1",
":",
"dskeys",
".",
"add",
"(",
"'realizations'",
")",
"if",
"len",
"(",
"dstore",
"[",
"'csm_info/sg_data'",
"]",
")",
">",
"1",
":",
"# export sourcegroups.csv",
"dskeys",
".",
"add",
"(",
"'sourcegroups'",
")",
"hdf5",
"=",
"dstore",
".",
"hdf5",
"if",
"'hcurves-stats'",
"in",
"hdf5",
"or",
"'hcurves-rlzs'",
"in",
"hdf5",
":",
"if",
"oq",
".",
"hazard_stats",
"(",
")",
"or",
"oq",
".",
"individual_curves",
"or",
"len",
"(",
"rlzs",
")",
"==",
"1",
":",
"dskeys",
".",
"add",
"(",
"'hcurves'",
")",
"if",
"oq",
".",
"uniform_hazard_spectra",
":",
"dskeys",
".",
"add",
"(",
"'uhs'",
")",
"# export them",
"if",
"oq",
".",
"hazard_maps",
":",
"dskeys",
".",
"add",
"(",
"'hmaps'",
")",
"# export them",
"if",
"'avg_losses-stats'",
"in",
"dstore",
"or",
"(",
"'avg_losses-rlzs'",
"in",
"dstore",
"and",
"len",
"(",
"rlzs",
")",
")",
":",
"dskeys",
".",
"add",
"(",
"'avg_losses-stats'",
")",
"if",
"'curves-rlzs'",
"in",
"dstore",
"and",
"len",
"(",
"rlzs",
")",
"==",
"1",
":",
"dskeys",
".",
"add",
"(",
"'loss_curves-rlzs'",
")",
"if",
"'curves-stats'",
"in",
"dstore",
"and",
"len",
"(",
"rlzs",
")",
">",
"1",
":",
"dskeys",
".",
"add",
"(",
"'loss_curves-stats'",
")",
"if",
"oq",
".",
"conditional_loss_poes",
":",
"# expose loss_maps outputs",
"if",
"'loss_curves-stats'",
"in",
"dstore",
":",
"dskeys",
".",
"add",
"(",
"'loss_maps-stats'",
")",
"if",
"'all_loss_ratios'",
"in",
"dskeys",
":",
"dskeys",
".",
"remove",
"(",
"'all_loss_ratios'",
")",
"# export only specific IDs",
"if",
"'ruptures'",
"in",
"dskeys",
"and",
"'scenario'",
"in",
"calcmode",
":",
"exportable",
".",
"remove",
"(",
"'ruptures'",
")",
"# do not export, as requested by Vitor",
"if",
"'rup_loss_table'",
"in",
"dskeys",
":",
"# keep it hidden for the moment",
"dskeys",
".",
"remove",
"(",
"'rup_loss_table'",
")",
"if",
"'hmaps'",
"in",
"dskeys",
"and",
"not",
"oq",
".",
"hazard_maps",
":",
"dskeys",
".",
"remove",
"(",
"'hmaps'",
")",
"# do not export the hazard maps",
"if",
"logs",
".",
"dbcmd",
"(",
"'get_job'",
",",
"dstore",
".",
"calc_id",
")",
"is",
"None",
":",
"# the calculation has not been imported in the db yet",
"logs",
".",
"dbcmd",
"(",
"'import_job'",
",",
"dstore",
".",
"calc_id",
",",
"oq",
".",
"calculation_mode",
",",
"oq",
".",
"description",
"+",
"' [parent]'",
",",
"owner",
",",
"status",
",",
"oq",
".",
"hazard_calculation_id",
",",
"dstore",
".",
"datadir",
")",
"keysize",
"=",
"[",
"]",
"for",
"key",
"in",
"sorted",
"(",
"dskeys",
"&",
"exportable",
")",
":",
"try",
":",
"size_mb",
"=",
"dstore",
".",
"get_attr",
"(",
"key",
",",
"'nbytes'",
")",
"/",
"MB",
"except",
"(",
"KeyError",
",",
"AttributeError",
")",
":",
"size_mb",
"=",
"None",
"keysize",
".",
"append",
"(",
"(",
"key",
",",
"size_mb",
")",
")",
"ds_size",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"dstore",
".",
"filename",
")",
"/",
"MB",
"logs",
".",
"dbcmd",
"(",
"'create_outputs'",
",",
"dstore",
".",
"calc_id",
",",
"keysize",
",",
"ds_size",
")"
] | Build a correspondence between the outputs in the datastore and the
ones in the database.
:param dstore: datastore | [
"Build",
"a",
"correspondence",
"between",
"the",
"outputs",
"in",
"the",
"datastore",
"and",
"the",
"ones",
"in",
"the",
"database",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/engine/engine.py#L119-L175 | train | 233,232 |
gem/oq-engine | openquake/engine/engine.py | raiseMasterKilled | def raiseMasterKilled(signum, _stack):
"""
When a SIGTERM is received, raise the MasterKilled
exception with an appropriate error message.
:param int signum: the number of the received signal
:param _stack: the current frame object, ignored
"""
# Disable further CTRL-C to allow tasks revocation when Celery is used
if OQ_DISTRIBUTE.startswith('celery'):
signal.signal(signal.SIGINT, inhibitSigInt)
msg = 'Received a signal %d' % signum
if signum in (signal.SIGTERM, signal.SIGINT):
msg = 'The openquake master process was killed manually'
# kill the calculation only if os.getppid() != _PPID, i.e. the controlling
# terminal died; in the workers, do nothing
# NB: there is no SIGHUP on Windows
if hasattr(signal, 'SIGHUP'):
if signum == signal.SIGHUP:
if os.getppid() == _PPID:
return
else:
msg = 'The openquake master lost its controlling terminal'
raise MasterKilled(msg) | python | def raiseMasterKilled(signum, _stack):
"""
When a SIGTERM is received, raise the MasterKilled
exception with an appropriate error message.
:param int signum: the number of the received signal
:param _stack: the current frame object, ignored
"""
# Disable further CTRL-C to allow tasks revocation when Celery is used
if OQ_DISTRIBUTE.startswith('celery'):
signal.signal(signal.SIGINT, inhibitSigInt)
msg = 'Received a signal %d' % signum
if signum in (signal.SIGTERM, signal.SIGINT):
msg = 'The openquake master process was killed manually'
# kill the calculation only if os.getppid() != _PPID, i.e. the controlling
# terminal died; in the workers, do nothing
# NB: there is no SIGHUP on Windows
if hasattr(signal, 'SIGHUP'):
if signum == signal.SIGHUP:
if os.getppid() == _PPID:
return
else:
msg = 'The openquake master lost its controlling terminal'
raise MasterKilled(msg) | [
"def",
"raiseMasterKilled",
"(",
"signum",
",",
"_stack",
")",
":",
"# Disable further CTRL-C to allow tasks revocation when Celery is used",
"if",
"OQ_DISTRIBUTE",
".",
"startswith",
"(",
"'celery'",
")",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"inhibitSigInt",
")",
"msg",
"=",
"'Received a signal %d'",
"%",
"signum",
"if",
"signum",
"in",
"(",
"signal",
".",
"SIGTERM",
",",
"signal",
".",
"SIGINT",
")",
":",
"msg",
"=",
"'The openquake master process was killed manually'",
"# kill the calculation only if os.getppid() != _PPID, i.e. the controlling",
"# terminal died; in the workers, do nothing",
"# NB: there is no SIGHUP on Windows",
"if",
"hasattr",
"(",
"signal",
",",
"'SIGHUP'",
")",
":",
"if",
"signum",
"==",
"signal",
".",
"SIGHUP",
":",
"if",
"os",
".",
"getppid",
"(",
")",
"==",
"_PPID",
":",
"return",
"else",
":",
"msg",
"=",
"'The openquake master lost its controlling terminal'",
"raise",
"MasterKilled",
"(",
"msg",
")"
] | When a SIGTERM is received, raise the MasterKilled
exception with an appropriate error message.
:param int signum: the number of the received signal
:param _stack: the current frame object, ignored | [
"When",
"a",
"SIGTERM",
"is",
"received",
"raise",
"the",
"MasterKilled",
"exception",
"with",
"an",
"appropriate",
"error",
"message",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/engine/engine.py#L186-L212 | train | 233,233 |
gem/oq-engine | openquake/engine/engine.py | job_from_file | def job_from_file(job_ini, job_id, username, **kw):
"""
Create a full job profile from a job config file.
:param job_ini:
Path to a job.ini file
:param job_id:
ID of the created job
:param username:
The user who will own this job profile and all results
:param kw:
Extra parameters including `calculation_mode` and `exposure_file`
:returns:
an oqparam instance
"""
hc_id = kw.get('hazard_calculation_id')
try:
oq = readinput.get_oqparam(job_ini, hc_id=hc_id)
except Exception:
logs.dbcmd('finish', job_id, 'failed')
raise
if 'calculation_mode' in kw:
oq.calculation_mode = kw.pop('calculation_mode')
if 'description' in kw:
oq.description = kw.pop('description')
if 'exposure_file' in kw: # hack used in commands.engine
fnames = kw.pop('exposure_file').split()
if fnames:
oq.inputs['exposure'] = fnames
elif 'exposure' in oq.inputs:
del oq.inputs['exposure']
logs.dbcmd('update_job', job_id,
dict(calculation_mode=oq.calculation_mode,
description=oq.description,
user_name=username,
hazard_calculation_id=hc_id))
return oq | python | def job_from_file(job_ini, job_id, username, **kw):
"""
Create a full job profile from a job config file.
:param job_ini:
Path to a job.ini file
:param job_id:
ID of the created job
:param username:
The user who will own this job profile and all results
:param kw:
Extra parameters including `calculation_mode` and `exposure_file`
:returns:
an oqparam instance
"""
hc_id = kw.get('hazard_calculation_id')
try:
oq = readinput.get_oqparam(job_ini, hc_id=hc_id)
except Exception:
logs.dbcmd('finish', job_id, 'failed')
raise
if 'calculation_mode' in kw:
oq.calculation_mode = kw.pop('calculation_mode')
if 'description' in kw:
oq.description = kw.pop('description')
if 'exposure_file' in kw: # hack used in commands.engine
fnames = kw.pop('exposure_file').split()
if fnames:
oq.inputs['exposure'] = fnames
elif 'exposure' in oq.inputs:
del oq.inputs['exposure']
logs.dbcmd('update_job', job_id,
dict(calculation_mode=oq.calculation_mode,
description=oq.description,
user_name=username,
hazard_calculation_id=hc_id))
return oq | [
"def",
"job_from_file",
"(",
"job_ini",
",",
"job_id",
",",
"username",
",",
"*",
"*",
"kw",
")",
":",
"hc_id",
"=",
"kw",
".",
"get",
"(",
"'hazard_calculation_id'",
")",
"try",
":",
"oq",
"=",
"readinput",
".",
"get_oqparam",
"(",
"job_ini",
",",
"hc_id",
"=",
"hc_id",
")",
"except",
"Exception",
":",
"logs",
".",
"dbcmd",
"(",
"'finish'",
",",
"job_id",
",",
"'failed'",
")",
"raise",
"if",
"'calculation_mode'",
"in",
"kw",
":",
"oq",
".",
"calculation_mode",
"=",
"kw",
".",
"pop",
"(",
"'calculation_mode'",
")",
"if",
"'description'",
"in",
"kw",
":",
"oq",
".",
"description",
"=",
"kw",
".",
"pop",
"(",
"'description'",
")",
"if",
"'exposure_file'",
"in",
"kw",
":",
"# hack used in commands.engine",
"fnames",
"=",
"kw",
".",
"pop",
"(",
"'exposure_file'",
")",
".",
"split",
"(",
")",
"if",
"fnames",
":",
"oq",
".",
"inputs",
"[",
"'exposure'",
"]",
"=",
"fnames",
"elif",
"'exposure'",
"in",
"oq",
".",
"inputs",
":",
"del",
"oq",
".",
"inputs",
"[",
"'exposure'",
"]",
"logs",
".",
"dbcmd",
"(",
"'update_job'",
",",
"job_id",
",",
"dict",
"(",
"calculation_mode",
"=",
"oq",
".",
"calculation_mode",
",",
"description",
"=",
"oq",
".",
"description",
",",
"user_name",
"=",
"username",
",",
"hazard_calculation_id",
"=",
"hc_id",
")",
")",
"return",
"oq"
] | Create a full job profile from a job config file.
:param job_ini:
Path to a job.ini file
:param job_id:
ID of the created job
:param username:
The user who will own this job profile and all results
:param kw:
Extra parameters including `calculation_mode` and `exposure_file`
:returns:
an oqparam instance | [
"Create",
"a",
"full",
"job",
"profile",
"from",
"a",
"job",
"config",
"file",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/engine/engine.py#L230-L266 | train | 233,234 |
gem/oq-engine | openquake/engine/engine.py | check_obsolete_version | def check_obsolete_version(calculation_mode='WebUI'):
"""
Check if there is a newer version of the engine.
:param calculation_mode:
- the calculation mode when called from the engine
- an empty string when called from the WebUI
:returns:
- a message if the running version of the engine is obsolete
- the empty string if the engine is updated
- None if the check could not be performed (i.e. github is down)
"""
if os.environ.get('JENKINS_URL') or os.environ.get('TRAVIS'):
# avoid flooding our API server with requests from CI systems
return
headers = {'User-Agent': 'OpenQuake Engine %s;%s;%s;%s' %
(__version__, calculation_mode, platform.platform(),
config.distribution.oq_distribute)}
try:
req = Request(OQ_API + '/engine/latest', headers=headers)
# NB: a timeout < 1 does not work
data = urlopen(req, timeout=1).read() # bytes
tag_name = json.loads(decode(data))['tag_name']
current = version_triple(__version__)
latest = version_triple(tag_name)
except Exception: # page not available or wrong version tag
return
if current < latest:
return ('Version %s of the engine is available, but you are '
'still using version %s' % (tag_name, __version__))
else:
return '' | python | def check_obsolete_version(calculation_mode='WebUI'):
"""
Check if there is a newer version of the engine.
:param calculation_mode:
- the calculation mode when called from the engine
- an empty string when called from the WebUI
:returns:
- a message if the running version of the engine is obsolete
- the empty string if the engine is updated
- None if the check could not be performed (i.e. github is down)
"""
if os.environ.get('JENKINS_URL') or os.environ.get('TRAVIS'):
# avoid flooding our API server with requests from CI systems
return
headers = {'User-Agent': 'OpenQuake Engine %s;%s;%s;%s' %
(__version__, calculation_mode, platform.platform(),
config.distribution.oq_distribute)}
try:
req = Request(OQ_API + '/engine/latest', headers=headers)
# NB: a timeout < 1 does not work
data = urlopen(req, timeout=1).read() # bytes
tag_name = json.loads(decode(data))['tag_name']
current = version_triple(__version__)
latest = version_triple(tag_name)
except Exception: # page not available or wrong version tag
return
if current < latest:
return ('Version %s of the engine is available, but you are '
'still using version %s' % (tag_name, __version__))
else:
return '' | [
"def",
"check_obsolete_version",
"(",
"calculation_mode",
"=",
"'WebUI'",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'JENKINS_URL'",
")",
"or",
"os",
".",
"environ",
".",
"get",
"(",
"'TRAVIS'",
")",
":",
"# avoid flooding our API server with requests from CI systems",
"return",
"headers",
"=",
"{",
"'User-Agent'",
":",
"'OpenQuake Engine %s;%s;%s;%s'",
"%",
"(",
"__version__",
",",
"calculation_mode",
",",
"platform",
".",
"platform",
"(",
")",
",",
"config",
".",
"distribution",
".",
"oq_distribute",
")",
"}",
"try",
":",
"req",
"=",
"Request",
"(",
"OQ_API",
"+",
"'/engine/latest'",
",",
"headers",
"=",
"headers",
")",
"# NB: a timeout < 1 does not work",
"data",
"=",
"urlopen",
"(",
"req",
",",
"timeout",
"=",
"1",
")",
".",
"read",
"(",
")",
"# bytes",
"tag_name",
"=",
"json",
".",
"loads",
"(",
"decode",
"(",
"data",
")",
")",
"[",
"'tag_name'",
"]",
"current",
"=",
"version_triple",
"(",
"__version__",
")",
"latest",
"=",
"version_triple",
"(",
"tag_name",
")",
"except",
"Exception",
":",
"# page not available or wrong version tag",
"return",
"if",
"current",
"<",
"latest",
":",
"return",
"(",
"'Version %s of the engine is available, but you are '",
"'still using version %s'",
"%",
"(",
"tag_name",
",",
"__version__",
")",
")",
"else",
":",
"return",
"''"
] | Check if there is a newer version of the engine.
:param calculation_mode:
- the calculation mode when called from the engine
- an empty string when called from the WebUI
:returns:
- a message if the running version of the engine is obsolete
- the empty string if the engine is updated
- None if the check could not be performed (i.e. github is down) | [
"Check",
"if",
"there",
"is",
"a",
"newer",
"version",
"of",
"the",
"engine",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/engine/engine.py#L384-L416 | train | 233,235 |
gem/oq-engine | openquake/baselib/python3compat.py | encode | def encode(val):
"""
Encode a string assuming the encoding is UTF-8.
:param: a unicode or bytes object
:returns: bytes
"""
if isinstance(val, (list, tuple)): # encode a list or tuple of strings
return [encode(v) for v in val]
elif isinstance(val, str):
return val.encode('utf-8')
else:
# assume it was an already encoded object
return val | python | def encode(val):
"""
Encode a string assuming the encoding is UTF-8.
:param: a unicode or bytes object
:returns: bytes
"""
if isinstance(val, (list, tuple)): # encode a list or tuple of strings
return [encode(v) for v in val]
elif isinstance(val, str):
return val.encode('utf-8')
else:
# assume it was an already encoded object
return val | [
"def",
"encode",
"(",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"# encode a list or tuple of strings",
"return",
"[",
"encode",
"(",
"v",
")",
"for",
"v",
"in",
"val",
"]",
"elif",
"isinstance",
"(",
"val",
",",
"str",
")",
":",
"return",
"val",
".",
"encode",
"(",
"'utf-8'",
")",
"else",
":",
"# assume it was an already encoded object",
"return",
"val"
] | Encode a string assuming the encoding is UTF-8.
:param: a unicode or bytes object
:returns: bytes | [
"Encode",
"a",
"string",
"assuming",
"the",
"encoding",
"is",
"UTF",
"-",
"8",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/python3compat.py#L28-L41 | train | 233,236 |
gem/oq-engine | openquake/baselib/python3compat.py | raise_ | def raise_(tp, value=None, tb=None):
"""
A function that matches the Python 2.x ``raise`` statement. This
allows re-raising exceptions with the cls value and traceback on
Python 2 and 3.
"""
if value is not None and isinstance(tp, Exception):
raise TypeError("instance exception may not have a separate value")
if value is not None:
exc = tp(value)
else:
exc = tp
if exc.__traceback__ is not tb:
raise exc.with_traceback(tb)
raise exc | python | def raise_(tp, value=None, tb=None):
"""
A function that matches the Python 2.x ``raise`` statement. This
allows re-raising exceptions with the cls value and traceback on
Python 2 and 3.
"""
if value is not None and isinstance(tp, Exception):
raise TypeError("instance exception may not have a separate value")
if value is not None:
exc = tp(value)
else:
exc = tp
if exc.__traceback__ is not tb:
raise exc.with_traceback(tb)
raise exc | [
"def",
"raise_",
"(",
"tp",
",",
"value",
"=",
"None",
",",
"tb",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"tp",
",",
"Exception",
")",
":",
"raise",
"TypeError",
"(",
"\"instance exception may not have a separate value\"",
")",
"if",
"value",
"is",
"not",
"None",
":",
"exc",
"=",
"tp",
"(",
"value",
")",
"else",
":",
"exc",
"=",
"tp",
"if",
"exc",
".",
"__traceback__",
"is",
"not",
"tb",
":",
"raise",
"exc",
".",
"with_traceback",
"(",
"tb",
")",
"raise",
"exc"
] | A function that matches the Python 2.x ``raise`` statement. This
allows re-raising exceptions with the cls value and traceback on
Python 2 and 3. | [
"A",
"function",
"that",
"matches",
"the",
"Python",
"2",
".",
"x",
"raise",
"statement",
".",
"This",
"allows",
"re",
"-",
"raising",
"exceptions",
"with",
"the",
"cls",
"value",
"and",
"traceback",
"on",
"Python",
"2",
"and",
"3",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/python3compat.py#L70-L84 | train | 233,237 |
gem/oq-engine | openquake/commands/plot_pyro.py | plot_pyro | def plot_pyro(calc_id=-1):
"""
Plot the pyroclastic cloud and the assets
"""
# NB: matplotlib is imported inside since it is a costly import
import matplotlib.pyplot as p
dstore = util.read(calc_id)
sitecol = dstore['sitecol']
asset_risk = dstore['asset_risk'].value
pyro, = numpy.where(dstore['multi_peril']['PYRO'] == 1)
lons = sitecol.lons[pyro]
lats = sitecol.lats[pyro]
p.scatter(lons, lats, marker='o', color='red')
building_pyro, = numpy.where(asset_risk['building-PYRO'] == 1)
lons = sitecol.lons[building_pyro]
lats = sitecol.lats[building_pyro]
p.scatter(lons, lats, marker='.', color='green')
p.show() | python | def plot_pyro(calc_id=-1):
"""
Plot the pyroclastic cloud and the assets
"""
# NB: matplotlib is imported inside since it is a costly import
import matplotlib.pyplot as p
dstore = util.read(calc_id)
sitecol = dstore['sitecol']
asset_risk = dstore['asset_risk'].value
pyro, = numpy.where(dstore['multi_peril']['PYRO'] == 1)
lons = sitecol.lons[pyro]
lats = sitecol.lats[pyro]
p.scatter(lons, lats, marker='o', color='red')
building_pyro, = numpy.where(asset_risk['building-PYRO'] == 1)
lons = sitecol.lons[building_pyro]
lats = sitecol.lats[building_pyro]
p.scatter(lons, lats, marker='.', color='green')
p.show() | [
"def",
"plot_pyro",
"(",
"calc_id",
"=",
"-",
"1",
")",
":",
"# NB: matplotlib is imported inside since it is a costly import",
"import",
"matplotlib",
".",
"pyplot",
"as",
"p",
"dstore",
"=",
"util",
".",
"read",
"(",
"calc_id",
")",
"sitecol",
"=",
"dstore",
"[",
"'sitecol'",
"]",
"asset_risk",
"=",
"dstore",
"[",
"'asset_risk'",
"]",
".",
"value",
"pyro",
",",
"=",
"numpy",
".",
"where",
"(",
"dstore",
"[",
"'multi_peril'",
"]",
"[",
"'PYRO'",
"]",
"==",
"1",
")",
"lons",
"=",
"sitecol",
".",
"lons",
"[",
"pyro",
"]",
"lats",
"=",
"sitecol",
".",
"lats",
"[",
"pyro",
"]",
"p",
".",
"scatter",
"(",
"lons",
",",
"lats",
",",
"marker",
"=",
"'o'",
",",
"color",
"=",
"'red'",
")",
"building_pyro",
",",
"=",
"numpy",
".",
"where",
"(",
"asset_risk",
"[",
"'building-PYRO'",
"]",
"==",
"1",
")",
"lons",
"=",
"sitecol",
".",
"lons",
"[",
"building_pyro",
"]",
"lats",
"=",
"sitecol",
".",
"lats",
"[",
"building_pyro",
"]",
"p",
".",
"scatter",
"(",
"lons",
",",
"lats",
",",
"marker",
"=",
"'.'",
",",
"color",
"=",
"'green'",
")",
"p",
".",
"show",
"(",
")"
] | Plot the pyroclastic cloud and the assets | [
"Plot",
"the",
"pyroclastic",
"cloud",
"and",
"the",
"assets"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/plot_pyro.py#L24-L42 | train | 233,238 |
gem/oq-engine | openquake/hazardlib/geo/polygon.py | get_resampled_coordinates | def get_resampled_coordinates(lons, lats):
"""
Resample polygon line segments and return the coordinates of the new
vertices. This limits distortions when projecting a polygon onto a
spherical surface.
Parameters define longitudes and latitudes of a point collection in the
form of lists or numpy arrays.
:return:
A tuple of two numpy arrays: longitudes and latitudes
of resampled vertices.
"""
num_coords = len(lons)
assert num_coords == len(lats)
lons1 = numpy.array(lons)
lats1 = numpy.array(lats)
lons2 = numpy.concatenate((lons1[1:], lons1[:1]))
lats2 = numpy.concatenate((lats1[1:], lats1[:1]))
distances = geodetic.geodetic_distance(lons1, lats1, lons2, lats2)
resampled_lons = [lons[0]]
resampled_lats = [lats[0]]
for i in range(num_coords):
next_point = (i + 1) % num_coords
lon1, lat1 = lons[i], lats[i]
lon2, lat2 = lons[next_point], lats[next_point]
distance = distances[i]
num_points = int(distance / UPSAMPLING_STEP_KM) + 1
if num_points >= 2:
# We need to increase the resolution of this arc by adding new
# points.
new_lons, new_lats, _ = geodetic.npoints_between(
lon1, lat1, 0, lon2, lat2, 0, num_points)
resampled_lons.extend(new_lons[1:])
resampled_lats.extend(new_lats[1:])
else:
resampled_lons.append(lon2)
resampled_lats.append(lat2)
# NB: we cut off the last point because it repeats the first one
return numpy.array(resampled_lons[:-1]), numpy.array(resampled_lats[:-1]) | python | def get_resampled_coordinates(lons, lats):
"""
Resample polygon line segments and return the coordinates of the new
vertices. This limits distortions when projecting a polygon onto a
spherical surface.
Parameters define longitudes and latitudes of a point collection in the
form of lists or numpy arrays.
:return:
A tuple of two numpy arrays: longitudes and latitudes
of resampled vertices.
"""
num_coords = len(lons)
assert num_coords == len(lats)
lons1 = numpy.array(lons)
lats1 = numpy.array(lats)
lons2 = numpy.concatenate((lons1[1:], lons1[:1]))
lats2 = numpy.concatenate((lats1[1:], lats1[:1]))
distances = geodetic.geodetic_distance(lons1, lats1, lons2, lats2)
resampled_lons = [lons[0]]
resampled_lats = [lats[0]]
for i in range(num_coords):
next_point = (i + 1) % num_coords
lon1, lat1 = lons[i], lats[i]
lon2, lat2 = lons[next_point], lats[next_point]
distance = distances[i]
num_points = int(distance / UPSAMPLING_STEP_KM) + 1
if num_points >= 2:
# We need to increase the resolution of this arc by adding new
# points.
new_lons, new_lats, _ = geodetic.npoints_between(
lon1, lat1, 0, lon2, lat2, 0, num_points)
resampled_lons.extend(new_lons[1:])
resampled_lats.extend(new_lats[1:])
else:
resampled_lons.append(lon2)
resampled_lats.append(lat2)
# NB: we cut off the last point because it repeats the first one
return numpy.array(resampled_lons[:-1]), numpy.array(resampled_lats[:-1]) | [
"def",
"get_resampled_coordinates",
"(",
"lons",
",",
"lats",
")",
":",
"num_coords",
"=",
"len",
"(",
"lons",
")",
"assert",
"num_coords",
"==",
"len",
"(",
"lats",
")",
"lons1",
"=",
"numpy",
".",
"array",
"(",
"lons",
")",
"lats1",
"=",
"numpy",
".",
"array",
"(",
"lats",
")",
"lons2",
"=",
"numpy",
".",
"concatenate",
"(",
"(",
"lons1",
"[",
"1",
":",
"]",
",",
"lons1",
"[",
":",
"1",
"]",
")",
")",
"lats2",
"=",
"numpy",
".",
"concatenate",
"(",
"(",
"lats1",
"[",
"1",
":",
"]",
",",
"lats1",
"[",
":",
"1",
"]",
")",
")",
"distances",
"=",
"geodetic",
".",
"geodetic_distance",
"(",
"lons1",
",",
"lats1",
",",
"lons2",
",",
"lats2",
")",
"resampled_lons",
"=",
"[",
"lons",
"[",
"0",
"]",
"]",
"resampled_lats",
"=",
"[",
"lats",
"[",
"0",
"]",
"]",
"for",
"i",
"in",
"range",
"(",
"num_coords",
")",
":",
"next_point",
"=",
"(",
"i",
"+",
"1",
")",
"%",
"num_coords",
"lon1",
",",
"lat1",
"=",
"lons",
"[",
"i",
"]",
",",
"lats",
"[",
"i",
"]",
"lon2",
",",
"lat2",
"=",
"lons",
"[",
"next_point",
"]",
",",
"lats",
"[",
"next_point",
"]",
"distance",
"=",
"distances",
"[",
"i",
"]",
"num_points",
"=",
"int",
"(",
"distance",
"/",
"UPSAMPLING_STEP_KM",
")",
"+",
"1",
"if",
"num_points",
">=",
"2",
":",
"# We need to increase the resolution of this arc by adding new",
"# points.",
"new_lons",
",",
"new_lats",
",",
"_",
"=",
"geodetic",
".",
"npoints_between",
"(",
"lon1",
",",
"lat1",
",",
"0",
",",
"lon2",
",",
"lat2",
",",
"0",
",",
"num_points",
")",
"resampled_lons",
".",
"extend",
"(",
"new_lons",
"[",
"1",
":",
"]",
")",
"resampled_lats",
".",
"extend",
"(",
"new_lats",
"[",
"1",
":",
"]",
")",
"else",
":",
"resampled_lons",
".",
"append",
"(",
"lon2",
")",
"resampled_lats",
".",
"append",
"(",
"lat2",
")",
"# NB: we cut off the last point because it repeats the first one",
"return",
"numpy",
".",
"array",
"(",
"resampled_lons",
"[",
":",
"-",
"1",
"]",
")",
",",
"numpy",
".",
"array",
"(",
"resampled_lats",
"[",
":",
"-",
"1",
"]",
")"
] | Resample polygon line segments and return the coordinates of the new
vertices. This limits distortions when projecting a polygon onto a
spherical surface.
Parameters define longitudes and latitudes of a point collection in the
form of lists or numpy arrays.
:return:
A tuple of two numpy arrays: longitudes and latitudes
of resampled vertices. | [
"Resample",
"polygon",
"line",
"segments",
"and",
"return",
"the",
"coordinates",
"of",
"the",
"new",
"vertices",
".",
"This",
"limits",
"distortions",
"when",
"projecting",
"a",
"polygon",
"onto",
"a",
"spherical",
"surface",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/polygon.py#L249-L291 | train | 233,239 |
gem/oq-engine | openquake/hazardlib/geo/surface/gridded.py | GriddedSurface.get_middle_point | def get_middle_point(self):
"""
Compute coordinates of surface middle point.
The actual definition of ``middle point`` depends on the type of
surface geometry.
:return:
instance of :class:`openquake.hazardlib.geo.point.Point`
representing surface middle point.
"""
lons = self.mesh.lons.squeeze()
lats = self.mesh.lats.squeeze()
depths = self.mesh.depths.squeeze()
lon_bar = lons.mean()
lat_bar = lats.mean()
idx = np.argmin((lons - lon_bar)**2 + (lats - lat_bar)**2)
return Point(lons[idx], lats[idx], depths[idx]) | python | def get_middle_point(self):
"""
Compute coordinates of surface middle point.
The actual definition of ``middle point`` depends on the type of
surface geometry.
:return:
instance of :class:`openquake.hazardlib.geo.point.Point`
representing surface middle point.
"""
lons = self.mesh.lons.squeeze()
lats = self.mesh.lats.squeeze()
depths = self.mesh.depths.squeeze()
lon_bar = lons.mean()
lat_bar = lats.mean()
idx = np.argmin((lons - lon_bar)**2 + (lats - lat_bar)**2)
return Point(lons[idx], lats[idx], depths[idx]) | [
"def",
"get_middle_point",
"(",
"self",
")",
":",
"lons",
"=",
"self",
".",
"mesh",
".",
"lons",
".",
"squeeze",
"(",
")",
"lats",
"=",
"self",
".",
"mesh",
".",
"lats",
".",
"squeeze",
"(",
")",
"depths",
"=",
"self",
".",
"mesh",
".",
"depths",
".",
"squeeze",
"(",
")",
"lon_bar",
"=",
"lons",
".",
"mean",
"(",
")",
"lat_bar",
"=",
"lats",
".",
"mean",
"(",
")",
"idx",
"=",
"np",
".",
"argmin",
"(",
"(",
"lons",
"-",
"lon_bar",
")",
"**",
"2",
"+",
"(",
"lats",
"-",
"lat_bar",
")",
"**",
"2",
")",
"return",
"Point",
"(",
"lons",
"[",
"idx",
"]",
",",
"lats",
"[",
"idx",
"]",
",",
"depths",
"[",
"idx",
"]",
")"
] | Compute coordinates of surface middle point.
The actual definition of ``middle point`` depends on the type of
surface geometry.
:return:
instance of :class:`openquake.hazardlib.geo.point.Point`
representing surface middle point. | [
"Compute",
"coordinates",
"of",
"surface",
"middle",
"point",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/gridded.py#L164-L181 | train | 233,240 |
gem/oq-engine | openquake/hazardlib/mfd/base.py | BaseMFD.modify | def modify(self, modification, parameters):
"""
Apply a single modification to an MFD parameters.
Reflects the modification method and calls it passing ``parameters``
as keyword arguments. See also :attr:`MODIFICATIONS`.
Modifications can be applied one on top of another. The logic
of stacking modifications is up to a specific MFD implementation.
:param modification:
String name representing the type of modification.
:param parameters:
Dictionary of parameters needed for modification.
:raises ValueError:
If ``modification`` is missing from :attr:`MODIFICATIONS`.
"""
if modification not in self.MODIFICATIONS:
raise ValueError('Modification %s is not supported by %s' %
(modification, type(self).__name__))
meth = getattr(self, 'modify_%s' % modification)
meth(**parameters)
self.check_constraints() | python | def modify(self, modification, parameters):
"""
Apply a single modification to an MFD parameters.
Reflects the modification method and calls it passing ``parameters``
as keyword arguments. See also :attr:`MODIFICATIONS`.
Modifications can be applied one on top of another. The logic
of stacking modifications is up to a specific MFD implementation.
:param modification:
String name representing the type of modification.
:param parameters:
Dictionary of parameters needed for modification.
:raises ValueError:
If ``modification`` is missing from :attr:`MODIFICATIONS`.
"""
if modification not in self.MODIFICATIONS:
raise ValueError('Modification %s is not supported by %s' %
(modification, type(self).__name__))
meth = getattr(self, 'modify_%s' % modification)
meth(**parameters)
self.check_constraints() | [
"def",
"modify",
"(",
"self",
",",
"modification",
",",
"parameters",
")",
":",
"if",
"modification",
"not",
"in",
"self",
".",
"MODIFICATIONS",
":",
"raise",
"ValueError",
"(",
"'Modification %s is not supported by %s'",
"%",
"(",
"modification",
",",
"type",
"(",
"self",
")",
".",
"__name__",
")",
")",
"meth",
"=",
"getattr",
"(",
"self",
",",
"'modify_%s'",
"%",
"modification",
")",
"meth",
"(",
"*",
"*",
"parameters",
")",
"self",
".",
"check_constraints",
"(",
")"
] | Apply a single modification to an MFD parameters.
Reflects the modification method and calls it passing ``parameters``
as keyword arguments. See also :attr:`MODIFICATIONS`.
Modifications can be applied one on top of another. The logic
of stacking modifications is up to a specific MFD implementation.
:param modification:
String name representing the type of modification.
:param parameters:
Dictionary of parameters needed for modification.
:raises ValueError:
If ``modification`` is missing from :attr:`MODIFICATIONS`. | [
"Apply",
"a",
"single",
"modification",
"to",
"an",
"MFD",
"parameters",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/mfd/base.py#L34-L56 | train | 233,241 |
gem/oq-engine | openquake/hazardlib/gsim/travasarou_2003.py | TravasarouEtAl2003._get_stddevs | def _get_stddevs(self, rup, arias, stddev_types, sites):
"""
Return standard deviations as defined in table 1, p. 200.
"""
stddevs = []
# Magnitude dependent inter-event term (Eq. 13)
if rup.mag < 4.7:
tau = 0.611
elif rup.mag > 7.6:
tau = 0.475
else:
tau = 0.611 - 0.047 * (rup.mag - 4.7)
# Retrieve site-class dependent sigma
sigma1, sigma2 = self._get_intra_event_sigmas(sites)
sigma = np.copy(sigma1)
# Implements the nonlinear intra-event sigma (Eq. 14)
idx = arias >= 0.125
sigma[idx] = sigma2[idx]
idx = np.logical_and(arias > 0.013, arias < 0.125)
sigma[idx] = sigma1[idx] - 0.106 * (np.log(arias[idx]) -
np.log(0.0132))
sigma_total = np.sqrt(tau ** 2. + sigma ** 2.)
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if stddev_type == const.StdDev.TOTAL:
stddevs.append(sigma_total)
elif stddev_type == const.StdDev.INTRA_EVENT:
stddevs.append(sigma)
elif stddev_type == const.StdDev.INTER_EVENT:
stddevs.append(tau * np.ones_like(sites.vs30))
return stddevs | python | def _get_stddevs(self, rup, arias, stddev_types, sites):
"""
Return standard deviations as defined in table 1, p. 200.
"""
stddevs = []
# Magnitude dependent inter-event term (Eq. 13)
if rup.mag < 4.7:
tau = 0.611
elif rup.mag > 7.6:
tau = 0.475
else:
tau = 0.611 - 0.047 * (rup.mag - 4.7)
# Retrieve site-class dependent sigma
sigma1, sigma2 = self._get_intra_event_sigmas(sites)
sigma = np.copy(sigma1)
# Implements the nonlinear intra-event sigma (Eq. 14)
idx = arias >= 0.125
sigma[idx] = sigma2[idx]
idx = np.logical_and(arias > 0.013, arias < 0.125)
sigma[idx] = sigma1[idx] - 0.106 * (np.log(arias[idx]) -
np.log(0.0132))
sigma_total = np.sqrt(tau ** 2. + sigma ** 2.)
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if stddev_type == const.StdDev.TOTAL:
stddevs.append(sigma_total)
elif stddev_type == const.StdDev.INTRA_EVENT:
stddevs.append(sigma)
elif stddev_type == const.StdDev.INTER_EVENT:
stddevs.append(tau * np.ones_like(sites.vs30))
return stddevs | [
"def",
"_get_stddevs",
"(",
"self",
",",
"rup",
",",
"arias",
",",
"stddev_types",
",",
"sites",
")",
":",
"stddevs",
"=",
"[",
"]",
"# Magnitude dependent inter-event term (Eq. 13)",
"if",
"rup",
".",
"mag",
"<",
"4.7",
":",
"tau",
"=",
"0.611",
"elif",
"rup",
".",
"mag",
">",
"7.6",
":",
"tau",
"=",
"0.475",
"else",
":",
"tau",
"=",
"0.611",
"-",
"0.047",
"*",
"(",
"rup",
".",
"mag",
"-",
"4.7",
")",
"# Retrieve site-class dependent sigma",
"sigma1",
",",
"sigma2",
"=",
"self",
".",
"_get_intra_event_sigmas",
"(",
"sites",
")",
"sigma",
"=",
"np",
".",
"copy",
"(",
"sigma1",
")",
"# Implements the nonlinear intra-event sigma (Eq. 14)",
"idx",
"=",
"arias",
">=",
"0.125",
"sigma",
"[",
"idx",
"]",
"=",
"sigma2",
"[",
"idx",
"]",
"idx",
"=",
"np",
".",
"logical_and",
"(",
"arias",
">",
"0.013",
",",
"arias",
"<",
"0.125",
")",
"sigma",
"[",
"idx",
"]",
"=",
"sigma1",
"[",
"idx",
"]",
"-",
"0.106",
"*",
"(",
"np",
".",
"log",
"(",
"arias",
"[",
"idx",
"]",
")",
"-",
"np",
".",
"log",
"(",
"0.0132",
")",
")",
"sigma_total",
"=",
"np",
".",
"sqrt",
"(",
"tau",
"**",
"2.",
"+",
"sigma",
"**",
"2.",
")",
"for",
"stddev_type",
"in",
"stddev_types",
":",
"assert",
"stddev_type",
"in",
"self",
".",
"DEFINED_FOR_STANDARD_DEVIATION_TYPES",
"if",
"stddev_type",
"==",
"const",
".",
"StdDev",
".",
"TOTAL",
":",
"stddevs",
".",
"append",
"(",
"sigma_total",
")",
"elif",
"stddev_type",
"==",
"const",
".",
"StdDev",
".",
"INTRA_EVENT",
":",
"stddevs",
".",
"append",
"(",
"sigma",
")",
"elif",
"stddev_type",
"==",
"const",
".",
"StdDev",
".",
"INTER_EVENT",
":",
"stddevs",
".",
"append",
"(",
"tau",
"*",
"np",
".",
"ones_like",
"(",
"sites",
".",
"vs30",
")",
")",
"return",
"stddevs"
] | Return standard deviations as defined in table 1, p. 200. | [
"Return",
"standard",
"deviations",
"as",
"defined",
"in",
"table",
"1",
"p",
".",
"200",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/travasarou_2003.py#L95-L128 | train | 233,242 |
gem/oq-engine | openquake/hazardlib/gsim/travasarou_2003.py | TravasarouEtAl2003._get_intra_event_sigmas | def _get_intra_event_sigmas(self, sites):
"""
The intra-event term nonlinear and dependent on both the site class
and the expected ground motion. In this case the sigma coefficients
are determined from the site class as described below Eq. 14
"""
sigma1 = 1.18 * np.ones_like(sites.vs30)
sigma2 = 0.94 * np.ones_like(sites.vs30)
idx1 = np.logical_and(sites.vs30 >= 360.0, sites.vs30 < 760.0)
idx2 = sites.vs30 < 360.0
sigma1[idx1] = 1.17
sigma2[idx1] = 0.93
sigma1[idx2] = 0.96
sigma2[idx2] = 0.73
return sigma1, sigma2 | python | def _get_intra_event_sigmas(self, sites):
"""
The intra-event term nonlinear and dependent on both the site class
and the expected ground motion. In this case the sigma coefficients
are determined from the site class as described below Eq. 14
"""
sigma1 = 1.18 * np.ones_like(sites.vs30)
sigma2 = 0.94 * np.ones_like(sites.vs30)
idx1 = np.logical_and(sites.vs30 >= 360.0, sites.vs30 < 760.0)
idx2 = sites.vs30 < 360.0
sigma1[idx1] = 1.17
sigma2[idx1] = 0.93
sigma1[idx2] = 0.96
sigma2[idx2] = 0.73
return sigma1, sigma2 | [
"def",
"_get_intra_event_sigmas",
"(",
"self",
",",
"sites",
")",
":",
"sigma1",
"=",
"1.18",
"*",
"np",
".",
"ones_like",
"(",
"sites",
".",
"vs30",
")",
"sigma2",
"=",
"0.94",
"*",
"np",
".",
"ones_like",
"(",
"sites",
".",
"vs30",
")",
"idx1",
"=",
"np",
".",
"logical_and",
"(",
"sites",
".",
"vs30",
">=",
"360.0",
",",
"sites",
".",
"vs30",
"<",
"760.0",
")",
"idx2",
"=",
"sites",
".",
"vs30",
"<",
"360.0",
"sigma1",
"[",
"idx1",
"]",
"=",
"1.17",
"sigma2",
"[",
"idx1",
"]",
"=",
"0.93",
"sigma1",
"[",
"idx2",
"]",
"=",
"0.96",
"sigma2",
"[",
"idx2",
"]",
"=",
"0.73",
"return",
"sigma1",
",",
"sigma2"
] | The intra-event term nonlinear and dependent on both the site class
and the expected ground motion. In this case the sigma coefficients
are determined from the site class as described below Eq. 14 | [
"The",
"intra",
"-",
"event",
"term",
"nonlinear",
"and",
"dependent",
"on",
"both",
"the",
"site",
"class",
"and",
"the",
"expected",
"ground",
"motion",
".",
"In",
"this",
"case",
"the",
"sigma",
"coefficients",
"are",
"determined",
"from",
"the",
"site",
"class",
"as",
"described",
"below",
"Eq",
".",
"14"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/travasarou_2003.py#L130-L145 | train | 233,243 |
gem/oq-engine | openquake/hazardlib/gsim/boore_2014.py | BooreEtAl2014._get_pga_on_rock | def _get_pga_on_rock(self, C, rup, dists):
"""
Returns the median PGA on rock, which is a sum of the
magnitude and distance scaling
"""
return np.exp(self._get_magnitude_scaling_term(C, rup) +
self._get_path_scaling(C, dists, rup.mag)) | python | def _get_pga_on_rock(self, C, rup, dists):
"""
Returns the median PGA on rock, which is a sum of the
magnitude and distance scaling
"""
return np.exp(self._get_magnitude_scaling_term(C, rup) +
self._get_path_scaling(C, dists, rup.mag)) | [
"def",
"_get_pga_on_rock",
"(",
"self",
",",
"C",
",",
"rup",
",",
"dists",
")",
":",
"return",
"np",
".",
"exp",
"(",
"self",
".",
"_get_magnitude_scaling_term",
"(",
"C",
",",
"rup",
")",
"+",
"self",
".",
"_get_path_scaling",
"(",
"C",
",",
"dists",
",",
"rup",
".",
"mag",
")",
")"
] | Returns the median PGA on rock, which is a sum of the
magnitude and distance scaling | [
"Returns",
"the",
"median",
"PGA",
"on",
"rock",
"which",
"is",
"a",
"sum",
"of",
"the",
"magnitude",
"and",
"distance",
"scaling"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/boore_2014.py#L103-L109 | train | 233,244 |
gem/oq-engine | openquake/hazardlib/mfd/multi_mfd.py | MultiMFD.modify | def modify(self, modification, parameters):
"""
Apply a modification to the underlying point sources, with the
same parameters for all sources
"""
for src in self:
src.modify(modification, parameters) | python | def modify(self, modification, parameters):
"""
Apply a modification to the underlying point sources, with the
same parameters for all sources
"""
for src in self:
src.modify(modification, parameters) | [
"def",
"modify",
"(",
"self",
",",
"modification",
",",
"parameters",
")",
":",
"for",
"src",
"in",
"self",
":",
"src",
".",
"modify",
"(",
"modification",
",",
"parameters",
")"
] | Apply a modification to the underlying point sources, with the
same parameters for all sources | [
"Apply",
"a",
"modification",
"to",
"the",
"underlying",
"point",
"sources",
"with",
"the",
"same",
"parameters",
"for",
"all",
"sources"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/mfd/multi_mfd.py#L143-L149 | train | 233,245 |
gem/oq-engine | openquake/hazardlib/gsim/geomatrix_1993.py | Geomatrix1993SSlabNSHMP2008._compute_mean | def _compute_mean(self, C, mag, ztor, rrup):
"""
Compute mean value as in ``subroutine getGeom`` in ``hazgridXnga2.f``
"""
gc0 = 0.2418
ci = 0.3846
gch = 0.00607
g4 = 1.7818
ge = 0.554
gm = 1.414
mean = (
gc0 + ci + ztor * gch + C['gc1'] +
gm * mag + C['gc2'] * (10 - mag) ** 3 +
C['gc3'] * np.log(rrup + g4 * np.exp(ge * mag))
)
return mean | python | def _compute_mean(self, C, mag, ztor, rrup):
"""
Compute mean value as in ``subroutine getGeom`` in ``hazgridXnga2.f``
"""
gc0 = 0.2418
ci = 0.3846
gch = 0.00607
g4 = 1.7818
ge = 0.554
gm = 1.414
mean = (
gc0 + ci + ztor * gch + C['gc1'] +
gm * mag + C['gc2'] * (10 - mag) ** 3 +
C['gc3'] * np.log(rrup + g4 * np.exp(ge * mag))
)
return mean | [
"def",
"_compute_mean",
"(",
"self",
",",
"C",
",",
"mag",
",",
"ztor",
",",
"rrup",
")",
":",
"gc0",
"=",
"0.2418",
"ci",
"=",
"0.3846",
"gch",
"=",
"0.00607",
"g4",
"=",
"1.7818",
"ge",
"=",
"0.554",
"gm",
"=",
"1.414",
"mean",
"=",
"(",
"gc0",
"+",
"ci",
"+",
"ztor",
"*",
"gch",
"+",
"C",
"[",
"'gc1'",
"]",
"+",
"gm",
"*",
"mag",
"+",
"C",
"[",
"'gc2'",
"]",
"*",
"(",
"10",
"-",
"mag",
")",
"**",
"3",
"+",
"C",
"[",
"'gc3'",
"]",
"*",
"np",
".",
"log",
"(",
"rrup",
"+",
"g4",
"*",
"np",
".",
"exp",
"(",
"ge",
"*",
"mag",
")",
")",
")",
"return",
"mean"
] | Compute mean value as in ``subroutine getGeom`` in ``hazgridXnga2.f`` | [
"Compute",
"mean",
"value",
"as",
"in",
"subroutine",
"getGeom",
"in",
"hazgridXnga2",
".",
"f"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/geomatrix_1993.py#L92-L109 | train | 233,246 |
gem/oq-engine | openquake/commands/abort.py | abort | def abort(job_id):
"""
Abort the given job
"""
job = logs.dbcmd('get_job', job_id) # job_id can be negative
if job is None:
print('There is no job %d' % job_id)
return
elif job.status not in ('executing', 'running'):
print('Job %d is %s' % (job.id, job.status))
return
name = 'oq-job-%d' % job.id
for p in psutil.process_iter():
if p.name() == name:
try:
os.kill(p.pid, signal.SIGTERM)
logs.dbcmd('set_status', job.id, 'aborted')
print('Job %d aborted' % job.id)
except Exception as exc:
print(exc)
break
else: # no break
# set job as failed if it is set as 'executing' or 'running' in the db
# but the corresponding process is not running anymore
logs.dbcmd('set_status', job.id, 'failed')
print('Unable to find a process for job %d,'
' setting it as failed' % job.id) | python | def abort(job_id):
"""
Abort the given job
"""
job = logs.dbcmd('get_job', job_id) # job_id can be negative
if job is None:
print('There is no job %d' % job_id)
return
elif job.status not in ('executing', 'running'):
print('Job %d is %s' % (job.id, job.status))
return
name = 'oq-job-%d' % job.id
for p in psutil.process_iter():
if p.name() == name:
try:
os.kill(p.pid, signal.SIGTERM)
logs.dbcmd('set_status', job.id, 'aborted')
print('Job %d aborted' % job.id)
except Exception as exc:
print(exc)
break
else: # no break
# set job as failed if it is set as 'executing' or 'running' in the db
# but the corresponding process is not running anymore
logs.dbcmd('set_status', job.id, 'failed')
print('Unable to find a process for job %d,'
' setting it as failed' % job.id) | [
"def",
"abort",
"(",
"job_id",
")",
":",
"job",
"=",
"logs",
".",
"dbcmd",
"(",
"'get_job'",
",",
"job_id",
")",
"# job_id can be negative",
"if",
"job",
"is",
"None",
":",
"print",
"(",
"'There is no job %d'",
"%",
"job_id",
")",
"return",
"elif",
"job",
".",
"status",
"not",
"in",
"(",
"'executing'",
",",
"'running'",
")",
":",
"print",
"(",
"'Job %d is %s'",
"%",
"(",
"job",
".",
"id",
",",
"job",
".",
"status",
")",
")",
"return",
"name",
"=",
"'oq-job-%d'",
"%",
"job",
".",
"id",
"for",
"p",
"in",
"psutil",
".",
"process_iter",
"(",
")",
":",
"if",
"p",
".",
"name",
"(",
")",
"==",
"name",
":",
"try",
":",
"os",
".",
"kill",
"(",
"p",
".",
"pid",
",",
"signal",
".",
"SIGTERM",
")",
"logs",
".",
"dbcmd",
"(",
"'set_status'",
",",
"job",
".",
"id",
",",
"'aborted'",
")",
"print",
"(",
"'Job %d aborted'",
"%",
"job",
".",
"id",
")",
"except",
"Exception",
"as",
"exc",
":",
"print",
"(",
"exc",
")",
"break",
"else",
":",
"# no break",
"# set job as failed if it is set as 'executing' or 'running' in the db",
"# but the corresponding process is not running anymore",
"logs",
".",
"dbcmd",
"(",
"'set_status'",
",",
"job",
".",
"id",
",",
"'failed'",
")",
"print",
"(",
"'Unable to find a process for job %d,'",
"' setting it as failed'",
"%",
"job",
".",
"id",
")"
] | Abort the given job | [
"Abort",
"the",
"given",
"job"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/abort.py#L27-L53 | train | 233,247 |
gem/oq-engine | openquake/baselib/sap.py | compose | def compose(scripts, name='main', description=None, prog=None,
version=None):
"""
Collects together different scripts and builds a single
script dispatching to the subparsers depending on
the first argument, i.e. the name of the subparser to invoke.
:param scripts: a list of script instances
:param name: the name of the composed parser
:param description: description of the composed parser
:param prog: name of the script printed in the usage message
:param version: version of the script printed with --version
"""
assert len(scripts) >= 1, scripts
parentparser = argparse.ArgumentParser(
description=description, add_help=False)
parentparser.add_argument(
'--version', '-v', action='version', version=version)
subparsers = parentparser.add_subparsers(
help='available subcommands; use %s help <subcmd>' % prog,
prog=prog)
def gethelp(cmd=None):
if cmd is None:
print(parentparser.format_help())
return
subp = subparsers._name_parser_map.get(cmd)
if subp is None:
print('No help for unknown command %r' % cmd)
else:
print(subp.format_help())
help_script = Script(gethelp, 'help', help=False)
progname = '%s ' % prog if prog else ''
help_script.arg('cmd', progname + 'subcommand')
for s in list(scripts) + [help_script]:
subp = subparsers.add_parser(s.name, description=s.description)
for args, kw in s.all_arguments:
subp.add_argument(*args, **kw)
subp.set_defaults(_func=s.func)
def main(**kw):
try:
func = kw.pop('_func')
except KeyError:
parentparser.print_usage()
else:
return func(**kw)
main.__name__ = name
return Script(main, name, parentparser) | python | def compose(scripts, name='main', description=None, prog=None,
version=None):
"""
Collects together different scripts and builds a single
script dispatching to the subparsers depending on
the first argument, i.e. the name of the subparser to invoke.
:param scripts: a list of script instances
:param name: the name of the composed parser
:param description: description of the composed parser
:param prog: name of the script printed in the usage message
:param version: version of the script printed with --version
"""
assert len(scripts) >= 1, scripts
parentparser = argparse.ArgumentParser(
description=description, add_help=False)
parentparser.add_argument(
'--version', '-v', action='version', version=version)
subparsers = parentparser.add_subparsers(
help='available subcommands; use %s help <subcmd>' % prog,
prog=prog)
def gethelp(cmd=None):
if cmd is None:
print(parentparser.format_help())
return
subp = subparsers._name_parser_map.get(cmd)
if subp is None:
print('No help for unknown command %r' % cmd)
else:
print(subp.format_help())
help_script = Script(gethelp, 'help', help=False)
progname = '%s ' % prog if prog else ''
help_script.arg('cmd', progname + 'subcommand')
for s in list(scripts) + [help_script]:
subp = subparsers.add_parser(s.name, description=s.description)
for args, kw in s.all_arguments:
subp.add_argument(*args, **kw)
subp.set_defaults(_func=s.func)
def main(**kw):
try:
func = kw.pop('_func')
except KeyError:
parentparser.print_usage()
else:
return func(**kw)
main.__name__ = name
return Script(main, name, parentparser) | [
"def",
"compose",
"(",
"scripts",
",",
"name",
"=",
"'main'",
",",
"description",
"=",
"None",
",",
"prog",
"=",
"None",
",",
"version",
"=",
"None",
")",
":",
"assert",
"len",
"(",
"scripts",
")",
">=",
"1",
",",
"scripts",
"parentparser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"description",
",",
"add_help",
"=",
"False",
")",
"parentparser",
".",
"add_argument",
"(",
"'--version'",
",",
"'-v'",
",",
"action",
"=",
"'version'",
",",
"version",
"=",
"version",
")",
"subparsers",
"=",
"parentparser",
".",
"add_subparsers",
"(",
"help",
"=",
"'available subcommands; use %s help <subcmd>'",
"%",
"prog",
",",
"prog",
"=",
"prog",
")",
"def",
"gethelp",
"(",
"cmd",
"=",
"None",
")",
":",
"if",
"cmd",
"is",
"None",
":",
"print",
"(",
"parentparser",
".",
"format_help",
"(",
")",
")",
"return",
"subp",
"=",
"subparsers",
".",
"_name_parser_map",
".",
"get",
"(",
"cmd",
")",
"if",
"subp",
"is",
"None",
":",
"print",
"(",
"'No help for unknown command %r'",
"%",
"cmd",
")",
"else",
":",
"print",
"(",
"subp",
".",
"format_help",
"(",
")",
")",
"help_script",
"=",
"Script",
"(",
"gethelp",
",",
"'help'",
",",
"help",
"=",
"False",
")",
"progname",
"=",
"'%s '",
"%",
"prog",
"if",
"prog",
"else",
"''",
"help_script",
".",
"arg",
"(",
"'cmd'",
",",
"progname",
"+",
"'subcommand'",
")",
"for",
"s",
"in",
"list",
"(",
"scripts",
")",
"+",
"[",
"help_script",
"]",
":",
"subp",
"=",
"subparsers",
".",
"add_parser",
"(",
"s",
".",
"name",
",",
"description",
"=",
"s",
".",
"description",
")",
"for",
"args",
",",
"kw",
"in",
"s",
".",
"all_arguments",
":",
"subp",
".",
"add_argument",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"subp",
".",
"set_defaults",
"(",
"_func",
"=",
"s",
".",
"func",
")",
"def",
"main",
"(",
"*",
"*",
"kw",
")",
":",
"try",
":",
"func",
"=",
"kw",
".",
"pop",
"(",
"'_func'",
")",
"except",
"KeyError",
":",
"parentparser",
".",
"print_usage",
"(",
")",
"else",
":",
"return",
"func",
"(",
"*",
"*",
"kw",
")",
"main",
".",
"__name__",
"=",
"name",
"return",
"Script",
"(",
"main",
",",
"name",
",",
"parentparser",
")"
] | Collects together different scripts and builds a single
script dispatching to the subparsers depending on
the first argument, i.e. the name of the subparser to invoke.
:param scripts: a list of script instances
:param name: the name of the composed parser
:param description: description of the composed parser
:param prog: name of the script printed in the usage message
:param version: version of the script printed with --version | [
"Collects",
"together",
"different",
"scripts",
"and",
"builds",
"a",
"single",
"script",
"dispatching",
"to",
"the",
"subparsers",
"depending",
"on",
"the",
"first",
"argument",
"i",
".",
"e",
".",
"the",
"name",
"of",
"the",
"subparser",
"to",
"invoke",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/sap.py#L205-L253 | train | 233,248 |
gem/oq-engine | openquake/baselib/sap.py | Script._add | def _add(self, name, *args, **kw):
"""
Add an argument to the underlying parser and grow the list
.all_arguments and the set .names
"""
argname = list(self.argdict)[self._argno]
if argname != name:
raise NameError(
'Setting argument %s, but it should be %s' % (name, argname))
self._group.add_argument(*args, **kw)
self.all_arguments.append((args, kw))
self.names.append(name)
self._argno += 1 | python | def _add(self, name, *args, **kw):
"""
Add an argument to the underlying parser and grow the list
.all_arguments and the set .names
"""
argname = list(self.argdict)[self._argno]
if argname != name:
raise NameError(
'Setting argument %s, but it should be %s' % (name, argname))
self._group.add_argument(*args, **kw)
self.all_arguments.append((args, kw))
self.names.append(name)
self._argno += 1 | [
"def",
"_add",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"argname",
"=",
"list",
"(",
"self",
".",
"argdict",
")",
"[",
"self",
".",
"_argno",
"]",
"if",
"argname",
"!=",
"name",
":",
"raise",
"NameError",
"(",
"'Setting argument %s, but it should be %s'",
"%",
"(",
"name",
",",
"argname",
")",
")",
"self",
".",
"_group",
".",
"add_argument",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"self",
".",
"all_arguments",
".",
"append",
"(",
"(",
"args",
",",
"kw",
")",
")",
"self",
".",
"names",
".",
"append",
"(",
"name",
")",
"self",
".",
"_argno",
"+=",
"1"
] | Add an argument to the underlying parser and grow the list
.all_arguments and the set .names | [
"Add",
"an",
"argument",
"to",
"the",
"underlying",
"parser",
"and",
"grow",
"the",
"list",
".",
"all_arguments",
"and",
"the",
"set",
".",
"names"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/sap.py#L116-L128 | train | 233,249 |
gem/oq-engine | openquake/baselib/sap.py | Script.arg | def arg(self, name, help, type=None, choices=None, metavar=None,
nargs=None):
"""Describe a positional argument"""
kw = dict(help=help, type=type, choices=choices, metavar=metavar,
nargs=nargs)
default = self.argdict[name]
if default is not NODEFAULT:
kw['nargs'] = nargs or '?'
kw['default'] = default
kw['help'] = kw['help'] + ' [default: %s]' % repr(default)
self._add(name, name, **kw) | python | def arg(self, name, help, type=None, choices=None, metavar=None,
nargs=None):
"""Describe a positional argument"""
kw = dict(help=help, type=type, choices=choices, metavar=metavar,
nargs=nargs)
default = self.argdict[name]
if default is not NODEFAULT:
kw['nargs'] = nargs or '?'
kw['default'] = default
kw['help'] = kw['help'] + ' [default: %s]' % repr(default)
self._add(name, name, **kw) | [
"def",
"arg",
"(",
"self",
",",
"name",
",",
"help",
",",
"type",
"=",
"None",
",",
"choices",
"=",
"None",
",",
"metavar",
"=",
"None",
",",
"nargs",
"=",
"None",
")",
":",
"kw",
"=",
"dict",
"(",
"help",
"=",
"help",
",",
"type",
"=",
"type",
",",
"choices",
"=",
"choices",
",",
"metavar",
"=",
"metavar",
",",
"nargs",
"=",
"nargs",
")",
"default",
"=",
"self",
".",
"argdict",
"[",
"name",
"]",
"if",
"default",
"is",
"not",
"NODEFAULT",
":",
"kw",
"[",
"'nargs'",
"]",
"=",
"nargs",
"or",
"'?'",
"kw",
"[",
"'default'",
"]",
"=",
"default",
"kw",
"[",
"'help'",
"]",
"=",
"kw",
"[",
"'help'",
"]",
"+",
"' [default: %s]'",
"%",
"repr",
"(",
"default",
")",
"self",
".",
"_add",
"(",
"name",
",",
"name",
",",
"*",
"*",
"kw",
")"
] | Describe a positional argument | [
"Describe",
"a",
"positional",
"argument"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/sap.py#L130-L140 | train | 233,250 |
gem/oq-engine | openquake/baselib/sap.py | Script.opt | def opt(self, name, help, abbrev=None,
type=None, choices=None, metavar=None, nargs=None):
"""Describe an option"""
kw = dict(help=help, type=type, choices=choices, metavar=metavar,
nargs=nargs)
default = self.argdict[name]
if default is not NODEFAULT:
kw['default'] = default
kw['metavar'] = metavar or str_choices(choices) or str(default)
abbrev = abbrev or '-' + name[0]
abbrevs = set(args[0] for args, kw in self.all_arguments)
longname = '--' + name.replace('_', '-')
if abbrev == '-h' or abbrev in abbrevs:
# avoid conflicts with predefined abbreviations
self._add(name, longname, **kw)
else:
self._add(name, abbrev, longname, **kw) | python | def opt(self, name, help, abbrev=None,
type=None, choices=None, metavar=None, nargs=None):
"""Describe an option"""
kw = dict(help=help, type=type, choices=choices, metavar=metavar,
nargs=nargs)
default = self.argdict[name]
if default is not NODEFAULT:
kw['default'] = default
kw['metavar'] = metavar or str_choices(choices) or str(default)
abbrev = abbrev or '-' + name[0]
abbrevs = set(args[0] for args, kw in self.all_arguments)
longname = '--' + name.replace('_', '-')
if abbrev == '-h' or abbrev in abbrevs:
# avoid conflicts with predefined abbreviations
self._add(name, longname, **kw)
else:
self._add(name, abbrev, longname, **kw) | [
"def",
"opt",
"(",
"self",
",",
"name",
",",
"help",
",",
"abbrev",
"=",
"None",
",",
"type",
"=",
"None",
",",
"choices",
"=",
"None",
",",
"metavar",
"=",
"None",
",",
"nargs",
"=",
"None",
")",
":",
"kw",
"=",
"dict",
"(",
"help",
"=",
"help",
",",
"type",
"=",
"type",
",",
"choices",
"=",
"choices",
",",
"metavar",
"=",
"metavar",
",",
"nargs",
"=",
"nargs",
")",
"default",
"=",
"self",
".",
"argdict",
"[",
"name",
"]",
"if",
"default",
"is",
"not",
"NODEFAULT",
":",
"kw",
"[",
"'default'",
"]",
"=",
"default",
"kw",
"[",
"'metavar'",
"]",
"=",
"metavar",
"or",
"str_choices",
"(",
"choices",
")",
"or",
"str",
"(",
"default",
")",
"abbrev",
"=",
"abbrev",
"or",
"'-'",
"+",
"name",
"[",
"0",
"]",
"abbrevs",
"=",
"set",
"(",
"args",
"[",
"0",
"]",
"for",
"args",
",",
"kw",
"in",
"self",
".",
"all_arguments",
")",
"longname",
"=",
"'--'",
"+",
"name",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"if",
"abbrev",
"==",
"'-h'",
"or",
"abbrev",
"in",
"abbrevs",
":",
"# avoid conflicts with predefined abbreviations",
"self",
".",
"_add",
"(",
"name",
",",
"longname",
",",
"*",
"*",
"kw",
")",
"else",
":",
"self",
".",
"_add",
"(",
"name",
",",
"abbrev",
",",
"longname",
",",
"*",
"*",
"kw",
")"
] | Describe an option | [
"Describe",
"an",
"option"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/sap.py#L142-L158 | train | 233,251 |
gem/oq-engine | openquake/baselib/sap.py | Script.flg | def flg(self, name, help, abbrev=None):
"""Describe a flag"""
abbrev = abbrev or '-' + name[0]
longname = '--' + name.replace('_', '-')
self._add(name, abbrev, longname, action='store_true', help=help) | python | def flg(self, name, help, abbrev=None):
"""Describe a flag"""
abbrev = abbrev or '-' + name[0]
longname = '--' + name.replace('_', '-')
self._add(name, abbrev, longname, action='store_true', help=help) | [
"def",
"flg",
"(",
"self",
",",
"name",
",",
"help",
",",
"abbrev",
"=",
"None",
")",
":",
"abbrev",
"=",
"abbrev",
"or",
"'-'",
"+",
"name",
"[",
"0",
"]",
"longname",
"=",
"'--'",
"+",
"name",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"self",
".",
"_add",
"(",
"name",
",",
"abbrev",
",",
"longname",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"help",
")"
] | Describe a flag | [
"Describe",
"a",
"flag"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/sap.py#L160-L164 | train | 233,252 |
gem/oq-engine | openquake/baselib/sap.py | Script.check_arguments | def check_arguments(self):
"""Make sure all arguments have a specification"""
for name, default in self.argdict.items():
if name not in self.names and default is NODEFAULT:
raise NameError('Missing argparse specification for %r' % name) | python | def check_arguments(self):
"""Make sure all arguments have a specification"""
for name, default in self.argdict.items():
if name not in self.names and default is NODEFAULT:
raise NameError('Missing argparse specification for %r' % name) | [
"def",
"check_arguments",
"(",
"self",
")",
":",
"for",
"name",
",",
"default",
"in",
"self",
".",
"argdict",
".",
"items",
"(",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"names",
"and",
"default",
"is",
"NODEFAULT",
":",
"raise",
"NameError",
"(",
"'Missing argparse specification for %r'",
"%",
"name",
")"
] | Make sure all arguments have a specification | [
"Make",
"sure",
"all",
"arguments",
"have",
"a",
"specification"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/sap.py#L166-L170 | train | 233,253 |
gem/oq-engine | openquake/baselib/sap.py | Script.callfunc | def callfunc(self, argv=None):
"""
Parse the argv list and extract a dictionary of arguments which
is then passed to the function underlying the script.
"""
if not self.checked:
self.check_arguments()
self.checked = True
namespace = self.parentparser.parse_args(argv or sys.argv[1:])
return self.func(**vars(namespace)) | python | def callfunc(self, argv=None):
"""
Parse the argv list and extract a dictionary of arguments which
is then passed to the function underlying the script.
"""
if not self.checked:
self.check_arguments()
self.checked = True
namespace = self.parentparser.parse_args(argv or sys.argv[1:])
return self.func(**vars(namespace)) | [
"def",
"callfunc",
"(",
"self",
",",
"argv",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"checked",
":",
"self",
".",
"check_arguments",
"(",
")",
"self",
".",
"checked",
"=",
"True",
"namespace",
"=",
"self",
".",
"parentparser",
".",
"parse_args",
"(",
"argv",
"or",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
"return",
"self",
".",
"func",
"(",
"*",
"*",
"vars",
"(",
"namespace",
")",
")"
] | Parse the argv list and extract a dictionary of arguments which
is then passed to the function underlying the script. | [
"Parse",
"the",
"argv",
"list",
"and",
"extract",
"a",
"dictionary",
"of",
"arguments",
"which",
"is",
"then",
"passed",
"to",
"the",
"function",
"underlying",
"the",
"script",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/sap.py#L172-L181 | train | 233,254 |
gem/oq-engine | openquake/hmtk/faults/mfd/anderson_luco_arbitrary.py | Type1RecurrenceModel.incremental_value | def incremental_value(self, slip_moment, mmax, mag_value, bbar, dbar):
"""
Returns the incremental rate of earthquakes with M = mag_value
"""
delta_m = mmax - mag_value
dirac_term = np.zeros_like(mag_value)
dirac_term[np.fabs(delta_m) < 1.0E-12] = 1.0
a_1 = self._get_a1(bbar, dbar, slip_moment, mmax)
return a_1 * (bbar * np.exp(bbar * delta_m) * (delta_m > 0.0)) +\
a_1 * dirac_term | python | def incremental_value(self, slip_moment, mmax, mag_value, bbar, dbar):
"""
Returns the incremental rate of earthquakes with M = mag_value
"""
delta_m = mmax - mag_value
dirac_term = np.zeros_like(mag_value)
dirac_term[np.fabs(delta_m) < 1.0E-12] = 1.0
a_1 = self._get_a1(bbar, dbar, slip_moment, mmax)
return a_1 * (bbar * np.exp(bbar * delta_m) * (delta_m > 0.0)) +\
a_1 * dirac_term | [
"def",
"incremental_value",
"(",
"self",
",",
"slip_moment",
",",
"mmax",
",",
"mag_value",
",",
"bbar",
",",
"dbar",
")",
":",
"delta_m",
"=",
"mmax",
"-",
"mag_value",
"dirac_term",
"=",
"np",
".",
"zeros_like",
"(",
"mag_value",
")",
"dirac_term",
"[",
"np",
".",
"fabs",
"(",
"delta_m",
")",
"<",
"1.0E-12",
"]",
"=",
"1.0",
"a_1",
"=",
"self",
".",
"_get_a1",
"(",
"bbar",
",",
"dbar",
",",
"slip_moment",
",",
"mmax",
")",
"return",
"a_1",
"*",
"(",
"bbar",
"*",
"np",
".",
"exp",
"(",
"bbar",
"*",
"delta_m",
")",
"*",
"(",
"delta_m",
">",
"0.0",
")",
")",
"+",
"a_1",
"*",
"dirac_term"
] | Returns the incremental rate of earthquakes with M = mag_value | [
"Returns",
"the",
"incremental",
"rate",
"of",
"earthquakes",
"with",
"M",
"=",
"mag_value"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/mfd/anderson_luco_arbitrary.py#L128-L137 | train | 233,255 |
gem/oq-engine | openquake/hmtk/faults/mfd/anderson_luco_arbitrary.py | Type2RecurrenceModel._get_a2 | def _get_a2(bbar, dbar, slip_moment, mmax):
"""
Returns the A2 value defined in II.4 of Table 2
"""
return ((dbar - bbar) / bbar) * (slip_moment / _scale_moment(mmax)) | python | def _get_a2(bbar, dbar, slip_moment, mmax):
"""
Returns the A2 value defined in II.4 of Table 2
"""
return ((dbar - bbar) / bbar) * (slip_moment / _scale_moment(mmax)) | [
"def",
"_get_a2",
"(",
"bbar",
",",
"dbar",
",",
"slip_moment",
",",
"mmax",
")",
":",
"return",
"(",
"(",
"dbar",
"-",
"bbar",
")",
"/",
"bbar",
")",
"*",
"(",
"slip_moment",
"/",
"_scale_moment",
"(",
"mmax",
")",
")"
] | Returns the A2 value defined in II.4 of Table 2 | [
"Returns",
"the",
"A2",
"value",
"defined",
"in",
"II",
".",
"4",
"of",
"Table",
"2"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/mfd/anderson_luco_arbitrary.py#L166-L170 | train | 233,256 |
gem/oq-engine | openquake/hmtk/faults/mfd/anderson_luco_arbitrary.py | Type3RecurrenceModel.incremental_value | def incremental_value(self, slip_moment, mmax, mag_value, bbar, dbar):
"""
Returns the incremental rate with Mmax = Mag_value
"""
delta_m = mmax - mag_value
a_3 = self._get_a3(bbar, dbar, slip_moment, mmax)
return a_3 * bbar * (np.exp(bbar * delta_m) - 1.0) * (delta_m > 0.0) | python | def incremental_value(self, slip_moment, mmax, mag_value, bbar, dbar):
"""
Returns the incremental rate with Mmax = Mag_value
"""
delta_m = mmax - mag_value
a_3 = self._get_a3(bbar, dbar, slip_moment, mmax)
return a_3 * bbar * (np.exp(bbar * delta_m) - 1.0) * (delta_m > 0.0) | [
"def",
"incremental_value",
"(",
"self",
",",
"slip_moment",
",",
"mmax",
",",
"mag_value",
",",
"bbar",
",",
"dbar",
")",
":",
"delta_m",
"=",
"mmax",
"-",
"mag_value",
"a_3",
"=",
"self",
".",
"_get_a3",
"(",
"bbar",
",",
"dbar",
",",
"slip_moment",
",",
"mmax",
")",
"return",
"a_3",
"*",
"bbar",
"*",
"(",
"np",
".",
"exp",
"(",
"bbar",
"*",
"delta_m",
")",
"-",
"1.0",
")",
"*",
"(",
"delta_m",
">",
"0.0",
")"
] | Returns the incremental rate with Mmax = Mag_value | [
"Returns",
"the",
"incremental",
"rate",
"with",
"Mmax",
"=",
"Mag_value"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/mfd/anderson_luco_arbitrary.py#L215-L221 | train | 233,257 |
gem/oq-engine | openquake/hmtk/faults/mfd/anderson_luco_arbitrary.py | AndersonLucoArbitrary.get_mmax | def get_mmax(self, mfd_conf, msr, rake, area):
'''
Gets the mmax for the fault - reading directly from the config file
or using the msr otherwise
:param dict mfd_config:
Configuration file (see setUp for paramters)
:param msr:
Instance of :class:`nhlib.scalerel`
:param float rake:
Rake of the fault (in range -180 to 180)
:param float area:
Area of the fault surface (km^2)
'''
if mfd_conf['Maximum_Magnitude']:
self.mmax = mfd_conf['Maximum_Magnitude']
else:
self.mmax = msr.get_median_mag(area, rake)
if ('Maximum_Magnitude_Uncertainty' in mfd_conf and
mfd_conf['Maximum_Magnitude_Uncertainty']):
self.mmax_sigma = mfd_conf['Maximum_Magnitude_Uncertainty']
else:
self.mmax_sigma = msr.get_std_dev_mag(rake) | python | def get_mmax(self, mfd_conf, msr, rake, area):
'''
Gets the mmax for the fault - reading directly from the config file
or using the msr otherwise
:param dict mfd_config:
Configuration file (see setUp for paramters)
:param msr:
Instance of :class:`nhlib.scalerel`
:param float rake:
Rake of the fault (in range -180 to 180)
:param float area:
Area of the fault surface (km^2)
'''
if mfd_conf['Maximum_Magnitude']:
self.mmax = mfd_conf['Maximum_Magnitude']
else:
self.mmax = msr.get_median_mag(area, rake)
if ('Maximum_Magnitude_Uncertainty' in mfd_conf and
mfd_conf['Maximum_Magnitude_Uncertainty']):
self.mmax_sigma = mfd_conf['Maximum_Magnitude_Uncertainty']
else:
self.mmax_sigma = msr.get_std_dev_mag(rake) | [
"def",
"get_mmax",
"(",
"self",
",",
"mfd_conf",
",",
"msr",
",",
"rake",
",",
"area",
")",
":",
"if",
"mfd_conf",
"[",
"'Maximum_Magnitude'",
"]",
":",
"self",
".",
"mmax",
"=",
"mfd_conf",
"[",
"'Maximum_Magnitude'",
"]",
"else",
":",
"self",
".",
"mmax",
"=",
"msr",
".",
"get_median_mag",
"(",
"area",
",",
"rake",
")",
"if",
"(",
"'Maximum_Magnitude_Uncertainty'",
"in",
"mfd_conf",
"and",
"mfd_conf",
"[",
"'Maximum_Magnitude_Uncertainty'",
"]",
")",
":",
"self",
".",
"mmax_sigma",
"=",
"mfd_conf",
"[",
"'Maximum_Magnitude_Uncertainty'",
"]",
"else",
":",
"self",
".",
"mmax_sigma",
"=",
"msr",
".",
"get_std_dev_mag",
"(",
"rake",
")"
] | Gets the mmax for the fault - reading directly from the config file
or using the msr otherwise
:param dict mfd_config:
Configuration file (see setUp for paramters)
:param msr:
Instance of :class:`nhlib.scalerel`
:param float rake:
Rake of the fault (in range -180 to 180)
:param float area:
Area of the fault surface (km^2) | [
"Gets",
"the",
"mmax",
"for",
"the",
"fault",
"-",
"reading",
"directly",
"from",
"the",
"config",
"file",
"or",
"using",
"the",
"msr",
"otherwise"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/mfd/anderson_luco_arbitrary.py#L290-L316 | train | 233,258 |
gem/oq-engine | openquake/hazardlib/gsim/lin_2009.py | Lin2009._get_magnitude_term | def _get_magnitude_term(self, C, mag):
"""
Returns the magnitude scaling term.
"""
lny = C['C1'] + (C['C3'] * ((8.5 - mag) ** 2.))
if mag > 6.3:
return lny + (-C['H'] * C['C5']) * (mag - 6.3)
else:
return lny + C['C2'] * (mag - 6.3) | python | def _get_magnitude_term(self, C, mag):
"""
Returns the magnitude scaling term.
"""
lny = C['C1'] + (C['C3'] * ((8.5 - mag) ** 2.))
if mag > 6.3:
return lny + (-C['H'] * C['C5']) * (mag - 6.3)
else:
return lny + C['C2'] * (mag - 6.3) | [
"def",
"_get_magnitude_term",
"(",
"self",
",",
"C",
",",
"mag",
")",
":",
"lny",
"=",
"C",
"[",
"'C1'",
"]",
"+",
"(",
"C",
"[",
"'C3'",
"]",
"*",
"(",
"(",
"8.5",
"-",
"mag",
")",
"**",
"2.",
")",
")",
"if",
"mag",
">",
"6.3",
":",
"return",
"lny",
"+",
"(",
"-",
"C",
"[",
"'H'",
"]",
"*",
"C",
"[",
"'C5'",
"]",
")",
"*",
"(",
"mag",
"-",
"6.3",
")",
"else",
":",
"return",
"lny",
"+",
"C",
"[",
"'C2'",
"]",
"*",
"(",
"mag",
"-",
"6.3",
")"
] | Returns the magnitude scaling term. | [
"Returns",
"the",
"magnitude",
"scaling",
"term",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/lin_2009.py#L83-L91 | train | 233,259 |
gem/oq-engine | openquake/hazardlib/gsim/lin_2009.py | Lin2009._get_style_of_faulting_term | def _get_style_of_faulting_term(self, C, rake):
"""
Returns the style of faulting factor
"""
f_n, f_r = self._get_fault_type_dummy_variables(rake)
return C['C6'] * f_n + C['C7'] * f_r | python | def _get_style_of_faulting_term(self, C, rake):
"""
Returns the style of faulting factor
"""
f_n, f_r = self._get_fault_type_dummy_variables(rake)
return C['C6'] * f_n + C['C7'] * f_r | [
"def",
"_get_style_of_faulting_term",
"(",
"self",
",",
"C",
",",
"rake",
")",
":",
"f_n",
",",
"f_r",
"=",
"self",
".",
"_get_fault_type_dummy_variables",
"(",
"rake",
")",
"return",
"C",
"[",
"'C6'",
"]",
"*",
"f_n",
"+",
"C",
"[",
"'C7'",
"]",
"*",
"f_r"
] | Returns the style of faulting factor | [
"Returns",
"the",
"style",
"of",
"faulting",
"factor"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/lin_2009.py#L100-L105 | train | 233,260 |
gem/oq-engine | openquake/hazardlib/gsim/lin_2009.py | Lin2009._get_stddevs | def _get_stddevs(self, C, stddev_types, nsites):
"""
Compute total standard deviation, see table 4.2, page 50.
"""
stddevs = []
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if stddev_type == const.StdDev.TOTAL:
stddevs.append(C['sigma'] + np.zeros(nsites, dtype=float))
return stddevs | python | def _get_stddevs(self, C, stddev_types, nsites):
"""
Compute total standard deviation, see table 4.2, page 50.
"""
stddevs = []
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if stddev_type == const.StdDev.TOTAL:
stddevs.append(C['sigma'] + np.zeros(nsites, dtype=float))
return stddevs | [
"def",
"_get_stddevs",
"(",
"self",
",",
"C",
",",
"stddev_types",
",",
"nsites",
")",
":",
"stddevs",
"=",
"[",
"]",
"for",
"stddev_type",
"in",
"stddev_types",
":",
"assert",
"stddev_type",
"in",
"self",
".",
"DEFINED_FOR_STANDARD_DEVIATION_TYPES",
"if",
"stddev_type",
"==",
"const",
".",
"StdDev",
".",
"TOTAL",
":",
"stddevs",
".",
"append",
"(",
"C",
"[",
"'sigma'",
"]",
"+",
"np",
".",
"zeros",
"(",
"nsites",
",",
"dtype",
"=",
"float",
")",
")",
"return",
"stddevs"
] | Compute total standard deviation, see table 4.2, page 50. | [
"Compute",
"total",
"standard",
"deviation",
"see",
"table",
"4",
".",
"2",
"page",
"50",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/lin_2009.py#L128-L137 | train | 233,261 |
gem/oq-engine | openquake/hazardlib/calc/disagg.py | lon_lat_bins | def lon_lat_bins(bb, coord_bin_width):
"""
Define bin edges for disaggregation histograms.
Given bins data as provided by :func:`collect_bin_data`, this function
finds edges of histograms, taking into account maximum and minimum values
of magnitude, distance and coordinates as well as requested sizes/numbers
of bins.
"""
west, south, east, north = bb
west = numpy.floor(west / coord_bin_width) * coord_bin_width
east = numpy.ceil(east / coord_bin_width) * coord_bin_width
lon_extent = get_longitudinal_extent(west, east)
lon_bins, _, _ = npoints_between(
west, 0, 0, east, 0, 0,
numpy.round(lon_extent / coord_bin_width + 1))
lat_bins = coord_bin_width * numpy.arange(
int(numpy.floor(south / coord_bin_width)),
int(numpy.ceil(north / coord_bin_width) + 1))
return lon_bins, lat_bins | python | def lon_lat_bins(bb, coord_bin_width):
"""
Define bin edges for disaggregation histograms.
Given bins data as provided by :func:`collect_bin_data`, this function
finds edges of histograms, taking into account maximum and minimum values
of magnitude, distance and coordinates as well as requested sizes/numbers
of bins.
"""
west, south, east, north = bb
west = numpy.floor(west / coord_bin_width) * coord_bin_width
east = numpy.ceil(east / coord_bin_width) * coord_bin_width
lon_extent = get_longitudinal_extent(west, east)
lon_bins, _, _ = npoints_between(
west, 0, 0, east, 0, 0,
numpy.round(lon_extent / coord_bin_width + 1))
lat_bins = coord_bin_width * numpy.arange(
int(numpy.floor(south / coord_bin_width)),
int(numpy.ceil(north / coord_bin_width) + 1))
return lon_bins, lat_bins | [
"def",
"lon_lat_bins",
"(",
"bb",
",",
"coord_bin_width",
")",
":",
"west",
",",
"south",
",",
"east",
",",
"north",
"=",
"bb",
"west",
"=",
"numpy",
".",
"floor",
"(",
"west",
"/",
"coord_bin_width",
")",
"*",
"coord_bin_width",
"east",
"=",
"numpy",
".",
"ceil",
"(",
"east",
"/",
"coord_bin_width",
")",
"*",
"coord_bin_width",
"lon_extent",
"=",
"get_longitudinal_extent",
"(",
"west",
",",
"east",
")",
"lon_bins",
",",
"_",
",",
"_",
"=",
"npoints_between",
"(",
"west",
",",
"0",
",",
"0",
",",
"east",
",",
"0",
",",
"0",
",",
"numpy",
".",
"round",
"(",
"lon_extent",
"/",
"coord_bin_width",
"+",
"1",
")",
")",
"lat_bins",
"=",
"coord_bin_width",
"*",
"numpy",
".",
"arange",
"(",
"int",
"(",
"numpy",
".",
"floor",
"(",
"south",
"/",
"coord_bin_width",
")",
")",
",",
"int",
"(",
"numpy",
".",
"ceil",
"(",
"north",
"/",
"coord_bin_width",
")",
"+",
"1",
")",
")",
"return",
"lon_bins",
",",
"lat_bins"
] | Define bin edges for disaggregation histograms.
Given bins data as provided by :func:`collect_bin_data`, this function
finds edges of histograms, taking into account maximum and minimum values
of magnitude, distance and coordinates as well as requested sizes/numbers
of bins. | [
"Define",
"bin",
"edges",
"for",
"disaggregation",
"histograms",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/disagg.py#L92-L111 | train | 233,262 |
gem/oq-engine | openquake/hazardlib/calc/disagg.py | _digitize_lons | def _digitize_lons(lons, lon_bins):
"""
Return indices of the bins to which each value in lons belongs.
Takes into account the case in which longitude values cross the
international date line.
:parameter lons:
An instance of `numpy.ndarray`.
:parameter lons_bins:
An instance of `numpy.ndarray`.
"""
if cross_idl(lon_bins[0], lon_bins[-1]):
idx = numpy.zeros_like(lons, dtype=numpy.int)
for i_lon in range(len(lon_bins) - 1):
extents = get_longitudinal_extent(lons, lon_bins[i_lon + 1])
lon_idx = extents > 0
if i_lon != 0:
extents = get_longitudinal_extent(lon_bins[i_lon], lons)
lon_idx &= extents >= 0
idx[lon_idx] = i_lon
return numpy.array(idx)
else:
return numpy.digitize(lons, lon_bins) - 1 | python | def _digitize_lons(lons, lon_bins):
"""
Return indices of the bins to which each value in lons belongs.
Takes into account the case in which longitude values cross the
international date line.
:parameter lons:
An instance of `numpy.ndarray`.
:parameter lons_bins:
An instance of `numpy.ndarray`.
"""
if cross_idl(lon_bins[0], lon_bins[-1]):
idx = numpy.zeros_like(lons, dtype=numpy.int)
for i_lon in range(len(lon_bins) - 1):
extents = get_longitudinal_extent(lons, lon_bins[i_lon + 1])
lon_idx = extents > 0
if i_lon != 0:
extents = get_longitudinal_extent(lon_bins[i_lon], lons)
lon_idx &= extents >= 0
idx[lon_idx] = i_lon
return numpy.array(idx)
else:
return numpy.digitize(lons, lon_bins) - 1 | [
"def",
"_digitize_lons",
"(",
"lons",
",",
"lon_bins",
")",
":",
"if",
"cross_idl",
"(",
"lon_bins",
"[",
"0",
"]",
",",
"lon_bins",
"[",
"-",
"1",
"]",
")",
":",
"idx",
"=",
"numpy",
".",
"zeros_like",
"(",
"lons",
",",
"dtype",
"=",
"numpy",
".",
"int",
")",
"for",
"i_lon",
"in",
"range",
"(",
"len",
"(",
"lon_bins",
")",
"-",
"1",
")",
":",
"extents",
"=",
"get_longitudinal_extent",
"(",
"lons",
",",
"lon_bins",
"[",
"i_lon",
"+",
"1",
"]",
")",
"lon_idx",
"=",
"extents",
">",
"0",
"if",
"i_lon",
"!=",
"0",
":",
"extents",
"=",
"get_longitudinal_extent",
"(",
"lon_bins",
"[",
"i_lon",
"]",
",",
"lons",
")",
"lon_idx",
"&=",
"extents",
">=",
"0",
"idx",
"[",
"lon_idx",
"]",
"=",
"i_lon",
"return",
"numpy",
".",
"array",
"(",
"idx",
")",
"else",
":",
"return",
"numpy",
".",
"digitize",
"(",
"lons",
",",
"lon_bins",
")",
"-",
"1"
] | Return indices of the bins to which each value in lons belongs.
Takes into account the case in which longitude values cross the
international date line.
:parameter lons:
An instance of `numpy.ndarray`.
:parameter lons_bins:
An instance of `numpy.ndarray`. | [
"Return",
"indices",
"of",
"the",
"bins",
"to",
"which",
"each",
"value",
"in",
"lons",
"belongs",
".",
"Takes",
"into",
"account",
"the",
"case",
"in",
"which",
"longitude",
"values",
"cross",
"the",
"international",
"date",
"line",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/disagg.py#L188-L210 | train | 233,263 |
gem/oq-engine | openquake/hazardlib/calc/disagg.py | mag_pmf | def mag_pmf(matrix):
"""
Fold full disaggregation matrix to magnitude PMF.
:returns:
1d array, a histogram representing magnitude PMF.
"""
nmags, ndists, nlons, nlats, neps = matrix.shape
mag_pmf = numpy.zeros(nmags)
for i in range(nmags):
mag_pmf[i] = numpy.prod(
[1. - matrix[i, j, k, l, m]
for j in range(ndists)
for k in range(nlons)
for l in range(nlats)
for m in range(neps)])
return 1. - mag_pmf | python | def mag_pmf(matrix):
"""
Fold full disaggregation matrix to magnitude PMF.
:returns:
1d array, a histogram representing magnitude PMF.
"""
nmags, ndists, nlons, nlats, neps = matrix.shape
mag_pmf = numpy.zeros(nmags)
for i in range(nmags):
mag_pmf[i] = numpy.prod(
[1. - matrix[i, j, k, l, m]
for j in range(ndists)
for k in range(nlons)
for l in range(nlats)
for m in range(neps)])
return 1. - mag_pmf | [
"def",
"mag_pmf",
"(",
"matrix",
")",
":",
"nmags",
",",
"ndists",
",",
"nlons",
",",
"nlats",
",",
"neps",
"=",
"matrix",
".",
"shape",
"mag_pmf",
"=",
"numpy",
".",
"zeros",
"(",
"nmags",
")",
"for",
"i",
"in",
"range",
"(",
"nmags",
")",
":",
"mag_pmf",
"[",
"i",
"]",
"=",
"numpy",
".",
"prod",
"(",
"[",
"1.",
"-",
"matrix",
"[",
"i",
",",
"j",
",",
"k",
",",
"l",
",",
"m",
"]",
"for",
"j",
"in",
"range",
"(",
"ndists",
")",
"for",
"k",
"in",
"range",
"(",
"nlons",
")",
"for",
"l",
"in",
"range",
"(",
"nlats",
")",
"for",
"m",
"in",
"range",
"(",
"neps",
")",
"]",
")",
"return",
"1.",
"-",
"mag_pmf"
] | Fold full disaggregation matrix to magnitude PMF.
:returns:
1d array, a histogram representing magnitude PMF. | [
"Fold",
"full",
"disaggregation",
"matrix",
"to",
"magnitude",
"PMF",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/disagg.py#L338-L354 | train | 233,264 |
gem/oq-engine | openquake/hazardlib/calc/disagg.py | trt_pmf | def trt_pmf(matrices):
"""
Fold full disaggregation matrix to tectonic region type PMF.
:param matrices:
a matrix with T submatrices
:returns:
an array of T probabilities one per each tectonic region type
"""
ntrts, nmags, ndists, nlons, nlats, neps = matrices.shape
pmf = numpy.zeros(ntrts)
for t in range(ntrts):
pmf[t] = 1. - numpy.prod(
[1. - matrices[t, i, j, k, l, m]
for i in range(nmags)
for j in range(ndists)
for k in range(nlons)
for l in range(nlats)
for m in range(neps)])
return pmf | python | def trt_pmf(matrices):
"""
Fold full disaggregation matrix to tectonic region type PMF.
:param matrices:
a matrix with T submatrices
:returns:
an array of T probabilities one per each tectonic region type
"""
ntrts, nmags, ndists, nlons, nlats, neps = matrices.shape
pmf = numpy.zeros(ntrts)
for t in range(ntrts):
pmf[t] = 1. - numpy.prod(
[1. - matrices[t, i, j, k, l, m]
for i in range(nmags)
for j in range(ndists)
for k in range(nlons)
for l in range(nlats)
for m in range(neps)])
return pmf | [
"def",
"trt_pmf",
"(",
"matrices",
")",
":",
"ntrts",
",",
"nmags",
",",
"ndists",
",",
"nlons",
",",
"nlats",
",",
"neps",
"=",
"matrices",
".",
"shape",
"pmf",
"=",
"numpy",
".",
"zeros",
"(",
"ntrts",
")",
"for",
"t",
"in",
"range",
"(",
"ntrts",
")",
":",
"pmf",
"[",
"t",
"]",
"=",
"1.",
"-",
"numpy",
".",
"prod",
"(",
"[",
"1.",
"-",
"matrices",
"[",
"t",
",",
"i",
",",
"j",
",",
"k",
",",
"l",
",",
"m",
"]",
"for",
"i",
"in",
"range",
"(",
"nmags",
")",
"for",
"j",
"in",
"range",
"(",
"ndists",
")",
"for",
"k",
"in",
"range",
"(",
"nlons",
")",
"for",
"l",
"in",
"range",
"(",
"nlats",
")",
"for",
"m",
"in",
"range",
"(",
"neps",
")",
"]",
")",
"return",
"pmf"
] | Fold full disaggregation matrix to tectonic region type PMF.
:param matrices:
a matrix with T submatrices
:returns:
an array of T probabilities one per each tectonic region type | [
"Fold",
"full",
"disaggregation",
"matrix",
"to",
"tectonic",
"region",
"type",
"PMF",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/disagg.py#L376-L395 | train | 233,265 |
gem/oq-engine | openquake/commands/db.py | db | def db(cmd, args=()):
"""
Run a database command
"""
if cmd not in commands:
okcmds = '\n'.join(
'%s %s' % (name, repr(' '.join(args)) if args else '')
for name, args in sorted(commands.items()))
print('Invalid command "%s": choose one from\n%s' % (cmd, okcmds))
elif len(args) != len(commands[cmd]):
print('Wrong number of arguments, expected %s, got %s' % (
commands[cmd], args))
else:
dbserver.ensure_on()
res = logs.dbcmd(cmd, *convert(args))
if hasattr(res, '_fields') and res.__class__.__name__ != 'Row':
print(rst_table(res))
else:
print(res) | python | def db(cmd, args=()):
"""
Run a database command
"""
if cmd not in commands:
okcmds = '\n'.join(
'%s %s' % (name, repr(' '.join(args)) if args else '')
for name, args in sorted(commands.items()))
print('Invalid command "%s": choose one from\n%s' % (cmd, okcmds))
elif len(args) != len(commands[cmd]):
print('Wrong number of arguments, expected %s, got %s' % (
commands[cmd], args))
else:
dbserver.ensure_on()
res = logs.dbcmd(cmd, *convert(args))
if hasattr(res, '_fields') and res.__class__.__name__ != 'Row':
print(rst_table(res))
else:
print(res) | [
"def",
"db",
"(",
"cmd",
",",
"args",
"=",
"(",
")",
")",
":",
"if",
"cmd",
"not",
"in",
"commands",
":",
"okcmds",
"=",
"'\\n'",
".",
"join",
"(",
"'%s %s'",
"%",
"(",
"name",
",",
"repr",
"(",
"' '",
".",
"join",
"(",
"args",
")",
")",
"if",
"args",
"else",
"''",
")",
"for",
"name",
",",
"args",
"in",
"sorted",
"(",
"commands",
".",
"items",
"(",
")",
")",
")",
"print",
"(",
"'Invalid command \"%s\": choose one from\\n%s'",
"%",
"(",
"cmd",
",",
"okcmds",
")",
")",
"elif",
"len",
"(",
"args",
")",
"!=",
"len",
"(",
"commands",
"[",
"cmd",
"]",
")",
":",
"print",
"(",
"'Wrong number of arguments, expected %s, got %s'",
"%",
"(",
"commands",
"[",
"cmd",
"]",
",",
"args",
")",
")",
"else",
":",
"dbserver",
".",
"ensure_on",
"(",
")",
"res",
"=",
"logs",
".",
"dbcmd",
"(",
"cmd",
",",
"*",
"convert",
"(",
"args",
")",
")",
"if",
"hasattr",
"(",
"res",
",",
"'_fields'",
")",
"and",
"res",
".",
"__class__",
".",
"__name__",
"!=",
"'Row'",
":",
"print",
"(",
"rst_table",
"(",
"res",
")",
")",
"else",
":",
"print",
"(",
"res",
")"
] | Run a database command | [
"Run",
"a",
"database",
"command"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/db.py#L47-L65 | train | 233,266 |
gem/oq-engine | openquake/hazardlib/stats.py | mean_curve | def mean_curve(values, weights=None):
"""
Compute the mean by using numpy.average on the first axis.
"""
if weights is None:
weights = [1. / len(values)] * len(values)
if not isinstance(values, numpy.ndarray):
values = numpy.array(values)
return numpy.average(values, axis=0, weights=weights) | python | def mean_curve(values, weights=None):
"""
Compute the mean by using numpy.average on the first axis.
"""
if weights is None:
weights = [1. / len(values)] * len(values)
if not isinstance(values, numpy.ndarray):
values = numpy.array(values)
return numpy.average(values, axis=0, weights=weights) | [
"def",
"mean_curve",
"(",
"values",
",",
"weights",
"=",
"None",
")",
":",
"if",
"weights",
"is",
"None",
":",
"weights",
"=",
"[",
"1.",
"/",
"len",
"(",
"values",
")",
"]",
"*",
"len",
"(",
"values",
")",
"if",
"not",
"isinstance",
"(",
"values",
",",
"numpy",
".",
"ndarray",
")",
":",
"values",
"=",
"numpy",
".",
"array",
"(",
"values",
")",
"return",
"numpy",
".",
"average",
"(",
"values",
",",
"axis",
"=",
"0",
",",
"weights",
"=",
"weights",
")"
] | Compute the mean by using numpy.average on the first axis. | [
"Compute",
"the",
"mean",
"by",
"using",
"numpy",
".",
"average",
"on",
"the",
"first",
"axis",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/stats.py#L25-L33 | train | 233,267 |
gem/oq-engine | openquake/hazardlib/stats.py | quantile_curve | def quantile_curve(quantile, curves, weights=None):
"""
Compute the weighted quantile aggregate of a set of curves.
:param quantile:
Quantile value to calculate. Should be in the range [0.0, 1.0].
:param curves:
Array of R PoEs (possibly arrays)
:param weights:
Array-like of weights, 1 for each input curve, or None
:returns:
A numpy array representing the quantile aggregate
"""
if not isinstance(curves, numpy.ndarray):
curves = numpy.array(curves)
R = len(curves)
if weights is None:
weights = numpy.ones(R) / R
else:
weights = numpy.array(weights)
assert len(weights) == R, (len(weights), R)
result = numpy.zeros(curves.shape[1:])
for idx, _ in numpy.ndenumerate(result):
data = numpy.array([a[idx] for a in curves])
sorted_idxs = numpy.argsort(data)
sorted_weights = weights[sorted_idxs]
sorted_data = data[sorted_idxs]
cum_weights = numpy.cumsum(sorted_weights)
# get the quantile from the interpolated CDF
result[idx] = numpy.interp(quantile, cum_weights, sorted_data)
return result | python | def quantile_curve(quantile, curves, weights=None):
"""
Compute the weighted quantile aggregate of a set of curves.
:param quantile:
Quantile value to calculate. Should be in the range [0.0, 1.0].
:param curves:
Array of R PoEs (possibly arrays)
:param weights:
Array-like of weights, 1 for each input curve, or None
:returns:
A numpy array representing the quantile aggregate
"""
if not isinstance(curves, numpy.ndarray):
curves = numpy.array(curves)
R = len(curves)
if weights is None:
weights = numpy.ones(R) / R
else:
weights = numpy.array(weights)
assert len(weights) == R, (len(weights), R)
result = numpy.zeros(curves.shape[1:])
for idx, _ in numpy.ndenumerate(result):
data = numpy.array([a[idx] for a in curves])
sorted_idxs = numpy.argsort(data)
sorted_weights = weights[sorted_idxs]
sorted_data = data[sorted_idxs]
cum_weights = numpy.cumsum(sorted_weights)
# get the quantile from the interpolated CDF
result[idx] = numpy.interp(quantile, cum_weights, sorted_data)
return result | [
"def",
"quantile_curve",
"(",
"quantile",
",",
"curves",
",",
"weights",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"curves",
",",
"numpy",
".",
"ndarray",
")",
":",
"curves",
"=",
"numpy",
".",
"array",
"(",
"curves",
")",
"R",
"=",
"len",
"(",
"curves",
")",
"if",
"weights",
"is",
"None",
":",
"weights",
"=",
"numpy",
".",
"ones",
"(",
"R",
")",
"/",
"R",
"else",
":",
"weights",
"=",
"numpy",
".",
"array",
"(",
"weights",
")",
"assert",
"len",
"(",
"weights",
")",
"==",
"R",
",",
"(",
"len",
"(",
"weights",
")",
",",
"R",
")",
"result",
"=",
"numpy",
".",
"zeros",
"(",
"curves",
".",
"shape",
"[",
"1",
":",
"]",
")",
"for",
"idx",
",",
"_",
"in",
"numpy",
".",
"ndenumerate",
"(",
"result",
")",
":",
"data",
"=",
"numpy",
".",
"array",
"(",
"[",
"a",
"[",
"idx",
"]",
"for",
"a",
"in",
"curves",
"]",
")",
"sorted_idxs",
"=",
"numpy",
".",
"argsort",
"(",
"data",
")",
"sorted_weights",
"=",
"weights",
"[",
"sorted_idxs",
"]",
"sorted_data",
"=",
"data",
"[",
"sorted_idxs",
"]",
"cum_weights",
"=",
"numpy",
".",
"cumsum",
"(",
"sorted_weights",
")",
"# get the quantile from the interpolated CDF",
"result",
"[",
"idx",
"]",
"=",
"numpy",
".",
"interp",
"(",
"quantile",
",",
"cum_weights",
",",
"sorted_data",
")",
"return",
"result"
] | Compute the weighted quantile aggregate of a set of curves.
:param quantile:
Quantile value to calculate. Should be in the range [0.0, 1.0].
:param curves:
Array of R PoEs (possibly arrays)
:param weights:
Array-like of weights, 1 for each input curve, or None
:returns:
A numpy array representing the quantile aggregate | [
"Compute",
"the",
"weighted",
"quantile",
"aggregate",
"of",
"a",
"set",
"of",
"curves",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/stats.py#L44-L74 | train | 233,268 |
gem/oq-engine | openquake/hazardlib/gsim/toro_2002.py | ToroEtAl2002._compute_mean | def _compute_mean(self, C, mag, rjb):
"""
Compute mean value according to equation 3, page 46.
"""
mean = (C['c1'] +
self._compute_term1(C, mag) +
self._compute_term2(C, mag, rjb))
return mean | python | def _compute_mean(self, C, mag, rjb):
"""
Compute mean value according to equation 3, page 46.
"""
mean = (C['c1'] +
self._compute_term1(C, mag) +
self._compute_term2(C, mag, rjb))
return mean | [
"def",
"_compute_mean",
"(",
"self",
",",
"C",
",",
"mag",
",",
"rjb",
")",
":",
"mean",
"=",
"(",
"C",
"[",
"'c1'",
"]",
"+",
"self",
".",
"_compute_term1",
"(",
"C",
",",
"mag",
")",
"+",
"self",
".",
"_compute_term2",
"(",
"C",
",",
"mag",
",",
"rjb",
")",
")",
"return",
"mean"
] | Compute mean value according to equation 3, page 46. | [
"Compute",
"mean",
"value",
"according",
"to",
"equation",
"3",
"page",
"46",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/toro_2002.py#L121-L128 | train | 233,269 |
gem/oq-engine | openquake/hazardlib/gsim/toro_2002.py | ToroEtAl2002._compute_stddevs | def _compute_stddevs(self, C, mag, rjb, imt, stddev_types):
"""
Compute total standard deviation, equations 5 and 6, page 48.
"""
# aleatory uncertainty
sigma_ale_m = np.interp(mag, [5.0, 5.5, 8.0],
[C['m50'], C['m55'], C['m80']])
sigma_ale_rjb = np.interp(rjb, [5.0, 20.0], [C['r5'], C['r20']])
sigma_ale = np.sqrt(sigma_ale_m ** 2 + sigma_ale_rjb ** 2)
# epistemic uncertainty
if imt.period < 1:
sigma_epi = 0.36 + 0.07 * (mag - 6)
else:
sigma_epi = 0.34 + 0.06 * (mag - 6)
sigma_total = np.sqrt(sigma_ale ** 2 + sigma_epi ** 2)
stddevs = []
for _ in stddev_types:
stddevs.append(sigma_total)
return stddevs | python | def _compute_stddevs(self, C, mag, rjb, imt, stddev_types):
"""
Compute total standard deviation, equations 5 and 6, page 48.
"""
# aleatory uncertainty
sigma_ale_m = np.interp(mag, [5.0, 5.5, 8.0],
[C['m50'], C['m55'], C['m80']])
sigma_ale_rjb = np.interp(rjb, [5.0, 20.0], [C['r5'], C['r20']])
sigma_ale = np.sqrt(sigma_ale_m ** 2 + sigma_ale_rjb ** 2)
# epistemic uncertainty
if imt.period < 1:
sigma_epi = 0.36 + 0.07 * (mag - 6)
else:
sigma_epi = 0.34 + 0.06 * (mag - 6)
sigma_total = np.sqrt(sigma_ale ** 2 + sigma_epi ** 2)
stddevs = []
for _ in stddev_types:
stddevs.append(sigma_total)
return stddevs | [
"def",
"_compute_stddevs",
"(",
"self",
",",
"C",
",",
"mag",
",",
"rjb",
",",
"imt",
",",
"stddev_types",
")",
":",
"# aleatory uncertainty",
"sigma_ale_m",
"=",
"np",
".",
"interp",
"(",
"mag",
",",
"[",
"5.0",
",",
"5.5",
",",
"8.0",
"]",
",",
"[",
"C",
"[",
"'m50'",
"]",
",",
"C",
"[",
"'m55'",
"]",
",",
"C",
"[",
"'m80'",
"]",
"]",
")",
"sigma_ale_rjb",
"=",
"np",
".",
"interp",
"(",
"rjb",
",",
"[",
"5.0",
",",
"20.0",
"]",
",",
"[",
"C",
"[",
"'r5'",
"]",
",",
"C",
"[",
"'r20'",
"]",
"]",
")",
"sigma_ale",
"=",
"np",
".",
"sqrt",
"(",
"sigma_ale_m",
"**",
"2",
"+",
"sigma_ale_rjb",
"**",
"2",
")",
"# epistemic uncertainty",
"if",
"imt",
".",
"period",
"<",
"1",
":",
"sigma_epi",
"=",
"0.36",
"+",
"0.07",
"*",
"(",
"mag",
"-",
"6",
")",
"else",
":",
"sigma_epi",
"=",
"0.34",
"+",
"0.06",
"*",
"(",
"mag",
"-",
"6",
")",
"sigma_total",
"=",
"np",
".",
"sqrt",
"(",
"sigma_ale",
"**",
"2",
"+",
"sigma_epi",
"**",
"2",
")",
"stddevs",
"=",
"[",
"]",
"for",
"_",
"in",
"stddev_types",
":",
"stddevs",
".",
"append",
"(",
"sigma_total",
")",
"return",
"stddevs"
] | Compute total standard deviation, equations 5 and 6, page 48. | [
"Compute",
"total",
"standard",
"deviation",
"equations",
"5",
"and",
"6",
"page",
"48",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/toro_2002.py#L130-L152 | train | 233,270 |
gem/oq-engine | openquake/hazardlib/gsim/mgmpe/nrcan15_site_term.py | NRCan15SiteTerm.BA08_AB06 | def BA08_AB06(self, vs30, imt, pgar):
"""
Computes amplification factor similarly to what is done in the 2015
version of the Canada building code. An initial version of this code
was kindly provided by Michal Kolaj - Geological Survey of Canada
:param vs30:
Can be either a scalar or a :class:`~numpy.ndarray` instance
:param imt:
The intensity measure type
:param pgar:
The value of hazard on rock (vs30=760). Can be either a scalar or
a :class:`~numpy.ndarray` instance. Unit of measure is fractions
of gravity acceleration.
:return:
A scalar or a :class:`~numpy.ndarray` instance with the
amplification factor.
"""
fa = np.ones_like(vs30)
if np.isscalar(vs30):
vs30 = np.array([vs30])
if np.isscalar(pgar):
pgar = np.array([pgar])
#
# Fixing vs30 for hard rock to 1999 m/s. Beyond this threshold the
# motion will not be deamplified further
vs = copy.copy(vs30)
vs[vs >= 2000] = 1999.
#
# Computing motion on rock
idx = np.where(vs30 > 760)
if np.size(idx) > 0:
"""
# This is the original implementation - Since this code is
# experimental we keep it for possible further developments
# For values of Vs30 greater than 760 a linear interpolation is
# used between the gm factor at 2000 m/s and 760 m/s
C2 = self.COEFFS_AB06r[imt]
fa[idx] = 10**(np.interp(np.log10(vs[idx]),
np.log10([760.0, 2000.0]),
np.log10([1.0, C2['c']])))
"""
C = self.COEFFS_BA08[imt]
nl = BooreAtkinson2008()._get_site_amplification_non_linear(
vs[idx], pgar[idx], C)
lin = BooreAtkinson2008()._get_site_amplification_linear(
vs[idx], C)
tmp = np.exp(nl+lin)
fa[idx] = tmp
#
# For values of Vs30 lower than 760 the amplification is computed
# using the site term of Boore and Atkinson (2008)
idx = np.where(vs < 760.)
if np.size(idx) > 0:
C = self.COEFFS_BA08[imt]
nl = BooreAtkinson2008()._get_site_amplification_non_linear(
vs[idx], pgar[idx], C)
lin = BooreAtkinson2008()._get_site_amplification_linear(
vs[idx], C)
fa[idx] = np.exp(nl+lin)
return fa | python | def BA08_AB06(self, vs30, imt, pgar):
"""
Computes amplification factor similarly to what is done in the 2015
version of the Canada building code. An initial version of this code
was kindly provided by Michal Kolaj - Geological Survey of Canada
:param vs30:
Can be either a scalar or a :class:`~numpy.ndarray` instance
:param imt:
The intensity measure type
:param pgar:
The value of hazard on rock (vs30=760). Can be either a scalar or
a :class:`~numpy.ndarray` instance. Unit of measure is fractions
of gravity acceleration.
:return:
A scalar or a :class:`~numpy.ndarray` instance with the
amplification factor.
"""
fa = np.ones_like(vs30)
if np.isscalar(vs30):
vs30 = np.array([vs30])
if np.isscalar(pgar):
pgar = np.array([pgar])
#
# Fixing vs30 for hard rock to 1999 m/s. Beyond this threshold the
# motion will not be deamplified further
vs = copy.copy(vs30)
vs[vs >= 2000] = 1999.
#
# Computing motion on rock
idx = np.where(vs30 > 760)
if np.size(idx) > 0:
"""
# This is the original implementation - Since this code is
# experimental we keep it for possible further developments
# For values of Vs30 greater than 760 a linear interpolation is
# used between the gm factor at 2000 m/s and 760 m/s
C2 = self.COEFFS_AB06r[imt]
fa[idx] = 10**(np.interp(np.log10(vs[idx]),
np.log10([760.0, 2000.0]),
np.log10([1.0, C2['c']])))
"""
C = self.COEFFS_BA08[imt]
nl = BooreAtkinson2008()._get_site_amplification_non_linear(
vs[idx], pgar[idx], C)
lin = BooreAtkinson2008()._get_site_amplification_linear(
vs[idx], C)
tmp = np.exp(nl+lin)
fa[idx] = tmp
#
# For values of Vs30 lower than 760 the amplification is computed
# using the site term of Boore and Atkinson (2008)
idx = np.where(vs < 760.)
if np.size(idx) > 0:
C = self.COEFFS_BA08[imt]
nl = BooreAtkinson2008()._get_site_amplification_non_linear(
vs[idx], pgar[idx], C)
lin = BooreAtkinson2008()._get_site_amplification_linear(
vs[idx], C)
fa[idx] = np.exp(nl+lin)
return fa | [
"def",
"BA08_AB06",
"(",
"self",
",",
"vs30",
",",
"imt",
",",
"pgar",
")",
":",
"fa",
"=",
"np",
".",
"ones_like",
"(",
"vs30",
")",
"if",
"np",
".",
"isscalar",
"(",
"vs30",
")",
":",
"vs30",
"=",
"np",
".",
"array",
"(",
"[",
"vs30",
"]",
")",
"if",
"np",
".",
"isscalar",
"(",
"pgar",
")",
":",
"pgar",
"=",
"np",
".",
"array",
"(",
"[",
"pgar",
"]",
")",
"#",
"# Fixing vs30 for hard rock to 1999 m/s. Beyond this threshold the",
"# motion will not be deamplified further",
"vs",
"=",
"copy",
".",
"copy",
"(",
"vs30",
")",
"vs",
"[",
"vs",
">=",
"2000",
"]",
"=",
"1999.",
"#",
"# Computing motion on rock",
"idx",
"=",
"np",
".",
"where",
"(",
"vs30",
">",
"760",
")",
"if",
"np",
".",
"size",
"(",
"idx",
")",
">",
"0",
":",
"\"\"\"\n # This is the original implementation - Since this code is\n # experimental we keep it for possible further developments\n # For values of Vs30 greater than 760 a linear interpolation is\n # used between the gm factor at 2000 m/s and 760 m/s\n C2 = self.COEFFS_AB06r[imt]\n fa[idx] = 10**(np.interp(np.log10(vs[idx]),\n np.log10([760.0, 2000.0]),\n np.log10([1.0, C2['c']])))\n \"\"\"",
"C",
"=",
"self",
".",
"COEFFS_BA08",
"[",
"imt",
"]",
"nl",
"=",
"BooreAtkinson2008",
"(",
")",
".",
"_get_site_amplification_non_linear",
"(",
"vs",
"[",
"idx",
"]",
",",
"pgar",
"[",
"idx",
"]",
",",
"C",
")",
"lin",
"=",
"BooreAtkinson2008",
"(",
")",
".",
"_get_site_amplification_linear",
"(",
"vs",
"[",
"idx",
"]",
",",
"C",
")",
"tmp",
"=",
"np",
".",
"exp",
"(",
"nl",
"+",
"lin",
")",
"fa",
"[",
"idx",
"]",
"=",
"tmp",
"#",
"# For values of Vs30 lower than 760 the amplification is computed",
"# using the site term of Boore and Atkinson (2008)",
"idx",
"=",
"np",
".",
"where",
"(",
"vs",
"<",
"760.",
")",
"if",
"np",
".",
"size",
"(",
"idx",
")",
">",
"0",
":",
"C",
"=",
"self",
".",
"COEFFS_BA08",
"[",
"imt",
"]",
"nl",
"=",
"BooreAtkinson2008",
"(",
")",
".",
"_get_site_amplification_non_linear",
"(",
"vs",
"[",
"idx",
"]",
",",
"pgar",
"[",
"idx",
"]",
",",
"C",
")",
"lin",
"=",
"BooreAtkinson2008",
"(",
")",
".",
"_get_site_amplification_linear",
"(",
"vs",
"[",
"idx",
"]",
",",
"C",
")",
"fa",
"[",
"idx",
"]",
"=",
"np",
".",
"exp",
"(",
"nl",
"+",
"lin",
")",
"return",
"fa"
] | Computes amplification factor similarly to what is done in the 2015
version of the Canada building code. An initial version of this code
was kindly provided by Michal Kolaj - Geological Survey of Canada
:param vs30:
Can be either a scalar or a :class:`~numpy.ndarray` instance
:param imt:
The intensity measure type
:param pgar:
The value of hazard on rock (vs30=760). Can be either a scalar or
a :class:`~numpy.ndarray` instance. Unit of measure is fractions
of gravity acceleration.
:return:
A scalar or a :class:`~numpy.ndarray` instance with the
amplification factor. | [
"Computes",
"amplification",
"factor",
"similarly",
"to",
"what",
"is",
"done",
"in",
"the",
"2015",
"version",
"of",
"the",
"Canada",
"building",
"code",
".",
"An",
"initial",
"version",
"of",
"this",
"code",
"was",
"kindly",
"provided",
"by",
"Michal",
"Kolaj",
"-",
"Geological",
"Survey",
"of",
"Canada"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/mgmpe/nrcan15_site_term.py#L89-L149 | train | 233,271 |
gem/oq-engine | openquake/calculators/scenario_damage.py | scenario_damage | def scenario_damage(riskinputs, riskmodel, param, monitor):
"""
Core function for a damage computation.
:param riskinputs:
:class:`openquake.risklib.riskinput.RiskInput` objects
:param riskmodel:
a :class:`openquake.risklib.riskinput.CompositeRiskModel` instance
:param monitor:
:class:`openquake.baselib.performance.Monitor` instance
:param param:
dictionary of extra parameters
:returns:
a dictionary {'d_asset': [(l, r, a, mean-stddev), ...],
'd_event': damage array of shape R, L, E, D,
'c_asset': [(l, r, a, mean-stddev), ...],
'c_event': damage array of shape R, L, E}
`d_asset` and `d_tag` are related to the damage distributions
whereas `c_asset` and `c_tag` are the consequence distributions.
If there is no consequence model `c_asset` is an empty list and
`c_tag` is a zero-valued array.
"""
L = len(riskmodel.loss_types)
D = len(riskmodel.damage_states)
E = param['number_of_ground_motion_fields']
R = riskinputs[0].hazard_getter.num_rlzs
result = dict(d_asset=[], d_event=numpy.zeros((E, R, L, D), F64),
c_asset=[], c_event=numpy.zeros((E, R, L), F64))
for ri in riskinputs:
for out in riskmodel.gen_outputs(ri, monitor):
r = out.rlzi
for l, loss_type in enumerate(riskmodel.loss_types):
for asset, fractions in zip(ri.assets, out[loss_type]):
dmg = fractions[:, :D] * asset['number'] # shape (E, D)
result['d_event'][:, r, l] += dmg
result['d_asset'].append(
(l, r, asset['ordinal'], scientific.mean_std(dmg)))
if riskmodel.consequences:
csq = fractions[:, D] * asset['value-' + loss_type]
result['c_asset'].append(
(l, r, asset['ordinal'], scientific.mean_std(csq)))
result['c_event'][:, r, l] += csq
return result | python | def scenario_damage(riskinputs, riskmodel, param, monitor):
"""
Core function for a damage computation.
:param riskinputs:
:class:`openquake.risklib.riskinput.RiskInput` objects
:param riskmodel:
a :class:`openquake.risklib.riskinput.CompositeRiskModel` instance
:param monitor:
:class:`openquake.baselib.performance.Monitor` instance
:param param:
dictionary of extra parameters
:returns:
a dictionary {'d_asset': [(l, r, a, mean-stddev), ...],
'd_event': damage array of shape R, L, E, D,
'c_asset': [(l, r, a, mean-stddev), ...],
'c_event': damage array of shape R, L, E}
`d_asset` and `d_tag` are related to the damage distributions
whereas `c_asset` and `c_tag` are the consequence distributions.
If there is no consequence model `c_asset` is an empty list and
`c_tag` is a zero-valued array.
"""
L = len(riskmodel.loss_types)
D = len(riskmodel.damage_states)
E = param['number_of_ground_motion_fields']
R = riskinputs[0].hazard_getter.num_rlzs
result = dict(d_asset=[], d_event=numpy.zeros((E, R, L, D), F64),
c_asset=[], c_event=numpy.zeros((E, R, L), F64))
for ri in riskinputs:
for out in riskmodel.gen_outputs(ri, monitor):
r = out.rlzi
for l, loss_type in enumerate(riskmodel.loss_types):
for asset, fractions in zip(ri.assets, out[loss_type]):
dmg = fractions[:, :D] * asset['number'] # shape (E, D)
result['d_event'][:, r, l] += dmg
result['d_asset'].append(
(l, r, asset['ordinal'], scientific.mean_std(dmg)))
if riskmodel.consequences:
csq = fractions[:, D] * asset['value-' + loss_type]
result['c_asset'].append(
(l, r, asset['ordinal'], scientific.mean_std(csq)))
result['c_event'][:, r, l] += csq
return result | [
"def",
"scenario_damage",
"(",
"riskinputs",
",",
"riskmodel",
",",
"param",
",",
"monitor",
")",
":",
"L",
"=",
"len",
"(",
"riskmodel",
".",
"loss_types",
")",
"D",
"=",
"len",
"(",
"riskmodel",
".",
"damage_states",
")",
"E",
"=",
"param",
"[",
"'number_of_ground_motion_fields'",
"]",
"R",
"=",
"riskinputs",
"[",
"0",
"]",
".",
"hazard_getter",
".",
"num_rlzs",
"result",
"=",
"dict",
"(",
"d_asset",
"=",
"[",
"]",
",",
"d_event",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"E",
",",
"R",
",",
"L",
",",
"D",
")",
",",
"F64",
")",
",",
"c_asset",
"=",
"[",
"]",
",",
"c_event",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"E",
",",
"R",
",",
"L",
")",
",",
"F64",
")",
")",
"for",
"ri",
"in",
"riskinputs",
":",
"for",
"out",
"in",
"riskmodel",
".",
"gen_outputs",
"(",
"ri",
",",
"monitor",
")",
":",
"r",
"=",
"out",
".",
"rlzi",
"for",
"l",
",",
"loss_type",
"in",
"enumerate",
"(",
"riskmodel",
".",
"loss_types",
")",
":",
"for",
"asset",
",",
"fractions",
"in",
"zip",
"(",
"ri",
".",
"assets",
",",
"out",
"[",
"loss_type",
"]",
")",
":",
"dmg",
"=",
"fractions",
"[",
":",
",",
":",
"D",
"]",
"*",
"asset",
"[",
"'number'",
"]",
"# shape (E, D)",
"result",
"[",
"'d_event'",
"]",
"[",
":",
",",
"r",
",",
"l",
"]",
"+=",
"dmg",
"result",
"[",
"'d_asset'",
"]",
".",
"append",
"(",
"(",
"l",
",",
"r",
",",
"asset",
"[",
"'ordinal'",
"]",
",",
"scientific",
".",
"mean_std",
"(",
"dmg",
")",
")",
")",
"if",
"riskmodel",
".",
"consequences",
":",
"csq",
"=",
"fractions",
"[",
":",
",",
"D",
"]",
"*",
"asset",
"[",
"'value-'",
"+",
"loss_type",
"]",
"result",
"[",
"'c_asset'",
"]",
".",
"append",
"(",
"(",
"l",
",",
"r",
",",
"asset",
"[",
"'ordinal'",
"]",
",",
"scientific",
".",
"mean_std",
"(",
"csq",
")",
")",
")",
"result",
"[",
"'c_event'",
"]",
"[",
":",
",",
"r",
",",
"l",
"]",
"+=",
"csq",
"return",
"result"
] | Core function for a damage computation.
:param riskinputs:
:class:`openquake.risklib.riskinput.RiskInput` objects
:param riskmodel:
a :class:`openquake.risklib.riskinput.CompositeRiskModel` instance
:param monitor:
:class:`openquake.baselib.performance.Monitor` instance
:param param:
dictionary of extra parameters
:returns:
a dictionary {'d_asset': [(l, r, a, mean-stddev), ...],
'd_event': damage array of shape R, L, E, D,
'c_asset': [(l, r, a, mean-stddev), ...],
'c_event': damage array of shape R, L, E}
`d_asset` and `d_tag` are related to the damage distributions
whereas `c_asset` and `c_tag` are the consequence distributions.
If there is no consequence model `c_asset` is an empty list and
`c_tag` is a zero-valued array. | [
"Core",
"function",
"for",
"a",
"damage",
"computation",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/scenario_damage.py#L28-L71 | train | 233,272 |
gem/oq-engine | openquake/calculators/views.py | form | def form(value):
"""
Format numbers in a nice way.
>>> form(0)
'0'
>>> form(0.0)
'0.0'
>>> form(0.0001)
'1.000E-04'
>>> form(1003.4)
'1,003'
>>> form(103.4)
'103'
>>> form(9.3)
'9.30000'
>>> form(-1.2)
'-1.2'
"""
if isinstance(value, FLOAT + INT):
if value <= 0:
return str(value)
elif value < .001:
return '%.3E' % value
elif value < 10 and isinstance(value, FLOAT):
return '%.5f' % value
elif value > 1000:
return '{:,d}'.format(int(round(value)))
elif numpy.isnan(value):
return 'NaN'
else: # in the range 10-1000
return str(int(value))
elif isinstance(value, bytes):
return decode(value)
elif isinstance(value, str):
return value
elif isinstance(value, numpy.object_):
return str(value)
elif hasattr(value, '__len__') and len(value) > 1:
return ' '.join(map(form, value))
return str(value) | python | def form(value):
"""
Format numbers in a nice way.
>>> form(0)
'0'
>>> form(0.0)
'0.0'
>>> form(0.0001)
'1.000E-04'
>>> form(1003.4)
'1,003'
>>> form(103.4)
'103'
>>> form(9.3)
'9.30000'
>>> form(-1.2)
'-1.2'
"""
if isinstance(value, FLOAT + INT):
if value <= 0:
return str(value)
elif value < .001:
return '%.3E' % value
elif value < 10 and isinstance(value, FLOAT):
return '%.5f' % value
elif value > 1000:
return '{:,d}'.format(int(round(value)))
elif numpy.isnan(value):
return 'NaN'
else: # in the range 10-1000
return str(int(value))
elif isinstance(value, bytes):
return decode(value)
elif isinstance(value, str):
return value
elif isinstance(value, numpy.object_):
return str(value)
elif hasattr(value, '__len__') and len(value) > 1:
return ' '.join(map(form, value))
return str(value) | [
"def",
"form",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"FLOAT",
"+",
"INT",
")",
":",
"if",
"value",
"<=",
"0",
":",
"return",
"str",
"(",
"value",
")",
"elif",
"value",
"<",
".001",
":",
"return",
"'%.3E'",
"%",
"value",
"elif",
"value",
"<",
"10",
"and",
"isinstance",
"(",
"value",
",",
"FLOAT",
")",
":",
"return",
"'%.5f'",
"%",
"value",
"elif",
"value",
">",
"1000",
":",
"return",
"'{:,d}'",
".",
"format",
"(",
"int",
"(",
"round",
"(",
"value",
")",
")",
")",
"elif",
"numpy",
".",
"isnan",
"(",
"value",
")",
":",
"return",
"'NaN'",
"else",
":",
"# in the range 10-1000",
"return",
"str",
"(",
"int",
"(",
"value",
")",
")",
"elif",
"isinstance",
"(",
"value",
",",
"bytes",
")",
":",
"return",
"decode",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"numpy",
".",
"object_",
")",
":",
"return",
"str",
"(",
"value",
")",
"elif",
"hasattr",
"(",
"value",
",",
"'__len__'",
")",
"and",
"len",
"(",
"value",
")",
">",
"1",
":",
"return",
"' '",
".",
"join",
"(",
"map",
"(",
"form",
",",
"value",
")",
")",
"return",
"str",
"(",
"value",
")"
] | Format numbers in a nice way.
>>> form(0)
'0'
>>> form(0.0)
'0.0'
>>> form(0.0001)
'1.000E-04'
>>> form(1003.4)
'1,003'
>>> form(103.4)
'103'
>>> form(9.3)
'9.30000'
>>> form(-1.2)
'-1.2' | [
"Format",
"numbers",
"in",
"a",
"nice",
"way",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L51-L91 | train | 233,273 |
gem/oq-engine | openquake/calculators/views.py | sum_tbl | def sum_tbl(tbl, kfield, vfields):
"""
Aggregate a composite array and compute the totals on a given key.
>>> dt = numpy.dtype([('name', (bytes, 10)), ('value', int)])
>>> tbl = numpy.array([('a', 1), ('a', 2), ('b', 3)], dt)
>>> sum_tbl(tbl, 'name', ['value'])['value']
array([3, 3])
"""
pairs = [(n, tbl.dtype[n]) for n in [kfield] + vfields]
dt = numpy.dtype(pairs + [('counts', int)])
def sum_all(group):
vals = numpy.zeros(1, dt)[0]
for rec in group:
for vfield in vfields:
vals[vfield] += rec[vfield]
vals['counts'] += 1
vals[kfield] = rec[kfield]
return vals
rows = groupby(tbl, operator.itemgetter(kfield), sum_all).values()
array = numpy.zeros(len(rows), dt)
for i, row in enumerate(rows):
for j, name in enumerate(dt.names):
array[i][name] = row[j]
return array | python | def sum_tbl(tbl, kfield, vfields):
"""
Aggregate a composite array and compute the totals on a given key.
>>> dt = numpy.dtype([('name', (bytes, 10)), ('value', int)])
>>> tbl = numpy.array([('a', 1), ('a', 2), ('b', 3)], dt)
>>> sum_tbl(tbl, 'name', ['value'])['value']
array([3, 3])
"""
pairs = [(n, tbl.dtype[n]) for n in [kfield] + vfields]
dt = numpy.dtype(pairs + [('counts', int)])
def sum_all(group):
vals = numpy.zeros(1, dt)[0]
for rec in group:
for vfield in vfields:
vals[vfield] += rec[vfield]
vals['counts'] += 1
vals[kfield] = rec[kfield]
return vals
rows = groupby(tbl, operator.itemgetter(kfield), sum_all).values()
array = numpy.zeros(len(rows), dt)
for i, row in enumerate(rows):
for j, name in enumerate(dt.names):
array[i][name] = row[j]
return array | [
"def",
"sum_tbl",
"(",
"tbl",
",",
"kfield",
",",
"vfields",
")",
":",
"pairs",
"=",
"[",
"(",
"n",
",",
"tbl",
".",
"dtype",
"[",
"n",
"]",
")",
"for",
"n",
"in",
"[",
"kfield",
"]",
"+",
"vfields",
"]",
"dt",
"=",
"numpy",
".",
"dtype",
"(",
"pairs",
"+",
"[",
"(",
"'counts'",
",",
"int",
")",
"]",
")",
"def",
"sum_all",
"(",
"group",
")",
":",
"vals",
"=",
"numpy",
".",
"zeros",
"(",
"1",
",",
"dt",
")",
"[",
"0",
"]",
"for",
"rec",
"in",
"group",
":",
"for",
"vfield",
"in",
"vfields",
":",
"vals",
"[",
"vfield",
"]",
"+=",
"rec",
"[",
"vfield",
"]",
"vals",
"[",
"'counts'",
"]",
"+=",
"1",
"vals",
"[",
"kfield",
"]",
"=",
"rec",
"[",
"kfield",
"]",
"return",
"vals",
"rows",
"=",
"groupby",
"(",
"tbl",
",",
"operator",
".",
"itemgetter",
"(",
"kfield",
")",
",",
"sum_all",
")",
".",
"values",
"(",
")",
"array",
"=",
"numpy",
".",
"zeros",
"(",
"len",
"(",
"rows",
")",
",",
"dt",
")",
"for",
"i",
",",
"row",
"in",
"enumerate",
"(",
"rows",
")",
":",
"for",
"j",
",",
"name",
"in",
"enumerate",
"(",
"dt",
".",
"names",
")",
":",
"array",
"[",
"i",
"]",
"[",
"name",
"]",
"=",
"row",
"[",
"j",
"]",
"return",
"array"
] | Aggregate a composite array and compute the totals on a given key.
>>> dt = numpy.dtype([('name', (bytes, 10)), ('value', int)])
>>> tbl = numpy.array([('a', 1), ('a', 2), ('b', 3)], dt)
>>> sum_tbl(tbl, 'name', ['value'])['value']
array([3, 3]) | [
"Aggregate",
"a",
"composite",
"array",
"and",
"compute",
"the",
"totals",
"on",
"a",
"given",
"key",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L145-L170 | train | 233,274 |
gem/oq-engine | openquake/calculators/views.py | view_slow_sources | def view_slow_sources(token, dstore, maxrows=20):
"""
Returns the slowest sources
"""
info = dstore['source_info'].value
info.sort(order='calc_time')
return rst_table(info[::-1][:maxrows]) | python | def view_slow_sources(token, dstore, maxrows=20):
"""
Returns the slowest sources
"""
info = dstore['source_info'].value
info.sort(order='calc_time')
return rst_table(info[::-1][:maxrows]) | [
"def",
"view_slow_sources",
"(",
"token",
",",
"dstore",
",",
"maxrows",
"=",
"20",
")",
":",
"info",
"=",
"dstore",
"[",
"'source_info'",
"]",
".",
"value",
"info",
".",
"sort",
"(",
"order",
"=",
"'calc_time'",
")",
"return",
"rst_table",
"(",
"info",
"[",
":",
":",
"-",
"1",
"]",
"[",
":",
"maxrows",
"]",
")"
] | Returns the slowest sources | [
"Returns",
"the",
"slowest",
"sources"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L183-L189 | train | 233,275 |
gem/oq-engine | openquake/calculators/views.py | view_contents | def view_contents(token, dstore):
"""
Returns the size of the contents of the datastore and its total size
"""
try:
desc = dstore['oqparam'].description
except KeyError:
desc = ''
data = sorted((dstore.getsize(key), key) for key in dstore)
rows = [(key, humansize(nbytes)) for nbytes, key in data]
total = '\n%s : %s' % (
dstore.filename, humansize(os.path.getsize(dstore.filename)))
return rst_table(rows, header=(desc, '')) + total | python | def view_contents(token, dstore):
"""
Returns the size of the contents of the datastore and its total size
"""
try:
desc = dstore['oqparam'].description
except KeyError:
desc = ''
data = sorted((dstore.getsize(key), key) for key in dstore)
rows = [(key, humansize(nbytes)) for nbytes, key in data]
total = '\n%s : %s' % (
dstore.filename, humansize(os.path.getsize(dstore.filename)))
return rst_table(rows, header=(desc, '')) + total | [
"def",
"view_contents",
"(",
"token",
",",
"dstore",
")",
":",
"try",
":",
"desc",
"=",
"dstore",
"[",
"'oqparam'",
"]",
".",
"description",
"except",
"KeyError",
":",
"desc",
"=",
"''",
"data",
"=",
"sorted",
"(",
"(",
"dstore",
".",
"getsize",
"(",
"key",
")",
",",
"key",
")",
"for",
"key",
"in",
"dstore",
")",
"rows",
"=",
"[",
"(",
"key",
",",
"humansize",
"(",
"nbytes",
")",
")",
"for",
"nbytes",
",",
"key",
"in",
"data",
"]",
"total",
"=",
"'\\n%s : %s'",
"%",
"(",
"dstore",
".",
"filename",
",",
"humansize",
"(",
"os",
".",
"path",
".",
"getsize",
"(",
"dstore",
".",
"filename",
")",
")",
")",
"return",
"rst_table",
"(",
"rows",
",",
"header",
"=",
"(",
"desc",
",",
"''",
")",
")",
"+",
"total"
] | Returns the size of the contents of the datastore and its total size | [
"Returns",
"the",
"size",
"of",
"the",
"contents",
"of",
"the",
"datastore",
"and",
"its",
"total",
"size"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L193-L205 | train | 233,276 |
gem/oq-engine | openquake/calculators/views.py | view_job_info | def view_job_info(token, dstore):
"""
Determine the amount of data transferred from the controller node
to the workers and back in a classical calculation.
"""
data = [['task', 'sent', 'received']]
for task in dstore['task_info']:
dset = dstore['task_info/' + task]
if 'argnames' in dset.attrs:
argnames = dset.attrs['argnames'].split()
totsent = dset.attrs['sent']
sent = ['%s=%s' % (a, humansize(s))
for s, a in sorted(zip(totsent, argnames), reverse=True)]
recv = dset['received'].sum()
data.append((task, ' '.join(sent), humansize(recv)))
return rst_table(data) | python | def view_job_info(token, dstore):
"""
Determine the amount of data transferred from the controller node
to the workers and back in a classical calculation.
"""
data = [['task', 'sent', 'received']]
for task in dstore['task_info']:
dset = dstore['task_info/' + task]
if 'argnames' in dset.attrs:
argnames = dset.attrs['argnames'].split()
totsent = dset.attrs['sent']
sent = ['%s=%s' % (a, humansize(s))
for s, a in sorted(zip(totsent, argnames), reverse=True)]
recv = dset['received'].sum()
data.append((task, ' '.join(sent), humansize(recv)))
return rst_table(data) | [
"def",
"view_job_info",
"(",
"token",
",",
"dstore",
")",
":",
"data",
"=",
"[",
"[",
"'task'",
",",
"'sent'",
",",
"'received'",
"]",
"]",
"for",
"task",
"in",
"dstore",
"[",
"'task_info'",
"]",
":",
"dset",
"=",
"dstore",
"[",
"'task_info/'",
"+",
"task",
"]",
"if",
"'argnames'",
"in",
"dset",
".",
"attrs",
":",
"argnames",
"=",
"dset",
".",
"attrs",
"[",
"'argnames'",
"]",
".",
"split",
"(",
")",
"totsent",
"=",
"dset",
".",
"attrs",
"[",
"'sent'",
"]",
"sent",
"=",
"[",
"'%s=%s'",
"%",
"(",
"a",
",",
"humansize",
"(",
"s",
")",
")",
"for",
"s",
",",
"a",
"in",
"sorted",
"(",
"zip",
"(",
"totsent",
",",
"argnames",
")",
",",
"reverse",
"=",
"True",
")",
"]",
"recv",
"=",
"dset",
"[",
"'received'",
"]",
".",
"sum",
"(",
")",
"data",
".",
"append",
"(",
"(",
"task",
",",
"' '",
".",
"join",
"(",
"sent",
")",
",",
"humansize",
"(",
"recv",
")",
")",
")",
"return",
"rst_table",
"(",
"data",
")"
] | Determine the amount of data transferred from the controller node
to the workers and back in a classical calculation. | [
"Determine",
"the",
"amount",
"of",
"data",
"transferred",
"from",
"the",
"controller",
"node",
"to",
"the",
"workers",
"and",
"back",
"in",
"a",
"classical",
"calculation",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L309-L324 | train | 233,277 |
gem/oq-engine | openquake/calculators/views.py | avglosses_data_transfer | def avglosses_data_transfer(token, dstore):
"""
Determine the amount of average losses transferred from the workers to the
controller node in a risk calculation.
"""
oq = dstore['oqparam']
N = len(dstore['assetcol'])
R = dstore['csm_info'].get_num_rlzs()
L = len(dstore.get_attr('risk_model', 'loss_types'))
ct = oq.concurrent_tasks
size_bytes = N * R * L * 8 * ct # 8 byte floats
return (
'%d asset(s) x %d realization(s) x %d loss type(s) losses x '
'8 bytes x %d tasks = %s' % (N, R, L, ct, humansize(size_bytes))) | python | def avglosses_data_transfer(token, dstore):
"""
Determine the amount of average losses transferred from the workers to the
controller node in a risk calculation.
"""
oq = dstore['oqparam']
N = len(dstore['assetcol'])
R = dstore['csm_info'].get_num_rlzs()
L = len(dstore.get_attr('risk_model', 'loss_types'))
ct = oq.concurrent_tasks
size_bytes = N * R * L * 8 * ct # 8 byte floats
return (
'%d asset(s) x %d realization(s) x %d loss type(s) losses x '
'8 bytes x %d tasks = %s' % (N, R, L, ct, humansize(size_bytes))) | [
"def",
"avglosses_data_transfer",
"(",
"token",
",",
"dstore",
")",
":",
"oq",
"=",
"dstore",
"[",
"'oqparam'",
"]",
"N",
"=",
"len",
"(",
"dstore",
"[",
"'assetcol'",
"]",
")",
"R",
"=",
"dstore",
"[",
"'csm_info'",
"]",
".",
"get_num_rlzs",
"(",
")",
"L",
"=",
"len",
"(",
"dstore",
".",
"get_attr",
"(",
"'risk_model'",
",",
"'loss_types'",
")",
")",
"ct",
"=",
"oq",
".",
"concurrent_tasks",
"size_bytes",
"=",
"N",
"*",
"R",
"*",
"L",
"*",
"8",
"*",
"ct",
"# 8 byte floats",
"return",
"(",
"'%d asset(s) x %d realization(s) x %d loss type(s) losses x '",
"'8 bytes x %d tasks = %s'",
"%",
"(",
"N",
",",
"R",
",",
"L",
",",
"ct",
",",
"humansize",
"(",
"size_bytes",
")",
")",
")"
] | Determine the amount of average losses transferred from the workers to the
controller node in a risk calculation. | [
"Determine",
"the",
"amount",
"of",
"average",
"losses",
"transferred",
"from",
"the",
"workers",
"to",
"the",
"controller",
"node",
"in",
"a",
"risk",
"calculation",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L328-L341 | train | 233,278 |
gem/oq-engine | openquake/calculators/views.py | ebr_data_transfer | def ebr_data_transfer(token, dstore):
"""
Display the data transferred in an event based risk calculation
"""
attrs = dstore['losses_by_event'].attrs
sent = humansize(attrs['sent'])
received = humansize(attrs['tot_received'])
return 'Event Based Risk: sent %s, received %s' % (sent, received) | python | def ebr_data_transfer(token, dstore):
"""
Display the data transferred in an event based risk calculation
"""
attrs = dstore['losses_by_event'].attrs
sent = humansize(attrs['sent'])
received = humansize(attrs['tot_received'])
return 'Event Based Risk: sent %s, received %s' % (sent, received) | [
"def",
"ebr_data_transfer",
"(",
"token",
",",
"dstore",
")",
":",
"attrs",
"=",
"dstore",
"[",
"'losses_by_event'",
"]",
".",
"attrs",
"sent",
"=",
"humansize",
"(",
"attrs",
"[",
"'sent'",
"]",
")",
"received",
"=",
"humansize",
"(",
"attrs",
"[",
"'tot_received'",
"]",
")",
"return",
"'Event Based Risk: sent %s, received %s'",
"%",
"(",
"sent",
",",
"received",
")"
] | Display the data transferred in an event based risk calculation | [
"Display",
"the",
"data",
"transferred",
"in",
"an",
"event",
"based",
"risk",
"calculation"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L345-L352 | train | 233,279 |
gem/oq-engine | openquake/calculators/views.py | view_totlosses | def view_totlosses(token, dstore):
"""
This is a debugging view. You can use it to check that the total
losses, i.e. the losses obtained by summing the average losses on
all assets are indeed equal to the aggregate losses. This is a
sanity check for the correctness of the implementation.
"""
oq = dstore['oqparam']
tot_losses = dstore['losses_by_asset']['mean'].sum(axis=0)
return rst_table(tot_losses.view(oq.loss_dt()), fmt='%.6E') | python | def view_totlosses(token, dstore):
"""
This is a debugging view. You can use it to check that the total
losses, i.e. the losses obtained by summing the average losses on
all assets are indeed equal to the aggregate losses. This is a
sanity check for the correctness of the implementation.
"""
oq = dstore['oqparam']
tot_losses = dstore['losses_by_asset']['mean'].sum(axis=0)
return rst_table(tot_losses.view(oq.loss_dt()), fmt='%.6E') | [
"def",
"view_totlosses",
"(",
"token",
",",
"dstore",
")",
":",
"oq",
"=",
"dstore",
"[",
"'oqparam'",
"]",
"tot_losses",
"=",
"dstore",
"[",
"'losses_by_asset'",
"]",
"[",
"'mean'",
"]",
".",
"sum",
"(",
"axis",
"=",
"0",
")",
"return",
"rst_table",
"(",
"tot_losses",
".",
"view",
"(",
"oq",
".",
"loss_dt",
"(",
")",
")",
",",
"fmt",
"=",
"'%.6E'",
")"
] | This is a debugging view. You can use it to check that the total
losses, i.e. the losses obtained by summing the average losses on
all assets are indeed equal to the aggregate losses. This is a
sanity check for the correctness of the implementation. | [
"This",
"is",
"a",
"debugging",
"view",
".",
"You",
"can",
"use",
"it",
"to",
"check",
"that",
"the",
"total",
"losses",
"i",
".",
"e",
".",
"the",
"losses",
"obtained",
"by",
"summing",
"the",
"average",
"losses",
"on",
"all",
"assets",
"are",
"indeed",
"equal",
"to",
"the",
"aggregate",
"losses",
".",
"This",
"is",
"a",
"sanity",
"check",
"for",
"the",
"correctness",
"of",
"the",
"implementation",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L357-L366 | train | 233,280 |
gem/oq-engine | openquake/calculators/views.py | view_portfolio_losses | def view_portfolio_losses(token, dstore):
"""
The losses for the full portfolio, for each realization and loss type,
extracted from the event loss table.
"""
oq = dstore['oqparam']
loss_dt = oq.loss_dt()
data = portfolio_loss(dstore).view(loss_dt)[:, 0]
rlzids = [str(r) for r in range(len(data))]
array = util.compose_arrays(numpy.array(rlzids), data, 'rlz')
# this is very sensitive to rounding errors, so I am using a low precision
return rst_table(array, fmt='%.5E') | python | def view_portfolio_losses(token, dstore):
"""
The losses for the full portfolio, for each realization and loss type,
extracted from the event loss table.
"""
oq = dstore['oqparam']
loss_dt = oq.loss_dt()
data = portfolio_loss(dstore).view(loss_dt)[:, 0]
rlzids = [str(r) for r in range(len(data))]
array = util.compose_arrays(numpy.array(rlzids), data, 'rlz')
# this is very sensitive to rounding errors, so I am using a low precision
return rst_table(array, fmt='%.5E') | [
"def",
"view_portfolio_losses",
"(",
"token",
",",
"dstore",
")",
":",
"oq",
"=",
"dstore",
"[",
"'oqparam'",
"]",
"loss_dt",
"=",
"oq",
".",
"loss_dt",
"(",
")",
"data",
"=",
"portfolio_loss",
"(",
"dstore",
")",
".",
"view",
"(",
"loss_dt",
")",
"[",
":",
",",
"0",
"]",
"rlzids",
"=",
"[",
"str",
"(",
"r",
")",
"for",
"r",
"in",
"range",
"(",
"len",
"(",
"data",
")",
")",
"]",
"array",
"=",
"util",
".",
"compose_arrays",
"(",
"numpy",
".",
"array",
"(",
"rlzids",
")",
",",
"data",
",",
"'rlz'",
")",
"# this is very sensitive to rounding errors, so I am using a low precision",
"return",
"rst_table",
"(",
"array",
",",
"fmt",
"=",
"'%.5E'",
")"
] | The losses for the full portfolio, for each realization and loss type,
extracted from the event loss table. | [
"The",
"losses",
"for",
"the",
"full",
"portfolio",
"for",
"each",
"realization",
"and",
"loss",
"type",
"extracted",
"from",
"the",
"event",
"loss",
"table",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L382-L393 | train | 233,281 |
gem/oq-engine | openquake/calculators/views.py | view_portfolio_loss | def view_portfolio_loss(token, dstore):
"""
The mean and stddev loss for the full portfolio for each loss type,
extracted from the event loss table, averaged over the realizations
"""
data = portfolio_loss(dstore) # shape (R, L)
loss_types = list(dstore['oqparam'].loss_dt().names)
header = ['portfolio_loss'] + loss_types
mean = ['mean'] + [row.mean() for row in data.T]
stddev = ['stddev'] + [row.std(ddof=1) for row in data.T]
return rst_table([mean, stddev], header) | python | def view_portfolio_loss(token, dstore):
"""
The mean and stddev loss for the full portfolio for each loss type,
extracted from the event loss table, averaged over the realizations
"""
data = portfolio_loss(dstore) # shape (R, L)
loss_types = list(dstore['oqparam'].loss_dt().names)
header = ['portfolio_loss'] + loss_types
mean = ['mean'] + [row.mean() for row in data.T]
stddev = ['stddev'] + [row.std(ddof=1) for row in data.T]
return rst_table([mean, stddev], header) | [
"def",
"view_portfolio_loss",
"(",
"token",
",",
"dstore",
")",
":",
"data",
"=",
"portfolio_loss",
"(",
"dstore",
")",
"# shape (R, L)",
"loss_types",
"=",
"list",
"(",
"dstore",
"[",
"'oqparam'",
"]",
".",
"loss_dt",
"(",
")",
".",
"names",
")",
"header",
"=",
"[",
"'portfolio_loss'",
"]",
"+",
"loss_types",
"mean",
"=",
"[",
"'mean'",
"]",
"+",
"[",
"row",
".",
"mean",
"(",
")",
"for",
"row",
"in",
"data",
".",
"T",
"]",
"stddev",
"=",
"[",
"'stddev'",
"]",
"+",
"[",
"row",
".",
"std",
"(",
"ddof",
"=",
"1",
")",
"for",
"row",
"in",
"data",
".",
"T",
"]",
"return",
"rst_table",
"(",
"[",
"mean",
",",
"stddev",
"]",
",",
"header",
")"
] | The mean and stddev loss for the full portfolio for each loss type,
extracted from the event loss table, averaged over the realizations | [
"The",
"mean",
"and",
"stddev",
"loss",
"for",
"the",
"full",
"portfolio",
"for",
"each",
"loss",
"type",
"extracted",
"from",
"the",
"event",
"loss",
"table",
"averaged",
"over",
"the",
"realizations"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L397-L407 | train | 233,282 |
gem/oq-engine | openquake/calculators/views.py | view_exposure_info | def view_exposure_info(token, dstore):
"""
Display info about the exposure model
"""
assetcol = dstore['assetcol/array'][:]
taxonomies = sorted(set(dstore['assetcol'].taxonomies))
cc = dstore['assetcol/cost_calculator']
ra_flag = ['relative', 'absolute']
data = [('#assets', len(assetcol)),
('#taxonomies', len(taxonomies)),
('deductibile', ra_flag[int(cc.deduct_abs)]),
('insurance_limit', ra_flag[int(cc.limit_abs)]),
]
return rst_table(data) + '\n\n' + view_assets_by_site(token, dstore) | python | def view_exposure_info(token, dstore):
"""
Display info about the exposure model
"""
assetcol = dstore['assetcol/array'][:]
taxonomies = sorted(set(dstore['assetcol'].taxonomies))
cc = dstore['assetcol/cost_calculator']
ra_flag = ['relative', 'absolute']
data = [('#assets', len(assetcol)),
('#taxonomies', len(taxonomies)),
('deductibile', ra_flag[int(cc.deduct_abs)]),
('insurance_limit', ra_flag[int(cc.limit_abs)]),
]
return rst_table(data) + '\n\n' + view_assets_by_site(token, dstore) | [
"def",
"view_exposure_info",
"(",
"token",
",",
"dstore",
")",
":",
"assetcol",
"=",
"dstore",
"[",
"'assetcol/array'",
"]",
"[",
":",
"]",
"taxonomies",
"=",
"sorted",
"(",
"set",
"(",
"dstore",
"[",
"'assetcol'",
"]",
".",
"taxonomies",
")",
")",
"cc",
"=",
"dstore",
"[",
"'assetcol/cost_calculator'",
"]",
"ra_flag",
"=",
"[",
"'relative'",
",",
"'absolute'",
"]",
"data",
"=",
"[",
"(",
"'#assets'",
",",
"len",
"(",
"assetcol",
")",
")",
",",
"(",
"'#taxonomies'",
",",
"len",
"(",
"taxonomies",
")",
")",
",",
"(",
"'deductibile'",
",",
"ra_flag",
"[",
"int",
"(",
"cc",
".",
"deduct_abs",
")",
"]",
")",
",",
"(",
"'insurance_limit'",
",",
"ra_flag",
"[",
"int",
"(",
"cc",
".",
"limit_abs",
")",
"]",
")",
",",
"]",
"return",
"rst_table",
"(",
"data",
")",
"+",
"'\\n\\n'",
"+",
"view_assets_by_site",
"(",
"token",
",",
"dstore",
")"
] | Display info about the exposure model | [
"Display",
"info",
"about",
"the",
"exposure",
"model"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L431-L444 | train | 233,283 |
gem/oq-engine | openquake/calculators/views.py | view_fullreport | def view_fullreport(token, dstore):
"""
Display an .rst report about the computation
"""
# avoid circular imports
from openquake.calculators.reportwriter import ReportWriter
return ReportWriter(dstore).make_report() | python | def view_fullreport(token, dstore):
"""
Display an .rst report about the computation
"""
# avoid circular imports
from openquake.calculators.reportwriter import ReportWriter
return ReportWriter(dstore).make_report() | [
"def",
"view_fullreport",
"(",
"token",
",",
"dstore",
")",
":",
"# avoid circular imports",
"from",
"openquake",
".",
"calculators",
".",
"reportwriter",
"import",
"ReportWriter",
"return",
"ReportWriter",
"(",
"dstore",
")",
".",
"make_report",
"(",
")"
] | Display an .rst report about the computation | [
"Display",
"an",
".",
"rst",
"report",
"about",
"the",
"computation"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L461-L467 | train | 233,284 |
gem/oq-engine | openquake/calculators/views.py | performance_view | def performance_view(dstore):
"""
Returns the performance view as a numpy array.
"""
data = sorted(dstore['performance_data'], key=operator.itemgetter(0))
out = []
for operation, group in itertools.groupby(data, operator.itemgetter(0)):
counts = 0
time = 0
mem = 0
for _operation, time_sec, memory_mb, counts_ in group:
counts += counts_
time += time_sec
mem = max(mem, memory_mb)
out.append((operation, time, mem, counts))
out.sort(key=operator.itemgetter(1), reverse=True) # sort by time
return numpy.array(out, perf_dt) | python | def performance_view(dstore):
"""
Returns the performance view as a numpy array.
"""
data = sorted(dstore['performance_data'], key=operator.itemgetter(0))
out = []
for operation, group in itertools.groupby(data, operator.itemgetter(0)):
counts = 0
time = 0
mem = 0
for _operation, time_sec, memory_mb, counts_ in group:
counts += counts_
time += time_sec
mem = max(mem, memory_mb)
out.append((operation, time, mem, counts))
out.sort(key=operator.itemgetter(1), reverse=True) # sort by time
return numpy.array(out, perf_dt) | [
"def",
"performance_view",
"(",
"dstore",
")",
":",
"data",
"=",
"sorted",
"(",
"dstore",
"[",
"'performance_data'",
"]",
",",
"key",
"=",
"operator",
".",
"itemgetter",
"(",
"0",
")",
")",
"out",
"=",
"[",
"]",
"for",
"operation",
",",
"group",
"in",
"itertools",
".",
"groupby",
"(",
"data",
",",
"operator",
".",
"itemgetter",
"(",
"0",
")",
")",
":",
"counts",
"=",
"0",
"time",
"=",
"0",
"mem",
"=",
"0",
"for",
"_operation",
",",
"time_sec",
",",
"memory_mb",
",",
"counts_",
"in",
"group",
":",
"counts",
"+=",
"counts_",
"time",
"+=",
"time_sec",
"mem",
"=",
"max",
"(",
"mem",
",",
"memory_mb",
")",
"out",
".",
"append",
"(",
"(",
"operation",
",",
"time",
",",
"mem",
",",
"counts",
")",
")",
"out",
".",
"sort",
"(",
"key",
"=",
"operator",
".",
"itemgetter",
"(",
"1",
")",
",",
"reverse",
"=",
"True",
")",
"# sort by time",
"return",
"numpy",
".",
"array",
"(",
"out",
",",
"perf_dt",
")"
] | Returns the performance view as a numpy array. | [
"Returns",
"the",
"performance",
"view",
"as",
"a",
"numpy",
"array",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L470-L486 | train | 233,285 |
gem/oq-engine | openquake/calculators/views.py | stats | def stats(name, array, *extras):
"""
Returns statistics from an array of numbers.
:param name: a descriptive string
:returns: (name, mean, std, min, max, len)
"""
std = numpy.nan if len(array) == 1 else numpy.std(array, ddof=1)
return (name, numpy.mean(array), std,
numpy.min(array), numpy.max(array), len(array)) + extras | python | def stats(name, array, *extras):
"""
Returns statistics from an array of numbers.
:param name: a descriptive string
:returns: (name, mean, std, min, max, len)
"""
std = numpy.nan if len(array) == 1 else numpy.std(array, ddof=1)
return (name, numpy.mean(array), std,
numpy.min(array), numpy.max(array), len(array)) + extras | [
"def",
"stats",
"(",
"name",
",",
"array",
",",
"*",
"extras",
")",
":",
"std",
"=",
"numpy",
".",
"nan",
"if",
"len",
"(",
"array",
")",
"==",
"1",
"else",
"numpy",
".",
"std",
"(",
"array",
",",
"ddof",
"=",
"1",
")",
"return",
"(",
"name",
",",
"numpy",
".",
"mean",
"(",
"array",
")",
",",
"std",
",",
"numpy",
".",
"min",
"(",
"array",
")",
",",
"numpy",
".",
"max",
"(",
"array",
")",
",",
"len",
"(",
"array",
")",
")",
"+",
"extras"
] | Returns statistics from an array of numbers.
:param name: a descriptive string
:returns: (name, mean, std, min, max, len) | [
"Returns",
"statistics",
"from",
"an",
"array",
"of",
"numbers",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L497-L506 | train | 233,286 |
gem/oq-engine | openquake/calculators/views.py | view_num_units | def view_num_units(token, dstore):
"""
Display the number of units by taxonomy
"""
taxo = dstore['assetcol/tagcol/taxonomy'].value
counts = collections.Counter()
for asset in dstore['assetcol']:
counts[taxo[asset['taxonomy']]] += asset['number']
data = sorted(counts.items())
data.append(('*ALL*', sum(d[1] for d in data)))
return rst_table(data, header=['taxonomy', 'num_units']) | python | def view_num_units(token, dstore):
"""
Display the number of units by taxonomy
"""
taxo = dstore['assetcol/tagcol/taxonomy'].value
counts = collections.Counter()
for asset in dstore['assetcol']:
counts[taxo[asset['taxonomy']]] += asset['number']
data = sorted(counts.items())
data.append(('*ALL*', sum(d[1] for d in data)))
return rst_table(data, header=['taxonomy', 'num_units']) | [
"def",
"view_num_units",
"(",
"token",
",",
"dstore",
")",
":",
"taxo",
"=",
"dstore",
"[",
"'assetcol/tagcol/taxonomy'",
"]",
".",
"value",
"counts",
"=",
"collections",
".",
"Counter",
"(",
")",
"for",
"asset",
"in",
"dstore",
"[",
"'assetcol'",
"]",
":",
"counts",
"[",
"taxo",
"[",
"asset",
"[",
"'taxonomy'",
"]",
"]",
"]",
"+=",
"asset",
"[",
"'number'",
"]",
"data",
"=",
"sorted",
"(",
"counts",
".",
"items",
"(",
")",
")",
"data",
".",
"append",
"(",
"(",
"'*ALL*'",
",",
"sum",
"(",
"d",
"[",
"1",
"]",
"for",
"d",
"in",
"data",
")",
")",
")",
"return",
"rst_table",
"(",
"data",
",",
"header",
"=",
"[",
"'taxonomy'",
",",
"'num_units'",
"]",
")"
] | Display the number of units by taxonomy | [
"Display",
"the",
"number",
"of",
"units",
"by",
"taxonomy"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L510-L520 | train | 233,287 |
gem/oq-engine | openquake/calculators/views.py | view_assets_by_site | def view_assets_by_site(token, dstore):
"""
Display statistical information about the distribution of the assets
"""
taxonomies = dstore['assetcol/tagcol/taxonomy'].value
assets_by_site = dstore['assetcol'].assets_by_site()
data = ['taxonomy mean stddev min max num_sites num_assets'.split()]
num_assets = AccumDict()
for assets in assets_by_site:
num_assets += {k: [len(v)] for k, v in group_array(
assets, 'taxonomy').items()}
for taxo in sorted(num_assets):
val = numpy.array(num_assets[taxo])
data.append(stats(taxonomies[taxo], val, val.sum()))
if len(num_assets) > 1: # more than one taxonomy, add a summary
n_assets = numpy.array([len(assets) for assets in assets_by_site])
data.append(stats('*ALL*', n_assets, n_assets.sum()))
return rst_table(data) | python | def view_assets_by_site(token, dstore):
"""
Display statistical information about the distribution of the assets
"""
taxonomies = dstore['assetcol/tagcol/taxonomy'].value
assets_by_site = dstore['assetcol'].assets_by_site()
data = ['taxonomy mean stddev min max num_sites num_assets'.split()]
num_assets = AccumDict()
for assets in assets_by_site:
num_assets += {k: [len(v)] for k, v in group_array(
assets, 'taxonomy').items()}
for taxo in sorted(num_assets):
val = numpy.array(num_assets[taxo])
data.append(stats(taxonomies[taxo], val, val.sum()))
if len(num_assets) > 1: # more than one taxonomy, add a summary
n_assets = numpy.array([len(assets) for assets in assets_by_site])
data.append(stats('*ALL*', n_assets, n_assets.sum()))
return rst_table(data) | [
"def",
"view_assets_by_site",
"(",
"token",
",",
"dstore",
")",
":",
"taxonomies",
"=",
"dstore",
"[",
"'assetcol/tagcol/taxonomy'",
"]",
".",
"value",
"assets_by_site",
"=",
"dstore",
"[",
"'assetcol'",
"]",
".",
"assets_by_site",
"(",
")",
"data",
"=",
"[",
"'taxonomy mean stddev min max num_sites num_assets'",
".",
"split",
"(",
")",
"]",
"num_assets",
"=",
"AccumDict",
"(",
")",
"for",
"assets",
"in",
"assets_by_site",
":",
"num_assets",
"+=",
"{",
"k",
":",
"[",
"len",
"(",
"v",
")",
"]",
"for",
"k",
",",
"v",
"in",
"group_array",
"(",
"assets",
",",
"'taxonomy'",
")",
".",
"items",
"(",
")",
"}",
"for",
"taxo",
"in",
"sorted",
"(",
"num_assets",
")",
":",
"val",
"=",
"numpy",
".",
"array",
"(",
"num_assets",
"[",
"taxo",
"]",
")",
"data",
".",
"append",
"(",
"stats",
"(",
"taxonomies",
"[",
"taxo",
"]",
",",
"val",
",",
"val",
".",
"sum",
"(",
")",
")",
")",
"if",
"len",
"(",
"num_assets",
")",
">",
"1",
":",
"# more than one taxonomy, add a summary",
"n_assets",
"=",
"numpy",
".",
"array",
"(",
"[",
"len",
"(",
"assets",
")",
"for",
"assets",
"in",
"assets_by_site",
"]",
")",
"data",
".",
"append",
"(",
"stats",
"(",
"'*ALL*'",
",",
"n_assets",
",",
"n_assets",
".",
"sum",
"(",
")",
")",
")",
"return",
"rst_table",
"(",
"data",
")"
] | Display statistical information about the distribution of the assets | [
"Display",
"statistical",
"information",
"about",
"the",
"distribution",
"of",
"the",
"assets"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L524-L541 | train | 233,288 |
gem/oq-engine | openquake/calculators/views.py | view_required_params_per_trt | def view_required_params_per_trt(token, dstore):
"""
Display the parameters needed by each tectonic region type
"""
csm_info = dstore['csm_info']
tbl = []
for grp_id, trt in sorted(csm_info.grp_by("trt").items()):
gsims = csm_info.gsim_lt.get_gsims(trt)
maker = ContextMaker(trt, gsims)
distances = sorted(maker.REQUIRES_DISTANCES)
siteparams = sorted(maker.REQUIRES_SITES_PARAMETERS)
ruptparams = sorted(maker.REQUIRES_RUPTURE_PARAMETERS)
tbl.append((grp_id, ' '.join(map(repr, map(repr, gsims))),
distances, siteparams, ruptparams))
return rst_table(
tbl, header='grp_id gsims distances siteparams ruptparams'.split(),
fmt=scientificformat) | python | def view_required_params_per_trt(token, dstore):
"""
Display the parameters needed by each tectonic region type
"""
csm_info = dstore['csm_info']
tbl = []
for grp_id, trt in sorted(csm_info.grp_by("trt").items()):
gsims = csm_info.gsim_lt.get_gsims(trt)
maker = ContextMaker(trt, gsims)
distances = sorted(maker.REQUIRES_DISTANCES)
siteparams = sorted(maker.REQUIRES_SITES_PARAMETERS)
ruptparams = sorted(maker.REQUIRES_RUPTURE_PARAMETERS)
tbl.append((grp_id, ' '.join(map(repr, map(repr, gsims))),
distances, siteparams, ruptparams))
return rst_table(
tbl, header='grp_id gsims distances siteparams ruptparams'.split(),
fmt=scientificformat) | [
"def",
"view_required_params_per_trt",
"(",
"token",
",",
"dstore",
")",
":",
"csm_info",
"=",
"dstore",
"[",
"'csm_info'",
"]",
"tbl",
"=",
"[",
"]",
"for",
"grp_id",
",",
"trt",
"in",
"sorted",
"(",
"csm_info",
".",
"grp_by",
"(",
"\"trt\"",
")",
".",
"items",
"(",
")",
")",
":",
"gsims",
"=",
"csm_info",
".",
"gsim_lt",
".",
"get_gsims",
"(",
"trt",
")",
"maker",
"=",
"ContextMaker",
"(",
"trt",
",",
"gsims",
")",
"distances",
"=",
"sorted",
"(",
"maker",
".",
"REQUIRES_DISTANCES",
")",
"siteparams",
"=",
"sorted",
"(",
"maker",
".",
"REQUIRES_SITES_PARAMETERS",
")",
"ruptparams",
"=",
"sorted",
"(",
"maker",
".",
"REQUIRES_RUPTURE_PARAMETERS",
")",
"tbl",
".",
"append",
"(",
"(",
"grp_id",
",",
"' '",
".",
"join",
"(",
"map",
"(",
"repr",
",",
"map",
"(",
"repr",
",",
"gsims",
")",
")",
")",
",",
"distances",
",",
"siteparams",
",",
"ruptparams",
")",
")",
"return",
"rst_table",
"(",
"tbl",
",",
"header",
"=",
"'grp_id gsims distances siteparams ruptparams'",
".",
"split",
"(",
")",
",",
"fmt",
"=",
"scientificformat",
")"
] | Display the parameters needed by each tectonic region type | [
"Display",
"the",
"parameters",
"needed",
"by",
"each",
"tectonic",
"region",
"type"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L545-L561 | train | 233,289 |
gem/oq-engine | openquake/calculators/views.py | view_global_hcurves | def view_global_hcurves(token, dstore):
"""
Display the global hazard curves for the calculation. They are
used for debugging purposes when comparing the results of two
calculations. They are the mean over the sites of the mean hazard
curves.
"""
oq = dstore['oqparam']
nsites = len(dstore['sitecol'])
rlzs_assoc = dstore['csm_info'].get_rlzs_assoc()
mean = getters.PmapGetter(dstore, rlzs_assoc).get_mean()
array = calc.convert_to_array(mean, nsites, oq.imtls)
res = numpy.zeros(1, array.dtype)
for name in array.dtype.names:
res[name] = array[name].mean()
return rst_table(res) | python | def view_global_hcurves(token, dstore):
"""
Display the global hazard curves for the calculation. They are
used for debugging purposes when comparing the results of two
calculations. They are the mean over the sites of the mean hazard
curves.
"""
oq = dstore['oqparam']
nsites = len(dstore['sitecol'])
rlzs_assoc = dstore['csm_info'].get_rlzs_assoc()
mean = getters.PmapGetter(dstore, rlzs_assoc).get_mean()
array = calc.convert_to_array(mean, nsites, oq.imtls)
res = numpy.zeros(1, array.dtype)
for name in array.dtype.names:
res[name] = array[name].mean()
return rst_table(res) | [
"def",
"view_global_hcurves",
"(",
"token",
",",
"dstore",
")",
":",
"oq",
"=",
"dstore",
"[",
"'oqparam'",
"]",
"nsites",
"=",
"len",
"(",
"dstore",
"[",
"'sitecol'",
"]",
")",
"rlzs_assoc",
"=",
"dstore",
"[",
"'csm_info'",
"]",
".",
"get_rlzs_assoc",
"(",
")",
"mean",
"=",
"getters",
".",
"PmapGetter",
"(",
"dstore",
",",
"rlzs_assoc",
")",
".",
"get_mean",
"(",
")",
"array",
"=",
"calc",
".",
"convert_to_array",
"(",
"mean",
",",
"nsites",
",",
"oq",
".",
"imtls",
")",
"res",
"=",
"numpy",
".",
"zeros",
"(",
"1",
",",
"array",
".",
"dtype",
")",
"for",
"name",
"in",
"array",
".",
"dtype",
".",
"names",
":",
"res",
"[",
"name",
"]",
"=",
"array",
"[",
"name",
"]",
".",
"mean",
"(",
")",
"return",
"rst_table",
"(",
"res",
")"
] | Display the global hazard curves for the calculation. They are
used for debugging purposes when comparing the results of two
calculations. They are the mean over the sites of the mean hazard
curves. | [
"Display",
"the",
"global",
"hazard",
"curves",
"for",
"the",
"calculation",
".",
"They",
"are",
"used",
"for",
"debugging",
"purposes",
"when",
"comparing",
"the",
"results",
"of",
"two",
"calculations",
".",
"They",
"are",
"the",
"mean",
"over",
"the",
"sites",
"of",
"the",
"mean",
"hazard",
"curves",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L671-L686 | train | 233,290 |
gem/oq-engine | openquake/calculators/views.py | view_dupl_sources_time | def view_dupl_sources_time(token, dstore):
"""
Display the time spent computing duplicated sources
"""
info = dstore['source_info']
items = sorted(group_array(info.value, 'source_id').items())
tbl = []
tot_time = 0
for source_id, records in items:
if len(records) > 1: # dupl
calc_time = records['calc_time'].sum()
tot_time += calc_time + records['split_time'].sum()
tbl.append((source_id, calc_time, len(records)))
if tbl and info.attrs.get('has_dupl_sources'):
tot = info['calc_time'].sum() + info['split_time'].sum()
percent = tot_time / tot * 100
m = '\nTotal time in duplicated sources: %d/%d (%d%%)' % (
tot_time, tot, percent)
return rst_table(tbl, ['source_id', 'calc_time', 'num_dupl']) + m
else:
return 'There are no duplicated sources' | python | def view_dupl_sources_time(token, dstore):
"""
Display the time spent computing duplicated sources
"""
info = dstore['source_info']
items = sorted(group_array(info.value, 'source_id').items())
tbl = []
tot_time = 0
for source_id, records in items:
if len(records) > 1: # dupl
calc_time = records['calc_time'].sum()
tot_time += calc_time + records['split_time'].sum()
tbl.append((source_id, calc_time, len(records)))
if tbl and info.attrs.get('has_dupl_sources'):
tot = info['calc_time'].sum() + info['split_time'].sum()
percent = tot_time / tot * 100
m = '\nTotal time in duplicated sources: %d/%d (%d%%)' % (
tot_time, tot, percent)
return rst_table(tbl, ['source_id', 'calc_time', 'num_dupl']) + m
else:
return 'There are no duplicated sources' | [
"def",
"view_dupl_sources_time",
"(",
"token",
",",
"dstore",
")",
":",
"info",
"=",
"dstore",
"[",
"'source_info'",
"]",
"items",
"=",
"sorted",
"(",
"group_array",
"(",
"info",
".",
"value",
",",
"'source_id'",
")",
".",
"items",
"(",
")",
")",
"tbl",
"=",
"[",
"]",
"tot_time",
"=",
"0",
"for",
"source_id",
",",
"records",
"in",
"items",
":",
"if",
"len",
"(",
"records",
")",
">",
"1",
":",
"# dupl",
"calc_time",
"=",
"records",
"[",
"'calc_time'",
"]",
".",
"sum",
"(",
")",
"tot_time",
"+=",
"calc_time",
"+",
"records",
"[",
"'split_time'",
"]",
".",
"sum",
"(",
")",
"tbl",
".",
"append",
"(",
"(",
"source_id",
",",
"calc_time",
",",
"len",
"(",
"records",
")",
")",
")",
"if",
"tbl",
"and",
"info",
".",
"attrs",
".",
"get",
"(",
"'has_dupl_sources'",
")",
":",
"tot",
"=",
"info",
"[",
"'calc_time'",
"]",
".",
"sum",
"(",
")",
"+",
"info",
"[",
"'split_time'",
"]",
".",
"sum",
"(",
")",
"percent",
"=",
"tot_time",
"/",
"tot",
"*",
"100",
"m",
"=",
"'\\nTotal time in duplicated sources: %d/%d (%d%%)'",
"%",
"(",
"tot_time",
",",
"tot",
",",
"percent",
")",
"return",
"rst_table",
"(",
"tbl",
",",
"[",
"'source_id'",
",",
"'calc_time'",
",",
"'num_dupl'",
"]",
")",
"+",
"m",
"else",
":",
"return",
"'There are no duplicated sources'"
] | Display the time spent computing duplicated sources | [
"Display",
"the",
"time",
"spent",
"computing",
"duplicated",
"sources"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L690-L710 | train | 233,291 |
gem/oq-engine | openquake/calculators/views.py | view_global_poes | def view_global_poes(token, dstore):
"""
Display global probabilities averaged on all sites and all GMPEs
"""
tbl = []
imtls = dstore['oqparam'].imtls
header = ['grp_id'] + [str(poe) for poe in imtls.array]
for grp in sorted(dstore['poes']):
poes = dstore['poes/' + grp]
nsites = len(poes)
site_avg = sum(poes[sid].array for sid in poes) / nsites
gsim_avg = site_avg.sum(axis=1) / poes.shape_z
tbl.append([grp] + list(gsim_avg))
return rst_table(tbl, header=header) | python | def view_global_poes(token, dstore):
"""
Display global probabilities averaged on all sites and all GMPEs
"""
tbl = []
imtls = dstore['oqparam'].imtls
header = ['grp_id'] + [str(poe) for poe in imtls.array]
for grp in sorted(dstore['poes']):
poes = dstore['poes/' + grp]
nsites = len(poes)
site_avg = sum(poes[sid].array for sid in poes) / nsites
gsim_avg = site_avg.sum(axis=1) / poes.shape_z
tbl.append([grp] + list(gsim_avg))
return rst_table(tbl, header=header) | [
"def",
"view_global_poes",
"(",
"token",
",",
"dstore",
")",
":",
"tbl",
"=",
"[",
"]",
"imtls",
"=",
"dstore",
"[",
"'oqparam'",
"]",
".",
"imtls",
"header",
"=",
"[",
"'grp_id'",
"]",
"+",
"[",
"str",
"(",
"poe",
")",
"for",
"poe",
"in",
"imtls",
".",
"array",
"]",
"for",
"grp",
"in",
"sorted",
"(",
"dstore",
"[",
"'poes'",
"]",
")",
":",
"poes",
"=",
"dstore",
"[",
"'poes/'",
"+",
"grp",
"]",
"nsites",
"=",
"len",
"(",
"poes",
")",
"site_avg",
"=",
"sum",
"(",
"poes",
"[",
"sid",
"]",
".",
"array",
"for",
"sid",
"in",
"poes",
")",
"/",
"nsites",
"gsim_avg",
"=",
"site_avg",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
"/",
"poes",
".",
"shape_z",
"tbl",
".",
"append",
"(",
"[",
"grp",
"]",
"+",
"list",
"(",
"gsim_avg",
")",
")",
"return",
"rst_table",
"(",
"tbl",
",",
"header",
"=",
"header",
")"
] | Display global probabilities averaged on all sites and all GMPEs | [
"Display",
"global",
"probabilities",
"averaged",
"on",
"all",
"sites",
"and",
"all",
"GMPEs"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L714-L727 | train | 233,292 |
gem/oq-engine | openquake/calculators/views.py | view_global_hmaps | def view_global_hmaps(token, dstore):
"""
Display the global hazard maps for the calculation. They are
used for debugging purposes when comparing the results of two
calculations. They are the mean over the sites of the mean hazard
maps.
"""
oq = dstore['oqparam']
dt = numpy.dtype([('%s-%s' % (imt, poe), F32)
for imt in oq.imtls for poe in oq.poes])
array = dstore['hmaps/mean'].value.view(dt)[:, 0]
res = numpy.zeros(1, array.dtype)
for name in array.dtype.names:
res[name] = array[name].mean()
return rst_table(res) | python | def view_global_hmaps(token, dstore):
"""
Display the global hazard maps for the calculation. They are
used for debugging purposes when comparing the results of two
calculations. They are the mean over the sites of the mean hazard
maps.
"""
oq = dstore['oqparam']
dt = numpy.dtype([('%s-%s' % (imt, poe), F32)
for imt in oq.imtls for poe in oq.poes])
array = dstore['hmaps/mean'].value.view(dt)[:, 0]
res = numpy.zeros(1, array.dtype)
for name in array.dtype.names:
res[name] = array[name].mean()
return rst_table(res) | [
"def",
"view_global_hmaps",
"(",
"token",
",",
"dstore",
")",
":",
"oq",
"=",
"dstore",
"[",
"'oqparam'",
"]",
"dt",
"=",
"numpy",
".",
"dtype",
"(",
"[",
"(",
"'%s-%s'",
"%",
"(",
"imt",
",",
"poe",
")",
",",
"F32",
")",
"for",
"imt",
"in",
"oq",
".",
"imtls",
"for",
"poe",
"in",
"oq",
".",
"poes",
"]",
")",
"array",
"=",
"dstore",
"[",
"'hmaps/mean'",
"]",
".",
"value",
".",
"view",
"(",
"dt",
")",
"[",
":",
",",
"0",
"]",
"res",
"=",
"numpy",
".",
"zeros",
"(",
"1",
",",
"array",
".",
"dtype",
")",
"for",
"name",
"in",
"array",
".",
"dtype",
".",
"names",
":",
"res",
"[",
"name",
"]",
"=",
"array",
"[",
"name",
"]",
".",
"mean",
"(",
")",
"return",
"rst_table",
"(",
"res",
")"
] | Display the global hazard maps for the calculation. They are
used for debugging purposes when comparing the results of two
calculations. They are the mean over the sites of the mean hazard
maps. | [
"Display",
"the",
"global",
"hazard",
"maps",
"for",
"the",
"calculation",
".",
"They",
"are",
"used",
"for",
"debugging",
"purposes",
"when",
"comparing",
"the",
"results",
"of",
"two",
"calculations",
".",
"They",
"are",
"the",
"mean",
"over",
"the",
"sites",
"of",
"the",
"mean",
"hazard",
"maps",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L731-L745 | train | 233,293 |
gem/oq-engine | openquake/calculators/views.py | view_global_gmfs | def view_global_gmfs(token, dstore):
"""
Display GMFs averaged on everything for debugging purposes
"""
imtls = dstore['oqparam'].imtls
row = dstore['gmf_data/data']['gmv'].mean(axis=0)
return rst_table([row], header=imtls) | python | def view_global_gmfs(token, dstore):
"""
Display GMFs averaged on everything for debugging purposes
"""
imtls = dstore['oqparam'].imtls
row = dstore['gmf_data/data']['gmv'].mean(axis=0)
return rst_table([row], header=imtls) | [
"def",
"view_global_gmfs",
"(",
"token",
",",
"dstore",
")",
":",
"imtls",
"=",
"dstore",
"[",
"'oqparam'",
"]",
".",
"imtls",
"row",
"=",
"dstore",
"[",
"'gmf_data/data'",
"]",
"[",
"'gmv'",
"]",
".",
"mean",
"(",
"axis",
"=",
"0",
")",
"return",
"rst_table",
"(",
"[",
"row",
"]",
",",
"header",
"=",
"imtls",
")"
] | Display GMFs averaged on everything for debugging purposes | [
"Display",
"GMFs",
"averaged",
"on",
"everything",
"for",
"debugging",
"purposes"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L749-L755 | train | 233,294 |
gem/oq-engine | openquake/calculators/views.py | view_mean_disagg | def view_mean_disagg(token, dstore):
"""
Display mean quantities for the disaggregation. Useful for checking
differences between two calculations.
"""
tbl = []
for key, dset in sorted(dstore['disagg'].items()):
vals = [ds.value.mean() for k, ds in sorted(dset.items())]
tbl.append([key] + vals)
header = ['key'] + sorted(dset)
return rst_table(sorted(tbl), header=header) | python | def view_mean_disagg(token, dstore):
"""
Display mean quantities for the disaggregation. Useful for checking
differences between two calculations.
"""
tbl = []
for key, dset in sorted(dstore['disagg'].items()):
vals = [ds.value.mean() for k, ds in sorted(dset.items())]
tbl.append([key] + vals)
header = ['key'] + sorted(dset)
return rst_table(sorted(tbl), header=header) | [
"def",
"view_mean_disagg",
"(",
"token",
",",
"dstore",
")",
":",
"tbl",
"=",
"[",
"]",
"for",
"key",
",",
"dset",
"in",
"sorted",
"(",
"dstore",
"[",
"'disagg'",
"]",
".",
"items",
"(",
")",
")",
":",
"vals",
"=",
"[",
"ds",
".",
"value",
".",
"mean",
"(",
")",
"for",
"k",
",",
"ds",
"in",
"sorted",
"(",
"dset",
".",
"items",
"(",
")",
")",
"]",
"tbl",
".",
"append",
"(",
"[",
"key",
"]",
"+",
"vals",
")",
"header",
"=",
"[",
"'key'",
"]",
"+",
"sorted",
"(",
"dset",
")",
"return",
"rst_table",
"(",
"sorted",
"(",
"tbl",
")",
",",
"header",
"=",
"header",
")"
] | Display mean quantities for the disaggregation. Useful for checking
differences between two calculations. | [
"Display",
"mean",
"quantities",
"for",
"the",
"disaggregation",
".",
"Useful",
"for",
"checking",
"differences",
"between",
"two",
"calculations",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L759-L769 | train | 233,295 |
gem/oq-engine | openquake/calculators/views.py | view_elt | def view_elt(token, dstore):
"""
Display the event loss table averaged by event
"""
oq = dstore['oqparam']
R = len(dstore['csm_info'].rlzs)
dic = group_array(dstore['losses_by_event'].value, 'rlzi')
header = oq.loss_dt().names
tbl = []
for rlzi in range(R):
if rlzi in dic:
tbl.append(dic[rlzi]['loss'].mean(axis=0))
else:
tbl.append([0.] * len(header))
return rst_table(tbl, header) | python | def view_elt(token, dstore):
"""
Display the event loss table averaged by event
"""
oq = dstore['oqparam']
R = len(dstore['csm_info'].rlzs)
dic = group_array(dstore['losses_by_event'].value, 'rlzi')
header = oq.loss_dt().names
tbl = []
for rlzi in range(R):
if rlzi in dic:
tbl.append(dic[rlzi]['loss'].mean(axis=0))
else:
tbl.append([0.] * len(header))
return rst_table(tbl, header) | [
"def",
"view_elt",
"(",
"token",
",",
"dstore",
")",
":",
"oq",
"=",
"dstore",
"[",
"'oqparam'",
"]",
"R",
"=",
"len",
"(",
"dstore",
"[",
"'csm_info'",
"]",
".",
"rlzs",
")",
"dic",
"=",
"group_array",
"(",
"dstore",
"[",
"'losses_by_event'",
"]",
".",
"value",
",",
"'rlzi'",
")",
"header",
"=",
"oq",
".",
"loss_dt",
"(",
")",
".",
"names",
"tbl",
"=",
"[",
"]",
"for",
"rlzi",
"in",
"range",
"(",
"R",
")",
":",
"if",
"rlzi",
"in",
"dic",
":",
"tbl",
".",
"append",
"(",
"dic",
"[",
"rlzi",
"]",
"[",
"'loss'",
"]",
".",
"mean",
"(",
"axis",
"=",
"0",
")",
")",
"else",
":",
"tbl",
".",
"append",
"(",
"[",
"0.",
"]",
"*",
"len",
"(",
"header",
")",
")",
"return",
"rst_table",
"(",
"tbl",
",",
"header",
")"
] | Display the event loss table averaged by event | [
"Display",
"the",
"event",
"loss",
"table",
"averaged",
"by",
"event"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L773-L787 | train | 233,296 |
gem/oq-engine | openquake/calculators/views.py | view_pmap | def view_pmap(token, dstore):
"""
Display the mean ProbabilityMap associated to a given source group name
"""
grp = token.split(':')[1] # called as pmap:grp
pmap = {}
rlzs_assoc = dstore['csm_info'].get_rlzs_assoc()
pgetter = getters.PmapGetter(dstore, rlzs_assoc)
pmap = pgetter.get_mean(grp)
return str(pmap) | python | def view_pmap(token, dstore):
"""
Display the mean ProbabilityMap associated to a given source group name
"""
grp = token.split(':')[1] # called as pmap:grp
pmap = {}
rlzs_assoc = dstore['csm_info'].get_rlzs_assoc()
pgetter = getters.PmapGetter(dstore, rlzs_assoc)
pmap = pgetter.get_mean(grp)
return str(pmap) | [
"def",
"view_pmap",
"(",
"token",
",",
"dstore",
")",
":",
"grp",
"=",
"token",
".",
"split",
"(",
"':'",
")",
"[",
"1",
"]",
"# called as pmap:grp",
"pmap",
"=",
"{",
"}",
"rlzs_assoc",
"=",
"dstore",
"[",
"'csm_info'",
"]",
".",
"get_rlzs_assoc",
"(",
")",
"pgetter",
"=",
"getters",
".",
"PmapGetter",
"(",
"dstore",
",",
"rlzs_assoc",
")",
"pmap",
"=",
"pgetter",
".",
"get_mean",
"(",
"grp",
")",
"return",
"str",
"(",
"pmap",
")"
] | Display the mean ProbabilityMap associated to a given source group name | [
"Display",
"the",
"mean",
"ProbabilityMap",
"associated",
"to",
"a",
"given",
"source",
"group",
"name"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L791-L800 | train | 233,297 |
gem/oq-engine | openquake/calculators/views.py | view_act_ruptures_by_src | def view_act_ruptures_by_src(token, dstore):
"""
Display the actual number of ruptures by source in event based calculations
"""
data = dstore['ruptures'].value[['srcidx', 'serial']]
counts = sorted(countby(data, 'srcidx').items(),
key=operator.itemgetter(1), reverse=True)
src_info = dstore['source_info'].value[['grp_id', 'source_id']]
table = [['src_id', 'grp_id', 'act_ruptures']]
for srcidx, act_ruptures in counts:
src = src_info[srcidx]
table.append([src['source_id'], src['grp_id'], act_ruptures])
return rst_table(table) | python | def view_act_ruptures_by_src(token, dstore):
"""
Display the actual number of ruptures by source in event based calculations
"""
data = dstore['ruptures'].value[['srcidx', 'serial']]
counts = sorted(countby(data, 'srcidx').items(),
key=operator.itemgetter(1), reverse=True)
src_info = dstore['source_info'].value[['grp_id', 'source_id']]
table = [['src_id', 'grp_id', 'act_ruptures']]
for srcidx, act_ruptures in counts:
src = src_info[srcidx]
table.append([src['source_id'], src['grp_id'], act_ruptures])
return rst_table(table) | [
"def",
"view_act_ruptures_by_src",
"(",
"token",
",",
"dstore",
")",
":",
"data",
"=",
"dstore",
"[",
"'ruptures'",
"]",
".",
"value",
"[",
"[",
"'srcidx'",
",",
"'serial'",
"]",
"]",
"counts",
"=",
"sorted",
"(",
"countby",
"(",
"data",
",",
"'srcidx'",
")",
".",
"items",
"(",
")",
",",
"key",
"=",
"operator",
".",
"itemgetter",
"(",
"1",
")",
",",
"reverse",
"=",
"True",
")",
"src_info",
"=",
"dstore",
"[",
"'source_info'",
"]",
".",
"value",
"[",
"[",
"'grp_id'",
",",
"'source_id'",
"]",
"]",
"table",
"=",
"[",
"[",
"'src_id'",
",",
"'grp_id'",
",",
"'act_ruptures'",
"]",
"]",
"for",
"srcidx",
",",
"act_ruptures",
"in",
"counts",
":",
"src",
"=",
"src_info",
"[",
"srcidx",
"]",
"table",
".",
"append",
"(",
"[",
"src",
"[",
"'source_id'",
"]",
",",
"src",
"[",
"'grp_id'",
"]",
",",
"act_ruptures",
"]",
")",
"return",
"rst_table",
"(",
"table",
")"
] | Display the actual number of ruptures by source in event based calculations | [
"Display",
"the",
"actual",
"number",
"of",
"ruptures",
"by",
"source",
"in",
"event",
"based",
"calculations"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L804-L816 | train | 233,298 |
gem/oq-engine | openquake/calculators/views.py | view_dupl_sources | def view_dupl_sources(token, dstore):
"""
Show the sources with the same ID and the truly duplicated sources
"""
fields = ['source_id', 'code', 'gidx1', 'gidx2', 'num_ruptures']
dic = group_array(dstore['source_info'].value[fields], 'source_id')
sameid = []
dupl = []
for source_id, group in dic.items():
if len(group) > 1: # same ID sources
sources = []
for rec in group:
geom = dstore['source_geom'][rec['gidx1']:rec['gidx2']]
src = Source(source_id, rec['code'], geom, rec['num_ruptures'])
sources.append(src)
if all_equal(sources):
dupl.append(source_id)
sameid.append(source_id)
if not dupl:
return ''
msg = str(dupl) + '\n'
msg += ('Found %d source(s) with the same ID and %d true duplicate(s)'
% (len(sameid), len(dupl)))
fakedupl = set(sameid) - set(dupl)
if fakedupl:
msg += '\nHere is a fake duplicate: %s' % fakedupl.pop()
return msg | python | def view_dupl_sources(token, dstore):
"""
Show the sources with the same ID and the truly duplicated sources
"""
fields = ['source_id', 'code', 'gidx1', 'gidx2', 'num_ruptures']
dic = group_array(dstore['source_info'].value[fields], 'source_id')
sameid = []
dupl = []
for source_id, group in dic.items():
if len(group) > 1: # same ID sources
sources = []
for rec in group:
geom = dstore['source_geom'][rec['gidx1']:rec['gidx2']]
src = Source(source_id, rec['code'], geom, rec['num_ruptures'])
sources.append(src)
if all_equal(sources):
dupl.append(source_id)
sameid.append(source_id)
if not dupl:
return ''
msg = str(dupl) + '\n'
msg += ('Found %d source(s) with the same ID and %d true duplicate(s)'
% (len(sameid), len(dupl)))
fakedupl = set(sameid) - set(dupl)
if fakedupl:
msg += '\nHere is a fake duplicate: %s' % fakedupl.pop()
return msg | [
"def",
"view_dupl_sources",
"(",
"token",
",",
"dstore",
")",
":",
"fields",
"=",
"[",
"'source_id'",
",",
"'code'",
",",
"'gidx1'",
",",
"'gidx2'",
",",
"'num_ruptures'",
"]",
"dic",
"=",
"group_array",
"(",
"dstore",
"[",
"'source_info'",
"]",
".",
"value",
"[",
"fields",
"]",
",",
"'source_id'",
")",
"sameid",
"=",
"[",
"]",
"dupl",
"=",
"[",
"]",
"for",
"source_id",
",",
"group",
"in",
"dic",
".",
"items",
"(",
")",
":",
"if",
"len",
"(",
"group",
")",
">",
"1",
":",
"# same ID sources",
"sources",
"=",
"[",
"]",
"for",
"rec",
"in",
"group",
":",
"geom",
"=",
"dstore",
"[",
"'source_geom'",
"]",
"[",
"rec",
"[",
"'gidx1'",
"]",
":",
"rec",
"[",
"'gidx2'",
"]",
"]",
"src",
"=",
"Source",
"(",
"source_id",
",",
"rec",
"[",
"'code'",
"]",
",",
"geom",
",",
"rec",
"[",
"'num_ruptures'",
"]",
")",
"sources",
".",
"append",
"(",
"src",
")",
"if",
"all_equal",
"(",
"sources",
")",
":",
"dupl",
".",
"append",
"(",
"source_id",
")",
"sameid",
".",
"append",
"(",
"source_id",
")",
"if",
"not",
"dupl",
":",
"return",
"''",
"msg",
"=",
"str",
"(",
"dupl",
")",
"+",
"'\\n'",
"msg",
"+=",
"(",
"'Found %d source(s) with the same ID and %d true duplicate(s)'",
"%",
"(",
"len",
"(",
"sameid",
")",
",",
"len",
"(",
"dupl",
")",
")",
")",
"fakedupl",
"=",
"set",
"(",
"sameid",
")",
"-",
"set",
"(",
"dupl",
")",
"if",
"fakedupl",
":",
"msg",
"+=",
"'\\nHere is a fake duplicate: %s'",
"%",
"fakedupl",
".",
"pop",
"(",
")",
"return",
"msg"
] | Show the sources with the same ID and the truly duplicated sources | [
"Show",
"the",
"sources",
"with",
"the",
"same",
"ID",
"and",
"the",
"truly",
"duplicated",
"sources"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L838-L864 | train | 233,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.