Example #1
0
    def test_numpy(self):

        from numpy import array, asarray
        from numpy.testing import assert_array_equal

        # Construct from a numpy array
        geom = MultiPoint(array([[0.0, 0.0], [1.0, 2.0]]))
        self.assertIsInstance(geom, MultiPoint)
        self.assertEqual(len(geom.geoms), 2)
        self.assertEqual(dump_coords(geom), [[(0.0, 0.0)], [(1.0, 2.0)]])

        # Geo interface (cont.)
        geom = MultiPoint((Point(1.0, 2.0), Point(3.0, 4.0)))
        assert_array_equal(array(geom), array([[1., 2.], [3., 4.]]))

        # Adapt a Numpy array to a multipoint
        a = array([[1.0, 2.0], [3.0, 4.0]])
        geoma = asMultiPoint(a)
        assert_array_equal(geoma.context, array([[1., 2.], [3., 4.]]))
        self.assertEqual(dump_coords(geoma), [[(1.0, 2.0)], [(3.0, 4.0)]])

        # Now, the inverse
        self.assertEqual(geoma.__array_interface__,
                         geoma.context.__array_interface__)

        pas = asarray(geoma)
        assert_array_equal(pas, array([[1., 2.], [3., 4.]]))
Example #2
0
    def test_multipoint(self):

        # From coordinate tuples
        geom = MultiPoint(((1.0, 2.0), (3.0, 4.0)))
        self.assertEqual(len(geom.geoms), 2)
        self.assertEqual(dump_coords(geom), [[(1.0, 2.0)], [(3.0, 4.0)]])

        # From points
        geom = MultiPoint((Point(1.0, 2.0), Point(3.0, 4.0)))
        self.assertEqual(len(geom.geoms), 2)
        self.assertEqual(dump_coords(geom), [[(1.0, 2.0)], [(3.0, 4.0)]])

        # From another multi-point
        geom2 = MultiPoint(geom)
        self.assertEqual(len(geom2.geoms), 2)
        self.assertEqual(dump_coords(geom2), [[(1.0, 2.0)], [(3.0, 4.0)]])

        # Sub-geometry Access
        self.assertIsInstance(geom.geoms[0], Point)
        self.assertEqual(geom.geoms[0].x, 1.0)
        self.assertEqual(geom.geoms[0].y, 2.0)
        with self.assertRaises(IndexError):  # index out of range
            geom.geoms[2]

        # Geo interface
        self.assertEqual(geom.__geo_interface__,
                         {'type': 'MultiPoint',
                          'coordinates': ((1.0, 2.0), (3.0, 4.0))})

        # Adapt a coordinate list to a line string
        coords = [[5.0, 6.0], [7.0, 8.0]]
        geoma = asMultiPoint(coords)
        self.assertEqual(dump_coords(geoma), [[(5.0, 6.0)], [(7.0, 8.0)]])
Example #3
0
def find_nearest_neighbor(x, y, num_neighbors=1):
    '''

    :param x: object borders as an m x 2 numpy array, where m is the number of points
    :param y: object borders as an n x 2 numpy array, where n is the number of points
    :param num_neighbors:
    :return:
    '''
    if isinstance(x, sg.Point) or isinstance(x, sg.MultiPoint):
        # x was input as a shapely point/multipoint object
        point_x = x
    elif x.ndim == 1 or np.shape(x)[0] == 1:
        # x is a vector, either shape (2,) or shape (1,2)
        point_x = sg.asPoint(np.squeeze(x))
    else:
        # x is an m x 2 array of multiple points (m > 1)
        point_x = sg.asMultiPoint(x)

    if isinstance(y, sg.Point) or isinstance(y, sg.MultiPoint):
        # y was input as a shapely point/multipoint object
        point_y = y
    elif y.ndim == 1 or np.shape(y)[0] == 1:
        # y is a vector, either shape (2,) or shape (1,2)
        point_y = sg.asPoint(np.squeeze(y))
    else:
        # y is an m y 2 array of multiple points (m > 1)
        point_y = sg.asMultiPoint(y)

    # if type(y) is sg.Point:
    #     point_y = y
    # else:
    #     point_y = sg.asPoint(y)

    near_x, near_y = so.nearest_points(point_x, point_y)
    nn_dist = near_x.distance(near_y)

    # left over from when I thought it would be useful to find the n nearest points. Right now, just finds the nearest points
    # pts_diff = y - x
    #
    # dist_from_x = np.linalg.norm(pts_diff, axis=1)
    #
    # sorted_dist_idx = np.argsort(dist_from_x)
    # sorted_dist = np.sort(dist_from_x)
    #
    # return sorted_dist[:num_neighbors], sorted_dist_idx[:num_neighbors]

    return nn_dist, near_y
Example #4
0
 def test_multipoint_adapter(self):
     arr = numpy.array([[1.0, 1.0, 2.0, 2.0, 1.0],
                        [3.0, 4.0, 4.0, 3.0, 3.0]])
     tarr = arr.T
     shape = geometry.asMultiPoint(tarr)
     coords = reduce(lambda x, y: x + y, [list(g.coords) for g in shape])
     self.assertEqual(coords, [(1.0, 3.0), (1.0, 4.0), (2.0, 4.0),
                               (2.0, 3.0), (1.0, 3.0)])
