示例#1
0
文件: obs.py 项目: spmls/pydelft
    def coords2mn(self,
                  grid,
                  station_names,
                  station_x,
                  station_y,
                  grid_epsg=4326,
                  station_epsg=4326):
        '''Calculate nearest m, n indices on a grid for an array of type (['name', x, y])
        where x and y are coordinates (longitude/latitude or eastin/northing etc.).
        If the two are different coordinate systems, will convert the array to the grid
        coordinate system (using EPSG codes, default is 4326=WGS84'''
        def find_nearest(grid, query):
            m = np.unravel_index(
                np.abs(grid.y - query[1]).argmin(), np.shape(grid.y))[0]
            n = np.unravel_index(
                np.abs(grid.x - query[0]).argmin(), np.shape(grid.x))[1]
            return [m, n]

        grid_proj = pyproj.Proj("+init=EPSG:%i" % grid_epsg)
        station_proj = pyproj.Proj("+init=EPSG:%i" % station_epsg)

        if grid_epsg != station_epsg:
            station_x, station_y = pyproj.transform(station_proj, grid_proj,
                                                    station_x, station_y)

        obs_idx = [
            find_nearest(grid, [station_x[i], station_y[i]])
            for i in range(0,
                           np.size(station_names) - 1)
        ]

        self.names = station_names
        self.m = [i[0] for i in obs_idx]
        self.n = [i[1] for i in obs_idx]
        self.num_obs = np.shape(obs_idx)[0]
示例#2
0
 def reproj_wgs84(self):
     # In basemap, the sinusoidal projection is global, so we won't use it.
     # Instead we'll convert the grid back to lat/lons.
     sinu = pyproj.Proj(
         "+proj=sinu +R=6371007.181000 +nadgrids=@null +wktext")
     wgs84 = pyproj.Proj("+init=EPSG:4326")
     self.Lon, self.Lat = pyproj.transform(sinu, wgs84, self.xv, self.yv)
示例#3
0
def transform(in_proj = 'EPSG:3011',out_proj = 'EPSG:4326', lat=0.0, lon=0.0):
    """
    Transform coordinates from one spatial reference system to another.
    in_proj is your current reference system
    out_proj is the reference system you want to transform to, default is EPSG:4326 = WGS84
    (Another good is EPSG:4258 = ETRS89 (Europe), almost the same as WGS84 (in Europe) 
    and not always clear if coordinates are in WGS84 or ETRS89, but differs <1m.
    lat = latitude
    lon = longitude
    
    To find your EPSG check this website: http://spatialreference.org/ref/epsg/
    """
    import mpl_toolkits.basemap.pyproj as pyproj
    
    o_proj = pyproj.Proj("+init="+out_proj) 
    i_proj = pyproj.Proj("+init="+in_proj)
    if type(lat) == list:
        if len(lat) != len(lon):
            print(u'Length of Latitude differs from length of Longitude! When providing lists och coordinates they must have the same length')
            x, y = None, None
        else:
            x = []
            y = []
            for i in range(len(lat)):
                x_i, y_i = pyproj.transform(i_proj, o_proj, float(lon[i]), float(lat[i]))
                x.append(x_i)
                y.append(y_i)
    else:
        x, y = pyproj.transform(i_proj, o_proj, float(lon), float(lat))
    
    return y, x
def flowline_latlon(coords, fromproj=pyproj.Proj("+init=epsg:3413"), toproj=pyproj.Proj("+init=EPSG:4326")):
    """Convert coords into lat/lon so that Basemap can convert them back for plotting (don't know why this is necessary, but it works)
    Defaults:
        fromproj = NSIDC Polar Stereographic North
        toproj = WGS84 lat-lon
    """
    xs = coords[:,0]
    ys = coords[:,1]
    x_lon, y_lat = pyproj.transform(fromproj, toproj, xs, ys)
    latlon_coords = np.asarray(zip(x_lon, y_lat))
    return latlon_coords
def getCoord(dataframe):
    df = dataframe.copy()
    WGS84 = pyproj.Proj(init='epsg:4326')
    Lambert2 = pyproj.Proj(init='epsg:27572')
    for i in np.arange(len(df)):
        x = df.ix[i].X_COORDINATE
        y = df.ix[i].Y_COORDINATE
        lons, lats = pyproj.transform(Lambert2, WGS84, x, y)
        df.set_value(i, 'LONGITUDE', lons)
        df.set_value(i, 'LATITUDE', lats)
    return df
示例#6
0
    def extract_coord_val(self, lon_sel, lat_sel):
        # Convert requested lat/lon to sinusoidal coords
        sinu = pyproj.Proj(
            "+proj=sinu +R=6371007.181000 +nadgrids=@null +wktext")
        wgs84 = pyproj.Proj("+init=EPSG:4326")
        lon_sel_sinu, lat_sel_sinu = pyproj.transform(wgs84, sinu, lon_sel,
                                                      lat_sel)

        # Method for extracting raster values at given coordinates
        y_sel = int((lat_sel_sinu - self.originY) / self.pixelHeight)
        x_sel = int((lon_sel_sinu - self.originX) / self.pixelWidth)
        return self.data[y_sel, x_sel]
