Python math.erf() Examples

The following are code examples for showing how to use math.erf(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: atesa   Author: team-mayes   File: Burgin_LMAX.py    MIT License 6 votes vote down vote up
def objective_function(params, A_data, B_data):
    # Returns -1*(sumA(ln(1 - theta)) + sumB(ln(theta))) where theta = (1 + erf(q))/2 and q is the reaction coordinate
    def erflike(arg):
        if -5.7 <= arg <= 5.7:
            return math.erf(arg)
        elif arg > 5.7:
            return math.erf(5.7)
        else:
            return math.erf(-5.7)

    params = list(params)
    sum = 0
    for observation in A_data:                  # observation is a list of CV values for a given observation
        try:
            q = params[0] + numpy.dot(params[1:],observation)
        except ValueError:
            print(params)
            print(observation)
            sys.exit()
        sum += numpy.log(1 - (1 + erflike(q))/2)            # increment log-likelihood by log(1-theta)
    for observation in B_data:
        q = params[0] + numpy.dot(params[1:],observation)
        sum += numpy.log((1 + erflike(q))/2)                # increment log-likelihood by log(theta)

    return -1 * sum 
Example 2
Project: atesa   Author: team-mayes   File: Burgin_LMAX.py    MIT License 6 votes vote down vote up
def objective_function(params, A_data, B_data):
    # Returns -1*(sumA(ln(1 - theta)) + sumB(ln(theta))) where theta = (1 + erf(q))/2 and q is the reaction coordinate
    def erflike(arg):
        if -5.7 <= arg <= 5.7:
            return math.erf(arg)
        elif arg > 5.7:
            return math.erf(5.7)
        else:
            return math.erf(-5.7)

    params = list(params)
    sum = 0
    for observation in A_data:                  # observation is a list of CV values for a given observation
        try:
            q = params[0] + numpy.dot(params[1:],observation)
        except ValueError:
            print(params)
            print(observation)
            sys.exit()
        sum += numpy.log(1 - (1 + erflike(q))/2)            # increment log-likelihood by log(1-theta)
    for observation in B_data:
        q = params[0] + numpy.dot(params[1:],observation)
        sum += numpy.log((1 + erflike(q))/2)                # increment log-likelihood by log(theta)

    return -1 * sum 
Example 3
Project: necrobot   Author: incnone   File: racestats.py    MIT License 6 votes vote down vote up
def get_winrates(user_id_1: int, user_id_2: int, ndchar: NDChar, amplified: bool) -> tuple or None:
    stats_1 = await get_character_stats(user_id_1, ndchar, amplified)
    stats_2 = await get_character_stats(user_id_2, ndchar, amplified)
    if not stats_1.has_wins or not stats_2.has_wins:
        return None

    m2_minus_m1 = stats_2.mean - stats_1.mean
    sum_var = stats_1.var + stats_2.var
    erf_arg = m2_minus_m1 / math.sqrt(2*sum_var)
    if m2_minus_m1 > 0:
        winrate_of_1_if_both_finish = (1.0 + math.erf(erf_arg))/2.0
    else:
        winrate_of_1_if_both_finish = (1.0 - math.erf(-erf_arg))/2.0

    both_finish_prob = stats_1.winrate * stats_2.winrate
    neither_finish_prob = (1-stats_1.winrate)*(1-stats_2.winrate)
    winrate_of_1 = winrate_of_1_if_both_finish*both_finish_prob + (stats_1.winrate - both_finish_prob)
    winrate_of_2 = (1.0-winrate_of_1_if_both_finish)*both_finish_prob + (stats_2.winrate - both_finish_prob)
    return winrate_of_1, winrate_of_2, neither_finish_prob 
Example 4
Project: pyKriging   Author: capaulson   File: regressionkrige.py    GNU General Public License v2.0 6 votes vote down vote up
def expimp(self, x):
        '''
        Returns the expected improvement at the design vector X in the model
        :param x: A real world coordinates design vector
        :return EI: The expected improvement value at the point x in the model
        '''
        S = self.predicterr_normalized(x)
        y_min = np.min(self.y)
        if S <= 0.:
            EI = 0.
        elif S > 0.:
            EI_one = ((y_min - self.predict_normalized(x)) * (0.5 + 0.5*m.erf((
                      1./np.sqrt(2.))*((y_min - self.predict_normalized(x)) /
                                       S))))
            EI_two = ((S * (1. / np.sqrt(2. * np.pi))) * (np.exp(-(1./2.) *
                      ((y_min - self.predict_normalized(x))**2. / S**2.))))
            EI = EI_one + EI_two
        return EI 
Example 5
Project: pyKriging   Author: capaulson   File: krige.py    GNU General Public License v2.0 6 votes vote down vote up
def expimp(self, x):
        '''
        Returns the expected improvement at the design vector X in the model
        :param x: A real world coordinates design vector
        :return EI: The expected improvement value at the point x in the model
        '''
        S = self.predicterr_normalized(x)
        y_min = np.min(self.y)
        if S <= 0.:
            EI = 0.
        elif S > 0.:
            EI_one = ((y_min - self.predict_normalized(x)) * (0.5 + 0.5*m.erf((
                      1./np.sqrt(2.))*((y_min - self.predict_normalized(x)) /
                                       S))))
            EI_two = ((S * (1. / np.sqrt(2. * np.pi))) * (np.exp(-(1./2.) *
                      ((y_min - self.predict_normalized(x))**2. / S**2.))))
            EI = EI_one + EI_two
        return EI 
Example 6
Project: kicker-module   Author: EvanTheB   File: trueskill.py    GNU General Public License v3.0 5 votes vote down vote up
def gaussian_cumulative_to(x, mean=0.0, standard_dev=1.0):
    """
    cumulative (error function) to x.
    """
    x = (x - mean) / standard_dev
    return 0.5 + 0.5 * math.erf(x / math.sqrt(2)) 
Example 7
Project: tripp   Author: mjamesruggiero   File: probability.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def normal_cdf(x, mu=0, sigma=1):
    """the probability that a real-valued random variable X
    with a given probability distribution will be found
    to have a value less than or equal to x"""
    return (1 + math.erf((x - mu) / math.sqrt(2) / sigma)) / 2 
Example 8
Project: tributary   Author: timkpaine   File: ops.py    Apache License 2.0 5 votes vote down vote up
def Erf(self):
    return self._gennode('erf(' + self._name + ')', (lambda x: math.erf(self.value())), [self], self._trace) 
Example 9
Project: tributary   Author: timkpaine   File: ops.py    Apache License 2.0 5 votes vote down vote up
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
    if ufunc == np.add:
        if isinstance(inputs[0], _Node):
            return inputs[0].__add__(inputs[1])
        else:
            return inputs[1].__add__(inputs[0])
    elif ufunc == np.subtract:
        if isinstance(inputs[0], _Node):
            return inputs[0].__sub__(inputs[1])
        else:
            return inputs[1].__sub__(inputs[0])
    elif ufunc == np.multiply:
        if isinstance(inputs[0], _Node):
            return inputs[0].__mul__(inputs[1])
        else:
            return inputs[1].__mul__(inputs[0])
    elif ufunc == np.divide:
        if isinstance(inputs[0], _Node):
            return inputs[0].__truedivide__(inputs[1])
        else:
            return inputs[1].__truedivide__(inputs[0])
    elif ufunc == np.sin:
        return inputs[0].sin()
    elif ufunc == np.cos:
        return inputs[0].cos()
    elif ufunc == np.tan:
        return inputs[0].tan()
    elif ufunc == np.arcsin:
        return inputs[0].arcsin()
    elif ufunc == np.arccos:
        return inputs[0].arccos()
    elif ufunc == np.arctan:
        return inputs[0].arctan()
    elif ufunc == np.exp:
        return inputs[0].exp()
    elif ufunc == sp.special.erf:
        return inputs[0].erf()
    else:
        raise NotImplementedError('Not Implemented!') 
Example 10
Project: litmus-site   Author: alps-jbnu   File: ratings.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def WP(RA, RB, VA, VB):
    return (math.erf((RB - RA) / math.sqrt(2 * (VA * VA + VB * VB))) + 1) / 2.0 
Example 11
Project: atesa   Author: team-mayes   File: atesa_lmax.py    MIT License 5 votes vote down vote up
def sigmoid_data(params, obs):
    # Returns reaction coordinate value for a given set of parameters and observation
    params = list(params)
    q = params[0] + numpy.dot(params[1:], obs)
    # for index in range(len(obs)):
    #     q += params[index + 1] * obs[index]
    theta = (1 + math.erf(q))/2

    return q 
Example 12
Project: atesa   Author: team-mayes   File: atesa_lmax.py    MIT License 5 votes vote down vote up
def objective_function(params, A_data, B_data):
    # Returns -1 * (sumA(ln(1 - theta)) + sumB(ln(theta))) where theta = (1 + erf(q))/2 and q is the reaction coordinate
    def erflikefast(arg):
        pl = numpy.ones(len(arg))
        ml = numpy.negative(numpy.ones(len(arg)))
        return numpy.where(arg > 5.7, pl, numpy.where(arg < -5.7, ml, erf(arg)))

    params = list(params)
    qa = params[0] + numpy.inner(params[1:], A_data)
    qb = params[0] + numpy.inner(params[1:], B_data)
    sum = numpy.sum(numpy.log((1 - erflikefast(qa)) / 2)) + numpy.sum(numpy.log((1 + erflikefast(qb)) / 2))
    
    # for observation in A_data:                  # observation is a list of CV values for a given observation
    #     try:
    #         q = params[0] + numpy.dot(params[1:],observation)
    #     except ValueError:
    #         print(params)
    #         print(observation)
    #         sys.exit()
    #     sum += numpy.log(1 - (1 + erflike(q))/2)            # increment log-likelihood by log(1-theta)
    # for observation in B_data:
    #     q = params[0] + numpy.dot(params[1:],observation)
    #     sum += numpy.log((1 + erflike(q))/2)                # increment log-likelihood by log(theta)
    # print sum, suma, params[0]

    return -1 * sum 
Example 13
Project: atesa   Author: team-mayes   File: Burgin_LMAX.py    MIT License 5 votes vote down vote up
def sigmoid_data(params, obs):
    # Returns reaction coordinate value for a given set of parameters and observation
    params = list(params)
    q = params[0]
    for index in range(len(obs)):
        q += params[index + 1] * obs[index]
    theta = (1 + math.erf(q))/2

    return q 
Example 14
Project: atesa   Author: team-mayes   File: Burgin_LMAX_josh.py    MIT License 5 votes vote down vote up
def sigmoid_data(params, obs):
    # Returns reaction coordinate value for a given set of parameters and observation
    params = list(params)
    q = params[0] + numpy.dot(params[1:], obs)
    # for index in range(len(obs)):
    #     q += params[index + 1] * obs[index]
    theta = (1 + math.erf(q))/2

    return q 
Example 15
Project: atesa   Author: team-mayes   File: Burgin_LMAX.py    MIT License 5 votes vote down vote up
def sigmoid_data(params, obs):
    # Returns reaction coordinate value for a given set of parameters and observation
    params = list(params)
    q = params[0]
    for index in range(len(obs)):
        q += params[index + 1] * obs[index]
    theta = (1 + math.erf(q))/2

    return q 
Example 16
Project: atesa   Author: team-mayes   File: Burgin_LMAX_josh.py    MIT License 5 votes vote down vote up
def sigmoid_data(params, obs):
    # Returns reaction coordinate value for a given set of parameters and observation
    params = list(params)
    q = params[0] + numpy.dot(params[1:], obs)
    # for index in range(len(obs)):
    #     q += params[index + 1] * obs[index]
    theta = (1 + math.erf(q))/2

    return q 
Example 17
Project: atesa   Author: team-mayes   File: Burgin_LMAX_josh.py    MIT License 5 votes vote down vote up
def objective_function(params, A_data, B_data):
    # Returns -1*(sumA(ln(1 - theta)) + sumB(ln(theta))) where theta = (1 + erf(q))/2 and q is the reaction coordinate
    def erflikefast(arg):
        pluslimit = erf(5.7) * numpy.ones(len(arg))
        minuslimit = erf(-5.7) * numpy.ones(len(arg))
        #This is not particularly efficient
        return numpy.where(arg>5.7, pluslimit, numpy.where(arg<-5.7, minuslimit, erf(arg)))
    def erflike(arg):
        if -5.7 <= arg <= 5.7:
            return math.erf(arg)
        elif arg > 5.7:
            return math.erf(5.7)
        else:
            return math.erf(-5.7)

    params = list(params)
    #sum = 0
    qa = params[0] + numpy.inner(params[1:], A_data)
    qb = params[0] + numpy.inner(params[1:], B_data)
    sum = numpy.sum(numpy.log((1-erflikefast(qa))/2)) + numpy.sum(numpy.log((1+erflikefast(qb))/2))
    
    # for observation in A_data:                  # observation is a list of CV values for a given observation
    #     try:
    #         q = params[0] + numpy.dot(params[1:],observation)
    #     except ValueError:
    #         print(params)
    #         print(observation)
    #         sys.exit()
    #     sum += numpy.log(1 - (1 + erflike(q))/2)            # increment log-likelihood by log(1-theta)
    # for observation in B_data:
    #     q = params[0] + numpy.dot(params[1:],observation)
    #     sum += numpy.log((1 + erflike(q))/2)                # increment log-likelihood by log(theta)
    # print sum, suma, params[0]
    return -1 * sum 
Example 18
Project: ironpython2   Author: IronLanguages   File: test_math.py    Apache License 2.0 5 votes vote down vote up
def test_erf_erfc(self):
        tolerance = 15
        for x in itertools.count(0.0, 0.001):
            if x > 5.0:
                break
            self.assertAlmostEqual(math.erf(x), -math.erf(-x), places=tolerance)
            self.assertAlmostEqual(math.erfc(x), 2.0 - math.erfc(-x), places=tolerance)

            self.assertAlmostEqual(1.0 - math.erf(x), math.erfc(x), places=tolerance)
            self.assertAlmostEqual(1.0 - math.erf(-x), math.erfc(-x), places=tolerance)
            self.assertAlmostEqual(1.0 - math.erfc(x), math.erf(x), places=tolerance)
            self.assertAlmostEqual(1.0 - math.erfc(-x), math.erf(-x), places=tolerance) 
Example 19
Project: onnx-tensorflow   Author: onnx   File: test_node.py    Apache License 2.0 5 votes vote down vote up
def test_erf(self):
    if legacy_opset_pre_ver(9):
      raise unittest.SkipTest("ONNX version {} doesn't support Erf.".format(
          defs.onnx_opset_version()))
    node_def = helper.make_node("Erf", ["X"], ["Y"])
    x = self._get_rnd_float32(shape=[3, 4, 5])
    output = run_node(node_def, [x])
    exp_output = np.vectorize(math.erf)(x).astype(np.float32)
    np.testing.assert_almost_equal(output["Y"], exp_output) 
Example 20
Project: FCM_FNN   Author: YSunLIN   File: fcm_fnn.py    Apache License 2.0 5 votes vote down vote up
def erf(x):
    return math.erf(x) * 0.5 
Example 21
Project: FCM_FNN   Author: YSunLIN   File: fcm_fnn.py    Apache License 2.0 5 votes vote down vote up
def erfs2(ld, C, sigma):
    return erf(sqrt2 * (ld - C) / sigma) 
Example 22
Project: macefash   Author: harababurel   File: ratingSystem.py    MIT License 5 votes vote down vote up
def getWinProbability(comparedTo, currentPlayer):
    return 0.5 * (erf((comparedTo.rating - currentPlayer.rating) / sqrt(2.0 * (comparedTo.volatility**2.0 + currentPlayer.volatility**2.0))) + 1.0) 
Example 23
Project: variantfishtest   Author: ianfab   File: stat_util.py    GNU General Public License v3.0 5 votes vote down vote up
def erf(x):
    # Python 2.7 defines math.erf(), but we need to cater for older versions.
    a = 8 * (math.pi - 3) / (3 * math.pi * (4 - math.pi))
    x2 = x * x
    y = -x2 * (4 / math.pi + a * x2) / (1 + a * x2)
    return math.copysign(math.sqrt(1 - math.exp(y)), x) 
Example 24
Project: variantfishtest   Author: ianfab   File: stat_util.py    GNU General Public License v3.0 5 votes vote down vote up
def erf_inv(x):
    # Above erf formula inverted analytically
    a = 8 * (math.pi - 3) / (3 * math.pi * (4 - math.pi))
    y = math.log(1 - x * x)
    z = 2 / (math.pi * a) + y / 2
    return math.copysign(math.sqrt(math.sqrt(z * z - y / a) - z), x) 
Example 25
Project: variantfishtest   Author: ianfab   File: stat_util.py    GNU General Public License v3.0 5 votes vote down vote up
def phi(q):
    # Cumlative distribution function for the standard Gaussian law: quantile -> probability
    return 0.5 * (1 + erf(q / math.sqrt(2))) 
Example 26
Project: gnubg   Author: gtzampanakis   File: elo.py    MIT License 5 votes vote down vote up
def phi(x):
	'Cumulative distribution function for the standard normal distribution'
	return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0 
Example 27
Project: necrobot   Author: incnone   File: ratingutil.py    MIT License 5 votes vote down vote up
def get_winrate(rating_1: Rating, rating_2: Rating):
    delta_mu = rating_1.mu - rating_2.mu
    if delta_mu >= 0:
        beta = trueskill.global_env().beta
        denom = sqrt(2 * (2 * beta * beta + rating_1.sigma * rating_1.sigma + rating_2.sigma * rating_2.sigma))
        return (erf(delta_mu/denom) + 1.0)/2.0
    else:
        return 1.0 - get_winrate(rating_2, rating_1) 
Example 28
Project: pyKriging   Author: capaulson   File: regressionkrige.py    GNU General Public License v2.0 5 votes vote down vote up
def weightedexpimp(self, x, w):
        """weighted expected improvement (Sobester et al. 2005)"""
        S = self.predicterr_normalized(x)
        y_min = np.min(self.y)
        if S <= 0.:
            EI = 0.
        elif S > 0.:
            EI_one = w*((y_min - self.predict_normalized(x)) * (0.5 +
                        0.5*m.erf((1./np.sqrt(2.))*((y_min -
                                  self.predict_normalized(x)) / S))))
            EI_two = ((1. - w)*(S * (1. / np.sqrt(2. * np.pi))) *
                      (np.exp(-(1./2.) * ((y_min -
                       self.predict_normalized(x))**2. / S**2.))))
            EI = EI_one + EI_two
        return EI 
Example 29
Project: pyKriging   Author: capaulson   File: krige.py    GNU General Public License v2.0 5 votes vote down vote up
def weightedexpimp(self, x, w):
        """weighted expected improvement (Sobester et al. 2005)"""
        S = self.predicterr_normalized(x)
        y_min = np.min(self.y)
        if S <= 0.:
            EI = 0.
        elif S > 0.:
            EI_one = w*((y_min - self.predict_normalized(x)) * (0.5 +
                        0.5*m.erf((1./np.sqrt(2.))*((y_min -
                                  self.predict_normalized(x)) / S))))
            EI_two = ((1. - w)*(S * (1. / np.sqrt(2. * np.pi))) *
                      (np.exp(-(1./2.) * ((y_min -
                       self.predict_normalized(x))**2. / S**2.))))
            EI = EI_one + EI_two
        return EI 
Example 30
Project: PyErf   Author: dougthor42   File: pyerf.py    GNU General Public License v3.0 5 votes vote down vote up
def _erf(x):
    """
    Port of cephes ``ndtr.c`` ``erf`` function.

    See https://github.com/jeremybarnes/cephes/blob/master/cprob/ndtr.c
    """
    T = [
        9.60497373987051638749E0,
        9.00260197203842689217E1,
        2.23200534594684319226E3,
        7.00332514112805075473E3,
        5.55923013010394962768E4,
    ]

    U = [
        3.35617141647503099647E1,
        5.21357949780152679795E2,
        4.59432382970980127987E3,
        2.26290000613890934246E4,
        4.92673942608635921086E4,
    ]

    # Shorcut special cases
    if x == 0:
        return 0
    if x >= MAXVAL:
        return 1
    if x <= -MAXVAL:
        return -1

    if abs(x) > 1:
        return 1 - erfc(x)

    z = x * x
    return x * _polevl(z, T, 4) / _p1evl(z, U, 5) 
Example 31
Project: HackerrankPractice   Author: marinskiy   File: 014. Day 6 - The Central Limit Theorem I.py    MIT License 5 votes vote down vote up
def cdf(x, mean, std):
    return 1/2*(1+math.erf((x-mean) / std / 2**(1/2)))


# inputs 
Example 32
Project: HackerrankPractice   Author: marinskiy   File: 012. Day 5 - Normal Distribution I.py    MIT License 5 votes vote down vote up
def cdf(x, mean, std):
    return 1/2*(1+math.erf((x-mean) / std / 2**(1/2))) 
Example 33
Project: HackerrankPractice   Author: marinskiy   File: 013. Day 5 - Normal Distribution II.py    MIT License 5 votes vote down vote up
def cdf(x, mean, std):
    return 1/2*(1+math.erf((x-mean) / std / 2**(1/2))) 
Example 34
Project: HackerrankPractice   Author: marinskiy   File: 015. Day 6 - The Central Limit Theorem II.py    MIT License 5 votes vote down vote up
def cdf(x, mean, std):
    return 1/2*(1+math.erf((x-mean) / std / 2**(1/2)))

# inputs 
Example 35
Project: ufora   Author: ufora   File: pure_math.py    Apache License 2.0 5 votes vote down vote up
def __call__(self, val):
        return __inline_fora(
            """fun(@unnamed_args:(val), *args) {
                   PyFloat(math.erf([email protected]))
                   }"""
            )(val) 
Example 36
Project: ufora   Author: ufora   File: MathTestCases.py    Apache License 2.0 5 votes vote down vote up
def test_pure_python_math_module(self):
        vals = [1, -.5, 1.5, 0, 0.0, -2, -2.2, .2]

        # not being tested: math.asinh, math.atanh, math.lgamma, math.erfc, math.acos
        def f():
            functions = [
                math.sqrt, math.cos, math.sin, math.tan, math.asin, math.atan,
                math.acosh, math.cosh, math.sinh, math.tanh, math.ceil,
                math.erf, math.exp, math.expm1, math.factorial, math.floor,
                math.log, math.log10, math.log1p
            ]
            tr = []
            for idx1 in range(len(vals)):
                v1 = vals[idx1]
                for funIdx in range(len(functions)):
                    function = functions[funIdx]
                    try:
                        tr = tr + [function(v1)]
                    except ValueError as ex:
                        pass

            return tr

        r1 = self.evaluateWithExecutor(f)
        r2 = f()
        self.assertGreater(len(r1), 100)
        self.assertTrue(numpy.allclose(r1, r2, 1e-6)) 
Example 37
Project: data-science-from-scratch   Author: kevntao   File: probability.py    The Unlicense 5 votes vote down vote up
def normal_cdf(x, mu=0,sigma=1):
    return (1 + math.erf((x - mu) / math.sqrt(2) / sigma)) / 2 
Example 38
Project: chainer   Author: chainer   File: test_erf.py    MIT License 5 votes vote down vote up
def _erf_cpu(x, dtype):
    return numpy.vectorize(math.erf, otypes=[dtype])(x) 
Example 39
Project: chainer   Author: chainer   File: erf.py    MIT License 5 votes vote down vote up
def label(self):
        return 'erf' 
Example 40
Project: chainer   Author: chainer   File: erf.py    MIT License 5 votes vote down vote up
def forward_cpu(self, x):
        global _erf_cpu
        if _erf_cpu is None:
            try:
                from scipy import special
                _erf_cpu = special.erf
            except ImportError:
                warnings.warn(
                    'SciPy is not available. Forward computation of erf in CPU'
                    ' can be slow without SciPy.',
                    chainer.warnings.PerformanceWarning)
                _erf_cpu = numpy.vectorize(math.erf)
        self.retain_inputs((0,))
        return utils.force_array(_erf_cpu(x[0]), dtype=x[0].dtype), 
Example 41
Project: chainer   Author: chainer   File: erf.py    MIT License 5 votes vote down vote up
def forward_gpu(self, x):
        self.retain_inputs((0,))
        return cuda.elementwise(
            'T x', 'T y',
            'y = erf(x)',
            'elementwise_erf',
        )(x[0]), 
Example 42
Project: chainer   Author: chainer   File: erf.py    MIT License 5 votes vote down vote up
def erf(x):
    """Elementwise error function.

    .. note::
       Forward computation in CPU can be slow if
       `SciPy <https://www.scipy.org/>`_ is not available.

    Args:
        x (:class:`~chainer.Variable` or :ref:`ndarray`): Input variable.

    Returns:
        ~chainer.Variable: Output variable.
    """
    return Erf().apply((x,))[0] 
Example 43
Project: numpy-ml   Author: ddbourgin   File: schedulers.py    GNU General Public License v3.0 5 votes vote down vote up
def gaussian_cdf(x, mean, var):
    """
    Compute the probability that a random draw from a 1D Gaussian with mean
    `mean` and variance `var` is less than or equal to `x`.
    """
    eps = np.finfo(float).eps
    x_scaled = (x - mean) / np.sqrt(var + eps)
    return (1 + erf(x_scaled / np.sqrt(2))) / 2 
Example 44
Project: hotxlfp   Author: aidhound   File: statistics.py    MIT License 5 votes vote down vote up
def cdf(self, x):
        'Cumulative distribution function.  P(X <= x)'
        if not self.sigma:
            raise StatisticsError('cdf() not defined when sigma is zero')
        return 0.5 * (1.0 + erf((x - self.mu) / (self.sigma * sqrt(2.0)))) 
Example 45
Project: hotxlfp   Author: aidhound   File: statistics.py    MIT License 5 votes vote down vote up
def overlap(self, other):
        '''Compute the overlapping coefficient (OVL) between two normal distributions.

        Measures the agreement between two normal probability distributions.
        Returns a value between 0.0 and 1.0 giving the overlapping area in
        the two underlying probability density functions.

            >>> N1 = NormalDist(2.4, 1.6)
            >>> N2 = NormalDist(3.2, 2.0)
            >>> N1.overlap(N2)
            0.8035050657330205
        '''
        # See: "The overlapping coefficient as a measure of agreement between
        # probability distributions and point estimation of the overlap of two
        # normal densities" -- Henry F. Inman and Edwin L. Bradley Jr
        # http://dx.doi.org/10.1080/03610928908830127
        if not isinstance(other, NormalDist):
            raise TypeError('Expected another NormalDist instance')
        X, Y = self, other
        if (Y.sigma, Y.mu) < (X.sigma, X.mu):   # sort to assure commutativity
            X, Y = Y, X
        X_var, Y_var = X.variance, Y.variance
        if not X_var or not Y_var:
            raise StatisticsError('overlap() not defined when sigma is zero')
        dv = Y_var - X_var
        dm = fabs(Y.mu - X.mu)
        if not dv:
            return 1.0 - erf(dm / (2.0 * X.sigma * sqrt(2.0)))
        a = X.mu * Y_var - Y.mu * X_var
        b = X.sigma * Y.sigma * sqrt(dm**2.0 + dv * log(Y_var / X_var))
        x1 = (a + b) / dv
        x2 = (a - b) / dv
        return 1.0 - (fabs(Y.cdf(x1) - X.cdf(x1)) + fabs(Y.cdf(x2) - X.cdf(x2))) 
Example 46
Project: deep_image_model   Author: tobegit3hub   File: cwise_ops_test.py    Apache License 2.0 5 votes vote down vote up
def testFloatBasic(self):
    x = np.arange(-3, 3).reshape(1, 3, 2).astype(np.float32)
    y = (x + .5).astype(np.float32)     # no zero
    z = (x + 15.5).astype(np.float32)   # all positive
    k = np.arange(-0.90, 0.90, 0.25).astype(np.float32) # between -1 and 1

    self._compareBoth(x, np.abs, tf.abs)
    self._compareBoth(x, np.abs, _ABS)
    self._compareBoth(x, np.negative, tf.neg)
    self._compareBoth(x, np.negative, _NEG)
    self._compareBoth(y, self._inv, tf.inv)
    self._compareBoth(x, np.square, tf.square)
    self._compareBoth(z, np.sqrt, tf.sqrt)
    self._compareBoth(z, self._rsqrt, tf.rsqrt)
    self._compareBoth(x, np.exp, tf.exp)
    self._compareBoth(z, np.log, tf.log)
    self._compareBoth(z, np.log1p, tf.log1p)
    self._compareBoth(x, np.tanh, tf.tanh)
    self._compareBoth(x, self._sigmoid, tf.sigmoid)
    self._compareBoth(y, np.sign, tf.sign)
    self._compareBoth(x, np.sin, tf.sin)
    self._compareBoth(x, np.cos, tf.cos)
    self._compareBoth(k, np.arcsin, tf.asin)
    self._compareBoth(k, np.arccos, tf.acos)
    self._compareBoth(x, np.arctan, tf.atan)
    self._compareBoth(x, np.tan, tf.tan)
    self._compareBoth(
        y,
        np.vectorize(self._replace_domain_error_with_inf(math.lgamma)),
        tf.lgamma)
    self._compareBoth(x, np.vectorize(math.erf), tf.erf)
    self._compareBoth(x, np.vectorize(math.erfc), tf.erfc)

    self._compareBothSparse(x, np.abs, tf.abs)
    self._compareBothSparse(x, np.negative, tf.neg)
    self._compareBothSparse(x, np.square, tf.square)
    self._compareBothSparse(z, np.sqrt, tf.sqrt, tol=1e-3)
    self._compareBothSparse(x, np.tanh, tf.tanh)
    self._compareBothSparse(y, np.sign, tf.sign)
    self._compareBothSparse(x, np.vectorize(math.erf), tf.erf) 
Example 47
Project: deep_image_model   Author: tobegit3hub   File: cwise_ops_test.py    Apache License 2.0 5 votes vote down vote up
def testFloatEmpty(self):
    x = np.empty((2, 0, 5), dtype=np.float32)
    self._compareBoth(x, np.abs, tf.abs)
    self._compareBoth(x, np.abs, _ABS)
    self._compareBoth(x, np.negative, tf.neg)
    self._compareBoth(x, np.negative, _NEG)
    self._compareBoth(x, self._inv, tf.inv)
    self._compareBoth(x, np.square, tf.square)
    self._compareBoth(x, np.sqrt, tf.sqrt)
    self._compareBoth(x, self._rsqrt, tf.rsqrt)
    self._compareBoth(x, np.exp, tf.exp)
    self._compareBoth(x, np.log, tf.log)
    self._compareBoth(x, np.log1p, tf.log1p)
    self._compareBoth(x, np.tanh, tf.tanh)
    self._compareBoth(x, self._sigmoid, tf.sigmoid)
    self._compareBoth(x, np.sign, tf.sign)
    self._compareBoth(x, np.sin, tf.sin)
    self._compareBoth(x, np.cos, tf.cos)
    # Can't use vectorize below, so just use some arbitrary function
    self._compareBoth(x, np.sign, tf.lgamma)
    self._compareBoth(x, np.sign, tf.erf)
    self._compareBoth(x, np.sign, tf.erfc)
    self._compareBoth(x, np.tan, tf.tan)
    self._compareBoth(x, np.arcsin, tf.asin)
    self._compareBoth(x, np.arccos, tf.acos)
    self._compareBoth(x, np.arctan, tf.atan)

    self._compareBothSparse(x, np.abs, tf.abs)
    self._compareBothSparse(x, np.negative, tf.neg)
    self._compareBothSparse(x, np.square, tf.square)
    self._compareBothSparse(x, np.sqrt, tf.sqrt, tol=1e-3)
    self._compareBothSparse(x, np.tanh, tf.tanh)
    self._compareBothSparse(x, np.sign, tf.sign)
    self._compareBothSparse(x, np.sign, tf.erf) 
Example 48
Project: deep_image_model   Author: tobegit3hub   File: cwise_ops_test.py    Apache License 2.0 5 votes vote down vote up
def testDoubleBasic(self):
    x = np.arange(-3, 3).reshape(1, 3, 2).astype(np.float64)
    y = (x + .5).astype(np.float64)    # no zero
    z = (x + 15.5).astype(np.float64)  # all positive
    k = np.arange(-0.90, 0.90, 0.35).reshape(1, 3, 2).astype(np.float64) # between -1 and 1
    self._compareBoth(x, np.abs, tf.abs)
    self._compareBoth(x, np.abs, _ABS)
    self._compareBoth(x, np.negative, tf.neg)
    self._compareBoth(x, np.negative, _NEG)
    self._compareBoth(y, self._inv, tf.inv)
    self._compareBoth(x, np.square, tf.square)
    self._compareBoth(z, np.sqrt, tf.sqrt)
    self._compareBoth(z, self._rsqrt, tf.rsqrt)
    self._compareBoth(x, np.exp, tf.exp)
    self._compareBoth(z, np.log, tf.log)
    self._compareBoth(z, np.log1p, tf.log1p)
    self._compareBoth(x, np.tanh, tf.tanh)
    self._compareBoth(x, self._sigmoid, tf.sigmoid)
    self._compareBoth(y, np.sign, tf.sign)
    self._compareBoth(x, np.sin, tf.sin)
    self._compareBoth(x, np.cos, tf.cos)
    self._compareBoth(
        y,
        np.vectorize(self._replace_domain_error_with_inf(math.lgamma)),
        tf.lgamma)
    self._compareBoth(x, np.vectorize(math.erf), tf.erf)
    self._compareBoth(x, np.vectorize(math.erfc), tf.erfc)
    self._compareBoth(x, np.arctan, tf.atan)
    self._compareBoth(k, np.arcsin, tf.asin)
    self._compareBoth(k, np.arccos, tf.acos)
    self._compareBoth(k, np.tan, tf.tan)

    self._compareBothSparse(x, np.abs, tf.abs)
    self._compareBothSparse(x, np.negative, tf.neg)
    self._compareBothSparse(x, np.square, tf.square)
    self._compareBothSparse(z, np.sqrt, tf.sqrt, tol=1e-3)
    self._compareBothSparse(x, np.tanh, tf.tanh)
    self._compareBothSparse(y, np.sign, tf.sign)
    self._compareBothSparse(x, np.vectorize(math.erf), tf.erf) 
Example 49
Project: deep_image_model   Author: tobegit3hub   File: cwise_ops_test.py    Apache License 2.0 5 votes vote down vote up
def testHalfBasic(self):
    x = np.arange(-3, 3).reshape(1, 3, 2).astype(np.float16)
    y = (x + .5).astype(np.float16)    # no zero
    z = (x + 15.5).astype(np.float16)  # all positive
    self._compareBoth(x, np.abs, tf.abs)
    self._compareBoth(x, np.abs, _ABS)
    self._compareBoth(x, np.negative, tf.neg)
    self._compareBoth(x, np.negative, _NEG)
    self._compareBoth(y, self._inv, tf.inv)
    self._compareBoth(x, np.square, tf.square)
    self._compareBoth(z, np.sqrt, tf.sqrt)
    self._compareBoth(z, self._rsqrt, tf.rsqrt)
    self._compareBoth(x, np.exp, tf.exp)
    self._compareBoth(z, np.log, tf.log)
    self._compareBoth(z, np.log1p, tf.log1p)
    self._compareBoth(x, np.tanh, tf.tanh)
    self._compareBoth(x, self._sigmoid, tf.sigmoid)
    self._compareBoth(y, np.sign, tf.sign)
    self._compareBoth(x, np.sin, tf.sin)
    self._compareBoth(x, np.cos, tf.cos)
    self._compareBoth(
        y,
        np.vectorize(self._replace_domain_error_with_inf(math.lgamma)),
        tf.lgamma)
    self._compareBoth(x, np.vectorize(math.erf), tf.erf)
    self._compareBoth(x, np.vectorize(math.erfc), tf.erfc)

    self._compareBothSparse(x, np.abs, tf.abs)
    self._compareBothSparse(x, np.negative, tf.neg)
    self._compareBothSparse(x, np.square, tf.square)
    self._compareBothSparse(z, np.sqrt, tf.sqrt, tol=1e-3)
    self._compareBothSparse(x, np.tanh, tf.tanh)
    self._compareBothSparse(y, np.sign, tf.sign)
    self._compareBothSparse(x, np.vectorize(math.erf), tf.erf, tol=1e-3) 
Example 50
Project: ml-privacy-csf18   Author: samuel-yeom   File: advantage.py    MIT License 5 votes vote down vote up
def theo_adv(sd): #known test error
    temp = sd * np.sqrt(np.log(sd) / (sd**2 - 1))
    return erf(temp) - erf(temp / sd) 
Example 51
Project: ml-privacy-csf18   Author: samuel-yeom   File: advantage.py    MIT License 5 votes vote down vote up
def theo_adv2(sd): #unknown test error
    return erf(0.5**0.5) - erf(0.5**0.5 / sd) 
Example 52
Project: hackerrank   Author: rene-d   File: normal-distribution-2.py    The Unlicense 5 votes vote down vote up
def phi(x, m, s):
    """ Cumulative Probability """
    return 1. / 2 * (1 + math.erf((x - m) / s / math.sqrt(2))) 
Example 53
Project: hackerrank   Author: rene-d   File: normal-distribution-1.py    The Unlicense 5 votes vote down vote up
def phi(x, m, s):
    """ Cumulative Probability """
    return 1. / 2 * (1 + math.erf((x - m) / s / math.sqrt(2))) 
Example 54
Project: hackerrank   Author: rene-d   File: normal-distribution-3.py    The Unlicense 5 votes vote down vote up
def phi(x, m, s):
        """ Cumulative Probability """
        return 1. / 2 * (1 + math.erf((x - m) / s / math.sqrt(2))) 
Example 55
Project: hackerrank   Author: rene-d   File: s10-the-central-limit-theorem-1.py    The Unlicense 5 votes vote down vote up
def Φ(x, µ, σ):
    """ Cumulative Probability """
    return 1 / 2 * (1 + math.erf((x - µ) / σ / math.sqrt(2))) 
Example 56
Project: hackerrank   Author: rene-d   File: s10-normal-distribution-2.py    The Unlicense 5 votes vote down vote up
def Φ(x, µ, σ):
    """ Cumulative Probability """
    return 1 / 2 * (1 + math.erf((x - µ) / σ / math.sqrt(2))) 
Example 57
Project: hackerrank   Author: rene-d   File: s10-the-central-limit-theorem-2.py    The Unlicense 5 votes vote down vote up
def Φ(x, µ, σ):
    """ Cumulative Probability """
    return 1 / 2 * (1 + math.erf((x - µ) / σ / math.sqrt(2))) 
Example 58
Project: HybridNaiveBayes   Author: ashkonf   File: distributions.py    MIT License 5 votes vote down vote up
def cdf(self, value):
        return 0.5 * (1.0 + math.erf((value - self.mean) / math.sqrt(2.0 * self.variance))) 
Example 59
Project: HybridNaiveBayes   Author: ashkonf   File: distributions.py    MIT License 5 votes vote down vote up
def __phi(self, value):
        return 0.5 * (1.0 + math.erf((value - self.mean) / (self.stdev * math.sqrt(2.0))))

## LogNormal ########################################################################################### 
Example 60
Project: HybridNaiveBayes   Author: ashkonf   File: distributions.py    MIT License 5 votes vote down vote up
def cdf(self, value):
        return 0.5 + 0.5 * math.erf((math.log(value) - self.mean) / math.sqrt(2.0 * self.variance)) 
Example 61
Project: titus2   Author: animator   File: link.py    Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x):
        return unwrapForNorm(x, lambda y: (math.erf(y/math.sqrt(2.)) + 1.)/2.) 
