Ejemplo n.º 1
0
def test_areal_inverses():
    assert asin(mpf(0)) == 0
    assert asinh(mpf(0)) == 0
    assert acosh(mpf(1)) == 0
    assert isinstance(asin(mpf(0.5)), mpf)
    assert isinstance(asin(mpf(2.0)), mpc)
    assert isinstance(acos(mpf(0.5)), mpf)
    assert isinstance(acos(mpf(2.0)), mpc)
    assert isinstance(atanh(mpf(0.1)), mpf)
    assert isinstance(atanh(mpf(1.1)), mpc)

    random.seed(1)
    for i in range(50):
        x = random.uniform(0, 1)
        assert asin(mpf(x)).ae(math.asin(x))
        assert acos(mpf(x)).ae(math.acos(x))

        x = random.uniform(-10, 10)
        assert asinh(mpf(x)).ae(cmath.asinh(x).real)
        assert isinstance(asinh(mpf(x)), mpf)
        x = random.uniform(1, 10)
        assert acosh(mpf(x)).ae(cmath.acosh(x).real)
        assert isinstance(acosh(mpf(x)), mpf)
        x = random.uniform(-10, 0.999)
        assert isinstance(acosh(mpf(x)), mpc)

        x = random.uniform(-1, 1)
        assert atanh(mpf(x)).ae(cmath.atanh(x).real)
        assert isinstance(atanh(mpf(x)), mpf)
Ejemplo n.º 2
0
def test_complex_inverse_functions():
    mp.dps = 15
    iv.dps = 15
    for (z1, z2) in random_complexes(30):
        # apparently cmath uses a different branch, so we
        # can't use it for comparison
        assert sinh(asinh(z1)).ae(z1)
        #
        assert acosh(z1).ae(cmath.acosh(z1))
        assert atanh(z1).ae(cmath.atanh(z1))
        assert atan(z1).ae(cmath.atan(z1))
        # the reason we set a big eps here is that the cmath
        # functions are inaccurate
        assert asin(z1).ae(cmath.asin(z1), rel_eps=1e-12)
        assert acos(z1).ae(cmath.acos(z1), rel_eps=1e-12)
        one = mpf(1)
    for i in range(-9, 10, 3):
        for k in range(-9, 10, 3):
            a = 0.9*j*10**k + 0.8*one*10**i
            b = cos(acos(a))
            assert b.ae(a)
            b = sin(asin(a))
            assert b.ae(a)
    one = mpf(1)
    err = 2*10**-15
    for i in range(-9, 9, 3):
        for k in range(-9, 9, 3):
            a = -0.9*10**k + j*0.8*one*10**i
            b = cosh(acosh(a))
            assert b.ae(a, err)
            b = sinh(asinh(a))
            assert b.ae(a, err)
Ejemplo n.º 3
0
def test_complex_inverse_functions():
    mp.dps = 15
    iv.dps = 15
    for (z1, z2) in random_complexes(30):
        # apparently cmath uses a different branch, so we
        # can't use it for comparison
        assert sinh(asinh(z1)).ae(z1)
        #
        assert acosh(z1).ae(cmath.acosh(z1))
        assert atanh(z1).ae(cmath.atanh(z1))
        assert atan(z1).ae(cmath.atan(z1))
        # the reason we set a big eps here is that the cmath
        # functions are inaccurate
        assert asin(z1).ae(cmath.asin(z1), rel_eps=1e-12)
        assert acos(z1).ae(cmath.acos(z1), rel_eps=1e-12)
        one = mpf(1)
    for i in range(-9, 10, 3):
        for k in range(-9, 10, 3):
            a = 0.9 * j * 10**k + 0.8 * one * 10**i
            b = cos(acos(a))
            assert b.ae(a)
            b = sin(asin(a))
            assert b.ae(a)
    one = mpf(1)
    err = 2 * 10**-15
    for i in range(-9, 9, 3):
        for k in range(-9, 9, 3):
            a = -0.9 * 10**k + j * 0.8 * one * 10**i
            b = cosh(acosh(a))
            assert b.ae(a, err)
            b = sinh(asinh(a))
            assert b.ae(a, err)
Ejemplo n.º 4
0
def test_areal_inverses():
    assert asin(mpf(0)) == 0
    assert asinh(mpf(0)) == 0
    assert acosh(mpf(1)) == 0
    assert isinstance(asin(mpf(0.5)), mpf)
    assert isinstance(asin(mpf(2.0)), mpc)
    assert isinstance(acos(mpf(0.5)), mpf)
    assert isinstance(acos(mpf(2.0)), mpc)
    assert isinstance(atanh(mpf(0.1)), mpf)
    assert isinstance(atanh(mpf(1.1)), mpc)

    random.seed(1)
    for i in range(50):
        x = random.uniform(0, 1)
        assert asin(mpf(x)).ae(math.asin(x))
        assert acos(mpf(x)).ae(math.acos(x))

        x = random.uniform(-10, 10)
        assert asinh(mpf(x)).ae(cmath.asinh(x).real)
        assert isinstance(asinh(mpf(x)), mpf)
        x = random.uniform(1, 10)
        assert acosh(mpf(x)).ae(cmath.acosh(x).real)
        assert isinstance(acosh(mpf(x)), mpf)
        x = random.uniform(-10, 0.999)
        assert isinstance(acosh(mpf(x)), mpc)

        x = random.uniform(-1, 1)
        assert atanh(mpf(x)).ae(cmath.atanh(x).real)
        assert isinstance(atanh(mpf(x)), mpf)
Ejemplo n.º 5
0
def test11_hyp():
    for i in range(-5, 5):
        for j in range(-5, 5):
            a = ek.sinh(C(i, j))
            b = C(cmath.sinh(complex(i, j)))
            assert ek.allclose(a, b)

            a = ek.cosh(C(i, j))
            b = C(cmath.cosh(complex(i, j)))
            assert ek.allclose(a, b)

            sa, ca = ek.sincosh(C(i, j))
            sb = C(cmath.sinh(complex(i, j)))
            cb = C(cmath.cosh(complex(i, j)))
            assert ek.allclose(sa, sb)
            assert ek.allclose(ca, cb)

            # Python appears to handle the branch cuts
            # differently from Enoki, C, and Mathematica..
            a = ek.asinh(C(i + 0.1, j))
            b = C(cmath.asinh(complex(i + 0.1, j)))
            assert ek.allclose(a, b)

            a = ek.acosh(C(i, j))
            b = C(cmath.acosh(complex(i, j)))
            assert ek.allclose(a, b, atol=1e-7)

            if abs(i) != 1 or j != 0:
                a = ek.atanh(C(i, j))
                b = C(cmath.atanh(complex(i, j)))
                assert ek.allclose(a, b, atol=1e-7)
Ejemplo n.º 6
0
def op_acosh(x):
    """Returns the inverse hyperbolic cosine of this mathematical object."""
    if isinstance(x, list):
        return [op_acosh(a) for a in x]
    elif isinstance(x, complex):
        return cmath.acosh(x)
    else:
        return math.acosh(x)
Ejemplo n.º 7
0
def p_sine(t):
    '''e : SINE LP e RP
         | COSINE LP e RP
         | SECANT LP e RP
         | COSECANT LP e RP
         | TANGENT LP e RP
         | COTANGENT LP e RP
         | LOG LP e COMMA e RP
         | LN LP e RP
         | EXP POW LP e RP
         | ARCSINE LP e RP
         | ARCCOSINE LP e RP
         | ARCTANGENT LP e RP
         | SINEH LP e RP
         | COSINEH LP e RP
         | TANGENTH LP e RP
         | ARCSINEH LP e RP
         | ARCCOSINEH LP e RP
         | ARCTANGENTH LP e RP
    '''
    if t[1] == 'sin':
        t[0] = cmath.sin(t[3])
    elif t[1] == 'cos':
        t[0] = cmath.cos(t[3])
    elif t[1] == 'sec':
        t[0] = 1/cmath.cos(t[3])
    elif t[1] == 'cosec':
        t[0] = 1/cmath.sin(t[3])
    elif t[1] == 'tan':
        t[0] = cmath.tan(t[3])
    elif t[1] == 'cot':
        t[0] = 1/cmath.tan(t[3])
    elif t[1] == 'log':
        t[0] = cmath.log(t[3], t[5])
    elif t[1] == 'ln':
        t[0] = cmath.log(t[3], cmath.e)
    elif t[1] == 'e':
        t[0] = cmath.exp(t[4])
    elif t[1] == 'asin':
        t[0] = cmath.asin(t[3])
    elif t[1] == 'acos':
        t[0] = cmath.acos(t[3])
    elif t[1] == 'atan':
        t[0] = cmath.atan(t[3])
    elif t[1] == 'sinh':
        t[0] = cmath.sinh(t[3])
    elif t[1] == 'cosh':
        t[0] = cmath.cosh(t[3])
    elif t[1] == 'tanh':
        t[0] = cmath.tanh(t[3])
    elif t[1] == 'asinh':
        t[0] = cmath.asinh(t[3])
    elif t[1] == 'acosh':
        t[0] = cmath.acosh(t[3])
    elif t[1] == 'atanh':
        t[0] = cmath.atanh(t[3])
