Python math.erfc() Examples

The following are 30 code examples of math.erfc(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module math , or try the search function .
Example #1
Source File: test_kl.py    From bayeslite with Apache License 2.0 6 votes vote down vote up
def compute_kullback_leibler_check_statistic(n=100, prngstate=None):
    """Compute the lowest of the survival function and the CDF of the exact KL
    divergence KL(N(mu1,s1)||N(mu2,s2)) w.r.t. the sample distribution of the
    KL divergence drawn by computing log(P(x|N(mu1,s1)))-log(P(x|N(mu2,s2)))
    over a sample x~N(mu1,s1). If we are computing the KL divergence
    accurately, the exact value should fall squarely in the sample, and the
    tail probabilities should be relatively large.

    """
    if prngstate is None:
        raise TypeError('Must explicitly specify numpy.random.RandomState')
    mu1 = mu2 = 0
    s1 = 1
    s2 = 2
    exact = gaussian_kl_divergence(mu1, s1, mu2, s2)
    sample = prngstate.normal(mu1, s1, n)
    lpdf1 = gaussian_log_pdf(mu1, s1)
    lpdf2 = gaussian_log_pdf(mu2, s2)
    estimate, std = kl.kullback_leibler(sample, lpdf1, lpdf2)
    # This computes the minimum of the left and right tail probabilities of the
    # exact KL divergence vs a gaussian fit to the sample estimate. There is a
    # distinct negative skew to the samples used to compute `estimate`, so this
    # statistic is not uniform. Nonetheless, we do not expect it to get too
    # small.
    return erfc(abs(exact - estimate) / std) / 2 
Example #2
Source File: density.py    From autogluon with Apache License 2.0 6 votes vote down vote up
def get_quantiles(acquisition_par, fmin, m, s):
    '''
    Quantiles of the Gaussian distribution useful to determine the acquisition function values
    :param acquisition_par: parameter of the acquisition function
    :param fmin: current minimum.
    :param m: vector of means.
    :param s: vector of standard deviations.
    '''
    if isinstance(s, np.ndarray):
        s[s<1e-10] = 1e-10
    elif s< 1e-10:
        s = 1e-10
    u = (fmin - m - acquisition_par)/s

    phi = np.exp(-0.5 * u**2) / np.sqrt(2*np.pi)
    # vectorized version of erfc to not depend on scipy
    Phi = 0.5 * erfc(-u / np.sqrt(2))
    return (phi, Phi, u) 
Example #3
Source File: sp800_22_runs_test.py    From sp800_22_tests with GNU General Public License v2.0 6 votes vote down vote up
def runs_test(bits):
    n = len(bits)
    zeroes,ones = count_ones_zeroes(bits)

    prop = float(ones)/float(n)
    print("  prop ",prop)

    tau = 2.0/math.sqrt(n)
    print("  tau ",tau)

    if abs(prop-0.5) > tau:
        return (False,0.0,None)

    vobs = 1.0
    for i in range(n-1):
        if bits[i] != bits[i+1]:
            vobs += 1.0

    print("  vobs ",vobs)
      
    p = math.erfc(abs(vobs - (2.0*n*prop*(1.0-prop)))/(2.0*math.sqrt(2.0*n)*prop*(1-prop) ))
    success = (p >= 0.01)
    return (success,p,None) 
Example #4
Source File: stats.py    From python_moztelemetry with Mozilla Public License 2.0 6 votes vote down vote up
def ndtr(a):
    """
    Returns the area under the Gaussian probability density function,
    integrated from minus infinity to x.

    See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.ndtr.html#scipy.special.ndtr

    """
    sqrth = math.sqrt(2) / 2
    x = float(a) * sqrth
    z = abs(x)
    if z < sqrth:
        y = 0.5 + 0.5 * math.erf(x)
    else:
        y = 0.5 * math.erfc(z)
        if x > 0:
            y = 1 - y
    return y 
Example #5
Source File: pure_math.py    From ufora with Apache License 2.0 5 votes vote down vote up
def __call__(self, val):
        return __inline_fora(
            """fun(@unnamed_args:(val), *args) {
                   PyFloat(math.erfc(val.@m))
                   }"""
            )(val) 
Example #6
Source File: spec.py    From hadrian with Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, a):
        try:
            return math.erfc(a)
        except:
            raise PFARuntimeException("domain error", self.errcodeBase + 0, self.name, pos) 
