Beispiel #1
0
def render_graph(bb_graph, filename):
    """
    Renders a basic block graph to file

    :param bb_graph: The Graph to render
    :type bb_graph: networkx.DiGraph
    """
    graph = pydotplus.Dot(graph_type='digraph', rankdir='TB')
    entryblock = nx.get_node_attributes(bb_graph, 'isEntry').keys()[0]
    returnblocks = nx.get_node_attributes(bb_graph, 'isTerminal').keys()

    nodedict = {}

    for bb in bb_graph.nodes.iterkeys():
        node = render_bb(bb, bb == entryblock, bb in returnblocks)
        if bb == entryblock:
            sub = pydotplus.Subgraph('sub', rank='source')
            sub.add_node(node)
            graph.add_subgraph(sub)
        else:
            graph.add_node(node)
        nodedict[bb] = node

    for edge in bb_graph.edges.iteritems():
        edge = (edge[0][0], edge[0][1], edge[1])
        src = nodedict[edge[0]]
        dest = nodedict[edge[1]]
        e_style = 'dashed' if edge[2]['edge_type'] == 'implicit' else 'solid'

        graph.add_edge(pydotplus.Edge(src, dest, style=e_style))
    # graph.set('splines', 'ortho')
    # graph.set_prog('neato')
    # graph.set('dpi', '100')

    graph.write(filename, format='svg')
Beispiel #2
0
def to_pydot(viz_dag, graph_attr=None, node_attr=None, edge_attr=None):
    node_groups = {}
    for name, data in viz_dag.nodes(data=True):
        group = data.get('_group')
        node_groups.setdefault(group, []).append(name)

    edge_groups = {}
    for name1, name2, data in viz_dag.edges(data=True):
        group = data.get('_group')
        edge_groups.setdefault(group, []).append((name1, name2))

    viz_dot = pydotplus.Dot()

    if graph_attr is not None:
        for k, v in six.iteritems(graph_attr):
            viz_dot.set(k, v)

    if node_attr is not None:
        viz_dot.set_node_defaults(**node_attr)

    if edge_attr is not None:
        viz_dot.set_edge_defaults(**edge_attr)

    for group, names in six.iteritems(node_groups):
        if group is None:
            continue
        c = pydotplus.Subgraph('cluster_' + str(group))

        for name in names:
            node = pydotplus.Node(name)
            for k, v in six.iteritems(viz_dag.node[name]):
                if not k.startswith("_"):
                    node.set(k, v)
            c.add_node(node)

        for name1, name2 in edge_groups.get(group, []):
            edge = pydotplus.Edge(name1, name2)
            c.add_edge(edge)

        c.obj_dict['label'] = str(group)
        viz_dot.add_subgraph(c)

    for name in node_groups.get(None, []):
        node = pydotplus.Node(name)
        for k, v in six.iteritems(viz_dag.nodes[name]):
            if not k.startswith("_"):
                node.set(k, v)
        viz_dot.add_node(node)

    for name1, name2 in edge_groups.get(None, []):
        edge = pydotplus.Edge(name1, name2)
        viz_dot.add_edge(edge)

    return viz_dot
Beispiel #3
0
    def test_subgraphs(self):

        g = pydotplus.Graph()
        s = pydotplus.Subgraph("foo")

        self.assertEqual(g.get_subgraphs(), [])
        self.assertEqual(g.get_subgraph_list(), [])

        g.add_subgraph(s)

        self.assertEqual(g.get_subgraphs()[0].get_name(), s.get_name())
        self.assertEqual(g.get_subgraph_list()[0].get_name(), s.get_name())
Beispiel #4
0
    def test_graph_pickling(self):

        import pickle

        g = pydotplus.Graph()
        s = pydotplus.Subgraph("foo")
        g.add_subgraph(s)
        g.add_edge(pydotplus.Edge('A', 'B'))
        g.add_edge(pydotplus.Edge('A', 'C'))
        g.add_edge(pydotplus.Edge(('D', 'E')))
        g.add_node(pydotplus.Node('node!'))

        self.assertEqual(type(pickle.dumps(g)), bytes)
def get_accounts_cluster(entity):
    """
    get a sub-graph representing the entity and its accounts.
    :param entity: central entity of the subgraph
    :return: subgraph
    """
    accounts = entity[-1].get("accounts")
    account_labels = accountsModule.get_account_labels(accounts)
    account_tooltips = accountsModule.get_account_tooltip(accounts)
    entity_id = entity[0]
    account_cluster = pydotplus.Subgraph(name='cluster_' + entity_id)
    for account in accounts.nodes(data=True):
        set_account_to_entity_edge(account_cluster, entity_id, account,
                                   account_labels, account_tooltips)
    return account_cluster
Beispiel #6
0
def push_subgraph_stmt(str, loc, toks):
    g = pydotplus.Subgraph('')

    for e in toks:
        if len(e) == 3:
            e[2].set_name(e[1])
            if e[0] == 'subgraph':
                e[2].obj_dict['show_keyword'] = True
            return e[2]
        else:
            if e[0] == 'subgraph':
                e[1].obj_dict['show_keyword'] = True
            return e[1]

    return g
Beispiel #7
0
def tree_to_graph(t, G=None):
    G = G or pdp.Dot()
    ids = []
    token_ids = []
    _tree_to_graph(t, G, ids, token_ids, parent=None)

    # Make token subgraph to constrain layout
    sg = pdp.Subgraph("tokens", rank="same")
    for token_id in token_ids:
        for node in G.get_node(str(token_id)):
            sg.add_node(node)
    G.add_subgraph(sg)
    # Add token-token edges to preserve sequence
    # Token ids should be sequential, due to left-right traversal.
    for i in range(1, len(token_ids)):
        G.add_edge(pdp.Edge(token_ids[i-1], token_ids[i],
                            arrowsize=0, penwidth=1, color="#CCCCCC"))

    return G