Example #5
0
 def rescale_points(points, image_size):
     """
     Rescales [0, 1] normalized points to the specified Width x Height.
     """
     coordinates = (
         np.array([p.xy for p in points]).squeeze(-1) * image_size
     ).round()
     return list(asMultiPoint(coordinates))
Example #6
0
 def test_multipoint(self):
     a = numpy.array([[1.0, 1.0, 2.0, 2.0, 1.0], [3.0, 4.0, 4.0, 3.0, 3.0]])
     t = a.T
     s = geometry.asMultiPoint(t)
     coords = reduce(lambda x, y: x + y, [list(g.coords) for g in s])
     self.failUnlessEqual(
         coords,
         [(1.0, 3.0), (1.0, 4.0), (2.0, 4.0), (2.0, 3.0), (1.0, 3.0)] )
Example #7
0
def filter_inside(points: Union[MultiPoint, np.ndarray],
                  poly: BaseGeometry) -> MultiPoint:
  if isinstance(points, np.ndarray):
    points = asMultiPoint(points)

  prep_polygon = prep(poly)
  points = [i for i in points if prep_polygon.contains(i)]
  points = MultiPoint(points)
  return points
Example #8
0
 def test_multipoint(self):
     arr = numpy.array([[1.0, 1.0, 2.0, 2.0, 1.0], [3.0, 4.0, 4.0, 3.0, 3.0]])
     tarr = arr.T
     shape = geometry.asMultiPoint(tarr)
     coords = reduce(lambda x, y: x + y, [list(g.coords) for g in shape])
     self.assertEqual(
         coords,
         [(1.0, 3.0), (1.0, 4.0), (2.0, 4.0), (2.0, 3.0), (1.0, 3.0)]
     )
Example #9
0
def simulate_patch_sampling(points, size, n=None):
    '''returns rectangles of given size sampled with centres at given by points'''
    if not isinstance(points, MultiPoint):
        points = MultiPoint(asMultiPoint(points))
    if isinstance(size, int):
        w = h = size
    else:
        w, h = size
    return MultiPolygon([CentredRectangle(*np.asarray(p.centroid).tolist(), w,h) \
                         for p in points[:n]])
Example #10
0
 def bounds(self):
     """ return bounding rect of the arc """
     # determine all angles pointing in possible extreme directions
     thetas = [t for t in np.linspace(0, 4*np.pi, 9)
               if self.start < t < self._end]
     thetas.append(self.start)
     thetas.append(self.end)
     # determine the bounding rect for all these points
     points = geometry.asMultiPoint(self.get_point(thetas))
     bounds = points.bounds
     return Rectangle.from_points(bounds[:2], bounds[2:])
Example #11
0
 def bounds(self):
     """ return bounding rect of the arc """
     # determine all angles pointing in possible extreme directions
     thetas = [t for t in np.linspace(0, 4*np.pi, 9)
               if self.start < t < self._end]
     thetas.append(self.start)
     thetas.append(self.end)
     # determine the bounding rect for all these points
     points = geometry.asMultiPoint(self.get_point(thetas))
     bounds = points.bounds
     return Rectangle.from_points(bounds[:2], bounds[2:])
Example #12
0
def _sample_points_(cnt,
                    n_points=None,
                    spacing=None,
                    mode='uniform_random',
                    random_seed=None):
    '''sample point within an oblong contour with shapely
    [deprecated]
    '''
    if (n_points is None) and (spacing is None):
        raise ValueError('either `spacing` or `n_points` must be specified')

    if isinstance(cnt, Polygon):
        pg = cnt
    else:
        pg = Polygon(cnt)

    center, sz, angle_ = cv2.minAreaRect(np.asarray(pg.boundary, dtype=int))
    w, h = sz

    if n_points is None:
        n_points = h * w / spacing**2

    pg_rot = rotate(pg, -angle_)
    x0, y0, x1, y1 = pg_rot.bounds

    # calculate area ratio and increment number of sampled points accordingly
    area_ratio = pg_rot.area / Polygon([(x0, y0), (x0, y1), (x1, y1),
                                        (x1, y0)]).area
    n_points = int(np.ceil(n_points / area_ratio))

    if mode == 'grid':
        points_rot = sample_grid(w,
                                 h,
                                 n_points=n_points,
                                 spacing=spacing,
                                 angle=angle_)
        points_rot = points_rot + np.r_[x0, y0]
    elif mode == 'rotated_grid':
        points_rot = sample_grid(w, h, n_points=n_points, spacing=spacing)
        points_rot = points_rot + np.r_[x0, y0]
    elif mode == 'uniform_random':
        np.random.seed(random_seed)
        points_rot = np.random.rand(
            n_points,
            2,
        ) * np.r_[w, h] + np.r_[x0, y0]
    else:
        raise ValueError('unknown mode:%s' % mode)

    points_rot = MultiPoint(asMultiPoint(points_rot))
    points_rot = points_rot.intersection(pg_rot)
    points = rotate(points_rot, angle_)
    return points
