Ejemplo n.º 1
0
    def _number_missing_edges(cls, actual_edges: igraph.EdgeSeq,
                              actual_nodes: igraph.VertexSeq,
                              previous_edges: igraph.EdgeSeq,
                              previous_nodes: igraph.VertexSeq) -> int:
        actual_new_edges = 0
        for e in actual_edges:
            source = e.source
            target = e.target

            source_name = actual_nodes[source]["name"]
            target_name = actual_nodes[target]["name"]

            source_n_prev_ts = previous_nodes.select(name=source_name)
            target_n_prev_ts = previous_nodes.select(name=target_name)

            if len(source_n_prev_ts) > 0 and len(target_n_prev_ts) > 0:
                source_id_prev_ts = source_n_prev_ts[0].index
                target_id_prev_ts = target_n_prev_ts[0].index

                prev_edge = previous_edges.select(
                    _between=((source_id_prev_ts, ), (target_id_prev_ts, )))
                if len(prev_edge) == 0:
                    actual_new_edges += 1
            else:
                actual_new_edges += 1
        return actual_new_edges
Ejemplo n.º 2
0
def setUpTree(graph: BruckerGraph, fileNameConnections: str):
    edges, _ = getConnectionsAndMachinesFromFile(fileNameConnections)
    edges = listOfListsToListOfTuples(edges)
    nodes = graph.get_nodes()

    nr_vertices = len(nodes)
    v_label = list(map(str, range(nr_vertices)))
    G = Graph.Tree(nr_vertices, 2)  # 2 stands for children number
    lay = G.layout('rt')

    position = {k: lay[k] for k in range(nr_vertices)}
    Y = [lay[k][1] for k in range(nr_vertices)]
    M = max(Y)

    es = EdgeSeq(G)  # sequence of edges
    E = [e.tuple for e in G.es]  # list of edges

    L = len(position)
    Xn = [position[k][0] for k in range(L)]
    Yn = [2 * M - position[k][1] for k in range(L)]
    Xe = []
    Ye = []
    for edge in E:
        Xe += [position[edge[0]][0], position[edge[1]][0], None]
        Ye += [2 * M - position[edge[0]][1], 2 * M - position[edge[1]][1], None]
    labels = v_label

    fig = go.Figure()
    fig.add_trace(go.Scatter(x=Xe,
                       y=Ye,
                       mode='lines',
                       line=dict(color='rgb(210,210,210)', width=1),
                       hoverinfo='none'
                       ))
    fig.add_trace(go.Scatter(x=Xn,
                      y=Yn,
                      mode='markers',
                      name='bla',
                      marker=dict(symbol='circle-dot',
                                    size=18,
                                    color='#6175c1',    #'#DB4551',
                                    line=dict(color='rgb(50,50,50)', width=1)
                                    ),
                      text=labels,
                      hoverinfo='text',
                      opacity=0.8
                      ))
    return fig
    def set_tree(self):
        G = Graph.Tree(self.nodes_quantity, 2) # 2 stands for children number
        lay = G.layout('rt',  root=(0,0))

        self.position = {k: lay[k] for k in range(self.nodes_quantity)}
        self.Y = [lay[k][1] for k in range(self.nodes_quantity)]
        self.M = max(self.Y)

        es = EdgeSeq(G) # sequence of edges
        E = [e.tuple for e in G.es] # list of edges

        L = len(self.position)
        self.Xn = [self.position[k][0] for k in range(L)]
        self.Yn = [2*self.M-self.position[k][1] for k in range(L)]
        self.Xe = []
        self.Ye = []
        for edge in E:
            self.Xe+=[self.position[edge[0]][0],self.position[edge[1]][0], None]
            self.Ye+=[2*self.M-self.position[edge[0]][1],2*self.M-self.position[edge[1]][1], None]
Ejemplo n.º 4
0
matrix = np.load(args.load_matrix_file)
nr_vertices = len(matrix[0])
v_label = list(map(str, range(nr_vertices)))
g = Graph()
g.add_vertices(nr_vertices)
nozero = matrix.nonzero()
Edges = [(idx, idy) for idx, idy in zip(nozero[0], nozero[1])]
g.add_edges(Edges)
lay = g.layout(args.graph_layout)