Example #7
Source File: stats.py    From Turing with MIT License 5 votes vote down vote up
def d_normal_std_cdf(x):
    return 1 - 0.5 * erfc(x / math.sqrt(2)) 
Example #8
Source File: stats.py    From Turing with MIT License 5 votes vote down vote up
def erfc(x):
    return math.erfc(x) 
Example #9
Source File: MathLib.py    From PyFlow with Apache License 2.0 5 votes vote down vote up
def erfc(x=('FloatPin', 0.0)):
        '''Return the complementary error function at `x`.'''
        return math.erfc(x) 
Example #10
Source File: test_math.py    From ironpython3 with 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 #11
Source File: cwise_ops_test.py    From deep_image_model with 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 #12
Source File: cwise_ops_test.py    From deep_image_model with 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 #13
Source File: cwise_ops_test.py    From deep_image_model with 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 #14
Source File: cwise_ops_test.py    From deep_image_model with 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 #15
Source File: utils.py    From choix with MIT License 5 votes vote down vote up
def normal_cdf(x):
    """Normal cumulative density function."""
    # If X ~ N(0,1), returns P(X < x).
    return math.erfc(-x / SQRT2) / 2.0 
Example #16
Source File: sp800_22_monobit_test.py    From sp800_22_tests with GNU General Public License v2.0 5 votes vote down vote up
def monobit_test(bits):
    n = len(bits)
    
    zeroes,ones = count_ones_zeroes(bits)
    s = abs(ones-zeroes)
    print("  Ones count   = %d" % ones)
    print("  Zeroes count = %d" % zeroes)
    
    p = math.erfc(float(s)/(math.sqrt(float(n)) * math.sqrt(2.0)))
    
    success = (p >= 0.01)
    return (success,p,None) 
