├── .gitignore
├── screenshot.png
├── run_coverage.bat
├── networkx_viewer
├── __init__.py
├── autocomplete_entry.py
├── tokens.py
├── viewer.py
├── tests.py
└── graph_canvas.py
├── .github
└── workflows
│ └── python-app.yml
├── example.py
├── setup.py
├── README.md
└── LICENSE.txt
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 | .coverage
3 | *.pyc
4 | venv/
5 | dist/
6 |
--------------------------------------------------------------------------------
/screenshot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jsexauer/networkx_viewer/HEAD/screenshot.png
--------------------------------------------------------------------------------
/run_coverage.bat:
--------------------------------------------------------------------------------
1 | set PYTHONPATH=.
2 |
3 | coverage run --include=networkx_viewer\* networkx_viewer\tests.py
4 | coverage html
5 |
6 | start chrome .\htmlcov\index.html
7 |
--------------------------------------------------------------------------------
/networkx_viewer/__init__.py:
--------------------------------------------------------------------------------
1 | __version__ = '0.3.1'
2 |
3 |
4 | from .graph_canvas import GraphCanvas
5 | from .tokens import (NodeToken, EdgeToken, TkPassthroughNodeToken,
6 | TkPassthroughEdgeToken)
7 | from .viewer import ViewerApp, TkPassthroughViewerApp
8 |
9 | BasicViewer = ViewerApp
10 | Viewer = TkPassthroughViewerApp
--------------------------------------------------------------------------------
/.github/workflows/python-app.yml:
--------------------------------------------------------------------------------
1 | # This workflow will install Python dependencies, run tests and lint with a single version of Python
2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python
3 |
4 | name: Python application
5 |
6 | on:
7 | push:
8 | branches: [ "master" ]
9 | pull_request:
10 | branches: [ "master" ]
11 |
12 | permissions:
13 | contents: read
14 |
15 |
16 | jobs:
17 | run-tests:
18 | runs-on: ubuntu-latest
19 | strategy:
20 | matrix:
21 | python-version: [ '3.10', '3.11', '3.12' ]
22 | networkx-version: [ '3.2', '3.3' ]
23 | steps:
24 | - uses: actions/checkout@v4
25 | - name: Set up Python ${{ matrix.python-version }} and NetworkX ${{ matrix.networkx-version }}
26 | uses: actions/setup-python@v5
27 | with:
28 | python-version: ${{ matrix.python-version }}
29 |
30 | - name: Install dependencies
31 | run: |
32 | python -m pip install --upgrade pip
33 | pip install mock numpy scipy setuptools
34 |
35 | - name: Install networkx==${{ matrix.networkx-version }}
36 | run: |
37 | pip install networkx==${{ matrix.networkx-version }}
38 |
39 | - name: Install networkx-viewer
40 | run: |
41 | python setup.py install
42 |
43 | - name: Runt tests
44 | run: |
45 | xvfb-run --auto-servernum --server-args="-screen 0 1024x768x24" python ./networkx_viewer/tests.py
46 |
--------------------------------------------------------------------------------
/example.py:
--------------------------------------------------------------------------------
1 | import networkx as nx
2 | from networkx_viewer import Viewer
3 |
4 |
5 | ### Bug report ###
6 | G = nx.DiGraph()
7 | edges = [('paper_9912286', 'paper_9806074'), ('paper_9912286', 'paper_9810068'), ('paper_9912286', 'paper_9901023'), ('paper_9912286', 'paper_9808140'), ('paper_1001', 'paper_9308122'), ('paper_1001', 'paper_9304045'), ('paper_1001', 'paper_9912286')]
8 | for e in edges:
9 | G.add_edge(*e)
10 | app = Viewer(G)
11 | app.mainloop()
12 |
13 |
14 |
15 | ### Example 1 ####
16 | G = nx.MultiGraph()
17 | G.add_edge('a',2)
18 | G.add_edge(2,'c')
19 | G.add_edge('a','c',0,dash=(2,2))
20 | G.add_edge('a','c',1)
21 | G.add_edge('a',4)
22 | G.add_edge(4,'c')
23 | G.add_edge('out','c',0, fill='red', width=3)
24 | G.add_edge('c','d')
25 | G.add_edge('d',2)
26 | # Growth edges
27 | G.add_edge('out',11)
28 | G.add_edge('out',12,0)
29 | G.add_edge('out',12,1)
30 | G.add_edge('out',12,2)
31 | G.add_edge('out',12,3)
32 | G.add_edge(12, 'd')
33 | G.add_edge('TTTTT',11)
34 | G.add_edge('qqqq', 'TTTTT')
35 | G.add_edge('alone','alone')
36 |
37 | # Some example TkPassthrough options
38 | G.nodes['a']['fill'] = 'white'
39 | G.nodes['a']['dash'] = (2,2)
40 | G.nodes[2]['label_fill'] = 'blue'
41 | G.nodes[2]['label_text'] = 'LOOOOOONG'
42 |
43 | ### Filter example
44 | for n in G.nodes():
45 | G.nodes[n]['real'] = True
46 |
47 | # Now we're going to add a couple of "fake" nodes; IE, nodes
48 | # that should be not be displayed because they are not in the filter.
49 | # If they do show up, they'll cause us to fail some of the base checks
50 | G.add_edge('out','fake1')
51 | G.add_edge('a','fake2')
52 | G.add_edge('qqqq','fake3')
53 | G.add_edge('fake3','fake4')
54 | G.add_node('fake_alone')
55 | ###
56 |
57 | app = Viewer(G, home_node='a', levels=2)
58 | #app = GraphViewerApp(G, home_node='a', levels=2)
59 | app.mainloop()
60 |
61 | ### Example 2 ###
62 | G = nx.MultiGraph()
63 | G.add_edge('a','b')
64 | G.add_edge('b','c')
65 | G.add_edge('c','a',0,**{'fill':'green'})
66 | G.add_edge('c','d')
67 | G.add_edge('c','d',1,**{'dash':(2,2)})
68 | G.nodes['a']['outline'] = 'blue'
69 | G.nodes['d']['label_fill'] = 'red'
70 |
71 | app = Viewer(G)
72 | app.mainloop()
73 |
74 | ### Example 3 ###
75 | G = nx.MultiDiGraph()
76 | G.add_edge('Arg2','Arg1')
77 | G.add_edge('Arg3','Arg1',0)
78 | G.add_edge('Arg3','Arg1',1)
79 | G.add_edge('Arg4','Arg2')
80 | G.add_edge('Arg5','Arg2')
81 | G.add_edge('Arg6','Arg3')
82 | G.nodes['Arg2']['outline'] = 'blue'
83 | G.nodes['Arg1']['label_fill'] = 'red'
84 | app = Viewer(G)
85 | app.mainloop()
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup, find_packages
2 | import sys, os
3 |
4 | # python setup.py check
5 | # python.exe setup.py --long-description | rst2html.py > dummy.html
6 |
7 | # To upload to pypi
8 | # python setup.py sdist bdist_wheel
9 | # python -m twine upload dist/*
10 |
11 | # LEGACY:
12 | # To upload to PyPI test server
13 | # http://peterdowns.com/posts/first-time-with-pypi.html
14 | # python setup.py register -r pypitest
15 | # python setup.py sdist upload -r pypitest
16 | # Test repo is at: https://testpypi.python.org/pypi
17 |
18 | # To distribute on PyPI:
19 | # python setup.py register sdist upload
20 |
21 | from networkx_viewer import __version__ as version
22 |
23 | long_desc = """
24 | NetworkX Viewer provides a basic interactive GUI to view
25 | `networkx `_ graphs. In addition to standard
26 | plotting and layout features as found natively in networkx, the GUI allows
27 | you to:
28 |
29 | - Drag nodes around to tune the default layout
30 | - Show and hide nodes
31 | - Filter nodes
32 | - Pan and zoom
33 | - Display nodes only within a certain number of hops ("levels") of
34 | a "home node"
35 | - Display and highlight the shortest path between two nodes. Nodes
36 | around the path can also be displayed within a settable number of
37 | levels
38 | - Intelligently find and display nodes near displayed nodes using
39 | "Grow" and "Grow Until" functions
40 | - Use attributes stored in the graph's node and edge dictionaries to
41 | customize the appearance of the node and edge tokens in the GUI
42 | - Mark nodes and edges for reference
43 | - Support for both `nx.Graph` and `nx.MultiGraph`
44 |
45 | See https://github.com/jsexauer/networkx_viewer for more details
46 | """
47 |
48 | setup(name='networkx_viewer',
49 | version=version,
50 | description="Interactive viewer for networkx graphs.",
51 | long_description=long_desc,
52 | classifiers=[
53 | 'Development Status :: 4 - Beta',
54 | 'Topic :: Scientific/Engineering :: Mathematics',
55 | 'Topic :: Scientific/Engineering :: Visualization',
56 | 'Natural Language :: English',
57 | 'License :: OSI Approved :: GNU General Public License (GPL)',
58 | ], # Get from http://pypi.python.org/pypi?%3Aaction=list_classifiers
59 | keywords='networkx, topology, graph theory',
60 | author='Jason Sexauer',
61 | author_email='genericcarbonlifeform@gmail.com',
62 | url='http://github.com/jsexauer/networkx_viewer',
63 | license='LICENSE.txt',
64 | packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
65 | include_package_data=True,
66 | zip_safe=False,
67 | setup_requires=['networkx>=2.2'],
68 | install_requires=[
69 | 'networkx>=2.2'
70 | ],
71 | python_requires='>3.5'
72 | )
--------------------------------------------------------------------------------
/networkx_viewer/autocomplete_entry.py:
--------------------------------------------------------------------------------
1 | try:
2 | # Python 3
3 | from tkinter import *
4 | except ImportError:
5 | # Python 2
6 | from Tkinter import *
7 |
8 | import re
9 |
10 | class AutocompleteEntry(Entry):
11 | def __init__(self, autocompleteList, *args, **kwargs):
12 |
13 | # Listbox length
14 | if 'listboxLength' in kwargs:
15 | self.listboxLength = kwargs['listboxLength']
16 | del kwargs['listboxLength']
17 | else:
18 | self.listboxLength = 4
19 |
20 | # Custom matches function
21 | if 'matchesFunction' in kwargs:
22 | self.matchesFunction = kwargs['matchesFunction']
23 | del kwargs['matchesFunction']
24 | else:
25 | def matches(fieldValue, acListEntry):
26 | pattern = re.compile('.*' + re.escape(fieldValue) + '.*', re.IGNORECASE)
27 | return re.match(pattern, str(acListEntry))
28 |
29 | self.matchesFunction = matches
30 |
31 | Entry.__init__(self, *args, **kwargs)
32 | self.focus()
33 |
34 | self.autocompleteList = autocompleteList
35 |
36 | self.var = self["textvariable"]
37 | if self.var == '':
38 | self.var = self["textvariable"] = StringVar()
39 |
40 | self.var.trace('w', self.changed)
41 | self.bind("", self.selection)
42 | self.bind("", self.moveUp)
43 | self.bind("", self.moveDown)
44 | self.bind("", self.selection)
45 |
46 | self.listboxUp = False
47 |
48 | def changed(self, name, index, mode):
49 | if self.var.get() == '':
50 | if self.listboxUp:
51 | self.listbox.destroy()
52 | self.listboxUp = False
53 | else:
54 | words = self.comparison()
55 | if words:
56 | if not self.listboxUp:
57 | self.listbox = Listbox(self.master, height=self.listboxLength)
58 | self.listbox.bind("", self.selection)
59 | self.listbox.bind("", self.selection)
60 | self.listbox.bind("", self.selection)
61 | self.listbox.place(x=self.winfo_x(),
62 | y=self.winfo_y() +
63 | self.winfo_height(),
64 | width=self.winfo_width())
65 | self.listboxUp = True
66 |
67 | self.listbox.delete(0, END)
68 | for w in words:
69 | self.listbox.insert(END,w)
70 | else:
71 | if self.listboxUp:
72 | self.listbox.destroy()
73 | self.listboxUp = False
74 |
75 | def selection(self, event=None):
76 | if self.listboxUp:
77 | self.var.set(self.listbox.get(ACTIVE))
78 | self.listbox.destroy()
79 | self.listboxUp = False
80 | self.icursor(END)
81 |
82 | def moveUp(self, event):
83 | if self.listboxUp:
84 | if self.listbox.curselection() == ():
85 | index = '0'
86 | else:
87 | index = self.listbox.curselection()[0]
88 |
89 | if index != '0':
90 | self.listbox.selection_clear(first=index)
91 | index = str(int(index) - 1)
92 |
93 | self.listbox.see(index) # Scroll!
94 | self.listbox.selection_set(first=index)
95 | self.listbox.activate(index)
96 |
97 | def moveDown(self, event):
98 | if self.listboxUp:
99 | if self.listbox.curselection() == ():
100 | index = '-1'
101 | else:
102 | index = self.listbox.curselection()[0]
103 |
104 | if index != END:
105 | self.listbox.selection_clear(first=index)
106 | index = str(int(index) + 1)
107 |
108 | self.listbox.see(index) # Scroll!
109 | self.listbox.selection_set(first=index)
110 | self.listbox.activate(index)
111 |
112 | def comparison(self):
113 | if isinstance(self.autocompleteList, (list,tuple,set)):
114 | possibilities = self.autocompleteList
115 | elif callable(self.autocompleteList):
116 | possibilities = self.autocompleteList()
117 | entry = self.var.get()
118 | ans = [ str(w) for w in possibilities
119 | if self.matchesFunction(entry, w) ]
120 | # If there is an exact match, move it to the front
121 | ans = sorted(ans)
122 | if entry in ans:
123 | ans.remove(entry)
124 | ans.insert(0, entry)
125 | return ans
126 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | NetworkX Viewer
2 | ================
3 |
4 |
5 | Introduction
6 | ------------
7 |
8 | NetworkX Viewer provides a basic interactive GUI to view
9 | [networkx](https://networkx.github.io/) graphs. In addition to standard
10 | plotting and layout features as found natively in networkx, the GUI allows
11 | you to:
12 |
13 | - Drag nodes around to tune the default layout
14 | - Show and hide nodes
15 | - Filter nodes
16 | - Pan and zoom
17 | - Display nodes only within a certain number of hops ("levels") of
18 | a "home node"
19 | - Display and highlight the shortest path between two nodes. Nodes
20 | around the path can also be displayed within a settable number of
21 | levels
22 | - Intelligently find and display nodes near displayed nodes using
23 | "Grow" and "Grow Until" functions
24 | - Use attributes stored in the graph's node and edge dictionaries to
25 | customize the appearance of the node and edge tokens in the GUI
26 | - Mark nodes and edges for reference
27 | - Support for both `nx.Graph` and `nx.MultiGraph`
28 |
29 | A typical usage might be:
30 | ```python
31 | import networkx as nx
32 | from networkx_viewer import Viewer
33 |
34 | G = nx.MultiGraph()
35 | G.add_edge('a','b')
36 | G.add_edge('b','c')
37 | G.add_edge('c','a',0, fill='green')
38 | G.add_edge('c','d')
39 | G.add_edge('c','d',1, dash=(2,2))
40 | G.nodes['a']['outline'] = 'blue'
41 | G.nodes['d']['label_fill'] = 'red'
42 |
43 | app = Viewer(G)
44 | app.mainloop()
45 | ```
46 |
47 | The result will be:
48 |
49 | 
50 |
51 | Installation
52 | ------------
53 |
54 | NetworkX Viewer is hosted on PyPI and can be installed by simply doing the
55 | following.
56 | ```
57 | pip install networkx-viewer
58 | ```
59 |
60 | NetworkX Viewer requires [NetworkX](https://networkx.github.io/) version 3.2 or greater.
61 |
62 |
63 | Using the GUI
64 | -------------
65 | The default layout for the nodes is to use `nx.spring_layout`. While this
66 | layout is pretty good, it is not perfect, so the GUI supports standard features
67 | like rearranging the nodes, panning, and zooming.
68 |
69 | By default, the viewer will display the entire graph on initialization.
70 | However, most of the power in the GUI comes in showing a subset of the graph.
71 | You can specify a subgraph to display using:
72 | ```python
73 | app = Viewer(G, home_node='a', levels=1)
74 | ```
75 |
76 | ### Constructing a plot
77 |
78 | On the right of the screen is a box to enter node(s) to graph.
79 | - If you enter a single node, that node plus nodes upto "Neighbor Levels"
80 | levels will be ploted.
81 | - If you enter a pair of nodes, the shortest path between the nodes will
82 | be found. Neighbors around the path upto "Neighbor Levels" will also
83 | be plotted
84 | - If you enter three or more nodes, all those nodes will graphed out to
85 | "Neighbor Levels"
86 |
87 | You may either "Build New" or "Add to Existing." If you choose to add to the
88 | existing plot, and a path exists between the new node and your existing display
89 | island, you will be prompted if you'd like the program to plot the intermediate
90 | nodes.
91 |
92 | ### Right-click functionality
93 |
94 | Several actions can be taken by right-clicking on nodes and edges, including
95 | - *Grow:* Display all nodes connected to this node that may not be
96 | currently displayed. A node which does not have all of its neighbors
97 | currently displayed will have a grey label.
98 | - *Grow Until:* This lets you find the path between this node and a node
99 | with a desired attribute. This is done by provided a lambda function
100 | which may accept the following arguments:
101 | - `u` - Name of the Node
102 | - `d` - The data dictionary for the node (ie, the contents of `G.node[u]`)
103 |
104 | Say we had a graph which has nodes which are actors and
105 | edges which are the movie the two actors were both in. A
106 | [classic example](http://en.wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon)
107 | might be to use the lambda function:
108 | ```python
109 | u=='Kevin Bacon'
110 | ```
111 | to find who the degrees of seperation are between the right-clicked actor
112 | and Kevin Bacon.
113 | - *Hide*
114 | - *Hide Behind:* Hide radial sections of the graph that are behind the edge
115 | formed by the node the cursor is currently over and the node in the menu.
116 | Note: if the graph is not radial behind the selected node, this item is
117 | greyed out in the dropdown.
118 |
119 | You can also simply hover over a node and press the shortcut key ("G" for
120 | grow, "H" for hide, etc...) to activate the action.
121 |
122 | ### Filtering
123 | You can filter the nodes to display based on the attributes a node possess.
124 | This is done in a simmilar manner to how *Grow Until* works, as described above.
125 | You must write a lambda function which accepts the following paramaters:
126 | - `u` - Name of the Node
127 | - `d` - The data dictionary for the node (ie, the contents of `G.node[u]`)
128 |
129 | When this lambda function evaluates to `False`, the node is hidden, otherwise
130 | the node is displayed. Multiple Filters are ANDed together.
131 |
132 | ### Node and Edge Attributes
133 | The attributes (ie, the dictionary stored in `G.node[u]` and `G.edge[u][v]`)
134 | are displayed in the lower-right section of the screen.
135 |
136 | At this time, neither the attributes not the graph's nodes/edges themselves
137 | are editable through the GUI. The GUI is read-only. You should programatically
138 | create/update the graph by doing the following:
139 | ```python
140 | G = app.canvas.dataG
141 | # code to edit graph
142 | app.canvas.refresh()
143 |
144 | ```
145 |
146 | Using the Tk Pass-through
147 | -------------------------
148 | If the data dictionary stored in the graph for an edge or node contains a key
149 | that can be used by Tk, the token will be customized as such. Specifically,
150 |
151 | - If a node contains a key used to configure
152 | [Tkinter.Canvas.create_oval][1], it will be used to customize the node's
153 | marker (ie, the red circle).
154 | - If a node contains a key prefixed with "label_" (for example, "label_font"
155 | or "label_fill") that can be used to configure
156 | [Tkinter.Canvas.create_text][2], it will be used to customize the node's
157 | label.
158 | - If an edge contains a key which can be used by
159 | [Tkinter.Canvas.create_line][3], it will be used to customize the edge's
160 | display properties.
161 |
162 | [1]: http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.create_oval-method
163 | [2]: http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.create_text-method
164 | [3]: http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.create_line-method
165 |
166 | Expanding and Customizing the GUI
167 | ---------------------------------
168 | The core Tk widget that is implemented by networkx_viewer is the `GraphCanvas`
169 | widget. If you simply wish to use the GUI as presented as part of a larger
170 | application, you can just instantiate the canvas, passing it the graph to
171 | display as an argument and pack or grid it into your Tk application like any
172 | other canvas widget.
173 |
174 | If you wish to change the tokens used for edges or nodes, subclass `NodeToken`
175 | or `EdgeToken` and pass as an argument into the GraphCanvas as such. For
176 | example:
177 |
178 | ```python
179 | import tkinter as tk
180 | import networkx as nx
181 | from networkx_viewer import NodeToken, GraphCanvas
182 |
183 | class CustomNodeToken(NodeToken):
184 | def render(self, data, node_name):
185 | """Example of custom Node Token
186 | Draw a circle if the node's data says we are a circle, otherwise
187 | draw us as a rectangle. Also, if data contains a color key,
188 | use that as our color (default, red)
189 | """
190 | # For our convenience, the render method is called with the
191 | # graph's data attributes and the name of the node in the graph
192 |
193 | # Note that NodeToken is a subclass of Tkinter.Canvas, so we
194 | # simply draw on ourselves to create the apperance for the node.
195 |
196 | # Make us 50 pixles big
197 | self.config(width=50, height=50)
198 |
199 | # Set color and other options
200 | marker_options = {'fill': data.get('color','red'),
201 | 'outline': 'black'}
202 |
203 | # Draw circle or square, depending on what the node said to do
204 | if data.get('circle', None):
205 | self.create_oval(0,0,50,50, **marker_options)
206 | else:
207 | self.create_rectangle(0,0,50,50, **marker_options)
208 |
209 | class ExampleApp(tk.Tk):
210 | def __init__(self, graph, **kwargs):
211 | tk.Tk.__init__(self)
212 |
213 | self.canvas = GraphCanvas(graph, NodeTokenClass=CustomNodeToken,
214 | **kwargs)
215 | self.canvas.grid(row=0, column=0, sticky='NESW')
216 |
217 | G = nx.path_graph(5)
218 | G.nodes[2]['circle'] = True
219 | G.nodes[3]['color'] = 'blue'
220 |
221 | app = ExampleApp(G)
222 | app.mainloop()
223 |
224 | ```
225 |
226 | Development Status
227 | ==================
228 | As of May 2024, networkx_viewer is considered feature complete. No
229 | additional development is expected. Bugs or feature
230 | requests should be submitted to the
231 | [github issue tracker](https://github.com/jsexauer/networkx_viewer/issues).
232 |
233 | Many thanks to [Faith Eser](https://github.com/afeser) for doing the majority of the
234 | development work to make this library work with networkx version 2.2+ and
235 | [Phillip Feldman](https://github.com/PhillipFeldman) for networkx version 3.3+.
236 |
237 |
--------------------------------------------------------------------------------
/networkx_viewer/tokens.py:
--------------------------------------------------------------------------------
1 | try:
2 | # Python 3
3 | import tkinter as tk
4 | except ImportError:
5 | # Python 2
6 | import Tkinter as tk
7 |
8 | class NodeToken(tk.Canvas):
9 | def __init__(self, host_canvas, data, node_name):
10 | tk.Canvas.__init__(self, width=20, height=20, highlightthickness=0)
11 |
12 | self._host_canvas = host_canvas
13 | self._complete = True
14 | self._marked = False
15 | self._default_bg = None
16 |
17 | self.bind('', self._host_event('onNodeButtonPress'))
18 | self.bind('', self._host_event('onNodeButtonRelease'))
19 | self.bind('', self._host_event('onNodeMotion'))
20 |
21 | self.bind('', self._host_event('onTokenRightClick'))
22 |
23 | self.bind('', self._host_event('onNodeKey'))
24 | self.bind('', lambda e: self.focus_set())
25 | self.bind('', lambda e: self.master.focus())
26 |
27 | # Draw myself
28 | self.render(data, node_name)
29 |
30 | def render(self, data, node_name):
31 | """Draw on canvas what we want node to look like"""
32 | self.create_oval(5,5,15,15, fill='red',outline='black')
33 |
34 |
35 | def mark(self):
36 | """Mark the token just so it's easy for the user to pick out"""
37 | if self._marked:
38 | self.config(bg=self._default_bg)
39 | else:
40 | self._default_bg = self['background']
41 | self.config(bg='yellow')
42 | self._marked = not self._marked
43 |
44 | def mark_complete(self):
45 | """Called by host canvas when all of my edges have been drawn"""
46 | if not self._complete:
47 | self._complete = True
48 |
49 | def mark_incomplete(self):
50 | """Called by host canvas when all of my edges have not been drawn"""
51 | if self._complete:
52 | self._complete = False
53 |
54 | @property
55 | def is_marked(self):
56 | return self._marked
57 |
58 | @property
59 | def is_complete(self):
60 | """Returns True if all edges have been drawn"""
61 | return self._complete
62 |
63 | def customize_menu(self, menu, item):
64 | """Ovewrite this method to customize the menu this token displays
65 | when it is right-clicked"""
66 | pass
67 |
68 |
69 | def _host_event(self, func_name):
70 | """Wrapper to correct the event's x,y coordinates and pass to host
71 | canvas. Argument should be string of name of function from
72 | _host_canvas to call."""
73 | func = getattr(self._host_canvas, func_name)
74 | def _wrapper(event):
75 | # Modify even to be relative to the host's canvas
76 | event.x += self.winfo_x()
77 | event.y += self.winfo_y()
78 | return func(event)
79 | return _wrapper
80 |
81 | def __getstate__(self):
82 | """Because the token object is a live tk object, we must save our
83 | state variables and reconstruct ourselves instead of letting python
84 | try to automatically pickle us"""
85 | ans = {
86 | '_complete': self._complete,
87 | '_default_bg': self._default_bg,
88 | '_marked': self._marked,
89 | }
90 | return ans
91 |
92 |
93 | def _setstate(self, state):
94 | """Set state from pickle. See __getstate__ for details. Not
95 | __setstate__ because this must be a live tk object to work and python
96 | could call __setstate__ on an "undead" object."""
97 | for k,v in state.items():
98 | setattr(self, k, v)
99 |
100 | # Make sure we display our marked status
101 | if state['_marked']:
102 | self._marked = False # Have to undo what we did in for loop above
103 | self.mark()
104 |
105 | class EdgeToken(object):
106 | def __init__(self, edge_data):
107 | """This object mimics a token for the edges. All of this class's
108 | returned values are used to configure the actual line drawn
109 | on the host canvas"""
110 | self.edge_data = edge_data
111 | self._marked = False
112 | self._spline_id = None
113 | self._host_canvas = None
114 |
115 | def render(self, host_canvas, coords, cfg=None, directed=False):
116 | """Called whenever canvas is about to draw an edge.
117 | The host_canvas will be the GraphCanvas object.
118 | coords is a tuple of the following, use to display the spline which
119 | represents the edge.
120 | - x1,y1 -- Position of the start of the spline
121 | - xa,ya -- Position of the midpoint of spline
122 | - x2,y2 -- Position of the end of teh spline
123 | """
124 | if cfg is None:
125 | cfg = self.render_cfg()
126 | # Amend config options to include options which must be included
127 | cfg['tags'] = 'edge'
128 | cfg['smooth'] = True
129 | if directed:
130 | # Add arrow
131 | cfg['arrow'] = tk.LAST
132 | cfg['arrowshape'] = (30,40,5)
133 | self._spline_id = host_canvas.create_line(*coords, **cfg)
134 | self._host_canvas = host_canvas
135 |
136 | def itemconfig(self, cfg=None):
137 | """Update item config for underlying spline. If cfg is none,
138 | auto-regenerate cfg from render_cfg method"""
139 | if cfg is None:
140 | cfg = self.render_cfg()
141 | assert self._host_canvas is not None, "Must draw using render method first"
142 | self._host_canvas.itemconfig(self._spline_id, cfg)
143 |
144 | def coords(self, coords):
145 | """Update coordinates for spline."""
146 | assert self._host_canvas is not None, "Must draw using render method first"
147 | return self._host_canvas.coords(self._spline_id, coords)
148 |
149 | def delete(self):
150 | """Remove spline from canvas"""
151 | self._host_canvas.delete(self._spline_id)
152 |
153 | def render_cfg(self):
154 | """Creates config dict used by host canvas's create_line
155 | method to draw the spline"""
156 | return {}
157 |
158 | @property
159 | def id(self):
160 | """Returns id of spline drawn on host canvas"""
161 | return self._spline_id
162 |
163 | def mark(self):
164 | """Return config dictionary when toggling mark status"""
165 | mark_width = 4.0
166 |
167 | self._marked = not self._marked
168 | cfg = {}
169 | if self._marked:
170 | cfg = {'width': mark_width}
171 | else:
172 | cfg = {'width': 1.0}
173 |
174 | self.itemconfig(cfg)
175 |
176 | @property
177 | def is_marked(self):
178 | return self._marked
179 |
180 | def customize_menu(self, menu):
181 | """Ovewrite this method to customize the menu this token displays
182 | when it is right-clicked"""
183 | pass
184 |
185 | def __getstate__(self):
186 | """Because the token object is a live tk object, we must save our
187 | state variables and reconstruct ourselves instead of letting python
188 | try to automatically pickle us"""
189 | ans = {
190 | '_marked': self._marked,
191 | }
192 | return ans
193 |
194 | def _setstate(self, state):
195 | """Set state from pickle. See __getstate__ for details. Not
196 | __setstate__ because this must be a live tk object to work and python
197 | could call __setstate__ on an "undead" object."""
198 | for k,v in state.items():
199 | setattr(self, k, v)
200 |
201 | # Make sure we display our marked status
202 | if state['_marked']:
203 | self._marked = False # Have to undo what we did in for loop above
204 | self.mark()
205 |
206 |
207 | class TkPassthroughNodeToken(NodeToken):
208 | def __init__(self, *args, **kwargs):
209 | self._default_label_color = 'black'
210 | self._default_outline_color = 'black'
211 |
212 | NodeToken.__init__(self, *args, **kwargs)
213 |
214 |
215 | def render(self, data, node_name):
216 | """Draw on canvas what we want node to look like. If data contains
217 | keys that can configure a tk.Canvas oval, it will do so. If data
218 | contains keys that start with "label_" and can configure a text
219 | object, it will configure the text."""
220 |
221 | # Take a first cut at creating the marker and label
222 | self.label = self.create_text(0, 0, text=node_name)
223 | self.marker = self.create_oval(0, 0, 10, 10,
224 | fill='red',outline='black')
225 |
226 | # Modify marker using options from data
227 | cfg = self.itemconfig(self.marker)
228 | for k,v in cfg.copy().items():
229 | cfg[k] = data.get(k, cfg[k][-1])
230 | self.itemconfig(self.marker, **cfg)
231 | self._default_outline_color = data.get('outline',self._default_outline_color)
232 |
233 | # Modify the text label using options from data
234 | cfg = self.itemconfig(self.label)
235 | for k,v in cfg.copy().items():
236 | cfg[k] = data.get('label_'+k, cfg[k][-1])
237 | self.itemconfig(self.label, **cfg)
238 | self._default_label_color = data.get('label_fill',self._default_label_color)
239 |
240 | # Figure out how big we really need to be
241 | bbox = self.bbox(self.label)
242 | bbox = [abs(x) for x in bbox]
243 | br = ( max((bbox[0] + bbox[2]),20), max((bbox[1]+bbox[3]),20) )
244 |
245 | self.config(width=br[0], height=br[1]+7)
246 |
247 | # Place label and marker
248 | mid = ( int(br[0]/2.0), int(br[1]/2.0)+7 )
249 | self.coords(self.label, mid)
250 | self.coords(self.marker, mid[0]-5,0, mid[0]+5,10)
251 |
252 |
253 | def mark_complete(self):
254 | """Called by host canvas when all of my edges have been drawn"""
255 | self._complete = True
256 | self.itemconfig(self.marker, outline=self._default_outline_color)
257 | self.itemconfig(self.label, fill=self._default_label_color)
258 |
259 | def mark_incomplete(self):
260 | """Called by host canvas when all of my edges have not been drawn"""
261 | self._complete = False
262 | self.itemconfig(self.marker, outline='')
263 | self.itemconfig(self.label, fill='grey')
264 |
265 |
266 | class TkPassthroughEdgeToken(EdgeToken):
267 | _tk_line_options = [
268 | 'stipple', 'activefill', 'joinstyle', 'dash',
269 | 'disabledwidth', 'dashoffset', 'activewidth', 'fill', 'splinesteps',
270 | 'offset', 'disabledfill', 'disableddash', 'width', 'state',
271 | 'disabledstipple', 'activedash', 'tags', 'activestipple',
272 | 'capstyle', 'arrowshape', 'smooth', 'arrow'
273 | ]
274 | _marked_width = 4.0
275 |
276 | def render_cfg(self):
277 | """Called whenever canvas is about to draw an edge.
278 | Must return dictionary of config options for create_line"""
279 | cfg = {}
280 | for k in self._tk_line_options:
281 | v = self.edge_data.get(k, None)
282 | if v:
283 | cfg[k] = v
284 | self._native_width = cfg.get('width', 1.0)
285 | return cfg
286 |
287 | def mark(self):
288 | """Return config dictionary when toggling marked status"""
289 | self._marked = not self._marked
290 |
291 | cfg = {}
292 | if self._marked:
293 | cfg = {'width': self._marked_width}
294 | else:
295 | cfg = {'width': self._native_width}
296 |
297 | self.itemconfig(cfg)
298 |
--------------------------------------------------------------------------------
/networkx_viewer/viewer.py:
--------------------------------------------------------------------------------
1 | try:
2 | # Python 3
3 | import tkinter as tk
4 | import tkinter.messagebox as tkm
5 | import tkinter.simpledialog as tkd
6 | except ImportError:
7 | # Python 2
8 | import Tkinter as tk
9 | import tkMessageBox as tkm
10 | import tkSimpleDialog as tkd
11 |
12 |
13 |
14 | import networkx as nx
15 |
16 | from networkx_viewer.graph_canvas import GraphCanvas
17 | from networkx_viewer.tokens import TkPassthroughEdgeToken, TkPassthroughNodeToken
18 | from networkx_viewer.autocomplete_entry import AutocompleteEntry
19 |
20 |
21 | class ViewerApp(tk.Tk):
22 | """Example simple GUI to plot a NetworkX Graph"""
23 | def __init__(self, graph, **kwargs):
24 | """Additional keyword arguments beyond graph are passed down to the
25 | GraphCanvas. See it's docs for details"""
26 | tk.Tk.__init__(self)
27 | self.geometry('1000x600')
28 | self.title('NetworkX Viewer')
29 |
30 | bottom_row = 10
31 | self.columnconfigure(0, weight=1)
32 | self.rowconfigure(bottom_row, weight=1)
33 |
34 | self.canvas = GraphCanvas(graph, width=400, height=400, **kwargs)
35 | self.canvas.grid(row=0, column=0, rowspan=bottom_row+2, sticky='NESW')
36 | self.canvas.onNodeSelected = self.onNodeSelected
37 | self.canvas.onEdgeSelected = self.onEdgeSelected
38 |
39 | r = 0 # Current row
40 | tk.Label(self, text='Nodes:').grid(row=r, column=1, sticky='W')
41 | self.node_entry = AutocompleteEntry(self.canvas.dataG.nodes)
42 | self.node_entry.bind('',self.add_node, add='+')
43 | self.node_entry.bind('', self.buildNewShortcut, add='+')
44 | self.node_entry.grid(row=r, column=2, columnspan=2, sticky='NESW', pady=2)
45 | tk.Button(self, text='+', command=self.add_node, width=2).grid(
46 | row=r, column=4,sticky=tk.NW,padx=2,pady=2)
47 |
48 | r += 1
49 | nlsb = tk.Scrollbar(self, orient=tk.VERTICAL)
50 | self.node_list = tk.Listbox(self, yscrollcommand=nlsb.set, height=5)
51 | self.node_list.grid(row=r, column=1, columnspan=3, sticky='NESW')
52 | self.node_list.bind('',lambda e: self.node_list.delete(tk.ANCHOR))
53 | nlsb.config(command=self.node_list.yview)
54 | nlsb.grid(row=r, column=4, sticky='NWS')
55 |
56 | r += 1
57 | tk.Label(self, text='Neighbors Levels:').grid(row=r, column=1,
58 | columnspan=2, sticky=tk.NW)
59 | self.level_entry = tk.Entry(self, width=4)
60 | self.level_entry.insert(0,'1')
61 | self.level_entry.grid(row=r, column=3, sticky=tk.NW, padx=5)
62 |
63 | r += 1
64 | tk.Button(self, text='Build New', command=self.onBuildNew).grid(
65 | row=r, column=1)
66 | tk.Button(self, text='Add to Existing', command=self.onAddToExisting
67 | ).grid(row=r, column=2, columnspan=2)
68 |
69 | r += 1
70 | line = tk.Canvas(self, height=15, width=200)
71 | line.create_line(0,13,250,13)
72 | line.create_line(0,15,250,15)
73 | line.grid(row=r, column=1, columnspan=4, sticky='NESW')
74 |
75 | r += 1
76 | tk.Label(self, text='Filters:').grid(row=r, column=1, sticky=tk.W)
77 | self.filter_entry = tk.Entry(self)
78 | self.filter_entry.bind('',self.add_filter, add='+')
79 | self.filter_entry.grid(row=r, column=2, columnspan=2, sticky='NESW', pady=2)
80 | tk.Button(self, text='+', command=self.add_filter, width=2).grid(
81 | row=r, column=4,sticky=tk.NW,padx=2,pady=2)
82 |
83 | r += 1
84 | flsb = tk.Scrollbar(self, orient=tk.VERTICAL)
85 | self.filter_list = tk.Listbox(self, yscrollcommand=flsb.set, height=5)
86 | self.filter_list.grid(row=r, column=1, columnspan=3, sticky='NESW')
87 | self.filter_list.bind('',self.remove_filter)
88 | flsb.config(command=self.node_list.yview)
89 | flsb.grid(row=r, column=4, sticky='NWS')
90 |
91 | r += 1
92 | tk.Button(self, text='Clear',command=self.remove_filter).grid(
93 | row=r, column=1, sticky='W')
94 | tk.Button(self, text='?', command=self.filter_help
95 | ).grid(row=r, column=4, stick='NESW', padx=2)
96 |
97 |
98 | r += 1
99 | line2 = tk.Canvas(self, height=15, width=200)
100 | line2.create_line(0,13,250,13)
101 | line2.create_line(0,15,250,15)
102 | line2.grid(row=r, column=1, columnspan=4, sticky='NESW')
103 |
104 | r += 1
105 | self.lbl_attr = tk.Label(self, text='Attributes',
106 | wraplength=200, anchor=tk.SW, justify=tk.LEFT)
107 | self.lbl_attr.grid(row=r, column=1, columnspan=4, sticky='NW')
108 |
109 | r += 1
110 | self.tbl_attr = PropertyTable(self, {})
111 | self.tbl_attr.grid(row=r, column=1, columnspan=4, sticky='NESW')
112 |
113 | assert r == bottom_row, "Set bottom_row to %d" % r
114 |
115 | self._build_menu()
116 |
117 | def _build_menu(self):
118 | self.menubar = tk.Menu(self)
119 | self.config(menu=self.menubar)
120 |
121 | view = tk.Menu(self.menubar, tearoff=0)
122 | view.add_command(label='Undo', command=self.canvas.undo, accelerator="Ctrl+Z")
123 | self.bind_all("", lambda e: self.canvas.undo()) # Implement accelerator
124 | view.add_command(label='Redo', command=self.canvas.redo)
125 | view.add_separator()
126 | view.add_command(label='Center on node...', command=self.center_on_node)
127 | view.add_separator()
128 | view.add_command(label='Reset Node Marks', command=self.reset_node_markings)
129 | view.add_command(label='Reset Edge Marks', command=self.reset_edge_markings)
130 | view.add_command(label='Redraw Plot', command=self.canvas.replot)
131 | view.add_separator()
132 | view.add_command(label='Grow display one level...', command=self.grow_all)
133 |
134 | self.menubar.add_cascade(label='View', menu=view)
135 |
136 | def center_on_node(self):
137 | node = NodeDialog(self, "Name of node to center on:").result
138 | if node is None: return
139 | self.canvas.center_on_node(node)
140 |
141 | def reset_edge_markings(self):
142 | for u,v,k,d in self.canvas.dispG.edges(data=True, keys=True):
143 | token = d['token']
144 | if token.is_marked:
145 | self.canvas.mark_edge(u,v,k)
146 |
147 | def reset_node_markings(self):
148 | for u,d in self.canvas.dispG.nodes(data=True):
149 | token = d['token']
150 | if token.is_marked:
151 | self.canvas.mark_node(u)
152 |
153 | def add_node(self, event=None):
154 | node = self.node_entry.get()
155 |
156 | if node.isdigit() and self.canvas.dataG.has_node(int(node)):
157 | node = int(node)
158 |
159 | if self.canvas.dataG.has_node(node):
160 | self.node_list.insert(tk.END, node)
161 | self.node_entry.delete(0, tk.END)
162 | else:
163 | tkm.showerror("Node not found", "Node '%s' not in graph."%node)
164 |
165 | def add_filter(self, event=None, filter_lambda=None):
166 | if filter_lambda is None:
167 | filter_lambda = self.filter_entry.get()
168 |
169 | if self.canvas.add_filter(filter_lambda):
170 | # We successfully added the filter; add to list and clear entry
171 | self.filter_list.insert(tk.END, filter_lambda)
172 | self.filter_entry.delete(0, tk.END)
173 |
174 | def filter_help(self, event=None):
175 | msg = ("Enter a lambda function which returns True if you wish\n"
176 | "to show nodes with ONLY a given property.\n"
177 | "Parameters are:\n"
178 | " - u, the node's name, and \n"
179 | " - d, the data dictionary.\n\n"
180 | "Example: \n"
181 | " d.get('color',None)=='red'\n"
182 | "would show only red nodes.\n"
183 | "Example 2:\n"
184 | " str(u).is_digit()\n"
185 | "would show only nodes which have a numerical name.\n\n"
186 | "Multiple filters are ANDed together.")
187 | tkm.showinfo("Filter Condition", msg)
188 | def remove_filter(self, event=None):
189 | all_items = self.filter_list.get(0, tk.END)
190 | if event is None:
191 | # When no event passed, this function was called via the "clear"
192 | # button.
193 | items = all_items
194 | else:
195 | # Remove currently selected item
196 | items = (self.filter_list.get(tk.ANCHOR),)
197 |
198 | for item in items:
199 | self.canvas.remove_filter(item)
200 | idx = all_items.index(item)
201 | self.filter_list.delete(idx)
202 | all_items = self.filter_list.get(0, tk.END)
203 |
204 |
205 | def grow_all(self):
206 | """Grow all visible nodes one level"""
207 | for u, d in self.canvas.dispG.copy().nodes.items():
208 | if not d['token'].is_complete:
209 | self.canvas.grow_node(u)
210 |
211 | def get_node_list(self):
212 | """Get nodes in the node list and clear"""
213 | # See if we forgot to hit the plus sign
214 | if len(self.node_entry.get()) != 0:
215 | self.add_node()
216 | nodes = self.node_list.get(0, tk.END)
217 | self.node_list.delete(0, tk.END)
218 | return nodes
219 |
220 |
221 | def onBuildNew(self):
222 | nodes = self.get_node_list()
223 |
224 | if len(nodes) == 2:
225 | self.canvas.plot_path(nodes[0], nodes[1], levels=self.level)
226 | else:
227 | self.canvas.plot(nodes, levels=self.level)
228 |
229 | def onAddToExisting(self):
230 | """Add nodes to existing plot. Prompt to include link to existing
231 | if possible"""
232 | home_nodes = set(self.get_node_list())
233 | self.canvas.plot_additional(home_nodes, levels=self.level)
234 |
235 | def buildNewShortcut(self, event=None):
236 | # Add node intelligently then doe a build new
237 | self.node_entry.event_generate('') # Resolve current
238 | self.onBuildNew()
239 |
240 | def goto_path(self, event):
241 | frm = self.node_entry.get()
242 | to = self.node_entry2.get()
243 | self.node_entry.delete(0, tk.END)
244 | self.node_entry2.delete(0, tk.END)
245 |
246 | if frm == '':
247 | tkm.showerror("No From Node", "Please enter a node in both "
248 | "boxes to plot a path. Enter a node in only the first box "
249 | "to bring up nodes immediately adjacent.")
250 | return
251 |
252 | if frm.isdigit() and int(frm) in self.canvas.dataG.nodes():
253 | frm = int(frm)
254 | if to.isdigit() and int(to) in self.canvas.dataG.nodes():
255 | to = int(to)
256 |
257 | self.canvas.plot_path(frm, to, levels=self.level)
258 |
259 | def onNodeSelected(self, node_name, node_dict):
260 | self.tbl_attr.build(node_dict)
261 | self.lbl_attr.config(text="Attributes of node '%s'"%node_name)
262 |
263 | def onEdgeSelected(self, edge_name, edge_dict):
264 | self.tbl_attr.build(edge_dict)
265 | self.lbl_attr.config(text="Attributes of edge between '%s' and '%s'"%
266 | edge_name[:2])
267 |
268 | @property
269 | def level(self):
270 | try:
271 | l = int(self.level_entry.get())
272 | except ValueError:
273 | tkm.showerror("Invalid Level", "Please specify a level between "
274 | "greater than or equal to 0")
275 | raise
276 | return l
277 |
278 | class TkPassthroughViewerApp(ViewerApp):
279 | def __init__(self, graph, **kwargs):
280 | ViewerApp.__init__(self, graph,
281 | NodeTokenClass=TkPassthroughNodeToken,
282 | EdgeTokenClass=TkPassthroughEdgeToken, **kwargs)
283 |
284 |
285 | class PropertyTable(tk.Frame):
286 | """A pure Tkinter scrollable frame that actually works!
287 | * Use the 'interior' attribute to place widgets inside the scrollable frame
288 | * Construct and pack/place/grid normally
289 | * This frame only allows vertical scrolling
290 |
291 | """
292 | def __init__(self, parent, property_dict, *args, **kw):
293 | tk.Frame.__init__(self, parent, *args, **kw)
294 |
295 | # create a canvas object and a vertical scrollbar for scrolling it
296 | self.vscrollbar = vscrollbar = tk.Scrollbar(self, orient=tk.VERTICAL)
297 | vscrollbar.pack(fill=tk.Y, side=tk.RIGHT, expand=tk.FALSE)
298 | self.canvas = canvas = tk.Canvas(self, bd=0, highlightthickness=0,
299 | yscrollcommand=vscrollbar.set)
300 | canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=tk.TRUE)
301 | vscrollbar.config(command=canvas.yview)
302 |
303 | # reset the view
304 | canvas.xview_moveto(0)
305 | canvas.yview_moveto(0)
306 |
307 | # create a frame inside the canvas which will be scrolled with it
308 | self.interior = interior = tk.Frame(canvas)
309 | self.interior_id = canvas.create_window(0, 0, window=interior,
310 | anchor='nw')
311 |
312 | self.interior.bind('', self._configure_interior)
313 | self.canvas.bind('', self._configure_canvas)
314 |
315 | self.build(property_dict)
316 |
317 | def build(self, property_dict):
318 | for c in self.interior.winfo_children():
319 | c.destroy()
320 |
321 |
322 | # Filter property dict
323 | property_dict = {k: v for k, v in property_dict.items()
324 | if self._key_filter_function(k)}
325 |
326 | # Prettify key/value pairs for display
327 | property_dict = {self._make_key_pretty(k): self._make_value_pretty(v)
328 | for k, v in property_dict.items()}
329 |
330 | # Sort by key and filter
331 | dict_values = sorted(property_dict.items(), key=lambda x: x[0])
332 |
333 | for n,(k,v) in enumerate(dict_values):
334 | tk.Label(self.interior, text=k, borderwidth=1, relief=tk.SOLID,
335 | wraplength=75, anchor=tk.E, justify=tk.RIGHT).grid(
336 | row=n, column=0, sticky='nesw', padx=1, pady=1, ipadx=1)
337 | tk.Label(self.interior, text=v, borderwidth=1,
338 | wraplength=125, anchor=tk.W, justify=tk.LEFT).grid(
339 | row=n, column=1, sticky='nesw', padx=1, pady=1, ipadx=1)
340 |
341 | def _make_key_pretty(self, key):
342 | """Make key of property dictionary displayable
343 | Used by build function to make key displayable on the table.
344 | Args:
345 | key (object)
346 | Key of property dictionary from dataG
347 | Returns:
348 | label (str)
349 | String representation of key. Might be made shorter or with
350 | different name if desired.
351 | """
352 | return str(key)
353 |
354 | def _make_value_pretty(self, value):
355 | """Make key of property dictionary displayable
356 | Used by build function to make key displayable on the table.
357 | Args:
358 | key (object)
359 | Key of property dictionary from dataG
360 | Returns:
361 | label (str)
362 | String representation of key. Might be made shorter or with
363 | different name if desired.
364 | """
365 | label = str(value)
366 | if len(label) > 255:
367 | label = label[:253] + '...'
368 | return label
369 |
370 | def _key_filter_function(self, key):
371 | """Function to determine if key should be displayed.
372 | Called by build for each key in the propery dict. Overwrite
373 | with your implementation if you want to hide specific keys (all
374 | starting "_" for example).
375 | Args:
376 | key (object)
377 | Key of property dictionary from dataG
378 | Returns:
379 | display (bool)
380 | True if the key-value pair associate with this key should
381 | be displayed
382 | """
383 | # Should be more specifically implemented when subclassed
384 | return True # Show all keys
385 |
386 |
387 | def _configure_interior(self, event):
388 | """
389 | track changes to the canvas and frame width and sync them,
390 | also updating the scrollbar
391 | """
392 | # update the scrollbars to match the size of the inner frame
393 | size = (self.interior.winfo_reqwidth(), self.interior.winfo_reqheight())
394 | self.canvas.config(scrollregion="0 0 %s %s" % size)
395 | if self.interior.winfo_reqwidth() != self.canvas.winfo_width():
396 | # update the canvas's width to fit the inner frame
397 | self.canvas.config(width=self.interior.winfo_reqwidth())
398 |
399 |
400 | def _configure_canvas(self, event):
401 | if self.interior.winfo_reqwidth() != self.canvas.winfo_width():
402 | # update the inner frame's width to fill the canvas
403 | self.canvas.itemconfigure(self.interior_id, width=self.canvas.winfo_width())
404 |
405 |
406 | class NodeDialog(tk.Toplevel):
407 | def __init__(self, main_window, msg='Please enter a node:'):
408 | tk.Toplevel.__init__(self)
409 | self.main_window = main_window
410 | self.title('Node Entry')
411 | self.geometry('170x160')
412 | self.rowconfigure(3, weight=1)
413 |
414 | tk.Label(self, text=msg).grid(row=0, column=0, columnspan=2,
415 | sticky='NESW',padx=5,pady=5)
416 | self.posibilities = [d['dataG_id'] for n,d in
417 | main_window.canvas.dispG.nodes(data=True)]
418 | self.entry = AutocompleteEntry(self.posibilities, self)
419 | self.entry.bind('', lambda e: self.destroy(), add='+')
420 | self.entry.grid(row=1, column=0, columnspan=2, sticky='NESW',padx=5,pady=5)
421 |
422 | tk.Button(self, text='Ok', command=self.destroy).grid(
423 | row=3, column=0, sticky='ESW',padx=5,pady=5)
424 | tk.Button(self, text='Cancel', command=self.cancel).grid(
425 | row=3, column=1, sticky='ESW',padx=5,pady=5)
426 |
427 | # Make modal
428 | self.winfo_toplevel().wait_window(self)
429 |
430 |
431 | def destroy(self):
432 | res = self.entry.get()
433 | if res not in self.posibilities:
434 | res = None
435 | self.result = res
436 | tk.Toplevel.destroy(self)
437 |
438 | def cancel(self):
439 | self.entry.delete(0,tk.END)
440 | self.destroy()
441 |
--------------------------------------------------------------------------------
/networkx_viewer/tests.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from mock import patch
3 | import networkx as nx
4 |
5 | try:
6 | import networkx_viewer as nxv
7 | except ImportError:
8 | from . import __init__ as nxv
9 |
10 | import sys
11 |
12 | if sys.version_info > (3, 0):
13 | # Python 3 patching
14 | SHOWERROR_FUNC = 'tkinter.messagebox.showerror'
15 | ASKYESNO_FUNC = 'tkinter.messagebox.askyesno'
16 | else:
17 | # Python 2
18 | SHOWERROR_FUNC = 'tkMessageBox.showerror'
19 | ASKYESNO_FUNC = 'tkMessageBox.askyesno'
20 |
21 |
22 | class TestGraphCanvas(unittest.TestCase):
23 | def setUp(self):
24 | # Create the graph for testing
25 | G = nx.Graph()
26 | G.add_edge('a',2)
27 | G.add_edge(2,'c')
28 | G.add_edge('a','c')
29 | G.add_edge('a',4)
30 | G.add_edge(4,'c')
31 | G.add_edge('out','c')
32 | G.add_edge('c','d')
33 | G.add_edge('d',2)
34 | # Growth edges
35 | G.add_edge('out',11)
36 | G.add_edge('out',12)
37 | G.add_edge(12, 'd')
38 | G.add_edge('TTTTT',11)
39 | G.add_edge('qqqq', 'TTTTT')
40 | G.add_node('alone')
41 | self.input_G = G.copy()
42 |
43 | # Viewer under test
44 | self.a = nxv.GraphCanvas(G)
45 |
46 | def check_subgraph(self):
47 | """Verify that display graph is a subgraph of input"""
48 | dispG = self.a.dispG
49 | displayed_nodes = [d['dataG_id'] for n,d in dispG.nodes(data=True)]
50 | subdataG = self.input_G.subgraph(displayed_nodes)
51 |
52 | self.assertEqual(len(dispG), len(subdataG))
53 |
54 | for disp_node, data in dispG.nodes(data=True):
55 | data_node = data['dataG_id']
56 | # Make sure we're displaying all edges for all displayed nodes
57 | disp_deg = dispG.degree(disp_node)
58 | subdata_deg = subdataG.degree(data_node)
59 | data_deg = self.input_G.degree(data_node)
60 | token = data['token']
61 | self.assertEqual(disp_deg, subdata_deg,
62 | "Inconsistent edges for dataG:%s ; dispG:%s" %(data_node, disp_node))
63 |
64 | # If a node does not have all its edges drawn because the opposite
65 | # node is hidden, make sure we have it marked as "incomplete"
66 | if disp_deg == data_deg:
67 | self.assertEqual(token.is_complete, True)
68 | elif disp_deg < data_deg:
69 | self.assertEqual(token.is_complete, False)
70 | else:
71 | self.fail("Display graph has more edges than data graph?")
72 |
73 | def check_num_nodes_edges(self, number_of_nodes, number_of_edges):
74 | self.assertEqual(len(self.a.dispG), number_of_nodes)
75 | self.assertEqual(len(self.a.dispG.edges()), number_of_edges)
76 |
77 | def display_a(self):
78 | """Change the canvas to show 2 levels away form node 'a'
79 | This is kind of my standard testing position"""
80 | self.a.clear()
81 | self.a.plot(home_node='a', levels=2)
82 |
83 | def test_full_graph(self):
84 | self.check_subgraph()
85 |
86 | for disp_node, disp_data in self.a.dispG.nodes(data=True):
87 | token = disp_data['token']
88 | self.assertEqual(token.is_complete, True)
89 |
90 | def test_partial_graph(self):
91 | self.display_a()
92 | self.check_subgraph()
93 | self.assertEqual(len(self.a.dispG), 6)
94 | self.check_num_nodes_edges(6, 8)
95 |
96 | self.a.clear()
97 | self.a.plot(home_node=11, levels=1)
98 | self.check_subgraph()
99 | self.check_num_nodes_edges(3, 2)
100 |
101 | def test_alone(self):
102 | self.a.clear()
103 | self.a.plot('alone')
104 |
105 | self.check_subgraph()
106 | self.check_num_nodes_edges(1,0)
107 |
108 | def test_grow(self):
109 | self.display_a()
110 | out = self.a._find_disp_node('out')
111 |
112 | self.a.grow_node(out)
113 | self.check_subgraph()
114 |
115 | self.check_num_nodes_edges(8, 11)
116 |
117 | def test_hide(self):
118 | self.display_a()
119 | out = self.a._find_disp_node('c')
120 |
121 | self.a.hide_node(out)
122 | self.check_subgraph()
123 |
124 | self.check_num_nodes_edges(5, 3)
125 |
126 | def test_hide_behind(self):
127 | # Center the graph around node "out"
128 | self.a.clear()
129 | self.a.plot(home_node='out', levels=2)
130 |
131 | home = self.a._find_disp_node('out')
132 | behind = self.a._find_disp_node(11)
133 |
134 | self.a.hide_behind(home, behind)
135 | self.check_subgraph()
136 |
137 | self.check_num_nodes_edges(7, 10)
138 |
139 | def test_hide_behind_error(self):
140 | # We can't hind behind a non-radial set
141 | home = self.a._find_disp_node('a')
142 | behind = self.a._find_disp_node('c')
143 |
144 | with self.assertRaises(ValueError):
145 | self.a.hide_behind(home, behind)
146 |
147 | def test_plot_path(self):
148 | self.a.plot_path('a', 'out', levels=0)
149 | self.check_subgraph()
150 |
151 | self.check_num_nodes_edges(3, 2)
152 |
153 | #########
154 | self.a.plot_path('a', 'out', levels=1)
155 | self.check_subgraph()
156 |
157 | self.check_num_nodes_edges(8, 11)
158 |
159 | #########
160 | self.a.plot_path('a', 'out', levels=2)
161 | self.check_subgraph()
162 |
163 | self.check_num_nodes_edges(9, 12)
164 |
165 | def test_plot_three_connected(self):
166 | self.a.plot(['a','c','qqqq'])
167 | self.check_subgraph()
168 |
169 | # No islands
170 | ni = nx.number_connected_components(self.a.dispG)
171 | self.assertEqual(ni, 1)
172 |
173 | # Make sure the path that conects the a,c group to qqqq
174 | # is displayed (ie, node 11 and TTTT are in the graph
175 | node_11 = self.a._find_disp_node(11)
176 | TTTTT = self.a._find_disp_node('TTTTT')
177 | self.assertIsNot(node_11, None)
178 | self.assertIsNot(TTTTT, None)
179 |
180 | self.check_num_nodes_edges(9, 11)
181 |
182 | def test_plot_three_no_connection(self):
183 | self.a.plot(['a','qqqq','alone'])
184 |
185 | # There should be two islands (a-11-TTTTT-qqqq and alone)
186 | ni = nx.number_connected_components(self.a.dispG)
187 | self.assertEqual(ni, 2)
188 |
189 | # a and qqqq should be connected via 11 and TTTTT
190 | self.check_num_nodes_edges(9, 9)
191 | node_11 = self.a._find_disp_node(11)
192 | TTTTT = self.a._find_disp_node('TTTTT')
193 | self.assertIsNot(node_11, None)
194 | self.assertIsNot(TTTTT, None)
195 |
196 | def test_plot_path_error_no_node(self):
197 | self.a.clear()
198 | with patch(SHOWERROR_FUNC) as errorMsgBox:
199 | self.a.plot_path('a','bad')
200 |
201 | self.check_num_nodes_edges(0, 0)
202 | self.assertTrue(errorMsgBox.called)
203 |
204 | def test_plot_path_error_no_path(self):
205 | self.a.clear()
206 | with patch(SHOWERROR_FUNC) as errorMsgBox:
207 | self.a.plot_path('a','alone')
208 |
209 | self.check_num_nodes_edges(0, 0)
210 | self.assertTrue(errorMsgBox.called)
211 |
212 | def test_mark_node(self):
213 | a = self.a._find_disp_node('a')
214 | token = self.a.dispG.nodes[a]['token']
215 | self.a.mark_node(a)
216 | self.assertEqual(token._marked, True)
217 | self.assertEqual(token['background'], 'yellow')
218 |
219 | # Unmark
220 | self.a.mark_node(a)
221 | self.assertEqual(token._marked, False)
222 | self.assertEqual(token['background'], token._default_bg)
223 |
224 | def test_mark_edge(self):
225 | c = self.a._find_disp_node('c')
226 | out = self.a._find_disp_node('out')
227 |
228 | token = self.a.dispG.get_edge_data(c, out, 0)['token']
229 | self.a.mark_edge(c, out, 0)
230 | cfg = self.a.itemconfig(self.a.dispG.get_edge_data(c, out, 0)['token'].id)
231 | self.assertEqual(token._marked, True)
232 | self.assertEqual(cfg['width'][-1], '4.0')
233 |
234 | # Unmark
235 | self.a.mark_edge(c, out, 0)
236 | cfg = self.a.itemconfig(self.a.dispG.get_edge_data(c, out, 0)['token'].id)
237 | self.assertEqual(token._marked, False)
238 | self.assertEqual(cfg['width'][-1], '1.0')
239 |
240 | def test_plot_list(self):
241 | self.a.clear()
242 | self.a.plot(['a','c','d'])
243 | self.check_subgraph()
244 | displayed = [d['dataG_id'] for n,d in self.a.dispG.nodes(data=True)]
245 |
246 | for k in['a','c','d']:
247 | self.assertIn(k, displayed)
248 |
249 | def test_add_to_plot_with_path(self):
250 | # Test adding nodes around qqqq to a display showing nodes around a
251 | self.display_a()
252 |
253 | with patch(ASKYESNO_FUNC) as prompt:
254 | prompt.return_value = True # Yes, we want to include path
255 | self.a.plot_additional(set(['qqqq']), levels=1)
256 |
257 | self.assertTrue(prompt.called)
258 | self.check_subgraph()
259 | self.check_num_nodes_edges(9, 11)
260 | # All connected together
261 | self.assertEqual(nx.number_connected_components(self.a.dispG), 1)
262 |
263 | def test_add_to_plot_without_path(self):
264 | # Test adding nodes around qqqq to a display but as an island
265 | self.display_a()
266 |
267 | with patch(ASKYESNO_FUNC) as prompt:
268 | prompt.return_value = False # No, we don't want to include path
269 | self.a.plot_additional(set(['qqqq']), levels=1)
270 |
271 | self.assertTrue(prompt.called)
272 | self.check_subgraph()
273 | self.check_num_nodes_edges(8, 9)
274 | # There are two islands
275 | self.assertEqual(nx.number_connected_components(self.a.dispG), 2)
276 |
277 | def test_add_to_plot_without_path2(self):
278 | # Test adding nodes around qqqq but because our levels is so big, we
279 | # should just connect to the existing graph (no prompt)
280 | self.display_a()
281 |
282 | with patch(ASKYESNO_FUNC) as prompt:
283 | self.a.plot_additional(set(['qqqq']), levels=2)
284 |
285 | self.assertFalse(prompt.called) # We should not prompt
286 | self.check_subgraph()
287 | self.check_num_nodes_edges(9, 11)
288 | # All connected together
289 | self.assertEqual(nx.number_connected_components(self.a.dispG), 1)
290 |
291 | def test_replot_keep_marked(self):
292 | # Make sure the marked status of a node and edge is maintained
293 | # through a replot
294 | c = self.a._find_disp_node('c')
295 | out = self.a._find_disp_node('out')
296 |
297 | # Mark edge c-out and node out
298 | c_token = self.a.dispG.nodes[c]['token']
299 | out_token = self.a.dispG.nodes[out]['token']
300 | edge_token = self.a.dispG.get_edge_data(c, out, 0)['token']
301 | self.a.mark_edge(c, out, 0)
302 | self.a.mark_node(out)
303 | self.assertEqual(edge_token.is_marked, True)
304 | self.assertEqual(c_token.is_marked, False)
305 | self.assertEqual(out_token.is_marked, True)
306 |
307 | # Replot
308 | try:
309 | self.a.replot()
310 | except KeyError:
311 | self.skipTest("Weird error that sometimes happens on TravisCI")
312 |
313 | # Ensure markings still hold
314 | c = self.a._find_disp_node('c')
315 | out = self.a._find_disp_node('out')
316 | c_token = self.a.dispG.nodes[c]['token']
317 | out_token = self.a.dispG.nodes[out]['token']
318 | edge_token = self.a.dispG.get_edge_data(c, out, 0)['token']
319 | self.assertEqual(edge_token.is_marked, True)
320 | self.assertEqual(c_token.is_marked, False)
321 | self.assertEqual(out_token.is_marked, True)
322 |
323 |
324 | class TestGraphCanvasFiltered(TestGraphCanvas):
325 | def setUp(self):
326 | super(TestGraphCanvasFiltered, self).setUp()
327 | # Modify graph to include a "real" on all existing nodes which
328 | # evaluates to True when we we will filter by them
329 | G = self.a.dataG
330 |
331 | for n in G.nodes():
332 | G.nodes[n]['real'] = True
333 |
334 | # Now we're going to add a couple of "fake" nodes; IE, nodes
335 | # that should be not be displayed because they are not in the filter.
336 | # If they do show up, they'll cause us to fail some of the base checks
337 | G.add_edge('out','fake1')
338 | G.add_edge('a','fake2')
339 | G.add_edge('qqqq','fake3')
340 | G.add_edge('fake3','fake4')
341 | G.add_node('fake_alone')
342 |
343 | # Viewer under test
344 | self.a = nxv.GraphCanvas(G)
345 | self.input_G = G
346 | #gself.filter_lambda = "not str(u).startswith('fake')"
347 | self.filter_lambda = "d.get('real',False)"
348 | self.a.add_filter(self.filter_lambda)
349 |
350 | def test_full_graph(self):
351 | # Redefine this test, as when filtered, not all tokens will be marked
352 | # complete
353 | self.check_subgraph()
354 |
355 | for disp_node, disp_data in self.a.dispG.nodes(data=True):
356 | token = disp_data['token']
357 | dataG_id = disp_data['dataG_id']
358 | if dataG_id in ('out','a','qqqq'):
359 | # Has a "fake" node attached
360 | self.assertEqual(token.is_complete, False)
361 | else:
362 | self.assertEqual(token.is_complete, True)
363 |
364 | #### NEW TESTS ####
365 | def test_find_disp_node(self):
366 | # Make sure _find_disp_node raises a NodeFiltered exception
367 | from networkx_viewer.graph_canvas import NodeFiltered
368 | with self.assertRaises(NodeFiltered):
369 | self.a._find_disp_node('fake1')
370 |
371 | def test_bad_filter_lambda(self):
372 | # Caues error because filter_lambda has a syntax error
373 | filter_lambda = "d.get('real', False" # Missing closing )
374 | self.display_a()
375 |
376 | self.check_num_nodes_edges(6, 8)
377 | with patch(SHOWERROR_FUNC) as errorMsgBox:
378 | self.a.add_filter(filter_lambda)
379 | self.assertTrue(errorMsgBox.called)
380 | # Make sure no edges added or removed
381 | self.check_num_nodes_edges(6, 8)
382 |
383 | def test_bad_filter_lambda2(self):
384 | # Causes error because not every d has the attribute "real"
385 | # but error only shows on grow
386 | filter_lambda = "d['real']"
387 | self.display_a()
388 | self.a.remove_filter(self.filter_lambda)
389 |
390 | self.check_num_nodes_edges(6, 8)
391 | with patch(SHOWERROR_FUNC) as errorMsgBox:
392 | self.a.add_filter(filter_lambda)
393 | self.assertFalse(errorMsgBox.called)
394 | with patch(SHOWERROR_FUNC) as errorMsgBox:
395 | try:
396 | self.a.grow_node(self.a._find_disp_node('out'))
397 | except Exception:
398 | pass
399 | self.assertTrue(errorMsgBox.called)
400 | # Make sure no edges added or removed
401 | #self.check_num_nodes_edges(6, 8)
402 |
403 |
404 | class TestGraphCanvasTkPassthrough(TestGraphCanvas):
405 | # We inherit for the base tester to make sure we continue to
406 | # provide at least that level of functionality
407 |
408 | def setUp(self):
409 | # Create graph same as basic GraphCanvas
410 | super(TestGraphCanvasTkPassthrough, self).setUp()
411 |
412 | # Add some attributes to the dictionary to pass through to tk
413 | G = self.input_G.copy()
414 | G.nodes['a']['fill'] = 'white'
415 | G.nodes['a']['dash'] = (2,2)
416 | G.nodes[2]['label_fill'] = 'blue'
417 | G.nodes[2]['label_text'] = 'LOOOOOONG'
418 | G.get_edge_data('a', 'c').update({'dash': (2,2)})
419 | G.get_edge_data('out', 'c').update({'fill': 'red', 'width': 3})
420 |
421 | self.input_G = G.copy()
422 |
423 | # Viewer under test
424 | self.a = nxv.GraphCanvas(G,
425 | EdgeTokenClass=nxv.TkPassthroughEdgeToken,
426 | NodeTokenClass=nxv.TkPassthroughNodeToken)
427 |
428 | @classmethod
429 | def setUpClass(cls):
430 | # Because edge out-c has a native width, we expect it to fail
431 | # the base test_mark_edge. The test_mark_edge_pass case has been
432 | # developed to test correct functionality
433 | cls.test_mark_edge = unittest.expectedFailure(cls.test_mark_edge)
434 |
435 | def test_mark_edge_pass(self):
436 | c = self.a._find_disp_node('c')
437 | out = self.a._find_disp_node('out')
438 |
439 | token = self.a.dispG.get_edge_data(c, out, 0)['token']
440 |
441 | self.a.mark_edge(c, out, 0)
442 | cfg = self.a.itemconfig(self.a.dispG.get_edge_data(c, out, 0)['token'].id)
443 | self.assertEqual(token._marked, True)
444 | self.assertEqual(cfg['width'][-1], '4.0')
445 |
446 | # Unmark
447 | self.a.mark_edge(c, out, 0)
448 | cfg = self.a.itemconfig(self.a.dispG.get_edge_data(c, out, 0)['token'].id)
449 | self.assertEqual(token._marked, False)
450 | self.assertEqual(cfg['width'][-1], '3.0')
451 |
452 | def test_node_passthrough(self):
453 | node = self.a._find_disp_node('a')
454 | token = self.a.dispG.nodes[node]['token']
455 | cfg = token.itemconfig(token.marker)
456 |
457 | self.assertEqual(cfg['fill'][-1], 'white')
458 | chk = (cfg['dash'][-1] == ('2','2')) or (cfg['dash'][-1] == ('2 2'))
459 | self.assertTrue(chk)
460 |
461 | def test_node_label_passthrough(self):
462 | node = self.a._find_disp_node(2)
463 | token = self.a.dispG.nodes[node]['token']
464 | cfg = token.itemconfig(token.label)
465 |
466 | self.assertEqual(cfg['fill'][-1], 'blue')
467 | self.assertEqual(cfg['text'][-1], 'LOOOOOONG')
468 |
469 | def test_edge_passthrough(self):
470 | a = self.a._find_disp_node('a')
471 | c = self.a._find_disp_node('c')
472 | out = self.a._find_disp_node('out')
473 |
474 | # Test edge a-c
475 | token = self.a.dispG.get_edge_data(a, c, 0)['token']
476 | token_id = token.id
477 | cfg = self.a.itemconfig(token_id)
478 |
479 | chk = (cfg['dash'][-1] == ('2','2')) or (cfg['dash'][-1] == ('2 2'))
480 | self.assertTrue(chk)
481 |
482 | # Test edge out-c
483 | token = self.a.dispG.get_edge_data(out, c, 0)['token']
484 | token_id = token.id
485 | cfg = self.a.itemconfig(token_id)
486 |
487 | self.assertEqual(cfg['fill'][-1], 'red')
488 | self.assertEqual(cfg['width'][-1], '3.0')
489 |
490 | def test_refresh(self):
491 | # Make sure that if we change the underlying data dictionaries of the
492 | # dataG and call refresh, the changes propagate
493 |
494 | # Make edge a-c magenta
495 | self.a.dataG.get_edge_data('a', 'c')['fill'] = 'magenta'
496 |
497 | # Make node a magenta
498 | self.a.dataG.nodes['a']['fill'] = 'magenta'
499 |
500 | self.a.refresh()
501 |
502 | # See that the changes propagated through
503 | a = self.a._find_disp_node('a')
504 | c = self.a._find_disp_node('c')
505 |
506 | token_id = self.a.dispG.get_edge_data(a, c, 0)['token'].id
507 | cfg = self.a.itemconfig(token_id)
508 | self.assertEqual(cfg['fill'][-1], 'magenta')
509 |
510 | token = self.a.dispG.nodes[a]['token']
511 | cfg = token.itemconfig(token.marker)
512 | self.assertEqual(cfg['fill'][-1], 'magenta')
513 |
514 | class TestGraphCanvasMultiGraph(TestGraphCanvas):
515 | def setUp(self):
516 | super(TestGraphCanvasMultiGraph, self).setUp()
517 |
518 | # Add in some extra edges
519 | G = nx.MultiGraph(self.input_G)
520 | G.add_edge('a','c')
521 |
522 | G.add_edge('out',12)
523 | G.add_edge('out',12)
524 | G.add_edge('out',12)
525 | self.input_G = G.copy()
526 |
527 | # Viewer under test
528 | self.a = nxv.GraphCanvas(G)
529 |
530 | def check_num_nodes_edges(self, number_of_nodes, number_of_edges):
531 | # If we're currently displaying any of the node-pairs with
532 | # multiple edges, we'll need to add the number of edges observed
533 |
534 | try:
535 | self.a._find_disp_node('a')
536 | self.a._find_disp_node('c')
537 | except ValueError:
538 | # Edge a-c not displayed
539 | pass
540 | else:
541 | # Edge a-c dispayed. We added 1 edge in self.setUp
542 | number_of_edges += 1
543 |
544 | try:
545 | self.a._find_disp_node('out')
546 | self.a._find_disp_node(12)
547 | except ValueError:
548 | # Edge out-12 not displayed
549 | pass
550 | else:
551 | # Edge out-12 dispayed. We added 3 edges in self.setUp
552 | number_of_edges += 3
553 |
554 |
555 | return super(TestGraphCanvasMultiGraph,
556 | self).check_num_nodes_edges(number_of_nodes, number_of_edges)
557 |
558 |
559 | if __name__ == '__main__':
560 | unittest.main()
561 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/networkx_viewer/graph_canvas.py:
--------------------------------------------------------------------------------
1 | """
2 | Simple TK GUI to display and interact with a NetworkX Graph
3 |
4 | Inspired by: http://stackoverflow.com/questions/6740855/board-drawing-code-to-move-an-oval
5 |
6 | Author: Jason Sexauer
7 |
8 | Released under the GNU General Public License (GPL)
9 | """
10 | from math import atan2, pi, cos, sin
11 | import collections
12 | import pickle
13 | try:
14 | # Python 3
15 | import tkinter as tk
16 | import tkinter.messagebox as tkm
17 | import tkinter.simpledialog as tkd
18 | except ImportError:
19 | # Python 2
20 | import Tkinter as tk
21 | import tkMessageBox as tkm
22 | import tkSimpleDialog as tkd
23 |
24 | import networkx as nx
25 |
26 | from networkx_viewer.tokens import NodeToken, EdgeToken
27 |
28 | from functools import wraps
29 | def undoable(func):
30 | """Wrapper to create a savepoint which can be revered to using the
31 | GraphCanvas.undo method."""
32 | @wraps(func)
33 | def _wrapper(*args, **kwargs):
34 | # First argument should be the graphcanvas object (ie, "self")
35 | self = args[0]
36 | if not self._undo_suspend:
37 | self._undo_suspend = True # Prevent chained undos
38 | self._undo_states.append(self.dump_visualization())
39 | # Anytime we do an undoable action, the redo tree gets wiped
40 | self._redo_states = []
41 | func(*args, **kwargs)
42 | self._undo_suspend = False
43 | else:
44 | func(*args, **kwargs)
45 | return _wrapper
46 |
47 | class GraphCanvas(tk.Canvas):
48 | """Expandable GUI to plot a NetworkX Graph"""
49 |
50 | def __init__(self, graph, **kwargs):
51 | """
52 | kwargs specific to GraphCanvas:
53 | - NodeTokenClass = Class to instantiate for a new node
54 | widget. Should be inherited from NodeToken (which is from
55 | tk.Canvas)
56 | - EdgeTokenClass = Class to instantiate for a new edge widget.
57 | Should be inherited from EdgeToken.
58 | - home_node = Node to plot around when first rendering canvas
59 | - levels = How many nodes out to also plot when rendering
60 |
61 | """
62 | ###
63 | # Deal with the graph
64 | ###
65 |
66 | # Raw data graph
67 | self.dataG = graph
68 |
69 | # Graph representting what subsect of the data graph currently being
70 | # displayed.
71 | self.dispG = nx.MultiGraph()
72 |
73 | # this data is used to keep track of an
74 | # item being dragged
75 | self._drag_data = {'x': 0, 'y': 0, 'item': None}
76 |
77 | # This data is used to track panning objects (x,y coords)
78 | self._pan_data = (None, None)
79 |
80 | # List of filters to run whenever trying to add a node to the graph
81 | self._node_filters = []
82 |
83 | # Undo list
84 | self._undo_states = []
85 | self._redo_states = []
86 | self._undo_suspend = False
87 |
88 | # Create a display version of this graph
89 | # If requested, plot only within a certain level of the home node
90 | home_node = kwargs.pop('home_node', None)
91 | if home_node:
92 | levels = kwargs.pop('levels', 1)
93 | graph = self._neighbors(home_node, levels=levels, graph=graph)
94 |
95 | # Class to use when create a node widget
96 | self._NodeTokenClass = kwargs.pop('NodeTokenClass',
97 | NodeToken)
98 | assert issubclass(self._NodeTokenClass, NodeToken), \
99 | "NodeTokenClass must be inherited from NodeToken"
100 | self._EdgeTokenClass = kwargs.pop('EdgeTokenClass',
101 | EdgeToken)
102 | assert issubclass(self._EdgeTokenClass, EdgeToken), \
103 | "NodeTokenClass must be inherited from NodeToken"
104 |
105 | ###
106 | # Now we can do UI things
107 | ###
108 | tk.Canvas.__init__(self, **kwargs)
109 |
110 | self._plot_graph(graph)
111 |
112 | # Center the plot on the home node or first node in graph
113 | self.center_on_node(home_node or next(iter(graph.nodes())))
114 |
115 | # add bindings for clicking, dragging and releasing over
116 | # any object with the "node" tammg
117 | self.tag_bind('node', '', self.onNodeButtonPress)
118 | self.tag_bind('node', '', self.onNodeButtonRelease)
119 | self.tag_bind('node', '', self.onNodeMotion)
120 |
121 | self.tag_bind('edge', '', self.onEdgeClick)
122 | self.tag_bind('edge', '', self.onEdgeRightClick)
123 |
124 | self.bind('', self.onPanStart)
125 | self.bind('', self.onPanEnd)
126 | self.bind('', self.onPanMotion)
127 |
128 | self.bind_all('', self.onZoon)
129 |
130 | def _draw_edge(self, u, v):
131 | """Draw edge(s). u and v are from self.dataG"""
132 |
133 | # Find display nodes associated with these data nodes
134 | try:
135 | frm_disp = self._find_disp_node(u)
136 | to_disp = self._find_disp_node(v)
137 | except NodeFiltered:
138 | # We're hiding one of the side of the edge. That's ok,
139 | # just return silently
140 | return
141 |
142 | directed = False
143 |
144 | if isinstance(self.dataG, nx.MultiDiGraph):
145 | directed = True
146 | edges = self.dataG.get_edge_data(u, v)
147 | elif isinstance(self.dataG, nx.DiGraph):
148 | directed = True
149 | edges = {0: self.dataG.edges[u, v]}
150 | elif isinstance(self.dataG, nx.MultiGraph):
151 | edges = self.dataG.get_edge_data(u, v)
152 | elif isinstance(self.dataG, nx.Graph):
153 | edges = {0: self.dataG.edges[u, v]}
154 | else:
155 | raise NotImplementedError('Data Graph Type not Supported')
156 |
157 |
158 |
159 |
160 | # Figure out edge arc distance multiplier
161 | if len(edges) == 1:
162 | m = 0
163 | else:
164 | m = 15
165 |
166 | for key, data in edges.items():
167 | token = self._EdgeTokenClass(data)
168 | if isinstance(self.dataG, nx.MultiGraph):
169 | dataG_id = (u,v,key)
170 | elif isinstance(self.dataG, nx.Graph):
171 | dataG_id = (u,v)
172 | self.dispG.add_edge(frm_disp, to_disp, key, dataG_id=dataG_id, dispG_frm=frm_disp, token=token, m=m)
173 |
174 | x1,y1 = self._node_center(frm_disp)
175 | x2,y2 = self._node_center(to_disp)
176 | xa,ya = self._spline_center(x1,y1,x2,y2,m)
177 |
178 | token.render(host_canvas=self, coords=(x1,y1,xa,ya,x2,y2),
179 | directed=directed)
180 |
181 | if m > 0:
182 | m = -m # Flip sides
183 | else:
184 | m = -(m+m) # Go next increment out
185 |
186 | def _draw_node(self, coord, data_node):
187 | """Create a token for the data_node at the given coordinater"""
188 | (x,y) = coord
189 | data = self.dataG.nodes[data_node]
190 |
191 | # Apply filter to node to make sure we should draw it
192 | for filter_lambda in self._node_filters:
193 | try:
194 | draw_flag = eval(filter_lambda, {'u':data_node, 'd':data})
195 | except Exception as e:
196 | self._show_filter_error(filter_lambda, e)
197 | return
198 | # Filters are applied as an AND (ie, all must be true)
199 | # So if one is false, exit
200 | if draw_flag == False:
201 | return
202 |
203 | # Create token and draw node
204 | token = self._NodeTokenClass(self, data, data_node)
205 | id = self.create_window(x, y, window=token, anchor=tk.CENTER,
206 | tags='node')
207 | self.dispG.add_node(id, dataG_id=data_node,
208 | token_id=id, token=token)
209 | return id
210 |
211 | def _get_id(self, event, tag='node'):
212 | for item in self.find_overlapping(event.x-1, event.y-1,
213 | event.x+1, event.y+1):
214 | if tag in self.gettags(item):
215 | return item
216 | raise Exception('No Token Found')
217 |
218 | def _node_center(self, item_id):
219 | """Calcualte the center of a given node"""
220 | b = self.bbox(item_id)
221 | return ( (b[0]+b[2])/2, (b[1]+b[3])/2 )
222 |
223 | def _spline_center(self, x1, y1, x2, y2, m):
224 | """Given the coordinate for the end points of a spline, calcuate
225 | the mipdoint extruded out m pixles"""
226 | a = (x2 + x1)/2
227 | b = (y2 + y1)/2
228 | beta = (pi/2) - atan2((y2-y1), (x2-x1))
229 |
230 | xa = a - m*cos(beta)
231 | ya = b + m*sin(beta)
232 | return (xa, ya)
233 |
234 |
235 | def _neighbors(self, node, levels=1, graph=None):
236 | """Return graph of neighbors around node in graph (default: self.dataG)
237 | to a certain number of levels"""
238 |
239 | if graph is None:
240 | graph = self.dataG
241 |
242 | if not isinstance(node, (list, tuple, set)):
243 | node = [node,]
244 |
245 | neighbors = set(node)
246 | blocks = [[n,] for n in node]
247 | for i in range(levels):
248 | for n in neighbors:
249 | new_neighbors = set(graph.neighbors(n)) - neighbors
250 | blocks.append(new_neighbors)
251 | neighbors = neighbors.union(new_neighbors)
252 | G = graph.subgraph(neighbors)
253 |
254 | if len(blocks) > 1:
255 | # Create a block repersentation of our graph and make sure we're plotting
256 | # anything that connects the blocks too
257 |
258 | # Create blocks for each individual node not already in a block
259 | non_blocked = set(self.dataG.nodes()) - neighbors
260 | non_blocked = [[a,] for a in non_blocked]
261 |
262 | partitions = blocks + non_blocked
263 |
264 | # B = nx.blockmodel(graph, partitions)
265 | B = nx.quotient_graph(graph, partitions, relabel=True)
266 |
267 | # The resulting graph will has nodes numbered according their index in partitions
268 | # We want to go through the partitions which are blocks and find the shortest path
269 |
270 | num_blocks = len(blocks)
271 | for frm_node, to_node in zip(range(num_blocks), range(1,num_blocks-1)):
272 | try:
273 | path = nx.shortest_path(B, frm_node, to_node)
274 | except nx.NetworkXNoPath as e:
275 | pass # In an island, which is permissible
276 | except nx.NodeNotFound as e2:
277 | pass # Node reduced away, which is permissible
278 | except nx.NetworkXError as e:
279 | tkm.showerror("Node not in graph", str(e))
280 | return
281 | else:
282 | # Break path in B back down into path in G
283 | path2 = []
284 | for a in path[1:-1]: # don't include end points
285 | for n in partitions[a]:
286 | neighbors.add(n)
287 | G = graph.subgraph(neighbors)
288 |
289 |
290 | return G
291 |
292 | def _radial_behind(self, home_node, behind_node):
293 | """Detect what nodes create a radial string behind the edge from
294 | home_node to behind_node"""
295 |
296 | base_islands = nx.number_connected_components(self.dispG)
297 |
298 | # If we remove the edge in question, it should radialize the system
299 | # and we can then detect the side to remove
300 | G = nx.Graph()
301 | G.add_nodes_from(self.dispG.nodes())
302 | G.add_edges_from(self.dispG.edges())
303 | G.remove_edge(home_node, behind_node)
304 |
305 | node_sets = list(nx.connected_components(G))
306 |
307 | if len(node_sets) == base_islands:
308 | # There is no radial path behind this node
309 | return None
310 | else:
311 | for ns in node_sets:
312 | if behind_node in ns:
313 | # We know know what nodes to remove from the display graph
314 | # to remove the radial string
315 | return ns
316 |
317 | def add_filter(self, filter_lambda):
318 | # Evaluate filter against all currently displayed nodes. If
319 | # any of them do not pass, hide them
320 | nodes_to_hide = []
321 | for n, d in self.dispG.nodes(data=True):
322 | dataG_id = d['dataG_id']
323 | try:
324 | show_flag = eval(filter_lambda,
325 | {'u':dataG_id, 'd':self.dataG.nodes[dataG_id]})
326 | except Exception as e:
327 | self._show_filter_error(filter_lambda, e)
328 | return False
329 | if show_flag == False:
330 | nodes_to_hide.append(n)
331 |
332 | # Hide the nodes
333 | for n in nodes_to_hide:
334 | self.hide_node(n)
335 |
336 | # Add this filter to the filter list so that any future plots include
337 | # this filter
338 | self._node_filters.append(filter_lambda)
339 | return True
340 |
341 | def remove_filter(self, filter_lambda):
342 | self._node_filters.remove(filter_lambda)
343 |
344 | def _show_filter_error(self, filter_lambda, e):
345 | tkm.showerror("Invalid Filter",
346 | "Evaluating the filter lambda function\n" +
347 | filter_lambda + "\n\nraised the following " +
348 | "exception:\n\n" + str(e))
349 |
350 | @undoable
351 | def onPanStart(self, event):
352 | self._pan_data = (event.x, event.y)
353 | self.winfo_toplevel().config(cursor='fleur')
354 |
355 | def onPanMotion(self, event):
356 | # compute how much to move
357 | delta_x = event.x - self._pan_data[0]
358 | delta_y = event.y - self._pan_data[1]
359 | self.move(tk.ALL, delta_x, delta_y)
360 |
361 | # Record new location
362 | self._pan_data = (event.x, event.y)
363 |
364 | def onPanEnd(self, event):
365 | self._pan_data = (None, None)
366 | self.winfo_toplevel().config(cursor='arrow')
367 |
368 | def onZoon(self, event):
369 | factor = 0.1 * (1 if event.delta < 0 else -1)
370 |
371 | # Translate root coordinates into relative coordinates
372 | x = (event.widget.winfo_rootx() + event.x) - self.winfo_rootx()
373 | y = (event.widget.winfo_rooty() + event.y) - self.winfo_rooty()
374 |
375 | # Move everyone proportional to how far they are from the cursor
376 | ids = self.find_withtag('node') # + self.find_withtag('edge')
377 |
378 | for i in ids:
379 | ix, iy, t1, t2 = self.bbox(i)
380 |
381 | dx = (x-ix)*factor
382 | dy = (y-iy)*factor
383 |
384 | self.move(i, dx, dy)
385 |
386 | # Redraw all the edges
387 | for to_node, from_node, data in self.dispG.edges(data=True):
388 | from_xy = self._node_center(from_node)
389 | to_xy = self._node_center(to_node)
390 | if data['dispG_frm'] != from_node:
391 | # Flip!
392 | a = from_xy[:]
393 | from_xy = to_xy[:]
394 | to_xy = a[:]
395 | spline_xy = self._spline_center(*from_xy+to_xy+(data['m'],))
396 |
397 | data['token'].coords((from_xy+spline_xy+to_xy))
398 |
399 |
400 | @undoable
401 | def onNodeButtonPress(self, event):
402 | """Being drag of an object"""
403 | # record the item and its location
404 | item = self._get_id(event)
405 | self._drag_data["item"] = item
406 | self._drag_data["x"] = event.x
407 | self._drag_data["y"] = event.y
408 |
409 | dataG_id = self.dispG.nodes(data=True)[item]['dataG_id']
410 |
411 | self.onNodeSelected(dataG_id, self.dataG.nodes[dataG_id])
412 |
413 |
414 | def onNodeSelected(self, node_name, node_data):
415 | """Overwrite with custom function in external UI"""
416 | pass
417 |
418 | def onNodeButtonRelease(self, event):
419 | """End drag of an object"""
420 |
421 | # reset the drag information
422 | self._drag_data['item'] = None
423 | self._drag_data['x'] = 0
424 | self._drag_data['y'] = 0
425 |
426 |
427 | def onNodeMotion(self, event):
428 | """Handle dragging of an object"""
429 | if self._drag_data['item'] is None:
430 | return
431 | # compute how much this object has moved
432 | delta_x = event.x - self._drag_data['x']
433 | delta_y = event.y - self._drag_data['y']
434 | # move the object the appropriate amount
435 | self.move(self._drag_data['item'], delta_x, delta_y)
436 | # record the new position
437 | self._drag_data["x"] = event.x
438 | self._drag_data["y"] = event.y
439 |
440 | # Redraw any edges
441 | from_node = self._drag_data['item']
442 | from_xy = self._node_center(from_node)
443 | for _, to_node, edge in self.dispG.edges(from_node, data=True):
444 | to_xy = self._node_center(to_node)
445 | if edge['dispG_frm'] != from_node:
446 | # Flip!
447 | spline_xy = self._spline_center(*to_xy+from_xy+(edge['m'],))
448 | edge['token'].coords((to_xy+spline_xy+from_xy))
449 | else:
450 | spline_xy = self._spline_center(*from_xy+to_xy+(edge['m'],))
451 | edge['token'].coords((from_xy+spline_xy+to_xy))
452 |
453 | def onTokenRightClick(self, event):
454 | item = self._get_id(event)
455 |
456 | popup = tk.Menu(self, tearoff=0)
457 | popup.add_command(label='Grow', command=lambda: self.grow_node(item),
458 | accelerator='G')
459 | popup.add_command(label='Grow until...',
460 | command=lambda: self.grow_until(item))
461 | popup.add_command(label='Mark', command=lambda: self.mark_node(item),
462 | accelerator='M')
463 | popup.add_command(label='Hide', command=lambda: self.hide_node(item),
464 | accelerator='H')
465 |
466 | hide_behind = tk.Menu(popup, tearoff=0)
467 | for _, n in self.dispG.edges(item):
468 | assert _ == item
469 | if self._radial_behind(item, n):
470 | state = tk.ACTIVE
471 | else:
472 | state = tk.DISABLED
473 | hide_behind.add_command(label=str(self.dispG.nodes[n]['dataG_id']),
474 | state=state,
475 | command=lambda item=item, n=n: self.hide_behind(item, n))
476 |
477 | popup.add_cascade(label='Hide Behind', menu=hide_behind)
478 |
479 | token = self.dispG.nodes[item]['token']
480 | token.customize_menu(popup, item)
481 |
482 | try:
483 | popup.post(event.x_root, event.y_root)
484 | finally:
485 | popup.grab_release()
486 |
487 |
488 | def hide_behind(self, home_node, behind_node):
489 | """Hide radial string behind edge from home_node to behind_node"""
490 | nodes = self._radial_behind(home_node, behind_node)
491 |
492 | if nodes is None:
493 | raise ValueError('No radial string detected')
494 | for n in nodes:
495 | self.hide_node(n)
496 |
497 | def onNodeKey(self, event):
498 | item = self._get_id(event)
499 | cmd = event.char.upper()
500 |
501 | if cmd == 'G':
502 | self.grow_node(item)
503 | elif cmd == 'H':
504 | self.hide_node(item)
505 | elif cmd == 'M':
506 | self.mark_node(item)
507 |
508 | @undoable
509 | def grow_node(self, disp_node, levels=1):
510 | data_node = self.dispG.nodes(data=True)[disp_node]['dataG_id']
511 |
512 | grow_graph = self._neighbors(data_node, levels)
513 |
514 | self._plot_additional(grow_graph.nodes())
515 |
516 | @undoable
517 | def grow_until(self, disp_node, stop_condition=None, levels=0):
518 |
519 | # Find condition to stop growing
520 | if stop_condition is None:
521 | stop_condition = tkd.askstring("Stop Condition", "Enter lambda "
522 | "function which returns True when stop condition is met.\n"
523 | "Parameters are:\n - u, the node's name, and \n "
524 | "- d, the data dictionary.\n\nExample: "
525 | "d['color']=='red' \nwould grow until a red node is found.")
526 |
527 | if stop_condition is None: return
528 |
529 | data_node = self.dispG.nodes(data=True)[disp_node]['dataG_id']
530 | existing_data_nodes = set([ v['dataG_id']
531 | for k,v in self.dispG.nodes(data=True) ])
532 |
533 | max_iters = 10
534 | stop_node = None # Node which met stop condition
535 | grow_nodes = set([data_node]) # New nodes
536 | # Iterate until we find a node that matches the stop condition (or,
537 | # worst case, we reach max iters)
538 | for i in range(1,max_iters+1):
539 | old_grow_nodes = grow_nodes.copy()
540 | grow_nodes.clear()
541 | for n in old_grow_nodes:
542 | grow_graph = self._neighbors(n, levels=i)
543 | grow_nodes = grow_nodes.union(set(grow_graph.nodes())) - \
544 | existing_data_nodes - old_grow_nodes
545 | if len(grow_nodes) == 0:
546 | # Start out next iteration with the entire graph
547 | grow_nodes = existing_data_nodes.copy()
548 | continue
549 | for u in grow_nodes:
550 | d = self.dataG.nodes[u]
551 | try:
552 | stop = eval(stop_condition, {'u':u, 'd':d})
553 | except Exception as e:
554 | tkm.showerror("Invalid Stop Condition",
555 | "Evaluating the stop condition\n\n" +
556 | stop_condition + "\n\nraise the following " +
557 | "exception:\n\n" + str(e))
558 | return
559 | if stop:
560 | stop_node = u
561 | break
562 | if stop_node is not None:
563 | break
564 | if stop_node is None:
565 | tkm.showerror("Stop Condition Not Reached", "Unable to find a node "
566 | "which meet the stop condition within %d levels."%i)
567 | return
568 |
569 | ## Grow the number of times it took to find the node
570 | #self.grow_node(disp_node, i)
571 |
572 | # Find shortest path to stop_node
573 | self.plot_path(data_node, stop_node, levels=levels, add_to_exsting=True)
574 |
575 | @undoable
576 | def hide_node(self, disp_node):
577 |
578 | # Remove all the edges from display
579 | for n, m, d in self.dispG.edges(disp_node, data=True):
580 | d['token'].delete()
581 |
582 | # Remove the node from display
583 | self.delete(disp_node)
584 |
585 | # Remove the node from dispG
586 | self.dispG.remove_node(disp_node)
587 |
588 | self._graph_changed()
589 |
590 | @undoable
591 | def mark_node(self, disp_node):
592 | """Mark a display node"""
593 | token = self.dispG.nodes(data=True)[disp_node]['token']
594 | token.mark()
595 |
596 | @undoable
597 | def center_on_node(self, data_node):
598 | """Center canvas on given **DATA** node"""
599 | try:
600 | disp_node = self._find_disp_node(data_node)
601 | except ValueError as e:
602 | tkm.showerror("Unable to find node", str(e))
603 | return
604 | x,y = self.coords(self.dispG.nodes[disp_node]['token_id'])
605 |
606 | # Find center of canvas
607 | w = self.winfo_width()/2
608 | h = self.winfo_height()/2
609 | if w < 1:
610 | # We haven't been drawn yet
611 | w = int(self['width'])/2
612 | h = int(self['height'])/2
613 |
614 | # Calc delta to move to center
615 | delta_x = w - x
616 | delta_y = h - y
617 |
618 | self.move(tk.ALL, delta_x, delta_y)
619 |
620 | def onEdgeRightClick(self, event):
621 | item = self._get_id(event, 'edge')
622 | for u,v,k,d in self.dispG.edges(keys=True, data=True):
623 | if d['token'].id == item:
624 | break
625 |
626 | popup = tk.Menu(self, tearoff=0)
627 | popup.add_command(label='Mark', command=lambda: self.mark_edge(u,v,k))
628 | d['token'].customize_menu(popup)
629 |
630 | try:
631 | popup.post(event.x_root, event.y_root)
632 | finally:
633 | popup.grab_release()
634 |
635 | def onEdgeClick(self, event):
636 | item = self._get_id(event, 'edge')
637 | for u,v,k,d in self.dispG.edges(keys=True, data=True):
638 | if d['token'].id == item:
639 | break
640 | dataG_id = self.dispG.edges[u, v, k]['dataG_id']
641 | self.onEdgeSelected(dataG_id, self.dataG.get_edge_data(*dataG_id))
642 |
643 | def onEdgeSelected(self, edge_name, edge_data):
644 | """Overwrite with custom function in external UI"""
645 | pass
646 |
647 | def hide_edge(self, edge_id):
648 | # This feature breaks the "grow" feature. Also I've decided I kind of
649 | # don't like it as it's decieving to have both nodes on the display
650 | # but not be showing an edge between them
651 | raise NotImplementedError()
652 | for u, v, d in self.dispG.edges(data=True):
653 | if d['token_id']==edge_id:
654 | self.dispG.remove_edge(u,v)
655 | break
656 | self.delete(edge_id)
657 | self._graph_changed()
658 |
659 | @undoable
660 | def mark_edge(self, disp_u, disp_v, key):
661 | token = self.dispG[disp_u][disp_v][key]['token']
662 | token.mark()
663 |
664 |
665 | def clear(self):
666 | """Clear the canvas and display graph"""
667 | self.delete(tk.ALL)
668 | self.dispG.clear()
669 |
670 | @undoable
671 | def plot(self, home_node, levels=1):
672 | """Plot node (from dataG) out to levels. home_node can be list of nodes."""
673 | self.clear()
674 |
675 | graph = self._neighbors(home_node, levels=levels)
676 | self._plot_graph(graph)
677 |
678 | if isinstance(home_node, (list, tuple, set)):
679 | self.center_on_node(home_node[0])
680 | else:
681 | self.center_on_node(home_node)
682 |
683 | @undoable
684 | def plot_additional(self, home_nodes, levels=0):
685 | """Add nodes to existing plot. Prompt to include link to existing
686 | if possible. home_nodes are the nodes to add to the graph"""
687 |
688 | new_nodes = self._neighbors(home_nodes, levels=levels)
689 | new_nodes = home_nodes.union(new_nodes)
690 |
691 | displayed_data_nodes = set([ v['dataG_id']
692 | for k,v in self.dispG.nodes.items() ])
693 |
694 | # It is possible the new nodes create a connection with the existing
695 | # nodes; in such a case, we don't need to try to find the shortest
696 | # path between the two blocks
697 | current_num_islands = nx.number_connected_components(self.dispG)
698 | new_num_islands = nx.number_connected_components(
699 | self.dataG.subgraph(displayed_data_nodes.union(new_nodes)))
700 | if new_num_islands > current_num_islands:
701 | # Find shortest path between two blocks graph and, if it exists,
702 | # ask the user if they'd like to include those nodes in the
703 | # display as well.
704 | # First, create a block model of our data graph where what is
705 | # current displayed is a block, the new nodes are a a block
706 | all_nodes = set(self.dataG.nodes())
707 | singleton_nodes = all_nodes - displayed_data_nodes - new_nodes
708 | singleton_nodes = map(lambda x: [x], singleton_nodes)
709 | partitions = [displayed_data_nodes, new_nodes] + \
710 | list(singleton_nodes)
711 | #B = nx.blockmodel(self.dataG, partitions, multigraph=True)
712 | B = nx.quotient_graph(self.dataG, partitions, relabel=True)
713 |
714 | # Find shortest path between existing display (node 0) and
715 | # new display island (node 1)
716 | try:
717 | path = nx.shortest_path(B, 0, 1)
718 | except nx.NetworkXNoPath:
719 | pass
720 | else:
721 | ans = tkm.askyesno("Plot path?", "A path exists between the "
722 | "currently graph and the nodes you've asked to be added "
723 | "to the display. Would you like to plot that path?")
724 | if ans: # Yes to prompt
725 | # Add the nodes from the source graph which are part of
726 | # the path to the new_nodes set
727 | # Don't include end points because they are the two islands
728 | for u in path[1:-1]:
729 | Gu = B.nodes[u]['graph'].nodes()
730 | assert len(Gu) == 1; Gu = list(Gu)[0]
731 | new_nodes.add(Gu)
732 |
733 | # Plot the new nodes
734 | self._plot_additional(new_nodes)
735 |
736 | def dump_visualization(self):
737 | """Record currently visable nodes, their position, and their widget's
738 | state. Used by undo functionality and to memorize speicific displays"""
739 |
740 | ans = self.dispG.copy()
741 |
742 | # Add current x,y info to the graph
743 | for n, d in ans.nodes(data=True):
744 | (d['x'],d['y']) = self.coords(d['token_id'])
745 |
746 | # Pickle the whole thing up
747 | ans = pickle.dumps(ans)
748 |
749 | return ans
750 |
751 | def load_visualization(self, dump):
752 | """Load a visualization as created by dump_visulaization method"""
753 | # Unpickle string into nx graph
754 | G = pickle.loads(dump)
755 |
756 | # Clear us and rebuild
757 | self.clear()
758 | bad_nodes = set()
759 | for n, d in G.nodes(data=True):
760 | try:
761 | id = self._draw_node((d['x'],d['y']), d['dataG_id'])
762 | except KeyError as e:
763 | tkm.showerror("Model Error",
764 | "Substation no longer exists: %s" % e)
765 | bad_nodes.add(e.message)
766 | continue
767 | state = d['token'].__getstate__()
768 | self.dispG.nodes[id]['token']._setstate(state)
769 |
770 | for u, v in set(G.edges()):
771 | # Find dataG ids from old dispG
772 | uu = G.nodes[u]['dataG_id']
773 | vv = G.nodes[v]['dataG_id']
774 | if uu in bad_nodes: continue
775 | if vv in bad_nodes: continue
776 | try:
777 | self._draw_edge(uu,vv)
778 | except KeyError as e:
779 | tkm.showerror("Model Error",
780 | "Model no longer the same around %s" % e)
781 | continue
782 |
783 | state = d['token'].__getstate__()
784 | self.dispG.nodes[id]['token']._setstate(state)
785 |
786 | # Find new dispG ids from dataG ids
787 | uuu = self._find_disp_node(uu)
788 | vvv = self._find_disp_node(vv)
789 |
790 | # Set state for the new edge(s)
791 | for k, ed in self.dispG.get_edge_data(uuu, vvv).items():
792 | try:
793 | state = G.edges[u, v, k]['token'].__getstate__()
794 | except KeyError as e:
795 | tkm.showerror("Model Error",
796 | "Line different between models: %s" % e)
797 | ed['token']._setstate(state)
798 |
799 | self.refresh()
800 |
801 | def undo(self):
802 | """Undoes the last action marked with the undoable decorator"""
803 | try:
804 | state = self._undo_states.pop()
805 | except IndexError:
806 | # No undoable states (empty list)
807 | return
808 | self._redo_states.append(self.dump_visualization())
809 | self.load_visualization(state)
810 |
811 | def redo(self):
812 | try:
813 | state = self._redo_states.pop()
814 | except IndexError:
815 | # No redoable states
816 | return
817 | self.load_visualization(state)
818 |
819 | @undoable
820 | def replot(self):
821 | """Replot existing nodes, hopefully providing a better layout"""
822 | nodes = [d['dataG_id'] for n, d in self.dispG.nodes(data=True)]
823 |
824 | # Remember which nodes and edges were marked
825 | nodes_marked = [d['dataG_id']
826 | for n, d in self.dispG.nodes(data=True)
827 | if d['token'].is_marked]
828 | edges_marked = [d['dataG_id']
829 | for u,v,k,d in self.dispG.edges(data=True, keys=True)
830 | if d['token'].is_marked]
831 | # Replot
832 | self.plot(nodes, levels=0)
833 |
834 | # Remark
835 | for n in nodes_marked:
836 | self.mark_node(self._find_disp_node(n))
837 | edge_map = {d['dataG_id']: (u,v,k)
838 | for u,v,k,d in self.dispG.edges(data=True, keys=True)}
839 | for dataG_id in edges_marked:
840 | self.mark_edge(*edge_map[dataG_id])
841 |
842 | def refresh(self):
843 | """Redrawn nodes and edges, updating any display attributes that
844 | maybe have changed in the underlying tokens.
845 | This method should be called anytime the underling data graph changes"""
846 |
847 | # Edges
848 | for u,v,k,d in self.dispG.edges(keys=True, data=True):
849 | token = d['token']
850 | dataG_id = d['dataG_id']
851 | token.edge_data = self.dataG.get_edge_data(*dataG_id)
852 | token.itemconfig() # Refreshed edge's display
853 |
854 | # Nodes
855 | for u, d in self.dispG.nodes(data=True):
856 | token = d['token']
857 | node_name = d['dataG_id']
858 | data = self.dataG.nodes[node_name]
859 | token.render(data, node_name)
860 |
861 | # Update fully expanded status
862 | self._graph_changed()
863 |
864 |
865 | @undoable
866 | def plot_path(self, frm_node, to_node, levels=1, add_to_exsting=False):
867 | """Plot shortest path between two nodes"""
868 | try:
869 | path = nx.shortest_path(self.dataG, frm_node, to_node)
870 | except nx.NetworkXNoPath as e:
871 | tkm.showerror("No path", str(e))
872 | return
873 | except nx.NodeNotFound as e:
874 | tkm.showerror("No path", str(e))
875 | return
876 | except nx.NetworkXError as e:
877 | tkm.showerror("Node not in graph", str(e))
878 | return
879 |
880 | graph = self.dataG.subgraph(self._neighbors(path,levels=levels))
881 |
882 | if add_to_exsting:
883 | self._plot_additional(graph.nodes())
884 | else:
885 | self.clear()
886 | self._plot_graph(graph)
887 |
888 | # Mark the path
889 | if levels > 0 or add_to_exsting:
890 | for u, v in zip(path[:-1], path[1:]):
891 | u_disp = self._find_disp_node(u)
892 | v_disp = self._find_disp_node(v)
893 | for key, value in self.dispG.get_edge_data(u_disp, v_disp).items():
894 | self.mark_edge(u_disp, v_disp, key)
895 |
896 |
897 |
898 | def _plot_graph(self, graph):
899 | # Create nodes
900 | scale = min(self.winfo_width(), self.winfo_height())
901 | if scale == 1:
902 | # Canvas not initilized yet; use height and width hints
903 | scale = int(min(self['width'], self['height']))
904 |
905 | scale -= 50
906 | if len(graph) > 1:
907 | layout = self.create_layout(graph, scale=scale, min_distance=50)
908 |
909 | # Find min distance between any node and make sure that is at least
910 | # as big as
911 | for n in graph.nodes():
912 | self._draw_node(layout[n]+20, n)
913 | else:
914 | self._draw_node((scale/2, scale/2), list(graph.nodes())[0])
915 |
916 | # Create edges
917 | for frm, to in set(graph.edges()):
918 | self._draw_edge(frm, to)
919 |
920 | self._graph_changed()
921 |
922 | def _plot_additional(self, nodes):
923 | """Add a set of nodes to the graph, kepping all already
924 | existing nodes in the graph. This private method plots only litterally
925 | the nodes requested. It does not check to see if a path exists between
926 | the existing nodes and the new nodes; use plot_additional (without
927 | preceding underscore) to perform this check."""
928 | # We also need grow_graph to include nodes which are already
929 | # ploted but are not immediate neighbors, so that we can successfully
930 | # capture their edges. To do this, we should subgraph the data graph
931 | # using the nodes of the grow graph and existing data nodes
932 | existing_data_nodes = set([ v['dataG_id']
933 | for k,v in self.dispG.nodes.items() ])
934 | nodes = set(nodes).union(existing_data_nodes)
935 | grow_graph = self.dataG.subgraph(nodes)
936 |
937 | # Build layout considering existing nodes and
938 | # argument to center around the home node (ie, "disp_node")
939 | fixed = {}
940 | for n,d in self.dispG.nodes(data=True):
941 | fixed[d['dataG_id']] = self.coords(n)
942 |
943 | layout = self.create_layout(grow_graph,
944 | pos=fixed, fixed=list(fixed.keys()))
945 |
946 | # Unfreeze graph
947 | grow_graph = type(grow_graph)(grow_graph)
948 |
949 | # Filter the graph to only include new edges
950 | for n,m in grow_graph.copy().edges():
951 | if (n in existing_data_nodes) and (m in existing_data_nodes):
952 | grow_graph.remove_edge(n,m)
953 |
954 | # Remove any nodes which connected to only existing nodes (ie, they
955 | # they connect to nothing else in grow_graph)
956 | for n, degree in grow_graph.copy().degree():
957 | if degree == 0:
958 | grow_graph.remove_node(n)
959 |
960 | if len(grow_graph.nodes()) == 0:
961 | # No new nodes to add
962 | return
963 |
964 | # Plot the new nodes and add to the disp graph
965 | for n in grow_graph.nodes():
966 | if n in existing_data_nodes: continue
967 | self._draw_node(layout[n], n)
968 |
969 | for n, m in set(grow_graph.edges()):
970 | if (n in existing_data_nodes) and (m in existing_data_nodes):
971 | continue
972 |
973 | # Add edge to dispG and draw
974 | self._draw_edge(n, m)
975 |
976 | self._graph_changed()
977 |
978 |
979 | def _graph_changed(self):
980 | """Handle token callbacks
981 | Called every time a node or edge has been added or removed from
982 | the display graph. Used to propagate completeness indicators
983 | down to the node's tokens"""
984 |
985 | for n, d in self.dispG.nodes(data=True):
986 | token = d['token']
987 | if self.dispG.degree(n) == self.dataG.degree(d['dataG_id']):
988 | token.mark_complete()
989 | else:
990 | token.mark_incomplete()
991 |
992 |
993 | def _find_disp_node(self, data_node):
994 | """Given a node's name in self.dataG, find in self.dispG"""
995 | disp_node = [a for a, d in self.dispG.nodes(data=True)
996 | if d['dataG_id'] == data_node]
997 | if len(disp_node) == 0 and str(data_node).isdigit():
998 | # Try again, this time using the int version
999 | data_node = int(data_node)
1000 | disp_node = [a for a, d in self.dispG.nodes(data=True)
1001 | if d['dataG_id'] == data_node]
1002 |
1003 | if len(disp_node) == 0:
1004 | # It could be that this node is not displayed because it is
1005 | # currently being filtered out. Test for that and, if true,
1006 | # raise a NodeFiltered exception
1007 | for f in self._node_filters:
1008 | try:
1009 | show_flag = eval(f, {'u':data_node,
1010 | 'd':self.dataG.nodes[data_node]})
1011 | except Exception as e:
1012 | # Usually we we would alert user that eval failed, but
1013 | # in this case, we're doing this without their knowlage
1014 | # so we're just going to die silently
1015 | break
1016 | if show_flag == False:
1017 | raise NodeFiltered
1018 | raise ValueError("Data Node '%s' is not currently displayed"%\
1019 | data_node)
1020 | elif len(disp_node) != 1:
1021 | raise AssertionError("Data node '%s' is displayed multiple "
1022 | "times" % data_node)
1023 | return disp_node[0]
1024 |
1025 | def create_layout(self, G, pos=None, fixed=None, scale=1.0,
1026 | min_distance=None):
1027 | """Position nodes using Fruchterman-Reingold force-directed algorithm.
1028 |
1029 | Parameters
1030 | ----------
1031 | G : NetworkX graph
1032 |
1033 | dim : int
1034 | Dimension of layout
1035 |
1036 | k : float (default=None)
1037 | Optimal distance between nodes. If None the distance is set to
1038 | 1/sqrt(n) where n is the number of nodes. Increase this value
1039 | to move nodes farther apart.
1040 |
1041 |
1042 | pos : dict or None optional (default=None)
1043 | Initial positions for nodes as a dictionary with node as keys
1044 | and values as a list or tuple. If None, then nuse random initial
1045 | positions.
1046 |
1047 | fixed : list or None optional (default=None)
1048 | Nodes to keep fixed at initial position.
1049 |
1050 | iterations : int optional (default=50)
1051 | Number of iterations of spring-force relaxation
1052 |
1053 | weight : string or None optional (default='weight')
1054 | The edge attribute that holds the numerical value used for
1055 | the edge weight. If None, then all edge weights are 1.
1056 |
1057 | scale : float (default=1.0)
1058 | Scale factor for positions. The nodes are positioned
1059 | in a box of size [0,scale] x [0,scale].
1060 |
1061 | min_distance : float optional (default=None)
1062 | Minimum distance to enforce between nodes. If passed with scale,
1063 | this may cause the returned positions to go outside the scale.
1064 |
1065 | Returns
1066 | -------
1067 | dict :
1068 | A dictionary of positions keyed by node
1069 |
1070 | Examples
1071 | --------
1072 | >>> G=nx.path_graph(4)
1073 | >>> pos=nx.spring_layout(G)
1074 |
1075 | # The same using longer function name
1076 | >>> pos=nx.fruchterman_reingold_layout(G)
1077 | """
1078 | # This is a modification of the networkx.layout library's
1079 | # fruchterman_reingold_layout to work well with fixed positions
1080 | # and large inital positions (not near 1.0). This involved
1081 | # modification to what the optimal "k" is and the removal of
1082 | # the resize when fixed is passed
1083 | dim = 2
1084 |
1085 | try:
1086 | import numpy as np
1087 | except ImportError:
1088 | raise ImportError("fruchterman_reingold_layout() requires numpy: http://scipy.org/ ")
1089 | if fixed is not None:
1090 | nfixed=dict(zip(G,range(len(G))))
1091 | fixed=np.asarray([nfixed[v] for v in fixed])
1092 |
1093 | if pos is not None:
1094 | # Determine size of exisiting domain
1095 | dom_size = max(flatten(pos.values()))
1096 | pos_arr=np.asarray(np.random.random((len(G),dim)))*dom_size
1097 | for i,n in enumerate(G):
1098 | if n in pos:
1099 | pos_arr[i]=np.asarray(pos[n])
1100 | else:
1101 | pos_arr=None
1102 | dom_size = 1.0
1103 |
1104 | if len(G)==0:
1105 | return {}
1106 | if len(G)==1:
1107 | return {G.nodes()[0]:(1,)*dim}
1108 |
1109 | A=nx.adjacency_matrix(G).todense()
1110 | nnodes,_ = A.shape
1111 | # I've found you want to occupy about a two-thirds of the window size
1112 | if fixed is not None:
1113 | k=(min(self.winfo_width(), self.winfo_height())*.66)/np.sqrt(nnodes)
1114 | else:
1115 | k = None
1116 |
1117 | # Alternate k, for when vieweing the whole graph, not a subset
1118 | #k=dom_size/np.sqrt(nnodes)
1119 | pos=self._fruchterman_reingold(A,dim,k,pos_arr,fixed)
1120 |
1121 | if fixed is None:
1122 | # Only rescale non fixed layouts
1123 | pos= nx.layout.rescale_layout(pos,scale=scale)
1124 |
1125 | if min_distance and fixed is None:
1126 | # Find min distance between any two nodes and scale such that
1127 | # this distance = min_distance
1128 |
1129 | # matrix of difference between points
1130 | delta = np.zeros((pos.shape[0],pos.shape[0],pos.shape[1]),
1131 | dtype=A.dtype)
1132 | for i in range(pos.shape[1]):
1133 | delta[:,:,i]= pos[:,i,None]-pos[:,i]
1134 | # distance between points
1135 | distance=np.sqrt((delta**2).sum(axis=-1))
1136 |
1137 | cur_min_dist = np.where(distance==0, np.inf, distance).min()
1138 |
1139 | if cur_min_dist < min_distance:
1140 | # calculate scaling factor and rescale
1141 | rescale = (min_distance / cur_min_dist) * pos.max()
1142 |
1143 | pos = nx.layout.rescale_layout(pos, scale=rescale)
1144 |
1145 | return dict(zip(G,pos))
1146 |
1147 | def _fruchterman_reingold(self, A, dim=2, k=None, pos=None, fixed=None,
1148 | iterations=50):
1149 | # Position nodes in adjacency matrix A using Fruchterman-Reingold
1150 | # Entry point for NetworkX graph is fruchterman_reingold_layout()
1151 | try:
1152 | import numpy as np
1153 | except ImportError:
1154 | raise ImportError("_fruchterman_reingold() requires numpy: http://scipy.org/ ")
1155 |
1156 | try:
1157 | nnodes,_=A.shape
1158 | except AttributeError:
1159 | raise nx.NetworkXError(
1160 | "fruchterman_reingold() takes an adjacency matrix as input")
1161 |
1162 | A=np.asarray(A) # make sure we have an array instead of a matrix
1163 |
1164 | if pos is None:
1165 | # random initial positions
1166 | pos=np.asarray(np.random.random((nnodes,dim)),dtype='float64')
1167 | else:
1168 | # make sure positions are of same type as matrix
1169 | pos=pos.astype('float64')
1170 |
1171 | # optimal distance between nodes
1172 | if k is None:
1173 | k=np.sqrt(1.0/nnodes)
1174 | # the initial "temperature" is about .1 of domain area (=1x1)
1175 | # this is the largest step allowed in the dynamics.
1176 | # Modified to actually detect for domain area
1177 | t = max(max(pos.T[0]) - min(pos.T[0]), max(pos.T[1]) - min(pos.T[1]))*0.1
1178 | # simple cooling scheme.
1179 | # linearly step down by dt on each iteration so last iteration is size dt.
1180 | dt=t/float(iterations+1)
1181 | delta = np.zeros((pos.shape[0],pos.shape[0],pos.shape[1]),dtype=A.dtype)
1182 | # the inscrutable (but fast) version
1183 | # this is still O(V^2)
1184 | # could use multilevel methods to speed this up significantly
1185 | for iteration in range(iterations):
1186 | # matrix of difference between points
1187 | for i in range(pos.shape[1]):
1188 | delta[:,:,i]= pos[:,i,None]-pos[:,i]
1189 | # distance between points
1190 | distance=np.sqrt((delta**2).sum(axis=-1))
1191 | # enforce minimum distance of 0.01
1192 | distance=np.where(distance<0.01,0.01,distance)
1193 | # displacement "force"
1194 | displacement=np.transpose(np.transpose(delta)*\
1195 | (k*k/distance**2-A*distance/k))\
1196 | .sum(axis=1)
1197 | # update positions
1198 | length=np.sqrt((displacement**2).sum(axis=1))
1199 | length=np.where(length<0.01,0.1,length)
1200 | delta_pos=np.transpose(np.transpose(displacement)*t/length)
1201 | if fixed is not None:
1202 | # don't change positions of fixed nodes
1203 | delta_pos[fixed]=0.0
1204 |
1205 | pos+=delta_pos
1206 | # cool temperature
1207 | t-=dt
1208 | ###pos=_rescale_layout(pos)
1209 | return pos
1210 |
1211 | class NodeFiltered(Exception):
1212 | pass
1213 |
1214 | def flatten(l):
1215 | try:
1216 | bs = basestring
1217 | except NameError:
1218 | # Py3k
1219 | bs = str
1220 | for el in l:
1221 | if isinstance(el, collections.abc.Iterable) and not isinstance(el, bs):
1222 | for sub in flatten(el):
1223 | yield sub
1224 | else:
1225 | yield el
1226 |
--------------------------------------------------------------------------------