Example #13
0
def viewport_to_shapely_box(viewport):
    """Convert a Google or OpenCage viewport to a shapely box.

    Argument viewport: A viewport is a dict of form:
        {'northeast': {'lat': -33.9806474, 'lng': 150.0169685},
          'southwest': {'lat': -39.18316069999999, 'lng': 140.9616819}}

    Returns: shapely box
    """
    points = geometry.asMultiPoint([[p['lng'], p['lat']]
                                    for p in viewport.values()])
    return geometry.box(*points.bounds)
def insert_multipoint(conn, points, test_name='test'):
    multipoint = asMultiPoint(points)

    wkb = multipoint.wkb
    # print(wkb)
    query = """
    INSERT INTO concave
    (test_name, Geometry)
    VALUES (?, MPointFromWKB(?, -1))
    """
    conn.execute(query, (test_name, wkb))
    conn.commit()
def np_to_wkb(np_array, in_server):
    from shapely import wkb

    np_array = np.array(np_array)

    if len(np_array.shape) <= 1:
        #print len(np_array.shape)
        from shapely.geometry import asPoint
        np_shapely = asPoint(np_array)
    else:
        from shapely.geometry import asMultiPoint
        np_shapely = asMultiPoint(np_array)
    return wkb.dumps(np_shapely, hex=in_server)
def np_to_wkb(np_array,in_server):
    from shapely import wkb
    
    np_array = np.array(np_array)
    
    if len(np_array.shape)<=1:
        #print len(np_array.shape)
        from shapely.geometry import asPoint
        np_shapely = asPoint(np_array)
    else:
        from shapely.geometry import asMultiPoint
        np_shapely = asMultiPoint(np_array) 
    return wkb.dumps(np_shapely, hex=in_server)
def insert_multipoint(connection, points, test_name='test'):
    multipoint = asMultiPoint(points)

    wkb = multipoint.wkb
    # print(wkb)
    query = """
    INSERT INTO concave
    (test_name, Geometry)
    VALUES (%s, ST_GeomFromWKB(%s, -1))
    """
    with connection.cursor() as cursor:
        cursor.execute(query, (test_name, wkb))

    # print("Size of WKB:", sys.getsizeof(wkb))

    connection.commit()
Example #18
0
    def test_numpy_adapter(self):

        from numpy import array, asarray
        from numpy.testing import assert_array_equal

        # Adapt a Numpy array to a multipoint
        a = array([[1.0, 2.0], [3.0, 4.0]])
        geoma = asMultiPoint(a)
        assert_array_equal(geoma.context, array([[1., 2.], [3., 4.]]))
        self.assertEqual(dump_coords(geoma), [[(1.0, 2.0)], [(3.0, 4.0)]])

        # Now, the inverse
        self.assertEqual(geoma.__array_interface__,
                         geoma.context.__array_interface__)

        pas = asarray(geoma)
        assert_array_equal(pas, array([[1., 2.], [3., 4.]]))
Example #19
0
    def points_in_domain(self, domain):
        '''
        Returns a boolean field that identifies the points inside the given domain.
        Domain: a polygon from shapely.geometry.Polygon
        '''

        idx = (self.lon > -9000) & (self.lat > -9000)
        traj = geometry.asMultiPoint(list(zip(self.lon[idx], self.lat[idx])))
        hits = domain.intersection(traj)
        if hits.is_empty:
            return None

        hits_array = np.array(hits)
        if np.shape(hits_array) == () or hits_array.ndim == 1:
            return None

        idx = np.in1d(self.lat, hits_array[:, 1])
        return idx
Example #20
0
File: obs.py Project: vnoel/pycode
    def points_in_domain(self, domain):
        '''
        Returns a boolean field that identifies the points inside the given domain.
        Domain: a polygon from shapely.geometry.Polygon
        '''

        idx = (self.lon > -9000) & (self.lat > -9000)
        traj = geometry.asMultiPoint(list(zip(self.lon[idx], self.lat[idx])))
        hits = domain.intersection(traj)
        if hits.is_empty:
            return None

        hits_array = np.array(hits)
        if np.shape(hits_array)==() or hits_array.ndim==1:
            return None

        idx = np.in1d(self.lat, hits_array[:,1])
        return idx
