Exemplo n.º 1
0
    def test_acosh(self):
        import math

        self.ftest(math.acosh(1), 0)
        self.ftest(math.acosh(2), 1.3169578969248168)
        assert math.isinf(math.asinh(float("inf")))
        raises(ValueError, math.acosh, 0)
Exemplo n.º 2
0
  def test_funcs_multi(self):
    pi = math.pi

    # sin family
    self.assertQuantity(data.sin(Quantity( (0,pi/2), (2,2))), (0,1), (2,0)) 
    self.assertQuantity(data.sinh(Quantity((0,1), (2,2))), (0, math.sinh(1)), (2, math.cosh(1)*2)) 
    self.assertQuantity(data.asin(Quantity((0,0.5), (2,2))), (0,math.asin(0.5)), (2,2/math.sqrt(1-0.5**2))) 
    self.assertQuantity(data.asinh(Quantity((0,1), (2,2))), (0,math.asinh(1)), (2,2/math.sqrt(1+1**2))) 

    # cos family
    self.assertQuantity(data.cos(Quantity((0,pi/2), (2,2))), (1,0), (0,-2)) 
    self.assertQuantity(data.cosh(Quantity((0,1), (2,2))), (1,math.cosh(1)), (0,math.sinh(1)*2)) 
    self.assertQuantity(data.acos(Quantity((0,0.5), (2,2))), (math.acos(0),math.acos(0.5)), (-2,-2/math.sqrt(1-0.5**2)))
    self.assertQuantity(data.acosh(Quantity((2,3), (2,2))), (math.acosh(2), math.acosh(3)), (2/math.sqrt(2**2-1),2/math.sqrt(3**2-1)))

    # tan family
    self.assertQuantity(data.tan(Quantity((0,1), (2,2))), (0,math.tan(1)), (2,2/math.cos(1)**2))
    self.assertQuantity(data.tanh(Quantity((0,1), (2,2))), (0,math.tanh(1)), (2,2/math.cosh(1)**2)) 
    self.assertQuantity(data.atan(Quantity((0,1), (2,2))), (0, math.atan(1)), (2,2/(1+1**2))) 
    self.assertQuantity(data.atan2(Quantity((0,1), (2,2)), Quantity((1,1), (0,0))), (0,math.atan(1)), (2,2/(1+1**2))) 
    self.assertQuantity(data.atanh(Quantity((0,0.5), (2,2))), (0,math.atanh(0.5)), (2,2/(1-0.5**2)))

    #misc
    self.assertQuantity(data.sqrt(Quantity((1,4), (2,2))), (1,2), (1,1/2))
    self.assertQuantity(data.exp(Quantity((1,4), (2,2))), (math.e, math.e**4), (2 * math.e,2*math.e**4))
    self.assertQuantity(data.log(Quantity((1,4), (2,2))), (0, math.log(4)), (2,1/2))
Exemplo n.º 3
0
def cheb(f,n,e):
    if abs(f)<1:
        t=math.cos(float(n)*math.acos(float(f)))
    elif f>=1:
        t=math.cosh(float(n)*math.acosh(float(f)))
    elif f<=-1:
       t=-1**n*math.cosh(float(n)*math.acosh(float(-f)))
    return 1.0/(float(float(1.0+float(e**2)*float(t**2)))**.5)
Exemplo n.º 4
0
 def testAcosh(self):
     self.assertRaises(TypeError, math.acosh)
     self.ftest('acosh(1)', math.acosh(1), 0)
     self.ftest('acosh(2)', math.acosh(2), 1.3169578969248168)
     self.assertRaises(ValueError, math.acosh, 0)
     self.assertRaises(ValueError, math.acosh, -1)
     self.assertEquals(math.acosh(INF), INF)
     self.assertRaises(ValueError, math.acosh, NINF)
     self.assert_(math.isnan(math.acosh(NAN)))
Exemplo n.º 5
0
def hexagon_sides(a, b, c):
    cosha, coshb, coshc = map(math.cosh, [a, b, c])
    sinha, sinhb, sinhc = map(math.sinh, [a, b, c])
    sides = [a,
             math.acosh((cosha * coshb + coshc) / (sinha * sinhb)),
             b,
             math.acosh((coshb * coshc + cosha) / (sinhb * sinhc)),
             c,
             math.acosh((coshc * cosha + coshb) / (sinhc * sinha))]
    return sides
Exemplo n.º 6
0
 def __init__(self, S, a, metal, dielec):
     '''\n
     S: center-to-center conductor separation, [unit: m]\n
     a: conductor radius, [unit: m]\n
     metal: conductor material, [unit: material]\n
     dielec: dielectric material between conductors, [unit: material]'''        
     
     self.S = S
     self.a = a
     self.sigma = cond(metal)
     self.eps = dielec_const(dielec)
     self.mu  = 1*spc.mu_0 # mu_r = 1
     self.L   = self.mu*math.acosh(S/(2*a))/math.pi
     self.C = math.pi*self.eps.real/math.acosh(S/(2*a))
Exemplo n.º 7
0
def hyperbolic_fun_cal(inp_val1, opn_type):
     oprn_dic = {
        '1': 'inverse hyperbolic cosine of x', '2':'inverse hyperbolic sine of x',
        '3':' inverse hyperbolic tangent of x', '4':'hyperbolic cosine of x',
        '5':'hyperbolic sine of x', '6':'hyperbolic tangent of x'}
     if int(opn_type) == 1:
         output = math.acosh(float(inp_val1))
         return str(output)
     if int(opn_type) == 2:
         output = math.asinh(float(inp_val1))
         return str(output)
     if int(opn_type) == 3:
         output = math.atanh(float(inp_val1))
         return str(output)
     if int(opn_type) == 4:
         output = math.cosh(float(inp_val1))
         return str(output)
     if int(opn_type) == 5:
         output = math.sinh(float(inp_val1))
         return str(output)
     if int(opn_type) == 6:
         output = math.tanh(float(inp_val1))
         return str(output)
     else:
         return "Invalid Operation"
