def test_affine_3d(self): g2 = load_wkt('LINESTRING(2.4 4.1, 2.4 3, 3 3)') g3 = load_wkt('LINESTRING(2.4 4.1 100.2, 2.4 3 132.8, 3 3 128.6)') # custom scale and translate matrix2d = (2, 0, 0, 2.5, -5, 4.1) matrix3d = (2, 0, 0, 0, 2.5, 0, 0, 0, 0.3048, -5, 4.1, 100) # Combinations of 2D and 3D geometries and matrices a22 = transform.affine(g2, matrix2d) a23 = transform.affine(g2, matrix3d) a32 = transform.affine(g3, matrix2d) a33 = transform.affine(g3, matrix3d) # Check dimensions self.assertFalse(a22.has_z) self.assertFalse(a23.has_z) self.assertTrue(a32.has_z) self.assertTrue(a33.has_z) # 2D equality checks expected2d = load_wkt('LINESTRING(-0.2 14.35, -0.2 11.6, 1 11.6)') expected3d = load_wkt('LINESTRING(-0.2 14.35 130.54096, '\ '-0.2 11.6 140.47744, 1 11.6 139.19728)') expected32 = load_wkt('LINESTRING(-0.2 14.35 100.2, '\ '-0.2 11.6 132.8, 1 11.6 128.6)') self.assertTrue(a22.almost_equals(expected2d)) self.assertTrue(a23.almost_equals(expected2d)) # Do explicit 3D check of coordinate values for a, e in zip(a32.coords, expected32.coords): for ap, ep in zip(a, e): self.assertAlmostEqual(ap, ep) for a, e in zip(a33.coords, expected3d.coords): for ap, ep in zip(a, e): self.assertAlmostEqual(ap, ep)
def test_scale(self): ls = load_wkt('LINESTRING(240 400 10, 240 300 30, 300 300 20)') # test defaults of 1.0 sls = transform.scale(ls) self.assertTrue(sls.equals(ls)) # different scaling in different dimensions sls = transform.scale(ls, 2, 3, 0.5) els = load_wkt('LINESTRING(210 500 5, 210 200 15, 330 200 10)') self.assertTrue(sls.equals(els)) # Do explicit 3D check of coordinate values for a, b in zip(sls.coords, els.coords): for ap, bp in zip(a, b): self.assertEqual(ap, bp) # retest with named parameters for the same result sls = transform.scale(geom=ls, xfact=2, yfact=3, zfact=0.5, origin='center') self.assertTrue(sls.equals(els)) ## other `origin` parameters # around the centroid sls = transform.scale(ls, 2, 3, 0.5, origin='centroid') els = load_wkt('LINESTRING(228.75 537.5, 228.75 237.5, 348.75 237.5)') self.assertTrue(sls.equals(els)) # around the second coordinate tuple sls = transform.scale(ls, 2, 3, 0.5, origin=ls.coords[1]) els = load_wkt('LINESTRING(240 600, 240 300, 360 300)') self.assertTrue(sls.equals(els)) # around some other 3D Point of origin sls = transform.scale(ls, 2, 3, 0.5, origin=Point(100, 200, 1000)) els = load_wkt('LINESTRING(380 800 505, 380 500 515, 500 500 510)') self.assertTrue(sls.equals(els)) # Do explicit 3D check of coordinate values for a, b in zip(sls.coords, els.coords): for ap, bp in zip(a, b): self.assertEqual(ap, bp)
def test_scale(self): ls = load_wkt('LINESTRING(240 400 10, 240 300 30, 300 300 20)') # test defaults of 1.0 sls = affinity.scale(ls) self.assertTrue(sls.equals(ls)) # different scaling in different dimensions sls = affinity.scale(ls, 2, 3, 0.5) els = load_wkt('LINESTRING(210 500 5, 210 200 15, 330 200 10)') self.assertTrue(sls.equals(els)) # Do explicit 3D check of coordinate values for a, b in zip(sls.coords, els.coords): for ap, bp in zip(a, b): self.assertEqual(ap, bp) # retest with named parameters for the same result sls = affinity.scale(geom=ls, xfact=2, yfact=3, zfact=0.5, origin='center') self.assertTrue(sls.equals(els)) ## other `origin` parameters # around the centroid sls = affinity.scale(ls, 2, 3, 0.5, origin='centroid') els = load_wkt('LINESTRING(228.75 537.5, 228.75 237.5, 348.75 237.5)') self.assertTrue(sls.equals(els)) # around the second coordinate tuple sls = affinity.scale(ls, 2, 3, 0.5, origin=ls.coords[1]) els = load_wkt('LINESTRING(240 600, 240 300, 360 300)') self.assertTrue(sls.equals(els)) # around some other 3D Point of origin sls = affinity.scale(ls, 2, 3, 0.5, origin=Point(100, 200, 1000)) els = load_wkt('LINESTRING(380 800 505, 380 500 515, 500 500 510)') self.assertTrue(sls.equals(els)) # Do explicit 3D check of coordinate values for a, b in zip(sls.coords, els.coords): for ap, bp in zip(a, b): self.assertEqual(ap, bp)
def test_rotate_angle_array(self): ls = load_wkt('LINESTRING(240 400, 240 300, 300 300)') els = load_wkt('LINESTRING(220 320, 320 320, 320 380)') # check with degrees theta = numpy.array([90.0]) rls = affinity.rotate(ls, theta) self.assertEqual(theta[0], 90.0) self.assertTrue(rls.equals(els)) # check with radians theta = numpy.array([pi / 2]) rls = affinity.rotate(ls, theta, use_radians=True) self.assertEqual(theta[0], pi / 2) self.assertTrue(rls.equals(els))
def test_affine_2d(self): g = load_wkt('LINESTRING(2.4 4.1, 2.4 3, 3 3)') # custom scale and translate expected2d = load_wkt('LINESTRING(-0.2 14.35, -0.2 11.6, 1 11.6)') matrix2d = (2, 0, 0, 2.5, -5, 4.1) a2 = transform.affine(g, matrix2d) self.assertTrue(a2.almost_equals(expected2d)) self.assertFalse(a2.has_z) # Make sure a 3D matrix does not make a 3D shape from a 2D input matrix3d = (2, 0, 0, 0, 2.5, 0, 0, 0, 10, -5, 4.1, 100) a3 = transform.affine(g, matrix3d) self.assertTrue(a3.almost_equals(expected2d)) self.assertFalse(a3.has_z)
def __init__(self, wkt, projection): if not isinstance(wkt, str): raise TypeError("'{}' object is not allowed".format(type(wkt))) if not isinstance(projection, str): raise TypeError("'{}' object is not allowed".format(type(projection))) try: load_wkt(wkt) except WKTReadingError: raise ValueError("The provided geometry is not a valid WKT") try: utils.get_sr(projection) except TypeError: raise ValueError("The provided projection is not a valid WKT") super().__init__(wkt, projection)
def test_affine_geom_types(self): # identity matrices, which should result with no transformation matrix2d = (1, 0, 0, 1, 0, 0) matrix3d = (1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0) # empty in, empty out empty2d = load_wkt('MULTIPOLYGON EMPTY') self.assertTrue(affinity.affine_transform(empty2d, matrix2d).is_empty) def test_geom(g2, g3=None): self.assertFalse(g2.has_z) a2 = affinity.affine_transform(g2, matrix2d) self.assertFalse(a2.has_z) self.assertTrue(g2.equals(a2)) if g3 is not None: self.assertTrue(g3.has_z) a3 = affinity.affine_transform(g3, matrix3d) self.assertTrue(a3.has_z) self.assertTrue(g3.equals(a3)) return pt2d = load_wkt('POINT(12.3 45.6)') pt3d = load_wkt('POINT(12.3 45.6 7.89)') test_geom(pt2d, pt3d) ls2d = load_wkt('LINESTRING(0.9 3.4, 0.7 2, 2.5 2.7)') ls3d = load_wkt('LINESTRING(0.9 3.4 3.3, 0.7 2 2.3, 2.5 2.7 5.5)') test_geom(ls2d, ls3d) test_geom(load_wkt('POLYGON((0.9 2.3, 0.5 1.1, 2.4 0.8, 0.9 2.3), ' '(1.1 1.7, 0.9 1.3, 1.4 1.2, 1.1 1.7), ' '(1.6 1.3, 1.7 1, 1.9 1.1, 1.6 1.3))')) test_geom(load_wkt( 'MULTIPOINT ((-300 300), (700 300), (-800 -1100), (200 -300))')) test_geom(load_wkt( 'MULTILINESTRING((0 0, -0.7 -0.7, 0.6 -1), ' '(-0.5 0.5, 0.7 0.6, 0 -0.6))')) test_geom(load_wkt( 'MULTIPOLYGON(((900 4300, -1100 -400, 900 -800, 900 4300)), ' '((1200 4300, 2300 4400, 1900 1000, 1200 4300)))')) # GeometryCollection fails, since it does not have a good constructor gc = load_wkt('GEOMETRYCOLLECTION(POINT(20 70),' ' POLYGON((60 70, 13 35, 60 -30, 60 70)),' ' LINESTRING(60 70, 50 100, 80 100))') self.assertRaises(TypeError, test_geom, gc) # TODO: fix this
def polygon_hole_cw_fully_on_rectangle_boundary(): """Polygon hole (CW) fully on rectangle boundary""" geom1 = load_wkt( "POLYGON ((0 0, 0 30, 30 30, 30 0, 0 0), (10 10, 10 20, 20 20, 20 10, 10 10))" ) geom2 = clip_by_rect(geom1, 10, 10, 20, 20) assert dump_wkt(geom2, rounding_precision=0) == "GEOMETRYCOLLECTION EMPTY"
def findCenters(newickFile, switchLo, switchHi, lossLo, lossHi): """This function takes as input a .newick file in the form <filename>.newick, and low and high values for costscape for both switches and losses. It returns a list of the centroids of each region in the costscape associated with the given .newick file.""" hostTree, parasiteTree, phi = newickFormatReader(newickFile) CVlist = reconcile.reconcile(parasiteTree, hostTree, phi, switchLo, switchHi, lossLo, lossHi) coordList = plotcosts.plotcosts(CVlist, lossLo, lossHi, switchLo, switchHi, "", False, False) polygonList = getNewCoordList(newickFile, switchLo, switchHi, lossLo, lossHi) pointList = [] for i in range(len(polygonList)): point = polygonList[i] numCommas = point.count(",") if numCommas > 1: # polygon case region = load_wkt(point) pointList.append(region.centroid.wkt) elif numCommas == 1: # line case x1 = coordList[i][0][0] y1 = coordList[i][0][1] x2 = coordList[i][1][0] y2 = coordList[i][1][1] midx = (x1 + x2) * 1.0 / 2 midy = (y1 + y2) * 1.0 / 2 pointList.append("POINT ({} {})".format(str(midx), str(midy))) else: # point case pointList.append("POINT {}".format(str(coordList[i][0]))) return pointList
def process(data, request): mode = request["mode"] if mode == "time": return {"time": [data]} elif mode == "meta": return {"meta": [None]} # load the geometry and transform it into the requested projection geometry = load_wkt(data["wkt"]) if data["projection"] != request["projection"]: geometry = utils.shapely_transform(geometry, data["projection"], request["projection"]) # take a shortcut when the geometry does not intersect the bbox if not geometry.intersects(box(*request["bbox"])): return { "values": np.full((1, request["height"], request["width"]), False, dtype=np.bool), "no_data_value": None, } return utils.rasterize_geoseries( geoseries=GeoSeries([geometry]) if not geometry.is_empty else None, bbox=request["bbox"], projection=request["projection"], height=request["height"], width=request["width"], )
def test_translate(self): ls = load_wkt('LINESTRING(240 400 10, 240 300 30, 300 300 20)') # test default offset of 0.0 tls = transform.translate(ls) self.assertTrue(tls.equals(ls)) # test all offsets tls = transform.translate(ls, 100, 400, -10) els = load_wkt('LINESTRING(340 800 0, 340 700 20, 400 700 10)') self.assertTrue(tls.equals(els)) # Do explicit 3D check of coordinate values for a, b in zip(tls.coords, els.coords): for ap, bp in zip(a, b): self.assertEqual(ap, bp) # retest with named parameters for the same result tls = transform.translate(geom=ls, xoff=100, yoff=400, zoff=-10) self.assertTrue(tls.equals(els))
def create_from_wkt(self, wkt, item_type, ingest_source, **attributes): ''' Create a single vector in the vector service Args: wkt (str): wkt representation of the geometry item_type (str): item_type of the vector ingest_source (str): source of the vector attributes: a set of key-value pairs of attributes Returns: id (str): string identifier of the vector created ''' # verify the "depth" of the attributes is single layer geojson = load_wkt(wkt).__geo_interface__ vector = { 'type': "Feature", 'geometry': geojson, 'properties': { 'item_type': item_type, 'ingest_source': ingest_source, 'attributes': attributes } } return self.create(vector)[0]
def standardize_polygons_str(data_str): """Given a POLYGON string, standardize the coordinates to a 1x1 grid. Input : data_str (taken from above) Output: tuple of polygon objects """ # find all of the polygons in the letter (for instance an A # needs to be constructed from 2 polygons) path_strs = re.findall("\(\(([^\)]+?)\)\)", data_str.strip()) # convert the data into a numpy array polygons_data = [] for path_str in path_strs: data = np.array([ tuple(map(float, x.split())) for x in path_str.strip().split(",")]) polygons_data.append(data) # standardize the coordinates min_coords = np.vstack(data.min(0) for data in polygons_data).min(0) max_coords = np.vstack(data.max(0) for data in polygons_data).max(0) for data in polygons_data: data[:, ] -= min_coords data[:, ] /= (max_coords - min_coords) polygons = [] for data in polygons_data: polygons.append(load_wkt( "POLYGON((%s))" % ",".join(" ".join(map(str, x)) for x in data))) return tuple(polygons)
def test_seed_with_res_list(self): # box from 10 10 to 80 80 with small spike/corner to -10 60 (upper left) geom = load_wkt( "POLYGON((10 10, 10 50, -10 60, 10 80, 80 80, 80 10, 10 10))") self.grid = TileGrid( SRS(4326), bbox=[-180, -90, 180, 90], res=[360 / 256, 360 / 720, 360 / 2000, 360 / 5000, 360 / 8000], ) self.tile_mgr = TileManager(self.grid, MockCache(), [self.source], "png", locker=DummyLocker()) task = self.make_geom_task(geom, SRS(4326), [0, 1, 2, 3, 4]) seeder = TileWalker(task, self.seed_pool, handle_uncached=True) seeder.walk() assert len(self.seed_pool.seeded_tiles) == 5 assert self.seed_pool.seeded_tiles[0] == set([(0, 0)]) assert self.grid.grid_sizes[1] == (3, 2) assert self.seed_pool.seeded_tiles[1] == set([(1, 0), (1, 1), (2, 0), (2, 1)]) assert self.grid.grid_sizes[2] == (8, 4) assert self.seed_pool.seeded_tiles[2] == set([(4, 2), (5, 2), (4, 3), (5, 3), (3, 3)]) assert self.grid.grid_sizes[3] == (20, 10) assert len(self.seed_pool.seeded_tiles[3]) == 5 * 5 + 2
def test_from_polygon_without_enough_tolerance(): poly = load_wkt('POLYGON ((0 0, 0.5 0, 0.5 0.5, 0 0.5, 0 0))') with pytest.raises(ValueError) as exc: voronoi_diagram(poly, tolerance=0.6) assert "Could not create Voronoi Diagram with the specified inputs" in str(exc.value) assert "Try running again with default tolerance value." in str(exc.value)
def process(data, request): mode = request["mode"] if mode == "time": return {"time": [data]} elif mode == "meta": return {"meta": [None]} # load the geometry and transform it into the requested projection geometry = load_wkt(data["wkt"]) if data["projection"] != request["projection"]: geometry = utils.shapely_transform( geometry, data["projection"], request["projection"] ) # take a shortcut when the geometry does not intersect the bbox x1, y1, x2, y2 = request["bbox"] if (x1 == x2) and (y1 == y2): # Don't do box(x1, y1, x2, y2), this gives an invalid geometry. bbox_geom = Point(x1, y1) else: bbox_geom = box(x1, y1, x2, y2) if not geometry.intersects(bbox_geom): return { "values": np.full( (1, request["height"], request["width"]), False, dtype=bool ), "no_data_value": None, } return utils.rasterize_geoseries( geoseries=GeoSeries([geometry]) if not geometry.is_empty else None, bbox=request["bbox"], projection=request["projection"], height=request["height"], width=request["width"], )
def test_from_polygon_without_floating_point_coordinates(): poly = load_wkt('POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))') with pytest.raises(ValueError) as exc: voronoi_diagram(poly, tolerance=0.1) assert "Could not create Voronoi Diagram with the specified inputs" in str(exc.value) assert "Try running again with default tolerance value." in str(exc.value)
def build_geometry(Entity): """Builds a geometry given an instance.""" try: geometry = load_wkt(Entity.geometry) except: geometry = box(0, 0, Entity.maxx, Entity.maxy) return geometry
def test_seed_with_res_list(self): if not load_wkt: raise SkipTest('no shapely installed') # box from 10 10 to 80 80 with small spike/corner to -10 60 (upper left) geom = load_wkt( "POLYGON((10 10, 10 50, -10 60, 10 80, 80 80, 80 10, 10 10))") self.grid = TileGrid( SRS(4326), bbox=[-180, -90, 180, 90], res=[360 / 256, 360 / 720, 360 / 2000, 360 / 5000, 360 / 8000]) self.tile_mgr = TileManager(self.grid, MockCache(), [self.source], 'png', locker=DummyLocker()) task = self.make_geom_task(geom, SRS(4326), [0, 1, 2, 3, 4]) seeder = TileWalker(task, self.seed_pool, handle_uncached=True) seeder.walk() eq_(len(self.seed_pool.seeded_tiles), 5) eq_(self.seed_pool.seeded_tiles[0], set([(0, 0)])) eq_(self.grid.grid_sizes[1], (3, 2)) eq_(self.seed_pool.seeded_tiles[1], set([(1, 0), (1, 1), (2, 0), (2, 1)])) eq_(self.grid.grid_sizes[2], (8, 4)) eq_(self.seed_pool.seeded_tiles[2], set([(4, 2), (5, 2), (4, 3), (5, 3), (3, 3)])) eq_(self.grid.grid_sizes[3], (20, 10)) eq_(len(self.seed_pool.seeded_tiles[3]), 5 * 5 + 2)
def test_smaller_envelope(): mp = MultiPoint(points=[(0.5, 0.5), (1.0, 1.0)]) poly = load_wkt('POLYGON ((0 0, 0.5 0, 0.5 0.5, 0 0.5, 0 0))') regions = voronoi_diagram(mp, envelope=poly) assert len(regions.geoms) == 2 assert sum(r.area for r in regions.geoms) > poly.area
def test_skew_xs_ys_array(self): ls = load_wkt('LINESTRING(240 400 10, 240 300 30, 300 300 20)') els = load_wkt('LINESTRING (253.39745962155615 417.3205080756888, ' '226.60254037844385 317.3205080756888, ' '286.60254037844385 282.67949192431126)') # check with degrees xs_ys = numpy.array([15.0, -30.0]) sls = affinity.skew(ls, xs_ys[0:1], xs_ys[1:2]) self.assertEqual(xs_ys[0], 15.0) self.assertEqual(xs_ys[1], -30.0) self.assertTrue(sls.almost_equals(els)) # check with radians xs_ys = numpy.array([pi / 12, -pi / 6]) sls = affinity.skew(ls, xs_ys[0:1], xs_ys[1:2], use_radians=True) self.assertEqual(xs_ys[0], pi / 12) self.assertEqual(xs_ys[1], -pi / 6) self.assertTrue(sls.almost_equals(els))
def _load_geometry(self, wkb_or_wkt): try: return load_wkb(wkb_or_wkt) except: try: return load_wkt(wkb_or_wkt) except: return None
def test_affine_params(self): g = load_wkt('LINESTRING(2.4 4.1, 2.4 3, 3 3)') self.assertRaises(TypeError, transform.affine, g, None) self.assertRaises(TypeError, transform.affine, g, '123456') self.assertRaises(ValueError, transform.affine, g, [1, 2, 3, 4, 5, 6, 7, 8, 9]) self.assertRaises(AttributeError, transform.affine, None, [1, 2, 3, 4, 5, 6])
def test_from_multipoint_with_tolerace_without_floating_point_coordinates(): """This multipoint will not work with a tolerance value.""" mp = load_wkt('MULTIPOINT (0 0, 1 0, 1 2, 0 1)') with pytest.raises(ValueError) as exc: voronoi_diagram(mp, tolerance=0.1) assert "Could not create Voronoi Diagram with the specified inputs" in str(exc.value) assert "Try running again with default tolerance value." in str(exc.value)
def polygon_overlapping_rectangle(): """Polygon overlapping rectangle""" wkt = "POLYGON ((0 0, 0 30, 30 30, 30 0, 0 0), (10 10, 20 10, 20 20, 10 20, 10 10))" geom1 = load_wkt(wkt) geom2 = clip_by_rect(geom1, 5, 5, 15, 15) assert dump_wkt( geom2, rounding_precision=0 ) == "POLYGON ((5 5, 5 15, 10 15, 10 10, 15 10, 15 5, 5 5))"
def test_scalerotatetranslate(self): ls = load_wkt('LINESTRING(240 400 10, 240 300 30, 300 300 20)') # test defaults tls = transform.translate(ls) self.assertTrue(tls.equals(ls)) # test all three tls = transform.scalerotatetranslate(ls, 2, 3, 0.5, 30, 100, 400, -10) els = load_wkt('LINESTRING(243.03847577293368 849.9038105676659 -5, '\ '393.0384757729336200 590.0961894323343100 5, '\ '496.9615242270662600 650.0961894323343100 0)') self.assertTrue(tls.almost_equals(els)) # Do explicit 3D check of coordinate values for a, b in zip(tls.coords, els.coords): for ap, bp in zip(a, b): self.assertEqual(ap, bp) # recheck with named parameters tls = transform.scalerotatetranslate(geom=ls, xfact=2, yfact=3, zfact=0.5, angle=30, xoff=100, yoff=400, zoff=-10, origin='center', use_radians=False) self.assertTrue(tls.almost_equals(els)) # test scale and rotate in radians tls = transform.scalerotatetranslate(ls, 2, 3, 0.5, pi / 6, use_radians=True) els = load_wkt('LINESTRING(143.03847577293368 449.90381056766591, '\ '293.0384757729336200 190.0961894323343100, '\ '396.9615242270662600 250.0961894323343100)') self.assertTrue(tls.almost_equals(els)) # test offsets only tls = transform.scalerotatetranslate(ls, xoff=100, yoff=400, zoff=-10) els = load_wkt('LINESTRING(340 800, 340 700, 400 700)') self.assertTrue(tls.almost_equals(els)) # Do explicit 3D check of coordinate values for a, b in zip(tls.coords, els.coords): for ap, bp in zip(a, b): self.assertEqual(ap, bp)
def __init__ (self, geometry, unique_id, dateRange = 10, completionDate = date.today()): # default is search for the past 10 days data self.email = '*****@*****.**' self.password = '******' self.startDate = completionDate - timedelta(days=dateRange) self.completionDate = completionDate self.geometry = geometry self.centroid = load_wkt(geometry).centroid self.unique_id = unique_id
def test_from_multipoint_without_floating_point_coordinates(): """A Multipoint with the same "shape" as the above Polygon raises the same error...""" mp = load_wkt('MULTIPOINT (0 0, 1 0, 1 1, 0 1)') with pytest.raises(ValueError) as exc: voronoi_diagram(mp, tolerance=0.1) assert "Could not create Voronoi Diagram with the specified inputs" in str(exc.value) assert "Try running again with default tolerance value." in str(exc.value)
def test_affine_params(self): g = load_wkt('LINESTRING(2.4 4.1, 2.4 3, 3 3)') self.assertRaises( TypeError, affinity.affine_transform, g, None) self.assertRaises( TypeError, affinity.affine_transform, g, '123456') self.assertRaises(ValueError, affinity.affine_transform, g, [1, 2, 3, 4, 5, 6, 7, 8, 9]) self.assertRaises(AttributeError, affinity.affine_transform, None, [1, 2, 3, 4, 5, 6])
def _deserialize(self, value, att, obj): try: geometry = load_wkt(value) return mapping(geometry) except WKTReadingError as e: try: raise ValidationError(e.message) # python3 hack for error message handling except AttributeError: raise ValidationError(str(e))
def _load_geometry(self, geometry_spec): if isinstance(geometry_spec, BaseGeometry): return geometry_spec try: return load_wkb(geometry_spec) except: try: return load_wkt(geometry_spec) except: return None
def test_larger_envelope(): """When the envelope we specify is larger than the area of the input feature, the created regions should expand to fill that area.""" mp = MultiPoint(points=[(0.5, 0.5), (1.0, 1.0)]) poly = load_wkt('POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))') regions = voronoi_diagram(mp, envelope=poly) assert len(regions.geoms) == 2 assert sum(r.area for r in regions.geoms) == poly.area
def calculate_centroid(self): centroid = None for geometry in self.geometries: if geometry.role == GeometryRole.Boundary and geometry.crs == CRS.WGS84: p1 = load_wkt(geometry.to_wkt(with_crs=False)) centroid = Geometry( p1.centroid.wkt.strip("POINT (").strip(")"), GeometryType.Point, GeometryRole.Centroid, "WGS84 Centroid", CRS.WGS84) self.geometries.append(centroid) return centroid
def return_locations_in_polygon(): data = request.json vehicleData = [] with open(fileName) as f: vehiclesSelect = json.loads(f.read()) polygon = load_wkt(data['shape']) for i in range(0, len(vehiclesSelect)): p = Point(vehiclesSelect[i].get('location').get('lng'), vehiclesSelect[i].get('location').get('lat')) if polygon.contains(p): vehicleData.append(vehiclesSelect[i]) return jsonify(vehicleData)
def test_rotate(self): ls = load_wkt('LINESTRING(240 400, 240 300, 300 300)') # counter-clockwise degrees rls = transform.rotate(ls, 90) els = load_wkt('LINESTRING(220 320, 320 320, 320 380)') self.assertTrue(rls.equals(els)) # retest with named parameters for the same result rls = transform.rotate(geom=ls, angle=90, origin='center') self.assertTrue(rls.equals(els)) # clockwise radians rls = transform.rotate(ls, -pi/2, use_radians=True) els = load_wkt('LINESTRING(320 380, 220 380, 220 320)') self.assertTrue(rls.equals(els)) ## other `origin` parameters # around the centroid rls = transform.rotate(ls, 90, origin='centroid') els = load_wkt('LINESTRING(182.5 320, 282.5 320, 282.5 380)') self.assertTrue(rls.equals(els)) # around the second coordinate tuple rls = transform.rotate(ls, 90, origin=ls.coords[1]) els = load_wkt('LINESTRING(140 300, 240 300, 240 360)') self.assertTrue(rls.equals(els)) # around the absolute Point of origin rls = transform.rotate(ls, 90, origin=Point(0,0)) els = load_wkt('LINESTRING(-400 240, -300 240, -300 300)') self.assertTrue(rls.equals(els))
def test_seed_with_geom(self): if not load_wkt: raise SkipTest('no shapely installed') # box from 10 10 to 80 80 with small spike/corner to -10 60 (upper left) geom = load_wkt("POLYGON((10 10, 10 50, -10 60, 10 80, 80 80, 80 10, 10 10))") task = self.make_geom_task(geom, SRS(4326), [0, 1, 2, 3, 4]) seeder = TileWalker(task, self.seed_pool, handle_uncached=True) seeder.walk() eq_(len(self.seed_pool.seeded_tiles), 5) eq_(self.seed_pool.seeded_tiles[0], set([(0, 0)])) eq_(self.seed_pool.seeded_tiles[1], set([(0, 0), (1, 0)])) eq_(self.seed_pool.seeded_tiles[2], set([(1, 1), (2, 1)])) eq_(self.seed_pool.seeded_tiles[3], set([(4, 2), (5, 2), (4, 3), (5, 3), (3, 3)])) eq_(len(self.seed_pool.seeded_tiles[4]), 4*4+2)
def test_scalerotatetranslate(self): ls = load_wkt('LINESTRING(240 400 10, 240 300 30, 300 300 20)') # test defaults tls = transform.translate(ls) self.assertTrue(tls.equals(ls)) # test all three tls = transform.scalerotatetranslate(ls, 2, 3, 0.5, 30, 100, 400, -10) els = load_wkt('LINESTRING(243.03847577293368 849.9038105676659 -5, '\ '393.0384757729336200 590.0961894323343100 5, '\ '496.9615242270662600 650.0961894323343100 0)') self.assertTrue(tls.almost_equals(els)) # Do explicit 3D check of coordinate values for a, b in zip(tls.coords, els.coords): for ap, bp in zip(a, b): self.assertEqual(ap, bp) # recheck with named parameters tls = transform.scalerotatetranslate(geom=ls, xfact=2, yfact=3, zfact=0.5, angle=30, xoff=100, yoff=400, zoff=-10, origin='center', use_radians=False) self.assertTrue(tls.almost_equals(els)) # test scale and rotate in radians tls = transform.scalerotatetranslate(ls, 2, 3, 0.5, pi/6, use_radians=True) els = load_wkt('LINESTRING(143.03847577293368 449.90381056766591, '\ '293.0384757729336200 190.0961894323343100, '\ '396.9615242270662600 250.0961894323343100)') self.assertTrue(tls.almost_equals(els)) # test offsets only tls = transform.scalerotatetranslate(ls, xoff=100, yoff=400, zoff=-10) els = load_wkt('LINESTRING(340 800, 340 700, 400 700)') self.assertTrue(tls.almost_equals(els)) # Do explicit 3D check of coordinate values for a, b in zip(tls.coords, els.coords): for ap, bp in zip(a, b): self.assertEqual(ap, bp)
def _load_geometry(self, geometry_spec): if isinstance(geometry_spec, BaseGeometry): return geometry_spec if isinstance(geometry_spec, dict): return SimpleShape(geometry_spec['coordinates'], geometry_spec["type"]) try: return load_wkb(geometry_spec) except Exception: try: return load_wkt(geometry_spec) except Exception: return None
def test_skew(self): ls = load_wkt('LINESTRING(240 400 10, 240 300 30, 300 300 20)') # test default shear angles of 0.0 sls = transform.skew(ls) self.assertTrue(sls.equals(ls)) # different shearing in x- and y-directions sls = transform.skew(ls, 15, -30) els = load_wkt('LINESTRING (253.39745962155615 417.3205080756888, '\ '226.60254037844385 317.3205080756888, '\ '286.60254037844385 282.67949192431126)') self.assertTrue(sls.almost_equals(els)) # retest with radians for the same result sls = transform.skew(ls, pi/12, -pi/6, use_radians=True) self.assertTrue(sls.almost_equals(els)) # retest with named parameters for the same result sls = transform.skew(geom=ls, xs=15, ys=-30, origin='center', use_radians=False) self.assertTrue(sls.almost_equals(els)) ## other `origin` parameters # around the centroid sls = transform.skew(ls, 15, -30, origin='centroid') els = load_wkt('LINESTRING(258.42150697963973 406.49519052838332, '\ '231.6265877365273980 306.4951905283833185, '\ '291.6265877365274264 271.8541743770057337)') self.assertTrue(sls.almost_equals(els)) # around the second coordinate tuple sls = transform.skew(ls, 15, -30, origin=ls.coords[1]) els = load_wkt('LINESTRING(266.7949192431123038 400, 240 300, '\ '300 265.3589838486224153)') self.assertTrue(sls.almost_equals(els)) # around the absolute Point of origin sls = transform.skew(ls, 15, -30, origin=Point(0,0)) els = load_wkt('LINESTRING(347.179676972449101 261.435935394489832, '\ '320.3847577293367976 161.4359353944898317, '\ '380.3847577293367976 126.7949192431122754)') self.assertTrue(sls.almost_equals(els))
def _loadGeometry(self, geometrySpec): """ A private method to convert a (E)WKB or (E)WKT to a Shapely geometry. """ if type(geometrySpec) is str and geometrySpec.startswith('POLYGON Z'): try: geometry = load_wkt(geometrySpec) except Exception: geometry = None else: try: geometry = load_wkb(geometrySpec) except Exception: geometry = None if geometry is None: raise ValueError('Failed to convert WKT or WKB to a Shapely geometry') return geometry
def test_seed_with_res_list(self): if not load_wkt: raise SkipTest('no shapely installed') # box from 10 10 to 80 80 with small spike/corner to -10 60 (upper left) geom = load_wkt("POLYGON((10 10, 10 50, -10 60, 10 80, 80 80, 80 10, 10 10))") self.grid = TileGrid(SRS(4326), bbox=[-180, -90, 180, 90], res=[360/256, 360/720, 360/2000, 360/5000, 360/8000]) self.tile_mgr = TileManager(self.grid, MockCache(), [self.source], 'png') task = self.make_geom_task(geom, SRS(4326), [0, 1, 2, 3, 4]) seeder = TileWalker(task, self.seed_pool, handle_uncached=True) seeder.walk() eq_(len(self.seed_pool.seeded_tiles), 5) eq_(self.seed_pool.seeded_tiles[0], set([(0, 0)])) eq_(self.grid.grid_sizes[1], (3, 2)) eq_(self.seed_pool.seeded_tiles[1], set([(1, 0), (1, 1), (2, 0), (2, 1)])) eq_(self.grid.grid_sizes[2], (8, 4)) eq_(self.seed_pool.seeded_tiles[2], set([(4, 2), (5, 2), (4, 3), (5, 3), (3, 3)])) eq_(self.grid.grid_sizes[3], (20, 10)) eq_(len(self.seed_pool.seeded_tiles[3]), 5*5+2)
def aggregate_query(self, searchAreaWkt, agg_def, query=None, start_date=None, end_date=None, count=10, index=default_index): """Aggregates results of a query into buckets defined by the 'agg_def' parameter. The aggregations are represented by dicts containing a 'name' key and a 'terms' key holding a list of the aggregation buckets. Each bucket element is a dict containing a 'term' key containing the term used for this bucket, a 'count' key containing the count of items that match this bucket, and an 'aggregations' key containing any child aggregations. Args: searchAreaWkt (str): wkt representation of the geometry agg_def (str or AggregationDef): the aggregation definitions query (str): a valid Elasticsearch query string to constrain the items going into the aggregation start_date (str): either an ISO-8601 date string or a 'now' expression (e.g. "now-6d" or just "now") end_date (str): either an ISO-8601 date string or a 'now' expression (e.g. "now-6d" or just "now") count (int): the number of buckets to include in the aggregations (the top N will be returned) index (str): the index (or alias or wildcard index expression) to run aggregations against, set to None for the entire set of vector indexes Returns: results (list): A (usually single-element) list of dict objects containing the aggregation results. """ geojson = load_wkt(searchAreaWkt).__geo_interface__ aggs_str = str(agg_def) # could be string or AggregationDef params = { "count": count, "aggs": aggs_str } if query: params['query'] = query if start_date: params['start_date'] = start_date if end_date: params['end_date'] = end_date url = self.aggregations_by_index_url % index if index else self.aggregations_url r = self.gbdx_connection.post(url, params=params, json=geojson) r.raise_for_status() return r.json(object_pairs_hook=OrderedDict)['aggregations']
def test_polygon_shell_cc_fully_on_rectangle_boundary(): """Polygon shell (CW) fully on rectangle boundary""" geom1 = load_wkt("POLYGON ((10 10, 10 20, 20 20, 20 10, 10 10))") geom2 = clip_by_rect(geom1, 10, 10, 20, 20) assert dump_wkt(geom2, rounding_precision=0) == "POLYGON ((10 10, 20 10, 20 20, 10 20, 10 10))"
def polygon_fully_within_rectangle(): """Polygon fully within rectangle""" wkt = "POLYGON ((1 1, 1 30, 30 30, 30 1, 1 1), (10 10, 20 10, 20 20, 10 20, 10 10))" geom1 = load_wkt(wkt) geom2 = clip_by_rect(geom1, 0, 0, 40, 40) assert dump_wkt(geom2, rounding_precision=0) == wkt
def test_point_outside(): """Point outside""" geom1 = load_wkt("POINT (0 0)") geom2 = clip_by_rect(geom1, 10, 10, 20, 20) assert dump_wkt(geom2, rounding_precision=0) == "GEOMETRYCOLLECTION EMPTY"
def test_line_splitting_rectangle(): """Line splitting rectangle""" geom1 = load_wkt("LINESTRING (10 5, 25 20)") geom2 = clip_by_rect(geom1, 10, 10, 20, 20) assert dump_wkt(geom2, rounding_precision=0) == "LINESTRING (15 10, 20 15)"
def test_line_on_boundary(): """Line on boundary""" geom1 = load_wkt("LINESTRING (10 15, 10 10, 15 10)") geom2 = clip_by_rect(geom1, 10, 10, 20, 20) assert dump_wkt(geom2, rounding_precision=0) == "GEOMETRYCOLLECTION EMPTY"
from shapely import affinity from descartes.patch import PolygonPatch from figures import SIZE, BLUE, GRAY, set_limits, add_origin fig = pyplot.figure(1, figsize=SIZE, dpi=90) # Geometry from JTS TestBuilder with fixed precision model of 100.0 # Using CreateShape > FontGlyphSanSerif and A = triangle.wkt from scale.py R = load_wkt( """\ POLYGON((2.218 2.204, 2.273 2.18, 2.328 2.144, 2.435 2.042, 2.541 1.895, 2.647 1.702, 3 1, 2.626 1, 2.298 1.659, 2.235 1.777, 2.173 1.873, 2.112 1.948, 2.051 2.001, 1.986 2.038, 1.91 2.064, 1.823 2.08, 1.726 2.085, 1.347 2.085, 1.347 1, 1 1, 1 3.567, 1.784 3.567, 1.99 3.556, 2.168 3.521, 2.319 3.464, 2.441 3.383, 2.492 3.334, 2.536 3.279, 2.604 3.152, 2.644 3.002, 2.658 2.828, 2.651 2.712, 2.63 2.606, 2.594 2.51, 2.545 2.425, 2.482 2.352, 2.407 2.29, 2.319 2.241, 2.218 2.204), (1.347 3.282, 1.347 2.371, 1.784 2.371, 1.902 2.378, 2.004 2.4, 2.091 2.436, 2.163 2.487, 2.219 2.552, 2.259 2.63, 2.283 2.722, 2.291 2.828, 2.283 2.933, 2.259 3.025, 2.219 3.103, 2.163 3.167, 2.091 3.217, 2.004 3.253, 1.902 3.275, 1.784 3.282, 1.347 3.282))""" ) # 1 ax = fig.add_subplot(121) patch1a = PolygonPatch(R, facecolor=GRAY, edgecolor=GRAY, alpha=0.5, zorder=1) skewR = affinity.skew(R, xs=20, origin=(1, 1)) patch1b = PolygonPatch(skewR, facecolor=BLUE, edgecolor=BLUE, alpha=0.5, zorder=2) ax.add_patch(patch1a) ax.add_patch(patch1b)
def test_line_inside(): """Line inside""" geom1 = load_wkt("LINESTRING (15 15, 16 15)") geom2 = clip_by_rect(geom1, 10, 10, 20, 20) assert dump_wkt(geom2, rounding_precision=0) == "LINESTRING (15 15, 16 15)"
def test_line_outside(): """Line outside""" geom1 = load_wkt("LINESTRING (0 0, -5 5)") geom2 = clip_by_rect(geom1, 10, 10, 20, 20) assert dump_wkt(geom2, rounding_precision=0) == "GEOMETRYCOLLECTION EMPTY"
def polygon_hole_cw_fully_on_rectangle_boundary(): """Polygon hole (CW) fully on rectangle boundary""" geom1 = load_wkt("POLYGON ((0 0, 0 30, 30 30, 30 0, 0 0), (10 10, 10 20, 20 20, 20 10, 10 10))") geom2 = clip_by_rect(geom1, 10, 10, 20, 20) assert dump_wkt(geom2, rounding_precision=0) == "GEOMETRYCOLLECTION EMPTY"
def test_point_inside(): """Point inside""" geom1 = load_wkt("POINT (15 15)") geom2 = clip_by_rect(geom1, 10, 10, 20, 20) assert dump_wkt(geom2, rounding_precision=0) == "POINT (15 15)"
def test_point_on_boundary(): """Point on boundary""" geom1 = load_wkt("POINT (15 10)") geom2 = clip_by_rect(geom1, 10, 10, 20, 20) assert dump_wkt(geom2, rounding_precision=0) == "GEOMETRYCOLLECTION EMPTY"