Exemple #1
0
def correlation_MRRtest(rx1y, rx2y, rx1x2, n):
    """Meng-Rosenthal-Rubin method comparing two correlated
    correlation coefficients.

    :param float rx1y: the correlation coefficient between variables x1 and y
    :param float rx2y: the correlation coefficient between variables x2 and y
    :param float rx1x2: the correlation coefficient between variables x1 and x2
    :param int n: sample size
    :return: two-tailed p-value

    Reference: Meng et al. (1992), Psychol. Bull. 111, 172,
    """

    assert (-1<=rx1y<=1) and (-1<=rx2y<=1) and (-1<=rx1x2<=1), \
           "Correlation coefficients should be in ]-1,1["

    from math import sqrt, atanh

    z1 = atanh(rx1y)                    # Fisher's Z-transformation
    z2 = atanh(rx2y)
    rs = (rx1y**2 + rx2y**2)/2.
    f = min((1 - rx1x2)/(2*(1 - rs)), 1)
    h = (1 - f*rs) / (1 - rs)
    dz = (z1 - z2) * sqrt((n - 3)/(2 * (1 - rx1x2) * h))
    p = 2 * S.distributions.norm.sf(abs(dz)) # Two-tailed probability

    return p
Exemple #2
0
 def test_atanh(self):
     import math
     self.ftest(math.atanh(0), 0)
     self.ftest(math.atanh(0.5), 0.54930614433405489)
     self.ftest(math.atanh(-0.5), -0.54930614433405489)
     raises(ValueError, math.atanh, 1.)
     assert math.isnan(math.atanh(float("nan")))
Exemple #3
0
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
def pwmTOu(pwm):
    
    u = np.array([0.0,0.0])
    
    u[0] = math.atanh((pwm[0]-1800)/200)+1
    u[1] = math.atanh((pwm[1]-1500)/500)
    
    return u
# # # FIN PARTIE SIMULATION # # #
 def testAtanh(self):
     self.assertRaises(TypeError, math.atan)
     self.ftest('atanh(0)', math.atanh(0), 0)
     self.ftest('atanh(0.5)', math.atanh(0.5), 0.54930614433405489)
     self.ftest('atanh(-0.5)', math.atanh(-0.5), -0.54930614433405489)
     self.assertRaises(ValueError, math.atanh, 1)
     self.assertRaises(ValueError, math.atanh, -1)
     self.assertRaises(ValueError, math.atanh, INF)
     self.assertRaises(ValueError, math.atanh, NINF)
     self.assert_(math.isnan(math.atanh(NAN)))
Exemple #6
0
 def min_f(self, a, b):
     """Custom minimum function using inverse hyperbolic function."""
     if a >= 2:
         a = 1.99
     if a <= 0:
         a = 0.01
     if b >= 2:
         b = 1.99
     if b <= 0:
         b = 0.01
     return 1 - math.tanh(math.atanh(1 - a) + math.atanh(1 - b))
Exemple #7
0
def correlation(x, y):
    """Calculate correlation with p-value and confidence interval."""
    assert len(x) == len(y)
    #r, p = sp.stats.pearsonr(x, y)
    #r, p = sp.stats.kendalltau(x, y)
    r, p = sp.stats.spearmanr(x, y)
    n = len(x)
    stderr = 1.0 / math.sqrt(n-3)
    delta = 1.96 * stderr
    lower = math.tanh(math.atanh(r) - delta)
    upper = math.tanh(math.atanh(r) + delta)
    return dict(r=r, p=p, lower=lower, upper=upper)
Exemple #8
0
def getEta(pEvent, index):
    pTot = math.sqrt(
        math.pow(pEvent.px[index], 2) + math.pow(pEvent.py[index], 2) +
        math.pow(pEvent.pz[index], 2))
    eta = math.atanh(pEvent.pz[index] / pTot)

    return eta
Exemple #9
0
def test_moments_basic():
    """Test that we can properly recover adaptive moments for Gaussians."""
    import time
    t1 = time.time()
    for sig in gaussian_sig_values:
        for g1 in shear_values:
            for g2 in shear_values:
                total_shear = np.sqrt(g1**2 + g2**2)
                conversion_factor = np.tanh(2.0*math.atanh(total_shear))/total_shear
                distortion_1 = g1*conversion_factor
                distortion_2 = g2*conversion_factor
                gal = galsim.Gaussian(flux = 1.0, sigma = sig)
                gal.applyShear(g1=g1, g2=g2)
                gal_image = gal.draw(scale = pixel_scale)
                result = gal_image.FindAdaptiveMom()
                # make sure we find the right Gaussian sigma
                np.testing.assert_almost_equal(np.fabs(result.moments_sigma-sig/pixel_scale), 0.0,
                                               err_msg = "- incorrect dsigma", decimal = decimal)
                # make sure we find the right e
                np.testing.assert_almost_equal(result.observed_shape.e1,
                                               distortion_1, err_msg = "- incorrect e1",
                                               decimal = decimal_shape)
                np.testing.assert_almost_equal(result.observed_shape.e2,
                                               distortion_2, err_msg = "- incorrect e2",
                                               decimal = decimal_shape)
    t2 = time.time()
    print 'time for %s = %.2f'%(funcname(),t2-t1)
Exemple #10
0
    def __init__(self, file_name):
        proc = subprocess.Popen("../bin/meas_moments %s" % file_name, stdout=subprocess.PIPE, shell=True)
        buf = os.read(proc.stdout.fileno(), 1000)
        while proc.poll() == None:
            pass
        if proc.returncode != 0:
            raise RuntimeError("meas_moments exited with an error code")

        results = buf.split()
        if results[0] is not "0":
            raise RuntimeError("meas_moments returned an error status")
        self.mxx = float(results[1])
        self.myy = float(results[2])
        self.mxy = float(results[3])
        self.e1 = float(results[4])
        self.e2 = float(results[5])
        # These are distortions e1,e2
        # Find the corresponding shear:
        esq = self.e1 * self.e1 + self.e2 * self.e2
        if esq > 0.0:
            e = math.sqrt(esq)
            g = math.tanh(0.5 * math.atanh(e))
            self.g1 = self.e1 * (g / e)
            self.g2 = self.e2 * (g / e)
        else:
            self.g1 = 0.0
            self.g2 = 0.0
Exemple #11
0
def km2_area_wgs84cell(center_lat, pixel_size):  #DS re-ordered, center_lat):
    """Calculate km^2 area of a wgs84 square pixel. As with area_of_pixel above
       but with atanh idea from same website

    Adapted from: https://gis.stackexchange.com/a/127327/2397

    Parameters:
        pixel_size (float): length of side of pixel in degrees.
        center_lat (float): latitude of the center of the pixel. Note this
            value +/- half the `pixel-size` must not exceed 90/-90 degrees
            latitude or an invalid area will be calculated.

    Returns:
        Area of square pixel of side length `pixel_size` centered at
        `center_lat` in km^2.

    """
    a = 6378137  # meters
    b = 6356752.3142  # meters
    e = math.sqrt(1 - (b / a)**2)
    area_list = []
    for f in [center_lat + pixel_size / 2, center_lat - pixel_size / 2]:
        zm = 1 - e * math.sin(math.radians(f))
        zp = 1 + e * math.sin(math.radians(f))
        area_list.append(math.pi * b**2 * (
            2 * atanh(e * sin(math.radians(f))) / (2 * e) +
            #math.log(zp/zm) / (2*e) +
            math.sin(math.radians(f)) / (zp * zm)))
    return 1.0e-6 * pixel_size / 360. * (area_list[0] - area_list[1]
                                         )  #DS now km2
