Esempio n. 1
0
def get_poly(theta_vertices, phi_vertices, theta_in, phi_in):
    """get the SphericalPolygon object for the geometry"""
    bounding_theta = theta_vertices - np.pi / 2.  #to radec
    bounding_phi = phi_vertices
    bounding_xyz = np.asarray(
        sgv.radec_to_vector(bounding_phi, bounding_theta, degrees=False)).T
    inside_xyz = np.asarray(
        sgv.radec_to_vector(phi_in, theta_in - np.pi / 2., degrees=False))

    sp_poly = SphericalPolygon(bounding_xyz, inside=inside_xyz)
    return sp_poly
Esempio n. 2
0
def get_difference(poly1, poly2, pixels=None):
    """attempt to get the difference poly1-poly2 as poly1^~poly2
        use a pixelation to attempt to find an outside point"""
    import matplotlib.pyplot as plt
    from mpl_toolkits.basemap import Basemap
    m = Basemap(projection='moll', lon_0=0)
    if pixels is None:
        pixels = get_healpix_pixelation(4)
    bounding_xyz = list(poly2.points)
    #contained = np.zeros(pixels.shape[0],dtype==bool)
    #for itr in range(0,len(bounding_xyz)):
    #    ra,dec = sgv.vector_to_radec(
    #    contained = contained | contains_points(bounding_xyz[itr],pixels)
    contained = contains_points(pixels, poly2)
    poly2_complement = None
    #poly2_complement = poly2.invert_polygon()
    #contained_c = contains_points(pixels,poly2_complement)
    #assert not np.any(contained & contained_c)
    first_false = 100 + np.argmin(contained[100:])
    #print("orig 1",contains_points(pixels[first_false:first_false+1],poly1),poly1.area())
    #print("orig 2",contains_points(pixels[first_false:first_false+1],poly2),poly2.area())
    print(poly2)
    colors = ['red', 'green', 'blue']
    for itr in range(0, len(bounding_xyz)):
        first_false = 100 + itr + np.argmin(contained[100 + itr:])
        theta_in = pixels[first_false, 0]
        phi_in = pixels[first_false, 1]
        inside_xyz = np.asarray(
            sgv.radec_to_vector(phi_in, theta_in - np.pi / 2., degrees=False))
        loc_poly = SphericalPolygon(bounding_xyz[itr].copy(),
                                    inside_xyz.copy())
        loc_poly.draw(m, color=colors[itr])
        cont = contains_points(pixels[first_false:first_false + 1], loc_poly)
        print("loc contains: ", cont)
        if poly2_complement is None:
            poly2_complement = deepcopy(loc_poly)
        else:
            poly2_complement = deepcopy(
                poly2_complement.intersection(loc_poly))
        cont_comp = contains_points(pixels[first_false:first_false + 1],
                                    poly2_complement)
        print("comp contains: ", cont_comp)
        print("test: ",
              np.all(contains_points(pixels[contained], poly2_complement)))
        print("test: ",
              np.any(contains_points(pixels[~contained], poly2_complement)))
        print("insp: ", list(poly2_complement.inside))
        #print("comp ",itr,contains_points(pixels[first_false:first_false+1],poly2_complement),poly2_complement.area(),poly2_complement.is_clockwise())
        #print("inside c ",list(poly2_complement.inside))
        #print("vert c ",list(poly2_complement.points))
        #for itr2 in range(0,len(list(poly2_complement.inside))):
        #    print("loc cont inside c ",loc_poly.contains_point(list(poly2_complement.inside)[itr2]))
    #print(poly1.area(),poly2.area(),poly2_complement.area())
    plt.show()
    return poly1.intersection(poly2_complement)