Exemplo n.º 8
0
    def cosh_const_effective_mass_errors(self, dt):

        jkasv = self.jackknife_average_sub_vev()
        jkemass = {}
        for cfg in self.configs:
            asvc = jkasv[cfg]
            emass = {}
            asvct = {t: asvc[t+dt] - asvc[t] for t in self.times[:-dt]}
            for t in self.times[dt:-(dt+1)]:
                if t in self.emass_skip_times:
                    emass[t] = 0.0
                    continue
                try:
                    emass[t] = (1.0 / float(dt))*math.acosh((asvc[t+dt] + asvc[t-dt])/(2.0*asvc[t]))
                except ValueError:
                    #logging.debug("invalid argument to log, setting to zero")
                    emass[t] = 0.0
                except ZeroDivisionError:
                    logging.debug("div by zero, setting to zero")
                    emass[t] = 0.0
                except KeyError:
                    logging.error("index out of range")
            jkemass[cfg] = emass
        jkemassobj = configtimeobj.Cfgtimeobj.fromDataDict(jkemass)
        effmass_dt = self.cosh_const_effective_mass(dt)
        return {t: jackknife.errorbars(effmass_dt[t], jkemassobj.get(time=t))
                for t in self.times[dt:-(dt+dt)]}
Exemplo n.º 9
0
    def cosh_effective_mass_errors(self, dt, fast=True, period=None):
        if fast: logging.info("cosh emass computed fast method")
        period = self.period
        T = self.period_check(period)

        jkasv = self.jackknife_average_sub_vev()
        jkemass = {}
        for cfg in self.configs:
            asvc = jkasv[cfg]
            emass = {}
            for t in self.times[dt:-dt]:
                if t in self.emass_skip_times:
                    emass[t] = 0.0
                    continue

                try:
                    guess = (1.0 / float(dt))*math.acosh((asvc[t+dt] + asvc[t-dt])/(2.0*asvc[t]))
                    if fast:
                        emass[t] = guess
                    else:
                        emass[t] = newton.newton_cosh_for_m(t,t+dt,asvc, guess,T)
                except ValueError:
                    #logging.debug("invalid argument to log, setting to zero")
                    emass[t] = 0.0
                except ZeroDivisionError:
                    logging.debug("div by zero, setting to zero")
                    emass[t] = 0.0
                except KeyError:
                    logging.error("index out of range")
            jkemass[cfg] = emass
        jkemassobj = configtimeobj.Cfgtimeobj.fromDataDict(jkemass)
        effmass_dt = self.cosh_effective_mass(dt, fast=fast, period=period)
        return {t: jackknife.errorbars(effmass_dt[t], jkemassobj.get(time=t))
                for t in self.times[dt:-dt]}
Exemplo n.º 10
0
    def compute(self, plug, data):

        #   Check if output value is connected
        if plug == self.aOutputVaue:

            #    Get input datas
            operationTypeHandle = data.inputValue(self.aOperationType)
            operationType = operationTypeHandle.asInt()

            inputValueHandle = data.inputValue(self.aInputValue)
            inputValue = inputValueHandle.asFloat()

            #   Math Cosinus
            outputValue = 0
            if operationType == 0:
                outputValue = math.acos(inputValue)
            if operationType == 1:
                outputValue = math.cos(inputValue)
            if operationType == 2:
                outputValue = math.acosh(inputValue)
            if operationType == 3:
                outputValue = math.cosh(inputValue)

            #   Output Value
            output_data = data.outputValue(self.aOutputVaue)
            output_data.setFloat(outputValue)

        #   Clean plug
        data.setClean(plug)
Exemplo n.º 11
0
    def cosh_effective_mass(self, dt, fast=True, period=None):
        if fast: logging.info("cosh emass computed fast method")

        T = self.period_check(period)
        asv = self.average_sub_vev()
        emass = {}
        for t in self.times[dt:-dt]:
            if t in self.emass_skip_times:
                emass[t] = 0.0
                continue
            try:
                guess = (1.0 / float(dt))*math.acosh((asv[t+dt] + asv[t-dt])/(2.0*asv[t]))
                if fast:
                    emass[t] = guess
                else:
                    emass[t] = newton.newton_cosh_for_m(t,t+dt,asv, guess, T)
            except ValueError:
                logging.debug("invalid argument to acosh, setting to zero")
                emass[t] = float('NaN')
            except KeyError:
                logging.error("index out of range")
            except ZeroDivisionError:
                logging.error("Div by zero either dt:{} or average value sub vev {}".format(dt,asv[t]))
                emass[t] = float('NaN')
        return emass
Exemplo n.º 12
0
def pmuboost3d(jets, met, lep):
    mw = 80.385
    wwwtlv = ROOT.TLorentzVector(1e-9,1e-9,1e-9,1e-9)
    mettlv = ROOT.TLorentzVector(1e-9,1e-9,1e-9,1e-9)
    leptlv = ROOT.TLorentzVector(1e-9,1e-9,1e-9,1e-9)
    for jet in jets:
#        if(e.jetPt[ij] > 30.):
            tlvaux = ROOT.TLorentzVector(1e-9,1e-9,1e-9,1e-9)
            tlvaux.SetPtEtaPhiM(jet['pt'],0.,jet['phi'],0.)
            wwwtlv -= tlvaux
    mettlv.SetPtEtaPhiM(met['pt'],0.,met['phi'],0.)
    leptlv.SetPtEtaPhiM(lep['pt'],lep['eta'],lep['phi'], 0.)
#    leptlv.SetPtEtaPhiM(e.muPt[0],e.muEta[0],e.muPhi[0],0.)
# calculate eta(W) estimate; take the + solution
    ptl = (wwwtlv - mettlv).Pt()
    ptn = mettlv.Pt()
    ptw = wwwtlv.Pt()
    etal = leptlv.Eta()
    A = (mw*mw + ptw*ptw - ptl*ptl - ptn*ptn) / (2.*ptl*ptn)
    if(A<1.): A=1.
    etaw = asinh((ptl*sinh(etal)+ptn*sinh(etal+acosh(A)))/ptw)
    if(abs(etaw)>10.): etaw=10*etaw/abs(etaw) # avoid too large values
    wwwtlv.SetPtEtaPhiM(wwwtlv.Pt(),etaw,wwwtlv.Phi(),mw)
# calulate boosted lepton momentum
    beta = wwwtlv.BoostVector()
    leptlv.Boost(-beta)
    return leptlv.P()
Exemplo n.º 13
0
    def test_arccosh(self):
        import math
        from _numpypy import arccosh

        for v in [1.0, 1.1, 2]:
            assert math.acosh(v) == arccosh(v)
        for v in [-1.0, 0, .99]:
            assert math.isnan(arccosh(v))
def chebyParam(n, r):
    n = float(n)
    r = float(r)
    iterator = math.cosh(1 / n * math.acosh(r))
    a = ((iterator - 1) / 2).real
    b = ((iterator + 1) / 2).real
    # returns the list of chebyshev's parameters
    return [a, b]
Exemplo n.º 15
0
def acosh(space, d):
    """ acosh - Inverse hyperbolic cosine """
    try:
        return space.wrap(math.acosh(d))
    except OverflowError:
        return space.wrap(rfloat.INFINITY)
    except ValueError:
        return space.wrap(rfloat.NAN)