Exemple #12
0
def bachelierFormulaImpliedVol(optionType,
                               strike,
                               forward,
                               tte,
                               bachelierPrice,
                               discount=1.0):
    strike = float(strike)
    forward = float(forward)
    tte = float(tte)
    bachelierPrice = float(bachelierPrice)
    discount = float(discount)

    pyFinAssert(tte > 0, ValueError,
                "tte ({0:f}) must be positive".format(tte))
    SQRT_QL_EPSILON = math.sqrt(MathConstants.QL_EPSILON)

    forwardPremium = bachelierPrice / discount

    if optionType == OptionType.Call:
        straddlePremium = 2.0 * forwardPremium - (forward - strike)
    else:
        straddlePremium = 2.0 * forwardPremium + (forward - strike)

    nu = (forward - strike) / straddlePremium
    nu = max(-1.0 + MathConstants.QL_EPSILON,
             min(nu, 1.0 - MathConstants.QL_EPSILON))
    eta = 1.0 if (abs(nu) < SQRT_QL_EPSILON) else (nu / math.atanh(nu))

    heta = HCalculator.calculate(eta)
    impliedBpvol = math.sqrt(MathConstants.M_PI /
                             (2 * tte)) * straddlePremium * heta
    return impliedBpvol
Exemple #13
0
    def __init__(self, file_name, file_name_epsf, array_shape):
        proc = subprocess.Popen(
            "../bin/meas_shape %s %s %f %f 0.0 REGAUSS 0.0"
            % (file_name, file_name_epsf, 0.5 * array_shape[0], 0.5 * array_shape[1]),
            stdout=subprocess.PIPE,
            shell=True,
        )
        buf = os.read(proc.stdout.fileno(), 1000)
        while proc.poll() == None:
            pass
        if proc.returncode != 0:
            raise RuntimeError("meas_shape exited with an error code, %d" % proc.returncode)

        results = buf.split()
        if results[0] is not "0":
            raise RuntimeError("meas_shape returned an error status")
        self.e1 = float(results[1])
        self.e2 = float(results[2])
        self.r2 = float(results[5])
        # These are distortions e1,e2
        # Find the corresponding shear:
        esq = self.e1 * self.e1 + self.e2 * self.e2
        e = math.sqrt(esq)
        g = math.tanh(0.5 * math.atanh(e))
        self.g1 = self.e1 * (g / e)
        self.g2 = self.e2 * (g / e)
 def fromGeographic(self, lat, lon):
     lat_rad = radians(lat)
     lon_rad = radians(lon)
     B = cos(lat_rad) * sin(lon_rad - self.lon_rad)
     x = self.radius * atanh(B)
     y = self.radius * (atan(tan(lat_rad) / cos(lon_rad - self.lon_rad)) - self.lat_rad)
     return x, y
    def compute_nfw(R):
        if R < Rcore:
            R2 = Rcore
        else:
            R2 = R

        if (R2 / Rs) < 0.999:
            func = (1 - 2 * math.atanh(math.sqrt(
                (1 - R2 / Rs) /
                (R2 / Rs + 1))) / math.sqrt(1 -
                                            (R2 / Rs)**2)) / ((R2 / Rs)**2 - 1)

        # There are some computational issues as R2/Rs -> 1, using taylor expansion of the function
        # around this point
        elif (R2 / Rs) < 1.001:
            func = -(20 / 63) * ((R2 / Rs)**3 - 1) + (13 / 35) * (
                (R2 / Rs)**2 - 1) - (2 / 5) * (R2 / Rs) + (11 / 15)

        else:
            func = (1 - 2 * math.atan(math.sqrt(
                (R2 / Rs - 1) /
                (R2 / Rs + 1))) / math.sqrt((R2 / Rs)**2 - 1)) / (
                    (R2 / Rs)**2 - 1)

        return norm_constant * 2 * math.pi * R * func
Exemple #16
0
    def compute(self, plug, data):

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

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

            inputValueXHandle = data.inputValue(self.aInputValueX)
            inputValueX = inputValueXHandle.asFloat()

            inputValueYHandle = data.inputValue(self.aInputValueY)
            inputValueY = inputValueYHandle.asFloat()
            
            #   Math tanus
            outputValue = 0
            if operationType == 0:
                outputValue = math.atan(inputValueX)
            if operationType == 1:
                outputValue = math.tan(inputValueX)
            if operationType == 2:
                outputValue = math.atanh(inputValueX)
            if operationType == 3:
                outputValue = math.tanh(inputValueX)
            if operationType == 4:
                outputValue = math.tanh(inputValueY, inputValueX)

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

        #   Clean plug
        data.setClean(plug)
Exemple #17
0
    def latlon2(self, datum=None):
        '''Convert this WM coordinate to a lat- and longitude.

           @kwarg datum: Optional ellipsoidal datum (C{Datum}).

           @return: A L{LatLon2Tuple}C{(lat, lon)}.

           @raise TypeError: Non-ellipsoidal B{C{datum}}.

           @see: Method C{toLatLon}.
        '''
        r = self.radius
        x = self._x / r
        y = 2 * atan(exp(self._y / r)) - PI_2
        if datum is not None:
            _xinstanceof(Datum, datum=datum)
            E = datum.ellipsoid
            if not E.isEllipsoidal:
                raise _IsnotError(_ellipsoidal_, datum=datum)
            # <https://Earth-Info.NGA.mil/GandG/wgs84/web_mercator/
            #        %28U%29%20NGA_SIG_0011_1.0.0_WEBMERC.pdf>
            y = y / r
            if E.e:
                y -= E.e * atanh(E.e * tanh(y))  # == E.es_atanh(tanh(y))
            y *= E.a
            x *= E.a / r

        r = LatLon2Tuple(Lat(degrees90(y)), Lon(degrees180(x)))
        return self._xnamed(r)
 def setup_method(self):
     self.functions = [
         utils.cos_close_0,
         utils.sinc_close_0,
         utils.inv_sinc_close_0,
         utils.inv_tanc_close_0,
         {
             "coefficients": utils.arctanh_card_close_0["coefficients"],
             "function": lambda x: math.atanh(x) / x,
         },
         {
             "coefficients": utils.cosc_close_0["coefficients"],
             "function": lambda x: (1 - math.cos(x)) / x**2,
         },
         utils.sinch_close_0,
         utils.cosh_close_0,
         {
             "coefficients": utils.inv_sinch_close_0["coefficients"],
             "function": lambda x: x / math.sinh(x),
         },
         {
             "coefficients": utils.inv_tanh_close_0["coefficients"],
             "function": lambda x: x / math.tanh(x),
         },
     ]
Exemple #19
0
def normal_cdf(x):
    if abs(x) > 7:
        return 1 if x > 0 else 0
    temp = 27 * x / 294
    temp = 111 * math.atanh(temp) - 358 * x / 23
    temp = 1 + math.exp(temp)
    return 1. / temp