Esempio n. 3
0
def whereis(raIn, decIn, wcs_corners):
    #
    # will identify all obsids where the input raIn,DecIn point is within the footprint polygon
    #
    # raI, decIn are the coordinates in degrees
    # wcs_corners is a astropy.table.Table objects with the obsid and the 4 footprint corners.
    #
    # returns the list of obsids
    #
    nm = len(wcs_corners)
    #
    obsids = wcs_corners["obsid"].data
    ra1 = wcs_corners["ra1"].data
    ra2 = wcs_corners["ra2"].data
    ra3 = wcs_corners["ra3"].data
    ra4 = wcs_corners["ra4"].data
    dec1 = wcs_corners["dec1"].data
    dec2 = wcs_corners["dec2"].data
    dec3 = wcs_corners["dec3"].data
    dec4 = wcs_corners["dec4"].data
    ra0 = ra1
    dec0 = dec1
    #
    # storing in a dictionary with SphericalPolygons
    spx = {}
    for i in np.arange(nm):
        iobs = obsids[i]
        ra_corn = [ra1[i], ra2[i], ra3[i], ra4[i], ra0[i]]
        dec_corn = [dec1[i], dec2[i], dec3[i], dec4[i], dec0[i]]
        spoly = polygon.SphericalPolygon.from_radec(ra_corn,
                                                    dec_corn,
                                                    degrees=True)
        spx[iobs] = spoly
    #
    # now checking if the input falls in a polygon
    #
    vec = vector.radec_to_vector(raIn, decIn)
    obsFound = []
    for j in spx.keys():
        if (spx[j].contains_point(vec)):
            obsFound.append(j)
        nfound = len(obsFound)
    return obsFound
Esempio n. 4
0
def contains_points(pixels, sp_poly):
    """contains procedure adapted from spherical_geometry but pixels can be a vector so faster"""
    xyz_vals = np.array(
        sgv.radec_to_vector(pixels[:, 1],
                            pixels[:, 0] - np.pi / 2.,
                            degrees=False)).T
    contained = np.zeros(pixels.shape[0], dtype=bool)
    points = list(sp_poly.points)
    inside = list(sp_poly.inside)
    #iterate over polygons if disjoint
    for itr1 in range(0, len(points)):
        intersects = np.zeros(pixels.shape[0], dtype=int)
        bounding_xyz = np.asarray(points[itr1])
        inside_xyz = np.asarray(inside[itr1])
        for itr2 in range(0, bounding_xyz.shape[0] - 1):
            intersects += contains_intersect(bounding_xyz[itr2],
                                             bounding_xyz[itr2 + 1],
                                             inside_xyz, xyz_vals)
        contained = contained | (np.mod(intersects, 2) == 0).astype(bool)
    return contained
Esempio n. 5
0
def whereis(raIn,decIn,wcs_corners):
    #
    # will identify all obsids where the input raIn,DecIn point is within the footprint polygon
    #
    # raI, decIn are the coordinates in degrees
    # wcs_corners is a astropy.table.Table objects with the obsid and the 4 footprint corners.
    #
    # returns the list of obsids
    #
    nm = len(wcs_corners)
    #
    obsids = wcs_corners["obsid"].data
    ra1 = wcs_corners["ra1"].data
    ra2 = wcs_corners["ra2"].data
    ra3 = wcs_corners["ra3"].data
    ra4 = wcs_corners["ra4"].data
    dec1 = wcs_corners["dec1"].data
    dec2 = wcs_corners["dec2"].data
    dec3 = wcs_corners["dec3"].data
    dec4 = wcs_corners["dec4"].data
    ra0 = ra1
    dec0 = dec1
    #
    # storing in a dictionary with SphericalPolygons
    spx = {}
    for i in np.arange(nm):
        iobs = obsids[i]
        ra_corn = [ra1[i],ra2[i],ra3[i],ra4[i],ra0[i]]
        dec_corn = [dec1[i],dec2[i],dec3[i],dec4[i],dec0[i]]
        spoly = polygon.SphericalPolygon.from_radec(ra_corn,dec_corn, degrees=True)
        spx[iobs] = spoly
    #
    # now checking if the input falls in a polygon
    #
    vec = vector.radec_to_vector(raIn,decIn)
    obsFound = []
    for j in spx.keys():
        if (spx[j].contains_point(vec)):
            obsFound.append(j)
        nfound = len(obsFound)
    return obsFound
Esempio n. 6
0
    def run(self, dataSlice, slicePoint=None):
        # RA and Dec from dataSlice doesn't necessarily match healpix
        RA = dataSlice['fieldRA'][0]
        Dec = dataSlice['fieldDec'][0]
        # Get RA and Dec from slicer
        RA = slicePoint['ra']
        Dec = slicePoint['dec']
        nside = slicePoint['nside']
        # get the boundaries from HealPix
        bounding = hp.boundaries(nside, slicePoint['sid'], step=1).T
        inside_val = np.asarray(
            sgv.radec_to_vector(slicePoint['ra'],
                                slicePoint['dec'],
                                degrees=False))
        test_pointing = SphericalPolygon(bounding, inside_val)

        overlap_area = [
            test_pointing.intersection(survey_polygon).area()
            for survey_polygon in survey_list[self.region_name]
        ]
        total = sum(overlap_area)
        healpix_area = test_pointing.area()
        return min(total, 4 * np.pi - total)
