コード例 #1
0
class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self, size=(800, 600), keys="interactive")

        img_data = get_mandlebrot_escape_values(600, 400)
        self.image = ImageVisual(img_data, cmap=colormap)

        image_transform = STTransform(scale=(1.3, 1.3), translate=(100, 0))
        self.image_transform_sys = TransformSystem(self)
        self.image_transform_sys.visual_to_document = image_transform

        self.vertical_bar = get_vertical_bar()

        # construct a default transform that does identity scaling
        # and does not translate the coordinates
        colorbar_transform = NullTransform()
        self.colorbar_transform_sys = TransformSystem(self)
        self.colorbar_transform_sys.visual_to_document = colorbar_transform

        self.show()

    def on_draw(self, event):
        # clear the color buffer
        gloo.clear(color=colormap[0.0])

        self.image.draw(self.image_transform_sys)

        # render the horizontal and vertical bar
        # with the TransformSystem we had created before
        # self.horizontal_bar.draw(self.colorbar_transform_sys)
        self.vertical_bar.draw(self.colorbar_transform_sys)
コード例 #2
0
 def __init__(
         self,
         renderer,
         data,
         cmap="gray",
         clim=(0, 1),
         interp="nearest",
         alpha=100,
         order=1,
 ):
     super().__init__(
         renderer,
         data,
         cmap=cmap,
         clim=clim,
         interp=interp,
         alpha=alpha,
         order=order,
     )
     self.visual = ImageVisual(self._data,
                               clim=self._clim,
                               cmap=cmap,
                               interpolation=self._interp)
     self.alphaFilter = Alpha(self._alpha / 100.0)
     self.visual.attach(self.alphaFilter)
     self._rescale()
     print("Vispy")
コード例 #3
0
ファイル: colorbar_visual.py プロジェクト: astrofrog/vispy
class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self, size=(800, 600), keys="interactive")

        img_data = get_mandlebrot_escape_values(600, 400)
        self.image = ImageVisual(img_data,  cmap=colormap)

        image_transform = STTransform(scale=(1.3, 1.3), translate=(100, 0))
        self.image_transform_sys = TransformSystem(self)
        self.image_transform_sys.visual_to_document = image_transform

        self.vertical_bar = get_vertical_bar()

        # construct a default transform that does identity scaling
        # and does not translate the coordinates
        colorbar_transform = NullTransform()
        self.colorbar_transform_sys = TransformSystem(self)
        self.colorbar_transform_sys.visual_to_document = colorbar_transform

        self.show()

    def on_draw(self, event):
        # clear the color buffer
        gloo.clear(color=colormap[0.0])

        self.image.draw(self.image_transform_sys)

        # render the horizontal and vertical bar
        # with the TransformSystem we had created before
        # self.horizontal_bar.draw(self.colorbar_transform_sys)
        self.vertical_bar.draw(self.colorbar_transform_sys)
コード例 #4
0
    def draw_init(self, backgroundImg=False, fontsize=14, fontColor="white"):
        gloo.clear(color="#231e1f")
        # gloo.set_state("translucent", depth_test=False,blend=True)
        try:
            self.text.clear()
        except:
            pass
        self.selected_point = -1
        self.fontsize = fontsize
        panzoom = PanZoomTransform(self.canvas)

        if backgroundImg:
            self.im = read_png("timg.png")
            self.image = ImageVisual(self.im, method="subdivide")
            self.image.update = self.canvas.update
            self.image.transform = STTransform(
                scale=(2 / self.image.size[0], 2 / self.image.size[1]),
                translate=(-1, -1),
            )
        else:
            self.image = None

        self.markers = PointCollection(
            "agg",
            vertex=self.pvertex,
            fragment=self.pfragment,
            color="shared",
            size="local",
            transform=panzoom,
        )
        self.lines = PathCollection(
            mode="agg",
            vertex=self.lvertex,
            fragment=self.lfragment,
            color="shared",
            linewidth="global",
            transform=panzoom,
        )
        self.markers.update.connect(self.canvas.update)
        self.lines.update.connect(self.canvas.update)
        self.text = TextVisual(u"", color="white")

        self.text.font_size = self.fontsize
        self.text.visible = False
        self.textpos = None

        self.canvas.events.draw.connect(self.on_draw)
        self.canvas.events.resize.connect(self.on_resize)
        self.canvas.events.mouse_press.connect(self.on_mouse_press)
        self.canvas.show()