Exemplo n.º 16
0
 def startingTime(self):
     angle = self.launchAngle
     F = math.acosh((self.e+math.cos(angle))/(1.0+self.e*math.cos(angle)))
     M = self.e*math.sinh(F)-F
     ht = pow(pow(self.apoapsis,3.0)/self.gm, .5) * M
     if angle>0:
         return -ht
     else:
         return ht
Exemplo n.º 17
0
    def testArithmeticFunctionsDeepcopy(self):
        data = {'x': 1}

        test = Exp('x')
        test.push(data)
        copied = copy.deepcopy(test)
        self.assertAlmostEqual(math.exp(data['x']), copied.value)

        test = Log('x')
        test.push(data)
        copied = copy.deepcopy(test)
        self.assertAlmostEqual(math.log(data['x']), copied.value)

        test = Sqrt('x')
        test.push(data)
        copied = copy.deepcopy(test)
        self.assertAlmostEqual(math.sqrt(data['x']), copied.value)

        data['x'] = -1.

        test = Pow('x', 2)
        test.push(data)
        copied = copy.deepcopy(test)
        self.assertAlmostEqual(data['x']**2, copied.value)

        test = Abs('x')
        test.push(data)
        copied = copy.deepcopy(test)
        self.assertAlmostEqual(abs(data['x']), copied.value)

        test = Sign('x')
        test.push(data)
        copied = copy.deepcopy(test)
        self.assertAlmostEqual(-1., copied.value)

        data['x'] = 1.

        test = Acos('x')
        test.push(data)
        copied = copy.deepcopy(test)
        self.assertAlmostEqual(math.acos(data['x']), copied.value)

        test = Asin('x')
        test.push(data)
        copied = copy.deepcopy(test)
        self.assertAlmostEqual(math.asin(data['x']), copied.value)

        test = Acosh('x')
        test.push(data)
        copied = copy.deepcopy(test)
        self.assertAlmostEqual(math.acosh(data['x']), copied.value)

        test = Asinh('x')
        test.push(data)
        copied = copy.deepcopy(test)
        self.assertAlmostEqual(math.asinh(data['x']), copied.value)
Exemplo n.º 18
0
    def operator(self, tok):
        """ Return operator handler if tok is a valid operator. Otherwise return False. """
        def stacksum(stack):
            """ Return sum of all elements on stack (++ operator). """
            acc = 0
            while stack:
                acc += stack.pop()
            return acc

        def stackproduct(stack):
            """ Return product of all elements on stack (** operator). """
            acc = 1
            while stack:
                acc *= stack.pop()
            return acc

        # Operator handlers.
        operators = {
            '++': stacksum,
            '**': stackproduct,
            '+': lambda stack: stack.pop(-2) + stack.pop(),
            '-': lambda stack: stack.pop(-2) - stack.pop(),
            '*': lambda stack: stack.pop(-2) * stack.pop(),
            '/': lambda stack: stack.pop(-2) / stack.pop(),
            '%': lambda stack: stack.pop(-2) % stack.pop(),
            '^': lambda stack: stack.pop(-2) ** stack.pop(),
            '!': lambda stack: math.factorial(stack.pop()),
            'ln': lambda stack: math.log(stack.pop()),
            'log': lambda stack: math.log(stack.pop(-2), stack.pop()),
            'log2': lambda stack: math.log(stack.pop(), 2),
            'log10': lambda stack: math.log(stack.pop(), 10),
            'rand': lambda stack: random.random(),
            'sqrt': lambda stack: math.sqrt(stack.pop()),
            'exp': lambda stack: math.exp(stack.pop()),
            'sin': lambda stack: math.sin(stack.pop()),
            'cos': lambda stack: math.cos(stack.pop()),
            'tan': lambda stack: math.tan(stack.pop()),
            'sinh': lambda stack: math.sinh(stack.pop()),
            'cosh': lambda stack: math.cosh(stack.pop()),
            'tanh': lambda stack: math.tanh(stack.pop()),
            'arcsin': lambda stack: math.asin(stack.pop()),
            'arccos': lambda stack: math.acos(stack.pop()),
            'arctan': lambda stack: math.atan(stack.pop()),
            'arcsinh': lambda stack: math.asinh(stack.pop()),
            'arccosh': lambda stack: math.acosh(stack.pop()),
            'arctanh': lambda stack: math.atanh(stack.pop()),
            'max': lambda stack: max(stack.pop(), stack.pop()),
            'min': lambda stack: min(stack.pop(), stack.pop()),
            'abs': lambda stack: abs(stack.pop()),
            'ans': lambda stack: self.ans,
        }

        # Return operation handler if exists, otherwise return False.
        if tok in operators:
            return operators[tok]
        return False
Exemplo n.º 19
0
 def acosh(a=(DataTypes.Float, 0.0), Result=(DataTypes.Reference, (DataTypes.Bool, False))):
     '''
     Return the inverse hyperbolic cosine of x
     '''
     try:
         Result(True)
         return math.acosh(a)
     except:
         Result(False)
         return -1
Exemplo n.º 20
0
def acosh(num):
    value = math.acosh(num.value)
    string = "\\text{arccosh} " + enclose(num.string)
    string_nums = "\\text{arccosh} " + enclose(rstr(num.value))
    error = num.error / math.sqrt(num.value**2 - 1)
    error_vars = fraction("1", root(square(enclose(num.string)) + " - 1")) \
            + PRODUCT + diff(num.string)
    error_nums = fraction("1", root(square(rstr(num.value)) + " - 1")) \
            + PRODUCT + rstr(num.value)
    return Number(value, string, error, string_nums, error_vars, error_nums)
Exemplo n.º 21
0
def native_disk_distance(r_1, theta_1, r_2, theta_2):
    if r_1 == r_2 and theta_1 == theta_2:
        return 0
    d_phi = pi - abs(pi - abs(theta_1 - theta_2))
    if d_phi == 0:
        return r_1 + r_2
    elif d_phi == pi:
        return abs(r_2 - r_1)
    else:
        return acosh(cosh(r_1)*cosh(r_2) - sinh(r_1)*sinh(r_2)*cos(d_phi))
Exemplo n.º 22
0
def ACOSH(value):
    """
  Returns the inverse hyperbolic cosine of a number.

  >>> ACOSH(1)
  0.0
  >>> round(ACOSH(10), 7)
  2.9932228
  """
    return _math.acosh(value)