Example 62
Project: titus2   Author: animator   File: dist.py    Apache License 2.0 5 votes vote down vote up
def CDF(self, x):
        if (self.sigma == 0.0) and (x < self.mu):
            return 0.0
        elif (self.sigma == 0.0) and (x >= self.mu):
            return 1.0
        else:
            return 0.5 * (1.0 + math.erf((x - self.mu)/(self.sigma * math.sqrt(2.0)))) 
Example 63
Project: titus2   Author: animator   File: spec.py    Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, a):
        try:
            return math.erf(a)
        except:
            raise PFARuntimeException("domain error", self.errcodeBase + 0, self.name, pos) 
Example 64
Project: timely-beliefs   Author: SeitaBV   File: classes.py    MIT License 5 votes vote down vote up
def __init__(self, sensor: Sensor, source: BeliefSource, value: float, **kwargs):
        self.sensor = sensor
        self.source = source
        self.event_value = value

        if "cumulative_probability" in kwargs:
            self.cumulative_probability = kwargs["cumulative_probability"]
        elif "cp" in kwargs:
            self.cumulative_probability = kwargs["cp"]
        elif "sigma" in kwargs:
            self.cumulative_probability = (
                1 / 2 + (math.erf(kwargs["sigma"] / 2 ** 0.5)) / 2
            )
        else:
            self.cumulative_probability = 0.5
        if "event_start" in kwargs:
            self.event_start = tb_utils.enforce_utc(kwargs["event_start"])
        elif "event_time" in kwargs:
            if self.sensor.event_resolution != timedelta():
                raise KeyError(
                    "Sensor has a non-zero resolution, so it doesn't measure instantaneous events. "
                    "Use event_start instead of event_time."
                )
            self.event_start = tb_utils.enforce_utc(kwargs["event_time"])
        if "belief_horizon" in kwargs:
            self.belief_horizon = kwargs["belief_horizon"]
        elif "belief_time" in kwargs:
            belief_time = tb_utils.enforce_utc(kwargs["belief_time"])
            self.belief_horizon = (
                self.sensor.knowledge_time(self.event_start) - belief_time
            ) 