def create_shortest_path(line_shp_name, start_node_id, end_node_id):
    """Calculates the shortest path from a network of lines.
    
    Args:
        line_shp_name (str): Input shapefile name
        start_node_id (int): Start node ID
        end_node_id (int): End node ID

    Returns:
        None: Creates a graph of nodes (coordinate pairs) connecting a start node with an end node in the defined ``line_shp_name``.
    """

    # load shapefile
    nx_load_shp = nx.read_shp(line_shp_name)

    # with not all graphs connected, take the largest connected subgraph by using the connected_component_subgraphs function.
    nx_list_subgraph = list(
        nx.connected_component_subgraphs(nx_load_shp.to_undirected()))[0]

    # get all the nodes in the network
    nx_nodes = np.array(nx_list_subgraph.nodes())

    # output the nodes to a GeoJSON file
    network_nodes = asMultiPoint(nx_nodes)
    write_geojson(
        line_shp_name.split(".shp")[0] + "_nodes.geojson",
        network_nodes.__geo_interface__)

    # Compute the shortest path. Dijkstra's algorithm.
    nx_short_path = nx.shortest_path(nx_list_subgraph,
                                     source=tuple(nx_nodes[start_node_id]),
                                     target=tuple(nx_nodes[end_node_id]),
                                     weight='distance')

    # create numpy array of coordinates representing result path
    nx_array_path = get_full_path(nx_short_path, nx_list_subgraph)

    # convert numpy array to Shapely Linestring
    shortest_path = asLineString(nx_array_path)

    write_geojson(
        line_shp_name.split(".shp")[0] + "_Xpath.geojson",
        shortest_path.__geo_interface__)
Example #22
0
def get_starts(known_wall_points, line, step, min_len):
  if line.length < min_len:
    return None

  ts = 0.0
  # TODO: maybe optimize
  if known_wall_points is not None and len(known_wall_points) > 0:
    known_wall_points = asMultiPoint(known_wall_points)
    try_starts = np.arange(0.0, line.length, step / 4)
    found_start = False
    for ts in try_starts:
      if line.interpolate(ts).distance(known_wall_points) > step:
        found_start = True
        break
    if not found_start:
      return None

  starts = np.arange(ts, line.length, step)
  return starts
Example #23
0
def line_convex_hull_intersect(line1, points):

    if type(line1) is sg.LineString:
        sg_line1 = line1
    else:
        sg_line1 = sg.asLineString(line1)

    if type(points) is sg.MultiPoint:
        sg_points = points
    else:
        sg_points = sg.asMultiPoint(points)

    cvhull_poly = sg_points.convex_hull

    if cvhull_poly.intersects(sg_line1):
        line_hull_intersect = cvhull_poly.intersection(sg_line1)
    else:
        line_hull_intersect = None

    return line_hull_intersect
def createConvexHull(points,order, clusters,shapefilename):
    m = len(clusters)
    point_sets = [[] for i in range(m+1)]
    
    for i,id in enumerate(order):        
        p = list(points[id])
        p.append(.0)
        cluster_id = -1
        for cluster in clusters:
            if cluster.start <= i <= cluster.end:
                cluster_id = cluster.id
                break
        point_sets[cluster_id].append(p)
    
    convex_hull_set = []
    from shapely.geometry import MultiPoint, asMultiPoint
    for i,point_set in enumerate(point_sets):
        mp = asMultiPoint(point_set)
        convex_hull_set.append(mp.convex_hull)
        
    shapeType = shapelib.SHPT_POLYGONZ
    shapeFile = shapelib.create(shapefilename, shapeType)
    dbfName = shapefilename[:-3]+ 'dbf'
    dbf = dbflib.create(dbfName)
    dbf.add_field('ID', dbflib.FTInteger, 50,0)
    dbf.add_field('Cluster', dbflib.FTInteger, 50,0)
        
    for i,convex_hull in enumerate(convex_hull_set):       
        cluster_id = i
        if cluster_id == m: cluster_id = -1
        shapeObject = np.array(convex_hull.exterior)
        n = len(shapeObject)
        shapeObject = np.append(shapeObject,[[.0] for j in range(n)],axis=1)
        shapeObject = [tuple(j) for j in shapeObject]
        obj = shapelib.SHPObject(shapeType, -1, [shapeObject])
        shapeFile.write_object(-1, obj)
        dbf.write_record(i, {'ID':id,'Cluster':cluster_id})
        
    shapeFile.close()
    dbf.close()
Example #25
0
    def _buffer_cluster_layers(self):
        """
        Buffers all points not removed after _remove_veg (or all points of self.remove_veg is set to False)
        :return:
        """
        from shapely.geometry import asMultiPoint
        # Subset to only complete layers
        multi_points = self.points[self.points['bins_z'].isin(
            self._complete_layers)]
        keep_bins_z = multi_points["bins_z"].values
        multi_points = asMultiPoint(multi_points[['x', 'y']].values)
        buffer_points = gpd.GeoDataFrame(
            gpd.GeoSeries(multi_points.geoms).buffer(self.buffer_distance))
        ## TODO handle for veg removal
        buffer_points["bins_z"] = keep_bins_z
        labels = [
            item for sublist in self._cluster_all_layers() for item in sublist
        ]
        buffer_points["labels"] = labels

        # Fix some GPD quirks
        buffer_points = buffer_points.set_geometry(0)
        buffer_points[0].geom_type = buffer_points.geom_type
        return (buffer_points)