Exemplo n.º 23
0
def poincareDist(a, b):
    # print(a,b)
    try:
        sigma = norm(np.subtract(a, b))**2.0 / ((1 - np.dot(a, a)) *
                                                (1 - np.dot(b, b)))
        return math.acosh(1 + 2 * sigma)
    except ValueError as e:
        print(a)
        print(b)
        raise (e)
Exemplo n.º 24
0
def acosh(column):
    i = 0
    column = mt.convert_num_col(column)
    result = list()
    while i < len(column):
        if (column[i] >= 1):
            result.insert(i + 1, math.acosh(column[i]))
        else:
            result.insert(i + 1, "Error de dominio")
        i += 1
    return result
Exemplo n.º 25
0
def check_rapidity_allowed(S123,PperpSquared,y):
	"""A function to check if the rapidity is in the allowed region of phase space."""
	##Using equation 49 of Initial-state showering based on colour dipoles connected to incoming parton lines.
	assert (type(S123) == float)
	assert (type(PperpSquared) == float)
	assert (type(y) == float)
	__yMagMax = math.acosh(math.sqrt(S123/PperpSquared)/2.0)
	if (abs(y) > __yMagMax):
		return False
	else:
		return True
Exemplo n.º 26
0
def st_acosh(x):
    """Inverse hyperbolic cosine function.
    
    Parameters
    ----------
    x : float, int, MissingValue instance, or None
    
    Returns
    -------
    Inverse hyperbolic cosine when x is non-missing and x >= 1,
    MISSING (".") otherwise
    
    """
    if isinstance(x, StataVarVals):
        return StataVarVals([
            mv if _is_missing(v) or v < 1 else math.acosh(v) for v in x.values
        ])
    if _is_missing(x) or x < 1:
        return mv
    return math.acosh(x)
Exemplo n.º 27
0
def check_rapidity_allowed(S123, PperpSquared, y):
    """A function to check if the rapidity is in the allowed region of phase space."""
    ##Using equation 49 of Initial-state showering based on colour dipoles connected to incoming parton lines.
    assert (type(S123) == float)
    assert (type(PperpSquared) == float)
    assert (type(y) == float)
    __yMagMax = math.acosh(math.sqrt(S123 / PperpSquared) / 2.0)
    if (abs(y) > __yMagMax):
        return False
    else:
        return True
Exemplo n.º 28
0
def func_arcosh(x):
    """Return arcosh(x) where the answer is in radians"""

    # invalid cases
    if x < 1:
        raise CalcOperationError(
            "Inverse hyperbolic cosine is undefined for values less than 1",
            "arcosh", [x])

    # use the function from the 'math' library
    return acosh(x)
Exemplo n.º 29
0
 def execute(self, table, tree):
     super().execute(table, tree)
     exp = self.exp.execute(table, tree)
     try:
         return math.acosh(exp)
     except ValueError:
         raise (Error(self.line, self.column, ErrorType.SEMANTIC, 'ValueError: Math domain error.'))
     except TypeError:
         raise (Error(self.line, self.column, ErrorType.SEMANTIC,
                      'TypeError: must be real number, not ' + str(type(exp))))
     except:
         raise (Error(self.line, self.column, ErrorType.SEMANTIC, 'ACOSH() function argument error'))
Exemplo n.º 30
0
    def calcCubeExp(self, A, B, C):
        '''Решение кубического уравнения тригонометрической формулой Виета
        x^3+Ax^2+Bx+C=0
        '''
        def sgn(x):
            if x > 0:
                return 1
            if x == 0:
                return 0
            if x < 0:
                return -1

        x1 = 'null'
        x2 = 'null'
        x3 = 'null'
        Q = (A * A - 3 * B) / 9
        R = (2 * A * A * A - 9 * A * B + 27 * C) / 54
        S = Q * Q * Q - R * R
        if S > 0:
            fi = 1 / 3 * math.acos(R / math.pow(Q, 3 / 2))
            x1 = -2 * math.sqrt(Q) * math.cos(fi) - A / 3
            if x1 < 0:
                x1 = 'null'
            x2 = -2 * math.sqrt(Q) * math.cos(fi + 2 / 3 * 3.14) - A / 3
            if x2 < 0:
                x2 = 'null'
            x3 = -2 * math.sqrt(Q) * math.cos(fi - 2 / 3 * 3.14) - A / 3
            if x3 < 0:
                x3 = 'null'
        if S < 0:
            if Q > 0:
                fi = 1 / 3 * math.acosh(abs(R) / math.pow(Q, 3 / 2))
                x1 = -2 * sgn(R) * math.sqrt(Q) * math.cosh(fi) - A / 3
                if x1 < 0:
                    x1 = 'null'
            if Q < 0:
                sss = abs(R) / math.pow(abs(Q), 3 / 2)
                fi = 1 / 3 * math.asinh(sss)
                x1 = -2 * sgn(R) * math.sqrt(abs(Q)) * math.sinh(fi) - A / 3
                if x1 < 0:
                    x1 = 'null'
            if Q == 0:
                x1 = -math.pow(C - A * A * A / 27, 1 / 3) - A / 3
                if x1 < 0:
                    x1 = 'null'
        if S == 0:
            x1 = -2 * sgn(R) * math.sqrt(Q) - A / 3
            if x1 < 0:
                x1 = 'null'
            x2 = sgn(R) * math.sqrt(Q) - A / 3
            if x2 < 0:
                x2 = 'null'
        return x1, x2, x3
Exemplo n.º 31
0
def acosh(input):
    """Coseno inverso hiperbólico

    Evalúa el coseno inverso hiperbólico a un número real enviado en input y arroja un resultado en radianes.

    Args:
        input(Number): valor real
    
    Returns:
        Number
    """
    return math.acosh(input)
