import graphistry

# To specify Graphistry account & server, use:
# graphistry.register(api=3, username='...', password='...', protocol='https', server='hub.graphistry.com')
# For more options, see https://github.com/graphistry/pygraphistry#configure

import networkx as nx
import pandas as pd

"""
Explanation: Demo: Externally Defined Layouts
This notebook computes a layout using NetworkX and sends it to Graphistry for subsequent interactive analysis.
End of explanation
"""


num_nodes = 1000
G=nx.Graph()
G.add_nodes_from(range(num_nodes))
Edges = [(x, (x * 2) % (num_nodes/5)) for x in range(num_nodes)] + [(x, (x + 1) % 20) for x in range(20)]
G.add_edges_from(Edges)
G

"""
Explanation: Make a NetworkX Graph
End of explanation
"""


%time
pos=nx.fruchterman_reingold_layout(G)
pos[0]

"""
Explanation: Use a NetworkX layout
End of explanation
"""


def pos2df (pos):
    nodes = pd.DataFrame({'key': pos.keys(), 'pos_0': [pos[k][0] for k in pos.keys()], 'pos_1': [pos[k][1] for k in pos.keys()]})
    nodes.columns = ['key', 'x', 'y']
    return nodes


nodes = pos2df(pos)
nodes[:3]

edges = pd.DataFrame(Edges)
edges.columns = ['src', 'dst']
edges[:3]

"""
Explanation: Combine into node, edge dataframes
End of explanation
"""


g = graphistry.nodes(nodes).edges(edges).bind(source='src', destination='dst', node='key')
g.plot()

"""
Explanation: Autolayout mode
End of explanation
"""


g2 = g.settings(url_params={'play':0})
g.plot()

"""
Explanation: Predefined layout mode
As the node table provides "x" and "y" columns, they will be automatically used as starting positions. To prevent the automatic layout algorithm from moving the nodes on load, we also set the URL parameter "play" to 0 seconds. (Both settings will likely change.)
End of explanation
"""


pos2=nx.circular_layout(G, scale=100)
nodes2 = pos2df(pos2)
g2.nodes(nodes2).plot()

"""
Explanation: For fun, here's a circular layout
End of explanation
"""