Exemple #20
0
def hyperbolic_fun_cal(inp_val1, opn_type):
     oprn_dic = {
        '1': 'inverse hyperbolic cosine of x', '2':'inverse hyperbolic sine of x',
        '3':' inverse hyperbolic tangent of x', '4':'hyperbolic cosine of x',
        '5':'hyperbolic sine of x', '6':'hyperbolic tangent of x'}
     if int(opn_type) == 1:
         output = math.acosh(float(inp_val1))
         return str(output)
     if int(opn_type) == 2:
         output = math.asinh(float(inp_val1))
         return str(output)
     if int(opn_type) == 3:
         output = math.atanh(float(inp_val1))
         return str(output)
     if int(opn_type) == 4:
         output = math.cosh(float(inp_val1))
         return str(output)
     if int(opn_type) == 5:
         output = math.sinh(float(inp_val1))
         return str(output)
     if int(opn_type) == 6:
         output = math.tanh(float(inp_val1))
         return str(output)
     else:
         return "Invalid Operation"
Exemple #21
0
def ci(n, corr, clevel):
    """return clevel-% lower and upper confidence levels for each pair
    
    n and corr are vectors of counts and correlations
    Correlations very close to +-1 do not get a CI
    """

    critz = abs(idfNormal((1 - clevel) / 2))
    res = []
    for nn, cc in zip(n, corr):
        if nn <= 3 or cc is None or abs(
                abs(cc) -
                1) < 1e-12:  # fuzz factor because of floating point properties
            res.append((None, None))
        else:
            try:
                Z = math.atanh(cc)
                zse = critz / math.sqrt(nn - 3)
                lowci = (math.tanh(Z) -
                         math.tanh(zse)) / (1 - math.tanh(Z) * math.tanh(zse))
                upperci = (math.tanh(Z) + math.tanh(zse)) / (
                    1 + math.tanh(Z) * math.tanh(zse))
                res.append((lowci, upperci))
            except:
                res.append((None, None))
    return res
Exemple #22
0
def update_cn_to_vr_msgs(H, vr_to_cn_msgs, cn_to_vr_msgs, LLRs):
    for j in range(len(H)):
        #print('ck11')
        for i in neighbors_cn(H, j):
            #print('ck12')
            product = 1.0
            for k in neighbors_cn(H, j):
                #print('ck13')
                if(k!=i):
                    product*=math.tanh(0.5*vr_to_cn_msgs[k][j])
                    #print('ck14')
            #print('ck15')
            if(abs(product)<0.9999999999999999):
                cn_to_vr_msgs[j][i] = 2*math.atanh(product)
            else:
                cn_to_vr_msgs[j][i] = 2*math.atanh(0.9999999999999999)
Exemple #23
0
def test_shearest_basic():
    """Test that we can recover shears for Gaussian galaxies and PSFs."""
    for sig in gaussian_sig_values:
        for g1 in shear_values:
            for g2 in shear_values:
                total_shear = np.sqrt(g1**2 + g2**2)
                conversion_factor = np.tanh(2.0*math.atanh(total_shear))/total_shear
                distortion_1 = g1*conversion_factor
                distortion_2 = g2*conversion_factor
                gal = galsim.Gaussian(flux = 1.0, sigma = sig)
                psf = galsim.Gaussian(flux = 1.0, sigma = sig)
                gal = gal.shear(g1=g1, g2=g2)
                psf = psf.shear(g1=0.1*g1, g2=0.05*g2)
                final = galsim.Convolve([gal, psf])
                final_image = final.drawImage(scale=pixel_scale, method='no_pixel')
                epsf_image = psf.drawImage(scale=pixel_scale, method='no_pixel')
                result = galsim.hsm.EstimateShear(final_image, epsf_image)
                # make sure we find the right e after PSF correction
                # with regauss, which returns a distortion
                np.testing.assert_almost_equal(result.corrected_e1,
                                               distortion_1, err_msg = "- incorrect e1",
                                               decimal = decimal_shape)
                np.testing.assert_almost_equal(result.corrected_e2,
                                               distortion_2, err_msg = "- incorrect e2",
                                               decimal = decimal_shape)
Exemple #24
0
def test_shearest_basic():
    """Test that we can recover shears for Gaussian galaxies and PSFs."""
    import time
    t1 = time.time()
    for sig in gaussian_sig_values:
        for g1 in shear_values:
            for g2 in shear_values:
                total_shear = np.sqrt(g1**2 + g2**2)
                conversion_factor = np.tanh(2.0*math.atanh(total_shear))/total_shear
                distortion_1 = g1*conversion_factor
                distortion_2 = g2*conversion_factor
                gal = galsim.Gaussian(flux = 1.0, sigma = sig)
                psf = galsim.Gaussian(flux = 1.0, sigma = sig)
                gal.applyShear(g1=g1, g2=g2)
                final = galsim.Convolve([gal, psf])
                final_image = final.draw(dx = pixel_scale)
                epsf_image = psf.draw(dx = pixel_scale)
                result = galsim.EstimateShearHSM(final_image, epsf_image)
                # make sure we find the right e after PSF correction
                # with regauss, which returns a distortion
                np.testing.assert_almost_equal(result.corrected_e1,
                                               distortion_1, err_msg = "- incorrect e1",
                                               decimal = decimal_shape)
                np.testing.assert_almost_equal(result.corrected_e2,
                                               distortion_2, err_msg = "- incorrect e2",
                                               decimal = decimal_shape)
    t2 = time.time()
    print 'time for %s = %.2f'%(funcname(),t2-t1)
Exemple #25
0
def dG12dsMN(s, par, B, ff, ff0, lep, wc):
    flavio.citations.register("Melikhov:2004mk")
    mlh = par['m_' + lep] / par['m_' + B]
    pref = 4 * prefactor(s, par, B, ff, lep,
                         wc) * par['f_' + B] / par['m_' + B] * (1 - s)
    return pref * atanh(sqrt(1 - 4 * mlh**2 / s)) * B120(
        s, par, B, ff, ff0, lep, wc)
Exemple #26
0
    def _get_distorted_indices(self, nb_images):
        inverse = random.randint(0, 1)

        if inverse:
            scale = random.random()
            scale *= 0.21
            scale += 0.6
        else:
            scale = random.random()
            scale *= 0.6
            scale += 0.8

        frames_per_clip = nb_images

        indices = np.linspace(-scale, scale, frames_per_clip).tolist()
        if inverse:
            values = [math.atanh(x) for x in indices]
        else:
            values = [math.tanh(x) for x in indices]

        values = [x / values[-1] for x in values]
        values = [
            int(round(((x + 1) / 2) * (frames_per_clip - 1), 0))
            for x in values
        ]
        return values
Exemple #27
0
    def to2ll(self, datum=None):
        '''Convert this WM coordinate to a geodetic lat- and longitude.

           @keyword datum: Optional datum (C{Datum}).

           @return: 2-Tuple (lat, lon) in (C{degrees90}, C{degrees180}).

           @raise TypeError: Non-ellipsoidal I{datum}.

           @raise ValueError: Invalid I{radius}.
        '''
        r = self.radius
        x = self._x / r
        y = 2 * atan(exp(self._y / r)) - PI_2
        if datum:
            E = datum.ellipsoid
            if not E.isEllipsoidal:
                raise TypeError('%s not %s: %r' %
                                ('datum', 'ellipsoidal', datum))
            # <http://Earth-Info.NGA.mil/GandG/wgs84/web_mercator/
            #       %28U%29%20NGA_SIG_0011_1.0.0_WEBMERC.pdf>
            y = y / r
            if E.e:
                y -= E.e * atanh(E.e * tanh(y))
            y *= E.a
            x *= E.a / r
        return degrees90(y), degrees180(x)
