Exemplo n.º 1
0
    def update_state(self):
        print('davor')
        g = self.graph_generator.__next__()
        #print(g)
        exists = g.new_vertex_property('bool', False)
        reset = g.new_vertex_property('bool', True)

        g, exists = self.update_graph(g, exists)
        g.set_vertex_filter(exists)
        self.set_drawing_properties(edge_size='cscore')
        arf_layout(g, pos=self.pos, max_iter=100, dt=1e-4)

        # The movement of the vertices may cause them to leave the display area. The
        # following function rescales the layout to fit the window to avoid this.
        #if count > 0 and count % 1000 == 0:
        #    win.graph.fit_to_window(ink=True)

        # The following will force the re-drawing of the graph, and issue a
        # re-drawing of the GTK window.
        self.win.graph.regenerate_surface()
        self.win.graph.queue_draw()

        g.set_vertex_filter(reset)

        # We need to return True so that the main loop will call this function more
        # than once.
        self.count += 1
        return True
Exemplo n.º 2
0
def run_visualization():
    global pos
    graph = Graph().graph

    def update_state():
        global count
        global pos

        if count % 60 == 0:
            logging.debug('fit to window')
            win.graph.fit_to_window(ink=True)
        count += 1

        pos = arf_layout(pos.get_graph(), pos=pos, max_iter=1)
        win.graph.regenerate_surface(lazy=False)
        win.graph.queue_draw()
        return True

    while graph.num_vertices() < 2:
        graph.add_vertex()

    pos = arf_layout(graph, max_iter=0)
    win = GraphWindow(pos.get_graph(),
                      pos,
                      geometry=(500, 400),
                      edge_color=(0, 6, 0, 6, 0, 6, 0, 6),
                      bg_color=(0, 0, 0, 255),
                      vertex_text=graph.vertex_index,
                      vertex_font_size=48)
    win.connect("delete-event", Gtk.main_quit)
    win.fullscreen()
    GObject.timeout_add(100, update_state)
    win.show_all()
    Gtk.main()
Exemplo n.º 3
0
    def do_draw(self, line):
        g = self.graph

        spectral = plt.get_cmap('spectral')
        n_levels = len(types)
        val = 0.0
        step = 1.0 / n_levels
        colors = {}
        for k in types.keys():
            colors[k] = spectral(val)
            val += step
        g.vp.v_colors = g.new_vp('vector<float>')
        for v in g.vertices():
            g.vp.v_colors[v] = colors[g.vp.type[v]]

        if line:
            gt_draw.graph_draw(self.graph,
                               pos=gt_draw.arf_layout(g),
                               output_size=(2400,2400),
                               vertex_text=g.vp.type,
                               vertex_fill_color=g.vp.v_colors,
                               vertex_size=10,
                               output=line)
        else:
            gt_draw.interactive_window(self.graph,
                                       vertex_fill_color=g.vp.v_colors,
                                       vertex_size=10,
                                       display_props=[g.vp.type,
                                                      g.vp.data,
                                                      g.vp.pool,
                                                      g.vp.unit ])
def run_visualization():
    global pos
    graph = Graph().graph

    def update_state():
        global count
        global pos

        if count % 60 == 0:
            logging.debug('fit to window')
            win.graph.fit_to_window(ink=True)
        count += 1

        pos = arf_layout(pos.get_graph(), pos=pos, max_iter=1)
        win.graph.regenerate_surface(lazy=False)
        win.graph.queue_draw()
        return True

    while graph.num_vertices() < 2:
        graph.add_vertex()

    pos = arf_layout(graph, max_iter=0)
    win = GraphWindow(
        pos.get_graph(), pos,
        geometry=(500, 400),
        edge_color=(0,6, 0,6, 0,6, 0,6),
        bg_color=(0,0,0,255),
        vertex_text=graph.vertex_index,
        vertex_font_size=48)
    win.connect("delete-event", Gtk.main_quit)
    win.fullscreen()
    GObject.timeout_add(100, update_state)
    win.show_all()
    Gtk.main()
Exemplo n.º 5
0
    def update_state():
        global count
        global pos

        if count % 60 == 0:
            logging.debug('fit to window')
            win.graph.fit_to_window(ink=True)
        count += 1

        pos = arf_layout(pos.get_graph(), pos=pos, max_iter=1)
        win.graph.regenerate_surface(lazy=False)
        win.graph.queue_draw()
        return True
    def update_state():
        global count
        global pos

        if count % 60 == 0:
            logging.debug('fit to window')
            win.graph.fit_to_window(ink=True)
        count += 1

        pos = arf_layout(pos.get_graph(), pos=pos, max_iter=1)
        win.graph.regenerate_surface(lazy=False)
        win.graph.queue_draw()
        return True