Exemplo n.º 32
0
def kubik_uravn(a, b, c, d):
    div_a = a
    a = b / div_a
    b = c / div_a
    c = d / div_a
    # x^3 + a*x^2 + b*x + c
    q = (a**2 - 3 * b) / 9
    r = (2 * a**3 - 9 * a * b + 27 * c) / 54
    s = q**3 - r**2
    if s > 0:
        fi = 1 / 3 * math.acos(r / (q**3)**(1 / 2))
        x1 = -2 * q**(1 / 2) * math.cos(fi) - a / 3
        x2 = -2 * q**(1 / 2) * math.cos(fi + 2 / 3 * math.pi) - a / 3
        x3 = -2 * q**(1 / 2) * math.cos(fi - 2 / 3 * math.pi) - a / 3
        print('S = %s, Q = %s, R = %s, sgn(R) = %s' % (s, q, r, sgn(r)))
        return x1, x2, x3
    elif s < 0:
        if q > 0:
            fi = 1 / 3 * math.acosh(abs(r) / ((q**3)**(1 / 2)))
            x1 = -2 * sgn(r) * q**(1 / 2) * math.cosh(fi) - a / 3
            x2 = complex(
                sgn(r) * q**(1 / 2) * math.cosh(fi) - a / 3,
                3**(1 / 2) * q**(1 / 2) * math.sinh(fi))
            x3 = complex(
                sgn(r) * q**(1 / 2) * math.cosh(fi) - a / 3,
                -3**(1 / 2) * q**(1 / 2) * math.sinh(fi))
            print('S = %s, Q = %s, R = %s, sgn(R) = %s' % (s, q, r, sgn(r)))
            return x1, x2, x3
        if q < 0:
            fi = math.asinh(abs(r) / (abs(q**3)**(1 / 2)))
            x1 = -2 * sgn(r) * abs(q)**(1 / 2) * math.sinh(fi) - a / 3
            x2 = complex(
                sgn(r) * abs(q)**(1 / 2) * math.sinh(fi) - a / 3,
                3**(1 / 2) * abs(q)**(1 / 2) * math.cosh(fi))
            x3 = complex(
                sgn(r) * abs(q)**(1 / 2) * math.sinh(fi) - a / 3,
                -3**(1 / 2) * abs(q)**(1 / 2) * math.cosh(fi))
            print('S = %s, Q = %s, R = %s, sgn(R) = %s' % (s, q, r, sgn(r)))
            return x1, x2, x3
        if q == 0:
            x1 = -rootodd(c - a**3 / 27, 3) - a / 3
            x2 = complex(-(a + x1) / 2,
                         1 / 2 * abs((a - 3 * x1) * (a + x1) - 4 * b)**(1 / 2))
            x3 = complex(
                -(a + x1) / 2,
                -1 / 2 * abs((a - 3 * x1) * (a + x1) - 4 * b)**(1 / 2))
            print('S = %s, Q = %s, R = %s, sgn(R) = %s' % (s, q, r, sgn(r)))
            return x1, x2, x3
    elif s == 0:
        x1 = -2 * sgn(r) * q**(1 / 2) - a / 3  # -2*rootodd(r, 3) - a/3
        x2 = sgn(r) * q**(1 / 2) - a / 3  # rootodd(r, 3) - a/3
        print('S = %s, Q = %s, R = %s, sgn(R) = %s' % (s, q, r, sgn(r)))
        return x1, x2
def chebyParamOptimized(n, r, k0):
    n = float(n)
    r = float(r)
    iterator = math.cosh(1 / n * math.acosh(r))
    a = ((iterator - 1) / 2).real
    b = ((iterator + 1) / 2).real
    optimized_dist = (2 * math.pi - math.acos((1 - a) / b)) / k0
    output = open("valori_a_b.txt", "a")
    output.write(" a = " + str(a) + " b = " + str(b) + "  N = " + str(n * 2 + 1) + "\n")
    output.close()
    print("N=" + str(n * 2 + 1) + "  d=" + str(optimized_dist))
    return [a, b, optimized_dist]
Exemplo n.º 34
0
def st_acosh(x):
    """Inverse hyperbolic cosine function.
    
    Parameters
    ----------
    x : float, int, MissingValue instance, or None
    
    Returns
    -------
    Inverse hyperbolic cosine when x is non-missing and x >= 1,
    MISSING (".") otherwise
    
    """
    if isinstance(x, StataVarVals):
        return StataVarVals([
            mv if _is_missing(v) or v < 1
            else math.acosh(v) for v in x.values
        ])
    if _is_missing(x) or x < 1:
        return mv
    return math.acosh(x)
Exemplo n.º 35
0
def chebyParamOptimized(n, r, k0):
    n = float(n)
    r = float(r)
    iterator = math.cosh(1 / n * math.acosh(r))
    a = ((iterator - 1) / 2).real
    b = ((iterator + 1) / 2).real
    optimized_dist = (2 * math.pi - math.acos((1 - a) / b)) / k0
    output = open("valori_a_b.txt", 'a')
    output.write(" a = " + str(a) + " b = " + str(b) + "  N = " +
                 str(n * 2 + 1) + "\n")
    output.close()
    print("N=" + str(n * 2 + 1) + "  d=" + str(optimized_dist))
    return [a, b, optimized_dist]
Exemplo n.º 36
0
    def acosh(self):
        '''
        Method to perform element-wise inverse hyperbolic cosine in radians
        on the vector.

        @return: result vector as a list.
        '''
        try:
            values = [math.acosh(x) for x in self.values]
        except:
            raise VectorError('Failure in Vector.acosh()')
        self.values = values
        return self.values
Exemplo n.º 37
0
def chebyschev_lowpass(f_pass, f_stop, tol_pass, tol_stop):
    """
    Returns the Chebyschev analog lowpass filter function corresponding to
    passband and stopband frequencies and tolerances.

    Inputs:
    - f_pass: The passband boundary frequency in Hz
    - f_stop: The stopband boundary frequency in Hz
    - tol_pass: The tolerance required in the passband
    - tol_stop: The tolerance required in the stopband.

    Returns a function that takes a frequency (in Hz) as input and returns
    the filter magnitude at that frequency as the output.
    """

    if f_pass == f_stop:
        raise ValueError(
            'The passband and stopband frequencies cannot be equal.')

    if tol_pass == 0 or tol_stop == 0:
        raise ValueError('Tolerance values cannot be zero.')

    D1 = 1 / (1 - tol_pass)**2 - 1
    D2 = 1 / tol_stop**2 - 1

    # Optimal epsilon to get minimum N possible
    # epsilon = math.sqrt(D1)

    # Minimum order of the filter that is required
    # (Note that D1 is the same as epsilon**2)
    N = math.acosh(D2 / D1) / math.acosh(f_stop / f_pass)
    N = math.ceil(N)

    def filter_func(f):
        # Note that D1 is the same as epsilon**2
        mag2 = 1 / (1 + D1 * chebyshev_polynomial(f / f_pass, N)**2)
        return math.sqrt(mag2)

    return filter_func
Exemplo n.º 38
0
    def __init__(self, a: float, b: float, x_max: float, n: int):
        t_max = acosh(x_max / a)
        dt = t_max / (n - 1)

        cf = cosh(dt)
        sf = sinh(dt)

        a_b = float(a) / b
        sf_a_b = sf * a_b
        sf_b_a = sf / a_b

        super().__init__(1, 0, lambda x, y: x * cf + y * sf_a_b,
                         lambda x, y: x * sf_b_a + y * cf, n, False)
