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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMAAdaptSigmaBase._update_ps | def _update_ps(self, es):
"""update the isotropic evolution path
:type es: CMAEvolutionStrategy
"""
if not self.is_initialized_base:
self.initialize_base(es)
if self._ps_updated_iteration == es.countiter:
return
if es.countiter <= es.itereigenupdated:
# es.B and es.D must/should be those from the last iteration
assert es.countiter >= es.itereigenupdated
_print_warning('distribution transformation (B and D) have been updated before ps could be computed',
'_update_ps', 'CMAAdaptSigmaBase')
z = dot(es.B, (1. / es.D) * dot(es.B.T, (es.mean - es.mean_old) / es.sigma_vec))
z *= es.sp.mueff**0.5 / es.sigma / es.sp.cmean
self.ps = (1 - self.cs) * self.ps + sqrt(self.cs * (2 - self.cs)) * z
self._ps_updated_iteration = es.countiter | python | def _update_ps(self, es):
"""update the isotropic evolution path
:type es: CMAEvolutionStrategy
"""
if not self.is_initialized_base:
self.initialize_base(es)
if self._ps_updated_iteration == es.countiter:
return
if es.countiter <= es.itereigenupdated:
# es.B and es.D must/should be those from the last iteration
assert es.countiter >= es.itereigenupdated
_print_warning('distribution transformation (B and D) have been updated before ps could be computed',
'_update_ps', 'CMAAdaptSigmaBase')
z = dot(es.B, (1. / es.D) * dot(es.B.T, (es.mean - es.mean_old) / es.sigma_vec))
z *= es.sp.mueff**0.5 / es.sigma / es.sp.cmean
self.ps = (1 - self.cs) * self.ps + sqrt(self.cs * (2 - self.cs)) * z
self._ps_updated_iteration = es.countiter | [
"def",
"_update_ps",
"(",
"self",
",",
"es",
")",
":",
"if",
"not",
"self",
".",
"is_initialized_base",
":",
"self",
".",
"initialize_base",
"(",
"es",
")",
"if",
"self",
".",
"_ps_updated_iteration",
"==",
"es",
".",
"countiter",
":",
"return",
"if",
"e... | update the isotropic evolution path
:type es: CMAEvolutionStrategy | [
"update",
"the",
"isotropic",
"evolution",
"path"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L2131-L2148 | train | 32,500 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMAEvolutionStrategy.stop | def stop(self, check=True):
"""return a dictionary with the termination status.
With ``check==False``, the termination conditions are not checked
and the status might not reflect the current situation.
"""
if (check and self.countiter > 0 and self.opts['termination_callback'] and
self.opts['termination_callback'] != str(self.opts['termination_callback'])):
self.callbackstop = self.opts['termination_callback'](self)
return self._stopdict(self, check) | python | def stop(self, check=True):
"""return a dictionary with the termination status.
With ``check==False``, the termination conditions are not checked
and the status might not reflect the current situation.
"""
if (check and self.countiter > 0 and self.opts['termination_callback'] and
self.opts['termination_callback'] != str(self.opts['termination_callback'])):
self.callbackstop = self.opts['termination_callback'](self)
return self._stopdict(self, check) | [
"def",
"stop",
"(",
"self",
",",
"check",
"=",
"True",
")",
":",
"if",
"(",
"check",
"and",
"self",
".",
"countiter",
">",
"0",
"and",
"self",
".",
"opts",
"[",
"'termination_callback'",
"]",
"and",
"self",
".",
"opts",
"[",
"'termination_callback'",
"... | return a dictionary with the termination status.
With ``check==False``, the termination conditions are not checked
and the status might not reflect the current situation. | [
"return",
"a",
"dictionary",
"with",
"the",
"termination",
"status",
".",
"With",
"check",
"==",
"False",
"the",
"termination",
"conditions",
"are",
"not",
"checked",
"and",
"the",
"status",
"might",
"not",
"reflect",
"the",
"current",
"situation",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L2741-L2751 | train | 32,501 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMAEvolutionStrategy.random_rescale_to_mahalanobis | def random_rescale_to_mahalanobis(self, x):
"""change `x` like for injection, all on genotypic level"""
x -= self.mean
if any(x):
x *= sum(self.randn(len(x))**2)**0.5 / self.mahalanobis_norm(x)
x += self.mean
return x | python | def random_rescale_to_mahalanobis(self, x):
"""change `x` like for injection, all on genotypic level"""
x -= self.mean
if any(x):
x *= sum(self.randn(len(x))**2)**0.5 / self.mahalanobis_norm(x)
x += self.mean
return x | [
"def",
"random_rescale_to_mahalanobis",
"(",
"self",
",",
"x",
")",
":",
"x",
"-=",
"self",
".",
"mean",
"if",
"any",
"(",
"x",
")",
":",
"x",
"*=",
"sum",
"(",
"self",
".",
"randn",
"(",
"len",
"(",
"x",
")",
")",
"**",
"2",
")",
"**",
"0.5",
... | change `x` like for injection, all on genotypic level | [
"change",
"x",
"like",
"for",
"injection",
"all",
"on",
"genotypic",
"level"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L3252-L3258 | train | 32,502 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMAEvolutionStrategy.prepare_injection_directions | def prepare_injection_directions(self):
"""provide genotypic directions for TPA and selective mirroring,
with no specific length normalization, to be used in the
coming iteration.
Details:
This method is called in the end of `tell`. The result is
assigned to ``self.pop_injection_directions`` and used in
`ask_geno`.
TODO: should be rather appended?
"""
# self.pop_injection_directions is supposed to be empty here
if hasattr(self, 'pop_injection_directions') and self.pop_injection_directions:
ValueError("Looks like a bug in calling order/logics")
ary = []
if (isinstance(self.adapt_sigma, CMAAdaptSigmaTPA) or
self.opts['mean_shift_line_samples']):
ary.append(self.mean - self.mean_old)
ary.append(self.mean_old - self.mean) # another copy!
if ary[-1][0] == 0.0:
_print_warning('zero mean shift encountered which ',
'prepare_injection_directions',
'CMAEvolutionStrategy', self.countiter)
if self.opts['pc_line_samples']: # caveat: before, two samples were used
ary.append(self.pc.copy())
if self.sp.lam_mirr and self.opts['CMA_mirrormethod'] == 2:
if self.pop_sorted is None:
_print_warning('pop_sorted attribute not found, mirrors obmitted',
'prepare_injection_directions',
iteration=self.countiter)
else:
ary += self.get_selective_mirrors()
self.pop_injection_directions = ary
return ary | python | def prepare_injection_directions(self):
"""provide genotypic directions for TPA and selective mirroring,
with no specific length normalization, to be used in the
coming iteration.
Details:
This method is called in the end of `tell`. The result is
assigned to ``self.pop_injection_directions`` and used in
`ask_geno`.
TODO: should be rather appended?
"""
# self.pop_injection_directions is supposed to be empty here
if hasattr(self, 'pop_injection_directions') and self.pop_injection_directions:
ValueError("Looks like a bug in calling order/logics")
ary = []
if (isinstance(self.adapt_sigma, CMAAdaptSigmaTPA) or
self.opts['mean_shift_line_samples']):
ary.append(self.mean - self.mean_old)
ary.append(self.mean_old - self.mean) # another copy!
if ary[-1][0] == 0.0:
_print_warning('zero mean shift encountered which ',
'prepare_injection_directions',
'CMAEvolutionStrategy', self.countiter)
if self.opts['pc_line_samples']: # caveat: before, two samples were used
ary.append(self.pc.copy())
if self.sp.lam_mirr and self.opts['CMA_mirrormethod'] == 2:
if self.pop_sorted is None:
_print_warning('pop_sorted attribute not found, mirrors obmitted',
'prepare_injection_directions',
iteration=self.countiter)
else:
ary += self.get_selective_mirrors()
self.pop_injection_directions = ary
return ary | [
"def",
"prepare_injection_directions",
"(",
"self",
")",
":",
"# self.pop_injection_directions is supposed to be empty here",
"if",
"hasattr",
"(",
"self",
",",
"'pop_injection_directions'",
")",
"and",
"self",
".",
"pop_injection_directions",
":",
"ValueError",
"(",
"\"Loo... | provide genotypic directions for TPA and selective mirroring,
with no specific length normalization, to be used in the
coming iteration.
Details:
This method is called in the end of `tell`. The result is
assigned to ``self.pop_injection_directions`` and used in
`ask_geno`.
TODO: should be rather appended? | [
"provide",
"genotypic",
"directions",
"for",
"TPA",
"and",
"selective",
"mirroring",
"with",
"no",
"specific",
"length",
"normalization",
"to",
"be",
"used",
"in",
"the",
"coming",
"iteration",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L3492-L3527 | train | 32,503 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMAEvolutionStrategy.inject | def inject(self, solutions):
"""inject a genotypic solution. The solution is used as direction
relative to the distribution mean to compute a new candidate
solution returned in method `ask_geno` which in turn is used in
method `ask`.
>>> import cma
>>> es = cma.CMAEvolutionStrategy(4 * [1], 2)
>>> while not es.stop():
... es.inject([4 * [0.0]])
... X = es.ask()
... break
>>> assert X[0][0] == X[0][1]
"""
if not hasattr(self, 'pop_injection_directions'):
self.pop_injection_directions = []
for solution in solutions:
if len(solution) != self.N:
raise ValueError('method `inject` needs a list or array'
+ (' each el with dimension (`len`) %d' % self.N))
self.pop_injection_directions.append(
array(solution, copy=False, dtype=float) - self.mean) | python | def inject(self, solutions):
"""inject a genotypic solution. The solution is used as direction
relative to the distribution mean to compute a new candidate
solution returned in method `ask_geno` which in turn is used in
method `ask`.
>>> import cma
>>> es = cma.CMAEvolutionStrategy(4 * [1], 2)
>>> while not es.stop():
... es.inject([4 * [0.0]])
... X = es.ask()
... break
>>> assert X[0][0] == X[0][1]
"""
if not hasattr(self, 'pop_injection_directions'):
self.pop_injection_directions = []
for solution in solutions:
if len(solution) != self.N:
raise ValueError('method `inject` needs a list or array'
+ (' each el with dimension (`len`) %d' % self.N))
self.pop_injection_directions.append(
array(solution, copy=False, dtype=float) - self.mean) | [
"def",
"inject",
"(",
"self",
",",
"solutions",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'pop_injection_directions'",
")",
":",
"self",
".",
"pop_injection_directions",
"=",
"[",
"]",
"for",
"solution",
"in",
"solutions",
":",
"if",
"len",
"(",... | inject a genotypic solution. The solution is used as direction
relative to the distribution mean to compute a new candidate
solution returned in method `ask_geno` which in turn is used in
method `ask`.
>>> import cma
>>> es = cma.CMAEvolutionStrategy(4 * [1], 2)
>>> while not es.stop():
... es.inject([4 * [0.0]])
... X = es.ask()
... break
>>> assert X[0][0] == X[0][1] | [
"inject",
"a",
"genotypic",
"solution",
".",
"The",
"solution",
"is",
"used",
"as",
"direction",
"relative",
"to",
"the",
"distribution",
"mean",
"to",
"compute",
"a",
"new",
"candidate",
"solution",
"returned",
"in",
"method",
"ask_geno",
"which",
"in",
"turn... | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L3863-L3885 | train | 32,504 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMAEvolutionStrategy.result_pretty | def result_pretty(self, number_of_runs=0, time_str=None,
fbestever=None):
"""pretty print result.
Returns ``self.result()``
"""
if fbestever is None:
fbestever = self.best.f
s = (' after %i restart' + ('s' if number_of_runs > 1 else '')) \
% number_of_runs if number_of_runs else ''
for k, v in self.stop().items():
print('termination on %s=%s%s' % (k, str(v), s +
(' (%s)' % time_str if time_str else '')))
print('final/bestever f-value = %e %e' % (self.best.last.f,
fbestever))
if self.N < 9:
print('incumbent solution: ' + str(list(self.gp.pheno(self.mean, into_bounds=self.boundary_handler.repair))))
print('std deviation: ' + str(list(self.sigma * self.sigma_vec * sqrt(self.dC) * self.gp.scales)))
else:
print('incumbent solution: %s ...]' % (str(self.gp.pheno(self.mean, into_bounds=self.boundary_handler.repair)[:8])[:-1]))
print('std deviations: %s ...]' % (str((self.sigma * self.sigma_vec * sqrt(self.dC) * self.gp.scales)[:8])[:-1]))
return self.result() | python | def result_pretty(self, number_of_runs=0, time_str=None,
fbestever=None):
"""pretty print result.
Returns ``self.result()``
"""
if fbestever is None:
fbestever = self.best.f
s = (' after %i restart' + ('s' if number_of_runs > 1 else '')) \
% number_of_runs if number_of_runs else ''
for k, v in self.stop().items():
print('termination on %s=%s%s' % (k, str(v), s +
(' (%s)' % time_str if time_str else '')))
print('final/bestever f-value = %e %e' % (self.best.last.f,
fbestever))
if self.N < 9:
print('incumbent solution: ' + str(list(self.gp.pheno(self.mean, into_bounds=self.boundary_handler.repair))))
print('std deviation: ' + str(list(self.sigma * self.sigma_vec * sqrt(self.dC) * self.gp.scales)))
else:
print('incumbent solution: %s ...]' % (str(self.gp.pheno(self.mean, into_bounds=self.boundary_handler.repair)[:8])[:-1]))
print('std deviations: %s ...]' % (str((self.sigma * self.sigma_vec * sqrt(self.dC) * self.gp.scales)[:8])[:-1]))
return self.result() | [
"def",
"result_pretty",
"(",
"self",
",",
"number_of_runs",
"=",
"0",
",",
"time_str",
"=",
"None",
",",
"fbestever",
"=",
"None",
")",
":",
"if",
"fbestever",
"is",
"None",
":",
"fbestever",
"=",
"self",
".",
"best",
".",
"f",
"s",
"=",
"(",
"' afte... | pretty print result.
Returns ``self.result()`` | [
"pretty",
"print",
"result",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L3898-L3921 | train | 32,505 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMAEvolutionStrategy.clip_or_fit_solutions | def clip_or_fit_solutions(self, pop, idx):
"""make sure that solutions fit to sample distribution, this interface will probably change.
In particular the frequency of long vectors appearing in pop[idx] - self.mean is limited.
"""
for k in idx:
self.repair_genotype(pop[k]) | python | def clip_or_fit_solutions(self, pop, idx):
"""make sure that solutions fit to sample distribution, this interface will probably change.
In particular the frequency of long vectors appearing in pop[idx] - self.mean is limited.
"""
for k in idx:
self.repair_genotype(pop[k]) | [
"def",
"clip_or_fit_solutions",
"(",
"self",
",",
"pop",
",",
"idx",
")",
":",
"for",
"k",
"in",
"idx",
":",
"self",
".",
"repair_genotype",
"(",
"pop",
"[",
"k",
"]",
")"
] | make sure that solutions fit to sample distribution, this interface will probably change.
In particular the frequency of long vectors appearing in pop[idx] - self.mean is limited. | [
"make",
"sure",
"that",
"solutions",
"fit",
"to",
"sample",
"distribution",
"this",
"interface",
"will",
"probably",
"change",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L3923-L3930 | train | 32,506 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMAEvolutionStrategy.repair_genotype | def repair_genotype(self, x, copy_if_changed=False):
"""make sure that solutions fit to the sample distribution, this interface will probably change.
In particular the frequency of x - self.mean being long is limited.
"""
x = array(x, copy=False)
mold = array(self.mean, copy=False)
if 1 < 3: # hard clip at upper_length
upper_length = self.N**0.5 + 2 * self.N / (self.N + 2) # should become an Option, but how? e.g. [0, 2, 2]
fac = self.mahalanobis_norm(x - mold) / upper_length
if fac > 1:
if copy_if_changed:
x = (x - mold) / fac + mold
else: # should be 25% faster:
x -= mold
x /= fac
x += mold
# print self.countiter, k, fac, self.mahalanobis_norm(pop[k] - mold)
# adapt also sigma: which are the trust-worthy/injected solutions?
else:
if 'checktail' not in self.__dict__: # hasattr(self, 'checktail')
raise NotImplementedError
# from check_tail_smooth import CheckTail # for the time being
# self.checktail = CheckTail()
# print('untested feature checktail is on')
fac = self.checktail.addchin(self.mahalanobis_norm(x - mold))
if fac < 1:
x = fac * (x - mold) + mold
return x | python | def repair_genotype(self, x, copy_if_changed=False):
"""make sure that solutions fit to the sample distribution, this interface will probably change.
In particular the frequency of x - self.mean being long is limited.
"""
x = array(x, copy=False)
mold = array(self.mean, copy=False)
if 1 < 3: # hard clip at upper_length
upper_length = self.N**0.5 + 2 * self.N / (self.N + 2) # should become an Option, but how? e.g. [0, 2, 2]
fac = self.mahalanobis_norm(x - mold) / upper_length
if fac > 1:
if copy_if_changed:
x = (x - mold) / fac + mold
else: # should be 25% faster:
x -= mold
x /= fac
x += mold
# print self.countiter, k, fac, self.mahalanobis_norm(pop[k] - mold)
# adapt also sigma: which are the trust-worthy/injected solutions?
else:
if 'checktail' not in self.__dict__: # hasattr(self, 'checktail')
raise NotImplementedError
# from check_tail_smooth import CheckTail # for the time being
# self.checktail = CheckTail()
# print('untested feature checktail is on')
fac = self.checktail.addchin(self.mahalanobis_norm(x - mold))
if fac < 1:
x = fac * (x - mold) + mold
return x | [
"def",
"repair_genotype",
"(",
"self",
",",
"x",
",",
"copy_if_changed",
"=",
"False",
")",
":",
"x",
"=",
"array",
"(",
"x",
",",
"copy",
"=",
"False",
")",
"mold",
"=",
"array",
"(",
"self",
".",
"mean",
",",
"copy",
"=",
"False",
")",
"if",
"1... | make sure that solutions fit to the sample distribution, this interface will probably change.
In particular the frequency of x - self.mean being long is limited. | [
"make",
"sure",
"that",
"solutions",
"fit",
"to",
"the",
"sample",
"distribution",
"this",
"interface",
"will",
"probably",
"change",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L3932-L3964 | train | 32,507 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMAEvolutionStrategy.decompose_C | def decompose_C(self):
"""eigen-decompose self.C and update self.dC, self.C, self.B.
Known bugs: this might give a runtime error with
CMA_diagonal / separable option on.
"""
if self.opts['CMA_diagonal']:
_print_warning("this might fail with CMA_diagonal option on",
iteration=self.countiter)
print(self.opts['CMA_diagonal'])
# print(' %.19e' % self.C[0][0])
self.C = (self.C + self.C.T) / 2
self.dC = np.diag(self.C).copy()
self.D, self.B = self.opts['CMA_eigenmethod'](self.C)
# self.B = np.round(self.B, 10)
# for i in rglen(self.D):
# d = self.D[i]
# oom = np.round(np.log10(d))
# self.D[i] = 10**oom * np.round(d / 10**oom, 10)
# print(' %.19e' % self.C[0][0])
# print(' %.19e' % self.D[0])
if any(self.D <= 0):
_print_warning("ERROR", iteration=self.countiter)
raise ValueError("covariance matrix was not positive definite," +
" this must be considered as a bug")
self.D = self.D**0.5
assert all(isfinite(self.D))
idx = np.argsort(self.D)
self.D = self.D[idx]
self.B = self.B[:, idx] # self.B[i] is a row, columns self.B[:,i] are eigenvectors
self.count_eigen += 1 | python | def decompose_C(self):
"""eigen-decompose self.C and update self.dC, self.C, self.B.
Known bugs: this might give a runtime error with
CMA_diagonal / separable option on.
"""
if self.opts['CMA_diagonal']:
_print_warning("this might fail with CMA_diagonal option on",
iteration=self.countiter)
print(self.opts['CMA_diagonal'])
# print(' %.19e' % self.C[0][0])
self.C = (self.C + self.C.T) / 2
self.dC = np.diag(self.C).copy()
self.D, self.B = self.opts['CMA_eigenmethod'](self.C)
# self.B = np.round(self.B, 10)
# for i in rglen(self.D):
# d = self.D[i]
# oom = np.round(np.log10(d))
# self.D[i] = 10**oom * np.round(d / 10**oom, 10)
# print(' %.19e' % self.C[0][0])
# print(' %.19e' % self.D[0])
if any(self.D <= 0):
_print_warning("ERROR", iteration=self.countiter)
raise ValueError("covariance matrix was not positive definite," +
" this must be considered as a bug")
self.D = self.D**0.5
assert all(isfinite(self.D))
idx = np.argsort(self.D)
self.D = self.D[idx]
self.B = self.B[:, idx] # self.B[i] is a row, columns self.B[:,i] are eigenvectors
self.count_eigen += 1 | [
"def",
"decompose_C",
"(",
"self",
")",
":",
"if",
"self",
".",
"opts",
"[",
"'CMA_diagonal'",
"]",
":",
"_print_warning",
"(",
"\"this might fail with CMA_diagonal option on\"",
",",
"iteration",
"=",
"self",
".",
"countiter",
")",
"print",
"(",
"self",
".",
... | eigen-decompose self.C and update self.dC, self.C, self.B.
Known bugs: this might give a runtime error with
CMA_diagonal / separable option on. | [
"eigen",
"-",
"decompose",
"self",
".",
"C",
"and",
"update",
"self",
".",
"dC",
"self",
".",
"C",
"self",
".",
"B",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L3966-L3998 | train | 32,508 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMAEvolutionStrategy.feedForResume | def feedForResume(self, X, function_values):
"""Given all "previous" candidate solutions and their respective
function values, the state of a `CMAEvolutionStrategy` object
can be reconstructed from this history. This is the purpose of
function `feedForResume`.
Arguments
---------
`X`
(all) solution points in chronological order, phenotypic
representation. The number of points must be a multiple
of popsize.
`function_values`
respective objective function values
Details
-------
`feedForResume` can be called repeatedly with only parts of
the history. The part must have the length of a multiple
of the population size.
`feedForResume` feeds the history in popsize-chunks into `tell`.
The state of the random number generator might not be
reconstructed, but this would be only relevant for the future.
Example
-------
::
import cma
# prepare
(x0, sigma0) = ... # initial values from previous trial
X = ... # list of generated solutions from a previous trial
f = ... # respective list of f-values
# resume
es = cma.CMAEvolutionStrategy(x0, sigma0)
es.feedForResume(X, f)
# continue with func as objective function
while not es.stop():
X = es.ask()
es.tell(X, [func(x) for x in X])
Credits to Dirk Bueche and Fabrice Marchal for the feeding idea.
:See: class `CMAEvolutionStrategy` for a simple dump/load to resume
"""
if self.countiter > 0:
_print_warning('feed should generally be used with a new object instance')
if len(X) != len(function_values):
raise _Error('number of solutions ' + str(len(X)) +
' and number function values ' +
str(len(function_values)) + ' must not differ')
popsize = self.sp.popsize
if (len(X) % popsize) != 0:
raise _Error('number of solutions ' + str(len(X)) +
' must be a multiple of popsize (lambda) ' +
str(popsize))
for i in rglen((X) / popsize):
# feed in chunks of size popsize
self.ask() # a fake ask, mainly for a conditioned calling of updateBD
# and secondary to get possibly the same random state
self.tell(X[i * popsize:(i + 1) * popsize], function_values[i * popsize:(i + 1) * popsize]) | python | def feedForResume(self, X, function_values):
"""Given all "previous" candidate solutions and their respective
function values, the state of a `CMAEvolutionStrategy` object
can be reconstructed from this history. This is the purpose of
function `feedForResume`.
Arguments
---------
`X`
(all) solution points in chronological order, phenotypic
representation. The number of points must be a multiple
of popsize.
`function_values`
respective objective function values
Details
-------
`feedForResume` can be called repeatedly with only parts of
the history. The part must have the length of a multiple
of the population size.
`feedForResume` feeds the history in popsize-chunks into `tell`.
The state of the random number generator might not be
reconstructed, but this would be only relevant for the future.
Example
-------
::
import cma
# prepare
(x0, sigma0) = ... # initial values from previous trial
X = ... # list of generated solutions from a previous trial
f = ... # respective list of f-values
# resume
es = cma.CMAEvolutionStrategy(x0, sigma0)
es.feedForResume(X, f)
# continue with func as objective function
while not es.stop():
X = es.ask()
es.tell(X, [func(x) for x in X])
Credits to Dirk Bueche and Fabrice Marchal for the feeding idea.
:See: class `CMAEvolutionStrategy` for a simple dump/load to resume
"""
if self.countiter > 0:
_print_warning('feed should generally be used with a new object instance')
if len(X) != len(function_values):
raise _Error('number of solutions ' + str(len(X)) +
' and number function values ' +
str(len(function_values)) + ' must not differ')
popsize = self.sp.popsize
if (len(X) % popsize) != 0:
raise _Error('number of solutions ' + str(len(X)) +
' must be a multiple of popsize (lambda) ' +
str(popsize))
for i in rglen((X) / popsize):
# feed in chunks of size popsize
self.ask() # a fake ask, mainly for a conditioned calling of updateBD
# and secondary to get possibly the same random state
self.tell(X[i * popsize:(i + 1) * popsize], function_values[i * popsize:(i + 1) * popsize]) | [
"def",
"feedForResume",
"(",
"self",
",",
"X",
",",
"function_values",
")",
":",
"if",
"self",
".",
"countiter",
">",
"0",
":",
"_print_warning",
"(",
"'feed should generally be used with a new object instance'",
")",
"if",
"len",
"(",
"X",
")",
"!=",
"len",
"... | Given all "previous" candidate solutions and their respective
function values, the state of a `CMAEvolutionStrategy` object
can be reconstructed from this history. This is the purpose of
function `feedForResume`.
Arguments
---------
`X`
(all) solution points in chronological order, phenotypic
representation. The number of points must be a multiple
of popsize.
`function_values`
respective objective function values
Details
-------
`feedForResume` can be called repeatedly with only parts of
the history. The part must have the length of a multiple
of the population size.
`feedForResume` feeds the history in popsize-chunks into `tell`.
The state of the random number generator might not be
reconstructed, but this would be only relevant for the future.
Example
-------
::
import cma
# prepare
(x0, sigma0) = ... # initial values from previous trial
X = ... # list of generated solutions from a previous trial
f = ... # respective list of f-values
# resume
es = cma.CMAEvolutionStrategy(x0, sigma0)
es.feedForResume(X, f)
# continue with func as objective function
while not es.stop():
X = es.ask()
es.tell(X, [func(x) for x in X])
Credits to Dirk Bueche and Fabrice Marchal for the feeding idea.
:See: class `CMAEvolutionStrategy` for a simple dump/load to resume | [
"Given",
"all",
"previous",
"candidate",
"solutions",
"and",
"their",
"respective",
"function",
"values",
"the",
"state",
"of",
"a",
"CMAEvolutionStrategy",
"object",
"can",
"be",
"reconstructed",
"from",
"this",
"history",
".",
"This",
"is",
"the",
"purpose",
"... | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L4162-L4226 | train | 32,509 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMAOptions.defaults | def defaults():
"""return a dictionary with default option values and description"""
return dict((str(k), str(v)) for k, v in cma_default_options.items()) | python | def defaults():
"""return a dictionary with default option values and description"""
return dict((str(k), str(v)) for k, v in cma_default_options.items()) | [
"def",
"defaults",
"(",
")",
":",
"return",
"dict",
"(",
"(",
"str",
"(",
"k",
")",
",",
"str",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"cma_default_options",
".",
"items",
"(",
")",
")"
] | return a dictionary with default option values and description | [
"return",
"a",
"dictionary",
"with",
"default",
"option",
"values",
"and",
"description"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L4445-L4447 | train | 32,510 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMAOptions.check | def check(self, options=None):
"""check for ambiguous keys and move attributes into dict"""
self.check_values(options)
self.check_attributes(options)
self.check_values(options)
return self | python | def check(self, options=None):
"""check for ambiguous keys and move attributes into dict"""
self.check_values(options)
self.check_attributes(options)
self.check_values(options)
return self | [
"def",
"check",
"(",
"self",
",",
"options",
"=",
"None",
")",
":",
"self",
".",
"check_values",
"(",
"options",
")",
"self",
".",
"check_attributes",
"(",
"options",
")",
"self",
".",
"check_values",
"(",
"options",
")",
"return",
"self"
] | check for ambiguous keys and move attributes into dict | [
"check",
"for",
"ambiguous",
"keys",
"and",
"move",
"attributes",
"into",
"dict"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L4462-L4467 | train | 32,511 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMAOptions.init | def init(self, dict_or_str, val=None, warn=True):
"""initialize one or several options.
Arguments
---------
`dict_or_str`
a dictionary if ``val is None``, otherwise a key.
If `val` is provided `dict_or_str` must be a valid key.
`val`
value for key
Details
-------
Only known keys are accepted. Known keys are in `CMAOptions.defaults()`
"""
# dic = dict_or_key if val is None else {dict_or_key:val}
self.check(dict_or_str)
dic = dict_or_str
if val is not None:
dic = {dict_or_str:val}
for key, val in dic.items():
key = self.corrected_key(key)
if key not in CMAOptions.defaults():
# TODO: find a better solution?
if warn:
print('Warning in cma.CMAOptions.init(): key ' +
str(key) + ' ignored')
else:
self[key] = val
return self | python | def init(self, dict_or_str, val=None, warn=True):
"""initialize one or several options.
Arguments
---------
`dict_or_str`
a dictionary if ``val is None``, otherwise a key.
If `val` is provided `dict_or_str` must be a valid key.
`val`
value for key
Details
-------
Only known keys are accepted. Known keys are in `CMAOptions.defaults()`
"""
# dic = dict_or_key if val is None else {dict_or_key:val}
self.check(dict_or_str)
dic = dict_or_str
if val is not None:
dic = {dict_or_str:val}
for key, val in dic.items():
key = self.corrected_key(key)
if key not in CMAOptions.defaults():
# TODO: find a better solution?
if warn:
print('Warning in cma.CMAOptions.init(): key ' +
str(key) + ' ignored')
else:
self[key] = val
return self | [
"def",
"init",
"(",
"self",
",",
"dict_or_str",
",",
"val",
"=",
"None",
",",
"warn",
"=",
"True",
")",
":",
"# dic = dict_or_key if val is None else {dict_or_key:val}",
"self",
".",
"check",
"(",
"dict_or_str",
")",
"dic",
"=",
"dict_or_str",
"if",
"val",
"is... | initialize one or several options.
Arguments
---------
`dict_or_str`
a dictionary if ``val is None``, otherwise a key.
If `val` is provided `dict_or_str` must be a valid key.
`val`
value for key
Details
-------
Only known keys are accepted. Known keys are in `CMAOptions.defaults()` | [
"initialize",
"one",
"or",
"several",
"options",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L4568-L4600 | train | 32,512 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMAOptions.complement | def complement(self):
"""add all missing options with their default values"""
# add meta-parameters, given options have priority
self.check()
for key in CMAOptions.defaults():
if key not in self:
self[key] = CMAOptions.defaults()[key]
return self | python | def complement(self):
"""add all missing options with their default values"""
# add meta-parameters, given options have priority
self.check()
for key in CMAOptions.defaults():
if key not in self:
self[key] = CMAOptions.defaults()[key]
return self | [
"def",
"complement",
"(",
"self",
")",
":",
"# add meta-parameters, given options have priority",
"self",
".",
"check",
"(",
")",
"for",
"key",
"in",
"CMAOptions",
".",
"defaults",
"(",
")",
":",
"if",
"key",
"not",
"in",
"self",
":",
"self",
"[",
"key",
"... | add all missing options with their default values | [
"add",
"all",
"missing",
"options",
"with",
"their",
"default",
"values"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L4634-L4642 | train | 32,513 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMAOptions.settable | def settable(self):
"""return the subset of those options that are settable at any
time.
Settable options are in `versatile_options()`, but the
list might be incomplete.
"""
return CMAOptions([i for i in list(self.items())
if i[0] in CMAOptions.versatile_options()]) | python | def settable(self):
"""return the subset of those options that are settable at any
time.
Settable options are in `versatile_options()`, but the
list might be incomplete.
"""
return CMAOptions([i for i in list(self.items())
if i[0] in CMAOptions.versatile_options()]) | [
"def",
"settable",
"(",
"self",
")",
":",
"return",
"CMAOptions",
"(",
"[",
"i",
"for",
"i",
"in",
"list",
"(",
"self",
".",
"items",
"(",
")",
")",
"if",
"i",
"[",
"0",
"]",
"in",
"CMAOptions",
".",
"versatile_options",
"(",
")",
"]",
")"
] | return the subset of those options that are settable at any
time.
Settable options are in `versatile_options()`, but the
list might be incomplete. | [
"return",
"the",
"subset",
"of",
"those",
"options",
"that",
"are",
"settable",
"at",
"any",
"time",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L4644-L4653 | train | 32,514 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMAOptions.eval | def eval(self, key, default=None, loc=None, correct_key=True):
"""Evaluates and sets the specified option value in
environment `loc`. Many options need ``N`` to be defined in
`loc`, some need `popsize`.
Details
-------
Keys that contain 'filename' are not evaluated.
For `loc` is None, the self-dict is used as environment
:See: `evalall()`, `__call__`
"""
# TODO: try: loc['dim'] = loc['N'] etc
if correct_key:
# in_key = key # for debugging only
key = self.corrected_key(key)
self[key] = self(key, default, loc)
return self[key] | python | def eval(self, key, default=None, loc=None, correct_key=True):
"""Evaluates and sets the specified option value in
environment `loc`. Many options need ``N`` to be defined in
`loc`, some need `popsize`.
Details
-------
Keys that contain 'filename' are not evaluated.
For `loc` is None, the self-dict is used as environment
:See: `evalall()`, `__call__`
"""
# TODO: try: loc['dim'] = loc['N'] etc
if correct_key:
# in_key = key # for debugging only
key = self.corrected_key(key)
self[key] = self(key, default, loc)
return self[key] | [
"def",
"eval",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
",",
"loc",
"=",
"None",
",",
"correct_key",
"=",
"True",
")",
":",
"# TODO: try: loc['dim'] = loc['N'] etc",
"if",
"correct_key",
":",
"# in_key = key # for debugging only",
"key",
"=",
"self... | Evaluates and sets the specified option value in
environment `loc`. Many options need ``N`` to be defined in
`loc`, some need `popsize`.
Details
-------
Keys that contain 'filename' are not evaluated.
For `loc` is None, the self-dict is used as environment
:See: `evalall()`, `__call__` | [
"Evaluates",
"and",
"sets",
"the",
"specified",
"option",
"value",
"in",
"environment",
"loc",
".",
"Many",
"options",
"need",
"N",
"to",
"be",
"defined",
"in",
"loc",
"some",
"need",
"popsize",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L4705-L4723 | train | 32,515 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMAOptions.evalall | def evalall(self, loc=None, defaults=None):
"""Evaluates all option values in environment `loc`.
:See: `eval()`
"""
self.check()
if defaults is None:
defaults = cma_default_options
# TODO: this needs rather the parameter N instead of loc
if 'N' in loc: # TODO: __init__ of CMA can be simplified
popsize = self('popsize', defaults['popsize'], loc)
for k in list(self.keys()):
k = self.corrected_key(k)
self.eval(k, defaults[k],
{'N':loc['N'], 'popsize':popsize})
self._lock_setting = True
return self | python | def evalall(self, loc=None, defaults=None):
"""Evaluates all option values in environment `loc`.
:See: `eval()`
"""
self.check()
if defaults is None:
defaults = cma_default_options
# TODO: this needs rather the parameter N instead of loc
if 'N' in loc: # TODO: __init__ of CMA can be simplified
popsize = self('popsize', defaults['popsize'], loc)
for k in list(self.keys()):
k = self.corrected_key(k)
self.eval(k, defaults[k],
{'N':loc['N'], 'popsize':popsize})
self._lock_setting = True
return self | [
"def",
"evalall",
"(",
"self",
",",
"loc",
"=",
"None",
",",
"defaults",
"=",
"None",
")",
":",
"self",
".",
"check",
"(",
")",
"if",
"defaults",
"is",
"None",
":",
"defaults",
"=",
"cma_default_options",
"# TODO: this needs rather the parameter N instead of loc... | Evaluates all option values in environment `loc`.
:See: `eval()` | [
"Evaluates",
"all",
"option",
"values",
"in",
"environment",
"loc",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L4725-L4742 | train | 32,516 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMAOptions.match | def match(self, s=''):
"""return all options that match, in the name or the description,
with string `s`, case is disregarded.
Example: ``cma.CMAOptions().match('verb')`` returns the verbosity
options.
"""
match = s.lower()
res = {}
for k in sorted(self):
s = str(k) + '=\'' + str(self[k]) + '\''
if match in s.lower():
res[k] = self[k]
return CMAOptions(res, unchecked=True) | python | def match(self, s=''):
"""return all options that match, in the name or the description,
with string `s`, case is disregarded.
Example: ``cma.CMAOptions().match('verb')`` returns the verbosity
options.
"""
match = s.lower()
res = {}
for k in sorted(self):
s = str(k) + '=\'' + str(self[k]) + '\''
if match in s.lower():
res[k] = self[k]
return CMAOptions(res, unchecked=True) | [
"def",
"match",
"(",
"self",
",",
"s",
"=",
"''",
")",
":",
"match",
"=",
"s",
".",
"lower",
"(",
")",
"res",
"=",
"{",
"}",
"for",
"k",
"in",
"sorted",
"(",
"self",
")",
":",
"s",
"=",
"str",
"(",
"k",
")",
"+",
"'=\\''",
"+",
"str",
"("... | return all options that match, in the name or the description,
with string `s`, case is disregarded.
Example: ``cma.CMAOptions().match('verb')`` returns the verbosity
options. | [
"return",
"all",
"options",
"that",
"match",
"in",
"the",
"name",
"or",
"the",
"description",
"with",
"string",
"s",
"case",
"is",
"disregarded",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L4744-L4758 | train | 32,517 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMADataLogger.data | def data(self):
"""return dictionary with data.
If data entries are None or incomplete, consider calling
``.load().data()`` to (re-)load the data from files first.
"""
d = {}
for name in self.key_names:
d[name] = self.__dict__.get(name, None)
return d | python | def data(self):
"""return dictionary with data.
If data entries are None or incomplete, consider calling
``.load().data()`` to (re-)load the data from files first.
"""
d = {}
for name in self.key_names:
d[name] = self.__dict__.get(name, None)
return d | [
"def",
"data",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"for",
"name",
"in",
"self",
".",
"key_names",
":",
"d",
"[",
"name",
"]",
"=",
"self",
".",
"__dict__",
".",
"get",
"(",
"name",
",",
"None",
")",
"return",
"d"
] | return dictionary with data.
If data entries are None or incomplete, consider calling
``.load().data()`` to (re-)load the data from files first. | [
"return",
"dictionary",
"with",
"data",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L5711-L5721 | train | 32,518 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMADataLogger.register | def register(self, es, append=None, modulo=None):
"""register a `CMAEvolutionStrategy` instance for logging,
``append=True`` appends to previous data logged under the same name,
by default previous data are overwritten.
"""
if not isinstance(es, CMAEvolutionStrategy):
raise TypeError("only class CMAEvolutionStrategy can be " +
"registered for logging")
self.es = es
if append is not None:
self.append = append
if modulo is not None:
self.modulo = modulo
self.registered = True
return self | python | def register(self, es, append=None, modulo=None):
"""register a `CMAEvolutionStrategy` instance for logging,
``append=True`` appends to previous data logged under the same name,
by default previous data are overwritten.
"""
if not isinstance(es, CMAEvolutionStrategy):
raise TypeError("only class CMAEvolutionStrategy can be " +
"registered for logging")
self.es = es
if append is not None:
self.append = append
if modulo is not None:
self.modulo = modulo
self.registered = True
return self | [
"def",
"register",
"(",
"self",
",",
"es",
",",
"append",
"=",
"None",
",",
"modulo",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"es",
",",
"CMAEvolutionStrategy",
")",
":",
"raise",
"TypeError",
"(",
"\"only class CMAEvolutionStrategy can be \"",
... | register a `CMAEvolutionStrategy` instance for logging,
``append=True`` appends to previous data logged under the same name,
by default previous data are overwritten. | [
"register",
"a",
"CMAEvolutionStrategy",
"instance",
"for",
"logging",
"append",
"=",
"True",
"appends",
"to",
"previous",
"data",
"logged",
"under",
"the",
"same",
"name",
"by",
"default",
"previous",
"data",
"are",
"overwritten",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L5722-L5737 | train | 32,519 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMADataLogger.save_to | def save_to(self, nameprefix, switch=False):
"""saves logger data to a different set of files, for
``switch=True`` also the loggers name prefix is switched to
the new value
"""
if not nameprefix or not isinstance(nameprefix, basestring):
raise _Error('filename prefix must be a nonempty string')
if nameprefix == self.default_prefix:
raise _Error('cannot save to default name "' + nameprefix + '...", chose another name')
if nameprefix == self.name_prefix:
return
for name in self.file_names:
open(nameprefix + name + '.dat', 'w').write(open(self.name_prefix + name + '.dat').read())
if switch:
self.name_prefix = nameprefix | python | def save_to(self, nameprefix, switch=False):
"""saves logger data to a different set of files, for
``switch=True`` also the loggers name prefix is switched to
the new value
"""
if not nameprefix or not isinstance(nameprefix, basestring):
raise _Error('filename prefix must be a nonempty string')
if nameprefix == self.default_prefix:
raise _Error('cannot save to default name "' + nameprefix + '...", chose another name')
if nameprefix == self.name_prefix:
return
for name in self.file_names:
open(nameprefix + name + '.dat', 'w').write(open(self.name_prefix + name + '.dat').read())
if switch:
self.name_prefix = nameprefix | [
"def",
"save_to",
"(",
"self",
",",
"nameprefix",
",",
"switch",
"=",
"False",
")",
":",
"if",
"not",
"nameprefix",
"or",
"not",
"isinstance",
"(",
"nameprefix",
",",
"basestring",
")",
":",
"raise",
"_Error",
"(",
"'filename prefix must be a nonempty string'",
... | saves logger data to a different set of files, for
``switch=True`` also the loggers name prefix is switched to
the new value | [
"saves",
"logger",
"data",
"to",
"a",
"different",
"set",
"of",
"files",
"for",
"switch",
"=",
"True",
"also",
"the",
"loggers",
"name",
"prefix",
"is",
"switched",
"to",
"the",
"new",
"value"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L6029-L6048 | train | 32,520 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMADataLogger.select_data | def select_data(self, iteration_indices):
"""keep only data of `iteration_indices`"""
dat = self
iteridx = iteration_indices
dat.f = dat.f[np.where([x in iteridx for x in dat.f[:, 0]])[0], :]
dat.D = dat.D[np.where([x in iteridx for x in dat.D[:, 0]])[0], :]
try:
iteridx = list(iteridx)
iteridx.append(iteridx[-1]) # last entry is artificial
except:
pass
dat.std = dat.std[np.where([x in iteridx
for x in dat.std[:, 0]])[0], :]
dat.xmean = dat.xmean[np.where([x in iteridx
for x in dat.xmean[:, 0]])[0], :]
try:
dat.xrecent = dat.x[np.where([x in iteridx for x in
dat.xrecent[:, 0]])[0], :]
except AttributeError:
pass
try:
dat.corrspec = dat.x[np.where([x in iteridx for x in
dat.corrspec[:, 0]])[0], :]
except AttributeError:
pass | python | def select_data(self, iteration_indices):
"""keep only data of `iteration_indices`"""
dat = self
iteridx = iteration_indices
dat.f = dat.f[np.where([x in iteridx for x in dat.f[:, 0]])[0], :]
dat.D = dat.D[np.where([x in iteridx for x in dat.D[:, 0]])[0], :]
try:
iteridx = list(iteridx)
iteridx.append(iteridx[-1]) # last entry is artificial
except:
pass
dat.std = dat.std[np.where([x in iteridx
for x in dat.std[:, 0]])[0], :]
dat.xmean = dat.xmean[np.where([x in iteridx
for x in dat.xmean[:, 0]])[0], :]
try:
dat.xrecent = dat.x[np.where([x in iteridx for x in
dat.xrecent[:, 0]])[0], :]
except AttributeError:
pass
try:
dat.corrspec = dat.x[np.where([x in iteridx for x in
dat.corrspec[:, 0]])[0], :]
except AttributeError:
pass | [
"def",
"select_data",
"(",
"self",
",",
"iteration_indices",
")",
":",
"dat",
"=",
"self",
"iteridx",
"=",
"iteration_indices",
"dat",
".",
"f",
"=",
"dat",
".",
"f",
"[",
"np",
".",
"where",
"(",
"[",
"x",
"in",
"iteridx",
"for",
"x",
"in",
"dat",
... | keep only data of `iteration_indices` | [
"keep",
"only",
"data",
"of",
"iteration_indices"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L6049-L6073 | train | 32,521 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMADataLogger.plot_correlations | def plot_correlations(self, iabscissa=1):
"""spectrum of correlation matrix and largest correlation"""
if not hasattr(self, 'corrspec'):
self.load()
if len(self.corrspec) < 2:
return self
x = self.corrspec[:, iabscissa]
y = self.corrspec[:, 6:] # principle axes
ys = self.corrspec[:, :6] # "special" values
from matplotlib.pyplot import semilogy, hold, text, grid, axis, title
self._enter_plotting()
semilogy(x, y, '-c')
hold(True)
semilogy(x[:], np.max(y, 1) / np.min(y, 1), '-r')
text(x[-1], np.max(y[-1, :]) / np.min(y[-1, :]), 'axis ratio')
if ys is not None:
semilogy(x, 1 + ys[:, 2], '-b')
text(x[-1], 1 + ys[-1, 2], '1 + min(corr)')
semilogy(x, 1 - ys[:, 5], '-b')
text(x[-1], 1 - ys[-1, 5], '1 - max(corr)')
semilogy(x[:], 1 + ys[:, 3], '-k')
text(x[-1], 1 + ys[-1, 3], '1 + max(neg corr)')
semilogy(x[:], 1 - ys[:, 4], '-k')
text(x[-1], 1 - ys[-1, 4], '1 - min(pos corr)')
grid(True)
ax = array(axis())
# ax[1] = max(minxend, ax[1])
axis(ax)
title('Spectrum (roots) of correlation matrix')
# pyplot.xticks(xticklocs)
self._xlabel(iabscissa)
self._finalize_plotting()
return self | python | def plot_correlations(self, iabscissa=1):
"""spectrum of correlation matrix and largest correlation"""
if not hasattr(self, 'corrspec'):
self.load()
if len(self.corrspec) < 2:
return self
x = self.corrspec[:, iabscissa]
y = self.corrspec[:, 6:] # principle axes
ys = self.corrspec[:, :6] # "special" values
from matplotlib.pyplot import semilogy, hold, text, grid, axis, title
self._enter_plotting()
semilogy(x, y, '-c')
hold(True)
semilogy(x[:], np.max(y, 1) / np.min(y, 1), '-r')
text(x[-1], np.max(y[-1, :]) / np.min(y[-1, :]), 'axis ratio')
if ys is not None:
semilogy(x, 1 + ys[:, 2], '-b')
text(x[-1], 1 + ys[-1, 2], '1 + min(corr)')
semilogy(x, 1 - ys[:, 5], '-b')
text(x[-1], 1 - ys[-1, 5], '1 - max(corr)')
semilogy(x[:], 1 + ys[:, 3], '-k')
text(x[-1], 1 + ys[-1, 3], '1 + max(neg corr)')
semilogy(x[:], 1 - ys[:, 4], '-k')
text(x[-1], 1 - ys[-1, 4], '1 - min(pos corr)')
grid(True)
ax = array(axis())
# ax[1] = max(minxend, ax[1])
axis(ax)
title('Spectrum (roots) of correlation matrix')
# pyplot.xticks(xticklocs)
self._xlabel(iabscissa)
self._finalize_plotting()
return self | [
"def",
"plot_correlations",
"(",
"self",
",",
"iabscissa",
"=",
"1",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'corrspec'",
")",
":",
"self",
".",
"load",
"(",
")",
"if",
"len",
"(",
"self",
".",
"corrspec",
")",
"<",
"2",
":",
"return",... | spectrum of correlation matrix and largest correlation | [
"spectrum",
"of",
"correlation",
"matrix",
"and",
"largest",
"correlation"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L6347-L6380 | train | 32,522 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMADataLogger._enter_plotting | def _enter_plotting(self, fontsize=9):
"""assumes that a figure is open """
# interactive_status = matplotlib.is_interactive()
self.original_fontsize = pyplot.rcParams['font.size']
pyplot.rcParams['font.size'] = fontsize
pyplot.hold(False) # opens a figure window, if non exists
pyplot.ioff() | python | def _enter_plotting(self, fontsize=9):
"""assumes that a figure is open """
# interactive_status = matplotlib.is_interactive()
self.original_fontsize = pyplot.rcParams['font.size']
pyplot.rcParams['font.size'] = fontsize
pyplot.hold(False) # opens a figure window, if non exists
pyplot.ioff() | [
"def",
"_enter_plotting",
"(",
"self",
",",
"fontsize",
"=",
"9",
")",
":",
"# interactive_status = matplotlib.is_interactive()",
"self",
".",
"original_fontsize",
"=",
"pyplot",
".",
"rcParams",
"[",
"'font.size'",
"]",
"pyplot",
".",
"rcParams",
"[",
"'font.size'"... | assumes that a figure is open | [
"assumes",
"that",
"a",
"figure",
"is",
"open"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L6522-L6528 | train | 32,523 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | CMADataLogger.downsampling | def downsampling(self, factor=10, first=3, switch=True, verbose=True):
"""
rude downsampling of a `CMADataLogger` data file by `factor`,
keeping also the first `first` entries. This function is a
stump and subject to future changes. Return self.
Arguments
---------
- `factor` -- downsampling factor
- `first` -- keep first `first` entries
- `switch` -- switch the new logger to the downsampled logger
original_name+'down'
Details
-------
``self.name_prefix+'down'`` files are written
Example
-------
::
import cma
cma.downsampling() # takes outcmaes* files
cma.plot('outcmaesdown')
"""
newprefix = self.name_prefix + 'down'
for name in self.file_names:
f = open(newprefix + name + '.dat', 'w')
iline = 0
cwritten = 0
for line in open(self.name_prefix + name + '.dat'):
if iline < first or iline % factor == 0:
f.write(line)
cwritten += 1
iline += 1
f.close()
if verbose and iline > first:
print('%d' % (cwritten) + ' lines written in ' + newprefix + name + '.dat')
if switch:
self.name_prefix += 'down'
return self | python | def downsampling(self, factor=10, first=3, switch=True, verbose=True):
"""
rude downsampling of a `CMADataLogger` data file by `factor`,
keeping also the first `first` entries. This function is a
stump and subject to future changes. Return self.
Arguments
---------
- `factor` -- downsampling factor
- `first` -- keep first `first` entries
- `switch` -- switch the new logger to the downsampled logger
original_name+'down'
Details
-------
``self.name_prefix+'down'`` files are written
Example
-------
::
import cma
cma.downsampling() # takes outcmaes* files
cma.plot('outcmaesdown')
"""
newprefix = self.name_prefix + 'down'
for name in self.file_names:
f = open(newprefix + name + '.dat', 'w')
iline = 0
cwritten = 0
for line in open(self.name_prefix + name + '.dat'):
if iline < first or iline % factor == 0:
f.write(line)
cwritten += 1
iline += 1
f.close()
if verbose and iline > first:
print('%d' % (cwritten) + ' lines written in ' + newprefix + name + '.dat')
if switch:
self.name_prefix += 'down'
return self | [
"def",
"downsampling",
"(",
"self",
",",
"factor",
"=",
"10",
",",
"first",
"=",
"3",
",",
"switch",
"=",
"True",
",",
"verbose",
"=",
"True",
")",
":",
"newprefix",
"=",
"self",
".",
"name_prefix",
"+",
"'down'",
"for",
"name",
"in",
"self",
".",
... | rude downsampling of a `CMADataLogger` data file by `factor`,
keeping also the first `first` entries. This function is a
stump and subject to future changes. Return self.
Arguments
---------
- `factor` -- downsampling factor
- `first` -- keep first `first` entries
- `switch` -- switch the new logger to the downsampled logger
original_name+'down'
Details
-------
``self.name_prefix+'down'`` files are written
Example
-------
::
import cma
cma.downsampling() # takes outcmaes* files
cma.plot('outcmaesdown') | [
"rude",
"downsampling",
"of",
"a",
"CMADataLogger",
"data",
"file",
"by",
"factor",
"keeping",
"also",
"the",
"first",
"first",
"entries",
".",
"This",
"function",
"is",
"a",
"stump",
"and",
"subject",
"to",
"future",
"changes",
".",
"Return",
"self",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L6613-L6654 | train | 32,524 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | NoiseHandler.update_measure | def update_measure(self):
"""updated noise level measure using two fitness lists ``self.fit`` and
``self.fitre``, return ``self.noiseS, all_individual_measures``.
Assumes that `self.idx` contains the indices where the fitness
lists differ
"""
lam = len(self.fit)
idx = np.argsort(self.fit + self.fitre)
ranks = np.argsort(idx).reshape((2, lam))
rankDelta = ranks[0] - ranks[1] - np.sign(ranks[0] - ranks[1])
# compute rank change limits using both ranks[0] and ranks[1]
r = np.arange(1, 2 * lam) # 2 * lam - 2 elements
limits = [0.5 * (Mh.prctile(np.abs(r - (ranks[0, i] + 1 - (ranks[0, i] > ranks[1, i]))),
self.theta * 50) +
Mh.prctile(np.abs(r - (ranks[1, i] + 1 - (ranks[1, i] > ranks[0, i]))),
self.theta * 50))
for i in self.idx]
# compute measurement
# max: 1 rankchange in 2*lambda is always fine
s = np.abs(rankDelta[self.idx]) - Mh.amax(limits, 1) # lives roughly in 0..2*lambda
self.noiseS += self.cum * (np.mean(s) - self.noiseS)
return self.noiseS, s | python | def update_measure(self):
"""updated noise level measure using two fitness lists ``self.fit`` and
``self.fitre``, return ``self.noiseS, all_individual_measures``.
Assumes that `self.idx` contains the indices where the fitness
lists differ
"""
lam = len(self.fit)
idx = np.argsort(self.fit + self.fitre)
ranks = np.argsort(idx).reshape((2, lam))
rankDelta = ranks[0] - ranks[1] - np.sign(ranks[0] - ranks[1])
# compute rank change limits using both ranks[0] and ranks[1]
r = np.arange(1, 2 * lam) # 2 * lam - 2 elements
limits = [0.5 * (Mh.prctile(np.abs(r - (ranks[0, i] + 1 - (ranks[0, i] > ranks[1, i]))),
self.theta * 50) +
Mh.prctile(np.abs(r - (ranks[1, i] + 1 - (ranks[1, i] > ranks[0, i]))),
self.theta * 50))
for i in self.idx]
# compute measurement
# max: 1 rankchange in 2*lambda is always fine
s = np.abs(rankDelta[self.idx]) - Mh.amax(limits, 1) # lives roughly in 0..2*lambda
self.noiseS += self.cum * (np.mean(s) - self.noiseS)
return self.noiseS, s | [
"def",
"update_measure",
"(",
"self",
")",
":",
"lam",
"=",
"len",
"(",
"self",
".",
"fit",
")",
"idx",
"=",
"np",
".",
"argsort",
"(",
"self",
".",
"fit",
"+",
"self",
".",
"fitre",
")",
"ranks",
"=",
"np",
".",
"argsort",
"(",
"idx",
")",
"."... | updated noise level measure using two fitness lists ``self.fit`` and
``self.fitre``, return ``self.noiseS, all_individual_measures``.
Assumes that `self.idx` contains the indices where the fitness
lists differ | [
"updated",
"noise",
"level",
"measure",
"using",
"two",
"fitness",
"lists",
"self",
".",
"fit",
"and",
"self",
".",
"fitre",
"return",
"self",
".",
"noiseS",
"all_individual_measures",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L7066-L7090 | train | 32,525 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | NoiseHandler.indices | def indices(self, fit):
"""return the set of indices to be reevaluated for noise
measurement.
Given the first values are the earliest, this is a useful policy also
with a time changing objective.
"""
## meta_parameters.noise_reeval_multiplier == 1.0
lam_reev = 1.0 * (self.lam_reeval if self.lam_reeval
else 2 + len(fit) / 20)
lam_reev = int(lam_reev) + ((lam_reev % 1) > np.random.rand())
## meta_parameters.noise_choose_reeval == 1
choice = 1
if choice == 1:
# take n_first first and reev - n_first best of the remaining
n_first = lam_reev - lam_reev // 2
sort_idx = np.argsort(array(fit, copy=False)[n_first:]) + n_first
return np.array(list(range(0, n_first)) +
list(sort_idx[0:lam_reev - n_first]), copy=False)
elif choice == 2:
idx_sorted = np.argsort(array(fit, copy=False))
# take lam_reev equally spaced, starting with best
linsp = np.linspace(0, len(fit) - len(fit) / lam_reev, lam_reev)
return idx_sorted[[int(i) for i in linsp]]
# take the ``lam_reeval`` best from the first ``2 * lam_reeval + 2`` values.
elif choice == 3:
return np.argsort(array(fit, copy=False)[:2 * (lam_reev + 1)])[:lam_reev]
else:
raise ValueError('unrecognized choice value %d for noise reev'
% choice) | python | def indices(self, fit):
"""return the set of indices to be reevaluated for noise
measurement.
Given the first values are the earliest, this is a useful policy also
with a time changing objective.
"""
## meta_parameters.noise_reeval_multiplier == 1.0
lam_reev = 1.0 * (self.lam_reeval if self.lam_reeval
else 2 + len(fit) / 20)
lam_reev = int(lam_reev) + ((lam_reev % 1) > np.random.rand())
## meta_parameters.noise_choose_reeval == 1
choice = 1
if choice == 1:
# take n_first first and reev - n_first best of the remaining
n_first = lam_reev - lam_reev // 2
sort_idx = np.argsort(array(fit, copy=False)[n_first:]) + n_first
return np.array(list(range(0, n_first)) +
list(sort_idx[0:lam_reev - n_first]), copy=False)
elif choice == 2:
idx_sorted = np.argsort(array(fit, copy=False))
# take lam_reev equally spaced, starting with best
linsp = np.linspace(0, len(fit) - len(fit) / lam_reev, lam_reev)
return idx_sorted[[int(i) for i in linsp]]
# take the ``lam_reeval`` best from the first ``2 * lam_reeval + 2`` values.
elif choice == 3:
return np.argsort(array(fit, copy=False)[:2 * (lam_reev + 1)])[:lam_reev]
else:
raise ValueError('unrecognized choice value %d for noise reev'
% choice) | [
"def",
"indices",
"(",
"self",
",",
"fit",
")",
":",
"## meta_parameters.noise_reeval_multiplier == 1.0",
"lam_reev",
"=",
"1.0",
"*",
"(",
"self",
".",
"lam_reeval",
"if",
"self",
".",
"lam_reeval",
"else",
"2",
"+",
"len",
"(",
"fit",
")",
"/",
"20",
")"... | return the set of indices to be reevaluated for noise
measurement.
Given the first values are the earliest, this is a useful policy also
with a time changing objective. | [
"return",
"the",
"set",
"of",
"indices",
"to",
"be",
"reevaluated",
"for",
"noise",
"measurement",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L7092-L7122 | train | 32,526 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | Sections.plot | def plot(self, plot_cmd=None, tf=lambda y: y):
"""plot the data we have, return ``self``"""
if not plot_cmd:
plot_cmd = self.plot_cmd
colors = 'bgrcmyk'
pyplot.hold(False)
res = self.res
flatx, flatf = self.flattened()
minf = np.inf
for i in flatf:
minf = min((minf, min(flatf[i])))
addf = 1e-9 - minf if minf <= 1e-9 else 0
for i in sorted(res.keys()): # we plot not all values here
if isinstance(i, int):
color = colors[i % len(colors)]
arx = sorted(res[i].keys())
plot_cmd(arx, [tf(np.median(res[i][x]) + addf) for x in arx], color + '-')
pyplot.text(arx[-1], tf(np.median(res[i][arx[-1]])), i)
pyplot.hold(True)
plot_cmd(flatx[i], tf(np.array(flatf[i]) + addf), color + 'o')
pyplot.ylabel('f + ' + str(addf))
pyplot.draw()
pyplot.ion()
pyplot.show()
# raw_input('press return')
return self | python | def plot(self, plot_cmd=None, tf=lambda y: y):
"""plot the data we have, return ``self``"""
if not plot_cmd:
plot_cmd = self.plot_cmd
colors = 'bgrcmyk'
pyplot.hold(False)
res = self.res
flatx, flatf = self.flattened()
minf = np.inf
for i in flatf:
minf = min((minf, min(flatf[i])))
addf = 1e-9 - minf if minf <= 1e-9 else 0
for i in sorted(res.keys()): # we plot not all values here
if isinstance(i, int):
color = colors[i % len(colors)]
arx = sorted(res[i].keys())
plot_cmd(arx, [tf(np.median(res[i][x]) + addf) for x in arx], color + '-')
pyplot.text(arx[-1], tf(np.median(res[i][arx[-1]])), i)
pyplot.hold(True)
plot_cmd(flatx[i], tf(np.array(flatf[i]) + addf), color + 'o')
pyplot.ylabel('f + ' + str(addf))
pyplot.draw()
pyplot.ion()
pyplot.show()
# raw_input('press return')
return self | [
"def",
"plot",
"(",
"self",
",",
"plot_cmd",
"=",
"None",
",",
"tf",
"=",
"lambda",
"y",
":",
"y",
")",
":",
"if",
"not",
"plot_cmd",
":",
"plot_cmd",
"=",
"self",
".",
"plot_cmd",
"colors",
"=",
"'bgrcmyk'",
"pyplot",
".",
"hold",
"(",
"False",
")... | plot the data we have, return ``self`` | [
"plot",
"the",
"data",
"we",
"have",
"return",
"self"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L7250-L7276 | train | 32,527 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | Sections.save | def save(self, name=None):
"""save to file"""
import pickle
name = name if name else self.name
fun = self.func
del self.func # instance method produces error
pickle.dump(self, open(name + '.pkl', "wb"))
self.func = fun
return self | python | def save(self, name=None):
"""save to file"""
import pickle
name = name if name else self.name
fun = self.func
del self.func # instance method produces error
pickle.dump(self, open(name + '.pkl', "wb"))
self.func = fun
return self | [
"def",
"save",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"import",
"pickle",
"name",
"=",
"name",
"if",
"name",
"else",
"self",
".",
"name",
"fun",
"=",
"self",
".",
"func",
"del",
"self",
".",
"func",
"# instance method produces error",
"pickle",... | save to file | [
"save",
"to",
"file"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L7295-L7303 | train | 32,528 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | Sections.load | def load(self, name=None):
"""load from file"""
import pickle
name = name if name else self.name
s = pickle.load(open(name + '.pkl', 'rb'))
self.res = s.res # disregard the class
return self | python | def load(self, name=None):
"""load from file"""
import pickle
name = name if name else self.name
s = pickle.load(open(name + '.pkl', 'rb'))
self.res = s.res # disregard the class
return self | [
"def",
"load",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"import",
"pickle",
"name",
"=",
"name",
"if",
"name",
"else",
"self",
".",
"name",
"s",
"=",
"pickle",
".",
"load",
"(",
"open",
"(",
"name",
"+",
"'.pkl'",
",",
"'rb'",
")",
")",
... | load from file | [
"load",
"from",
"file"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L7305-L7311 | train | 32,529 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | Misc.loglikelihood | def loglikelihood(self, x, previous=False):
"""return log-likelihood of `x` regarding the current sample distribution"""
# testing of original fct: MC integrate must be one: mean(p(x_i)) * volume(where x_i are uniformely sampled)
# for i in xrange(3): print mean([cma.likelihood(20*r-10, dim * [0], None, 3) for r in rand(10000,dim)]) * 20**dim
# TODO: test this!!
# c=cma.fmin...
# c[3]['cma'].loglikelihood(...)
if previous and hasattr(self, 'lastiter'):
sigma = self.lastiter.sigma
Crootinv = self.lastiter._Crootinv
xmean = self.lastiter.mean
D = self.lastiter.D
elif previous and self.countiter > 1:
raise _Error('no previous distribution parameters stored, check options importance_mixing')
else:
sigma = self.sigma
Crootinv = self._Crootinv
xmean = self.mean
D = self.D
dx = array(x) - xmean # array(x) - array(m)
n = self.N
logs2pi = n * log(2 * np.pi) / 2.
logdetC = 2 * sum(log(D))
dx = np.dot(Crootinv, dx)
res = -sum(dx**2) / sigma**2 / 2 - logs2pi - logdetC / 2 - n * log(sigma)
if 1 < 3: # testing
s2pi = (2 * np.pi)**(n / 2.)
detC = np.prod(D)**2
res2 = -sum(dx**2) / sigma**2 / 2 - log(s2pi * abs(detC)**0.5 * sigma**n)
assert res2 < res + 1e-8 or res2 > res - 1e-8
return res | python | def loglikelihood(self, x, previous=False):
"""return log-likelihood of `x` regarding the current sample distribution"""
# testing of original fct: MC integrate must be one: mean(p(x_i)) * volume(where x_i are uniformely sampled)
# for i in xrange(3): print mean([cma.likelihood(20*r-10, dim * [0], None, 3) for r in rand(10000,dim)]) * 20**dim
# TODO: test this!!
# c=cma.fmin...
# c[3]['cma'].loglikelihood(...)
if previous and hasattr(self, 'lastiter'):
sigma = self.lastiter.sigma
Crootinv = self.lastiter._Crootinv
xmean = self.lastiter.mean
D = self.lastiter.D
elif previous and self.countiter > 1:
raise _Error('no previous distribution parameters stored, check options importance_mixing')
else:
sigma = self.sigma
Crootinv = self._Crootinv
xmean = self.mean
D = self.D
dx = array(x) - xmean # array(x) - array(m)
n = self.N
logs2pi = n * log(2 * np.pi) / 2.
logdetC = 2 * sum(log(D))
dx = np.dot(Crootinv, dx)
res = -sum(dx**2) / sigma**2 / 2 - logs2pi - logdetC / 2 - n * log(sigma)
if 1 < 3: # testing
s2pi = (2 * np.pi)**(n / 2.)
detC = np.prod(D)**2
res2 = -sum(dx**2) / sigma**2 / 2 - log(s2pi * abs(detC)**0.5 * sigma**n)
assert res2 < res + 1e-8 or res2 > res - 1e-8
return res | [
"def",
"loglikelihood",
"(",
"self",
",",
"x",
",",
"previous",
"=",
"False",
")",
":",
"# testing of original fct: MC integrate must be one: mean(p(x_i)) * volume(where x_i are uniformely sampled)",
"# for i in xrange(3): print mean([cma.likelihood(20*r-10, dim * [0], None, 3) for r in ra... | return log-likelihood of `x` regarding the current sample distribution | [
"return",
"log",
"-",
"likelihood",
"of",
"x",
"regarding",
"the",
"current",
"sample",
"distribution"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L7505-L7537 | train | 32,530 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | FitnessFunctions.noisysphere | def noisysphere(self, x, noise=2.10e-9, cond=1.0, noise_offset=0.10):
"""noise=10 does not work with default popsize, noise handling does not help """
return self.elli(x, cond=cond) * (1 + noise * np.random.randn() / len(x)) + noise_offset * np.random.rand() | python | def noisysphere(self, x, noise=2.10e-9, cond=1.0, noise_offset=0.10):
"""noise=10 does not work with default popsize, noise handling does not help """
return self.elli(x, cond=cond) * (1 + noise * np.random.randn() / len(x)) + noise_offset * np.random.rand() | [
"def",
"noisysphere",
"(",
"self",
",",
"x",
",",
"noise",
"=",
"2.10e-9",
",",
"cond",
"=",
"1.0",
",",
"noise_offset",
"=",
"0.10",
")",
":",
"return",
"self",
".",
"elli",
"(",
"x",
",",
"cond",
"=",
"cond",
")",
"*",
"(",
"1",
"+",
"noise",
... | noise=10 does not work with default popsize, noise handling does not help | [
"noise",
"=",
"10",
"does",
"not",
"work",
"with",
"default",
"popsize",
"noise",
"handling",
"does",
"not",
"help"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L8277-L8279 | train | 32,531 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | FitnessFunctions.cigar | def cigar(self, x, rot=0, cond=1e6, noise=0):
"""Cigar test objective function"""
if rot:
x = rotate(x)
x = [x] if isscalar(x[0]) else x # scalar into list
f = [(x[0]**2 + cond * sum(x[1:]**2)) * np.exp(noise * np.random.randn(1)[0] / len(x)) for x in x]
return f if len(f) > 1 else f[0] # 1-element-list into scalar | python | def cigar(self, x, rot=0, cond=1e6, noise=0):
"""Cigar test objective function"""
if rot:
x = rotate(x)
x = [x] if isscalar(x[0]) else x # scalar into list
f = [(x[0]**2 + cond * sum(x[1:]**2)) * np.exp(noise * np.random.randn(1)[0] / len(x)) for x in x]
return f if len(f) > 1 else f[0] # 1-element-list into scalar | [
"def",
"cigar",
"(",
"self",
",",
"x",
",",
"rot",
"=",
"0",
",",
"cond",
"=",
"1e6",
",",
"noise",
"=",
"0",
")",
":",
"if",
"rot",
":",
"x",
"=",
"rotate",
"(",
"x",
")",
"x",
"=",
"[",
"x",
"]",
"if",
"isscalar",
"(",
"x",
"[",
"0",
... | Cigar test objective function | [
"Cigar",
"test",
"objective",
"function"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L8336-L8342 | train | 32,532 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | FitnessFunctions.tablet | def tablet(self, x, rot=0):
"""Tablet test objective function"""
if rot and rot is not fcts.tablet:
x = rotate(x)
x = [x] if isscalar(x[0]) else x # scalar into list
f = [1e6 * x[0]**2 + sum(x[1:]**2) for x in x]
return f if len(f) > 1 else f[0] # 1-element-list into scalar | python | def tablet(self, x, rot=0):
"""Tablet test objective function"""
if rot and rot is not fcts.tablet:
x = rotate(x)
x = [x] if isscalar(x[0]) else x # scalar into list
f = [1e6 * x[0]**2 + sum(x[1:]**2) for x in x]
return f if len(f) > 1 else f[0] # 1-element-list into scalar | [
"def",
"tablet",
"(",
"self",
",",
"x",
",",
"rot",
"=",
"0",
")",
":",
"if",
"rot",
"and",
"rot",
"is",
"not",
"fcts",
".",
"tablet",
":",
"x",
"=",
"rotate",
"(",
"x",
")",
"x",
"=",
"[",
"x",
"]",
"if",
"isscalar",
"(",
"x",
"[",
"0",
... | Tablet test objective function | [
"Tablet",
"test",
"objective",
"function"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L8353-L8359 | train | 32,533 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | FitnessFunctions.elli | def elli(self, x, rot=0, xoffset=0, cond=1e6, actuator_noise=0.0, both=False):
"""Ellipsoid test objective function"""
if not isscalar(x[0]): # parallel evaluation
return [self.elli(xi, rot) for xi in x] # could save 20% overall
if rot:
x = rotate(x)
N = len(x)
if actuator_noise:
x = x + actuator_noise * np.random.randn(N)
ftrue = sum(cond**(np.arange(N) / (N - 1.)) * (x + xoffset)**2)
alpha = 0.49 + 1. / N
beta = 1
felli = np.random.rand(1)[0]**beta * ftrue * \
max(1, (10.**9 / (ftrue + 1e-99))**(alpha * np.random.rand(1)[0]))
# felli = ftrue + 1*np.random.randn(1)[0] / (1e-30 +
# np.abs(np.random.randn(1)[0]))**0
if both:
return (felli, ftrue)
else:
# return felli # possibly noisy value
return ftrue # + np.random.randn() | python | def elli(self, x, rot=0, xoffset=0, cond=1e6, actuator_noise=0.0, both=False):
"""Ellipsoid test objective function"""
if not isscalar(x[0]): # parallel evaluation
return [self.elli(xi, rot) for xi in x] # could save 20% overall
if rot:
x = rotate(x)
N = len(x)
if actuator_noise:
x = x + actuator_noise * np.random.randn(N)
ftrue = sum(cond**(np.arange(N) / (N - 1.)) * (x + xoffset)**2)
alpha = 0.49 + 1. / N
beta = 1
felli = np.random.rand(1)[0]**beta * ftrue * \
max(1, (10.**9 / (ftrue + 1e-99))**(alpha * np.random.rand(1)[0]))
# felli = ftrue + 1*np.random.randn(1)[0] / (1e-30 +
# np.abs(np.random.randn(1)[0]))**0
if both:
return (felli, ftrue)
else:
# return felli # possibly noisy value
return ftrue # + np.random.randn() | [
"def",
"elli",
"(",
"self",
",",
"x",
",",
"rot",
"=",
"0",
",",
"xoffset",
"=",
"0",
",",
"cond",
"=",
"1e6",
",",
"actuator_noise",
"=",
"0.0",
",",
"both",
"=",
"False",
")",
":",
"if",
"not",
"isscalar",
"(",
"x",
"[",
"0",
"]",
")",
":",... | Ellipsoid test objective function | [
"Ellipsoid",
"test",
"objective",
"function"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L8384-L8406 | train | 32,534 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | FitnessFunctions.elliconstraint | def elliconstraint(self, x, cfac=1e8, tough=True, cond=1e6):
"""ellipsoid test objective function with "constraints" """
N = len(x)
f = sum(cond**(np.arange(N)[-1::-1] / (N - 1)) * x**2)
cvals = (x[0] + 1,
x[0] + 1 + 100 * x[1],
x[0] + 1 - 100 * x[1])
if tough:
f += cfac * sum(max(0, c) for c in cvals)
else:
f += cfac * sum(max(0, c + 1e-3)**2 for c in cvals)
return f | python | def elliconstraint(self, x, cfac=1e8, tough=True, cond=1e6):
"""ellipsoid test objective function with "constraints" """
N = len(x)
f = sum(cond**(np.arange(N)[-1::-1] / (N - 1)) * x**2)
cvals = (x[0] + 1,
x[0] + 1 + 100 * x[1],
x[0] + 1 - 100 * x[1])
if tough:
f += cfac * sum(max(0, c) for c in cvals)
else:
f += cfac * sum(max(0, c + 1e-3)**2 for c in cvals)
return f | [
"def",
"elliconstraint",
"(",
"self",
",",
"x",
",",
"cfac",
"=",
"1e8",
",",
"tough",
"=",
"True",
",",
"cond",
"=",
"1e6",
")",
":",
"N",
"=",
"len",
"(",
"x",
")",
"f",
"=",
"sum",
"(",
"cond",
"**",
"(",
"np",
".",
"arange",
"(",
"N",
"... | ellipsoid test objective function with "constraints" | [
"ellipsoid",
"test",
"objective",
"function",
"with",
"constraints"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L8434-L8445 | train | 32,535 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | FitnessFunctions.rosen | def rosen(self, x, alpha=1e2):
"""Rosenbrock test objective function"""
x = [x] if isscalar(x[0]) else x # scalar into list
f = [sum(alpha * (x[:-1]**2 - x[1:])**2 + (1. - x[:-1])**2) for x in x]
return f if len(f) > 1 else f[0] # 1-element-list into scalar | python | def rosen(self, x, alpha=1e2):
"""Rosenbrock test objective function"""
x = [x] if isscalar(x[0]) else x # scalar into list
f = [sum(alpha * (x[:-1]**2 - x[1:])**2 + (1. - x[:-1])**2) for x in x]
return f if len(f) > 1 else f[0] # 1-element-list into scalar | [
"def",
"rosen",
"(",
"self",
",",
"x",
",",
"alpha",
"=",
"1e2",
")",
":",
"x",
"=",
"[",
"x",
"]",
"if",
"isscalar",
"(",
"x",
"[",
"0",
"]",
")",
"else",
"x",
"# scalar into list",
"f",
"=",
"[",
"sum",
"(",
"alpha",
"*",
"(",
"x",
"[",
"... | Rosenbrock test objective function | [
"Rosenbrock",
"test",
"objective",
"function"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L8446-L8450 | train | 32,536 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | FitnessFunctions.diffpow | def diffpow(self, x, rot=0):
"""Diffpow test objective function"""
N = len(x)
if rot:
x = rotate(x)
return sum(np.abs(x)**(2. + 4.*np.arange(N) / (N - 1.)))**0.5 | python | def diffpow(self, x, rot=0):
"""Diffpow test objective function"""
N = len(x)
if rot:
x = rotate(x)
return sum(np.abs(x)**(2. + 4.*np.arange(N) / (N - 1.)))**0.5 | [
"def",
"diffpow",
"(",
"self",
",",
"x",
",",
"rot",
"=",
"0",
")",
":",
"N",
"=",
"len",
"(",
"x",
")",
"if",
"rot",
":",
"x",
"=",
"rotate",
"(",
"x",
")",
"return",
"sum",
"(",
"np",
".",
"abs",
"(",
"x",
")",
"**",
"(",
"2.",
"+",
"... | Diffpow test objective function | [
"Diffpow",
"test",
"objective",
"function"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L8459-L8464 | train | 32,537 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | FitnessFunctions.ridgecircle | def ridgecircle(self, x, expo=0.5):
"""happy cat by HG Beyer"""
a = len(x)
s = sum(x**2)
return ((s - a)**2)**(expo / 2) + s / a + sum(x) / a | python | def ridgecircle(self, x, expo=0.5):
"""happy cat by HG Beyer"""
a = len(x)
s = sum(x**2)
return ((s - a)**2)**(expo / 2) + s / a + sum(x) / a | [
"def",
"ridgecircle",
"(",
"self",
",",
"x",
",",
"expo",
"=",
"0.5",
")",
":",
"a",
"=",
"len",
"(",
"x",
")",
"s",
"=",
"sum",
"(",
"x",
"**",
"2",
")",
"return",
"(",
"(",
"s",
"-",
"a",
")",
"**",
"2",
")",
"**",
"(",
"expo",
"/",
"... | happy cat by HG Beyer | [
"happy",
"cat",
"by",
"HG",
"Beyer"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L8472-L8476 | train | 32,538 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | FitnessFunctions.rastrigin | def rastrigin(self, x):
"""Rastrigin test objective function"""
if not isscalar(x[0]):
N = len(x[0])
return [10 * N + sum(xi**2 - 10 * np.cos(2 * np.pi * xi)) for xi in x]
# return 10*N + sum(x**2 - 10*np.cos(2*np.pi*x), axis=1)
N = len(x)
return 10 * N + sum(x**2 - 10 * np.cos(2 * np.pi * x)) | python | def rastrigin(self, x):
"""Rastrigin test objective function"""
if not isscalar(x[0]):
N = len(x[0])
return [10 * N + sum(xi**2 - 10 * np.cos(2 * np.pi * xi)) for xi in x]
# return 10*N + sum(x**2 - 10*np.cos(2*np.pi*x), axis=1)
N = len(x)
return 10 * N + sum(x**2 - 10 * np.cos(2 * np.pi * x)) | [
"def",
"rastrigin",
"(",
"self",
",",
"x",
")",
":",
"if",
"not",
"isscalar",
"(",
"x",
"[",
"0",
"]",
")",
":",
"N",
"=",
"len",
"(",
"x",
"[",
"0",
"]",
")",
"return",
"[",
"10",
"*",
"N",
"+",
"sum",
"(",
"xi",
"**",
"2",
"-",
"10",
... | Rastrigin test objective function | [
"Rastrigin",
"test",
"objective",
"function"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L8498-L8505 | train | 32,539 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | FitnessFunctions.schwefelmult | def schwefelmult(self, x, pen_fac=1e4):
"""multimodal Schwefel function with domain -500..500"""
y = [x] if isscalar(x[0]) else x
N = len(y[0])
f = array([418.9829 * N - 1.27275661e-5 * N - sum(x * np.sin(np.abs(x)**0.5))
+ pen_fac * sum((abs(x) > 500) * (abs(x) - 500)**2) for x in y])
return f if len(f) > 1 else f[0] | python | def schwefelmult(self, x, pen_fac=1e4):
"""multimodal Schwefel function with domain -500..500"""
y = [x] if isscalar(x[0]) else x
N = len(y[0])
f = array([418.9829 * N - 1.27275661e-5 * N - sum(x * np.sin(np.abs(x)**0.5))
+ pen_fac * sum((abs(x) > 500) * (abs(x) - 500)**2) for x in y])
return f if len(f) > 1 else f[0] | [
"def",
"schwefelmult",
"(",
"self",
",",
"x",
",",
"pen_fac",
"=",
"1e4",
")",
":",
"y",
"=",
"[",
"x",
"]",
"if",
"isscalar",
"(",
"x",
"[",
"0",
"]",
")",
"else",
"x",
"N",
"=",
"len",
"(",
"y",
"[",
"0",
"]",
")",
"f",
"=",
"array",
"(... | multimodal Schwefel function with domain -500..500 | [
"multimodal",
"Schwefel",
"function",
"with",
"domain",
"-",
"500",
"..",
"500"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L8519-L8525 | train | 32,540 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | FitnessFunctions.lincon | def lincon(self, x, theta=0.01):
"""ridge like linear function with one linear constraint"""
if x[0] < 0:
return np.NaN
return theta * x[1] + x[0] | python | def lincon(self, x, theta=0.01):
"""ridge like linear function with one linear constraint"""
if x[0] < 0:
return np.NaN
return theta * x[1] + x[0] | [
"def",
"lincon",
"(",
"self",
",",
"x",
",",
"theta",
"=",
"0.01",
")",
":",
"if",
"x",
"[",
"0",
"]",
"<",
"0",
":",
"return",
"np",
".",
"NaN",
"return",
"theta",
"*",
"x",
"[",
"1",
"]",
"+",
"x",
"[",
"0",
"]"
] | ridge like linear function with one linear constraint | [
"ridge",
"like",
"linear",
"function",
"with",
"one",
"linear",
"constraint"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L8530-L8534 | train | 32,541 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | FitnessFunctions.rosen_nesterov | def rosen_nesterov(self, x, rho=100):
"""needs exponential number of steps in a non-increasing f-sequence.
x_0 = (-1,1,...,1)
See Jarre (2011) "On Nesterov's Smooth Chebyshev-Rosenbrock Function"
"""
f = 0.25 * (x[0] - 1)**2
f += rho * sum((x[1:] - 2 * x[:-1]**2 + 1)**2)
return f | python | def rosen_nesterov(self, x, rho=100):
"""needs exponential number of steps in a non-increasing f-sequence.
x_0 = (-1,1,...,1)
See Jarre (2011) "On Nesterov's Smooth Chebyshev-Rosenbrock Function"
"""
f = 0.25 * (x[0] - 1)**2
f += rho * sum((x[1:] - 2 * x[:-1]**2 + 1)**2)
return f | [
"def",
"rosen_nesterov",
"(",
"self",
",",
"x",
",",
"rho",
"=",
"100",
")",
":",
"f",
"=",
"0.25",
"*",
"(",
"x",
"[",
"0",
"]",
"-",
"1",
")",
"**",
"2",
"f",
"+=",
"rho",
"*",
"sum",
"(",
"(",
"x",
"[",
"1",
":",
"]",
"-",
"2",
"*",
... | needs exponential number of steps in a non-increasing f-sequence.
x_0 = (-1,1,...,1)
See Jarre (2011) "On Nesterov's Smooth Chebyshev-Rosenbrock Function" | [
"needs",
"exponential",
"number",
"of",
"steps",
"in",
"a",
"non",
"-",
"increasing",
"f",
"-",
"sequence",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L8535-L8544 | train | 32,542 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | FitnessFunctions.bukin | def bukin(self, x):
"""Bukin function from Wikipedia, generalized simplistically from 2-D.
http://en.wikipedia.org/wiki/Test_functions_for_optimization"""
s = 0
for k in xrange((1+len(x)) // 2):
z = x[2 * k]
y = x[min((2*k + 1, len(x)-1))]
s += 100 * np.abs(y - 0.01 * z**2)**0.5 + 0.01 * np.abs(z + 10)
return s | python | def bukin(self, x):
"""Bukin function from Wikipedia, generalized simplistically from 2-D.
http://en.wikipedia.org/wiki/Test_functions_for_optimization"""
s = 0
for k in xrange((1+len(x)) // 2):
z = x[2 * k]
y = x[min((2*k + 1, len(x)-1))]
s += 100 * np.abs(y - 0.01 * z**2)**0.5 + 0.01 * np.abs(z + 10)
return s | [
"def",
"bukin",
"(",
"self",
",",
"x",
")",
":",
"s",
"=",
"0",
"for",
"k",
"in",
"xrange",
"(",
"(",
"1",
"+",
"len",
"(",
"x",
")",
")",
"//",
"2",
")",
":",
"z",
"=",
"x",
"[",
"2",
"*",
"k",
"]",
"y",
"=",
"x",
"[",
"min",
"(",
... | Bukin function from Wikipedia, generalized simplistically from 2-D.
http://en.wikipedia.org/wiki/Test_functions_for_optimization | [
"Bukin",
"function",
"from",
"Wikipedia",
"generalized",
"simplistically",
"from",
"2",
"-",
"D",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L8562-L8571 | train | 32,543 |
flowersteam/explauto | explauto/models/pydmps/dmp.py | DMPs.check_offset | def check_offset(self):
"""Check to see if initial position and goal are the same
if they are, offset slightly so that the forcing term is not 0"""
for d in range(self.dmps):
if (self.y0[d] == self.goal[d]):
self.goal[d] += 1e-4 | python | def check_offset(self):
"""Check to see if initial position and goal are the same
if they are, offset slightly so that the forcing term is not 0"""
for d in range(self.dmps):
if (self.y0[d] == self.goal[d]):
self.goal[d] += 1e-4 | [
"def",
"check_offset",
"(",
"self",
")",
":",
"for",
"d",
"in",
"range",
"(",
"self",
".",
"dmps",
")",
":",
"if",
"(",
"self",
".",
"y0",
"[",
"d",
"]",
"==",
"self",
".",
"goal",
"[",
"d",
"]",
")",
":",
"self",
".",
"goal",
"[",
"d",
"]"... | Check to see if initial position and goal are the same
if they are, offset slightly so that the forcing term is not 0 | [
"Check",
"to",
"see",
"if",
"initial",
"position",
"and",
"goal",
"are",
"the",
"same",
"if",
"they",
"are",
"offset",
"slightly",
"so",
"that",
"the",
"forcing",
"term",
"is",
"not",
"0"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/models/pydmps/dmp.py#L65-L71 | train | 32,544 |
flowersteam/explauto | explauto/models/pydmps/dmp.py | DMPs.rollout | def rollout(self, timesteps=None, **kwargs):
"""Generate a system trial, no feedback is incorporated."""
self.reset_state()
if timesteps is None:
if kwargs.has_key('tau'):
timesteps = int(self.timesteps / kwargs['tau'])
else:
timesteps = self.timesteps
# set up tracking vectors
y_track = np.zeros((timesteps, self.dmps))
dy_track = np.zeros((timesteps, self.dmps))
ddy_track = np.zeros((timesteps, self.dmps))
for t in range(timesteps):
y, dy, ddy = self.step(**kwargs)
# record timestep
y_track[t] = y
dy_track[t] = dy
ddy_track[t] = ddy
return y_track, dy_track, ddy_track | python | def rollout(self, timesteps=None, **kwargs):
"""Generate a system trial, no feedback is incorporated."""
self.reset_state()
if timesteps is None:
if kwargs.has_key('tau'):
timesteps = int(self.timesteps / kwargs['tau'])
else:
timesteps = self.timesteps
# set up tracking vectors
y_track = np.zeros((timesteps, self.dmps))
dy_track = np.zeros((timesteps, self.dmps))
ddy_track = np.zeros((timesteps, self.dmps))
for t in range(timesteps):
y, dy, ddy = self.step(**kwargs)
# record timestep
y_track[t] = y
dy_track[t] = dy
ddy_track[t] = ddy
return y_track, dy_track, ddy_track | [
"def",
"rollout",
"(",
"self",
",",
"timesteps",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"reset_state",
"(",
")",
"if",
"timesteps",
"is",
"None",
":",
"if",
"kwargs",
".",
"has_key",
"(",
"'tau'",
")",
":",
"timesteps",
"=",
"... | Generate a system trial, no feedback is incorporated. | [
"Generate",
"a",
"system",
"trial",
"no",
"feedback",
"is",
"incorporated",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/models/pydmps/dmp.py#L147-L172 | train | 32,545 |
flowersteam/explauto | explauto/models/pydmps/dmp.py | DMPs.reset_state | def reset_state(self):
"""Reset the system state"""
self.y = self.y0.copy()
self.dy = np.zeros(self.dmps)
self.ddy = np.zeros(self.dmps)
self.cs.reset_state() | python | def reset_state(self):
"""Reset the system state"""
self.y = self.y0.copy()
self.dy = np.zeros(self.dmps)
self.ddy = np.zeros(self.dmps)
self.cs.reset_state() | [
"def",
"reset_state",
"(",
"self",
")",
":",
"self",
".",
"y",
"=",
"self",
".",
"y0",
".",
"copy",
"(",
")",
"self",
".",
"dy",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"dmps",
")",
"self",
".",
"ddy",
"=",
"np",
".",
"zeros",
"(",
"self",... | Reset the system state | [
"Reset",
"the",
"system",
"state"
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/models/pydmps/dmp.py#L174-L179 | train | 32,546 |
flowersteam/explauto | explauto/models/pydmps/dmp.py | DMPs.step | def step(self, tau=1.0, state_fb=None):
"""Run the DMP system for a single timestep.
tau float: scales the timestep
increase tau to make the system execute faster
state_fb np.array: optional system feedback
"""
# run canonical system
cs_args = {'tau':tau,
'error_coupling':1.0}
if state_fb is not None:
# take the 2 norm of the overall error
state_fb = state_fb.reshape(1,self.dmps)
dist = np.sqrt(np.sum((state_fb - self.y)**2))
cs_args['error_coupling'] = 1.0 / (1.0 + 10*dist)
x = self.cs.step(**cs_args)
# generate basis function activation
psi = self.gen_psi(x)
for d in range(self.dmps):
# generate the forcing term
f = self.gen_front_term(x, d) * \
(np.dot(psi, self.w[d])) / np.sum(psi) if self.bfs > 0. else 0.
# DMP acceleration
self.ddy[d] = (self.ay[d] *
(self.by[d] * (self.goal[d] - self.y[d]) - \
self.dy[d]/tau) + f) * tau
self.dy[d] += self.ddy[d] * tau * self.dt * cs_args['error_coupling']
self.y[d] += self.dy[d] * self.dt * cs_args['error_coupling']
return self.y, self.dy, self.ddy | python | def step(self, tau=1.0, state_fb=None):
"""Run the DMP system for a single timestep.
tau float: scales the timestep
increase tau to make the system execute faster
state_fb np.array: optional system feedback
"""
# run canonical system
cs_args = {'tau':tau,
'error_coupling':1.0}
if state_fb is not None:
# take the 2 norm of the overall error
state_fb = state_fb.reshape(1,self.dmps)
dist = np.sqrt(np.sum((state_fb - self.y)**2))
cs_args['error_coupling'] = 1.0 / (1.0 + 10*dist)
x = self.cs.step(**cs_args)
# generate basis function activation
psi = self.gen_psi(x)
for d in range(self.dmps):
# generate the forcing term
f = self.gen_front_term(x, d) * \
(np.dot(psi, self.w[d])) / np.sum(psi) if self.bfs > 0. else 0.
# DMP acceleration
self.ddy[d] = (self.ay[d] *
(self.by[d] * (self.goal[d] - self.y[d]) - \
self.dy[d]/tau) + f) * tau
self.dy[d] += self.ddy[d] * tau * self.dt * cs_args['error_coupling']
self.y[d] += self.dy[d] * self.dt * cs_args['error_coupling']
return self.y, self.dy, self.ddy | [
"def",
"step",
"(",
"self",
",",
"tau",
"=",
"1.0",
",",
"state_fb",
"=",
"None",
")",
":",
"# run canonical system",
"cs_args",
"=",
"{",
"'tau'",
":",
"tau",
",",
"'error_coupling'",
":",
"1.0",
"}",
"if",
"state_fb",
"is",
"not",
"None",
":",
"# tak... | Run the DMP system for a single timestep.
tau float: scales the timestep
increase tau to make the system execute faster
state_fb np.array: optional system feedback | [
"Run",
"the",
"DMP",
"system",
"for",
"a",
"single",
"timestep",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/models/pydmps/dmp.py#L181-L215 | train | 32,547 |
flowersteam/explauto | explauto/environment/npendulum/simulation.py | step | def step(weights, duration):
""" This function creates a sum of boxcar functions.
:param numpy.array weight: height of each boxcar function.
:param float duration: duration of the generated trajectory.
"""
dt = duration / len(weights)
def activate(t, dt):
"""This function returns 1 if t is in [0, dt[ and 0 otherwise.
:param float t: current time
:param float dt: time step
"""
return 0 <= t < dt
return (lambda t: sum([w * activate(t - i * dt, dt) for i, w in enumerate(weights)])) | python | def step(weights, duration):
""" This function creates a sum of boxcar functions.
:param numpy.array weight: height of each boxcar function.
:param float duration: duration of the generated trajectory.
"""
dt = duration / len(weights)
def activate(t, dt):
"""This function returns 1 if t is in [0, dt[ and 0 otherwise.
:param float t: current time
:param float dt: time step
"""
return 0 <= t < dt
return (lambda t: sum([w * activate(t - i * dt, dt) for i, w in enumerate(weights)])) | [
"def",
"step",
"(",
"weights",
",",
"duration",
")",
":",
"dt",
"=",
"duration",
"/",
"len",
"(",
"weights",
")",
"def",
"activate",
"(",
"t",
",",
"dt",
")",
":",
"\"\"\"This function returns 1 if t is in [0, dt[ and 0 otherwise.\n\n :param float t: current ti... | This function creates a sum of boxcar functions.
:param numpy.array weight: height of each boxcar function.
:param float duration: duration of the generated trajectory. | [
"This",
"function",
"creates",
"a",
"sum",
"of",
"boxcar",
"functions",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/environment/npendulum/simulation.py#L9-L26 | train | 32,548 |
flowersteam/explauto | explauto/environment/npendulum/simulation.py | cartesian | def cartesian(n, states):
""" This function computes cartesians coordinates from the states returned by the simulate function.
:param int n: number of particules suspended to the top one
:param numpy.array states: list of the positions and speeds at a certain time.
"""
length = 1. / n # arm_length
pos_x = hstack((states[0], zeros(n)))
pos_y = zeros(n + 1)
for j in arange(1, n + 1):
pos_x[j] = pos_x[j - 1] + length * cos(states[j])
pos_y[j] = pos_y[j - 1] + length * sin(states[j])
pos = hstack((pos_x, pos_y))
return pos | python | def cartesian(n, states):
""" This function computes cartesians coordinates from the states returned by the simulate function.
:param int n: number of particules suspended to the top one
:param numpy.array states: list of the positions and speeds at a certain time.
"""
length = 1. / n # arm_length
pos_x = hstack((states[0], zeros(n)))
pos_y = zeros(n + 1)
for j in arange(1, n + 1):
pos_x[j] = pos_x[j - 1] + length * cos(states[j])
pos_y[j] = pos_y[j - 1] + length * sin(states[j])
pos = hstack((pos_x, pos_y))
return pos | [
"def",
"cartesian",
"(",
"n",
",",
"states",
")",
":",
"length",
"=",
"1.",
"/",
"n",
"# arm_length",
"pos_x",
"=",
"hstack",
"(",
"(",
"states",
"[",
"0",
"]",
",",
"zeros",
"(",
"n",
")",
")",
")",
"pos_y",
"=",
"zeros",
"(",
"n",
"+",
"1",
... | This function computes cartesians coordinates from the states returned by the simulate function.
:param int n: number of particules suspended to the top one
:param numpy.array states: list of the positions and speeds at a certain time. | [
"This",
"function",
"computes",
"cartesians",
"coordinates",
"from",
"the",
"states",
"returned",
"by",
"the",
"simulate",
"function",
"."
] | cf0f81ecb9f6412f7276a95bd27359000e1e26b6 | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/environment/npendulum/simulation.py#L151-L164 | train | 32,549 |
aamalev/aiohttp_apiset | aiohttp_apiset/swagger/route.py | SwaggerRoute.build_swagger_data | def build_swagger_data(self, loader):
""" Prepare data when schema loaded
:param swagger_schema: loaded schema
"""
if self.is_built:
return
self.is_built = True
self._required = []
self._parameters = {}
if not self._swagger_data:
return
elif loader is not None:
data = loader.resolve_data(self._swagger_data).copy()
else:
data = self._swagger_data
for param in data.get('parameters', ()):
p = param.copy()
if loader is None:
p = allOf(p)
name = p.pop('name')
self._parameters[name] = p
if p.pop('required', False):
self._required.append(name) | python | def build_swagger_data(self, loader):
""" Prepare data when schema loaded
:param swagger_schema: loaded schema
"""
if self.is_built:
return
self.is_built = True
self._required = []
self._parameters = {}
if not self._swagger_data:
return
elif loader is not None:
data = loader.resolve_data(self._swagger_data).copy()
else:
data = self._swagger_data
for param in data.get('parameters', ()):
p = param.copy()
if loader is None:
p = allOf(p)
name = p.pop('name')
self._parameters[name] = p
if p.pop('required', False):
self._required.append(name) | [
"def",
"build_swagger_data",
"(",
"self",
",",
"loader",
")",
":",
"if",
"self",
".",
"is_built",
":",
"return",
"self",
".",
"is_built",
"=",
"True",
"self",
".",
"_required",
"=",
"[",
"]",
"self",
".",
"_parameters",
"=",
"{",
"}",
"if",
"not",
"s... | Prepare data when schema loaded
:param swagger_schema: loaded schema | [
"Prepare",
"data",
"when",
"schema",
"loaded"
] | ba3492ce929e39be1325d506b727a8bfb34e7b33 | https://github.com/aamalev/aiohttp_apiset/blob/ba3492ce929e39be1325d506b727a8bfb34e7b33/aiohttp_apiset/swagger/route.py#L38-L62 | train | 32,550 |
aamalev/aiohttp_apiset | aiohttp_apiset/swagger/route.py | SwaggerRoute.validate | async def validate(self, request: web.Request):
""" Returns parameters extract from request and multidict errors
:param request: Request
:return: tuple of parameters and errors
"""
parameters = {}
files = {}
errors = self.errors_factory()
body = None
if request.method in request.POST_METHODS:
try:
body = await self._content_receiver.receive(request)
except ValueError as e:
errors[request.content_type].add(str(e))
except TypeError:
errors[request.content_type].add('Not supported content type')
for name, param in self._parameters.items():
where = param['in']
schema = param.get('schema', param)
vtype = schema['type']
is_array = vtype == 'array'
if where == 'query':
source = request.query
elif where == 'header':
source = request.headers
elif where == 'path':
source = request.match_info
elif body is None:
source = ()
elif where == 'formData':
source = body
elif where == 'body':
if isinstance(body, BaseException):
errors[name].add(str(body))
else:
parameters[name] = body
continue
else:
raise ValueError(where)
if is_array and hasattr(source, 'getall'):
collection_format = param.get('collectionFormat')
default = param.get('default', [])
value = get_collection(source, name,
collection_format, default)
if param.get('minItems') and not value \
and name not in self._required:
continue
elif isinstance(source, Mapping) and name in source and (
vtype not in ('number', 'integer') or source[name] != ''
):
value = source[name]
elif 'default' in param:
parameters[name] = param['default']
continue
elif name in self._required:
errors[name].add('Required')
if isinstance(source, BaseException):
errors[name].add(str(body))
continue
else:
continue
if is_array:
vtype = schema['items']['type']
vformat = schema['items'].get('format')
else:
vformat = schema.get('format')
if source is body and isinstance(body, dict):
pass
elif vtype not in ('string', 'file'):
value = convert(name, value, vtype, vformat, errors)
if vtype == 'file':
files[name] = value
else:
parameters[name] = value
parameters = self._validate(parameters, errors)
parameters.update(files)
return parameters, errors | python | async def validate(self, request: web.Request):
""" Returns parameters extract from request and multidict errors
:param request: Request
:return: tuple of parameters and errors
"""
parameters = {}
files = {}
errors = self.errors_factory()
body = None
if request.method in request.POST_METHODS:
try:
body = await self._content_receiver.receive(request)
except ValueError as e:
errors[request.content_type].add(str(e))
except TypeError:
errors[request.content_type].add('Not supported content type')
for name, param in self._parameters.items():
where = param['in']
schema = param.get('schema', param)
vtype = schema['type']
is_array = vtype == 'array'
if where == 'query':
source = request.query
elif where == 'header':
source = request.headers
elif where == 'path':
source = request.match_info
elif body is None:
source = ()
elif where == 'formData':
source = body
elif where == 'body':
if isinstance(body, BaseException):
errors[name].add(str(body))
else:
parameters[name] = body
continue
else:
raise ValueError(where)
if is_array and hasattr(source, 'getall'):
collection_format = param.get('collectionFormat')
default = param.get('default', [])
value = get_collection(source, name,
collection_format, default)
if param.get('minItems') and not value \
and name not in self._required:
continue
elif isinstance(source, Mapping) and name in source and (
vtype not in ('number', 'integer') or source[name] != ''
):
value = source[name]
elif 'default' in param:
parameters[name] = param['default']
continue
elif name in self._required:
errors[name].add('Required')
if isinstance(source, BaseException):
errors[name].add(str(body))
continue
else:
continue
if is_array:
vtype = schema['items']['type']
vformat = schema['items'].get('format')
else:
vformat = schema.get('format')
if source is body and isinstance(body, dict):
pass
elif vtype not in ('string', 'file'):
value = convert(name, value, vtype, vformat, errors)
if vtype == 'file':
files[name] = value
else:
parameters[name] = value
parameters = self._validate(parameters, errors)
parameters.update(files)
return parameters, errors | [
"async",
"def",
"validate",
"(",
"self",
",",
"request",
":",
"web",
".",
"Request",
")",
":",
"parameters",
"=",
"{",
"}",
"files",
"=",
"{",
"}",
"errors",
"=",
"self",
".",
"errors_factory",
"(",
")",
"body",
"=",
"None",
"if",
"request",
".",
"... | Returns parameters extract from request and multidict errors
:param request: Request
:return: tuple of parameters and errors | [
"Returns",
"parameters",
"extract",
"from",
"request",
"and",
"multidict",
"errors"
] | ba3492ce929e39be1325d506b727a8bfb34e7b33 | https://github.com/aamalev/aiohttp_apiset/blob/ba3492ce929e39be1325d506b727a8bfb34e7b33/aiohttp_apiset/swagger/route.py#L96-L181 | train | 32,551 |
aamalev/aiohttp_apiset | aiohttp_apiset/swagger/router.py | SwaggerRouter.include | def include(self, spec, *,
basePath=None,
operationId_mapping=None,
name=None):
""" Adds a new specification to a router
:param spec: path to specification
:param basePath: override base path specify in specification
:param operationId_mapping: mapping for handlers
:param name: name to access original spec
"""
data = self._file_loader.load(spec)
if basePath is None:
basePath = data.get('basePath', '')
if name is not None:
d = dict(data)
d['basePath'] = basePath
self._swagger_data[name] = d
# TODO clear d
swagger_data = {k: v for k, v in data.items() if k != 'paths'}
swagger_data['basePath'] = basePath
for url, methods in data.get('paths', {}).items():
url = basePath + url
methods = dict(methods)
location_name = methods.pop(self.NAME, None)
parameters = methods.pop('parameters', [])
for method, body in methods.items():
if method == self.VIEW:
view = utils.import_obj(body)
view.add_routes(self, prefix=url, encoding=self._encoding)
continue
body = dict(body)
if parameters:
body['parameters'] = parameters + \
body.get('parameters', [])
handler = body.pop(self.HANDLER, None)
name = location_name or handler
if not handler:
op_id = body.get('operationId')
if op_id and operationId_mapping:
handler = operationId_mapping.get(op_id)
if handler:
name = location_name or op_id
if handler:
validate = body.pop(self.VALIDATE, self._default_validate)
self.add_route(
method.upper(), utils.url_normolize(url),
handler=handler,
name=name,
swagger_data=body,
validate=validate,
)
self._swagger_data[basePath] = swagger_data
for route in self.routes():
if isinstance(route, SwaggerRoute) and not route.is_built:
route.build_swagger_data(self._file_loader) | python | def include(self, spec, *,
basePath=None,
operationId_mapping=None,
name=None):
""" Adds a new specification to a router
:param spec: path to specification
:param basePath: override base path specify in specification
:param operationId_mapping: mapping for handlers
:param name: name to access original spec
"""
data = self._file_loader.load(spec)
if basePath is None:
basePath = data.get('basePath', '')
if name is not None:
d = dict(data)
d['basePath'] = basePath
self._swagger_data[name] = d
# TODO clear d
swagger_data = {k: v for k, v in data.items() if k != 'paths'}
swagger_data['basePath'] = basePath
for url, methods in data.get('paths', {}).items():
url = basePath + url
methods = dict(methods)
location_name = methods.pop(self.NAME, None)
parameters = methods.pop('parameters', [])
for method, body in methods.items():
if method == self.VIEW:
view = utils.import_obj(body)
view.add_routes(self, prefix=url, encoding=self._encoding)
continue
body = dict(body)
if parameters:
body['parameters'] = parameters + \
body.get('parameters', [])
handler = body.pop(self.HANDLER, None)
name = location_name or handler
if not handler:
op_id = body.get('operationId')
if op_id and operationId_mapping:
handler = operationId_mapping.get(op_id)
if handler:
name = location_name or op_id
if handler:
validate = body.pop(self.VALIDATE, self._default_validate)
self.add_route(
method.upper(), utils.url_normolize(url),
handler=handler,
name=name,
swagger_data=body,
validate=validate,
)
self._swagger_data[basePath] = swagger_data
for route in self.routes():
if isinstance(route, SwaggerRoute) and not route.is_built:
route.build_swagger_data(self._file_loader) | [
"def",
"include",
"(",
"self",
",",
"spec",
",",
"*",
",",
"basePath",
"=",
"None",
",",
"operationId_mapping",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"data",
"=",
"self",
".",
"_file_loader",
".",
"load",
"(",
"spec",
")",
"if",
"basePath"... | Adds a new specification to a router
:param spec: path to specification
:param basePath: override base path specify in specification
:param operationId_mapping: mapping for handlers
:param name: name to access original spec | [
"Adds",
"a",
"new",
"specification",
"to",
"a",
"router"
] | ba3492ce929e39be1325d506b727a8bfb34e7b33 | https://github.com/aamalev/aiohttp_apiset/blob/ba3492ce929e39be1325d506b727a8bfb34e7b33/aiohttp_apiset/swagger/router.py#L183-L244 | train | 32,552 |
aamalev/aiohttp_apiset | aiohttp_apiset/swagger/router.py | SwaggerRouter.setup | def setup(self, app: web.Application):
""" Installation routes to app.router
:param app: instance of aiohttp.web.Application
"""
if self.app is app:
raise ValueError('The router is already configured '
'for this application')
self.app = app
routes = sorted(
((r.name, (r, r.url_for().human_repr())) for r in self.routes()),
key=utils.sort_key)
exists = set() # type: Set[str]
for name, (route, path) in routes:
if name and name not in exists:
exists.add(name)
else:
name = None
app.router.add_route(
route.method, path,
route.handler, name=name) | python | def setup(self, app: web.Application):
""" Installation routes to app.router
:param app: instance of aiohttp.web.Application
"""
if self.app is app:
raise ValueError('The router is already configured '
'for this application')
self.app = app
routes = sorted(
((r.name, (r, r.url_for().human_repr())) for r in self.routes()),
key=utils.sort_key)
exists = set() # type: Set[str]
for name, (route, path) in routes:
if name and name not in exists:
exists.add(name)
else:
name = None
app.router.add_route(
route.method, path,
route.handler, name=name) | [
"def",
"setup",
"(",
"self",
",",
"app",
":",
"web",
".",
"Application",
")",
":",
"if",
"self",
".",
"app",
"is",
"app",
":",
"raise",
"ValueError",
"(",
"'The router is already configured '",
"'for this application'",
")",
"self",
".",
"app",
"=",
"app",
... | Installation routes to app.router
:param app: instance of aiohttp.web.Application | [
"Installation",
"routes",
"to",
"app",
".",
"router"
] | ba3492ce929e39be1325d506b727a8bfb34e7b33 | https://github.com/aamalev/aiohttp_apiset/blob/ba3492ce929e39be1325d506b727a8bfb34e7b33/aiohttp_apiset/swagger/router.py#L283-L303 | train | 32,553 |
aamalev/aiohttp_apiset | aiohttp_apiset/jinja2.py | template | def template(template_name, *, app_key=APP_KEY, encoding='utf-8', status=200):
"""
Decorator compatible with aiohttp_apiset router
"""
def wrapper(func):
@functools.wraps(func)
async def wrapped(*args, **kwargs):
if asyncio.iscoroutinefunction(func):
coro = func
else:
coro = asyncio.coroutine(func)
context = await coro(*args, **kwargs)
if isinstance(context, web.StreamResponse):
return context
if 'request' in kwargs:
request = kwargs['request']
elif not args:
request = None
warnings.warn("Request not detected")
elif isinstance(args[0], AbstractView):
request = args[0].request
else:
request = args[-1]
response = render_template(template_name, request, context,
app_key=app_key, encoding=encoding)
response.set_status(status)
return response
return wrapped
return wrapper | python | def template(template_name, *, app_key=APP_KEY, encoding='utf-8', status=200):
"""
Decorator compatible with aiohttp_apiset router
"""
def wrapper(func):
@functools.wraps(func)
async def wrapped(*args, **kwargs):
if asyncio.iscoroutinefunction(func):
coro = func
else:
coro = asyncio.coroutine(func)
context = await coro(*args, **kwargs)
if isinstance(context, web.StreamResponse):
return context
if 'request' in kwargs:
request = kwargs['request']
elif not args:
request = None
warnings.warn("Request not detected")
elif isinstance(args[0], AbstractView):
request = args[0].request
else:
request = args[-1]
response = render_template(template_name, request, context,
app_key=app_key, encoding=encoding)
response.set_status(status)
return response
return wrapped
return wrapper | [
"def",
"template",
"(",
"template_name",
",",
"*",
",",
"app_key",
"=",
"APP_KEY",
",",
"encoding",
"=",
"'utf-8'",
",",
"status",
"=",
"200",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"async... | Decorator compatible with aiohttp_apiset router | [
"Decorator",
"compatible",
"with",
"aiohttp_apiset",
"router"
] | ba3492ce929e39be1325d506b727a8bfb34e7b33 | https://github.com/aamalev/aiohttp_apiset/blob/ba3492ce929e39be1325d506b727a8bfb34e7b33/aiohttp_apiset/jinja2.py#L10-L41 | train | 32,554 |
aamalev/aiohttp_apiset | aiohttp_apiset/swagger/validate.py | get_collection | def get_collection(source, name, collection_format, default):
"""get collection named `name` from the given `source` that
formatted accordingly to `collection_format`.
"""
if collection_format in COLLECTION_SEP:
separator = COLLECTION_SEP[collection_format]
value = source.get(name, None)
if value is None:
return default
return value.split(separator)
if collection_format == 'brackets':
return source.getall(name + '[]', default)
else: # format: multi
return source.getall(name, default) | python | def get_collection(source, name, collection_format, default):
"""get collection named `name` from the given `source` that
formatted accordingly to `collection_format`.
"""
if collection_format in COLLECTION_SEP:
separator = COLLECTION_SEP[collection_format]
value = source.get(name, None)
if value is None:
return default
return value.split(separator)
if collection_format == 'brackets':
return source.getall(name + '[]', default)
else: # format: multi
return source.getall(name, default) | [
"def",
"get_collection",
"(",
"source",
",",
"name",
",",
"collection_format",
",",
"default",
")",
":",
"if",
"collection_format",
"in",
"COLLECTION_SEP",
":",
"separator",
"=",
"COLLECTION_SEP",
"[",
"collection_format",
"]",
"value",
"=",
"source",
".",
"get"... | get collection named `name` from the given `source` that
formatted accordingly to `collection_format`. | [
"get",
"collection",
"named",
"name",
"from",
"the",
"given",
"source",
"that",
"formatted",
"accordingly",
"to",
"collection_format",
"."
] | ba3492ce929e39be1325d506b727a8bfb34e7b33 | https://github.com/aamalev/aiohttp_apiset/blob/ba3492ce929e39be1325d506b727a8bfb34e7b33/aiohttp_apiset/swagger/validate.py#L171-L184 | train | 32,555 |
aamalev/aiohttp_apiset | aiohttp_apiset/compat.py | CompatRouter.add_get | def add_get(self, *args, **kwargs):
"""
Shortcut for add_route with method GET
"""
return self.add_route(hdrs.METH_GET, *args, **kwargs) | python | def add_get(self, *args, **kwargs):
"""
Shortcut for add_route with method GET
"""
return self.add_route(hdrs.METH_GET, *args, **kwargs) | [
"def",
"add_get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"add_route",
"(",
"hdrs",
".",
"METH_GET",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Shortcut for add_route with method GET | [
"Shortcut",
"for",
"add_route",
"with",
"method",
"GET"
] | ba3492ce929e39be1325d506b727a8bfb34e7b33 | https://github.com/aamalev/aiohttp_apiset/blob/ba3492ce929e39be1325d506b727a8bfb34e7b33/aiohttp_apiset/compat.py#L352-L356 | train | 32,556 |
aamalev/aiohttp_apiset | aiohttp_apiset/swagger/operations.py | OperationIdMapping.add | def add(self, *args, **kwargs):
""" Add new mapping from args and kwargs
>>> om = OperationIdMapping()
>>> om.add(
... OperationIdMapping(),
... 'aiohttp_apiset.swagger.operations', # any module
... getPets='mymod.handler',
... getPet='mymod.get_pet',
... )
>>> om['getPets']
'mymod.handler'
:param args: str, Mapping, module or obj
:param kwargs: operationId='handler' or operationId=handler
"""
for arg in args:
if isinstance(arg, str):
self._operations.append(self._from_str(arg))
else:
self._operations.append(arg)
if kwargs:
self._operations.append(kwargs) | python | def add(self, *args, **kwargs):
""" Add new mapping from args and kwargs
>>> om = OperationIdMapping()
>>> om.add(
... OperationIdMapping(),
... 'aiohttp_apiset.swagger.operations', # any module
... getPets='mymod.handler',
... getPet='mymod.get_pet',
... )
>>> om['getPets']
'mymod.handler'
:param args: str, Mapping, module or obj
:param kwargs: operationId='handler' or operationId=handler
"""
for arg in args:
if isinstance(arg, str):
self._operations.append(self._from_str(arg))
else:
self._operations.append(arg)
if kwargs:
self._operations.append(kwargs) | [
"def",
"add",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"arg",
"in",
"args",
":",
"if",
"isinstance",
"(",
"arg",
",",
"str",
")",
":",
"self",
".",
"_operations",
".",
"append",
"(",
"self",
".",
"_from_str",
"(",
... | Add new mapping from args and kwargs
>>> om = OperationIdMapping()
>>> om.add(
... OperationIdMapping(),
... 'aiohttp_apiset.swagger.operations', # any module
... getPets='mymod.handler',
... getPet='mymod.get_pet',
... )
>>> om['getPets']
'mymod.handler'
:param args: str, Mapping, module or obj
:param kwargs: operationId='handler' or operationId=handler | [
"Add",
"new",
"mapping",
"from",
"args",
"and",
"kwargs"
] | ba3492ce929e39be1325d506b727a8bfb34e7b33 | https://github.com/aamalev/aiohttp_apiset/blob/ba3492ce929e39be1325d506b727a8bfb34e7b33/aiohttp_apiset/swagger/operations.py#L48-L70 | train | 32,557 |
mila/pyoo | pyoo.py | str_repr | def str_repr(klass):
"""
Implements string conversion methods for the given class.
The given class must implement the __str__ method. This decorat
will add __repr__ and __unicode__ (for Python 2).
"""
if PY2:
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
klass.__repr__ = lambda self: '<%s: %r>' % (self.__class__.__name__, str(self))
return klass | python | def str_repr(klass):
"""
Implements string conversion methods for the given class.
The given class must implement the __str__ method. This decorat
will add __repr__ and __unicode__ (for Python 2).
"""
if PY2:
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
klass.__repr__ = lambda self: '<%s: %r>' % (self.__class__.__name__, str(self))
return klass | [
"def",
"str_repr",
"(",
"klass",
")",
":",
"if",
"PY2",
":",
"klass",
".",
"__unicode__",
"=",
"klass",
".",
"__str__",
"klass",
".",
"__str__",
"=",
"lambda",
"self",
":",
"self",
".",
"__unicode__",
"(",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"kl... | Implements string conversion methods for the given class.
The given class must implement the __str__ method. This decorat
will add __repr__ and __unicode__ (for Python 2). | [
"Implements",
"string",
"conversion",
"methods",
"for",
"the",
"given",
"class",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L97-L109 | train | 32,558 |
mila/pyoo | pyoo.py | _clean_slice | def _clean_slice(key, length):
"""
Validates and normalizes a cell range slice.
>>> _clean_slice(slice(None, None), 10)
(0, 10)
>>> _clean_slice(slice(-10, 10), 10)
(0, 10)
>>> _clean_slice(slice(-11, 11), 10)
(0, 10)
>>> _clean_slice(slice('x', 'y'), 10)
Traceback (most recent call last):
...
TypeError: Cell indices must be integers, str given.
>>> _clean_slice(slice(0, 10, 2), 10)
Traceback (most recent call last):
...
NotImplementedError: Cell slice with step is not supported.
>>> _clean_slice(slice(5, 5), 10)
Traceback (most recent call last):
...
ValueError: Cell slice can not be empty.
"""
if key.step is not None:
raise NotImplementedError('Cell slice with step is not supported.')
start, stop = key.start, key.stop
if start is None:
start = 0
if stop is None:
stop = length
if not isinstance(start, integer_types):
raise TypeError('Cell indices must be integers, %s given.' % type(start).__name__)
if not isinstance(stop, integer_types):
raise TypeError('Cell indices must be integers, %s given.' % type(stop).__name__)
if start < 0:
start = start + length
if stop < 0:
stop = stop + length
start, stop = max(0, start), min(length, stop)
if start == stop:
raise ValueError('Cell slice can not be empty.')
return start, stop | python | def _clean_slice(key, length):
"""
Validates and normalizes a cell range slice.
>>> _clean_slice(slice(None, None), 10)
(0, 10)
>>> _clean_slice(slice(-10, 10), 10)
(0, 10)
>>> _clean_slice(slice(-11, 11), 10)
(0, 10)
>>> _clean_slice(slice('x', 'y'), 10)
Traceback (most recent call last):
...
TypeError: Cell indices must be integers, str given.
>>> _clean_slice(slice(0, 10, 2), 10)
Traceback (most recent call last):
...
NotImplementedError: Cell slice with step is not supported.
>>> _clean_slice(slice(5, 5), 10)
Traceback (most recent call last):
...
ValueError: Cell slice can not be empty.
"""
if key.step is not None:
raise NotImplementedError('Cell slice with step is not supported.')
start, stop = key.start, key.stop
if start is None:
start = 0
if stop is None:
stop = length
if not isinstance(start, integer_types):
raise TypeError('Cell indices must be integers, %s given.' % type(start).__name__)
if not isinstance(stop, integer_types):
raise TypeError('Cell indices must be integers, %s given.' % type(stop).__name__)
if start < 0:
start = start + length
if stop < 0:
stop = stop + length
start, stop = max(0, start), min(length, stop)
if start == stop:
raise ValueError('Cell slice can not be empty.')
return start, stop | [
"def",
"_clean_slice",
"(",
"key",
",",
"length",
")",
":",
"if",
"key",
".",
"step",
"is",
"not",
"None",
":",
"raise",
"NotImplementedError",
"(",
"'Cell slice with step is not supported.'",
")",
"start",
",",
"stop",
"=",
"key",
".",
"start",
",",
"key",
... | Validates and normalizes a cell range slice.
>>> _clean_slice(slice(None, None), 10)
(0, 10)
>>> _clean_slice(slice(-10, 10), 10)
(0, 10)
>>> _clean_slice(slice(-11, 11), 10)
(0, 10)
>>> _clean_slice(slice('x', 'y'), 10)
Traceback (most recent call last):
...
TypeError: Cell indices must be integers, str given.
>>> _clean_slice(slice(0, 10, 2), 10)
Traceback (most recent call last):
...
NotImplementedError: Cell slice with step is not supported.
>>> _clean_slice(slice(5, 5), 10)
Traceback (most recent call last):
...
ValueError: Cell slice can not be empty. | [
"Validates",
"and",
"normalizes",
"a",
"cell",
"range",
"slice",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L112-L154 | train | 32,559 |
mila/pyoo | pyoo.py | _clean_index | def _clean_index(key, length):
"""
Validates and normalizes a cell range index.
>>> _clean_index(0, 10)
0
>>> _clean_index(-10, 10)
0
>>> _clean_index(10, 10)
Traceback (most recent call last):
...
IndexError: Cell index out of range.
>>> _clean_index(-11, 10)
Traceback (most recent call last):
...
IndexError: Cell index out of range.
>>> _clean_index(None, 10)
Traceback (most recent call last):
...
TypeError: Cell indices must be integers, NoneType given.
"""
if not isinstance(key, integer_types):
raise TypeError('Cell indices must be integers, %s given.' % type(key).__name__)
if -length <= key < 0:
return key + length
elif 0 <= key < length:
return key
else:
raise IndexError('Cell index out of range.') | python | def _clean_index(key, length):
"""
Validates and normalizes a cell range index.
>>> _clean_index(0, 10)
0
>>> _clean_index(-10, 10)
0
>>> _clean_index(10, 10)
Traceback (most recent call last):
...
IndexError: Cell index out of range.
>>> _clean_index(-11, 10)
Traceback (most recent call last):
...
IndexError: Cell index out of range.
>>> _clean_index(None, 10)
Traceback (most recent call last):
...
TypeError: Cell indices must be integers, NoneType given.
"""
if not isinstance(key, integer_types):
raise TypeError('Cell indices must be integers, %s given.' % type(key).__name__)
if -length <= key < 0:
return key + length
elif 0 <= key < length:
return key
else:
raise IndexError('Cell index out of range.') | [
"def",
"_clean_index",
"(",
"key",
",",
"length",
")",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"integer_types",
")",
":",
"raise",
"TypeError",
"(",
"'Cell indices must be integers, %s given.'",
"%",
"type",
"(",
"key",
")",
".",
"__name__",
")",
"i... | Validates and normalizes a cell range index.
>>> _clean_index(0, 10)
0
>>> _clean_index(-10, 10)
0
>>> _clean_index(10, 10)
Traceback (most recent call last):
...
IndexError: Cell index out of range.
>>> _clean_index(-11, 10)
Traceback (most recent call last):
...
IndexError: Cell index out of range.
>>> _clean_index(None, 10)
Traceback (most recent call last):
...
TypeError: Cell indices must be integers, NoneType given. | [
"Validates",
"and",
"normalizes",
"a",
"cell",
"range",
"index",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L157-L186 | train | 32,560 |
mila/pyoo | pyoo.py | _col_name | def _col_name(index):
"""
Converts a column index to a column name.
>>> _col_name(0)
'A'
>>> _col_name(26)
'AA'
"""
for exp in itertools.count(1):
limit = 26 ** exp
if index < limit:
return ''.join(chr(ord('A') + index // (26 ** i) % 26) for i in range(exp-1, -1, -1))
index -= limit | python | def _col_name(index):
"""
Converts a column index to a column name.
>>> _col_name(0)
'A'
>>> _col_name(26)
'AA'
"""
for exp in itertools.count(1):
limit = 26 ** exp
if index < limit:
return ''.join(chr(ord('A') + index // (26 ** i) % 26) for i in range(exp-1, -1, -1))
index -= limit | [
"def",
"_col_name",
"(",
"index",
")",
":",
"for",
"exp",
"in",
"itertools",
".",
"count",
"(",
"1",
")",
":",
"limit",
"=",
"26",
"**",
"exp",
"if",
"index",
"<",
"limit",
":",
"return",
"''",
".",
"join",
"(",
"chr",
"(",
"ord",
"(",
"'A'",
"... | Converts a column index to a column name.
>>> _col_name(0)
'A'
>>> _col_name(26)
'AA' | [
"Converts",
"a",
"column",
"index",
"to",
"a",
"column",
"name",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L202-L216 | train | 32,561 |
mila/pyoo | pyoo.py | Axis.__set_title | def __set_title(self, value):
"""
Sets title of this axis.
"""
# OpenOffice on Debian "squeeze" ignore value of target.XAxis.String
# unless target.HasXAxisTitle is set to True first. (Despite the
# fact that target.HasXAxisTitle is reported to be False until
# target.XAxis.String is set to non empty value.)
self._target.setPropertyValue(self._has_axis_title_property, True)
target = self._get_title_target()
target.setPropertyValue('String', text_type(value)) | python | def __set_title(self, value):
"""
Sets title of this axis.
"""
# OpenOffice on Debian "squeeze" ignore value of target.XAxis.String
# unless target.HasXAxisTitle is set to True first. (Despite the
# fact that target.HasXAxisTitle is reported to be False until
# target.XAxis.String is set to non empty value.)
self._target.setPropertyValue(self._has_axis_title_property, True)
target = self._get_title_target()
target.setPropertyValue('String', text_type(value)) | [
"def",
"__set_title",
"(",
"self",
",",
"value",
")",
":",
"# OpenOffice on Debian \"squeeze\" ignore value of target.XAxis.String",
"# unless target.HasXAxisTitle is set to True first. (Despite the",
"# fact that target.HasXAxisTitle is reported to be False until",
"# target.XAxis.String is s... | Sets title of this axis. | [
"Sets",
"title",
"of",
"this",
"axis",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L505-L515 | train | 32,562 |
mila/pyoo | pyoo.py | Chart.ranges | def ranges(self):
"""
Returns a list of addresses with source data.
"""
ranges = self._target.getRanges()
return map(SheetAddress._from_uno, ranges) | python | def ranges(self):
"""
Returns a list of addresses with source data.
"""
ranges = self._target.getRanges()
return map(SheetAddress._from_uno, ranges) | [
"def",
"ranges",
"(",
"self",
")",
":",
"ranges",
"=",
"self",
".",
"_target",
".",
"getRanges",
"(",
")",
"return",
"map",
"(",
"SheetAddress",
".",
"_from_uno",
",",
"ranges",
")"
] | Returns a list of addresses with source data. | [
"Returns",
"a",
"list",
"of",
"addresses",
"with",
"source",
"data",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L805-L810 | train | 32,563 |
mila/pyoo | pyoo.py | Chart.diagram | def diagram(self):
"""
Diagram - inner content of this chart.
The diagram can be replaced by another type using change_type method.
"""
target = self._embedded.getDiagram()
target_type = target.getDiagramType()
cls = _DIAGRAM_TYPES.get(target_type, Diagram)
return cls(target) | python | def diagram(self):
"""
Diagram - inner content of this chart.
The diagram can be replaced by another type using change_type method.
"""
target = self._embedded.getDiagram()
target_type = target.getDiagramType()
cls = _DIAGRAM_TYPES.get(target_type, Diagram)
return cls(target) | [
"def",
"diagram",
"(",
"self",
")",
":",
"target",
"=",
"self",
".",
"_embedded",
".",
"getDiagram",
"(",
")",
"target_type",
"=",
"target",
".",
"getDiagramType",
"(",
")",
"cls",
"=",
"_DIAGRAM_TYPES",
".",
"get",
"(",
"target_type",
",",
"Diagram",
")... | Diagram - inner content of this chart.
The diagram can be replaced by another type using change_type method. | [
"Diagram",
"-",
"inner",
"content",
"of",
"this",
"chart",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L813-L822 | train | 32,564 |
mila/pyoo | pyoo.py | Chart.change_type | def change_type(self, cls):
"""
Change type of diagram in this chart.
Accepts one of classes which extend Diagram.
"""
target_type = cls._type
target = self._embedded.createInstance(target_type)
self._embedded.setDiagram(target)
return cls(target) | python | def change_type(self, cls):
"""
Change type of diagram in this chart.
Accepts one of classes which extend Diagram.
"""
target_type = cls._type
target = self._embedded.createInstance(target_type)
self._embedded.setDiagram(target)
return cls(target) | [
"def",
"change_type",
"(",
"self",
",",
"cls",
")",
":",
"target_type",
"=",
"cls",
".",
"_type",
"target",
"=",
"self",
".",
"_embedded",
".",
"createInstance",
"(",
"target_type",
")",
"self",
".",
"_embedded",
".",
"setDiagram",
"(",
"target",
")",
"r... | Change type of diagram in this chart.
Accepts one of classes which extend Diagram. | [
"Change",
"type",
"of",
"diagram",
"in",
"this",
"chart",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L824-L833 | train | 32,565 |
mila/pyoo | pyoo.py | ChartCollection.create | def create(self, name, position, ranges=(), col_header=False, row_header=False):
"""
Creates and inserts a new chart.
"""
rect = self._uno_rect(position)
ranges = self._uno_ranges(ranges)
self._create(name, rect, ranges, col_header, row_header)
return self[name] | python | def create(self, name, position, ranges=(), col_header=False, row_header=False):
"""
Creates and inserts a new chart.
"""
rect = self._uno_rect(position)
ranges = self._uno_ranges(ranges)
self._create(name, rect, ranges, col_header, row_header)
return self[name] | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"position",
",",
"ranges",
"=",
"(",
")",
",",
"col_header",
"=",
"False",
",",
"row_header",
"=",
"False",
")",
":",
"rect",
"=",
"self",
".",
"_uno_rect",
"(",
"position",
")",
"ranges",
"=",
"self",
... | Creates and inserts a new chart. | [
"Creates",
"and",
"inserts",
"a",
"new",
"chart",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L852-L859 | train | 32,566 |
mila/pyoo | pyoo.py | SheetCursor.get_target | def get_target(self, row, col, row_count, col_count):
"""
Moves cursor to the specified position and returns in.
"""
# This method is called for almost any operation so it should
# be maximally optimized.
#
# Any comparison here is negligible compared to UNO call. So we do all
# possible checks which can prevent an unnecessary cursor movement.
#
# Generally we need to expand or collapse selection to the desired
# size and move it to the desired position. But both of these actions
# can fail if there is not enough space. For this reason we must
# determine which of the actions has to be done first. In some cases
# we must even move the cursor twice (cursor movement is faster than
# selection change).
#
target = self._target
# If we cannot resize selection now then we must move cursor first.
if self.row + row_count > self.max_row_count or self.col + col_count > self.max_col_count:
# Move cursor to the desired position if possible.
row_delta = row - self.row if row + self.row_count <= self.max_row_count else 0
col_delta = col - self.col if col + self.col_count <= self.max_col_count else 0
target.gotoOffset(col_delta, row_delta)
self.row += row_delta
self.col += col_delta
# Resize selection
if (row_count, col_count) != (self.row_count, self.col_count):
target.collapseToSize(col_count, row_count)
self.row_count = row_count
self.col_count = col_count
# Move cursor to the desired position
if (row, col) != (self.row, self.col):
target.gotoOffset(col - self.col, row - self.row)
self.row = row
self.col = col
return target | python | def get_target(self, row, col, row_count, col_count):
"""
Moves cursor to the specified position and returns in.
"""
# This method is called for almost any operation so it should
# be maximally optimized.
#
# Any comparison here is negligible compared to UNO call. So we do all
# possible checks which can prevent an unnecessary cursor movement.
#
# Generally we need to expand or collapse selection to the desired
# size and move it to the desired position. But both of these actions
# can fail if there is not enough space. For this reason we must
# determine which of the actions has to be done first. In some cases
# we must even move the cursor twice (cursor movement is faster than
# selection change).
#
target = self._target
# If we cannot resize selection now then we must move cursor first.
if self.row + row_count > self.max_row_count or self.col + col_count > self.max_col_count:
# Move cursor to the desired position if possible.
row_delta = row - self.row if row + self.row_count <= self.max_row_count else 0
col_delta = col - self.col if col + self.col_count <= self.max_col_count else 0
target.gotoOffset(col_delta, row_delta)
self.row += row_delta
self.col += col_delta
# Resize selection
if (row_count, col_count) != (self.row_count, self.col_count):
target.collapseToSize(col_count, row_count)
self.row_count = row_count
self.col_count = col_count
# Move cursor to the desired position
if (row, col) != (self.row, self.col):
target.gotoOffset(col - self.col, row - self.row)
self.row = row
self.col = col
return target | [
"def",
"get_target",
"(",
"self",
",",
"row",
",",
"col",
",",
"row_count",
",",
"col_count",
")",
":",
"# This method is called for almost any operation so it should",
"# be maximally optimized.",
"#",
"# Any comparison here is negligible compared to UNO call. So we do all",
"# ... | Moves cursor to the specified position and returns in. | [
"Moves",
"cursor",
"to",
"the",
"specified",
"position",
"and",
"returns",
"in",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L916-L952 | train | 32,567 |
mila/pyoo | pyoo.py | Cell.__set_value | def __set_value(self, value):
"""
Sets cell value to a string or number based on the given value.
"""
array = ((self._clean_value(value),),)
return self._get_target().setDataArray(array) | python | def __set_value(self, value):
"""
Sets cell value to a string or number based on the given value.
"""
array = ((self._clean_value(value),),)
return self._get_target().setDataArray(array) | [
"def",
"__set_value",
"(",
"self",
",",
"value",
")",
":",
"array",
"=",
"(",
"(",
"self",
".",
"_clean_value",
"(",
"value",
")",
",",
")",
",",
")",
"return",
"self",
".",
"_get_target",
"(",
")",
".",
"setDataArray",
"(",
"array",
")"
] | Sets cell value to a string or number based on the given value. | [
"Sets",
"cell",
"value",
"to",
"a",
"string",
"or",
"number",
"based",
"on",
"the",
"given",
"value",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1285-L1290 | train | 32,568 |
mila/pyoo | pyoo.py | Cell.__set_formula | def __set_formula(self, formula):
"""
Sets a formula in this cell.
Any cell value can be set using this method. Actual formulas must
start with an equal sign.
"""
array = ((self._clean_formula(formula),),)
return self._get_target().setFormulaArray(array) | python | def __set_formula(self, formula):
"""
Sets a formula in this cell.
Any cell value can be set using this method. Actual formulas must
start with an equal sign.
"""
array = ((self._clean_formula(formula),),)
return self._get_target().setFormulaArray(array) | [
"def",
"__set_formula",
"(",
"self",
",",
"formula",
")",
":",
"array",
"=",
"(",
"(",
"self",
".",
"_clean_formula",
"(",
"formula",
")",
",",
")",
",",
")",
"return",
"self",
".",
"_get_target",
"(",
")",
".",
"setFormulaArray",
"(",
"array",
")"
] | Sets a formula in this cell.
Any cell value can be set using this method. Actual formulas must
start with an equal sign. | [
"Sets",
"a",
"formula",
"in",
"this",
"cell",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1302-L1310 | train | 32,569 |
mila/pyoo | pyoo.py | TabularCellRange.__set_values | def __set_values(self, values):
"""
Sets values in this cell range from an iterable of iterables.
"""
# Tuple of tuples is required
array = tuple(tuple(self._clean_value(col) for col in row) for row in values)
self._get_target().setDataArray(array) | python | def __set_values(self, values):
"""
Sets values in this cell range from an iterable of iterables.
"""
# Tuple of tuples is required
array = tuple(tuple(self._clean_value(col) for col in row) for row in values)
self._get_target().setDataArray(array) | [
"def",
"__set_values",
"(",
"self",
",",
"values",
")",
":",
"# Tuple of tuples is required",
"array",
"=",
"tuple",
"(",
"tuple",
"(",
"self",
".",
"_clean_value",
"(",
"col",
")",
"for",
"col",
"in",
"row",
")",
"for",
"row",
"in",
"values",
")",
"self... | Sets values in this cell range from an iterable of iterables. | [
"Sets",
"values",
"in",
"this",
"cell",
"range",
"from",
"an",
"iterable",
"of",
"iterables",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1390-L1396 | train | 32,570 |
mila/pyoo | pyoo.py | TabularCellRange.__set_formulas | def __set_formulas(self, formulas):
"""
Sets formulas in this cell range from an iterable of iterables.
Any cell values can be set using this method. Actual formulas must
start with an equal sign.
"""
# Tuple of tuples is required
array = tuple(tuple(self._clean_formula(col) for col in row) for row in formulas)
self._get_target().setFormulaArray(array) | python | def __set_formulas(self, formulas):
"""
Sets formulas in this cell range from an iterable of iterables.
Any cell values can be set using this method. Actual formulas must
start with an equal sign.
"""
# Tuple of tuples is required
array = tuple(tuple(self._clean_formula(col) for col in row) for row in formulas)
self._get_target().setFormulaArray(array) | [
"def",
"__set_formulas",
"(",
"self",
",",
"formulas",
")",
":",
"# Tuple of tuples is required",
"array",
"=",
"tuple",
"(",
"tuple",
"(",
"self",
".",
"_clean_formula",
"(",
"col",
")",
"for",
"col",
"in",
"row",
")",
"for",
"row",
"in",
"formulas",
")",... | Sets formulas in this cell range from an iterable of iterables.
Any cell values can be set using this method. Actual formulas must
start with an equal sign. | [
"Sets",
"formulas",
"in",
"this",
"cell",
"range",
"from",
"an",
"iterable",
"of",
"iterables",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1407-L1416 | train | 32,571 |
mila/pyoo | pyoo.py | VerticalCellRange.__get_values | def __get_values(self):
"""
Gets values in this cell range as a tuple.
This is much more effective than reading cell values one by one.
"""
array = self._get_target().getDataArray()
return tuple(itertools.chain.from_iterable(array)) | python | def __get_values(self):
"""
Gets values in this cell range as a tuple.
This is much more effective than reading cell values one by one.
"""
array = self._get_target().getDataArray()
return tuple(itertools.chain.from_iterable(array)) | [
"def",
"__get_values",
"(",
"self",
")",
":",
"array",
"=",
"self",
".",
"_get_target",
"(",
")",
".",
"getDataArray",
"(",
")",
"return",
"tuple",
"(",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"array",
")",
")"
] | Gets values in this cell range as a tuple.
This is much more effective than reading cell values one by one. | [
"Gets",
"values",
"in",
"this",
"cell",
"range",
"as",
"a",
"tuple",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1511-L1518 | train | 32,572 |
mila/pyoo | pyoo.py | VerticalCellRange.__set_values | def __set_values(self, values):
"""
Sets values in this cell range from an iterable.
This is much more effective than writing cell values one by one.
"""
array = tuple((self._clean_value(v),) for v in values)
self._get_target().setDataArray(array) | python | def __set_values(self, values):
"""
Sets values in this cell range from an iterable.
This is much more effective than writing cell values one by one.
"""
array = tuple((self._clean_value(v),) for v in values)
self._get_target().setDataArray(array) | [
"def",
"__set_values",
"(",
"self",
",",
"values",
")",
":",
"array",
"=",
"tuple",
"(",
"(",
"self",
".",
"_clean_value",
"(",
"v",
")",
",",
")",
"for",
"v",
"in",
"values",
")",
"self",
".",
"_get_target",
"(",
")",
".",
"setDataArray",
"(",
"ar... | Sets values in this cell range from an iterable.
This is much more effective than writing cell values one by one. | [
"Sets",
"values",
"in",
"this",
"cell",
"range",
"from",
"an",
"iterable",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1519-L1526 | train | 32,573 |
mila/pyoo | pyoo.py | VerticalCellRange.__get_formulas | def __get_formulas(self):
"""
Gets formulas in this cell range as a tuple.
If cells contain actual formulas then the returned values start
with an equal sign but all values are returned.
"""
array = self._get_target().getFormulaArray()
return tuple(itertools.chain.from_iterable(array)) | python | def __get_formulas(self):
"""
Gets formulas in this cell range as a tuple.
If cells contain actual formulas then the returned values start
with an equal sign but all values are returned.
"""
array = self._get_target().getFormulaArray()
return tuple(itertools.chain.from_iterable(array)) | [
"def",
"__get_formulas",
"(",
"self",
")",
":",
"array",
"=",
"self",
".",
"_get_target",
"(",
")",
".",
"getFormulaArray",
"(",
")",
"return",
"tuple",
"(",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"array",
")",
")"
] | Gets formulas in this cell range as a tuple.
If cells contain actual formulas then the returned values start
with an equal sign but all values are returned. | [
"Gets",
"formulas",
"in",
"this",
"cell",
"range",
"as",
"a",
"tuple",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1529-L1537 | train | 32,574 |
mila/pyoo | pyoo.py | VerticalCellRange.__set_formulas | def __set_formulas(self, formulas):
"""
Sets formulas in this cell range from an iterable.
Any cell values can be set using this method. Actual formulas must
start with an equal sign.
"""
array = tuple((self._clean_formula(v),) for v in formulas)
self._get_target().setFormulaArray(array) | python | def __set_formulas(self, formulas):
"""
Sets formulas in this cell range from an iterable.
Any cell values can be set using this method. Actual formulas must
start with an equal sign.
"""
array = tuple((self._clean_formula(v),) for v in formulas)
self._get_target().setFormulaArray(array) | [
"def",
"__set_formulas",
"(",
"self",
",",
"formulas",
")",
":",
"array",
"=",
"tuple",
"(",
"(",
"self",
".",
"_clean_formula",
"(",
"v",
")",
",",
")",
"for",
"v",
"in",
"formulas",
")",
"self",
".",
"_get_target",
"(",
")",
".",
"setFormulaArray",
... | Sets formulas in this cell range from an iterable.
Any cell values can be set using this method. Actual formulas must
start with an equal sign. | [
"Sets",
"formulas",
"in",
"this",
"cell",
"range",
"from",
"an",
"iterable",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1538-L1546 | train | 32,575 |
mila/pyoo | pyoo.py | SpreadsheetCollection.create | def create(self, name, index=None):
"""
Creates a new sheet with the given name.
If an optional index argument is not provided then the created
sheet is appended at the end. Returns the new sheet.
"""
if index is None:
index = len(self)
self._create(name, index)
return self[name] | python | def create(self, name, index=None):
"""
Creates a new sheet with the given name.
If an optional index argument is not provided then the created
sheet is appended at the end. Returns the new sheet.
"""
if index is None:
index = len(self)
self._create(name, index)
return self[name] | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"index",
"=",
"None",
")",
":",
"if",
"index",
"is",
"None",
":",
"index",
"=",
"len",
"(",
"self",
")",
"self",
".",
"_create",
"(",
"name",
",",
"index",
")",
"return",
"self",
"[",
"name",
"]"
] | Creates a new sheet with the given name.
If an optional index argument is not provided then the created
sheet is appended at the end. Returns the new sheet. | [
"Creates",
"a",
"new",
"sheet",
"with",
"the",
"given",
"name",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1624-L1634 | train | 32,576 |
mila/pyoo | pyoo.py | SpreadsheetCollection.copy | def copy(self, old_name, new_name, index=None):
"""
Copies an old sheet with the old_name to a new sheet with new_name.
If an optional index argument is not provided then the created
sheet is appended at the end. Returns the new sheet.
"""
if index is None:
index = len(self)
self._copy(old_name, new_name, index)
return self[new_name] | python | def copy(self, old_name, new_name, index=None):
"""
Copies an old sheet with the old_name to a new sheet with new_name.
If an optional index argument is not provided then the created
sheet is appended at the end. Returns the new sheet.
"""
if index is None:
index = len(self)
self._copy(old_name, new_name, index)
return self[new_name] | [
"def",
"copy",
"(",
"self",
",",
"old_name",
",",
"new_name",
",",
"index",
"=",
"None",
")",
":",
"if",
"index",
"is",
"None",
":",
"index",
"=",
"len",
"(",
"self",
")",
"self",
".",
"_copy",
"(",
"old_name",
",",
"new_name",
",",
"index",
")",
... | Copies an old sheet with the old_name to a new sheet with new_name.
If an optional index argument is not provided then the created
sheet is appended at the end. Returns the new sheet. | [
"Copies",
"an",
"old",
"sheet",
"with",
"the",
"old_name",
"to",
"a",
"new",
"sheet",
"with",
"new_name",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1636-L1646 | train | 32,577 |
mila/pyoo | pyoo.py | SpreadsheetDocument.save | def save(self, path=None, filter_name=None):
"""
Saves this document to a local file system.
The optional first argument defaults to the document's path.
Accept optional second argument which defines type of
the saved file. Use one of FILTER_* constants or see list of
available filters at http://wakka.net/archives/7 or
http://www.oooforum.org/forum/viewtopic.phtml?t=71294.
"""
if path is None:
try:
self._target.store()
except _IOException as e:
raise IOError(e.Message)
return
# UNO requires absolute paths
url = uno.systemPathToFileUrl(os.path.abspath(path))
if filter_name:
format_filter = uno.createUnoStruct('com.sun.star.beans.PropertyValue')
format_filter.Name = 'FilterName'
format_filter.Value = filter_name
filters = (format_filter,)
else:
filters = ()
# http://www.openoffice.org/api/docs/common/ref/com/sun/star/frame/XStorable.html#storeToURL
try:
self._target.storeToURL(url, filters)
except _IOException as e:
raise IOError(e.Message) | python | def save(self, path=None, filter_name=None):
"""
Saves this document to a local file system.
The optional first argument defaults to the document's path.
Accept optional second argument which defines type of
the saved file. Use one of FILTER_* constants or see list of
available filters at http://wakka.net/archives/7 or
http://www.oooforum.org/forum/viewtopic.phtml?t=71294.
"""
if path is None:
try:
self._target.store()
except _IOException as e:
raise IOError(e.Message)
return
# UNO requires absolute paths
url = uno.systemPathToFileUrl(os.path.abspath(path))
if filter_name:
format_filter = uno.createUnoStruct('com.sun.star.beans.PropertyValue')
format_filter.Name = 'FilterName'
format_filter.Value = filter_name
filters = (format_filter,)
else:
filters = ()
# http://www.openoffice.org/api/docs/common/ref/com/sun/star/frame/XStorable.html#storeToURL
try:
self._target.storeToURL(url, filters)
except _IOException as e:
raise IOError(e.Message) | [
"def",
"save",
"(",
"self",
",",
"path",
"=",
"None",
",",
"filter_name",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"try",
":",
"self",
".",
"_target",
".",
"store",
"(",
")",
"except",
"_IOException",
"as",
"e",
":",
"raise",
"IOErro... | Saves this document to a local file system.
The optional first argument defaults to the document's path.
Accept optional second argument which defines type of
the saved file. Use one of FILTER_* constants or see list of
available filters at http://wakka.net/archives/7 or
http://www.oooforum.org/forum/viewtopic.phtml?t=71294. | [
"Saves",
"this",
"document",
"to",
"a",
"local",
"file",
"system",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1698-L1730 | train | 32,578 |
mila/pyoo | pyoo.py | SpreadsheetDocument.get_locale | def get_locale(self, language=None, country=None, variant=None):
"""
Returns locale which can be used for access to number formats.
"""
# http://www.openoffice.org/api/docs/common/ref/com/sun/star/lang/Locale.html
locale = uno.createUnoStruct('com.sun.star.lang.Locale')
if language:
locale.Language = language
if country:
locale.Country = country
if variant:
locale.Variant = variant
formats = self._target.getNumberFormats()
return Locale(locale, formats) | python | def get_locale(self, language=None, country=None, variant=None):
"""
Returns locale which can be used for access to number formats.
"""
# http://www.openoffice.org/api/docs/common/ref/com/sun/star/lang/Locale.html
locale = uno.createUnoStruct('com.sun.star.lang.Locale')
if language:
locale.Language = language
if country:
locale.Country = country
if variant:
locale.Variant = variant
formats = self._target.getNumberFormats()
return Locale(locale, formats) | [
"def",
"get_locale",
"(",
"self",
",",
"language",
"=",
"None",
",",
"country",
"=",
"None",
",",
"variant",
"=",
"None",
")",
":",
"# http://www.openoffice.org/api/docs/common/ref/com/sun/star/lang/Locale.html",
"locale",
"=",
"uno",
".",
"createUnoStruct",
"(",
"'... | Returns locale which can be used for access to number formats. | [
"Returns",
"locale",
"which",
"can",
"be",
"used",
"for",
"access",
"to",
"number",
"formats",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1739-L1752 | train | 32,579 |
mila/pyoo | pyoo.py | SpreadsheetDocument.sheets | def sheets(self):
"""
Collection of sheets in this document.
"""
# http://www.openoffice.org/api/docs/common/ref/com/sun/star/sheet/XSpreadsheetDocument.html#getSheets
try:
return self._sheets
except AttributeError:
target = self._target.getSheets()
self._sheets = SpreadsheetCollection(self, target)
return self._sheets | python | def sheets(self):
"""
Collection of sheets in this document.
"""
# http://www.openoffice.org/api/docs/common/ref/com/sun/star/sheet/XSpreadsheetDocument.html#getSheets
try:
return self._sheets
except AttributeError:
target = self._target.getSheets()
self._sheets = SpreadsheetCollection(self, target)
return self._sheets | [
"def",
"sheets",
"(",
"self",
")",
":",
"# http://www.openoffice.org/api/docs/common/ref/com/sun/star/sheet/XSpreadsheetDocument.html#getSheets",
"try",
":",
"return",
"self",
".",
"_sheets",
"except",
"AttributeError",
":",
"target",
"=",
"self",
".",
"_target",
".",
"ge... | Collection of sheets in this document. | [
"Collection",
"of",
"sheets",
"in",
"this",
"document",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1755-L1765 | train | 32,580 |
mila/pyoo | pyoo.py | SpreadsheetDocument.date_from_number | def date_from_number(self, value):
"""
Converts a float value to corresponding datetime instance.
"""
if not isinstance(value, numbers.Real):
return None
delta = datetime.timedelta(days=value)
return self._null_date + delta | python | def date_from_number(self, value):
"""
Converts a float value to corresponding datetime instance.
"""
if not isinstance(value, numbers.Real):
return None
delta = datetime.timedelta(days=value)
return self._null_date + delta | [
"def",
"date_from_number",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"numbers",
".",
"Real",
")",
":",
"return",
"None",
"delta",
"=",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"value",
")",
"return",
"sel... | Converts a float value to corresponding datetime instance. | [
"Converts",
"a",
"float",
"value",
"to",
"corresponding",
"datetime",
"instance",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1767-L1774 | train | 32,581 |
mila/pyoo | pyoo.py | SpreadsheetDocument.date_to_number | def date_to_number(self, date):
"""
Converts a date or datetime instance to a corresponding float value.
"""
if isinstance(date, datetime.datetime):
delta = date - self._null_date
elif isinstance(date, datetime.date):
delta = date - self._null_date.date()
else:
raise TypeError(date)
return delta.days + delta.seconds / (24.0 * 60 * 60) | python | def date_to_number(self, date):
"""
Converts a date or datetime instance to a corresponding float value.
"""
if isinstance(date, datetime.datetime):
delta = date - self._null_date
elif isinstance(date, datetime.date):
delta = date - self._null_date.date()
else:
raise TypeError(date)
return delta.days + delta.seconds / (24.0 * 60 * 60) | [
"def",
"date_to_number",
"(",
"self",
",",
"date",
")",
":",
"if",
"isinstance",
"(",
"date",
",",
"datetime",
".",
"datetime",
")",
":",
"delta",
"=",
"date",
"-",
"self",
".",
"_null_date",
"elif",
"isinstance",
"(",
"date",
",",
"datetime",
".",
"da... | Converts a date or datetime instance to a corresponding float value. | [
"Converts",
"a",
"date",
"or",
"datetime",
"instance",
"to",
"a",
"corresponding",
"float",
"value",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1776-L1786 | train | 32,582 |
mila/pyoo | pyoo.py | SpreadsheetDocument.time_from_number | def time_from_number(self, value):
"""
Converts a float value to corresponding time instance.
"""
if not isinstance(value, numbers.Real):
return None
delta = datetime.timedelta(days=value)
minutes, second = divmod(delta.seconds, 60)
hour, minute = divmod(minutes, 60)
return datetime.time(hour, minute, second) | python | def time_from_number(self, value):
"""
Converts a float value to corresponding time instance.
"""
if not isinstance(value, numbers.Real):
return None
delta = datetime.timedelta(days=value)
minutes, second = divmod(delta.seconds, 60)
hour, minute = divmod(minutes, 60)
return datetime.time(hour, minute, second) | [
"def",
"time_from_number",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"numbers",
".",
"Real",
")",
":",
"return",
"None",
"delta",
"=",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"value",
")",
"minutes",
","... | Converts a float value to corresponding time instance. | [
"Converts",
"a",
"float",
"value",
"to",
"corresponding",
"time",
"instance",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1788-L1797 | train | 32,583 |
mila/pyoo | pyoo.py | SpreadsheetDocument.time_to_number | def time_to_number(self, time):
"""
Converts a time instance to a corresponding float value.
"""
if not isinstance(time, datetime.time):
raise TypeError(time)
return ((time.second / 60.0 + time.minute) / 60.0 + time.hour) / 24.0 | python | def time_to_number(self, time):
"""
Converts a time instance to a corresponding float value.
"""
if not isinstance(time, datetime.time):
raise TypeError(time)
return ((time.second / 60.0 + time.minute) / 60.0 + time.hour) / 24.0 | [
"def",
"time_to_number",
"(",
"self",
",",
"time",
")",
":",
"if",
"not",
"isinstance",
"(",
"time",
",",
"datetime",
".",
"time",
")",
":",
"raise",
"TypeError",
"(",
"time",
")",
"return",
"(",
"(",
"time",
".",
"second",
"/",
"60.0",
"+",
"time",
... | Converts a time instance to a corresponding float value. | [
"Converts",
"a",
"time",
"instance",
"to",
"a",
"corresponding",
"float",
"value",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1799-L1805 | train | 32,584 |
mila/pyoo | pyoo.py | SpreadsheetDocument._null_date | def _null_date(self):
"""
Returns date which is represented by a integer 0.
"""
# http://www.openoffice.org/api/docs/common/ref/com/sun/star/util/NumberFormatSettings.html#NullDate
try:
return self.__null_date
except AttributeError:
number_settings = self._target.getNumberFormatSettings()
d = number_settings.getPropertyValue('NullDate')
self.__null_date = datetime.datetime(d.Year, d.Month, d.Day)
return self.__null_date | python | def _null_date(self):
"""
Returns date which is represented by a integer 0.
"""
# http://www.openoffice.org/api/docs/common/ref/com/sun/star/util/NumberFormatSettings.html#NullDate
try:
return self.__null_date
except AttributeError:
number_settings = self._target.getNumberFormatSettings()
d = number_settings.getPropertyValue('NullDate')
self.__null_date = datetime.datetime(d.Year, d.Month, d.Day)
return self.__null_date | [
"def",
"_null_date",
"(",
"self",
")",
":",
"# http://www.openoffice.org/api/docs/common/ref/com/sun/star/util/NumberFormatSettings.html#NullDate",
"try",
":",
"return",
"self",
".",
"__null_date",
"except",
"AttributeError",
":",
"number_settings",
"=",
"self",
".",
"_target... | Returns date which is represented by a integer 0. | [
"Returns",
"date",
"which",
"is",
"represented",
"by",
"a",
"integer",
"0",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1810-L1821 | train | 32,585 |
mila/pyoo | pyoo.py | LazyDesktop.create_spreadsheet | def create_spreadsheet(self):
"""
Creates a new spreadsheet document.
"""
desktop = self.cls(self.hostname, self.port, self.pipe)
return desktop.create_spreadsheet() | python | def create_spreadsheet(self):
"""
Creates a new spreadsheet document.
"""
desktop = self.cls(self.hostname, self.port, self.pipe)
return desktop.create_spreadsheet() | [
"def",
"create_spreadsheet",
"(",
"self",
")",
":",
"desktop",
"=",
"self",
".",
"cls",
"(",
"self",
".",
"hostname",
",",
"self",
".",
"port",
",",
"self",
".",
"pipe",
")",
"return",
"desktop",
".",
"create_spreadsheet",
"(",
")"
] | Creates a new spreadsheet document. | [
"Creates",
"a",
"new",
"spreadsheet",
"document",
"."
] | 1e024999f608c87ea72cd443e39c89eb0ba3cc62 | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1911-L1916 | train | 32,586 |
mbakker7/timml | timml/util.py | PlotTim.vcontoursf1D | def vcontoursf1D(self, x1, x2, nx, levels, labels=False, decimals=0, color=None,
nudge=1e-6, newfig=True, figsize=None, layout=True, ax=None):
"""
Vertical contour for 1D model
"""
naq = self.aq.naq
xflow = np.linspace(x1 + nudge, x2 - nudge, nx)
Qx = np.empty((naq, nx))
for i in range(nx):
Qx[:, i], Qydump = self.disvec(xflow[i], 0)
zflow = np.empty(2 * naq)
for i in range(self.aq.naq):
zflow[2 * i] = self.aq.zaqtop[i]
zflow[2 * i + 1] = self.aq.zaqbot[i]
Qx = Qx[::-1] # set upside down
Qxgrid = np.empty((2 * naq, nx))
Qxgrid[0] = 0
for i in range(naq - 1):
Qxgrid[2 * i + 1] = Qxgrid[2 * i] - Qx[i]
Qxgrid[2 * i + 2] = Qxgrid[2 * i + 1]
Qxgrid[-1] = Qxgrid[-2] - Qx[-1]
Qxgrid = Qxgrid[::-1] # index 0 at top
if newfig:
fig, ax = plt.subplots(1, 1, figsize=figsize)
else:
ax=ax
cs = ax.contour(xflow, zflow, Qxgrid, levels, colors=color)
if labels:
fmt = '%1.' + str(decimals) + 'f'
plt.clabel(cs, fmt=fmt) | python | def vcontoursf1D(self, x1, x2, nx, levels, labels=False, decimals=0, color=None,
nudge=1e-6, newfig=True, figsize=None, layout=True, ax=None):
"""
Vertical contour for 1D model
"""
naq = self.aq.naq
xflow = np.linspace(x1 + nudge, x2 - nudge, nx)
Qx = np.empty((naq, nx))
for i in range(nx):
Qx[:, i], Qydump = self.disvec(xflow[i], 0)
zflow = np.empty(2 * naq)
for i in range(self.aq.naq):
zflow[2 * i] = self.aq.zaqtop[i]
zflow[2 * i + 1] = self.aq.zaqbot[i]
Qx = Qx[::-1] # set upside down
Qxgrid = np.empty((2 * naq, nx))
Qxgrid[0] = 0
for i in range(naq - 1):
Qxgrid[2 * i + 1] = Qxgrid[2 * i] - Qx[i]
Qxgrid[2 * i + 2] = Qxgrid[2 * i + 1]
Qxgrid[-1] = Qxgrid[-2] - Qx[-1]
Qxgrid = Qxgrid[::-1] # index 0 at top
if newfig:
fig, ax = plt.subplots(1, 1, figsize=figsize)
else:
ax=ax
cs = ax.contour(xflow, zflow, Qxgrid, levels, colors=color)
if labels:
fmt = '%1.' + str(decimals) + 'f'
plt.clabel(cs, fmt=fmt) | [
"def",
"vcontoursf1D",
"(",
"self",
",",
"x1",
",",
"x2",
",",
"nx",
",",
"levels",
",",
"labels",
"=",
"False",
",",
"decimals",
"=",
"0",
",",
"color",
"=",
"None",
",",
"nudge",
"=",
"1e-6",
",",
"newfig",
"=",
"True",
",",
"figsize",
"=",
"No... | Vertical contour for 1D model | [
"Vertical",
"contour",
"for",
"1D",
"model"
] | 91e99ad573cb8a9ad8ac1fa041c3ca44520c2390 | https://github.com/mbakker7/timml/blob/91e99ad573cb8a9ad8ac1fa041c3ca44520c2390/timml/util.py#L211-L241 | train | 32,587 |
mbakker7/timml | timml/linesink1d.py | LineSink1DBase.discharge | def discharge(self):
"""Discharge per unit length"""
Q = np.zeros(self.aq.naq)
Q[self.layers] = self.parameters[:, 0]
return Q | python | def discharge(self):
"""Discharge per unit length"""
Q = np.zeros(self.aq.naq)
Q[self.layers] = self.parameters[:, 0]
return Q | [
"def",
"discharge",
"(",
"self",
")",
":",
"Q",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"aq",
".",
"naq",
")",
"Q",
"[",
"self",
".",
"layers",
"]",
"=",
"self",
".",
"parameters",
"[",
":",
",",
"0",
"]",
"return",
"Q"
] | Discharge per unit length | [
"Discharge",
"per",
"unit",
"length"
] | 91e99ad573cb8a9ad8ac1fa041c3ca44520c2390 | https://github.com/mbakker7/timml/blob/91e99ad573cb8a9ad8ac1fa041c3ca44520c2390/timml/linesink1d.py#L92-L96 | train | 32,588 |
mbakker7/timml | timml/linesink.py | LineSinkStringBase2.discharge | def discharge(self):
"""Discharge of the element in each layer
"""
rv = np.zeros(self.aq[0].naq)
Qls = self.parameters[:, 0] * self.dischargeinf()
Qls.shape = (self.nls, self.nlayers, self.order + 1)
Qls = np.sum(Qls, 2)
for i, q in enumerate(Qls):
rv[self.layers[i]] += q
#rv[self.layers] = np.sum(Qls.reshape(self.nls * (self.order + 1), self.nlayers), 0)
return rv | python | def discharge(self):
"""Discharge of the element in each layer
"""
rv = np.zeros(self.aq[0].naq)
Qls = self.parameters[:, 0] * self.dischargeinf()
Qls.shape = (self.nls, self.nlayers, self.order + 1)
Qls = np.sum(Qls, 2)
for i, q in enumerate(Qls):
rv[self.layers[i]] += q
#rv[self.layers] = np.sum(Qls.reshape(self.nls * (self.order + 1), self.nlayers), 0)
return rv | [
"def",
"discharge",
"(",
"self",
")",
":",
"rv",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"aq",
"[",
"0",
"]",
".",
"naq",
")",
"Qls",
"=",
"self",
".",
"parameters",
"[",
":",
",",
"0",
"]",
"*",
"self",
".",
"dischargeinf",
"(",
")",
"Qls... | Discharge of the element in each layer | [
"Discharge",
"of",
"the",
"element",
"in",
"each",
"layer"
] | 91e99ad573cb8a9ad8ac1fa041c3ca44520c2390 | https://github.com/mbakker7/timml/blob/91e99ad573cb8a9ad8ac1fa041c3ca44520c2390/timml/linesink.py#L753-L764 | train | 32,589 |
mbakker7/timml | timml/aquifer.py | AquiferData.findlayer | def findlayer(self, z):
'''
Returns layer-number, layer-type and model-layer-number'''
if z > self.z[0]:
modellayer, ltype = -1, 'above'
layernumber = None
elif z < self.z[-1]:
modellayer, ltype = len(self.layernumber), 'below'
layernumber = None
else:
modellayer = np.argwhere((z <= self.z[:-1]) & (z >= self.z[1:]))[0, 0]
layernumber = self.layernumber[modellayer]
ltype = self.ltype[modellayer]
return layernumber, ltype, modellayer | python | def findlayer(self, z):
'''
Returns layer-number, layer-type and model-layer-number'''
if z > self.z[0]:
modellayer, ltype = -1, 'above'
layernumber = None
elif z < self.z[-1]:
modellayer, ltype = len(self.layernumber), 'below'
layernumber = None
else:
modellayer = np.argwhere((z <= self.z[:-1]) & (z >= self.z[1:]))[0, 0]
layernumber = self.layernumber[modellayer]
ltype = self.ltype[modellayer]
return layernumber, ltype, modellayer | [
"def",
"findlayer",
"(",
"self",
",",
"z",
")",
":",
"if",
"z",
">",
"self",
".",
"z",
"[",
"0",
"]",
":",
"modellayer",
",",
"ltype",
"=",
"-",
"1",
",",
"'above'",
"layernumber",
"=",
"None",
"elif",
"z",
"<",
"self",
".",
"z",
"[",
"-",
"1... | Returns layer-number, layer-type and model-layer-number | [
"Returns",
"layer",
"-",
"number",
"layer",
"-",
"type",
"and",
"model",
"-",
"layer",
"-",
"number"
] | 91e99ad573cb8a9ad8ac1fa041c3ca44520c2390 | https://github.com/mbakker7/timml/blob/91e99ad573cb8a9ad8ac1fa041c3ca44520c2390/timml/aquifer.py#L85-L98 | train | 32,590 |
mbakker7/timml | timml/model.py | Model.remove_element | def remove_element(self, e):
"""Remove element `e` from model
"""
if e.label is not None: self.elementdict.pop(e.label)
self.elementlist.remove(e) | python | def remove_element(self, e):
"""Remove element `e` from model
"""
if e.label is not None: self.elementdict.pop(e.label)
self.elementlist.remove(e) | [
"def",
"remove_element",
"(",
"self",
",",
"e",
")",
":",
"if",
"e",
".",
"label",
"is",
"not",
"None",
":",
"self",
".",
"elementdict",
".",
"pop",
"(",
"e",
".",
"label",
")",
"self",
".",
"elementlist",
".",
"remove",
"(",
"e",
")"
] | Remove element `e` from model | [
"Remove",
"element",
"e",
"from",
"model"
] | 91e99ad573cb8a9ad8ac1fa041c3ca44520c2390 | https://github.com/mbakker7/timml/blob/91e99ad573cb8a9ad8ac1fa041c3ca44520c2390/timml/model.py#L70-L75 | train | 32,591 |
limix/pandas-plink | pandas_plink/_read.py | read_plink | def read_plink(file_prefix, verbose=True):
r"""Read PLINK files into Pandas data frames.
Parameters
----------
file_prefix : str
Path prefix to the set of PLINK files. It supports loading many BED
files at once using globstrings wildcard.
verbose : bool
``True`` for progress information; ``False`` otherwise.
Returns
-------
:class:`pandas.DataFrame`
Alleles.
:class:`pandas.DataFrame`
Samples.
:class:`numpy.ndarray`
Genotype.
Examples
--------
We have shipped this package with an example so can load and inspect by
doing
.. doctest::
>>> from pandas_plink import read_plink
>>> from pandas_plink import example_file_prefix
>>> (bim, fam, bed) = read_plink(example_file_prefix(), verbose=False)
>>> print(bim.head()) #doctest: +NORMALIZE_WHITESPACE
chrom snp cm pos a0 a1 i
0 1 rs10399749 0.0 45162 G C 0
1 1 rs2949420 0.0 45257 C T 1
2 1 rs2949421 0.0 45413 0 0 2
3 1 rs2691310 0.0 46844 A T 3
4 1 rs4030303 0.0 72434 0 G 4
>>> print(fam.head()) #doctest: +NORMALIZE_WHITESPACE
fid iid father mother gender trait i
0 Sample_1 Sample_1 0 0 1 -9 0
1 Sample_2 Sample_2 0 0 2 -9 1
2 Sample_3 Sample_3 Sample_1 Sample_2 2 -9 2
>>> print(bed.compute()) #doctest: +NORMALIZE_WHITESPACE
[[ 2. 2. 1.]
[ 2. 1. 2.]
[nan nan nan]
[nan nan 1.]
[ 2. 2. 2.]
[ 2. 2. 2.]
[ 2. 1. 0.]
[ 2. 2. 2.]
[ 1. 2. 2.]
[ 2. 1. 2.]]
The values of the ``bed`` matrix denote how many alleles ``a1`` (see
output of data frame ``bim``) are in the corresponding position and
individual. Notice the column ``i`` in ``bim`` and ``fam`` data frames.
It maps to the corresponding position of the bed matrix:
.. doctest::
>>> chrom1 = bim.query("chrom=='1'")
>>> X = bed[chrom1.i.values, :].compute()
>>> print(X) #doctest: +NORMALIZE_WHITESPACE
[[ 2. 2. 1.]
[ 2. 1. 2.]
[nan nan nan]
[nan nan 1.]
[ 2. 2. 2.]
[ 2. 2. 2.]
[ 2. 1. 0.]
[ 2. 2. 2.]
[ 1. 2. 2.]
[ 2. 1. 2.]]
It also allows the use of the wildcard character ``*`` for mapping
multiple BED files at
once: ``(bim, fam, bed) = read_plink("chrom*")``.
In this case, only one of the FAM files will be used to define
sample information. Data from BIM and BED files are concatenated to
provide a single view of the files.
"""
from dask.array import concatenate
file_prefixes = sorted(glob(file_prefix))
if len(file_prefixes) == 0:
file_prefixes = [file_prefix.replace("*", "")]
file_prefixes = sorted(_clean_prefixes(file_prefixes))
fn = []
for fp in file_prefixes:
fn.append({s: "%s.%s" % (fp, s) for s in ["bed", "bim", "fam"]})
pbar = tqdm(desc="Mapping files", total=3 * len(fn), disable=not verbose)
msg = "Reading bim file(s)..."
bim = _read_file(fn, msg, lambda fn: _read_bim(fn["bim"]), pbar)
if len(file_prefixes) > 1:
if verbose:
msg = "Multiple files read in this order: {}"
print(msg.format([basename(f) for f in file_prefixes]))
nmarkers = dict()
index_offset = 0
for i, bi in enumerate(bim):
nmarkers[fn[i]["bed"]] = bi.shape[0]
bi["i"] += index_offset
index_offset += bi.shape[0]
bim = pd.concat(bim, axis=0, ignore_index=True)
msg = "Reading fam file(s)..."
fam = _read_file([fn[0]], msg, lambda fn: _read_fam(fn["fam"]), pbar)[0]
nsamples = fam.shape[0]
bed = _read_file(
fn,
"Reading bed file(s)...",
lambda fn: _read_bed(fn["bed"], nsamples, nmarkers[fn["bed"]]),
pbar,
)
bed = concatenate(bed, axis=0)
pbar.close()
return (bim, fam, bed) | python | def read_plink(file_prefix, verbose=True):
r"""Read PLINK files into Pandas data frames.
Parameters
----------
file_prefix : str
Path prefix to the set of PLINK files. It supports loading many BED
files at once using globstrings wildcard.
verbose : bool
``True`` for progress information; ``False`` otherwise.
Returns
-------
:class:`pandas.DataFrame`
Alleles.
:class:`pandas.DataFrame`
Samples.
:class:`numpy.ndarray`
Genotype.
Examples
--------
We have shipped this package with an example so can load and inspect by
doing
.. doctest::
>>> from pandas_plink import read_plink
>>> from pandas_plink import example_file_prefix
>>> (bim, fam, bed) = read_plink(example_file_prefix(), verbose=False)
>>> print(bim.head()) #doctest: +NORMALIZE_WHITESPACE
chrom snp cm pos a0 a1 i
0 1 rs10399749 0.0 45162 G C 0
1 1 rs2949420 0.0 45257 C T 1
2 1 rs2949421 0.0 45413 0 0 2
3 1 rs2691310 0.0 46844 A T 3
4 1 rs4030303 0.0 72434 0 G 4
>>> print(fam.head()) #doctest: +NORMALIZE_WHITESPACE
fid iid father mother gender trait i
0 Sample_1 Sample_1 0 0 1 -9 0
1 Sample_2 Sample_2 0 0 2 -9 1
2 Sample_3 Sample_3 Sample_1 Sample_2 2 -9 2
>>> print(bed.compute()) #doctest: +NORMALIZE_WHITESPACE
[[ 2. 2. 1.]
[ 2. 1. 2.]
[nan nan nan]
[nan nan 1.]
[ 2. 2. 2.]
[ 2. 2. 2.]
[ 2. 1. 0.]
[ 2. 2. 2.]
[ 1. 2. 2.]
[ 2. 1. 2.]]
The values of the ``bed`` matrix denote how many alleles ``a1`` (see
output of data frame ``bim``) are in the corresponding position and
individual. Notice the column ``i`` in ``bim`` and ``fam`` data frames.
It maps to the corresponding position of the bed matrix:
.. doctest::
>>> chrom1 = bim.query("chrom=='1'")
>>> X = bed[chrom1.i.values, :].compute()
>>> print(X) #doctest: +NORMALIZE_WHITESPACE
[[ 2. 2. 1.]
[ 2. 1. 2.]
[nan nan nan]
[nan nan 1.]
[ 2. 2. 2.]
[ 2. 2. 2.]
[ 2. 1. 0.]
[ 2. 2. 2.]
[ 1. 2. 2.]
[ 2. 1. 2.]]
It also allows the use of the wildcard character ``*`` for mapping
multiple BED files at
once: ``(bim, fam, bed) = read_plink("chrom*")``.
In this case, only one of the FAM files will be used to define
sample information. Data from BIM and BED files are concatenated to
provide a single view of the files.
"""
from dask.array import concatenate
file_prefixes = sorted(glob(file_prefix))
if len(file_prefixes) == 0:
file_prefixes = [file_prefix.replace("*", "")]
file_prefixes = sorted(_clean_prefixes(file_prefixes))
fn = []
for fp in file_prefixes:
fn.append({s: "%s.%s" % (fp, s) for s in ["bed", "bim", "fam"]})
pbar = tqdm(desc="Mapping files", total=3 * len(fn), disable=not verbose)
msg = "Reading bim file(s)..."
bim = _read_file(fn, msg, lambda fn: _read_bim(fn["bim"]), pbar)
if len(file_prefixes) > 1:
if verbose:
msg = "Multiple files read in this order: {}"
print(msg.format([basename(f) for f in file_prefixes]))
nmarkers = dict()
index_offset = 0
for i, bi in enumerate(bim):
nmarkers[fn[i]["bed"]] = bi.shape[0]
bi["i"] += index_offset
index_offset += bi.shape[0]
bim = pd.concat(bim, axis=0, ignore_index=True)
msg = "Reading fam file(s)..."
fam = _read_file([fn[0]], msg, lambda fn: _read_fam(fn["fam"]), pbar)[0]
nsamples = fam.shape[0]
bed = _read_file(
fn,
"Reading bed file(s)...",
lambda fn: _read_bed(fn["bed"], nsamples, nmarkers[fn["bed"]]),
pbar,
)
bed = concatenate(bed, axis=0)
pbar.close()
return (bim, fam, bed) | [
"def",
"read_plink",
"(",
"file_prefix",
",",
"verbose",
"=",
"True",
")",
":",
"from",
"dask",
".",
"array",
"import",
"concatenate",
"file_prefixes",
"=",
"sorted",
"(",
"glob",
"(",
"file_prefix",
")",
")",
"if",
"len",
"(",
"file_prefixes",
")",
"==",
... | r"""Read PLINK files into Pandas data frames.
Parameters
----------
file_prefix : str
Path prefix to the set of PLINK files. It supports loading many BED
files at once using globstrings wildcard.
verbose : bool
``True`` for progress information; ``False`` otherwise.
Returns
-------
:class:`pandas.DataFrame`
Alleles.
:class:`pandas.DataFrame`
Samples.
:class:`numpy.ndarray`
Genotype.
Examples
--------
We have shipped this package with an example so can load and inspect by
doing
.. doctest::
>>> from pandas_plink import read_plink
>>> from pandas_plink import example_file_prefix
>>> (bim, fam, bed) = read_plink(example_file_prefix(), verbose=False)
>>> print(bim.head()) #doctest: +NORMALIZE_WHITESPACE
chrom snp cm pos a0 a1 i
0 1 rs10399749 0.0 45162 G C 0
1 1 rs2949420 0.0 45257 C T 1
2 1 rs2949421 0.0 45413 0 0 2
3 1 rs2691310 0.0 46844 A T 3
4 1 rs4030303 0.0 72434 0 G 4
>>> print(fam.head()) #doctest: +NORMALIZE_WHITESPACE
fid iid father mother gender trait i
0 Sample_1 Sample_1 0 0 1 -9 0
1 Sample_2 Sample_2 0 0 2 -9 1
2 Sample_3 Sample_3 Sample_1 Sample_2 2 -9 2
>>> print(bed.compute()) #doctest: +NORMALIZE_WHITESPACE
[[ 2. 2. 1.]
[ 2. 1. 2.]
[nan nan nan]
[nan nan 1.]
[ 2. 2. 2.]
[ 2. 2. 2.]
[ 2. 1. 0.]
[ 2. 2. 2.]
[ 1. 2. 2.]
[ 2. 1. 2.]]
The values of the ``bed`` matrix denote how many alleles ``a1`` (see
output of data frame ``bim``) are in the corresponding position and
individual. Notice the column ``i`` in ``bim`` and ``fam`` data frames.
It maps to the corresponding position of the bed matrix:
.. doctest::
>>> chrom1 = bim.query("chrom=='1'")
>>> X = bed[chrom1.i.values, :].compute()
>>> print(X) #doctest: +NORMALIZE_WHITESPACE
[[ 2. 2. 1.]
[ 2. 1. 2.]
[nan nan nan]
[nan nan 1.]
[ 2. 2. 2.]
[ 2. 2. 2.]
[ 2. 1. 0.]
[ 2. 2. 2.]
[ 1. 2. 2.]
[ 2. 1. 2.]]
It also allows the use of the wildcard character ``*`` for mapping
multiple BED files at
once: ``(bim, fam, bed) = read_plink("chrom*")``.
In this case, only one of the FAM files will be used to define
sample information. Data from BIM and BED files are concatenated to
provide a single view of the files. | [
"r",
"Read",
"PLINK",
"files",
"into",
"Pandas",
"data",
"frames",
"."
] | 11ab505eef6ca9155dab6c7ec9e238a3747e0ec0 | https://github.com/limix/pandas-plink/blob/11ab505eef6ca9155dab6c7ec9e238a3747e0ec0/pandas_plink/_read.py#L25-L151 | train | 32,592 |
moremoban/moban | setup.py | read_files | def read_files(*files):
"""Read files into setup"""
text = ""
for single_file in files:
content = read(single_file)
text = text + content + "\n"
return text | python | def read_files(*files):
"""Read files into setup"""
text = ""
for single_file in files:
content = read(single_file)
text = text + content + "\n"
return text | [
"def",
"read_files",
"(",
"*",
"files",
")",
":",
"text",
"=",
"\"\"",
"for",
"single_file",
"in",
"files",
":",
"content",
"=",
"read",
"(",
"single_file",
")",
"text",
"=",
"text",
"+",
"content",
"+",
"\"\\n\"",
"return",
"text"
] | Read files into setup | [
"Read",
"files",
"into",
"setup"
] | 5d1674ae461b065a9a54fe89c445cbf6d3cd63c0 | https://github.com/moremoban/moban/blob/5d1674ae461b065a9a54fe89c445cbf6d3cd63c0/setup.py#L148-L154 | train | 32,593 |
moremoban/moban | setup.py | read | def read(afile):
"""Read a file into setup"""
the_relative_file = os.path.join(HERE, afile)
with codecs.open(the_relative_file, 'r', 'utf-8') as opened_file:
content = filter_out_test_code(opened_file)
content = "".join(list(content))
return content | python | def read(afile):
"""Read a file into setup"""
the_relative_file = os.path.join(HERE, afile)
with codecs.open(the_relative_file, 'r', 'utf-8') as opened_file:
content = filter_out_test_code(opened_file)
content = "".join(list(content))
return content | [
"def",
"read",
"(",
"afile",
")",
":",
"the_relative_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"HERE",
",",
"afile",
")",
"with",
"codecs",
".",
"open",
"(",
"the_relative_file",
",",
"'r'",
",",
"'utf-8'",
")",
"as",
"opened_file",
":",
"conten... | Read a file into setup | [
"Read",
"a",
"file",
"into",
"setup"
] | 5d1674ae461b065a9a54fe89c445cbf6d3cd63c0 | https://github.com/moremoban/moban/blob/5d1674ae461b065a9a54fe89c445cbf6d3cd63c0/setup.py#L157-L163 | train | 32,594 |
moremoban/moban | moban/main.py | main | def main():
"""
program entry point
"""
parser = create_parser()
options = vars(parser.parse_args())
HASH_STORE.IGNORE_CACHE_FILE = options[constants.LABEL_FORCE]
moban_file = options[constants.LABEL_MOBANFILE]
load_engine_factory_and_engines() # Error: jinja2 if removed
if moban_file is None:
moban_file = mobanfile.find_default_moban_file()
if moban_file:
try:
count = handle_moban_file(moban_file, options)
moban_exit(options[constants.LABEL_EXIT_CODE], count)
except (
exceptions.DirectoryNotFound,
exceptions.NoThirdPartyEngine,
exceptions.MobanfileGrammarException,
) as e:
reporter.report_error_message(str(e))
moban_exit(options[constants.LABEL_EXIT_CODE], constants.ERROR)
else:
try:
count = handle_command_line(options)
moban_exit(options[constants.LABEL_EXIT_CODE], count)
except exceptions.NoTemplate as e:
reporter.report_error_message(str(e))
moban_exit(options[constants.LABEL_EXIT_CODE], constants.ERROR) | python | def main():
"""
program entry point
"""
parser = create_parser()
options = vars(parser.parse_args())
HASH_STORE.IGNORE_CACHE_FILE = options[constants.LABEL_FORCE]
moban_file = options[constants.LABEL_MOBANFILE]
load_engine_factory_and_engines() # Error: jinja2 if removed
if moban_file is None:
moban_file = mobanfile.find_default_moban_file()
if moban_file:
try:
count = handle_moban_file(moban_file, options)
moban_exit(options[constants.LABEL_EXIT_CODE], count)
except (
exceptions.DirectoryNotFound,
exceptions.NoThirdPartyEngine,
exceptions.MobanfileGrammarException,
) as e:
reporter.report_error_message(str(e))
moban_exit(options[constants.LABEL_EXIT_CODE], constants.ERROR)
else:
try:
count = handle_command_line(options)
moban_exit(options[constants.LABEL_EXIT_CODE], count)
except exceptions.NoTemplate as e:
reporter.report_error_message(str(e))
moban_exit(options[constants.LABEL_EXIT_CODE], constants.ERROR) | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"create_parser",
"(",
")",
"options",
"=",
"vars",
"(",
"parser",
".",
"parse_args",
"(",
")",
")",
"HASH_STORE",
".",
"IGNORE_CACHE_FILE",
"=",
"options",
"[",
"constants",
".",
"LABEL_FORCE",
"]",
"moban_file"... | program entry point | [
"program",
"entry",
"point"
] | 5d1674ae461b065a9a54fe89c445cbf6d3cd63c0 | https://github.com/moremoban/moban/blob/5d1674ae461b065a9a54fe89c445cbf6d3cd63c0/moban/main.py#L21-L49 | train | 32,595 |
moremoban/moban | moban/main.py | create_parser | def create_parser():
"""
construct the program options
"""
parser = argparse.ArgumentParser(
prog=constants.PROGRAM_NAME, description=constants.PROGRAM_DESCRIPTION
)
parser.add_argument(
"-cd",
"--%s" % constants.LABEL_CONFIG_DIR,
help="the directory for configuration file lookup",
)
parser.add_argument(
"-c", "--%s" % constants.LABEL_CONFIG, help="the dictionary file"
)
parser.add_argument(
"-td",
"--%s" % constants.LABEL_TMPL_DIRS,
nargs="*",
help="the directories for template file lookup",
)
parser.add_argument(
"-t", "--%s" % constants.LABEL_TEMPLATE, help="the template file"
)
parser.add_argument(
"-o", "--%s" % constants.LABEL_OUTPUT, help="the output file"
)
parser.add_argument(
"--%s" % constants.LABEL_TEMPLATE_TYPE,
help="the template type, default is jinja2",
)
parser.add_argument(
"-f",
action="store_true",
dest=constants.LABEL_FORCE,
default=False,
help="force moban to template all files despite of .moban.hashes",
)
parser.add_argument(
"--%s" % constants.LABEL_EXIT_CODE,
action="store_true",
dest=constants.LABEL_EXIT_CODE,
default=False,
help="tell moban to change exit code",
)
parser.add_argument(
"-m", "--%s" % constants.LABEL_MOBANFILE, help="custom moban file"
)
parser.add_argument(
"-g", "--%s" % constants.LABEL_GROUP, help="a subset of targets"
)
parser.add_argument(
constants.POSITIONAL_LABEL_TEMPLATE,
metavar="template",
type=str,
nargs="?",
help="string templates",
)
parser.add_argument(
"-v",
"--%s" % constants.LABEL_VERSION,
action="version",
version="%(prog)s {v}".format(v=__version__),
)
return parser | python | def create_parser():
"""
construct the program options
"""
parser = argparse.ArgumentParser(
prog=constants.PROGRAM_NAME, description=constants.PROGRAM_DESCRIPTION
)
parser.add_argument(
"-cd",
"--%s" % constants.LABEL_CONFIG_DIR,
help="the directory for configuration file lookup",
)
parser.add_argument(
"-c", "--%s" % constants.LABEL_CONFIG, help="the dictionary file"
)
parser.add_argument(
"-td",
"--%s" % constants.LABEL_TMPL_DIRS,
nargs="*",
help="the directories for template file lookup",
)
parser.add_argument(
"-t", "--%s" % constants.LABEL_TEMPLATE, help="the template file"
)
parser.add_argument(
"-o", "--%s" % constants.LABEL_OUTPUT, help="the output file"
)
parser.add_argument(
"--%s" % constants.LABEL_TEMPLATE_TYPE,
help="the template type, default is jinja2",
)
parser.add_argument(
"-f",
action="store_true",
dest=constants.LABEL_FORCE,
default=False,
help="force moban to template all files despite of .moban.hashes",
)
parser.add_argument(
"--%s" % constants.LABEL_EXIT_CODE,
action="store_true",
dest=constants.LABEL_EXIT_CODE,
default=False,
help="tell moban to change exit code",
)
parser.add_argument(
"-m", "--%s" % constants.LABEL_MOBANFILE, help="custom moban file"
)
parser.add_argument(
"-g", "--%s" % constants.LABEL_GROUP, help="a subset of targets"
)
parser.add_argument(
constants.POSITIONAL_LABEL_TEMPLATE,
metavar="template",
type=str,
nargs="?",
help="string templates",
)
parser.add_argument(
"-v",
"--%s" % constants.LABEL_VERSION,
action="version",
version="%(prog)s {v}".format(v=__version__),
)
return parser | [
"def",
"create_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"constants",
".",
"PROGRAM_NAME",
",",
"description",
"=",
"constants",
".",
"PROGRAM_DESCRIPTION",
")",
"parser",
".",
"add_argument",
"(",
"\"-cd\"",
"... | construct the program options | [
"construct",
"the",
"program",
"options"
] | 5d1674ae461b065a9a54fe89c445cbf6d3cd63c0 | https://github.com/moremoban/moban/blob/5d1674ae461b065a9a54fe89c445cbf6d3cd63c0/moban/main.py#L61-L125 | train | 32,596 |
moremoban/moban | moban/main.py | handle_moban_file | def handle_moban_file(moban_file, options):
"""
act upon default moban file
"""
moban_file_configurations = load_data(None, moban_file)
if moban_file_configurations is None:
raise exceptions.MobanfileGrammarException(
constants.ERROR_INVALID_MOBAN_FILE % moban_file
)
if (
constants.LABEL_TARGETS not in moban_file_configurations
and constants.LABEL_COPY not in moban_file_configurations
):
raise exceptions.MobanfileGrammarException(
constants.ERROR_NO_TARGETS % moban_file
)
check_none(moban_file_configurations, moban_file)
version = moban_file_configurations.get(
constants.MOBAN_VERSION, constants.DEFAULT_MOBAN_VERSION
)
if version == constants.DEFAULT_MOBAN_VERSION:
mobanfile.handle_moban_file_v1(moban_file_configurations, options)
else:
raise exceptions.MobanfileGrammarException(
constants.MESSAGE_FILE_VERSION_NOT_SUPPORTED % version
)
HASH_STORE.save_hashes() | python | def handle_moban_file(moban_file, options):
"""
act upon default moban file
"""
moban_file_configurations = load_data(None, moban_file)
if moban_file_configurations is None:
raise exceptions.MobanfileGrammarException(
constants.ERROR_INVALID_MOBAN_FILE % moban_file
)
if (
constants.LABEL_TARGETS not in moban_file_configurations
and constants.LABEL_COPY not in moban_file_configurations
):
raise exceptions.MobanfileGrammarException(
constants.ERROR_NO_TARGETS % moban_file
)
check_none(moban_file_configurations, moban_file)
version = moban_file_configurations.get(
constants.MOBAN_VERSION, constants.DEFAULT_MOBAN_VERSION
)
if version == constants.DEFAULT_MOBAN_VERSION:
mobanfile.handle_moban_file_v1(moban_file_configurations, options)
else:
raise exceptions.MobanfileGrammarException(
constants.MESSAGE_FILE_VERSION_NOT_SUPPORTED % version
)
HASH_STORE.save_hashes() | [
"def",
"handle_moban_file",
"(",
"moban_file",
",",
"options",
")",
":",
"moban_file_configurations",
"=",
"load_data",
"(",
"None",
",",
"moban_file",
")",
"if",
"moban_file_configurations",
"is",
"None",
":",
"raise",
"exceptions",
".",
"MobanfileGrammarException",
... | act upon default moban file | [
"act",
"upon",
"default",
"moban",
"file"
] | 5d1674ae461b065a9a54fe89c445cbf6d3cd63c0 | https://github.com/moremoban/moban/blob/5d1674ae461b065a9a54fe89c445cbf6d3cd63c0/moban/main.py#L128-L154 | train | 32,597 |
moremoban/moban | moban/main.py | handle_command_line | def handle_command_line(options):
"""
act upon command options
"""
options = merge(options, constants.DEFAULT_OPTIONS)
engine = plugins.ENGINES.get_engine(
options[constants.LABEL_TEMPLATE_TYPE],
options[constants.LABEL_TMPL_DIRS],
options[constants.LABEL_CONFIG_DIR],
)
if options[constants.LABEL_TEMPLATE] is None:
if options[constants.POSITIONAL_LABEL_TEMPLATE] is None:
raise exceptions.NoTemplate(constants.ERROR_NO_TEMPLATE)
else:
engine.render_string_to_file(
options[constants.POSITIONAL_LABEL_TEMPLATE],
options[constants.LABEL_CONFIG],
options[constants.LABEL_OUTPUT],
)
else:
engine.render_to_file(
options[constants.LABEL_TEMPLATE],
options[constants.LABEL_CONFIG],
options[constants.LABEL_OUTPUT],
)
engine.report()
HASH_STORE.save_hashes()
exit_code = reporter.convert_to_shell_exit_code(
engine.number_of_templated_files()
)
return exit_code | python | def handle_command_line(options):
"""
act upon command options
"""
options = merge(options, constants.DEFAULT_OPTIONS)
engine = plugins.ENGINES.get_engine(
options[constants.LABEL_TEMPLATE_TYPE],
options[constants.LABEL_TMPL_DIRS],
options[constants.LABEL_CONFIG_DIR],
)
if options[constants.LABEL_TEMPLATE] is None:
if options[constants.POSITIONAL_LABEL_TEMPLATE] is None:
raise exceptions.NoTemplate(constants.ERROR_NO_TEMPLATE)
else:
engine.render_string_to_file(
options[constants.POSITIONAL_LABEL_TEMPLATE],
options[constants.LABEL_CONFIG],
options[constants.LABEL_OUTPUT],
)
else:
engine.render_to_file(
options[constants.LABEL_TEMPLATE],
options[constants.LABEL_CONFIG],
options[constants.LABEL_OUTPUT],
)
engine.report()
HASH_STORE.save_hashes()
exit_code = reporter.convert_to_shell_exit_code(
engine.number_of_templated_files()
)
return exit_code | [
"def",
"handle_command_line",
"(",
"options",
")",
":",
"options",
"=",
"merge",
"(",
"options",
",",
"constants",
".",
"DEFAULT_OPTIONS",
")",
"engine",
"=",
"plugins",
".",
"ENGINES",
".",
"get_engine",
"(",
"options",
"[",
"constants",
".",
"LABEL_TEMPLATE_... | act upon command options | [
"act",
"upon",
"command",
"options"
] | 5d1674ae461b065a9a54fe89c445cbf6d3cd63c0 | https://github.com/moremoban/moban/blob/5d1674ae461b065a9a54fe89c445cbf6d3cd63c0/moban/main.py#L179-L209 | train | 32,598 |
tammoippen/iso4217parse | iso4217parse/__init__.py | by_symbol | def by_symbol(symbol, country_code=None):
"""Get list of possible currencies for symbol; filter by country_code
Look for all currencies that use the `symbol`. If there are currencies used
in the country of `country_code`, return only those; otherwise return all
found currencies.
Parameters:
symbol: unicode Currency symbol.
country_code: Optional[unicode] Iso3166 alpha2 country code.
Returns:
List[Currency]: Currency objects for `symbol`; filter by country_code.
"""
res = _data()['symbol'].get(symbol)
if res:
tmp_res = []
for d in res:
if country_code in d.countries:
tmp_res += [d]
if tmp_res:
return tmp_res
if country_code is None:
return res | python | def by_symbol(symbol, country_code=None):
"""Get list of possible currencies for symbol; filter by country_code
Look for all currencies that use the `symbol`. If there are currencies used
in the country of `country_code`, return only those; otherwise return all
found currencies.
Parameters:
symbol: unicode Currency symbol.
country_code: Optional[unicode] Iso3166 alpha2 country code.
Returns:
List[Currency]: Currency objects for `symbol`; filter by country_code.
"""
res = _data()['symbol'].get(symbol)
if res:
tmp_res = []
for d in res:
if country_code in d.countries:
tmp_res += [d]
if tmp_res:
return tmp_res
if country_code is None:
return res | [
"def",
"by_symbol",
"(",
"symbol",
",",
"country_code",
"=",
"None",
")",
":",
"res",
"=",
"_data",
"(",
")",
"[",
"'symbol'",
"]",
".",
"get",
"(",
"symbol",
")",
"if",
"res",
":",
"tmp_res",
"=",
"[",
"]",
"for",
"d",
"in",
"res",
":",
"if",
... | Get list of possible currencies for symbol; filter by country_code
Look for all currencies that use the `symbol`. If there are currencies used
in the country of `country_code`, return only those; otherwise return all
found currencies.
Parameters:
symbol: unicode Currency symbol.
country_code: Optional[unicode] Iso3166 alpha2 country code.
Returns:
List[Currency]: Currency objects for `symbol`; filter by country_code. | [
"Get",
"list",
"of",
"possible",
"currencies",
"for",
"symbol",
";",
"filter",
"by",
"country_code"
] | dd2971bd66e83424c43d16d6b54b3f6d0c4201cf | https://github.com/tammoippen/iso4217parse/blob/dd2971bd66e83424c43d16d6b54b3f6d0c4201cf/iso4217parse/__init__.py#L157-L181 | train | 32,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.