Code Monkey home page Code Monkey logo

Comments (11)

diitaz93 avatar diitaz93 commented on May 24, 2024 3

Hi,
I just starting using pyvis and I still get this error. I am building a networkx graph from an adjacency matrix, so I can't use Bjorn's workaround. I am working in a jupyter notebook, with python 3.8.10, networkx 2.5.1 and pyvis 0.1.9. My code is as follows:

import networkx as nx
import scipy.sparse as sp
from pyvis.network import Network

M = sp.random(5,5,density=0.6)
G = nx.from_scipy_sparse_matrix(M)
nt = Network('500px', '500px')
nt.from_nx(G)
nt.show("nx.html")

which throws the same error as above:

---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-10-fa438620fb54> in <module>
      6 G = nx.from_scipy_sparse_matrix(M)
      7 nt = Network('500px', '500px')
----> 8 nt.from_nx(G)
      9 nt.show("nx.html")

~/miniconda3/envs/netx/lib/python3.8/site-packages/pyvis/network.py in from_nx(self, nx_graph, node_size_transf, edge_weight_transf, default_node_size, default_edge_weight)
    611                 nodes[e[1]]['size'] = int(node_size_transf(nodes[e[1]]['size']))
    612                 self.add_node(e[0], **nodes[e[0]])
--> 613                 self.add_node(e[1], **nodes[e[1]])
    614 
    615                 if 'weight' not in e[2].keys():

~/miniconda3/envs/netx/lib/python3.8/site-packages/pyvis/network.py in add_node(self, n_id, label, shape, **options)
    205         :type y: num (optional)
    206         """
--> 207         assert isinstance(n_id, str) or isinstance(n_id, int)
    208         if label:
    209             node_label = label

AssertionError: 

from pyvis.

boludo00 avatar boludo00 commented on May 24, 2024

Hi @bjodah ,
would you mind sharing the code you wrote to get this error? I can't seem to reproduce it using numpy and the from_nx method.

This is my output (Python3.6)

from pyvis.network import Network
import networkx as nx
import numpy as np
nxg = nx.Graph()
nxg.add_nodes_from(np.arange(3))
g=Network()
g.from_nx(nxg)
g
<class 'pyvis.network.Network'> |N|=3 |E|=0
g.get_nodes()
[0, 1, 2]
type(g.get_nodes()[0])
numpy.int64

from pyvis.

bjodah avatar bjodah commented on May 24, 2024

Sure, I'm using pyvis 0.1.4.1 (what pip tells me, saw no pyvis.__version__).
Here's a reproducer:

import sys
import networkx as nx
from networkx.drawing.nx_agraph import graphviz_layout
import numpy as np
import pyvis
from pyvis import network as net

print('\n'.join(['%s: %s' % (m.__name__, m.__version__) for m in (nx, np)]))
print('python: {}'.format(sys.version_info))
def mk_graph(from_to):
    dg = nx.DiGraph()
    dg.add_nodes_from([0, 1, 2])
    for src, dst_lst in from_to.items():
        for dst in dst_lst:
            dg.add_edge(src, dst)
    return dg


def viz(gr):
    pos = graphviz_layout(gr)
    g = net.Network(notebook=True)
    g.from_nx(gr)
    for i, node in enumerate(g.nodes):
        node['x'] = pos[i][0]
        node['y'] = pos[i][1]
        node['physics'] = False
    for edge in g.edges:
        edge['physics'] = False
    return g

dg = mk_graph({0: np.array([1, 2], dtype=int)})

viz(dg)

which gives me the following output in jupyter notebook:

networkx: 2.1
numpy: 1.15.0
python: sys.version_info(major=3, minor=6, micro=5, releaselevel='final', serial=0)
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-18-60d494b73f4a> in <module>()
     31 dg = mk_graph({0: np.array([1, 2], dtype=int)})
     32 
---> 33 viz(dg)

<ipython-input-18-60d494b73f4a> in viz(gr)
     20     pos = graphviz_layout(gr)
     21     g = net.Network(notebook=True)
---> 22     g.from_nx(gr)
     23     for i, node in enumerate(g.nodes):
     24         node['x'] = pos[i][0]

/usr/local/lib/python3.6/dist-packages/pyvis/network.py in from_nx(self, nx_graph)
    554             for e in edges:
    555                 self.add_node(e[0], e[0], title=str(e[0]))
--> 556                 self.add_node(e[1], e[1], title=str(e[1]))
    557                 self.add_edge(e[0], e[1])
    558         else:

/usr/local/lib/python3.6/dist-packages/pyvis/network.py in add_node(self, n_id, label, shape, **options)
    195         :type y: num (optional)
    196         """