Esempio n. 7
0
    def __init__(self, zs, thetas, phis, theta_in, phi_in, C, z_fine, l_max,
                 poly_params):
        """     inputs:
                    zs: the tomographic z bins
                    thetas,phis: an array of theta values for the edges in radians, last value should be first for closure, edges will be clockwise
                    theta_in,phi_in: a theta and phi known to be outside, needed for finding intersect for now
                    C: a CosmoPie object
                    z_fine: the resolution z slices
                    l_max: the maximum l to compute the alm table to
                    poly_params: a dict of parameters
        """

        self.poly_params = poly_params
        self.n_double = poly_params['n_double']
        self.l_max = l_max

        #maximum alm already available, only a00 available at start
        self._l_max = 0
        self.n_v = thetas.size - 1

        self.bounding_theta = thetas - np.pi / 2.  #to radec
        self.bounding_phi = np.pi - phis
        self.bounding_xyz = np.asarray(
            sgv.radec_to_vector(self.bounding_phi,
                                self.bounding_theta,
                                degrees=False)).T
        self.theta_in = theta_in
        self.phi_in = phi_in
        self.thetas_orig = thetas
        self.phis_orig = phis

        #this gets correct internal angles with specified vertex order (copied from spherical_polygon clas)
        angle_body = gca.angle(self.bounding_xyz[:-2],
                               self.bounding_xyz[1:-1],
                               self.bounding_xyz[2:],
                               degrees=False)
        angle_end = gca.angle(self.bounding_xyz[-2],
                              self.bounding_xyz[0],
                              self.bounding_xyz[1],
                              degrees=False)
        self.internal_angles = 2. * np.pi - np.hstack([angle_body, angle_end])

        Geo.__init__(self, zs, C, z_fine)

        self.sp_poly = get_poly(thetas, phis, theta_in, phi_in)
        print("PolygonGeo: area calculated by SphericalPolygon: " +
              str(self.sp_poly.area()))
        print("PolygonGeo: area calculated by PolygonGeo: " +
              str(self.angular_area()) + " sr or " +
              str(self.angular_area() * (180. / np.pi)**2) + " deg^2")

        self.alm_table = {(0, 0): self.angular_area() / np.sqrt(4. * np.pi)}

        self.z_hats = np.zeros((self.n_v, 3))
        self.y_hats = np.zeros_like(self.z_hats)
        self.xps = np.zeros_like(self.z_hats)

        self.betas = np.zeros(self.n_v)
        self.theta_alphas = np.zeros(self.n_v)
        self.omega_alphas = np.zeros(self.n_v)
        self.gamma_alphas = np.zeros(self.n_v)

        for itr1 in range(0, self.n_v):
            itr2 = itr1 + 1
            pa1 = self.bounding_xyz[itr1]  #vertex 1
            pa2 = self.bounding_xyz[itr2]  #vertex 2
            cos_beta12 = np.dot(pa2, pa1)  #cos of angle between pa1 and pa2
            cross_12 = np.cross(pa2, pa1)
            sin_beta12 = np.linalg.norm(cross_12)  #magnitude of cross product
            self.betas[itr1] = np.arctan2(
                sin_beta12, cos_beta12)  #angle between pa1 and pa2
            #angle should be in quadrant expected by arccos because angle should be <pi
            beta_alt = np.arccos(cos_beta12)

            assert np.isclose(sin_beta12, np.sin(self.betas[itr1]))
            assert np.isclose(sin_beta12**2 + cos_beta12**2, 1.)
            assert np.isclose(beta_alt, self.betas[itr1])

            #define z_hat if possible
            if np.isclose(self.betas[itr1], 0.):
                print(
                    "PolygonGeo: side length 0, directions unconstrained, picking directions arbitrarily"
                )
                #z_hat is not uniquely defined here so arbitrarily pick one orthogonal to pa1
                arbitrary = np.zeros(3)
                if not np.isclose(np.abs(pa1[0]), 1.):
                    arbitrary[0] = 1.
                elif not np.isclose(np.abs(pa1[1]), 1.):
                    arbitrary[1] = 1.
                else:
                    arbitrary[2] = 1.
                cross_12 = np.cross(arbitrary, pa1)
                self.z_hats[itr1] = cross_12 / np.linalg.norm(cross_12)
            elif np.isclose(self.betas[itr1], np.pi):
                raise RuntimeError(
                    "PolygonGeo: Spherical polygons with sides of length pi are not uniquely determined"
                )
            else:
                self.z_hats[
                    itr1] = cross_12 / sin_beta12  #direction of cross product

            #three euler rotation angles
            if not (np.isclose(self.z_hats[itr1, 1], 0.)
                    and np.isclose(self.z_hats[itr1, 0], 0.)):
                self.theta_alphas[itr1] = -np.arccos(self.z_hats[itr1, 2])
                y1 = np.cross(self.z_hats[itr1], pa1)
                self.y_hats[itr1] = y1
                assert np.allclose(
                    pa1 * np.cos(self.betas[itr1]) -
                    y1 * np.sin(self.betas[itr1]), pa2)
                assert np.allclose(np.cross(pa1, y1), self.z_hats[itr1])
                self.xps[itr1] = np.array([
                    self.z_hats[itr1][1] * pa1[0] -
                    self.z_hats[itr1][0] * pa1[1],
                    self.z_hats[itr1][1] * y1[0] -
                    self.z_hats[itr1][0] * y1[1], 0.
                ])

                self.gamma_alphas[itr1] = np.arctan2(-self.z_hats[itr1, 0],
                                                     self.z_hats[itr1, 1])
                gamma_alpha2 = np.arctan2(self.z_hats[itr1, 1],
                                          self.z_hats[itr1, 0]) - np.pi / 2.
                assert np.isclose(np.mod(self.gamma_alphas[itr1] + 0.000001,
                                         2. * np.pi),
                                  np.mod(gamma_alpha2 + 0.000001, 2. * np.pi),
                                  atol=1.e-5)
                self.omega_alphas[itr1] = -np.arctan2(self.xps[itr1, 1],
                                                      self.xps[itr1, 0])
            else:
                self.omega_alphas[itr1] = 0.
                self.gamma_alphas[itr1] = np.arctan2(pa1[1], pa1[0])
                #need to handle the case where z||z_hat separately (so don't divide by 0)
                if self.z_hats[itr1, 2] < 0:
                    print("PolygonGeo: setting theta_alpha to pi at " +
                          str(itr1))
                    self.theta_alphas[itr1] = np.pi
                else:
                    print("PolygonGeo: setting theta_alpha to 0 at " +
                          str(itr1))
                    self.theta_alphas[itr1] = 0.

        self.expand_alm_table(l_max)
        print("PolygonGeo: finished initialization")