コード例 #5
0
def test_canvas_render(blend_func):
    """Test rendering a canvas to an array.

    Different blending functions are used to test what various Visuals may
    produce without actually using different types of Visuals.

    """
    with Canvas(size=(125, 125), show=True, title='run') as c:
        im1 = np.zeros((100, 100, 4)).astype(np.float32)
        im1[:, :, 0] = 1
        im1[:, :, 3] = 1

        im2 = np.zeros((50, 50, 4)).astype(np.float32)
        im2[:, :, 1] = 1
        im2[:, :, 3] = 0.4

        # Create the image
        image1 = ImageVisual(im1)
        image1.transform = STTransform(translate=(20, 20, 0))
        image1.transforms.configure(canvas=c, viewport=(0, 0, 125, 125))
        image2 = ImageVisual(im2)
        image2.transform = STTransform(translate=(0, 0, -1))
        image2.transforms.configure(canvas=c, viewport=(0, 0, 125, 125))
        if blend_func:
            image1.set_gl_state(preset='translucent', blend_func=blend_func)
            image2.set_gl_state(preset='translucent', blend_func=blend_func)

        @c.events.draw.connect
        def on_draw(ev):
            gloo.clear('black')
            gloo.set_viewport(0, 0, *c.physical_size)
            image1.draw()
            image2.draw()

        rgba_result = c.render()
        rgb_result = c.render(alpha=False)

        # the results should be the same except for alpha
        np.testing.assert_allclose(rgba_result[..., :3], rgb_result)
        # the image should have something drawn in it
        assert not np.allclose(rgba_result[..., :3], 0)
        # the alpha should not be completely transparent
        assert not np.allclose(rgba_result[..., 3], 0)
        if blend_func is None or 'one' in blend_func:
            # no transparency
            np.testing.assert_allclose(rgba_result[..., 3], 255)
        else:
            # the alpha should have some transparency
            assert (rgba_result[..., 3] != 255).any()
コード例 #6
0
    def __init__(self):
        app.Canvas.__init__(self, size=(800, 600), keys="interactive")

        img_data = get_mandlebrot_escape_values(600, 400)
        self.image = ImageVisual(img_data, cmap=colormap)

        image_transform = STTransform(scale=(1.3, 1.3), translate=(100, 0))
        self.image_transform_sys = TransformSystem(self)
        self.image_transform_sys.visual_to_document = image_transform

        self.vertical_bar = get_vertical_bar()

        # construct a default transform that does identity scaling
        # and does not translate the coordinates
        colorbar_transform = NullTransform()
        self.colorbar_transform_sys = TransformSystem(self)
        self.colorbar_transform_sys.visual_to_document = colorbar_transform

        self.show()
コード例 #7
0
class Canvas(app.Canvas):
    def __init__(self):
        # dimensions of generated image
        img_dim = np.array([700, 500])
        # position of colorbar
        colorbar_pos = np.array([100, 300])
        # size of the colorbar, measured as (major, minor)
        colorbar_size = np.array([400, 20])
        # position of the generated image
        image_pos = np.array([200, 80])

        app.Canvas.__init__(self, size=(800, 600), keys="interactive")

        img_data = get_mandlebrot_escape_values(img_dim[0], img_dim[1])
        self.image = ImageVisual(img_data, cmap=colormap)

        self.image.transform = \
            STTransform(scale=1.1,
                        translate=image_pos)

        self.vertical_bar = get_vertical_bar(colorbar_pos, colorbar_size)

        self.show()

    def on_resize(self, event):
        # Set canvas viewport and reconfigure visual transforms to match.
        vp = (0, 0, self.physical_size[0], self.physical_size[1])
        self.context.set_viewport(*vp)

        self.image.transforms.configure(canvas=self, viewport=vp)
        self.vertical_bar.transforms.configure(canvas=self, viewport=vp)

    def on_draw(self, event):
        # clear the color buffer
        gloo.clear(color=colormap[0.0])

        self.image.draw()

        # render the horizontal and vertical bar
        # with the TransformSystem we had created before
        # self.horizontal_bar.draw(self.colorbar_transform_sys)
        self.vertical_bar.draw()