Exemple #28
0
    def set_e1e2(self, e1, e2):
        etot = sqrt(e1**2 + e2**2)

        if etot >= 1:
            mess="e values must be < 1, found %.16g (%.16g,%.16g)"
            mess = mess % (etot,e1,e2)
            raise ShapeRangeError(mess)

        if etot==0:
            self.eta1,self.eta2,self.g1,self.g2=(0.,0.,0.,0.)
            self.e1,self.e2=(0., 0.)
            return 

        eta = atanh(etot)
        gtot = tanh(eta/2)

        cos2theta = e1/etot
        sin2theta = e2/etot

        self.e1=e1
        self.e2=e2
        self.g1=gtot*cos2theta
        self.g2=gtot*sin2theta
        self.eta1=eta*cos2theta
        self.eta2=eta*sin2theta
Exemple #29
0
  def test_funcs_multi(self):
    pi = math.pi

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

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

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

    #misc
    self.assertQuantity(data.sqrt(Quantity((1,4), (2,2))), (1,2), (1,1/2))
    self.assertQuantity(data.exp(Quantity((1,4), (2,2))), (math.e, math.e**4), (2 * math.e,2*math.e**4))
    self.assertQuantity(data.log(Quantity((1,4), (2,2))), (0, math.log(4)), (2,1/2))
Exemple #30
0
def test_moments_basic():
    """Test that we can properly recover adaptive moments for Gaussians."""
    import time
    t1 = time.time()
    for sig in gaussian_sig_values:
        for g1 in shear_values:
            for g2 in shear_values:
                total_shear = np.sqrt(g1**2 + g2**2)
                conversion_factor = np.tanh(2.0*math.atanh(total_shear))/total_shear
                distortion_1 = g1*conversion_factor
                distortion_2 = g2*conversion_factor
                gal = galsim.Gaussian(flux = 1.0, sigma = sig)
                gal.applyShear(g1=g1, g2=g2)
                gal_image = gal.draw(dx = pixel_scale)
                result = gal_image.FindAdaptiveMom()
                # make sure we find the right Gaussian sigma
                np.testing.assert_almost_equal(np.fabs(result.moments_sigma-sig/pixel_scale), 0.0,
                                               err_msg = "- incorrect dsigma", decimal = decimal)
                # make sure we find the right e
                np.testing.assert_almost_equal(result.observed_shape.e1,
                                               distortion_1, err_msg = "- incorrect e1",
                                               decimal = decimal_shape)
                np.testing.assert_almost_equal(result.observed_shape.e2,
                                               distortion_2, err_msg = "- incorrect e2",
                                               decimal = decimal_shape)
    t2 = time.time()
    print 'time for %s = %.2f'%(funcname(),t2-t1)
Exemple #31
0
	def _constants(self, stages, bits):
		if self.func_mode == "circular":
			s = range(stages)
			a = [atan(2**-i) for i in s]
			g = [sqrt(1 + 2**(-2*i)) for i in s]
			#zmax = sum(a)
			# use pi anyway as the input z can cause overflow
			# and we need the range for quadrant mapping
			zmax = pi
		elif self.func_mode == "linear":
			s = range(stages)
			a = [2**-i for i in s]
			g = [1 for i in s]
			#zmax = sum(a)
			# use 2 anyway as this simplifies a and scaling
			zmax = 2.
		else: # hyperbolic
			s = []
			# need to repeat some stages:
			j = 4
			for i in range(stages):
				if i == j:
					s.append(j)
					j = 3*j + 1
				s.append(i + 1)
			a = [atanh(2**-i) for i in s]
			g = [sqrt(1 - 2**(-2*i)) for i in s]
			zmax = sum(a)*2
		a = [int(ai*2**(bits - 1)/zmax) for ai in a]
		# round here helps the width=2**i - 1 case but hurts the
		# important width=2**i case
		gain = 1.
		for gi in g:
			gain *= gi
		return a, s, zmax, gain
def bachelierFormulaImpliedVol(optionType,
                               strike,
                               forward,
                               tte,
                               bachelierPrice,
                               discount=1.0):
    strike = float(strike)
    forward = float(forward)
    tte = float(tte)
    bachelierPrice = float(bachelierPrice)
    discount = float(discount)

    pyFinAssert(tte > 0, ValueError, "tte ({0:f}) must be positive".format(tte))
    SQRT_QL_EPSILON = math.sqrt(MathConstants.QL_EPSILON)

    forwardPremium = bachelierPrice / discount

    if optionType == OptionType.Call:
        straddlePremium = 2.0 * forwardPremium - (forward - strike)
    else:
        straddlePremium = 2.0 * forwardPremium + (forward - strike)

    nu = (forward - strike) / straddlePremium
    nu = max(-1.0 + MathConstants.QL_EPSILON, min(nu, 1.0 - MathConstants.QL_EPSILON))
    eta = 1.0 if (abs(nu) < SQRT_QL_EPSILON) else (nu / math.atanh(nu))

    heta = HCalculator.calculate(eta)
    impliedBpvol = math.sqrt(MathConstants.M_PI / (2 * tte)) * straddlePremium * heta
    return impliedBpvol
Exemple #33
0
def g1g2_to_eta1eta2(g1,g2):
    gtot=sqrt(g1**2 + g2**2)
    if isinstance(gtot,numpy.ndarray):
        eta1=numpy.zeros(gtot.size)
        eta2=numpy.zeros(gtot.size)

        w,=numpy.where(gtot != 0)
        if w.size > 0:
            cos2theta=g1[w]/gtot[w]
            sin2theta=g2[w]/gtot[w]

            eta = 2*arctanh(gtot[w])
            eta1[w]=eta*cos2theta
            eta2[w]=eta*sin2theta
    else:
        from math import atanh        
        if gtot == 0:
            eta1,eta2=0.0,0.0
        else:
            cos2theta=g1/gtot
            sin2theta=g2/gtot

            eta = 2*atanh(gtot)
            eta1=eta*cos2theta
            eta2=eta*sin2theta

    return eta1,eta2
Exemple #34
0
def test_shearest_basic():
    """Test that we can recover shears for Gaussian galaxies and PSFs."""
    for sig in gaussian_sig_values:
        for g1 in shear_values:
            for g2 in shear_values:
                total_shear = np.sqrt(g1**2 + g2**2)
                conversion_factor = np.tanh(
                    2.0 * math.atanh(total_shear)) / total_shear
                distortion_1 = g1 * conversion_factor
                distortion_2 = g2 * conversion_factor
                gal = galsim.Gaussian(flux=1.0, sigma=sig)
                psf = galsim.Gaussian(flux=1.0, sigma=sig)
                gal = gal.shear(g1=g1, g2=g2)
                psf = psf.shear(g1=0.1 * g1, g2=0.05 * g2)
                final = galsim.Convolve([gal, psf])
                final_image = final.drawImage(scale=pixel_scale,
                                              method='no_pixel')
                epsf_image = psf.drawImage(scale=pixel_scale,
                                           method='no_pixel')
                result = galsim.hsm.EstimateShear(final_image, epsf_image)
                # make sure we find the right e after PSF correction
                # with regauss, which returns a distortion
                np.testing.assert_almost_equal(result.corrected_e1,
                                               distortion_1,
                                               err_msg="- incorrect e1",
                                               decimal=decimal_shape)
                np.testing.assert_almost_equal(result.corrected_e2,
                                               distortion_2,
                                               err_msg="- incorrect e2",
                                               decimal=decimal_shape)
