Beispiel #1
0
 def create_network_from_genmodelwrapper(self, gen_model_wrapper):
     self._gen_model_wrapper = gen_model_wrapper
     self._gen_model = self._gen_model_wrapper.get_GenModel()
     # self._test_names = ['GeneChoice_V_gene_Undefined_side_prio7_size89',
     #                     'GeneChoice_J_gene_Undefined_side_prio7_size15',
     #                     'GeneChoice_D_gene_Undefined_side_prio6_size3']
     out = pg.BayesianNetwork('')
     self._init_from_gen_model_wrapper(out)
     return out
Beispiel #2
0
    def __set_bayesian_network(self):

        if self._considered['target']:
            self.__set_target_probability()

        # Model
        self.__model = pm.BayesianNetwork("Bayesian Controller")

        # Adding the direction states
        for i in range(action.Action.num_actions):
            self.__model.add_states(self.__s_direction[i])

        for i in range(action.Action.num_actions):
            if self._considered['target']:
                self.__model.add_states(self.__s_target[i])
                self.__model.add_transition(self.__s_direction[i],
                                            self.__s_target[i])

            if self._considered['danger']:
                self.__model.add_states(self.__s_danger[i])
                self.__model.add_transition(self.__s_direction[i],
                                            self.__s_danger[i])

            if self._considered['obstruction']:
                self.__model.add_states(self.__s_obstruction[i])
                self.__model.add_transition(self.__s_direction[i],
                                            self.__s_obstruction[i])

            if self._considered['visibility']:
                self.__model.add_states(self.__s_visibility[i])
                self.__model.add_transition(self.__s_direction[i],
                                            self.__s_visibility[i])

            if self._considered['hider']:
                self.__model.add_states(self.__s_hider[i])
                self.__model.add_transition(self.__s_direction[i],
                                            self.__s_hider[i])

            if self._considered['seeker']:
                self.__model.add_states(self.__s_seeker[i])
                self.__model.add_transition(self.__s_direction[i],
                                            self.__s_seeker[i])

            if self._considered['blockage']:
                self.__model.add_states(self.__s_blockage[i])
                self.__model.add_transition(self.__s_direction[i],
                                            self.__s_blockage[i])

        self.__model.bake()
Beispiel #3
0
	def fit(self, similarBldDF):
		'''
		climate zone, Design cooling load and principle building activity are parents attributes of main cooling equipment.
		Census division, main cooling equipment, cooling degree days, percentage of building cooled are four parent attribute of high efficient building
		Attributes:
			similarBldDF, a pandas DataFrame object includes a group of building similar to the proposed 
				building.This object is used to train the Bayesian Network classifier.

		'''
		climateZoneDict,COOLLOADDict,principleActivityNDict,MAINCLCPTList,MAINCLDict,CDD65NDict,HECSCPTList=self.attributeDistribution(similarBldDF)

		climateZone=pm.DiscreteDistribution(climateZoneDict)
		designCoolingLoad=pm.DiscreteDistribution(COOLLOADDict)
		principleBuildingActivity=pm.DiscreteDistribution(principleActivityNDict)
		coolingDegreeDays = pm.DiscreteDistribution(CDD65NDict)

		#MCE_CPT is the conditional probability table of main cooling equipment
		mainCoolingEquipmentCPT=pm.ConditionalProbabilityTable(MAINCLCPTList,[climateZone,designCoolingLoad,principleBuildingActivity])
		#HECS_CPT is the conditional probability table of high efficient cooling system.
		highEfficientCoolingSystemCPT=pm.ConditionalProbabilityTable(HECSCPTList,[mainCoolingEquipmentCPT,principleBuildingActivity,\
	                                                                           coolingDegreeDays])
		
		#the first layer parent attributes
		p1_climateZone=pm.Node(climateZone,name="climateZone")#climateZone
		p1_COOLLOAD=pm.Node(designCoolingLoad,name="COOLLOAD")#COOLLOAD
		p1_principleActivity=pm.Node(principleBuildingActivity,name="principleActivity")#principleActivity

		#the second layer parent attributes
		#the main cooling equipment
		p2_MAINCL = pm.Node(mainCoolingEquipmentCPT,name="MAINCL")#
		p2_CDD65 = pm.Node(coolingDegreeDays,name="CDD65")

		#high efficient cooling system
		p_HECS = pm.Node(highEfficientCoolingSystemCPT, name="highEfficientCoolingSystemCPT")

		#the Bayesian Network for the main cooling equipment
		modelMCE = pm.BayesianNetwork("Main cooling equipment")
		modelMCE.add_nodes(p1_climateZone,p1_COOLLOAD,p1_principleActivity,p2_MAINCL,p2_CDD65,p_HECS)
		modelMCE.add_edge(p1_climateZone,p2_MAINCL)
		modelMCE.add_edge(p1_COOLLOAD,p2_MAINCL)
		modelMCE.add_edge(p1_principleActivity,p2_MAINCL)
		modelMCE.add_edge(p2_MAINCL,p_HECS)
		modelMCE.add_edge(p1_principleActivity,p_HECS)
		modelMCE.add_edge(p2_CDD65,p_HECS)
		modelMCE.bake()
		self.BN4CLfitted=modelMCE
