Пример #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)
Пример #2
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)
Пример #3
0
def asinh(x):
    """
    Uncertain number hyperbolic arcsine function

    .. note::
    
        In the complex case there are two branch cuts: one extends
        from :math:`\mathrm{j}` along the imaginary axis to
        :math:`\mathrm{j}\infty`, continuous from the right;
        the other extends from :math:`-\mathrm{j}` along the
        imaginary axis to :math:`-\mathrm{j}\infty`, continuous
        from the left.
        
    """
    try:
        return x._asinh()
    except AttributeError:
        if isinstance(x,numbers.Real):
            return math.asinh(x)
        elif isinstance(x,numbers.Complex):
            return cmath.asinh(x)
        else:
            raise TypeError(
                "illegal argument: {!r}".format(x)
            )
Пример #4
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)
Пример #5
0
def op_asinh(x):
    """Returns the inverse hyperbolic sine of this mathematical object."""
    if isinstance(x, list):
        return [op_asinh(a) for a in x]
    elif isinstance(x, complex):
        return cmath.asinh(x)
    else:
        return math.asinh(x)
Пример #6
0
    def test_every_phi(phi):
        # https://dlmf.nist.gov/19.6.E8
        assert nice_and_close(ellipkinc(phi, 1), asinh(tan(phi)))

        # https://dlmf.nist.gov/19.6.E9, line 4
        assert nice_and_close(ellipeinc(phi, 1), sin(phi))
        #
        # https://dlmf.nist.gov/19.6.E11, line 3
        assert nice_and_close(ellippiinc(1, phi, 0), tan(phi))
Пример #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])
Пример #8
0
def ASINH(df, price='Close'):
    """
    Inverse Hyperbolic Sine
    """
    asinh_list = []
    i = 0
    while i < len(df[price]):
        asinh = cmath.asinh(df[price][i]).real
        asinh_list.append(asinh)
        i += 1
    return asinh_list
Пример #9
0
def asinh(z):
    """ An AlComplex compatible hyperbolic arcsine function. It gets the main value.

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

        Returns
        -------
        AlComplex
    """
    return AlComplex.from_python_complex(cm.asinh(z.to_python_complex()))
Пример #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)
Пример #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)
Пример #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
         }, {})
Пример #13
0
def FitsImageFromData(fits_data, xsize, ysize, contrast="percentile", contrast_opts={},
                      scale="linear", scale_opts={}):

    if contrast not in ("zscale", "percentile"):
        raise ValueError("invalid contrast algorithm '%s'" % contrast)
    if scale not in ("linear", "arcsinh"):
        raise ValueError("invalid scale value '%s'" % scale)

    # compute the proper scaling for the image
    if contrast == "zscale":
        contrast_value = contrast_opts.get("contrast", 0.25)
        num_points = contrast_opts.get("num_points", 600)
        num_per_row = contrast_opts.get("num_per_row", 120)
        zmin, zmax = zscale_range(fits_data, contrast=contrast_value,
                                  num_points=num_points,
                                  num_per_row=num_per_row)
    elif contrast == "percentile":
        min_percent = contrast_opts.get("min_percent", 3.0)
        max_percent = contrast_opts.get("max_percent", 99.0)
        num_points = contrast_opts.get("num_points", 5000)
        num_per_row = contrast_opts.get("num_per_row", 250)
        zmin, zmax = percentile_range(fits_data, min_percent=min_percent,
                                      max_percent=max_percent,
                                      num_points=num_points,
                                      num_per_row=num_per_row)

    # set all points less than zmin to zmin and points greater than
    # zmax to zmax
    fits_data = numpy.where(numpy.isfinite(fits_data), fits_data, zmin)
    fits_data = numpy.where(fits_data > zmin, fits_data, zmin)
    fits_data = numpy.where(fits_data < zmax, fits_data, zmax)

    if scale == "linear":
        scaled_data = (fits_data - zmin) * (255.0 / (zmax - zmin)) + 0.5
    elif scale == "arcsinh":
        # nonlinearity sets the range over which we sample values of the
        # asinh function; values near 0 are linear and values near infinity
        # are logarithmic
        nonlinearity = scale_opts.get("nonlinearity", 3.0)
        nonlinearity = max(nonlinearity, 0.001)
        max_asinh = cmath.asinh(nonlinearity).real
        scaled_data = (255.0 / max_asinh) * \
                      (numpy.arcsinh((fits_data - zmin) * \
                                     (nonlinearity / (zmax - zmin))))

    # convert to 8 bit unsigned int ("b" in numpy)
    scaled_data = scaled_data.astype("b")

    # create the image
    image = Image.frombuffer("L", (xsize, ysize), scaled_data, "raw", "L", 0, 1)
    return image