Ejemplo n.º 8
0
def ACOSH(df, price='Close'):
    """
    Inverse Hyperbolic Cosine
    """
    acosh_list = []
    i = 0
    while i < len(df[price]):
        acosh = cmath.acosh(df[price][i]).real
        acosh_list.append(acosh)
        i += 1
    return acosh_list
Ejemplo n.º 9
0
def acosh(z):
    """ An AlComplex compatible hyperbolic arccosine function. It gets the main value.

        Parameters
        ----------
        z : Python numeric type or AlComplex

        Returns
        -------
        AlComplex
    """
    return AlComplex.from_python_complex(cm.acosh(z.to_python_complex()))
Ejemplo n.º 10
0
def oneArgFuncEval(function, value):
    # Evaluates functions that take a complex number input
    if function == "sin":
        return cmath.sin(value)
    elif function == "cos":
        return cmath.cos(value)
    elif function == "tan":
        return cmath.tan(value)
    elif function == "asin":
        return cmath.asin(value)
    elif function == "acos":
        return cmath.acos(value)
    elif function == "atan":
        return cmath.atan(value)
    elif function == "csc":
        return 1.0 / cmath.sin(value)
    elif function == "sec":
        return 1.0 / cmath.cos(value)
    elif function == "cot":
        return 1.0 / cmath.tan(value)
    elif function == "ln":
        return cmath.log(value)
    elif function == "sqr":
        return cmath.sqrt(value)
    elif function == "abs":
        return cmath.sqrt((value.real**2) + (value.imag**2))
    elif function == "exp":
        return cmath.exp(value)
    if function == "sinh":
        return cmath.sinh(value)
    elif function == "cosh":
        return cmath.cosh(value)
    elif function == "tanh":
        return cmath.tanh(value)
    elif function == "asinh":
        return cmath.asinh(value)
    elif function == "acosh":
        return cmath.acosh(value)
    elif function == "atanh":
        return cmath.atanh(value)
    elif function == "ceil":
        return math.ceil(value.real) + complex(0, 1) * math.ceil(value.imag)
    elif function == "floor":
        return math.floor(value.real) + complex(0, 1) * math.floor(value.imag)
    elif function == "trunc":
        return math.trunc(value.real) + complex(0, 1) * math.trunc(value.imag)
    elif function == "fac":
        if value.imag == 0 and value < 0 and value.real == int(value.real):
            return "Error: The factorial function is not defined on the negative integers."
        return gamma(value + 1)
    elif function == "log":
        return cmath.log10(value)
Ejemplo n.º 11
0
def oneArgFuncEval(function, value):
        # Evaluates functions that take a complex number input
        if function == "sin":
                return cmath.sin(value)
        elif function == "cos":
                return cmath.cos(value)
        elif function == "tan":
                return cmath.tan(value)
        elif function == "asin":
                return cmath.asin(value)
        elif function == "acos":
                return cmath.acos(value)
        elif function == "atan":
                return cmath.atan(value)
        elif function == "csc":
                return 1.0 / cmath.sin(value)
        elif function == "sec":
                return 1.0 / cmath.cos(value)
        elif function == "cot":
                return 1.0 / cmath.tan(value)        
        elif function == "ln":
                return cmath.log(value)
        elif function == "sqr":
                return cmath.sqrt(value)
        elif function == "abs":
                return cmath.sqrt((value.real ** 2) + (value.imag ** 2))
        elif function == "exp":
                return cmath.exp(value)
        if function == "sinh":
                return cmath.sinh(value)
        elif function == "cosh":
                return cmath.cosh(value)
        elif function == "tanh":
                return cmath.tanh(value)
        elif function == "asinh":
                return cmath.asinh(value)
        elif function == "acosh":
                return cmath.acosh(value)
        elif function == "atanh":
                return cmath.atanh(value)
        elif function == "ceil":
                return math.ceil(value.real) + complex(0, 1) * math.ceil(value.imag)
        elif function == "floor":
                return math.floor(value.real) + complex(0, 1) * math.floor(value.imag)
        elif function == "trunc":
                return math.trunc(value.real) + complex(0, 1) * math.trunc(value.imag)
        elif function == "fac":
                if value.imag == 0 and value < 0 and value.real == int(value.real):
                        return "Error: The factorial function is not defined on the negative integers."
                return gamma(value + 1)
        elif function == "log":
                return cmath.log10(value)
Ejemplo n.º 12
0
 def do_func(self, funcstr, x):
     return eval(
         funcstr, {
             "x": x,
             "e": cmath.e,
             "pi": cmath.pi,
             "i": 1j,
             "exp": cmath.exp,
             "sin": cmath.sin,
             "cos": cmath.cos,
             "tan": cmath.tan,
             "sinh": cmath.sinh,
             "cosh": cmath.cosh,
             "tanh": cmath.tanh,
             "sec": lambda x: 1 / cmath.cos(x),
             "csc": lambda x: 1 / cmath.sin(x),
             "cot": lambda x: cmath.cos(x) / cmath.sin(x),
             "sech": lambda x: 1 / cmath.cosh(x),
             "csch": lambda x: 1 / cmath.sinh(x),
             "coth": lambda x: cmath.cosh(x) / cmath.sinh(x),
             "arcsin": cmath.asin,
             "arccos": cmath.acos,
             "arctan": cmath.atan,
             "arsinh": cmath.asinh,
             "arcosh": cmath.acosh,
             "artanh": cmath.atanh,
             "arcsec": lambda x: cmath.acos(1 / x),
             "arccsc": lambda x: cmath.asin(1 / x),
             "arccot": lambda x: cmath.atan(1 / x),
             "arsech": lambda x: cmath.acosh(1 / x),
             "arcsch": lambda x: cmath.asinh(1 / x),
             "arcoth": lambda x: cmath.atanh(1 / x),
             "abs": abs,
             "sgn": sign,
             "arg": cmath.phase,
             "cis": lambda x: cmath.cos(x) + 1j * cmath.sin(x),
             "pow": pow,
             "sqrt": cmath.sqrt,
             "nrt": lambda x, n: x**(1 / n),
             "log": cmath.log,
             "ln": lambda x: cmath.log(x),
             "floor": math.floor,
             "ceil": math.ceil,
             "trunc": math.trunc,
             "round": round,
             "gamma": math_gamma,
             "weierstrauss": math_weierstrauss,
             "choose": math_choose,
             "max": max,
             "min": min
         }, {})
Ejemplo n.º 13
0
def acosh(x):
    """
    Return the inverse hyperbolic cosine of x.
    """
    if isinstance(x,ADF):
        ad_funcs = list(map(to_auto_diff,[x]))

        x = ad_funcs[0].x
        
        ########################################
        # Nominal value of the constructed ADF:
        f = acosh(x)
        
        ########################################

        variables = ad_funcs[0]._get_variables(ad_funcs)
        
        if not variables or isinstance(f, bool):
            return f

        ########################################

        # Calculation of the derivatives with respect to the arguments
        # of f (ad_funcs):

        lc_wrt_args = [1/sqrt(x**2 - 1)]
        qc_wrt_args = [-x/(x**2 - 1)**1.5]
        cp_wrt_args = 0.0

        ########################################
        # Calculation of the derivative of f with respect to all the
        # variables (Variable) involved.

        lc_wrt_vars,qc_wrt_vars,cp_wrt_vars = _apply_chain_rule(
                                    ad_funcs,variables,lc_wrt_args,qc_wrt_args,
                                    cp_wrt_args)
                                    
        # The function now returns an ADF object:
        return ADF(f, lc_wrt_vars, qc_wrt_vars, cp_wrt_vars)
    else:
#        try: # pythonic: fails gracefully when x is not an array-like object
#            return [acosh(xi) for xi in x]
#        except TypeError:
        if x.imag:
            return cmath.acosh(x)
        else:
            return math.acosh(x.real)
Ejemplo n.º 14
0
def acosh(x):
    """
    Return the inverse hyperbolic cosine of x.
    """
    if isinstance(x, ADF):
        ad_funcs = list(map(to_auto_diff, [x]))

        x = ad_funcs[0].x

        ########################################
        # Nominal value of the constructed ADF:
        f = acosh(x)

        ########################################

        variables = ad_funcs[0]._get_variables(ad_funcs)

        if not variables or isinstance(f, bool):
            return f

        ########################################

        # Calculation of the derivatives with respect to the arguments
        # of f (ad_funcs):

        lc_wrt_args = [1 / sqrt(x**2 - 1)]
        qc_wrt_args = [-x / (x**2 - 1)**1.5]
        cp_wrt_args = 0.0

        ########################################
        # Calculation of the derivative of f with respect to all the
        # variables (Variable) involved.

        lc_wrt_vars, qc_wrt_vars, cp_wrt_vars = _apply_chain_rule(
            ad_funcs, variables, lc_wrt_args, qc_wrt_args, cp_wrt_args)

        # The function now returns an ADF object:
        return ADF(f, lc_wrt_vars, qc_wrt_vars, cp_wrt_vars)
    else:
        #        try: # pythonic: fails gracefully when x is not an array-like object
        #            return [acosh(xi) for xi in x]
        #        except TypeError:
        if x.imag:
            return cmath.acosh(x)
        else:
            return math.acosh(x.real)
