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/commands/webui.py | webui | def webui(cmd, hostport='127.0.0.1:8800', skip_browser=False):
"""
start the webui server in foreground or perform other operation on the
django application
"""
dbpath = os.path.realpath(os.path.expanduser(config.dbserver.file))
if os.path.isfile(dbpath) and not os.access(dbpath, os.W_OK):
sys.exit('This command must be run by the proper user: '
'see the documentation for details')
if cmd == 'start':
dbserver.ensure_on() # start the dbserver in a subprocess
rundjango('runserver', hostport, skip_browser)
elif cmd in commands:
rundjango(cmd) | python | def webui(cmd, hostport='127.0.0.1:8800', skip_browser=False):
"""
start the webui server in foreground or perform other operation on the
django application
"""
dbpath = os.path.realpath(os.path.expanduser(config.dbserver.file))
if os.path.isfile(dbpath) and not os.access(dbpath, os.W_OK):
sys.exit('This command must be run by the proper user: '
'see the documentation for details')
if cmd == 'start':
dbserver.ensure_on() # start the dbserver in a subprocess
rundjango('runserver', hostport, skip_browser)
elif cmd in commands:
rundjango(cmd) | [
"def",
"webui",
"(",
"cmd",
",",
"hostport",
"=",
"'127.0.0.1:8800'",
",",
"skip_browser",
"=",
"False",
")",
":",
"dbpath",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"config",
".",
"dbserver",
".",
"file",
")",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"dbpath",
")",
"and",
"not",
"os",
".",
"access",
"(",
"dbpath",
",",
"os",
".",
"W_OK",
")",
":",
"sys",
".",
"exit",
"(",
"'This command must be run by the proper user: '",
"'see the documentation for details'",
")",
"if",
"cmd",
"==",
"'start'",
":",
"dbserver",
".",
"ensure_on",
"(",
")",
"# start the dbserver in a subprocess",
"rundjango",
"(",
"'runserver'",
",",
"hostport",
",",
"skip_browser",
")",
"elif",
"cmd",
"in",
"commands",
":",
"rundjango",
"(",
"cmd",
")"
] | start the webui server in foreground or perform other operation on the
django application | [
"start",
"the",
"webui",
"server",
"in",
"foreground",
"or",
"perform",
"other",
"operation",
"on",
"the",
"django",
"application"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/webui.py#L51-L64 | train | 233,400 |
gem/oq-engine | openquake/hazardlib/gsim/abrahamson_2014.py | AbrahamsonEtAl2014._get_basic_term | def _get_basic_term(self, C, rup, dists):
"""
Compute and return basic form, see page 1030.
"""
# Fictitious depth calculation
if rup.mag > 5.:
c4m = C['c4']
elif rup.mag > 4.:
c4m = C['c4'] - (C['c4']-1.) * (5. - rup.mag)
else:
c4m = 1.
R = np.sqrt(dists.rrup**2. + c4m**2.)
# basic form
base_term = C['a1'] * np.ones_like(dists.rrup) + C['a17'] * dists.rrup
# equation 2 at page 1030
if rup.mag >= C['m1']:
base_term += (C['a5'] * (rup.mag - C['m1']) +
C['a8'] * (8.5 - rup.mag)**2. +
(C['a2'] + C['a3'] * (rup.mag - C['m1'])) *
np.log(R))
elif rup.mag >= self.CONSTS['m2']:
base_term += (C['a4'] * (rup.mag - C['m1']) +
C['a8'] * (8.5 - rup.mag)**2. +
(C['a2'] + C['a3'] * (rup.mag - C['m1'])) *
np.log(R))
else:
base_term += (C['a4'] * (self.CONSTS['m2'] - C['m1']) +
C['a8'] * (8.5 - self.CONSTS['m2'])**2. +
C['a6'] * (rup.mag - self.CONSTS['m2']) +
C['a7'] * (rup.mag - self.CONSTS['m2'])**2. +
(C['a2'] + C['a3'] * (self.CONSTS['m2'] - C['m1'])) *
np.log(R))
return base_term | python | def _get_basic_term(self, C, rup, dists):
"""
Compute and return basic form, see page 1030.
"""
# Fictitious depth calculation
if rup.mag > 5.:
c4m = C['c4']
elif rup.mag > 4.:
c4m = C['c4'] - (C['c4']-1.) * (5. - rup.mag)
else:
c4m = 1.
R = np.sqrt(dists.rrup**2. + c4m**2.)
# basic form
base_term = C['a1'] * np.ones_like(dists.rrup) + C['a17'] * dists.rrup
# equation 2 at page 1030
if rup.mag >= C['m1']:
base_term += (C['a5'] * (rup.mag - C['m1']) +
C['a8'] * (8.5 - rup.mag)**2. +
(C['a2'] + C['a3'] * (rup.mag - C['m1'])) *
np.log(R))
elif rup.mag >= self.CONSTS['m2']:
base_term += (C['a4'] * (rup.mag - C['m1']) +
C['a8'] * (8.5 - rup.mag)**2. +
(C['a2'] + C['a3'] * (rup.mag - C['m1'])) *
np.log(R))
else:
base_term += (C['a4'] * (self.CONSTS['m2'] - C['m1']) +
C['a8'] * (8.5 - self.CONSTS['m2'])**2. +
C['a6'] * (rup.mag - self.CONSTS['m2']) +
C['a7'] * (rup.mag - self.CONSTS['m2'])**2. +
(C['a2'] + C['a3'] * (self.CONSTS['m2'] - C['m1'])) *
np.log(R))
return base_term | [
"def",
"_get_basic_term",
"(",
"self",
",",
"C",
",",
"rup",
",",
"dists",
")",
":",
"# Fictitious depth calculation",
"if",
"rup",
".",
"mag",
">",
"5.",
":",
"c4m",
"=",
"C",
"[",
"'c4'",
"]",
"elif",
"rup",
".",
"mag",
">",
"4.",
":",
"c4m",
"=",
"C",
"[",
"'c4'",
"]",
"-",
"(",
"C",
"[",
"'c4'",
"]",
"-",
"1.",
")",
"*",
"(",
"5.",
"-",
"rup",
".",
"mag",
")",
"else",
":",
"c4m",
"=",
"1.",
"R",
"=",
"np",
".",
"sqrt",
"(",
"dists",
".",
"rrup",
"**",
"2.",
"+",
"c4m",
"**",
"2.",
")",
"# basic form",
"base_term",
"=",
"C",
"[",
"'a1'",
"]",
"*",
"np",
".",
"ones_like",
"(",
"dists",
".",
"rrup",
")",
"+",
"C",
"[",
"'a17'",
"]",
"*",
"dists",
".",
"rrup",
"# equation 2 at page 1030",
"if",
"rup",
".",
"mag",
">=",
"C",
"[",
"'m1'",
"]",
":",
"base_term",
"+=",
"(",
"C",
"[",
"'a5'",
"]",
"*",
"(",
"rup",
".",
"mag",
"-",
"C",
"[",
"'m1'",
"]",
")",
"+",
"C",
"[",
"'a8'",
"]",
"*",
"(",
"8.5",
"-",
"rup",
".",
"mag",
")",
"**",
"2.",
"+",
"(",
"C",
"[",
"'a2'",
"]",
"+",
"C",
"[",
"'a3'",
"]",
"*",
"(",
"rup",
".",
"mag",
"-",
"C",
"[",
"'m1'",
"]",
")",
")",
"*",
"np",
".",
"log",
"(",
"R",
")",
")",
"elif",
"rup",
".",
"mag",
">=",
"self",
".",
"CONSTS",
"[",
"'m2'",
"]",
":",
"base_term",
"+=",
"(",
"C",
"[",
"'a4'",
"]",
"*",
"(",
"rup",
".",
"mag",
"-",
"C",
"[",
"'m1'",
"]",
")",
"+",
"C",
"[",
"'a8'",
"]",
"*",
"(",
"8.5",
"-",
"rup",
".",
"mag",
")",
"**",
"2.",
"+",
"(",
"C",
"[",
"'a2'",
"]",
"+",
"C",
"[",
"'a3'",
"]",
"*",
"(",
"rup",
".",
"mag",
"-",
"C",
"[",
"'m1'",
"]",
")",
")",
"*",
"np",
".",
"log",
"(",
"R",
")",
")",
"else",
":",
"base_term",
"+=",
"(",
"C",
"[",
"'a4'",
"]",
"*",
"(",
"self",
".",
"CONSTS",
"[",
"'m2'",
"]",
"-",
"C",
"[",
"'m1'",
"]",
")",
"+",
"C",
"[",
"'a8'",
"]",
"*",
"(",
"8.5",
"-",
"self",
".",
"CONSTS",
"[",
"'m2'",
"]",
")",
"**",
"2.",
"+",
"C",
"[",
"'a6'",
"]",
"*",
"(",
"rup",
".",
"mag",
"-",
"self",
".",
"CONSTS",
"[",
"'m2'",
"]",
")",
"+",
"C",
"[",
"'a7'",
"]",
"*",
"(",
"rup",
".",
"mag",
"-",
"self",
".",
"CONSTS",
"[",
"'m2'",
"]",
")",
"**",
"2.",
"+",
"(",
"C",
"[",
"'a2'",
"]",
"+",
"C",
"[",
"'a3'",
"]",
"*",
"(",
"self",
".",
"CONSTS",
"[",
"'m2'",
"]",
"-",
"C",
"[",
"'m1'",
"]",
")",
")",
"*",
"np",
".",
"log",
"(",
"R",
")",
")",
"return",
"base_term"
] | Compute and return basic form, see page 1030. | [
"Compute",
"and",
"return",
"basic",
"form",
"see",
"page",
"1030",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L130-L162 | train | 233,401 |
gem/oq-engine | openquake/hazardlib/gsim/abrahamson_2014.py | AbrahamsonEtAl2014._get_vs30star | def _get_vs30star(self, vs30, imt):
"""
This computes equations 8 and 9 at page 1034
"""
# compute the v1 value (see eq. 9, page 1034)
if imt.name == "SA":
t = imt.period
if t <= 0.50:
v1 = 1500.0
elif t < 3.0:
v1 = np.exp(-0.35 * np.log(t / 0.5) + np.log(1500.))
else:
v1 = 800.0
elif imt.name == "PGA":
v1 = 1500.0
else:
# This covers the PGV case
v1 = 1500.0
# set the vs30 star value (see eq. 8, page 1034)
vs30_star = np.ones_like(vs30) * vs30
vs30_star[vs30 >= v1] = v1
return vs30_star | python | def _get_vs30star(self, vs30, imt):
"""
This computes equations 8 and 9 at page 1034
"""
# compute the v1 value (see eq. 9, page 1034)
if imt.name == "SA":
t = imt.period
if t <= 0.50:
v1 = 1500.0
elif t < 3.0:
v1 = np.exp(-0.35 * np.log(t / 0.5) + np.log(1500.))
else:
v1 = 800.0
elif imt.name == "PGA":
v1 = 1500.0
else:
# This covers the PGV case
v1 = 1500.0
# set the vs30 star value (see eq. 8, page 1034)
vs30_star = np.ones_like(vs30) * vs30
vs30_star[vs30 >= v1] = v1
return vs30_star | [
"def",
"_get_vs30star",
"(",
"self",
",",
"vs30",
",",
"imt",
")",
":",
"# compute the v1 value (see eq. 9, page 1034)",
"if",
"imt",
".",
"name",
"==",
"\"SA\"",
":",
"t",
"=",
"imt",
".",
"period",
"if",
"t",
"<=",
"0.50",
":",
"v1",
"=",
"1500.0",
"elif",
"t",
"<",
"3.0",
":",
"v1",
"=",
"np",
".",
"exp",
"(",
"-",
"0.35",
"*",
"np",
".",
"log",
"(",
"t",
"/",
"0.5",
")",
"+",
"np",
".",
"log",
"(",
"1500.",
")",
")",
"else",
":",
"v1",
"=",
"800.0",
"elif",
"imt",
".",
"name",
"==",
"\"PGA\"",
":",
"v1",
"=",
"1500.0",
"else",
":",
"# This covers the PGV case",
"v1",
"=",
"1500.0",
"# set the vs30 star value (see eq. 8, page 1034)",
"vs30_star",
"=",
"np",
".",
"ones_like",
"(",
"vs30",
")",
"*",
"vs30",
"vs30_star",
"[",
"vs30",
">=",
"v1",
"]",
"=",
"v1",
"return",
"vs30_star"
] | This computes equations 8 and 9 at page 1034 | [
"This",
"computes",
"equations",
"8",
"and",
"9",
"at",
"page",
"1034"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L186-L207 | train | 233,402 |
gem/oq-engine | openquake/hazardlib/gsim/abrahamson_2014.py | AbrahamsonEtAl2014._get_site_response_term | def _get_site_response_term(self, C, imt, vs30, sa1180):
"""
Compute and return site response model term see page 1033
"""
# vs30 star
vs30_star = self._get_vs30star(vs30, imt)
# compute the site term
site_resp_term = np.zeros_like(vs30)
gt_vlin = vs30 >= C['vlin']
lw_vlin = vs30 < C['vlin']
# compute site response term for sites with vs30 greater than vlin
vs30_rat = vs30_star / C['vlin']
site_resp_term[gt_vlin] = ((C['a10'] + C['b'] * self.CONSTS['n']) *
np.log(vs30_rat[gt_vlin]))
# compute site response term for sites with vs30 lower than vlin
site_resp_term[lw_vlin] = (C['a10'] * np.log(vs30_rat[lw_vlin]) -
C['b'] * np.log(sa1180[lw_vlin] + C['c']) +
C['b'] * np.log(sa1180[lw_vlin] + C['c'] *
vs30_rat[lw_vlin] **
self.CONSTS['n']))
return site_resp_term | python | def _get_site_response_term(self, C, imt, vs30, sa1180):
"""
Compute and return site response model term see page 1033
"""
# vs30 star
vs30_star = self._get_vs30star(vs30, imt)
# compute the site term
site_resp_term = np.zeros_like(vs30)
gt_vlin = vs30 >= C['vlin']
lw_vlin = vs30 < C['vlin']
# compute site response term for sites with vs30 greater than vlin
vs30_rat = vs30_star / C['vlin']
site_resp_term[gt_vlin] = ((C['a10'] + C['b'] * self.CONSTS['n']) *
np.log(vs30_rat[gt_vlin]))
# compute site response term for sites with vs30 lower than vlin
site_resp_term[lw_vlin] = (C['a10'] * np.log(vs30_rat[lw_vlin]) -
C['b'] * np.log(sa1180[lw_vlin] + C['c']) +
C['b'] * np.log(sa1180[lw_vlin] + C['c'] *
vs30_rat[lw_vlin] **
self.CONSTS['n']))
return site_resp_term | [
"def",
"_get_site_response_term",
"(",
"self",
",",
"C",
",",
"imt",
",",
"vs30",
",",
"sa1180",
")",
":",
"# vs30 star",
"vs30_star",
"=",
"self",
".",
"_get_vs30star",
"(",
"vs30",
",",
"imt",
")",
"# compute the site term",
"site_resp_term",
"=",
"np",
".",
"zeros_like",
"(",
"vs30",
")",
"gt_vlin",
"=",
"vs30",
">=",
"C",
"[",
"'vlin'",
"]",
"lw_vlin",
"=",
"vs30",
"<",
"C",
"[",
"'vlin'",
"]",
"# compute site response term for sites with vs30 greater than vlin",
"vs30_rat",
"=",
"vs30_star",
"/",
"C",
"[",
"'vlin'",
"]",
"site_resp_term",
"[",
"gt_vlin",
"]",
"=",
"(",
"(",
"C",
"[",
"'a10'",
"]",
"+",
"C",
"[",
"'b'",
"]",
"*",
"self",
".",
"CONSTS",
"[",
"'n'",
"]",
")",
"*",
"np",
".",
"log",
"(",
"vs30_rat",
"[",
"gt_vlin",
"]",
")",
")",
"# compute site response term for sites with vs30 lower than vlin",
"site_resp_term",
"[",
"lw_vlin",
"]",
"=",
"(",
"C",
"[",
"'a10'",
"]",
"*",
"np",
".",
"log",
"(",
"vs30_rat",
"[",
"lw_vlin",
"]",
")",
"-",
"C",
"[",
"'b'",
"]",
"*",
"np",
".",
"log",
"(",
"sa1180",
"[",
"lw_vlin",
"]",
"+",
"C",
"[",
"'c'",
"]",
")",
"+",
"C",
"[",
"'b'",
"]",
"*",
"np",
".",
"log",
"(",
"sa1180",
"[",
"lw_vlin",
"]",
"+",
"C",
"[",
"'c'",
"]",
"*",
"vs30_rat",
"[",
"lw_vlin",
"]",
"**",
"self",
".",
"CONSTS",
"[",
"'n'",
"]",
")",
")",
"return",
"site_resp_term"
] | Compute and return site response model term see page 1033 | [
"Compute",
"and",
"return",
"site",
"response",
"model",
"term",
"see",
"page",
"1033"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L209-L229 | train | 233,403 |
gem/oq-engine | openquake/hazardlib/gsim/abrahamson_2014.py | AbrahamsonEtAl2014._get_hanging_wall_term | def _get_hanging_wall_term(self, C, dists, rup):
"""
Compute and return hanging wall model term, see page 1038.
"""
if rup.dip == 90.0:
return np.zeros_like(dists.rx)
else:
Fhw = np.zeros_like(dists.rx)
Fhw[dists.rx > 0] = 1.
# Compute taper t1
T1 = np.ones_like(dists.rx)
T1 *= 60./45. if rup.dip <= 30. else (90.-rup.dip)/45.0
# Compute taper t2 (eq 12 at page 1039) - a2hw set to 0.2 as
# indicated at page 1041
T2 = np.zeros_like(dists.rx)
a2hw = 0.2
if rup.mag > 6.5:
T2 += (1. + a2hw * (rup.mag - 6.5))
elif rup.mag > 5.5:
T2 += (1. + a2hw * (rup.mag - 6.5) - (1. - a2hw) *
(rup.mag - 6.5)**2)
else:
T2 *= 0.
# Compute taper t3 (eq. 13 at page 1039) - r1 and r2 specified at
# page 1040
T3 = np.zeros_like(dists.rx)
r1 = rup.width * np.cos(np.radians(rup.dip))
r2 = 3. * r1
#
idx = dists.rx < r1
T3[idx] = (np.ones_like(dists.rx)[idx] * self.CONSTS['h1'] +
self.CONSTS['h2'] * (dists.rx[idx] / r1) +
self.CONSTS['h3'] * (dists.rx[idx] / r1)**2)
#
idx = ((dists.rx >= r1) & (dists.rx <= r2))
T3[idx] = 1. - (dists.rx[idx] - r1) / (r2 - r1)
# Compute taper t4 (eq. 14 at page 1040)
T4 = np.zeros_like(dists.rx)
#
if rup.ztor <= 10.:
T4 += (1. - rup.ztor**2. / 100.)
# Compute T5 (eq 15a at page 1040) - ry1 computed according to
# suggestions provided at page 1040
T5 = np.zeros_like(dists.rx)
ry1 = dists.rx * np.tan(np.radians(20.))
#
idx = (dists.ry0 - ry1) <= 0.0
T5[idx] = 1.
#
idx = (((dists.ry0 - ry1) > 0.0) & ((dists.ry0 - ry1) < 5.0))
T5[idx] = 1. - (dists.ry0[idx] - ry1[idx]) / 5.0
# Finally, compute the hanging wall term
return Fhw*C['a13']*T1*T2*T3*T4*T5 | python | def _get_hanging_wall_term(self, C, dists, rup):
"""
Compute and return hanging wall model term, see page 1038.
"""
if rup.dip == 90.0:
return np.zeros_like(dists.rx)
else:
Fhw = np.zeros_like(dists.rx)
Fhw[dists.rx > 0] = 1.
# Compute taper t1
T1 = np.ones_like(dists.rx)
T1 *= 60./45. if rup.dip <= 30. else (90.-rup.dip)/45.0
# Compute taper t2 (eq 12 at page 1039) - a2hw set to 0.2 as
# indicated at page 1041
T2 = np.zeros_like(dists.rx)
a2hw = 0.2
if rup.mag > 6.5:
T2 += (1. + a2hw * (rup.mag - 6.5))
elif rup.mag > 5.5:
T2 += (1. + a2hw * (rup.mag - 6.5) - (1. - a2hw) *
(rup.mag - 6.5)**2)
else:
T2 *= 0.
# Compute taper t3 (eq. 13 at page 1039) - r1 and r2 specified at
# page 1040
T3 = np.zeros_like(dists.rx)
r1 = rup.width * np.cos(np.radians(rup.dip))
r2 = 3. * r1
#
idx = dists.rx < r1
T3[idx] = (np.ones_like(dists.rx)[idx] * self.CONSTS['h1'] +
self.CONSTS['h2'] * (dists.rx[idx] / r1) +
self.CONSTS['h3'] * (dists.rx[idx] / r1)**2)
#
idx = ((dists.rx >= r1) & (dists.rx <= r2))
T3[idx] = 1. - (dists.rx[idx] - r1) / (r2 - r1)
# Compute taper t4 (eq. 14 at page 1040)
T4 = np.zeros_like(dists.rx)
#
if rup.ztor <= 10.:
T4 += (1. - rup.ztor**2. / 100.)
# Compute T5 (eq 15a at page 1040) - ry1 computed according to
# suggestions provided at page 1040
T5 = np.zeros_like(dists.rx)
ry1 = dists.rx * np.tan(np.radians(20.))
#
idx = (dists.ry0 - ry1) <= 0.0
T5[idx] = 1.
#
idx = (((dists.ry0 - ry1) > 0.0) & ((dists.ry0 - ry1) < 5.0))
T5[idx] = 1. - (dists.ry0[idx] - ry1[idx]) / 5.0
# Finally, compute the hanging wall term
return Fhw*C['a13']*T1*T2*T3*T4*T5 | [
"def",
"_get_hanging_wall_term",
"(",
"self",
",",
"C",
",",
"dists",
",",
"rup",
")",
":",
"if",
"rup",
".",
"dip",
"==",
"90.0",
":",
"return",
"np",
".",
"zeros_like",
"(",
"dists",
".",
"rx",
")",
"else",
":",
"Fhw",
"=",
"np",
".",
"zeros_like",
"(",
"dists",
".",
"rx",
")",
"Fhw",
"[",
"dists",
".",
"rx",
">",
"0",
"]",
"=",
"1.",
"# Compute taper t1",
"T1",
"=",
"np",
".",
"ones_like",
"(",
"dists",
".",
"rx",
")",
"T1",
"*=",
"60.",
"/",
"45.",
"if",
"rup",
".",
"dip",
"<=",
"30.",
"else",
"(",
"90.",
"-",
"rup",
".",
"dip",
")",
"/",
"45.0",
"# Compute taper t2 (eq 12 at page 1039) - a2hw set to 0.2 as",
"# indicated at page 1041",
"T2",
"=",
"np",
".",
"zeros_like",
"(",
"dists",
".",
"rx",
")",
"a2hw",
"=",
"0.2",
"if",
"rup",
".",
"mag",
">",
"6.5",
":",
"T2",
"+=",
"(",
"1.",
"+",
"a2hw",
"*",
"(",
"rup",
".",
"mag",
"-",
"6.5",
")",
")",
"elif",
"rup",
".",
"mag",
">",
"5.5",
":",
"T2",
"+=",
"(",
"1.",
"+",
"a2hw",
"*",
"(",
"rup",
".",
"mag",
"-",
"6.5",
")",
"-",
"(",
"1.",
"-",
"a2hw",
")",
"*",
"(",
"rup",
".",
"mag",
"-",
"6.5",
")",
"**",
"2",
")",
"else",
":",
"T2",
"*=",
"0.",
"# Compute taper t3 (eq. 13 at page 1039) - r1 and r2 specified at",
"# page 1040",
"T3",
"=",
"np",
".",
"zeros_like",
"(",
"dists",
".",
"rx",
")",
"r1",
"=",
"rup",
".",
"width",
"*",
"np",
".",
"cos",
"(",
"np",
".",
"radians",
"(",
"rup",
".",
"dip",
")",
")",
"r2",
"=",
"3.",
"*",
"r1",
"#",
"idx",
"=",
"dists",
".",
"rx",
"<",
"r1",
"T3",
"[",
"idx",
"]",
"=",
"(",
"np",
".",
"ones_like",
"(",
"dists",
".",
"rx",
")",
"[",
"idx",
"]",
"*",
"self",
".",
"CONSTS",
"[",
"'h1'",
"]",
"+",
"self",
".",
"CONSTS",
"[",
"'h2'",
"]",
"*",
"(",
"dists",
".",
"rx",
"[",
"idx",
"]",
"/",
"r1",
")",
"+",
"self",
".",
"CONSTS",
"[",
"'h3'",
"]",
"*",
"(",
"dists",
".",
"rx",
"[",
"idx",
"]",
"/",
"r1",
")",
"**",
"2",
")",
"#",
"idx",
"=",
"(",
"(",
"dists",
".",
"rx",
">=",
"r1",
")",
"&",
"(",
"dists",
".",
"rx",
"<=",
"r2",
")",
")",
"T3",
"[",
"idx",
"]",
"=",
"1.",
"-",
"(",
"dists",
".",
"rx",
"[",
"idx",
"]",
"-",
"r1",
")",
"/",
"(",
"r2",
"-",
"r1",
")",
"# Compute taper t4 (eq. 14 at page 1040)",
"T4",
"=",
"np",
".",
"zeros_like",
"(",
"dists",
".",
"rx",
")",
"#",
"if",
"rup",
".",
"ztor",
"<=",
"10.",
":",
"T4",
"+=",
"(",
"1.",
"-",
"rup",
".",
"ztor",
"**",
"2.",
"/",
"100.",
")",
"# Compute T5 (eq 15a at page 1040) - ry1 computed according to",
"# suggestions provided at page 1040",
"T5",
"=",
"np",
".",
"zeros_like",
"(",
"dists",
".",
"rx",
")",
"ry1",
"=",
"dists",
".",
"rx",
"*",
"np",
".",
"tan",
"(",
"np",
".",
"radians",
"(",
"20.",
")",
")",
"#",
"idx",
"=",
"(",
"dists",
".",
"ry0",
"-",
"ry1",
")",
"<=",
"0.0",
"T5",
"[",
"idx",
"]",
"=",
"1.",
"#",
"idx",
"=",
"(",
"(",
"(",
"dists",
".",
"ry0",
"-",
"ry1",
")",
">",
"0.0",
")",
"&",
"(",
"(",
"dists",
".",
"ry0",
"-",
"ry1",
")",
"<",
"5.0",
")",
")",
"T5",
"[",
"idx",
"]",
"=",
"1.",
"-",
"(",
"dists",
".",
"ry0",
"[",
"idx",
"]",
"-",
"ry1",
"[",
"idx",
"]",
")",
"/",
"5.0",
"# Finally, compute the hanging wall term",
"return",
"Fhw",
"*",
"C",
"[",
"'a13'",
"]",
"*",
"T1",
"*",
"T2",
"*",
"T3",
"*",
"T4",
"*",
"T5"
] | Compute and return hanging wall model term, see page 1038. | [
"Compute",
"and",
"return",
"hanging",
"wall",
"model",
"term",
"see",
"page",
"1038",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L231-L283 | train | 233,404 |
gem/oq-engine | openquake/hazardlib/gsim/abrahamson_2014.py | AbrahamsonEtAl2014._get_top_of_rupture_depth_term | def _get_top_of_rupture_depth_term(self, C, imt, rup):
"""
Compute and return top of rupture depth term. See paragraph
'Depth-to-Top of Rupture Model', page 1042.
"""
if rup.ztor >= 20.0:
return C['a15']
else:
return C['a15'] * rup.ztor / 20.0 | python | def _get_top_of_rupture_depth_term(self, C, imt, rup):
"""
Compute and return top of rupture depth term. See paragraph
'Depth-to-Top of Rupture Model', page 1042.
"""
if rup.ztor >= 20.0:
return C['a15']
else:
return C['a15'] * rup.ztor / 20.0 | [
"def",
"_get_top_of_rupture_depth_term",
"(",
"self",
",",
"C",
",",
"imt",
",",
"rup",
")",
":",
"if",
"rup",
".",
"ztor",
">=",
"20.0",
":",
"return",
"C",
"[",
"'a15'",
"]",
"else",
":",
"return",
"C",
"[",
"'a15'",
"]",
"*",
"rup",
".",
"ztor",
"/",
"20.0"
] | Compute and return top of rupture depth term. See paragraph
'Depth-to-Top of Rupture Model', page 1042. | [
"Compute",
"and",
"return",
"top",
"of",
"rupture",
"depth",
"term",
".",
"See",
"paragraph",
"Depth",
"-",
"to",
"-",
"Top",
"of",
"Rupture",
"Model",
"page",
"1042",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L285-L293 | train | 233,405 |
gem/oq-engine | openquake/hazardlib/gsim/abrahamson_2014.py | AbrahamsonEtAl2014._get_soil_depth_term | def _get_soil_depth_term(self, C, z1pt0, vs30):
"""
Compute and return soil depth term. See page 1042.
"""
# Get reference z1pt0
z1ref = self._get_z1pt0ref(vs30)
# Get z1pt0
z10 = copy.deepcopy(z1pt0)
# This is used for the calculation of the motion on reference rock
idx = z1pt0 < 0
z10[idx] = z1ref[idx]
factor = np.log((z10 + 0.01) / (z1ref + 0.01))
# Here we use a linear interpolation as suggested in the 'Application
# guidelines' at page 1044
# Above 700 m/s the trend is flat, but we extend the Vs30 range to
# 6,000 m/s (basically the upper limit for mantle shear wave velocity
# on earth) to allow extrapolation without throwing an error.
f2 = interpolate.interp1d(
[0.0, 150, 250, 400, 700, 1000, 6000],
[C['a43'], C['a43'], C['a44'], C['a45'], C['a46'], C['a46'],
C['a46']],
kind='linear')
return f2(vs30) * factor | python | def _get_soil_depth_term(self, C, z1pt0, vs30):
"""
Compute and return soil depth term. See page 1042.
"""
# Get reference z1pt0
z1ref = self._get_z1pt0ref(vs30)
# Get z1pt0
z10 = copy.deepcopy(z1pt0)
# This is used for the calculation of the motion on reference rock
idx = z1pt0 < 0
z10[idx] = z1ref[idx]
factor = np.log((z10 + 0.01) / (z1ref + 0.01))
# Here we use a linear interpolation as suggested in the 'Application
# guidelines' at page 1044
# Above 700 m/s the trend is flat, but we extend the Vs30 range to
# 6,000 m/s (basically the upper limit for mantle shear wave velocity
# on earth) to allow extrapolation without throwing an error.
f2 = interpolate.interp1d(
[0.0, 150, 250, 400, 700, 1000, 6000],
[C['a43'], C['a43'], C['a44'], C['a45'], C['a46'], C['a46'],
C['a46']],
kind='linear')
return f2(vs30) * factor | [
"def",
"_get_soil_depth_term",
"(",
"self",
",",
"C",
",",
"z1pt0",
",",
"vs30",
")",
":",
"# Get reference z1pt0",
"z1ref",
"=",
"self",
".",
"_get_z1pt0ref",
"(",
"vs30",
")",
"# Get z1pt0",
"z10",
"=",
"copy",
".",
"deepcopy",
"(",
"z1pt0",
")",
"# This is used for the calculation of the motion on reference rock",
"idx",
"=",
"z1pt0",
"<",
"0",
"z10",
"[",
"idx",
"]",
"=",
"z1ref",
"[",
"idx",
"]",
"factor",
"=",
"np",
".",
"log",
"(",
"(",
"z10",
"+",
"0.01",
")",
"/",
"(",
"z1ref",
"+",
"0.01",
")",
")",
"# Here we use a linear interpolation as suggested in the 'Application",
"# guidelines' at page 1044",
"# Above 700 m/s the trend is flat, but we extend the Vs30 range to",
"# 6,000 m/s (basically the upper limit for mantle shear wave velocity",
"# on earth) to allow extrapolation without throwing an error.",
"f2",
"=",
"interpolate",
".",
"interp1d",
"(",
"[",
"0.0",
",",
"150",
",",
"250",
",",
"400",
",",
"700",
",",
"1000",
",",
"6000",
"]",
",",
"[",
"C",
"[",
"'a43'",
"]",
",",
"C",
"[",
"'a43'",
"]",
",",
"C",
"[",
"'a44'",
"]",
",",
"C",
"[",
"'a45'",
"]",
",",
"C",
"[",
"'a46'",
"]",
",",
"C",
"[",
"'a46'",
"]",
",",
"C",
"[",
"'a46'",
"]",
"]",
",",
"kind",
"=",
"'linear'",
")",
"return",
"f2",
"(",
"vs30",
")",
"*",
"factor"
] | Compute and return soil depth term. See page 1042. | [
"Compute",
"and",
"return",
"soil",
"depth",
"term",
".",
"See",
"page",
"1042",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L303-L325 | train | 233,406 |
gem/oq-engine | openquake/hazardlib/gsim/abrahamson_2014.py | AbrahamsonEtAl2014._get_stddevs | def _get_stddevs(self, C, imt, rup, sites, stddev_types, sa1180, dists):
"""
Return standard deviations as described in paragraph 'Equations for
standard deviation', page 1046.
"""
std_intra = self._get_intra_event_std(C, rup.mag, sa1180, sites.vs30,
sites.vs30measured, dists.rrup)
std_inter = self._get_inter_event_std(C, rup.mag, sa1180, sites.vs30)
stddevs = []
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if stddev_type == const.StdDev.TOTAL:
stddevs.append(np.sqrt(std_intra ** 2 +
std_inter ** 2))
elif stddev_type == const.StdDev.INTRA_EVENT:
stddevs.append(std_intra)
elif stddev_type == const.StdDev.INTER_EVENT:
stddevs.append(std_inter)
return stddevs | python | def _get_stddevs(self, C, imt, rup, sites, stddev_types, sa1180, dists):
"""
Return standard deviations as described in paragraph 'Equations for
standard deviation', page 1046.
"""
std_intra = self._get_intra_event_std(C, rup.mag, sa1180, sites.vs30,
sites.vs30measured, dists.rrup)
std_inter = self._get_inter_event_std(C, rup.mag, sa1180, sites.vs30)
stddevs = []
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if stddev_type == const.StdDev.TOTAL:
stddevs.append(np.sqrt(std_intra ** 2 +
std_inter ** 2))
elif stddev_type == const.StdDev.INTRA_EVENT:
stddevs.append(std_intra)
elif stddev_type == const.StdDev.INTER_EVENT:
stddevs.append(std_inter)
return stddevs | [
"def",
"_get_stddevs",
"(",
"self",
",",
"C",
",",
"imt",
",",
"rup",
",",
"sites",
",",
"stddev_types",
",",
"sa1180",
",",
"dists",
")",
":",
"std_intra",
"=",
"self",
".",
"_get_intra_event_std",
"(",
"C",
",",
"rup",
".",
"mag",
",",
"sa1180",
",",
"sites",
".",
"vs30",
",",
"sites",
".",
"vs30measured",
",",
"dists",
".",
"rrup",
")",
"std_inter",
"=",
"self",
".",
"_get_inter_event_std",
"(",
"C",
",",
"rup",
".",
"mag",
",",
"sa1180",
",",
"sites",
".",
"vs30",
")",
"stddevs",
"=",
"[",
"]",
"for",
"stddev_type",
"in",
"stddev_types",
":",
"assert",
"stddev_type",
"in",
"self",
".",
"DEFINED_FOR_STANDARD_DEVIATION_TYPES",
"if",
"stddev_type",
"==",
"const",
".",
"StdDev",
".",
"TOTAL",
":",
"stddevs",
".",
"append",
"(",
"np",
".",
"sqrt",
"(",
"std_intra",
"**",
"2",
"+",
"std_inter",
"**",
"2",
")",
")",
"elif",
"stddev_type",
"==",
"const",
".",
"StdDev",
".",
"INTRA_EVENT",
":",
"stddevs",
".",
"append",
"(",
"std_intra",
")",
"elif",
"stddev_type",
"==",
"const",
".",
"StdDev",
".",
"INTER_EVENT",
":",
"stddevs",
".",
"append",
"(",
"std_inter",
")",
"return",
"stddevs"
] | Return standard deviations as described in paragraph 'Equations for
standard deviation', page 1046. | [
"Return",
"standard",
"deviations",
"as",
"described",
"in",
"paragraph",
"Equations",
"for",
"standard",
"deviation",
"page",
"1046",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L334-L352 | train | 233,407 |
gem/oq-engine | openquake/hazardlib/gsim/abrahamson_2014.py | AbrahamsonEtAl2014._get_intra_event_std | def _get_intra_event_std(self, C, mag, sa1180, vs30, vs30measured,
rrup):
"""
Returns Phi as described at pages 1046 and 1047
"""
phi_al = self._get_phi_al_regional(C, mag, vs30measured, rrup)
derAmp = self._get_derivative(C, sa1180, vs30)
phi_amp = 0.4
idx = phi_al < phi_amp
if np.any(idx):
# In the case of small magnitudes and long periods it is possible
# for phi_al to take a value less than phi_amp, which would return
# a complex value. According to the GMPE authors in this case
# phi_amp should be reduced such that it is fractionally smaller
# than phi_al
phi_amp = 0.4 * np.ones_like(phi_al)
phi_amp[idx] = 0.99 * phi_al[idx]
phi_b = np.sqrt(phi_al**2 - phi_amp**2)
phi = np.sqrt(phi_b**2 * (1 + derAmp)**2 + phi_amp**2)
return phi | python | def _get_intra_event_std(self, C, mag, sa1180, vs30, vs30measured,
rrup):
"""
Returns Phi as described at pages 1046 and 1047
"""
phi_al = self._get_phi_al_regional(C, mag, vs30measured, rrup)
derAmp = self._get_derivative(C, sa1180, vs30)
phi_amp = 0.4
idx = phi_al < phi_amp
if np.any(idx):
# In the case of small magnitudes and long periods it is possible
# for phi_al to take a value less than phi_amp, which would return
# a complex value. According to the GMPE authors in this case
# phi_amp should be reduced such that it is fractionally smaller
# than phi_al
phi_amp = 0.4 * np.ones_like(phi_al)
phi_amp[idx] = 0.99 * phi_al[idx]
phi_b = np.sqrt(phi_al**2 - phi_amp**2)
phi = np.sqrt(phi_b**2 * (1 + derAmp)**2 + phi_amp**2)
return phi | [
"def",
"_get_intra_event_std",
"(",
"self",
",",
"C",
",",
"mag",
",",
"sa1180",
",",
"vs30",
",",
"vs30measured",
",",
"rrup",
")",
":",
"phi_al",
"=",
"self",
".",
"_get_phi_al_regional",
"(",
"C",
",",
"mag",
",",
"vs30measured",
",",
"rrup",
")",
"derAmp",
"=",
"self",
".",
"_get_derivative",
"(",
"C",
",",
"sa1180",
",",
"vs30",
")",
"phi_amp",
"=",
"0.4",
"idx",
"=",
"phi_al",
"<",
"phi_amp",
"if",
"np",
".",
"any",
"(",
"idx",
")",
":",
"# In the case of small magnitudes and long periods it is possible",
"# for phi_al to take a value less than phi_amp, which would return",
"# a complex value. According to the GMPE authors in this case",
"# phi_amp should be reduced such that it is fractionally smaller",
"# than phi_al",
"phi_amp",
"=",
"0.4",
"*",
"np",
".",
"ones_like",
"(",
"phi_al",
")",
"phi_amp",
"[",
"idx",
"]",
"=",
"0.99",
"*",
"phi_al",
"[",
"idx",
"]",
"phi_b",
"=",
"np",
".",
"sqrt",
"(",
"phi_al",
"**",
"2",
"-",
"phi_amp",
"**",
"2",
")",
"phi",
"=",
"np",
".",
"sqrt",
"(",
"phi_b",
"**",
"2",
"*",
"(",
"1",
"+",
"derAmp",
")",
"**",
"2",
"+",
"phi_amp",
"**",
"2",
")",
"return",
"phi"
] | Returns Phi as described at pages 1046 and 1047 | [
"Returns",
"Phi",
"as",
"described",
"at",
"pages",
"1046",
"and",
"1047"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L354-L373 | train | 233,408 |
gem/oq-engine | openquake/hazardlib/gsim/abrahamson_2014.py | AbrahamsonEtAl2014._get_derivative | def _get_derivative(self, C, sa1180, vs30):
"""
Returns equation 30 page 1047
"""
derAmp = np.zeros_like(vs30)
n = self.CONSTS['n']
c = C['c']
b = C['b']
idx = vs30 < C['vlin']
derAmp[idx] = (b * sa1180[idx] * (-1./(sa1180[idx]+c) +
1./(sa1180[idx] + c*(vs30[idx]/C['vlin'])**n)))
return derAmp | python | def _get_derivative(self, C, sa1180, vs30):
"""
Returns equation 30 page 1047
"""
derAmp = np.zeros_like(vs30)
n = self.CONSTS['n']
c = C['c']
b = C['b']
idx = vs30 < C['vlin']
derAmp[idx] = (b * sa1180[idx] * (-1./(sa1180[idx]+c) +
1./(sa1180[idx] + c*(vs30[idx]/C['vlin'])**n)))
return derAmp | [
"def",
"_get_derivative",
"(",
"self",
",",
"C",
",",
"sa1180",
",",
"vs30",
")",
":",
"derAmp",
"=",
"np",
".",
"zeros_like",
"(",
"vs30",
")",
"n",
"=",
"self",
".",
"CONSTS",
"[",
"'n'",
"]",
"c",
"=",
"C",
"[",
"'c'",
"]",
"b",
"=",
"C",
"[",
"'b'",
"]",
"idx",
"=",
"vs30",
"<",
"C",
"[",
"'vlin'",
"]",
"derAmp",
"[",
"idx",
"]",
"=",
"(",
"b",
"*",
"sa1180",
"[",
"idx",
"]",
"*",
"(",
"-",
"1.",
"/",
"(",
"sa1180",
"[",
"idx",
"]",
"+",
"c",
")",
"+",
"1.",
"/",
"(",
"sa1180",
"[",
"idx",
"]",
"+",
"c",
"*",
"(",
"vs30",
"[",
"idx",
"]",
"/",
"C",
"[",
"'vlin'",
"]",
")",
"**",
"n",
")",
")",
")",
"return",
"derAmp"
] | Returns equation 30 page 1047 | [
"Returns",
"equation",
"30",
"page",
"1047"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L375-L386 | train | 233,409 |
gem/oq-engine | openquake/hazardlib/gsim/abrahamson_2014.py | AbrahamsonEtAl2014RegJPN._get_regional_term | def _get_regional_term(self, C, imt, vs30, rrup):
"""
Compute regional term for Japan. See page 1043
"""
f3 = interpolate.interp1d(
[150, 250, 350, 450, 600, 850, 1150, 2000],
[C['a36'], C['a37'], C['a38'], C['a39'], C['a40'], C['a41'],
C['a42'], C['a42']],
kind='linear')
return f3(vs30) + C['a29'] * rrup | python | def _get_regional_term(self, C, imt, vs30, rrup):
"""
Compute regional term for Japan. See page 1043
"""
f3 = interpolate.interp1d(
[150, 250, 350, 450, 600, 850, 1150, 2000],
[C['a36'], C['a37'], C['a38'], C['a39'], C['a40'], C['a41'],
C['a42'], C['a42']],
kind='linear')
return f3(vs30) + C['a29'] * rrup | [
"def",
"_get_regional_term",
"(",
"self",
",",
"C",
",",
"imt",
",",
"vs30",
",",
"rrup",
")",
":",
"f3",
"=",
"interpolate",
".",
"interp1d",
"(",
"[",
"150",
",",
"250",
",",
"350",
",",
"450",
",",
"600",
",",
"850",
",",
"1150",
",",
"2000",
"]",
",",
"[",
"C",
"[",
"'a36'",
"]",
",",
"C",
"[",
"'a37'",
"]",
",",
"C",
"[",
"'a38'",
"]",
",",
"C",
"[",
"'a39'",
"]",
",",
"C",
"[",
"'a40'",
"]",
",",
"C",
"[",
"'a41'",
"]",
",",
"C",
"[",
"'a42'",
"]",
",",
"C",
"[",
"'a42'",
"]",
"]",
",",
"kind",
"=",
"'linear'",
")",
"return",
"f3",
"(",
"vs30",
")",
"+",
"C",
"[",
"'a29'",
"]",
"*",
"rrup"
] | Compute regional term for Japan. See page 1043 | [
"Compute",
"regional",
"term",
"for",
"Japan",
".",
"See",
"page",
"1043"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L511-L520 | train | 233,410 |
gem/oq-engine | openquake/hazardlib/gsim/yu_2013.py | gc | def gc(coeff, mag):
"""
Returns the set of coefficients to be used for the calculation of GM
as a function of earthquake magnitude
:param coeff:
A dictionary of parameters for the selected IMT
:param mag:
Magnitude value
:returns:
The set of coefficients
"""
if mag > 6.5:
a1ca = coeff['ua']
a1cb = coeff['ub']
a1cc = coeff['uc']
a1cd = coeff['ud']
a1ce = coeff['ue']
a2ca = coeff['ia']
a2cb = coeff['ib']
a2cc = coeff['ic']
a2cd = coeff['id']
a2ce = coeff['ie']
else:
a1ca = coeff['a']
a1cb = coeff['b']
a1cc = coeff['c']
a1cd = coeff['d']
a1ce = coeff['e']
a2ca = coeff['ma']
a2cb = coeff['mb']
a2cc = coeff['mc']
a2cd = coeff['md']
a2ce = coeff['me']
return a1ca, a1cb, a1cc, a1cd, a1ce, a2ca, a2cb, a2cc, a2cd, a2ce | python | def gc(coeff, mag):
"""
Returns the set of coefficients to be used for the calculation of GM
as a function of earthquake magnitude
:param coeff:
A dictionary of parameters for the selected IMT
:param mag:
Magnitude value
:returns:
The set of coefficients
"""
if mag > 6.5:
a1ca = coeff['ua']
a1cb = coeff['ub']
a1cc = coeff['uc']
a1cd = coeff['ud']
a1ce = coeff['ue']
a2ca = coeff['ia']
a2cb = coeff['ib']
a2cc = coeff['ic']
a2cd = coeff['id']
a2ce = coeff['ie']
else:
a1ca = coeff['a']
a1cb = coeff['b']
a1cc = coeff['c']
a1cd = coeff['d']
a1ce = coeff['e']
a2ca = coeff['ma']
a2cb = coeff['mb']
a2cc = coeff['mc']
a2cd = coeff['md']
a2ce = coeff['me']
return a1ca, a1cb, a1cc, a1cd, a1ce, a2ca, a2cb, a2cc, a2cd, a2ce | [
"def",
"gc",
"(",
"coeff",
",",
"mag",
")",
":",
"if",
"mag",
">",
"6.5",
":",
"a1ca",
"=",
"coeff",
"[",
"'ua'",
"]",
"a1cb",
"=",
"coeff",
"[",
"'ub'",
"]",
"a1cc",
"=",
"coeff",
"[",
"'uc'",
"]",
"a1cd",
"=",
"coeff",
"[",
"'ud'",
"]",
"a1ce",
"=",
"coeff",
"[",
"'ue'",
"]",
"a2ca",
"=",
"coeff",
"[",
"'ia'",
"]",
"a2cb",
"=",
"coeff",
"[",
"'ib'",
"]",
"a2cc",
"=",
"coeff",
"[",
"'ic'",
"]",
"a2cd",
"=",
"coeff",
"[",
"'id'",
"]",
"a2ce",
"=",
"coeff",
"[",
"'ie'",
"]",
"else",
":",
"a1ca",
"=",
"coeff",
"[",
"'a'",
"]",
"a1cb",
"=",
"coeff",
"[",
"'b'",
"]",
"a1cc",
"=",
"coeff",
"[",
"'c'",
"]",
"a1cd",
"=",
"coeff",
"[",
"'d'",
"]",
"a1ce",
"=",
"coeff",
"[",
"'e'",
"]",
"a2ca",
"=",
"coeff",
"[",
"'ma'",
"]",
"a2cb",
"=",
"coeff",
"[",
"'mb'",
"]",
"a2cc",
"=",
"coeff",
"[",
"'mc'",
"]",
"a2cd",
"=",
"coeff",
"[",
"'md'",
"]",
"a2ce",
"=",
"coeff",
"[",
"'me'",
"]",
"return",
"a1ca",
",",
"a1cb",
",",
"a1cc",
",",
"a1cd",
",",
"a1ce",
",",
"a2ca",
",",
"a2cb",
",",
"a2cc",
",",
"a2cd",
",",
"a2ce"
] | Returns the set of coefficients to be used for the calculation of GM
as a function of earthquake magnitude
:param coeff:
A dictionary of parameters for the selected IMT
:param mag:
Magnitude value
:returns:
The set of coefficients | [
"Returns",
"the",
"set",
"of",
"coefficients",
"to",
"be",
"used",
"for",
"the",
"calculation",
"of",
"GM",
"as",
"a",
"function",
"of",
"earthquake",
"magnitude"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/yu_2013.py#L34-L68 | train | 233,411 |
gem/oq-engine | openquake/hazardlib/gsim/yu_2013.py | rbf | def rbf(ra, coeff, mag):
"""
Calculate the median ground motion for a given magnitude and distance
:param ra:
Distance value [km]
:param coeff:
The set of coefficients
:param mag:
Magnitude value
:returns:
"""
a1ca, a1cb, a1cc, a1cd, a1ce, a2ca, a2cb, a2cc, a2cd, a2ce = gc(coeff, mag)
term1 = a1ca + a1cb * mag + a1cc * np.log(ra + a1cd*np.exp(a1ce*mag))
term2 = a2ca + a2cb * mag
term3 = a2cd*np.exp(a2ce*mag)
return np.exp((term1 - term2) / a2cc) - term3 | python | def rbf(ra, coeff, mag):
"""
Calculate the median ground motion for a given magnitude and distance
:param ra:
Distance value [km]
:param coeff:
The set of coefficients
:param mag:
Magnitude value
:returns:
"""
a1ca, a1cb, a1cc, a1cd, a1ce, a2ca, a2cb, a2cc, a2cd, a2ce = gc(coeff, mag)
term1 = a1ca + a1cb * mag + a1cc * np.log(ra + a1cd*np.exp(a1ce*mag))
term2 = a2ca + a2cb * mag
term3 = a2cd*np.exp(a2ce*mag)
return np.exp((term1 - term2) / a2cc) - term3 | [
"def",
"rbf",
"(",
"ra",
",",
"coeff",
",",
"mag",
")",
":",
"a1ca",
",",
"a1cb",
",",
"a1cc",
",",
"a1cd",
",",
"a1ce",
",",
"a2ca",
",",
"a2cb",
",",
"a2cc",
",",
"a2cd",
",",
"a2ce",
"=",
"gc",
"(",
"coeff",
",",
"mag",
")",
"term1",
"=",
"a1ca",
"+",
"a1cb",
"*",
"mag",
"+",
"a1cc",
"*",
"np",
".",
"log",
"(",
"ra",
"+",
"a1cd",
"*",
"np",
".",
"exp",
"(",
"a1ce",
"*",
"mag",
")",
")",
"term2",
"=",
"a2ca",
"+",
"a2cb",
"*",
"mag",
"term3",
"=",
"a2cd",
"*",
"np",
".",
"exp",
"(",
"a2ce",
"*",
"mag",
")",
"return",
"np",
".",
"exp",
"(",
"(",
"term1",
"-",
"term2",
")",
"/",
"a2cc",
")",
"-",
"term3"
] | Calculate the median ground motion for a given magnitude and distance
:param ra:
Distance value [km]
:param coeff:
The set of coefficients
:param mag:
Magnitude value
:returns: | [
"Calculate",
"the",
"median",
"ground",
"motion",
"for",
"a",
"given",
"magnitude",
"and",
"distance"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/yu_2013.py#L71-L88 | train | 233,412 |
gem/oq-engine | openquake/hazardlib/gsim/yu_2013.py | fnc | def fnc(ra, *args):
"""
Function used in the minimisation problem.
:param ra:
Semi-axis of the ellipses used in the Yu et al.
:returns:
The absolute difference between the epicentral distance and the
adjusted distance
"""
#
# epicentral distance
repi = args[0]
#
# azimuth
theta = args[1]
#
# magnitude
mag = args[2]
#
# coefficients
coeff = args[3]
#
# compute the difference between epicentral distances
rb = rbf(ra, coeff, mag)
t1 = ra**2 * (np.sin(np.radians(theta)))**2
t2 = rb**2 * (np.cos(np.radians(theta)))**2
xx = ra * rb / (t1+t2)**0.5
return xx-repi | python | def fnc(ra, *args):
"""
Function used in the minimisation problem.
:param ra:
Semi-axis of the ellipses used in the Yu et al.
:returns:
The absolute difference between the epicentral distance and the
adjusted distance
"""
#
# epicentral distance
repi = args[0]
#
# azimuth
theta = args[1]
#
# magnitude
mag = args[2]
#
# coefficients
coeff = args[3]
#
# compute the difference between epicentral distances
rb = rbf(ra, coeff, mag)
t1 = ra**2 * (np.sin(np.radians(theta)))**2
t2 = rb**2 * (np.cos(np.radians(theta)))**2
xx = ra * rb / (t1+t2)**0.5
return xx-repi | [
"def",
"fnc",
"(",
"ra",
",",
"*",
"args",
")",
":",
"#",
"# epicentral distance",
"repi",
"=",
"args",
"[",
"0",
"]",
"#",
"# azimuth",
"theta",
"=",
"args",
"[",
"1",
"]",
"#",
"# magnitude",
"mag",
"=",
"args",
"[",
"2",
"]",
"#",
"# coefficients",
"coeff",
"=",
"args",
"[",
"3",
"]",
"#",
"# compute the difference between epicentral distances",
"rb",
"=",
"rbf",
"(",
"ra",
",",
"coeff",
",",
"mag",
")",
"t1",
"=",
"ra",
"**",
"2",
"*",
"(",
"np",
".",
"sin",
"(",
"np",
".",
"radians",
"(",
"theta",
")",
")",
")",
"**",
"2",
"t2",
"=",
"rb",
"**",
"2",
"*",
"(",
"np",
".",
"cos",
"(",
"np",
".",
"radians",
"(",
"theta",
")",
")",
")",
"**",
"2",
"xx",
"=",
"ra",
"*",
"rb",
"/",
"(",
"t1",
"+",
"t2",
")",
"**",
"0.5",
"return",
"xx",
"-",
"repi"
] | Function used in the minimisation problem.
:param ra:
Semi-axis of the ellipses used in the Yu et al.
:returns:
The absolute difference between the epicentral distance and the
adjusted distance | [
"Function",
"used",
"in",
"the",
"minimisation",
"problem",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/yu_2013.py#L91-L119 | train | 233,413 |
gem/oq-engine | openquake/hazardlib/gsim/yu_2013.py | get_ras | def get_ras(repi, theta, mag, coeff):
"""
Computes equivalent distance
:param repi:
Epicentral distance
:param theta:
Azimuth value
:param mag:
Magnitude
:param coeff:
GMPE coefficients
"""
rx = 100.
ras = 200.
#
# calculate the difference between epicentral distances
dff = fnc(ras, repi, theta, mag, coeff)
while abs(dff) > 1e-3:
# update the value of distance computed
if dff > 0.:
ras = ras - rx
else:
ras = ras + rx
dff = fnc(ras, repi, theta, mag, coeff)
rx = rx / 2.
if rx < 1e-3:
break
return ras | python | def get_ras(repi, theta, mag, coeff):
"""
Computes equivalent distance
:param repi:
Epicentral distance
:param theta:
Azimuth value
:param mag:
Magnitude
:param coeff:
GMPE coefficients
"""
rx = 100.
ras = 200.
#
# calculate the difference between epicentral distances
dff = fnc(ras, repi, theta, mag, coeff)
while abs(dff) > 1e-3:
# update the value of distance computed
if dff > 0.:
ras = ras - rx
else:
ras = ras + rx
dff = fnc(ras, repi, theta, mag, coeff)
rx = rx / 2.
if rx < 1e-3:
break
return ras | [
"def",
"get_ras",
"(",
"repi",
",",
"theta",
",",
"mag",
",",
"coeff",
")",
":",
"rx",
"=",
"100.",
"ras",
"=",
"200.",
"#",
"# calculate the difference between epicentral distances",
"dff",
"=",
"fnc",
"(",
"ras",
",",
"repi",
",",
"theta",
",",
"mag",
",",
"coeff",
")",
"while",
"abs",
"(",
"dff",
")",
">",
"1e-3",
":",
"# update the value of distance computed",
"if",
"dff",
">",
"0.",
":",
"ras",
"=",
"ras",
"-",
"rx",
"else",
":",
"ras",
"=",
"ras",
"+",
"rx",
"dff",
"=",
"fnc",
"(",
"ras",
",",
"repi",
",",
"theta",
",",
"mag",
",",
"coeff",
")",
"rx",
"=",
"rx",
"/",
"2.",
"if",
"rx",
"<",
"1e-3",
":",
"break",
"return",
"ras"
] | Computes equivalent distance
:param repi:
Epicentral distance
:param theta:
Azimuth value
:param mag:
Magnitude
:param coeff:
GMPE coefficients | [
"Computes",
"equivalent",
"distance"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/yu_2013.py#L122-L150 | train | 233,414 |
gem/oq-engine | openquake/hazardlib/gsim/shahjouei_pezeshk_2016.py | ShahjoueiPezeshk2016._get_stddevs | def _get_stddevs(self, C, stddev_types, rup, imt, num_sites):
"""
Return standard deviations as defined in eq. 4 and 5, page 744,
based on table 8, page 744.
Eq. 5 yields std dev in natural log, so convert to log10
"""
stddevs = []
for stddev_type in stddev_types:
sigma_mean = self._compute_standard_dev(rup, imt, C)
sigma_tot = np.sqrt((sigma_mean ** 2) + (C['SigmaReg'] ** 2))
sigma_tot = np.log10(np.exp(sigma_tot))
stddevs.append(sigma_tot + np.zeros(num_sites))
return stddevs | python | def _get_stddevs(self, C, stddev_types, rup, imt, num_sites):
"""
Return standard deviations as defined in eq. 4 and 5, page 744,
based on table 8, page 744.
Eq. 5 yields std dev in natural log, so convert to log10
"""
stddevs = []
for stddev_type in stddev_types:
sigma_mean = self._compute_standard_dev(rup, imt, C)
sigma_tot = np.sqrt((sigma_mean ** 2) + (C['SigmaReg'] ** 2))
sigma_tot = np.log10(np.exp(sigma_tot))
stddevs.append(sigma_tot + np.zeros(num_sites))
return stddevs | [
"def",
"_get_stddevs",
"(",
"self",
",",
"C",
",",
"stddev_types",
",",
"rup",
",",
"imt",
",",
"num_sites",
")",
":",
"stddevs",
"=",
"[",
"]",
"for",
"stddev_type",
"in",
"stddev_types",
":",
"sigma_mean",
"=",
"self",
".",
"_compute_standard_dev",
"(",
"rup",
",",
"imt",
",",
"C",
")",
"sigma_tot",
"=",
"np",
".",
"sqrt",
"(",
"(",
"sigma_mean",
"**",
"2",
")",
"+",
"(",
"C",
"[",
"'SigmaReg'",
"]",
"**",
"2",
")",
")",
"sigma_tot",
"=",
"np",
".",
"log10",
"(",
"np",
".",
"exp",
"(",
"sigma_tot",
")",
")",
"stddevs",
".",
"append",
"(",
"sigma_tot",
"+",
"np",
".",
"zeros",
"(",
"num_sites",
")",
")",
"return",
"stddevs"
] | Return standard deviations as defined in eq. 4 and 5, page 744,
based on table 8, page 744.
Eq. 5 yields std dev in natural log, so convert to log10 | [
"Return",
"standard",
"deviations",
"as",
"defined",
"in",
"eq",
".",
"4",
"and",
"5",
"page",
"744",
"based",
"on",
"table",
"8",
"page",
"744",
".",
"Eq",
".",
"5",
"yields",
"std",
"dev",
"in",
"natural",
"log",
"so",
"convert",
"to",
"log10"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/shahjouei_pezeshk_2016.py#L103-L115 | train | 233,415 |
gem/oq-engine | openquake/hazardlib/gsim/shahjouei_pezeshk_2016.py | ShahjoueiPezeshk2016._compute_standard_dev | def _compute_standard_dev(self, rup, imt, C):
"""
Compute the the standard deviation in terms of magnitude
described on page 744, eq. 4
"""
sigma_mean = 0.
if imt.name in "SA PGA":
psi = -6.898E-3
else:
psi = -3.054E-5
if rup.mag <= 6.5:
sigma_mean = (C['c12'] * rup.mag) + C['c13']
elif rup.mag > 6.5:
sigma_mean = (psi * rup.mag) + C['c14']
return sigma_mean | python | def _compute_standard_dev(self, rup, imt, C):
"""
Compute the the standard deviation in terms of magnitude
described on page 744, eq. 4
"""
sigma_mean = 0.
if imt.name in "SA PGA":
psi = -6.898E-3
else:
psi = -3.054E-5
if rup.mag <= 6.5:
sigma_mean = (C['c12'] * rup.mag) + C['c13']
elif rup.mag > 6.5:
sigma_mean = (psi * rup.mag) + C['c14']
return sigma_mean | [
"def",
"_compute_standard_dev",
"(",
"self",
",",
"rup",
",",
"imt",
",",
"C",
")",
":",
"sigma_mean",
"=",
"0.",
"if",
"imt",
".",
"name",
"in",
"\"SA PGA\"",
":",
"psi",
"=",
"-",
"6.898E-3",
"else",
":",
"psi",
"=",
"-",
"3.054E-5",
"if",
"rup",
".",
"mag",
"<=",
"6.5",
":",
"sigma_mean",
"=",
"(",
"C",
"[",
"'c12'",
"]",
"*",
"rup",
".",
"mag",
")",
"+",
"C",
"[",
"'c13'",
"]",
"elif",
"rup",
".",
"mag",
">",
"6.5",
":",
"sigma_mean",
"=",
"(",
"psi",
"*",
"rup",
".",
"mag",
")",
"+",
"C",
"[",
"'c14'",
"]",
"return",
"sigma_mean"
] | Compute the the standard deviation in terms of magnitude
described on page 744, eq. 4 | [
"Compute",
"the",
"the",
"standard",
"deviation",
"in",
"terms",
"of",
"magnitude",
"described",
"on",
"page",
"744",
"eq",
".",
"4"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/shahjouei_pezeshk_2016.py#L164-L178 | train | 233,416 |
gem/oq-engine | openquake/server/dbapi.py | Db.insert | def insert(self, table, columns, rows):
"""
Insert several rows with executemany. Return a cursor.
"""
cursor = self.conn.cursor()
if len(rows):
templ, _args = match('INSERT INTO ?s (?S) VALUES (?X)',
table, columns, rows[0])
cursor.executemany(templ, rows)
return cursor | python | def insert(self, table, columns, rows):
"""
Insert several rows with executemany. Return a cursor.
"""
cursor = self.conn.cursor()
if len(rows):
templ, _args = match('INSERT INTO ?s (?S) VALUES (?X)',
table, columns, rows[0])
cursor.executemany(templ, rows)
return cursor | [
"def",
"insert",
"(",
"self",
",",
"table",
",",
"columns",
",",
"rows",
")",
":",
"cursor",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"if",
"len",
"(",
"rows",
")",
":",
"templ",
",",
"_args",
"=",
"match",
"(",
"'INSERT INTO ?s (?S) VALUES (?X)'",
",",
"table",
",",
"columns",
",",
"rows",
"[",
"0",
"]",
")",
"cursor",
".",
"executemany",
"(",
"templ",
",",
"rows",
")",
"return",
"cursor"
] | Insert several rows with executemany. Return a cursor. | [
"Insert",
"several",
"rows",
"with",
"executemany",
".",
"Return",
"a",
"cursor",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/dbapi.py#L362-L371 | train | 233,417 |
gem/oq-engine | openquake/hazardlib/calc/hazard_curve.py | _cluster | def _cluster(param, tom, imtls, gsims, grp_ids, pmap):
"""
Computes the probability map in case of a cluster group
"""
pmapclu = AccumDict({grp_id: ProbabilityMap(len(imtls.array), len(gsims))
for grp_id in grp_ids})
# Get temporal occurrence model
# Number of occurrences for the cluster
first = True
for nocc in range(0, 50):
# TODO fix this once the occurrence rate will be used just as
# an object attribute
ocr = tom.occurrence_rate
prob_n_occ = tom.get_probability_n_occurrences(ocr, nocc)
if first:
pmapclu = prob_n_occ * (~pmap)**nocc
first = False
else:
pmapclu += prob_n_occ * (~pmap)**nocc
pmap = ~pmapclu
return pmap | python | def _cluster(param, tom, imtls, gsims, grp_ids, pmap):
"""
Computes the probability map in case of a cluster group
"""
pmapclu = AccumDict({grp_id: ProbabilityMap(len(imtls.array), len(gsims))
for grp_id in grp_ids})
# Get temporal occurrence model
# Number of occurrences for the cluster
first = True
for nocc in range(0, 50):
# TODO fix this once the occurrence rate will be used just as
# an object attribute
ocr = tom.occurrence_rate
prob_n_occ = tom.get_probability_n_occurrences(ocr, nocc)
if first:
pmapclu = prob_n_occ * (~pmap)**nocc
first = False
else:
pmapclu += prob_n_occ * (~pmap)**nocc
pmap = ~pmapclu
return pmap | [
"def",
"_cluster",
"(",
"param",
",",
"tom",
",",
"imtls",
",",
"gsims",
",",
"grp_ids",
",",
"pmap",
")",
":",
"pmapclu",
"=",
"AccumDict",
"(",
"{",
"grp_id",
":",
"ProbabilityMap",
"(",
"len",
"(",
"imtls",
".",
"array",
")",
",",
"len",
"(",
"gsims",
")",
")",
"for",
"grp_id",
"in",
"grp_ids",
"}",
")",
"# Get temporal occurrence model",
"# Number of occurrences for the cluster",
"first",
"=",
"True",
"for",
"nocc",
"in",
"range",
"(",
"0",
",",
"50",
")",
":",
"# TODO fix this once the occurrence rate will be used just as",
"# an object attribute",
"ocr",
"=",
"tom",
".",
"occurrence_rate",
"prob_n_occ",
"=",
"tom",
".",
"get_probability_n_occurrences",
"(",
"ocr",
",",
"nocc",
")",
"if",
"first",
":",
"pmapclu",
"=",
"prob_n_occ",
"*",
"(",
"~",
"pmap",
")",
"**",
"nocc",
"first",
"=",
"False",
"else",
":",
"pmapclu",
"+=",
"prob_n_occ",
"*",
"(",
"~",
"pmap",
")",
"**",
"nocc",
"pmap",
"=",
"~",
"pmapclu",
"return",
"pmap"
] | Computes the probability map in case of a cluster group | [
"Computes",
"the",
"probability",
"map",
"in",
"case",
"of",
"a",
"cluster",
"group"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/hazard_curve.py#L71-L91 | train | 233,418 |
gem/oq-engine | openquake/hazardlib/gsim/kale_2015.py | KaleEtAl2015Turkey._get_stddevs | def _get_stddevs(self, C, rup, shape, stddev_types):
"""
Return standard deviations as defined in p. 971.
"""
weight = self._compute_weight_std(C, rup.mag)
std_intra = weight * C["sd1"] * np.ones(shape)
std_inter = weight * C["sd2"] * np.ones(shape)
stddevs = []
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if stddev_type == const.StdDev.TOTAL:
stddevs.append(np.sqrt(std_intra ** 2. + std_inter ** 2.))
elif stddev_type == const.StdDev.INTRA_EVENT:
stddevs.append(std_intra)
elif stddev_type == const.StdDev.INTER_EVENT:
stddevs.append(std_inter)
return stddevs | python | def _get_stddevs(self, C, rup, shape, stddev_types):
"""
Return standard deviations as defined in p. 971.
"""
weight = self._compute_weight_std(C, rup.mag)
std_intra = weight * C["sd1"] * np.ones(shape)
std_inter = weight * C["sd2"] * np.ones(shape)
stddevs = []
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if stddev_type == const.StdDev.TOTAL:
stddevs.append(np.sqrt(std_intra ** 2. + std_inter ** 2.))
elif stddev_type == const.StdDev.INTRA_EVENT:
stddevs.append(std_intra)
elif stddev_type == const.StdDev.INTER_EVENT:
stddevs.append(std_inter)
return stddevs | [
"def",
"_get_stddevs",
"(",
"self",
",",
"C",
",",
"rup",
",",
"shape",
",",
"stddev_types",
")",
":",
"weight",
"=",
"self",
".",
"_compute_weight_std",
"(",
"C",
",",
"rup",
".",
"mag",
")",
"std_intra",
"=",
"weight",
"*",
"C",
"[",
"\"sd1\"",
"]",
"*",
"np",
".",
"ones",
"(",
"shape",
")",
"std_inter",
"=",
"weight",
"*",
"C",
"[",
"\"sd2\"",
"]",
"*",
"np",
".",
"ones",
"(",
"shape",
")",
"stddevs",
"=",
"[",
"]",
"for",
"stddev_type",
"in",
"stddev_types",
":",
"assert",
"stddev_type",
"in",
"self",
".",
"DEFINED_FOR_STANDARD_DEVIATION_TYPES",
"if",
"stddev_type",
"==",
"const",
".",
"StdDev",
".",
"TOTAL",
":",
"stddevs",
".",
"append",
"(",
"np",
".",
"sqrt",
"(",
"std_intra",
"**",
"2.",
"+",
"std_inter",
"**",
"2.",
")",
")",
"elif",
"stddev_type",
"==",
"const",
".",
"StdDev",
".",
"INTRA_EVENT",
":",
"stddevs",
".",
"append",
"(",
"std_intra",
")",
"elif",
"stddev_type",
"==",
"const",
".",
"StdDev",
".",
"INTER_EVENT",
":",
"stddevs",
".",
"append",
"(",
"std_inter",
")",
"return",
"stddevs"
] | Return standard deviations as defined in p. 971. | [
"Return",
"standard",
"deviations",
"as",
"defined",
"in",
"p",
".",
"971",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/kale_2015.py#L99-L116 | train | 233,419 |
gem/oq-engine | openquake/hazardlib/gsim/kale_2015.py | KaleEtAl2015Turkey._compute_weight_std | def _compute_weight_std(self, C, mag):
"""
Common part of equations 8 and 9, page 971.
"""
if mag < 6.0:
return C['a1']
elif mag >= 6.0 and mag < 6.5:
return C['a1'] + (C['a2'] - C['a1']) * ((mag - 6.0) / 0.5)
else:
return C['a2'] | python | def _compute_weight_std(self, C, mag):
"""
Common part of equations 8 and 9, page 971.
"""
if mag < 6.0:
return C['a1']
elif mag >= 6.0 and mag < 6.5:
return C['a1'] + (C['a2'] - C['a1']) * ((mag - 6.0) / 0.5)
else:
return C['a2'] | [
"def",
"_compute_weight_std",
"(",
"self",
",",
"C",
",",
"mag",
")",
":",
"if",
"mag",
"<",
"6.0",
":",
"return",
"C",
"[",
"'a1'",
"]",
"elif",
"mag",
">=",
"6.0",
"and",
"mag",
"<",
"6.5",
":",
"return",
"C",
"[",
"'a1'",
"]",
"+",
"(",
"C",
"[",
"'a2'",
"]",
"-",
"C",
"[",
"'a1'",
"]",
")",
"*",
"(",
"(",
"mag",
"-",
"6.0",
")",
"/",
"0.5",
")",
"else",
":",
"return",
"C",
"[",
"'a2'",
"]"
] | Common part of equations 8 and 9, page 971. | [
"Common",
"part",
"of",
"equations",
"8",
"and",
"9",
"page",
"971",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/kale_2015.py#L118-L127 | train | 233,420 |
gem/oq-engine | openquake/hazardlib/gsim/kale_2015.py | KaleEtAl2015Turkey._compute_magnitude_scaling_term | def _compute_magnitude_scaling_term(self, C, mag):
"""
Compute and return magnitude scaling term in equation 2,
page 970.
"""
c1 = self.CONSTS['c1']
if mag <= c1:
return C['b1'] + C['b2'] * (mag - c1) + C['b3'] * (8.5 - mag) ** 2
else:
return C['b1'] + C['b7'] * (mag - c1) + C['b3'] * (8.5 - mag) ** 2 | python | def _compute_magnitude_scaling_term(self, C, mag):
"""
Compute and return magnitude scaling term in equation 2,
page 970.
"""
c1 = self.CONSTS['c1']
if mag <= c1:
return C['b1'] + C['b2'] * (mag - c1) + C['b3'] * (8.5 - mag) ** 2
else:
return C['b1'] + C['b7'] * (mag - c1) + C['b3'] * (8.5 - mag) ** 2 | [
"def",
"_compute_magnitude_scaling_term",
"(",
"self",
",",
"C",
",",
"mag",
")",
":",
"c1",
"=",
"self",
".",
"CONSTS",
"[",
"'c1'",
"]",
"if",
"mag",
"<=",
"c1",
":",
"return",
"C",
"[",
"'b1'",
"]",
"+",
"C",
"[",
"'b2'",
"]",
"*",
"(",
"mag",
"-",
"c1",
")",
"+",
"C",
"[",
"'b3'",
"]",
"*",
"(",
"8.5",
"-",
"mag",
")",
"**",
"2",
"else",
":",
"return",
"C",
"[",
"'b1'",
"]",
"+",
"C",
"[",
"'b7'",
"]",
"*",
"(",
"mag",
"-",
"c1",
")",
"+",
"C",
"[",
"'b3'",
"]",
"*",
"(",
"8.5",
"-",
"mag",
")",
"**",
"2"
] | Compute and return magnitude scaling term in equation 2,
page 970. | [
"Compute",
"and",
"return",
"magnitude",
"scaling",
"term",
"in",
"equation",
"2",
"page",
"970",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/kale_2015.py#L129-L138 | train | 233,421 |
gem/oq-engine | openquake/hazardlib/gsim/kale_2015.py | KaleEtAl2015Turkey._compute_geometric_decay_term | def _compute_geometric_decay_term(self, C, mag, dists):
"""
Compute and return geometric decay term in equation 3,
page 970.
"""
c1 = self.CONSTS['c1']
return (
(C['b4'] + C['b5'] * (mag - c1)) *
np.log(np.sqrt(dists.rjb ** 2.0 + C['b6'] ** 2.0))
) | python | def _compute_geometric_decay_term(self, C, mag, dists):
"""
Compute and return geometric decay term in equation 3,
page 970.
"""
c1 = self.CONSTS['c1']
return (
(C['b4'] + C['b5'] * (mag - c1)) *
np.log(np.sqrt(dists.rjb ** 2.0 + C['b6'] ** 2.0))
) | [
"def",
"_compute_geometric_decay_term",
"(",
"self",
",",
"C",
",",
"mag",
",",
"dists",
")",
":",
"c1",
"=",
"self",
".",
"CONSTS",
"[",
"'c1'",
"]",
"return",
"(",
"(",
"C",
"[",
"'b4'",
"]",
"+",
"C",
"[",
"'b5'",
"]",
"*",
"(",
"mag",
"-",
"c1",
")",
")",
"*",
"np",
".",
"log",
"(",
"np",
".",
"sqrt",
"(",
"dists",
".",
"rjb",
"**",
"2.0",
"+",
"C",
"[",
"'b6'",
"]",
"**",
"2.0",
")",
")",
")"
] | Compute and return geometric decay term in equation 3,
page 970. | [
"Compute",
"and",
"return",
"geometric",
"decay",
"term",
"in",
"equation",
"3",
"page",
"970",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/kale_2015.py#L140-L149 | train | 233,422 |
gem/oq-engine | openquake/hazardlib/gsim/kale_2015.py | KaleEtAl2015Turkey._compute_anelestic_attenuation_term | def _compute_anelestic_attenuation_term(self, C, dists):
"""
Compute and return anelastic attenuation term in equation 5,
page 970.
"""
f_aat = np.zeros_like(dists.rjb)
idx = dists.rjb > 80.0
f_aat[idx] = C["b10"] * (dists.rjb[idx] - 80.0)
return f_aat | python | def _compute_anelestic_attenuation_term(self, C, dists):
"""
Compute and return anelastic attenuation term in equation 5,
page 970.
"""
f_aat = np.zeros_like(dists.rjb)
idx = dists.rjb > 80.0
f_aat[idx] = C["b10"] * (dists.rjb[idx] - 80.0)
return f_aat | [
"def",
"_compute_anelestic_attenuation_term",
"(",
"self",
",",
"C",
",",
"dists",
")",
":",
"f_aat",
"=",
"np",
".",
"zeros_like",
"(",
"dists",
".",
"rjb",
")",
"idx",
"=",
"dists",
".",
"rjb",
">",
"80.0",
"f_aat",
"[",
"idx",
"]",
"=",
"C",
"[",
"\"b10\"",
"]",
"*",
"(",
"dists",
".",
"rjb",
"[",
"idx",
"]",
"-",
"80.0",
")",
"return",
"f_aat"
] | Compute and return anelastic attenuation term in equation 5,
page 970. | [
"Compute",
"and",
"return",
"anelastic",
"attenuation",
"term",
"in",
"equation",
"5",
"page",
"970",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/kale_2015.py#L161-L169 | train | 233,423 |
gem/oq-engine | openquake/hazardlib/gsim/kale_2015.py | KaleEtAl2015Turkey._compute_non_linear_term | def _compute_non_linear_term(self, C, pga_only, sites):
"""
Compute non-linear term, equation 6, page 970.
"""
Vref = self.CONSTS['Vref']
Vcon = self.CONSTS['Vcon']
c = self.CONSTS['c']
n = self.CONSTS['n']
lnS = np.zeros_like(sites.vs30)
# equation (6a)
idx = sites.vs30 < Vref
lnS[idx] = (
C['sb1'] * np.log(sites.vs30[idx] / Vref) +
C['sb2'] * np.log(
(pga_only[idx] + c * (sites.vs30[idx] / Vref) ** n) /
((pga_only[idx] + c) * (sites.vs30[idx] / Vref) ** n)
)
)
# equation (6b)
idx = sites.vs30 >= Vref
new_sites = sites.vs30[idx]
new_sites[new_sites > Vcon] = Vcon
lnS[idx] = C['sb1'] * np.log(new_sites / Vref)
return lnS | python | def _compute_non_linear_term(self, C, pga_only, sites):
"""
Compute non-linear term, equation 6, page 970.
"""
Vref = self.CONSTS['Vref']
Vcon = self.CONSTS['Vcon']
c = self.CONSTS['c']
n = self.CONSTS['n']
lnS = np.zeros_like(sites.vs30)
# equation (6a)
idx = sites.vs30 < Vref
lnS[idx] = (
C['sb1'] * np.log(sites.vs30[idx] / Vref) +
C['sb2'] * np.log(
(pga_only[idx] + c * (sites.vs30[idx] / Vref) ** n) /
((pga_only[idx] + c) * (sites.vs30[idx] / Vref) ** n)
)
)
# equation (6b)
idx = sites.vs30 >= Vref
new_sites = sites.vs30[idx]
new_sites[new_sites > Vcon] = Vcon
lnS[idx] = C['sb1'] * np.log(new_sites / Vref)
return lnS | [
"def",
"_compute_non_linear_term",
"(",
"self",
",",
"C",
",",
"pga_only",
",",
"sites",
")",
":",
"Vref",
"=",
"self",
".",
"CONSTS",
"[",
"'Vref'",
"]",
"Vcon",
"=",
"self",
".",
"CONSTS",
"[",
"'Vcon'",
"]",
"c",
"=",
"self",
".",
"CONSTS",
"[",
"'c'",
"]",
"n",
"=",
"self",
".",
"CONSTS",
"[",
"'n'",
"]",
"lnS",
"=",
"np",
".",
"zeros_like",
"(",
"sites",
".",
"vs30",
")",
"# equation (6a)\r",
"idx",
"=",
"sites",
".",
"vs30",
"<",
"Vref",
"lnS",
"[",
"idx",
"]",
"=",
"(",
"C",
"[",
"'sb1'",
"]",
"*",
"np",
".",
"log",
"(",
"sites",
".",
"vs30",
"[",
"idx",
"]",
"/",
"Vref",
")",
"+",
"C",
"[",
"'sb2'",
"]",
"*",
"np",
".",
"log",
"(",
"(",
"pga_only",
"[",
"idx",
"]",
"+",
"c",
"*",
"(",
"sites",
".",
"vs30",
"[",
"idx",
"]",
"/",
"Vref",
")",
"**",
"n",
")",
"/",
"(",
"(",
"pga_only",
"[",
"idx",
"]",
"+",
"c",
")",
"*",
"(",
"sites",
".",
"vs30",
"[",
"idx",
"]",
"/",
"Vref",
")",
"**",
"n",
")",
")",
")",
"# equation (6b)\r",
"idx",
"=",
"sites",
".",
"vs30",
">=",
"Vref",
"new_sites",
"=",
"sites",
".",
"vs30",
"[",
"idx",
"]",
"new_sites",
"[",
"new_sites",
">",
"Vcon",
"]",
"=",
"Vcon",
"lnS",
"[",
"idx",
"]",
"=",
"C",
"[",
"'sb1'",
"]",
"*",
"np",
".",
"log",
"(",
"new_sites",
"/",
"Vref",
")",
"return",
"lnS"
] | Compute non-linear term, equation 6, page 970. | [
"Compute",
"non",
"-",
"linear",
"term",
"equation",
"6",
"page",
"970",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/kale_2015.py#L171-L197 | train | 233,424 |
gem/oq-engine | openquake/hazardlib/gsim/kale_2015.py | KaleEtAl2015Turkey._compute_mean | def _compute_mean(self, C, mag, dists, rake):
"""
Compute and return mean value without site conditions,
that is equations 2-5, page 970.
"""
mean = (
self._compute_magnitude_scaling_term(C, mag) +
self._compute_geometric_decay_term(C, mag, dists) +
self._compute_faulting_style_term(C, rake) +
self._compute_anelestic_attenuation_term(C, dists)
)
return mean | python | def _compute_mean(self, C, mag, dists, rake):
"""
Compute and return mean value without site conditions,
that is equations 2-5, page 970.
"""
mean = (
self._compute_magnitude_scaling_term(C, mag) +
self._compute_geometric_decay_term(C, mag, dists) +
self._compute_faulting_style_term(C, rake) +
self._compute_anelestic_attenuation_term(C, dists)
)
return mean | [
"def",
"_compute_mean",
"(",
"self",
",",
"C",
",",
"mag",
",",
"dists",
",",
"rake",
")",
":",
"mean",
"=",
"(",
"self",
".",
"_compute_magnitude_scaling_term",
"(",
"C",
",",
"mag",
")",
"+",
"self",
".",
"_compute_geometric_decay_term",
"(",
"C",
",",
"mag",
",",
"dists",
")",
"+",
"self",
".",
"_compute_faulting_style_term",
"(",
"C",
",",
"rake",
")",
"+",
"self",
".",
"_compute_anelestic_attenuation_term",
"(",
"C",
",",
"dists",
")",
")",
"return",
"mean"
] | Compute and return mean value without site conditions,
that is equations 2-5, page 970. | [
"Compute",
"and",
"return",
"mean",
"value",
"without",
"site",
"conditions",
"that",
"is",
"equations",
"2",
"-",
"5",
"page",
"970",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/kale_2015.py#L199-L211 | train | 233,425 |
gem/oq-engine | openquake/hazardlib/source/multi.py | MultiPointSource.get_bounding_box | def get_bounding_box(self, maxdist):
"""
Bounding box containing all the point sources, enlarged by the
maximum distance.
"""
return utils.get_bounding_box([ps.location for ps in self], maxdist) | python | def get_bounding_box(self, maxdist):
"""
Bounding box containing all the point sources, enlarged by the
maximum distance.
"""
return utils.get_bounding_box([ps.location for ps in self], maxdist) | [
"def",
"get_bounding_box",
"(",
"self",
",",
"maxdist",
")",
":",
"return",
"utils",
".",
"get_bounding_box",
"(",
"[",
"ps",
".",
"location",
"for",
"ps",
"in",
"self",
"]",
",",
"maxdist",
")"
] | Bounding box containing all the point sources, enlarged by the
maximum distance. | [
"Bounding",
"box",
"containing",
"all",
"the",
"point",
"sources",
"enlarged",
"by",
"the",
"maximum",
"distance",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/source/multi.py#L109-L114 | train | 233,426 |
gem/oq-engine | openquake/hazardlib/gsim/pezeshk_2011.py | PezeshkEtAl2011._compute_standard_dev | def _compute_standard_dev(self, rup, imt, C):
"""
Compute the the standard deviation in terms of magnitude
described on p. 1866, eq. 6
"""
sigma_mean = 0.
if rup.mag <= 7.0:
sigma_mean = (C['c12'] * rup.mag) + C['c13']
elif rup.mag > 7.0:
sigma_mean = (-0.00695 * rup.mag) + C['c14']
return sigma_mean | python | def _compute_standard_dev(self, rup, imt, C):
"""
Compute the the standard deviation in terms of magnitude
described on p. 1866, eq. 6
"""
sigma_mean = 0.
if rup.mag <= 7.0:
sigma_mean = (C['c12'] * rup.mag) + C['c13']
elif rup.mag > 7.0:
sigma_mean = (-0.00695 * rup.mag) + C['c14']
return sigma_mean | [
"def",
"_compute_standard_dev",
"(",
"self",
",",
"rup",
",",
"imt",
",",
"C",
")",
":",
"sigma_mean",
"=",
"0.",
"if",
"rup",
".",
"mag",
"<=",
"7.0",
":",
"sigma_mean",
"=",
"(",
"C",
"[",
"'c12'",
"]",
"*",
"rup",
".",
"mag",
")",
"+",
"C",
"[",
"'c13'",
"]",
"elif",
"rup",
".",
"mag",
">",
"7.0",
":",
"sigma_mean",
"=",
"(",
"-",
"0.00695",
"*",
"rup",
".",
"mag",
")",
"+",
"C",
"[",
"'c14'",
"]",
"return",
"sigma_mean"
] | Compute the the standard deviation in terms of magnitude
described on p. 1866, eq. 6 | [
"Compute",
"the",
"the",
"standard",
"deviation",
"in",
"terms",
"of",
"magnitude",
"described",
"on",
"p",
".",
"1866",
"eq",
".",
"6"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/pezeshk_2011.py#L158-L168 | train | 233,427 |
gem/oq-engine | openquake/hmtk/strain/shift.py | Shift.get_rate_osr_normal_transform | def get_rate_osr_normal_transform(self, threshold_moment, id0):
'''
Gets seismicity rate for special case of the ridge condition with
spreading and transform component
:param float threshold_moment:
Moment required for calculating activity rate
:param np.ndarray id0:
Logical vector indicating the cells to which this condition applies
:returns:
Activity rates for cells corresponding to the hybrid ocean
spreading ridge and oceanic transform condition
'''
# Get normal component
e1h_ridge = np.zeros(np.sum(id0), dtype=float)
e2h_ridge = self.strain.data['e1h'][id0] + self.strain.data['e2h'][id0]
err_ridge = -(e1h_ridge + e2h_ridge)
calculated_rate_ridge = self.continuum_seismicity(
threshold_moment,
e1h_ridge,
e2h_ridge,
err_ridge,
self.regionalisation['OSRnor'])
# Get transform
e1h_trans = self.strain.data['e1h'][id0]
e2h_trans = -e1h_trans
err_trans = np.zeros(np.sum(id0), dtype=float)
calculated_rate_transform = self.continuum_seismicity(
threshold_moment,
e1h_trans,
e2h_trans,
err_trans,
self.regionalisation['OTFmed'])
return (
self.regionalisation['OSRnor']['adjustment_factor'] *
(calculated_rate_ridge + calculated_rate_transform)) | python | def get_rate_osr_normal_transform(self, threshold_moment, id0):
'''
Gets seismicity rate for special case of the ridge condition with
spreading and transform component
:param float threshold_moment:
Moment required for calculating activity rate
:param np.ndarray id0:
Logical vector indicating the cells to which this condition applies
:returns:
Activity rates for cells corresponding to the hybrid ocean
spreading ridge and oceanic transform condition
'''
# Get normal component
e1h_ridge = np.zeros(np.sum(id0), dtype=float)
e2h_ridge = self.strain.data['e1h'][id0] + self.strain.data['e2h'][id0]
err_ridge = -(e1h_ridge + e2h_ridge)
calculated_rate_ridge = self.continuum_seismicity(
threshold_moment,
e1h_ridge,
e2h_ridge,
err_ridge,
self.regionalisation['OSRnor'])
# Get transform
e1h_trans = self.strain.data['e1h'][id0]
e2h_trans = -e1h_trans
err_trans = np.zeros(np.sum(id0), dtype=float)
calculated_rate_transform = self.continuum_seismicity(
threshold_moment,
e1h_trans,
e2h_trans,
err_trans,
self.regionalisation['OTFmed'])
return (
self.regionalisation['OSRnor']['adjustment_factor'] *
(calculated_rate_ridge + calculated_rate_transform)) | [
"def",
"get_rate_osr_normal_transform",
"(",
"self",
",",
"threshold_moment",
",",
"id0",
")",
":",
"# Get normal component",
"e1h_ridge",
"=",
"np",
".",
"zeros",
"(",
"np",
".",
"sum",
"(",
"id0",
")",
",",
"dtype",
"=",
"float",
")",
"e2h_ridge",
"=",
"self",
".",
"strain",
".",
"data",
"[",
"'e1h'",
"]",
"[",
"id0",
"]",
"+",
"self",
".",
"strain",
".",
"data",
"[",
"'e2h'",
"]",
"[",
"id0",
"]",
"err_ridge",
"=",
"-",
"(",
"e1h_ridge",
"+",
"e2h_ridge",
")",
"calculated_rate_ridge",
"=",
"self",
".",
"continuum_seismicity",
"(",
"threshold_moment",
",",
"e1h_ridge",
",",
"e2h_ridge",
",",
"err_ridge",
",",
"self",
".",
"regionalisation",
"[",
"'OSRnor'",
"]",
")",
"# Get transform",
"e1h_trans",
"=",
"self",
".",
"strain",
".",
"data",
"[",
"'e1h'",
"]",
"[",
"id0",
"]",
"e2h_trans",
"=",
"-",
"e1h_trans",
"err_trans",
"=",
"np",
".",
"zeros",
"(",
"np",
".",
"sum",
"(",
"id0",
")",
",",
"dtype",
"=",
"float",
")",
"calculated_rate_transform",
"=",
"self",
".",
"continuum_seismicity",
"(",
"threshold_moment",
",",
"e1h_trans",
",",
"e2h_trans",
",",
"err_trans",
",",
"self",
".",
"regionalisation",
"[",
"'OTFmed'",
"]",
")",
"return",
"(",
"self",
".",
"regionalisation",
"[",
"'OSRnor'",
"]",
"[",
"'adjustment_factor'",
"]",
"*",
"(",
"calculated_rate_ridge",
"+",
"calculated_rate_transform",
")",
")"
] | Gets seismicity rate for special case of the ridge condition with
spreading and transform component
:param float threshold_moment:
Moment required for calculating activity rate
:param np.ndarray id0:
Logical vector indicating the cells to which this condition applies
:returns:
Activity rates for cells corresponding to the hybrid ocean
spreading ridge and oceanic transform condition | [
"Gets",
"seismicity",
"rate",
"for",
"special",
"case",
"of",
"the",
"ridge",
"condition",
"with",
"spreading",
"and",
"transform",
"component"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/strain/shift.py#L369-L411 | train | 233,428 |
gem/oq-engine | openquake/hmtk/strain/shift.py | Shift.get_rate_osr_convergent_transform | def get_rate_osr_convergent_transform(self, threshold_moment, id0):
'''
Calculates seismicity rate for special case of the ridge condition
with convergence and transform
:param float threshold_moment:
Moment required for calculating activity rate
:param np.ndarray id0:
Logical vector indicating the cells to which this condition applies
:returns:
Activity rates for cells corresponding to the hybrid ocean
convergent boundary and oceanic transform condition
'''
# Get convergent component
e1h_ocb = self.strain.data['e1h'][id0] + self.strain.data['e2h'][id0]
e2h_ocb = np.zeros(np.sum(id0), dtype=float)
err_ocb = -(e1h_ocb + e2h_ocb)
calculated_rate_ocb = self.continuum_seismicity(
threshold_moment,
e1h_ocb,
e2h_ocb,
err_ocb,
self.regionalisation['OCB'])
# Get transform
e2h_trans = self.strain.data['e2h'][id0]
e1h_trans = -e2h_trans
err_trans = np.zeros(np.sum(id0), dtype=float)
calculated_rate_transform = self.continuum_seismicity(
threshold_moment,
e1h_trans,
e2h_trans,
err_trans,
self.regionalisation['OTFmed'])
return (self.regionalisation['OSRnor']['adjustment_factor'] *
(calculated_rate_ocb + calculated_rate_transform)) | python | def get_rate_osr_convergent_transform(self, threshold_moment, id0):
'''
Calculates seismicity rate for special case of the ridge condition
with convergence and transform
:param float threshold_moment:
Moment required for calculating activity rate
:param np.ndarray id0:
Logical vector indicating the cells to which this condition applies
:returns:
Activity rates for cells corresponding to the hybrid ocean
convergent boundary and oceanic transform condition
'''
# Get convergent component
e1h_ocb = self.strain.data['e1h'][id0] + self.strain.data['e2h'][id0]
e2h_ocb = np.zeros(np.sum(id0), dtype=float)
err_ocb = -(e1h_ocb + e2h_ocb)
calculated_rate_ocb = self.continuum_seismicity(
threshold_moment,
e1h_ocb,
e2h_ocb,
err_ocb,
self.regionalisation['OCB'])
# Get transform
e2h_trans = self.strain.data['e2h'][id0]
e1h_trans = -e2h_trans
err_trans = np.zeros(np.sum(id0), dtype=float)
calculated_rate_transform = self.continuum_seismicity(
threshold_moment,
e1h_trans,
e2h_trans,
err_trans,
self.regionalisation['OTFmed'])
return (self.regionalisation['OSRnor']['adjustment_factor'] *
(calculated_rate_ocb + calculated_rate_transform)) | [
"def",
"get_rate_osr_convergent_transform",
"(",
"self",
",",
"threshold_moment",
",",
"id0",
")",
":",
"# Get convergent component",
"e1h_ocb",
"=",
"self",
".",
"strain",
".",
"data",
"[",
"'e1h'",
"]",
"[",
"id0",
"]",
"+",
"self",
".",
"strain",
".",
"data",
"[",
"'e2h'",
"]",
"[",
"id0",
"]",
"e2h_ocb",
"=",
"np",
".",
"zeros",
"(",
"np",
".",
"sum",
"(",
"id0",
")",
",",
"dtype",
"=",
"float",
")",
"err_ocb",
"=",
"-",
"(",
"e1h_ocb",
"+",
"e2h_ocb",
")",
"calculated_rate_ocb",
"=",
"self",
".",
"continuum_seismicity",
"(",
"threshold_moment",
",",
"e1h_ocb",
",",
"e2h_ocb",
",",
"err_ocb",
",",
"self",
".",
"regionalisation",
"[",
"'OCB'",
"]",
")",
"# Get transform",
"e2h_trans",
"=",
"self",
".",
"strain",
".",
"data",
"[",
"'e2h'",
"]",
"[",
"id0",
"]",
"e1h_trans",
"=",
"-",
"e2h_trans",
"err_trans",
"=",
"np",
".",
"zeros",
"(",
"np",
".",
"sum",
"(",
"id0",
")",
",",
"dtype",
"=",
"float",
")",
"calculated_rate_transform",
"=",
"self",
".",
"continuum_seismicity",
"(",
"threshold_moment",
",",
"e1h_trans",
",",
"e2h_trans",
",",
"err_trans",
",",
"self",
".",
"regionalisation",
"[",
"'OTFmed'",
"]",
")",
"return",
"(",
"self",
".",
"regionalisation",
"[",
"'OSRnor'",
"]",
"[",
"'adjustment_factor'",
"]",
"*",
"(",
"calculated_rate_ocb",
"+",
"calculated_rate_transform",
")",
")"
] | Calculates seismicity rate for special case of the ridge condition
with convergence and transform
:param float threshold_moment:
Moment required for calculating activity rate
:param np.ndarray id0:
Logical vector indicating the cells to which this condition applies
:returns:
Activity rates for cells corresponding to the hybrid ocean
convergent boundary and oceanic transform condition | [
"Calculates",
"seismicity",
"rate",
"for",
"special",
"case",
"of",
"the",
"ridge",
"condition",
"with",
"convergence",
"and",
"transform"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/strain/shift.py#L413-L453 | train | 233,429 |
gem/oq-engine | openquake/hazardlib/scalerel/leonard2014.py | Leonard2014_SCR.get_median_area | def get_median_area(self, mag, rake):
"""
Calculates median fault area from magnitude.
"""
if rake is None:
# Return average of strike-slip and dip-slip curves
return power(10.0, (mag - 4.185))
elif (-45 <= rake <= 45) or (rake >= 135) or (rake <= -135):
# strike-slip
return power(10.0, (mag - 4.18))
else:
# Dip-slip (thrust or normal), and undefined rake
return power(10.0, (mag - 4.19)) | python | def get_median_area(self, mag, rake):
"""
Calculates median fault area from magnitude.
"""
if rake is None:
# Return average of strike-slip and dip-slip curves
return power(10.0, (mag - 4.185))
elif (-45 <= rake <= 45) or (rake >= 135) or (rake <= -135):
# strike-slip
return power(10.0, (mag - 4.18))
else:
# Dip-slip (thrust or normal), and undefined rake
return power(10.0, (mag - 4.19)) | [
"def",
"get_median_area",
"(",
"self",
",",
"mag",
",",
"rake",
")",
":",
"if",
"rake",
"is",
"None",
":",
"# Return average of strike-slip and dip-slip curves",
"return",
"power",
"(",
"10.0",
",",
"(",
"mag",
"-",
"4.185",
")",
")",
"elif",
"(",
"-",
"45",
"<=",
"rake",
"<=",
"45",
")",
"or",
"(",
"rake",
">=",
"135",
")",
"or",
"(",
"rake",
"<=",
"-",
"135",
")",
":",
"# strike-slip",
"return",
"power",
"(",
"10.0",
",",
"(",
"mag",
"-",
"4.18",
")",
")",
"else",
":",
"# Dip-slip (thrust or normal), and undefined rake",
"return",
"power",
"(",
"10.0",
",",
"(",
"mag",
"-",
"4.19",
")",
")"
] | Calculates median fault area from magnitude. | [
"Calculates",
"median",
"fault",
"area",
"from",
"magnitude",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/scalerel/leonard2014.py#L36-L48 | train | 233,430 |
gem/oq-engine | openquake/server/views.py | _get_base_url | def _get_base_url(request):
"""
Construct a base URL, given a request object.
This comprises the protocol prefix (http:// or https://) and the host,
which can include the port number. For example:
http://www.openquake.org or https://www.openquake.org:8000.
"""
if request.is_secure():
base_url = 'https://%s'
else:
base_url = 'http://%s'
base_url %= request.META['HTTP_HOST']
return base_url | python | def _get_base_url(request):
"""
Construct a base URL, given a request object.
This comprises the protocol prefix (http:// or https://) and the host,
which can include the port number. For example:
http://www.openquake.org or https://www.openquake.org:8000.
"""
if request.is_secure():
base_url = 'https://%s'
else:
base_url = 'http://%s'
base_url %= request.META['HTTP_HOST']
return base_url | [
"def",
"_get_base_url",
"(",
"request",
")",
":",
"if",
"request",
".",
"is_secure",
"(",
")",
":",
"base_url",
"=",
"'https://%s'",
"else",
":",
"base_url",
"=",
"'http://%s'",
"base_url",
"%=",
"request",
".",
"META",
"[",
"'HTTP_HOST'",
"]",
"return",
"base_url"
] | Construct a base URL, given a request object.
This comprises the protocol prefix (http:// or https://) and the host,
which can include the port number. For example:
http://www.openquake.org or https://www.openquake.org:8000. | [
"Construct",
"a",
"base",
"URL",
"given",
"a",
"request",
"object",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L108-L121 | train | 233,431 |
gem/oq-engine | openquake/server/views.py | _prepare_job | def _prepare_job(request, candidates):
"""
Creates a temporary directory, move uploaded files there and
select the job file by looking at the candidate names.
:returns: full path of the job_file
"""
temp_dir = tempfile.mkdtemp()
inifiles = []
arch = request.FILES.get('archive')
if arch is None:
# move each file to a new temp dir, using the upload file names,
# not the temporary ones
for each_file in request.FILES.values():
new_path = os.path.join(temp_dir, each_file.name)
shutil.move(each_file.temporary_file_path(), new_path)
if each_file.name in candidates:
inifiles.append(new_path)
return inifiles
# else extract the files from the archive into temp_dir
return readinput.extract_from_zip(arch, candidates) | python | def _prepare_job(request, candidates):
"""
Creates a temporary directory, move uploaded files there and
select the job file by looking at the candidate names.
:returns: full path of the job_file
"""
temp_dir = tempfile.mkdtemp()
inifiles = []
arch = request.FILES.get('archive')
if arch is None:
# move each file to a new temp dir, using the upload file names,
# not the temporary ones
for each_file in request.FILES.values():
new_path = os.path.join(temp_dir, each_file.name)
shutil.move(each_file.temporary_file_path(), new_path)
if each_file.name in candidates:
inifiles.append(new_path)
return inifiles
# else extract the files from the archive into temp_dir
return readinput.extract_from_zip(arch, candidates) | [
"def",
"_prepare_job",
"(",
"request",
",",
"candidates",
")",
":",
"temp_dir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"inifiles",
"=",
"[",
"]",
"arch",
"=",
"request",
".",
"FILES",
".",
"get",
"(",
"'archive'",
")",
"if",
"arch",
"is",
"None",
":",
"# move each file to a new temp dir, using the upload file names,",
"# not the temporary ones",
"for",
"each_file",
"in",
"request",
".",
"FILES",
".",
"values",
"(",
")",
":",
"new_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"temp_dir",
",",
"each_file",
".",
"name",
")",
"shutil",
".",
"move",
"(",
"each_file",
".",
"temporary_file_path",
"(",
")",
",",
"new_path",
")",
"if",
"each_file",
".",
"name",
"in",
"candidates",
":",
"inifiles",
".",
"append",
"(",
"new_path",
")",
"return",
"inifiles",
"# else extract the files from the archive into temp_dir",
"return",
"readinput",
".",
"extract_from_zip",
"(",
"arch",
",",
"candidates",
")"
] | Creates a temporary directory, move uploaded files there and
select the job file by looking at the candidate names.
:returns: full path of the job_file | [
"Creates",
"a",
"temporary",
"directory",
"move",
"uploaded",
"files",
"there",
"and",
"select",
"the",
"job",
"file",
"by",
"looking",
"at",
"the",
"candidate",
"names",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L124-L144 | train | 233,432 |
gem/oq-engine | openquake/server/views.py | ajax_login | def ajax_login(request):
"""
Accept a POST request to login.
:param request:
`django.http.HttpRequest` object, containing mandatory parameters
username and password required.
"""
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponse(content='Successful login',
content_type='text/plain', status=200)
else:
return HttpResponse(content='Disabled account',
content_type='text/plain', status=403)
else:
return HttpResponse(content='Invalid login',
content_type='text/plain', status=403) | python | def ajax_login(request):
"""
Accept a POST request to login.
:param request:
`django.http.HttpRequest` object, containing mandatory parameters
username and password required.
"""
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponse(content='Successful login',
content_type='text/plain', status=200)
else:
return HttpResponse(content='Disabled account',
content_type='text/plain', status=403)
else:
return HttpResponse(content='Invalid login',
content_type='text/plain', status=403) | [
"def",
"ajax_login",
"(",
"request",
")",
":",
"username",
"=",
"request",
".",
"POST",
"[",
"'username'",
"]",
"password",
"=",
"request",
".",
"POST",
"[",
"'password'",
"]",
"user",
"=",
"authenticate",
"(",
"username",
"=",
"username",
",",
"password",
"=",
"password",
")",
"if",
"user",
"is",
"not",
"None",
":",
"if",
"user",
".",
"is_active",
":",
"login",
"(",
"request",
",",
"user",
")",
"return",
"HttpResponse",
"(",
"content",
"=",
"'Successful login'",
",",
"content_type",
"=",
"'text/plain'",
",",
"status",
"=",
"200",
")",
"else",
":",
"return",
"HttpResponse",
"(",
"content",
"=",
"'Disabled account'",
",",
"content_type",
"=",
"'text/plain'",
",",
"status",
"=",
"403",
")",
"else",
":",
"return",
"HttpResponse",
"(",
"content",
"=",
"'Invalid login'",
",",
"content_type",
"=",
"'text/plain'",
",",
"status",
"=",
"403",
")"
] | Accept a POST request to login.
:param request:
`django.http.HttpRequest` object, containing mandatory parameters
username and password required. | [
"Accept",
"a",
"POST",
"request",
"to",
"login",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L150-L171 | train | 233,433 |
gem/oq-engine | openquake/server/views.py | get_available_gsims | def get_available_gsims(request):
"""
Return a list of strings with the available GSIMs
"""
gsims = list(gsim.get_available_gsims())
return HttpResponse(content=json.dumps(gsims), content_type=JSON) | python | def get_available_gsims(request):
"""
Return a list of strings with the available GSIMs
"""
gsims = list(gsim.get_available_gsims())
return HttpResponse(content=json.dumps(gsims), content_type=JSON) | [
"def",
"get_available_gsims",
"(",
"request",
")",
":",
"gsims",
"=",
"list",
"(",
"gsim",
".",
"get_available_gsims",
"(",
")",
")",
"return",
"HttpResponse",
"(",
"content",
"=",
"json",
".",
"dumps",
"(",
"gsims",
")",
",",
"content_type",
"=",
"JSON",
")"
] | Return a list of strings with the available GSIMs | [
"Return",
"a",
"list",
"of",
"strings",
"with",
"the",
"available",
"GSIMs"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L207-L212 | train | 233,434 |
gem/oq-engine | openquake/server/views.py | validate_nrml | def validate_nrml(request):
"""
Leverage oq-risklib to check if a given XML text is a valid NRML
:param request:
a `django.http.HttpRequest` object containing the mandatory
parameter 'xml_text': the text of the XML to be validated as NRML
:returns: a JSON object, containing:
* 'valid': a boolean indicating if the provided text is a valid NRML
* 'error_msg': the error message, if any error was found
(None otherwise)
* 'error_line': line of the given XML where the error was found
(None if no error was found or if it was not a
validation error)
"""
xml_text = request.POST.get('xml_text')
if not xml_text:
return HttpResponseBadRequest(
'Please provide the "xml_text" parameter')
xml_file = gettemp(xml_text, suffix='.xml')
try:
nrml.to_python(xml_file)
except ExpatError as exc:
return _make_response(error_msg=str(exc),
error_line=exc.lineno,
valid=False)
except Exception as exc:
# get the exception message
exc_msg = exc.args[0]
if isinstance(exc_msg, bytes):
exc_msg = exc_msg.decode('utf-8') # make it a unicode object
elif isinstance(exc_msg, str):
pass
else:
# if it is another kind of object, it is not obvious a priori how
# to extract the error line from it
return _make_response(
error_msg=str(exc_msg), error_line=None, valid=False)
# if the line is not mentioned, the whole message is taken
error_msg = exc_msg.split(', line')[0]
# check if the exc_msg contains a line number indication
search_match = re.search(r'line \d+', exc_msg)
if search_match:
error_line = int(search_match.group(0).split()[1])
else:
error_line = None
return _make_response(
error_msg=error_msg, error_line=error_line, valid=False)
else:
return _make_response(error_msg=None, error_line=None, valid=True) | python | def validate_nrml(request):
"""
Leverage oq-risklib to check if a given XML text is a valid NRML
:param request:
a `django.http.HttpRequest` object containing the mandatory
parameter 'xml_text': the text of the XML to be validated as NRML
:returns: a JSON object, containing:
* 'valid': a boolean indicating if the provided text is a valid NRML
* 'error_msg': the error message, if any error was found
(None otherwise)
* 'error_line': line of the given XML where the error was found
(None if no error was found or if it was not a
validation error)
"""
xml_text = request.POST.get('xml_text')
if not xml_text:
return HttpResponseBadRequest(
'Please provide the "xml_text" parameter')
xml_file = gettemp(xml_text, suffix='.xml')
try:
nrml.to_python(xml_file)
except ExpatError as exc:
return _make_response(error_msg=str(exc),
error_line=exc.lineno,
valid=False)
except Exception as exc:
# get the exception message
exc_msg = exc.args[0]
if isinstance(exc_msg, bytes):
exc_msg = exc_msg.decode('utf-8') # make it a unicode object
elif isinstance(exc_msg, str):
pass
else:
# if it is another kind of object, it is not obvious a priori how
# to extract the error line from it
return _make_response(
error_msg=str(exc_msg), error_line=None, valid=False)
# if the line is not mentioned, the whole message is taken
error_msg = exc_msg.split(', line')[0]
# check if the exc_msg contains a line number indication
search_match = re.search(r'line \d+', exc_msg)
if search_match:
error_line = int(search_match.group(0).split()[1])
else:
error_line = None
return _make_response(
error_msg=error_msg, error_line=error_line, valid=False)
else:
return _make_response(error_msg=None, error_line=None, valid=True) | [
"def",
"validate_nrml",
"(",
"request",
")",
":",
"xml_text",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'xml_text'",
")",
"if",
"not",
"xml_text",
":",
"return",
"HttpResponseBadRequest",
"(",
"'Please provide the \"xml_text\" parameter'",
")",
"xml_file",
"=",
"gettemp",
"(",
"xml_text",
",",
"suffix",
"=",
"'.xml'",
")",
"try",
":",
"nrml",
".",
"to_python",
"(",
"xml_file",
")",
"except",
"ExpatError",
"as",
"exc",
":",
"return",
"_make_response",
"(",
"error_msg",
"=",
"str",
"(",
"exc",
")",
",",
"error_line",
"=",
"exc",
".",
"lineno",
",",
"valid",
"=",
"False",
")",
"except",
"Exception",
"as",
"exc",
":",
"# get the exception message",
"exc_msg",
"=",
"exc",
".",
"args",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"exc_msg",
",",
"bytes",
")",
":",
"exc_msg",
"=",
"exc_msg",
".",
"decode",
"(",
"'utf-8'",
")",
"# make it a unicode object",
"elif",
"isinstance",
"(",
"exc_msg",
",",
"str",
")",
":",
"pass",
"else",
":",
"# if it is another kind of object, it is not obvious a priori how",
"# to extract the error line from it",
"return",
"_make_response",
"(",
"error_msg",
"=",
"str",
"(",
"exc_msg",
")",
",",
"error_line",
"=",
"None",
",",
"valid",
"=",
"False",
")",
"# if the line is not mentioned, the whole message is taken",
"error_msg",
"=",
"exc_msg",
".",
"split",
"(",
"', line'",
")",
"[",
"0",
"]",
"# check if the exc_msg contains a line number indication",
"search_match",
"=",
"re",
".",
"search",
"(",
"r'line \\d+'",
",",
"exc_msg",
")",
"if",
"search_match",
":",
"error_line",
"=",
"int",
"(",
"search_match",
".",
"group",
"(",
"0",
")",
".",
"split",
"(",
")",
"[",
"1",
"]",
")",
"else",
":",
"error_line",
"=",
"None",
"return",
"_make_response",
"(",
"error_msg",
"=",
"error_msg",
",",
"error_line",
"=",
"error_line",
",",
"valid",
"=",
"False",
")",
"else",
":",
"return",
"_make_response",
"(",
"error_msg",
"=",
"None",
",",
"error_line",
"=",
"None",
",",
"valid",
"=",
"True",
")"
] | Leverage oq-risklib to check if a given XML text is a valid NRML
:param request:
a `django.http.HttpRequest` object containing the mandatory
parameter 'xml_text': the text of the XML to be validated as NRML
:returns: a JSON object, containing:
* 'valid': a boolean indicating if the provided text is a valid NRML
* 'error_msg': the error message, if any error was found
(None otherwise)
* 'error_line': line of the given XML where the error was found
(None if no error was found or if it was not a
validation error) | [
"Leverage",
"oq",
"-",
"risklib",
"to",
"check",
"if",
"a",
"given",
"XML",
"text",
"is",
"a",
"valid",
"NRML"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L226-L276 | train | 233,435 |
gem/oq-engine | openquake/server/views.py | calc_list | def calc_list(request, id=None):
# view associated to the endpoints /v1/calc/list and /v1/calc/:id/status
"""
Get a list of calculations and report their id, status, calculation_mode,
is_running, description, and a url where more detailed information
can be accessed. This is called several times by the Javascript.
Responses are in JSON.
"""
base_url = _get_base_url(request)
calc_data = logs.dbcmd('get_calcs', request.GET,
utils.get_valid_users(request),
utils.get_acl_on(request), id)
response_data = []
username = psutil.Process(os.getpid()).username()
for (hc_id, owner, status, calculation_mode, is_running, desc, pid,
parent_id, size_mb) in calc_data:
url = urlparse.urljoin(base_url, 'v1/calc/%d' % hc_id)
abortable = False
if is_running:
try:
if psutil.Process(pid).username() == username:
abortable = True
except psutil.NoSuchProcess:
pass
response_data.append(
dict(id=hc_id, owner=owner,
calculation_mode=calculation_mode, status=status,
is_running=bool(is_running), description=desc, url=url,
parent_id=parent_id, abortable=abortable, size_mb=size_mb))
# if id is specified the related dictionary is returned instead the list
if id is not None:
[response_data] = response_data
return HttpResponse(content=json.dumps(response_data),
content_type=JSON) | python | def calc_list(request, id=None):
# view associated to the endpoints /v1/calc/list and /v1/calc/:id/status
"""
Get a list of calculations and report their id, status, calculation_mode,
is_running, description, and a url where more detailed information
can be accessed. This is called several times by the Javascript.
Responses are in JSON.
"""
base_url = _get_base_url(request)
calc_data = logs.dbcmd('get_calcs', request.GET,
utils.get_valid_users(request),
utils.get_acl_on(request), id)
response_data = []
username = psutil.Process(os.getpid()).username()
for (hc_id, owner, status, calculation_mode, is_running, desc, pid,
parent_id, size_mb) in calc_data:
url = urlparse.urljoin(base_url, 'v1/calc/%d' % hc_id)
abortable = False
if is_running:
try:
if psutil.Process(pid).username() == username:
abortable = True
except psutil.NoSuchProcess:
pass
response_data.append(
dict(id=hc_id, owner=owner,
calculation_mode=calculation_mode, status=status,
is_running=bool(is_running), description=desc, url=url,
parent_id=parent_id, abortable=abortable, size_mb=size_mb))
# if id is specified the related dictionary is returned instead the list
if id is not None:
[response_data] = response_data
return HttpResponse(content=json.dumps(response_data),
content_type=JSON) | [
"def",
"calc_list",
"(",
"request",
",",
"id",
"=",
"None",
")",
":",
"# view associated to the endpoints /v1/calc/list and /v1/calc/:id/status",
"base_url",
"=",
"_get_base_url",
"(",
"request",
")",
"calc_data",
"=",
"logs",
".",
"dbcmd",
"(",
"'get_calcs'",
",",
"request",
".",
"GET",
",",
"utils",
".",
"get_valid_users",
"(",
"request",
")",
",",
"utils",
".",
"get_acl_on",
"(",
"request",
")",
",",
"id",
")",
"response_data",
"=",
"[",
"]",
"username",
"=",
"psutil",
".",
"Process",
"(",
"os",
".",
"getpid",
"(",
")",
")",
".",
"username",
"(",
")",
"for",
"(",
"hc_id",
",",
"owner",
",",
"status",
",",
"calculation_mode",
",",
"is_running",
",",
"desc",
",",
"pid",
",",
"parent_id",
",",
"size_mb",
")",
"in",
"calc_data",
":",
"url",
"=",
"urlparse",
".",
"urljoin",
"(",
"base_url",
",",
"'v1/calc/%d'",
"%",
"hc_id",
")",
"abortable",
"=",
"False",
"if",
"is_running",
":",
"try",
":",
"if",
"psutil",
".",
"Process",
"(",
"pid",
")",
".",
"username",
"(",
")",
"==",
"username",
":",
"abortable",
"=",
"True",
"except",
"psutil",
".",
"NoSuchProcess",
":",
"pass",
"response_data",
".",
"append",
"(",
"dict",
"(",
"id",
"=",
"hc_id",
",",
"owner",
"=",
"owner",
",",
"calculation_mode",
"=",
"calculation_mode",
",",
"status",
"=",
"status",
",",
"is_running",
"=",
"bool",
"(",
"is_running",
")",
",",
"description",
"=",
"desc",
",",
"url",
"=",
"url",
",",
"parent_id",
"=",
"parent_id",
",",
"abortable",
"=",
"abortable",
",",
"size_mb",
"=",
"size_mb",
")",
")",
"# if id is specified the related dictionary is returned instead the list",
"if",
"id",
"is",
"not",
"None",
":",
"[",
"response_data",
"]",
"=",
"response_data",
"return",
"HttpResponse",
"(",
"content",
"=",
"json",
".",
"dumps",
"(",
"response_data",
")",
",",
"content_type",
"=",
"JSON",
")"
] | Get a list of calculations and report their id, status, calculation_mode,
is_running, description, and a url where more detailed information
can be accessed. This is called several times by the Javascript.
Responses are in JSON. | [
"Get",
"a",
"list",
"of",
"calculations",
"and",
"report",
"their",
"id",
"status",
"calculation_mode",
"is_running",
"description",
"and",
"a",
"url",
"where",
"more",
"detailed",
"information",
"can",
"be",
"accessed",
".",
"This",
"is",
"called",
"several",
"times",
"by",
"the",
"Javascript",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L298-L335 | train | 233,436 |
gem/oq-engine | openquake/server/views.py | calc_abort | def calc_abort(request, calc_id):
"""
Abort the given calculation, it is it running
"""
job = logs.dbcmd('get_job', calc_id)
if job is None:
message = {'error': 'Unknown job %s' % calc_id}
return HttpResponse(content=json.dumps(message), content_type=JSON)
if job.status not in ('submitted', 'executing'):
message = {'error': 'Job %s is not running' % job.id}
return HttpResponse(content=json.dumps(message), content_type=JSON)
if not utils.user_has_permission(request, job.user_name):
message = {'error': ('User %s has no permission to abort job %s' %
(job.user_name, job.id))}
return HttpResponse(content=json.dumps(message), content_type=JSON,
status=403)
if job.pid: # is a spawned job
try:
os.kill(job.pid, signal.SIGTERM)
except Exception as exc:
logging.error(exc)
else:
logging.warning('Aborting job %d, pid=%d', job.id, job.pid)
logs.dbcmd('set_status', job.id, 'aborted')
message = {'success': 'Killing job %d' % job.id}
return HttpResponse(content=json.dumps(message), content_type=JSON)
message = {'error': 'PID for job %s not found' % job.id}
return HttpResponse(content=json.dumps(message), content_type=JSON) | python | def calc_abort(request, calc_id):
"""
Abort the given calculation, it is it running
"""
job = logs.dbcmd('get_job', calc_id)
if job is None:
message = {'error': 'Unknown job %s' % calc_id}
return HttpResponse(content=json.dumps(message), content_type=JSON)
if job.status not in ('submitted', 'executing'):
message = {'error': 'Job %s is not running' % job.id}
return HttpResponse(content=json.dumps(message), content_type=JSON)
if not utils.user_has_permission(request, job.user_name):
message = {'error': ('User %s has no permission to abort job %s' %
(job.user_name, job.id))}
return HttpResponse(content=json.dumps(message), content_type=JSON,
status=403)
if job.pid: # is a spawned job
try:
os.kill(job.pid, signal.SIGTERM)
except Exception as exc:
logging.error(exc)
else:
logging.warning('Aborting job %d, pid=%d', job.id, job.pid)
logs.dbcmd('set_status', job.id, 'aborted')
message = {'success': 'Killing job %d' % job.id}
return HttpResponse(content=json.dumps(message), content_type=JSON)
message = {'error': 'PID for job %s not found' % job.id}
return HttpResponse(content=json.dumps(message), content_type=JSON) | [
"def",
"calc_abort",
"(",
"request",
",",
"calc_id",
")",
":",
"job",
"=",
"logs",
".",
"dbcmd",
"(",
"'get_job'",
",",
"calc_id",
")",
"if",
"job",
"is",
"None",
":",
"message",
"=",
"{",
"'error'",
":",
"'Unknown job %s'",
"%",
"calc_id",
"}",
"return",
"HttpResponse",
"(",
"content",
"=",
"json",
".",
"dumps",
"(",
"message",
")",
",",
"content_type",
"=",
"JSON",
")",
"if",
"job",
".",
"status",
"not",
"in",
"(",
"'submitted'",
",",
"'executing'",
")",
":",
"message",
"=",
"{",
"'error'",
":",
"'Job %s is not running'",
"%",
"job",
".",
"id",
"}",
"return",
"HttpResponse",
"(",
"content",
"=",
"json",
".",
"dumps",
"(",
"message",
")",
",",
"content_type",
"=",
"JSON",
")",
"if",
"not",
"utils",
".",
"user_has_permission",
"(",
"request",
",",
"job",
".",
"user_name",
")",
":",
"message",
"=",
"{",
"'error'",
":",
"(",
"'User %s has no permission to abort job %s'",
"%",
"(",
"job",
".",
"user_name",
",",
"job",
".",
"id",
")",
")",
"}",
"return",
"HttpResponse",
"(",
"content",
"=",
"json",
".",
"dumps",
"(",
"message",
")",
",",
"content_type",
"=",
"JSON",
",",
"status",
"=",
"403",
")",
"if",
"job",
".",
"pid",
":",
"# is a spawned job",
"try",
":",
"os",
".",
"kill",
"(",
"job",
".",
"pid",
",",
"signal",
".",
"SIGTERM",
")",
"except",
"Exception",
"as",
"exc",
":",
"logging",
".",
"error",
"(",
"exc",
")",
"else",
":",
"logging",
".",
"warning",
"(",
"'Aborting job %d, pid=%d'",
",",
"job",
".",
"id",
",",
"job",
".",
"pid",
")",
"logs",
".",
"dbcmd",
"(",
"'set_status'",
",",
"job",
".",
"id",
",",
"'aborted'",
")",
"message",
"=",
"{",
"'success'",
":",
"'Killing job %d'",
"%",
"job",
".",
"id",
"}",
"return",
"HttpResponse",
"(",
"content",
"=",
"json",
".",
"dumps",
"(",
"message",
")",
",",
"content_type",
"=",
"JSON",
")",
"message",
"=",
"{",
"'error'",
":",
"'PID for job %s not found'",
"%",
"job",
".",
"id",
"}",
"return",
"HttpResponse",
"(",
"content",
"=",
"json",
".",
"dumps",
"(",
"message",
")",
",",
"content_type",
"=",
"JSON",
")"
] | Abort the given calculation, it is it running | [
"Abort",
"the",
"given",
"calculation",
"it",
"is",
"it",
"running"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L341-L372 | train | 233,437 |
gem/oq-engine | openquake/server/views.py | calc_remove | def calc_remove(request, calc_id):
"""
Remove the calculation id
"""
# Only the owner can remove a job
user = utils.get_user(request)
try:
message = logs.dbcmd('del_calc', calc_id, user)
except dbapi.NotFound:
return HttpResponseNotFound()
if 'success' in message:
return HttpResponse(content=json.dumps(message),
content_type=JSON, status=200)
elif 'error' in message:
logging.error(message['error'])
return HttpResponse(content=json.dumps(message),
content_type=JSON, status=403)
else:
# This is an untrapped server error
logging.error(message)
return HttpResponse(content=message,
content_type='text/plain', status=500) | python | def calc_remove(request, calc_id):
"""
Remove the calculation id
"""
# Only the owner can remove a job
user = utils.get_user(request)
try:
message = logs.dbcmd('del_calc', calc_id, user)
except dbapi.NotFound:
return HttpResponseNotFound()
if 'success' in message:
return HttpResponse(content=json.dumps(message),
content_type=JSON, status=200)
elif 'error' in message:
logging.error(message['error'])
return HttpResponse(content=json.dumps(message),
content_type=JSON, status=403)
else:
# This is an untrapped server error
logging.error(message)
return HttpResponse(content=message,
content_type='text/plain', status=500) | [
"def",
"calc_remove",
"(",
"request",
",",
"calc_id",
")",
":",
"# Only the owner can remove a job",
"user",
"=",
"utils",
".",
"get_user",
"(",
"request",
")",
"try",
":",
"message",
"=",
"logs",
".",
"dbcmd",
"(",
"'del_calc'",
",",
"calc_id",
",",
"user",
")",
"except",
"dbapi",
".",
"NotFound",
":",
"return",
"HttpResponseNotFound",
"(",
")",
"if",
"'success'",
"in",
"message",
":",
"return",
"HttpResponse",
"(",
"content",
"=",
"json",
".",
"dumps",
"(",
"message",
")",
",",
"content_type",
"=",
"JSON",
",",
"status",
"=",
"200",
")",
"elif",
"'error'",
"in",
"message",
":",
"logging",
".",
"error",
"(",
"message",
"[",
"'error'",
"]",
")",
"return",
"HttpResponse",
"(",
"content",
"=",
"json",
".",
"dumps",
"(",
"message",
")",
",",
"content_type",
"=",
"JSON",
",",
"status",
"=",
"403",
")",
"else",
":",
"# This is an untrapped server error",
"logging",
".",
"error",
"(",
"message",
")",
"return",
"HttpResponse",
"(",
"content",
"=",
"message",
",",
"content_type",
"=",
"'text/plain'",
",",
"status",
"=",
"500",
")"
] | Remove the calculation id | [
"Remove",
"the",
"calculation",
"id"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L378-L400 | train | 233,438 |
gem/oq-engine | openquake/server/views.py | log_to_json | def log_to_json(log):
"""Convert a log record into a list of strings"""
return [log.timestamp.isoformat()[:22],
log.level, log.process, log.message] | python | def log_to_json(log):
"""Convert a log record into a list of strings"""
return [log.timestamp.isoformat()[:22],
log.level, log.process, log.message] | [
"def",
"log_to_json",
"(",
"log",
")",
":",
"return",
"[",
"log",
".",
"timestamp",
".",
"isoformat",
"(",
")",
"[",
":",
"22",
"]",
",",
"log",
".",
"level",
",",
"log",
".",
"process",
",",
"log",
".",
"message",
"]"
] | Convert a log record into a list of strings | [
"Convert",
"a",
"log",
"record",
"into",
"a",
"list",
"of",
"strings"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L403-L406 | train | 233,439 |
gem/oq-engine | openquake/server/views.py | calc_log_size | def calc_log_size(request, calc_id):
"""
Get the current number of lines in the log
"""
try:
response_data = logs.dbcmd('get_log_size', calc_id)
except dbapi.NotFound:
return HttpResponseNotFound()
return HttpResponse(content=json.dumps(response_data), content_type=JSON) | python | def calc_log_size(request, calc_id):
"""
Get the current number of lines in the log
"""
try:
response_data = logs.dbcmd('get_log_size', calc_id)
except dbapi.NotFound:
return HttpResponseNotFound()
return HttpResponse(content=json.dumps(response_data), content_type=JSON) | [
"def",
"calc_log_size",
"(",
"request",
",",
"calc_id",
")",
":",
"try",
":",
"response_data",
"=",
"logs",
".",
"dbcmd",
"(",
"'get_log_size'",
",",
"calc_id",
")",
"except",
"dbapi",
".",
"NotFound",
":",
"return",
"HttpResponseNotFound",
"(",
")",
"return",
"HttpResponse",
"(",
"content",
"=",
"json",
".",
"dumps",
"(",
"response_data",
")",
",",
"content_type",
"=",
"JSON",
")"
] | Get the current number of lines in the log | [
"Get",
"the",
"current",
"number",
"of",
"lines",
"in",
"the",
"log"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L426-L434 | train | 233,440 |
gem/oq-engine | openquake/server/views.py | submit_job | def submit_job(job_ini, username, hazard_job_id=None):
"""
Create a job object from the given job.ini file in the job directory
and run it in a new process. Returns the job ID and PID.
"""
job_id = logs.init('job')
oq = engine.job_from_file(
job_ini, job_id, username, hazard_calculation_id=hazard_job_id)
pik = pickle.dumps(oq, protocol=0) # human readable protocol
code = RUNCALC % dict(job_id=job_id, hazard_job_id=hazard_job_id, pik=pik,
username=username)
tmp_py = gettemp(code, suffix='.py')
# print(code, tmp_py) # useful when debugging
devnull = subprocess.DEVNULL
popen = subprocess.Popen([sys.executable, tmp_py],
stdin=devnull, stdout=devnull, stderr=devnull)
threading.Thread(target=popen.wait).start()
logs.dbcmd('update_job', job_id, {'pid': popen.pid})
return job_id, popen.pid | python | def submit_job(job_ini, username, hazard_job_id=None):
"""
Create a job object from the given job.ini file in the job directory
and run it in a new process. Returns the job ID and PID.
"""
job_id = logs.init('job')
oq = engine.job_from_file(
job_ini, job_id, username, hazard_calculation_id=hazard_job_id)
pik = pickle.dumps(oq, protocol=0) # human readable protocol
code = RUNCALC % dict(job_id=job_id, hazard_job_id=hazard_job_id, pik=pik,
username=username)
tmp_py = gettemp(code, suffix='.py')
# print(code, tmp_py) # useful when debugging
devnull = subprocess.DEVNULL
popen = subprocess.Popen([sys.executable, tmp_py],
stdin=devnull, stdout=devnull, stderr=devnull)
threading.Thread(target=popen.wait).start()
logs.dbcmd('update_job', job_id, {'pid': popen.pid})
return job_id, popen.pid | [
"def",
"submit_job",
"(",
"job_ini",
",",
"username",
",",
"hazard_job_id",
"=",
"None",
")",
":",
"job_id",
"=",
"logs",
".",
"init",
"(",
"'job'",
")",
"oq",
"=",
"engine",
".",
"job_from_file",
"(",
"job_ini",
",",
"job_id",
",",
"username",
",",
"hazard_calculation_id",
"=",
"hazard_job_id",
")",
"pik",
"=",
"pickle",
".",
"dumps",
"(",
"oq",
",",
"protocol",
"=",
"0",
")",
"# human readable protocol",
"code",
"=",
"RUNCALC",
"%",
"dict",
"(",
"job_id",
"=",
"job_id",
",",
"hazard_job_id",
"=",
"hazard_job_id",
",",
"pik",
"=",
"pik",
",",
"username",
"=",
"username",
")",
"tmp_py",
"=",
"gettemp",
"(",
"code",
",",
"suffix",
"=",
"'.py'",
")",
"# print(code, tmp_py) # useful when debugging",
"devnull",
"=",
"subprocess",
".",
"DEVNULL",
"popen",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"sys",
".",
"executable",
",",
"tmp_py",
"]",
",",
"stdin",
"=",
"devnull",
",",
"stdout",
"=",
"devnull",
",",
"stderr",
"=",
"devnull",
")",
"threading",
".",
"Thread",
"(",
"target",
"=",
"popen",
".",
"wait",
")",
".",
"start",
"(",
")",
"logs",
".",
"dbcmd",
"(",
"'update_job'",
",",
"job_id",
",",
"{",
"'pid'",
":",
"popen",
".",
"pid",
"}",
")",
"return",
"job_id",
",",
"popen",
".",
"pid"
] | Create a job object from the given job.ini file in the job directory
and run it in a new process. Returns the job ID and PID. | [
"Create",
"a",
"job",
"object",
"from",
"the",
"given",
"job",
".",
"ini",
"file",
"in",
"the",
"job",
"directory",
"and",
"run",
"it",
"in",
"a",
"new",
"process",
".",
"Returns",
"the",
"job",
"ID",
"and",
"PID",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L502-L520 | train | 233,441 |
gem/oq-engine | openquake/server/views.py | calc_result | def calc_result(request, result_id):
"""
Download a specific result, by ``result_id``.
The common abstracted functionality for getting hazard or risk results.
:param request:
`django.http.HttpRequest` object. Can contain a `export_type` GET
param (the default is 'xml' if no param is specified).
:param result_id:
The id of the requested artifact.
:returns:
If the requested ``result_id`` is not available in the format
designated by the `export_type`.
Otherwise, return a `django.http.HttpResponse` containing the content
of the requested artifact.
Parameters for the GET request can include an `export_type`, such as 'xml',
'geojson', 'csv', etc.
"""
# If the result for the requested ID doesn't exist, OR
# the job which it is related too is not complete,
# throw back a 404.
try:
job_id, job_status, job_user, datadir, ds_key = logs.dbcmd(
'get_result', result_id)
if not utils.user_has_permission(request, job_user):
return HttpResponseForbidden()
except dbapi.NotFound:
return HttpResponseNotFound()
etype = request.GET.get('export_type')
export_type = etype or DEFAULT_EXPORT_TYPE
tmpdir = tempfile.mkdtemp()
try:
exported = core.export_from_db(
(ds_key, export_type), job_id, datadir, tmpdir)
except DataStoreExportError as exc:
# TODO: there should be a better error page
return HttpResponse(content='%s: %s' % (exc.__class__.__name__, exc),
content_type='text/plain', status=500)
if not exported:
# Throw back a 404 if the exact export parameters are not supported
return HttpResponseNotFound(
'Nothing to export for export_type=%s, %s' % (export_type, ds_key))
elif len(exported) > 1:
# Building an archive so that there can be a single file download
archname = ds_key + '-' + export_type + '.zip'
zipfiles(exported, os.path.join(tmpdir, archname))
exported = os.path.join(tmpdir, archname)
else: # single file
exported = exported[0]
content_type = EXPORT_CONTENT_TYPE_MAP.get(
export_type, DEFAULT_CONTENT_TYPE)
fname = 'output-%s-%s' % (result_id, os.path.basename(exported))
stream = FileWrapper(open(exported, 'rb')) # 'b' is needed on Windows
stream.close = lambda: (
FileWrapper.close(stream), shutil.rmtree(tmpdir))
response = FileResponse(stream, content_type=content_type)
response['Content-Disposition'] = (
'attachment; filename=%s' % os.path.basename(fname))
response['Content-Length'] = str(os.path.getsize(exported))
return response | python | def calc_result(request, result_id):
"""
Download a specific result, by ``result_id``.
The common abstracted functionality for getting hazard or risk results.
:param request:
`django.http.HttpRequest` object. Can contain a `export_type` GET
param (the default is 'xml' if no param is specified).
:param result_id:
The id of the requested artifact.
:returns:
If the requested ``result_id`` is not available in the format
designated by the `export_type`.
Otherwise, return a `django.http.HttpResponse` containing the content
of the requested artifact.
Parameters for the GET request can include an `export_type`, such as 'xml',
'geojson', 'csv', etc.
"""
# If the result for the requested ID doesn't exist, OR
# the job which it is related too is not complete,
# throw back a 404.
try:
job_id, job_status, job_user, datadir, ds_key = logs.dbcmd(
'get_result', result_id)
if not utils.user_has_permission(request, job_user):
return HttpResponseForbidden()
except dbapi.NotFound:
return HttpResponseNotFound()
etype = request.GET.get('export_type')
export_type = etype or DEFAULT_EXPORT_TYPE
tmpdir = tempfile.mkdtemp()
try:
exported = core.export_from_db(
(ds_key, export_type), job_id, datadir, tmpdir)
except DataStoreExportError as exc:
# TODO: there should be a better error page
return HttpResponse(content='%s: %s' % (exc.__class__.__name__, exc),
content_type='text/plain', status=500)
if not exported:
# Throw back a 404 if the exact export parameters are not supported
return HttpResponseNotFound(
'Nothing to export for export_type=%s, %s' % (export_type, ds_key))
elif len(exported) > 1:
# Building an archive so that there can be a single file download
archname = ds_key + '-' + export_type + '.zip'
zipfiles(exported, os.path.join(tmpdir, archname))
exported = os.path.join(tmpdir, archname)
else: # single file
exported = exported[0]
content_type = EXPORT_CONTENT_TYPE_MAP.get(
export_type, DEFAULT_CONTENT_TYPE)
fname = 'output-%s-%s' % (result_id, os.path.basename(exported))
stream = FileWrapper(open(exported, 'rb')) # 'b' is needed on Windows
stream.close = lambda: (
FileWrapper.close(stream), shutil.rmtree(tmpdir))
response = FileResponse(stream, content_type=content_type)
response['Content-Disposition'] = (
'attachment; filename=%s' % os.path.basename(fname))
response['Content-Length'] = str(os.path.getsize(exported))
return response | [
"def",
"calc_result",
"(",
"request",
",",
"result_id",
")",
":",
"# If the result for the requested ID doesn't exist, OR",
"# the job which it is related too is not complete,",
"# throw back a 404.",
"try",
":",
"job_id",
",",
"job_status",
",",
"job_user",
",",
"datadir",
",",
"ds_key",
"=",
"logs",
".",
"dbcmd",
"(",
"'get_result'",
",",
"result_id",
")",
"if",
"not",
"utils",
".",
"user_has_permission",
"(",
"request",
",",
"job_user",
")",
":",
"return",
"HttpResponseForbidden",
"(",
")",
"except",
"dbapi",
".",
"NotFound",
":",
"return",
"HttpResponseNotFound",
"(",
")",
"etype",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'export_type'",
")",
"export_type",
"=",
"etype",
"or",
"DEFAULT_EXPORT_TYPE",
"tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"try",
":",
"exported",
"=",
"core",
".",
"export_from_db",
"(",
"(",
"ds_key",
",",
"export_type",
")",
",",
"job_id",
",",
"datadir",
",",
"tmpdir",
")",
"except",
"DataStoreExportError",
"as",
"exc",
":",
"# TODO: there should be a better error page",
"return",
"HttpResponse",
"(",
"content",
"=",
"'%s: %s'",
"%",
"(",
"exc",
".",
"__class__",
".",
"__name__",
",",
"exc",
")",
",",
"content_type",
"=",
"'text/plain'",
",",
"status",
"=",
"500",
")",
"if",
"not",
"exported",
":",
"# Throw back a 404 if the exact export parameters are not supported",
"return",
"HttpResponseNotFound",
"(",
"'Nothing to export for export_type=%s, %s'",
"%",
"(",
"export_type",
",",
"ds_key",
")",
")",
"elif",
"len",
"(",
"exported",
")",
">",
"1",
":",
"# Building an archive so that there can be a single file download",
"archname",
"=",
"ds_key",
"+",
"'-'",
"+",
"export_type",
"+",
"'.zip'",
"zipfiles",
"(",
"exported",
",",
"os",
".",
"path",
".",
"join",
"(",
"tmpdir",
",",
"archname",
")",
")",
"exported",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmpdir",
",",
"archname",
")",
"else",
":",
"# single file",
"exported",
"=",
"exported",
"[",
"0",
"]",
"content_type",
"=",
"EXPORT_CONTENT_TYPE_MAP",
".",
"get",
"(",
"export_type",
",",
"DEFAULT_CONTENT_TYPE",
")",
"fname",
"=",
"'output-%s-%s'",
"%",
"(",
"result_id",
",",
"os",
".",
"path",
".",
"basename",
"(",
"exported",
")",
")",
"stream",
"=",
"FileWrapper",
"(",
"open",
"(",
"exported",
",",
"'rb'",
")",
")",
"# 'b' is needed on Windows",
"stream",
".",
"close",
"=",
"lambda",
":",
"(",
"FileWrapper",
".",
"close",
"(",
"stream",
")",
",",
"shutil",
".",
"rmtree",
"(",
"tmpdir",
")",
")",
"response",
"=",
"FileResponse",
"(",
"stream",
",",
"content_type",
"=",
"content_type",
")",
"response",
"[",
"'Content-Disposition'",
"]",
"=",
"(",
"'attachment; filename=%s'",
"%",
"os",
".",
"path",
".",
"basename",
"(",
"fname",
")",
")",
"response",
"[",
"'Content-Length'",
"]",
"=",
"str",
"(",
"os",
".",
"path",
".",
"getsize",
"(",
"exported",
")",
")",
"return",
"response"
] | Download a specific result, by ``result_id``.
The common abstracted functionality for getting hazard or risk results.
:param request:
`django.http.HttpRequest` object. Can contain a `export_type` GET
param (the default is 'xml' if no param is specified).
:param result_id:
The id of the requested artifact.
:returns:
If the requested ``result_id`` is not available in the format
designated by the `export_type`.
Otherwise, return a `django.http.HttpResponse` containing the content
of the requested artifact.
Parameters for the GET request can include an `export_type`, such as 'xml',
'geojson', 'csv', etc. | [
"Download",
"a",
"specific",
"result",
"by",
"result_id",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L587-L653 | train | 233,442 |
gem/oq-engine | openquake/server/views.py | extract | def extract(request, calc_id, what):
"""
Wrapper over the `oq extract` command. If `setting.LOCKDOWN` is true
only calculations owned by the current user can be retrieved.
"""
job = logs.dbcmd('get_job', int(calc_id))
if job is None:
return HttpResponseNotFound()
if not utils.user_has_permission(request, job.user_name):
return HttpResponseForbidden()
try:
# read the data and save them on a temporary .npz file
with datastore.read(job.ds_calc_dir + '.hdf5') as ds:
fd, fname = tempfile.mkstemp(
prefix=what.replace('/', '-'), suffix='.npz')
os.close(fd)
n = len(request.path_info)
query_string = unquote_plus(request.get_full_path()[n:])
aw = _extract(ds, what + query_string)
a = {}
for key, val in vars(aw).items():
key = str(key) # can be a numpy.bytes_
if isinstance(val, str):
# without this oq extract would fail
a[key] = numpy.array(val.encode('utf-8'))
elif isinstance(val, dict):
# this is hack: we are losing the values
a[key] = list(val)
else:
a[key] = val
numpy.savez_compressed(fname, **a)
except Exception as exc:
tb = ''.join(traceback.format_tb(exc.__traceback__))
return HttpResponse(
content='%s: %s\n%s' % (exc.__class__.__name__, exc, tb),
content_type='text/plain', status=500)
# stream the data back
stream = FileWrapper(open(fname, 'rb'))
stream.close = lambda: (FileWrapper.close(stream), os.remove(fname))
response = FileResponse(stream, content_type='application/octet-stream')
response['Content-Disposition'] = (
'attachment; filename=%s' % os.path.basename(fname))
response['Content-Length'] = str(os.path.getsize(fname))
return response | python | def extract(request, calc_id, what):
"""
Wrapper over the `oq extract` command. If `setting.LOCKDOWN` is true
only calculations owned by the current user can be retrieved.
"""
job = logs.dbcmd('get_job', int(calc_id))
if job is None:
return HttpResponseNotFound()
if not utils.user_has_permission(request, job.user_name):
return HttpResponseForbidden()
try:
# read the data and save them on a temporary .npz file
with datastore.read(job.ds_calc_dir + '.hdf5') as ds:
fd, fname = tempfile.mkstemp(
prefix=what.replace('/', '-'), suffix='.npz')
os.close(fd)
n = len(request.path_info)
query_string = unquote_plus(request.get_full_path()[n:])
aw = _extract(ds, what + query_string)
a = {}
for key, val in vars(aw).items():
key = str(key) # can be a numpy.bytes_
if isinstance(val, str):
# without this oq extract would fail
a[key] = numpy.array(val.encode('utf-8'))
elif isinstance(val, dict):
# this is hack: we are losing the values
a[key] = list(val)
else:
a[key] = val
numpy.savez_compressed(fname, **a)
except Exception as exc:
tb = ''.join(traceback.format_tb(exc.__traceback__))
return HttpResponse(
content='%s: %s\n%s' % (exc.__class__.__name__, exc, tb),
content_type='text/plain', status=500)
# stream the data back
stream = FileWrapper(open(fname, 'rb'))
stream.close = lambda: (FileWrapper.close(stream), os.remove(fname))
response = FileResponse(stream, content_type='application/octet-stream')
response['Content-Disposition'] = (
'attachment; filename=%s' % os.path.basename(fname))
response['Content-Length'] = str(os.path.getsize(fname))
return response | [
"def",
"extract",
"(",
"request",
",",
"calc_id",
",",
"what",
")",
":",
"job",
"=",
"logs",
".",
"dbcmd",
"(",
"'get_job'",
",",
"int",
"(",
"calc_id",
")",
")",
"if",
"job",
"is",
"None",
":",
"return",
"HttpResponseNotFound",
"(",
")",
"if",
"not",
"utils",
".",
"user_has_permission",
"(",
"request",
",",
"job",
".",
"user_name",
")",
":",
"return",
"HttpResponseForbidden",
"(",
")",
"try",
":",
"# read the data and save them on a temporary .npz file",
"with",
"datastore",
".",
"read",
"(",
"job",
".",
"ds_calc_dir",
"+",
"'.hdf5'",
")",
"as",
"ds",
":",
"fd",
",",
"fname",
"=",
"tempfile",
".",
"mkstemp",
"(",
"prefix",
"=",
"what",
".",
"replace",
"(",
"'/'",
",",
"'-'",
")",
",",
"suffix",
"=",
"'.npz'",
")",
"os",
".",
"close",
"(",
"fd",
")",
"n",
"=",
"len",
"(",
"request",
".",
"path_info",
")",
"query_string",
"=",
"unquote_plus",
"(",
"request",
".",
"get_full_path",
"(",
")",
"[",
"n",
":",
"]",
")",
"aw",
"=",
"_extract",
"(",
"ds",
",",
"what",
"+",
"query_string",
")",
"a",
"=",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"vars",
"(",
"aw",
")",
".",
"items",
"(",
")",
":",
"key",
"=",
"str",
"(",
"key",
")",
"# can be a numpy.bytes_",
"if",
"isinstance",
"(",
"val",
",",
"str",
")",
":",
"# without this oq extract would fail",
"a",
"[",
"key",
"]",
"=",
"numpy",
".",
"array",
"(",
"val",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"elif",
"isinstance",
"(",
"val",
",",
"dict",
")",
":",
"# this is hack: we are losing the values",
"a",
"[",
"key",
"]",
"=",
"list",
"(",
"val",
")",
"else",
":",
"a",
"[",
"key",
"]",
"=",
"val",
"numpy",
".",
"savez_compressed",
"(",
"fname",
",",
"*",
"*",
"a",
")",
"except",
"Exception",
"as",
"exc",
":",
"tb",
"=",
"''",
".",
"join",
"(",
"traceback",
".",
"format_tb",
"(",
"exc",
".",
"__traceback__",
")",
")",
"return",
"HttpResponse",
"(",
"content",
"=",
"'%s: %s\\n%s'",
"%",
"(",
"exc",
".",
"__class__",
".",
"__name__",
",",
"exc",
",",
"tb",
")",
",",
"content_type",
"=",
"'text/plain'",
",",
"status",
"=",
"500",
")",
"# stream the data back",
"stream",
"=",
"FileWrapper",
"(",
"open",
"(",
"fname",
",",
"'rb'",
")",
")",
"stream",
".",
"close",
"=",
"lambda",
":",
"(",
"FileWrapper",
".",
"close",
"(",
"stream",
")",
",",
"os",
".",
"remove",
"(",
"fname",
")",
")",
"response",
"=",
"FileResponse",
"(",
"stream",
",",
"content_type",
"=",
"'application/octet-stream'",
")",
"response",
"[",
"'Content-Disposition'",
"]",
"=",
"(",
"'attachment; filename=%s'",
"%",
"os",
".",
"path",
".",
"basename",
"(",
"fname",
")",
")",
"response",
"[",
"'Content-Length'",
"]",
"=",
"str",
"(",
"os",
".",
"path",
".",
"getsize",
"(",
"fname",
")",
")",
"return",
"response"
] | Wrapper over the `oq extract` command. If `setting.LOCKDOWN` is true
only calculations owned by the current user can be retrieved. | [
"Wrapper",
"over",
"the",
"oq",
"extract",
"command",
".",
"If",
"setting",
".",
"LOCKDOWN",
"is",
"true",
"only",
"calculations",
"owned",
"by",
"the",
"current",
"user",
"can",
"be",
"retrieved",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L658-L703 | train | 233,443 |
gem/oq-engine | openquake/server/views.py | calc_datastore | def calc_datastore(request, job_id):
"""
Download a full datastore file.
:param request:
`django.http.HttpRequest` object.
:param job_id:
The id of the requested datastore
:returns:
A `django.http.HttpResponse` containing the content
of the requested artifact, if present, else throws a 404
"""
job = logs.dbcmd('get_job', int(job_id))
if job is None:
return HttpResponseNotFound()
if not utils.user_has_permission(request, job.user_name):
return HttpResponseForbidden()
fname = job.ds_calc_dir + '.hdf5'
response = FileResponse(
FileWrapper(open(fname, 'rb')), content_type=HDF5)
response['Content-Disposition'] = (
'attachment; filename=%s' % os.path.basename(fname))
response['Content-Length'] = str(os.path.getsize(fname))
return response | python | def calc_datastore(request, job_id):
"""
Download a full datastore file.
:param request:
`django.http.HttpRequest` object.
:param job_id:
The id of the requested datastore
:returns:
A `django.http.HttpResponse` containing the content
of the requested artifact, if present, else throws a 404
"""
job = logs.dbcmd('get_job', int(job_id))
if job is None:
return HttpResponseNotFound()
if not utils.user_has_permission(request, job.user_name):
return HttpResponseForbidden()
fname = job.ds_calc_dir + '.hdf5'
response = FileResponse(
FileWrapper(open(fname, 'rb')), content_type=HDF5)
response['Content-Disposition'] = (
'attachment; filename=%s' % os.path.basename(fname))
response['Content-Length'] = str(os.path.getsize(fname))
return response | [
"def",
"calc_datastore",
"(",
"request",
",",
"job_id",
")",
":",
"job",
"=",
"logs",
".",
"dbcmd",
"(",
"'get_job'",
",",
"int",
"(",
"job_id",
")",
")",
"if",
"job",
"is",
"None",
":",
"return",
"HttpResponseNotFound",
"(",
")",
"if",
"not",
"utils",
".",
"user_has_permission",
"(",
"request",
",",
"job",
".",
"user_name",
")",
":",
"return",
"HttpResponseForbidden",
"(",
")",
"fname",
"=",
"job",
".",
"ds_calc_dir",
"+",
"'.hdf5'",
"response",
"=",
"FileResponse",
"(",
"FileWrapper",
"(",
"open",
"(",
"fname",
",",
"'rb'",
")",
")",
",",
"content_type",
"=",
"HDF5",
")",
"response",
"[",
"'Content-Disposition'",
"]",
"=",
"(",
"'attachment; filename=%s'",
"%",
"os",
".",
"path",
".",
"basename",
"(",
"fname",
")",
")",
"response",
"[",
"'Content-Length'",
"]",
"=",
"str",
"(",
"os",
".",
"path",
".",
"getsize",
"(",
"fname",
")",
")",
"return",
"response"
] | Download a full datastore file.
:param request:
`django.http.HttpRequest` object.
:param job_id:
The id of the requested datastore
:returns:
A `django.http.HttpResponse` containing the content
of the requested artifact, if present, else throws a 404 | [
"Download",
"a",
"full",
"datastore",
"file",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L708-L732 | train | 233,444 |
gem/oq-engine | openquake/server/views.py | calc_oqparam | def calc_oqparam(request, job_id):
"""
Return the calculation parameters as a JSON
"""
job = logs.dbcmd('get_job', int(job_id))
if job is None:
return HttpResponseNotFound()
if not utils.user_has_permission(request, job.user_name):
return HttpResponseForbidden()
with datastore.read(job.ds_calc_dir + '.hdf5') as ds:
oq = ds['oqparam']
return HttpResponse(content=json.dumps(vars(oq)), content_type=JSON) | python | def calc_oqparam(request, job_id):
"""
Return the calculation parameters as a JSON
"""
job = logs.dbcmd('get_job', int(job_id))
if job is None:
return HttpResponseNotFound()
if not utils.user_has_permission(request, job.user_name):
return HttpResponseForbidden()
with datastore.read(job.ds_calc_dir + '.hdf5') as ds:
oq = ds['oqparam']
return HttpResponse(content=json.dumps(vars(oq)), content_type=JSON) | [
"def",
"calc_oqparam",
"(",
"request",
",",
"job_id",
")",
":",
"job",
"=",
"logs",
".",
"dbcmd",
"(",
"'get_job'",
",",
"int",
"(",
"job_id",
")",
")",
"if",
"job",
"is",
"None",
":",
"return",
"HttpResponseNotFound",
"(",
")",
"if",
"not",
"utils",
".",
"user_has_permission",
"(",
"request",
",",
"job",
".",
"user_name",
")",
":",
"return",
"HttpResponseForbidden",
"(",
")",
"with",
"datastore",
".",
"read",
"(",
"job",
".",
"ds_calc_dir",
"+",
"'.hdf5'",
")",
"as",
"ds",
":",
"oq",
"=",
"ds",
"[",
"'oqparam'",
"]",
"return",
"HttpResponse",
"(",
"content",
"=",
"json",
".",
"dumps",
"(",
"vars",
"(",
"oq",
")",
")",
",",
"content_type",
"=",
"JSON",
")"
] | Return the calculation parameters as a JSON | [
"Return",
"the",
"calculation",
"parameters",
"as",
"a",
"JSON"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L737-L749 | train | 233,445 |
gem/oq-engine | openquake/server/views.py | on_same_fs | def on_same_fs(request):
"""
Accept a POST request to check access to a FS available by a client.
:param request:
`django.http.HttpRequest` object, containing mandatory parameters
filename and checksum.
"""
filename = request.POST['filename']
checksum_in = request.POST['checksum']
checksum = 0
try:
data = open(filename, 'rb').read(32)
checksum = zlib.adler32(data, checksum) & 0xffffffff
if checksum == int(checksum_in):
return HttpResponse(content=json.dumps({'success': True}),
content_type=JSON, status=200)
except (IOError, ValueError):
pass
return HttpResponse(content=json.dumps({'success': False}),
content_type=JSON, status=200) | python | def on_same_fs(request):
"""
Accept a POST request to check access to a FS available by a client.
:param request:
`django.http.HttpRequest` object, containing mandatory parameters
filename and checksum.
"""
filename = request.POST['filename']
checksum_in = request.POST['checksum']
checksum = 0
try:
data = open(filename, 'rb').read(32)
checksum = zlib.adler32(data, checksum) & 0xffffffff
if checksum == int(checksum_in):
return HttpResponse(content=json.dumps({'success': True}),
content_type=JSON, status=200)
except (IOError, ValueError):
pass
return HttpResponse(content=json.dumps({'success': False}),
content_type=JSON, status=200) | [
"def",
"on_same_fs",
"(",
"request",
")",
":",
"filename",
"=",
"request",
".",
"POST",
"[",
"'filename'",
"]",
"checksum_in",
"=",
"request",
".",
"POST",
"[",
"'checksum'",
"]",
"checksum",
"=",
"0",
"try",
":",
"data",
"=",
"open",
"(",
"filename",
",",
"'rb'",
")",
".",
"read",
"(",
"32",
")",
"checksum",
"=",
"zlib",
".",
"adler32",
"(",
"data",
",",
"checksum",
")",
"&",
"0xffffffff",
"if",
"checksum",
"==",
"int",
"(",
"checksum_in",
")",
":",
"return",
"HttpResponse",
"(",
"content",
"=",
"json",
".",
"dumps",
"(",
"{",
"'success'",
":",
"True",
"}",
")",
",",
"content_type",
"=",
"JSON",
",",
"status",
"=",
"200",
")",
"except",
"(",
"IOError",
",",
"ValueError",
")",
":",
"pass",
"return",
"HttpResponse",
"(",
"content",
"=",
"json",
".",
"dumps",
"(",
"{",
"'success'",
":",
"False",
"}",
")",
",",
"content_type",
"=",
"JSON",
",",
"status",
"=",
"200",
")"
] | Accept a POST request to check access to a FS available by a client.
:param request:
`django.http.HttpRequest` object, containing mandatory parameters
filename and checksum. | [
"Accept",
"a",
"POST",
"request",
"to",
"check",
"access",
"to",
"a",
"FS",
"available",
"by",
"a",
"client",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L769-L791 | train | 233,446 |
gem/oq-engine | openquake/calculators/classical_damage.py | classical_damage | def classical_damage(riskinputs, riskmodel, param, monitor):
"""
Core function for a classical damage computation.
:param riskinputs:
:class:`openquake.risklib.riskinput.RiskInput` objects
:param riskmodel:
a :class:`openquake.risklib.riskinput.CompositeRiskModel` instance
:param param:
dictionary of extra parameters
:param monitor:
:class:`openquake.baselib.performance.Monitor` instance
:returns:
a nested dictionary lt_idx, rlz_idx -> asset_idx -> <damage array>
"""
result = AccumDict(accum=AccumDict())
for ri in riskinputs:
for out in riskmodel.gen_outputs(ri, monitor):
for l, loss_type in enumerate(riskmodel.loss_types):
ordinals = ri.assets['ordinal']
result[l, out.rlzi] += dict(zip(ordinals, out[loss_type]))
return result | python | def classical_damage(riskinputs, riskmodel, param, monitor):
"""
Core function for a classical damage computation.
:param riskinputs:
:class:`openquake.risklib.riskinput.RiskInput` objects
:param riskmodel:
a :class:`openquake.risklib.riskinput.CompositeRiskModel` instance
:param param:
dictionary of extra parameters
:param monitor:
:class:`openquake.baselib.performance.Monitor` instance
:returns:
a nested dictionary lt_idx, rlz_idx -> asset_idx -> <damage array>
"""
result = AccumDict(accum=AccumDict())
for ri in riskinputs:
for out in riskmodel.gen_outputs(ri, monitor):
for l, loss_type in enumerate(riskmodel.loss_types):
ordinals = ri.assets['ordinal']
result[l, out.rlzi] += dict(zip(ordinals, out[loss_type]))
return result | [
"def",
"classical_damage",
"(",
"riskinputs",
",",
"riskmodel",
",",
"param",
",",
"monitor",
")",
":",
"result",
"=",
"AccumDict",
"(",
"accum",
"=",
"AccumDict",
"(",
")",
")",
"for",
"ri",
"in",
"riskinputs",
":",
"for",
"out",
"in",
"riskmodel",
".",
"gen_outputs",
"(",
"ri",
",",
"monitor",
")",
":",
"for",
"l",
",",
"loss_type",
"in",
"enumerate",
"(",
"riskmodel",
".",
"loss_types",
")",
":",
"ordinals",
"=",
"ri",
".",
"assets",
"[",
"'ordinal'",
"]",
"result",
"[",
"l",
",",
"out",
".",
"rlzi",
"]",
"+=",
"dict",
"(",
"zip",
"(",
"ordinals",
",",
"out",
"[",
"loss_type",
"]",
")",
")",
"return",
"result"
] | Core function for a classical damage computation.
:param riskinputs:
:class:`openquake.risklib.riskinput.RiskInput` objects
:param riskmodel:
a :class:`openquake.risklib.riskinput.CompositeRiskModel` instance
:param param:
dictionary of extra parameters
:param monitor:
:class:`openquake.baselib.performance.Monitor` instance
:returns:
a nested dictionary lt_idx, rlz_idx -> asset_idx -> <damage array> | [
"Core",
"function",
"for",
"a",
"classical",
"damage",
"computation",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/classical_damage.py#L26-L47 | train | 233,447 |
gem/oq-engine | openquake/hmtk/seismicity/gcmt_catalogue.py | cmp_mat | def cmp_mat(a, b):
"""
Sorts two matrices returning a positive or zero value
"""
c = 0
for x, y in zip(a.flat, b.flat):
c = cmp(abs(x), abs(y))
if c != 0:
return c
return c | python | def cmp_mat(a, b):
"""
Sorts two matrices returning a positive or zero value
"""
c = 0
for x, y in zip(a.flat, b.flat):
c = cmp(abs(x), abs(y))
if c != 0:
return c
return c | [
"def",
"cmp_mat",
"(",
"a",
",",
"b",
")",
":",
"c",
"=",
"0",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"a",
".",
"flat",
",",
"b",
".",
"flat",
")",
":",
"c",
"=",
"cmp",
"(",
"abs",
"(",
"x",
")",
",",
"abs",
"(",
"y",
")",
")",
"if",
"c",
"!=",
"0",
":",
"return",
"c",
"return",
"c"
] | Sorts two matrices returning a positive or zero value | [
"Sorts",
"two",
"matrices",
"returning",
"a",
"positive",
"or",
"zero",
"value"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_catalogue.py#L62-L71 | train | 233,448 |
gem/oq-engine | openquake/hmtk/seismicity/gcmt_catalogue.py | GCMTCentroid._get_centroid_time | def _get_centroid_time(self, time_diff):
"""
Calculates the time difference between the date-time classes
"""
source_time = datetime.datetime.combine(self.date, self.time)
second_diff = floor(fabs(time_diff))
microsecond_diff = int(1000. * (time_diff - second_diff))
if time_diff < 0.:
source_time = source_time - datetime.timedelta(
seconds=int(second_diff), microseconds=microsecond_diff)
else:
source_time = source_time + datetime.timedelta(
seconds=int(second_diff), microseconds=microsecond_diff)
self.time = source_time.time()
self.date = source_time.date() | python | def _get_centroid_time(self, time_diff):
"""
Calculates the time difference between the date-time classes
"""
source_time = datetime.datetime.combine(self.date, self.time)
second_diff = floor(fabs(time_diff))
microsecond_diff = int(1000. * (time_diff - second_diff))
if time_diff < 0.:
source_time = source_time - datetime.timedelta(
seconds=int(second_diff), microseconds=microsecond_diff)
else:
source_time = source_time + datetime.timedelta(
seconds=int(second_diff), microseconds=microsecond_diff)
self.time = source_time.time()
self.date = source_time.date() | [
"def",
"_get_centroid_time",
"(",
"self",
",",
"time_diff",
")",
":",
"source_time",
"=",
"datetime",
".",
"datetime",
".",
"combine",
"(",
"self",
".",
"date",
",",
"self",
".",
"time",
")",
"second_diff",
"=",
"floor",
"(",
"fabs",
"(",
"time_diff",
")",
")",
"microsecond_diff",
"=",
"int",
"(",
"1000.",
"*",
"(",
"time_diff",
"-",
"second_diff",
")",
")",
"if",
"time_diff",
"<",
"0.",
":",
"source_time",
"=",
"source_time",
"-",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"int",
"(",
"second_diff",
")",
",",
"microseconds",
"=",
"microsecond_diff",
")",
"else",
":",
"source_time",
"=",
"source_time",
"+",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"int",
"(",
"second_diff",
")",
",",
"microseconds",
"=",
"microsecond_diff",
")",
"self",
".",
"time",
"=",
"source_time",
".",
"time",
"(",
")",
"self",
".",
"date",
"=",
"source_time",
".",
"date",
"(",
")"
] | Calculates the time difference between the date-time classes | [
"Calculates",
"the",
"time",
"difference",
"between",
"the",
"date",
"-",
"time",
"classes"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_catalogue.py#L120-L134 | train | 233,449 |
gem/oq-engine | openquake/hmtk/seismicity/gcmt_catalogue.py | GCMTMomentTensor._to_ned | def _to_ned(self):
"""
Switches the reference frame to NED
"""
if self.ref_frame is 'USE':
# Rotate
return utils.use_to_ned(self.tensor), \
utils.use_to_ned(self.tensor_sigma)
elif self.ref_frame is 'NED':
# Alreadt NED
return self.tensor, self.tensor_sigma
else:
raise ValueError('Reference frame %s not recognised - cannot '
'transform to NED!' % self.ref_frame) | python | def _to_ned(self):
"""
Switches the reference frame to NED
"""
if self.ref_frame is 'USE':
# Rotate
return utils.use_to_ned(self.tensor), \
utils.use_to_ned(self.tensor_sigma)
elif self.ref_frame is 'NED':
# Alreadt NED
return self.tensor, self.tensor_sigma
else:
raise ValueError('Reference frame %s not recognised - cannot '
'transform to NED!' % self.ref_frame) | [
"def",
"_to_ned",
"(",
"self",
")",
":",
"if",
"self",
".",
"ref_frame",
"is",
"'USE'",
":",
"# Rotate",
"return",
"utils",
".",
"use_to_ned",
"(",
"self",
".",
"tensor",
")",
",",
"utils",
".",
"use_to_ned",
"(",
"self",
".",
"tensor_sigma",
")",
"elif",
"self",
".",
"ref_frame",
"is",
"'NED'",
":",
"# Alreadt NED",
"return",
"self",
".",
"tensor",
",",
"self",
".",
"tensor_sigma",
"else",
":",
"raise",
"ValueError",
"(",
"'Reference frame %s not recognised - cannot '",
"'transform to NED!'",
"%",
"self",
".",
"ref_frame",
")"
] | Switches the reference frame to NED | [
"Switches",
"the",
"reference",
"frame",
"to",
"NED"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_catalogue.py#L193-L206 | train | 233,450 |
gem/oq-engine | openquake/hmtk/seismicity/gcmt_catalogue.py | GCMTMomentTensor._to_use | def _to_use(self):
"""
Returns a tensor in the USE reference frame
"""
if self.ref_frame is 'NED':
# Rotate
return utils.ned_to_use(self.tensor), \
utils.ned_to_use(self.tensor_sigma)
elif self.ref_frame is 'USE':
# Already USE
return self.tensor, self.tensor_sigma
else:
raise ValueError('Reference frame %s not recognised - cannot '
'transform to USE!' % self.ref_frame) | python | def _to_use(self):
"""
Returns a tensor in the USE reference frame
"""
if self.ref_frame is 'NED':
# Rotate
return utils.ned_to_use(self.tensor), \
utils.ned_to_use(self.tensor_sigma)
elif self.ref_frame is 'USE':
# Already USE
return self.tensor, self.tensor_sigma
else:
raise ValueError('Reference frame %s not recognised - cannot '
'transform to USE!' % self.ref_frame) | [
"def",
"_to_use",
"(",
"self",
")",
":",
"if",
"self",
".",
"ref_frame",
"is",
"'NED'",
":",
"# Rotate",
"return",
"utils",
".",
"ned_to_use",
"(",
"self",
".",
"tensor",
")",
",",
"utils",
".",
"ned_to_use",
"(",
"self",
".",
"tensor_sigma",
")",
"elif",
"self",
".",
"ref_frame",
"is",
"'USE'",
":",
"# Already USE",
"return",
"self",
".",
"tensor",
",",
"self",
".",
"tensor_sigma",
"else",
":",
"raise",
"ValueError",
"(",
"'Reference frame %s not recognised - cannot '",
"'transform to USE!'",
"%",
"self",
".",
"ref_frame",
")"
] | Returns a tensor in the USE reference frame | [
"Returns",
"a",
"tensor",
"in",
"the",
"USE",
"reference",
"frame"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_catalogue.py#L208-L221 | train | 233,451 |
gem/oq-engine | openquake/hmtk/seismicity/gcmt_catalogue.py | GCMTMomentTensor.get_nodal_planes | def get_nodal_planes(self):
"""
Returns the nodal planes by eigendecomposition of the moment tensor
"""
# Convert reference frame to NED
self.tensor, self.tensor_sigma = self._to_ned()
self.ref_frame = 'NED'
# Eigenvalue decomposition
# Tensor
_, evect = utils.eigendecompose(self.tensor)
# Rotation matrix
_, rot_vec = utils.eigendecompose(np.matrix([[0., 0., -1],
[0., 0., 0.],
[-1., 0., 0.]]))
rotation_matrix = (np.matrix(evect * rot_vec.T)).T
if np.linalg.det(rotation_matrix) < 0.:
rotation_matrix *= -1.
flip_dc = np.matrix([[0., 0., -1.],
[0., -1., 0.],
[-1., 0., 0.]])
rotation_matrices = sorted(
[rotation_matrix, flip_dc * rotation_matrix],
cmp=cmp_mat)
nodal_planes = GCMTNodalPlanes()
dip, strike, rake = [(180. / pi) * angle
for angle in utils.matrix_to_euler(rotation_matrices[0])]
# 1st Nodal Plane
nodal_planes.nodal_plane_1 = {'strike': strike % 360,
'dip': dip,
'rake': -rake}
# 2nd Nodal Plane
dip, strike, rake = [(180. / pi) * angle
for angle in utils.matrix_to_euler(rotation_matrices[1])]
nodal_planes.nodal_plane_2 = {'strike': strike % 360.,
'dip': dip,
'rake': -rake}
return nodal_planes | python | def get_nodal_planes(self):
"""
Returns the nodal planes by eigendecomposition of the moment tensor
"""
# Convert reference frame to NED
self.tensor, self.tensor_sigma = self._to_ned()
self.ref_frame = 'NED'
# Eigenvalue decomposition
# Tensor
_, evect = utils.eigendecompose(self.tensor)
# Rotation matrix
_, rot_vec = utils.eigendecompose(np.matrix([[0., 0., -1],
[0., 0., 0.],
[-1., 0., 0.]]))
rotation_matrix = (np.matrix(evect * rot_vec.T)).T
if np.linalg.det(rotation_matrix) < 0.:
rotation_matrix *= -1.
flip_dc = np.matrix([[0., 0., -1.],
[0., -1., 0.],
[-1., 0., 0.]])
rotation_matrices = sorted(
[rotation_matrix, flip_dc * rotation_matrix],
cmp=cmp_mat)
nodal_planes = GCMTNodalPlanes()
dip, strike, rake = [(180. / pi) * angle
for angle in utils.matrix_to_euler(rotation_matrices[0])]
# 1st Nodal Plane
nodal_planes.nodal_plane_1 = {'strike': strike % 360,
'dip': dip,
'rake': -rake}
# 2nd Nodal Plane
dip, strike, rake = [(180. / pi) * angle
for angle in utils.matrix_to_euler(rotation_matrices[1])]
nodal_planes.nodal_plane_2 = {'strike': strike % 360.,
'dip': dip,
'rake': -rake}
return nodal_planes | [
"def",
"get_nodal_planes",
"(",
"self",
")",
":",
"# Convert reference frame to NED",
"self",
".",
"tensor",
",",
"self",
".",
"tensor_sigma",
"=",
"self",
".",
"_to_ned",
"(",
")",
"self",
".",
"ref_frame",
"=",
"'NED'",
"# Eigenvalue decomposition",
"# Tensor",
"_",
",",
"evect",
"=",
"utils",
".",
"eigendecompose",
"(",
"self",
".",
"tensor",
")",
"# Rotation matrix",
"_",
",",
"rot_vec",
"=",
"utils",
".",
"eigendecompose",
"(",
"np",
".",
"matrix",
"(",
"[",
"[",
"0.",
",",
"0.",
",",
"-",
"1",
"]",
",",
"[",
"0.",
",",
"0.",
",",
"0.",
"]",
",",
"[",
"-",
"1.",
",",
"0.",
",",
"0.",
"]",
"]",
")",
")",
"rotation_matrix",
"=",
"(",
"np",
".",
"matrix",
"(",
"evect",
"*",
"rot_vec",
".",
"T",
")",
")",
".",
"T",
"if",
"np",
".",
"linalg",
".",
"det",
"(",
"rotation_matrix",
")",
"<",
"0.",
":",
"rotation_matrix",
"*=",
"-",
"1.",
"flip_dc",
"=",
"np",
".",
"matrix",
"(",
"[",
"[",
"0.",
",",
"0.",
",",
"-",
"1.",
"]",
",",
"[",
"0.",
",",
"-",
"1.",
",",
"0.",
"]",
",",
"[",
"-",
"1.",
",",
"0.",
",",
"0.",
"]",
"]",
")",
"rotation_matrices",
"=",
"sorted",
"(",
"[",
"rotation_matrix",
",",
"flip_dc",
"*",
"rotation_matrix",
"]",
",",
"cmp",
"=",
"cmp_mat",
")",
"nodal_planes",
"=",
"GCMTNodalPlanes",
"(",
")",
"dip",
",",
"strike",
",",
"rake",
"=",
"[",
"(",
"180.",
"/",
"pi",
")",
"*",
"angle",
"for",
"angle",
"in",
"utils",
".",
"matrix_to_euler",
"(",
"rotation_matrices",
"[",
"0",
"]",
")",
"]",
"# 1st Nodal Plane",
"nodal_planes",
".",
"nodal_plane_1",
"=",
"{",
"'strike'",
":",
"strike",
"%",
"360",
",",
"'dip'",
":",
"dip",
",",
"'rake'",
":",
"-",
"rake",
"}",
"# 2nd Nodal Plane",
"dip",
",",
"strike",
",",
"rake",
"=",
"[",
"(",
"180.",
"/",
"pi",
")",
"*",
"angle",
"for",
"angle",
"in",
"utils",
".",
"matrix_to_euler",
"(",
"rotation_matrices",
"[",
"1",
"]",
")",
"]",
"nodal_planes",
".",
"nodal_plane_2",
"=",
"{",
"'strike'",
":",
"strike",
"%",
"360.",
",",
"'dip'",
":",
"dip",
",",
"'rake'",
":",
"-",
"rake",
"}",
"return",
"nodal_planes"
] | Returns the nodal planes by eigendecomposition of the moment tensor | [
"Returns",
"the",
"nodal",
"planes",
"by",
"eigendecomposition",
"of",
"the",
"moment",
"tensor"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_catalogue.py#L239-L276 | train | 233,452 |
gem/oq-engine | openquake/hmtk/seismicity/gcmt_catalogue.py | GCMTMomentTensor.get_principal_axes | def get_principal_axes(self):
"""
Uses the eigendecomposition to extract the principal axes from the
moment tensor - returning an instance of the GCMTPrincipalAxes class
"""
# Perform eigendecomposition - returns in order P, B, T
_ = self.eigendecompose(normalise=True)
principal_axes = GCMTPrincipalAxes()
# Eigenvalues
principal_axes.p_axis = {'eigenvalue': self.eigenvalues[0]}
principal_axes.b_axis = {'eigenvalue': self.eigenvalues[1]}
principal_axes.t_axis = {'eigenvalue': self.eigenvalues[2]}
# Eigen vectors
# 1) P axis
azim, plun = utils.get_azimuth_plunge(self.eigenvectors[:, 0], True)
principal_axes.p_axis['azimuth'] = azim
principal_axes.p_axis['plunge'] = plun
# 2) B axis
azim, plun = utils.get_azimuth_plunge(self.eigenvectors[:, 1], True)
principal_axes.b_axis['azimuth'] = azim
principal_axes.b_axis['plunge'] = plun
# 3) T axis
azim, plun = utils.get_azimuth_plunge(self.eigenvectors[:, 2], True)
principal_axes.t_axis['azimuth'] = azim
principal_axes.t_axis['plunge'] = plun
return principal_axes | python | def get_principal_axes(self):
"""
Uses the eigendecomposition to extract the principal axes from the
moment tensor - returning an instance of the GCMTPrincipalAxes class
"""
# Perform eigendecomposition - returns in order P, B, T
_ = self.eigendecompose(normalise=True)
principal_axes = GCMTPrincipalAxes()
# Eigenvalues
principal_axes.p_axis = {'eigenvalue': self.eigenvalues[0]}
principal_axes.b_axis = {'eigenvalue': self.eigenvalues[1]}
principal_axes.t_axis = {'eigenvalue': self.eigenvalues[2]}
# Eigen vectors
# 1) P axis
azim, plun = utils.get_azimuth_plunge(self.eigenvectors[:, 0], True)
principal_axes.p_axis['azimuth'] = azim
principal_axes.p_axis['plunge'] = plun
# 2) B axis
azim, plun = utils.get_azimuth_plunge(self.eigenvectors[:, 1], True)
principal_axes.b_axis['azimuth'] = azim
principal_axes.b_axis['plunge'] = plun
# 3) T axis
azim, plun = utils.get_azimuth_plunge(self.eigenvectors[:, 2], True)
principal_axes.t_axis['azimuth'] = azim
principal_axes.t_axis['plunge'] = plun
return principal_axes | [
"def",
"get_principal_axes",
"(",
"self",
")",
":",
"# Perform eigendecomposition - returns in order P, B, T",
"_",
"=",
"self",
".",
"eigendecompose",
"(",
"normalise",
"=",
"True",
")",
"principal_axes",
"=",
"GCMTPrincipalAxes",
"(",
")",
"# Eigenvalues",
"principal_axes",
".",
"p_axis",
"=",
"{",
"'eigenvalue'",
":",
"self",
".",
"eigenvalues",
"[",
"0",
"]",
"}",
"principal_axes",
".",
"b_axis",
"=",
"{",
"'eigenvalue'",
":",
"self",
".",
"eigenvalues",
"[",
"1",
"]",
"}",
"principal_axes",
".",
"t_axis",
"=",
"{",
"'eigenvalue'",
":",
"self",
".",
"eigenvalues",
"[",
"2",
"]",
"}",
"# Eigen vectors",
"# 1) P axis",
"azim",
",",
"plun",
"=",
"utils",
".",
"get_azimuth_plunge",
"(",
"self",
".",
"eigenvectors",
"[",
":",
",",
"0",
"]",
",",
"True",
")",
"principal_axes",
".",
"p_axis",
"[",
"'azimuth'",
"]",
"=",
"azim",
"principal_axes",
".",
"p_axis",
"[",
"'plunge'",
"]",
"=",
"plun",
"# 2) B axis",
"azim",
",",
"plun",
"=",
"utils",
".",
"get_azimuth_plunge",
"(",
"self",
".",
"eigenvectors",
"[",
":",
",",
"1",
"]",
",",
"True",
")",
"principal_axes",
".",
"b_axis",
"[",
"'azimuth'",
"]",
"=",
"azim",
"principal_axes",
".",
"b_axis",
"[",
"'plunge'",
"]",
"=",
"plun",
"# 3) T axis",
"azim",
",",
"plun",
"=",
"utils",
".",
"get_azimuth_plunge",
"(",
"self",
".",
"eigenvectors",
"[",
":",
",",
"2",
"]",
",",
"True",
")",
"principal_axes",
".",
"t_axis",
"[",
"'azimuth'",
"]",
"=",
"azim",
"principal_axes",
".",
"t_axis",
"[",
"'plunge'",
"]",
"=",
"plun",
"return",
"principal_axes"
] | Uses the eigendecomposition to extract the principal axes from the
moment tensor - returning an instance of the GCMTPrincipalAxes class | [
"Uses",
"the",
"eigendecomposition",
"to",
"extract",
"the",
"principal",
"axes",
"from",
"the",
"moment",
"tensor",
"-",
"returning",
"an",
"instance",
"of",
"the",
"GCMTPrincipalAxes",
"class"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_catalogue.py#L278-L303 | train | 233,453 |
gem/oq-engine | openquake/hmtk/seismicity/gcmt_catalogue.py | GCMTCatalogue.select_catalogue_events | def select_catalogue_events(self, id0):
'''
Orders the events in the catalogue according to an indexing vector
:param np.ndarray id0:
Pointer array indicating the locations of selected events
'''
for key in self.data.keys():
if isinstance(
self.data[key], np.ndarray) and len(self.data[key]) > 0:
# Dictionary element is numpy array - use logical indexing
self.data[key] = self.data[key][id0]
elif isinstance(
self.data[key], list) and len(self.data[key]) > 0:
# Dictionary element is list
self.data[key] = [self.data[key][iloc] for iloc in id0]
else:
continue
if len(self.gcmts) > 0:
self.gcmts = [self.gcmts[iloc] for iloc in id0]
self.number_gcmts = self.get_number_tensors() | python | def select_catalogue_events(self, id0):
'''
Orders the events in the catalogue according to an indexing vector
:param np.ndarray id0:
Pointer array indicating the locations of selected events
'''
for key in self.data.keys():
if isinstance(
self.data[key], np.ndarray) and len(self.data[key]) > 0:
# Dictionary element is numpy array - use logical indexing
self.data[key] = self.data[key][id0]
elif isinstance(
self.data[key], list) and len(self.data[key]) > 0:
# Dictionary element is list
self.data[key] = [self.data[key][iloc] for iloc in id0]
else:
continue
if len(self.gcmts) > 0:
self.gcmts = [self.gcmts[iloc] for iloc in id0]
self.number_gcmts = self.get_number_tensors() | [
"def",
"select_catalogue_events",
"(",
"self",
",",
"id0",
")",
":",
"for",
"key",
"in",
"self",
".",
"data",
".",
"keys",
"(",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"data",
"[",
"key",
"]",
",",
"np",
".",
"ndarray",
")",
"and",
"len",
"(",
"self",
".",
"data",
"[",
"key",
"]",
")",
">",
"0",
":",
"# Dictionary element is numpy array - use logical indexing",
"self",
".",
"data",
"[",
"key",
"]",
"=",
"self",
".",
"data",
"[",
"key",
"]",
"[",
"id0",
"]",
"elif",
"isinstance",
"(",
"self",
".",
"data",
"[",
"key",
"]",
",",
"list",
")",
"and",
"len",
"(",
"self",
".",
"data",
"[",
"key",
"]",
")",
">",
"0",
":",
"# Dictionary element is list",
"self",
".",
"data",
"[",
"key",
"]",
"=",
"[",
"self",
".",
"data",
"[",
"key",
"]",
"[",
"iloc",
"]",
"for",
"iloc",
"in",
"id0",
"]",
"else",
":",
"continue",
"if",
"len",
"(",
"self",
".",
"gcmts",
")",
">",
"0",
":",
"self",
".",
"gcmts",
"=",
"[",
"self",
".",
"gcmts",
"[",
"iloc",
"]",
"for",
"iloc",
"in",
"id0",
"]",
"self",
".",
"number_gcmts",
"=",
"self",
".",
"get_number_tensors",
"(",
")"
] | Orders the events in the catalogue according to an indexing vector
:param np.ndarray id0:
Pointer array indicating the locations of selected events | [
"Orders",
"the",
"events",
"in",
"the",
"catalogue",
"according",
"to",
"an",
"indexing",
"vector"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_catalogue.py#L424-L445 | train | 233,454 |
gem/oq-engine | openquake/hazardlib/geo/surface/multi.py | MultiSurface._get_edge_set | def _get_edge_set(self, tol=0.1):
"""
Retrieve set of top edges from all of the individual surfaces,
downsampling the upper edge based on the specified tolerance
"""
edges = []
for surface in self.surfaces:
if isinstance(surface, GriddedSurface):
return edges.append(surface.mesh)
elif isinstance(surface, PlanarSurface):
# Top edge determined from two end points
edge = []
for pnt in [surface.top_left, surface.top_right]:
edge.append([pnt.longitude, pnt.latitude, pnt.depth])
edges.append(numpy.array(edge))
elif isinstance(surface,
(ComplexFaultSurface, SimpleFaultSurface)):
# Rectangular meshes are downsampled to reduce their
# overall size
edges.append(downsample_trace(surface.mesh, tol))
else:
raise ValueError("Surface %s not recognised" % str(surface))
return edges | python | def _get_edge_set(self, tol=0.1):
"""
Retrieve set of top edges from all of the individual surfaces,
downsampling the upper edge based on the specified tolerance
"""
edges = []
for surface in self.surfaces:
if isinstance(surface, GriddedSurface):
return edges.append(surface.mesh)
elif isinstance(surface, PlanarSurface):
# Top edge determined from two end points
edge = []
for pnt in [surface.top_left, surface.top_right]:
edge.append([pnt.longitude, pnt.latitude, pnt.depth])
edges.append(numpy.array(edge))
elif isinstance(surface,
(ComplexFaultSurface, SimpleFaultSurface)):
# Rectangular meshes are downsampled to reduce their
# overall size
edges.append(downsample_trace(surface.mesh, tol))
else:
raise ValueError("Surface %s not recognised" % str(surface))
return edges | [
"def",
"_get_edge_set",
"(",
"self",
",",
"tol",
"=",
"0.1",
")",
":",
"edges",
"=",
"[",
"]",
"for",
"surface",
"in",
"self",
".",
"surfaces",
":",
"if",
"isinstance",
"(",
"surface",
",",
"GriddedSurface",
")",
":",
"return",
"edges",
".",
"append",
"(",
"surface",
".",
"mesh",
")",
"elif",
"isinstance",
"(",
"surface",
",",
"PlanarSurface",
")",
":",
"# Top edge determined from two end points",
"edge",
"=",
"[",
"]",
"for",
"pnt",
"in",
"[",
"surface",
".",
"top_left",
",",
"surface",
".",
"top_right",
"]",
":",
"edge",
".",
"append",
"(",
"[",
"pnt",
".",
"longitude",
",",
"pnt",
".",
"latitude",
",",
"pnt",
".",
"depth",
"]",
")",
"edges",
".",
"append",
"(",
"numpy",
".",
"array",
"(",
"edge",
")",
")",
"elif",
"isinstance",
"(",
"surface",
",",
"(",
"ComplexFaultSurface",
",",
"SimpleFaultSurface",
")",
")",
":",
"# Rectangular meshes are downsampled to reduce their",
"# overall size",
"edges",
".",
"append",
"(",
"downsample_trace",
"(",
"surface",
".",
"mesh",
",",
"tol",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Surface %s not recognised\"",
"%",
"str",
"(",
"surface",
")",
")",
"return",
"edges"
] | Retrieve set of top edges from all of the individual surfaces,
downsampling the upper edge based on the specified tolerance | [
"Retrieve",
"set",
"of",
"top",
"edges",
"from",
"all",
"of",
"the",
"individual",
"surfaces",
"downsampling",
"the",
"upper",
"edge",
"based",
"on",
"the",
"specified",
"tolerance"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/multi.py#L137-L159 | train | 233,455 |
gem/oq-engine | openquake/hazardlib/geo/surface/multi.py | MultiSurface.get_min_distance | def get_min_distance(self, mesh):
"""
For each point in ``mesh`` compute the minimum distance to each
surface element and return the smallest value.
See :meth:`superclass method
<.base.BaseSurface.get_min_distance>`
for spec of input and result values.
"""
dists = [surf.get_min_distance(mesh) for surf in self.surfaces]
return numpy.min(dists, axis=0) | python | def get_min_distance(self, mesh):
"""
For each point in ``mesh`` compute the minimum distance to each
surface element and return the smallest value.
See :meth:`superclass method
<.base.BaseSurface.get_min_distance>`
for spec of input and result values.
"""
dists = [surf.get_min_distance(mesh) for surf in self.surfaces]
return numpy.min(dists, axis=0) | [
"def",
"get_min_distance",
"(",
"self",
",",
"mesh",
")",
":",
"dists",
"=",
"[",
"surf",
".",
"get_min_distance",
"(",
"mesh",
")",
"for",
"surf",
"in",
"self",
".",
"surfaces",
"]",
"return",
"numpy",
".",
"min",
"(",
"dists",
",",
"axis",
"=",
"0",
")"
] | For each point in ``mesh`` compute the minimum distance to each
surface element and return the smallest value.
See :meth:`superclass method
<.base.BaseSurface.get_min_distance>`
for spec of input and result values. | [
"For",
"each",
"point",
"in",
"mesh",
"compute",
"the",
"minimum",
"distance",
"to",
"each",
"surface",
"element",
"and",
"return",
"the",
"smallest",
"value",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/multi.py#L161-L172 | train | 233,456 |
gem/oq-engine | openquake/hazardlib/geo/surface/multi.py | MultiSurface.get_closest_points | def get_closest_points(self, mesh):
"""
For each point in ``mesh`` find the closest surface element, and return
the corresponding closest point.
See :meth:`superclass method
<.base.BaseSurface.get_closest_points>`
for spec of input and result values.
"""
# first, for each point in mesh compute minimum distance to each
# surface. The distance matrix is flattend, because mesh can be of
# an arbitrary shape. By flattening we obtain a ``distances`` matrix
# for which the first dimension represents the different surfaces
# and the second dimension the mesh points.
dists = numpy.array(
[surf.get_min_distance(mesh).flatten() for surf in self.surfaces]
)
# find for each point in mesh the index of closest surface
idx = dists == numpy.min(dists, axis=0)
# loop again over surfaces. For each surface compute the closest
# points, and associate them to the mesh points for which the surface
# is the closest. Note that if a surface is not the closest to any of
# the mesh points then the calculation is skipped
lons = numpy.empty_like(mesh.lons.flatten())
lats = numpy.empty_like(mesh.lats.flatten())
depths = None if mesh.depths is None else \
numpy.empty_like(mesh.depths.flatten())
for i, surf in enumerate(self.surfaces):
if not idx[i, :].any():
continue
cps = surf.get_closest_points(mesh)
lons[idx[i, :]] = cps.lons.flatten()[idx[i, :]]
lats[idx[i, :]] = cps.lats.flatten()[idx[i, :]]
if depths is not None:
depths[idx[i, :]] = cps.depths.flatten()[idx[i, :]]
lons = lons.reshape(mesh.lons.shape)
lats = lats.reshape(mesh.lats.shape)
if depths is not None:
depths = depths.reshape(mesh.depths.shape)
return Mesh(lons, lats, depths) | python | def get_closest_points(self, mesh):
"""
For each point in ``mesh`` find the closest surface element, and return
the corresponding closest point.
See :meth:`superclass method
<.base.BaseSurface.get_closest_points>`
for spec of input and result values.
"""
# first, for each point in mesh compute minimum distance to each
# surface. The distance matrix is flattend, because mesh can be of
# an arbitrary shape. By flattening we obtain a ``distances`` matrix
# for which the first dimension represents the different surfaces
# and the second dimension the mesh points.
dists = numpy.array(
[surf.get_min_distance(mesh).flatten() for surf in self.surfaces]
)
# find for each point in mesh the index of closest surface
idx = dists == numpy.min(dists, axis=0)
# loop again over surfaces. For each surface compute the closest
# points, and associate them to the mesh points for which the surface
# is the closest. Note that if a surface is not the closest to any of
# the mesh points then the calculation is skipped
lons = numpy.empty_like(mesh.lons.flatten())
lats = numpy.empty_like(mesh.lats.flatten())
depths = None if mesh.depths is None else \
numpy.empty_like(mesh.depths.flatten())
for i, surf in enumerate(self.surfaces):
if not idx[i, :].any():
continue
cps = surf.get_closest_points(mesh)
lons[idx[i, :]] = cps.lons.flatten()[idx[i, :]]
lats[idx[i, :]] = cps.lats.flatten()[idx[i, :]]
if depths is not None:
depths[idx[i, :]] = cps.depths.flatten()[idx[i, :]]
lons = lons.reshape(mesh.lons.shape)
lats = lats.reshape(mesh.lats.shape)
if depths is not None:
depths = depths.reshape(mesh.depths.shape)
return Mesh(lons, lats, depths) | [
"def",
"get_closest_points",
"(",
"self",
",",
"mesh",
")",
":",
"# first, for each point in mesh compute minimum distance to each",
"# surface. The distance matrix is flattend, because mesh can be of",
"# an arbitrary shape. By flattening we obtain a ``distances`` matrix",
"# for which the first dimension represents the different surfaces",
"# and the second dimension the mesh points.",
"dists",
"=",
"numpy",
".",
"array",
"(",
"[",
"surf",
".",
"get_min_distance",
"(",
"mesh",
")",
".",
"flatten",
"(",
")",
"for",
"surf",
"in",
"self",
".",
"surfaces",
"]",
")",
"# find for each point in mesh the index of closest surface",
"idx",
"=",
"dists",
"==",
"numpy",
".",
"min",
"(",
"dists",
",",
"axis",
"=",
"0",
")",
"# loop again over surfaces. For each surface compute the closest",
"# points, and associate them to the mesh points for which the surface",
"# is the closest. Note that if a surface is not the closest to any of",
"# the mesh points then the calculation is skipped",
"lons",
"=",
"numpy",
".",
"empty_like",
"(",
"mesh",
".",
"lons",
".",
"flatten",
"(",
")",
")",
"lats",
"=",
"numpy",
".",
"empty_like",
"(",
"mesh",
".",
"lats",
".",
"flatten",
"(",
")",
")",
"depths",
"=",
"None",
"if",
"mesh",
".",
"depths",
"is",
"None",
"else",
"numpy",
".",
"empty_like",
"(",
"mesh",
".",
"depths",
".",
"flatten",
"(",
")",
")",
"for",
"i",
",",
"surf",
"in",
"enumerate",
"(",
"self",
".",
"surfaces",
")",
":",
"if",
"not",
"idx",
"[",
"i",
",",
":",
"]",
".",
"any",
"(",
")",
":",
"continue",
"cps",
"=",
"surf",
".",
"get_closest_points",
"(",
"mesh",
")",
"lons",
"[",
"idx",
"[",
"i",
",",
":",
"]",
"]",
"=",
"cps",
".",
"lons",
".",
"flatten",
"(",
")",
"[",
"idx",
"[",
"i",
",",
":",
"]",
"]",
"lats",
"[",
"idx",
"[",
"i",
",",
":",
"]",
"]",
"=",
"cps",
".",
"lats",
".",
"flatten",
"(",
")",
"[",
"idx",
"[",
"i",
",",
":",
"]",
"]",
"if",
"depths",
"is",
"not",
"None",
":",
"depths",
"[",
"idx",
"[",
"i",
",",
":",
"]",
"]",
"=",
"cps",
".",
"depths",
".",
"flatten",
"(",
")",
"[",
"idx",
"[",
"i",
",",
":",
"]",
"]",
"lons",
"=",
"lons",
".",
"reshape",
"(",
"mesh",
".",
"lons",
".",
"shape",
")",
"lats",
"=",
"lats",
".",
"reshape",
"(",
"mesh",
".",
"lats",
".",
"shape",
")",
"if",
"depths",
"is",
"not",
"None",
":",
"depths",
"=",
"depths",
".",
"reshape",
"(",
"mesh",
".",
"depths",
".",
"shape",
")",
"return",
"Mesh",
"(",
"lons",
",",
"lats",
",",
"depths",
")"
] | For each point in ``mesh`` find the closest surface element, and return
the corresponding closest point.
See :meth:`superclass method
<.base.BaseSurface.get_closest_points>`
for spec of input and result values. | [
"For",
"each",
"point",
"in",
"mesh",
"find",
"the",
"closest",
"surface",
"element",
"and",
"return",
"the",
"corresponding",
"closest",
"point",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/multi.py#L174-L216 | train | 233,457 |
gem/oq-engine | openquake/hazardlib/geo/surface/multi.py | MultiSurface.get_bounding_box | def get_bounding_box(self):
"""
Compute bounding box for each surface element, and then return
the bounding box of all surface elements' bounding boxes.
:return:
A tuple of four items. These items represent western, eastern,
northern and southern borders of the bounding box respectively.
Values are floats in decimal degrees.
"""
lons = []
lats = []
for surf in self.surfaces:
west, east, north, south = surf.get_bounding_box()
lons.extend([west, east])
lats.extend([north, south])
return utils.get_spherical_bounding_box(lons, lats) | python | def get_bounding_box(self):
"""
Compute bounding box for each surface element, and then return
the bounding box of all surface elements' bounding boxes.
:return:
A tuple of four items. These items represent western, eastern,
northern and southern borders of the bounding box respectively.
Values are floats in decimal degrees.
"""
lons = []
lats = []
for surf in self.surfaces:
west, east, north, south = surf.get_bounding_box()
lons.extend([west, east])
lats.extend([north, south])
return utils.get_spherical_bounding_box(lons, lats) | [
"def",
"get_bounding_box",
"(",
"self",
")",
":",
"lons",
"=",
"[",
"]",
"lats",
"=",
"[",
"]",
"for",
"surf",
"in",
"self",
".",
"surfaces",
":",
"west",
",",
"east",
",",
"north",
",",
"south",
"=",
"surf",
".",
"get_bounding_box",
"(",
")",
"lons",
".",
"extend",
"(",
"[",
"west",
",",
"east",
"]",
")",
"lats",
".",
"extend",
"(",
"[",
"north",
",",
"south",
"]",
")",
"return",
"utils",
".",
"get_spherical_bounding_box",
"(",
"lons",
",",
"lats",
")"
] | Compute bounding box for each surface element, and then return
the bounding box of all surface elements' bounding boxes.
:return:
A tuple of four items. These items represent western, eastern,
northern and southern borders of the bounding box respectively.
Values are floats in decimal degrees. | [
"Compute",
"bounding",
"box",
"for",
"each",
"surface",
"element",
"and",
"then",
"return",
"the",
"bounding",
"box",
"of",
"all",
"surface",
"elements",
"bounding",
"boxes",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/multi.py#L291-L307 | train | 233,458 |
gem/oq-engine | openquake/hazardlib/geo/surface/multi.py | MultiSurface._get_areas | def _get_areas(self):
"""
Return surface elements area values in a numpy array.
"""
if self.areas is None:
self.areas = []
for surf in self.surfaces:
self.areas.append(surf.get_area())
self.areas = numpy.array(self.areas)
return self.areas | python | def _get_areas(self):
"""
Return surface elements area values in a numpy array.
"""
if self.areas is None:
self.areas = []
for surf in self.surfaces:
self.areas.append(surf.get_area())
self.areas = numpy.array(self.areas)
return self.areas | [
"def",
"_get_areas",
"(",
"self",
")",
":",
"if",
"self",
".",
"areas",
"is",
"None",
":",
"self",
".",
"areas",
"=",
"[",
"]",
"for",
"surf",
"in",
"self",
".",
"surfaces",
":",
"self",
".",
"areas",
".",
"append",
"(",
"surf",
".",
"get_area",
"(",
")",
")",
"self",
".",
"areas",
"=",
"numpy",
".",
"array",
"(",
"self",
".",
"areas",
")",
"return",
"self",
".",
"areas"
] | Return surface elements area values in a numpy array. | [
"Return",
"surface",
"elements",
"area",
"values",
"in",
"a",
"numpy",
"array",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/multi.py#L350-L360 | train | 233,459 |
gem/oq-engine | openquake/hazardlib/geo/surface/multi.py | MultiSurface._get_cartesian_edge_set | def _get_cartesian_edge_set(self):
"""
For the GC2 calculations a set of cartesian representations of the
fault edges are needed. In this present case we use a common cartesian
framework for all edges, as opposed to defining a separate orthographic
projection per edge
"""
# Get projection space for cartesian projection
edge_sets = numpy.vstack(self.edge_set)
west, east, north, south = utils.get_spherical_bounding_box(
edge_sets[:, 0],
edge_sets[:, 1])
self.proj = utils.OrthographicProjection(west, east, north, south)
for edges in self.edge_set:
# Project edges into cartesian space
px, py = self.proj(edges[:, 0], edges[:, 1])
# Store the two end-points of the trace
self.cartesian_endpoints.append(
numpy.array([[px[0], py[0], edges[0, 2]],
[px[-1], py[-1], edges[-1, 2]]]))
self.cartesian_edges.append(numpy.column_stack([px, py,
edges[:, 2]]))
# Get surface length vector for the trace - easier in cartesian
lengths = numpy.sqrt((px[:-1] - px[1:]) ** 2. +
(py[:-1] - py[1:]) ** 2.)
self.length_set.append(lengths)
# Get cumulative surface length vector
self.cum_length_set.append(
numpy.hstack([0., numpy.cumsum(lengths)]))
return edge_sets | python | def _get_cartesian_edge_set(self):
"""
For the GC2 calculations a set of cartesian representations of the
fault edges are needed. In this present case we use a common cartesian
framework for all edges, as opposed to defining a separate orthographic
projection per edge
"""
# Get projection space for cartesian projection
edge_sets = numpy.vstack(self.edge_set)
west, east, north, south = utils.get_spherical_bounding_box(
edge_sets[:, 0],
edge_sets[:, 1])
self.proj = utils.OrthographicProjection(west, east, north, south)
for edges in self.edge_set:
# Project edges into cartesian space
px, py = self.proj(edges[:, 0], edges[:, 1])
# Store the two end-points of the trace
self.cartesian_endpoints.append(
numpy.array([[px[0], py[0], edges[0, 2]],
[px[-1], py[-1], edges[-1, 2]]]))
self.cartesian_edges.append(numpy.column_stack([px, py,
edges[:, 2]]))
# Get surface length vector for the trace - easier in cartesian
lengths = numpy.sqrt((px[:-1] - px[1:]) ** 2. +
(py[:-1] - py[1:]) ** 2.)
self.length_set.append(lengths)
# Get cumulative surface length vector
self.cum_length_set.append(
numpy.hstack([0., numpy.cumsum(lengths)]))
return edge_sets | [
"def",
"_get_cartesian_edge_set",
"(",
"self",
")",
":",
"# Get projection space for cartesian projection",
"edge_sets",
"=",
"numpy",
".",
"vstack",
"(",
"self",
".",
"edge_set",
")",
"west",
",",
"east",
",",
"north",
",",
"south",
"=",
"utils",
".",
"get_spherical_bounding_box",
"(",
"edge_sets",
"[",
":",
",",
"0",
"]",
",",
"edge_sets",
"[",
":",
",",
"1",
"]",
")",
"self",
".",
"proj",
"=",
"utils",
".",
"OrthographicProjection",
"(",
"west",
",",
"east",
",",
"north",
",",
"south",
")",
"for",
"edges",
"in",
"self",
".",
"edge_set",
":",
"# Project edges into cartesian space",
"px",
",",
"py",
"=",
"self",
".",
"proj",
"(",
"edges",
"[",
":",
",",
"0",
"]",
",",
"edges",
"[",
":",
",",
"1",
"]",
")",
"# Store the two end-points of the trace",
"self",
".",
"cartesian_endpoints",
".",
"append",
"(",
"numpy",
".",
"array",
"(",
"[",
"[",
"px",
"[",
"0",
"]",
",",
"py",
"[",
"0",
"]",
",",
"edges",
"[",
"0",
",",
"2",
"]",
"]",
",",
"[",
"px",
"[",
"-",
"1",
"]",
",",
"py",
"[",
"-",
"1",
"]",
",",
"edges",
"[",
"-",
"1",
",",
"2",
"]",
"]",
"]",
")",
")",
"self",
".",
"cartesian_edges",
".",
"append",
"(",
"numpy",
".",
"column_stack",
"(",
"[",
"px",
",",
"py",
",",
"edges",
"[",
":",
",",
"2",
"]",
"]",
")",
")",
"# Get surface length vector for the trace - easier in cartesian",
"lengths",
"=",
"numpy",
".",
"sqrt",
"(",
"(",
"px",
"[",
":",
"-",
"1",
"]",
"-",
"px",
"[",
"1",
":",
"]",
")",
"**",
"2.",
"+",
"(",
"py",
"[",
":",
"-",
"1",
"]",
"-",
"py",
"[",
"1",
":",
"]",
")",
"**",
"2.",
")",
"self",
".",
"length_set",
".",
"append",
"(",
"lengths",
")",
"# Get cumulative surface length vector",
"self",
".",
"cum_length_set",
".",
"append",
"(",
"numpy",
".",
"hstack",
"(",
"[",
"0.",
",",
"numpy",
".",
"cumsum",
"(",
"lengths",
")",
"]",
")",
")",
"return",
"edge_sets"
] | For the GC2 calculations a set of cartesian representations of the
fault edges are needed. In this present case we use a common cartesian
framework for all edges, as opposed to defining a separate orthographic
projection per edge | [
"For",
"the",
"GC2",
"calculations",
"a",
"set",
"of",
"cartesian",
"representations",
"of",
"the",
"fault",
"edges",
"are",
"needed",
".",
"In",
"this",
"present",
"case",
"we",
"use",
"a",
"common",
"cartesian",
"framework",
"for",
"all",
"edges",
"as",
"opposed",
"to",
"defining",
"a",
"separate",
"orthographic",
"projection",
"per",
"edge"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/multi.py#L362-L392 | train | 233,460 |
gem/oq-engine | openquake/hazardlib/geo/surface/multi.py | MultiSurface._get_gc2_coordinates_for_rupture | def _get_gc2_coordinates_for_rupture(self, edge_sets):
"""
Calculates the GC2 coordinates for the nodes of the upper edge of the
fault
"""
# Establish GC2 length - for use with Ry0
rup_gc2t, rup_gc2u = self.get_generalised_coordinates(
edge_sets[:, 0], edge_sets[:, 1])
# GC2 length should be the largest positive GC2 value of the edges
self.gc_length = numpy.max(rup_gc2u) | python | def _get_gc2_coordinates_for_rupture(self, edge_sets):
"""
Calculates the GC2 coordinates for the nodes of the upper edge of the
fault
"""
# Establish GC2 length - for use with Ry0
rup_gc2t, rup_gc2u = self.get_generalised_coordinates(
edge_sets[:, 0], edge_sets[:, 1])
# GC2 length should be the largest positive GC2 value of the edges
self.gc_length = numpy.max(rup_gc2u) | [
"def",
"_get_gc2_coordinates_for_rupture",
"(",
"self",
",",
"edge_sets",
")",
":",
"# Establish GC2 length - for use with Ry0",
"rup_gc2t",
",",
"rup_gc2u",
"=",
"self",
".",
"get_generalised_coordinates",
"(",
"edge_sets",
"[",
":",
",",
"0",
"]",
",",
"edge_sets",
"[",
":",
",",
"1",
"]",
")",
"# GC2 length should be the largest positive GC2 value of the edges",
"self",
".",
"gc_length",
"=",
"numpy",
".",
"max",
"(",
"rup_gc2u",
")"
] | Calculates the GC2 coordinates for the nodes of the upper edge of the
fault | [
"Calculates",
"the",
"GC2",
"coordinates",
"for",
"the",
"nodes",
"of",
"the",
"upper",
"edge",
"of",
"the",
"fault"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/multi.py#L454-L464 | train | 233,461 |
gem/oq-engine | openquake/hazardlib/geo/surface/multi.py | MultiSurface._get_ut_i | def _get_ut_i(self, seg, sx, sy):
"""
Returns the U and T coordinate for a specific trace segment
:param seg:
End points of the segment edge
:param sx:
Sites longitudes rendered into coordinate system
:param sy:
Sites latitudes rendered into coordinate system
"""
p0x, p0y, p1x, p1y = seg[0, 0], seg[0, 1], seg[1, 0], seg[1, 1]
# Unit vector normal to strike
t_i_vec = [p1y - p0y, -(p1x - p0x), 0.0]
t_i_hat = t_i_vec / numpy.linalg.norm(t_i_vec)
# Unit vector along strike
u_i_vec = [p1x - p0x, p1y - p0y, 0.0]
u_i_hat = u_i_vec / numpy.linalg.norm(u_i_vec)
# Vectors from P0 to sites
rsite = numpy.column_stack([sx - p0x, sy - p0y])
return numpy.sum(u_i_hat[:-1] * rsite, axis=1),\
numpy.sum(t_i_hat[:-1] * rsite, axis=1) | python | def _get_ut_i(self, seg, sx, sy):
"""
Returns the U and T coordinate for a specific trace segment
:param seg:
End points of the segment edge
:param sx:
Sites longitudes rendered into coordinate system
:param sy:
Sites latitudes rendered into coordinate system
"""
p0x, p0y, p1x, p1y = seg[0, 0], seg[0, 1], seg[1, 0], seg[1, 1]
# Unit vector normal to strike
t_i_vec = [p1y - p0y, -(p1x - p0x), 0.0]
t_i_hat = t_i_vec / numpy.linalg.norm(t_i_vec)
# Unit vector along strike
u_i_vec = [p1x - p0x, p1y - p0y, 0.0]
u_i_hat = u_i_vec / numpy.linalg.norm(u_i_vec)
# Vectors from P0 to sites
rsite = numpy.column_stack([sx - p0x, sy - p0y])
return numpy.sum(u_i_hat[:-1] * rsite, axis=1),\
numpy.sum(t_i_hat[:-1] * rsite, axis=1) | [
"def",
"_get_ut_i",
"(",
"self",
",",
"seg",
",",
"sx",
",",
"sy",
")",
":",
"p0x",
",",
"p0y",
",",
"p1x",
",",
"p1y",
"=",
"seg",
"[",
"0",
",",
"0",
"]",
",",
"seg",
"[",
"0",
",",
"1",
"]",
",",
"seg",
"[",
"1",
",",
"0",
"]",
",",
"seg",
"[",
"1",
",",
"1",
"]",
"# Unit vector normal to strike",
"t_i_vec",
"=",
"[",
"p1y",
"-",
"p0y",
",",
"-",
"(",
"p1x",
"-",
"p0x",
")",
",",
"0.0",
"]",
"t_i_hat",
"=",
"t_i_vec",
"/",
"numpy",
".",
"linalg",
".",
"norm",
"(",
"t_i_vec",
")",
"# Unit vector along strike",
"u_i_vec",
"=",
"[",
"p1x",
"-",
"p0x",
",",
"p1y",
"-",
"p0y",
",",
"0.0",
"]",
"u_i_hat",
"=",
"u_i_vec",
"/",
"numpy",
".",
"linalg",
".",
"norm",
"(",
"u_i_vec",
")",
"# Vectors from P0 to sites",
"rsite",
"=",
"numpy",
".",
"column_stack",
"(",
"[",
"sx",
"-",
"p0x",
",",
"sy",
"-",
"p0y",
"]",
")",
"return",
"numpy",
".",
"sum",
"(",
"u_i_hat",
"[",
":",
"-",
"1",
"]",
"*",
"rsite",
",",
"axis",
"=",
"1",
")",
",",
"numpy",
".",
"sum",
"(",
"t_i_hat",
"[",
":",
"-",
"1",
"]",
"*",
"rsite",
",",
"axis",
"=",
"1",
")"
] | Returns the U and T coordinate for a specific trace segment
:param seg:
End points of the segment edge
:param sx:
Sites longitudes rendered into coordinate system
:param sy:
Sites latitudes rendered into coordinate system | [
"Returns",
"the",
"U",
"and",
"T",
"coordinate",
"for",
"a",
"specific",
"trace",
"segment"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/multi.py#L466-L489 | train | 233,462 |
gem/oq-engine | openquake/hazardlib/geo/surface/multi.py | MultiSurface.get_rx_distance | def get_rx_distance(self, mesh):
"""
For each point determine the corresponding rx distance using the GC2
configuration.
See :meth:`superclass method
<.base.BaseSurface.get_rx_distance>`
for spec of input and result values.
"""
# If the GC2 calculations have already been computed (by invoking Ry0
# first) and the mesh is identical then class has GC2 attributes
# already pre-calculated
if not self.tmp_mesh or (self.tmp_mesh == mesh):
self.gc2t, self.gc2u = self.get_generalised_coordinates(mesh.lons,
mesh.lats)
# Update mesh
self.tmp_mesh = deepcopy(mesh)
# Rx coordinate is taken directly from gc2t
return self.gc2t | python | def get_rx_distance(self, mesh):
"""
For each point determine the corresponding rx distance using the GC2
configuration.
See :meth:`superclass method
<.base.BaseSurface.get_rx_distance>`
for spec of input and result values.
"""
# If the GC2 calculations have already been computed (by invoking Ry0
# first) and the mesh is identical then class has GC2 attributes
# already pre-calculated
if not self.tmp_mesh or (self.tmp_mesh == mesh):
self.gc2t, self.gc2u = self.get_generalised_coordinates(mesh.lons,
mesh.lats)
# Update mesh
self.tmp_mesh = deepcopy(mesh)
# Rx coordinate is taken directly from gc2t
return self.gc2t | [
"def",
"get_rx_distance",
"(",
"self",
",",
"mesh",
")",
":",
"# If the GC2 calculations have already been computed (by invoking Ry0",
"# first) and the mesh is identical then class has GC2 attributes",
"# already pre-calculated",
"if",
"not",
"self",
".",
"tmp_mesh",
"or",
"(",
"self",
".",
"tmp_mesh",
"==",
"mesh",
")",
":",
"self",
".",
"gc2t",
",",
"self",
".",
"gc2u",
"=",
"self",
".",
"get_generalised_coordinates",
"(",
"mesh",
".",
"lons",
",",
"mesh",
".",
"lats",
")",
"# Update mesh",
"self",
".",
"tmp_mesh",
"=",
"deepcopy",
"(",
"mesh",
")",
"# Rx coordinate is taken directly from gc2t",
"return",
"self",
".",
"gc2t"
] | For each point determine the corresponding rx distance using the GC2
configuration.
See :meth:`superclass method
<.base.BaseSurface.get_rx_distance>`
for spec of input and result values. | [
"For",
"each",
"point",
"determine",
"the",
"corresponding",
"rx",
"distance",
"using",
"the",
"GC2",
"configuration",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/multi.py#L570-L588 | train | 233,463 |
gem/oq-engine | openquake/hazardlib/geo/surface/multi.py | MultiSurface.get_ry0_distance | def get_ry0_distance(self, mesh):
"""
For each point determine the corresponding Ry0 distance using the GC2
configuration.
See :meth:`superclass method
<.base.BaseSurface.get_ry0_distance>`
for spec of input and result values.
"""
# If the GC2 calculations have already been computed (by invoking Ry0
# first) and the mesh is identical then class has GC2 attributes
# already pre-calculated
if not self.tmp_mesh or (self.tmp_mesh == mesh):
# If that's not the case, or the mesh is different then
# re-compute GC2 configuration
self.gc2t, self.gc2u = self.get_generalised_coordinates(mesh.lons,
mesh.lats)
# Update mesh
self.tmp_mesh = deepcopy(mesh)
# Default value ry0 (for sites within fault length) is 0.0
ry0 = numpy.zeros_like(self.gc2u, dtype=float)
# For sites with negative gc2u (off the initial point of the fault)
# take the absolute value of gc2u
neg_gc2u = self.gc2u < 0.0
ry0[neg_gc2u] = numpy.fabs(self.gc2u[neg_gc2u])
# Sites off the end of the fault have values shifted by the
# GC2 length of the fault
pos_gc2u = self.gc2u >= self.gc_length
ry0[pos_gc2u] = self.gc2u[pos_gc2u] - self.gc_length
return ry0 | python | def get_ry0_distance(self, mesh):
"""
For each point determine the corresponding Ry0 distance using the GC2
configuration.
See :meth:`superclass method
<.base.BaseSurface.get_ry0_distance>`
for spec of input and result values.
"""
# If the GC2 calculations have already been computed (by invoking Ry0
# first) and the mesh is identical then class has GC2 attributes
# already pre-calculated
if not self.tmp_mesh or (self.tmp_mesh == mesh):
# If that's not the case, or the mesh is different then
# re-compute GC2 configuration
self.gc2t, self.gc2u = self.get_generalised_coordinates(mesh.lons,
mesh.lats)
# Update mesh
self.tmp_mesh = deepcopy(mesh)
# Default value ry0 (for sites within fault length) is 0.0
ry0 = numpy.zeros_like(self.gc2u, dtype=float)
# For sites with negative gc2u (off the initial point of the fault)
# take the absolute value of gc2u
neg_gc2u = self.gc2u < 0.0
ry0[neg_gc2u] = numpy.fabs(self.gc2u[neg_gc2u])
# Sites off the end of the fault have values shifted by the
# GC2 length of the fault
pos_gc2u = self.gc2u >= self.gc_length
ry0[pos_gc2u] = self.gc2u[pos_gc2u] - self.gc_length
return ry0 | [
"def",
"get_ry0_distance",
"(",
"self",
",",
"mesh",
")",
":",
"# If the GC2 calculations have already been computed (by invoking Ry0",
"# first) and the mesh is identical then class has GC2 attributes",
"# already pre-calculated",
"if",
"not",
"self",
".",
"tmp_mesh",
"or",
"(",
"self",
".",
"tmp_mesh",
"==",
"mesh",
")",
":",
"# If that's not the case, or the mesh is different then",
"# re-compute GC2 configuration",
"self",
".",
"gc2t",
",",
"self",
".",
"gc2u",
"=",
"self",
".",
"get_generalised_coordinates",
"(",
"mesh",
".",
"lons",
",",
"mesh",
".",
"lats",
")",
"# Update mesh",
"self",
".",
"tmp_mesh",
"=",
"deepcopy",
"(",
"mesh",
")",
"# Default value ry0 (for sites within fault length) is 0.0",
"ry0",
"=",
"numpy",
".",
"zeros_like",
"(",
"self",
".",
"gc2u",
",",
"dtype",
"=",
"float",
")",
"# For sites with negative gc2u (off the initial point of the fault)",
"# take the absolute value of gc2u",
"neg_gc2u",
"=",
"self",
".",
"gc2u",
"<",
"0.0",
"ry0",
"[",
"neg_gc2u",
"]",
"=",
"numpy",
".",
"fabs",
"(",
"self",
".",
"gc2u",
"[",
"neg_gc2u",
"]",
")",
"# Sites off the end of the fault have values shifted by the",
"# GC2 length of the fault",
"pos_gc2u",
"=",
"self",
".",
"gc2u",
">=",
"self",
".",
"gc_length",
"ry0",
"[",
"pos_gc2u",
"]",
"=",
"self",
".",
"gc2u",
"[",
"pos_gc2u",
"]",
"-",
"self",
".",
"gc_length",
"return",
"ry0"
] | For each point determine the corresponding Ry0 distance using the GC2
configuration.
See :meth:`superclass method
<.base.BaseSurface.get_ry0_distance>`
for spec of input and result values. | [
"For",
"each",
"point",
"determine",
"the",
"corresponding",
"Ry0",
"distance",
"using",
"the",
"GC2",
"configuration",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/multi.py#L590-L622 | train | 233,464 |
gem/oq-engine | openquake/hmtk/comparison/rate_grids.py | RateGrid.from_model_files | def from_model_files(cls, limits, input_model, investigation_time=1.0,
simple_mesh_spacing=1.0, complex_mesh_spacing=5.0,
mfd_width=0.1, area_discretisation=10.0):
"""
Reads the hazard model from a file
:param list limits:
Grid configuration [west, east, xspc, south, north, yspc,
upper, lower, zspc]
:param str input_model:
Path to input source model
:param float investigation_time:
Investigation time of Poisson model
:param float simple_mesh_spacing:
Rupture mesh spacing of simple fault (km)
:param float complex_mesh_spacing:
Rupture mesh spacing of complex fault (km)
:param float mfd_width:
Spacing (in magnitude units) of MFD
:param float area_discretisation:
Spacing of discretisation of area source (km)
"""
converter = SourceConverter(investigation_time,
simple_mesh_spacing,
complex_mesh_spacing,
mfd_width,
area_discretisation)
sources = []
for grp in nrml.to_python(input_model, converter):
sources.extend(grp.sources)
return cls(limits, sources, area_discretisation) | python | def from_model_files(cls, limits, input_model, investigation_time=1.0,
simple_mesh_spacing=1.0, complex_mesh_spacing=5.0,
mfd_width=0.1, area_discretisation=10.0):
"""
Reads the hazard model from a file
:param list limits:
Grid configuration [west, east, xspc, south, north, yspc,
upper, lower, zspc]
:param str input_model:
Path to input source model
:param float investigation_time:
Investigation time of Poisson model
:param float simple_mesh_spacing:
Rupture mesh spacing of simple fault (km)
:param float complex_mesh_spacing:
Rupture mesh spacing of complex fault (km)
:param float mfd_width:
Spacing (in magnitude units) of MFD
:param float area_discretisation:
Spacing of discretisation of area source (km)
"""
converter = SourceConverter(investigation_time,
simple_mesh_spacing,
complex_mesh_spacing,
mfd_width,
area_discretisation)
sources = []
for grp in nrml.to_python(input_model, converter):
sources.extend(grp.sources)
return cls(limits, sources, area_discretisation) | [
"def",
"from_model_files",
"(",
"cls",
",",
"limits",
",",
"input_model",
",",
"investigation_time",
"=",
"1.0",
",",
"simple_mesh_spacing",
"=",
"1.0",
",",
"complex_mesh_spacing",
"=",
"5.0",
",",
"mfd_width",
"=",
"0.1",
",",
"area_discretisation",
"=",
"10.0",
")",
":",
"converter",
"=",
"SourceConverter",
"(",
"investigation_time",
",",
"simple_mesh_spacing",
",",
"complex_mesh_spacing",
",",
"mfd_width",
",",
"area_discretisation",
")",
"sources",
"=",
"[",
"]",
"for",
"grp",
"in",
"nrml",
".",
"to_python",
"(",
"input_model",
",",
"converter",
")",
":",
"sources",
".",
"extend",
"(",
"grp",
".",
"sources",
")",
"return",
"cls",
"(",
"limits",
",",
"sources",
",",
"area_discretisation",
")"
] | Reads the hazard model from a file
:param list limits:
Grid configuration [west, east, xspc, south, north, yspc,
upper, lower, zspc]
:param str input_model:
Path to input source model
:param float investigation_time:
Investigation time of Poisson model
:param float simple_mesh_spacing:
Rupture mesh spacing of simple fault (km)
:param float complex_mesh_spacing:
Rupture mesh spacing of complex fault (km)
:param float mfd_width:
Spacing (in magnitude units) of MFD
:param float area_discretisation:
Spacing of discretisation of area source (km) | [
"Reads",
"the",
"hazard",
"model",
"from",
"a",
"file"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/comparison/rate_grids.py#L114-L144 | train | 233,465 |
gem/oq-engine | openquake/hmtk/comparison/rate_grids.py | RateGrid.get_rates | def get_rates(self, mmin, mmax=np.inf):
"""
Returns the cumulative rates greater than Mmin
:param float mmin:
Minimum magnitude
"""
nsrcs = self.number_sources()
for iloc, source in enumerate(self.source_model):
print("Source Number %s of %s, Name = %s, Typology = %s" % (
iloc + 1,
nsrcs,
source.name,
source.__class__.__name__))
if isinstance(source, CharacteristicFaultSource):
self._get_fault_rates(source, mmin, mmax)
elif isinstance(source, ComplexFaultSource):
self._get_fault_rates(source, mmin, mmax)
elif isinstance(source, SimpleFaultSource):
self._get_fault_rates(source, mmin, mmax)
elif isinstance(source, AreaSource):
self._get_area_rates(source, mmin, mmax)
elif isinstance(source, PointSource):
self._get_point_rates(source, mmin, mmax)
else:
print("Source type %s not recognised - skipping!" % source)
continue | python | def get_rates(self, mmin, mmax=np.inf):
"""
Returns the cumulative rates greater than Mmin
:param float mmin:
Minimum magnitude
"""
nsrcs = self.number_sources()
for iloc, source in enumerate(self.source_model):
print("Source Number %s of %s, Name = %s, Typology = %s" % (
iloc + 1,
nsrcs,
source.name,
source.__class__.__name__))
if isinstance(source, CharacteristicFaultSource):
self._get_fault_rates(source, mmin, mmax)
elif isinstance(source, ComplexFaultSource):
self._get_fault_rates(source, mmin, mmax)
elif isinstance(source, SimpleFaultSource):
self._get_fault_rates(source, mmin, mmax)
elif isinstance(source, AreaSource):
self._get_area_rates(source, mmin, mmax)
elif isinstance(source, PointSource):
self._get_point_rates(source, mmin, mmax)
else:
print("Source type %s not recognised - skipping!" % source)
continue | [
"def",
"get_rates",
"(",
"self",
",",
"mmin",
",",
"mmax",
"=",
"np",
".",
"inf",
")",
":",
"nsrcs",
"=",
"self",
".",
"number_sources",
"(",
")",
"for",
"iloc",
",",
"source",
"in",
"enumerate",
"(",
"self",
".",
"source_model",
")",
":",
"print",
"(",
"\"Source Number %s of %s, Name = %s, Typology = %s\"",
"%",
"(",
"iloc",
"+",
"1",
",",
"nsrcs",
",",
"source",
".",
"name",
",",
"source",
".",
"__class__",
".",
"__name__",
")",
")",
"if",
"isinstance",
"(",
"source",
",",
"CharacteristicFaultSource",
")",
":",
"self",
".",
"_get_fault_rates",
"(",
"source",
",",
"mmin",
",",
"mmax",
")",
"elif",
"isinstance",
"(",
"source",
",",
"ComplexFaultSource",
")",
":",
"self",
".",
"_get_fault_rates",
"(",
"source",
",",
"mmin",
",",
"mmax",
")",
"elif",
"isinstance",
"(",
"source",
",",
"SimpleFaultSource",
")",
":",
"self",
".",
"_get_fault_rates",
"(",
"source",
",",
"mmin",
",",
"mmax",
")",
"elif",
"isinstance",
"(",
"source",
",",
"AreaSource",
")",
":",
"self",
".",
"_get_area_rates",
"(",
"source",
",",
"mmin",
",",
"mmax",
")",
"elif",
"isinstance",
"(",
"source",
",",
"PointSource",
")",
":",
"self",
".",
"_get_point_rates",
"(",
"source",
",",
"mmin",
",",
"mmax",
")",
"else",
":",
"print",
"(",
"\"Source type %s not recognised - skipping!\"",
"%",
"source",
")",
"continue"
] | Returns the cumulative rates greater than Mmin
:param float mmin:
Minimum magnitude | [
"Returns",
"the",
"cumulative",
"rates",
"greater",
"than",
"Mmin"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/comparison/rate_grids.py#L152-L178 | train | 233,466 |
gem/oq-engine | openquake/hmtk/comparison/rate_grids.py | RateGrid._get_point_location | def _get_point_location(self, location):
"""
Returns the location in the output grid corresponding to the cell in
which the epicentre lays
:param location:
Source hypocentre as instance of :class:
openquake.hazardlib.geo.point.Point
:returns:
xloc - Location of longitude cell
yloc - Location of latitude cell
"""
if (location.longitude < self.xlim[0]) or\
(location.longitude > self.xlim[-1]):
return None, None
xloc = int(((location.longitude - self.xlim[0]) / self.xspc) + 1E-7)
if (location.latitude < self.ylim[0]) or\
(location.latitude > self.ylim[-1]):
return None, None
yloc = int(((location.latitude - self.ylim[0]) / self.yspc) + 1E-7)
return xloc, yloc | python | def _get_point_location(self, location):
"""
Returns the location in the output grid corresponding to the cell in
which the epicentre lays
:param location:
Source hypocentre as instance of :class:
openquake.hazardlib.geo.point.Point
:returns:
xloc - Location of longitude cell
yloc - Location of latitude cell
"""
if (location.longitude < self.xlim[0]) or\
(location.longitude > self.xlim[-1]):
return None, None
xloc = int(((location.longitude - self.xlim[0]) / self.xspc) + 1E-7)
if (location.latitude < self.ylim[0]) or\
(location.latitude > self.ylim[-1]):
return None, None
yloc = int(((location.latitude - self.ylim[0]) / self.yspc) + 1E-7)
return xloc, yloc | [
"def",
"_get_point_location",
"(",
"self",
",",
"location",
")",
":",
"if",
"(",
"location",
".",
"longitude",
"<",
"self",
".",
"xlim",
"[",
"0",
"]",
")",
"or",
"(",
"location",
".",
"longitude",
">",
"self",
".",
"xlim",
"[",
"-",
"1",
"]",
")",
":",
"return",
"None",
",",
"None",
"xloc",
"=",
"int",
"(",
"(",
"(",
"location",
".",
"longitude",
"-",
"self",
".",
"xlim",
"[",
"0",
"]",
")",
"/",
"self",
".",
"xspc",
")",
"+",
"1E-7",
")",
"if",
"(",
"location",
".",
"latitude",
"<",
"self",
".",
"ylim",
"[",
"0",
"]",
")",
"or",
"(",
"location",
".",
"latitude",
">",
"self",
".",
"ylim",
"[",
"-",
"1",
"]",
")",
":",
"return",
"None",
",",
"None",
"yloc",
"=",
"int",
"(",
"(",
"(",
"location",
".",
"latitude",
"-",
"self",
".",
"ylim",
"[",
"0",
"]",
")",
"/",
"self",
".",
"yspc",
")",
"+",
"1E-7",
")",
"return",
"xloc",
",",
"yloc"
] | Returns the location in the output grid corresponding to the cell in
which the epicentre lays
:param location:
Source hypocentre as instance of :class:
openquake.hazardlib.geo.point.Point
:returns:
xloc - Location of longitude cell
yloc - Location of latitude cell | [
"Returns",
"the",
"location",
"in",
"the",
"output",
"grid",
"corresponding",
"to",
"the",
"cell",
"in",
"which",
"the",
"epicentre",
"lays"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/comparison/rate_grids.py#L180-L200 | train | 233,467 |
gem/oq-engine | openquake/hmtk/comparison/rate_grids.py | RateGrid._get_area_rates | def _get_area_rates(self, source, mmin, mmax=np.inf):
"""
Adds the rates from the area source by discretising the source
to a set of point sources
:param source:
Area source as instance of :class:
openquake.hazardlib.source.area.AreaSource
"""
points = list(source)
for point in points:
self._get_point_rates(point, mmin, mmax) | python | def _get_area_rates(self, source, mmin, mmax=np.inf):
"""
Adds the rates from the area source by discretising the source
to a set of point sources
:param source:
Area source as instance of :class:
openquake.hazardlib.source.area.AreaSource
"""
points = list(source)
for point in points:
self._get_point_rates(point, mmin, mmax) | [
"def",
"_get_area_rates",
"(",
"self",
",",
"source",
",",
"mmin",
",",
"mmax",
"=",
"np",
".",
"inf",
")",
":",
"points",
"=",
"list",
"(",
"source",
")",
"for",
"point",
"in",
"points",
":",
"self",
".",
"_get_point_rates",
"(",
"point",
",",
"mmin",
",",
"mmax",
")"
] | Adds the rates from the area source by discretising the source
to a set of point sources
:param source:
Area source as instance of :class:
openquake.hazardlib.source.area.AreaSource | [
"Adds",
"the",
"rates",
"from",
"the",
"area",
"source",
"by",
"discretising",
"the",
"source",
"to",
"a",
"set",
"of",
"point",
"sources"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/comparison/rate_grids.py#L231-L242 | train | 233,468 |
gem/oq-engine | openquake/hazardlib/gsim/megawati_pan_2010.py | MegawatiPan2010._get_distance_scaling | def _get_distance_scaling(self, C, mag, rhypo):
"""
Returns the distance scalig term
"""
return (C["a3"] * np.log(rhypo)) + (C["a4"] + C["a5"] * mag) * rhypo | python | def _get_distance_scaling(self, C, mag, rhypo):
"""
Returns the distance scalig term
"""
return (C["a3"] * np.log(rhypo)) + (C["a4"] + C["a5"] * mag) * rhypo | [
"def",
"_get_distance_scaling",
"(",
"self",
",",
"C",
",",
"mag",
",",
"rhypo",
")",
":",
"return",
"(",
"C",
"[",
"\"a3\"",
"]",
"*",
"np",
".",
"log",
"(",
"rhypo",
")",
")",
"+",
"(",
"C",
"[",
"\"a4\"",
"]",
"+",
"C",
"[",
"\"a5\"",
"]",
"*",
"mag",
")",
"*",
"rhypo"
] | Returns the distance scalig term | [
"Returns",
"the",
"distance",
"scalig",
"term"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/megawati_pan_2010.py#L98-L102 | train | 233,469 |
gem/oq-engine | openquake/hazardlib/gsim/rietbrock_2013.py | RietbrockEtAl2013SelfSimilar._get_distance_scaling_term | def _get_distance_scaling_term(self, C, rjb, mag):
"""
Returns the distance scaling component of the model
Equation 10, Page 63
"""
# Depth adjusted distance, equation 11 (Page 63)
rval = np.sqrt(rjb ** 2.0 + C["c11"] ** 2.0)
f_0, f_1, f_2 = self._get_distance_segment_coefficients(rval)
return ((C["c4"] + C["c5"] * mag) * f_0 +
(C["c6"] + C["c7"] * mag) * f_1 +
(C["c8"] + C["c9"] * mag) * f_2 +
(C["c10"] * rval)) | python | def _get_distance_scaling_term(self, C, rjb, mag):
"""
Returns the distance scaling component of the model
Equation 10, Page 63
"""
# Depth adjusted distance, equation 11 (Page 63)
rval = np.sqrt(rjb ** 2.0 + C["c11"] ** 2.0)
f_0, f_1, f_2 = self._get_distance_segment_coefficients(rval)
return ((C["c4"] + C["c5"] * mag) * f_0 +
(C["c6"] + C["c7"] * mag) * f_1 +
(C["c8"] + C["c9"] * mag) * f_2 +
(C["c10"] * rval)) | [
"def",
"_get_distance_scaling_term",
"(",
"self",
",",
"C",
",",
"rjb",
",",
"mag",
")",
":",
"# Depth adjusted distance, equation 11 (Page 63)",
"rval",
"=",
"np",
".",
"sqrt",
"(",
"rjb",
"**",
"2.0",
"+",
"C",
"[",
"\"c11\"",
"]",
"**",
"2.0",
")",
"f_0",
",",
"f_1",
",",
"f_2",
"=",
"self",
".",
"_get_distance_segment_coefficients",
"(",
"rval",
")",
"return",
"(",
"(",
"C",
"[",
"\"c4\"",
"]",
"+",
"C",
"[",
"\"c5\"",
"]",
"*",
"mag",
")",
"*",
"f_0",
"+",
"(",
"C",
"[",
"\"c6\"",
"]",
"+",
"C",
"[",
"\"c7\"",
"]",
"*",
"mag",
")",
"*",
"f_1",
"+",
"(",
"C",
"[",
"\"c8\"",
"]",
"+",
"C",
"[",
"\"c9\"",
"]",
"*",
"mag",
")",
"*",
"f_2",
"+",
"(",
"C",
"[",
"\"c10\"",
"]",
"*",
"rval",
")",
")"
] | Returns the distance scaling component of the model
Equation 10, Page 63 | [
"Returns",
"the",
"distance",
"scaling",
"component",
"of",
"the",
"model",
"Equation",
"10",
"Page",
"63"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/rietbrock_2013.py#L109-L120 | train | 233,470 |
gem/oq-engine | openquake/hazardlib/gsim/rietbrock_2013.py | RietbrockEtAl2013SelfSimilar._get_distance_segment_coefficients | def _get_distance_segment_coefficients(self, rval):
"""
Returns the coefficients describing the distance attenuation shape
for three different distance bins, equations 12a - 12c
"""
# Get distance segment ends
nsites = len(rval)
# Equation 12a
f_0 = np.log10(self.CONSTS["r0"] / rval)
f_0[rval > self.CONSTS["r0"]] = 0.0
# Equation 12b
f_1 = np.log10(rval)
f_1[rval > self.CONSTS["r1"]] = np.log10(self.CONSTS["r1"])
# Equation 12c
f_2 = np.log10(rval / self.CONSTS["r2"])
f_2[rval <= self.CONSTS["r2"]] = 0.0
return f_0, f_1, f_2 | python | def _get_distance_segment_coefficients(self, rval):
"""
Returns the coefficients describing the distance attenuation shape
for three different distance bins, equations 12a - 12c
"""
# Get distance segment ends
nsites = len(rval)
# Equation 12a
f_0 = np.log10(self.CONSTS["r0"] / rval)
f_0[rval > self.CONSTS["r0"]] = 0.0
# Equation 12b
f_1 = np.log10(rval)
f_1[rval > self.CONSTS["r1"]] = np.log10(self.CONSTS["r1"])
# Equation 12c
f_2 = np.log10(rval / self.CONSTS["r2"])
f_2[rval <= self.CONSTS["r2"]] = 0.0
return f_0, f_1, f_2 | [
"def",
"_get_distance_segment_coefficients",
"(",
"self",
",",
"rval",
")",
":",
"# Get distance segment ends",
"nsites",
"=",
"len",
"(",
"rval",
")",
"# Equation 12a",
"f_0",
"=",
"np",
".",
"log10",
"(",
"self",
".",
"CONSTS",
"[",
"\"r0\"",
"]",
"/",
"rval",
")",
"f_0",
"[",
"rval",
">",
"self",
".",
"CONSTS",
"[",
"\"r0\"",
"]",
"]",
"=",
"0.0",
"# Equation 12b",
"f_1",
"=",
"np",
".",
"log10",
"(",
"rval",
")",
"f_1",
"[",
"rval",
">",
"self",
".",
"CONSTS",
"[",
"\"r1\"",
"]",
"]",
"=",
"np",
".",
"log10",
"(",
"self",
".",
"CONSTS",
"[",
"\"r1\"",
"]",
")",
"# Equation 12c",
"f_2",
"=",
"np",
".",
"log10",
"(",
"rval",
"/",
"self",
".",
"CONSTS",
"[",
"\"r2\"",
"]",
")",
"f_2",
"[",
"rval",
"<=",
"self",
".",
"CONSTS",
"[",
"\"r2\"",
"]",
"]",
"=",
"0.0",
"return",
"f_0",
",",
"f_1",
",",
"f_2"
] | Returns the coefficients describing the distance attenuation shape
for three different distance bins, equations 12a - 12c | [
"Returns",
"the",
"coefficients",
"describing",
"the",
"distance",
"attenuation",
"shape",
"for",
"three",
"different",
"distance",
"bins",
"equations",
"12a",
"-",
"12c"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/rietbrock_2013.py#L122-L139 | train | 233,471 |
gem/oq-engine | openquake/commonlib/readinput.py | collect_files | def collect_files(dirpath, cond=lambda fullname: True):
"""
Recursively collect the files contained inside dirpath.
:param dirpath: path to a readable directory
:param cond: condition on the path to collect the file
"""
files = []
for fname in os.listdir(dirpath):
fullname = os.path.join(dirpath, fname)
if os.path.isdir(fullname): # navigate inside
files.extend(collect_files(fullname))
else: # collect files
if cond(fullname):
files.append(fullname)
return files | python | def collect_files(dirpath, cond=lambda fullname: True):
"""
Recursively collect the files contained inside dirpath.
:param dirpath: path to a readable directory
:param cond: condition on the path to collect the file
"""
files = []
for fname in os.listdir(dirpath):
fullname = os.path.join(dirpath, fname)
if os.path.isdir(fullname): # navigate inside
files.extend(collect_files(fullname))
else: # collect files
if cond(fullname):
files.append(fullname)
return files | [
"def",
"collect_files",
"(",
"dirpath",
",",
"cond",
"=",
"lambda",
"fullname",
":",
"True",
")",
":",
"files",
"=",
"[",
"]",
"for",
"fname",
"in",
"os",
".",
"listdir",
"(",
"dirpath",
")",
":",
"fullname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirpath",
",",
"fname",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"fullname",
")",
":",
"# navigate inside",
"files",
".",
"extend",
"(",
"collect_files",
"(",
"fullname",
")",
")",
"else",
":",
"# collect files",
"if",
"cond",
"(",
"fullname",
")",
":",
"files",
".",
"append",
"(",
"fullname",
")",
"return",
"files"
] | Recursively collect the files contained inside dirpath.
:param dirpath: path to a readable directory
:param cond: condition on the path to collect the file | [
"Recursively",
"collect",
"the",
"files",
"contained",
"inside",
"dirpath",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/readinput.py#L69-L84 | train | 233,472 |
gem/oq-engine | openquake/commonlib/readinput.py | extract_from_zip | def extract_from_zip(path, candidates):
"""
Given a zip archive and a function to detect the presence of a given
filename, unzip the archive into a temporary directory and return the
full path of the file. Raise an IOError if the file cannot be found
within the archive.
:param path: pathname of the archive
:param candidates: list of names to search for
"""
temp_dir = tempfile.mkdtemp()
with zipfile.ZipFile(path) as archive:
archive.extractall(temp_dir)
return [f for f in collect_files(temp_dir)
if os.path.basename(f) in candidates] | python | def extract_from_zip(path, candidates):
"""
Given a zip archive and a function to detect the presence of a given
filename, unzip the archive into a temporary directory and return the
full path of the file. Raise an IOError if the file cannot be found
within the archive.
:param path: pathname of the archive
:param candidates: list of names to search for
"""
temp_dir = tempfile.mkdtemp()
with zipfile.ZipFile(path) as archive:
archive.extractall(temp_dir)
return [f for f in collect_files(temp_dir)
if os.path.basename(f) in candidates] | [
"def",
"extract_from_zip",
"(",
"path",
",",
"candidates",
")",
":",
"temp_dir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"path",
")",
"as",
"archive",
":",
"archive",
".",
"extractall",
"(",
"temp_dir",
")",
"return",
"[",
"f",
"for",
"f",
"in",
"collect_files",
"(",
"temp_dir",
")",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"f",
")",
"in",
"candidates",
"]"
] | Given a zip archive and a function to detect the presence of a given
filename, unzip the archive into a temporary directory and return the
full path of the file. Raise an IOError if the file cannot be found
within the archive.
:param path: pathname of the archive
:param candidates: list of names to search for | [
"Given",
"a",
"zip",
"archive",
"and",
"a",
"function",
"to",
"detect",
"the",
"presence",
"of",
"a",
"given",
"filename",
"unzip",
"the",
"archive",
"into",
"a",
"temporary",
"directory",
"and",
"return",
"the",
"full",
"path",
"of",
"the",
"file",
".",
"Raise",
"an",
"IOError",
"if",
"the",
"file",
"cannot",
"be",
"found",
"within",
"the",
"archive",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/readinput.py#L87-L101 | train | 233,473 |
gem/oq-engine | openquake/commonlib/readinput.py | get_params | def get_params(job_inis, **kw):
"""
Parse one or more INI-style config files.
:param job_inis:
List of configuration files (or list containing a single zip archive)
:param kw:
Optionally override some parameters
:returns:
A dictionary of parameters
"""
input_zip = None
if len(job_inis) == 1 and job_inis[0].endswith('.zip'):
input_zip = job_inis[0]
job_inis = extract_from_zip(
job_inis[0], ['job_hazard.ini', 'job_haz.ini',
'job.ini', 'job_risk.ini'])
not_found = [ini for ini in job_inis if not os.path.exists(ini)]
if not_found: # something was not found
raise IOError('File not found: %s' % not_found[0])
cp = configparser.ConfigParser()
cp.read(job_inis)
# directory containing the config files we're parsing
job_ini = os.path.abspath(job_inis[0])
base_path = decode(os.path.dirname(job_ini))
params = dict(base_path=base_path, inputs={'job_ini': job_ini})
if input_zip:
params['inputs']['input_zip'] = os.path.abspath(input_zip)
for sect in cp.sections():
_update(params, cp.items(sect), base_path)
_update(params, kw.items(), base_path) # override on demand
if params['inputs'].get('reqv'):
# using pointsource_distance=0 because of the reqv approximation
params['pointsource_distance'] = '0'
return params | python | def get_params(job_inis, **kw):
"""
Parse one or more INI-style config files.
:param job_inis:
List of configuration files (or list containing a single zip archive)
:param kw:
Optionally override some parameters
:returns:
A dictionary of parameters
"""
input_zip = None
if len(job_inis) == 1 and job_inis[0].endswith('.zip'):
input_zip = job_inis[0]
job_inis = extract_from_zip(
job_inis[0], ['job_hazard.ini', 'job_haz.ini',
'job.ini', 'job_risk.ini'])
not_found = [ini for ini in job_inis if not os.path.exists(ini)]
if not_found: # something was not found
raise IOError('File not found: %s' % not_found[0])
cp = configparser.ConfigParser()
cp.read(job_inis)
# directory containing the config files we're parsing
job_ini = os.path.abspath(job_inis[0])
base_path = decode(os.path.dirname(job_ini))
params = dict(base_path=base_path, inputs={'job_ini': job_ini})
if input_zip:
params['inputs']['input_zip'] = os.path.abspath(input_zip)
for sect in cp.sections():
_update(params, cp.items(sect), base_path)
_update(params, kw.items(), base_path) # override on demand
if params['inputs'].get('reqv'):
# using pointsource_distance=0 because of the reqv approximation
params['pointsource_distance'] = '0'
return params | [
"def",
"get_params",
"(",
"job_inis",
",",
"*",
"*",
"kw",
")",
":",
"input_zip",
"=",
"None",
"if",
"len",
"(",
"job_inis",
")",
"==",
"1",
"and",
"job_inis",
"[",
"0",
"]",
".",
"endswith",
"(",
"'.zip'",
")",
":",
"input_zip",
"=",
"job_inis",
"[",
"0",
"]",
"job_inis",
"=",
"extract_from_zip",
"(",
"job_inis",
"[",
"0",
"]",
",",
"[",
"'job_hazard.ini'",
",",
"'job_haz.ini'",
",",
"'job.ini'",
",",
"'job_risk.ini'",
"]",
")",
"not_found",
"=",
"[",
"ini",
"for",
"ini",
"in",
"job_inis",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"ini",
")",
"]",
"if",
"not_found",
":",
"# something was not found",
"raise",
"IOError",
"(",
"'File not found: %s'",
"%",
"not_found",
"[",
"0",
"]",
")",
"cp",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"cp",
".",
"read",
"(",
"job_inis",
")",
"# directory containing the config files we're parsing",
"job_ini",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"job_inis",
"[",
"0",
"]",
")",
"base_path",
"=",
"decode",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"job_ini",
")",
")",
"params",
"=",
"dict",
"(",
"base_path",
"=",
"base_path",
",",
"inputs",
"=",
"{",
"'job_ini'",
":",
"job_ini",
"}",
")",
"if",
"input_zip",
":",
"params",
"[",
"'inputs'",
"]",
"[",
"'input_zip'",
"]",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"input_zip",
")",
"for",
"sect",
"in",
"cp",
".",
"sections",
"(",
")",
":",
"_update",
"(",
"params",
",",
"cp",
".",
"items",
"(",
"sect",
")",
",",
"base_path",
")",
"_update",
"(",
"params",
",",
"kw",
".",
"items",
"(",
")",
",",
"base_path",
")",
"# override on demand",
"if",
"params",
"[",
"'inputs'",
"]",
".",
"get",
"(",
"'reqv'",
")",
":",
"# using pointsource_distance=0 because of the reqv approximation",
"params",
"[",
"'pointsource_distance'",
"]",
"=",
"'0'",
"return",
"params"
] | Parse one or more INI-style config files.
:param job_inis:
List of configuration files (or list containing a single zip archive)
:param kw:
Optionally override some parameters
:returns:
A dictionary of parameters | [
"Parse",
"one",
"or",
"more",
"INI",
"-",
"style",
"config",
"files",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/readinput.py#L152-L191 | train | 233,474 |
gem/oq-engine | openquake/commonlib/readinput.py | get_oqparam | def get_oqparam(job_ini, pkg=None, calculators=None, hc_id=None, validate=1,
**kw):
"""
Parse a dictionary of parameters from an INI-style config file.
:param job_ini:
Path to configuration file/archive or dictionary of parameters
:param pkg:
Python package where to find the configuration file (optional)
:param calculators:
Sequence of calculator names (optional) used to restrict the
valid choices for `calculation_mode`
:param hc_id:
Not None only when called from a post calculation
:param validate:
Flag. By default it is true and the parameters are validated
:param kw:
String-valued keyword arguments used to override the job.ini parameters
:returns:
An :class:`openquake.commonlib.oqvalidation.OqParam` instance
containing the validate and casted parameters/values parsed from
the job.ini file as well as a subdictionary 'inputs' containing
absolute paths to all of the files referenced in the job.ini, keyed by
the parameter name.
"""
# UGLY: this is here to avoid circular imports
from openquake.calculators import base
OqParam.calculation_mode.validator.choices = tuple(
calculators or base.calculators)
if not isinstance(job_ini, dict):
basedir = os.path.dirname(pkg.__file__) if pkg else ''
job_ini = get_params([os.path.join(basedir, job_ini)])
if hc_id:
job_ini.update(hazard_calculation_id=str(hc_id))
job_ini.update(kw)
oqparam = OqParam(**job_ini)
if validate:
oqparam.validate()
return oqparam | python | def get_oqparam(job_ini, pkg=None, calculators=None, hc_id=None, validate=1,
**kw):
"""
Parse a dictionary of parameters from an INI-style config file.
:param job_ini:
Path to configuration file/archive or dictionary of parameters
:param pkg:
Python package where to find the configuration file (optional)
:param calculators:
Sequence of calculator names (optional) used to restrict the
valid choices for `calculation_mode`
:param hc_id:
Not None only when called from a post calculation
:param validate:
Flag. By default it is true and the parameters are validated
:param kw:
String-valued keyword arguments used to override the job.ini parameters
:returns:
An :class:`openquake.commonlib.oqvalidation.OqParam` instance
containing the validate and casted parameters/values parsed from
the job.ini file as well as a subdictionary 'inputs' containing
absolute paths to all of the files referenced in the job.ini, keyed by
the parameter name.
"""
# UGLY: this is here to avoid circular imports
from openquake.calculators import base
OqParam.calculation_mode.validator.choices = tuple(
calculators or base.calculators)
if not isinstance(job_ini, dict):
basedir = os.path.dirname(pkg.__file__) if pkg else ''
job_ini = get_params([os.path.join(basedir, job_ini)])
if hc_id:
job_ini.update(hazard_calculation_id=str(hc_id))
job_ini.update(kw)
oqparam = OqParam(**job_ini)
if validate:
oqparam.validate()
return oqparam | [
"def",
"get_oqparam",
"(",
"job_ini",
",",
"pkg",
"=",
"None",
",",
"calculators",
"=",
"None",
",",
"hc_id",
"=",
"None",
",",
"validate",
"=",
"1",
",",
"*",
"*",
"kw",
")",
":",
"# UGLY: this is here to avoid circular imports",
"from",
"openquake",
".",
"calculators",
"import",
"base",
"OqParam",
".",
"calculation_mode",
".",
"validator",
".",
"choices",
"=",
"tuple",
"(",
"calculators",
"or",
"base",
".",
"calculators",
")",
"if",
"not",
"isinstance",
"(",
"job_ini",
",",
"dict",
")",
":",
"basedir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"pkg",
".",
"__file__",
")",
"if",
"pkg",
"else",
"''",
"job_ini",
"=",
"get_params",
"(",
"[",
"os",
".",
"path",
".",
"join",
"(",
"basedir",
",",
"job_ini",
")",
"]",
")",
"if",
"hc_id",
":",
"job_ini",
".",
"update",
"(",
"hazard_calculation_id",
"=",
"str",
"(",
"hc_id",
")",
")",
"job_ini",
".",
"update",
"(",
"kw",
")",
"oqparam",
"=",
"OqParam",
"(",
"*",
"*",
"job_ini",
")",
"if",
"validate",
":",
"oqparam",
".",
"validate",
"(",
")",
"return",
"oqparam"
] | Parse a dictionary of parameters from an INI-style config file.
:param job_ini:
Path to configuration file/archive or dictionary of parameters
:param pkg:
Python package where to find the configuration file (optional)
:param calculators:
Sequence of calculator names (optional) used to restrict the
valid choices for `calculation_mode`
:param hc_id:
Not None only when called from a post calculation
:param validate:
Flag. By default it is true and the parameters are validated
:param kw:
String-valued keyword arguments used to override the job.ini parameters
:returns:
An :class:`openquake.commonlib.oqvalidation.OqParam` instance
containing the validate and casted parameters/values parsed from
the job.ini file as well as a subdictionary 'inputs' containing
absolute paths to all of the files referenced in the job.ini, keyed by
the parameter name. | [
"Parse",
"a",
"dictionary",
"of",
"parameters",
"from",
"an",
"INI",
"-",
"style",
"config",
"file",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/readinput.py#L194-L233 | train | 233,475 |
gem/oq-engine | openquake/commonlib/readinput.py | get_site_model | def get_site_model(oqparam):
"""
Convert the NRML file into an array of site parameters.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:returns:
an array with fields lon, lat, vs30, ...
"""
req_site_params = get_gsim_lt(oqparam).req_site_params
arrays = []
for fname in oqparam.inputs['site_model']:
if isinstance(fname, str) and fname.endswith('.csv'):
sm = read_csv(fname)
if 'site_id' in sm.dtype.names:
raise InvalidFile('%s: you passed a sites.csv file instead of '
'a site_model.csv file!' % fname)
z = numpy.zeros(len(sm), sorted(sm.dtype.descr))
for name in z.dtype.names: # reorder the fields
z[name] = sm[name]
arrays.append(z)
continue
nodes = nrml.read(fname).siteModel
params = [valid.site_param(node.attrib) for node in nodes]
missing = req_site_params - set(params[0])
if 'vs30measured' in missing: # use a default of False
missing -= {'vs30measured'}
for param in params:
param['vs30measured'] = False
if 'backarc' in missing: # use a default of False
missing -= {'backarc'}
for param in params:
param['backarc'] = False
if missing:
raise InvalidFile('%s: missing parameter %s' %
(oqparam.inputs['site_model'],
', '.join(missing)))
# NB: the sorted in sorted(params[0]) is essential, otherwise there is
# an heisenbug in scenario/test_case_4
site_model_dt = numpy.dtype([(p, site.site_param_dt[p])
for p in sorted(params[0])])
sm = numpy.array([tuple(param[name] for name in site_model_dt.names)
for param in params], site_model_dt)
arrays.append(sm)
return numpy.concatenate(arrays) | python | def get_site_model(oqparam):
"""
Convert the NRML file into an array of site parameters.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:returns:
an array with fields lon, lat, vs30, ...
"""
req_site_params = get_gsim_lt(oqparam).req_site_params
arrays = []
for fname in oqparam.inputs['site_model']:
if isinstance(fname, str) and fname.endswith('.csv'):
sm = read_csv(fname)
if 'site_id' in sm.dtype.names:
raise InvalidFile('%s: you passed a sites.csv file instead of '
'a site_model.csv file!' % fname)
z = numpy.zeros(len(sm), sorted(sm.dtype.descr))
for name in z.dtype.names: # reorder the fields
z[name] = sm[name]
arrays.append(z)
continue
nodes = nrml.read(fname).siteModel
params = [valid.site_param(node.attrib) for node in nodes]
missing = req_site_params - set(params[0])
if 'vs30measured' in missing: # use a default of False
missing -= {'vs30measured'}
for param in params:
param['vs30measured'] = False
if 'backarc' in missing: # use a default of False
missing -= {'backarc'}
for param in params:
param['backarc'] = False
if missing:
raise InvalidFile('%s: missing parameter %s' %
(oqparam.inputs['site_model'],
', '.join(missing)))
# NB: the sorted in sorted(params[0]) is essential, otherwise there is
# an heisenbug in scenario/test_case_4
site_model_dt = numpy.dtype([(p, site.site_param_dt[p])
for p in sorted(params[0])])
sm = numpy.array([tuple(param[name] for name in site_model_dt.names)
for param in params], site_model_dt)
arrays.append(sm)
return numpy.concatenate(arrays) | [
"def",
"get_site_model",
"(",
"oqparam",
")",
":",
"req_site_params",
"=",
"get_gsim_lt",
"(",
"oqparam",
")",
".",
"req_site_params",
"arrays",
"=",
"[",
"]",
"for",
"fname",
"in",
"oqparam",
".",
"inputs",
"[",
"'site_model'",
"]",
":",
"if",
"isinstance",
"(",
"fname",
",",
"str",
")",
"and",
"fname",
".",
"endswith",
"(",
"'.csv'",
")",
":",
"sm",
"=",
"read_csv",
"(",
"fname",
")",
"if",
"'site_id'",
"in",
"sm",
".",
"dtype",
".",
"names",
":",
"raise",
"InvalidFile",
"(",
"'%s: you passed a sites.csv file instead of '",
"'a site_model.csv file!'",
"%",
"fname",
")",
"z",
"=",
"numpy",
".",
"zeros",
"(",
"len",
"(",
"sm",
")",
",",
"sorted",
"(",
"sm",
".",
"dtype",
".",
"descr",
")",
")",
"for",
"name",
"in",
"z",
".",
"dtype",
".",
"names",
":",
"# reorder the fields",
"z",
"[",
"name",
"]",
"=",
"sm",
"[",
"name",
"]",
"arrays",
".",
"append",
"(",
"z",
")",
"continue",
"nodes",
"=",
"nrml",
".",
"read",
"(",
"fname",
")",
".",
"siteModel",
"params",
"=",
"[",
"valid",
".",
"site_param",
"(",
"node",
".",
"attrib",
")",
"for",
"node",
"in",
"nodes",
"]",
"missing",
"=",
"req_site_params",
"-",
"set",
"(",
"params",
"[",
"0",
"]",
")",
"if",
"'vs30measured'",
"in",
"missing",
":",
"# use a default of False",
"missing",
"-=",
"{",
"'vs30measured'",
"}",
"for",
"param",
"in",
"params",
":",
"param",
"[",
"'vs30measured'",
"]",
"=",
"False",
"if",
"'backarc'",
"in",
"missing",
":",
"# use a default of False",
"missing",
"-=",
"{",
"'backarc'",
"}",
"for",
"param",
"in",
"params",
":",
"param",
"[",
"'backarc'",
"]",
"=",
"False",
"if",
"missing",
":",
"raise",
"InvalidFile",
"(",
"'%s: missing parameter %s'",
"%",
"(",
"oqparam",
".",
"inputs",
"[",
"'site_model'",
"]",
",",
"', '",
".",
"join",
"(",
"missing",
")",
")",
")",
"# NB: the sorted in sorted(params[0]) is essential, otherwise there is",
"# an heisenbug in scenario/test_case_4",
"site_model_dt",
"=",
"numpy",
".",
"dtype",
"(",
"[",
"(",
"p",
",",
"site",
".",
"site_param_dt",
"[",
"p",
"]",
")",
"for",
"p",
"in",
"sorted",
"(",
"params",
"[",
"0",
"]",
")",
"]",
")",
"sm",
"=",
"numpy",
".",
"array",
"(",
"[",
"tuple",
"(",
"param",
"[",
"name",
"]",
"for",
"name",
"in",
"site_model_dt",
".",
"names",
")",
"for",
"param",
"in",
"params",
"]",
",",
"site_model_dt",
")",
"arrays",
".",
"append",
"(",
"sm",
")",
"return",
"numpy",
".",
"concatenate",
"(",
"arrays",
")"
] | Convert the NRML file into an array of site parameters.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:returns:
an array with fields lon, lat, vs30, ... | [
"Convert",
"the",
"NRML",
"file",
"into",
"an",
"array",
"of",
"site",
"parameters",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/readinput.py#L342-L386 | train | 233,476 |
gem/oq-engine | openquake/commonlib/readinput.py | get_site_collection | def get_site_collection(oqparam):
"""
Returns a SiteCollection instance by looking at the points and the
site model defined by the configuration parameters.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
"""
mesh = get_mesh(oqparam)
req_site_params = get_gsim_lt(oqparam).req_site_params
if oqparam.inputs.get('site_model'):
sm = get_site_model(oqparam)
try:
# in the future we could have elevation in the site model
depth = sm['depth']
except ValueError:
# this is the normal case
depth = None
sitecol = site.SiteCollection.from_points(
sm['lon'], sm['lat'], depth, sm, req_site_params)
if oqparam.region_grid_spacing:
logging.info('Reducing the grid sites to the site '
'parameters within the grid spacing')
sitecol, params, _ = geo.utils.assoc(
sm, sitecol, oqparam.region_grid_spacing * 1.414, 'filter')
sitecol.make_complete()
else:
params = sm
for name in req_site_params:
if name in ('vs30measured', 'backarc') \
and name not in params.dtype.names:
sitecol._set(name, 0) # the default
else:
sitecol._set(name, params[name])
elif mesh is None and oqparam.ground_motion_fields:
raise InvalidFile('You are missing sites.csv or site_model.csv in %s'
% oqparam.inputs['job_ini'])
elif mesh is None:
# a None sitecol is okay when computing the ruptures only
return
else: # use the default site params
sitecol = site.SiteCollection.from_points(
mesh.lons, mesh.lats, mesh.depths, oqparam, req_site_params)
ss = os.environ.get('OQ_SAMPLE_SITES')
if ss:
# debugging tip to reduce the size of a calculation
# OQ_SAMPLE_SITES=.1 oq engine --run job.ini
# will run a computation with 10 times less sites
sitecol.array = numpy.array(random_filter(sitecol.array, float(ss)))
sitecol.make_complete()
return sitecol | python | def get_site_collection(oqparam):
"""
Returns a SiteCollection instance by looking at the points and the
site model defined by the configuration parameters.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
"""
mesh = get_mesh(oqparam)
req_site_params = get_gsim_lt(oqparam).req_site_params
if oqparam.inputs.get('site_model'):
sm = get_site_model(oqparam)
try:
# in the future we could have elevation in the site model
depth = sm['depth']
except ValueError:
# this is the normal case
depth = None
sitecol = site.SiteCollection.from_points(
sm['lon'], sm['lat'], depth, sm, req_site_params)
if oqparam.region_grid_spacing:
logging.info('Reducing the grid sites to the site '
'parameters within the grid spacing')
sitecol, params, _ = geo.utils.assoc(
sm, sitecol, oqparam.region_grid_spacing * 1.414, 'filter')
sitecol.make_complete()
else:
params = sm
for name in req_site_params:
if name in ('vs30measured', 'backarc') \
and name not in params.dtype.names:
sitecol._set(name, 0) # the default
else:
sitecol._set(name, params[name])
elif mesh is None and oqparam.ground_motion_fields:
raise InvalidFile('You are missing sites.csv or site_model.csv in %s'
% oqparam.inputs['job_ini'])
elif mesh is None:
# a None sitecol is okay when computing the ruptures only
return
else: # use the default site params
sitecol = site.SiteCollection.from_points(
mesh.lons, mesh.lats, mesh.depths, oqparam, req_site_params)
ss = os.environ.get('OQ_SAMPLE_SITES')
if ss:
# debugging tip to reduce the size of a calculation
# OQ_SAMPLE_SITES=.1 oq engine --run job.ini
# will run a computation with 10 times less sites
sitecol.array = numpy.array(random_filter(sitecol.array, float(ss)))
sitecol.make_complete()
return sitecol | [
"def",
"get_site_collection",
"(",
"oqparam",
")",
":",
"mesh",
"=",
"get_mesh",
"(",
"oqparam",
")",
"req_site_params",
"=",
"get_gsim_lt",
"(",
"oqparam",
")",
".",
"req_site_params",
"if",
"oqparam",
".",
"inputs",
".",
"get",
"(",
"'site_model'",
")",
":",
"sm",
"=",
"get_site_model",
"(",
"oqparam",
")",
"try",
":",
"# in the future we could have elevation in the site model",
"depth",
"=",
"sm",
"[",
"'depth'",
"]",
"except",
"ValueError",
":",
"# this is the normal case",
"depth",
"=",
"None",
"sitecol",
"=",
"site",
".",
"SiteCollection",
".",
"from_points",
"(",
"sm",
"[",
"'lon'",
"]",
",",
"sm",
"[",
"'lat'",
"]",
",",
"depth",
",",
"sm",
",",
"req_site_params",
")",
"if",
"oqparam",
".",
"region_grid_spacing",
":",
"logging",
".",
"info",
"(",
"'Reducing the grid sites to the site '",
"'parameters within the grid spacing'",
")",
"sitecol",
",",
"params",
",",
"_",
"=",
"geo",
".",
"utils",
".",
"assoc",
"(",
"sm",
",",
"sitecol",
",",
"oqparam",
".",
"region_grid_spacing",
"*",
"1.414",
",",
"'filter'",
")",
"sitecol",
".",
"make_complete",
"(",
")",
"else",
":",
"params",
"=",
"sm",
"for",
"name",
"in",
"req_site_params",
":",
"if",
"name",
"in",
"(",
"'vs30measured'",
",",
"'backarc'",
")",
"and",
"name",
"not",
"in",
"params",
".",
"dtype",
".",
"names",
":",
"sitecol",
".",
"_set",
"(",
"name",
",",
"0",
")",
"# the default",
"else",
":",
"sitecol",
".",
"_set",
"(",
"name",
",",
"params",
"[",
"name",
"]",
")",
"elif",
"mesh",
"is",
"None",
"and",
"oqparam",
".",
"ground_motion_fields",
":",
"raise",
"InvalidFile",
"(",
"'You are missing sites.csv or site_model.csv in %s'",
"%",
"oqparam",
".",
"inputs",
"[",
"'job_ini'",
"]",
")",
"elif",
"mesh",
"is",
"None",
":",
"# a None sitecol is okay when computing the ruptures only",
"return",
"else",
":",
"# use the default site params",
"sitecol",
"=",
"site",
".",
"SiteCollection",
".",
"from_points",
"(",
"mesh",
".",
"lons",
",",
"mesh",
".",
"lats",
",",
"mesh",
".",
"depths",
",",
"oqparam",
",",
"req_site_params",
")",
"ss",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'OQ_SAMPLE_SITES'",
")",
"if",
"ss",
":",
"# debugging tip to reduce the size of a calculation",
"# OQ_SAMPLE_SITES=.1 oq engine --run job.ini",
"# will run a computation with 10 times less sites",
"sitecol",
".",
"array",
"=",
"numpy",
".",
"array",
"(",
"random_filter",
"(",
"sitecol",
".",
"array",
",",
"float",
"(",
"ss",
")",
")",
")",
"sitecol",
".",
"make_complete",
"(",
")",
"return",
"sitecol"
] | Returns a SiteCollection instance by looking at the points and the
site model defined by the configuration parameters.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance | [
"Returns",
"a",
"SiteCollection",
"instance",
"by",
"looking",
"at",
"the",
"points",
"and",
"the",
"site",
"model",
"defined",
"by",
"the",
"configuration",
"parameters",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/readinput.py#L389-L439 | train | 233,477 |
gem/oq-engine | openquake/commonlib/readinput.py | get_rupture | def get_rupture(oqparam):
"""
Read the `rupture_model` file and by filter the site collection
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:returns:
an hazardlib rupture
"""
rup_model = oqparam.inputs['rupture_model']
[rup_node] = nrml.read(rup_model)
conv = sourceconverter.RuptureConverter(
oqparam.rupture_mesh_spacing, oqparam.complex_fault_mesh_spacing)
rup = conv.convert_node(rup_node)
rup.tectonic_region_type = '*' # there is not TRT for scenario ruptures
rup.serial = oqparam.random_seed
return rup | python | def get_rupture(oqparam):
"""
Read the `rupture_model` file and by filter the site collection
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:returns:
an hazardlib rupture
"""
rup_model = oqparam.inputs['rupture_model']
[rup_node] = nrml.read(rup_model)
conv = sourceconverter.RuptureConverter(
oqparam.rupture_mesh_spacing, oqparam.complex_fault_mesh_spacing)
rup = conv.convert_node(rup_node)
rup.tectonic_region_type = '*' # there is not TRT for scenario ruptures
rup.serial = oqparam.random_seed
return rup | [
"def",
"get_rupture",
"(",
"oqparam",
")",
":",
"rup_model",
"=",
"oqparam",
".",
"inputs",
"[",
"'rupture_model'",
"]",
"[",
"rup_node",
"]",
"=",
"nrml",
".",
"read",
"(",
"rup_model",
")",
"conv",
"=",
"sourceconverter",
".",
"RuptureConverter",
"(",
"oqparam",
".",
"rupture_mesh_spacing",
",",
"oqparam",
".",
"complex_fault_mesh_spacing",
")",
"rup",
"=",
"conv",
".",
"convert_node",
"(",
"rup_node",
")",
"rup",
".",
"tectonic_region_type",
"=",
"'*'",
"# there is not TRT for scenario ruptures",
"rup",
".",
"serial",
"=",
"oqparam",
".",
"random_seed",
"return",
"rup"
] | Read the `rupture_model` file and by filter the site collection
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:returns:
an hazardlib rupture | [
"Read",
"the",
"rupture_model",
"file",
"and",
"by",
"filter",
"the",
"site",
"collection"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/readinput.py#L498-L514 | train | 233,478 |
gem/oq-engine | openquake/commonlib/readinput.py | get_composite_source_model | def get_composite_source_model(oqparam, monitor=None, in_memory=True,
srcfilter=SourceFilter(None, {})):
"""
Parse the XML and build a complete composite source model in memory.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:param monitor:
a `openquake.baselib.performance.Monitor` instance
:param in_memory:
if False, just parse the XML without instantiating the sources
:param srcfilter:
if not None, use it to prefilter the sources
"""
ucerf = oqparam.calculation_mode.startswith('ucerf')
source_model_lt = get_source_model_lt(oqparam, validate=not ucerf)
trts = source_model_lt.tectonic_region_types
trts_lower = {trt.lower() for trt in trts}
reqv = oqparam.inputs.get('reqv', {})
for trt in reqv: # these are lowercase because they come from the job.ini
if trt not in trts_lower:
raise ValueError('Unknown TRT=%s in %s [reqv]' %
(trt, oqparam.inputs['job_ini']))
gsim_lt = get_gsim_lt(oqparam, trts or ['*'])
p = source_model_lt.num_paths * gsim_lt.get_num_paths()
if oqparam.number_of_logic_tree_samples:
logging.info('Considering {:,d} logic tree paths out of {:,d}'.format(
oqparam.number_of_logic_tree_samples, p))
else: # full enumeration
if oqparam.is_event_based() and p > oqparam.max_potential_paths:
raise ValueError(
'There are too many potential logic tree paths (%d) '
'use sampling instead of full enumeration' % p)
logging.info('Potential number of logic tree paths = {:,d}'.format(p))
if source_model_lt.on_each_source:
logging.info('There is a logic tree on each source')
if monitor is None:
monitor = performance.Monitor()
smodels = []
for source_model in get_source_models(
oqparam, gsim_lt, source_model_lt, monitor, in_memory, srcfilter):
for src_group in source_model.src_groups:
src_group.sources = sorted(src_group, key=getid)
for src in src_group:
# there are two cases depending on the flag in_memory:
# 1) src is a hazardlib source and has a src_group_id
# attribute; in that case the source has to be numbered
# 2) src is a Node object, then nothing must be done
if isinstance(src, Node):
continue
smodels.append(source_model)
csm = source.CompositeSourceModel(gsim_lt, source_model_lt, smodels,
oqparam.optimize_same_id_sources)
for sm in csm.source_models:
counter = collections.Counter()
for sg in sm.src_groups:
for srcid in map(getid, sg):
counter[srcid] += 1
dupl = [srcid for srcid in counter if counter[srcid] > 1]
if dupl:
raise nrml.DuplicatedID('Found duplicated source IDs in %s: %s'
% (sm, dupl))
if not in_memory:
return csm
if oqparam.is_event_based():
# initialize the rupture serial numbers before splitting/filtering; in
# this way the serials are independent from the site collection
csm.init_serials(oqparam.ses_seed)
if oqparam.disagg_by_src:
csm = csm.grp_by_src() # one group per source
csm.info.gsim_lt.check_imts(oqparam.imtls)
parallel.Starmap.shutdown() # save memory
return csm | python | def get_composite_source_model(oqparam, monitor=None, in_memory=True,
srcfilter=SourceFilter(None, {})):
"""
Parse the XML and build a complete composite source model in memory.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:param monitor:
a `openquake.baselib.performance.Monitor` instance
:param in_memory:
if False, just parse the XML without instantiating the sources
:param srcfilter:
if not None, use it to prefilter the sources
"""
ucerf = oqparam.calculation_mode.startswith('ucerf')
source_model_lt = get_source_model_lt(oqparam, validate=not ucerf)
trts = source_model_lt.tectonic_region_types
trts_lower = {trt.lower() for trt in trts}
reqv = oqparam.inputs.get('reqv', {})
for trt in reqv: # these are lowercase because they come from the job.ini
if trt not in trts_lower:
raise ValueError('Unknown TRT=%s in %s [reqv]' %
(trt, oqparam.inputs['job_ini']))
gsim_lt = get_gsim_lt(oqparam, trts or ['*'])
p = source_model_lt.num_paths * gsim_lt.get_num_paths()
if oqparam.number_of_logic_tree_samples:
logging.info('Considering {:,d} logic tree paths out of {:,d}'.format(
oqparam.number_of_logic_tree_samples, p))
else: # full enumeration
if oqparam.is_event_based() and p > oqparam.max_potential_paths:
raise ValueError(
'There are too many potential logic tree paths (%d) '
'use sampling instead of full enumeration' % p)
logging.info('Potential number of logic tree paths = {:,d}'.format(p))
if source_model_lt.on_each_source:
logging.info('There is a logic tree on each source')
if monitor is None:
monitor = performance.Monitor()
smodels = []
for source_model in get_source_models(
oqparam, gsim_lt, source_model_lt, monitor, in_memory, srcfilter):
for src_group in source_model.src_groups:
src_group.sources = sorted(src_group, key=getid)
for src in src_group:
# there are two cases depending on the flag in_memory:
# 1) src is a hazardlib source and has a src_group_id
# attribute; in that case the source has to be numbered
# 2) src is a Node object, then nothing must be done
if isinstance(src, Node):
continue
smodels.append(source_model)
csm = source.CompositeSourceModel(gsim_lt, source_model_lt, smodels,
oqparam.optimize_same_id_sources)
for sm in csm.source_models:
counter = collections.Counter()
for sg in sm.src_groups:
for srcid in map(getid, sg):
counter[srcid] += 1
dupl = [srcid for srcid in counter if counter[srcid] > 1]
if dupl:
raise nrml.DuplicatedID('Found duplicated source IDs in %s: %s'
% (sm, dupl))
if not in_memory:
return csm
if oqparam.is_event_based():
# initialize the rupture serial numbers before splitting/filtering; in
# this way the serials are independent from the site collection
csm.init_serials(oqparam.ses_seed)
if oqparam.disagg_by_src:
csm = csm.grp_by_src() # one group per source
csm.info.gsim_lt.check_imts(oqparam.imtls)
parallel.Starmap.shutdown() # save memory
return csm | [
"def",
"get_composite_source_model",
"(",
"oqparam",
",",
"monitor",
"=",
"None",
",",
"in_memory",
"=",
"True",
",",
"srcfilter",
"=",
"SourceFilter",
"(",
"None",
",",
"{",
"}",
")",
")",
":",
"ucerf",
"=",
"oqparam",
".",
"calculation_mode",
".",
"startswith",
"(",
"'ucerf'",
")",
"source_model_lt",
"=",
"get_source_model_lt",
"(",
"oqparam",
",",
"validate",
"=",
"not",
"ucerf",
")",
"trts",
"=",
"source_model_lt",
".",
"tectonic_region_types",
"trts_lower",
"=",
"{",
"trt",
".",
"lower",
"(",
")",
"for",
"trt",
"in",
"trts",
"}",
"reqv",
"=",
"oqparam",
".",
"inputs",
".",
"get",
"(",
"'reqv'",
",",
"{",
"}",
")",
"for",
"trt",
"in",
"reqv",
":",
"# these are lowercase because they come from the job.ini",
"if",
"trt",
"not",
"in",
"trts_lower",
":",
"raise",
"ValueError",
"(",
"'Unknown TRT=%s in %s [reqv]'",
"%",
"(",
"trt",
",",
"oqparam",
".",
"inputs",
"[",
"'job_ini'",
"]",
")",
")",
"gsim_lt",
"=",
"get_gsim_lt",
"(",
"oqparam",
",",
"trts",
"or",
"[",
"'*'",
"]",
")",
"p",
"=",
"source_model_lt",
".",
"num_paths",
"*",
"gsim_lt",
".",
"get_num_paths",
"(",
")",
"if",
"oqparam",
".",
"number_of_logic_tree_samples",
":",
"logging",
".",
"info",
"(",
"'Considering {:,d} logic tree paths out of {:,d}'",
".",
"format",
"(",
"oqparam",
".",
"number_of_logic_tree_samples",
",",
"p",
")",
")",
"else",
":",
"# full enumeration",
"if",
"oqparam",
".",
"is_event_based",
"(",
")",
"and",
"p",
">",
"oqparam",
".",
"max_potential_paths",
":",
"raise",
"ValueError",
"(",
"'There are too many potential logic tree paths (%d) '",
"'use sampling instead of full enumeration'",
"%",
"p",
")",
"logging",
".",
"info",
"(",
"'Potential number of logic tree paths = {:,d}'",
".",
"format",
"(",
"p",
")",
")",
"if",
"source_model_lt",
".",
"on_each_source",
":",
"logging",
".",
"info",
"(",
"'There is a logic tree on each source'",
")",
"if",
"monitor",
"is",
"None",
":",
"monitor",
"=",
"performance",
".",
"Monitor",
"(",
")",
"smodels",
"=",
"[",
"]",
"for",
"source_model",
"in",
"get_source_models",
"(",
"oqparam",
",",
"gsim_lt",
",",
"source_model_lt",
",",
"monitor",
",",
"in_memory",
",",
"srcfilter",
")",
":",
"for",
"src_group",
"in",
"source_model",
".",
"src_groups",
":",
"src_group",
".",
"sources",
"=",
"sorted",
"(",
"src_group",
",",
"key",
"=",
"getid",
")",
"for",
"src",
"in",
"src_group",
":",
"# there are two cases depending on the flag in_memory:",
"# 1) src is a hazardlib source and has a src_group_id",
"# attribute; in that case the source has to be numbered",
"# 2) src is a Node object, then nothing must be done",
"if",
"isinstance",
"(",
"src",
",",
"Node",
")",
":",
"continue",
"smodels",
".",
"append",
"(",
"source_model",
")",
"csm",
"=",
"source",
".",
"CompositeSourceModel",
"(",
"gsim_lt",
",",
"source_model_lt",
",",
"smodels",
",",
"oqparam",
".",
"optimize_same_id_sources",
")",
"for",
"sm",
"in",
"csm",
".",
"source_models",
":",
"counter",
"=",
"collections",
".",
"Counter",
"(",
")",
"for",
"sg",
"in",
"sm",
".",
"src_groups",
":",
"for",
"srcid",
"in",
"map",
"(",
"getid",
",",
"sg",
")",
":",
"counter",
"[",
"srcid",
"]",
"+=",
"1",
"dupl",
"=",
"[",
"srcid",
"for",
"srcid",
"in",
"counter",
"if",
"counter",
"[",
"srcid",
"]",
">",
"1",
"]",
"if",
"dupl",
":",
"raise",
"nrml",
".",
"DuplicatedID",
"(",
"'Found duplicated source IDs in %s: %s'",
"%",
"(",
"sm",
",",
"dupl",
")",
")",
"if",
"not",
"in_memory",
":",
"return",
"csm",
"if",
"oqparam",
".",
"is_event_based",
"(",
")",
":",
"# initialize the rupture serial numbers before splitting/filtering; in",
"# this way the serials are independent from the site collection",
"csm",
".",
"init_serials",
"(",
"oqparam",
".",
"ses_seed",
")",
"if",
"oqparam",
".",
"disagg_by_src",
":",
"csm",
"=",
"csm",
".",
"grp_by_src",
"(",
")",
"# one group per source",
"csm",
".",
"info",
".",
"gsim_lt",
".",
"check_imts",
"(",
"oqparam",
".",
"imtls",
")",
"parallel",
".",
"Starmap",
".",
"shutdown",
"(",
")",
"# save memory",
"return",
"csm"
] | Parse the XML and build a complete composite source model in memory.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:param monitor:
a `openquake.baselib.performance.Monitor` instance
:param in_memory:
if False, just parse the XML without instantiating the sources
:param srcfilter:
if not None, use it to prefilter the sources | [
"Parse",
"the",
"XML",
"and",
"build",
"a",
"complete",
"composite",
"source",
"model",
"in",
"memory",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/readinput.py#L816-L892 | train | 233,479 |
gem/oq-engine | openquake/commonlib/readinput.py | get_mesh_hcurves | def get_mesh_hcurves(oqparam):
"""
Read CSV data in the format `lon lat, v1-vN, w1-wN, ...`.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:returns:
the mesh of points and the data as a dictionary
imt -> array of curves for each site
"""
imtls = oqparam.imtls
lon_lats = set()
data = AccumDict() # imt -> list of arrays
ncols = len(imtls) + 1 # lon_lat + curve_per_imt ...
csvfile = oqparam.inputs['hazard_curves']
for line, row in enumerate(csv.reader(csvfile), 1):
try:
if len(row) != ncols:
raise ValueError('Expected %d columns, found %d' %
ncols, len(row))
x, y = row[0].split()
lon_lat = valid.longitude(x), valid.latitude(y)
if lon_lat in lon_lats:
raise DuplicatedPoint(lon_lat)
lon_lats.add(lon_lat)
for i, imt_ in enumerate(imtls, 1):
values = valid.decreasing_probabilities(row[i])
if len(values) != len(imtls[imt_]):
raise ValueError('Found %d values, expected %d' %
(len(values), len(imtls([imt_]))))
data += {imt_: [numpy.array(values)]}
except (ValueError, DuplicatedPoint) as err:
raise err.__class__('%s: file %s, line %d' % (err, csvfile, line))
lons, lats = zip(*sorted(lon_lats))
mesh = geo.Mesh(numpy.array(lons), numpy.array(lats))
return mesh, {imt: numpy.array(lst) for imt, lst in data.items()} | python | def get_mesh_hcurves(oqparam):
"""
Read CSV data in the format `lon lat, v1-vN, w1-wN, ...`.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:returns:
the mesh of points and the data as a dictionary
imt -> array of curves for each site
"""
imtls = oqparam.imtls
lon_lats = set()
data = AccumDict() # imt -> list of arrays
ncols = len(imtls) + 1 # lon_lat + curve_per_imt ...
csvfile = oqparam.inputs['hazard_curves']
for line, row in enumerate(csv.reader(csvfile), 1):
try:
if len(row) != ncols:
raise ValueError('Expected %d columns, found %d' %
ncols, len(row))
x, y = row[0].split()
lon_lat = valid.longitude(x), valid.latitude(y)
if lon_lat in lon_lats:
raise DuplicatedPoint(lon_lat)
lon_lats.add(lon_lat)
for i, imt_ in enumerate(imtls, 1):
values = valid.decreasing_probabilities(row[i])
if len(values) != len(imtls[imt_]):
raise ValueError('Found %d values, expected %d' %
(len(values), len(imtls([imt_]))))
data += {imt_: [numpy.array(values)]}
except (ValueError, DuplicatedPoint) as err:
raise err.__class__('%s: file %s, line %d' % (err, csvfile, line))
lons, lats = zip(*sorted(lon_lats))
mesh = geo.Mesh(numpy.array(lons), numpy.array(lats))
return mesh, {imt: numpy.array(lst) for imt, lst in data.items()} | [
"def",
"get_mesh_hcurves",
"(",
"oqparam",
")",
":",
"imtls",
"=",
"oqparam",
".",
"imtls",
"lon_lats",
"=",
"set",
"(",
")",
"data",
"=",
"AccumDict",
"(",
")",
"# imt -> list of arrays",
"ncols",
"=",
"len",
"(",
"imtls",
")",
"+",
"1",
"# lon_lat + curve_per_imt ...",
"csvfile",
"=",
"oqparam",
".",
"inputs",
"[",
"'hazard_curves'",
"]",
"for",
"line",
",",
"row",
"in",
"enumerate",
"(",
"csv",
".",
"reader",
"(",
"csvfile",
")",
",",
"1",
")",
":",
"try",
":",
"if",
"len",
"(",
"row",
")",
"!=",
"ncols",
":",
"raise",
"ValueError",
"(",
"'Expected %d columns, found %d'",
"%",
"ncols",
",",
"len",
"(",
"row",
")",
")",
"x",
",",
"y",
"=",
"row",
"[",
"0",
"]",
".",
"split",
"(",
")",
"lon_lat",
"=",
"valid",
".",
"longitude",
"(",
"x",
")",
",",
"valid",
".",
"latitude",
"(",
"y",
")",
"if",
"lon_lat",
"in",
"lon_lats",
":",
"raise",
"DuplicatedPoint",
"(",
"lon_lat",
")",
"lon_lats",
".",
"add",
"(",
"lon_lat",
")",
"for",
"i",
",",
"imt_",
"in",
"enumerate",
"(",
"imtls",
",",
"1",
")",
":",
"values",
"=",
"valid",
".",
"decreasing_probabilities",
"(",
"row",
"[",
"i",
"]",
")",
"if",
"len",
"(",
"values",
")",
"!=",
"len",
"(",
"imtls",
"[",
"imt_",
"]",
")",
":",
"raise",
"ValueError",
"(",
"'Found %d values, expected %d'",
"%",
"(",
"len",
"(",
"values",
")",
",",
"len",
"(",
"imtls",
"(",
"[",
"imt_",
"]",
")",
")",
")",
")",
"data",
"+=",
"{",
"imt_",
":",
"[",
"numpy",
".",
"array",
"(",
"values",
")",
"]",
"}",
"except",
"(",
"ValueError",
",",
"DuplicatedPoint",
")",
"as",
"err",
":",
"raise",
"err",
".",
"__class__",
"(",
"'%s: file %s, line %d'",
"%",
"(",
"err",
",",
"csvfile",
",",
"line",
")",
")",
"lons",
",",
"lats",
"=",
"zip",
"(",
"*",
"sorted",
"(",
"lon_lats",
")",
")",
"mesh",
"=",
"geo",
".",
"Mesh",
"(",
"numpy",
".",
"array",
"(",
"lons",
")",
",",
"numpy",
".",
"array",
"(",
"lats",
")",
")",
"return",
"mesh",
",",
"{",
"imt",
":",
"numpy",
".",
"array",
"(",
"lst",
")",
"for",
"imt",
",",
"lst",
"in",
"data",
".",
"items",
"(",
")",
"}"
] | Read CSV data in the format `lon lat, v1-vN, w1-wN, ...`.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:returns:
the mesh of points and the data as a dictionary
imt -> array of curves for each site | [
"Read",
"CSV",
"data",
"in",
"the",
"format",
"lon",
"lat",
"v1",
"-",
"vN",
"w1",
"-",
"wN",
"...",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/readinput.py#L1212-L1247 | train | 233,480 |
gem/oq-engine | openquake/commonlib/readinput.py | reduce_source_model | def reduce_source_model(smlt_file, source_ids, remove=True):
"""
Extract sources from the composite source model
"""
found = 0
to_remove = []
for paths in logictree.collect_info(smlt_file).smpaths.values():
for path in paths:
logging.info('Reading %s', path)
root = nrml.read(path)
model = Node('sourceModel', root[0].attrib)
origmodel = root[0]
if root['xmlns'] == 'http://openquake.org/xmlns/nrml/0.4':
for src_node in origmodel:
if src_node['id'] in source_ids:
model.nodes.append(src_node)
else: # nrml/0.5
for src_group in origmodel:
sg = copy.copy(src_group)
sg.nodes = []
weights = src_group.get('srcs_weights')
if weights:
assert len(weights) == len(src_group.nodes)
else:
weights = [1] * len(src_group.nodes)
src_group['srcs_weights'] = reduced_weigths = []
for src_node, weight in zip(src_group, weights):
if src_node['id'] in source_ids:
found += 1
sg.nodes.append(src_node)
reduced_weigths.append(weight)
if sg.nodes:
model.nodes.append(sg)
shutil.copy(path, path + '.bak')
if model:
with open(path, 'wb') as f:
nrml.write([model], f, xmlns=root['xmlns'])
elif remove: # remove the files completely reduced
to_remove.append(path)
if found:
for path in to_remove:
os.remove(path) | python | def reduce_source_model(smlt_file, source_ids, remove=True):
"""
Extract sources from the composite source model
"""
found = 0
to_remove = []
for paths in logictree.collect_info(smlt_file).smpaths.values():
for path in paths:
logging.info('Reading %s', path)
root = nrml.read(path)
model = Node('sourceModel', root[0].attrib)
origmodel = root[0]
if root['xmlns'] == 'http://openquake.org/xmlns/nrml/0.4':
for src_node in origmodel:
if src_node['id'] in source_ids:
model.nodes.append(src_node)
else: # nrml/0.5
for src_group in origmodel:
sg = copy.copy(src_group)
sg.nodes = []
weights = src_group.get('srcs_weights')
if weights:
assert len(weights) == len(src_group.nodes)
else:
weights = [1] * len(src_group.nodes)
src_group['srcs_weights'] = reduced_weigths = []
for src_node, weight in zip(src_group, weights):
if src_node['id'] in source_ids:
found += 1
sg.nodes.append(src_node)
reduced_weigths.append(weight)
if sg.nodes:
model.nodes.append(sg)
shutil.copy(path, path + '.bak')
if model:
with open(path, 'wb') as f:
nrml.write([model], f, xmlns=root['xmlns'])
elif remove: # remove the files completely reduced
to_remove.append(path)
if found:
for path in to_remove:
os.remove(path) | [
"def",
"reduce_source_model",
"(",
"smlt_file",
",",
"source_ids",
",",
"remove",
"=",
"True",
")",
":",
"found",
"=",
"0",
"to_remove",
"=",
"[",
"]",
"for",
"paths",
"in",
"logictree",
".",
"collect_info",
"(",
"smlt_file",
")",
".",
"smpaths",
".",
"values",
"(",
")",
":",
"for",
"path",
"in",
"paths",
":",
"logging",
".",
"info",
"(",
"'Reading %s'",
",",
"path",
")",
"root",
"=",
"nrml",
".",
"read",
"(",
"path",
")",
"model",
"=",
"Node",
"(",
"'sourceModel'",
",",
"root",
"[",
"0",
"]",
".",
"attrib",
")",
"origmodel",
"=",
"root",
"[",
"0",
"]",
"if",
"root",
"[",
"'xmlns'",
"]",
"==",
"'http://openquake.org/xmlns/nrml/0.4'",
":",
"for",
"src_node",
"in",
"origmodel",
":",
"if",
"src_node",
"[",
"'id'",
"]",
"in",
"source_ids",
":",
"model",
".",
"nodes",
".",
"append",
"(",
"src_node",
")",
"else",
":",
"# nrml/0.5",
"for",
"src_group",
"in",
"origmodel",
":",
"sg",
"=",
"copy",
".",
"copy",
"(",
"src_group",
")",
"sg",
".",
"nodes",
"=",
"[",
"]",
"weights",
"=",
"src_group",
".",
"get",
"(",
"'srcs_weights'",
")",
"if",
"weights",
":",
"assert",
"len",
"(",
"weights",
")",
"==",
"len",
"(",
"src_group",
".",
"nodes",
")",
"else",
":",
"weights",
"=",
"[",
"1",
"]",
"*",
"len",
"(",
"src_group",
".",
"nodes",
")",
"src_group",
"[",
"'srcs_weights'",
"]",
"=",
"reduced_weigths",
"=",
"[",
"]",
"for",
"src_node",
",",
"weight",
"in",
"zip",
"(",
"src_group",
",",
"weights",
")",
":",
"if",
"src_node",
"[",
"'id'",
"]",
"in",
"source_ids",
":",
"found",
"+=",
"1",
"sg",
".",
"nodes",
".",
"append",
"(",
"src_node",
")",
"reduced_weigths",
".",
"append",
"(",
"weight",
")",
"if",
"sg",
".",
"nodes",
":",
"model",
".",
"nodes",
".",
"append",
"(",
"sg",
")",
"shutil",
".",
"copy",
"(",
"path",
",",
"path",
"+",
"'.bak'",
")",
"if",
"model",
":",
"with",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"f",
":",
"nrml",
".",
"write",
"(",
"[",
"model",
"]",
",",
"f",
",",
"xmlns",
"=",
"root",
"[",
"'xmlns'",
"]",
")",
"elif",
"remove",
":",
"# remove the files completely reduced",
"to_remove",
".",
"append",
"(",
"path",
")",
"if",
"found",
":",
"for",
"path",
"in",
"to_remove",
":",
"os",
".",
"remove",
"(",
"path",
")"
] | Extract sources from the composite source model | [
"Extract",
"sources",
"from",
"the",
"composite",
"source",
"model"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/readinput.py#L1251-L1292 | train | 233,481 |
gem/oq-engine | openquake/commonlib/readinput.py | get_checksum32 | def get_checksum32(oqparam, hazard=False):
"""
Build an unsigned 32 bit integer from the input files of a calculation.
:param oqparam: an OqParam instance
:param hazard: if True, consider only the hazard files
:returns: the checkume
"""
# NB: using adler32 & 0xffffffff is the documented way to get a checksum
# which is the same between Python 2 and Python 3
checksum = 0
for fname in get_input_files(oqparam, hazard):
checksum = _checksum(fname, checksum)
if hazard:
hazard_params = []
for key, val in vars(oqparam).items():
if key in ('rupture_mesh_spacing', 'complex_fault_mesh_spacing',
'width_of_mfd_bin', 'area_source_discretization',
'random_seed', 'ses_seed', 'truncation_level',
'maximum_distance', 'investigation_time',
'number_of_logic_tree_samples', 'imtls',
'ses_per_logic_tree_path', 'minimum_magnitude',
'prefilter_sources', 'sites',
'pointsource_distance', 'filter_distance'):
hazard_params.append('%s = %s' % (key, val))
data = '\n'.join(hazard_params).encode('utf8')
checksum = zlib.adler32(data, checksum) & 0xffffffff
return checksum | python | def get_checksum32(oqparam, hazard=False):
"""
Build an unsigned 32 bit integer from the input files of a calculation.
:param oqparam: an OqParam instance
:param hazard: if True, consider only the hazard files
:returns: the checkume
"""
# NB: using adler32 & 0xffffffff is the documented way to get a checksum
# which is the same between Python 2 and Python 3
checksum = 0
for fname in get_input_files(oqparam, hazard):
checksum = _checksum(fname, checksum)
if hazard:
hazard_params = []
for key, val in vars(oqparam).items():
if key in ('rupture_mesh_spacing', 'complex_fault_mesh_spacing',
'width_of_mfd_bin', 'area_source_discretization',
'random_seed', 'ses_seed', 'truncation_level',
'maximum_distance', 'investigation_time',
'number_of_logic_tree_samples', 'imtls',
'ses_per_logic_tree_path', 'minimum_magnitude',
'prefilter_sources', 'sites',
'pointsource_distance', 'filter_distance'):
hazard_params.append('%s = %s' % (key, val))
data = '\n'.join(hazard_params).encode('utf8')
checksum = zlib.adler32(data, checksum) & 0xffffffff
return checksum | [
"def",
"get_checksum32",
"(",
"oqparam",
",",
"hazard",
"=",
"False",
")",
":",
"# NB: using adler32 & 0xffffffff is the documented way to get a checksum",
"# which is the same between Python 2 and Python 3",
"checksum",
"=",
"0",
"for",
"fname",
"in",
"get_input_files",
"(",
"oqparam",
",",
"hazard",
")",
":",
"checksum",
"=",
"_checksum",
"(",
"fname",
",",
"checksum",
")",
"if",
"hazard",
":",
"hazard_params",
"=",
"[",
"]",
"for",
"key",
",",
"val",
"in",
"vars",
"(",
"oqparam",
")",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"(",
"'rupture_mesh_spacing'",
",",
"'complex_fault_mesh_spacing'",
",",
"'width_of_mfd_bin'",
",",
"'area_source_discretization'",
",",
"'random_seed'",
",",
"'ses_seed'",
",",
"'truncation_level'",
",",
"'maximum_distance'",
",",
"'investigation_time'",
",",
"'number_of_logic_tree_samples'",
",",
"'imtls'",
",",
"'ses_per_logic_tree_path'",
",",
"'minimum_magnitude'",
",",
"'prefilter_sources'",
",",
"'sites'",
",",
"'pointsource_distance'",
",",
"'filter_distance'",
")",
":",
"hazard_params",
".",
"append",
"(",
"'%s = %s'",
"%",
"(",
"key",
",",
"val",
")",
")",
"data",
"=",
"'\\n'",
".",
"join",
"(",
"hazard_params",
")",
".",
"encode",
"(",
"'utf8'",
")",
"checksum",
"=",
"zlib",
".",
"adler32",
"(",
"data",
",",
"checksum",
")",
"&",
"0xffffffff",
"return",
"checksum"
] | Build an unsigned 32 bit integer from the input files of a calculation.
:param oqparam: an OqParam instance
:param hazard: if True, consider only the hazard files
:returns: the checkume | [
"Build",
"an",
"unsigned",
"32",
"bit",
"integer",
"from",
"the",
"input",
"files",
"of",
"a",
"calculation",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/readinput.py#L1388-L1415 | train | 233,482 |
gem/oq-engine | openquake/commands/dump.py | smart_save | def smart_save(dbpath, archive, calc_id):
"""
Make a copy of the db, remove the incomplete jobs and add the copy
to the archive
"""
tmpdir = tempfile.mkdtemp()
newdb = os.path.join(tmpdir, os.path.basename(dbpath))
shutil.copy(dbpath, newdb)
try:
with sqlite3.connect(newdb) as conn:
conn.execute('DELETE FROM job WHERE status != "complete"')
if calc_id:
conn.execute('DELETE FROM job WHERE id != %d' % calc_id)
except:
safeprint('Please check the copy of the db in %s' % newdb)
raise
zipfiles([newdb], archive, 'a', safeprint)
shutil.rmtree(tmpdir) | python | def smart_save(dbpath, archive, calc_id):
"""
Make a copy of the db, remove the incomplete jobs and add the copy
to the archive
"""
tmpdir = tempfile.mkdtemp()
newdb = os.path.join(tmpdir, os.path.basename(dbpath))
shutil.copy(dbpath, newdb)
try:
with sqlite3.connect(newdb) as conn:
conn.execute('DELETE FROM job WHERE status != "complete"')
if calc_id:
conn.execute('DELETE FROM job WHERE id != %d' % calc_id)
except:
safeprint('Please check the copy of the db in %s' % newdb)
raise
zipfiles([newdb], archive, 'a', safeprint)
shutil.rmtree(tmpdir) | [
"def",
"smart_save",
"(",
"dbpath",
",",
"archive",
",",
"calc_id",
")",
":",
"tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"newdb",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmpdir",
",",
"os",
".",
"path",
".",
"basename",
"(",
"dbpath",
")",
")",
"shutil",
".",
"copy",
"(",
"dbpath",
",",
"newdb",
")",
"try",
":",
"with",
"sqlite3",
".",
"connect",
"(",
"newdb",
")",
"as",
"conn",
":",
"conn",
".",
"execute",
"(",
"'DELETE FROM job WHERE status != \"complete\"'",
")",
"if",
"calc_id",
":",
"conn",
".",
"execute",
"(",
"'DELETE FROM job WHERE id != %d'",
"%",
"calc_id",
")",
"except",
":",
"safeprint",
"(",
"'Please check the copy of the db in %s'",
"%",
"newdb",
")",
"raise",
"zipfiles",
"(",
"[",
"newdb",
"]",
",",
"archive",
",",
"'a'",
",",
"safeprint",
")",
"shutil",
".",
"rmtree",
"(",
"tmpdir",
")"
] | Make a copy of the db, remove the incomplete jobs and add the copy
to the archive | [
"Make",
"a",
"copy",
"of",
"the",
"db",
"remove",
"the",
"incomplete",
"jobs",
"and",
"add",
"the",
"copy",
"to",
"the",
"archive"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/dump.py#L28-L45 | train | 233,483 |
gem/oq-engine | openquake/commands/dump.py | dump | def dump(archive, calc_id=0, user=None):
"""
Dump the openquake database and all the complete calculations into a zip
file. In a multiuser installation must be run as administrator.
"""
t0 = time.time()
assert archive.endswith('.zip'), archive
getfnames = 'select ds_calc_dir || ".hdf5" from job where ?A'
param = dict(status='complete')
if calc_id:
param['id'] = calc_id
if user:
param['user_name'] = user
fnames = [f for f, in db(getfnames, param) if os.path.exists(f)]
zipfiles(fnames, archive, 'w', safeprint)
pending_jobs = db('select id, status, description from job '
'where status="executing"')
if pending_jobs:
safeprint('WARNING: there were calculations executing during the dump,'
' they have been not copied')
for job_id, status, descr in pending_jobs:
safeprint('%d %s %s' % (job_id, status, descr))
# this also checks that the copied db is not corrupted
smart_save(db.path, archive, calc_id)
dt = time.time() - t0
safeprint('Archived %d calculations into %s in %d seconds'
% (len(fnames), archive, dt)) | python | def dump(archive, calc_id=0, user=None):
"""
Dump the openquake database and all the complete calculations into a zip
file. In a multiuser installation must be run as administrator.
"""
t0 = time.time()
assert archive.endswith('.zip'), archive
getfnames = 'select ds_calc_dir || ".hdf5" from job where ?A'
param = dict(status='complete')
if calc_id:
param['id'] = calc_id
if user:
param['user_name'] = user
fnames = [f for f, in db(getfnames, param) if os.path.exists(f)]
zipfiles(fnames, archive, 'w', safeprint)
pending_jobs = db('select id, status, description from job '
'where status="executing"')
if pending_jobs:
safeprint('WARNING: there were calculations executing during the dump,'
' they have been not copied')
for job_id, status, descr in pending_jobs:
safeprint('%d %s %s' % (job_id, status, descr))
# this also checks that the copied db is not corrupted
smart_save(db.path, archive, calc_id)
dt = time.time() - t0
safeprint('Archived %d calculations into %s in %d seconds'
% (len(fnames), archive, dt)) | [
"def",
"dump",
"(",
"archive",
",",
"calc_id",
"=",
"0",
",",
"user",
"=",
"None",
")",
":",
"t0",
"=",
"time",
".",
"time",
"(",
")",
"assert",
"archive",
".",
"endswith",
"(",
"'.zip'",
")",
",",
"archive",
"getfnames",
"=",
"'select ds_calc_dir || \".hdf5\" from job where ?A'",
"param",
"=",
"dict",
"(",
"status",
"=",
"'complete'",
")",
"if",
"calc_id",
":",
"param",
"[",
"'id'",
"]",
"=",
"calc_id",
"if",
"user",
":",
"param",
"[",
"'user_name'",
"]",
"=",
"user",
"fnames",
"=",
"[",
"f",
"for",
"f",
",",
"in",
"db",
"(",
"getfnames",
",",
"param",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"f",
")",
"]",
"zipfiles",
"(",
"fnames",
",",
"archive",
",",
"'w'",
",",
"safeprint",
")",
"pending_jobs",
"=",
"db",
"(",
"'select id, status, description from job '",
"'where status=\"executing\"'",
")",
"if",
"pending_jobs",
":",
"safeprint",
"(",
"'WARNING: there were calculations executing during the dump,'",
"' they have been not copied'",
")",
"for",
"job_id",
",",
"status",
",",
"descr",
"in",
"pending_jobs",
":",
"safeprint",
"(",
"'%d %s %s'",
"%",
"(",
"job_id",
",",
"status",
",",
"descr",
")",
")",
"# this also checks that the copied db is not corrupted",
"smart_save",
"(",
"db",
".",
"path",
",",
"archive",
",",
"calc_id",
")",
"dt",
"=",
"time",
".",
"time",
"(",
")",
"-",
"t0",
"safeprint",
"(",
"'Archived %d calculations into %s in %d seconds'",
"%",
"(",
"len",
"(",
"fnames",
")",
",",
"archive",
",",
"dt",
")",
")"
] | Dump the openquake database and all the complete calculations into a zip
file. In a multiuser installation must be run as administrator. | [
"Dump",
"the",
"openquake",
"database",
"and",
"all",
"the",
"complete",
"calculations",
"into",
"a",
"zip",
"file",
".",
"In",
"a",
"multiuser",
"installation",
"must",
"be",
"run",
"as",
"administrator",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/dump.py#L49-L77 | train | 233,484 |
conan-io/conan-package-tools | setup.py | load_version | def load_version():
"""Loads a file content"""
filename = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),
"cpt", "__init__.py"))
with open(filename, "rt") as version_file:
conan_init = version_file.read()
version = re.search("__version__ = '([0-9a-z.-]+)'", conan_init).group(1)
return version | python | def load_version():
"""Loads a file content"""
filename = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),
"cpt", "__init__.py"))
with open(filename, "rt") as version_file:
conan_init = version_file.read()
version = re.search("__version__ = '([0-9a-z.-]+)'", conan_init).group(1)
return version | [
"def",
"load_version",
"(",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
",",
"\"cpt\"",
",",
"\"__init__.py\"",
")",
")",
"with",
"open",
"(",
"filename",
",",
"\"rt\"",
")",
"as",
"version_file",
":",
"conan_init",
"=",
"version_file",
".",
"read",
"(",
")",
"version",
"=",
"re",
".",
"search",
"(",
"\"__version__ = '([0-9a-z.-]+)'\"",
",",
"conan_init",
")",
".",
"group",
"(",
"1",
")",
"return",
"version"
] | Loads a file content | [
"Loads",
"a",
"file",
"content"
] | 3d0f5f4dc5d9dc899a57626e8d8a125fc28b8324 | https://github.com/conan-io/conan-package-tools/blob/3d0f5f4dc5d9dc899a57626e8d8a125fc28b8324/setup.py#L25-L32 | train | 233,485 |
conan-io/conan-package-tools | cpt/packager.py | ConanMultiPackager.builds | def builds(self, confs):
"""For retro compatibility directly assigning builds"""
self._named_builds = {}
self._builds = []
for values in confs:
if len(values) == 2:
self._builds.append(BuildConf(values[0], values[1], {}, {}, self.reference))
elif len(values) == 4:
self._builds.append(BuildConf(values[0], values[1], values[2], values[3],
self.reference))
elif len(values) != 5:
raise Exception("Invalid build configuration, has to be a tuple of "
"(settings, options, env_vars, build_requires, reference)")
else:
self._builds.append(BuildConf(*values)) | python | def builds(self, confs):
"""For retro compatibility directly assigning builds"""
self._named_builds = {}
self._builds = []
for values in confs:
if len(values) == 2:
self._builds.append(BuildConf(values[0], values[1], {}, {}, self.reference))
elif len(values) == 4:
self._builds.append(BuildConf(values[0], values[1], values[2], values[3],
self.reference))
elif len(values) != 5:
raise Exception("Invalid build configuration, has to be a tuple of "
"(settings, options, env_vars, build_requires, reference)")
else:
self._builds.append(BuildConf(*values)) | [
"def",
"builds",
"(",
"self",
",",
"confs",
")",
":",
"self",
".",
"_named_builds",
"=",
"{",
"}",
"self",
".",
"_builds",
"=",
"[",
"]",
"for",
"values",
"in",
"confs",
":",
"if",
"len",
"(",
"values",
")",
"==",
"2",
":",
"self",
".",
"_builds",
".",
"append",
"(",
"BuildConf",
"(",
"values",
"[",
"0",
"]",
",",
"values",
"[",
"1",
"]",
",",
"{",
"}",
",",
"{",
"}",
",",
"self",
".",
"reference",
")",
")",
"elif",
"len",
"(",
"values",
")",
"==",
"4",
":",
"self",
".",
"_builds",
".",
"append",
"(",
"BuildConf",
"(",
"values",
"[",
"0",
"]",
",",
"values",
"[",
"1",
"]",
",",
"values",
"[",
"2",
"]",
",",
"values",
"[",
"3",
"]",
",",
"self",
".",
"reference",
")",
")",
"elif",
"len",
"(",
"values",
")",
"!=",
"5",
":",
"raise",
"Exception",
"(",
"\"Invalid build configuration, has to be a tuple of \"",
"\"(settings, options, env_vars, build_requires, reference)\"",
")",
"else",
":",
"self",
".",
"_builds",
".",
"append",
"(",
"BuildConf",
"(",
"*",
"values",
")",
")"
] | For retro compatibility directly assigning builds | [
"For",
"retro",
"compatibility",
"directly",
"assigning",
"builds"
] | 3d0f5f4dc5d9dc899a57626e8d8a125fc28b8324 | https://github.com/conan-io/conan-package-tools/blob/3d0f5f4dc5d9dc899a57626e8d8a125fc28b8324/cpt/packager.py#L357-L371 | train | 233,486 |
conan-io/conan-package-tools | cpt/profiles.py | patch_default_base_profile | def patch_default_base_profile(conan_api, profile_abs_path):
"""If we have a profile including default, but the users default in config is that the default
is other, we have to change the include"""
text = tools.load(profile_abs_path)
if "include(default)" in text: # User didn't specified a custom profile
if Version(conan_version) < Version("1.12.0"):
cache = conan_api._client_cache
else:
cache = conan_api._cache
default_profile_name = os.path.basename(cache.default_profile_path)
if not os.path.exists(cache.default_profile_path):
conan_api.create_profile(default_profile_name, detect=True)
if default_profile_name != "default": # User have a different default profile name
# https://github.com/conan-io/conan-package-tools/issues/121
text = text.replace("include(default)", "include(%s)" % default_profile_name)
tools.save(profile_abs_path, text) | python | def patch_default_base_profile(conan_api, profile_abs_path):
"""If we have a profile including default, but the users default in config is that the default
is other, we have to change the include"""
text = tools.load(profile_abs_path)
if "include(default)" in text: # User didn't specified a custom profile
if Version(conan_version) < Version("1.12.0"):
cache = conan_api._client_cache
else:
cache = conan_api._cache
default_profile_name = os.path.basename(cache.default_profile_path)
if not os.path.exists(cache.default_profile_path):
conan_api.create_profile(default_profile_name, detect=True)
if default_profile_name != "default": # User have a different default profile name
# https://github.com/conan-io/conan-package-tools/issues/121
text = text.replace("include(default)", "include(%s)" % default_profile_name)
tools.save(profile_abs_path, text) | [
"def",
"patch_default_base_profile",
"(",
"conan_api",
",",
"profile_abs_path",
")",
":",
"text",
"=",
"tools",
".",
"load",
"(",
"profile_abs_path",
")",
"if",
"\"include(default)\"",
"in",
"text",
":",
"# User didn't specified a custom profile",
"if",
"Version",
"(",
"conan_version",
")",
"<",
"Version",
"(",
"\"1.12.0\"",
")",
":",
"cache",
"=",
"conan_api",
".",
"_client_cache",
"else",
":",
"cache",
"=",
"conan_api",
".",
"_cache",
"default_profile_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"cache",
".",
"default_profile_path",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"cache",
".",
"default_profile_path",
")",
":",
"conan_api",
".",
"create_profile",
"(",
"default_profile_name",
",",
"detect",
"=",
"True",
")",
"if",
"default_profile_name",
"!=",
"\"default\"",
":",
"# User have a different default profile name",
"# https://github.com/conan-io/conan-package-tools/issues/121",
"text",
"=",
"text",
".",
"replace",
"(",
"\"include(default)\"",
",",
"\"include(%s)\"",
"%",
"default_profile_name",
")",
"tools",
".",
"save",
"(",
"profile_abs_path",
",",
"text",
")"
] | If we have a profile including default, but the users default in config is that the default
is other, we have to change the include | [
"If",
"we",
"have",
"a",
"profile",
"including",
"default",
"but",
"the",
"users",
"default",
"in",
"config",
"is",
"that",
"the",
"default",
"is",
"other",
"we",
"have",
"to",
"change",
"the",
"include"
] | 3d0f5f4dc5d9dc899a57626e8d8a125fc28b8324 | https://github.com/conan-io/conan-package-tools/blob/3d0f5f4dc5d9dc899a57626e8d8a125fc28b8324/cpt/profiles.py#L51-L68 | train | 233,487 |
edx/auth-backends | auth_backends/pipeline.py | get_user_if_exists | def get_user_if_exists(strategy, details, user=None, *args, **kwargs):
"""Return a User with the given username iff the User exists."""
if user:
return {'is_new': False}
try:
username = details.get('username')
# Return the user if it exists
return {
'is_new': False,
'user': User.objects.get(username=username)
}
except User.DoesNotExist:
# Fall to the default return value
pass
# Nothing to return since we don't have a user
return {} | python | def get_user_if_exists(strategy, details, user=None, *args, **kwargs):
"""Return a User with the given username iff the User exists."""
if user:
return {'is_new': False}
try:
username = details.get('username')
# Return the user if it exists
return {
'is_new': False,
'user': User.objects.get(username=username)
}
except User.DoesNotExist:
# Fall to the default return value
pass
# Nothing to return since we don't have a user
return {} | [
"def",
"get_user_if_exists",
"(",
"strategy",
",",
"details",
",",
"user",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"user",
":",
"return",
"{",
"'is_new'",
":",
"False",
"}",
"try",
":",
"username",
"=",
"details",
".",
"get",
"(",
"'username'",
")",
"# Return the user if it exists",
"return",
"{",
"'is_new'",
":",
"False",
",",
"'user'",
":",
"User",
".",
"objects",
".",
"get",
"(",
"username",
"=",
"username",
")",
"}",
"except",
"User",
".",
"DoesNotExist",
":",
"# Fall to the default return value",
"pass",
"# Nothing to return since we don't have a user",
"return",
"{",
"}"
] | Return a User with the given username iff the User exists. | [
"Return",
"a",
"User",
"with",
"the",
"given",
"username",
"iff",
"the",
"User",
"exists",
"."
] | 493f93e9d87d0237f0fea6d75c7b70646ad6d31e | https://github.com/edx/auth-backends/blob/493f93e9d87d0237f0fea6d75c7b70646ad6d31e/auth_backends/pipeline.py#L14-L31 | train | 233,488 |
edx/auth-backends | auth_backends/pipeline.py | update_email | def update_email(strategy, details, user=None, *args, **kwargs):
"""Update the user's email address using data from provider."""
if user:
email = details.get('email')
if email and user.email != email:
user.email = email
strategy.storage.user.changed(user) | python | def update_email(strategy, details, user=None, *args, **kwargs):
"""Update the user's email address using data from provider."""
if user:
email = details.get('email')
if email and user.email != email:
user.email = email
strategy.storage.user.changed(user) | [
"def",
"update_email",
"(",
"strategy",
",",
"details",
",",
"user",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"user",
":",
"email",
"=",
"details",
".",
"get",
"(",
"'email'",
")",
"if",
"email",
"and",
"user",
".",
"email",
"!=",
"email",
":",
"user",
".",
"email",
"=",
"email",
"strategy",
".",
"storage",
".",
"user",
".",
"changed",
"(",
"user",
")"
] | Update the user's email address using data from provider. | [
"Update",
"the",
"user",
"s",
"email",
"address",
"using",
"data",
"from",
"provider",
"."
] | 493f93e9d87d0237f0fea6d75c7b70646ad6d31e | https://github.com/edx/auth-backends/blob/493f93e9d87d0237f0fea6d75c7b70646ad6d31e/auth_backends/pipeline.py#L34-L41 | train | 233,489 |
edx/auth-backends | auth_backends/backends.py | EdXOpenIdConnect.get_user_claims | def get_user_claims(self, access_token, claims=None, token_type='Bearer'):
"""Returns a dictionary with the values for each claim requested."""
data = self.get_json(
self.USER_INFO_URL,
headers={'Authorization': '{token_type} {token}'.format(token_type=token_type, token=access_token)}
)
if claims:
claims_names = set(claims)
data = {k: v for (k, v) in six.iteritems(data) if k in claims_names}
return data | python | def get_user_claims(self, access_token, claims=None, token_type='Bearer'):
"""Returns a dictionary with the values for each claim requested."""
data = self.get_json(
self.USER_INFO_URL,
headers={'Authorization': '{token_type} {token}'.format(token_type=token_type, token=access_token)}
)
if claims:
claims_names = set(claims)
data = {k: v for (k, v) in six.iteritems(data) if k in claims_names}
return data | [
"def",
"get_user_claims",
"(",
"self",
",",
"access_token",
",",
"claims",
"=",
"None",
",",
"token_type",
"=",
"'Bearer'",
")",
":",
"data",
"=",
"self",
".",
"get_json",
"(",
"self",
".",
"USER_INFO_URL",
",",
"headers",
"=",
"{",
"'Authorization'",
":",
"'{token_type} {token}'",
".",
"format",
"(",
"token_type",
"=",
"token_type",
",",
"token",
"=",
"access_token",
")",
"}",
")",
"if",
"claims",
":",
"claims_names",
"=",
"set",
"(",
"claims",
")",
"data",
"=",
"{",
"k",
":",
"v",
"for",
"(",
"k",
",",
"v",
")",
"in",
"six",
".",
"iteritems",
"(",
"data",
")",
"if",
"k",
"in",
"claims_names",
"}",
"return",
"data"
] | Returns a dictionary with the values for each claim requested. | [
"Returns",
"a",
"dictionary",
"with",
"the",
"values",
"for",
"each",
"claim",
"requested",
"."
] | 493f93e9d87d0237f0fea6d75c7b70646ad6d31e | https://github.com/edx/auth-backends/blob/493f93e9d87d0237f0fea6d75c7b70646ad6d31e/auth_backends/backends.py#L170-L181 | train | 233,490 |
napalm-automation/napalm-logs | napalm_logs/server.py | NapalmLogsServerProc._setup_ipc | def _setup_ipc(self):
'''
Setup the IPC pub and sub.
Subscript to the listener IPC
and publish to the device specific IPC.
'''
log.debug('Setting up the server IPC puller to receive from the listener')
self.ctx = zmq.Context()
# subscribe to listener
self.sub = self.ctx.socket(zmq.PULL)
self.sub.bind(LST_IPC_URL)
try:
self.sub.setsockopt(zmq.HWM, self.opts['hwm'])
# zmq 2
except AttributeError:
# zmq 3
self.sub.setsockopt(zmq.RCVHWM, self.opts['hwm'])
# device publishers
log.debug('Creating the router ICP on the server')
self.pub = self.ctx.socket(zmq.ROUTER)
self.pub.bind(DEV_IPC_URL)
try:
self.pub.setsockopt(zmq.HWM, self.opts['hwm'])
# zmq 2
except AttributeError:
# zmq 3
self.pub.setsockopt(zmq.SNDHWM, self.opts['hwm'])
# Pipe to the publishers
self.publisher_pub = self.ctx.socket(zmq.PUB)
self.publisher_pub.connect(PUB_PX_IPC_URL)
try:
self.publisher_pub.setsockopt(zmq.HWM, self.opts['hwm'])
# zmq 2
except AttributeError:
# zmq 3
self.publisher_pub.setsockopt(zmq.SNDHWM, self.opts['hwm']) | python | def _setup_ipc(self):
'''
Setup the IPC pub and sub.
Subscript to the listener IPC
and publish to the device specific IPC.
'''
log.debug('Setting up the server IPC puller to receive from the listener')
self.ctx = zmq.Context()
# subscribe to listener
self.sub = self.ctx.socket(zmq.PULL)
self.sub.bind(LST_IPC_URL)
try:
self.sub.setsockopt(zmq.HWM, self.opts['hwm'])
# zmq 2
except AttributeError:
# zmq 3
self.sub.setsockopt(zmq.RCVHWM, self.opts['hwm'])
# device publishers
log.debug('Creating the router ICP on the server')
self.pub = self.ctx.socket(zmq.ROUTER)
self.pub.bind(DEV_IPC_URL)
try:
self.pub.setsockopt(zmq.HWM, self.opts['hwm'])
# zmq 2
except AttributeError:
# zmq 3
self.pub.setsockopt(zmq.SNDHWM, self.opts['hwm'])
# Pipe to the publishers
self.publisher_pub = self.ctx.socket(zmq.PUB)
self.publisher_pub.connect(PUB_PX_IPC_URL)
try:
self.publisher_pub.setsockopt(zmq.HWM, self.opts['hwm'])
# zmq 2
except AttributeError:
# zmq 3
self.publisher_pub.setsockopt(zmq.SNDHWM, self.opts['hwm']) | [
"def",
"_setup_ipc",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"'Setting up the server IPC puller to receive from the listener'",
")",
"self",
".",
"ctx",
"=",
"zmq",
".",
"Context",
"(",
")",
"# subscribe to listener",
"self",
".",
"sub",
"=",
"self",
".",
"ctx",
".",
"socket",
"(",
"zmq",
".",
"PULL",
")",
"self",
".",
"sub",
".",
"bind",
"(",
"LST_IPC_URL",
")",
"try",
":",
"self",
".",
"sub",
".",
"setsockopt",
"(",
"zmq",
".",
"HWM",
",",
"self",
".",
"opts",
"[",
"'hwm'",
"]",
")",
"# zmq 2",
"except",
"AttributeError",
":",
"# zmq 3",
"self",
".",
"sub",
".",
"setsockopt",
"(",
"zmq",
".",
"RCVHWM",
",",
"self",
".",
"opts",
"[",
"'hwm'",
"]",
")",
"# device publishers",
"log",
".",
"debug",
"(",
"'Creating the router ICP on the server'",
")",
"self",
".",
"pub",
"=",
"self",
".",
"ctx",
".",
"socket",
"(",
"zmq",
".",
"ROUTER",
")",
"self",
".",
"pub",
".",
"bind",
"(",
"DEV_IPC_URL",
")",
"try",
":",
"self",
".",
"pub",
".",
"setsockopt",
"(",
"zmq",
".",
"HWM",
",",
"self",
".",
"opts",
"[",
"'hwm'",
"]",
")",
"# zmq 2",
"except",
"AttributeError",
":",
"# zmq 3",
"self",
".",
"pub",
".",
"setsockopt",
"(",
"zmq",
".",
"SNDHWM",
",",
"self",
".",
"opts",
"[",
"'hwm'",
"]",
")",
"# Pipe to the publishers",
"self",
".",
"publisher_pub",
"=",
"self",
".",
"ctx",
".",
"socket",
"(",
"zmq",
".",
"PUB",
")",
"self",
".",
"publisher_pub",
".",
"connect",
"(",
"PUB_PX_IPC_URL",
")",
"try",
":",
"self",
".",
"publisher_pub",
".",
"setsockopt",
"(",
"zmq",
".",
"HWM",
",",
"self",
".",
"opts",
"[",
"'hwm'",
"]",
")",
"# zmq 2",
"except",
"AttributeError",
":",
"# zmq 3",
"self",
".",
"publisher_pub",
".",
"setsockopt",
"(",
"zmq",
".",
"SNDHWM",
",",
"self",
".",
"opts",
"[",
"'hwm'",
"]",
")"
] | Setup the IPC pub and sub.
Subscript to the listener IPC
and publish to the device specific IPC. | [
"Setup",
"the",
"IPC",
"pub",
"and",
"sub",
".",
"Subscript",
"to",
"the",
"listener",
"IPC",
"and",
"publish",
"to",
"the",
"device",
"specific",
"IPC",
"."
] | 4b89100a6e4f994aa004f3ea42a06dc803a7ccb0 | https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/server.py#L55-L90 | train | 233,491 |
napalm-automation/napalm-logs | napalm_logs/server.py | NapalmLogsServerProc._cleanup_buffer | def _cleanup_buffer(self):
'''
Periodically cleanup the buffer.
'''
if not self._buffer:
return
while True:
time.sleep(60)
log.debug('Cleaning up buffer')
items = self._buffer.items()
# The ``items`` function should also cleanup the buffer
log.debug('Collected items')
log.debug(list(items)) | python | def _cleanup_buffer(self):
'''
Periodically cleanup the buffer.
'''
if not self._buffer:
return
while True:
time.sleep(60)
log.debug('Cleaning up buffer')
items = self._buffer.items()
# The ``items`` function should also cleanup the buffer
log.debug('Collected items')
log.debug(list(items)) | [
"def",
"_cleanup_buffer",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_buffer",
":",
"return",
"while",
"True",
":",
"time",
".",
"sleep",
"(",
"60",
")",
"log",
".",
"debug",
"(",
"'Cleaning up buffer'",
")",
"items",
"=",
"self",
".",
"_buffer",
".",
"items",
"(",
")",
"# The ``items`` function should also cleanup the buffer",
"log",
".",
"debug",
"(",
"'Collected items'",
")",
"log",
".",
"debug",
"(",
"list",
"(",
"items",
")",
")"
] | Periodically cleanup the buffer. | [
"Periodically",
"cleanup",
"the",
"buffer",
"."
] | 4b89100a6e4f994aa004f3ea42a06dc803a7ccb0 | https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/server.py#L92-L104 | train | 233,492 |
napalm-automation/napalm-logs | napalm_logs/server.py | NapalmLogsServerProc._compile_prefixes | def _compile_prefixes(self):
'''
Create a dict of all OS prefixes and their compiled regexs
'''
self.compiled_prefixes = {}
for dev_os, os_config in self.config.items():
if not os_config:
continue
self.compiled_prefixes[dev_os] = []
for prefix in os_config.get('prefixes', []):
values = prefix.get('values', {})
line = prefix.get('line', '')
if prefix.get('__python_fun__'):
self.compiled_prefixes[dev_os].append({
'__python_fun__': prefix['__python_fun__'],
'__python_mod__': prefix['__python_mod__']
})
continue # if python profiler defined for this prefix,
# no need to go further, but jump to the next prefix
# Add 'pri' and 'message' to the line, and values
line = '{{pri}}{}{{message}}'.format(line)
# PRI https://tools.ietf.org/html/rfc5424#section-6.2.1
values['pri'] = r'\<(\d+)\>'
values['message'] = '(.*)'
# We will now figure out which position each value is in so we can use it with the match statement
position = {}
for key in values.keys():
position[line.find('{' + key + '}')] = key
sorted_position = {}
for i, elem in enumerate(sorted(position.items())):
sorted_position[elem[1]] = i + 1
# Escape the line, then remove the escape for the curly bracets so they can be used when formatting
escaped = re.escape(line).replace(r'\{', '{').replace(r'\}', '}')
# Replace a whitespace with \s+
escaped = escaped.replace(r'\ ', r'\s+')
self.compiled_prefixes[dev_os].append({
'prefix': re.compile(escaped.format(**values)),
'prefix_positions': sorted_position,
'raw_prefix': escaped.format(**values),
'values': values
}) | python | def _compile_prefixes(self):
'''
Create a dict of all OS prefixes and their compiled regexs
'''
self.compiled_prefixes = {}
for dev_os, os_config in self.config.items():
if not os_config:
continue
self.compiled_prefixes[dev_os] = []
for prefix in os_config.get('prefixes', []):
values = prefix.get('values', {})
line = prefix.get('line', '')
if prefix.get('__python_fun__'):
self.compiled_prefixes[dev_os].append({
'__python_fun__': prefix['__python_fun__'],
'__python_mod__': prefix['__python_mod__']
})
continue # if python profiler defined for this prefix,
# no need to go further, but jump to the next prefix
# Add 'pri' and 'message' to the line, and values
line = '{{pri}}{}{{message}}'.format(line)
# PRI https://tools.ietf.org/html/rfc5424#section-6.2.1
values['pri'] = r'\<(\d+)\>'
values['message'] = '(.*)'
# We will now figure out which position each value is in so we can use it with the match statement
position = {}
for key in values.keys():
position[line.find('{' + key + '}')] = key
sorted_position = {}
for i, elem in enumerate(sorted(position.items())):
sorted_position[elem[1]] = i + 1
# Escape the line, then remove the escape for the curly bracets so they can be used when formatting
escaped = re.escape(line).replace(r'\{', '{').replace(r'\}', '}')
# Replace a whitespace with \s+
escaped = escaped.replace(r'\ ', r'\s+')
self.compiled_prefixes[dev_os].append({
'prefix': re.compile(escaped.format(**values)),
'prefix_positions': sorted_position,
'raw_prefix': escaped.format(**values),
'values': values
}) | [
"def",
"_compile_prefixes",
"(",
"self",
")",
":",
"self",
".",
"compiled_prefixes",
"=",
"{",
"}",
"for",
"dev_os",
",",
"os_config",
"in",
"self",
".",
"config",
".",
"items",
"(",
")",
":",
"if",
"not",
"os_config",
":",
"continue",
"self",
".",
"compiled_prefixes",
"[",
"dev_os",
"]",
"=",
"[",
"]",
"for",
"prefix",
"in",
"os_config",
".",
"get",
"(",
"'prefixes'",
",",
"[",
"]",
")",
":",
"values",
"=",
"prefix",
".",
"get",
"(",
"'values'",
",",
"{",
"}",
")",
"line",
"=",
"prefix",
".",
"get",
"(",
"'line'",
",",
"''",
")",
"if",
"prefix",
".",
"get",
"(",
"'__python_fun__'",
")",
":",
"self",
".",
"compiled_prefixes",
"[",
"dev_os",
"]",
".",
"append",
"(",
"{",
"'__python_fun__'",
":",
"prefix",
"[",
"'__python_fun__'",
"]",
",",
"'__python_mod__'",
":",
"prefix",
"[",
"'__python_mod__'",
"]",
"}",
")",
"continue",
"# if python profiler defined for this prefix,",
"# no need to go further, but jump to the next prefix",
"# Add 'pri' and 'message' to the line, and values",
"line",
"=",
"'{{pri}}{}{{message}}'",
".",
"format",
"(",
"line",
")",
"# PRI https://tools.ietf.org/html/rfc5424#section-6.2.1",
"values",
"[",
"'pri'",
"]",
"=",
"r'\\<(\\d+)\\>'",
"values",
"[",
"'message'",
"]",
"=",
"'(.*)'",
"# We will now figure out which position each value is in so we can use it with the match statement",
"position",
"=",
"{",
"}",
"for",
"key",
"in",
"values",
".",
"keys",
"(",
")",
":",
"position",
"[",
"line",
".",
"find",
"(",
"'{'",
"+",
"key",
"+",
"'}'",
")",
"]",
"=",
"key",
"sorted_position",
"=",
"{",
"}",
"for",
"i",
",",
"elem",
"in",
"enumerate",
"(",
"sorted",
"(",
"position",
".",
"items",
"(",
")",
")",
")",
":",
"sorted_position",
"[",
"elem",
"[",
"1",
"]",
"]",
"=",
"i",
"+",
"1",
"# Escape the line, then remove the escape for the curly bracets so they can be used when formatting",
"escaped",
"=",
"re",
".",
"escape",
"(",
"line",
")",
".",
"replace",
"(",
"r'\\{'",
",",
"'{'",
")",
".",
"replace",
"(",
"r'\\}'",
",",
"'}'",
")",
"# Replace a whitespace with \\s+",
"escaped",
"=",
"escaped",
".",
"replace",
"(",
"r'\\ '",
",",
"r'\\s+'",
")",
"self",
".",
"compiled_prefixes",
"[",
"dev_os",
"]",
".",
"append",
"(",
"{",
"'prefix'",
":",
"re",
".",
"compile",
"(",
"escaped",
".",
"format",
"(",
"*",
"*",
"values",
")",
")",
",",
"'prefix_positions'",
":",
"sorted_position",
",",
"'raw_prefix'",
":",
"escaped",
".",
"format",
"(",
"*",
"*",
"values",
")",
",",
"'values'",
":",
"values",
"}",
")"
] | Create a dict of all OS prefixes and their compiled regexs | [
"Create",
"a",
"dict",
"of",
"all",
"OS",
"prefixes",
"and",
"their",
"compiled",
"regexs"
] | 4b89100a6e4f994aa004f3ea42a06dc803a7ccb0 | https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/server.py#L106-L146 | train | 233,493 |
napalm-automation/napalm-logs | napalm_logs/server.py | NapalmLogsServerProc._identify_prefix | def _identify_prefix(self, msg, data):
'''
Check the message again each OS prefix and if matched return the
message dict
'''
prefix_id = -1
for prefix in data:
msg_dict = {}
prefix_id += 1
match = None
if '__python_fun__' in prefix:
log.debug('Trying to match using the %s custom python profiler', prefix['__python_mod__'])
try:
match = prefix['__python_fun__'](msg)
except Exception:
log.error('Exception while parsing %s with the %s python profiler',
msg, prefix['__python_mod__'], exc_info=True)
else:
log.debug('Matching using YAML-defined profiler:')
log.debug(prefix['raw_prefix'])
match = prefix['prefix'].search(msg)
if not match:
log.debug('Match not found')
continue
if '__python_fun__' in prefix:
log.debug('%s matched using the custom python profiler %s', msg, prefix['__python_mod__'])
msg_dict = match # the output as-is from the custom function
else:
positions = prefix.get('prefix_positions', {})
values = prefix.get('values')
msg_dict = {}
for key in values.keys():
msg_dict[key] = match.group(positions.get(key))
# Remove whitespace from the start or end of the message
msg_dict['__prefix_id__'] = prefix_id
msg_dict['message'] = msg_dict['message'].strip()
# The pri has to be an int as it is retrived using regex '\<(\d+)\>'
if 'pri' in msg_dict:
msg_dict['facility'] = int(int(msg_dict['pri']) / 8)
msg_dict['severity'] = int(int(msg_dict['pri']) - (msg_dict['facility'] * 8))
return msg_dict | python | def _identify_prefix(self, msg, data):
'''
Check the message again each OS prefix and if matched return the
message dict
'''
prefix_id = -1
for prefix in data:
msg_dict = {}
prefix_id += 1
match = None
if '__python_fun__' in prefix:
log.debug('Trying to match using the %s custom python profiler', prefix['__python_mod__'])
try:
match = prefix['__python_fun__'](msg)
except Exception:
log.error('Exception while parsing %s with the %s python profiler',
msg, prefix['__python_mod__'], exc_info=True)
else:
log.debug('Matching using YAML-defined profiler:')
log.debug(prefix['raw_prefix'])
match = prefix['prefix'].search(msg)
if not match:
log.debug('Match not found')
continue
if '__python_fun__' in prefix:
log.debug('%s matched using the custom python profiler %s', msg, prefix['__python_mod__'])
msg_dict = match # the output as-is from the custom function
else:
positions = prefix.get('prefix_positions', {})
values = prefix.get('values')
msg_dict = {}
for key in values.keys():
msg_dict[key] = match.group(positions.get(key))
# Remove whitespace from the start or end of the message
msg_dict['__prefix_id__'] = prefix_id
msg_dict['message'] = msg_dict['message'].strip()
# The pri has to be an int as it is retrived using regex '\<(\d+)\>'
if 'pri' in msg_dict:
msg_dict['facility'] = int(int(msg_dict['pri']) / 8)
msg_dict['severity'] = int(int(msg_dict['pri']) - (msg_dict['facility'] * 8))
return msg_dict | [
"def",
"_identify_prefix",
"(",
"self",
",",
"msg",
",",
"data",
")",
":",
"prefix_id",
"=",
"-",
"1",
"for",
"prefix",
"in",
"data",
":",
"msg_dict",
"=",
"{",
"}",
"prefix_id",
"+=",
"1",
"match",
"=",
"None",
"if",
"'__python_fun__'",
"in",
"prefix",
":",
"log",
".",
"debug",
"(",
"'Trying to match using the %s custom python profiler'",
",",
"prefix",
"[",
"'__python_mod__'",
"]",
")",
"try",
":",
"match",
"=",
"prefix",
"[",
"'__python_fun__'",
"]",
"(",
"msg",
")",
"except",
"Exception",
":",
"log",
".",
"error",
"(",
"'Exception while parsing %s with the %s python profiler'",
",",
"msg",
",",
"prefix",
"[",
"'__python_mod__'",
"]",
",",
"exc_info",
"=",
"True",
")",
"else",
":",
"log",
".",
"debug",
"(",
"'Matching using YAML-defined profiler:'",
")",
"log",
".",
"debug",
"(",
"prefix",
"[",
"'raw_prefix'",
"]",
")",
"match",
"=",
"prefix",
"[",
"'prefix'",
"]",
".",
"search",
"(",
"msg",
")",
"if",
"not",
"match",
":",
"log",
".",
"debug",
"(",
"'Match not found'",
")",
"continue",
"if",
"'__python_fun__'",
"in",
"prefix",
":",
"log",
".",
"debug",
"(",
"'%s matched using the custom python profiler %s'",
",",
"msg",
",",
"prefix",
"[",
"'__python_mod__'",
"]",
")",
"msg_dict",
"=",
"match",
"# the output as-is from the custom function",
"else",
":",
"positions",
"=",
"prefix",
".",
"get",
"(",
"'prefix_positions'",
",",
"{",
"}",
")",
"values",
"=",
"prefix",
".",
"get",
"(",
"'values'",
")",
"msg_dict",
"=",
"{",
"}",
"for",
"key",
"in",
"values",
".",
"keys",
"(",
")",
":",
"msg_dict",
"[",
"key",
"]",
"=",
"match",
".",
"group",
"(",
"positions",
".",
"get",
"(",
"key",
")",
")",
"# Remove whitespace from the start or end of the message",
"msg_dict",
"[",
"'__prefix_id__'",
"]",
"=",
"prefix_id",
"msg_dict",
"[",
"'message'",
"]",
"=",
"msg_dict",
"[",
"'message'",
"]",
".",
"strip",
"(",
")",
"# The pri has to be an int as it is retrived using regex '\\<(\\d+)\\>'",
"if",
"'pri'",
"in",
"msg_dict",
":",
"msg_dict",
"[",
"'facility'",
"]",
"=",
"int",
"(",
"int",
"(",
"msg_dict",
"[",
"'pri'",
"]",
")",
"/",
"8",
")",
"msg_dict",
"[",
"'severity'",
"]",
"=",
"int",
"(",
"int",
"(",
"msg_dict",
"[",
"'pri'",
"]",
")",
"-",
"(",
"msg_dict",
"[",
"'facility'",
"]",
"*",
"8",
")",
")",
"return",
"msg_dict"
] | Check the message again each OS prefix and if matched return the
message dict | [
"Check",
"the",
"message",
"again",
"each",
"OS",
"prefix",
"and",
"if",
"matched",
"return",
"the",
"message",
"dict"
] | 4b89100a6e4f994aa004f3ea42a06dc803a7ccb0 | https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/server.py#L150-L191 | train | 233,494 |
napalm-automation/napalm-logs | napalm_logs/server.py | NapalmLogsServerProc._identify_os | def _identify_os(self, msg):
'''
Using the prefix of the syslog message,
we are able to identify the operating system and then continue parsing.
'''
ret = []
for dev_os, data in self.compiled_prefixes.items():
# TODO Should we prevent attepmting to determine the OS for the blacklisted?
# [mircea] I think its good from a logging perspective to know at least that
# that the server found the matching and it tells that it won't be processed
# further. Later, we could potentially add an option to control this.
log.debug('Matching under %s', dev_os)
msg_dict = self._identify_prefix(msg, data)
if msg_dict:
log.debug('Adding %s to list of matched OS', dev_os)
ret.append((dev_os, msg_dict))
else:
log.debug('No match found for %s', dev_os)
if not ret:
log.debug('Not matched any OS, returning original log')
msg_dict = {'message': msg}
ret.append((None, msg_dict))
return ret | python | def _identify_os(self, msg):
'''
Using the prefix of the syslog message,
we are able to identify the operating system and then continue parsing.
'''
ret = []
for dev_os, data in self.compiled_prefixes.items():
# TODO Should we prevent attepmting to determine the OS for the blacklisted?
# [mircea] I think its good from a logging perspective to know at least that
# that the server found the matching and it tells that it won't be processed
# further. Later, we could potentially add an option to control this.
log.debug('Matching under %s', dev_os)
msg_dict = self._identify_prefix(msg, data)
if msg_dict:
log.debug('Adding %s to list of matched OS', dev_os)
ret.append((dev_os, msg_dict))
else:
log.debug('No match found for %s', dev_os)
if not ret:
log.debug('Not matched any OS, returning original log')
msg_dict = {'message': msg}
ret.append((None, msg_dict))
return ret | [
"def",
"_identify_os",
"(",
"self",
",",
"msg",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"dev_os",
",",
"data",
"in",
"self",
".",
"compiled_prefixes",
".",
"items",
"(",
")",
":",
"# TODO Should we prevent attepmting to determine the OS for the blacklisted?",
"# [mircea] I think its good from a logging perspective to know at least that",
"# that the server found the matching and it tells that it won't be processed",
"# further. Later, we could potentially add an option to control this.",
"log",
".",
"debug",
"(",
"'Matching under %s'",
",",
"dev_os",
")",
"msg_dict",
"=",
"self",
".",
"_identify_prefix",
"(",
"msg",
",",
"data",
")",
"if",
"msg_dict",
":",
"log",
".",
"debug",
"(",
"'Adding %s to list of matched OS'",
",",
"dev_os",
")",
"ret",
".",
"append",
"(",
"(",
"dev_os",
",",
"msg_dict",
")",
")",
"else",
":",
"log",
".",
"debug",
"(",
"'No match found for %s'",
",",
"dev_os",
")",
"if",
"not",
"ret",
":",
"log",
".",
"debug",
"(",
"'Not matched any OS, returning original log'",
")",
"msg_dict",
"=",
"{",
"'message'",
":",
"msg",
"}",
"ret",
".",
"append",
"(",
"(",
"None",
",",
"msg_dict",
")",
")",
"return",
"ret"
] | Using the prefix of the syslog message,
we are able to identify the operating system and then continue parsing. | [
"Using",
"the",
"prefix",
"of",
"the",
"syslog",
"message",
"we",
"are",
"able",
"to",
"identify",
"the",
"operating",
"system",
"and",
"then",
"continue",
"parsing",
"."
] | 4b89100a6e4f994aa004f3ea42a06dc803a7ccb0 | https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/server.py#L193-L215 | train | 233,495 |
napalm-automation/napalm-logs | napalm_logs/device.py | NapalmLogsDeviceProc._setup_ipc | def _setup_ipc(self):
'''
Subscribe to the right topic
in the device IPC and publish to the
publisher proxy.
'''
self.ctx = zmq.Context()
# subscribe to device IPC
log.debug('Creating the dealer IPC for %s', self._name)
self.sub = self.ctx.socket(zmq.DEALER)
if six.PY2:
self.sub.setsockopt(zmq.IDENTITY, self._name)
elif six.PY3:
self.sub.setsockopt(zmq.IDENTITY, bytes(self._name, 'utf-8'))
try:
self.sub.setsockopt(zmq.HWM, self.opts['hwm'])
# zmq 2
except AttributeError:
# zmq 3
self.sub.setsockopt(zmq.RCVHWM, self.opts['hwm'])
# subscribe to the corresponding IPC pipe
self.sub.connect(DEV_IPC_URL)
# publish to the publisher IPC
self.pub = self.ctx.socket(zmq.PUB)
self.pub.connect(PUB_PX_IPC_URL)
try:
self.pub.setsockopt(zmq.HWM, self.opts['hwm'])
# zmq 2
except AttributeError:
# zmq 3
self.pub.setsockopt(zmq.SNDHWM, self.opts['hwm']) | python | def _setup_ipc(self):
'''
Subscribe to the right topic
in the device IPC and publish to the
publisher proxy.
'''
self.ctx = zmq.Context()
# subscribe to device IPC
log.debug('Creating the dealer IPC for %s', self._name)
self.sub = self.ctx.socket(zmq.DEALER)
if six.PY2:
self.sub.setsockopt(zmq.IDENTITY, self._name)
elif six.PY3:
self.sub.setsockopt(zmq.IDENTITY, bytes(self._name, 'utf-8'))
try:
self.sub.setsockopt(zmq.HWM, self.opts['hwm'])
# zmq 2
except AttributeError:
# zmq 3
self.sub.setsockopt(zmq.RCVHWM, self.opts['hwm'])
# subscribe to the corresponding IPC pipe
self.sub.connect(DEV_IPC_URL)
# publish to the publisher IPC
self.pub = self.ctx.socket(zmq.PUB)
self.pub.connect(PUB_PX_IPC_URL)
try:
self.pub.setsockopt(zmq.HWM, self.opts['hwm'])
# zmq 2
except AttributeError:
# zmq 3
self.pub.setsockopt(zmq.SNDHWM, self.opts['hwm']) | [
"def",
"_setup_ipc",
"(",
"self",
")",
":",
"self",
".",
"ctx",
"=",
"zmq",
".",
"Context",
"(",
")",
"# subscribe to device IPC",
"log",
".",
"debug",
"(",
"'Creating the dealer IPC for %s'",
",",
"self",
".",
"_name",
")",
"self",
".",
"sub",
"=",
"self",
".",
"ctx",
".",
"socket",
"(",
"zmq",
".",
"DEALER",
")",
"if",
"six",
".",
"PY2",
":",
"self",
".",
"sub",
".",
"setsockopt",
"(",
"zmq",
".",
"IDENTITY",
",",
"self",
".",
"_name",
")",
"elif",
"six",
".",
"PY3",
":",
"self",
".",
"sub",
".",
"setsockopt",
"(",
"zmq",
".",
"IDENTITY",
",",
"bytes",
"(",
"self",
".",
"_name",
",",
"'utf-8'",
")",
")",
"try",
":",
"self",
".",
"sub",
".",
"setsockopt",
"(",
"zmq",
".",
"HWM",
",",
"self",
".",
"opts",
"[",
"'hwm'",
"]",
")",
"# zmq 2",
"except",
"AttributeError",
":",
"# zmq 3",
"self",
".",
"sub",
".",
"setsockopt",
"(",
"zmq",
".",
"RCVHWM",
",",
"self",
".",
"opts",
"[",
"'hwm'",
"]",
")",
"# subscribe to the corresponding IPC pipe",
"self",
".",
"sub",
".",
"connect",
"(",
"DEV_IPC_URL",
")",
"# publish to the publisher IPC",
"self",
".",
"pub",
"=",
"self",
".",
"ctx",
".",
"socket",
"(",
"zmq",
".",
"PUB",
")",
"self",
".",
"pub",
".",
"connect",
"(",
"PUB_PX_IPC_URL",
")",
"try",
":",
"self",
".",
"pub",
".",
"setsockopt",
"(",
"zmq",
".",
"HWM",
",",
"self",
".",
"opts",
"[",
"'hwm'",
"]",
")",
"# zmq 2",
"except",
"AttributeError",
":",
"# zmq 3",
"self",
".",
"pub",
".",
"setsockopt",
"(",
"zmq",
".",
"SNDHWM",
",",
"self",
".",
"opts",
"[",
"'hwm'",
"]",
")"
] | Subscribe to the right topic
in the device IPC and publish to the
publisher proxy. | [
"Subscribe",
"to",
"the",
"right",
"topic",
"in",
"the",
"device",
"IPC",
"and",
"publish",
"to",
"the",
"publisher",
"proxy",
"."
] | 4b89100a6e4f994aa004f3ea42a06dc803a7ccb0 | https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/device.py#L52-L82 | train | 233,496 |
napalm-automation/napalm-logs | napalm_logs/device.py | NapalmLogsDeviceProc._compile_messages | def _compile_messages(self):
'''
Create a list of all OS messages and their compiled regexs
'''
self.compiled_messages = []
if not self._config:
return
for message_dict in self._config.get('messages', {}):
error = message_dict['error']
tag = message_dict['tag']
model = message_dict['model']
match_on = message_dict.get('match_on', 'tag')
if '__python_fun__' in message_dict:
self.compiled_messages.append({
'error': error,
'tag': tag,
'match_on': match_on,
'model': model,
'__python_fun__': message_dict['__python_fun__']
})
continue
values = message_dict['values']
line = message_dict['line']
mapping = message_dict['mapping']
# We will now figure out which position each value is in so we can use it with the match statement
position = {}
replace = {}
for key in values.keys():
if '|' in key:
new_key, replace[new_key] = key.replace(' ', '').split('|')
values[new_key] = values.pop(key)
key = new_key
position[line.find('{' + key + '}')] = key
sorted_position = {}
for i, elem in enumerate(sorted(position.items())):
sorted_position[elem[1]] = i + 1
# Escape the line, then remove the escape for the curly bracets so they can be used when formatting
escaped = re.escape(line).replace(r'\{', '{').replace(r'\}', '}')
# Replace a whitespace with \s+
escaped = escaped.replace(r'\ ', r'\s+')
self.compiled_messages.append(
{
'error': error,
'tag': tag,
'match_on': match_on,
'line': re.compile(escaped.format(**values)),
'positions': sorted_position,
'values': values,
'replace': replace,
'model': model,
'mapping': mapping
}
)
log.debug('Compiled messages:')
log.debug(self.compiled_messages) | python | def _compile_messages(self):
'''
Create a list of all OS messages and their compiled regexs
'''
self.compiled_messages = []
if not self._config:
return
for message_dict in self._config.get('messages', {}):
error = message_dict['error']
tag = message_dict['tag']
model = message_dict['model']
match_on = message_dict.get('match_on', 'tag')
if '__python_fun__' in message_dict:
self.compiled_messages.append({
'error': error,
'tag': tag,
'match_on': match_on,
'model': model,
'__python_fun__': message_dict['__python_fun__']
})
continue
values = message_dict['values']
line = message_dict['line']
mapping = message_dict['mapping']
# We will now figure out which position each value is in so we can use it with the match statement
position = {}
replace = {}
for key in values.keys():
if '|' in key:
new_key, replace[new_key] = key.replace(' ', '').split('|')
values[new_key] = values.pop(key)
key = new_key
position[line.find('{' + key + '}')] = key
sorted_position = {}
for i, elem in enumerate(sorted(position.items())):
sorted_position[elem[1]] = i + 1
# Escape the line, then remove the escape for the curly bracets so they can be used when formatting
escaped = re.escape(line).replace(r'\{', '{').replace(r'\}', '}')
# Replace a whitespace with \s+
escaped = escaped.replace(r'\ ', r'\s+')
self.compiled_messages.append(
{
'error': error,
'tag': tag,
'match_on': match_on,
'line': re.compile(escaped.format(**values)),
'positions': sorted_position,
'values': values,
'replace': replace,
'model': model,
'mapping': mapping
}
)
log.debug('Compiled messages:')
log.debug(self.compiled_messages) | [
"def",
"_compile_messages",
"(",
"self",
")",
":",
"self",
".",
"compiled_messages",
"=",
"[",
"]",
"if",
"not",
"self",
".",
"_config",
":",
"return",
"for",
"message_dict",
"in",
"self",
".",
"_config",
".",
"get",
"(",
"'messages'",
",",
"{",
"}",
")",
":",
"error",
"=",
"message_dict",
"[",
"'error'",
"]",
"tag",
"=",
"message_dict",
"[",
"'tag'",
"]",
"model",
"=",
"message_dict",
"[",
"'model'",
"]",
"match_on",
"=",
"message_dict",
".",
"get",
"(",
"'match_on'",
",",
"'tag'",
")",
"if",
"'__python_fun__'",
"in",
"message_dict",
":",
"self",
".",
"compiled_messages",
".",
"append",
"(",
"{",
"'error'",
":",
"error",
",",
"'tag'",
":",
"tag",
",",
"'match_on'",
":",
"match_on",
",",
"'model'",
":",
"model",
",",
"'__python_fun__'",
":",
"message_dict",
"[",
"'__python_fun__'",
"]",
"}",
")",
"continue",
"values",
"=",
"message_dict",
"[",
"'values'",
"]",
"line",
"=",
"message_dict",
"[",
"'line'",
"]",
"mapping",
"=",
"message_dict",
"[",
"'mapping'",
"]",
"# We will now figure out which position each value is in so we can use it with the match statement",
"position",
"=",
"{",
"}",
"replace",
"=",
"{",
"}",
"for",
"key",
"in",
"values",
".",
"keys",
"(",
")",
":",
"if",
"'|'",
"in",
"key",
":",
"new_key",
",",
"replace",
"[",
"new_key",
"]",
"=",
"key",
".",
"replace",
"(",
"' '",
",",
"''",
")",
".",
"split",
"(",
"'|'",
")",
"values",
"[",
"new_key",
"]",
"=",
"values",
".",
"pop",
"(",
"key",
")",
"key",
"=",
"new_key",
"position",
"[",
"line",
".",
"find",
"(",
"'{'",
"+",
"key",
"+",
"'}'",
")",
"]",
"=",
"key",
"sorted_position",
"=",
"{",
"}",
"for",
"i",
",",
"elem",
"in",
"enumerate",
"(",
"sorted",
"(",
"position",
".",
"items",
"(",
")",
")",
")",
":",
"sorted_position",
"[",
"elem",
"[",
"1",
"]",
"]",
"=",
"i",
"+",
"1",
"# Escape the line, then remove the escape for the curly bracets so they can be used when formatting",
"escaped",
"=",
"re",
".",
"escape",
"(",
"line",
")",
".",
"replace",
"(",
"r'\\{'",
",",
"'{'",
")",
".",
"replace",
"(",
"r'\\}'",
",",
"'}'",
")",
"# Replace a whitespace with \\s+",
"escaped",
"=",
"escaped",
".",
"replace",
"(",
"r'\\ '",
",",
"r'\\s+'",
")",
"self",
".",
"compiled_messages",
".",
"append",
"(",
"{",
"'error'",
":",
"error",
",",
"'tag'",
":",
"tag",
",",
"'match_on'",
":",
"match_on",
",",
"'line'",
":",
"re",
".",
"compile",
"(",
"escaped",
".",
"format",
"(",
"*",
"*",
"values",
")",
")",
",",
"'positions'",
":",
"sorted_position",
",",
"'values'",
":",
"values",
",",
"'replace'",
":",
"replace",
",",
"'model'",
":",
"model",
",",
"'mapping'",
":",
"mapping",
"}",
")",
"log",
".",
"debug",
"(",
"'Compiled messages:'",
")",
"log",
".",
"debug",
"(",
"self",
".",
"compiled_messages",
")"
] | Create a list of all OS messages and their compiled regexs | [
"Create",
"a",
"list",
"of",
"all",
"OS",
"messages",
"and",
"their",
"compiled",
"regexs"
] | 4b89100a6e4f994aa004f3ea42a06dc803a7ccb0 | https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/device.py#L84-L138 | train | 233,497 |
napalm-automation/napalm-logs | napalm_logs/device.py | NapalmLogsDeviceProc._parse | def _parse(self, msg_dict):
'''
Parse a syslog message and check what OpenConfig object should
be generated.
'''
error_present = False
# log.debug('Matching the message:')
# log.debug(msg_dict)
for message in self.compiled_messages:
# log.debug('Matching using:')
# log.debug(message)
match_on = message['match_on']
if match_on not in msg_dict:
# log.debug('%s is not a valid key in the partially parsed dict', match_on)
continue
if message['tag'] != msg_dict[match_on]:
continue
if '__python_fun__' in message:
return {
'model': message['model'],
'error': message['error'],
'__python_fun__': message['__python_fun__']
}
error_present = True
match = message['line'].search(msg_dict['message'])
if not match:
continue
positions = message.get('positions', {})
values = message.get('values')
ret = {
'model': message['model'],
'mapping': message['mapping'],
'replace': message['replace'],
'error': message['error']
}
for key in values.keys():
# Check if the value needs to be replaced
if key in message['replace']:
result = napalm_logs.utils.cast(match.group(positions.get(key)), message['replace'][key])
else:
result = match.group(positions.get(key))
ret[key] = result
return ret
if error_present is True:
log.info('Configured regex did not match for os: %s tag %s', self._name, msg_dict.get('tag', ''))
else:
log.info('Syslog message not configured for os: %s tag %s', self._name, msg_dict.get('tag', '')) | python | def _parse(self, msg_dict):
'''
Parse a syslog message and check what OpenConfig object should
be generated.
'''
error_present = False
# log.debug('Matching the message:')
# log.debug(msg_dict)
for message in self.compiled_messages:
# log.debug('Matching using:')
# log.debug(message)
match_on = message['match_on']
if match_on not in msg_dict:
# log.debug('%s is not a valid key in the partially parsed dict', match_on)
continue
if message['tag'] != msg_dict[match_on]:
continue
if '__python_fun__' in message:
return {
'model': message['model'],
'error': message['error'],
'__python_fun__': message['__python_fun__']
}
error_present = True
match = message['line'].search(msg_dict['message'])
if not match:
continue
positions = message.get('positions', {})
values = message.get('values')
ret = {
'model': message['model'],
'mapping': message['mapping'],
'replace': message['replace'],
'error': message['error']
}
for key in values.keys():
# Check if the value needs to be replaced
if key in message['replace']:
result = napalm_logs.utils.cast(match.group(positions.get(key)), message['replace'][key])
else:
result = match.group(positions.get(key))
ret[key] = result
return ret
if error_present is True:
log.info('Configured regex did not match for os: %s tag %s', self._name, msg_dict.get('tag', ''))
else:
log.info('Syslog message not configured for os: %s tag %s', self._name, msg_dict.get('tag', '')) | [
"def",
"_parse",
"(",
"self",
",",
"msg_dict",
")",
":",
"error_present",
"=",
"False",
"# log.debug('Matching the message:')",
"# log.debug(msg_dict)",
"for",
"message",
"in",
"self",
".",
"compiled_messages",
":",
"# log.debug('Matching using:')",
"# log.debug(message)",
"match_on",
"=",
"message",
"[",
"'match_on'",
"]",
"if",
"match_on",
"not",
"in",
"msg_dict",
":",
"# log.debug('%s is not a valid key in the partially parsed dict', match_on)",
"continue",
"if",
"message",
"[",
"'tag'",
"]",
"!=",
"msg_dict",
"[",
"match_on",
"]",
":",
"continue",
"if",
"'__python_fun__'",
"in",
"message",
":",
"return",
"{",
"'model'",
":",
"message",
"[",
"'model'",
"]",
",",
"'error'",
":",
"message",
"[",
"'error'",
"]",
",",
"'__python_fun__'",
":",
"message",
"[",
"'__python_fun__'",
"]",
"}",
"error_present",
"=",
"True",
"match",
"=",
"message",
"[",
"'line'",
"]",
".",
"search",
"(",
"msg_dict",
"[",
"'message'",
"]",
")",
"if",
"not",
"match",
":",
"continue",
"positions",
"=",
"message",
".",
"get",
"(",
"'positions'",
",",
"{",
"}",
")",
"values",
"=",
"message",
".",
"get",
"(",
"'values'",
")",
"ret",
"=",
"{",
"'model'",
":",
"message",
"[",
"'model'",
"]",
",",
"'mapping'",
":",
"message",
"[",
"'mapping'",
"]",
",",
"'replace'",
":",
"message",
"[",
"'replace'",
"]",
",",
"'error'",
":",
"message",
"[",
"'error'",
"]",
"}",
"for",
"key",
"in",
"values",
".",
"keys",
"(",
")",
":",
"# Check if the value needs to be replaced",
"if",
"key",
"in",
"message",
"[",
"'replace'",
"]",
":",
"result",
"=",
"napalm_logs",
".",
"utils",
".",
"cast",
"(",
"match",
".",
"group",
"(",
"positions",
".",
"get",
"(",
"key",
")",
")",
",",
"message",
"[",
"'replace'",
"]",
"[",
"key",
"]",
")",
"else",
":",
"result",
"=",
"match",
".",
"group",
"(",
"positions",
".",
"get",
"(",
"key",
")",
")",
"ret",
"[",
"key",
"]",
"=",
"result",
"return",
"ret",
"if",
"error_present",
"is",
"True",
":",
"log",
".",
"info",
"(",
"'Configured regex did not match for os: %s tag %s'",
",",
"self",
".",
"_name",
",",
"msg_dict",
".",
"get",
"(",
"'tag'",
",",
"''",
")",
")",
"else",
":",
"log",
".",
"info",
"(",
"'Syslog message not configured for os: %s tag %s'",
",",
"self",
".",
"_name",
",",
"msg_dict",
".",
"get",
"(",
"'tag'",
",",
"''",
")",
")"
] | Parse a syslog message and check what OpenConfig object should
be generated. | [
"Parse",
"a",
"syslog",
"message",
"and",
"check",
"what",
"OpenConfig",
"object",
"should",
"be",
"generated",
"."
] | 4b89100a6e4f994aa004f3ea42a06dc803a7ccb0 | https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/device.py#L140-L186 | train | 233,498 |
napalm-automation/napalm-logs | napalm_logs/device.py | NapalmLogsDeviceProc._emit | def _emit(self, **kwargs):
'''
Emit an OpenConfig object given a certain combination of
fields mappeed in the config to the corresponding hierarchy.
'''
oc_dict = {}
for mapping, result_key in kwargs['mapping']['variables'].items():
result = kwargs[result_key]
oc_dict = napalm_logs.utils.setval(mapping.format(**kwargs), result, oc_dict)
for mapping, result in kwargs['mapping']['static'].items():
oc_dict = napalm_logs.utils.setval(mapping.format(**kwargs), result, oc_dict)
return oc_dict | python | def _emit(self, **kwargs):
'''
Emit an OpenConfig object given a certain combination of
fields mappeed in the config to the corresponding hierarchy.
'''
oc_dict = {}
for mapping, result_key in kwargs['mapping']['variables'].items():
result = kwargs[result_key]
oc_dict = napalm_logs.utils.setval(mapping.format(**kwargs), result, oc_dict)
for mapping, result in kwargs['mapping']['static'].items():
oc_dict = napalm_logs.utils.setval(mapping.format(**kwargs), result, oc_dict)
return oc_dict | [
"def",
"_emit",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"oc_dict",
"=",
"{",
"}",
"for",
"mapping",
",",
"result_key",
"in",
"kwargs",
"[",
"'mapping'",
"]",
"[",
"'variables'",
"]",
".",
"items",
"(",
")",
":",
"result",
"=",
"kwargs",
"[",
"result_key",
"]",
"oc_dict",
"=",
"napalm_logs",
".",
"utils",
".",
"setval",
"(",
"mapping",
".",
"format",
"(",
"*",
"*",
"kwargs",
")",
",",
"result",
",",
"oc_dict",
")",
"for",
"mapping",
",",
"result",
"in",
"kwargs",
"[",
"'mapping'",
"]",
"[",
"'static'",
"]",
".",
"items",
"(",
")",
":",
"oc_dict",
"=",
"napalm_logs",
".",
"utils",
".",
"setval",
"(",
"mapping",
".",
"format",
"(",
"*",
"*",
"kwargs",
")",
",",
"result",
",",
"oc_dict",
")",
"return",
"oc_dict"
] | Emit an OpenConfig object given a certain combination of
fields mappeed in the config to the corresponding hierarchy. | [
"Emit",
"an",
"OpenConfig",
"object",
"given",
"a",
"certain",
"combination",
"of",
"fields",
"mappeed",
"in",
"the",
"config",
"to",
"the",
"corresponding",
"hierarchy",
"."
] | 4b89100a6e4f994aa004f3ea42a06dc803a7ccb0 | https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/device.py#L188-L200 | train | 233,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.