예제 #1
0
파일: point.py 프로젝트: mwtoews/shapely
    def __new__(self, *args):
        if len(args) == 0:
            # empty geometry
            # TODO better constructor
            return shapely.from_wkt("POINT EMPTY")
        elif len(args) > 3:
            raise TypeError(
                "Point() takes at most 3 arguments ({} given)".format(
                    len(args)))
        elif len(args) == 1:
            coords = args[0]
            if isinstance(coords, Point):
                return coords

            # Accept either (x, y) or [(x, y)]
            if not hasattr(coords, "__getitem__"):  # generators
                coords = list(coords)

            if isinstance(coords[0], tuple):
                coords = coords[0]

            geom = shapely.points(coords)
        else:
            # 2 or 3 args
            geom = shapely.points(*args)

        if not isinstance(geom, Point):
            raise ValueError("Invalid values passed to Point constructor")
        return geom
예제 #2
0
def test_dwithin():
    p1 = shapely.points(50, 4)
    p2 = shapely.points(50.1, 4.1)
    actual = shapely.dwithin([p1, p2, None], p1, distance=0.05)
    np.testing.assert_equal(actual, [True, False, False])
    assert actual.dtype == np.bool_
    actual = shapely.dwithin([p1, p2, None], p1, distance=0.2)
    np.testing.assert_allclose(actual, [True, True, False])
    assert actual.dtype == np.bool_

    # an array of distances
    actual = shapely.dwithin(p1, p2, distance=[0.05, 0.2, np.nan])
    np.testing.assert_allclose(actual, [False, True, False])
예제 #3
0
 def setup(self):
     # create irregular polygons by merging overlapping point buffers
     self.left = shapely.union_all(
         shapely.buffer(shapely.points(np.random.random((500, 2)) * 500),
                        15))
     # shift this up and right
     self.right = shapely.transform(self.left, lambda x: x + 50)
예제 #4
0
def test_from_wkb_hex():
    # HEX form
    expected = shapely.points(1, 1)
    actual = shapely.from_wkb("0101000000000000000000F03F000000000000F03F")
    assert_geometries_equal(actual, expected)
    actual = shapely.from_wkb(b"0101000000000000000000F03F000000000000F03F")
    assert_geometries_equal(actual, expected)
예제 #5
0
def test_to_wkb_hex():
    point = shapely.points(1, 1)
    actual = shapely.to_wkb(point, hex=True, byte_order=1)
    le = "01"
    point_type = "01000000"
    coord = "000000000000F03F"  # 1.0 as double (LE)
    assert actual == le + point_type + 2 * coord
예제 #6
0
def test_from_wkt():
    expected = shapely.points(1, 1)
    actual = shapely.from_wkt("POINT (1 1)")
    assert_geometries_equal(actual, expected)
    # also accept bytes
    actual = shapely.from_wkt(b"POINT (1 1)")
    assert_geometries_equal(actual, expected)
예제 #7
0
def test_to_wkb_3D():
    point_z = shapely.points(1, 1, 1)
    actual = shapely.to_wkb(point_z, byte_order=1)
    # fmt: off
    assert actual == b"\x01\x01\x00\x00\x80\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?"  # noqa
    # fmt: on
    actual = shapely.to_wkb(point_z, output_dimension=2, byte_order=1)
    assert actual == POINT11_WKB
예제 #8
0
def test_equals_exact_tolerance():
    # specifying tolerance
    p1 = shapely.points(50, 4)
    p2 = shapely.points(50.1, 4.1)
    actual = shapely.equals_exact([p1, p2, None], p1, tolerance=0.05)
    np.testing.assert_allclose(actual, [True, False, False])
    assert actual.dtype == np.bool_
    actual = shapely.equals_exact([p1, p2, None], p1, tolerance=0.2)
    np.testing.assert_allclose(actual, [True, True, False])
    assert actual.dtype == np.bool_

    # default value for tolerance
    assert shapely.equals_exact(p1, p1).item() is True
    assert shapely.equals_exact(p1, p2).item() is False

    # an array of tolerances
    actual = shapely.equals_exact(p1, p2, tolerance=[0.05, 0.2, np.nan])
    np.testing.assert_allclose(actual, [False, True, False])
예제 #9
0
def test_points_out(indices, expected):
    out = np.empty(4, dtype=object)
    out[2] = empty_point
    actual = shapely.points(
        [[2, 3], [2, 3]],
        indices=indices,
        out=out,
    )
    assert_geometries_equal(out, expected)
    assert actual is out
예제 #10
0
def test_destroy_prepared():
    arr = np.array([shapely.points(1, 1), None, shapely.box(0, 0, 1, 1)])
    shapely.prepare(arr)
    assert arr[0]._ptr_prepared != 0
    assert arr[2]._ptr_prepared != 0
    shapely.destroy_prepared(arr)
    assert arr[0]._ptr_prepared == 0
    assert arr[1] is None
    assert arr[2]._ptr_prepared == 0
    shapely.destroy_prepared(arr)  # does not error