示例#7
0
 def _calculate_center_second_domain(self):
     '''
 Calculate the center of the second domain for running in UPP mode
 '''
     grid_ratio = self.nml['geogrid']['parent_grid_ratio'][1]
     i_start = self.nml['geogrid']['i_parent_start']
     j_start = self.nml['geogrid']['j_parent_start']
     e_we = self.nml['geogrid']['e_we']
     e_sn = self.nml['geogrid']['e_sn']
     ref_lat = self.nml['geogrid']['ref_lat']
     ref_lon = self.nml['geogrid']['ref_lon']
     truelat1 = self.nml['geogrid']['truelat1']
     truelat2 = self.nml['geogrid']['truelat2']
     # new dx and dy
     self.dx = float(self.nml['geogrid']['dx']) / grid_ratio
     self.dy = float(self.nml['geogrid']['dy']) / grid_ratio
     # define projection string
     projstring = (
         "+init=EPSG:4326 +proj=lcc +lat_1=%s +lat_2=%s +lat_0=%s "
         "+lon_0=%s +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 "
         "+units=m +no_defs" %
         (str(truelat1), str(truelat2), str(ref_lat), str(ref_lon)))
     projection = pyproj.Proj(projstring)
     # calculate east/west/south/north
     west = (-self.nml['geogrid']['dx'] * (e_we[0] - 1) * 0.5) + (
         (i_start[1] - 1) * self.nml['geogrid']['dx'])
     south = (-self.nml['geogrid']['dy'] * (e_sn[0] - 1) * 0.5) + (
         (j_start[1] - 1) * self.nml['geogrid']['dy'])
     east = west + ((e_we[1] - 1) * self.dx)
     north = south + ((e_sn[1] - 1) * self.dy)
     # new ref_lat and ref_lon
     self.ref_lon, self.ref_lat = projection((west + east) * 0.5,
                                             (north + south) * 0.5,
                                             inverse=True)
示例#8
0
    def __init__(self, grid, debug=False):
        """ initalize the object. """
        # check that basemap is available
        if not _BASEMAP_AVAILABLE:
            raise MissingOptionalDependency(
                "Basemap is required to use GridMapDisplay but is not " +
                "installed")

        self.grid = grid
        self.debug = debug

        # set up the projection
        lat0 = grid.axes['lat']['data'][0]
        lon0 = grid.axes['lon']['data'][0]
        self.proj = pyproj.Proj(proj='aeqd', datum='NAD83',
                                lat_0=lat0, lon_0=lon0)

        # determine grid latitudes and longitudes.
        x_1d = grid.axes['x_disp']['data']
        y_1d = grid.axes['y_disp']['data']
        x_2d, y_2d = np.meshgrid(x_1d, y_1d)
        self.grid_lons, self.grid_lats = self.proj(x_2d, y_2d, inverse=True)

        # set attributes
        self.mappables = []
        self.fields = []
        self.origin = 'origin'
        self.basemap = None
示例#9
0
    def __init__(self, grid, debug=False):
        """ initalize the object. """
        self.grid = grid
        self.debug = debug

        # set up the projection
        lat0 = grid.axes['lat']['data'][0]
        lon0 = grid.axes['lon']['data'][0]
        self.proj = pyproj.Proj(proj='lcc',
                                datum='NAD83',
                                lat_0=lat0,
                                lon_0=lon0,
                                x_0=0.0,
                                y_0=0.0)

        # determine grid latitudes and longitudes.
        x_1d = grid.axes['x_disp']['data']
        y_1d = grid.axes['y_disp']['data']
        x_2d, y_2d = np.meshgrid(x_1d, y_1d)
        self.grid_lons, self.grid_lats = self.proj(x_2d, y_2d, inverse=True)

        # set attributes
        self.mappables = []
        self.fields = []
        self.basemap = None
示例#10
0
    def compute_station_distance(self):
        ''' Compute the maximum station to station distance.

        '''
        # Get the longitude and latidue coordinates of the stations.
        lon_lat = [stat.get_lon_lat() for stat in self.stations]
        lon = [x[0] for x in lon_lat]
        lat = [x[1] for x in lon_lat]
        proj = pyproj.Proj(init=self.map_config['epsg'])
        x, y = proj(lon, lat)
        x = np.reshape(x, (len(x), 1))
        y = np.reshape(y, (len(y), 1))
        x_mat = np.tile(np.array(x), (1, len(x)))
        y_mat = np.tile(np.array(y), (1, len(y)))

        rows, cols = np.ogrid[:x_mat.shape[0], :x_mat.shape[1]]
        rows = rows - np.arange(x_mat.shape[0])
        x_mat_roll = x_mat[rows, cols]

        rows, cols = np.ogrid[:y_mat.shape[0], :y_mat.shape[1]]
        rows = rows - np.arange(y_mat.shape[0])
        y_mat_roll = y_mat[rows, cols]

        # Compute the distances between all stations.
        dist = np.sqrt((x_mat - x_mat_roll)**2 + (y_mat - y_mat_roll)**2)
        self.max_station_dist = np.max(dist)
