├── .gitignore ├── .gitmodules ├── .travis.yml ├── LICENSE ├── README.md ├── appengine ├── app.yaml ├── css │ ├── bootstrap.min.css │ ├── codemirror.css │ ├── github.css │ ├── layout.css │ ├── perfenforce.css │ ├── queryvis.css │ ├── select2-bootstrap.css │ ├── select2.css │ └── solarized.css ├── data │ ├── histogram_4_0.csv │ ├── histogram_4_1.csv │ ├── histogram_4_2.csv │ ├── histogram_4_3.csv │ ├── profiling_4_0.csv │ ├── profiling_4_1.csv │ ├── profiling_4_2.csv │ ├── profiling_4_3.csv │ ├── sent_4_0.csv │ ├── sent_4_1.csv │ └── sent_4_2.csv ├── dateutil ├── demo3_examples.py ├── examples ├── examples.py ├── fonts │ ├── glyphicons-halflings-regular.eot │ ├── glyphicons-halflings-regular.svg │ ├── glyphicons-halflings-regular.ttf │ └── glyphicons-halflings-regular.woff ├── img │ ├── myria-logo.svg │ ├── select2-spinner.gif │ ├── select2.png │ └── select2x2.png ├── js │ ├── angular.min.js │ ├── bootstrap.min.js │ ├── chroma.js │ ├── chroma.min.js │ ├── codemirror.js │ ├── colorbrewer.js │ ├── colorlegend.js │ ├── d3.js │ ├── d3.min.js │ ├── d3.selection.popover.js │ ├── d3.selection.tooltip.js │ ├── editor.js │ ├── fragmentoverview.js │ ├── fragmentvis.js │ ├── graph.js │ ├── jquery-2.1.1.min.js │ ├── jquery-2.1.1.min.map │ ├── jquery.panzoom.js │ ├── jquery.panzoom.min.js │ ├── jquery.tablesorter.min.js │ ├── jquery.timeago.js │ ├── lodash.min.js │ ├── main.js │ ├── myrial.js │ ├── networkvis.js │ ├── operatorvis.js │ ├── perfenforce.js │ ├── prolog.js │ ├── queries.js │ ├── querystats.js │ ├── queryvis.js │ ├── runmode.js │ ├── select2.min.js │ ├── sql.js │ ├── svg-crowbar.js │ ├── underscore-min.js │ ├── underscore-min.map │ └── viz.js ├── jupyter_not_found.txt ├── myria ├── myria_web_main.py ├── networkx │ ├── __init__.py │ ├── algorithms │ │ ├── __init__.py │ │ ├── assortativity │ │ │ ├── __init__.py │ │ │ ├── connectivity.py │ │ │ ├── correlation.py │ │ │ ├── mixing.py │ │ │ ├── neighbor_degree.py │ │ │ ├── pairs.py │ │ │ └── tests │ │ │ │ ├── base_test.py │ │ │ │ ├── test_connectivity.py │ │ │ │ ├── test_correlation.py │ │ │ │ ├── test_mixing.py │ │ │ │ ├── test_neighbor_degree.py │ │ │ │ └── test_pairs.py │ │ ├── bipartite │ │ │ ├── __init__.py │ │ │ ├── basic.py │ │ │ ├── centrality.py │ │ │ ├── cluster.py │ │ │ ├── projection.py │ │ │ ├── redundancy.py │ │ │ ├── spectral.py │ │ │ └── tests │ │ │ │ ├── test_basic.py │ │ │ │ ├── test_centrality.py │ │ │ │ ├── test_cluster.py │ │ │ │ ├── test_project.py │ │ │ │ └── test_spectral_bipartivity.py │ │ ├── block.py │ │ ├── boundary.py │ │ ├── centrality │ │ │ ├── __init__.py │ │ │ ├── betweenness.py │ │ │ ├── betweenness_subset.py │ │ │ ├── closeness.py │ │ │ ├── communicability_alg.py │ │ │ ├── current_flow_betweenness.py │ │ │ ├── current_flow_betweenness_subset.py │ │ │ ├── current_flow_closeness.py │ │ │ ├── degree_alg.py │ │ │ ├── eigenvector.py │ │ │ ├── flow_matrix.py │ │ │ ├── load.py │ │ │ └── tests │ │ │ │ ├── test_betweenness_centrality.py │ │ │ │ ├── test_betweenness_centrality_subset.py │ │ │ │ ├── test_closeness_centrality.py │ │ │ │ ├── test_communicability.py │ │ │ │ ├── test_current_flow_betweenness_centrality.py │ │ │ │ ├── test_current_flow_betweenness_centrality_subset.py │ │ │ │ ├── test_current_flow_closeness.py │ │ │ │ ├── test_degree_centrality.py │ │ │ │ ├── test_eigenvector_centrality.py │ │ │ │ └── test_load_centrality.py │ │ ├── chordal │ │ │ ├── __init__.py │ │ │ ├── chordal_alg.py │ │ │ └── tests │ │ │ │ └── test_chordal.py │ │ ├── clique.py │ │ ├── cluster.py │ │ ├── community │ │ │ ├── __init__.py │ │ │ ├── kclique.py │ │ │ └── tests │ │ │ │ └── test_kclique.py │ │ ├── components │ │ │ ├── __init__.py │ │ │ ├── attracting.py │ │ │ ├── biconnected.py │ │ │ ├── connected.py │ │ │ ├── strongly_connected.py │ │ │ ├── tests │ │ │ │ ├── test_attracting.py │ │ │ │ ├── test_biconnected.py │ │ │ │ ├── test_connected.py │ │ │ │ ├── test_strongly_connected.py │ │ │ │ └── test_weakly_connected.py │ │ │ └── weakly_connected.py │ │ ├── core.py │ │ ├── cycles.py │ │ ├── dag.py │ │ ├── distance_measures.py │ │ ├── distance_regular.py │ │ ├── euler.py │ │ ├── flow │ │ │ ├── __init__.py │ │ │ ├── maxflow.py │ │ │ ├── mincost.py │ │ │ └── tests │ │ │ │ ├── test_maxflow.py │ │ │ │ ├── test_maxflow_large_graph.py │ │ │ │ └── test_mincost.py │ │ ├── graphical.py │ │ ├── isolate.py │ │ ├── isomorphism │ │ │ ├── __init__.py │ │ │ ├── isomorph.py │ │ │ ├── isomorphvf2.py │ │ │ ├── matchhelpers.py │ │ │ ├── tests │ │ │ │ ├── iso_r01_s80.A99 │ │ │ │ ├── iso_r01_s80.B99 │ │ │ │ ├── si2_b06_m200.A99 │ │ │ │ ├── si2_b06_m200.B99 │ │ │ │ ├── test_isomorphism.py │ │ │ │ ├── test_isomorphvf2.py │ │ │ │ └── test_vf2userfunc.py │ │ │ └── vf2userfunc.py │ │ ├── link_analysis │ │ │ ├── __init__.py │ │ │ ├── hits_alg.py │ │ │ ├── pagerank_alg.py │ │ │ └── tests │ │ │ │ ├── test_hits.py │ │ │ │ └── test_pagerank.py │ │ ├── matching.py │ │ ├── mis.py │ │ ├── mst.py │ │ ├── operators.py │ │ ├── product.py │ │ ├── richclub.py │ │ ├── shortest_paths │ │ │ ├── __init__.py │ │ │ ├── astar.py │ │ │ ├── dense.py │ │ │ ├── generic.py │ │ │ ├── tests │ │ │ │ ├── test_astar.py │ │ │ │ ├── test_dense.py │ │ │ │ ├── test_generic.py │ │ │ │ ├── test_unweighted.py │ │ │ │ └── test_weighted.py │ │ │ ├── unweighted.py │ │ │ └── weighted.py │ │ ├── smetric.py │ │ ├── swap.py │ │ ├── tests │ │ │ ├── test_block.py │ │ │ ├── test_boundary.py │ │ │ ├── test_clique.py │ │ │ ├── test_cluster.py │ │ │ ├── test_core.py │ │ │ ├── test_cycles.py │ │ │ ├── test_dag.py │ │ │ ├── test_distance_measures.py │ │ │ ├── test_distance_regular.py │ │ │ ├── test_euler.py │ │ │ ├── test_graphical.py │ │ │ ├── test_matching.py │ │ │ ├── test_mis.py │ │ │ ├── test_mst.py │ │ │ ├── test_operators.py │ │ │ ├── test_product.py │ │ │ ├── test_richclub.py │ │ │ ├── test_smetric.py │ │ │ ├── test_swap.py │ │ │ └── test_vitality.py │ │ ├── traversal │ │ │ ├── __init__.py │ │ │ ├── breadth_first_search.py │ │ │ ├── depth_first_search.py │ │ │ └── tests │ │ │ │ ├── test_bfs.py │ │ │ │ └── test_dfs.py │ │ └── vitality.py │ ├── classes │ │ ├── __init__.py │ │ ├── digraph.py │ │ ├── function.py │ │ ├── graph.py │ │ ├── multidigraph.py │ │ ├── multigraph.py │ │ └── tests │ │ │ ├── historical_tests.py │ │ │ ├── test_digraph.py │ │ │ ├── test_digraph_historical.py │ │ │ ├── test_function.py │ │ │ ├── test_graph.py │ │ │ ├── test_graph_historical.py │ │ │ ├── test_multidigraph.py │ │ │ └── test_multigraph.py │ ├── convert.py │ ├── drawing │ │ ├── __init__.py │ │ ├── layout.py │ │ ├── nx_agraph.py │ │ ├── nx_pydot.py │ │ ├── nx_pylab.py │ │ └── tests │ │ │ ├── test_agraph.py │ │ │ ├── test_layout.py │ │ │ ├── test_pydot.py │ │ │ └── test_pylab.py │ ├── exception.py │ ├── external │ │ ├── __init__.py │ │ └── decorator │ │ │ ├── __init__.py │ │ │ ├── _decorator.py │ │ │ └── _decorator3.py │ ├── generators │ │ ├── __init__.py │ │ ├── atlas.py │ │ ├── bipartite.py │ │ ├── classic.py │ │ ├── degree_seq.py │ │ ├── directed.py │ │ ├── ego.py │ │ ├── geometric.py │ │ ├── hybrid.py │ │ ├── intersection.py │ │ ├── line.py │ │ ├── random_clustered.py │ │ ├── random_graphs.py │ │ ├── small.py │ │ ├── social.py │ │ ├── stochastic.py │ │ ├── tests │ │ │ ├── test_atlas.py │ │ │ ├── test_bipartite.py │ │ │ ├── test_classic.py │ │ │ ├── test_degree_seq.py │ │ │ ├── test_directed.py │ │ │ ├── test_ego.py │ │ │ ├── test_geometric.py │ │ │ ├── test_hybrid.py │ │ │ ├── test_intersection.py │ │ │ ├── test_line.py │ │ │ ├── test_random_clustered.py │ │ │ ├── test_random_graphs.py │ │ │ ├── test_small.py │ │ │ ├── test_stochastic.py │ │ │ └── test_threshold.py │ │ └── threshold.py │ ├── linalg │ │ ├── __init__.py │ │ ├── attrmatrix.py │ │ ├── graphmatrix.py │ │ ├── laplacianmatrix.py │ │ ├── spectrum.py │ │ └── tests │ │ │ ├── test_graphmatrix.py │ │ │ ├── test_laplaican.py │ │ │ └── test_spectrum.py │ ├── readwrite │ │ ├── __init__.py │ │ ├── adjlist.py │ │ ├── edgelist.py │ │ ├── gexf.py │ │ ├── gml.py │ │ ├── gpickle.py │ │ ├── graphml.py │ │ ├── json_graph │ │ │ ├── __init__.py │ │ │ ├── adjacency.py │ │ │ ├── node_link.py │ │ │ ├── serialize.py │ │ │ ├── tests │ │ │ │ ├── test_adjacency.py │ │ │ │ ├── test_node_link.py │ │ │ │ ├── test_serialize.py │ │ │ │ └── test_tree.py │ │ │ └── tree.py │ │ ├── leda.py │ │ ├── multiline_adjlist.py │ │ ├── nx_shp.py │ │ ├── nx_yaml.py │ │ ├── p2g.py │ │ ├── pajek.py │ │ ├── sparsegraph6.py │ │ └── tests │ │ │ ├── test_adjlist.py │ │ │ ├── test_edgelist.py │ │ │ ├── test_gexf.py │ │ │ ├── test_gml.py │ │ │ ├── test_gpickle.py │ │ │ ├── test_graphml.py │ │ │ ├── test_leda.py │ │ │ ├── test_p2g.py │ │ │ ├── test_pajek.py │ │ │ ├── test_shp.py │ │ │ ├── test_sparsegraph6.py │ │ │ └── test_yaml.py │ ├── relabel.py │ ├── release.py │ ├── tests │ │ ├── __init__.py │ │ ├── benchmark.py │ │ ├── test.py │ │ ├── test_convert.py │ │ ├── test_convert_numpy.py │ │ ├── test_convert_scipy.py │ │ ├── test_exceptions.py │ │ └── test_relabel.py │ ├── utils │ │ ├── __init__.py │ │ ├── decorators.py │ │ ├── misc.py │ │ ├── random_sequence.py │ │ ├── rcm.py │ │ ├── tests │ │ │ ├── test_decorators.py │ │ │ ├── test_misc.py │ │ │ ├── test_random_sequence.py │ │ │ └── test_rcm.py │ │ └── union_find.py │ └── version.py ├── pagination.py ├── parsetab.py ├── ply │ ├── __init__.py │ ├── cpp.py │ ├── ctokens.py │ ├── lex.py │ └── yacc.py ├── pyparsing.py ├── raco ├── requests ├── robots.txt ├── six.py ├── sqlalchemy ├── static │ ├── apple-touch-icon-114x114-precomposed.png │ ├── apple-touch-icon-120x120-precomposed.png │ ├── apple-touch-icon-144x144-precomposed.png │ ├── apple-touch-icon-152x152-precomposed.png │ ├── apple-touch-icon-72x72-precomposed.png │ ├── apple-touch-icon-76x76-precomposed.png │ ├── apple-touch-icon-precomposed.png │ └── favicon.ico ├── templates │ ├── base.html │ ├── datasets.html │ ├── editor.html │ ├── perfenforce.html │ ├── queries.html │ └── visualization.html ├── test │ ├── test_myria_down.py │ └── test_myria_up.py └── test_style.py ├── customize-bootstrap ├── README.md └── variables.less.diff ├── deploy.sh ├── docs └── index.md └── requirements-dev.txt /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | .DS_Store 3 | .*.swp 4 | appengine/VERSION 5 | appengine/BRANCH 6 | /google_appengine 7 | /google_appengine*.zip 8 | .idea 9 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "datalogcompiler"] 2 | path = submodules/raco 3 | url = https://github.com/uwescience/datalogcompiler.git 4 | branch = master 5 | [submodule "myria-python"] 6 | path = submodules/myria-python 7 | url = https://github.com/uwescience/myria-python.git 8 | branch = master 9 | [submodule "requests"] 10 | path = submodules/requests 11 | url = https://github.com/kennethreitz/requests/ 12 | [submodule "submodules/sqlalchemy"] 13 | path = submodules/sqlalchemy 14 | url = https://github.com/zzzeek/sqlalchemy.git 15 | [submodule "submodules/dateutil"] 16 | path = submodules/dateutil 17 | url = https://github.com/dateutil/dateutil.git 18 | [submodule "submodules/six"] 19 | path = submodules/six 20 | url = https://github.com/gsutil-mirrors/six.git 21 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "2.7" 4 | install: 5 | - curl -O https://storage.googleapis.com/appengine-sdks/featured/google_appengine_1.9.22.zip && unzip -q google_appengine_1.9.22.zip 6 | - pip install -r requirements-dev.txt 7 | script: nosetests test/test_myria_down.py test/test_myria_up.py test_style.py -w appengine --with-gae --gae-lib-root=google_appengine 8 | sudo: false 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012-2015 University of Washington 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 5 | Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 6 | Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 7 | Neither the name of the University of Washington nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 8 | 9 | THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF WASHINGTON AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF WASHINGTON OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 10 | -------------------------------------------------------------------------------- /appengine/app.yaml: -------------------------------------------------------------------------------- 1 | application: myria-web 2 | version: 1 3 | runtime: python27 4 | api_version: 1 5 | threadsafe: true 6 | 7 | handlers: 8 | - url: /favicon\.ico 9 | expiration: "7d" 10 | static_files: static/favicon.ico 11 | upload: static/favicon\.ico 12 | - url: /(apple-touch.*\.png) 13 | expiration: "7d" 14 | static_files: static/\1 15 | upload: static/apple.*\.png 16 | - url: /jupyter_not_found 17 | static_files: jupyter_not_found.txt 18 | upload: jupyter_not_found.txt 19 | - url: /css 20 | static_dir: css 21 | - url: /fonts 22 | static_dir: fonts 23 | - url: /img 24 | static_dir: img 25 | - url: /js 26 | static_dir: js 27 | - url: /data 28 | static_dir: data 29 | - url: /robots\.txt 30 | static_files: robots.txt 31 | upload: robots\.txt 32 | # This handler must be last 33 | - url: /.* 34 | script: myria_web_main.app 35 | secure: always 36 | 37 | libraries: 38 | - name: webapp2 39 | version: latest 40 | - name: jinja2 41 | version: latest 42 | 43 | env_variables: 44 | MYRIAX_REST_HOST: localhost 45 | MYRIAX_REST_PORT: 8753 46 | MYRIA_JUPYTER_PORT: 8888 47 | -------------------------------------------------------------------------------- /appengine/css/layout.css: -------------------------------------------------------------------------------- 1 | .navbar-inverse .navbar-brand { 2 | padding-top: 5px; 3 | padding-bottom: 5px; 4 | } 5 | 6 | .navbar-inverse { 7 | margin-bottom: 10px; 8 | } 9 | 10 | .modal-header input[type=range] { 11 | width: 250px; 12 | height: 10px; 13 | margin: 0 30px 0 5px; 14 | } 15 | 16 | .my-fluid-container { 17 | width: 100%; 18 | } 19 | 20 | html { 21 | position: relative; 22 | min-height: 100%; 23 | } 24 | body { 25 | /* Margin bottom by footer height */ 26 | margin-bottom: 60px; 27 | } 28 | 29 | #footer { 30 | position: absolute; 31 | bottom: 0; 32 | width: 100%; 33 | /* Set the fixed height of the footer here */ 34 | height: 60px; 35 | background-color: #f5f5f5; 36 | } 37 | 38 | .container .credit { 39 | margin: 20px 0; 40 | } 41 | 42 | .spacer { 43 | padding-top: 10px; 44 | } 45 | 46 | input[type=range].zoom-range { 47 | display: inline; 48 | } 49 | 50 | #editor-tabs li a { 51 | padding: 8px 3px; 52 | } 53 | 54 | .dataset-search { 55 | width: 100%; 56 | } 57 | 58 | .triple-input .form-control { 59 | width: 33.33%; 60 | border-right-width: 0px; 61 | } 62 | .triple-input .form-control:focus { 63 | border-right-width: 1px; 64 | } 65 | 66 | .back-to-top { 67 | position: fixed; 68 | bottom: 8px; 69 | right: 8px; 70 | padding: 8px 12px; 71 | z-index: 10; 72 | background-color: rgba(255, 255, 255, 0.7); 73 | } 74 | 75 | #svg-modal-body { 76 | padding: 0; 77 | } 78 | 79 | .CodeMirror { 80 | border: 1px solid #eee; 81 | height: auto; 82 | } 83 | 84 | .CodeMirror-hscrollbar { 85 | display: none !important; 86 | } 87 | 88 | .select2-result-label strong { 89 | text-decoration: underline; 90 | } 91 | 92 | #examples-list .list-group-item { 93 | padding-top: 0; 94 | padding-bottom: 0; 95 | } 96 | 97 | #examples-list pre { 98 | font-size: 10px; 99 | } 100 | 101 | #examples-list { 102 | overflow: auto; 103 | } 104 | 105 | #loadexamples-list .list-group-item { 106 | padding-top: 0; 107 | padding-bottom: 0; 108 | } 109 | 110 | #loadexamples-list pre { 111 | font-size: 10px; 112 | } 113 | 114 | #loadexamples-list { 115 | overflow: auto; 116 | } 117 | 118 | #myria_svg { 119 | width: 100%; 120 | } 121 | 122 | .tablesorter-header[aria-disabled=false] { 123 | cursor: pointer; 124 | } 125 | 126 | .query-panel-heading .form-group { 127 | margin-bottom: 0; 128 | } 129 | 130 | .query-panel-heading .panel-title { 131 | margin-top: 7px; 132 | } -------------------------------------------------------------------------------- /appengine/css/perfenforce.css: -------------------------------------------------------------------------------- 1 | .glyphicon.spinning { 2 | animation: spin 1s infinite linear; 3 | -webkit-animation: spin2 1s infinite linear; 4 | } 5 | 6 | @keyframes spin { 7 | from { transform: scale(1) rotate(0deg);} 8 | to { transform: scale(1) rotate(360deg);} 9 | } 10 | 11 | @-webkit-keyframes spin2 { 12 | from { -webkit-transform: rotate(0deg);} 13 | to { -webkit-transform: rotate(360deg);} 14 | } 15 | 16 | .glyphicon-left { 17 | margin-right: 7px; 18 | } 19 | 20 | .page-anchor { 21 | line-height: 1em; 22 | display: inline-block; 23 | text-decoration: none; 24 | margin-top: 500px; 25 | } 26 | 27 | #previousQueryList 28 | { 29 | height: 100px; 30 | overflow: auto; 31 | border: 1px solid black; 32 | } 33 | 34 | ul { 35 | padding: 0; 36 | } 37 | li { 38 | margin: 0; 39 | list-style-type: none; 40 | } 41 | 42 | 43 | .list-group-item{ 44 | border: 1px solid #808080; 45 | } 46 | 47 | .top-buffer { margin-top:40px; } -------------------------------------------------------------------------------- /appengine/data/sent_4_2.csv: -------------------------------------------------------------------------------- 1 | workerId,nanoTime,numTuples,destWorkerId 2 | 3,1040212134,143,1 3 | 3,2059371044,3259,1 4 | 3,3065649769,5422,1 5 | 3,3549528390,10000,1 6 | 3,4236235180,10000,1 7 | 3,4897241800,3093,1 8 | 1,1031169627,209,1 9 | 1,2049172616,1402,1 10 | 1,3057253192,2858,1 11 | 1,4078224688,5901,1 12 | 1,4888275121,1566,1 13 | 7,1036117216,159,1 14 | 7,2055480109,3272,1 15 | 7,3060842477,4045,1 16 | 7,4140191100,4041,1 17 | 7,4893253135,739,1 18 | 5,1001856273,140,1 19 | 5,2076853745,1003,1 20 | 5,2413825865,10000,1 21 | 5,2441449427,10000,1 22 | 5,2480383113,10000,1 23 | 5,2518129100,10000,1 24 | 5,2556666536,10000,1 25 | 5,2595475333,10000,1 26 | 5,2639974919,10000,1 27 | 5,2733050327,10000,1 28 | 5,2783048573,10000,1 29 | 5,2819065828,10000,1 30 | 5,2857651639,10000,1 31 | 5,2895833651,10000,1 32 | 5,2932926858,10000,1 33 | 5,2970162367,10000,1 34 | 5,3024694567,10000,1 35 | 5,3077566857,10000,1 36 | 5,3290031871,10000,1 37 | 5,3366705113,10000,1 38 | 5,3438554481,10000,1 39 | 5,3510310986,10000,1 40 | 5,3587130299,10000,1 41 | 5,3659335785,10000,1 42 | 5,3722179458,10000,1 43 | 5,3794343402,10000,1 44 | 5,3853666293,10000,1 45 | 5,3923608935,10000,1 46 | 5,3991528316,10000,1 47 | 5,4068186032,10000,1 48 | 5,4147132636,10000,1 49 | 5,4221442157,10000,1 50 | 5,4281493775,10000,1 51 | 5,4468693435,10000,1 52 | 5,4489147709,10000,1 53 | 5,4512187018,10000,1 54 | 5,4547537806,10000,1 55 | 5,4649467543,10000,1 56 | 5,4700225098,10000,1 57 | 5,4727947368,10000,1 58 | 5,4804216202,10000,1 59 | 5,4889306968,10000,1 60 | 5,4909136289,10000,1 61 | 5,4941848562,10000,1 62 | 5,4959749354,10000,1 63 | 5,4985471821,10000,1 64 | 5,5045634269,2673,1 65 | 2,980267924,128,1 66 | 2,1988198944,1037,1 67 | 2,3006043295,3393,1 68 | 2,4154062648,4044,1 69 | 2,4955249558,693,1 70 | 6,1033411968,135,1 71 | 6,2034185617,2430,1 72 | 6,3058293289,1731,1 73 | 6,4158173610,4225,1 74 | 6,4958239761,898,1 75 | 4,1023091563,205,1 76 | 4,2024121979,728,1 77 | 4,3023832324,1710,1 78 | 4,4147103057,2659,1 79 | 4,4947294558,365,1 80 | 8,1020043267,222,1 81 | 8,2021275872,1608,1 82 | 8,3046053510,2228,1 83 | 8,4145079480,4090,1 84 | 8,4946289187,429,1 85 | -------------------------------------------------------------------------------- /appengine/dateutil: -------------------------------------------------------------------------------- 1 | ../submodules/dateutil/dateutil -------------------------------------------------------------------------------- /appengine/examples: -------------------------------------------------------------------------------- 1 | ../submodules/raco/examples -------------------------------------------------------------------------------- /appengine/fonts/glyphicons-halflings-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uwescience/myria-web/b1c175a5cbe76d4f2219b192635085ece1326588/appengine/fonts/glyphicons-halflings-regular.eot -------------------------------------------------------------------------------- /appengine/fonts/glyphicons-halflings-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uwescience/myria-web/b1c175a5cbe76d4f2219b192635085ece1326588/appengine/fonts/glyphicons-halflings-regular.ttf -------------------------------------------------------------------------------- /appengine/fonts/glyphicons-halflings-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uwescience/myria-web/b1c175a5cbe76d4f2219b192635085ece1326588/appengine/fonts/glyphicons-halflings-regular.woff -------------------------------------------------------------------------------- /appengine/img/select2-spinner.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uwescience/myria-web/b1c175a5cbe76d4f2219b192635085ece1326588/appengine/img/select2-spinner.gif -------------------------------------------------------------------------------- /appengine/img/select2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uwescience/myria-web/b1c175a5cbe76d4f2219b192635085ece1326588/appengine/img/select2.png -------------------------------------------------------------------------------- /appengine/img/select2x2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uwescience/myria-web/b1c175a5cbe76d4f2219b192635085ece1326588/appengine/img/select2x2.png -------------------------------------------------------------------------------- /appengine/js/d3.selection.popover.js: -------------------------------------------------------------------------------- 1 | // adapted from: https://gist.github.com/mrfr0g/5968059 2 | 3 | (function () { 4 | // Bootstrap provided getPosition uses offsetWidth and offsetHeight to calculate 5 | // the positioning of the popover. SVG Elements do not have this property because 6 | // SVG does not layout elements, it assumes elements are always positioned. 7 | // This replaces their implementation for SVG elements, and utilizes getBoundingClientRect. 8 | var getPosition = $.fn.popover.Constructor.prototype.getPosition; 9 | $.fn.popover.Constructor.prototype.getPosition = function (inside) { 10 | var svgParent = this.$element.parents('svg'); 11 | // Only apply to SVG children 12 | // Test for iOS 3/BlackBerry 13 | if(svgParent.length && Element.prototype.getBoundingClientRect) { 14 | // Get initial offset 15 | var offset = this.$element.offset(), 16 | // Get rect (with width/height values) 17 | rect = this.$element[0].getBoundingClientRect(); 18 | 19 | offset.width = rect.width; 20 | offset.height = rect.height; 21 | 22 | // Return the completed object 23 | return offset; 24 | } 25 | return getPosition.call(this, inside); 26 | }; 27 | 28 | // Attach the popover method to d3's selection object 29 | d3.selection.prototype.popover = function (/* Accepts value, or function */ accessorOrValue) { 30 | this.each(function (d) { 31 | var popover = accessorOrValue instanceof Function ? null : accessorOrValue; 32 | 33 | popover = popover || accessorOrValue && accessorOrValue(d) || d.popover; 34 | 35 | if(popover) { 36 | $(this).popover({ 37 | title: popover.title, 38 | content: popover.content, 39 | container: 'body', 40 | placement: popover.placement ? popover.placement : 'auto', 41 | offset: 10, 42 | trigger: 'manual', 43 | html: true, 44 | template: '

