def test_apply_0dim(): # a geometry input returns a geometry actual = apply(point, lambda x: x + 1) assert isinstance(actual, pygeos.Geometry) # a 0-dim array input returns a 0-dim array actual = apply(np.asarray(point), lambda x: x + 1) assert isinstance(actual, np.ndarray) assert actual.ndim == 0
def test_apply(geoms, include_z): geoms = np.array(geoms, np.object_) coordinates_before = get_coordinates(geoms, include_z=include_z) new_geoms = apply(geoms, lambda x: x + 1, include_z=include_z) assert new_geoms is not geoms coordinates_after = get_coordinates(new_geoms, include_z=include_z) assert_allclose(coordinates_before + 1, coordinates_after, equal_nan=True)
def test_apply(geoms): geoms = np.array(geoms, np.object) coordinates_before = get_coordinates(geoms) new_geoms = apply(geoms, lambda x: x + 1) assert new_geoms is not geoms coordinates_after = get_coordinates(new_geoms) assert_equal(coordinates_before + 1, coordinates_after)
def setup(self): # create irregular polygons by merging overlapping point buffers self.left = pygeos.union_all( pygeos.buffer(pygeos.points(np.random.random((500, 2)) * 500), 15) ) # shift this up and right self.right = pygeos.apply(self.left, lambda x: x + 50)
def drop_z(map_: gpd.GeoDataFrame): """Drops z attribute""" if pygeos.has_z(map_.geometry).any(): warnings.warn( "Geometry contains Z co-ordinates. Removed from Map3D (height attribute)" ) map_.geometry = pygeos.apply(map_.geometry, lambda x: x, include_z=False) return map_
def _prepare_input(geometry, prepare): """Prepare without modifying inplace""" if prepare: geometry = pygeos.apply(geometry, lambda x: x) # makes a copy pygeos.prepare(geometry) return geometry else: return geometry
def filter_process(session, file, action, wkt, **kwargs): """Wrapper function for the filtering process. Arguments: session (dict): Dictionary with session information. file (str): The full path of the source file. action (str): The filtering operation. wkt (str): Well-Known Text of the input geometry. **kwargs: Additional keyword arguments for the filtering operation. Returns: (tuple): - (str): Request ticket. - (str): Full path of the resulted file(s). - (bool): Whether operation succeeded. - (str): Error message in case of failure. """ try: crs = kwargs.pop('crs', None) read_options = kwargs.pop('read_options', {}) geovaex = GeoVaex(file, session['working_path'], crs=crs, read_options=read_options) if action == 'travel_distance' or action == 'travel_time': valhalla = Valhalla() distance = kwargs.pop('distance', None) time = kwargs.pop('time', None) costing = kwargs.pop('costing', None) if costing == '': costing = None lat, lon = wkt polygon = valhalla.isochrone( lat, lon, distance=distance, costing=costing ) if action == 'travel_distance' else valhalla.isochrone( lat, lon, time=time, costing=costing) if geovaex.gdf.geometry.crs.to_epsg() != 4326: from_ = pyproj.crs.CRS.from_epsg(4326) to_ = geovaex.gdf.geometry.crs transformer = pyproj.Transformer.from_crs(from_, to_, always_xy=True) def transform(coords): x, y = transformer.transform(*coords.T) return np.array([x, y]).T polygon = pg.apply(polygon, transform) wkt = pg.to_wkt(polygon) action = 'within' export = geovaex.filter_(action, wkt, **kwargs) except ResultedEmptyDataFrame as e: return (session['ticket'], None, True, str(e)) except Exception as e: return (session['ticket'], None, False, str(e)) return (session['ticket'], export, True, None)
def drop_z(map_: gpd.GeoDataFrame): """Drops z attribute""" output = map_.copy() if pygeos.has_z(map_.geometry.array.data).any(): warnings.warn( "Geometry contains Z co-ordinates. Removed from Map3D (height attribute)") output.geometry = pygeos.apply( map_.geometry.array.data, lambda x: x, include_z=False) return output
def test_threaded(self): for (geometry_1, geometry_2), value in zip(zip(*self.VALUE_GEOMETRIES), self.VALUE): geometry_1 = np.array([geometry_1], dtype=object) for _ in range(4 * cpu_count()): geometry_1 = np.concatenate([ geometry_1, apply(geometry_1[-2:], lambda x: x + randn(2)) ]) geometry_2 = np.array([geometry_2], dtype=object) for _ in range(4 * cpu_count()): geometry_2 = np.concatenate([ geometry_1, apply(geometry_2[-2:], lambda x: x + randn(2)) ]) assert np.allclose( self._similarity(geometry_1, geometry_2, force_thread=True), self._similarity(geometry_1, geometry_2, force_thread=False))
def test_set_unique(geom): a = {geom, pygeos.apply(geom, lambda x: x)} assert len(a) == 1
def test_neq(geom): assert geom != pygeos.apply(geom, lambda x: x + 1)
def test_eq(geom): assert geom == pygeos.apply(geom, lambda x: x)
def test_hash_same_not_equal(geom): assert hash(geom) != hash(pygeos.apply(geom, lambda x: x + 1))
def test_hash_same_equal(geom): assert hash(geom) == hash(pygeos.apply(geom, lambda x: x))
def test_apply_correct_coordinate_dimension(): # ensure that new geometry is 2D with include_z=False geom = line_string_z assert pygeos.get_coordinate_dimension(geom) == 3 new_geom = apply(geom, lambda x: x + 1, include_z=False) assert pygeos.get_coordinate_dimension(new_geom) == 2
}) print("Read {:,} dams in Puerto Rico".format(len(df))) ### Standardize data # SARPID is a string in other places df["SARPID"] = df.SARPID.astype("str") df["HasNetwork"] = df.upNetID.notnull() # WARNING: make sure to increment these when merging in with main dams dataset df["id"] = df.index.astype("uint32") df = df.set_index("id", drop=False) # convert to 2D and project to CRS # TODO: this is a hack that takes advantage of apply only supporting 2 dimensions df.geometry = pg.apply(df.geometry, lambda x: x) df.geometry = to_crs(df.geometry, src_crs, CRS) # We store total # size classes, rather than gained df["sizeclasses"] = (df.sizeclasses.fillna(0) + 1).astype("uint8") ### Join in network stats from above upstream_networks = (df[["upNetID"]].join(network_stats, on="upNetID").rename( columns={ "miles": "TotalUpstreamMiles", "free_miles": "FreeUpstreamMiles", })).drop(columns=["upNetID"]) downstream_networks = (df[["downNetID"]].join( network_stats[["free_miles", "miles"]].rename(columns={
def _prepare_with_copy(geometry): """Prepare without modifying inplace""" geometry = pygeos.apply(geometry, lambda x: x) # makes a copy pygeos.prepare(geometry) return geometry
def test_apply_check_shape(): def remove_coord(arr): return arr[:-1] with pytest.raises(ValueError): apply(linear_ring, remove_coord)