Beispiel #8
0
def draw_tree():
    from PIL import ImageTk, Image as Image_PIL
    
    class ResizingCanvas(Canvas):
        def __init__(self,parent,**kwargs):
            Canvas.__init__(self,parent,**kwargs)
            self.bind("<Configure>", self.on_resize)
            self.height = self.winfo_reqheight()
            self.width = self.winfo_reqwidth()
            # self.bind_all("<MouseWheel>", self.on_mousewheel)
    
        def on_resize(self,event):     
            new_width = self.master.winfo_width()
            new_height = self.master.winfo_height()
    
        #colors
    col_f='#ff4e5c'
    col_m='#1c3144'
    col_w='#9d7a7d'
    #
                   
    top = tk.Tk()
    top.iconbitmap(f'{main_f}2683232.ico')
    Grid.rowconfigure(top, 0, weight=1)
    Grid.columnconfigure(top, 0, weight=1)
    top.geometry("900x480")
    top.wm_title("Tree")
    
    frame = tk.Frame(top)
    frame.grid(row=0, column=0, sticky=N+S+E+W)
    
    #scrollbars
    xscrollbar = tk.Scrollbar(frame, orient=tk.HORIZONTAL)
    xscrollbar.grid(row=1, column=0, sticky="EW")
    yscrollbar = tk.Scrollbar(frame)
    yscrollbar.grid(row=0, column=1, sticky="NS")
    
    
    canvas = ResizingCanvas(frame,  xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set)
    canvas.grid(row=0, column=0, sticky="EWNS")
    canvas.configure(bg='white')
    
    # Image
        
    import pydotplus as pdt
    import time

    df=pddf(backend_app.view(), columns=c_header)
    
    for c in ['id',   
            'mother_id',
            'father_id',
            'spouse_id',                                   
            'generation',
            'cluster', 
            'gender'       ]:
        df[c]=to_numeric(df[c], downcast='integer',errors='coerce')
    
    min_level=int(df['generation'].min())
    max_level=int(df['generation'].max())
    
    g = pdt.Dot(graph_type='digraph', compound='true', rankdir='TB',newrank = 'true')
    
    i=0
    edges = []
    nodes=[]
    # create all edges
    
    from ast import literal_eval as make_tuple
    nl=max_level-min_level+1
    s=[None]*(max_level+1)
    
    
    for i in range(min_level,max_level+1):
        s = pdt.Subgraph(i,rank='same')
        for j in df.loc[df['generation']==i, 'id'].values :
            s.add_node(pdt.Node(f"{df.loc[df['id']==j, 'id'].values[0]}"))
        g.add_subgraph(s)
       
    
    min_cl=int(df['cluster'].min())
    max_cl=int(df['cluster'].max())
    nl=max_cl-min_cl+1
    ss=[None]*(max_cl+1)
    for i in range(min_cl,max_cl+1):
        ss = pdt.Cluster(f'c1_{i}', color="white",rankdir="TB")
        for j in df.loc[df['cluster']==i, 'id'].values :
            ss.add_node(pdt.Node(f"{df.loc[df['id']==j, 'id'].values[0]}"))
        g.add_subgraph(ss)
      
     
        
    for i in range(df.shape[0]):
        m=df.loc[i, 'mother_id']
        f=df.loc[i, 'father_id']
        nod=pdt.Node(f"{df.loc[i, 'id']}",  shape='record', color=col_m, style='rounded')
        if m in df['id'].values:        g.add_edge(pdt.Edge(pdt.Node(f"{df.loc[df['id']==m, 'id'].values[0]}"), nod, color=col_f))
        if f in df['id'].values:        g.add_edge(pdt.Edge(pdt.Node(f"{df.loc[df['id']==f, 'id'].values[0]}"), nod, color=col_m))
    
    
        if notnull(df.loc[i, 'spouse_id']):
            who=to_numeric(df.loc[i, 'spouse_id'], downcast='integer', errors='coerce')
            if who in df['id'].values:
                g.add_edge(pdt.Edge(pdt.Node(f"{df.loc[df['id']==who, 'id'].values[0]}"), nod,  dir='none',color=col_w)) #label='m',
    
    
    
    for i in  range(df.shape[0]):
        cc=col_f
        if df.loc[i, 'gender']==1: cc=col_m
        sstr=f"{df.loc[i, 'name']}"
        if notnull(df.loc[i, 'surname']): sstr=f"{sstr} {df.loc[i, 'surname']}"
        if notnull(df.loc[i, 'date_birth']): 
            if isinstance(df.loc[i, 'date_birth'], int) or isinstance(df.loc[i, 'date_birth'], str): 
                sstr=f"{sstr}\nB: {df.loc[i, 'date_birth']}"
            else: 
                sstr=f"{sstr}\nB: {df.loc[i, 'date_birth'].strftime('%d %b %Y') }" # %H:%M:%S
        
        d=df.loc[i, 'date_death']
        # import numpy as np
        if notnull(d): 
            # print("ddd" , isna(d), isnull(d), d, type(d) )
            sstr=f"{sstr}\nD: {d}"
        
        if notnull(df.loc[i, 'place_birth']): 
            sstr=f"{sstr}\nPoB: {df.loc[i, 'place_birth']} ({df.loc[i, 'country_birth']})"
        
        if not (isnull(df.loc[i, 'comments']) or df.loc[i, 'comments']==''): 
            sstr=f"{sstr}\nComments: {df.loc[i, 'comments']}"
                
        nod=pdt.Node(f"{df.loc[i, 'id']}", label=sstr, shape='box', color=cc, style='rounded')
    
        g.add_node(nod)
    
    
    import io
    buf = io.BytesIO()
    g.write_png(buf)
    # plt.savefig(buf, format='png')
    buf.seek(0)
    img_g = Image_PIL.open(buf)
    img = ImageTk.PhotoImage(img_g, master=frame)
    canvas.create_image(0, 0, image=img)
    
    #scrollconfig
    canvas.config(scrollregion=canvas.bbox(tk.ALL))
    
    xscrollbar.config(command=canvas.xview)
    yscrollbar.config(command=canvas.yview)
    
    
    
    frame.grid(row=0, column=0)
    frame.grid_rowconfigure(0, weight=1)
    frame.grid_columnconfigure(0, weight=1)
    
    #menu
    menubar = Menu(top)
    top.config(menu=menubar)
    menu = Menu(menubar)
    
    def file_save():

        from tkinter.filedialog import asksaveasfilename
        f =  asksaveasfilename(title = "Select file",filetypes = (("png files","*.png"),("all files","*.*")), defaultextension='.png')
        if f is None: # asksaveasfile return `None` if dialog closed with "cancel".
            return
        img_g.save(f)


    menu.add_command(label='Save',command=file_save)
    
    menu.add_command(label='Close',command=top.destroy)
    # menu.add_command(label="Exit", command=window.quit)
    menubar.add_cascade(label="File", menu=menu)

    top.mainloop()
