def target(x, pattern: BaseGeometry, pos: BaseGeometry): params = _TargetTransformParams(x[0], x[1], x[2], x[3]) pos_trans = _target_affine_transform(pos, params) neg = box(*pos_trans.bounds).difference(pos_trans) # neg = box(*pos.bounds).difference(pos) # neg_trans = _target_affine_transform(neg, params) pos_overlap = pattern.intersection(pos_trans).area neg_overlap = pattern.intersection(neg).area false_pos_overlap = pos_trans.difference(pattern).area # return neg_overlap+false_pos_overlap-pos_overlap return false_pos_overlap - 2.0 * pos_overlap + neg_overlap + 0.1 * abs( x[0]) + 0.1 * abs(x[1])
def find_shape_in_index(shape: BaseGeometry, index): # (minx, miny, maxx, maxy) bounds = shape.bounds lon = [] lat = [] weights = [] for result in index.intersection(bounds, objects="raw"): point = result['point'] rect = result['bbox'] poly = Polygon([(r[0], r[1]) for r in rect]) inters = shape.intersection(poly) # Intersection with bounds might not intersect with detailed poly if inters: weights.append(inters.area) lon.append(point[0]) lat.append(point[1]) lon = np.array(lon) lat = np.array(lat) weights = np.array(weights) weights = weights / np.sum(weights) return GridLookupResults(lon, lat, weights)
def make_geom(geo_frame, voronoi_frame): #new columns to add voronoi_frame['area'] = None #create full continent of europe euro_geoms = [ geo_frame.loc[index]['geometry'] for index in range(len(geo_frame)) ] all_europe = unary_union(euro_geoms) #test to see if voronoi shapes intersect with the europe shape for index in range(len(voronoi_frame)): current_shape = voronoi_frame.loc[index]['points'] intersect = BaseGeometry.intersection(all_europe.buffer(0), current_shape.buffer(0)) voronoi_frame.loc[index, 'geometry'] = intersect voronoi_frame.loc[index, 'area'] = intersect.area #there is always an error where index 39 should be a part of norway (index 40) nshape = voronoi_frame.loc[40]['geometry'] missing_part = voronoi_frame.loc[39]['geometry'] voronoi_frame.loc[40]['geometry'] = unary_union([nshape, missing_part]) voronoi_frame.loc[39] = None return voronoi_frame
def make_geoms(vframe, geo_frame): vframe['geometry'] = None poly = geo_frame.unary_union for index in range(135): try: loop_geom = BaseGeometry.intersection( vframe.loc[index]['points'].buffer(0), poly.buffer(0)) vframe.loc[index, 'geometry'] = loop_geom except: True #set projection as mercator for the new data frame vframe.crs = {'init': 'epsg = 3395'} return vframe
x, y = list(zip(*loop_points)) loop_points = list(zip(y, x)) poly = Polygon(loop_points) voronoi_frame.loc[i, 'geometry'] = [] voronoi_frame.loc[i, 'points'] = poly i += 1 except (ValueError, TypeError): True # PART 3: Make Voronoi shapes fit Brazil's shape voronoi_frame['area'] = None br_geoms = [cap.loc[i]['Geometria'] for i in range(len(cap))] all_br = unary_union(br_geoms) for i in range(len(voronoi_frame)): cur_shape = voronoi_frame.loc[i]['points'] intersect = BaseGeometry.intersection(all_br.buffer(0), cur_shape.buffer(0)) if i == 0: # We have to deal this way with the State of Acre intersect = ( all_br.buffer(0) ) # This state is known as nowhere land. It's the Brazilian Wyoming. voronoi_frame.loc[i, 'geometry'] = intersect voronoi_frame.loc[i, 'area'] = intersect.area # PART 4: Plot the map voronoi_frame['map color'] = [ 1, 2, 3, 4, 3, 4, 1, 2, 4, 2, 2, 1, 1, 2, 3, 4, 1, 2, 3, 4, 2, 1, 4, 3, 4, 2, 1 ] capital_pts = [(cap.loc[index]['Latitude'], cap.loc[index]['Longitude']) for index in range(len(cap))] fig, ax = plt.subplots()
def intersect_geometry_with_feature_class(geometry: BaseGeometry, in_layer_path: str, output_geom_type: int, epsg: int = None, attribute_filter: str = None, ) -> BaseGeometry: """[summary] Args: geometry (BaseGeometry): [description] in_layer_path (str): [description] out_layer_path (str): [description] output_geom_type (int): [description] epsg (int, optional): [description]. Defaults to None. attribute_filter (str, optional): [description]. Defaults to None. Raises: VectorBaseException: [description] VectorBaseException: [description] Returns: BaseGeometry: [description] """ log = Logger('intersect_geometry_with_feature_class') if output_geom_type not in [ogr.wkbMultiPoint, ogr.wkbMultiLineString]: raise VectorBaseException('Unsupported ogr type for geometry intersection: "{}"'.format(output_geom_type)) log.debug('Intersection with feature class: Performing unary union on input: {}'.format(in_layer_path)) geom_union = get_geometry_unary_union(in_layer_path, epsg=epsg, attribute_filter=attribute_filter, clip_shape=geometry) # Nothing to do if there were no features in the feature class if not geom_union: return log.debug('Finding intersections (may take a few minutes)...') tmr = Timer() geom_inter = geometry.intersection(geom_union) log.debug('Intersection done in {:.1f} seconds'.format(tmr.ellapsed())) # Nothing to do if the intersection is empty if geom_inter.is_empty: return # Single features and collections need to be converted into Multi-features if output_geom_type == ogr.wkbMultiPoint and not isinstance(geom_inter, MultiPoint): if isinstance(geom_inter, Point): geom_inter = MultiPoint([(geom_inter)]) elif isinstance(geom_inter, LineString): # Break this linestring down into vertices as points geom_inter = MultiPoint([geom_inter.coords[0], geom_inter.coords[-1]]) elif isinstance(geom_inter, MultiLineString): # Break this linestring down into vertices as points geom_inter = MultiPoint(reduce(lambda acc, ls: acc + [ls.coords[0], ls.coords[-1]], list(geom_inter.geoms), [])) elif isinstance(geom_inter, GeometryCollection): geom_inter = MultiPoint([geom for geom in geom_inter.geoms if isinstance(geom, Point)]) elif output_geom_type == ogr.wkbMultiLineString and not isinstance(geom_inter, MultiLineString): if isinstance(geom_inter, LineString): geom_inter = MultiLineString([(geom_inter)]) else: raise VectorBaseException('Unsupported ogr type: "{}" does not match shapely type of "{}"'.format(output_geom_type, geom_inter.type)) return geom_inter
def voronoi_tesselation(region = read_gis()): region_shape = region.unary_union region['points'] = None region['city'] = None #read locations of city from file with pandas top_cities = pd.read_csv('europe_1mil.csv') x, y = top_cities['mercx'].tolist(), top_cities['mercy'].tolist() name = top_cities['city_ascii'].tolist() city_locs = [(name[index], (float(x[index]), float(y[index]))) for index in range(len(name))] points = [item[1] for item in city_locs] #add four extra points to later ignore points.append((-500000000,-500000000)) points.append((-500000000,500000000)) points.append((500000000,-500000000)) points.append((500000000,500000000)) vor = Voronoi(points) regions = vor.regions pts = vor.vertices i = 0 for part in regions: loop_points = [] if -1 not in part and part != []: loop_points = [pts[part[index]] for index in range(len(part))] poly = Polygon(loop_points) region.loc[i, 'points'] = poly name_index = 0 for point in points: if poly.contains(Point(point)): region.loc[i, 'city'] = city_locs[name_index][0] break name_index += 1 i += 1 #only want to keep the ones that have city data keep = [index for index in range(len(region)) if isinstance(region.iloc[index]['city'], str)] keep = [region.index[item] for item in keep] #filter out the rest region = region.filter(keep, axis = 0) #make geometry intersection of region geometry and voronoi tesselation extras = [] for index in range(len(region)): current_vor = region.loc[index]['points'] geom = BaseGeometry.intersection(current_vor.buffer(0), region_shape.buffer(0)) region.at[index, 'geometry'] = geom current_city = region.loc[index]['city'] color_1 = ['Dublin','London','Hamburg','Warsaw','Mannheim','Munich', 'Marseille', 'Rabat','Rome','Budapest','Athens','Bursa', 'Adana','El Giza','Amman','Karaj','Shiraz','Moscow', 'Yekaterinburg'] color_2 = ['Birmingham','Paris','Essen','Madrid','Milan','Stockholm', 'Kiev','Nizhny Novgorod','Istanbul','Aleppo','Tel Aviv-Yafo', 'Baghdad','Tbilisi','Tehran','Chelyabinsk'] color_3 = ['Lisbon','Copenhagen','Frankfurt','Turin','Algiers','Belgrade', 'Katowice','St. Petersburg','Kharkiv','Kazan','Tabriz', 'Kuwait','Cairo','Beirut','Ankara'] color_4 = ['Brussels','Stuttgart','Tunis','Vienna','Alexandria','Minsk', 'Izmir','Rostov','Yerevan','Damascus','Mashhad'] color_5 = ['Barcelona','Berlin','Bucharest','Naples','Tripoli','Mosul', 'Isfahan','Baku', 'Manchester','Casablanca'] if current_city in color_1: region.loc[index, 'color'] = 1 elif current_city in color_2: region.loc[index, 'color'] = 2 elif current_city in color_3: region.loc[index, 'color'] = 3 elif current_city in color_4: region.loc[index, 'color'] = 4 elif current_city in color_5: region.loc[index, 'color'] = 5 else: region.loc[index, 'color'] = 6 return region.to_crs(epsg = 4326)
def is_inside(a: BaseGeometry, b: BaseGeometry, *, threshold: float = 0.05) -> bool: """ Checks if one geometry (a) is inside other (b)""" return a.intersection(b).area / (b.area + 1e-8) >= threshold