示例#11
0
def transformWrfProj(curs, domainNum, wrfLong, wrfLat, proj='epsg_4326'):
    """Uses pyproj to transform from WRF Lambert Conformal Conic to a new projection.

    Args:
        curs: WinDB2 cursor
        domainNum: WinDB2 domain number
        wrfLong: 1D or 2D Numpy array of WRF longitudes
        wrfLat: 1D or 2D Numpy array of WRF longitudes
        proj: Defaults to WGS84, use a pyproj legal projection string to change e.g. proj='epsg:4326'

    Returns:
        Reprojected long and lat arrays in of the same dimension of the input data

    """
    import numpy as np
    import mpl_toolkits.basemap.pyproj as pyproj

    # Temporarily convert to 1D if we've been passed a grid
    if len(wrfLong.shape) == 2 and len(wrfLat.shape) == 2:
        twoDToOneD = True
        wrfLongShape = wrfLong.shape
        wrfLong = wrfLong.ravel()
        wrfLatShape = wrfLat.shape
        wrfLat = wrfLat.ravel()
    else:
        twoDToOneD = False

    # Get the SRID of the WRF domain
    sql = """SELECT proj4text FROM spatial_ref_sys WHERE srid=(SELECT st_srid(geom) FROM horizgeom WHERE domainkey=""" + str(
        domainNum) + """ LIMIT 1)"""
    curs.execute(sql)
    wrfProj4Str = curs.fetchone()[0]

    # Create the WRF projection
    wrfProj4 = pyproj.Proj(wrfProj4Str)

    # Transform from WRF to WGS84
    wrfWgs84Lon, wrfWgs84Lat = pyproj.transform(wrfProj4,
                                                pyproj.Proj(init='epsg:4326'),
                                                wrfLong, wrfLat)

    # Convert back to 2D if necessary
    if twoDToOneD:
        wrfWgs84Lon = np.reshape(wrfWgs84Lon, wrfLongShape)
        wrfWgs84Lat = np.reshape(wrfWgs84Lat, wrfLatShape)

    return wrfWgs84Lon, wrfWgs84Lat
示例#12
0
    def compute_map_configuration(self):
        ''' The map limits computed from the stations.
        '''
        # Get the longitude and latidue coordinates of the stations.
        lon_lat = [stat.get_lon_lat() for stat in self.stations]
        lon = [x[0] for x in lon_lat]
        lat = [x[1] for x in lon_lat]

        # Get the UTM zone for the map limits.
        self.map_config['utmZone'] = geom_util.lon2UtmZone(
            np.mean([np.min(lon), np.max(lon)]))
        self.map_config['ellips'] = 'wgs84'
        self.map_config['lon_0'] = geom_util.zone2UtmCentralMeridian(
            self.map_config['utmZone'])
        self.map_config['lat_0'] = 0
        if np.mean([np.min(lat), np.max(lat)]) >= 0:
            self.map_config['hemisphere'] = 'north'
        else:
            self.map_config['hemisphere'] = 'south'

        #lon_lat_min = np.min(lon_lat, 0)
        #lon_lat_max = np.max(lon_lat, 0)
        #map_extent = lon_lat_max - lon_lat_min
        #self.map_config['limits'] = np.hstack([lon_lat_min, lon_lat_max])

        # Get the epsg code of the UTM projection.
        search_dict = {
            'projection': 'utm',
            'ellps': self.map_config['ellips'].upper(),
            'zone': self.map_config['utmZone'],
            'no_defs': True,
            'units': 'm'
        }
        if self.map_config['hemisphere'] == 'south':
            search_dict['south'] = True
        epsg_dict = geom_util.get_epsg_dict()
        code = [(c, x) for c, x in list(epsg_dict.items()) if x == search_dict]

        self.map_config['epsg'] = 'epsg:' + code[0][0]

        proj = pyproj.Proj(init=self.map_config['epsg'])

        x_coord, y_coord = proj(lon, lat)

        x_min = np.floor(np.min(x_coord) / float(self.map_dx)) * self.map_dx
        x_max = np.ceil(np.max(x_coord) / float(self.map_dx)) * self.map_dx

        y_min = np.floor(np.min(y_coord) / float(self.map_dy)) * self.map_dy
        y_max = np.ceil(np.max(y_coord) / float(self.map_dy)) * self.map_dy

        self.map_config['x_lim'] = (x_min, x_max)
        self.map_config['y_lim'] = (y_min, y_max)

        # Compute the maximum station to station distance.
        self.compute_station_distance()

        # Set the data length of the stations.
        for cur_station in self.stations:
            cur_station.data_length = np.ceil(self.window_length)
示例#13
0
 def proj(self):
     """ Deprecated proj attribute. """
     warnings.warn(
         "The 'proj' attribute has been deprecated and will be removed "
         "in future versions of Py-ART", category=DeprecatedAttribute)
     lat0 = self.grid.origin_latitude['data'][0]
     lon0 = self.grid.origin_longitude['data'][0]
     return pyproj.Proj(proj='aeqd', datum='NAD83', lat_0=lat0, lon_0=lon0)
示例#14
0
 def getGeoProj(self):
     import mpl_toolkits.basemap.pyproj as pyproj
     p1 = self._location["projParameter"].split()
     params = {}
     for p in p1:
         ps = p.split("=")
         if len(ps) == 2:
             params[ps[0]] = ps[1]
         else:
             params[ps[0]] = True
     return pyproj.Proj(projparams=params)
示例#15
0
    def ll2utm(lon, lat):
        #lon needs to be between +/-180
        zone = (int((180 + lon) / 6.0) + 1) % 60
        print "ZONE:  ", zone
        #zone needs to be between 1 and 60
        centralMeridian = zone * 6 - 180 - 3
        south = False
        if lat < 0.0:
            south = True

        p = pyproj.Proj(proj='utm', zone=zone, south=south, ellps='WGS84')
        return p(lon, lat)