Esempio n. 8
0
def test_geos1():
    """do second test posted to bug report"""
    n_fill = 10

    theta1_high_fill = np.full(n_fill, 5.)
    theta1_low_fill = np.full(n_fill, -65.)
    phi1_high_fill = np.linspace(50. - 360., 50. - 1., n_fill)
    phi1_low_fill = phi1_high_fill[::-1]
    theta1s = np.hstack(
        [theta1_high_fill, theta1_low_fill, theta1_high_fill[0]])
    phi1s = np.hstack([phi1_high_fill, phi1_low_fill, phi1_high_fill[0]])

    phi_in1 = 0.
    theta_in1 = 70.

    bounding_xyz1 = np.array(sgv.radec_to_vector(phi1s, theta1s,
                                                 degrees=True)).T
    inside_xyz1 = np.array(
        sgv.radec_to_vector(phi_in1, theta_in1, degrees=True))
    sp_poly1 = SphericalPolygon(bounding_xyz1, inside=inside_xyz1)

    theta2_high_fill = np.full(n_fill, -30.)
    theta2_low_fill = np.full(n_fill, -85.)
    phi2_high_fill = np.linspace(65 - 360., 55. - 10., n_fill)
    phi2_low_fill = np.linspace(5 - 360., 5. - 10., n_fill)[::-1]
    theta2s = np.hstack(
        [theta2_high_fill, theta2_low_fill, theta2_high_fill[0]])
    phi2s = np.hstack([phi2_high_fill, phi2_low_fill, phi2_high_fill[0]])

    phi_in2 = 0.
    theta_in2 = 70.

    bounding_xyz2 = np.array(sgv.radec_to_vector(phi2s, theta2s,
                                                 degrees=True)).T
    inside_xyz2 = np.array(
        sgv.radec_to_vector(phi_in2, theta_in2, degrees=True))
    sp_poly2 = SphericalPolygon(bounding_xyz2, inside=inside_xyz2)

    int_poly = sp_poly2.intersection(sp_poly1)

    theta_out = -50. * np.pi / 180.
    phi_out = 0.
    outside_xyz = np.array(
        sgv.radec_to_vector(phi_out, theta_out, degrees=False))

    theta_in3 = 70. * np.pi / 180.
    phi_in3 = 0.
    inside_xyz3 = np.array(
        sgv.radec_to_vector(phi_in3, theta_in3, degrees=False))

    print("area int, area 1,area 2: ", int_poly.area(), sp_poly1.area(),
          sp_poly2.area())
    print("Should be True , True : ",
          int_poly.area() <= sp_poly1.area(),
          int_poly.area() <= sp_poly2.area())
    assert int_poly.area() <= sp_poly1.area()
    assert int_poly.area() <= sp_poly2.area()

    assert not int_poly.contains_point(outside_xyz)
    assert not sp_poly1.contains_point(outside_xyz)
    assert not sp_poly2.contains_point(outside_xyz)
    print("Should be True ,True ,True : ",
          int_poly.contains_point(inside_xyz1),
          sp_poly1.contains_point(inside_xyz1),
          sp_poly2.contains_point(inside_xyz1))
    assert int_poly.contains_point(inside_xyz1)
    assert sp_poly1.contains_point(inside_xyz1)
    assert sp_poly2.contains_point(inside_xyz1)
    print("Should be True ,True ,True : ",
          int_poly.contains_point(inside_xyz2),
          sp_poly1.contains_point(inside_xyz2),
          sp_poly2.contains_point(inside_xyz2))
    assert int_poly.contains_point(inside_xyz2)
    assert sp_poly1.contains_point(inside_xyz2)
    assert sp_poly2.contains_point(inside_xyz2)
    print("Should be True ,True ,True : ",
          int_poly.contains_point(inside_xyz3),
          sp_poly1.contains_point(inside_xyz3),
          sp_poly2.contains_point(inside_xyz3))
    assert int_poly.contains_point(inside_xyz3)
    assert sp_poly1.contains_point(inside_xyz3)
    assert sp_poly2.contains_point(inside_xyz3)

    inside_res = list(int_poly.inside)
    for itr in range(0, len(inside_res)):
        print("Should be True ,True ,True : ",
              int_poly.contains_point(inside_res[itr]),
              sp_poly1.contains_point(inside_res[itr]),
              sp_poly2.contains_point(inside_res[itr]))
        assert int_poly.contains_point(inside_res[itr])
        assert sp_poly1.contains_point(inside_res[itr])
        assert sp_poly2.contains_point(inside_res[itr])
