from IPython.core.display import display, HTML
from string import Template
import pandas as pd
import json, random

HTML('''
<script src="lib/sigmajs/sigma.min.js"></script>
<script src="js/sigma-add-method-neighbors.js"></script>
''')

"""
Explanation: Network Diagram with Sigma.js
This example uses sigma.js to visualize a network produced in python.
Notebook Config
End of explanation
"""


random.seed(42)

n_nodes = 40
n_edges = 200

graph_data = { 'nodes': [], 'edges': [] }

for i in range(n_nodes):
    graph_data['nodes'].append({
            "id": "n" + str(i),
            "label": "n" + str(i),
            "x": random.uniform(0,1),
            "y": random.uniform(0,1),
            "size": random.uniform(0.2,1)
        })

for j in range(n_edges):
    x_center = random.uniform(0,1)
    y_center = random.uniform(0,1)
    x_dist = random.uniform(0.1,0.5)
    y_dist = random.uniform(0.2,0.5)
    neighborhood = []
    for node in graph_data['nodes']:
        if abs(node['x'] - x_center) < x_dist:
            if abs(node['y'] - y_center) < y_dist:
                neighborhood.append(int(node['id'].replace('n','')))
    if len(neighborhood) >= 2:
        ends = random.sample(neighborhood,2)
        graph_data['edges'].append({
                "id": "e" + str(j),
                "source": "n" + str(ends[0]),
                "target": "n" + str(ends[1])
            })

pd.DataFrame(graph_data['nodes']).head()

pd.DataFrame(graph_data['edges']).head()

"""
Explanation: Network Construction
End of explanation
"""


js_text_template = Template(open('js/sigma-graph.js','r').read())

js_text = js_text_template.substitute({'graph_data': json.dumps(graph_data),
                                       'container': 'graph-div'})

html_template = Template('''
<div id="graph-div" style="height:400px"></div>
<script> $js_text </script>
''')
HTML(html_template.substitute({'js_text': js_text}))

"""
Explanation: Visualization
End of explanation
"""