示例#16
0
def interior_grid(path, grid, basemap, level, plot_type):
    '''
    Return the bins of the Radar in the interior of the path.

    Parameters
    ----------
    path : Matplotlib Path instance
    grid : :py:class:`pyart.core.Grid` Instance
    level : int
        Section from the grid to be considered.
    plot_type : "gridZ", "gridY" or "gridX"
        Plot type used

    Returns
    -------
    xy : Numpy Array
        Array of the shape (bins,2) containing the x,y
        coordinate for every bin inside path
    index : Numpy Array
        Array of the shape (bins,2) containing the ray and range
        coordinate for every bin inside path
    '''
    if plot_type == "gridZ":
        x, y = np.meshgrid(grid.axes['x_disp']['data'],
                           grid.axes['y_disp']['data'])
        ny = len(grid.axes['y_disp']['data'])
        if basemap is not None:
            from mpl_toolkits.basemap import pyproj
            proj = pyproj.Proj(proj='aeqd', datum='NAD83',
                               lat_0=grid.axes['lat']['data'][0],
                               lon_0=grid.axes['lon']['data'][0])
            lat, lon = proj(x, y, inverse=True)
            x, y = basemap(lat, lon)
    elif plot_type == "gridY":
        x, y = np.meshgrid(grid.axes['x_disp']['data'] / 1000.,
                           grid.axes['z_disp']['data'] / 1000.)
        ny = len(grid.axes['z_disp']['data'])
    elif plot_type == "gridX":
        x, y = np.meshgrid(grid.axes['y_disp']['data'] / 1000.,
                           grid.axes['z_disp']['data'] / 1000.)
        ny = len(grid.axes['z_disp']['data'])

    xys = np.empty(shape=(x.size, 2))
    xys[:, 0] = x.flatten()
    xys[:, 1] = y.flatten()
    # XXX in new versions (1.3) of mpl there is contains_pointS function
    ind = np.nonzero([path.contains_point(xy) for xy in xys])[0]

    x_index = ind / ny
    y_index = ind % ny
    index = np.concatenate((x_index[np.newaxis],
                            y_index[np.newaxis]), axis=0)
    return (xys[ind], index.transpose().astype(np.int))
示例#17
0
def ice_map(date_inp,m):
    date_code=str(date_inp.year)+'%02.0f' % date_inp.month
    file_path='/Users/paulchamberlain/Data/SOCCOM/SEA_ICE/NOAAG02135/'+str(date_inp.strftime("%B"))+'/shp_extent/extent_S_'+date_code+'_polyline/extent_S_'+date_code+'_polyline'
    prj_file = open(file_path+'.prj', 'r')
    prj_txt = prj_file.read()
    srs = osr.SpatialReference()
    srs.ImportFromESRI([prj_txt])

    shpProj = pyproj.Proj(srs.ExportToProj4())
    mapProj = pyproj.Proj(m.proj4string)
    sf = shapefile.Reader(file_path)
    shapes = sf.shapes()
    shpX = [] 
    shpY = []
    for n in range(len(shapes)):
        shpX = [px[0] for px in shapes[n].points]
        shpY = [px[1] for px in shapes[n].points]
        lonlat = np.array(shpProj(shpX,shpY,inverse=True)).T
        ice_data = np.array(mapProj(lonlat[:,0],lonlat[:,1])).T
        m.plot(ice_data[:,0],ice_data[:,1],linewidth=.9,color='m')
    return m 
示例#18
0
文件: grid.py 项目: xuexianwu/pyart
 def projection_proj(self):
     # Proj instance as specified by the projection attribute.
     # Raises a ValueError if the pyart_aeqd projection is specified.
     projparams = self.get_projparams()
     if projparams['proj'] == 'pyart_aeqd':
         raise ValueError(
             'Proj instance can not be made for the pyart_aeqd projection')
     if not _PYPROJ_AVAILABLE:
         raise MissingOptionalDependency(
             "Basemap is required to create a Proj instance but it " +
             "is not installed")
     proj = pyproj.Proj(projparams)
     return proj