Example 65
Project: deeplearning-notes   Author: juxiangwu   File: 10-normal-cdf-inverse.py    Apache License 2.0 5 votes vote down vote up
def normal_cdf(x, mu=0,sigma=1):
    return (1 + math.erf((x - mu) / math.sqrt(2) / sigma)) / 2 
Example 66
Project: deeplearning-notes   Author: juxiangwu   File: 11-bernoulli.py    Apache License 2.0 5 votes vote down vote up
def normal_cdf(x, mu=0,sigma=1):
    return (1 + math.erf((x - mu) / math.sqrt(2) / sigma)) / 2

# 伯努利随机数 
Example 67
Project: deeplearning-notes   Author: juxiangwu   File: 12-stastic-check.py    Apache License 2.0 5 votes vote down vote up
def normal_cdf(x, mu=0,sigma=1):
    return (1 + math.erf((x - mu) / math.sqrt(2) / sigma)) / 2

# 求CDF的逆 
Example 68
Project: deeplearning-notes   Author: juxiangwu   File: 09-normal-cdf.py    Apache License 2.0 5 votes vote down vote up
def normal_cdf(x, mu=0,sigma=1):
    return (1 + math.erf((x - mu) / math.sqrt(2) / sigma)) / 2 
Example 69
Project: PyFlow   Author: wonderworks-software   File: MathLib.py    Apache License 2.0 5 votes vote down vote up
def erf(x=('FloatPin', 0.0)):
        '''Return the error function at `x`.'''
        return math.erf(x) 