Ejemplo n.º 15
0
def acosh(x):
    """
    Uncertain number hyperbolic arc-cosine function

    .. note::
        In the complex case there is one branch cut,
        extending left from 1 along the
        real axis to :math:`-\infty`, continuous from above.
        
    """
    try:
        return x._acosh()
    except AttributeError:
        if isinstance(x, numbers.Real):
            return math.acosh(x)
        elif isinstance(x, numbers.Complex):
            return cmath.acosh(x)
        else:
            raise TypeError("illegal argument: {!r}".format(x))
Ejemplo n.º 16
0
def fit(lines_seriestab, file_prefix, sparky_peaklist, OS):

    import os, math, cmath

    ##
    ## (tau,R2eff)-fit and kex,R2-determ.
    ##

    lines_fit_o = ['#atom Ra Rb ka kb dw\n']

    fd = open('%s.gnudata' % (file_prefix), 'r')
    gnudata = fd.readlines()
    fd.close()

    ## set a list of sums of squares
    SS = []

    for i in range(len(lines_seriestab)):

        if not sparky_peaklist:
            ass = assignments_Sparky[peakindexes_NMRPipe[i]]
        else:
            ass = lines_seriestab[i][58:68].strip()

        print 'nonlinear fit for %s' % (ass)

        lines_gnuplot_script = ([
            '#freqCP = x\n'
            'tauCP(x) = 1/(4.*x)\n',
            ##            'psi(x) = (Ra-Rb-ka+kb)**2-deltaomega**2+4.*ka*kb\n', ## tc
            'psi(x) = kex**2-deltaomega**2\n',  ## kt
            ##            'epsilon(x) = 2*deltaomega*(Ra-Rb-ka+kb)\n', ## tc
            'epsilon(x) = -2*deltaomega*kex*(2*pA-1)\n',  ## kt
            ##            'Dpos(x) = (1./2.)*( 1+(psi(x)+2*deltaomega**2)/sqrt(psi(x)**2+epsilon(x)**2))\n',
            ##            'Dneg(x) = (1./2.)*(-1+(psi(x)+2*deltaomega**2)/sqrt(psi(x)**2+epsilon(x)**2))\n',
            'Dpos(x) = (1./2.)*( 1+(psi(x)+2*deltaomega**2)/sqrt(psi(x)**2+epsilon(x)**2))\n',
            'Dneg(x) = (1./2.)*(-1+(psi(x)+2*deltaomega**2)/sqrt(psi(x)**2+epsilon(x)**2))\n',
            'etapos(x) = (tauCP(x)/sqrt(2))*sqrt( psi(x)+sqrt(psi(x)**2+epsilon(x)**2))\n',
            'etaneg(x) = (tauCP(x)/sqrt(2))*sqrt(-psi(x)+sqrt(psi(x)**2+epsilon(x)**2))\n',
            ##            'f(x) = (1./2.)*(   Ra+Rb+ka+kb-(1/tauCP(x))*(  acosh( Dpos(x)*cosh(etapos(x)) - Dneg(x)*cos(etaneg(x)) )  )   )\n',
            'f(x) = R+(1./2.)*(   kex-(1/tauCP(x))*(  acosh( Dpos(x)*cosh(etapos(x)) - Dneg(x)*cos(etaneg(x)) )  )   )\n',
            ##            'Ra = 17\n', ## tc
            ##            'Rb = 23\n', ## tc
            ##            'ka = 29\n', ## tc
            ##            'kb = 19\n', ## tc
            'kex = 2000\n',  ## kt
            'pA = 0.9\n',  ## kt
            'R = 7\n',  ## kt
            'deltaomega = 1000\n',
            ##            'fit f(x) "%s.gnudata" using 1:%s via Ra,Rb,ka,kb,deltaomega\n' %(file_prefix, i+2),
            'fit f(x) "%s.gnudata" using 1:%s via kex,pA,R,deltaomega\n' %
            (file_prefix, i + 2),
            'set terminal png\n',
            'set output "%s%s.png"\n' % (file_prefix, i),
            'plot [][0:]"%s.gnudata" using 1:%s title "%s", f(x)\n' %
            (file_prefix, i + 2, ass)
        ])

        ## write gnuplot script file
        fd = open('%s.gnuscript%s' % (file_prefix, i), 'w')
        fd.writelines(lines_gnuplot_script)
        fd.close()
        ## execute gnuplot script file and write gnuplot fit log
        if OS == 'linux':
            os.system('/usr/bin/gnuplot %s.gnuscript%s' % (file_prefix, i))
        elif OS == 'windows':
            os.system('gnuplot %s.gnuscript%s' % (file_prefix, i))
## remove gnuplot script file
        os.remove('%s.gnuscript%s' % (file_prefix, i))

        ## parse gnuplot fit log
        if OS == 'linux':
            lines_fit_i = os.popen('tail -n18 fit.log').readlines()
        elif OS == 'windows':
            fd = open('fit.log', 'r')
            lines_fit_i = fd.readlines()[-18:]
            fd.close()


##	Ra = float(lines_fit_i[3].split()[2])
##	Rb = float(lines_fit_i[4].split()[2])
##	ka = float(lines_fit_i[5].split()[2])
##	kb = float(lines_fit_i[6].split()[2])
##	dw = float(lines_fit_i[7].split()[2])
        kex = float(lines_fit_i[5].split()[2])
        pA = float(lines_fit_i[6].split()[2])
        R = float(lines_fit_i[7].split()[2])
        dw = float(lines_fit_i[8].split()[2])

        ## write parsed fit data to other fit log
        ##        lines_fit_o += ['%10s %6.3f %6.3f %6.3f %6.3f %8.3f\n' %(ass, Ra, Rb, ka, kb, dw)]
        lines_fit_o += [
            '%10s %6.3f %6.3f %6.3f %8.3f\n' % (ass, kex, pA, R, dw)
        ]

        ##
        ## SS calculation for use in F-test comparing nonlinear and linear fits
        ##

        n = len(gnudata[1:])
        deltaomega = dw
        sumdiffsq = 0
        sumdiff = 0
        for line in gnudata[1:]:
            x = float(line.split()[0])
            y = float(line.split()[i + 1])
            tauCP = 1 / (4. * x)
            ##            psi = (Ra-Rb-ka+kb)**2-deltaomega**2+4.*ka*kb
            psi = kex**2 - deltaomega**2
            ##            epsilon = 2*deltaomega*(Ra-Rb-ka+kb)
            epsilon = -2 * deltaomega * kex * (2 * pA - 1)
            Dpos = (1. / 2.) * (
                1 + (psi + 2 * deltaomega**2) / math.sqrt(psi**2 + epsilon**2))
            Dneg = (1. / 2.) * (
                -1 +
                (psi + 2 * deltaomega**2) / math.sqrt(psi**2 + epsilon**2))
            etapos = (tauCP / math.sqrt(2)
                      ) * math.sqrt(psi + math.sqrt(psi**2 + epsilon**2))
            etaneg = (tauCP / math.sqrt(2)
                      ) * math.sqrt(-psi + math.sqrt(psi**2 + epsilon**2))
            ##            yhat = (1./2.)*(   Ra+Rb+ka+kb-(1/tauCP)*(  cmath.acosh( Dpos*cmath.cosh(etapos) - Dneg*math.cos(etaneg) )  )   )
            yhat = R + (1. / 2.) * (kex - (1 / tauCP) *
                                    (cmath.acosh(Dpos * cmath.cosh(etapos) -
                                                 Dneg * math.cos(etaneg))))
            diff = yhat - y
            sumdiff += diff  ## abs??
            sumdiffsq += diff**2
        ss = abs(sumdiffsq - (sumdiff**2) / n)
        stop
        ## append ss calculated for 1 chemical group to list of sums of squares
        SS += [ss]

    os.remove('fit.log')

    fd = open('%s.fit' % (file_prefix), 'w')
    fd.writelines(lines_fit_o)
    fd.close()

    return SS
print('sqrt(c) =', cmath.sqrt(c))

# trigonometric functions
c = 2 + 2j
print('arc sine =', cmath.asin(c))
print('arc cosine =', cmath.acos(c))
print('arc tangent =', cmath.atan(c))

print('sine =', cmath.sin(c))
print('cosine =', cmath.cos(c))
print('tangent =', cmath.tan(c))

# hyperbolic functions
c = 2 + 2j
print('inverse hyperbolic sine =', cmath.asinh(c))
print('inverse hyperbolic cosine =', cmath.acosh(c))
print('inverse hyperbolic tangent =', cmath.atanh(c))

print('hyperbolic sine =', cmath.sinh(c))
print('hyperbolic cosine =', cmath.cosh(c))
print('hyperbolic tangent =', cmath.tanh(c))

# classification functions
print(cmath.isfinite(2 + 2j))  # True
print(cmath.isfinite(cmath.inf + 2j))  # False

print(cmath.isinf(2 + 2j))  # False
print(cmath.isinf(cmath.inf + 2j))  # True
print(cmath.isinf(cmath.nan + 2j))  # False

Ejemplo n.º 18
0
import matplotlib.pyplot as plt
import cmath

