コード例 #1
0
ファイル: numpepo.py プロジェクト: gkc1000/tomato
def heisenT(beta):
    # Following notation of Xiang (http://arxiv.org/pdf/1201.1144v4.pdf)
    W=np.array([[math.sqrt(math.cosh(beta)), math.sqrt(math.sinh(beta))],
               [math.sqrt(math.cosh(beta)), -math.sqrt(math.sinh(beta))]])
    #T=np.einsum("au,ad,al,ar->udlr",W,W,W,W)
    T=np.einsum("al,ar->lr",W,W)
    return T
コード例 #2
0
ファイル: mathematical.py プロジェクト: Eleanor320/pygep
 def testHyperbolic(self):
     self.assertEqual(math.sinh(5), hyperbolic.sineh_op(5))
     self.assertEqual(math.cosh(5), hyperbolic.cosineh_op(5))
     self.assertEqual(math.tanh(5), hyperbolic.tangenth_op(5))
     self.assertEqual(1. / math.sinh(5), hyperbolic.cosecanth_op(5))
     self.assertEqual(1. / math.cosh(5), hyperbolic.secanth_op(5))
     self.assertEqual(1. / math.tanh(5), hyperbolic.cotangenth_op(5))
コード例 #3
0
ファイル: cmath.py プロジェクト: brython-dev/brython
def sinh(x):
    """ Return the hyperbolic sine of x. """

    if math.isinf(x.real) or math.isinf(x.imag):
        # need to raise DomainError if y is +/- infinity and x is not
        # a NaN and not -infinity
        if math.isinf(x.imag) and not math.isnan(x.real):
            raise ValueError("math domain error")

        if math.isinf(x.real) and -_INF < x.imag < _INF and x.imag != .0:
            if x.real > 0:
                _real = math.copysign(_INF, cos(x.imag))
                _imag = math.copysign(_INF, sin(x.imag))
            else:
                _real = -math.copysign(_INF, cos(x.imag))
                _imag = math.copysign(_INF, sin(x.imag))
            return complex(_real, _imag)

        return  _SPECIAL_VALUE(x,_sinh_special_values)

    if math.fabs(x.real) > _CM_LOG_LARGE_DOUBLE:
        x_minus_one = x.real - math.copysign(1.0, x.real)
        _real = math.cos(x.imag)*math.sinh(x.imag)*math.e
        _imag = math.sin(x.imag)*math.cosh(x.imag)*math.e
    else:
        _real = math.cos(x.imag)*math.sinh(x.real)
        _imag = math.sin(x.imag)*math.cosh(x.real)

    if math.isinf(_real) or math.isinf(_imag):
        raise OverflowError()

    return complex(_real, _imag)
コード例 #4
0
ファイル: cmath.py プロジェクト: brython-dev/brython
def cosh(x):
    """Return the hyperbolic cosine of x."""

    # special treatment for cosh(+/-inf + iy) if y is not a NaN
    if isinf(x):
        if -_INF < x.imag < _INF and x.imag != .0:
            if x.real > 0:
                _real = math.copysign(_INF, math.cos(x.imag))
                _imag = math.copysign(_INF, math.sin(x.imag))
            else:
                _real = math.copysign(_INF, math.cos(x.imag))
                _imag = -math.copysign(_INF, math.sin(x.imag))
            return complex(_real,_imag)
        else:
            # need to raise math domain error if y is +/- infinity and x is not a NaN
            if x.imag != .0 and not math.isnan(x.real):
                raise ValueError("math domain error")
            return _SPECIAL_VALUE(x,_cosh_special_values)

    if math.fabs(x.real) > _CM_LOG_LARGE_DOUBLE:
        #  deal correctly with cases where cosh(x.real) overflows but
        #  cosh(z) does not.
        x_minus_one = x.real - math.copysign(1.0, x.real)
        _real = cos(x.imag) * math.cosh(x_minus_one) * math.e
        _imag = sin(x.imag) * math.sinh(x_minus_one) * math.e
    else:
        _real = math.cos(x.imag) * math.cosh(x.real)
        _imag = math.sin(x.imag) * math.sinh(x.real)

    ret = complex(_real, _imag)
    #  detect overflow
    if isinf(ret):
        raise OverflowError()
    return ret
コード例 #5
0
ファイル: __init__.py プロジェクト: wagamama/geo-twd
def to_wgs84(x, y, twd67=False):
    '''
    The formula is based on
    "https://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system"
    '''

    if twd67:
        x, y = twd67_to_twd97(x, y)

    x /= 1000.0  # m to km
    y /= 1000.0  # m to km

    xi = (y - N0) / (k0 * A)
    eta = (x - E0) / (k0 * A)
    xip = (xi -
           b1 * math.sin(2 * xi) * math.cosh(2 * eta) -
           b2 * math.sin(4 * xi) * math.cosh(4 * eta) -
           b3 * math.sin(6 * xi) * math.cosh(6 * eta))
    etap = (eta -
            b1 * math.cos(2 * xi) * math.sinh(2 * eta) -
            b2 * math.cos(4 * xi) * math.sinh(4 * eta) -
            b3 * math.cos(6 * xi) * math.sinh(6 * eta))
    chi = math.asin(math.sin(xip) / math.cosh(etap))
    lat = math.degrees(
            chi +
            d1 * math.sin(2 * chi) +
            d2 * math.sin(4 * chi) +
            d3 * math.sin(6 * chi))
    lon = lon0 + math.degrees(
            math.atan(math.sinh(etap) / math.cos(xip)))

    return (lat, lon)
コード例 #6
0
ファイル: data.py プロジェクト: esel7353/ephys
  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))
コード例 #7
0
ファイル: greatcircle.py プロジェクト: obsc/flight-planner
def to_latlon(northings, eastings, altitude):
    f = 1/298.257223563
    n = f / (2 - f)
    n_0 = 0.0
    k_0 = 0.9996
    e_0 = 500.
    a = 6378.137 #km
    big_a = (a / (1 + n)) * (1 + (n**2 / 4) + (n**4 / 64)) #approximately
    alpha_1 = .5 * n - (2. / 3.) * n**2 + (5. / 16.) * n**3
    alpha_2 = (13./48.) * n**2 - (3./5.) * n**3
    alpha_3 = (61./240.) * n**3
    beta_1 = (1./2.) * n - (2. / 3.) * n**2 + (37./96.) * n**3
    beta_2 = (1./48.) * n**2 + (1. / 15.) * n**3
    beta_3 = (17. /480.) * n**3
    delta_1 = 2. * n - (2./3.) * n**2 - 2* n**3
    delta_2 = (7./3.) * n**2 - (8. / 5.) * n**3 
    delta_3 = (56./15.) * n**3

    psi = (n - n_0) / (k_0 * big_a)
    eta = (e - e_0) / (k_0 * big_a)
    psi_prime = psi - ((beta_1 * sin(2. * 1 * eta) * cosh(2. * 1 * eta)) + 
        (beta_2 * sin(2. * 2 * eta) * cosh(2. * 2 * eta)) + (beta_3 * sin(2. * 3 * eta) * cosh(2. * 3 * eta)))
    eta_prime = eta - ((beta_1 * cos(2. * 1 * psi) * sinh(2. * 1 * eta)) + 
        (beta_2 * cos(2. * 2 * psi) * sinh(2. * 2 * eta)) + (beta_3 * cos(2. * 3 * psi) * sinh(2. * 3 * eta)))
    sigma_prime = 1. - ((2. * 1 * beta_1 * cos(2. * 1 * psi) * cosh(2. * 1 * eta)) +
        (2. * 2 * beta_2 * cos(2. * 2 * psi) * cosh(2. * 2 * eta)) + (2. * 3 * beta_3 * cos(2. * 3 * psi) * cosh(2. * 3 * eta)))
    tau_prime = ((2. * 1 * beta_1 * sin(2. * 1 * psi) * sinh(2. * 1 * eta)) +
        (2. * 2 * beta_2 * sin(2. * 2 * psi) * sinh(2. * 2 * eta)) + (2. * 3 * beta_3 * sin(2. * 3 * psi) * sinh(2. * 3 * eta)))
    chi = asin (sin(psi_prime)/cosh(eta_prime)) 
    phi = chi + (delta_1 * sin(2. * 1 * chi)) + (delta_2 * sin(2. * 2 * chi)) + (delta_3 * sin(2. * 3 * chi))
    lambda_0 = 0
    lambdu = 0 
    k =  0
    gamma = 0
    return None
コード例 #8
0
ファイル: mkrgBuilder.py プロジェクト: jeffgertler/mkrg
def recN(K, MAX_VALUE):
    if(abs(K[0] + K[1] + K[2] + K[3] + K[4] + K[5] + K[6] + K[7]) > MAX_VALUE
    	or abs(K[0] + K[1] + K[2] + K[3] - K[4] - K[5] - K[6] - K[7]) > MAX_VALUE):
    	return recN0T(K)
    else:
    	return .5 * math.log(math.cosh(K[0] + K[1] + K[2] + K[3] + K[4] + K[5] + K[6] + K[7])
               			  / math.cosh(K[0] + K[1] + K[2] + K[3] - K[4] - K[5] - K[6] - K[7]))
コード例 #9
0
ファイル: stdfunc.py プロジェクト: filipevarjao/IntPy
def cosh(self, other=None):
# Return hyperbolic cosine of interval

	if other != None:
		intv = IReal(self, other)
	else:
		if type(self) == float or type(self) == str:
			intv = IReal(self)
		else:
			intv = self
 
	if math.cosh(intv.inf) > math.cosh(intv.sup):
		inf = max(intv.inf, intv.sup)
		sup = min(intv.inf, intv.sup)
	else:
		inf = intv.inf
		sup = intv.sup

	if 0 in intv:
		inf = 0

	ireal.rounding.set_mode(1)

	ireal.rounding.set_mode(-1)
	ireal.rounding.set_mode(-1)

	new_inf = math.cosh(inf)
	ireal.rounding.set_mode(1)
	new_sup = max(float(IReal('%.16f' % math.cosh(sup)).sup), float(IReal('%.20f' % math.cosh(sup)).sup))

	return IReal(new_inf, new_sup)
コード例 #10
0
ファイル: interp_cmath.py プロジェクト: Debug-Orz/Sypy
def c_sinh(x, y):
    # special treatment for sinh(+/-inf + iy) if y is finite and nonzero
    if not isfinite(x) or not isfinite(y):
        if isinf(x) and isfinite(y) and y != 0.:
            if x > 0:
                real = copysign(INF, math.cos(y))
                imag = copysign(INF, math.sin(y))
            else:
                real = -copysign(INF, math.cos(y))
                imag = copysign(INF, math.sin(y))
            r = (real, imag)
        else:
            r = sinh_special_values[special_type(x)][special_type(y)]

        # need to raise ValueError if y is +/- infinity and x is not
        # a NaN
        if isinf(y) and not isnan(x):
            raise ValueError("math domain error")
        return r

    if fabs(x) > CM_LOG_LARGE_DOUBLE:
        x_minus_one = x - copysign(1., x)
        real = math.cos(y) * math.sinh(x_minus_one) * math.e
        imag = math.sin(y) * math.cosh(x_minus_one) * math.e
    else:
        real = math.cos(y) * math.sinh(x)
        imag = math.sin(y) * math.cosh(x)
    if isinf(real) or isinf(imag):
        raise OverflowError("math range error")
    return real, imag
コード例 #11
0
ファイル: interp_cmath.py プロジェクト: Debug-Orz/Sypy
def c_cosh(x, y):
    if not isfinite(x) or not isfinite(y):
        if isinf(x) and isfinite(y) and y != 0.:
            if x > 0:
                real = copysign(INF, math.cos(y))
                imag = copysign(INF, math.sin(y))
            else:
                real = copysign(INF, math.cos(y))
                imag = -copysign(INF, math.sin(y))
            r = (real, imag)
        else:
            r = cosh_special_values[special_type(x)][special_type(y)]

        # need to raise ValueError if y is +/- infinity and x is not
        # a NaN
        if isinf(y) and not isnan(x):
            raise ValueError("math domain error")
        return r

    if fabs(x) > CM_LOG_LARGE_DOUBLE:
        # deal correctly with cases where cosh(x) overflows but
        # cosh(z) does not.
        x_minus_one = x - copysign(1., x)
        real = math.cos(y) * math.cosh(x_minus_one) * math.e
        imag = math.sin(y) * math.sinh(x_minus_one) * math.e
    else:
        real = math.cos(y) * math.cosh(x)
        imag = math.sin(y) * math.sinh(x)
    if isinf(real) or isinf(imag):
        raise OverflowError("math range error")
    return real, imag
コード例 #12
0
ファイル: cmath.py プロジェクト: pombredanne/ouroboros
def sinh(x):

    _sinh_special = [
        [inf+nanj, None, complex(-float("inf"), -0.0), -inf, None, inf+nanj, inf+nanj],
        [nan+nanj, None, None, None, None, nan+nanj, nan+nanj],
        [nanj, None, complex(-0.0, -0.0), complex(-0.0, 0.0), None, nanj, nanj],
        [nanj, None, complex(0.0, -0.0), complex(0.0, 0.0), None, nanj, nanj],
        [nan+nanj, None, None, None, None, nan+nanj, nan+nanj],
        [inf+nanj, None, complex(float("inf"), -0.0), inf, None, inf+nanj, inf+nanj],
        [nan+nanj, nan+nanj, complex(float("nan"), -0.0), nan, nan+nanj, nan+nanj, nan+nanj]
    ]

    z = _make_complex(x)

    if not isfinite(z):
        if math.isinf(z.imag) and not math.isnan(z.real):
            raise ValueError
        if math.isinf(z.real) and math.isfinite(z.imag) and z.imag != 0:
            if z.real > 0:
                return complex(math.copysign(inf, math.cos(z.imag)),
                               math.copysign(inf, math.sin(z.imag)))
            return complex(-math.copysign(inf, math.cos(z.imag)),
                           math.copysign(inf, math.sin(z.imag)))
        return _sinh_special[_special_type(z.real)][_special_type(z.imag)]

    if abs(z.real) > _LOG_LARGE_DOUBLE:
        x_minus_one = z.real - math.copysign(1, z.real)
        return complex(math.cos(z.imag) * math.sinh(x_minus_one) * e,
                       math.sin(z.imag) * math.cosh(x_minus_one) * e)
    return complex(math.cos(z.imag) * math.sinh(z.real),
                   math.sin(z.imag) * math.cosh(z.real))