Example 70
Project: Emergence   Author: LennonLab   File: metrics.py    MIT License 5 votes vote down vote up
def Preston(sad):

    sad = filter(lambda a: a != 0, sad)

    x = sum(1 for n in sad if n < 0)
    if x >= 1:
        return float('NaN')

    N = sum(sad)

    if N <= 0:
        return float('NaN')

    Nmax = max(sad)

    left = (2 * N)/(np.sqrt(np.pi) * Nmax)

    func = lambda a : left - (math.erf(np.log(2)/a) / a)

    guess = 0.1 # alpha is often ~0.2, but appears to be lower for larger N
    a = fsolve(func, guess)

    expS = (np.sqrt(np.pi) / a) * np.exp( (np.log(2)/(2*a))**2 )

    return a[0], expS[0]



############### DOMINANCE ###################################################### 
Example 71
Project: Emergence   Author: LennonLab   File: SAD-Models.py    MIT License 5 votes vote down vote up
def alpha(self, a, Nmax, Nmin=1):

        """Numerically solve for Preston's a. Needed to estimate S using the lognormal"""

        y = sqrt(pi*Nmin*Nmax)/(2.0*a) * exp((a * log2(sqrt(Nmax/Nmin)))**2.0)
        y = y * exp((log(2.0)/(2.0*a))**2.0)
        y = y * erf(a * log2(sqrt(Nmax/Nmin)) - log(2.0)/(2.0*a))
        y += erf(a * log2(sqrt(Nmax/Nmin)) + log(2.0)/(2.0*a))
        y -= self.N

        return y # find alpha 