' 45 | }).mouseenter(function(e) { 46 | $(this).popover('show'); 47 | }).mouseleave(function(e) { 48 | var ref = $(this); 49 | timeoutObj = setTimeout(function(){ 50 | ref.popover('hide'); 51 | }, 100); 52 | }); 53 | } 54 | }); 55 | 56 | return this; 57 | }; 58 | })(); -------------------------------------------------------------------------------- /appengine/js/d3.selection.tooltip.js: -------------------------------------------------------------------------------- 1 | // adapted from: https://gist.github.com/mrfr0g/5968059 2 | 3 | (function () { 4 | // Bootstrap provided getPosition uses offsetWidth and offsetHeight to calculate 5 | // the positioning of the tooltip. SVG Elements do not have this property because 6 | // SVG does not layout elements, it assumes elements are always positioned. 7 | // This replaces their implementation for SVG elements, and utilizes getBoundingClientRect. 8 | var getPosition = $.fn.tooltip.Constructor.prototype.getPosition; 9 | $.fn.tooltip.Constructor.prototype.getPosition = function (inside) { 10 | var svgParent = this.$element.parents('svg'); 11 | // Only apply to SVG children 12 | // Test for iOS 3/BlackBerry 13 | if(svgParent.length && Element.prototype.getBoundingClientRect) { 14 | // Get initial offset 15 | var offset = this.$element.offset(), 16 | // Get rect (with width/height values) 17 | rect = this.$element[0].getBoundingClientRect(); 18 | 19 | offset.width = rect.width; 20 | offset.height = rect.height; 21 | 22 | // Return the completed object 23 | return offset; 24 | } 25 | return getPosition.call(this, inside); 26 | }; 27 | 28 | // Attach the tooltip method to d3's selection object 29 | d3.selection.prototype.tooltip = function (/* Accepts value, or function */ accessorOrValue) { 30 | this.each(function (d) { 31 | var tooltip = accessorOrValue instanceof Function ? null : accessorOrValue; 32 | 33 | tooltip = tooltip || accessorOrValue && accessorOrValue(d) || d.tooltip; 34 | 35 | if(tooltip) { 36 | $(this).tooltip({ 37 | title: tooltip, 38 | container: 'body', 39 | html: true 40 | }); 41 | } 42 | }); 43 | 44 | return this; 45 | }; 46 | })(); -------------------------------------------------------------------------------- /appengine/js/prolog.js: -------------------------------------------------------------------------------- 1 | CodeMirror.defineMode("prolog", function() { 2 | return { 3 | startState: function() { 4 | return { in_comment:0 }; 5 | }, 6 | token: function(stream,state) { 7 | var token_name; 8 | if (state.in_comment) { 9 | token_name = 'comment'; 10 | if (stream.match("*/")) 11 | state.in_comment--; 12 | else if (stream.match("/*")) 13 | state.in_comment++; 14 | else 15 | stream.next(); 16 | } else if (stream.match("/*")) { 17 | token_name = 'comment'; 18 | state.in_comment++; 19 | } else if (stream.match(/[a-z][A-Za-z0-9_]*/)) 20 | token_name = 'atom'; 21 | else if (stream.match(/\'(\\\'|[^\'])*\'/)) 22 | token_name = 'atom'; 23 | else if (stream.match(/\"(\\\"|[^\"])*\"/)) 24 | token_name = 'string'; 25 | else if (stream.match(/0'./)) 26 | token_name = 'string-2'; 27 | else if (stream.match(/[A-Z_][A-Za-z0-9_]*/)) 28 | token_name = 'variable-2'; 29 | else if (stream.match(/[0-9]+(\.[0-9]+)?/)) 30 | token_name = 'number'; 31 | else if (stream.match(/[\+\-\*\/\=\^<>~:\.\?@#$\\&{}`]+/)) 32 | token_name = 'operator'; 33 | else 34 | if (stream.next() === '%') { 35 | stream.skipToEnd(); 36 | token_name = 'comment'; 37 | } 38 | return token_name; 39 | } 40 | }; 41 | }); -------------------------------------------------------------------------------- /appengine/js/queries.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function() { 2 | $('.query-row[data-status="RUNNING"]').each(function(i, e) { 3 | var qid = $(this).attr('data-id'); 4 | window.setInterval(function() { 5 | $.getJSON('/execute', { 'queryId': qid }, function(data) { 6 | if (data.status != 'RUNNING') { 7 | location.reload(); 8 | } 9 | }); 10 | }, 10*1000); 11 | }); 12 | 13 | $('.kill-query').click(function() { 14 | $.ajax({ 15 | url: $(this).attr('href'), 16 | type: 'DELETE', 17 | success: function(result) { 18 | location.reload(); 19 | } 20 | }); 21 | return false; 22 | }); 23 | }); -------------------------------------------------------------------------------- /appengine/js/querystats.js: -------------------------------------------------------------------------------- 1 | var updateQueryStats = function(element, queryStatus) { 2 | var shuffleUrl = templates.urls.aggregatedSentData({ 3 | myria: myriaConnection, 4 | query: queryStatus.queryId, 5 | subquery: queryStatus.subqueryId 6 | }); 7 | 8 | d3.csv(shuffleUrl, function(d) { 9 | d.numTuples = +d.numTuples; 10 | return d; 11 | }, function (data) { 12 | $(element.node()).empty(); 13 | var div = element.append("div") 14 | .attr("class", "query-stats"); 15 | var h = div.append("h4") 16 | .text("Query stats:"); 17 | var totalTuple = data.reduce(function(a,b){ 18 | return a + b.numTuples; 19 | }, 0); 20 | var items = ""; 21 | items += templates.defItem({key: "Running time:", value: customFullTimeFormat(queryStatus.elapsedNanos, false)}); 22 | items += templates.defItem({key: "# shuffled tuples:", value: Intl.NumberFormat().format(totalTuple)}); 23 | var dl = templates.defList({items: items}); 24 | $(".query-stats").append(dl); 25 | }); 26 | }; -------------------------------------------------------------------------------- /appengine/js/runmode.js: -------------------------------------------------------------------------------- 1 | // CodeMirror, copyright (c) by Marijn Haverbeke and others 2 | // Distributed under an MIT license: http://codemirror.net/LICENSE 3 | 4 | (function(mod) { 5 | if (typeof exports == "object" && typeof module == "object") // CommonJS 6 | mod(require("../../lib/codemirror")); 7 | else if (typeof define == "function" && define.amd) // AMD 8 | define(["../../lib/codemirror"], mod); 9 | else // Plain browser env 10 | mod(CodeMirror); 11 | })(function(CodeMirror) { 12 | "use strict"; 13 | 14 | CodeMirror.runMode = function(string, modespec, callback, options) { 15 | var mode = CodeMirror.getMode(CodeMirror.defaults, modespec); 16 | var ie = /MSIE \d/.test(navigator.userAgent); 17 | var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9); 18 | 19 | if (callback.nodeType == 1) { 20 | var tabSize = (options && options.tabSize) || CodeMirror.defaults.tabSize; 21 | var node = callback, col = 0; 22 | node.innerHTML = ""; 23 | callback = function(text, style) { 24 | if (text == "\n") { 25 | // Emitting LF or CRLF on IE8 or earlier results in an incorrect display. 26 | // Emitting a carriage return makes everything ok. 27 | node.appendChild(document.createTextNode(ie_lt9 ? '\r' : text)); 28 | col = 0; 29 | return; 30 | } 31 | var content = ""; 32 | // replace tabs 33 | for (var pos = 0;;) { 34 | var idx = text.indexOf("\t", pos); 35 | if (idx == -1) { 36 | content += text.slice(pos); 37 | col += text.length - pos; 38 | break; 39 | } else { 40 | col += idx - pos; 41 | content += text.slice(pos, idx); 42 | var size = tabSize - col % tabSize; 43 | col += size; 44 | for (var i = 0; i < size; ++i) content += " "; 45 | pos = idx + 1; 46 | } 47 | } 48 | 49 | if (style) { 50 | var sp = node.appendChild(document.createElement("span")); 51 | sp.className = "cm-" + style.replace(/ +/g, " cm-"); 52 | sp.appendChild(document.createTextNode(content)); 53 | } else { 54 | node.appendChild(document.createTextNode(content)); 55 | } 56 | }; 57 | } 58 | 59 | var lines = CodeMirror.splitLines(string), state = (options && options.state) || CodeMirror.startState(mode); 60 | for (var i = 0, e = lines.length; i < e; ++i) { 61 | if (i) callback("\n"); 62 | var stream = new CodeMirror.StringStream(lines[i]); 63 | if (!stream.string && mode.blankLine) mode.blankLine(state); 64 | while (!stream.eol()) { 65 | var style = mode.token(stream, state); 66 | callback(stream.current(), style, i, stream.start, state); 67 | stream.start = stream.pos; 68 | } 69 | } 70 | }; 71 | 72 | }); 73 | -------------------------------------------------------------------------------- /appengine/jupyter_not_found.txt: -------------------------------------------------------------------------------- 1 | Jupyter Notebook not found, please check that the service is running and set up on port 8888. -------------------------------------------------------------------------------- /appengine/myria: -------------------------------------------------------------------------------- 1 | ../submodules/myria-python/myria -------------------------------------------------------------------------------- /appengine/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("spam") 19 | >>> print(G.nodes()) 20 | [1, 2, 'spam'] 21 | >>> print(G.edges()) 22 | [(1, 2)] 23 | """ 24 | # Copyright (C) 2004-2010 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, 6): 38 | m = "Python version 2.6 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 | #These are import orderwise 54 | from networkx.exception import * 55 | import networkx.external 56 | import networkx.utils 57 | # these packages work with Python >= 2.6 58 | 59 | import networkx.classes 60 | from networkx.classes import * 61 | 62 | 63 | import networkx.convert 64 | from networkx.convert import * 65 | 66 | import networkx.relabel 67 | from networkx.relabel import * 68 | 69 | import networkx.generators 70 | from networkx.generators import * 71 | 72 | import networkx.readwrite 73 | from networkx.readwrite import * 74 | 75 | #Need to test with SciPy, when available 76 | import networkx.algorithms 77 | from networkx.algorithms import * 78 | import networkx.linalg 79 | 80 | from networkx.linalg import * 81 | from networkx.tests.test import run as test 82 | 83 | import networkx.drawing 84 | from networkx.drawing import * 85 | 86 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/__init__.py: -------------------------------------------------------------------------------- 1 | from networkx.algorithms.assortativity import * 2 | from networkx.algorithms.block import * 3 | from networkx.algorithms.boundary import * 4 | from networkx.algorithms.centrality import * 5 | from networkx.algorithms.cluster import * 6 | from networkx.algorithms.clique import * 7 | from networkx.algorithms.community import * 8 | from networkx.algorithms.components import * 9 | from networkx.algorithms.core import * 10 | from networkx.algorithms.cycles import * 11 | from networkx.algorithms.dag import * 12 | from networkx.algorithms.distance_measures import * 13 | from networkx.algorithms.flow import * 14 | from networkx.algorithms.matching import * 15 | from networkx.algorithms.mis import * 16 | from networkx.algorithms.mst import * 17 | from networkx.algorithms.link_analysis import * 18 | from networkx.algorithms.operators import * 19 | from networkx.algorithms.product import * 20 | from networkx.algorithms.shortest_paths import * 21 | from networkx.algorithms.smetric import * 22 | from networkx.algorithms.traversal import * 23 | from networkx.algorithms.isolate import * 24 | from networkx.algorithms.euler import * 25 | from networkx.algorithms.vitality import * 26 | from networkx.algorithms.chordal import * 27 | from networkx.algorithms.richclub import * 28 | from networkx.algorithms.distance_regular import * 29 | from networkx.algorithms.swap import * 30 | from networkx.algorithms.graphical import * 31 | 32 | import networkx.algorithms.assortativity 33 | import networkx.algorithms.bipartite 34 | import networkx.algorithms.centrality 35 | import networkx.algorithms.cluster 36 | import networkx.algorithms.clique 37 | import networkx.algorithms.components 38 | import networkx.algorithms.flow 39 | import networkx.algorithms.isomorphism 40 | import networkx.algorithms.link_analysis 41 | import networkx.algorithms.shortest_paths 42 | import networkx.algorithms.traversal 43 | import networkx.algorithms.chordal 44 | 45 | from networkx.algorithms.bipartite import projected_graph,project,is_bipartite 46 | from networkx.algorithms.isomorphism import is_isomorphic,could_be_isomorphic,\ 47 | fast_could_be_isomorphic,faster_could_be_isomorphic 48 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/bipartite/__init__.py: -------------------------------------------------------------------------------- 1 | """ This module provides functions and operations for bipartite 2 | graphs. Bipartite graphs G(X,Y,E) have two node sets X,Y and edges in 3 | E that only connect nodes from opposite sets. 4 | 5 | NetworkX does not have a custom bipartite graph class but the Graph() 6 | or DiGraph() classes can be used to represent bipartite graphs. 7 | 8 | For example: 9 | 10 | >>> import networkx as nx 11 | >>> top_nodes=[1,1,2,3,3] 12 | >>> bottom_nodes=['a','b','b','b','c'] 13 | >>> edges=zip(top_nodes,bottom_nodes) # create 2-tuples of edges 14 | >>> B=nx.Graph(edges) 15 | 16 | 17 | The bipartite algorithms are not imported into the networkx namespace 18 | at the top level so the easiest way to use them is with: 19 | 20 | >>> from networkx.algorithms import bipartite 21 | 22 | Some of the functions such as bipartite_density and projected_graph take 23 | a node set as an argument in addition to the graph B. 24 | 25 | >>> print(bipartite.density(B,top_nodes)) 26 | 1.0 27 | >>> G=bipartite.projected_graph(B,bottom_nodes) 28 | >>> G.edges() 29 | [('a', 'b'), ('c', 'b')] 30 | 31 | You can find the bipartite node sets using 32 | 33 | >>> X,Y=bipartite.sets(B) 34 | >>> print(list(X)) 35 | ['a', 'c', 'b'] 36 | >>> print(list(Y)) 37 | [1, 2, 3] 38 | 39 | """ 40 | from networkx.algorithms.bipartite.basic import * 41 | from networkx.algorithms.bipartite.centrality import * 42 | from networkx.algorithms.bipartite.cluster import * 43 | from networkx.algorithms.bipartite.projection import * 44 | from networkx.algorithms.bipartite.redundancy import * 45 | from networkx.algorithms.bipartite.spectral import * 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/bipartite/redundancy.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | """Node redundancy for bipartite graphs.""" 3 | # Copyright (C) 2011 by 4 | # Jordi Torrents 5 | # Aric Hagberg 6 | # All rights reserved. 7 | # BSD license. 8 | from itertools import combinations 9 | import networkx as nx 10 | 11 | __author__ = """\n""".join(['Jordi Torrents ', 12 | 'Aric Hagberg (hagberg@lanl.gov)']) 13 | __all__ = ['node_redundancy'] 14 | 15 | def node_redundancy(G, nodes=None): 16 | r"""Compute bipartite node redundancy coefficient. 17 | 18 | The redundancy coefficient of a node `v` is the fraction of pairs of 19 | neighbors of `v` that are both linked to other nodes. In a one-mode 20 | projection these nodes would be linked together even if `v` were 21 | not there. 22 | 23 | .. math:: 24 | 25 | rc(v) = \frac{|\{\{u,w\} \subseteq N(v), 26 | \: \exists v' \neq v,\: (v',u) \in E\: 27 | \mathrm{and}\: (v',w) \in E\}|}{ \frac{|N(v)|(|N(v)|-1)}{2}} 28 | 29 | where `N(v)` are the neighbors of `v` in `G`. 30 | 31 | Parameters 32 | ---------- 33 | G : graph 34 | A bipartite graph 35 | 36 | nodes : list or iterable (optional) 37 | Compute redundancy for these nodes. The default is all nodes in G. 38 | 39 | Returns 40 | ------- 41 | redundancy : dictionary 42 | A dictionary keyed by node with the node redundancy value. 43 | 44 | Examples 45 | -------- 46 | >>> from networkx.algorithms import bipartite 47 | >>> G = nx.cycle_graph(4) 48 | >>> rc = bipartite.node_redundancy(G) 49 | >>> rc[0] 50 | 1.0 51 | 52 | Compute the average redundancy for the graph: 53 | 54 | >>> sum(rc.values())/len(G) 55 | 1.0 56 | 57 | Compute the average redundancy for a set of nodes: 58 | 59 | >>> nodes = [0, 2] 60 | >>> sum(rc[n] for n in nodes)/len(nodes) 61 | 1.0 62 | 63 | References 64 | ---------- 65 | .. [1] Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008). 66 | Basic notions for the analysis of large two-mode networks. 67 | Social Networks 30(1), 31--48. 68 | """ 69 | if nodes is None: 70 | nodes = G 71 | rc = {} 72 | for v in nodes: 73 | overlap = 0.0 74 | for u, w in combinations(G[v], 2): 75 | if len((set(G[u]) & set(G[w])) - set([v])) > 0: 76 | overlap += 1 77 | if overlap > 0: 78 | n = len(G[v]) 79 | norm = 2.0/(n*(n-1)) 80 | else: 81 | norm = 1.0 82 | rc[v] = overlap*norm 83 | return rc 84 | 85 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/bipartite/tests/test_basic.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | from networkx.algorithms import bipartite 5 | class TestBipartiteBasic: 6 | 7 | def test_is_bipartite(self): 8 | G=nx.path_graph(4) 9 | assert_true(bipartite.is_bipartite(G)) 10 | G=nx.DiGraph([(1,0)]) 11 | assert_true(bipartite.is_bipartite(G)) 12 | 13 | def test_bipartite_color(self): 14 | G=nx.path_graph(4) 15 | c=bipartite.color(G) 16 | assert_equal(c,{0: 1, 1: 0, 2: 1, 3: 0}) 17 | 18 | def test_bipartite_directed(self): 19 | G = nx.bipartite_random_graph(10, 10, 0.1, directed=True) 20 | assert_true(bipartite.is_bipartite(G)) 21 | 22 | def test_bipartite_sets(self): 23 | G=nx.path_graph(4) 24 | X,Y=bipartite.sets(G) 25 | assert_equal(X,set([0,2])) 26 | assert_equal(Y,set([1,3])) 27 | 28 | def test_is_bipartite_node_set(self): 29 | G=nx.path_graph(4) 30 | assert_true(bipartite.is_bipartite_node_set(G,[0,2])) 31 | assert_true(bipartite.is_bipartite_node_set(G,[1,3])) 32 | G.add_path([10,20]) 33 | assert_true(bipartite.is_bipartite_node_set(G,[0,2,10])) 34 | assert_true(bipartite.is_bipartite_node_set(G,[0,2,20])) 35 | assert_true(bipartite.is_bipartite_node_set(G,[1,3,10])) 36 | assert_true(bipartite.is_bipartite_node_set(G,[1,3,20])) 37 | 38 | def test_bipartite_density(self): 39 | G=nx.path_graph(5) 40 | X,Y=bipartite.sets(G) 41 | density=float(len(G.edges()))/(len(X)*len(Y)) 42 | assert_equal(bipartite.density(G,X),density) 43 | 44 | def test_bipartite_degrees(self): 45 | G=nx.path_graph(5) 46 | X=set([1,3]) 47 | Y=set([0,2,4]) 48 | u,d=bipartite.degrees(G,Y) 49 | assert_equal(u,{1:2,3:2}) 50 | assert_equal(d,{0:1,2:2,4:1}) 51 | 52 | def test_bipartite_weighted_degrees(self): 53 | G=nx.path_graph(5) 54 | G.add_edge(0,1,weight=0.1,other=0.2) 55 | X=set([1,3]) 56 | Y=set([0,2,4]) 57 | u,d=bipartite.degrees(G,Y,weight='weight') 58 | assert_equal(u,{1:1.1,3:2}) 59 | assert_equal(d,{0:0.1,2:2,4:1}) 60 | u,d=bipartite.degrees(G,Y,weight='other') 61 | assert_equal(u,{1:1.2,3:2}) 62 | assert_equal(d,{0:0.2,2:2,4:1}) 63 | -------------------------------------------------------------------------------- /appengine/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], 1:[1/2.0, 2/3.0, 2/3.0], 2:[2/8.0, 2/5.0, 2/5.0]} 14 | for i, G in enumerate([G1, G2, G3]): 15 | assert(bipartite.is_bipartite(G)) 16 | assert(cc_dot(set(G[0]), set(G[1])) == result[i][0]) 17 | assert(cc_min(set(G[0]), set(G[1])) == result[i][1]) 18 | assert(cc_max(set(G[0]), set(G[1])) == result[i][2]) 19 | 20 | def test_star_graph(): 21 | G=nx.star_graph(3) 22 | # all modes are the same 23 | answer={0:0,1:1,2:1,3:1} 24 | assert_equal(bipartite.clustering(G,mode='dot'),answer) 25 | assert_equal(bipartite.clustering(G,mode='min'),answer) 26 | assert_equal(bipartite.clustering(G,mode='max'),answer) 27 | 28 | def test_path_graph(): 29 | G=nx.path_graph(4) 30 | answer={0:0.5,1:0.5,2:0.5,3:0.5} 31 | assert_equal(bipartite.clustering(G,mode='dot'),answer) 32 | assert_equal(bipartite.clustering(G,mode='max'),answer) 33 | answer={0:1,1:1,2:1,3:1} 34 | assert_equal(bipartite.clustering(G,mode='min'),answer) 35 | 36 | 37 | def test_average_path_graph(): 38 | G=nx.path_graph(4) 39 | assert_equal(bipartite.average_clustering(G,mode='dot'),0.5) 40 | assert_equal(bipartite.average_clustering(G,mode='max'),0.5) 41 | assert_equal(bipartite.average_clustering(G,mode='min'),1) 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/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-2008 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 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/centrality/__init__.py: -------------------------------------------------------------------------------- 1 | from networkx.algorithms.centrality.betweenness import * 2 | from networkx.algorithms.centrality.betweenness_subset import * 3 | from networkx.algorithms.centrality.closeness import * 4 | from networkx.algorithms.centrality.current_flow_closeness import * 5 | from networkx.algorithms.centrality.current_flow_betweenness import * 6 | from networkx.algorithms.centrality.current_flow_betweenness_subset import * 7 | from networkx.algorithms.centrality.degree_alg import * 8 | from networkx.algorithms.centrality.eigenvector import * 9 | from networkx.algorithms.centrality.load import * 10 | from networkx.algorithms.centrality.communicability_alg import * 11 | import networkx.algorithms.centrality.betweenness 12 | import networkx.algorithms.centrality.closeness 13 | import networkx.algorithms.centrality.current_flow_betweenness 14 | import networkx.algorithms.centrality.current_flow_closeness 15 | import networkx.algorithms.centrality.degree_alg 16 | import networkx.algorithms.centrality.eigenvector 17 | import networkx.algorithms.centrality.load 18 | import networkx.algorithms.centrality.communicability_alg 19 | 20 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/centrality/closeness.py: -------------------------------------------------------------------------------- 1 | """ 2 | Closeness centrality measures. 3 | 4 | """ 5 | # Copyright (C) 2004-2010 by 6 | # Aric Hagberg 7 | # Dan Schult 8 | # Pieter Swart 9 | # All rights reserved. 10 | # BSD license. 11 | import functools 12 | import networkx as nx 13 | __author__ = "\n".join(['Aric Hagberg (hagberg@lanl.gov)', 14 | 'Pieter Swart (swart@lanl.gov)', 15 | 'Sasha Gutfraind (ag362@cornell.edu)']) 16 | __all__ = ['closeness_centrality'] 17 | 18 | 19 | def closeness_centrality(G, v=None, distance=None, normalized=True): 20 | """Compute closeness centrality for nodes. 21 | 22 | Closeness centrality at a node is 1/average distance to all other nodes. 23 | 24 | Parameters 25 | ---------- 26 | G : graph 27 | A networkx graph 28 | v : node, optional 29 | Return only the value for node v 30 | distance : string key, optional (default=None) 31 | Use specified edge key as edge distance. 32 | If True, use 'weight' as the edge key. 33 | normalized : bool, optional 34 | If True (default) normalize by the graph size. 35 | 36 | Returns 37 | ------- 38 | nodes : dictionary 39 | Dictionary of nodes with closeness centrality as the value. 40 | 41 | See Also 42 | -------- 43 | betweenness_centrality, load_centrality, eigenvector_centrality, 44 | degree_centrality 45 | 46 | Notes 47 | ----- 48 | The closeness centrality is normalized to to n-1 / size(G)-1 where 49 | n is the number of nodes in the connected part of graph containing 50 | the node. If the graph is not completely connected, this 51 | algorithm computes the closeness centrality for each connected 52 | part separately. 53 | """ 54 | if distance is not None: 55 | if distance is True: distance='weight' 56 | path_length=functools.partial(nx.single_source_dijkstra_path_length, 57 | weight=distance) 58 | else: 59 | path_length=nx.single_source_shortest_path_length 60 | 61 | if v is None: 62 | nodes=G.nodes() 63 | else: 64 | nodes=[v] 65 | closeness_centrality={} 66 | 67 | for n in nodes: 68 | sp=path_length(G,n) 69 | totsp=sum(sp.values()) 70 | if totsp > 0.0 and len(G) > 1: 71 | closeness_centrality[n]= (len(sp)-1.0) / totsp 72 | # normalize to number of nodes-1 in connected part 73 | if normalized: 74 | s=(len(sp)-1.0) / ( len(G) - 1 ) 75 | closeness_centrality[n] *= s 76 | else: 77 | closeness_centrality[n]=0.0 78 | if v is not None: 79 | return closeness_centrality[v] 80 | else: 81 | return closeness_centrality 82 | 83 | -------------------------------------------------------------------------------- /appengine/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=True) 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 | -------------------------------------------------------------------------------- /appengine/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,normalized=True) 22 | b_answer={0: 2.0, 1: 2.0, 2: 2.0, 3: 2.0} 23 | for n in sorted(G): 24 | assert_almost_equal(b[n],b_answer[n]) 25 | 26 | 27 | def test_P4_normalized(self): 28 | """Closeness centrality: P4 normalized""" 29 | G=networkx.path_graph(4) 30 | b=networkx.current_flow_closeness_centrality(G,normalized=True) 31 | b_answer={0: 1./2, 1: 3./4, 2: 3./4, 3:1./2} 32 | for n in sorted(G): 33 | assert_almost_equal(b[n],b_answer[n]) 34 | 35 | 36 | def test_P4(self): 37 | """Closeness centrality: P4""" 38 | G=networkx.path_graph(4) 39 | b=networkx.current_flow_closeness_centrality(G,normalized=False) 40 | b_answer={0: 1.0/6, 1: 1.0/4, 2: 1.0/4, 3:1.0/6} 41 | for n in sorted(G): 42 | assert_almost_equal(b[n],b_answer[n]) 43 | 44 | def test_star(self): 45 | """Closeness centrality: star """ 46 | G=networkx.Graph() 47 | G.add_star(['a','b','c','d']) 48 | b=networkx.current_flow_closeness_centrality(G,normalized=True) 49 | b_answer={'a': 1.0, 'b': 0.6, 'c': 0.6, 'd':0.6} 50 | for n in sorted(G): 51 | assert_almost_equal(b[n],b_answer[n]) 52 | 53 | 54 | 55 | class TestWeightedFlowClosenessCentrality(object): 56 | pass 57 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/centrality/tests/test_eigenvector_centrality.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import math 3 | from nose import SkipTest 4 | from nose.tools import * 5 | import networkx 6 | 7 | class TestEigenvectorCentrality(object): 8 | numpy=1 # nosetests attribute, use nosetests -a 'not numpy' to skip test 9 | @classmethod 10 | def setupClass(cls): 11 | global np 12 | try: 13 | import numpy as np 14 | except ImportError: 15 | raise SkipTest('NumPy not available.') 16 | 17 | def test_K5(self): 18 | """Eigenvector centrality: K5""" 19 | G=networkx.complete_graph(5) 20 | b=networkx.eigenvector_centrality(G) 21 | v=math.sqrt(1/5.0) 22 | b_answer=dict.fromkeys(G,v) 23 | for n in sorted(G): 24 | assert_almost_equal(b[n],b_answer[n]) 25 | b=networkx.eigenvector_centrality_numpy(G) 26 | for n in sorted(G): 27 | assert_almost_equal(b[n],b_answer[n],places=3) 28 | 29 | def test_P3(self): 30 | """Eigenvector centrality: P3""" 31 | G=networkx.path_graph(3) 32 | b_answer={0: 0.5, 1: 0.7071, 2: 0.5} 33 | b=networkx.eigenvector_centrality_numpy(G) 34 | for n in sorted(G): 35 | assert_almost_equal(b[n],b_answer[n],places=4) 36 | 37 | 38 | class TestEigenvectorCentralityDirected(object): 39 | numpy=1 # nosetests attribute, use nosetests -a 'not numpy' to skip test 40 | @classmethod 41 | def setupClass(cls): 42 | global np 43 | try: 44 | import numpy as np 45 | except ImportError: 46 | raise SkipTest('NumPy not available.') 47 | 48 | def setUp(self): 49 | 50 | G=networkx.DiGraph() 51 | 52 | edges=[(1,2),(1,3),(2,4),(3,2),(3,5),(4,2),(4,5),(4,6),\ 53 | (5,6),(5,7),(5,8),(6,8),(7,1),(7,5),\ 54 | (7,8),(8,6),(8,7)] 55 | 56 | G.add_edges_from(edges,weight=2.0) 57 | self.G=G 58 | self.G.evc=[0.25368793, 0.19576478, 0.32817092, 0.40430835, 59 | 0.48199885, 0.15724483, 0.51346196, 0.32475403] 60 | 61 | H=networkx.DiGraph() 62 | 63 | edges=[(1,2),(1,3),(2,4),(3,2),(3,5),(4,2),(4,5),(4,6),\ 64 | (5,6),(5,7),(5,8),(6,8),(7,1),(7,5),\ 65 | (7,8),(8,6),(8,7)] 66 | 67 | G.add_edges_from(edges) 68 | self.H=G 69 | self.H.evc=[0.25368793, 0.19576478, 0.32817092, 0.40430835, 70 | 0.48199885, 0.15724483, 0.51346196, 0.32475403] 71 | 72 | 73 | def test_eigenvector_centrality_weighted(self): 74 | G=self.G 75 | p=networkx.eigenvector_centrality_numpy(G) 76 | for (a,b) in zip(list(p.values()),self.G.evc): 77 | assert_almost_equal(a,b) 78 | 79 | def test_eigenvector_centrality_unweighted(self): 80 | G=self.H 81 | p=networkx.eigenvector_centrality_numpy(G) 82 | for (a,b) in zip(list(p.values()),self.G.evc): 83 | assert_almost_equal(a,b) 84 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/chordal/__init__.py: -------------------------------------------------------------------------------- 1 | from networkx.algorithms.chordal.chordal_alg import * 2 | 3 | 4 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/community/__init__.py: -------------------------------------------------------------------------------- 1 | from networkx.algorithms.community.kclique import * 2 | -------------------------------------------------------------------------------- /appengine/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 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, 5)) 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 cliques is None: 52 | cliques = nx.find_cliques(G) 53 | cliques = [frozenset(c) for c in cliques if len(c) >= k] 54 | 55 | # First index which nodes are in which cliques 56 | membership_dict = defaultdict(list) 57 | for clique in cliques: 58 | for node in clique: 59 | membership_dict[node].append(clique) 60 | 61 | # For each clique, see which adjacent cliques percolate 62 | perc_graph = nx.Graph() 63 | for clique in cliques: 64 | for adj_clique in _get_adjacent_cliques(clique, membership_dict): 65 | if len(clique.intersection(adj_clique)) >= (k - 1): 66 | perc_graph.add_edge(clique, adj_clique) 67 | 68 | # Connected components of clique graph with perc edges 69 | # are the percolated cliques 70 | for component in nx.connected_components(perc_graph): 71 | yield(frozenset.union(*component)) 72 | 73 | def _get_adjacent_cliques(clique, membership_dict): 74 | adjacent_cliques = set() 75 | for n in clique: 76 | for adj_clique in membership_dict[n]: 77 | if clique != adj_clique: 78 | adjacent_cliques.add(adj_clique) 79 | return adjacent_cliques 80 | -------------------------------------------------------------------------------- /appengine/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 | 6 | def test_overlaping_K5(): 7 | G = nx.Graph() 8 | G.add_edges_from(combinations(range(5), 2)) # Add a five clique 9 | G.add_edges_from(combinations(range(2,7), 2)) # Add another five clique 10 | c = list(nx.k_clique_communities(G, 4)) 11 | assert_equal(c,[frozenset([0, 1, 2, 3, 4, 5, 6])]) 12 | c= list(nx.k_clique_communities(G, 5)) 13 | assert_equal(c,[]) 14 | 15 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/components/tests/test_attracting.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | 5 | 6 | class TestAttractingComponents(object): 7 | def setUp(self): 8 | self.G1 = nx.DiGraph() 9 | self.G1.add_edges_from([(5,11),(11,2),(11,9),(11,10), 10 | (7,11),(7,8),(8,9),(3,8),(3,10)]) 11 | self.G2 = nx.DiGraph() 12 | self.G2.add_edges_from([(0,1),(0,2),(1,1),(1,2),(2,1)]) 13 | 14 | self.G3 = nx.DiGraph() 15 | self.G3.add_edges_from([(0,1),(1,2),(2,1),(0,3),(3,4),(4,3)]) 16 | 17 | def test_attracting_components(self): 18 | ac = nx.attracting_components(self.G1) 19 | assert_true([2] in ac) 20 | assert_true([9] in ac) 21 | assert_true([10] in ac) 22 | 23 | ac = nx.attracting_components(self.G2) 24 | ac = [tuple(sorted(x)) for x in ac] 25 | assert_true(ac == [(1,2)]) 26 | 27 | ac = nx.attracting_components(self.G3) 28 | ac = [tuple(sorted(x)) for x in ac] 29 | assert_true((1,2) in ac) 30 | assert_true((3,4) in ac) 31 | assert_equal(len(ac), 2) 32 | 33 | def test_number_attacting_components(self): 34 | assert_equal(len(nx.attracting_components(self.G1)), 3) 35 | assert_equal(len(nx.attracting_components(self.G2)), 1) 36 | assert_equal(len(nx.attracting_components(self.G3)), 2) 37 | 38 | def test_is_attracting_component(self): 39 | assert_false(nx.is_attracting_component(self.G1)) 40 | assert_false(nx.is_attracting_component(self.G2)) 41 | assert_false(nx.is_attracting_component(self.G3)) 42 | g2 = self.G3.subgraph([1,2]) 43 | assert_true(nx.is_attracting_component(g2)) 44 | 45 | def test_attracting_component_subgraphs(self): 46 | subgraphs = nx.attracting_component_subgraphs(self.G1) 47 | for subgraph in subgraphs: 48 | assert_equal(len(subgraph), 1) 49 | 50 | self.G2.add_edge(1,2,eattr='red') # test attrs copied to subgraphs 51 | self.G2.node[2]['nattr']='blue' 52 | self.G2.graph['gattr']='green' 53 | subgraphs = nx.attracting_component_subgraphs(self.G2) 54 | assert_equal(len(subgraphs), 1) 55 | SG2=subgraphs[0] 56 | assert_true(1 in SG2) 57 | assert_true(2 in SG2) 58 | assert_equal(SG2[1][2]['eattr'],'red') 59 | assert_equal(SG2.node[2]['nattr'],'blue') 60 | assert_equal(SG2.graph['gattr'],'green') 61 | SG2.add_edge(1,2,eattr='blue') 62 | assert_equal(SG2[1][2]['eattr'],'blue') 63 | assert_equal(self.G2[1][2]['eattr'],'red') 64 | 65 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/components/tests/test_connected.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | from networkx import convert_node_labels_to_integers as cnlti 5 | from networkx import NetworkXError 6 | 7 | class TestConnected: 8 | 9 | def setUp(self): 10 | G1=cnlti(nx.grid_2d_graph(2,2),first_label=0,ordering="sorted") 11 | G2=cnlti(nx.lollipop_graph(3,3),first_label=4,ordering="sorted") 12 | G3=cnlti(nx.house_graph(),first_label=10,ordering="sorted") 13 | self.G=nx.union(G1,G2) 14 | self.G=nx.union(self.G,G3) 15 | self.DG=nx.DiGraph([(1,2),(1,3),(2,3)]) 16 | self.grid=cnlti(nx.grid_2d_graph(4,4),first_label=1) 17 | 18 | def test_connected_components(self): 19 | cc=nx.connected_components 20 | G=self.G 21 | C=[[0, 1, 2, 3], [4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]] 22 | assert_equal(sorted([sorted(g) for g in cc(G)]),sorted(C)) 23 | 24 | def test_number_connected_components(self): 25 | ncc=nx.number_connected_components 26 | assert_equal(ncc(self.G),3) 27 | 28 | def test_number_connected_components2(self): 29 | ncc=nx.number_connected_components 30 | assert_equal(ncc(self.grid),1) 31 | 32 | def test_connected_components2(self): 33 | cc=nx.connected_components 34 | G=self.grid 35 | C=[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]] 36 | assert_equal(sorted([sorted(g) for g in cc(G)]),sorted(C)) 37 | 38 | def test_node_connected_components(self): 39 | ncc=nx.node_connected_component 40 | G=self.grid 41 | C=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] 42 | assert_equal(sorted(ncc(G,1)),sorted(C)) 43 | 44 | def test_connected_component_subgraphs(self): 45 | G=self.grid 46 | G.add_edge(1,2,eattr='red') # test attributes copied to subgraphs 47 | G.node[1]['nattr']='blue' 48 | G.graph['gattr']='green' 49 | ccs=nx.connected_component_subgraphs(G) 50 | assert_equal(len(ccs),1) 51 | sg=ccs[0] 52 | assert_equal(sorted(sg.nodes()),list(range(1,17))) 53 | assert_equal(sg[1][2]['eattr'],'red') 54 | assert_equal(sg.node[1]['nattr'],'blue') 55 | assert_equal(sg.graph['gattr'],'green') 56 | sg[1][2]['eattr']='blue' 57 | assert_equal(G[1][2]['eattr'],'red') 58 | assert_equal(sg[1][2]['eattr'],'blue') 59 | 60 | 61 | def test_is_connected(self): 62 | assert_true(nx.is_connected(self.grid)) 63 | G=nx.Graph() 64 | G.add_nodes_from([1,2]) 65 | assert_false(nx.is_connected(G)) 66 | 67 | def test_connected_raise(self): 68 | assert_raises(NetworkXError,nx.connected_components,self.DG) 69 | assert_raises(NetworkXError,nx.number_connected_components,self.DG) 70 | assert_raises(NetworkXError,nx.connected_component_subgraphs,self.DG) 71 | assert_raises(NetworkXError,nx.node_connected_component,self.DG,1) 72 | assert_raises(NetworkXError,nx.is_connected,self.DG) 73 | -------------------------------------------------------------------------------- /appengine/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 NetworkXError 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), 12 | (4,5),(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 | wcc=nx.weakly_connected_components 38 | cc=nx.connected_components 39 | for G,C in self.gc: 40 | U=G.to_undirected() 41 | w=sorted([sorted(g) for g in wcc(G)]) 42 | c=sorted([sorted(g) for g in cc(U)]) 43 | assert_equal(w,c) 44 | 45 | def test_number_weakly_connected_components(self): 46 | wcc=nx.number_weakly_connected_components 47 | cc=nx.number_connected_components 48 | for G,C in self.gc: 49 | U=G.to_undirected() 50 | w=wcc(G) 51 | c=cc(U) 52 | assert_equal(w,c) 53 | 54 | def test_weakly_connected_component_subgraphs(self): 55 | wcc=nx.weakly_connected_component_subgraphs 56 | cc=nx.connected_component_subgraphs 57 | for G,C in self.gc: 58 | U=G.to_undirected() 59 | w=sorted([sorted(g.nodes()) for g in wcc(G)]) 60 | c=sorted([sorted(g.nodes()) for g in cc(U)]) 61 | assert_equal(w,c) 62 | G,C=self.gc[0] 63 | G.add_edge(1,2,eattr='red') 64 | G.node[1]['nattr']='blue' 65 | G.graph['gattr']='green' 66 | sgs=wcc(G)[0] 67 | assert_equal(sgs[1][2]['eattr'],'red') 68 | assert_equal(sgs.node[1]['nattr'],'blue') 69 | assert_equal(sgs.graph['gattr'],'green') 70 | sgs[1][2]['eattr']='blue' 71 | assert_equal(G[1][2]['eattr'],'red') 72 | assert_equal(sgs[1][2]['eattr'],'blue') 73 | 74 | def test_is_weakly_connected(self): 75 | wcc=nx.is_weakly_connected 76 | cc=nx.is_connected 77 | for G,C in self.gc: 78 | U=G.to_undirected() 79 | assert_equal(wcc(G),cc(U)) 80 | 81 | 82 | def test_connected_raise(self): 83 | G=nx.Graph() 84 | assert_raises(NetworkXError,nx.weakly_connected_components,G) 85 | assert_raises(NetworkXError,nx.number_weakly_connected_components,G) 86 | assert_raises(NetworkXError,nx.weakly_connected_component_subgraphs,G) 87 | assert_raises(NetworkXError,nx.is_weakly_connected,G) 88 | 89 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/flow/__init__.py: -------------------------------------------------------------------------------- 1 | from networkx.algorithms.flow.maxflow import * 2 | from networkx.algorithms.flow.mincost import * 3 | 4 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/flow/tests/test_maxflow_large_graph.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """Max flow algorithm test suite on large graphs. 3 | 4 | Run with nose: nosetests -v test_max_flow.py 5 | """ 6 | 7 | __author__ = """Loïc Séguin-C. """ 8 | # Copyright (C) 2010 Loïc Séguin-C. 9 | # All rights reserved. 10 | # BSD license. 11 | 12 | 13 | import networkx as nx 14 | from nose.tools import * 15 | 16 | def gen_pyramid(N): 17 | # This graph admits a flow of value 1 for which every arc is at 18 | # capacity (except the arcs incident to the sink which have 19 | # infinite capacity). 20 | G = nx.DiGraph() 21 | 22 | for i in range(N - 1): 23 | cap = 1. / (i + 2) 24 | for j in range(i + 1): 25 | G.add_edge((i, j), (i + 1, j), 26 | capacity = cap) 27 | cap = 1. / (i + 1) - cap 28 | G.add_edge((i, j), (i + 1, j + 1), 29 | capacity = cap) 30 | cap = 1. / (i + 2) - cap 31 | 32 | for j in range(N): 33 | G.add_edge((N - 1, j), 't') 34 | 35 | return G 36 | 37 | 38 | class TestMaxflowLargeGraph: 39 | def test_complete_graph(self): 40 | N = 50 41 | G = nx.complete_graph(N) 42 | for (u, v) in G.edges(): 43 | G[u][v]['capacity'] = 5 44 | assert_equal(nx.ford_fulkerson(G, 1, 2)[0], 5 * (N - 1)) 45 | 46 | def test_pyramid(self): 47 | N = 10 48 | # N = 100 # this gives a graph with 5051 nodes 49 | G = gen_pyramid(N) 50 | assert_almost_equal(nx.ford_fulkerson(G, (0, 0), 't')[0], 1.) 51 | 52 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/isolate.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """ 3 | Functions for identifying isolate (degree zero) nodes. 4 | """ 5 | # Copyright (C) 2004-2011 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 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/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 -------------------------------------------------------------------------------- /appengine/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 -------------------------------------------------------------------------------- /appengine/networkx/algorithms/isomorphism/tests/si2_b06_m200.A99: -------------------------------------------------------------------------------- 1 | ( 2 |   3 |    4 |  5 |   6 |   !!!" $%$%#!#'&$& !" -------------------------------------------------------------------------------- /appengine/networkx/algorithms/isomorphism/tests/si2_b06_m200.B99: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uwescience/myria-web/b1c175a5cbe76d4f2219b192635085ece1326588/appengine/networkx/algorithms/isomorphism/tests/si2_b06_m200.B99 -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/link_analysis/tests/test_pagerank.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 TestPageRank: 13 | 14 | def setUp(self): 15 | G=networkx.DiGraph() 16 | edges=[(1,2),(1,3),\ 17 | (3,1),(3,2),(3,5),\ 18 | (4,5),(4,6),\ 19 | (5,4),(5,6),\ 20 | (6,4)] 21 | 22 | G.add_edges_from(edges) 23 | self.G=G 24 | self.G.pagerank=dict(zip(G, 25 | [0.03721197,0.05395735,0.04150565, 26 | 0.37508082,0.20599833, 0.28624589])) 27 | 28 | def test_pagerank(self): 29 | G=self.G 30 | p=networkx.pagerank(G,alpha=0.9,tol=1.e-08) 31 | for n in G: 32 | assert_almost_equal(p[n],G.pagerank[n],places=4) 33 | 34 | @attr('numpy') 35 | def test_numpy_pagerank(self): 36 | try: 37 | import numpy 38 | except ImportError: 39 | raise SkipTest('numpy not available.') 40 | G=self.G 41 | p=networkx.pagerank_numpy(G,alpha=0.9) 42 | for n in G: 43 | assert_almost_equal(p[n],G.pagerank[n],places=4) 44 | 45 | 46 | @attr('numpy') 47 | def test_google_matrix(self): 48 | try: 49 | import numpy.linalg 50 | except ImportError: 51 | raise SkipTest('numpy not available.') 52 | G=self.G 53 | M=networkx.google_matrix(G,alpha=0.9) 54 | e,ev=numpy.linalg.eig(M.T) 55 | p=numpy.array(ev[:,0]/ev[:,0].sum())[:,0] 56 | for (a,b) in zip(p,self.G.pagerank.values()): 57 | assert_almost_equal(a,b) 58 | 59 | 60 | def test_scipy_pagerank(self): 61 | G=self.G 62 | try: 63 | import scipy 64 | except ImportError: 65 | raise SkipTest('scipy not available.') 66 | p=networkx.pagerank_scipy(G,alpha=0.9,tol=1.e-08) 67 | for n in G: 68 | assert_almost_equal(p[n],G.pagerank[n],places=4) 69 | 70 | def test_personalization(self): 71 | G=networkx.complete_graph(4) 72 | personalize={0:1,1:1,2:4,3:4} 73 | answer={0:0.1,1:0.1,2:0.4,3:0.4} 74 | p=networkx.pagerank(G,alpha=0.0,personalization=personalize) 75 | for n in G: 76 | assert_almost_equal(p[n],answer[n],places=4) 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/shortest_paths/tests/test_unweighted.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | 5 | class TestUnweightedPath: 6 | 7 | def setUp(self): 8 | from networkx import convert_node_labels_to_integers as cnlti 9 | self.grid=cnlti(nx.grid_2d_graph(4,4),first_label=1,ordering="sorted") 10 | self.cycle=nx.cycle_graph(7) 11 | self.directed_cycle=nx.cycle_graph(7,create_using=nx.DiGraph()) 12 | 13 | 14 | def test_bidirectional_shortest_path(self): 15 | assert_equal(nx.bidirectional_shortest_path(self.cycle,0,3), 16 | [0, 1, 2, 3]) 17 | assert_equal(nx.bidirectional_shortest_path(self.cycle,0,4), 18 | [0, 6, 5, 4]) 19 | assert_equal(nx.bidirectional_shortest_path(self.grid,1,12), 20 | [1, 2, 3, 4, 8, 12]) 21 | assert_equal(nx.bidirectional_shortest_path(self.directed_cycle,0,3), 22 | [0, 1, 2, 3]) 23 | 24 | def test_shortest_path_length(self): 25 | assert_equal(nx.shortest_path_length(self.cycle,0,3),3) 26 | assert_equal(nx.shortest_path_length(self.grid,1,12),5) 27 | assert_equal(nx.shortest_path_length(self.directed_cycle,0,4),4) 28 | # now with weights 29 | assert_equal(nx.shortest_path_length(self.cycle,0,3,weight=True),3) 30 | assert_equal(nx.shortest_path_length(self.grid,1,12,weight=True),5) 31 | assert_equal(nx.shortest_path_length(self.directed_cycle,0,4,weight=True),4) 32 | 33 | 34 | def test_single_source_shortest_path(self): 35 | p=nx.single_source_shortest_path(self.cycle,0) 36 | assert_equal(p[3],[0,1,2,3]) 37 | 38 | def test_single_source_shortest_path_length(self): 39 | assert_equal(nx.single_source_shortest_path_length(self.cycle,0), 40 | {0:0,1:1,2:2,3:3,4:3,5:2,6:1}) 41 | 42 | def test_all_pairs_shortest_path(self): 43 | p=nx.all_pairs_shortest_path(self.cycle) 44 | assert_equal(p[0][3],[0,1,2,3]) 45 | p=nx.all_pairs_shortest_path(self.grid) 46 | assert_equal(p[1][12],[1, 2, 3, 4, 8, 12]) 47 | 48 | def test_all_pairs_shortest_path_length(self): 49 | l=nx.all_pairs_shortest_path_length(self.cycle) 50 | assert_equal(l[0],{0:0,1:1,2:2,3:3,4:3,5:2,6:1}) 51 | l=nx.all_pairs_shortest_path_length(self.grid) 52 | assert_equal(l[1][16],6) 53 | 54 | def test_predecessor(self): 55 | G=nx.path_graph(4) 56 | assert_equal(nx.predecessor(G,0),{0: [], 1: [0], 2: [1], 3: [2]}) 57 | assert_equal(nx.predecessor(G,0,3),[2]) 58 | G=nx.grid_2d_graph(2,2) 59 | assert_equal(sorted(nx.predecessor(G,(0,0)).items()), 60 | [((0, 0), []), ((0, 1), [(0, 0)]), 61 | ((1, 0), [(0, 0)]), ((1, 1), [(0, 1), (1, 0)])]) 62 | 63 | 64 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/tests/test_block.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx 4 | 5 | class TestBlock: 6 | 7 | def test_path(self): 8 | G=networkx.path_graph(6) 9 | partition=[[0,1],[2,3],[4,5]] 10 | M=networkx.blockmodel(G,partition) 11 | assert_equal(sorted(M.nodes()),[0,1,2]) 12 | assert_equal(sorted(M.edges()),[(0,1),(1,2)]) 13 | for n in M.nodes(): 14 | assert_equal(M.node[n]['nedges'],1) 15 | assert_equal(M.node[n]['nnodes'],2) 16 | assert_equal(M.node[n]['density'],1.0) 17 | 18 | def test_weighted_path(self): 19 | G=networkx.path_graph(6) 20 | G[0][1]['weight']=1 21 | G[1][2]['weight']=2 22 | G[2][3]['weight']=3 23 | G[3][4]['weight']=4 24 | G[4][5]['weight']=5 25 | partition=[[0,1],[2,3],[4,5]] 26 | M=networkx.blockmodel(G,partition) 27 | assert_equal(sorted(M.nodes()),[0,1,2]) 28 | assert_equal(sorted(M.edges()),[(0,1),(1,2)]) 29 | assert_equal(M[0][1]['weight'],2) 30 | assert_equal(M[1][2]['weight'],4) 31 | for n in M.nodes(): 32 | assert_equal(M.node[n]['nedges'],1) 33 | assert_equal(M.node[n]['nnodes'],2) 34 | assert_equal(M.node[n]['density'],1.0) 35 | 36 | 37 | def test_barbell(self): 38 | G=networkx.barbell_graph(3,0) 39 | partition=[[0,1,2],[3,4,5]] 40 | M=networkx.blockmodel(G,partition) 41 | assert_equal(sorted(M.nodes()),[0,1]) 42 | assert_equal(sorted(M.edges()),[(0,1)]) 43 | for n in M.nodes(): 44 | assert_equal(M.node[n]['nedges'],3) 45 | assert_equal(M.node[n]['nnodes'],3) 46 | assert_equal(M.node[n]['density'],1.0) 47 | 48 | def test_barbell_plus(self): 49 | G=networkx.barbell_graph(3,0) 50 | G.add_edge(0,5) # add extra edge between bells 51 | partition=[[0,1,2],[3,4,5]] 52 | M=networkx.blockmodel(G,partition) 53 | assert_equal(sorted(M.nodes()),[0,1]) 54 | assert_equal(sorted(M.edges()),[(0,1)]) 55 | assert_equal(M[0][1]['weight'],2) 56 | for n in M.nodes(): 57 | assert_equal(M.node[n]['nedges'],3) 58 | assert_equal(M.node[n]['nnodes'],3) 59 | assert_equal(M.node[n]['density'],1.0) 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /appengine/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 | 18 | def test_diameter(self): 19 | assert_equal(networkx.diameter(self.G),6) 20 | 21 | def test_radius(self): 22 | assert_equal(networkx.radius(self.G),4) 23 | 24 | def test_periphery(self): 25 | assert_equal(set(networkx.periphery(self.G)),set([1, 4, 13, 16])) 26 | 27 | def test_center(self): 28 | assert_equal(set(networkx.center(self.G)),set([6, 7, 10, 11])) 29 | 30 | def test_radius_exception(self): 31 | G=networkx.Graph() 32 | G.add_edge(1,2) 33 | G.add_edge(3,4) 34 | assert_raises(networkx.NetworkXError, networkx.diameter, G) 35 | 36 | def test_eccentricity_exception(self): 37 | G=networkx.Graph() 38 | G.add_edge(1,2) 39 | G.add_edge(3,4) 40 | assert_raises(networkx.NetworkXError, networkx.eccentricity, G) 41 | 42 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/tests/test_euler.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # run with nose: nosetests -v test_euler.py 3 | 4 | from nose.tools import * 5 | import networkx as nx 6 | from networkx import is_eulerian,eulerian_circuit 7 | 8 | class TestEuler: 9 | 10 | def test_is_eulerian(self): 11 | assert_true(is_eulerian(nx.complete_graph(5))) 12 | assert_true(is_eulerian(nx.complete_graph(7))) 13 | assert_true(is_eulerian(nx.hypercube_graph(4))) 14 | assert_true(is_eulerian(nx.hypercube_graph(6))) 15 | 16 | assert_false(is_eulerian(nx.complete_graph(4))) 17 | assert_false(is_eulerian(nx.complete_graph(6))) 18 | assert_false(is_eulerian(nx.hypercube_graph(3))) 19 | assert_false(is_eulerian(nx.hypercube_graph(5))) 20 | 21 | assert_false(is_eulerian(nx.petersen_graph())) 22 | 23 | assert_false(is_eulerian(nx.path_graph(4))) 24 | 25 | def test_eulerian_circuit_cycle(self): 26 | G=nx.cycle_graph(4) 27 | 28 | edges=list(eulerian_circuit(G,source=0)) 29 | nodes=[u for u,v in edges] 30 | assert_equal(nodes,[0,1,2,3]) 31 | assert_equal(edges,[(0,1),(1,2),(2,3),(3,0)]) 32 | 33 | edges=list(eulerian_circuit(G,source=1)) 34 | nodes=[u for u,v in edges] 35 | assert_equal(nodes,[1,0,3,2]) 36 | assert_equal(edges,[(1,0),(0,3),(3,2),(2,1)]) 37 | 38 | 39 | def test_eulerian_circuit_digraph(self): 40 | G=nx.DiGraph() 41 | G.add_cycle([0,1,2,3]) 42 | 43 | edges=list(eulerian_circuit(G,source=0)) 44 | nodes=[u for u,v in edges] 45 | assert_equal(nodes,[0,1,2,3]) 46 | assert_equal(edges,[(0,1),(1,2),(2,3),(3,0)]) 47 | 48 | edges=list(eulerian_circuit(G,source=1)) 49 | nodes=[u for u,v in edges] 50 | assert_equal(nodes,[1,2,3,0]) 51 | assert_equal(edges,[(1,2),(2,3),(3,0),(0,1)]) 52 | 53 | 54 | def test_eulerian_circuit_multigraph(self): 55 | G=nx.MultiGraph() 56 | G.add_cycle([0,1,2,3]) 57 | G.add_edge(1,2) 58 | G.add_edge(1,2) 59 | edges=list(eulerian_circuit(G,source=0)) 60 | nodes=[u for u,v in edges] 61 | assert_equal(nodes,[0,1,2,1,2,3]) 62 | assert_equal(edges,[(0,1),(1,2),(2,1),(1,2),(2,3),(3,0)]) 63 | 64 | 65 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/tests/test_graphical.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | 5 | def test_valid_degree_sequence1(): 6 | n = 100 7 | p = .3 8 | for i in range(10): 9 | G = nx.erdos_renyi_graph(n,p) 10 | deg = list(G.degree().values()) 11 | assert_true( nx.is_valid_degree_sequence(deg, method='eg') ) 12 | assert_true( nx.is_valid_degree_sequence(deg, method='hh') ) 13 | 14 | def test_valid_degree_sequence2(): 15 | n = 100 16 | for i in range(10): 17 | G = nx.barabasi_albert_graph(n,1) 18 | deg = list(G.degree().values()) 19 | assert_true( nx.is_valid_degree_sequence(deg, method='eg') ) 20 | assert_true( nx.is_valid_degree_sequence(deg, method='hh') ) 21 | 22 | def test_atlas(): 23 | for graph in nx.graph_atlas_g(): 24 | deg = list(graph.degree().values()) 25 | assert_true( nx.is_valid_degree_sequence(deg, method='eg') ) 26 | assert_true( nx.is_valid_degree_sequence(deg, method='hh') ) 27 | 28 | def test_small_graph_true(): 29 | z=[5,3,3,3,3,2,2,2,1,1,1] 30 | assert_true(nx.is_valid_degree_sequence(z, method='hh')) 31 | assert_true(nx.is_valid_degree_sequence(z, method='eg')) 32 | z=[10,3,3,3,3,2,2,2,2,2,2] 33 | assert_true(nx.is_valid_degree_sequence(z, method='hh')) 34 | assert_true(nx.is_valid_degree_sequence(z, method='eg')) 35 | z=[1, 1, 1, 1, 1, 2, 2, 2, 3, 4] 36 | assert_true(nx.is_valid_degree_sequence(z, method='hh')) 37 | assert_true(nx.is_valid_degree_sequence(z, method='eg')) 38 | 39 | 40 | 41 | def test_small_graph_false(): 42 | z=[1000,3,3,3,3,2,2,2,1,1,1] 43 | assert_false(nx.is_valid_degree_sequence(z, method='hh')) 44 | assert_false(nx.is_valid_degree_sequence(z, method='eg')) 45 | z=[6,5,4,4,2,1,1,1] 46 | assert_false(nx.is_valid_degree_sequence(z, method='hh')) 47 | assert_false(nx.is_valid_degree_sequence(z, method='eg')) 48 | z=[1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 4] 49 | assert_false(nx.is_valid_degree_sequence(z, method='hh')) 50 | assert_false(nx.is_valid_degree_sequence(z, method='eg')) 51 | 52 | 53 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/tests/test_smetric.py: -------------------------------------------------------------------------------- 1 | 2 | from nose.tools import assert_equal 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 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/tests/test_swap.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | from networkx import * 4 | 5 | def test_double_edge_swap(): 6 | graph = barabasi_albert_graph(200,1) 7 | degreeStart = sorted(graph.degree().values()) 8 | G = connected_double_edge_swap(graph, 40) 9 | assert_true(is_connected(graph)) 10 | degseq = sorted(graph.degree().values()) 11 | assert_true(degreeStart == degseq) 12 | G = double_edge_swap(graph, 40) 13 | degseq2 = sorted(graph.degree().values()) 14 | assert_true(degreeStart == degseq2) 15 | 16 | def test_degree_seq_c4(): 17 | G = cycle_graph(4) 18 | degree_start = sorted(G.degree().values()) 19 | G = double_edge_swap(G,1,100) 20 | degseq = sorted(G.degree().values()) 21 | assert_true(degree_start == degseq) 22 | 23 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/tests/test_vitality.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from nose.tools import * 4 | import networkx as nx 5 | 6 | class TestVitality: 7 | 8 | def test_closeness_vitality_unweighted(self): 9 | G=nx.cycle_graph(3) 10 | v=nx.closeness_vitality(G) 11 | assert_equal(v,{0:4.0, 1:4.0, 2: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 | 32 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/traversal/__init__.py: -------------------------------------------------------------------------------- 1 | import networkx.algorithms.traversal.depth_first_search 2 | from networkx.algorithms.traversal.depth_first_search import * 3 | import networkx.algorithms.traversal.breadth_first_search 4 | from networkx.algorithms.traversal.breadth_first_search import * 5 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/traversal/breadth_first_search.py: -------------------------------------------------------------------------------- 1 | """ 2 | ==================== 3 | Breadth-first search 4 | ==================== 5 | 6 | Basic algorithms for breadth-first searching. 7 | """ 8 | __author__ = """\n""".join(['Aric Hagberg ']) 9 | 10 | __all__ = ['bfs_edges', 'bfs_tree', 11 | 'bfs_predecessors', 'bfs_successors'] 12 | 13 | import networkx as nx 14 | from collections import defaultdict 15 | 16 | def bfs_edges(G,source): 17 | """Produce edges in a breadth-first-search starting at source.""" 18 | # Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py 19 | # by D. Eppstein, July 2004. 20 | visited=set([source]) 21 | stack = [(source,iter(G[source]))] 22 | while stack: 23 | parent,children = stack[0] 24 | try: 25 | child = next(children) 26 | if child not in visited: 27 | yield parent,child 28 | visited.add(child) 29 | stack.append((child,iter(G[child]))) 30 | except StopIteration: 31 | stack.pop(0) 32 | 33 | 34 | def bfs_tree(G, source): 35 | """Return directed tree of breadth-first-search from source.""" 36 | return nx.DiGraph(bfs_edges(G,source)) 37 | 38 | 39 | def bfs_predecessors(G, source): 40 | """Return dictionary of predecessors in breadth-first-search from source.""" 41 | return dict((t,s) for s,t in bfs_edges(G,source)) 42 | 43 | 44 | def bfs_successors(G, source): 45 | """Return dictionary of successors in breadth-first-search from source.""" 46 | d=defaultdict(list) 47 | for s,t in bfs_edges(G,source): 48 | d[s].append(t) 49 | return dict(d) 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/traversal/tests/test_bfs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | 5 | class TestBFS: 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 | 13 | def test_successor(self): 14 | assert_equal(nx.bfs_successors(self.G,source=0), 15 | {0: [1], 1: [2,3], 2:[4]}) 16 | 17 | def test_predecessor(self): 18 | assert_equal(nx.bfs_predecessors(self.G,source=0), 19 | {1: 0, 2: 1, 3: 1, 4: 2}) 20 | 21 | def test_bfs_tree(self): 22 | T=nx.bfs_tree(self.G,source=0) 23 | assert_equal(sorted(T.nodes()),sorted(self.G.nodes())) 24 | assert_equal(sorted(T.edges()),[(0, 1), (1, 2), (1, 3), (2, 4)]) 25 | 26 | def test_bfs_edges(self): 27 | edges=nx.bfs_edges(self.G,source=0) 28 | assert_equal(list(edges),[(0, 1), (1, 2), (1, 3), (2, 4)]) 29 | 30 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/networkx/algorithms/vitality.py: -------------------------------------------------------------------------------- 1 | """ 2 | Vitality measures. 3 | 4 | """ 5 | # Copyright (C) 2010 by 6 | # Aric Hagberg 7 | # Dan Schult 8 | # Pieter Swart 9 | # All rights reserved. 10 | # BSD license. 11 | __author__ = "\n".join(['Aric Hagberg (hagberg@lanl.gov)', 12 | 'Renato Fabbri']) 13 | 14 | __all__ = ['closeness_vitality'] 15 | 16 | import networkx as nx 17 | 18 | def weiner_index(G, weight=None): 19 | # compute sum of distances between all node pairs 20 | # (with optional weights) 21 | weiner=0.0 22 | if weight is None: 23 | for n in G: 24 | path_length=nx.single_source_shortest_path_length(G,n) 25 | weiner+=sum(path_length.values()) 26 | else: 27 | for n in G: 28 | path_length=nx.single_source_dijkstra_path_length(G, 29 | n,weight=weight) 30 | weiner+=sum(path_length.values()) 31 | return weiner 32 | 33 | 34 | def closeness_vitality(G, v=None, weight=None): 35 | """Compute closeness vitality for nodes. 36 | 37 | Closeness vitality at a node is the change in the sum of distances 38 | between all node pairs when excluding a that node. 39 | 40 | Parameters 41 | ---------- 42 | G : graph 43 | A networkx graph 44 | 45 | v : node, optional 46 | Return only the value for node v. 47 | 48 | weight : None or string, optional 49 | If None, edge weights are ignored. 50 | Otherwise holds the name of the edge attribute used as weight. 51 | 52 | Returns 53 | ------- 54 | nodes : dictionary 55 | Dictionary with nodes as keys and closeness vitality as the value. 56 | 57 | Examples 58 | -------- 59 | >>> G=nx.cycle_graph(3) 60 | >>> nx.closeness_vitality(G) 61 | {0: 4.0, 1: 4.0, 2: 4.0} 62 | 63 | See Also 64 | -------- 65 | closeness_centrality() 66 | 67 | Notes 68 | ----- 69 | """ 70 | wig=weiner_index(G,weight) 71 | closeness_vitality={} 72 | for n in G: 73 | # remove edges connected to node n and keep list of edges with data 74 | # could remove node n but it doesn't count anyway 75 | edges=G.edges(n,data=True) 76 | if G.is_directed(): 77 | edges+=G.in_edges(n,data=True) 78 | G.remove_edges_from(edges) 79 | closeness_vitality[n]=wig-weiner_index(G,weight) 80 | # add edges and data back to graph 81 | G.add_edges_from(edges) 82 | if v is not None: 83 | return closeness_vitality[v] 84 | else: 85 | return closeness_vitality 86 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /appengine/networkx/classes/__init__.py: -------------------------------------------------------------------------------- 1 | from networkx.classes.graph import Graph 2 | from networkx.classes.digraph import DiGraph 3 | from networkx.classes.multigraph import MultiGraph 4 | from networkx.classes.multidigraph import MultiDiGraph 5 | from networkx.classes.function import * 6 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/networkx/drawing/__init__.py: -------------------------------------------------------------------------------- 1 | # graph drawing and interface to graphviz 2 | import sys 3 | from networkx.drawing.layout import * 4 | from networkx.drawing.nx_pylab import * 5 | 6 | # graphviz interface 7 | # prefer pygraphviz/agraph (it's faster) 8 | from networkx.drawing.nx_agraph import * 9 | try: 10 | import pydot 11 | import networkx.drawing.nx_pydot 12 | from networkx.drawing.nx_pydot import * 13 | except: 14 | pass 15 | try: 16 | import pygraphviz 17 | from networkx.drawing.nx_agraph import * 18 | except: 19 | pass 20 | 21 | -------------------------------------------------------------------------------- /appengine/networkx/drawing/tests/test_agraph.py: -------------------------------------------------------------------------------- 1 | """ 2 | Unit tests for PyGraphviz intefaace. 3 | """ 4 | 5 | import os 6 | import tempfile 7 | 8 | from nose import SkipTest 9 | from nose.tools import assert_true 10 | 11 | import networkx as nx 12 | 13 | class TestAGraph(object): 14 | @classmethod 15 | def setupClass(cls): 16 | global pygraphviz 17 | try: 18 | import pygraphviz 19 | except ImportError: 20 | raise SkipTest('PyGraphviz not available.') 21 | 22 | def build_graph(self, G): 23 | G.add_edge('A','B') 24 | G.add_edge('A','C') 25 | G.add_edge('A','C') 26 | G.add_edge('B','C') 27 | G.add_edge('A','D') 28 | G.add_node('E') 29 | return G 30 | 31 | def assert_equal(self, G1, G2): 32 | assert_true( sorted(G1.nodes())==sorted(G2.nodes()) ) 33 | assert_true( sorted(G1.edges())==sorted(G2.edges()) ) 34 | 35 | 36 | def agraph_checks(self, G): 37 | G = self.build_graph(G) 38 | A=nx.to_agraph(G) 39 | H=nx.from_agraph(A) 40 | self.assert_equal(G, H) 41 | 42 | 43 | fname=tempfile.mktemp() 44 | nx.drawing.nx_agraph.write_dot(H,fname) 45 | Hin=nx.drawing.nx_agraph.read_dot(fname) 46 | os.unlink(fname) 47 | self.assert_equal(H,Hin) 48 | 49 | 50 | (fd,fname)=tempfile.mkstemp() 51 | fh=open(fname,'w') 52 | nx.drawing.nx_agraph.write_dot(H,fh) 53 | fh.close() 54 | 55 | fh=open(fname,'r') 56 | Hin=nx.drawing.nx_agraph.read_dot(fh) 57 | fh.close() 58 | os.unlink(fname) 59 | self.assert_equal(H,Hin) 60 | 61 | 62 | def testUndirected(self): 63 | self.agraph_checks(nx.Graph()) 64 | 65 | def testDirected(self): 66 | self.agraph_checks(nx.DiGraph()) 67 | 68 | def testMultiUndirected(self): 69 | self.agraph_checks(nx.MultiGraph()) 70 | 71 | def testMultiDirected(self): 72 | self.agraph_checks(nx.MultiDiGraph()) 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /appengine/networkx/drawing/tests/test_layout.py: -------------------------------------------------------------------------------- 1 | """ 2 | Unit tests for layout functions. 3 | """ 4 | 5 | import sys 6 | 7 | from nose import SkipTest 8 | from nose.tools import assert_equal 9 | 10 | import networkx as nx 11 | 12 | class TestLayout(object): 13 | numpy=1 # nosetests attribute, use nosetests -a 'not numpy' to skip test 14 | @classmethod 15 | def setupClass(cls): 16 | global numpy 17 | try: 18 | import numpy 19 | except ImportError: 20 | raise SkipTest('numpy not available.') 21 | 22 | 23 | def setUp(self): 24 | self.Gi=nx.grid_2d_graph(5,5) 25 | self.Gs=nx.Graph() 26 | self.Gs.add_path('abcdef') 27 | self.bigG=nx.grid_2d_graph(25,25) #bigger than 500 nodes for sparse 28 | 29 | def test_smoke_int(self): 30 | G=self.Gi 31 | vpos=nx.random_layout(G) 32 | vpos=nx.circular_layout(G) 33 | vpos=nx.spring_layout(G) 34 | vpos=nx.fruchterman_reingold_layout(G) 35 | vpos=nx.spectral_layout(G) 36 | vpos=nx.spectral_layout(self.bigG) 37 | vpos=nx.shell_layout(G) 38 | 39 | def test_smoke_string(self): 40 | G=self.Gs 41 | vpos=nx.random_layout(G) 42 | vpos=nx.circular_layout(G) 43 | vpos=nx.spring_layout(G) 44 | vpos=nx.fruchterman_reingold_layout(G) 45 | vpos=nx.spectral_layout(G) 46 | vpos=nx.shell_layout(G) 47 | 48 | 49 | def test_adjacency_interface_numpy(self): 50 | A=nx.to_numpy_matrix(self.Gs) 51 | pos=nx.drawing.layout._fruchterman_reingold(A) 52 | pos=nx.drawing.layout._fruchterman_reingold(A,dim=3) 53 | assert_equal(pos.shape,(6,3)) 54 | 55 | def test_adjacency_interface_scipy(self): 56 | try: 57 | import scipy 58 | except ImportError: 59 | raise SkipTest('scipy not available.') 60 | 61 | A=nx.to_scipy_sparse_matrix(self.Gs) 62 | pos=nx.drawing.layout._sparse_fruchterman_reingold(A) 63 | pos=nx.drawing.layout._sparse_spectral(A) 64 | 65 | pos=nx.drawing.layout._sparse_fruchterman_reingold(A,dim=3) 66 | assert_equal(pos.shape,(6,3)) 67 | 68 | 69 | -------------------------------------------------------------------------------- /appengine/networkx/drawing/tests/test_pydot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Unit tests for pydot drawing functions. 3 | """ 4 | 5 | import os 6 | import tempfile 7 | 8 | from nose import SkipTest 9 | from nose.tools import assert_true 10 | 11 | import networkx as nx 12 | 13 | class TestPydot(object): 14 | @classmethod 15 | def setupClass(cls): 16 | global pydot 17 | try: 18 | import pydot 19 | except ImportError: 20 | raise SkipTest('pydot not available.') 21 | 22 | def build_graph(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 | return G, nx.to_pydot(G) 29 | 30 | def assert_equal(self, G1, G2): 31 | assert_true( sorted(G1.nodes())==sorted(G2.nodes()) ) 32 | assert_true( sorted(G1.edges())==sorted(G2.edges()) ) 33 | 34 | def pydot_checks(self, G): 35 | H, P = self.build_graph(G) 36 | G2 = H.__class__(nx.from_pydot(P)) 37 | self.assert_equal(H, G2) 38 | 39 | fname = tempfile.mktemp() 40 | assert_true( P.write_raw(fname) ) 41 | 42 | Pin = pydot.graph_from_dot_file(fname) 43 | 44 | n1 = sorted([p.get_name() for p in P.get_node_list()]) 45 | n2 = sorted([p.get_name() for p in Pin.get_node_list()]) 46 | assert_true( n1 == n2 ) 47 | 48 | e1=[(e.get_source(),e.get_destination()) for e in P.get_edge_list()] 49 | e2=[(e.get_source(),e.get_destination()) for e in Pin.get_edge_list()] 50 | assert_true( sorted(e1)==sorted(e2) ) 51 | 52 | Hin = nx.drawing.nx_pydot.read_dot(fname) 53 | Hin = H.__class__(Hin) 54 | self.assert_equal(H, Hin) 55 | # os.unlink(fname) 56 | 57 | 58 | def testUndirected(self): 59 | self.pydot_checks(nx.Graph()) 60 | 61 | def testDirected(self): 62 | self.pydot_checks(nx.DiGraph()) 63 | 64 | 65 | -------------------------------------------------------------------------------- /appengine/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 pylab 15 | try: 16 | import matplotlib as mpl 17 | mpl.use('PS',warn=False) 18 | import pylab 19 | except ImportError: 20 | raise SkipTest('matplotlib not available.') 21 | except RuntimeError: 22 | raise SkipTest('matplotlib not available.') 23 | 24 | def setUp(self): 25 | self.G=nx.barbell_graph(5,10) 26 | 27 | 28 | def test_draw(self): 29 | # hold(False) 30 | N=self.G 31 | nx.draw_spring(N) 32 | pylab.savefig("test.ps") 33 | nx.draw_random(N) 34 | pylab.savefig("test.ps") 35 | nx.draw_circular(N) 36 | pylab.savefig("test.ps") 37 | nx.draw_spectral(N) 38 | pylab.savefig("test.ps") 39 | nx.draw_spring(N.to_directed()) 40 | pylab.savefig("test.ps") 41 | os.unlink('test.ps') 42 | -------------------------------------------------------------------------------- /appengine/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-2008 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 NetworkXUnbounded(NetworkXAlgorithmError): 46 | """Exception raised by algorithms trying to solve a maximization 47 | or a minimization problem instance that is unbounded.""" 48 | 49 | 50 | -------------------------------------------------------------------------------- /appengine/networkx/external/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uwescience/myria-web/b1c175a5cbe76d4f2219b192635085ece1326588/appengine/networkx/external/__init__.py -------------------------------------------------------------------------------- /appengine/networkx/external/decorator/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Hack for including decorator-3.3.1 in NetworkX. 3 | """ 4 | 5 | import sys 6 | 7 | if sys.version >= '3': 8 | from ._decorator3 import * 9 | _decorator = _decorator3 10 | else: 11 | from ._decorator import * 12 | -------------------------------------------------------------------------------- /appengine/networkx/generators/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | A package for generating various graphs in networkx. 3 | 4 | """ 5 | from networkx.generators.atlas import * 6 | from networkx.generators.bipartite import * 7 | from networkx.generators.classic import * 8 | from networkx.generators.degree_seq import * 9 | from networkx.generators.directed import * 10 | from networkx.generators.ego import * 11 | from networkx.generators.geometric import * 12 | from networkx.generators.hybrid import * 13 | from networkx.generators.line import * 14 | from networkx.generators.random_graphs import * 15 | from networkx.generators.small import * 16 | from networkx.generators.stochastic import * 17 | from networkx.generators.social import * 18 | from networkx.generators.threshold import * 19 | from networkx.generators.intersection import * 20 | from networkx.generators.random_clustered import * 21 | 22 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/networkx/generators/line.py: -------------------------------------------------------------------------------- 1 | """ 2 | Line graphs. 3 | 4 | """ 5 | # Copyright (C) 2010 by 6 | # Aric Hagberg 7 | # Dan Schult 8 | # Pieter Swart 9 | # All rights reserved. 10 | # BSD license. 11 | __author__ = """Aric Hagberg (hagberg@lanl.gov)\nPieter Swart (swart@lanl.gov)\nDan Schult(dschult@colgate.edu)""" 12 | 13 | __all__ = ['line_graph'] 14 | 15 | import networkx as nx 16 | 17 | def line_graph(G): 18 | """Return the line graph of the graph or digraph G. 19 | 20 | The line graph of a graph G has a node for each edge 21 | in G and an edge between those nodes if the two edges 22 | in G share a common node. 23 | 24 | For DiGraphs an edge an edge represents a directed path of length 2. 25 | 26 | The original node labels are kept as two-tuple node labels 27 | in the line graph. 28 | 29 | Parameters 30 | ---------- 31 | G : graph 32 | A NetworkX Graph or DiGraph 33 | 34 | Examples 35 | -------- 36 | >>> G=nx.star_graph(3) 37 | >>> L=nx.line_graph(G) 38 | >>> print(sorted(L.edges())) # makes a clique, K3 39 | [((0, 1), (0, 2)), ((0, 1), (0, 3)), ((0, 3), (0, 2))] 40 | 41 | Notes 42 | ----- 43 | Not implemented for MultiGraph or MultiDiGraph classes. 44 | 45 | Graph, node, and edge data are not propagated to the new graph. 46 | 47 | """ 48 | if type(G) == nx.MultiGraph or type(G) == nx.MultiDiGraph: 49 | raise Exception("Line graph not implemented for Multi(Di)Graphs") 50 | L=G.__class__() 51 | if G.is_directed(): 52 | for u,nlist in G.adjacency_iter(): # same as successors for digraph 53 | # look for directed path of length two 54 | for n in nlist: 55 | nbrs=G[n] # successors 56 | for nbr in nbrs: 57 | if nbr!=u: 58 | L.add_edge((u,n),(n,nbr)) 59 | else: 60 | for u,nlist in G.adjacency_iter(): 61 | # label nodes as tuple of edge endpoints in original graph 62 | # "node tuple" must be in lexigraphical order 63 | nodes=[tuple(sorted(n)) for n in zip([u]*len(nlist),nlist)] 64 | # add clique of nodes to graph 65 | while nodes: 66 | u=nodes.pop() 67 | L.add_edges_from((u,v) for v in nodes) 68 | return L 69 | 70 | -------------------------------------------------------------------------------- /appengine/networkx/generators/stochastic.py: -------------------------------------------------------------------------------- 1 | """Stocastic graph.""" 2 | import networkx as nx 3 | # Copyright (C) 2010 by 4 | # Aric Hagberg 5 | # Dan Schult 6 | # Pieter Swart 7 | # All rights reserved. 8 | # BSD license. 9 | __author__ = "Aric Hagberg " 10 | __all__ = ['stochastic_graph'] 11 | 12 | def stochastic_graph(G, copy=True, weight='weight'): 13 | """Return a right-stochastic representation of G. 14 | 15 | A right-stochastic graph is a weighted graph in which all of 16 | the node (out) neighbors edge weights sum to 1. 17 | 18 | Parameters 19 | ----------- 20 | G : graph 21 | A NetworkX graph, must have valid edge weights 22 | 23 | copy : boolean, optional 24 | If True make a copy of the graph, otherwise modify original graph 25 | 26 | weight : key (optional) 27 | Edge data key used for weight. If None all weights are set to 1. 28 | """ 29 | if type(G) == nx.MultiGraph or type(G) == nx.MultiDiGraph: 30 | raise Exception("stochastic_graph not implemented for multigraphs") 31 | 32 | if not G.is_directed(): 33 | raise Exception("stochastic_graph not defined for undirected graphs") 34 | 35 | if copy: 36 | W=nx.DiGraph(G) 37 | else: 38 | W=G # reference original graph, no copy 39 | 40 | degree=W.out_degree(weight=weight) 41 | for (u,v,d) in W.edges(data=True): 42 | d[weight]=d.get(weight,1.0)/degree[u] 43 | return W 44 | -------------------------------------------------------------------------------- /appengine/networkx/generators/tests/test_atlas.py: -------------------------------------------------------------------------------- 1 | from nose.tools import * 2 | import networkx as nx 3 | 4 | 5 | class TestAtlas(object): 6 | def setUp(self): 7 | self.GAG=nx.graph_atlas_g() 8 | 9 | def test_sizes(self): 10 | G=self.GAG[0] 11 | assert_equal(G.number_of_nodes(),0) 12 | assert_equal(G.number_of_edges(),0) 13 | 14 | G=self.GAG[7] 15 | assert_equal(G.number_of_nodes(),3) 16 | assert_equal(G.number_of_edges(),3) 17 | 18 | def test_names(self): 19 | i=0 20 | for g in self.GAG: 21 | name=g.name 22 | assert_equal(int(name[1:]),i) 23 | i+=1 24 | 25 | def test_monotone_nodes(self): 26 | # check for monotone increasing number of nodes 27 | previous=self.GAG[0] 28 | for g in self.GAG: 29 | assert_false(len(g)-len(previous) > 1) 30 | previous=g.copy() 31 | 32 | def test_monotone_nodes(self): 33 | # check for monotone increasing number of edges 34 | # (for fixed number of nodes) 35 | previous=self.GAG[0] 36 | for g in self.GAG: 37 | if len(g)==len(previous): 38 | assert_false(g.size()-previous.size() > 1) 39 | previous=g.copy() 40 | 41 | def test_monotone_degree_sequence(self): 42 | # check for monotone increasing degree sequence 43 | # (for fixed number f nodes and edges) 44 | # note that 111223 < 112222 45 | previous=self.GAG[0] 46 | for g in self.GAG: 47 | if len(g)==0: 48 | continue 49 | if len(g)==len(previous) & g.size()==previous.size(): 50 | deg_seq=sorted(g.degree().values()) 51 | previous_deg_seq=sorted(previous.degree().values()) 52 | assert_true(previous_deg_seq < deg_seq) 53 | previous=g.copy() 54 | 55 | 56 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/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 | 24 | def test_ego_distance(self): 25 | G=nx.Graph() 26 | G.add_edge(0,1,weight=2,distance=1) 27 | G.add_edge(1,2,weight=2,distance=2) 28 | G.add_edge(2,3,weight=2,distance=1) 29 | assert_equal(sorted(nx.ego_graph(G,0,radius=3).nodes()),[0,1,2,3]) 30 | eg=nx.ego_graph(G,0,radius=3,distance='weight') 31 | assert_equal(sorted(eg.nodes()),[0,1]) 32 | eg=nx.ego_graph(G,0,radius=3,distance='distance') 33 | assert_equal(sorted(eg.nodes()),[0,1,2]) 34 | 35 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/networkx/generators/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 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/networkx/generators/tests/test_line.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """line graph 4 | ---------- 5 | """ 6 | 7 | import networkx as nx 8 | from nose.tools import * 9 | 10 | 11 | class TestGeneratorLine(): 12 | def test_line(self): 13 | G=nx.star_graph(5) 14 | L=nx.line_graph(G) 15 | assert_true(nx.is_isomorphic(L,nx.complete_graph(5))) 16 | G=nx.path_graph(5) 17 | L=nx.line_graph(G) 18 | assert_true(nx.is_isomorphic(L,nx.path_graph(4))) 19 | G=nx.cycle_graph(5) 20 | L=nx.line_graph(G) 21 | assert_true(nx.is_isomorphic(L,G)) 22 | G=nx.DiGraph() 23 | G.add_edges_from([(0,1),(0,2),(0,3)]) 24 | L=nx.line_graph(G) 25 | assert_equal(L.adj, {}) 26 | G=nx.DiGraph() 27 | G.add_edges_from([(0,1),(1,2),(2,3)]) 28 | L=nx.line_graph(G) 29 | assert_equal(sorted(L.edges()), [((0, 1), (1, 2)), ((1, 2), (2, 3))]) 30 | 31 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/networkx/generators/tests/test_stochastic.py: -------------------------------------------------------------------------------- 1 | from nose.tools import assert_true, assert_equal,assert_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 | 19 | def test_stochastic_error(): 20 | G=nx.Graph() 21 | assert_raises(Exception,nx.stochastic_graph,G) 22 | G=nx.MultiGraph() 23 | assert_raises(Exception,nx.stochastic_graph,G) 24 | -------------------------------------------------------------------------------- /appengine/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 | 10 | -------------------------------------------------------------------------------- /appengine/networkx/linalg/spectrum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Eigenvalue spectrum of graphs. 3 | """ 4 | # Copyright (C) 2004-2011 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 | 'Pieter Swart (swart@lanl.gov)', 13 | 'Dan Schult(dschult@colgate.edu)']) 14 | 15 | __all__ = ['laplacian_spectrum', 'adjacency_spectrum'] 16 | 17 | 18 | def laplacian_spectrum(G, weight='weight'): 19 | """Return eigenvalues of the Laplacian of G 20 | 21 | Parameters 22 | ---------- 23 | G : graph 24 | A NetworkX graph 25 | 26 | weight : string or None, optional (default='weight') 27 | The edge data key used to compute each value in the matrix. 28 | If None, then each edge has weight 1. 29 | 30 | Returns 31 | ------- 32 | evals : NumPy array 33 | Eigenvalues 34 | 35 | Notes 36 | ----- 37 | For MultiGraph/MultiDiGraph, the edges weights are summed. 38 | See to_numpy_matrix for other options. 39 | 40 | See Also 41 | -------- 42 | laplacian_matrix 43 | """ 44 | try: 45 | import numpy as np 46 | except ImportError: 47 | raise ImportError( 48 | "laplacian_spectrum() requires NumPy: http://scipy.org/ ") 49 | return np.linalg.eigvals(nx.laplacian_matrix(G,weight=weight)) 50 | 51 | def adjacency_spectrum(G, weight='weight'): 52 | """Return eigenvalues of the adjacency matrix of G. 53 | 54 | Parameters 55 | ---------- 56 | G : graph 57 | A NetworkX graph 58 | 59 | weight : string or None, optional (default='weight') 60 | The edge data key used to compute each value in the matrix. 61 | If None, then each edge has weight 1. 62 | 63 | Returns 64 | ------- 65 | evals : NumPy array 66 | Eigenvalues 67 | 68 | Notes 69 | ----- 70 | For MultiGraph/MultiDiGraph, the edges weights are summed. 71 | See to_numpy_matrix for other options. 72 | 73 | See Also 74 | -------- 75 | adjacency_matrix 76 | """ 77 | try: 78 | import numpy as np 79 | except ImportError: 80 | raise ImportError( 81 | "adjacency_spectrum() requires NumPy: http://scipy.org/ ") 82 | return np.linalg.eigvals(nx.adjacency_matrix(G,weight=weight)) 83 | 84 | # fixture for nose tests 85 | def setup_module(module): 86 | from nose import SkipTest 87 | try: 88 | import numpy 89 | except: 90 | raise SkipTest("NumPy not available") 91 | -------------------------------------------------------------------------------- /appengine/networkx/linalg/tests/test_laplaican.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 TestLaplacian(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 setUp(self): 20 | deg=[3,2,2,1,0] 21 | self.G=havel_hakimi_graph(deg) 22 | self.WG=nx.Graph( (u,v,{'weight':0.5,'other':0.3}) 23 | for (u,v) in self.G.edges_iter() ) 24 | self.WG.add_node(4) 25 | self.MG=nx.MultiGraph(self.G) 26 | 27 | 28 | def test_laplacian(self): 29 | "Graph Laplacian" 30 | NL=numpy.array([[ 3, -1, -1, -1, 0], 31 | [-1, 2, -1, 0, 0], 32 | [-1, -1, 2, 0, 0], 33 | [-1, 0, 0, 1, 0], 34 | [ 0, 0, 0, 0, 0]]) 35 | WL=0.5*NL 36 | OL=0.3*NL 37 | assert_equal(nx.laplacian(self.G),NL) 38 | assert_equal(nx.laplacian(self.MG),NL) 39 | assert_equal(nx.laplacian(self.G,nodelist=[0,1]), 40 | numpy.array([[ 1, -1],[-1, 1]])) 41 | assert_equal(nx.laplacian(self.WG),WL) 42 | assert_equal(nx.laplacian(self.WG,weight=None),NL) 43 | assert_equal(nx.laplacian(self.WG,weight='other'),OL) 44 | 45 | def test_generalized_laplacian(self): 46 | "Generalized Graph Laplacian" 47 | GL=numpy.array([[ 1.00, -0.408, -0.408, -0.577, 0.00], 48 | [-0.408, 1.00, -0.50, 0.00 , 0.00], 49 | [-0.408, -0.50, 1.00, 0.00, 0.00], 50 | [-0.577, 0.00, 0.00, 1.00, 0.00], 51 | [ 0.00, 0.00, 0.00, 0.00, 0.00]]) 52 | assert_almost_equal(nx.generalized_laplacian(self.G),GL,decimal=3) 53 | 54 | def test_normalized_laplacian(self): 55 | "Generalized Graph Laplacian" 56 | GL=numpy.array([[ 1.00, -0.408, -0.408, -0.577, 0.00], 57 | [-0.408, 1.00, -0.50, 0.00 , 0.00], 58 | [-0.408, -0.50, 1.00, 0.00, 0.00], 59 | [-0.577, 0.00, 0.00, 1.00, 0.00], 60 | [ 0.00, 0.00, 0.00, 0.00, 0.00]]) 61 | assert_almost_equal(nx.normalized_laplacian(self.G),GL,decimal=3) 62 | assert_almost_equal(nx.normalized_laplacian(self.MG),GL,decimal=3) 63 | assert_almost_equal(nx.normalized_laplacian(self.WG),GL,decimal=3) 64 | assert_almost_equal(nx.normalized_laplacian(self.WG,weight='other'),GL,decimal=3) 65 | 66 | -------------------------------------------------------------------------------- /appengine/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 | from numpy.testing import assert_equal,assert_almost_equal 16 | except ImportError: 17 | raise SkipTest('NumPy not available.') 18 | 19 | def setUp(self): 20 | deg=[3,2,2,1,0] 21 | self.G=havel_hakimi_graph(deg) 22 | self.P=nx.path_graph(3) 23 | self.WG=nx.Graph( (u,v,{'weight':0.5,'other':0.3}) 24 | for (u,v) in self.G.edges_iter() ) 25 | self.WG.add_node(4) 26 | 27 | def test_laplacian_spectrum(self): 28 | "Laplacian eigenvalues" 29 | evals=numpy.array([0, 0, 1, 3, 4]) 30 | e=sorted(nx.laplacian_spectrum(self.G)) 31 | assert_almost_equal(e,evals) 32 | e=sorted(nx.laplacian_spectrum(self.WG,weight=None)) 33 | assert_almost_equal(e,evals) 34 | e=sorted(nx.laplacian_spectrum(self.WG)) 35 | assert_almost_equal(e,0.5*evals) 36 | e=sorted(nx.laplacian_spectrum(self.WG,weight='other')) 37 | assert_almost_equal(e,0.3*evals) 38 | 39 | def test_adjacency_spectrum(self): 40 | "Adjacency eigenvalues" 41 | evals=numpy.array([-numpy.sqrt(2), 0, numpy.sqrt(2)]) 42 | e=sorted(nx.adjacency_spectrum(self.P)) 43 | assert_almost_equal(e,evals) 44 | 45 | -------------------------------------------------------------------------------- /appengine/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.sparsegraph6 import * 12 | from networkx.readwrite.nx_yaml import * 13 | from networkx.readwrite.gml import * 14 | from networkx.readwrite.graphml import * 15 | from networkx.readwrite.gexf import * 16 | from networkx.readwrite.nx_shp import * 17 | -------------------------------------------------------------------------------- /appengine/networkx/readwrite/gpickle.py: -------------------------------------------------------------------------------- 1 | """ 2 | ************** 3 | Pickled Graphs 4 | ************** 5 | Read and write NetworkX graphs as Python pickles. 6 | 7 | "The pickle module implements a fundamental, but powerful algorithm 8 | for serializing and de-serializing a Python object 9 | structure. "Pickling" is the process whereby a Python object hierarchy 10 | is converted into a byte stream, and "unpickling" is the inverse 11 | operation, whereby a byte stream is converted back into an object 12 | hierarchy." 13 | 14 | Note that NetworkX graphs can contain any hashable Python object as 15 | node (not just integers and strings). For arbitrary data types it may 16 | be difficult to represent the data as text. In that case using Python 17 | pickles to store the graph data can be used. 18 | 19 | Format 20 | ------ 21 | See http://docs.python.org/library/pickle.html 22 | """ 23 | __author__ = """Aric Hagberg (hagberg@lanl.gov)\nDan Schult (dschult@colgate.edu)""" 24 | # Copyright (C) 2004-2010 by 25 | # Aric Hagberg 26 | # Dan Schult 27 | # Pieter Swart 28 | # All rights reserved. 29 | # BSD license. 30 | 31 | __all__ = ['read_gpickle', 'write_gpickle'] 32 | 33 | import networkx as nx 34 | from networkx.utils import open_file 35 | 36 | try: 37 | import cPickle as pickle 38 | except ImportError: 39 | import pickle 40 | 41 | @open_file(1,mode='wb') 42 | def write_gpickle(G, path): 43 | """Write graph in Python pickle format. 44 | 45 | Pickles are a serialized byte stream of a Python object [1]_. 46 | This format will preserve Python objects used as nodes or edges. 47 | 48 | Parameters 49 | ---------- 50 | G : graph 51 | A NetworkX graph 52 | path : file or string 53 | File or filename to write. 54 | Filenames ending in .gz or .bz2 will be compressed. 55 | 56 | Examples 57 | -------- 58 | >>> G=nx.path_graph(4) 59 | >>> nx.write_gpickle(G,"test.gpickle") 60 | 61 | References 62 | ---------- 63 | .. [1] http://docs.python.org/library/pickle.html 64 | """ 65 | pickle.dump(G, path, pickle.HIGHEST_PROTOCOL) 66 | 67 | @open_file(0,mode='rb') 68 | def read_gpickle(path): 69 | """Read graph object in Python pickle format. 70 | 71 | Pickles are a serialized byte stream of a Python object [1]_. 72 | This format will preserve Python objects used as nodes or edges. 73 | 74 | Parameters 75 | ---------- 76 | path : file or string 77 | File or filename to write. 78 | Filenames ending in .gz or .bz2 will be uncompressed. 79 | 80 | Returns 81 | ------- 82 | G : graph 83 | A NetworkX graph 84 | 85 | Examples 86 | -------- 87 | >>> G=nx.path_graph(4) 88 | >>> nx.write_gpickle(G,"test.gpickle") 89 | >>> G=nx.read_gpickle("test.gpickle") 90 | 91 | References 92 | ---------- 93 | .. [1] http://docs.python.org/library/pickle.html 94 | """ 95 | return pickle.load(path) 96 | 97 | # fixture for nose tests 98 | def teardown_module(module): 99 | import os 100 | os.unlink('test.gpickle') 101 | -------------------------------------------------------------------------------- /appengine/networkx/readwrite/json_graph/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | ********* 3 | JSON data 4 | ********* 5 | Generate and parse JSON serializable data for NetworkX graphs. 6 | """ 7 | from networkx.readwrite.json_graph.node_link import * 8 | from networkx.readwrite.json_graph.adjacency import * 9 | from networkx.readwrite.json_graph.tree import * 10 | from networkx.readwrite.json_graph.serialize import * 11 | -------------------------------------------------------------------------------- /appengine/networkx/readwrite/json_graph/serialize.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2011 by 2 | # Aric Hagberg 3 | # Dan Schult 4 | # Pieter Swart 5 | # All rights reserved. 6 | # BSD license. 7 | from functools import partial,update_wrapper 8 | import json 9 | from networkx.readwrite.json_graph import node_link_data,node_link_graph 10 | __author__ = """Aric Hagberg (hagberg@lanl.gov))""" 11 | __all__ = ['dumps','loads','dump','load'] 12 | 13 | class NXJSONEncoder(json.JSONEncoder): 14 | def default(self, o): 15 | return node_link_data(o) 16 | 17 | 18 | class NXJSONDecoder(json.JSONDecoder): 19 | def decode(self, s): 20 | d = json.loads(s) 21 | return node_link_graph(d) 22 | 23 | # modification of json functions to serialize networkx graphs 24 | dumps = partial(json.dumps, cls=NXJSONEncoder) 25 | update_wrapper(dumps,json.dumps) 26 | loads = partial(json.loads, cls=NXJSONDecoder) 27 | update_wrapper(loads,json.loads) 28 | dump = partial(json.dump, cls=NXJSONEncoder) 29 | update_wrapper(dump,json.dump) 30 | load = partial(json.load, cls=NXJSONDecoder) 31 | update_wrapper(load,json.load) 32 | -------------------------------------------------------------------------------- /appengine/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 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 | H = adjacency_graph(adjacency_data(G)) 35 | assert_true(H.is_directed()) 36 | 37 | def test_multidigraph(self): 38 | G = nx.MultiDiGraph() 39 | H = adjacency_graph(adjacency_data(G)) 40 | assert_true(H.is_directed()) 41 | assert_true(H.is_multigraph()) 42 | -------------------------------------------------------------------------------- /appengine/networkx/readwrite/json_graph/tests/test_node_link.py: -------------------------------------------------------------------------------- 1 | import json 2 | from nose.tools import assert_equal, assert_raises, assert_not_equal,assert_true 3 | import networkx as nx 4 | from networkx.readwrite.json_graph import * 5 | 6 | class TestNodeLink: 7 | 8 | def test_graph(self): 9 | G = nx.path_graph(4) 10 | H = node_link_graph(node_link_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[1]='one' 18 | G.graph['foo']='bar' 19 | 20 | H = node_link_graph(node_link_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(node_link_data(G)) 26 | H = node_link_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 | H = node_link_graph(node_link_data(G)) 35 | assert_true(H.is_directed()) 36 | 37 | def test_multidigraph(self): 38 | G = nx.MultiDiGraph() 39 | H = node_link_graph(node_link_data(G)) 40 | assert_true(H.is_directed()) 41 | assert_true(H.is_multigraph()) 42 | -------------------------------------------------------------------------------- /appengine/networkx/readwrite/json_graph/tests/test_serialize.py: -------------------------------------------------------------------------------- 1 | import json 2 | from nose.tools import assert_equal, assert_raises, assert_not_equal,assert_true 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 = loads(dumps(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 = loads(dumps(G)) 21 | assert_equal(H.graph['foo'],'bar') 22 | assert_equal(H.graph[1],'one') 23 | assert_equal(H.node[1]['color'],'red') 24 | assert_equal(H[1][2]['width'],7) 25 | 26 | try: 27 | from StringIO import StringIO 28 | except: 29 | from io import StringIO 30 | io = StringIO() 31 | dump(G,io) 32 | io.seek(0) 33 | H=load(io) 34 | assert_equal(H.graph['foo'],'bar') 35 | assert_equal(H.graph[1],'one') 36 | assert_equal(H.node[1]['color'],'red') 37 | assert_equal(H[1][2]['width'],7) 38 | 39 | 40 | def test_digraph(self): 41 | G = nx.DiGraph() 42 | H = loads(dumps(G)) 43 | assert_true(H.is_directed()) 44 | 45 | def test_multidigraph(self): 46 | G = nx.MultiDiGraph() 47 | H = loads(dumps(G)) 48 | assert_true(H.is_directed()) 49 | assert_true(H.is_multigraph()) 50 | -------------------------------------------------------------------------------- /appengine/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 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 | -------------------------------------------------------------------------------- /appengine/networkx/readwrite/leda.py: -------------------------------------------------------------------------------- 1 | """ 2 | Read graphs in LEDA format. 3 | 4 | LEDA is a C++ class library for efficient data types and algorithms. 5 | 6 | Format 7 | ------ 8 | See http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html 9 | 10 | """ 11 | # Original author: D. Eppstein, UC Irvine, August 12, 2003. 12 | # The original code at http://www.ics.uci.edu/~eppstein/PADS/ is public domain. 13 | __author__ = """Aric Hagberg (hagberg@lanl.gov)""" 14 | # Copyright (C) 2004-2010 by 15 | # Aric Hagberg 16 | # Dan Schult 17 | # Pieter Swart 18 | # All rights reserved. 19 | # BSD license. 20 | 21 | __all__ = ['read_leda', 'parse_leda'] 22 | 23 | import networkx as nx 24 | from networkx.exception import NetworkXError 25 | from networkx.utils import open_file, is_string_like 26 | 27 | @open_file(0,mode='rb') 28 | def read_leda(path, encoding='UTF-8'): 29 | """Read graph in LEDA format from path. 30 | 31 | Parameters 32 | ---------- 33 | path : file or string 34 | File or filename to read. Filenames ending in .gz or .bz2 will be 35 | uncompressed. 36 | 37 | Returns 38 | ------- 39 | G : NetworkX graph 40 | 41 | Examples 42 | -------- 43 | G=nx.read_leda('file.leda') 44 | 45 | References 46 | ---------- 47 | .. [1] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html 48 | """ 49 | lines=(line.decode(encoding) for line in path) 50 | G=parse_leda(lines) 51 | return G 52 | 53 | 54 | def parse_leda(lines): 55 | """Read graph in LEDA format from string or iterable. 56 | 57 | Parameters 58 | ---------- 59 | lines : string or iterable 60 | Data in LEDA format. 61 | 62 | Returns 63 | ------- 64 | G : NetworkX graph 65 | 66 | Examples 67 | -------- 68 | G=nx.parse_leda(string) 69 | 70 | References 71 | ---------- 72 | .. [1] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html 73 | """ 74 | if is_string_like(lines): lines=iter(lines.split('\n')) 75 | lines = iter([line.rstrip('\n') for line in lines \ 76 | if not (line.startswith('#') or line.startswith('\n') or line=='')]) 77 | for i in range(3): 78 | next(lines) 79 | # Graph 80 | du = int(next(lines)) # -1=directed, -2=undirected 81 | if du==-1: 82 | G = nx.DiGraph() 83 | else: 84 | G = nx.Graph() 85 | 86 | # Nodes 87 | n =int(next(lines)) # number of nodes 88 | node={} 89 | for i in range(1,n+1): # LEDA counts from 1 to n 90 | symbol=next(lines).rstrip().strip('|{}| ') 91 | if symbol=="": symbol=str(i) # use int if no label - could be trouble 92 | node[i]=symbol 93 | 94 | G.add_nodes_from([s for i,s in node.items()]) 95 | 96 | # Edges 97 | m = int(next(lines)) # number of edges 98 | for i in range(m): 99 | try: 100 | s,t,reversal,label=next(lines).split() 101 | except: 102 | raise NetworkXError('Too few fields in LEDA.GRAPH edge %d'%(i+1)) 103 | # BEWARE: no handling of reversal edges 104 | G.add_edge(node[int(s)],node[int(t)],label=label[2:-2]) 105 | return G 106 | 107 | -------------------------------------------------------------------------------- /appengine/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-2010 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 | -------------------------------------------------------------------------------- /appengine/networkx/readwrite/tests/test_gpickle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import assert_equal 3 | import networkx as nx 4 | import os,tempfile 5 | 6 | class TestGpickle(object): 7 | def setUp(self): 8 | G=nx.Graph(name="test") 9 | e=[('a','b'),('b','c'),('c','d'),('d','e'),('e','f'),('a','f')] 10 | G.add_edges_from(e,width=10) 11 | G.add_node('g',color='green') 12 | G.graph['number']=1 13 | self.G=G 14 | 15 | def test_gpickle(self): 16 | G=self.G 17 | (fd,fname)=tempfile.mkstemp() 18 | nx.write_gpickle(G,fname); 19 | Gin=nx.read_gpickle(fname); 20 | assert_equal(sorted(G.nodes(data=True)), 21 | sorted(Gin.nodes(data=True))) 22 | assert_equal(sorted(G.edges(data=True)), 23 | sorted(Gin.edges(data=True))) 24 | assert_equal(G.graph,Gin.graph) 25 | os.close(fd) 26 | os.unlink(fname) 27 | 28 | -------------------------------------------------------------------------------- /appengine/networkx/readwrite/tests/test_leda.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | import 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 | 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}|""" 26 | G=nx.parse_leda(data) 27 | (fd,fname)=tempfile.mkstemp() 28 | fh=open(fname,'w') 29 | b=fh.write(data) 30 | fh.close() 31 | Gin=nx.read_leda(fname) 32 | assert_equal(sorted(G.nodes()),sorted(Gin.nodes())) 33 | assert_equal(sorted(G.edges()),sorted(Gin.edges())) 34 | os.close(fd) 35 | os.unlink(fname) 36 | -------------------------------------------------------------------------------- /appengine/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 | 8 | def assert_equal_edges(elist1,elist2): 9 | if len(elist1[0]) == 2: 10 | return assert_equal(sorted(sorted(e) for e in elist1), 11 | sorted(sorted(e) for e in elist2)) 12 | else: 13 | return assert_equal(sorted((sorted((u, v)), d) for u, v, d in elist1), 14 | sorted((sorted((u, v)), d) for u, v, d in elist2)) 15 | 16 | class TestP2G: 17 | 18 | def setUp(self): 19 | self.G=nx.Graph(name="test") 20 | e=[('a','b'),('b','c'),('c','d'),('d','e'),('e','f'),('a','f')] 21 | self.G.add_edges_from(e) 22 | self.G.add_node('g') 23 | self.DG=nx.DiGraph(self.G) 24 | 25 | def test_read_p2g(self): 26 | s = b"""\ 27 | name 28 | 3 4 29 | a 30 | 1 2 31 | b 32 | 33 | c 34 | 0 2 35 | """ 36 | bytesIO = io.BytesIO(s) 37 | G = read_p2g(bytesIO) 38 | assert_equal(G.name,'name') 39 | assert_equal(sorted(G),['a','b','c']) 40 | assert_equal_edges(G.edges(),[('a','b'),('a','c'),('c','a'),('c','c')]) 41 | 42 | def test_write_p2g(self): 43 | s=b"""foo 44 | 3 2 45 | 1 46 | 1 47 | 2 48 | 2 49 | 3 50 | 51 | """ 52 | fh=io.BytesIO() 53 | G=nx.DiGraph() 54 | G.name='foo' 55 | G.add_edges_from([(1,2),(2,3)]) 56 | write_p2g(G,fh) 57 | fh.seek(0) 58 | r=fh.read() 59 | assert_equal(r,s) 60 | 61 | def test_write_read_p2g(self): 62 | fh=io.BytesIO() 63 | G=nx.DiGraph() 64 | G.name='foo' 65 | G.add_edges_from([('a','b'),('b','c')]) 66 | write_p2g(G,fh) 67 | fh.seek(0) 68 | H=read_p2g(fh) 69 | assert_equal_edges(G.edges(),H.edges()) 70 | -------------------------------------------------------------------------------- /appengine/networkx/readwrite/tests/test_pajek.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Pajek tests 4 | """ 5 | 6 | from nose.tools import assert_equal 7 | from networkx import * 8 | import os,tempfile 9 | from io import open 10 | 11 | class TestPajek(object): 12 | def setUp(self): 13 | self.data="""*network Tralala\n*vertices 4\n 1 "A1" 0.0938 0.0896 ellipse x_fact 1 y_fact 1\n 2 "Bb" 0.8188 0.2458 ellipse x_fact 1 y_fact 1\n 3 "C" 0.3688 0.7792 ellipse x_fact 1\n 4 "D2" 0.9583 0.8563 ellipse x_fact 1\n*arcs\n1 1 1 h2 0 w 3 c Blue s 3 a1 -130 k1 0.6 a2 -130 k2 0.6 ap 0.5 l "Bezier loop" lc BlueViolet fos 20 lr 58 lp 0.3 la 360\n2 1 1 h2 0 a1 120 k1 1.3 a2 -120 k2 0.3 ap 25 l "Bezier arc" lphi 270 la 180 lr 19 lp 0.5\n1 2 1 h2 0 a1 40 k1 2.8 a2 30 k2 0.8 ap 25 l "Bezier arc" lphi 90 la 0 lp 0.65\n4 2 -1 h2 0 w 1 k1 -2 k2 250 ap 25 l "Circular arc" c Red lc OrangeRed\n3 4 1 p Dashed h2 0 w 2 c OliveGreen ap 25 l "Straight arc" lc PineGreen\n1 3 1 p Dashed h2 0 w 5 k1 -1 k2 -20 ap 25 l "Oval arc" c Brown lc Black\n3 3 -1 h1 6 w 1 h2 12 k1 -2 k2 -15 ap 0.5 l "Circular loop" c Red lc OrangeRed lphi 270 la 180""" 14 | self.G=nx.MultiDiGraph() 15 | self.G.add_nodes_from(['A1', 'Bb', 'C', 'D2']) 16 | self.G.add_edges_from([('A1', 'A1'), ('A1', 'Bb'), ('A1', 'C'), 17 | ('Bb', 'A1'),('C', 'C'), ('C', 'D2'), 18 | ('D2', 'Bb')]) 19 | 20 | self.G.graph['name']='Tralala' 21 | (self.fd,self.fname)=tempfile.mkstemp() 22 | fh=open(self.fname,'wb') 23 | fh.write(self.data.encode('UTF-8')) 24 | fh.close() 25 | 26 | def tearDown(self): 27 | os.close(self.fd) 28 | os.unlink(self.fname) 29 | 30 | def test_parse_pajek_simple(self): 31 | # Example without node positions or shape 32 | data="""*Vertices 2\n1 "1"\n2 "2"\n*Edges\n1 2\n2 1""" 33 | G=parse_pajek(data) 34 | assert_equal(sorted(G.nodes()), ['1', '2']) 35 | assert_equal(sorted(G.edges()), [('1', '2'), ('1', '2')]) 36 | 37 | def test_parse_pajek(self): 38 | G=parse_pajek(self.data) 39 | assert_equal(sorted(G.nodes()), ['A1', 'Bb', 'C', 'D2']) 40 | assert_equal(sorted(G.edges()), 41 | [('A1', 'A1'), ('A1', 'Bb'), ('A1', 'C'), ('Bb', 'A1'), 42 | ('C', 'C'), ('C', 'D2'), ('D2', 'Bb')]) 43 | 44 | def test_read_pajek(self): 45 | G=parse_pajek(self.data) 46 | Gin=read_pajek(self.fname) 47 | assert_equal(sorted(G.nodes()), sorted(Gin.nodes())) 48 | assert_equal(sorted(G.edges()), sorted(Gin.edges())) 49 | assert_equal(self.G.graph,Gin.graph) 50 | for n in G.node: 51 | assert_equal(G.node[n],Gin.node[n]) 52 | -------------------------------------------------------------------------------- /appengine/networkx/readwrite/tests/test_sparsegraph6.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from nose.tools import * 3 | import networkx as nx 4 | import os,tempfile 5 | 6 | class TestGraph6(object): 7 | 8 | def test_parse_graph6(self): 9 | data="""DF{""" 10 | G=nx.parse_graph6(data) 11 | assert_equal(sorted(G.nodes()),[0, 1, 2, 3, 4]) 12 | assert_equal([e for e in sorted(G.edges())], 13 | [(0, 3), (0, 4), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]) 14 | 15 | def test_read_graph6(self): 16 | data="""DF{""" 17 | G=nx.parse_graph6(data) 18 | (fd,fname)=tempfile.mkstemp() 19 | fh=open(fname,'w') 20 | b=fh.write(data) 21 | fh.close() 22 | Gin=nx.read_graph6(fname) 23 | assert_equal(sorted(G.nodes()),sorted(Gin.nodes())) 24 | assert_equal(sorted(G.edges()),sorted(Gin.edges())) 25 | os.close(fd) 26 | os.unlink(fname) 27 | 28 | def test_read_many_graph6(self): 29 | # Read many graphs into list 30 | data="""DF{\nD`{\nDqK\nD~{\n""" 31 | (fd,fname)=tempfile.mkstemp() 32 | fh=open(fname,'w') 33 | b=fh.write(data) 34 | fh.close() 35 | glist=nx.read_graph6_list(fname) 36 | assert_equal(len(glist),4) 37 | for G in glist: 38 | assert_equal(sorted(G.nodes()),[0, 1, 2, 3, 4]) 39 | os.close(fd) 40 | os.unlink(fname) 41 | 42 | 43 | class TestSparseGraph6(object): 44 | 45 | def test_parse_sparse6(self): 46 | data=""":Q___eDcdFcDeFcE`GaJ`IaHbKNbLM""" 47 | G=nx.parse_sparse6(data) 48 | assert_equal(sorted(G.nodes()), 49 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 50 | 10, 11, 12, 13, 14, 15, 16, 17]) 51 | assert_equal([e for e in sorted(G.edges())], 52 | [(0, 1), (0, 2), (0, 3), (1, 12), (1, 14), (2, 13), 53 | (2, 15), (3, 16), (3, 17), (4, 7), (4, 9), (4, 11), 54 | (5, 6), (5, 8), (5, 9), (6, 10), (6, 11), (7, 8), 55 | (7, 10), (8, 12), (9, 15), (10, 14), (11, 13), 56 | (12, 16), (13, 17), (14, 17), (15, 16)]) 57 | 58 | 59 | def test_read_sparse6(self): 60 | data=""":Q___eDcdFcDeFcE`GaJ`IaHbKNbLM""" 61 | G=nx.parse_sparse6(data) 62 | (fd,fname)=tempfile.mkstemp() 63 | fh=open(fname,'w') 64 | b=fh.write(data) 65 | fh.close() 66 | Gin=nx.read_sparse6(fname) 67 | assert_equal(sorted(G.nodes()),sorted(Gin.nodes())) 68 | assert_equal(sorted(G.edges()),sorted(Gin.edges())) 69 | os.close(fd) 70 | os.unlink(fname) 71 | 72 | def test_read_many_graph6(self): 73 | # Read many graphs into list 74 | data=""":Q___eDcdFcDeFcE`GaJ`IaHbKNbLM\n:Q___dCfDEdcEgcbEGbFIaJ`JaHN`IM""" 75 | (fd,fname)=tempfile.mkstemp() 76 | fh=open(fname,'w') 77 | b=fh.write(data) 78 | fh.close() 79 | glist=nx.read_sparse6_list(fname) 80 | assert_equal(len(glist),2) 81 | for G in glist: 82 | assert_equal(sorted(G.nodes()), 83 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 84 | 10, 11, 12, 13, 14, 15, 16, 17]) 85 | os.close(fd) 86 | os.unlink(fname) 87 | 88 | -------------------------------------------------------------------------------- /appengine/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 | 11 | class TestYaml(object): 12 | @classmethod 13 | def setupClass(cls): 14 | global yaml 15 | try: 16 | import yaml 17 | except ImportError: 18 | raise SkipTest('yaml not available.') 19 | 20 | def setUp(self): 21 | self.build_graphs() 22 | 23 | def build_graphs(self): 24 | self.G = nx.Graph(name="test") 25 | e = [('a','b'),('b','c'),('c','d'),('d','e'),('e','f'),('a','f')] 26 | self.G.add_edges_from(e) 27 | self.G.add_node('g') 28 | 29 | self.DG = nx.DiGraph(self.G) 30 | 31 | self.MG = nx.MultiGraph() 32 | self.MG.add_weighted_edges_from([(1,2,5),(1,2,5),(1,2,1),(3,3,42)]) 33 | 34 | def assert_equal(self, G, data=False): 35 | (fd, fname) = tempfile.mkstemp() 36 | nx.write_yaml(G, fname) 37 | Gin = nx.read_yaml(fname); 38 | 39 | assert_equal(sorted(G.nodes()),sorted(Gin.nodes())) 40 | assert_equal(G.edges(data=data),Gin.edges(data=data)) 41 | 42 | os.close(fd) 43 | os.unlink(fname) 44 | 45 | def testUndirected(self): 46 | self.assert_equal(self.G, False) 47 | 48 | def testDirected(self): 49 | self.assert_equal(self.DG, False) 50 | 51 | def testMultiGraph(self): 52 | self.assert_equal(self.MG, True) 53 | 54 | -------------------------------------------------------------------------------- /appengine/networkx/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uwescience/myria-web/b1c175a5cbe76d4f2219b192635085ece1326588/appengine/networkx/tests/__init__.py -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/networkx/utils/tests/test_misc.py: -------------------------------------------------------------------------------- 1 | from nose.tools import * 2 | import networkx as nx 3 | from networkx.utils import * 4 | 5 | def test_is_string_like(): 6 | assert_true(is_string_like("aaaa")) 7 | assert_false(is_string_like(None)) 8 | assert_false(is_string_like(123)) 9 | 10 | def test_iterable(): 11 | assert_false(iterable(None)) 12 | assert_false(iterable(10)) 13 | assert_true(iterable([1,2,3])) 14 | assert_true(iterable((1,2,3))) 15 | assert_true(iterable({1:"A",2:"X"})) 16 | assert_true(iterable("ABC")) 17 | 18 | def test_graph_iterable(): 19 | K=nx.complete_graph(10) 20 | assert_true(iterable(K)) 21 | assert_true(iterable(K.nodes_iter())) 22 | assert_true(iterable(K.edges_iter())) 23 | 24 | def test_is_list_of_ints(): 25 | assert_true(is_list_of_ints([1,2,3,42])) 26 | assert_false(is_list_of_ints([1,2,3,"kermit"])) 27 | 28 | def test_random_number_distribution(): 29 | # smoke test only 30 | z=uniform_sequence(20) 31 | z=powerlaw_sequence(20,exponent=2.5) 32 | z=pareto_sequence(20,exponent=1.5) 33 | z=discrete_sequence(20,distribution=[0,0,0,0,1,1,1,1,2,2,3]) 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /appengine/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 | -------------------------------------------------------------------------------- /appengine/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 | def test_reverse_cuthill_mckee(): 6 | # example graph from 7 | # http://www.boost.org/doc/libs/1_37_0/libs/graph/example/cuthill_mckee_ordering.cpp 8 | G = nx.Graph([(0,3),(0,5),(1,2),(1,4),(1,6),(1,9),(2,3), 9 | (2,4),(3,5),(3,8),(4,6),(5,6),(5,7),(6,7)]) 10 | rcm = list(reverse_cuthill_mckee_ordering(G,start=0)) 11 | assert_equal(rcm,[9, 1, 4, 6, 7, 2, 8, 5, 3, 0]) 12 | rcm = list(reverse_cuthill_mckee_ordering(G)) 13 | assert_equal(rcm,[0, 8, 5, 7, 3, 6, 4, 2, 1, 9]) 14 | -------------------------------------------------------------------------------- /appengine/networkx/utils/union_find.py: -------------------------------------------------------------------------------- 1 | """ 2 | Union-find data structure. 3 | """ 4 | # Copyright (C) 2004-2011 by 5 | # Aric Hagberg 6 | # Dan Schult 7 | # Pieter Swart 8 | # All rights reserved. 9 | # BSD license. 10 | import networkx as nx 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 | return iter(self.parents) 64 | 65 | def union(self, *objects): 66 | """Find the sets containing the objects and merge them all.""" 67 | roots = [self[x] for x in objects] 68 | heaviest = max([(self.weights[r],r) for r in roots])[1] 69 | for r in roots: 70 | if r != heaviest: 71 | self.weights[heaviest] += self.weights[r] 72 | self.parents[r] = heaviest 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /appengine/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.6' 11 | date = 'Tue Nov 22 07:16:50 2011' 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, 6, '2049c85eac50') 19 | 20 | # Format: a 'datetime.datetime' instance 21 | date_info = datetime.datetime(2011, 11, 22, 7, 16, 50, 102859) 22 | 23 | # Format: (vcs, vcs_tuple) 24 | vcs_info = ('mercurial', ('2049c85eac50', 'tip')) 25 | 26 | -------------------------------------------------------------------------------- /appengine/pagination.py: -------------------------------------------------------------------------------- 1 | import copy 2 | 3 | 4 | QUERIES_PER_PAGE = 25 5 | QUERIES = 'results' 6 | QUERY_ID = 'queryId' 7 | MAX = 'max' 8 | MIN = 'min' 9 | LIMIT = 'limit' 10 | SEARCH = 'q' 11 | 12 | 13 | class Pagination(object): 14 | 15 | def __init__(self, args, result): 16 | self.args = args 17 | self.result = result 18 | self.base_args = {} 19 | try: 20 | self.base_args[LIMIT] = int(self.args[LIMIT]) 21 | except (KeyError, ValueError, TypeError): 22 | self.base_args[LIMIT] = QUERIES_PER_PAGE 23 | try: 24 | self.base_args[SEARCH] = self.args[SEARCH] 25 | except KeyError: 26 | pass 27 | 28 | @property 29 | def prev_args(self): 30 | q = self.result[QUERIES] 31 | ret = copy.copy(self.base_args) 32 | if not q: 33 | return ret 34 | 35 | current_max = q[0][QUERY_ID] 36 | if current_max < self.result[MAX]: 37 | ret[MIN] = current_max + 1 38 | 39 | return ret 40 | 41 | @property 42 | def has_next(self): 43 | q = self.result[QUERIES] 44 | if not q: 45 | return False 46 | 47 | return q[-1][QUERY_ID] > self.result[MIN] 48 | 49 | @property 50 | def next_args(self): 51 | assert self.has_next 52 | 53 | q = self.result[QUERIES] 54 | ret = copy.copy(self.base_args) 55 | if q: 56 | current_min = q[-1][QUERY_ID] 57 | ret[MAX] = current_min - 1 58 | 59 | return ret 60 | 61 | @property 62 | def can_jump(self): 63 | return SEARCH not in self.args 64 | 65 | def iter_pages(self, left_edge=2, left_current=3, 66 | right_current=3, right_edge=2): 67 | 68 | # No explicit page numbers if we can't jump to a specific page 69 | if not self.can_jump: 70 | raise NotImplementedError("page iteration when we cannot jump") 71 | 72 | # The user's search had no results 73 | if self.result[QUERIES]: 74 | current_max = self.result[QUERIES][0][QUERY_ID] 75 | else: 76 | current_max = 0 77 | 78 | max_query = self.result[MAX] 79 | per_page = self.base_args[LIMIT] 80 | current_page = 1 + (max_query - current_max + per_page - 1) / per_page 81 | all_pages = current_page + ((current_max - 1) / per_page) 82 | last = 0 83 | for num in xrange(1, all_pages + 1): 84 | if (num <= left_edge or # we show the first left_edge pages 85 | (current_page - left_current <= num 86 | <= current_page + right_current) # +/- a few nearby 87 | or num > all_pages - right_edge): # and last right_edge 88 | if last + 1 != num: 89 | yield None 90 | ret = copy.copy(self.base_args) 91 | ret[MAX] = current_max + (current_page - num) * per_page 92 | yield {'page': num, 93 | 'args': ret, 94 | 'current': num == current_page} 95 | last = num 96 | -------------------------------------------------------------------------------- /appengine/parsetab.py: -------------------------------------------------------------------------------- 1 | ../submodules/raco/parsetab.py -------------------------------------------------------------------------------- /appengine/ply/__init__.py: -------------------------------------------------------------------------------- 1 | # PLY package 2 | # Author: David Beazley (dave@dabeaz.com) 3 | 4 | __all__ = ['lex','yacc'] 5 | -------------------------------------------------------------------------------- /appengine/raco: -------------------------------------------------------------------------------- 1 | ../submodules/raco/raco -------------------------------------------------------------------------------- /appengine/requests: -------------------------------------------------------------------------------- 1 | ../submodules/requests/requests -------------------------------------------------------------------------------- /appengine/robots.txt: -------------------------------------------------------------------------------- 1 | User-agent: * 2 | Disallow: / 3 | Allow: /editor 4 | -------------------------------------------------------------------------------- /appengine/six.py: -------------------------------------------------------------------------------- 1 | ../submodules/six/six.py -------------------------------------------------------------------------------- /appengine/sqlalchemy: -------------------------------------------------------------------------------- 1 | ../submodules/sqlalchemy/lib/sqlalchemy -------------------------------------------------------------------------------- /appengine/static/apple-touch-icon-114x114-precomposed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uwescience/myria-web/b1c175a5cbe76d4f2219b192635085ece1326588/appengine/static/apple-touch-icon-114x114-precomposed.png -------------------------------------------------------------------------------- /appengine/static/apple-touch-icon-120x120-precomposed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uwescience/myria-web/b1c175a5cbe76d4f2219b192635085ece1326588/appengine/static/apple-touch-icon-120x120-precomposed.png -------------------------------------------------------------------------------- /appengine/static/apple-touch-icon-144x144-precomposed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uwescience/myria-web/b1c175a5cbe76d4f2219b192635085ece1326588/appengine/static/apple-touch-icon-144x144-precomposed.png -------------------------------------------------------------------------------- /appengine/static/apple-touch-icon-152x152-precomposed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uwescience/myria-web/b1c175a5cbe76d4f2219b192635085ece1326588/appengine/static/apple-touch-icon-152x152-precomposed.png -------------------------------------------------------------------------------- /appengine/static/apple-touch-icon-72x72-precomposed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uwescience/myria-web/b1c175a5cbe76d4f2219b192635085ece1326588/appengine/static/apple-touch-icon-72x72-precomposed.png -------------------------------------------------------------------------------- /appengine/static/apple-touch-icon-76x76-precomposed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uwescience/myria-web/b1c175a5cbe76d4f2219b192635085ece1326588/appengine/static/apple-touch-icon-76x76-precomposed.png -------------------------------------------------------------------------------- /appengine/static/apple-touch-icon-precomposed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uwescience/myria-web/b1c175a5cbe76d4f2219b192635085ece1326588/appengine/static/apple-touch-icon-precomposed.png -------------------------------------------------------------------------------- /appengine/static/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uwescience/myria-web/b1c175a5cbe76d4f2219b192635085ece1326588/appengine/static/favicon.ico -------------------------------------------------------------------------------- /appengine/templates/datasets.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block datasets_active %} class="active"{% endblock %} 4 | 5 | {% block content %} 6 |
7 |
8 |

Datasets in Myria

9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | {% for d in datasets %} 20 | 21 | 22 | 23 | 26 | 27 | 28 | {% endfor %} 29 |
Relation nameCreating queryCreate timeDownload
{{d.relationKey.relationName}}{{d.queryId}} 24 | {{d.created}} 25 | {% if d is small_dataset(100*1000*1000) %}JSON CSV TSV{% else %}not available{% endif %}
30 |
31 | {% endblock %} 32 | 33 | {% block footer %} 34 | 35 | 55 | {% endblock %} -------------------------------------------------------------------------------- /appengine/test_style.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | import sys 3 | import unittest 4 | 5 | 6 | class StyleTest(unittest.TestCase): 7 | "run flake8 with the right arguments and ensure all files pass" 8 | def test_style(self): 9 | try: 10 | exclude = [ 11 | 'ply', 12 | 'networkx', 13 | 'six.py', 14 | 'pyparsing.py', 15 | 'parsetab.py', 16 | 'test_myria_up.py', 17 | 'examples.py' 18 | ] 19 | subprocess.check_output( 20 | ['flake8', 21 | '--exclude='+','.join(exclude), 22 | '.'], 23 | stderr=subprocess.STDOUT) 24 | except subprocess.CalledProcessError as e: 25 | print >> sys.stderr, e.output 26 | raise 27 | 28 | if __name__ == '__main__': 29 | unittest.main() 30 | -------------------------------------------------------------------------------- /customize-bootstrap/README.md: -------------------------------------------------------------------------------- 1 | Customizing Bootstrap for Myria 2 | =============================== 3 | 4 | We customize Bootstrap's colors for use in `myria-web` (See [#25](https://github.com/uwescience/myria-web/issues/25)). Here we explain how this is done: 5 | 6 | 1. Check out Bootstrap and switch to the _tag_ matching the current release. At the time of writing, this is version 3.1.1. 7 | 8 | ``` 9 | git clone https://github.com/twbs/bootstrap.git 10 | git checkout v3.1.1 11 | ``` 12 | 13 | 2. The customizations are in this directory in `variables.less.diff`. To apply them, use the `patch` command in the `bootstrap` root directory. 14 | 15 | ``` 16 | cd bootstrap # go to the bootstrap root directory 17 | patch < [path-to-myria-web]/customize-bootstrap/variables.less.diff 18 | ``` 19 | 20 | 3. Compile the `bootstrap` distribution. You should follow their instructions [here](https://github.com/twbs/bootstrap#compiling-css-and-javascript), but the key command is `grunt dist`. 21 | 22 | 4. Copy the modified `css` and `js` files to `myria-web`. 23 | 24 | ``` 25 | cp dist/css/bootstrap.min.css [path-to-myria-web]/appengine/css/ 26 | cp dist/js/bootstrap.min.js [path-to-myria-web]/appengine/js/ 27 | ``` 28 | 29 | 5. Check out the `myria-web` page. 30 | 31 | ## If you make further customizations 32 | 33 | 1. For styling, you should only need to edit `variables.less`. After making changes, you can follow steps 3–5 above to test them out. 34 | 35 | 2. Once you're happy, save the diff back here 36 | 37 | ``` 38 | git diff variables.less > [path-to-myria-web]/customize-bootstrap/variables.less.diff 39 | ``` 40 | 41 | and commit it. 42 | 43 | Also make sure you copy and commit the updated `css` and/or `js` files (if the Bootstrap version changed as well). -------------------------------------------------------------------------------- /customize-bootstrap/variables.less.diff: -------------------------------------------------------------------------------- 1 | diff --git a/less/variables.less b/less/variables.less 2 | index 3846adc..0a6b270 100644 3 | --- a/less/variables.less 4 | +++ b/less/variables.less 5 | @@ -12,6 +12,10 @@ 6 | @gray: lighten(#000, 33.5%); // #555 7 | @gray-light: lighten(#000, 60%); // #999 8 | @gray-lighter: lighten(#000, 93.5%); // #eee 9 | +@white: #fff; 10 | + 11 | +@uw-purple: #39275B; 12 | +@uw-gold: #C79900; 13 | 14 | @brand-primary: #428bca; 15 | @brand-success: #5cb85c; 16 | @@ -360,7 +364,7 @@ 17 | // Inverted navbar 18 | // Reset inverted navbar basics 19 | @navbar-inverse-color: @gray-light; 20 | -@navbar-inverse-bg: #222; 21 | +@navbar-inverse-bg: @uw-purple; 22 | @navbar-inverse-border: darken(@navbar-inverse-bg, 10%); 23 | 24 | // Inverted navbar links 25 | @@ -368,7 +372,7 @@ 26 | @navbar-inverse-link-hover-color: #fff; 27 | @navbar-inverse-link-hover-bg: transparent; 28 | @navbar-inverse-link-active-color: @navbar-inverse-link-hover-color; 29 | -@navbar-inverse-link-active-bg: darken(@navbar-inverse-bg, 10%); 30 | +@navbar-inverse-link-active-bg: transparent; 31 | @navbar-inverse-link-disabled-color: #444; 32 | @navbar-inverse-link-disabled-bg: transparent; 33 | 34 | @@ -378,9 +382,9 @@ 35 | @navbar-inverse-brand-hover-bg: transparent; 36 | 37 | // Inverted navbar toggle 38 | -@navbar-inverse-toggle-hover-bg: #333; 39 | +@navbar-inverse-toggle-hover-bg: transparent; 40 | @navbar-inverse-toggle-icon-bar-bg: #fff; 41 | -@navbar-inverse-toggle-border-color: #333; 42 | +@navbar-inverse-toggle-border-color: transparent; 43 | 44 | 45 | //== Navs 46 | -------------------------------------------------------------------------------- /deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cur_status="$(git status -s)" 4 | cur_branch="$(git rev-parse --abbrev-ref HEAD)" 5 | if [ -n "$cur_status" ] 6 | then 7 | echo "myria-web has been modified; cannot deploy" 8 | elif [ "production" != "$cur_branch" ] 9 | then 10 | echo "myria-web is not on the production branch; cannot deploy" 11 | else 12 | # make sure that raco's parsetab.py is up to date 13 | pushd submodules/raco ; ./scripts/myrial examples/uda.myl > /dev/null ; raco_exit_code=$? ; popd 14 | if [[ $raco_exit_code != 0 ]] ; then 15 | echo "could not re-create parsetab.py in raco submodule; cannot deploy" 16 | exit 17 | fi 18 | git rev-parse HEAD > appengine/VERSION && \ 19 | git rev-parse --abbrev-ref HEAD > appengine/BRANCH && \ 20 | appcfg.py --oauth2 update appengine 21 | fi 22 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: default 3 | title: Myria Web 4 | group: "docs" 5 | weight: 1 6 | section: 5 7 | --- 8 | 9 | # Myria-Web 10 | 11 | In Myria-Web, you will see an editor where you can write MyriaL or SQL queries and execute them with Myria. At the top of the screen, you should see three tabs: "Editor", "Queries", and "Datasets". 12 | 13 | Here is a quick tour of the interface: 14 | 15 | - Click on the **Datasets** tab. Here, you can see the list of all the datasets currently ingested 16 | and available in the service. You can click on the name of a dataset to see its metadata 17 | including the schema. Click on "JSON", "CSV", or "TSV" to download the dataset in the 18 | specified format. 19 | 20 | - Now click on the **Queries** tab. This is where you can see all the queries that yourself 21 | and others have been running. Observe the keyword search window. After you run the example 22 | query below, type the word "Twitter" to see all queries executed on the `public:adhoc:Twitter` relation. 23 | 24 | - Finally, click on the **Editor** tab. This is where you can write and execute queries. 25 | You can start from one of the examples on the right. Click on the example and the 26 | query will appear in the editor window. Queries can be written in SQL or MyriaL. We 27 | recommend MyriaL because, in that mode, you can inter-twine SQL and MyriaL in your 28 | script. 29 | 30 | Try the following query, which ingests a dataset from S3, stores it in the relation `public:adhoc:Twitter`: 31 | 32 | Twitter = LOAD("https://s3-us-west-2.amazonaws.com/myria/public-adhoc-TwitterK.csv", csv(schema(column0:int, column1:int), skip=1)); 33 | STORE(Twitter, public:adhoc:Twitter, [$0]); 34 | 35 | The query below computes an aggregate that it stores in a relation called `public:adhoc:Followers`: 36 | 37 | Twitter = SCAN(public:adhoc:Twitter); 38 | Followers = SELECT $0, COUNT($1) FROM Twitter; 39 | STORE(Followers, public:adhoc:Followers, [$0]); 40 | 41 | (The third argument in the `STORE` statement means to hash-partition the data on the first attribute and store it hash-partitioned across all worker instances.) 42 | 43 | First click on "Parse". This will show you the query plan that Myria will 44 | execute. Then click on "Execute Query". This will execute the query and 45 | produce a link to the output. 46 | 47 | Now select the "Profile Query" option below the query window and 48 | re-execute the query with the option ON. Below the result, you will 49 | see the "Profiling results". Click on it. It wil show you profiling information 50 | about the way the query executed. Explore the output of the profiler. 51 | 52 | ## Perfopticon 53 | 54 | The query execution debugger is described in our paper. Please see [https://idl.cs.washington.edu/papers/perfopticon/](https://idl.cs.washington.edu/papers/perfopticon/). 55 | 56 | # MyriaL 57 | 58 | The above examples use MyriaL. For more information, please see [http://myria.cs.washington.edu/docs/myrial.html](http://myria.cs.washington.edu/docs/myrial.html). 59 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | httmock 2 | nosegae 3 | nose-exclude 4 | WebTest 5 | webapp2 6 | jinja2 7 | paste 8 | 9 | # Flake8: hardcode version plus dependency versions 10 | flake8 == 2.1.0 11 | pep8 == 1.5.4 12 | pyflakes == 0.8.1 13 | mccabe == 0.2.1 14 | # /Flake8 15 | --------------------------------------------------------------------------------