コード例 #13
0
ファイル: cmath.py プロジェクト: pombredanne/ouroboros
def cosh(x):
    _cosh_special = [
        [inf+nanj, None, inf, complex(float("inf"), -0.0), None, inf+nanj, inf+nanj],
        [nan+nanj, None, None, None, None, nan+nanj, nan+nanj],
        [nan, None, 1, complex(1, -0.0), None, nan, nan],
        [nan, None, complex(1, -0.0), 1, None, nan, nan],
        [nan+nanj, None, None, None, None, nan+nanj, nan+nanj],
        [inf+nanj, None, complex(float("inf"), -0.0), inf, None, inf+nanj, inf+nanj],
        [nan+nanj, nan+nanj, nan, nan, nan+nanj, nan+nanj, nan+nanj]
    ]

    z = _make_complex(x)

    if not isfinite(z):
        if math.isinf(z.imag) and not math.isnan(z.real):
            raise ValueError
        if math.isinf(z.real) and math.isfinite(z.imag) and z.imag != 0:
            if z.real > 0:
                return complex(math.copysign(inf, math.cos(z.imag)),
                               math.copysign(inf, math.sin(z.imag)))
            return complex(math.copysign(inf, math.cos(z.imag)),
                           -math.copysign(inf, math.sin(z.imag)))
        return _cosh_special[_special_type(z.real)][_special_type(z.imag)]

    if abs(z.real) > _LOG_LARGE_DOUBLE:
        x_minus_one = z.real - math.copysign(1, z.real)
        ret = complex(e * math.cos(z.imag) * math.cosh(x_minus_one),
                      e * math.sin(z.imag) * math.sinh(x_minus_one))
    else:
        ret = complex(math.cos(z.imag) * math.cosh(z.real),
                      math.sin(z.imag) * math.sinh(z.real))
    if math.isinf(ret.real) or math.isinf(ret.imag):
        raise OverflowError

    return ret
コード例 #14
0
ファイル: coordinates.py プロジェクト: jonathanlee1/SARBayes
def from_utm(easting: float, northing: float,
             zone: int, hemisphere: int =1) -> (float, float):
    """
    Convert UTM coordinates to decimal latitude and longitude coordinates.

    Keyword Arguments:
        easting: The easting in m.
        northing: The northing in m.
        zone: The zone, an integer between 1 and 60, inclusive.
        hemisphere: A signed number, where a negative number indicates the
                    coordinates are located in the southern hemisphere.

    Returns:
        latitude: The latitude in decimal degrees.
        longitude: The longitude in deciaml degrees.

    Raises:
        OverflowError: The coordinate does not exist.
    """
    easting, northing = easting/1000, northing/1000
    northing_ = 10000 if hemisphere < 0 else 0

    xi_ = xi = (northing - northing_)/(k0*A)
    eta_ = eta = (easting - easting_)/(k0*A)
    for j in range(1, 4):
        p, q = 2*j*xi, 2*j*eta
        xi_ -= beta[j - 1]*sin(p)*cosh(q)
        eta_ -= beta[j - 1]*cos(p)*sinh(q)

    chi = asin(sin(xi_)/cosh(eta_))
    latitude = chi + sum(delta[j - 1]*sin(2*j*chi) for j in range(1, 4))
    longitude_ = radians(6*zone - 183)
    longitude = longitude_ + atan2(sinh(eta_), cos(xi_))
    return degrees(latitude), degrees(longitude)
コード例 #15
0
ファイル: converter.py プロジェクト: shupingT/twd97
def fromwgs84(lat, lng, pkm=False):
    """
    Convert coordintes from WGS84 to TWD97

    pkm true for Penghu, Kinmen and Matsu area
    The latitude and longitude can be in the following formats:
        [+/-]DDD°MMM'SSS.SSSS" (unicode)
        [+/-]DDD°MMM.MMMM' (unicode)
        [+/-]DDD.DDDDD (string, unicode or float)
    The returned coordinates are in meters
    """

    _lng0 = lng0pkm if pkm else lng0

    lat = radians(todegdec(lat))
    lng = radians(todegdec(lng))

    t = sinh((atanh(sin(lat)) - 2*pow(n,0.5)/(1+n)*atanh(2*pow(n,0.5)/(1+n)*sin(lat))))
    epsilonp = atan(t/cos(lng-_lng0))
    etap = atan(sin(lng-_lng0) / pow(1+t*t, 0.5))

    E = E0 + k0*A*(etap + alpha1*cos(2*1*epsilonp)*sinh(2*1*etap) + 
                          alpha2*cos(2*2*epsilonp)*sinh(2*2*etap) +
                          alpha3*cos(2*3*epsilonp)*sinh(2*3*etap))
    N = N0 + k0*A*(epsilonp + alpha1*sin(2*1*epsilonp)*cosh(2*1*etap) +
                              alpha2*sin(2*2*epsilonp)*cosh(2*2*etap) +
                              alpha3*sin(2*3*epsilonp)*cosh(2*3*etap))

    return E*1000, N*1000
コード例 #16
0
ファイル: coordinates.py プロジェクト: guaq/paikkis
def lalo_to_xy(la, lo, lo0, E0, ellipsoid):
  lo0 = math.radians(lo0)  
  la = math.radians(la)
  lo = math.radians(lo)  
  
  e = ellipsoid['e']
  k0 = ellipsoid['k0']
  h1p = ellipsoid['h1p']
  h2p = ellipsoid['h2p']
  h3p = ellipsoid['h3p']
  h4p = ellipsoid['h4p']
  A1 = ellipsoid['A1']  
    
  Q = asinh(math.tan(la)) - e * atanh(e * math.sin(la))
  be = math.atan(math.sinh(Q))
  nnp = atanh(math.cos(be) * math.sin(lo - lo0))
  Ep = math.asin(math.sin(be) * math.cosh(nnp))  
  E1 = h1p * math.sin(2.0 * Ep) * math.cosh(2.0 * nnp)
  E2 = h2p * math.sin(4.0 * Ep) * math.cosh(4.0 * nnp)
  E3 = h3p * math.sin(6.0 * Ep) * math.cosh(6.0 * nnp)
  E4 = h4p * math.sin(8.0 * Ep) * math.cosh(8.0 * nnp)
  nn1 = h1p * math.cos(2.0 * Ep) * math.sinh(2.0 * nnp)
  nn2 = h2p * math.cos(4.0 * Ep) * math.sinh(4.0 * nnp)
  nn3 = h3p * math.cos(6.0 * Ep) * math.sinh(6.0 * nnp)
  nn4 = h4p * math.cos(8.0 * Ep) * math.sinh(8.0 * nnp)
  E = Ep + E1 + E2 + E3 + E4
  nn = nnp + nn1 + nn2 + nn3 + nn4
  
  XY = {}
  XY['N'] = A1 * E * k0
  XY['E'] = A1 * nn * k0 + E0

  return XY
コード例 #17
0
ファイル: hyp.py プロジェクト: aldenwalker/shine
def tri_angles(L):
  ans = [0, 0, 0]
  for i in xrange(3):
    top = math.cosh(L[i])*math.cosh(L[(i+2)%3]) - math.cosh( L[(i+1)%3] )
    bottom = math.sinh(L[i])*math.sinh(L[(i+2)%3])
    ans[i] = math.acos(top/bottom)
  return ans
コード例 #18
0
    def gridToGeodetic(self, north, east):
        """
        Transformation from grid coordinates to geodetic coordinates.
        @param north (corresponds to X in RT 90 and N in SWEREF 99.)
        @param east (corresponds to Y in RT 90 and E in SWEREF 99.)
        @return (latitude, longitude)
        """
        if (self._initialized == False):
            return None

        deg_to_rad = math.pi / 180
        lambda_zero = self._central_meridian * deg_to_rad
        xi = (north - self._false_northing) / (self._scale * self._a_roof)        
        eta = (east - self._false_easting) / (self._scale * self._a_roof)
        xi_prim = xi - \
                self._delta1*math.sin(2.0*xi) * math.cosh(2.0*eta) - \
                self._delta2*math.sin(4.0*xi) * math.cosh(4.0*eta) - \
                self._delta3*math.sin(6.0*xi) * math.cosh(6.0*eta) - \
                self._delta4*math.sin(8.0*xi) * math.cosh(8.0*eta)
        eta_prim = eta - \
                self._delta1*math.cos(2.0*xi) * math.sinh(2.0*eta) - \
                self._delta2*math.cos(4.0*xi) * math.sinh(4.0*eta) - \
                self._delta3*math.cos(6.0*xi) * math.sinh(6.0*eta) - \
                self._delta4*math.cos(8.0*xi) * math.sinh(8.0*eta)
        phi_star = math.asin(math.sin(xi_prim) / math.cosh(eta_prim))
        delta_lambda = math.atan(math.sinh(eta_prim) / math.cos(xi_prim))
        lon_radian = lambda_zero + delta_lambda
        lat_radian = phi_star + math.sin(phi_star) * math.cos(phi_star) * \
                (self._Astar + \
                 self._Bstar*math.pow(math.sin(phi_star), 2) + \
                 self._Cstar*math.pow(math.sin(phi_star), 4) + \
                 self._Dstar*math.pow(math.sin(phi_star), 6))      
        lat = lat_radian * 180.0 / math.pi
        lon = lon_radian * 180.0 / math.pi
        return (lat, lon)
コード例 #19
0
ファイル: clean_mocks.py プロジェクト: aszewciw/gal_structure
def gal_weights(Z, R):
    '''
    Returns a weight based on a particular model of the MW.
    For now we will use a two-disk model with the form below.
    This can be expanded at a later time.

    Z - Height above/below galactic plane
    R - Distance from galactic center

    '''

    # Parameters
    thick_s_height = 0.674
    thick_s_length = 2.51
    thin_s_height = 0.233
    thin_s_length = 2.34
    a = 0.1


    weight = ( ( ( math.cosh(Z / 2 / thin_s_height) ) ** (-2) )
        * math.exp(-R / thin_s_length) +
        a * ( ( math.cosh(Z / 2 / thick_s_height) ) ** (-2) )
        * math.exp(-R / thick_s_length))

    return weight
コード例 #20
0
ファイル: somaticModel.py プロジェクト: mfinemorris/WilsonLab
def df(y,t): 
    Vs=y[0]
    ns=y[1]
    hs=y[2]
    
    # SOMATIC FUNCTIONS
    minfs=1/(1+math.exp((Vs-vm) /sm))
    ninfs=1/(1+math.exp((Vs-vn) /sn))
    minfps=1/(1+math.exp((Vs-vmp)/smp))
    hinfs=1/(1+math.exp((Vs-vh) /sh))
    
    tauns=taunb/math.cosh((Vs-vn)/(2*sn))
    tauhs=tauhb/math.cosh((Vs-vh)/(2*sh))
    
    I_nas=gna*math.pow(minfs,3)*(1-ns)*(Vs-vna)
    I_ks=gk*math.pow(ns,4)*(Vs-Vk)
    I_naps=gnaps*minfps*hs*(Vs-vna)
    
    I_ls =gls*(Vs-vleaks)

    # SOMATIC EQUATIONS

    dVs= (-I_ks - I_nas-I_naps-I_ls-Iaps)/Cms
    dns= (ninfs-ns)/tauns
    dhs= (hinfs-hs)/tauhs
    
    return [dVs,dns,dhs]
コード例 #21
0
ファイル: RectangularPipe.py プロジェクト: lewisamarshall/ebb
    def _velocity_term(self, y, z, i):
        prefactor = (-1)**((i-1)/2)
        first_term = 1 - (cosh(i * pi * z / 2 / self.width) /
                          cosh(i * pi * self.height / 2 / self.width)
                          )
        second_term = cos(i * pi * y / 2 / self.width) / i**3

        return prefactor * first_term * second_term
コード例 #22
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)
コード例 #23
0
ファイル: test_qmath.py プロジェクト: ufkapano/py-quats
 def test_cosh(self):
     self.assertAlmostEqual(qmath.cosh(self.f1), math.cosh(self.f1))
     self.assertAlmostEqual(qmath.cosh(self.c1), cmath.cosh(self.c1))
     self.assertAlmostEqual(qmath.cosh(self.c2), cmath.cosh(self.c2))
     self.assertAlmostEqual(qmath.cosh(Quat(self.f1)), math.cosh(self.f1))
     self.assertAlmostEqual(qmath.cosh(Quat(0, 3)), cmath.cosh(3J))
     self.assertAlmostEqual(qmath.cosh(Quat(4, 5)), cmath.cosh(4 + 5J))
     self.assertAlmostEqual(qmath.cosh(Quat(0, self.f1)), Quat(math.cos(self.f1)))
コード例 #24
0
ファイル: AutoDeriv.py プロジェクト: JensLo/pyEDA
 def aux1(x):
     '''
     Auxiliary function 1. 
     
     Break points used to ensure maximal precision::
     
                                            x
                              Aux1(x) =  -------
                                          sinh(x)
 
                         d           sinh(x) - x*cosh(x)
                         --Aux1(x) = -------------------
                         dx              (sinh(x))^2
     '''
     if isinstance(x, ADVar):
         y = x.val
     else:
         y=float(x);
         
     if y < -_BP0_MISC:
         y = -_BP0_MISC
     elif y > _BP0_MISC:
         y =  _BP0_MISC
 
     if y <= _BP0_AUX1:
         z = y / math.sinh(y)
     elif y <= _BP1_AUX1:
         z = 1 - y*y/6.0*(1.0 - 7.0*y*y/60.0)
     else:
         z = y / math.sinh(y)
         
     if not isinstance(x, ADVar):
         return z
     
     r = ADVar()
     r.val = z
     
     if y <= _BP4_DAUX1:
         pd = 0.0
     elif y <= _BP2_DAUX1:
         pd = -(1+y)*math.exp(y)
     elif y <= _BP0_DAUX1:
         tmp = math.sinh(y); 
         pd = (tmp - y*math.cosh(y))/(tmp*tmp)
     elif y <= _BP1_DAUX1:
         pd = -y/3.0*(1.0 - 7.0*y*y/30.0)
     elif y <= _BP3_DAUX1:
         tmp = math.sinh(y)
         pd = (z - y*math.cosh(y))/(z*z)
     elif y <= _BP5_DAUX1:
         pd =  (1-y)*math.exp(-y)
     else:
         pd = 0.0
 
     for i,dx in x.deriv:
         r.deriv.append( (i, pd*dx) )
 
     return r
コード例 #25
0
ファイル: theta.py プロジェクト: frostburn/frostsynth
def formant(phase, ratio, width):
    """Formant waveform with energy concentrated on the harmonic specified by ratio."""
    ratio = floor(ratio)
    if width < 700:
        x = pi * phase
        return cosh(cos(x) * width) / cosh(width) * cos(2 * x * ratio)
    else:
        x = phase - floor(phase + 0.5)
        return exp(-half_pi_squared * width * x * x) * cos(two_pi * x * ratio)