Example 72
Project: Machine-Learning-with-Python   Author: devAmoghS   File: probabilty.py    MIT License 5 votes vote down vote up
def normal_cdf(x, mu=0, sigma=1.0):
    return (1 + math.erf((x - mu) / math.sqrt(2) / sigma)) / 2 
Example 73
Project: m-stp   Author: MukeunKim   File: core.py    MIT License 5 votes vote down vote up
def erf(x):
    if isinstance(x, LineValue): lx = x.get_value()
    else: lx = x
    if lx == NAN: return LineValue(NAN)
    return LineValue(math.erf(lx)) 
Example 74
Project: SignLanguage_ML   Author: mareep-raljodid   File: util.py    MIT License 5 votes vote down vote up
def normal_cdf(x):
  """Cumulative distribution function for a standard normal distribution."""
  return 0.5 + 0.5 * np.vectorize(math.erf)(x / math.sqrt(2)) 
Example 75
Project: cms   Author: broadinstitute   File: stats.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def gammainc_halfint(s, x) :
    """ Lower incomplete gamma function = 
            integral from 0 to x of t ** (s-1) exp(-t) dt divided by gamma(s),
        i.e., the fraction of gamma that you get if you integrate only until
            x instead of all the way to infinity.
        Implemented here only if s is a positive multiple of 0.5.
    """
    # scipy equivalent: scipy.special.gammainc(s,x)
    
    if s <= 0 :
        raise ValueError('%s is not positive' % s)
    if x < 0 :
        raise ValueError('%s < 0' % x)
    if s * 2 != int(s * 2) :
        raise NotImplementedError('%s is not a multiple of 0.5' % s)
    
    # Handle integers analytically
    if s == int(s) :
        term = 1
        total = 1
        for k in range(1, int(s)) :
            term *= x /  k
            total += term
        return 1 - exp(-x) * total

    # Otherwise s is integer + 0.5. Decrease to 0.5 using recursion formula:
    result = 0.0
    while s > 1 :
        result -= x ** (s - 1) * exp(-x) / gamma(s)
        s = s - 1
    # Then use gammainc(0.5, x) = erf(sqrt(x))
    result += erf(sqrt(x))
    return result 