示例#19
0
def getCoordsOfReguarGridInWrfCoords(curs, domainNum, outputLong, outputLat,
                                     nInputLong, nInputLat):
    """Calculates the WRF native coordinates of a regularly defined long, lat grid. The return values are meant
    to plug directly into the mpl_toolkits.basemap.interp function.
    
    @param curs: Psycopg2 cursor of the WinDB database
    @param domainNum: WinDB domain number
    @param outputLong: 1D Numpy array of longitudes in the regular grid
    @param outputLat: 1D Numpy array of latitudes in the regular grid
    
    @return: wrfX -> 1D WRF native longitudinal coordinate
             wrfY  -> 1D WRF native latitudinal coordinate
             regGridInWrfX -> 2D WRF native longitudinal coordinate of the regular grid longitudinal coordinates
             regGridInWrfY -> 2D WRF native latitudinal coordinate of the regular grid latitudinal coordinates
    """
    import numpy as np
    import mpl_toolkits.basemap.pyproj as pyproj

    # Get the coordinates of the WRF grid in the native WRF projection
    sql = """SELECT generate_series(x.min::int, x.max::int,(x.max::int - x.min::int)/({} - 1)) as x_coords
             FROM (SELECT min(st_x(geom)), max(st_x(geom)), resolution 
                   FROM horizgeom h, domain d
                   WHERE h.domainkey=d.key AND domainkey={}
                   GROUP BY d.resolution) x
             ORDER BY x_coords""".format(nInputLong, domainNum)
    curs.execute(sql)
    results = curs.fetchall()
    wrfX = np.array(results)[:, 0]
    sql = """SELECT generate_series(y.min::int, y.max::int,(y.max::int - y.min::int)/({} - 1)) as y_coords
             FROM (SELECT min(st_y(geom)), max(st_y(geom)), resolution 
                   FROM horizgeom h, domain d
                   WHERE h.domainkey=d.key AND domainkey={}
                   GROUP BY d.resolution) y
             ORDER BY y_coords""".format(nInputLat, domainNum)
    curs.execute(sql)
    results = curs.fetchall()
    wrfY = np.array(results)[:, 0]

    # Get the SRID of the WRF domain
    sql = """SELECT proj4text FROM spatial_ref_sys WHERE srid=(SELECT st_srid(geom) FROM horizgeom WHERE domainkey=""" + str(
        domainNum) + """ LIMIT 1)"""
    curs.execute(sql)
    wrfProj4Str = curs.fetchone()[0]

    # Change the WRF coordinates of the regular long, lat grid
    # Great tutorial on Basemap Proj4 transformations here: http://all-geo.org/volcan01010/2012/11/change-coordinates-with-pyproj/
    wrfProj4 = pyproj.Proj(wrfProj4Str)
    longGrid, latGrid = np.meshgrid(outputLong, outputLat)
    regGridInWrfX, regGridInWrfY = wrfProj4(longGrid, latGrid)

    return wrfX, wrfY, regGridInWrfX, regGridInWrfY
示例#20
0
def nearest_point_grid(grid, basemap, zvalue, yvalue, xvalue):
    '''
    Return the nearest bins to a given position.

    Parameters
    ----------
    grid : :py:class:`pyart.core.Grid` Instance
    xvalue, yvalue, zvalue : float, list of float or array of shape (npoints,)
        position in the plot coordinate system

    Returns
    -------
    index : Numpy Array
        Array of the shape (npoints, 3) containing the index in the Z, Y ,X
        axis of grid.
    '''
    if isinstance(xvalue, (list, tuple, np.ndarray)):
        xvalue = np.array((xvalue))
    else:
        xvalue = np.array((xvalue, ))
    if isinstance(yvalue, (list, tuple, np.ndarray)):
        yvalue = np.array((yvalue))
    else:
        yvalue = np.array((yvalue, ))
    if isinstance(zvalue, (list, tuple, np.ndarray)):
        zvalue = np.array((zvalue))
    else:
        zvalue = np.array((zvalue, ))

    if basemap is not None:
        from mpl_toolkits.basemap import pyproj
        proj = pyproj.Proj(proj='aeqd',
                           datum='NAD83',
                           lat_0=grid.axes['lat']['data'][0],
                           lon_0=grid.axes['lon']['data'][0])
        lat, lon = proj(xvalue, yvalue, inverse=True)
        xvalue, yvalue = basemap(lat, lon)
    zdata, zvalue = np.meshgrid(grid.axes["z_disp"]["data"], zvalue)
    z_index = np.argmin(np.abs(zdata - zvalue), axis=1)
    ydata, yvalue = np.meshgrid(grid.axes["y_disp"]["data"], yvalue)
    y_index = np.argmin(np.abs(ydata - yvalue), axis=1)
    xdata, xvalue = np.meshgrid(grid.axes["x_disp"]["data"], xvalue)
    x_index = np.argmin(np.abs(xdata - xvalue), axis=1)

    index = np.concatenate((
        z_index[np.newaxis],
        y_index[np.newaxis],
        x_index[np.newaxis],
    ),
                           axis=0)
    return index.transpose().astype(np.int)
示例#21
0
def my_project(in_east, in_north, direction):
    '''
    Sample user-defined projection and inverse projection of (lon,lat) to (x,y) 
      
      function [out_east,out_north] = my_project(in_east,in_north,direction) 
      
      DESCRIPTION:
         Define projections between geographical and Euclidean coordinates 
      
      INPUT: 
        in_east   = 1D vector containing longitude (forward) x (reverse)
        in_north  = 1D vector containing latitude  (forward) y (reverse)
        direction = ['forward' ;  'inverse']
                
      OUTPUT:
        (lon,lat) or (x,y) depending on choice of forward or reverse projection
      
      EXAMPLE USAGE
         lon,lat = my_project(x,y,'reverse') 
    '''
    #import mpl_toolkits.basemap.pyproj as pyproj
    from mpl_toolkits.basemap import pyproj
    #state_plane = pyproj.Proj(r'+proj=tmerc +datum=NAD83 +lon_0=-70d10 lat_0=42d50 k=.9999666666666667 x_0=900000 y_0=0 +to_meter=1')
    #state_plane = pyproj.Proj(r'+proj=tmerc +lat_0=42.83333333333334 +lon_0=-70.16666666666667 +k=0.9999666666666667 +x_0=900000 +y_0=0 +ellps=GRS80 +units=m +no_defs')
    state_plane = pyproj.Proj(r'+proj=tmerc +lat_0=42d50 +lon_0=-70d10 +k=0.9999666666666667 +x_0=900000 +y_0=0 +ellps=GRS80 +units=m +no_defs')
    
    wgs = pyproj.Proj(proj='latlong', datum='WGS84', ellps='WGS84')
    if direction=='forward':
    	lon = in_east
    	lat = in_north
    	x,y = pyproj.transform(wgs, state_plane, lon, lat)
    	return x, y
    else:
    	x = in_east
    	y = in_north

    	lon, lat = pyproj.transform(state_plane, wgs, x, y)
    	return lon, lat