コード例 #26
0
ファイル: solution.py プロジェクト: TerraFERMA/benchmarks
def t0_xi():
  delta_rho = (rho0-rhou)*g
  rhog = rho0*g
  mu = mu0
  k = wavenumber()
  return -1.0*(((delta_rho*k**2*mu - k**2*mu*rhog)*D*sinh(D*k)**2 - (delta_rho*k**2*mu - k**2*mu*rhog)*D*cosh(D*k)**2 - (delta_rho*k*mu -\
k*mu*rhog)*sinh(D*k)*cosh(D*k) + sqrt((delta_rho**2*k**2 - 2*delta_rho*k**2*rhog + k**2*rhog**2)*D**2*cosh(D*k)**4 - 2*(delta_rho**2*k -\
2*delta_rho*k*rhog + k*rhog**2)*D*sinh(D*k)**3*cosh(D*k) + 2*(delta_rho**2*k - 2*delta_rho*k*rhog + k*rhog**2)*D*sinh(D*k)*cosh(D*k)**3 +\
((delta_rho**2*k**2 + 2*delta_rho*k**2*rhog + k**2*rhog**2)*D**2 + 4*delta_rho*rhog)*sinh(D*k)**4 - (2*(delta_rho**2*k**2 + k**2*rhog**2)*D**2 -\
delta_rho**2 + 2*delta_rho*rhog - rhog**2)*sinh(D*k)**2*cosh(D*k)**2)*k*mu)/(delta_rho*rhog*sinh(D*k)**2))
コード例 #27
0
ファイル: place.py プロジェクト: SNoiraud/gramps
def __conv_WGS84_SWED_RT90(lat, lon):
    """
    Input is lat and lon as two float numbers
    Output is X and Y coordinates in RT90
    as a tuple of float numbers

    The code below converts to/from the Swedish RT90 koordinate
    system. The converion functions use "Gauss Conformal Projection
    (Transverse Marcator)" Krüger Formulas.
    The constanst are for the Swedish RT90-system.
    With other constants the conversion should be useful for
    other geographical areas.

    """
    # Some constants used for conversion to/from Swedish RT90
    f = 1.0/298.257222101
    e2 = f*(2.0-f)
    n = f/(2.0-f)
    L0 = math.radians(15.8062845294)   # 15 deg 48 min 22.624306 sec
    k0 = 1.00000561024
    a = 6378137.0   # meter
    at = a/(1.0+n)*(1.0+ 1.0/4.0* pow(n, 2)+1.0/64.0*pow(n, 4))
    FN = -667.711 # m
    FE = 1500064.274 # m

    #the conversion
    lat_rad = math.radians(lat)
    lon_rad = math.radians(lon)
    A = e2
    B = 1.0/6.0*(5.0*pow(e2, 2) - pow(e2, 3))
    C = 1.0/120.0*(104.0*pow(e2, 3) - 45.0*pow(e2, 4))
    D = 1.0/1260.0*(1237.0*pow(e2, 4))
    DL = lon_rad - L0
    E = A + B*pow(math.sin(lat_rad), 2) + \
            C*pow(math.sin(lat_rad), 4) + \
            D*pow(math.sin(lat_rad), 6)
    psi = lat_rad - math.sin(lat_rad)*math.cos(lat_rad)*E
    xi = math.atan2(math.tan(psi), math.cos(DL))
    eta = atanh(math.cos(psi)*math.sin(DL))
    B1 = 1.0/2.0*n - 2.0/3.0*pow(n, 2) + 5.0/16.0*pow(n, 3) + \
                     41.0/180.0*pow(n, 4)
    B2 = 13.0/48.0*pow(n, 2) - 3.0/5.0*pow(n, 3) + 557.0/1440.0*pow(n, 4)
    B3 = 61.0/240.0*pow(n, 3) - 103.0/140.0*pow(n, 4)
    B4 = 49561.0/161280.0*pow(n, 4)
    X = xi + B1*math.sin(2.0*xi)*math.cosh(2.0*eta) + \
             B2*math.sin(4.0*xi)*math.cosh(4.0*eta) + \
             B3*math.sin(6.0*xi)*math.cosh(6.0*eta) + \
             B4*math.sin(8.0*xi)*math.cosh(8.0*eta)
    Y = eta + B1*math.cos(2.0*xi)*math.sinh(2.0*eta) + \
              B2*math.cos(4.0*xi)*math.sinh(4.0*eta) + \
              B3*math.cos(6.0*xi)*math.sinh(6.0*eta) + \
              B4*math.cos(8.0*xi)*math.sinh(8.0*eta)
    X = X*k0*at + FN
    Y = Y*k0*at + FE
    return (X, Y)
コード例 #28
0
ファイル: solution.py プロジェクト: TerraFERMA/benchmarks
def nond_G_ss(x):
  k = nond_wavenumber()
  F0 = nond_eta0()
  G0 = nond_xi0()
  delta_rho = (rho0-rhou)*nond_factor()/rho0
  zprime = depth/D
  T0 = deltaT
  alphag = nond_factor()
  rhog = nond_factor() # use this as a proxy for the nondimensional factorisation
  return (-(alphag*k*sinh(k*zprime)*cosh(k) - (alphag*k*zprime*cosh(k*zprime) - alphag*sinh(k*zprime))*sinh(k))/\
(T0*delta_rho*sinh(k)**2))*cos(k*x)
コード例 #29
0
ファイル: solution.py プロジェクト: FluidityProject/fluidity
def t0_xi():
  delta_rho = (rhou-rho0)*g
  rhog = rho0*g
  mu = mu0
  k = wavenumber()
  return -1.0*(((delta_rho*k**2*mu + k**2*mu*rhog)*D*sinh(D*k)**2 - (delta_rho*k**2*mu + k**2*mu*rhog)*D*cosh(D*k)**2 \
               - (delta_rho*k*mu + k*mu*rhog)*sinh(D*k)*cosh(D*k) + sqrt((delta_rho**2*k**2 + 2*delta_rho*k**2*rhog \
               + k**2*rhog**2)*D**2*cosh(D*k)**4 - 2*(delta_rho**2*k + 2*delta_rho*k*rhog \
               + k*rhog**2)*D*sinh(D*k)**3*cosh(D*k) + 2*(delta_rho**2*k + 2*delta_rho*k*rhog \
               + k*rhog**2)*D*sinh(D*k)*cosh(D*k)**3 + ((delta_rho**2*k**2 - 2*delta_rho*k**2*rhog \
               + k**2*rhog**2)*D**2 - 4*delta_rho*rhog)*sinh(D*k)**4 - (2*(delta_rho**2*k**2 + k**2*rhog**2)*D**2 \
               - delta_rho**2 - 2*delta_rho*rhog - rhog**2)*sinh(D*k)**2*cosh(D*k)**2)*k*mu)/(delta_rho*rhog*sinh(D*k)**2))
コード例 #30
0
ファイル: qmath.py プロジェクト: ufkapano/py-quats
def cosh(x):
    """Return the hyperbolic cosine of x."""
    if isinstance(x, (int, long, float)):
        return Quat(math.cosh(x))
    elif isinstance(x, complex):
        #return Quat(1) * cmath.cosh(x)
        return Quat(math.cosh(x.real) * math.cos(x.imag), 
                    math.sinh(x.real) * math.sin(x.imag))
    else:   # isinstance(x, Quat)
        # cos(q)=(exp(q)+exp(-q))/2
        result = exp(x) + exp(-x)
        result = result * Quat(0.5)
        return result
コード例 #31
0
 def hwhm(self, right=False):
     # NB -- bounds on p[1] set such that this is well-defined
     return np.arccos(2 - cosh(self.p[0])) / TWOPI
コード例 #32
0
ファイル: _var.py プロジェクト: ProFatXuanAll/ML_practice
 def cosh(self):
     r"""Hyperbolic operation ``cosh(self)``."""
     out = Variable(math.cosh(self.val))
     out.bp_graph.append((self, math.sinh(self.val)))
     out.priority = self.priority + 1
     return out
コード例 #33
0
def v(x):
    alpha = 1
    lamb = 4
    return alpha * alpha * lamb * (lamb - 1) * float(
        0.5 - float(1 / (math.pow(math.cosh(alpha * x), 2)))) / 2.
コード例 #34
0
def passMultiLepton(electron, multiLeptonMenu):
    # Check objects are available
    if not electron.trackParticle():
        return False
    if not electron.trackParticle().trackSummary():
        return False
    if not electron.trackParticle().measuredPerigee():
        return False

    # double etas2           =  el_etas2;
    etas2 = electron.cluster().etaBE(2)
    if abs(etas2) > 300.:
        return False
    # double Et_cl           =  el_cl_E/cosh(el_etas2);
    Et_cl = electron.cluster().e() / math.cosh(etas2)
    if Et_cl == 0.:
        return False
    # double DEmaxs1         = fabs(el_emaxs1+el_Emax2)>0. ? (el_emaxs1-el_Emax2)/(el_emaxs1+el_Emax2) : 0.;
    DEmaxs1 = 0.
    emaxs1 = electron.detailValue(egammaParameters.emaxs1)
    Emax2 = electron.detailValue(egammaParameters.e2tsts1)
    if abs(emaxs1 + Emax2) > 0.:
        DEmaxs1 = (emaxs1 - Emax2) / (emaxs1 + Emax2)

    # double rHad            =  el_Ethad/Et_cl;
    rHad = electron.detailValue(egammaParameters.ethad) / Et_cl
    # double rHad1           =  el_Ethad1/Et_cl;
    rHad1 = electron.detailValue(egammaParameters.ethad1) / Et_cl
    # double Reta            =  el_reta;
    e237 = electron.detailValue(egammaParameters.e237)
    e277 = electron.detailValue(egammaParameters.e277)
    Reta = 0.
    if e277 != 0.:
        Reta = e237 / e277
    # double w2              =  el_weta2;
    w2 = electron.detailValue(egammaParameters.weta2)
    # double f1              =  el_f1;
    f1 = electron.detailValue(egammaParameters.f1)
    # double f3              =  el_f3;
    f3 = electron.detailValue(egammaParameters.f3)
    # double wstot           =  el_wstot;
    wstot = electron.detailValue(egammaParameters.wtots1)
    # double deltaEta        = el_deltaeta1;
    deltaEta = electron.detailValue(egammaParameters.deltaEta1)
    # double deltaPhiRescaled = el_deltaphiRescaled;
    deltaPhiRescaled = electron.detailValue(egammaParameters.deltaPhiRescaled)

    # int    nPix             = el_nPixHits;
    nPix = electron.trackParticle().trackSummary().get(
        ROOT.Trk.numberOfPixelHits)
    # int    nSi              = el_nSiHits;
    nSi = electron.trackParticle().trackSummary().get(
        ROOT.Trk.numberOfSCTHits) + nPix
    # int    nPixDeadSensors  = el_nPixelDeadSensors;
    nPixDeadSensors = electron.trackParticle().trackSummary().get(
        ROOT.Trk.numberOfPixelDeadSensors)
    # int    nSiDeadSensors   = el_nSCTDeadSensors+el_nPixelDeadSensors;
    nSiDeadSensors = electron.trackParticle().trackSummary().get(
        ROOT.Trk.numberOfSCTDeadSensors) + nPixDeadSensors
    # int    nTRThigh         = el_nTRTHighTHits;
    nTRThigh = electron.trackParticle().trackSummary().get(
        ROOT.Trk.numberOfTRTHighThresholdHits)
    # int    nTRThighOutliers = el_nTRTHighTOutliers;
    nTRThighOutliers = electron.trackParticle().trackSummary().get(
        ROOT.Trk.numberOfTRTHighThresholdOutliers)
    # int    nTRT             = el_nTRTHits;
    nTRT = electron.trackParticle().trackSummary().get(
        ROOT.Trk.numberOfTRTHits)
    # int    nTRTOutliers     = el_nTRTOutliers;
    nTRTOutliers = electron.trackParticle().trackSummary().get(
        ROOT.Trk.numberOfTRTOutliers)
    # bool   expectBlayer     = el_expectBLayerHit;
    expectBlayer = electron.trackParticle().trackSummary().get(
        ROOT.Trk.expectBLayerHit)
    # int    nBlayerHits      = el_nBLHits;
    nBlayerHits = electron.trackParticle().trackSummary().get(
        ROOT.Trk.numberOfBLayerHits)

    nTRTTotal = nTRT + nTRTOutliers
    rTRT = 0.
    if nTRTTotal > 0:
        rTRT = float(nTRThigh + nTRThighOutliers) / float(nTRTTotal)

    dpOverp = 0.
    trackqoverp = electron.trackParticle().measuredPerigee().parameters()[
        ROOT.Trk.qOverP]
    for id in range(electron.nDetails()):
        if not electron.detailElementLink(id).isValid():
            continue
        if electron.detailName(id) != "egDetailAOD":
            print 'H4lDPDMaker::passMultiLepton WARNING electron.detailName(%i) = %s != egDetailAOD' % (
                id, electron.detailName(id))
            continue
        if not isinstance(electron.detail(id), PyAthena.EMTrackFit
                          ):  # This corresponds to dynamic_cast in C++
            continue
        if electron.detail(id).linkIndex() >= electron.nTrackParticles():
            continue
        if electron.detail(id).bremTrackAuthor() != 4:
            continue
        dpOverp = 1. - (trackqoverp / electron.detail(id).track_LastM_qOverP())
        break

    return multiLeptonMenu.passMultiLepton(etas2, Et_cl,\
                                           rHad, rHad1, Reta, w2,\
                                           f1,f3, wstot, DEmaxs1,\
                                           deltaEta, nSi,nSiDeadSensors, nPix,\
                                           nPixDeadSensors,deltaPhiRescaled,dpOverp,\
                                           rTRT,nTRTTotal,nBlayerHits,expectBlayer)
コード例 #35
0
    def analyze(self, event):
        # Read branches that may be created by previous step in the chain
        # It's important to read them like this in case they
        # are created by the step before in a PostProcessor chain.
        self.vbs_category = event.VBS_category
        self.rawJet_coll = Collection(event, 'Jet')
        self.Jet_coll = Collection(event, 'CleanJet')
        self.JetNotFat_coll = Collection(event, 'CleanJetNotFat')

        # # do this check at every event, as other modules might have read further branches
        # if event._tree._ttreereaderversion > self._ttreereaderversion:
        #     self.initReaders(event._tree)

        lepton_raw = Object(event, "Lepton", index=0)
        puppiMET = Object(event, "PuppiMET")
        category = int(self.vbs_category)

        lep = TLorentzVector()
        lep.SetPtEtaPhiE(lepton_raw.pt, lepton_raw.eta, lepton_raw.phi,
                         lepton_raw.pt * cosh(lepton_raw.eta))
        puppimet = TLorentzVector()
        puppimet.SetPtEtaPhiE(puppiMET.pt, 0., puppiMET.phi, puppiMET.pt)

        # Trick for ArrayRead -> list
        # vbs_jets_index = [self.vbs_jets[0], self.vbs_jets[1]]
        # v_jets_index = [self.v_jets[0], self.v_jets[1]]

        jets, jets_ids = self.get_jets_vectors(self.minptjet)

        output = None

        if category == 0:
            #####################
            # Boosted category
            v_jets_index = [
                event[self.V_jets_var[0]][0], event[self.V_jets_var[0]][1]
            ]
            vbs_jets_index = [
                event[self.VBS_jets_var[0]][0], event[self.VBS_jets_var[0]][1]
            ]
            fatjet = Object(event, "CleanFatJet", index=0)
            other_jets = []
            vbsjets = []
            # N.B. VBsjets and VJets indexes refers to the original CleanJet collection
            # the jets list is loaded with the NotFatJet mask. We have to compare original ids.
            for jet, jetind in zip(jets, jets_ids):
                if jetind in vbs_jets_index:
                    vbsjets.append(jet)
                else:
                    other_jets.append(jet)

            # CleanFatJet collection mass is Softdrop PUPPI mass
            output = vbs_vars.getVBSkin_boosted(vbsjets,
                                                fatjet.p4(),
                                                lep,
                                                puppimet,
                                                other_jets,
                                                debug=self.debug)

        elif category == 1:
            #####################
            # Resolved category
            v_jets_index = [
                event[self.V_jets_var[1]][0], event[self.V_jets_var[1]][1]
            ]
            vbs_jets_index = [
                event[self.VBS_jets_var[1]][0], event[self.VBS_jets_var[1]][1]
            ]
            other_jets = []
            vbsjets = []
            vjets = []
            for jet, jetind in zip(jets, jets_ids):
                if jetind in vbs_jets_index:
                    vbsjets.append(jet)
                elif jetind in v_jets_index:
                    vjets.append(jet)
                else:
                    other_jets.append(jet)
            output = vbs_vars.getVBSkin_resolved(vbsjets,
                                                 vjets,
                                                 lep,
                                                 puppimet,
                                                 other_jets,
                                                 debug=self.debug)

        # elif category == 2:
        #     ##############################
        #     # Missing jet (3-jet) category
        #     if self.debug: print "Category 2: Missing one jet"
        #     output = vbs_vars.getDefault()

        # Fill the branches
        for var, val in output.items():
            self.out.fillBranch(var, val)
        """return True (go to next module) or False (fail, go to next event)"""
        return True