Beispiel #4
0
def probDiagnose(percList):
    """
    Funzione che riceve in input una lista con tre tuple contenenti ognuna una
    categoria e la loro percentuale e, attraverso l'uso di una rete bayesiana ed
    il calcolo delle probabilità condizionate, restituisce una lista con le 
    probabilità delle categorie delle diagnosi condizionate dalle categorie
    dei sintomi
    
    Parameters
    ----------
    percList: list
        Lista contenente tre tuple: ogni tupla contiene una categoria  e la
        rispettiva percentuale(per i sintomi) 
    
    Returns
    -------
    condProbList: list
        Lista contenente tre tuple: ogni tupla contiene una categoria e la
        rispettiva probabilità(per le diagnosi)  
    """
    import pomegranate as pg
    sym = pg.DiscreteDistribution({
        'gen': 192. / 389,
        'sup': 125. / 389,
        'inf': 72. / 389
    })
    diagn = pg.ConditionalProbabilityTable(
        [['gen', 'gen', 0.5], ['gen', 'sup', 0.25], ['gen', 'inf', 0.25],
         ['sup', 'gen', 0.20], ['sup', 'sup', 0.75], ['sup', 'inf', 0.05],
         ['inf', 'gen', 0.2], ['inf', 'sup', 0.05], ['inf', 'inf', 0.75]],
        [sym])

    s1 = pg.State(sym, name="sym")
    s2 = pg.State(diagn, name="diagn")

    model = pg.BayesianNetwork("Diagnose finder")
    model.add_states(s1, s2)
    model.add_edge(s1, s2)
    model.bake()

    condProbList = []
    for i in percList:
        beliefs1 = model.predict_proba({'sym': i[1]})
        condProbList.append(beliefs1[1].parameters[0])

    return condProbList
Beispiel #5
0
def _solve_bayes_network(cpts, conditionals=None):
    print(f'cpts: {cpts}')
    print(f'conditionals: {cpts}')
    model = pmg.BayesianNetwork("User Produced Model")
    states = []
    distributions = []
    cond = []
    _cond_stage = []

    def _translator(string):
        if string == 0 or string == '0':
            return 'True'
        elif string == 1 or string == '1':
            return 'False'
        else:
            return None

    counter = 0
    for i, name in enumerate(cpts.keys()):
        temp_dict = cpts[name].to_dict()
        if name not in conditionals:
            for k in temp_dict.keys():
                distributions.append(pmg.DiscreteDistribution(temp_dict[k]))
                states.append(pmg.State(distributions[counter], name=name))
                counter += 1
        else:
            _cond_stage.append(i)
            for col in temp_dict.keys():
                for val in temp_dict[col].keys():
                    arr = [_translator(col), val, temp_dict[col][val]]
                    cond.append(arr)

            print(f'cond: {cond}')
            states.append(
                pmg.State(pmg.ConditionalProbabilityTable(cond, distributions),
                          name=name))
    for i, s in enumerate(states):
        print(f'i: {i}')
        print(f's: {s}')
        model.add_states(s)
        if i not in _cond_stage and _cond_stage:
            model.add_edge(s, states[_cond_stage[0]])
    model.bake()
    return model
