Materials: * Points in polygon
We need the libraries:
import os, sys, gzip, random, csv, json, datetime, re
import numpy as np
import pandas as pd
import scipy as sp
import matplotlib.pyplot as plt
import geopandas as gpd
from scipy.spatial import cKDTree
from scipy import inf
import shapely as sh
= "~/raw/" baseDir
= pd.read_csv(baseDir + "poi.csv")
poi #x,y,name,region,bla bla
Coordinates in region:
= gpd.GeoDataFrame.from_file(baseDir + "gis/geo/bundesland.shp")
region = region['GEN']
region.index = region['geometry']
region = poi[['x','y']].apply(lambda x: sh.geometry.Point(x[0],x[1]),axis=1)
pL = gpd.GeoDataFrame(geometry=pL)
pnts = pnts.assign(**{key: pnts.within(geom) for key, geom in region.items()})
pnts for i in pnts.columns[1:]:
"region"] = i poi.loc[pnts[i],
Cluster coordinates within a distance
from scipy.cluster.hierarchy import dendrogram, linkage
from scipy.cluster.hierarchy import fcluster
= linkage(poi[['x','y']], 'ward')
Z = 111122.19769899677
gradMeter = 1500./gradMeter
max_d 'id_zone'] = fcluster(Z,max_d,criterion='distance') poi.loc[:,
Calculate orientation of a segment, orthogonal distance from segment to reference point, calculates chirality
= np.sqrt((nodeL['x1'] - nodeL['x_poi'])**2 + (nodeL['y1'] - nodeL['y_poi'])**2)
dist1 = np.sqrt((nodeL['x2'] - nodeL['x_poi'])**2 + (nodeL['y2'] - nodeL['y_poi'])**2)
dist2 'dist'] = np.min([dist1,dist2],axis=0)
nodeL.loc[:,"orth_dist"] = np.abs((nodeL['x2']-nodeL['x1'])*(nodeL['y1']-nodeL['y_poi'])-(nodeL['y2']-nodeL['y1'])*(nodeL['x1']-nodeL['x_poi']))
nodeL.loc[:,"orth_dist"] = nodeL["orth_dist"]/(np.abs((nodeL['x2']-nodeL['x1'])) + np.abs((nodeL['y2']-nodeL['y1'])))
nodeL.loc[:,"dist"] = nodeL['orth_dist']*nodeL['dist']
nodeL.loc[:,= [nodeL['x1'] - metr['deCenter'][0],nodeL['y1'] - metr['deCenter'][1]]
v1 = [nodeL['x2'] - nodeL['x1'],nodeL['y2'] - nodeL['y1']]
v2 = v1[0]*v2[1] - v2[0]*v1[1]
crossP 'chirality_v'] = 1.*(crossP > 0.) nodeL.loc[:,
Calculates the chirality between two angles
'angle'] = np.arctan2((poi['y']-poi['y_mot']),(poi['x']-poi['x_mot']))*180./np.pi
poi.loc[:,'angle'] = - poi.loc[:,'angle']
poi.loc[:,'tang'] = np.arctan2(metr['deCenter'][1]-poi['y'],metr['deCenter'][0]-poi['x'])*180./np.pi
poi.loc[:,'tang'] = 90. - poi.loc[:,'tang']
poi.loc[:,'tang']>180.,'tang'] -= 180.
poi.loc[poi[= np.abs(poi['tang']-poi['angle'])
t >180.] = 360.-t
t[t'chirality'] = 1*(t>90) poi.loc[:,
Calculates the tangent point on a line from a reference point
from shapely.ops import split, snap
from shapely import geometry, ops
= gpd.GeoDataFrame.from_file(baseDir + "gis/geo/motorway.shp")
motG = motG[motG['geometry'].apply(lambda x: x.is_valid).values]
motG = motG.geometry.unary_union
line for i,poii in poi.iterrows():
= geometry.Point(poi.loc[i][['x','y']])
p = line.interpolate(line.project(p))
neip #snap(coords, line, tolerance)
"x_mot"] = neip.x
poi.loc[i,"y_mot"] = neip.y poi.loc[i,
Which polygon contains a point
import shapely.speedups
shapely.speedups.enable()= gpd.GeoDataFrame.from_file(baseDir + "gis/geo/pop_dens_2km.shp")
densG = densG['geometry'][0]
g = [sha.geometry.Point(x,y) for x,y in zip(poi['x'],poi['y'])]
p = gpd.GeoDataFrame(p,columns=["geometry"]) poiG
Dissolve a polygon into its edges
= gpd.read_file(baseDir + "gis/tank/tileList.geojson")
tileG 'sum'] = tileG.loc[:,'north_in'] + tileG.loc[:,'south_in'] + tileG.loc[:,'east_in'] + tileG.loc[:,'west_in']
tileG.loc[:,= tileG[['tile_id','sum','north_in','south_in','east_in','west_in','north_out','south_out','east_out','west_out']].groupby(['tile_id']).agg(sum)
dirg = dirg.reset_index()
dirg = tileG[['tile_id','col_id','row_id','geometry']].groupby(['tile_id']).head(1)
tileL = pd.merge(dirg,tileL,left_on="tile_id",right_on="tile_id",how="left")
dirg = gpd.GeoDataFrame(dirg)
dirg with open(baseDir + "gis/tank/junction_tile.geojson","w") as fo:
fo.write(dirg.to_json())
= gpd.GeoDataFrame(columns=["in","out","dir","geometry"])
dirl for i,a in dirg.iterrows():
= a['geometry'].boundary
l = LineString([(l.xy[0][0],l.xy[1][0]),(l.xy[0][1],l.xy[1][1])])
ll str(a['tile_id']) + 'a'] = [a['east_in'],a['east_out'],"e",ll]
dirl.loc[= LineString([(l.xy[0][1],l.xy[1][1]),(l.xy[0][2],l.xy[1][2])])
ll str(a['tile_id']) + 'b'] = [a['north_in'],a['north_out'],"n",ll]
dirl.loc[= LineString([(l.xy[0][2],l.xy[1][2]),(l.xy[0][3],l.xy[1][3])])
ll str(a['tile_id']) + 'c'] = [a['west_in'],a['west_out'],"w",ll]
dirl.loc[= LineString([(l.xy[0][3],l.xy[1][3]),(l.xy[0][4],l.xy[1][4])])
ll str(a['tile_id']) + 'd'] = [a['south_in'],a['south_out'],"s",ll]
dirl.loc[
= gpd.GeoDataFrame(dirl)
dirl with open(baseDir + "gis/tank/junction_edge.geojson","w") as fo:
fo.write(dirl.to_json())
from sklearn.cluster import SpectralClustering
from sklearn.cluster import KMeans
= np.matrix([[1.,.1,.6,.4],[.1,1.,.1,.2],[.6,.1,1.,.7],[.4,.2,.7,1.]])
mat print(SpectralClustering(2).fit_predict(mat))
= np.linalg.eigh(mat)
eigen_values, eigen_vectors print(KMeans(n_clusters=2, init='k-means++').fit_predict(eigen_vectors[:, 2:4]))
from sklearn.cluster import DBSCAN
=1).fit_predict(mat) DBSCAN(min_samples
= gpd.read_file(baseDir + "junction_area.geojson")
junct = gpd.read_file(baseDir + "count_dir.geojson")
dirc = [np.arctan(0.),np.arctan(np.pi/2.),np.arctan(np.pi),np.arctan(3.*np.pi/2.),np.arctan(2.*np.pi)]
dirA def getAng(dx,dy):
= int(np.arctan2(dy,dx)*2./np.pi + 0.5)
ang = ["east","north","west","south"]
cordD return cordD[ang], cordD[abs(2-ang)]
def getDir(dtx,dty):
= [("east","west"),("north","south"),("west","east"),("south","north")]
cordD = 1
ang if(dtx < 0):
= 0
ang elif(dtx > 0):
= 2
ang elif(dty < 0):
= 3
ang return cordD[ang]
= [("east","west"),("north","south"),("west","east"),("south","north")]
cordD = gpd.read_file(baseDir + "/motorway_exit_axes.geojson")
exits = pd.DataFrame(index=range(0,4*24))
fluxC 'exit'] = 0
exits.loc[:,'enter'] = 0
exits.loc[:,for i,ex in exits.iterrows():
= ex['geometry']
l = [a.contains(Point(l.xy[0][0],l.xy[1][0])) for a in dirc['geometry']]
inTile = [a.contains(Point(l.xy[0][1],l.xy[1][1])) for a in dirc['geometry']]
outTile = dirc.loc[inTile]
dircI = dirc.loc[outTile]
dircO # ang1, ang2 = getAng(l.xy[1][1] - l.xy[1][0],l.xy[0][1] - l.xy[0][0])
= dircI.iloc[0]['col_id'] - dircO.iloc[0]['col_id']
dtx = dircI.iloc[0]['row_id'] - dircO.iloc[0]['row_id']
dty = getDir(dtx,dty) ang1, ang2
= gpd.GeoDataFrame.from_file(baseDir + "gis/geo/pop_density.shp")
densG = densG['geometry'].apply(lambda x: x.centroid)
centL "hash"] = centL.apply(lambda x: geohash.encode(x.xy[0][0],x.xy[1][0],precision=5))
densG.loc[:,def clampF(x):
return pd.Series({"pop_dens":x['Einwohner'].sum()
"flat_dens":x['Wohnfl_Bew'].sum()
,"foreign":x['Auslaender'].sum()
,"women":x['Frauen_A'].sum()
,"young":x['unter18_A'].sum()
,"geometry":cascaded_union(x['geometry'])
,"household":x['HHGroesse_'].sum()
,"n":len(x['Flaeche'])
,
})= densG.groupby("hash").apply(clampF).reset_index()
densG 'geometry'] = densG['geometry'].apply(lambda f: f.convex_hull)
densG.loc[:,for i in ['pop_dens','flat_dens','foreign','women','young','household']:
= densG[i]/densG['n']
densG.loc[:,i] = gpd.GeoDataFrame(densG)
densG + "gis/geo/pop_dens_2km.shp") densG.to_file(baseDir
import os, sys, gzip, random, csv, json, datetime, re
import numpy as np
import pandas as pd
import scipy as sp
import matplotlib.pyplot as plt
import geopandas as gpd
from scipy.spatial import cKDTree
from scipy import inf
import shapely as sh
import pymongo
= "~/raw/" baseDir
We initiate the client
with open(baseDir + '/credenza/geomadi.json') as f:
= json.load(f)
cred
with open(baseDir + '/raw/metrics.json') as f:
= json.load(f)['metrics']
metr
= pymongo.MongoClient(cred['mongo']['address'],cred['mongo']['port'])
client = client["index_name"]["collection_name"] coll
Returns all points within a distance
= 200.
neiDist = []
nodeL for i,poii in poi.iterrows():
= poi.loc[i]
poii = [x for x in poii.ix[['x','y']]]
poi_coord = coll.find({'loc':{'$nearSphere':{'$geometry':{'type':"Point",'coordinates':poi_coord},'$minDistance':0,'$maxDistance':neiDist}}})
neiN = []
nodeId for neii in neiN:
'id_poi':poii['id_poi'],'src':neii['src'],'trg':neii['trg'],"maxspeed":neii['maxspeed'],'street':neii['highway']
nodeL.append({"x_poi":poii['x'],"y_poi":poii['y']
, })
Take all locations inside polygons
= gpd.GeoDataFrame.from_file(baseDir + "gis/geo/motorway_area.shp")
motG = []
cellL for g in np.array(motG['geometry'][0]):
= g.exterior.coords.xy
c = [[x,y] for x,y in zip(c[0],c[1])]
c1 = coll.find({'geom':{'$geoIntersects':{'$geometry':{'type':"Polygon",'coordinates':[c1]}}}})
neiN = neiN[0]
neii for neii in neiN:
"cilac":str(neii['cell_ci']) + '-' + str(neii['cell_lac'])})
cellL.append({= pd.DataFrame(cellL) cellL
Filtering by list
coll = client["tdg_infra"]["infrastructure"]
poi = pd.read_csv(baseDir + "raw/tr_cilac_sel1.csv")
colL = list(poi.columns)
colL[0] = 'domcell'
poi.columns = colL
poi.loc[:,'ci'] = [re.sub("-.*","",x) for x in poi['domcell']]
poi.loc[:,'lac'] = [re.sub(".*-","",x) for x in poi['domcell']]
queryL = []
for i,p in poi.iterrows():
queryL.append({"cell_ci":p['ci']})
queryL.append({"cell_lac":p['lac']})
= coll.find({'loc':{'$geoWithin':{'$box':[ [BBox[0],BBox[2]],[BBox[1],BBox[3]] ]}}}) neiN
from neo4j.v1 import GraphDatabase, basic_auth
= GraphDatabase.driver("bolt://localhost:7687", auth=basic_auth("neo4j", "neo4j"))
driver = driver.session()
session
"CREATE (a:Person {name: {name}, title: {title}})",
session.run("name": "Arthur", "title": "King"})
{
= session.run("MATCH (a:Person) WHERE a.name = {name} "
result "RETURN a.name AS name, a.title AS title",
"name": "Arthur"})
{for record in result:
print("%s %s" % (record["title"], record["name"]))
session.close()
from py2neo import Graph, Path
= Graph()
graph
= graph.cypher.begin()
tx for name in ["Alice", "Bob", "Carol"]:
"CREATE (person:Person {name:{name}}) RETURN person", name=name)
tx.append(= [result.one for result in tx.commit()]
alice, bob, carol
= Path(alice, "KNOWS", bob, "KNOWS", carol)
friends
graph.create(friends)
from neomodel import StructuredNode, StringProperty, RelationshipTo, RelationshipFrom, config
= 'bolt://neo4j:test@localhost:7687'
config.DATABASE_URL
class Book(StructuredNode):
= StringProperty(unique_index=True)
title = RelationshipTo('Author', 'AUTHOR')
author
class Author(StructuredNode):
= StringProperty(unique_index=True)
name = RelationshipFrom('Book', 'AUTHOR')
books
= Book(title='Harry potter and the..').save()
harry_potter = Author(name='J. K. Rowling').save()
rowling connect(rowling) harry_potter.author.
import osmnx as ox
import networkx as nx
Graph:
= ox.load_graphml(filename="germany_split_motorway_motorwaylink.graphml")
graph1 = ox.load_graphml( filename="germany_split_trunk_trunk_link.graphml")
graph2 = ox.load_graphml( filename="germany_split_primlink.graphml")
graph3 = ox.load_graphml( filename="germany_split_prim.graphml")
graph4 = ox.load_graphml( filename="germany_split_seclink.graphml") graph5
Compose:
= [graph1, graph2, graph3, graph4, graph5]
c_graphs = nx.compose_all(c_graphs) composed_G
Simplify:
= ox.simplify_graph(composed_G)
simp_G = max(nx.strongly_connected_component_subgraphs(simp_G), key=len)
connected_G = ox.project_graph(connected_G)
graph_proj ="allGermany_allstreetsUntilSec_proj.graphml") ox.save_graphml(graph_proj, filename
import networkx as nx
=nx.Graph()
G1)
G.add_node(2,3])
G.add_nodes_from([=nx.path_graph(10)
H
G.add_nodes_from(H)
G.add_node(H)1,2)
G.add_edge(=(2,3)
e*e)
G.add_edge(1,2),(1,3)])
G.add_edges_from([(
G.add_edges_from(H.edges())
G.remove_node(H)
G.clear()1,2),(1,3)])
G.add_edges_from([(1)
G.add_node(1,2)
G.add_edge("spam")
G.add_node("spam")
G.add_nodes_from(/f/f_nodes()
G.number_o../f/f_edges()
G.number_o..
G.nodes()
G.edges()1)
G.neighbors("spam")
G.remove_nodes_from(
G.nodes()1,3)
G.remove_edge(=nx.DiGraph(G)
H
H.edges()=[(0,1),(1,2),(2,3)]
edgelist=nx.Graph(edgelist)
H1,3)
G.add_edge(1][3]['color']='blue'
G[=nx.Graph()
FG1,2,0.125),(1,3,0.75),(2,4,1.2),(3,4,0.375)])
FG.add_weighted_edges_from([(for n,nbrs in FG.adjacency_iter():
for nbr,eattr in nbrs.items():
=eattr['weight']
dataif data<0.5: print('(%d, %d, %.3f)' % (n,nbr,data))
for (u,v,d) in FG.edges(data='weight'):
if d<0.5: print('(%d, %d, %.3f)'%(n,nbr,d))
= nx.Graph(day="Friday")
G
G.graph'day']='Monday'
G.graph[
G.graphimport matplotlib.pyplot as plt
nx.draw(G)
nx.draw_random(G)
nx.draw_circular(G)
nx.draw_spectral(G) plt.show()