예제 #11
0
def test_to_wkb_byte_order():
    point = shapely.points(1.0, 1.0)
    be = b"\x00"
    le = b"\x01"
    point_type = b"\x01\x00\x00\x00"  # 1 as 32-bit uint (LE)
    coord = b"\x00\x00\x00\x00\x00\x00\xf0?"  # 1.0 as double (LE)

    assert shapely.to_wkb(point, byte_order=1) == le + point_type + 2 * coord
    assert (shapely.to_wkb(point, byte_order=0) == be + point_type[::-1] +
            2 * coord[::-1])
예제 #12
0
def test_to_wkt():
    point = shapely.points(1, 1)
    actual = shapely.to_wkt(point)
    assert actual == "POINT (1 1)"

    actual = shapely.to_wkt(point, trim=False)
    assert actual == "POINT (1.000000 1.000000)"

    actual = shapely.to_wkt(point, rounding_precision=3, trim=False)
    assert actual == "POINT (1.000 1.000)"
예제 #13
0
def _construct_points(x, y):
    x, y = np.asanyarray(x), np.asanyarray(y)
    if x.shape != y.shape:
        raise ValueError("X and Y shapes must be equivalent.")

    if x.dtype != np.float64:
        x = x.astype(np.float64)
    if y.dtype != np.float64:
        y = y.astype(np.float64)

    return shapely.points(x, y)
예제 #14
0
 def setup(self):
     # create irregular polygons by merging overlapping point buffers
     self.polygon = shapely.union_all(
         shapely.buffer(shapely.points(np.random.random((1000, 2)) * 500),
                        10))
     xmin = np.random.random(100) * 100
     xmax = xmin + 100
     ymin = np.random.random(100) * 100
     ymax = ymin + 100
     self.bounds = np.array([xmin, ymin, xmax, ymax]).T
     self.boxes = shapely.box(xmin, ymin, xmax, ymax)
예제 #15
0
def test_to_wkt_3D():
    # 3D points
    point_z = shapely.points(1, 1, 1)
    actual = shapely.to_wkt(point_z)
    assert actual == "POINT Z (1 1 1)"
    actual = shapely.to_wkt(point_z, output_dimension=3)
    assert actual == "POINT Z (1 1 1)"

    actual = shapely.to_wkt(point_z, output_dimension=2)
    assert actual == "POINT (1 1)"

    actual = shapely.to_wkt(point_z, old_3d=True)
    assert actual == "POINT (1 1 1)"
예제 #16
0
def test_prepare():
    arr = np.array([shapely.points(1, 1), None, shapely.box(0, 0, 1, 1)])
    assert arr[0]._ptr_prepared == 0
    assert arr[2]._ptr_prepared == 0
    shapely.prepare(arr)
    assert arr[0]._ptr_prepared != 0
    assert arr[1] is None
    assert arr[2]._ptr_prepared != 0

    # preparing again actually does nothing
    original = arr[0]._ptr_prepared
    shapely.prepare(arr)
    assert arr[0]._ptr_prepared == original
예제 #17
0
    def __new__(self, *args):
        """
        Parameters
        ----------
        There are 2 cases:

        1) 1 parameter: this must satisfy the numpy array protocol.
        2) 2 or more parameters: x, y, z : float
            Easting, northing, and elevation.
        """
        if len(args) == 0:
            # empty geometry
            # TODO better constructor
            return shapely.from_wkt("POINT EMPTY")
        elif len(args) > 3:
            raise TypeError(
                "Point() takes at most 3 arguments ({} given)".format(len(args))
            )
        elif len(args) == 1:
            coords = args[0]
            if isinstance(coords, Point):
                return coords

            # Accept either (x, y) or [(x, y)]
            if not hasattr(coords, "__getitem__"):  # generators
                coords = list(coords)

            if isinstance(coords[0], tuple):
                coords = coords[0]

            geom = shapely.points(coords)
        else:
            # 2 or 3 args
            geom = shapely.points(*args)

        if not isinstance(geom, Point):
            raise ValueError("Invalid values passed to Point constructor")
        return geom
예제 #18
0
def test_to_wkb_srid():
    # hex representation of POINT (0 0) with SRID=4
    ewkb = "01010000200400000000000000000000000000000000000000"
    wkb = "010100000000000000000000000000000000000000"

    actual = shapely.from_wkb(ewkb)
    assert shapely.to_wkt(actual, trim=True) == "POINT (0 0)"

    assert shapely.to_wkb(actual, hex=True, byte_order=1) == wkb
    assert shapely.to_wkb(actual, hex=True, include_srid=True, byte_order=1) == ewkb

    point = shapely.points(1, 1)
    point_with_srid = shapely.set_srid(point, np.int32(4326))
    result = shapely.to_wkb(point_with_srid, include_srid=True, byte_order=1)
    assert np.frombuffer(result[5:9], "<u4").item() == 4326
