def test_from_epsg(): proj = CRS.from_epsg(4326) assert proj.to_epsg() == 4326 # Test with invalid EPSG code with pytest.raises(CRSError): assert CRS.from_epsg(0)
def test_sub_crs(): crs = CRS.from_epsg(5972) sub_crs_list = crs.sub_crs_list assert len(sub_crs_list) == 2 assert sub_crs_list[0] == CRS.from_epsg(25832) assert sub_crs_list[1] == CRS.from_epsg(5941) assert crs.is_projected assert not crs.is_geographic
def test_coordinate_system(): crs = CRS.from_epsg(26915) assert repr(crs.coordinate_system).startswith("CS[Cartesian") assert crs.coordinate_system.name == "cartesian" assert crs.coordinate_system.name == str(crs.coordinate_system) assert crs.coordinate_system.axis_list == crs.axis_info assert len(crs.coordinate_system.axis_list) == 2
def test_datum(): datum = CRS.from_epsg(4326).datum assert repr(datum).startswith('DATUM["World Geodetic System 1984"') assert "\n" in repr(datum) assert datum.to_wkt().startswith('DATUM["World Geodetic System 1984"') assert datum == datum assert datum.is_exact_same(datum)
def test_coordinate_operation(): crs = CRS.from_epsg(26915) assert repr(crs.coordinate_operation).startswith('CONVERSION["UTM zone 15N"') assert crs.coordinate_operation.method_name == "Transverse Mercator" assert crs.coordinate_operation.name == str(crs.coordinate_operation) assert crs.coordinate_operation.method_auth_name == "EPSG" assert crs.coordinate_operation.method_code == "9807" assert crs.coordinate_operation.is_instantiable == 1 assert crs.coordinate_operation.has_ballpark_transformation == 0 assert crs.coordinate_operation.accuracy == -1.0 assert repr(crs.coordinate_operation.params) == ( "[Param(name=Latitude of natural origin, auth_name=EPSG, code=8801, " "value=0.0, unit_name=degree, unit_auth_name=EPSG, " "unit_code=9102, unit_category=angular), " "Param(name=Longitude of natural origin, auth_name=EPSG, code=8802, " "value=-93.0, unit_name=degree, unit_auth_name=EPSG, " "unit_code=9102, unit_category=angular), " "Param(name=Scale factor at natural origin, auth_name=EPSG, code=8805, " "value=0.9996, unit_name=unity, unit_auth_name=EPSG, " "unit_code=9201, unit_category=scale), " "Param(name=False easting, auth_name=EPSG, code=8806, value=500000.0, " "unit_name=metre, unit_auth_name=EPSG, unit_code=9001, unit_category=linear), " "Param(name=False northing, auth_name=EPSG, code=8807, value=0.0, " "unit_name=metre, unit_auth_name=EPSG, unit_code=9001, unit_category=linear)]" ) assert crs.coordinate_operation.grids == []
def test_georef_with_depth_nan(self): multibeam = self.dset.raw_ping[0].isel(time=0).expand_dims('time') dpth_with_nan = expected_depth.copy() dpth_with_nan[0][10] = np.nan dpth_with_nan[0][20] = np.nan x = xr.DataArray(data=expected_alongtrack, dims=['time', 'beam'], coords={'time': multibeam.time.values, 'beam': multibeam.beam.values}) y = xr.DataArray(data=expected_acrosstrack, dims=['time', 'beam'], coords={'time': multibeam.time.values, 'beam': multibeam.beam.values}) z = xr.DataArray(data=dpth_with_nan, dims=['time', 'beam'], coords={'time': multibeam.time.values, 'beam': multibeam.beam.values}) sv_corr = [x, y, z] raw_attitude = self.dset.raw_att heading = raw_attitude.heading.interp_like(z) heave = raw_attitude.heave.interp_like(z) altitude = self.dset.raw_ping[0].altitude longitude = self.dset.raw_ping[0].longitude latitude = self.dset.raw_ping[0].latitude installation_params_time = list(self.dset.xyzrph['tx_r'].keys())[0] waterline = float(self.dset.xyzrph['waterline'][installation_params_time]) vert_ref = 'waterline' input_datum = CRS.from_epsg(7911) output_datum = CRS.from_epsg(26910) z_offset = 1.0 georef_x, georef_y, georef_z, corrected_heave, corrected_altitude, vdatumunc, geohashes = georef_by_worker( sv_corr, altitude, longitude, latitude, heading, heave, waterline, vert_ref, input_datum, output_datum, z_offset) assert np.array_equal(georef_x, expected_georef_x) assert np.array_equal(georef_y, expected_georef_y) assert np.isnan(georef_z.values[0][10]) assert np.isnan(georef_z.values[0][20])
def test_area_epsg4326(): """Test with EPSG4326 (latlong) area, which has no CRS coordinate operation.""" from pyproj import CRS shp = (16, 8) euro4326 = create_area_def("epgs4326europa", CRS.from_epsg(4326), resolution=1 / 128, shape=shp, center=(0, 0)) return euro4326
def from_wsf(cls, wsf): """ parse wsf:srs uri i.e http://www.opengis.net/gml/srs/epsg.xml#4326. From wsf:uri is strip epsg code that is entered into from_epsg function. Side effect, accept also EPSG as str :param wsf: str - wsf:uri :return pyproj.CRS """ loc = wsf.find('#') epsg = wsf[loc + 1:] return CRS.from_epsg(epsg)
def test_custom_tms_bounds_user_crs(): """Check bounds with epsg4326.""" custom_tms = TileMatrixSet.custom( (-120, 30, -110, 40), CRS.from_epsg(4326), ) assert custom_tms.xy_bbox == (-120, 30, -110, 40) assert custom_tms.bbox == (-120, 30, -110, 40) assert custom_tms.xy_bounds(0, 0, 0) == (-120, 30, -110, 40) assert custom_tms.bounds(0, 0, 0) == (-120, 30, -110, 40)
def test_creating_multiple_crs_without_file_limit(): """ This test checks for two things: 1. Ensure database connection is closed for file limit https://github.com/pyproj4/pyproj/issues/374 2. Ensure core-dumping does not occur when many objects are created https://github.com/pyproj4/pyproj/issues/678 """ codes = get_codes("EPSG", PJType.PROJECTED_CRS, False) assert [CRS.from_epsg(code) for code in codes]
def clip_to_bbox(self, bbox, bbox_crs): msg = f"bbox must be a {Bbox} instance." assert isinstance(bbox, Bbox), msg bbox_pol = Polygon( [[bbox.xmin, bbox.ymin], [bbox.xmax, bbox.ymin], [bbox.xmax, bbox.ymax], [bbox.xmin, bbox.ymax], [bbox.xmin, bbox.ymin] ]) _switch = True unique_dates = np.unique(self._df['datetime']) _found_start_date = False for _datetime in unique_dates: records = self._df[self._df['datetime'] == _datetime] radii = records['radius_of_last_closed_isobar'].iloc[0] radii = 1852. * radii # convert to meters lon = records['longitude'].iloc[0] lat = records['latitude'].iloc[0] _, _, number, letter = utm.from_latlon(lat, lon) df_crs = CRS.from_epsg(4326) utm_crs = CRS( proj='utm', zone=f'{number}{letter}', ellps={ 'GRS 1980': 'GRS80', 'WGS 84': 'WGS84' }[df_crs.ellipsoid.name] ) transformer = Transformer.from_crs( df_crs, utm_crs, always_xy=True) p = Point(*transformer.transform(lon, lat)) pol = p.buffer(radii) transformer = Transformer.from_crs( utm_crs, bbox_crs, always_xy=True) pol = ops.transform(transformer.transform, pol) if _switch is True: if not pol.intersects(bbox_pol): continue else: self.start_date = records['datetime'].iloc[0] _found_start_date = True _switch = False continue else: if pol.intersects(bbox_pol): continue else: self.end_date = records['datetime'].iloc[0] break if _found_start_date is False: raise Exception( f'No data within mesh bounding box for storm {self.storm_id}.')
def __init__(self, fname, grid, crs): self.grid = grid self.crs = crs # grid centroilds xc = (np.arange(grid['nx']) + .5) * grid['dx'] + grid['x0'] yc = (np.arange(grid['ny']) + .5) * grid['dy'] + grid['y0'] self.x = xc self.y = yc # crs crs_wgs = CRS.from_epsg(4326) crs_model = CRS.from_proj4(crs.proj4_init) self.trns = Transformer.from_crs(crs_wgs, crs_model) # read the receptor file df = pd.read_csv(fname, delimiter=' ', names=['rdx', 'lat', 'lon']) # get x,y coords x, y = [_ * .001 for _ in self.trns.transform(df.lat, df.lon)] df['x'], df['y'] = x, y # get i,j idx = np.array([np.arange(len(xc))[np.isclose(_, xc)][0] for _ in x]) jdx = np.array([np.arange(len(yc))[np.isclose(_, yc)][0] for _ in y]) df['idx0'], df['jdx0'] = idx, jdx df['idx1'], df['jdx1'] = idx + 1, jdx + 1 # see if grid is fully covered, and if it does order nx, ny = len(self.x), len(self.y) self.nx, self.ny = nx, ny cnt_g = nx * ny cnt_d = len(df.index) self.nsta = cnt_d if cnt_g == cnt_d: # full if np.all(idx == np.tile(np.arange(nx), ny)) \ and np.all(jdx == np.repeat(np.arange(ny), nx)): self.coverage = 'full, c-order' elif np.all(idx == np.repeat(np.arange(nx), ny)) \ and np.all(jdx == np.tile(np.arange(ny), nx)): self.coverage = 'full, f-order' else: self.coverage = 'full, random' elif cnt_g > cnt_d: self.coverage = 'partial, random' else: raise ValueError('more data than grid def') print(self.coverage) #df = df.set_index('rdx', drop=False) self.df = df
def __init__(self, grid_tuple): self.name = grid_tuple.name self.epsg = grid_tuple.epsg self.rows = grid_tuple.rows self.cols = grid_tuple.cols self.cell_width = grid_tuple.cell_width self.cell_height = grid_tuple.cell_height self.upper_left_x = grid_tuple.upper_left_x self.upper_left_y = grid_tuple.upper_left_y self.crs = CRS.from_epsg(grid_tuple.epsg)
def interpolate_from_latlon(interpolator, interpolator_crs): input_crs = CRS.from_epsg(4326) transformer = Transformer.from_crs(input_crs, interpolator_crs, always_xy=True) def interpol(lat, lon): r, h = transformer.transform(lon, lat) return interpolator(r, h) return interpol
def test_datum(): datum = CRS.from_epsg(4326).datum assert "\n" in repr(datum) if PROJ_GTE_8: datum_wkt = 'ENSEMBLE["World Geodetic System 1984 ensemble"' else: datum_wkt = 'DATUM["World Geodetic System 1984"' assert repr(datum).startswith(datum_wkt) assert datum.to_wkt().startswith(datum_wkt) assert datum == datum assert datum.is_exact_same(datum)
def test_coordinate_system_geog(): crs = CRS.from_epsg(4326) assert repr(crs.coordinate_system).startswith("CS[ellipsoidal") assert crs.coordinate_system.name == "ellipsoidal" assert crs.coordinate_system.name == str(crs.coordinate_system) assert crs.coordinate_system.axis_list == crs.axis_info assert repr(crs.coordinate_system.axis_list) == ( "[Axis(name=Geodetic latitude, abbrev=Lat, direction=north, " "unit_auth_code=EPSG, unit_code=9122, unit_name=degree), " "Axis(name=Geodetic longitude, abbrev=Lon, direction=east, " "unit_auth_code=EPSG, unit_code=9122, unit_name=degree)]")
def infer_crs(crs_str: str) -> Optional[str]: plausible_list = [ PJCRS.from_epsg(code).to_wkt() for code in DEFAULT_CRS_INFERENCES ] closest_wkt = difflib.get_close_matches(crs_str, plausible_list, cutoff=0.38) if len(closest_wkt) == 0: return epsg = PJCRS.from_wkt(closest_wkt[0]).to_epsg() return f"epsg:{epsg}"
def wgs84_utm_zone(self): """ Finds the UTM zone where the first point of the GCP falls into :return utm zone string valid for a coordinates header """ if self.entries_count() > 0: entry = self.get_entry(0) longlat = CRS.from_epsg("4326") lon, lat = location.transform2(self.srs, longlat, entry.x, entry.y) utm_zone, hemisphere = location.get_utm_zone_and_hemisphere_from(lon, lat) return "WGS84 UTM %s%s" % (utm_zone, hemisphere)
def test_to_wkt_enum(): crs = CRS.from_epsg(4326) assert crs.to_wkt("WKT1_GDAL") == crs.to_wkt(WktVersion.WKT1_GDAL) assert crs.to_wkt("WKT2_2018") == crs.to_wkt(WktVersion.WKT2_2018) assert crs.to_wkt("WKT2_2018_SIMPLIFIED") == crs.to_wkt( WktVersion.WKT2_2018_SIMPLIFIED ) assert crs.to_wkt("WKT2_2015") == crs.to_wkt(WktVersion.WKT2_2015) assert crs.to_wkt("WKT2_2015_SIMPLIFIED") == crs.to_wkt( WktVersion.WKT2_2015_SIMPLIFIED )
def validate_crs(ctx, param, value): if not value: return CRS.from_epsg(4326) elif value == "keep": return None if value.isdigit(): value = int(value) try: return CRS.from_user_input(value) except pyproj.exceptions.CRSError as e: raise click.BadParameter(str(e))
def build_crs(zone_num: str = None, datum: str = None, epsg: str = None, projected: bool = True): horizontal_crs = None if epsg: try: horizontal_crs = CRS.from_epsg(int(epsg)) except CRSError: # if the CRS we generate here has no epsg, when we save it to disk we save the proj string horizontal_crs = CRS.from_string(epsg) elif not epsg and not projected: datum = datum.upper() if datum == 'NAD83': horizontal_crs = CRS.from_epsg(epsg_determinator('nad83(2011)')) elif datum == 'WGS84': horizontal_crs = CRS.from_epsg(epsg_determinator('wgs84')) else: err = '{} not supported. Only supports WGS84 and NAD83'.format( datum) return horizontal_crs, err elif not epsg and projected: datum = datum.upper() zone = zone_num # this will be the zone and hemi concatenated, '10N' try: zone, hemi = int(zone[:-1]), str(zone[-1:]) except: raise ValueError( 'construct_crs: found invalid projected zone/hemisphere identifier: {}, expected something like "10N"' .format(zone)) if datum == 'NAD83': horizontal_crs = CRS.from_epsg( epsg_determinator('nad83(2011)', zone=zone, hemisphere=hemi)) elif datum == 'WGS84': horizontal_crs = CRS.from_epsg( epsg_determinator('wgs84', zone=zone, hemisphere=hemi)) else: err = '{} not supported. Only supports WGS84 and NAD83'.format( datum) return horizontal_crs, err return horizontal_crs, ''
def geodeticToProj(lat, lon, ellip, proj_out, proj_in=6319): """Convert geodetic coordinates to projected coordinate system Parameters: lat (np.array): latitudes lon (np.array): longitudes ellip (np.height): ellipsoid heights proj_out (int): epsg code of output projected coordinate system proj_in (int): epsg code of input geodetic coordinate system, defaults to NAD83 (2011) Returns: tuple: X, Y, Z of projected coordinate system """ # Define transformation parameters geodetic = CRS.from_epsg(proj_in) projected = CRS.from_epsg(proj_out) transformer = Transformer.from_crs(geodetic, projected) # Transform coordinates return transformer.transform(lat, lon, ellip)
def test_coordinate_system_geog(): crs = CRS.from_epsg(4326) assert repr(crs.coordinate_system).startswith("CS[ellipsoidal") assert crs.coordinate_system.name == "ellipsoidal" assert crs.coordinate_system.name == str(crs.coordinate_system) assert crs.coordinate_system.axis_list == crs.axis_info assert repr(crs.coordinate_system.axis_list) == ( "[Axis(name=Geodetic latitude, abbrev=Lat, direction=north, " "unit_auth_code=EPSG, unit_code=9122, unit_name=degree), " "Axis(name=Geodetic longitude, abbrev=Lon, direction=east, " "unit_auth_code=EPSG, unit_code=9122, unit_name=degree)]" )
def ll2utm(lat, lon): """ Convert lat/long to UTM coordinates (m) :param lat: latitude (decimal) :param lon: longitude (decimal) :return: x, y, ((utm_zone, north/south, latitude_letter), projection_instance) """ utm_z = get_utm_zone(lat, lon) p = Proj(CRS.from_epsg(get_wgs84_utm_epsg_code(*utm_z))) x, y = p(lon, lat) return x, y, (utm_z, p)
def test_geometric_dict(self): geometric_object = GeometricClass(Point(-77, 38.9)) geometric_dict = GeometricDict() geometric_dict[123] = geometric_object geometric_dict[234] = geometric_object crs_4326 = CRS.from_epsg(4326) geometric_dict.crs = crs_4326 geometric_dict.to_geoseries() folium_map = folium.Map(location=(38.9, -77), zoom_start=12) geometric_dict.plot_folium(folium_map) aea = CRS.from_string("North America Albers Equal Area Conic") geometric_dict.to_crs(aea)
def name_to_crs(name, default=None): return { "latlon": CRS.from_epsg(geo_capnp.EPSG.wgs84), "wgs84": CRS.from_epsg(geo_capnp.EPSG.wgs84), "gk3": CRS.from_epsg(geo_capnp.EPSG.gk3), "gk4": CRS.from_epsg(geo_capnp.EPSG.gk4), "gk5": CRS.from_epsg(geo_capnp.EPSG.gk5), "utm21s": CRS.from_epsg(geo_capnp.EPSG.utm21S), "utm32n": CRS.from_epsg(geo_capnp.EPSG.utm32N) }.get(name.lower(), default)
def meta_update(self, buffer_image, buffer_region, affine): # self represent the original file meta data meta_data = self.meta.copy() epsg_code = int(buffer_region.crs['init'][5:]) meta_data.update({ "driver": "GTiff", "height": buffer_image.shape[1], "width": buffer_image.shape[2], "transform": affine, "crs": CRS.from_epsg(epsg_code).to_proj4() }) return meta_data
def read_nid(self): df = pd.read_excel(self.data_config.nid_file) """transform data to geopandas""" data = gpd.GeoDataFrame(df, crs=CRS.from_epsg(self.data_config.nid_epsg).to_wkt()) data['geometry'] = None for idx in range(df.shape[0]): # create a point based on x and y column values on this row: point = Point(df['LONGITUDE'][idx], df['LATITUDE'][idx]) # Add the point object to the geometry column on this row: data.at[idx, 'geometry'] = point return data
def _custom_output_crs(self, destination_epsg: int): try: out_crs = CRS.from_epsg(int(destination_epsg)) except CRSError: self.log_error(f'Expected integer epsg code that is readable by the pyproj CRS object, got {destination_epsg}', ValueError) if out_crs.is_vertical: self.log_error(f'Only 2d coordinate system epsg supported when using the new_2d_crs option, got {destination_epsg}', ValueError) in_crs = CRS.from_epsg(6319) # Transformer.transform input order is based on the CRS, see CRS.geodetic_crs.axis_info # - lon, lat - this appears to be valid when using CRS from proj4 string # - lat, lon - this appears to be valid when using CRS from epsg # use the always_xy option to force the transform to expect lon/lat order transformer = Transformer.from_crs(in_crs, out_crs, always_xy=True) new_min_x, new_min_y = transformer.transform(self.geographic_min_x, self.geographic_min_y) new_max_x, new_max_y = transformer.transform(self.geographic_max_x, self.geographic_max_y) # if out_crs.is_projected: # if new_min_x < 0: # new_min_x = int(np.ceil(new_min_x)) # else: # new_min_x = int(np.floor(new_min_x)) # if new_min_y < 0: # new_min_y = int(np.ceil(new_min_y)) # else: # new_min_y = int(np.floor(new_min_y)) # if new_max_x < 0: # new_max_x = int(np.floor(new_max_x)) # else: # new_max_x = int(np.ceil(new_max_x)) # if new_max_y < 0: # new_max_y = int(np.floor(new_max_y)) # else: # new_max_y = int(np.ceil(new_max_y)) x_rez = (new_max_x - new_min_x) / self.width y_rez = (new_max_y - new_min_y) / self.height self.output_geotransform = (new_min_x, x_rez, 0.0, new_max_y, 0.0, -y_rez) self.out_crs.horiz_wkt = out_crs.to_wkt()
def calculate_bounding_box(given_srid): """ calculate the local bounding box and return a shapely polygon of this BB with local coordq """ xmin, ymin, xmax, ymax = CRS.from_epsg(given_srid).area_of_use.bounds bounding_polygon_4326 = Polygon([(xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax)]) projection = Transformer.from_crs(CRS(4326), CRS(int(given_srid)), always_xy=True) return transform(projection.transform, bounding_polygon_4326)
def _save_hfun_to_db(self, hfun, id): self._logger.debug("_save_hfun_to_db()") _original_crs = hfun.crs if not _original_crs.equals(CRS.from_epsg(4326)): self._logger.debug(f"tranforming from {hfun.crs} to EPSG:4326") hfun.transform_to('EPSG:4326') self._session.add( db.Hfun( hfun=geoalchemy2.shape.from_shape(hfun.multipolygon), id=id)) self._session.commit() if not hfun.crs.equals(_original_crs): hfun.transform_to(_original_crs)
def _save_geom_to_db(self, geom, id): self._logger.debug("_save_geom_to_db()") _original_crs = geom.crs if not _original_crs.equals(CRS.from_epsg(4326)): self._logger.debug(f"tranforming from {geom.crs} to EPSG:4326") geom.transform_to('EPSG:4326') self._session.add( db.Geom( geom=geoalchemy2.shape.from_shape(geom.multipolygon), id=id)) self._session.commit() if not geom.crs.equals(_original_crs): geom.transform_to(_original_crs)
def NormCoords(lista, NORM): # Recibe una lista de coordenadas from pyproj.aoi import AreaOfInterest from pyproj.database import query_utm_crs_info from pyproj import CRS from pyproj import Proj import math import numpy as np import pandas as pd Lat = np.array(lista)[:, 0] Long = np.array(lista)[:, 1] utm_crs_list = query_utm_crs_info( datum_name="WGS 84", area_of_interest=AreaOfInterest( west_lon_degree=Lat.mean(), south_lat_degree=Long.mean(), east_lon_degree=Lat.mean(), north_lat_degree=Long.mean(), ), ) utm_crs = CRS.from_epsg(utm_crs_list[0].code) myProj = Proj(utm_crs_list[0].name) UTMx, UTMy = myProj(Long, Lat, inverse=False) MxLon = UTMx.max() MnLon = UTMx.min() MxLat = UTMy.max() MnLat = UTMy.min() bx = (UTMx.max() - UTMx.min()) by = (UTMy.max() - UTMy.min()) NormLon = [] NormLat = [] for i in range(0, len(UTMx)): NormLon.append((UTMx[i] - MxLon) * NORM / bx + NORM) NormLat.append((UTMy[i] - MxLat) * NORM / by + NORM) Info = [] for i in range(0, len(NormLon)): Info.append([NormLon[i], NormLat[i]]) return (Info)
def plot(self, sph_epsg=4326, car_epsg=3857): """ Visualize the grid.If the coordinate system is spherical, it will be automatically convert to cartesian coordinate system. You can specify the EPSG of coordiante by assigning sph_egsp and car_epsg. Find the EPSG of more coordinate system in the following link. https://developers.arcgis.com/javascript/3/jshelp/pcs.htm Parameters ---------- sph_epsg : int, optional car_epsg : int, optional Examples ------- >>> grd = GrdFile('river.grd') >>> grd.plot() >>> grd.plot(sph_epsg=4326, car_epsg=26917) """ if self.header['Coordinate System'] == 'Spherical': # transform from spherical to cartesian grd_crs = CRS.from_epsg(sph_epsg) plot_crs = CRS.from_epsg(car_epsg) projection = Transformer.from_crs(grd_crs, plot_crs) x, y = projection.transform(self.x, self.y) print( "Automatically transform from spherical to cartesian coordinates.\n" "Change the default projection by giving specific grd_epsg and plot_epsg" ) else: x, y = self.x, self.y # plot grid plt.pcolormesh(x, y, np.zeros(np.shape(self.x)), edgecolor=None, facecolor='none', linewidth=0.005) plt.axis('equal') plt.show()
def _build_polygons(self, polygon: np.ndarray, geographic: bool): """ Build separate geographic/projected polygon coordinates from the provided polygon coordinates Parameters ---------- polygon (N, 2) array of points that make up the selection polygon geographic If True, the coordinates provided are geographic (latitude/longitude) Returns ------- polygon (N, 2) array of points that make up the selection polygon in geographic coordinates polygon (N, 2) array of points that make up the selection polygon in projected coordinates in the Fqpr instance coordinate system """ if isinstance(polygon, list): polygon = np.array(polygon) if not geographic: proj_polygon = polygon trans = Transformer.from_crs( CRS.from_epsg(self.fqpr.multibeam.raw_ping[0].horizontal_crs), CRS.from_epsg(kluster_variables.epsg_wgs84), always_xy=True) polyx, polyy = trans.transform(polygon[:, 0], polygon[:, 1]) geo_polygon = np.c_[polyx, polyy] else: geo_polygon = polygon trans = Transformer.from_crs( CRS.from_epsg(kluster_variables.epsg_wgs84), CRS.from_epsg(self.fqpr.multibeam.raw_ping[0].horizontal_crs), always_xy=True) polyx, polyy = trans.transform(polygon[:, 0], polygon[:, 1]) proj_polygon = np.c_[polyx, polyy] return geo_polygon, proj_polygon
def set_crs(self, crs=None, epsg=None, inplace=False, allow_override=False): """ Set the Coordinate Reference System (CRS) of a ``GeoSeries``. NOTE: The underlying geometries are not transformed to this CRS. To transform the geometries to a new CRS, use the ``to_crs`` method. Parameters ---------- crs : pyproj.CRS, optional if `epsg` is specified The value can be anything accepted by :meth:`pyproj.CRS.from_user_input() <pyproj.crs.CRS.from_user_input>`, such as an authority string (eg "EPSG:4326") or a WKT string. epsg : int, optional if `crs` is specified EPSG code specifying the projection. inplace : bool, default False If True, the CRS of the GeoSeries will be changed in place (while still returning the result) instead of making a copy of the GeoSeries. allow_override : bool, default False If the the GeoSeries already has a CRS, allow to replace the existing CRS, even when both are not equal. Returns ------- GeoSeries """ if crs is not None: crs = CRS.from_user_input(crs) elif epsg is not None: crs = CRS.from_epsg(epsg) else: raise ValueError("Must pass either crs or epsg.") if not allow_override and self.crs is not None and not self.crs == crs: raise ValueError( "The GeoSeries already has a CRS which is not equal to the passed " "CRS. Specify 'allow_override=True' to allow replacing the existing " "CRS without doing any transformation. If you actually want to " "transform the geometries, use 'GeoSeries.to_crs' instead.") if not inplace: result = self.copy() else: result = self result.crs = crs return result
def test_to_wkt_pretty(): crs = CRS.from_epsg(4326) assert "\n" in crs.to_wkt(pretty=True) assert "\n" not in crs.to_wkt()
def test_epsg(): assert CRS({"init": "EPSG:4326"}).to_epsg(20) == 4326 assert CRS({"init": "EPSG:4326"}).to_epsg() is None assert CRS.from_user_input(4326).to_epsg() == 4326 assert CRS.from_epsg(4326).to_epsg() == 4326 assert CRS.from_user_input("epsg:4326").to_epsg() == 4326
def test_datum_horizontal(): assert CRS.from_epsg(5972).datum == CRS.from_epsg(25832).datum
def test_coordinate_operation__missing(): crs = CRS.from_epsg(4326) assert crs.coordinate_operation is None
def test_sub_crs__none(): assert CRS.from_epsg(4326).sub_crs_list == []
def test_ellipsoid(): crs1 = CRS.from_epsg(4326) assert "{:.3f}".format(crs1.ellipsoid.inverse_flattening) == "298.257" assert "{:.3f}".format(crs1.ellipsoid.semi_major_metre) == "6378137.000" assert "{:.3f}".format(crs1.ellipsoid.semi_minor_metre) == "6356752.314"
def test_area_of_use(): crs1 = CRS.from_epsg(4326) assert crs1.area_of_use.bounds == (-180.0, -90.0, 180.0, 90.0) assert crs1.area_of_use.name == "World"
def to_wkt(self): return CRS.from_epsg(4326).to_wkt()
def test_from_user_input_custom_crs_class(): class CustomCRS(object): def to_wkt(self): return CRS.from_epsg(4326).to_wkt() assert CRS.from_user_input(CustomCRS()) == CRS.from_epsg(4326)