position = {k: lay[k] for k in range(nr_vertices)}
Y = [lay[k][1] for k in range(nr_vertices)]
M = max(Y)

es = EdgeSeq(g) # sequence of edges
E = [e.tuple for e in g.es] # list of edges

matrix = np.zeros((nr_vertices, nr_vertices))

L = len(position)
Xn = [position[k][0] for k in range(L)]
Yn = [2*M-position[k][1] for k in range(L)]
Xe = []
Ye = []
for edge in E:
    Xe+=[position[edge[0]][0],position[edge[1]][0], None]
    Ye+=[2*M-position[edge[0]][1],2*M-position[edge[1]][1], None]

    matrix[edge[0], edge[1]] = 1
    matrix[edge[1], edge[0]] = 1
Ejemplo n.º 5
0
# Temos um erro de criação na linha abaixo.
G = Graph.Tree(
    nr_vertices, 3
)  # Número de filhos de um vértice. Podemos colocar um número máximo e não usar.
lay = G.layout_reingold_tilford(mode="in", root=[0])

position = {k: lay[k] for k in range(nr_vertices)}
Y = [lay[k][1] for k in range(nr_vertices)]
M = max(Y)

# Apagando as arestas criadas por padrão.
E = [e.tuple for e in G.es]  # Criando uma lista com as arestas
G.delete_edges(E)  # Apagando as arestas
G.add_edges([(1, 0), (2, 0), (3, 0), (4, 1), (5, 1),
             (6, 2)])  # Sequência de vértices.
es = EdgeSeq(G)  # Sequence of edges
E = [e.tuple for e in G.es]  # List of edges

L = len(position)
Xn = [position[k][0] for k in range(L)]
Yn = [2 * M - position[k][1] for k in range(L)]
Xe = []
Ye = []
for edge in E:
    Xe += [position[edge[0]][0], position[edge[1]][0], None]
    Ye += [2 * M - position[edge[0]][1], 2 * M - position[edge[1]][1], None]

labels = ['com', 'cefetmg', 'ufmg', 'pucmg', 'decom', 'df', 'icex']