# PLOTS OF THE LOWPASS CHEBYSCHEV FILTER OF ORDER N AND
# 0.3184 < epsilon < 0.6197

N = 4
epsilon = np.arange(0.35, 0.61, 0.05)
le = len(epsilon)
epsilon = epsilon.reshape(le, 1)

omega = np.linspace(0, 2, 201)
omega = omega.reshape(len(omega), 1)
lo = len(omega)
H = np.zeros((len(epsilon), len(omega)))

for i in range(len(epsilon)):
    for j in range(len(omega)):
        H[i][j] = (1 / np.sqrt(1 + (epsilon[i]**2) *
                               np.cosh(N * cmath.acosh(omega[j]))**2)).real
    plt.plot(omega, H[i, :], linewidth=0.1)

leglist = [
    "$\epsilon$ = 0.35", "$\epsilon$ = 0.40", "$\epsilon$ = 0.45",
    "$\epsilon$ = 0.50", "$\epsilon$ = 0.55", "$\epsilon$ = 0.60"
]
plt.xlabel("$\Omega$")
plt.ylabel("$|H_{a,LP}(j\Omega)|$")
plt.legend(leglist, loc="upper right")
plt.savefig('../../figs/para_plot.eps')
Ejemplo n.º 19
0
def acosh(x):
    if isinstance(x, complex):
        return cmath.acosh(x)
    else:
        return math.acosh(x)
Ejemplo n.º 20
0
def hyplen(tr):
    return 2.0*(acosh(0.5*tr).real)
def measure(schlafli, i0,i1):

    if i0 == i1:
        return 0.,0.
    if i0 > i1:
        i0,i1 = i1,i0

    if len(schlafli) == 0:
        # 0 dimensional surface, {}
        # can't get here-- i0,i1 must be 0,0 which was handled above
        assert False
    if len(schlafli) == 1:
        # 1 dimensional surface, {p}
        p = schlafli
        if (i0,i1) == (0,1):
            assert False # I don't think this is well-defined... maybe infinite?
        else:
            assert False
    elif len(schlafli) == 2:
        # 2 dimensional surface, {p,q}
        p,q = schlafli
        if (i0,i1) == (0,1):
            # half edge length
            coshValue = cos(pi/p)/sin(pi/q)
        elif (i0,i1) == (1,2):
            # face in-radius
            coshValue = cos(pi/q)/sin(pi/p)
        elif (i0,i1) == (0,2):
            # face circum-radius
            coshValue = 1/(tan(pi/p)*tan(pi/q))
        else:
            assert False
    elif len(schlafli) == 3:
        # 3 dimensional surface, {p,q,r}
        p,q,r = schlafli
        def sin_pi_over_h(p,q):
            # = sqrt(1 - cos^2 (pi / h(p,q)))
            # = sqrt(1 - (cos(pi/p)^2 + cos(pi/q)^2)
            return sqrt(1 - (cos(pi/p)**2 + cos(pi/q)**2))
        if (i0,i1) == (0,1):
            # half edge length
            coshValue = cos(pi/p)*sin(pi/r)/sin_pi_over_h(q,r)
        elif (i0,i1) == (2,3):
            # cell in-radius
            coshValue = sin(pi/p)*cos(pi/r)/sin_pi_over_h(p,q)
        elif (i0,i1) == (0,3):
            # cell circum-radius
            coshValue = cos(pi/p)*cos(pi/q)*cos(pi/r)/(sin_pi_over_h(p,q)*sin_pi_over_h(q,r))
        elif (i0,i1) == (0,2):
            # 2d face circum-radius
            cosh2_r01,cosh_r01,r01 = measure(schlafli,0,1)
            sinh_r01 = sqrt(cosh2_r01-1)
            sinhValue = sinh_r01/sin(pi/p)
            coshValue = sqrt(1+sinhValue**2)
            #do('coshValue')

            # hmm, this doesn't seem to be simplifying much
            sinh2Value = ((cos(pi/p)*sin(pi/r))**2/(1 - (cos(pi/q)**2 + cos(pi/r)**2))-1)/sin(pi/p)**2
            cosh2Value = 1+sinh2Value
            coshValue = sqrt(cosh2Value)
            #do('coshValue')
            # oh wait, wolframalpha says sinh2Value is equal to cot^2(pi/p)cos^2(pi/q)/(sin^2(pi/q)-cos^2(pi/r))
            # maybe get h back out of the equation and it wil turn somewhat nice
            # TODO: try to simplify some more

            h = pi/asin(sin_pi_over_h(q,r))
            sinhValue = sqrt((cos(pi/p)*sin(pi/r)/sin(pi/h))**2-1)/sin(pi/p)
            coshValue = sqrt(1+sinhValue**2)
            coshValue = sqrt(1+((cos(pi/p)*sin(pi/r)/sin(pi/h))**2-1)/sin(pi/p)**2)
            #do('coshValue')

            # huh? this is wacked, it's not equal to what I thought above
            #sinh2Value = sin(pi/p)**2*cos(pi/q)**2/sin_pi_over_h(q,r)**2/cos(pi/p)**2
            sinh2Value = cos(pi/p)**2/sin(pi/p)**2 * cos(pi/q)**2 / (sin(pi/q)**2 - cos(pi/r)**2)
            cosh2Value = 1+sinh2Value
            coshValue = sqrt(cosh2Value)
            #do('coshValue')



        elif (i0,i1) == (1,3):
            # cell mid-radius
            return measure([r,q,p], 0,2)
        elif (i0,i1) == (1,2):
            # 2d face in-radius
            # We can calculate this in one of two ways,
            # using the hyperbolic right triangle identities:
            #   cos A = tanh b / tanh c
            #   sinh a / sin A = sinh c / 1
            # => sinh a = sinh c * sqrt(1 - (tanh b / tanh c)^2)
            # with either: b=r01, c=r02
            #          or: b=r23, c=r13
            # But, it simplifies to the simplest of all
            # (don't ask me how, I used wolframalpha
            # on a horrendous expression after
            # breaking it up into bite sized pieces):

            coshValue = cos(pi/q) / (sin(pi/p) * sin(pi/r))

        else:
            assert False # illegal
    elif len(schlafli) == 4:
        # 4 dimensional surface, {p,q,r,s}
        p,q,r,s = schlafli
        if (i0,i1) == (0,1):
            # half edge length
            assert False # unimplemented
        elif (i0,i1) == (3,4):
            # facet in-radius
            assert False # unimplemented
        elif (i0,i1) == (0,4):
            # facet circum-radius
            assert False # unimplemented
        else:
            assert False # illegal
    else:
        assert False # unimplemented

    return coshValue**2, coshValue,acosh(coshValue)
Ejemplo n.º 22
0
def fit(lines_seriestab, file_prefix, sparky_peaklist, OS):

    import os, math, cmath

    ##
    ## (tau,R2eff)-fit and kex,R2-determ.
    ##

    lines_fit_o = ['#atom Ra Rb ka kb dw\n']

    fd = open('%s.gnudata' %(file_prefix),'r')
    gnudata = fd.readlines()
    fd.close()

    ## set a list of sums of squares
    SS = []

    for i in range(len(lines_seriestab)):

        if not sparky_peaklist:
            ass = assignments_Sparky[peakindexes_NMRPipe[i]]
        else:
            ass = lines_seriestab[i][58:68].strip()

        print 'nonlinear fit for %s' %(ass)

        lines_gnuplot_script = ([
	    '#freqCP = x\n'
	    'tauCP(x) = 1/(4.*x)\n',
##            'psi(x) = (Ra-Rb-ka+kb)**2-deltaomega**2+4.*ka*kb\n', ## tc
            'psi(x) = kex**2-deltaomega**2\n', ## kt
##            'epsilon(x) = 2*deltaomega*(Ra-Rb-ka+kb)\n', ## tc
            'epsilon(x) = -2*deltaomega*kex*(2*pA-1)\n', ## kt
##            'Dpos(x) = (1./2.)*( 1+(psi(x)+2*deltaomega**2)/sqrt(psi(x)**2+epsilon(x)**2))\n',
##            'Dneg(x) = (1./2.)*(-1+(psi(x)+2*deltaomega**2)/sqrt(psi(x)**2+epsilon(x)**2))\n',
            'Dpos(x) = (1./2.)*( 1+(psi(x)+2*deltaomega**2)/sqrt(psi(x)**2+epsilon(x)**2))\n',
            'Dneg(x) = (1./2.)*(-1+(psi(x)+2*deltaomega**2)/sqrt(psi(x)**2+epsilon(x)**2))\n',
            'etapos(x) = (tauCP(x)/sqrt(2))*sqrt( psi(x)+sqrt(psi(x)**2+epsilon(x)**2))\n',
            'etaneg(x) = (tauCP(x)/sqrt(2))*sqrt(-psi(x)+sqrt(psi(x)**2+epsilon(x)**2))\n',
##            'f(x) = (1./2.)*(   Ra+Rb+ka+kb-(1/tauCP(x))*(  acosh( Dpos(x)*cosh(etapos(x)) - Dneg(x)*cos(etaneg(x)) )  )   )\n',
            'f(x) = R+(1./2.)*(   kex-(1/tauCP(x))*(  acosh( Dpos(x)*cosh(etapos(x)) - Dneg(x)*cos(etaneg(x)) )  )   )\n',
##            'Ra = 17\n', ## tc
##            'Rb = 23\n', ## tc
##            'ka = 29\n', ## tc
##            'kb = 19\n', ## tc
            'kex = 2000\n', ## kt
            'pA = 0.9\n', ## kt
            'R = 7\n', ## kt
            'deltaomega = 1000\n',
##            'fit f(x) "%s.gnudata" using 1:%s via Ra,Rb,ka,kb,deltaomega\n' %(file_prefix, i+2),
            'fit f(x) "%s.gnudata" using 1:%s via kex,pA,R,deltaomega\n' %(file_prefix, i+2),
            'set terminal png\n',
            'set output "%s%s.png"\n' %(file_prefix, i),
            'plot [][0:]"%s.gnudata" using 1:%s title "%s", f(x)\n' %(file_prefix, i+2, ass)
            ])

        ## write gnuplot script file
        fd = open('%s.gnuscript%s' %(file_prefix, i), 'w')
        fd.writelines(lines_gnuplot_script)
        fd.close()
        ## execute gnuplot script file and write gnuplot fit log
        if OS == 'linux':
            os.system('/usr/bin/gnuplot %s.gnuscript%s' %(file_prefix, i))
        elif OS == 'windows':
            os.system('gnuplot %s.gnuscript%s' %(file_prefix, i))
	## remove gnuplot script file
	os.remove('%s.gnuscript%s' %(file_prefix, i))

	## parse gnuplot fit log
	if OS == 'linux':
            lines_fit_i = os.popen('tail -n18 fit.log').readlines()
        elif OS == 'windows':
            fd = open('fit.log','r')
            lines_fit_i = fd.readlines()[-18:]
            fd.close()
