def test_set_coords_0dim(): # a geometry input returns a geometry actual = set_coordinates(point, [[1, 1]]) assert isinstance(actual, pygeos.Geometry) # a 0-dim array input returns a 0-dim array actual = set_coordinates(np.asarray(point), [[1, 1]]) assert isinstance(actual, np.ndarray) assert actual.ndim == 0
def add_distances(network): #Find crs of current gdf and arbitrary point(lat,lon) for new crs current_crs = "epsg:4326" #The commented out crs does not work in all cases #current_crs = [*network.edges.crs.values()] #current_crs = str(current_crs[0]) print(network.nodes.iloc[0]) print(network.nodes) lat = pygeom.get_y(network.nodes['geometry'].iloc[0]) lon = pygeom.get_x(network.nodes['geometry'].iloc[0]) # formula below based on :https://gis.stackexchange.com/a/190209/80697 approximate_crs = "epsg:" + str( int(32700 - np.round((45 + lat) / 90, 0) * 100 + np.round((183 + lon) / 6, 0))) #from pygeos/issues/95 geometries = network.edges['geometry'] coords = pygeos.get_coordinates(geometries) transformer = pyproj.Transformer.from_crs(current_crs, approximate_crs, always_xy=True) new_coords = transformer.transform(coords[:, 0], coords[:, 1]) result = pygeos.set_coordinates(geometries.copy(), np.array(new_coords).T) dist = pygeos.length(result) edges = network.edges.copy() edges['distance'] = dist return Network(nodes=network.nodes, edges=edges)
def convert_crs(gdf, current_crs="epsg:4326"): """[summary] Args: gdf ([type]): [description] Returns: [type]: [description] """ if current_crs == "epsg:4326": lat = pygeos.geometry.get_y(pygeos.centroid(gdf['geometry'].iloc[0])) lon = pygeos.geometry.get_x(pygeos.centroid(gdf['geometry'].iloc[0])) # formula below based on :https://gis.stackexchange.com/a/190209/80697 approximate_crs = "epsg:" + str( int(32700 - np.round((45 + lat) / 90, 0) * 100 + np.round((183 + lon) / 6, 0))) else: approximate_crs = "epsg:4326" #from pygeos/issues/95 geometries = gdf['geometry'] coords = pygeos.get_coordinates(geometries) transformer = pyproj.Transformer.from_crs(current_crs, approximate_crs, always_xy=True) new_coords = transformer.transform(coords[:, 0], coords[:, 1]) result = pygeos.set_coordinates(geometries.copy(), np.array(new_coords).T) return result, approximate_crs
def test_set_coords(geoms, count, has_ring, include_z): arr_geoms = np.array(geoms, np.object_) n = 3 if include_z else 2 coords = get_coordinates(arr_geoms, include_z=include_z) + np.random.random((1, n)) new_geoms = set_coordinates(arr_geoms, coords) assert_equal(coords, get_coordinates(new_geoms, include_z=include_z))
def perspective_projection(df, sc_coords, sc_heading, fov, width, height, debug=False): lat, lon, alt = sc_coords head, tilt, roll = sc_heading crs_cart = CRS.from_string('+proj=cart') transformer = Transformer.from_crs(df.crs, crs_cart) # cartesian coordinates: # x-axis points from the Earth center to the point of longitude=0, latitude=0 # y-axis points from the Earth center to the point of longitude=90, latitude=0 # z-axis points to the North pole # satellite location in cartesian coords sc_pos_v = np.array(transformer.transform(lat, lon, alt)) # get rotation and projection matrices rot_mx = get_rot_mx(lat, lon, head, tilt, roll) cam_mx = get_cam_mx(fov, width, height) if debug: # test with svalbard coords sval = np.array(transformer.transform(78.148, 16.043, 520)) sc_sv = sval - sc_pos_v sc_sv_cf = rot_mx.dot(sc_sv) * 1e-3 sv_im = cam_mx.dot(sc_sv_cf) print('svalbard at [km] %s, in image [px]: %s' % (sc_sv_cf, sv_im[:2] / sv_im[2])) data = df.geometry.values.data coords = pygeos.get_coordinates(data, include_z=True) # order out: lon, lat shape = coords.shape fc = coords.flatten() fc[np.isnan(fc)] = 0 coords = fc.reshape(shape) loc = transformer.transform(coords[:, 1], coords[:, 0], coords[:, 2]) # order in: lat, lon loc = np.stack(loc, axis=1) rel_loc = loc - sc_pos_v # remove features that are farther away than the horizon r = np.linalg.norm(loc[0, :]) horizon_dist = math.sqrt((r + alt)**2 - r**2) mask = np.linalg.norm(rel_loc, axis=1) > horizon_dist rel_loc[mask, :] = np.nan # rotate and project to image img_coords = cam_mx.dot(rot_mx).dot(rel_loc.T).T img_coords = img_coords[:, :2] / img_coords[:, 2:] new_data = pygeos.set_coordinates(data.copy(), img_coords) new_geom = GeoSeries(GeometryArray(new_data), crs=crs_cart, name=df.geometry.name) df.geometry = new_geom[new_geom.is_valid]
def transform(arr, src_crs, tgt_crs): transformer = pyproj.Transformer.from_crs(src_crs, tgt_crs, always_xy=True) geometry = pg.from_wkb(arr) coords = pg.get_coordinates(geometry) new_coords = transformer.transform(coords[:, 0], coords[:, 1]) projected = pg.set_coordinates(geometry, np.array(new_coords).T) return pg.to_wkb(projected)
def test_set_coords(geoms, count, has_ring): geoms = np.array(geoms, np.object) if has_ring: # do not randomize; linearrings / polygons should stay closed coords = get_coordinates(geoms) + np.random.random((1, 2)) else: coords = np.random.random((count, 2)) new_geoms = set_coordinates(geoms, coords) assert_equal(coords, get_coordinates(new_geoms))
def test_set_coords_mixed_dimension(include_z): geoms = np.array([point, point_z], dtype=object) coords = get_coordinates(geoms, include_z=include_z) new_geoms = set_coordinates(geoms, coords * 2) if include_z: # preserve original dimensionality assert not pygeos.has_z(new_geoms[0]) assert pygeos.has_z(new_geoms[1]) else: # all 2D assert not pygeos.has_z(new_geoms).any()
def transform(data, func): if compat.USE_PYGEOS: coords = pygeos.get_coordinates(data) new_coords = func(coords[:, 0], coords[:, 1]) result = pygeos.set_coordinates(data.copy(), np.array(new_coords).T) else: from shapely.ops import transform n = len(data) result = np.empty(n, dtype=object) for i in range(n): geom = data[i] result[i] = geom if _isna(geom) else transform(func, geom) return result
def mbr(self): """Returns the Minimum Bounding Rectangle. Returns: (string) The WKT representation of the MBR. """ if not self._has_geometry: warnings.warn('DataFrame is not spatial.') return None total_bounds = self.df.geometry.total_bounds() transformer = pyproj.Transformer.from_crs(self.crs, "EPSG:4326", always_xy=True) coords = pg.get_coordinates(total_bounds) new_coords = transformer.transform(coords[:, 0], coords[:, 1]) transformed = pg.set_coordinates(total_bounds, np.array(new_coords).T) return pg.to_wkt(transformed)
def to_crs(geometries, src_crs, target_crs): """Convert coordinates from one CRS to another CRS. Parameters ---------- geometries : ndarray of pygeos geometries src_crs : CRS or params to create it target_crs : CRS or params to create it """ if src_crs == target_crs: return geometries.copy() transformer = Transformer.from_crs(src_crs, target_crs, always_xy=True) coords = pg.get_coordinates(geometries) new_coords = transformer.transform(coords[:, 0], coords[:, 1]) result = pg.set_coordinates(geometries.copy(), np.array(new_coords).T) return result
def transform_geoseries(geometry): target_crs = pyproj.crs.CRS(target) if target_crs == geometry.crs: return geometry cm.check.crs(target_crs) cm.check.crs(geometry.crs) transformer = pyproj.Transformer.from_crs( geometry.crs, target_crs, always_xy=True) if not all(pygeos.has_z(geometry.array.data)): coords = pygeos.get_coordinates( geometry.array.data, include_z=False) new_coords = transformer.transform(coords[:, 0], coords[:, 1]) else: coords = pygeos.get_coordinates( geometry.array.data, include_z=True) new_coords = transformer.transform( coords[:, 0], coords[:, 1], coords[:, 2]) return pygeos.set_coordinates(geometry.array.data.copy(), np.array(new_coords).T)
def convex_hull(self, chunksize=50000, max_workers=None): """Returns the convex hull of all geometries in the dataframe. Parameters: chunksize (int): The chunksize (number of features) for each computation. max_workers (int): The number of workers to be used, if None equals to number of available cores. Returns: (string) The WKT representation of convex hull. """ if not self._has_geometry: warnings.warn('DataFrame is not spatial.') return None hull = self.df.geometry.convex_hull_all(chunksize=chunksize, max_workers=max_workers) transformer = pyproj.Transformer.from_crs(self.crs, "EPSG:4326", always_xy=True) coords = pg.get_coordinates(hull) new_coords = transformer.transform(coords[:, 0], coords[:, 1]) transformed = pg.set_coordinates(hull, np.array(new_coords).T) return pg.to_wkt(transformed)
def addWKT(self, wkt, epsg): """Add WKT in static map. Parameters: wkt (string) The Well-Known-Text representation of geometry. epsg (int) The WKT CRS. Returns: (obj) The matplotlib plot. """ import pygeos as pg from pyproj.transformer import Transformer geometry = pg.from_wkt(wkt) coords = pg.get_coordinates(geometry) try: transformer = Transformer.from_crs(epsg, 3857, always_xy=True) new_coords = transformer.transform(coords[:, 0], coords[:, 1]) geometry = pg.set_coordinates(geometry, array(new_coords).T) except: raise Exception('Transformation to EPSG:3857 failed.') with warnings.catch_warnings(): warnings.filterwarnings("ignore") minx, miny, maxx, maxy = self._getBorders(new_coords, self.aspect_ratio) fig, ax = plt.subplots(figsize=(self._width, self._height), dpi=self.dpi) ax.set_xlim(minx, maxx) ax.set_ylim(miny, maxy) plt.xticks([], []) plt.yticks([], []) ax.fill(new_coords[0], new_coords[1], facecolor='#50505050', edgecolor='orange', linewidth=3) ctx.add_basemap(ax, source=self.basemap) self.map = fig plt.close(fig) return fig
def swap_lat_lon(df): data = df.geometry.values.data coords = pygeos.get_coordinates(data) pygeos.set_coordinates(data, coords[:, (1, 0)])
def test_set_coords_breaks_ring(): with pytest.raises(pygeos.GEOSException): set_coordinates(linear_ring, np.random.random((5, 2)))
def test_set_coords_nan(): geoms = np.array([point]) coords = np.array([[np.nan, np.inf]]) new_geoms = set_coordinates(geoms, coords) assert_equal(coords, get_coordinates(new_geoms))