Example #26
0
    ]
    print(rec_name_to_array_idx_map)

    #process each scene in this episode
    #count # of ep.scenes
    for sc_i, sc in enumerate(ep.scenes):
        #print('Processing scene # ', sc_i)
        polygon_list = []
        polygon_z = []
        polygons_of_interest_idx_list = []
        rec_present = []

        for obj in sc.objects:
            if len(obj.receivers) == 0:
                continue  #do not process objects that are not receivers
            obj_polygon = geometry.asMultiPoint(
                obj.vertice_array[:, (0, 1)]).convex_hull
            # check if object is inside the analysis_area
            if obj_polygon.within(analysis_polygon):
                # if the object is a receiver and is within the analysis area
                if len(obj.receivers) > 0:
                    rec_array_idx = rec_name_to_array_idx_map.index(obj.name)
                    for rec in obj.receivers:  #for all receivers
                        ray_i = 0
                        isLOSChannel = 0
                        for ray in rec.rays:  #for all rays
                            #gather all info
                            thisRayInfo = np.zeros(numVariablePerRay)
                            thisRayInfo[0] = ray.path_gain
                            thisRayInfo[1] = ray.time_of_arrival
                            thisRayInfo[2] = ray.departure_elevation
                            thisRayInfo[3] = ray.departure_azimuth
Example #27
0
# grover  40.868393, -104.226126
# Wellington  40.702324, -105.005497
#
# buffer  64373.76
#
# +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs
#
# +proj=aea +lat_0=23 +lon_0=-96 +lat_1=29.5 +lat_2=45.5 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs

original = CRS.from_proj4("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
destination = CRS.from_proj4(
    "+proj=aea +lat_0=23 +lon_0=-96 +lat_1=29.5 +lat_2=45.5 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"
)
transprojr = Transformer.from_proj(original, destination)
ma = asMultiPoint(np.array([[40.868393, -104.226126], [40.702324, -105.005497]]))

out = []
for pt in transprojr.itransform(
    np.array([[-104.226126, 40.868393], [-105.005497, 40.702324]])
):
    print(pt)
    out.append(pt)
print(out)
ma = asMultiPoint(out)
print(ma)
# small_rect = ma.buffer(80467.2).minimum_rotated_rectangle
(minx, miny, maxx, maxy) = ma.buffer(80467.2).bounds
small_rect = shapely.geometry.box(minx, miny, maxx, maxy)
# big_rect = ma.buffer(100000).minimum_rotated_rectangle
(minx, miny, maxx, maxy) = ma.buffer(160000).bounds
Example #28
0
def test_multipoint_adapter_deprecated():
    coords = [[5.0, 6.0], [7.0, 8.0]]
    with pytest.warns(ShapelyDeprecationWarning, match="proxy geometries"):
        asMultiPoint(coords)
af = AffinityPropagation(damping=0.9,max_iter=10000,convergence_iter=150,affinity='euclidean').fit(pos_xyz )
 
cluster_number = af.labels_
cluster_centers_indices = af.cluster_centers_indices_
n_clusters_ = len(cluster_centers_indices)
cluster_number = af.labels_

#maintenant on a pour chaque classe la position , et le numero du cluster associé
#on va calculer les formes géoémtriques patatoides pour chaque cluster
import shapely
from shapely.geometry import MultiPoint
from shapely.geometry import asMultiPoint

mps = [] ;#list de multipoints, séparé par cluster
for i in range(0,n_clusters_):
    mps.append(asMultiPoint(pos_xyz[cluster_number==i]))

bb_mps = []    #liste de multipoints double bufferisé (morpho math !)
for i in range(0,n_clusters_):
    bb_mps.append(
    mps[i].buffer(1.0).buffer(-0.95)   
    )

###plot madness !
#tracer les patatoides
from matplotlib.patches import Polygon 
from matplotlib import colors;
polygons = bb_mps; 
a_colour_map = cmap.get_cmap('jet')
jet = cmap.get_cmap('jet') 
cNorm  = colors.Normalize(vmin=0, vmax= 1 )
Example #30
0
 def test_multipoint_adapter(self):
     # Adapt a coordinate list to a line string
     coords = [[5.0, 6.0], [7.0, 8.0]]
     geoma = asMultiPoint(coords)
     self.assertEqual(dump_coords(geoma), [[(5.0, 6.0)], [(7.0, 8.0)]])
# use Networkx to load a Noded shapefile
# returns a graph where each node is a coordinate pair
# and the edge is the line connecting the two nodes

nx_load_shp = nx.read_shp("../geodata/shp/e01_network_lines_3857.shp")

# A graph is not always connected, so we take the largest connected subgraph
# by using the connected_component_subgraphs function.
nx_list_subgraph = list(nx.connected_component_subgraphs(nx_load_shp.to_undirected()))[0]


# get all the nodes in the network
nx_nodes = np.array(nx_list_subgraph.nodes())

# output the nodes to a GeoJSON file to view in QGIS
network_nodes = asMultiPoint(nx_nodes)
write_geojson("../geodata/ch08_final_netx_nodes.geojson", network_nodes.__geo_interface__ )


# this number represents the nodes position
# in the array to identify the node
start_node_pos = 30
end_node_pos = 21


# Compute the shortest path. Dijkstra's algorithm.
nx_short_path = nx.shortest_path(nx_list_subgraph,
                                 source=tuple(nx_nodes[start_node_pos]),
                                 target=tuple(nx_nodes[end_node_pos]),
                                 weight='distance')
Example #32
0
        nturns -= 1
    else:
        heading = nturns * np.pi / 3
        points.append(points[-1] + [np.cos(heading), np.sin(heading)])

# Create curve geometry.
curve = geometry.LineString(points)

# Create exterior of coaster.
exterior = curve.envelope.buffer(1).exterior

# Connect curve to exterior.
for _ in range(2):
    proj = exterior.interpolate(exterior.project(geometry.Point(points[0])))
    points = points[::-1] + [proj]
i = np.argmin([pt.distance(proj) for pt in geometry.asMultiPoint(exterior)])
points += exterior.coords[i:]
points += exterior.coords[:i + 1]

# Determine bounding box for artwork.
minx, miny, maxx, maxy = exterior.bounds
pad = 1
minx -= pad
maxx += pad
miny -= pad
maxy += pad
width = maxx - minx
height = maxy - miny

# Write SVG document.
print('<svg xmlns="http://www.w3.org/2000/svg"')
Example #33
0
def operation_example():
	patch = Point(0.0, 0.0).buffer(10.0)
	print('patch = {}.'.format(patch))
	print('patch.area = {}.'.format(patch.area))

	line = LineString([(0, 0), (1, 1), (0, 2), (2, 2), (3, 1), (1, 0)])
	dilated = line.buffer(0.5)
	eroded = dilated.buffer(-0.3)

	ring = LinearRing([(0, 0), (1, 1), (1, 0)])

	point = Point(0.5, 0.5)
	polygon = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])
	print('polygon.contains(point) = {}.'.format(polygon.contains(point)))

	#box = shapely.geometry.box(minx, miny, maxx, maxy, ccw=True)

	pa = asPoint(np.array([0.0, 0.0]))
	la = asLineString(np.array([[1.0, 2.0], [3.0, 4.0]]))
	ma = asMultiPoint(np.array([[1.1, 2.2], [3.3, 4.4], [5.5, 6.6]]))

	data = {'type': 'Point', 'coordinates': (0.0, 0.0)}
	geom = shapely.geometry.shape(data)
	#geom = shapely.geometry.asShape(data)

	#--------------------
	#geom = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])
	geom = LineString([(0, 0), (10, 0), (10, 5), (20, 5)])

	print('polygon.has_z = {}.'.format(geom.has_z))
	if isinstance(geom, LinearRing):
		print('polygon.is_ccw = {}.'.format(geom.is_ccw))  # LinearRing only.
	print('polygon.is_empty = {}.'.format(geom.is_empty))
	print('polygon.is_ring = {}.'.format(geom.is_ring))
	print('polygon.is_simple = {}.'.format(geom.is_simple))
	print('polygon.is_valid = {}.'.format(geom.is_valid))

	print('polygon.coords = {}.'.format(geom.coords))

	print('polygon.area = {}.'.format(geom.area))
	print('polygon.bounds = {}.'.format(geom.bounds))
	print('polygon.length = {}.'.format(geom.length))
	print('polygon.minimum_clearance = {}.'.format(geom.minimum_clearance))
	print('polygon.geom_type = {}.'.format(geom.geom_type))

	print('polygon.boundary = {}.'.format(geom.boundary))
	print('polygon.centroid = {}.'.format(geom.centroid))

	print('polygon.convex_hull.exterior.coords.xy = {}.'.format(list((x, y) for x, y in zip(*geom.convex_hull.exterior.coords.xy))))
	print('polygon.envelope = {}.'.format(geom.envelope))
	print('polygon.minimum_rotated_rectangle = {}.'.format(geom.minimum_rotated_rectangle))

	#polygon.parallel_offset(distance, side, resolution=16, join_style=1, mitre_limit=5.0)
	#polygon.simplify(tolerance, preserve_topology=True)

	#--------------------
	poly1 = Polygon([(3, 3), (5, 3), (5, 5), (3, 5)])
	poly2 = Polygon([(1, 1), (4, 1), (4, 3.5), (1, 3.5)])

	print('poly1.intersection(poly2) = {}.'.format(poly1.intersection(poly2)))
	print('poly1.difference(poly2) = {}.'.format(poly1.difference(poly2)))
	print('poly1.symmetric_difference(poly2) = {}.'.format(poly1.symmetric_difference(poly2)))
	print('poly1.union(poly2) = {}.'.format(poly1.union(poly2)))

	print('poly1.equals(poly2) = {}.'.format(poly1.equals(poly2)))
	print('poly1.almost_equals(poly2, decimal=6) = {}.'.format(poly1.almost_equals(poly2, decimal=6)))
	print('poly1.contains(poly2) = {}.'.format(poly1.contains(poly2)))
	print('poly1.covers(poly2) = {}.'.format(poly1.covers(poly2)))
	print('poly1.crosses(poly2) = {}.'.format(poly1.crosses(poly2)))
	print('poly1.disjoint(poly2) = {}.'.format(poly1.disjoint(poly2)))
	print('poly1.intersects(poly2) = {}.'.format(poly1.intersects(poly2)))
	print('poly1.overlaps(poly2) = {}.'.format(poly1.overlaps(poly2)))
	print('poly1.touches(poly2) = {}.'.format(poly1.touches(poly2)))
	print('poly1.within(poly2) = {}.'.format(poly1.within(poly2)))

	#--------------------
	poly1 = Polygon([(40, 50), (60, 50), (60, 90), (40, 90)])
	poly2 = Polygon([(10, 100), (100, 100), (100, 150), (10, 150)])

	print('The distance between two convex polygons = {}.'.format(poly1.distance(poly2)))
	print('The Hausdorff distance between two convex polygons = {}.'.format(poly1.hausdorff_distance(poly2)))
	print('The representative point of a polygon = {}.'.format(poly1.representative_point()))

	#--------------------
	lines = [
		((0, 0), (1, 1)),
		((0, 0), (0, 1)),
		((0, 1), (1, 1)),
		((1, 1), (1, 0)),
		((1, 0), (0, 0)),
		((1, 1), (2, 0)),
		((2, 0), (1, 0)),
		((5, 5), (6, 6)),
		((1, 1), (100, 100)),
	]

	polys = shapely.ops.polygonize(lines)
	result, dangles, cuts, invalids = shapely.ops.polygonize_full(lines)
	merged_line = shapely.ops.linemerge(lines)

	# Efficient unions.
	polygons = [Point(i, 0).buffer(0.7) for i in range(5)]
	shapely.ops.unary_union(polygons)
	shapely.ops.cascaded_union(polygons)

	# Delaunay triangulation.
	points = MultiPoint([(0, 0), (1, 1), (0, 2), (2, 2), (3, 1), (1, 0)])
	triangles = shapely.ops.triangulate(points)

	# Voronoi diagram.
	#points = MultiPoint([(0, 0), (1, 1), (0, 2), (2, 2), (3, 1), (1, 0)])
	#regions = shapely.ops.voronoi_diagram(points)

	# Nearest points.
	triangle = Polygon([(0, 0), (1, 0), (0.5, 1), (0, 0)])
	square = Polygon([(0, 2), (1, 2), (1, 3), (0, 3), (0, 2)])
	nearest_points = shapely.ops.nearest_points(triangle, square)

	square = Polygon([(1,1), (2, 1), (2, 2), (1, 2), (1, 1)])
	line = LineString([(0,0), (0.8, 0.8), (1.8, 0.95), (2.6, 0.5)])
	result = shapely.ops.snap(line, square, 0.5)

	g1 = LineString([(0, 0), (10, 0), (10, 5), (20, 5)])
	g2 = LineString([(5, 0), (30, 0), (30, 5), (0, 5)])
	forward, backward = shapely.ops.shared_paths(g1, g2)

	pt = Point((1, 1))
	line = LineString([(0, 0), (2, 2)])
	result = shapely.ops.split(line, pt)

	ls = LineString((i, 0) for i in range(6))
	shapely.ops.substring(ls, start_dist=1, end_dist=3)
	shapely.ops.substring(ls, start_dist=3, end_dist=1)
	shapely.ops.substring(ls, start_dist=1, end_dist=-3)
	shapely.ops.substring(ls, start_dist=0.2, end_dist=-0.6, normalized=True)
