def generate_subpanel_bridges(dxf_outline_space, dxf_drill_space, area, cutout_width, count_x, count_y): __generate_bridges(dxf_outline_space, area, count_x, count_y) frame_lines = MultiLineString(cutout_lines) generate_mouse_bites(area, dxf_drill_space, frame_lines) for splitter in splitter_rectangles: frame_lines = frame_lines.difference(splitter) # Merge all lines, so the endpoints are not where lines cross frame_lines = ops.linemerge(frame_lines) inset_lines = [] for frame_line in frame_lines: line = frame_line.parallel_offset(2, 'left') # line2 = frame_line.parallel_offset(2, 'right') if frame_line.boundary and line.boundary: inset_line = LineString([frame_line.boundary[0], line.boundary[0]]) inset_lines.append(inset_line) inset_line = LineString([frame_line.boundary[1], line.boundary[1]]) inset_lines.append(inset_line) line = frame_line.parallel_offset(2, 'right') if frame_line.boundary and line.boundary: inset_line = LineString([frame_line.boundary[0], line.boundary[1]]) inset_lines.append(inset_line) inset_line = LineString([frame_line.boundary[1], line.boundary[0]]) inset_lines.append(inset_line) # frame_lines = frame_lines.union(inset_line) inset_lines = MultiLineString(inset_lines) dilated_insets = inset_lines.buffer(cutout_width / 3, join_style=1) # Remove outward bridges TODO: Needs better solution, this one is a quick hack TODO: Check if interior exterior # of polygon would work: https://gis.stackexchange.com/questions/341604/creating-shapely-polygons-with-holes # dilated_insets = clean_outer_perimeter(area, dilated_insets) # Merge cutouts and insets dilated = frame_lines.buffer(cutout_width / 2, cap_style=2, join_style=2) dilated = dilated.union(dilated_insets) # Round the corners of insets dilated = dilated.buffer(0.8, join_style=1).buffer(-0.8, join_style=1) for element in dilated: dxf_outline_space.add_lwpolyline(element.exterior.coords)
def find_regions(ml: MultiLineString, alts: list): lon_bounds = [ml.bounds[0], ml.bounds[2]] lat_bounds = [ml.bounds[1], ml.bounds[3]] multi_line_buffered = ml.buffer(0.0001) diff_regions = ml.envelope.difference(multi_line_buffered) # Pad with zeros if necessary if len(diff_regions) > len(alts): alts.extend([0.0] * (len(diff_regions) - len(alts))) i = 0 regions = [] region_data = pd.DataFrame(columns=["lat", "lon", "alt", "region_num"]) for num, geom in enumerate(diff_regions): if any(x in lon_bounds for x in geom.exterior.xy[0]) and any( y in lat_bounds for y in geom.exterior.xy[1]): continue else: for lon, lat in zip(geom.exterior.xy[0], geom.exterior.xy[1]): regions.append(geom) region_data.loc[i, "lat"] = lat region_data.loc[i, "lon"] = lon region_data.loc[i, "alt"] = alts[num] region_data.loc[i, "region_num"] = num i += 1 return region_data, regions
def expose_to_environment(self, coords): creature = MultiLineString(coords) creature_length = creature.length creature_feed_area = creature.buffer(self.feed_radius) fitness = self.get_fitness(creature_feed_area) return creature_length, creature_feed_area, fitness
def plot_with_feed_zones(self): """ a plotting tool for branching creatures Returns ------- """ fig = plt.figure(1, figsize=(5, 5), dpi=180) ax = fig.add_subplot(111) line = MultiLineString(self.coords) patches = [PolygonPatch(circ) for circ in self.feed_zones] for patch in patches: ax.add_patch(patch) dilated = line.buffer(self.feed_radius) patch1 = PolygonPatch(dilated, facecolor='#99ccff', edgecolor='#6699cc') ax.add_patch(patch1) for i in range(len(self.coords)): x, y = line[i].xy plt.axis('equal') ax.plot(x, y, color='#999999') plt.show()
def plot_buff(G_, ax, buff=20, color='yellow', alpha=0.3, title='Proposal Snapping', title_fontsize=8, outfile='', dpi=200, verbose=False): '''plot buffer around graph using shapely buffer''' # get lines line_list = [] for u, v, key, data in G_.edges(keys=True, data=True): if verbose: print("u, v, key:", u, v, key) print(" data:", data) geom = data['geometry'] line_list.append(geom) mls = MultiLineString(line_list) mls_buff = mls.buffer(buff) if verbose: print("type(mls_buff) == MultiPolygon:", type(mls_buff) == shapely.geometry.MultiPolygon) if type(mls_buff) == shapely.geometry.Polygon: mls_buff_list = [mls_buff] else: mls_buff_list = mls_buff for poly in mls_buff_list: x, y = poly.exterior.xy coords = np.stack((x, y), axis=1) interiors = poly.interiors #coords_inner = np.stack((x_inner,y_inner), axis=1) if len(interiors) == 0: #ax.plot(x, y, color='#6699cc', alpha=0.0, linewidth=3, solid_capstyle='round', zorder=2) ax.add_patch( matplotlib.patches.Polygon(coords, alpha=alpha, color=color)) else: path = pathify(poly) patch = PathPatch(path, facecolor=color, edgecolor=color, alpha=alpha) ax.add_patch(patch) ax.axis('off') if len(title) > 0: ax.set_title(title, fontsize=title_fontsize) #outfile = os.path.join(res_dir, 'gt_raw_buffer.png') if outfile: plt.savefig(outfile, dpi=dpi) return ax
def extract(self, region: Union[Polygon, MultiPolygon], linestrings: MultiLineString) -> MultiPolygon: info("%sApplying buffer of %s.", "(" + self.name + ") " if self.name else "", self.epsilon) buffered = linestrings.buffer(self.epsilon) info("%sCalculating difference.", "(" + self.name + ") " if self.name else "") difference = region.difference(buffered) return MultiPolygon([difference ]) if difference.type == "Polygon" else difference
def generate_pcb_bridges(dxf_modelspace, area, cutout_width, count_x, count_y): __generate_bridges(dxf_modelspace, area, count_x, count_y) frame_lines = MultiLineString(cutout_lines) for splitter in splitter_rectangles: frame_lines = frame_lines.difference(splitter) dilated = frame_lines.buffer(cutout_width / 2) for element in dilated: dxf_modelspace.add_lwpolyline(element.exterior.coords)
def urban_blocks(roads, aoi, types_of_roads=None): """Extract urban blocks from the road network. Here, blocks are defined as the difference between the whole area of interest and the buffered road network. Roads and AOI must have the same CRS. Parameters ---------- roads : GeoDataFrame OSM roads. aoi : geometry Area of interest as a shapely geometry. types_of_roads : list of str List of `highway` tags included in the analysis. Returns ------- blocks : GeoDataFrame Urban blocks as a GeoDataFrame. """ crs = roads.crs # Only include the provided road types if types_of_roads: roads = roads[roads.highway.isin(types_of_roads)] # Clean the roads geodataframe. If some geometries are # MultiLineString, convert them to multiple LineStrings def _to_linestrings(geoms): lines = [] for geom in geoms: if isinstance(geom, MultiLineString): for linestring in geom: lines.append(linestring) else: lines.append(geom) return lines # Blocks are the polygons resulting from the difference binary # predicate between the AOI and the buffered road network geoms = _to_linestrings(roads.geometry) geoms = MultiLineString([geom for geom in geoms if geom.is_valid]) geoms = linemerge(geoms) road_network = geoms.buffer(1, resolution=1, cap_style=3) geometries = aoi.difference(road_network) # Put the geometries into a GeoDataFrame dataframe = gpd.GeoDataFrame( index=[x for x in range(len(geometries))], columns=['geometry']) dataframe.geometry = [geom for geom in geometries] dataframe.crs = crs return dataframe
def plot(lines): fig = plt.figure(1, figsize=(5, 5), dpi=180) ax = fig.add_subplot(111) line = MultiLineString(lines) dilated = line.buffer(0.5) patch1 = PolygonPatch(dilated, facecolor='#99ccff', edgecolor='#6699cc') ax.add_patch(patch1) for i in range(len(lines)): x, y = line[i].xy plt.axis('equal') ax.plot(x, y, color='#999999') plt.show()
def plot_buff(G_, ax, buff=20, color='yellow', alpha=0.3, title='Proposal Snapping', title_fontsize=8, outfile='', dpi=200, verbose=False): '''plot buffer around graph using shapely buffer''' # get lines line_list = [] for u, v, key, data in G_.edges(keys=True, data=True): if verbose: print("u, v, key:", u, v, key) print(" data:", data) geom = data['geometry'] line_list.append(geom) mls = MultiLineString(line_list) mls_buff = mls.buffer(buff) if verbose: print("type(mls_buff) == MultiPolygon:", type(mls_buff) == shapely.geometry.MultiPolygon) if type(mls_buff) == shapely.geometry.Polygon: mls_buff_list = [mls_buff] else: mls_buff_list = mls_buff for poly in mls_buff_list: x,y = poly.exterior.xy coords = np.stack((x,y), axis=1) interiors = poly.interiors #coords_inner = np.stack((x_inner,y_inner), axis=1) if len(interiors) == 0: #ax.plot(x, y, color='#6699cc', alpha=0.0, linewidth=3, solid_capstyle='round', zorder=2) ax.add_patch(matplotlib.patches.Polygon(coords, alpha=alpha, color=color)) else: path = pathify(poly) patch = PathPatch(path, facecolor=color, edgecolor=color, alpha=alpha) ax.add_patch(patch) ax.axis('off') if len(title) > 0: ax.set_title(title, fontsize=title_fontsize) #outfile = os.path.join(res_dir, 'gt_raw_buffer.png') if outfile: plt.savefig(outfile, dpi=dpi) return ax
def case4(): """ expected length 2.0 area 1 + 2 * o.76 = 2.5682742 Returns ------- """ line1 = [(-0.5, 0), (0.5, 0)] line2 = [(0, -0.5), (0, 0.5)] lines = [line1, line2] line = MultiLineString(lines) dilated = line.buffer(0.5) length = line.length area = dilated.area print("length : {0} \t area {1}:".format(length, area)) return lines
def case2(): """ expected length 2.0 area 1 + 1 + 2 * 0.7854 = 3.5708 Returns ------- """ line1 = [(0, 0), (1, 0)] line2 = [(0, 1.0), (1, 1.0)] lines = [line1, line2] line = MultiLineString(lines) dilated = line.buffer(0.5) length = line.length area = dilated.area print("length : {0} \t area {1}:".format(length, area)) return lines
def case5(): """ expected length 2.0 area 1 + 0.76 = 1.76 Returns ------- """ line1 = [(0, 0), (0, 1)] line2 = [(0, 0), (0, 1)] lines = [line1, line2] line = MultiLineString(lines) dilated = line.buffer(0.5) length = line.length area = dilated.area print("length : {0} \t area {1}:".format(length, area)) return lines
from shapely.ops import polygonize, polygonize_full, transform, linemerge shapely_line_strings = [LineString(x) for x in snap_lines] # add bounding lines needed by polygonize (it's easy to do per pixel. TODO refactor to create only necessary lines) #for i in xrange(sz): # pair_lines.append(((0,i),(0,i+1))) # pair_lines.append(((sz,i),(sz,i+1))) # pair_lines.append(((i,0),(i+1,0))) # pair_lines.append(((i,sz),(i+1,sz))) #ps = list(polygonize(shapely_line_strings)) # simple polygonize doesn't work. it is a trick (see http://gis.stackexchange.com/questions/58245/generate-polygons-from-a-set-of-intersecting-lines) M = MultiLineString(shapely_line_strings) MB = M.buffer(0.001) P = Polygon([(0, 0), (0, sz), (sz, sz), (sz, 0)]) pso = P.difference(MB) # round vertices coords ps = [] for p in pso: pb = p.buffer(0.001) pbt = transform(lambda x, y, z=None: (int(round(x)), int(round(y))), pb) ps.append(pbt) # associate LineString_s with Polygon_s pt_polygon_index = dict(); for p in ps: for pt in p.exterior.coords:
# (._;>;); # out geom;""".format(poly_osmid), # build=False, responseformat="json") # # Collect coords into list coords = [] for element in poly_resp['elements']: if element['type'] == 'way': one_line = [] for j in range(len(element['geometry'])): lon = element['geometry'][j]['lon'] lat = element['geometry'][j]['lat'] one_line.append((lon, lat)) coords.append(LineString(one_line)) # ml = MultiLineString(coords) buff_ml = ml.buffer(0.000000003) pl = ml.convex_hull diff = pl.difference(buff_ml) lst_len = [] i = 0 max_ind = -1 for i in range(len(diff)): len_poly = diff[i].length lst_len.append(len_poly) if len_poly == max(lst_len): max_ind = i # boundary = diff[max_ind] gdf_poly = gpd.GeoDataFrame(geometry=[boundary]) gdf_poly['osm_id'] = poly_osmid gdf_poly.crs = 'epsg:4326'
def _salvar_nos_rastreados(self, vertices: np.ndarray): """Salva os nós rastreados pelo layer 'rastreador_nos{i}'""" linhas_layers = self._dicionario_linhas_dxf() pontos_layers = self._dicionario_pontos_dxf() dmed = self.diametro_medio_elementos(self.poligono_estrutura()) # Nós rastreados nos_rastreados = {} # KDTree kd = KDTree(vertices) multipontos = MultiPoint(vertices) nome_arq_txt = ARQUIVOS_DADOS_ZIP[16] if any( i.startswith(Malha.LAYER_RASTREADOR_NOS) for i in linhas_layers): for layer_rastreado in linhas_layers: if layer_rastreado.startswith(Malha.LAYER_RASTREADOR_NOS): linhas = [] nos_rastreados[layer_rastreado] = [] for lin in linhas_layers[layer_rastreado]: x1, y1, x2, y2 = lin linhas.append(LineString([(x1, y1), (x2, y2)])) multiline_i = MultiLineString(linhas) # Identificar pontos multiline_i = multiline_i.buffer(0.1 * dmed) pontos_contorno = multiline_i.intersection(multipontos) # Adicionando os nós rastreados pelas linhas if not isinstance(pontos_contorno, Point): if len(pontos_contorno) > 0: for p in pontos_contorno: nos_rastreados[layer_rastreado].append( kd.query(p.coords[:][0])[1]) else: nos_rastreados[layer_rastreado].append( kd.query(pontos_contorno.coords[:][0])[1]) # Adicionando os nós rastreados pelos pontos. pts = pontos_layers[layer_rastreado] for id_pt in range(pts.shape[0]): nos_rastreados[layer_rastreado].append( kd.query(pts[id_pt])[1]) # Salvar a identificação do ponto no arquivo with open(nome_arq_txt, 'w') as arq: for lay in nos_rastreados: if (len(nos_rastreados[lay])) > 0: arq.write( f'{lay} = {sorted(set(nos_rastreados[lay]))}\n') # Salvar no arquivo zip with zipfile.ZipFile(self.dados.arquivo.name, 'a', compression=zipfile.ZIP_DEFLATED) as arq_zip: arq_zip.write(pathlib.Path(nome_arq_txt).name) # Apagar o arquivo txt os.remove(nome_arq_txt)
def get_layer(filename): list_split = filename[:-4].rsplit("_") str_date = list_split[-2] + "_" + list_split[-1] rel_id = list_split[-3] poly_osmid = rel_id buff_km = 0 ### path_new = os.getcwd() path_data = path_new + '\\data\\' + str(poly_osmid) + '\\' + str_date path_res = path_data + '\\res' ### lrs = LayersReader(filename) def GirsGdf(lr_nm): new_df = lrs.get_geometries_and_field_values(layer_number=lr_nm, geometry_format='wkt') lst_geo = [] new_df = new_df.reset_index() del new_df['FID'] for i in (range(len(new_df))): one_geo = new_df._GEOM_[i] lst_geo.append(shapely.wkt.loads(one_geo)) # try: new_df['geometry'] = lst_geo del new_df['_GEOM_'] new_gdf = gpd.GeoDataFrame(new_df) new_gdf.crs = 'epsg:4326' except: pass del new_df return new_gdf # try: gdf_multipolygons = GirsGdf(3) except (RuntimeError): print("RuntimeError, data is too big") exit() #gdf_other = GirsGdf(4) del lrs #extract polygon of the city from all polygons gdf_poly = gdf_multipolygons[gdf_multipolygons.osm_id == poly_osmid][[ 'osm_id', 'name', 'place', 'other_tags', 'geometry' ]].reset_index(drop=True) # if len(gdf_poly) > 0: gdf_poly.crs = 'epsg:4326' try: #gdf_poly = gdf_poly.iloc[[0]] gdf_poly.geometry[0] = gdf_poly.geometry[0][0] except: pass # else: try: api = overpass.API() poly_resp = api.get("""[out:json][timeout:25]; relation({}); (._;>;); out geom;""".format(poly_osmid), build=False, responseformat="json") # Collect coords into list coords = [] for element in poly_resp['elements']: if element['type'] == 'way': one_line = [] for j in range(len(element['geometry'])): lon = element['geometry'][j]['lon'] lat = element['geometry'][j]['lat'] one_line.append((lon, lat)) coords.append(LineString(one_line)) # ml = MultiLineString(coords) buff_ml = ml.buffer(0.000000003) pl = ml.convex_hull diff = pl.difference(buff_ml) lst_len = [] i = 0 max_ind = -1 for i in range(len(diff)): len_poly = diff[i].length lst_len.append(len_poly) if len_poly == max(lst_len): max_ind = i # boundary = diff[max_ind] gdf_poly = gpd.GeoDataFrame(geometry=[boundary]) gdf_poly['osm_id'] = poly_osmid gdf_poly.crs = 'epsg:4326' except: pass # if int(buff_km) > 0: buffer = int(buff_km) * 1000 try: gdf_poly.geometry = gdf_poly.geometry.to_crs('epsg:32637').buffer( buffer).to_crs('epsg:4326') except: pass # ###################### gdf_buildings = gdf_multipolygons[~gdf_multipolygons.building.isna( )].reset_index(drop=True) gdf_buildings = gpd.sjoin(gdf_buildings, gdf_poly[['geometry']], how='inner', op='intersects') gdf_buildings = gdf_buildings.drop("index_right", axis=1).reset_index(drop=True) ############################### # сохранение без геометрии - нужны только поля. # если кодировка просто utf-8, то сохраняются каракули вместо букв, # а windows-1251 или cp1251 не декодируют какие-то конкретные символы, я хз почему # обрезать для сохранения в шейп gdf_buildings_shp = gdf_buildings.copy() i = 0 for i in range(len(gdf_buildings_shp)): if len(str(gdf_buildings_shp.other_tags[i])) > 254: gdf_buildings_shp.other_tags[i] = gdf_buildings_shp.other_tags[ i][:254] # gdf_buildings_shp.to_file("{}\\gdf_buildings_{}_{}.shp".format( path_res, rel_id, str_date), encoding="utf-8") try: gdf_poly.to_file('{}\\poly_{}_{}.shp'.format(path_res, rel_id, str_date), encoding='utf-8') except: pass print("Borders of the region are not saved to shp")
def generate_geometry(self, type, **kwargs): """Generate a `shapely` entity according to the geometry description provided. The input `type` containts the name of the geometry to be generated and the necessary arguments must be provided in the `dict` input `description`. Possible geometries according to the different input values in `type` are: * `area` ```python description=dict( points=[ [0, 0, 0], [0, 1, 1], ... ] # List of 3D points that describe the vertices of the plane area ) ``` * `line` ```python description=dict( points=[ [0, 0, 0], [0, 1, 1], ... ] # List of 3D points that describe the line ) ``` * `circle` ```python description=dict( center=[-6.8, -6.8, 0] # Center of the circle radius=0.2 # Radius of the circle ) ``` **Others are still not implemented** > *Input arguments* * `type` (*type:* `str`): Geometry type. Options are: `line`, `area`, `volume`, `multi_line`, `multi_point`, `circle` * `description` (*type:* `dict`): Arguments to describe the geometry """ if type == 'area' and 'points' in kwargs: return MultiPoint([(x[0], x[1]) for x in kwargs['points']]).convex_hull elif type == 'line' and 'points' in kwargs: line = LineString([(x[0], x[1]) for x in kwargs['points']]) if 'buffer' in kwargs: assert kwargs['buffer'] > 0, \ 'Buffer around line must be greater than 0' return line.buffer(kwargs['buffer']) else: return line elif type == 'multipoint' and 'points' in kwargs: points = MultiPoint([(x[0], x[1]) for x in kwargs['points']]) if 'buffer' in kwargs: assert kwargs['buffer'] > 0, \ 'Buffer around line must be greater than 0' return points.buffer(kwargs['buffer']) else: return points elif type == 'multiline' and 'lines' in kwargs: lines = MultiLineString(kwargs['lines']) if 'buffer' in kwargs: assert kwargs['buffer'] > 0, \ 'Buffer around line must be greater than 0' return lines.buffer(kwargs['buffer']) else: return lines elif type == 'circle' and \ 'center' in kwargs and 'radius' in kwargs: return shapes.circle(**kwargs) elif type == 'polygon' and 'polygon' in kwargs: assert isinstance(kwargs['polygon'], (Polygon, MultiPolygon)) assert not kwargs['polygon'].is_empty, 'Polygon is empty' assert kwargs['polygon'].area > 0, 'Polygon area is zero' return kwargs['polygon'] elif type == 'box': assert 'size' in kwargs return trimesh.creation.box(extents=kwargs['size']) elif type == 'sphere': assert 'radius' in kwargs assert kwargs['radius'] > 0 return trimesh.creation.icosphere(radius=kwargs['radius']) elif type == 'cylinder': assert 'radius' in kwargs assert kwargs['radius'] > 0 assert 'length' in kwargs assert kwargs['length'] > 0 return trimesh.creation.cylinder(radius=kwargs['radius'], height=kwargs['length']) elif type == 'mesh': if 'mesh' in kwargs: if isinstance(kwargs['mesh'], trimesh.base.Trimesh): return kwargs['mesh'] elif isinstance(kwargs['mesh'], trimesh.scene.Scene): return kwargs['mesh'].convex_hull else: raise ValueError('Invalid input mesh') elif 'model' in kwargs: if 'mesh_type' in kwargs: assert kwargs['mesh_type'] in ['collision', 'visual'] mesh_type = kwargs['mesh_type'] else: mesh_type = 'collision' if isinstance(kwargs['model'], SimulationModel): return kwargs['model'].create_scene( mesh_type=mesh_type).convex_hull else: raise ValueError('Invalid input simulation model') elif 'entity' in kwargs: if 'mesh_type' in kwargs: assert kwargs['mesh_type'] in ['collision', 'visual'] mesh_type = kwargs['mesh_type'] else: mesh_type = 'collision' if isinstance(kwargs['entity'], Entity) and \ not isinstance(kwargs['entity'], SimulationModel): return kwargs['entity'].create_scene(mesh_type=mesh_type, ignore_models=[ 'ground_plane' ]).convex_hull elif 'points' in kwargs: points = np.array(kwargs['points']) assert points.shape[1] == 3 assert points.shape[0] > 3 points = trimesh.points.PointCloud(points) return points.convex_hull else: raise NotImplementedError( 'Invalid geometry type, provided={}'.format(type))
from shapely.ops import polygonize, polygonize_full, transform, linemerge shapely_line_strings = map(lambda x: LineString(x), snap_lines) # add bounding lines needed by polygonize (it's easy to do per pixel. TODO refactor to create only necessary lines) #for i in xrange(sz): # pair_lines.append(((0,i),(0,i+1))) # pair_lines.append(((sz,i),(sz,i+1))) # pair_lines.append(((i,0),(i+1,0))) # pair_lines.append(((i,sz),(i+1,sz))) #ps = list(polygonize(shapely_line_strings)) # simple polygonize doesn't work. it is a trick (see http://gis.stackexchange.com/questions/58245/generate-polygons-from-a-set-of-intersecting-lines) M = MultiLineString(shapely_line_strings) MB = M.buffer(0.001) P = Polygon([(0, 0), (0, sz), (sz, sz), (sz, 0)]) pso = P.difference(MB) # round vertices coords ps = [] for p in pso: pb = p.buffer(0.001) pbt = transform(lambda x, y, z=None: (int(round(x)), int(round(y))), pb) ps.append(pbt) # associate LineString_s with Polygon_s pt_polygon_index = dict() for p in ps: for pt in p.exterior.coords:
def create(vehicle_id, start_date, end_date): csv.field_size_limit(1000000000) connection = pymysql.connect(host='000.000.000.00', user='******', password='******', db='database', charset='utf8mb4', cursorclass=pymysql.cursors.SSDictCursor) cur = connection.cursor() # execute a select query and return results as a generator def generator(stmt): # error handling code removed cur.execute(stmt) for row in cur: yield row sql = "select latitude, longitude from ngp.hist_trackrecords where device_id='%s' and reportstamp between '%s' and '%s'" % ( vehicle_id, start_date, end_date) pts = set() for l in generator(sql): pts.add(str(Point(l['longitude'], l['latitude']))) connection.close() point_list = list(pts) road = open('roads.csv') read = csv.reader(road) for j in read: m = loads(j[0]) line_list = [] c = 0 for r in point_list: if c != (len(point_list) - 1): line = LineString([ m.interpolate(m.project(loads(r))), m.interpolate(m.project(loads(point_list[c + 1]))) ]) line_list.append(line) c += 1 ml = MultiLineString(line_list) geom = ogr.CreateGeometryFromWkt(str(ml)) length = int(geom.Length()) bml_in = str(ml.buffer(.0001)) cut = re.split(r'[()]', bml_in) cut2 = re.split(r'[,]', cut[2]) nodes = [] if cut2 == [''] or len(cut2) < 3: pass else: for coords in cut2: cut3 = re.split(r'[ ]', coords) retype = float(cut3[1]), float(cut3[0]) nodes.append(tuple(retype)) bml_out = Polygon(nodes) return bml_out, length