Пример #14
0
def asinh(x):
    """
    Return the inverse hyperbolic sine 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 = asinh(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 [asinh(xi) for xi in x]
#        except TypeError:
        if x.imag:
            return cmath.asinh(x)
        else:
            return math.asinh(x.real)
Пример #15
0
def asinh(x):
    """
    Return the inverse hyperbolic sine 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 = asinh(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 [asinh(xi) for xi in x]
        #        except TypeError:
        if x.imag:
            return cmath.asinh(x)
        else:
            return math.asinh(x.real)
Пример #16
0
    def OnInit(self):
        self.SettingsFile = "props.pickle"
        self.Properties = PropertySet()
        self.Name = "app choices"
        self.leftUp = True
        self.rightUp = False
        self.Properties.append(
            ChoiceProperty("left tube up", self.SetLeftTube, self.GetLeftTube))
        self.Properties.append(
            ChoiceProperty("right tube up", self.SetRightTube,
                           self.GetRightTube))
        'Create the main window and insert the custom frame'
        domain = [-0, 10, .1]
        backdrop = Backdrop(((0, cmath.asinh(-10).real, 0), (10, 4, 10)))
        self.twist = ParametricSurface(domain, LeftUp, RightDown)
        if self.leftUp:
            upTube = LineTube(LeftUp, domain)
        else:
            upTube = LineTube(LeftDown, domain)
        if self.rightUp:
            downTube = LineTube(RightUp, domain)
        else:
            downTube = LineTube(RightDown, domain)

        self.twist.Name = "twist surface"
        upTube.Name = "left tube"
        downTube.Name = "right tube"
        backdrop.Name = "backdrop"
        self.pipelines = [self.twist, upTube, downTube, backdrop, self]
        window = VTKFrame()
        appMenu = AppMenu(window, self, self.pipelines)
        window.AddActor(self.twist.GetActor())
        window.AddActor(upTube.GetActor())
        window.AddActor(downTube.GetActor())
        backActors = backdrop.GetActor()
        self.window = window
        window.AddActor(backActors[0])
        window.AddActor(backActors[1])
        self.LoadProperties()
        #frame.Show(True)
        return True
Пример #17
0
def ParametricDown(t):
    return [t, cmath.asinh(-t).real, -2]
Пример #18
0
def ParametricUp(t):
    return [t, cmath.asinh(t).real, 2]
Пример #19
0
def asinh_usecase(x):
    return cmath.asinh(x)
Пример #20
0
  for i in range(len(matching_files)):
    #print matching_files[i],
    if var2_list[i]==v2:
      d2 = get_EV(matching_files[i])
      if 'tw-1' in sys.argv and d2.data['tw']!=0:
        nfacy = d2.data['tw']
      evals = d2.evals
      evalsr = evals.real  #Only for initialization to the right size
      for j in range(len(evals)):
        if 'lin' in sys.argv:
          if 'err' in sys.argv:
            evalsr[j] = Numeric.sum(d2.BCerror)
          else:
            evalsr[j] = (evals[j]**2).real
        else:
          evalsr[j] = cmath.asinh(scale_fac*(evals[j]**2).real).real
      if minevalsr > min(evalsr):
        minevalsr = min(evalsr)
      if maxevalsr < max(evalsr):
        maxevalsr = max(evalsr)
      if ttl:
        g._add_to_queue([Gnuplot.Data([var_list[i]]*len(evalsr),evalsr,with='points %i '%k,title='%s=%g'%(var_key2,v2))])
        g1._add_to_queue([Gnuplot.Data([var_list[i]]*len(evalsr),nfacy*evals.imag,with='points  %i'%k,title='%s=%g'%(var_key2,v2))])
        ttl = False
      else:
        g._add_to_queue([Gnuplot.Data([var_list[i]]*len(evalsr),evalsr,with='points %i '%k)])
        g1._add_to_queue([Gnuplot.Data([var_list[i]]*len(evalsr),nfacy*evals.imag,with='points %i'%k)])
  k = k+1
#for i in range(len(matching_files)):
  #print matching_files[i],':',var_list[i],';  ',
print matching_files
Пример #21
0
    def doPhotons(self, filePar):
        self.initHTML()

        #f = ROOT.TFile('ntuple.root')
        #f.cd('CollectionTree')
        #mytree=ROOT.gDirectory.Get('CollectionTree')

        ##################################
        #os.system('ls photons/*root* > ntuples.txt')
        os.system('ls nt*root > ntuples.txt')
        f = open('ntuples.txt', 'r')
        lines = f.readlines()
        f.close()

        chain = ROOT.TChain('CollectionTree')

        for li in lines:
            chain.Add('./' + li.strip())

        mytree = chain
        #################################

        m_drmin = ROOT.TH1F("m_drmin", "drmin", 100, -0.2, 0.2)
        m_h1 = ROOT.TH1F("m_h1", "Energy resolution", 100, -0.25, 0.25)
        m_h1.SetXTitle("(E_{t}(reco)-E_{t}(true))/E_{t}(true)")

        m_h2 = ROOT.TH1F("m_h2", "Phi resolution", 100, -0.01, 0.01)
        m_h2.SetXTitle("#Phi resolution (rad)")

        m_h3 = ROOT.TH1F("m_h3", "Eta resolution in the barrel", 100, -0.01,
                         0.01)
        m_h3.SetXTitle("#eta resolution")

        m_h4 = ROOT.TH1F("m_h4", "Eta resolution in the endcap", 100, -0.01,
                         0.01)
        m_h4.SetXTitle("#eta resolution")

        m_h5 = ROOT.TH1F("m_h5", "Efficiency vs eta", 50, -3, 3)
        m_h5.SetXTitle("#eta")

        m_tmp1 = ROOT.TH1F("m_tmp1", "EtaGen", 50, -3, 3)
        m_tmp2 = ROOT.TH1F("m_tmp2", "cl_eta", 50, -3, 3)

        entries = mytree.GetEntriesFast()

        for jentry in xrange(entries):
            ientry = mytree.LoadTree(jentry)
            if ientry < 0:
                break

            nb = mytree.GetEntry(jentry)
            if nb <= 0:
                continue

            nEvent = int(mytree.IEvent)
            if nEvent < 0:
                continue

            dRmin = 999.
            TheNearestCluster = -1
            for i in range(0, int(mytree.cl_nc)):
                dphi = 1000.
                deta = 1000.

                # resolution in energy
                val = ((mytree.cl_et)[i] -
                       (mytree.PtGen)[0]) / (mytree.PtGen)[0]

                m_h1.Fill(val)
                # resolution in phi
                if (mytree.cl_phi)[i] - (mytree.PhiGen)[0] < 6:
                    dphi = ((mytree.cl_phi)[i] - (mytree.PhiGen)[0])
                    m_h2.Fill(dphi)

                # resolution in eta barrel corrected by the z vertex spread
                deta = 0.
                if math.fabs((mytree.EtaGen)[0]) < 1.475:
                    deta = (mytree.cl_eta)[i] - cmath.asinh(
                        cmath.sinh((mytree.EtaGen)[0]) +
                        (mytree.ZV)[mytree.IVPrimary] / 1600.)
                    m_h3.Fill(deta.real)
                elif math.fabs((mytree.EtaGen)[0]) >= 1.475:
                    deta = (mytree.cl_eta)[i] - cmath.asinh(
                        cmath.sinh((mytree.EtaGen)[0]) /
                        (1 - self.mysign((mytree.EtaGen)[0]) *
                         (mytree.ZV)[mytree.IVPrimary] / 3800.))

                    m_h4.Fill(deta.real)

                if (math.fabs(dphi) > math.pi):
                    dphi = 2.0 * math.pi - math.fabs(dphi)
                dR = math.sqrt(deta.real * deta.real + dphi * dphi)
                if dR < dRmin:
                    dRmin = dR
                    TheNearestCluster = i

            m_tmp2.Fill((mytree.EtaGen)[0])
            if TheNearestCluster >= 0 and dRmin < 0.1:
                m_tmp1.Fill((mytree.EtaGen)[0])

        ROOT.gStyle.SetOptFit(1011)

        m_h1.Fit("gaus")
        m_h2.Fit("gaus")
        m_h3.Fit("gaus")
        m_h4.Fit("gaus")

        res1 = self.saveHisto(m_h1, filePar, '')
        res2 = self.saveHisto(m_h2, filePar, '')
        res3 = self.saveHisto(m_h3, filePar, '')
        res4 = self.saveHisto(m_h4, filePar, '')
        m_h5.Divide(m_tmp1, m_tmp2, 1, 1, "B")

        res5 = self.saveHisto(m_h5, filePar, "E")

        if res1 == -1 or res2 == -1 or res3 == -1 or res4 == -1 or res5 == -1:
            return -1
        else:
            return 0
Пример #22
0
    def doElectrons(self, filePar):
        self.initHTML()

        #f = ROOT.TFile('ntuple.root')
        #f.cd('CollectionTree')
        #mytree=ROOT.gDirectory.Get('CollectionTree')

        ##################################
        #os.system('ls data/*root.* > ntuples.txt')
        os.system('ls nt*root > ntuples.txt')

        f = open('ntuples.txt', 'r')
        lines = f.readlines()
        f.close()

        chain = ROOT.TChain('CollectionTree')

        for li in lines:
            chain.Add('./' + li.strip())

        mytree = chain
        #################################

        m_drmin = ROOT.TH1F("m_drmin", "drmin", 100, -0.2, 0.2)
        m_h1 = ROOT.TH1F("m_h1", "Energy resolution", 100, -0.25, 0.25)
        m_h1.SetXTitle("(E_{t}(reco)-E_{t}(true))/E_{t}(true)")

        m_h2 = ROOT.TH1F("m_h2", "Phi resolution", 100, -0.01, 0.01)
        m_h2.SetXTitle("#Phi resolution (rad)")

        m_h3 = ROOT.TH1F("m_h3", "Eta resolution in the barrel", 100, -0.01,
                         0.01)
        m_h3.SetXTitle("#eta resolution")

        m_h4 = ROOT.TH1F("m_h4", "Eta resolution in the endcap", 100, -0.01,
                         0.01)
        m_h4.SetXTitle("#eta resolution")

        m_h5 = ROOT.TH1F("m_h5", "Efficiency vs eta", 50, -3, 3)
        m_h5.SetXTitle("#eta")

        m_tmp1 = ROOT.TH1F("m_tmp1", "EtaGen", 50, -3, 3)
        m_tmp2 = ROOT.TH1F("m_tmp2", "cl_eta", 50, -3, 3)

        entries = mytree.GetEntriesFast()

        for jentry in xrange(entries):
            ientry = mytree.LoadTree(jentry)
            if ientry < 0:
                break

            nb = mytree.GetEntry(jentry)
            if nb <= 0:
                continue

            nEvent = int(mytree.IEvent)
            if nEvent < 0:
                continue

            indEle = []
            iele = 0
            for ipart in range(0, mytree.NPar):
                if abs((mytree.Type)[ipart]) == 11 and (
                        mytree.GenStat)[ipart] == 1 and (
                            mytree.KMothNt)[ipart] == -1:
                    indEle.append(ipart)
                    m_tmp2.Fill((mytree.EtaGen)[indEle[iele]])

                    iele += 1

                    if iele > 1:
                        logger.info('two many electrons')
                        return -1

            nele = iele

            # a quel cluster correspond quel electron ?
            # je tourne sur ts les clusters de l ev
            for ic in range(0, mytree.cl_nc):
                etacl = (mytree.cl_eta)[ic]
                phicl = (mytree.cl_phi)[ic]
                etcl = (mytree.cl_et)[ic]

                m_drmin.Fill((mytree.ZV)[0])
                etae = (mytree.EtaGen)[indEle[0]]
                if math.fabs((mytree.cl_eta)[ic]) > 1.475:
                    etaclcor = cmath.asinh(
                        cmath.sinh((mytree.cl_eta)[ic]) *
                        (1 - (mytree.ZV)[mytree.IVPrimary] / (self.mysign(
                            (mytree.cl_eta)[ic]) * 3800.0)))
                    phiclcor = (mytree.cl_phi)[ic] + (
                        0.3 * 3800.0 *
                        (-(mytree.Type)[indEle[0]] / 11.0) * self.mysign(
                            (mytree.cl_eta)[ic])) / (
                                (mytree.cl_et)[ic] * cmath.sinh(
                                    (mytree.cl_eta)[ic]))
                    m_h4.Fill((etaclcor - etae).real)
                else:
                    etaclcor = cmath.asinh(
                        cmath.sinh((mytree.cl_eta)[ic]) -
                        (mytree.ZV)[mytree.IVPrimary] / 1600.0)
                    m_h3.Fill((etaclcor - etae).real)
                    phiclcor = (mytree.cl_phi)[ic] + (
                        0.3 * 1600.0 * (-(mytree.Type)[indEle[0]] / 11.0) /
                        (mytree.cl_et)[ic])

                phie = (mytree.PhiGen)[indEle[0]]
                ete = (mytree.PtGen)[indEle[0]]

                try:
                    m_h2.Fill(phiclcor.real - phie)
                except:
                    m_h2.Fill(phiclcor - phie)
                m_h1.Fill((etcl - ete) / ete)

                m_tmp1.Fill(etae)

        ROOT.gStyle.SetOptFit(1011)

        m_h1.Fit("gaus")
        m_h2.Fit("gaus")
        m_h3.Fit("gaus")
        m_h4.Fit("gaus")

        res1 = self.saveHisto(m_h1, filePar, '')
        res2 = self.saveHisto(m_h2, filePar, '')
        res3 = self.saveHisto(m_h3, filePar, '')
        res4 = self.saveHisto(m_h4, filePar, '')
        m_h5.Divide(m_tmp1, m_tmp2, 1, 1, "B")

        res5 = self.saveHisto(m_h5, filePar, "E")

        if res1 == -1 or res2 == -1 or res3 == -1 or res4 == -1 or res5 == -1:
            return -1
        else:
            return 0
Пример #23
0
def FitsImage(fitsfile, contrast="zscale", contrast_opts={}, scale="linear",
              scale_opts={}, mask=None):

    """
    Constructor-like function that returns a Python Imaging Library (PIL)
    Image object.  This allows extremely easy and powerful manipulation of
    FITs files as images.  The contrast is automatically adjusted using the
    zscale algorithm (see zscale_range() above).

    Input:  fitsfile      -- a FITS image filename
            contrast      -- the algorithm for determining the min/max
                             values in the FITS pixel data to use when
                             compressing the dynamic range of the FITS
                             data to something visible by the eye, either
                             "zscale" or "percentile"
            contrast_opts -- options for the contrast algorithm, see
                             the optional args of [contrast]_range()
                             for what to name the keys
            scale         -- how to scale the pixel values between the
                             min/max values from the contrast
                             algorithm when converting to a a raster
                             format, either "linear" or "arcsinh"
            scale_opts    -- options for the scaling algorithm, currently
                             only "nonlinearity" is supported for arcsinh,
                             which has a default value of 3
    """

    if contrast not in ("zscale", "percentile"):
        raise ValueError("invalid contrast algorithm '%s'" % contrast)
    if scale not in ("linear", "arcsinh"):
        raise ValueError("invalid scale value '%s'" % scale)

    # open the fits file and read the image data and size
    #fitslib.fits_simple_verify(fitsfile)
    fits = pyfits.open(fitsfile)

    try:
        hdr = fits[0].header
        xsize = hdr["NAXIS1"]
        ysize = hdr["NAXIS2"]
        fits_data = fits[0].data
    finally:
        fits.close()
    
    # compute the proper scaling for the image
    if contrast == "zscale":
        contrast_value = contrast_opts.get("contrast", 0.25)
        num_points = contrast_opts.get("num_points", 600)
        num_per_row = contrast_opts.get("num_per_row", 120)
        zmin, zmax = zscale_range(fits_data, contrast=contrast_value,
                                  num_points=num_points,
                                  num_per_row=num_per_row, mask=mask)
    elif contrast == "percentile":
        min_percent = contrast_opts.get("min_percent", 3.0)
        max_percent = contrast_opts.get("max_percent", 99.0)
        num_points = contrast_opts.get("num_points", 5000)
        num_per_row = contrast_opts.get("num_per_row", 250)
        zmin, zmax = percentile_range(fits_data, min_percent=min_percent,
                                      max_percent=max_percent,
                                      num_points=num_points,
                                      num_per_row=num_per_row, mask=mask)

    # set all points less than zmin to zmin and points greater than
    # zmax to zmax
    fits_data = numpy.where(fits_data > zmin, fits_data, zmin)
    fits_data = numpy.where(fits_data < zmax, fits_data, zmax)

    if scale == "linear":
        scaled_data = (fits_data - zmin) * (255.0 / (zmax - zmin)) + 0.5
    elif scale == "arcsinh":
        # nonlinearity sets the range over which we sample values of the
        # asinh function; values near 0 are linear and values near infinity
        # are logarithmic
        nonlinearity = scale_opts.get("nonlinearity", 3.0)
        nonlinearity = max(nonlinearity, 0.001)
        max_asinh = cmath.asinh(nonlinearity).real
        scaled_data = (255.0 / max_asinh) * \
                      (numpy.arcsinh((fits_data - zmin) * \
                                     (nonlinearity / (zmax - zmin))))

    # convert to 8 bit unsigned int ("b" in numpy)
    scaled_data = scaled_data.astype("b")
    
    # create the image
    image = Image.frombuffer("L", (xsize, ysize), scaled_data)
    return image
Пример #24
0
 def asin_impl(z):
     """cmath.asin(z) = -j * cmath.asinh(z j)"""
     r = cmath.asinh(complex(-z.imag, z.real))
     return complex(r.imag, -r.real)
Пример #25
0
def create_expression():
    """This function takes no arguments and returns an expression that
    generates a number between -1.0 and 1.0, given x and y coordinates."""
    expr15 = lambda x: math.sin(pi*x)
    expr14 = lambda x: math.cos(pi*x)
    expr13 = lambda x: math.atan(x)
    expr12 = lambda x: 1/(1+x) if x != -1 else 1

    expr11 = lambda x: random.choice([x.real, x.imag])
    expr10 = lambda x: abs(x)

    expr9 = lambda x: cmath.asin(pi*x)
    expr8 = lambda x: x*cmath.asinh(1j*x.real - x.imag)
    expr7 = lambda x: (1j-x)*(1j+x) if x != -1j else 1/(1-x)
    expr6 = lambda x: (1+x)/(1-x) if x !=1 else 1/(1+x)

    ave = lambda x,y: (x+y)/2
    unave = lambda x,y: (x-y)/2

    expr5 = lambda x,y:  (x+1j*y)*cmath.exp(1j*random.uniform(-.5,.5))
    expr4 = lambda x,y: (x+y)/2
    expr3 = lambda x,y: (x-y)/2
    expr2 = lambda x,y: random.choice([x,y])
    expr1 = lambda x,y: x*y

    list_1 = [expr1, expr2, expr3, expr4, expr5] # real/complex, 2 -> 2
    list_2 = [expr6, expr7, expr8, expr9] # real/complex 1 -> 1
    list_3 = [expr12, expr13, expr14, expr15] # real 1 -> 1
    reals = [expr10, expr11] # complex -> real, 1 -> 1


    num_start = random.randint(1,10)
    num_choices = random.randint(1,10)
    num_real = random.randint(1,10)
    start = []
    choices = []
    final = []

    average = random.choice([ave, unave]) # averages or not...
    real = random.choice(reals) # makes it real

    for _ in range(num_start):
        start.append((random.choice(list_1), random.choice(list_1)))

    for _ in range(num_choices):
        choices.append(random.choice(list_2))

    for _ in range(num_real):
        final.append(random.choice(list_3))




    def returner(x, y):
        start_x, start_y = x, y


        for item1, item2 in start:
            start_x, start_y = item1(start_x, start_y), item2(start_y, start_x)

        num = average(start_x, start_y)

        for item in choices:
            num = item(num)

        num = real(num)

        for item in final:
            num = item(num)

        return num

    return returner
Пример #26
0
def RightUp(t):
    s = t - 5
    return [t, cmath.asinh(2 * s).real, 0]
Пример #27
0
def LeftUp(t):
    s = t - 5
    return [0, cmath.asinh(2 * s).real, t]
print('log10(c) =', cmath.log10(c))
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
Пример #29
0
 def asin_impl(z):
     """cmath.asin(z) = -j * cmath.asinh(z j)"""
     r = cmath.asinh(complex(-z.imag, z.real))
     return complex(r.imag, -r.real)
Пример #30
0
def asinh(a, b):
    result = a**2 + b**2
    return cmath.asinh(result) + 1.6j
Пример #31
0
                    'ln': lambda x: cmath.log(x), 
                    '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    
import math
import cmath

# ACMI Line's electrical parameters
# See Table VI in the manuscript for parameters definitions
L = 2.440e-6
R = 0.986
w0 = 2 * cmath.pi * 13.56e6
Q = w0 * L / R
k = 0.09267  # Nominal Rx coupling at 65-mm height
kRx55 = 0.119768
kRx65 = k
kRx75 = 0.070197
Zo = w0 * k * L  # Characteristic impedance at w0 and no loss
X = 1j * Zo  # Positive Mutual impedance between adjacent cells
alphaD = cmath.asinh(1 / (2 * k * Q))
betaD = cmath.pi / 2  # Assumming operation at resonance
GammaD = alphaD + 1j * betaD
RL = Zo  # Set Rx's load resistance to Zo
#Zs = Zo + 1i*2*Zo;              # Initially set Zs to conjugate if Zo, then changed
# to conjugate of average Zin
Zs = 22.4574 + 1j * 35.5804  # Conjugate of average Zin: use this for
# recalculation efficiency and normalized power
Zm = (w0 * kRx65 * L)**2 / (RL + R)  # Change kRx- for different height here
ZLeff = Zm * RL / (RL + R)  # Effective power delivered to RL

# Settings of coupling polarties and Zmi in vector form
# Zcell = [Zm1 Zm2 ... ZM] <-- modify fixed impedance at each cell here
#                              for reactive termination and multi-loads
# ucell = [u1 u2 ... uM] <-- modify coupling polarities here
Zcell_cw = [0, 0, 0, 0, 0, 0, 0]
Пример #33
0
def asinh(a, b):
    result = a**2 + b**2
    return cmath.asinh(result) + 1.6j
Пример #34
0
def asinh_usecase(x):
    return cmath.asinh(x)
Пример #35
0
    def doTop(self, filePar):
        self.initHTML()

        f = ROOT.TFile('ntuple.root')
        f.cd('CollectionTree')
        mytree = ROOT.gDirectory.Get('CollectionTree')

        m_drmin = ROOT.TH1F("m_drmin", "drmin", 100, -0.2, 0.2)
        m_h1 = ROOT.TH1F("m_h1", "Energy resolution", 100, -0.25, 0.25)
        m_h1.SetXTitle("(E_{t}(reco)-E_{t}(true))/E_{t}(true)")

        m_h2 = ROOT.TH1F("m_h2", "Phi resolution", 100, -0.01, 0.01)
        m_h2.SetXTitle("#Phi resolution (rad)")

        m_h3 = ROOT.TH1F("m_h3", "Eta resolution in the barrel", 100, -0.01,
                         0.01)
        m_h3.SetXTitle("#eta resolution")

        m_h4 = ROOT.TH1F("m_h4", "Eta resolution in the endcap", 100, -0.01,
                         0.01)
        m_h4.SetXTitle("#eta resolution")

        m_h5 = ROOT.TH1F("m_h5", "Efficiency vs eta", 50, -3, 3)
        m_h5.SetXTitle("#eta")

        m_tmp1 = ROOT.TH1F("m_tmp1", "EtaGen", 50, -3, 3)
        m_tmp2 = ROOT.TH1F("m_tmp2", "cl_eta", 50, -3, 3)

        entries = mytree.GetEntriesFast()

        for jentry in xrange(entries):
            ientry = mytree.LoadTree(jentry)
            if ientry < 0:
                break

            nb = mytree.GetEntry(jentry)
            if nb <= 0:
                continue

            nEvent = int(mytree.IEvent)
            if nEvent < 0:
                continue

            indEle = []
            iele = 0
            for ipart in range(0, mytree.NPar):
                if abs((mytree.Type)[ipart]) == 11 and abs(
                    (mytree.Type)[(mytree.KMothNt)[ipart]]) == 24:
                    #indEle[iele]=ipart
                    indEle.append(ipart)
                    m_tmp2.Fill((mytree.EtaGen)[indEle[iele]])
                    iele = +1
                    if iele > 4:
                        logger.info('two many electrons')
                        return -1

            nele = iele

            # a quel cluster correspond quel electron ?
            # je tourne sur ts les clusters de l ev
            for ic in range(0, mytree.cl_nc):
                drmin = 9999.
                im = 0

                # pour un cluster donne je tourne sur tous les electrons primaires trouves precedemment et je minimise dr pour savoir celui qui est le plus pres du cluster
                for iele in range(0, nele):
                    deta = (mytree.EtaGen)[indEle[iele]] - (mytree.cl_eta)[ic]
                    dphi = (mytree.PhiGen)[indEle[iele]] - (mytree.cl_phi)[ic]

                    if dphi > math.pi:
                        dphi = math.fabs(dphi) - 2. * math.pi
                    dr = math.sqrt(dphi * dphi + deta * deta)

                    if dr < drmin:
                        drmin = dr
                        im = iele

                # l'electron matchant le cluster a l'indice im

                m_drmin.Fill(drmin)

                if drmin < 0.1:
                    etacl = (mytree.cl_eta)[ic]
                    phicl = (mytree.cl_phi)[ic]
                    etcl = (mytree.cl_et)[ic]
                    etae = (mytree.EtaGen)[indEle[im]]
                    if math.fabs((mytree.cl_eta)[ic]) > 1.475:
                        etaclcor = cmath.asinh(
                            cmath.sinh((mytree.cl_eta)[ic]) *
                            (1 - (mytree.ZV)[mytree.IVPrimary] / (self.mysign(
                                (mytree.cl_eta)[ic]) * 3800.0)))
                        phiclcor = (mytree.cl_phi)[ic] + (
                            0.3 * 3800 *
                            (-(mytree.Type)[indEle[im]] / 11.0) * self.mysign(
                                (mytree.cl_eta)[ic])) / (
                                    (mytree.cl_et)[ic] * cmath.sinh(
                                        (mytree.cl_eta)[ic]))
                        m_h4.Fill((etaclcor - etae).real)
                    else:
                        etaclcor = cmath.asinh(
                            cmath.sinh((mytree.cl_eta)[ic]) -
                            (mytree.ZV)[mytree.IVPrimary] / 1600.0)
                        phiclcor = (mytree.cl_phi)[ic] + (
                            0.3 * 1600.0 *
                            (-(mytree.Type)[indEle[im]] / 11.0) /
                            (mytree.cl_et)[ic])
                        m_h3.Fill((etaclcor - etae).real)

                    phie = (mytree.PhiGen)[indEle[im]]
                    ete = (mytree.PtGen)[indEle[im]]

                    try:
                        m_h2.Fill(phiclcor.real - phie)
                    except:
                        m_h2.Fill(phiclcor - phie)
                    m_h1.Fill((etcl - ete) / ete)
                    m_tmp1.Fill(etae)

        ROOT.gStyle.SetOptFit(1011)

        m_h1.Fit("gaus")
        m_h2.Fit("gaus")
        m_h3.Fit("gaus")
        m_h4.Fit("gaus")

        res1 = self.saveHisto(m_h1, filePar, '')
        res2 = self.saveHisto(m_h2, filePar, '')
        res3 = self.saveHisto(m_h3, filePar, '')
        res4 = self.saveHisto(m_h4, filePar, '')
        m_h5.Divide(m_tmp1, m_tmp2, 1, 1, "B")

        res5 = self.saveHisto(m_h5, filePar, "E")

        if res1 == -1 or res2 == -1 or res3 == -1 or res4 == -1 or res5 == -1:
            return -1
        else:
            return 0
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
assert abs(round(0.25,1) - 0.3) < 1e-14
Пример #37
0
 def test_asinh(self):
     self.assertAlmostEqual(complex(2.29991, 0.917617),
                            cmath.asinh(complex(3, 4)))
Пример #38
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
Пример #39
0
def LeftDown(t):
    s = t - 5
    return [0, cmath.asinh(-2 * s).real, t]
Пример #40
0
 except:
     continue
 foldMarkThisScore = False
 if markFold:
     tempscore = score
     if tempscore == 0:
         tempscore = 0.03
     tempratio = newscore / tempscore
     if tempratio == 0:
         tempratio2 = tempscore / 0.03
     else:
         tempratio2 = 1. / tempratio
     if tempratio > foldChange or tempratio2 > foldChange:
         foldMarkThisScore = True
 if doArcsinh:
     score = abs(cmath.asinh(score))
 elif doLogF1:
     #if score < 1.0:
     #    score = 1.0
     #    #continue
     try:
         score = math.log(score, base)
     except:
         score = forcexmin
     if score > xmax:
         xmax = score
 if doArcsinh:
     newscore = abs(cmath.asinh(newscore))
 elif doLogF2:
     #newscore += 1
     #if newscore < 1.0:
Пример #41
0
def RightDown(t):
    s = t - 5
    return [t, cmath.asinh(-2 * s).real, 0]
Пример #42
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))