Exemple #35
0
def checkio(height, width):
    '''height是拉长,width是半径,返回表面积和体积'''
    from math import pi
    volume = 4 * pi / 3 * (width / 2)**3 * height / width
    # 椭球的近似表面积
    # surface_area = pi/3 * (width**2+width*height*2)
    # 球体的表面积,拉长
    # surface_area = pi * width**2 * (height/width)**(2/3)
    if height == width:
        # 球体的表面积
        surface_area = pi * width**2
    # 新的公式..
    # 不学数学就是不行
    # http://mathworld.wolfram.com/ProlateSpheroid.html
    elif height < width:
        import math
        e = math.sqrt(1 - height**2 / width**2)
        surface_area = 0.5 * pi * (width**2) * (1 +
                                                (1 - e**2) / e * math.atanh(e))
    else:
        import math
        e = math.sqrt(1 - width**2 / height**2)
        surface_area = 0.5 * pi * width**2 + 0.5 * pi * width * height / e * math.asin(
            e)

    return [round(volume, 2), round(surface_area, 2)]
Exemple #36
0
def test_shearest_shape():
    """Test that shear estimation is insensitive to shape of input images."""
    # this test can help reveal bugs having to do with x / y indexing issues
    # just do test for one particular gaussian
    g1 = shear_values[1]
    g2 = shear_values[2]
    e1_psf = 0.05
    e2_psf = -0.04
    total_shear = np.sqrt(g1**2 + g2**2)
    conversion_factor = np.tanh(2.0 * math.atanh(total_shear)) / total_shear
    distortion_1 = g1 * conversion_factor
    distortion_2 = g2 * conversion_factor
    gal = galsim.Exponential(flux=1.0, half_light_radius=1.)
    gal = gal.shear(g1=g1, g2=g2)
    psf = galsim.Kolmogorov(flux=1.0, fwhm=0.7)
    psf = psf.shear(e1=e1_psf, e2=e2_psf)
    final = galsim.Convolve([gal, psf])

    imsize = [128, 256]
    for method_index in range(len(correction_methods)):
        print(correction_methods[method_index])

        save_e1 = -100.
        save_e2 = -100.
        for gal_x_imsize in imsize:
            for gal_y_imsize in imsize:
                for psf_x_imsize in imsize:
                    for psf_y_imsize in imsize:
                        final_image = galsim.ImageF(gal_x_imsize, gal_y_imsize)
                        epsf_image = galsim.ImageF(psf_x_imsize, psf_y_imsize)

                        final.drawImage(image=final_image,
                                        scale=pixel_scale,
                                        method='no_pixel')
                        psf.drawImage(image=epsf_image,
                                      scale=pixel_scale,
                                      method='no_pixel')
                        result = galsim.hsm.EstimateShear(
                            final_image,
                            epsf_image,
                            shear_est=correction_methods[method_index])
                        e1 = result.corrected_e1
                        e2 = result.corrected_e2
                        # make sure answers don't change as we vary image size

                        tot_e = np.sqrt(save_e1**2 + save_e2**2)
                        if tot_e < 99.:
                            np.testing.assert_almost_equal(
                                e1,
                                save_e1,
                                err_msg="- incorrect e1",
                                decimal=decimal_shape)
                            np.testing.assert_almost_equal(
                                e2,
                                save_e2,
                                err_msg="- incorrect e2",
                                decimal=decimal_shape)
                        save_e1 = e1
                        save_e2 = e2
Exemple #37
0
def p_expression_trig(t):
    '''expression : COS expression
                  | SEN expression
                  | TAN expression
                  | SEC expression
                  | CSC expression
                  | COT expression
                  | COSH expression
                  | SENH expression
                  | TANH expression
                  | SECH expression
                  | CSCH expression
                  | COTH expression
                  | ACOS expression
                  | ASEN expression
                  | ATAN expression
                  | ACOSH expression
                  | ASENH expression
                  | ATANH expression
                  '''
    try:
        if t[1] == 'cos' or t[1] == 'COS' : t[0] = m.cos(t[2])
        elif t[1] == 'sen' or t[1] == 'SEN' : t[0] = m.sin(t[2])
        elif t[1] == 'tan' or t[1] == 'TAN' : t[0] = m.tan(t[2])
        elif t[1] == 'sec' or t[1] == 'SEC' : t[0] = 1/m.cos(t[2])
        elif t[1] == 'csc' or t[1] == 'CSC' : t[0] = 1/m.sin(t[2])
        elif t[1] == 'cot' or t[1] == 'COT' : t[0] = 1/m.tan(t[2])
        ##Hiperbólicas
        elif t[1] == 'cosh' or t[1] == 'COSH' : t[0] = m.cosh(t[2])
        elif t[1] == 'senh' or t[1] == 'SENH' : t[0] = m.sinh(t[2])
        elif t[1] == 'tanh' or t[1] == 'TANH' : t[0] = m.tanh(t[2])
        elif t[1] == 'sech' or t[1] == 'SECH' : t[0] = 1/m.cosh(t[2])
        elif t[1] == 'csch' or t[1] == 'CSCH' : t[0] = 1/m.sinh(t[2])
        elif t[1] == 'coth' or t[1] == 'COTH' : t[0] = 1/m.tanh(t[2])
        ##Inversas
        elif t[1] == 'acos' or t[1] == 'ACOS' : t[0] = m.acos(t[2])
        elif t[1] == 'asen' or t[1] == 'ASEN' : t[0] = m.asin(t[2])
        elif t[1] == 'atan' or t[1] == 'ATAN' : t[0] = m.atan(t[2])
        ##Inversas hiperbolicas
        elif t[1] == 'acosh' or t[1] == 'ACOSH': 
            try:
                t[0] = m.acosh(t[2])
            except:
                print("Math error: acosh(%s)" %t[2])
                t[0] = 0
        elif t[1] == 'asenh' or t[1] == 'ASENH': 
            try:
                t[0] = m.asinh(t[2])
            except:
                print("Math error: asenh(%s)" %t[2])
                t[0] = 0
        elif t[1] == 'atanh' or t[1] == 'ATANH': 
            try:
                t[0] = m.atanh(t[2])
            except:
                print("Math error: atanh(%s)" %t[2])
                t[0] = 0
    except:
        print("Syntax error: Trigonometric function")
Exemple #38
0
 def arctangenth(self):
     x = self.xinput.get('1.0', 'end-1c')
     x = float(x)
     z = float(math.atanh(x))
     print(z)
     z = str(z)
     z = z + "\n"
     self.display.insert(END, z)
