def get_goes_ccrs(goes_ds): return ccrs.Geostationary( satellite_height=goes_ds.goes_imager_projection. perspective_point_height, central_longitude=goes_ds.goes_imager_projection. longitude_of_projection_origin, sweep_axis=goes_ds.goes_imager_projection.sweep_angle_axis)
def test_viz(self): (gf.ocean + gf.land + gf.ocean * gf.land * gf.coastline * gf.borders).options( 'Feature', projection=crs.Geostationary(), global_extent=True, height=325).cols(3)
def geos_image(): """ Return a specific SEVIRI image by retrieving it from a github gist URL. Returns ------- img : numpy array The pixels of the image in a numpy array. img_proj : cartopy CRS The rectangular coordinate system of the image. img_extent : tuple of floats The extent of the image ``(x0, y0, x1, y1)`` referenced in the ``img_proj`` coordinate system. origin : str The origin of the image to be passed through to matplotlib's imshow. """ filename="20190921_MSG4.jpg" with open(filename, 'rb') as fin: img_handle = BytesIO(fin.read()) img = plt.imread(img_handle, format="jpeg") img_proj = ccrs.Geostationary(satellite_height=31086000) #satellite_height=35786000 # img_extent = (-371200, 371200, -371200, 371200) img_extent = (-5500000, 5500000, -5500000, 5500000) return img, img_proj, img_extent, 'upper'
def proj_GOES16(): geostationaryProjParams_GOES16 = { 'central_longitude': -75.0, 'satellite_height': 35786023.0, 'sweep_axis': 'x' } return ccrs.Geostationary(**geostationaryProjParams_GOES16)
def project_cartopy(self): """ Reproject the satellite image on an equirectangular map using the cartopy library """ import cartopy.crs as ccrs from cartopy.img_transform import warp_array self.load_image() width = self.outwidth height = self.outheight buf, _extent = \ warp_array(self.data, source_proj=ccrs.Geostationary( central_longitude=self.longitude, satellite_height=35785831.0 ), target_proj=ccrs.PlateCarree(), target_res=(width, height)) dataResampledImage = self.rescale(buf.data) dataResampledImage = self.polar_clouds(dataResampledImage) weight = self.get_weight() result = np.array([dataResampledImage, weight]) return result
def setUp(self): self.latitude_of_projection_origin = 0.0 self.longitude_of_projection_origin = 0.0 self.perspective_point_height = 35785831.0 self.sweep_angle_axis = 'y' self.false_easting = 0.0 self.false_northing = 0.0 self.semi_major_axis = 6377563.396 self.semi_minor_axis = 6356256.909 self.ellipsoid = GeogCS(self.semi_major_axis, self.semi_minor_axis) self.globe = ccrs.Globe(semimajor_axis=self.semi_major_axis, semiminor_axis=self.semi_minor_axis, ellipse=None) # Actual and expected coord system can be re-used for # Geostationary.test_crs_creation and test_projection_creation. self.expected = ccrs.Geostationary( central_longitude=self.longitude_of_projection_origin, satellite_height=self.perspective_point_height, false_easting=self.false_easting, false_northing=self.false_northing, globe=self.globe, sweep_axis=self.sweep_angle_axis) self.geo_cs = Geostationary(self.latitude_of_projection_origin, self.longitude_of_projection_origin, self.perspective_point_height, self.sweep_angle_axis, self.false_easting, self.false_northing, self.ellipsoid)
def test_projection_creation(self): res = self.vp_cs.as_cartopy_projection() globe = ccrs.Globe(semimajor_axis=self.semi_major_axis, semiminor_axis=self.semi_minor_axis, ellipse=None) expected = ccrs.Geostationary(self.longitude_of_projection_origin, self.perspective_point_height, globe=globe) self.assertEqual(res, expected)
def main(): img, globe, crs, extent = vesta_image() projection = ccrs.Geostationary(globe=globe) ax = plt.axes(projection=projection) ax.imshow(img, transform=crs, extent=extent) plt.gcf().text(.075, .012, "Image credit: NASA/JPL-Caltech/UCLA/MPS/DLR/IDA/PSI", bbox={'facecolor': 'w', 'edgecolor': 'k'}) plt.show()
def goes_proj(data): import cartopy.crs as crs from cartopy.crs import Globe globe=Globe(datum=None,ellipse='WGS84', semimajor_axis=data['semi_major_axis'], semiminor_axis=data['semi_minor_axis']) proj=crs.Geostationary(central_longitude=data['lon0'], satellite_height=data['h'], globe=globe, sweep_axis='y') return proj
def as_cartopy_crs(self): globe = self._ellipsoid_to_globe(self.ellipsoid, ccrs.Globe()) return ccrs.Geostationary( central_longitude=self.longitude_of_projection_origin, satellite_height=self.perspective_point_height, false_easting=self.false_easting, false_northing=self.false_northing, globe=globe, sweep_axis=self.sweep_angle_axis)
def test_default(self): geos = ccrs.Geostationary() expected = [ '+ellps=WGS84', 'h=35785831', 'lat_0=0', 'lon_0=0.0', 'no_defs', 'proj=geos', 'units=m', 'x_0=0', 'y_0=0' ] self.check_proj4_params(geos, expected) assert_almost_equal(geos.boundary.bounds, (-5372584.78443894, -5372584.78443894, 5372584.78443894, 5372584.78443894), decimal=4)
def as_cartopy_crs(self): if self.ellipsoid is not None: globe = self.ellipsoid.as_cartopy_globe() else: globe = ccrs.Globe() return ccrs.Geostationary( central_longitude=self.longitude_of_projection_origin, satellite_height=self.perspective_point_height, false_easting=self.false_easting, false_northing=self.false_northing, globe=globe)
def test_sweep(self): geos = ccrs.Geostationary(sweep_axis='x') other_args = { 'ellps=WGS84', 'h=35785831', 'lat_0=0.0', 'lon_0=0.0', 'sweep=x', 'x_0=0', 'y_0=0' } check_proj4_params(self.expected_proj_name, geos, other_args) pt = geos.transform_point(-60, 25, ccrs.PlateCarree()) assert_almost_equal(pt, (-4529521.6442, 2437479.4195), decimal=4)
def main(): # We define the semimajor and semiminor axes, but must also tell the # globe not to use the WGS84 ellipse, which is its default behaviour. eccentric_globe = ccrs.Globe(semimajor_axis=1000, semiminor_axis=500, ellipse=None) geostationary = ccrs.Geostationary(globe=eccentric_globe) ax = plt.axes(projection=geostationary) ax.stock_img() ax.coastlines() plt.show()
def test_sweep(self): geos = ccrs.Geostationary(sweep_axis='x') expected = [ '+ellps=WGS84', 'h=35785831', 'lat_0=0.0', 'lon_0=0.0', 'no_defs', 'proj=geos', 'sweep=x', 'units=m', 'x_0=0', 'y_0=0' ] check_proj4_params(geos, expected) pt = geos.transform_point(-60, 25, ccrs.PlateCarree()) assert_almost_equal(pt, (-4529521.6442, 2437479.4195), decimal=4)
def basic_map(data): fig, ax = plt.subplots(subplot_kw={'projection': ccrs.Geostationary()}) lons, lats = np.meshgrid(data['lon'], data['lat']) im1 = ax.pcolormesh(lons, lats, data, transform=ccrs.PlateCarree(), cmap='inferno') ax.coastlines() ax.set_title("Pincus Map") fig.colorbar(im1) fig.savefig(home + "/Desktop/my_fancy_map.png")
def test_eccentric_globe(self): globe = ccrs.Globe(semimajor_axis=10000, semiminor_axis=5000, ellipse=None) geos = ccrs.Geostationary(satellite_height=50000, globe=globe) expected = [ '+a=10000', 'b=5000', 'h=50000', 'lat_0=0', 'lon_0=0.0', 'no_defs', 'proj=geos', 'units=m', 'x_0=0', 'y_0=0' ] self.check_proj4_params(geos, expected) assert_almost_equal(geos.boundary.bounds, (-8257.4338, -4532.9943, 8257.4338, 4532.9943), decimal=4)
def main(): img, globe, crs, extent = vesta_image() projection = ccrs.Geostationary(globe=globe) fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection=projection) ax.imshow(img, transform=crs, extent=extent) fig.text(.075, .012, "Image credit: NASA/JPL-Caltech/UCLA/MPS/DLR/IDA/PSI", bbox={ 'facecolor': 'w', 'edgecolor': 'k' }) plt.show()
def plot_goes(data): import cartopy.crs as crs from cartopy.crs import Globe globe=Globe(datum=None,ellipse='WGS84', semimajor_axis=data['semi_major_axis'], semiminor_axis=data['semi_minor_axis']) proj=crs.Geostationary(central_longitude=data['lon0'], satellite_height=data['h'], globe=globe, sweep_axis='y') ax = plt.subplot(1,1, projection=proj) ax.set_xlim(data['xlim']) ax.set_ylim(data['ylim']) im = ax.imshow(data['array'],origin='lower', extent=img_extent,transform=proj ) return ax
def plot_msgradfd_geo(): """MSG Cloud Top Temperature Full Disc.""" import cartopy.crs as ccrs SUBTYPE = 'MSGRADFD' ELEMENT = 'CLOD_TOP_TMPR' req = mdbx.Query( SUBTYPE, ELEMENT, area=['67N', '67S', '67W', '67E'], # must specify start='TODAY-1/1000Z', stop='TODAY-1/1230Z', keep=True) return req.plot( ELEMENT, use_cartopy=True, projection=ccrs.Geostationary(), delta=(.5, .5), cb_on=True, describe_data=True)
def test_eastings(self): geos = ccrs.Geostationary( false_easting=5000000, false_northing=-125000, ) expected = [ '+ellps=WGS84', 'h=35785831', 'lat_0=0', 'lon_0=0.0', 'no_defs', 'proj=geos', 'units=m', 'x_0=5000000', 'y_0=-125000' ] self.check_proj4_params(geos, expected) assert_almost_equal(geos.boundary.bounds, (-372584.78443894, -5497584.78443894, 10372584.78443894, 5247584.78443894), decimal=4)
def test_alpha_2d_warp(): # tests that both image and alpha arrays (if alpha is 2D) are warped plt_crs = ccrs.Geostationary(central_longitude=-155.) fig = plt.figure(figsize=(5, 5)) ax = fig.add_subplot(1, 1, 1, projection=plt_crs) latlon_crs = ccrs.PlateCarree() coords = [-162., -148., 17.5, 23.] ax.set_extent(coords, crs=latlon_crs) fake_data = np.zeros([100, 100]) fake_alphas = np.zeros(fake_data.shape) image = ax.imshow(fake_data, extent=coords, transform=latlon_crs, alpha=fake_alphas) plt.close() image_data = image.get_array() image_alpha = image.get_alpha() assert image_data.shape == image_alpha.shape
def img_proj_merc(fname, res_name, resolution, height): import cartopy.crs as ccrs from cartopy.img_transform import warp_array import numpy as np import PIL.Image img = PIL.Image.open(fname) result_array, extent = warp_array( np.array(img), source_proj=ccrs.Geostationary(satellite_height=height), target_proj=ccrs.Mercator(), target_res=resolution) result = PIL.Image.fromarray(result_array) result.save(res_name) return ()
def make_geo(attrs_dict, globe): """Handle geostationary projection.""" attr_mapping = [('satellite_height', 'perspective_point_height'), ('sweep_axis', 'sweep_angle_axis')] kwargs = CFProjection.build_projection_kwargs(attrs_dict, attr_mapping) # CartoPy can't handle central latitude for Geostationary (nor should it) # Just remove it if it's 0. if not kwargs.get('central_latitude'): kwargs.pop('central_latitude', None) # If sweep_angle_axis is not present, we should look for fixed_angle_axis and adjust if 'sweep_axis' not in kwargs: kwargs['sweep_axis'] = 'x' if attrs_dict[ 'fixed_angle_axis'] == 'y' else 'y' return ccrs.Geostationary(globe=globe, **kwargs)
def plot_mask(mask, colorbar=False, title=None, vmin=0., vmax=1.): plt.figure(figsize=(10, 10)) ax = plt.axes(projection=ccrs.Geostationary(central_longitude=140.0)) mask.plot.pcolormesh(ax=ax, transform=ccrs.PlateCarree(), vmin=vmin, vmax=vmax, x='longitude', y='latitude', add_colorbar=colorbar) ax.coastlines(color='w') if title is None: #date = str(time[0]).split(':00.')[0].replace('T',' ') date = str(time[0]) ax.set_title('HW cloud mask, ' + date) else: ax.set_title(title) plt.show()
def set_projection_attribute_and_scale_coords(ds): gp = ds.goes_imager_projection globe = ccrs.Globe( ellipse="sphere", semimajor_axis=gp.semi_major_axis, semiminor_axis=gp.semi_minor_axis, ) img_proj = ccrs.Geostationary( satellite_height=gp.perspective_point_height, central_longitude=gp.longitude_of_projection_origin, globe=globe, ) ds.attrs["crs"] = img_proj # coordinates are scaled by satellite height in image ds.coords["x"] = ds.x * gp.perspective_point_height ds.coords["y"] = ds.y * gp.perspective_point_height return ds
def add_projection(ds): proj_info = ds.goes_imager_projection globe = ccrs.Globe( semimajor_axis=proj_info.semi_major_axis.item(), semiminor_axis=proj_info.semi_minor_axis.item(), inverse_flattening=proj_info.inverse_flattening.item(), ) crs = ccrs.Geostationary( globe=globe, satellite_height=proj_info.perspective_point_height.item(), central_longitude=proj_info.longitude_of_projection_origin.item(), sweep_axis=proj_info.sweep_angle_axis, ) return ds.assign_coords(crs=crs).update({ "x": ds.x * proj_info.perspective_point_height.item(), "y": ds.y * proj_info.perspective_point_height.item(), })
def main(): # Edge length in pixels out_size_px = 7500 source_path = 'c:/temp/world.200411.3x21600x10800.jpg' # Get satellite details output_filename, longitude = get_satellite_details() # Allow large images to be loaded PIL.Image.MAX_IMAGE_PIXELS = 933120000 # Perform geostationary projection of source image fig = plt.figure(figsize=(1, 1), dpi=out_size_px) ax = fig.add_subplot( projection=ccrs.Geostationary(longitude, satellite_height=35786000)) # Disable full disc border ax.outline_patch.set_linewidth(0) print( f'Projecting and plotting image; longitude: {longitude}; output file: {output_filename}' ) file = open(source_path, "rb") img_handle = BytesIO(file.read()) img = plt.imread(img_handle, "jpg") img_proj = ccrs.PlateCarree() ax.imshow(img, transform=img_proj, origin='upper', regrid_shape=out_size_px) plt.savefig(output_filename, dpi=out_size_px, facecolor='black', edgecolor='black', transparent=True)
def as_cartopy_crs(self): """Return this projection as a Cartopy CRS instance.""" import iris.exceptions as iexcept import cartopy.crs as ccrs proj = ccrs.Geostationary(central_longitude=self.sub_lon, satellite_height=self.satellite_height, sweep_axis=self.sweep, globe=ccrs.Globe(semimajor_axis=self.req, semiminor_axis=self.rpol, ellipse=None)) # Calculate extent proj.extent = None # (x0, x1, y0, y1) try: proj.extent = ( self.iris_cube().coord('projection_x_coordinate').points[-1], self.iris_cube().coord('projection_x_coordinate').points[0], self.iris_cube().coord('projection_y_coordinate').points[0], self.iris_cube().coord('projection_y_coordinate').points[-1] ) except iexcept.CoordinateNotFoundError as err: log.warning(err) return proj
def plot_satellite_projection(): """Stored for future use.""" ax = plt.axes(projection=ccrs.Geostationary(central_longitude=0.0, satellite_height=35785831, false_easting=0, false_northing=0, globe=None)) ax.coastlines() ax.add_feature(cp.feature.OCEAN, zorder=0) ax.add_feature(cp.feature.LAND, zorder=0, edgecolor='black') ax.set_extent([-15, 25, 30, 50]) plt.subplots_adjust(left=0.01, bottom=0.1, right=0.9, top=0.9, wspace=0.1, hspace=0.1) plt.savefig(os.path.join(save_dir, "Domain_SAT.png"), bbox_inches='tight') ax.set_xticklabels([3, 5, 6, 7]) return