コード例 #36
0
ファイル: test_loadlib.py プロジェクト: jamienoss/msl-loadlib
def test_java():
    jar = loadlib.LoadLibrary(EXAMPLES_DIR + '/java_lib.jar')

    Math = jar.lib.nz.msl.examples.MathUtils
    Matrix = jar.lib.nz.msl.examples.Matrix

    assert 0.0 <= Math.random() < 1.0
    assert abs(Math.sqrt(32.4) - 5.69209978830308) < eps

    #
    # check LU decomposition
    #

    n = 14
    m1 = Matrix(n, n, 2.0, 8.0)
    L = m1.getL()
    U = m1.getU()
    LU = m1.multiply(L, U)
    for i in range(n):
        for j in range(n):
            assert abs(m1.getValue(i, j) - LU.getValue(i, j)) < eps

    #
    # check QR decomposition
    #

    n = 8
    m2 = Matrix(n, n, -100.0, 100.0)
    Q = m2.getQ()
    R = m2.getR()
    QR = m2.multiply(Q, R)
    for i in range(n):
        for j in range(n):
            assert abs(m2.getValue(i, j) - QR.getValue(i, j)) < eps

    #
    # solve Ax=b
    #
    m3 = jar.gateway.new_array(jar.lib.Double, 3, 3)
    m3[0][0] = 3.
    m3[0][1] = 2.
    m3[0][2] = -1.
    m3[1][0] = 2.
    m3[1][1] = -2.
    m3[1][2] = 4.
    m3[2][0] = -1.0
    m3[2][1] = 0.5
    m3[2][2] = 1.0

    m4 = jar.gateway.new_array(jar.lib.Double, 3)
    m4[0] = 1.0
    m4[1] = -2.0
    m4[2] = 0.0

    A = Matrix(m3)
    x = Matrix.solve(A, Matrix(m4))

    bprime = Matrix.multiply(A, x)
    for i in range(3):
        assert abs(bprime.getValue(i, 0) - m4[i]) < eps

    #
    # Check inverse
    #
    n = 30
    m5 = Matrix(n, n, 0.0, 100.0)
    m6 = m5.getInverse()
    m7 = Matrix.multiply(m5, m6)
    identity = Matrix(n)
    for i in range(n):
        for j in range(n):
            assert abs(identity.getValue(i, j) - m7.getValue(i, j)) < eps

    #
    # Check determinant
    #
    a = [[6, 1, 1], [4, -2, 5], [2, 8, 7]]
    ja = jar.gateway.new_array(jar.lib.Double, 3, 3)
    for i in range(3):
        for j in range(3):
            ja[i][j] = float(a[i][j])
    m8 = Matrix(ja)
    assert abs(m8.getDeterminant() - (-306)) < eps

    jar.gateway.shutdown()

    import math

    cls = loadlib.LoadLibrary(EXAMPLES_DIR + '/Trig.class')
    Trig = cls.lib.Trig

    x = 0.123456
    assert abs(Trig.cos(x) - math.cos(x)) < eps
    assert abs(Trig.cosh(x) - math.cosh(x)) < eps
    assert abs(Trig.acos(x) - math.acos(x)) < eps
    assert abs(Trig.sin(x) - math.sin(x)) < eps
    assert abs(Trig.sinh(x) - math.sinh(x)) < eps
    assert abs(Trig.asin(x) - math.asin(x)) < eps
    assert abs(Trig.tan(x) - math.tan(x)) < eps
    assert abs(Trig.tanh(x) - math.tanh(x)) < eps
    assert abs(Trig.atan(x) - math.atan(x)) < eps
    assert abs(Trig.atan2(-4.321, x) - math.atan2(-4.321, x)) < eps

    cls.gateway.shutdown()
コード例 #37
0
def sec_bend_matrix(L, B, n, p, rest_mass=938):

    if B == 0:
        return drift_matrix(L, p, rest_mass=rest_mass)

    Brho = PtoBrho(p)
    h = B / Brho

    if n > 0 and n < 1:
        kx = sqrt((1 - n) * h**2)
        ky = sqrt(n * h**2)
        bend_mat = np.array([[
            cos(kx * L), 1 / kx * sin(kx * L), 0, 0, 0,
            h / kx**2 * (1 - cos(kx * L))
        ], [-kx * sin(kx * L),
            cos(kx * L), 0, 0, 0, h / kx * sin(kx * L)],
                             [0, 0,
                              cos(ky * L), 1 / ky * sin(ky * L), 0, 0],
                             [0, 0, -ky * sin(ky * L),
                              cos(ky * L), 0, 0],
                             [
                                 -h / kx * sin(kx * L),
                                 -h / kx**2 * (1 - cos(kx * L)), 0, 0, 1,
                                 -h**2 / kx**3 * (kx * L - sin(kx * L))
                             ], [0, 0, 0, 0, 0, 1]])
    elif n > 1:
        kx = sqrt(-(1 - n) *
                  h**2)  #complex value --> change sign and forumulas
        ky = sqrt(n * h**2)
        bend_mat = np.array([[
            cosh(kx * L), 1 / kx * sinh(kx * L), 0, 0, 0,
            -h / kx**2 * (1 - cosh(kx * L))
        ], [kx * sinh(kx * L),
            cosh(kx * L), 0, 0, 0, h / kx * sinh(kx * L)],
                             [0, 0,
                              cos(ky * L), 1 / ky * sin(ky * L), 0, 0],
                             [0, 0, -ky * sin(ky * L),
                              cos(ky * L), 0, 0],
                             [
                                 -h / kx * sinh(kx * L),
                                 h / kx**2 * (1 - cosh(kx * L)), 0, 0, 1,
                                 h**2 / kx**3 * (kx * L - sinh(kx * L))
                             ], [0, 0, 0, 0, 0, 1]])
    elif n < 0:
        kx = sqrt((1 - n) * h**2)
        ky = sqrt(-n * h**2)  #complex value --> change sign and forumulas
        bend_mat = np.array([[
            cos(kx * L), 1 / kx * sin(kx * L), 0, 0, 0,
            h / kx**2 * (1 - cos(kx * L))
        ], [-kx * sin(kx * L),
            cos(kx * L), 0, 0, 0, h / kx * sin(kx * L)],
                             [0, 0,
                              cosh(ky * L), 1 / ky * sinh(ky * L), 0, 0],
                             [0, 0, ky * sinh(ky * L),
                              cosh(ky * L), 0, 0],
                             [
                                 -h / kx * sin(kx * L),
                                 -h / kx**2 * (1 - cos(kx * L)), 0, 0, 1,
                                 -h**2 / kx**3 * (kx * L - sin(kx * L))
                             ], [0, 0, 0, 0, 0, 1]])
    elif n == 1:  #kx=0
        ky = sqrt(n * h**2)
        bend_mat = np.array(
            [[1, L, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0],
             [0, 0, cos(ky * L), 1 / ky * sin(ky * L), 0, 0],
             [0, 0, -ky * sin(ky * L),
              cos(ky * L), 0, 0],
             [-h * L, -h * L**2 / 2, 0, 0, 1, -h**2 * L**3 / 6],
             [0, 0, 0, 0, 0, 1]])
    elif n == 0:
        kx = sqrt((1 - n) * h**2)  #ky=0
        bend_mat = np.array([[
            cos(kx * L), 1 / kx * sin(kx * L), 0, 0, 0,
            h / kx**2 * (1 - cos(kx * L))
        ], [-kx * sin(kx * L),
            cos(kx * L), 0, 0, 0, h / kx * sin(kx * L)], [0, 0, 1, L, 0, 0],
                             [0, 0, 0, 1, 0, 0],
                             [
                                 -h / kx * sin(kx * L),
                                 -h / kx**2 * (1 - cos(kx * L)), 0, 0, 1,
                                 -h**2 / kx**3 * (kx * L - sin(kx * L))
                             ], [0, 0, 0, 0, 0, 1]])

    return bend_mat
コード例 #38
0
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""
        # do this check at every event, as other modules might have read further branches
        #if event._tree._ttreereaderversion > self._ttreereaderversion: 
        #    self.initReaders(event._tree)
        #nOrgJets = getattr(event, "nJet")
        #OrgJets = Collection(event, "Jet")

	# initialize
	self.GenH_v4.SetPtEtaPhiM(0,0,0,0)
	self.gSingleLept_v4.SetPtEtaPhiM(0,0,0,0)
	self.gMet_v4.SetPtEtaPhiM(0,0,0,0)
	self.gW_Lept_v4.SetPtEtaPhiM(0,0,0,0)
	self.gW_Ak8_v4.SetPtEtaPhiM(0,0,0,0)
	self.gW_Ak4_v4.SetPtEtaPhiM(0,0,0,0)

        Lept_col        = Collection(event, 'Lepton')
        CleanJet_col    = Collection(event, 'CleanJet')
        FatJet_col      = Collection(event, 'FatJet')

        if self.DataMc == 'MC':
          genSemiLeptFatJetEvt = False
          genSemiLeptResolvEvt = False
	  genIsAk8_B_evt = False
	  genIsAk4_B_evt = False
          # accepted jet idx
          fidJetIdx = []
          gAk4_idx0 = 999
          gAk4_idx1 = 999
          dRAk8Ak4_list = []
          dRAk8Lept = -999
          dRAk4Lept = [-1] *2
          GenDressedLept_col    = Collection(event, 'GenDressedLepton')
          GenAK4_col            = Collection(event, 'GenJet')
          GenAK8_col            = Collection(event, 'GenJetAK8')
          gMet_pt   = getattr(event, "GenMET_pt")
          gMet_phi  = getattr(event, "GenMET_phi")
          # For single lepton evt
          singleLeptEvt = False
          gSingleLept_id  = -999
          gSingleLept_pt  = -1000
          gSingleLept_eta = -999
          gSingleLept_phi = -999

          for idx in range(GenDressedLept_col._len):
            gLept_id = GenDressedLept_col[idx]['pdgId']
            gLept_pt = GenDressedLept_col[idx]['pt']
            gLept_eta = GenDressedLept_col[idx]['eta']
            gLept_phi = GenDressedLept_col[idx]['phi']
            if not singleLeptEvt:
              if gLept_pt > 30:
                if abs(gLept_id) == 11:
                  if abs(gLept_eta) < 2.1:
                    singleLeptEvt = True
                    gSingleLept_id = gLept_id
                    gSingleLept_pt = gLept_pt
                    gSingleLept_eta = gLept_eta
                    gSingleLept_phi = gLept_phi
                    continue
                elif abs(gLept_id) == 13:
                  if abs(gLept_eta) < 2.4:
                    singleLeptEvt = True
                    gSingleLept_id = gLept_id
                    gSingleLept_pt = gLept_pt
                    gSingleLept_eta = gLept_eta
                    gSingleLept_phi = gLept_phi
                    continue
                else:
                  continue
            # check additional lepton
            if singleLeptEvt == True :
              if abs(gLept_id) == 11:
                if abs(gLept_eta) < 2.1 and gLept_pt > 15:
                  singleLeptEvt = False
                  break
              elif abs(gLept_id) == 13:
                if abs(gLept_eta) < 2.4 and gLept_pt > 10:
                  singleLeptEvt = False
                  break
              else : pass
          # Only for single lepton evt ##############################
          if singleLeptEvt :
            # Wleptonic decay recon
            gSingleLept_px = gSingleLept_pt*math.cos(gSingleLept_phi)
            gSingleLept_py = gSingleLept_pt*math.sin(gSingleLept_phi)
            gSingleLept_pz = gSingleLept_pt*math.sinh(gSingleLept_eta) ##pz = pt*sinh(eta)
            gSingleLept_E  = gSingleLept_pt*math.cosh(gSingleLept_eta) ## p = pt*cosh(eta)
            self.gSingleLept_v4.SetPxPyPzE(gSingleLept_px, gSingleLept_py, gSingleLept_pz, gSingleLept_E)
            gMet_px = gMet_pt*math.cos(gMet_phi)
            gMet_py = gMet_pt*math.sin(gMet_phi)
            gMet_pz = self.WlepMetPzCalc( gSingleLept_E, gSingleLept_pt, gSingleLept_pz, gSingleLept_phi,
                gMet_pt, gMet_phi)
            gMet_E  = math.sqrt(gMet_pz**2 + gMet_pt**2)
            self.gMet_v4.SetPxPyPzE(gMet_px, gMet_py, gMet_pz, gMet_E)

            # Check if Boosted Evt ########################
            for igAk8 in range(GenAK8_col._len):
	      if genIsAk8_B_evt : break
              if genSemiLeptFatJetEvt : break
              gW_Ak8_pt    = GenAK8_col[igAk8]['pt']
              gW_Ak8_eta   = GenAK8_col[igAk8]['eta']
              gW_Ak8_phi   = GenAK8_col[igAk8]['phi']
              gW_Ak8_mass  = GenAK8_col[igAk8]['mass']
              if gW_Ak8_pt < 200: continue
              if abs(gW_Ak8_eta) > 2.4: continue
              genSemiLeptFatJetEvt = True

              dRAk8Lept = self.getDeltaR(gW_Ak8_phi,  gW_Ak8_eta, gSingleLept_phi, gSingleLept_eta)

              for igAk4 in range(GenAK4_col._len):
                gAk4_pt 	= GenAK4_col[igAk4]['pt']
                gAk4_eta        = GenAK4_col[igAk4]['eta']
                gAk4_phi        = GenAK4_col[igAk4]['phi']
                gAk4_id         = GenAK4_col[igAk4]['partonFlavour']
                if abs(gAk4_eta) > 2.4: continue
                dRAk8Ak4 = self.getDeltaR(gW_Ak8_phi,  gW_Ak8_eta, gAk4_phi, gAk4_eta)
	        # b-veto for W_Ak8 evet
		if dRAk8Ak4 > 0.8 and abs(gAk4_id) == 5 and gAk4_pt > 20:
		  genIsAk8_B_evt = True
		  genSemiLeptFatJetEvt = False
		  break
                elif gAk4_pt > 30:
                  dRAk8Ak4_list.append( dRAk8Ak4 )
		else: pass

            # Check if Resolved Evt ####################################
            if not genSemiLeptFatJetEvt and not genIsAk8_B_evt:
              for idx in range(GenAK4_col._len):
                gAk4_0_pt               = GenAK4_col[idx]['pt']
                gAk4_0_eta      = GenAK4_col[idx]['eta']
                if gAk4_0_pt < 30: continue
                if abs(gAk4_0_eta) > 2.4: continue
                fidJetIdx.append(idx)
              # Pairing Ak4s
              dM = 9999.
              for idx in fidJetIdx:
                for jdx in fidJetIdx:
                  if jdx <= idx: continue
                  gAk4_0_pt     = GenAK4_col[idx]['pt']
                  gAk4_0_eta    = GenAK4_col[idx]['eta']
                  gAk4_0_phi    = GenAK4_col[idx]['phi']
                  gAk4_0_mass   = GenAK4_col[idx]['mass']

                  gAk4_1_pt     = GenAK4_col[jdx]['pt']
                  gAk4_1_eta    = GenAK4_col[jdx]['eta']
                  gAk4_1_phi    = GenAK4_col[jdx]['phi']
                  gAk4_1_mass   = GenAK4_col[jdx]['mass']
                  WhadMass = self.InvMassCalc(gAk4_0_pt, gAk4_0_eta, gAk4_0_phi, gAk4_0_mass,
                                              gAk4_1_pt, gAk4_1_eta, gAk4_1_phi, gAk4_1_mass)
                  if abs(WhadMass - Wmass) < dM:
                    genSemiLeptResolvEvt = True
                    dM = abs(WhadMass - Wmass)
                    gAk4_idx0 = idx
                    gAk4_idx1 = jdx
	      # Check if b-event
              for idx in range(GenAK4_col._len):
                gAk4_0_pt       = GenAK4_col[idx]['pt']
                gAk4_0_eta      = GenAK4_col[idx]['eta']
                gAk4_0_id       = GenAK4_col[idx]['partonFlavour']
		if idx == gAk4_idx0 or idx == gAk4_idx1: continue
                if gAk4_0_pt < 20: continue
                if abs(gAk4_0_eta) > 2.4: continue
                if abs(gAk4_0_id) == 5:
		  genIsAk4_B_evt = True
                  genSemiLeptResolvEvt = False
		  break

              if genSemiLeptResolvEvt:
                gResJet_0_pt    = GenAK4_col[gAk4_idx0]['pt']
                gResJet_0_eta   = GenAK4_col[gAk4_idx0]['eta']
                gResJet_0_phi   = GenAK4_col[gAk4_idx0]['phi']
                gResJet_0_mass  = GenAK4_col[gAk4_idx0]['mass']
                gW_Ak4_v4_0 = ROOT.TLorentzVector()
                gW_Ak4_v4_0.SetPtEtaPhiM(gResJet_0_pt, gResJet_0_eta, gResJet_0_phi, gResJet_0_mass)
                gResJet_1_pt    = GenAK4_col[gAk4_idx1]['pt']
                gResJet_1_eta   = GenAK4_col[gAk4_idx1]['eta']
                gResJet_1_phi   = GenAK4_col[gAk4_idx1]['phi']
                gResJet_1_mass  = GenAK4_col[gAk4_idx1]['mass']
                gW_Ak4_v4_1 = ROOT.TLorentzVector()
                gW_Ak4_v4_1.SetPtEtaPhiM(gResJet_1_pt, gResJet_1_eta, gResJet_1_phi, gResJet_1_mass)
		self.gW_Ak4_v4 = gW_Ak4_v4_0 + gW_Ak4_v4_1
                dRAk4Lept[0] = self.getDeltaR(gResJet_0_phi,  gResJet_0_eta, gSingleLept_phi, gSingleLept_eta)
                dRAk4Lept[1] = self.getDeltaR(gResJet_0_phi,  gResJet_0_eta, gSingleLept_phi, gSingleLept_eta)


          if genSemiLeptFatJetEvt or  genSemiLeptResolvEvt:
            # wLeptonic 4 vector
            self.gW_Lept_v4 = self.gSingleLept_v4 + self.gMet_v4
            gW_Lept_dict = {}
            gW_Lept_dict['pt']   = self.gW_Lept_v4.Pt()
            gW_Lept_dict['eta']  = self.gW_Lept_v4.Eta()
            gW_Lept_dict['phi']  = self.gW_Lept_v4.Phi()
            gW_Lept_dict['mass'] = self.gW_Lept_v4.M()
            for var in gW_Lept_dict:
              self.out.fillBranch( 'GenW_Lept_' + var, gW_Lept_dict[var])

          if genSemiLeptFatJetEvt:
            # H+ mass recon
            #gW_Ak8_px = gAk8_pt*math.cos(gAk8_phi)
            #gW_Ak8_py = gAk8_pt*math.sin(gAk8_phi)
            #gW_Ak8_pz = gAk8_pt*math.sinh(gAk8_eta) ##pz = pt*sinh(eta)
            self.gW_Ak8_v4.SetPtEtaPhiM(gW_Ak8_pt, gW_Ak8_eta, gW_Ak8_phi, gW_Ak8_mass)

            self.GenH_v4 = self.gW_Lept_v4 + self.gW_Ak8_v4
            self.out.fillBranch("GenEvtFlag", 1)
            self.out.fillBranch("GenDrAk8Lept", dRAk8Lept)
            self.out.fillBranch("GenH_pt",  self.GenH_v4.Pt() )
            self.out.fillBranch("GenH_eta", self.GenH_v4.Eta() )
            self.out.fillBranch("GenH_phi", self.GenH_v4.Phi() )
            self.out.fillBranch("GenH_mass",self.GenH_v4.M() )
            self.out.fillBranch("GenW_Ak8_mass", gW_Ak8_mass )

          elif genSemiLeptResolvEvt:
            self.GenH_v4 = self.gW_Lept_v4 + self.gW_Ak4_v4

            self.out.fillBranch("GenEvtFlag", 2)
            self.out.fillBranch("GenH_pt",  self.GenH_v4.Pt() )
            self.out.fillBranch("GenH_eta", self.GenH_v4.Eta() )
            self.out.fillBranch("GenH_phi", self.GenH_v4.Phi() )
            self.out.fillBranch("GenH_mass",self.GenH_v4.M() )
            self.out.fillBranch("GenW_Ak4_mass", self.gW_Ak4_v4.M())
	  else :
            self.out.fillBranch("GenEvtFlag", 0)


          self.out.fillBranch("GenDrAk8Ak4", dRAk8Ak4_list)


        return True