Exemplo n.º 39
0
def to_prolate_spheroidal(coords):
    focus = 0.3525E+02
    x = coords[0]
    y = coords[1]
    z = coords[2]

    theta = math.atan(z / y)
    mu = math.acos(1 / (2 * focus) * ((y * y + z * z + (x + focus)**2)**0.5 -
                                      (y * y + z * z + (x - focus)**2)**0.5))
    lam = math.acosh(1 / (2 * focus) * ((y * y + z * z + (x + focus)**2)**0.5 +
                                        (y * y + z * z + (x - focus)**2)**0.5))

    return ([lam, mu, theta])
Exemplo n.º 40
0
def hyperbola(a, b, begin, end, n):
    th_min = m.acosh(1.0 * begin / a)
    th_max = m.acosh(1.0 * end / a)
    delta_theta = (th_max - th_min) / (n - 1)
    start = [a * m.cosh(th_min), b * m.sinh(th_min)]

    points = [start]

    cosh = m.cosh(delta_theta)
    sinh = m.sinh(delta_theta)

    for i in range(1, n):
        xi, yi = points[i - 1]
        new_point = [
            xi * cosh + yi * a / b * sinh, a / b * xi * sinh + yi * cosh
        ]
        points.append(new_point)

    points_rev = [[p[0], -p[1]] for p in reversed(points)]
    points = points_rev + points
    points_rev = [[-p[0], p[1]] for p in reversed(points)]

    return np.array(points + points_rev)
Exemplo n.º 41
0
 def acosh_click(self, event):
     try:
         self.txt_box1.SetForegroundColour('Default')
         self.txt_box1.SetValue(
             str(math.acosh(eval(self.txt_box.GetValue()))))
     except ZeroDivisionError:
         self.txt_box1.SetForegroundColour('red')
         self.txt_box1.SetValue(u'除数为0,请重新输入!')
     except SyntaxError:
         self.txt_box1.SetForegroundColour('red')
         self.txt_box1.SetValue(u'输入算式错误,请重新输入!')
     except ValueError:
         self.txt_box1.SetForegroundColour('red')
         self.txt_box1.SetValue(u'输入值错误,不能运算,请重新输入!')
Exemplo n.º 42
0
def hyperbolicDistance(vector1, vector2):
    if (len(vector1) != num_dimensions):
        print("error vector1")
    if (len(vector2) != num_dimensions):
        print("error vector2")
    L2Distance = findL2Distance(vector1, vector2)

    vector1norm = findL2Norm(vector1)
    vector2norm = findL2Norm(vector2)

    inside = 1 + (2 * np.square(L2Distance)) / ((1 - np.square(vector1norm)) *
                                                (1 - np.square(vector2norm)))

    return math.acosh(inside)
Exemplo n.º 43
0
 def resolverFuncionTrigonometrica(self, nodo, resultado):
     if nodo.valor.lower() == 'acos':
         a = self.expresion_aritmetica(nodo.hijos[0], [], [], [])
         c = math.acos(a)
         resultado.append(c)
     elif nodo.valor.lower() == 'asin':
         a = self.expresion_aritmetica(nodo.hijos[0], [], [], [])
         c = math.asin(a)
         resultado.append(c)
     elif nodo.valor.lower() == 'atan':
         a = self.expresion_aritmetica(nodo.hijos[0], [], [], [])
         c = math.atan(a)
         resultado.append(c)
     elif nodo.valor.lower() == 'cos':
         a = self.expresion_aritmetica(nodo.hijos[0], [], [], [])
         c = math.cos(a)
         resultado.append(c)
     elif nodo.valor.lower() == 'sin':
         a = self.expresion_aritmetica(nodo.hijos[0], [], [], [])
         c = math.sin(a)
         resultado.append(c)
     elif nodo.valor.lower() == 'tan':
         a = self.expresion_aritmetica(nodo.hijos[0], [], [], [])
         c = math.tan(a)
         resultado.append(c)
     elif nodo.valor.lower() == 'sinh':
         a = self.expresion_aritmetica(nodo.hijos[0], [], [], [])
         c = math.sinh(a)
         resultado.append(c)
     elif nodo.valor.lower() == 'cosh':
         a = self.expresion_aritmetica(nodo.hijos[0], [], [], [])
         c = math.cosh(a)
         resultado.append(c)
     elif nodo.valor.lower() == 'tanh':
         a = self.expresion_aritmetica(nodo.hijos[0], [], [], [])
         c = math.tanh(a)
         resultado.append(c)
     elif nodo.valor.lower() == 'asinh':
         a = self.expresion_aritmetica(nodo.hijos[0], [], [], [])
         c = math.asinh(a)
         resultado.append(c)
     elif nodo.valor.lower() == 'acosh':
         a = self.expresion_aritmetica(nodo.hijos[0], [], [], [])
         c = math.acosh(a)
         resultado.append(c)
     elif nodo.valor.lower() == 'atanh':
         a = self.expresion_aritmetica(nodo.hijos[0], [], [], [])
         print(a)
         c = math.atanh(a)
         resultado.append(c)
Exemplo n.º 44
0
def calc_order(Apmax, Asmin, wp, ws):
    """
    Parameters:
    Apmax - maximum passand loss
    Asmin - minimum stopband loss
    wp - passband frequency
    ws - stopband frequency
    
    ----
    output: order of the required chebyshev filter
    """

    n = 0
    A = calc_epsilon(Asmin) / calc_epsilon(Apmax)
    omega = ws/wp

    if omega > 1:
        n = math.acosh(A)/math.acosh(omega)
    else:
        n = math.acos(A)/math.acos(omega)

    n = math.ceil(n)
    return n
Exemplo n.º 45
0
def acosh(column):
    i = 0
    column = mt.convert_num_col(column)
    result = list()
    while i < len(column):
        if isinstance(column[i], int) or isinstance(column[i], float):
            if column[i] >= 1:
                result.append(math.acosh(column[i]))
            else:
                result.append("Error de dominio")
                list_errors_tg.append("Error: 22003: la entrada esta fuera del dominio")
        else:
            result.append(column[i])
        i += 1
    return result
Exemplo n.º 46
0
    def compute_eff_energies(self, eff_en_type):

        for k in range(self.corrs.shape[0]):
            self.eff_energies.append( [] )
            for j in range(self.corrs.shape[1]-1):
            #for j in range(self.corrs.shape[1]/2):

                if eff_en_type=="exp":
                    self.eff_energies[len(self.eff_energies)-1].append( log( self.corrs[k,j]/self.corrs[k,j+1] ) )
                elif eff_en_type=="3pt":
                    self.eff_energies[len(self.eff_energies)-1].append( acosh( (self.corrs[k,j+1]+self.corrs[k,j-1]) / (2*self.corrs[k,j]) ) )
                else:
                    raise Exception("Effective energy type not available.")

        self.eff_energies = np.array(self.eff_energies)
