{ "metadata": { "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "code", "collapsed": false, "input": [ "from __future__ import print_function # py 2.7 compat\n", "\n", "import networkx as nx" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "This notebook demonstrates how NetworkX and D3 can be married using custom widget code." ] }, { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Hooking NetworkX Graphs" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "NetworkX graphs do not have events that can be listened to. In order to watch the NetworkX graph object for changes a custom eventful graph object must be created. The custom eventful graph object will inherit from the base graph object and use special eventful dictionaries instead of standard Python dict instances. Because NetworkX nests dictionaries inside dictionaries, it's important that the eventful dictionary is capable of recognizing when a dictionary value is set to another dictionary instance. When this happens, the eventful dictionary needs to also make the new dictionary an eventful dictionary. This allows the eventful dictionary to listen to changes made to dictionaries within dictionaries." ] }, { "cell_type": "code", "collapsed": false, "input": [ "class EventfulDict(dict):\n", " \n", " def __init__(self, *args, **kwargs):\n", " self._add_callbacks = []\n", " self._del_callbacks = []\n", " self._set_callbacks = []\n", " dict.__init__(self, *args, **kwargs)\n", " \n", " def on_add(self, callback, remove=False):\n", " self._register_callback(self._add_callbacks, callback, remove)\n", " def on_del(self, callback, remove=False):\n", " self._register_callback(self._del_callbacks, callback, remove)\n", " def on_set(self, callback, remove=False):\n", " self._register_callback(self._set_callbacks, callback, remove)\n", " def _register_callback(self, callback_list, callback, remove=False):\n", " if callable(callback):\n", " if remove and callback in callback_list:\n", " callback_list.remove(callback)\n", " elif not remove and not callback in callback_list:\n", " callback_list.append(callback)\n", " else:\n", " raise Exception('Callback must be callable.')\n", "\n", " def _handle_add(self, key, value):\n", " self._try_callbacks(self._add_callbacks, key, value)\n", " def _handle_del(self, key):\n", " self._try_callbacks(self._del_callbacks, key)\n", " def _handle_set(self, key, value):\n", " self._try_callbacks(self._set_callbacks, key, value)\n", " def _try_callbacks(self, callback_list, *pargs, **kwargs):\n", " for callback in callback_list:\n", " callback(*pargs, **kwargs)\n", " \n", " def __setitem__(self, key, value):\n", " return_val = None\n", " exists = False\n", " if key in self:\n", " exists = True\n", " \n", " # If the user sets the property to a new dict, make the dict\n", " # eventful and listen to the changes of it ONLY if it is not\n", " # already eventful. Any modification to this new dict will\n", " # fire a set event of the parent dict.\n", " if isinstance(value, dict) and not isinstance(value, EventfulDict):\n", " new_dict = EventfulDict(value)\n", " \n", " def handle_change(*pargs, **kwargs):\n", " self._try_callbacks(self._set_callbacks, key, dict.__getitem__(self, key))\n", " \n", " new_dict.on_add(handle_change)\n", " new_dict.on_del(handle_change)\n", " new_dict.on_set(handle_change)\n", " return_val = dict.__setitem__(self, key, new_dict)\n", " else:\n", " return_val = dict.__setitem__(self, key, value)\n", " \n", " if exists:\n", " self._handle_set(key, value)\n", " else:\n", " self._handle_add(key, value)\n", " return return_val\n", " \n", "\n", " def __delitem__(self, key):\n", " return_val = dict.__delitem__(self, key)\n", " self._handle_del(key)\n", " return return_val\n", "\n", " \n", " def pop(self, key):\n", " return_val = dict.pop(self, key)\n", " if key in self:\n", " self._handle_del(key)\n", " return return_val\n", "\n", " def popitem(self):\n", " popped = dict.popitem(self)\n", " if popped is not None and popped[0] is not None:\n", " self._handle_del(popped[0])\n", " return popped\n", "\n", " def update(self, other_dict):\n", " for (key, value) in other_dict.items():\n", " self[key] = value\n", " \n", " def clear(self):\n", " for key in list(self.keys()):\n", " del self[key]" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Override the NetworkX Graph object to make an eventful graph." ] }, { "cell_type": "code", "collapsed": false, "input": [ "class EventfulGraph(nx.Graph):\n", " \n", " def __init__(self, *pargs, **kwargs):\n", " \"\"\"Initialize a graph with edges, name, graph attributes.\"\"\"\n", " super(EventfulGraph, self).__init__(*pargs, **kwargs)\n", " \n", " self.graph = EventfulDict(self.graph)\n", " self.node = EventfulDict(self.node)\n", " self.adj = EventfulDict(self.adj)\n", " " ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "To make sure that the eventful graph works, create a new graph and log the dictionary events raised." ] }, { "cell_type": "code", "collapsed": false, "input": [ "def echo_dict_events(eventful_dict, prefix=''):\n", " def key_add(key, value):\n", " print(prefix + 'add (%s, %s)' % (key, str(value)))\n", " def key_set(key, value):\n", " print(prefix + 'set (%s, %s)' % (key, str(value)))\n", " def key_del(key):\n", " print(prefix + 'del %s' % key)\n", " eventful_dict.on_add(key_add)\n", " eventful_dict.on_set(key_set)\n", " eventful_dict.on_del(key_del)\n", " \n", "def echo_graph_events(eventful_graph):\n", " for key in ['graph', 'node', 'adj']:\n", " echo_dict_events(getattr(eventful_graph, key), prefix=key+' ')" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 4 }, { "cell_type": "code", "collapsed": false, "input": [ "G = EventfulGraph()\n", "echo_graph_events(G)\n", "\n", "G.add_node('hello')\n", "G.add_node('goodbye', fill=\"red\")\n", "G.add_edges_from([(1,2),(1,3), (1,'goodbye')], stroke=\"lime\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "adj add (hello, {})\n", "node add (hello, {})\n", "adj add (goodbye, {})\n", "node add (goodbye, {'fill': 'red'})\n", "adj add (1, {})\n", "node add (1, {})\n", "adj add (2, {})\n", "node add (2, {})\n", "adj set (1, {2: {'stroke': 'lime'}})\n", "adj set (2, {1: {'stroke': 'lime'}})\n", "adj add (3, {})\n", "node add (3, {})\n", "adj set (1, {2: {'stroke': 'lime'}, 3: {'stroke': 'lime'}})\n", "adj set (3, {1: {'stroke': 'lime'}})\n", "adj set (1, {2: {'stroke': 'lime'}, 3: {'stroke': 'lime'}, 'goodbye': {'stroke': 'lime'}})\n", "adj set (goodbye, {1: {'stroke': 'lime'}})\n" ] } ], "prompt_number": 5 }, { "cell_type": "code", "collapsed": false, "input": [ "G.adj" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 6, "text": [ "{1: {2: {'stroke': 'lime'},\n", " 3: {'stroke': 'lime'},\n", " 'goodbye': {'stroke': 'lime'}},\n", " 2: {1: {'stroke': 'lime'}},\n", " 3: {1: {'stroke': 'lime'}},\n", " 'goodbye': {1: {'stroke': 'lime'}},\n", " 'hello': {}}" ] } ], "prompt_number": 6 }, { "cell_type": "code", "collapsed": false, "input": [ "G.node" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 7, "text": [ "{1: {}, 2: {}, 3: {}, 'goodbye': {'fill': 'red'}, 'hello': {}}" ] } ], "prompt_number": 7 }, { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "D3 Widget" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The D3 widget will blindly port all of the dictionary events over custom widget messages." ] }, { "cell_type": "code", "collapsed": false, "input": [ "from IPython.html import widgets # Widget definitions\n", "from IPython.display import display # Used to display widgets in the notebook" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 8 }, { "cell_type": "code", "collapsed": false, "input": [ "# Import the base Widget class and the traitlets Unicode class.\n", "from IPython.html.widgets import Widget\n", "from IPython.utils.traitlets import Unicode, Int\n", "\n", "# Define our ForceDirectedGraphWidget and its target model and default view.\n", "class ForceDirectedGraphWidget(Widget):\n", " target_name = Unicode('ForceDirectedGraphModel')\n", " default_view_name = Unicode('D3ForceDirectedGraphView')\n", " \n", " _keys = ['width', 'height']\n", " width = Int(400)\n", " height = Int(300)\n", " \n", " def __init__(self, eventful_graph, *pargs, **kwargs):\n", " Widget.__init__(self, *pargs, **kwargs)\n", " \n", " self._eventful_graph = eventful_graph\n", " self._send_dict_changes(eventful_graph.graph, 'graph')\n", " self._send_dict_changes(eventful_graph.node, 'node')\n", " self._send_dict_changes(eventful_graph.adj, 'adj')\n", " \n", " \n", " def _repr_widget_(self, *pargs, **kwargs):\n", " \n", " # Show the widget, then send the current state\n", " Widget._repr_widget_(self, *pargs, **kwargs)\n", " for (key, value) in self._eventful_graph.graph.items():\n", " self.send({'dict': 'graph', 'action': 'add', 'key': key, 'value': value})\n", " for (key, value) in self._eventful_graph.node.items():\n", " self.send({'dict': 'node', 'action': 'add', 'key': key, 'value': value})\n", " for (key, value) in self._eventful_graph.adj.items():\n", " self.send({'dict': 'adj', 'action': 'add', 'key': key, 'value': value})\n", " \n", " \n", " def _send_dict_changes(self, eventful_dict, dict_name):\n", " def key_add(key, value):\n", " self.send({'dict': dict_name, 'action': 'add', 'key': key, 'value': value})\n", " def key_set(key, value):\n", " self.send({'dict': dict_name, 'action': 'set', 'key': key, 'value': value})\n", " def key_del(key):\n", " self.send({'dict': dict_name, 'action': 'del', 'key': key})\n", " eventful_dict.on_add(key_add)\n", " eventful_dict.on_set(key_set)\n", " eventful_dict.on_del(key_del)\n", " " ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 9 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The front-end listens to the dictionary events and keeps the D3 control in sync with the dictionary in the back-end." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%javascript\n", "\n", "require([\"http://d3js.org/d3.v3.min.js\", \"notebook/js/widget\"], function(){\n", " \n", " // Define the ForceDirectedGraphModel and register it with the widget manager.\n", " var ForceDirectedGraphModel = IPython.WidgetModel.extend({});\n", " IPython.widget_manager.register_widget_model('ForceDirectedGraphModel', ForceDirectedGraphModel);\n", " \n", " // Define the D3ForceDirectedGraphView\n", " var D3ForceDirectedGraphView = IPython.WidgetView.extend({\n", " \n", " render: function(){\n", " this.guid = 'd3force' + IPython.utils.uuid();\n", " this.setElement($('
', {id: this.guid}));\n", " this.model.on_msg($.proxy(this.handle_msg, this));\n", " this.has_drawn = false;\n", " },\n", " \n", " try_add_node: function(id){\n", " var index = this.find_node(id);\n", " if (index == -1) {\n", " var node = {id: id};\n", " this.nodes.push(node);\n", " return node;\n", " } else {\n", " return this.nodes[index];\n", " }\n", " },\n", " \n", " update_node: function(node, attributes) {\n", " if (node !== null) {\n", " for (var key in attributes) {\n", " node[key] = attributes[key];\n", " }\n", " this._update_node(d3.select('#' + this.guid + node.id));\n", " }\n", " },\n", " \n", " remove_node: function(id){\n", " this.remove_links_to(id);\n", " \n", " var found_index = this.find_node(id);\n", " if (found_index>=0) {\n", " this.nodes.splice(found_index, 1);\n", " }\n", " },\n", " \n", " find_node: function(id){\n", " var found_index = -1;\n", " for (var index in this.nodes) {\n", " if (this.nodes[index].id == id) {\n", " found_index = index;\n", " break;\n", " }\n", " }\n", " return found_index;\n", " },\n", " \n", " find_link: function(source_id, target_id){\n", " for (var index in this.links) {\n", " if (this.links[index].source.id == source_id && this.links[index].target.id == target_id) {\n", " return index;\n", " }\n", " }\n", " return -1;\n", " },\n", " \n", " try_add_link: function(source_id, target_id){\n", " var index = this.find_link(source_id, target_id);\n", " if (index == -1) {\n", " var source_node = this.try_add_node(source_id);\n", " var target_node = this.try_add_node(target_id);\n", " var new_link = {source: source_node, target: target_node};\n", " this.links.push(new_link);\n", " return new_link;\n", " } else {\n", " return this.links[index]\n", " }\n", " },\n", " \n", " update_link: function(link, attributes){\n", " if (link != null) {\n", " for (var key in attributes) {\n", " link[key] = attributes[key];\n", " }\n", " this._update_edge(d3.select('#' + this.guid + link.source.id + \"-\" + link.target.id));\n", " }\n", " },\n", " \n", " remove_links: function(source_id){\n", " var found_indicies = [];\n", " for (var index in this.links) {\n", " if (this.links[index].source.id == source_id) {\n", " found_indicies.push(index);\n", " }\n", " }\n", " found_indicies.reverse();\n", " \n", " for (var index in found_indicies) {\n", " this.links.splice(index, 1);\n", " };\n", " },\n", " \n", " remove_links_to: function(id){\n", " var found_indicies = [];\n", " for (var index in this.links) {\n", " if (this.links[index].source.id == id || this.links[index].target.id == id) {\n", " found_indicies.push(index);\n", " }\n", " }\n", " found_indicies.reverse();\n", " \n", " for (var index in found_indicies) {\n", " this.links.splice(index, 1);\n", " };\n", " },\n", " \n", " handle_msg: function(content){\n", " var dict = content.dict;\n", " var action = content.action;\n", " var key = content.key;\n", " \n", " if (dict=='node') {\n", " if (action=='add' || action=='set') {\n", " this.update_node(this.try_add_node(key), content.value)\n", " } else if (action=='del') {\n", " this.remove_node(key);\n", " }\n", " \n", " } else if (dict=='adj') {\n", " if (action=='add' || action=='set') {\n", " var links = content.value;\n", " for (var target_id in links) {\n", " this.update_link(this.try_add_link(key, target_id), links[target_id]);\n", " }\n", " } else if (action=='del') {\n", " this.remove_links(key);\n", " }\n", " }\n", " this.start();\n", " },\n", " \n", " start: function() {\n", " var node = this.svg.selectAll(\".node\"),\n", " link = this.svg.selectAll(\".link\");\n", " \n", " var link = link.data(this.force.links(), function(d) { return d.source.id + \"-\" + d.target.id; });\n", " this._update_edge(link.enter().insert(\"line\", \".node\"))\n", " link.exit().remove();\n", " \n", " var node = node.data(this.force.nodes(), function(d) { return d.id;});\n", " var that = this;\n", " this._update_node(node.enter().append(\"circle\"));\n", " node.exit().remove();\n", " \n", " this.force.start();\n", " },\n", " \n", " _update_node: function(node) {\n", " var that = this;\n", " node\n", " .attr(\"id\", function(d) { return that.guid + d.id; })\n", " .attr(\"class\", function(d) { return \"node \" + d.id; })\n", " .attr(\"r\", function(d) {\n", " if (d.r == undefined) {\n", " return 8; \n", " } else {\n", " return d.r;\n", " }\n", " \n", " })\n", " .style(\"fill\", function(d) {\n", " if (d.fill == undefined) {\n", " return that.color(d.group); \n", " } else {\n", " return d.fill;\n", " }\n", " \n", " })\n", " .style(\"stroke\", function(d) {\n", " if (d.stroke == undefined) {\n", " return \"#FFF\"; \n", " } else {\n", " return d.stroke;\n", " }\n", " \n", " })\n", " .style(\"stroke-width\", function(d) {\n", " if (d.strokewidth == undefined) {\n", " return \"#FFF\"; \n", " } else {\n", " return d.strokewidth;\n", " }\n", " \n", " })\n", " .call(this.force.drag);\n", " },\n", " \n", " _update_edge: function(edge) {\n", " var that = this;\n", " edge\n", " .attr(\"id\", function(d) { return that.guid + d.source.id + \"-\" + d.target.id; })\n", " .attr(\"class\", \"link\")\n", " .style(\"stroke-width\", function(d) {\n", " if (d.strokewidth == undefined) {\n", " return \"1.5px\"; \n", " } else {\n", " return d.strokewidth;\n", " }\n", " \n", " })\n", " .style('stroke', function(d) {\n", " if (d.stroke == undefined) {\n", " return \"#999\"; \n", " } else {\n", " return d.stroke;\n", " }\n", " \n", " });\n", " },\n", " \n", " tick: function() {\n", " var node = this.svg.selectAll(\".node\"),\n", " link = this.svg.selectAll(\".link\");\n", " \n", " link.attr(\"x1\", function(d) { return d.source.x; })\n", " .attr(\"y1\", function(d) { return d.source.y; })\n", " .attr(\"x2\", function(d) { return d.target.x; })\n", " .attr(\"y2\", function(d) { return d.target.y; });\n", " \n", " node.attr(\"cx\", function(d) { return d.x; })\n", " .attr(\"cy\", function(d) { return d.y; });\n", " },\n", " \n", " update: function(){\n", " if (!this.has_drawn) {\n", " this.has_drawn = true;\n", " \n", " var width = this.model.get('width'),\n", " height = this.model.get('height');\n", " \n", " this.color = d3.scale.category20();\n", " \n", " this.nodes = [];\n", " this.links = [];\n", " \n", " this.force = d3.layout.force()\n", " .nodes(this.nodes)\n", " .links(this.links)\n", " .charge(function (d) {\n", " if (d.charge === undefined) {\n", " return -120;\n", " } else {\n", " return d.charge;\n", " }\n", " })\n", " .linkDistance(function (d) {\n", " if (d.distance === undefined) {\n", " return 40;\n", " } else {\n", " return d.distance;\n", " }\n", " })\n", " .linkStrength(function (d) {\n", " if (d.strength === undefined) {\n", " return 1.0;\n", " } else {\n", " return d.strength;\n", " }\n", " })\n", " .size([width, height])\n", " .on(\"tick\", $.proxy(this.tick, this));\n", " \n", " this.svg = d3.select(\"#\" + this.guid).append(\"svg\")\n", " .attr(\"width\", width)\n", " .attr(\"height\", height);\n", " \n", " var that = this;\n", " setTimeout(function() {\n", " that.start();\n", " }, 0);\n", " }\n", " \n", " return IPython.WidgetView.prototype.update.call(this);\n", " },\n", " \n", " });\n", " \n", " // Register the D3ForceDirectedGraphView with the widget manager.\n", " IPython.widget_manager.register_widget_view('D3ForceDirectedGraphView', D3ForceDirectedGraphView);\n", "});" ], "language": "python", "metadata": {}, "outputs": [ { "javascript": [ "\n", "require([\"http://d3js.org/d3.v3.min.js\", \"notebook/js/widget\"], function(){\n", " \n", " // Define the ForceDirectedGraphModel and register it with the widget manager.\n", " var ForceDirectedGraphModel = IPython.WidgetModel.extend({});\n", " IPython.widget_manager.register_widget_model('ForceDirectedGraphModel', ForceDirectedGraphModel);\n", " \n", " // Define the D3ForceDirectedGraphView\n", " var D3ForceDirectedGraphView = IPython.WidgetView.extend({\n", " \n", " render: function(){\n", " this.guid = 'd3force' + IPython.utils.uuid();\n", " this.setElement($('
', {id: this.guid}));\n", " this.model.on_msg($.proxy(this.handle_msg, this));\n", " this.has_drawn = false;\n", " },\n", " \n", " try_add_node: function(id){\n", " var index = this.find_node(id);\n", " if (index == -1) {\n", " var node = {id: id};\n", " this.nodes.push(node);\n", " return node;\n", " } else {\n", " return this.nodes[index];\n", " }\n", " },\n", " \n", " update_node: function(node, attributes) {\n", " if (node !== null) {\n", " for (var key in attributes) {\n", " node[key] = attributes[key];\n", " }\n", " this._update_node(d3.select('#' + this.guid + node.id));\n", " }\n", " },\n", " \n", " remove_node: function(id){\n", " this.remove_links_to(id);\n", " \n", " var found_index = this.find_node(id);\n", " if (found_index>=0) {\n", " this.nodes.splice(found_index, 1);\n", " }\n", " },\n", " \n", " find_node: function(id){\n", " var found_index = -1;\n", " for (var index in this.nodes) {\n", " if (this.nodes[index].id == id) {\n", " found_index = index;\n", " break;\n", " }\n", " }\n", " return found_index;\n", " },\n", " \n", " find_link: function(source_id, target_id){\n", " for (var index in this.links) {\n", " if (this.links[index].source.id == source_id && this.links[index].target.id == target_id) {\n", " return index;\n", " }\n", " }\n", " return -1;\n", " },\n", " \n", " try_add_link: function(source_id, target_id){\n", " var index = this.find_link(source_id, target_id);\n", " if (index == -1) {\n", " var source_node = this.try_add_node(source_id);\n", " var target_node = this.try_add_node(target_id);\n", " var new_link = {source: source_node, target: target_node};\n", " this.links.push(new_link);\n", " return new_link;\n", " } else {\n", " return this.links[index]\n", " }\n", " },\n", " \n", " update_link: function(link, attributes){\n", " if (link != null) {\n", " for (var key in attributes) {\n", " link[key] = attributes[key];\n", " }\n", " this._update_edge(d3.select('#' + this.guid + link.source.id + \"-\" + link.target.id));\n", " }\n", " },\n", " \n", " remove_links: function(source_id){\n", " var found_indicies = [];\n", " for (var index in this.links) {\n", " if (this.links[index].source.id == source_id) {\n", " found_indicies.push(index);\n", " }\n", " }\n", " found_indicies.reverse();\n", " \n", " for (var index in found_indicies) {\n", " this.links.splice(index, 1);\n", " };\n", " },\n", " \n", " remove_links_to: function(id){\n", " var found_indicies = [];\n", " for (var index in this.links) {\n", " if (this.links[index].source.id == id || this.links[index].target.id == id) {\n", " found_indicies.push(index);\n", " }\n", " }\n", " found_indicies.reverse();\n", " \n", " for (var index in found_indicies) {\n", " this.links.splice(index, 1);\n", " };\n", " },\n", " \n", " handle_msg: function(content){\n", " var dict = content.dict;\n", " var action = content.action;\n", " var key = content.key;\n", " \n", " if (dict=='node') {\n", " if (action=='add' || action=='set') {\n", " this.update_node(this.try_add_node(key), content.value)\n", " } else if (action=='del') {\n", " this.remove_node(key);\n", " }\n", " \n", " } else if (dict=='adj') {\n", " if (action=='add' || action=='set') {\n", " var links = content.value;\n", " for (var target_id in links) {\n", " this.update_link(this.try_add_link(key, target_id), links[target_id]);\n", " }\n", " } else if (action=='del') {\n", " this.remove_links(key);\n", " }\n", " }\n", " this.start();\n", " },\n", " \n", " start: function() {\n", " var node = this.svg.selectAll(\".node\"),\n", " link = this.svg.selectAll(\".link\");\n", " \n", " var link = link.data(this.force.links(), function(d) { return d.source.id + \"-\" + d.target.id; });\n", " this._update_edge(link.enter().insert(\"line\", \".node\"))\n", " link.exit().remove();\n", " \n", " var node = node.data(this.force.nodes(), function(d) { return d.id;});\n", " var that = this;\n", " this._update_node(node.enter().append(\"circle\"));\n", " node.exit().remove();\n", " \n", " this.force.start();\n", " },\n", " \n", " _update_node: function(node) {\n", " var that = this;\n", " node\n", " .attr(\"id\", function(d) { return that.guid + d.id; })\n", " .attr(\"class\", function(d) { return \"node \" + d.id; })\n", " .attr(\"r\", function(d) {\n", " if (d.r == undefined) {\n", " return 8; \n", " } else {\n", " return d.r;\n", " }\n", " \n", " })\n", " .style(\"fill\", function(d) {\n", " if (d.fill == undefined) {\n", " return that.color(d.group); \n", " } else {\n", " return d.fill;\n", " }\n", " \n", " })\n", " .style(\"stroke\", function(d) {\n", " if (d.stroke == undefined) {\n", " return \"#FFF\"; \n", " } else {\n", " return d.stroke;\n", " }\n", " \n", " })\n", " .style(\"stroke-width\", function(d) {\n", " if (d.strokewidth == undefined) {\n", " return \"#FFF\"; \n", " } else {\n", " return d.strokewidth;\n", " }\n", " \n", " })\n", " .call(this.force.drag);\n", " },\n", " \n", " _update_edge: function(edge) {\n", " var that = this;\n", " edge\n", " .attr(\"id\", function(d) { return that.guid + d.source.id + \"-\" + d.target.id; })\n", " .attr(\"class\", \"link\")\n", " .style(\"stroke-width\", function(d) {\n", " if (d.strokewidth == undefined) {\n", " return \"1.5px\"; \n", " } else {\n", " return d.strokewidth;\n", " }\n", " \n", " })\n", " .style('stroke', function(d) {\n", " if (d.stroke == undefined) {\n", " return \"#999\"; \n", " } else {\n", " return d.stroke;\n", " }\n", " \n", " });\n", " },\n", " \n", " tick: function() {\n", " var node = this.svg.selectAll(\".node\"),\n", " link = this.svg.selectAll(\".link\");\n", " \n", " link.attr(\"x1\", function(d) { return d.source.x; })\n", " .attr(\"y1\", function(d) { return d.source.y; })\n", " .attr(\"x2\", function(d) { return d.target.x; })\n", " .attr(\"y2\", function(d) { return d.target.y; });\n", " \n", " node.attr(\"cx\", function(d) { return d.x; })\n", " .attr(\"cy\", function(d) { return d.y; });\n", " },\n", " \n", " update: function(){\n", " if (!this.has_drawn) {\n", " this.has_drawn = true;\n", " \n", " var width = this.model.get('width'),\n", " height = this.model.get('height');\n", " \n", " this.color = d3.scale.category20();\n", " \n", " this.nodes = [];\n", " this.links = [];\n", " \n", " this.force = d3.layout.force()\n", " .nodes(this.nodes)\n", " .links(this.links)\n", " .charge(function (d) {\n", " if (d.charge === undefined) {\n", " return -120;\n", " } else {\n", " return d.charge;\n", " }\n", " })\n", " .linkDistance(function (d) {\n", " if (d.distance === undefined) {\n", " return 40;\n", " } else {\n", " return d.distance;\n", " }\n", " })\n", " .linkStrength(function (d) {\n", " if (d.strength === undefined) {\n", " return 1.0;\n", " } else {\n", " return d.strength;\n", " }\n", " })\n", " .size([width, height])\n", " .on(\"tick\", $.proxy(this.tick, this));\n", " \n", " this.svg = d3.select(\"#\" + this.guid).append(\"svg\")\n", " .attr(\"width\", width)\n", " .attr(\"height\", height);\n", " \n", " var that = this;\n", " setTimeout(function() {\n", " that.start();\n", " }, 0);\n", " }\n", " \n", " return IPython.WidgetView.prototype.update.call(this);\n", " },\n", " \n", " });\n", " \n", " // Register the D3ForceDirectedGraphView with the widget manager.\n", " IPython.widget_manager.register_widget_view('D3ForceDirectedGraphView', D3ForceDirectedGraphView);\n", "});" ], "metadata": {}, "output_type": "display_data", "text": [ "" ] } ], "prompt_number": 10 }, { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Test" ] }, { "cell_type": "code", "collapsed": false, "input": [ "floating_container = widgets.ContainerWidget(default_view_name='ModalView')\n", "floating_container.description = \"Dynamic D3 rendering of a NetworkX graph\"\n", "floating_container.button_text = \"Render Window\"\n", "floating_container.set_css({\n", " 'width': '420px',\n", " 'height': '350px'}, selector='modal')\n", "\n", "G = EventfulGraph()\n", "d3 = ForceDirectedGraphWidget(G, parent=floating_container)\n", "display(floating_container)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 11 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following code creates an animation of some of the plot's properties." ] }, { "cell_type": "code", "collapsed": false, "input": [ "import time\n", "\n", "G.add_node(1, fill=\"red\", stroke=\"black\")\n", "time.sleep(1.0)\n", "\n", "G.add_node(2, fill=\"gold\", stroke=\"black\")\n", "time.sleep(1.0)\n", "\n", "G.add_node(3, fill=\"green\", stroke=\"black\")\n", "time.sleep(1.0)\n", "\n", "G.add_edges_from([(1,2),(1,3), (2,3)], stroke=\"#aaa\", strokewidth=\"1px\", distance=200, strength=0.5)\n", "time.sleep(1.0)\n", "\n", "G.adj[1][2]['distance'] = 20\n", "time.sleep(1.0)\n", "\n", "G.adj[1][3]['distance'] = 20\n", "time.sleep(1.0)\n", "\n", "G.adj[2][3]['distance'] = 20\n", "time.sleep(1.0)\n", "\n", "G.node[1]['r'] = 16\n", "time.sleep(0.3)\n", "G.node[1]['r'] = 8\n", "G.node[2]['r'] = 16\n", "time.sleep(0.3)\n", "G.node[2]['r'] = 8\n", "G.node[3]['r'] = 16\n", "time.sleep(0.3)\n", "G.node[3]['r'] = 8\n", "\n", "G.node[1]['fill'] = 'purple'\n", "time.sleep(0.3)\n", "G.node[1]['fill'] = 'red'\n", "G.node[2]['fill'] = 'purple'\n", "time.sleep(0.3)\n", "G.node[2]['fill'] = 'gold'\n", "G.node[3]['fill'] = 'purple'\n", "time.sleep(0.3)\n", "G.node[3]['fill'] = 'green'\n", "time.sleep(1.0)\n", "\n", "G.node.clear()\n", "time.sleep(1.0)\n", "\n", "floating_container.close()\n" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 12 }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Prime Factor Finder" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Find the prime numbers inside a large integer" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def is_int(number):\n", " return int(number) == number\n", "\n", "def factor_int(number):\n", " return [i + 1 for i in range(number) if is_int(number / (float(i) + 1.0))] " ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 13 }, { "cell_type": "code", "collapsed": false, "input": [ "import time\n", "BACKGROUND = '#F7EBD5'\n", "PARENT_COLOR = '#66635D'\n", "FACTOR_COLOR = '#6CC5C1'\n", "EDGE_COLOR = '#000000'\n", "PRIME_COLOR = '#E54140'\n", "\n", "existing_graphs = []\n", "\n", "def add_unique_node(graph, value, **kwargs):\n", " index = len(graph.node)\n", " graph.add_node(index, charge=-50, strokewidth=0, value=value, **kwargs)\n", " return index\n", "\n", "def plot_primes(graph, number, parent, start_number, delay=0.0):\n", " if delay > 0.0:\n", " time.sleep(delay)\n", " \n", " factors = factor_int(number)\n", " if len(factors) > 2:\n", " for factor in factors:\n", " if factor != number:\n", " factor_size = max(float(factor) / start_number * 30.0,3.0)\n", " parent_factor_size = max(float(number) / start_number * 30.0,3.0)\n", " index = add_unique_node(graph, number, fill=FACTOR_COLOR, r='%.2fpx' % factor_size)\n", " graph.add_edge(index, parent, distance=parent_factor_size+factor_size, stroke=EDGE_COLOR)\n", " plot_primes(graph, factor, parent=index, start_number=start_number, delay=delay)\n", " else:\n", " # Prime, set parent color to prime color.\n", " graph.node[parent]['fill'] = PRIME_COLOR\n", "\n", "def graph_primes(number, delay):\n", " if len(existing_graphs) > 0:\n", " for graph in existing_graphs:\n", " graph.close()\n", " del existing_graphs[:]\n", " \n", " floating_container = widgets.ContainerWidget(default_view_name='ModalView')\n", " floating_container.description = \"Factors of %d\" % number\n", " floating_container.button_text = str(number)\n", " floating_container.set_css({\n", " 'width': '620px',\n", " 'height': '450px'}, selector='modal')\n", " \n", " graph = EventfulGraph()\n", " d3 = ForceDirectedGraphWidget(graph, parent=floating_container)\n", " floating_container.set_css('background', BACKGROUND)\n", " d3.width = 600\n", " d3.height = 400\n", " display(floating_container)\n", " existing_graphs.append(floating_container)\n", " \n", " index = add_unique_node(graph, number, fill=PARENT_COLOR, r='30px')\n", " plot_primes(graph, number=number, parent=index, start_number=number, delay=delay)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 14 }, { "cell_type": "code", "collapsed": false, "input": [ "box = widgets.ContainerWidget()\n", "box.vbox()\n", "box.align_center()\n", "box.pack_center()\n", "header = widgets.StringWidget(parent=box, default_view_name=\"LabelView\", value=\"

Number Factorizer


\")\n", "subbox = widgets.ContainerWidget(parent=box)\n", "subbox.hbox()\n", "subbox.align_center()\n", "subbox.pack_center()\n", "number = widgets.IntWidget(value=100, parent=subbox)\n", "button = widgets.ButtonWidget(description=\"Calculate\", parent=subbox)\n", "speed = widgets.FloatRangeWidget(parent=box, min=0.0, max=0.5, value=0.4, step=0.01)\n", "display(box)\n", "box.add_class('well well-small')\n", "\n", "def handle_caclulate():\n", " graph_primes(number.value, 0.5-speed.value)\n", "button.on_click(handle_caclulate)\n" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 15 }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Twitter Tweet Watcher" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This example requires the Python \"twitter\" library to be installed (https://github.com/sixohsix/twitter). You can install Python twitter by running `sudo pip install twitter` or `sudo easy_install twitter` from the commandline." ] }, { "cell_type": "code", "collapsed": false, "input": [ "from twitter import *\n", "import time, datetime\n", "import math\n", "\n", "twitter_timestamp_format = \"%a %b %d %X +0000 %Y\"" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 16 }, { "cell_type": "code", "collapsed": false, "input": [ "# Sign on to twitter.\n", "auth = OAuth(\n", " consumer_key='iQvYfTfuD86fgVWGjPY0UA',\n", " consumer_secret='C3jjP6vzYzTYoHV4s5NYPGuRkpT5SulKRKTkRmYg',\n", " token='2218195843-cOPQa0D1Yk3JbvjvsCa0tIYzBOEWxINekmGcEql',\n", " token_secret='3BFncT1zAvJRN6rj8haCxveZVLZWZ23QeulxzByXWlfoO'\n", ")\n", "twitter = Twitter(auth = auth)\n", "twitter_stream = TwitterStream(auth = auth, block = False)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 17 }, { "cell_type": "code", "collapsed": false, "input": [ "widget_container = widgets.ContainerWidget()\n", "widget_container.hbox()\n", "floating_container = widgets.ContainerWidget(parent=widget_container, default_view_name='ModalView')\n", "floating_container.description = \"Dynamic D3 rendering of a NetworkX graph\"\n", "floating_container.button_text = \"Render Window\"\n", "floating_container.set_css({\n", " 'width': '620px',\n", " 'height': '450px'}, selector='modal')\n", "\n", "graph = EventfulGraph()\n", "d3 = ForceDirectedGraphWidget(graph, parent=floating_container)\n", "d3.width = 600\n", "d3.height = 400\n", "\n", "stop_button = widgets.ButtonWidget(parent=widget_container, description=\"Stop\")\n", "stop_button.set_css('margin-left', '5px')\n", " \n", "# Only listen to tweets while they are available and the user\n", "# doesn't want to stop.\n", "stop_listening = [False]\n", "def handle_stop():\n", " stop_listening[0] = True\n", " print(\"Service stopped\")\n", "stop_button.on_click(handle_stop)\n", "\n", "def watch_tweets(screen_name=None):\n", " display(widget_container)\n", " graph.node.clear()\n", " graph.adj.clear()\n", " start_timestamp = None\n", " stop_button.add_class('btn-danger')\n", " \n", " # Get Barack's tweets\n", " tweets = twitter.statuses.user_timeline(screen_name=screen_name)\n", " user_id = twitter.users.lookup(screen_name=screen_name)[0]['id']\n", " \n", " # Determine the maximum number of retweets.\n", " max_retweets = 0.0\n", " for tweet in tweets:\n", " max_retweets = float(max(tweet['retweet_count'], max_retweets))\n", " \n", " \n", " def plot_tweet(tweet, parent=None, elapsed_seconds=1.0, color=\"gold\"):\n", " new_id = tweet['id']\n", " graph.add_node(\n", " new_id, \n", " r=max(float(tweet['retweet_count']) / max_retweets * 30.0, 3.0),\n", " charge=-60,\n", " fill = color,\n", " )\n", " \n", " if parent is not None:\n", " parent_radius = max(float(parent['retweet_count']) / max_retweets * 30.0, 3.0)\n", " graph.node[parent['id']]['r'] = parent_radius\n", " \n", " graph.add_edge(new_id, parent['id'], distance=math.log(elapsed_seconds) * 9.0 + parent_radius)\n", " graph.node[new_id]['fill'] = 'red'\n", " \n", " \n", " # Plot each tweet.\n", " for tweet in tweets:\n", " plot_tweet(tweet)\n", " \n", " kernel=get_ipython().kernel\n", " iterator = twitter_stream.statuses.filter(follow=user_id)\n", " \n", " while not stop_listening[0]:\n", " kernel.do_one_iteration()\n", " \n", " for tweet in iterator:\n", " kernel.do_one_iteration()\n", " if stop_listening[0] or tweet is None:\n", " break\n", " else:\n", " if 'retweeted_status' in tweet:\n", " original_tweet = tweet['retweeted_status']\n", " if original_tweet['id'] in graph.node:\n", " tweet_timestamp = datetime.datetime.strptime(tweet['created_at'], twitter_timestamp_format) \n", " if start_timestamp is None:\n", " start_timestamp = tweet_timestamp\n", " elapsed_seconds = max((tweet_timestamp - start_timestamp).total_seconds(),1.0)\n", " \n", " plot_tweet(tweet, parent=original_tweet, elapsed_seconds=elapsed_seconds)\n", " elif 'id' in tweet:\n", " plot_tweet(tweet, color='lime')\n" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 18 }, { "cell_type": "code", "collapsed": false, "input": [ "watch_tweets(screen_name=\"justinbieber\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Service stopped\n" ] } ], "prompt_number": 19 } ], "metadata": {} } ] }