コード例 #8
0
ファイル: colorbar_visual.py プロジェクト: Calvarez20/vispy
class Canvas(app.Canvas):
    def __init__(self):
        # dimensions of generated image
        img_dim = np.array([700, 500])
        # position of colorbar
        colorbar_pos = np.array([100, 300])
        # size of the colorbar, measured as (major, minor)
        colorbar_size = np.array([400, 20])
        # position of the generated image
        image_pos = np.array([200, 80])

        app.Canvas.__init__(self, size=(800, 600), keys="interactive")

        img_data = get_mandlebrot_escape_values(img_dim[0], img_dim[1])
        self.image = ImageVisual(img_data,  cmap=colormap)

        self.image.transform = \
            STTransform(scale=1.1,
                        translate=image_pos)

        self.vertical_bar = get_vertical_bar(colorbar_pos, colorbar_size)

        self.show()

    def on_resize(self, event):
        # Set canvas viewport and reconfigure visual transforms to match.
        vp = (0, 0, self.physical_size[0], self.physical_size[1])
        self.context.set_viewport(*vp)

        self.image.transforms.configure(canvas=self, viewport=vp)
        self.vertical_bar.transforms.configure(canvas=self, viewport=vp)

    def on_draw(self, event):
        # clear the color buffer
        gloo.clear(color=colormap[0.0])

        self.image.draw()

        # render the horizontal and vertical bar
        # with the TransformSystem we had created before
        # self.horizontal_bar.draw(self.colorbar_transform_sys)
        self.vertical_bar.draw()
コード例 #9
0
class VispyLayer(Layer):
    def __init__(self,
                 renderer,
                 data,
                 cmap='viridis',
                 clim=(0, 1),
                 interp='nearest',
                 alpha=100,
                 order=1):
        super().__init__(renderer,
                         data,
                         cmap=cmap,
                         clim=clim,
                         interp=interp,
                         alpha=alpha,
                         order=order)
        self.visual = ImageVisual(self._data,
                                  clim=self._clim,
                                  cmap=self._cmap,
                                  interpolation=self._interp)
        self.alphaFilter = Alpha(self._alpha / 100.)
        self.visual.attach(self.alphaFilter)
        self._rescale()

    def set_order(self, order):
        super().set_order(order)
        self.visual.transform.translate = (-1, 1, -.01 * order)

    def _convert_cmap(self, cmap):
        if type(cmap) == list:
            cmap = Colormap(ColorArray(cmap))
        return cmap

    def _rescale(self):
        height, width = self._data.shape[:2]
        vscale = -2. / height
        hscale = 2. / width
        zdepth = -0.01 * self._order
        transform = transforms.STTransform(scale=(hscale, vscale),
                                           translate=(-1, 1, zdepth))
        self.visual.transform = transform

    def update_image(self, data, **kwargs):
        self.visual.set_data(data)
        if 'clim' in kwargs:
            self.visual.clim = kwargs['clim']
        if 'cmap' in kwargs:
            cmap = self._convert_cmap(kwargs['cmap'])
            self.visual.cmap = cmap
        if 'interp' in kwargs:
            self.visual.interpolation = kwargs['interp']
        if 'alpha' in kwargs:
            self.alphaFilter.alpha = kwargs['alpha'] / 100.
        if 'order' in kwargs:
            self.set_order(kwargs['order'])
        super().update_image(data, **kwargs)

    def draw(self):
        if self.is_visible():
            self.visual.draw()
コード例 #10
0
    def __init__(self):
        # dimensions of generated image
        img_dim = np.array([700, 500])
        # position of colorbar
        colorbar_pos = np.array([100, 300])
        # size of the colorbar, measured as (major, minor)
        colorbar_size = np.array([400, 20])
        # position of the generated image
        image_pos = np.array([200, 80])

        app.Canvas.__init__(self, size=(800, 600), keys="interactive")

        img_data = get_mandlebrot_escape_values(img_dim[0], img_dim[1])
        self.image = ImageVisual(img_data, cmap=colormap)

        self.image.transform = \
            STTransform(scale=1.1,
                        translate=image_pos)

        self.vertical_bar = get_vertical_bar(colorbar_pos, colorbar_size)

        self.show()
