Blame view

students/amartins/tarefas/bninput.py 3 KB
3e0f9b8a   Francisco Coelho   back to work?
1
2
import pickle

505cdc43   Francisco Coelho   long due comeback
3
4
5
6
from pgmpy.readwrite import BIFReader
import networkx as nx
import pydot
from networkx.drawing.nx_pydot import graphviz_layout
3e0f9b8a   Francisco Coelho   back to work?
7
8
9
10
from pgmpy.models import BayesianModel
from test import * 

import unittest
505cdc43   Francisco Coelho   long due comeback
11
12

def summary_dag(filename):
3e0f9b8a   Francisco Coelho   back to work?
13
14
15
    """A função "summary_dag" tem como argumento uma string com o nome do ficheiro a ler e 
    retorna um modelo com os dados recolhidos do respetivo ficheiro.
    """
505cdc43   Francisco Coelho   long due comeback
16
17
    file = BIFReader(filename)
    model = file.get_model() # Cria um objeto BayesianModel
3e0f9b8a   Francisco Coelho   back to work?
18
    nodes = list(model.nodes())  # Converte o NodeView para uma lista
505cdc43   Francisco Coelho   long due comeback
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
    
    asc = 0
    des = 0
    nodes_in = 0
    nodes_out = 0

    for x in nodes:
        # Obtem os nós pais e filhos de cada nós
        parents = model.get_parents(x)
        children = model.get_children(x)
        
        if len(parents) != 0:
            des += 1
        if len(children) != 0:
            asc += 1
        nodes_in += len(children)
        nodes_out += len(parents)
    
    return {
        'dag_file': filename, 
        'nodes': nodes, 
        'count_parents': des, 
        'count_children': asc, 
        'count_in_edges': nodes_in, 
        'count_out_edges': nodes_out,
        'bnmodel': model
        }

def summary_str(d):
    s = "DAG file:               " + d["dag_file"] + "\n"
    s += "    Number of nodes:    " + str(len(d["nodes"])) + "\n"
    s += "    Number of parents:  " + str(d["count_parents"]) + "\n"
    s += "    Number of children: " + str(d["count_children"]) + "\n"
    s += "    Average in-degree:  " + str(d["count_in_edges"]/len(d["nodes"])) + "\n"
    s += "    Average out-degree: " + str(d["count_out_edges"]/len(d["nodes"])) + "\n"
    s += "    Nodes:" + "\n"
    nodes = d["nodes"]
    for x in nodes:
        s += "        " + str(x) + "\n"
    return s

def show_dag(model):
    G = nx.DiGraph()
    dot = pydot.Dot(graph_type='digraph')
    for node in model['nodes']:
        G.add_node(node)
        dot.add_node(pydot.Node(node))
    for edge in model['bnmodel'].edges:
        G.add_edge(edge[0], edge[1])
        dot.add_edge(pydot.Edge(edge[0], edge[1]))
    # objeto pydot
    
    # defina o layout do grafo
    pos = graphviz_layout(G, prog='dot')
    # desenhe o grafo usando o networkx
    nx.draw(G, pos, with_labels=True)
    
def save_dag(model, target_filename):
    G = nx.DiGraph()
    for node in model.nodes:
        G.add_node(node)
    for edge in model.edges:
        G.add_edge(edge[0], edge[1])
    # objeto pydot
    dot = pydot.Dot(graph_type='digraph')
    for node in model.nodes:
        dot.add_node(pydot.Node(node))
    for edge in model.edges:
        dot.add_edge(pydot.Edge(edge[0], edge[1]))
    # defina o layout do grafo
    pos = graphviz_layout(G, prog='dot')
    # renderize o grafo com o pydot
    graph = pydot.graph_from_dot_data(dot.to_string())[0]
    graph.write_png(target_filename)

if __name__ == "__main__":
    summary = summary_dag("asia2.bif")
3e0f9b8a   Francisco Coelho   back to work?
96
    pickle.dump(summary, open("asia2.pkl", "wb"))
505cdc43   Francisco Coelho   long due comeback
97
    message = summary_str(summary)
3e0f9b8a   Francisco Coelho   back to work?
98
99
    print(message)
    unittest.main()