Exemplo n.º 7
0
    def visualize(self,
                  output_size=None,
                  vertex_size=None,
                  vertex_min=None,
                  vertex_max=None,
                  vertex_text=None,
                  vertex_font_size=None,
                  vertex_color_by_type=True,
                  edge_size=None,
                  edge_min=None,
                  edge_max=None):

        self.set_drawing_properties(output_size=output_size,
                                    vertex_size=vertex_size,
                                    vertex_min=vertex_min,
                                    vertex_max=vertex_max,
                                    vertex_text=vertex_text,
                                    vertex_font_size=vertex_font_size,
                                    vertex_color_by_type=vertex_color_by_type,
                                    edge_size=edge_size,
                                    edge_min=edge_min,
                                    edge_max=edge_max)
        self.pos = arf_layout(self.gt, max_iter=100, dt=1e-4)
        self.graph_generator = self.dynamic_graph_generator()
        self.gt.clear_edges()
        self.win = GraphWindow(
            self.gt,
            self.pos,
            geometry=self.output_size,
            vprops=self.drawing_props['vprops'],
            eprops=self.drawing_props['eprops'],
            edge_marker_size=
            5,  # müsste auch noch über set properties gesetzt werden können.
            vertex_text_position=
            -2,  # müsste auch noch über set properties gesetzt werden können.
            vertex_font_family=
            'sans-serif',  # müsste auch noch über set properties gesetzt werden können.
            vertex_font_weight=cairo.
            FONT_WEIGHT_BOLD,  # müsste auch noch über set properties gesetzt werden können.
            edge_color='#cbcbcb'
        )  # müsste auch noch über set properties gesetzt werden können.

        cid = GObject.idle_add(self.update_state)

        # We will give the user the ability to stop the program by closing the window.
        self.win.connect("delete_event", Gtk.main_quit)

        # Actually show the window, and start the main loop.
        self.win.show_all()
        Gtk.main()
Exemplo n.º 8
0
    def visualize(self, graph_view, outfile, drawing_props):
        g = graph_view
        props = self.process_drawing_properties(g, drawing_props)
        out = os.path.join(
            self.results_path, 'arf_' + drawing_props['props_type'] + '_' +
            outfile + '.' + props['fmt'])
        os.makedirs(os.path.dirname(out), exist_ok=True)

        pos = arf_layout(g, max_iter=0)
        # pos = arf_layout(g, max_iter=100, dt=1e-4)
        # According to https://git.skewed.de/count0/graph-tool/issues/239 setting max_iter and dt fixed cairo error.
        # Check quality?!
        try:
            if len(list(g.vertices())) > 0:
                graph_draw(g,
                           pos,
                           vprops=props['vprops'],
                           eprops=props['eprops'],
                           output_size=(props['output_width'],
                                        props['output_height']),
                           output=out)
        except Exception as e:
            print(e)
Exemplo n.º 9
0
def render_graph(g, path='graph/{}.pdf'):

    # the simplest way
    arg_map = dict(
        g = g,
        output = path.format('1-1-random-simplest'),
    )
    graph_draw(**arg_map)

    # use constants
    arg_map.update(dict(
        output = path.format('1-2-random-constant'),
        output_size = (SIZE, SIZE),
        vertex_size = MA_V_SIZE,
        edge_pen_width = MA_E_PWIDTH,
    ))
    graph_draw(**arg_map)

    # use prop_to_size
    v_count_p = g.vp['count']
    e_count_p = g.ep['count']
    v_size_by_count_p = prop_to_size(v_count_p, MI_V_SIZE, MA_V_SIZE)
    e_pwidth_by_count_p = prop_to_size(e_count_p, MI_E_PWIDTH, MA_E_PWIDTH)
    arg_map.update(dict(
        output = path.format('1-3-random-size'),
        vertex_size = v_size_by_count_p,
        edge_pen_width = e_pwidth_by_count_p,
    ))
    graph_draw(**arg_map)

    # use fill_color
    debug('v_count_p.a         : {}', v_count_p.a)
    v_color_by_count_p = prop_to_size(v_count_p, 0, 1)
    debug('v_color_by_count_p.a: {}', v_color_by_count_p.a)
    arg_map.update(dict(
        output = path.format('1-4-random-color'),
        vertex_fill_color = v_color_by_count_p,
    ))
    graph_draw(**arg_map)

    # use closeness
    v_closeness_p = g.vp['closeness']
    v_color_by_closeness_p = prop_to_size(v_closeness_p, 0, 1)
    #closeness_arg_map = arg_map.copy()
    #closeness_arg_map.update(dict(
    #    output = path.format('1-5-random-closeness'),
    #    vertex_fill_color = v_color_by_closeness_p,
    #))
    arg_map.update(dict(
        output = path.format('1-5-random-closeness'),
        vertex_fill_color = v_color_by_closeness_p,
    ))
    graph_draw(**arg_map)

    # sfdp_layout
    arg_map.update(dict(
        output = path.format('2-1-sfdp'),
        pos = sfdp_layout(g),
    ))
    graph_draw(**arg_map)

    # sfdp_layout with only edge's weight
    arg_map.update(dict(
        output = path.format('2-2-sfdp-edge-weight'),
        pos = sfdp_layout(g, eweight=e_count_p),
    ))
    graph_draw(**arg_map)

    # sfdp_layout with both edge and vertex's weight
    arg_map.update(dict(
        output = path.format('2-3-sfdp-both-weight'),
        pos = sfdp_layout(g, eweight=e_count_p, vweight=v_count_p),
    ))
    graph_draw(**arg_map)

    # fruchterman_reingold_layout
    arg_map.update(dict(
        output = path.format('3-1-fr'),
        pos = fruchterman_reingold_layout(g),
    ))
    graph_draw(**arg_map)

    # fruchterman_reingold_layout with edge's weight
    arg_map.update(dict(
        output = path.format('3-2-fp-edge-weight'),
        pos = fruchterman_reingold_layout(g, weight=e_count_p),
    ))
    graph_draw(**arg_map)

    # arf_layout
    arg_map.update(dict(
        output = path.format('4-1-arf'),
        pos = arf_layout(g),
    ))
    graph_draw(**arg_map)

    # arf_layout with edge's weight
    arg_map.update(dict(
        output = path.format('4-2-arf-edge-weight'),
        pos = arf_layout(g, weight=e_count_p),
    ))
    graph_draw(**arg_map)