コード例 #11
0
 def __init__(self,
              renderer,
              data,
              cmap='viridis',
              clim=(0, 1),
              interp='nearest',
              alpha=100,
              order=1):
     super().__init__(renderer,
                      data,
                      cmap=cmap,
                      clim=clim,
                      interp=interp,
                      alpha=alpha,
                      order=order)
     self.visual = ImageVisual(self._data,
                               clim=self._clim,
                               cmap=self._cmap,
                               interpolation=self._interp)
     self.alphaFilter = Alpha(self._alpha / 100.)
     self.visual.attach(self.alphaFilter)
     self._rescale()
コード例 #12
0
ファイル: colorbar_visual.py プロジェクト: jay3sh/vispy
    def __init__(self):
        app.Canvas.__init__(self, size=(800, 600), keys="interactive")

        img_data = get_mandlebrot_escape_values(600, 400)
        self.image = ImageVisual(img_data,  cmap=colormap)

        image_transform = STTransform(scale=(1.3, 1.3), translate=(100, 0))
        self.image_transform_sys = TransformSystem(self)
        self.image_transform_sys.visual_to_document = image_transform

        self.vertical_bar = get_vertical_bar()

        # construct a default transform that does identity scaling
        # and does not translate the coordinates
        colorbar_transform = NullTransform()
        self.colorbar_transform_sys = TransformSystem(self)
        self.colorbar_transform_sys.visual_to_document = colorbar_transform

        self.show()
コード例 #13
0
ファイル: colorbar_visual.py プロジェクト: Calvarez20/vispy
    def __init__(self):
        # dimensions of generated image
        img_dim = np.array([700, 500])
        # position of colorbar
        colorbar_pos = np.array([100, 300])
        # size of the colorbar, measured as (major, minor)
        colorbar_size = np.array([400, 20])
        # position of the generated image
        image_pos = np.array([200, 80])

        app.Canvas.__init__(self, size=(800, 600), keys="interactive")

        img_data = get_mandlebrot_escape_values(img_dim[0], img_dim[1])
        self.image = ImageVisual(img_data,  cmap=colormap)

        self.image.transform = \
            STTransform(scale=1.1,
                        translate=image_pos)

        self.vertical_bar = get_vertical_bar(colorbar_pos, colorbar_size)

        self.show()