##	Ra = float(lines_fit_i[3].split()[2])
##	Rb = float(lines_fit_i[4].split()[2])
##	ka = float(lines_fit_i[5].split()[2])
##	kb = float(lines_fit_i[6].split()[2])
##	dw = float(lines_fit_i[7].split()[2])
	kex = float(lines_fit_i[5].split()[2])
	pA = float(lines_fit_i[6].split()[2])
	R = float(lines_fit_i[7].split()[2])
	dw = float(lines_fit_i[8].split()[2])
        
	## write parsed fit data to other fit log
##        lines_fit_o += ['%10s %6.3f %6.3f %6.3f %6.3f %8.3f\n' %(ass, Ra, Rb, ka, kb, dw)]
        lines_fit_o += ['%10s %6.3f %6.3f %6.3f %8.3f\n' %(ass, kex, pA, R, dw)]

        ##
        ## SS calculation for use in F-test comparing nonlinear and linear fits
        ##

        n = len(gnudata[1:])
        deltaomega = dw
        sumdiffsq = 0
        sumdiff = 0
        for line in gnudata[1:]:
            x = float(line.split()[0])
            y = float(line.split()[i+1])
	    tauCP = 1/(4.*x)
##            psi = (Ra-Rb-ka+kb)**2-deltaomega**2+4.*ka*kb
	    psi = kex**2-deltaomega**2
##            epsilon = 2*deltaomega*(Ra-Rb-ka+kb)
	    epsilon = -2*deltaomega*kex*(2*pA-1)
            Dpos = (1./2.)*( 1+(psi+2*deltaomega**2)/math.sqrt(psi**2+epsilon**2))
            Dneg = (1./2.)*(-1+(psi+2*deltaomega**2)/math.sqrt(psi**2+epsilon**2))
            etapos = (tauCP/math.sqrt(2))*math.sqrt( psi+math.sqrt(psi**2+epsilon**2))
            etaneg = (tauCP/math.sqrt(2))*math.sqrt(-psi+math.sqrt(psi**2+epsilon**2))
##            yhat = (1./2.)*(   Ra+Rb+ka+kb-(1/tauCP)*(  cmath.acosh( Dpos*cmath.cosh(etapos) - Dneg*math.cos(etaneg) )  )   )
            yhat = R+(1./2.)*(   kex-(1/tauCP)*(  cmath.acosh( Dpos*cmath.cosh(etapos) - Dneg*math.cos(etaneg) )  )   )
            diff = yhat-y
            sumdiff += diff ## abs??
            sumdiffsq += diff**2
        ss = abs(sumdiffsq-(sumdiff**2)/n)
        stop
        ## append ss calculated for 1 chemical group to list of sums of squares
        SS += [ss]

    os.remove('fit.log')

    fd = open('%s.fit' %(file_prefix), 'w')
    fd.writelines(lines_fit_o)
    fd.close()

    return SS
Ejemplo n.º 23
0
x = 0.5

assert abs(cosh(x) - math.cosh(x)) < 1e-14
assert abs(sinh(x) - math.sinh(x)) < 1e-14
assert abs(tanh(x) - math.tanh(x)) < 1e-14

#------------------------------------------------------------------------------
# Hyperbolic functions - complex version

x = 0.5j

assert abs(cosh(x) - cmath.cosh(x)) < 1e-14
assert abs(sinh(x) - cmath.sinh(x)) < 1e-14
assert abs(tanh(x) - cmath.tanh(x)) < 1e-14

assert abs(acosh(x) - cmath.acosh(x)) < 1e-14
assert abs(asinh(x) - cmath.asinh(x)) < 1e-14
assert abs(atanh(x) - cmath.atanh(x)) < 1e-14

#------------------------------------------------------------------------------
# Rounding operations.

assert type(round(0.5)) is mpf
assert type(round(mpq(1, 2))) is mpf
assert type(floor(0.5)) is mpf
assert type(ceil(0.5)) is mpf

assert round(0.5) == 1
assert round(-0.5) == -1
assert round(1.5) == 2
assert round(-1.5) == -2
x = 0.5

assert abs(cosh(x) - math.cosh(x)) < 1e-14
assert abs(sinh(x) - math.sinh(x)) < 1e-14
assert abs(tanh(x) - math.tanh(x)) < 1e-14

#------------------------------------------------------------------------------
# Hyperbolic functions - complex version

x = 0.5j

assert abs(cosh(x) - cmath.cosh(x)) < 1e-14
assert abs(sinh(x) - cmath.sinh(x)) < 1e-14
assert abs(tanh(x) - cmath.tanh(x)) < 1e-14

assert abs(acosh(x) - cmath.acosh(x)) < 1e-14
assert abs(asinh(x) - cmath.asinh(x)) < 1e-14
assert abs(atanh(x) - cmath.atanh(x)) < 1e-14

#------------------------------------------------------------------------------
# Rounding operations.

assert type(round(0.5)) is mpf
assert type(round(mpq(1,2))) is mpf
assert type(floor(0.5)) is mpf
assert type(ceil(0.5)) is mpf

assert round(0.5) == 1
assert round(-0.5) == -1
assert round(1.5) == 2
assert round(-1.5) == -2
Ejemplo n.º 25
0
    Power and Log Functions
        The cmath() module provides some useful functions for logarithmic
        and power operations.
"""
c = 1+2j
print('e^c = ', cmath.exp(c))
print('log2(c) = ', cmath.log(c,2))
print('log10(c) = ', cmath.log10(c))
print('sqrt(c) = ', cmath.sqrt(c))

"""
    Trigonometric Functions
"""
c = 2+4j
print('arc sine value:\n ', cmath.asin(c))
print('arc cosine value:\n ', cmath.acos(c))
print('arc tangent value:\n ', cmath.atan(c))
print('sine value:\n ', cmath.sin(c))
print('cosine value:\n ', cmath.cos(c))
print('tangent value:\n ', cmath.tan(c))

"""
    Hyperbolic Functions