Exemplo n.º 47
0
def getHyperbolicDistance(sourceNode, destNode):
    """
    Return hyperbolic or geohyperbolic distance between two nodes. The distance is computed
    on the basis of following algorithm/mathematics
    ref: https://en.wikipedia.org/wiki/Hyperbolic_geometry
    """
    r1 = [key for key in sourceNode][0]
    r2 = [key for key in destNode][0]
    zeta = 1.0
    dtheta = calculateAngularDistance(sourceNode[r1], destNode[r2])
    hyperbolicDistance = (1. / zeta) * acosh(cosh(zeta * r1) * cosh(zeta * r2) - \
                                             sinh(zeta * r1) * sinh(zeta * r2) * cos(dtheta))
    debug("Distance from {} to {} is {}".format(sourceNode, destNode,
                                                hyperbolicDistance))
    return hyperbolicDistance
Exemplo n.º 48
0
def S_isothermal_pipe_eccentric_to_isothermal_pipe(D1, D2, Z, L=1.):
    r'''Returns the Shape factor `S` of a pipe of constant outer temperature
    and of outer diameter `D1` which is `Z` distance from the center of another
    pipe of outer diameter`D2`. Length `L` must be provided, but can be set to
    1 to obtain a dimensionless shape factor used in some sources.

    .. math::
        S = \frac{2\pi L}{\cosh^{-1}
        \left(\frac{D_2^2 + D_1^2 - 4Z^2}{2D_1D_2}\right)}

    Parameters
    ----------
    D1 : float
        Diameter of inner pipe, [m]
    D2 : float
        Diameter of outer pipe, [m]
    Z : float
        Distance from the middle of inner pipe to the center of the other, [m]
    L : float, optional
        Length of the pipe, [m]

    Returns
    -------
    S : float
        Shape factor [m]

    Examples
    --------
    >>> S_isothermal_pipe_eccentric_to_isothermal_pipe(.1, .4, .05, 10)
    47.709841915608976

    Notes
    -----
    L should be much larger than both diameters. D2 should be larger than D1.

    .. math::
        Q = Sk(T_1 - T_2) \\ R_{\text{shape}}=\frac{1}{Sk}

    References
    ----------
    .. [1] Kreith, Frank, Raj Manglik, and Mark Bohn. Principles of Heat
       Transfer. Cengage, 2010.
    .. [2] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and
       David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:
       Wiley, 2011.
    '''
    S = 2*pi*L/acosh((D2**2 + D1**2 - 4*Z**2)/(2*D1*D2))
    return S
Exemplo n.º 49
0
def S_isothermal_pipe_eccentric_to_isothermal_pipe(D1, D2, Z, L=1.):
    r'''Returns the Shape factor `S` of a pipe of constant outer temperature
    and of outer diameter `D1` which is `Z` distance from the center of another
    pipe of outer diameter`D2`. Length `L` must be provided, but can be set to
    1 to obtain a dimensionless shape factor used in some sources.

    .. math::
        S = \frac{2\pi L}{\cosh^{-1}
        \left(\frac{D_2^2 + D_1^2 - 4Z^2}{2D_1D_2}\right)}

    Parameters
    ----------
    D1 : float
        Diameter of inner pipe, [m]
    D2 : float
        Diameter of outer pipe, [m]
    Z : float
        Distance from the middle of inner pipe to the center of the other, [m]
    L : float, optional
        Length of the pipe, [m]

    Returns
    -------
    S : float
        Shape factor [m]

    Examples
    --------
    >>> S_isothermal_pipe_eccentric_to_isothermal_pipe(.1, .4, .05, 10)
    47.709841915608976

    Notes
    -----
    L should be much larger than both diameters. D2 should be larger than D1.

    .. math::
        Q = Sk(T_1 - T_2) \\ R_{\text{shape}}=\frac{1}{Sk}

    References
    ----------
    .. [1] Kreith, Frank, Raj Manglik, and Mark Bohn. Principles of Heat
       Transfer. Cengage, 2010.
    .. [2] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and
       David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:
       Wiley, 2011.
    '''
    S = 2*pi*L/acosh((D2**2 + D1**2 - 4*Z**2)/(2*D1*D2))
    return S
Exemplo n.º 50
0
    def computeTOF(self):
        mu = self.myUniverse.mu
        r = (self.periapseState[0]**2 + self.periapseState[1]**2 +
             self.periapseState[2]**2)**0.5

        rSOI = self.myUniverse.r_SOI
        SMA = -mu / self.vMAG / self.vMAG
        ECC = 1 - r / SMA
        H = acosh(1.0 / ECC * (rSOI / -SMA + 1.0))
        N = ECC * sinh(H) - H
        self.TOF = N / sqrt(mu / -(SMA * SMA * SMA))

        self.DeltaTA = 2.0 * atan(
            ((ECC + 1.0) / (ECC - 1.0))**0.5 * tanh(0.5 * H))

        DeltaTA2 = acos(1.0 / ECC * (SMA * (1 - ECC**2) / rSOI - 1.0))
    def testAcoshFunction(self):
        ma5 = MovingAverage(5, 'close')
        holder = Acosh(ma5)

        sampleClose = np.cosh(self.sampleClose)

        for i, close in enumerate(sampleClose):
            data = {'close': close}
            ma5.push(data)
            holder.push(data)

            expected = math.acosh(ma5.result())
            calculated = holder.result()
            self.assertAlmostEqual(calculated, expected, 12, "at index {0:d}\n"
                                                             "expected:   {1:f}\n"
                                                             "calculated: {2:f}".format(i, expected, calculated))
Exemplo n.º 52
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)
Exemplo n.º 53
0
 def acosh(*args):
     if args[0].__class__.__name__ == "vmath":
         self = args[0]
     else:
         self = vmath()
     arg = vmath.self_remove(args)
     if self.arg_type != None:
         arg[0] = self.arg_type(arg[0])
     arg_name = arg[0].__class__.__name__
     pn_class_much = [x for x in vmath.pn_class if x == arg_name]
     if len(pn_class_much) == 1:
         answer = arg[0].math.acosh(arg[0])
     else:
         answer = math.acosh(arg[0])
     if self.return_type != None:
         answer = self.return_type(answer)
     return answer
