Python networkx.read_shp() Examples
The following are 16
code examples of networkx.read_shp().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
networkx
, or try the search function
.
Example #1
Source File: mapmatcher.py From mapmatching with MIT License | 7 votes |
def getNetworkGraph(segments,segmentlengths): """ Builds a networkx graph from the network file, inluding segment length taken from arcpy. It selects the largest connected component of the network (to prevent errors from routing between unconnected parts) """ #generate the full network path for GDAL to be able to read the file path =str(os.path.join(arcpy.env.workspace,segments)) print path if arcpy.Exists(path): g = nx.read_shp(path) #This selects the largest connected component of the graph sg = list(nx.connected_component_subgraphs(g.to_undirected()))[0] print "graph size (excluding unconnected parts): "+str(len(g)) # Get the length for each road segment and append it as an attribute to the edges in the graph. for n0, n1 in sg.edges(): oid = sg[n0][n1]["OBJECTID"] sg[n0][n1]['length'] = segmentlengths[oid] return sg else: print "network file not found on path: "+path
Example #2
Source File: mapmatcher.py From mapmatching with MIT License | 6 votes |
def getNetworkGraph(segments,segmentlengths): """ Builds a networkx graph from the network file, inluding segment length taken from arcpy. It selects the largest connected component of the network (to prevent errors from routing between unconnected parts) """ #generate the full network path for GDAL to be able to read the file path =str(os.path.join(arcpy.env.workspace,segments)) print path if arcpy.Exists(path): g = nx.read_shp(path) #This selects the largest connected component of the graph sg = list(nx.connected_component_subgraphs(g.to_undirected()))[0] print "graph size (excluding unconnected parts): "+str(len(g)) # Get the length for each road segment and append it as an attribute to the edges in the graph. for n0, n1 in sg.edges(): oid = sg[n0][n1]["OBJECTID"] sg[n0][n1]['length'] = segmentlengths[oid] return sg else: print "network file not found on path: "+path
Example #3
Source File: test_shp.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def testload(self): def compare_graph_paths_names(g, paths, names): expected = nx.DiGraph() for p in paths: expected.add_path(p) assert_equal(sorted(expected.node), sorted(g.node)) assert_equal(sorted(expected.edges()), sorted(g.edges())) g_names = [g.get_edge_data(s, e)['Name'] for s, e in g.edges()] assert_equal(names, sorted(g_names)) # simplified G = nx.read_shp(self.shppath) compare_graph_paths_names(G, self.simplified_paths, \ self.simplified_names) # unsimplified G = nx.read_shp(self.shppath, simplify=False) compare_graph_paths_names(G, self.paths, self.names)
Example #4
Source File: test_shp.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def test_attributeexport(self): def testattributes(lyr, graph): feature = lyr.GetNextFeature() while feature: coords = [] ref = feature.GetGeometryRef() last = ref.GetPointCount() - 1 edge_nodes = (ref.GetPoint_2D(0), ref.GetPoint_2D(last)) name = feature.GetFieldAsString('Name') assert_equal(graph.get_edge_data(*edge_nodes)['Name'], name) feature = lyr.GetNextFeature() tpath = os.path.join(tempfile.gettempdir(), 'shpdir') G = nx.read_shp(self.shppath) nx.write_shp(G, tpath) shpdir = ogr.Open(tpath) edges = shpdir.GetLayerByName("edges") testattributes(edges, G)
Example #5
Source File: test_shp.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def testload(self): def compare_graph_paths_names(g, paths, names): expected = nx.DiGraph() for p in paths: nx.add_path(expected, p) assert_equal(sorted(expected.nodes), sorted(g.nodes)) assert_equal(sorted(expected.edges()), sorted(g.edges())) g_names = [g.get_edge_data(s, e)['Name'] for s, e in g.edges()] assert_equal(names, sorted(g_names)) # simplified G = nx.read_shp(self.shppath) compare_graph_paths_names(G, self.simplified_paths, self.simplified_names) # unsimplified G = nx.read_shp(self.shppath, simplify=False) compare_graph_paths_names(G, self.paths, self.names) # multiline unsimplified G = nx.read_shp(self.multi_shppath, simplify=False) compare_graph_paths_names(G, self.paths, self.multi_names)
Example #6
Source File: test_shp.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_attributeexport(self): def testattributes(lyr, graph): feature = lyr.GetNextFeature() while feature: coords = [] ref = feature.GetGeometryRef() last = ref.GetPointCount() - 1 edge_nodes = (ref.GetPoint_2D(0), ref.GetPoint_2D(last)) name = feature.GetFieldAsString('Name') assert_equal(graph.get_edge_data(*edge_nodes)['Name'], name) feature = lyr.GetNextFeature() tpath = os.path.join(tempfile.gettempdir(), 'shpdir') G = nx.read_shp(self.shppath) nx.write_shp(G, tpath) shpdir = ogr.Open(tpath) edges = shpdir.GetLayerByName("edges") testattributes(edges, G) # Test export of node attributes in nx.write_shp (#2778)
Example #7
Source File: test_shp.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_nodeattributeexport(self): tpath = os.path.join(tempfile.gettempdir(), 'shpdir') G = nx.DiGraph() A = (0, 0) B = (1, 1) C = (2, 2) G.add_edge(A, B) G.add_edge(A, C) label = 'node_label' for n, d in G.nodes(data=True): d['label'] = label nx.write_shp(G, tpath) H = nx.read_shp(tpath) for n, d in H.nodes(data=True): assert_equal(d['label'], label)
Example #8
Source File: test_shp.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_missing_attributes(self): G = nx.DiGraph() A = (0, 0) B = (1, 1) C = (2, 2) G.add_edge(A, B, foo=100) G.add_edge(A, C) nx.write_shp(G, self.path) H = nx.read_shp(self.path) for u, v, d in H.edges(data=True): if u == A and v == B: assert_equal(d['foo'], 100) if u == A and v == C: assert_equal(d['foo'], None)
Example #9
Source File: test_shp.py From aws-kube-codesuite with Apache License 2.0 | 6 votes |
def testload(self): def compare_graph_paths_names(g, paths, names): expected = nx.DiGraph() for p in paths: nx.add_path(expected, p) assert_equal(sorted(expected.nodes), sorted(g.nodes)) assert_equal(sorted(expected.edges()), sorted(g.edges())) g_names = [g.get_edge_data(s, e)['Name'] for s, e in g.edges()] assert_equal(names, sorted(g_names)) # simplified G = nx.read_shp(self.shppath) compare_graph_paths_names(G, self.simplified_paths, \ self.simplified_names) # unsimplified G = nx.read_shp(self.shppath, simplify=False) compare_graph_paths_names(G, self.paths, self.names) # multiline unsimplified G = nx.read_shp(self.multi_shppath, simplify=False) compare_graph_paths_names(G, self.paths, self.multi_names)
Example #10
Source File: test_shp.py From aws-kube-codesuite with Apache License 2.0 | 6 votes |
def test_attributeexport(self): def testattributes(lyr, graph): feature = lyr.GetNextFeature() while feature: coords = [] ref = feature.GetGeometryRef() last = ref.GetPointCount() - 1 edge_nodes = (ref.GetPoint_2D(0), ref.GetPoint_2D(last)) name = feature.GetFieldAsString('Name') assert_equal(graph.get_edge_data(*edge_nodes)['Name'], name) feature = lyr.GetNextFeature() tpath = os.path.join(tempfile.gettempdir(), 'shpdir') G = nx.read_shp(self.shppath) nx.write_shp(G, tpath) shpdir = ogr.Open(tpath) edges = shpdir.GetLayerByName("edges") testattributes(edges, G)
Example #11
Source File: test_shp.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_read_shp_nofile(): try: from osgeo import ogr except ImportError: raise SkipTest('ogr not available.') G = nx.read_shp("hopefully_this_file_will_not_be_available")
Example #12
Source File: minimum_spanning_tree.py From CityEnergyAnalyst with MIT License | 4 votes |
def calc_minimum_spanning_tree(input_network_shp, output_network_folder, building_nodes_shp, output_edges, output_nodes, weight_field, type_mat_default, pipe_diameter_default): # read shapefile into networkx format into a directed graph graph = nx.read_shp(input_network_shp) # transform to an undirected graph iterator_edges = graph.edges(data=True) G = nx.Graph() # plant = (11660.95859999981, 37003.7689999986) for (x, y, data) in iterator_edges: G.add_edge(x, y, weight=data[weight_field]) # calculate minimum spanning tree of undirected graph mst_non_directed = nx.minimum_spanning_edges(G, data=False) # transform back directed graph and save: mst_directed = nx.DiGraph() mst_directed.add_edges_from(mst_non_directed) nx.write_shp(mst_directed, output_network_folder) # populate fields Type_mat, Name, Pipe_Dn mst_edges = gdf.from_file(output_edges) mst_edges['Type_mat'] = type_mat_default mst_edges['Pipe_DN'] = pipe_diameter_default mst_edges['Name'] = ["PIPE" + str(x) for x in mst_edges['FID']] mst_edges.drop("FID", axis=1, inplace=True) mst_edges.crs = gdf.from_file(input_network_shp).crs # to add coordinate system mst_edges.to_file(output_edges, driver='ESRI Shapefile') # populate fields Building, Type, Name mst_nodes = gdf.from_file(output_nodes) buiding_nodes_df = gdf.from_file(building_nodes_shp) mst_nodes.crs = buiding_nodes_df.crs # to add same coordinate system buiding_nodes_df['coordinates'] = buiding_nodes_df['geometry'].apply( lambda x: (round(x.coords[0][0], 4), round(x.coords[0][1], 4))) mst_nodes['coordinates'] = mst_nodes['geometry'].apply( lambda x: (round(x.coords[0][0], 4), round(x.coords[0][1], 4))) names_temporary = ["NODE" + str(x) for x in mst_nodes['FID']] new_mst_nodes = mst_nodes.merge(buiding_nodes_df, suffixes=['', '_y'], on="coordinates", how='outer') new_mst_nodes.fillna(value="NONE", inplace=True) new_mst_nodes['Building'] = new_mst_nodes['Name'] new_mst_nodes['Name'] = names_temporary new_mst_nodes['Type'] = new_mst_nodes['Building'].apply(lambda x: 'CONSUMER' if x != "NONE" else x) new_mst_nodes.drop(["FID", "coordinates", 'floors_bg', 'floors_ag', 'height_bg', 'height_ag', 'geometry_y'], axis=1, inplace=True) new_mst_nodes.to_file(output_nodes, driver='ESRI Shapefile')
Example #13
Source File: minimum_spanning_tree.py From CityEnergyAnalyst with MIT License | 4 votes |
def calc_minimum_spanning_tree(input_network_shp, output_network_folder, building_nodes_shp, output_edges, output_nodes, weight_field, type_mat_default, pipe_diameter_default): # read shapefile into networkx format into a directed graph graph = nx.read_shp(input_network_shp) # transform to an undirected graph iterator_edges = graph.edges(data=True) G = nx.Graph() # plant = (11660.95859999981, 37003.7689999986) for (x, y, data) in iterator_edges: G.add_edge(x, y, weight=data[weight_field]) # calculate minimum spanning tree of undirected graph mst_non_directed = nx.minimum_spanning_edges(G, data=False) # transform back directed graph and save: mst_directed = nx.DiGraph() mst_directed.add_edges_from(mst_non_directed) nx.write_shp(mst_directed, output_network_folder) # populate fields Type_mat, Name, Pipe_Dn mst_edges = gdf.from_file(output_edges) mst_edges['Type_mat'] = type_mat_default mst_edges['Pipe_DN'] = pipe_diameter_default mst_edges['Name'] = ["PIPE" + str(x) for x in mst_edges['FID']] mst_edges.drop("FID", axis=1, inplace=True) mst_edges.crs = gdf.from_file(input_network_shp).crs # to add coordinate system mst_edges.to_file(output_edges, driver='ESRI Shapefile') # populate fields Building, Type, Name mst_nodes = gdf.from_file(output_nodes) buiding_nodes_df = gdf.from_file(building_nodes_shp) mst_nodes.crs = buiding_nodes_df.crs # to add same coordinate system buiding_nodes_df['coordinates'] = buiding_nodes_df['geometry'].apply( lambda x: (round(x.coords[0][0], 4), round(x.coords[0][1], 4))) mst_nodes['coordinates'] = mst_nodes['geometry'].apply( lambda x: (round(x.coords[0][0], 4), round(x.coords[0][1], 4))) names_temporary = ["NODE" + str(x) for x in mst_nodes['FID']] new_mst_nodes = mst_nodes.merge(buiding_nodes_df, suffixes=['', '_y'], on="coordinates", how='outer') new_mst_nodes.fillna(value="NONE", inplace=True) new_mst_nodes['Building'] = new_mst_nodes['Name'] new_mst_nodes['Name'] = names_temporary new_mst_nodes['Type'] = new_mst_nodes['Building'].apply(lambda x: 'CONSUMER' if x != "NONE" else x) new_mst_nodes.drop(["FID", "coordinates", 'floors_bg', 'floors_ag', 'height_bg', 'height_ag', 'geometry_y'], axis=1, inplace=True) new_mst_nodes.to_file(output_nodes, driver='ESRI Shapefile')
Example #14
Source File: test_shp.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 4 votes |
def test_geometryexport(self): expectedpoints_simple = ( "POINT (1 1)", "POINT (2 2)", "POINT (3 3)", "POINT (0.9 0.9)", "POINT (4 2)" ) expectedlines_simple = ( "LINESTRING (1 1,2 2)", "LINESTRING (2 2,3 3)", "LINESTRING (0.9 0.9,4.0 0.9,4 2)" ) expectedpoints = ( "POINT (1 1)", "POINT (2 2)", "POINT (3 3)", "POINT (0.9 0.9)", "POINT (4.0 0.9)", "POINT (4 2)" ) expectedlines = ( "LINESTRING (1 1,2 2)", "LINESTRING (2 2,3 3)", "LINESTRING (0.9 0.9,4.0 0.9)", "LINESTRING (4.0 0.9,4 2)" ) tpath = os.path.join(tempfile.gettempdir(), 'shpdir') G = nx.read_shp(self.shppath) nx.write_shp(G, tpath) shpdir = ogr.Open(tpath) self.checkgeom(shpdir.GetLayerByName("nodes"), expectedpoints_simple) self.checkgeom(shpdir.GetLayerByName("edges"), expectedlines_simple) # Test unsimplified # Nodes should have additional point, # edges should be 'flattened' G = nx.read_shp(self.shppath, simplify=False) nx.write_shp(G, tpath) shpdir = ogr.Open(tpath) self.checkgeom(shpdir.GetLayerByName("nodes"), expectedpoints) self.checkgeom(shpdir.GetLayerByName("edges"), expectedlines)
Example #15
Source File: test_shp.py From Carnets with BSD 3-Clause "New" or "Revised" License | 4 votes |
def test_geometryexport(self): expectedpoints_simple = ( "POINT (1 1)", "POINT (2 2)", "POINT (3 3)", "POINT (0.9 0.9)", "POINT (4 2)" ) expectedlines_simple = ( "LINESTRING (1 1,2 2)", "LINESTRING (2 2,3 3)", "LINESTRING (0.9 0.9,4.0 0.9,4 2)" ) expectedpoints = ( "POINT (1 1)", "POINT (2 2)", "POINT (3 3)", "POINT (0.9 0.9)", "POINT (4.0 0.9)", "POINT (4 2)" ) expectedlines = ( "LINESTRING (1 1,2 2)", "LINESTRING (2 2,3 3)", "LINESTRING (0.9 0.9,4.0 0.9)", "LINESTRING (4.0 0.9,4 2)" ) tpath = os.path.join(tempfile.gettempdir(), 'shpdir') G = nx.read_shp(self.shppath) nx.write_shp(G, tpath) shpdir = ogr.Open(tpath) self.checkgeom(shpdir.GetLayerByName("nodes"), expectedpoints_simple) self.checkgeom(shpdir.GetLayerByName("edges"), expectedlines_simple) # Test unsimplified # Nodes should have additional point, # edges should be 'flattened' G = nx.read_shp(self.shppath, simplify=False) nx.write_shp(G, tpath) shpdir = ogr.Open(tpath) self.checkgeom(shpdir.GetLayerByName("nodes"), expectedpoints) self.checkgeom(shpdir.GetLayerByName("edges"), expectedlines)
Example #16
Source File: test_shp.py From aws-kube-codesuite with Apache License 2.0 | 4 votes |
def test_geometryexport(self): expectedpoints_simple = ( "POINT (1 1)", "POINT (2 2)", "POINT (3 3)", "POINT (0.9 0.9)", "POINT (4 2)" ) expectedlines_simple = ( "LINESTRING (1 1,2 2)", "LINESTRING (2 2,3 3)", "LINESTRING (0.9 0.9,4.0 0.9,4 2)" ) expectedpoints = ( "POINT (1 1)", "POINT (2 2)", "POINT (3 3)", "POINT (0.9 0.9)", "POINT (4.0 0.9)", "POINT (4 2)" ) expectedlines = ( "LINESTRING (1 1,2 2)", "LINESTRING (2 2,3 3)", "LINESTRING (0.9 0.9,4.0 0.9)", "LINESTRING (4.0 0.9,4 2)" ) tpath = os.path.join(tempfile.gettempdir(), 'shpdir') G = nx.read_shp(self.shppath) nx.write_shp(G, tpath) shpdir = ogr.Open(tpath) self.checkgeom(shpdir.GetLayerByName("nodes"), expectedpoints_simple) self.checkgeom(shpdir.GetLayerByName("edges"), expectedlines_simple) # Test unsimplified # Nodes should have additional point, # edges should be 'flattened' G = nx.read_shp(self.shppath, simplify=False) nx.write_shp(G, tpath) shpdir = ogr.Open(tpath) self.checkgeom(shpdir.GetLayerByName("nodes"), expectedpoints) self.checkgeom(shpdir.GetLayerByName("edges"), expectedlines)