python类e()的实例源码

example_numpy_calculator.py 文件源码 项目:typped 作者: abarker 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
test_io.py 文件源码 项目:Alfred 作者: jkachhadia 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
test_io.py 文件源码 项目:Alfred 作者: jkachhadia 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
test_ngspicepy.py 文件源码 项目:ngspicepy 作者: ashwith 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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)
distributions.py 文件源码 项目:distributional_perspective_on_RL 作者: Kiwoo 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def entropy(self):
        return U.sum(self.logstd + .5 * np.log(2.0 * np.pi * np.e), -1)
test_hyperparameters.py 文件源码 项目:ConfigSpace 作者: automl 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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))
tools.py 文件源码 项目:Feon 作者: YaoyaoBae 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
tools.py 文件源码 项目:Feon 作者: YaoyaoBae 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def fun2(x,a,b):
    return a*x[0]*x[1]*np.e**(b*x[2])
cider_scorer_compute_sentence.py 文件源码 项目:monogreedy 作者: jinjunqi 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
cider_scorer.py 文件源码 项目:monogreedy 作者: jinjunqi 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
cider_scorer.py 文件源码 项目:keras-image-captioning 作者: danieljl 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
test_io.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 45 收藏 0 点赞 0 评论 0
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'])
test_io.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)
math.py 文件源码 项目:Sverchok 作者: Sverchok 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def e() -> Float:
    return np.e
layers.py 文件源码 项目:cortex 作者: rdevon 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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()
diagonal_gaussian.py 文件源码 项目:third_person_im 作者: bstadie 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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)
diagonal_gaussian.py 文件源码 项目:third_person_im 作者: bstadie 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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)
cma_es_lib.py 文件源码 项目:third_person_im 作者: bstadie 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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')
cma_es_lib.py 文件源码 项目:third_person_im 作者: bstadie 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
cma_es_lib.py 文件源码 项目:third_person_im 作者: bstadie 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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 = ...


问题


面经


文章

微信
公众号

扫码关注公众号