Exemplo n.º 54
0
def S_isothermal_pipe_to_plane(D, Z, L=1):
    r'''Returns the Shape factor `S` of a pipe of constant outer temperature
    and of outer diameter `D` which is `Z` distance from an infinite plane.
    Length `L` must be provided, but can be set to 1 to obtain a dimensionless
    shape factor used in some sources.

    .. math::
        S = \frac{2\pi L}{\cosh^{-1}(2z/D)}

    Parameters
    ----------
    D : float
        Diameter of the pipe, [m]
    Z : float
        Distance from the middle of the pipe to the infinite plane, [m]
    L : float, optional
        Length of the pipe, [m]

    Returns
    -------
    S : float
        Shape factor [m]

    Examples
    --------
    >>> S_isothermal_pipe_to_plane(1, 100, 3)
    3.146071454894645

    Notes
    -----
    L should be much larger than D.

    .. math::
        Q = Sk(T_1 - T_2) \\ R_{\text{shape}}=\frac{1}{Sk}

    References
    ----------
    .. [1] Kreith, Frank, Raj Manglik, and Mark Bohn. Principles of Heat
       Transfer. Cengage, 2010.
    .. [2] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and
       David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:
       Wiley, 2011.
    '''
    S = 2*pi*L/acosh(2*Z/D)
    return S
Exemplo n.º 55
0
def add_fit_info(filename, ax=None):
    if not ax:
        ax = plt
    funmap = {"two_exp": two_exp, "single_exp": single_exp, "periodic_two_exp": periodic_two_exp,
              "fwd-back-exp": periodic_exp, "periodic_two_exp_const": periodic_two_exp_const, "fwd-back-exp_const": periodic_exp_const}
    try:
        fittype, function, tmin, tmax, fitparams, fiterrors, Nt = get_fit(filename)
        fun = funmap[function](Nt)
        massindex = fun.parameter_names.index("mass")
        mass = fitparams[massindex]
        masserror = fiterrors[massindex]
        if fittype == "#fit":
            logging.info("correlator fit info")
            xpoints = np.arange(tmin, tmax, 0.3)
            fitpoints = fun.formula(fitparams, xpoints)
            ax.plot(xpoints, fitpoints, ls="dashed", color="r", lw=2, zorder=5)
            if args.fitfunction:
                return fun.template.format(*fitparams)
        if fittype == "#fit_emass":
            xpoints = np.arange(tmin, tmax+1, 1.0)
            fitpoints = fun.formula(fitparams, xpoints)
            emassfit = []
            dt = 3
            for i in range(len(fitpoints))[:-dt]:
                try:
                    #emass = (1.0 / float(dt)) * np.log(fitpoints[i] / fitpoints[i + dt])
                    emass = (1.0 / float(dt)) * math.acosh((fitpoints[i+dt] + fitpoints[i-dt])/(2.0*fitpoints[i]))
                    emassfit.append(emass)
                except:
                    emassfit.append(np.nan)

            if args.fit_errors:
                ax.plot(xpoints[:-dt], np.full_like(xpoints[:-dt],mass+masserror), ls="--", color="k", lw=2, zorder=50)
                ax.plot(xpoints[:-dt], np.full_like(xpoints[:-dt],mass-masserror), ls="--", color="k", lw=2, zorder=50)
            else:
                ax.plot(xpoints[:-dt], emassfit, ls="dashed", color="r", lw=2, zorder=5)
        if masserror == 0:
            return "{}".format(mass)
        digits = -1.0*round(math.log10(masserror))
        formated_error = int(round(masserror * (10**(digits + 1))))
        formated_mass = "{m:.{d}f}".format(d=int(digits) + 1, m=mass)
        #return "{m}({e})".format(m=formated_mass, e=formated_error)
        return print_paren_error(mass, masserror)
    except RuntimeError:
        logging.error("File {} had no fit into".format(filename))
Exemplo n.º 56
0
 def cosh_const_effective_mass(self, dt):
     asv = self.average_sub_vev()
     asvt = {t: asv[t+dt]-asv[t] for t in self.times[:-dt] }
     emass = {}
     for t in self.times[dt:-(dt+dt)]:
         if t in self.emass_skip_times:
             emass[t] = 0.0
             continue
         try:
             emass[t] = (1.0 / float(dt))*math.acosh((asvt[t+dt] + asvt[t-dt])/(2.0*asvt[t]))
         except ValueError:
             logging.debug("invalid argument to acosh, setting to nan")
             emass[t] = float('NaN')
         except KeyError:
             logging.error("index out of range")
         except ZeroDivisionError:
             logging.error("Div by zero either dt:{} or average value sub vev {}".format(dt,asv[t]))
             emass[t] = 0.0
     return emass
Exemplo n.º 57
0
def taylor_win(n, sll):
    """
    http://www.dsprelated.com/showcode/6.php

    from http://mathforum.org/kb/message.jspa?messageID=925929:

    A Taylor window is very similar to Chebychev weights. While Chebychev
    weights provide the tighest beamwidth for a given side-lobe level, taylor
    weights provide the least taper loss for a given sidelobe level.

    'Antenna Theory: Analysis and Design' by Constantine Balanis, 2nd
    edition, 1997, pp. 358-368, or 'Modern Antenna Design' by Thomas
    Milligan, 1985, pp.141-148.
    """
    def calculate_fm(m, sp2, a, nbar):
        n = np.arange(1, nbar)
        p = np.hstack([np.arange(1, m), np.arange(m + 1, nbar)])
        num = np.prod((1 - (m**2 / sp2) / (a**2 + (n - 0.5)**2)))
        den = np.prod(1 - m**2 / p**2)
        return ((-1)**(m + 1) * num) / (2 * den)
    nbar = int(np.ceil(2.0 * (acosh(10**(-sll / 20.0)) / pi)**2 + 0.5))
    n *= 2
    a = np.arccosh(10**(-sll / 20)) / pi
    sp2 = nbar**2 / (a**2 + (nbar - 0.5)**2)
    w = np.ones(n)
    fm = np.zeros(nbar)
    summation = 0
    k = np.arange(n)
    xi = (k - 0.5 * n + 0.5) / n
    for m in range(1, nbar):
        fm[m] = calculate_fm(m, sp2, a, nbar)
        summation += fm[m] * np.cos(2 * pi * m * xi)
    w += w * summation
    w /= w.max()
    w = w[n//2:]
    return w
Exemplo n.º 58
0
 def testACosh(self):
     vectorA = m.Vector([1, 2, 3, 4])
     result = [math.acosh(x) for x in vectorA.values]
     self.assertEqual(vectorA.acosh(), result)
Exemplo n.º 59
0
def nud(self):
    return math.acosh(self.expression())