Esempio n. 9
0
def test_geos2():
    """do initial test posted to spherical_geometry problem report"""
    n_fill = 10

    theta1_high_fill = np.full(n_fill, 5.)
    theta1_low_fill = np.full(n_fill, -65.)
    phi1_high_fill = np.linspace(50. - 360., 50. - 1., n_fill)
    phi1_low_fill = phi1_high_fill[::-1]
    theta1s = np.hstack(
        [theta1_high_fill, theta1_low_fill, theta1_high_fill[0]])
    phi1s = np.hstack([phi1_high_fill, phi1_low_fill, phi1_high_fill[0]])

    phi_in1 = 0.
    theta_in1 = 0.

    bounding_xyz1 = np.array(sgv.radec_to_vector(phi1s, theta1s,
                                                 degrees=True)).T
    inside_xyz1 = np.array(
        sgv.radec_to_vector(phi_in1, theta_in1, degrees=True))
    sp_poly1 = SphericalPolygon(bounding_xyz1, inside=inside_xyz1)

    theta2_high_fill = np.full(n_fill, -30.)
    theta2_low_fill = np.full(n_fill, -85.)
    phi2_high_fill = np.linspace(65 - 360., 55. - 10., n_fill)
    phi2_low_fill = np.linspace(5 - 360., 5. - 10., n_fill)[::-1]
    theta2s = np.hstack(
        [theta2_high_fill, theta2_low_fill, theta2_high_fill[0]])
    phi2s = np.hstack([phi2_high_fill, phi2_low_fill, phi2_high_fill[0]])

    phi_in2 = 0.
    theta_in2 = -70.

    bounding_xyz2 = np.array(sgv.radec_to_vector(phi2s, theta2s,
                                                 degrees=True)).T
    inside_xyz2 = np.array(
        sgv.radec_to_vector(phi_in2, theta_in2, degrees=True))
    sp_poly2 = SphericalPolygon(bounding_xyz2, inside=inside_xyz2)

    int_poly = sp_poly2.intersection(sp_poly1)

    theta_out = 30. * np.pi / 180.
    phi_out = 0.
    outside_xyz = np.array(
        sgv.radec_to_vector(phi_out, theta_out, degrees=False))

    theta_in3 = -40. * np.pi / 180.
    phi_in3 = 0.
    inside_xyz3 = np.array(
        sgv.radec_to_vector(phi_in3, theta_in3, degrees=False))

    assert not int_poly.contains_point(outside_xyz)

    assert not int_poly.contains_point(outside_xyz)
    assert not sp_poly1.contains_point(outside_xyz)
    assert not sp_poly2.contains_point(outside_xyz)
    assert not int_poly.contains_point(inside_xyz1)
    assert sp_poly1.contains_point(inside_xyz1)
    assert not sp_poly2.contains_point(inside_xyz1)
    assert not int_poly.contains_point(inside_xyz2)
    assert not sp_poly1.contains_point(inside_xyz2)
    assert sp_poly2.contains_point(inside_xyz2)
    assert int_poly.contains_point(inside_xyz3)
    assert sp_poly1.contains_point(inside_xyz3)
    assert sp_poly2.contains_point(inside_xyz3)