Exemplo n.º 10
0
def create_fuzzy_hairball(Heatmap, save_path, top=None):
    '''Creates connectivity network based on heatmap class
    If top is passed into the function, we will highlight the top nodes'''
    g = gt.Graph()
    g.add_vertex(int(len(Heatmap.heatmap)))
    file_name = "fuzzy_hairball.pdf"

    #Init vertex propertys
    vprop_label = g.new_vertex_property("string")
    vprop_vertex_color = g.new_vertex_property("string")
    #vprop_halo_color = g.new_vertex_property("string")
    #vprop_halo = g.new_vertex_property("bool")
    vprop_halo_size = g.new_vertex_property("float")
    #vprop_color = g.new_vertex_property("string")
    eprop_color = g.new_edge_property("string")

    edge_colors = []

    total_avg = np.absolute(Heatmap.heatmap).mean()
    total_std = np.absolute(Heatmap.heatmap).std()

    for i in range((len(Heatmap.heatmap))):
        vprop_label[g.vertex(i)] = str(i)
        vprop_vertex_color[g.vertex(i)] = "gray"
        #vprop_color[g.vertex(i)] = "green"
    for row_num, row_val in enumerate(Heatmap.heatmap):
        for col_num, col_val in enumerate(Heatmap.heatmap[row_num]):
            row_std = np.absolute(Heatmap.heatmap[row_num]).std()
            row_avg = np.absolute(Heatmap.heatmap[row_num]).mean()
            col_stds = np.absolute(Heatmap.heatmap).std(0)
            col_avgs = np.absolute(Heatmap.heatmap).mean(0)
            #if row_num != col_num and abs(col_val) > row_avg*3:
            if row_num != col_num and abs(col_val) > total_avg + 3 * total_std:
                g.add_edge(g.vertex(row_num), g.vertex(col_num))
                if col_val >= 0:
                    edge_colors.append("blue")
                else:
                    edge_colors.append("red")
    counter = 0
    for e in g.edges():
        eprop_color[e] = edge_colors[counter]
        counter += 1

    # If you want to delete vertices with no edges comment this out
    #del_list = []
    #for v in g.vertices():
    #    if v.in_degree() == 0 and v.out_degree() == 0:
    #        del_list.append(v)
    #for v in reversed(sorted(del_list)):
    #    g.remove_vertex(v)
    pos = gtd.arf_layout(g, a=3)

    vprops = {'text': vprop_label, 'fill_color': vprop_vertex_color}
    #'color'     :   vprop_color         }
    eprops = {'color': eprop_color, 'pen_width': 3 * (246 / 1000)}

    full_path = os.path.join(save_path, file_name)
    gtd.graph_draw(g,
                   pos=pos,
                   output_size=(800, 800),
                   eprops=eprops,
                   vprops=vprops,
                   output=full_path)

    return g