示例#22
0
def get_proj(ifile):
    """
    MAP_PROJ - Model projection [1=Lambert, 2=polar stereographic,
                                 3=mercator, 6=lat-lon]  (required)
    TRUELAT1 - required for MAP_PROJ = 1, 2, 3 (defaults to 0 otherwise)
    TRUELAT2 - required for MAP_PROJ = 6 (defaults to 0 otherwise)
    STAND_LON - Standard longitude used in model projection (required)
    REF_LON, REF_LON - A reference longitude and latitude (required)
    KNOWNI, KNOWNJ - The I and J locations of REF_LON and REF_LAT (required)
    POLE_LAT - optional for MAP_PROJ = 6 (defaults to 90 otherwise)
    POLE_LAT - optional for MAP_PROJ = 6 (defaults to 0 otherwise)
    DX, DY - required for MAP_PROJ = 1, 2, 3 (defaults to 0 otherwise)
    LATINC, LONINC - required for MAP_PROJ = 6 (defaults to 0 otherwise)
    """

    projname = {
        1: "lambert_conformal_conic",
        2: 'polar_stereographic',
        3: 'mercator'
    }[ifile.MAP_PROJ]
    var = ifile.createVariable(projname, 'i', ())
    var.grid_mapping_name = projname
    var.earth_radius = 6370000.
    var.false_easting = 0
    var.false_northing = 0
    x0_from_cen = len(ifile.dimensions['west_east']) / 2 * ifile.DX
    y0_from_cen = len(ifile.dimensions['south_north']) / 2 * ifile.DY
    if projname == 'mercator':
        var.longitude_of_projection_origin = ifile.STAND_LON
        var.standard_parallel = ifile.TRUELAT1
    elif projname == "lambert_conformal_conic":
        var.standard_parallel = np.array([ifile.TRUELAT1, ifile.TRUELAT2])
        var.longitude_of_central_meridian = ifile.STAND_LON
        var.latitude_of_projection_origin = ifile.MOAD_CEN_LAT
    elif projname == 'polar_stereographic':
        var.straight_vertical_longitude_from_pole = ifile.STAND_LON
        var.latitude_of_projection_origin = ifile.TRUELAT1
        var.standard_parallel = ifile.MOAD_CEN_LAT

    from PseudoNetCDF.coordutil import getproj4_from_cf_var
    from mpl_toolkits.basemap import pyproj
    projstr = getproj4_from_cf_var(var)
    proj = pyproj.Proj(projstr)
    gcx, gcy = proj(ifile.CEN_LON, ifile.CEN_LAT)
    glx = gcx - x0_from_cen
    gly = gcy - y0_from_cen
    var.false_easting = -glx
    var.false_northing = -gly
    return projname
示例#23
0
    def compute_distance_grid(self):
        ''' Compute the hypo- and epi-distance for all stations.
        '''
        x_grid, y_grid = np.meshgrid(self.map_x_coord, self.map_y_coord)

        proj = pyproj.Proj(init=self.map_config['epsg'])

        for cur_station in self.compute_stations:
            stat_lon_lat = cur_station.get_lon_lat()
            stat_x, stat_y = proj(stat_lon_lat[0], stat_lon_lat[1])
            cur_station.epi_dist = np.sqrt((stat_x - x_grid)**2 +
                                           (stat_y - y_grid)**2)
            cur_station.hypo_dist = np.sqrt(cur_station.epi_dist**2 +
                                            (cur_station.z +
                                             self.hypo_depth)**2)
示例#24
0
文件: transforms.py 项目: iar/pyart
def cartesian_to_geographic(x, y, projparams):
    """
    Geographic to Cartesian coordinate transform.

    Transform a set of Cartesian/Cartographic coordinates (x, y) to a
    geographic coordinate system (lat, lon) using pyproj or a build in
    Azimuthal equidistance projection.

    Parameters
    ----------
    x, y : array-like
        Cartesian coordinates in meters unless R is defined in different units
        in the projparams parameter.
    projparams : dict or str
        Projection parameters passed to pyproj.Proj. If this parameter is a
        dictionary with a 'proj' key equal to 'pyart_aeqd' then a azimuthal
        equidistant projection will be used that is native to Py-ART and
        does not require pyproj/basemap to be installed. In this case a
        non-default value of R can be specified by setting the 'R' key to the
        desired value.

    Returns
    -------
    lon, lat : array
        Longitude and latitude of the Cartesian coordinates in degrees.

    """
    if isinstance(projparams, dict) and projparams.get('proj') == 'pyart_aeqd':
        # Use Py-ART's Azimuthal equidistance projection
        lon_0 = projparams['lon_0']
        lat_0 = projparams['lat_0']
        if 'R' in projparams:
            R = projparams['R']
            lon, lat = cartesian_to_geographic_aeqd(x, y, lon_0, lat_0, R)
        else:
            lon, lat = cartesian_to_geographic_aeqd(x, y, lon_0, lat_0)
    else:
        # Use pyproj for the projection
        # check that pyproj is available
        if not _PYPROJ_AVAILABLE:
            raise MissingOptionalDependency(
                "Basemap is required to use cartesian_to_geographic "
                "with a projection other than pyart_aeqd but it is not "
                "installed")
        proj = pyproj.Proj(projparams)
        lon, lat = proj(x, y, inverse=True)
    return lon, lat
