def computeLineString(bounding_box, pos, long_lats): bbx = box(bounding_box[0], bounding_box[1], bounding_box[2], bounding_box[3]) basedist = point.Point(bounding_box[0], bounding_box[1]).distance( point.Point(bounding_box[0], bounding_box[3])) * 1.2 start = pos end = pos + 1 while (start > 0): p = point.Point(long_lats[start][0], long_lats[start][1]) if (bbx.contains(p) or (basedist > bbx.distance(p))): start -= 1 else: break while (end < len(long_lats)): p = point.Point(long_lats[end][0], long_lats[end][1]) if (bbx.contains(p) or (basedist > bbx.distance(p))): end += 1 else: break end += 1 if (end > len(long_lats)): end = len(long_lats) if (end - start == 1): if (start > 0): start -= 1 if (end < len(long_lats)): end += 1 return linestring.LineString([(long_lats[i][0], long_lats[i][1]) for i in range(start, end)])
def LineGeoJSONToShp_WGS84(json_fp, shp_fp=None): #线状GeoJSON文件转成SHP(火星坐标 转 WGS84) import coordinate_conversion from shapely.geometry import linestring if not json_fp.endswith("json"): return False if shp_fp is None: shp_fp = "{}_wgs84.shp".format(json_fp[:-5]) elif not shp_fp.endswith("shp"): return False gdf = geopandas.read_file(json_fp) # GCJ02转WGS84 for i in range(0, len(gdf)): line = gdf.geometry[i] # 获取空间属性,即GeoSeries old_pnts = line.coords #获得坐标串 new_pnts = [] #新坐标 for old_pnt in old_pnts: lng, lat = old_pnt lng, lat = coordinate_conversion.gcj02towgs84(lng, lat) #转换 new_pnts.append((lng, lat)) gdf.geometry[i] = linestring.LineString(new_pnts) # 设置成WGS84,并保存 gdf.crs = {'init': 'epsg:4326'} gdf.to_file(shp_fp, encoding="utf-8") return shp_fp
def calcAlignment(backPos, walls, wallProbVec, dR): """ calculating object alignment, currently only w.r.t. supporting wall backPos - vector of objects' back position (numpy array) walls - list of walls, each represented as a line (end points) wallProbVec - probability vector of objects' to stand against the wall dR - space diagonal (scalar) """ # # ====> DIDNOT check direction, i.e. that object is parallel/perpendicular to wall # nW = len(walls) nO = len(backPos) wLines = [] for iW in range(nW): wLines.append(sgls.LineString((walls[iW][0], walls[iW][1]))) wSum = 0 for iO in range(nO): dP = np.array([]) for iW in range(nW): # shortest distance to wall dP = np.append(dP, wLines[iW].distance(spt.Point(backPos[iO]))) wSum += wallProbVec[iO] * min(dP) wSum /= (nO * dR) return wSum
def loadPolys(config): import shapefile sf = shapefile.Reader(config['landshapefile']) bbx = config['confines'] shapes = sf.shapes() shapeSetOfInterest = [ linestring.LineString(x.points) for x in shapes if toShape(x.points).intersects(bbx) ] return shapeSetOfInterest
def calcGoldenSec(objPos, roomRect, dR): """ calculating objects location w.r.t. golden section lines objPos: objects' center position roomRect: 4 points of room (or sub-area) rectangle dR: room diagonal """ # make sure the vertices are ordered tmpRect = sgp.Polygon(roomRect) tmpRect = tmpRect.convex_hull t_rect = tmpRect.exterior.coords[0:-1] # creating golden lines. Assuming gsRatio = 13/21 # go over the 2 consecutive pair of vertices and generate the 4-lines, 2 in each side gsr = 13.0 / 21.0 line1 = sgls.LineString((t_rect[0], t_rect[1])) length = npla.norm(np.array(t_rect[0]) - np.array(t_rect[1])) pt11 = line1.interpolate(length * (1.0 - gsr)) pt12 = line1.interpolate(length * gsr) line3 = sgls.LineString((t_rect[2], t_rect[3])) length = npla.norm(np.array(t_rect[2]) - np.array(t_rect[3])) pt32 = line3.interpolate(length * (1.0 - gsr)) pt31 = line3.interpolate(length * gsr) line2 = sgls.LineString((t_rect[1], t_rect[2])) length = npla.norm(np.array(t_rect[1]) - np.array(t_rect[2])) pt21 = line2.interpolate(length * (1.0 - gsr)) pt22 = line2.interpolate(length * gsr) line4 = sgls.LineString((t_rect[3], t_rect[0])) length = npla.norm(np.array(t_rect[3]) - np.array(t_rect[0])) pt42 = line4.interpolate(length * (1.0 - gsr)) pt41 = line4.interpolate(length * gsr) gsLines = [] gsLines.append(sgls.LineString((pt11, pt31))) gsLines.append(sgls.LineString((pt12, pt32))) gsLines.append(sgls.LineString((pt21, pt41))) gsLines.append(sgls.LineString((pt22, pt42))) dObjGs = [] for i in range(len(objPos)): dd = [] for j in range(len(gsLines)): dd.append(gsLines[j].distance(spt.Point(objPos[i]))) dObjGs.append(min(dd)) gP = np.sum(dObjGs) gP /= (1.0 * dR * len(objPos)) return gP
def get_linestrings_for_stop_section(self, stop_tuple, trip_id, from_shape_brake, to_shape_brake): try: assert self.shapes shapedict = get_shape_between_stops( self.gtfs.conn.cursor(), trip_id, stop_tuple[0], stop_tuple[1], (from_shape_brake, to_shape_brake)) assert not len(set(shapedict["lat"])) <= 1 assert not len(set(shapedict["lon"])) <= 1 return shapely.LineString([ (lon, lat) for lat, lon in zip(shapedict["lat"], shapedict["lon"]) ]) except (ValueError, AssertionError): lat0, lon0 = self.gtfs.get_stop_coordinates(stop_tuple[0]) lat1, lon1 = self.gtfs.get_stop_coordinates(stop_tuple[1]) if lat0 == lat1 and lon0 == lon1: return else: return shapely.LineString([(lon0, lat0), (lon1, lat1)])
def get_geometry(self, stop_tuple, route, all_routes, cluster_dict): #line = get_linestrings_for_stop_section(stop_tuple, trip_id, from_shape_break, to_shape_break) #print(stop_tuple, cluster_dict[stop_tuple[0]], cluster_dict[stop_tuple[1]]) line = shapely.LineString( [cluster_dict[stop_tuple[0]][0], cluster_dict[stop_tuple[1]][0]]) if stop_tuple[0] == stop_tuple[1]: return else: return self.route_parallels(line, route, all_routes, bunching_value=self.bunching_value, line_spacing=self.line_spacing)
def createAxes(wallSkeletons, slabSkeleton): Haxes = [] Vaxes = [] intersections = [] CurPotentialColumns = [] HorizontalMid, VerticalMid, HaxesCoords, VaxesCoords = WallSkeleton.getMids( wallSkeletons) for coord in VaxesCoords: first = (coord, 0) second = (coord, round(slabSkeleton.poly.MaxCoords().y(), 2)) Axis = linestring.LineString([first, second]) Vaxes.append(Axis) for coord in HaxesCoords: first = (0, coord) second = (round(slabSkeleton.poly.MaxCoords().x(), 2), coord) Axis = linestring.LineString([first, second]) Haxes.append(Axis) for Vaxis in Vaxes: for Haxis in Haxes: intersection = Vaxis.intersection(Haxis) if intersection not in intersections: intersections.append(intersection) Mids = VerticalMid + HorizontalMid i = 0 for pnt in intersections: print("Point", pnt.x, pnt.y) for mid in Mids: if pnt.within(mid): i = i + 1 point = Point(round(pnt.x, 2), round(pnt.y, 2)) if point not in CurPotentialColumns: CurPotentialColumns.append(point) return Vaxes, Haxes, CurPotentialColumns
def __new__(self, lines=None): if not lines: # allow creation of empty multilinestrings, to support unpickling # TODO better empty constructor return shapely.from_wkt("MULTILINESTRING EMPTY") elif isinstance(lines, MultiLineString): return lines lines = getattr(lines, "geoms", lines) m = len(lines) subs = [] for i in range(m): line = linestring.LineString(lines[i]) if line.is_empty: raise EmptyPartError( "Can't create MultiLineString with empty component") subs.append(line) if len(lines) == 0: return shapely.from_wkt("MULTILINESTRING EMPTY") return shapely.multilinestrings(subs)
def __new__(self, lines=None): """ Parameters ---------- lines : sequence A sequence of line-like coordinate sequences or objects that provide the numpy array interface, including instances of LineString. Example ------- Construct a collection containing one line string. >>> lines = MultiLineString( [[[0.0, 0.0], [1.0, 2.0]]] ) """ if not lines: # allow creation of empty multilinestrings, to support unpickling # TODO better empty constructor return shapely.from_wkt("MULTILINESTRING EMPTY") elif isinstance(lines, MultiLineString): return lines lines = getattr(lines, "geoms", lines) m = len(lines) subs = [] for i in range(m): line = linestring.LineString(lines[i]) if line.is_empty: raise EmptyPartError( "Can't create MultiLineString with empty component") subs.append(line) if len(lines) == 0: return shapely.from_wkt("MULTILINESTRING EMPTY") return shapely.multilinestrings(subs)
def path_to_geos(path): """ """ import time start_time = time.time() log = [] DEBUG = False # path_verts, path_codes = zip(*list(path.iter_segments(curves=False))) path_verts, path_codes = path_segments(path, curves=False) path_verts = np.array(path_verts) path_codes = np.array(path_codes) if DEBUG: print 'codes:', path_codes verts_split_inds = np.where(path_codes == Path.MOVETO)[0] verts_split = np.split(path_verts, verts_split_inds, 0) codes_split = np.split(path_codes, verts_split_inds, 0) if DEBUG: print 'vs: ', `verts_split` if DEBUG: print 'cs: ', `codes_split` log.append('split done %s' % (time.time() - start_time)) collection = [] for path_verts, path_codes in zip(verts_split, codes_split): if len(path_verts) == 0: continue # XXX A path can be given which does not end with close poly, in that situation, we have to guess? if DEBUG: print 'pv: ', path_verts # XXX Implement a point if path_verts.shape[0] > 2 and (path_codes[-1] == Path.CLOSEPOLY or all(path_verts[0, :] == path_verts[-1, :])): if path_codes[-1] == Path.CLOSEPOLY: ipath2 = polygon.Polygon(path_verts[:-1, :]) else: ipath2 = polygon.Polygon(path_verts) else: ipath2 = linestring.LineString(path_verts) if (len(collection) > 0 and isinstance(collection[-1][0], polygon.Polygon) and isinstance(ipath2, polygon.Polygon) and collection[-1][0].contains(ipath2.exterior)): collection[-1][1].append(ipath2.exterior) else: # collection is a list of [exernal_poly, list_of_internal_polys] collection.append([ipath2, []]) log.append('collection done before while %s.' % (time.time() - start_time)) log.append('Len of collection %s.' % (len(collection))) res = [] for external_poly, internal_polys in collection: # print external_poly if len(internal_polys) > 0: # print internal_polys # XXX worry about islands within lakes poly = polygon.Polygon(external_poly.exterior, internal_polys) else: poly = external_poly res.append(poly) collection = res # if len(collection) > 1: # i = 0 # while i<len(collection)-1: # poly = collection[i] # poly2 = collection[i+1] # # # TODO Worry about islands within lakes # if isinstance(poly, polygon.Polygon) and isinstance(poly2, polygon.Polygon): # if poly.contains(poly2): # # XXX This is the slow bit! ## collection[i] = polygon.Polygon(poly.exterior, list(poly.interiors) + [poly2.exterior]) # collection.pop(i+1) # continue # else: # res.append([poly]) # i+=1 # # log.append('Post len of collection %s.' % (len(collection))) # log.append('collection done after while %s' % (time.time() - start_time)) if len(collection) == 1: result = collection else: if all([isinstance(geom, linestring.LineString) for geom in collection]): result = [MultiLineString(collection)] else: result = collection # if DEBUG: print 'geom: ', collection, type(collection) # raise NotImplementedError('The path given was not a collection of line strings, ' # 'nor a single polygon with interiors.') if (time.time() - start_time) > 1: print 'geos time %s' % (time.time() - start_time) print '\n'.join(log) # remove any zero area polygons result = filter(lambda geom: (isinstance(geom, polygon.Polygon) and geom.area != 0) or \ not isinstance(geom, polygon.Polygon), result) return result
def cluster_shapes(self): """ :return: """ # get unique stop-to-stop shapes, with trips aggregated # split by nearby stops # match splitted, and aggregate trips # identify branches: large overlap but crosses buffer, insert pseudo stop at branch # split everything again # match splitted #this query returns shapes for of the maximum trips, both directions df = self.gtfs.execute_custom_query_pandas("""WITH a AS ( SELECT routes.name AS name, shape_id, route_I, trip_I, routes.type, direction_id, max(end_time_ds-start_time_ds) AS trip_duration, count(*) AS n_trips FROM trips LEFT JOIN routes USING(route_I) WHERE start_time_ds >= 7*3600 AND start_time_ds < 8*3600 GROUP BY routes.route_I, direction_id ), b AS( SELECT q1.trip_I AS trip_I, q1.stop_I AS from_stop_I, q2.stop_I AS to_stop_I, q1.seq AS seq, q1.shape_break AS from_shape_break, q2.shape_break AS to_shape_break FROM (SELECT stop_I, trip_I, shape_break, seq FROM stop_times) q1, (SELECT stop_I, trip_I, shape_break, seq AS seq FROM stop_times) q2 WHERE q1.seq=q2.seq-1 AND q1.trip_I=q2.trip_I AND q1.trip_I IN (SELECT trip_I FROM a) ), c AS( SELECT b.*, name, direction_id, route_I, a.shape_id, group_concat(lat) AS lats, group_concat(lon) AS lons, count(*) AS n_coords FROM b, a, shapes WHERE b.trip_I = a.trip_I AND shapes.shape_id=a.shape_id AND b.from_shape_break <= shapes.seq AND b.to_shape_break >= shapes.seq GROUP BY route_I, direction_id, b.seq ORDER BY route_I, b.seq ) SELECT from_stop_I, to_stop_I, group_concat(trip_I) AS trip_ids, group_concat(direction_id) AS direction_ids, lats, lons FROM c WHERE n_coords > 1 GROUP BY from_stop_I, to_stop_I ORDER BY count(*) DESC""") df["geometry"] = df.apply(lambda row: shapely.LineString([ (float(lon), float(lat)) for lon, lat in zip(row["lons"].split(","), row["lats"].split(",")) ]), axis=1) gdf = GeoDataFrame(df, crs=self.crs_wgs, geometry=df["geometry"]) #gdf = gdf.to_crs(self.crs_eurefin) gdf = gdf.to_crs(self.crs_wgs) gdf = gdf.drop(["lats", "lons"], axis=1) stops_set = set(gdf["from_stop_I"]) | set(gdf["to_stop_I"]) gdf["orig_parent_stops"] = list( zip(gdf['from_stop_I'], gdf['to_stop_I'])) clustered_stops = self.cluster_stops(stops_set) cluster_dict = clustered_stops[[ "new_stop_I", "stop_I", "geometry" ]].set_index('stop_I').T.to_dict('list') geom_dict = clustered_stops[[ "new_stop_I", "geometry" ]].set_index("new_stop_I").T.to_dict('list') gdf["to_stop_I"] = gdf.apply( lambda row: cluster_dict[row["to_stop_I"]][0], axis=1) gdf["from_stop_I"] = gdf.apply( lambda row: cluster_dict[row["from_stop_I"]][0], axis=1) # to/from_stop_I: cluster id # orig_parent_stops: old id # child_stop_I: cluster id splitted_gdf = self.split_shapes_by_nearby_stops(clustered_stops, gdf) splitted_gdf['child_stop_I'] = splitted_gdf.apply( lambda row: ",".join([str(int(x)) for x in row.child_stop_I]), axis=1) splitted_gdf_grouped = splitted_gdf.groupby(['child_stop_I']) splitted_gdf_grouped = splitted_gdf_grouped.agg( { 'orig_parent_stops': lambda x: tuple(x), 'geometry': lambda x: x.iloc[0] }, axis=1) splitted_gdf = splitted_gdf_grouped.reset_index() splitted_gdf['value'] = splitted_gdf.apply(lambda row: 1, axis=1) #splitted_gdf = splitted_gdf.set_geometry(splitted_gdf["geometry"], crs=self.crs_eurefin) splitted_gdf = self.match_shapes(splitted_gdf) splitted_gdf["rand"] = np.random.randint(1, 10, splitted_gdf.shape[0]) print(splitted_gdf) self.plot_geopandas(splitted_gdf, alpha=0.3)
def HorizontalMids (self, width, height): topleft = Pnt.getTopLeft(self.points) midleft = (topleft.x(), round(topleft.y()+width/2,2)) midright = (topleft.x() + height, round(topleft.y() + width/2,2)) Mid = linestring.LineString([midright, midleft]) return Mid, midright[1]
def toShape(x): if (len(x) == 2): return linestring.LineString(x) return polygon.asPolygon(x)
def toShape(x): if (len(x) == 2): return linestring.LineString(x)
def shape_factory(self, *args): return linestring.LineString(*args)
def VerticalalMids(self, width, height): topleft = Pnt.getTopLeft(self.points) midleft = (round(topleft.x()+width/2,2),topleft.y()) midright= (round(topleft.x()+width/2,2),topleft.y()+height) Mid = linestring.LineString([midright, midleft]) return Mid, midright[0]