Example #17
Source File: sp800_22_dft_test.py    From sp800_22_tests with GNU General Public License v2.0 5 votes vote down vote up
def dft_test(bits):
    n = len(bits)
    if (n % 2) == 1:        # Make it an even number
        bits = bits[:-1]

    ts = list()             # Convert to +1,-1
    for bit in bits:
        ts.append((bit*2)-1)

    ts_np = numpy.array(ts)
    fs = numpy.fft.fft(ts_np)  # Compute DFT
   
    if sys.version_info > (3,0):
        mags = abs(fs)[:n//2] # Compute magnitudes of first half of sequence
    else:
        mags = abs(fs)[:n/2] # Compute magnitudes of first half of sequence
    
    T = math.sqrt(math.log(1.0/0.05)*n) # Compute upper threshold
    N0 = 0.95*n/2.0
    print("  N0 = %f" % N0)

    N1 = 0.0   # Count the peaks above the upper theshold
    for mag in mags:
        if mag < T:
            N1 += 1.0
    print("  N1 = %f" % N1)
    d = (N1 - N0)/math.sqrt((n*0.95*0.05)/4) # Compute the P value
    p = math.erfc(abs(d)/math.sqrt(2))

    success = (p >= 0.01)
    return (success,p,None) 
Example #18
Source File: sp800_22_cumulative_sums_test.py    From sp800_22_tests with GNU General Public License v2.0 5 votes vote down vote up
def normcdf(n):
    return 0.5 * math.erfc(-n * math.sqrt(0.5)) 
Example #19
Source File: erfc.py    From chainer with MIT License 5 votes vote down vote up
def erfc(x):
    """Elementwise complementary 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 Erfc().apply((x,))[0] 
Example #20
Source File: erfc.py    From chainer with MIT License 5 votes vote down vote up
def forward_cpu(self, x):
        global _erfc_cpu
        if _erfc_cpu is None:
            try:
                from scipy import special
                _erfc_cpu = special.erfc
            except ImportError:
                warnings.warn(
                    'SciPy is not available. Forward computation of erfc in'
                    ' CPU can be slow without SciPy.',
                    chainer.warnings.PerformanceWarning)
                _erfc_cpu = numpy.vectorize(math.erfc)
        self.retain_inputs((0,))
        return utils.force_array(_erfc_cpu(x[0]), dtype=x[0].dtype), 
Example #21
Source File: erfc.py    From chainer with MIT License 5 votes vote down vote up
def label(self):
        return 'erfc' 
Example #22
Source File: ndtr.py    From chainer with MIT License 5 votes vote down vote up
def _slow_ndtr_cpu(x):
    return 0.5 * math.erfc(-x / 2 ** 0.5) 
Example #23
Source File: test_ndtr.py    From chainer with MIT License 5 votes vote down vote up
def _ndtr_cpu(x, dtype):
    erfc = numpy.vectorize(
        lambda x: 0.5 * math.erfc(-x / 2 ** 0.5))
    return utils.force_array(erfc(x), dtype=dtype) 
Example #24
Source File: test_erfc.py    From chainer with MIT License 5 votes vote down vote up
def _erfc_cpu(x, dtype):
    return numpy.vectorize(math.erfc, otypes=[dtype])(x) 
Example #25
Source File: MathTestCases.py    From ufora with 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 #26
Source File: test_math.py    From ironpython2 with 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 #27
Source File: test_math.py    From ironpython2 with Apache License 2.0 4 votes vote down vote up
def test_erfc(self):
        table = [
            (0.0,  1.0000000),
            (0.05, 0.9436280),
            (0.1,  0.8875371),
            (0.15, 0.8320040),
            (0.2,  0.7772974),
            (0.25, 0.7236736),
            (0.3,  0.6713732),
            (0.35, 0.6206179),
            (0.4,  0.5716076),
            (0.45, 0.5245183),
            (0.5,  0.4795001),
            (0.55, 0.4366766),
            (0.6,  0.3961439),
            (0.65, 0.3579707),
            (0.7,  0.3221988),
            (0.75, 0.2888444),
            (0.8,  0.2578990),
            (0.85, 0.2293319),
            (0.9,  0.2030918),
            (0.95, 0.1791092),
            (1.0,  0.1572992),
            (1.1,  0.1197949),
            (1.2,  0.0896860),
            (1.3,  0.0659921),
            (1.4,  0.0477149),
            (1.5,  0.0338949),
            (1.6,  0.0236516),
            (1.7,  0.0162095),
            (1.8,  0.0109095),
            (1.9,  0.0072096),
            (2.0,  0.0046777),
            (2.1,  0.0029795),
            (2.2,  0.0018628),
            (2.3,  0.0011432),
            (2.4,  0.0006885),
            (2.5,  0.0004070),
            (2.6,  0.0002360),
            (2.7,  0.0001343),
            (2.8,  0.0000750),
            (2.9,  0.0000411),
            (3.0,  0.0000221),
            (3.1,  0.0000116),
            (3.2,  0.0000060),
            (3.3,  0.0000031),
            (3.4,  0.0000015),
            (3.5,  0.0000007),
            (4.0,  0.0000000),
        ]

        for x, y in table:
            self.assertAlmostEqual(y, math.erfc(x), places=7)
            self.assertAlmostEqual(2.0 - y, math.erfc(-x), places=7) 
Example #28
Source File: sp800_22_random_excursion_variant_test.py    From sp800_22_tests with GNU General Public License v2.0 4 votes vote down vote up
def random_excursion_variant_test(bits):
    n = len(bits)

    x = list()             # Convert to +1,-1
    for bit in bits:
        x.append((bit * 2)-1)

    # Build the partial sums
    pos = 0
    s = list()
    for e in x:
        pos = pos+e
        s.append(pos)    
    sprime = [0]+s+[0] # Add 0 on each end

    # Count the number of cycles J
    J = 0
    for value in sprime[1:]:
        if value == 0:
            J += 1
    print("J=",J)
    # Build the counts of offsets
    count = [0 for x in range(-9,10)]
    for value in sprime:
        if (abs(value) < 10):
            count[value] += 1

    # Compute P values
    success = True
    plist = list()
    for x in range(-9,10):
        if x != 0:
            top = abs(count[x]-J)
            bottom = math.sqrt(2.0 * J *((4.0*abs(x))-2.0))
            p = math.erfc(top/bottom)
            plist.append(p)
            if p < 0.01:
                err = " Not Random"
                success = False
            else:
                err = ""
            print("x = %1.0f\t count=%d\tp = %f %s"  % (x,count[x],p,err))
            
    if (J < 500):
        print("J too small (J=%d < 500) for result to be reliable" % J)
    elif success:
        print("PASS")
    else:    
        print("FAIL: Data not random")
    return (success,None,plist) 
Example #29
Source File: test_math.py    From ironpython3 with Apache License 2.0 4 votes vote down vote up
def test_erfc(self):
        table = [
            (0.0,  1.0000000),
            (0.05, 0.9436280),
            (0.1,  0.8875371),
            (0.15, 0.8320040),
            (0.2,  0.7772974),
            (0.25, 0.7236736),
            (0.3,  0.6713732),
            (0.35, 0.6206179),
            (0.4,  0.5716076),
            (0.45, 0.5245183),
            (0.5,  0.4795001),
            (0.55, 0.4366766),
            (0.6,  0.3961439),
            (0.65, 0.3579707),
            (0.7,  0.3221988),
            (0.75, 0.2888444),
            (0.8,  0.2578990),
            (0.85, 0.2293319),
            (0.9,  0.2030918),
            (0.95, 0.1791092),
            (1.0,  0.1572992),
            (1.1,  0.1197949),
            (1.2,  0.0896860),
            (1.3,  0.0659921),
            (1.4,  0.0477149),
            (1.5,  0.0338949),
            (1.6,  0.0236516),
            (1.7,  0.0162095),
            (1.8,  0.0109095),
            (1.9,  0.0072096),
            (2.0,  0.0046777),
            (2.1,  0.0029795),
            (2.2,  0.0018628),
            (2.3,  0.0011432),
            (2.4,  0.0006885),
            (2.5,  0.0004070),
            (2.6,  0.0002360),
            (2.7,  0.0001343),
            (2.8,  0.0000750),
            (2.9,  0.0000411),
            (3.0,  0.0000221),
            (3.1,  0.0000116),
            (3.2,  0.0000060),
            (3.3,  0.0000031),
            (3.4,  0.0000015),
            (3.5,  0.0000007),
            (4.0,  0.0000000),
        ]

        for x, y in table:
            self.assertAlmostEqual(y, math.erfc(x), places=7)
            self.assertAlmostEqual(2.0 - y, math.erfc(-x), places=7) 
Example #30
Source File: radar.py    From Stone-Soup with MIT License 4 votes vote down vote up
def gen_probability(self, sky_state):
        """Generates probability of detection of a given State.

        Parameters
        ----------
        sky_state : The target state.

        Returns
        -------
        det_prob : `float`
            Probability of detection.
        snr : `float`
            Signal to noise ratio.
        rcs : `float`
            RCS after the Swerling 1 case is applied.
        directed_power : `float`
            Power in the direction of the target.
        spoiled_gain : `float`
            Gain in decibels with beam spoiling applied.
        spoiled_width : `float`
            Beam width with beam spoiling applied.
        """
        if getattr(sky_state, 'rcs', None) is not None:
            # use state's rcs if it has one
            rcs = sky_state.rcs
        else:
            rcs = self.rcs
        # apply swerling 1 case?
        if self.swerling_on:
            rcs = self._swerling_1(rcs)

        # e-scan beam steer
        [beam_az, beam_el] = self.beam_transition_model.move_beam(
            sky_state.timestamp)  # [az,el]

        # effects of e-scan on gain and beam width
        spoiled_gain = 10 ** (self.antenna_gain / 10) * np.cos(beam_az) * np.cos(beam_el)
        spoiled_width = self.beam_width / (np.cos(beam_az) * np.cos(beam_el))
        # state relative to radar (in cartesian space)

        relative_vector = sky_state.state_vector[self.position_mapping, :] - self.position

        relative_vector = self._rotation_matrix @ relative_vector

        # calculate target position in spherical coordinates
        [r, pos_az, pos_el] = cart2sphere(*relative_vector)

        # target position relative to beam position
        relative_az = pos_az - beam_az
        relative_el = pos_el - beam_el
        # calculate power directed towards target
        self.beam_shape.beam_width = spoiled_width  # beam spoiling to width
        directed_power = self.beam_shape.beam_power(relative_az, relative_el)
        # calculate signal to noise ratio
        snr = self._snr_constant * rcs * spoiled_gain ** 2 * directed_power / (r ** 4)
        # calculate probability of detection using the North's approximation
        det_prob = 0.5 * erfc(
            (-np.log(self.probability_false_alarm)) ** 0.5 - (
                    snr + 1 / 2) ** 0.5)
        return det_prob, snr, rcs, directed_power,\
            10 * np.log10(spoiled_gain), spoiled_width