Beispiel #6
0
def create_truncated_network(template):
    template_wrapper = BayesianNetworkWrapper(template)
    out = pom.BayesianNetwork()
    v_state = template_wrapper.get_state(
        'GeneChoice_V_gene_Undefined_side_prio7_size147')
    #v_del_state = template_wrapper.get_state('Deletion_V_gene_Three_prime_prio5_size21')
    j_state = template_wrapper.get_state(
        'GeneChoice_J_gene_Undefined_side_prio7_size16')
    #j_del_state = template_wrapper.get_state('Deletion_J_gene_Five_prime_prio5_size23')
    d_state = template_wrapper.get_state(
        'GeneChoice_D_gene_Undefined_side_prio6_size3')
    out.add_states(v_state, j_state, d_state)
    #out.add_states(v_state, j_state, v_del_state, j_del_state, d_state)
    out.add_edge(v_state, j_state)
    #out.add_edge(v_state, v_del_state)
    #out.add_edge(j_state, j_del_state)
    out.add_edge(v_state, d_state)
    out.add_edge(j_state, d_state)
    out.bake()
    return out
Beispiel #7
0
    def export_pom(self):
        '''
        Returns
        -------
        pomegranate BN Model based on given DAG.
        Assume my "sort" function correctly returns a list where
        children are allways ranked higher than parents
        '''
        s = self.sort_nodes(l=list(self.nds.values()))
        model = pm.BayesianNetwork("DIY_GRN")

        # Convert Top Level nodes to Discrete distributions
        top = [i for i in s if len(i.par) == 0]
        topStates = {}

        for n in top:
            pr = n.cpt['Prob'].to_dict()
            va = n.cpt[n.idx].to_dict()
            dist = {}
            for v in va.keys():
                dist[va[v]] = pr[v]

            dist = pm.DiscreteDistribution(dist)
            state = pm.Node(dist, name="G" + str(n.idx))

            topStates["G" + str(n.idx)] = state
            model.add_state(state)

        # Convert Depent Nodes to Conditional Distributions
        dep = [i for i in s if len(i.par) != 0]
        depStates = {}

        for n in dep:

            # Convert floats cpt outcome levels to integers if needed
            if isinstance(n.cpt.iloc[0, 0], np.int64):
                cpt = [fl(l) for l in n.cpt.values.tolist()]

            else:
                cpt = n.cpt.values.tolist()

            # Vector of ID for each parent
            par_id = ["G" + str(i.idx) for i in n.par]

            # Validate that all parents have been processed
            for p in par_id:
                if (not p in topStates.keys()) and (not p in depStates.keys()):
                    print("Problem with parent:", p, "of node:", n.idx)
                    return [topStates, depStates]

            # Get all parents found in the topStates dict
            par = [topStates[i] for i in par_id if i in topStates.keys()]

            # Add all parents in the depStates dict
            par = par + [depStates[i] for i in par_id if i in depStates.keys()]

            cpt = pm.ConditionalProbabilityTable(cpt,
                                                 [p.distribution for p in par])

            state = pm.Node(cpt, name="G" + str(n.idx))
            depStates["G" + str(n.idx)] = state

            # Add node to model
            model.add_state(state)

            # Add edges from parent to this node
            for p in par:
                model.add_edge(p, state)

        # Assemble and "Bake" model
        model.bake()
        return (topStates, depStates, model)
Beispiel #8
0
# In[6]:

s0 = pg.base.State(asia, name="asia")
s1 = pg.base.State(tuberculosis, name="tuberculosis")
s2 = pg.base.State(smoking, name="smoker")
s3 = pg.base.State(lung, name="cancer")
s4 = pg.base.State(bronchitis, name="bronchitis")
s5 = pg.base.State(tuberculosis_or_cancer, name="TvC")
s6 = pg.base.State(xray, name="xray")
s7 = pg.base.State(dyspnea, name='dyspnea')

# Finally we can create our bayesian network. We do this by creating an instance of BayesianNetwork, then adding the states.

# In[7]:

network = pg.BayesianNetwork("asia")
network.add_nodes(s0, s1, s2, s3, s4, s5, s6, s7)

# Then we add the edges to our network.

# In[8]:

network.add_edge(s0, s1)
network.add_edge(s1, s5)
network.add_edge(s2, s3)
network.add_edge(s2, s4)
network.add_edge(s3, s5)
network.add_edge(s5, s6)
network.add_edge(s5, s7)
network.add_edge(s4, s7)
Beispiel #9
0
def export_pom(net, by='index'):
    '''
    Returns
    -------
    pomegranate BN Model based on given DAG.
    Assume my "sort" function correctly returns a list where
    children are allways ranked higher than parents. If Pommegranate is used
    to estimate model likelihood, all outcomes must be of the same data type. 
    Either All int or all string. 
    '''
    s = topoSort(net.export_nds())
    model = pm.BayesianNetwork("DIY_GRN")

    # Convert Top Level nodes to Discrete distributions
    top = [i for i in s if len(i.par) == 0]
    topStates = {}

    for n in top:
        pr = n.cpt['Prob'].to_dict()
        if by == 'index':
            va = n.cpt[n.idx].to_dict()
        else:
            va = n.cpt[n.label].to_dict()
        dist = {}
        for v in va.keys():
            dist[va[v]] = pr[v]

        dist = pm.DiscreteDistribution(dist)
        if by == 'index':
            state = pm.Node(dist, name=str(n.idx))
            topStates[str(n.idx)] = state
        else:
            state = pm.Node(dist, name=str(n.label))
            topStates[str(n.label)] = state

        model.add_state(state)

    # Convert Depent Nodes to Conditional Distributions
    dep = [i for i in s if len(i.par) != 0]
    depStates = {}

    for n in dep:

        # Convert floats cpt outcome levels to integers if needed
        if isinstance(n.cpt.iloc[0, 0], np.int64):
            cpt = [fl(l) for l in n.cpt.values.tolist()]

        else:
            cpt = n.cpt.values.tolist()

        # Vector of ID for each parent
        if by == 'index':
            par_id = [str(i.idx) for i in n.par]
        else:
            par_id = [str(i.label) for i in n.par]

        # Validate that all parents have been processed
        for p in par_id:
            if (not p in topStates.keys()) and (not p in depStates.keys()):
                print("Problem with parent:", p, "of node:", n.idx)
                return [topStates, depStates]

        par = [
            topStates[i] if i in topStates.keys() else depStates[i]
            for i in par_id if i in topStates.keys() or i in depStates.keys()
        ]

        cpt = pm.ConditionalProbabilityTable(cpt,
                                             [p.distribution for p in par])

        if by == 'index':
            state = pm.Node(cpt, name=str(n.idx))
            depStates[str(n.idx)] = state

        else:
            state = pm.Node(cpt, name=str(n.label))
            depStates[str(n.label)] = state

        # Add node to model
        model.add_state(state)

        # Add edges from parent to this node
        for p in par:
            model.add_edge(p, state)

    # Assemble and "Bake" model
    model.bake()
    return (model)
Beispiel #10
0
     [True, True, 0.40]], [ownsDeviceDist])

fraudDist = pom.ConditionalProbabilityTable(
    [[False, False, False, 0.25], [False, True, False, 0.15],
     [True, False, False, 0.20], [True, True, False, 0.0005],
     [False, False, True, 0.75], [False, True, True, 0.85],
     [True, False, True, 0.80], [True, True, True, 0.9995]],
    [onlinePurchaseDist, travelDist])

foreignPurchase = pom.Node(foreignPurchaseDist, name=FP)
onlinePurchase = pom.Node(onlinePurchaseDist, name=OP)
fraud = pom.Node(fraudDist, name=F)
ownsDevice = pom.Node(ownsDeviceDist, name=OD)
travel = pom.Node(travelDist, name=T)

model = pom.BayesianNetwork("Fraud Detection")
model.add_states(fraud, ownsDevice, travel, foreignPurchase, onlinePurchase)
model.add_edge(travel, foreignPurchase)
model.add_edge(ownsDevice, onlinePurchase)
model.add_edge(travel, fraud)
model.add_edge(onlinePurchase, fraud)
model.bake()


def plot(model, filename=None):
    G = pygraphviz.AGraph(directed=True)

    for state in model.states:
        G.add_node(state.name, color='red')

    for parent, child in model.edges:
Beispiel #11
0
    ["F", "F", max_cdf[n - 1, t]],
    ["F", "S", 1 - max_cdf[n - 1, t]],
    ["S", "F", max_cdf[n, t]],
    ["S", "S", 1 - max_cdf[n, t]],
]

distB_A = pm.ConditionalProbabilityTable(cpd, [distA])
distC_B = pm.ConditionalProbabilityTable(cpd, [distB_A])
# distD_C = pm.ConditionalProbabilityTable(cpd, [distC_B])