"""
c = 2+4j
print('Inverse hyperbolic sine value: \n', cmath.asinh(c))
print('Inverse hyperbolic cosine value: \n', cmath.acosh(c))
print('Inverse hyperbolic tangent value: \n', cmath.atanh(c))
print('Inverse sine value: \n', cmath.sinh(c))
print('Inverse cosine value: \n', cmath.cosh(c))
print('Inverse tangent value: \n', cmath.tanh(c))
Ejemplo n.º 26
0
def Cheb(m, x):
    if (abs(x) <= 1):
        return math.cos(m * math.acos(x))
    else:
        return (cmath.cosh(m * cmath.acosh(x))).real
 def halfEdgeLength(p,q,r):
     return acosh(cos(pi/p)*sin(pi/r)/sqrt(1-cos(pi/q)**2-cos(pi/r)**2))
Ejemplo n.º 28
0
print("The tangent value of complex number is : ")
print(cmath.tan(z))

print("The arc sine value of complex number is : ")
print(cmath.asin(z))

print("The arc cosine value of complex number is : ")
print(cmath.acos(z))

print("The arc tangent value of complex number is : ")
print(cmath.atan(z))

print("The hyperbolic sine value of complex number is : ")
print(cmath.sinh(z))

print("The hyperbolic cosine value of complex number is : ")
print(cmath.cosh(z))

print("The hyperbolic tangent value of complex number is : ")
print(cmath.tanh(z))

print("The inverse hyperbolic sine value of complex number is : ")
print(cmath.asinh(z))

print("The inverse hyperbolic cosine value of complex number is : ")
print(cmath.acosh(z))

print("The inverse hyperbolic tangent value of complex number is : ")
print(cmath.atanh(z))
Ejemplo n.º 29
0
def acosh_usecase(x):
    return cmath.acosh(x)
Ejemplo n.º 30
0
#The analog bandpass filter (design) frequencies
#obtained using the bilinear transformation
Omega_p1 = np.tan(omega_p1 / 2)
Omega_p2 = np.tan(omega_p2 / 2)

Omega_s1 = np.tan(omega_s1 / 2)
Omega_s2 = np.tan(omega_s2 / 2)

#The analog bandpass-lowpass (design) transformation
#parameters
Omega_0 = np.sqrt(Omega_p1 * Omega_p2)
B = Omega_p1 - Omega_p2

#The lowpass Chebyschev approximation stopband frequency
Omega_Ls = min(abs((Omega_s1**2 - Omega_0**2) / (B * Omega_s1)),
               abs((Omega_s2**2 - Omega_0**2) / (B * Omega_s2)))

#The lowpass Chebyschev approximation
D1 = 1 / ((1 - delta)**2) - 1
D2 = 1 / (delta**2) - 1

#Estimated lowpass Chebyschev filter order
N = np.ceil((cmath.acosh(np.sqrt(D2 / D1)) / cmath.acosh(Omega_Ls)).real)

#Range Of the Chebyschev filter parameter epsilon
epsilon1 = np.sqrt(D2) / np.cosh(N * cmath.acosh(Omega_Ls))
epsilon2 = np.sqrt(D1)

print(epsilon1)
print(epsilon2)
Ejemplo n.º 31
0
def ACOSH(df, price='Close'):
    """
    Inverse Hyperbolic Cosine
    Returns: list of floats = jhta.ACOSH(df, price='Close')
    """
    return [cmath.acosh(df[price][i]).real for i in range(len(df[price]))]
Ejemplo n.º 32
0
def acosh(x):
    if is_complex(x):
        return cmath.acosh(x)
    return math.acosh(x)
Ejemplo n.º 33
0
def acosh_usecase(x):
    return cmath.acosh(x)
Ejemplo n.º 34
0
 def test_acosh(self):
     self.assertAlmostEqual(complex(2.30551, 0.93681),
                            cmath.acosh(complex(3, 4)))
Ejemplo n.º 35
0
import mpmath
import cmath

N = 4
epsilon = np.arange(0.35, 0.61, 0.05)
epsilon = epsilon.reshape(len(epsilon), 1)

omega = np.linspace(0, 2, 201)
omega = omega.reshape(len(omega), 1)
H = np.zeros((len(epsilon), len(omega)))

for i in range(len(epsilon)):
    for j in range(len(omega)):
        H[i][j] = (
            1 /
            np.sqrt(1 + epsilon[i]**2 * np.cosh(N * cmath.acosh(omega[j]))**2)
        ).real
    plt.plot(omega, H[i, :])

plt.grid()
plt.legend([
    "$\epsilon$ = 0.35", "$\epsilon$ = 0.40", "$\epsilon$ = 0.45",
    "$\epsilon$ = 0.50", "$\epsilon$ = 0.55", "$\epsilon$ = 0.60"
],
           loc="upper right")
plt.xlabel("$\Omega$")
plt.ylabel("$|H_{a,LP}(j\Omega)|$")
plt.title(
    "Plots of Lowpass Chebyshev filter of order N and 0.3184 < $\epsilon$ < 0.6197"
)
plt.savefig('figs/ee18btech11034_parameter_plots.eps')
Ejemplo n.º 36
0
print('sqrt(c) =', cmath.sqrt(c))

# trigonometric functions
c = 2 + 2j
print('arc sine =', cmath.asin(c))
print('arc cosine =', cmath.acos(c))
print('arc tangent =', cmath.atan(c))

print('sine =', cmath.sin(c))
print('cosine =', cmath.cos(c))
print('tangent =', cmath.tan(c))

# hyperbolic functions
c = 2 + 2j
print('inverse hyperbolic sine =', cmath.asinh(c))
print('inverse hyperbolic cosine =', cmath.acosh(c))
print('inverse hyperbolic tangent =', cmath.atanh(c))

print('hyperbolic sine =', cmath.sinh(c))
print('hyperbolic cosine =', cmath.cosh(c))
print('hyperbolic tangent =', cmath.tanh(c))

# classification functions
print(cmath.isfinite(2 + 2j))  # True
print(cmath.isfinite(cmath.inf + 2j))  # False

print(cmath.isinf(2 + 2j))  # False
print(cmath.isinf(cmath.inf + 2j))  # True
print(cmath.isinf(cmath.nan + 2j))  # False

print(cmath.isnan(2 + 2j))  # False
Ejemplo n.º 37
0
Omega_p2 = np.tan(omega_p2 / 2)

Omega_s1 = np.tan(omega_s1 / 2)
Omega_s2 = np.tan(omega_s2 / 2)

#The analog bandpass-lowpass (design) transformation
#parameters
Omega_0 = np.sqrt(Omega_p1 * Omega_p2)
B = Omega_p1 - Omega_p2

#The lowpass Chebyschev approximation stopband frequency
Omega_Ls = min(abs((Omega_s1**2 - Omega_0**2) / (B * Omega_s1)),
               abs((Omega_s2**2 - Omega_0**2) / (B * Omega_s2)))

#The lowpass Chebyschev approximation

D1 = 1 / ((1 - delta)**2) - 1
D2 = 1 / (delta**2) - 1

#Estimated lowpass Chebyschev filter order
N = (cmath.acosh(np.sqrt(D2 / D1)) / cmath.acosh(Omega_Ls))
N = N.real
N = np.ceil(N)

#Range Of the Chebyschev filter parameter epsilon
epsilon1 = np.sqrt(D2) / np.cosh(N * cmath.acosh(Omega_Ls))
epsilon2 = np.sqrt(D1)

#print(epsilon1)
#print(epsilon2)
Ejemplo n.º 38
0
                    'log': lambda x: cmath.log(x)/cmath.log(10),
                    'fact': lambda x: factorial(int(x)),
                    'asin': lambda x: cmath.asin(x), 
                    'acos': lambda x: cmath.acos(x),
                    'atan': lambda x: cmath.atan(x), 
                    'acsc': lambda x: cmath.asin(1/x),
                    'asec': lambda x: cmath.acos(1/x), 
                    'acot': lambda x: cmath.atan(1/x),
                    'sinh': lambda x: cmath.sinh(x), 
                    'cosh': lambda x: cmath.cosh(x),
                    'tanh': lambda x: cmath.tanh(x), 
                    'csch': lambda x: 1/cmath.sinh(x),
                    'sech': lambda x: 1/cmath.cosh(x),
                    'coth': lambda x: 1/cmath.tanh(x),
                    'asinh': lambda x: cmath.asinh(x), 
                    'acosh': lambda x: cmath.acosh(x),
                    'atanh': lambda x: cmath.atanh(x), 
                    'acsch': lambda x: cmath.asinh(1/x),
                    'asech': lambda x: cmath.acosh(1/x),
                    'acoth': lambda x: cmath.atanh(1/x)
                    }

def replace_variables(phrase, replacement, var = 'x'):
    """Replaces all instances of a named variable in a phrase with a 
    replacement, 'x' by default."""
    i = 0
    while i < len(phrase):
        match = re.match('((sum.+?,).+,.+?\))', phrase[i:])
        if match:
            i += len(match.groups(0)[1]) - 1    
        match = re.match(function_pattern, phrase[i:])
Ejemplo n.º 39
0
def rpn_calc(input, angle_mode = 0):
	global stack
	single_arg_funcs = ['exp','sqrt','sin','asin','cos','acos','tan','atan', 'sinh','asinh','cosh','acosh','tanh',
                        'atanh','!', 'polar']
	
	num, arg, option = parse(input)
	#print(num, arg, option)
	#print('\n')
	
	if arg == None and (num != None or num != 'Error'):
		config.stack.append(num)
		history.append('Entered number: ' + str(num) )
		return config.stack

	

# Simple arithmatic-----------------------------------------------------------------------	
	if option == None and num != None:
		if arg not in single_arg_funcs:
			last = config.stack.pop()
	
		if arg == '+':
			try:
				result = Decimal(last) + Decimal(num)
				hist = str(last) + '+' + str(num) + '=' + str(result)
			except TypeError:
				result = last + num
				hist = str(last) + '+' + str(num) + '=' + str(result)
				
		if arg == '-':
			try:
				result = Decimal(last) - Decimal(num)
				hist = str(last) + '-' + str(num) + '=' + str(result)
			except TypeError:
				result = last - num
				hist = str(last) + '-' + str(num) + '=' + str(result)
			
		if arg == '*':
			try:
				result = Decimal(last) * Decimal(num)
				hist = str(last) + '*' + str(num) + '=' + str(result)
			except TypeError:
				result = last * num
				hist = str(last) + '*' + str(num) + '=' + str(result)
				
		if arg == '/':
			try:
				result = Decimal(last) / Decimal(num)
				hist = str(last) + '/' + str(num) + '=' + str(result)
			except TypeError:
				result = last / num
				hist = str(last) + '/' + str(num) + '=' + str(result)
				
		if arg == '**':
			try:
				result = pow(Decimal(last), Decimal(num) )
				hist = str(last) + '**' + str(num) + '=' + str(result)
			except TypeError:
				result = last ** num
				hist = str(last) + '**' + str(num) + '=' + str(result)
				
		if arg == 'rt':
			try:
				result = root(Decimal(last), Decimal(num) )
				hist = str(last) + 'raised to 1 over ' + str(num) + '=' + str(result)
			except TypeError:
				result = root(last + num)
				hist = str(last) + 'raised to 1 over ' + str(num) + '=' + str(result)
				
		if arg == '%':
			try:
				result = Decimal(last) % Decimal(num)
				hist = str(last) + '%' + str(num) + '=' + str(result)
			except TypeError:
				result = last % num
				hist = str(last) + '%' + str(num) + '=' + str(result)
		
		if arg == '!':
			try:
				result = Decimal(math.factorial(num))
				hist = str(num) + '!' + '=' + str(result)
			except TypeError:
				result = math.factorial(num)
				hist = str(num) + '!' + '=' + str(result)
				
		if arg == 'exp':
			try:
				result = math.exp(Decimal(num))
				hist = str(num) + 'exp' + '=' + str(result)
			except ValueError:
				result = cmath.exp(Decimal(num))
				hist = str(num) + 'exp' + '=' + str(result)
			except TypeError:
				result = cmath.exp(num)
				hist = str(num) + 'exp' + '=' + str(result)
				
		if arg == 'sqrt':
			try:
				result = math.sqrt(Decimal(num))
				hist = str(num) + 'sqrt' + '=' + str(result)
			except ValueError:
				result = cmath.sqrt(Decimal(num))
				hist = str(num) + 'sqrt' + '=' + str(result)
			except TypeError:
				result = cmath.sqrt(num)
				hist = str(num) + 'sqrt' + '=' + str(result)
				
		if arg == 'log':
			try:
				result = math.log10(Decimal(num))
				hist = str(num) + 'log10' + '=' + str(result)
			except ValueError:
				result = cmath.log10(Decimal(num))
				hist = str(num) + 'log10' + '=' + str(result)
			except TypeError:
				result = cmath.log10(num)
				hist = str(num) + 'log10' + '=' + str(result)
		#=================================
		if arg == 'ln':
			try:
				result = math.log(Decimal(num))
				hist = str(num) + 'ln' + '=' + str(result)
			except ValueError:
				result = cmath.log(Decimal(num))
				hist = str(num) + 'ln' + '=' + str(result)
			except TypeError:
				result = cmath.log(num)
				hist = str(num) + 'ln' + '=' + str(result)
		#--------TRIG--------------------------------
		if arg == 'sin':
			if angle_mode == 1:
				try:
					result = math.sin(Decimal(num))
					hist = 'sin' + str(num) + '=' + str(result)
				except TypeError:
					result = cmath.sin(num)
					hist = 'sin' + str(num) + '=' + str(result)
			elif angle_mode == 0:
				try:
					result = math.sin(math.radians(Decimal(num)))
					hist = 'sin' + str(num) + '=' + str(result)
				except TypeError:
					result = cmath.sin(num)
					hist = 'sin' + str(num) + '=' + str(result)
		
		if arg == 'cos':
			if angle_mode == 1:
				try:
					result = math.cos(Decimal(num))
					hist = 'cos' + str(num) + '=' + str(result)
				except TypeError:
					result = cmath.cos(num)
					hist = 'cos' + str(num) + '=' + str(result)
			elif angle_mode == 0:
				try:
					result = math.cos(math.radians(Decimal(num)))
					hist = 'cos' + str(num) + '=' + str(result)
				except TypeError:
					result = cmath.cos(num)
					hist = 'cos' + str(num) + '=' + str(result)

		if arg == 'tan':
			if angle_mode == 1:
				try:
					result = math.tan(Decimal(num))
					hist = 'tan' + str(num) + '=' + str(result)
				except TypeError:
					result = cmath.tan(num)
					hist = 'tan' + str(num) + '=' + str(result)
			elif angle_mode == 0:
				try:
					result = math.tan(math.radians(Decimal(num)))
					hist = 'tan' + str(num) + '=' + str(result)
				except TypeError:
					result = cmath.tan(num)
					hist = 'tan' + str(num) + '=' + str(result)
			
		if arg == 'asin':
			if angle_mode == 1:
				try:
					result = math.asin(Decimal(num))
					hist = 'asin' + str(num) + '=' + str(result)
				except TypeError:
					result = cmath.asin(num)
					hist = 'asin' + str(num) + '=' + str(result)
			elif angle_mode == 0:
				try:
					result = math.asin(math.radians(Decimal(num)))
					hist = 'asin' + str(num) + '=' + str(result)
				except TypeError:
					result = cmath.asin(num)
					hist = 'asin' + str(num) + '=' + str(result)
		
		if arg == 'acos':
			if angle_mode == 1:
				try:
					result = math.acos(Decimal(num))
					hist = 'acos' + str(num) + '=' + str(result)
				except TypeError:
					result = cmath.acos(num)
					hist = 'acos' + str(num) + '=' + str(result)
			elif angle_mode == 0:
				try:
					result = math.acos(math.radians(Decimal(num)))
					hist = 'acos' + str(num) + '=' + str(result)
				except TypeError:
					result = cmath.acos(num)
					hist = 'acos' + str(num) + '=' + str(result)

		if arg == 'atan':
			if angle_mode == 1:
				try:
					result = math.atan(Decimal(num))
					hist = 'atan' + str(num) + '=' + str(result)
				except TypeError:
					result = cmath.atan(num)
					hist = 'atan' + str(num) + '=' + str(result)
			elif angle_mode == 0:
				try:
					result = math.atan(math.radians(Decimal(num)))
					hist = 'atan' + str(num) + '=' + str(result)
				except TypeError:
					result = cmath.atan(num)
					hist = 'atan' + str(num) + '=' + str(result)
			
		if arg == 'sinh':
			try:
				result = math.sinh(Decimal(num))
				hist = 'sinh' + str(num) + '=' + str(result)
			except TypeError:
				result = cmath.sinh(num)
				hist = 'sinh' + str(num) + '=' + str(result)
		
		if arg == 'cosh':
			try:
				result = math.cosh(Decimal(num))
				hist = 'cosh' + str(num) + '=' + str(result)
			except TypeError:
				result = cmath.cosh(num)
				hist = 'cosh' + str(num) + '=' + str(result)

		if arg == 'tanh':
			try:
				result = math.tanh(Decimal(num))
				hist = 'tanh' + str(num) + '=' + str(result)
			except TypeError:
				result = cmath.tanh(num)
				hist = 'tanh' + str(num) + '=' + str(result)
			
		if arg == 'asinh':
			try:
				result = math.asinh(Decimal(num))
				hist = 'asinh' + str(num) + '=' + str(result)
			except TypeError:
				result = cmath.asinh(num)
				hist = 'asinh' + str(num) + '=' + str(result)
		
		if arg == 'acosh':
			try:
				result = math.acosh(Decimal(num))
				hist = 'acosh' + str(num) + '=' + str(result)
			except TypeError:
				result = cmath.acosh(num)
				hist = 'acosh' + str(num) + '=' + str(result)

		if arg == 'atanh':
			try:
				result = math.atanh(Decimal(num))
				hist = 'atanh' + str(num) + '=' + str(result)
			except TypeError:
				result = cmath.atanh(num)
				hist = 'atanh' + str(num) + '=' + str(result)

		if arg == 'rect': #continue here....
			try:
				result = rect(last, num)
				hist = 'Convert ' + str(last) + ',' + str(num) + ' to rectangular coords.'

			except TypeError:
				result = 'Error'
				hist = 'Error in attempted conversion to rectangular coords.  No result.'

		if arg == 'polar':
			try:
				result = polar(num)
				hist = 'Convert ' + str(num) + ' to polar coords.'
			except TypeError:
				result = 'Error'
				hist = 'Error in attempted conversion to polar coords.  No result.'
		
			
		config.stack.append(result)
		history.append(hist)
		return config.stack
#=======================================================================================================================
#----Only argument passed-----------------------------------------------------------------------------------------------
#=======================================================================================================================
	elif option == None and num == None:
		last = config.stack.pop()
		if arg not in single_arg_funcs:
			try:
				n_minus1 = config.stack.pop()
			except IndexError:
				try:
					config.stack.append(Decimal(last))
				except TypeError:
					config.stack.append(last)
			except TypeError:
				config.stack.append(last)
			except Exception as e:
				return 'Error'

		if arg == '+':
			try:
				result = Decimal(n_minus1) + Decimal(last)
				hist = str(n_minus1) + '+' + str(last) + '=' + str(result)
			except TypeError:
				result = n_minus1 + last
				hist = str(n_minus1) + '+' + str(last) + '=' + str(result)
				
		if arg == '-':
			try:
				result = Decimal(n_minus1) -  Decimal(last)
				hist = str(n_minus1) + '-' + str(last) + '=' + str(result)
			except TypeError:
				result = n_minus1 - last
				hist = str(n_minus1) + '-' + str(last) + '=' + str(result)
				
		if arg == '*':
			try:
				result = Decimal(n_minus1) * Decimal(last)
				hist = str(n_minus1) + '*' + str(last) + '=' + str(result)
			except TypeError:
				result = n_minus1 * last
				hist = str(n_minus1) + '*' + str(last) + '=' + str(result)
				
		if arg == '/':
			try:
				result = Decimal(n_minus1) / Decimal(last)
				hist = str(n_minus1) + '/' + str(last) + '=' + str(result)
			except TypeError:
				result = n_minus1 / last
				hist = str(n_minus1) + '/' + str(last) + '=' + str(result)
				
		if arg == '!':
			try:
				result = Decimal(math.factorial(last))
				hist = str(last) + '!' '=' + str(result)
			except TypeError:
				result = math.factorial(last)
				hist = str(last) + '!' '=' + str(result)
			except OverflowError:
				config.stack.append(last)
				hist = str('Factorial overflow error, no result.')
				return 'Error'
				
		if arg == '**':
			try:
				result = pow(Decimal(last), Decimal(last))
				hist = str(n_minus1) + '**' + str(last) + '=' + str(result)
			except TypeError:
				result = last ** last
				hist = str(n_minus1) + '**' + str(last) + '=' + str(result)
				
		if arg == 'log':
			try:
				result = math.log10(Decimal(last))
				hist = str(last) +'log10' + '=' + str(result)
			except ValueError:
				result = cmath.log10(Decimal(last))
				hist = str(last) +'log10' + '=' + str(result)
			except TypeError:
				result = cmath.log10(last)
				hist = str(last) +'log10' + '=' + str(result)
		
		if arg == 'ln':
			try:
				result = math.log(Decimal(last))
				hist = str(last) +'ln' + '=' + str(result)
			except ValueError:
				result = cmath.log(Decimal(last))
				hist = str(last) +'ln' + '=' + str(result)
			except TypeError:
				result = cmath.log(last)
				hist = str(last) +'ln' + '=' + str(result)
			
		if arg == 'rt':
			try:
				result = root(Decimal(last), Decimal(n_minus1))
				hist = str(n_minus1) + 'root' + str(last) + '=' + str(result)
			except TypeError:
				result = root(last), (n_minus1)
				hist = str(n_minus1) + 'root' + str(last) + '=' + str(result)
				
		if arg == 'exp':
			try:
				result = math.exp(Decimal(last))
				hist = str(last) +'exp' + '=' + str(result)
			except TypeError:
				result = cmath.exp(last)
				hist = str(last) +'exp' + '=' + str(result)
			
				
		if arg == 'sqrt':
			try:
				result = math.sqrt(Decimal(last))
				hist = 'Square root of ' + str(last) + '=' + str(result)
			except ValueError:
				result = cmath.sqrt(Decimal(last))
				hist = 'Square root of ' + str(last) + '=' + str(result)
			except TypeError:
				result = cmath.sqrt(last)
				hist = 'Square root of ' + str(last) + '=' + str(result)
#----------Trig----------------------------------------				
		#--------TRIG--------------------------------
		if arg == 'sin':
			if angle_mode == 1:
				try:
					result = math.sin(Decimal(last))
					hist = 'sin' + str(last) + '=' + str(result)
				except TypeError:
					result = cmath.sin(last)
					hist = 'sin' + str(last) + '=' + str(result)
			elif angle_mode == 0:
				try:
					result = math.sin(math.radians(Decimal(last)))
					hist = 'sin' + str(last) + '=' + str(result)
				except TypeError:
					result = cmath.sin(last)
					hist = 'sin' + str(last) + '=' + str(result)
					
		if arg == 'cos':
			if angle_mode == 1:
				try:
					result = math.cos(Decimal(last))
					hist = 'cos' + str(last) + '=' + str(result)
				except TypeError:
					result = cmath.cos(last)
					hist = 'cos' + str(last) + '=' + str(result)
			elif angle_mode == 0:
				try:
					result = math.cos(math.radians(Decimal(last)))
					hist = 'cos' + str(last) + '=' + str(result)
				except TypeError:
					result = cmath.cos(last)
					hist = 'cos' + str(last) + '=' + str(result)
					
		if arg == 'tan':
			if angle_mode == 1:
				try:
					result = math.tan(Decimal(last))
					hist = 'tan' + str(last) + '=' + str(result)
				except TypeError:
					result = cmath.tan(last)
					hist = 'tan' + str(last) + '=' + str(result)
			elif angle_mode == 0:
				try:
					result = math.tan(math.radians(Decimal(last)))
					hist = 'tan' + str(last) + '=' + str(result)
				except TypeError:
					result = cmath.tan(last)
					hist = 'tan' + str(last) + '=' + str(result)
					
		if arg == 'asin':
			if angle_mode == 1:
				try:
					result = math.asin(Decimal(last))
					hist = 'asin' + str(last) + '=' + str(result)
				except TypeError:
					result = cmath.asin(last)
					hist = 'asin' + str(last) + '=' + str(result)
			elif angle_mode == 0:
				try:
					result = math.asin(math.radians(Decimal(last)))
					hist = 'asin' + str(last) + '=' + str(result)
				except TypeError:
					result = cmath.asin(last)
					hist = 'asin' + str(last) + '=' + str(result)
					
		if arg == 'acos':
			if angle_mode == 1:
				try:
					result = math.acos(Decimal(last))
					hist = 'acos' + str(last) + '=' + str(result)
				except TypeError:
					result = cmath.acos(last)
					hist = 'acos' + str(last) + '=' + str(result)
			elif angle_mode == 0:
				try:
					result = math.acos(math.radians(Decimal(last)))
					hist = 'acos' + str(last) + '=' + str(result)
				except TypeError:
					result = cmath.acos(last)
					hist = 'acos' + str(last) + '=' + str(result)

		if arg == 'atan':
			if angle_mode == 1:
				try:
					result = math.atan(Decimal(last))
					hist = 'atan' + str(last) + '=' + str(result)
				except TypeError:
					result = cmath.atan(last)
					hist = 'atan' + str(last) + '=' + str(result)
			elif angle_mode == 0:
				try:
					result = math.atan(math.radians(Decimal(last)))
					hist = 'atan' + str(last) + '=' + str(result)
				except TypeError:
					result = cmath.atan(last)
					hist = 'atan' + str(last) + '=' + str(result)
			
		if arg == 'sinh':
			try:
				result = math.sinh(Decimal(last))
				hist = 'sinh' + str(last) + '=' + str(result)
			except TypeError:
				result = math.sinh(last)
				hist = 'sinh' + str(last) + '=' + str(result)
		
		if arg == 'cosh':
			try:
				result = math.cosh(Decimal(last))
				hist = 'cosh' + str(last) + '=' + str(result)
			except TypeError:
				result = math.cosh(last)
				hist = 'cosh' + str(last) + '=' + str(result)

		if arg == 'tanh':
			try:
				result = math.tanh(Decimal(last))
				hist = 'tanh' + str(last) + '=' + str(result)
			except TypeError:
				result = math.tanh(last)
				hist = 'tanh' + str(last) + '=' + str(result)
			
		if arg == 'asinh':
			try:
				result = math.asinh(Decimal(last))
				hist = 'asinh' + str(last) + '=' + str(result)
			except TypeError:
				result = math.asinh(last)
				hist = 'asinh' + str(last) + '=' + str(result)
		
		if arg == 'acosh':
			try:
				result = math.acosh(Decimal(last))
				hist = 'acosh' + str(last) + '=' + str(result)
			except TypeError:
				result = math.acosh(last)
				hist = 'acosh' + str(last) + '=' + str(result)

		if arg == 'atanh':
			try:
				result = math.atanh(Decimal(last))
				hist = 'atanh' + str(last) + '=' + str(result)
			except TypeError:
				result = math.atanh(last)
				hist = 'atanh' + str(last) + '=' + str(result)
				
		if arg == 'rect': #continue here....
			try:
				result = rect(n_minus1, last)
				hist = 'Convert ' + str(n_minus1) + ',' + str(last) + ' to rectangular coords.'

			except TypeError:
				result = 'Error'
				hist = 'Error in attempted conversion to rectangular coords.  No result.'

		if arg == 'polar':
			try:
				result = polar(last)
				hist = 'Convert complex value ' + str(last) + ' to rectangular coords.'
			except TypeError:
				result = 'Error'
				hist = 'Error in attempted conversion to polar coords.  No result.'

		config.stack.append(result)
		history.append(hist)
		return config.stack
Ejemplo n.º 40
0
def arcosh(x):
    return cmath.acosh(x), False
Ejemplo n.º 41
0
 def arccosh(self):
     comp_value = cmath.acosh(self.comp_value)
     dx1 = cmath.sqrt(self.comp_value**2) - cmath.sqrt(1)
     dxr = 1 / dx1
     comp_unc = self.comp_unc * dxr  # if y = acosh(x) than U(y) = U(x) 1/sqrt(x^2-1)
     return Ucom(comp_value, comp_unc, self.name, self.dep)