コード例 #39
0
a,b=1,2
import math
import cmath

print(math.sin(a))
print(math.cosh(b))
print(math.atan(math.pi))
print(math.hypot(a,b)) # pareil que math.sqrt(a*a + b*b)

print(math.degrees(a)) #convertis a radiants en degrés
print(math.radians(57.299577)) #convertis 57 degrés en radians

a = a + 1
a = a * 2

a += 1
a *= 2

#logarithmes
math.log(5) # = 1.609
math.log(5, math.e) #pareil

#module : le RESTE de la division des deux nombres
print(3 % 4)  # 3 car il y a pas 4 dans 3
print(10 % 2) # 0 car il y a deux 5 dans 10
print(6 % 4)  # 2 car il y a UN 4 dans 6, et le reste est 2

print(-9 % 7) # 5
print(9 % -7) # -5
print(-9 % -7) # -2
コード例 #40
0
def geo2grid(lat, lon, zone=0, ellipsoid=grs80):
    """
    Takes a geographic co-ordinate (latitude, longitude) and returns its
    corresponding Hemisphere, Zone and Projection Easting and Northing, Point
    Scale Factor and Grid Convergence. Default Projection is Universal
    Transverse Mercator Projection using
    GRS80 Ellipsoid parameters.
    :param lat: Latitude
    :type lat: Float (Decimal Degrees), DMSAngle or DDMAngle
    :param lon: Longitude
    :type lon: Float (Decimal Degrees, DMSAngle or DDMAngle
    :param zone: Optional Zone Number - Only required if calculating grid
                                        co-ordinate outside zone boundaries
    :param ellipsoid: Ellipsoid Object
    :type ellipsoid: Ellipsoid
    :return: hemisphere, zone, east (m), north (m), Point Scale Factor,
             Grid Convergence (Decimal Degrees)
    :rtype: tuple
    """

    # Convert DMSAngle and DDMAngle to Decimal Angle
    lat = angular_typecheck(lat)
    lon = angular_typecheck(lon)
    # Input Validation - UTM Extents and Values
    zone = int(zone)
    if zone < 0 or zone > 60:
        raise ValueError('Invalid Zone - Zones from 1 to 60')

    if lat < -80 or lat > 84:
        raise ValueError('Invalid Latitude - Latitudes from -80 to +84')

    if lon < -180 or lon > 180:
        raise ValueError('Invalid Longitude - Longitudes from -180 to +180')

    A = rect_radius(ellipsoid)
    a = alpha_coeff(ellipsoid)
    lat = radians(lat)
    # Calculate Zone
    if zone == 0:
        zone = int((float(lon) - (
                    proj.initialcm - (1.5 * proj.zonewidth))) / proj.zonewidth)
    cm = float(zone * proj.zonewidth) + (proj.initialcm - proj.zonewidth)

    # Conformal Latitude
    sigx = (ellipsoid.ecc1 * tan(lat)) / sqrt(1 + (tan(lat) ** 2))
    sig = sinh(ellipsoid.ecc1 * (0.5 * log((1 + sigx) / (1 - sigx))))
    conf_lat = tan(lat) * sqrt(1 + sig ** 2) - sig * sqrt(1 + (tan(lat) ** 2))
    conf_lat = atan(conf_lat)

    # Longitude Difference
    long_diff = radians(lon - cm)
    # Gauss-Schreiber Ratios
    xi1 = atan(tan(conf_lat) / cos(long_diff))
    eta1x = sin(long_diff) / (sqrt(tan(conf_lat) ** 2 + cos(long_diff) ** 2))
    eta1 = log(eta1x + sqrt(1 + eta1x ** 2))

    # Transverse Mercator Ratios
    eta = eta1
    xi = xi1
    for r in range(1, 9):
        eta += a[r-1] * cos(2*r * xi1) * sinh(2*r * eta1)
        xi += a[r-1] * sin(2*r * xi1) * cosh(2*r * eta1)

    # Transverse Mercator Co-ordinates
    x = A * eta
    y = A * xi

    # Hemisphere-dependent UTM Projection Co-ordinates
    east = proj.cmscale * x + proj.falseeast
    if y < 0:
        hemisphere = 'South'
        north = proj.cmscale * y + proj.falsenorth
    else:
        hemisphere = 'North'
        falsenorth = 0
        north = proj.cmscale * y + falsenorth

    # Point Scale Factor and Grid Convergence
    psf, grid_conv = psfandgridconv(xi1, eta1, degrees(lat), lon, cm, conf_lat)

    return (hemisphere, zone,
            round(float(east), 4),
            round(float(north), 4),
            round(psf, 8), grid_conv)
コード例 #41
0
def grid2geo(zone, east, north, hemisphere='south', ellipsoid=grs80):
    """
    Takes a Transverse Mercator grid co-ordinate (Zone, Easting, Northing,
    Hemisphere) and returns its corresponding Geographic Latitude and Longitude,
    Point Scale Factor and Grid Convergence. Default Projection is Universal
    Transverse Mercator Projection using GRS80 Ellipsoid parameters.
    :param zone: Zone Number - 1 to 60
    :param east: Easting (m, within 3330km of Central Meridian)
    :param north: Northing (m, 0 to 10,000,000m)
    :param hemisphere: String - 'North' or 'South'(default)
    :param ellipsoid: Ellipsoid Object
    :type ellipsoid: Ellipsoid
    :return: Latitude and Longitude (Decimal Degrees), Point Scale Factor,
             Grid Convergence (Decimal Degrees)
    :rtype: tuple
    """
    # Input Validation - UTM Extents and Values
    zone = int(zone)
    if zone < 0 or zone > 60:
        raise ValueError('Invalid Zone - Zones from 1 to 60')

    if east < -2830000 or east > 3830000:
        raise ValueError('Invalid Easting - Must be within'
                         '3330km of Central Meridian')

    if north < 0 or north > 10000000:
        raise ValueError('Invalid Northing - Must be between 0 and 10,000,000m')

    h = hemisphere.lower()
    if h != 'north' and h != 'south':
        raise ValueError('Invalid Hemisphere - String, either North or South')

    A = rect_radius(ellipsoid)
    b = beta_coeff(ellipsoid)
    # Transverse Mercator Co-ordinates
    x = (east - float(proj.falseeast)) / float(proj.cmscale)
    if hemisphere.lower() == 'north':
        y = -(north / float(proj.cmscale))
        hemisign = -1
    else:
        y = (north - float(proj.falsenorth)) / float(proj.cmscale)
        hemisign = 1

    # Transverse Mercator Ratios
    xi = y / A
    eta = x / A

    # Gauss-Schreiber Ratios
    eta1 = eta
    xi1 = xi
    for r in range(1, 9):
        eta1 += b[r-1] * cos(2*r * xi) * sinh(2*r * eta)
        xi1 += b[r-1] * sin(2*r * xi) * cosh(2*r * eta)

    # Conformal Latitude
    conf_lat = (sin(xi1)) / (sqrt((sinh(eta1)) ** 2 + (cos(xi1)) ** 2))
    t1 = conf_lat
    conf_lat = atan(conf_lat)

    # Finding t using Newtons Method
    def sigma(tn, ecc1):
        return (sinh(ecc1
                     * 0.5
                     * log((1 + ((ecc1 * tn) / (sqrt(1 + tn ** 2))))
                           / (1 - ((ecc1 * tn) / (sqrt(1 + tn ** 2)))))))

    def ftn(tn, ecc1):
        return (t * sqrt(1 + (sigma(tn, ecc1)) ** 2) -
                sigma(tn, ecc1) * sqrt(1 + tn ** 2) - t1)

    def f1tn(tn, ecc1, ecc1sq):
        return ((sqrt(1 + (sigma(tn, ecc1)) ** 2) * sqrt(1 + tn ** 2)
                 - sigma(tn, ecc1) * tn)
                * (((1 - float(ecc1sq)) * sqrt(1 + t ** 2))
                   / (1 + (1 - float(ecc1sq)) * t ** 2)))

    diff = 1
    t = t1
    itercount = 0
    while diff > 1e-15 and itercount < 100:
        itercount += 1
        t_before = t
        t = t - (ftn(t, ellipsoid.ecc1)
                 / f1tn(t, ellipsoid.ecc1, ellipsoid.ecc1sq))
        diff = abs(t - t_before)
    lat = degrees(atan(t))

    # Compute Longitude
    cm = float((zone * proj.zonewidth) + proj.initialcm - proj.zonewidth)
    long_diff = degrees(atan(sinh(eta1) / cos(xi1)))
    long = cm + long_diff

    # Point Scale Factor and Grid Convergence
    psf, grid_conv = psfandgridconv(xi1, eta1, lat, long, cm, conf_lat)

    return (hemisign * round(lat, 11),
            round(long, 11), round(psf, 8),
            hemisign * grid_conv)