예제 #19
0
    def setup(self):
        # create irregular polygons my merging overlapping point buffers
        self.polygons = shapely.get_parts(
            shapely.union_all(
                shapely.buffer(
                    shapely.points(np.random.random((2000, 2)) * 500), 5)))
        self.tree = shapely.STRtree(self.polygons)
        # initialize the tree by making a tiny query first
        self.tree.query(shapely.points(0, 0))

        # create points that extend beyond the domain of the above polygons to ensure
        # some don't overlap
        self.points = shapely.points((np.random.random((2000, 2)) * 750) - 125)
        self.point_tree = shapely.STRtree(
            shapely.points(np.random.random((2000, 2)) * 750))
        self.point_tree.query(shapely.points(0, 0))

        # create points on a grid for testing equidistant nearest neighbors
        # creates 2025 points
        grid_coords = np.mgrid[:45, :45].T.reshape(-1, 2)
        self.grid_point_tree = shapely.STRtree(shapely.points(grid_coords))
        self.grid_points = shapely.points(grid_coords + 0.5)
예제 #20
0
 def setup(self):
     self.coords = np.random.random((10000, 2))
     self.points = shapely.points(self.coords)
예제 #21
0
def test_to_wkb():
    point = shapely.points(1, 1)
    actual = shapely.to_wkb(point, byte_order=1)
    assert actual == POINT11_WKB
예제 #22
0
def test_relate():
    p1 = shapely.points(0, 0)
    p2 = shapely.points(1, 1)
    actual = shapely.relate(p1, p2)
    assert isinstance(actual, str)
    assert actual == "FF0FFF0F2"
예제 #23
0
def test_shared_paths_non_linestring():
    g1 = shapely.linestrings([(0, 0), (1, 0), (1, 1)])
    g2 = shapely.points(0, 1)
    with pytest.raises(shapely.GEOSException):
        shapely.shared_paths(g1, g2)
예제 #24
0
def test_from_wkb():
    expected = shapely.points(1, 1)
    actual = shapely.from_wkb(POINT11_WKB)
    assert_geometries_equal(actual, expected)
예제 #25
0
 def setup(self):
     self.points = shapely.points(np.random.random((100000, 2)))
     self.polygon = shapely.polygons(np.random.random((3, 2)))
예제 #26
0
 def time_tree_create(self):
     tree = shapely.STRtree(self.polygons)
     tree.query(shapely.points(0, 0))
예제 #27
0
def test_line_locate_point_geom_array():
    point = shapely.points(0, 1)
    actual = shapely.line_locate_point([line_string, linear_ring], point)
    np.testing.assert_allclose(actual, [0.0, 3.0])
예제 #28
0
import sys
from contextlib import contextmanager

import numpy as np
import pytest

import shapely

shapely20_todo = pytest.mark.xfail(
    strict=False, reason="Not yet implemented for Shapely 2.0"
)

point_polygon_testdata = (
    shapely.points(np.arange(6), np.arange(6)),
    shapely.box(2, 2, 4, 4),
)
point = shapely.points(2, 3)
line_string = shapely.linestrings([(0, 0), (1, 0), (1, 1)])
linear_ring = shapely.linearrings([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)])
polygon = shapely.polygons([(0, 0), (2, 0), (2, 2), (0, 2), (0, 0)])
multi_point = shapely.multipoints([(0, 0), (1, 2)])
multi_line_string = shapely.multilinestrings([[(0, 0), (1, 2)]])
multi_polygon = shapely.multipolygons(
    [
        [(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)],
        [(2.1, 2.1), (2.2, 2.1), (2.2, 2.2), (2.1, 2.2), (2.1, 2.1)],
    ]
)
geometry_collection = shapely.geometrycollections(
    [shapely.points(51, -1), shapely.linestrings([(52, -1), (49, 2)])]
)
예제 #29
0
def test_line_locate_point_geom_array2():
    points = shapely.points([[0, 0], [1, 0]])
    actual = shapely.line_locate_point(line_string, points)
    np.testing.assert_allclose(actual, [0.0, 1.0])
예제 #30
0
                        [100.0, 0.0],
                    ]],
                },
                "properties": {
                    "prop1": {
                        "this": "that"
                    },
                    "prop0": "value0"
                },
            },
        ],
    },
    indent=4,
)

GEOJSON_GEOMETRY_EXPECTED = shapely.points(125.6, 10.1)
GEOJSON_COLLECTION_EXPECTED = [
    shapely.points([102.0, 0.6]),
    shapely.linestrings([[102.0, 0.0], [103.0, 1.0], [104.0, 0.0],
                         [105.0, 1.0]]),
    shapely.polygons([[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0],
                      [100.0, 0.0]]),
]


class ShapelyGeometryMock:
    def __init__(self, g):
        self.g = g
        self.__geom__ = g._ptr if hasattr(g, "_ptr") else g

    @property