def getGraph(protagonista, partable, tipus):
    graph = pdp.Dot(graph_type='graph')
    Avis = pdp.Subgraph()
    Pares = pdp.Subgraph()
    Gen = pdp.Subgraph()
    graph.add_subgraph(Avis)
    graph.add_subgraph(Pares)
    graph.add_subgraph(Gen)
    if tipus == 'Baptisme':
        nomProta = ''
        cercafillprota = True
        cercagermansprota = True
        cercatietsP = True
        cercatietsM = True
        if protagonista[0]['Nom'] is not None:
            nomProta += protagonista[0]['Nom'].strip() + " "
        else:
            nomProta += "- "
            cercafillprota = False
        if protagonista[0]['Cognom1'] is not None:
            nomProta += protagonista[0]['Cognom1'].strip()
        else:
            nomProta += "-"
            cercafillprota = False
        nodeProta = pdp.Node("Prota",
                             label=nomProta,
                             style="filled",
                             fillcolor="#55ffff")
        nodePare = pdp.Node("Pare", label='-')
        nodeMare = pdp.Node("Mare", label='-')
        nodeMatrimoniPares = pdp.Node("MP",
                                      label="",
                                      shape='diamond',
                                      style='filled',
                                      height=.1,
                                      width=.1)
        nodeAviP = pdp.Node("AviP", label='-')
        nodeAviaP = pdp.Node("AviaP", label='-')
        nodeMatrimoniAvisP = pdp.Node("MAP",
                                      label="",
                                      shape='diamond',
                                      style='filled',
                                      height=.1,
                                      width=.1)
        nodeAviM = pdp.Node("AviM", label='-')
        nodeAviaM = pdp.Node("AviaM", label='-')
        nodeMatrimoniAvisM = pdp.Node("MAM",
                                      label="",
                                      shape='diamond',
                                      style='filled',
                                      height=.1,
                                      width=.1)
        Pare = [None, None]
        Mare = [None, None]
        AviP = [None, None]
        AviaP = [None, None]
        AviM = [None, None]
        AviaM = [None, None]

        for p in partable:
            nom = ''
            if p['Nom'] is not None: nom += p['Nom'].strip() + " "
            else: nom += "- "
            if p['Cognom1'] is not None: nom += p['Cognom1'].strip()
            else: nom += "-"
            if p['Tip_part'] == 'Pare':
                nodePare = pdp.Node("Pare", label=nom)
                Pare = [p['Nom'], p['Cognom1']]
            if p['Tip_part'] == 'Mare':
                nodeMare = pdp.Node("Mare", label=nom)
                Mare = [p['Nom'], p['Cognom1']]
            if p['Tip_part'] == 'Avi Patern':
                nodeAviP = pdp.Node("AviP", label=nom)
                AviP = [p['Nom'], p['Cognom1']]
            if p['Tip_part'] == 'Avia Paterna':
                nodeAviaP = pdp.Node("AviaP", label=nom)
                AviaP = [p['Nom'], p['Cognom1']]
            if p['Tip_part'] == 'Avi Matern':
                nodeAviM = pdp.Node("AviM", label=nom)
                AviM = [p['Nom'], p['Cognom1']]
            if p['Tip_part'] == 'Avia Materna':
                nodeAviaM = pdp.Node("AviaM", label=nom)
                AviaM = [p['Nom'], p['Cognom1']]

        Avis.add_node(nodeAviP)
        Avis.add_node(nodeMatrimoniAvisP)
        Avis.add_node(nodeAviaP)
        Avis.add_node(nodeAviM)
        Avis.add_node(nodeMatrimoniAvisM)
        Avis.add_node(nodeAviaM)
        Avis.add_edge(pdp.Edge(nodeAviP, nodeMatrimoniAvisP))
        Avis.add_edge(pdp.Edge(nodeAviaP, nodeMatrimoniAvisP))
        Avis.add_edge(pdp.Edge(nodeAviM, nodeMatrimoniAvisM))
        Avis.add_edge(pdp.Edge(nodeAviaM, nodeMatrimoniAvisM))

        data = protagonista[0]['Data']
        if data is None or not Assistant.checkData(data):
            data = protagonista[0]['Data_Naix']
            if data is None or not Assistant.checkData(data):
                cercafillprota = False
                cercagermansprota = False
                cercatietsP = False
                cercatietsM = False

        #busquem tiets Paternts del protagonista
        if None in AviP or None in AviaP: cercatietsP = False
        if cercatietsP:
            cerca = {
                'nomMarit': AviP[0],
                'cognomMarit': AviP[1],
                'data': data[0:4],
                'nomMuller': AviaP[0],
                'cognomMuller': AviaP[1],
                'tipus': 'TietsBatejat'
            }
            TietsP = cercaFills(cerca)
            listoftietsP = []
            for t in TietsP:
                if t['nom'] not in listoftietsP and not (
                        Pare[0] is not None and t['nom'] == Pare[0].strip()):
                    listoftietsP.append(t['nom'])
                    nodeTietP = pdp.Node("tietP " + t['nom'],
                                         label=t['nom'] + " " + t['cognom'])
                    Pares.add_node(nodeTietP)
                    graph.add_edge(pdp.Edge(nodeMatrimoniAvisP, nodeTietP))

        Pares.add_node(nodePare)
        Pares.add_node(nodeMatrimoniPares)
        Pares.add_node(nodeMare)
        Pares.add_edge(pdp.Edge(nodePare, nodeMatrimoniPares))
        Pares.add_edge(pdp.Edge(nodeMare, nodeMatrimoniPares))

        #busquem tiets Materns del protagonista
        if None in AviM or None in AviaM: cercatietsM = False
        if cercatietsM:
            cerca = {
                'nomMarit': AviM[0],
                'cognomMarit': AviM[1],
                'data': data[0:4],
                'nomMuller': AviaM[0],
                'cognomMuller': AviaM[1],
                'tipus': 'TietsBatejat'
            }
            TietsM = cercaFills(cerca)
            listoftietsM = []
            for t in TietsM:
                if t['nom'] not in listoftietsM and not (
                        Mare[0] is not None and t['nom'] == Mare[0].strip()):
                    listoftietsM.append(t['nom'])
                    nodeTietM = pdp.Node("tietM " + t['nom'],
                                         label=t['nom'] + " " + t['cognom'])
                    Pares.add_node(nodeTietM)
                    graph.add_edge(pdp.Edge(nodeMatrimoniAvisM, nodeTietM))

        graph.add_edge(pdp.Edge(nodeMatrimoniAvisM, nodeMare))
        graph.add_edge(pdp.Edge(nodeMatrimoniAvisP, nodePare))
        graph.add_edge(pdp.Edge(nodeMatrimoniPares, nodeProta))

        # busquem germans del protagonista
        if None in Pare or None in Mare: cercagermansprota = False
        if cercagermansprota:
            cerca = {
                'nomMarit': Pare[0],
                'cognomMarit': Pare[1],
                'data': data[0:4],
                'nomMuller': Mare[0],
                'cognomMuller': Mare[1],
                'tipus': 'GermansBatejat'
            }
            GermansProta = cercaFills(cerca)
            listofgermans = []
            for g in GermansProta:
                if not (protagonista[0]['Nom'] is not None
                        and protagonista[0]['Nom'].strip()
                        == g['nom']) and g['nom'] not in listofgermans:
                    listofgermans.append(g['nom'])
                    nodeGerma = pdp.Node("germa " + g['nom'] + g['cognom'],
                                         label=g['nom'] + " " + g['cognom'])
                    Gen.add_node(nodeGerma)
                    graph.add_edge(pdp.Edge(nodeMatrimoniPares, nodeGerma))

        Gen.add_node(nodeProta)
        # fem expansions buscant fills del protagonista

        if protagonista[0]['Sexe'] is None or (protagonista[0]['Sexe'] != 'M'
                                               and
                                               protagonista[0]['Sexe'] != 'F'):
            cercafillprota = False
        if cercafillprota:
            cerca = {
                'nom': protagonista[0]['Nom'],
                'cognom': protagonista[0]['Cognom1'],
                'data': data[0:4],
                'sexe': protagonista[0]['Sexe'],
                'tipus': 'Batejat'
            }
            fillsProta = cercaFills(cerca)
            ParentCreat = False
            idParents = []
            idMatrimonifills = []
            Fills = pdp.Subgraph()
            for f in fillsProta:
                nomParent = "-"
                cognomParent = "-"
                idPM = ""
                if not ParentCreat:
                    if f['nomPM'] is not None: nomParent = f['nomPM'].strip()
                    if f['cognomPM'] is not None:
                        cognomParent = f['cognomPM'].strip()
                    idPM = nomParent + " " + cognomParent
                    idParents.append([nomParent, cognomParent, idPM])
                    ParentCreat = True
                else:
                    if f['nomPM'] is not None: nomParent = f['nomPM'].strip()
                    if f['cognomPM'] is not None:
                        cognomParent = f['cognomPM'].strip()
                    idTrobat = False
                    for i in idParents:
                        if nomParent == i[0] or cognomParent == i[1]:
                            nomParent = i[0]
                            cognomParent = i[1]
                            idPM = nomParent + " " + cognomParent
                            idTrobat = True
                            break
                    if not idTrobat:
                        idPM = nomParent + " " + cognomParent
                        idParents.append([nomParent, cognomParent, idPM])
                noufill = [f['nom'].strip() + " " + f['cognom'].strip(), idPM]
                if noufill not in idMatrimonifills:
                    idMatrimonifills.append(noufill)
            for p in idParents:
                nodeParella = pdp.Node("Parella" + p[2], label=p[2])
                nodeMatrimoniParella = pdp.Node("MP" + p[2],
                                                label="",
                                                shape='diamond',
                                                style='filled',
                                                height=.1,
                                                width=.1)
                Gen.add_node(nodeParella)
                Gen.add_node(nodeMatrimoniParella)
                Gen.add_edge(pdp.Edge(nodeParella, nodeMatrimoniParella))
                Gen.add_edge(pdp.Edge(nodeProta, nodeMatrimoniParella))
                for f in idMatrimonifills:
                    if f[1] == p[2]:
                        nodeFill = pdp.Node("fill " + f[0], label=f[0])
                        Fills.add_node(nodeFill)
                        Fills.add_edge(pdp.Edge(nodeMatrimoniParella,
                                                nodeFill))
            graph.add_subgraph(Fills)

    elif tipus == 'Matrimoni':
        nomMarit = ''
        cercafills = True
        cercaCunyatsMarit = True
        cercaCunyatsMuller = True
        if protagonista[0]['Nom_Marit'] is not None:
            nomMarit += protagonista[0]['Nom_Marit'].strip() + " "
        else:
            nomMarit += "- "
            cercafills = False
        if protagonista[0]['Cognom1_Marit'] is not None:
            nomMarit += protagonista[0]['Cognom1_Marit'].strip()
        else:
            nomMarit += "-"
            cercafills = False
        nomMuller = ''
        if protagonista[0]['Nom_Muller'] is not None:
            nomMuller += protagonista[0]['Nom_Muller'].strip() + " "
        else:
            nomMuller += "- "
            cercafills = False
        if protagonista[0]['Cognom1_Muller'] is not None:
            nomMuller += protagonista[0]['Cognom1_Muller'].strip()
        else:
            nomMuller += "-"
            cercafills = False
        nodeMarit = pdp.Node("Marit",
                             label=nomMarit,
                             style="filled",
                             fillcolor="#55ffff")
        nodeMuller = pdp.Node("Muller",
                              label=nomMuller,
                              style="filled",
                              fillcolor="#55ffff")
        nodeMatrimoni = pdp.Node("P",
                                 label="",
                                 shape='diamond',
                                 style='filled',
                                 height=.1,
                                 width=.1)
        nodePareMarit = pdp.Node("PMarit", label='-')
        nodeMareMarit = pdp.Node("MMarit", label='-')
        nodeMatrimoniPMarit = pdp.Node("MPMarit",
                                       label="",
                                       shape='diamond',
                                       style='filled',
                                       height=.1,
                                       width=.1)
        nodePareMuller = pdp.Node("PMuller", label='-')
        nodeMareMuller = pdp.Node("MMuller", label='-')
        nodeMatrimoniPMuller = pdp.Node("MPMuller",
                                        label="",
                                        shape='diamond',
                                        style='filled',
                                        height=.1,
                                        width=.1)
        PareMarit = [None, None]
        MareMarit = [None, None]
        PareMuller = [None, None]
        MareMuller = [None, None]

        for p in partable:
            nom = ''
            if p['Nom'] is not None: nom += p['Nom'].strip() + " "
            else: nom += "- "
            if p['Cognom1'] is not None: nom += p['Cognom1'].strip()
            else: nom += "-"
            if p['Tip_part'] == 'Pare Marit':
                nodePareMarit = pdp.Node("PMarit", label=nom)
                PareMarit = [p['Nom'], p['Cognom1']]
            if p['Tip_part'] == 'Mare Marit':
                nodeMareMarit = pdp.Node("MMarit", label=nom)
                MareMarit = [p['Nom'], p['Cognom1']]
            if p['Tip_part'] == 'Pare Muller':
                nodePareMuller = pdp.Node("PMuller", label=nom)
                PareMuller = [p['Nom'], p['Cognom1']]
            if p['Tip_part'] == 'Mare Muller':
                nodeMareMuller = pdp.Node("MMuller", label=nom)
                MareMuller = [p['Nom'], p['Cognom1']]
        Pares.add_node(nodePareMarit)
        Pares.add_node(nodeMareMarit)
        Pares.add_node(nodePareMuller)
        Pares.add_node(nodeMareMuller)
        Pares.add_node(nodeMatrimoniPMarit)
        Pares.add_node(nodeMatrimoniPMuller)
        graph.add_edge(pdp.Edge(nodePareMarit, nodeMatrimoniPMarit))
        graph.add_edge(pdp.Edge(nodeMareMarit, nodeMatrimoniPMarit))
        graph.add_edge(pdp.Edge(nodePareMuller, nodeMatrimoniPMuller))
        graph.add_edge(pdp.Edge(nodeMareMuller, nodeMatrimoniPMuller))
        Gen.add_node(nodeMarit)
        Gen.add_node(nodeMuller)
        Gen.add_node(nodeMatrimoni)
        graph.add_edge(pdp.Edge(nodeMarit, nodeMatrimoni))
        graph.add_edge(pdp.Edge(nodeMuller, nodeMatrimoni))
        graph.add_edge(pdp.Edge(nodeMatrimoniPMarit, nodeMarit))
        graph.add_edge(pdp.Edge(nodeMatrimoniPMuller, nodeMuller))

        #un cop tenim l'arbre bàsic fem expansions buscant fills dels protagonistes
        data = protagonista[0]['Data']
        if data is None or not Assistant.checkData(data):
            data = protagonista[0]['Data_Ins']
            if data is None or not Assistant.checkData(data):
                cercafills = cercaCunyatsMarit = cercaCunyatsMuller = False
        if cercafills:
            cerca = {
                'nomMarit': protagonista[0]['Nom_Marit'],
                'cognomMarit': protagonista[0]['Cognom1_Marit'],
                'data': data[0:4],
                'nomMuller': protagonista[0]['Nom_Muller'],
                'cognomMuller': protagonista[0]['Cognom1_Muller'],
                'tipus': 'Matrimoni'
            }
            fillsProta = cercaFills(cerca)
            Fills = pdp.Subgraph()
            graph.add_subgraph(Fills)
            listoffills = []
            for f in fillsProta:
                if ("fill " + f['nom'] + f['cognom']) not in listoffills:
                    listoffills.append("fill " + f['nom'] + f['cognom'])
                    nodeFill = pdp.Node("fill " + f['nom'] + f['cognom'],
                                        label=f['nom'] + " " + f['cognom'])
                    Fills.add_node(nodeFill)
                    graph.add_edge(pdp.Edge(nodeMatrimoni, nodeFill))

        #Procedim a buscar els cunyats
        if None in PareMarit or None in MareMarit: cercaCunyatsMarit = False
        if cercaCunyatsMarit:
            cerca = {
                'nomMarit': PareMarit[0],
                'cognomMarit': PareMarit[1],
                'data': data[0:4],
                'nomMuller': MareMarit[0],
                'cognomMuller': MareMarit[1],
                'tipus': 'CunyatsMatrimoni'
            }
            nodeCunyatsMarit = cercaFills(cerca)
            listofCunyatsMarit = []
            for t in nodeCunyatsMarit:
                if not (protagonista[0]['Nom_Marit'] is not None
                        and protagonista[0]['Nom_Marit'].strip()
                        == t['nom']) and t['nom'] not in listofCunyatsMarit:
                    listofCunyatsMarit.append(t['nom'])
                    nodeCunyatsMarit = pdp.Node("CunyatMarit " + t['nom'],
                                                label=t['nom'] + " " +
                                                t['cognom'])
                    Gen.add_node(nodeCunyatsMarit)
                    graph.add_edge(
                        pdp.Edge(nodeMatrimoniPMarit, nodeCunyatsMarit))

        if None in PareMuller or None in MareMuller: cercaCunyatsMuller = False
        if cercaCunyatsMuller:
            cerca = {
                'nomMarit': PareMuller[0],
                'cognomMarit': PareMuller[1],
                'data': data[0:4],
                'nomMuller': MareMuller[0],
                'cognomMuller': MareMuller[1],
                'tipus': 'CunyatsMatrimoni'
            }
            nodeCunyatsMuller = cercaFills(cerca)
            listofCunyatsMuller = []
            for t in nodeCunyatsMuller:
                if not (protagonista[0]['Nom_Muller'] is not None
                        and protagonista[0]['Nom_Muller'].strip()
                        == t['nom']) and t['nom'] not in listofCunyatsMuller:
                    listofCunyatsMuller.append(t['nom'])
                    nodeCunyatsMuller = pdp.Node("CunyatMuller " + t['nom'],
                                                 label=t['nom'] + " " +
                                                 t['cognom'])
                    Gen.add_node(nodeCunyatsMuller)
                    graph.add_edge(
                        pdp.Edge(nodeMatrimoniPMuller, nodeCunyatsMuller))

    elif tipus == 'Obituari':
        nomProta = ''
        cercafills = True
        cercaGermans = True

        if protagonista[0]['Nom'] is not None:
            nomProta += protagonista[0]['Nom'].strip() + " "
        else:
            nomProta += "- "
            cercafills = False
        if protagonista[0]['Cognom1'] is not None:
            nomProta += protagonista[0]['Cognom1'].strip()
        else:
            nomProta += "-"
            cercafills = False
        nodeProta = pdp.Node("Prota",
                             label=nomProta,
                             style="filled",
                             fillcolor="#55ffff")
        Gen.add_node(nodeProta)
        nodePareD = pdp.Node("PD", label='-')
        nodeMareD = pdp.Node("MD", label='-')
        nodeMatrimoniPDifunt = pdp.Node("MPDifunt",
                                        label="",
                                        shape='diamond',
                                        style='filled',
                                        height=.1,
                                        width=.1)
        teConjugue = False
        nomParella = []
        PareD = MareD = [None, None]
        for p in partable:
            nom = ''
            if p['Nom'] is not None: nom += p['Nom'].strip() + " "
            else: nom += "- "
            if p['Cognom1'] is not None: nom += p['Cognom1'].strip()
            else: nom += "-"
            if p['Tip_part'] == 'Pare Difunt':
                nodePareD = pdp.Node("PD", label=nom)
                PareD = [p['Nom'], p['Cognom1']]
            if p['Tip_part'] == 'Mare Difunt':
                nodeMareD = pdp.Node("MD", label=nom)
                MareD = [p['Nom'], p['Cognom1']]

            if p['Tip_part'] == 'Conjugue Difunt':
                teConjugue = True
                nomParella = [p['Nom'], p['Cognom1']]
                nodeConjugueDifunt = pdp.Node("ConjugeDifunt", label=nom)
                nodeMatrimoniDifunt = pdp.Node("MDifunt",
                                               label="",
                                               shape='diamond',
                                               style='filled',
                                               height=.1,
                                               width=.1)
                Gen.add_node(nodeConjugueDifunt)
                Gen.add_node(nodeMatrimoniDifunt)
                Gen.add_edge(pdp.Edge(nodeProta, nodeMatrimoniDifunt))
                Gen.add_edge(pdp.Edge(nodeConjugueDifunt, nodeMatrimoniDifunt))

        if not teConjugue or None in nomParella: cercafills = False

        Pares.add_node(nodePareD)
        Pares.add_node(nodeMareD)
        Pares.add_node(nodeMatrimoniPDifunt)
        graph.add_edge(pdp.Edge(nodePareD, nodeMatrimoniPDifunt))
        graph.add_edge(pdp.Edge(nodeMareD, nodeMatrimoniPDifunt))
        graph.add_edge(pdp.Edge(nodeMatrimoniPDifunt, nodeProta))

        # Un cop tenim l arbre original l'expandim amb fills del protagonista
        sexe = protagonista[0]['Sexe']
        if sexe is None or (sexe != 'M' and sexe != 'F'): cercafills = False
        data = protagonista[0]['Data']
        if data is None or not Assistant.checkData(data):
            data = protagonista[0]['Data_Ins']
            if data is None or not Assistant.checkData(data):
                cercafills = False
                cercaGermans = False
        if cercafills:
            if sexe == 'M':
                cerca = {
                    'nomMarit': protagonista[0]['Nom'],
                    'cognomMarit': protagonista[0]['Cognom1'],
                    'data': data[0:4],
                    'nomMuller': nomParella[0],
                    'cognomMuller': nomParella[1],
                    'tipus': 'Obituari'
                }
            else:
                cerca = {
                    'nomMarit': nomParella[0],
                    'cognomMarit': nomParella[1],
                    'data': data[0:4],
                    'nomMuller': protagonista[0]['Nom'],
                    'cognomMuller': protagonista[0]['Cognom1'],
                    'tipus': 'Obituari'
                }
            fillsProta = cercaFills(cerca)
            fillsProta = cercaFills(cerca)
            Fills = pdp.Subgraph()
            graph.add_subgraph(Fills)
            listoffills = []
            for f in fillsProta:
                if ("fill " + f['nom'] + f['cognom']) not in listoffills:
                    listoffills.append("fill " + f['nom'] + f['cognom'])
                    nodeFill = pdp.Node("fill " + f['nom'] + f['cognom'],
                                        label=f['nom'] + " " + f['cognom'])
                    Fills.add_node(nodeFill)
                    graph.add_edge(pdp.Edge(nodeMatrimoniDifunt, nodeFill))
        if None in PareD or None in MareD: cercaGermans = False
        if cercaGermans:
            cerca = {
                'nomMarit': PareD[0],
                'cognomMarit': PareD[1],
                'data': data[0:4],
                'nomMuller': MareD[0],
                'cognomMuller': MareD[1],
                'tipus': 'GermansDifunt'
            }
            GermansProta = cercaFills(cerca)
            listofgermans = []
            for g in GermansProta:
                if not (protagonista[0]['Nom'] is not None
                        and protagonista[0]['Nom'].strip()
                        == g['nom']) and g['nom'] not in listofgermans:
                    listofgermans.append(g['nom'])
                    nodeGerma = pdp.Node("germa " + g['nom'] + g['cognom'],
                                         label=g['nom'] + " " + g['cognom'])
                    Gen.add_node(nodeGerma)
                    graph.add_edge(pdp.Edge(nodeMatrimoniPDifunt, nodeGerma))

    graph.write_png("tfg/static/images/arbre.png")

    return True