示例#25
0
    def _convert_map_extent(self):

        # convert map units to lat / lons using pyproj
        #if self.epsg is not None:
        #    p1 = pyproj.Proj("+init=EPSG:{}".format(self.epsg))
        #else:
        p1 = pyproj.Proj(self.proj4, errcheck=True, preserve_units=True)

        extent = self.extent_proj

        self.llcrnrlon, self.llcrnrlat = p1(extent[0], extent[1], inverse=True)
        self.urcrnrlon, self.urcrnrlat = p1(extent[2], extent[3], inverse=True)

        self.Basemap_kwargs.update({'llcrnrlon': self.llcrnrlon,
                                    'llcrnrlat': self.llcrnrlat,
                                    'urcrnrlon': self.urcrnrlon,
                                    'urcrnrlat': self.urcrnrlat})
示例#26
0
    def get_map(self, **kwargs):
        from mpl_toolkits.basemap import Basemap
        #     from .conventions.ioapi import get_ioapi_sphere
        if (getattr(self.coord, "COORDTYPE", 0) in (2, 6, 7) and all([
                hasattr(self.coord, k) for k in ("P_GAM", "P_ALP", "P_BET")
        ]) and all(
            [hasattr(self, k) for k in ("XORIG", "YORIG", "XCELL", "YCELL")])):

            llcrnrx = self.XORIG
            urcrnrx = self.XORIG + self.NCOLS * self.XCELL

            llcrnry = self.YORIG
            urcrnry = self.YORIG + self.NROWS * self.YCELL

            # semi_major_axis, semi_minor_axis = get_ioapi_sphere()
            semi_major_axis, semi_minor_axis = (6370997, 6370997)
            if self.coord.COORDTYPE == 2:
                from mpl_toolkits.basemap import pyproj
                p = pyproj.Proj(proj='lcc',
                                a=semi_major_axis,
                                b=semi_major_axis,
                                lon_0=self.coord.P_GAM,
                                lat_1=self.coord.P_ALP,
                                lat_2=self.coord.P_BET,
                                lat_0=self.coord.YCENT)
                llcrnrlon, llcrnrlat = p(llcrnrx, llcrnry, inverse=True)
                urcrnrlon, urcrnrlat = p(urcrnrx, urcrnry, inverse=True)
                m = Basemap(projection='lcc',
                            rsphere=(semi_major_axis, semi_major_axis),
                            lon_0=self.coord.P_GAM,
                            lat_1=self.coord.P_ALP,
                            lat_2=self.coord.P_BET,
                            lat_0=self.coord.YCENT,
                            llcrnrlon=llcrnrlon,
                            llcrnrlat=llcrnrlat,
                            urcrnrlat=urcrnrlat,
                            urcrnrlon=urcrnrlon,
                            **kwargs)
                return m
            else:
                raise ("Only lcc")
        else:
            raise ("Only lcc")
示例#27
0
    def basemap(test):
        arc1960 = pyproj.Proj("+init=EPSG:21036")
        shp = fiona.open(
            '/Users/admin/Dropbox/CODING/PYTHON/sites/tango_with_django_project/geofiles/relions/PAs_UTM_1.shp'
        )
        bds = shp.bounds
        shp.close()
        extra = 0.01
        ll = arc1960(bds[0], bds[1], inverse=True)
        ur = arc1960(bds[2], bds[3], inverse=True)

        coords = list(chain(ll, ur))
        w, h = coords[2] - coords[0], coords[3] - coords[1]
        map = Basemap(llcrnrlon=coords[0] - extra * w,
                      llcrnrlat=coords[1] - extra + 0.01 * h,
                      urcrnrlon=coords[2] + extra * w,
                      urcrnrlat=coords[3] + extra + 0.01 * h,
                      resolution='i')
        plt.show()
        return 1
示例#28
0
    def save_png(self):
        ''' Save the result as a png image.
        '''
        # TODO: Think about a consistent method to save results, that provide a
        # single file output like the grid_2d and those that provide outputs
        # that can be combined in a spreadsheet like the value results. The
        # saving currently is not consistent. See also the todo note in
        # window_processor modul in the process method.
        from mpl_toolkits.basemap import pyproj
        import matplotlib.pyplot as plt

        map_config = self.metadata['map_config']
        proj = pyproj.Proj(init=map_config['epsg'])
        #stat_lon_lat = [x.get_lon_lat() for x in sm.compute_stations]
        #stat_lon = [x[0] for x in stat_lon_lat]
        #stat_lat = [x[1] for x in stat_lon_lat]
        #stat_x, stat_y = proj(stat_lon, stat_lat)
        plt.pcolormesh(self.x_coord, self.y_coord, self.grid, cmap='rainbow')
        plt.colorbar()
        plt.contour(self.x_coord, self.y_coord, self.grid, colors='k')
        #plt.scatter(stat_x, stat_y)
        plt.show()