Exemple #39
0
 def atanh(x=('FloatPin', 0.0), Result=("Reference", ('BoolPin', False))):
     '''Return the inverse hyperbolic tangent of `x`.'''
     try:
         Result(True)
         return math.atanh(x)
     except:
         Result(False)
         return -1
Exemple #40
0
 def fromGeographic(self, lat, lon):
     lat_rad = radians(lat)
     lon_rad = radians(lon)
     B = cos(lat_rad) * sin(lon_rad - self.lon_rad)
     x = self.radius * atanh(B)
     y = self.radius * (atan(tan(lat_rad) / cos(lon_rad - self.lon_rad)) -
                        self.lat_rad)
     return x, y
Exemple #41
0
def G_e(Z, W, endpoint):
    beta = beta_rel(W)
    if W <= 1:
        result = 0
    else:

        W0 = endpoint / ELECTRON_MASS + 1
        result = 3 * math.log(NUCLEON_MASS / ELECTRON_MASS) - 0.75 + 4 * (
            math.atanh(beta) / beta - 1) * (
                (W0 - W) / (3 * W) - 1.5 + math.log(2 * (W0 + 0.01 - W))
            ) + 4 / beta * dilog(2 * beta /
                                 (1 + beta)) + math.atanh(beta) / beta * (
                                     2 * (1 + beta**2) +
                                     (W0 - W)**2 /
                                     (6 * W**2) - 4 * math.atanh(beta))
        result = ALPHA * result / (2 * PI) + 1
    return result
 def F(self, e, theta):
     """
     :param e:
     :param theta:
     :return: Hyperbolic anomaly (F)
     """
     F = 2 * atanh(sqrt((e - 1) / (e + 1)) * tan(theta / 2))
     return F + 2 * pi if F <= 0 else F
Exemple #43
0
def pearson_confidence(r, num, interval=0.95):
    """
    Calculate upper and lower 95% CI for a Pearson r (not R**2)
    Inspired by https://stats.stackexchange.com/questions/18887
    :param r: Pearson's R
    :param num: number of data points
    :param interval: confidence interval (0-1.0)
    :return: lower bound, upper bound
    """
    stderr = 1.0 / math.sqrt(num - 3)
    z_score = norm.ppf(
        interval +
        (1.0 - interval) / 2.0)  # There was a bug in the original code
    delta = z_score * stderr
    lower = math.tanh(math.atanh(r) - delta)
    upper = math.tanh(math.atanh(r) + delta)
    return lower, upper
Exemple #44
0
def model1(t, a, beta):

    row = (a * N) / beta
    alpha = m.sqrt(((S0_1 / row) - 1)**2 + (2 * S0_1 * (N - S0_1)) / (row**2))
    phai = m.atanh((1 / alpha) * ((S0_1 / row) - 1))
    rt = ((row**2) / S0_1) * (((S0_1 / row) - 1) + alpha *
                              (np.tanh(((a * alpha * t) / 2) - phai)))
    return rt
Exemple #45
0
def atanh(space, d):
    """ atanh - Inverse hyperbolic tangent """
    try:
        return space.wrap(math.atanh(d))
    except OverflowError:
        return space.wrap(rfloat.INFINITY)
    except ValueError:
        return space.wrap(rfloat.NAN)
	def ChkOp(self):
		for i in self.ChkNodes:
			msgvec=[]
			for j in i.edges:
				msgvec.append(math.tanh(0.5*j.msg1))
			extr=extrProd(msgvec)
			for j in range(0,len(i.edges)):
				i.edges[j].msg2=2.0*math.atanh(extr[j])
Exemple #47
0
def adjustValue(value):
    pMark = 0.65 #> percentage mark where values gets pushed up or down
    result = value + (1.5*math.atanh(value - pMark)) * value
    upperLimit = 0.9
    lowerLimit = 0.0
    result = min(result,upperLimit)
    result = max(result,lowerLimit)
    return result
Exemple #48
0
def atanh(space, d):
    """ atanh - Inverse hyperbolic tangent """
    try:
        return space.wrap(math.atanh(d))
    except OverflowError:
        return space.wrap(rfloat.INFINITY)
    except ValueError:
        return space.wrap(rfloat.NAN)
Exemple #49
0
def op_atanh(x):
    """Returns the inverse hyperbolic tangent of this mathematical object."""
    if isinstance(x, list):
        return [op_atanh(a) for a in x]
    elif isinstance(x, complex):
        return cmath.atanh(x)
    else:
        return math.atanh(x)
Exemple #50
0
def convertToShear(e1,e2):
    # Convert a distortion (e1,e2) to a shear (g1,g2)
    import math
    e = math.sqrt(e1*e1 + e2*e2)
    g = math.tanh( 0.5 * math.atanh(e) )
    g1 = e1 * (g/e)
    g2 = e2 * (g/e)
    return (g1,g2)
Exemple #51
0
def convert_pixcel_tolonglati(pixel_x, pixel_y, z):
    Longitude, Latitude = 0, 0
    Longitude = 180 * (pixel_x / math.pow(2, z + 7) - 1)
    Latitude = 180 / PAI \
            * (math.asin(math.tanh(-1 * (PAI / math.pow(2, z + 7) * pixel_y) \
            + math.atanh(math.sin((PAI / 180) * L)))))

    return Latitude, Longitude
Exemple #52
0
def convertToShear(e1, e2):
    # Convert a distortion (e1,e2) to a shear (g1,g2)
    import math
    e = math.sqrt(e1 * e1 + e2 * e2)
    g = math.tanh(0.5 * math.atanh(e))
    g1 = e1 * (g / e)
    g2 = e2 * (g / e)
    return (g1, g2)
Exemple #53
0
 def coords2pixel(self, zoom, coords):
     TILESIZE = self.TILESIZE
     (lat, lon) = coords
     lon = lon / 360 + 0.5
     lat = math.atanh(math.sin(lat / 180 * math.pi))
     lat = - lat / (2 * math.pi) + 0.5
     scale = 2 ** zoom * TILESIZE
     return (lon * scale, lat * scale)