Exemplo n.º 11
0
def create_fuzzy_hairball_fixed(Heatmap, save_path, n, d, names):
    '''
    This is kinda weird because in order to find our most connected taxa, we need to make 
    our connectivity network first in order to find out whats connected to what
    so we can't highlight the top in real time, because we might want to change what we want to hightlight
    So were just going to make it twice until I make it more slick
    No one has to know though, it will be our secret.
    '''
    g = gt.Graph()
    g.add_vertex(int(len(Heatmap.heatmap)))
    file_name = "fuzzyhairball.png"
    halo_numbers = []
    #Init vertex propertys
    vprop_label = g.new_vertex_property("string")
    vprop_vertex_color = g.new_vertex_property("string")
    vprop_shape = g.new_vertex_property("string")
    vprop_halo_color = g.new_vertex_property("string")
    vprop_halo = g.new_vertex_property("bool")
    vprop_halo_size = g.new_vertex_property("float")
    #vprop_color = g.new_vertex_property("string")
    eprop_color = g.new_edge_property("string")
    #eprop_size = g.new_edge_proprty("float")
    edge_colors = []

    total_avg = np.absolute(Heatmap.heatmap).mean()
    total_std = np.absolute(Heatmap.heatmap).std()

    to_highlight = [str(i) for i in d.keys()[-n:]]

    for i in range((len(Heatmap.heatmap))):
        vprop_label[g.vertex(i)] = str(i)
        name = names[i]
        if name in to_highlight:
            vprop_vertex_color[g.vertex(i)] = "gold"
        else:
            vprop_vertex_color[g.vertex(i)] = "lightgrey"
        if int(i) in halo_numbers:
            #vprop_halo[g.vertex(i)] = True
            vprop_shape[g.vertex(i)] = "square"
        else:
            #`vprop_halo[g.vertex(i)] = False
            vprop_shape[g.vertex(i)] = "circle"
        #vprop_halo_color[g.vertex(i)] = "green"
        vprop_halo_size[g.vertex(i)] = 0.0
        vprop_halo[g.vertex(i)] = False
        #vprop_color[g.vertex(i)] = "green"
    for row_num, row_val in enumerate(Heatmap.heatmap):
        for col_num, col_val in enumerate(Heatmap.heatmap[row_num]):
            row_std = np.absolute(Heatmap.heatmap[row_num]).std()
            row_avg = np.absolute(Heatmap.heatmap[row_num]).mean()
            col_stds = np.absolute(Heatmap.heatmap).std(0)
            col_avgs = np.absolute(Heatmap.heatmap).mean(0)
            #if row_num != col_num and abs(col_val) > row_avg*3:
            if row_num != col_num and abs(col_val) > total_avg + 3 * total_std:
                g.add_edge(g.vertex(row_num), g.vertex(col_num))
                if col_val >= 0:
                    edge_colors.append("blue")
                else:
                    edge_colors.append("red")
    counter = 0
    for e in g.edges():
        eprop_color[e] = edge_colors[counter]
        counter += 1

    vprops = {
        'text': vprop_label,
        'font_size': 45,
        'size': 85,
        'fill_color': vprop_vertex_color,
        'halo': vprop_halo,
        #'halo_color':   vprop_halo_color,
        #'halo' :   vprop_halo_size,
        'pen_width': 0,
        'shape': vprop_shape
    }
    #'color'     :   vprop_color         }
    eprops = {'color': eprop_color, 'pen_width': 7.5}
    del_list = []
    for v in g.vertices():
        if v.in_degree() == 0 and v.out_degree() == 0:
            del_list.append(v)
    for v in reversed(sorted(del_list)):
        g.remove_vertex(v)
    pos = gtd.arf_layout(g, d=0.01, a=3, max_iter=0)
    #pos = gtd.sfdp_layout(g)
    full_path = os.path.join(save_path, file_name)
    try:
        gtd.graph_draw(g,
                       pos=pos,
                       bg_color=[1, 1, 1, 1],
                       output_size=(1200, 1200),
                       eprops=eprops,
                       vprops=vprops,
                       output=full_path,
                       fmt="png")
    except Exception as e:
        print e
    return g
import graph_tool as gt
import graph_tool.stats as gts
import graph_tool.util as gtu
import graph_tool.draw as gtd
import pickle

directory = '../../data/motif_preprocess/v1/'
dict_patterns = pickle.load(open(directory + 'motifs_pat.pickle',
                                 'rb'))  # motif patterns dictionary
directory_plots = '../../plots/motif_patterns/3'

# print(dict_patterns)
for g in dict_patterns:
    gr = dict_patterns[g]
    pos = gtd.arf_layout(gr)
    gtd.graph_draw(gr, pos=pos, output=directory_plots + "/" + str(g) + ".pdf")