A = pm.Node(distA, name="A")
B = pm.Node(distB_A, name="B")
C = pm.Node(distC_B, name="C")
# D = pm.Node(distD_C, name="D")

model = pm.BayesianNetwork("Chain Model")
model.add_states(A, B, C)  #, D)
model.add_edge(A, B)
model.add_edge(B, C)
# model.add_edge(C, D)
model.bake()

model.predict_proba([[None, None, None]])  #, None]])

# Star model
# A  B
#  \/
#  C
n = 6
t = s - 3
distA = pm.DiscreteDistribution({
dist_B_A = pm.ConditionalProbabilityTable(cpd_B_A, [dist_A])

cpd_C_B = [
    ["S", "S", sf[n + 1, t]],
    ["S", "F", 1 - sf[n + 1, t]],
    ["F", "S", sf[n, t]],
    ["F", "F", 1 - sf[n, t]],
]

dist_C_B = pm.ConditionalProbabilityTable(cpd_C_B, [dist_B_A])

A = pm.Node(dist_A, name="A")
B = pm.Node(dist_B_A, name="B")
C = pm.Node(dist_C_B, name="C")

model = pm.BayesianNetwork("Chain Model")
model.add_states(A, B, C)
model.add_edge(A, B)
model.add_edge(B, C)
model.bake()

model.predict_proba([[None, None, None]])
model.predict_proba([[None, "S", None]])

# Tree model
# A  B
#  \/
#  C
n = 5
t = 4
    def create_graph(self, name_network="Byesian netowrk"):
        """
        Metodo per create il modello di rete bayesiana (tramite pomegranate) a partire dai dati caricati dal file XML.

        :param name_network: nome della rete bayesiana
        :type name_network: stringa

        :return: Modello pomegranate della rete bayesiana
        :rtype: pomegranate.BayesianNetwork
        """

        cpt_node = {}
        pg_node = {}
        model = pomegranate.BayesianNetwork(name_network)

        for node_name in self.nodes_list:
            if not self.parents[node_name]:
                dict_dist = {}
                for elem in self.name_classes_nodes[node_name]:
                    dict_dist[elem] = self.cpt_nodes[node_name][0][self.name_classes_nodes[node_name].index(elem)]
                # print("name_prior: {}".format(node_name))
                self.nodes[node_name] = pomegranate.DiscreteDistribution(dict_dist)
                # print(self.nodes[node_name])
                pg_node[node_name] = pomegranate.Node(self.nodes[node_name], name=node_name)
            else:
                cpt_pg = []
                parent_list = self.parents[node_name].copy()
                parent_list.reverse()

                mod_list = [len(self.name_classes_nodes[node_name])]

                for i in range(len(parent_list) - 1):
                    mul = mod_list[i] * len(self.name_classes_nodes[parent_list[i]])
                    mod_list.append(mul)

                cont = 0
                for elem in self.cpt_nodes[node_name]:
                    for prob in elem:
                        row = [prob, self.name_classes_nodes[node_name][cont % mod_list[0]]]

                        for parent in parent_list:
                            attr = (cont // mod_list[parent_list.index(parent)]) % len(self.name_classes_nodes[parent])
                            row.append(self.name_classes_nodes[parent][attr])
                        cont += 1
                        row.reverse()
                        cpt_pg.append(row)
                cpt_node[node_name] = cpt_pg

        for node_name in self.nodes_list:
            if self.parents[node_name]:
                # print("parents: {}".format(self.parents[node_name]))
                parent_node_list = []
                for parent in self.parents[node_name]:
                    parent_node_list.append(self.nodes[parent])
                self.nodes[node_name] = pomegranate.ConditionalProbabilityTable(cpt_node[node_name], parent_node_list)
                # print("node {}: {}".format(node_name,self.nodes[node_name]))
                # print("parent_node_list: {}".format(parent_node_list))
                pg_node[node_name] = pomegranate.Node(self.nodes[node_name], name=node_name)

        for node_name in self.nodes_list:
            # le distribuzioni di output seguono l'ordine con cui vengono aggiunti i nodi qui
            model.add_node(pg_node[node_name])

        for node_name in self.nodes_list:
            # print("name {}".format(node_name))
            for parent in self.parents[node_name]:
                # print("parent {}".format(parent))
                model.add_edge(pg_node[parent], pg_node[node_name])

        model.bake()

        return model