Esempio n. 10
0
 latsC = latVertex[1:, :-1].ravel()
 lonsC = lonVertex[1:, :-1].ravel()  # upper left
 latsB = latVertex[1:, 1:].ravel()
 lonsB = lonVertex[1:, 1:].ravel()  # upper right
 latsD = latVertex[:-1, 1:].ravel()
 lonsD = lonVertex[:-1, 1:].ravel()  # lower right
 nxp1, nyp1 = lonVertex.shape
 nx = nxp1 - 1
 ny = nyp1 - 1
 npts = len(latsA)
 A = np.empty((npts, 3), dtype=np.float)
 B = np.empty((npts, 3), dtype=np.float)
 C = np.empty((npts, 3), dtype=np.float)
 D = np.empty((npts, 3), dtype=np.float)
 A[:, 0], A[:, 1], A[:, 2] = vector.radec_to_vector(lonsA,
                                                    latsA,
                                                    degrees=True)
 B[:, 0], B[:, 1], B[:, 2] = vector.radec_to_vector(lonsB,
                                                    latsB,
                                                    degrees=True)
 C[:, 0], C[:, 1], C[:, 2] = vector.radec_to_vector(lonsC,
                                                    latsC,
                                                    degrees=True)
 D[:, 0], D[:, 1], D[:, 2] = vector.radec_to_vector(lonsD,
                                                    latsD,
                                                    degrees=True)
 # find intersection of great circle arcs from each corner of grid box
 T = great_circle_arc.intersection(A, B, C, D)
 lonCell, latCell =\
 vector.vector_to_radec(T[:,0],T[:,1],T[:,2],degrees=True)
 nCells = len(lonCell)