Example 76
Project: ironpython2   Author: IronLanguages   File: test_math.py    Apache License 2.0 4 votes vote down vote up
def test_erf(self):
        table = [
            (0.0,  0.0000000),
            (0.05, 0.0563720),
            (0.1,  0.1124629),
            (0.15, 0.1679960),
            (0.2,  0.2227026),
            (0.25, 0.2763264),
            (0.3,  0.3286268),
            (0.35, 0.3793821),
            (0.4,  0.4283924),
            (0.45, 0.4754817),
            (0.5,  0.5204999),
            (0.55, 0.5633234),
            (0.6,  0.6038561),
            (0.65, 0.6420293),
            (0.7,  0.6778012),
            (0.75, 0.7111556),
            (0.8,  0.7421010),
            (0.85, 0.7706681),
            (0.9,  0.7969082),
            (0.95, 0.8208908),
            (1.0,  0.8427008),
            (1.1,  0.8802051),
            (1.2,  0.9103140),
            (1.3,  0.9340079),
            (1.4,  0.9522851),
            (1.5,  0.9661051),
            (1.6,  0.9763484),
            (1.7,  0.9837905),
            (1.8,  0.9890905),
            (1.9,  0.9927904),
            (2.0,  0.9953223),
            (2.1,  0.9970205),
            (2.2,  0.9981372),
            (2.3,  0.9988568),
            (2.4,  0.9993115),
            (2.5,  0.9995930),
            (2.6,  0.9997640),
            (2.7,  0.9998657),
            (2.8,  0.9999250),
            (2.9,  0.9999589),
            (3.0,  0.9999779),
            (3.1,  0.9999884),
            (3.2,  0.9999940),
            (3.3,  0.9999969),
            (3.4,  0.9999985),
            (3.5,  0.9999993),
            (4.0,  1.0000000),
        ]

        for x, y in table:
            self.assertAlmostEqual(y, math.erf(x), places=7)
            self.assertAlmostEqual(-y, math.erf(-x), places=7) 