# Código para plotar a árvore
fig = go.Figure()
Ejemplo n.º 6
0
    def Update_graph(select_graph):

        if select_graph == 'Shannon-Fano Algorithm':
            nr_vertices, value, v_labels = main()
            labels = v_labels

            def get_seq():
                text = open('Text.txt', 'r')

                contents = text.read()
                return contents

            dict_shannon = {}
            message = get_seq()
            code = 0
            count = {}
            code_mes = ""
            for c in message:
                if c not in count:
                    count[c] = 1
                else:
                    count[c] += 1

            def Entropy_value(frequency, length):
                entropy = 0
                for i in frequency:
                    entropy -= (frequency[i] / length *
                                math.log2(frequency[i] / length))
                return entropy

            def Shannon_Fano(seq, temp):
                f = {}
                k = {}
                if len(seq) == 1:
                    dict_shannon[seq.popitem()[0]] = temp
                    return 0
                for i in sorted(seq.items(),
                                key=operator.itemgetter(1),
                                reverse=True):
                    if sum(f.values()) < sum(k.values()):
                        f[i[0]] = seq[i[0]]
                    else:
                        k[i[0]] = seq[i[0]]
                Shannon_Fano(f, temp + '0')
                Shannon_Fano(k, temp + '1')

            Shannon_Fano(count, "")
            for i in message:
                code_mes += dict_shannon[i]
            value = code_mes

            G = Graph.Tree(nr_vertices, 3)
            lay = G.layout('kk')
            position = {k: lay[k] for k in range(nr_vertices)}
            Y = [lay[k][1] for k in range(nr_vertices)]
            M = max(Y)

            es = EdgeSeq(G)  # sequence of edges
            E = [e.tuple for e in G.es]  # list of edges

            L = len(position)
            Xn = [position[k][0] for k in range(L)]
            Yn = [2 * M - position[k][1] for k in range(L)]
            Xe = []
            Ye = []
            for edge in E:
                Xe += [position[edge[0]][0], position[edge[1]][0], None]
                Ye += [
                    2 * M - position[edge[0]][1], 2 * M - position[edge[1]][1],
                    None
                ]
            layout = go.Layout(title={
                'text': "Shannon-Fano Algorithm",
                'y': 0.9,
                'x': 0.5,
                'xanchor': 'center',
                'yanchor': 'top',
                'font': title_font
            },
                               paper_bgcolor='rgba(0,0,0,0)',
                               plot_bgcolor='rgba(0,0,0,0)',
                               font=general_font)
            fig = go.Figure(layout=layout)
            fig.add_trace(
                go.Scatter(x=Xe,
                           y=Ye,
                           mode='lines',
                           line=dict(color='#f28b1d', width=2),
                           hoverinfo='none'))
            fig.add_trace(
                go.Scatter(x=Xn,
                           y=Yn,
                           mode='markers',
                           name='bla',
                           marker=dict(symbol='circle-dot',
                                       size=22,
                                       color='#e61c1c',
                                       line=dict(color='#f28b1d', width=2)),
                           text=labels,
                           hoverinfo='text',
                           opacity=1))
            return fig, 'Shannon-Fano encoding: {}'.format(value)
        else:
            nr_vertices, value, v_labels = main()
            labels = v_labels
            G = Graph.Tree(nr_vertices, 2)
            lay = G.layout('rt')
            position = {k: lay[k] for k in range(nr_vertices)}
            Y = [lay[k][1] for k in range(nr_vertices)]
            M = max(Y)

            es = EdgeSeq(G)  # sequence of edges
            E = [e.tuple for e in G.es]  # list of edges

            L = len(position)
            Xn = [position[k][0] for k in range(L)]
            Yn = [2 * M - position[k][1] for k in range(L)]
            Xe = []
            Ye = []
            for edge in E:
                Xe += [position[edge[0]][0], position[edge[1]][0], None]
                Ye += [
                    2 * M - position[edge[0]][1], 2 * M - position[edge[1]][1],
                    None
                ]
            layout = go.Layout(title={
                'text': "Huffman Algorithm",
                'y': 0.9,
                'x': 0.5,
                'xanchor': 'center',
                'yanchor': 'top',
                'font': title_font
            },
                               paper_bgcolor='rgba(0,0,0,0)',
                               plot_bgcolor='rgba(0,0,0,0)',
                               font=general_font)
            fig = go.Figure(layout=layout)
            fig.add_trace(
                go.Scatter(x=Xe,
                           y=Ye,
                           mode='lines',
                           line=dict(color='#f28b1d', width=2),
                           hoverinfo='none'))
            fig.add_trace(
                go.Scatter(x=Xn,
                           y=Yn,
                           mode='markers',
                           name='bla',
                           marker=dict(symbol='circle-dot',
                                       size=22,
                                       color='#e61c1c',
                                       line=dict(color='#f28b1d', width=2)),
                           text=labels,
                           hoverinfo='text',
                           opacity=1))
            return fig, 'Huffman encoding: {}'.format(value)