--> 197         assert isinstance(n_id, str) or isinstance(n_id, int)
    198         if label:
    199             node_label = label

AssertionError: 

from pyvis.

bjodah avatar bjodah commented on May 24, 2024

I can fix the code by simply doing:

dg.add_edge(src, int(dst))

instead, so no biggie.

from pyvis.

boludo00 avatar boludo00 commented on May 24, 2024

So strange, that code didnt throw an error for me
Oh well, glad you got it working. I'll play around more with the types that that JS api accepts.

from pyvis.

Yquetzal avatar Yquetzal commented on May 24, 2024

Hi, great project.
Same error here for a similar case.

from pyvis.

Economax avatar Economax commented on May 24, 2024

Same here, trying to build a network graph from a scipy sparse matrix, converting to networkx and then pyvis.
Originating graph is from scikit-learn's nearest neighbor algorithm.

from pyvis.

SPA20 avatar SPA20 commented on May 24, 2024

Any answer to the above fault ?
I see the same error:

from pyvis.network import Network

nodes =[{"color": "red", "id": "2", "label": "N2", "shape": "o", "size": 50},
{"color": "red", "id": "3", "label": "N3", "shape": "o", "size": 50},
{"color": "red", "id": "1", "label": "N1", "shape": "o", "size": 50},
{"color": "red", "id": "4", "label": "N4", "shape": "o", "size": 50}]

edges=[{"arrows": "to", "font_size": 8, "from": "1", "label": "L12 : 500", "to": "2", "weight": 500},
{"arrows": "to", "font_size": 8, "from": "2", "label": "L231 : 1", "to": "3", "weight": 1},
{"arrows": "to", "font_size": 8, "from": "2", "label": "L232 : 1", "to": "3", "weight": 1},
{"arrows": "to", "font_size": 8, "from": "3", "label": "L34 : 500", "to": "4", "weight": 500},
{"arrows": "to", "font_size": 8, "from": "4", "label": "L41 : 500", "to": "1", "weight": 500}]

G = Network(width="800px", height='600px', heading='Test connectivity', layout=True, bgcolor='#aaaaaa', directed=True)
G.add_nodes(nodes)
G.add_edges(edges)
G.show('pyg.html')

Error:
C:\Apps\python.exe C:/.../ScratchMG2.py
Traceback (most recent call last):
File "C:\Apps\lib\site-packages\pyvis\network.py", line 261, in add_nodes
node = int(node)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'dict'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:/.../ScratchMG2.py", line 17, in
G.add_nodes(nodes)
File "C:\Apps\lib\site-packages\pyvis\network.py", line 265, in add_nodes
assert isinstance(node, str)
AssertionError

Process finished with exit code 1

why is the code trying to check whether the data "node" is a string... As per documentation, the request "add_nodes" should parse a LIST data structure.

from pyvis.

dianamindroc avatar dianamindroc commented on May 24, 2024

Having the same error and could not find a fix yet.

from pyvis.

Rocks-n-Code avatar Rocks-n-Code commented on May 24, 2024

I resolved my similar error by dropping the indexes from my DataFrame with null values in the src and dst columns.

from pyvis.

ignaciogavier avatar ignaciogavier commented on May 24, 2024

After some investigation on the source code pyvis.readthedocs.io/en/latest/_modules/pyvis/network.html I found that the issue is that the only accepted format to add a node is either string and integer (check the add_node method):

assert isinstance(n_id, str) or isinstance(n_id, int)

A way to solve this issue is converting all nodes to string before transferring from networkx.Graph to pyvis.Network.

from pyvis.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.