Hey!, Currently I am working on a project that require a dynamic network. 
So I learned about pyqtgraph and using it's examples I've made an program 
in which I've implemented all the Graph functions like add edge , add node, 
remove node and remove edge. And everything is working fine. 

This is my code:

#!/usr/bin/env python3
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
import time

class Graph(pg.GraphItem):
    def __init__(self):
        self.textItems = []
        pg.GraphItem.__init__(self)
        self.pos = []
        self.edges = []
        self.texts = []
        
    def setData(self, **kwds):
        self.text = kwds.pop('text', [])
        self.data = kwds
        if 'pos' in self.data:
            npts = self.data['pos'].shape[0]
            self.data['data'] = np.empty(npts, dtype=[('index', int)])
            self.data['data']['index'] = np.arange(npts)
        self.setTexts(self.text)
        self.updateGraph()
        
    def setTexts(self, text):
        for i in self.textItems:
            i.scene().removeItem(i)
        self.textItems = []
        for t in text:
            item = pg.TextItem(t)
            self.textItems.append(item)
            item.setParentItem(self)
        
    def updateGraph(self):
        pg.GraphItem.setData(self, **self.data)
        for i,item in enumerate(self.textItems):
            item.setPos(*self.data['pos'][i])

    def rescale_layout(self,pos,scale=1):
        # rescale to (-scale,scale) in all axes

        # shift origin to (0,0)
        lim=0 # max coordinate for all axes
        for i in range(pos.shape[1]):
            pos[:,i]-=pos[:,i].mean()
            lim=max(pos[:,i].max(),lim)
        # rescale to (-scale,scale) in all directions, preserves aspect
        for i in range(pos.shape[1]):
            pos[:,i]*=scale/lim
        return pos

    def getNodePosn(self,n):
        if n==1:
            return [[0,0]]
        theta = np.linspace(0, 1, n + 1)[:-1] * 2 * np.pi
        theta = theta.astype(np.float32)
        pos = np.column_stack([np.cos(theta), np.sin(theta)])
        pos = self.rescale_layout(pos, scale=1)+(0,0)
        return pos

    def add_node(self,name):
        if name not in self.texts:
            n = len(self.pos)
            self.pos = self.getNodePosn(n+1)
            print(self.pos)
            self.texts.append(name)
            self.setData(pos=np.array(self.pos,dtype=float), 
adj=np.array(self.edges,dtype=int),size=0.1, pxMode=False, 
text=np.array(self.texts))
            print(name + " added ")
    def remove_node(self,n):
        # pass
        self.pos = np.delete(self.pos,n,axis=0)
        self.texts = np.delete(self.texts,n,axis=0)
        print(self.pos.shape)
        for edge in self.edges:
            if edge[0]==n or edge[1]==n:
                self.remove_edge(edge)
                self.setData(pos=np.array(self.pos,dtype=float), 
adj=np.array(self.edges,dtype=int),size=0.1, pxMode=False, 
text=np.array(self.texts))
        self.setData(pos=np.array(self.pos,dtype=float), 
adj=np.array(self.edges,dtype=int),size=0.1, pxMode=False, 
text=np.array(self.texts))
        print(str(n) + " node removed ")


    def add_edge(self,edge):
        if edge not in self.edges:
            print("%s Edge Added"%edge)
            self.edges.append(edge)
            self.setData(pos=np.array(self.pos,dtype=float), 
adj=np.array(self.edges,dtype=int),size=0.1, pxMode=False, 
text=np.array(self.texts))
        print(self.edges)

    def remove_edge(self,edge):
        print(self.edges)
        if edge in self.edges:
            self.edges.remove(edge)
            self.setData(pos=np.array(self.pos,dtype=float), 
adj=np.array(self.edges,dtype=int),size=0.1, pxMode=False, 
text=np.array(self.texts))
            self.updateGraph()
            print("%s Edge removed"%edge)
        else:
            print("No such edge exist")


## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
    import sys,time
        # Enable antialiasing for prettier plots
    app = QtGui.QApplication([])


    pg.setConfigOptions(antialias=True)

    w = pg.GraphicsWindow()
    w.setWindowTitle('pyqtgraph example: CustomGraphItem')
    w.resize(800,600)
    v = w.addViewBox()
    v.setAspectLocked()
    ## Define positions of nodes


    g = Graph()
    v.addItem(g)

    g.add_node('node 0')
    g.add_node('node 1')
    g.add_node('node 2')
    g.add_node('node 3')
    g.add_node('node 4')
    add_edges = [[0,1],[1,2],[0,2],[3,4],[1,4]]
                
    for edge in add_edges:
        g.add_edge(edge)
        app.processEvents()
        time.sleep(1)


    remove_edges = [[0,2],[1,2],[3,4],[0,1],[1,4]]
    

        
        
    for edge in remove_edges:
        g.remove_edge(edge)
        app.processEvents()
        time.sleep(1)



But I'm facing some issue with remove edge functionality. I able to remove 
all edges except the last one. And it throws following error.

  File 
"/Users/sachinsingh/Desktop/Desktop/Development/projects/p2psp/PyQtExperiments/venv/lib/python3.6/site-packages/pyqtgraph/graphicsItems/GraphItem.py",
 
line 131, in paint

    self.generatePicture()

  File 
"/Users/sachinsingh/Desktop/Desktop/Development/projects/p2psp/PyQtExperiments/venv/lib/python3.6/site-packages/pyqtgraph/graphicsItems/GraphItem.py",
 
line 123, in generatePicture

    pts = pts.reshape((pts.shape[0]*pts.shape[1], pts.shape[2]))

IndexError: tuple index out of range

Abort trap: 6

I think this due to the fact that when I remove all of the edges the list 
become empty and so as the points. Hence have no shape.

Please help me out !

-- 
You received this message because you are subscribed to the Google Groups 
"pyqtgraph" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/pyqtgraph/5f1fd3c9-6f0d-4d8f-9c09-02e1abeeeb8f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to