Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

isinstance check too strict #16

Closed
bjodah opened this issue Dec 5, 2018 · 12 comments
Closed

isinstance check too strict #16

bjodah opened this issue Dec 5, 2018 · 12 comments
Assignees
Labels

Comments

@bjodah
Copy link

bjodah commented Dec 5, 2018

Hi, thank you for making this project available--it looks really interesting.
I'm just getting started and immediately ran into this (when using from_nx):

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

ipdb> p n_id
2
ipdb> p type(n_id)
<class 'numpy.int64'>

one possible fix would be to check against the abstract base class:

ipdb> from numbers import Integral
ipdb> isinstance(n_id, Integral)
True
@boludo00 boludo00 self-assigned this Dec 5, 2018
@boludo00 boludo00 added the hotfix label Dec 5, 2018
@boludo00
Copy link
Collaborator

boludo00 commented Dec 5, 2018

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

@bjodah
Copy link
Author

bjodah commented Dec 6, 2018

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: 

@bjodah
Copy link
Author

bjodah commented Dec 6, 2018

I can fix the code by simply doing:

dg.add_edge(src, int(dst))

instead, so no biggie.

@boludo00
Copy link
Collaborator

boludo00 commented Dec 6, 2018

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.

@diitaz93
Copy link

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: 

@Yquetzal
Copy link

Yquetzal commented Jun 3, 2021

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

@Economax
Copy link

Economax commented Jul 3, 2021

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.

@SPA20
Copy link

SPA20 commented Nov 26, 2021

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.

@dianamindroc
Copy link

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

@Rocks-n-Code
Copy link

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

@ignaciogavier
Copy link

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.

@matriculus
Copy link

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.

It is a bad design to force network nodes to be only int or str. Networkx takes any object and pyvis is based on that and it doesn't. Seems artificial bottleneck.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

10 participants