コード例 #42
0
ファイル: gigrnd.py プロジェクト: geighei/PRScs
def gigrnd(p, a, b):
    # setup -- sample from the two-parameter version gig(lam,omega)
    p = float(p)
    a = float(a)
    b = float(b)
    lam = p
    omega = math.sqrt(a * b)

    if lam < 0:
        lam = -lam
        swap = True
    else:
        swap = False

    # we run into issues here if omega is smaller than machine precision epsilon, in which
    # case alpha evaluates to zero, resulting in later ZeroDivisionError exception
    alpha = max(1e-16, math.sqrt(math.pow(omega, 2) + math.pow(lam, 2)) - lam)

    # find t
    x = -psi(1, alpha, lam)
    if (x >= 1 / 2) and (x <= 2):
        t = 1
    elif x > 2:
        t = math.sqrt(2 / (alpha + lam))
    elif x < 1 / 2:
        t = math.log(4 / (alpha + 2 * lam))

    # find s
    x = -psi(-1, alpha, lam)
    if (x >= 1 / 2) and (x <= 2):
        s = 1
    elif x > 2:
        s = math.sqrt(4 / (alpha * math.cosh(1) + lam))
    elif x < 1 / 2:
        try:
            s = min(
                1 / lam,
                math.log(1 + 1 / alpha +
                         math.sqrt(1 / math.pow(alpha, 2) + 2 / alpha)))
        except ZeroDivisionError:
            print("ZeroDivisionError exception thrown due to alpha value of " +
                  str(alpha) + ". Setting s = 1/lam.")
            s = 1 / lam
    # find auxiliary parameters
    eta = -psi(t, alpha, lam)
    zeta = -dpsi(t, alpha, lam)
    theta = -psi(-s, alpha, lam)
    xi = dpsi(-s, alpha, lam)

    p = 1 / xi
    r = 1 / zeta

    td = t - r * eta
    sd = s - p * theta
    q = td + sd

    # random variate generation
    while True:
        U = random.random()
        V = random.random()
        W = random.random()
        if U < q / (p + q + r):
            rnd = -sd + q * V
        elif U < (q + r) / (p + q + r):
            rnd = td - r * math.log(V)
        else:
            rnd = -sd + p * math.log(V)

        f1 = math.exp(-eta - zeta * (rnd - t))
        f2 = math.exp(-theta + xi * (rnd + s))
        if W * g(rnd, sd, td, f1, f2) <= math.exp(psi(rnd, alpha, lam)):
            break

    # transform back to the three-parameter version gig(p,a,b)
    rnd = math.exp(rnd) * (
        lam / omega + math.sqrt(1 + math.pow(lam, 2) / math.pow(omega, 2)))
    if swap:
        rnd = 1 / rnd

    rnd = rnd / math.sqrt(a / b)
    return rnd
コード例 #43
0
ファイル: gigrnd.py プロジェクト: geighei/PRScs
def psi(x, alpha, lam):
    f = -alpha * (math.cosh(x) - 1) - lam * (math.exp(x) - x - 1)
    return f
コード例 #44
0
def arccos ():
    """
    Fonction: arccos ()
    X = arccos(X)
    """
    _setX( math.cosh( get("X") ) )
コード例 #45
0
    Sum = simpson(y, h)
    Sum = math.sqrt(Sum)
    #print Sum
    for i in range(nx + 1):
        u[i] /= Sum
    f0 = ur[nr - 1] + ul[nl - 1] - ur[nr - 3] - ul[nl - 3]
    return float(f0 / (2 * h * ur[nr - 2]))


#main section
e = Sacant(ni, delta, e, de)

#plot potetial and wave function :
x = x1
V = [{}] * (nx + 1)
alpha = 1
lamb = 4
for i in range(nx + 1):
    x = x1 + i * h
    V[i] = alpha * alpha * lamb * (lamb - 1) * float(
        0.5 - float(1 / (math.pow(math.cosh(alpha * x), 2)))) / 2.

x = np.linspace(-10, 10, 501)
plt.plot(x, u, x, V)
plt.grid()
plt.title("The eigenvalue Schrodinger equation")
plt.xlabel("$x$")
plt.ylabel("$V(x),U(x)$")
plt.show()
コード例 #46
0
ファイル: LeptonSel.py プロジェクト: wadud001/LatinoAnalysis
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""

        if event._tree._ttreereaderversion > self._ttreereaderversion: # do this check at every event, as other modules might have read further branches
            self.initReaders(event._tree)
        # do NOT access other branches in python between the check/call to initReaders and the call to C++ worker code
       
        lepton_col   = Collection(event, 'Lepton')
        vetolepton_col   = Collection(event, 'VetoLepton')
        electron_col = Collection(event, 'Electron')
        muon_col     = Collection(event, 'Muon')
        jet_col      = Collection(event, 'CleanJet')
        nLep = len(lepton_col) 
        nJet = len(jet_col)
        
        # Fast lepton filter
        if nLep < self.nLF: return False

        # Tags and variables
        Clean_Tag = LepFilter_dict[self.LepFilter]
        Clean_TagWP = LepFilter_dict[Clean_Tag]

        Lep_Tags = {}
        Lep_Tags['isLoose'] = []
        Lep_Tags['isVeto'] = []
        
        for wp in self.ElectronWP[self.cmssw]['TightObjWP']:
           Lep_Tags['isTightElectron_' + wp] = []
        for wp in self.MuonWP[self.cmssw]['TightObjWP']:
           Lep_Tags['isTightMuon_' + wp] = []

        # Cleaning aid
        good_lep_idx = []
        good_vetlep_idx = []
        good_jet_idx = range(nJet)
        Clean_counter = 0

        if self.doWgS:
            Lep_Tags['isWgs'] = []
            Lep_Wgs = self.passWgS(lepton_col, electron_col, muon_col)

        #------ Lepton Loop
        for iLep in range(nLep):
           
           # Check lepton hygiene
           isClean_lep = True
           isVeto_lep = True
           if abs(lepton_col[iLep]['pdgId']) == 11:
              if self.doWgS: isClean_lep = Lep_Wgs[iLep]
              else:
                for wp in self.ElectronWP[self.cmssw][Clean_TagWP]:
                   if not self.passWP(lepton_col, electron_col, muon_col, iLep, self.ElectronWP[self.cmssw][Clean_TagWP][wp]): isClean_lep = False
              for wp in self.ElectronWP[self.cmssw]['VetoObjWP']:
                 if not self.passWP(lepton_col, electron_col, muon_col, iLep, self.ElectronWP[self.cmssw]['VetoObjWP'][wp]): isVeto_lep = False
           elif abs(lepton_col[iLep]['pdgId']) == 13:
              if self.doWgS: isClean_lep = Lep_Wgs[iLep]
              else:
                for wp in self.MuonWP[self.cmssw][Clean_TagWP]:
                   if not self.passWP(lepton_col, electron_col, muon_col, iLep, self.MuonWP[self.cmssw][Clean_TagWP][wp]): isClean_lep = False
              for wp in self.MuonWP[self.cmssw]['VetoObjWP']:
                 if not self.passWP(lepton_col, electron_col, muon_col, iLep, self.MuonWP[self.cmssw]['VetoObjWP'][wp]): isVeto_lep = False

           # Filter illegal lepton pgdId's 
           else: 
              isClean_lep = False
              isVeto_lep = False

           if isVeto_lep:
              good_vetlep_idx.append(iLep)
              Lep_Tags['isVeto'].append(1)
           else:
              Lep_Tags['isVeto'].append(0)
 
           if not isClean_lep: continue
              
           # Lepton id's
           if self.doWgS: Lep_Tags['isWgs'].append(1)
           if abs(lepton_col[iLep]['pdgId']) == 11:
              for wp in self.ElectronWP[self.cmssw]['FakeObjWP']:
                 if self.passWP(lepton_col, electron_col, muon_col, iLep, self.ElectronWP[self.cmssw]['FakeObjWP'][wp]):   Lep_Tags['isLoose'].append(1)
                 else: Lep_Tags['isLoose'].append(0)
              for wp in self.ElectronWP[self.cmssw]['TightObjWP']:
                 if self.passWP(lepton_col, electron_col, muon_col, iLep, self.ElectronWP[self.cmssw]['TightObjWP'][wp]):  Lep_Tags['isTightElectron_' + wp].append(1)
                 else: Lep_Tags['isTightElectron_' + wp].append(0)
              for wp in self.MuonWP[self.cmssw]['TightObjWP']:
                 Lep_Tags['isTightMuon_' + wp].append(0)
           elif abs(lepton_col[iLep]['pdgId']) == 13:
              for wp in self.MuonWP[self.cmssw]['FakeObjWP']:
                 if self.passWP(lepton_col, electron_col, muon_col, iLep, self.MuonWP[self.cmssw]['FakeObjWP'][wp]):   Lep_Tags['isLoose'].append(1)
                 else: Lep_Tags['isLoose'].append(0)
              for wp in self.MuonWP[self.cmssw]['TightObjWP']:
                 if self.passWP(lepton_col, electron_col, muon_col, iLep, self.MuonWP[self.cmssw]['TightObjWP'][wp]):  Lep_Tags['isTightMuon_' + wp].append(1)
                 else: Lep_Tags['isTightMuon_' + wp].append(0)
              for wp in self.ElectronWP[self.cmssw]['TightObjWP']:
                 Lep_Tags['isTightElectron_' + wp].append(0)
           #else: raise ValueError('Unexpected Lepton_pdgId occured: Lepton_pdgId = ' + str(lepton_col[iLep]['pdgId']))

           # Cleaning aids
           good_lep_idx.append(iLep)
           if Clean_counter < self.nLF:
              if lepton_col[iLep]['pt'] > self.Lep_minPt[Clean_counter]: Clean_counter += 1          

           # Jet lepton filter   
           if lepton_col[iLep]['pt'] < self.JC_minPtLep: continue
           Eta_lep = lepton_col[iLep]['eta']
           Phi_lep = lepton_col[iLep]['phi']      
           #------ Jet Loop
           for iJet in good_jet_idx:
              Eta_jet = jet_col[iJet]['eta']
              Phi_jet = jet_col[iJet]['phi']
              if abs(Eta_jet) > self.JC_absEta:
                 if iJet in good_jet_idx: 
                    good_jet_idx.remove(iJet)
              if self.jetIsLepton(Eta_jet, Phi_jet, Eta_lep, Phi_lep):
                 if iJet in good_jet_idx: 
                    good_jet_idx.remove(iJet)

        # Lepton cleaning
        if Clean_counter < self.nLF: return False

        # MET filter (moved to TriggerMaker)
        
        # dmZll
        dmZll = 9999.
        for i in range(len(vetolepton_col)):
           if i not in good_vetlep_idx: continue
           for j in range(len(vetolepton_col)):
              if j not in good_vetlep_idx: continue
              if i == j: continue
              if vetolepton_col[j]['pt'] < 10.: break
              if not vetolepton_col[i]['pdgId'] == -1.*vetolepton_col[j]['pdgId']: continue
              temp_dmZll = abs( math.sqrt(2*vetolepton_col[i]['pt']*vetolepton_col[j]['pt']*\
                                          (math.cosh(vetolepton_col[i]['eta']-vetolepton_col[j]['eta']) - \
                                           math.cos(vetolepton_col[i]['phi']- vetolepton_col[j]['phi']))) - 91.1876)
              if temp_dmZll < dmZll: dmZll = temp_dmZll

        # Filling new branches
        for key in Lep_Tags:
           self.out.fillBranch('Lepton_' + key, Lep_Tags[key])
        self.out.fillBranch('dmZll_veto', dmZll) 

        # Cleaning and filling old branches
        for typ in Lepton_br:
           for name in Lepton_br[typ]:
              temp_v = []
              temp_v = [lepton_col[idx][name[7:]] for idx in good_lep_idx]
              self.out.fillBranch(name, temp_v)
        for typ in VetoLepton_br:
           for name in VetoLepton_br[typ]:
              temp_v = []
              temp_v = [vetolepton_col[idx][name[11:]] for idx in good_vetlep_idx]
              self.out.fillBranch(name, temp_v)
        for typ in CleanJet_br:
           for name in CleanJet_br[typ]:
              temp_v = []
              temp_v = [jet_col[idx][name[9:]] for idx in good_jet_idx]
              self.out.fillBranch(name, temp_v)
 
        return True
コード例 #47
0
 def T(a,b,d):
     if d > 700:
         return 0
     else:
         T = (math.cosh(a+b) - math.cosh(a-b))/(math.cosh(a+b) + math.cosh(d))
         return T