Beispiel #10
0
def push_graph_stmt(str, loc, toks):
    g = pydotplus.Subgraph('')
    add_elements(g, toks)
    return g
Beispiel #11
0
def draw_tree():
    from PIL import ImageTk, Image as Image_PIL
    
    c_header=['id',   
            'name', 
            'surname',                                   
            'date_birth',
            'date_death',
            'mother_id',
            'father_id',
            'spouse_id',                                   
            'generation',
            'cluster', 
            'gender',
            'place_birth',
            'country_birth',
            'country',
            'comments'
             ]

    
    # Image
        
    import pydotplus as pdt
    import time
    # import pandas as pd

    df=pddf(backend.view(), columns=c_header)
    
    for c in ['id',   
            'mother_id',
            'father_id',
            'spouse_id',                                   
            'generation',
            'cluster', 
            'gender'       ]:
        df[c]=to_numeric(df[c], downcast='integer',errors='coerce')
        # df[c]=df[c].astype(int)
    
    
    
    
    # df=pd.read_excel('c:/a_tree/gen_tree.xlsx', sheet_name=nn)
    # print(df)
    
    min_level=int(df['generation'].min())
    max_level=int(df['generation'].max())
    
    g = pdt.Dot(graph_type='digraph', compound='true', rankdir='TB',newrank = 'true')
    
    i=0
    edges = []
    nodes=[]
    # create all edges
    
    
    
    #edges = [(1,2), (1,3), (2,4), (2,5), (3,5)]
    #nodes = [(1, "A", "r"), (2, "B", "g"), (3, "C", "g"), (4, "D", "r"), (5, "E", "g")]
    #for e in edges:
    #    g.add_edge(pdt.Edge(e[0], e[1], color=e[2]))
    #    
    #for n in nodes:
    #    node = pdt.Node(name=n[0], label= n[1], fillcolor=n[2], style="filled" )
    #    g.add_node(node)
    #    
    #    
    from ast import literal_eval as make_tuple
    nl=max_level-min_level+1
    s=[None]*(max_level+1)
    
    
    for i in range(min_level,max_level+1):
        s = pdt.Subgraph(i,rank='same')
        for j in df.loc[df['generation']==i, 'id'].values :
    #       s.add_node(pdt.Node(f"{df.loc[df['id']==j, 'Name'].values[0]} {df.loc[df['id']==j, 'Surname'].values[0]}"))
            s.add_node(pdt.Node(f"{df.loc[df['id']==j, 'id'].values[0]}"))
        g.add_subgraph(s)
    
    #min_cl=df['Cluster2'].min()
    #max_cl=df['Cluster2'].max()
    #nl=max_cl-min_cl+1
    #ss=[None]*(max_cl+1)
    #for i in range(min_cl,max_cl+1):
    #    if i>0:
    #        ss = pdt.Cluster(f'c2_{i}', color="blue",rankdir="TB")
    #        for j in df.loc[df['Cluster2']==i, 'id'].values :
    #    #       s.add_node(pdt.Node(f"{df.loc[df['id']==j, 'Name'].values[0]} {df.loc[df['id']==j, 'Surname'].values[0]}"))
    #            ss.add_node(pdt.Node(f"{df.loc[df['id']==j, 'id'].values[0]}"))
    #        g.add_subgraph(ss)
       
    
    min_cl=int(df['cluster'].min())
    max_cl=int(df['cluster'].max())
    nl=max_cl-min_cl+1
    ss=[None]*(max_cl+1)
    for i in range(min_cl,max_cl+1):
        ss = pdt.Cluster(f'c1_{i}', color="white",rankdir="TB")
        for j in df.loc[df['cluster']==i, 'id'].values :
    #       s.add_node(pdt.Node(f"{df.loc[df['id']==j, 'Name'].values[0]} {df.loc[df['id']==j, 'Surname'].values[0]}"))
            ss.add_node(pdt.Node(f"{df.loc[df['id']==j, 'id'].values[0]}"))
        g.add_subgraph(ss)
      
     
        
    for i in range(df.shape[0]):
        m=df.loc[i, 'mother_id']
        f=df.loc[i, 'father_id']
    #    if m in df['id'].values: edges.append((i,df.loc[df['id']==m, 'Name'].index[0],'orange'))
    #    if f in df['id'].values: edges.append((i,df.loc[df['id']==f, 'Name'].index[0],'blue'))  
    #    nodes.append((i, df.loc[i, 'Name'], 'blue'))
    
    
    #    nod=pdt.Node(f"{df.loc[i, 'id']}",label=f"{df.loc[i, 'Name']} {df.loc[i, 'Surname']}",  shape='record', color="blue", style='rounded')
        nod=pdt.Node(f"{df.loc[i, 'id']}",  shape='record', color="blue", style='rounded')
        if m in df['id'].values:        g.add_edge(pdt.Edge(pdt.Node(f"{df.loc[df['id']==m, 'id'].values[0]}"), nod, color='orange'))
        if f in df['id'].values:        g.add_edge(pdt.Edge(pdt.Node(f"{df.loc[df['id']==f, 'id'].values[0]}"), nod, color='#066dba'))
    
    
        if notnull(df.loc[i, 'spouse_id']):
    #         rel=df.loc[i, 'relation to']
    # #        tuple(map(int, re.findall(r'[0-9]+', rel)))
    #         rel=rel.replace('(','').replace(')','').split(',')
            # who=pd.to_numeric(rel[0]).astype(int)
            who=to_numeric(df.loc[i, 'spouse_id'], downcast='integer', errors='coerce')

            # how=rel[1]
    #        g.add_edge(pdt.Edge(pdt.Node(f"{df.loc[df['id']==who, 'Name'].values[0]} {df.loc[df['id']==who, 'Surname'].values[0]}"), nod,  dir='none',color='#bf3fbf')) #label='m',
            if who in df['id'].values:
                # print('yes')
                g.add_edge(pdt.Edge(pdt.Node(f"{df.loc[df['id']==who, 'id'].values[0]}"), nod,  dir='none',color='#bf3fbf')) #label='m',
    
    
    
    for i in  range(df.shape[0]):
        cc='orange'
        if df.loc[i, 'gender']==1: cc='#066dba'
        sstr=f"{df.loc[i, 'name']}"
        if notnull(df.loc[i, 'surname']): sstr=f"{sstr} {df.loc[i, 'surname']}"
        if notnull(df.loc[i, 'date_birth']): 
            if isinstance(df.loc[i, 'date_birth'], int) or isinstance(df.loc[i, 'date_birth'], str): 
                sstr=f"{sstr}\nB: {df.loc[i, 'date_birth']}"
            else: 
                sstr=f"{sstr}\nB: {df.loc[i, 'date_birth'].strftime('%d %b %Y') }" # %H:%M:%S
        
        d=df.loc[i, 'date_death']
        # import numpy as np
        if notnull(d): 
            # print("ddd" , isna(d), isnull(d), d, type(d) )
            sstr=f"{sstr}\nD: {d}"
        
        if notnull(df.loc[i, 'place_birth']): 
            sstr=f"{sstr}\nPoB: {df.loc[i, 'place_birth']} ({df.loc[i, 'country_birth']})"
        
        if not (isnull(df.loc[i, 'comments']) or df.loc[i, 'comments']==''): 
            sstr=f"{sstr}\nComments: {df.loc[i, 'comments']}"
                
        nod=pdt.Node(f"{df.loc[i, 'id']}", label=sstr, shape='box', color=cc, style='rounded')
    
    #    nod=pdt.Node(f"{df.loc[i, 'id']}", label=f"{df.loc[i, 'Name']} {df.loc[i, 'Surname']}\nB: {df.loc[i, 'DoB']}\nD: {df.loc[i, 'DoD']}\nPoB: {df.loc[i, 'Place of Birth']} ({df.loc[i, 'Country of Birth']})", shape='box', color=cc, style='rounded')
        g.add_node(nod)
    
    
    import io
    buf = io.BytesIO()
    g.write_png(buf)
    # plt.savefig(buf, format='png')
    buf.seek(0)
    
    import base64
    buf_img64 = base64.b64encode(buf.getvalue())
    # buf_im_str= u'data:img/jpeg;base64,'+buf_img64.decode('utf-8')
    
    buf_im_str=buf_img64.decode("utf-8")
    # img_g = Image_PIL.open(buf)
    
    # img=Img_IP(g.create_png())
    # img=g.create_png()
    
    # return send_file(buf, mimetype='image/PNG')

    # print (buf_img64)
    # return render_template('image.html' , img= buf_img64.decode('ascii'))


    return render_template('image.html' , img= buf_im_str)