nansat package
Subpackages
- nansat.mappers package
- Submodules
- nansat.mappers.envisat module
- nansat.mappers.globcolour module
- nansat.mappers.hdf4_mapper module
- nansat.mappers.mapper_aapp_l1b module
- nansat.mappers.mapper_aapp_l1c module
- nansat.mappers.mapper_amsr2_l1r module
- nansat.mappers.mapper_amsr2_l3 module
- nansat.mappers.mapper_amsre_uham_leadfraction module
- nansat.mappers.mapper_arome module
- nansat.mappers.mapper_asar module
- nansat.mappers.mapper_ascat module
- nansat.mappers.mapper_aster_l1a module
- nansat.mappers.mapper_aster_l1b module
- nansat.mappers.mapper_case2reg module
- nansat.mappers.mapper_cmems module
- nansat.mappers.mapper_csks module
- nansat.mappers.mapper_ecmwf_metno module
- nansat.mappers.mapper_emodnet module
- nansat.mappers.mapper_generic module
- nansat.mappers.mapper_geostationary module
- nansat.mappers.mapper_globcolour_l3b module
- nansat.mappers.mapper_globcolour_l3m module
- nansat.mappers.mapper_goci_l1 module
- nansat.mappers.mapper_hirlam module
- nansat.mappers.mapper_hirlam_wind_netcdf module
- nansat.mappers.mapper_kmss module
- nansat.mappers.mapper_landsat module
- nansat.mappers.mapper_meris_l1 module
- nansat.mappers.mapper_meris_l2 module
- nansat.mappers.mapper_metno_hires_seaice module
- nansat.mappers.mapper_metno_local_hires_seaice module
- nansat.mappers.mapper_mod44w module
- nansat.mappers.mapper_modis_l1 module
- nansat.mappers.mapper_ncep module
- nansat.mappers.mapper_ncep_wind module
- nansat.mappers.mapper_ncep_wind_online module
- nansat.mappers.mapper_netcdf_cf module
- nansat.mappers.mapper_netcdf_cf_sentinel1 module
- nansat.mappers.mapper_nora10_local_vpv module
- nansat.mappers.mapper_obpg_l2 module
- nansat.mappers.mapper_obpg_l2_nc module
- nansat.mappers.mapper_obpg_l3 module
- nansat.mappers.mapper_ocean_productivity module
- nansat.mappers.mapper_opendap_arome module
- nansat.mappers.mapper_opendap_globcurrent module
- nansat.mappers.mapper_opendap_globcurrent_thredds module
- nansat.mappers.mapper_opendap_mywave module
- nansat.mappers.mapper_opendap_occci module
- nansat.mappers.mapper_opendap_osisaf module
- nansat.mappers.mapper_opendap_ostia module
- nansat.mappers.mapper_opendap_sentinel1 module
- nansat.mappers.mapper_opendap_sentinel2 module
- nansat.mappers.mapper_opendap_siwtacsst module
- nansat.mappers.mapper_opendap_sstcci module
- nansat.mappers.mapper_pathfinder52 module
- nansat.mappers.mapper_quikscat module
- nansat.mappers.mapper_radarsat2 module
- nansat.mappers.mapper_sentinel1_l1 module
- nansat.mappers.mapper_sentinel1_l2 module
- nansat.mappers.mapper_topography module
- nansat.mappers.mapper_viirs_l1 module
- nansat.mappers.obpg module
- nansat.mappers.opendap module
Opendap
Opendap.P2S
Opendap.test_mapper()
Opendap.get_dataset()
Opendap.get_geospatial_variable_names()
Opendap.get_dataset_time()
Opendap.get_layer_datetime()
Opendap.get_metaitem()
Opendap.create_vrt()
Opendap.create_metadict()
Opendap.get_time_coverage_resolution()
Opendap.get_shape()
Opendap.get_geotransform()
- nansat.mappers.scatterometers module
- nansat.mappers.sentinel1 module
- Module contents
- nansat.tests package
- Subpackages
- Submodules
- nansat.tests.nansat_test_base module
- nansat.tests.nansat_test_data module
- nansat.tests.test_domain module
DomainTest
DomainTest.setUp()
DomainTest.test_dont_init_from_invalid_combination()
DomainTest.test_init_from_GDALDataset()
DomainTest.test_init_from_GDALDataset_and_srs()
DomainTest.test_dont_init_if_gdal_AutoCreateWarpedVRT_fails()
DomainTest.test_init_from_srs_and_ext_te()
DomainTest.test_init_from_srs_and_ext_lle()
DomainTest.test_init_lonlat()
DomainTest.test_init_from_lonlat()
DomainTest.test_init_from_lonlat_no_gcps()
DomainTest.test_repr()
DomainTest.test_write_kml()
DomainTest.test_get_geolocation_grids_from_GDAL_transformer()
DomainTest.test_get_geolocation_grids_from_geolocationArray()
DomainTest.test_convert_extentDic()
DomainTest.test_add_to_dict()
DomainTest.test_validate_ts_tr()
DomainTest.test_validate_te_lle()
DomainTest.test_check_size()
DomainTest.test_gen_regexp()
DomainTest.test_create_extent_dict()
DomainTest.test_get_border()
DomainTest.test_compound_row_col_vectors()
DomainTest.test_get_row_col_vector()
DomainTest.test_get_border_wkt()
DomainTest.test_get_border_geometry()
DomainTest.test_border_geojson()
DomainTest.test_overlaps_intersects_and_contains()
DomainTest.test_contains()
DomainTest.test_get_border_postgis()
DomainTest.test_get_corners()
DomainTest.test_get_min_max_lon_lat()
DomainTest.test_get_pixelsize_meters()
DomainTest.test_get_geotransform()
DomainTest.test_transform_tr()
DomainTest.test_transform_ts2()
DomainTest.test_transform_points()
DomainTest.test_transform_points_inverse()
DomainTest.test_transform_points_dstsrs()
DomainTest.test_azimuth_y()
DomainTest.test_shape()
DomainTest.test_reproject_gcps()
DomainTest.test_reproject_gcps_auto()
DomainTest.test_intersects()
DomainTest.test_overlaps()
DomainTest.test_get_border_dateline()
- nansat.tests.test_exporter module
ExporterTest
ExporterTest.test_export__with_nan_values()
ExporterTest.test_geolocation_of_exportedNC_vs_original()
ExporterTest.test_special_characters_in_exported_metadata()
ExporterTest.test_time_coverage_metadata_of_exported_equals_original()
ExporterTest.test_export_netcdf()
ExporterTest.test_export_gcps_to_netcdf()
ExporterTest.test_export_gcps_complex_to_netcdf()
ExporterTest.test_export_gtiff()
ExporterTest.test_export_band()
ExporterTest.test_export_band_by_name()
ExporterTest.test_reproject_and_export_band()
ExporterTest.test_export_selected_bands()
ExporterTest.test_export_option()
ExporterTest.test_export2thredds_arctic_long_lat()
ExporterTest.test_dont_export2thredds_gcps()
ExporterTest.test_export2thredds_longlat_list()
ExporterTest.test_export2thredds_longlat_dict()
ExporterTest.test_export_netcdf_complex_remove_meta()
ExporterTest.test_export_netcdf_arctic()
ExporterTest.test_export_netcdf_arctic_hardcopy()
ExporterTest.test_export_add_geoloc()
ExporterTest.test_export2thredds_rmmetadata()
TestExporter__export2thredds
- nansat.tests.test_figure module
FigureTest
FigureTest.test_init_array()
FigureTest.test_get_auto_ticks_number()
FigureTest.test_get_auto_ticks_vector()
FigureTest.test_add_latlon_grids_auto()
FigureTest.test_add_latlon_grids_number()
FigureTest.test_add_latlon_grids_list()
FigureTest.test_get_tick_index_from_grid()
FigureTest.test_apply_logarithm()
FigureTest.test_make_transparent_color()
- nansat.tests.test_geolocation module
- nansat.tests.test_nansat module
NansatTest
NansatTest.test_open_gcps()
NansatTest.test_that_only_mappers_with_mapper_in_the_module_name_are_imported()
NansatTest.test_get_time_coverage_start_end()
NansatTest.test_from_domain_array()
NansatTest.test_from_domain_nansat()
NansatTest.test_add_band()
NansatTest.test_add_band_twice()
NansatTest.test_add_bands()
NansatTest.test_add_bands_no_parameter()
NansatTest.test_add_subvrts_only_to_one_nansat()
NansatTest.test_bands()
NansatTest.test_has_band_if_name_matches()
NansatTest.test_has_band_if_standard_name_matches()
NansatTest.test_write_fig_tif()
NansatTest.test_resize_by_pixelsize()
NansatTest.test_resize_by_factor()
NansatTest.test_resize_by_width()
NansatTest.test_resize_by_height()
NansatTest.test_resize_resize()
NansatTest.test_resize_complex_alg_average()
NansatTest.test_resize_complex_alg0()
NansatTest.test_resize_complex_alg1()
NansatTest.test_resize_complex_alg2()
NansatTest.test_resize_complex_alg3()
NansatTest.test_resize_complex_alg4()
NansatTest.test_get_GDALRasterBand()
NansatTest.test_get_GDALRasterBand_if_band_id_is_given()
NansatTest.test_list_bands_true()
NansatTest.test_list_bands_false()
NansatTest.test_reproject_domain()
NansatTest.test_reproject_domain_if_dst_domain_is_given()
NansatTest.test_reproject_domain_if_resample_alg_is_given()
NansatTest.test_reproject_domain_if_source_and_destination_domain_span_entire_lons()
NansatTest.test_reproject_domain_if_tps_is_given()
NansatTest.test_reproject_of_complex()
NansatTest.test_add_band_and_reproject()
NansatTest.test_reproject_no_addmask()
NansatTest.test_reproject_stere()
NansatTest.test_reproject_gcps()
NansatTest.test_reproject_gcps_on_repro_gcps()
NansatTest.test_reproject_gcps_resize()
NansatTest.test_undo()
NansatTest.test_write_figure()
NansatTest.test_write_figure_band()
NansatTest.test_write_figure_clim()
NansatTest.test_write_figure_legend()
NansatTest.test_write_figure_logo()
NansatTest.test_write_geotiffimage()
NansatTest.test_write_geotiffimage_if_band_id_is_given()
NansatTest.test_get_metadata()
NansatTest.test_get_metadata_key()
NansatTest.test_get_metadata_wrong_key()
NansatTest.test_get_metadata_band_id()
NansatTest.test_set_metadata()
NansatTest.test_set_metadata_band_id()
NansatTest.test_get_band_number()
NansatTest.test_get_transect()
NansatTest.test_get_transect_outside()
NansatTest.test_get_transect_wrong_points()
NansatTest.test_get_transect_wrong_band()
NansatTest.test_get_transect_pixlin()
NansatTest.test_get_transect_data()
NansatTest.test_digitize_points()
NansatTest.test_crop()
NansatTest.test_crop_gcpproj()
NansatTest.test_crop_complex()
NansatTest.test_crop_no_gcps_arctic()
NansatTest.test_crop_lonlat()
NansatTest.test_crop_outside()
NansatTest.test_watermask()
NansatTest.test_watermask_fail_if_mod44path_is_wrong()
NansatTest.test_watermask_fail_if_mod44path_not_exist()
NansatTest.test_init_no_arguments()
NansatTest.test_get_item_basic_expressions()
NansatTest.test_get_item_inf_expressions()
NansatTest.test_repr_basic()
NansatTest.test_getitem()
NansatTest.test_crop_interactive()
NansatTest.test_extend()
NansatTest.test_open_no_mapper()
NansatTest.test_get_metadata_unescape()
NansatTest.test_reproject_pure_geolocation()
- nansat.tests.test_node module
- nansat.tests.test_nsr module
- nansat.tests.test_pixelfunctions module
- nansat.tests.test_pointbrowser module
- nansat.tests.test_tools module
ToolsTest
ToolsTest.setUp()
ToolsTest.test_distance2coast_source_not_exists_envvar()
ToolsTest.test_distance2coast_source_not_exists_attribute()
ToolsTest.test_distance2coast_integration()
ToolsTest.test_warning()
ToolsTest.test_get_domain_map()
ToolsTest.test_get_domain_map_no_cartopy()
ToolsTest.test_save_domain_map()
- nansat.tests.test_vrt module
VRTTest
VRTTest.nsr_wkt
VRTTest.test_init()
VRTTest.test_del()
VRTTest.test_from_gdal_dataset()
VRTTest.test_init_from_gdal_dataset()
VRTTest.test_from_dataset_params()
VRTTest.test_from_array()
VRTTest.test_from_lonlat()
VRTTest.test_from_lonlat_no_gcps()
VRTTest.test_copy_empty_vrt()
VRTTest.test_copy_vrt_with_band()
VRTTest.test_copy_vrt_pixel_func()
VRTTest.test_copy_geolocation()
VRTTest.test_export()
VRTTest.test_create_band()
VRTTest.test_make_source_bands_xml()
VRTTest.test_set_add_band_options()
VRTTest.test_remove_geotransform()
VRTTest.test_set_geotransform_for_resize()
VRTTest.test_set_gcps_geolocation_geotransform_with_geolocation()
VRTTest.test_set_gcps_geolocation_geotransform_with_gcps()
VRTTest.test_set_gcps_geolocation_geotransform_with_geotransform()
VRTTest.test_update_warped_vrt_xml()
VRTTest.test_set_fake_gcps_empty()
VRTTest.test_set_fake_gcps()
VRTTest.test_get_dst_band_data_type()
VRTTest.test_create_band_name_no_wkv()
VRTTest.test_create_band_name_wkv()
VRTTest.test_create_band_name_existing_name()
VRTTest.test_create_band_name_wkv_and_name()
VRTTest.test_leave_few_bands()
VRTTest.test_find_complex_band()
VRTTest.test_split_complex_bands()
VRTTest.test_create_geolocation_bands()
VRTTest.test_fix_band_metadata()
VRTTest.test_fix_global_metadata()
VRTTest.test_hardcopy_bands()
VRTTest.test_get_projection_dataset()
VRTTest.test_get_projection_gcps()
VRTTest.test_get_projection_geolocation()
VRTTest.test_get_projection_raises_NansatProjectionError()
VRTTest.test_repr()
VRTTest.test_add_swath_mask_band()
VRTTest.test_remove_strings_in_metadata_keys()
VRTTest.test_super_vrt_of_geolocation_bands()
VRTTest.test_get_shifted_vrt()
VRTTest.test_get_super_vrt()
VRTTest.test_get_super_vrt_geolocation()
VRTTest.test_get_super_vrt_and_copy()
VRTTest.test_get_sub_vrt0()
VRTTest.test_get_sub_vrt3()
VRTTest.test_get_sub_vrt_steps_0()
VRTTest.test_transform_points()
VRTTest.test_make_filename()
VRTTest.test_transform_coordinates_list()
VRTTest.test_transform_coordinates_1d_array()
VRTTest.test_transform_coordinates_2d_array()
VRTTest.test_reproject_gcps()
- Module contents
- Subpackages
Submodules
nansat.domain module
- class nansat.domain.Domain(srs=None, ext=None, ds=None, **kwargs)
Bases:
object
Container for geographical reference of a raster
A Domain object describes all attributes of geographical reference of a raster:
width and height (number of pixels)
pixel size (e.g. in decimal degrees or in meters)
relation between pixel/line coordinates and geographical coordinates (e.g. a linear relation)
type of data projection (e.g. geographical or stereographic)
- Parameters:
srs (PROJ4 or EPSG or WKT or NSR or osr.SpatialReference()) – Input parameter for nansat.NSR()
ext (string) – some gdalwarp options + additional options [http://www.gdal.org/gdalwarp.html] Specifies extent, resolution / size Available options: ((‘-te’ or ‘-lle’) and (‘-tr’ or ‘-ts’)) (e.g. ‘-lle -10 30 55 60 -ts 1000 1000’ or ‘-te 100 2000 300 10000 -tr 300 200’) -tr resolutionx resolutiony -ts sizex sizey -te xmin ymin xmax ymax -lle lonmin latmin lonmax latmax
ds (GDAL dataset)
Examples
>>> d = Domain(srs, ext) #size, extent and spatial reference is given by strings >>> d = Domain(ds=GDALDataset) #size, extent copied from input GDAL dataset >>> d = Domain(srs, ds=GDALDataset) # spatial reference is given by srs, but size and extent is determined from input GDAL dataset
Notes
The core of Domain is a GDAL Dataset. It has no bands, but only georeference information: rasterXsize, rasterYsize, GeoTransform and Projection or GCPs, etc. which fully describe dimentions and spatial reference of the grid.
There are three ways to store geo-reference in a GDAL dataset:
Using GeoTransfrom to define linear relationship between raster pixel/line and geographical X/Y coordinates
Using GCPs (set of Ground Control Points) to define non-linear relationship between pixel/line and X/Y
Using Geolocation Array - full grids of X/Y coordinates for each pixel of a raster
The relation between X/Y coordinates of the raster and latitude/longitude coordinates is defined by projection type and projection parameters. These pieces of information are therefore stored in Domain:
Type and parameters of projection +
GeoTransform, or
GCPs, or
GeolocationArrays
Domain has methods for basic operations with georeference information:
creating georeference from input options;
fetching corner, border or full grids of X/Y coordinates;
making map of the georeferenced grid in a PNG or KML file;
and some more…
The main attribute of Domain is a VRT object self.vrt. Nansat inherits from Domain and adds bands to self.vrt
:raises NansatProjectionError : occurs when Projection() is empty: despite it is required for creating extentDic. :raises OptionError : occures when the arguments are not proper.:
- OUTPUT_SEPARATOR = '----------------------------------------\n'
- KML_BASE = '<?xml version="1.0" encoding="UTF-8"?>\n <kml xmlns="http://www.opengis.net/kml/2.2"\n xmlns:gx="http://www.google.com/kml/ext/2.2"\n xmlns:kml="http://www.opengis.net/kml/2.2"\n xmlns:atom="http://www.w3.org/2005/Atom">\n {content}\n </kml>'
- logger = None
- name = None
- vrt = None
- classmethod from_lonlat(lon, lat, add_gcps=True)
Create Domain object from input longitudes, latitudes arrays
- Parameters:
lon (numpy.ndarray) – longitudes
lat (numpy.ndarray) – latitudes
add_gcps (bool) – Add GCPs from lon/lat arrays.
- Returns:
d
- Return type:
Examples
>>> lon, lat = np.meshgrid(range(10), range(10)) >>> d1 = Domain.from_lonlat(lon, lat) >>> d2 = Domain.from_lonlat(lon, lat, add_gcps=False) # add only geolocation arrays
- write_kml(xmlFileName=None, kmlFileName=None)
Write KML file with domains
Convert XML-file with domains into KML-file for GoogleEarth or write KML-file with the current Domain
- Parameters:
xmlFileName (string, optional) – Name of the XML-file to convert. If only this value is given - kmlFileName=xmlFileName+’.kml’
kmlFileName (string, optional) – Name of the KML-file to generate from the current Domain
- write_kml_image(kmlFileName, kmlFigureName=None)
Create KML file for already projected image
Write Domain Image into KML-file for GoogleEarth
- Parameters:
kmlFileName (str) – Name of the KML-file to generate from the current Domain
kmlFigureName (str) – Name of the projected image stored in .png format
Examples
>>> n.undo(100) # cancel previous reprojection >>> lons, lats = n.get_corners() # Get corners of the image and the pixel resolution >>> srsString = '+proj=latlong +datum=WGS84 +ellps=WGS84 +no_defs' >>> extentString = '-lle %f %f %f %f -ts 3000 3000' % (min(lons), min(lats), max(lons), max(lats)) >>> d = Domain(srs=srsString, ext=extentString) # Create Domain with stereographic projection, corner coordinates and resolution 1000m >>> n.reproject(d) >>> n.write_figure(filename=figureName, bands=[3], clim=[0,0.15], cmapName='gray', transparency=0) >>> n.write_kml_image(kmlFileName=oPath + filename + '.kml', kmlFigureName=figureName) # 6.
- get_geolocation_grids(stepSize=1, dst_srs=None)
Get longitude and latitude grids representing the full data grid
If GEOLOCATION is not present in the self.vrt.dataset then grids are generated by converting pixel/line of each pixel into lat/lon If GEOLOCATION is present in the self.vrt.dataset then grids are read from the geolocation bands.
- Parameters:
stepSize (int) – Reduction factor if output is desired on a reduced grid size
- Returns:
longitude (numpy array) – grid with longitudes
latitude (numpy array) – grid with latitudes
- get_border(n_points=10, fix_lon=True, **kwargs)
Generate two vectors with values of lat/lon for the border of domain
- Parameters:
n_points (int, optional) – Number of points on each border
fix_lon (bool) – Convert longitudes to positive numbers when Domain crosses dateline?
- Returns:
lonVec, latVec – vectors with lon/lat values for each point at the border
- Return type:
lists
- get_border_wkt(*args, **kwargs)
Creates string with WKT representation of the border polygon
- Returns:
WKTPolygon – string with WKT representation of the border polygon
- Return type:
string
- get_border_geometry(*args, **kwargs)
Get OGR Geometry of the border Polygon
- Returns:
OGR Geometry
- Return type:
Polygon
- get_border_geojson(*args, **kwargs)
Create border of the Polygon in GeoJson format
- Returns:
the Polygon border in GeoJson format
- Return type:
str
- overlaps(anotherDomain)
Checks if this Domain overlaps another Domain
- Returns:
overlaps – True if Domains overlaps, False otherwise
- Return type:
bool
- intersects(anotherDomain)
Checks if this Domain intersects another Domain
- Returns:
intersects – True if Domains intersects, False otherwise
- Return type:
bool
- contains(anotherDomain)
Checks if this Domain fully covers another Domain
- Returns:
contains – True if this Domain fully covers another Domain, False otherwise
- Return type:
bool
- get_border_postgis(**kwargs)
Get PostGIS formatted string of the border Polygon
- Returns:
‘PolygonFromText(PolygonWKT)’
- Return type:
str
- get_corners()
Get coordinates of corners of the Domain
- Returns:
lonVec, latVec – vectors with lon/lat values for each corner
- Return type:
lists
- get_min_max_lon_lat()
Get minimum and maximum of longitude and latitude geolocation grids
- Returns:
min_lon, max_lon, min_lat, max_lat, – min/max lon/lat values for the Domain
- Return type:
float
- get_pixelsize_meters()
Returns the pixelsize (deltaX, deltaY) of the domain
For projected domains, the exact result which is constant over the domain is returned. For geographic (lon-lat) projections, or domains with no geotransform, the haversine formula is used to calculate the pixel size in the center of the domain.
- Returns:
delta_x, delta_y – pixel size in X and Y directions given in meters
- Return type:
float
- transform_points(colVector, rowVector, DstToSrc=0, dst_srs=None)
Transform given lists of X,Y coordinates into lon/lat or inverse
- Parameters:
colVector (lists) – X and Y coordinates in pixel/line or lon/lat coordinate system
DstToSrc (0 or 1) –
0 - forward transform (pix/line => lon/lat)
1 - inverse transformation
dst_srs (NSR) – destination spatial reference
- Returns:
X, Y – X and Y coordinates in lon/lat or pixel/line coordinate system
- Return type:
lists
- azimuth_y(reductionFactor=1)
Calculate the angle of each pixel position vector with respect to the Y-axis (azimuth).
In general, azimuth is the angle from a reference vector (e.g., the direction to North) to the chosen position vector. The azimuth increases clockwise from direction to North. http://en.wikipedia.org/wiki/Azimuth
- Parameters:
reductionFactor (integer) – factor by which the size of the output array is reduced
- Returns:
azimuth – Values of azimuth in degrees in range 0 - 360
- Return type:
numpy array
- shape()
Return Numpy-like shape of Domain object (ySize, xSize)
- Returns:
shape – Numpy-like shape of Domain object (ySize, xSize)
- Return type:
tuple of two INT
- reproject_gcps(srs_string='')
Reproject all GCPs to a new spatial reference system
Necessary before warping an image if the given GCPs are in a coordinate system which has a singularity in (or near) the destination area (e.g. poles for lonlat GCPs)
- Parameters:
srs_string (string) – SRS given as Proj4 string. If empty ‘+proj=stere’ is used
Notes
Reprojects all GCPs to new SRS and updates GCPProjection
nansat.exceptions module
- exception nansat.exceptions.NansatProjectionError
Bases:
Exception
Cannot get the projection
- exception nansat.exceptions.NansatGDALError
Bases:
Exception
Error from GDAL
- exception nansat.exceptions.NansatReadError
Bases:
Exception
Exception if a file cannot be read with Nansat
- exception nansat.exceptions.NansatGeolocationError
Bases:
Exception
Exception if geolocation is wrong (e.g., all lat/lon values are 0)
- exception nansat.exceptions.NansatMissingProjectionError
Bases:
Exception
Exception raised if no (sub-) dataset has projection
- exception nansat.exceptions.WrongMapperError
Bases:
Exception
Error for handling data that does not fit a given mapper
nansat.exporter module
- class nansat.exporter.Exporter
Bases:
object
Abstract class for export functions
- DEFAULT_INSTITUTE = 'NERSC'
- DEFAULT_SOURCE = 'satellite remote sensing'
- UNWANTED_METADATA = ['dataType', 'SourceFilename', 'SourceBand', '_Unsigned', 'FillValue', '_FillValue', 'type', 'scale', 'offset', 'NETCDF_VARNAME']
- export(filename='', bands=None, rm_metadata=None, add_geolocation=True, driver='netCDF', options='FORMAT=NC4', hardcopy=False)
Export Nansat object into netCDF or GTiff file
- Parameters:
filename (str) – output file name
bands (list (default=None)) – Specify band numbers to export. If None, all bands are exported.
rm_metadata (list) – metadata names for removal before export. e.g. [‘name’, ‘colormap’, ‘source’, ‘sourceBands’]
add_geolocation (bool) – add geolocation array datasets to exported file?
driver (str) – Name of GDAL driver (format)
options (str or list (default: 'FORMAT=NC4' for NetCDF 4) – file format) GDAL export options in format of: ‘OPT=VAL’, or [‘OPT1=VAL1’, ‘OP2=’VAL2’] See also http://www.gdal.org/frmt_netcdf.html
hardcopy (bool) – Evaluate all bands just before export?
- Returns:
filename
- Return type:
netCDF or GTiff
Notes
CreateCopy fails in case the band name has special characters, e.g. the slash in ‘HH/VV’.
Metadata strings with special characters are escaped with XML/HTML encoding.
Examples
# export all the bands into a netDCF 3 file
>>> n.export(netcdfile)
# export all bands into a GeoTiff
>>> n.export(driver='GTiff')
- static rename_attributes(filename)
Rename global attributes to get rid of the “GDAL_”-string added by gdal.
- static rename_variables(filename)
Rename variable names to reflect the name attribute of the variable’s metadata.
- Parameters:
filename (str) – NetCDF file name
- export2thredds(filename, bands=None, metadata=None, mask_name=None, no_mask_value=64, rm_metadata=None, time=None, created=None, zlib=True)
Export data into a netCDF formatted for THREDDS server
- Parameters:
filename (str) – output file name
bands (dict) –
- {‘band_name’: {‘type’’>i1’,
’scale’ : 0.1, ‘offset’ : 1000, ‘metaKey1’ : ‘meta value 1’, ‘metaKey2’ : ‘meta value 2’}}
dictionary sets parameters for band creation
’type’ - string representation of data type in the output band
’scale’ - sets scale_factor and applies scaling
’offset’ - sets ‘scale_offset and applies offsetting
other entries (e.g. ‘units’: ‘K’) set other metadata
metadata (dict) – Glbal metadata to add
mask_name (str) – if data include a mask band: give the mask name. if None: no mask is added
no_mask_value (int) – Non-masked value is 64.
rm_metadata (list) – unwanted metadata names which will be removed
time (list with datetime objects) – aqcuisition time of original data. That value will be in time dim
created (datetime) – date of creation. Will be in metadata ‘created’
zlib (bool) – compress output netCDF files?
Note
Nansat object (self) has to be projected (with valid GeoTransform and valid Spatial reference information) but not wth GCPs
Examples
# create THREDDS formatted netcdf file with all bands and time variable
>>> n.export2thredds(filename)
# export only one band and add global metadata
>>> n.export2thredds(filename, {'L_469': {'description': 'example'}})
# export several bands and modify type, scale and offset
>>> bands = {'L_645' : {'type': '>i2', 'scale': 0.1, 'offset': 0}, 'L_555' : {'type': '>i2', 'scale': 0.1, 'offset': 0}}
>>> n.export2thredds(filename, bands)
nansat.figure module
- class nansat.figure.Figure(nparray, **kwargs)
Bases:
object
Perform operations with graphical files: create, append legend, save.
Figure instance is created in the Nansat.write_figure method. The methods below are applied consequently in order to generate a figure from one or three bands, estimate min/max, apply logarithmic scaling, convert to uint8, append legend, save to a file
Modifies: self.sizeX, self.sizeY (int), width and height of the image
Modifies: self.pilImg (PIL image), figure
Modifies: self.pilImgLegend (PIL image)
Note
If pilImgLegend is None, legend is not added to the figure. If it is replaced, pilImgLegend includes text string, color-bar, longName and units.
- Parameters:
array (numpy array (2D or 3D)) – dataset from Nansat
cmin (number (int ot float) or [number, number, number]) – 0, minimum value of varibale in the matrix to be shown
cmax (number (int ot float) or [number, number, number]) – 1, minimum value of varibale in the matrix to be shown
gamma (float, >0) – 2, coefficient for tone curve udjustment
subsetArraySize (int) – 100000, size of the subset array which is used to get histogram
numOfColor (int) – 250, number of colors for use of the palette. 254th is black and 255th is white.
cmapName (string) – ‘jet’, name of Matplotlib colormaps see –> http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps
ratio (float, [0 1]) – 1.0, ratio of pixels which are used to write the figure
numOfTicks (int) – 5, number of ticks on a colorbar
titleString (string) – ‘’, title of legend (1st line)
caption (string) – ‘’, caption of the legend (2nd line, e.g. long name and units)
fontRatio (positive float) – 1, factor for changing the fontSize.
fontSize (int) – 12, size of the font of title, caption and ticks. If not given, fontSize is calculated using fontRatio: fontSize = height / 45 * fontRatio. fontSize has priority over fontRatio
logarithm (boolean, defult = False) – If True, tone curve is used to convert pixel values. If False, linear.
legend (boolean, default = False) – if True, information as textString, colorbar, longName and units are added in the figure.
mask_array (2D numpy array, int, the shape should be equal to) – array.shape. If given, this array is used for masking land, clouds, etc on the output image. Value of the array are indices. LUT from mask_lut is used for coloring upon this indices.
mask_lut (dictionary) –
Look-Up-Table with colors for masking land, clouds etc. Used tgether with mask_array: {0, [0,0,0], 1, [100,100,100], 2: [150,150,150], 3: [0,0,255]} index
0 - will have black color
1 - dark gray
2 - light gray
3 - blue
logoFileName (string) – name of the file with logo
logoLocation (list of two int, default = [0,0]) – X and Y offset of the image If positive - offset is from left, upper edge If Negative - from right, lower edge Offset is calculated from the entire image legend inclusive
logoSize (list of two int) – desired X,Y size of logo. If None - original size is used
latGrid (numpy array) – full size array with latitudes. For adding lat/lon grid lines
lonGrid (numpy array) – full size array with longitudes. For adding lat/lon grid lines
nGridLines (int) – number of lat/lon grid lines to show
latlonLabels (int) – number of lat/lon labels to show along each side.
transparency (int) – transparency of the image background(mask), set for PIL alpha mask in Figure.save()
default (None)
LEGEND_HEIGHT (float, [0 1]) – 0.1, legend height relative to image height
CBAR_HEIGHTMIN (int) – 5, minimum colorbar height, pixels
CBAR_HEIGHT (float, [0 1]) – 0.15, colorbar height relative to image height
CBAR_WIDTH (float [0 1]) – 0.8, colorbar width relative to legend width
CBAR_LOCATION_X (float [0 1]) – 0.1, colorbar offset X relative to legend width
CBAR_LOCATION_Y (float [0 1]) – 0.5, colorbar offset Y relative to legend height
CBTICK_LOC_ADJUST_X (int) – 5, colorbar tick label offset X, pixels
CBTICK_LOC_ADJUST_Y (int) – 3, colorbar tick label offset Y, pixels
CAPTION_LOCATION_X (float, [0 1]) – 0.1, caption offset X relative to legend width
CAPTION_LOCATION_Y (float, [0 1]) – 0.1, caption offset Y relative to legend height
TITLE_LOCATION_X (float, [0 1]) – 0.1, title offset X relative to legend width
TITLE_LOCATION_Y – 0.3, title offset Y relative to legend height
DEFAULT_EXTENSION (string) – ‘.png’
- cmin = [0.0]
- cmax = [1.0]
- gamma = 2.0
- subsetArraySize = 100000
- numOfColor = 250
- cmapName = 'jet'
- ratio = 1.0
- numOfTicks = 5
- titleString = ''
- caption = ''
- fontRatio = 1
- fontSize = None
- logarithm = False
- legend = False
- mask_array = None
- mask_lut = None
- logoFileName = None
- logoLocation = [0, 0]
- logoSize = None
- latGrid = None
- lonGrid = None
- lonTicks = 5
- latTicks = 5
- transparency = None
- LEGEND_HEIGHT = 0.1
- CBAR_HEIGHTMIN = 5
- CBAR_HEIGHT = 0.15
- CBAR_WIDTH = 0.8
- CBAR_LOCATION_X = 0.1
- CBAR_LOCATION_Y = 0.5
- CBTICK_LOC_ADJUST_X = 5
- CBTICK_LOC_ADJUST_Y = 3
- CAPTION_LOCATION_X = 0.1
- CAPTION_LOCATION_Y = 0.25
- TITLE_LOCATION_X = 0.1
- TITLE_LOCATION_Y = 0.05
- DEFAULT_EXTENSION = '.png'
- palette = None
- pilImg = None
- pilImgLegend = None
- extensionList = ['png', 'PNG', 'tif', 'TIF', 'bmp', 'BMP', 'jpg', 'JPG', 'jpeg', 'JPEG']
- array = None
- apply_logarithm(**kwargs)
Apply a tone curve to the array
After the normalization of the values from 0 to 1, logarithm is applied Then the values are converted to the normal scale.
Modifies: self.array (numpy array)
- Parameters:
**kwargs (dict) – Any of Figure parameters
- apply_mask(**kwargs)
Apply mask for coloring land, clouds, etc
If mask_array and mask_lut are provided as input parameters. The pixels in self.array which have index equal to mask_lut key in mask_array will have color equal to mask_lut value.
Modifies: self.array (numpy array)
Note
apply_mask should be called only after convert_palettesize (i.e. to uint8 data)
- Parameters:
**kwargs (dict) – Any of Figure parameters
- add_logo(**kwargs)
Insert logo into the PIL image
Read logo from file as PIL. Resize to the given size. Pan using the given location. Paste into pilImg.
Modifies: self.pilImg (PIL image)
- Parameters:
**kwargs (dict) – Any of Figure parameters
- add_latlon_grids(**kwargs)
Add lat/lon grid lines into the PIL image
Compute step of the grid. Make matrices with binarized lat/lon. Find edge (make line). Convert to mask. Add mask to PIL
Modifies: self.pilImg (PIL image), added lat/lon grid lines
- Parameters:
latGrid (numpy array) – array with values of latitudes
lonGrid (numpy array) – array with values of longitudes
lonTicks (int or list) – number of lines to draw or locations of gridlines
latTicks (int or list) – number of lines to draw or locations of gridlines
**kwargs (dict) – any of Figure parameters
- add_latlon_labels(**kwargs)
Add lat/lon labels along upper and left side
Compute step of lables. Get lat/lon for these labels from latGrid, lonGrid Print lables to PIL in white.
Modifies: self.pilImg (PIL image), added lat/lon labels
- Parameters:
latGrid (numpy array) – array with values of latitudes
lonGrid (numpy array) – array with values of longitudes
lonTicks (int or list) – number of lines to draw or locations of gridlines
latTicks (int or list) – number of lines to draw or locations of gridlines
**kwargs (dict) – Any of Figure parameters
- clim_from_histogram(**kwargs)
Estimate min and max pixel values from histogram
if ratio=1.0, simply the minimum and maximum values are returned. if 0 < ratio < 1.0, get the histogram of the pixel values. Then get rid of (1.0-ratio)/2 from the both sides and return the minimum and maximum values.
- Parameters:
**kwargs (dict) – Any of Figure parameters
- Returns:
clim – minimum and maximum pixel values for each band
- Return type:
numpy array 2D ((3x2) or (1x2))
- clip(**kwargs)
Convert self.array to values between cmin and cmax
if pixel value < cmin, replaced to cmin.
if pixel value > cmax, replaced to cmax.
Modifies: self.array (numpy array)
Modifies: self.cmin, self.cmax : allowed min/max values
- Parameters:
**kwargs (dict) – Any of Figure parameters
- convert_palettesize(**kwargs)
Convert self.array to palette color size in uint8
Modifies: self.array (numpy array)
- Parameters:
**kwargs (dict) – Any of Figure parameters
- create_legend(**kwargs)
self.legend is replaced from None to PIL image
PIL image includes colorbar, caption, and titleString.
Modifies: self.legend (PIL image)
- Parameters:
**kwargs (dict) – Any of Figure parameters
- create_pilImage(**kwargs)
self.create_pilImage is replaced from None to PIL image
If three images are given, create a image with RGB mode. if self.pilImgLegend is not None, it is pasted.
If one image is given, create a image with P(palette) mode. if self.pilImgLegend is not None, self.array is extended before create the pilImag and then paste pilImgLegend onto it.
Modifies: self.pilImg (PIL image), PIL image with / without the legend
Modifies: self.array (replace to None)
- Parameters:
**kwargs (dict) – Any of Figure parameters
- process(**kwargs)
Do all common operations for preparation of a figure for saving
Modify default values of parameters by the provided ones (if any)
Clip to min/max
Apply logarithm if required
Convert data to uint8
Create palette
Apply mask for colouring land, clouds, etc if required
Create legend if required
Create PIL image
Add logo if required
Modifies: self.d
Modifies: self.array
Modifies: self.palette
Modifies: self.pilImgLegend
Modifies: self.pilImg
- Parameters:
**kwargs (dict) – Any of Figure parameters
- save(fileName, **kwargs)
Save self.pilImg to a physical file
If given extension is JPG, convert the image mode from Palette to RGB.
Modifies: self.pilImg (None)
- Parameters:
fileName (string) – name of outputfile
**kwargs (dict) – Any of Figure parameters
nansat.geolocation module
- class nansat.geolocation.Geolocation(x_vrt, y_vrt, **kwargs)
Bases:
object
Container for GEOLOCATION data
Keeps references to bands with X and Y coordinates, offset and step of pixel and line. All information is stored in dictionary self.data
Instance of Geolocation is used in VRT and ususaly created in a Mapper.
- data = None
- x_vrt = None
- y_vrt = None
- classmethod from_dataset(dataset)
Create geolocation from GDAL dataset :param dataset: input dataset to copy Geolocation metadata from :type dataset: gdal.Dataset
- classmethod from_filenames(x_filename, y_filename, **kwargs)
Create geolocation from names of files with geolocation :param x_filename: name of file for X-dataset :type x_filename: str :param y_filename: name of file for Y-dataset :type y_filename: str :param **kwargs: parameters for self._init_data() :type **kwargs: dict
- get_geolocation_grids()
Read values of geolocation grids
nansat.nansat module
- class nansat.nansat.Nansat(filename='', mapper='', log_level=30, **kwargs)
-
Container for geospatial data. Performs all high-level operations.
n = Nansat(filename) opens the file with satellite or model data for reading, adds scientific metadata to bands, and prepares the data for further handling.
- Parameters:
filename (str) – uri of the input file or OpeNDAP datastream
mapper (str) – name of the mapper from nansat/mappers dir. E.g. ‘sentinel1_l1’, ‘asar’, ‘hirlam’, ‘meris_l1’, ‘meris_l2’, etc.
log_level (int) – Level of logging. See: http://docs.python.org/howto/logging.html
kwargs (additional arguments for mappers)
Examples
>>> n1 = Nansat(filename) >>> n2 = Nansat(sentinel1_filename, mapper='sentinel1_l1') >>> array1 = n1[1] >>> array2 = n2['sigma0_HV']
Notes
The instance of Nansat class (the object <n>) contains information about geographical reference of the data (e.g raster size, pixel resolution, type of projection, etc) and about bands with values of geophysical variables (e.g. water leaving radiance, normalized radar cross section, chlrophyll concentraion, etc). The object <n> has methods for high-level operations with data. E.g.: * reading data from file (Nansat.__getitem__); * visualization (Nansat.write_figure); * changing geographical reference (Nansat.reproject); * exporting (Nansat.export) * and much more…
Nansat inherits from Domain (container of geo-reference information) Nansat uses instance of VRT (wraper around GDAL VRT-files) Nansat uses instance of Figure (collection of methods for visualization)
- logger = None
- filename = None
- name = None
- path = None
- mapper = None
- classmethod from_domain(domain, array=None, parameters=None, log_level=30)
Create Nansat object from input Domain [and array with data]
- Parameters:
domain (Domain) – Defines spatial reference system and geographical extent.
array (numpy NDarray) – Data for the first band. Shape must correspond to shape of <domain>
parameters (dict) – Metadata for the first band. May contain ‘name’, ‘wkv’ and other keys.
log_level (int) – Level of logging.
- vrt = None
- add_band(array, parameters=None, nomem=False)
Add band from numpy array with metadata.
Create VRT object which contains VRT and RAW binary file and append it to self.vrt.band_vrts
- Parameters:
array (ndarray) – new band data. Shape should be equal to shape
parameters (dict) – band metadata: wkv, name, etc. (or for several bands)
nomem (bool) – saves the vrt to a tempfile on disk?
Notes
Creates VRT object with VRT-file and RAW-file. Adds band to the self.vrt.
Examples
>>> n.add_band(array, {'name': 'new_data'}) # add new band and metadata, keep in memory >>> n.add_band(array, nomem=True) # add new band, keep on disk
- add_bands(arrays, parameters=None, nomem=False)
Add bands from numpy arrays with metadata.
Create VRT object which contains VRT and RAW binary file and append it to self.vrt.band_vrts
- Parameters:
arrays (list of ndarrays) – new band data. Shape should be equal to shape
parameters (list of dict) – band metadata: wkv, name, etc. (or for several bands)
nomem (bool) – saves the vrt to a tempfile on disk?
Notes
Creates VRT object with VRT-file and RAW-file. Adds band to the self.vrt.
Examples
>>> n.add_bands([array1, array2]) # add new bands, keep in memory
- bands()
Make a dictionary with all metadata from all bands
- Returns:
b – key = N, value = dict with all band metadata
- Return type:
dictionary
- has_band(band)
Check if self has band with name <band> :param band: name or standard_name of the band to check :type band: str
- Return type:
True/False if band exists or not
- resize(factor=None, width=None, height=None, pixelsize=None, resample_alg=-1)
Proportional resize of the dataset.
The dataset is resized as (x_size*factor, y_size*factor) If desired width, height or pixelsize is specified, the scaling factor is calculated accordingly. If GCPs are given in a dataset, they are also rewritten.
- Parameters:
factor (float, optional, default=1) –
Scaling factor for width and height
> 1 means increasing domain size
< 1 means decreasing domain size
width (int, optional) – Desired new width in pixels
height (int, optional) – Desired new height in pixels
pixelsize (float, optional) – Desired new pixelsize in meters (approximate). A factor is calculated from ratio of the current pixelsize to the desired pixelsize.
resample_alg (int (GDALResampleAlg), optional) –
-1 : Average (default),
0 : NearestNeighbour
1 : Bilinear,
2 : Cubic,
3 : CubicSpline,
4 : Lancoz
Notes
- self.vrt.datasetVRT dataset of VRT object
raster size are modified to downscaled size. If GCPs are given in the dataset, they are also overwritten.
- get_GDALRasterBand(band_id=1)
Get a GDALRasterBand of a given Nansat object
If str is given find corresponding band number If int is given check if band with this number exists. Get a GDALRasterBand from vrt.
- Parameters:
band_id (int or str) –
if int - a band number of the band to fetch
if str band_id = {‘name’: band_id}
- Return type:
GDAL RasterBand
Example
>>> b = n.get_GDALRasterBand(1) >>> b = n.get_GDALRasterBand('sigma0')
- list_bands(do_print=True)
Show band information of the given Nansat object
Show serial number, longName, name and all parameters for each band in the metadata of the given Nansat object.
- Parameters:
do_print (boolean) – print on screen?
- Returns:
outString – formatted string with bands info
- Return type:
String
- reproject(dst_domain=None, resample_alg=0, block_size=None, tps=None, skip_gcps=1, addmask=True, **kwargs)
Change projection of the object based on the given Domain
Create superVRT from self.vrt with AutoCreateWarpedVRT() using projection from the dst_domain. Modify XML content of the warped vrt using the Domain parameters. Generate warpedVRT and replace self.vrt with warpedVRT. If current object spans from 0 to 360 and dst_domain is west of 0, the object is shifted by 180 westwards.
- Parameters:
dst_domain (domain) – destination Domain where projection and resolution are set
resample_alg (int (GDALResampleAlg)) –
0 : NearestNeighbour
1 : Bilinear
2 : Cubic,
3 : CubicSpline
4 : Lancoz
block_size (int) – size of blocks for resampling. Large value decrease speed but increase accuracy at the edge
tps (bool) – Apply Thin Spline Transformation if source or destination has GCPs Usage of TPS can also be triggered by setting self.vrt.tps=True before calling to reproject. This options has priority over self.vrt.tps
skip_gcps (int) – Using TPS can be very slow if the number of GCPs are large. If this parameter is given, only every [skip_gcp] GCP is used, improving calculation time at the cost of accuracy. If not given explicitly, ‘skip_gcps’ is fetched from the metadata of self, or from dst_domain (as set by mapper or user). [defaults to 1 if not specified, i.e. using all GCPs]
addmask (bool) – If True, add band ‘swathmask’. 1 - valid data, 0 no-data. This band is used to replace no-data values with np.nan
Notes
self.vrt : VRT object with dataset replaced to warpedVRT dataset Integer data is returnd by integer. Round off to decimal place. If you do not want to round off, convert the data types to GDT_Float32, GDT_Float64, or GDT_CFloat32.
See also
- undo(steps=1)
Undo reproject, resize, add_band or crop of Nansat object
Restore the self.vrt from self.vrt.vrt
- Parameters:
steps (int) – How many steps back to undo
Notes
Modifies self.vrt
- watermask(mod44path=None, dst_domain=None, **kwargs)
Create numpy array with watermask (water=1, land=0)
250 meters resolution watermask from MODIS 44W Product: http://www.glcf.umd.edu/data/watermask/
Watermask is stored as tiles in TIF(LZW) format and a VRT file All files are stored in one directory. A tarball with compressed TIF and VRT files should be additionally downloaded from the Nansat documentation page: http://nansat.readthedocs.io/en/latest/source/features.html#differentiating-between-land-and-water
- The method :
Gets the directory either from input parameter or from environment variable MOD44WPATH Open Nansat object from the VRT file Reprojects the watermask onto the current object using reproject() or reproject_on_jcps() Returns the reprojected Nansat object
- Parameters:
mod44path (string) – path with MOD44W Products and a VRT file
dst_domain (Domain) – destination domain other than self
tps (Bool) – Use Thin Spline Transformation in reprojection of watermask? See also Nansat.reproject()
skip_gcps (int) – Factor to reduce the number of GCPs by and increase speed See also Nansat.reproject()
- Returns:
watermask
- Return type:
Nansat object with water mask in current projection
- write_figure(filename='', bands=1, clim=None, addDate=False, array_modfunc=None, **kwargs)
Save a raster band to a figure in graphical format.
Get numpy array from the band(s) and band information specified either by given band number or band id. – If three bands are given, merge them and create PIL image. – If one band is given, create indexed image Create Figure object and: Adjust the array brightness and contrast using the given min/max or histogram. Apply logarithmic scaling of color tone. Generate and append legend. Save the PIL output image in PNG or any other graphical format. If the filename extension is ‘tif’, the figure file is converted to GeoTiff
- Parameters:
filename (str) – Output file name. if one of extensions ‘png’, ‘PNG’, ‘tif’, ‘TIF’, ‘bmp’, ‘BMP’, ‘jpg’, ‘JPG’, ‘jpeg’, ‘JPEG’ is included, specified file is created. otherwise, ‘png’ file is created.
bands (integer or string or list (elements are integer or string),) – default = 1 the size of the list has to be 1 or 3. if the size is 3, RGB image is created based on the three bands. Then the first element is Red, the second is Green, and the third is Blue.
clim (list with two elements or 'hist' to specify range of colormap) – None (default) : min/max values are fetched from WKV, fallback-‘hist’ [min, max] : min and max are numbers, or [[min, min, min], [max, max, max]]: three bands used ‘hist’ : a histogram is used to calculate min and max values
addDate (boolean) – False (default) : no date will be aded to the caption True : the first time of the object will be added to the caption
array_modfunc (None) – None (default) : figure created using array in provided band function : figure created using array modified by provided function
**kwargs (parameters for Figure().)
Notes
if filename is specified, creates image file
- Returns:
Figure – filename extension define format (default format is png)
- Return type:
Figure object
Example
>>> n.write_figure('test.jpg') # write indexed image >>> n.write_figure('test_rgb_hist.jpg', clim='hist', bands=[1, 2, 3]) # RGB image >>> n.write_figure('r09_log3_leg.jpg', logarithm=True, legend=True, gamma=3, titleString='Title', fontSize=30, numOfTicks=15) # add legend >>> n.write_figure(filename='transparent.png', bands=[3], mask_array=wmArray, mask_lut={0: [0,0,0]}, clim=[0,0.15], cmapName='gray', transparency=[0,0,0]) # write transparent image
- write_geotiffimage(filename, band_id=1)
Writes an 8-bit GeoTiff image for a given band.
The colormap is fetched from the metadata item ‘colormap’. Fallback colormap is ‘gray’.
Color limits are fetched from the metadata item ‘minmax’. If ‘minmax’ is not specified, min and max of the raster data is used.
The method can be replaced by using nansat.write_figure(). However, write_figure uses PIL, which does not allow Tiff compression. This gives much larger files.
- Parameters:
filename (str)
band_id (int or str)
- property time_coverage_start
- property time_coverage_end
- get_metadata(key=None, band_id=None, unescape=True)
Get metadata from self.vrt.dataset
- Parameters:
key (str) – name of the metadata key. If not givem all metadata is returned
band_id (int or str) – number or name of band to get metadata from. If not given, global metadata is returned
unescape (bool) – Replace ‘"’, ‘&’, ‘<’ and ‘>’ with these symbols “ & < > ?
- Returns:
metadata (str) – string with metadata if key is given and found
metadata (dict) – dictionary with all metadata if key is not given
- Raises:
ValueError, if key is not found –
- set_metadata(key='', value='', band_id=None)
Set metadata to self.vrt.dataset
- Parameters:
key (string or dictionary with strings) – name of the metadata, or dictionary with metadata names, values
value (string) – value of metadata
band_id (int or str) – number or name of band Without : global metadata is set
Notes
self.vrt.dataset : sets metadata in GDAL current dataset
- get_band_number(band_id)
Return absolute band number
Check if given band_id is valid Return absolute number of the band in the VRT
- Parameters:
band_id (int or str or dict) –
if int : checks if such band exists and returns band_id
if str : finds band with coresponding name
if dict : finds first band with given metadata
- Returns:
absolute band number
- Return type:
int
- get_transect(points, bands, lonlat=True, smooth_radius=0, smooth_function=numpy.nanmedian, data=None, cornersonly=False)
Get values from transect from given vector of poins
- Parameters:
points (2xN list or array, N (number of points) >= 1) – coordinates [[x1, x2, y2], [y1, y2, y3]]
bands (list of int or string) – elements of the list are band number or band Name
lonlat (bool) – If the points in lat/lon, then True. If the points in pixel/line, then False.
smooth_radius (int) – If smootRadius is greater than 0, smooth every transect pixel as the median or mean value in a circule with radius equal to the given number.
smooth_function (func) – function for averaging values collected within smooth radius
data (ndarray) – alternative array with data to take values from
- Returns:
transect
- Return type:
numpy record array
- digitize_points(band=1, **kwargs)
Get coordinates of interactively digitized points
- Parameters:
band (int or str) – ID of Nansat band
**kwargs (keyword arguments for imshow)
- Returns:
points – list of 2xN arrays of points to be used in Nansat.get_transect()
- Return type:
list
- crop_interactive(band=1, maxwidth=1000, **kwargs)
Interactively select boundary and crop Nansat object
- Parameters:
band (int or str) – id of the band to show for interactive selection of boundaries
maxwidth (int) – large input data is downscaled to <maxwidth>
**kwargs (keyword arguments for imshow)
Notes
- self.vrtVRT
superVRT is created with modified SrcRect and DstRect
- Returns:
extent – x_offset - X offset in the original dataset y_offset - Y offset in the original dataset x_size - width of the new dataset y_size - height of the new dataset
- Return type:
(x_offset, y_offset, x_size, y_size)
Examples
>>> extent = n.crop_interactive(band=1) # crop a subimage interactively
- crop_lonlat(lonlim, latlim)
Crop Nansat object to fit into given longitude/latitude limit
- Parameters:
lonlim (list of 2 float) – min/max of longitude
latlim (list of 2 float) – min/max of latitude
Notes
- self.vrtVRT
crops vrt to size that corresponds to lon/lat limits
- Returns:
extent – x_offset - X offset in the original dataset y_offset - Y offset in the original dataset x_size - width of the new dataset y_size - height of the new dataset
- Return type:
(x_offset, y_offset, x_size, y_size)
Examples
>>> extent = n.crop(lonlim=[-10,10], latlim=[-20,20]) # crop for given lon/lat limits
- crop(x_offset, y_offset, x_size, y_size, allow_larger=False)
Crop Nansat object
Create superVRT, modify the Source Rectangle (SrcRect) and Destination Rectangle (DstRect) tags in the VRT file for each band in order to take only part of the original image, create new GCPs or new GeoTransform for the cropped object.
- Parameters:
x_offset (int) – pixel offset of subimage
y_offset (int) – line offset of subimage
x_size (int) – width in pixels of subimage
y_size (int) – height in pizels of subimage
allow_larger (bool) – Allow resulting extent to be larger than the original image?
Notes
self.vrt : super-VRT is created with modified SrcRect and DstRect
- Returns:
extent – x_offset - X offset in the original dataset y_offset - Y offset in the original dataset x_size - width of the new dataset y_size - height of the new dataset
- Return type:
(x_offset, y_offset, x_size, y_size)
Examples
>>> extent = n.crop(10, 20, 100, 200)
- extend(left=0, right=0, top=0, bottom=0)
Extend domain from four sides
- Parameters:
left (int) – number of pixels to add from left side
right (int) – number of pixels to add from right side
top (int) – number of pixels to add from top side
bottom (int) – number of pixels to add from bottom side
Notes
Canges self.vrt by adding nexgative offset or setting size to be large that original size.
nansat.node module
- class nansat.node.Node(tag, value=None, **attributes)
Bases:
object
Rapidly assemble XML using minimal coding.
By Bruce Eckel, (c)2006 MindView Inc. www.MindView.net Permission is granted to use or modify without payment as long as this copyright notice is retained.
Everything is a Node, and each Node can either have a value or subnodes. Subnodes can be appended to Nodes using ‘+=’, and a group of Nodes can be strung together using ‘+’.
Create a node containing a value by saying Node(‘tag’, ‘value’) You can also give attributes to the node in the constructor: Node(‘tag’, ‘value’, attr1 = ‘attr1’, attr2 = ‘attr2’) or without a value: Node(‘tag’, attr1 = ‘attr1’, attr2 = ‘attr2’)
To produce xml from a finished Node n, say n.xml() (for nicely formatted output) or n.rawxml().
You can read and modify the attributes of an xml Node using getAttribute(), setAttribute(), or delAttribute().
You can find the value of the first subnode with tag == ‘tag’ by saying n[‘tag’]. If there are multiple instances of n[‘tag’], this will only find the first one, so you should use node() or nodeList() to narrow your search down to a Node that only has one instance of n[‘tag’] first.
You can replace the value of the first subnode with tag == ‘tag’ by saying n[‘tag’] = newValue. The same issues exist as noted in the above paragraph.
You can find the first node with tag == ‘tag’ by saying node(‘tag’). If there are multiple nodes with the same tag at the same level, use nodeList(‘tag’).
The Node class is also designed to create a kind of ‘domain specific language’ by subclassing Node to create Node types specific to your problem domain.
This implementation uses xml.dom.minidom which is available in the standard Python 2.4 library. However, it can be retargeted to use other XML libraries without much effort.
- getAttribute(name)
Read XML attribute of this node.
- setAttribute(name, item)
Modify XML attribute of this node.
- delAttribute(name)
Remove XML attribute with this name.
- replaceAttribute(name, value)
replace XML arrtibute of this node.
- node(tag, elemNum=0)
Recursively find the first subnode with this tag.
- Parameters:
elemNum (int) – if there are several same tag, specify which element to take.
- replaceNode(tag, elemNum=0, newNode=None)
Find the first subnode with this tag and replace with given node.
- Parameters:
tag (str) – node tag
elemNum (int) – number of subnode among other subnodes with similar tag
- delNode(tag, options=None)
Recursively find nodes containing subnodes with this tag and remove subnodes
- Parameters:
options (dictionary) – if there are several tags, specify a node by their attributes.
- nodeList(tag)
Produce a list of subnodes with the same tag.
Note
It only makes sense to do this for the immediate children of a node. If you went another level down, the results would be ambiguous, so the user must choose the node to iterate over.
- tagList()
Produce a list of all tags of the immediate children
- replaceTag(oldTag, newTag)
Replace tag name
- getAttributeList()
get attributes and valuse from the node and return their lists
- insert(contents)
return Node of the node with inserted <contents>
- doc = <xml.dom.minidom.Document object>
- dom()
Lazily create a minidom from the information stored in this Node object.
- xml(separator=' ')
- rawxml()
- static create(dom)
Create a Node representation, given either a string representation of an XML doc, or a dom.
nansat.nsr module
- class nansat.nsr.NSR(*args: Any, **kwargs: Any)
Bases:
SpatialReference
,object
Nansat Spatial Reference. Overrides constructor of osr.SpatialReference.
- Parameters:
srs (0, PROJ4 or EPSG or WKT or osr.SpatialReference, NSR) –
Specifies spatial reference system (SRS) PROJ4: string with proj4 options [http://trac.osgeo.org/proj/] e.g.: ‘+proj=latlong +datum=WGS84 +ellps=WGS84 +no_defs’ ‘+proj=stere +datum=WGS84 +ellps=WGS84 +lat_0=75 +lon_0=0 +no_defs’ EPSG: integer with EPSG number, [http://spatialreference.org/], e.g. 4326 WKT: string with Well Know Text of SRS. E.g.: ‘GEOGCS[“WGS 84”,
- DATUM[“WGS_1984”,
- SPHEROID[“WGS 84”,6378137,298.257223563,
AUTHORITY[“EPSG”,”7030”]],
TOWGS84[0,0,0,0,0,0,0], AUTHORITY[“EPSG”,”6326”]],
- PRIMEM[“Greenwich”,0,
AUTHORITY[“EPSG”,”8901”]],
- UNIT[“degree”,0.0174532925199433,
AUTHORITY[“EPSG”,”9108”]],
AUTHORITY[“EPSG”,”4326”]]’
- property wkt
Well Known Text representation of SRS
nansat.pointbrowser module
- class nansat.pointbrowser.PointBrowser(data, fmt='x-k', force_interactive=True, **kwargs)
Bases:
object
Click on raster images shown by plt.imshow and get the X-Y coordinates.
- Parameters:
data (ndarray) – image to imshow
transect (bool) – if True, get transects / points if False, get only points
force_interactive (bool) – force PointBrowser to interactive mode? (True for regular use, False for tests)
**kwargs (dict) – optional parameters for imshow
Note
self.fig : pyplot Figure
self.data : ndarray with data
self.ax : axes
self.points : plot with points
self.line : plot with points
self.coordinates: container for recorded coordinates
- fig = None
- data = None
- fmt = None
- text_ax = None
- ax = None
- points = None
- lines = None
- coordinates = None
- onclick(event)
Process mouse onclick event Append coordinates of the click to self.coordinates, add point and 2D line to self.points If click is outside, nothing is done If click with ‘z’ pressed, nothing is done If click with ‘anykey’, new line is started
- Parameters:
event (matplotlib.mouse_event)
- get_points()
Enables the onclick events and returns the points.
The format of the returned array: [array([[x1,…,xn],[y1,…,yn]]),array([[xn+1,…],[yn+1,…]]),…] Each ‘array’ element is a numpy.ndarray and represents one transect, where x1,y1 is the first point in the first transect, and xn,yn the last point in the first transect. The inner x/y-arrays are also numpy.ndarrays
- Returns:
points
- Return type:
array
nansat.tools module
- nansat.tools.distance2coast(dst_domain, distance_src=None)
Estimate distance to the nearest coast (in km) for each pixcel in the domain of interest. The method utilizes NASA’s OBPG group Distance to the Nearest Coast product: https://oceancolor.gsfc.nasa.gov/docs/distfromcoast/. The product is stored in GeoTiff format with pixcelsize of 0.01x0.01 degree.
- Parameters:
dst_domain (Domain) – destination domain
distance_src (str) – path to the NASA Distance to the Nearest coast GeoTIFF product
- Returns:
distance
- Return type:
Nansat object with distance to the coast mask in current projection
See also
https://oceancolor.gsfc.nasa.gov/docs/distfromcoast/ <http://nansat.readthedocs.io/en/latest/source/features.html#differentiating-between-land-and-water>
- nansat.tools.get_domain_map(domain, crs=None, lon_margin=10.0, lat_margin=10.0, lw=1, linestyle='b.-', fill_color='coral', fill_alpha=0.5, draw_gridlines=True, draw_labels=True, grid_lw=2, grid_color='gray', grid_alpha=0.5, grid_linestyle='--', **kwargs)
Create a pyplot figure axis with Domain map, Cartopy projection, coastlines
- Parameters:
domain (Domain) – the desired Domain to plot
crs (cartopy CRS or None) – projection of the map, cartopy.crs.PlateCaree by default
lon_margin (float) – 10, horisontal border around patch (degrees of longitude)
lat_margin (float) – 10, vertical border around patch (degrees of latitude)
linestyle (str) – domain line style
lw (float) – domain line width
fill_color (str) – domain fill color
fill_alpha (float) – domain fill transparency
draw_gridlines (bool) – Add gridlines to the plot?
draw_labels (bool) – Add labels to the plot?
grid_lw (float) – gridlines line width
grid_color (str,) – gridlines color
grid_alpha (float) – gridlines transparency
grid_linestyle (str) – gridlines style
- Returns:
ax – Axes with the map and domain patch
- Return type:
pyplot/cartopy axes
- nansat.tools.show_domain_map(domain, **kwargs)
Show Domain map interactively
- Parameters:
domain (Domain) – the Domain to show
**kwargs (dict) – parameters for nansat.tools.get_domain_map
- nansat.tools.save_domain_map(domain, filename, figsize=(5, 5), dpi=150, bbox_inches='tight', pad_inches=0, **kwargs)
Save Domain to PNG file
- Parameters:
domain (Domain) – the Domain to show
filename (str) – destination filename
figsize ((int, int)) – size of the figure in inches
dpi (PNG resolution)
bbox_inches (str or int) – see pyplot.savefig
pad_inches (int) – see pyplot.savefig
**kwargs (dict) – parameters for nansat.tools.get_domain_map
- nansat.tools.deprecated(func)
- nansat.tools.remove_keys(dict, keys)
- nansat.tools.register_colormaps()
- nansat.tools.initial_bearing(lon1, lat1, lon2, lat2)
- nansat.tools.haversine(lon1, lat1, lon2, lat2)
- nansat.tools.add_logger(logName='', logLevel=None)
- nansat.tools.get_random_color(c0=None, minDist=100, low=0, high=255)
- nansat.tools.parse_time(time_string)
nansat.vrt module
- class nansat.vrt.VRT(x_size=1, y_size=1, metadata=None, nomem=False, **kwargs)
Bases:
object
Wrapper around GDAL VRT-file
The GDAL VRT-file is an XML-file. It contains all metadata, geo-reference information and information ABOUT each band including band metadata, reference to the bands in the source file. VRT-class performs all operation on VRT-files: create, copy, modify, read, write, add band, add GeoTransform, set Projection, etc. It uses either GDAL methods for these operations (e.g. Create, AddBand, SetMetadata, AutoCreateWarpedVRT, etc.) or reads/writes the XML-file directly (e.g. remove_geotransform, get_warped_vrt, etc).
The core of the VRT object is GDAL dataset <self.dataset> generated by the GDAL VRT-Driver. The respective VRT-file is located in /vismem and has a random name.
GDAL data model doesn’t have place for geolocaion arrays therefore VRT-object has instance of Geolocation (self.geolocation) an object to keep information about Geolocation metadata: reference to file with source data, pixel and line step and offset, etc.
Domain has an instance of VRT-class <self.vrt>. It keeps only geo- reference information.
All Mappers inherit from VRT. When Nansat opens a file it loops through list of mappers, selects the one appropriate for the input file, and creates an instance of Mapper.
Nansat has one instances of Mapper-class (>=VRT-class): self.vrt. It holds VRT-file in original projection (derived from the input file). After most of the operations with Nansat object (e.g. reproject, crop, resize, add_band) self.vrt is replaced with a new VRT object which has reference to the previous VRT object inside (self.vrt.vrt).
- Parameters:
x_size (int) – width of self.dataset
y_size (int) – arguments for VRT()
metadata (dict) – dictionray with metadata keys (str) and values (str)
nomem (bool) – don’t create VRT in VSI memory?
Notes
adds self.logger, self.driver, self.filename, self.band_vrts, self.tps, self.vrt adds self.dataset - GDAL Dataset without bands and with size=(x_zie, y_size) adds metadata to self.dataset writes VRT file content to self.filename
- COMPLEX_SOURCE_XML = <string.Template object>
- RAW_RASTER_BAND_SOURCE_XML = <string.Template object>
- REPROJECT_TRANSFORMER = <string.Template object>
- geolocation = None
- classmethod from_gdal_dataset(gdal_dataset, **kwargs)
Create VRT from GDAL Dataset with the same size/georeference but wihout bands.
- Parameters:
gdal_dataset (gdal.Dataset) – input GDAL dataset
**kwargs (dict) – arguments for VRT()
- Returns:
vrt
- Return type:
- classmethod from_dataset_params(x_size, y_size, geo_transform, projection, gcps, gcp_projection, **kwargs)
Create VRT from GDAL Dataset parameters
Create VRT with dataset wihout bands but with size/georeference corresponding to input parameters.
- Parameters:
x_size (int) – X-size of dataset
y_size (int) – Y-size of dataset
geotransform (tuple with 6 floats) – informaton on affine transformtaion
projection (str) – WKT representation of spatial reference system
gcps (tuple or list with GDAL GCP objects) – GDAL Ground Control Points
gcp_projection (str) – WKT representation of GCPs spatial reference system
**kwargs (dict) – arguments for VRT()
- Returns:
vrt
- Return type:
- classmethod from_array(array, **kwargs)
Create VRT from numpy array with dataset wih one band but without georeference.
- Parameters:
array (numpy.ndarray) – array with data
**kwargs (dict) – arguments for VRT()
- Returns:
vrt
- Return type:
- classmethod from_lonlat(lon, lat, add_gcps=True, **kwargs)
Create VRT from longitude, latitude arrays
Create VRT with dataset without bands but with GEOLOCATION metadata and Geolocation object. Geolocation contains 2 2D arrays with lon/lat values given at regular pixel/line steps. GCPs can bee created from lon/lat arrays and added to the dataset
- Parameters:
lon (numpy.ndarray) – array with longitudes
lat (numpy.ndarray) – array with latitudes
add_gcps (bool) – Create GCPs from lon/lat arrays and add to dataset
**kwargs (dict) – arguments for VRT()
- Returns:
vrt
- Return type:
- classmethod copy_dataset(gdal_dataset, **kwargs)
Create VRT with bands and georefernce as a full copy of input GDAL Dataset
- Parameters:
gdal_dataset (GDAL.Dataset) – input dataset
**kwargs (dict) – arguments for VRT()
- Returns:
vrt
- Return type:
- logger = None
- driver = None
- filename = ''
- band_vrts = None
- tps = None
- vrt = None
- dataset = None
- leave_few_bands(bands=None)
Leave only given bands in VRT
- split_complex_bands()
Recursevly find complex bands and relace by real and imag components
- create_geolocation_bands()
Create bands from Geolocation
- fix_band_metadata(rm_metadata)
Add NETCDF_VARNAME and remove <rm_metadata> in metadata for each band
- fix_global_metadata(rm_metadata)
Remove unwanted global metadata and escape special characters
- hardcopy_bands()
Make ‘hardcopy’ of bands: evaluate array from band and put into original band
- prepare_export_gtiff()
Prepare dataset for export using GTiff driver
- prepare_export_netcdf()
Prepare dataset for export using netCDF driver
- copy()
Create and return a full copy of a VRT instance with new filenames
If self.dataset has no bands, the copy is created also without bands. If self.dataset has bands, the copy is created from the dataset with all bands. If self has attribute ‘vrt’ (a sub-VRT object, result of get_super_vrt) it’s contents is also copied into sub-VRT of the copy. Other attributes of self, such as tps flag and band_vrts are also copied.
- property xml
Read XML content of the VRT-file using VSI
- Returns:
string
- Return type:
XMl Content which is read from the VSI file
- create_bands(metadata_dict)
Generic function called from the mappers to create bands in the VRT dataset from an input dictionary of metadata
- Parameters:
metadata_dict (list of dict with params of input bands and generated bands.) – Each dict has: ‘src’ : dictionary with parameters of the sources: ‘dst’ : dictionary with parameters of the generated bands
Notes
Adds bands to the self.dataset based on info in metaDict
See also
- create_band(src, dst=None)
Add band to self.dataset:
Get parameters of the source band(s) from input Generate source XML for the VRT, add options of creating Call GDALDataset.AddBand Set source and options Add metadata
- Parameters:
src (dict with parameters of sources) – SourceFilename, SourceBand, ScaleRatio, ScaleOffset, NODATA, LUT, SourceType, DataType, ImageOffset (RawVRT), PixelOffset (RawVRT), LineOffset (RawVRT), ByteOrder (RawVRT), xSize, ySize
dst (dict with parameters of the created band) – name, dataType, wkv, suffix, AnyOtherMetadata, PixelFunctionType ( 1) band will be a pixel function defined by the corresponding name/value. In this case src may be list of dicts with parameters for each source. 2) in case the dst band has a different datatype than the source band it is important to add a SourceTransferType parameter in dst), SourceTransferType
- Returns:
name
- Return type:
string, name of the added band
Examples
>>> vrt.create_band({'SourceFilename': filename, 'SourceBand': 1})
>>> vrt.create_band({'SourceFilename': filename, 'SourceBand': 2, 'ScaleRatio': 0.0001}, {'name': 'LAT', 'wkv': 'latitude'})
>>> vrt.create_band({'SourceFilename': filename, 'SourceBand': 2}, {'suffix': '670', 'wkv': 'brightness_temperature'})
>>> vrt.create_band([{'SourceFilename': filename, 'SourceBand': 1}, {'SourceFilename': filename, 'SourceBand': 1}], {'PixelFunctionType': 'NameOfPixelFunction'})
- write_xml(vsi_file_content=None)
Write XML content into a VRT dataset
- Parameters:
vsi_fileContent (string, optional) – XML Content of the VSI file to write
Notes
- self.dataset
If XML content was written, self.dataset is re-opened
- export(filename)
Export VRT file as XML into given <filename>
- get_warped_vrt(dst_srs, x_size, y_size, geo_transform, resample_alg=0, dst_gcps=[], skip_gcps=1, block_size=None, working_data_type=None, resize_only=False)
Create warped (reprojected) VRT object
Create a simple warped dataset using GDAL.AutoCreateWarpedVRT.
Create VRT from the warped dataset.
Modify the warped VRT according to the input options (size, geotransform, GCPs, etc)
Keep the original VRT in the attribute vrt
For reprojecting the function tries to use geolocation by default, if geolocation is not present it tries to use GCPs, if GCPs are not present it uses GeoTransform.
If destination image has GCPs (provided in <dst_gcps>): fake GCPs for referencing line/pixel of SRC image and X/Y of DST image are created and added to the SRC image. After warping the dst_gcps are added to the warped VRT.
- Parameters:
dst_srs (string) – WKT of the destination projection
x_size (int) – dimentions of the destination rasetr
y_size (int) – dimentions of the destination rasetr
geo_transform (tuple with 6 floats) – destination GDALGeoTransfrom
resample_alg (int (GDALResampleAlg)) – 0 : NearestNeighbour, 1 : Bilinear, 2 : Cubic, 3 : CubicSpline, 4 : Lancoz
dst_gcps (list with GDAL GCPs) – GCPs of the destination image
skip_gcps (int) – Using TPS can be very slow if the number of GCPs are large. If this parameter is given, only every [skip_gcp] GCP is used, improving calculation time at the cost of accuracy.
block_size (int) – BlockSize to use for resampling. Larger blocksize reduces speed but increases accuracy.
working_data_type (str) – ‘Float32’, ‘Int16’, etc.
resize_only (bool) – Create warped_vrt which will be used for resizing only?
- Returns:
warped_vrt
- Return type:
VRT object with warped dataset and with vrt
- copyproj(filename)
Copy geoloctation data from given VRT to a figure file
Useful for adding geolocation information to figure files produced e.g. by Figure class, which contain no geolocation. Analogue to utility gdalcopyproj.py.
- Parameters:
filename (string) – Name of file to which the geolocation data shall be written
- delete_band(band_num)
Delete a band from the given VRT
- Parameters:
band_num (int) – band number
- delete_bands(band_nums)
Delete bands
- Parameters:
bandNums (list) – elements are int
- get_shifted_vrt(shift_degree)
Roll data in bands westwards or eastwards
Create shift_vrt which references self. Modify georeference of shift_vrt to account for the roll. Add as many bands as in self but for each band create two complex sources: for western and eastern parts. Keep self in shift_vrt.vrt
- Parameters:
shift_degree (float) – rolling angle, how far east/west to roll
- Returns:
shift_vrt
- Return type:
VRT object with rolled bands
- get_sub_vrt(steps=1)
Returns sub-VRT from given depth
Iteratively copy self.vrt into self until self.vrt is None or steps == 0
- Parameters:
steps (int) – How many sub VRTs to restore
- Returns:
self (if no deeper VRTs found)
self.vrt (if deeper VRTs are found)
Notes
self self.vrt
- get_super_vrt()
Create a new VRT object with a reference to the current object (self)
Create a new VRT (super_vrt) with exactly the same structure (number of bands, raster size, metadata) as the current object (self). Create a copy of the current object and add it as an attribute of the new object (super_vrt.vrt). Bands in the new object will refer to the same bands in the current object. Recursively copy all vrt attributes of the current object (self.vrt.vrt.vrt…) into the new object (super_vrt.vrt.vrt.vrt.vrt…).
- Returns:
super_vrt – a new VRT object with copy of self in super_vrt.vrt
- Return type:
- get_subsampled_vrt(new_raster_x_size, new_raster_y_size, resample_alg)
Create VRT and replace step in the source
- transform_points(col_vector, row_vector, dst2src=0, dst_srs=None, dst_ds=None, options=None)
Transform input pixel/line coordinates into lon/lat (or opposite)
- Parameters:
col_vector (lists) – X and Y coordinates with any coordinate system
row_vector (lists) – X and Y coordinates with any coordinate system
dst2src (0 or 1) – 1 for inverse transformation, 0 for forward transformation.
dst_srs (NSR) – destination SRS.
dst_ds (GDAL Dataset) – destination dataset. The default is None. It means transform ownPixLin <–> ownXY.
option (string) – if ‘METHOD=GEOLOC_ARRAY’, specify here.
- Returns:
lon_vector, lat_vector – X and Y coordinates in degree of lat/lon
- Return type:
numpy arrays
- get_projection()
Get projection (spatial reference system) of the dataset
Uses dataset.GetProjection() or dataset.GetGCPProjection() or dataset.GetMetadata(‘GEOLOCATION’)[‘SRS’]
- Returns:
projection (projection WKT)
source (str [‘gcps’ or ‘dataset’ or ‘geolocation’])
:raises NansatProjectionError : occurs when the projection is empty.:
- get_resized_vrt(x_size, y_size, resample_alg=1)
Resize VRT
Create Warped VRT with modified RasterXSize, RasterYSize, GeoTransform. The returned VRT object has a copy of its original source VRT in its own vrt object (e.g. warpedVRT.vrt = originalVRT.copy()).
- Parameters:
x_size (int) – new size of the VRT object
y_size (int) – new size of the VRT object
resample_alg (GDALResampleAlg) – see also gdal.AutoCreateWarpedVRT
- Returns:
warped_vrt
- Return type:
Resized VRT object
- reproject_gcps(dst_srs)
Reproject all GCPs to a new spatial reference system
Necessary before warping an image if the given GCPs are in a coordinate system which has a singularity in (or near) the destination area (e.g. poles for lonlat GCPs)
- Parameters:
dst_srs (proj4, WKT, NSR, EPSG) – Destiination SRS given as any NSR input parameter
Notes
Reprojects all GCPs to new SRS and updates GCPProjection
- static transform_coordinates(src_srs, src_points, dst_srs)
Transform coordinates of points from one spatial reference to another
- Parameters:
src_srs (nansat.NSR) – Source spatial reference system
src_points (tuple of two or three N-D arrays) – Coordinates of points in the source spatial reference system. A tuple with (X, Y) or (X, Y, Z) coordinates arrays. Each array can be a list, 1D, 2D, N-D array.
dst_srs (nansat.NSR) – Destination spatial reference
- Returns:
dst_points – Coordinates of points in the destination spatial reference system. A tuple with (X, Y) or (X, Y, Z) coordinates arrays. Each array can be 1D, 2D, N-D. Shape of output arrays corrrrespond to shape of inputs.
- Return type:
tuple of two or three N-D arrays
- set_offset_size(axis, offset, size)
Set offset and size in VRT dataset and band attributes
- Parameters:
axis (str) – name of axis (‘x’ or ‘y’)
offset (int) – value of offset to put into VRT
size (int) – value of size to put into VRT
Notes
Changes VRT file, sets new offset and size
- shift_cropped_gcps(x_offset, x_size, y_offset, y_size)
Modify GCPs to fit the size/offset of cropped image
- shift_cropped_geo_transform(x_offset, x_size, y_offset, y_size)
Modify GeoTransform to fit the size/offset of the cropped image
- static read_vsi(filename)
Read text from input <filename:str> using VSI and return <content:str>.
nansat.warnings module
- exception nansat.warnings.NansatFutureWarning
Bases:
Warning
Module contents
- class nansat.NSR(*args: Any, **kwargs: Any)
Bases:
SpatialReference
,object
Nansat Spatial Reference. Overrides constructor of osr.SpatialReference.
- Parameters:
srs (0, PROJ4 or EPSG or WKT or osr.SpatialReference, NSR) –
Specifies spatial reference system (SRS) PROJ4: string with proj4 options [http://trac.osgeo.org/proj/] e.g.: ‘+proj=latlong +datum=WGS84 +ellps=WGS84 +no_defs’ ‘+proj=stere +datum=WGS84 +ellps=WGS84 +lat_0=75 +lon_0=0 +no_defs’ EPSG: integer with EPSG number, [http://spatialreference.org/], e.g. 4326 WKT: string with Well Know Text of SRS. E.g.: ‘GEOGCS[“WGS 84”,
- DATUM[“WGS_1984”,
- SPHEROID[“WGS 84”,6378137,298.257223563,
AUTHORITY[“EPSG”,”7030”]],
TOWGS84[0,0,0,0,0,0,0], AUTHORITY[“EPSG”,”6326”]],
- PRIMEM[“Greenwich”,0,
AUTHORITY[“EPSG”,”8901”]],
- UNIT[“degree”,0.0174532925199433,
AUTHORITY[“EPSG”,”9108”]],
AUTHORITY[“EPSG”,”4326”]]’
- property wkt
Well Known Text representation of SRS
- class nansat.Domain(srs=None, ext=None, ds=None, **kwargs)
Bases:
object
Container for geographical reference of a raster
A Domain object describes all attributes of geographical reference of a raster:
width and height (number of pixels)
pixel size (e.g. in decimal degrees or in meters)
relation between pixel/line coordinates and geographical coordinates (e.g. a linear relation)
type of data projection (e.g. geographical or stereographic)
- Parameters:
srs (PROJ4 or EPSG or WKT or NSR or osr.SpatialReference()) – Input parameter for nansat.NSR()
ext (string) – some gdalwarp options + additional options [http://www.gdal.org/gdalwarp.html] Specifies extent, resolution / size Available options: ((‘-te’ or ‘-lle’) and (‘-tr’ or ‘-ts’)) (e.g. ‘-lle -10 30 55 60 -ts 1000 1000’ or ‘-te 100 2000 300 10000 -tr 300 200’) -tr resolutionx resolutiony -ts sizex sizey -te xmin ymin xmax ymax -lle lonmin latmin lonmax latmax
ds (GDAL dataset)
Examples
>>> d = Domain(srs, ext) #size, extent and spatial reference is given by strings >>> d = Domain(ds=GDALDataset) #size, extent copied from input GDAL dataset >>> d = Domain(srs, ds=GDALDataset) # spatial reference is given by srs, but size and extent is determined from input GDAL dataset
Notes
The core of Domain is a GDAL Dataset. It has no bands, but only georeference information: rasterXsize, rasterYsize, GeoTransform and Projection or GCPs, etc. which fully describe dimentions and spatial reference of the grid.
There are three ways to store geo-reference in a GDAL dataset:
Using GeoTransfrom to define linear relationship between raster pixel/line and geographical X/Y coordinates
Using GCPs (set of Ground Control Points) to define non-linear relationship between pixel/line and X/Y
Using Geolocation Array - full grids of X/Y coordinates for each pixel of a raster
The relation between X/Y coordinates of the raster and latitude/longitude coordinates is defined by projection type and projection parameters. These pieces of information are therefore stored in Domain:
Type and parameters of projection +
GeoTransform, or
GCPs, or
GeolocationArrays
Domain has methods for basic operations with georeference information:
creating georeference from input options;
fetching corner, border or full grids of X/Y coordinates;
making map of the georeferenced grid in a PNG or KML file;
and some more…
The main attribute of Domain is a VRT object self.vrt. Nansat inherits from Domain and adds bands to self.vrt
:raises NansatProjectionError : occurs when Projection() is empty: despite it is required for creating extentDic. :raises OptionError : occures when the arguments are not proper.:
- OUTPUT_SEPARATOR = '----------------------------------------\n'
- KML_BASE = '<?xml version="1.0" encoding="UTF-8"?>\n <kml xmlns="http://www.opengis.net/kml/2.2"\n xmlns:gx="http://www.google.com/kml/ext/2.2"\n xmlns:kml="http://www.opengis.net/kml/2.2"\n xmlns:atom="http://www.w3.org/2005/Atom">\n {content}\n </kml>'
- logger = None
- name = None
- vrt = None
- classmethod from_lonlat(lon, lat, add_gcps=True)
Create Domain object from input longitudes, latitudes arrays
- Parameters:
lon (numpy.ndarray) – longitudes
lat (numpy.ndarray) – latitudes
add_gcps (bool) – Add GCPs from lon/lat arrays.
- Returns:
d
- Return type:
Examples
>>> lon, lat = np.meshgrid(range(10), range(10)) >>> d1 = Domain.from_lonlat(lon, lat) >>> d2 = Domain.from_lonlat(lon, lat, add_gcps=False) # add only geolocation arrays
- write_kml(xmlFileName=None, kmlFileName=None)
Write KML file with domains
Convert XML-file with domains into KML-file for GoogleEarth or write KML-file with the current Domain
- Parameters:
xmlFileName (string, optional) – Name of the XML-file to convert. If only this value is given - kmlFileName=xmlFileName+’.kml’
kmlFileName (string, optional) – Name of the KML-file to generate from the current Domain
- write_kml_image(kmlFileName, kmlFigureName=None)
Create KML file for already projected image
Write Domain Image into KML-file for GoogleEarth
- Parameters:
kmlFileName (str) – Name of the KML-file to generate from the current Domain
kmlFigureName (str) – Name of the projected image stored in .png format
Examples
>>> n.undo(100) # cancel previous reprojection >>> lons, lats = n.get_corners() # Get corners of the image and the pixel resolution >>> srsString = '+proj=latlong +datum=WGS84 +ellps=WGS84 +no_defs' >>> extentString = '-lle %f %f %f %f -ts 3000 3000' % (min(lons), min(lats), max(lons), max(lats)) >>> d = Domain(srs=srsString, ext=extentString) # Create Domain with stereographic projection, corner coordinates and resolution 1000m >>> n.reproject(d) >>> n.write_figure(filename=figureName, bands=[3], clim=[0,0.15], cmapName='gray', transparency=0) >>> n.write_kml_image(kmlFileName=oPath + filename + '.kml', kmlFigureName=figureName) # 6.
- get_geolocation_grids(stepSize=1, dst_srs=None)
Get longitude and latitude grids representing the full data grid
If GEOLOCATION is not present in the self.vrt.dataset then grids are generated by converting pixel/line of each pixel into lat/lon If GEOLOCATION is present in the self.vrt.dataset then grids are read from the geolocation bands.
- Parameters:
stepSize (int) – Reduction factor if output is desired on a reduced grid size
- Returns:
longitude (numpy array) – grid with longitudes
latitude (numpy array) – grid with latitudes
- get_border(n_points=10, fix_lon=True, **kwargs)
Generate two vectors with values of lat/lon for the border of domain
- Parameters:
n_points (int, optional) – Number of points on each border
fix_lon (bool) – Convert longitudes to positive numbers when Domain crosses dateline?
- Returns:
lonVec, latVec – vectors with lon/lat values for each point at the border
- Return type:
lists
- get_border_wkt(*args, **kwargs)
Creates string with WKT representation of the border polygon
- Returns:
WKTPolygon – string with WKT representation of the border polygon
- Return type:
string
- get_border_geometry(*args, **kwargs)
Get OGR Geometry of the border Polygon
- Returns:
OGR Geometry
- Return type:
Polygon
- get_border_geojson(*args, **kwargs)
Create border of the Polygon in GeoJson format
- Returns:
the Polygon border in GeoJson format
- Return type:
str
- overlaps(anotherDomain)
Checks if this Domain overlaps another Domain
- Returns:
overlaps – True if Domains overlaps, False otherwise
- Return type:
bool
- intersects(anotherDomain)
Checks if this Domain intersects another Domain
- Returns:
intersects – True if Domains intersects, False otherwise
- Return type:
bool
- contains(anotherDomain)
Checks if this Domain fully covers another Domain
- Returns:
contains – True if this Domain fully covers another Domain, False otherwise
- Return type:
bool
- get_border_postgis(**kwargs)
Get PostGIS formatted string of the border Polygon
- Returns:
‘PolygonFromText(PolygonWKT)’
- Return type:
str
- get_corners()
Get coordinates of corners of the Domain
- Returns:
lonVec, latVec – vectors with lon/lat values for each corner
- Return type:
lists
- get_min_max_lon_lat()
Get minimum and maximum of longitude and latitude geolocation grids
- Returns:
min_lon, max_lon, min_lat, max_lat, – min/max lon/lat values for the Domain
- Return type:
float
- get_pixelsize_meters()
Returns the pixelsize (deltaX, deltaY) of the domain
For projected domains, the exact result which is constant over the domain is returned. For geographic (lon-lat) projections, or domains with no geotransform, the haversine formula is used to calculate the pixel size in the center of the domain.
- Returns:
delta_x, delta_y – pixel size in X and Y directions given in meters
- Return type:
float
- transform_points(colVector, rowVector, DstToSrc=0, dst_srs=None)
Transform given lists of X,Y coordinates into lon/lat or inverse
- Parameters:
colVector (lists) – X and Y coordinates in pixel/line or lon/lat coordinate system
DstToSrc (0 or 1) –
0 - forward transform (pix/line => lon/lat)
1 - inverse transformation
dst_srs (NSR) – destination spatial reference
- Returns:
X, Y – X and Y coordinates in lon/lat or pixel/line coordinate system
- Return type:
lists
- azimuth_y(reductionFactor=1)
Calculate the angle of each pixel position vector with respect to the Y-axis (azimuth).
In general, azimuth is the angle from a reference vector (e.g., the direction to North) to the chosen position vector. The azimuth increases clockwise from direction to North. http://en.wikipedia.org/wiki/Azimuth
- Parameters:
reductionFactor (integer) – factor by which the size of the output array is reduced
- Returns:
azimuth – Values of azimuth in degrees in range 0 - 360
- Return type:
numpy array
- shape()
Return Numpy-like shape of Domain object (ySize, xSize)
- Returns:
shape – Numpy-like shape of Domain object (ySize, xSize)
- Return type:
tuple of two INT
- reproject_gcps(srs_string='')
Reproject all GCPs to a new spatial reference system
Necessary before warping an image if the given GCPs are in a coordinate system which has a singularity in (or near) the destination area (e.g. poles for lonlat GCPs)
- Parameters:
srs_string (string) – SRS given as Proj4 string. If empty ‘+proj=stere’ is used
Notes
Reprojects all GCPs to new SRS and updates GCPProjection
- class nansat.Nansat(filename='', mapper='', log_level=30, **kwargs)
-
Container for geospatial data. Performs all high-level operations.
n = Nansat(filename) opens the file with satellite or model data for reading, adds scientific metadata to bands, and prepares the data for further handling.
- Parameters:
filename (str) – uri of the input file or OpeNDAP datastream
mapper (str) – name of the mapper from nansat/mappers dir. E.g. ‘sentinel1_l1’, ‘asar’, ‘hirlam’, ‘meris_l1’, ‘meris_l2’, etc.
log_level (int) – Level of logging. See: http://docs.python.org/howto/logging.html
kwargs (additional arguments for mappers)
Examples
>>> n1 = Nansat(filename) >>> n2 = Nansat(sentinel1_filename, mapper='sentinel1_l1') >>> array1 = n1[1] >>> array2 = n2['sigma0_HV']
Notes
The instance of Nansat class (the object <n>) contains information about geographical reference of the data (e.g raster size, pixel resolution, type of projection, etc) and about bands with values of geophysical variables (e.g. water leaving radiance, normalized radar cross section, chlrophyll concentraion, etc). The object <n> has methods for high-level operations with data. E.g.: * reading data from file (Nansat.__getitem__); * visualization (Nansat.write_figure); * changing geographical reference (Nansat.reproject); * exporting (Nansat.export) * and much more…
Nansat inherits from Domain (container of geo-reference information) Nansat uses instance of VRT (wraper around GDAL VRT-files) Nansat uses instance of Figure (collection of methods for visualization)
- logger = None
- filename = None
- name = None
- path = None
- mapper = None
- classmethod from_domain(domain, array=None, parameters=None, log_level=30)
Create Nansat object from input Domain [and array with data]
- Parameters:
domain (Domain) – Defines spatial reference system and geographical extent.
array (numpy NDarray) – Data for the first band. Shape must correspond to shape of <domain>
parameters (dict) – Metadata for the first band. May contain ‘name’, ‘wkv’ and other keys.
log_level (int) – Level of logging.
- vrt = None
- add_band(array, parameters=None, nomem=False)
Add band from numpy array with metadata.
Create VRT object which contains VRT and RAW binary file and append it to self.vrt.band_vrts
- Parameters:
array (ndarray) – new band data. Shape should be equal to shape
parameters (dict) – band metadata: wkv, name, etc. (or for several bands)
nomem (bool) – saves the vrt to a tempfile on disk?
Notes
Creates VRT object with VRT-file and RAW-file. Adds band to the self.vrt.
Examples
>>> n.add_band(array, {'name': 'new_data'}) # add new band and metadata, keep in memory >>> n.add_band(array, nomem=True) # add new band, keep on disk
- add_bands(arrays, parameters=None, nomem=False)
Add bands from numpy arrays with metadata.
Create VRT object which contains VRT and RAW binary file and append it to self.vrt.band_vrts
- Parameters:
arrays (list of ndarrays) – new band data. Shape should be equal to shape
parameters (list of dict) – band metadata: wkv, name, etc. (or for several bands)
nomem (bool) – saves the vrt to a tempfile on disk?
Notes
Creates VRT object with VRT-file and RAW-file. Adds band to the self.vrt.
Examples
>>> n.add_bands([array1, array2]) # add new bands, keep in memory
- bands()
Make a dictionary with all metadata from all bands
- Returns:
b – key = N, value = dict with all band metadata
- Return type:
dictionary
- has_band(band)
Check if self has band with name <band> :param band: name or standard_name of the band to check :type band: str
- Return type:
True/False if band exists or not
- resize(factor=None, width=None, height=None, pixelsize=None, resample_alg=-1)
Proportional resize of the dataset.
The dataset is resized as (x_size*factor, y_size*factor) If desired width, height or pixelsize is specified, the scaling factor is calculated accordingly. If GCPs are given in a dataset, they are also rewritten.
- Parameters:
factor (float, optional, default=1) –
Scaling factor for width and height
> 1 means increasing domain size
< 1 means decreasing domain size
width (int, optional) – Desired new width in pixels
height (int, optional) – Desired new height in pixels
pixelsize (float, optional) – Desired new pixelsize in meters (approximate). A factor is calculated from ratio of the current pixelsize to the desired pixelsize.
resample_alg (int (GDALResampleAlg), optional) –
-1 : Average (default),
0 : NearestNeighbour
1 : Bilinear,
2 : Cubic,
3 : CubicSpline,
4 : Lancoz
Notes
- self.vrt.datasetVRT dataset of VRT object
raster size are modified to downscaled size. If GCPs are given in the dataset, they are also overwritten.
- get_GDALRasterBand(band_id=1)
Get a GDALRasterBand of a given Nansat object
If str is given find corresponding band number If int is given check if band with this number exists. Get a GDALRasterBand from vrt.
- Parameters:
band_id (int or str) –
if int - a band number of the band to fetch
if str band_id = {‘name’: band_id}
- Return type:
GDAL RasterBand
Example
>>> b = n.get_GDALRasterBand(1) >>> b = n.get_GDALRasterBand('sigma0')
- list_bands(do_print=True)
Show band information of the given Nansat object
Show serial number, longName, name and all parameters for each band in the metadata of the given Nansat object.
- Parameters:
do_print (boolean) – print on screen?
- Returns:
outString – formatted string with bands info
- Return type:
String
- reproject(dst_domain=None, resample_alg=0, block_size=None, tps=None, skip_gcps=1, addmask=True, **kwargs)
Change projection of the object based on the given Domain
Create superVRT from self.vrt with AutoCreateWarpedVRT() using projection from the dst_domain. Modify XML content of the warped vrt using the Domain parameters. Generate warpedVRT and replace self.vrt with warpedVRT. If current object spans from 0 to 360 and dst_domain is west of 0, the object is shifted by 180 westwards.
- Parameters:
dst_domain (domain) – destination Domain where projection and resolution are set
resample_alg (int (GDALResampleAlg)) –
0 : NearestNeighbour
1 : Bilinear
2 : Cubic,
3 : CubicSpline
4 : Lancoz
block_size (int) – size of blocks for resampling. Large value decrease speed but increase accuracy at the edge
tps (bool) – Apply Thin Spline Transformation if source or destination has GCPs Usage of TPS can also be triggered by setting self.vrt.tps=True before calling to reproject. This options has priority over self.vrt.tps
skip_gcps (int) – Using TPS can be very slow if the number of GCPs are large. If this parameter is given, only every [skip_gcp] GCP is used, improving calculation time at the cost of accuracy. If not given explicitly, ‘skip_gcps’ is fetched from the metadata of self, or from dst_domain (as set by mapper or user). [defaults to 1 if not specified, i.e. using all GCPs]
addmask (bool) – If True, add band ‘swathmask’. 1 - valid data, 0 no-data. This band is used to replace no-data values with np.nan
Notes
self.vrt : VRT object with dataset replaced to warpedVRT dataset Integer data is returnd by integer. Round off to decimal place. If you do not want to round off, convert the data types to GDT_Float32, GDT_Float64, or GDT_CFloat32.
See also
- undo(steps=1)
Undo reproject, resize, add_band or crop of Nansat object
Restore the self.vrt from self.vrt.vrt
- Parameters:
steps (int) – How many steps back to undo
Notes
Modifies self.vrt
- watermask(mod44path=None, dst_domain=None, **kwargs)
Create numpy array with watermask (water=1, land=0)
250 meters resolution watermask from MODIS 44W Product: http://www.glcf.umd.edu/data/watermask/
Watermask is stored as tiles in TIF(LZW) format and a VRT file All files are stored in one directory. A tarball with compressed TIF and VRT files should be additionally downloaded from the Nansat documentation page: http://nansat.readthedocs.io/en/latest/source/features.html#differentiating-between-land-and-water
- The method :
Gets the directory either from input parameter or from environment variable MOD44WPATH Open Nansat object from the VRT file Reprojects the watermask onto the current object using reproject() or reproject_on_jcps() Returns the reprojected Nansat object
- Parameters:
mod44path (string) – path with MOD44W Products and a VRT file
dst_domain (Domain) – destination domain other than self
tps (Bool) – Use Thin Spline Transformation in reprojection of watermask? See also Nansat.reproject()
skip_gcps (int) – Factor to reduce the number of GCPs by and increase speed See also Nansat.reproject()
- Returns:
watermask
- Return type:
Nansat object with water mask in current projection
- write_figure(filename='', bands=1, clim=None, addDate=False, array_modfunc=None, **kwargs)
Save a raster band to a figure in graphical format.
Get numpy array from the band(s) and band information specified either by given band number or band id. – If three bands are given, merge them and create PIL image. – If one band is given, create indexed image Create Figure object and: Adjust the array brightness and contrast using the given min/max or histogram. Apply logarithmic scaling of color tone. Generate and append legend. Save the PIL output image in PNG or any other graphical format. If the filename extension is ‘tif’, the figure file is converted to GeoTiff
- Parameters:
filename (str) – Output file name. if one of extensions ‘png’, ‘PNG’, ‘tif’, ‘TIF’, ‘bmp’, ‘BMP’, ‘jpg’, ‘JPG’, ‘jpeg’, ‘JPEG’ is included, specified file is created. otherwise, ‘png’ file is created.
bands (integer or string or list (elements are integer or string),) – default = 1 the size of the list has to be 1 or 3. if the size is 3, RGB image is created based on the three bands. Then the first element is Red, the second is Green, and the third is Blue.
clim (list with two elements or 'hist' to specify range of colormap) – None (default) : min/max values are fetched from WKV, fallback-‘hist’ [min, max] : min and max are numbers, or [[min, min, min], [max, max, max]]: three bands used ‘hist’ : a histogram is used to calculate min and max values
addDate (boolean) – False (default) : no date will be aded to the caption True : the first time of the object will be added to the caption
array_modfunc (None) – None (default) : figure created using array in provided band function : figure created using array modified by provided function
**kwargs (parameters for Figure().)
Notes
if filename is specified, creates image file
- Returns:
Figure – filename extension define format (default format is png)
- Return type:
Figure object
Example
>>> n.write_figure('test.jpg') # write indexed image >>> n.write_figure('test_rgb_hist.jpg', clim='hist', bands=[1, 2, 3]) # RGB image >>> n.write_figure('r09_log3_leg.jpg', logarithm=True, legend=True, gamma=3, titleString='Title', fontSize=30, numOfTicks=15) # add legend >>> n.write_figure(filename='transparent.png', bands=[3], mask_array=wmArray, mask_lut={0: [0,0,0]}, clim=[0,0.15], cmapName='gray', transparency=[0,0,0]) # write transparent image
- write_geotiffimage(filename, band_id=1)
Writes an 8-bit GeoTiff image for a given band.
The colormap is fetched from the metadata item ‘colormap’. Fallback colormap is ‘gray’.
Color limits are fetched from the metadata item ‘minmax’. If ‘minmax’ is not specified, min and max of the raster data is used.
The method can be replaced by using nansat.write_figure(). However, write_figure uses PIL, which does not allow Tiff compression. This gives much larger files.
- Parameters:
filename (str)
band_id (int or str)
- property time_coverage_start
- property time_coverage_end
- get_metadata(key=None, band_id=None, unescape=True)
Get metadata from self.vrt.dataset
- Parameters:
key (str) – name of the metadata key. If not givem all metadata is returned
band_id (int or str) – number or name of band to get metadata from. If not given, global metadata is returned
unescape (bool) – Replace ‘"’, ‘&’, ‘<’ and ‘>’ with these symbols “ & < > ?
- Returns:
metadata (str) – string with metadata if key is given and found
metadata (dict) – dictionary with all metadata if key is not given
- Raises:
ValueError, if key is not found –
- set_metadata(key='', value='', band_id=None)
Set metadata to self.vrt.dataset
- Parameters:
key (string or dictionary with strings) – name of the metadata, or dictionary with metadata names, values
value (string) – value of metadata
band_id (int or str) – number or name of band Without : global metadata is set
Notes
self.vrt.dataset : sets metadata in GDAL current dataset
- get_band_number(band_id)
Return absolute band number
Check if given band_id is valid Return absolute number of the band in the VRT
- Parameters:
band_id (int or str or dict) –
if int : checks if such band exists and returns band_id
if str : finds band with coresponding name
if dict : finds first band with given metadata
- Returns:
absolute band number
- Return type:
int
- get_transect(points, bands, lonlat=True, smooth_radius=0, smooth_function=numpy.nanmedian, data=None, cornersonly=False)
Get values from transect from given vector of poins
- Parameters:
points (2xN list or array, N (number of points) >= 1) – coordinates [[x1, x2, y2], [y1, y2, y3]]
bands (list of int or string) – elements of the list are band number or band Name
lonlat (bool) – If the points in lat/lon, then True. If the points in pixel/line, then False.
smooth_radius (int) – If smootRadius is greater than 0, smooth every transect pixel as the median or mean value in a circule with radius equal to the given number.
smooth_function (func) – function for averaging values collected within smooth radius
data (ndarray) – alternative array with data to take values from
- Returns:
transect
- Return type:
numpy record array
- digitize_points(band=1, **kwargs)
Get coordinates of interactively digitized points
- Parameters:
band (int or str) – ID of Nansat band
**kwargs (keyword arguments for imshow)
- Returns:
points – list of 2xN arrays of points to be used in Nansat.get_transect()
- Return type:
list
- crop_interactive(band=1, maxwidth=1000, **kwargs)
Interactively select boundary and crop Nansat object
- Parameters:
band (int or str) – id of the band to show for interactive selection of boundaries
maxwidth (int) – large input data is downscaled to <maxwidth>
**kwargs (keyword arguments for imshow)
Notes
- self.vrtVRT
superVRT is created with modified SrcRect and DstRect
- Returns:
extent – x_offset - X offset in the original dataset y_offset - Y offset in the original dataset x_size - width of the new dataset y_size - height of the new dataset
- Return type:
(x_offset, y_offset, x_size, y_size)
Examples
>>> extent = n.crop_interactive(band=1) # crop a subimage interactively
- crop_lonlat(lonlim, latlim)
Crop Nansat object to fit into given longitude/latitude limit
- Parameters:
lonlim (list of 2 float) – min/max of longitude
latlim (list of 2 float) – min/max of latitude
Notes
- self.vrtVRT
crops vrt to size that corresponds to lon/lat limits
- Returns:
extent – x_offset - X offset in the original dataset y_offset - Y offset in the original dataset x_size - width of the new dataset y_size - height of the new dataset
- Return type:
(x_offset, y_offset, x_size, y_size)
Examples
>>> extent = n.crop(lonlim=[-10,10], latlim=[-20,20]) # crop for given lon/lat limits
- crop(x_offset, y_offset, x_size, y_size, allow_larger=False)
Crop Nansat object
Create superVRT, modify the Source Rectangle (SrcRect) and Destination Rectangle (DstRect) tags in the VRT file for each band in order to take only part of the original image, create new GCPs or new GeoTransform for the cropped object.
- Parameters:
x_offset (int) – pixel offset of subimage
y_offset (int) – line offset of subimage
x_size (int) – width in pixels of subimage
y_size (int) – height in pizels of subimage
allow_larger (bool) – Allow resulting extent to be larger than the original image?
Notes
self.vrt : super-VRT is created with modified SrcRect and DstRect
- Returns:
extent – x_offset - X offset in the original dataset y_offset - Y offset in the original dataset x_size - width of the new dataset y_size - height of the new dataset
- Return type:
(x_offset, y_offset, x_size, y_size)
Examples
>>> extent = n.crop(10, 20, 100, 200)
- extend(left=0, right=0, top=0, bottom=0)
Extend domain from four sides
- Parameters:
left (int) – number of pixels to add from left side
right (int) – number of pixels to add from right side
top (int) – number of pixels to add from top side
bottom (int) – number of pixels to add from bottom side
Notes
Canges self.vrt by adding nexgative offset or setting size to be large that original size.
- class nansat.Figure(nparray, **kwargs)
Bases:
object
Perform operations with graphical files: create, append legend, save.
Figure instance is created in the Nansat.write_figure method. The methods below are applied consequently in order to generate a figure from one or three bands, estimate min/max, apply logarithmic scaling, convert to uint8, append legend, save to a file
Modifies: self.sizeX, self.sizeY (int), width and height of the image
Modifies: self.pilImg (PIL image), figure
Modifies: self.pilImgLegend (PIL image)
Note
If pilImgLegend is None, legend is not added to the figure. If it is replaced, pilImgLegend includes text string, color-bar, longName and units.
- Parameters:
array (numpy array (2D or 3D)) – dataset from Nansat
cmin (number (int ot float) or [number, number, number]) – 0, minimum value of varibale in the matrix to be shown
cmax (number (int ot float) or [number, number, number]) – 1, minimum value of varibale in the matrix to be shown
gamma (float, >0) – 2, coefficient for tone curve udjustment
subsetArraySize (int) – 100000, size of the subset array which is used to get histogram
numOfColor (int) – 250, number of colors for use of the palette. 254th is black and 255th is white.
cmapName (string) – ‘jet’, name of Matplotlib colormaps see –> http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps
ratio (float, [0 1]) – 1.0, ratio of pixels which are used to write the figure
numOfTicks (int) – 5, number of ticks on a colorbar
titleString (string) – ‘’, title of legend (1st line)
caption (string) – ‘’, caption of the legend (2nd line, e.g. long name and units)
fontRatio (positive float) – 1, factor for changing the fontSize.
fontSize (int) – 12, size of the font of title, caption and ticks. If not given, fontSize is calculated using fontRatio: fontSize = height / 45 * fontRatio. fontSize has priority over fontRatio
logarithm (boolean, defult = False) – If True, tone curve is used to convert pixel values. If False, linear.
legend (boolean, default = False) – if True, information as textString, colorbar, longName and units are added in the figure.
mask_array (2D numpy array, int, the shape should be equal to) – array.shape. If given, this array is used for masking land, clouds, etc on the output image. Value of the array are indices. LUT from mask_lut is used for coloring upon this indices.
mask_lut (dictionary) –
Look-Up-Table with colors for masking land, clouds etc. Used tgether with mask_array: {0, [0,0,0], 1, [100,100,100], 2: [150,150,150], 3: [0,0,255]} index
0 - will have black color
1 - dark gray
2 - light gray
3 - blue
logoFileName (string) – name of the file with logo
logoLocation (list of two int, default = [0,0]) – X and Y offset of the image If positive - offset is from left, upper edge If Negative - from right, lower edge Offset is calculated from the entire image legend inclusive
logoSize (list of two int) – desired X,Y size of logo. If None - original size is used
latGrid (numpy array) – full size array with latitudes. For adding lat/lon grid lines
lonGrid (numpy array) – full size array with longitudes. For adding lat/lon grid lines
nGridLines (int) – number of lat/lon grid lines to show
latlonLabels (int) – number of lat/lon labels to show along each side.
transparency (int) – transparency of the image background(mask), set for PIL alpha mask in Figure.save()
default (None)
LEGEND_HEIGHT (float, [0 1]) – 0.1, legend height relative to image height
CBAR_HEIGHTMIN (int) – 5, minimum colorbar height, pixels
CBAR_HEIGHT (float, [0 1]) – 0.15, colorbar height relative to image height
CBAR_WIDTH (float [0 1]) – 0.8, colorbar width relative to legend width
CBAR_LOCATION_X (float [0 1]) – 0.1, colorbar offset X relative to legend width
CBAR_LOCATION_Y (float [0 1]) – 0.5, colorbar offset Y relative to legend height
CBTICK_LOC_ADJUST_X (int) – 5, colorbar tick label offset X, pixels
CBTICK_LOC_ADJUST_Y (int) – 3, colorbar tick label offset Y, pixels
CAPTION_LOCATION_X (float, [0 1]) – 0.1, caption offset X relative to legend width
CAPTION_LOCATION_Y (float, [0 1]) – 0.1, caption offset Y relative to legend height
TITLE_LOCATION_X (float, [0 1]) – 0.1, title offset X relative to legend width
TITLE_LOCATION_Y – 0.3, title offset Y relative to legend height
DEFAULT_EXTENSION (string) – ‘.png’
- cmin = [0.0]
- cmax = [1.0]
- gamma = 2.0
- subsetArraySize = 100000
- numOfColor = 250
- cmapName = 'jet'
- ratio = 1.0
- numOfTicks = 5
- titleString = ''
- caption = ''
- fontRatio = 1
- fontSize = None
- logarithm = False
- legend = False
- mask_array = None
- mask_lut = None
- logoFileName = None
- logoLocation = [0, 0]
- logoSize = None
- latGrid = None
- lonGrid = None
- lonTicks = 5
- latTicks = 5
- transparency = None
- LEGEND_HEIGHT = 0.1
- CBAR_HEIGHTMIN = 5
- CBAR_HEIGHT = 0.15
- CBAR_WIDTH = 0.8
- CBAR_LOCATION_X = 0.1
- CBAR_LOCATION_Y = 0.5
- CBTICK_LOC_ADJUST_X = 5
- CBTICK_LOC_ADJUST_Y = 3
- CAPTION_LOCATION_X = 0.1
- CAPTION_LOCATION_Y = 0.25
- TITLE_LOCATION_X = 0.1
- TITLE_LOCATION_Y = 0.05
- DEFAULT_EXTENSION = '.png'
- palette = None
- pilImg = None
- pilImgLegend = None
- extensionList = ['png', 'PNG', 'tif', 'TIF', 'bmp', 'BMP', 'jpg', 'JPG', 'jpeg', 'JPEG']
- array = None
- apply_logarithm(**kwargs)
Apply a tone curve to the array
After the normalization of the values from 0 to 1, logarithm is applied Then the values are converted to the normal scale.
Modifies: self.array (numpy array)
- Parameters:
**kwargs (dict) – Any of Figure parameters
- apply_mask(**kwargs)
Apply mask for coloring land, clouds, etc
If mask_array and mask_lut are provided as input parameters. The pixels in self.array which have index equal to mask_lut key in mask_array will have color equal to mask_lut value.
Modifies: self.array (numpy array)
Note
apply_mask should be called only after convert_palettesize (i.e. to uint8 data)
- Parameters:
**kwargs (dict) – Any of Figure parameters
- add_logo(**kwargs)
Insert logo into the PIL image
Read logo from file as PIL. Resize to the given size. Pan using the given location. Paste into pilImg.
Modifies: self.pilImg (PIL image)
- Parameters:
**kwargs (dict) – Any of Figure parameters
- add_latlon_grids(**kwargs)
Add lat/lon grid lines into the PIL image
Compute step of the grid. Make matrices with binarized lat/lon. Find edge (make line). Convert to mask. Add mask to PIL
Modifies: self.pilImg (PIL image), added lat/lon grid lines
- Parameters:
latGrid (numpy array) – array with values of latitudes
lonGrid (numpy array) – array with values of longitudes
lonTicks (int or list) – number of lines to draw or locations of gridlines
latTicks (int or list) – number of lines to draw or locations of gridlines
**kwargs (dict) – any of Figure parameters
- add_latlon_labels(**kwargs)
Add lat/lon labels along upper and left side
Compute step of lables. Get lat/lon for these labels from latGrid, lonGrid Print lables to PIL in white.
Modifies: self.pilImg (PIL image), added lat/lon labels
- Parameters:
latGrid (numpy array) – array with values of latitudes
lonGrid (numpy array) – array with values of longitudes
lonTicks (int or list) – number of lines to draw or locations of gridlines
latTicks (int or list) – number of lines to draw or locations of gridlines
**kwargs (dict) – Any of Figure parameters
- clim_from_histogram(**kwargs)
Estimate min and max pixel values from histogram
if ratio=1.0, simply the minimum and maximum values are returned. if 0 < ratio < 1.0, get the histogram of the pixel values. Then get rid of (1.0-ratio)/2 from the both sides and return the minimum and maximum values.
- Parameters:
**kwargs (dict) – Any of Figure parameters
- Returns:
clim – minimum and maximum pixel values for each band
- Return type:
numpy array 2D ((3x2) or (1x2))
- clip(**kwargs)
Convert self.array to values between cmin and cmax
if pixel value < cmin, replaced to cmin.
if pixel value > cmax, replaced to cmax.
Modifies: self.array (numpy array)
Modifies: self.cmin, self.cmax : allowed min/max values
- Parameters:
**kwargs (dict) – Any of Figure parameters
- convert_palettesize(**kwargs)
Convert self.array to palette color size in uint8
Modifies: self.array (numpy array)
- Parameters:
**kwargs (dict) – Any of Figure parameters
- create_legend(**kwargs)
self.legend is replaced from None to PIL image
PIL image includes colorbar, caption, and titleString.
Modifies: self.legend (PIL image)
- Parameters:
**kwargs (dict) – Any of Figure parameters
- create_pilImage(**kwargs)
self.create_pilImage is replaced from None to PIL image
If three images are given, create a image with RGB mode. if self.pilImgLegend is not None, it is pasted.
If one image is given, create a image with P(palette) mode. if self.pilImgLegend is not None, self.array is extended before create the pilImag and then paste pilImgLegend onto it.
Modifies: self.pilImg (PIL image), PIL image with / without the legend
Modifies: self.array (replace to None)
- Parameters:
**kwargs (dict) – Any of Figure parameters
- process(**kwargs)
Do all common operations for preparation of a figure for saving
Modify default values of parameters by the provided ones (if any)
Clip to min/max
Apply logarithm if required
Convert data to uint8
Create palette
Apply mask for colouring land, clouds, etc if required
Create legend if required
Create PIL image
Add logo if required
Modifies: self.d
Modifies: self.array
Modifies: self.palette
Modifies: self.pilImgLegend
Modifies: self.pilImg
- Parameters:
**kwargs (dict) – Any of Figure parameters
- save(fileName, **kwargs)
Save self.pilImg to a physical file
If given extension is JPG, convert the image mode from Palette to RGB.
Modifies: self.pilImg (None)
- Parameters:
fileName (string) – name of outputfile
**kwargs (dict) – Any of Figure parameters