Ejemplo n.º 7
0
def plotTree(vertices, edge_list, num_vertices):

    labels = [vertices[k].name for k in range(num_vertices)]
    G = Graph()
    G.add_vertices(num_vertices)
    G.add_edges(edge_list)
    lay = G.layout('rt', 2)

    position = {k: lay[k] for k in range(num_vertices)}
    Y = [lay[k][1] for k in range(num_vertices)]
    M = max(Y)

    es = EdgeSeq(G) # sequence of edges
    E = [e.tuple for e in G.es] # list of edges

    L = len(position.items())
    Xn = [position[k][0] for k in range(L)]
    Yn = [2*M-position[k][1] for k in range(L)]
    Xe = []
    Ye = []
    for edge in E:
        Xe+=[position[edge[0]][0],position[edge[1]][0], None]
        Ye+=[2*M-position[edge[0]][1],2*M-position[edge[1]][1], None]

    #Create Plotly Traces

    lines = go.Scatter(x=Xe,
                       y=Ye,
                       mode='lines',
                       line=dict(color='rgb(210,210,210)', width=1),
                       hoverinfo='none'
                       )
    dots = go.Scatter(x=Xn,
                      y=Yn,
                      mode='markers',
                      name='',
                      marker=dict(symbol='dot',
                                    size=18,
                                    color='#6175c1',    #'#DB4551',
                                    line=dict(color='rgb(50,50,50)', width=1)
                                    ),
                      text=labels,
                      hoverinfo='text',
                      opacity=0.8
                      )

    # Create Text Inside the Circle via Annotations

    def make_annotations(pos, text, font_size=10,
                         font_color='rgb(250,250,250)'):
        L=len(pos)
        if len(list(text))!=L:
            raise ValueError('The lists pos and text must have the same len')
        annotations = go.Annotations()
        for k in range(L):
            annotations.append(
                go.Annotation(
                    text=labels[k], # or replace labels with a different list
                                    # for the text within the circle
                    x=pos[k][0], y=2*M-position[k][1],
                    xref='x1', yref='y1',
                    font=dict(color=font_color, size=font_size),
                    showarrow=False)
            )
        return annotations

    # Add Axis Specifications and Create the Layout

    axis = dict(showline=False, # hide axis line, grid, ticklabels and  title
                zeroline=False,
                showgrid=False,
                showticklabels=False,
                )

    layout = dict(title= 'Tree with Reingold-Tilford Layout',
                  font=dict(size=12),
                  showlegend=False,
                  xaxis=go.XAxis(axis),
                  yaxis=go.YAxis(axis),
                  margin=dict(l=40, r=40, b=85, t=100),
                  hovermode='closest',
                  plot_bgcolor='rgb(248,248,248)'
                  )

    # Plot

    data=go.Data([lines, dots])
    fig=dict(data=data, layout=layout)
    fig['layout'].update(annotations=make_annotations(position, labels))
    py.plot(fig, filename='Tree-Reingold-Tilf')
Ejemplo n.º 8
0
def constructGraph(person1List, person2List, person1, person2, commonAncestor):
    # print(person1List)
    # print(person2List)
    # print(person1, person2, commonAncestor)
    person2rever = person2List[::-1] #reversed personList2
    tempPerson1List = person1List[:-1] #personlist1 with the common ancestor element removed
    totalLen = len(person1List)+len(person2List)-1 #
    v_label = tempPerson1List+person2rever # vertex labels from bot modified concatanated person lists
    G = Graph.Tree(totalLen, 1) # 1 stands for children number

    lay = G.layout_reingold_tilford(mode="in", root=[len(person1List) - 1]) #Layout of graph with the root node as  the common ancestor

    position = {k: lay[k] for k in range(totalLen)} #position of visualizations 
    Y = [lay[k][1] for k in range(totalLen)]
    M = max(Y)

    empty = [""] #empty list to not display any labels in igraph nodes
    es = EdgeSeq(G) # sequence of edges
    E = [e.tuple for e in G.es] # list of edges

    L = len(position)
    Xn = [position[k][0] for k in range(L)]
    Yn = [2*M-position[k][1] for k in range(L)]
    Xe = []
    Ye = []
    for edge in E: #Creates edges within graph
        Xe+=[position[edge[0]][0],position[edge[1]][0], None]
        Ye+=[2*M-position[edge[0]][1],2*M-position[edge[1]][1], None]

    labels = v_label
    #def createVis():
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=Xe,
                        y=Ye,
                        mode='lines',
                        line=dict(color='rgb(200,200,200)', width=1),
                        hoverinfo='none'
                        ))
    fig.add_trace(go.Scatter(x=Xn,
                        y=Yn,
                        mode='markers',
                        name='bla',
                        marker=dict(symbol='circle-dot',
                                    size=20,
                                    color='#6175c1',    #'#DB4551',
                                    line=dict(color='rgb(100,100,100)', width=1)
                                    ),
                        text=labels,
                        hoverinfo='text',
                        opacity=0.8
                        ))

    def make_annotations(pos, text, font_size=10, font_color='rgb(0,0,0)'):
        L=len(pos)
        if len(text)!=L:
            raise ValueError('The lists pos and text must have the same len')
        annotations = []
        for k in range(L):
            annotations.append(
                dict(
                text=labels[k], 
                    x=pos[k][0], y=2*M-position[k][1],
                    xref='x1', yref='y1',
                    font=dict(color=font_color, size=font_size),
                    showarrow=False)
            )
        return annotations


    axis = dict(showline=False, # hides axis line, grid, ticklabels and title
                zeroline=False,
                showgrid=False,
                showticklabels=False,
                )
    fig.update_layout(title= commonAncestor+' is the closest ancestor between '+person1+' and '+person2 ,
                    annotations=make_annotations(position, v_label),
                    font_size=12,
                    showlegend=False,
                    xaxis=axis,
                    yaxis=axis,
                    margin=dict(l=40, r=40, b=85, t=100),
                    hovermode='closest',
                    plot_bgcolor='rgb(248,248,248)'
                    )
    fig.show()

