diff --git a/api/pagination.py b/api/pagination.py index 0cfdc0d78..19861bb8f 100644 --- a/api/pagination.py +++ b/api/pagination.py @@ -24,6 +24,7 @@ def count(self): class FuzzyPageNumberPagination(PageNumberPagination): django_paginator_class = FuzzyPaginator + max_page_size = 300 class CursorPagination(CursorPagination): diff --git a/api/serializers.py b/api/serializers.py index 1eaf5f3f0..e6365fdad 100644 --- a/api/serializers.py +++ b/api/serializers.py @@ -5,10 +5,10 @@ from rest_framework_json_api import serializers from share import models -from share.models import ProviderRegistration, SiteBanner, CeleryTaskResult -from api import fields +from share.models import ProviderRegistration, SiteBanner, CeleryTaskResult, logs +from api import fields class BaseShareSerializer(serializers.ModelSerializer): @@ -132,12 +132,20 @@ class Meta: 'is_active', 'gravatar', 'locale', 'time_zone', 'is_trusted' ) - class SourceSerializer(ShareModelSerializer): class Meta: model = models.Source fields = ('name', 'home_page', 'long_title', 'icon') +class HarvestLogSerializer(ShareModelSerializer): + class Meta: + model = models.HarvestLog + fields = '__all__' + +class SourceConfigSerializer(ShareModelSerializer): + class Meta: + model = models.SourceConfig + fields = '__all__' class SiteBannerSerializer(ShareModelSerializer): color = serializers.SerializerMethodField() diff --git a/api/urls.py b/api/urls.py index ec60b1804..47daf496a 100644 --- a/api/urls.py +++ b/api/urls.py @@ -14,6 +14,8 @@ from api.serializers import BaseShareSerializer from api.views.share import ShareObjectViewSet + + app_name = 'api' router = DefaultRouter() @@ -86,6 +88,8 @@ def register_url(self, subclass, viewset): register_route(r'rawdata', views.RawDatumViewSet) register_route(r'user', views.ShareUserViewSet) register_route(r'sources', views.SourceViewSet) +register_route(r'HarvestLog', views.HarvestLogViewSet) +register_route(r'SourceConfig', views.SourceConfigViewSet) router.register(r'normalizeddata', views.NormalizedDataViewSet, base_name='normalizeddata') diff --git a/api/views/__init__.py b/api/views/__init__.py index 68bec4096..ca4da1cb9 100644 --- a/api/views/__init__.py +++ b/api/views/__init__.py @@ -5,3 +5,5 @@ from .registration import * # noqa from .schema import * # noqa from .banner import * # noqa +from .harvestlogs import * # noqa +from .sourceConfig import * # noqa diff --git a/api/views/harvestlogs.py b/api/views/harvestlogs.py new file mode 100644 index 000000000..0ed788fe1 --- /dev/null +++ b/api/views/harvestlogs.py @@ -0,0 +1,24 @@ +from rest_framework import viewsets +from rest_framework import filters +from django_filters.filters import MultipleChoiceFilter +from api.views import ShareObjectViewSet +from share.util import IDObfuscator + +from api.serializers import HarvestLogSerializer +from share.models import HarvestLog + +class SourceConfigFilterBackend(MultipleChoiceFilter): + def filter_queryset(self, request, queryset, view, conjoined=True): + if 'source_config_id' in request.GET: + decoded = IDObfuscator.decode_id(request.GET['source_config_id']) + queryset = queryset.filter(source_config_id=decoded) + if 'status' in request.GET: + queryset = queryset.filter(status__in=request.GET.getlist('status')) + return queryset + #return queryset.order_by('endDate') + +class HarvestLogViewSet(ShareObjectViewSet): + serializer_class = HarvestLogSerializer + queryset = HarvestLog.objects.all() + filter_backends = (SourceConfigFilterBackend, ) + filter_fields = ('status',) diff --git a/api/views/share.py b/api/views/share.py index 798762c2a..11199bf70 100644 --- a/api/views/share.py +++ b/api/views/share.py @@ -28,6 +28,7 @@ class ShareObjectViewSet(viewsets.ReadOnlyModelViewSet): # Override get_queryset to handle items marked as deleted. def get_queryset(self, list=True): + # import ipdb; ipdb.set_trace() queryset = super().get_queryset() if list and hasattr(queryset.model, 'is_deleted'): return queryset.exclude(is_deleted=True) diff --git a/api/views/sourceConfig.py b/api/views/sourceConfig.py new file mode 100644 index 000000000..5c5f67689 --- /dev/null +++ b/api/views/sourceConfig.py @@ -0,0 +1,33 @@ +from rest_framework import viewsets +from api.views import ShareObjectViewSet +from rest_framework import filters +from api.serializers import SourceConfigSerializer +from share.models import SourceConfig +from api.pagination import FuzzyPageNumberPagination +from django.db.models import Count +from django.db.models import Aggregate +from share.models import HarvestLog +from django.db.models import OuterRef, Subquery +from django.db.models import IntegerField + +class SourceConfigViewSet(ShareObjectViewSet): + serializer_class = SourceConfigSerializer + pagination_class = FuzzyPageNumberPagination + queryset = SourceConfig.objects.all() + + # def get_queryset(self): + # recent_harvests = HarvestLog.objects.filter( + # source_config_id = OuterRef(OuterRef('id')), + # status__in = [HarvestLog.STATUS.failed, HarvestLog.STATUS.succeeded] + # ).order_by('-date_started')[:10] + # recent_fails = HarvestLog.objects.filter( + # status = HarvestLog.STATUS.failed, + # id__in = Subquery(recent_harvests.values('id')), + # # output_field = models.IntegerField()) + # ) + # queryset = SourceConfig.objects.all().annotate( + # fails=Count(Subquery(recent_fails.values('id')), + # # output_field = models.IntegerField())) + # ) + # queryset = queryset.order_by('fails') + # return queryset diff --git a/bin/celery b/bin/celery new file mode 100755 index 000000000..96c8eea01 --- /dev/null +++ b/bin/celery @@ -0,0 +1,12 @@ +#!/Users/admin/SHARE/bin/python3.5 +# EASY-INSTALL-ENTRY-SCRIPT: 'celery==4.0.2','console_scripts','celery' +__requires__ = 'celery==4.0.2' +import re +import sys +from pkg_resources import load_entry_point + +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) + sys.exit( + load_entry_point('celery==4.0.2', 'console_scripts', 'celery')() + ) diff --git a/bin/share b/bin/share deleted file mode 100755 index 34473a2e4..000000000 --- a/bin/share +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env python -import os -import sys -from share.bin import main - -if __name__ == '__main__': - main(sys.argv) diff --git a/docs/elasticsearch.rst b/docs/elasticsearch.rst index 5c6f59b37..3d0645b25 100644 --- a/docs/elasticsearch.rst +++ b/docs/elasticsearch.rst @@ -26,6 +26,7 @@ Elasticsearch can be used to search the following fields in the normalized data: 'contributors' 'funders' 'publishers' + 'id' Accessing the Search API diff --git a/include/site/python3.5/greenlet/greenlet.h b/include/site/python3.5/greenlet/greenlet.h new file mode 100644 index 000000000..0eceecbf1 --- /dev/null +++ b/include/site/python3.5/greenlet/greenlet.h @@ -0,0 +1,148 @@ +/* vim:set noet ts=8 sw=8 : */ + +/* Greenlet object interface */ + +#ifndef Py_GREENLETOBJECT_H +#define Py_GREENLETOBJECT_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define GREENLET_VERSION "0.4.12" + +typedef struct _greenlet { + PyObject_HEAD + char* stack_start; + char* stack_stop; + char* stack_copy; + intptr_t stack_saved; + struct _greenlet* stack_prev; + struct _greenlet* parent; + PyObject* run_info; + struct _frame* top_frame; + int recursion_depth; + PyObject* weakreflist; + PyObject* exc_type; + PyObject* exc_value; + PyObject* exc_traceback; + PyObject* dict; +} PyGreenlet; + +#define PyGreenlet_Check(op) PyObject_TypeCheck(op, &PyGreenlet_Type) +#define PyGreenlet_MAIN(op) (((PyGreenlet*)(op))->stack_stop == (char*) -1) +#define PyGreenlet_STARTED(op) (((PyGreenlet*)(op))->stack_stop != NULL) +#define PyGreenlet_ACTIVE(op) (((PyGreenlet*)(op))->stack_start != NULL) +#define PyGreenlet_GET_PARENT(op) (((PyGreenlet*)(op))->parent) + +#if (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 1) || PY_MAJOR_VERSION > 3 +#define GREENLET_USE_PYCAPSULE +#endif + +/* C API functions */ + +/* Total number of symbols that are exported */ +#define PyGreenlet_API_pointers 8 + +#define PyGreenlet_Type_NUM 0 +#define PyExc_GreenletError_NUM 1 +#define PyExc_GreenletExit_NUM 2 + +#define PyGreenlet_New_NUM 3 +#define PyGreenlet_GetCurrent_NUM 4 +#define PyGreenlet_Throw_NUM 5 +#define PyGreenlet_Switch_NUM 6 +#define PyGreenlet_SetParent_NUM 7 + +#ifndef GREENLET_MODULE +/* This section is used by modules that uses the greenlet C API */ +static void **_PyGreenlet_API = NULL; + +#define PyGreenlet_Type (*(PyTypeObject *) _PyGreenlet_API[PyGreenlet_Type_NUM]) + +#define PyExc_GreenletError \ + ((PyObject *) _PyGreenlet_API[PyExc_GreenletError_NUM]) + +#define PyExc_GreenletExit \ + ((PyObject *) _PyGreenlet_API[PyExc_GreenletExit_NUM]) + +/* + * PyGreenlet_New(PyObject *args) + * + * greenlet.greenlet(run, parent=None) + */ +#define PyGreenlet_New \ + (* (PyGreenlet * (*)(PyObject *run, PyGreenlet *parent)) \ + _PyGreenlet_API[PyGreenlet_New_NUM]) + +/* + * PyGreenlet_GetCurrent(void) + * + * greenlet.getcurrent() + */ +#define PyGreenlet_GetCurrent \ + (* (PyGreenlet * (*)(void)) _PyGreenlet_API[PyGreenlet_GetCurrent_NUM]) + +/* + * PyGreenlet_Throw( + * PyGreenlet *greenlet, + * PyObject *typ, + * PyObject *val, + * PyObject *tb) + * + * g.throw(...) + */ +#define PyGreenlet_Throw \ + (* (PyObject * (*) \ + (PyGreenlet *self, PyObject *typ, PyObject *val, PyObject *tb)) \ + _PyGreenlet_API[PyGreenlet_Throw_NUM]) + +/* + * PyGreenlet_Switch(PyGreenlet *greenlet, PyObject *args) + * + * g.switch(*args, **kwargs) + */ +#define PyGreenlet_Switch \ + (* (PyObject * (*)(PyGreenlet *greenlet, PyObject *args, PyObject *kwargs)) \ + _PyGreenlet_API[PyGreenlet_Switch_NUM]) + +/* + * PyGreenlet_SetParent(PyObject *greenlet, PyObject *new_parent) + * + * g.parent = new_parent + */ +#define PyGreenlet_SetParent \ + (* (int (*)(PyGreenlet *greenlet, PyGreenlet *nparent)) \ + _PyGreenlet_API[PyGreenlet_SetParent_NUM]) + +/* Macro that imports greenlet and initializes C API */ +#ifdef GREENLET_USE_PYCAPSULE +#define PyGreenlet_Import() \ +{ \ + _PyGreenlet_API = (void**)PyCapsule_Import("greenlet._C_API", 0); \ +} +#else +#define PyGreenlet_Import() \ +{ \ + PyObject *module = PyImport_ImportModule("greenlet"); \ + if (module != NULL) { \ + PyObject *c_api_object = PyObject_GetAttrString( \ + module, "_C_API"); \ + if (c_api_object != NULL && PyCObject_Check(c_api_object)) { \ + _PyGreenlet_API = \ + (void **) PyCObject_AsVoidPtr(c_api_object); \ + Py_DECREF(c_api_object); \ + } \ + Py_DECREF(module); \ + } \ +} +#endif + +#endif /* GREENLET_MODULE */ + +#ifdef __cplusplus +} +#endif +#endif /* !Py_GREENLETOBJECT_H */ diff --git a/pip-selfcheck.json b/pip-selfcheck.json new file mode 100644 index 000000000..eed65ddb9 --- /dev/null +++ b/pip-selfcheck.json @@ -0,0 +1 @@ +{"last_check":"2017-06-22T15:35:52Z","pypi_version":"9.0.1"} diff --git a/pyvenv.cfg b/pyvenv.cfg new file mode 100644 index 000000000..aba37e81a --- /dev/null +++ b/pyvenv.cfg @@ -0,0 +1,3 @@ +home = /usr/local/bin +include-system-site-packages = false +version = 3.5.3 diff --git a/share/doc/networkx-1.11/INSTALL.txt b/share/doc/networkx-1.11/INSTALL.txt new file mode 100644 index 000000000..0df6ae25f --- /dev/null +++ b/share/doc/networkx-1.11/INSTALL.txt @@ -0,0 +1,3 @@ +See doc/source/install.rst +or +http://networkx.github.io/documentation/latest/install.html diff --git a/share/doc/networkx-1.11/LICENSE.txt b/share/doc/networkx-1.11/LICENSE.txt new file mode 100644 index 000000000..5d07e773c --- /dev/null +++ b/share/doc/networkx-1.11/LICENSE.txt @@ -0,0 +1,40 @@ +License +======= +NetworkX is distributed with the BSD license. + +:: + + Copyright (C) 2004-2016, NetworkX Developers + Aric Hagberg + Dan Schult + Pieter Swart + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * Neither the name of the NetworkX Developers nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT + OWNER 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. diff --git a/share/doc/networkx-1.11/examples/3d_drawing/mayavi2_spring.py b/share/doc/networkx-1.11/examples/3d_drawing/mayavi2_spring.py new file mode 100644 index 000000000..b9eda22b7 --- /dev/null +++ b/share/doc/networkx-1.11/examples/3d_drawing/mayavi2_spring.py @@ -0,0 +1,37 @@ +# needs mayavi2 +# run with ipython -wthread +import networkx as nx +import numpy as np +from enthought.mayavi import mlab + +# some graphs to try +#H=nx.krackhardt_kite_graph() +#H=nx.Graph();H.add_edge('a','b');H.add_edge('a','c');H.add_edge('a','d') +#H=nx.grid_2d_graph(4,5) +H=nx.cycle_graph(20) + +# reorder nodes from 0,len(G)-1 +G=nx.convert_node_labels_to_integers(H) +# 3d spring layout +pos=nx.spring_layout(G,dim=3) +# numpy array of x,y,z positions in sorted node order +xyz=np.array([pos[v] for v in sorted(G)]) +# scalar colors +scalars=np.array(G.nodes())+5 + +mlab.figure(1, bgcolor=(0, 0, 0)) +mlab.clf() + +pts = mlab.points3d(xyz[:,0], xyz[:,1], xyz[:,2], + scalars, + scale_factor=0.1, + scale_mode='none', + colormap='Blues', + resolution=20) + +pts.mlab_source.dataset.lines = np.array(G.edges()) +tube = mlab.pipeline.tube(pts, tube_radius=0.01) +mlab.pipeline.surface(tube, color=(0.8, 0.8, 0.8)) + +mlab.savefig('mayavi2_spring.png') +# mlab.show() # interactive window diff --git a/share/doc/networkx-1.11/examples/advanced/eigenvalues.py b/share/doc/networkx-1.11/examples/advanced/eigenvalues.py new file mode 100644 index 000000000..dffa429ac --- /dev/null +++ b/share/doc/networkx-1.11/examples/advanced/eigenvalues.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python +""" +Create an G{n,m} random graph and compute the eigenvalues. +Requires numpy and matplotlib. +""" +import networkx as nx +import numpy.linalg +import matplotlib.pyplot as plt + +n = 1000 # 1000 nodes +m = 5000 # 5000 edges +G = nx.gnm_random_graph(n,m) + +L = nx.normalized_laplacian_matrix(G) +e = numpy.linalg.eigvals(L.A) +print("Largest eigenvalue:", max(e)) +print("Smallest eigenvalue:", min(e)) +plt.hist(e,bins=100) # histogram with 100 bins +plt.xlim(0,2) # eigenvalues between 0 and 2 +plt.show() diff --git a/share/doc/networkx-1.11/examples/advanced/heavy_metal_umlaut.py b/share/doc/networkx-1.11/examples/advanced/heavy_metal_umlaut.py new file mode 100644 index 000000000..9055771e2 --- /dev/null +++ b/share/doc/networkx-1.11/examples/advanced/heavy_metal_umlaut.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Example using unicode strings as graph labels. + +Also shows creative use of the Heavy Metal Umlaut: +http://en.wikipedia.org/wiki/Heavy_metal_umlaut + +""" +# Author: Aric Hagberg (hagberg@lanl.gov) + +# Copyright (C) 2006-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +import networkx as NX +try: + import pylab as P +except ImportError: + pass + +try: + hd='H' + unichr(252) + 'sker D' + unichr(252) + mh='Mot' + unichr(246) + 'rhead' + mc='M' + unichr(246) + 'tley Cr' + unichr(252) + 'e' + st='Sp' + unichr(305) + 'n' + unichr(776) + 'al Tap' + q='Queensr' + unichr(255) + 'che' + boc='Blue ' + unichr(214) +'yster Cult' + dt='Deatht' + unichr(246) + 'ngue' +except NameError: + hd='H' + chr(252) + 'sker D' + chr(252) + mh='Mot' + chr(246) + 'rhead' + mc='M' + chr(246) + 'tley Cr' + chr(252) + 'e' + st='Sp' + chr(305) + 'n' + chr(776) + 'al Tap' + q='Queensr' + chr(255) + 'che' + boc='Blue ' + chr(214) +'yster Cult' + dt='Deatht' + chr(246) + 'ngue' + +G=NX.Graph() +G.add_edge(hd,mh) +G.add_edge(mc,st) +G.add_edge(boc,mc) +G.add_edge(boc,dt) +G.add_edge(st,dt) +G.add_edge(q,st) +G.add_edge(dt,mh) +G.add_edge(st,mh) + +# write in UTF-8 encoding +fh=open('edgelist.utf-8','wb') +fh.write('# -*- coding: utf-8 -*-\n'.encode('utf-8')) # encoding hint for emacs +NX.write_multiline_adjlist(G,fh,delimiter='\t', encoding = 'utf-8') + +# read and store in UTF-8 +fh=open('edgelist.utf-8','rb') +H=NX.read_multiline_adjlist(fh,delimiter='\t', encoding = 'utf-8') + +for n in G.nodes(): + if n not in H: + print(False) + +print(G.nodes()) + +try: + pos=NX.spring_layout(G) + NX.draw(G,pos,font_size=16,with_labels=False) + for p in pos: # raise text positions + pos[p][1]+=0.07 + NX.draw_networkx_labels(G,pos) + P.show() +except: + pass + + diff --git a/share/doc/networkx-1.11/examples/advanced/iterated_dynamical_systems.py b/share/doc/networkx-1.11/examples/advanced/iterated_dynamical_systems.py new file mode 100644 index 000000000..2355b24ac --- /dev/null +++ b/share/doc/networkx-1.11/examples/advanced/iterated_dynamical_systems.py @@ -0,0 +1,199 @@ +""" +Digraphs from Integer-valued Iterated Functions +=============================================== + + +Sums of cubes on 3N +------------------- + +The number 153 has a curious property. + +Let 3N={3,6,9,12,...} be the set of positive multiples of 3. Define an +iterative process f:3N->3N as follows: for a given n, take each digit +of n (in base 10), cube it and then sum the cubes to obtain f(n). + +When this process is repeated, the resulting series n, f(n), f(f(n)),... +terminate in 153 after a finite number of iterations (the process ends +because 153 = 1**3 + 5**3 + 3**3). + +In the language of discrete dynamical systems, 153 is the global +attractor for the iterated map f restricted to the set 3N. + +For example: take the number 108 + +f(108) = 1**3 + 0**3 + 8**3 = 513 + +and + +f(513) = 5**3 + 1**3 + 3**3 = 153 + +So, starting at 108 we reach 153 in two iterations, +represented as: + +108->513->153 + +Computing all orbits of 3N up to 10**5 reveals that the attractor +153 is reached in a maximum of 14 iterations. In this code we +show that 13 cycles is the maximum required for all integers (in 3N) +less than 10,000. + +The smallest number that requires 13 iterations to reach 153, is 177, i.e., + +177->687->1071->345->216->225->141->66->432->99->1458->702->351->153 + +The resulting large digraphs are useful for testing network software. + +The general problem +------------------- + +Given numbers n, a power p and base b, define F(n; p, b) as the sum of +the digits of n (in base b) raised to the power p. The above example +corresponds to f(n)=F(n; 3,10), and below F(n; p, b) is implemented as +the function powersum(n,p,b). The iterative dynamical system defined by +the mapping n:->f(n) above (over 3N) converges to a single fixed point; +153. Applying the map to all positive integers N, leads to a discrete +dynamical process with 5 fixed points: 1, 153, 370, 371, 407. Modulo 3 +those numbers are 1, 0, 1, 2, 2. The function f above has the added +property that it maps a multiple of 3 to another multiple of 3; i.e. it +is invariant on the subset 3N. + + +The squaring of digits (in base 10) result in cycles and the +single fixed point 1. I.e., from a certain point on, the process +starts repeating itself. + +keywords: "Recurring Digital Invariant", "Narcissistic Number", +"Happy Number" + +The 3n+1 problem +---------------- + +There is a rich history of mathematical recreations +associated with discrete dynamical systems. The most famous +is the Collatz 3n+1 problem. See the function +collatz_problem_digraph below. The Collatz conjecture +--- that every orbit returrns to the fixed point 1 in finite time +--- is still unproven. Even the great Paul Erdos said "Mathematics +is not yet ready for such problems", and offered $500 +for its solution. + +keywords: "3n+1", "3x+1", "Collatz problem", "Thwaite's conjecture" + + +""" +from networkx import * +from math import * + + +nmax=10000 +p=3 +mach_eps=0.00000000001 + +def digitsrep(n,b=10): + """Return list of digits comprising n represented in base b. + n must be a nonnegative integer""" + + # very inefficient if you only work with base 10 + dlist=[] + if n<=0: + return [0] + maxpow=int(floor( log(n)/log(b) + mach_eps )) + pow=maxpow + while pow>=0: + x=int(floor(n // b**pow)) + dlist.append(x) + n=n-x*b**pow + pow=pow-1 + return dlist + +def powersum(n,p,b=10): + """Return sum of digits of n (in base b) raised to the power p.""" + dlist=digitsrep(n,b) + sum=0 + for k in dlist: + sum+=k**p + return sum + +def attractor153_graph(n,p,multiple=3,b=10): + """Return digraph of iterations of powersum(n,3,10).""" + G=DiGraph() + for k in range(1,n+1): + if k%multiple==0 and k not in G: + k1=k + knext=powersum(k1,p,b) + while k1!=knext: + G.add_edge(k1,knext) + k1=knext + knext=powersum(k1,p,b) + return G + +def squaring_cycle_graph_old(n,b=10): + """Return digraph of iterations of powersum(n,2,10).""" + G=DiGraph() + for k in range(1,n+1): + k1=k + G.add_node(k1) # case k1==knext, at least add node + knext=powersum(k1,2,b) + G.add_edge(k1,knext) + while k1!=knext: # stop if fixed point + k1=knext + knext=powersum(k1,2,b) + G.add_edge(k1,knext) + if G.out_degree(knext) >=1: + # knext has already been iterated in and out + break + return G + +def sum_of_digits_graph(nmax,b=10): + def f(n): return powersum(n,1,b) + return discrete_dynamics_digraph(nmax,f) + +def squaring_cycle_digraph(nmax,b=10): + def f(n): return powersum(n,2,b) + return discrete_dynamics_digraph(nmax,f) + +def cubing_153_digraph(nmax): + def f(n): return powersum(n,3,10) + return discrete_dynamics_digraph(nmax,f) + +def discrete_dynamics_digraph(nmax,f,itermax=50000): + G=DiGraph() + for k in range(1,nmax+1): + kold=k + G.add_node(kold) + knew=f(kold) + G.add_edge(kold,knew) + while kold!=knew and kold<=1: + # knew has already been iterated in and out + break + return G + +def collatz_problem_digraph(nmax): + def f(n): + if n%2==0: + return n // 2 + else: + return 3*n+1 + return discrete_dynamics_digraph(nmax,f) + +def fixed_points(G): + """Return a list of fixed points for the discrete dynamical + system represented by the digraph G. + """ + return [n for n in G if G.out_degree(n)==0] + + +if __name__ == "__main__": + nmax=10000 + print("Building cubing_153_digraph(%d)"% nmax) + G=cubing_153_digraph(nmax) + print("Resulting digraph has", len(G), "nodes and", + G.size()," edges") + print("Shortest path from 177 to 153 is:") + print(shortest_path(G,177,153)) + print("fixed points are %s" % fixed_points(G)) diff --git a/share/doc/networkx-1.11/examples/advanced/parallel_betweenness.py b/share/doc/networkx-1.11/examples/advanced/parallel_betweenness.py new file mode 100644 index 000000000..45cafd582 --- /dev/null +++ b/share/doc/networkx-1.11/examples/advanced/parallel_betweenness.py @@ -0,0 +1,73 @@ +""" +Example of parallel implementation of betweenness centrality using the +multiprocessing module from Python Standard Library. + +The function betweenness centrality accepts a bunch of nodes and computes +the contribution of those nodes to the betweenness centrality of the whole +network. Here we divide the network in chunks of nodes and we compute their +contribution to the betweenness centrality of the whole network. +""" + +from multiprocessing import Pool +import time +import itertools +import networkx as nx + + +def chunks(l, n): + """Divide a list of nodes `l` in `n` chunks""" + l_c = iter(l) + while 1: + x = tuple(itertools.islice(l_c, n)) + if not x: + return + yield x + + +def _betmap(G_normalized_weight_sources_tuple): + """Pool for multiprocess only accepts functions with one argument. + This function uses a tuple as its only argument. We use a named tuple for + python 3 compatibility, and then unpack it when we send it to + `betweenness_centrality_source` + """ + return nx.betweenness_centrality_source(*G_normalized_weight_sources_tuple) + + +def betweenness_centrality_parallel(G, processes=None): + """Parallel betweenness centrality function""" + p = Pool(processes=processes) + node_divisor = len(p._pool)*4 + node_chunks = list(chunks(G.nodes(), int(G.order()/node_divisor))) + num_chunks = len(node_chunks) + bt_sc = p.map(_betmap, + zip([G]*num_chunks, + [True]*num_chunks, + [None]*num_chunks, + node_chunks)) + + # Reduce the partial solutions + bt_c = bt_sc[0] + for bt in bt_sc[1:]: + for n in bt: + bt_c[n] += bt[n] + return bt_c + +if __name__ == "__main__": + G_ba = nx.barabasi_albert_graph(1000, 3) + G_er = nx.gnp_random_graph(1000, 0.01) + G_ws = nx.connected_watts_strogatz_graph(1000, 4, 0.1) + for G in [G_ba, G_er, G_ws]: + print("") + print("Computing betweenness centrality for:") + print(nx.info(G)) + print("\tParallel version") + start = time.time() + bt = betweenness_centrality_parallel(G) + print("\t\tTime: %.4F" % (time.time()-start)) + print("\t\tBetweenness centrality for node 0: %.5f" % (bt[0])) + print("\tNon-Parallel version") + start = time.time() + bt = nx.betweenness_centrality(G) + print("\t\tTime: %.4F seconds" % (time.time()-start)) + print("\t\tBetweenness centrality for node 0: %.5f" % (bt[0])) + print("") diff --git a/share/doc/networkx-1.11/examples/algorithms/blockmodel.py b/share/doc/networkx-1.11/examples/algorithms/blockmodel.py new file mode 100644 index 000000000..2fed34764 --- /dev/null +++ b/share/doc/networkx-1.11/examples/algorithms/blockmodel.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python +# encoding: utf-8 +""" +Example of creating a block model using the blockmodel function in NX. Data used is the Hartford, CT drug users network: + +@article{, + title = {Social Networks of Drug Users in {High-Risk} Sites: Finding the Connections}, + volume = {6}, + shorttitle = {Social Networks of Drug Users in {High-Risk} Sites}, + url = {http://dx.doi.org/10.1023/A:1015457400897}, + doi = {10.1023/A:1015457400897}, + number = {2}, + journal = {{AIDS} and Behavior}, + author = {Margaret R. Weeks and Scott Clair and Stephen P. Borgatti and Kim Radda and Jean J. Schensul}, + month = jun, + year = {2002}, + pages = {193--206} +} + +""" +# Authors: Drew Conway , Aric Hagberg + +from collections import defaultdict +import networkx as nx +import numpy +from scipy.cluster import hierarchy +from scipy.spatial import distance +import matplotlib.pyplot as plt + + +def create_hc(G): + """Creates hierarchical cluster of graph G from distance matrix""" + path_length=nx.all_pairs_shortest_path_length(G) + distances=numpy.zeros((len(G),len(G))) + for u,p in path_length.items(): + for v,d in p.items(): + distances[u][v]=d + # Create hierarchical cluster + Y=distance.squareform(distances) + Z=hierarchy.complete(Y) # Creates HC using farthest point linkage + # This partition selection is arbitrary, for illustrive purposes + membership=list(hierarchy.fcluster(Z,t=1.15)) + # Create collection of lists for blockmodel + partition=defaultdict(list) + for n,p in zip(list(range(len(G))),membership): + partition[p].append(n) + return list(partition.values()) + +if __name__ == '__main__': + G=nx.read_edgelist("hartford_drug.edgelist") + + # Extract largest connected component into graph H + H=nx.connected_component_subgraphs(G)[0] + # Makes life easier to have consecutively labeled integer nodes + H=nx.convert_node_labels_to_integers(H) + # Create parititions with hierarchical clustering + partitions=create_hc(H) + # Build blockmodel graph + BM=nx.blockmodel(H,partitions) + + + # Draw original graph + pos=nx.spring_layout(H,iterations=100) + fig=plt.figure(1,figsize=(6,10)) + ax=fig.add_subplot(211) + nx.draw(H,pos,with_labels=False,node_size=10) + plt.xlim(0,1) + plt.ylim(0,1) + + # Draw block model with weighted edges and nodes sized by number of internal nodes + node_size=[BM.node[x]['nnodes']*10 for x in BM.nodes()] + edge_width=[(2*d['weight']) for (u,v,d) in BM.edges(data=True)] + # Set positions to mean of positions of internal nodes from original graph + posBM={} + for n in BM: + xy=numpy.array([pos[u] for u in BM.node[n]['graph']]) + posBM[n]=xy.mean(axis=0) + ax=fig.add_subplot(212) + nx.draw(BM,posBM,node_size=node_size,width=edge_width,with_labels=False) + plt.xlim(0,1) + plt.ylim(0,1) + plt.axis('off') + plt.savefig('hartford_drug_block_model.png') diff --git a/share/doc/networkx-1.11/examples/algorithms/davis_club.py b/share/doc/networkx-1.11/examples/algorithms/davis_club.py new file mode 100644 index 000000000..68fab4bf2 --- /dev/null +++ b/share/doc/networkx-1.11/examples/algorithms/davis_club.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python +""" +Davis Southern Club Women + +Shows how to make unipartite projections of the graph and compute the +properties of those graphs. + +These data were collected by Davis et al. in the 1930s. +They represent observed attendance at 14 social events by 18 Southern women. +The graph is bipartite (clubs, women). +""" +import networkx as nx +import networkx.algorithms.bipartite as bipartite + +G = nx.davis_southern_women_graph() +women = G.graph['top'] +clubs = G.graph['bottom'] + +print("Biadjacency matrix") +print(bipartite.biadjacency_matrix(G,women,clubs)) + +# project bipartite graph onto women nodes +W = bipartite.projected_graph(G, women) +print('') +print("#Friends, Member") +for w in women: + print('%d %s' % (W.degree(w),w)) + +# project bipartite graph onto women nodes keeping number of co-occurence +# the degree computed is weighted and counts the total number of shared contacts +W = bipartite.weighted_projected_graph(G, women) +print('') +print("#Friend meetings, Member") +for w in women: + print('%d %s' % (W.degree(w,weight='weight'),w)) + diff --git a/share/doc/networkx-1.11/examples/algorithms/hartford_drug.edgelist b/share/doc/networkx-1.11/examples/algorithms/hartford_drug.edgelist new file mode 100644 index 000000000..c1e92c8eb --- /dev/null +++ b/share/doc/networkx-1.11/examples/algorithms/hartford_drug.edgelist @@ -0,0 +1,338 @@ +# source target +1 2 +1 10 +2 1 +2 10 +3 7 +4 7 +4 209 +5 132 +6 150 +7 3 +7 4 +7 9 +8 106 +8 115 +9 1 +9 2 +9 7 +10 1 +10 2 +11 133 +11 218 +12 88 +13 214 +14 24 +14 52 +16 10 +16 19 +17 64 +17 78 +18 55 +18 103 +18 163 +19 18 +20 64 +20 180 +21 16 +21 22 +22 21 +22 64 +22 106 +23 20 +23 22 +23 64 +24 14 +24 31 +24 122 +27 115 +28 29 +29 28 +30 19 +31 24 +31 32 +31 122 +31 147 +31 233 +32 31 +32 86 +34 35 +34 37 +35 34 +35 43 +36 132 +36 187 +37 38 +37 90 +37 282 +38 42 +38 43 +38 210 +40 20 +42 15 +42 38 +43 34 +43 35 +43 38 +45 107 +46 61 +46 72 +48 23 +49 30 +49 64 +49 108 +49 115 +49 243 +50 30 +50 47 +50 55 +50 125 +50 163 +52 218 +52 224 +54 111 +54 210 +55 65 +55 67 +55 105 +55 108 +55 222 +56 18 +56 64 +57 65 +57 125 +58 20 +58 30 +58 50 +58 103 +58 180 +59 164 +63 125 +64 8 +64 50 +64 70 +64 256 +66 20 +66 84 +66 106 +66 125 +67 22 +67 50 +67 113 +68 50 +70 50 +70 64 +71 72 +74 29 +74 75 +74 215 +75 74 +75 215 +76 58 +76 104 +77 103 +78 64 +78 68 +80 207 +80 210 +82 8 +82 77 +82 83 +82 97 +82 163 +83 82 +83 226 +83 243 +84 29 +84 154 +87 101 +87 189 +89 90 +90 89 +90 94 +91 86 +92 19 +92 30 +92 106 +94 72 +94 89 +94 90 +95 30 +96 75 +96 256 +97 80 +97 128 +98 86 +100 86 +101 87 +103 77 +103 104 +104 58 +104 77 +104 103 +106 22 +107 38 +107 114 +107 122 +108 49 +108 55 +111 121 +111 128 +111 210 +113 253 +114 107 +116 30 +116 140 +118 129 +118 138 +120 88 +121 128 +122 31 +123 32 +124 244 +125 132 +126 163 +126 180 +128 38 +128 111 +129 118 +132 29 +132 30 +133 30 +134 135 +134 150 +135 134 +137 144 +138 118 +138 129 +139 142 +141 157 +141 163 +142 139 +143 2 +144 137 +145 151 +146 137 +146 165 +146 169 +146 171 +147 31 +147 128 +148 146 +148 169 +148 171 +148 282 +149 128 +149 148 +149 172 +150 86 +151 145 +152 4 +153 134 +154 155 +156 161 +157 141 +161 156 +165 144 +165 148 +167 149 +169 15 +169 148 +169 171 +170 115 +170 173 +170 183 +170 202 +171 72 +171 148 +171 169 +173 170 +175 100 +176 10 +178 181 +181 178 +182 38 +182 171 +183 96 +185 50 +186 127 +187 50 +187 65 +188 30 +188 50 +189 87 +189 89 +190 35 +190 38 +190 122 +190 182 +191 54 +191 118 +191 129 +191 172 +192 149 +192 167 +195 75 +197 50 +197 188 +198 218 +198 221 +198 222 +200 65 +200 220 +201 113 +202 156 +203 232 +204 194 +207 38 +207 122 +207 124 +208 30 +208 50 +210 38 +210 207 +211 37 +213 35 +213 38 +214 13 +214 14 +214 171 +214 213 +215 75 +217 39 +218 68 +218 222 +221 198 +222 198 +222 218 +223 39 +225 3 +226 22 +229 65 +230 68 +231 43 +232 95 +232 203 +233 99 +234 68 +234 230 +237 244 +238 145 +242 3 +242 113 +244 237 +249 96 +250 156 +252 65 +254 65 +258 113 +268 4 +270 183 +272 6 +275 96 +280 183 +280 206 +282 37 +285 75 +290 285 +293 290 \ No newline at end of file diff --git a/share/doc/networkx-1.11/examples/algorithms/krackhardt_centrality.py b/share/doc/networkx-1.11/examples/algorithms/krackhardt_centrality.py new file mode 100644 index 000000000..71dee8f18 --- /dev/null +++ b/share/doc/networkx-1.11/examples/algorithms/krackhardt_centrality.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python +""" +Centrality measures of Krackhardt social network. +""" +# Author: Aric Hagberg (hagberg@lanl.gov) +# Date: 2005-05-12 14:33:11 -0600 (Thu, 12 May 2005) +# Revision: 998 + +# Copyright (C) 2004-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +from networkx import * + +G=krackhardt_kite_graph() + +print("Betweenness") +b=betweenness_centrality(G) +for v in G.nodes(): + print("%0.2d %5.3f"%(v,b[v])) + +print("Degree centrality") +d=degree_centrality(G) +for v in G.nodes(): + print("%0.2d %5.3f"%(v,d[v])) + +print("Closeness centrality") +c=closeness_centrality(G) +for v in G.nodes(): + print("%0.2d %5.3f"%(v,c[v])) diff --git a/share/doc/networkx-1.11/examples/algorithms/rcm.py b/share/doc/networkx-1.11/examples/algorithms/rcm.py new file mode 100644 index 000000000..43fa56f6c --- /dev/null +++ b/share/doc/networkx-1.11/examples/algorithms/rcm.py @@ -0,0 +1,32 @@ +# Cuthill-McKee ordering of matrices +# The reverse Cuthill-McKee algorithm gives a sparse matrix ordering that +# reduces the matrix bandwidth. +# Requires NumPy +# Copyright (C) 2011-2016 by +# Author: Aric Hagberg +# BSD License +import networkx as nx +from networkx.utils import reverse_cuthill_mckee_ordering +import numpy as np + +# build low-bandwidth numpy matrix +G=nx.grid_2d_graph(3,3) +rcm = list(reverse_cuthill_mckee_ordering(G)) +print("ordering",rcm) + +print("unordered Laplacian matrix") +A = nx.laplacian_matrix(G) +x,y = np.nonzero(A) +#print("lower bandwidth:",(y-x).max()) +#print("upper bandwidth:",(x-y).max()) +print("bandwidth: %d"%((y-x).max()+(x-y).max()+1)) +print(A) + +B = nx.laplacian_matrix(G,nodelist=rcm) +print("low-bandwidth Laplacian matrix") +x,y = np.nonzero(B) +#print("lower bandwidth:",(y-x).max()) +#print("upper bandwidth:",(x-y).max()) +print("bandwidth: %d"%((y-x).max()+(x-y).max()+1)) +print(B) + diff --git a/share/doc/networkx-1.11/examples/basic/properties.py b/share/doc/networkx-1.11/examples/basic/properties.py new file mode 100644 index 000000000..9ac87f86e --- /dev/null +++ b/share/doc/networkx-1.11/examples/basic/properties.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python +""" +Compute some network properties for the lollipop graph. +""" +# Copyright (C) 2004-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +from networkx import * + +G = lollipop_graph(4,6) + +pathlengths=[] + +print("source vertex {target:length, }") +for v in G.nodes(): + spl=single_source_shortest_path_length(G,v) + print('%s %s' % (v,spl)) + for p in spl.values(): + pathlengths.append(p) + +print('') +print("average shortest path length %s" % (sum(pathlengths)/len(pathlengths))) + +# histogram of path lengths +dist={} +for p in pathlengths: + if p in dist: + dist[p]+=1 + else: + dist[p]=1 + +print('') +print("length #paths") +verts=dist.keys() +for d in sorted(verts): + print('%s %d' % (d,dist[d])) + +print("radius: %d" % radius(G)) +print("diameter: %d" % diameter(G)) +print("eccentricity: %s" % eccentricity(G)) +print("center: %s" % center(G)) +print("periphery: %s" % periphery(G)) +print("density: %s" % density(G)) + diff --git a/share/doc/networkx-1.11/examples/basic/read_write.py b/share/doc/networkx-1.11/examples/basic/read_write.py new file mode 100644 index 000000000..37db0cd7a --- /dev/null +++ b/share/doc/networkx-1.11/examples/basic/read_write.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python +""" +Read and write graphs. +""" +# Author: Aric Hagberg (hagberg@lanl.gov) + +# Copyright (C) 2004-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +from networkx import * +import sys +G=grid_2d_graph(5,5) # 5x5 grid +try: # Python 2.6+ + write_adjlist(G,sys.stdout) # write adjacency list to screen +except TypeError: # Python 3.x + write_adjlist(G,sys.stdout.buffer) # write adjacency list to screen +# write edgelist to grid.edgelist +write_edgelist(G,path="grid.edgelist",delimiter=":") +# read edgelist from grid.edgelist +H=read_edgelist(path="grid.edgelist",delimiter=":") + diff --git a/share/doc/networkx-1.11/examples/drawing/atlas.py b/share/doc/networkx-1.11/examples/drawing/atlas.py new file mode 100644 index 000000000..418ac6363 --- /dev/null +++ b/share/doc/networkx-1.11/examples/drawing/atlas.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python +""" +Atlas of all graphs of 6 nodes or less. + +""" +# Author: Aric Hagberg (hagberg@lanl.gov) + +# Copyright (C) 2004-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +import networkx as nx +from networkx.generators.atlas import * +from networkx.algorithms.isomorphism.isomorph import graph_could_be_isomorphic as isomorphic +import random + +def atlas6(): + """ Return the atlas of all connected graphs of 6 nodes or less. + Attempt to check for isomorphisms and remove. + """ + + Atlas = graph_atlas_g()[0:208] # 208 + # remove isolated nodes, only connected graphs are left + U = nx.Graph() # graph for union of all graphs in atlas + for G in Atlas: + zerodegree = [n for n in G if G.degree(n)==0] + for n in zerodegree: + G.remove_node(n) + U = nx.disjoint_union(U, G) + + # list of graphs of all connected components + C = nx.connected_component_subgraphs(U) + + UU = nx.Graph() + # do quick isomorphic-like check, not a true isomorphism checker + nlist = [] # list of nonisomorphic graphs + for G in C: + # check against all nonisomorphic graphs so far + if not iso(G, nlist): + nlist.append(G) + UU = nx.disjoint_union(UU, G) # union the nonisomorphic graphs + return UU + +def iso(G1, glist): + """Quick and dirty nonisomorphism checker used to check isomorphisms.""" + for G2 in glist: + if isomorphic(G1, G2): + return True + return False + + +if __name__ == '__main__': + G=atlas6() + + print("graph has %d nodes with %d edges"\ + %(nx.number_of_nodes(G), nx.number_of_edges(G))) + print(nx.number_connected_components(G), "connected components") + + try: + import pygraphviz + from networkx.drawing.nx_agraph import graphviz_layout + except ImportError: + try: + import pydotplus + from networkx.drawing.nx_pydot import graphviz_layout + except ImportError: + raise ImportError("This example needs Graphviz and either " + "PyGraphviz or PyDotPlus") + + import matplotlib.pyplot as plt + plt.figure(1, figsize=(8, 8)) + # layout graphs with positions using graphviz neato + pos = graphviz_layout(G, prog="neato") + # color nodes the same in each connected subgraph + C = nx.connected_component_subgraphs(G) + for g in C: + c = [random.random()] * nx.number_of_nodes(g) # random color... + nx.draw(g, + pos, + node_size=40, + node_color=c, + vmin=0.0, + vmax=1.0, + with_labels=False + ) + plt.savefig("atlas.png", dpi=75) diff --git a/share/doc/networkx-1.11/examples/drawing/chess_masters.py b/share/doc/networkx-1.11/examples/drawing/chess_masters.py new file mode 100644 index 000000000..76e8ae6f7 --- /dev/null +++ b/share/doc/networkx-1.11/examples/drawing/chess_masters.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python + +""" +An example of the MultiDiGraph clas + +The function chess_pgn_graph reads a collection of chess +matches stored in the specified PGN file +(PGN ="Portable Game Notation") +Here the (compressed) default file --- + chess_masters_WCC.pgn.bz2 --- +contains all 685 World Chess Championship matches +from 1886 - 1985. +(data from http://chessproblem.my-free-games.com/chess/games/Download-PGN.php) + +The chess_pgn_graph() function returns a MultiDiGraph +with multiple edges. Each node is +the last name of a chess master. Each edge is directed +from white to black and contains selected game info. + +The key statement in chess_pgn_graph below is + G.add_edge(white, black, game_info) +where game_info is a dict describing each game. + +""" +# Copyright (C) 2006-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +import networkx as nx + +# tag names specifying what game info should be +# stored in the dict on each digraph edge +game_details=["Event", + "Date", + "Result", + "ECO", + "Site"] + +def chess_pgn_graph(pgn_file="chess_masters_WCC.pgn.bz2"): + """Read chess games in pgn format in pgn_file. + + Filenames ending in .gz or .bz2 will be uncompressed. + + Return the MultiDiGraph of players connected by a chess game. + Edges contain game data in a dict. + + """ + import bz2 + G=nx.MultiDiGraph() + game={} + datafile = bz2.BZ2File(pgn_file) + lines = (line.decode().rstrip('\r\n') for line in datafile) + for line in lines: + if line.startswith('['): + tag,value=line[1:-1].split(' ',1) + game[str(tag)]=value.strip('"') + else: + # empty line after tag set indicates + # we finished reading game info + if game: + white=game.pop('White') + black=game.pop('Black') + G.add_edge(white, black, **game) + game={} + return G + + +if __name__ == '__main__': + G=chess_pgn_graph() + + ngames=G.number_of_edges() + nplayers=G.number_of_nodes() + + print("Loaded %d chess games between %d players\n"\ + % (ngames,nplayers)) + + # identify connected components + # of the undirected version + Gcc=list(nx.connected_component_subgraphs(G.to_undirected())) + if len(Gcc)>1: + print("Note the disconnected component consisting of:") + print(Gcc[1].nodes()) + + # find all games with B97 opening (as described in ECO) + openings=set([game_info['ECO'] + for (white,black,game_info) in G.edges(data=True)]) + print("\nFrom a total of %d different openings,"%len(openings)) + print('the following games used the Sicilian opening') + print('with the Najdorff 7...Qb6 "Poisoned Pawn" variation.\n') + + for (white,black,game_info) in G.edges(data=True): + if game_info['ECO']=='B97': + print(white,"vs",black) + for k,v in game_info.items(): + print(" ",k,": ",v) + print("\n") + + + try: + import matplotlib.pyplot as plt + except ImportError: + import sys + print("Matplotlib needed for drawing. Skipping") + sys.exit(0) + + # make new undirected graph H without multi-edges + H=nx.Graph(G) + + # edge width is proportional number of games played + edgewidth=[] + for (u,v,d) in H.edges(data=True): + edgewidth.append(len(G.get_edge_data(u,v))) + + # node size is proportional to number of games won + wins=dict.fromkeys(G.nodes(),0.0) + for (u,v,d) in G.edges(data=True): + r=d['Result'].split('-') + if r[0]=='1': + wins[u]+=1.0 + elif r[0]=='1/2': + wins[u]+=0.5 + wins[v]+=0.5 + else: + wins[v]+=1.0 + try: + pos=nx.nx_agraph.graphviz_layout(H) + except: + pos=nx.spring_layout(H,iterations=20) + + plt.rcParams['text.usetex'] = False + plt.figure(figsize=(8,8)) + nx.draw_networkx_edges(H,pos,alpha=0.3,width=edgewidth, edge_color='m') + nodesize=[wins[v]*50 for v in H] + nx.draw_networkx_nodes(H,pos,node_size=nodesize,node_color='w',alpha=0.4) + nx.draw_networkx_edges(H,pos,alpha=0.4,node_size=0,width=1,edge_color='k') + nx.draw_networkx_labels(H,pos,fontsize=14) + font = {'fontname' : 'Helvetica', + 'color' : 'k', + 'fontweight' : 'bold', + 'fontsize' : 14} + plt.title("World Chess Championship Games: 1886 - 1985", font) + + # change font and write text (using data coordinates) + font = {'fontname' : 'Helvetica', + 'color' : 'r', + 'fontweight' : 'bold', + 'fontsize' : 14} + + plt.text(0.5, 0.97, "edge width = # games played", + horizontalalignment='center', + transform=plt.gca().transAxes) + plt.text(0.5, 0.94, "node size = # games won", + horizontalalignment='center', + transform=plt.gca().transAxes) + + plt.axis('off') + plt.savefig("chess_masters.png",dpi=75) + print("Wrote chess_masters.png") + plt.show() # display diff --git a/share/doc/networkx-1.11/examples/drawing/chess_masters_WCC.pgn.bz2 b/share/doc/networkx-1.11/examples/drawing/chess_masters_WCC.pgn.bz2 new file mode 100644 index 000000000..3761ce528 Binary files /dev/null and b/share/doc/networkx-1.11/examples/drawing/chess_masters_WCC.pgn.bz2 differ diff --git a/share/doc/networkx-1.11/examples/drawing/circular_tree.py b/share/doc/networkx-1.11/examples/drawing/circular_tree.py new file mode 100644 index 000000000..77216bd76 --- /dev/null +++ b/share/doc/networkx-1.11/examples/drawing/circular_tree.py @@ -0,0 +1,22 @@ +import networkx as nx +import matplotlib.pyplot as plt + +try: + import pygraphviz + from networkx.drawing.nx_agraph import graphviz_layout +except ImportError: + try: + import pydotplus + from networkx.drawing.nx_pydot import graphviz_layout + except ImportError: + raise ImportError("This example needs Graphviz and either " + "PyGraphviz or PyDotPlus") + +G = nx.balanced_tree(3, 5) +pos = graphviz_layout(G, prog='twopi', args='') +plt.figure(figsize=(8, 8)) +nx.draw(G, pos, node_size=20, alpha=0.5, node_color="blue", with_labels=False) +plt.axis('equal') +plt.savefig('circular_tree.png') +plt.show() + diff --git a/share/doc/networkx-1.11/examples/drawing/degree_histogram.py b/share/doc/networkx-1.11/examples/drawing/degree_histogram.py new file mode 100644 index 000000000..a6dd8742c --- /dev/null +++ b/share/doc/networkx-1.11/examples/drawing/degree_histogram.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python +""" +Random graph from given degree sequence. +Draw degree rank plot and graph with matplotlib. +""" +# Author: Aric Hagberg +import matplotlib.pyplot as plt +import networkx as nx + +G = nx.gnp_random_graph(100,0.02) + +degree_sequence=sorted(nx.degree(G).values(),reverse=True) # degree sequence +#print "Degree sequence", degree_sequence +dmax=max(degree_sequence) + +plt.loglog(degree_sequence,'b-',marker='o') +plt.title("Degree rank plot") +plt.ylabel("degree") +plt.xlabel("rank") + +# draw graph in inset +plt.axes([0.45,0.45,0.45,0.45]) +Gcc=sorted(nx.connected_component_subgraphs(G), key = len, reverse=True)[0] +pos=nx.spring_layout(Gcc) +plt.axis('off') +nx.draw_networkx_nodes(Gcc,pos,node_size=20) +nx.draw_networkx_edges(Gcc,pos,alpha=0.4) + +plt.savefig("degree_histogram.png") +plt.show() + diff --git a/share/doc/networkx-1.11/examples/drawing/edge_colormap.py b/share/doc/networkx-1.11/examples/drawing/edge_colormap.py new file mode 100644 index 000000000..a2aa7a3a4 --- /dev/null +++ b/share/doc/networkx-1.11/examples/drawing/edge_colormap.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python +""" +Draw a graph with matplotlib, color edges. +You must have matplotlib>=87.7 for this to work. +""" +# Author: Aric Hagberg (hagberg@lanl.gov) +try: + import matplotlib.pyplot as plt +except: + raise + +import networkx as nx + +G=nx.star_graph(20) +pos=nx.spring_layout(G) +colors=range(20) +nx.draw(G,pos,node_color='#A0CBE2',edge_color=colors,width=4,edge_cmap=plt.cm.Blues,with_labels=False) +plt.savefig("edge_colormap.png") # save as png +plt.show() # display diff --git a/share/doc/networkx-1.11/examples/drawing/ego_graph.py b/share/doc/networkx-1.11/examples/drawing/ego_graph.py new file mode 100644 index 000000000..e1092738a --- /dev/null +++ b/share/doc/networkx-1.11/examples/drawing/ego_graph.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Example using the NetworkX ego_graph() function to return the main egonet of +the largest hub in a Barabási-Albert network. +""" +# Author: Drew Conway (drew.conway@nyu.edu) + +from operator import itemgetter +import networkx as nx +import matplotlib.pyplot as plt + + +if __name__ == '__main__': + # Create a BA model graph + n=1000 + m=2 + G=nx.generators.barabasi_albert_graph(n,m) + # find node with largest degree + node_and_degree=G.degree() + (largest_hub,degree)=sorted(node_and_degree.items(),key=itemgetter(1))[-1] + # Create ego graph of main hub + hub_ego=nx.ego_graph(G,largest_hub) + # Draw graph + pos=nx.spring_layout(hub_ego) + nx.draw(hub_ego,pos,node_color='b',node_size=50,with_labels=False) + # Draw ego as large and red + nx.draw_networkx_nodes(hub_ego,pos,nodelist=[largest_hub],node_size=300,node_color='r') + plt.savefig('ego_graph.png') + plt.show() diff --git a/share/doc/networkx-1.11/examples/drawing/four_grids.py b/share/doc/networkx-1.11/examples/drawing/four_grids.py new file mode 100644 index 000000000..112019170 --- /dev/null +++ b/share/doc/networkx-1.11/examples/drawing/four_grids.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python +""" +Draw a graph with matplotlib. +You must have matplotlib for this to work. +""" +# Author: Aric Hagberg (hagberg@lanl.gov) + +# Copyright (C) 2004-2016 +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +try: + import matplotlib.pyplot as plt +except: + raise + +import networkx as nx + +G=nx.grid_2d_graph(4,4) #4x4 grid + +pos=nx.spring_layout(G,iterations=100) + +plt.subplot(221) +nx.draw(G,pos,font_size=8) + +plt.subplot(222) +nx.draw(G,pos,node_color='k',node_size=0,with_labels=False) + +plt.subplot(223) +nx.draw(G,pos,node_color='g',node_size=250,with_labels=False,width=6) + +plt.subplot(224) +H=G.to_directed() +nx.draw(H,pos,node_color='b',node_size=20,with_labels=False) + +plt.savefig("four_grids.png") +plt.show() diff --git a/share/doc/networkx-1.11/examples/drawing/giant_component.py b/share/doc/networkx-1.11/examples/drawing/giant_component.py new file mode 100644 index 000000000..9ec3266c1 --- /dev/null +++ b/share/doc/networkx-1.11/examples/drawing/giant_component.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python +""" +This example illustrates the sudden appearance of a +giant connected component in a binomial random graph. + +Requires pygraphviz and matplotlib to draw. + +""" +# Copyright (C) 2006-2016 +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +try: + import matplotlib.pyplot as plt +except: + raise + +import networkx as nx +import math + +try: + import pygraphviz + from networkx.drawing.nx_agraph import graphviz_layout + layout = graphviz_layout +except ImportError: + try: + import pydotplus + from networkx.drawing.nx_pydot import graphviz_layout + layout = graphviz_layout + except ImportError: + print("PyGraphviz and PyDotPlus not found;\n" + "drawing with spring layout;\n" + "will be slow.") + layout = nx.spring_layout + + +n=150 # 150 nodes +# p value at which giant component (of size log(n) nodes) is expected +p_giant=1.0/(n-1) +# p value at which graph is expected to become completely connected +p_conn=math.log(n)/float(n) + +# the following range of p values should be close to the threshold +pvals=[0.003, 0.006, 0.008, 0.015] + +region=220 # for pylab 2x2 subplot layout +plt.subplots_adjust(left=0,right=1,bottom=0,top=0.95,wspace=0.01,hspace=0.01) +for p in pvals: + G=nx.binomial_graph(n,p) + pos=layout(G) + region+=1 + plt.subplot(region) + plt.title("p = %6.3f"%(p)) + nx.draw(G,pos, + with_labels=False, + node_size=10 + ) + # identify largest connected component + Gcc=sorted(nx.connected_component_subgraphs(G), key = len, reverse=True) + G0=Gcc[0] + nx.draw_networkx_edges(G0,pos, + with_labels=False, + edge_color='r', + width=6.0 + ) + # show other connected components + for Gi in Gcc[1:]: + if len(Gi)>1: + nx.draw_networkx_edges(Gi,pos, + with_labels=False, + edge_color='r', + alpha=0.3, + width=5.0 + ) +plt.savefig("giant_component.png") +plt.show() # display diff --git a/share/doc/networkx-1.11/examples/drawing/house_with_colors.py b/share/doc/networkx-1.11/examples/drawing/house_with_colors.py new file mode 100644 index 000000000..78aa15219 --- /dev/null +++ b/share/doc/networkx-1.11/examples/drawing/house_with_colors.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python +""" +Draw a graph with matplotlib. +You must have matplotlib for this to work. +""" +# Author: Aric Hagberg (hagberg@lanl.gov) +try: + import matplotlib.pyplot as plt +except: + raise + +import networkx as nx + +G=nx.house_graph() +# explicitly set positions +pos={0:(0,0), + 1:(1,0), + 2:(0,1), + 3:(1,1), + 4:(0.5,2.0)} + +nx.draw_networkx_nodes(G,pos,node_size=2000,nodelist=[4]) +nx.draw_networkx_nodes(G,pos,node_size=3000,nodelist=[0,1,2,3],node_color='b') +nx.draw_networkx_edges(G,pos,alpha=0.5,width=6) +plt.axis('off') +plt.savefig("house_with_colors.png") # save as png +plt.show() # display diff --git a/share/doc/networkx-1.11/examples/drawing/knuth_miles.py b/share/doc/networkx-1.11/examples/drawing/knuth_miles.py new file mode 100644 index 000000000..0ba9fd767 --- /dev/null +++ b/share/doc/networkx-1.11/examples/drawing/knuth_miles.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python +""" +An example using networkx.Graph(). + +miles_graph() returns an undirected graph over the 128 US cities from +the datafile miles_dat.txt. The cities each have location and population +data. The edges are labeled with the distance betwen the two cities. + +This example is described in Section 1.1 in Knuth's book [1,2]. + +References. +----------- + +[1] Donald E. Knuth, + "The Stanford GraphBase: A Platform for Combinatorial Computing", + ACM Press, New York, 1993. +[2] http://www-cs-faculty.stanford.edu/~knuth/sgb.html + + +""" +# Author: Aric Hagberg (hagberg@lanl.gov) + +# Copyright (C) 2004-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +import networkx as nx + + +def miles_graph(): + """ Return the cites example graph in miles_dat.txt + from the Stanford GraphBase. + """ + # open file miles_dat.txt.gz (or miles_dat.txt) + import gzip + fh = gzip.open('knuth_miles.txt.gz','r') + + G=nx.Graph() + G.position={} + G.population={} + + cities=[] + for line in fh.readlines(): + line = line.decode() + if line.startswith("*"): # skip comments + continue + + numfind=re.compile("^\d+") + + if numfind.match(line): # this line is distances + dist=line.split() + for d in dist: + G.add_edge(city,cities[i],weight=int(d)) + i=i+1 + else: # this line is a city, position, population + i=1 + (city,coordpop)=line.split("[") + cities.insert(0,city) + (coord,pop)=coordpop.split("]") + (y,x)=coord.split(",") + + G.add_node(city) + # assign position - flip x axis for matplotlib, shift origin + G.position[city]=(-int(x)+7500,int(y)-3000) + G.population[city]=float(pop)/1000.0 + return G + +if __name__ == '__main__': + import networkx as nx + import re + import sys + + G=miles_graph() + + print("Loaded miles_dat.txt containing 128 cities.") + print("digraph has %d nodes with %d edges"\ + %(nx.number_of_nodes(G),nx.number_of_edges(G))) + + + # make new graph of cites, edge if less then 300 miles between them + H=nx.Graph() + for v in G: + H.add_node(v) + for (u,v,d) in G.edges(data=True): + if d['weight'] < 300: + H.add_edge(u,v) + + # draw with matplotlib/pylab + + try: + import matplotlib.pyplot as plt + plt.figure(figsize=(8,8)) + # with nodes colored by degree sized by population + node_color=[float(H.degree(v)) for v in H] + nx.draw(H,G.position, + node_size=[G.population[v] for v in H], + node_color=node_color, + with_labels=False) + + # scale the axes equally + plt.xlim(-5000,500) + plt.ylim(-2000,3500) + + plt.savefig("knuth_miles.png") + except: + pass + + + diff --git a/share/doc/networkx-1.11/examples/drawing/knuth_miles.txt.gz b/share/doc/networkx-1.11/examples/drawing/knuth_miles.txt.gz new file mode 100644 index 000000000..62b7f95fb Binary files /dev/null and b/share/doc/networkx-1.11/examples/drawing/knuth_miles.txt.gz differ diff --git a/share/doc/networkx-1.11/examples/drawing/labels_and_colors.py b/share/doc/networkx-1.11/examples/drawing/labels_and_colors.py new file mode 100644 index 000000000..cf06a95a7 --- /dev/null +++ b/share/doc/networkx-1.11/examples/drawing/labels_and_colors.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +""" +Draw a graph with matplotlib, color by degree. + +You must have matplotlib for this to work. +""" +# Author: Aric Hagberg (hagberg@lanl.gov) +import matplotlib.pyplot as plt + +import networkx as nx + +G=nx.cubical_graph() +pos=nx.spring_layout(G) # positions for all nodes + +# nodes +nx.draw_networkx_nodes(G,pos, + nodelist=[0,1,2,3], + node_color='r', + node_size=500, + alpha=0.8) +nx.draw_networkx_nodes(G,pos, + nodelist=[4,5,6,7], + node_color='b', + node_size=500, + alpha=0.8) + +# edges +nx.draw_networkx_edges(G,pos,width=1.0,alpha=0.5) +nx.draw_networkx_edges(G,pos, + edgelist=[(0,1),(1,2),(2,3),(3,0)], + width=8,alpha=0.5,edge_color='r') +nx.draw_networkx_edges(G,pos, + edgelist=[(4,5),(5,6),(6,7),(7,4)], + width=8,alpha=0.5,edge_color='b') + + +# some math labels +labels={} +labels[0]=r'$a$' +labels[1]=r'$b$' +labels[2]=r'$c$' +labels[3]=r'$d$' +labels[4]=r'$\alpha$' +labels[5]=r'$\beta$' +labels[6]=r'$\gamma$' +labels[7]=r'$\delta$' +nx.draw_networkx_labels(G,pos,labels,font_size=16) + +plt.axis('off') +plt.savefig("labels_and_colors.png") # save as png +plt.show() # display diff --git a/share/doc/networkx-1.11/examples/drawing/lanl_routes.edgelist b/share/doc/networkx-1.11/examples/drawing/lanl_routes.edgelist new file mode 100644 index 000000000..db831813c --- /dev/null +++ b/share/doc/networkx-1.11/examples/drawing/lanl_routes.edgelist @@ -0,0 +1,1363 @@ +1 0 9 +2 3 173 +3 4 167 +4 5 165 +5 102 96 +5 6 96.43 +6 7 96.62 +7 8 86 +8 9 87 +9 10 82 +10 11 79 +11 12 74 +12 13 41 +13 1 3 +14 15 187.46 +15 16 187 +16 17 187.04 +17 18 186.62 +18 19 185.88 +19 20 185.4 +20 21 184.02 +21 22 184.38 +22 23 183.97 +23 24 93.01 +24 25 88.59 +25 26 86.26 +26 27 88.04 +27 28 77.12 +28 29 74 +29 119 70.1 +29 30 72 +30 31 73 +31 32 89.41 +32 13 6.63 +33 34 212.25 +34 35 211.46 +35 36 209.04 +36 37 211.57 +37 38 206.57 +38 39 105.04 +39 40 77.21 +40 41 86.5 +41 42 0 +42 1 16 +43 44 112.67 +44 45 111.94 +45 46 111.77 +46 47 111.83 +47 48 111.27 +48 49 111.76 +49 50 109.32 +50 51 110.67 +51 52 80.63 +52 53 80.78 +53 41 30 +54 55 164.62 +55 56 164.13 +56 57 164.24 +57 58 156.43 +58 59 88.92 +59 60 88.6 +60 61 86.53 +61 62 85.96 +62 10 86.8 +63 64 221.31 +64 65 220.88 +65 66 220.84 +66 67 220.27 +67 68 215.19 +68 69 209 +69 70 213.81 +70 71 208.04 +71 72 196.45 +72 73 197.05 +73 74 163.85 +74 75 186.4 +75 76 180.35 +76 77 103.92 +77 78 98.6 +78 79 98.83 +79 80 96.09 +80 10 309 +81 82 174.3 +82 83 173.57 +83 84 173.9 +84 85 173.66 +85 86 173.75 +86 87 92.62 +87 88 73.93 +88 32 91.44 +89 90 158 +90 91 155 +91 92 158 +91 97 157.76 +92 93 86 +93 94 325.32 +94 32 5.53000000000003 +95 96 158.17 +96 91 157.6 +97 98 84.74 +98 94 84.87 +99 100 282 +100 101 279 +101 5 167 +102 7 87 +103 104 201.16 +104 105 200.5 +105 106 200.5 +106 39 121.02 +107 108 148.27 +108 109 147.59 +109 110 147.87 +110 111 147.88 +111 112 147.82 +112 113 140.19 +113 114 147.54 +114 115 64.02 +115 116 67.75 +116 117 70.55 +117 118 98.3 +118 119 80.4 +119 31 81.28 +120 121 161.26 +121 122 160.84 +122 123 160.86 +123 58 160.84 +124 125 238.34 +125 126 237.79 +126 127 237.08 +127 128 234.34 +128 129 236.72 +129 130 237.18 +130 131 119.25 +131 132 111.15 +132 133 30.93 +133 134 50 +134 135 49 +135 42 43 +136 137 148.68 +137 138 147.78 +138 139 147.74 +139 140 148.29 +140 141 136.56 +141 142 145.37 +142 143 144.93 +143 144 141.78 +143 160 144.92 +144 145 141.65 +145 146 72.32 +146 147 68.81 +147 148 73.15 +148 149 93.13 +149 150 82.38 +150 151 86.03 +151 152 73.3 +152 153 80.2 +153 154 83.08 +154 32 0 +155 156 152.24 +156 157 151.47 +157 158 150.17 +158 159 151.59 +159 140 145.38 +160 145 143.86 +161 162 197.3 +162 163 196.83 +163 164 196.73 +164 165 196.8 +165 166 131.22 +165 383 128.8 +166 167 36 +167 168 44.08 +168 42 11.49 +169 170 178 +170 171 174 +171 172 166 +172 5 166 +173 174 213.7 +174 175 213.01 +175 176 213.03 +176 177 213.38 +177 178 202.81 +178 179 204.73 +179 180 203 +180 38 202.46 +181 182 44 +182 183 41 +183 184 43 +184 185 44 +185 186 42 +186 187 33 +187 188 32 +188 189 39.44 +189 42 36.28 +190 191 258.85 +191 192 257.61 +192 193 258.1 +193 194 87.26 +194 195 88.26 +195 196 85.82 +196 197 18.93 +197 198 32 +198 188 33.68 +199 200 114 +200 201 110 +201 202 114 +202 203 112 +203 204 29 +204 205 36 +205 206 37 +206 42 27 +207 208 562.86 +208 209 561.89 +209 210 561.94 +210 211 9.50999999999999 +211 212 14.12 +212 213 6.81000000000006 +213 214 1.72000000000003 +214 215 11.83 +215 117 85.94 +216 217 114.12 +217 218 112.57 +218 219 112.04 +219 220 112.01 +220 188 88.74 +221 222 211 +222 223 208 +223 224 211 +224 225 103 +225 226 104.75 +226 227 103 +226 687 105 +227 98 73 +228 229 67.83 +229 230 66.68 +230 231 67.39 +231 232 67.36 +232 233 66.39 +233 234 32.11 +234 188 32.19 +235 236 194 +236 237 191 +237 172 166 +238 239 191.94 +239 240 190.85 +240 241 191.48 +241 242 190.73 +242 243 183.14 +243 244 182.32 +244 245 179.92 +245 246 182.17 +246 97 173.79 +247 248 195.23 +248 249 194.78 +249 250 179.06 +250 251 179.01 +251 252 168.31 +252 57 165.26 +253 254 92.14 +254 255 91.07 +255 256 90.41 +256 257 90.85 +257 258 46.52 +258 259 57.31 +259 260 4.04000000000001 +260 261 19.22 +261 262 8.82000000000001 +262 263 79 +263 41 78 +264 265 102.69 +265 266 102.24 +266 267 101.92 +267 1355 116 +267 268 101.64 +268 269 0 +269 270 80.77 +270 271 89.27 +271 272 115 +272 273 116 +273 274 115 +274 133 50 +275 276 58.9 +276 277 58.19 +277 278 0 +278 279 58.13 +279 280 58.21 +280 281 58.04 +281 282 58.12 +282 283 31.7 +283 284 26.07 +284 285 38.42 +284 574 32.12 +285 286 196 +286 42 127 +287 288 186.74 +288 289 185.88 +289 290 183.24 +290 291 184.06 +291 292 181.22 +292 293 0 +293 294 171.29 +294 295 102.04 +295 296 68.99 +296 30 68.93 +297 298 103.31 +298 299 102.8 +299 300 102.75 +300 301 102.77 +301 302 102.55 +302 270 101.64 +303 304 555.45 +305 306 76.2 +306 307 75.65 +307 308 75.66 +308 309 75.9 +309 310 75.7 +310 311 69.12 +311 312 68.99 +312 32 0 +313 314 170 +314 315 167 +315 316 169 +316 317 169 +317 318 169 +318 319 167 +319 320 167 +320 321 27 +321 198 16 +322 323 178 +323 324 175 +324 325 177 +325 326 125 +326 327 117 +327 328 34 +328 329 34 +329 330 34 +330 331 0 +331 198 33 +332 333 85.6 +333 334 84.88 +334 335 84.69 +335 336 77.26 +336 337 80.75 +337 53 79.65 +338 339 104.12 +339 340 103.35 +340 341 103.55 +341 342 61.24 +342 343 90.09 +343 344 92.58 +344 345 92.92 +345 346 86 +346 9 86 +347 348 106.96 +348 349 106.37 +349 350 75.33 +350 351 90.59 +351 61 66 +352 353 76.11 +353 354 75.34 +354 355 75.16 +355 356 74.84 +356 357 61.66 +357 358 103.06 +358 359 34 +359 168 34 +360 361 122.16 +361 362 121.69 +362 166 121.31 +363 364 63.84 +364 365 63.35 +365 366 63.5 +366 367 48.79 +367 368 47.81 +368 369 38.89 +369 370 38.77 +370 371 37.31 +371 358 36.43 +372 373 210 +373 374 206 +374 375 187 +375 376 343 +376 377 193 +377 378 33 +378 379 86 +378 866 33.57 +378 958 33 +379 285 196 +380 381 51.17 +381 382 50.66 +382 383 27.75 +383 359 32 +384 385 44.03 +385 386 43.56 +386 387 43.19 +387 358 40.03 +388 389 79.01 +389 390 0 +390 358 78.04 +391 392 186.71 +392 393 185.92 +393 394 184.8 +394 395 171.14 +395 396 176.31 +396 53 82 +397 398 133.54 +398 399 133.05 +399 400 133.09 +400 383 132.6 +401 402 101.49 +402 403 101 +403 358 100.55 +404 405 199.34 +405 406 198.85 +406 407 198.94 +407 408 199.01 +408 409 198.79 +409 410 53.72 +410 411 33.45 +411 412 38.86 +412 413 36.46 +413 414 38.68 +414 205 31.92 +415 416 35.64 +416 417 34.93 +417 418 34.91 +418 414 34.93 +419 420 119.9 +420 421 119.37 +421 422 119.02 +422 423 118.89 +423 215 111.28 +424 425 57.09 +425 426 56.3 +426 427 54.33 +427 428 55.68 +428 429 55.89 +429 430 52.57 +430 283 39.54 +431 432 91.65 +432 433 90.74 +433 434 91.05 +434 435 90.27 +435 436 87.89 +436 437 83.17 +437 438 76.52 +438 439 67.26 +440 441 32.05 +441 42 32.57 +442 443 103.73 +443 444 100.75 +444 357 103.22 +445 446 226.87 +446 447 226.41 +447 448 226.52 +448 166 225.66 +449 450 107.54 +450 451 107.08 +451 383 106.74 +452 453 190.21 +453 454 186.79 +454 455 188.77 +455 456 188.36 +456 457 41.12 +457 458 39.38 +458 459 39.48 +459 460 37.96 +460 286 32 +461 462 32.81 +462 359 32.31 +463 464 106.75 +464 465 106.27 +465 358 105.93 +466 467 34.12 +467 468 15.78 +468 469 33.79 +469 470 33.05 +470 471 53.35 +471 188 17.55 +472 473 90.41 +473 474 89.07 +474 475 90.06 +475 476 89.2 +476 477 88.42 +477 478 85.87 +478 10 0 +479 480 142.27 +480 481 8.90000000000001 +481 482 13.62 +482 483 112.18 +483 29 138.4 +484 485 101.64 +485 486 100.96 +486 487 101.12 +487 488 100.77 +488 489 49.98 +489 117 48.89 +490 491 42.63 +491 492 42.02 +492 493 41.89 +493 494 41.72 +494 460 40.09 +495 496 184.89 +496 497 184.2 +497 498 184.58 +498 499 184.51 +499 500 43.65 +500 501 43.27 +501 502 39.97 +502 286 39.64 +503 504 87.59 +504 505 86.98 +505 506 68.34 +506 507 86.09 +507 79 85.85 +508 509 35.46 +509 510 34.98 +510 511 35.09 +511 512 35.06 +512 203 32.71 +513 514 237.49 +514 515 236.63 +515 516 235.99 +516 517 235.45 +517 119 232.59 +518 519 108.9 +519 520 108.33 +520 521 108.34 +521 522 108.32 +522 523 89.23 +523 524 76.97 +524 525 76.55 +525 32 74.26 +526 527 94.58 +527 528 93.93 +528 529 93.74 +529 530 92.33 +530 531 91.65 +531 532 92.78 +532 533 52.01 +533 119 76 +534 535 278.82 +535 536 277.82 +536 537 277.42 +537 538 277.54 +538 215 269.96 +539 540 61.14 +540 541 59.85 +541 542 60.8 +542 543 60.65 +543 544 56.01 +544 470 33.14 +545 546 111.16 +546 547 109.47 +547 548 110.05 +548 549 108.98 +549 550 108.86 +550 551 47.69 +551 552 47.26 +552 205 55.57 +553 554 85.92 +554 555 83.29 +555 556 85.58 +556 557 85.45 +557 558 79.84 +558 559 76.12 +559 478 67.6 +560 561 315.3 +561 562 314.68 +562 563 314.69 +563 564 314.81 +564 565 291.4 +565 596 287.51 +566 567 281.41 +567 568 117.21 +567 597 134.64 +568 569 121.28 +569 570 138.98 +570 571 130.29 +571 572 85.41 +572 573 85.15 +573 283 35.07 +574 286 31.89 +575 576 107.08 +576 577 106.44 +577 578 96 +578 1347 96 +578 579 106.29 +579 580 106.33 +580 204 21 +581 582 182.8 +582 583 180.62 +583 584 181.1 +584 585 181 +585 586 176.62 +586 587 167.92 +587 588 33.47 +588 589 34.93 +589 580 33.76 +590 591 293.64 +591 592 293.08 +592 593 293.16 +594 595 292.45 +595 564 291.9 +596 566 287.81 +597 569 129.61 +598 599 108.64 +599 600 103.72 +600 203 108.12 +601 602 188.26 +602 603 186.83 +603 101 150.99 +604 605 172.09 +605 606 171.68 +606 607 171.75 +607 57 165.06 +608 609 108.26 +609 610 107.62 +610 611 107.17 +611 612 107.3 +612 613 94.52 +614 615 179.19 +615 616 178.63 +616 617 178.73 +617 618 177.65 +618 619 93.43 +619 312 87.42 +620 621 180.61 +621 622 179.95 +622 623 180.24 +623 624 180.2 +624 625 180.07 +625 626 182.28 +626 627 176.33 +627 628 99.93 +628 629 96.99 +629 630 96.68 +630 396 76.07 +631 632 156.82 +632 633 156.12 +633 634 155.87 +634 635 156 +635 636 155.69 +636 637 155.46 +637 638 169.15 +638 639 168.91 +639 640 168.78 +640 28 47.56 +641 642 199.77 +642 643 196.16 +643 644 199.4 +644 645 197.12 +645 646 174.59 +646 71 197.29 +647 648 234 +648 649 230 +649 650 233 +650 651 102 +651 652 98 +652 197 101 +653 654 187 +654 655 184 +655 101 167 +656 657 203.5 +657 658 202.75 +658 659 202.65 +659 660 202.31 +660 661 202.32 +661 662 202.19 +662 663 181.05 +663 664 93.39 +664 665 86.23 +665 148 93.14 +666 667 204.1 +667 668 203.08 +668 669 203.14 +669 617 177.3 +670 671 115.11 +671 672 114.18 +672 673 114.39 +673 674 110.33 +674 675 107.11 +676 677 262 +677 678 261.21 +678 679 256.73 +679 680 258.46 +680 681 258.25 +681 637 257.7 +682 683 234.24 +683 684 233.35 +684 685 232.7 +685 686 29.28 +686 225 103.48 +687 93 321.3 +688 689 89.06 +689 690 88.36 +691 692 88.72 +692 693 88.5 +693 285 88.12 +694 695 637.37 +695 696 636.56 +696 697 634.76 +697 698 628.88 +698 699 615.38 +699 700 102.91 +700 701 85.77 +701 702 78.1799999999999 +702 703 96.09 +703 165 52.89 +704 705 98.12 +705 706 97.48 +706 707 95.44 +707 708 97.47 +708 709 97.42 +709 167 43.83 +710 711 237.43 +711 712 236.85 +712 713 236.53 +713 714 236.33 +714 715 208.15 +715 716 207.98 +716 38 108.65 +716 717 107.34 +717 39 111.29 +718 719 87 +719 720 82 +720 721 86 +721 722 87 +722 723 86 +723 724 79 +724 725 32 +725 396 83 +726 727 196.18 +727 728 195.25 +728 729 194.91 +729 730 195.83 +730 731 110.77 +731 732 111.26 +732 733 111.4 +733 734 111.31 +734 735 111.15 +735 736 90.31 +736 737 93.77 +737 215 96.41 +738 739 456.99 +739 740 454.87 +740 741 455.13 +741 742 454.46 +742 743 422.76 +743 744 327.98 +744 687 326.23 +745 746 241.98 +746 747 241.31 +747 748 241.24 +748 749 236 +749 750 231.22 +750 751 91.12 +751 752 97.31 +752 753 103.3 +753 754 31.03 +754 198 0 +755 756 219.66 +756 757 218.95 +757 758 219.13 +758 759 219.11 +759 760 218.51 +760 761 218.5 +761 762 200.71 +762 763 199.49 +763 203 105.48 +764 765 186.62 +765 766 185.87 +766 5 127.52 +767 768 88 +768 102 85 +769 770 199.66 +770 771 199.14 +771 772 199.05 +772 773 196.95 +773 774 194.12 +774 775 194 +775 776 190.3 +776 777 190.08 +777 625 187.75 +778 779 203.98 +779 780 203.14 +780 781 202.48 +781 782 182.54 +782 783 177.2 +783 626 175.98 +784 785 230.98 +785 786 230.13 +786 787 229.17 +787 788 228.7 +788 789 222.24 +789 790 208.82 +790 791 96.82 +791 628 96.76 +792 793 107 +793 794 105 +794 795 106 +795 796 107 +796 797 106 +797 798 106 +798 799 91 +799 345 91 +800 801 343 +801 375 340 +802 803 191 +803 804 188 +804 805 190 +805 806 191 +806 807 149 +807 808 149 +808 809 146 +809 810 11 +810 811 13 +811 812 33.77 +812 42 16.29 +813 814 201.7 +814 815 200.68 +815 816 199.52 +816 817 199.61 +817 818 199.6 +818 819 45.02 +819 820 44.94 +820 821 26.66 +821 285 43.1 +822 823 156.08 +823 824 131.23 +824 825 149.04 +825 826 151.23 +826 827 142.62 +827 828 111.31 +827 856 109.19 +828 829 110.5 +829 295 110.86 +830 831 83.15 +831 832 82.49 +832 833 80.44 +833 834 80.99 +834 40 81.66 +835 836 126.83 +836 837 125.73 +837 838 125.54 +838 839 118.42 +839 840 110.85 +840 841 111.09 +841 842 81.99 +842 358 80.97 +843 844 619.19 +844 845 618.53 +845 846 106.9 +846 847 105.36 +847 848 65.2 +848 849 82.97 +849 850 103.91 +850 851 106.54 +851 829 105.35 +852 853 161.36 +853 854 160.48 +854 855 153.31 +855 826 145.92 +856 857 111.26 +857 858 111.27 +858 533 72 +859 860 146.09 +860 861 145.5 +861 827 144.82 +862 863 75.24 +863 864 74.61 +864 865 34.1 +865 378 197 +866 285 33.46 +867 868 138 +868 869 135 +869 166 137 +870 871 526.33 +871 872 524.67 +872 873 171.42 +873 874 167.51 +874 875 174.09 +875 876 98.02 +876 877 100.53 +877 878 104.75 +878 879 98.28 +879 880 103.86 +880 117 0 +881 882 406.4 +882 883 405.18 +883 884 404.32 +884 885 395.55 +885 886 38.38 +886 887 39.79 +887 574 36.72 +888 889 196.54 +889 890 195.66 +890 891 195.5 +891 892 34.95 +892 893 34.39 +893 188 35.13 +894 895 98 +895 896 95 +896 897 98 +897 383 98 +898 899 200.41 +899 900 199.7 +900 901 199.66 +901 902 199.24 +902 903 199.17 +903 165 194.72 +904 905 240.47 +905 906 239.63 +906 907 240.14 +907 908 239.85 +908 909 239.93 +909 910 239.8 +910 911 153.73 +911 912 139.02 +912 913 25.99 +913 914 25.8 +914 640 30.59 +915 916 57.63 +916 917 56.93 +917 918 56.9 +918 919 56.61 +919 920 56.6 +920 921 56.31 +921 922 52.48 +922 923 49.64 +923 924 37 +925 926 698.1 +926 927 696.29 +927 928 697.35 +928 929 696.84 +929 930 104.07 +930 931 112.53 +931 932 116.56 +932 933 113.51 +933 42 72.73 +934 935 108 +935 936 105 +936 937 108 +937 166 108 +938 939 247.1 +939 940 246.42 +940 941 245.86 +941 942 218.76 +942 943 218.87 +943 944 33.42 +944 188 31 +945 946 75 +946 947 72 +947 383 74 +948 949 103 +949 950 95 +950 951 103 +951 952 103 +952 953 98 +953 725 83 +954 955 180 +955 956 177 +956 957 179 +957 377 76 +957 865 146 +958 460 32 +959 960 91 +960 961 87 +961 962 91 +962 963 91 +963 964 90 +964 118 89 +965 966 306 +966 967 303 +967 968 305 +968 969 155 +969 970 303 +970 971 192 +971 972 112 +972 973 112 +973 974 111 +974 975 80 +975 41 79 +976 977 170.09 +977 978 56.57 +978 979 165.74 +979 980 169.19 +980 981 168.92 +981 982 169.16 +982 983 169.1 +983 984 161.78 +984 985 161.68 +985 986 164.96 +986 987 164.63 +987 988 144.05 +988 989 33.96 +989 811 33.93 +990 991 194.72 +991 992 193.9 +992 993 194.2 +993 994 165.1 +994 995 164.38 +995 985 164.86 +996 997 144.93 +997 998 144.35 +998 999 144.48 +999 1000 144.54 +1000 1001 142.77 +1001 987 144.15 +1002 1003 92 +1003 1004 16 +1004 1005 60 +1005 62 91 +1006 1007 103 +1007 1008 100 +1008 1009 103 +1009 1010 96 +1010 1011 60 +1011 80 86 +1012 1013 101 +1013 1014 97 +1014 1015 95 +1015 1016 77 +1016 60 54 +1017 1018 98 +1018 1019 95 +1019 1020 0 +1020 351 19 +1021 1022 380 +1022 1023 254 +1023 1024 370 +1024 1025 372 +1025 1026 379 +1026 80 311 +1027 1028 47 +1028 1029 40 +1029 1030 40 +1030 1031 46 +1031 924 59.42 +1032 1033 39 +1033 1034 36 +1034 1035 38 +1035 552 39 +1036 1037 56 +1037 1038 52 +1038 1039 55 +1039 923 55 +1040 1041 42 +1041 1042 39 +1042 1043 42 +1043 358 41 +1044 1045 104 +1045 1046 101 +1046 1047 103 +1047 1048 102 +1048 1049 102 +1049 858 98 +1050 1051 338 +1051 1052 335 +1052 1053 337 +1053 1054 337 +1054 1055 64 +1055 1056 178 +1056 1057 177 +1057 1058 177 +1058 1059 177 +1059 1060 64 +1060 1061 153 +1061 1062 31 +1062 460 153 +1063 1064 183 +1064 1065 180 +1065 377 33 +1066 1067 255.41 +1067 1068 254.7 +1068 1069 254.31 +1069 1070 218.96 +1070 1071 238.65 +1071 1072 238.41 +1072 1073 237.99 +1073 1074 81.72 +1074 1075 102.28 +1075 188 92.68 +1076 1077 87.02 +1077 1078 86.6 +1078 1079 86.7 +1079 1080 86.71 +1080 1081 86.51 +1081 1082 86.28 +1082 117 72.11 +1083 1084 37 +1084 865 26 +1085 1086 88.34 +1086 1087 86.73 +1087 1088 87.48 +1088 1089 87.6 +1089 1090 86.77 +1090 571 85.58 +1091 1092 82 +1092 1093 78 +1093 1094 80 +1094 1095 79 +1095 1096 78 +1096 1097 77 +1097 1098 79 +1098 262 79 +1099 1100 80.61 +1100 1101 77.63 +1101 40 71.88 +1102 1103 90.9 +1103 1104 90.1 +1104 1105 90.42 +1106 1107 329 +1107 1108 326 +1108 957 301 +1109 1110 157.39 +1110 1111 156.91 +1111 1112 156.99 +1112 1113 32.57 +1113 188 3.44 +1114 1115 33 +1115 1116 29 +1116 1117 33 +1117 1118 32 +1118 1119 32 +1119 135 32 +1120 1121 179 +1121 1122 175 +1122 1123 178 +1123 1124 0 +1124 1125 0 +1126 1127 43.71 +1127 1128 43.16 +1128 1129 41.4 +1129 1130 33.49 +1130 812 31.02 +1131 1132 87.82 +1132 1133 86.88 +1133 1134 85.49 +1134 9 77.69 +1135 1136 98 +1136 1137 102 +1137 1138 98 +1138 1139 100 +1139 1140 41 +1140 1141 95 +1141 1142 91 +1142 41 34 +1143 1144 352.6 +1144 1145 351.82 +1145 1146 351.73 +1146 1147 343.47 +1147 1148 323.5 +1148 1149 172.05 +1149 1150 171.57 +1150 1151 179.87 +1151 1152 154.08 +1152 1153 157.73 +1153 1154 170.23 +1154 42 55.24 +1155 1156 185.3 +1156 1157 184.13 +1157 1158 183.56 +1158 1159 183.14 +1159 1160 42.16 +1160 1161 40.43 +1162 1163 40.61 +1163 1164 32.05 +1164 1165 34.36 +1165 205 31.2 +1166 1167 39 +1167 1168 36 +1168 1169 0 +1169 1170 38 +1170 924 38 +1171 1172 240.93 +1172 1173 240.24 +1173 1174 238.02 +1174 1074 96.87 +1175 1176 107 +1176 1177 104 +1177 1178 104 +1178 1179 104 +1179 1180 102 +1180 1181 84 +1181 1182 84 +1182 28 74 +1183 1184 108.07 +1184 1185 107.53 +1185 1186 106.58 +1186 709 106.38 +1187 1188 119.42 +1188 1189 118.71 +1189 1190 118.15 +1190 1191 117.11 +1191 1192 115.11 +1192 1193 114.82 +1193 1194 104.91 +1194 41 103.99 +1195 1196 37.68 +1196 1197 37.15 +1197 1198 37.19 +1198 1199 33.94 +1199 414 34.17 +1200 1201 118.72 +1201 1202 113.14 +1202 1203 0 +1203 1204 78.09 +1204 1205 117.75 +1205 1206 117.48 +1206 1207 103.57 +1207 1208 116.96 +1208 1209 117.29 +1209 1210 106.13 +1210 10 113.75 +1211 1212 95.92 +1212 1213 95.3 +1213 1214 93.98 +1214 1215 93.98 +1215 1216 93.93 +1216 1217 89.21 +1217 1218 85.06 +1218 1219 65.28 +1219 1220 65.3 +1220 40 63.33 +1221 1222 33 +1222 1223 30 +1223 1224 33 +1224 187 33 +1225 1226 216.31 +1226 1227 215.75 +1227 1228 207.33 +1228 716 201.93 +1229 1230 163.93 +1230 1231 163.51 +1231 1232 163.47 +1232 1233 163.54 +1233 1234 91.76 +1234 59 88.9 +1235 1236 155.59 +1236 1237 154.73 +1237 1238 155.15 +1238 1239 155.18 +1239 1240 155.17 +1240 1241 155.12 +1241 1242 154.86 +1242 1243 75.58 +1243 1244 75.58 +1244 1245 75.6 +1245 117 70.16 +1246 1247 211.11 +1247 1248 210.29 +1248 1249 210.75 +1249 1250 210.68 +1250 1251 210.58 +1251 1252 210.37 +1252 1227 209.84 +1253 1254 86.95 +1254 1255 86.13 +1255 1256 86.29 +1256 1257 85.37 +1257 1258 77.29 +1258 1259 76.3 +1259 215 75.57 +1260 1261 117.66 +1261 1262 109.11 +1262 1263 101.86 +1263 1264 92.95 +1264 215 107.68 +1265 1266 69.35 +1266 1267 68.74 +1267 1268 67.13 +1268 1269 67.59 +1269 1270 66.29 +1270 1031 67.14 +1271 1272 95.06 +1272 1273 94.48 +1273 1274 93.89 +1274 1275 93.92 +1275 1276 76.55 +1276 1277 93.73 +1277 149 87.97 +1278 1279 67 +1279 1280 90 +1280 1281 91 +1281 1282 91 +1282 1283 90 +1283 1284 89 +1284 1285 90 +1285 1286 89 +1286 1287 85 +1287 9 85 +1288 1289 123 +1289 1290 120 +1290 1291 122 +1291 1292 115 +1292 1293 119 +1293 1294 116 +1294 1295 113 +1295 1296 116 +1296 1297 44 +1297 133 29 +1298 1299 109 +1299 1300 106 +1300 1301 103 +1301 1302 103 +1302 1303 103 +1303 1304 94 +1304 1305 95 +1305 1306 90 +1306 1307 84 +1307 1308 84 +1308 1142 83 +1309 1310 215 +1310 1311 212 +1311 1312 214 +1312 1313 212 +1313 1314 213 +1313 1331 245.24 +1314 188 37.52 +1315 1316 227 +1316 1317 224 +1317 1318 226 +1318 1319 226 +1319 944 45 +1320 1321 219.19 +1321 1322 218.4 +1322 1323 218.88 +1323 1324 218.55 +1324 1325 213.7 +1325 1314 214.5 +1326 1327 248.5 +1327 1328 247.98 +1328 1329 248.15 +1329 1330 247.15 +1330 1313 245.15 +1331 188 64.76 +1332 1333 140 +1333 1334 137 +1334 1335 139 +1335 1336 139 +1336 1337 139 +1337 1338 138 +1338 1339 70 +1339 1340 119 +1340 1341 121 +1341 1342 121 +1342 274 107 +1343 1344 97 +1344 1345 93 +1345 1346 96 +1346 577 96 +1347 580 95 +1348 1349 51 +1349 1350 48 +1350 1351 50 +1351 203 47 +1352 1353 117 +1353 1354 114 +1354 267 116 +1355 1356 116 +1356 1357 116 +1357 271 116 diff --git a/share/doc/networkx-1.11/examples/drawing/lanl_routes.py b/share/doc/networkx-1.11/examples/drawing/lanl_routes.py new file mode 100644 index 000000000..ed316229b --- /dev/null +++ b/share/doc/networkx-1.11/examples/drawing/lanl_routes.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python +""" +Routes to LANL from 186 sites on the Internet. + +This uses Graphviz for layout so you need PyGraphviz or PyDotPlus. + +""" +# Author: Aric Hagberg (hagberg@lanl.gov) + +# Copyright (C) 2004-2016 +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + + +def lanl_graph(): + """ Return the lanl internet view graph from lanl.edges + """ + import networkx as nx + try: + fh = open('lanl_routes.edgelist' , 'r') + except IOError: + print("lanl.edges not found") + raise + + G = nx.Graph() + + time = {} + time[0] = 0 # assign 0 to center node + for line in fh.readlines(): + (head, tail, rtt) = line.split() + G.add_edge(int(head), int(tail)) + time[int(head)] = float(rtt) + + # get largest component and assign ping times to G0time dictionary + G0 = sorted(nx.connected_component_subgraphs(G), key = len, reverse=True)[0] + G0.rtt = {} + for n in G0: + G0.rtt[n] = time[n] + + return G0 + +if __name__ == '__main__': + import networkx as nx + import math + try: + import pygraphviz + from networkx.drawing.nx_agraph import graphviz_layout + except ImportError: + try: + import pydotplus + from networkx.drawing.nx_pydot import graphviz_layout + except ImportError: + raise ImportError("This example needs Graphviz and either " + "PyGraphviz or PyDotPlus") + + G=lanl_graph() + + print("graph has %d nodes with %d edges"\ + %(nx.number_of_nodes(G), nx.number_of_edges(G))) + print(nx.number_connected_components(G), "connected components") + + import matplotlib.pyplot as plt + plt.figure(figsize=(8, 8)) + # use graphviz to find radial layout + pos = graphviz_layout(G, prog="twopi", root=0) + # draw nodes, coloring by rtt ping time + nx.draw(G, pos, + node_color=[G.rtt[v] for v in G], + with_labels=False, + alpha=0.5, + node_size=15) + # adjust the plot limits + xmax = 1.02 * max(xx for xx,yy in pos.values()) + ymax = 1.02 * max(yy for xx,yy in pos.values()) + plt.xlim(0, xmax) + plt.ylim(0, ymax) + plt.savefig("lanl_routes.png") diff --git a/share/doc/networkx-1.11/examples/drawing/node_colormap.py b/share/doc/networkx-1.11/examples/drawing/node_colormap.py new file mode 100644 index 000000000..6a2d28d4b --- /dev/null +++ b/share/doc/networkx-1.11/examples/drawing/node_colormap.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python +""" +Draw a graph with matplotlib, color by degree. +You must have matplotlib for this to work. +""" +# Author: Aric Hagberg (hagberg@lanl.gov) + +try: + import matplotlib.pyplot as plt +except: + raise +import networkx as nx + + +G=nx.cycle_graph(24) +pos=nx.spring_layout(G,iterations=200) +nx.draw(G,pos,node_color=range(24),node_size=800,cmap=plt.cm.Blues) +plt.savefig("node_colormap.png") # save as png +plt.show() # display diff --git a/share/doc/networkx-1.11/examples/drawing/random_geometric_graph.py b/share/doc/networkx-1.11/examples/drawing/random_geometric_graph.py new file mode 100644 index 000000000..d39fec6f3 --- /dev/null +++ b/share/doc/networkx-1.11/examples/drawing/random_geometric_graph.py @@ -0,0 +1,33 @@ +import networkx as nx +import matplotlib.pyplot as plt + +G=nx.random_geometric_graph(200,0.125) +# position is stored as node attribute data for random_geometric_graph +pos=nx.get_node_attributes(G,'pos') + +# find node near center (0.5,0.5) +dmin=1 +ncenter=0 +for n in pos: + x,y=pos[n] + d=(x-0.5)**2+(y-0.5)**2 + if d +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +import zipfile, cStringIO +import networkx as nx +import matplotlib.pyplot as plt + +zf = zipfile.ZipFile('sampson_data.zip') # zipfile object +e1=cStringIO.StringIO(zf.read('samplike1.txt')) # read info file +e2=cStringIO.StringIO(zf.read('samplike2.txt')) # read info file +e3=cStringIO.StringIO(zf.read('samplike3.txt')) # read info file +G1=nx.read_edgelist(e1,delimiter='\t') +G2=nx.read_edgelist(e2,delimiter='\t') +G3=nx.read_edgelist(e3,delimiter='\t') +pos=nx.spring_layout(G3,iterations=100) +plt.clf() + +plt.subplot(221) +plt.title('samplike1') +nx.draw(G1,pos,node_size=50,with_labels=False) +plt.subplot(222) +plt.title('samplike2') +nx.draw(G2,pos,node_size=50,with_labels=False) +plt.subplot(223) +plt.title('samplike3') +nx.draw(G3,pos,node_size=50,with_labels=False) +plt.subplot(224) +plt.title('samplike1,2,3') +nx.draw(G3,pos,edgelist=G3.edges(),node_size=50,with_labels=False) +nx.draw_networkx_edges(G1,pos,alpha=0.25) +nx.draw_networkx_edges(G2,pos,alpha=0.25) +plt.savefig("sampson.png") # save as png +plt.show() # display diff --git a/share/doc/networkx-1.11/examples/drawing/simple_path.py b/share/doc/networkx-1.11/examples/drawing/simple_path.py new file mode 100644 index 000000000..b7f70b9fc --- /dev/null +++ b/share/doc/networkx-1.11/examples/drawing/simple_path.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python +""" +Draw a graph with matplotlib. +You must have matplotlib for this to work. +""" +try: + import matplotlib.pyplot as plt +except: + raise + +import networkx as nx + +G=nx.path_graph(8) +nx.draw(G) +plt.savefig("simple_path.png") # save as png +plt.show() # display diff --git a/share/doc/networkx-1.11/examples/drawing/unix_email.mbox b/share/doc/networkx-1.11/examples/drawing/unix_email.mbox new file mode 100644 index 000000000..a3a7cf8dd --- /dev/null +++ b/share/doc/networkx-1.11/examples/drawing/unix_email.mbox @@ -0,0 +1,84 @@ +From alice@edu Thu Jun 16 16:12:12 2005 +From: Alice +Subject: NetworkX +Date: Thu, 16 Jun 2005 16:12:13 -0700 +To: Bob +Status: RO +Content-Length: 86 +Lines: 5 + +Bob, check out the new networkx release - you and +Carol might really like it. + +Alice + + +From bob@gov Thu Jun 16 18:13:12 2005 +Return-Path: +Subject: Re: NetworkX +From: Bob +To: Alice +Content-Type: text/plain +Date: Thu, 16 Jun 2005 18:13:12 -0700 +Status: RO +Content-Length: 26 +Lines: 4 + +Thanks for the tip. + +Bob + + +From ted@com Thu Jul 28 09:53:31 2005 +Return-Path: +Subject: Graph package in Python? +From: Ted +To: Bob +Content-Type: text/plain +Date: Thu, 28 Jul 2005 09:47:03 -0700 +Status: RO +Content-Length: 90 +Lines: 3 + +Hey Ted - I'm looking for a Python package for +graphs and networks. Do you know of any? + + +From bob@gov Thu Jul 28 09:59:31 2005 +Return-Path: +Subject: Re: Graph package in Python? +From: Bob +To: Ted +Content-Type: text/plain +Date: Thu, 28 Jul 2005 09:59:03 -0700 +Status: RO +Content-Length: 180 +Lines: 9 + + +Check out the NetworkX package - Alice sent me the tip! + +Bob + +>> bob@gov scrawled: +>> Hey Ted - I'm looking for a Python package for +>> graphs and networks. Do you know of any? + + +From ted@com Thu Jul 28 15:53:31 2005 +Return-Path: +Subject: get together for lunch to discuss Networks? +From: Ted +To: Bob , Carol , Alice +Content-Type: text/plain +Date: Thu, 28 Jul 2005 15:47:03 -0700 +Status: RO +Content-Length: 139 +Lines: 5 + +Hey everyrone! Want to meet at that restaurant on the +island in Konigsburg tonight? Bring your laptops +and we can install NetworkX. + +Ted + diff --git a/share/doc/networkx-1.11/examples/drawing/unix_email.py b/share/doc/networkx-1.11/examples/drawing/unix_email.py new file mode 100755 index 000000000..ae95b729a --- /dev/null +++ b/share/doc/networkx-1.11/examples/drawing/unix_email.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +""" +Create a directed graph, allowing multiple edges and self loops, from +a unix mailbox. The nodes are email addresses with links +that point from the sender to the recievers. The edge data +is a Python email.Message object which contains all of +the email message data. + +This example shows the power of XDiGraph to hold edge data +of arbitrary Python objects (in this case a list of email messages). + +By default, load the sample unix email mailbox called "unix_email.mbox". +You can load your own mailbox by naming it on the command line, eg + +python unixemail.py /var/spool/mail/username + +""" +# Author: Aric Hagberg (hagberg@lanl.gov) + +# Copyright (C) 2005-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +import email +from email.utils import getaddresses,parseaddr +import mailbox +import sys + +# unix mailbox recipe +# see http://www.python.org/doc/current/lib/module-mailbox.html +def msgfactory(fp): + try: + return email.message_from_file(fp) + except email.Errors.MessageParseError: + # Don't return None since that will stop the mailbox iterator + return '' + + + +if __name__ == '__main__': + + import networkx as nx + try: + import matplotlib.pyplot as plt + except: + pass + + if len(sys.argv)==1: + filePath = "unix_email.mbox" + else: + filePath = sys.argv[1] + + mbox = mailbox.mbox(filePath, msgfactory) # parse unix mailbox + + G=nx.MultiDiGraph() # create empty graph + + # parse each messages and build graph + for msg in mbox: # msg is python email.Message.Message object + (source_name,source_addr) = parseaddr(msg['From']) # sender + # get all recipients + # see http://www.python.org/doc/current/lib/module-email.Utils.html + tos = msg.get_all('to', []) + ccs = msg.get_all('cc', []) + resent_tos = msg.get_all('resent-to', []) + resent_ccs = msg.get_all('resent-cc', []) + all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs) + # now add the edges for this mail message + for (target_name,target_addr) in all_recipients: + G.add_edge(source_addr,target_addr,message=msg) + + # print edges with message subject + for (u,v,d) in G.edges_iter(data=True): + print("From: %s To: %s Subject: %s"%(u,v,d['message']["Subject"])) + + + try: # draw + pos=nx.spring_layout(G,iterations=10) + nx.draw(G,pos,node_size=0,alpha=0.4,edge_color='r',font_size=16) + plt.savefig("unix_email.png") + plt.show() + except: # matplotlib not available + pass diff --git a/share/doc/networkx-1.11/examples/drawing/weighted_graph.py b/share/doc/networkx-1.11/examples/drawing/weighted_graph.py new file mode 100644 index 000000000..74e265144 --- /dev/null +++ b/share/doc/networkx-1.11/examples/drawing/weighted_graph.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python +""" +An example using Graph as a weighted network. +""" +# Author: Aric Hagberg (hagberg@lanl.gov) +try: + import matplotlib.pyplot as plt +except: + raise + +import networkx as nx + +G=nx.Graph() + +G.add_edge('a','b',weight=0.6) +G.add_edge('a','c',weight=0.2) +G.add_edge('c','d',weight=0.1) +G.add_edge('c','e',weight=0.7) +G.add_edge('c','f',weight=0.9) +G.add_edge('a','d',weight=0.3) + +elarge=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >0.5] +esmall=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] <=0.5] + +pos=nx.spring_layout(G) # positions for all nodes + +# nodes +nx.draw_networkx_nodes(G,pos,node_size=700) + +# edges +nx.draw_networkx_edges(G,pos,edgelist=elarge, + width=6) +nx.draw_networkx_edges(G,pos,edgelist=esmall, + width=6,alpha=0.5,edge_color='b',style='dashed') + +# labels +nx.draw_networkx_labels(G,pos,font_size=20,font_family='sans-serif') + +plt.axis('off') +plt.savefig("weighted_graph.png") # save as png +plt.show() # display diff --git a/share/doc/networkx-1.11/examples/graph/atlas.py b/share/doc/networkx-1.11/examples/graph/atlas.py new file mode 100644 index 000000000..418ac6363 --- /dev/null +++ b/share/doc/networkx-1.11/examples/graph/atlas.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python +""" +Atlas of all graphs of 6 nodes or less. + +""" +# Author: Aric Hagberg (hagberg@lanl.gov) + +# Copyright (C) 2004-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +import networkx as nx +from networkx.generators.atlas import * +from networkx.algorithms.isomorphism.isomorph import graph_could_be_isomorphic as isomorphic +import random + +def atlas6(): + """ Return the atlas of all connected graphs of 6 nodes or less. + Attempt to check for isomorphisms and remove. + """ + + Atlas = graph_atlas_g()[0:208] # 208 + # remove isolated nodes, only connected graphs are left + U = nx.Graph() # graph for union of all graphs in atlas + for G in Atlas: + zerodegree = [n for n in G if G.degree(n)==0] + for n in zerodegree: + G.remove_node(n) + U = nx.disjoint_union(U, G) + + # list of graphs of all connected components + C = nx.connected_component_subgraphs(U) + + UU = nx.Graph() + # do quick isomorphic-like check, not a true isomorphism checker + nlist = [] # list of nonisomorphic graphs + for G in C: + # check against all nonisomorphic graphs so far + if not iso(G, nlist): + nlist.append(G) + UU = nx.disjoint_union(UU, G) # union the nonisomorphic graphs + return UU + +def iso(G1, glist): + """Quick and dirty nonisomorphism checker used to check isomorphisms.""" + for G2 in glist: + if isomorphic(G1, G2): + return True + return False + + +if __name__ == '__main__': + G=atlas6() + + print("graph has %d nodes with %d edges"\ + %(nx.number_of_nodes(G), nx.number_of_edges(G))) + print(nx.number_connected_components(G), "connected components") + + try: + import pygraphviz + from networkx.drawing.nx_agraph import graphviz_layout + except ImportError: + try: + import pydotplus + from networkx.drawing.nx_pydot import graphviz_layout + except ImportError: + raise ImportError("This example needs Graphviz and either " + "PyGraphviz or PyDotPlus") + + import matplotlib.pyplot as plt + plt.figure(1, figsize=(8, 8)) + # layout graphs with positions using graphviz neato + pos = graphviz_layout(G, prog="neato") + # color nodes the same in each connected subgraph + C = nx.connected_component_subgraphs(G) + for g in C: + c = [random.random()] * nx.number_of_nodes(g) # random color... + nx.draw(g, + pos, + node_size=40, + node_color=c, + vmin=0.0, + vmax=1.0, + with_labels=False + ) + plt.savefig("atlas.png", dpi=75) diff --git a/share/doc/networkx-1.11/examples/graph/atlas2.py b/share/doc/networkx-1.11/examples/graph/atlas2.py new file mode 100644 index 000000000..268f5d3a6 --- /dev/null +++ b/share/doc/networkx-1.11/examples/graph/atlas2.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python +""" +Write first 20 graphs from the graph atlas as graphviz dot files +Gn.dot where n=0,19. +Requires pygraphviz and graphviz. +""" +# Author: Aric Hagberg (hagberg@lanl.gov) +# Date: 2005-05-19 14:23:02 -0600 (Thu, 19 May 2005) + +# Copyright (C) 2006-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +import networkx as nx +from networkx.generators.atlas import * +from pygraphviz import * + +atlas = graph_atlas_g()[0:20] + + +for G in atlas: + print("graph %s has %d nodes with %d edges" + %(G.name,NX.number_of_nodes(G),NX.number_of_edges(G))) + A = nx.nx_agraph.to_agraph(G) + A.graph_attr['label'] = G.name + # set default node attributes + A.node_attr['color'] = 'red' + A.node_attr['style'] = 'filled' + A.node_attr['shape'] = 'circle' + A.write(G.name + '.dot') diff --git a/share/doc/networkx-1.11/examples/graph/degree_sequence.py b/share/doc/networkx-1.11/examples/graph/degree_sequence.py new file mode 100644 index 000000000..8a767d293 --- /dev/null +++ b/share/doc/networkx-1.11/examples/graph/degree_sequence.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python +""" +Random graph from given degree sequence. +""" +# Author: Aric Hagberg (hagberg@lanl.gov) +# Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) +# Revision: 503 + +# Copyright (C) 2004-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +from networkx import * + +z=[5,3,3,3,3,2,2,2,1,1,1] +print(is_valid_degree_sequence(z)) + +print("Configuration model") +G=configuration_model(z) # configuration model +degree_sequence=list(degree(G).values()) # degree sequence +print("Degree sequence %s" % degree_sequence) +print("Degree histogram") +hist={} +for d in degree_sequence: + if d in hist: + hist[d]+=1 + else: + hist[d]=1 +print("degree #nodes") +for d in hist: + print('%d %d' % (d,hist[d])) diff --git a/share/doc/networkx-1.11/examples/graph/erdos_renyi.py b/share/doc/networkx-1.11/examples/graph/erdos_renyi.py new file mode 100644 index 000000000..63ffb1891 --- /dev/null +++ b/share/doc/networkx-1.11/examples/graph/erdos_renyi.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +#!/usr/bin/env python +""" +Create an G{n,m} random graph with n nodes and m edges +and report some properties. + +This graph is sometimes called the Erdős-Rényi graph +but is different from G{n,p} or binomial_graph which is also +sometimes called the Erdős-Rényi graph. +""" +# Author: Aric Hagberg (hagberg@lanl.gov) + +# Copyright (C) 2004-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +from networkx import * +import sys + +n=10 # 10 nodes +m=20 # 20 edges + +G=gnm_random_graph(n,m) + +# some properties +print("node degree clustering") +for v in nodes(G): + print('%s %d %f' % (v,degree(G,v),clustering(G,v))) + +# print the adjacency list to terminal +try: + write_adjlist(G,sys.stdout) +except TypeError: # Python 3.x + write_adjlist(G,sys.stdout.buffer) + diff --git a/share/doc/networkx-1.11/examples/graph/expected_degree_sequence.py b/share/doc/networkx-1.11/examples/graph/expected_degree_sequence.py new file mode 100644 index 000000000..0a00851cd --- /dev/null +++ b/share/doc/networkx-1.11/examples/graph/expected_degree_sequence.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +""" +Random graph from given degree sequence. +""" +# Author: Aric Hagberg (hagberg@lanl.gov) + +# Copyright (C) 2006-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +from networkx import * +from networkx.generators.degree_seq import * + +# make a random graph of 500 nodes with expected degrees of 50 +n=500 # n nodes +p=0.1 +w=[p*n for i in range(n)] # w = p*n for all nodes +G=expected_degree_graph(w) # configuration model +print("Degree histogram") +print("degree (#nodes) ****") +dh=degree_histogram(G) +low=min(degree(G)) +for i in range(low,len(dh)): + bar=''.join(dh[i]*['*']) + print("%2s (%2s) %s"%(i,dh[i],bar)) + diff --git a/share/doc/networkx-1.11/examples/graph/football.py b/share/doc/networkx-1.11/examples/graph/football.py new file mode 100644 index 000000000..d70cebc6c --- /dev/null +++ b/share/doc/networkx-1.11/examples/graph/football.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python +""" +Load football network in GML format and compute some network statistcs. + +Shows how to download GML graph in a zipped file, unpack it, and load +into a NetworkX graph. + +Requires Internet connection to download the URL +http://www-personal.umich.edu/~mejn/netdata/football.zip + +""" +# Author: Aric Hagberg (hagberg@lanl.gov) + +# Copyright (C) 2007-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +from networkx import * + +url="http://www-personal.umich.edu/~mejn/netdata/football.zip" + +try: # Python 3.x + import urllib.request as urllib +except ImportError: # Python 2.x + import urllib +import io +import zipfile + +sock = urllib.urlopen(url) # open URL +s=io.BytesIO(sock.read()) # read into BytesIO "file" +sock.close() + +zf = zipfile.ZipFile(s) # zipfile object +txt=zf.read('football.txt').decode() # read info file +gml=zf.read('football.gml').decode() # read gml data +# throw away bogus first line with # from mejn files +gml=gml.split('\n')[1:] +G=parse_gml(gml) # parse gml data + +print(txt) +# print degree for each team - number of games +for n,d in G.degree_iter(): + print('%s %d' % (n, d)) diff --git a/share/doc/networkx-1.11/examples/graph/karate_club.py b/share/doc/networkx-1.11/examples/graph/karate_club.py new file mode 100644 index 000000000..58121f3c7 --- /dev/null +++ b/share/doc/networkx-1.11/examples/graph/karate_club.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python +""" +Zachary's Karate Club graph + +Data file from: +http://vlado.fmf.uni-lj.si/pub/networks/data/Ucinet/UciData.htm + +Reference: +Zachary W. (1977). +An information flow model for conflict and fission in small groups. +Journal of Anthropological Research, 33, 452-473. +""" +import networkx as nx +G=nx.karate_club_graph() +print("Node Degree") +for v in G: + print('%s %s' % (v,G.degree(v))) diff --git a/share/doc/networkx-1.11/examples/graph/knuth_miles.py b/share/doc/networkx-1.11/examples/graph/knuth_miles.py new file mode 100644 index 000000000..0ba9fd767 --- /dev/null +++ b/share/doc/networkx-1.11/examples/graph/knuth_miles.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python +""" +An example using networkx.Graph(). + +miles_graph() returns an undirected graph over the 128 US cities from +the datafile miles_dat.txt. The cities each have location and population +data. The edges are labeled with the distance betwen the two cities. + +This example is described in Section 1.1 in Knuth's book [1,2]. + +References. +----------- + +[1] Donald E. Knuth, + "The Stanford GraphBase: A Platform for Combinatorial Computing", + ACM Press, New York, 1993. +[2] http://www-cs-faculty.stanford.edu/~knuth/sgb.html + + +""" +# Author: Aric Hagberg (hagberg@lanl.gov) + +# Copyright (C) 2004-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +import networkx as nx + + +def miles_graph(): + """ Return the cites example graph in miles_dat.txt + from the Stanford GraphBase. + """ + # open file miles_dat.txt.gz (or miles_dat.txt) + import gzip + fh = gzip.open('knuth_miles.txt.gz','r') + + G=nx.Graph() + G.position={} + G.population={} + + cities=[] + for line in fh.readlines(): + line = line.decode() + if line.startswith("*"): # skip comments + continue + + numfind=re.compile("^\d+") + + if numfind.match(line): # this line is distances + dist=line.split() + for d in dist: + G.add_edge(city,cities[i],weight=int(d)) + i=i+1 + else: # this line is a city, position, population + i=1 + (city,coordpop)=line.split("[") + cities.insert(0,city) + (coord,pop)=coordpop.split("]") + (y,x)=coord.split(",") + + G.add_node(city) + # assign position - flip x axis for matplotlib, shift origin + G.position[city]=(-int(x)+7500,int(y)-3000) + G.population[city]=float(pop)/1000.0 + return G + +if __name__ == '__main__': + import networkx as nx + import re + import sys + + G=miles_graph() + + print("Loaded miles_dat.txt containing 128 cities.") + print("digraph has %d nodes with %d edges"\ + %(nx.number_of_nodes(G),nx.number_of_edges(G))) + + + # make new graph of cites, edge if less then 300 miles between them + H=nx.Graph() + for v in G: + H.add_node(v) + for (u,v,d) in G.edges(data=True): + if d['weight'] < 300: + H.add_edge(u,v) + + # draw with matplotlib/pylab + + try: + import matplotlib.pyplot as plt + plt.figure(figsize=(8,8)) + # with nodes colored by degree sized by population + node_color=[float(H.degree(v)) for v in H] + nx.draw(H,G.position, + node_size=[G.population[v] for v in H], + node_color=node_color, + with_labels=False) + + # scale the axes equally + plt.xlim(-5000,500) + plt.ylim(-2000,3500) + + plt.savefig("knuth_miles.png") + except: + pass + + + diff --git a/share/doc/networkx-1.11/examples/graph/knuth_miles.txt.gz b/share/doc/networkx-1.11/examples/graph/knuth_miles.txt.gz new file mode 100644 index 000000000..62b7f95fb Binary files /dev/null and b/share/doc/networkx-1.11/examples/graph/knuth_miles.txt.gz differ diff --git a/share/doc/networkx-1.11/examples/graph/napoleon_russian_campaign.py b/share/doc/networkx-1.11/examples/graph/napoleon_russian_campaign.py new file mode 100644 index 000000000..bdc8e918f --- /dev/null +++ b/share/doc/networkx-1.11/examples/graph/napoleon_russian_campaign.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python +""" +Minard's data from Napoleon's 1812-1813 Russian Campaign. +http://www.math.yorku.ca/SCS/Gallery/minard/minard.txt + +""" +# Author: Aric Hagberg (hagberg@lanl.gov) + +# Copyright (C) 2006-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +import string +import networkx as nx + + +def minard_graph(): + data1="""\ +24.0,54.9,340000,A,1 +24.5,55.0,340000,A,1 +25.5,54.5,340000,A,1 +26.0,54.7,320000,A,1 +27.0,54.8,300000,A,1 +28.0,54.9,280000,A,1 +28.5,55.0,240000,A,1 +29.0,55.1,210000,A,1 +30.0,55.2,180000,A,1 +30.3,55.3,175000,A,1 +32.0,54.8,145000,A,1 +33.2,54.9,140000,A,1 +34.4,55.5,127100,A,1 +35.5,55.4,100000,A,1 +36.0,55.5,100000,A,1 +37.6,55.8,100000,A,1 +37.7,55.7,100000,R,1 +37.5,55.7,98000,R,1 +37.0,55.0,97000,R,1 +36.8,55.0,96000,R,1 +35.4,55.3,87000,R,1 +34.3,55.2,55000,R,1 +33.3,54.8,37000,R,1 +32.0,54.6,24000,R,1 +30.4,54.4,20000,R,1 +29.2,54.3,20000,R,1 +28.5,54.2,20000,R,1 +28.3,54.3,20000,R,1 +27.5,54.5,20000,R,1 +26.8,54.3,12000,R,1 +26.4,54.4,14000,R,1 +25.0,54.4,8000,R,1 +24.4,54.4,4000,R,1 +24.2,54.4,4000,R,1 +24.1,54.4,4000,R,1""" + data2="""\ +24.0,55.1,60000,A,2 +24.5,55.2,60000,A,2 +25.5,54.7,60000,A,2 +26.6,55.7,40000,A,2 +27.4,55.6,33000,A,2 +28.7,55.5,33000,R,2 +29.2,54.2,30000,R,2 +28.5,54.1,30000,R,2 +28.3,54.2,28000,R,2""" + data3="""\ +24.0,55.2,22000,A,3 +24.5,55.3,22000,A,3 +24.6,55.8,6000,A,3 +24.6,55.8,6000,R,3 +24.2,54.4,6000,R,3 +24.1,54.4,6000,R,3""" + cities="""\ +24.0,55.0,Kowno +25.3,54.7,Wilna +26.4,54.4,Smorgoni +26.8,54.3,Moiodexno +27.7,55.2,Gloubokoe +27.6,53.9,Minsk +28.5,54.3,Studienska +28.7,55.5,Polotzk +29.2,54.4,Bobr +30.2,55.3,Witebsk +30.4,54.5,Orscha +30.4,53.9,Mohilow +32.0,54.8,Smolensk +33.2,54.9,Dorogobouge +34.3,55.2,Wixma +34.4,55.5,Chjat +36.0,55.5,Mojaisk +37.6,55.8,Moscou +36.6,55.3,Tarantino +36.5,55.0,Malo-Jarosewii""" + + c={} + for line in cities.split('\n'): + x,y,name=line.split(',') + c[name]=(float(x),float(y)) + + g=[] + + for data in [data1,data2,data3]: + G=nx.Graph() + i=0 + G.pos={} # location + G.pop={} # size + last=None + for line in data.split('\n'): + x,y,p,r,n=line.split(',') + G.pos[i]=(float(x),float(y)) + G.pop[i]=int(p) + if last is None: + last=i + else: + G.add_edge(i,last,{r:int(n)}) + last=i + i=i+1 + g.append(G) + + return g,c + +if __name__ == "__main__": + + (g,city)=minard_graph() + + try: + import matplotlib.pyplot as plt + plt.figure(1,figsize=(11,5)) + plt.clf() + colors=['b','g','r'] + for G in g: + c=colors.pop(0) + node_size=[int(G.pop[n]/300.0) for n in G] + nx.draw_networkx_edges(G,G.pos,edge_color=c,width=4,alpha=0.5) + nx.draw_networkx_nodes(G,G.pos,node_size=node_size,node_color=c,alpha=0.5) + nx.draw_networkx_nodes(G,G.pos,node_size=5,node_color='k') + + for c in city: + x,y=city[c] + plt.text(x,y+0.1,c) + plt.savefig("napoleon_russian_campaign.png") + except ImportError: + pass + diff --git a/share/doc/networkx-1.11/examples/graph/roget.py b/share/doc/networkx-1.11/examples/graph/roget.py new file mode 100644 index 000000000..b31baa322 --- /dev/null +++ b/share/doc/networkx-1.11/examples/graph/roget.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python +""" +Build a directed graph of 1022 categories and +5075 cross-references as defined in the 1879 version of Roget's Thesaurus +contained in the datafile roget_dat.txt. This example is described in +Section 1.2 in Knuth's book [1,2]. + +Note that one of the 5075 cross references is a self loop yet +it is included in the graph built here because +the standard networkx DiGraph class allows self loops. +(cf. 400pungency:400 401 403 405). + +References. +---------- + +[1] Donald E. Knuth, + "The Stanford GraphBase: A Platform for Combinatorial Computing", + ACM Press, New York, 1993. +[2] http://www-cs-faculty.stanford.edu/~knuth/sgb.html + + +""" +from __future__ import print_function +# Authors: Brendt Wohlberg, Aric Hagberg (hagberg@lanl.gov) +# Date: 2005-04-01 07:56:22 -0700 (Fri, 01 Apr 2005) + +# Copyright (C) 2004-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +from networkx import * +import re +import sys + +def roget_graph(): + """ Return the thesaurus graph from the roget.dat example in + the Stanford Graph Base. + """ + # open file roget_dat.txt.gz (or roget_dat.txt) + import gzip + fh=gzip.open('roget_dat.txt.gz','r') + + G=DiGraph() + + for line in fh.readlines(): + line = line.decode() + if line.startswith("*"): # skip comments + continue + if line.startswith(" "): # this is a continuation line, append + line=oldline+line + if line.endswith("\\\n"): # continuation line, buffer, goto next + oldline=line.strip("\\\n") + continue + + (headname,tails)=line.split(":") + + # head + numfind=re.compile("^\d+") # re to find the number of this word + head=numfind.findall(headname)[0] # get the number + + G.add_node(head) + + for tail in tails.split(): + if head==tail: + print("skipping self loop",head,tail, file=sys.stderr) + G.add_edge(head,tail) + + return G + +if __name__ == '__main__': + from networkx import * + G=roget_graph() + print("Loaded roget_dat.txt containing 1022 categories.") + print("digraph has %d nodes with %d edges"\ + %(number_of_nodes(G),number_of_edges(G))) + UG=G.to_undirected() + print(number_connected_components(UG),"connected components") + diff --git a/share/doc/networkx-1.11/examples/graph/roget_dat.txt.gz b/share/doc/networkx-1.11/examples/graph/roget_dat.txt.gz new file mode 100644 index 000000000..6552465de Binary files /dev/null and b/share/doc/networkx-1.11/examples/graph/roget_dat.txt.gz differ diff --git a/share/doc/networkx-1.11/examples/graph/unix_email.mbox b/share/doc/networkx-1.11/examples/graph/unix_email.mbox new file mode 100644 index 000000000..a3a7cf8dd --- /dev/null +++ b/share/doc/networkx-1.11/examples/graph/unix_email.mbox @@ -0,0 +1,84 @@ +From alice@edu Thu Jun 16 16:12:12 2005 +From: Alice +Subject: NetworkX +Date: Thu, 16 Jun 2005 16:12:13 -0700 +To: Bob +Status: RO +Content-Length: 86 +Lines: 5 + +Bob, check out the new networkx release - you and +Carol might really like it. + +Alice + + +From bob@gov Thu Jun 16 18:13:12 2005 +Return-Path: +Subject: Re: NetworkX +From: Bob +To: Alice +Content-Type: text/plain +Date: Thu, 16 Jun 2005 18:13:12 -0700 +Status: RO +Content-Length: 26 +Lines: 4 + +Thanks for the tip. + +Bob + + +From ted@com Thu Jul 28 09:53:31 2005 +Return-Path: +Subject: Graph package in Python? +From: Ted +To: Bob +Content-Type: text/plain +Date: Thu, 28 Jul 2005 09:47:03 -0700 +Status: RO +Content-Length: 90 +Lines: 3 + +Hey Ted - I'm looking for a Python package for +graphs and networks. Do you know of any? + + +From bob@gov Thu Jul 28 09:59:31 2005 +Return-Path: +Subject: Re: Graph package in Python? +From: Bob +To: Ted +Content-Type: text/plain +Date: Thu, 28 Jul 2005 09:59:03 -0700 +Status: RO +Content-Length: 180 +Lines: 9 + + +Check out the NetworkX package - Alice sent me the tip! + +Bob + +>> bob@gov scrawled: +>> Hey Ted - I'm looking for a Python package for +>> graphs and networks. Do you know of any? + + +From ted@com Thu Jul 28 15:53:31 2005 +Return-Path: +Subject: get together for lunch to discuss Networks? +From: Ted +To: Bob , Carol , Alice +Content-Type: text/plain +Date: Thu, 28 Jul 2005 15:47:03 -0700 +Status: RO +Content-Length: 139 +Lines: 5 + +Hey everyrone! Want to meet at that restaurant on the +island in Konigsburg tonight? Bring your laptops +and we can install NetworkX. + +Ted + diff --git a/share/doc/networkx-1.11/examples/graph/unix_email.py b/share/doc/networkx-1.11/examples/graph/unix_email.py new file mode 100644 index 000000000..ae95b729a --- /dev/null +++ b/share/doc/networkx-1.11/examples/graph/unix_email.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +""" +Create a directed graph, allowing multiple edges and self loops, from +a unix mailbox. The nodes are email addresses with links +that point from the sender to the recievers. The edge data +is a Python email.Message object which contains all of +the email message data. + +This example shows the power of XDiGraph to hold edge data +of arbitrary Python objects (in this case a list of email messages). + +By default, load the sample unix email mailbox called "unix_email.mbox". +You can load your own mailbox by naming it on the command line, eg + +python unixemail.py /var/spool/mail/username + +""" +# Author: Aric Hagberg (hagberg@lanl.gov) + +# Copyright (C) 2005-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +import email +from email.utils import getaddresses,parseaddr +import mailbox +import sys + +# unix mailbox recipe +# see http://www.python.org/doc/current/lib/module-mailbox.html +def msgfactory(fp): + try: + return email.message_from_file(fp) + except email.Errors.MessageParseError: + # Don't return None since that will stop the mailbox iterator + return '' + + + +if __name__ == '__main__': + + import networkx as nx + try: + import matplotlib.pyplot as plt + except: + pass + + if len(sys.argv)==1: + filePath = "unix_email.mbox" + else: + filePath = sys.argv[1] + + mbox = mailbox.mbox(filePath, msgfactory) # parse unix mailbox + + G=nx.MultiDiGraph() # create empty graph + + # parse each messages and build graph + for msg in mbox: # msg is python email.Message.Message object + (source_name,source_addr) = parseaddr(msg['From']) # sender + # get all recipients + # see http://www.python.org/doc/current/lib/module-email.Utils.html + tos = msg.get_all('to', []) + ccs = msg.get_all('cc', []) + resent_tos = msg.get_all('resent-to', []) + resent_ccs = msg.get_all('resent-cc', []) + all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs) + # now add the edges for this mail message + for (target_name,target_addr) in all_recipients: + G.add_edge(source_addr,target_addr,message=msg) + + # print edges with message subject + for (u,v,d) in G.edges_iter(data=True): + print("From: %s To: %s Subject: %s"%(u,v,d['message']["Subject"])) + + + try: # draw + pos=nx.spring_layout(G,iterations=10) + nx.draw(G,pos,node_size=0,alpha=0.4,edge_color='r',font_size=16) + plt.savefig("unix_email.png") + plt.show() + except: # matplotlib not available + pass diff --git a/share/doc/networkx-1.11/examples/graph/words.py b/share/doc/networkx-1.11/examples/graph/words.py new file mode 100644 index 000000000..9b5b9dfcf --- /dev/null +++ b/share/doc/networkx-1.11/examples/graph/words.py @@ -0,0 +1,84 @@ +""" +Words/Ladder Graph +------------------ +Generate an undirected graph over the 5757 5-letter words in the +datafile words_dat.txt.gz. Two words are connected by an edge +if they differ in one letter, resulting in 14,135 edges. This example +is described in Section 1.1 in Knuth's book [1]_,[2]_. + +References +---------- +.. [1] Donald E. Knuth, + "The Stanford GraphBase: A Platform for Combinatorial Computing", + ACM Press, New York, 1993. +.. [2] http://www-cs-faculty.stanford.edu/~knuth/sgb.html +""" +# Authors: Aric Hagberg (hagberg@lanl.gov), +# Brendt Wohlberg, +# hughdbrown@yahoo.com + +# Copyright (C) 2004-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +import networkx as nx + +#------------------------------------------------------------------- +# The Words/Ladder graph of Section 1.1 +#------------------------------------------------------------------- +def generate_graph(words): + from string import ascii_lowercase as lowercase + G = nx.Graph(name="words") + lookup = dict((c,lowercase.index(c)) for c in lowercase) + def edit_distance_one(word): + for i in range(len(word)): + left, c, right = word[0:i], word[i], word[i+1:] + j = lookup[c] # lowercase.index(c) + for cc in lowercase[j+1:]: + yield left + cc + right + candgen = ((word, cand) for word in sorted(words) + for cand in edit_distance_one(word) if cand in words) + G.add_nodes_from(words) + for word, cand in candgen: + G.add_edge(word, cand) + return G + +def words_graph(): + """Return the words example graph from the Stanford GraphBase""" + import gzip + fh=gzip.open('words_dat.txt.gz','r') + words=set() + for line in fh.readlines(): + line = line.decode() + if line.startswith('*'): + continue + w=str(line[0:5]) + words.add(w) + return generate_graph(words) + +if __name__ == '__main__': + from networkx import * + G=words_graph() + print("Loaded words_dat.txt containing 5757 five-letter English words.") + print("Two words are connected if they differ in one letter.") + print("Graph has %d nodes with %d edges" + %(number_of_nodes(G),number_of_edges(G))) + print("%d connected components" % number_connected_components(G)) + + for (source,target) in [('chaos','order'), + ('nodes','graph'), + ('pound','marks')]: + print("Shortest path between %s and %s is"%(source,target)) + try: + sp=shortest_path(G, source, target) + for n in sp: + print(n) + except nx.NetworkXNoPath: + print("None") + + + + diff --git a/share/doc/networkx-1.11/examples/graph/words_dat.txt.gz b/share/doc/networkx-1.11/examples/graph/words_dat.txt.gz new file mode 100644 index 000000000..78aff7913 Binary files /dev/null and b/share/doc/networkx-1.11/examples/graph/words_dat.txt.gz differ diff --git a/share/doc/networkx-1.11/examples/multigraph/chess_masters.py b/share/doc/networkx-1.11/examples/multigraph/chess_masters.py new file mode 100644 index 000000000..76e8ae6f7 --- /dev/null +++ b/share/doc/networkx-1.11/examples/multigraph/chess_masters.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python + +""" +An example of the MultiDiGraph clas + +The function chess_pgn_graph reads a collection of chess +matches stored in the specified PGN file +(PGN ="Portable Game Notation") +Here the (compressed) default file --- + chess_masters_WCC.pgn.bz2 --- +contains all 685 World Chess Championship matches +from 1886 - 1985. +(data from http://chessproblem.my-free-games.com/chess/games/Download-PGN.php) + +The chess_pgn_graph() function returns a MultiDiGraph +with multiple edges. Each node is +the last name of a chess master. Each edge is directed +from white to black and contains selected game info. + +The key statement in chess_pgn_graph below is + G.add_edge(white, black, game_info) +where game_info is a dict describing each game. + +""" +# Copyright (C) 2006-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +import networkx as nx + +# tag names specifying what game info should be +# stored in the dict on each digraph edge +game_details=["Event", + "Date", + "Result", + "ECO", + "Site"] + +def chess_pgn_graph(pgn_file="chess_masters_WCC.pgn.bz2"): + """Read chess games in pgn format in pgn_file. + + Filenames ending in .gz or .bz2 will be uncompressed. + + Return the MultiDiGraph of players connected by a chess game. + Edges contain game data in a dict. + + """ + import bz2 + G=nx.MultiDiGraph() + game={} + datafile = bz2.BZ2File(pgn_file) + lines = (line.decode().rstrip('\r\n') for line in datafile) + for line in lines: + if line.startswith('['): + tag,value=line[1:-1].split(' ',1) + game[str(tag)]=value.strip('"') + else: + # empty line after tag set indicates + # we finished reading game info + if game: + white=game.pop('White') + black=game.pop('Black') + G.add_edge(white, black, **game) + game={} + return G + + +if __name__ == '__main__': + G=chess_pgn_graph() + + ngames=G.number_of_edges() + nplayers=G.number_of_nodes() + + print("Loaded %d chess games between %d players\n"\ + % (ngames,nplayers)) + + # identify connected components + # of the undirected version + Gcc=list(nx.connected_component_subgraphs(G.to_undirected())) + if len(Gcc)>1: + print("Note the disconnected component consisting of:") + print(Gcc[1].nodes()) + + # find all games with B97 opening (as described in ECO) + openings=set([game_info['ECO'] + for (white,black,game_info) in G.edges(data=True)]) + print("\nFrom a total of %d different openings,"%len(openings)) + print('the following games used the Sicilian opening') + print('with the Najdorff 7...Qb6 "Poisoned Pawn" variation.\n') + + for (white,black,game_info) in G.edges(data=True): + if game_info['ECO']=='B97': + print(white,"vs",black) + for k,v in game_info.items(): + print(" ",k,": ",v) + print("\n") + + + try: + import matplotlib.pyplot as plt + except ImportError: + import sys + print("Matplotlib needed for drawing. Skipping") + sys.exit(0) + + # make new undirected graph H without multi-edges + H=nx.Graph(G) + + # edge width is proportional number of games played + edgewidth=[] + for (u,v,d) in H.edges(data=True): + edgewidth.append(len(G.get_edge_data(u,v))) + + # node size is proportional to number of games won + wins=dict.fromkeys(G.nodes(),0.0) + for (u,v,d) in G.edges(data=True): + r=d['Result'].split('-') + if r[0]=='1': + wins[u]+=1.0 + elif r[0]=='1/2': + wins[u]+=0.5 + wins[v]+=0.5 + else: + wins[v]+=1.0 + try: + pos=nx.nx_agraph.graphviz_layout(H) + except: + pos=nx.spring_layout(H,iterations=20) + + plt.rcParams['text.usetex'] = False + plt.figure(figsize=(8,8)) + nx.draw_networkx_edges(H,pos,alpha=0.3,width=edgewidth, edge_color='m') + nodesize=[wins[v]*50 for v in H] + nx.draw_networkx_nodes(H,pos,node_size=nodesize,node_color='w',alpha=0.4) + nx.draw_networkx_edges(H,pos,alpha=0.4,node_size=0,width=1,edge_color='k') + nx.draw_networkx_labels(H,pos,fontsize=14) + font = {'fontname' : 'Helvetica', + 'color' : 'k', + 'fontweight' : 'bold', + 'fontsize' : 14} + plt.title("World Chess Championship Games: 1886 - 1985", font) + + # change font and write text (using data coordinates) + font = {'fontname' : 'Helvetica', + 'color' : 'r', + 'fontweight' : 'bold', + 'fontsize' : 14} + + plt.text(0.5, 0.97, "edge width = # games played", + horizontalalignment='center', + transform=plt.gca().transAxes) + plt.text(0.5, 0.94, "node size = # games won", + horizontalalignment='center', + transform=plt.gca().transAxes) + + plt.axis('off') + plt.savefig("chess_masters.png",dpi=75) + print("Wrote chess_masters.png") + plt.show() # display diff --git a/share/doc/networkx-1.11/examples/multigraph/chess_masters_WCC.pgn.bz2 b/share/doc/networkx-1.11/examples/multigraph/chess_masters_WCC.pgn.bz2 new file mode 100644 index 000000000..3761ce528 Binary files /dev/null and b/share/doc/networkx-1.11/examples/multigraph/chess_masters_WCC.pgn.bz2 differ diff --git a/share/doc/networkx-1.11/examples/pygraphviz/pygraphviz_attributes.py b/share/doc/networkx-1.11/examples/pygraphviz/pygraphviz_attributes.py new file mode 100644 index 000000000..0279569ac --- /dev/null +++ b/share/doc/networkx-1.11/examples/pygraphviz/pygraphviz_attributes.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +""" +An example showing how to use the interface to the pygraphviz +AGraph class to convert to and from graphviz. + +Also see the pygraphviz documentation and examples at +http://pygraphviz.github.io/ + +""" +# Author: Aric Hagberg (hagberg@lanl.gov) + +# Copyright (C) 2006-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +import networkx as nx + +# networkx graph +G = nx.Graph() +# ad edges with red color +G.add_edge(1, 2, color='red') +G.add_edge(2, 3, color='red') +# add nodes 3 and 4 +G.add_node(3) +G.add_node(4) + +# convert to a graphviz agraph +A = nx.nx_agraph.to_agraph(G) + +# write to dot file +A.write('k5_attributes.dot') + +# convert back to networkx Graph with attributes on edges and +# default attributes as dictionary data +X = nx.nx_agraph.from_agraph(A) +print("edges") +print(X.edges(data=True)) +print("default graph attributes") +print(X.graph) +print("node node attributes") +print(X.node) diff --git a/share/doc/networkx-1.11/examples/pygraphviz/pygraphviz_draw.py b/share/doc/networkx-1.11/examples/pygraphviz/pygraphviz_draw.py new file mode 100644 index 000000000..8f361eb22 --- /dev/null +++ b/share/doc/networkx-1.11/examples/pygraphviz/pygraphviz_draw.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python +""" +An example showing how to use the interface to the pygraphviz +AGraph class to draw a graph. + +Also see the pygraphviz documentation and examples at +http://pygraphviz.github.io/ + + +""" +# Author: Aric Hagberg (hagberg@lanl.gov) + +# Copyright (C) 2006-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +import networkx as nx + +# plain graph + +G = nx.complete_graph(5) # start with K5 in networkx +A = nx.nx_agraph.to_agraph(G) # convert to a graphviz graph +A.layout() # neato layout +A.draw("k5.ps") # write postscript in k5.ps with neato layout + diff --git a/share/doc/networkx-1.11/examples/pygraphviz/pygraphviz_simple.py b/share/doc/networkx-1.11/examples/pygraphviz/pygraphviz_simple.py new file mode 100644 index 000000000..7fb4ad421 --- /dev/null +++ b/share/doc/networkx-1.11/examples/pygraphviz/pygraphviz_simple.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python +""" +An example showing how to use the interface to the pygraphviz +AGraph class to convert to and from graphviz. + +Also see the pygraphviz documentation and examples at +http://pygraphviz.github.io/ + + +""" +# Author: Aric Hagberg (hagberg@lanl.gov) + +# Copyright (C) 2006-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +import networkx as nx + +# plain graph + +G = nx.complete_graph(5) # start with K5 in networkx +A = nx.nx_agraph.to_agraph(G) # convert to a graphviz graph +X1 = nx.nx_agraph.from_agraph(A) # convert back to networkx (but as Graph) +X2 = nx.Graph(A) # fancy way to do conversion +G1 = nx.Graph(X1) # now make it a Graph + +A.write('k5.dot') # write to dot file +X3 = nx.nx_agraph.read_dot('k5.dot') # read from dotfile + diff --git a/share/doc/networkx-1.11/examples/pygraphviz/write_dotfile.py b/share/doc/networkx-1.11/examples/pygraphviz/write_dotfile.py new file mode 100644 index 000000000..5d41ff0d5 --- /dev/null +++ b/share/doc/networkx-1.11/examples/pygraphviz/write_dotfile.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +""" +Write a dot file from a networkx graph for further processing with graphviz. + +You need to have either pygraphviz or pydotplus for this example. + +See http://networkx.github.io/documentation/latest/reference/drawing.html +for more info. + +""" +# Author: Aric Hagberg (hagberg@lanl.gov) + +# Copyright (C) 2004-2016 by +# Aric Hagberg +# Dan Schult +# Pieter Swart +# All rights reserved. +# BSD license. + +import networkx as nx + +# and the following code block is not needed +# but we want to see which module is used and +# if and why it fails +try: + import pygraphviz + from networkx.drawing.nx_agraph import write_dot + print("using package pygraphviz") +except ImportError: + try: + import pydotplus + from networkx.drawing.nx_pydot import write_dot + print("using package pydotplus") + except ImportError: + print() + print("Both pygraphviz and pydotplus were not found ") + print("see http://networkx.github.io/documentation" + "/latest/reference/drawing.html for info") + print() + raise + +G=nx.grid_2d_graph(5,5) # 5x5 grid +write_dot(G,"grid.dot") +print("Now run: neato -Tps grid.dot >grid.ps") diff --git a/share/harvest/scheduler.py b/share/harvest/scheduler.py index 3c6fc5164..dcf8abf96 100644 --- a/share/harvest/scheduler.py +++ b/share/harvest/scheduler.py @@ -34,7 +34,7 @@ def all(self, cutoff=None, allow_full_harvest=True, **kwargs): if hasattr(self.source_config, 'latest'): latest_date = self.source_config.latest else: - latest_date = self.source_config.harvest_logs.aggregate(models.Max('end_date'))['end_date__max'] + latest_date = HarvestLog.objects.filter(source_config=self.source_config).aggregate(models.Max('end_date'))['end_date__max'] # If we can build full harvests and the earliest log that would be generated does NOT exist # Go ahead and reset the latest_date to the earliest_date diff --git a/share/models/logs.py b/share/models/logs.py index c63a8f6cd..810eda7ca 100644 --- a/share/models/logs.py +++ b/share/models/logs.py @@ -188,7 +188,8 @@ class SkipReasons(enum.Enum): comprised = 'Comprised of succeeded tasks' obsolete = 'Obsolete' - task_id = models.UUIDField(null=True) + # task_id = models.UUIDField(null=True) + task_id = models.UUIDField(null=True, blank=True) status = models.IntegerField(db_index=True, choices=STATUS, default=STATUS.created) context = models.TextField(blank=True, default='')