Example #34
0
    # y_offset = -26.6000003815
    x_offset = 0
    y_offset = 0
    # for i in range(len(contours)):
    res = 0.05
    for i in range(len(ver)):
        ver[i] = (ver[i][0] / res + x_offset, ver[i][1] / res + y_offset)

        # ver[i] = (ver[i][0], ver[i][1])
    ver = np.array(ver)
    # plt.scatter((ver[:, 0]), (ver[:, 1]))
    # plt.imshow(gray)
    #
    # plt.show()
    # ver = np.array(sorted(ver, key=lambda row: row[0]))
    vr = asMultiPoint(ver)
    for i in range(len(corners)):
        if i in [11, 14, 25, 28, 52, 53, 54, 0, 45, 44, 49, 50, 63]:
            corners[i] = [0, 0]
    # corners = np.array([x for (k,x) in enumerate(corners) if k not in [11,14,25, 28, 52, 53, 54, 0, 45, 44, 49, 50, 63 ]])
    segms2, idc, v3 = [], [], []
    # for i in range(len(corners)-1):
    p = [[31, 27], [27, 8], [27, 30], [8, 7], [7, 29], [29, 13], [13, 12],
         [12, 3], [3, 4], [4, 24], [24, 21], [21, 22], [21, 5], [5, 6],
         [6, 17], [17, 18], [18, 1], [1, 2], [2, 19], [19, 15], [15, 20],
         [15, 9], [9, 10], [10, 16], [16, 23], [23, 37], [37, 42], [42, 32],
         [32, 33], [33, 35], [33, 51], [51, 56], [56, 36], [36, 38], [38, 57],
         [38, 39], [57, 58], [58, 43], [43, 41], [43, 46], [46, 47], [46, 59],
         [59, 60], [60, 48], [48, 55], [55, 61], [61, 62], [62, 31]]
    # poli = []
    #