# constructGraph(person1List, person2List, person1, person2, commonAncestor)
# print("testing string")
Ejemplo n.º 9
0
def img_generator():
    n_vertices = 3
    while True:
        print('called')
        if n_vertices > 100:
            n_vertices = 3
        n_children_per_node = 2
        vertex_labels = [str(x) for x in range(n_vertices)]

        G = Graph.Tree(n_vertices, n_children_per_node)

        # Defines a layout algorithm
        layout = G.layout('rt')

        position = {k: layout[k] for k in range(n_vertices)}
        Y = [layout[k][1] for k in range(n_vertices)]
        M = max(Y)

        es = EdgeSeq(G)  # sequence of edges
        E = [e.tuple for e in G.es]  # list of edges

        L = len(position)
        Xn = [position[k][0] for k in range(L)]
        Yn = [2 * M - position[k][1] for k in range(L)]
        Xe = []
        Ye = []
        for edge in E:
            Xe += [position[edge[0]][0], position[edge[1]][0], None]
            Ye += [
                2 * M - position[edge[0]][1], 2 * M - position[edge[1]][1],
                None
            ]

        labels = vertex_labels

        print('called2')
        fig = go.Figure()

        print('called3')
        # Plot Vertices
        fig.add_trace(
            go.Scatter(x=Xn,
                       y=Yn,
                       mode='markers',
                       name='bla',
                       marker=dict(symbol='circle-dot',
                                   size=18,
                                   color='#DB4551',
                                   line=dict(color='rgb(50,50,50)', width=1)),
                       text=labels,
                       hoverinfo='text',
                       opacity=0.8))

        # Plot Edges
        fig.add_trace(
            go.Scatter(x=Xe,
                       y=Ye,
                       mode='lines',
                       line=dict(color='rgb(210,210,210)', width=1),
                       hoverinfo='none'))

        print('called3')
        img_bytes = fig.to_image(format="png")
        print('called4')
        sleep(1 / FRAMERATE)
        yield (b'--frame\r\n'
               b'Content-Type: image/png\r\n\r\n' + img_bytes + b'\r\n')
        n_vertices += 1
Ejemplo n.º 10
0
import numpy as np
from sklearn.neighbors import NearestNeighbors, LSHForest

from igraph import Graph, EdgeSeq
from timeit import timeit
import random

random.seed(100)

#robjects.r['load']('../processed_sub_Data.RData')
print "Reading sparce matrix..."
matrix = mmread("sub_matrix")
print "Converting matrix to dense format..."
a = np.array(matrix.todense())
print a.shape
print "Initialize LSH..."
lshf = LSHForest(n_neighbors=10, random_state=1, n_estimators=10)
print "fit LSH..."
lshf.fit(a)

K = lshf.kneighbors_graph(a)

print "convert into adjacency matrix..."
K = K.toarray()

g = Graph.Adjacency(K.tolist())
es = EdgeSeq(g)

print "writing graph edgelist..."
g.write_edgelist("src_dst_lsh.csv")