def run(FILE_NAME):

    # Identify the data field.
    DATAFIELD_NAME = '500m 16 days EVI'

    if USE_GDAL:
        import gdal
        GRID_NAME = 'MODIS_Grid_16DAY_500m_VI'

        gname = 'HDF4_EOS:EOS_GRID:"{0}":{1}:{2}'.format(
            FILE_NAME, GRID_NAME, DATAFIELD_NAME)
        gdset = gdal.Open(gname)
        data = gdset.ReadAsArray().astype(np.float64)
        # Construct the grid.
        x0, xinc, _, y0, _, yinc = gdset.GetGeoTransform()
        nx, ny = (gdset.RasterXSize, gdset.RasterYSize)
        x = np.linspace(x0, x0 + xinc * nx, nx)
        y = np.linspace(y0, y0 + yinc * ny, ny)
        xv, yv = np.meshgrid(x, y)

        # In basemap, the sinusoidal projection is global, so we won't use it.
        # Instead we'll convert the grid back to lat/lons.
        sinu = pyproj.Proj("+proj=sinu +R=6371007.181 +nadgrids=@null +wktext")
        wgs84 = pyproj.Proj("+init=EPSG:4326")
        lon, lat = pyproj.transform(sinu, wgs84, xv, yv)

        # Read the attributes.
        meta = gdset.GetMetadata()
        long_name = meta['long_name']
        units = meta['units']
        _FillValue = np.float(meta['_FillValue'])
        scale_factor = np.float(meta['scale_factor'])
        valid_range = [np.float(x) for x in meta['valid_range'].split(', ')]

        del gdset
    else:
        from pyhdf.SD import SD, SDC
        hdf = SD(FILE_NAME, SDC.READ)

        # Read dataset.
        data2D = hdf.select(DATAFIELD_NAME)
        data = data2D[:, :].astype(np.double)

        # Read geolocation dataset from HDF-EOS2 dumper output.
        GEO_FILE_NAME = 'lat_MOD13A1.A2007257.h09v05.005.2007277183254.output'
        GEO_FILE_NAME = os.path.join(os.environ['HDFEOS_ZOO_DIR'],
                                     GEO_FILE_NAME)
        lat = np.genfromtxt(GEO_FILE_NAME, delimiter=',', usecols=[0])
        lat = lat.reshape(data.shape)

        GEO_FILE_NAME = 'lon_MOD13A1.A2007257.h09v05.005.2007277183254.output'
        GEO_FILE_NAME = os.path.join(os.environ['HDFEOS_ZOO_DIR'],
                                     GEO_FILE_NAME)
        lon = np.genfromtxt(GEO_FILE_NAME, delimiter=',', usecols=[0])
        lon = lon.reshape(data.shape)

        # Read attributes.
        attrs = data2D.attributes(full=1)
        lna = attrs["long_name"]
        long_name = lna[0]
        vra = attrs["valid_range"]
        valid_range = vra[0]
        fva = attrs["_FillValue"]
        _FillValue = fva[0]
        sfa = attrs["scale_factor"]
        scale_factor = sfa[0]
        ua = attrs["units"]
        units = ua[0]

    invalid = np.logical_or(data > valid_range[1], data < valid_range[0])
    invalid = np.logical_or(invalid, data == _FillValue)
    data[invalid] = np.nan
    data = data / scale_factor
    data = np.ma.masked_array(data, np.isnan(data))

    m = Basemap(projection='cyl',
                resolution='i',
                llcrnrlat=25,
                urcrnrlat=45,
                llcrnrlon=-120,
                urcrnrlon=-90)
    m.drawcoastlines(linewidth=0.5)
    m.drawparallels(np.arange(20, 50, 10), labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(-125, -75, 10), labels=[0, 0, 0, 1])
    m.pcolormesh(lon[::2], lat[::2], data[::2], latlon=True)
    cb = m.colorbar()
    cb.set_label(units)

    basename = os.path.basename(FILE_NAME)
    plt.title('{0}\n{1}'.format(basename, long_name))
    fig = plt.gcf()
    # plt.show()
    pngfile = "{0}.py.png".format(basename)
    fig.savefig(pngfile)
示例#30
0
parser.add_argument('stl_filename', nargs='?',help='stl filname (if not used, stl_filename = dfxbasename.stl)',default='')
parser.add_argument('--proj', nargs=1, metavar=('projname'), default = (''), help='name of the projection (ex EPSG:32646 (UTM46N)) if a projection is considered')

args = parser.parse_args()

if args.stl_filename == '':
   args.stl_filename = args.dxf_filename[0:-4]+'.stl'

fid = open(args.dxf_filename)
fout = open(args.stl_filename,'w')

if args.proj!='':
   print "projecting the nodes coordinates"
   import mpl_toolkits.basemap.pyproj as pyproj
   sProj = "+init=%s" %args.proj[0]
   myproj=pyproj.Proj(sProj)
else:
   print "no projection carried out"

while fid.readline():  #0
	sId = fid.readline().strip() #eg 3DFACE
	
	if not sId in ["SECTION","POINT","3DFACE","ENDSEC"]:
		print sId
		print("unknown format file")
		break

	options[sId]();