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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
profusion/sgqlc | sgqlc/types/relay.py | connection_args | def connection_args(*lst, **mapping):
'''Returns the default parameters for connection.
Extra parameters may be given as argument, both as iterable,
positional tuples or mapping.
By default, provides:
- ``after: String``
- ``before: String``
- ``first: Int``
- ``last: Int``
'''
pd = ArgDict(*lst, **mapping)
pd.setdefault('after', String)
pd.setdefault('before', String)
pd.setdefault('first', Int)
pd.setdefault('last', Int)
return pd | python | def connection_args(*lst, **mapping):
'''Returns the default parameters for connection.
Extra parameters may be given as argument, both as iterable,
positional tuples or mapping.
By default, provides:
- ``after: String``
- ``before: String``
- ``first: Int``
- ``last: Int``
'''
pd = ArgDict(*lst, **mapping)
pd.setdefault('after', String)
pd.setdefault('before', String)
pd.setdefault('first', Int)
pd.setdefault('last', Int)
return pd | [
"def",
"connection_args",
"(",
"*",
"lst",
",",
"*",
"*",
"mapping",
")",
":",
"pd",
"=",
"ArgDict",
"(",
"*",
"lst",
",",
"*",
"*",
"mapping",
")",
"pd",
".",
"setdefault",
"(",
"'after'",
",",
"String",
")",
"pd",
".",
"setdefault",
"(",
"'before'",
",",
"String",
")",
"pd",
".",
"setdefault",
"(",
"'first'",
",",
"Int",
")",
"pd",
".",
"setdefault",
"(",
"'last'",
",",
"Int",
")",
"return",
"pd"
] | Returns the default parameters for connection.
Extra parameters may be given as argument, both as iterable,
positional tuples or mapping.
By default, provides:
- ``after: String``
- ``before: String``
- ``first: Int``
- ``last: Int`` | [
"Returns",
"the",
"default",
"parameters",
"for",
"connection",
"."
] | 684afb059c93f142150043cafac09b7fd52bfa27 | https://github.com/profusion/sgqlc/blob/684afb059c93f142150043cafac09b7fd52bfa27/sgqlc/types/relay.py#L406-L424 | train | 232,800 |
nchopin/particles | book/pmcmc/pmmh_lingauss_varying_scale.py | msjd | def msjd(theta):
"""Mean squared jumping distance.
"""
s = 0.
for p in theta.dtype.names:
s += np.sum(np.diff(theta[p], axis=0) ** 2)
return s | python | def msjd(theta):
"""Mean squared jumping distance.
"""
s = 0.
for p in theta.dtype.names:
s += np.sum(np.diff(theta[p], axis=0) ** 2)
return s | [
"def",
"msjd",
"(",
"theta",
")",
":",
"s",
"=",
"0.",
"for",
"p",
"in",
"theta",
".",
"dtype",
".",
"names",
":",
"s",
"+=",
"np",
".",
"sum",
"(",
"np",
".",
"diff",
"(",
"theta",
"[",
"p",
"]",
",",
"axis",
"=",
"0",
")",
"**",
"2",
")",
"return",
"s"
] | Mean squared jumping distance. | [
"Mean",
"squared",
"jumping",
"distance",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/book/pmcmc/pmmh_lingauss_varying_scale.py#L31-L37 | train | 232,801 |
nchopin/particles | particles/smc_samplers.py | StaticModel.loglik | def loglik(self, theta, t=None):
""" log-likelihood at given parameter values.
Parameters
----------
theta: dict-like
theta['par'] is a ndarray containing the N values for parameter par
t: int
time (if set to None, the full log-likelihood is returned)
Returns
-------
l: float numpy.ndarray
the N log-likelihood values
"""
if t is None:
t = self.T - 1
l = np.zeros(shape=theta.shape[0])
for s in range(t + 1):
l += self.logpyt(theta, s)
return l | python | def loglik(self, theta, t=None):
""" log-likelihood at given parameter values.
Parameters
----------
theta: dict-like
theta['par'] is a ndarray containing the N values for parameter par
t: int
time (if set to None, the full log-likelihood is returned)
Returns
-------
l: float numpy.ndarray
the N log-likelihood values
"""
if t is None:
t = self.T - 1
l = np.zeros(shape=theta.shape[0])
for s in range(t + 1):
l += self.logpyt(theta, s)
return l | [
"def",
"loglik",
"(",
"self",
",",
"theta",
",",
"t",
"=",
"None",
")",
":",
"if",
"t",
"is",
"None",
":",
"t",
"=",
"self",
".",
"T",
"-",
"1",
"l",
"=",
"np",
".",
"zeros",
"(",
"shape",
"=",
"theta",
".",
"shape",
"[",
"0",
"]",
")",
"for",
"s",
"in",
"range",
"(",
"t",
"+",
"1",
")",
":",
"l",
"+=",
"self",
".",
"logpyt",
"(",
"theta",
",",
"s",
")",
"return",
"l"
] | log-likelihood at given parameter values.
Parameters
----------
theta: dict-like
theta['par'] is a ndarray containing the N values for parameter par
t: int
time (if set to None, the full log-likelihood is returned)
Returns
-------
l: float numpy.ndarray
the N log-likelihood values | [
"log",
"-",
"likelihood",
"at",
"given",
"parameter",
"values",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/smc_samplers.py#L91-L111 | train | 232,802 |
nchopin/particles | particles/smc_samplers.py | StaticModel.logpost | def logpost(self, theta, t=None):
"""Posterior log-density at given parameter values.
Parameters
----------
theta: dict-like
theta['par'] is a ndarray containing the N values for parameter par
t: int
time (if set to None, the full posterior is returned)
Returns
-------
l: float numpy.ndarray
the N log-likelihood values
"""
return self.prior.logpdf(theta) + self.loglik(theta, t) | python | def logpost(self, theta, t=None):
"""Posterior log-density at given parameter values.
Parameters
----------
theta: dict-like
theta['par'] is a ndarray containing the N values for parameter par
t: int
time (if set to None, the full posterior is returned)
Returns
-------
l: float numpy.ndarray
the N log-likelihood values
"""
return self.prior.logpdf(theta) + self.loglik(theta, t) | [
"def",
"logpost",
"(",
"self",
",",
"theta",
",",
"t",
"=",
"None",
")",
":",
"return",
"self",
".",
"prior",
".",
"logpdf",
"(",
"theta",
")",
"+",
"self",
".",
"loglik",
"(",
"theta",
",",
"t",
")"
] | Posterior log-density at given parameter values.
Parameters
----------
theta: dict-like
theta['par'] is a ndarray containing the N values for parameter par
t: int
time (if set to None, the full posterior is returned)
Returns
-------
l: float numpy.ndarray
the N log-likelihood values | [
"Posterior",
"log",
"-",
"density",
"at",
"given",
"parameter",
"values",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/smc_samplers.py#L113-L128 | train | 232,803 |
nchopin/particles | particles/smc_samplers.py | FancyList.copyto | def copyto(self, src, where=None):
"""
Same syntax and functionality as numpy.copyto
"""
for n, _ in enumerate(self.l):
if where[n]:
self.l[n] = src.l[n] | python | def copyto(self, src, where=None):
"""
Same syntax and functionality as numpy.copyto
"""
for n, _ in enumerate(self.l):
if where[n]:
self.l[n] = src.l[n] | [
"def",
"copyto",
"(",
"self",
",",
"src",
",",
"where",
"=",
"None",
")",
":",
"for",
"n",
",",
"_",
"in",
"enumerate",
"(",
"self",
".",
"l",
")",
":",
"if",
"where",
"[",
"n",
"]",
":",
"self",
".",
"l",
"[",
"n",
"]",
"=",
"src",
".",
"l",
"[",
"n",
"]"
] | Same syntax and functionality as numpy.copyto | [
"Same",
"syntax",
"and",
"functionality",
"as",
"numpy",
".",
"copyto"
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/smc_samplers.py#L178-L185 | train | 232,804 |
nchopin/particles | particles/smc_samplers.py | ThetaParticles.copy | def copy(self):
"""Returns a copy of the object."""
attrs = {k: self.__dict__[k].copy() for k in self.containers}
attrs.update({k: cp.deepcopy(self.__dict__[k]) for k in self.shared})
return self.__class__(**attrs) | python | def copy(self):
"""Returns a copy of the object."""
attrs = {k: self.__dict__[k].copy() for k in self.containers}
attrs.update({k: cp.deepcopy(self.__dict__[k]) for k in self.shared})
return self.__class__(**attrs) | [
"def",
"copy",
"(",
"self",
")",
":",
"attrs",
"=",
"{",
"k",
":",
"self",
".",
"__dict__",
"[",
"k",
"]",
".",
"copy",
"(",
")",
"for",
"k",
"in",
"self",
".",
"containers",
"}",
"attrs",
".",
"update",
"(",
"{",
"k",
":",
"cp",
".",
"deepcopy",
"(",
"self",
".",
"__dict__",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"self",
".",
"shared",
"}",
")",
"return",
"self",
".",
"__class__",
"(",
"*",
"*",
"attrs",
")"
] | Returns a copy of the object. | [
"Returns",
"a",
"copy",
"of",
"the",
"object",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/smc_samplers.py#L245-L249 | train | 232,805 |
nchopin/particles | particles/smc_samplers.py | ThetaParticles.copyto | def copyto(self, src, where=None):
"""Emulates function `copyto` in NumPy.
Parameters
----------
where: (N,) bool ndarray
True if particle n in src must be copied.
src: (N,) `ThetaParticles` object
source
for each n such that where[n] is True, copy particle n in src
into self (at location n)
"""
for k in self.containers:
v = self.__dict__[k]
if isinstance(v, np.ndarray):
np.copyto(v, src.__dict__[k], where=where)
else:
v.copyto(src.__dict__[k], where=where) | python | def copyto(self, src, where=None):
"""Emulates function `copyto` in NumPy.
Parameters
----------
where: (N,) bool ndarray
True if particle n in src must be copied.
src: (N,) `ThetaParticles` object
source
for each n such that where[n] is True, copy particle n in src
into self (at location n)
"""
for k in self.containers:
v = self.__dict__[k]
if isinstance(v, np.ndarray):
np.copyto(v, src.__dict__[k], where=where)
else:
v.copyto(src.__dict__[k], where=where) | [
"def",
"copyto",
"(",
"self",
",",
"src",
",",
"where",
"=",
"None",
")",
":",
"for",
"k",
"in",
"self",
".",
"containers",
":",
"v",
"=",
"self",
".",
"__dict__",
"[",
"k",
"]",
"if",
"isinstance",
"(",
"v",
",",
"np",
".",
"ndarray",
")",
":",
"np",
".",
"copyto",
"(",
"v",
",",
"src",
".",
"__dict__",
"[",
"k",
"]",
",",
"where",
"=",
"where",
")",
"else",
":",
"v",
".",
"copyto",
"(",
"src",
".",
"__dict__",
"[",
"k",
"]",
",",
"where",
"=",
"where",
")"
] | Emulates function `copyto` in NumPy.
Parameters
----------
where: (N,) bool ndarray
True if particle n in src must be copied.
src: (N,) `ThetaParticles` object
source
for each n such that where[n] is True, copy particle n in src
into self (at location n) | [
"Emulates",
"function",
"copyto",
"in",
"NumPy",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/smc_samplers.py#L251-L270 | train | 232,806 |
nchopin/particles | particles/smc_samplers.py | ThetaParticles.copyto_at | def copyto_at(self, n, src, m):
"""Copy to at a given location.
Parameters
----------
n: int
index where to copy
src: `ThetaParticles` object
source
m: int
index of the element to be copied
Note
----
Basically, does self[n] <- src[m]
"""
for k in self.containers:
self.__dict__[k][n] = src.__dict__[k][m] | python | def copyto_at(self, n, src, m):
"""Copy to at a given location.
Parameters
----------
n: int
index where to copy
src: `ThetaParticles` object
source
m: int
index of the element to be copied
Note
----
Basically, does self[n] <- src[m]
"""
for k in self.containers:
self.__dict__[k][n] = src.__dict__[k][m] | [
"def",
"copyto_at",
"(",
"self",
",",
"n",
",",
"src",
",",
"m",
")",
":",
"for",
"k",
"in",
"self",
".",
"containers",
":",
"self",
".",
"__dict__",
"[",
"k",
"]",
"[",
"n",
"]",
"=",
"src",
".",
"__dict__",
"[",
"k",
"]",
"[",
"m",
"]"
] | Copy to at a given location.
Parameters
----------
n: int
index where to copy
src: `ThetaParticles` object
source
m: int
index of the element to be copied
Note
----
Basically, does self[n] <- src[m] | [
"Copy",
"to",
"at",
"a",
"given",
"location",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/smc_samplers.py#L272-L289 | train | 232,807 |
nchopin/particles | particles/smc_samplers.py | MetroParticles.Metropolis | def Metropolis(self, compute_target, mh_options):
"""Performs a certain number of Metropolis steps.
Parameters
----------
compute_target: function
computes the target density for the proposed values
mh_options: dict
+ 'type_prop': {'random_walk', 'independent'}
type of proposal: either Gaussian random walk, or independent Gaussian
+ 'adaptive': bool
If True, the covariance matrix of the random walk proposal is
set to a `rw_scale` times the weighted cov matrix of the particle
sample (ignored if proposal is independent)
+ 'rw_scale': float (default=None)
see above (ignored if proposal is independent)
+ 'indep_scale': float (default=1.1)
for an independent proposal, the proposal distribution is
Gaussian with mean set to the particle mean, cov set to
`indep_scale` times particle covariance
+ 'nsteps': int (default: 0)
number of steps; if 0, the number of steps is chosen adaptively
as follows: we stop when the average distance between the
starting points and the stopping points increase less than a
certain fraction
+ 'delta_dist': float (default: 0.1)
threshold for when nsteps = 0
"""
opts = mh_options.copy()
nsteps = opts.pop('nsteps', 0)
delta_dist = opts.pop('delta_dist', 0.1)
proposal = self.choose_proposal(**opts)
xout = self.copy()
xp = self.__class__(theta=np.empty_like(self.theta))
step_ars = []
for _ in self.mcmc_iterate(nsteps, self.arr, xout.arr, delta_dist):
xp.arr[:, :], delta_lp = proposal.step(xout.arr)
compute_target(xp)
lp_acc = xp.lpost - xout.lpost + delta_lp
accept = (np.log(stats.uniform.rvs(size=self.N)) < lp_acc)
xout.copyto(xp, where=accept)
step_ars.append(np.mean(accept))
xout.acc_rates = self.acc_rates + [step_ars]
return xout | python | def Metropolis(self, compute_target, mh_options):
"""Performs a certain number of Metropolis steps.
Parameters
----------
compute_target: function
computes the target density for the proposed values
mh_options: dict
+ 'type_prop': {'random_walk', 'independent'}
type of proposal: either Gaussian random walk, or independent Gaussian
+ 'adaptive': bool
If True, the covariance matrix of the random walk proposal is
set to a `rw_scale` times the weighted cov matrix of the particle
sample (ignored if proposal is independent)
+ 'rw_scale': float (default=None)
see above (ignored if proposal is independent)
+ 'indep_scale': float (default=1.1)
for an independent proposal, the proposal distribution is
Gaussian with mean set to the particle mean, cov set to
`indep_scale` times particle covariance
+ 'nsteps': int (default: 0)
number of steps; if 0, the number of steps is chosen adaptively
as follows: we stop when the average distance between the
starting points and the stopping points increase less than a
certain fraction
+ 'delta_dist': float (default: 0.1)
threshold for when nsteps = 0
"""
opts = mh_options.copy()
nsteps = opts.pop('nsteps', 0)
delta_dist = opts.pop('delta_dist', 0.1)
proposal = self.choose_proposal(**opts)
xout = self.copy()
xp = self.__class__(theta=np.empty_like(self.theta))
step_ars = []
for _ in self.mcmc_iterate(nsteps, self.arr, xout.arr, delta_dist):
xp.arr[:, :], delta_lp = proposal.step(xout.arr)
compute_target(xp)
lp_acc = xp.lpost - xout.lpost + delta_lp
accept = (np.log(stats.uniform.rvs(size=self.N)) < lp_acc)
xout.copyto(xp, where=accept)
step_ars.append(np.mean(accept))
xout.acc_rates = self.acc_rates + [step_ars]
return xout | [
"def",
"Metropolis",
"(",
"self",
",",
"compute_target",
",",
"mh_options",
")",
":",
"opts",
"=",
"mh_options",
".",
"copy",
"(",
")",
"nsteps",
"=",
"opts",
".",
"pop",
"(",
"'nsteps'",
",",
"0",
")",
"delta_dist",
"=",
"opts",
".",
"pop",
"(",
"'delta_dist'",
",",
"0.1",
")",
"proposal",
"=",
"self",
".",
"choose_proposal",
"(",
"*",
"*",
"opts",
")",
"xout",
"=",
"self",
".",
"copy",
"(",
")",
"xp",
"=",
"self",
".",
"__class__",
"(",
"theta",
"=",
"np",
".",
"empty_like",
"(",
"self",
".",
"theta",
")",
")",
"step_ars",
"=",
"[",
"]",
"for",
"_",
"in",
"self",
".",
"mcmc_iterate",
"(",
"nsteps",
",",
"self",
".",
"arr",
",",
"xout",
".",
"arr",
",",
"delta_dist",
")",
":",
"xp",
".",
"arr",
"[",
":",
",",
":",
"]",
",",
"delta_lp",
"=",
"proposal",
".",
"step",
"(",
"xout",
".",
"arr",
")",
"compute_target",
"(",
"xp",
")",
"lp_acc",
"=",
"xp",
".",
"lpost",
"-",
"xout",
".",
"lpost",
"+",
"delta_lp",
"accept",
"=",
"(",
"np",
".",
"log",
"(",
"stats",
".",
"uniform",
".",
"rvs",
"(",
"size",
"=",
"self",
".",
"N",
")",
")",
"<",
"lp_acc",
")",
"xout",
".",
"copyto",
"(",
"xp",
",",
"where",
"=",
"accept",
")",
"step_ars",
".",
"append",
"(",
"np",
".",
"mean",
"(",
"accept",
")",
")",
"xout",
".",
"acc_rates",
"=",
"self",
".",
"acc_rates",
"+",
"[",
"step_ars",
"]",
"return",
"xout"
] | Performs a certain number of Metropolis steps.
Parameters
----------
compute_target: function
computes the target density for the proposed values
mh_options: dict
+ 'type_prop': {'random_walk', 'independent'}
type of proposal: either Gaussian random walk, or independent Gaussian
+ 'adaptive': bool
If True, the covariance matrix of the random walk proposal is
set to a `rw_scale` times the weighted cov matrix of the particle
sample (ignored if proposal is independent)
+ 'rw_scale': float (default=None)
see above (ignored if proposal is independent)
+ 'indep_scale': float (default=1.1)
for an independent proposal, the proposal distribution is
Gaussian with mean set to the particle mean, cov set to
`indep_scale` times particle covariance
+ 'nsteps': int (default: 0)
number of steps; if 0, the number of steps is chosen adaptively
as follows: we stop when the average distance between the
starting points and the stopping points increase less than a
certain fraction
+ 'delta_dist': float (default: 0.1)
threshold for when nsteps = 0 | [
"Performs",
"a",
"certain",
"number",
"of",
"Metropolis",
"steps",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/smc_samplers.py#L375-L418 | train | 232,808 |
nchopin/particles | particles/hmm.py | BaumWelch.backward | def backward(self):
"""Backward recursion.
Upon completion, the following list of length T is available:
* smth: marginal smoothing probabilities
Note
----
Performs the forward step in case it has not been performed before.
"""
if not self.filt:
self.forward()
self.smth = [self.filt[-1]]
log_trans = np.log(self.hmm.trans_mat)
ctg = np.zeros(self.hmm.dim) # cost to go (log-lik of y_{t+1:T} given x_t=k)
for filt, next_ft in reversed(list(zip(self.filt[:-1],
self.logft[1:]))):
new_ctg = np.empty(self.hmm.dim)
for k in range(self.hmm.dim):
new_ctg[k] = rs.log_sum_exp(log_trans[k, :] + next_ft + ctg)
ctg = new_ctg
smth = rs.exp_and_normalise(np.log(filt) + ctg)
self.smth.append(smth)
self.smth.reverse() | python | def backward(self):
"""Backward recursion.
Upon completion, the following list of length T is available:
* smth: marginal smoothing probabilities
Note
----
Performs the forward step in case it has not been performed before.
"""
if not self.filt:
self.forward()
self.smth = [self.filt[-1]]
log_trans = np.log(self.hmm.trans_mat)
ctg = np.zeros(self.hmm.dim) # cost to go (log-lik of y_{t+1:T} given x_t=k)
for filt, next_ft in reversed(list(zip(self.filt[:-1],
self.logft[1:]))):
new_ctg = np.empty(self.hmm.dim)
for k in range(self.hmm.dim):
new_ctg[k] = rs.log_sum_exp(log_trans[k, :] + next_ft + ctg)
ctg = new_ctg
smth = rs.exp_and_normalise(np.log(filt) + ctg)
self.smth.append(smth)
self.smth.reverse() | [
"def",
"backward",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"filt",
":",
"self",
".",
"forward",
"(",
")",
"self",
".",
"smth",
"=",
"[",
"self",
".",
"filt",
"[",
"-",
"1",
"]",
"]",
"log_trans",
"=",
"np",
".",
"log",
"(",
"self",
".",
"hmm",
".",
"trans_mat",
")",
"ctg",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"hmm",
".",
"dim",
")",
"# cost to go (log-lik of y_{t+1:T} given x_t=k)",
"for",
"filt",
",",
"next_ft",
"in",
"reversed",
"(",
"list",
"(",
"zip",
"(",
"self",
".",
"filt",
"[",
":",
"-",
"1",
"]",
",",
"self",
".",
"logft",
"[",
"1",
":",
"]",
")",
")",
")",
":",
"new_ctg",
"=",
"np",
".",
"empty",
"(",
"self",
".",
"hmm",
".",
"dim",
")",
"for",
"k",
"in",
"range",
"(",
"self",
".",
"hmm",
".",
"dim",
")",
":",
"new_ctg",
"[",
"k",
"]",
"=",
"rs",
".",
"log_sum_exp",
"(",
"log_trans",
"[",
"k",
",",
":",
"]",
"+",
"next_ft",
"+",
"ctg",
")",
"ctg",
"=",
"new_ctg",
"smth",
"=",
"rs",
".",
"exp_and_normalise",
"(",
"np",
".",
"log",
"(",
"filt",
")",
"+",
"ctg",
")",
"self",
".",
"smth",
".",
"append",
"(",
"smth",
")",
"self",
".",
"smth",
".",
"reverse",
"(",
")"
] | Backward recursion.
Upon completion, the following list of length T is available:
* smth: marginal smoothing probabilities
Note
----
Performs the forward step in case it has not been performed before. | [
"Backward",
"recursion",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/hmm.py#L215-L238 | train | 232,809 |
nchopin/particles | particles/kalman.py | predict_step | def predict_step(F, covX, filt):
"""Predictive step of Kalman filter.
Parameters
----------
F: (dx, dx) numpy array
Mean of X_t | X_{t-1} is F * X_{t-1}
covX: (dx, dx) numpy array
covariance of X_t | X_{t-1}
filt: MeanAndCov object
filtering distribution at time t-1
Returns
-------
pred: MeanAndCov object
predictive distribution at time t
Note
----
filt.mean may either be of shape (dx,) or (N, dx); in the latter case
N predictive steps are performed in parallel.
"""
pred_mean = np.matmul(filt.mean, F.T)
pred_cov = dotdot(F, filt.cov, F.T) + covX
return MeanAndCov(mean=pred_mean, cov=pred_cov) | python | def predict_step(F, covX, filt):
"""Predictive step of Kalman filter.
Parameters
----------
F: (dx, dx) numpy array
Mean of X_t | X_{t-1} is F * X_{t-1}
covX: (dx, dx) numpy array
covariance of X_t | X_{t-1}
filt: MeanAndCov object
filtering distribution at time t-1
Returns
-------
pred: MeanAndCov object
predictive distribution at time t
Note
----
filt.mean may either be of shape (dx,) or (N, dx); in the latter case
N predictive steps are performed in parallel.
"""
pred_mean = np.matmul(filt.mean, F.T)
pred_cov = dotdot(F, filt.cov, F.T) + covX
return MeanAndCov(mean=pred_mean, cov=pred_cov) | [
"def",
"predict_step",
"(",
"F",
",",
"covX",
",",
"filt",
")",
":",
"pred_mean",
"=",
"np",
".",
"matmul",
"(",
"filt",
".",
"mean",
",",
"F",
".",
"T",
")",
"pred_cov",
"=",
"dotdot",
"(",
"F",
",",
"filt",
".",
"cov",
",",
"F",
".",
"T",
")",
"+",
"covX",
"return",
"MeanAndCov",
"(",
"mean",
"=",
"pred_mean",
",",
"cov",
"=",
"pred_cov",
")"
] | Predictive step of Kalman filter.
Parameters
----------
F: (dx, dx) numpy array
Mean of X_t | X_{t-1} is F * X_{t-1}
covX: (dx, dx) numpy array
covariance of X_t | X_{t-1}
filt: MeanAndCov object
filtering distribution at time t-1
Returns
-------
pred: MeanAndCov object
predictive distribution at time t
Note
----
filt.mean may either be of shape (dx,) or (N, dx); in the latter case
N predictive steps are performed in parallel. | [
"Predictive",
"step",
"of",
"Kalman",
"filter",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/kalman.py#L163-L187 | train | 232,810 |
nchopin/particles | particles/kalman.py | filter_step | def filter_step(G, covY, pred, yt):
"""Filtering step of Kalman filter.
Parameters
----------
G: (dy, dx) numpy array
mean of Y_t | X_t is G * X_t
covX: (dx, dx) numpy array
covariance of Y_t | X_t
pred: MeanAndCov object
predictive distribution at time t
Returns
-------
pred: MeanAndCov object
filtering distribution at time t
logpyt: float
log density of Y_t | Y_{0:t-1}
"""
# data prediction
data_pred_mean = np.matmul(pred.mean, G.T)
data_pred_cov = dotdot(G, pred.cov, G.T) + covY
if covY.shape[0] == 1:
logpyt = dists.Normal(loc=data_pred_mean,
scale=np.sqrt(data_pred_cov)).logpdf(yt)
else:
logpyt = dists.MvNormal(loc=data_pred_mean,
cov=data_pred_cov).logpdf(yt)
# filter
residual = yt - data_pred_mean
gain = dotdot(pred.cov, G.T, inv(data_pred_cov))
filt_mean = pred.mean + np.matmul(residual, gain.T)
filt_cov = pred.cov - dotdot(gain, G, pred.cov)
return MeanAndCov(mean=filt_mean, cov=filt_cov), logpyt | python | def filter_step(G, covY, pred, yt):
"""Filtering step of Kalman filter.
Parameters
----------
G: (dy, dx) numpy array
mean of Y_t | X_t is G * X_t
covX: (dx, dx) numpy array
covariance of Y_t | X_t
pred: MeanAndCov object
predictive distribution at time t
Returns
-------
pred: MeanAndCov object
filtering distribution at time t
logpyt: float
log density of Y_t | Y_{0:t-1}
"""
# data prediction
data_pred_mean = np.matmul(pred.mean, G.T)
data_pred_cov = dotdot(G, pred.cov, G.T) + covY
if covY.shape[0] == 1:
logpyt = dists.Normal(loc=data_pred_mean,
scale=np.sqrt(data_pred_cov)).logpdf(yt)
else:
logpyt = dists.MvNormal(loc=data_pred_mean,
cov=data_pred_cov).logpdf(yt)
# filter
residual = yt - data_pred_mean
gain = dotdot(pred.cov, G.T, inv(data_pred_cov))
filt_mean = pred.mean + np.matmul(residual, gain.T)
filt_cov = pred.cov - dotdot(gain, G, pred.cov)
return MeanAndCov(mean=filt_mean, cov=filt_cov), logpyt | [
"def",
"filter_step",
"(",
"G",
",",
"covY",
",",
"pred",
",",
"yt",
")",
":",
"# data prediction",
"data_pred_mean",
"=",
"np",
".",
"matmul",
"(",
"pred",
".",
"mean",
",",
"G",
".",
"T",
")",
"data_pred_cov",
"=",
"dotdot",
"(",
"G",
",",
"pred",
".",
"cov",
",",
"G",
".",
"T",
")",
"+",
"covY",
"if",
"covY",
".",
"shape",
"[",
"0",
"]",
"==",
"1",
":",
"logpyt",
"=",
"dists",
".",
"Normal",
"(",
"loc",
"=",
"data_pred_mean",
",",
"scale",
"=",
"np",
".",
"sqrt",
"(",
"data_pred_cov",
")",
")",
".",
"logpdf",
"(",
"yt",
")",
"else",
":",
"logpyt",
"=",
"dists",
".",
"MvNormal",
"(",
"loc",
"=",
"data_pred_mean",
",",
"cov",
"=",
"data_pred_cov",
")",
".",
"logpdf",
"(",
"yt",
")",
"# filter",
"residual",
"=",
"yt",
"-",
"data_pred_mean",
"gain",
"=",
"dotdot",
"(",
"pred",
".",
"cov",
",",
"G",
".",
"T",
",",
"inv",
"(",
"data_pred_cov",
")",
")",
"filt_mean",
"=",
"pred",
".",
"mean",
"+",
"np",
".",
"matmul",
"(",
"residual",
",",
"gain",
".",
"T",
")",
"filt_cov",
"=",
"pred",
".",
"cov",
"-",
"dotdot",
"(",
"gain",
",",
"G",
",",
"pred",
".",
"cov",
")",
"return",
"MeanAndCov",
"(",
"mean",
"=",
"filt_mean",
",",
"cov",
"=",
"filt_cov",
")",
",",
"logpyt"
] | Filtering step of Kalman filter.
Parameters
----------
G: (dy, dx) numpy array
mean of Y_t | X_t is G * X_t
covX: (dx, dx) numpy array
covariance of Y_t | X_t
pred: MeanAndCov object
predictive distribution at time t
Returns
-------
pred: MeanAndCov object
filtering distribution at time t
logpyt: float
log density of Y_t | Y_{0:t-1} | [
"Filtering",
"step",
"of",
"Kalman",
"filter",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/kalman.py#L190-L223 | train | 232,811 |
nchopin/particles | particles/kalman.py | MVLinearGauss.check_shapes | def check_shapes(self):
"""
Check all dimensions are correct.
"""
assert self.covX.shape == (self.dx, self.dx), error_msg
assert self.covY.shape == (self.dy, self.dy), error_msg
assert self.F.shape == (self.dx, self.dx), error_msg
assert self.G.shape == (self.dy, self.dx), error_msg
assert self.mu0.shape == (self.dx,), error_msg
assert self.cov0.shape == (self.dx, self.dx), error_msg | python | def check_shapes(self):
"""
Check all dimensions are correct.
"""
assert self.covX.shape == (self.dx, self.dx), error_msg
assert self.covY.shape == (self.dy, self.dy), error_msg
assert self.F.shape == (self.dx, self.dx), error_msg
assert self.G.shape == (self.dy, self.dx), error_msg
assert self.mu0.shape == (self.dx,), error_msg
assert self.cov0.shape == (self.dx, self.dx), error_msg | [
"def",
"check_shapes",
"(",
"self",
")",
":",
"assert",
"self",
".",
"covX",
".",
"shape",
"==",
"(",
"self",
".",
"dx",
",",
"self",
".",
"dx",
")",
",",
"error_msg",
"assert",
"self",
".",
"covY",
".",
"shape",
"==",
"(",
"self",
".",
"dy",
",",
"self",
".",
"dy",
")",
",",
"error_msg",
"assert",
"self",
".",
"F",
".",
"shape",
"==",
"(",
"self",
".",
"dx",
",",
"self",
".",
"dx",
")",
",",
"error_msg",
"assert",
"self",
".",
"G",
".",
"shape",
"==",
"(",
"self",
".",
"dy",
",",
"self",
".",
"dx",
")",
",",
"error_msg",
"assert",
"self",
".",
"mu0",
".",
"shape",
"==",
"(",
"self",
".",
"dx",
",",
")",
",",
"error_msg",
"assert",
"self",
".",
"cov0",
".",
"shape",
"==",
"(",
"self",
".",
"dx",
",",
"self",
".",
"dx",
")",
",",
"error_msg"
] | Check all dimensions are correct. | [
"Check",
"all",
"dimensions",
"are",
"correct",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/kalman.py#L326-L335 | train | 232,812 |
nchopin/particles | particles/qmc.py | sobol | def sobol(N, dim, scrambled=1):
""" Sobol sequence.
Parameters
----------
N : int
length of sequence
dim: int
dimension
scrambled: int
which scrambling method to use:
+ 0: no scrambling
+ 1: Owen's scrambling
+ 2: Faure-Tezuka
+ 3: Owen + Faure-Tezuka
Returns
-------
(N, dim) numpy array.
Notes
-----
For scrambling, seed is set randomly.
Fun fact: this venerable but playful piece of Fortran code occasionally
returns numbers above 1. (i.e. for a very small number of seeds); when this
happen we just start over (since the seed is randomly generated).
"""
while(True):
seed = np.random.randint(2**32)
out = lowdiscrepancy.sobol(N, dim, scrambled, seed, 1, 0)
if (scrambled == 0) or ((out < 1.).all() and (out > 0.).all()):
# no need to test if scrambled==0
return out | python | def sobol(N, dim, scrambled=1):
""" Sobol sequence.
Parameters
----------
N : int
length of sequence
dim: int
dimension
scrambled: int
which scrambling method to use:
+ 0: no scrambling
+ 1: Owen's scrambling
+ 2: Faure-Tezuka
+ 3: Owen + Faure-Tezuka
Returns
-------
(N, dim) numpy array.
Notes
-----
For scrambling, seed is set randomly.
Fun fact: this venerable but playful piece of Fortran code occasionally
returns numbers above 1. (i.e. for a very small number of seeds); when this
happen we just start over (since the seed is randomly generated).
"""
while(True):
seed = np.random.randint(2**32)
out = lowdiscrepancy.sobol(N, dim, scrambled, seed, 1, 0)
if (scrambled == 0) or ((out < 1.).all() and (out > 0.).all()):
# no need to test if scrambled==0
return out | [
"def",
"sobol",
"(",
"N",
",",
"dim",
",",
"scrambled",
"=",
"1",
")",
":",
"while",
"(",
"True",
")",
":",
"seed",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"2",
"**",
"32",
")",
"out",
"=",
"lowdiscrepancy",
".",
"sobol",
"(",
"N",
",",
"dim",
",",
"scrambled",
",",
"seed",
",",
"1",
",",
"0",
")",
"if",
"(",
"scrambled",
"==",
"0",
")",
"or",
"(",
"(",
"out",
"<",
"1.",
")",
".",
"all",
"(",
")",
"and",
"(",
"out",
">",
"0.",
")",
".",
"all",
"(",
")",
")",
":",
"# no need to test if scrambled==0",
"return",
"out"
] | Sobol sequence.
Parameters
----------
N : int
length of sequence
dim: int
dimension
scrambled: int
which scrambling method to use:
+ 0: no scrambling
+ 1: Owen's scrambling
+ 2: Faure-Tezuka
+ 3: Owen + Faure-Tezuka
Returns
-------
(N, dim) numpy array.
Notes
-----
For scrambling, seed is set randomly.
Fun fact: this venerable but playful piece of Fortran code occasionally
returns numbers above 1. (i.e. for a very small number of seeds); when this
happen we just start over (since the seed is randomly generated). | [
"Sobol",
"sequence",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/qmc.py#L29-L64 | train | 232,813 |
nchopin/particles | particles/smoothing.py | smoothing_worker | def smoothing_worker(method=None, N=100, seed=None, fk=None, fk_info=None,
add_func=None, log_gamma=None):
"""Generic worker for off-line smoothing algorithms.
This worker may be used in conjunction with utils.multiplexer in order to
run in parallel (and eventually compare) off-line smoothing algorithms.
Parameters
----------
method: string
['FFBS_ON', 'FFBS_ON2', 'FFBS_QMC',
'two-filter_ON', 'two-filter_ON_prop', 'two-filter_ON2']
N: int
number of particles
seed: int
random generator seed; if None, generator is not seeded
fk: Feynman-Kac object
The Feynman-Kac model for the forward filter
fk_info: Feynman-Kac object (default=None)
the Feynman-Kac model for the information filter; if None,
set to the same Feynman-Kac model as fk, with data in reverse
add_func: function, with signature (t, x, xf)
additive function, at time t, for particles x=x_t and xf=x_{t+1}
log_gamma: function
log of function gamma (see book)
Returns
-------
a dict with fields:
est: a ndarray of length T
cpu_time
"""
T = fk.T
if fk_info is None:
fk_info = fk.__class__(ssm=fk.ssm, data=fk.data[::-1])
if seed:
random.seed(seed)
est = np.zeros(T - 1)
if method=='FFBS_QMC':
pf = particles.SQMC(fk=fk, N=N, store_history=True)
else:
pf = particles.SMC(fk=fk, N=N, store_history=True)
tic = time.clock()
pf.run()
if method in ['FFBS_ON', 'FFBS_ON2', 'FFBS_QMC']:
if method.startswith('FFBS_ON'):
z = pf.hist.backward_sampling(N, linear_cost=(method == 'FFBS_ON'))
else:
z = pf.hist.backward_sampling_qmc(N)
for t in range(T - 1):
est[t] = np.mean(add_func(t, z[t], z[t + 1]))
elif method in ['two-filter_ON2', 'two-filter_ON', 'two-filter_ON_prop']:
infopf = particles.SMC(fk=fk_info, N=N, store_history=True)
infopf.run()
for t in range(T - 1):
psi = lambda x, xf: add_func(t, x, xf)
if method == 'two-filter_ON2':
est[t] = pf.hist.twofilter_smoothing(t, infopf, psi, log_gamma)
else:
ti = T - 2 - t # t+1 for info filter
if method == 'two-filter_ON_prop':
modif_fwd = stats.norm.logpdf(pf.hist.X[t],
loc=np.mean(infopf.hist.X[ti + 1]),
scale=np.std(infopf.hist.X[ti + 1]))
modif_info = stats.norm.logpdf(infopf.hist.X[ti],
loc=np.mean(pf.hist.X[t + 1]),
scale=np.std(pf.hist.X[t + 1]))
else:
modif_fwd, modif_info = None, None
est[t] = pf.hist.twofilter_smoothing(t, infopf, psi, log_gamma,
linear_cost=True,
modif_forward=modif_fwd,
modif_info=modif_info)
else:
print('no such method?')
cpu_time = time.clock() - tic
print(method + ' took %.2f s for N=%i' % (cpu_time, N))
return {'est': est, 'cpu': cpu_time} | python | def smoothing_worker(method=None, N=100, seed=None, fk=None, fk_info=None,
add_func=None, log_gamma=None):
"""Generic worker for off-line smoothing algorithms.
This worker may be used in conjunction with utils.multiplexer in order to
run in parallel (and eventually compare) off-line smoothing algorithms.
Parameters
----------
method: string
['FFBS_ON', 'FFBS_ON2', 'FFBS_QMC',
'two-filter_ON', 'two-filter_ON_prop', 'two-filter_ON2']
N: int
number of particles
seed: int
random generator seed; if None, generator is not seeded
fk: Feynman-Kac object
The Feynman-Kac model for the forward filter
fk_info: Feynman-Kac object (default=None)
the Feynman-Kac model for the information filter; if None,
set to the same Feynman-Kac model as fk, with data in reverse
add_func: function, with signature (t, x, xf)
additive function, at time t, for particles x=x_t and xf=x_{t+1}
log_gamma: function
log of function gamma (see book)
Returns
-------
a dict with fields:
est: a ndarray of length T
cpu_time
"""
T = fk.T
if fk_info is None:
fk_info = fk.__class__(ssm=fk.ssm, data=fk.data[::-1])
if seed:
random.seed(seed)
est = np.zeros(T - 1)
if method=='FFBS_QMC':
pf = particles.SQMC(fk=fk, N=N, store_history=True)
else:
pf = particles.SMC(fk=fk, N=N, store_history=True)
tic = time.clock()
pf.run()
if method in ['FFBS_ON', 'FFBS_ON2', 'FFBS_QMC']:
if method.startswith('FFBS_ON'):
z = pf.hist.backward_sampling(N, linear_cost=(method == 'FFBS_ON'))
else:
z = pf.hist.backward_sampling_qmc(N)
for t in range(T - 1):
est[t] = np.mean(add_func(t, z[t], z[t + 1]))
elif method in ['two-filter_ON2', 'two-filter_ON', 'two-filter_ON_prop']:
infopf = particles.SMC(fk=fk_info, N=N, store_history=True)
infopf.run()
for t in range(T - 1):
psi = lambda x, xf: add_func(t, x, xf)
if method == 'two-filter_ON2':
est[t] = pf.hist.twofilter_smoothing(t, infopf, psi, log_gamma)
else:
ti = T - 2 - t # t+1 for info filter
if method == 'two-filter_ON_prop':
modif_fwd = stats.norm.logpdf(pf.hist.X[t],
loc=np.mean(infopf.hist.X[ti + 1]),
scale=np.std(infopf.hist.X[ti + 1]))
modif_info = stats.norm.logpdf(infopf.hist.X[ti],
loc=np.mean(pf.hist.X[t + 1]),
scale=np.std(pf.hist.X[t + 1]))
else:
modif_fwd, modif_info = None, None
est[t] = pf.hist.twofilter_smoothing(t, infopf, psi, log_gamma,
linear_cost=True,
modif_forward=modif_fwd,
modif_info=modif_info)
else:
print('no such method?')
cpu_time = time.clock() - tic
print(method + ' took %.2f s for N=%i' % (cpu_time, N))
return {'est': est, 'cpu': cpu_time} | [
"def",
"smoothing_worker",
"(",
"method",
"=",
"None",
",",
"N",
"=",
"100",
",",
"seed",
"=",
"None",
",",
"fk",
"=",
"None",
",",
"fk_info",
"=",
"None",
",",
"add_func",
"=",
"None",
",",
"log_gamma",
"=",
"None",
")",
":",
"T",
"=",
"fk",
".",
"T",
"if",
"fk_info",
"is",
"None",
":",
"fk_info",
"=",
"fk",
".",
"__class__",
"(",
"ssm",
"=",
"fk",
".",
"ssm",
",",
"data",
"=",
"fk",
".",
"data",
"[",
":",
":",
"-",
"1",
"]",
")",
"if",
"seed",
":",
"random",
".",
"seed",
"(",
"seed",
")",
"est",
"=",
"np",
".",
"zeros",
"(",
"T",
"-",
"1",
")",
"if",
"method",
"==",
"'FFBS_QMC'",
":",
"pf",
"=",
"particles",
".",
"SQMC",
"(",
"fk",
"=",
"fk",
",",
"N",
"=",
"N",
",",
"store_history",
"=",
"True",
")",
"else",
":",
"pf",
"=",
"particles",
".",
"SMC",
"(",
"fk",
"=",
"fk",
",",
"N",
"=",
"N",
",",
"store_history",
"=",
"True",
")",
"tic",
"=",
"time",
".",
"clock",
"(",
")",
"pf",
".",
"run",
"(",
")",
"if",
"method",
"in",
"[",
"'FFBS_ON'",
",",
"'FFBS_ON2'",
",",
"'FFBS_QMC'",
"]",
":",
"if",
"method",
".",
"startswith",
"(",
"'FFBS_ON'",
")",
":",
"z",
"=",
"pf",
".",
"hist",
".",
"backward_sampling",
"(",
"N",
",",
"linear_cost",
"=",
"(",
"method",
"==",
"'FFBS_ON'",
")",
")",
"else",
":",
"z",
"=",
"pf",
".",
"hist",
".",
"backward_sampling_qmc",
"(",
"N",
")",
"for",
"t",
"in",
"range",
"(",
"T",
"-",
"1",
")",
":",
"est",
"[",
"t",
"]",
"=",
"np",
".",
"mean",
"(",
"add_func",
"(",
"t",
",",
"z",
"[",
"t",
"]",
",",
"z",
"[",
"t",
"+",
"1",
"]",
")",
")",
"elif",
"method",
"in",
"[",
"'two-filter_ON2'",
",",
"'two-filter_ON'",
",",
"'two-filter_ON_prop'",
"]",
":",
"infopf",
"=",
"particles",
".",
"SMC",
"(",
"fk",
"=",
"fk_info",
",",
"N",
"=",
"N",
",",
"store_history",
"=",
"True",
")",
"infopf",
".",
"run",
"(",
")",
"for",
"t",
"in",
"range",
"(",
"T",
"-",
"1",
")",
":",
"psi",
"=",
"lambda",
"x",
",",
"xf",
":",
"add_func",
"(",
"t",
",",
"x",
",",
"xf",
")",
"if",
"method",
"==",
"'two-filter_ON2'",
":",
"est",
"[",
"t",
"]",
"=",
"pf",
".",
"hist",
".",
"twofilter_smoothing",
"(",
"t",
",",
"infopf",
",",
"psi",
",",
"log_gamma",
")",
"else",
":",
"ti",
"=",
"T",
"-",
"2",
"-",
"t",
"# t+1 for info filter",
"if",
"method",
"==",
"'two-filter_ON_prop'",
":",
"modif_fwd",
"=",
"stats",
".",
"norm",
".",
"logpdf",
"(",
"pf",
".",
"hist",
".",
"X",
"[",
"t",
"]",
",",
"loc",
"=",
"np",
".",
"mean",
"(",
"infopf",
".",
"hist",
".",
"X",
"[",
"ti",
"+",
"1",
"]",
")",
",",
"scale",
"=",
"np",
".",
"std",
"(",
"infopf",
".",
"hist",
".",
"X",
"[",
"ti",
"+",
"1",
"]",
")",
")",
"modif_info",
"=",
"stats",
".",
"norm",
".",
"logpdf",
"(",
"infopf",
".",
"hist",
".",
"X",
"[",
"ti",
"]",
",",
"loc",
"=",
"np",
".",
"mean",
"(",
"pf",
".",
"hist",
".",
"X",
"[",
"t",
"+",
"1",
"]",
")",
",",
"scale",
"=",
"np",
".",
"std",
"(",
"pf",
".",
"hist",
".",
"X",
"[",
"t",
"+",
"1",
"]",
")",
")",
"else",
":",
"modif_fwd",
",",
"modif_info",
"=",
"None",
",",
"None",
"est",
"[",
"t",
"]",
"=",
"pf",
".",
"hist",
".",
"twofilter_smoothing",
"(",
"t",
",",
"infopf",
",",
"psi",
",",
"log_gamma",
",",
"linear_cost",
"=",
"True",
",",
"modif_forward",
"=",
"modif_fwd",
",",
"modif_info",
"=",
"modif_info",
")",
"else",
":",
"print",
"(",
"'no such method?'",
")",
"cpu_time",
"=",
"time",
".",
"clock",
"(",
")",
"-",
"tic",
"print",
"(",
"method",
"+",
"' took %.2f s for N=%i'",
"%",
"(",
"cpu_time",
",",
"N",
")",
")",
"return",
"{",
"'est'",
":",
"est",
",",
"'cpu'",
":",
"cpu_time",
"}"
] | Generic worker for off-line smoothing algorithms.
This worker may be used in conjunction with utils.multiplexer in order to
run in parallel (and eventually compare) off-line smoothing algorithms.
Parameters
----------
method: string
['FFBS_ON', 'FFBS_ON2', 'FFBS_QMC',
'two-filter_ON', 'two-filter_ON_prop', 'two-filter_ON2']
N: int
number of particles
seed: int
random generator seed; if None, generator is not seeded
fk: Feynman-Kac object
The Feynman-Kac model for the forward filter
fk_info: Feynman-Kac object (default=None)
the Feynman-Kac model for the information filter; if None,
set to the same Feynman-Kac model as fk, with data in reverse
add_func: function, with signature (t, x, xf)
additive function, at time t, for particles x=x_t and xf=x_{t+1}
log_gamma: function
log of function gamma (see book)
Returns
-------
a dict with fields:
est: a ndarray of length T
cpu_time | [
"Generic",
"worker",
"for",
"off",
"-",
"line",
"smoothing",
"algorithms",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/smoothing.py#L367-L444 | train | 232,814 |
nchopin/particles | particles/smoothing.py | ParticleHistory.save | def save(self, X=None, w=None, A=None):
"""Save one "page" of history at a given time.
.. note::
This method is used internally by `SMC` to store the state of the
particle system at each time t. In most cases, users should not
have to call this method directly.
"""
self.X.append(X)
self.wgt.append(w)
self.A.append(A) | python | def save(self, X=None, w=None, A=None):
"""Save one "page" of history at a given time.
.. note::
This method is used internally by `SMC` to store the state of the
particle system at each time t. In most cases, users should not
have to call this method directly.
"""
self.X.append(X)
self.wgt.append(w)
self.A.append(A) | [
"def",
"save",
"(",
"self",
",",
"X",
"=",
"None",
",",
"w",
"=",
"None",
",",
"A",
"=",
"None",
")",
":",
"self",
".",
"X",
".",
"append",
"(",
"X",
")",
"self",
".",
"wgt",
".",
"append",
"(",
"w",
")",
"self",
".",
"A",
".",
"append",
"(",
"A",
")"
] | Save one "page" of history at a given time.
.. note::
This method is used internally by `SMC` to store the state of the
particle system at each time t. In most cases, users should not
have to call this method directly. | [
"Save",
"one",
"page",
"of",
"history",
"at",
"a",
"given",
"time",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/smoothing.py#L92-L102 | train | 232,815 |
nchopin/particles | particles/smoothing.py | ParticleHistory.extract_one_trajectory | def extract_one_trajectory(self):
"""Extract a single trajectory from the particle history.
The final state is chosen randomly, then the corresponding trajectory
is constructed backwards, until time t=0.
"""
traj = []
for t in reversed(range(self.T)):
if t == self.T - 1:
n = rs.multinomial_once(self.wgt[-1].W)
else:
n = self.A[t + 1][n]
traj.append(self.X[t][n])
return traj[::-1] | python | def extract_one_trajectory(self):
"""Extract a single trajectory from the particle history.
The final state is chosen randomly, then the corresponding trajectory
is constructed backwards, until time t=0.
"""
traj = []
for t in reversed(range(self.T)):
if t == self.T - 1:
n = rs.multinomial_once(self.wgt[-1].W)
else:
n = self.A[t + 1][n]
traj.append(self.X[t][n])
return traj[::-1] | [
"def",
"extract_one_trajectory",
"(",
"self",
")",
":",
"traj",
"=",
"[",
"]",
"for",
"t",
"in",
"reversed",
"(",
"range",
"(",
"self",
".",
"T",
")",
")",
":",
"if",
"t",
"==",
"self",
".",
"T",
"-",
"1",
":",
"n",
"=",
"rs",
".",
"multinomial_once",
"(",
"self",
".",
"wgt",
"[",
"-",
"1",
"]",
".",
"W",
")",
"else",
":",
"n",
"=",
"self",
".",
"A",
"[",
"t",
"+",
"1",
"]",
"[",
"n",
"]",
"traj",
".",
"append",
"(",
"self",
".",
"X",
"[",
"t",
"]",
"[",
"n",
"]",
")",
"return",
"traj",
"[",
":",
":",
"-",
"1",
"]"
] | Extract a single trajectory from the particle history.
The final state is chosen randomly, then the corresponding trajectory
is constructed backwards, until time t=0. | [
"Extract",
"a",
"single",
"trajectory",
"from",
"the",
"particle",
"history",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/smoothing.py#L104-L117 | train | 232,816 |
nchopin/particles | particles/smoothing.py | ParticleHistory.compute_trajectories | def compute_trajectories(self):
"""Compute the N trajectories that constitute the current genealogy.
Compute and add attribute ``B`` to ``self`` where ``B`` is an array
such that ``B[t,n]`` is the index of ancestor at time t of particle X_T^n,
where T is the current length of history.
"""
self.B = np.empty((self.T, self.N), 'int')
self.B[-1, :] = self.A[-1]
for t in reversed(range(self.T - 1)):
self.B[t, :] = self.A[t + 1][self.B[t + 1]] | python | def compute_trajectories(self):
"""Compute the N trajectories that constitute the current genealogy.
Compute and add attribute ``B`` to ``self`` where ``B`` is an array
such that ``B[t,n]`` is the index of ancestor at time t of particle X_T^n,
where T is the current length of history.
"""
self.B = np.empty((self.T, self.N), 'int')
self.B[-1, :] = self.A[-1]
for t in reversed(range(self.T - 1)):
self.B[t, :] = self.A[t + 1][self.B[t + 1]] | [
"def",
"compute_trajectories",
"(",
"self",
")",
":",
"self",
".",
"B",
"=",
"np",
".",
"empty",
"(",
"(",
"self",
".",
"T",
",",
"self",
".",
"N",
")",
",",
"'int'",
")",
"self",
".",
"B",
"[",
"-",
"1",
",",
":",
"]",
"=",
"self",
".",
"A",
"[",
"-",
"1",
"]",
"for",
"t",
"in",
"reversed",
"(",
"range",
"(",
"self",
".",
"T",
"-",
"1",
")",
")",
":",
"self",
".",
"B",
"[",
"t",
",",
":",
"]",
"=",
"self",
".",
"A",
"[",
"t",
"+",
"1",
"]",
"[",
"self",
".",
"B",
"[",
"t",
"+",
"1",
"]",
"]"
] | Compute the N trajectories that constitute the current genealogy.
Compute and add attribute ``B`` to ``self`` where ``B`` is an array
such that ``B[t,n]`` is the index of ancestor at time t of particle X_T^n,
where T is the current length of history. | [
"Compute",
"the",
"N",
"trajectories",
"that",
"constitute",
"the",
"current",
"genealogy",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/smoothing.py#L119-L129 | train | 232,817 |
nchopin/particles | particles/smoothing.py | ParticleHistory.twofilter_smoothing | def twofilter_smoothing(self, t, info, phi, loggamma, linear_cost=False,
return_ess=False, modif_forward=None,
modif_info=None):
"""Two-filter smoothing.
Parameters
----------
t: time, in range 0 <= t < T-1
info: SMC object
the information filter
phi: function
test function, a function of (X_t,X_{t+1})
loggamma: function
a function of (X_{t+1})
linear_cost: bool
if True, use the O(N) variant (basic version is O(N^2))
Returns
-------
Two-filter estimate of the smoothing expectation of phi(X_t,x_{t+1})
"""
ti = self.T - 2 - t # t+1 in reverse
if t < 0 or t >= self.T - 1:
raise ValueError(
'two-filter smoothing: t must be in range 0,...,T-2')
lwinfo = info.hist.wgt[ti].lw - loggamma(info.hist.X[ti])
if linear_cost:
return self._twofilter_smoothing_ON(t, ti, info, phi, lwinfo,
return_ess,
modif_forward, modif_info)
else:
return self._twofilter_smoothing_ON2(t, ti, info, phi, lwinfo) | python | def twofilter_smoothing(self, t, info, phi, loggamma, linear_cost=False,
return_ess=False, modif_forward=None,
modif_info=None):
"""Two-filter smoothing.
Parameters
----------
t: time, in range 0 <= t < T-1
info: SMC object
the information filter
phi: function
test function, a function of (X_t,X_{t+1})
loggamma: function
a function of (X_{t+1})
linear_cost: bool
if True, use the O(N) variant (basic version is O(N^2))
Returns
-------
Two-filter estimate of the smoothing expectation of phi(X_t,x_{t+1})
"""
ti = self.T - 2 - t # t+1 in reverse
if t < 0 or t >= self.T - 1:
raise ValueError(
'two-filter smoothing: t must be in range 0,...,T-2')
lwinfo = info.hist.wgt[ti].lw - loggamma(info.hist.X[ti])
if linear_cost:
return self._twofilter_smoothing_ON(t, ti, info, phi, lwinfo,
return_ess,
modif_forward, modif_info)
else:
return self._twofilter_smoothing_ON2(t, ti, info, phi, lwinfo) | [
"def",
"twofilter_smoothing",
"(",
"self",
",",
"t",
",",
"info",
",",
"phi",
",",
"loggamma",
",",
"linear_cost",
"=",
"False",
",",
"return_ess",
"=",
"False",
",",
"modif_forward",
"=",
"None",
",",
"modif_info",
"=",
"None",
")",
":",
"ti",
"=",
"self",
".",
"T",
"-",
"2",
"-",
"t",
"# t+1 in reverse",
"if",
"t",
"<",
"0",
"or",
"t",
">=",
"self",
".",
"T",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"'two-filter smoothing: t must be in range 0,...,T-2'",
")",
"lwinfo",
"=",
"info",
".",
"hist",
".",
"wgt",
"[",
"ti",
"]",
".",
"lw",
"-",
"loggamma",
"(",
"info",
".",
"hist",
".",
"X",
"[",
"ti",
"]",
")",
"if",
"linear_cost",
":",
"return",
"self",
".",
"_twofilter_smoothing_ON",
"(",
"t",
",",
"ti",
",",
"info",
",",
"phi",
",",
"lwinfo",
",",
"return_ess",
",",
"modif_forward",
",",
"modif_info",
")",
"else",
":",
"return",
"self",
".",
"_twofilter_smoothing_ON2",
"(",
"t",
",",
"ti",
",",
"info",
",",
"phi",
",",
"lwinfo",
")"
] | Two-filter smoothing.
Parameters
----------
t: time, in range 0 <= t < T-1
info: SMC object
the information filter
phi: function
test function, a function of (X_t,X_{t+1})
loggamma: function
a function of (X_{t+1})
linear_cost: bool
if True, use the O(N) variant (basic version is O(N^2))
Returns
-------
Two-filter estimate of the smoothing expectation of phi(X_t,x_{t+1}) | [
"Two",
"-",
"filter",
"smoothing",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/smoothing.py#L286-L317 | train | 232,818 |
nchopin/particles | particles/core.py | multiSMC | def multiSMC(nruns=10, nprocs=0, out_func=None, **args):
"""Run SMC algorithms in parallel, for different combinations of parameters.
`multiSMC` relies on the `multiplexer` utility, and obeys the same logic.
A basic usage is::
results = multiSMC(fk=my_fk_model, N=100, nruns=20, nprocs=0)
This runs the same SMC algorithm 20 times, using all available CPU cores.
The output, ``results``, is a list of 20 dictionaries; a given dict corresponds
to a single run, and contains the following (key, value) pairs:
+ ``'run'``: a run identifier (a number between 0 and nruns-1)
+ ``'output'``: the corresponding SMC object (once method run was completed)
Since a `SMC` object may take a lot of space in memory (especially when
the option ``store_history`` is set to True), it is possible to require
`multiSMC` to store only some chosen summary of the SMC runs, using option
`out_func`. For instance, if we only want to store the estimate
of the log-likelihood of the model obtained from each particle filter::
of = lambda pf: pf.logLt
results = multiSMC(fk=my_fk_model, N=100, nruns=20, out_func=of)
It is also possible to vary the parameters. Say::
results = multiSMC(fk=my_fk_model, N=[100, 500, 1000])
will run the same SMC algorithm 30 times: 10 times for N=100, 10 times for
N=500, and 10 times for N=1000. The number 10 comes from the fact that we
did not specify nruns, and its default value is 10. The 30 dictionaries
obtained in results will then contain an extra (key, value) pair that will
give the value of N for which the run was performed.
It is possible to vary several arguments. Each time a list must be
provided. The end result will amount to take a *cartesian product* of the
arguments::
results = multiSMC(fk=my_fk_model, N=[100, 1000], resampling=['multinomial',
'residual'], nruns=20)
In that case we run our algorithm 80 times: 20 times with N=100 and
resampling set to multinomial, 20 times with N=100 and resampling set to
residual and so on.
Parameters
----------
* nruns: int, optional
number of runs (default is 10)
* nprocs: int, optional
number of processors to use; if negative, number of cores not to use.
Default value is 1 (no multiprocessing)
* out_func: callable, optional
function to transform the output of each SMC run. (If not given, output
will be the complete SMC object).
* args: dict
arguments passed to SMC class
Returns
-------
A list of dicts
See also
--------
`utils.multiplexer`: for more details on the syntax.
"""
def f(**args):
pf = SMC(**args)
pf.run()
return out_func(pf)
if out_func is None:
out_func = lambda x: x
return utils.multiplexer(f=f, nruns=nruns, nprocs=nprocs, seeding=True,
**args) | python | def multiSMC(nruns=10, nprocs=0, out_func=None, **args):
"""Run SMC algorithms in parallel, for different combinations of parameters.
`multiSMC` relies on the `multiplexer` utility, and obeys the same logic.
A basic usage is::
results = multiSMC(fk=my_fk_model, N=100, nruns=20, nprocs=0)
This runs the same SMC algorithm 20 times, using all available CPU cores.
The output, ``results``, is a list of 20 dictionaries; a given dict corresponds
to a single run, and contains the following (key, value) pairs:
+ ``'run'``: a run identifier (a number between 0 and nruns-1)
+ ``'output'``: the corresponding SMC object (once method run was completed)
Since a `SMC` object may take a lot of space in memory (especially when
the option ``store_history`` is set to True), it is possible to require
`multiSMC` to store only some chosen summary of the SMC runs, using option
`out_func`. For instance, if we only want to store the estimate
of the log-likelihood of the model obtained from each particle filter::
of = lambda pf: pf.logLt
results = multiSMC(fk=my_fk_model, N=100, nruns=20, out_func=of)
It is also possible to vary the parameters. Say::
results = multiSMC(fk=my_fk_model, N=[100, 500, 1000])
will run the same SMC algorithm 30 times: 10 times for N=100, 10 times for
N=500, and 10 times for N=1000. The number 10 comes from the fact that we
did not specify nruns, and its default value is 10. The 30 dictionaries
obtained in results will then contain an extra (key, value) pair that will
give the value of N for which the run was performed.
It is possible to vary several arguments. Each time a list must be
provided. The end result will amount to take a *cartesian product* of the
arguments::
results = multiSMC(fk=my_fk_model, N=[100, 1000], resampling=['multinomial',
'residual'], nruns=20)
In that case we run our algorithm 80 times: 20 times with N=100 and
resampling set to multinomial, 20 times with N=100 and resampling set to
residual and so on.
Parameters
----------
* nruns: int, optional
number of runs (default is 10)
* nprocs: int, optional
number of processors to use; if negative, number of cores not to use.
Default value is 1 (no multiprocessing)
* out_func: callable, optional
function to transform the output of each SMC run. (If not given, output
will be the complete SMC object).
* args: dict
arguments passed to SMC class
Returns
-------
A list of dicts
See also
--------
`utils.multiplexer`: for more details on the syntax.
"""
def f(**args):
pf = SMC(**args)
pf.run()
return out_func(pf)
if out_func is None:
out_func = lambda x: x
return utils.multiplexer(f=f, nruns=nruns, nprocs=nprocs, seeding=True,
**args) | [
"def",
"multiSMC",
"(",
"nruns",
"=",
"10",
",",
"nprocs",
"=",
"0",
",",
"out_func",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"def",
"f",
"(",
"*",
"*",
"args",
")",
":",
"pf",
"=",
"SMC",
"(",
"*",
"*",
"args",
")",
"pf",
".",
"run",
"(",
")",
"return",
"out_func",
"(",
"pf",
")",
"if",
"out_func",
"is",
"None",
":",
"out_func",
"=",
"lambda",
"x",
":",
"x",
"return",
"utils",
".",
"multiplexer",
"(",
"f",
"=",
"f",
",",
"nruns",
"=",
"nruns",
",",
"nprocs",
"=",
"nprocs",
",",
"seeding",
"=",
"True",
",",
"*",
"*",
"args",
")"
] | Run SMC algorithms in parallel, for different combinations of parameters.
`multiSMC` relies on the `multiplexer` utility, and obeys the same logic.
A basic usage is::
results = multiSMC(fk=my_fk_model, N=100, nruns=20, nprocs=0)
This runs the same SMC algorithm 20 times, using all available CPU cores.
The output, ``results``, is a list of 20 dictionaries; a given dict corresponds
to a single run, and contains the following (key, value) pairs:
+ ``'run'``: a run identifier (a number between 0 and nruns-1)
+ ``'output'``: the corresponding SMC object (once method run was completed)
Since a `SMC` object may take a lot of space in memory (especially when
the option ``store_history`` is set to True), it is possible to require
`multiSMC` to store only some chosen summary of the SMC runs, using option
`out_func`. For instance, if we only want to store the estimate
of the log-likelihood of the model obtained from each particle filter::
of = lambda pf: pf.logLt
results = multiSMC(fk=my_fk_model, N=100, nruns=20, out_func=of)
It is also possible to vary the parameters. Say::
results = multiSMC(fk=my_fk_model, N=[100, 500, 1000])
will run the same SMC algorithm 30 times: 10 times for N=100, 10 times for
N=500, and 10 times for N=1000. The number 10 comes from the fact that we
did not specify nruns, and its default value is 10. The 30 dictionaries
obtained in results will then contain an extra (key, value) pair that will
give the value of N for which the run was performed.
It is possible to vary several arguments. Each time a list must be
provided. The end result will amount to take a *cartesian product* of the
arguments::
results = multiSMC(fk=my_fk_model, N=[100, 1000], resampling=['multinomial',
'residual'], nruns=20)
In that case we run our algorithm 80 times: 20 times with N=100 and
resampling set to multinomial, 20 times with N=100 and resampling set to
residual and so on.
Parameters
----------
* nruns: int, optional
number of runs (default is 10)
* nprocs: int, optional
number of processors to use; if negative, number of cores not to use.
Default value is 1 (no multiprocessing)
* out_func: callable, optional
function to transform the output of each SMC run. (If not given, output
will be the complete SMC object).
* args: dict
arguments passed to SMC class
Returns
-------
A list of dicts
See also
--------
`utils.multiplexer`: for more details on the syntax. | [
"Run",
"SMC",
"algorithms",
"in",
"parallel",
"for",
"different",
"combinations",
"of",
"parameters",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/core.py#L438-L512 | train | 232,819 |
nchopin/particles | particles/core.py | SMC.reset_weights | def reset_weights(self):
"""Reset weights after a resampling step.
"""
if self.fk.isAPF:
lw = (rs.log_mean_exp(self.logetat, W=self.W)
- self.logetat[self.A])
self.wgts = rs.Weights(lw=lw)
else:
self.wgts = rs.Weights() | python | def reset_weights(self):
"""Reset weights after a resampling step.
"""
if self.fk.isAPF:
lw = (rs.log_mean_exp(self.logetat, W=self.W)
- self.logetat[self.A])
self.wgts = rs.Weights(lw=lw)
else:
self.wgts = rs.Weights() | [
"def",
"reset_weights",
"(",
"self",
")",
":",
"if",
"self",
".",
"fk",
".",
"isAPF",
":",
"lw",
"=",
"(",
"rs",
".",
"log_mean_exp",
"(",
"self",
".",
"logetat",
",",
"W",
"=",
"self",
".",
"W",
")",
"-",
"self",
".",
"logetat",
"[",
"self",
".",
"A",
"]",
")",
"self",
".",
"wgts",
"=",
"rs",
".",
"Weights",
"(",
"lw",
"=",
"lw",
")",
"else",
":",
"self",
".",
"wgts",
"=",
"rs",
".",
"Weights",
"(",
")"
] | Reset weights after a resampling step. | [
"Reset",
"weights",
"after",
"a",
"resampling",
"step",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/core.py#L317-L325 | train | 232,820 |
nchopin/particles | particles/resampling.py | log_sum_exp | def log_sum_exp(v):
"""Log of the sum of the exp of the arguments.
Parameters
----------
v: ndarray
Returns
-------
l: float
l = log(sum(exp(v)))
Note
----
use the log_sum_exp trick to avoid overflow: i.e. we remove the max of v
before exponentiating, then we add it back
See also
--------
log_mean_exp
"""
m = v.max()
return m + np.log(np.sum(np.exp(v - m))) | python | def log_sum_exp(v):
"""Log of the sum of the exp of the arguments.
Parameters
----------
v: ndarray
Returns
-------
l: float
l = log(sum(exp(v)))
Note
----
use the log_sum_exp trick to avoid overflow: i.e. we remove the max of v
before exponentiating, then we add it back
See also
--------
log_mean_exp
"""
m = v.max()
return m + np.log(np.sum(np.exp(v - m))) | [
"def",
"log_sum_exp",
"(",
"v",
")",
":",
"m",
"=",
"v",
".",
"max",
"(",
")",
"return",
"m",
"+",
"np",
".",
"log",
"(",
"np",
".",
"sum",
"(",
"np",
".",
"exp",
"(",
"v",
"-",
"m",
")",
")",
")"
] | Log of the sum of the exp of the arguments.
Parameters
----------
v: ndarray
Returns
-------
l: float
l = log(sum(exp(v)))
Note
----
use the log_sum_exp trick to avoid overflow: i.e. we remove the max of v
before exponentiating, then we add it back
See also
--------
log_mean_exp | [
"Log",
"of",
"the",
"sum",
"of",
"the",
"exp",
"of",
"the",
"arguments",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/resampling.py#L233-L256 | train | 232,821 |
nchopin/particles | particles/resampling.py | log_sum_exp_ab | def log_sum_exp_ab(a, b):
"""log_sum_exp for two scalars.
Parameters
----------
a, b: float
Returns
-------
c: float
c = log(e^a + e^b)
"""
if a > b:
return a + np.log(1. + np.exp(b - a))
else:
return b + np.log(1. + np.exp(a - b)) | python | def log_sum_exp_ab(a, b):
"""log_sum_exp for two scalars.
Parameters
----------
a, b: float
Returns
-------
c: float
c = log(e^a + e^b)
"""
if a > b:
return a + np.log(1. + np.exp(b - a))
else:
return b + np.log(1. + np.exp(a - b)) | [
"def",
"log_sum_exp_ab",
"(",
"a",
",",
"b",
")",
":",
"if",
"a",
">",
"b",
":",
"return",
"a",
"+",
"np",
".",
"log",
"(",
"1.",
"+",
"np",
".",
"exp",
"(",
"b",
"-",
"a",
")",
")",
"else",
":",
"return",
"b",
"+",
"np",
".",
"log",
"(",
"1.",
"+",
"np",
".",
"exp",
"(",
"a",
"-",
"b",
")",
")"
] | log_sum_exp for two scalars.
Parameters
----------
a, b: float
Returns
-------
c: float
c = log(e^a + e^b) | [
"log_sum_exp",
"for",
"two",
"scalars",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/resampling.py#L259-L274 | train | 232,822 |
nchopin/particles | particles/resampling.py | wmean_and_var | def wmean_and_var(W, x):
"""Component-wise weighted mean and variance.
Parameters
----------
W: (N,) ndarray
normalised weights (must be >=0 and sum to one).
x: ndarray (such that shape[0]==N)
data
Returns
-------
dictionary
{'mean':weighted_means, 'var':weighted_variances}
"""
m = np.average(x, weights=W, axis=0)
m2 = np.average(x**2, weights=W, axis=0)
v = m2 - m**2
return {'mean': m, 'var': v} | python | def wmean_and_var(W, x):
"""Component-wise weighted mean and variance.
Parameters
----------
W: (N,) ndarray
normalised weights (must be >=0 and sum to one).
x: ndarray (such that shape[0]==N)
data
Returns
-------
dictionary
{'mean':weighted_means, 'var':weighted_variances}
"""
m = np.average(x, weights=W, axis=0)
m2 = np.average(x**2, weights=W, axis=0)
v = m2 - m**2
return {'mean': m, 'var': v} | [
"def",
"wmean_and_var",
"(",
"W",
",",
"x",
")",
":",
"m",
"=",
"np",
".",
"average",
"(",
"x",
",",
"weights",
"=",
"W",
",",
"axis",
"=",
"0",
")",
"m2",
"=",
"np",
".",
"average",
"(",
"x",
"**",
"2",
",",
"weights",
"=",
"W",
",",
"axis",
"=",
"0",
")",
"v",
"=",
"m2",
"-",
"m",
"**",
"2",
"return",
"{",
"'mean'",
":",
"m",
",",
"'var'",
":",
"v",
"}"
] | Component-wise weighted mean and variance.
Parameters
----------
W: (N,) ndarray
normalised weights (must be >=0 and sum to one).
x: ndarray (such that shape[0]==N)
data
Returns
-------
dictionary
{'mean':weighted_means, 'var':weighted_variances} | [
"Component",
"-",
"wise",
"weighted",
"mean",
"and",
"variance",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/resampling.py#L306-L324 | train | 232,823 |
nchopin/particles | particles/resampling.py | wmean_and_var_str_array | def wmean_and_var_str_array(W, x):
"""Weighted mean and variance of each component of a structured array.
Parameters
----------
W: (N,) ndarray
normalised weights (must be >=0 and sum to one).
x: (N,) structured array
data
Returns
-------
dictionary
{'mean':weighted_means, 'var':weighted_variances}
"""
m = np.empty(shape=x.shape[1:], dtype=x.dtype)
v = np.empty_like(m)
for p in x.dtype.names:
m[p], v[p] = wmean_and_var(W, x[p]).values()
return {'mean': m, 'var': v} | python | def wmean_and_var_str_array(W, x):
"""Weighted mean and variance of each component of a structured array.
Parameters
----------
W: (N,) ndarray
normalised weights (must be >=0 and sum to one).
x: (N,) structured array
data
Returns
-------
dictionary
{'mean':weighted_means, 'var':weighted_variances}
"""
m = np.empty(shape=x.shape[1:], dtype=x.dtype)
v = np.empty_like(m)
for p in x.dtype.names:
m[p], v[p] = wmean_and_var(W, x[p]).values()
return {'mean': m, 'var': v} | [
"def",
"wmean_and_var_str_array",
"(",
"W",
",",
"x",
")",
":",
"m",
"=",
"np",
".",
"empty",
"(",
"shape",
"=",
"x",
".",
"shape",
"[",
"1",
":",
"]",
",",
"dtype",
"=",
"x",
".",
"dtype",
")",
"v",
"=",
"np",
".",
"empty_like",
"(",
"m",
")",
"for",
"p",
"in",
"x",
".",
"dtype",
".",
"names",
":",
"m",
"[",
"p",
"]",
",",
"v",
"[",
"p",
"]",
"=",
"wmean_and_var",
"(",
"W",
",",
"x",
"[",
"p",
"]",
")",
".",
"values",
"(",
")",
"return",
"{",
"'mean'",
":",
"m",
",",
"'var'",
":",
"v",
"}"
] | Weighted mean and variance of each component of a structured array.
Parameters
----------
W: (N,) ndarray
normalised weights (must be >=0 and sum to one).
x: (N,) structured array
data
Returns
-------
dictionary
{'mean':weighted_means, 'var':weighted_variances} | [
"Weighted",
"mean",
"and",
"variance",
"of",
"each",
"component",
"of",
"a",
"structured",
"array",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/resampling.py#L326-L345 | train | 232,824 |
nchopin/particles | particles/resampling.py | wquantiles | def wquantiles(W, x, alphas=(0.25, 0.50, 0.75)):
"""Quantiles for weighted data.
Parameters
----------
W: (N,) ndarray
normalised weights (weights are >=0 and sum to one)
x: (N,) or (N,d) ndarray
data
alphas: list-like of size k (default: (0.25, 0.50, 0.75))
probabilities (between 0. and 1.)
Returns
-------
a (k,) or (d, k) ndarray containing the alpha-quantiles
"""
if len(x.shape) == 1:
return _wquantiles(W, x, alphas=alphas)
elif len(x.shape) == 2:
return np.array([_wquantiles(W, x[:, i], alphas=alphas)
for i in range(x.shape[1])]) | python | def wquantiles(W, x, alphas=(0.25, 0.50, 0.75)):
"""Quantiles for weighted data.
Parameters
----------
W: (N,) ndarray
normalised weights (weights are >=0 and sum to one)
x: (N,) or (N,d) ndarray
data
alphas: list-like of size k (default: (0.25, 0.50, 0.75))
probabilities (between 0. and 1.)
Returns
-------
a (k,) or (d, k) ndarray containing the alpha-quantiles
"""
if len(x.shape) == 1:
return _wquantiles(W, x, alphas=alphas)
elif len(x.shape) == 2:
return np.array([_wquantiles(W, x[:, i], alphas=alphas)
for i in range(x.shape[1])]) | [
"def",
"wquantiles",
"(",
"W",
",",
"x",
",",
"alphas",
"=",
"(",
"0.25",
",",
"0.50",
",",
"0.75",
")",
")",
":",
"if",
"len",
"(",
"x",
".",
"shape",
")",
"==",
"1",
":",
"return",
"_wquantiles",
"(",
"W",
",",
"x",
",",
"alphas",
"=",
"alphas",
")",
"elif",
"len",
"(",
"x",
".",
"shape",
")",
"==",
"2",
":",
"return",
"np",
".",
"array",
"(",
"[",
"_wquantiles",
"(",
"W",
",",
"x",
"[",
":",
",",
"i",
"]",
",",
"alphas",
"=",
"alphas",
")",
"for",
"i",
"in",
"range",
"(",
"x",
".",
"shape",
"[",
"1",
"]",
")",
"]",
")"
] | Quantiles for weighted data.
Parameters
----------
W: (N,) ndarray
normalised weights (weights are >=0 and sum to one)
x: (N,) or (N,d) ndarray
data
alphas: list-like of size k (default: (0.25, 0.50, 0.75))
probabilities (between 0. and 1.)
Returns
-------
a (k,) or (d, k) ndarray containing the alpha-quantiles | [
"Quantiles",
"for",
"weighted",
"data",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/resampling.py#L359-L379 | train | 232,825 |
nchopin/particles | particles/resampling.py | wquantiles_str_array | def wquantiles_str_array(W, x, alphas=(0.25, 0.50, 0,75)):
"""quantiles for weighted data stored in a structured array.
Parameters
----------
W: (N,) ndarray
normalised weights (weights are >=0 and sum to one)
x: (N,) structured array
data
alphas: list-like of size k (default: (0.25, 0.50, 0.75))
probabilities (between 0. and 1.)
Returns
-------
dictionary {p: quantiles} that stores for each field name p
the corresponding quantiles
"""
return {p: wquantiles(W, x[p], alphas) for p in x.dtype.names} | python | def wquantiles_str_array(W, x, alphas=(0.25, 0.50, 0,75)):
"""quantiles for weighted data stored in a structured array.
Parameters
----------
W: (N,) ndarray
normalised weights (weights are >=0 and sum to one)
x: (N,) structured array
data
alphas: list-like of size k (default: (0.25, 0.50, 0.75))
probabilities (between 0. and 1.)
Returns
-------
dictionary {p: quantiles} that stores for each field name p
the corresponding quantiles
"""
return {p: wquantiles(W, x[p], alphas) for p in x.dtype.names} | [
"def",
"wquantiles_str_array",
"(",
"W",
",",
"x",
",",
"alphas",
"=",
"(",
"0.25",
",",
"0.50",
",",
"0",
",",
"75",
")",
")",
":",
"return",
"{",
"p",
":",
"wquantiles",
"(",
"W",
",",
"x",
"[",
"p",
"]",
",",
"alphas",
")",
"for",
"p",
"in",
"x",
".",
"dtype",
".",
"names",
"}"
] | quantiles for weighted data stored in a structured array.
Parameters
----------
W: (N,) ndarray
normalised weights (weights are >=0 and sum to one)
x: (N,) structured array
data
alphas: list-like of size k (default: (0.25, 0.50, 0.75))
probabilities (between 0. and 1.)
Returns
-------
dictionary {p: quantiles} that stores for each field name p
the corresponding quantiles | [
"quantiles",
"for",
"weighted",
"data",
"stored",
"in",
"a",
"structured",
"array",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/resampling.py#L381-L399 | train | 232,826 |
nchopin/particles | particles/resampling.py | resampling_scheme | def resampling_scheme(func):
"""Decorator for resampling schemes."""
@functools.wraps(func)
def modif_func(W, M=None):
M = W.shape[0] if M is None else M
return func(W, M)
rs_funcs[func.__name__] = modif_func
modif_func.__doc__ = rs_doc % func.__name__.capitalize()
return modif_func | python | def resampling_scheme(func):
"""Decorator for resampling schemes."""
@functools.wraps(func)
def modif_func(W, M=None):
M = W.shape[0] if M is None else M
return func(W, M)
rs_funcs[func.__name__] = modif_func
modif_func.__doc__ = rs_doc % func.__name__.capitalize()
return modif_func | [
"def",
"resampling_scheme",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"modif_func",
"(",
"W",
",",
"M",
"=",
"None",
")",
":",
"M",
"=",
"W",
".",
"shape",
"[",
"0",
"]",
"if",
"M",
"is",
"None",
"else",
"M",
"return",
"func",
"(",
"W",
",",
"M",
")",
"rs_funcs",
"[",
"func",
".",
"__name__",
"]",
"=",
"modif_func",
"modif_func",
".",
"__doc__",
"=",
"rs_doc",
"%",
"func",
".",
"__name__",
".",
"capitalize",
"(",
")",
"return",
"modif_func"
] | Decorator for resampling schemes. | [
"Decorator",
"for",
"resampling",
"schemes",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/resampling.py#L423-L433 | train | 232,827 |
nchopin/particles | particles/resampling.py | inverse_cdf | def inverse_cdf(su, W):
"""Inverse CDF algorithm for a finite distribution.
Parameters
----------
su: (M,) ndarray
M sorted uniform variates (i.e. M ordered points in [0,1]).
W: (N,) ndarray
a vector of N normalized weights (>=0 and sum to one)
Returns
-------
A: (M,) ndarray
a vector of M indices in range 0, ..., N-1
"""
j = 0
s = W[0]
M = su.shape[0]
A = np.empty(M, 'int')
for n in range(M):
while su[n] > s:
j += 1
s += W[j]
A[n] = j
return A | python | def inverse_cdf(su, W):
"""Inverse CDF algorithm for a finite distribution.
Parameters
----------
su: (M,) ndarray
M sorted uniform variates (i.e. M ordered points in [0,1]).
W: (N,) ndarray
a vector of N normalized weights (>=0 and sum to one)
Returns
-------
A: (M,) ndarray
a vector of M indices in range 0, ..., N-1
"""
j = 0
s = W[0]
M = su.shape[0]
A = np.empty(M, 'int')
for n in range(M):
while su[n] > s:
j += 1
s += W[j]
A[n] = j
return A | [
"def",
"inverse_cdf",
"(",
"su",
",",
"W",
")",
":",
"j",
"=",
"0",
"s",
"=",
"W",
"[",
"0",
"]",
"M",
"=",
"su",
".",
"shape",
"[",
"0",
"]",
"A",
"=",
"np",
".",
"empty",
"(",
"M",
",",
"'int'",
")",
"for",
"n",
"in",
"range",
"(",
"M",
")",
":",
"while",
"su",
"[",
"n",
"]",
">",
"s",
":",
"j",
"+=",
"1",
"s",
"+=",
"W",
"[",
"j",
"]",
"A",
"[",
"n",
"]",
"=",
"j",
"return",
"A"
] | Inverse CDF algorithm for a finite distribution.
Parameters
----------
su: (M,) ndarray
M sorted uniform variates (i.e. M ordered points in [0,1]).
W: (N,) ndarray
a vector of N normalized weights (>=0 and sum to one)
Returns
-------
A: (M,) ndarray
a vector of M indices in range 0, ..., N-1 | [
"Inverse",
"CDF",
"algorithm",
"for",
"a",
"finite",
"distribution",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/resampling.py#L443-L467 | train | 232,828 |
nchopin/particles | particles/hilbert.py | hilbert_array | def hilbert_array(xint):
"""Compute Hilbert indices.
Parameters
----------
xint: (N, d) int numpy.ndarray
Returns
-------
h: (N,) int numpy.ndarray
Hilbert indices
"""
N, d = xint.shape
h = np.zeros(N, int64)
for n in range(N):
h[n] = Hilbert_to_int(xint[n, :])
return h | python | def hilbert_array(xint):
"""Compute Hilbert indices.
Parameters
----------
xint: (N, d) int numpy.ndarray
Returns
-------
h: (N,) int numpy.ndarray
Hilbert indices
"""
N, d = xint.shape
h = np.zeros(N, int64)
for n in range(N):
h[n] = Hilbert_to_int(xint[n, :])
return h | [
"def",
"hilbert_array",
"(",
"xint",
")",
":",
"N",
",",
"d",
"=",
"xint",
".",
"shape",
"h",
"=",
"np",
".",
"zeros",
"(",
"N",
",",
"int64",
")",
"for",
"n",
"in",
"range",
"(",
"N",
")",
":",
"h",
"[",
"n",
"]",
"=",
"Hilbert_to_int",
"(",
"xint",
"[",
"n",
",",
":",
"]",
")",
"return",
"h"
] | Compute Hilbert indices.
Parameters
----------
xint: (N, d) int numpy.ndarray
Returns
-------
h: (N,) int numpy.ndarray
Hilbert indices | [
"Compute",
"Hilbert",
"indices",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/hilbert.py#L17-L33 | train | 232,829 |
nchopin/particles | particles/mcmc.py | MCMC.mean_sq_jump_dist | def mean_sq_jump_dist(self, discard_frac=0.1):
"""Mean squared jumping distance estimated from chain.
Parameters
----------
discard_frac: float
fraction of iterations to discard at the beginning (as a burn-in)
Returns
-------
float
"""
discard = int(self.niter * discard_frac)
return msjd(self.chain.theta[discard:]) | python | def mean_sq_jump_dist(self, discard_frac=0.1):
"""Mean squared jumping distance estimated from chain.
Parameters
----------
discard_frac: float
fraction of iterations to discard at the beginning (as a burn-in)
Returns
-------
float
"""
discard = int(self.niter * discard_frac)
return msjd(self.chain.theta[discard:]) | [
"def",
"mean_sq_jump_dist",
"(",
"self",
",",
"discard_frac",
"=",
"0.1",
")",
":",
"discard",
"=",
"int",
"(",
"self",
".",
"niter",
"*",
"discard_frac",
")",
"return",
"msjd",
"(",
"self",
".",
"chain",
".",
"theta",
"[",
"discard",
":",
"]",
")"
] | Mean squared jumping distance estimated from chain.
Parameters
----------
discard_frac: float
fraction of iterations to discard at the beginning (as a burn-in)
Returns
-------
float | [
"Mean",
"squared",
"jumping",
"distance",
"estimated",
"from",
"chain",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/mcmc.py#L99-L112 | train | 232,830 |
nchopin/particles | particles/mcmc.py | VanishCovTracker.update | def update(self, v):
"""Adds point v"""
self.t += 1
g = self.gamma()
self.mu = (1. - g) * self.mu + g * v
mv = v - self.mu
self.Sigma = ((1. - g) * self.Sigma
+ g * np.dot(mv[:, np.newaxis], mv[np.newaxis, :]))
try:
self.L = cholesky(self.Sigma, lower=True)
except LinAlgError:
self.L = self.L0 | python | def update(self, v):
"""Adds point v"""
self.t += 1
g = self.gamma()
self.mu = (1. - g) * self.mu + g * v
mv = v - self.mu
self.Sigma = ((1. - g) * self.Sigma
+ g * np.dot(mv[:, np.newaxis], mv[np.newaxis, :]))
try:
self.L = cholesky(self.Sigma, lower=True)
except LinAlgError:
self.L = self.L0 | [
"def",
"update",
"(",
"self",
",",
"v",
")",
":",
"self",
".",
"t",
"+=",
"1",
"g",
"=",
"self",
".",
"gamma",
"(",
")",
"self",
".",
"mu",
"=",
"(",
"1.",
"-",
"g",
")",
"*",
"self",
".",
"mu",
"+",
"g",
"*",
"v",
"mv",
"=",
"v",
"-",
"self",
".",
"mu",
"self",
".",
"Sigma",
"=",
"(",
"(",
"1.",
"-",
"g",
")",
"*",
"self",
".",
"Sigma",
"+",
"g",
"*",
"np",
".",
"dot",
"(",
"mv",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
",",
"mv",
"[",
"np",
".",
"newaxis",
",",
":",
"]",
")",
")",
"try",
":",
"self",
".",
"L",
"=",
"cholesky",
"(",
"self",
".",
"Sigma",
",",
"lower",
"=",
"True",
")",
"except",
"LinAlgError",
":",
"self",
".",
"L",
"=",
"self",
".",
"L0"
] | Adds point v | [
"Adds",
"point",
"v"
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/mcmc.py#L161-L172 | train | 232,831 |
nchopin/particles | particles/utils.py | cartesian_lists | def cartesian_lists(d):
"""
turns a dict of lists into a list of dicts that represents
the cartesian product of the initial lists
Example
-------
cartesian_lists({'a':[0, 2], 'b':[3, 4, 5]}
returns
[ {'a':0, 'b':3}, {'a':0, 'b':4}, ... {'a':2, 'b':5} ]
"""
return [{k: v for k, v in zip(d.keys(), args)}
for args in itertools.product(*d.values())] | python | def cartesian_lists(d):
"""
turns a dict of lists into a list of dicts that represents
the cartesian product of the initial lists
Example
-------
cartesian_lists({'a':[0, 2], 'b':[3, 4, 5]}
returns
[ {'a':0, 'b':3}, {'a':0, 'b':4}, ... {'a':2, 'b':5} ]
"""
return [{k: v for k, v in zip(d.keys(), args)}
for args in itertools.product(*d.values())] | [
"def",
"cartesian_lists",
"(",
"d",
")",
":",
"return",
"[",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"zip",
"(",
"d",
".",
"keys",
"(",
")",
",",
"args",
")",
"}",
"for",
"args",
"in",
"itertools",
".",
"product",
"(",
"*",
"d",
".",
"values",
"(",
")",
")",
"]"
] | turns a dict of lists into a list of dicts that represents
the cartesian product of the initial lists
Example
-------
cartesian_lists({'a':[0, 2], 'b':[3, 4, 5]}
returns
[ {'a':0, 'b':3}, {'a':0, 'b':4}, ... {'a':2, 'b':5} ] | [
"turns",
"a",
"dict",
"of",
"lists",
"into",
"a",
"list",
"of",
"dicts",
"that",
"represents",
"the",
"cartesian",
"product",
"of",
"the",
"initial",
"lists"
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/utils.py#L87-L100 | train | 232,832 |
nchopin/particles | particles/utils.py | cartesian_args | def cartesian_args(args, listargs, dictargs):
""" Compute a list of inputs and outputs for a function
with kw arguments.
args: dict
fixed arguments, e.g. {'x': 3}, then x=3 for all inputs
listargs: dict
arguments specified as a list; then the inputs
should be the Cartesian products of these lists
dictargs: dict
same as above, except the key will be used in the output
(see module doc for more explanation)
"""
ils = {k: [v, ] for k, v in args.items()}
ils.update(listargs)
ils.update({k: v.values() for k, v in dictargs.items()})
ols = listargs.copy()
ols.update({k: v.keys() for k, v in dictargs.items()})
return cartesian_lists(ils), cartesian_lists(ols) | python | def cartesian_args(args, listargs, dictargs):
""" Compute a list of inputs and outputs for a function
with kw arguments.
args: dict
fixed arguments, e.g. {'x': 3}, then x=3 for all inputs
listargs: dict
arguments specified as a list; then the inputs
should be the Cartesian products of these lists
dictargs: dict
same as above, except the key will be used in the output
(see module doc for more explanation)
"""
ils = {k: [v, ] for k, v in args.items()}
ils.update(listargs)
ils.update({k: v.values() for k, v in dictargs.items()})
ols = listargs.copy()
ols.update({k: v.keys() for k, v in dictargs.items()})
return cartesian_lists(ils), cartesian_lists(ols) | [
"def",
"cartesian_args",
"(",
"args",
",",
"listargs",
",",
"dictargs",
")",
":",
"ils",
"=",
"{",
"k",
":",
"[",
"v",
",",
"]",
"for",
"k",
",",
"v",
"in",
"args",
".",
"items",
"(",
")",
"}",
"ils",
".",
"update",
"(",
"listargs",
")",
"ils",
".",
"update",
"(",
"{",
"k",
":",
"v",
".",
"values",
"(",
")",
"for",
"k",
",",
"v",
"in",
"dictargs",
".",
"items",
"(",
")",
"}",
")",
"ols",
"=",
"listargs",
".",
"copy",
"(",
")",
"ols",
".",
"update",
"(",
"{",
"k",
":",
"v",
".",
"keys",
"(",
")",
"for",
"k",
",",
"v",
"in",
"dictargs",
".",
"items",
"(",
")",
"}",
")",
"return",
"cartesian_lists",
"(",
"ils",
")",
",",
"cartesian_lists",
"(",
"ols",
")"
] | Compute a list of inputs and outputs for a function
with kw arguments.
args: dict
fixed arguments, e.g. {'x': 3}, then x=3 for all inputs
listargs: dict
arguments specified as a list; then the inputs
should be the Cartesian products of these lists
dictargs: dict
same as above, except the key will be used in the output
(see module doc for more explanation) | [
"Compute",
"a",
"list",
"of",
"inputs",
"and",
"outputs",
"for",
"a",
"function",
"with",
"kw",
"arguments",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/utils.py#L103-L122 | train | 232,833 |
nchopin/particles | particles/utils.py | worker | def worker(qin, qout, f):
"""Worker for muliprocessing.
A worker repeatedly picks a dict of arguments in the queue and computes
f for this set of arguments, until the input queue is empty.
"""
while not qin.empty():
i, args = qin.get()
qout.put((i, f(**args))) | python | def worker(qin, qout, f):
"""Worker for muliprocessing.
A worker repeatedly picks a dict of arguments in the queue and computes
f for this set of arguments, until the input queue is empty.
"""
while not qin.empty():
i, args = qin.get()
qout.put((i, f(**args))) | [
"def",
"worker",
"(",
"qin",
",",
"qout",
",",
"f",
")",
":",
"while",
"not",
"qin",
".",
"empty",
"(",
")",
":",
"i",
",",
"args",
"=",
"qin",
".",
"get",
"(",
")",
"qout",
".",
"put",
"(",
"(",
"i",
",",
"f",
"(",
"*",
"*",
"args",
")",
")",
")"
] | Worker for muliprocessing.
A worker repeatedly picks a dict of arguments in the queue and computes
f for this set of arguments, until the input queue is empty. | [
"Worker",
"for",
"muliprocessing",
".",
"A",
"worker",
"repeatedly",
"picks",
"a",
"dict",
"of",
"arguments",
"in",
"the",
"queue",
"and",
"computes",
"f",
"for",
"this",
"set",
"of",
"arguments",
"until",
"the",
"input",
"queue",
"is",
"empty",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/utils.py#L133-L141 | train | 232,834 |
nchopin/particles | particles/utils.py | distinct_seeds | def distinct_seeds(k):
""" returns k distinct seeds for random number generation
"""
seeds = []
for _ in range(k):
while True:
s = random.randint(2**32 - 1)
if s not in seeds:
break
seeds.append(s)
return seeds | python | def distinct_seeds(k):
""" returns k distinct seeds for random number generation
"""
seeds = []
for _ in range(k):
while True:
s = random.randint(2**32 - 1)
if s not in seeds:
break
seeds.append(s)
return seeds | [
"def",
"distinct_seeds",
"(",
"k",
")",
":",
"seeds",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"k",
")",
":",
"while",
"True",
":",
"s",
"=",
"random",
".",
"randint",
"(",
"2",
"**",
"32",
"-",
"1",
")",
"if",
"s",
"not",
"in",
"seeds",
":",
"break",
"seeds",
".",
"append",
"(",
"s",
")",
"return",
"seeds"
] | returns k distinct seeds for random number generation | [
"returns",
"k",
"distinct",
"seeds",
"for",
"random",
"number",
"generation"
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/utils.py#L179-L189 | train | 232,835 |
nchopin/particles | particles/utils.py | multiplexer | def multiplexer(f=None, nruns=1, nprocs=1, seeding=None, **args):
"""Evaluate a function for different parameters, optionally in parallel.
Parameters
----------
f: function
function f to evaluate, must take only kw arguments as inputs
nruns: int
number of evaluations of f for each set of arguments
nprocs: int
+ if <=0, set to actual number of physical processors plus nprocs
(i.e. -1 => number of cpus on your machine minus one)
Default is 1, which means no multiprocessing
seeding: bool (default: True if nruns > 1, False otherwise)
whether we need to provide different seeds for RNGS
**args:
keyword arguments for function f.
Note
----
see documentation of `utils`
"""
if not callable(f):
raise ValueError('multiplexer: function f missing, or not callable')
if seeding is None:
seeding = (nruns > 1)
# extra arguments (meant to be arguments for f)
fixedargs, listargs, dictargs = {}, {}, {}
listargs['run'] = list(range(nruns))
for k, v in args.items():
if isinstance(v, list):
listargs[k] = v
elif isinstance(v, dict):
dictargs[k] = v
else:
fixedargs[k] = v
# cartesian product
inputs, outputs = cartesian_args(fixedargs, listargs, dictargs)
for ip in inputs:
ip.pop('run') # run is not an argument of f, just an id for output
# distributing different seeds
if seeding:
seeds = distinct_seeds(len(inputs))
for ip, op, s in zip(inputs, outputs, seeds):
ip['seed'] = s
op['seed'] = s
# the actual work happens here
return distribute_work(f, inputs, outputs, nprocs=nprocs) | python | def multiplexer(f=None, nruns=1, nprocs=1, seeding=None, **args):
"""Evaluate a function for different parameters, optionally in parallel.
Parameters
----------
f: function
function f to evaluate, must take only kw arguments as inputs
nruns: int
number of evaluations of f for each set of arguments
nprocs: int
+ if <=0, set to actual number of physical processors plus nprocs
(i.e. -1 => number of cpus on your machine minus one)
Default is 1, which means no multiprocessing
seeding: bool (default: True if nruns > 1, False otherwise)
whether we need to provide different seeds for RNGS
**args:
keyword arguments for function f.
Note
----
see documentation of `utils`
"""
if not callable(f):
raise ValueError('multiplexer: function f missing, or not callable')
if seeding is None:
seeding = (nruns > 1)
# extra arguments (meant to be arguments for f)
fixedargs, listargs, dictargs = {}, {}, {}
listargs['run'] = list(range(nruns))
for k, v in args.items():
if isinstance(v, list):
listargs[k] = v
elif isinstance(v, dict):
dictargs[k] = v
else:
fixedargs[k] = v
# cartesian product
inputs, outputs = cartesian_args(fixedargs, listargs, dictargs)
for ip in inputs:
ip.pop('run') # run is not an argument of f, just an id for output
# distributing different seeds
if seeding:
seeds = distinct_seeds(len(inputs))
for ip, op, s in zip(inputs, outputs, seeds):
ip['seed'] = s
op['seed'] = s
# the actual work happens here
return distribute_work(f, inputs, outputs, nprocs=nprocs) | [
"def",
"multiplexer",
"(",
"f",
"=",
"None",
",",
"nruns",
"=",
"1",
",",
"nprocs",
"=",
"1",
",",
"seeding",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"if",
"not",
"callable",
"(",
"f",
")",
":",
"raise",
"ValueError",
"(",
"'multiplexer: function f missing, or not callable'",
")",
"if",
"seeding",
"is",
"None",
":",
"seeding",
"=",
"(",
"nruns",
">",
"1",
")",
"# extra arguments (meant to be arguments for f)",
"fixedargs",
",",
"listargs",
",",
"dictargs",
"=",
"{",
"}",
",",
"{",
"}",
",",
"{",
"}",
"listargs",
"[",
"'run'",
"]",
"=",
"list",
"(",
"range",
"(",
"nruns",
")",
")",
"for",
"k",
",",
"v",
"in",
"args",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"list",
")",
":",
"listargs",
"[",
"k",
"]",
"=",
"v",
"elif",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"dictargs",
"[",
"k",
"]",
"=",
"v",
"else",
":",
"fixedargs",
"[",
"k",
"]",
"=",
"v",
"# cartesian product",
"inputs",
",",
"outputs",
"=",
"cartesian_args",
"(",
"fixedargs",
",",
"listargs",
",",
"dictargs",
")",
"for",
"ip",
"in",
"inputs",
":",
"ip",
".",
"pop",
"(",
"'run'",
")",
"# run is not an argument of f, just an id for output",
"# distributing different seeds",
"if",
"seeding",
":",
"seeds",
"=",
"distinct_seeds",
"(",
"len",
"(",
"inputs",
")",
")",
"for",
"ip",
",",
"op",
",",
"s",
"in",
"zip",
"(",
"inputs",
",",
"outputs",
",",
"seeds",
")",
":",
"ip",
"[",
"'seed'",
"]",
"=",
"s",
"op",
"[",
"'seed'",
"]",
"=",
"s",
"# the actual work happens here",
"return",
"distribute_work",
"(",
"f",
",",
"inputs",
",",
"outputs",
",",
"nprocs",
"=",
"nprocs",
")"
] | Evaluate a function for different parameters, optionally in parallel.
Parameters
----------
f: function
function f to evaluate, must take only kw arguments as inputs
nruns: int
number of evaluations of f for each set of arguments
nprocs: int
+ if <=0, set to actual number of physical processors plus nprocs
(i.e. -1 => number of cpus on your machine minus one)
Default is 1, which means no multiprocessing
seeding: bool (default: True if nruns > 1, False otherwise)
whether we need to provide different seeds for RNGS
**args:
keyword arguments for function f.
Note
----
see documentation of `utils` | [
"Evaluate",
"a",
"function",
"for",
"different",
"parameters",
"optionally",
"in",
"parallel",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/utils.py#L192-L240 | train | 232,836 |
nchopin/particles | particles/state_space_models.py | StateSpaceModel.simulate | def simulate(self, T):
"""Simulate state and observation processes.
Parameters
----------
T: int
processes are simulated from time 0 to time T-1
Returns
-------
x, y: lists
lists of length T
"""
x = []
for t in range(T):
law_x = self.PX0() if t == 0 else self.PX(t, x[-1])
x.append(law_x.rvs(size=1))
y = self.simulate_given_x(x)
return x, y | python | def simulate(self, T):
"""Simulate state and observation processes.
Parameters
----------
T: int
processes are simulated from time 0 to time T-1
Returns
-------
x, y: lists
lists of length T
"""
x = []
for t in range(T):
law_x = self.PX0() if t == 0 else self.PX(t, x[-1])
x.append(law_x.rvs(size=1))
y = self.simulate_given_x(x)
return x, y | [
"def",
"simulate",
"(",
"self",
",",
"T",
")",
":",
"x",
"=",
"[",
"]",
"for",
"t",
"in",
"range",
"(",
"T",
")",
":",
"law_x",
"=",
"self",
".",
"PX0",
"(",
")",
"if",
"t",
"==",
"0",
"else",
"self",
".",
"PX",
"(",
"t",
",",
"x",
"[",
"-",
"1",
"]",
")",
"x",
".",
"append",
"(",
"law_x",
".",
"rvs",
"(",
"size",
"=",
"1",
")",
")",
"y",
"=",
"self",
".",
"simulate_given_x",
"(",
"x",
")",
"return",
"x",
",",
"y"
] | Simulate state and observation processes.
Parameters
----------
T: int
processes are simulated from time 0 to time T-1
Returns
-------
x, y: lists
lists of length T | [
"Simulate",
"state",
"and",
"observation",
"processes",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/state_space_models.py#L280-L298 | train | 232,837 |
nchopin/particles | book/mle/malikpitt_interpolation.py | interpoled_resampling | def interpoled_resampling(W, x):
"""Resampling based on an interpolated CDF, as described in Malik and Pitt.
Parameters
----------
W: (N,) array
weights
x: (N,) array
particles
Returns
-------
xrs: (N,) array
the resampled particles
"""
N = W.shape[0]
idx = np.argsort(x)
xs = x[idx]
ws = W[idx]
cs = np.cumsum(avg_n_nplusone(ws))
u = random.rand(N)
xrs = np.empty(N)
where = np.searchsorted(cs, u)
# costs O(N log(N)) but algorithm has O(N log(N)) complexity anyway
for n in range(N):
m = where[n]
if m==0:
xrs[n] = xs[0]
elif m==N:
xrs[n] = xs[-1]
else:
xrs[n] = interpol(cs[m-1], cs[m], xs[m-1], xs[m], u[n])
return xrs | python | def interpoled_resampling(W, x):
"""Resampling based on an interpolated CDF, as described in Malik and Pitt.
Parameters
----------
W: (N,) array
weights
x: (N,) array
particles
Returns
-------
xrs: (N,) array
the resampled particles
"""
N = W.shape[0]
idx = np.argsort(x)
xs = x[idx]
ws = W[idx]
cs = np.cumsum(avg_n_nplusone(ws))
u = random.rand(N)
xrs = np.empty(N)
where = np.searchsorted(cs, u)
# costs O(N log(N)) but algorithm has O(N log(N)) complexity anyway
for n in range(N):
m = where[n]
if m==0:
xrs[n] = xs[0]
elif m==N:
xrs[n] = xs[-1]
else:
xrs[n] = interpol(cs[m-1], cs[m], xs[m-1], xs[m], u[n])
return xrs | [
"def",
"interpoled_resampling",
"(",
"W",
",",
"x",
")",
":",
"N",
"=",
"W",
".",
"shape",
"[",
"0",
"]",
"idx",
"=",
"np",
".",
"argsort",
"(",
"x",
")",
"xs",
"=",
"x",
"[",
"idx",
"]",
"ws",
"=",
"W",
"[",
"idx",
"]",
"cs",
"=",
"np",
".",
"cumsum",
"(",
"avg_n_nplusone",
"(",
"ws",
")",
")",
"u",
"=",
"random",
".",
"rand",
"(",
"N",
")",
"xrs",
"=",
"np",
".",
"empty",
"(",
"N",
")",
"where",
"=",
"np",
".",
"searchsorted",
"(",
"cs",
",",
"u",
")",
"# costs O(N log(N)) but algorithm has O(N log(N)) complexity anyway",
"for",
"n",
"in",
"range",
"(",
"N",
")",
":",
"m",
"=",
"where",
"[",
"n",
"]",
"if",
"m",
"==",
"0",
":",
"xrs",
"[",
"n",
"]",
"=",
"xs",
"[",
"0",
"]",
"elif",
"m",
"==",
"N",
":",
"xrs",
"[",
"n",
"]",
"=",
"xs",
"[",
"-",
"1",
"]",
"else",
":",
"xrs",
"[",
"n",
"]",
"=",
"interpol",
"(",
"cs",
"[",
"m",
"-",
"1",
"]",
",",
"cs",
"[",
"m",
"]",
",",
"xs",
"[",
"m",
"-",
"1",
"]",
",",
"xs",
"[",
"m",
"]",
",",
"u",
"[",
"n",
"]",
")",
"return",
"xrs"
] | Resampling based on an interpolated CDF, as described in Malik and Pitt.
Parameters
----------
W: (N,) array
weights
x: (N,) array
particles
Returns
-------
xrs: (N,) array
the resampled particles | [
"Resampling",
"based",
"on",
"an",
"interpolated",
"CDF",
"as",
"described",
"in",
"Malik",
"and",
"Pitt",
"."
] | 3faa97a1073db45c5889eef3e015dd76ef350b52 | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/book/mle/malikpitt_interpolation.py#L26-L59 | train | 232,838 |
Fortran-FOSS-Programmers/ford | ford/sourceform.py | sort_items | def sort_items(self,items,args=False):
"""
Sort the `self`'s contents, as contained in the list `items` as
specified in `self`'s meta-data.
"""
if self.settings['sort'].lower() == 'src': return
def alpha(i):
return i.name
def permission(i):
if args:
if i.intent == 'in': return 'b'
if i.intent == 'inout': return 'c'
if i.intent == 'out': return 'd'
if i.intent == '': return 'e'
perm = getattr(i, 'permission', '')
if perm == 'public': return 'b'
if perm == 'protected': return 'c'
if perm == 'private': return 'd'
return 'a'
def permission_alpha(i):
return permission(i) + '-' + i.name
def itype(i):
if i.obj == 'variable':
retstr = i.vartype
if retstr == 'class': retstr = 'type'
if i.kind: retstr = retstr + '-' + str(i.kind)
if i.strlen: retstr = retstr + '-' + str(i.strlen)
if i.proto:
retstr = retstr + '-' + i.proto[0]
return retstr
elif i.obj == 'proc':
if i.proctype != 'Function':
return i.proctype.lower()
else:
return i.proctype.lower() + '-' + itype(i.retvar)
else:
return i.obj
def itype_alpha(i):
return itype(i) + '-' + i.name
if self.settings['sort'].lower() == 'alpha':
items.sort(key=alpha)
elif self.settings['sort'].lower() == 'permission':
items.sort(key=permission)
elif self.settings['sort'].lower() == 'permission-alpha':
items.sort(key=permission_alpha)
elif self.settings['sort'].lower() == 'type':
items.sort(key=itype)
elif self.settings['sort'].lower() == 'type-alpha':
items.sort(key=itype_alpha) | python | def sort_items(self,items,args=False):
"""
Sort the `self`'s contents, as contained in the list `items` as
specified in `self`'s meta-data.
"""
if self.settings['sort'].lower() == 'src': return
def alpha(i):
return i.name
def permission(i):
if args:
if i.intent == 'in': return 'b'
if i.intent == 'inout': return 'c'
if i.intent == 'out': return 'd'
if i.intent == '': return 'e'
perm = getattr(i, 'permission', '')
if perm == 'public': return 'b'
if perm == 'protected': return 'c'
if perm == 'private': return 'd'
return 'a'
def permission_alpha(i):
return permission(i) + '-' + i.name
def itype(i):
if i.obj == 'variable':
retstr = i.vartype
if retstr == 'class': retstr = 'type'
if i.kind: retstr = retstr + '-' + str(i.kind)
if i.strlen: retstr = retstr + '-' + str(i.strlen)
if i.proto:
retstr = retstr + '-' + i.proto[0]
return retstr
elif i.obj == 'proc':
if i.proctype != 'Function':
return i.proctype.lower()
else:
return i.proctype.lower() + '-' + itype(i.retvar)
else:
return i.obj
def itype_alpha(i):
return itype(i) + '-' + i.name
if self.settings['sort'].lower() == 'alpha':
items.sort(key=alpha)
elif self.settings['sort'].lower() == 'permission':
items.sort(key=permission)
elif self.settings['sort'].lower() == 'permission-alpha':
items.sort(key=permission_alpha)
elif self.settings['sort'].lower() == 'type':
items.sort(key=itype)
elif self.settings['sort'].lower() == 'type-alpha':
items.sort(key=itype_alpha) | [
"def",
"sort_items",
"(",
"self",
",",
"items",
",",
"args",
"=",
"False",
")",
":",
"if",
"self",
".",
"settings",
"[",
"'sort'",
"]",
".",
"lower",
"(",
")",
"==",
"'src'",
":",
"return",
"def",
"alpha",
"(",
"i",
")",
":",
"return",
"i",
".",
"name",
"def",
"permission",
"(",
"i",
")",
":",
"if",
"args",
":",
"if",
"i",
".",
"intent",
"==",
"'in'",
":",
"return",
"'b'",
"if",
"i",
".",
"intent",
"==",
"'inout'",
":",
"return",
"'c'",
"if",
"i",
".",
"intent",
"==",
"'out'",
":",
"return",
"'d'",
"if",
"i",
".",
"intent",
"==",
"''",
":",
"return",
"'e'",
"perm",
"=",
"getattr",
"(",
"i",
",",
"'permission'",
",",
"''",
")",
"if",
"perm",
"==",
"'public'",
":",
"return",
"'b'",
"if",
"perm",
"==",
"'protected'",
":",
"return",
"'c'",
"if",
"perm",
"==",
"'private'",
":",
"return",
"'d'",
"return",
"'a'",
"def",
"permission_alpha",
"(",
"i",
")",
":",
"return",
"permission",
"(",
"i",
")",
"+",
"'-'",
"+",
"i",
".",
"name",
"def",
"itype",
"(",
"i",
")",
":",
"if",
"i",
".",
"obj",
"==",
"'variable'",
":",
"retstr",
"=",
"i",
".",
"vartype",
"if",
"retstr",
"==",
"'class'",
":",
"retstr",
"=",
"'type'",
"if",
"i",
".",
"kind",
":",
"retstr",
"=",
"retstr",
"+",
"'-'",
"+",
"str",
"(",
"i",
".",
"kind",
")",
"if",
"i",
".",
"strlen",
":",
"retstr",
"=",
"retstr",
"+",
"'-'",
"+",
"str",
"(",
"i",
".",
"strlen",
")",
"if",
"i",
".",
"proto",
":",
"retstr",
"=",
"retstr",
"+",
"'-'",
"+",
"i",
".",
"proto",
"[",
"0",
"]",
"return",
"retstr",
"elif",
"i",
".",
"obj",
"==",
"'proc'",
":",
"if",
"i",
".",
"proctype",
"!=",
"'Function'",
":",
"return",
"i",
".",
"proctype",
".",
"lower",
"(",
")",
"else",
":",
"return",
"i",
".",
"proctype",
".",
"lower",
"(",
")",
"+",
"'-'",
"+",
"itype",
"(",
"i",
".",
"retvar",
")",
"else",
":",
"return",
"i",
".",
"obj",
"def",
"itype_alpha",
"(",
"i",
")",
":",
"return",
"itype",
"(",
"i",
")",
"+",
"'-'",
"+",
"i",
".",
"name",
"if",
"self",
".",
"settings",
"[",
"'sort'",
"]",
".",
"lower",
"(",
")",
"==",
"'alpha'",
":",
"items",
".",
"sort",
"(",
"key",
"=",
"alpha",
")",
"elif",
"self",
".",
"settings",
"[",
"'sort'",
"]",
".",
"lower",
"(",
")",
"==",
"'permission'",
":",
"items",
".",
"sort",
"(",
"key",
"=",
"permission",
")",
"elif",
"self",
".",
"settings",
"[",
"'sort'",
"]",
".",
"lower",
"(",
")",
"==",
"'permission-alpha'",
":",
"items",
".",
"sort",
"(",
"key",
"=",
"permission_alpha",
")",
"elif",
"self",
".",
"settings",
"[",
"'sort'",
"]",
".",
"lower",
"(",
")",
"==",
"'type'",
":",
"items",
".",
"sort",
"(",
"key",
"=",
"itype",
")",
"elif",
"self",
".",
"settings",
"[",
"'sort'",
"]",
".",
"lower",
"(",
")",
"==",
"'type-alpha'",
":",
"items",
".",
"sort",
"(",
"key",
"=",
"itype_alpha",
")"
] | Sort the `self`'s contents, as contained in the list `items` as
specified in `self`'s meta-data. | [
"Sort",
"the",
"self",
"s",
"contents",
"as",
"contained",
"in",
"the",
"list",
"items",
"as",
"specified",
"in",
"self",
"s",
"meta",
"-",
"data",
"."
] | d46a44eae20d99205292c31785f936fbed47070f | https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/sourceform.py#L2402-L2451 | train | 232,839 |
Fortran-FOSS-Programmers/ford | ford/sourceform.py | FortranBase.contents_size | def contents_size(self):
'''
Returns the number of different categories to be shown in the
contents side-bar in the HTML documentation.
'''
count = 0
if hasattr(self,'variables'): count += 1
if hasattr(self,'types'): count += 1
if hasattr(self,'modules'): count += 1
if hasattr(self,'submodules'): count += 1
if hasattr(self,'subroutines'): count += 1
if hasattr(self,'modprocedures'): count += 1
if hasattr(self,'functions'): count += 1
if hasattr(self,'interfaces'): count += 1
if hasattr(self,'absinterfaces'): count += 1
if hasattr(self,'programs'): count += 1
if hasattr(self,'boundprocs'): count += 1
if hasattr(self,'finalprocs'): count += 1
if hasattr(self,'enums'): count += 1
if hasattr(self,'procedure'): count += 1
if hasattr(self,'constructor'): count += 1
if hasattr(self,'modfunctions'): count += 1
if hasattr(self,'modsubroutines'): count += 1
if hasattr(self,'modprocs'): count += 1
if getattr(self,'src',None): count += 1
return count | python | def contents_size(self):
'''
Returns the number of different categories to be shown in the
contents side-bar in the HTML documentation.
'''
count = 0
if hasattr(self,'variables'): count += 1
if hasattr(self,'types'): count += 1
if hasattr(self,'modules'): count += 1
if hasattr(self,'submodules'): count += 1
if hasattr(self,'subroutines'): count += 1
if hasattr(self,'modprocedures'): count += 1
if hasattr(self,'functions'): count += 1
if hasattr(self,'interfaces'): count += 1
if hasattr(self,'absinterfaces'): count += 1
if hasattr(self,'programs'): count += 1
if hasattr(self,'boundprocs'): count += 1
if hasattr(self,'finalprocs'): count += 1
if hasattr(self,'enums'): count += 1
if hasattr(self,'procedure'): count += 1
if hasattr(self,'constructor'): count += 1
if hasattr(self,'modfunctions'): count += 1
if hasattr(self,'modsubroutines'): count += 1
if hasattr(self,'modprocs'): count += 1
if getattr(self,'src',None): count += 1
return count | [
"def",
"contents_size",
"(",
"self",
")",
":",
"count",
"=",
"0",
"if",
"hasattr",
"(",
"self",
",",
"'variables'",
")",
":",
"count",
"+=",
"1",
"if",
"hasattr",
"(",
"self",
",",
"'types'",
")",
":",
"count",
"+=",
"1",
"if",
"hasattr",
"(",
"self",
",",
"'modules'",
")",
":",
"count",
"+=",
"1",
"if",
"hasattr",
"(",
"self",
",",
"'submodules'",
")",
":",
"count",
"+=",
"1",
"if",
"hasattr",
"(",
"self",
",",
"'subroutines'",
")",
":",
"count",
"+=",
"1",
"if",
"hasattr",
"(",
"self",
",",
"'modprocedures'",
")",
":",
"count",
"+=",
"1",
"if",
"hasattr",
"(",
"self",
",",
"'functions'",
")",
":",
"count",
"+=",
"1",
"if",
"hasattr",
"(",
"self",
",",
"'interfaces'",
")",
":",
"count",
"+=",
"1",
"if",
"hasattr",
"(",
"self",
",",
"'absinterfaces'",
")",
":",
"count",
"+=",
"1",
"if",
"hasattr",
"(",
"self",
",",
"'programs'",
")",
":",
"count",
"+=",
"1",
"if",
"hasattr",
"(",
"self",
",",
"'boundprocs'",
")",
":",
"count",
"+=",
"1",
"if",
"hasattr",
"(",
"self",
",",
"'finalprocs'",
")",
":",
"count",
"+=",
"1",
"if",
"hasattr",
"(",
"self",
",",
"'enums'",
")",
":",
"count",
"+=",
"1",
"if",
"hasattr",
"(",
"self",
",",
"'procedure'",
")",
":",
"count",
"+=",
"1",
"if",
"hasattr",
"(",
"self",
",",
"'constructor'",
")",
":",
"count",
"+=",
"1",
"if",
"hasattr",
"(",
"self",
",",
"'modfunctions'",
")",
":",
"count",
"+=",
"1",
"if",
"hasattr",
"(",
"self",
",",
"'modsubroutines'",
")",
":",
"count",
"+=",
"1",
"if",
"hasattr",
"(",
"self",
",",
"'modprocs'",
")",
":",
"count",
"+=",
"1",
"if",
"getattr",
"(",
"self",
",",
"'src'",
",",
"None",
")",
":",
"count",
"+=",
"1",
"return",
"count"
] | Returns the number of different categories to be shown in the
contents side-bar in the HTML documentation. | [
"Returns",
"the",
"number",
"of",
"different",
"categories",
"to",
"be",
"shown",
"in",
"the",
"contents",
"side",
"-",
"bar",
"in",
"the",
"HTML",
"documentation",
"."
] | d46a44eae20d99205292c31785f936fbed47070f | https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/sourceform.py#L267-L292 | train | 232,840 |
Fortran-FOSS-Programmers/ford | ford/sourceform.py | FortranBase.sort | def sort(self):
'''
Sorts components of the object.
'''
if hasattr(self,'variables'):
sort_items(self,self.variables)
if hasattr(self,'modules'):
sort_items(self,self.modules)
if hasattr(self,'submodules'):
sort_items(self,self.submodules)
if hasattr(self,'common'):
sort_items(self,self.common)
if hasattr(self,'subroutines'):
sort_items(self,self.subroutines)
if hasattr(self,'modprocedures'):
sort_items(self,self.modprocedures)
if hasattr(self,'functions'):
sort_items(self,self.functions)
if hasattr(self,'interfaces'):
sort_items(self,self.interfaces)
if hasattr(self,'absinterfaces'):
sort_items(self,self.absinterfaces)
if hasattr(self,'types'):
sort_items(self,self.types)
if hasattr(self,'programs'):
sort_items(self,self.programs)
if hasattr(self,'blockdata'):
sort_items(self,self.blockdata)
if hasattr(self,'boundprocs'):
sort_items(self,self.boundprocs)
if hasattr(self,'finalprocs'):
sort_items(self,self.finalprocs)
if hasattr(self,'args'):
#sort_items(self.args,args=True)
pass | python | def sort(self):
'''
Sorts components of the object.
'''
if hasattr(self,'variables'):
sort_items(self,self.variables)
if hasattr(self,'modules'):
sort_items(self,self.modules)
if hasattr(self,'submodules'):
sort_items(self,self.submodules)
if hasattr(self,'common'):
sort_items(self,self.common)
if hasattr(self,'subroutines'):
sort_items(self,self.subroutines)
if hasattr(self,'modprocedures'):
sort_items(self,self.modprocedures)
if hasattr(self,'functions'):
sort_items(self,self.functions)
if hasattr(self,'interfaces'):
sort_items(self,self.interfaces)
if hasattr(self,'absinterfaces'):
sort_items(self,self.absinterfaces)
if hasattr(self,'types'):
sort_items(self,self.types)
if hasattr(self,'programs'):
sort_items(self,self.programs)
if hasattr(self,'blockdata'):
sort_items(self,self.blockdata)
if hasattr(self,'boundprocs'):
sort_items(self,self.boundprocs)
if hasattr(self,'finalprocs'):
sort_items(self,self.finalprocs)
if hasattr(self,'args'):
#sort_items(self.args,args=True)
pass | [
"def",
"sort",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'variables'",
")",
":",
"sort_items",
"(",
"self",
",",
"self",
".",
"variables",
")",
"if",
"hasattr",
"(",
"self",
",",
"'modules'",
")",
":",
"sort_items",
"(",
"self",
",",
"self",
".",
"modules",
")",
"if",
"hasattr",
"(",
"self",
",",
"'submodules'",
")",
":",
"sort_items",
"(",
"self",
",",
"self",
".",
"submodules",
")",
"if",
"hasattr",
"(",
"self",
",",
"'common'",
")",
":",
"sort_items",
"(",
"self",
",",
"self",
".",
"common",
")",
"if",
"hasattr",
"(",
"self",
",",
"'subroutines'",
")",
":",
"sort_items",
"(",
"self",
",",
"self",
".",
"subroutines",
")",
"if",
"hasattr",
"(",
"self",
",",
"'modprocedures'",
")",
":",
"sort_items",
"(",
"self",
",",
"self",
".",
"modprocedures",
")",
"if",
"hasattr",
"(",
"self",
",",
"'functions'",
")",
":",
"sort_items",
"(",
"self",
",",
"self",
".",
"functions",
")",
"if",
"hasattr",
"(",
"self",
",",
"'interfaces'",
")",
":",
"sort_items",
"(",
"self",
",",
"self",
".",
"interfaces",
")",
"if",
"hasattr",
"(",
"self",
",",
"'absinterfaces'",
")",
":",
"sort_items",
"(",
"self",
",",
"self",
".",
"absinterfaces",
")",
"if",
"hasattr",
"(",
"self",
",",
"'types'",
")",
":",
"sort_items",
"(",
"self",
",",
"self",
".",
"types",
")",
"if",
"hasattr",
"(",
"self",
",",
"'programs'",
")",
":",
"sort_items",
"(",
"self",
",",
"self",
".",
"programs",
")",
"if",
"hasattr",
"(",
"self",
",",
"'blockdata'",
")",
":",
"sort_items",
"(",
"self",
",",
"self",
".",
"blockdata",
")",
"if",
"hasattr",
"(",
"self",
",",
"'boundprocs'",
")",
":",
"sort_items",
"(",
"self",
",",
"self",
".",
"boundprocs",
")",
"if",
"hasattr",
"(",
"self",
",",
"'finalprocs'",
")",
":",
"sort_items",
"(",
"self",
",",
"self",
".",
"finalprocs",
")",
"if",
"hasattr",
"(",
"self",
",",
"'args'",
")",
":",
"#sort_items(self.args,args=True)",
"pass"
] | Sorts components of the object. | [
"Sorts",
"components",
"of",
"the",
"object",
"."
] | d46a44eae20d99205292c31785f936fbed47070f | https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/sourceform.py#L417-L451 | train | 232,841 |
Fortran-FOSS-Programmers/ford | ford/sourceform.py | FortranBase.make_links | def make_links(self, project):
"""
Process intra-site links to documentation of other parts of the program.
"""
self.doc = ford.utils.sub_links(self.doc,project)
if 'summary' in self.meta:
self.meta['summary'] = ford.utils.sub_links(self.meta['summary'],project)
# Create links in the project
for item in self.iterator('variables', 'types', 'enums', 'modules',
'submodules', 'subroutines', 'functions',
'interfaces', 'absinterfaces', 'programs',
'boundprocs', 'args', 'bindings'):
if isinstance(item, FortranBase):
item.make_links(project)
if hasattr(self, 'retvar'):
if self.retvar:
if isinstance(self.retvar, FortranBase):
self.retvar.make_links(project)
if hasattr(self, 'procedure'):
if isinstance(self.procedure, FortranBase):
self.procedure.make_links(project) | python | def make_links(self, project):
"""
Process intra-site links to documentation of other parts of the program.
"""
self.doc = ford.utils.sub_links(self.doc,project)
if 'summary' in self.meta:
self.meta['summary'] = ford.utils.sub_links(self.meta['summary'],project)
# Create links in the project
for item in self.iterator('variables', 'types', 'enums', 'modules',
'submodules', 'subroutines', 'functions',
'interfaces', 'absinterfaces', 'programs',
'boundprocs', 'args', 'bindings'):
if isinstance(item, FortranBase):
item.make_links(project)
if hasattr(self, 'retvar'):
if self.retvar:
if isinstance(self.retvar, FortranBase):
self.retvar.make_links(project)
if hasattr(self, 'procedure'):
if isinstance(self.procedure, FortranBase):
self.procedure.make_links(project) | [
"def",
"make_links",
"(",
"self",
",",
"project",
")",
":",
"self",
".",
"doc",
"=",
"ford",
".",
"utils",
".",
"sub_links",
"(",
"self",
".",
"doc",
",",
"project",
")",
"if",
"'summary'",
"in",
"self",
".",
"meta",
":",
"self",
".",
"meta",
"[",
"'summary'",
"]",
"=",
"ford",
".",
"utils",
".",
"sub_links",
"(",
"self",
".",
"meta",
"[",
"'summary'",
"]",
",",
"project",
")",
"# Create links in the project",
"for",
"item",
"in",
"self",
".",
"iterator",
"(",
"'variables'",
",",
"'types'",
",",
"'enums'",
",",
"'modules'",
",",
"'submodules'",
",",
"'subroutines'",
",",
"'functions'",
",",
"'interfaces'",
",",
"'absinterfaces'",
",",
"'programs'",
",",
"'boundprocs'",
",",
"'args'",
",",
"'bindings'",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"FortranBase",
")",
":",
"item",
".",
"make_links",
"(",
"project",
")",
"if",
"hasattr",
"(",
"self",
",",
"'retvar'",
")",
":",
"if",
"self",
".",
"retvar",
":",
"if",
"isinstance",
"(",
"self",
".",
"retvar",
",",
"FortranBase",
")",
":",
"self",
".",
"retvar",
".",
"make_links",
"(",
"project",
")",
"if",
"hasattr",
"(",
"self",
",",
"'procedure'",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"procedure",
",",
"FortranBase",
")",
":",
"self",
".",
"procedure",
".",
"make_links",
"(",
"project",
")"
] | Process intra-site links to documentation of other parts of the program. | [
"Process",
"intra",
"-",
"site",
"links",
"to",
"documentation",
"of",
"other",
"parts",
"of",
"the",
"program",
"."
] | d46a44eae20d99205292c31785f936fbed47070f | https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/sourceform.py#L454-L475 | train | 232,842 |
Fortran-FOSS-Programmers/ford | ford/sourceform.py | FortranBase.iterator | def iterator(self, *argv):
""" Iterator returning any list of elements via attribute lookup in `self`
This iterator retains the order of the arguments """
for arg in argv:
if hasattr(self, arg):
for item in getattr(self, arg):
yield item | python | def iterator(self, *argv):
""" Iterator returning any list of elements via attribute lookup in `self`
This iterator retains the order of the arguments """
for arg in argv:
if hasattr(self, arg):
for item in getattr(self, arg):
yield item | [
"def",
"iterator",
"(",
"self",
",",
"*",
"argv",
")",
":",
"for",
"arg",
"in",
"argv",
":",
"if",
"hasattr",
"(",
"self",
",",
"arg",
")",
":",
"for",
"item",
"in",
"getattr",
"(",
"self",
",",
"arg",
")",
":",
"yield",
"item"
] | Iterator returning any list of elements via attribute lookup in `self`
This iterator retains the order of the arguments | [
"Iterator",
"returning",
"any",
"list",
"of",
"elements",
"via",
"attribute",
"lookup",
"in",
"self"
] | d46a44eae20d99205292c31785f936fbed47070f | https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/sourceform.py#L486-L493 | train | 232,843 |
Fortran-FOSS-Programmers/ford | ford/sourceform.py | FortranModule.get_used_entities | def get_used_entities(self,use_specs):
"""
Returns the entities which are imported by a use statement. These
are contained in dicts.
"""
if len(use_specs.strip()) == 0:
return (self.pub_procs, self.pub_absints, self.pub_types, self.pub_vars)
only = bool(self.ONLY_RE.match(use_specs))
use_specs = self.ONLY_RE.sub('',use_specs)
ulist = self.SPLIT_RE.split(use_specs)
ulist[-1] = ulist[-1].strip()
uspecs = {}
for item in ulist:
match = self.RENAME_RE.search(item)
if match:
uspecs[match.group(1).lower()] = match.group(2)
else:
uspecs[item.lower()] = item
ret_procs = {}
ret_absints = {}
ret_types = {}
ret_vars = {}
for name, obj in self.pub_procs.items():
name = name.lower()
if only:
if name in uspecs:
ret_procs[name] = obj
else:
ret_procs[name] = obj
for name, obj in self.pub_absints.items():
name = name.lower()
if only:
if name in uspecs:
ret_absints[name] = obj
else:
ret_absints[name] = obj
for name, obj in self.pub_types.items():
name = name.lower()
if only:
if name in uspecs:
ret_types[name] = obj
else:
ret_types[name] = obj
for name, obj in self.pub_vars.items():
name = name.lower()
if only:
if name in uspecs:
ret_vars[name] = obj
else:
ret_vars[name] = obj
return (ret_procs,ret_absints,ret_types,ret_vars) | python | def get_used_entities(self,use_specs):
"""
Returns the entities which are imported by a use statement. These
are contained in dicts.
"""
if len(use_specs.strip()) == 0:
return (self.pub_procs, self.pub_absints, self.pub_types, self.pub_vars)
only = bool(self.ONLY_RE.match(use_specs))
use_specs = self.ONLY_RE.sub('',use_specs)
ulist = self.SPLIT_RE.split(use_specs)
ulist[-1] = ulist[-1].strip()
uspecs = {}
for item in ulist:
match = self.RENAME_RE.search(item)
if match:
uspecs[match.group(1).lower()] = match.group(2)
else:
uspecs[item.lower()] = item
ret_procs = {}
ret_absints = {}
ret_types = {}
ret_vars = {}
for name, obj in self.pub_procs.items():
name = name.lower()
if only:
if name in uspecs:
ret_procs[name] = obj
else:
ret_procs[name] = obj
for name, obj in self.pub_absints.items():
name = name.lower()
if only:
if name in uspecs:
ret_absints[name] = obj
else:
ret_absints[name] = obj
for name, obj in self.pub_types.items():
name = name.lower()
if only:
if name in uspecs:
ret_types[name] = obj
else:
ret_types[name] = obj
for name, obj in self.pub_vars.items():
name = name.lower()
if only:
if name in uspecs:
ret_vars[name] = obj
else:
ret_vars[name] = obj
return (ret_procs,ret_absints,ret_types,ret_vars) | [
"def",
"get_used_entities",
"(",
"self",
",",
"use_specs",
")",
":",
"if",
"len",
"(",
"use_specs",
".",
"strip",
"(",
")",
")",
"==",
"0",
":",
"return",
"(",
"self",
".",
"pub_procs",
",",
"self",
".",
"pub_absints",
",",
"self",
".",
"pub_types",
",",
"self",
".",
"pub_vars",
")",
"only",
"=",
"bool",
"(",
"self",
".",
"ONLY_RE",
".",
"match",
"(",
"use_specs",
")",
")",
"use_specs",
"=",
"self",
".",
"ONLY_RE",
".",
"sub",
"(",
"''",
",",
"use_specs",
")",
"ulist",
"=",
"self",
".",
"SPLIT_RE",
".",
"split",
"(",
"use_specs",
")",
"ulist",
"[",
"-",
"1",
"]",
"=",
"ulist",
"[",
"-",
"1",
"]",
".",
"strip",
"(",
")",
"uspecs",
"=",
"{",
"}",
"for",
"item",
"in",
"ulist",
":",
"match",
"=",
"self",
".",
"RENAME_RE",
".",
"search",
"(",
"item",
")",
"if",
"match",
":",
"uspecs",
"[",
"match",
".",
"group",
"(",
"1",
")",
".",
"lower",
"(",
")",
"]",
"=",
"match",
".",
"group",
"(",
"2",
")",
"else",
":",
"uspecs",
"[",
"item",
".",
"lower",
"(",
")",
"]",
"=",
"item",
"ret_procs",
"=",
"{",
"}",
"ret_absints",
"=",
"{",
"}",
"ret_types",
"=",
"{",
"}",
"ret_vars",
"=",
"{",
"}",
"for",
"name",
",",
"obj",
"in",
"self",
".",
"pub_procs",
".",
"items",
"(",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"if",
"only",
":",
"if",
"name",
"in",
"uspecs",
":",
"ret_procs",
"[",
"name",
"]",
"=",
"obj",
"else",
":",
"ret_procs",
"[",
"name",
"]",
"=",
"obj",
"for",
"name",
",",
"obj",
"in",
"self",
".",
"pub_absints",
".",
"items",
"(",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"if",
"only",
":",
"if",
"name",
"in",
"uspecs",
":",
"ret_absints",
"[",
"name",
"]",
"=",
"obj",
"else",
":",
"ret_absints",
"[",
"name",
"]",
"=",
"obj",
"for",
"name",
",",
"obj",
"in",
"self",
".",
"pub_types",
".",
"items",
"(",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"if",
"only",
":",
"if",
"name",
"in",
"uspecs",
":",
"ret_types",
"[",
"name",
"]",
"=",
"obj",
"else",
":",
"ret_types",
"[",
"name",
"]",
"=",
"obj",
"for",
"name",
",",
"obj",
"in",
"self",
".",
"pub_vars",
".",
"items",
"(",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"if",
"only",
":",
"if",
"name",
"in",
"uspecs",
":",
"ret_vars",
"[",
"name",
"]",
"=",
"obj",
"else",
":",
"ret_vars",
"[",
"name",
"]",
"=",
"obj",
"return",
"(",
"ret_procs",
",",
"ret_absints",
",",
"ret_types",
",",
"ret_vars",
")"
] | Returns the entities which are imported by a use statement. These
are contained in dicts. | [
"Returns",
"the",
"entities",
"which",
"are",
"imported",
"by",
"a",
"use",
"statement",
".",
"These",
"are",
"contained",
"in",
"dicts",
"."
] | d46a44eae20d99205292c31785f936fbed47070f | https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/sourceform.py#L1138-L1188 | train | 232,844 |
Fortran-FOSS-Programmers/ford | ford/sourceform.py | NameSelector.get_name | def get_name(self,item):
"""
Return the name for this item registered with this NameSelector.
If no name has previously been registered, then generate a new
one.
"""
if not isinstance(item,ford.sourceform.FortranBase):
raise Exception('{} is not of a type derived from FortranBase'.format(str(item)))
if item in self._items:
return self._items[item]
else:
if item.get_dir() not in self._counts:
self._counts[item.get_dir()] = {}
if item.name in self._counts[item.get_dir()]:
num = self._counts[item.get_dir()][item.name] + 1
else:
num = 1
self._counts[item.get_dir()][item.name] = num
name = item.name.lower().replace('<','lt')
# name is already lower
name = name.replace('>','gt')
name = name.replace('/','SLASH')
if name == '': name = '__unnamed__'
if num > 1:
name = name + '~' + str(num)
self._items[item] = name
return name | python | def get_name(self,item):
"""
Return the name for this item registered with this NameSelector.
If no name has previously been registered, then generate a new
one.
"""
if not isinstance(item,ford.sourceform.FortranBase):
raise Exception('{} is not of a type derived from FortranBase'.format(str(item)))
if item in self._items:
return self._items[item]
else:
if item.get_dir() not in self._counts:
self._counts[item.get_dir()] = {}
if item.name in self._counts[item.get_dir()]:
num = self._counts[item.get_dir()][item.name] + 1
else:
num = 1
self._counts[item.get_dir()][item.name] = num
name = item.name.lower().replace('<','lt')
# name is already lower
name = name.replace('>','gt')
name = name.replace('/','SLASH')
if name == '': name = '__unnamed__'
if num > 1:
name = name + '~' + str(num)
self._items[item] = name
return name | [
"def",
"get_name",
"(",
"self",
",",
"item",
")",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"ford",
".",
"sourceform",
".",
"FortranBase",
")",
":",
"raise",
"Exception",
"(",
"'{} is not of a type derived from FortranBase'",
".",
"format",
"(",
"str",
"(",
"item",
")",
")",
")",
"if",
"item",
"in",
"self",
".",
"_items",
":",
"return",
"self",
".",
"_items",
"[",
"item",
"]",
"else",
":",
"if",
"item",
".",
"get_dir",
"(",
")",
"not",
"in",
"self",
".",
"_counts",
":",
"self",
".",
"_counts",
"[",
"item",
".",
"get_dir",
"(",
")",
"]",
"=",
"{",
"}",
"if",
"item",
".",
"name",
"in",
"self",
".",
"_counts",
"[",
"item",
".",
"get_dir",
"(",
")",
"]",
":",
"num",
"=",
"self",
".",
"_counts",
"[",
"item",
".",
"get_dir",
"(",
")",
"]",
"[",
"item",
".",
"name",
"]",
"+",
"1",
"else",
":",
"num",
"=",
"1",
"self",
".",
"_counts",
"[",
"item",
".",
"get_dir",
"(",
")",
"]",
"[",
"item",
".",
"name",
"]",
"=",
"num",
"name",
"=",
"item",
".",
"name",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"'<'",
",",
"'lt'",
")",
"# name is already lower",
"name",
"=",
"name",
".",
"replace",
"(",
"'>'",
",",
"'gt'",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"'/'",
",",
"'SLASH'",
")",
"if",
"name",
"==",
"''",
":",
"name",
"=",
"'__unnamed__'",
"if",
"num",
">",
"1",
":",
"name",
"=",
"name",
"+",
"'~'",
"+",
"str",
"(",
"num",
")",
"self",
".",
"_items",
"[",
"item",
"]",
"=",
"name",
"return",
"name"
] | Return the name for this item registered with this NameSelector.
If no name has previously been registered, then generate a new
one. | [
"Return",
"the",
"name",
"for",
"this",
"item",
"registered",
"with",
"this",
"NameSelector",
".",
"If",
"no",
"name",
"has",
"previously",
"been",
"registered",
"then",
"generate",
"a",
"new",
"one",
"."
] | d46a44eae20d99205292c31785f936fbed47070f | https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/sourceform.py#L2466-L2493 | train | 232,845 |
Fortran-FOSS-Programmers/ford | ford/__init__.py | main | def main(proj_data,proj_docs,md):
"""
Main driver of FORD.
"""
if proj_data['relative']: proj_data['project_url'] = '.'
# Parse the files in your project
project = ford.fortran_project.Project(proj_data)
if len(project.files) < 1:
print("Error: No source files with appropriate extension found in specified directory.")
sys.exit(1)
# Convert the documentation from Markdown to HTML. Make sure to properly
# handle LateX and metadata.
if proj_data['relative']:
project.markdown(md,'..')
else:
project.markdown(md,proj_data['project_url'])
project.correlate()
if proj_data['relative']:
project.make_links('..')
else:
project.make_links(proj_data['project_url'])
# Convert summaries and descriptions to HTML
if proj_data['relative']: ford.sourceform.set_base_url('.')
if 'summary' in proj_data:
proj_data['summary'] = md.convert(proj_data['summary'])
proj_data['summary'] = ford.utils.sub_links(ford.utils.sub_macros(ford.utils.sub_notes(proj_data['summary']),proj_data['project_url']),project)
if 'author_description' in proj_data:
proj_data['author_description'] = md.convert(proj_data['author_description'])
proj_data['author_description'] = ford.utils.sub_links(ford.utils.sub_macros(ford.utils.sub_notes(proj_data['author_description']),proj_data['project_url']),project)
proj_docs_ = ford.utils.sub_links(ford.utils.sub_macros(ford.utils.sub_notes(proj_docs),proj_data['project_url']),project)
# Process any pages
if 'page_dir' in proj_data:
page_tree = ford.pagetree.get_page_tree(os.path.normpath(proj_data['page_dir']),md)
print()
else:
page_tree = None
proj_data['pages'] = page_tree
# Produce the documentation using Jinja2. Output it to the desired location
# and copy any files that are needed (CSS, JS, images, fonts, source files,
# etc.)
docs = ford.output.Documentation(proj_data,proj_docs_,project,page_tree)
docs.writeout()
print('')
return 0 | python | def main(proj_data,proj_docs,md):
"""
Main driver of FORD.
"""
if proj_data['relative']: proj_data['project_url'] = '.'
# Parse the files in your project
project = ford.fortran_project.Project(proj_data)
if len(project.files) < 1:
print("Error: No source files with appropriate extension found in specified directory.")
sys.exit(1)
# Convert the documentation from Markdown to HTML. Make sure to properly
# handle LateX and metadata.
if proj_data['relative']:
project.markdown(md,'..')
else:
project.markdown(md,proj_data['project_url'])
project.correlate()
if proj_data['relative']:
project.make_links('..')
else:
project.make_links(proj_data['project_url'])
# Convert summaries and descriptions to HTML
if proj_data['relative']: ford.sourceform.set_base_url('.')
if 'summary' in proj_data:
proj_data['summary'] = md.convert(proj_data['summary'])
proj_data['summary'] = ford.utils.sub_links(ford.utils.sub_macros(ford.utils.sub_notes(proj_data['summary']),proj_data['project_url']),project)
if 'author_description' in proj_data:
proj_data['author_description'] = md.convert(proj_data['author_description'])
proj_data['author_description'] = ford.utils.sub_links(ford.utils.sub_macros(ford.utils.sub_notes(proj_data['author_description']),proj_data['project_url']),project)
proj_docs_ = ford.utils.sub_links(ford.utils.sub_macros(ford.utils.sub_notes(proj_docs),proj_data['project_url']),project)
# Process any pages
if 'page_dir' in proj_data:
page_tree = ford.pagetree.get_page_tree(os.path.normpath(proj_data['page_dir']),md)
print()
else:
page_tree = None
proj_data['pages'] = page_tree
# Produce the documentation using Jinja2. Output it to the desired location
# and copy any files that are needed (CSS, JS, images, fonts, source files,
# etc.)
docs = ford.output.Documentation(proj_data,proj_docs_,project,page_tree)
docs.writeout()
print('')
return 0 | [
"def",
"main",
"(",
"proj_data",
",",
"proj_docs",
",",
"md",
")",
":",
"if",
"proj_data",
"[",
"'relative'",
"]",
":",
"proj_data",
"[",
"'project_url'",
"]",
"=",
"'.'",
"# Parse the files in your project",
"project",
"=",
"ford",
".",
"fortran_project",
".",
"Project",
"(",
"proj_data",
")",
"if",
"len",
"(",
"project",
".",
"files",
")",
"<",
"1",
":",
"print",
"(",
"\"Error: No source files with appropriate extension found in specified directory.\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"# Convert the documentation from Markdown to HTML. Make sure to properly",
"# handle LateX and metadata.",
"if",
"proj_data",
"[",
"'relative'",
"]",
":",
"project",
".",
"markdown",
"(",
"md",
",",
"'..'",
")",
"else",
":",
"project",
".",
"markdown",
"(",
"md",
",",
"proj_data",
"[",
"'project_url'",
"]",
")",
"project",
".",
"correlate",
"(",
")",
"if",
"proj_data",
"[",
"'relative'",
"]",
":",
"project",
".",
"make_links",
"(",
"'..'",
")",
"else",
":",
"project",
".",
"make_links",
"(",
"proj_data",
"[",
"'project_url'",
"]",
")",
"# Convert summaries and descriptions to HTML",
"if",
"proj_data",
"[",
"'relative'",
"]",
":",
"ford",
".",
"sourceform",
".",
"set_base_url",
"(",
"'.'",
")",
"if",
"'summary'",
"in",
"proj_data",
":",
"proj_data",
"[",
"'summary'",
"]",
"=",
"md",
".",
"convert",
"(",
"proj_data",
"[",
"'summary'",
"]",
")",
"proj_data",
"[",
"'summary'",
"]",
"=",
"ford",
".",
"utils",
".",
"sub_links",
"(",
"ford",
".",
"utils",
".",
"sub_macros",
"(",
"ford",
".",
"utils",
".",
"sub_notes",
"(",
"proj_data",
"[",
"'summary'",
"]",
")",
",",
"proj_data",
"[",
"'project_url'",
"]",
")",
",",
"project",
")",
"if",
"'author_description'",
"in",
"proj_data",
":",
"proj_data",
"[",
"'author_description'",
"]",
"=",
"md",
".",
"convert",
"(",
"proj_data",
"[",
"'author_description'",
"]",
")",
"proj_data",
"[",
"'author_description'",
"]",
"=",
"ford",
".",
"utils",
".",
"sub_links",
"(",
"ford",
".",
"utils",
".",
"sub_macros",
"(",
"ford",
".",
"utils",
".",
"sub_notes",
"(",
"proj_data",
"[",
"'author_description'",
"]",
")",
",",
"proj_data",
"[",
"'project_url'",
"]",
")",
",",
"project",
")",
"proj_docs_",
"=",
"ford",
".",
"utils",
".",
"sub_links",
"(",
"ford",
".",
"utils",
".",
"sub_macros",
"(",
"ford",
".",
"utils",
".",
"sub_notes",
"(",
"proj_docs",
")",
",",
"proj_data",
"[",
"'project_url'",
"]",
")",
",",
"project",
")",
"# Process any pages",
"if",
"'page_dir'",
"in",
"proj_data",
":",
"page_tree",
"=",
"ford",
".",
"pagetree",
".",
"get_page_tree",
"(",
"os",
".",
"path",
".",
"normpath",
"(",
"proj_data",
"[",
"'page_dir'",
"]",
")",
",",
"md",
")",
"print",
"(",
")",
"else",
":",
"page_tree",
"=",
"None",
"proj_data",
"[",
"'pages'",
"]",
"=",
"page_tree",
"# Produce the documentation using Jinja2. Output it to the desired location",
"# and copy any files that are needed (CSS, JS, images, fonts, source files,",
"# etc.)",
"docs",
"=",
"ford",
".",
"output",
".",
"Documentation",
"(",
"proj_data",
",",
"proj_docs_",
",",
"project",
",",
"page_tree",
")",
"docs",
".",
"writeout",
"(",
")",
"print",
"(",
"''",
")",
"return",
"0"
] | Main driver of FORD. | [
"Main",
"driver",
"of",
"FORD",
"."
] | d46a44eae20d99205292c31785f936fbed47070f | https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/__init__.py#L337-L382 | train | 232,846 |
Fortran-FOSS-Programmers/ford | ford/fixed2free2.py | convertToFree | def convertToFree(stream, length_limit=True):
"""Convert stream from fixed source form to free source form."""
linestack = []
for line in stream:
convline = FortranLine(line, length_limit)
if convline.is_regular:
if convline.isContinuation and linestack:
linestack[0].continueLine()
for l in linestack:
yield str(l)
linestack = []
linestack.append(convline)
for l in linestack:
yield str(l) | python | def convertToFree(stream, length_limit=True):
"""Convert stream from fixed source form to free source form."""
linestack = []
for line in stream:
convline = FortranLine(line, length_limit)
if convline.is_regular:
if convline.isContinuation and linestack:
linestack[0].continueLine()
for l in linestack:
yield str(l)
linestack = []
linestack.append(convline)
for l in linestack:
yield str(l) | [
"def",
"convertToFree",
"(",
"stream",
",",
"length_limit",
"=",
"True",
")",
":",
"linestack",
"=",
"[",
"]",
"for",
"line",
"in",
"stream",
":",
"convline",
"=",
"FortranLine",
"(",
"line",
",",
"length_limit",
")",
"if",
"convline",
".",
"is_regular",
":",
"if",
"convline",
".",
"isContinuation",
"and",
"linestack",
":",
"linestack",
"[",
"0",
"]",
".",
"continueLine",
"(",
")",
"for",
"l",
"in",
"linestack",
":",
"yield",
"str",
"(",
"l",
")",
"linestack",
"=",
"[",
"]",
"linestack",
".",
"append",
"(",
"convline",
")",
"for",
"l",
"in",
"linestack",
":",
"yield",
"str",
"(",
"l",
")"
] | Convert stream from fixed source form to free source form. | [
"Convert",
"stream",
"from",
"fixed",
"source",
"form",
"to",
"free",
"source",
"form",
"."
] | d46a44eae20d99205292c31785f936fbed47070f | https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/fixed2free2.py#L110-L127 | train | 232,847 |
Fortran-FOSS-Programmers/ford | ford/fixed2free2.py | FortranLine.continueLine | def continueLine(self):
"""Insert line continuation symbol at end of line."""
if not (self.isLong and self.is_regular):
self.line_conv = self.line_conv.rstrip() + " &\n"
else:
temp = self.line_conv[:72].rstrip() + " &"
self.line_conv = temp.ljust(72) + self.excess_line | python | def continueLine(self):
"""Insert line continuation symbol at end of line."""
if not (self.isLong and self.is_regular):
self.line_conv = self.line_conv.rstrip() + " &\n"
else:
temp = self.line_conv[:72].rstrip() + " &"
self.line_conv = temp.ljust(72) + self.excess_line | [
"def",
"continueLine",
"(",
"self",
")",
":",
"if",
"not",
"(",
"self",
".",
"isLong",
"and",
"self",
".",
"is_regular",
")",
":",
"self",
".",
"line_conv",
"=",
"self",
".",
"line_conv",
".",
"rstrip",
"(",
")",
"+",
"\" &\\n\"",
"else",
":",
"temp",
"=",
"self",
".",
"line_conv",
"[",
":",
"72",
"]",
".",
"rstrip",
"(",
")",
"+",
"\" &\"",
"self",
".",
"line_conv",
"=",
"temp",
".",
"ljust",
"(",
"72",
")",
"+",
"self",
".",
"excess_line"
] | Insert line continuation symbol at end of line. | [
"Insert",
"line",
"continuation",
"symbol",
"at",
"end",
"of",
"line",
"."
] | d46a44eae20d99205292c31785f936fbed47070f | https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/fixed2free2.py#L52-L59 | train | 232,848 |
Fortran-FOSS-Programmers/ford | ford/fortran_project.py | id_mods | def id_mods(obj,modlist,intrinsic_mods={},submodlist=[]):
"""
Match USE statements up with the right modules
"""
for i in range(len(obj.uses)):
for candidate in modlist:
if obj.uses[i][0].lower() == candidate.name.lower():
obj.uses[i] = [candidate, obj.uses[i][1]]
break
else:
if obj.uses[i][0].lower() in intrinsic_mods:
obj.uses[i] = [intrinsic_mods[obj.uses[i][0].lower()], obj.uses[i][1]]
continue
if getattr(obj,'ancestor',None):
for submod in submodlist:
if obj.ancestor.lower() == submod.name.lower():
obj.ancestor = submod
break
if hasattr(obj,'ancestor_mod'):
for mod in modlist:
if obj.ancestor_mod.lower() == mod.name.lower():
obj.ancestor_mod = mod
break
for modproc in getattr(obj,'modprocedures',[]):
id_mods(modproc,modlist,intrinsic_mods)
for func in getattr(obj,'functions',[]):
id_mods(func,modlist,intrinsic_mods)
for subroutine in getattr(obj,'subroutines',[]):
id_mods(subroutine,modlist,intrinsic_mods) | python | def id_mods(obj,modlist,intrinsic_mods={},submodlist=[]):
"""
Match USE statements up with the right modules
"""
for i in range(len(obj.uses)):
for candidate in modlist:
if obj.uses[i][0].lower() == candidate.name.lower():
obj.uses[i] = [candidate, obj.uses[i][1]]
break
else:
if obj.uses[i][0].lower() in intrinsic_mods:
obj.uses[i] = [intrinsic_mods[obj.uses[i][0].lower()], obj.uses[i][1]]
continue
if getattr(obj,'ancestor',None):
for submod in submodlist:
if obj.ancestor.lower() == submod.name.lower():
obj.ancestor = submod
break
if hasattr(obj,'ancestor_mod'):
for mod in modlist:
if obj.ancestor_mod.lower() == mod.name.lower():
obj.ancestor_mod = mod
break
for modproc in getattr(obj,'modprocedures',[]):
id_mods(modproc,modlist,intrinsic_mods)
for func in getattr(obj,'functions',[]):
id_mods(func,modlist,intrinsic_mods)
for subroutine in getattr(obj,'subroutines',[]):
id_mods(subroutine,modlist,intrinsic_mods) | [
"def",
"id_mods",
"(",
"obj",
",",
"modlist",
",",
"intrinsic_mods",
"=",
"{",
"}",
",",
"submodlist",
"=",
"[",
"]",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"obj",
".",
"uses",
")",
")",
":",
"for",
"candidate",
"in",
"modlist",
":",
"if",
"obj",
".",
"uses",
"[",
"i",
"]",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"==",
"candidate",
".",
"name",
".",
"lower",
"(",
")",
":",
"obj",
".",
"uses",
"[",
"i",
"]",
"=",
"[",
"candidate",
",",
"obj",
".",
"uses",
"[",
"i",
"]",
"[",
"1",
"]",
"]",
"break",
"else",
":",
"if",
"obj",
".",
"uses",
"[",
"i",
"]",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"in",
"intrinsic_mods",
":",
"obj",
".",
"uses",
"[",
"i",
"]",
"=",
"[",
"intrinsic_mods",
"[",
"obj",
".",
"uses",
"[",
"i",
"]",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"]",
",",
"obj",
".",
"uses",
"[",
"i",
"]",
"[",
"1",
"]",
"]",
"continue",
"if",
"getattr",
"(",
"obj",
",",
"'ancestor'",
",",
"None",
")",
":",
"for",
"submod",
"in",
"submodlist",
":",
"if",
"obj",
".",
"ancestor",
".",
"lower",
"(",
")",
"==",
"submod",
".",
"name",
".",
"lower",
"(",
")",
":",
"obj",
".",
"ancestor",
"=",
"submod",
"break",
"if",
"hasattr",
"(",
"obj",
",",
"'ancestor_mod'",
")",
":",
"for",
"mod",
"in",
"modlist",
":",
"if",
"obj",
".",
"ancestor_mod",
".",
"lower",
"(",
")",
"==",
"mod",
".",
"name",
".",
"lower",
"(",
")",
":",
"obj",
".",
"ancestor_mod",
"=",
"mod",
"break",
"for",
"modproc",
"in",
"getattr",
"(",
"obj",
",",
"'modprocedures'",
",",
"[",
"]",
")",
":",
"id_mods",
"(",
"modproc",
",",
"modlist",
",",
"intrinsic_mods",
")",
"for",
"func",
"in",
"getattr",
"(",
"obj",
",",
"'functions'",
",",
"[",
"]",
")",
":",
"id_mods",
"(",
"func",
",",
"modlist",
",",
"intrinsic_mods",
")",
"for",
"subroutine",
"in",
"getattr",
"(",
"obj",
",",
"'subroutines'",
",",
"[",
"]",
")",
":",
"id_mods",
"(",
"subroutine",
",",
"modlist",
",",
"intrinsic_mods",
")"
] | Match USE statements up with the right modules | [
"Match",
"USE",
"statements",
"up",
"with",
"the",
"right",
"modules"
] | d46a44eae20d99205292c31785f936fbed47070f | https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/fortran_project.py#L338-L366 | train | 232,849 |
Fortran-FOSS-Programmers/ford | ford/fortran_project.py | Project.allfiles | def allfiles(self):
""" Instead of duplicating files, it is much more efficient to create the itterator on the fly """
for f in self.files:
yield f
for f in self.extra_files:
yield f | python | def allfiles(self):
""" Instead of duplicating files, it is much more efficient to create the itterator on the fly """
for f in self.files:
yield f
for f in self.extra_files:
yield f | [
"def",
"allfiles",
"(",
"self",
")",
":",
"for",
"f",
"in",
"self",
".",
"files",
":",
"yield",
"f",
"for",
"f",
"in",
"self",
".",
"extra_files",
":",
"yield",
"f"
] | Instead of duplicating files, it is much more efficient to create the itterator on the fly | [
"Instead",
"of",
"duplicating",
"files",
"it",
"is",
"much",
"more",
"efficient",
"to",
"create",
"the",
"itterator",
"on",
"the",
"fly"
] | d46a44eae20d99205292c31785f936fbed47070f | https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/fortran_project.py#L124-L129 | train | 232,850 |
Fortran-FOSS-Programmers/ford | ford/fortran_project.py | Project.make_links | def make_links(self,base_url='..'):
"""
Substitute intrasite links to documentation for other parts of
the program.
"""
ford.sourceform.set_base_url(base_url)
for src in self.allfiles:
src.make_links(self) | python | def make_links(self,base_url='..'):
"""
Substitute intrasite links to documentation for other parts of
the program.
"""
ford.sourceform.set_base_url(base_url)
for src in self.allfiles:
src.make_links(self) | [
"def",
"make_links",
"(",
"self",
",",
"base_url",
"=",
"'..'",
")",
":",
"ford",
".",
"sourceform",
".",
"set_base_url",
"(",
"base_url",
")",
"for",
"src",
"in",
"self",
".",
"allfiles",
":",
"src",
".",
"make_links",
"(",
"self",
")"
] | Substitute intrasite links to documentation for other parts of
the program. | [
"Substitute",
"intrasite",
"links",
"to",
"documentation",
"for",
"other",
"parts",
"of",
"the",
"program",
"."
] | d46a44eae20d99205292c31785f936fbed47070f | https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/fortran_project.py#L305-L312 | train | 232,851 |
Fortran-FOSS-Programmers/ford | ford/utils.py | sub_notes | def sub_notes(docs):
"""
Substitutes the special controls for notes, warnings, todos, and bugs with
the corresponding div.
"""
def substitute(match):
ret = "</p><div class=\"alert alert-{}\" role=\"alert\"><h4>{}</h4>" \
"<p>{}</p></div>".format(NOTE_TYPE[match.group(1).lower()],
match.group(1).capitalize(), match.group(2))
if len(match.groups()) >= 4 and not match.group(4): ret += '\n<p>'
return ret
for regex in NOTE_RE:
docs = regex.sub(substitute,docs)
return docs | python | def sub_notes(docs):
"""
Substitutes the special controls for notes, warnings, todos, and bugs with
the corresponding div.
"""
def substitute(match):
ret = "</p><div class=\"alert alert-{}\" role=\"alert\"><h4>{}</h4>" \
"<p>{}</p></div>".format(NOTE_TYPE[match.group(1).lower()],
match.group(1).capitalize(), match.group(2))
if len(match.groups()) >= 4 and not match.group(4): ret += '\n<p>'
return ret
for regex in NOTE_RE:
docs = regex.sub(substitute,docs)
return docs | [
"def",
"sub_notes",
"(",
"docs",
")",
":",
"def",
"substitute",
"(",
"match",
")",
":",
"ret",
"=",
"\"</p><div class=\\\"alert alert-{}\\\" role=\\\"alert\\\"><h4>{}</h4>\"",
"\"<p>{}</p></div>\"",
".",
"format",
"(",
"NOTE_TYPE",
"[",
"match",
".",
"group",
"(",
"1",
")",
".",
"lower",
"(",
")",
"]",
",",
"match",
".",
"group",
"(",
"1",
")",
".",
"capitalize",
"(",
")",
",",
"match",
".",
"group",
"(",
"2",
")",
")",
"if",
"len",
"(",
"match",
".",
"groups",
"(",
")",
")",
">=",
"4",
"and",
"not",
"match",
".",
"group",
"(",
"4",
")",
":",
"ret",
"+=",
"'\\n<p>'",
"return",
"ret",
"for",
"regex",
"in",
"NOTE_RE",
":",
"docs",
"=",
"regex",
".",
"sub",
"(",
"substitute",
",",
"docs",
")",
"return",
"docs"
] | Substitutes the special controls for notes, warnings, todos, and bugs with
the corresponding div. | [
"Substitutes",
"the",
"special",
"controls",
"for",
"notes",
"warnings",
"todos",
"and",
"bugs",
"with",
"the",
"corresponding",
"div",
"."
] | d46a44eae20d99205292c31785f936fbed47070f | https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/utils.py#L42-L55 | train | 232,852 |
Fortran-FOSS-Programmers/ford | ford/utils.py | paren_split | def paren_split(sep,string):
"""
Splits the string into pieces divided by sep, when sep is outside of parentheses.
"""
if len(sep) != 1: raise Exception("Separation string must be one character long")
retlist = []
level = 0
blevel = 0
left = 0
for i in range(len(string)):
if string[i] == "(": level += 1
elif string[i] == ")": level -= 1
elif string[i] == "[": blevel += 1
elif string[i] == "]": blevel -= 1
elif string[i] == sep and level == 0 and blevel == 0:
retlist.append(string[left:i])
left = i+1
retlist.append(string[left:])
return retlist | python | def paren_split(sep,string):
"""
Splits the string into pieces divided by sep, when sep is outside of parentheses.
"""
if len(sep) != 1: raise Exception("Separation string must be one character long")
retlist = []
level = 0
blevel = 0
left = 0
for i in range(len(string)):
if string[i] == "(": level += 1
elif string[i] == ")": level -= 1
elif string[i] == "[": blevel += 1
elif string[i] == "]": blevel -= 1
elif string[i] == sep and level == 0 and blevel == 0:
retlist.append(string[left:i])
left = i+1
retlist.append(string[left:])
return retlist | [
"def",
"paren_split",
"(",
"sep",
",",
"string",
")",
":",
"if",
"len",
"(",
"sep",
")",
"!=",
"1",
":",
"raise",
"Exception",
"(",
"\"Separation string must be one character long\"",
")",
"retlist",
"=",
"[",
"]",
"level",
"=",
"0",
"blevel",
"=",
"0",
"left",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"string",
")",
")",
":",
"if",
"string",
"[",
"i",
"]",
"==",
"\"(\"",
":",
"level",
"+=",
"1",
"elif",
"string",
"[",
"i",
"]",
"==",
"\")\"",
":",
"level",
"-=",
"1",
"elif",
"string",
"[",
"i",
"]",
"==",
"\"[\"",
":",
"blevel",
"+=",
"1",
"elif",
"string",
"[",
"i",
"]",
"==",
"\"]\"",
":",
"blevel",
"-=",
"1",
"elif",
"string",
"[",
"i",
"]",
"==",
"sep",
"and",
"level",
"==",
"0",
"and",
"blevel",
"==",
"0",
":",
"retlist",
".",
"append",
"(",
"string",
"[",
"left",
":",
"i",
"]",
")",
"left",
"=",
"i",
"+",
"1",
"retlist",
".",
"append",
"(",
"string",
"[",
"left",
":",
"]",
")",
"return",
"retlist"
] | Splits the string into pieces divided by sep, when sep is outside of parentheses. | [
"Splits",
"the",
"string",
"into",
"pieces",
"divided",
"by",
"sep",
"when",
"sep",
"is",
"outside",
"of",
"parentheses",
"."
] | d46a44eae20d99205292c31785f936fbed47070f | https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/utils.py#L88-L106 | train | 232,853 |
Fortran-FOSS-Programmers/ford | ford/utils.py | quote_split | def quote_split(sep,string):
"""
Splits the strings into pieces divided by sep, when sep in not inside quotes.
"""
if len(sep) != 1: raise Exception("Separation string must be one character long")
retlist = []
squote = False
dquote = False
left = 0
i = 0
while i < len(string):
if string[i] == '"' and not dquote:
if not squote:
squote = True
elif (i+1) < len(string) and string[i+1] == '"':
i += 1
else:
squote = False
elif string[i] == "'" and not squote:
if not dquote:
dquote = True
elif (i+1) < len(string) and string[i+1] == "'":
i += 1
else:
dquote = False
elif string[i] == sep and not dquote and not squote:
retlist.append(string[left:i])
left = i + 1
i += 1
retlist.append(string[left:])
return retlist | python | def quote_split(sep,string):
"""
Splits the strings into pieces divided by sep, when sep in not inside quotes.
"""
if len(sep) != 1: raise Exception("Separation string must be one character long")
retlist = []
squote = False
dquote = False
left = 0
i = 0
while i < len(string):
if string[i] == '"' and not dquote:
if not squote:
squote = True
elif (i+1) < len(string) and string[i+1] == '"':
i += 1
else:
squote = False
elif string[i] == "'" and not squote:
if not dquote:
dquote = True
elif (i+1) < len(string) and string[i+1] == "'":
i += 1
else:
dquote = False
elif string[i] == sep and not dquote and not squote:
retlist.append(string[left:i])
left = i + 1
i += 1
retlist.append(string[left:])
return retlist | [
"def",
"quote_split",
"(",
"sep",
",",
"string",
")",
":",
"if",
"len",
"(",
"sep",
")",
"!=",
"1",
":",
"raise",
"Exception",
"(",
"\"Separation string must be one character long\"",
")",
"retlist",
"=",
"[",
"]",
"squote",
"=",
"False",
"dquote",
"=",
"False",
"left",
"=",
"0",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"string",
")",
":",
"if",
"string",
"[",
"i",
"]",
"==",
"'\"'",
"and",
"not",
"dquote",
":",
"if",
"not",
"squote",
":",
"squote",
"=",
"True",
"elif",
"(",
"i",
"+",
"1",
")",
"<",
"len",
"(",
"string",
")",
"and",
"string",
"[",
"i",
"+",
"1",
"]",
"==",
"'\"'",
":",
"i",
"+=",
"1",
"else",
":",
"squote",
"=",
"False",
"elif",
"string",
"[",
"i",
"]",
"==",
"\"'\"",
"and",
"not",
"squote",
":",
"if",
"not",
"dquote",
":",
"dquote",
"=",
"True",
"elif",
"(",
"i",
"+",
"1",
")",
"<",
"len",
"(",
"string",
")",
"and",
"string",
"[",
"i",
"+",
"1",
"]",
"==",
"\"'\"",
":",
"i",
"+=",
"1",
"else",
":",
"dquote",
"=",
"False",
"elif",
"string",
"[",
"i",
"]",
"==",
"sep",
"and",
"not",
"dquote",
"and",
"not",
"squote",
":",
"retlist",
".",
"append",
"(",
"string",
"[",
"left",
":",
"i",
"]",
")",
"left",
"=",
"i",
"+",
"1",
"i",
"+=",
"1",
"retlist",
".",
"append",
"(",
"string",
"[",
"left",
":",
"]",
")",
"return",
"retlist"
] | Splits the strings into pieces divided by sep, when sep in not inside quotes. | [
"Splits",
"the",
"strings",
"into",
"pieces",
"divided",
"by",
"sep",
"when",
"sep",
"in",
"not",
"inside",
"quotes",
"."
] | d46a44eae20d99205292c31785f936fbed47070f | https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/utils.py#L110-L140 | train | 232,854 |
Fortran-FOSS-Programmers/ford | ford/utils.py | split_path | def split_path(path):
'''
Splits the argument into its constituent directories and returns them as
a list.
'''
def recurse_path(path,retlist):
if len(retlist) > 100:
fullpath = os.path.join(*([ path, ] + retlist))
print("Directory '{}' contains too many levels".format(fullpath))
exit(1)
head, tail = os.path.split(path)
if len(tail) > 0:
retlist.insert(0,tail)
recurse_path(head,retlist)
elif len(head) > 1:
recurse_path(head,retlist)
else:
return
retlist = []
path = os.path.realpath(os.path.normpath(path))
drive, path = os.path.splitdrive(path)
if len(drive) > 0: retlist.append(drive)
recurse_path(path,retlist)
return retlist | python | def split_path(path):
'''
Splits the argument into its constituent directories and returns them as
a list.
'''
def recurse_path(path,retlist):
if len(retlist) > 100:
fullpath = os.path.join(*([ path, ] + retlist))
print("Directory '{}' contains too many levels".format(fullpath))
exit(1)
head, tail = os.path.split(path)
if len(tail) > 0:
retlist.insert(0,tail)
recurse_path(head,retlist)
elif len(head) > 1:
recurse_path(head,retlist)
else:
return
retlist = []
path = os.path.realpath(os.path.normpath(path))
drive, path = os.path.splitdrive(path)
if len(drive) > 0: retlist.append(drive)
recurse_path(path,retlist)
return retlist | [
"def",
"split_path",
"(",
"path",
")",
":",
"def",
"recurse_path",
"(",
"path",
",",
"retlist",
")",
":",
"if",
"len",
"(",
"retlist",
")",
">",
"100",
":",
"fullpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"*",
"(",
"[",
"path",
",",
"]",
"+",
"retlist",
")",
")",
"print",
"(",
"\"Directory '{}' contains too many levels\"",
".",
"format",
"(",
"fullpath",
")",
")",
"exit",
"(",
"1",
")",
"head",
",",
"tail",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"if",
"len",
"(",
"tail",
")",
">",
"0",
":",
"retlist",
".",
"insert",
"(",
"0",
",",
"tail",
")",
"recurse_path",
"(",
"head",
",",
"retlist",
")",
"elif",
"len",
"(",
"head",
")",
">",
"1",
":",
"recurse_path",
"(",
"head",
",",
"retlist",
")",
"else",
":",
"return",
"retlist",
"=",
"[",
"]",
"path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"normpath",
"(",
"path",
")",
")",
"drive",
",",
"path",
"=",
"os",
".",
"path",
".",
"splitdrive",
"(",
"path",
")",
"if",
"len",
"(",
"drive",
")",
">",
"0",
":",
"retlist",
".",
"append",
"(",
"drive",
")",
"recurse_path",
"(",
"path",
",",
"retlist",
")",
"return",
"retlist"
] | Splits the argument into its constituent directories and returns them as
a list. | [
"Splits",
"the",
"argument",
"into",
"its",
"constituent",
"directories",
"and",
"returns",
"them",
"as",
"a",
"list",
"."
] | d46a44eae20d99205292c31785f936fbed47070f | https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/utils.py#L143-L167 | train | 232,855 |
Fortran-FOSS-Programmers/ford | ford/utils.py | sub_macros | def sub_macros(string,base_url):
'''
Replaces macros in documentation with their appropriate values. These macros
are used for things like providing URLs.
'''
macros = { '|url|': base_url,
'|media|': os.path.join(base_url,'media'),
'|page|': os.path.join(base_url,'page')
}
for key, val in macros.items():
string = string.replace(key,val)
return string | python | def sub_macros(string,base_url):
'''
Replaces macros in documentation with their appropriate values. These macros
are used for things like providing URLs.
'''
macros = { '|url|': base_url,
'|media|': os.path.join(base_url,'media'),
'|page|': os.path.join(base_url,'page')
}
for key, val in macros.items():
string = string.replace(key,val)
return string | [
"def",
"sub_macros",
"(",
"string",
",",
"base_url",
")",
":",
"macros",
"=",
"{",
"'|url|'",
":",
"base_url",
",",
"'|media|'",
":",
"os",
".",
"path",
".",
"join",
"(",
"base_url",
",",
"'media'",
")",
",",
"'|page|'",
":",
"os",
".",
"path",
".",
"join",
"(",
"base_url",
",",
"'page'",
")",
"}",
"for",
"key",
",",
"val",
"in",
"macros",
".",
"items",
"(",
")",
":",
"string",
"=",
"string",
".",
"replace",
"(",
"key",
",",
"val",
")",
"return",
"string"
] | Replaces macros in documentation with their appropriate values. These macros
are used for things like providing URLs. | [
"Replaces",
"macros",
"in",
"documentation",
"with",
"their",
"appropriate",
"values",
".",
"These",
"macros",
"are",
"used",
"for",
"things",
"like",
"providing",
"URLs",
"."
] | d46a44eae20d99205292c31785f936fbed47070f | https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/utils.py#L279-L290 | train | 232,856 |
Fortran-FOSS-Programmers/ford | ford/output.py | copytree | def copytree(src, dst):
"""Replaces shutil.copytree to avoid problems on certain file systems.
shutil.copytree() and shutil.copystat() invoke os.setxattr(), which seems
to fail when called for directories on at least one NFS file system.
The current routine is a simple replacement, which should be good enough for
Ford.
"""
def touch(path):
now = time.time()
try:
# assume it's there
os.utime(path, (now, now))
except os.error:
# if it isn't, try creating the directory,
# a file with that name
os.makedirs(os.path.dirname(path))
open(path, "w").close()
os.utime(path, (now, now))
for root, dirs, files in os.walk(src):
relsrcdir = os.path.relpath(root, src)
dstdir = os.path.join(dst, relsrcdir)
if not os.path.exists(dstdir):
try:
os.makedirs(dstdir)
except OSError as ex:
if ex.errno != errno.EEXIST:
raise
for ff in files:
shutil.copy(os.path.join(root, ff), os.path.join(dstdir, ff))
touch(os.path.join(dstdir, ff)) | python | def copytree(src, dst):
"""Replaces shutil.copytree to avoid problems on certain file systems.
shutil.copytree() and shutil.copystat() invoke os.setxattr(), which seems
to fail when called for directories on at least one NFS file system.
The current routine is a simple replacement, which should be good enough for
Ford.
"""
def touch(path):
now = time.time()
try:
# assume it's there
os.utime(path, (now, now))
except os.error:
# if it isn't, try creating the directory,
# a file with that name
os.makedirs(os.path.dirname(path))
open(path, "w").close()
os.utime(path, (now, now))
for root, dirs, files in os.walk(src):
relsrcdir = os.path.relpath(root, src)
dstdir = os.path.join(dst, relsrcdir)
if not os.path.exists(dstdir):
try:
os.makedirs(dstdir)
except OSError as ex:
if ex.errno != errno.EEXIST:
raise
for ff in files:
shutil.copy(os.path.join(root, ff), os.path.join(dstdir, ff))
touch(os.path.join(dstdir, ff)) | [
"def",
"copytree",
"(",
"src",
",",
"dst",
")",
":",
"def",
"touch",
"(",
"path",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"try",
":",
"# assume it's there",
"os",
".",
"utime",
"(",
"path",
",",
"(",
"now",
",",
"now",
")",
")",
"except",
"os",
".",
"error",
":",
"# if it isn't, try creating the directory,",
"# a file with that name",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
")",
"open",
"(",
"path",
",",
"\"w\"",
")",
".",
"close",
"(",
")",
"os",
".",
"utime",
"(",
"path",
",",
"(",
"now",
",",
"now",
")",
")",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"src",
")",
":",
"relsrcdir",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"root",
",",
"src",
")",
"dstdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dst",
",",
"relsrcdir",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dstdir",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"dstdir",
")",
"except",
"OSError",
"as",
"ex",
":",
"if",
"ex",
".",
"errno",
"!=",
"errno",
".",
"EEXIST",
":",
"raise",
"for",
"ff",
"in",
"files",
":",
"shutil",
".",
"copy",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"ff",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"dstdir",
",",
"ff",
")",
")",
"touch",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dstdir",
",",
"ff",
")",
")"
] | Replaces shutil.copytree to avoid problems on certain file systems.
shutil.copytree() and shutil.copystat() invoke os.setxattr(), which seems
to fail when called for directories on at least one NFS file system.
The current routine is a simple replacement, which should be good enough for
Ford. | [
"Replaces",
"shutil",
".",
"copytree",
"to",
"avoid",
"problems",
"on",
"certain",
"file",
"systems",
"."
] | d46a44eae20d99205292c31785f936fbed47070f | https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/output.py#L520-L551 | train | 232,857 |
gem/oq-engine | openquake/calculators/export/hazard.py | export_hmaps_csv | def export_hmaps_csv(key, dest, sitemesh, array, comment):
"""
Export the hazard maps of the given realization into CSV.
:param key: output_type and export_type
:param dest: name of the exported file
:param sitemesh: site collection
:param array: a composite array of dtype hmap_dt
:param comment: comment to use as header of the exported CSV file
"""
curves = util.compose_arrays(sitemesh, array)
writers.write_csv(dest, curves, comment=comment)
return [dest] | python | def export_hmaps_csv(key, dest, sitemesh, array, comment):
"""
Export the hazard maps of the given realization into CSV.
:param key: output_type and export_type
:param dest: name of the exported file
:param sitemesh: site collection
:param array: a composite array of dtype hmap_dt
:param comment: comment to use as header of the exported CSV file
"""
curves = util.compose_arrays(sitemesh, array)
writers.write_csv(dest, curves, comment=comment)
return [dest] | [
"def",
"export_hmaps_csv",
"(",
"key",
",",
"dest",
",",
"sitemesh",
",",
"array",
",",
"comment",
")",
":",
"curves",
"=",
"util",
".",
"compose_arrays",
"(",
"sitemesh",
",",
"array",
")",
"writers",
".",
"write_csv",
"(",
"dest",
",",
"curves",
",",
"comment",
"=",
"comment",
")",
"return",
"[",
"dest",
"]"
] | Export the hazard maps of the given realization into CSV.
:param key: output_type and export_type
:param dest: name of the exported file
:param sitemesh: site collection
:param array: a composite array of dtype hmap_dt
:param comment: comment to use as header of the exported CSV file | [
"Export",
"the",
"hazard",
"maps",
"of",
"the",
"given",
"realization",
"into",
"CSV",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L223-L235 | train | 232,858 |
gem/oq-engine | openquake/calculators/export/hazard.py | export_hcurves_by_imt_csv | def export_hcurves_by_imt_csv(
key, kind, rlzs_assoc, fname, sitecol, array, oq, checksum):
"""
Export the curves of the given realization into CSV.
:param key: output_type and export_type
:param kind: a string with the kind of output (realization or statistics)
:param rlzs_assoc: a :class:`openquake.commonlib.source.RlzsAssoc` instance
:param fname: name of the exported file
:param sitecol: site collection
:param array: an array of shape (N, L) and dtype numpy.float32
:param oq: job.ini parameters
"""
nsites = len(sitecol)
fnames = []
for imt, imls in oq.imtls.items():
slc = oq.imtls(imt)
dest = add_imt(fname, imt)
lst = [('lon', F32), ('lat', F32), ('depth', F32)]
for iml in imls:
lst.append(('poe-%s' % iml, F32))
hcurves = numpy.zeros(nsites, lst)
for sid, lon, lat, dep in zip(
range(nsites), sitecol.lons, sitecol.lats, sitecol.depths):
hcurves[sid] = (lon, lat, dep) + tuple(array[sid, slc])
fnames.append(writers.write_csv(dest, hcurves, comment=_comment(
rlzs_assoc, kind, oq.investigation_time) + (
', imt="%s", checksum=%d' % (imt, checksum)
), header=[name for (name, dt) in lst]))
return fnames | python | def export_hcurves_by_imt_csv(
key, kind, rlzs_assoc, fname, sitecol, array, oq, checksum):
"""
Export the curves of the given realization into CSV.
:param key: output_type and export_type
:param kind: a string with the kind of output (realization or statistics)
:param rlzs_assoc: a :class:`openquake.commonlib.source.RlzsAssoc` instance
:param fname: name of the exported file
:param sitecol: site collection
:param array: an array of shape (N, L) and dtype numpy.float32
:param oq: job.ini parameters
"""
nsites = len(sitecol)
fnames = []
for imt, imls in oq.imtls.items():
slc = oq.imtls(imt)
dest = add_imt(fname, imt)
lst = [('lon', F32), ('lat', F32), ('depth', F32)]
for iml in imls:
lst.append(('poe-%s' % iml, F32))
hcurves = numpy.zeros(nsites, lst)
for sid, lon, lat, dep in zip(
range(nsites), sitecol.lons, sitecol.lats, sitecol.depths):
hcurves[sid] = (lon, lat, dep) + tuple(array[sid, slc])
fnames.append(writers.write_csv(dest, hcurves, comment=_comment(
rlzs_assoc, kind, oq.investigation_time) + (
', imt="%s", checksum=%d' % (imt, checksum)
), header=[name for (name, dt) in lst]))
return fnames | [
"def",
"export_hcurves_by_imt_csv",
"(",
"key",
",",
"kind",
",",
"rlzs_assoc",
",",
"fname",
",",
"sitecol",
",",
"array",
",",
"oq",
",",
"checksum",
")",
":",
"nsites",
"=",
"len",
"(",
"sitecol",
")",
"fnames",
"=",
"[",
"]",
"for",
"imt",
",",
"imls",
"in",
"oq",
".",
"imtls",
".",
"items",
"(",
")",
":",
"slc",
"=",
"oq",
".",
"imtls",
"(",
"imt",
")",
"dest",
"=",
"add_imt",
"(",
"fname",
",",
"imt",
")",
"lst",
"=",
"[",
"(",
"'lon'",
",",
"F32",
")",
",",
"(",
"'lat'",
",",
"F32",
")",
",",
"(",
"'depth'",
",",
"F32",
")",
"]",
"for",
"iml",
"in",
"imls",
":",
"lst",
".",
"append",
"(",
"(",
"'poe-%s'",
"%",
"iml",
",",
"F32",
")",
")",
"hcurves",
"=",
"numpy",
".",
"zeros",
"(",
"nsites",
",",
"lst",
")",
"for",
"sid",
",",
"lon",
",",
"lat",
",",
"dep",
"in",
"zip",
"(",
"range",
"(",
"nsites",
")",
",",
"sitecol",
".",
"lons",
",",
"sitecol",
".",
"lats",
",",
"sitecol",
".",
"depths",
")",
":",
"hcurves",
"[",
"sid",
"]",
"=",
"(",
"lon",
",",
"lat",
",",
"dep",
")",
"+",
"tuple",
"(",
"array",
"[",
"sid",
",",
"slc",
"]",
")",
"fnames",
".",
"append",
"(",
"writers",
".",
"write_csv",
"(",
"dest",
",",
"hcurves",
",",
"comment",
"=",
"_comment",
"(",
"rlzs_assoc",
",",
"kind",
",",
"oq",
".",
"investigation_time",
")",
"+",
"(",
"', imt=\"%s\", checksum=%d'",
"%",
"(",
"imt",
",",
"checksum",
")",
")",
",",
"header",
"=",
"[",
"name",
"for",
"(",
"name",
",",
"dt",
")",
"in",
"lst",
"]",
")",
")",
"return",
"fnames"
] | Export the curves of the given realization into CSV.
:param key: output_type and export_type
:param kind: a string with the kind of output (realization or statistics)
:param rlzs_assoc: a :class:`openquake.commonlib.source.RlzsAssoc` instance
:param fname: name of the exported file
:param sitecol: site collection
:param array: an array of shape (N, L) and dtype numpy.float32
:param oq: job.ini parameters | [
"Export",
"the",
"curves",
"of",
"the",
"given",
"realization",
"into",
"CSV",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L248-L277 | train | 232,859 |
gem/oq-engine | openquake/calculators/export/hazard.py | export_hcurves_csv | def export_hcurves_csv(ekey, dstore):
"""
Exports the hazard curves into several .csv files
:param ekey: export key, i.e. a pair (datastore key, fmt)
:param dstore: datastore object
"""
oq = dstore['oqparam']
info = get_info(dstore)
rlzs_assoc = dstore['csm_info'].get_rlzs_assoc()
R = len(rlzs_assoc.realizations)
sitecol = dstore['sitecol']
sitemesh = get_mesh(sitecol)
key, kind, fmt = get_kkf(ekey)
fnames = []
checksum = dstore.get_attr('/', 'checksum32')
hmap_dt = oq.hmap_dt()
for kind in oq.get_kinds(kind, R):
fname = hazard_curve_name(dstore, (key, fmt), kind, rlzs_assoc)
comment = _comment(rlzs_assoc, kind, oq.investigation_time)
if (key in ('hmaps', 'uhs') and oq.uniform_hazard_spectra or
oq.hazard_maps):
hmap = extract(dstore, 'hmaps?kind=' + kind)[kind]
if key == 'uhs' and oq.poes and oq.uniform_hazard_spectra:
uhs_curves = calc.make_uhs(hmap, info)
writers.write_csv(
fname, util.compose_arrays(sitemesh, uhs_curves),
comment=comment + ', checksum=%d' % checksum)
fnames.append(fname)
elif key == 'hmaps' and oq.poes and oq.hazard_maps:
fnames.extend(
export_hmaps_csv(ekey, fname, sitemesh,
hmap.flatten().view(hmap_dt),
comment + ', checksum=%d' % checksum))
elif key == 'hcurves':
hcurves = extract(dstore, 'hcurves?kind=' + kind)[kind]
fnames.extend(
export_hcurves_by_imt_csv(
ekey, kind, rlzs_assoc, fname, sitecol, hcurves, oq,
checksum))
return sorted(fnames) | python | def export_hcurves_csv(ekey, dstore):
"""
Exports the hazard curves into several .csv files
:param ekey: export key, i.e. a pair (datastore key, fmt)
:param dstore: datastore object
"""
oq = dstore['oqparam']
info = get_info(dstore)
rlzs_assoc = dstore['csm_info'].get_rlzs_assoc()
R = len(rlzs_assoc.realizations)
sitecol = dstore['sitecol']
sitemesh = get_mesh(sitecol)
key, kind, fmt = get_kkf(ekey)
fnames = []
checksum = dstore.get_attr('/', 'checksum32')
hmap_dt = oq.hmap_dt()
for kind in oq.get_kinds(kind, R):
fname = hazard_curve_name(dstore, (key, fmt), kind, rlzs_assoc)
comment = _comment(rlzs_assoc, kind, oq.investigation_time)
if (key in ('hmaps', 'uhs') and oq.uniform_hazard_spectra or
oq.hazard_maps):
hmap = extract(dstore, 'hmaps?kind=' + kind)[kind]
if key == 'uhs' and oq.poes and oq.uniform_hazard_spectra:
uhs_curves = calc.make_uhs(hmap, info)
writers.write_csv(
fname, util.compose_arrays(sitemesh, uhs_curves),
comment=comment + ', checksum=%d' % checksum)
fnames.append(fname)
elif key == 'hmaps' and oq.poes and oq.hazard_maps:
fnames.extend(
export_hmaps_csv(ekey, fname, sitemesh,
hmap.flatten().view(hmap_dt),
comment + ', checksum=%d' % checksum))
elif key == 'hcurves':
hcurves = extract(dstore, 'hcurves?kind=' + kind)[kind]
fnames.extend(
export_hcurves_by_imt_csv(
ekey, kind, rlzs_assoc, fname, sitecol, hcurves, oq,
checksum))
return sorted(fnames) | [
"def",
"export_hcurves_csv",
"(",
"ekey",
",",
"dstore",
")",
":",
"oq",
"=",
"dstore",
"[",
"'oqparam'",
"]",
"info",
"=",
"get_info",
"(",
"dstore",
")",
"rlzs_assoc",
"=",
"dstore",
"[",
"'csm_info'",
"]",
".",
"get_rlzs_assoc",
"(",
")",
"R",
"=",
"len",
"(",
"rlzs_assoc",
".",
"realizations",
")",
"sitecol",
"=",
"dstore",
"[",
"'sitecol'",
"]",
"sitemesh",
"=",
"get_mesh",
"(",
"sitecol",
")",
"key",
",",
"kind",
",",
"fmt",
"=",
"get_kkf",
"(",
"ekey",
")",
"fnames",
"=",
"[",
"]",
"checksum",
"=",
"dstore",
".",
"get_attr",
"(",
"'/'",
",",
"'checksum32'",
")",
"hmap_dt",
"=",
"oq",
".",
"hmap_dt",
"(",
")",
"for",
"kind",
"in",
"oq",
".",
"get_kinds",
"(",
"kind",
",",
"R",
")",
":",
"fname",
"=",
"hazard_curve_name",
"(",
"dstore",
",",
"(",
"key",
",",
"fmt",
")",
",",
"kind",
",",
"rlzs_assoc",
")",
"comment",
"=",
"_comment",
"(",
"rlzs_assoc",
",",
"kind",
",",
"oq",
".",
"investigation_time",
")",
"if",
"(",
"key",
"in",
"(",
"'hmaps'",
",",
"'uhs'",
")",
"and",
"oq",
".",
"uniform_hazard_spectra",
"or",
"oq",
".",
"hazard_maps",
")",
":",
"hmap",
"=",
"extract",
"(",
"dstore",
",",
"'hmaps?kind='",
"+",
"kind",
")",
"[",
"kind",
"]",
"if",
"key",
"==",
"'uhs'",
"and",
"oq",
".",
"poes",
"and",
"oq",
".",
"uniform_hazard_spectra",
":",
"uhs_curves",
"=",
"calc",
".",
"make_uhs",
"(",
"hmap",
",",
"info",
")",
"writers",
".",
"write_csv",
"(",
"fname",
",",
"util",
".",
"compose_arrays",
"(",
"sitemesh",
",",
"uhs_curves",
")",
",",
"comment",
"=",
"comment",
"+",
"', checksum=%d'",
"%",
"checksum",
")",
"fnames",
".",
"append",
"(",
"fname",
")",
"elif",
"key",
"==",
"'hmaps'",
"and",
"oq",
".",
"poes",
"and",
"oq",
".",
"hazard_maps",
":",
"fnames",
".",
"extend",
"(",
"export_hmaps_csv",
"(",
"ekey",
",",
"fname",
",",
"sitemesh",
",",
"hmap",
".",
"flatten",
"(",
")",
".",
"view",
"(",
"hmap_dt",
")",
",",
"comment",
"+",
"', checksum=%d'",
"%",
"checksum",
")",
")",
"elif",
"key",
"==",
"'hcurves'",
":",
"hcurves",
"=",
"extract",
"(",
"dstore",
",",
"'hcurves?kind='",
"+",
"kind",
")",
"[",
"kind",
"]",
"fnames",
".",
"extend",
"(",
"export_hcurves_by_imt_csv",
"(",
"ekey",
",",
"kind",
",",
"rlzs_assoc",
",",
"fname",
",",
"sitecol",
",",
"hcurves",
",",
"oq",
",",
"checksum",
")",
")",
"return",
"sorted",
"(",
"fnames",
")"
] | Exports the hazard curves into several .csv files
:param ekey: export key, i.e. a pair (datastore key, fmt)
:param dstore: datastore object | [
"Exports",
"the",
"hazard",
"curves",
"into",
"several",
".",
"csv",
"files"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L333-L373 | train | 232,860 |
gem/oq-engine | openquake/calculators/export/hazard.py | save_disagg_to_csv | def save_disagg_to_csv(metadata, matrices):
"""
Save disaggregation matrices to multiple .csv files.
"""
skip_keys = ('Mag', 'Dist', 'Lon', 'Lat', 'Eps', 'TRT')
base_header = ','.join(
'%s=%s' % (key, value) for key, value in metadata.items()
if value is not None and key not in skip_keys)
for disag_tup, (poe, iml, matrix, fname) in matrices.items():
header = '%s,poe=%.7f,iml=%.7e\n' % (base_header, poe, iml)
if disag_tup == ('Mag', 'Lon', 'Lat'):
matrix = numpy.swapaxes(matrix, 0, 1)
matrix = numpy.swapaxes(matrix, 1, 2)
disag_tup = ('Lon', 'Lat', 'Mag')
axis = [metadata[v] for v in disag_tup]
header += ','.join(v for v in disag_tup)
header += ',poe'
# compute axis mid points
axis = [(ax[: -1] + ax[1:]) / 2. if ax.dtype == float
else ax for ax in axis]
values = None
if len(axis) == 1:
values = numpy.array([axis[0], matrix.flatten()]).T
else:
grids = numpy.meshgrid(*axis, indexing='ij')
values = [g.flatten() for g in grids]
values.append(matrix.flatten())
values = numpy.array(values).T
writers.write_csv(fname, values, comment=header, fmt='%.5E') | python | def save_disagg_to_csv(metadata, matrices):
"""
Save disaggregation matrices to multiple .csv files.
"""
skip_keys = ('Mag', 'Dist', 'Lon', 'Lat', 'Eps', 'TRT')
base_header = ','.join(
'%s=%s' % (key, value) for key, value in metadata.items()
if value is not None and key not in skip_keys)
for disag_tup, (poe, iml, matrix, fname) in matrices.items():
header = '%s,poe=%.7f,iml=%.7e\n' % (base_header, poe, iml)
if disag_tup == ('Mag', 'Lon', 'Lat'):
matrix = numpy.swapaxes(matrix, 0, 1)
matrix = numpy.swapaxes(matrix, 1, 2)
disag_tup = ('Lon', 'Lat', 'Mag')
axis = [metadata[v] for v in disag_tup]
header += ','.join(v for v in disag_tup)
header += ',poe'
# compute axis mid points
axis = [(ax[: -1] + ax[1:]) / 2. if ax.dtype == float
else ax for ax in axis]
values = None
if len(axis) == 1:
values = numpy.array([axis[0], matrix.flatten()]).T
else:
grids = numpy.meshgrid(*axis, indexing='ij')
values = [g.flatten() for g in grids]
values.append(matrix.flatten())
values = numpy.array(values).T
writers.write_csv(fname, values, comment=header, fmt='%.5E') | [
"def",
"save_disagg_to_csv",
"(",
"metadata",
",",
"matrices",
")",
":",
"skip_keys",
"=",
"(",
"'Mag'",
",",
"'Dist'",
",",
"'Lon'",
",",
"'Lat'",
",",
"'Eps'",
",",
"'TRT'",
")",
"base_header",
"=",
"','",
".",
"join",
"(",
"'%s=%s'",
"%",
"(",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"metadata",
".",
"items",
"(",
")",
"if",
"value",
"is",
"not",
"None",
"and",
"key",
"not",
"in",
"skip_keys",
")",
"for",
"disag_tup",
",",
"(",
"poe",
",",
"iml",
",",
"matrix",
",",
"fname",
")",
"in",
"matrices",
".",
"items",
"(",
")",
":",
"header",
"=",
"'%s,poe=%.7f,iml=%.7e\\n'",
"%",
"(",
"base_header",
",",
"poe",
",",
"iml",
")",
"if",
"disag_tup",
"==",
"(",
"'Mag'",
",",
"'Lon'",
",",
"'Lat'",
")",
":",
"matrix",
"=",
"numpy",
".",
"swapaxes",
"(",
"matrix",
",",
"0",
",",
"1",
")",
"matrix",
"=",
"numpy",
".",
"swapaxes",
"(",
"matrix",
",",
"1",
",",
"2",
")",
"disag_tup",
"=",
"(",
"'Lon'",
",",
"'Lat'",
",",
"'Mag'",
")",
"axis",
"=",
"[",
"metadata",
"[",
"v",
"]",
"for",
"v",
"in",
"disag_tup",
"]",
"header",
"+=",
"','",
".",
"join",
"(",
"v",
"for",
"v",
"in",
"disag_tup",
")",
"header",
"+=",
"',poe'",
"# compute axis mid points",
"axis",
"=",
"[",
"(",
"ax",
"[",
":",
"-",
"1",
"]",
"+",
"ax",
"[",
"1",
":",
"]",
")",
"/",
"2.",
"if",
"ax",
".",
"dtype",
"==",
"float",
"else",
"ax",
"for",
"ax",
"in",
"axis",
"]",
"values",
"=",
"None",
"if",
"len",
"(",
"axis",
")",
"==",
"1",
":",
"values",
"=",
"numpy",
".",
"array",
"(",
"[",
"axis",
"[",
"0",
"]",
",",
"matrix",
".",
"flatten",
"(",
")",
"]",
")",
".",
"T",
"else",
":",
"grids",
"=",
"numpy",
".",
"meshgrid",
"(",
"*",
"axis",
",",
"indexing",
"=",
"'ij'",
")",
"values",
"=",
"[",
"g",
".",
"flatten",
"(",
")",
"for",
"g",
"in",
"grids",
"]",
"values",
".",
"append",
"(",
"matrix",
".",
"flatten",
"(",
")",
")",
"values",
"=",
"numpy",
".",
"array",
"(",
"values",
")",
".",
"T",
"writers",
".",
"write_csv",
"(",
"fname",
",",
"values",
",",
"comment",
"=",
"header",
",",
"fmt",
"=",
"'%.5E'",
")"
] | Save disaggregation matrices to multiple .csv files. | [
"Save",
"disaggregation",
"matrices",
"to",
"multiple",
".",
"csv",
"files",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L743-L776 | train | 232,861 |
gem/oq-engine | openquake/hazardlib/gsim/bradley_2013b.py | Bradley2013bChchCBD._interp_function | def _interp_function(self, y_ip1, y_i, t_ip1, t_i, imt_per):
"""
Generic interpolation function used in equation 19 of 2013 report.
"""
return y_i + (y_ip1 - y_i) / (t_ip1 - t_i) * (imt_per - t_i) | python | def _interp_function(self, y_ip1, y_i, t_ip1, t_i, imt_per):
"""
Generic interpolation function used in equation 19 of 2013 report.
"""
return y_i + (y_ip1 - y_i) / (t_ip1 - t_i) * (imt_per - t_i) | [
"def",
"_interp_function",
"(",
"self",
",",
"y_ip1",
",",
"y_i",
",",
"t_ip1",
",",
"t_i",
",",
"imt_per",
")",
":",
"return",
"y_i",
"+",
"(",
"y_ip1",
"-",
"y_i",
")",
"/",
"(",
"t_ip1",
"-",
"t_i",
")",
"*",
"(",
"imt_per",
"-",
"t_i",
")"
] | Generic interpolation function used in equation 19 of 2013 report. | [
"Generic",
"interpolation",
"function",
"used",
"in",
"equation",
"19",
"of",
"2013",
"report",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L154-L158 | train | 232,862 |
gem/oq-engine | openquake/hazardlib/gsim/bradley_2013b.py | Bradley2013bChchCBD._get_SRF_tau | def _get_SRF_tau(self, imt_per):
"""
Table 6 and equation 19 of 2013 report.
"""
if imt_per < 1:
srf = 0.87
elif 1 <= imt_per < 5:
srf = self._interp_function(0.58, 0.87, 5, 1, imt_per)
elif 5 <= imt_per <= 10:
srf = 0.58
else:
srf = 1
return srf | python | def _get_SRF_tau(self, imt_per):
"""
Table 6 and equation 19 of 2013 report.
"""
if imt_per < 1:
srf = 0.87
elif 1 <= imt_per < 5:
srf = self._interp_function(0.58, 0.87, 5, 1, imt_per)
elif 5 <= imt_per <= 10:
srf = 0.58
else:
srf = 1
return srf | [
"def",
"_get_SRF_tau",
"(",
"self",
",",
"imt_per",
")",
":",
"if",
"imt_per",
"<",
"1",
":",
"srf",
"=",
"0.87",
"elif",
"1",
"<=",
"imt_per",
"<",
"5",
":",
"srf",
"=",
"self",
".",
"_interp_function",
"(",
"0.58",
",",
"0.87",
",",
"5",
",",
"1",
",",
"imt_per",
")",
"elif",
"5",
"<=",
"imt_per",
"<=",
"10",
":",
"srf",
"=",
"0.58",
"else",
":",
"srf",
"=",
"1",
"return",
"srf"
] | Table 6 and equation 19 of 2013 report. | [
"Table",
"6",
"and",
"equation",
"19",
"of",
"2013",
"report",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L160-L173 | train | 232,863 |
gem/oq-engine | openquake/hazardlib/gsim/bradley_2013b.py | Bradley2013bChchCBD._get_SRF_phi | def _get_SRF_phi(self, imt_per):
"""
Table 7 and equation 19 of 2013 report. NB change in notation,
2013 report calls this term 'sigma' but it is referred to here
as phi.
"""
if imt_per < 0.6:
srf = 0.8
elif 0.6 <= imt_per < 1:
srf = self._interp_function(0.7, 0.8, 1, 0.6, imt_per)
elif 1 <= imt_per <= 10:
srf = self._interp_function(0.6, 0.7, 10, 1, imt_per)
else:
srf = 1
return srf | python | def _get_SRF_phi(self, imt_per):
"""
Table 7 and equation 19 of 2013 report. NB change in notation,
2013 report calls this term 'sigma' but it is referred to here
as phi.
"""
if imt_per < 0.6:
srf = 0.8
elif 0.6 <= imt_per < 1:
srf = self._interp_function(0.7, 0.8, 1, 0.6, imt_per)
elif 1 <= imt_per <= 10:
srf = self._interp_function(0.6, 0.7, 10, 1, imt_per)
else:
srf = 1
return srf | [
"def",
"_get_SRF_phi",
"(",
"self",
",",
"imt_per",
")",
":",
"if",
"imt_per",
"<",
"0.6",
":",
"srf",
"=",
"0.8",
"elif",
"0.6",
"<=",
"imt_per",
"<",
"1",
":",
"srf",
"=",
"self",
".",
"_interp_function",
"(",
"0.7",
",",
"0.8",
",",
"1",
",",
"0.6",
",",
"imt_per",
")",
"elif",
"1",
"<=",
"imt_per",
"<=",
"10",
":",
"srf",
"=",
"self",
".",
"_interp_function",
"(",
"0.6",
",",
"0.7",
",",
"10",
",",
"1",
",",
"imt_per",
")",
"else",
":",
"srf",
"=",
"1",
"return",
"srf"
] | Table 7 and equation 19 of 2013 report. NB change in notation,
2013 report calls this term 'sigma' but it is referred to here
as phi. | [
"Table",
"7",
"and",
"equation",
"19",
"of",
"2013",
"report",
".",
"NB",
"change",
"in",
"notation",
"2013",
"report",
"calls",
"this",
"term",
"sigma",
"but",
"it",
"is",
"referred",
"to",
"here",
"as",
"phi",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L175-L190 | train | 232,864 |
gem/oq-engine | openquake/hazardlib/gsim/bradley_2013b.py | Bradley2013bChchCBD._get_SRF_sigma | def _get_SRF_sigma(self, imt_per):
"""
Table 8 and equation 19 of 2013 report. NB change in notation,
2013 report calls this term 'sigma_t' but it is referred to
here as sigma. Note that Table 8 is identical to Table 7 in
the 2013 report.
"""
if imt_per < 0.6:
srf = 0.8
elif 0.6 <= imt_per < 1:
srf = self._interp_function(0.7, 0.8, 1, 0.6, imt_per)
elif 1 <= imt_per <= 10:
srf = self._interp_function(0.6, 0.7, 10, 1, imt_per)
else:
srf = 1
return srf | python | def _get_SRF_sigma(self, imt_per):
"""
Table 8 and equation 19 of 2013 report. NB change in notation,
2013 report calls this term 'sigma_t' but it is referred to
here as sigma. Note that Table 8 is identical to Table 7 in
the 2013 report.
"""
if imt_per < 0.6:
srf = 0.8
elif 0.6 <= imt_per < 1:
srf = self._interp_function(0.7, 0.8, 1, 0.6, imt_per)
elif 1 <= imt_per <= 10:
srf = self._interp_function(0.6, 0.7, 10, 1, imt_per)
else:
srf = 1
return srf | [
"def",
"_get_SRF_sigma",
"(",
"self",
",",
"imt_per",
")",
":",
"if",
"imt_per",
"<",
"0.6",
":",
"srf",
"=",
"0.8",
"elif",
"0.6",
"<=",
"imt_per",
"<",
"1",
":",
"srf",
"=",
"self",
".",
"_interp_function",
"(",
"0.7",
",",
"0.8",
",",
"1",
",",
"0.6",
",",
"imt_per",
")",
"elif",
"1",
"<=",
"imt_per",
"<=",
"10",
":",
"srf",
"=",
"self",
".",
"_interp_function",
"(",
"0.6",
",",
"0.7",
",",
"10",
",",
"1",
",",
"imt_per",
")",
"else",
":",
"srf",
"=",
"1",
"return",
"srf"
] | Table 8 and equation 19 of 2013 report. NB change in notation,
2013 report calls this term 'sigma_t' but it is referred to
here as sigma. Note that Table 8 is identical to Table 7 in
the 2013 report. | [
"Table",
"8",
"and",
"equation",
"19",
"of",
"2013",
"report",
".",
"NB",
"change",
"in",
"notation",
"2013",
"report",
"calls",
"this",
"term",
"sigma_t",
"but",
"it",
"is",
"referred",
"to",
"here",
"as",
"sigma",
".",
"Note",
"that",
"Table",
"8",
"is",
"identical",
"to",
"Table",
"7",
"in",
"the",
"2013",
"report",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L192-L208 | train | 232,865 |
gem/oq-engine | openquake/hazardlib/gsim/bradley_2013b.py | Bradley2013bChchCBD._get_dL2L | def _get_dL2L(self, imt_per):
"""
Table 3 and equation 19 of 2013 report.
"""
if imt_per < 0.18:
dL2L = -0.06
elif 0.18 <= imt_per < 0.35:
dL2L = self._interp_function(0.12, -0.06, 0.35, 0.18, imt_per)
elif 0.35 <= imt_per <= 10:
dL2L = self._interp_function(0.65, 0.12, 10, 0.35, imt_per)
else:
dL2L = 0
return dL2L | python | def _get_dL2L(self, imt_per):
"""
Table 3 and equation 19 of 2013 report.
"""
if imt_per < 0.18:
dL2L = -0.06
elif 0.18 <= imt_per < 0.35:
dL2L = self._interp_function(0.12, -0.06, 0.35, 0.18, imt_per)
elif 0.35 <= imt_per <= 10:
dL2L = self._interp_function(0.65, 0.12, 10, 0.35, imt_per)
else:
dL2L = 0
return dL2L | [
"def",
"_get_dL2L",
"(",
"self",
",",
"imt_per",
")",
":",
"if",
"imt_per",
"<",
"0.18",
":",
"dL2L",
"=",
"-",
"0.06",
"elif",
"0.18",
"<=",
"imt_per",
"<",
"0.35",
":",
"dL2L",
"=",
"self",
".",
"_interp_function",
"(",
"0.12",
",",
"-",
"0.06",
",",
"0.35",
",",
"0.18",
",",
"imt_per",
")",
"elif",
"0.35",
"<=",
"imt_per",
"<=",
"10",
":",
"dL2L",
"=",
"self",
".",
"_interp_function",
"(",
"0.65",
",",
"0.12",
",",
"10",
",",
"0.35",
",",
"imt_per",
")",
"else",
":",
"dL2L",
"=",
"0",
"return",
"dL2L"
] | Table 3 and equation 19 of 2013 report. | [
"Table",
"3",
"and",
"equation",
"19",
"of",
"2013",
"report",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L210-L223 | train | 232,866 |
gem/oq-engine | openquake/hazardlib/gsim/bradley_2013b.py | Bradley2013bChchCBD._get_dS2S | def _get_dS2S(self, imt_per):
"""
Table 4 of 2013 report
"""
if imt_per == 0:
dS2S = 0.05
elif 0 < imt_per < 0.15:
dS2S = self._interp_function(-0.15, 0.05, 0.15, 0, imt_per)
elif 0.15 <= imt_per < 0.45:
dS2S = self._interp_function(0.4, -0.15, 0.45, 0.15, imt_per)
elif 0.45 <= imt_per < 3.2:
dS2S = 0.4
elif 3.2 <= imt_per < 5:
dS2S = self._interp_function(0.08, 0.4, 5, 3.2, imt_per)
elif 5 <= imt_per <= 10:
dS2S = 0.08
else:
dS2S = 0
return dS2S | python | def _get_dS2S(self, imt_per):
"""
Table 4 of 2013 report
"""
if imt_per == 0:
dS2S = 0.05
elif 0 < imt_per < 0.15:
dS2S = self._interp_function(-0.15, 0.05, 0.15, 0, imt_per)
elif 0.15 <= imt_per < 0.45:
dS2S = self._interp_function(0.4, -0.15, 0.45, 0.15, imt_per)
elif 0.45 <= imt_per < 3.2:
dS2S = 0.4
elif 3.2 <= imt_per < 5:
dS2S = self._interp_function(0.08, 0.4, 5, 3.2, imt_per)
elif 5 <= imt_per <= 10:
dS2S = 0.08
else:
dS2S = 0
return dS2S | [
"def",
"_get_dS2S",
"(",
"self",
",",
"imt_per",
")",
":",
"if",
"imt_per",
"==",
"0",
":",
"dS2S",
"=",
"0.05",
"elif",
"0",
"<",
"imt_per",
"<",
"0.15",
":",
"dS2S",
"=",
"self",
".",
"_interp_function",
"(",
"-",
"0.15",
",",
"0.05",
",",
"0.15",
",",
"0",
",",
"imt_per",
")",
"elif",
"0.15",
"<=",
"imt_per",
"<",
"0.45",
":",
"dS2S",
"=",
"self",
".",
"_interp_function",
"(",
"0.4",
",",
"-",
"0.15",
",",
"0.45",
",",
"0.15",
",",
"imt_per",
")",
"elif",
"0.45",
"<=",
"imt_per",
"<",
"3.2",
":",
"dS2S",
"=",
"0.4",
"elif",
"3.2",
"<=",
"imt_per",
"<",
"5",
":",
"dS2S",
"=",
"self",
".",
"_interp_function",
"(",
"0.08",
",",
"0.4",
",",
"5",
",",
"3.2",
",",
"imt_per",
")",
"elif",
"5",
"<=",
"imt_per",
"<=",
"10",
":",
"dS2S",
"=",
"0.08",
"else",
":",
"dS2S",
"=",
"0",
"return",
"dS2S"
] | Table 4 of 2013 report | [
"Table",
"4",
"of",
"2013",
"report"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L225-L244 | train | 232,867 |
gem/oq-engine | openquake/hazardlib/calc/filters.py | context | def context(src):
"""
Used to add the source_id to the error message. To be used as
with context(src):
operation_with(src)
Typically the operation is filtering a source, that can fail for
tricky geometries.
"""
try:
yield
except Exception:
etype, err, tb = sys.exc_info()
msg = 'An error occurred with source id=%s. Error: %s'
msg %= (src.source_id, err)
raise_(etype, msg, tb) | python | def context(src):
"""
Used to add the source_id to the error message. To be used as
with context(src):
operation_with(src)
Typically the operation is filtering a source, that can fail for
tricky geometries.
"""
try:
yield
except Exception:
etype, err, tb = sys.exc_info()
msg = 'An error occurred with source id=%s. Error: %s'
msg %= (src.source_id, err)
raise_(etype, msg, tb) | [
"def",
"context",
"(",
"src",
")",
":",
"try",
":",
"yield",
"except",
"Exception",
":",
"etype",
",",
"err",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'An error occurred with source id=%s. Error: %s'",
"msg",
"%=",
"(",
"src",
".",
"source_id",
",",
"err",
")",
"raise_",
"(",
"etype",
",",
"msg",
",",
"tb",
")"
] | Used to add the source_id to the error message. To be used as
with context(src):
operation_with(src)
Typically the operation is filtering a source, that can fail for
tricky geometries. | [
"Used",
"to",
"add",
"the",
"source_id",
"to",
"the",
"error",
"message",
".",
"To",
"be",
"used",
"as"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L39-L55 | train | 232,868 |
gem/oq-engine | openquake/hazardlib/calc/filters.py | IntegrationDistance.get_bounding_box | def get_bounding_box(self, lon, lat, trt=None, mag=None):
"""
Build a bounding box around the given lon, lat by computing the
maximum_distance at the given tectonic region type and magnitude.
:param lon: longitude
:param lat: latitude
:param trt: tectonic region type, possibly None
:param mag: magnitude, possibly None
:returns: min_lon, min_lat, max_lon, max_lat
"""
if trt is None: # take the greatest integration distance
maxdist = max(self(trt, mag) for trt in self.dic)
else: # get the integration distance for the given TRT
maxdist = self(trt, mag)
a1 = min(maxdist * KM_TO_DEGREES, 90)
a2 = min(angular_distance(maxdist, lat), 180)
return lon - a2, lat - a1, lon + a2, lat + a1 | python | def get_bounding_box(self, lon, lat, trt=None, mag=None):
"""
Build a bounding box around the given lon, lat by computing the
maximum_distance at the given tectonic region type and magnitude.
:param lon: longitude
:param lat: latitude
:param trt: tectonic region type, possibly None
:param mag: magnitude, possibly None
:returns: min_lon, min_lat, max_lon, max_lat
"""
if trt is None: # take the greatest integration distance
maxdist = max(self(trt, mag) for trt in self.dic)
else: # get the integration distance for the given TRT
maxdist = self(trt, mag)
a1 = min(maxdist * KM_TO_DEGREES, 90)
a2 = min(angular_distance(maxdist, lat), 180)
return lon - a2, lat - a1, lon + a2, lat + a1 | [
"def",
"get_bounding_box",
"(",
"self",
",",
"lon",
",",
"lat",
",",
"trt",
"=",
"None",
",",
"mag",
"=",
"None",
")",
":",
"if",
"trt",
"is",
"None",
":",
"# take the greatest integration distance",
"maxdist",
"=",
"max",
"(",
"self",
"(",
"trt",
",",
"mag",
")",
"for",
"trt",
"in",
"self",
".",
"dic",
")",
"else",
":",
"# get the integration distance for the given TRT",
"maxdist",
"=",
"self",
"(",
"trt",
",",
"mag",
")",
"a1",
"=",
"min",
"(",
"maxdist",
"*",
"KM_TO_DEGREES",
",",
"90",
")",
"a2",
"=",
"min",
"(",
"angular_distance",
"(",
"maxdist",
",",
"lat",
")",
",",
"180",
")",
"return",
"lon",
"-",
"a2",
",",
"lat",
"-",
"a1",
",",
"lon",
"+",
"a2",
",",
"lat",
"+",
"a1"
] | Build a bounding box around the given lon, lat by computing the
maximum_distance at the given tectonic region type and magnitude.
:param lon: longitude
:param lat: latitude
:param trt: tectonic region type, possibly None
:param mag: magnitude, possibly None
:returns: min_lon, min_lat, max_lon, max_lat | [
"Build",
"a",
"bounding",
"box",
"around",
"the",
"given",
"lon",
"lat",
"by",
"computing",
"the",
"maximum_distance",
"at",
"the",
"given",
"tectonic",
"region",
"type",
"and",
"magnitude",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L138-L155 | train | 232,869 |
gem/oq-engine | openquake/hazardlib/calc/filters.py | IntegrationDistance.get_affected_box | def get_affected_box(self, src):
"""
Get the enlarged bounding box of a source.
:param src: a source object
:returns: a bounding box (min_lon, min_lat, max_lon, max_lat)
"""
mag = src.get_min_max_mag()[1]
maxdist = self(src.tectonic_region_type, mag)
bbox = get_bounding_box(src, maxdist)
return (fix_lon(bbox[0]), bbox[1], fix_lon(bbox[2]), bbox[3]) | python | def get_affected_box(self, src):
"""
Get the enlarged bounding box of a source.
:param src: a source object
:returns: a bounding box (min_lon, min_lat, max_lon, max_lat)
"""
mag = src.get_min_max_mag()[1]
maxdist = self(src.tectonic_region_type, mag)
bbox = get_bounding_box(src, maxdist)
return (fix_lon(bbox[0]), bbox[1], fix_lon(bbox[2]), bbox[3]) | [
"def",
"get_affected_box",
"(",
"self",
",",
"src",
")",
":",
"mag",
"=",
"src",
".",
"get_min_max_mag",
"(",
")",
"[",
"1",
"]",
"maxdist",
"=",
"self",
"(",
"src",
".",
"tectonic_region_type",
",",
"mag",
")",
"bbox",
"=",
"get_bounding_box",
"(",
"src",
",",
"maxdist",
")",
"return",
"(",
"fix_lon",
"(",
"bbox",
"[",
"0",
"]",
")",
",",
"bbox",
"[",
"1",
"]",
",",
"fix_lon",
"(",
"bbox",
"[",
"2",
"]",
")",
",",
"bbox",
"[",
"3",
"]",
")"
] | Get the enlarged bounding box of a source.
:param src: a source object
:returns: a bounding box (min_lon, min_lat, max_lon, max_lat) | [
"Get",
"the",
"enlarged",
"bounding",
"box",
"of",
"a",
"source",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L157-L167 | train | 232,870 |
gem/oq-engine | openquake/hazardlib/calc/filters.py | SourceFilter.sitecol | def sitecol(self):
"""
Read the site collection from .filename and cache it
"""
if 'sitecol' in vars(self):
return self.__dict__['sitecol']
if self.filename is None or not os.path.exists(self.filename):
# case of nofilter/None sitecol
return
with hdf5.File(self.filename, 'r') as h5:
self.__dict__['sitecol'] = sc = h5.get('sitecol')
return sc | python | def sitecol(self):
"""
Read the site collection from .filename and cache it
"""
if 'sitecol' in vars(self):
return self.__dict__['sitecol']
if self.filename is None or not os.path.exists(self.filename):
# case of nofilter/None sitecol
return
with hdf5.File(self.filename, 'r') as h5:
self.__dict__['sitecol'] = sc = h5.get('sitecol')
return sc | [
"def",
"sitecol",
"(",
"self",
")",
":",
"if",
"'sitecol'",
"in",
"vars",
"(",
"self",
")",
":",
"return",
"self",
".",
"__dict__",
"[",
"'sitecol'",
"]",
"if",
"self",
".",
"filename",
"is",
"None",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"filename",
")",
":",
"# case of nofilter/None sitecol",
"return",
"with",
"hdf5",
".",
"File",
"(",
"self",
".",
"filename",
",",
"'r'",
")",
"as",
"h5",
":",
"self",
".",
"__dict__",
"[",
"'sitecol'",
"]",
"=",
"sc",
"=",
"h5",
".",
"get",
"(",
"'sitecol'",
")",
"return",
"sc"
] | Read the site collection from .filename and cache it | [
"Read",
"the",
"site",
"collection",
"from",
".",
"filename",
"and",
"cache",
"it"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L276-L287 | train | 232,871 |
gem/oq-engine | openquake/hazardlib/geo/surface/simple_fault.py | SimpleFaultSurface.hypocentre_patch_index | def hypocentre_patch_index(cls, hypocentre, rupture_top_edge,
upper_seismogenic_depth,
lower_seismogenic_depth, dip):
"""
This methods finds the index of the fault patch including
the hypocentre.
:param hypocentre:
:class:`~openquake.hazardlib.geo.point.Point` object
representing the location of hypocentre.
:param rupture_top_edge:
A instances of :class:`openquake.hazardlib.geo.line.Line`
representing the rupture surface's top edge.
:param upper_seismo_depth:
Minimum depth ruptures can reach, in km (i.e. depth
to fault's top edge).
:param lower_seismo_depth:
Maximum depth ruptures can reach, in km (i.e. depth
to fault's bottom edge).
:param dip:
Dip angle (i.e. angle between fault surface
and earth surface), in degrees.
:return:
An integer corresponding to the index of the fault patch which
contains the hypocentre.
"""
totaln_patch = len(rupture_top_edge)
indexlist = []
dist_list = []
for i, index in enumerate(range(1, totaln_patch)):
p0, p1, p2, p3 = cls.get_fault_patch_vertices(
rupture_top_edge, upper_seismogenic_depth,
lower_seismogenic_depth, dip, index_patch=index)
[normal, dist_to_plane] = get_plane_equation(p0, p1, p2,
hypocentre)
indexlist.append(index)
dist_list.append(dist_to_plane)
if numpy.allclose(dist_to_plane, 0., atol=25., rtol=0.):
return index
break
index = indexlist[numpy.argmin(dist_list)]
return index | python | def hypocentre_patch_index(cls, hypocentre, rupture_top_edge,
upper_seismogenic_depth,
lower_seismogenic_depth, dip):
"""
This methods finds the index of the fault patch including
the hypocentre.
:param hypocentre:
:class:`~openquake.hazardlib.geo.point.Point` object
representing the location of hypocentre.
:param rupture_top_edge:
A instances of :class:`openquake.hazardlib.geo.line.Line`
representing the rupture surface's top edge.
:param upper_seismo_depth:
Minimum depth ruptures can reach, in km (i.e. depth
to fault's top edge).
:param lower_seismo_depth:
Maximum depth ruptures can reach, in km (i.e. depth
to fault's bottom edge).
:param dip:
Dip angle (i.e. angle between fault surface
and earth surface), in degrees.
:return:
An integer corresponding to the index of the fault patch which
contains the hypocentre.
"""
totaln_patch = len(rupture_top_edge)
indexlist = []
dist_list = []
for i, index in enumerate(range(1, totaln_patch)):
p0, p1, p2, p3 = cls.get_fault_patch_vertices(
rupture_top_edge, upper_seismogenic_depth,
lower_seismogenic_depth, dip, index_patch=index)
[normal, dist_to_plane] = get_plane_equation(p0, p1, p2,
hypocentre)
indexlist.append(index)
dist_list.append(dist_to_plane)
if numpy.allclose(dist_to_plane, 0., atol=25., rtol=0.):
return index
break
index = indexlist[numpy.argmin(dist_list)]
return index | [
"def",
"hypocentre_patch_index",
"(",
"cls",
",",
"hypocentre",
",",
"rupture_top_edge",
",",
"upper_seismogenic_depth",
",",
"lower_seismogenic_depth",
",",
"dip",
")",
":",
"totaln_patch",
"=",
"len",
"(",
"rupture_top_edge",
")",
"indexlist",
"=",
"[",
"]",
"dist_list",
"=",
"[",
"]",
"for",
"i",
",",
"index",
"in",
"enumerate",
"(",
"range",
"(",
"1",
",",
"totaln_patch",
")",
")",
":",
"p0",
",",
"p1",
",",
"p2",
",",
"p3",
"=",
"cls",
".",
"get_fault_patch_vertices",
"(",
"rupture_top_edge",
",",
"upper_seismogenic_depth",
",",
"lower_seismogenic_depth",
",",
"dip",
",",
"index_patch",
"=",
"index",
")",
"[",
"normal",
",",
"dist_to_plane",
"]",
"=",
"get_plane_equation",
"(",
"p0",
",",
"p1",
",",
"p2",
",",
"hypocentre",
")",
"indexlist",
".",
"append",
"(",
"index",
")",
"dist_list",
".",
"append",
"(",
"dist_to_plane",
")",
"if",
"numpy",
".",
"allclose",
"(",
"dist_to_plane",
",",
"0.",
",",
"atol",
"=",
"25.",
",",
"rtol",
"=",
"0.",
")",
":",
"return",
"index",
"break",
"index",
"=",
"indexlist",
"[",
"numpy",
".",
"argmin",
"(",
"dist_list",
")",
"]",
"return",
"index"
] | This methods finds the index of the fault patch including
the hypocentre.
:param hypocentre:
:class:`~openquake.hazardlib.geo.point.Point` object
representing the location of hypocentre.
:param rupture_top_edge:
A instances of :class:`openquake.hazardlib.geo.line.Line`
representing the rupture surface's top edge.
:param upper_seismo_depth:
Minimum depth ruptures can reach, in km (i.e. depth
to fault's top edge).
:param lower_seismo_depth:
Maximum depth ruptures can reach, in km (i.e. depth
to fault's bottom edge).
:param dip:
Dip angle (i.e. angle between fault surface
and earth surface), in degrees.
:return:
An integer corresponding to the index of the fault patch which
contains the hypocentre. | [
"This",
"methods",
"finds",
"the",
"index",
"of",
"the",
"fault",
"patch",
"including",
"the",
"hypocentre",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/simple_fault.py#L256-L298 | train | 232,872 |
gem/oq-engine | openquake/hazardlib/geo/surface/simple_fault.py | SimpleFaultSurface.get_surface_vertexes | def get_surface_vertexes(cls, fault_trace,
upper_seismogenic_depth,
lower_seismogenic_depth, dip):
"""
Get surface main vertexes.
Parameters are the same as for :meth:`from_fault_data`, excluding
mesh spacing.
:returns:
Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon`
describing the surface projection of the simple fault with
specified parameters.
"""
# Similar to :meth:`from_fault_data`, we just don't resample edges
dip_tan = math.tan(math.radians(dip))
hdist_top = upper_seismogenic_depth / dip_tan
hdist_bottom = lower_seismogenic_depth / dip_tan
strike = fault_trace[0].azimuth(fault_trace[-1])
azimuth = (strike + 90.0) % 360
# Collect coordinates of vertices on the top and bottom edge
lons = []
lats = []
for point in fault_trace.points:
top_edge_point = point.point_at(hdist_top, 0, azimuth)
bottom_edge_point = point.point_at(hdist_bottom, 0, azimuth)
lons.append(top_edge_point.longitude)
lats.append(top_edge_point.latitude)
lons.append(bottom_edge_point.longitude)
lats.append(bottom_edge_point.latitude)
lons = numpy.array(lons, float)
lats = numpy.array(lats, float)
return lons, lats | python | def get_surface_vertexes(cls, fault_trace,
upper_seismogenic_depth,
lower_seismogenic_depth, dip):
"""
Get surface main vertexes.
Parameters are the same as for :meth:`from_fault_data`, excluding
mesh spacing.
:returns:
Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon`
describing the surface projection of the simple fault with
specified parameters.
"""
# Similar to :meth:`from_fault_data`, we just don't resample edges
dip_tan = math.tan(math.radians(dip))
hdist_top = upper_seismogenic_depth / dip_tan
hdist_bottom = lower_seismogenic_depth / dip_tan
strike = fault_trace[0].azimuth(fault_trace[-1])
azimuth = (strike + 90.0) % 360
# Collect coordinates of vertices on the top and bottom edge
lons = []
lats = []
for point in fault_trace.points:
top_edge_point = point.point_at(hdist_top, 0, azimuth)
bottom_edge_point = point.point_at(hdist_bottom, 0, azimuth)
lons.append(top_edge_point.longitude)
lats.append(top_edge_point.latitude)
lons.append(bottom_edge_point.longitude)
lats.append(bottom_edge_point.latitude)
lons = numpy.array(lons, float)
lats = numpy.array(lats, float)
return lons, lats | [
"def",
"get_surface_vertexes",
"(",
"cls",
",",
"fault_trace",
",",
"upper_seismogenic_depth",
",",
"lower_seismogenic_depth",
",",
"dip",
")",
":",
"# Similar to :meth:`from_fault_data`, we just don't resample edges",
"dip_tan",
"=",
"math",
".",
"tan",
"(",
"math",
".",
"radians",
"(",
"dip",
")",
")",
"hdist_top",
"=",
"upper_seismogenic_depth",
"/",
"dip_tan",
"hdist_bottom",
"=",
"lower_seismogenic_depth",
"/",
"dip_tan",
"strike",
"=",
"fault_trace",
"[",
"0",
"]",
".",
"azimuth",
"(",
"fault_trace",
"[",
"-",
"1",
"]",
")",
"azimuth",
"=",
"(",
"strike",
"+",
"90.0",
")",
"%",
"360",
"# Collect coordinates of vertices on the top and bottom edge",
"lons",
"=",
"[",
"]",
"lats",
"=",
"[",
"]",
"for",
"point",
"in",
"fault_trace",
".",
"points",
":",
"top_edge_point",
"=",
"point",
".",
"point_at",
"(",
"hdist_top",
",",
"0",
",",
"azimuth",
")",
"bottom_edge_point",
"=",
"point",
".",
"point_at",
"(",
"hdist_bottom",
",",
"0",
",",
"azimuth",
")",
"lons",
".",
"append",
"(",
"top_edge_point",
".",
"longitude",
")",
"lats",
".",
"append",
"(",
"top_edge_point",
".",
"latitude",
")",
"lons",
".",
"append",
"(",
"bottom_edge_point",
".",
"longitude",
")",
"lats",
".",
"append",
"(",
"bottom_edge_point",
".",
"latitude",
")",
"lons",
"=",
"numpy",
".",
"array",
"(",
"lons",
",",
"float",
")",
"lats",
"=",
"numpy",
".",
"array",
"(",
"lats",
",",
"float",
")",
"return",
"lons",
",",
"lats"
] | Get surface main vertexes.
Parameters are the same as for :meth:`from_fault_data`, excluding
mesh spacing.
:returns:
Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon`
describing the surface projection of the simple fault with
specified parameters. | [
"Get",
"surface",
"main",
"vertexes",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/simple_fault.py#L301-L336 | train | 232,873 |
gem/oq-engine | openquake/hazardlib/geo/surface/simple_fault.py | SimpleFaultSurface.surface_projection_from_fault_data | def surface_projection_from_fault_data(cls, fault_trace,
upper_seismogenic_depth,
lower_seismogenic_depth, dip):
"""
Get a surface projection of the simple fault surface.
Parameters are the same as for :meth:`from_fault_data`, excluding
mesh spacing.
:returns:
Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon`
describing the surface projection of the simple fault with
specified parameters.
"""
lons, lats = cls.get_surface_vertexes(fault_trace,
upper_seismogenic_depth,
lower_seismogenic_depth, dip)
return Mesh(lons, lats, depths=None).get_convex_hull() | python | def surface_projection_from_fault_data(cls, fault_trace,
upper_seismogenic_depth,
lower_seismogenic_depth, dip):
"""
Get a surface projection of the simple fault surface.
Parameters are the same as for :meth:`from_fault_data`, excluding
mesh spacing.
:returns:
Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon`
describing the surface projection of the simple fault with
specified parameters.
"""
lons, lats = cls.get_surface_vertexes(fault_trace,
upper_seismogenic_depth,
lower_seismogenic_depth, dip)
return Mesh(lons, lats, depths=None).get_convex_hull() | [
"def",
"surface_projection_from_fault_data",
"(",
"cls",
",",
"fault_trace",
",",
"upper_seismogenic_depth",
",",
"lower_seismogenic_depth",
",",
"dip",
")",
":",
"lons",
",",
"lats",
"=",
"cls",
".",
"get_surface_vertexes",
"(",
"fault_trace",
",",
"upper_seismogenic_depth",
",",
"lower_seismogenic_depth",
",",
"dip",
")",
"return",
"Mesh",
"(",
"lons",
",",
"lats",
",",
"depths",
"=",
"None",
")",
".",
"get_convex_hull",
"(",
")"
] | Get a surface projection of the simple fault surface.
Parameters are the same as for :meth:`from_fault_data`, excluding
mesh spacing.
:returns:
Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon`
describing the surface projection of the simple fault with
specified parameters. | [
"Get",
"a",
"surface",
"projection",
"of",
"the",
"simple",
"fault",
"surface",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/simple_fault.py#L339-L356 | train | 232,874 |
gem/oq-engine | openquake/hazardlib/gsim/zhao_2006.py | ZhaoEtAl2006Asc._compute_distance_term | def _compute_distance_term(self, C, mag, rrup):
"""
Compute second and third terms in equation 1, p. 901.
"""
term1 = C['b'] * rrup
term2 = - np.log(rrup + C['c'] * np.exp(C['d'] * mag))
return term1 + term2 | python | def _compute_distance_term(self, C, mag, rrup):
"""
Compute second and third terms in equation 1, p. 901.
"""
term1 = C['b'] * rrup
term2 = - np.log(rrup + C['c'] * np.exp(C['d'] * mag))
return term1 + term2 | [
"def",
"_compute_distance_term",
"(",
"self",
",",
"C",
",",
"mag",
",",
"rrup",
")",
":",
"term1",
"=",
"C",
"[",
"'b'",
"]",
"*",
"rrup",
"term2",
"=",
"-",
"np",
".",
"log",
"(",
"rrup",
"+",
"C",
"[",
"'c'",
"]",
"*",
"np",
".",
"exp",
"(",
"C",
"[",
"'d'",
"]",
"*",
"mag",
")",
")",
"return",
"term1",
"+",
"term2"
] | Compute second and third terms in equation 1, p. 901. | [
"Compute",
"second",
"and",
"third",
"terms",
"in",
"equation",
"1",
"p",
".",
"901",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L133-L140 | train | 232,875 |
gem/oq-engine | openquake/hazardlib/gsim/zhao_2006.py | ZhaoEtAl2006Asc._compute_focal_depth_term | def _compute_focal_depth_term(self, C, hypo_depth):
"""
Compute fourth term in equation 1, p. 901.
"""
# p. 901. "(i.e, depth is capped at 125 km)".
focal_depth = hypo_depth
if focal_depth > 125.0:
focal_depth = 125.0
# p. 902. "We used the value of 15 km for the
# depth coefficient hc ...".
hc = 15.0
# p. 901. "When h is larger than hc, the depth terms takes
# effect ...". The next sentence specifies h>=hc.
return float(focal_depth >= hc) * C['e'] * (focal_depth - hc) | python | def _compute_focal_depth_term(self, C, hypo_depth):
"""
Compute fourth term in equation 1, p. 901.
"""
# p. 901. "(i.e, depth is capped at 125 km)".
focal_depth = hypo_depth
if focal_depth > 125.0:
focal_depth = 125.0
# p. 902. "We used the value of 15 km for the
# depth coefficient hc ...".
hc = 15.0
# p. 901. "When h is larger than hc, the depth terms takes
# effect ...". The next sentence specifies h>=hc.
return float(focal_depth >= hc) * C['e'] * (focal_depth - hc) | [
"def",
"_compute_focal_depth_term",
"(",
"self",
",",
"C",
",",
"hypo_depth",
")",
":",
"# p. 901. \"(i.e, depth is capped at 125 km)\".",
"focal_depth",
"=",
"hypo_depth",
"if",
"focal_depth",
">",
"125.0",
":",
"focal_depth",
"=",
"125.0",
"# p. 902. \"We used the value of 15 km for the",
"# depth coefficient hc ...\".",
"hc",
"=",
"15.0",
"# p. 901. \"When h is larger than hc, the depth terms takes",
"# effect ...\". The next sentence specifies h>=hc.",
"return",
"float",
"(",
"focal_depth",
">=",
"hc",
")",
"*",
"C",
"[",
"'e'",
"]",
"*",
"(",
"focal_depth",
"-",
"hc",
")"
] | Compute fourth term in equation 1, p. 901. | [
"Compute",
"fourth",
"term",
"in",
"equation",
"1",
"p",
".",
"901",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L142-L157 | train | 232,876 |
gem/oq-engine | openquake/hazardlib/gsim/zhao_2006.py | ZhaoEtAl2006Asc._compute_site_class_term | def _compute_site_class_term(self, C, vs30):
"""
Compute nine-th term in equation 1, p. 901.
"""
# map vs30 value to site class, see table 2, p. 901.
site_term = np.zeros(len(vs30))
# hard rock
site_term[vs30 > 1100.0] = C['CH']
# rock
site_term[(vs30 > 600) & (vs30 <= 1100)] = C['C1']
# hard soil
site_term[(vs30 > 300) & (vs30 <= 600)] = C['C2']
# medium soil
site_term[(vs30 > 200) & (vs30 <= 300)] = C['C3']
# soft soil
site_term[vs30 <= 200] = C['C4']
return site_term | python | def _compute_site_class_term(self, C, vs30):
"""
Compute nine-th term in equation 1, p. 901.
"""
# map vs30 value to site class, see table 2, p. 901.
site_term = np.zeros(len(vs30))
# hard rock
site_term[vs30 > 1100.0] = C['CH']
# rock
site_term[(vs30 > 600) & (vs30 <= 1100)] = C['C1']
# hard soil
site_term[(vs30 > 300) & (vs30 <= 600)] = C['C2']
# medium soil
site_term[(vs30 > 200) & (vs30 <= 300)] = C['C3']
# soft soil
site_term[vs30 <= 200] = C['C4']
return site_term | [
"def",
"_compute_site_class_term",
"(",
"self",
",",
"C",
",",
"vs30",
")",
":",
"# map vs30 value to site class, see table 2, p. 901.",
"site_term",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"vs30",
")",
")",
"# hard rock",
"site_term",
"[",
"vs30",
">",
"1100.0",
"]",
"=",
"C",
"[",
"'CH'",
"]",
"# rock",
"site_term",
"[",
"(",
"vs30",
">",
"600",
")",
"&",
"(",
"vs30",
"<=",
"1100",
")",
"]",
"=",
"C",
"[",
"'C1'",
"]",
"# hard soil",
"site_term",
"[",
"(",
"vs30",
">",
"300",
")",
"&",
"(",
"vs30",
"<=",
"600",
")",
"]",
"=",
"C",
"[",
"'C2'",
"]",
"# medium soil",
"site_term",
"[",
"(",
"vs30",
">",
"200",
")",
"&",
"(",
"vs30",
"<=",
"300",
")",
"]",
"=",
"C",
"[",
"'C3'",
"]",
"# soft soil",
"site_term",
"[",
"vs30",
"<=",
"200",
"]",
"=",
"C",
"[",
"'C4'",
"]",
"return",
"site_term"
] | Compute nine-th term in equation 1, p. 901. | [
"Compute",
"nine",
"-",
"th",
"term",
"in",
"equation",
"1",
"p",
".",
"901",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L168-L190 | train | 232,877 |
gem/oq-engine | openquake/hazardlib/gsim/zhao_2006.py | ZhaoEtAl2006Asc._compute_magnitude_squared_term | def _compute_magnitude_squared_term(self, P, M, Q, W, mag):
"""
Compute magnitude squared term, equation 5, p. 909.
"""
return P * (mag - M) + Q * (mag - M) ** 2 + W | python | def _compute_magnitude_squared_term(self, P, M, Q, W, mag):
"""
Compute magnitude squared term, equation 5, p. 909.
"""
return P * (mag - M) + Q * (mag - M) ** 2 + W | [
"def",
"_compute_magnitude_squared_term",
"(",
"self",
",",
"P",
",",
"M",
",",
"Q",
",",
"W",
",",
"mag",
")",
":",
"return",
"P",
"*",
"(",
"mag",
"-",
"M",
")",
"+",
"Q",
"*",
"(",
"mag",
"-",
"M",
")",
"**",
"2",
"+",
"W"
] | Compute magnitude squared term, equation 5, p. 909. | [
"Compute",
"magnitude",
"squared",
"term",
"equation",
"5",
"p",
".",
"909",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L192-L196 | train | 232,878 |
gem/oq-engine | openquake/hazardlib/gsim/zhao_2006.py | ZhaoEtAl2006SSlab._compute_slab_correction_term | def _compute_slab_correction_term(self, C, rrup):
"""
Compute path modification term for slab events, that is
the 8-th term in equation 1, p. 901.
"""
slab_term = C['SSL'] * np.log(rrup)
return slab_term | python | def _compute_slab_correction_term(self, C, rrup):
"""
Compute path modification term for slab events, that is
the 8-th term in equation 1, p. 901.
"""
slab_term = C['SSL'] * np.log(rrup)
return slab_term | [
"def",
"_compute_slab_correction_term",
"(",
"self",
",",
"C",
",",
"rrup",
")",
":",
"slab_term",
"=",
"C",
"[",
"'SSL'",
"]",
"*",
"np",
".",
"log",
"(",
"rrup",
")",
"return",
"slab_term"
] | Compute path modification term for slab events, that is
the 8-th term in equation 1, p. 901. | [
"Compute",
"path",
"modification",
"term",
"for",
"slab",
"events",
"that",
"is",
"the",
"8",
"-",
"th",
"term",
"in",
"equation",
"1",
"p",
".",
"901",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L369-L376 | train | 232,879 |
gem/oq-engine | openquake/hazardlib/gsim/zhao_2006.py | ZhaoEtAl2006AscSGS.get_mean_and_stddevs | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
Using a minimum distance of 5km for the calculation.
"""
dists_mod = copy.deepcopy(dists)
dists_mod.rrup[dists.rrup <= 5.] = 5.
return super().get_mean_and_stddevs(
sites, rup, dists_mod, imt, stddev_types) | python | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
Using a minimum distance of 5km for the calculation.
"""
dists_mod = copy.deepcopy(dists)
dists_mod.rrup[dists.rrup <= 5.] = 5.
return super().get_mean_and_stddevs(
sites, rup, dists_mod, imt, stddev_types) | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"dists_mod",
"=",
"copy",
".",
"deepcopy",
"(",
"dists",
")",
"dists_mod",
".",
"rrup",
"[",
"dists",
".",
"rrup",
"<=",
"5.",
"]",
"=",
"5.",
"return",
"super",
"(",
")",
".",
"get_mean_and_stddevs",
"(",
"sites",
",",
"rup",
",",
"dists_mod",
",",
"imt",
",",
"stddev_types",
")"
] | Using a minimum distance of 5km for the calculation. | [
"Using",
"a",
"minimum",
"distance",
"of",
"5km",
"for",
"the",
"calculation",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L654-L663 | train | 232,880 |
gem/oq-engine | openquake/engine/utils/__init__.py | confirm | def confirm(prompt):
"""
Ask for confirmation, given a ``prompt`` and return a boolean value.
"""
while True:
try:
answer = input(prompt)
except KeyboardInterrupt:
# the user presses ctrl+c, just say 'no'
return False
answer = answer.strip().lower()
if answer not in ('y', 'n'):
print('Please enter y or n')
continue
return answer == 'y' | python | def confirm(prompt):
"""
Ask for confirmation, given a ``prompt`` and return a boolean value.
"""
while True:
try:
answer = input(prompt)
except KeyboardInterrupt:
# the user presses ctrl+c, just say 'no'
return False
answer = answer.strip().lower()
if answer not in ('y', 'n'):
print('Please enter y or n')
continue
return answer == 'y' | [
"def",
"confirm",
"(",
"prompt",
")",
":",
"while",
"True",
":",
"try",
":",
"answer",
"=",
"input",
"(",
"prompt",
")",
"except",
"KeyboardInterrupt",
":",
"# the user presses ctrl+c, just say 'no'",
"return",
"False",
"answer",
"=",
"answer",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"if",
"answer",
"not",
"in",
"(",
"'y'",
",",
"'n'",
")",
":",
"print",
"(",
"'Please enter y or n'",
")",
"continue",
"return",
"answer",
"==",
"'y'"
] | Ask for confirmation, given a ``prompt`` and return a boolean value. | [
"Ask",
"for",
"confirmation",
"given",
"a",
"prompt",
"and",
"return",
"a",
"boolean",
"value",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/engine/utils/__init__.py#L20-L34 | train | 232,881 |
gem/oq-engine | openquake/risklib/asset.py | Exposure._csv_header | def _csv_header(self):
"""
Extract the expected CSV header from the exposure metadata
"""
fields = ['id', 'number', 'taxonomy', 'lon', 'lat']
for name in self.cost_types['name']:
fields.append(name)
if 'per_area' in self.cost_types['type']:
fields.append('area')
if self.occupancy_periods:
fields.extend(self.occupancy_periods.split())
fields.extend(self.tagcol.tagnames)
return set(fields) | python | def _csv_header(self):
"""
Extract the expected CSV header from the exposure metadata
"""
fields = ['id', 'number', 'taxonomy', 'lon', 'lat']
for name in self.cost_types['name']:
fields.append(name)
if 'per_area' in self.cost_types['type']:
fields.append('area')
if self.occupancy_periods:
fields.extend(self.occupancy_periods.split())
fields.extend(self.tagcol.tagnames)
return set(fields) | [
"def",
"_csv_header",
"(",
"self",
")",
":",
"fields",
"=",
"[",
"'id'",
",",
"'number'",
",",
"'taxonomy'",
",",
"'lon'",
",",
"'lat'",
"]",
"for",
"name",
"in",
"self",
".",
"cost_types",
"[",
"'name'",
"]",
":",
"fields",
".",
"append",
"(",
"name",
")",
"if",
"'per_area'",
"in",
"self",
".",
"cost_types",
"[",
"'type'",
"]",
":",
"fields",
".",
"append",
"(",
"'area'",
")",
"if",
"self",
".",
"occupancy_periods",
":",
"fields",
".",
"extend",
"(",
"self",
".",
"occupancy_periods",
".",
"split",
"(",
")",
")",
"fields",
".",
"extend",
"(",
"self",
".",
"tagcol",
".",
"tagnames",
")",
"return",
"set",
"(",
"fields",
")"
] | Extract the expected CSV header from the exposure metadata | [
"Extract",
"the",
"expected",
"CSV",
"header",
"from",
"the",
"exposure",
"metadata"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L885-L897 | train | 232,882 |
gem/oq-engine | openquake/risklib/riskmodels.py | build_vf_node | def build_vf_node(vf):
"""
Convert a VulnerabilityFunction object into a Node suitable
for XML conversion.
"""
nodes = [Node('imls', {'imt': vf.imt}, vf.imls),
Node('meanLRs', {}, vf.mean_loss_ratios),
Node('covLRs', {}, vf.covs)]
return Node(
'vulnerabilityFunction',
{'id': vf.id, 'dist': vf.distribution_name}, nodes=nodes) | python | def build_vf_node(vf):
"""
Convert a VulnerabilityFunction object into a Node suitable
for XML conversion.
"""
nodes = [Node('imls', {'imt': vf.imt}, vf.imls),
Node('meanLRs', {}, vf.mean_loss_ratios),
Node('covLRs', {}, vf.covs)]
return Node(
'vulnerabilityFunction',
{'id': vf.id, 'dist': vf.distribution_name}, nodes=nodes) | [
"def",
"build_vf_node",
"(",
"vf",
")",
":",
"nodes",
"=",
"[",
"Node",
"(",
"'imls'",
",",
"{",
"'imt'",
":",
"vf",
".",
"imt",
"}",
",",
"vf",
".",
"imls",
")",
",",
"Node",
"(",
"'meanLRs'",
",",
"{",
"}",
",",
"vf",
".",
"mean_loss_ratios",
")",
",",
"Node",
"(",
"'covLRs'",
",",
"{",
"}",
",",
"vf",
".",
"covs",
")",
"]",
"return",
"Node",
"(",
"'vulnerabilityFunction'",
",",
"{",
"'id'",
":",
"vf",
".",
"id",
",",
"'dist'",
":",
"vf",
".",
"distribution_name",
"}",
",",
"nodes",
"=",
"nodes",
")"
] | Convert a VulnerabilityFunction object into a Node suitable
for XML conversion. | [
"Convert",
"a",
"VulnerabilityFunction",
"object",
"into",
"a",
"Node",
"suitable",
"for",
"XML",
"conversion",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/riskmodels.py#L69-L79 | train | 232,883 |
gem/oq-engine | openquake/risklib/riskmodels.py | get_riskmodel | def get_riskmodel(taxonomy, oqparam, **extra):
"""
Return an instance of the correct riskmodel class, depending on the
attribute `calculation_mode` of the object `oqparam`.
:param taxonomy:
a taxonomy string
:param oqparam:
an object containing the parameters needed by the riskmodel class
:param extra:
extra parameters to pass to the riskmodel class
"""
riskmodel_class = registry[oqparam.calculation_mode]
# arguments needed to instantiate the riskmodel class
argnames = inspect.getfullargspec(riskmodel_class.__init__).args[3:]
# arguments extracted from oqparam
known_args = set(name for name, value in
inspect.getmembers(oqparam.__class__)
if isinstance(value, valid.Param))
all_args = {}
for argname in argnames:
if argname in known_args:
all_args[argname] = getattr(oqparam, argname)
if 'hazard_imtls' in argnames: # special case
all_args['hazard_imtls'] = oqparam.imtls
all_args.update(extra)
missing = set(argnames) - set(all_args)
if missing:
raise TypeError('Missing parameter: %s' % ', '.join(missing))
return riskmodel_class(taxonomy, **all_args) | python | def get_riskmodel(taxonomy, oqparam, **extra):
"""
Return an instance of the correct riskmodel class, depending on the
attribute `calculation_mode` of the object `oqparam`.
:param taxonomy:
a taxonomy string
:param oqparam:
an object containing the parameters needed by the riskmodel class
:param extra:
extra parameters to pass to the riskmodel class
"""
riskmodel_class = registry[oqparam.calculation_mode]
# arguments needed to instantiate the riskmodel class
argnames = inspect.getfullargspec(riskmodel_class.__init__).args[3:]
# arguments extracted from oqparam
known_args = set(name for name, value in
inspect.getmembers(oqparam.__class__)
if isinstance(value, valid.Param))
all_args = {}
for argname in argnames:
if argname in known_args:
all_args[argname] = getattr(oqparam, argname)
if 'hazard_imtls' in argnames: # special case
all_args['hazard_imtls'] = oqparam.imtls
all_args.update(extra)
missing = set(argnames) - set(all_args)
if missing:
raise TypeError('Missing parameter: %s' % ', '.join(missing))
return riskmodel_class(taxonomy, **all_args) | [
"def",
"get_riskmodel",
"(",
"taxonomy",
",",
"oqparam",
",",
"*",
"*",
"extra",
")",
":",
"riskmodel_class",
"=",
"registry",
"[",
"oqparam",
".",
"calculation_mode",
"]",
"# arguments needed to instantiate the riskmodel class",
"argnames",
"=",
"inspect",
".",
"getfullargspec",
"(",
"riskmodel_class",
".",
"__init__",
")",
".",
"args",
"[",
"3",
":",
"]",
"# arguments extracted from oqparam",
"known_args",
"=",
"set",
"(",
"name",
"for",
"name",
",",
"value",
"in",
"inspect",
".",
"getmembers",
"(",
"oqparam",
".",
"__class__",
")",
"if",
"isinstance",
"(",
"value",
",",
"valid",
".",
"Param",
")",
")",
"all_args",
"=",
"{",
"}",
"for",
"argname",
"in",
"argnames",
":",
"if",
"argname",
"in",
"known_args",
":",
"all_args",
"[",
"argname",
"]",
"=",
"getattr",
"(",
"oqparam",
",",
"argname",
")",
"if",
"'hazard_imtls'",
"in",
"argnames",
":",
"# special case",
"all_args",
"[",
"'hazard_imtls'",
"]",
"=",
"oqparam",
".",
"imtls",
"all_args",
".",
"update",
"(",
"extra",
")",
"missing",
"=",
"set",
"(",
"argnames",
")",
"-",
"set",
"(",
"all_args",
")",
"if",
"missing",
":",
"raise",
"TypeError",
"(",
"'Missing parameter: %s'",
"%",
"', '",
".",
"join",
"(",
"missing",
")",
")",
"return",
"riskmodel_class",
"(",
"taxonomy",
",",
"*",
"*",
"all_args",
")"
] | Return an instance of the correct riskmodel class, depending on the
attribute `calculation_mode` of the object `oqparam`.
:param taxonomy:
a taxonomy string
:param oqparam:
an object containing the parameters needed by the riskmodel class
:param extra:
extra parameters to pass to the riskmodel class | [
"Return",
"an",
"instance",
"of",
"the",
"correct",
"riskmodel",
"class",
"depending",
"on",
"the",
"attribute",
"calculation_mode",
"of",
"the",
"object",
"oqparam",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/riskmodels.py#L548-L580 | train | 232,884 |
gem/oq-engine | openquake/hmtk/plotting/beachball.py | Beachball | def Beachball(fm, linewidth=2, facecolor='b', bgcolor='w', edgecolor='k',
alpha=1.0, xy=(0, 0), width=200, size=100, nofill=False,
zorder=100, outfile=None, format=None, fig=None):
"""
Draws a beach ball diagram of an earthquake focal mechanism.
S1, D1, and R1, the strike, dip and rake of one of the focal planes, can
be vectors of multiple focal mechanisms.
:param fm: Focal mechanism that is either number of mechanisms (NM) by 3
(strike, dip, and rake) or NM x 6 (M11, M22, M33, M12, M13, M23 - the
six independent components of the moment tensor, where the coordinate
system is 1,2,3 = Up,South,East which equals r,theta,phi). The strike
is of the first plane, clockwise relative to north.
The dip is of the first plane, defined clockwise and perpendicular to
strike, relative to horizontal such that 0 is horizontal and 90 is
vertical. The rake is of the first focal plane solution. 90 moves the
hanging wall up-dip (thrust), 0 moves it in the strike direction
(left-lateral), -90 moves it down-dip (normal), and 180 moves it
opposite to strike (right-lateral).
:param facecolor: Color to use for quadrants of tension; can be a string,
e.g. ``'r'``, ``'b'`` or three component color vector, [R G B].
Defaults to ``'b'`` (blue).
:param bgcolor: The background color. Defaults to ``'w'`` (white).
:param edgecolor: Color of the edges. Defaults to ``'k'`` (black).
:param alpha: The alpha level of the beach ball. Defaults to ``1.0``
(opaque).
:param xy: Origin position of the beach ball as tuple. Defaults to
``(0, 0)``.
:type width: int
:param width: Symbol size of beach ball. Defaults to ``200``.
:param size: Controls the number of interpolation points for the
curves. Minimum is automatically set to ``100``.
:param nofill: Do not fill the beach ball, but only plot the planes.
:param zorder: Set zorder. Artists with lower zorder values are drawn
first.
:param outfile: Output file string. Also used to automatically
determine the output format. Supported file formats depend on your
matplotlib backend. Most backends support png, pdf, ps, eps and
svg. Defaults to ``None``.
:param format: Format of the graph picture. If no format is given the
outfile parameter will be used to try to automatically determine
the output format. If no format is found it defaults to png output.
If no outfile is specified but a format is, than a binary
imagestring will be returned.
Defaults to ``None``.
:param fig: Give an existing figure instance to plot into. New Figure if
set to ``None``.
"""
plot_width = width * 0.95
# plot the figure
if not fig:
fig = plt.figure(figsize=(3, 3), dpi=100)
fig.subplots_adjust(left=0, bottom=0, right=1, top=1)
fig.set_figheight(width // 100)
fig.set_figwidth(width // 100)
ax = fig.add_subplot(111, aspect='equal')
# hide axes + ticks
ax.axison = False
# plot the collection
collection = Beach(fm, linewidth=linewidth, facecolor=facecolor,
edgecolor=edgecolor, bgcolor=bgcolor,
alpha=alpha, nofill=nofill, xy=xy,
width=plot_width, size=size, zorder=zorder)
ax.add_collection(collection)
ax.autoscale_view(tight=False, scalex=True, scaley=True)
# export
if outfile:
if format:
fig.savefig(outfile, dpi=100, transparent=True, format=format)
else:
fig.savefig(outfile, dpi=100, transparent=True)
elif format and not outfile:
imgdata = compatibility.BytesIO()
fig.savefig(imgdata, format=format, dpi=100, transparent=True)
imgdata.seek(0)
return imgdata.read()
else:
plt.show()
return fig | python | def Beachball(fm, linewidth=2, facecolor='b', bgcolor='w', edgecolor='k',
alpha=1.0, xy=(0, 0), width=200, size=100, nofill=False,
zorder=100, outfile=None, format=None, fig=None):
"""
Draws a beach ball diagram of an earthquake focal mechanism.
S1, D1, and R1, the strike, dip and rake of one of the focal planes, can
be vectors of multiple focal mechanisms.
:param fm: Focal mechanism that is either number of mechanisms (NM) by 3
(strike, dip, and rake) or NM x 6 (M11, M22, M33, M12, M13, M23 - the
six independent components of the moment tensor, where the coordinate
system is 1,2,3 = Up,South,East which equals r,theta,phi). The strike
is of the first plane, clockwise relative to north.
The dip is of the first plane, defined clockwise and perpendicular to
strike, relative to horizontal such that 0 is horizontal and 90 is
vertical. The rake is of the first focal plane solution. 90 moves the
hanging wall up-dip (thrust), 0 moves it in the strike direction
(left-lateral), -90 moves it down-dip (normal), and 180 moves it
opposite to strike (right-lateral).
:param facecolor: Color to use for quadrants of tension; can be a string,
e.g. ``'r'``, ``'b'`` or three component color vector, [R G B].
Defaults to ``'b'`` (blue).
:param bgcolor: The background color. Defaults to ``'w'`` (white).
:param edgecolor: Color of the edges. Defaults to ``'k'`` (black).
:param alpha: The alpha level of the beach ball. Defaults to ``1.0``
(opaque).
:param xy: Origin position of the beach ball as tuple. Defaults to
``(0, 0)``.
:type width: int
:param width: Symbol size of beach ball. Defaults to ``200``.
:param size: Controls the number of interpolation points for the
curves. Minimum is automatically set to ``100``.
:param nofill: Do not fill the beach ball, but only plot the planes.
:param zorder: Set zorder. Artists with lower zorder values are drawn
first.
:param outfile: Output file string. Also used to automatically
determine the output format. Supported file formats depend on your
matplotlib backend. Most backends support png, pdf, ps, eps and
svg. Defaults to ``None``.
:param format: Format of the graph picture. If no format is given the
outfile parameter will be used to try to automatically determine
the output format. If no format is found it defaults to png output.
If no outfile is specified but a format is, than a binary
imagestring will be returned.
Defaults to ``None``.
:param fig: Give an existing figure instance to plot into. New Figure if
set to ``None``.
"""
plot_width = width * 0.95
# plot the figure
if not fig:
fig = plt.figure(figsize=(3, 3), dpi=100)
fig.subplots_adjust(left=0, bottom=0, right=1, top=1)
fig.set_figheight(width // 100)
fig.set_figwidth(width // 100)
ax = fig.add_subplot(111, aspect='equal')
# hide axes + ticks
ax.axison = False
# plot the collection
collection = Beach(fm, linewidth=linewidth, facecolor=facecolor,
edgecolor=edgecolor, bgcolor=bgcolor,
alpha=alpha, nofill=nofill, xy=xy,
width=plot_width, size=size, zorder=zorder)
ax.add_collection(collection)
ax.autoscale_view(tight=False, scalex=True, scaley=True)
# export
if outfile:
if format:
fig.savefig(outfile, dpi=100, transparent=True, format=format)
else:
fig.savefig(outfile, dpi=100, transparent=True)
elif format and not outfile:
imgdata = compatibility.BytesIO()
fig.savefig(imgdata, format=format, dpi=100, transparent=True)
imgdata.seek(0)
return imgdata.read()
else:
plt.show()
return fig | [
"def",
"Beachball",
"(",
"fm",
",",
"linewidth",
"=",
"2",
",",
"facecolor",
"=",
"'b'",
",",
"bgcolor",
"=",
"'w'",
",",
"edgecolor",
"=",
"'k'",
",",
"alpha",
"=",
"1.0",
",",
"xy",
"=",
"(",
"0",
",",
"0",
")",
",",
"width",
"=",
"200",
",",
"size",
"=",
"100",
",",
"nofill",
"=",
"False",
",",
"zorder",
"=",
"100",
",",
"outfile",
"=",
"None",
",",
"format",
"=",
"None",
",",
"fig",
"=",
"None",
")",
":",
"plot_width",
"=",
"width",
"*",
"0.95",
"# plot the figure",
"if",
"not",
"fig",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"(",
"3",
",",
"3",
")",
",",
"dpi",
"=",
"100",
")",
"fig",
".",
"subplots_adjust",
"(",
"left",
"=",
"0",
",",
"bottom",
"=",
"0",
",",
"right",
"=",
"1",
",",
"top",
"=",
"1",
")",
"fig",
".",
"set_figheight",
"(",
"width",
"//",
"100",
")",
"fig",
".",
"set_figwidth",
"(",
"width",
"//",
"100",
")",
"ax",
"=",
"fig",
".",
"add_subplot",
"(",
"111",
",",
"aspect",
"=",
"'equal'",
")",
"# hide axes + ticks",
"ax",
".",
"axison",
"=",
"False",
"# plot the collection",
"collection",
"=",
"Beach",
"(",
"fm",
",",
"linewidth",
"=",
"linewidth",
",",
"facecolor",
"=",
"facecolor",
",",
"edgecolor",
"=",
"edgecolor",
",",
"bgcolor",
"=",
"bgcolor",
",",
"alpha",
"=",
"alpha",
",",
"nofill",
"=",
"nofill",
",",
"xy",
"=",
"xy",
",",
"width",
"=",
"plot_width",
",",
"size",
"=",
"size",
",",
"zorder",
"=",
"zorder",
")",
"ax",
".",
"add_collection",
"(",
"collection",
")",
"ax",
".",
"autoscale_view",
"(",
"tight",
"=",
"False",
",",
"scalex",
"=",
"True",
",",
"scaley",
"=",
"True",
")",
"# export",
"if",
"outfile",
":",
"if",
"format",
":",
"fig",
".",
"savefig",
"(",
"outfile",
",",
"dpi",
"=",
"100",
",",
"transparent",
"=",
"True",
",",
"format",
"=",
"format",
")",
"else",
":",
"fig",
".",
"savefig",
"(",
"outfile",
",",
"dpi",
"=",
"100",
",",
"transparent",
"=",
"True",
")",
"elif",
"format",
"and",
"not",
"outfile",
":",
"imgdata",
"=",
"compatibility",
".",
"BytesIO",
"(",
")",
"fig",
".",
"savefig",
"(",
"imgdata",
",",
"format",
"=",
"format",
",",
"dpi",
"=",
"100",
",",
"transparent",
"=",
"True",
")",
"imgdata",
".",
"seek",
"(",
"0",
")",
"return",
"imgdata",
".",
"read",
"(",
")",
"else",
":",
"plt",
".",
"show",
"(",
")",
"return",
"fig"
] | Draws a beach ball diagram of an earthquake focal mechanism.
S1, D1, and R1, the strike, dip and rake of one of the focal planes, can
be vectors of multiple focal mechanisms.
:param fm: Focal mechanism that is either number of mechanisms (NM) by 3
(strike, dip, and rake) or NM x 6 (M11, M22, M33, M12, M13, M23 - the
six independent components of the moment tensor, where the coordinate
system is 1,2,3 = Up,South,East which equals r,theta,phi). The strike
is of the first plane, clockwise relative to north.
The dip is of the first plane, defined clockwise and perpendicular to
strike, relative to horizontal such that 0 is horizontal and 90 is
vertical. The rake is of the first focal plane solution. 90 moves the
hanging wall up-dip (thrust), 0 moves it in the strike direction
(left-lateral), -90 moves it down-dip (normal), and 180 moves it
opposite to strike (right-lateral).
:param facecolor: Color to use for quadrants of tension; can be a string,
e.g. ``'r'``, ``'b'`` or three component color vector, [R G B].
Defaults to ``'b'`` (blue).
:param bgcolor: The background color. Defaults to ``'w'`` (white).
:param edgecolor: Color of the edges. Defaults to ``'k'`` (black).
:param alpha: The alpha level of the beach ball. Defaults to ``1.0``
(opaque).
:param xy: Origin position of the beach ball as tuple. Defaults to
``(0, 0)``.
:type width: int
:param width: Symbol size of beach ball. Defaults to ``200``.
:param size: Controls the number of interpolation points for the
curves. Minimum is automatically set to ``100``.
:param nofill: Do not fill the beach ball, but only plot the planes.
:param zorder: Set zorder. Artists with lower zorder values are drawn
first.
:param outfile: Output file string. Also used to automatically
determine the output format. Supported file formats depend on your
matplotlib backend. Most backends support png, pdf, ps, eps and
svg. Defaults to ``None``.
:param format: Format of the graph picture. If no format is given the
outfile parameter will be used to try to automatically determine
the output format. If no format is found it defaults to png output.
If no outfile is specified but a format is, than a binary
imagestring will be returned.
Defaults to ``None``.
:param fig: Give an existing figure instance to plot into. New Figure if
set to ``None``. | [
"Draws",
"a",
"beach",
"ball",
"diagram",
"of",
"an",
"earthquake",
"focal",
"mechanism",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L147-L230 | train | 232,885 |
gem/oq-engine | openquake/hmtk/plotting/beachball.py | StrikeDip | def StrikeDip(n, e, u):
"""
Finds strike and dip of plane given normal vector having components n, e,
and u.
Adapted from MATLAB script
`bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_
written by Andy Michael and Oliver Boyd.
"""
r2d = 180 / np.pi
if u < 0:
n = -n
e = -e
u = -u
strike = np.arctan2(e, n) * r2d
strike = strike - 90
while strike >= 360:
strike = strike - 360
while strike < 0:
strike = strike + 360
x = np.sqrt(np.power(n, 2) + np.power(e, 2))
dip = np.arctan2(x, u) * r2d
return (strike, dip) | python | def StrikeDip(n, e, u):
"""
Finds strike and dip of plane given normal vector having components n, e,
and u.
Adapted from MATLAB script
`bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_
written by Andy Michael and Oliver Boyd.
"""
r2d = 180 / np.pi
if u < 0:
n = -n
e = -e
u = -u
strike = np.arctan2(e, n) * r2d
strike = strike - 90
while strike >= 360:
strike = strike - 360
while strike < 0:
strike = strike + 360
x = np.sqrt(np.power(n, 2) + np.power(e, 2))
dip = np.arctan2(x, u) * r2d
return (strike, dip) | [
"def",
"StrikeDip",
"(",
"n",
",",
"e",
",",
"u",
")",
":",
"r2d",
"=",
"180",
"/",
"np",
".",
"pi",
"if",
"u",
"<",
"0",
":",
"n",
"=",
"-",
"n",
"e",
"=",
"-",
"e",
"u",
"=",
"-",
"u",
"strike",
"=",
"np",
".",
"arctan2",
"(",
"e",
",",
"n",
")",
"*",
"r2d",
"strike",
"=",
"strike",
"-",
"90",
"while",
"strike",
">=",
"360",
":",
"strike",
"=",
"strike",
"-",
"360",
"while",
"strike",
"<",
"0",
":",
"strike",
"=",
"strike",
"+",
"360",
"x",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"power",
"(",
"n",
",",
"2",
")",
"+",
"np",
".",
"power",
"(",
"e",
",",
"2",
")",
")",
"dip",
"=",
"np",
".",
"arctan2",
"(",
"x",
",",
"u",
")",
"*",
"r2d",
"return",
"(",
"strike",
",",
"dip",
")"
] | Finds strike and dip of plane given normal vector having components n, e,
and u.
Adapted from MATLAB script
`bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_
written by Andy Michael and Oliver Boyd. | [
"Finds",
"strike",
"and",
"dip",
"of",
"plane",
"given",
"normal",
"vector",
"having",
"components",
"n",
"e",
"and",
"u",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L669-L692 | train | 232,886 |
gem/oq-engine | openquake/hmtk/plotting/beachball.py | AuxPlane | def AuxPlane(s1, d1, r1):
"""
Get Strike and dip of second plane.
Adapted from MATLAB script
`bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_
written by Andy Michael and Oliver Boyd.
"""
r2d = 180 / np.pi
z = (s1 + 90) / r2d
z2 = d1 / r2d
z3 = r1 / r2d
# slick vector in plane 1
sl1 = -np.cos(z3) * np.cos(z) - np.sin(z3) * np.sin(z) * np.cos(z2)
sl2 = np.cos(z3) * np.sin(z) - np.sin(z3) * np.cos(z) * np.cos(z2)
sl3 = np.sin(z3) * np.sin(z2)
(strike, dip) = StrikeDip(sl2, sl1, sl3)
n1 = np.sin(z) * np.sin(z2) # normal vector to plane 1
n2 = np.cos(z) * np.sin(z2)
h1 = -sl2 # strike vector of plane 2
h2 = sl1
# note h3=0 always so we leave it out
# n3 = np.cos(z2)
z = h1 * n1 + h2 * n2
z = z / np.sqrt(h1 * h1 + h2 * h2)
z = np.arccos(z)
rake = 0
if sl3 > 0:
rake = z * r2d
if sl3 <= 0:
rake = -z * r2d
return (strike, dip, rake) | python | def AuxPlane(s1, d1, r1):
"""
Get Strike and dip of second plane.
Adapted from MATLAB script
`bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_
written by Andy Michael and Oliver Boyd.
"""
r2d = 180 / np.pi
z = (s1 + 90) / r2d
z2 = d1 / r2d
z3 = r1 / r2d
# slick vector in plane 1
sl1 = -np.cos(z3) * np.cos(z) - np.sin(z3) * np.sin(z) * np.cos(z2)
sl2 = np.cos(z3) * np.sin(z) - np.sin(z3) * np.cos(z) * np.cos(z2)
sl3 = np.sin(z3) * np.sin(z2)
(strike, dip) = StrikeDip(sl2, sl1, sl3)
n1 = np.sin(z) * np.sin(z2) # normal vector to plane 1
n2 = np.cos(z) * np.sin(z2)
h1 = -sl2 # strike vector of plane 2
h2 = sl1
# note h3=0 always so we leave it out
# n3 = np.cos(z2)
z = h1 * n1 + h2 * n2
z = z / np.sqrt(h1 * h1 + h2 * h2)
z = np.arccos(z)
rake = 0
if sl3 > 0:
rake = z * r2d
if sl3 <= 0:
rake = -z * r2d
return (strike, dip, rake) | [
"def",
"AuxPlane",
"(",
"s1",
",",
"d1",
",",
"r1",
")",
":",
"r2d",
"=",
"180",
"/",
"np",
".",
"pi",
"z",
"=",
"(",
"s1",
"+",
"90",
")",
"/",
"r2d",
"z2",
"=",
"d1",
"/",
"r2d",
"z3",
"=",
"r1",
"/",
"r2d",
"# slick vector in plane 1",
"sl1",
"=",
"-",
"np",
".",
"cos",
"(",
"z3",
")",
"*",
"np",
".",
"cos",
"(",
"z",
")",
"-",
"np",
".",
"sin",
"(",
"z3",
")",
"*",
"np",
".",
"sin",
"(",
"z",
")",
"*",
"np",
".",
"cos",
"(",
"z2",
")",
"sl2",
"=",
"np",
".",
"cos",
"(",
"z3",
")",
"*",
"np",
".",
"sin",
"(",
"z",
")",
"-",
"np",
".",
"sin",
"(",
"z3",
")",
"*",
"np",
".",
"cos",
"(",
"z",
")",
"*",
"np",
".",
"cos",
"(",
"z2",
")",
"sl3",
"=",
"np",
".",
"sin",
"(",
"z3",
")",
"*",
"np",
".",
"sin",
"(",
"z2",
")",
"(",
"strike",
",",
"dip",
")",
"=",
"StrikeDip",
"(",
"sl2",
",",
"sl1",
",",
"sl3",
")",
"n1",
"=",
"np",
".",
"sin",
"(",
"z",
")",
"*",
"np",
".",
"sin",
"(",
"z2",
")",
"# normal vector to plane 1",
"n2",
"=",
"np",
".",
"cos",
"(",
"z",
")",
"*",
"np",
".",
"sin",
"(",
"z2",
")",
"h1",
"=",
"-",
"sl2",
"# strike vector of plane 2",
"h2",
"=",
"sl1",
"# note h3=0 always so we leave it out",
"# n3 = np.cos(z2)",
"z",
"=",
"h1",
"*",
"n1",
"+",
"h2",
"*",
"n2",
"z",
"=",
"z",
"/",
"np",
".",
"sqrt",
"(",
"h1",
"*",
"h1",
"+",
"h2",
"*",
"h2",
")",
"z",
"=",
"np",
".",
"arccos",
"(",
"z",
")",
"rake",
"=",
"0",
"if",
"sl3",
">",
"0",
":",
"rake",
"=",
"z",
"*",
"r2d",
"if",
"sl3",
"<=",
"0",
":",
"rake",
"=",
"-",
"z",
"*",
"r2d",
"return",
"(",
"strike",
",",
"dip",
",",
"rake",
")"
] | Get Strike and dip of second plane.
Adapted from MATLAB script
`bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_
written by Andy Michael and Oliver Boyd. | [
"Get",
"Strike",
"and",
"dip",
"of",
"second",
"plane",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L695-L729 | train | 232,887 |
gem/oq-engine | openquake/hmtk/plotting/beachball.py | MT2Plane | def MT2Plane(mt):
"""
Calculates a nodal plane of a given moment tensor.
:param mt: :class:`~MomentTensor`
:return: :class:`~NodalPlane`
Adapted from MATLAB script
`bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_
written by Andy Michael and Oliver Boyd.
"""
(d, v) = np.linalg.eig(mt.mt)
D = np.array([d[1], d[0], d[2]])
V = np.array([[v[1, 1], -v[1, 0], -v[1, 2]],
[v[2, 1], -v[2, 0], -v[2, 2]],
[-v[0, 1], v[0, 0], v[0, 2]]])
IMAX = D.argmax()
IMIN = D.argmin()
AE = (V[:, IMAX] + V[:, IMIN]) / np.sqrt(2.0)
AN = (V[:, IMAX] - V[:, IMIN]) / np.sqrt(2.0)
AER = np.sqrt(np.power(AE[0], 2) + np.power(AE[1], 2) + np.power(AE[2], 2))
ANR = np.sqrt(np.power(AN[0], 2) + np.power(AN[1], 2) + np.power(AN[2], 2))
AE = AE / AER
if not ANR:
AN = np.array([np.nan, np.nan, np.nan])
else:
AN = AN / ANR
if AN[2] <= 0.:
AN1 = AN
AE1 = AE
else:
AN1 = -AN
AE1 = -AE
(ft, fd, fl) = TDL(AN1, AE1)
return NodalPlane(360 - ft, fd, 180 - fl) | python | def MT2Plane(mt):
"""
Calculates a nodal plane of a given moment tensor.
:param mt: :class:`~MomentTensor`
:return: :class:`~NodalPlane`
Adapted from MATLAB script
`bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_
written by Andy Michael and Oliver Boyd.
"""
(d, v) = np.linalg.eig(mt.mt)
D = np.array([d[1], d[0], d[2]])
V = np.array([[v[1, 1], -v[1, 0], -v[1, 2]],
[v[2, 1], -v[2, 0], -v[2, 2]],
[-v[0, 1], v[0, 0], v[0, 2]]])
IMAX = D.argmax()
IMIN = D.argmin()
AE = (V[:, IMAX] + V[:, IMIN]) / np.sqrt(2.0)
AN = (V[:, IMAX] - V[:, IMIN]) / np.sqrt(2.0)
AER = np.sqrt(np.power(AE[0], 2) + np.power(AE[1], 2) + np.power(AE[2], 2))
ANR = np.sqrt(np.power(AN[0], 2) + np.power(AN[1], 2) + np.power(AN[2], 2))
AE = AE / AER
if not ANR:
AN = np.array([np.nan, np.nan, np.nan])
else:
AN = AN / ANR
if AN[2] <= 0.:
AN1 = AN
AE1 = AE
else:
AN1 = -AN
AE1 = -AE
(ft, fd, fl) = TDL(AN1, AE1)
return NodalPlane(360 - ft, fd, 180 - fl) | [
"def",
"MT2Plane",
"(",
"mt",
")",
":",
"(",
"d",
",",
"v",
")",
"=",
"np",
".",
"linalg",
".",
"eig",
"(",
"mt",
".",
"mt",
")",
"D",
"=",
"np",
".",
"array",
"(",
"[",
"d",
"[",
"1",
"]",
",",
"d",
"[",
"0",
"]",
",",
"d",
"[",
"2",
"]",
"]",
")",
"V",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"v",
"[",
"1",
",",
"1",
"]",
",",
"-",
"v",
"[",
"1",
",",
"0",
"]",
",",
"-",
"v",
"[",
"1",
",",
"2",
"]",
"]",
",",
"[",
"v",
"[",
"2",
",",
"1",
"]",
",",
"-",
"v",
"[",
"2",
",",
"0",
"]",
",",
"-",
"v",
"[",
"2",
",",
"2",
"]",
"]",
",",
"[",
"-",
"v",
"[",
"0",
",",
"1",
"]",
",",
"v",
"[",
"0",
",",
"0",
"]",
",",
"v",
"[",
"0",
",",
"2",
"]",
"]",
"]",
")",
"IMAX",
"=",
"D",
".",
"argmax",
"(",
")",
"IMIN",
"=",
"D",
".",
"argmin",
"(",
")",
"AE",
"=",
"(",
"V",
"[",
":",
",",
"IMAX",
"]",
"+",
"V",
"[",
":",
",",
"IMIN",
"]",
")",
"/",
"np",
".",
"sqrt",
"(",
"2.0",
")",
"AN",
"=",
"(",
"V",
"[",
":",
",",
"IMAX",
"]",
"-",
"V",
"[",
":",
",",
"IMIN",
"]",
")",
"/",
"np",
".",
"sqrt",
"(",
"2.0",
")",
"AER",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"power",
"(",
"AE",
"[",
"0",
"]",
",",
"2",
")",
"+",
"np",
".",
"power",
"(",
"AE",
"[",
"1",
"]",
",",
"2",
")",
"+",
"np",
".",
"power",
"(",
"AE",
"[",
"2",
"]",
",",
"2",
")",
")",
"ANR",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"power",
"(",
"AN",
"[",
"0",
"]",
",",
"2",
")",
"+",
"np",
".",
"power",
"(",
"AN",
"[",
"1",
"]",
",",
"2",
")",
"+",
"np",
".",
"power",
"(",
"AN",
"[",
"2",
"]",
",",
"2",
")",
")",
"AE",
"=",
"AE",
"/",
"AER",
"if",
"not",
"ANR",
":",
"AN",
"=",
"np",
".",
"array",
"(",
"[",
"np",
".",
"nan",
",",
"np",
".",
"nan",
",",
"np",
".",
"nan",
"]",
")",
"else",
":",
"AN",
"=",
"AN",
"/",
"ANR",
"if",
"AN",
"[",
"2",
"]",
"<=",
"0.",
":",
"AN1",
"=",
"AN",
"AE1",
"=",
"AE",
"else",
":",
"AN1",
"=",
"-",
"AN",
"AE1",
"=",
"-",
"AE",
"(",
"ft",
",",
"fd",
",",
"fl",
")",
"=",
"TDL",
"(",
"AN1",
",",
"AE1",
")",
"return",
"NodalPlane",
"(",
"360",
"-",
"ft",
",",
"fd",
",",
"180",
"-",
"fl",
")"
] | Calculates a nodal plane of a given moment tensor.
:param mt: :class:`~MomentTensor`
:return: :class:`~NodalPlane`
Adapted from MATLAB script
`bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_
written by Andy Michael and Oliver Boyd. | [
"Calculates",
"a",
"nodal",
"plane",
"of",
"a",
"given",
"moment",
"tensor",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L732-L766 | train | 232,888 |
gem/oq-engine | openquake/hmtk/plotting/beachball.py | TDL | def TDL(AN, BN):
"""
Helper function for MT2Plane.
Adapted from MATLAB script
`bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_
written by Andy Michael and Oliver Boyd.
"""
XN = AN[0]
YN = AN[1]
ZN = AN[2]
XE = BN[0]
YE = BN[1]
ZE = BN[2]
AAA = 1.0 / (1000000)
CON = 57.2957795
if np.fabs(ZN) < AAA:
FD = 90.
AXN = np.fabs(XN)
if AXN > 1.0:
AXN = 1.0
FT = np.arcsin(AXN) * CON
ST = -XN
CT = YN
if ST >= 0. and CT < 0:
FT = 180. - FT
if ST < 0. and CT <= 0:
FT = 180. + FT
if ST < 0. and CT > 0:
FT = 360. - FT
FL = np.arcsin(abs(ZE)) * CON
SL = -ZE
if np.fabs(XN) < AAA:
CL = XE / YN
else:
CL = -YE / XN
if SL >= 0. and CL < 0:
FL = 180. - FL
if SL < 0. and CL <= 0:
FL = FL - 180.
if SL < 0. and CL > 0:
FL = -FL
else:
if - ZN > 1.0:
ZN = -1.0
FDH = np.arccos(-ZN)
FD = FDH * CON
SD = np.sin(FDH)
if SD == 0:
return
ST = -XN / SD
CT = YN / SD
SX = np.fabs(ST)
if SX > 1.0:
SX = 1.0
FT = np.arcsin(SX) * CON
if ST >= 0. and CT < 0:
FT = 180. - FT
if ST < 0. and CT <= 0:
FT = 180. + FT
if ST < 0. and CT > 0:
FT = 360. - FT
SL = -ZE / SD
SX = np.fabs(SL)
if SX > 1.0:
SX = 1.0
FL = np.arcsin(SX) * CON
if ST == 0:
CL = XE / CT
else:
XXX = YN * ZN * ZE / SD / SD + YE
CL = -SD * XXX / XN
if CT == 0:
CL = YE / ST
if SL >= 0. and CL < 0:
FL = 180. - FL
if SL < 0. and CL <= 0:
FL = FL - 180.
if SL < 0. and CL > 0:
FL = -FL
return (FT, FD, FL) | python | def TDL(AN, BN):
"""
Helper function for MT2Plane.
Adapted from MATLAB script
`bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_
written by Andy Michael and Oliver Boyd.
"""
XN = AN[0]
YN = AN[1]
ZN = AN[2]
XE = BN[0]
YE = BN[1]
ZE = BN[2]
AAA = 1.0 / (1000000)
CON = 57.2957795
if np.fabs(ZN) < AAA:
FD = 90.
AXN = np.fabs(XN)
if AXN > 1.0:
AXN = 1.0
FT = np.arcsin(AXN) * CON
ST = -XN
CT = YN
if ST >= 0. and CT < 0:
FT = 180. - FT
if ST < 0. and CT <= 0:
FT = 180. + FT
if ST < 0. and CT > 0:
FT = 360. - FT
FL = np.arcsin(abs(ZE)) * CON
SL = -ZE
if np.fabs(XN) < AAA:
CL = XE / YN
else:
CL = -YE / XN
if SL >= 0. and CL < 0:
FL = 180. - FL
if SL < 0. and CL <= 0:
FL = FL - 180.
if SL < 0. and CL > 0:
FL = -FL
else:
if - ZN > 1.0:
ZN = -1.0
FDH = np.arccos(-ZN)
FD = FDH * CON
SD = np.sin(FDH)
if SD == 0:
return
ST = -XN / SD
CT = YN / SD
SX = np.fabs(ST)
if SX > 1.0:
SX = 1.0
FT = np.arcsin(SX) * CON
if ST >= 0. and CT < 0:
FT = 180. - FT
if ST < 0. and CT <= 0:
FT = 180. + FT
if ST < 0. and CT > 0:
FT = 360. - FT
SL = -ZE / SD
SX = np.fabs(SL)
if SX > 1.0:
SX = 1.0
FL = np.arcsin(SX) * CON
if ST == 0:
CL = XE / CT
else:
XXX = YN * ZN * ZE / SD / SD + YE
CL = -SD * XXX / XN
if CT == 0:
CL = YE / ST
if SL >= 0. and CL < 0:
FL = 180. - FL
if SL < 0. and CL <= 0:
FL = FL - 180.
if SL < 0. and CL > 0:
FL = -FL
return (FT, FD, FL) | [
"def",
"TDL",
"(",
"AN",
",",
"BN",
")",
":",
"XN",
"=",
"AN",
"[",
"0",
"]",
"YN",
"=",
"AN",
"[",
"1",
"]",
"ZN",
"=",
"AN",
"[",
"2",
"]",
"XE",
"=",
"BN",
"[",
"0",
"]",
"YE",
"=",
"BN",
"[",
"1",
"]",
"ZE",
"=",
"BN",
"[",
"2",
"]",
"AAA",
"=",
"1.0",
"/",
"(",
"1000000",
")",
"CON",
"=",
"57.2957795",
"if",
"np",
".",
"fabs",
"(",
"ZN",
")",
"<",
"AAA",
":",
"FD",
"=",
"90.",
"AXN",
"=",
"np",
".",
"fabs",
"(",
"XN",
")",
"if",
"AXN",
">",
"1.0",
":",
"AXN",
"=",
"1.0",
"FT",
"=",
"np",
".",
"arcsin",
"(",
"AXN",
")",
"*",
"CON",
"ST",
"=",
"-",
"XN",
"CT",
"=",
"YN",
"if",
"ST",
">=",
"0.",
"and",
"CT",
"<",
"0",
":",
"FT",
"=",
"180.",
"-",
"FT",
"if",
"ST",
"<",
"0.",
"and",
"CT",
"<=",
"0",
":",
"FT",
"=",
"180.",
"+",
"FT",
"if",
"ST",
"<",
"0.",
"and",
"CT",
">",
"0",
":",
"FT",
"=",
"360.",
"-",
"FT",
"FL",
"=",
"np",
".",
"arcsin",
"(",
"abs",
"(",
"ZE",
")",
")",
"*",
"CON",
"SL",
"=",
"-",
"ZE",
"if",
"np",
".",
"fabs",
"(",
"XN",
")",
"<",
"AAA",
":",
"CL",
"=",
"XE",
"/",
"YN",
"else",
":",
"CL",
"=",
"-",
"YE",
"/",
"XN",
"if",
"SL",
">=",
"0.",
"and",
"CL",
"<",
"0",
":",
"FL",
"=",
"180.",
"-",
"FL",
"if",
"SL",
"<",
"0.",
"and",
"CL",
"<=",
"0",
":",
"FL",
"=",
"FL",
"-",
"180.",
"if",
"SL",
"<",
"0.",
"and",
"CL",
">",
"0",
":",
"FL",
"=",
"-",
"FL",
"else",
":",
"if",
"-",
"ZN",
">",
"1.0",
":",
"ZN",
"=",
"-",
"1.0",
"FDH",
"=",
"np",
".",
"arccos",
"(",
"-",
"ZN",
")",
"FD",
"=",
"FDH",
"*",
"CON",
"SD",
"=",
"np",
".",
"sin",
"(",
"FDH",
")",
"if",
"SD",
"==",
"0",
":",
"return",
"ST",
"=",
"-",
"XN",
"/",
"SD",
"CT",
"=",
"YN",
"/",
"SD",
"SX",
"=",
"np",
".",
"fabs",
"(",
"ST",
")",
"if",
"SX",
">",
"1.0",
":",
"SX",
"=",
"1.0",
"FT",
"=",
"np",
".",
"arcsin",
"(",
"SX",
")",
"*",
"CON",
"if",
"ST",
">=",
"0.",
"and",
"CT",
"<",
"0",
":",
"FT",
"=",
"180.",
"-",
"FT",
"if",
"ST",
"<",
"0.",
"and",
"CT",
"<=",
"0",
":",
"FT",
"=",
"180.",
"+",
"FT",
"if",
"ST",
"<",
"0.",
"and",
"CT",
">",
"0",
":",
"FT",
"=",
"360.",
"-",
"FT",
"SL",
"=",
"-",
"ZE",
"/",
"SD",
"SX",
"=",
"np",
".",
"fabs",
"(",
"SL",
")",
"if",
"SX",
">",
"1.0",
":",
"SX",
"=",
"1.0",
"FL",
"=",
"np",
".",
"arcsin",
"(",
"SX",
")",
"*",
"CON",
"if",
"ST",
"==",
"0",
":",
"CL",
"=",
"XE",
"/",
"CT",
"else",
":",
"XXX",
"=",
"YN",
"*",
"ZN",
"*",
"ZE",
"/",
"SD",
"/",
"SD",
"+",
"YE",
"CL",
"=",
"-",
"SD",
"*",
"XXX",
"/",
"XN",
"if",
"CT",
"==",
"0",
":",
"CL",
"=",
"YE",
"/",
"ST",
"if",
"SL",
">=",
"0.",
"and",
"CL",
"<",
"0",
":",
"FL",
"=",
"180.",
"-",
"FL",
"if",
"SL",
"<",
"0.",
"and",
"CL",
"<=",
"0",
":",
"FL",
"=",
"FL",
"-",
"180.",
"if",
"SL",
"<",
"0.",
"and",
"CL",
">",
"0",
":",
"FL",
"=",
"-",
"FL",
"return",
"(",
"FT",
",",
"FD",
",",
"FL",
")"
] | Helper function for MT2Plane.
Adapted from MATLAB script
`bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_
written by Andy Michael and Oliver Boyd. | [
"Helper",
"function",
"for",
"MT2Plane",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L769-L849 | train | 232,889 |
gem/oq-engine | openquake/hmtk/plotting/beachball.py | MT2Axes | def MT2Axes(mt):
"""
Calculates the principal axes of a given moment tensor.
:param mt: :class:`~MomentTensor`
:return: tuple of :class:`~PrincipalAxis` T, N and P
Adapted from ps_tensor / utilmeca.c /
`Generic Mapping Tools (GMT) <http://gmt.soest.hawaii.edu>`_.
"""
(D, V) = np.linalg.eigh(mt.mt)
pl = np.arcsin(-V[0])
az = np.arctan2(V[2], -V[1])
for i in range(0, 3):
if pl[i] <= 0:
pl[i] = -pl[i]
az[i] += np.pi
if az[i] < 0:
az[i] += 2 * np.pi
if az[i] > 2 * np.pi:
az[i] -= 2 * np.pi
pl *= R2D
az *= R2D
T = PrincipalAxis(D[2], az[2], pl[2])
N = PrincipalAxis(D[1], az[1], pl[1])
P = PrincipalAxis(D[0], az[0], pl[0])
return (T, N, P) | python | def MT2Axes(mt):
"""
Calculates the principal axes of a given moment tensor.
:param mt: :class:`~MomentTensor`
:return: tuple of :class:`~PrincipalAxis` T, N and P
Adapted from ps_tensor / utilmeca.c /
`Generic Mapping Tools (GMT) <http://gmt.soest.hawaii.edu>`_.
"""
(D, V) = np.linalg.eigh(mt.mt)
pl = np.arcsin(-V[0])
az = np.arctan2(V[2], -V[1])
for i in range(0, 3):
if pl[i] <= 0:
pl[i] = -pl[i]
az[i] += np.pi
if az[i] < 0:
az[i] += 2 * np.pi
if az[i] > 2 * np.pi:
az[i] -= 2 * np.pi
pl *= R2D
az *= R2D
T = PrincipalAxis(D[2], az[2], pl[2])
N = PrincipalAxis(D[1], az[1], pl[1])
P = PrincipalAxis(D[0], az[0], pl[0])
return (T, N, P) | [
"def",
"MT2Axes",
"(",
"mt",
")",
":",
"(",
"D",
",",
"V",
")",
"=",
"np",
".",
"linalg",
".",
"eigh",
"(",
"mt",
".",
"mt",
")",
"pl",
"=",
"np",
".",
"arcsin",
"(",
"-",
"V",
"[",
"0",
"]",
")",
"az",
"=",
"np",
".",
"arctan2",
"(",
"V",
"[",
"2",
"]",
",",
"-",
"V",
"[",
"1",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"3",
")",
":",
"if",
"pl",
"[",
"i",
"]",
"<=",
"0",
":",
"pl",
"[",
"i",
"]",
"=",
"-",
"pl",
"[",
"i",
"]",
"az",
"[",
"i",
"]",
"+=",
"np",
".",
"pi",
"if",
"az",
"[",
"i",
"]",
"<",
"0",
":",
"az",
"[",
"i",
"]",
"+=",
"2",
"*",
"np",
".",
"pi",
"if",
"az",
"[",
"i",
"]",
">",
"2",
"*",
"np",
".",
"pi",
":",
"az",
"[",
"i",
"]",
"-=",
"2",
"*",
"np",
".",
"pi",
"pl",
"*=",
"R2D",
"az",
"*=",
"R2D",
"T",
"=",
"PrincipalAxis",
"(",
"D",
"[",
"2",
"]",
",",
"az",
"[",
"2",
"]",
",",
"pl",
"[",
"2",
"]",
")",
"N",
"=",
"PrincipalAxis",
"(",
"D",
"[",
"1",
"]",
",",
"az",
"[",
"1",
"]",
",",
"pl",
"[",
"1",
"]",
")",
"P",
"=",
"PrincipalAxis",
"(",
"D",
"[",
"0",
"]",
",",
"az",
"[",
"0",
"]",
",",
"pl",
"[",
"0",
"]",
")",
"return",
"(",
"T",
",",
"N",
",",
"P",
")"
] | Calculates the principal axes of a given moment tensor.
:param mt: :class:`~MomentTensor`
:return: tuple of :class:`~PrincipalAxis` T, N and P
Adapted from ps_tensor / utilmeca.c /
`Generic Mapping Tools (GMT) <http://gmt.soest.hawaii.edu>`_. | [
"Calculates",
"the",
"principal",
"axes",
"of",
"a",
"given",
"moment",
"tensor",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L852-L879 | train | 232,890 |
gem/oq-engine | openquake/hmtk/strain/strain_utils.py | tapered_gutenberg_richter_cdf | def tapered_gutenberg_richter_cdf(moment, moment_threshold, beta,
corner_moment):
'''
Tapered Gutenberg Richter Cumulative Density Function
:param float or numpy.ndarray moment:
Moment for calculation of rate
:param float or numpy.ndarray moment_threshold:
Threshold Moment of the distribution (moment rate essentially!)
:param float beta:
Beta value (b * ln(10.)) of the Tapered Gutenberg-Richter Function
:param float corner_momnet:
Corner moment of the Tapered Gutenberg-Richter Function
:returns:
Cumulative probability of moment release > moment
'''
cdf = np.exp((moment_threshold - moment) / corner_moment)
return ((moment / moment_threshold) ** (-beta)) * cdf | python | def tapered_gutenberg_richter_cdf(moment, moment_threshold, beta,
corner_moment):
'''
Tapered Gutenberg Richter Cumulative Density Function
:param float or numpy.ndarray moment:
Moment for calculation of rate
:param float or numpy.ndarray moment_threshold:
Threshold Moment of the distribution (moment rate essentially!)
:param float beta:
Beta value (b * ln(10.)) of the Tapered Gutenberg-Richter Function
:param float corner_momnet:
Corner moment of the Tapered Gutenberg-Richter Function
:returns:
Cumulative probability of moment release > moment
'''
cdf = np.exp((moment_threshold - moment) / corner_moment)
return ((moment / moment_threshold) ** (-beta)) * cdf | [
"def",
"tapered_gutenberg_richter_cdf",
"(",
"moment",
",",
"moment_threshold",
",",
"beta",
",",
"corner_moment",
")",
":",
"cdf",
"=",
"np",
".",
"exp",
"(",
"(",
"moment_threshold",
"-",
"moment",
")",
"/",
"corner_moment",
")",
"return",
"(",
"(",
"moment",
"/",
"moment_threshold",
")",
"**",
"(",
"-",
"beta",
")",
")",
"*",
"cdf"
] | Tapered Gutenberg Richter Cumulative Density Function
:param float or numpy.ndarray moment:
Moment for calculation of rate
:param float or numpy.ndarray moment_threshold:
Threshold Moment of the distribution (moment rate essentially!)
:param float beta:
Beta value (b * ln(10.)) of the Tapered Gutenberg-Richter Function
:param float corner_momnet:
Corner moment of the Tapered Gutenberg-Richter Function
:returns:
Cumulative probability of moment release > moment | [
"Tapered",
"Gutenberg",
"Richter",
"Cumulative",
"Density",
"Function"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/strain/strain_utils.py#L111-L134 | train | 232,891 |
gem/oq-engine | openquake/hmtk/strain/strain_utils.py | tapered_gutenberg_richter_pdf | def tapered_gutenberg_richter_pdf(moment, moment_threshold, beta,
corner_moment):
'''
Tapered Gutenberg-Richter Probability Density Function
:param float or numpy.ndarray moment:
Moment for calculation of rate
:param float or numpy.ndarray moment_threshold:
Threshold Moment of the distribution (moment rate essentially!)
:param float beta:
Beta value (b * ln(10.)) of the Tapered Gutenberg-Richter Function
:param float corner_momnet:
Corner moment of the Tapered Gutenberg-Richter Function
:returns:
Absolute probability of moment release > moment
'''
return ((beta / moment + 1. / corner_moment) *
tapered_gutenberg_richter_cdf(moment, moment_threshold, beta,
corner_moment)) | python | def tapered_gutenberg_richter_pdf(moment, moment_threshold, beta,
corner_moment):
'''
Tapered Gutenberg-Richter Probability Density Function
:param float or numpy.ndarray moment:
Moment for calculation of rate
:param float or numpy.ndarray moment_threshold:
Threshold Moment of the distribution (moment rate essentially!)
:param float beta:
Beta value (b * ln(10.)) of the Tapered Gutenberg-Richter Function
:param float corner_momnet:
Corner moment of the Tapered Gutenberg-Richter Function
:returns:
Absolute probability of moment release > moment
'''
return ((beta / moment + 1. / corner_moment) *
tapered_gutenberg_richter_cdf(moment, moment_threshold, beta,
corner_moment)) | [
"def",
"tapered_gutenberg_richter_pdf",
"(",
"moment",
",",
"moment_threshold",
",",
"beta",
",",
"corner_moment",
")",
":",
"return",
"(",
"(",
"beta",
"/",
"moment",
"+",
"1.",
"/",
"corner_moment",
")",
"*",
"tapered_gutenberg_richter_cdf",
"(",
"moment",
",",
"moment_threshold",
",",
"beta",
",",
"corner_moment",
")",
")"
] | Tapered Gutenberg-Richter Probability Density Function
:param float or numpy.ndarray moment:
Moment for calculation of rate
:param float or numpy.ndarray moment_threshold:
Threshold Moment of the distribution (moment rate essentially!)
:param float beta:
Beta value (b * ln(10.)) of the Tapered Gutenberg-Richter Function
:param float corner_momnet:
Corner moment of the Tapered Gutenberg-Richter Function
:returns:
Absolute probability of moment release > moment | [
"Tapered",
"Gutenberg",
"-",
"Richter",
"Probability",
"Density",
"Function"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/strain/strain_utils.py#L137-L159 | train | 232,892 |
gem/oq-engine | openquake/engine/export/core.py | makedirs | def makedirs(path):
"""
Make all of the directories in the ``path`` using `os.makedirs`.
"""
if os.path.exists(path):
if not os.path.isdir(path):
# If it's not a directory, we can't do anything.
# This is a problem
raise RuntimeError('%s already exists and is not a directory.'
% path)
else:
os.makedirs(path) | python | def makedirs(path):
"""
Make all of the directories in the ``path`` using `os.makedirs`.
"""
if os.path.exists(path):
if not os.path.isdir(path):
# If it's not a directory, we can't do anything.
# This is a problem
raise RuntimeError('%s already exists and is not a directory.'
% path)
else:
os.makedirs(path) | [
"def",
"makedirs",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"# If it's not a directory, we can't do anything.",
"# This is a problem",
"raise",
"RuntimeError",
"(",
"'%s already exists and is not a directory.'",
"%",
"path",
")",
"else",
":",
"os",
".",
"makedirs",
"(",
"path",
")"
] | Make all of the directories in the ``path`` using `os.makedirs`. | [
"Make",
"all",
"of",
"the",
"directories",
"in",
"the",
"path",
"using",
"os",
".",
"makedirs",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/engine/export/core.py#L80-L91 | train | 232,893 |
gem/oq-engine | openquake/hmtk/seismicity/max_magnitude/base.py | _get_observed_mmax | def _get_observed_mmax(catalogue, config):
'''Check see if observed mmax values are input, if not then take
from the catalogue'''
if config['input_mmax']:
obsmax = config['input_mmax']
if config['input_mmax_uncertainty']:
return config['input_mmax'], config['input_mmax_uncertainty']
else:
raise ValueError('Input mmax uncertainty must be specified!')
max_location = np.argmax(catalogue['magnitude'])
obsmax = catalogue['magnitude'][max_location]
cond = isinstance(catalogue['sigmaMagnitude'], np.ndarray) and \
len(catalogue['sigmaMagnitude']) > 0 and not \
np.all(np.isnan(catalogue['sigmaMagnitude']))
if cond:
if not np.isnan(catalogue['sigmaMagnitude'][max_location]):
return obsmax, catalogue['sigmaMagnitude'][max_location]
else:
print('Uncertainty not given on observed Mmax\n'
'Taking largest magnitude uncertainty found in catalogue')
return obsmax, np.nanmax(catalogue['sigmaMagnitude'])
elif config['input_mmax_uncertainty']:
return obsmax, config['input_mmax_uncertainty']
else:
raise ValueError('Input mmax uncertainty must be specified!') | python | def _get_observed_mmax(catalogue, config):
'''Check see if observed mmax values are input, if not then take
from the catalogue'''
if config['input_mmax']:
obsmax = config['input_mmax']
if config['input_mmax_uncertainty']:
return config['input_mmax'], config['input_mmax_uncertainty']
else:
raise ValueError('Input mmax uncertainty must be specified!')
max_location = np.argmax(catalogue['magnitude'])
obsmax = catalogue['magnitude'][max_location]
cond = isinstance(catalogue['sigmaMagnitude'], np.ndarray) and \
len(catalogue['sigmaMagnitude']) > 0 and not \
np.all(np.isnan(catalogue['sigmaMagnitude']))
if cond:
if not np.isnan(catalogue['sigmaMagnitude'][max_location]):
return obsmax, catalogue['sigmaMagnitude'][max_location]
else:
print('Uncertainty not given on observed Mmax\n'
'Taking largest magnitude uncertainty found in catalogue')
return obsmax, np.nanmax(catalogue['sigmaMagnitude'])
elif config['input_mmax_uncertainty']:
return obsmax, config['input_mmax_uncertainty']
else:
raise ValueError('Input mmax uncertainty must be specified!') | [
"def",
"_get_observed_mmax",
"(",
"catalogue",
",",
"config",
")",
":",
"if",
"config",
"[",
"'input_mmax'",
"]",
":",
"obsmax",
"=",
"config",
"[",
"'input_mmax'",
"]",
"if",
"config",
"[",
"'input_mmax_uncertainty'",
"]",
":",
"return",
"config",
"[",
"'input_mmax'",
"]",
",",
"config",
"[",
"'input_mmax_uncertainty'",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"'Input mmax uncertainty must be specified!'",
")",
"max_location",
"=",
"np",
".",
"argmax",
"(",
"catalogue",
"[",
"'magnitude'",
"]",
")",
"obsmax",
"=",
"catalogue",
"[",
"'magnitude'",
"]",
"[",
"max_location",
"]",
"cond",
"=",
"isinstance",
"(",
"catalogue",
"[",
"'sigmaMagnitude'",
"]",
",",
"np",
".",
"ndarray",
")",
"and",
"len",
"(",
"catalogue",
"[",
"'sigmaMagnitude'",
"]",
")",
">",
"0",
"and",
"not",
"np",
".",
"all",
"(",
"np",
".",
"isnan",
"(",
"catalogue",
"[",
"'sigmaMagnitude'",
"]",
")",
")",
"if",
"cond",
":",
"if",
"not",
"np",
".",
"isnan",
"(",
"catalogue",
"[",
"'sigmaMagnitude'",
"]",
"[",
"max_location",
"]",
")",
":",
"return",
"obsmax",
",",
"catalogue",
"[",
"'sigmaMagnitude'",
"]",
"[",
"max_location",
"]",
"else",
":",
"print",
"(",
"'Uncertainty not given on observed Mmax\\n'",
"'Taking largest magnitude uncertainty found in catalogue'",
")",
"return",
"obsmax",
",",
"np",
".",
"nanmax",
"(",
"catalogue",
"[",
"'sigmaMagnitude'",
"]",
")",
"elif",
"config",
"[",
"'input_mmax_uncertainty'",
"]",
":",
"return",
"obsmax",
",",
"config",
"[",
"'input_mmax_uncertainty'",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"'Input mmax uncertainty must be specified!'",
")"
] | Check see if observed mmax values are input, if not then take
from the catalogue | [
"Check",
"see",
"if",
"observed",
"mmax",
"values",
"are",
"input",
"if",
"not",
"then",
"take",
"from",
"the",
"catalogue"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/max_magnitude/base.py#L57-L83 | train | 232,894 |
gem/oq-engine | openquake/hmtk/seismicity/max_magnitude/base.py | _get_magnitude_vector_properties | def _get_magnitude_vector_properties(catalogue, config):
'''If an input minimum magnitude is given then consider catalogue
only above the minimum magnitude - returns corresponding properties'''
mmin = config.get('input_mmin', np.min(catalogue['magnitude']))
neq = np.float(np.sum(catalogue['magnitude'] >= mmin - 1.E-7))
return neq, mmin | python | def _get_magnitude_vector_properties(catalogue, config):
'''If an input minimum magnitude is given then consider catalogue
only above the minimum magnitude - returns corresponding properties'''
mmin = config.get('input_mmin', np.min(catalogue['magnitude']))
neq = np.float(np.sum(catalogue['magnitude'] >= mmin - 1.E-7))
return neq, mmin | [
"def",
"_get_magnitude_vector_properties",
"(",
"catalogue",
",",
"config",
")",
":",
"mmin",
"=",
"config",
".",
"get",
"(",
"'input_mmin'",
",",
"np",
".",
"min",
"(",
"catalogue",
"[",
"'magnitude'",
"]",
")",
")",
"neq",
"=",
"np",
".",
"float",
"(",
"np",
".",
"sum",
"(",
"catalogue",
"[",
"'magnitude'",
"]",
">=",
"mmin",
"-",
"1.E-7",
")",
")",
"return",
"neq",
",",
"mmin"
] | If an input minimum magnitude is given then consider catalogue
only above the minimum magnitude - returns corresponding properties | [
"If",
"an",
"input",
"minimum",
"magnitude",
"is",
"given",
"then",
"consider",
"catalogue",
"only",
"above",
"the",
"minimum",
"magnitude",
"-",
"returns",
"corresponding",
"properties"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/max_magnitude/base.py#L104-L110 | train | 232,895 |
gem/oq-engine | openquake/hazardlib/geo/surface/complex_fault.py | ComplexFaultSurface.get_dip | def get_dip(self):
"""
Return the fault dip as the average dip over the mesh.
The average dip is defined as the weighted mean inclination
of all the mesh cells. See
:meth:`openquake.hazardlib.geo.mesh.RectangularMesh.get_mean_inclination_and_azimuth`
:returns:
The average dip, in decimal degrees.
"""
# uses the same approach as in simple fault surface
if self.dip is None:
mesh = self.mesh
self.dip, self.strike = mesh.get_mean_inclination_and_azimuth()
return self.dip | python | def get_dip(self):
"""
Return the fault dip as the average dip over the mesh.
The average dip is defined as the weighted mean inclination
of all the mesh cells. See
:meth:`openquake.hazardlib.geo.mesh.RectangularMesh.get_mean_inclination_and_azimuth`
:returns:
The average dip, in decimal degrees.
"""
# uses the same approach as in simple fault surface
if self.dip is None:
mesh = self.mesh
self.dip, self.strike = mesh.get_mean_inclination_and_azimuth()
return self.dip | [
"def",
"get_dip",
"(",
"self",
")",
":",
"# uses the same approach as in simple fault surface",
"if",
"self",
".",
"dip",
"is",
"None",
":",
"mesh",
"=",
"self",
".",
"mesh",
"self",
".",
"dip",
",",
"self",
".",
"strike",
"=",
"mesh",
".",
"get_mean_inclination_and_azimuth",
"(",
")",
"return",
"self",
".",
"dip"
] | Return the fault dip as the average dip over the mesh.
The average dip is defined as the weighted mean inclination
of all the mesh cells. See
:meth:`openquake.hazardlib.geo.mesh.RectangularMesh.get_mean_inclination_and_azimuth`
:returns:
The average dip, in decimal degrees. | [
"Return",
"the",
"fault",
"dip",
"as",
"the",
"average",
"dip",
"over",
"the",
"mesh",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/complex_fault.py#L96-L111 | train | 232,896 |
gem/oq-engine | openquake/hazardlib/geo/surface/complex_fault.py | ComplexFaultSurface.check_surface_validity | def check_surface_validity(cls, edges):
"""
Check validity of the surface.
Project edge points to vertical plane anchored to surface upper left
edge and with strike equal to top edge strike. Check that resulting
polygon is valid.
This method doesn't have to be called by hands before creating the
surface object, because it is called from :meth:`from_fault_data`.
"""
# extract coordinates of surface boundary (as defined from edges)
full_boundary = []
left_boundary = []
right_boundary = []
for i in range(1, len(edges) - 1):
left_boundary.append(edges[i].points[0])
right_boundary.append(edges[i].points[-1])
full_boundary.extend(edges[0].points)
full_boundary.extend(right_boundary)
full_boundary.extend(edges[-1].points[::-1])
full_boundary.extend(left_boundary[::-1])
lons = [p.longitude for p in full_boundary]
lats = [p.latitude for p in full_boundary]
depths = [p.depth for p in full_boundary]
# define reference plane. Corner points are separated by an arbitrary
# distance of 10 km. The mesh spacing is set to 2 km. Both corner
# distance and mesh spacing values do not affect the algorithm results.
ul = edges[0].points[0]
strike = ul.azimuth(edges[0].points[-1])
dist = 10.
ur = ul.point_at(dist, 0, strike)
bl = Point(ul.longitude, ul.latitude, ul.depth + dist)
br = bl.point_at(dist, 0, strike)
# project surface boundary to reference plane and check for
# validity.
ref_plane = PlanarSurface.from_corner_points(ul, ur, br, bl)
_, xx, yy = ref_plane._project(
spherical_to_cartesian(lons, lats, depths))
coords = [(x, y) for x, y in zip(xx, yy)]
p = shapely.geometry.Polygon(coords)
if not p.is_valid:
raise ValueError('Edges points are not in the right order') | python | def check_surface_validity(cls, edges):
"""
Check validity of the surface.
Project edge points to vertical plane anchored to surface upper left
edge and with strike equal to top edge strike. Check that resulting
polygon is valid.
This method doesn't have to be called by hands before creating the
surface object, because it is called from :meth:`from_fault_data`.
"""
# extract coordinates of surface boundary (as defined from edges)
full_boundary = []
left_boundary = []
right_boundary = []
for i in range(1, len(edges) - 1):
left_boundary.append(edges[i].points[0])
right_boundary.append(edges[i].points[-1])
full_boundary.extend(edges[0].points)
full_boundary.extend(right_boundary)
full_boundary.extend(edges[-1].points[::-1])
full_boundary.extend(left_boundary[::-1])
lons = [p.longitude for p in full_boundary]
lats = [p.latitude for p in full_boundary]
depths = [p.depth for p in full_boundary]
# define reference plane. Corner points are separated by an arbitrary
# distance of 10 km. The mesh spacing is set to 2 km. Both corner
# distance and mesh spacing values do not affect the algorithm results.
ul = edges[0].points[0]
strike = ul.azimuth(edges[0].points[-1])
dist = 10.
ur = ul.point_at(dist, 0, strike)
bl = Point(ul.longitude, ul.latitude, ul.depth + dist)
br = bl.point_at(dist, 0, strike)
# project surface boundary to reference plane and check for
# validity.
ref_plane = PlanarSurface.from_corner_points(ul, ur, br, bl)
_, xx, yy = ref_plane._project(
spherical_to_cartesian(lons, lats, depths))
coords = [(x, y) for x, y in zip(xx, yy)]
p = shapely.geometry.Polygon(coords)
if not p.is_valid:
raise ValueError('Edges points are not in the right order') | [
"def",
"check_surface_validity",
"(",
"cls",
",",
"edges",
")",
":",
"# extract coordinates of surface boundary (as defined from edges)",
"full_boundary",
"=",
"[",
"]",
"left_boundary",
"=",
"[",
"]",
"right_boundary",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"edges",
")",
"-",
"1",
")",
":",
"left_boundary",
".",
"append",
"(",
"edges",
"[",
"i",
"]",
".",
"points",
"[",
"0",
"]",
")",
"right_boundary",
".",
"append",
"(",
"edges",
"[",
"i",
"]",
".",
"points",
"[",
"-",
"1",
"]",
")",
"full_boundary",
".",
"extend",
"(",
"edges",
"[",
"0",
"]",
".",
"points",
")",
"full_boundary",
".",
"extend",
"(",
"right_boundary",
")",
"full_boundary",
".",
"extend",
"(",
"edges",
"[",
"-",
"1",
"]",
".",
"points",
"[",
":",
":",
"-",
"1",
"]",
")",
"full_boundary",
".",
"extend",
"(",
"left_boundary",
"[",
":",
":",
"-",
"1",
"]",
")",
"lons",
"=",
"[",
"p",
".",
"longitude",
"for",
"p",
"in",
"full_boundary",
"]",
"lats",
"=",
"[",
"p",
".",
"latitude",
"for",
"p",
"in",
"full_boundary",
"]",
"depths",
"=",
"[",
"p",
".",
"depth",
"for",
"p",
"in",
"full_boundary",
"]",
"# define reference plane. Corner points are separated by an arbitrary",
"# distance of 10 km. The mesh spacing is set to 2 km. Both corner",
"# distance and mesh spacing values do not affect the algorithm results.",
"ul",
"=",
"edges",
"[",
"0",
"]",
".",
"points",
"[",
"0",
"]",
"strike",
"=",
"ul",
".",
"azimuth",
"(",
"edges",
"[",
"0",
"]",
".",
"points",
"[",
"-",
"1",
"]",
")",
"dist",
"=",
"10.",
"ur",
"=",
"ul",
".",
"point_at",
"(",
"dist",
",",
"0",
",",
"strike",
")",
"bl",
"=",
"Point",
"(",
"ul",
".",
"longitude",
",",
"ul",
".",
"latitude",
",",
"ul",
".",
"depth",
"+",
"dist",
")",
"br",
"=",
"bl",
".",
"point_at",
"(",
"dist",
",",
"0",
",",
"strike",
")",
"# project surface boundary to reference plane and check for",
"# validity.",
"ref_plane",
"=",
"PlanarSurface",
".",
"from_corner_points",
"(",
"ul",
",",
"ur",
",",
"br",
",",
"bl",
")",
"_",
",",
"xx",
",",
"yy",
"=",
"ref_plane",
".",
"_project",
"(",
"spherical_to_cartesian",
"(",
"lons",
",",
"lats",
",",
"depths",
")",
")",
"coords",
"=",
"[",
"(",
"x",
",",
"y",
")",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"xx",
",",
"yy",
")",
"]",
"p",
"=",
"shapely",
".",
"geometry",
".",
"Polygon",
"(",
"coords",
")",
"if",
"not",
"p",
".",
"is_valid",
":",
"raise",
"ValueError",
"(",
"'Edges points are not in the right order'",
")"
] | Check validity of the surface.
Project edge points to vertical plane anchored to surface upper left
edge and with strike equal to top edge strike. Check that resulting
polygon is valid.
This method doesn't have to be called by hands before creating the
surface object, because it is called from :meth:`from_fault_data`. | [
"Check",
"validity",
"of",
"the",
"surface",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/complex_fault.py#L182-L230 | train | 232,897 |
gem/oq-engine | openquake/hazardlib/geo/surface/complex_fault.py | ComplexFaultSurface.surface_projection_from_fault_data | def surface_projection_from_fault_data(cls, edges):
"""
Get a surface projection of the complex fault surface.
:param edges:
A list of horizontal edges of the surface as instances
of :class:`openquake.hazardlib.geo.line.Line`.
:returns:
Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon`
describing the surface projection of the complex fault.
"""
# collect lons and lats of all the vertices of all the edges
lons = []
lats = []
for edge in edges:
for point in edge:
lons.append(point.longitude)
lats.append(point.latitude)
lons = numpy.array(lons, dtype=float)
lats = numpy.array(lats, dtype=float)
return Mesh(lons, lats, depths=None).get_convex_hull() | python | def surface_projection_from_fault_data(cls, edges):
"""
Get a surface projection of the complex fault surface.
:param edges:
A list of horizontal edges of the surface as instances
of :class:`openquake.hazardlib.geo.line.Line`.
:returns:
Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon`
describing the surface projection of the complex fault.
"""
# collect lons and lats of all the vertices of all the edges
lons = []
lats = []
for edge in edges:
for point in edge:
lons.append(point.longitude)
lats.append(point.latitude)
lons = numpy.array(lons, dtype=float)
lats = numpy.array(lats, dtype=float)
return Mesh(lons, lats, depths=None).get_convex_hull() | [
"def",
"surface_projection_from_fault_data",
"(",
"cls",
",",
"edges",
")",
":",
"# collect lons and lats of all the vertices of all the edges",
"lons",
"=",
"[",
"]",
"lats",
"=",
"[",
"]",
"for",
"edge",
"in",
"edges",
":",
"for",
"point",
"in",
"edge",
":",
"lons",
".",
"append",
"(",
"point",
".",
"longitude",
")",
"lats",
".",
"append",
"(",
"point",
".",
"latitude",
")",
"lons",
"=",
"numpy",
".",
"array",
"(",
"lons",
",",
"dtype",
"=",
"float",
")",
"lats",
"=",
"numpy",
".",
"array",
"(",
"lats",
",",
"dtype",
"=",
"float",
")",
"return",
"Mesh",
"(",
"lons",
",",
"lats",
",",
"depths",
"=",
"None",
")",
".",
"get_convex_hull",
"(",
")"
] | Get a surface projection of the complex fault surface.
:param edges:
A list of horizontal edges of the surface as instances
of :class:`openquake.hazardlib.geo.line.Line`.
:returns:
Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon`
describing the surface projection of the complex fault. | [
"Get",
"a",
"surface",
"projection",
"of",
"the",
"complex",
"fault",
"surface",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/complex_fault.py#L302-L323 | train | 232,898 |
gem/oq-engine | openquake/calculators/base.py | check_time_event | def check_time_event(oqparam, occupancy_periods):
"""
Check the `time_event` parameter in the datastore, by comparing
with the periods found in the exposure.
"""
time_event = oqparam.time_event
if time_event and time_event not in occupancy_periods:
raise ValueError(
'time_event is %s in %s, but the exposure contains %s' %
(time_event, oqparam.inputs['job_ini'],
', '.join(occupancy_periods))) | python | def check_time_event(oqparam, occupancy_periods):
"""
Check the `time_event` parameter in the datastore, by comparing
with the periods found in the exposure.
"""
time_event = oqparam.time_event
if time_event and time_event not in occupancy_periods:
raise ValueError(
'time_event is %s in %s, but the exposure contains %s' %
(time_event, oqparam.inputs['job_ini'],
', '.join(occupancy_periods))) | [
"def",
"check_time_event",
"(",
"oqparam",
",",
"occupancy_periods",
")",
":",
"time_event",
"=",
"oqparam",
".",
"time_event",
"if",
"time_event",
"and",
"time_event",
"not",
"in",
"occupancy_periods",
":",
"raise",
"ValueError",
"(",
"'time_event is %s in %s, but the exposure contains %s'",
"%",
"(",
"time_event",
",",
"oqparam",
".",
"inputs",
"[",
"'job_ini'",
"]",
",",
"', '",
".",
"join",
"(",
"occupancy_periods",
")",
")",
")"
] | Check the `time_event` parameter in the datastore, by comparing
with the periods found in the exposure. | [
"Check",
"the",
"time_event",
"parameter",
"in",
"the",
"datastore",
"by",
"comparing",
"with",
"the",
"periods",
"found",
"in",
"the",
"exposure",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L321-L331 | train | 232,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.