Example 77
Project: data_algebra   Author: WinVector   File: SQLite.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def prepare_connection(self, conn):
        # https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.create_function
        conn.create_function("is_bad", 1, _check_scalar_bad)
        # math fns
        conn.create_function("acos", 1, math.acos)
        conn.create_function("acosh", 1, math.acosh)
        conn.create_function("asin", 1, math.asin)
        conn.create_function("asinh", 1, math.asinh)
        conn.create_function("atan", 1, math.atan)
        conn.create_function("atanh", 1, math.atanh)
        conn.create_function("ceil", 1, math.ceil)
        conn.create_function("cos", 1, math.cos)
        conn.create_function("cosh", 1, math.cosh)
        conn.create_function("degrees", 1, math.degrees)
        conn.create_function("erf", 1, math.erf)
        conn.create_function("erfc", 1, math.erfc)
        conn.create_function("exp", 1, math.exp)
        conn.create_function("expm1", 1, math.expm1)
        conn.create_function("fabs", 1, math.fabs)
        conn.create_function("factorial", 1, math.factorial)
        conn.create_function("floor", 1, math.floor)
        conn.create_function("frexp", 1, math.frexp)
        conn.create_function("gamma", 1, math.gamma)
        conn.create_function("isfinite", 1, math.isfinite)
        conn.create_function("isinf", 1, math.isinf)
        conn.create_function("isnan", 1, math.isnan)
        conn.create_function("lgamma", 1, math.lgamma)
        conn.create_function("log", 1, math.log)
        conn.create_function("log10", 1, math.log10)
        conn.create_function("log1p", 1, math.log1p)
        conn.create_function("log2", 1, math.log2)
        conn.create_function("modf", 1, math.modf)
        conn.create_function("radians", 1, math.radians)
        conn.create_function("sin", 1, math.sin)
        conn.create_function("sinh", 1, math.sinh)
        conn.create_function("sqrt", 1, math.sqrt)
        conn.create_function("tan", 1, math.tan)
        conn.create_function("tanh", 1, math.tanh)
        conn.create_function("trunc", 1, math.trunc)
        conn.create_function("atan2", 2, math.atan2)
        conn.create_function("copysign", 2, math.copysign)
        conn.create_function("fmod", 2, math.fmod)
        conn.create_function("gcd", 2, math.gcd)
        conn.create_function("hypot", 2, math.hypot)
        conn.create_function("isclose", 2, math.isclose)
        conn.create_function("ldexp", 2, math.ldexp)
        conn.create_function("pow", 2, math.pow) 