Esempio n. 11
0
def fv3_regrid(datafiles,
               gridspecfiles,
               olons,
               olats,
               varname,
               slice_out,
               tri=None):
    """
    Regrid FV3 cubed sphere data to reg lat/lon mesh using
    triangulation + linear interpolation.

    datafiles : list of data filenames for each tile
    gridspecfiles : list of grid_spec filenames for each tile
    olons : 1d array of lons (in degrees) for output mesh
    olats : 1d array of lats (in degrees) for output mesh
    varname : var name to read from data files
    slice_out : python slice object for data slice
    tri : existing triangulation instance.  If None, it is computed.

    returns 2d data array on regular lat/lon mesh, triangulation instance."""
    lons = []
    lats = []
    data = []
    A = None
    for datafile, gridspecfile in zip(datafiles, gridspecfiles):
        print 'reading ', datafile
        nc = Dataset(datafile)
        arr = nc.variables[varname][slice_out]
        data.append(arr)
        nc.close()
        if tri is None:
            print 'reading ', gridspecfile
            nc = Dataset(gridspecfile)
            lons_tmp = nc.variables['grid_lon'][:]
            lats_tmp = nc.variables['grid_lat'][:]
            latsA = lats_tmp[:-1, :-1].ravel()
            lonsA = lons_tmp[:-1, :-1].ravel()  # lower left
            latsC = lats_tmp[1:, :-1].ravel()
            lonsC = lons_tmp[1:, :-1].ravel()  # upper left
            latsB = lats_tmp[1:, 1:].ravel()
            lonsB = lons_tmp[1:, 1:].ravel()  # upper right
            latsD = lats_tmp[:-1, 1:].ravel()
            lonsD = lons_tmp[:-1, 1:].ravel()  # lower right
            if A is None:
                nxp1, nyp1 = lons_tmp.shape
                nx = nxp1 - 1
                ny = nyp1 - 1
                npts = len(latsA)
                A = np.empty((npts, 3), dtype=np.float)
                B = np.empty((npts, 3), dtype=np.float)
                C = np.empty((npts, 3), dtype=np.float)
                D = np.empty((npts, 3), dtype=np.float)
            A[:, 0], A[:, 1], A[:, 2] = vector.radec_to_vector(lonsA,
                                                               latsA,
                                                               degrees=True)
            B[:, 0], B[:, 1], B[:, 2] = vector.radec_to_vector(lonsB,
                                                               latsB,
                                                               degrees=True)
            C[:, 0], C[:, 1], C[:, 2] = vector.radec_to_vector(lonsC,
                                                               latsC,
                                                               degrees=True)
            D[:, 0], D[:, 1], D[:, 2] = vector.radec_to_vector(lonsD,
                                                               latsD,
                                                               degrees=True)
            # find intersection of great circle arcs from each corner of grid box
            T = great_circle_arc.intersection(A, B, C, D)
            lonsmid, latsmid =\
            vector.vector_to_radec(T[:,0],T[:,1],T[:,2],degrees=True)
            lonsmid = lonsmid.reshape((ny, nx))
            latsmid = latsmid.reshape((ny, nx))
            lons.append(lonsmid)
            lats.append(latsmid)
            nc.close()
    if tri is None:
        lons = np.radians(np.array(lons, dtype=np.float64)).ravel()
        lats = np.radians(np.array(lats, dtype=np.float64)).ravel()
    else:
        lons = tri.lons
        lats = tri.lats
    data = (np.array(data, dtype=np.float64)).ravel()
    if getattr(tri, '_shuffle', False): data = data[tri._ix]
    return _regrid(lons, lats, data, olons, olats, shuffle=True, tri=tri)
Esempio n. 12
0
    hl = height / 2.
    #convert decimal degrees dimensions to correct array
    dRA1 = width / np.cos((Dec + hl) * np.pi / 180)
    dRA2 = width / np.cos((Dec - hl) * np.pi / 180)
    coord1 = np.asarray(
        [RA - dRA2, RA - dRA1, RA + dRA1, RA + dRA2, RA - dRA2])  #RA
    coord2 = np.asarray([Dec - hl, Dec + hl, Dec + hl, Dec - hl,
                         Dec - hl])  #Dec
    return coord1, coord2


# create the triangle test region 'survey'
temp_survey = []
coord1 = np.asarray([60, 40, 80, 60])  #RA
coord2 = np.asarray([10, -20, -20, 10])  #Dec
bounding = np.array(sgv.radec_to_vector(coord1, coord2, degrees=True)).T
inside_val = np.asarray(sgv.radec_to_vector(60, -10, degrees=True))
test_poly = SphericalPolygon(bounding, inside_val)
temp_survey.append(test_poly)
coord1 = np.asarray([160, 140, 180, 160])  #RA
coord2 = np.asarray([10, -20, -20, 10])  #Dec
bounding = np.array(sgv.radec_to_vector(coord1, coord2, degrees=True)).T
inside_val = np.asarray(sgv.radec_to_vector(160, -10, degrees=True))
test_poly = SphericalPolygon(bounding, inside_val)
temp_survey.append(test_poly)
survey_list['triangles'] = temp_survey

# create a WFIRST survey area based off of OGLE
temp_survey = []
coord1 = np.asarray([269.3875, 269.3917, 270.7667, 269.3875])  #RA
coord2 = np.asarray([-27.9944, -29.2208, -28.6108, -27.9944])  #Dec