Exemple #54
0
def test_moments_basic():
    """Test that we can properly recover adaptive moments for Gaussians."""
    import time
    t1 = time.time()
    first_test=True
    for sig in gaussian_sig_values:
        for g1 in shear_values:
            for g2 in shear_values:
                total_shear = np.sqrt(g1**2 + g2**2)
                conversion_factor = np.tanh(2.0*math.atanh(total_shear))/total_shear
                distortion_1 = g1*conversion_factor
                distortion_2 = g2*conversion_factor
                gal = galsim.Gaussian(flux = 1.0, sigma = sig)
                gal = gal.shear(g1=g1, g2=g2)
                gal_image = gal.drawImage(scale = pixel_scale, method='no_pixel')
                result = gal_image.FindAdaptiveMom()
                # make sure we find the right Gaussian sigma
                np.testing.assert_almost_equal(np.fabs(result.moments_sigma-sig/pixel_scale), 0.0,
                                               err_msg = "- incorrect dsigma", decimal = decimal)
                # make sure we find the right e
                np.testing.assert_almost_equal(result.observed_shape.e1,
                                               distortion_1, err_msg = "- incorrect e1",
                                               decimal = decimal_shape)
                np.testing.assert_almost_equal(result.observed_shape.e2,
                                               distortion_2, err_msg = "- incorrect e2",
                                               decimal = decimal_shape)
                # if this is the first time through this loop, just make sure it runs and gives the
                # same result for ImageView and ConstImageViews:
                if first_test:
                    result = gal_image.view().FindAdaptiveMom()
                    first_test=False
                    np.testing.assert_almost_equal(
                        np.fabs(result.moments_sigma-sig/pixel_scale), 0.0,
                        err_msg = "- incorrect dsigma (ImageView)", decimal = decimal)
                    np.testing.assert_almost_equal(
                        result.observed_shape.e1,
                        distortion_1, err_msg = "- incorrect e1 (ImageView)",
                        decimal = decimal_shape)
                    np.testing.assert_almost_equal(
                        result.observed_shape.e2,
                        distortion_2, err_msg = "- incorrect e2 (ImageView)",
                        decimal = decimal_shape)
                    result = gal_image.view(make_const=True).FindAdaptiveMom()
                    np.testing.assert_almost_equal(
                        np.fabs(result.moments_sigma-sig/pixel_scale), 0.0,
                        err_msg = "- incorrect dsigma (ConstImageView)", decimal = decimal)
                    np.testing.assert_almost_equal(
                        result.observed_shape.e1,
                        distortion_1, err_msg = "- incorrect e1 (ConstImageView)",
                        decimal = decimal_shape)
                    np.testing.assert_almost_equal(
                        result.observed_shape.e2,
                        distortion_2, err_msg = "- incorrect e2 (ConstImageView)",
                        decimal = decimal_shape)


    t2 = time.time()
    print 'time for %s = %.2f'%(funcname(),t2-t1)
def utm2LL(Easting, Northing, zone, zoneQuadrant=None, North=None, datum='wgs84'):
    a, b = Datums[datum]
    zone_cm = getZoneCM(zone)           # zone central meridian in degrees longitude

    if zoneQuadrant:    # if both North and zoneQuadrant are specified, use zoneQuadrant to determine North
        North = isNorth(zoneQuadrant)
    elif North is None:
        raise Exception("Either 'zoneQuadrant' or 'North' arguments must be specified")

    e, n, AA = getDatumProperties(a, b)
    b1, b2, b3, b4, b5, b6, b7 = getBetaSeries(n)   # (Krüger 1912, pg. 21, eqn. 41)

    if North:
        xi = Northing / (k0 * AA)  # (Karney 2010, pg.3, eqn. 15)
    else:
        xi = Northing / (1e7 - Northing) / (k0 * AA)

    eta = (Easting - falseEasting) / (k0 * AA)     # (Karney 2010, pg.3, eqn. 13)

    # (Karney 2010, pg.3, eqn. 11) which is an inversion of (Karney 2010, pg. 2, eqn. 7-9)
    xi_prime = (xi - (
        b1 * sin(2 * xi) * cosh(2 * eta) + b2 * sin(4 * xi) * cosh(4 * eta) + b3 * sin(6 * xi) * cosh(
            6 * eta) + b4 * sin(8 * xi) * cosh(8 * eta) + b5 * sin(10 * xi) * cosh(10 * eta) + b6 * sin(
                12 * xi) * cosh(12 * eta) + b7 * sin(14 * xi) * cosh(14 * eta)))

    eta_prime = (eta - (
        b1 * cos(2 * xi) * sinh(2 * eta) + b2 * cos(4 * xi) * sinh(4 * eta) + b3 * cos(6 * xi) * sinh(
            6 * eta) + b4 * cos(8 * xi) * sinh(8 * eta) + b5 * cos(10 * xi) * sinh(10 * eta) + b6 * cos(
                12 * xi) * sinh(12 * eta) + b7 * cos(14 * xi) * sinh(14 * eta)))

    tau_prime = sin(xi_prime) / sqrt(sinh(eta_prime) ** 2 + cos(xi_prime) ** 2)
    relative_long_rad = atan(sinh(eta_prime) / cos(xi_prime))
    relative_long = degrees(relative_long_rad)  # longitude relative to central meridian

    # We are in a pickle here. Since tau is unknown and sigma is a function of tau, we need to use an approximation
    # for newton's method with a first guess for tau, say tau = tau_prime. With each iteration, f converges closer and
    # closer to zero and tau stabilizes. f should converge after 2-3 iterations, but other programs have used 7.
    # Likewise, we will be using 7 iterations.
    # source: [https: // stevedutch.net / usefuldata / utmformulas.htm] analogous to (Karney 2010, pg.3, eqn. 19-21)

    tau = tau_prime
    for iteration in range(7):
        sigma = sinh(e * atanh(e * tau / sqrt(1 + tau ** 2)))
        f_tau = tau * sqrt(1 + sigma ** 2) - sigma * sqrt(1 + tau ** 2) - tau_prime
        d_tau = (sqrt((1 + sigma ** 2) * (1 + tau ** 2)) - sigma * tau) * (1 - e ** 2) * sqrt(1 + tau ** 2) / (
                    1 + (1 - e ** 2) * tau ** 2)
        tau = tau - f_tau / d_tau

    lat = degrees(atan(tau))    # Return latitude back to degrees.

    if North:                   # Convert latitude to negative if South.
        lat = abs(lat)
    else:
        lat = abs(lat) * -1

    long = relative_long + zone_cm

    return lat, long
Exemple #56
0
def _ellipsoidal_area(a, b, lambda12, phi1, phi2, alpha1, alpha2):
    """ Area of a single quatrilateral defined by two meridians, the equator,
    and another geodesic.
    """
    f = (a-b)/a
    e2 = f*(2-f)
    ep2 = e2/(1-e2)
    e = sqrt(e2)

    # Authalic radius
    c = sqrt(a**2/2 + b**2/2*atanh(e)/e)

    beta1 = atan((1-f)*tan(phi1))
    beta2 = atan((1-f)*tan(phi2))

    _i = sqrt(cos(alpha1)**2 + (sin(alpha1)*sin(beta1))**2)
    alpha0 = atan2(sin(alpha1)*cos(beta1), _i)

    sigma1, omega1 = _solve_NEA(alpha0, alpha1, beta1)
    _, sigma2, omega2 = _solve_NEB(alpha0, alpha1, beta1, beta2)
    omega12 = omega2 - omega1

    # Bessel identity for alpha2 - alpha1
    alpha12 = 2*atan(sin(0.5*beta1+0.5*beta2)/cos(0.5*beta2-0.5*beta1) \
            * tan(0.5*omega12))
    sph_term = c**2 * alpha12

    # compute integrals for ellipsoidal correction
    k2 = ep2*cos(alpha0)**2

    C40 = (2.0/3 - ep2/15 + 4*ep2**2/105 - 8*ep2**3/315 + 64*ep2**4/3465 - 128*ep2**5/9009) \
        - (1.0/20 - ep2/35 + 2*ep2**2/105 - 16*ep2**3/1155 + 32*ep2**4/3003) * k2 \
        + (1.0/42 - ep2/63 + 8*ep2**2/693 - 90*ep2**3/9009) * k2**2 \
        - (1.0/72 - ep2/99 + 10*ep2**2/1287) * k2**3 \
        + (1.0/110 - ep2/143) * k2**4 - k2**5/156

    C41 = (1.0/180 - ep2/315 + 2*ep2**2/945 - 16*ep2**3/10395 + 32*ep2**4/27027) * k2 \
        - (1.0/252 - ep2/378 + 4*ep2**2/2079 - 40*ep2**3/27027) * k2**2 \
        + (1.0/360 - ep2/495 + 2*ep2**2/1287) * k2**3 \
        - (1.0/495 - 2*ep2/1287) * k2**4 + 5*k2**5/3276

    C42 = (1.0/2100 - ep2/3150 + 4*ep2**2/17325 - 8*ep2**3/45045) * k2**2 \
        - (1.0/1800 - ep2/2475 + 2*ep2**2/6435) * k2**3 \
        + (1.0/1925 - 2*ep2/5005) * k2**4 - k2**5/2184

    C43 = (1.0/17640 - ep2/24255 + 2*ep2**2/63063) * k2**3 \
        - (1.0/10780 - ep2/14014) * k2**4 + 5*k2**5/45864

    C44 = (1.0/124740 - ep2/162162) * k2**4 - 1*k2**5/58968

    C45 = k2**5/792792

    Cs = [C40, C41, C42, C43, C44, C45]
    I4s1 = sum(c*cos((2*i+1)*sigma1) for i,c in enumerate(Cs))
    I4s2 = sum(c*cos((2*i+1)*sigma2) for i,c in enumerate(Cs))

    S12 = sph_term + e**2*a**2 * cos(alpha0)*sin(alpha0) * (I4s2-I4s1)
    return S12
