├── src ├── __init__.py ├── networkx │ ├── external │ │ └── __init__.py │ ├── tests │ │ ├── __init__.py │ │ ├── test_exceptions.py │ │ ├── test.py │ │ └── test_convert_pandas.py │ ├── testing │ │ ├── __init__.py │ │ └── utils.py │ ├── algorithms │ │ ├── community │ │ │ ├── __init__.py │ │ │ ├── tests │ │ │ │ └── test_kclique.py │ │ │ └── kclique.py │ │ ├── tree │ │ │ └── __init__.py │ │ ├── chordal │ │ │ ├── __init__.py │ │ │ └── tests │ │ │ │ └── test_chordal.py │ │ ├── coloring │ │ │ └── __init__.py │ │ ├── traversal │ │ │ ├── __init__.py │ │ │ └── tests │ │ │ │ ├── test_bfs.py │ │ │ │ └── test_dfs.py │ │ ├── flow │ │ │ ├── tests │ │ │ │ ├── gl1.gpickle.bz2 │ │ │ │ ├── gw1.gpickle.bz2 │ │ │ │ ├── wlm3.gpickle.bz2 │ │ │ │ └── netgen-2.gpickle.bz2 │ │ │ └── __init__.py │ │ ├── isomorphism │ │ │ ├── tests │ │ │ │ ├── si2_b06_m200.B99 │ │ │ │ ├── si2_b06_m200.A99 │ │ │ │ ├── test_isomorphism.py │ │ │ │ ├── iso_r01_s80.B99 │ │ │ │ └── iso_r01_s80.A99 │ │ │ └── __init__.py │ │ ├── link_analysis │ │ │ ├── __init__.py │ │ │ └── tests │ │ │ │ └── test_hits.py │ │ ├── operators │ │ │ ├── __init__.py │ │ │ ├── tests │ │ │ │ └── test_unary.py │ │ │ └── unary.py │ │ ├── approximation │ │ │ ├── tests │ │ │ │ ├── test_matching.py │ │ │ │ ├── test_independent_set.py │ │ │ │ ├── test_ramsey.py │ │ │ │ ├── test_approx_clust_coeff.py │ │ │ │ ├── test_vertex_cover.py │ │ │ │ ├── test_clique.py │ │ │ │ └── test_dominating_set.py │ │ │ ├── __init__.py │ │ │ ├── ramsey.py │ │ │ ├── matching.py │ │ │ ├── clustering_coefficient.py │ │ │ ├── independent_set.py │ │ │ └── vertex_cover.py │ │ ├── assortativity │ │ │ ├── __init__.py │ │ │ └── tests │ │ │ │ ├── base_test.py │ │ │ │ └── test_neighbor_degree.py │ │ ├── shortest_paths │ │ │ ├── __init__.py │ │ │ └── tests │ │ │ │ └── test_dense_numpy.py │ │ ├── components │ │ │ ├── __init__.py │ │ │ ├── semiconnected.py │ │ │ └── tests │ │ │ │ ├── test_semiconnected.py │ │ │ │ ├── test_attracting.py │ │ │ │ └── test_weakly_connected.py │ │ ├── centrality │ │ │ ├── __init__.py │ │ │ ├── tests │ │ │ │ ├── test_dispersion.py │ │ │ │ ├── test_current_flow_closeness.py │ │ │ │ └── test_closeness_centrality.py │ │ │ └── harmonic.py │ │ ├── connectivity │ │ │ └── __init__.py │ │ ├── tests │ │ │ ├── test_smetric.py │ │ │ ├── test_hybrid.py │ │ │ ├── test_triads.py │ │ │ ├── test_hierarchy.py │ │ │ ├── test_richclub.py │ │ │ ├── test_vitality.py │ │ │ ├── test_swap.py │ │ │ ├── test_dominating.py │ │ │ ├── test_distance_regular.py │ │ │ └── test_distance_measures.py │ │ ├── smetric.py │ │ ├── bipartite │ │ │ ├── tests │ │ │ │ ├── test_redundancy.py │ │ │ │ ├── test_spectral_bipartivity.py │ │ │ │ └── test_cluster.py │ │ │ └── spectral.py │ │ ├── hierarchy.py │ │ ├── isolate.py │ │ ├── dominating.py │ │ ├── mis.py │ │ ├── vitality.py │ │ └── boundary.py │ ├── drawing │ │ ├── __init__.py │ │ └── tests │ │ │ ├── test_pylab.py │ │ │ ├── test_pydot.py │ │ │ └── test_agraph.py │ ├── classes │ │ ├── __init__.py │ │ ├── tests │ │ │ ├── test_graph_historical.py │ │ │ └── test_ordered.py │ │ └── ordered.py │ ├── utils │ │ ├── __init__.py │ │ ├── tests │ │ │ ├── test_unionfind.py │ │ │ ├── test_contextmanager.py │ │ │ ├── test_random_sequence.py │ │ │ └── test_rcm.py │ │ ├── contextmanagers.py │ │ └── union_find.py │ ├── linalg │ │ ├── __init__.py │ │ └── tests │ │ │ ├── test_spectrum.py │ │ │ └── test_modularity.py │ ├── readwrite │ │ ├── __init__.py │ │ ├── json_graph │ │ │ ├── __init__.py │ │ │ └── tests │ │ │ │ ├── test_tree.py │ │ │ │ ├── test_adjacency.py │ │ │ │ └── test_node_link.py │ │ ├── tests │ │ │ ├── test_yaml.py │ │ │ ├── test_p2g.py │ │ │ ├── test_leda.py │ │ │ └── test_gpickle.py │ │ └── nx_yaml.py │ ├── version.py │ ├── generators │ │ ├── tests │ │ │ ├── test_intersection.py │ │ │ ├── test_random_clustered.py │ │ │ ├── test_geometric.py │ │ │ ├── test_stochastic.py │ │ │ ├── test_directed.py │ │ │ ├── test_ego.py │ │ │ ├── test_nonisomorphic_trees.py │ │ │ ├── test_atlas.py │ │ │ ├── test_line.py │ │ │ └── test_expanders.py │ │ ├── __init__.py │ │ ├── stochastic.py │ │ └── ego.py │ ├── exception.py │ └── __init__.py ├── ArgParser.py ├── VRPModel.py ├── vrpmain.py └── TspPainter.py ├── doc └── Problem_Formulation.pdf ├── resources ├── optimal_graph.png └── optimal_solution.png ├── data ├── eil7.vrp ├── att48.opt.tour ├── eil51.opt.tour ├── eil76.opt.tour ├── eil51.tsp ├── att48.tsp ├── eil101.opt.tour ├── eil76.tsp ├── eil51.vrp ├── eil51.demand ├── att48.vrp ├── eil101.tsp ├── eil51.graph └── eil76.graph ├── README.md └── .gitignore /src/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/networkx/external/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/networkx/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/networkx/testing/__init__.py: -------------------------------------------------------------------------------- 1 | from networkx.testing.utils import * 2 | -------------------------------------------------------------------------------- /src/networkx/algorithms/community/__init__.py: -------------------------------------------------------------------------------- 1 | from networkx.algorithms.community.kclique import * 2 | -------------------------------------------------------------------------------- /src/networkx/algorithms/tree/__init__.py: -------------------------------------------------------------------------------- 1 | from .recognition import * 2 | from .branchings import * 3 | -------------------------------------------------------------------------------- /src/networkx/algorithms/chordal/__init__.py: -------------------------------------------------------------------------------- 1 | from networkx.algorithms.chordal.chordal_alg import * 2 | 3 | 4 | -------------------------------------------------------------------------------- /doc/Problem_Formulation.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leon-li-inspire/Gurobi-VRP/HEAD/doc/Problem_Formulation.pdf -------------------------------------------------------------------------------- /resources/optimal_graph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leon-li-inspire/Gurobi-VRP/HEAD/resources/optimal_graph.png -------------------------------------------------------------------------------- /resources/optimal_solution.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leon-li-inspire/Gurobi-VRP/HEAD/resources/optimal_solution.png -------------------------------------------------------------------------------- /src/networkx/algorithms/coloring/__init__.py: -------------------------------------------------------------------------------- 1 | from networkx.algorithms.coloring.greedy_coloring import * 2 | __all__ = ['greedy_color'] 3 | -------------------------------------------------------------------------------- /src/networkx/algorithms/traversal/__init__.py: -------------------------------------------------------------------------------- 1 | from .depth_first_search import * 2 | from .breadth_first_search import * 3 | from .edgedfs import * 4 | -------------------------------------------------------------------------------- /src/networkx/algorithms/flow/tests/gl1.gpickle.bz2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leon-li-inspire/Gurobi-VRP/HEAD/src/networkx/algorithms/flow/tests/gl1.gpickle.bz2 -------------------------------------------------------------------------------- /src/networkx/algorithms/flow/tests/gw1.gpickle.bz2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leon-li-inspire/Gurobi-VRP/HEAD/src/networkx/algorithms/flow/tests/gw1.gpickle.bz2 -------------------------------------------------------------------------------- /src/networkx/algorithms/flow/tests/wlm3.gpickle.bz2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leon-li-inspire/Gurobi-VRP/HEAD/src/networkx/algorithms/flow/tests/wlm3.gpickle.bz2 -------------------------------------------------------------------------------- /src/networkx/algorithms/flow/tests/netgen-2.gpickle.bz2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leon-li-inspire/Gurobi-VRP/HEAD/src/networkx/algorithms/flow/tests/netgen-2.gpickle.bz2 -------------------------------------------------------------------------------- /src/networkx/algorithms/isomorphism/tests/si2_b06_m200.B99: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leon-li-inspire/Gurobi-VRP/HEAD/src/networkx/algorithms/isomorphism/tests/si2_b06_m200.B99 -------------------------------------------------------------------------------- /src/networkx/algorithms/link_analysis/__init__.py: -------------------------------------------------------------------------------- 1 | from networkx.algorithms.link_analysis.pagerank_alg import * 2 | from networkx.algorithms.link_analysis.hits_alg import * 3 | -------------------------------------------------------------------------------- /src/networkx/drawing/__init__.py: -------------------------------------------------------------------------------- 1 | # graph drawing and interface to graphviz 2 | 3 | from .layout import * 4 | from .nx_pylab import * 5 | from . import nx_agraph 6 | from . import nx_pydot 7 | -------------------------------------------------------------------------------- /src/networkx/algorithms/isomorphism/__init__.py: -------------------------------------------------------------------------------- 1 | from networkx.algorithms.isomorphism.isomorph import * 2 | from networkx.algorithms.isomorphism.vf2userfunc import * 3 | from networkx.algorithms.isomorphism.matchhelpers import * 4 | 5 | -------------------------------------------------------------------------------- /src/networkx/classes/__init__.py: -------------------------------------------------------------------------------- 1 | from .graph import Graph 2 | from .digraph import DiGraph 3 | from .multigraph import MultiGraph 4 | from .multidigraph import MultiDiGraph 5 | from .ordered import * 6 | 7 | from .function import * 8 | -------------------------------------------------------------------------------- /src/networkx/algorithms/operators/__init__.py: -------------------------------------------------------------------------------- 1 | from networkx.algorithms.operators.all import * 2 | from networkx.algorithms.operators.binary import * 3 | from networkx.algorithms.operators.product import * 4 | from networkx.algorithms.operators.unary import * 5 | -------------------------------------------------------------------------------- /src/networkx/algorithms/approximation/tests/test_matching.py: -------------------------------------------------------------------------------- 1 | from nose.tools import * 2 | import networkx as nx 3 | import networkx.algorithms.approximation as a 4 | 5 | def test_min_maximal_matching(): 6 | # smoke test 7 | G = nx.Graph() 8 | assert_equal(len(a.min_maximal_matching(G)),0) 9 | -------------------------------------------------------------------------------- /src/networkx/algorithms/approximation/tests/test_independent_set.py: -------------------------------------------------------------------------------- 1 | from nose.tools import * 2 | import networkx as nx 3 | import networkx.algorithms.approximation as a 4 | 5 | def test_independent_set(): 6 | # smoke test 7 | G = nx.Graph() 8 | assert_equal(len(a.maximum_independent_set(G)),0) 9 | -------------------------------------------------------------------------------- /src/networkx/algorithms/flow/__init__.py: -------------------------------------------------------------------------------- 1 | from .maxflow import * 2 | from .mincost import * 3 | from .edmondskarp import * 4 | from .preflowpush import * 5 | from .shortestaugmentingpath import * 6 | from .capacityscaling import * 7 | from .networksimplex import * 8 | from .utils import build_flow_dict, build_residual_network 9 | -------------------------------------------------------------------------------- /src/networkx/utils/__init__.py: -------------------------------------------------------------------------------- 1 | from networkx.utils.misc import * 2 | from networkx.utils.decorators import * 3 | from networkx.utils.random_sequence import * 4 | from networkx.utils.union_find import * 5 | from networkx.utils.rcm import * 6 | from networkx.utils.heaps import * 7 | from networkx.utils.contextmanagers import * 8 | -------------------------------------------------------------------------------- /src/networkx/algorithms/assortativity/__init__.py: -------------------------------------------------------------------------------- 1 | from networkx.algorithms.assortativity.connectivity import * 2 | from networkx.algorithms.assortativity.correlation import * 3 | from networkx.algorithms.assortativity.mixing import * 4 | from networkx.algorithms.assortativity.neighbor_degree import * 5 | from networkx.algorithms.assortativity.pairs import * 6 | -------------------------------------------------------------------------------- /src/networkx/algorithms/shortest_paths/__init__.py: -------------------------------------------------------------------------------- 1 | from networkx.algorithms.shortest_paths.generic import * 2 | from networkx.algorithms.shortest_paths.unweighted import * 3 | from networkx.algorithms.shortest_paths.weighted import * 4 | from networkx.algorithms.shortest_paths.astar import * 5 | from networkx.algorithms.shortest_paths.dense import * 6 | 7 | -------------------------------------------------------------------------------- /src/ArgParser.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | parser = argparse.ArgumentParser( 4 | description = "Parser TSP files and calculate the optimization solution using Ant Colony System" 5 | ) 6 | 7 | parser.add_argument ( 8 | "tsp_file" 9 | , nargs = "+" 10 | , metavar = "PATH" 11 | , help = "Path to directory or .tsp or .vrp file." 12 | ) -------------------------------------------------------------------------------- /src/networkx/algorithms/isomorphism/tests/si2_b06_m200.A99: -------------------------------------------------------------------------------- 1 | ( 2 |   3 |    4 |  5 |   6 |   !!!" $%$%#!#'&$& !" -------------------------------------------------------------------------------- /src/networkx/classes/tests/test_graph_historical.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Original NetworkX graph tests""" 3 | from nose.tools import * 4 | import networkx 5 | import networkx as nx 6 | 7 | from historical_tests import HistoricalTests 8 | 9 | class TestGraphHistorical(HistoricalTests): 10 | 11 | def setUp(self): 12 | HistoricalTests.setUp(self) 13 | self.G=nx.Graph 14 | 15 | -------------------------------------------------------------------------------- /src/networkx/algorithms/components/__init__.py: -------------------------------------------------------------------------------- 1 | from networkx.algorithms.components.connected import * 2 | from networkx.algorithms.components.strongly_connected import * 3 | from networkx.algorithms.components.weakly_connected import * 4 | from networkx.algorithms.components.attracting import * 5 | from networkx.algorithms.components.biconnected import * 6 | from networkx.algorithms.components.semiconnected import * 7 | -------------------------------------------------------------------------------- /src/networkx/classes/tests/test_ordered.py: -------------------------------------------------------------------------------- 1 | import networkx as nx 2 | 3 | class SmokeTestOrdered(object): 4 | # Just test instantiation. 5 | def test_graph(): 6 | G = nx.OrderedGraph() 7 | 8 | def test_digraph(): 9 | G = nx.OrderedDiGraph() 10 | 11 | def test_multigraph(): 12 | G = nx.OrderedMultiGraph() 13 | 14 | def test_multidigraph(): 15 | G = nx.OrderedMultiDiGraph() 16 | 17 | -------------------------------------------------------------------------------- /src/networkx/algorithms/centrality/__init__.py: -------------------------------------------------------------------------------- 1 | from .betweenness import * 2 | from .betweenness_subset import * 3 | from .closeness import * 4 | from .communicability_alg import * 5 | from .current_flow_closeness import * 6 | from .current_flow_betweenness import * 7 | from .current_flow_betweenness_subset import * 8 | from .degree_alg import * 9 | from .dispersion import * 10 | from .eigenvector import * 11 | from .harmonic import * 12 | from .katz import * 13 | from .load import * 14 | -------------------------------------------------------------------------------- /data/eil7.vrp: -------------------------------------------------------------------------------- 1 | NAME : eil7 2 | COMMENT : (Eilon et al.) 3 | TYPE : CVRP 4 | DIMENSION : 7 5 | EDGE_WEIGHT_TYPE : EXPLICIT 6 | EDGE_WEIGHT_FORMAT: LOWER_COL 7 | DISPLAY_DATA_TYPE: NO_DISPLAY 8 | CAPACITY : 3 9 | EDGE_WEIGHT_SECTION 10 | 10 20 25 25 20 10 12 20 25 30 11 | 20 10 11 22 30 2 11 25 10 20 12 | 12 13 | DEMAND_SECTION 14 | 1 0 15 | 2 1 16 | 3 1 17 | 4 1 18 | 5 1 19 | 6 1 20 | 7 1 21 | DEPOT_SECTION 22 | 1 23 | -1 24 | EOF 25 | -------------------------------------------------------------------------------- /src/networkx/utils/tests/test_unionfind.py: -------------------------------------------------------------------------------- 1 | from nose.tools import * 2 | 3 | import networkx as nx 4 | 5 | def test_unionfind(): 6 | # Fixed by: 2cddd5958689bdecdcd89b91ac9aaf6ce0e4f6b8 7 | # Previously (in 2.x), the UnionFind class could handle mixed types. 8 | # But in Python 3.x, this causes a TypeError such as: 9 | # TypeError: unorderable types: str() > int() 10 | # 11 | # Now we just make sure that no exception is raised. 12 | x = nx.utils.UnionFind() 13 | x.union(0, 'a') 14 | -------------------------------------------------------------------------------- /src/networkx/algorithms/connectivity/__init__.py: -------------------------------------------------------------------------------- 1 | """Connectivity and cut algorithms 2 | """ 3 | from .connectivity import * 4 | from .cuts import * 5 | from .kcomponents import * 6 | from .kcutsets import * 7 | from .stoerwagner import * 8 | from .utils import * 9 | 10 | __all__ = sum([connectivity.__all__, 11 | cuts.__all__, 12 | kcomponents.__all__, 13 | kcutsets.__all__, 14 | stoerwagner.__all__, 15 | utils.__all__, 16 | ], []) 17 | -------------------------------------------------------------------------------- /src/networkx/linalg/__init__.py: -------------------------------------------------------------------------------- 1 | from networkx.linalg.attrmatrix import * 2 | import networkx.linalg.attrmatrix 3 | from networkx.linalg.spectrum import * 4 | import networkx.linalg.spectrum 5 | from networkx.linalg.graphmatrix import * 6 | import networkx.linalg.graphmatrix 7 | from networkx.linalg.laplacianmatrix import * 8 | import networkx.linalg.laplacianmatrix 9 | from networkx.linalg.algebraicconnectivity import * 10 | from networkx.linalg.modularitymatrix import * 11 | import networkx.linalg.modularitymatrix 12 | -------------------------------------------------------------------------------- /data/att48.opt.tour: -------------------------------------------------------------------------------- 1 | NAME : att48.opt.tour 2 | COMMENT : Optimum solution for att48 3 | TYPE : TOUR 4 | DIMENSION : 48 5 | TOUR_SECTION 6 | 1 7 | 8 8 | 38 9 | 31 10 | 44 11 | 18 12 | 7 13 | 28 14 | 6 15 | 37 16 | 19 17 | 27 18 | 17 19 | 43 20 | 30 21 | 36 22 | 46 23 | 33 24 | 20 25 | 47 26 | 21 27 | 32 28 | 39 29 | 48 30 | 5 31 | 42 32 | 24 33 | 10 34 | 45 35 | 35 36 | 4 37 | 26 38 | 2 39 | 29 40 | 34 41 | 41 42 | 16 43 | 22 44 | 3 45 | 23 46 | 14 47 | 25 48 | 13 49 | 11 50 | 12 51 | 15 52 | 40 53 | 9 54 | -1 55 | EOF 56 | -------------------------------------------------------------------------------- /src/networkx/utils/tests/test_contextmanager.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from nose.tools import * 4 | 5 | import networkx as nx 6 | 7 | def test_reversed(): 8 | G = nx.DiGraph() 9 | G.add_edge('A', 'B') 10 | 11 | # no exception 12 | with nx.utils.reversed(G): 13 | pass 14 | assert_true('B' in G['A']) 15 | 16 | # exception 17 | try: 18 | with nx.utils.reversed(G): 19 | raise Exception 20 | except: 21 | assert_true('B' in G['A']) 22 | -------------------------------------------------------------------------------- /data/eil51.opt.tour: -------------------------------------------------------------------------------- 1 | NAME : eil51.opt.tour 2 | COMMENT : Optimal tour for eil51.tsp (426) 3 | TYPE : TOUR 4 | DIMENSION : 51 5 | TOUR_SECTION 6 | 1 7 | 22 8 | 8 9 | 26 10 | 31 11 | 28 12 | 3 13 | 36 14 | 35 15 | 20 16 | 2 17 | 29 18 | 21 19 | 16 20 | 50 21 | 34 22 | 30 23 | 9 24 | 49 25 | 10 26 | 39 27 | 33 28 | 45 29 | 15 30 | 44 31 | 42 32 | 40 33 | 19 34 | 41 35 | 13 36 | 25 37 | 14 38 | 24 39 | 43 40 | 7 41 | 23 42 | 48 43 | 6 44 | 27 45 | 51 46 | 46 47 | 12 48 | 47 49 | 18 50 | 4 51 | 17 52 | 37 53 | 5 54 | 38 55 | 11 56 | 32 57 | -1 58 | EOF 59 | -------------------------------------------------------------------------------- /src/networkx/algorithms/tests/test_smetric.py: -------------------------------------------------------------------------------- 1 | 2 | from nose.tools import assert_equal,raises 3 | 4 | import networkx as nx 5 | 6 | def test_smetric(): 7 | g = nx.Graph() 8 | g.add_edge(1,2) 9 | g.add_edge(2,3) 10 | g.add_edge(2,4) 11 | g.add_edge(1,4) 12 | sm = nx.s_metric(g,normalized=False) 13 | assert_equal(sm, 19.0) 14 | # smNorm = nx.s_metric(g,normalized=True) 15 | # assert_equal(smNorm, 0.95) 16 | 17 | @raises(nx.NetworkXError) 18 | def test_normalized(): 19 | sm = nx.s_metric(nx.Graph(),normalized=True) 20 | -------------------------------------------------------------------------------- /src/networkx/algorithms/approximation/__init__.py: -------------------------------------------------------------------------------- 1 | from networkx.algorithms.approximation.clustering_coefficient import * 2 | from networkx.algorithms.approximation.clique import * 3 | from networkx.algorithms.approximation.connectivity import * 4 | from networkx.algorithms.approximation.dominating_set import * 5 | from networkx.algorithms.approximation.kcomponents import * 6 | from networkx.algorithms.approximation.independent_set import * 7 | from networkx.algorithms.approximation.matching import * 8 | from networkx.algorithms.approximation.ramsey import * 9 | from networkx.algorithms.approximation.vertex_cover import * 10 | -------------------------------------------------------------------------------- /src/networkx/readwrite/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | A package for reading and writing graphs in various formats. 3 | 4 | """ 5 | from networkx.readwrite.adjlist import * 6 | from networkx.readwrite.multiline_adjlist import * 7 | from networkx.readwrite.edgelist import * 8 | from networkx.readwrite.gpickle import * 9 | from networkx.readwrite.pajek import * 10 | from networkx.readwrite.leda import * 11 | from networkx.readwrite.sparse6 import * 12 | from networkx.readwrite.graph6 import * 13 | from networkx.readwrite.nx_yaml import * 14 | from networkx.readwrite.gml import * 15 | from networkx.readwrite.graphml import * 16 | from networkx.readwrite.gexf import * 17 | from networkx.readwrite.nx_shp import * 18 | -------------------------------------------------------------------------------- /src/networkx/utils/contextmanagers.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from contextlib import contextmanager 4 | 5 | __all__ = [ 6 | 'reversed', 7 | ] 8 | 9 | @contextmanager 10 | def reversed(G): 11 | """A context manager for temporarily reversing a directed graph in place. 12 | 13 | This is a no-op for undirected graphs. 14 | 15 | Parameters 16 | ---------- 17 | G : graph 18 | A NetworkX graph. 19 | """ 20 | directed = G.is_directed() 21 | if directed: 22 | G.reverse(copy=False) 23 | 24 | try: 25 | yield 26 | finally: 27 | if directed: 28 | # Reverse the reverse. 29 | G.reverse(copy=False) 30 | -------------------------------------------------------------------------------- /src/networkx/readwrite/json_graph/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | ********* 3 | JSON data 4 | ********* 5 | Generate and parse JSON serializable data for NetworkX graphs. 6 | 7 | These formats are suitable for use with the d3.js examples http://d3js.org/ 8 | 9 | The three formats that you can generate with NetworkX are: 10 | 11 | - node-link like in the d3.js example http://bl.ocks.org/mbostock/4062045 12 | - tree like in the d3.js example http://bl.ocks.org/mbostock/4063550 13 | - adjacency like in the d3.js example http://bost.ocks.org/mike/miserables/ 14 | """ 15 | from networkx.readwrite.json_graph.node_link import * 16 | from networkx.readwrite.json_graph.adjacency import * 17 | from networkx.readwrite.json_graph.tree import * 18 | -------------------------------------------------------------------------------- /src/networkx/version.py: -------------------------------------------------------------------------------- 1 | """ 2 | Version information for NetworkX, created during installation. 3 | 4 | Do not add this file to the repository. 5 | 6 | """ 7 | 8 | import datetime 9 | 10 | version = '1.11' 11 | date = 'Sat Jan 30 09:55:40 2016' 12 | 13 | # Was NetworkX built from a development version? If so, remember that the major 14 | # and minor versions reference the "target" (rather than "current") release. 15 | dev = False 16 | 17 | # Format: (name, major, min, revision) 18 | version_info = ('networkx', '1', '11', None) 19 | 20 | # Format: a 'datetime.datetime' instance 21 | date_info = datetime.datetime(2016, 1, 30, 9, 55, 40, 165755) 22 | 23 | # Format: (vcs, vcs_tuple) 24 | vcs_info = (None, (None, None)) 25 | 26 | -------------------------------------------------------------------------------- /data/eil76.opt.tour: -------------------------------------------------------------------------------- 1 | NAME : eil76.opt.tour 2 | COMMENT : Optimum tour for eil76.tsp (538) 3 | TYPE : TOUR 4 | DIMENSION : 76 5 | TOUR_SECTION 6 | 1 7 | 33 8 | 63 9 | 16 10 | 3 11 | 44 12 | 32 13 | 9 14 | 39 15 | 72 16 | 58 17 | 10 18 | 31 19 | 55 20 | 25 21 | 50 22 | 18 23 | 24 24 | 49 25 | 23 26 | 56 27 | 41 28 | 43 29 | 42 30 | 64 31 | 22 32 | 61 33 | 21 34 | 47 35 | 36 36 | 69 37 | 71 38 | 60 39 | 70 40 | 20 41 | 37 42 | 5 43 | 15 44 | 57 45 | 13 46 | 54 47 | 19 48 | 14 49 | 59 50 | 66 51 | 65 52 | 38 53 | 11 54 | 53 55 | 7 56 | 35 57 | 8 58 | 46 59 | 34 60 | 52 61 | 27 62 | 45 63 | 29 64 | 48 65 | 30 66 | 4 67 | 75 68 | 76 69 | 67 70 | 26 71 | 12 72 | 40 73 | 17 74 | 51 75 | 6 76 | 68 77 | 2 78 | 74 79 | 28 80 | 62 81 | 73 82 | -1 83 | EOF 84 | -------------------------------------------------------------------------------- /src/networkx/generators/tests/test_intersection.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | 5 | class TestIntersectionGraph(): 6 | def test_random_intersection_graph(self): 7 | G=nx.uniform_random_intersection_graph(10,5,0.5) 8 | assert_equal(len(G),10) 9 | 10 | def test_k_random_intersection_graph(self): 11 | G=nx.k_random_intersection_graph(10,5,2) 12 | assert_equal(len(G),10) 13 | 14 | def test_general_random_intersection_graph(self): 15 | G=nx.general_random_intersection_graph(10,5,[0.1,0.2,0.2,0.1,0.1]) 16 | assert_equal(len(G),10) 17 | assert_raises(ValueError, nx.general_random_intersection_graph,10,5, 18 | [0.1,0.2,0.2,0.1]) 19 | 20 | -------------------------------------------------------------------------------- /data/eil51.tsp: -------------------------------------------------------------------------------- 1 | NAME : eil51 2 | COMMENT : 51-city problem (Christofides/Eilon) 3 | TYPE : TSP 4 | DIMENSION : 51 5 | EDGE_WEIGHT_TYPE : EUC_2D 6 | NODE_COORD_SECTION 7 | 1 37 52 8 | 2 49 49 9 | 3 52 64 10 | 4 20 26 11 | 5 40 30 12 | 6 21 47 13 | 7 17 63 14 | 8 31 62 15 | 9 52 33 16 | 10 51 21 17 | 11 42 41 18 | 12 31 32 19 | 13 5 25 20 | 14 12 42 21 | 15 36 16 22 | 16 52 41 23 | 17 27 23 24 | 18 17 33 25 | 19 13 13 26 | 20 57 58 27 | 21 62 42 28 | 22 42 57 29 | 23 16 57 30 | 24 8 52 31 | 25 7 38 32 | 26 27 68 33 | 27 30 48 34 | 28 43 67 35 | 29 58 48 36 | 30 58 27 37 | 31 37 69 38 | 32 38 46 39 | 33 46 10 40 | 34 61 33 41 | 35 62 63 42 | 36 63 69 43 | 37 32 22 44 | 38 45 35 45 | 39 59 15 46 | 40 5 6 47 | 41 10 17 48 | 42 21 10 49 | 43 5 64 50 | 44 30 15 51 | 45 39 10 52 | 46 32 39 53 | 47 25 32 54 | 48 25 55 55 | 49 48 28 56 | 50 56 37 57 | 51 30 40 58 | EOF 59 | -------------------------------------------------------------------------------- /src/networkx/generators/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | A package for generating various graphs in networkx. 3 | 4 | """ 5 | from networkx.generators.classic import * 6 | from networkx.generators.degree_seq import * 7 | from networkx.generators.directed import * 8 | from networkx.generators.ego import * 9 | from networkx.generators.expanders import * 10 | from networkx.generators.geometric import * 11 | from networkx.generators.line import * 12 | from networkx.generators.random_graphs import * 13 | from networkx.generators.small import * 14 | from networkx.generators.stochastic import * 15 | from networkx.generators.social import * 16 | from networkx.generators.threshold import * 17 | from networkx.generators.intersection import * 18 | from networkx.generators.random_clustered import * 19 | from networkx.generators.community import * 20 | from networkx.generators.nonisomorphic_trees import * 21 | -------------------------------------------------------------------------------- /src/networkx/algorithms/tests/test_hybrid.py: -------------------------------------------------------------------------------- 1 | from nose.tools import * 2 | import networkx as nx 3 | 4 | def test_2d_grid_graph(): 5 | # FC article claims 2d grid graph of size n is (3,3)-connected 6 | # and (5,9)-connected, but I don't think it is (5,9)-connected 7 | G=nx.grid_2d_graph(8,8,periodic=True) 8 | assert_true(nx.is_kl_connected(G,3,3)) 9 | assert_false(nx.is_kl_connected(G,5,9)) 10 | (H,graphOK)=nx.kl_connected_subgraph(G,5,9,same_as_graph=True) 11 | assert_false(graphOK) 12 | 13 | def test_small_graph(): 14 | G=nx.Graph() 15 | G.add_edge(1,2) 16 | G.add_edge(1,3) 17 | G.add_edge(2,3) 18 | assert_true(nx.is_kl_connected(G,2,2)) 19 | H=nx.kl_connected_subgraph(G,2,2) 20 | (H,graphOK)=nx.kl_connected_subgraph(G,2,2, 21 | low_memory=True, 22 | same_as_graph=True) 23 | assert_true(graphOK) 24 | 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ACS-VRP-Gurobi 2 | This is a project using Gurobi to vehicle routing problem. 3 | 4 | ## How to run 5 | 6 | ### Construction requirment 7 | 8 | python 3.5, graphics.py Gurobi 6.5.2 9 | 10 | ### Input 11 | 12 | Command line `python src/vrpmain.py *.graph`, where `*.graph` is the graph file identify the necessary information for the problem, the example file could be found at `data/eil51.graph`. 13 | 14 | ###Graph file format 15 | 16 | The graph file format is based on the TSPLIB sample data file, and add some additional attributes like `DELIVER_SECTION` and `LOCKER_SECTION`. 17 | 18 | ## Output 19 | The output for each problem is the optimal delivery assignments for all the delivers, the capacity assignment for each locker and a optiaml solution graph. 20 | 21 | Below is the optimal solution for the sample data `data/eil51.graph`. 22 | 23 | ![sample](/resources/optimal_solution.png) 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /src/networkx/tests/test_exceptions.py: -------------------------------------------------------------------------------- 1 | from nose.tools import raises 2 | import networkx as nx 3 | 4 | # smoke tests for exceptions 5 | 6 | @raises(nx.NetworkXException) 7 | def test_raises_networkx_exception(): 8 | raise nx.NetworkXException 9 | 10 | @raises(nx.NetworkXError) 11 | def test_raises_networkx_error(): 12 | raise nx.NetworkXError 13 | 14 | @raises(nx.NetworkXPointlessConcept) 15 | def test_raises_networkx_pointless_concept(): 16 | raise nx.NetworkXPointlessConcept 17 | 18 | @raises(nx.NetworkXAlgorithmError) 19 | def test_raises_networkx_algorithm_error(): 20 | raise nx.NetworkXAlgorithmError 21 | 22 | @raises(nx.NetworkXUnfeasible) 23 | def test_raises_networkx_unfeasible(): 24 | raise nx.NetworkXUnfeasible 25 | 26 | @raises(nx.NetworkXNoPath) 27 | def test_raises_networkx_no_path(): 28 | raise nx.NetworkXNoPath 29 | 30 | @raises(nx.NetworkXUnbounded) 31 | def test_raises_networkx_unbounded(): 32 | raise nx.NetworkXUnbounded 33 | 34 | -------------------------------------------------------------------------------- /data/att48.tsp: -------------------------------------------------------------------------------- 1 | NAME : att48 2 | COMMENT : 48 capitals of the US (Padberg/Rinaldi) 3 | TYPE : TSP 4 | DIMENSION : 48 5 | EDGE_WEIGHT_TYPE : ATT 6 | NODE_COORD_SECTION 7 | 1 6734 1453 8 | 2 2233 10 9 | 3 5530 1424 10 | 4 401 841 11 | 5 3082 1644 12 | 6 7608 4458 13 | 7 7573 3716 14 | 8 7265 1268 15 | 9 6898 1885 16 | 10 1112 2049 17 | 11 5468 2606 18 | 12 5989 2873 19 | 13 4706 2674 20 | 14 4612 2035 21 | 15 6347 2683 22 | 16 6107 669 23 | 17 7611 5184 24 | 18 7462 3590 25 | 19 7732 4723 26 | 20 5900 3561 27 | 21 4483 3369 28 | 22 6101 1110 29 | 23 5199 2182 30 | 24 1633 2809 31 | 25 4307 2322 32 | 26 675 1006 33 | 27 7555 4819 34 | 28 7541 3981 35 | 29 3177 756 36 | 30 7352 4506 37 | 31 7545 2801 38 | 32 3245 3305 39 | 33 6426 3173 40 | 34 4608 1198 41 | 35 23 2216 42 | 36 7248 3779 43 | 37 7762 4595 44 | 38 7392 2244 45 | 39 3484 2829 46 | 40 6271 2135 47 | 41 4985 140 48 | 42 1916 1569 49 | 43 7280 4899 50 | 44 7509 3239 51 | 45 10 2676 52 | 46 6807 2993 53 | 47 5185 3258 54 | 48 3023 1942 55 | EOF 56 | -------------------------------------------------------------------------------- /src/networkx/algorithms/tests/test_triads.py: -------------------------------------------------------------------------------- 1 | # test_triads.py - unit tests for the triads module 2 | # 3 | # Copyright 2015 NetworkX developers. 4 | # Copyright 2009 Diederik van Liere . 5 | # 6 | # This file is part of NetworkX. 7 | # 8 | # NetworkX is distributed under a BSD license; see LICENSE.txt for more 9 | # information. 10 | """Unit tests for the :mod:`networkx.algorithms.triads` module.""" 11 | from nose.tools import assert_equal 12 | 13 | import networkx as nx 14 | 15 | 16 | def test_triadic_census(): 17 | """Tests the triadic census function.""" 18 | G = nx.DiGraph() 19 | G.add_edges_from(['01', '02', '03', '04', '05', '12', '16', '51', '56', 20 | '65']) 21 | expected = {'030T': 2, '120C': 1, '210': 0, '120U': 0, '012': 9, '102': 3, 22 | '021U': 0, '111U': 0, '003': 8, '030C': 0, '021D': 9, '201': 0, 23 | '111D': 1, '300': 0, '120D': 0, '021C': 2} 24 | actual = nx.triadic_census(G) 25 | assert_equal(expected, actual) 26 | -------------------------------------------------------------------------------- /data/eil101.opt.tour: -------------------------------------------------------------------------------- 1 | NAME : eil101.opt.tour 2 | COMMENT : Optimum tour for eil101.tsp (Length 629) 3 | TYPE : TOUR 4 | DIMENSION : 101 5 | TOUR_SECTION 6 | 1 7 | 69 8 | 27 9 | 101 10 | 53 11 | 28 12 | 26 13 | 12 14 | 80 15 | 68 16 | 29 17 | 24 18 | 54 19 | 55 20 | 25 21 | 4 22 | 39 23 | 67 24 | 23 25 | 56 26 | 75 27 | 41 28 | 22 29 | 74 30 | 72 31 | 73 32 | 21 33 | 40 34 | 58 35 | 13 36 | 94 37 | 95 38 | 97 39 | 87 40 | 2 41 | 57 42 | 15 43 | 43 44 | 42 45 | 14 46 | 44 47 | 38 48 | 86 49 | 16 50 | 61 51 | 85 52 | 91 53 | 100 54 | 98 55 | 37 56 | 92 57 | 59 58 | 93 59 | 99 60 | 96 61 | 6 62 | 89 63 | 52 64 | 18 65 | 83 66 | 60 67 | 5 68 | 84 69 | 17 70 | 45 71 | 8 72 | 46 73 | 47 74 | 36 75 | 49 76 | 64 77 | 63 78 | 90 79 | 32 80 | 10 81 | 62 82 | 11 83 | 19 84 | 48 85 | 82 86 | 7 87 | 88 88 | 31 89 | 70 90 | 30 91 | 20 92 | 66 93 | 71 94 | 65 95 | 35 96 | 34 97 | 78 98 | 81 99 | 9 100 | 51 101 | 33 102 | 79 103 | 3 104 | 77 105 | 76 106 | 50 107 | -1 108 | EOF 109 | -------------------------------------------------------------------------------- /src/networkx/algorithms/approximation/ramsey.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Ramsey numbers. 4 | """ 5 | # Copyright (C) 2011 by 6 | # Nicholas Mancuso 7 | # All rights reserved. 8 | # BSD license. 9 | import networkx as nx 10 | __all__ = ["ramsey_R2"] 11 | __author__ = """Nicholas Mancuso (nick.mancuso@gmail.com)""" 12 | 13 | def ramsey_R2(G): 14 | r"""Approximately computes the Ramsey number `R(2;s,t)` for graph. 15 | 16 | Parameters 17 | ---------- 18 | G : NetworkX graph 19 | Undirected graph 20 | 21 | Returns 22 | ------- 23 | max_pair : (set, set) tuple 24 | Maximum clique, Maximum independent set. 25 | """ 26 | if not G: 27 | return (set([]), set([])) 28 | 29 | node = next(G.nodes_iter()) 30 | nbrs = nx.all_neighbors(G, node) 31 | nnbrs = nx.non_neighbors(G, node) 32 | c_1, i_1 = ramsey_R2(G.subgraph(nbrs)) 33 | c_2, i_2 = ramsey_R2(G.subgraph(nnbrs)) 34 | 35 | c_1.add(node) 36 | i_2.add(node) 37 | return (max([c_1, c_2]), max([i_1, i_2])) 38 | -------------------------------------------------------------------------------- /src/networkx/generators/tests/test_random_clustered.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx 4 | 5 | class TestRandomClusteredGraph: 6 | 7 | def test_valid(self): 8 | node=[1,1,1,2,1,2,0,0] 9 | tri=[0,0,0,0,0,1,1,1] 10 | joint_degree_sequence=zip(node,tri) 11 | G = networkx.random_clustered_graph(joint_degree_sequence) 12 | assert_equal(G.number_of_nodes(),8) 13 | assert_equal(G.number_of_edges(),7) 14 | 15 | def test_valid2(self): 16 | G = networkx.random_clustered_graph(\ 17 | [(1,2),(2,1),(1,1),(1,1),(1,1),(2,0)]) 18 | assert_equal(G.number_of_nodes(),6) 19 | assert_equal(G.number_of_edges(),10) 20 | 21 | def test_invalid1(self): 22 | assert_raises((TypeError,networkx.NetworkXError), 23 | networkx.random_clustered_graph,[[1,1],[2,1],[0,1]]) 24 | 25 | def test_invalid2(self): 26 | assert_raises((TypeError,networkx.NetworkXError), 27 | networkx.random_clustered_graph,[[1,1],[1,2],[0,1]]) 28 | 29 | -------------------------------------------------------------------------------- /src/networkx/algorithms/tests/test_hierarchy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | 5 | def test_hierarchy_exception(): 6 | G = nx.cycle_graph(5) 7 | assert_raises(nx.NetworkXError,nx.flow_hierarchy,G) 8 | 9 | def test_hierarchy_cycle(): 10 | G = nx.cycle_graph(5,create_using=nx.DiGraph()) 11 | assert_equal(nx.flow_hierarchy(G),0.0) 12 | 13 | def test_hierarchy_tree(): 14 | G = nx.full_rary_tree(2,16,create_using=nx.DiGraph()) 15 | assert_equal(nx.flow_hierarchy(G),1.0) 16 | 17 | def test_hierarchy_1(): 18 | G = nx.DiGraph() 19 | G.add_edges_from([(0,1),(1,2),(2,3),(3,1),(3,4),(0,4)]) 20 | assert_equal(nx.flow_hierarchy(G),0.5) 21 | 22 | def test_hierarchy_weight(): 23 | G = nx.DiGraph() 24 | G.add_edges_from([(0,1,{'weight':.3}), 25 | (1,2,{'weight':.1}), 26 | (2,3,{'weight':.1}), 27 | (3,1,{'weight':.1}), 28 | (3,4,{'weight':.3}), 29 | (0,4,{'weight':.3})]) 30 | assert_equal(nx.flow_hierarchy(G,weight='weight'),.75) -------------------------------------------------------------------------------- /src/networkx/algorithms/tests/test_richclub.py: -------------------------------------------------------------------------------- 1 | import networkx as nx 2 | from nose.tools import * 3 | 4 | 5 | def test_richclub(): 6 | G = nx.Graph([(0,1),(0,2),(1,2),(1,3),(1,4),(4,5)]) 7 | rc = nx.richclub.rich_club_coefficient(G,normalized=False) 8 | assert_equal(rc,{0: 12.0/30,1:8.0/12}) 9 | 10 | # test single value 11 | rc0 = nx.richclub.rich_club_coefficient(G,normalized=False)[0] 12 | assert_equal(rc0,12.0/30.0) 13 | 14 | def test_richclub_normalized(): 15 | G = nx.Graph([(0,1),(0,2),(1,2),(1,3),(1,4),(4,5)]) 16 | rcNorm = nx.richclub.rich_club_coefficient(G,Q=2) 17 | assert_equal(rcNorm,{0:1.0,1:1.0}) 18 | 19 | 20 | def test_richclub2(): 21 | T = nx.balanced_tree(2,10) 22 | rc = nx.richclub.rich_club_coefficient(T,normalized=False) 23 | assert_equal(rc,{0:4092/(2047*2046.0), 24 | 1:(2044.0/(1023*1022)), 25 | 2:(2040.0/(1022*1021))}) 26 | 27 | #def test_richclub2_normalized(): 28 | # T = nx.balanced_tree(2,10) 29 | # rcNorm = nx.richclub.rich_club_coefficient(T,Q=2) 30 | # assert_true(rcNorm[0] ==1.0 and rcNorm[1] < 0.9 and rcNorm[2] < 0.9) 31 | -------------------------------------------------------------------------------- /src/networkx/algorithms/approximation/tests/test_ramsey.py: -------------------------------------------------------------------------------- 1 | from nose.tools import * 2 | import networkx as nx 3 | import networkx.algorithms.approximation as apxa 4 | 5 | def test_ramsey(): 6 | # this should only find the complete graph 7 | graph = nx.complete_graph(10) 8 | c, i = apxa.ramsey_R2(graph) 9 | cdens = nx.density(graph.subgraph(c)) 10 | eq_(cdens, 1.0, "clique not found by ramsey!") 11 | idens = nx.density(graph.subgraph(i)) 12 | eq_(idens, 0.0, "i-set not found by ramsey!") 13 | 14 | # this trival graph has no cliques. should just find i-sets 15 | graph = nx.trivial_graph(nx.Graph()) 16 | c, i = apxa.ramsey_R2(graph) 17 | cdens = nx.density(graph.subgraph(c)) 18 | eq_(cdens, 0.0, "clique not found by ramsey!") 19 | idens = nx.density(graph.subgraph(i)) 20 | eq_(idens, 0.0, "i-set not found by ramsey!") 21 | 22 | graph = nx.barbell_graph(10, 5, nx.Graph()) 23 | c, i = apxa.ramsey_R2(graph) 24 | cdens = nx.density(graph.subgraph(c)) 25 | eq_(cdens, 1.0, "clique not found by ramsey!") 26 | idens = nx.density(graph.subgraph(i)) 27 | eq_(idens, 0.0, "i-set not found by ramsey!") 28 | -------------------------------------------------------------------------------- /src/networkx/utils/tests/test_random_sequence.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | from networkx.utils import uniform_sequence,powerlaw_sequence,\ 4 | create_degree_sequence,zipf_rv,zipf_sequence,random_weighted_sample,\ 5 | weighted_choice 6 | import networkx.utils 7 | 8 | def test_degree_sequences(): 9 | seq=create_degree_sequence(10,uniform_sequence) 10 | assert_equal(len(seq), 10) 11 | seq=create_degree_sequence(10,powerlaw_sequence) 12 | assert_equal(len(seq), 10) 13 | 14 | def test_zipf_rv(): 15 | r = zipf_rv(2.3) 16 | assert_true(type(r),int) 17 | assert_raises(ValueError,zipf_rv,0.5) 18 | assert_raises(ValueError,zipf_rv,2,xmin=0) 19 | 20 | def test_zipf_sequence(): 21 | s = zipf_sequence(10) 22 | assert_equal(len(s),10) 23 | 24 | def test_random_weighted_sample(): 25 | mapping={'a':10,'b':20} 26 | s = random_weighted_sample(mapping,2) 27 | assert_equal(sorted(s),sorted(mapping.keys())) 28 | assert_raises(ValueError,random_weighted_sample,mapping,3) 29 | 30 | def test_random_weighted_choice(): 31 | mapping={'a':10,'b':0} 32 | c = weighted_choice(mapping) 33 | assert_equal(c,'a') 34 | -------------------------------------------------------------------------------- /data/eil76.tsp: -------------------------------------------------------------------------------- 1 | NAME : eil76 2 | COMMENT : 76-city problem (Christofides/Eilon) 3 | TYPE : TSP 4 | DIMENSION : 76 5 | EDGE_WEIGHT_TYPE : EUC_2D 6 | NODE_COORD_SECTION 7 | 1 22 22 8 | 2 36 26 9 | 3 21 45 10 | 4 45 35 11 | 5 55 20 12 | 6 33 34 13 | 7 50 50 14 | 8 55 45 15 | 9 26 59 16 | 10 40 66 17 | 11 55 65 18 | 12 35 51 19 | 13 62 35 20 | 14 62 57 21 | 15 62 24 22 | 16 21 36 23 | 17 33 44 24 | 18 9 56 25 | 19 62 48 26 | 20 66 14 27 | 21 44 13 28 | 22 26 13 29 | 23 11 28 30 | 24 7 43 31 | 25 17 64 32 | 26 41 46 33 | 27 55 34 34 | 28 35 16 35 | 29 52 26 36 | 30 43 26 37 | 31 31 76 38 | 32 22 53 39 | 33 26 29 40 | 34 50 40 41 | 35 55 50 42 | 36 54 10 43 | 37 60 15 44 | 38 47 66 45 | 39 30 60 46 | 40 30 50 47 | 41 12 17 48 | 42 15 14 49 | 43 16 19 50 | 44 21 48 51 | 45 50 30 52 | 46 51 42 53 | 47 50 15 54 | 48 48 21 55 | 49 12 38 56 | 50 15 56 57 | 51 29 39 58 | 52 54 38 59 | 53 55 57 60 | 54 67 41 61 | 55 10 70 62 | 56 6 25 63 | 57 65 27 64 | 58 40 60 65 | 59 70 64 66 | 60 64 4 67 | 61 36 6 68 | 62 30 20 69 | 63 20 30 70 | 64 15 5 71 | 65 50 70 72 | 66 57 72 73 | 67 45 42 74 | 68 38 33 75 | 69 50 4 76 | 70 66 8 77 | 71 59 5 78 | 72 35 60 79 | 73 27 24 80 | 74 40 20 81 | 75 40 37 82 | 76 40 40 83 | EOF 84 | -------------------------------------------------------------------------------- /src/networkx/generators/tests/test_geometric.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | 5 | class TestGeneratorsGeometric(): 6 | def test_random_geometric_graph(self): 7 | G=nx.random_geometric_graph(50,0.25) 8 | assert_equal(len(G),50) 9 | 10 | def test_geographical_threshold_graph(self): 11 | G=nx.geographical_threshold_graph(50,100) 12 | assert_equal(len(G),50) 13 | 14 | def test_waxman_graph(self): 15 | G=nx.waxman_graph(50,0.5,0.1) 16 | assert_equal(len(G),50) 17 | G=nx.waxman_graph(50,0.5,0.1,L=1) 18 | assert_equal(len(G),50) 19 | 20 | def test_naviable_small_world(self): 21 | G = nx.navigable_small_world_graph(5,p=1,q=0) 22 | gg = nx.grid_2d_graph(5,5).to_directed() 23 | assert_true(nx.is_isomorphic(G,gg)) 24 | 25 | G = nx.navigable_small_world_graph(5,p=1,q=0,dim=3) 26 | gg = nx.grid_graph([5,5,5]).to_directed() 27 | assert_true(nx.is_isomorphic(G,gg)) 28 | 29 | G = nx.navigable_small_world_graph(5,p=1,q=0,dim=1) 30 | gg = nx.grid_graph([5]).to_directed() 31 | assert_true(nx.is_isomorphic(G,gg)) 32 | -------------------------------------------------------------------------------- /src/networkx/generators/tests/test_stochastic.py: -------------------------------------------------------------------------------- 1 | from nose.tools import assert_true, assert_equal, raises 2 | import networkx as nx 3 | 4 | def test_stochastic(): 5 | G=nx.DiGraph() 6 | G.add_edge(0,1) 7 | G.add_edge(0,2) 8 | S=nx.stochastic_graph(G) 9 | assert_true(nx.is_isomorphic(G,S)) 10 | assert_equal(sorted(S.edges(data=True)), 11 | [(0, 1, {'weight': 0.5}), 12 | (0, 2, {'weight': 0.5})]) 13 | S=nx.stochastic_graph(G,copy=True) 14 | assert_equal(sorted(S.edges(data=True)), 15 | [(0, 1, {'weight': 0.5}), 16 | (0, 2, {'weight': 0.5})]) 17 | 18 | def test_stochastic_ints(): 19 | G=nx.DiGraph() 20 | G.add_edge(0,1,weight=1) 21 | G.add_edge(0,2,weight=1) 22 | S=nx.stochastic_graph(G) 23 | assert_equal(sorted(S.edges(data=True)), 24 | [(0, 1, {'weight': 0.5}), 25 | (0, 2, {'weight': 0.5})]) 26 | 27 | @raises(nx.NetworkXNotImplemented) 28 | def test_stochastic_graph_input(): 29 | S = nx.stochastic_graph(nx.Graph()) 30 | 31 | @raises(nx.NetworkXNotImplemented) 32 | def test_stochastic_multigraph_input(): 33 | S = nx.stochastic_graph(nx.MultiGraph()) 34 | -------------------------------------------------------------------------------- /src/networkx/readwrite/json_graph/tests/test_tree.py: -------------------------------------------------------------------------------- 1 | import json 2 | from nose.tools import assert_equal, assert_raises, assert_not_equal, assert_true, raises 3 | import networkx as nx 4 | from networkx.readwrite.json_graph import * 5 | 6 | class TestTree: 7 | 8 | def test_graph(self): 9 | G=nx.DiGraph() 10 | G.add_nodes_from([1,2,3],color='red') 11 | G.add_edge(1,2,foo=7) 12 | G.add_edge(1,3,foo=10) 13 | G.add_edge(3,4,foo=10) 14 | H = tree_graph(tree_data(G,1)) 15 | nx.is_isomorphic(G,H) 16 | 17 | def test_graph_attributes(self): 18 | G=nx.DiGraph() 19 | G.add_nodes_from([1,2,3],color='red') 20 | G.add_edge(1,2,foo=7) 21 | G.add_edge(1,3,foo=10) 22 | G.add_edge(3,4,foo=10) 23 | H = tree_graph(tree_data(G,1)) 24 | assert_equal(H.node[1]['color'],'red') 25 | 26 | d = json.dumps(tree_data(G,1)) 27 | H = tree_graph(json.loads(d)) 28 | assert_equal(H.node[1]['color'],'red') 29 | 30 | @raises(nx.NetworkXError) 31 | def test_exception(self): 32 | G = nx.MultiDiGraph() 33 | G.add_node(0) 34 | attrs = dict(id='node', children='node') 35 | tree_data(G, 0, attrs) 36 | -------------------------------------------------------------------------------- /src/networkx/classes/ordered.py: -------------------------------------------------------------------------------- 1 | """ 2 | OrderedDict variants of the default base classes. 3 | 4 | """ 5 | from collections import OrderedDict 6 | 7 | from .graph import Graph 8 | from .multigraph import MultiGraph 9 | from .digraph import DiGraph 10 | from .multidigraph import MultiDiGraph 11 | 12 | __all__ = [] 13 | 14 | __all__.extend([ 15 | 'OrderedGraph', 16 | 'OrderedDiGraph', 17 | 'OrderedMultiGraph', 18 | 'OrderedMultiDiGraph', 19 | ]) 20 | 21 | 22 | class OrderedGraph(Graph): 23 | node_dict_factory = OrderedDict 24 | adjlist_dict_factory = OrderedDict 25 | edge_attr_dict_factory = OrderedDict 26 | 27 | 28 | class OrderedDiGraph(DiGraph): 29 | node_dict_factory = OrderedDict 30 | adjlist_dict_factory = OrderedDict 31 | edge_attr_dict_factory = OrderedDict 32 | 33 | 34 | class OrderedMultiGraph(MultiGraph): 35 | node_dict_factory = OrderedDict 36 | adjlist_dict_factory = OrderedDict 37 | edge_key_dict_factory = OrderedDict 38 | edge_attr_dict_factory = OrderedDict 39 | 40 | 41 | class OrderedMultiDiGraph(MultiDiGraph): 42 | node_dict_factory = OrderedDict 43 | adjlist_dict_factory = OrderedDict 44 | edge_key_dict_factory = OrderedDict 45 | edge_attr_dict_factory = OrderedDict 46 | -------------------------------------------------------------------------------- /src/networkx/algorithms/tests/test_vitality.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | 5 | class TestVitality: 6 | 7 | def test_closeness_vitality_unweighted(self): 8 | G=nx.cycle_graph(3) 9 | v=nx.closeness_vitality(G) 10 | assert_equal(v,{0:4.0, 1:4.0, 2:4.0}) 11 | assert_equal(v[0],4.0) 12 | 13 | def test_closeness_vitality_weighted(self): 14 | G=nx.Graph() 15 | G.add_cycle([0,1,2],weight=2) 16 | v=nx.closeness_vitality(G,weight='weight') 17 | assert_equal(v,{0:8.0, 1:8.0, 2:8.0}) 18 | 19 | def test_closeness_vitality_unweighted_digraph(self): 20 | G=nx.DiGraph() 21 | G.add_cycle([0,1,2]) 22 | v=nx.closeness_vitality(G) 23 | assert_equal(v,{0:8.0, 1:8.0, 2:8.0}) 24 | 25 | def test_closeness_vitality_weighted_digraph(self): 26 | G=nx.DiGraph() 27 | G.add_cycle([0,1,2],weight=2) 28 | v=nx.closeness_vitality(G,weight='weight') 29 | assert_equal(v,{0:16.0, 1:16.0, 2:16.0}) 30 | 31 | def test_closeness_vitality_weighted_multidigraph(self): 32 | G=nx.MultiDiGraph() 33 | G.add_cycle([0,1,2],weight=2) 34 | v=nx.closeness_vitality(G,weight='weight') 35 | assert_equal(v,{0:16.0, 1:16.0, 2:16.0}) 36 | -------------------------------------------------------------------------------- /src/networkx/algorithms/approximation/tests/test_approx_clust_coeff.py: -------------------------------------------------------------------------------- 1 | from nose.tools import assert_equal 2 | import networkx as nx 3 | from networkx.algorithms.approximation import average_clustering 4 | 5 | # This approximation has to be be exact in regular graphs 6 | # with no triangles or with all possible triangles. 7 | def test_petersen(): 8 | # Actual coefficient is 0 9 | G = nx.petersen_graph() 10 | assert_equal(average_clustering(G, trials=int(len(G)/2)), 11 | nx.average_clustering(G)) 12 | 13 | def test_tetrahedral(): 14 | # Actual coefficient is 1 15 | G = nx.tetrahedral_graph() 16 | assert_equal(average_clustering(G, trials=int(len(G)/2)), 17 | nx.average_clustering(G)) 18 | 19 | def test_dodecahedral(): 20 | # Actual coefficient is 0 21 | G = nx.dodecahedral_graph() 22 | assert_equal(average_clustering(G, trials=int(len(G)/2)), 23 | nx.average_clustering(G)) 24 | 25 | def test_empty(): 26 | G = nx.empty_graph(5) 27 | assert_equal(average_clustering(G, trials=int(len(G)/2)), 0) 28 | 29 | def test_complete(): 30 | G = nx.complete_graph(5) 31 | assert_equal(average_clustering(G, trials=int(len(G)/2)), 1) 32 | G = nx.complete_graph(7) 33 | assert_equal(average_clustering(G, trials=int(len(G)/2)), 1) 34 | -------------------------------------------------------------------------------- /src/networkx/algorithms/approximation/tests/test_vertex_cover.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | from networkx.algorithms import approximation as a 5 | 6 | class TestMWVC: 7 | 8 | def test_min_vertex_cover(self): 9 | # create a simple star graph 10 | size = 50 11 | sg = nx.star_graph(size) 12 | cover = a.min_weighted_vertex_cover(sg) 13 | assert_equals(2, len(cover)) 14 | for u, v in sg.edges_iter(): 15 | ok_((u in cover or v in cover), "Node node covered!") 16 | 17 | wg = nx.Graph() 18 | wg.add_node(0, weight=10) 19 | wg.add_node(1, weight=1) 20 | wg.add_node(2, weight=1) 21 | wg.add_node(3, weight=1) 22 | wg.add_node(4, weight=1) 23 | 24 | wg.add_edge(0, 1) 25 | wg.add_edge(0, 2) 26 | wg.add_edge(0, 3) 27 | wg.add_edge(0, 4) 28 | 29 | wg.add_edge(1,2) 30 | wg.add_edge(2,3) 31 | wg.add_edge(3,4) 32 | wg.add_edge(4,1) 33 | 34 | cover = a.min_weighted_vertex_cover(wg, weight="weight") 35 | csum = sum(wg.node[node]["weight"] for node in cover) 36 | assert_equals(4, csum) 37 | 38 | for u, v in wg.edges_iter(): 39 | ok_((u in cover or v in cover), "Node node covered!") 40 | -------------------------------------------------------------------------------- /src/networkx/algorithms/isomorphism/tests/test_isomorphism.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | from networkx.algorithms import isomorphism as iso 5 | 6 | class TestIsomorph: 7 | 8 | def setUp(self): 9 | self.G1=nx.Graph() 10 | self.G2=nx.Graph() 11 | self.G3=nx.Graph() 12 | self.G4=nx.Graph() 13 | self.G1.add_edges_from([ [1,2],[1,3],[1,5],[2,3] ]) 14 | self.G2.add_edges_from([ [10,20],[20,30],[10,30],[10,50] ]) 15 | self.G3.add_edges_from([ [1,2],[1,3],[1,5],[2,5] ]) 16 | self.G4.add_edges_from([ [1,2],[1,3],[1,5],[2,4] ]) 17 | 18 | def test_could_be_isomorphic(self): 19 | assert_true(iso.could_be_isomorphic(self.G1,self.G2)) 20 | assert_true(iso.could_be_isomorphic(self.G1,self.G3)) 21 | assert_false(iso.could_be_isomorphic(self.G1,self.G4)) 22 | assert_true(iso.could_be_isomorphic(self.G3,self.G2)) 23 | 24 | def test_fast_could_be_isomorphic(self): 25 | assert_true(iso.fast_could_be_isomorphic(self.G3,self.G2)) 26 | 27 | def test_faster_could_be_isomorphic(self): 28 | assert_true(iso.faster_could_be_isomorphic(self.G3,self.G2)) 29 | 30 | def test_is_isomorphic(self): 31 | assert_true(iso.is_isomorphic(self.G1,self.G2)) 32 | assert_false(iso.is_isomorphic(self.G1,self.G4)) 33 | -------------------------------------------------------------------------------- /src/networkx/drawing/tests/test_pylab.py: -------------------------------------------------------------------------------- 1 | """ 2 | Unit tests for matplotlib drawing functions. 3 | """ 4 | 5 | import os 6 | 7 | from nose import SkipTest 8 | 9 | import networkx as nx 10 | 11 | class TestPylab(object): 12 | @classmethod 13 | def setupClass(cls): 14 | global plt 15 | try: 16 | import matplotlib as mpl 17 | mpl.use('PS',warn=False) 18 | import matplotlib.pyplot as plt 19 | plt.rcParams['text.usetex'] = False 20 | except ImportError: 21 | raise SkipTest('matplotlib not available.') 22 | except RuntimeError: 23 | raise SkipTest('matplotlib not available.') 24 | 25 | def setUp(self): 26 | self.G=nx.barbell_graph(5,10) 27 | 28 | 29 | def test_draw(self): 30 | try: 31 | N=self.G 32 | nx.draw_spring(N) 33 | plt.savefig("test.ps") 34 | nx.draw_random(N) 35 | plt.savefig("test.ps") 36 | nx.draw_circular(N) 37 | plt.savefig("test.ps") 38 | nx.draw_spectral(N) 39 | plt.savefig("test.ps") 40 | nx.draw_spring(N.to_directed()) 41 | plt.savefig("test.ps") 42 | finally: 43 | try: 44 | os.unlink('test.ps') 45 | except OSError: 46 | pass 47 | -------------------------------------------------------------------------------- /src/networkx/algorithms/smetric.py: -------------------------------------------------------------------------------- 1 | import networkx as nx 2 | #from networkx.generators.smax import li_smax_graph 3 | 4 | def s_metric(G, normalized=True): 5 | """Return the s-metric of graph. 6 | 7 | The s-metric is defined as the sum of the products deg(u)*deg(v) 8 | for every edge (u,v) in G. If norm is provided construct the 9 | s-max graph and compute it's s_metric, and return the normalized 10 | s value 11 | 12 | Parameters 13 | ---------- 14 | G : graph 15 | The graph used to compute the s-metric. 16 | normalized : bool (optional) 17 | Normalize the value. 18 | 19 | Returns 20 | ------- 21 | s : float 22 | The s-metric of the graph. 23 | 24 | References 25 | ---------- 26 | .. [1] Lun Li, David Alderson, John C. Doyle, and Walter Willinger, 27 | Towards a Theory of Scale-Free Graphs: 28 | Definition, Properties, and Implications (Extended Version), 2005. 29 | http://arxiv.org/abs/cond-mat/0501169 30 | """ 31 | if normalized: 32 | raise nx.NetworkXError("Normalization not implemented") 33 | # Gmax = li_smax_graph(list(G.degree().values())) 34 | # return s_metric(G,normalized=False)/s_metric(Gmax,normalized=False) 35 | # else: 36 | return float(sum([G.degree(u)*G.degree(v) for (u,v) in G.edges_iter()])) 37 | 38 | -------------------------------------------------------------------------------- /src/networkx/tests/test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import sys 3 | from os import path,getcwd 4 | 5 | def run(verbosity=1,doctest=False,numpy=True): 6 | """Run NetworkX tests. 7 | 8 | Parameters 9 | ---------- 10 | verbosity: integer, optional 11 | Level of detail in test reports. Higher numbers provide more detail. 12 | 13 | doctest: bool, optional 14 | True to run doctests in code modules 15 | 16 | numpy: bool, optional 17 | True to test modules dependent on numpy 18 | """ 19 | try: 20 | import nose 21 | except ImportError: 22 | raise ImportError(\ 23 | "The nose package is needed to run the NetworkX tests.") 24 | 25 | sys.stderr.write("Running NetworkX tests:") 26 | nx_install_dir=path.join(path.dirname(__file__), path.pardir) 27 | # stop if running from source directory 28 | if getcwd() == path.abspath(path.join(nx_install_dir,path.pardir)): 29 | raise RuntimeError("Can't run tests from source directory.\n" 30 | "Run 'nosetests' from the command line.") 31 | 32 | argv=[' ','--verbosity=%d'%verbosity, 33 | '-w',nx_install_dir, 34 | '-exe'] 35 | if doctest: 36 | argv.extend(['--with-doctest','--doctest-extension=txt']) 37 | if not numpy: 38 | argv.extend(['-A not numpy']) 39 | 40 | 41 | nose.run(argv=argv) 42 | 43 | if __name__=="__main__": 44 | run() 45 | 46 | -------------------------------------------------------------------------------- /src/networkx/algorithms/bipartite/tests/test_redundancy.py: -------------------------------------------------------------------------------- 1 | # test_redundancy.py - unit tests for the bipartite.redundancy module 2 | # 3 | # Copyright 2015 Jeffrey Finkelstein . 4 | # 5 | # This file is part of NetworkX. 6 | # 7 | # NetworkX is distributed under a BSD license; see LICENSE.txt for more 8 | # information. 9 | """Unit tests for the :mod:`networkx.algorithms.bipartite.redundancy` module. 10 | 11 | """ 12 | from __future__ import division 13 | 14 | from nose.tools import assert_equal 15 | from nose.tools import assert_true 16 | from nose.tools import raises 17 | 18 | from networkx import cycle_graph 19 | from networkx import NetworkXError 20 | from networkx.algorithms.bipartite import complete_bipartite_graph 21 | from networkx.algorithms.bipartite import node_redundancy 22 | 23 | 24 | def test_no_redundant_nodes(): 25 | G = complete_bipartite_graph(2, 2) 26 | rc = node_redundancy(G) 27 | assert_true(all(redundancy == 1 for redundancy in rc.values())) 28 | 29 | 30 | def test_redundant_nodes(): 31 | G = cycle_graph(6) 32 | edge = {0, 3} 33 | G.add_edge(*edge) 34 | redundancy = node_redundancy(G) 35 | for v in edge: 36 | assert_equal(redundancy[v], 2 / 3) 37 | for v in set(G) - edge: 38 | assert_equal(redundancy[v], 1) 39 | 40 | 41 | @raises(NetworkXError) 42 | def test_not_enough_neighbors(): 43 | G = complete_bipartite_graph(1, 2) 44 | node_redundancy(G) 45 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | .idea/ 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *,cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # IPython Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # dotenv 80 | .env 81 | 82 | # virtualenv 83 | venv/ 84 | ENV/ 85 | 86 | # Spyder project settings 87 | .spyderproject 88 | 89 | # Rope project settings 90 | .ropeproject 91 | -------------------------------------------------------------------------------- /src/networkx/generators/tests/test_directed.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """Generators - Directed Graphs 4 | ---------------------------- 5 | """ 6 | 7 | from nose.tools import * 8 | from networkx import * 9 | from networkx.generators.directed import * 10 | 11 | class TestGeneratorsDirected(): 12 | def test_smoke_test_random_graphs(self): 13 | G=gn_graph(100) 14 | G=gnr_graph(100,0.5) 15 | G=gnc_graph(100) 16 | G=scale_free_graph(100) 17 | 18 | def test_create_using_keyword_arguments(self): 19 | assert_raises(networkx.exception.NetworkXError, 20 | gn_graph, 100, create_using=Graph()) 21 | assert_raises(networkx.exception.NetworkXError, 22 | gnr_graph, 100, 0.5, create_using=Graph()) 23 | assert_raises(networkx.exception.NetworkXError, 24 | gnc_graph, 100, create_using=Graph()) 25 | assert_raises(networkx.exception.NetworkXError, 26 | scale_free_graph, 100, create_using=Graph()) 27 | G=gn_graph(100,seed=1) 28 | MG=gn_graph(100,create_using=MultiDiGraph(),seed=1) 29 | assert_equal(G.edges(), MG.edges()) 30 | G=gnr_graph(100,0.5,seed=1) 31 | MG=gnr_graph(100,0.5,create_using=MultiDiGraph(),seed=1) 32 | assert_equal(G.edges(), MG.edges()) 33 | G=gnc_graph(100,seed=1) 34 | MG=gnc_graph(100,create_using=MultiDiGraph(),seed=1) 35 | assert_equal(G.edges(), MG.edges()) 36 | 37 | -------------------------------------------------------------------------------- /src/networkx/utils/tests/test_rcm.py: -------------------------------------------------------------------------------- 1 | from nose.tools import * 2 | from networkx.utils import reverse_cuthill_mckee_ordering 3 | import networkx as nx 4 | 5 | 6 | def test_reverse_cuthill_mckee(): 7 | # example graph from 8 | # http://www.boost.org/doc/libs/1_37_0/libs/graph/example/cuthill_mckee_ordering.cpp 9 | G = nx.Graph([(0, 3), (0, 5), (1, 2), (1, 4), (1, 6), (1, 9), (2, 3), 10 | (2, 4), (3, 5), (3, 8), (4, 6), (5, 6), (5, 7), (6, 7)]) 11 | rcm = list(reverse_cuthill_mckee_ordering(G)) 12 | assert_true(rcm in [[0, 8, 5, 7, 3, 6, 2, 4, 1, 9], 13 | [0, 8, 5, 7, 3, 6, 4, 2, 1, 9]]) 14 | 15 | 16 | def test_rcm_alternate_heuristic(): 17 | # example from 18 | G = nx.Graph([(0, 0), 19 | (0, 4), 20 | (1, 1), 21 | (1, 2), 22 | (1, 5), 23 | (1, 7), 24 | (2, 2), 25 | (2, 4), 26 | (3, 3), 27 | (3, 6), 28 | (4, 4), 29 | (5, 5), 30 | (5, 7), 31 | (6, 6), 32 | (7, 7)]) 33 | 34 | answers = [[6, 3, 5, 7, 1, 2, 4, 0], [6, 3, 7, 5, 1, 2, 4, 0]] 35 | 36 | def smallest_degree(G): 37 | node, deg = min(G.degree().items(), key=lambda x: x[1]) 38 | return node 39 | rcm = list(reverse_cuthill_mckee_ordering(G, heuristic=smallest_degree)) 40 | assert_true(rcm in answers) 41 | -------------------------------------------------------------------------------- /src/networkx/algorithms/tests/test_swap.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | from networkx import * 4 | 5 | import random 6 | random.seed(0) 7 | 8 | def test_double_edge_swap(): 9 | graph = barabasi_albert_graph(200,1) 10 | degrees = sorted(graph.degree().values()) 11 | G = double_edge_swap(graph, 40) 12 | assert_equal(degrees, sorted(graph.degree().values())) 13 | 14 | def test_connected_double_edge_swap(): 15 | graph = barabasi_albert_graph(200,1) 16 | degrees = sorted(graph.degree().values()) 17 | G = connected_double_edge_swap(graph, 40) 18 | assert_true(is_connected(graph)) 19 | assert_equal(degrees, sorted(graph.degree().values())) 20 | 21 | @raises(NetworkXError) 22 | def test_double_edge_swap_small(): 23 | G = nx.double_edge_swap(nx.path_graph(3)) 24 | 25 | @raises(NetworkXError) 26 | def test_double_edge_swap_tries(): 27 | G = nx.double_edge_swap(nx.path_graph(10),nswap=1,max_tries=0) 28 | 29 | @raises(NetworkXError) 30 | def test_connected_double_edge_swap_small(): 31 | G = nx.connected_double_edge_swap(nx.path_graph(3)) 32 | 33 | @raises(NetworkXError) 34 | def test_connected_double_edge_swap_not_connected(): 35 | G = nx.path_graph(3) 36 | G.add_path([10,11,12]) 37 | G = nx.connected_double_edge_swap(G) 38 | 39 | def test_degree_seq_c4(): 40 | G = cycle_graph(4) 41 | degrees = sorted(G.degree().values()) 42 | G = double_edge_swap(G,1,100) 43 | assert_equal(degrees, sorted(G.degree().values())) 44 | 45 | -------------------------------------------------------------------------------- /src/networkx/algorithms/isomorphism/tests/iso_r01_s80.B99: -------------------------------------------------------------------------------- 1 | P78<BG 2:FJ 2 | !$&,1:>FN25<?/;= ,K !"#%2@9=K&'>EKO3:<?AGIN &025<>K 3 | (4: ;@FJL!&.:@K!(*6CD $'-/4BK ",>@C !%9?AHN 4 | %7H *2CIL.18:M 5 | -<>BGI$+.6D"2K&, ?CFH "*.@HJN %4LN'IJO"1?@H 6 | K );D$348E;J#%)F  &-34@AM 7 |  8 | !#1<?BK !.@CFI  ')*56E ;O &;O $&127J$GI  $45:AKO !%./18?EN  %&8J05;>BIL *;EI4H  #05>GM +?@/2@  ./5>ACG 9 | 4B #+3EGH  *B ;?HN#27=FN23=>B  10 | !/38AHK-@  (-58:>?CGO -/02?JO7>$BMN $'(C"/24?I 9L(F &.0<J (+B  11 | ,<BK/29BCG 12 | !#&-2<>CMOM%DEHN;DH  13 | &.4=J !*/;B "')9C -------------------------------------------------------------------------------- /src/networkx/algorithms/isomorphism/tests/iso_r01_s80.A99: -------------------------------------------------------------------------------- 1 | P%6:CG ,-.9:G%014 !$+02:BJ !*567<AL 2 | 26 13DGIK,29M+/FJ -1 3 | (/6;ACDH   %1<?@AJ #%05 4 | ,/HMO .KL 5 | $-04=';@ $36;DO/268;!%):=H #)15G ",15BFK #+?@ #&)5@AGJM*=L *49F&(+/?*/58>DL02<>M 6 | %:C #&157A 7 | &(2<AD#*.D  8 | ')*+AFHKN,=AH*-/O-6"$&+1F>?FK&*1H)+2=IM<M 9 | !3> "%/  !$/47&?FI '-367HJNO/23HJK 10 | "$&/0J %(2<(23@ ,2ABJ &/CEJN +8&)3469=@BCHO!0@G >?C )-08<  (/6  ->CL#1<  )KLN &'-15B $%E  "#$+/ADFMO".:EHNO 0;BFM  "')46FHK!25;(?LO ')?O !)07C 11 | $,BGN 8J 12 | 13 |  (+236B 14 | &'(357K !BIAEF -------------------------------------------------------------------------------- /data/eil51.vrp: -------------------------------------------------------------------------------- 1 | NAME : eil51 2 | COMMENT : (Eilon et al.) 3 | TYPE : CVRP 4 | DIMENSION : 51 5 | EDGE_WEIGHT_TYPE : EUC_2D 6 | CAPACITY : 160 7 | NODE_COORD_SECTION 8 | 1 30 40 9 | 2 37 52 10 | 3 49 49 11 | 4 52 64 12 | 5 20 26 13 | 6 40 30 14 | 7 21 47 15 | 8 17 63 16 | 9 31 62 17 | 10 52 33 18 | 11 51 21 19 | 12 42 41 20 | 13 31 32 21 | 14 5 25 22 | 15 12 42 23 | 16 36 16 24 | 17 52 41 25 | 18 27 23 26 | 19 17 33 27 | 20 13 13 28 | 21 57 58 29 | 22 62 42 30 | 23 42 57 31 | 24 16 57 32 | 25 8 52 33 | 26 7 38 34 | 27 27 68 35 | 28 30 48 36 | 29 43 67 37 | 30 58 48 38 | 31 58 27 39 | 32 37 69 40 | 33 38 46 41 | 34 46 10 42 | 35 61 33 43 | 36 62 63 44 | 37 63 69 45 | 38 32 22 46 | 39 45 35 47 | 40 59 15 48 | 41 5 6 49 | 42 10 17 50 | 43 21 10 51 | 44 5 64 52 | 45 30 15 53 | 46 39 10 54 | 47 32 39 55 | 48 25 32 56 | 49 25 55 57 | 50 48 28 58 | 51 56 37 59 | DEMAND_SECTION 60 | 1 0 61 | 2 7 62 | 3 30 63 | 4 16 64 | 5 9 65 | 6 21 66 | 7 15 67 | 8 19 68 | 9 23 69 | 10 11 70 | 11 5 71 | 12 19 72 | 13 29 73 | 14 23 74 | 15 21 75 | 16 10 76 | 17 15 77 | 18 3 78 | 19 41 79 | 20 9 80 | 21 28 81 | 22 8 82 | 23 8 83 | 24 16 84 | 25 10 85 | 26 28 86 | 27 7 87 | 28 15 88 | 29 14 89 | 30 6 90 | 31 19 91 | 32 11 92 | 33 12 93 | 34 23 94 | 35 26 95 | 36 17 96 | 37 6 97 | 38 9 98 | 39 15 99 | 40 14 100 | 41 7 101 | 42 27 102 | 43 13 103 | 44 11 104 | 45 16 105 | 46 10 106 | 47 5 107 | 48 25 108 | 49 17 109 | 50 18 110 | 51 10 111 | DEPOT_SECTION 112 | 1 113 | -1 114 | EOF 115 | -------------------------------------------------------------------------------- /data/eil51.demand: -------------------------------------------------------------------------------- 1 | NAME : eil51 2 | COMMENT : (Eilon et al.) 3 | TYPE : CVRP 4 | DIMENSION : 51 5 | EDGE_WEIGHT_TYPE : EUC_2D 6 | CAPACITY : 160 7 | NODE_COORD_SECTION 8 | 1 30 40 9 | 2 37 52 10 | 3 49 49 11 | 4 52 64 12 | 5 20 26 13 | 6 40 30 14 | 7 21 47 15 | 8 17 63 16 | 9 31 62 17 | 10 52 33 18 | 11 51 21 19 | 12 42 41 20 | 13 31 32 21 | 14 5 25 22 | 15 12 42 23 | 16 36 16 24 | 17 52 41 25 | 18 27 23 26 | 19 17 33 27 | 20 13 13 28 | 21 57 58 29 | 22 62 42 30 | 23 42 57 31 | 24 16 57 32 | 25 8 52 33 | 26 7 38 34 | 27 27 68 35 | 28 30 48 36 | 29 43 67 37 | 30 58 48 38 | 31 58 27 39 | 32 37 69 40 | 33 38 46 41 | 34 46 10 42 | 35 61 33 43 | 36 62 63 44 | 37 63 69 45 | 38 32 22 46 | 39 45 35 47 | 40 59 15 48 | 41 5 6 49 | 42 10 17 50 | 43 21 10 51 | 44 5 64 52 | 45 30 15 53 | 46 39 10 54 | 47 32 39 55 | 48 25 32 56 | 49 25 55 57 | 50 48 28 58 | 51 56 37 59 | DEMAND_SECTION 60 | 1 0 61 | 2 7 62 | 3 30 63 | 4 16 64 | 5 9 65 | 6 21 66 | 7 15 67 | 8 19 68 | 9 23 69 | 10 11 70 | 11 5 71 | 12 19 72 | 13 29 73 | 14 23 74 | 15 21 75 | 16 10 76 | 17 15 77 | 18 3 78 | 19 41 79 | 20 9 80 | 21 28 81 | 22 8 82 | 23 8 83 | 24 16 84 | 25 10 85 | 26 28 86 | 27 7 87 | 28 15 88 | 29 14 89 | 30 6 90 | 31 19 91 | 32 11 92 | 33 12 93 | 34 23 94 | 35 26 95 | 36 17 96 | 37 6 97 | 38 9 98 | 39 15 99 | 40 14 100 | 41 7 101 | 42 27 102 | 43 13 103 | 44 11 104 | 45 16 105 | 46 10 106 | 47 5 107 | 48 25 108 | 49 17 109 | 50 18 110 | 51 10 111 | DEPOT_SECTION 112 | 1 113 | -1 114 | EOF 115 | -------------------------------------------------------------------------------- /src/networkx/algorithms/tests/test_dominating.py: -------------------------------------------------------------------------------- 1 | from nose.tools import assert_equal, assert_true, assert_false, raises 2 | import networkx as nx 3 | 4 | def test_dominating_set(): 5 | G = nx.gnp_random_graph(100, 0.1) 6 | D = nx.dominating_set(G) 7 | assert_true(nx.is_dominating_set(G, D)) 8 | D = nx.dominating_set(G, start_with=0) 9 | assert_true(nx.is_dominating_set(G, D)) 10 | 11 | def test_complete(): 12 | """ In complete graphs each node is a dominating set. 13 | Thus the dominating set has to be of cardinality 1. 14 | """ 15 | K4 = nx.complete_graph(4) 16 | assert_equal(len(nx.dominating_set(K4)), 1) 17 | K5 = nx.complete_graph(5) 18 | assert_equal(len(nx.dominating_set(K5)), 1) 19 | 20 | @raises(nx.NetworkXError) 21 | def test_dominating_set_error(): 22 | G = nx.path_graph(4) 23 | D = nx.dominating_set(G, start_with=10) 24 | 25 | def test_is_dominating_set(): 26 | G = nx.path_graph(4) 27 | d = set([1, 3]) 28 | assert_true(nx.is_dominating_set(G, d)) 29 | d = set([0, 2]) 30 | assert_true(nx.is_dominating_set(G, d)) 31 | d = set([1]) 32 | assert_false(nx.is_dominating_set(G, d)) 33 | 34 | def test_wikipedia_is_dominating_set(): 35 | """Example from http://en.wikipedia.org/wiki/Dominating_set 36 | """ 37 | G = nx.cycle_graph(4) 38 | G.add_edges_from([(0, 4), (1, 4), (2,5)]) 39 | assert_true(nx.is_dominating_set(G, set([4, 3, 5]))) 40 | assert_true(nx.is_dominating_set(G, set([0, 2]))) 41 | assert_true(nx.is_dominating_set(G, set([1, 2]))) 42 | -------------------------------------------------------------------------------- /src/networkx/generators/tests/test_ego.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | ego graph 4 | --------- 5 | """ 6 | 7 | from nose.tools import assert_true, assert_equal 8 | import networkx as nx 9 | 10 | class TestGeneratorEgo(): 11 | def test_ego(self): 12 | G=nx.star_graph(3) 13 | H=nx.ego_graph(G,0) 14 | assert_true(nx.is_isomorphic(G,H)) 15 | G.add_edge(1,11) 16 | G.add_edge(2,22) 17 | G.add_edge(3,33) 18 | H=nx.ego_graph(G,0) 19 | assert_true(nx.is_isomorphic(nx.star_graph(3),H)) 20 | G=nx.path_graph(3) 21 | H=nx.ego_graph(G,0) 22 | assert_equal(H.edges(), [(0, 1)]) 23 | H=nx.ego_graph(G,0,undirected=True) 24 | assert_equal(H.edges(), [(0, 1)]) 25 | H=nx.ego_graph(G,0,center=False) 26 | assert_equal(H.edges(), []) 27 | 28 | 29 | def test_ego_distance(self): 30 | G=nx.Graph() 31 | G.add_edge(0,1,weight=2,distance=1) 32 | G.add_edge(1,2,weight=2,distance=2) 33 | G.add_edge(2,3,weight=2,distance=1) 34 | assert_equal(sorted(nx.ego_graph(G,0,radius=3).nodes()),[0,1,2,3]) 35 | eg=nx.ego_graph(G,0,radius=3,distance='weight') 36 | assert_equal(sorted(eg.nodes()),[0,1]) 37 | eg=nx.ego_graph(G,0,radius=3,distance='weight',undirected=True) 38 | assert_equal(sorted(eg.nodes()),[0,1]) 39 | eg=nx.ego_graph(G,0,radius=3,distance='distance') 40 | assert_equal(sorted(eg.nodes()),[0,1,2]) 41 | 42 | 43 | -------------------------------------------------------------------------------- /src/networkx/algorithms/approximation/matching.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | ************** 4 | Graph Matching 5 | ************** 6 | 7 | Given a graph G = (V,E), a matching M in G is a set of pairwise non-adjacent 8 | edges; that is, no two edges share a common vertex. 9 | 10 | http://en.wikipedia.org/wiki/Matching_(graph_theory) 11 | """ 12 | # Copyright (C) 2011-2012 by 13 | # Nicholas Mancuso 14 | # All rights reserved. 15 | # BSD license. 16 | import networkx as nx 17 | __all__ = ["min_maximal_matching"] 18 | __author__ = """Nicholas Mancuso (nick.mancuso@gmail.com)""" 19 | 20 | def min_maximal_matching(G): 21 | r"""Returns the minimum maximal matching of G. That is, out of all maximal 22 | matchings of the graph G, the smallest is returned. 23 | 24 | Parameters 25 | ---------- 26 | G : NetworkX graph 27 | Undirected graph 28 | 29 | Returns 30 | ------- 31 | min_maximal_matching : set 32 | Returns a set of edges such that no two edges share a common endpoint 33 | and every edge not in the set shares some common endpoint in the set. 34 | Cardinality will be 2*OPT in the worst case. 35 | 36 | Notes 37 | ----- 38 | The algorithm computes an approximate solution fo the minimum maximal 39 | cardinality matching problem. The solution is no more than 2 * OPT in size. 40 | Runtime is `O(|E|)`. 41 | 42 | References 43 | ---------- 44 | .. [1] Vazirani, Vijay Approximation Algorithms (2001) 45 | """ 46 | return nx.maximal_matching(G) 47 | -------------------------------------------------------------------------------- /src/networkx/algorithms/operators/tests/test_unary.py: -------------------------------------------------------------------------------- 1 | from nose.tools import * 2 | import networkx as nx 3 | from networkx import * 4 | 5 | 6 | def test_complement(): 7 | null=null_graph() 8 | empty1=empty_graph(1) 9 | empty10=empty_graph(10) 10 | K3=complete_graph(3) 11 | K5=complete_graph(5) 12 | K10=complete_graph(10) 13 | P2=path_graph(2) 14 | P3=path_graph(3) 15 | P5=path_graph(5) 16 | P10=path_graph(10) 17 | #complement of the complete graph is empty 18 | 19 | G=complement(K3) 20 | assert_true(is_isomorphic(G,empty_graph(3))) 21 | G=complement(K5) 22 | assert_true(is_isomorphic(G,empty_graph(5))) 23 | # for any G, G=complement(complement(G)) 24 | P3cc=complement(complement(P3)) 25 | assert_true(is_isomorphic(P3,P3cc)) 26 | nullcc=complement(complement(null)) 27 | assert_true(is_isomorphic(null,nullcc)) 28 | b=bull_graph() 29 | bcc=complement(complement(b)) 30 | assert_true(is_isomorphic(b,bcc)) 31 | 32 | def test_complement_2(): 33 | G1=nx.DiGraph() 34 | G1.add_edge('A','B') 35 | G1.add_edge('A','C') 36 | G1.add_edge('A','D') 37 | G1C=complement(G1) 38 | assert_equal(sorted(G1C.edges()), 39 | [('B', 'A'), ('B', 'C'), 40 | ('B', 'D'), ('C', 'A'), ('C', 'B'), 41 | ('C', 'D'), ('D', 'A'), ('D', 'B'), ('D', 'C')]) 42 | 43 | def test_reverse1(): 44 | # Other tests for reverse are done by the DiGraph and MultiDigraph. 45 | G1=nx.Graph() 46 | assert_raises(nx.NetworkXError, nx.reverse, G1) 47 | 48 | -------------------------------------------------------------------------------- /src/networkx/algorithms/traversal/tests/test_bfs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | 5 | 6 | class TestBFS: 7 | 8 | def setUp(self): 9 | # simple graph 10 | G = nx.Graph() 11 | G.add_edges_from([(0, 1), (1, 2), (1, 3), (2, 4), (3, 4)]) 12 | self.G = G 13 | 14 | def test_successor(self): 15 | assert_equal(nx.bfs_successors(self.G, source=0), 16 | {0: [1], 1: [2, 3], 2: [4]}) 17 | 18 | def test_predecessor(self): 19 | assert_equal(nx.bfs_predecessors(self.G, source=0), 20 | {1: 0, 2: 1, 3: 1, 4: 2}) 21 | 22 | def test_bfs_tree(self): 23 | T = nx.bfs_tree(self.G, source=0) 24 | assert_equal(sorted(T.nodes()), sorted(self.G.nodes())) 25 | assert_equal(sorted(T.edges()), [(0, 1), (1, 2), (1, 3), (2, 4)]) 26 | 27 | def test_bfs_edges(self): 28 | edges = nx.bfs_edges(self.G, source=0) 29 | assert_equal(list(edges), [(0, 1), (1, 2), (1, 3), (2, 4)]) 30 | 31 | def test_bfs_edges_reverse(self): 32 | D = nx.DiGraph() 33 | D.add_edges_from([(0, 1), (1, 2), (1, 3), (2, 4), (3, 4)]) 34 | edges = nx.bfs_edges(D, source=4, reverse=True) 35 | assert_equal(list(edges), [(4, 2), (4, 3), (2, 1), (1, 0)]) 36 | 37 | def test_bfs_tree_isolates(self): 38 | G = nx.Graph() 39 | G.add_node(1) 40 | G.add_node(2) 41 | T = nx.bfs_tree(G, source=1) 42 | assert_equal(sorted(T.nodes()), [1]) 43 | assert_equal(sorted(T.edges()), []) 44 | -------------------------------------------------------------------------------- /src/networkx/readwrite/tests/test_yaml.py: -------------------------------------------------------------------------------- 1 | """ 2 | Unit tests for yaml. 3 | """ 4 | 5 | import os,tempfile 6 | from nose import SkipTest 7 | from nose.tools import assert_equal 8 | 9 | import networkx as nx 10 | from networkx.testing import assert_edges_equal, assert_nodes_equal 11 | 12 | class TestYaml(object): 13 | @classmethod 14 | def setupClass(cls): 15 | global yaml 16 | try: 17 | import yaml 18 | except ImportError: 19 | raise SkipTest('yaml not available.') 20 | 21 | def setUp(self): 22 | self.build_graphs() 23 | 24 | def build_graphs(self): 25 | self.G = nx.Graph(name="test") 26 | e = [('a','b'),('b','c'),('c','d'),('d','e'),('e','f'),('a','f')] 27 | self.G.add_edges_from(e) 28 | self.G.add_node('g') 29 | 30 | self.DG = nx.DiGraph(self.G) 31 | 32 | self.MG = nx.MultiGraph() 33 | self.MG.add_weighted_edges_from([(1,2,5),(1,2,5),(1,2,1),(3,3,42)]) 34 | 35 | def assert_equal(self, G, data=False): 36 | (fd, fname) = tempfile.mkstemp() 37 | nx.write_yaml(G, fname) 38 | Gin = nx.read_yaml(fname); 39 | 40 | assert_nodes_equal(G.nodes(), Gin.nodes()) 41 | assert_edges_equal(G.edges(data=data), Gin.edges(data=data)) 42 | 43 | os.close(fd) 44 | os.unlink(fname) 45 | 46 | def testUndirected(self): 47 | self.assert_equal(self.G, False) 48 | 49 | def testDirected(self): 50 | self.assert_equal(self.DG, False) 51 | 52 | def testMultiGraph(self): 53 | self.assert_equal(self.MG, True) 54 | 55 | -------------------------------------------------------------------------------- /data/att48.vrp: -------------------------------------------------------------------------------- 1 | NAME : att48 2 | COMMENT : (Rinaldi,Yarrow/Araque) 3 | TYPE : CVRP 4 | DIMENSION : 48 5 | EDGE_WEIGHT_TYPE : ATT 6 | CAPACITY : 15 7 | NODE_COORD_SECTION 8 | 1 6823 4674 9 | 2 7692 2247 10 | 3 9135 6748 11 | 4 7721 3451 12 | 5 8304 8580 13 | 6 7501 5899 14 | 7 4687 1373 15 | 8 5429 1408 16 | 9 7877 1716 17 | 10 7260 2083 18 | 11 7096 7869 19 | 12 6539 3513 20 | 13 6272 2992 21 | 14 6471 4275 22 | 15 7110 4369 23 | 16 6462 2634 24 | 17 8476 2874 25 | 18 3961 1370 26 | 19 5555 1519 27 | 20 4422 1249 28 | 21 5584 3081 29 | 22 5776 4498 30 | 23 8035 2880 31 | 24 6963 3782 32 | 25 6336 7348 33 | 26 8139 8306 34 | 27 4326 1426 35 | 28 5164 1440 36 | 29 8389 5804 37 | 30 4639 1629 38 | 31 6344 1436 39 | 32 5840 5736 40 | 33 5972 2555 41 | 34 7947 4373 42 | 35 6929 8958 43 | 36 5366 1733 44 | 37 4550 1219 45 | 38 6901 1589 46 | 39 6316 5497 47 | 40 7010 2710 48 | 41 9005 3996 49 | 42 7576 7065 50 | 43 4246 1701 51 | 44 5906 1472 52 | 45 6469 8971 53 | 46 6152 2174 54 | 47 5887 3796 55 | 48 7203 5958 56 | DEMAND_SECTION 57 | 1 0 58 | 2 1 59 | 3 1 60 | 4 1 61 | 5 1 62 | 6 1 63 | 7 1 64 | 8 1 65 | 9 1 66 | 10 1 67 | 11 1 68 | 12 1 69 | 13 1 70 | 14 1 71 | 15 1 72 | 16 1 73 | 17 1 74 | 18 1 75 | 19 1 76 | 20 1 77 | 21 1 78 | 22 1 79 | 23 1 80 | 24 1 81 | 25 1 82 | 26 1 83 | 27 1 84 | 28 1 85 | 29 1 86 | 30 1 87 | 31 1 88 | 32 1 89 | 33 1 90 | 34 1 91 | 35 1 92 | 36 1 93 | 37 1 94 | 38 1 95 | 39 1 96 | 40 1 97 | 41 1 98 | 42 1 99 | 43 1 100 | 44 1 101 | 45 1 102 | 46 1 103 | 47 1 104 | 48 1 105 | DEPOT_SECTION 106 | 1 107 | -1 108 | EOF 109 | -------------------------------------------------------------------------------- /src/networkx/algorithms/approximation/tests/test_clique.py: -------------------------------------------------------------------------------- 1 | from nose.tools import * 2 | import networkx as nx 3 | import networkx.algorithms.approximation as apxa 4 | 5 | def test_clique_removal(): 6 | graph = nx.complete_graph(10) 7 | i, cs = apxa.clique_removal(graph) 8 | idens = nx.density(graph.subgraph(i)) 9 | eq_(idens, 0.0, "i-set not found by clique_removal!") 10 | for clique in cs: 11 | cdens = nx.density(graph.subgraph(clique)) 12 | eq_(cdens, 1.0, "clique not found by clique_removal!") 13 | 14 | graph = nx.trivial_graph(nx.Graph()) 15 | i, cs = apxa.clique_removal(graph) 16 | idens = nx.density(graph.subgraph(i)) 17 | eq_(idens, 0.0, "i-set not found by ramsey!") 18 | # we should only have 1-cliques. Just singleton nodes. 19 | for clique in cs: 20 | cdens = nx.density(graph.subgraph(clique)) 21 | eq_(cdens, 0.0, "clique not found by clique_removal!") 22 | 23 | graph = nx.barbell_graph(10, 5, nx.Graph()) 24 | i, cs = apxa.clique_removal(graph) 25 | idens = nx.density(graph.subgraph(i)) 26 | eq_(idens, 0.0, "i-set not found by ramsey!") 27 | for clique in cs: 28 | cdens = nx.density(graph.subgraph(clique)) 29 | eq_(cdens, 1.0, "clique not found by clique_removal!") 30 | 31 | def test_max_clique_smoke(): 32 | # smoke test 33 | G = nx.Graph() 34 | assert_equal(len(apxa.max_clique(G)),0) 35 | 36 | def test_max_clique(): 37 | # create a complete graph 38 | graph = nx.complete_graph(30) 39 | # this should return the entire graph 40 | mc = apxa.max_clique(graph) 41 | assert_equals(30, len(mc)) 42 | -------------------------------------------------------------------------------- /data/eil101.tsp: -------------------------------------------------------------------------------- 1 | NAME : eil101 2 | COMMENT : 101-city problem (Christofides/Eilon) 3 | TYPE : TSP 4 | DIMENSION : 101 5 | EDGE_WEIGHT_TYPE : EUC_2D 6 | NODE_COORD_SECTION 7 | 1 41 49 8 | 2 35 17 9 | 3 55 45 10 | 4 55 20 11 | 5 15 30 12 | 6 25 30 13 | 7 20 50 14 | 8 10 43 15 | 9 55 60 16 | 10 30 60 17 | 11 20 65 18 | 12 50 35 19 | 13 30 25 20 | 14 15 10 21 | 15 30 5 22 | 16 10 20 23 | 17 5 30 24 | 18 20 40 25 | 19 15 60 26 | 20 45 65 27 | 21 45 20 28 | 22 45 10 29 | 23 55 5 30 | 24 65 35 31 | 25 65 20 32 | 26 45 30 33 | 27 35 40 34 | 28 41 37 35 | 29 64 42 36 | 30 40 60 37 | 31 31 52 38 | 32 35 69 39 | 33 53 52 40 | 34 65 55 41 | 35 63 65 42 | 36 2 60 43 | 37 20 20 44 | 38 5 5 45 | 39 60 12 46 | 40 40 25 47 | 41 42 7 48 | 42 24 12 49 | 43 23 3 50 | 44 11 14 51 | 45 6 38 52 | 46 2 48 53 | 47 8 56 54 | 48 13 52 55 | 49 6 68 56 | 50 47 47 57 | 51 49 58 58 | 52 27 43 59 | 53 37 31 60 | 54 57 29 61 | 55 63 23 62 | 56 53 12 63 | 57 32 12 64 | 58 36 26 65 | 59 21 24 66 | 60 17 34 67 | 61 12 24 68 | 62 24 58 69 | 63 27 69 70 | 64 15 77 71 | 65 62 77 72 | 66 49 73 73 | 67 67 5 74 | 68 56 39 75 | 69 37 47 76 | 70 37 56 77 | 71 57 68 78 | 72 47 16 79 | 73 44 17 80 | 74 46 13 81 | 75 49 11 82 | 76 49 42 83 | 77 53 43 84 | 78 61 52 85 | 79 57 48 86 | 80 56 37 87 | 81 55 54 88 | 82 15 47 89 | 83 14 37 90 | 84 11 31 91 | 85 16 22 92 | 86 4 18 93 | 87 28 18 94 | 88 26 52 95 | 89 26 35 96 | 90 31 67 97 | 91 15 19 98 | 92 22 22 99 | 93 18 24 100 | 94 26 27 101 | 95 25 24 102 | 96 22 27 103 | 97 25 21 104 | 98 19 21 105 | 99 20 26 106 | 100 18 18 107 | 101 35 35 108 | EOF 109 | -------------------------------------------------------------------------------- /src/networkx/algorithms/centrality/tests/test_dispersion.py: -------------------------------------------------------------------------------- 1 | import networkx as nx 2 | from nose.tools import * 3 | 4 | def small_ego_G(): 5 | """The sample network from http://arxiv.org/pdf/1310.6753v1.pdf""" 6 | edges=[('a','b'), ('a','c'), ('b','c'), ('b','d'), 7 | ('b', 'e'),('b','f'),('c','d'),('c','f'),('c','h'),('d','f'), ('e','f'), 8 | ('f','h'),('h','j'), ('h','k'),('i','j'), ('i','k'), ('j','k'), ('u','a'), 9 | ('u','b'), ('u','c'), ('u','d'), ('u','e'), ('u','f'), ('u','g'), ('u','h'), 10 | ('u','i'), ('u','j'), ('u','k')] 11 | G = nx.Graph() 12 | G.add_edges_from(edges) 13 | 14 | return G 15 | 16 | class TestDispersion(object): 17 | 18 | def test_article(self): 19 | """our algorithm matches article's""" 20 | G = small_ego_G() 21 | disp_uh = nx.dispersion(G, 'u', 'h', normalized=False) 22 | disp_ub = nx.dispersion(G, 'u', 'b', normalized=False) 23 | assert disp_uh == 4 24 | assert disp_ub == 1 25 | 26 | def test_results_length(self): 27 | """there is a result for every node""" 28 | G = small_ego_G() 29 | disp = nx.dispersion(G) 30 | disp_Gu = nx.dispersion(G, 'u') 31 | disp_uv = nx.dispersion(G, 'u', 'h') 32 | assert len(disp) == len(G) 33 | assert len(disp_Gu) == len(G) - 1 34 | assert type(disp_uv) is float 35 | 36 | def test_impossible_things(self): 37 | G=nx.karate_club_graph() 38 | disp = nx.dispersion(G) 39 | for u in disp: 40 | for v in disp[u]: 41 | assert disp[u][v] >= 0 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/networkx/readwrite/tests/test_p2g.py: -------------------------------------------------------------------------------- 1 | from nose.tools import assert_equal, assert_raises, assert_not_equal 2 | import networkx as nx 3 | import io 4 | import tempfile 5 | import os 6 | from networkx.readwrite.p2g import * 7 | from networkx.testing import * 8 | 9 | 10 | class TestP2G: 11 | 12 | def setUp(self): 13 | self.G=nx.Graph(name="test") 14 | e=[('a','b'),('b','c'),('c','d'),('d','e'),('e','f'),('a','f')] 15 | self.G.add_edges_from(e) 16 | self.G.add_node('g') 17 | self.DG=nx.DiGraph(self.G) 18 | 19 | def test_read_p2g(self): 20 | s = b"""\ 21 | name 22 | 3 4 23 | a 24 | 1 2 25 | b 26 | 27 | c 28 | 0 2 29 | """ 30 | bytesIO = io.BytesIO(s) 31 | G = read_p2g(bytesIO) 32 | assert_equal(G.name,'name') 33 | assert_equal(sorted(G),['a','b','c']) 34 | edges = [(str(u),str(v)) for u,v in G.edges()] 35 | assert_edges_equal(G.edges(),[('a','c'),('a','b'),('c','a'),('c','c')]) 36 | 37 | def test_write_p2g(self): 38 | s=b"""foo 39 | 3 2 40 | 1 41 | 1 42 | 2 43 | 2 44 | 3 45 | 46 | """ 47 | fh=io.BytesIO() 48 | G=nx.DiGraph() 49 | G.name='foo' 50 | G.add_edges_from([(1,2),(2,3)]) 51 | write_p2g(G,fh) 52 | fh.seek(0) 53 | r=fh.read() 54 | assert_equal(r,s) 55 | 56 | def test_write_read_p2g(self): 57 | fh=io.BytesIO() 58 | G=nx.DiGraph() 59 | G.name='foo' 60 | G.add_edges_from([('a','b'),('b','c')]) 61 | write_p2g(G,fh) 62 | fh.seek(0) 63 | H=read_p2g(fh) 64 | assert_edges_equal(G.edges(),H.edges()) 65 | -------------------------------------------------------------------------------- /src/networkx/algorithms/centrality/tests/test_current_flow_closeness.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | from nose import SkipTest 4 | import networkx 5 | 6 | class TestFlowClosenessCentrality(object): 7 | numpy=1 # nosetests attribute, use nosetests -a 'not numpy' to skip test 8 | @classmethod 9 | def setupClass(cls): 10 | global np 11 | try: 12 | import numpy as np 13 | import scipy 14 | except ImportError: 15 | raise SkipTest('NumPy not available.') 16 | 17 | 18 | def test_K4(self): 19 | """Closeness centrality: K4""" 20 | G=networkx.complete_graph(4) 21 | b=networkx.current_flow_closeness_centrality(G) 22 | b_answer={0: 2.0/3, 1: 2.0/3, 2: 2.0/3, 3: 2.0/3} 23 | for n in sorted(G): 24 | assert_almost_equal(b[n],b_answer[n]) 25 | 26 | 27 | def test_P4(self): 28 | """Closeness centrality: P4""" 29 | G=networkx.path_graph(4) 30 | b=networkx.current_flow_closeness_centrality(G) 31 | b_answer={0: 1.0/6, 1: 1.0/4, 2: 1.0/4, 3:1.0/6} 32 | for n in sorted(G): 33 | assert_almost_equal(b[n],b_answer[n]) 34 | 35 | def test_star(self): 36 | """Closeness centrality: star """ 37 | G=networkx.Graph() 38 | G.add_star(['a','b','c','d']) 39 | b=networkx.current_flow_closeness_centrality(G) 40 | b_answer={'a': 1.0/3, 'b': 0.6/3, 'c': 0.6/3, 'd':0.6/3} 41 | for n in sorted(G): 42 | assert_almost_equal(b[n],b_answer[n]) 43 | 44 | 45 | 46 | class TestWeightedFlowClosenessCentrality(object): 47 | pass 48 | -------------------------------------------------------------------------------- /src/networkx/readwrite/tests/test_leda.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | import io,os,tempfile 5 | 6 | class TestLEDA(object): 7 | 8 | def test_parse_leda(self): 9 | data="""#header section \nLEDA.GRAPH \nstring\nint\n-1\n#nodes section\n5 \n|{v1}| \n|{v2}| \n|{v3}| \n|{v4}| \n|{v5}| \n\n#edges section\n7 \n1 2 0 |{4}| \n1 3 0 |{3}| \n2 3 0 |{2}| \n3 4 0 |{3}| \n3 5 0 |{7}| \n4 5 0 |{6}| \n5 1 0 |{foo}|""" 10 | G=nx.parse_leda(data) 11 | G=nx.parse_leda(data.split('\n')) 12 | assert_equal(sorted(G.nodes()), 13 | ['v1', 'v2', 'v3', 'v4', 'v5']) 14 | assert_equal([e for e in sorted(G.edges(data=True))], 15 | [('v1', 'v2', {'label': '4'}), 16 | ('v1', 'v3', {'label': '3'}), 17 | ('v2', 'v3', {'label': '2'}), 18 | ('v3', 'v4', {'label': '3'}), 19 | ('v3', 'v5', {'label': '7'}), 20 | ('v4', 'v5', {'label': '6'}), 21 | ('v5', 'v1', {'label': 'foo'})]) 22 | 23 | 24 | def test_read_LEDA(self): 25 | fh = io.BytesIO() 26 | data="""#header section \nLEDA.GRAPH \nstring\nint\n-1\n#nodes section\n5 \n|{v1}| \n|{v2}| \n|{v3}| \n|{v4}| \n|{v5}| \n\n#edges section\n7 \n1 2 0 |{4}| \n1 3 0 |{3}| \n2 3 0 |{2}| \n3 4 0 |{3}| \n3 5 0 |{7}| \n4 5 0 |{6}| \n5 1 0 |{foo}|""" 27 | G=nx.parse_leda(data) 28 | fh.write(data.encode('UTF-8')) 29 | fh.seek(0) 30 | Gin = nx.read_leda(fh) 31 | assert_equal(sorted(G.nodes()),sorted(Gin.nodes())) 32 | assert_equal(sorted(G.edges()),sorted(Gin.edges())) 33 | -------------------------------------------------------------------------------- /src/VRPModel.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Locker: 4 | def __init__(self, locker_id, pos): 5 | self.id = locker_id 6 | self.pos = pos 7 | self.orders = [] 8 | self.delivers = [] 9 | 10 | def __str__(self): 11 | return "[id:{}, pos:{}, delivers:{}]".format(self.id, self.pos, self.delivers) 12 | 13 | 14 | class Deliver: 15 | def __init__(self, deliver_id, pos, max_distance, max_capacity): 16 | self.id = deliver_id 17 | self.pos = pos 18 | self.locker_id = None 19 | self.max_distance = max_distance 20 | self.max_capacity = max_capacity 21 | 22 | def __str__(self): 23 | return "[id:{}, pos:{}, locker_id:{}, max_distance:{}, max_capacity:{}]".format(self.id, self.pos, self.locker_id, self.max_distance, self.max_capacity) 24 | 25 | def __repr__(self): 26 | return "{}".format(self.pos) 27 | 28 | def nearest_locker(self, lockers, nodes_mat): 29 | min_d = float('inf') 30 | for locker in lockers: 31 | if nodes_mat[locker.pos][self.pos] < min_d: 32 | self.locker_id = locker.id 33 | min_d = nodes_mat[locker.pos][self.pos] 34 | return self.locker_id 35 | 36 | class Package: 37 | def __init__(self, pos, capacity, deliver, index): 38 | self.pos = pos 39 | self.capacity = capacity 40 | self.deliver = deliver 41 | self.index = index 42 | 43 | def __str__(self): 44 | return "[pos:{}, capacity:{}, deliver:{}, index:{}]".format(self.pos, self.capacity, self.deliver, self.index) 45 | 46 | def __repr__(self): 47 | return "[pos:{}, capacity:{}, deliver:{}, index:{}]".format(self.pos, self.capacity, self.deliver, self.index) -------------------------------------------------------------------------------- /src/networkx/algorithms/assortativity/tests/base_test.py: -------------------------------------------------------------------------------- 1 | import networkx as nx 2 | 3 | class BaseTestAttributeMixing(object): 4 | 5 | def setUp(self): 6 | G=nx.Graph() 7 | G.add_nodes_from([0,1],fish='one') 8 | G.add_nodes_from([2,3],fish='two') 9 | G.add_nodes_from([4],fish='red') 10 | G.add_nodes_from([5],fish='blue') 11 | G.add_edges_from([(0,1),(2,3),(0,4),(2,5)]) 12 | self.G=G 13 | 14 | D=nx.DiGraph() 15 | D.add_nodes_from([0,1],fish='one') 16 | D.add_nodes_from([2,3],fish='two') 17 | D.add_nodes_from([4],fish='red') 18 | D.add_nodes_from([5],fish='blue') 19 | D.add_edges_from([(0,1),(2,3),(0,4),(2,5)]) 20 | self.D=D 21 | 22 | M=nx.MultiGraph() 23 | M.add_nodes_from([0,1],fish='one') 24 | M.add_nodes_from([2,3],fish='two') 25 | M.add_nodes_from([4],fish='red') 26 | M.add_nodes_from([5],fish='blue') 27 | M.add_edges_from([(0,1),(0,1),(2,3)]) 28 | self.M=M 29 | 30 | S=nx.Graph() 31 | S.add_nodes_from([0,1],fish='one') 32 | S.add_nodes_from([2,3],fish='two') 33 | S.add_nodes_from([4],fish='red') 34 | S.add_nodes_from([5],fish='blue') 35 | S.add_edge(0,0) 36 | S.add_edge(2,2) 37 | self.S=S 38 | 39 | class BaseTestDegreeMixing(object): 40 | 41 | def setUp(self): 42 | self.P4=nx.path_graph(4) 43 | self.D=nx.DiGraph() 44 | self.D.add_edges_from([(0, 2), (0, 3), (1, 3), (2, 3)]) 45 | self.M=nx.MultiGraph() 46 | self.M.add_path(list(range(4))) 47 | self.M.add_edge(0,1) 48 | self.S=nx.Graph() 49 | self.S.add_edges_from([(0,0),(1,1)]) 50 | 51 | -------------------------------------------------------------------------------- /src/networkx/drawing/tests/test_pydot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Unit tests for pydot drawing functions. 3 | """ 4 | import os 5 | import tempfile 6 | 7 | from nose import SkipTest 8 | from nose.tools import assert_true 9 | 10 | import networkx as nx 11 | from networkx.testing import assert_graphs_equal 12 | 13 | class TestPydot(object): 14 | @classmethod 15 | def setupClass(cls): 16 | global pydotplus 17 | try: 18 | import pydotplus 19 | except ImportError: 20 | raise SkipTest('pydotplus not available.') 21 | 22 | def pydot_checks(self, G): 23 | G.add_edge('A','B') 24 | G.add_edge('A','C') 25 | G.add_edge('B','C') 26 | G.add_edge('A','D') 27 | G.add_node('E') 28 | P = nx.nx_pydot.to_pydot(G) 29 | G2 = G.__class__(nx.nx_pydot.from_pydot(P)) 30 | assert_graphs_equal(G, G2) 31 | 32 | fname = tempfile.mktemp() 33 | assert_true( P.write_raw(fname) ) 34 | 35 | Pin = pydotplus.graph_from_dot_file(fname) 36 | 37 | n1 = sorted([p.get_name() for p in P.get_node_list()]) 38 | n2 = sorted([p.get_name() for p in Pin.get_node_list()]) 39 | assert_true( n1 == n2 ) 40 | 41 | e1=[(e.get_source(),e.get_destination()) for e in P.get_edge_list()] 42 | e2=[(e.get_source(),e.get_destination()) for e in Pin.get_edge_list()] 43 | assert_true( sorted(e1)==sorted(e2) ) 44 | 45 | Hin = nx.nx_pydot.read_dot(fname) 46 | Hin = G.__class__(Hin) 47 | assert_graphs_equal(G, Hin) 48 | 49 | # os.unlink(fname) 50 | 51 | 52 | def testUndirected(self): 53 | self.pydot_checks(nx.Graph()) 54 | 55 | def testDirected(self): 56 | self.pydot_checks(nx.DiGraph()) 57 | -------------------------------------------------------------------------------- /src/networkx/algorithms/components/semiconnected.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Semiconnectedness. 4 | """ 5 | 6 | __author__ = """ysitu """ 7 | # Copyright (C) 2014 ysitu 8 | # All rights reserved. 9 | # BSD license. 10 | 11 | import networkx as nx 12 | from networkx.utils import not_implemented_for 13 | 14 | __all__ = ['is_semiconnected'] 15 | 16 | @not_implemented_for('undirected') 17 | def is_semiconnected(G): 18 | """Return True if the graph is semiconnected, False otherwise. 19 | 20 | A graph is semiconnected if, and only if, for any pair of nodes, either one 21 | is reachable from the other, or they are mutually reachable. 22 | 23 | Parameters 24 | ---------- 25 | G : NetworkX graph 26 | A directed graph. 27 | 28 | Returns 29 | ------- 30 | semiconnected : bool 31 | True if the graph is semiconnected, False otherwise. 32 | 33 | Raises 34 | ------ 35 | NetworkXNotImplemented : 36 | If the input graph is not directed. 37 | 38 | NetworkXPointlessConcept : 39 | If the graph is empty. 40 | 41 | Examples 42 | -------- 43 | >>> G=nx.path_graph(4,create_using=nx.DiGraph()) 44 | >>> print(nx.is_semiconnected(G)) 45 | True 46 | >>> G=nx.DiGraph([(1, 2), (3, 2)]) 47 | >>> print(nx.is_semiconnected(G)) 48 | False 49 | 50 | See Also 51 | -------- 52 | is_strongly_connected, 53 | is_weakly_connected 54 | """ 55 | if len(G) == 0: 56 | raise nx.NetworkXPointlessConcept( 57 | 'Connectivity is undefined for the null graph.') 58 | 59 | if not nx.is_weakly_connected(G): 60 | return False 61 | 62 | G = nx.condensation(G) 63 | path = nx.topological_sort(G) 64 | return all(G.has_edge(u, v) for u, v in zip(path[:-1], path[1:])) 65 | -------------------------------------------------------------------------------- /src/networkx/algorithms/tests/test_distance_regular.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | 5 | class TestDistanceRegular: 6 | 7 | def test_is_distance_regular(self): 8 | assert_true(nx.is_distance_regular(nx.icosahedral_graph())) 9 | assert_true(nx.is_distance_regular(nx.petersen_graph())) 10 | assert_true(nx.is_distance_regular(nx.cubical_graph())) 11 | assert_true(nx.is_distance_regular(nx.complete_bipartite_graph(3,3))) 12 | assert_true(nx.is_distance_regular(nx.tetrahedral_graph())) 13 | assert_true(nx.is_distance_regular(nx.dodecahedral_graph())) 14 | assert_true(nx.is_distance_regular(nx.pappus_graph())) 15 | assert_true(nx.is_distance_regular(nx.heawood_graph())) 16 | assert_true(nx.is_distance_regular(nx.cycle_graph(3))) 17 | # no distance regular 18 | assert_false(nx.is_distance_regular(nx.path_graph(4))) 19 | 20 | def test_not_connected(self): 21 | G=nx.cycle_graph(4) 22 | G.add_cycle([5,6,7]) 23 | assert_false(nx.is_distance_regular(G)) 24 | 25 | 26 | def test_global_parameters(self): 27 | b,c=nx.intersection_array(nx.cycle_graph(5)) 28 | g=nx.global_parameters(b,c) 29 | assert_equal(list(g),[(0, 0, 2), (1, 0, 1), (1, 1, 0)]) 30 | b,c=nx.intersection_array(nx.cycle_graph(3)) 31 | g=nx.global_parameters(b,c) 32 | assert_equal(list(g),[(0, 0, 2), (1, 1, 0)]) 33 | 34 | 35 | def test_intersection_array(self): 36 | b,c=nx.intersection_array(nx.cycle_graph(5)) 37 | assert_equal(b,[2, 1]) 38 | assert_equal(c,[1, 1]) 39 | b,c=nx.intersection_array(nx.dodecahedral_graph()) 40 | assert_equal(b,[3, 2, 1, 1, 1]) 41 | assert_equal(c,[1, 1, 1, 2, 3]) 42 | b,c=nx.intersection_array(nx.icosahedral_graph()) 43 | assert_equal(b,[5, 2, 1]) 44 | assert_equal(c,[1, 2, 5]) 45 | -------------------------------------------------------------------------------- /data/eil51.graph: -------------------------------------------------------------------------------- 1 | NAME : eil51 2 | COMMENT : (Eilon et al.) 3 | TYPE : CVRP 4 | DIMENSION : 51 5 | EDGE_WEIGHT_TYPE : EUC_2D 6 | CAPACITY : 160 7 | NODE_COORD_SECTION 8 | 1 30 40 9 | 2 37 52 10 | 3 49 49 11 | 4 52 64 12 | 5 20 26 13 | 6 40 30 14 | 7 21 47 15 | 8 17 63 16 | 9 31 62 17 | 10 52 33 18 | 11 51 21 19 | 12 42 41 20 | 13 31 32 21 | 14 5 25 22 | 15 12 42 23 | 16 36 16 24 | 17 52 41 25 | 18 27 23 26 | 19 17 33 27 | 20 13 13 28 | 21 57 58 29 | 22 62 42 30 | 23 42 57 31 | 24 16 57 32 | 25 8 52 33 | 26 7 38 34 | 27 27 68 35 | 28 30 48 36 | 29 43 67 37 | 30 58 48 38 | 31 58 27 39 | 32 37 69 40 | 33 38 46 41 | 34 46 10 42 | 35 61 33 43 | 36 62 63 44 | 37 63 69 45 | 38 32 22 46 | 39 45 35 47 | 40 59 15 48 | 41 5 6 49 | 42 10 17 50 | 43 21 10 51 | 44 5 64 52 | 45 30 15 53 | 46 39 10 54 | 47 32 39 55 | 48 25 32 56 | 49 25 55 57 | 50 48 28 58 | 51 56 37 59 | LOCKER_SECTION : id, pos 60 | 1 10 61 | 2 20 62 | 3 30 63 | 4 40 64 | 5 50 65 | 6 7 66 | 7 26 67 | DELIVER_SECTION : id, pos, max_distance, max_capacity 68 | 1 3 100 100 69 | 2 6 100 100 70 | 3 9 100 100 71 | 4 12 100 100 72 | 5 15 100 100 73 | 6 18 100 100 74 | 7 21 100 100 75 | 8 24 100 100 76 | 9 27 100 100 77 | 10 30 100 100 78 | 11 33 100 100 79 | 12 36 100 100 80 | 13 39 100 100 81 | 14 42 100 100 82 | 15 45 100 100 83 | 16 48 100 100 84 | DEMAND_SECTION 85 | 1 5 86 | 2 7 87 | 3 30 88 | 4 16 89 | 5 9 90 | 6 21 91 | 7 15 92 | 8 19 93 | 9 23 94 | 10 11 95 | 11 5 96 | 12 19 97 | 13 29 98 | 14 23 99 | 15 21 100 | 16 10 101 | 17 15 102 | 18 3 103 | 19 41 104 | 20 9 105 | 21 28 106 | 22 8 107 | 23 8 108 | 24 16 109 | 25 10 110 | 26 28 111 | 27 7 112 | 28 15 113 | 29 14 114 | 30 6 115 | 31 19 116 | 32 11 117 | 33 12 118 | 34 23 119 | 35 26 120 | 36 17 121 | 37 6 122 | 38 9 123 | 39 15 124 | 40 14 125 | 41 7 126 | 42 27 127 | 43 13 128 | 44 11 129 | 45 16 130 | 46 10 131 | 47 5 132 | 48 25 133 | 49 17 134 | 50 18 135 | 51 10 136 | DEPOT_SECTION 137 | 1 138 | -1 139 | EOF 140 | -------------------------------------------------------------------------------- /src/networkx/algorithms/hierarchy.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Flow Hierarchy. 4 | """ 5 | # Copyright (C) 2004-2015 by 6 | # Aric Hagberg 7 | # Dan Schult 8 | # Pieter Swart 9 | # All rights reserved. 10 | # BSD license. 11 | import networkx as nx 12 | __authors__ = "\n".join(['Ben Edwards (bedwards@cs.unm.edu)']) 13 | __all__ = ['flow_hierarchy'] 14 | 15 | def flow_hierarchy(G, weight=None): 16 | """Returns the flow hierarchy of a directed network. 17 | 18 | Flow hierarchy is defined as the fraction of edges not participating 19 | in cycles in a directed graph [1]_. 20 | 21 | Parameters 22 | ---------- 23 | G : DiGraph or MultiDiGraph 24 | A directed graph 25 | 26 | weight : key,optional (default=None) 27 | Attribute to use for node weights. If None the weight defaults to 1. 28 | 29 | Returns 30 | ------- 31 | h : float 32 | Flow heirarchy value 33 | 34 | Notes 35 | ----- 36 | The algorithm described in [1]_ computes the flow hierarchy through 37 | exponentiation of the adjacency matrix. This function implements an 38 | alternative approach that finds strongly connected components. 39 | An edge is in a cycle if and only if it is in a strongly connected 40 | component, which can be found in `O(m)` time using Tarjan's algorithm. 41 | 42 | References 43 | ---------- 44 | .. [1] Luo, J.; Magee, C.L. (2011), 45 | Detecting evolving patterns of self-organizing networks by flow 46 | hierarchy measurement, Complexity, Volume 16 Issue 6 53-61. 47 | DOI: 10.1002/cplx.20368 48 | http://web.mit.edu/~cmagee/www/documents/28-DetectingEvolvingPatterns_FlowHierarchy.pdf 49 | """ 50 | if not G.is_directed(): 51 | raise nx.NetworkXError("G must be a digraph in flow_heirarchy") 52 | scc = nx.strongly_connected_components(G) 53 | return 1.-sum(G.subgraph(c).size(weight) for c in scc)/float(G.size(weight)) 54 | -------------------------------------------------------------------------------- /src/networkx/algorithms/isolate.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """ 3 | Functions for identifying isolate (degree zero) nodes. 4 | """ 5 | # Copyright (C) 2004-2015 by 6 | # Aric Hagberg 7 | # Dan Schult 8 | # Pieter Swart 9 | # All rights reserved. 10 | # BSD license. 11 | import networkx as nx 12 | __author__ = """\n""".join(['Drew Conway ', 13 | 'Aric Hagberg ']) 14 | __all__=['is_isolate','isolates'] 15 | 16 | def is_isolate(G,n): 17 | """Determine of node n is an isolate (degree zero). 18 | 19 | Parameters 20 | ---------- 21 | G : graph 22 | A networkx graph 23 | n : node 24 | A node in G 25 | 26 | Returns 27 | ------- 28 | isolate : bool 29 | True if n has no neighbors, False otherwise. 30 | 31 | Examples 32 | -------- 33 | >>> G=nx.Graph() 34 | >>> G.add_edge(1,2) 35 | >>> G.add_node(3) 36 | >>> nx.is_isolate(G,2) 37 | False 38 | >>> nx.is_isolate(G,3) 39 | True 40 | """ 41 | return G.degree(n)==0 42 | 43 | def isolates(G): 44 | """Return list of isolates in the graph. 45 | 46 | Isolates are nodes with no neighbors (degree zero). 47 | 48 | Parameters 49 | ---------- 50 | G : graph 51 | A networkx graph 52 | 53 | Returns 54 | ------- 55 | isolates : list 56 | List of isolate nodes. 57 | 58 | Examples 59 | -------- 60 | >>> G = nx.Graph() 61 | >>> G.add_edge(1,2) 62 | >>> G.add_node(3) 63 | >>> nx.isolates(G) 64 | [3] 65 | 66 | To remove all isolates in the graph use 67 | >>> G.remove_nodes_from(nx.isolates(G)) 68 | >>> G.nodes() 69 | [1, 2] 70 | 71 | For digraphs isolates have zero in-degree and zero out_degre 72 | >>> G = nx.DiGraph([(0,1),(1,2)]) 73 | >>> G.add_node(3) 74 | >>> nx.isolates(G) 75 | [3] 76 | """ 77 | return [n for (n,d) in G.degree_iter() if d==0] 78 | -------------------------------------------------------------------------------- /src/networkx/exception.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | ********** 4 | Exceptions 5 | ********** 6 | 7 | Base exceptions and errors for NetworkX. 8 | 9 | """ 10 | __author__ = """Aric Hagberg (hagberg@lanl.gov)\nPieter Swart (swart@lanl.gov)\nDan Schult(dschult@colgate.edu)\nLoïc Séguin-C. """ 11 | # Copyright (C) 2004-2015 by 12 | # Aric Hagberg 13 | # Dan Schult 14 | # Pieter Swart 15 | # All rights reserved. 16 | # BSD license. 17 | # 18 | 19 | # Exception handling 20 | 21 | # the root of all Exceptions 22 | class NetworkXException(Exception): 23 | """Base class for exceptions in NetworkX.""" 24 | 25 | class NetworkXError(NetworkXException): 26 | """Exception for a serious error in NetworkX""" 27 | 28 | class NetworkXPointlessConcept(NetworkXException): 29 | """Harary, F. and Read, R. "Is the Null Graph a Pointless Concept?" 30 | In Graphs and Combinatorics Conference, George Washington University. 31 | New York: Springer-Verlag, 1973. 32 | """ 33 | 34 | class NetworkXAlgorithmError(NetworkXException): 35 | """Exception for unexpected termination of algorithms.""" 36 | 37 | class NetworkXUnfeasible(NetworkXAlgorithmError): 38 | """Exception raised by algorithms trying to solve a problem 39 | instance that has no feasible solution.""" 40 | 41 | class NetworkXNoPath(NetworkXUnfeasible): 42 | """Exception for algorithms that should return a path when running 43 | on graphs where such a path does not exist.""" 44 | 45 | class NetworkXNoCycle(NetworkXUnfeasible): 46 | """Exception for algorithms that should return a cycle when running 47 | on graphs where such a cycle does not exist.""" 48 | 49 | class NetworkXUnbounded(NetworkXAlgorithmError): 50 | """Exception raised by algorithms trying to solve a maximization 51 | or a minimization problem instance that is unbounded.""" 52 | 53 | class NetworkXNotImplemented(NetworkXException): 54 | """Exception raised by algorithms not implemented for a type of graph.""" 55 | -------------------------------------------------------------------------------- /src/networkx/algorithms/operators/unary.py: -------------------------------------------------------------------------------- 1 | """Unary operations on graphs""" 2 | # Copyright (C) 2004-2015 by 3 | # Aric Hagberg 4 | # Dan Schult 5 | # Pieter Swart 6 | # All rights reserved. 7 | # BSD license. 8 | import networkx as nx 9 | __author__ = """\n""".join(['Aric Hagberg ', 10 | 'Pieter Swart (swart@lanl.gov)', 11 | 'Dan Schult(dschult@colgate.edu)']) 12 | __all__ = ['complement', 'reverse'] 13 | 14 | 15 | def complement(G, name=None): 16 | """Return the graph complement of G. 17 | 18 | Parameters 19 | ---------- 20 | G : graph 21 | A NetworkX graph 22 | 23 | name : string 24 | Specify name for new graph 25 | 26 | Returns 27 | ------- 28 | GC : A new graph. 29 | 30 | Notes 31 | ------ 32 | Note that complement() does not create self-loops and also 33 | does not produce parallel edges for MultiGraphs. 34 | 35 | Graph, node, and edge data are not propagated to the new graph. 36 | """ 37 | if name is None: 38 | name = "complement(%s)" % (G.name) 39 | R = G.__class__() 40 | R.name = name 41 | R.add_nodes_from(G) 42 | R.add_edges_from(((n, n2) 43 | for n, nbrs in G.adjacency_iter() 44 | for n2 in G if n2 not in nbrs 45 | if n != n2)) 46 | return R 47 | 48 | 49 | def reverse(G, copy=True): 50 | """Return the reverse directed graph of G. 51 | 52 | Parameters 53 | ---------- 54 | G : directed graph 55 | A NetworkX directed graph 56 | copy : bool 57 | If True, then a new graph is returned. If False, then the graph is 58 | reversed in place. 59 | 60 | Returns 61 | ------- 62 | H : directed graph 63 | The reversed G. 64 | 65 | """ 66 | if not G.is_directed(): 67 | raise nx.NetworkXError("Cannot reverse an undirected graph.") 68 | else: 69 | return G.reverse(copy=copy) 70 | -------------------------------------------------------------------------------- /src/networkx/readwrite/json_graph/tests/test_adjacency.py: -------------------------------------------------------------------------------- 1 | import json 2 | from nose.tools import assert_equal, assert_raises, assert_not_equal, assert_true, raises 3 | import networkx as nx 4 | from networkx.readwrite.json_graph import * 5 | 6 | class TestAdjacency: 7 | 8 | def test_graph(self): 9 | G = nx.path_graph(4) 10 | H = adjacency_graph(adjacency_data(G)) 11 | nx.is_isomorphic(G,H) 12 | 13 | def test_graph_attributes(self): 14 | G = nx.path_graph(4) 15 | G.add_node(1,color='red') 16 | G.add_edge(1,2,width=7) 17 | G.graph['foo']='bar' 18 | G.graph[1]='one' 19 | 20 | H = adjacency_graph(adjacency_data(G)) 21 | assert_equal(H.graph['foo'],'bar') 22 | assert_equal(H.node[1]['color'],'red') 23 | assert_equal(H[1][2]['width'],7) 24 | 25 | d = json.dumps(adjacency_data(G)) 26 | H = adjacency_graph(json.loads(d)) 27 | assert_equal(H.graph['foo'],'bar') 28 | assert_equal(H.graph[1],'one') 29 | assert_equal(H.node[1]['color'],'red') 30 | assert_equal(H[1][2]['width'],7) 31 | 32 | def test_digraph(self): 33 | G = nx.DiGraph() 34 | G.add_path([1,2,3]) 35 | H = adjacency_graph(adjacency_data(G)) 36 | assert_true(H.is_directed()) 37 | nx.is_isomorphic(G,H) 38 | 39 | def test_multidigraph(self): 40 | G = nx.MultiDiGraph() 41 | G.add_path([1,2,3]) 42 | H = adjacency_graph(adjacency_data(G)) 43 | assert_true(H.is_directed()) 44 | assert_true(H.is_multigraph()) 45 | 46 | def test_multigraph(self): 47 | G = nx.MultiGraph() 48 | G.add_edge(1,2,key='first') 49 | G.add_edge(1,2,key='second',color='blue') 50 | H = adjacency_graph(adjacency_data(G)) 51 | nx.is_isomorphic(G,H) 52 | assert_equal(H[1][2]['second']['color'],'blue') 53 | 54 | @raises(nx.NetworkXError) 55 | def test_exception(self): 56 | G = nx.MultiDiGraph() 57 | attrs = dict(id='node', key='node') 58 | adjacency_data(G, attrs) 59 | -------------------------------------------------------------------------------- /src/networkx/generators/tests/test_nonisomorphic_trees.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | ==================== 4 | Generators - Non Isomorphic Trees 5 | ==================== 6 | 7 | Unit tests for WROM algorithm generator in generators/nonisomorphic_trees.py 8 | """ 9 | from nose.tools import * 10 | from networkx import * 11 | 12 | 13 | class TestGeneratorNonIsomorphicTrees(): 14 | 15 | def test_tree_structure(self): 16 | # test for tree structure for nx.nonisomorphic_trees() 17 | f = lambda x: list(nx.nonisomorphic_trees(x)) 18 | for i in f(6): 19 | assert_true(nx.is_tree(i)) 20 | for i in f(8): 21 | assert_true(nx.is_tree(i)) 22 | 23 | def test_nonisomorphism(self): 24 | # test for nonisomorphism of trees for nx.nonisomorphic_trees() 25 | f = lambda x: list(nx.nonisomorphic_trees(x)) 26 | trees = f(6) 27 | for i in range(len(trees)): 28 | for j in range(i + 1, len(trees)): 29 | assert_false(nx.is_isomorphic(trees[i], trees[j])) 30 | trees = f(8) 31 | for i in range(len(trees)): 32 | for j in range(i + 1, len(trees)): 33 | assert_false(nx.is_isomorphic(trees[i], trees[j])) 34 | 35 | def test_number_of_nonisomorphic_trees(self): 36 | # http://oeis.org/A000055 37 | assert_equal(nx.number_of_nonisomorphic_trees(2), 1) 38 | assert_equal(nx.number_of_nonisomorphic_trees(3), 1) 39 | assert_equal(nx.number_of_nonisomorphic_trees(4), 2) 40 | assert_equal(nx.number_of_nonisomorphic_trees(5), 3) 41 | assert_equal(nx.number_of_nonisomorphic_trees(6), 6) 42 | assert_equal(nx.number_of_nonisomorphic_trees(7), 11) 43 | assert_equal(nx.number_of_nonisomorphic_trees(8), 23) 44 | 45 | def test_nonisomorphic_trees(self): 46 | f = lambda x: list(nx.nonisomorphic_trees(x)) 47 | assert_equal(sorted(f(3)[0].edges()), [(0, 1), (0, 2)]) 48 | assert_equal(sorted(f(4)[0].edges()), [(0, 1), (0, 3), (1, 2)]) 49 | assert_equal(sorted(f(4)[1].edges()), [(0, 1), (0, 2), (0, 3)]) 50 | -------------------------------------------------------------------------------- /src/vrpmain.py: -------------------------------------------------------------------------------- 1 | from TsplibParser import parser as tspparser 2 | from ArgParser import parser as argparser 3 | from VRPCenter import VRPCenter 4 | from TspPainter import tspPainter 5 | import logging 6 | 7 | # construct the logger 8 | logger = logging.getLogger("logger") 9 | logger.setLevel(logging.INFO) 10 | logFormatter = logging.Formatter("%(asctime)s [%(threadName)s] [%(levelname)s] %(message)s") 11 | consoleHandler = logging.StreamHandler() 12 | consoleHandler.setFormatter(logFormatter) 13 | logger.addHandler(consoleHandler) 14 | 15 | def run(tspparser): 16 | center = VRPCenter(tspparser) 17 | logger.info("Nodes: ") 18 | for i in range(1, len(tspparser.cities_coord)): 19 | logger.info("Node " + str(i) + " coordinate is " + str(tspparser.cities_coord[i][0]) + ", " + str(tspparser.cities_coord[i][1])) 20 | tspPainter.coord_mat = tspparser.cities_coord 21 | tspPainter.drawMap() 22 | 23 | logger.info("Lockers: ") 24 | for i in range(0, len(tspparser.lockers)): 25 | logger.info(tspparser.lockers[i]) 26 | tspPainter.drawLockers(tspparser.lockers) 27 | 28 | logger.info("Delivers: ") 29 | for i in range(0, len(tspparser.delivers)): 30 | logger.info(tspparser.delivers[i]) 31 | logger.info("Demands: ") 32 | demands = 0 33 | for i in range(0, len(tspparser.demands)): 34 | demands += tspparser.demands[i] 35 | logger.info("Node {} {}".format(i, tspparser.demands[i])) 36 | logger.info("Total demands is: {}".format(demands)) 37 | 38 | center.start() 39 | raw_input("Press Enter to quit...") 40 | 41 | def main(): 42 | args = argparser.parse_args() 43 | tspparser.read_file(args.tsp_file[0]) 44 | 45 | logger.info("-------------------------------------------") 46 | logger.info("Problem formulation information") 47 | logger.info("-------------------------------------------") 48 | logger.info("Name: " + tspparser.name) 49 | logger.info("Comment: " + tspparser.comment) 50 | logger.info("Type: " + tspparser.type) 51 | # run vrp center 52 | run(tspparser) 53 | 54 | if __name__ == "__main__": 55 | main() -------------------------------------------------------------------------------- /src/networkx/algorithms/components/tests/test_semiconnected.py: -------------------------------------------------------------------------------- 1 | from itertools import chain 2 | import networkx as nx 3 | from nose.tools import * 4 | 5 | class TestIsSemiconnected(object): 6 | 7 | def test_undirected(self): 8 | assert_raises(nx.NetworkXNotImplemented, nx.is_semiconnected, 9 | nx.Graph()) 10 | assert_raises(nx.NetworkXNotImplemented, nx.is_semiconnected, 11 | nx.MultiGraph()) 12 | 13 | def test_empty(self): 14 | assert_raises(nx.NetworkXPointlessConcept, nx.is_semiconnected, 15 | nx.DiGraph()) 16 | assert_raises(nx.NetworkXPointlessConcept, nx.is_semiconnected, 17 | nx.MultiDiGraph()) 18 | 19 | def test_single_node_graph(self): 20 | G = nx.DiGraph() 21 | G.add_node(0) 22 | ok_(nx.is_semiconnected(G)) 23 | 24 | def test_path(self): 25 | G = nx.path_graph(100, create_using=nx.DiGraph()) 26 | ok_(nx.is_semiconnected(G)) 27 | G.add_edge(100, 99) 28 | ok_(not nx.is_semiconnected(G)) 29 | 30 | def test_cycle(self): 31 | G = nx.cycle_graph(100, create_using=nx.DiGraph()) 32 | ok_(nx.is_semiconnected(G)) 33 | G = nx.path_graph(100, create_using=nx.DiGraph()) 34 | G.add_edge(0, 99) 35 | ok_(nx.is_semiconnected(G)) 36 | 37 | def test_tree(self): 38 | G = nx.DiGraph() 39 | G.add_edges_from(chain.from_iterable([(i, 2 * i + 1), (i, 2 * i + 2)] 40 | for i in range(100))) 41 | ok_(not nx.is_semiconnected(G)) 42 | 43 | def test_dumbbell(self): 44 | G = nx.cycle_graph(100, create_using=nx.DiGraph()) 45 | G.add_edges_from((i + 100, (i + 1) % 100 + 100) for i in range(100)) 46 | ok_(not nx.is_semiconnected(G)) # G is disconnected. 47 | G.add_edge(100, 99) 48 | ok_(nx.is_semiconnected(G)) 49 | 50 | def test_alternating_path(self): 51 | G = nx.DiGraph(chain.from_iterable([(i, i - 1), (i, i + 1)] 52 | for i in range(0, 100, 2))) 53 | ok_(not nx.is_semiconnected(G)) 54 | -------------------------------------------------------------------------------- /src/networkx/testing/utils.py: -------------------------------------------------------------------------------- 1 | import operator 2 | from nose.tools import * 3 | __all__ = ['assert_nodes_equal', 'assert_edges_equal','assert_graphs_equal'] 4 | 5 | def assert_nodes_equal(nlist1, nlist2): 6 | # Assumes lists are either nodes, or (node,datadict) tuples, 7 | # and also that nodes are orderable/sortable. 8 | try: 9 | n1 = sorted(nlist1,key=operator.itemgetter(0)) 10 | n2 = sorted(nlist2,key=operator.itemgetter(0)) 11 | assert_equal(len(n1),len(n2)) 12 | for a,b in zip(n1,n2): 13 | assert_equal(a,b) 14 | except TypeError: 15 | assert_equal(set(nlist1),set(nlist2)) 16 | return 17 | 18 | def assert_edges_equal(elist1, elist2): 19 | # Assumes lists with u,v nodes either as 20 | # edge tuples (u,v) 21 | # edge tuples with data dicts (u,v,d) 22 | # edge tuples with keys and data dicts (u,v,k, d) 23 | # and also that nodes are orderable/sortable. 24 | e1 = sorted(elist1,key=lambda x: sorted(x[0:2])) 25 | e2 = sorted(elist2,key=lambda x: sorted(x[0:2])) 26 | assert_equal(len(e1),len(e2)) 27 | if len(e1) == 0: 28 | return True 29 | if len(e1[0]) == 2: 30 | for a,b in zip(e1,e2): 31 | assert_equal(set(a[0:2]),set(b[0:2])) 32 | elif len(e1[0]) == 3: 33 | for a,b in zip(e1,e2): 34 | assert_equal(set(a[0:2]),set(b[0:2])) 35 | assert_equal(a[2],b[2]) 36 | elif len(e1[0]) == 4: 37 | for a,b in zip(e1,e2): 38 | assert_equal(set(a[0:2]),set(b[0:2])) 39 | assert_equal(a[2],b[2]) 40 | assert_equal(a[3],b[3]) 41 | 42 | 43 | def assert_graphs_equal(graph1, graph2): 44 | if graph1.is_multigraph(): 45 | edges1 = graph1.edges(data=True,keys=True) 46 | else: 47 | edges1 = graph1.edges(data=True) 48 | if graph2.is_multigraph(): 49 | edges2 = graph2.edges(data=True,keys=True) 50 | else: 51 | edges2 = graph2.edges(data=True) 52 | assert_nodes_equal(graph1.nodes(data=True), 53 | graph2.nodes(data=True)) 54 | assert_edges_equal(edges1, edges2) 55 | assert_equal(graph1.graph,graph2.graph) 56 | return 57 | -------------------------------------------------------------------------------- /src/networkx/generators/tests/test_atlas.py: -------------------------------------------------------------------------------- 1 | from nose.tools import * 2 | from nose import SkipTest 3 | 4 | class TestAtlas(object): 5 | @classmethod 6 | def setupClass(cls): 7 | global atlas 8 | import platform 9 | if platform.python_implementation()=='Jython': 10 | raise SkipTest('graph atlas not available under Jython.') 11 | import networkx.generators.atlas as atlas 12 | 13 | def setUp(self): 14 | self.GAG=atlas.graph_atlas_g() 15 | 16 | def test_sizes(self): 17 | G=self.GAG[0] 18 | assert_equal(G.number_of_nodes(),0) 19 | assert_equal(G.number_of_edges(),0) 20 | 21 | G=self.GAG[7] 22 | assert_equal(G.number_of_nodes(),3) 23 | assert_equal(G.number_of_edges(),3) 24 | 25 | def test_names(self): 26 | i=0 27 | for g in self.GAG: 28 | name=g.name 29 | assert_equal(int(name[1:]),i) 30 | i+=1 31 | 32 | def test_monotone_nodes(self): 33 | # check for monotone increasing number of nodes 34 | previous=self.GAG[0] 35 | for g in self.GAG: 36 | assert_false(len(g)-len(previous) > 1) 37 | previous=g.copy() 38 | 39 | def test_monotone_nodes(self): 40 | # check for monotone increasing number of edges 41 | # (for fixed number of nodes) 42 | previous=self.GAG[0] 43 | for g in self.GAG: 44 | if len(g)==len(previous): 45 | assert_false(g.size()-previous.size() > 1) 46 | previous=g.copy() 47 | 48 | def test_monotone_degree_sequence(self): 49 | # check for monotone increasing degree sequence 50 | # (for fixed number f nodes and edges) 51 | # note that 111223 < 112222 52 | previous=self.GAG[0] 53 | for g in self.GAG: 54 | if len(g)==0: 55 | continue 56 | if len(g)==len(previous) & g.size()==previous.size(): 57 | deg_seq=sorted(g.degree().values()) 58 | previous_deg_seq=sorted(previous.degree().values()) 59 | assert_true(previous_deg_seq < deg_seq) 60 | previous=g.copy() 61 | 62 | 63 | -------------------------------------------------------------------------------- /src/networkx/linalg/tests/test_spectrum.py: -------------------------------------------------------------------------------- 1 | from nose import SkipTest 2 | 3 | import networkx as nx 4 | from networkx.generators.degree_seq import havel_hakimi_graph 5 | 6 | class TestSpectrum(object): 7 | numpy=1 # nosetests attribute, use nosetests -a 'not numpy' to skip test 8 | @classmethod 9 | def setupClass(cls): 10 | global numpy 11 | global assert_equal 12 | global assert_almost_equal 13 | try: 14 | import numpy 15 | import scipy 16 | from numpy.testing import assert_equal,assert_almost_equal 17 | except ImportError: 18 | raise SkipTest('SciPy not available.') 19 | 20 | def setUp(self): 21 | deg=[3,2,2,1,0] 22 | self.G=havel_hakimi_graph(deg) 23 | self.P=nx.path_graph(3) 24 | self.WG=nx.Graph( (u,v,{'weight':0.5,'other':0.3}) 25 | for (u,v) in self.G.edges_iter() ) 26 | self.WG.add_node(4) 27 | self.DG=nx.DiGraph() 28 | self.DG.add_path([0,1,2]) 29 | 30 | def test_laplacian_spectrum(self): 31 | "Laplacian eigenvalues" 32 | evals=numpy.array([0, 0, 1, 3, 4]) 33 | e=sorted(nx.laplacian_spectrum(self.G)) 34 | assert_almost_equal(e,evals) 35 | e=sorted(nx.laplacian_spectrum(self.WG,weight=None)) 36 | assert_almost_equal(e,evals) 37 | e=sorted(nx.laplacian_spectrum(self.WG)) 38 | assert_almost_equal(e,0.5*evals) 39 | e=sorted(nx.laplacian_spectrum(self.WG,weight='other')) 40 | assert_almost_equal(e,0.3*evals) 41 | 42 | def test_adjacency_spectrum(self): 43 | "Adjacency eigenvalues" 44 | evals=numpy.array([-numpy.sqrt(2), 0, numpy.sqrt(2)]) 45 | e=sorted(nx.adjacency_spectrum(self.P)) 46 | assert_almost_equal(e,evals) 47 | 48 | def test_modularity_spectrum(self): 49 | "Modularity eigenvalues" 50 | evals=numpy.array([-1.5, 0., 0.]) 51 | e=sorted(nx.modularity_spectrum(self.P)) 52 | assert_almost_equal(e,evals) 53 | # Directed modularity eigenvalues 54 | evals=numpy.array([-0.5, 0., 0.]) 55 | e=sorted(nx.modularity_spectrum(self.DG)) 56 | assert_almost_equal(e,evals) 57 | 58 | 59 | -------------------------------------------------------------------------------- /src/networkx/algorithms/components/tests/test_attracting.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | from networkx import NetworkXNotImplemented 5 | 6 | 7 | class TestAttractingComponents(object): 8 | def setUp(self): 9 | self.G1 = nx.DiGraph() 10 | self.G1.add_edges_from([(5, 11), (11, 2), (11, 9), (11, 10), 11 | (7, 11), (7, 8), (8, 9), (3, 8), (3, 10)]) 12 | self.G2 = nx.DiGraph() 13 | self.G2.add_edges_from([(0, 1), (0, 2), (1, 1), (1, 2), (2, 1)]) 14 | 15 | self.G3 = nx.DiGraph() 16 | self.G3.add_edges_from([(0, 1), (1, 2), (2, 1), (0, 3), (3, 4), (4, 3)]) 17 | 18 | def test_attracting_components(self): 19 | ac = list(nx.attracting_components(self.G1)) 20 | assert_true({2} in ac) 21 | assert_true({9} in ac) 22 | assert_true({10} in ac) 23 | 24 | ac = list(nx.attracting_components(self.G2)) 25 | ac = [tuple(sorted(x)) for x in ac] 26 | assert_true(ac == [(1, 2)]) 27 | 28 | ac = list(nx.attracting_components(self.G3)) 29 | ac = [tuple(sorted(x)) for x in ac] 30 | assert_true((1, 2) in ac) 31 | assert_true((3, 4) in ac) 32 | assert_equal(len(ac), 2) 33 | 34 | def test_number_attacting_components(self): 35 | assert_equal(nx.number_attracting_components(self.G1), 3) 36 | assert_equal(nx.number_attracting_components(self.G2), 1) 37 | assert_equal(nx.number_attracting_components(self.G3), 2) 38 | 39 | def test_is_attracting_component(self): 40 | assert_false(nx.is_attracting_component(self.G1)) 41 | assert_false(nx.is_attracting_component(self.G2)) 42 | assert_false(nx.is_attracting_component(self.G3)) 43 | g2 = self.G3.subgraph([1, 2]) 44 | assert_true(nx.is_attracting_component(g2)) 45 | 46 | def test_connected_raise(self): 47 | G=nx.Graph() 48 | assert_raises(NetworkXNotImplemented, nx.attracting_components, G) 49 | assert_raises(NetworkXNotImplemented, nx.number_attracting_components, G) 50 | assert_raises(NetworkXNotImplemented, nx.is_attracting_component, G) 51 | assert_raises(NetworkXNotImplemented, nx.attracting_component_subgraphs, G) 52 | -------------------------------------------------------------------------------- /src/networkx/readwrite/json_graph/tests/test_node_link.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import json 3 | from nose.tools import assert_equal, assert_raises, assert_not_equal, assert_true, raises 4 | import networkx as nx 5 | from networkx.readwrite.json_graph import * 6 | 7 | class TestNodeLink: 8 | 9 | def test_graph(self): 10 | G = nx.path_graph(4) 11 | H = node_link_graph(node_link_data(G)) 12 | nx.is_isomorphic(G,H) 13 | 14 | def test_graph_attributes(self): 15 | G = nx.path_graph(4) 16 | G.add_node(1,color='red') 17 | G.add_edge(1,2,width=7) 18 | G.graph[1]='one' 19 | G.graph['foo']='bar' 20 | 21 | H = node_link_graph(node_link_data(G)) 22 | assert_equal(H.graph['foo'],'bar') 23 | assert_equal(H.node[1]['color'],'red') 24 | assert_equal(H[1][2]['width'],7) 25 | 26 | d = json.dumps(node_link_data(G)) 27 | H = node_link_graph(json.loads(d)) 28 | assert_equal(H.graph['foo'],'bar') 29 | assert_equal(H.graph['1'],'one') 30 | assert_equal(H.node[1]['color'],'red') 31 | assert_equal(H[1][2]['width'],7) 32 | 33 | def test_digraph(self): 34 | G = nx.DiGraph() 35 | H = node_link_graph(node_link_data(G)) 36 | assert_true(H.is_directed()) 37 | 38 | 39 | def test_multigraph(self): 40 | G = nx.MultiGraph() 41 | G.add_edge(1,2,key='first') 42 | G.add_edge(1,2,key='second',color='blue') 43 | H = node_link_graph(node_link_data(G)) 44 | nx.is_isomorphic(G,H) 45 | assert_equal(H[1][2]['second']['color'],'blue') 46 | 47 | def test_unicode_keys(self): 48 | try: 49 | q = unicode("qualité",'utf-8') 50 | except NameError: 51 | q = "qualité" 52 | G = nx.Graph() 53 | G.add_node(1, {q:q}) 54 | s = node_link_data(G) 55 | output = json.dumps(s, ensure_ascii=False) 56 | data = json.loads(output) 57 | H = node_link_graph(data) 58 | assert_equal(H.node[1][q], q) 59 | 60 | @raises(nx.NetworkXError) 61 | def test_exception(self): 62 | G = nx.MultiDiGraph() 63 | attrs = dict(id='id', source='node', target='node', key='node') 64 | node_link_data(G, attrs) 65 | -------------------------------------------------------------------------------- /src/networkx/algorithms/approximation/clustering_coefficient.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2013 by 3 | # Fred Morstatter 4 | # Jordi Torrents 5 | # All rights reserved. 6 | # BSD license. 7 | import random 8 | from networkx.utils import not_implemented_for 9 | 10 | __all__ = ['average_clustering'] 11 | __author__ = """\n""".join(['Fred Morstatter ', 12 | 'Jordi Torrents ']) 13 | 14 | @not_implemented_for('directed') 15 | def average_clustering(G, trials=1000): 16 | r"""Estimates the average clustering coefficient of G. 17 | 18 | The local clustering of each node in `G` is the fraction of triangles 19 | that actually exist over all possible triangles in its neighborhood. 20 | The average clustering coefficient of a graph `G` is the mean of 21 | local clusterings. 22 | 23 | This function finds an approximate average clustering coefficient 24 | for G by repeating `n` times (defined in `trials`) the following 25 | experiment: choose a node at random, choose two of its neighbors 26 | at random, and check if they are connected. The approximate 27 | coefficient is the fraction of triangles found over the number 28 | of trials [1]_. 29 | 30 | Parameters 31 | ---------- 32 | G : NetworkX graph 33 | 34 | trials : integer 35 | Number of trials to perform (default 1000). 36 | 37 | Returns 38 | ------- 39 | c : float 40 | Approximated average clustering coefficient. 41 | 42 | References 43 | ---------- 44 | .. [1] Schank, Thomas, and Dorothea Wagner. Approximating clustering 45 | coefficient and transitivity. Universität Karlsruhe, Fakultät für 46 | Informatik, 2004. 47 | http://www.emis.ams.org/journals/JGAA/accepted/2005/SchankWagner2005.9.2.pdf 48 | 49 | """ 50 | n = len(G) 51 | triangles = 0 52 | nodes = G.nodes() 53 | for i in [int(random.random() * n) for i in range(trials)]: 54 | nbrs = list(G[nodes[i]]) 55 | if len(nbrs) < 2: 56 | continue 57 | u, v = random.sample(nbrs, 2) 58 | if u in G[v]: 59 | triangles += 1 60 | return triangles / float(trials) 61 | -------------------------------------------------------------------------------- /src/networkx/drawing/tests/test_agraph.py: -------------------------------------------------------------------------------- 1 | """Unit tests for PyGraphviz intefaace. 2 | """ 3 | import os 4 | import tempfile 5 | 6 | from nose import SkipTest 7 | from nose.tools import assert_true,assert_equal 8 | from networkx.testing import assert_edges_equal, assert_nodes_equal 9 | 10 | import networkx as nx 11 | 12 | class TestAGraph(object): 13 | @classmethod 14 | def setupClass(cls): 15 | global pygraphviz 16 | try: 17 | import pygraphviz 18 | except ImportError: 19 | raise SkipTest('PyGraphviz not available.') 20 | 21 | def build_graph(self, G): 22 | G.add_edge('A','B') 23 | G.add_edge('A','C') 24 | G.add_edge('A','C') 25 | G.add_edge('B','C') 26 | G.add_edge('A','D') 27 | G.add_node('E') 28 | return G 29 | 30 | def assert_equal(self, G1, G2): 31 | assert_nodes_equal(G1.nodes(),G2.nodes()) 32 | assert_edges_equal(G1.edges(),G2.edges()) 33 | 34 | 35 | def agraph_checks(self, G): 36 | G = self.build_graph(G) 37 | A = nx.nx_agraph.to_agraph(G) 38 | H = nx.nx_agraph.from_agraph(A) 39 | self.assert_equal(G, H) 40 | 41 | fname=tempfile.mktemp() 42 | nx.drawing.nx_agraph.write_dot(H,fname) 43 | Hin = nx.nx_agraph.read_dot(fname) 44 | os.unlink(fname) 45 | self.assert_equal(H,Hin) 46 | 47 | 48 | (fd,fname)=tempfile.mkstemp() 49 | fh=open(fname,'w') 50 | nx.drawing.nx_agraph.write_dot(H,fh) 51 | fh.close() 52 | 53 | fh=open(fname,'r') 54 | Hin = nx.nx_agraph.read_dot(fh) 55 | fh.close() 56 | os.unlink(fname) 57 | self.assert_equal(H,Hin) 58 | 59 | def test_from_agraph_name(self): 60 | G = nx.Graph(name='test') 61 | A = nx.nx_agraph.to_agraph(G) 62 | H = nx.nx_agraph.from_agraph(A) 63 | assert_equal(G.name,'test') 64 | 65 | 66 | def testUndirected(self): 67 | self.agraph_checks(nx.Graph()) 68 | 69 | def testDirected(self): 70 | self.agraph_checks(nx.DiGraph()) 71 | 72 | def testMultiUndirected(self): 73 | self.agraph_checks(nx.MultiGraph()) 74 | 75 | def testMultiDirected(self): 76 | self.agraph_checks(nx.MultiDiGraph()) 77 | -------------------------------------------------------------------------------- /src/networkx/algorithms/approximation/independent_set.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Independent Set 4 | 5 | Independent set or stable set is a set of vertices in a graph, no two of 6 | which are adjacent. That is, it is a set I of vertices such that for every 7 | two vertices in I, there is no edge connecting the two. Equivalently, each 8 | edge in the graph has at most one endpoint in I. The size of an independent 9 | set is the number of vertices it contains. 10 | 11 | A maximum independent set is a largest independent set for a given graph G 12 | and its size is denoted α(G). The problem of finding such a set is called 13 | the maximum independent set problem and is an NP-hard optimization problem. 14 | As such, it is unlikely that there exists an efficient algorithm for finding 15 | a maximum independent set of a graph. 16 | 17 | http://en.wikipedia.org/wiki/Independent_set_(graph_theory) 18 | 19 | Independent set algorithm is based on the following paper: 20 | 21 | `O(|V|/(log|V|)^2)` apx of maximum clique/independent set. 22 | 23 | Boppana, R., & Halldórsson, M. M. (1992). 24 | Approximating maximum independent sets by excluding subgraphs. 25 | BIT Numerical Mathematics, 32(2), 180–196. Springer. 26 | doi:10.1007/BF01994876 27 | 28 | """ 29 | # Copyright (C) 2011-2012 by 30 | # Nicholas Mancuso 31 | # All rights reserved. 32 | # BSD license. 33 | from networkx.algorithms.approximation import clique_removal 34 | __all__ = ["maximum_independent_set"] 35 | __author__ = """Nicholas Mancuso (nick.mancuso@gmail.com)""" 36 | 37 | 38 | def maximum_independent_set(G): 39 | """Return an approximate maximum independent set. 40 | 41 | Parameters 42 | ---------- 43 | G : NetworkX graph 44 | Undirected graph 45 | 46 | Returns 47 | ------- 48 | iset : Set 49 | The apx-maximum independent set 50 | 51 | Notes 52 | ----- 53 | Finds the `O(|V|/(log|V|)^2)` apx of independent set in the worst case. 54 | 55 | 56 | References 57 | ---------- 58 | .. [1] Boppana, R., & Halldórsson, M. M. (1992). 59 | Approximating maximum independent sets by excluding subgraphs. 60 | BIT Numerical Mathematics, 32(2), 180–196. Springer. 61 | """ 62 | iset, _ = clique_removal(G) 63 | return iset 64 | -------------------------------------------------------------------------------- /src/networkx/generators/stochastic.py: -------------------------------------------------------------------------------- 1 | """Functions for generating stochastic graphs from a given weighted directed 2 | graph. 3 | 4 | """ 5 | # Copyright (C) 2010-2013 by 6 | # Aric Hagberg 7 | # Dan Schult 8 | # Pieter Swart 9 | # All rights reserved. 10 | # BSD license. 11 | from __future__ import division 12 | import warnings 13 | 14 | import networkx as nx 15 | from networkx.utils import not_implemented_for 16 | 17 | __author__ = "Aric Hagberg " 18 | __all__ = ['stochastic_graph'] 19 | 20 | 21 | @not_implemented_for('multigraph') 22 | @not_implemented_for('undirected') 23 | def stochastic_graph(G, copy=True, weight='weight'): 24 | """Returns a right-stochastic representation of the directed graph ``G``. 25 | 26 | A right-stochastic graph is a weighted digraph in which for each node, the 27 | sum of the weights of all the out-edges of that node is 1. If the graph is 28 | already weighted (for example, via a ``'weight'`` edge attribute), the 29 | reweighting takes that into account. 30 | 31 | Parameters 32 | ---------- 33 | G : directed graph 34 | A :class:`~networkx.DiGraph` or :class:`~networkx.MultiDiGraph`. 35 | 36 | copy : boolean, optional 37 | If this is ``True``, then this function returns a new instance of 38 | :class:`networkx.Digraph`. Otherwise, the original graph is modified 39 | in-place (and also returned, for convenience). 40 | 41 | weight : edge attribute key (optional, default='weight') 42 | Edge attribute key used for reading the existing weight and setting the 43 | new weight. If no attribute with this key is found for an edge, then the 44 | edge weight is assumed to be 1. If an edge has a weight, it must be a 45 | a positive number. 46 | 47 | """ 48 | if copy: 49 | W = nx.DiGraph(G) 50 | else: 51 | # Reference the original graph, don't make a copy. 52 | W = G 53 | degree = W.out_degree(weight=weight) 54 | for (u, v, d) in W.edges(data=True): 55 | if degree[u] == 0: 56 | warnings.warn('zero out-degree for node %s' % u) 57 | d[weight] = 0 58 | else: 59 | d[weight] = d.get(weight, 1) / degree[u] 60 | return W 61 | -------------------------------------------------------------------------------- /src/networkx/readwrite/tests/test_gpickle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import assert_equal 3 | import os 4 | import tempfile 5 | 6 | import networkx as nx 7 | from networkx.testing.utils import * 8 | 9 | 10 | class TestGpickle(object): 11 | def setUp(self): 12 | G=nx.Graph(name="test") 13 | e=[('a','b'),('b','c'),('c','d'),('d','e'),('e','f'),('a','f')] 14 | G.add_edges_from(e,width=10) 15 | G.add_node('g',color='green') 16 | G.graph['number']=1 17 | DG=nx.DiGraph(G) 18 | MG=nx.MultiGraph(G) 19 | MG.add_edge('a', 'a') 20 | MDG=nx.MultiDiGraph(G) 21 | MDG.add_edge('a', 'a') 22 | fG = G.copy() 23 | fDG = DG.copy() 24 | fMG = MG.copy() 25 | fMDG = MDG.copy() 26 | nx.freeze(fG) 27 | nx.freeze(fDG) 28 | nx.freeze(fMG) 29 | nx.freeze(fMDG) 30 | self.G=G 31 | self.DG=DG 32 | self.MG=MG 33 | self.MDG=MDG 34 | self.fG=fG 35 | self.fDG=fDG 36 | self.fMG=fMG 37 | self.fMDG=fMDG 38 | 39 | def test_gpickle(self): 40 | for G in [self.G, self.DG, self.MG, self.MDG, 41 | self.fG, self.fDG, self.fMG, self.fMDG]: 42 | (fd,fname)=tempfile.mkstemp() 43 | nx.write_gpickle(G,fname) 44 | Gin=nx.read_gpickle(fname) 45 | assert_nodes_equal(G.nodes(data=True), 46 | Gin.nodes(data=True)) 47 | assert_edges_equal(G.edges(data=True), 48 | Gin.edges(data=True)) 49 | assert_graphs_equal(G, Gin) 50 | os.close(fd) 51 | os.unlink(fname) 52 | 53 | def test_protocol(self): 54 | for G in [self.G, self.DG, self.MG, self.MDG, 55 | self.fG, self.fDG, self.fMG, self.fMDG]: 56 | with tempfile.TemporaryFile() as f: 57 | nx.write_gpickle(G, f, 0) 58 | f.seek(0) 59 | Gin = nx.read_gpickle(f) 60 | assert_nodes_equal(G.nodes(data=True), 61 | Gin.nodes(data=True)) 62 | assert_edges_equal(G.edges(data=True), 63 | Gin.edges(data=True)) 64 | assert_graphs_equal(G, Gin) 65 | -------------------------------------------------------------------------------- /src/networkx/algorithms/community/tests/test_kclique.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | from itertools import combinations 5 | from networkx import k_clique_communities 6 | 7 | def test_overlaping_K5(): 8 | G = nx.Graph() 9 | G.add_edges_from(combinations(range(5), 2)) # Add a five clique 10 | G.add_edges_from(combinations(range(2,7), 2)) # Add another five clique 11 | c = list(nx.k_clique_communities(G, 4)) 12 | assert_equal(c,[frozenset([0, 1, 2, 3, 4, 5, 6])]) 13 | c= list(nx.k_clique_communities(G, 5)) 14 | assert_equal(set(c),set([frozenset([0,1,2,3,4]),frozenset([2,3,4,5,6])])) 15 | 16 | def test_isolated_K5(): 17 | G = nx.Graph() 18 | G.add_edges_from(combinations(range(0,5), 2)) # Add a five clique 19 | G.add_edges_from(combinations(range(5,10), 2)) # Add another five clique 20 | c= list(nx.k_clique_communities(G, 5)) 21 | assert_equal(set(c),set([frozenset([0,1,2,3,4]),frozenset([5,6,7,8,9])])) 22 | 23 | def test_zachary(): 24 | z = nx.karate_club_graph() 25 | # clique percolation with k=2 is just connected components 26 | zachary_k2_ground_truth = set([frozenset(z.nodes())]) 27 | zachary_k3_ground_truth = set([frozenset([0, 1, 2, 3, 7, 8, 12, 13, 14, 28 | 15, 17, 18, 19, 20, 21, 22, 23, 29 | 26, 27, 28, 29, 30, 31, 32, 33]), 30 | frozenset([0, 4, 5, 6, 10, 16]), 31 | frozenset([24, 25, 31])]) 32 | zachary_k4_ground_truth = set([frozenset([0, 1, 2, 3, 7, 13]), 33 | frozenset([8, 32, 30, 33]), 34 | frozenset([32, 33, 29, 23])]) 35 | zachary_k5_ground_truth = set([frozenset([0, 1, 2, 3, 7, 13])]) 36 | zachary_k6_ground_truth = set([]) 37 | 38 | assert set(k_clique_communities(z, 2)) == zachary_k2_ground_truth 39 | assert set(k_clique_communities(z, 3)) == zachary_k3_ground_truth 40 | assert set(k_clique_communities(z, 4)) == zachary_k4_ground_truth 41 | assert set(k_clique_communities(z, 5)) == zachary_k5_ground_truth 42 | assert set(k_clique_communities(z, 6)) == zachary_k6_ground_truth 43 | 44 | @raises(nx.NetworkXError) 45 | def test_bad_k(): 46 | c = list(k_clique_communities(nx.Graph(),1)) 47 | -------------------------------------------------------------------------------- /src/networkx/algorithms/approximation/vertex_cover.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | ************ 4 | Vertex Cover 5 | ************ 6 | 7 | Given an undirected graph `G = (V, E)` and a function w assigning nonnegative 8 | weights to its vertices, find a minimum weight subset of V such that each edge 9 | in E is incident to at least one vertex in the subset. 10 | 11 | http://en.wikipedia.org/wiki/Vertex_cover 12 | """ 13 | # Copyright (C) 2011-2012 by 14 | # Nicholas Mancuso 15 | # All rights reserved. 16 | # BSD license. 17 | from networkx.utils import * 18 | __all__ = ["min_weighted_vertex_cover"] 19 | __author__ = """Nicholas Mancuso (nick.mancuso@gmail.com)""" 20 | 21 | @not_implemented_for('directed') 22 | def min_weighted_vertex_cover(G, weight=None): 23 | r"""2-OPT Local Ratio for Minimum Weighted Vertex Cover 24 | 25 | Find an approximate minimum weighted vertex cover of a graph. 26 | 27 | Parameters 28 | ---------- 29 | G : NetworkX graph 30 | Undirected graph 31 | 32 | weight : None or string, optional (default = None) 33 | If None, every edge has weight/distance/cost 1. If a string, use this 34 | edge attribute as the edge weight. Any edge attribute not present 35 | defaults to 1. 36 | 37 | Returns 38 | ------- 39 | min_weighted_cover : set 40 | Returns a set of vertices whose weight sum is no more than 2 * OPT. 41 | 42 | Notes 43 | ----- 44 | Local-Ratio algorithm for computing an approximate vertex cover. 45 | Algorithm greedily reduces the costs over edges and iteratively 46 | builds a cover. Worst-case runtime is `O(|E|)`. 47 | 48 | References 49 | ---------- 50 | .. [1] Bar-Yehuda, R., & Even, S. (1985). A local-ratio theorem for 51 | approximating the weighted vertex cover problem. 52 | Annals of Discrete Mathematics, 25, 27–46 53 | http://www.cs.technion.ac.il/~reuven/PDF/vc_lr.pdf 54 | """ 55 | weight_func = lambda nd: nd.get(weight, 1) 56 | cost = dict((n, weight_func(nd)) for n, nd in G.nodes(data=True)) 57 | 58 | # while there are edges uncovered, continue 59 | for u,v in G.edges_iter(): 60 | # select some uncovered edge 61 | min_cost = min([cost[u], cost[v]]) 62 | cost[u] -= min_cost 63 | cost[v] -= min_cost 64 | 65 | return set(u for u in cost if cost[u] == 0) 66 | -------------------------------------------------------------------------------- /src/networkx/tests/test_convert_pandas.py: -------------------------------------------------------------------------------- 1 | from nose import SkipTest 2 | from nose.tools import assert_true 3 | 4 | import networkx as nx 5 | 6 | class TestConvertPandas(object): 7 | numpy=1 # nosetests attribute, use nosetests -a 'not numpy' to skip test 8 | @classmethod 9 | def setupClass(cls): 10 | try: 11 | import pandas as pd 12 | except ImportError: 13 | raise SkipTest('Pandas not available.') 14 | 15 | def __init__(self, ): 16 | global pd 17 | import pandas as pd 18 | 19 | self.r = pd.np.random.RandomState(seed=5) 20 | ints = self.r.random_integers(1, 10, size=(3,2)) 21 | a = ['A', 'B', 'C'] 22 | b = ['D', 'A', 'E'] 23 | df = pd.DataFrame(ints, columns=['weight', 'cost']) 24 | df[0] = a # Column label 0 (int) 25 | df['b'] = b # Column label 'b' (str) 26 | self.df = df 27 | 28 | def assert_equal(self, G1, G2): 29 | assert_true( nx.is_isomorphic(G1, G2, edge_match=lambda x, y: x == y )) 30 | 31 | def test_from_dataframe_all_attr(self, ): 32 | Gtrue = nx.Graph([('E', 'C', {'cost': 9, 'weight': 10}), 33 | ('B', 'A', {'cost': 1, 'weight': 7}), 34 | ('A', 'D', {'cost': 7, 'weight': 4})]) 35 | G=nx.from_pandas_dataframe(self.df, 0, 'b', True) 36 | self.assert_equal(G, Gtrue) 37 | 38 | def test_from_dataframe_multi_attr(self, ): 39 | Gtrue = nx.Graph([('E', 'C', {'cost': 9, 'weight': 10}), 40 | ('B', 'A', {'cost': 1, 'weight': 7}), 41 | ('A', 'D', {'cost': 7, 'weight': 4})]) 42 | G=nx.from_pandas_dataframe(self.df, 0, 'b', ['weight', 'cost']) 43 | self.assert_equal(G, Gtrue) 44 | 45 | def test_from_dataframe_one_attr(self, ): 46 | Gtrue = nx.Graph([('E', 'C', {'weight': 10}), 47 | ('B', 'A', {'weight': 7}), 48 | ('A', 'D', {'weight': 4})]) 49 | G=nx.from_pandas_dataframe(self.df, 0, 'b', 'weight') 50 | self.assert_equal(G, Gtrue) 51 | 52 | def test_from_dataframe_no_attr(self, ): 53 | Gtrue = nx.Graph([('E', 'C', {}), 54 | ('B', 'A', {}), 55 | ('A', 'D', {})]) 56 | G=nx.from_pandas_dataframe(self.df, 0, 'b',) 57 | self.assert_equal(G, Gtrue) 58 | -------------------------------------------------------------------------------- /src/networkx/algorithms/tests/test_distance_measures.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx 4 | 5 | class TestDistance: 6 | 7 | def setUp(self): 8 | G=networkx.Graph() 9 | from networkx import convert_node_labels_to_integers as cnlti 10 | G=cnlti(networkx.grid_2d_graph(4,4),first_label=1,ordering="sorted") 11 | self.G=G 12 | 13 | def test_eccentricity(self): 14 | assert_equal(networkx.eccentricity(self.G,1),6) 15 | e=networkx.eccentricity(self.G) 16 | assert_equal(e[1],6) 17 | sp=networkx.shortest_path_length(self.G) 18 | e=networkx.eccentricity(self.G,sp=sp) 19 | assert_equal(e[1],6) 20 | e=networkx.eccentricity(self.G,v=1) 21 | assert_equal(e,6) 22 | e=networkx.eccentricity(self.G,v=[1,1]) #This behavior changed in version 1.8 (ticket #739) 23 | assert_equal(e[1],6) 24 | e=networkx.eccentricity(self.G,v=[1,2]) 25 | assert_equal(e[1],6) 26 | # test against graph with one node 27 | G=networkx.path_graph(1) 28 | e=networkx.eccentricity(G) 29 | assert_equal(e[0],0) 30 | e=networkx.eccentricity(G,v=0) 31 | assert_equal(e,0) 32 | assert_raises(networkx.NetworkXError, networkx.eccentricity, G, 1) 33 | # test against empty graph 34 | G=networkx.empty_graph() 35 | e=networkx.eccentricity(G) 36 | assert_equal(e,{}) 37 | 38 | 39 | 40 | 41 | def test_diameter(self): 42 | assert_equal(networkx.diameter(self.G),6) 43 | 44 | def test_radius(self): 45 | assert_equal(networkx.radius(self.G),4) 46 | 47 | def test_periphery(self): 48 | assert_equal(set(networkx.periphery(self.G)),set([1, 4, 13, 16])) 49 | 50 | def test_center(self): 51 | assert_equal(set(networkx.center(self.G)),set([6, 7, 10, 11])) 52 | 53 | def test_radius_exception(self): 54 | G=networkx.Graph() 55 | G.add_edge(1,2) 56 | G.add_edge(3,4) 57 | assert_raises(networkx.NetworkXError, networkx.diameter, G) 58 | 59 | @raises(networkx.NetworkXError) 60 | def test_eccentricity_infinite(self): 61 | G=networkx.Graph([(1,2),(3,4)]) 62 | e = networkx.eccentricity(G) 63 | 64 | @raises(networkx.NetworkXError) 65 | def test_eccentricity_invalid(self): 66 | G=networkx.Graph([(1,2),(3,4)]) 67 | e = networkx.eccentricity(G,sp=1) 68 | 69 | 70 | -------------------------------------------------------------------------------- /src/networkx/generators/ego.py: -------------------------------------------------------------------------------- 1 | """ 2 | Ego graph. 3 | """ 4 | # Copyright (C) 2010 by 5 | # Aric Hagberg 6 | # Dan Schult 7 | # Pieter Swart 8 | # All rights reserved. 9 | # BSD license. 10 | __author__ = """\n""".join(['Drew Conway ', 11 | 'Aric Hagberg ']) 12 | __all__ = ['ego_graph'] 13 | 14 | import networkx as nx 15 | 16 | def ego_graph(G,n,radius=1,center=True,undirected=False,distance=None): 17 | """Returns induced subgraph of neighbors centered at node n within 18 | a given radius. 19 | 20 | Parameters 21 | ---------- 22 | G : graph 23 | A NetworkX Graph or DiGraph 24 | 25 | n : node 26 | A single node 27 | 28 | radius : number, optional 29 | Include all neighbors of distance<=radius from n. 30 | 31 | center : bool, optional 32 | If False, do not include center node in graph 33 | 34 | undirected : bool, optional 35 | If True use both in- and out-neighbors of directed graphs. 36 | 37 | distance : key, optional 38 | Use specified edge data key as distance. For example, setting 39 | distance='weight' will use the edge weight to measure the 40 | distance from the node n. 41 | 42 | Notes 43 | ----- 44 | For directed graphs D this produces the "out" neighborhood 45 | or successors. If you want the neighborhood of predecessors 46 | first reverse the graph with D.reverse(). If you want both 47 | directions use the keyword argument undirected=True. 48 | 49 | Node, edge, and graph attributes are copied to the returned subgraph. 50 | """ 51 | if undirected: 52 | if distance is not None: 53 | sp,_=nx.single_source_dijkstra(G.to_undirected(), 54 | n,cutoff=radius, 55 | weight=distance) 56 | else: 57 | sp=nx.single_source_shortest_path_length(G.to_undirected(), 58 | n,cutoff=radius) 59 | else: 60 | if distance is not None: 61 | sp,_=nx.single_source_dijkstra(G, 62 | n,cutoff=radius, 63 | weight=distance) 64 | else: 65 | sp=nx.single_source_shortest_path_length(G,n,cutoff=radius) 66 | 67 | H=G.subgraph(sp).copy() 68 | if not center: 69 | H.remove_node(n) 70 | return H 71 | -------------------------------------------------------------------------------- /data/eil76.graph: -------------------------------------------------------------------------------- 1 | NAME : eil76 2 | COMMENT : 76-city problem (Christofides/Eilon) 3 | TYPE : TSP 4 | DIMENSION : 76 5 | EDGE_WEIGHT_TYPE : EUC_2D 6 | NODE_COORD_SECTION 7 | 1 22 22 8 | 2 36 26 9 | 3 21 45 10 | 4 45 35 11 | 5 55 20 12 | 6 33 34 13 | 7 50 50 14 | 8 55 45 15 | 9 26 59 16 | 10 40 66 17 | 11 55 65 18 | 12 35 51 19 | 13 62 35 20 | 14 62 57 21 | 15 62 24 22 | 16 21 36 23 | 17 33 44 24 | 18 9 56 25 | 19 62 48 26 | 20 66 14 27 | 21 44 13 28 | 22 26 13 29 | 23 11 28 30 | 24 7 43 31 | 25 17 64 32 | 26 41 46 33 | 27 55 34 34 | 28 35 16 35 | 29 52 26 36 | 30 43 26 37 | 31 31 76 38 | 32 22 53 39 | 33 26 29 40 | 34 50 40 41 | 35 55 50 42 | 36 54 10 43 | 37 60 15 44 | 38 47 66 45 | 39 30 60 46 | 40 30 50 47 | 41 12 17 48 | 42 15 14 49 | 43 16 19 50 | 44 21 48 51 | 45 50 30 52 | 46 51 42 53 | 47 50 15 54 | 48 48 21 55 | 49 12 38 56 | 50 15 56 57 | 51 29 39 58 | 52 54 38 59 | 53 55 57 60 | 54 67 41 61 | 55 10 70 62 | 56 6 25 63 | 57 65 27 64 | 58 40 60 65 | 59 70 64 66 | 60 64 4 67 | 61 36 6 68 | 62 30 20 69 | 63 20 30 70 | 64 15 5 71 | 65 50 70 72 | 66 57 72 73 | 67 45 42 74 | 68 38 33 75 | 69 50 4 76 | 70 66 8 77 | 71 59 5 78 | 72 35 60 79 | 73 27 24 80 | 74 40 20 81 | 75 40 37 82 | 76 40 40 83 | LOCKER_SECTION : id, pos 84 | 1 10 85 | 2 20 86 | 3 30 87 | 4 40 88 | 5 50 89 | DELIVER_SECTION : id, pos, max_distance, max_capacity 90 | 1 3 100 100 91 | 2 6 100 100 92 | 3 9 100 100 93 | 4 12 100 100 94 | 5 15 100 100 95 | 6 18 100 100 96 | 7 21 100 100 97 | 8 24 100 100 98 | 9 27 100 100 99 | 10 30 100 100 100 | 11 33 100 100 101 | 12 36 100 100 102 | 13 39 100 100 103 | 14 42 100 100 104 | 15 45 100 100 105 | 16 48 100 100 106 | DEMAND_SECTION 107 | 1 0 108 | 2 7 109 | 3 30 110 | 4 16 111 | 5 9 112 | 6 21 113 | 7 15 114 | 8 19 115 | 9 23 116 | 10 11 117 | 11 5 118 | 12 19 119 | 13 29 120 | 14 23 121 | 15 21 122 | 16 10 123 | 17 15 124 | 18 3 125 | 19 41 126 | 20 9 127 | 21 28 128 | 22 8 129 | 23 8 130 | 24 16 131 | 25 10 132 | 26 28 133 | 27 7 134 | 28 15 135 | 29 14 136 | 30 6 137 | 31 19 138 | 32 11 139 | 33 12 140 | 34 23 141 | 35 26 142 | 36 17 143 | 37 6 144 | 38 9 145 | 39 15 146 | 40 14 147 | 41 7 148 | 42 27 149 | 43 13 150 | 44 11 151 | 45 16 152 | 46 10 153 | 47 5 154 | 48 25 155 | 49 17 156 | 50 18 157 | 51 10 158 | 52 11 159 | 53 12 160 | 54 10 161 | 55 13 162 | 56 14 163 | 57 15 164 | 58 15 165 | 59 29 166 | 60 24 167 | 61 14 168 | 62 54 169 | 63 34 170 | 64 35 171 | 65 5 172 | 66 23 173 | 67 34 174 | 68 5 175 | 69 5 176 | 70 35 177 | 71 66 178 | 72 4 179 | 73 64 180 | 74 64 181 | 75 35 182 | 76 54 183 | EOF 184 | -------------------------------------------------------------------------------- /src/networkx/algorithms/dominating.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import networkx as nx 3 | __author__ = '\n'.join(['Jordi Torrents ']) 4 | __all__ = [ 'dominating_set', 'is_dominating_set'] 5 | 6 | def dominating_set(G, start_with=None): 7 | r"""Finds a dominating set for the graph G. 8 | 9 | A dominating set for a graph `G = (V, E)` is a node subset `D` of `V` 10 | such that every node not in `D` is adjacent to at least one member 11 | of `D` [1]_. 12 | 13 | Parameters 14 | ---------- 15 | 16 | G : NetworkX graph 17 | 18 | start_with : Node (default=None) 19 | Node to use as a starting point for the algorithm. 20 | 21 | Returns 22 | ------- 23 | D : set 24 | A dominating set for G. 25 | 26 | Notes 27 | ----- 28 | This function is an implementation of algorithm 7 in [2]_ which 29 | finds some dominating set, not necessarily the smallest one. 30 | 31 | See also 32 | -------- 33 | is_dominating_set 34 | 35 | References 36 | ---------- 37 | .. [1] http://en.wikipedia.org/wiki/Dominating_set 38 | 39 | .. [2] Abdol-Hossein Esfahanian. Connectivity Algorithms. 40 | http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf 41 | 42 | """ 43 | all_nodes = set(G) 44 | if start_with is None: 45 | v = set(G).pop() # pick a node 46 | else: 47 | if start_with not in G: 48 | raise nx.NetworkXError('node %s not in G' % start_with) 49 | v = start_with 50 | D = set([v]) 51 | ND = set(G[v]) 52 | other = all_nodes - ND - D 53 | while other: 54 | w = other.pop() 55 | D.add(w) 56 | ND.update([nbr for nbr in G[w] if nbr not in D]) 57 | other = all_nodes - ND - D 58 | return D 59 | 60 | def is_dominating_set(G, nbunch): 61 | r"""Checks if nodes in nbunch are a dominating set for G. 62 | 63 | A dominating set for a graph `G = (V, E)` is a node subset `D` of `V` 64 | such that every node not in `D` is adjacent to at least one member 65 | of `D` [1]_. 66 | 67 | Parameters 68 | ---------- 69 | 70 | G : NetworkX graph 71 | 72 | nbunch : Node container 73 | 74 | See also 75 | -------- 76 | dominating_set 77 | 78 | References 79 | ---------- 80 | .. [1] http://en.wikipedia.org/wiki/Dominating_set 81 | 82 | """ 83 | testset = set(n for n in nbunch if n in G) 84 | nbrs = set() 85 | for n in testset: 86 | nbrs.update(G[n]) 87 | if len(set(G) - testset - nbrs) > 0: 88 | return False 89 | else: 90 | return True 91 | -------------------------------------------------------------------------------- /src/networkx/algorithms/chordal/tests/test_chordal.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | 5 | class TestMCS: 6 | 7 | def setUp(self): 8 | # simple graph 9 | connected_chordal_G=nx.Graph() 10 | connected_chordal_G.add_edges_from([(1,2),(1,3),(2,3),(2,4),(3,4), 11 | (3,5),(3,6),(4,5),(4,6),(5,6)]) 12 | self.connected_chordal_G=connected_chordal_G 13 | 14 | chordal_G = nx.Graph() 15 | chordal_G.add_edges_from([(1,2),(1,3),(2,3),(2,4),(3,4), 16 | (3,5),(3,6),(4,5),(4,6),(5,6),(7,8)]) 17 | chordal_G.add_node(9) 18 | self.chordal_G=chordal_G 19 | 20 | non_chordal_G = nx.Graph() 21 | non_chordal_G.add_edges_from([(1,2),(1,3),(2,4),(2,5),(3,4),(3,5)]) 22 | self.non_chordal_G = non_chordal_G 23 | 24 | def test_is_chordal(self): 25 | assert_false(nx.is_chordal(self.non_chordal_G)) 26 | assert_true(nx.is_chordal(self.chordal_G)) 27 | assert_true(nx.is_chordal(self.connected_chordal_G)) 28 | assert_true(nx.is_chordal(nx.complete_graph(3))) 29 | assert_true(nx.is_chordal(nx.cycle_graph(3))) 30 | assert_false(nx.is_chordal(nx.cycle_graph(5))) 31 | 32 | def test_induced_nodes(self): 33 | G = nx.generators.classic.path_graph(10) 34 | I = nx.find_induced_nodes(G,1,9,2) 35 | assert_equal(I,set([1,2,3,4,5,6,7,8,9])) 36 | assert_raises(nx.NetworkXTreewidthBoundExceeded, 37 | nx.find_induced_nodes,G,1,9,1) 38 | I = nx.find_induced_nodes(self.chordal_G,1,6) 39 | assert_equal(I,set([1,2,4,6])) 40 | assert_raises(nx.NetworkXError, 41 | nx.find_induced_nodes,self.non_chordal_G,1,5) 42 | 43 | def test_chordal_find_cliques(self): 44 | cliques = set([frozenset([9]),frozenset([7,8]),frozenset([1,2,3]), 45 | frozenset([2,3,4]),frozenset([3,4,5,6])]) 46 | assert_equal(nx.chordal_graph_cliques(self.chordal_G),cliques) 47 | 48 | def test_chordal_find_cliques_path(self): 49 | G = nx.path_graph(10) 50 | cliqueset = nx.chordal_graph_cliques(G) 51 | for (u,v) in G.edges_iter(): 52 | assert_true(frozenset([u,v]) in cliqueset 53 | or frozenset([v,u]) in cliqueset) 54 | 55 | def test_chordal_find_cliquesCC(self): 56 | cliques = set([frozenset([1,2,3]),frozenset([2,3,4]), 57 | frozenset([3,4,5,6])]) 58 | assert_equal(nx.chordal_graph_cliques(self.connected_chordal_G),cliques) 59 | 60 | -------------------------------------------------------------------------------- /src/networkx/linalg/tests/test_modularity.py: -------------------------------------------------------------------------------- 1 | from nose import SkipTest 2 | 3 | import networkx as nx 4 | from networkx.generators.degree_seq import havel_hakimi_graph 5 | 6 | 7 | class TestModularity(object): 8 | numpy = 1 # nosetests attribute, use nosetests -a 'not numpy' to skip test 9 | 10 | @classmethod 11 | def setupClass(cls): 12 | global numpy 13 | global scipy 14 | global assert_equal 15 | global assert_almost_equal 16 | try: 17 | import numpy 18 | import scipy 19 | from numpy.testing import assert_equal, assert_almost_equal 20 | except ImportError: 21 | raise SkipTest('SciPy not available.') 22 | 23 | def setUp(self): 24 | deg = [3, 2, 2, 1, 0] 25 | self.G = havel_hakimi_graph(deg) 26 | # Graph used as an example in Sec. 4.1 of Langville and Meyer, 27 | # "Google's PageRank and Beyond". (Used for test_directed_laplacian) 28 | self.DG = nx.DiGraph() 29 | self.DG.add_edges_from(((1,2), (1,3), (3,1), (3,2), (3,5), (4,5), (4,6), 30 | (5,4), (5,6), (6,4))) 31 | 32 | 33 | def test_modularity(self): 34 | "Modularity matrix" 35 | B = numpy.matrix([[-1.125, 0.25 , 0.25 , 0.625, 0. ], 36 | [ 0.25 , -0.5 , 0.5 , -0.25 , 0. ], 37 | [ 0.25 , 0.5 , -0.5 , -0.25 , 0. ], 38 | [ 0.625, -0.25 , -0.25 , -0.125, 0. ], 39 | [ 0. , 0. , 0. , 0. , 0. ]]) 40 | 41 | permutation = [4, 0, 1, 2, 3] 42 | assert_equal(nx.modularity_matrix(self.G), B) 43 | assert_equal(nx.modularity_matrix(self.G, nodelist=permutation), 44 | B[numpy.ix_(permutation, permutation)]) 45 | 46 | def test_directed_modularity(self): 47 | "Directed Modularity matrix" 48 | B = numpy.matrix([[-0.2, 0.6, 0.8, -0.4, -0.4, -0.4], 49 | [ 0. , 0. , 0. , 0. , 0. , 0. ], 50 | [ 0.7, 0.4, -0.3, -0.6, 0.4, -0.6], 51 | [-0.2, -0.4, -0.2, -0.4, 0.6, 0.6], 52 | [-0.2, -0.4, -0.2, 0.6, -0.4, 0.6], 53 | [-0.1, -0.2, -0.1, 0.8, -0.2, -0.2]]) 54 | node_permutation = [5, 1, 2, 3, 4, 6] 55 | idx_permutation = [4, 0, 1, 2, 3, 5] 56 | assert_equal(nx.directed_modularity_matrix(self.DG), B) 57 | assert_equal(nx.directed_modularity_matrix(self.DG, nodelist=node_permutation), 58 | B[numpy.ix_(idx_permutation, idx_permutation)]) 59 | -------------------------------------------------------------------------------- /src/networkx/algorithms/centrality/harmonic.py: -------------------------------------------------------------------------------- 1 | """ 2 | Harmonic centrality measure. 3 | """ 4 | # Copyright (C) 2015 by 5 | # Alessandro Luongo 6 | # BSD license. 7 | from __future__ import division 8 | import functools 9 | import networkx as nx 10 | 11 | __author__ = "\n".join(['Alessandro Luongo (alessandro.luongo@studenti.unimi.it']) 12 | __all__ = ['harmonic_centrality'] 13 | 14 | 15 | def harmonic_centrality(G, distance=None): 16 | r"""Compute harmonic centrality for nodes. 17 | 18 | Harmonic centrality [1]_ of a node `u` is the sum of the reciprocal 19 | of the shortest path distances from all other nodes to `u` 20 | 21 | .. math:: 22 | 23 | C(u) = \sum_{v \neq u} \frac{1}{d(v, u)} 24 | 25 | where `d(v, u)` is the shortest-path distance between `v` and `u`. 26 | 27 | Notice that higher values indicate higher centrality. 28 | 29 | Parameters 30 | ---------- 31 | G : graph 32 | A NetworkX graph 33 | 34 | distance : edge attribute key, optional (default=None) 35 | Use the specified edge attribute as the edge distance in shortest 36 | path calculations. If `None`, then each edge will have distance equal to 1. 37 | 38 | Returns 39 | ------- 40 | nodes : dictionary 41 | Dictionary of nodes with harmonic centrality as the value. 42 | 43 | See Also 44 | -------- 45 | betweenness_centrality, load_centrality, eigenvector_centrality, 46 | degree_centrality, closeness_centrality 47 | 48 | Notes 49 | ----- 50 | If the 'distance' keyword is set to an edge attribute key then the 51 | shortest-path length will be computed using Dijkstra's algorithm with 52 | that edge attribute as the edge weight. 53 | 54 | References 55 | ---------- 56 | .. [1] Boldi, Paolo, and Sebastiano Vigna. "Axioms for centrality." Internet Mathematics 10.3-4 (2014): 222-262. 57 | """ 58 | 59 | if distance is not None: 60 | # use Dijkstra's algorithm with specified attribute as edge weight 61 | path_length = functools.partial(nx.all_pairs_dijkstra_path_length, 62 | weight=distance) 63 | else: 64 | path_length = nx.all_pairs_shortest_path_length 65 | 66 | nodes = G.nodes() 67 | harmonic_centrality = {} 68 | 69 | if len(G) <= 1: 70 | for singleton in nodes: 71 | harmonic_centrality[singleton] = 0.0 72 | return harmonic_centrality 73 | 74 | sp = path_length(G.reverse() if G.is_directed() else G) 75 | 76 | for n in nodes: 77 | harmonic_centrality[n] = sum([1/i if i > 0 else 0 for i in sp[n].values()]) 78 | 79 | return harmonic_centrality 80 | 81 | 82 | -------------------------------------------------------------------------------- /src/networkx/algorithms/approximation/tests/test_dominating_set.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import ok_ 3 | from nose.tools import eq_ 4 | import networkx as nx 5 | from networkx.algorithms.approximation import min_weighted_dominating_set 6 | from networkx.algorithms.approximation import min_edge_dominating_set 7 | 8 | 9 | class TestMinWeightDominatingSet: 10 | 11 | def test_min_weighted_dominating_set(self): 12 | graph = nx.Graph() 13 | graph.add_edge(1, 2) 14 | graph.add_edge(1, 5) 15 | graph.add_edge(2, 3) 16 | graph.add_edge(2, 5) 17 | graph.add_edge(3, 4) 18 | graph.add_edge(3, 6) 19 | graph.add_edge(5, 6) 20 | 21 | vertices = set([1, 2, 3, 4, 5, 6]) 22 | # due to ties, this might be hard to test tight bounds 23 | dom_set = min_weighted_dominating_set(graph) 24 | for vertex in vertices - dom_set: 25 | neighbors = set(graph.neighbors(vertex)) 26 | ok_(len(neighbors & dom_set) > 0, "Non dominating set found!") 27 | 28 | def test_star_graph(self): 29 | """Tests that an approximate dominating set for the star graph, 30 | even when the center node does not have the smallest integer 31 | label, gives just the center node. 32 | 33 | For more information, see #1527. 34 | 35 | """ 36 | # Create a star graph in which the center node has the highest 37 | # label instead of the lowest. 38 | G = nx.star_graph(10) 39 | G = nx.relabel_nodes(G, {0: 9, 9: 0}) 40 | eq_(min_weighted_dominating_set(G), {9}) 41 | 42 | def test_min_edge_dominating_set(self): 43 | graph = nx.path_graph(5) 44 | dom_set = min_edge_dominating_set(graph) 45 | 46 | # this is a crappy way to test, but good enough for now. 47 | for edge in graph.edges_iter(): 48 | if edge in dom_set: 49 | continue 50 | else: 51 | u, v = edge 52 | found = False 53 | for dom_edge in dom_set: 54 | found |= u == dom_edge[0] or u == dom_edge[1] 55 | ok_(found, "Non adjacent edge found!") 56 | 57 | graph = nx.complete_graph(10) 58 | dom_set = min_edge_dominating_set(graph) 59 | 60 | # this is a crappy way to test, but good enough for now. 61 | for edge in graph.edges_iter(): 62 | if edge in dom_set: 63 | continue 64 | else: 65 | u, v = edge 66 | found = False 67 | for dom_edge in dom_set: 68 | found |= u == dom_edge[0] or u == dom_edge[1] 69 | ok_(found, "Non adjacent edge found!") 70 | -------------------------------------------------------------------------------- /src/networkx/algorithms/traversal/tests/test_dfs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | 5 | class TestDFS: 6 | 7 | def setUp(self): 8 | # simple graph 9 | G=nx.Graph() 10 | G.add_edges_from([(0,1),(1,2),(1,3),(2,4),(3,4)]) 11 | self.G=G 12 | # simple graph, disconnected 13 | D=nx.Graph() 14 | D.add_edges_from([(0,1),(2,3)]) 15 | self.D=D 16 | 17 | 18 | def test_preorder_nodes(self): 19 | assert_equal(list(nx.dfs_preorder_nodes(self.G,source=0)), 20 | [0, 1, 2, 4, 3]) 21 | assert_equal(list(nx.dfs_preorder_nodes(self.D)),[0, 1, 2, 3]) 22 | 23 | def test_postorder_nodes(self): 24 | assert_equal(list(nx.dfs_postorder_nodes(self.G,source=0)), 25 | [3, 4, 2, 1, 0]) 26 | assert_equal(list(nx.dfs_postorder_nodes(self.D)),[1, 0, 3, 2]) 27 | 28 | def test_successor(self): 29 | assert_equal(nx.dfs_successors(self.G,source=0), 30 | {0: [1], 1: [2], 2: [4], 4: [3]}) 31 | assert_equal(nx.dfs_successors(self.D), {0: [1], 2: [3]}) 32 | 33 | def test_predecessor(self): 34 | assert_equal(nx.dfs_predecessors(self.G,source=0), 35 | {1: 0, 2: 1, 3: 4, 4: 2}) 36 | assert_equal(nx.dfs_predecessors(self.D), {1: 0, 3: 2}) 37 | 38 | def test_dfs_tree(self): 39 | T=nx.dfs_tree(self.G,source=0) 40 | assert_equal(sorted(T.nodes()),sorted(self.G.nodes())) 41 | assert_equal(sorted(T.edges()),[(0, 1), (1, 2), (2, 4), (4, 3)]) 42 | 43 | def test_dfs_edges(self): 44 | edges=nx.dfs_edges(self.G,source=0) 45 | assert_equal(list(edges),[(0, 1), (1, 2), (2, 4), (4, 3)]) 46 | edges=nx.dfs_edges(self.D) 47 | assert_equal(list(edges),[(0, 1), (2, 3)]) 48 | 49 | def test_dfs_labeled_edges(self): 50 | edges=list(nx.dfs_labeled_edges(self.G,source=0)) 51 | forward=[(u,v) for (u,v,d) in edges if d['dir']=='forward'] 52 | assert_equal(forward,[(0,0), (0, 1), (1, 2), (2, 4), (4, 3)]) 53 | 54 | def test_dfs_labeled_disconnected_edges(self): 55 | edges=list(nx.dfs_labeled_edges(self.D)) 56 | forward=[(u,v) for (u,v,d) in edges if d['dir']=='forward'] 57 | assert_equal(forward,[(0, 0), (0, 1), (2, 2), (2, 3)]) 58 | 59 | def test_dfs_tree_isolates(self): 60 | G = nx.Graph() 61 | G.add_node(1) 62 | G.add_node(2) 63 | T=nx.dfs_tree(G,source=1) 64 | assert_equal(sorted(T.nodes()),[1]) 65 | assert_equal(sorted(T.edges()),[]) 66 | T=nx.dfs_tree(G,source=None) 67 | assert_equal(sorted(T.nodes()),[1, 2]) 68 | assert_equal(sorted(T.edges()),[]) 69 | -------------------------------------------------------------------------------- /src/networkx/generators/tests/test_line.py: -------------------------------------------------------------------------------- 1 | import networkx as nx 2 | from nose.tools import * 3 | 4 | import networkx.generators.line as line 5 | 6 | def test_node_func(): 7 | # graph 8 | G = nx.Graph() 9 | G.add_edge(1,2) 10 | nf = line._node_func(G) 11 | assert_equal(nf(1,2), (1,2)) 12 | assert_equal(nf(2,1), (1,2)) 13 | 14 | # multigraph 15 | G = nx.MultiGraph() 16 | G.add_edge(1,2) 17 | G.add_edge(1,2) 18 | nf = line._node_func(G) 19 | assert_equal(nf(1,2,0), (1,2,0)) 20 | assert_equal(nf(2,1,0), (1,2,0)) 21 | 22 | def test_edge_func(): 23 | # graph 24 | G = nx.Graph() 25 | G.add_edge(1,2) 26 | G.add_edge(2,3) 27 | ef = line._edge_func(G) 28 | expected = [(1,2),(2,3)] 29 | result = sorted(ef()) 30 | assert_equal(expected, result) 31 | 32 | # digraph 33 | G = nx.MultiDiGraph() 34 | G.add_edge(1,2) 35 | G.add_edge(2,3) 36 | G.add_edge(2,3) 37 | ef = line._edge_func(G) 38 | expected = [(1,2,0),(2,3,0),(2,3,1)] 39 | result = sorted(ef()) 40 | assert_equal(expected, result) 41 | 42 | def test_sorted_edge(): 43 | assert_equal( (1,2), line._sorted_edge(1,2) ) 44 | assert_equal( (1,2), line._sorted_edge(2,1) ) 45 | 46 | class TestGeneratorLine(): 47 | def test_star(self): 48 | G = nx.star_graph(5) 49 | L = nx.line_graph(G) 50 | assert_true(nx.is_isomorphic(L, nx.complete_graph(5))) 51 | 52 | def test_path(self): 53 | G = nx.path_graph(5) 54 | L = nx.line_graph(G) 55 | assert_true(nx.is_isomorphic(L, nx.path_graph(4))) 56 | 57 | def test_cycle(self): 58 | G = nx.cycle_graph(5) 59 | L = nx.line_graph(G) 60 | assert_true(nx.is_isomorphic(L, G)) 61 | 62 | def test_digraph1(self): 63 | G = nx.DiGraph() 64 | G.add_edges_from([(0,1),(0,2),(0,3)]) 65 | L = nx.line_graph(G) 66 | # no edge graph, but with nodes 67 | assert_equal(L.adj, {(0,1):{}, (0,2):{}, (0,3):{}}) 68 | 69 | def test_digraph2(self): 70 | G = nx.DiGraph() 71 | G.add_edges_from([(0,1),(1,2),(2,3)]) 72 | L = nx.line_graph(G) 73 | assert_equal(sorted(L.edges()), [((0, 1), (1, 2)), ((1, 2), (2, 3))]) 74 | 75 | def test_create1(self): 76 | G = nx.DiGraph() 77 | G.add_edges_from([(0,1),(1,2),(2,3)]) 78 | L = nx.line_graph(G, create_using=nx.Graph()) 79 | assert_equal(sorted(L.edges()), [((0, 1), (1, 2)), ((1, 2), (2, 3))]) 80 | 81 | def test_create2(self): 82 | G = nx.Graph() 83 | G.add_edges_from([(0,1),(1,2),(2,3)]) 84 | L = nx.line_graph(G, create_using=nx.DiGraph()) 85 | assert_equal(sorted(L.edges()), [((0, 1), (1, 2)), ((1, 2), (2, 3))]) 86 | -------------------------------------------------------------------------------- /src/networkx/algorithms/shortest_paths/tests/test_dense_numpy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | from nose import SkipTest 4 | import networkx as nx 5 | 6 | class TestFloydNumpy(object): 7 | numpy=1 # nosetests attribute, use nosetests -a 'not numpy' to skip test 8 | @classmethod 9 | def setupClass(cls): 10 | global numpy 11 | global assert_equal 12 | global assert_almost_equal 13 | try: 14 | import numpy 15 | from numpy.testing import assert_equal,assert_almost_equal 16 | except ImportError: 17 | raise SkipTest('NumPy not available.') 18 | 19 | def test_cycle_numpy(self): 20 | dist = nx.floyd_warshall_numpy(nx.cycle_graph(7)) 21 | assert_equal(dist[0,3],3) 22 | assert_equal(dist[0,4],3) 23 | 24 | def test_weighted_numpy(self): 25 | XG3=nx.Graph() 26 | XG3.add_weighted_edges_from([ [0,1,2],[1,2,12],[2,3,1], 27 | [3,4,5],[4,5,1],[5,0,10] ]) 28 | dist = nx.floyd_warshall_numpy(XG3) 29 | assert_equal(dist[0,3],15) 30 | 31 | def test_weighted_numpy(self): 32 | XG4=nx.Graph() 33 | XG4.add_weighted_edges_from([ [0,1,2],[1,2,2],[2,3,1], 34 | [3,4,1],[4,5,1],[5,6,1], 35 | [6,7,1],[7,0,1] ]) 36 | dist = nx.floyd_warshall_numpy(XG4) 37 | assert_equal(dist[0,2],4) 38 | 39 | def test_weight_parameter_numpy(self): 40 | XG4 = nx.Graph() 41 | XG4.add_edges_from([ (0, 1, {'heavy': 2}), (1, 2, {'heavy': 2}), 42 | (2, 3, {'heavy': 1}), (3, 4, {'heavy': 1}), 43 | (4, 5, {'heavy': 1}), (5, 6, {'heavy': 1}), 44 | (6, 7, {'heavy': 1}), (7, 0, {'heavy': 1}) ]) 45 | dist = nx.floyd_warshall_numpy(XG4, weight='heavy') 46 | assert_equal(dist[0, 2], 4) 47 | 48 | def test_directed_cycle_numpy(self): 49 | G = nx.DiGraph() 50 | G.add_cycle([0,1,2,3]) 51 | pred,dist = nx.floyd_warshall_predecessor_and_distance(G) 52 | D = nx.utils.dict_to_numpy_array(dist) 53 | assert_equal(nx.floyd_warshall_numpy(G),D) 54 | 55 | def test_zero_weight(self): 56 | G = nx.DiGraph() 57 | edges = [(1,2,-2), (2,3,-4), (1,5,1), (5,4,0), (4,3,-5), (2,5,-7)] 58 | G.add_weighted_edges_from(edges) 59 | dist = nx.floyd_warshall_numpy(G) 60 | assert_equal(int(numpy.min(dist)), -14) 61 | 62 | G = nx.MultiDiGraph() 63 | edges.append( (2,5,-7) ) 64 | G.add_weighted_edges_from(edges) 65 | dist = nx.floyd_warshall_numpy(G) 66 | assert_equal(int(numpy.min(dist)), -14) 67 | 68 | -------------------------------------------------------------------------------- /src/networkx/generators/tests/test_expanders.py: -------------------------------------------------------------------------------- 1 | # Copyright 2014 "cheebee7i". 2 | # Copyright 2014 "alexbrc". 3 | # Copyright 2014 Jeffrey Finkelstein . 4 | """Unit tests for the :mod:`networkx.generators.expanders` module. 5 | 6 | """ 7 | try: 8 | import scipy 9 | is_scipy_available = True 10 | except: 11 | is_scipy_available = False 12 | 13 | import networkx as nx 14 | from networkx import adjacency_matrix 15 | from networkx import number_of_nodes 16 | from networkx.generators.expanders import chordal_cycle_graph 17 | from networkx.generators.expanders import margulis_gabber_galil_graph 18 | 19 | from nose import SkipTest 20 | from nose.tools import assert_equal 21 | from nose.tools import assert_less 22 | from nose.tools import assert_raises 23 | from nose.tools import assert_true 24 | 25 | 26 | def test_margulis_gabber_galil_graph(): 27 | try: 28 | # Scipy is required for conversion to an adjacency matrix. 29 | # We also use scipy for computing the eigenvalues, 30 | # but this second use could be done using only numpy. 31 | import numpy as np 32 | import scipy.linalg 33 | has_scipy = True 34 | except ImportError as e: 35 | has_scipy = False 36 | for n in 2, 3, 5, 6, 10: 37 | g = margulis_gabber_galil_graph(n) 38 | assert_equal(number_of_nodes(g), n*n) 39 | for node in g: 40 | assert_equal(g.degree(node), 8) 41 | assert_equal(len(node), 2) 42 | for i in node: 43 | assert_equal(int(i), i) 44 | assert_true(0 <= i < n) 45 | if has_scipy: 46 | # Eigenvalues are already sorted using the scipy eigvalsh, 47 | # but the implementation in numpy does not guarantee order. 48 | w = sorted(scipy.linalg.eigvalsh(adjacency_matrix(g).A)) 49 | assert_less(w[-2], 5*np.sqrt(2)) 50 | 51 | 52 | def test_chordal_cycle_graph(): 53 | """Test for the :func:`networkx.chordal_cycle_graph` function.""" 54 | if not is_scipy_available: 55 | raise SkipTest('SciPy is not available') 56 | primes = [3, 5, 7, 11] 57 | for p in primes: 58 | G = chordal_cycle_graph(p) 59 | assert_equal(len(G), p) 60 | # TODO The second largest eigenvalue should be smaller than a constant, 61 | # independent of the number of nodes in the graph: 62 | # 63 | # eigs = sorted(scipy.linalg.eigvalsh(adjacency_matrix(G).A)) 64 | # assert_less(eigs[-2], ...) 65 | # 66 | 67 | 68 | def test_margulis_gabber_galil_graph_badinput(): 69 | assert_raises(nx.NetworkXError, margulis_gabber_galil_graph, 3, 70 | nx.DiGraph()) 71 | assert_raises(nx.NetworkXError, margulis_gabber_galil_graph, 3, 72 | nx.Graph()) 73 | -------------------------------------------------------------------------------- /src/networkx/algorithms/components/tests/test_weakly_connected.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | from networkx import NetworkXNotImplemented 5 | 6 | class TestWeaklyConnected: 7 | 8 | def setUp(self): 9 | self.gc = [] 10 | G = nx.DiGraph() 11 | G.add_edges_from([(1, 2), (2, 3), (2, 8), (3, 4), (3, 7), (4, 5), 12 | (5, 3), (5, 6), (7, 4), (7, 6), (8, 1), (8, 7)]) 13 | C = [[3, 4, 5, 7], [1, 2, 8], [6]] 14 | self.gc.append((G, C)) 15 | 16 | G = nx.DiGraph() 17 | G.add_edges_from([(1, 2), (1, 3), (1, 4), (4, 2), (3, 4), (2, 3)]) 18 | C = [[2, 3, 4],[1]] 19 | self.gc.append((G, C)) 20 | 21 | G = nx.DiGraph() 22 | G.add_edges_from([(1, 2), (2, 3), (3, 2), (2, 1)]) 23 | C = [[1, 2, 3]] 24 | self.gc.append((G,C)) 25 | 26 | # Eppstein's tests 27 | G = nx.DiGraph({0:[1], 1:[2, 3], 2:[4, 5], 3:[4, 5], 4:[6], 5:[], 6:[]}) 28 | C = [[0], [1], [2],[ 3], [4], [5], [6]] 29 | self.gc.append((G,C)) 30 | 31 | G = nx.DiGraph({0:[1], 1:[2, 3, 4], 2:[0, 3], 3:[4], 4:[3]}) 32 | C = [[0, 1, 2], [3, 4]] 33 | self.gc.append((G, C)) 34 | 35 | 36 | def test_weakly_connected_components(self): 37 | for G, C in self.gc: 38 | U = G.to_undirected() 39 | w = {frozenset(g) for g in nx.weakly_connected_components(G)} 40 | c = {frozenset(g) for g in nx.connected_components(U)} 41 | assert_equal(w, c) 42 | 43 | def test_number_weakly_connected_components(self): 44 | for G, C in self.gc: 45 | U = G.to_undirected() 46 | w = nx.number_weakly_connected_components(G) 47 | c = nx.number_connected_components(U) 48 | assert_equal(w, c) 49 | 50 | def test_weakly_connected_component_subgraphs(self): 51 | wcc = nx.weakly_connected_component_subgraphs 52 | cc = nx.connected_component_subgraphs 53 | for G, C in self.gc: 54 | U = G.to_undirected() 55 | w = {frozenset(g) for g in wcc(G)} 56 | c = {frozenset(g) for g in cc(U)} 57 | assert_equal(w, c) 58 | 59 | def test_is_weakly_connected(self): 60 | for G, C in self.gc: 61 | U = G.to_undirected() 62 | assert_equal(nx.is_weakly_connected(G), nx.is_connected(U)) 63 | 64 | def test_connected_raise(self): 65 | G=nx.Graph() 66 | assert_raises(NetworkXNotImplemented,nx.weakly_connected_components, G) 67 | assert_raises(NetworkXNotImplemented,nx.number_weakly_connected_components, G) 68 | assert_raises(NetworkXNotImplemented,nx.weakly_connected_component_subgraphs, G) 69 | assert_raises(NetworkXNotImplemented,nx.is_weakly_connected, G) 70 | -------------------------------------------------------------------------------- /src/networkx/algorithms/mis.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # $Id: maximalIndependentSet.py 576 2011-03-01 05:50:34Z lleeoo $ 3 | """ 4 | Algorithm to find a maximal (not maximum) independent set. 5 | 6 | """ 7 | # Leo Lopes 8 | # Aric Hagberg 9 | # Dan Schult 10 | # Pieter Swart 11 | # All rights reserved. 12 | # BSD license. 13 | 14 | __author__ = "\n".join(["Leo Lopes ", 15 | "Loïc Séguin-C. "]) 16 | 17 | __all__ = ['maximal_independent_set'] 18 | 19 | import random 20 | import networkx as nx 21 | 22 | def maximal_independent_set(G, nodes=None): 23 | """Return a random maximal independent set guaranteed to contain 24 | a given set of nodes. 25 | 26 | An independent set is a set of nodes such that the subgraph 27 | of G induced by these nodes contains no edges. A maximal 28 | independent set is an independent set such that it is not possible 29 | to add a new node and still get an independent set. 30 | 31 | Parameters 32 | ---------- 33 | G : NetworkX graph 34 | 35 | nodes : list or iterable 36 | Nodes that must be part of the independent set. This set of nodes 37 | must be independent. 38 | 39 | Returns 40 | ------- 41 | indep_nodes : list 42 | List of nodes that are part of a maximal independent set. 43 | 44 | Raises 45 | ------ 46 | NetworkXUnfeasible 47 | If the nodes in the provided list are not part of the graph or 48 | do not form an independent set, an exception is raised. 49 | 50 | Examples 51 | -------- 52 | >>> G = nx.path_graph(5) 53 | >>> nx.maximal_independent_set(G) # doctest: +SKIP 54 | [4, 0, 2] 55 | >>> nx.maximal_independent_set(G, [1]) # doctest: +SKIP 56 | [1, 3] 57 | 58 | Notes 59 | ----- 60 | This algorithm does not solve the maximum independent set problem. 61 | 62 | """ 63 | if not nodes: 64 | nodes = set([random.choice(G.nodes())]) 65 | else: 66 | nodes = set(nodes) 67 | if not nodes.issubset(G): 68 | raise nx.NetworkXUnfeasible( 69 | "%s is not a subset of the nodes of G" % nodes) 70 | neighbors = set.union(*[set(G.neighbors(v)) for v in nodes]) 71 | if set.intersection(neighbors, nodes): 72 | raise nx.NetworkXUnfeasible( 73 | "%s is not an independent set of G" % nodes) 74 | indep_nodes = list(nodes) 75 | available_nodes = set(G.nodes()).difference(neighbors.union(nodes)) 76 | while available_nodes: 77 | node = random.choice(list(available_nodes)) 78 | indep_nodes.append(node) 79 | available_nodes.difference_update(G.neighbors(node) + [node]) 80 | return indep_nodes 81 | 82 | -------------------------------------------------------------------------------- /src/networkx/algorithms/assortativity/tests/test_neighbor_degree.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | 5 | class TestAverageNeighbor(object): 6 | 7 | def test_degree_p4(self): 8 | G=nx.path_graph(4) 9 | answer={0:2,1:1.5,2:1.5,3:2} 10 | nd = nx.average_neighbor_degree(G) 11 | assert_equal(nd,answer) 12 | 13 | D=G.to_directed() 14 | nd = nx.average_neighbor_degree(D) 15 | assert_equal(nd,answer) 16 | 17 | D=G.to_directed() 18 | nd = nx.average_neighbor_degree(D) 19 | assert_equal(nd,answer) 20 | 21 | D=G.to_directed() 22 | nd = nx.average_neighbor_degree(D, source='in', target='in') 23 | assert_equal(nd,answer) 24 | 25 | def test_degree_p4_weighted(self): 26 | G=nx.path_graph(4) 27 | G[1][2]['weight']=4 28 | answer={0:2,1:1.8,2:1.8,3:2} 29 | nd = nx.average_neighbor_degree(G,weight='weight') 30 | assert_equal(nd,answer) 31 | 32 | D=G.to_directed() 33 | nd = nx.average_neighbor_degree(D,weight='weight') 34 | assert_equal(nd,answer) 35 | 36 | D=G.to_directed() 37 | nd = nx.average_neighbor_degree(D,weight='weight') 38 | assert_equal(nd,answer) 39 | nd = nx.average_neighbor_degree(D,source='out',target='out', 40 | weight='weight') 41 | assert_equal(nd,answer) 42 | 43 | D=G.to_directed() 44 | nd = nx.average_neighbor_degree(D,source='in',target='in', 45 | weight='weight') 46 | assert_equal(nd,answer) 47 | 48 | 49 | def test_degree_k4(self): 50 | G=nx.complete_graph(4) 51 | answer={0:3,1:3,2:3,3:3} 52 | nd = nx.average_neighbor_degree(G) 53 | assert_equal(nd,answer) 54 | 55 | D=G.to_directed() 56 | nd = nx.average_neighbor_degree(D) 57 | assert_equal(nd,answer) 58 | 59 | D=G.to_directed() 60 | nd = nx.average_neighbor_degree(D) 61 | assert_equal(nd,answer) 62 | 63 | D=G.to_directed() 64 | nd = nx.average_neighbor_degree(D,source='in',target='in') 65 | assert_equal(nd,answer) 66 | 67 | def test_degree_k4_nodes(self): 68 | G=nx.complete_graph(4) 69 | answer={1:3.0,2:3.0} 70 | nd = nx.average_neighbor_degree(G,nodes=[1,2]) 71 | assert_equal(nd,answer) 72 | 73 | def test_degree_barrat(self): 74 | G=nx.star_graph(5) 75 | G.add_edges_from([(5,6),(5,7),(5,8),(5,9)]) 76 | G[0][5]['weight']=5 77 | nd = nx.average_neighbor_degree(G)[5] 78 | assert_equal(nd,1.8) 79 | nd = nx.average_neighbor_degree(G,weight='weight')[5] 80 | assert_almost_equal(nd,3.222222,places=5) 81 | 82 | 83 | -------------------------------------------------------------------------------- /src/networkx/utils/union_find.py: -------------------------------------------------------------------------------- 1 | """ 2 | Union-find data structure. 3 | """ 4 | # Copyright (C) 2004-2015 by 5 | # Aric Hagberg 6 | # Dan Schult 7 | # Pieter Swart 8 | # All rights reserved. 9 | # BSD license. 10 | 11 | 12 | class UnionFind: 13 | """Union-find data structure. 14 | 15 | Each unionFind instance X maintains a family of disjoint sets of 16 | hashable objects, supporting the following two methods: 17 | 18 | - X[item] returns a name for the set containing the given item. 19 | Each set is named by an arbitrarily-chosen one of its members; as 20 | long as the set remains unchanged it will keep the same name. If 21 | the item is not yet part of a set in X, a new singleton set is 22 | created for it. 23 | 24 | - X.union(item1, item2, ...) merges the sets containing each item 25 | into a single larger set. If any item is not yet part of a set 26 | in X, it is added to X as one of the members of the merged set. 27 | 28 | Union-find data structure. Based on Josiah Carlson's code, 29 | http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/215912 30 | with significant additional changes by D. Eppstein. 31 | http://www.ics.uci.edu/~eppstein/PADS/UnionFind.py 32 | 33 | """ 34 | 35 | def __init__(self): 36 | """Create a new empty union-find structure.""" 37 | self.weights = {} 38 | self.parents = {} 39 | 40 | def __getitem__(self, object): 41 | """Find and return the name of the set containing the object.""" 42 | 43 | # check for previously unknown object 44 | if object not in self.parents: 45 | self.parents[object] = object 46 | self.weights[object] = 1 47 | return object 48 | 49 | # find path of objects leading to the root 50 | path = [object] 51 | root = self.parents[object] 52 | while root != path[-1]: 53 | path.append(root) 54 | root = self.parents[root] 55 | 56 | # compress the path and return 57 | for ancestor in path: 58 | self.parents[ancestor] = root 59 | return root 60 | 61 | def __iter__(self): 62 | """Iterate through all items ever found or unioned by this structure. 63 | 64 | """ 65 | return iter(self.parents) 66 | 67 | def union(self, *objects): 68 | """Find the sets containing the objects and merge them all.""" 69 | roots = [self[x] for x in objects] 70 | # Find the heaviest root according to its weight. 71 | heaviest = max(roots, key=lambda r: self.weights[r]) 72 | for r in roots: 73 | if r != heaviest: 74 | self.weights[heaviest] += self.weights[r] 75 | self.parents[r] = heaviest 76 | -------------------------------------------------------------------------------- /src/networkx/algorithms/vitality.py: -------------------------------------------------------------------------------- 1 | """ 2 | Vitality measures. 3 | """ 4 | # Copyright (C) 2012 by 5 | # Aric Hagberg 6 | # Dan Schult 7 | # Pieter Swart 8 | # All rights reserved. 9 | # BSD license. 10 | import networkx as nx 11 | __author__ = "\n".join(['Aric Hagberg (hagberg@lanl.gov)', 12 | 'Renato Fabbri']) 13 | __all__ = ['closeness_vitality'] 14 | 15 | def weiner_index(G, weight=None): 16 | # compute sum of distances between all node pairs 17 | # (with optional weights) 18 | weiner=0.0 19 | if weight is None: 20 | for n in G: 21 | path_length=nx.single_source_shortest_path_length(G,n) 22 | weiner+=sum(path_length.values()) 23 | else: 24 | for n in G: 25 | path_length=nx.single_source_dijkstra_path_length(G, 26 | n,weight=weight) 27 | weiner+=sum(path_length.values()) 28 | return weiner 29 | 30 | 31 | def closeness_vitality(G, weight=None): 32 | """Compute closeness vitality for nodes. 33 | 34 | Closeness vitality of a node is the change in the sum of distances 35 | between all node pairs when excluding that node. 36 | 37 | Parameters 38 | ---------- 39 | G : graph 40 | 41 | weight : None or string (optional) 42 | The name of the edge attribute used as weight. If None the edge 43 | weights are ignored. 44 | 45 | Returns 46 | ------- 47 | nodes : dictionary 48 | Dictionary with nodes as keys and closeness vitality as the value. 49 | 50 | Examples 51 | -------- 52 | >>> G=nx.cycle_graph(3) 53 | >>> nx.closeness_vitality(G) 54 | {0: 4.0, 1: 4.0, 2: 4.0} 55 | 56 | See Also 57 | -------- 58 | closeness_centrality() 59 | 60 | References 61 | ---------- 62 | .. [1] Ulrik Brandes, Sec. 3.6.2 in 63 | Network Analysis: Methodological Foundations, Springer, 2005. 64 | http://books.google.com/books?id=TTNhSm7HYrIC 65 | """ 66 | multigraph = G.is_multigraph() 67 | wig = weiner_index(G,weight) 68 | closeness_vitality = {} 69 | for n in G: 70 | # remove edges connected to node n and keep list of edges with data 71 | # could remove node n but it doesn't count anyway 72 | if multigraph: 73 | edges = G.edges(n,data=True,keys=True) 74 | if G.is_directed(): 75 | edges += G.in_edges(n,data=True,keys=True) 76 | else: 77 | edges = G.edges(n,data=True) 78 | if G.is_directed(): 79 | edges += G.in_edges(n,data=True) 80 | G.remove_edges_from(edges) 81 | closeness_vitality[n] = wig - weiner_index(G,weight) 82 | # add edges and data back to graph 83 | G.add_edges_from(edges) 84 | return closeness_vitality 85 | -------------------------------------------------------------------------------- /src/networkx/algorithms/bipartite/spectral.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Spectral bipartivity measure. 4 | """ 5 | import networkx as nx 6 | __author__ = """Aric Hagberg (hagberg@lanl.gov)""" 7 | # Copyright (C) 2011 by 8 | # Aric Hagberg 9 | # Dan Schult 10 | # Pieter Swart 11 | # All rights reserved. 12 | # BSD license. 13 | __all__ = ['spectral_bipartivity'] 14 | 15 | def spectral_bipartivity(G, nodes=None, weight='weight'): 16 | """Returns the spectral bipartivity. 17 | 18 | Parameters 19 | ---------- 20 | G : NetworkX graph 21 | 22 | nodes : list or container optional(default is all nodes) 23 | Nodes to return value of spectral bipartivity contribution. 24 | 25 | weight : string or None optional (default = 'weight') 26 | Edge data key to use for edge weights. If None, weights set to 1. 27 | 28 | Returns 29 | ------- 30 | sb : float or dict 31 | A single number if the keyword nodes is not specified, or 32 | a dictionary keyed by node with the spectral bipartivity contribution 33 | of that node as the value. 34 | 35 | Examples 36 | -------- 37 | >>> from networkx.algorithms import bipartite 38 | >>> G = nx.path_graph(4) 39 | >>> bipartite.spectral_bipartivity(G) 40 | 1.0 41 | 42 | Notes 43 | ----- 44 | This implementation uses Numpy (dense) matrices which are not efficient 45 | for storing large sparse graphs. 46 | 47 | See Also 48 | -------- 49 | color 50 | 51 | References 52 | ---------- 53 | .. [1] E. Estrada and J. A. Rodríguez-Velázquez, "Spectral measures of 54 | bipartivity in complex networks", PhysRev E 72, 046105 (2005) 55 | """ 56 | try: 57 | import scipy.linalg 58 | except ImportError: 59 | raise ImportError('spectral_bipartivity() requires SciPy: ', 60 | 'http://scipy.org/') 61 | nodelist = G.nodes() # ordering of nodes in matrix 62 | A = nx.to_numpy_matrix(G, nodelist, weight=weight) 63 | expA = scipy.linalg.expm(A) 64 | expmA = scipy.linalg.expm(-A) 65 | coshA = 0.5 * (expA + expmA) 66 | if nodes is None: 67 | # return single number for entire graph 68 | return coshA.diagonal().sum() / expA.diagonal().sum() 69 | else: 70 | # contribution for individual nodes 71 | index = dict(zip(nodelist, range(len(nodelist)))) 72 | sb = {} 73 | for n in nodes: 74 | i = index[n] 75 | sb[n] = coshA[i, i] / expA[i, i] 76 | return sb 77 | 78 | def setup_module(module): 79 | """Fixture for nose tests.""" 80 | from nose import SkipTest 81 | try: 82 | import numpy 83 | except: 84 | raise SkipTest("NumPy not available") 85 | try: 86 | import scipy 87 | except: 88 | raise SkipTest("SciPy not available") 89 | -------------------------------------------------------------------------------- /src/networkx/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | NetworkX 3 | ======== 4 | 5 | NetworkX (NX) is a Python package for the creation, manipulation, and 6 | study of the structure, dynamics, and functions of complex networks. 7 | 8 | https://networkx.lanl.gov/ 9 | 10 | Using 11 | ----- 12 | 13 | Just write in Python 14 | 15 | >>> import networkx as nx 16 | >>> G=nx.Graph() 17 | >>> G.add_edge(1,2) 18 | >>> G.add_node(42) 19 | >>> print(sorted(G.nodes())) 20 | [1, 2, 42] 21 | >>> print(sorted(G.edges())) 22 | [(1, 2)] 23 | """ 24 | # Copyright (C) 2004-2015 by 25 | # Aric Hagberg 26 | # Dan Schult 27 | # Pieter Swart 28 | # All rights reserved. 29 | # BSD license. 30 | # 31 | # Add platform dependent shared library path to sys.path 32 | # 33 | 34 | from __future__ import absolute_import 35 | 36 | import sys 37 | if sys.version_info[:2] < (2, 7): 38 | m = "Python 2.7 or later is required for NetworkX (%d.%d detected)." 39 | raise ImportError(m % sys.version_info[:2]) 40 | del sys 41 | 42 | # Release data 43 | from networkx import release 44 | 45 | __author__ = '%s <%s>\n%s <%s>\n%s <%s>' % \ 46 | (release.authors['Hagberg'] + release.authors['Schult'] + 47 | release.authors['Swart']) 48 | __license__ = release.license 49 | 50 | __date__ = release.date 51 | __version__ = release.version 52 | 53 | __bibtex__ = """@inproceedings{hagberg-2008-exploring, 54 | author = {Aric A. Hagberg and Daniel A. Schult and Pieter J. Swart}, 55 | title = {Exploring network structure, dynamics, and function using {NetworkX}}, 56 | year = {2008}, 57 | month = Aug, 58 | urlpdf = {http://math.lanl.gov/~hagberg/Papers/hagberg-2008-exploring.pdf}, 59 | booktitle = {Proceedings of the 7th Python in Science Conference (SciPy2008)}, 60 | editors = {G\"{a}el Varoquaux, Travis Vaught, and Jarrod Millman}, 61 | address = {Pasadena, CA USA}, 62 | pages = {11--15} 63 | }""" 64 | 65 | # These are import orderwise 66 | from networkx.exception import * 67 | import networkx.external 68 | import networkx.utils 69 | 70 | import networkx.classes 71 | from networkx.classes import * 72 | 73 | 74 | import networkx.convert 75 | from networkx.convert import * 76 | 77 | import networkx.convert_matrix 78 | from networkx.convert_matrix import * 79 | 80 | 81 | import networkx.relabel 82 | from networkx.relabel import * 83 | 84 | import networkx.generators 85 | from networkx.generators import * 86 | 87 | import networkx.readwrite 88 | from networkx.readwrite import * 89 | 90 | # Need to test with SciPy, when available 91 | import networkx.algorithms 92 | from networkx.algorithms import * 93 | import networkx.linalg 94 | 95 | from networkx.linalg import * 96 | from networkx.tests.test import run as test 97 | 98 | import networkx.drawing 99 | from networkx.drawing import * 100 | -------------------------------------------------------------------------------- /src/networkx/algorithms/bipartite/tests/test_spectral_bipartivity.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from nose import SkipTest 3 | from nose.tools import * 4 | import networkx as nx 5 | from networkx.algorithms.bipartite import spectral_bipartivity as sb 6 | 7 | # Examples from Figure 1 8 | # E. Estrada and J. A. Rodríguez-Velázquez, "Spectral measures of 9 | # bipartivity in complex networks", PhysRev E 72, 046105 (2005) 10 | 11 | class TestSpectralBipartivity(object): 12 | @classmethod 13 | def setupClass(cls): 14 | global scipy 15 | global assert_equal 16 | global assert_almost_equal 17 | try: 18 | import scipy.linalg 19 | except ImportError: 20 | raise SkipTest('SciPy not available.') 21 | 22 | 23 | def test_star_like(self): 24 | # star-like 25 | 26 | G=nx.star_graph(2) 27 | G.add_edge(1,2) 28 | assert_almost_equal(sb(G),0.843,places=3) 29 | 30 | G=nx.star_graph(3) 31 | G.add_edge(1,2) 32 | assert_almost_equal(sb(G),0.871,places=3) 33 | 34 | G=nx.star_graph(4) 35 | G.add_edge(1,2) 36 | assert_almost_equal(sb(G),0.890,places=3) 37 | 38 | 39 | def k23_like(self): 40 | # K2,3-like 41 | G=nx.complete_bipartite_graph(2,3) 42 | G.add_edge(0,1) 43 | assert_almost_equal(sb(G),0.769,places=3) 44 | 45 | G=nx.complete_bipartite_graph(2,3) 46 | G.add_edge(2,4) 47 | assert_almost_equal(sb(G),0.829,places=3) 48 | 49 | G=nx.complete_bipartite_graph(2,3) 50 | G.add_edge(2,4) 51 | G.add_edge(3,4) 52 | assert_almost_equal(sb(G),0.731,places=3) 53 | 54 | 55 | G=nx.complete_bipartite_graph(2,3) 56 | G.add_edge(0,1) 57 | G.add_edge(2,4) 58 | assert_almost_equal(sb(G),0.692,places=3) 59 | 60 | G=nx.complete_bipartite_graph(2,3) 61 | G.add_edge(2,4) 62 | G.add_edge(3,4) 63 | G.add_edge(0,1) 64 | assert_almost_equal(sb(G),0.645,places=3) 65 | 66 | G=nx.complete_bipartite_graph(2,3) 67 | G.add_edge(2,4) 68 | G.add_edge(3,4) 69 | G.add_edge(2,3) 70 | assert_almost_equal(sb(G),0.645,places=3) 71 | 72 | G=nx.complete_bipartite_graph(2,3) 73 | G.add_edge(2,4) 74 | G.add_edge(3,4) 75 | G.add_edge(2,3) 76 | G.add_edge(0,1) 77 | assert_almost_equal(sb(G),0.597,places=3) 78 | 79 | def test_single_nodes(self): 80 | 81 | # single nodes 82 | G=nx.complete_bipartite_graph(2, 3) 83 | G.add_edge(2,4) 84 | sbn=sb(G,nodes=[1,2]) 85 | assert_almost_equal(sbn[1],0.85,places=2) 86 | assert_almost_equal(sbn[2],0.77,places=2) 87 | 88 | G=nx.complete_bipartite_graph(2,3) 89 | G.add_edge(0,1) 90 | sbn=sb(G,nodes=[1,2]) 91 | assert_almost_equal(sbn[1],0.73,places=2) 92 | assert_almost_equal(sbn[2],0.82,places=2) 93 | 94 | -------------------------------------------------------------------------------- /src/networkx/algorithms/link_analysis/tests/test_hits.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | from nose import SkipTest 4 | from nose.plugins.attrib import attr 5 | import networkx 6 | 7 | # Example from 8 | # A. Langville and C. Meyer, "A survey of eigenvector methods of web 9 | # information retrieval." http://citeseer.ist.psu.edu/713792.html 10 | 11 | 12 | class TestHITS: 13 | 14 | def setUp(self): 15 | 16 | G=networkx.DiGraph() 17 | 18 | edges=[(1,3),(1,5),\ 19 | (2,1),\ 20 | (3,5),\ 21 | (5,4),(5,3),\ 22 | (6,5)] 23 | 24 | G.add_edges_from(edges,weight=1) 25 | self.G=G 26 | self.G.a=dict(zip(G,[0.000000, 0.000000, 0.366025, 27 | 0.133975, 0.500000, 0.000000])) 28 | self.G.h=dict(zip(G,[ 0.366025, 0.000000, 0.211325, 29 | 0.000000, 0.211325, 0.211325])) 30 | 31 | 32 | def test_hits(self): 33 | G=self.G 34 | h,a=networkx.hits(G,tol=1.e-08) 35 | for n in G: 36 | assert_almost_equal(h[n],G.h[n],places=4) 37 | for n in G: 38 | assert_almost_equal(a[n],G.a[n],places=4) 39 | 40 | def test_hits_nstart(self): 41 | G = self.G 42 | nstart = dict([(i, 1./2) for i in G]) 43 | h, a = networkx.hits(G, nstart = nstart) 44 | 45 | @attr('numpy') 46 | def test_hits_numpy(self): 47 | try: 48 | import numpy as np 49 | except ImportError: 50 | raise SkipTest('NumPy not available.') 51 | 52 | 53 | G=self.G 54 | h,a=networkx.hits_numpy(G) 55 | for n in G: 56 | assert_almost_equal(h[n],G.h[n],places=4) 57 | for n in G: 58 | assert_almost_equal(a[n],G.a[n],places=4) 59 | 60 | 61 | def test_hits_scipy(self): 62 | try: 63 | import scipy as sp 64 | except ImportError: 65 | raise SkipTest('SciPy not available.') 66 | 67 | G=self.G 68 | h,a=networkx.hits_scipy(G,tol=1.e-08) 69 | for n in G: 70 | assert_almost_equal(h[n],G.h[n],places=4) 71 | for n in G: 72 | assert_almost_equal(a[n],G.a[n],places=4) 73 | 74 | 75 | @attr('numpy') 76 | def test_empty(self): 77 | try: 78 | import numpy 79 | except ImportError: 80 | raise SkipTest('numpy not available.') 81 | G=networkx.Graph() 82 | assert_equal(networkx.hits(G),({},{})) 83 | assert_equal(networkx.hits_numpy(G),({},{})) 84 | assert_equal(networkx.authority_matrix(G).shape,(0,0)) 85 | assert_equal(networkx.hub_matrix(G).shape,(0,0)) 86 | 87 | def test_empty_scipy(self): 88 | try: 89 | import scipy 90 | except ImportError: 91 | raise SkipTest('scipy not available.') 92 | G=networkx.Graph() 93 | assert_equal(networkx.hits_scipy(G),({},{})) 94 | -------------------------------------------------------------------------------- /src/networkx/algorithms/bipartite/tests/test_cluster.py: -------------------------------------------------------------------------------- 1 | import networkx as nx 2 | from nose.tools import * 3 | from networkx.algorithms.bipartite.cluster import cc_dot,cc_min,cc_max 4 | import networkx.algorithms.bipartite as bipartite 5 | 6 | def test_pairwise_bipartite_cc_functions(): 7 | # Test functions for different kinds of bipartite clustering coefficients 8 | # between pairs of nodes using 3 example graphs from figure 5 p. 40 9 | # Latapy et al (2008) 10 | G1 = nx.Graph([(0,2),(0,3),(0,4),(0,5),(0,6),(1,5),(1,6),(1,7)]) 11 | G2 = nx.Graph([(0,2),(0,3),(0,4),(1,3),(1,4),(1,5)]) 12 | G3 = nx.Graph([(0,2),(0,3),(0,4),(0,5),(0,6),(1,5),(1,6),(1,7),(1,8),(1,9)]) 13 | result = {0:[1/3.0, 2/3.0, 2/5.0], 14 | 1:[1/2.0, 2/3.0, 2/3.0], 15 | 2:[2/8.0, 2/5.0, 2/5.0]} 16 | for i, G in enumerate([G1, G2, G3]): 17 | assert(bipartite.is_bipartite(G)) 18 | assert(cc_dot(set(G[0]), set(G[1])) == result[i][0]) 19 | assert(cc_min(set(G[0]), set(G[1])) == result[i][1]) 20 | assert(cc_max(set(G[0]), set(G[1])) == result[i][2]) 21 | 22 | def test_star_graph(): 23 | G=nx.star_graph(3) 24 | # all modes are the same 25 | answer={0:0,1:1,2:1,3:1} 26 | assert_equal(bipartite.clustering(G,mode='dot'),answer) 27 | assert_equal(bipartite.clustering(G,mode='min'),answer) 28 | assert_equal(bipartite.clustering(G,mode='max'),answer) 29 | 30 | @raises(nx.NetworkXError) 31 | def test_not_bipartite(): 32 | bipartite.clustering(nx.complete_graph(4)) 33 | 34 | @raises(nx.NetworkXError) 35 | def test_bad_mode(): 36 | bipartite.clustering(nx.path_graph(4),mode='foo') 37 | 38 | def test_path_graph(): 39 | G=nx.path_graph(4) 40 | answer={0:0.5,1:0.5,2:0.5,3:0.5} 41 | assert_equal(bipartite.clustering(G,mode='dot'),answer) 42 | assert_equal(bipartite.clustering(G,mode='max'),answer) 43 | answer={0:1,1:1,2:1,3:1} 44 | assert_equal(bipartite.clustering(G,mode='min'),answer) 45 | 46 | def test_average_path_graph(): 47 | G=nx.path_graph(4) 48 | assert_equal(bipartite.average_clustering(G,mode='dot'),0.5) 49 | assert_equal(bipartite.average_clustering(G,mode='max'),0.5) 50 | assert_equal(bipartite.average_clustering(G,mode='min'),1) 51 | 52 | def test_ra_clustering_davis(): 53 | G = nx.davis_southern_women_graph() 54 | cc4 = round(bipartite.robins_alexander_clustering(G), 3) 55 | assert_equal(cc4, 0.468) 56 | 57 | def test_ra_clustering_square(): 58 | G = nx.path_graph(4) 59 | G.add_edge(0, 3) 60 | assert_equal(bipartite.robins_alexander_clustering(G), 1.0) 61 | 62 | def test_ra_clustering_zero(): 63 | G = nx.Graph() 64 | assert_equal(bipartite.robins_alexander_clustering(G), 0) 65 | G.add_nodes_from(range(4)) 66 | assert_equal(bipartite.robins_alexander_clustering(G), 0) 67 | G.add_edges_from([(0,1),(2,3),(3,4)]) 68 | assert_equal(bipartite.robins_alexander_clustering(G), 0) 69 | G.add_edge(1,2) 70 | assert_equal(bipartite.robins_alexander_clustering(G), 0) 71 | -------------------------------------------------------------------------------- /src/networkx/algorithms/community/kclique.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | # Copyright (C) 2011 by 3 | # Conrad Lee 4 | # Aric Hagberg 5 | # All rights reserved. 6 | # BSD license. 7 | from collections import defaultdict 8 | import networkx as nx 9 | __author__ = """\n""".join(['Conrad Lee ', 10 | 'Aric Hagberg ']) 11 | __all__ = ['k_clique_communities'] 12 | 13 | def k_clique_communities(G, k, cliques=None): 14 | """Find k-clique communities in graph using the percolation method. 15 | 16 | A k-clique community is the union of all cliques of size k that 17 | can be reached through adjacent (sharing k-1 nodes) k-cliques. 18 | 19 | Parameters 20 | ---------- 21 | G : NetworkX graph 22 | 23 | k : int 24 | Size of smallest clique 25 | 26 | cliques: list or generator 27 | Precomputed cliques (use networkx.find_cliques(G)) 28 | 29 | Returns 30 | ------- 31 | Yields sets of nodes, one for each k-clique community. 32 | 33 | Examples 34 | -------- 35 | >>> G = nx.complete_graph(5) 36 | >>> K5 = nx.convert_node_labels_to_integers(G,first_label=2) 37 | >>> G.add_edges_from(K5.edges()) 38 | >>> c = list(nx.k_clique_communities(G, 4)) 39 | >>> list(c[0]) 40 | [0, 1, 2, 3, 4, 5, 6] 41 | >>> list(nx.k_clique_communities(G, 6)) 42 | [] 43 | 44 | References 45 | ---------- 46 | .. [1] Gergely Palla, Imre Derényi, Illés Farkas1, and Tamás Vicsek, 47 | Uncovering the overlapping community structure of complex networks 48 | in nature and society Nature 435, 814-818, 2005, 49 | doi:10.1038/nature03607 50 | """ 51 | if k < 2: 52 | raise nx.NetworkXError("k=%d, k must be greater than 1."%k) 53 | if cliques is None: 54 | cliques = nx.find_cliques(G) 55 | cliques = [frozenset(c) for c in cliques if len(c) >= k] 56 | 57 | # First index which nodes are in which cliques 58 | membership_dict = defaultdict(list) 59 | for clique in cliques: 60 | for node in clique: 61 | membership_dict[node].append(clique) 62 | 63 | # For each clique, see which adjacent cliques percolate 64 | perc_graph = nx.Graph() 65 | perc_graph.add_nodes_from(cliques) 66 | for clique in cliques: 67 | for adj_clique in _get_adjacent_cliques(clique, membership_dict): 68 | if len(clique.intersection(adj_clique)) >= (k - 1): 69 | perc_graph.add_edge(clique, adj_clique) 70 | 71 | # Connected components of clique graph with perc edges 72 | # are the percolated cliques 73 | for component in nx.connected_components(perc_graph): 74 | yield(frozenset.union(*component)) 75 | 76 | def _get_adjacent_cliques(clique, membership_dict): 77 | adjacent_cliques = set() 78 | for n in clique: 79 | for adj_clique in membership_dict[n]: 80 | if clique != adj_clique: 81 | adjacent_cliques.add(adj_clique) 82 | return adjacent_cliques 83 | -------------------------------------------------------------------------------- /src/networkx/readwrite/nx_yaml.py: -------------------------------------------------------------------------------- 1 | """ 2 | **** 3 | YAML 4 | **** 5 | Read and write NetworkX graphs in YAML format. 6 | 7 | "YAML is a data serialization format designed for human readability 8 | and interaction with scripting languages." 9 | See http://www.yaml.org for documentation. 10 | 11 | Format 12 | ------ 13 | http://pyyaml.org/wiki/PyYAML 14 | 15 | """ 16 | __author__ = """Aric Hagberg (hagberg@lanl.gov)""" 17 | # Copyright (C) 2004-2015 by 18 | # Aric Hagberg 19 | # Dan Schult 20 | # Pieter Swart 21 | # All rights reserved. 22 | # BSD license. 23 | 24 | __all__ = ['read_yaml', 'write_yaml'] 25 | 26 | import networkx as nx 27 | from networkx.utils import open_file 28 | 29 | @open_file(1,mode='w') 30 | def write_yaml(G, path, encoding='UTF-8', **kwds): 31 | """Write graph G in YAML format to path. 32 | 33 | YAML is a data serialization format designed for human readability 34 | and interaction with scripting languages [1]_. 35 | 36 | Parameters 37 | ---------- 38 | G : graph 39 | A NetworkX graph 40 | path : file or string 41 | File or filename to write. 42 | Filenames ending in .gz or .bz2 will be compressed. 43 | encoding: string, optional 44 | Specify which encoding to use when writing file. 45 | 46 | Examples 47 | -------- 48 | >>> G=nx.path_graph(4) 49 | >>> nx.write_yaml(G,'test.yaml') 50 | 51 | References 52 | ---------- 53 | .. [1] http://www.yaml.org 54 | """ 55 | try: 56 | import yaml 57 | except ImportError: 58 | raise ImportError("write_yaml() requires PyYAML: http://pyyaml.org/") 59 | yaml.dump(G, path, **kwds) 60 | 61 | @open_file(0,mode='r') 62 | def read_yaml(path): 63 | """Read graph in YAML format from path. 64 | 65 | YAML is a data serialization format designed for human readability 66 | and interaction with scripting languages [1]_. 67 | 68 | Parameters 69 | ---------- 70 | path : file or string 71 | File or filename to read. Filenames ending in .gz or .bz2 72 | will be uncompressed. 73 | 74 | Returns 75 | ------- 76 | G : NetworkX graph 77 | 78 | Examples 79 | -------- 80 | >>> G=nx.path_graph(4) 81 | >>> nx.write_yaml(G,'test.yaml') 82 | >>> G=nx.read_yaml('test.yaml') 83 | 84 | References 85 | ---------- 86 | .. [1] http://www.yaml.org 87 | 88 | """ 89 | try: 90 | import yaml 91 | except ImportError: 92 | raise ImportError("read_yaml() requires PyYAML: http://pyyaml.org/") 93 | 94 | G=yaml.load(path) 95 | return G 96 | 97 | 98 | # fixture for nose tests 99 | def setup_module(module): 100 | from nose import SkipTest 101 | try: 102 | import yaml 103 | except: 104 | raise SkipTest("PyYAML not available") 105 | 106 | # fixture for nose tests 107 | def teardown_module(module): 108 | import os 109 | os.unlink('test.yaml') 110 | -------------------------------------------------------------------------------- /src/networkx/algorithms/boundary.py: -------------------------------------------------------------------------------- 1 | """ 2 | Routines to find the boundary of a set of nodes. 3 | 4 | Edge boundaries are edges that have only one end 5 | in the set of nodes. 6 | 7 | Node boundaries are nodes outside the set of nodes 8 | that have an edge to a node in the set. 9 | 10 | """ 11 | __author__ = """Aric Hagberg (hagberg@lanl.gov)\nPieter Swart (swart@lanl.gov)\nDan Schult (dschult@colgate.edu)""" 12 | # Copyright (C) 2004-2015 by 13 | # Aric Hagberg 14 | # Dan Schult 15 | # Pieter Swart 16 | # All rights reserved. 17 | # BSD license. 18 | 19 | __all__=['edge_boundary','node_boundary'] 20 | 21 | def edge_boundary(G, nbunch1, nbunch2=None): 22 | """Return the edge boundary. 23 | 24 | Edge boundaries are edges that have only one end 25 | in the given set of nodes. 26 | 27 | Parameters 28 | ---------- 29 | G : graph 30 | A networkx graph 31 | 32 | nbunch1 : list, container 33 | Interior node set 34 | 35 | nbunch2 : list, container 36 | Exterior node set. If None then it is set to all of the 37 | nodes in G not in nbunch1. 38 | 39 | Returns 40 | ------- 41 | elist : list 42 | List of edges 43 | 44 | Notes 45 | ----- 46 | Nodes in nbunch1 and nbunch2 that are not in G are ignored. 47 | 48 | nbunch1 and nbunch2 are usually meant to be disjoint, 49 | but in the interest of speed and generality, that is 50 | not required here. 51 | 52 | """ 53 | if nbunch2 is None: # Then nbunch2 is complement of nbunch1 54 | nset1=set((n for n in nbunch1 if n in G)) 55 | return [(n1,n2) for n1 in nset1 for n2 in G[n1] \ 56 | if n2 not in nset1] 57 | 58 | nset2=set(nbunch2) 59 | return [(n1,n2) for n1 in nbunch1 if n1 in G for n2 in G[n1] \ 60 | if n2 in nset2] 61 | 62 | def node_boundary(G, nbunch1, nbunch2=None): 63 | """Return the node boundary. 64 | 65 | The node boundary is all nodes in the edge boundary of a given 66 | set of nodes that are in the set. 67 | 68 | Parameters 69 | ---------- 70 | G : graph 71 | A networkx graph 72 | 73 | nbunch1 : list, container 74 | Interior node set 75 | 76 | nbunch2 : list, container 77 | Exterior node set. If None then it is set to all of the 78 | nodes in G not in nbunch1. 79 | 80 | Returns 81 | ------- 82 | nlist : list 83 | List of nodes. 84 | 85 | Notes 86 | ----- 87 | Nodes in nbunch1 and nbunch2 that are not in G are ignored. 88 | 89 | nbunch1 and nbunch2 are usually meant to be disjoint, 90 | but in the interest of speed and generality, that is 91 | not required here. 92 | 93 | """ 94 | nset1=set(n for n in nbunch1 if n in G) 95 | bdy=set() 96 | for n1 in nset1: 97 | bdy.update(G[n1]) 98 | bdy -= nset1 99 | if nbunch2 is not None: # else nbunch2 is complement of nbunch1 100 | bdy &= set(nbunch2) 101 | return list(bdy) 102 | 103 | -------------------------------------------------------------------------------- /src/networkx/algorithms/centrality/tests/test_closeness_centrality.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tests for degree centrality. 3 | """ 4 | from nose.tools import * 5 | import networkx as nx 6 | 7 | class TestClosenessCentrality: 8 | def setUp(self): 9 | 10 | self.K = nx.krackhardt_kite_graph() 11 | self.P3 = nx.path_graph(3) 12 | self.P4 = nx.path_graph(4) 13 | self.K5 = nx.complete_graph(5) 14 | 15 | self.C4=nx.cycle_graph(4) 16 | self.T=nx.balanced_tree(r=2, h=2) 17 | self.Gb = nx.Graph() 18 | self.Gb.add_edges_from([(0,1), (0,2), (1,3), (2,3), 19 | (2,4), (4,5), (3,5)]) 20 | 21 | 22 | F = nx.florentine_families_graph() 23 | self.F = F 24 | 25 | 26 | def test_k5_closeness(self): 27 | c=nx.closeness_centrality(self.K5) 28 | d={0: 1.000, 29 | 1: 1.000, 30 | 2: 1.000, 31 | 3: 1.000, 32 | 4: 1.000} 33 | for n in sorted(self.K5): 34 | assert_almost_equal(c[n],d[n],places=3) 35 | 36 | def test_p3_closeness(self): 37 | c=nx.closeness_centrality(self.P3) 38 | d={0: 0.667, 39 | 1: 1.000, 40 | 2: 0.667} 41 | for n in sorted(self.P3): 42 | assert_almost_equal(c[n],d[n],places=3) 43 | 44 | def test_krackhardt_closeness(self): 45 | c=nx.closeness_centrality(self.K) 46 | d={0: 0.529, 47 | 1: 0.529, 48 | 2: 0.500, 49 | 3: 0.600, 50 | 4: 0.500, 51 | 5: 0.643, 52 | 6: 0.643, 53 | 7: 0.600, 54 | 8: 0.429, 55 | 9: 0.310} 56 | for n in sorted(self.K): 57 | assert_almost_equal(c[n],d[n],places=3) 58 | 59 | def test_florentine_families_closeness(self): 60 | c=nx.closeness_centrality(self.F) 61 | d={'Acciaiuoli': 0.368, 62 | 'Albizzi': 0.483, 63 | 'Barbadori': 0.4375, 64 | 'Bischeri': 0.400, 65 | 'Castellani': 0.389, 66 | 'Ginori': 0.333, 67 | 'Guadagni': 0.467, 68 | 'Lamberteschi': 0.326, 69 | 'Medici': 0.560, 70 | 'Pazzi': 0.286, 71 | 'Peruzzi': 0.368, 72 | 'Ridolfi': 0.500, 73 | 'Salviati': 0.389, 74 | 'Strozzi': 0.4375, 75 | 'Tornabuoni': 0.483} 76 | for n in sorted(self.F): 77 | assert_almost_equal(c[n],d[n],places=3) 78 | 79 | def test_weighted_closeness(self): 80 | XG=nx.Graph() 81 | XG.add_weighted_edges_from([('s','u',10), ('s','x',5), ('u','v',1), 82 | ('u','x',2), ('v','y',1), ('x','u',3), 83 | ('x','v',5), ('x','y',2), ('y','s',7), 84 | ('y','v',6)]) 85 | c=nx.closeness_centrality(XG,distance='weight') 86 | d={'y': 0.200, 87 | 'x': 0.286, 88 | 's': 0.138, 89 | 'u': 0.235, 90 | 'v': 0.200} 91 | for n in sorted(XG): 92 | assert_almost_equal(c[n],d[n],places=3) 93 | 94 | -------------------------------------------------------------------------------- /src/TspPainter.py: -------------------------------------------------------------------------------- 1 | from graphics import * 2 | import random 3 | 4 | class TspPainter: 5 | def __init__(self): 6 | self.win = GraphWin('TSP', 500, 500) 7 | self.win.setCoords(0, 0, 80, 80) 8 | self.win.width = 100 9 | self.coord_mat = None 10 | self.nodes = [] 11 | self.lockers = [] 12 | self.paths = [] 13 | 14 | def reset(self): 15 | for pt in self.nodes: 16 | self.win.delete(pt) 17 | self.nodes = [] 18 | for locker in self.lockers: 19 | self.win.delete(locker) 20 | self.lockers = [] 21 | for path in self.paths: 22 | self.win.delete(path) 23 | self.paths = [] 24 | 25 | def drawMap(self): 26 | self.reset() 27 | coord_mat = self.coord_mat 28 | for coord in coord_mat: 29 | pt = Point(coord[0], coord[1]) 30 | cir = Circle(pt, 0.5) 31 | cir.setFill("black") 32 | cir.setOutline("black") 33 | cir.draw(self.win) 34 | self.nodes.append(cir) 35 | 36 | def drawLockers(self, lockers): 37 | for locker in lockers: 38 | pt = Point(self.coord_mat[locker.pos][0], self.coord_mat[locker.pos][1]) 39 | cir = Circle(pt, 0.5) 40 | cir.setFill("red") 41 | cir.setOutline("red") 42 | cir.draw(self.win) 43 | self.lockers.append(cir) 44 | 45 | def drawDeliver(self, delivers): 46 | for deliver in delivers: 47 | pt = Point(self.coord_mat[deliver.pos][0], self.coord_mat[deliver.pos][1]) 48 | cir = Circle(pt, 0.5) 49 | cir.setFill("green") 50 | cir.setOutline("green") 51 | cir.draw(self.win) 52 | self.lockers.append(cir) 53 | 54 | def drawRoutes(self, routes): 55 | for key in routes: 56 | color = color_rgb(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) 57 | self.drawPath(routes[key], color) 58 | 59 | def drawPath(self, path, color): 60 | for i in range(0, len(path) ): 61 | i1 = i % len(path) 62 | i2 = (i + 1) % len(path) 63 | pack1 = path[i1] 64 | pack2 = path[i2] 65 | pt1 = Point(self.coord_mat[pack1.pos][0], self.coord_mat[pack1.pos][1]) 66 | pt2 = Point(self.coord_mat[pack2.pos][0], self.coord_mat[pack2.pos][1]) 67 | line = Line(pt1, pt2) 68 | line.setFill(color) 69 | line.setOutline(color) 70 | line.draw(self.win) 71 | self.paths.append(line) 72 | 73 | def drawPathX(self, x, n, k, color): 74 | for i in range(n): 75 | for j in range(i + 1): 76 | if x[i, j, k].X > 0.5: 77 | pt1 = Point(self.coord_mat[i][0], self.coord_mat[i][1]) 78 | pt2 = Point(self.coord_mat[j][0], self.coord_mat[j][1]) 79 | line = Line(pt1, pt2) 80 | line.setFill(color) 81 | line.setOutline(color) 82 | line.draw(self.win) 83 | self.paths.append(line) 84 | 85 | tspPainter = TspPainter() 86 | --------------------------------------------------------------------------------