コード例 #48
0
    def testFunctions(self):
        """ Test all built-in simple functions """
        doc = FreeCAD.newDocument()
        sheet = self.doc.addObject('Spreadsheet::Sheet', 'Spreadsheet')
        sheet.set('A1', '=cos(60)')  # Cos
        sheet.set('B1', '=cos(60deg)')
        sheet.set('C1', '=cos(pi / 2 * 1rad)')
        sheet.set('A2', '=sin(30)')  # Sin
        sheet.set('B2', '=sin(30deg)')
        sheet.set('C2', '=sin(pi / 6 * 1rad)')
        sheet.set('A3', '=tan(45)')  # Tan
        sheet.set('B3', '=tan(45deg)')
        sheet.set('C3', '=tan(pi / 4 * 1rad)')
        sheet.set('A4', '=abs(3)')  # Abs
        sheet.set('B4', '=abs(-3)')
        sheet.set('C4', '=abs(-3mm)')
        sheet.set('A5', '=exp(3)')  # Exp
        sheet.set('B5', '=exp(-3)')
        sheet.set('C5', '=exp(-3mm)')
        sheet.set('A6', '=log(3)')  # Log
        sheet.set('B6', '=log(-3)')
        sheet.set('C6', '=log(-3mm)')
        sheet.set('A7', '=log10(10)')  # Log10
        sheet.set('B7', '=log10(-3)')
        sheet.set('C7', '=log10(-3mm)')
        sheet.set('A8', '=round(3.4)')  # Round
        sheet.set('B8', '=round(3.6)')
        sheet.set('C8', '=round(-3.4)')
        sheet.set('D8', '=round(-3.6)')
        sheet.set('E8', '=round(3.4mm)')
        sheet.set('F8', '=round(3.6mm)')
        sheet.set('G8', '=round(-3.4mm)')
        sheet.set('H8', '=round(-3.6mm)')
        sheet.set('A9', '=trunc(3.4)')  # Trunc
        sheet.set('B9', '=trunc(3.6)')
        sheet.set('C9', '=trunc(-3.4)')
        sheet.set('D9', '=trunc(-3.6)')
        sheet.set('E9', '=trunc(3.4mm)')
        sheet.set('F9', '=trunc(3.6mm)')
        sheet.set('G9', '=trunc(-3.4mm)')
        sheet.set('H9', '=trunc(-3.6mm)')
        sheet.set('A10', '=ceil(3.4)')  # Ceil
        sheet.set('B10', '=ceil(3.6)')
        sheet.set('C10', '=ceil(-3.4)')
        sheet.set('D10', '=ceil(-3.6)')
        sheet.set('E10', '=ceil(3.4mm)')
        sheet.set('F10', '=ceil(3.6mm)')
        sheet.set('G10', '=ceil(-3.4mm)')
        sheet.set('H10', '=ceil(-3.6mm)')
        sheet.set('A11', '=floor(3.4)')  # Floor
        sheet.set('B11', '=floor(3.6)')
        sheet.set('C11', '=floor(-3.4)')
        sheet.set('D11', '=floor(-3.6)')
        sheet.set('E11', '=floor(3.4mm)')
        sheet.set('F11', '=floor(3.6mm)')
        sheet.set('G11', '=floor(-3.4mm)')
        sheet.set('H11', '=floor(-3.6mm)')
        sheet.set('A12', '=asin(0.5)')  # Asin
        sheet.set('B12', '=asin(0.5mm)')
        sheet.set('A13', '=acos(0.5)')  # Acos
        sheet.set('B13', '=acos(0.5mm)')
        sheet.set('A14', '=atan(sqrt(3))')  # Atan
        sheet.set('B14', '=atan(0.5mm)')
        sheet.set('A15', '=sinh(0.5)')  # Sinh
        sheet.set('B15', '=sinh(0.5mm)')
        sheet.set('A16', '=cosh(0.5)')  # Cosh
        sheet.set('B16', '=cosh(0.5mm)')
        sheet.set('A17', '=tanh(0.5)')  # Tanh
        sheet.set('B17', '=tanh(0.5mm)')
        sheet.set('A18', '=sqrt(4)')  # Sqrt
        sheet.set('B18', '=sqrt(4mm^2)')
        sheet.set('A19', '=mod(7; 4)')  # Mod
        sheet.set('B19', '=mod(-7; 4)')
        sheet.set('C19', '=mod(7mm; 4)')
        sheet.set('D19', '=mod(7mm; 4mm)')
        sheet.set('A20', '=atan2(3; 3)')  # Atan2
        sheet.set('B20', '=atan2(-3; 3)')
        sheet.set('C20', '=atan2(3mm; 3)')
        sheet.set('D20', '=atan2(3mm; 3mm)')
        sheet.set('A21', '=pow(7; 4)')  # Pow
        sheet.set('B21', '=pow(-7; 4)')
        sheet.set('C21', '=pow(7mm; 4)')
        sheet.set('D21', '=pow(7mm; 4mm)')
        sheet.set('A23', '=hypot(3; 4)')  # Hypot
        sheet.set('B23', '=hypot(-3; 4)')
        sheet.set('C23', '=hypot(3mm; 4)')
        sheet.set('D23', '=hypot(3mm; 4mm)')
        sheet.set('A24', '=hypot(3; 4; 5)')  # Hypot
        sheet.set('B24', '=hypot(-3; 4; 5)')
        sheet.set('C24', '=hypot(3mm; 4; 5)')
        sheet.set('D24', '=hypot(3mm; 4mm; 5mm)')
        sheet.set('A26', '=cath(5; 3)')  # Cath
        sheet.set('B26', '=cath(-5; 3)')
        sheet.set('C26', '=cath(5mm; 3)')
        sheet.set('D26', '=cath(5mm; 3mm)')

        l = math.sqrt(5 * 5 + 4 * 4 + 3 * 3)
        sheet.set('A27', '=cath(%0.15f; 5; 4)' % l)  # Cath
        sheet.set('B27', '=cath(%0.15f; -5; 4)' % l)
        sheet.set('C27', '=cath(%0.15f mm; 5mm; 4)' % l)
        sheet.set('D27', '=cath(%0.15f mm; 5mm; 4mm)' % l)

        self.doc.recompute()
        self.assertMostlyEqual(sheet.A1, 0.5)  # Cos
        self.assertMostlyEqual(sheet.B1, 0.5)
        self.assertMostlyEqual(sheet.C1, 0)
        self.assertMostlyEqual(sheet.A2, 0.5)  # Sin
        self.assertMostlyEqual(sheet.B2, 0.5)
        self.assertMostlyEqual(sheet.C2, 0.5)
        self.assertMostlyEqual(sheet.A3, 1)  # Tan
        self.assertMostlyEqual(sheet.B3, 1)
        self.assertMostlyEqual(sheet.C3, 1)
        self.assertMostlyEqual(sheet.A4, 3)  # Abs
        self.assertMostlyEqual(sheet.B4, 3)
        self.assertMostlyEqual(sheet.C4, Units.Quantity('3 mm'))
        self.assertMostlyEqual(sheet.A5, math.exp(3))  # Exp
        self.assertMostlyEqual(sheet.B5, math.exp(-3))
        self.assertEqual(sheet.C5, u'ERR: Unit must be empty.')
        self.assertMostlyEqual(sheet.A6, math.log(3))  # Log
        self.assertTrue(math.isnan(sheet.B6))
        self.assertEqual(sheet.C6, u'ERR: Unit must be empty.')
        self.assertMostlyEqual(sheet.A7, math.log10(10))  # Log10
        self.assertTrue(math.isnan(sheet.B7))
        self.assertEqual(sheet.C7, u'ERR: Unit must be empty.')
        self.assertMostlyEqual(sheet.A8, 3)  # Round
        self.assertMostlyEqual(sheet.B8, 4)
        self.assertMostlyEqual(sheet.C8, -3)
        self.assertMostlyEqual(sheet.D8, -4)
        self.assertEqual(sheet.E8, Units.Quantity('3 mm'))
        self.assertEqual(sheet.F8, Units.Quantity('4 mm'))
        self.assertEqual(sheet.G8, Units.Quantity('-3 mm'))
        self.assertEqual(sheet.H8, Units.Quantity('-4 mm'))
        self.assertMostlyEqual(sheet.A9, 3)  # Trunc
        self.assertMostlyEqual(sheet.B9, 3)
        self.assertMostlyEqual(sheet.C9, -3)
        self.assertMostlyEqual(sheet.D9, -3)
        self.assertEqual(sheet.E9, Units.Quantity('3 mm'))
        self.assertEqual(sheet.F9, Units.Quantity('3 mm'))
        self.assertEqual(sheet.G9, Units.Quantity('-3 mm'))
        self.assertEqual(sheet.H9, Units.Quantity('-3 mm'))
        self.assertMostlyEqual(sheet.A10, 4)  # Ceil
        self.assertMostlyEqual(sheet.B10, 4)
        self.assertMostlyEqual(sheet.C10, -3)
        self.assertMostlyEqual(sheet.D10, -3)
        self.assertMostlyEqual(sheet.E10, Units.Quantity('4 mm'))
        self.assertMostlyEqual(sheet.F10, Units.Quantity('4 mm'))
        self.assertMostlyEqual(sheet.G10, Units.Quantity('-3 mm'))
        self.assertMostlyEqual(sheet.H10, Units.Quantity('-3 mm'))
        self.assertMostlyEqual(sheet.A11, 3)  # Floor
        self.assertMostlyEqual(sheet.B11, 3)
        self.assertMostlyEqual(sheet.C11, -4)
        self.assertMostlyEqual(sheet.D11, -4)
        self.assertMostlyEqual(sheet.E11, Units.Quantity('3 mm'))
        self.assertMostlyEqual(sheet.F11, Units.Quantity('3 mm'))
        self.assertMostlyEqual(sheet.G11, Units.Quantity('-4 mm'))
        self.assertMostlyEqual(sheet.H11, Units.Quantity('-4 mm'))
        self.assertMostlyEqual(sheet.A12, Units.Quantity('30 deg'))  # Asin
        self.assertEqual(sheet.B12, u'ERR: Unit must be empty.')
        self.assertMostlyEqual(sheet.A13, Units.Quantity('60 deg'))  # Acos
        self.assertEqual(sheet.B13, u'ERR: Unit must be empty.')
        self.assertMostlyEqual(sheet.A14, Units.Quantity('60 deg'))  # Atan
        self.assertEqual(sheet.B14, u'ERR: Unit must be empty.')
        self.assertMostlyEqual(sheet.A15, math.sinh(0.5))  # Sinh
        self.assertEqual(sheet.B15, u'ERR: Unit must be empty.')
        self.assertMostlyEqual(sheet.A16, math.cosh(0.5))  # Cosh
        self.assertEqual(sheet.B16, u'ERR: Unit must be empty.')
        self.assertMostlyEqual(sheet.A17, math.tanh(0.5))  # Tanh
        self.assertEqual(sheet.B17, u'ERR: Unit must be empty.')
        self.assertMostlyEqual(sheet.A18, 2)  # Sqrt
        self.assertMostlyEqual(sheet.B18, Units.Quantity('2 mm'))
        self.assertMostlyEqual(sheet.A19, 3)  # Mod
        self.assertMostlyEqual(sheet.B19, -3)
        self.assertMostlyEqual(sheet.C19, Units.Quantity('3 mm'))
        self.assertEqual(sheet.D19, 3)
        self.assertMostlyEqual(sheet.A20, Units.Quantity('45 deg'))  # Atan2
        self.assertMostlyEqual(sheet.B20, Units.Quantity('-45 deg'))
        self.assertEqual(sheet.C20, u'ERR: Units must be equal')
        self.assertMostlyEqual(sheet.D20, Units.Quantity('45 deg'))
        self.assertMostlyEqual(sheet.A21, 2401)  # Pow
        self.assertMostlyEqual(sheet.B21, 2401)
        self.assertMostlyEqual(sheet.C21, Units.Quantity('2401mm^4'))
        self.assertEqual(sheet.D21,
                         u'ERR: Exponent is not allowed to have a unit.')
        self.assertMostlyEqual(sheet.A23, 5)  # Hypot
        self.assertMostlyEqual(sheet.B23, 5)
        self.assertEqual(sheet.C23, u'ERR: Units must be equal')
        self.assertMostlyEqual(sheet.D23, Units.Quantity('5mm'))

        l = math.sqrt(3 * 3 + 4 * 4 + 5 * 5)
        self.assertMostlyEqual(sheet.A24, l)  # Hypot
        self.assertMostlyEqual(sheet.B24, l)
        self.assertEqual(sheet.C24, u'ERR: Units must be equal')
        self.assertMostlyEqual(sheet.D24,
                               Units.Quantity("7.07106781186548 mm"))
        self.assertMostlyEqual(sheet.A26, 4)  # Cath
        self.assertMostlyEqual(sheet.B26, 4)
        self.assertEqual(sheet.C26, u'ERR: Units must be equal')
        self.assertMostlyEqual(sheet.D26, Units.Quantity('4mm'))

        l = math.sqrt(5 * 5 + 4 * 4 + 3 * 3)
        l = math.sqrt(l * l - 5 * 5 - 4 * 4)
        self.assertMostlyEqual(sheet.A27, l)  # Cath
        self.assertMostlyEqual(sheet.B27, l)
        self.assertEqual(sheet.C27, u'ERR: Units must be equal')
        self.assertMostlyEqual(sheet.D27, Units.Quantity("3 mm"))
        FreeCAD.closeDocument(doc.Name)
コード例 #49
0
ファイル: gigrnd.py プロジェクト: sparkler0323/PRScs
def gigrnd(p, a, b):
    # setup -- sample from the two-parameter version gig(lam,omega)
    p = float(p)
    a = float(a)
    b = float(b)
    lam = p
    omega = math.sqrt(a * b)

    if lam < 0:
        lam = -lam
        swap = True
    else:
        swap = False

    alpha = math.sqrt(math.pow(omega, 2) + math.pow(lam, 2)) - lam

    # find t
    x = -psi(1, alpha, lam)
    if (x >= 1 / 2) and (x <= 2):
        t = 1
    elif x > 2:
        t = math.sqrt(2 / (alpha + lam))
    elif x < 1 / 2:
        t = math.log(4 / (alpha + 2 * lam))

    # find s
    x = -psi(-1, alpha, lam)
    if (x >= 1 / 2) and (x <= 2):
        s = 1
    elif x > 2:
        s = math.sqrt(4 / (alpha * math.cosh(1) + lam))
    elif x < 1 / 2:
        s = min(
            1 / lam,
            math.log(1 + 1 / alpha +
                     math.sqrt(1 / math.pow(alpha, 2) + 2 / alpha)))

    # find auxiliary parameters
    eta = -psi(t, alpha, lam)
    zeta = -dpsi(t, alpha, lam)
    theta = -psi(-s, alpha, lam)
    xi = dpsi(-s, alpha, lam)

    p = 1 / xi
    r = 1 / zeta

    td = t - r * eta
    sd = s - p * theta
    q = td + sd

    # random variate generation
    while True:
        U = random.random()
        V = random.random()
        W = random.random()
        if U < q / (p + q + r):
            rnd = -sd + q * V
        elif U < (q + r) / (p + q + r):
            rnd = td - r * math.log(V)
        else:
            rnd = -sd + p * math.log(V)

        f1 = math.exp(-eta - zeta * (rnd - t))
        f2 = math.exp(-theta + xi * (rnd + s))
        if W * g(rnd, sd, td, f1, f2) <= math.exp(psi(rnd, alpha, lam)):
            break

    # transform back to the three-parameter version gig(p,a,b)
    rnd = math.exp(rnd) * (
        lam / omega + math.sqrt(1 + math.pow(lam, 2) / math.pow(omega, 2)))
    if swap:
        rnd = 1 / rnd

    rnd = rnd / math.sqrt(a / b)
    return rnd
コード例 #50
0
 def cosh(self):
     self.result = False
     self.current = math.cosh(float(txtDisplay.get()))
     self.display(self.current)
コード例 #51
0
    def findQualified(self):

        for i in range(self.nLept):

            collection = 0

            if self.cutDict["type"][i] == "mu":

                try:
                    collection = self.storeGateSvc.retrieve(
                        "Analysis::MuonContainer", self.cutDict["coll"][i])
                except LookupError:
                    self.msg.warning('Collection %s not found' %
                                     self.cutDict["coll"][i])
                    self.setFilterPassed(False)
                    self.nFail += 1
                    return StatusCode.Success

            elif self.cutDict["type"][i] == "e":

                try:
                    collection = self.storeGateSvc.retrieve(
                        "ElectronContainer", self.cutDict["coll"][i])
                except LookupError:
                    self.msg.warning('Collection %s not found' %
                                     self.cutDict["coll"][i])
                    self.setFilterPassed(False)
                    self.nFail += 1
                    return StatusCode.Success
                #print "looking into electrons from  ",self.cutDict["coll"][i], "there are",len(collection)

            else:
                try:
                    collection = self.storeGateSvc.retrieve(
                        "PhotonContainer", self.cutDict["coll"][i])
                except LookupError:
                    self.msg.warning('Collection %s not found' %
                                     self.cutDict["coll"][i])
                    self.setFilterPassed(False)
                    self.nFail += 1
                    return StatusCode.Success

            for lepton in collection:

                passedCuts = True

                if len(self.cutDict["pt"]):
                    passedCuts = passedCuts and lepton.pt(
                    ) > self.cutDict["pt"][i]

                if len(self.cutDict["eta"]):
                    passedCuts = passedCuts and abs(
                        lepton.eta()) < self.cutDict["eta"][i]

                if len(self.cutDict["et"]):
                    if self.cutDict["type"][i] == "e":
                        if lepton.cluster() and lepton.trackParticle():
                            passedCuts = lepton.cluster().e() / math.cosh(
                                lepton.trackParticle().eta(
                                )) > self.cutDict["et"][i]
                            #print lepton.cluster().e()/math.cosh(lepton.trackParticle().eta()),lepton.et()
                        else:
                            passedCuts = passedCuts and lepton.et(
                            ) > self.cutDict["et"][i]
                    elif self.cutDict["type"][i] == "gamma":
                        if lepton.cluster():
                            passedCuts = lepton.cluster().pt(
                            ) > self.cutDict["et"][i]
                        else:
                            passedCuts = lepton.et() > self.cutDict["et"][i]

                    else:
                        passedCuts = passedCuts and lepton.et(
                        ) > self.cutDict["et"][i]

                passedCuts = passedCuts and self.checkQuality(lepton, i)

                if passedCuts:
                    #print 'lepton',lepton,'passed cuts',i
                    self.qualified[i].append(lepton)
コード例 #52
0
def v(x):
  al = 1.0
  la = 4.0
  return al*al*la*(la-1)*(0.5-1/pow(cosh(al*x),2))/2
