def define_assignment_operator(parser):
"""Define assignment and reading of simple variables."""
parser.calculator_symbol_dict = {} # Store symbol dict as a new parser attribute.
symbol_dict = parser.calculator_symbol_dict
symbol_dict["pi"] = np.pi # Predefine pi.
symbol_dict["e"] = np.e # Predefine e.
# Note that on_ties for identifiers is set to -1, so that when string
# lengths are equal defined function names will take precedence over generic
# identifiers (which are only defined as a group regex).
parser.def_token("k_identifier", r"[a-zA-Z_](?:\w*)", on_ties=-1)
parser.def_literal("k_identifier", eval_fun=lambda t: symbol_dict.get(t.value, 0.0))
def eval_assign(t):
"""Evaluate the identifier token `t` and save the value in `symbol_dict`."""
rhs = t[1].eval_subtree()
symbol_dict[t[0].value] = rhs
return rhs
parser.def_infix_op("k_equals", 5, "right",
precond_fun=lambda tok, lex: lex.peek(-1).token_label == "k_identifier",
eval_fun=eval_assign)
python类e()的实例源码
def test_closing_fid(self):
# Test that issue #1517 (too many opened files) remains closed
# It might be a "weak" test since failed to get triggered on
# e.g. Debian sid of 2012 Jul 05 but was reported to
# trigger the failure on Ubuntu 10.04:
# http://projects.scipy.org/numpy/ticket/1517#comment:2
with temppath(suffix='.npz') as tmp:
np.savez(tmp, data='LOVELY LOAD')
# We need to check if the garbage collector can properly close
# numpy npz file returned by np.load when their reference count
# goes to zero. Python 3 running in debug mode raises a
# ResourceWarning when file closing is left to the garbage
# collector, so we catch the warnings. Because ResourceWarning
# is unknown in Python < 3.x, we take the easy way out and
# catch all warnings.
with warnings.catch_warnings():
warnings.simplefilter("ignore")
for i in range(1, 1025):
try:
np.load(tmp)["data"]
except Exception as e:
msg = "Failed to load data from a file: %s" % e
raise AssertionError(msg)
def test_invalid_raise(self):
# Test invalid raise
data = ["1, 1, 1, 1, 1"] * 50
for i in range(5):
data[10 * i] = "2, 2, 2, 2 2"
data.insert(0, "a, b, c, d, e")
mdata = TextIO("\n".join(data))
#
kwargs = dict(delimiter=",", dtype=None, names=True)
# XXX: is there a better way to get the return value of the
# callable in assert_warns ?
ret = {}
def f(_ret={}):
_ret['mtest'] = np.ndfromtxt(mdata, invalid_raise=False, **kwargs)
assert_warns(ConversionWarning, f, _ret=ret)
mtest = ret['mtest']
assert_equal(len(mtest), 45)
assert_equal(mtest, np.ones(45, dtype=[(_, int) for _ in 'abcde']))
#
mdata.seek(0)
assert_raises(ValueError, np.ndfromtxt, mdata,
delimiter=",", names=True)
def test_real(self):
val = ng.get_data('const.e')
assert type(val) == np.ndarray
assert len(val) == 1
assert val.dtype == 'float64'
assert val[0] == pytest.approx(np.e)
def entropy(self):
return U.sum(self.logstd + .5 * np.log(2.0 * np.pi * np.e), -1)
def test_uniformfloat_to_integer(self):
f1 = UniformFloatHyperparameter("param", 1, 10, q=0.1, log=True)
with warnings.catch_warnings():
f2 = f1.to_integer()
warnings.simplefilter("ignore")
# TODO is this a useful rounding?
# TODO should there be any rounding, if e.g. lower=0.1
self.assertEqual("param, Type: UniformInteger, Range: [1, 10], "
"Default: 3, on log-scale", str(f2))
def gl_quad3d(fun,n,x_lim = None,y_lim = None,z_lim = None,args=()):
if x_lim is None:
a,b = -1, 1
else:
a,b= x_lim[0],x_lim[1]
if y_lim is None:
c ,d = -1,1
else:
c ,d = y_lim[0],y_lim[1]
if z_lim is None:
e,f= -1,1
else:
e ,f = z_lim[0],z_lim[1]
if not callable(fun):
return (b-a)*(d-c)*(f-e)*fun
else:
loc,w = np.polynomial.legendre.leggauss(n)
s = (1/8.*(b-a)*(d-c)*(f-e)*fun(((b-a)*v1/2.+(a+b)/2.,
(d-c)*v2/2.+(c+d)/2.,
(f-e)*v3/2.+(e+f)/2.),*args)*w[i]*w[j]*w[k]
for i,v1 in enumerate(loc)
for j,v2 in enumerate(loc)
for k,v3 in enumerate(loc))
return sum(s)
def fun2(x,a,b):
return a*x[0]*x[1]*np.e**(b*x[2])
def __iadd__(self, other):
'''add an instance (e.g., from another sentence).'''
if type(other) is tuple:
## avoid creating new CiderScorer instances
self.cook_append(other[0], other[1])
else:
self.ctest.extend(other.ctest)
self.crefs.extend(other.crefs)
return self
def __iadd__(self, other):
'''add an instance (e.g., from another sentence).'''
if type(other) is tuple:
## avoid creating new CiderScorer instances
self.cook_append(other[0], other[1])
else:
self.ctest.extend(other.ctest)
self.crefs.extend(other.crefs)
return self
def __iadd__(self, other):
'''add an instance (e.g., from another sentence).'''
if type(other) is tuple:
## avoid creating new CiderScorer instances
self.cook_append(other[0], other[1])
else:
self.ctest.extend(other.ctest)
self.crefs.extend(other.crefs)
return self
def test_complex_arrays(self):
ncols = 2
nrows = 2
a = np.zeros((ncols, nrows), dtype=np.complex128)
re = np.pi
im = np.e
a[:] = re + 1.0j * im
# One format only
c = BytesIO()
np.savetxt(c, a, fmt=' %+.3e')
c.seek(0)
lines = c.readlines()
assert_equal(
lines,
[b' ( +3.142e+00+ +2.718e+00j) ( +3.142e+00+ +2.718e+00j)\n',
b' ( +3.142e+00+ +2.718e+00j) ( +3.142e+00+ +2.718e+00j)\n'])
# One format for each real and imaginary part
c = BytesIO()
np.savetxt(c, a, fmt=' %+.3e' * 2 * ncols)
c.seek(0)
lines = c.readlines()
assert_equal(
lines,
[b' +3.142e+00 +2.718e+00 +3.142e+00 +2.718e+00\n',
b' +3.142e+00 +2.718e+00 +3.142e+00 +2.718e+00\n'])
# One format for each complex number
c = BytesIO()
np.savetxt(c, a, fmt=['(%.3e%+.3ej)'] * ncols)
c.seek(0)
lines = c.readlines()
assert_equal(
lines,
[b'(3.142e+00+2.718e+00j) (3.142e+00+2.718e+00j)\n',
b'(3.142e+00+2.718e+00j) (3.142e+00+2.718e+00j)\n'])
def test_invalid_raise_with_usecols(self):
# Test invalid_raise with usecols
data = ["1, 1, 1, 1, 1"] * 50
for i in range(5):
data[10 * i] = "2, 2, 2, 2 2"
data.insert(0, "a, b, c, d, e")
mdata = TextIO("\n".join(data))
kwargs = dict(delimiter=",", dtype=None, names=True,
invalid_raise=False)
# XXX: is there a better way to get the return value of the
# callable in assert_warns ?
ret = {}
def f(_ret={}):
_ret['mtest'] = np.ndfromtxt(mdata, usecols=(0, 4), **kwargs)
assert_warns(ConversionWarning, f, _ret=ret)
mtest = ret['mtest']
assert_equal(len(mtest), 45)
assert_equal(mtest, np.ones(45, dtype=[(_, int) for _ in 'ae']))
#
mdata.seek(0)
mtest = np.ndfromtxt(mdata, usecols=(0, 1), **kwargs)
assert_equal(len(mtest), 50)
control = np.ones(50, dtype=[(_, int) for _ in 'ab'])
control[[10 * _ for _ in range(5)]] = (2, 2)
assert_equal(mtest, control)
def e() -> Float:
return np.e
def __call__(self, samples, x):
z = T.log(self.sigma * T.sqrt(2 * pi)).sum()
d_s = (samples[:, None, :] - x[None, :, :]) / self.sigma[None, None, :]
e = log_mean_exp((-.5 * d_s ** 2).sum(axis=2), axis=0)
return (e - z).mean()
def entropy(self, dist_info):
log_stds = dist_info["log_std"]
return np.sum(log_stds + np.log(np.sqrt(2 * np.pi * np.e)), axis=-1)
def entropy_sym(self, dist_info_var):
log_std_var = dist_info_var["log_std"]
return TT.sum(log_std_var + TT.log(np.sqrt(2 * np.pi * np.e)), axis=-1)
def shift_or_mirror_into_invertible_domain(self, solution_genotype):
"""return the reference solution that has the same ``box_constraints_transformation(solution)``
value, i.e. ``tf.shift_or_mirror_into_invertible_domain(x) = tf.inverse(tf.transform(x))``.
This is an idempotent mapping (leading to the same result independent how often it is
repeatedly applied).
"""
return self.inverse(self(solution_genotype))
raise NotImplementedError('this is an abstract method that should be implemented in the derived class')
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 __init__(self, fitness_function, *args, **kwargs):
"""`fitness_function` must be callable (e.g. a function
or a callable class instance)"""
# the original fitness to be called
self.inner_fitness = fitness_function
# self.condition_number = ...