def lambert93_to_WGPS(lambertE, lambertN):
    """
    Converts coordinates given in
    `Lambert 93 <https://fr.wikipedia.org/wiki/Projection_conique_conforme_de_Lambert>`_
    system, this system is used by `IGN <http://http://professionnels.ign.fr/>`_
    and their :epkg:`GEOFLA` file format.

    @param      lambertE        east
    @param      lambertN        north
    @return                     longitude, latitude

    The function is inspired from
    `lam93toLatLon.py <https://gist.github.com/flire/0a305eeec77bc84a73af8ddc8f9ec043>`_.

    .. faqref::
        :tag: geo
        :title: Les fichiers GEOFLA ne contiennent pas de longitude, latitude ?

        Les coordonnées contenues dans les fichiers :epkg:`GEOFLA`
        ne sont pas toujours des longitudes, latitudes mais des coordonnées exprimées dans un système
        de projection conique `Lambert 93 <https://fr.wikipedia.org/wiki/Projection_conique_conforme_de_Lambert>`_.
        Il faut convertir les coordonnées avant de pouvoir tracer la carte ou changer la projection
        utilisée par :epkg:`cartopy` :
        `Lambert Conformal Projection <https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#lambertconformal>`_.
    """
    class constantes:
        GRS80E = 0.081819191042816
        LONG_0 = 3
        XS = 700000
        YS = 12655612.0499
        n = 0.7256077650532670
        C = 11754255.4261

    delX = lambertE - constantes.XS
    delY = lambertN - constantes.YS
    gamma = math.atan(-delX / delY)
    R = math.sqrt(delX * delX + delY * delY)
    latiso = math.log(constantes.C / R) / constantes.n
    sinPhiit0 = math.tanh(latiso + constantes.GRS80E *
                          math.atanh(constantes.GRS80E * math.sin(1)))
    sinPhiit1 = math.tanh(latiso + constantes.GRS80E *
                          math.atanh(constantes.GRS80E * sinPhiit0))
    sinPhiit2 = math.tanh(latiso + constantes.GRS80E *
                          math.atanh(constantes.GRS80E * sinPhiit1))
    sinPhiit3 = math.tanh(latiso + constantes.GRS80E *
                          math.atanh(constantes.GRS80E * sinPhiit2))
    sinPhiit4 = math.tanh(latiso + constantes.GRS80E *
                          math.atanh(constantes.GRS80E * sinPhiit3))
    sinPhiit5 = math.tanh(latiso + constantes.GRS80E *
                          math.atanh(constantes.GRS80E * sinPhiit4))
    sinPhiit6 = math.tanh(latiso + constantes.GRS80E *
                          math.atanh(constantes.GRS80E * sinPhiit5))

    longRad = math.asin(sinPhiit6)
    latRad = gamma / constantes.n + constantes.LONG_0 / 180 * math.pi

    longitude = latRad / math.pi * 180
    latitude = longRad / math.pi * 180

    return longitude, latitude
Exemple #58
0
 def transMercator (cls, lat, lon, centerlon=0.0):
     """
     Transversal Mercator projection - returns (x,y) tuple (unit:  m)
     """
     _lat = math.radians(lat)
     _lon = math.radians(lon-centerlon)
     x = cls.r_earth * math.atanh(math.sin(_lon) * math.cos(_lat))
     y = cls.r_earth * math.atan(math.tan(_lat) / math.cos(_lon))
     return x,y
Exemple #59
0
def test_shearest_shape():
    """Test that shear estimation is insensitive to shape of input images."""
    # this test can help reveal bugs having to do with x / y indexing issues
    import time
    t1 = time.time()
    # just do test for one particular gaussian
    g1 = shear_values[1]
    g2 = shear_values[2]
    e1_psf = 0.05
    e2_psf = -0.04
    total_shear = np.sqrt(g1**2 + g2**2)
    conversion_factor = np.tanh(2.0*math.atanh(total_shear))/total_shear
    distortion_1 = g1*conversion_factor
    distortion_2 = g2*conversion_factor
    gal = galsim.Exponential(flux = 1.0, half_light_radius = 1.)
    gal.applyShear(g1=g1, g2=g2)
    psf = galsim.Kolmogorov(flux = 1.0, fwhm = 0.7)
    psf.applyShear(e1=e1_psf, e2=e2_psf)
    final = galsim.Convolve([gal, psf])

    imsize = [128, 256]
    for method_index in range(len(correction_methods)):
        print correction_methods[method_index]

        save_e1 = -100.
        save_e2 = -100.
        for gal_x_imsize in imsize:
            for gal_y_imsize in imsize:
                for psf_x_imsize in imsize:
                    for psf_y_imsize in imsize:
                        print gal_x_imsize, gal_y_imsize, psf_x_imsize, psf_y_imsize
                        final_image = galsim.ImageF(gal_x_imsize, gal_y_imsize)
                        epsf_image = galsim.ImageF(psf_x_imsize, psf_y_imsize)

                        final_image = final.draw(image = final_image, dx = pixel_scale)
                        epsf_image = psf.draw(image = epsf_image, dx = pixel_scale)
                        result = galsim.EstimateShearHSM(final_image, epsf_image,
                            shear_est = correction_methods[method_index])
                        e1 = result.corrected_e1
                        e2 = result.corrected_e2
                        # make sure answers don't change as we vary image size

                        tot_e = np.sqrt(save_e1**2 + save_e2**2)
                        if tot_e < 99.:
                            print "Testing!"
                            np.testing.assert_almost_equal(e1, save_e1,
                                err_msg = "- incorrect e1",
                                decimal = decimal_shape)
                            np.testing.assert_almost_equal(e2, save_e2,
                                err_msg = "- incorrect e2",
                                decimal = decimal_shape)
                        print save_e1, save_e2, e1, e2
                        save_e1 = e1
                        save_e2 = e2

    t2 = time.time()
    print 'time for %s = %.2f'%(funcname(),t2-t1)