コード例 #53
0
def passLikelihood(electron, electronLikelihoodTool, trackToVertexTool,
                   primaryVertexPosition, numberOfPrimaryVertices):
    # Check objects are available
    if not electron.trackParticle():
        return False
    if not electron.trackParticle().trackSummary():
        return False
    if not electron.trackParticle().measuredPerigee():
        return False

    # eta              : el_etas2
    eta = electron.cluster().etaBE(2)
    if abs(eta) > 300.:
        return False
    # eT (in MeV)      : el_cl_E/cosh(el_etas2)
    eT = electron.cluster().e() / math.cosh(eta)
    if eT == 0.:
        return False
    # f3               : el_f3
    f3 = electron.detailValue(egammaParameters.f3)
    # rHad             : el_Ethad / eT
    rHad = electron.detailValue(egammaParameters.ethad) / eT
    # rHad1            : el_Ethad1/ eT
    rHad1 = electron.detailValue(egammaParameters.ethad1) / eT
    # Reta             : el_reta
    e237 = electron.detailValue(egammaParameters.e237)
    e277 = electron.detailValue(egammaParameters.e277)
    Reta = 0.
    if e277 != 0.:
        Reta = e237 / e277
    # w2               : el_weta2
    w2 = electron.detailValue(egammaParameters.weta2)
    # f1               : el_f1
    f1 = electron.detailValue(egammaParameters.f1)
    # wstot            : el_wstot
    # wstot = electron.detailValue(egammaParameters.wtots1)
    # DEmaxs1          : (el_emaxs1+el_Emax2 == 0.) ? 0. : (el_emaxs1-el_Emax2)/(el_emaxs1+el_Emax2)
    DEmaxs1 = 0.
    emaxs1 = electron.detailValue(egammaParameters.emaxs1)
    Emax2 = electron.detailValue(egammaParameters.e2tsts1)
    if abs(emaxs1 + Emax2) > 0.:
        DEmaxs1 = (emaxs1 - Emax2) / (emaxs1 + Emax2)
    # deltaEta         : el_deltaeta1
    deltaEta = electron.detailValue(egammaParameters.deltaEta1)
    # d0               : el_trackd0pv defined in PhysicsAnalysis/D3PDMaker/egammaD3PDAnalysis/src/egammaTrackImpactAlg.cxx
    d0 = -9999.
    newMeasPerigee = trackToVertexTool.perigeeAtVertex(
        electron.trackParticle(), primaryVertexPosition)
    ROOT.SetOwnership(newMeasPerigee, True)
    if newMeasPerigee != None:
        d0 = newMeasPerigee.parameters()[ROOT.Trk.d0]
    # TRratio          : el_TRTHighTOutliersRatio
    # Defined in PhysicsAnalysis/D3PDMaker/TrackD3PDMaker/src/TrackTrackSummaryFillerTool.cxx
    # if (ntrtxenon > 0)
    #   *m_TRTHighTOutliersRatio = (float)(nhightrt + nhightrt_outl) / (float)(ntrtxenon);
    # else if (ntrtxenon < 0 && (ntrt + ntrt_outl) > 0) {
    #   // Backwards compatibility if xenon information isn't present.
    #   *m_TRTHighTOutliersRatio = (float)(nhightrt + nhightrt_outl) / (float)(ntrt + ntrt_outl);
    TRratio = 0.
    # ntrtxenon = numberOfTRTXenonHits
    ntrtxenon = electron.trackParticle().trackSummary().get(
        ROOT.Trk.numberOfTRTXenonHits)
    # nhightrt = numberOfTRTHighThresholdHits
    nhightrt = electron.trackParticle().trackSummary().get(
        ROOT.Trk.numberOfTRTHighThresholdHits)
    # nhightrt_outl = numberOfTRTHighThresholdOutliers
    nhightrt_outl = electron.trackParticle().trackSummary().get(
        ROOT.Trk.numberOfTRTHighThresholdOutliers)
    # ntrt = numberOfTRTHits
    ntrt = electron.trackParticle().trackSummary().get(
        ROOT.Trk.numberOfTRTHits)
    # ntrt_outl = numberOfTRTOutliers
    ntrt_outl = electron.trackParticle().trackSummary().get(
        ROOT.Trk.numberOfTRTOutliers)
    if ntrtxenon > 0:
        TRratio = float(nhightrt + nhightrt_outl) / float(ntrtxenon)
    elif ntrtxenon < 0 and (ntrt + ntrt_outl) > 0:
        TRratio = float(nhightrt + nhightrt_outl) / float(ntrt + ntrt_outl)
    # d0sigma          : el_tracksigd0pv
    d0sigma = -9999.
    if newMeasPerigee != None:
        d0sigma = newMeasPerigee.localErrorMatrix().error(ROOT.Trk.d0)
    # fside            : el_fside defined in PhysicsAnalysis/D3PDMaker/egammaD3PDMaker/python/ElectronD3PDObject.py
    # fside = electron.detailValue(egammaParameters.fracs1)
    # rphi             : el_rphi defined in PhysicsAnalysis/D3PDMaker/egammaD3PDMaker/src/egammaRetaphiFillerTool.cxx
    rphi = 0.
    if e237 != 0.:
        e233 = electron.detailValue(egammaParameters.e233)
        rphi = e233 / e237
    # ws3              : el_ws3 defined in PhysicsAnalysis/D3PDMaker/egammaD3PDMaker/python/ElectronD3PDObject.py
    ws3 = electron.detailValue(egammaParameters.weta1)
    # deltaPoverP      : see below.
    # double dpOverp = 0.;
    # for (unsigned int i = 0; i<el_refittedTrack_LMqoverp[el].size();++i) {
    #        if((el_refittedTrack_author[el]).at(i)== 4) {
    #          dpOverp= 1.-(el_trackqoverp[el]/(el_refittedTrack_LMqoverp[el].at(i)));
    #             }
    # }
    # return dpOverp;
    deltaPoverP = 0.
    trackqoverp = electron.trackParticle().measuredPerigee().parameters()[
        ROOT.Trk.qOverP]
    for id in range(electron.nDetails()):
        if not electron.detailElementLink(id).isValid():
            continue
        if electron.detailName(id) != "egDetailAOD":
            print 'H4lDPDMaker::passLikelihood WARNING electron.detailName(%i) = %s != egDetailAOD' % (
                id, electron.detailName(id))
            continue
        if not isinstance(electron.detail(id), PyAthena.EMTrackFit
                          ):  # This corresponds to dynamic_cast in C++
            continue
        if electron.detail(id).linkIndex() >= electron.nTrackParticles():
            continue
        if electron.detail(id).bremTrackAuthor() != 4:
            continue
        deltaPoverP = 1. - (trackqoverp /
                            electron.detail(id).track_LastM_qOverP())
        break
    # deltaphires      : el_deltaphiRescaled
    deltaphires = electron.detailValue(egammaParameters.deltaPhiRescaled)
    # nSi              : el_nSiHits
    nSi = electron.trackParticle().trackSummary().get(
        ROOT.Trk.numberOfSCTHits) + electron.trackParticle().trackSummary(
        ).get(ROOT.Trk.numberOfPixelHits)
    # nSiDeadSensors   : el_nPixelDeadSensors + el_nSCTDeadSensors
    nSiDeadSensors = electron.trackParticle().trackSummary().get(
        ROOT.Trk.numberOfSCTDeadSensors) + electron.trackParticle(
        ).trackSummary().get(ROOT.Trk.numberOfPixelDeadSensors)
    # nPix             : el_nPixHits
    nPix = electron.trackParticle().trackSummary().get(
        ROOT.Trk.numberOfPixelHits)
    # nPixDeadSensors  : el_nPixelDeadSensors
    nPixDeadSensors = electron.trackParticle().trackSummary().get(
        ROOT.Trk.numberOfPixelDeadSensors)
    # nBlayer          : el_nBLHits
    nBlayer = electron.trackParticle().trackSummary().get(
        ROOT.Trk.numberOfBLayerHits)
    # nBlayerOutliers  : el_nBLayerOutliers
    nBlayerOutliers = electron.trackParticle().trackSummary().get(
        ROOT.Trk.numberOfBLayerOutliers)
    # expectBlayer     : el_expectHitInBLayer
    expectBlayer = bool(
        electron.detailValue(egammaParameters.expectHitInBLayer))
    # convBit          : el_isEM & (0x1 << egammaPID::ConversionMatch_Electron)
    # el_isEM is defined in PhysicsAnalysis/D3PDMaker/egammaD3PDMaker/src/egammaIsEMoneFillerTool.cxx
    convBit = long(electron.egammaID(
        egammaPID.IsEM)) & (0x1 << egammaPID.ConversionMatch_Electron)
    # ip               : Count number of vertices in vxp_n with >= 2 tracks in vxp_trk_n
    ip = numberOfPrimaryVertices

    result = electronLikelihoodTool.passLikelihood(
        ROOT.LikeEnum.
        Loose_BL_Pix,  # LikeEnum::Menu operating_point, Loose_BL_Pix=100 
        eta,
        eT,
        f3,
        rHad,
        rHad1,
        Reta,
        w2,
        f1,
        DEmaxs1,
        deltaEta,
        d0,
        TRratio,
        d0sigma,
        rphi,
        ws3,
        deltaPoverP,
        deltaphires,
        nSi,
        nSiDeadSensors,
        nPix,
        nPixDeadSensors,
        nBlayer,
        nBlayerOutliers,
        expectBlayer,
        convBit,
        ip)
    return result
コード例 #54
0
def cosh(x):
    return math.cosh(x)
コード例 #55
0
    if (x > xmax): xmax = x
    if (e < emin): emin = e
    if (e > emax): emax = e

beta = 3.0
#sigmoid   = lambda x: 1.0/(1.0+math.exp(-x))
#sigmoidp  = lambda x: math.exp(-x)/(1.0+math.exp(-x))**2
#sigmoidpp = lambda x: math.exp(-x)*(math.exp(-x)-1.0)/(1.0+math.exp(-x))**3
ap = 1.0
xp = 2.5
bp = 3.0
penalty = lambda x: ap * (0.5 *
                          (math.tanh(bp *
                                     (x - xp)) - math.tanh(bp *
                                                           (x + xp))) + 1.0)
penaltyp = lambda x: ap * 0.5 * bp * ((1 / math.cosh(bp * (x - xp)))**2 -
                                      (1.0 / math.cosh(bp * (x + xp)))**2)

sigmoid = lambda x: 0.5 * (math.tanh(beta * x) + 1.0)
sigmoidp = lambda x: 0.5 * beta * (1.0 / math.cosh(beta * x))**2
sigmoidpp = lambda x: 0.5 * (-2.0) * beta * beta * math.tanh(beta * x) * (
    1.0 / math.sech(beta * x))**2
xmoid1 = lambda x: x
xmoidp1 = lambda x: 1.0
xmoidpp1 = lambda x: 0.0
#xmoid2   = lambda x: x*x * 0.5
#xmoidp2  = lambda x: x
#xmoidpp2 = lambda x: 1.0
#xmoid3   = lambda x: x*x*x * (1.0/6.0)
#xmoidp3  = lambda x: 3*x*x * (1.0/6.0)
#xmoidpp3 = lambda x: 6*x   * (1.0/6.0)
コード例 #56
0
    step_num = 0

    # For posture control
    delta_hip_angle = 0.0  # To be accumulated during stance
    desired_angle = -0.2

    # Initialisation for filter
    x_ft = np.zeros((7, 2))
    raw_data = np.zeros((7, 2))
    ankle_ang_real, ankle_ang_filt = [], []

    while True:
        t = (steps) / float(FPS)

        # READ: estimate CoM position and velocity
        x_t_est = x_s * math.cosh(t / T_c) + T_c * v_s * math.sinh(
            t / T_c)  # estimated CoM velocity by LIPM
        v_t_est = x_s / T_c * math.sinh(t / T_c) + v_s * math.cosh(t / T_c)
        x_T_est = x_s * math.cosh(T_step / T_c) + T_c * v_s * math.sinh(
            T_step / T_c)
        v_T_est = x_s / T_c * math.sinh(T_step / T_c) + v_s * math.cosh(
            T_step / T_c)

        #vel_targ.append(v_t_est)
        vel_targ.append(v_t_est)

        # READ: IK to obtain hip (gamma) and knee (theta) angles of supporting leg
        theta_sp_est, gamma_sp_est = geometry_sp(x_t_est)

        # Foot placement estimation
        P = T_c * v_T_est * (math.cosh(T_step / T_c) / math.sinh(T_step / T_c)) \
コード例 #57
0
#    print (i)
#    print(L[i])
#    for i in range(0,100):
#        print(i)
#        print(L[i])
#        print(L0)
#        print(h)
#        Lnew = L0 * np.tanh(2.*np.pi/L[i]*h)
#        print(Lnew)
#        if(abs(Lnew-L[i])<0.001):
#            L[i] = Lnew
#            break
#        L[i] = Lnew
    k[i] = 2.*np.pi/L[i]
    w[i] = 2.*np.pi/T[i]
    QTF[i]=2*(math.cosh(2*k[i]*h)-1)/(2*k[i]*h+math.sinh(2*k[i]*h))
print(L)
print(k)
print(w)
print(QTF)
print(a)
times = np.linspace(t0, tEnd, round((tEnd-t0)/dt)+1)
coords = np.linspace(bLims[0], bLims[1], nPaddles+1)
coords = coords[:-1] + np.diff(coords)/2.
# Export
fid = open('wavemakerMovement.txt', 'w')

fid.write('wavemakerType   Piston;\n')
fid.write('tSmooth         1.5;\n')
fid.write('genAbs          0;\n\n')
コード例 #58
0
ファイル: tests.py プロジェクト: sallecta/sparrow
#print 'ceil'
testit('ceil(0.5)', math.ceil(0.5), 1)
testit('ceil(1.0)', math.ceil(1.0), 1)
testit('ceil(1.5)', math.ceil(1.5), 2)
testit('ceil(-0.5)', math.ceil(-0.5), 0)
testit('ceil(-1.0)', math.ceil(-1.0), -1)
testit('ceil(-1.5)', math.ceil(-1.5), -1)

#print 'cos'
testit('cos(-pi/2)', math.cos(-math.pi / 2), 0)
testit('cos(0)', math.cos(0), 1)
testit('cos(pi/2)', math.cos(math.pi / 2), 0)
testit('cos(pi)', math.cos(math.pi), -1)

#print 'cosh'
testit('cosh(0)', math.cosh(0), 1)
testit('cosh(2)-2*(cosh(1)**2)',
       math.cosh(2) - 2 * (math.cosh(1)**2), -1)  # Thanks to Lambert

#print 'degrees'
testit('degrees(pi)', math.degrees(math.pi), 180.0)
testit('degrees(pi/2)', math.degrees(math.pi / 2), 90.0)
testit('degrees(-pi/4)', math.degrees(-math.pi / 4), -45.0)

#print 'exp'
testit('exp(-1)', math.exp(-1), 1 / math.e)
testit('exp(0)', math.exp(0), 1)
testit('exp(1)', math.exp(1), math.e)

#print 'fabs'
testit('fabs(-1)', math.fabs(-1), 1)
コード例 #59
0
ファイル: suspension bridge 2.py プロジェクト: happywu/Kattis
def calculate_a(a):
    ans = (a * math.cosh(d / (2 * a))) - a
    return ans
コード例 #60
0
def exactp(x):
    from math import cosh
    from math import sinh
    value = 1.0 - cosh(x) / sinh(1.0)
    return value