コード例 #14
0
class GraphHigh(QtWidgets.QWidget):
    """Widget defined in Qt Designer"""

    filter_signal = QtCore.Signal(object, object)
    neighbors_signal = QtCore.Signal(str, object)

    def __init__(self, parent=None):

        super(GraphHigh, self).__init__(parent)
        self.canvas = app.Canvas(size=(1800, 600),
                                 keys="interactive",
                                 show=False)
        gloo.set_viewport(0, 0, self.canvas.size[0], self.canvas.size[1])

        gloo.set_state("translucent", depth_test=False)

        # self.setObjectName("ThemeWidget")
        # self.setStyleSheet("QWidget#ThemeWidget{background:transparent;border: 0px;}")
        # self.canvas.native.setObjectName("ThemeWidget")
        # self.canvas.native.setStyleSheet("QWidget#ThemeWidget{background:transparent;border: 0px;}")
        self.filter_signal.connect(self.updateMarkerVisible)

        vbl = QtWidgets.QVBoxLayout()
        vbl.setSpacing(0)
        vbl.setContentsMargins(0, 0, 0, 0)
        vbl.addWidget(self.canvas.native)
        self.setLayout(vbl)

        gloo.clear(color="#231e1f")
        # gloo.set_state("translucent", depth_test=False,blend=True)
        self.canvas.show()
        self.pvertex = """
        varying float v_size;
varying vec4  v_color;
varying float v_linewidth;
varying float v_antialias;

// Main (hooked)
// ------------------------------------
void main (void)
{
    fetch_uniforms();

    v_size = size;
    v_color = color;

    gl_Position = $transform(vec4(position, 1));
    gl_PointSize = size + 2.0 * (1.0 + 1.5*1.0);
}
        """
        self.pfragment = """
        #include "markers/disc.glsl"
#include "antialias/filled.glsl"

// Varyings
// ------------------------------------
varying float v_size;
varying vec4  v_color;

// Main
// ------------------------------------
void main()
{
    vec2 P = gl_PointCoord.xy - vec2(0.5,0.5);
    float point_size = v_size  + 2. * (1.0 + 1.5*1.0);
    float distance = marker_disc(P*point_size, v_size);
    gl_FragColor = filled(distance, 1.0, 1.0, v_color);
}
        """
        self.lvertex = """
#include "misc/viewport-NDC.glsl"

// Externs
// ------------------------------------
// extern vec3  prev;
// extern vec3  curr;
// extern vec3  next;
// extern float id;
// extern vec4  color;
// extern float antialias;
// extern float linewidth;
// extern vec4 viewport;
//        vec4 transform(vec3 position);

// Varyings
// ------------------------------------
varying float v_antialias;
varying float v_linewidth;
varying float v_distance;
varying vec4  v_color;


// Main
// ------------------------------------
void main (void)
{
    // This function is externally generated
    fetch_uniforms();
    v_linewidth = linewidth;
    v_antialias = antialias;
    v_color     = color;

    // transform prev/curr/next
    vec4 prev_ = $transform(vec4(prev, 1));
    vec4 curr_ = $transform(vec4(curr, 1));
    vec4 next_ = $transform(vec4(next, 1));

    // prev/curr/next in viewport coordinates
    vec2 _prev = NDC_to_viewport(prev_, viewport.zw);
    vec2 _curr = NDC_to_viewport(curr_, viewport.zw);
    vec2 _next = NDC_to_viewport(next_, viewport.zw);

    // Compute vertex final position (in viewport coordinates)
    float w = linewidth/2.0 + 1.5*antialias;
    float z;
    vec2 P;
    if( curr == prev) {
        vec2 v = normalize(_next.xy - _curr.xy);
        vec2 normal = normalize(vec2(-v.y,v.x));
        P = _curr.xy + normal*w*id;
    } else if (curr == next) {
        vec2 v = normalize(_curr.xy - _prev.xy);
        vec2 normal  = normalize(vec2(-v.y,v.x));
        P = _curr.xy + normal*w*id;
    } else {
        vec2 v0 = normalize(_curr.xy - _prev.xy);
        vec2 v1 = normalize(_next.xy - _curr.xy);
        vec2 normal  = normalize(vec2(-v0.y,v0.x));
        vec2 tangent = normalize(v0+v1);
        vec2 miter   = vec2(-tangent.y, tangent.x);
        float l = abs(w / dot(miter,normal));
        P = _curr.xy + miter*l*sign(id);
    }

    if( abs(id) > 1.5 ) v_color.a = 0.0;

    v_distance = w*id;
    gl_Position = viewport_to_NDC(vec3(P, curr_.z/curr_.w), viewport.zw);

}
        """
        self.lfragment = """
#include "antialias/antialias.glsl"

// Varyings
// ------------------------------------
varying vec4  v_color;
varying float v_distance;
varying float v_linewidth;
varying float v_antialias;

// Main
// ------------------------------------
void main()
{
    if (v_color.a == 0.)  { discard; }
    gl_FragColor = stroke(v_distance, v_linewidth, v_antialias, v_color);
}
        """

    def draw_init(self, backgroundImg=False, fontsize=14, fontColor="white"):
        gloo.clear(color="#231e1f")
        # gloo.set_state("translucent", depth_test=False,blend=True)
        try:
            self.text.clear()
        except:
            pass
        self.selected_point = -1
        self.fontsize = fontsize
        panzoom = PanZoomTransform(self.canvas)

        if backgroundImg:
            self.im = read_png("timg.png")
            self.image = ImageVisual(self.im, method="subdivide")
            self.image.update = self.canvas.update
            self.image.transform = STTransform(
                scale=(2 / self.image.size[0], 2 / self.image.size[1]),
                translate=(-1, -1),
            )
        else:
            self.image = None

        self.markers = PointCollection(
            "agg",
            vertex=self.pvertex,
            fragment=self.pfragment,
            color="shared",
            size="local",
            transform=panzoom,
        )
        self.lines = PathCollection(
            mode="agg",
            vertex=self.lvertex,
            fragment=self.lfragment,
            color="shared",
            linewidth="global",
            transform=panzoom,
        )
        self.markers.update.connect(self.canvas.update)
        self.lines.update.connect(self.canvas.update)
        self.text = TextVisual(u"", color="white")

        self.text.font_size = self.fontsize
        self.text.visible = False
        self.textpos = None

        self.canvas.events.draw.connect(self.on_draw)
        self.canvas.events.resize.connect(self.on_resize)
        self.canvas.events.mouse_press.connect(self.on_mouse_press)
        self.canvas.show()

    def init_data2(self, filename):
        work = GraphWork()
        self.SubG = None
        self.G = work.readFile(filename)
        # Compute centrality measures
        work.DegreeCentrality(self.G)
        # Compute community measures
        work.LouvainCommunity(self.G)

        # Compute node sizes
        self.marksize = work.setGNodesSize(self.G)

        # Compute node colors
        self.colors = work.setGNodesColor(self.G)

        self.labels = work.getGNodesAttrList(self.G, "label")

        # Compute graph layout
        node_pos, edge_pos = work.pygraphviz_layout(self.G,
                                                    prog="sfdp",
                                                    bundle=False)

        # Number of nodes
        self.npts = self.G.number_of_nodes()
        # Number of edges
        self.nlinks = self.G.number_of_edges()

        print("aaaa")
        self.drawgraph(node_pos, edge_pos, self.colors, self.marksize)

    def init_data(self, G, marksize, colors, labels, node_pos, edge_pos, npts,
                  nlinks):
        self.G = G
        self.SubG = None
        self.marksize = marksize
        self.colors = colors
        self.labels = labels
        # Number of nodes
        self.npts = npts
        # Number of edges
        self.nlinks = nlinks

        self.draw(node_pos, edge_pos, self.colors, self.marksize)

    def draw(self, pos, edges, colors, marksize):
        # Number of nodes
        self.npts = len(pos)
        # Number of edges
        self.nlinks = len(edges)

        self.colors = np.array(self.colors)
        self.marksize = marksize

        self.pos = np.array(pos)

        edges = np.array(edges)
        # Set node positions
        self.get_Range()
        self.pos = (self.pos - (self.width / 2, self.height / 2)) * (
            2 / self.width,
            2 / self.height,
        )
        self.pos = np.c_[self.pos, np.zeros(len(self.pos))]

        self.markers.append(self.pos, size=self.marksize)
        self.markers["color"] = self.colors

        # Set edge colors
        self.normal_selected_linecolor = np.array([[0.86, 0.86, 0.86, 0.4],
                                                   [1, 0, 0, 1],
                                                   [0.86, 0.86, 0.86, 0.1]])
        self.lineselected = np.zeros(self.nlinks, dtype=int)

        self.edges = []

        for i in edges:
            i = np.array(i)
            i = (i - (self.width / 2, self.height / 2)) * (
                2 / self.width,
                2 / self.height,
            )
            self.edges.append(i)
            tmp = np.c_[i, np.ones(len(i))]
            self.lines.append(tmp, itemsize=len(i))
        self.edges = np.array(self.edges)
        self.lines["color"] = (0.86, 0.86, 0.86, 0.6)
        self.lines["linewidth"] = 0.5
        self.selected_point = -1
        self.canvas.show()

    def get_Range(self):
        x = self.pos[:, 0]
        y = self.pos[:, 1]
        self.width = (x.max() - x.min()) * 1.05
        self.height = (y.max() - y.min()) * 1.05
        if x.max() == x.min():
            self.width = x.max() * 1.05
        if y.max() == y.min():
            self.height = y.max() * 1.05

    def on_draw(self, e):
        gloo.clear(color="#231e1f")
        if self.image:
            self.image.draw()

        self.lines.draw()
        self.markers.draw()
        try:
            self.text.draw()
        except:
            vp = (0, 0, self.canvas.physical_size[0],
                  self.canvas.physical_size[1])
            self.canvas.context.set_viewport(*vp)
            self.markers["viewport"] = vp
            self.lines["viewport"] = vp
            self.text.transforms.configure(canvas=self.canvas, viewport=vp)
            self.text.draw()

        if self.textpos != None:
            npos = self.pos[self.textpos]

            npos = self.itransPos(npos)
            self.text.pos = [npos[0], npos[1]]

        self.canvas.update()

    def on_resize(self, event):
        vp = (0, 0, self.canvas.physical_size[0], self.canvas.physical_size[1])
        self.canvas.context.set_viewport(*vp)
        self.markers["viewport"] = vp
        self.lines["viewport"] = vp
        self.text.transforms.configure(canvas=self.canvas, viewport=vp)

    def transPos(self, pos):
        npos = self.markers.transform.canvas_tr.map(pos)
        npos = (npos - self.markers.transform.translate
                ) / self.markers.transform.scale
        return npos

    def itransPos(self, pos):
        npos = [pos[0], pos[1], 0, 1]
        npos = self.markers.transform.canvas_tr.imap(
            npos * self.markers.transform.scale +
            self.markers.transform.translate)
        return npos

    def on_resize(self, event):
        vp = (0, 0, self.canvas.physical_size[0], self.canvas.physical_size[1])
        self.canvas.context.set_viewport(*vp)
        self.lines["viewport"] = vp
        self.markers["viewport"] = vp
        self.text.transforms.configure(canvas=self.canvas, viewport=vp)

    def on_mouse_press(self, event):
        if event.button == 1:
            if self.selected_point != -1:
                self.updateSubGVisible()
                self.selected_point = -1
            if self.selected_point == -1:
                width = self.canvas.physical_size[0]
                height = self.canvas.physical_size[1]
                pos = self.markers.transform.canvas_tr.map(event.pos)
                pos = (pos - self.markers.transform.translate
                       ) / self.markers.transform.scale
                D = self.pos - [pos[0], pos[1], 0]
                D = np.sqrt((D**2).sum(axis=1))
                self.selected_point = np.argmin(D)

                if D[self.selected_point] < 0.01:
                    self.colors[:, 3:4] = 1

                    nid = int(self.selected_point)
                    seleted = self.labels[nid]
                    self.updateMarkerVisible(seleted)
                else:
                    self.selected_point = -1
                    self.textpos = None
                    self.text.visible = False
                    if self.SubG is None:
                        self.neighbors_signal.emit("", None)
                    else:
                        self.neighbors_signal.emit("", [])

    def on_mouse_release(self, event):
        self.selected_point = -1

    def setSubG(self, SubG):
        self.SubG = SubG

    def updateSubGVisible(self):
        if self.SubG is None:
            self.colors[:, 3:4] = 1
            self.markers["color"] = self.colors
            self.lineselected[:] = 0
            self.lines["color"] = self.normal_selected_linecolor[
                self.lineselected]
            self.canvas.update()
        else:
            result = self.SubG.nodes()
            edges = self.SubG.edges()
            for i, n in enumerate(self.G.nodes()):
                if n not in result:
                    self.colors[i][3] = 0.0
                else:
                    self.colors[i][3] = 1.0

            self.markers["color"] = self.colors

            itemindex = []
            for i, edge in enumerate(self.G.edges()):
                if edge in edges:
                    itemindex.append(i)

            self.lineselected[:] = 2

            for i in itemindex:
                self.lineselected[i] = 1
            self.lines["color"] = self.normal_selected_linecolor[
                self.lineselected]
            self.canvas.update()

    def updateMarkerVisible(self, seleted):

        if self.SubG is None:
            G = self.G
            self.colors[:, 3:4] = 1
            self.markers["color"] = self.colors
            self.lineselected[:] = 0
            self.lines["color"] = self.normal_selected_linecolor[
                self.lineselected]
        else:
            G = self.SubG
            result = self.SubG.nodes()
            edges = self.SubG.edges()
            for i, n in enumerate(self.G.nodes()):
                if n not in result:
                    self.colors[i][3] = 0.0
                else:
                    self.colors[i][3] = 1.0

            self.markers["color"] = self.colors
        if seleted in G.nodes():
            nid = self.labels.index(seleted)
            self.selected_point = nid
            result = []
            nodes = G.nodes()
            for i, edge in enumerate(self.G.edges()):
                if seleted == edge[0] and edge[1] in nodes:
                    result.append(edge[1])
                if seleted == edge[1] and edge[0] in nodes:
                    result.append(edge[0])
            result = list(set(result))
            sss = self.getNodeInfo(G, seleted)
            self.neighbors_signal.emit(sss, result)
            for i, n in enumerate(self.G.nodes()):
                if n not in result:
                    self.colors[i][3] = 0.0

            self.colors[self.selected_point][3] = 1

            self.markers["color"] = self.colors
            self.text.text = seleted

            npos = self.pos[nid]
            npos = [npos[0], npos[1], 0, 1]
            npos = (npos * self.markers.transform.scale +
                    self.markers.transform.translate)
            npos = self.markers.transform.canvas_tr.imap(npos)
            self.textpos = nid
            self.text.pos = [npos[0], npos[1]]
            self.text.visible = True

            itemindex = []
            edges = G.edges()
            for i, edge in enumerate(self.G.edges()):
                if seleted == edge[0] or seleted == edge[1]:
                    if edge in edges:
                        itemindex.append(i)

            self.lineselected[:] = 2

            for i in itemindex:
                self.lineselected[i] = 1
            self.lines["color"] = self.normal_selected_linecolor[
                self.lineselected]
            self.canvas.update()
        else:
            self.text.visible = False
            if self.SubG is None:
                self.neighbors_signal.emit("", None)
            else:
                self.neighbors_signal.emit("", [])

            self.selected_point = -1

    def getNodeInfo(self, G, node):
        nodesAttrs = [
            ("label", "Node name"),
            ("node_type", "Node type"),
            ("InDegree", "InDegree centrality"),
            ("OutDegree", "OutDegree centrality"),
            ("Degree", "Degree centrality"),
            ("Betweeness", "Betweenness centrality"),
            ("Closeness", "Closeness centrality"),
            ("PageRank", "PageRank centrality"),
            ("Louvain", "Louvain community"),
            ("Label propagation", "Label propagation community"),
            ("Union find", "Union find community"),
        ]
        outstr = ""
        data = G.nodes()[node]
        for attr in nodesAttrs:
            outstr = outstr + "%s: %s\n" % (attr[1], data[attr[0]])
        return outstr

    def updateMarkersColor(self, attrName):
        work = GraphWork()
        self.colors = work.setGNodesColor(self.G, attrName=attrName)
        self.colors = np.array(self.colors)
        if self.SubG is None:
            self.colors[:, 3:4] = 1
        else:
            result = self.SubG.nodes()
            for i, n in enumerate(self.G.nodes()):
                if n not in result:
                    self.colors[i][3] = 0.0
                else:
                    self.colors[i][3] = 1.0
        self.markers["color"] = self.colors
        self.canvas.update()

    def updateMarkersSize(self, attrName):
        work = GraphWork()
        self.marksize = work.setGNodesSize(self.G, attrName=attrName)
        for i in self.pos:
            self.markers.__delitem__(0)
        self.markers.append(self.pos, size=self.marksize)
        if self.SubG is None:
            self.colors[:, 3:4] = 1
        else:
            result = self.SubG.nodes()
            for i, n in enumerate(self.G.nodes()):
                if n not in result:
                    self.colors[i][3] = 0.0
                else:
                    self.colors[i][3] = 1.0
        self.markers["color"] = self.colors
        self.canvas.update()