Example 78
Project: data_algebra   Author: WinVector   File: SQLite.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def prepare_connection(self, conn):
        # https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.create_function
        conn.create_function("is_bad", 1, _check_scalar_bad)
        # math fns
        conn.create_function("acos", 1, math.acos)
        conn.create_function("acosh", 1, math.acosh)
        conn.create_function("asin", 1, math.asin)
        conn.create_function("asinh", 1, math.asinh)
        conn.create_function("atan", 1, math.atan)
        conn.create_function("atanh", 1, math.atanh)
        conn.create_function("ceil", 1, math.ceil)
        conn.create_function("cos", 1, math.cos)
        conn.create_function("cosh", 1, math.cosh)
        conn.create_function("degrees", 1, math.degrees)
        conn.create_function("erf", 1, math.erf)
        conn.create_function("erfc", 1, math.erfc)
        conn.create_function("exp", 1, math.exp)
        conn.create_function("expm1", 1, math.expm1)
        conn.create_function("fabs", 1, math.fabs)
        conn.create_function("factorial", 1, math.factorial)
        conn.create_function("floor", 1, math.floor)
        conn.create_function("frexp", 1, math.frexp)
        conn.create_function("gamma", 1, math.gamma)
        conn.create_function("isfinite", 1, math.isfinite)
        conn.create_function("isinf", 1, math.isinf)
        conn.create_function("isnan", 1, math.isnan)
        conn.create_function("lgamma", 1, math.lgamma)
        conn.create_function("log", 1, math.log)
        conn.create_function("log10", 1, math.log10)
        conn.create_function("log1p", 1, math.log1p)
        conn.create_function("log2", 1, math.log2)
        conn.create_function("modf", 1, math.modf)
        conn.create_function("radians", 1, math.radians)
        conn.create_function("sin", 1, math.sin)
        conn.create_function("sinh", 1, math.sinh)
        conn.create_function("sqrt", 1, math.sqrt)
        conn.create_function("tan", 1, math.tan)
        conn.create_function("tanh", 1, math.tanh)
        conn.create_function("trunc", 1, math.trunc)
        conn.create_function("atan2", 2, math.atan2)
        conn.create_function("copysign", 2, math.copysign)
        conn.create_function("fmod", 2, math.fmod)
        conn.create_function("gcd", 2, math.gcd)
        conn.create_function("hypot", 2, math.hypot)
        conn.create_function("isclose", 2, math.isclose)
        conn.create_function("ldexp", 2, math.ldexp)
        conn.create_function("pow", 2, math.pow) 
Example 79
Project: PyErf   Author: dougthor42   File: pyerf.py    GNU General Public License v3.0 4 votes vote down vote up
def erfinv(z):
    """
    Calculate the inverse error function at point ``z``.

    This is a direct port of the SciPy ``erfinv`` function, originally
    written in C.

    Parameters
    ----------
    z : numeric

    Returns
    -------
    float

    References
    ----------
    + https://en.wikipedia.org/wiki/Error_function#Inverse_functions
    + http://functions.wolfram.com/GammaBetaErf/InverseErf/

    Examples
    --------
    >>> round(erfinv(0.1), 12)
    0.088855990494
    >>> round(erfinv(0.5), 12)
    0.476936276204
    >>> round(erfinv(-0.5), 12)
    -0.476936276204
    >>> round(erfinv(0.95), 12)
    1.38590382435
    >>> round(erf(erfinv(0.3)), 3)
    0.3
    >>> round(erfinv(erf(0.5)), 3)
    0.5
    >>> erfinv(0)
    0
    >>> erfinv(1)
    inf
    >>> erfinv(-1)
    -inf
    """
    if abs(z) > 1:
        raise ValueError("`z` must be between -1 and 1 inclusive")

    # Shortcut special cases
    if z == 0:
        return 0
    if z == 1:
        return inf
    if z == -1:
        return -inf

    # otherwise calculate things.
    return _ndtri((z + 1) / 2.0) / math.sqrt(2)


# bring the built-ins into this namespace for conveinence. 
Example 80
Project: va   Author: lnls-fac   File: injection.py    GNU General Public License v3.0 4 votes vote down vote up
def calc_charge_loss_fraction_in_line(accelerator, **kwargs):
    """Calculate charge loss in a line

    Keyword arguments:
    twiss_at_entrance -- Twiss parameters at the start of first element
    global_coupling   -- Global coupling
    energy_spread     -- Relative energy spread
    emittance         -- [m·rad]
    delta_rx          -- [m]
    delta_angle       -- [rad]
    hmax              -- [m]
    hmin              -- [m]
    vmax              -- [m]
    vmin              -- [m]
    """
    init_twiss, energy_spread, emittance, hmax, hmin, vmax, vmin = _process_loss_fraction_args(accelerator, **kwargs)
    coupling = kwargs['global_coupling']

    try:
        twiss, m66 = pyaccel.optics.calc_twiss(accelerator, init_twiss = init_twiss, indices ='open')
        betax, etax, betay, etay = twiss.betax, twiss.etax, twiss.betay, twiss.etay
        if math.isnan(betax[-1]):
            loss_fraction = 1.0
            return (loss_fraction, None, None)
    except (numpy.linalg.linalg.LinAlgError, pyaccel.optics.OpticsException, pyaccel.tracking.TrackingException):
        loss_fraction = 1.0
        return (loss_fraction, None, None)

    emitx = emittance * 1 / (1 + coupling)
    emity = emittance * coupling / (1 + coupling)
    sigmax = numpy.sqrt(betax * emitx + (etax * energy_spread)**2)
    sigmay = numpy.sqrt(betay * emity + (etax * energy_spread)**2)
    h_vc = hmax - hmin
    v_vc = vmax - vmin
    co = twiss.co
    rx, ry = co[0,:], co[2,:]
    xlim_inf, xlim_sup = rx - hmin, hmax - rx
    ylim_inf, ylim_sup = ry - vmin, vmax - ry
    xlim_inf[xlim_inf < 0] = 0
    xlim_sup[xlim_sup < 0] = 0
    ylim_inf[ylim_inf < 0] = 0
    ylim_sup[ylim_sup < 0] = 0
    xlim_inf[xlim_inf > h_vc] = 0
    xlim_sup[xlim_sup > h_vc] = 0
    ylim_inf[ylim_inf > v_vc] = 0
    ylim_sup[ylim_sup > v_vc] = 0
    min_xfrac_inf = numpy.amin(xlim_inf/sigmax)
    min_xfrac_sup = numpy.amin(xlim_sup/sigmax)
    min_yfrac_inf = numpy.amin(ylim_inf/sigmay)
    min_yfrac_sup = numpy.amin(ylim_sup/sigmay)
    sqrt2 = math.sqrt(2)

    x_surviving_fraction = 0.5*math.erf(min_xfrac_inf/sqrt2) + \
                           0.5*math.erf(min_xfrac_sup/sqrt2)
    y_surviving_fraction = 0.5*math.erf(min_yfrac_inf/sqrt2) + \
                           0.5*math.erf(min_yfrac_sup/sqrt2)
    surviving_fraction = x_surviving_fraction * y_surviving_fraction
    loss_fraction = 1.0 - surviving_fraction
    return loss_fraction, twiss, m66