Example #35
0
    def joiner(self, data):
        """
        Entry point for the class Join. This function identiefs junctions
        (intersection points) of shared paths.

        The join function is the second step in the topology computation.
        The following sequence is adopted:
        1. extract
        2. join
        3. cut
        4. dedup
        5. hashmap

        Detects the junctions of shared paths from the specified hash of linestrings.

        After decomposing all geometric objects into linestrings it is necessary to
        detect the junctions or start and end-points of shared paths so these paths can
        be 'merged' in the next step. Merge is quoted as in fact only one of the
        shared path is kept and the other path is removed.

        Parameters
        ----------
        data : dict
            object created by the method topojson.extract.
        quant_factor : int, optional (default: None)
            quantization factor, used to constrain float numbers to integer values.
            - Use 1e4 for 5 valued values (00001-99999)
            - Use 1e6 for 7 valued values (0000001-9999999)

        Returns
        -------
        dict
            object expanded with
            - new key: junctions
            - new key: transform (if quant_factor is not None)
        """

        # presimplify linestrings if required
        if self.options.presimplify > 0:
            # set default if not specifically given in the options
            if type(self.options.presimplify) == bool:
                simplify_factor = 2
            else:
                simplify_factor = self.options.presimplify

            data["linestrings"] = simplify(
                data["linestrings"],
                simplify_factor,
                algorithm=self.options.simplify_algorithm,
                package=self.options.simplify_with,
                input_as="linestring",
            )

        # compute the bounding box of input geometry
        lsbs = geometry.asMultiLineString(data["linestrings"]).bounds
        ptbs = geometry.asMultiPoint(data["coordinates"]).bounds
        data["bbox"] = compare_bounds(lsbs, ptbs)

        # prequantize linestrings if required
        if self.options.prequantize > 0:
            # set default if not specifically given in the options
            if type(self.options.prequantize) == bool:
                quant_factor = 1e6
            else:
                quant_factor = self.options.prequantize

            data["linestrings"], data["transform"] = quantize(
                data["linestrings"], data["bbox"], quant_factor)

            data["coordinates"], data["transform"] = quantize(
                data["coordinates"], data["bbox"], quant_factor)

        if not self.options.topology or not data["linestrings"]:
            data["junctions"] = self.junctions
            return data

        if self.options.shared_paths == "coords":

            def _get_verts(geom):
                # get coords of each LineString
                return [x for x in geom.coords]

            geoms = {}
            junctions = []

            for ls in data["linestrings"]:
                verts = _get_verts(ls)
                for i, vert in enumerate(verts):
                    ran = geoms.pop(vert, None)
                    neighs = sorted([
                        verts[i - 1], verts[i + 1 if i < len(verts) - 1 else 0]
                    ])
                    if ran and ran != neighs:
                        junctions.append(vert)
                    geoms[vert] = neighs

            self.junctions = [geometry.Point(xy) for xy in set(junctions)]
        else:

            # create list with unique combinations of lines using a rdtree
            line_combs = select_unique_combs(data["linestrings"])

            # iterate over index combinations
            for i1, i2 in line_combs:
                g1 = data["linestrings"][i1]
                g2 = data["linestrings"][i2]

                # check if geometry are equal
                # being equal meaning the geometry object coincide with each other.
                # a rotated polygon or reversed linestring are both considered equal.
                if not g1.equals(g2):
                    # geoms are unique, let's find junctions
                    self.shared_segs(g1, g2)

            # self.segments are nested lists of LineStrings, get coordinates of each nest
            s_coords = []
            for segment in self.segments:
                s_coords.extend([[(x.xy[0][y], x.xy[1][y]) for x in segment
                                  for y in range(len(x.xy[0]))]])
                # s_coords.extend([[y for x in segment for y in list(x.coords)]])

            # only keep junctions that appear only once in each segment (nested list)
            # coordinates that appear multiple times are not junctions
            for coords in s_coords:
                self.junctions.extend([
                    geometry.Point(i) for i in coords if coords.count(i) == 1
                ])

            # junctions can appear multiple times in multiple segments, remove duplicates
            self.junctions = [
                loads(xy) for xy in list(set([x.wkb for x in self.junctions]))
            ]

        # prepare to return object
        data["junctions"] = self.junctions

        return data
Example #36
0
 def as_polygon(self, axis=(0, 1)):
     if geometry is None:
         raise NotImplementedError('shapely module was not found')
     return geometry.asMultiPoint(self.as_vertice_array()[:,
                                                          axis]).convex_hull
def maybe_as_multipoint(points: Union[np.ndarray, MultiPoint]) -> MultiPoint:
    if isinstance(points, np.ndarray):
        points = asMultiPoint(points)
    return points
def _xyz_to_wkt(xyz):
    '''Converts the xy of the xyz into a wkt MultiPoint format'''
    return asMultiPoint(xyz[:, :-1]).wkt