コード例 #15
0
class VispyLayer(Layer):
    def __init__(
            self,
            renderer,
            data,
            cmap="gray",
            clim=(0, 1),
            interp="nearest",
            alpha=100,
            order=1,
    ):
        super().__init__(
            renderer,
            data,
            cmap=cmap,
            clim=clim,
            interp=interp,
            alpha=alpha,
            order=order,
        )
        self.visual = ImageVisual(self._data,
                                  clim=self._clim,
                                  cmap=cmap,
                                  interpolation=self._interp)
        self.alphaFilter = Alpha(self._alpha / 100.0)
        self.visual.attach(self.alphaFilter)
        self._rescale()
        print("Vispy")

    def set_order(self, order):
        super().set_order(order)
        self.visual.transform.translate = (-1, 1, -0.01 * order)

    def _convert_cmap(self, cmap):
        if type(cmap) == list:
            cmap = Colormap(ColorArray(cmap))
        return cmap

    def _rescale(self):
        height, width = self._data.shape[:2]
        vscale = -2.0 / height
        hscale = 2.0 / width
        zdepth = -0.01 * self._order
        transform = transforms.STTransform(scale=(hscale, vscale),
                                           translate=(-1, 1, zdepth))
        self.visual.transform = transform

    def update_image(self, data, **kwargs):
        self.visual.set_data(data)
        if "clim" in kwargs:
            self.visual.clim = kwargs["clim"]
        if "cmap" in kwargs:
            cmap = self._convert_cmap(kwargs["cmap"])
            self.visual.cmap = cmap
        if "interp" in kwargs:
            self.visual.interpolation = kwargs["interp"]
        if "alpha" in kwargs:
            self.alphaFilter.alpha = kwargs["alpha"] / 100.0
        if "order" in kwargs:
            self.set_order(kwargs["order"])
        super().update_image(data, **kwargs)

    def draw(self):
        if self.is_visible():
            self.visual.draw()