def union(self, af): currentNodes = copy.copy(self.getNodes().keys()) extraNodes = af.getNodes() nodesCounter = 1 renames = {} # Renombramos los nodos del nuevo AF que existen en el primero for nodeName, node in extraNodes.iteritems(): if nodeName in currentNodes: newNodeName = "Q" + str(nodesCounter) while newNodeName in currentNodes: nodesCounter += 1 newNodeName = "Q" + str(nodesCounter) renames[nodeName] = newNodeName node.setName(newNodeName) nodesCounter += 1 for oldNodeName, newNodeName in renames.iteritems(): for nodeName, node in extraNodes.iteritems(): node.replaceTransition(newNodeName, oldNodeName) firstNodeAF = af.getFirst() if renames.has_key(firstNodeAF): firstNodeAF = renames[firstNodeAF] # Buscamos un nombre valido para el nuevo nodo newNodeName = "Q" + str(nodesCounter) while self.nodes.has_key(newNodeName) or renames.has_key(newNodeName): nodesCounter += 1 newNodeName = "Q" + str(nodesCounter) # Seteamos el nuevo nodo como no-final y agregamos la transicion al inicial de cada AF node = Node(newNodeName, False) node.addTransition("E", self.getFirst()) node.addTransition("E", firstNodeAF) # Reiniciamos el listado de nodos (No podemos agregar una entrada al inicio en un orderecDict) newNodes = collections.OrderedDict() # Agregamos el nodo al AF usando el nombre del nodo como llave newNodes[node.getName()] = node self.first = node.getName() # Agregamos los elementos del AF actual al nuevo listado de nodos for nodeName, node in self.nodes.iteritems(): newNodes[nodeName] = node # Agregamos los elementos del nodo que se une al nuevo listado de nodos for nodeName, node in af.nodes.iteritems(): # Tenemos que reescribir la variable, cuando cambiamos el nombre no cambiamos # el indice en el listado de nodos nodeName = node.getName() newNodes[nodeName] = node # Reemplazamos el listado de nodos self.nodes = newNodes # Actualizamos el listado de simbolos validos self.updateSymbols()
def addBegin(self, element): # Instanciando um novo nó node = Node(element) node.next = self.head self.head = node
def p_p(p): '''body_data : body_data P_O body_data P_E data''' node=Node("P") node.add_children(p[3]) p[0]=sum([p[1],[node],p[5]],[])
def insert_first(self, value): first_value = Node(value) first_value.next = self.head_value self.head_value = first_value self.__length += 1
from linkedlist import Linked_List from node import Node from queue import Queue from stack import Stack linked_list = Linked_List() newNode = Node(4) linked_list.insert_front(newNode) newNode = Node(5) linked_list.insert_front(newNode) newNode = Node(6) linked_list.insert_front(newNode) newNode = Node(7) linked_list.insert_rear(newNode) newNode = Node(8) linked_list.insert_rear(newNode) newNode = Node(9) linked_list.insert_rear(newNode) # linked_list.remove_front() # linked_list.remove_rear() # for i in linked_list.travers_list(): # print(i.data) # newNode = Node(12) # queue = Queue() # queue.enqueue(newNode)
import network from network import Network from network import node from node import Node from node import nodeMode from node import entity from entity import Entity from entity import nodeNature # Construct IoT devices (name, consumption rate, hasIdentifiables, # hasPasswords,hasBiometrics, hasTelemetry, hasMiscellaneous, security mode) # As well as unidentified Entities(name, nature, utility) device1 = Node('Laptop_1', 2, True, True, True, True, True) device2 = Node('Cell_Phone_1', 3, False, True, True, True, True) device3 = Node('MP3_Player_1', 4, False, False, False, True, True) device4 = Node('Pager_1', 5, False, False, False, False, False) # Open file for writing results output = open("../outputs/results_highbenevolent_highthreshold.txt", "a+") totalBenefit = 0 for i in range(10000): # Initialize BAN with previously-constructed IoT devices ban = [device1, device2, device3, device4] # Construct network network = Network(ban) # Run simulation of communication within BAN-- lasts until all known Benevolent # nodes are depleted of power. #@param: Number of random entities, Arbitrary threshold network.runSimulation(ban.__len__() * 100, 0.5000)
temp = current.next hasDuplicates = False while temp and temp.data == current.data: temp = temp.next hasDuplicates = True if hasDuplicates: if temp: current.data = temp.data current.next = temp.next else: current.next = None if head.next == None: head = None else: runner = head while runner.next != current: runner = runner.next runner.next = current.next else: current = current.next return head a = Node(1) a.append(2) a.append(3) a.append(2) a.append(1) print a b = deleteDuplicates(a) print b # return head
def main(k_value=None, p_value=None, paa_value=None, dataset_path=None): """ :param k_value: :param p_value: :param dataset_path: :return: """ if os.path.isfile(dataset_path): # read time_series_from_file time_series = pd.read_csv(dataset_path) # get columns name columns = list(time_series.columns) columns.pop(0) # remove product code # save all maximum value for each attribute attributes_maximum_value = list() attributes_minimum_value = list() for column in columns: attributes_maximum_value.append(time_series[column].max()) attributes_minimum_value.append(time_series[column].min()) time_series_dict = dict() # save dict file instead pandas for index, row in time_series.iterrows(): time_series_dict[row["Product_Code"]] = list(row["W0":"W51"]) # start k_anonymity_top_down time_series_k_anonymized = list() time_series_dict_copy = time_series_dict.copy() logger.info("Start k-anonymity top down approach") k_anonymity_top_down_approach(time_series=time_series_dict_copy, k_value=k_value, columns_list=columns, maximum_value=attributes_maximum_value, minimum_value=attributes_minimum_value, time_series_k_anonymized=time_series_k_anonymized) logger.info("End k-anonymity top down approach") # start kp anonymity # print(list(time_series_k_anonymized[0].values())) # TODO ciclare su tutta la time series e instanziare dataset_anonymized dataset_anonymized = DatasetAnonymized() for group in time_series_k_anonymized: # append group to anonymzed_data (after we will create a complete dataset anonymized) dataset_anonymized.anonymized_data.append(group) # good leaf nodes good_leaf_nodes = list() bad_leaf_nodes = list() # creation root and start splitting node logger.info("Start Splitting node") node = Node(level=1, group=group, paa_value=paa_value) node.start_splitting(p_value, max_level, good_leaf_nodes, bad_leaf_nodes) logger.info("Finish Splitting node") logger.info("Start postprocessing node merge all bad leaf node (if exists) in good " "leaf node with most similar patter") for x in good_leaf_nodes: logger.info("Good leaf node {}, {}".format(x.size, x.pattern_representation)) for x in bad_leaf_nodes: logger.info("Bad leaf node {}".format(x.size)) if len(bad_leaf_nodes) > 0: logger.info("Add bad node {} to good node, start postprocessing".format(len(bad_leaf_nodes))) Node.postprocessing(good_leaf_nodes, bad_leaf_nodes) for x in good_leaf_nodes: logger.info("Now Good leaf node {}, {}".format(x.size, x.pattern_representation)) # list of leaf node associated to group anonymized dataset_anonymized.pattern_anonymized_data.append(good_leaf_nodes) # dataset_anonymized.compute_anonymized_data() # return # dataset_anonymized.compute_anonymized_data() dataset_anonymized.compute_anonymized_data() dataset_anonymized.save_on_file("Dataset\output.csv")
def build_tree(self, points, index_x, index_y, index_z, level): """ Recursively build a kd tree Args: points: a np.ndarray of 3-ele tuples index_x: the sorted index of points in the order of superkey 'x-y-z' index_y: the sorted index of points in the order of superkey 'y-z-x' index_z: the sorted index of points in the order of superkey 'z-x-y' level: The current depth in the tree Returns: The root Node """ # print (index_x, index_y, index_z) assert len(index_x) == len(index_y) == len(index_z) length = len(index_x) if length == 0: return None elif length == 1: # If length is 1, index_x, index_y and index_z contain the same index return Node(points[index_x[0]]) else: # Partition accordint to x-axis if level == 0: # partition 3 index arrays according to the median of index_x median_point_index = index_x[length / 2] # partition x index index_x_lower = copy.deepcopy(index_x[:length / 2]) index_x_upper = copy.deepcopy(index_x[length / 2 + 1:]) # partition y index index_y_lower, index_y_upper = self.partition( points, index_y, median_point_index, level) # partition z index index_z_lower, index_z_upper = self.partition( points, index_z, median_point_index, level) # Partition accordint to y-axis elif level == 1: median_point_index = index_y[length / 2] # partition y index index_y_lower = copy.deepcopy(index_y[:length / 2]) index_y_upper = copy.deepcopy(index_y[length / 2 + 1:]) # partition z index index_z_lower, index_z_upper = self.partition( points, index_z, median_point_index, level) # partition x index index_x_lower, index_x_upper = self.partition( points, index_x, median_point_index, level) # Partition accordint to z-axis elif level == 2: median_point_index = index_z[length / 2] # partition z index index_z_lower = copy.deepcopy(index_z[:length / 2]) index_z_upper = copy.deepcopy(index_z[length / 2 + 1:]) # partition x index index_x_lower, index_x_upper = self.partition( points, index_x, median_point_index, level) # partition y index index_y_lower, index_y_upper = self.partition( points, index_y, median_point_index, level) del index_x, index_y, index_z # Avoid memory increasing during recurssion res = Node(points[median_point_index]) res.left = self.build_tree(points, index_x_lower, index_y_lower, index_z_lower, (level + 1) % self.dim) res.right = self.build_tree(points, index_x_upper, index_y_upper, index_z_upper, (level + 1) % self.dim) return res
class BlockchainHolder: node = Node()
from node import Node import utilities import time import depth_first # Take puzzle in as input from user # Split input by spaces and convert all elements to int puzzle = [int(x) for x in input().split()] root_node = Node(puzzle, None, '0', 0) #DFS start_time = time.time() goal_node = depth_first.search(root_node) solution_path = utilities.find_solution_path(goal_node) utilities.write_to_file(solution_path, 'puzzleDFS.txt') print("Time to finish DFS: {}".format(time.time() - start_time))
node_list=[] while node!=None: node_list.append(node) node=node.next if len(node_list)==0: return None tmp=node_list.pop() head=tmp while len(node_list)!=0: node=node_list.pop() tmp.next=node tmp=node tmp.next=None return head def printReversedList(self,pHead): node=pHead while node!=None: print node.data node=node.next head=Node(1) head.next=Node(2) head.next.next=Node(3) head.next.next.next=Node(4) head.next.next.next.next=Node(5) s=Solution() phead=s.ReverseList_2(head) s.printReversedList(phead)
def setup(self): self.rnode1 = RoutingNode(Node(addr1, id1), 1) self.rnode2 = RoutingNode(Node(addr2, id2), 1)
def test_node_exceptions(self): Node(addr1, id1).id = id2
from node import Node from walletapp import WalletApp import socket import sys import threading """ Syntax python test_p2p node 8000: Open new connection python test_p2p node register 8000: Connect to port 8000 python test_p2p wallet register 8000: Subscribe to node 8000 """ host = socket.gethostname() port = int(sys.argv[-1]) node = Node(port) next_port = 9000 is_first = len(sys.argv) == 3 if is_first: t = threading.Thread(target=node.listening) t.start() else: if sys.argv[1] == 'node': print(f'New node') t = threading.Thread(target=node.receiving, args=[port]) next_port += 1 t.start() else: print(f'New wallet') wa = WalletApp(port + 3000) t = threading.Thread(target=wa.receiving, args=[port]) t.start() t2 = threading.Thread(target=wa.listening, args=[wa.port])
textFile.close() textFile = open("graphs.txt", "r") lines = textFile.read() lines = lines.split("\n") graphs = {} distant = {} for line in lines: aux = line.split(", ") if graphs.get(aux[0]) is None: graphs[aux[0]] = [] distant[aux[0]] = float('inf') distant[aux[1]] = float('inf') graphs[aux[0]].append(Node(aux[1], int(aux[2]))) pq = PriorityQueueImpl() camino = {} pq.push(Node("A", 0), 0) distant["A"] = 0 while not pq.empty(): nodeAct = pq.pop() if graphs.get(nodeAct.dest) is None: continue for nodeAdy in graphs.get(nodeAct.dest): if (distant[nodeAct.dest] + nodeAdy.distant) < distant[nodeAdy.dest]: distant[nodeAdy.dest] = distant[nodeAct.dest] + nodeAdy.distant camino[nodeAdy.dest] = nodeAct.dest pq.push(Node(nodeAdy.dest, distant[nodeAdy.dest]), distant[nodeAdy.dest])
def add(self, item): temp = Node(item) temp.setNext(self.head) self.head = temp
def add(self, item): """Adds item to self.""" if not item in self: self.items = Node(item, self.items) self.size += 1
def show_kripke_model(self, graph_name): node = Node(nodes=self.possible_worlds, edges=self.relations) node.show_kripke_model(graph_name)
def push(self, elem): node = Node(elem) node.next = self.top self.top = node self._size = self._size + 1
def bfs(initial_state): graph = pydot.Dot(graph_type='digraph', label="Missionaries and Cannibals State Space", fontsize="30", color="red", fontcolor="blue", style="filled", fillcolor="black") start_node = Node(initial_state, None, None, 0) if start_node.goal_test(): return start_node.find_solution() q = Queue() q.put(start_node) explored = [] killed = [] print("The starting node is \ndepth=%d" % start_node.depth) print(str(start_node.state)) while not (q.empty()): node = q.get() print("\nthe node selected to expand is\ndepth=" + str(node.depth) + "\n" + str(node.state) + "\n") explored.append(node.state) graph.add_node(node.graph_node) if node.parent: diff = np.subtract(node.parent.state, node.state) if node.parent.state[2] == 0: diff[0], diff[1] = -diff[0], -diff[1] graph.add_edge( pydot.Edge(node.parent.graph_node, node.graph_node, label=str(diff))) children = node.generate_child() if not node.is_killed(): print("the children nodes of this node are", end="") for child in children: if child.state not in explored: print("\ndepth=%d" % child.depth) print(str(child.state)) if child.goal_test(): print("which is the goal state\n") graph.add_node(child.graph_node) diff = np.subtract(node.parent.state, node.state) if node.parent.state[2] == 0: diff[0], diff[1] = -diff[0], -diff[1] graph.add_edge( pydot.Edge(child.parent.graph_node, child.graph_node, label=str(diff))) # colour all leaves blue leafs = {n.get_name(): True for n in graph.get_nodes()} for e in graph.get_edge_list(): leafs[e.get_source()] = False for leaf in leafs: if leafs[leaf] and str(leaf) not in killed and str( leaf) != "\"[0, 0, 0]\"": node = pydot.Node(leaf, style="filled", fillcolor="blue") graph.add_node(node) draw_legend(graph) graph.write_png('solution.png') return child.find_solution() if child.is_valid(): q.put(child) explored.append(child.state) else: print("This node is killed") killed.append("\"" + str(node.state) + "\"") return
def getAllChildren(node: Node): currentNodeState = node.state tempChildState = copy.deepcopy(currentNodeState) allChildren = [] # child 0-1 tempChildState[0], tempChildState[1] = tempChildState[1], tempChildState[0] newChild = Node(currentNodeState, tempChildState) allChildren.append(newChild) tempChildState = copy.deepcopy(currentNodeState) # child 1-2 tempChildState[1], tempChildState[2] = tempChildState[2], tempChildState[1] newChild = Node(currentNodeState, tempChildState) allChildren.append(newChild) tempChildState = copy.deepcopy(currentNodeState) # child 0-3 tempChildState[0], tempChildState[3] = tempChildState[3], tempChildState[0] newChild = Node(currentNodeState, tempChildState) allChildren.append(newChild) tempChildState = copy.deepcopy(currentNodeState) # child 1-4 tempChildState[1], tempChildState[4] = tempChildState[4], tempChildState[1] newChild = Node(currentNodeState, tempChildState) allChildren.append(newChild) tempChildState = copy.deepcopy(currentNodeState) # child 2-5 tempChildState[2], tempChildState[5] = tempChildState[5], tempChildState[2] newChild = Node(currentNodeState, tempChildState) allChildren.append(newChild) tempChildState = copy.deepcopy(currentNodeState) # child 3-4 tempChildState[3], tempChildState[4] = tempChildState[4], tempChildState[3] newChild = Node(currentNodeState, tempChildState) allChildren.append(newChild) tempChildState = copy.deepcopy(currentNodeState) # child 4-5 tempChildState[4], tempChildState[5] = tempChildState[5], tempChildState[4] newChild = Node(currentNodeState, tempChildState) allChildren.append(newChild) tempChildState = copy.deepcopy(currentNodeState) # child 3-6 tempChildState[3], tempChildState[6] = tempChildState[6], tempChildState[3] newChild = Node(currentNodeState, tempChildState) allChildren.append(newChild) tempChildState = copy.deepcopy(currentNodeState) # child 4-7 tempChildState[4], tempChildState[7] = tempChildState[7], tempChildState[4] newChild = Node(currentNodeState, tempChildState) allChildren.append(newChild) tempChildState = copy.deepcopy(currentNodeState) # child 5-8 tempChildState[5], tempChildState[8] = tempChildState[8], tempChildState[5] newChild = Node(currentNodeState, tempChildState) allChildren.append(newChild) tempChildState = copy.deepcopy(currentNodeState) # child 6-7 tempChildState[6], tempChildState[7] = tempChildState[7], tempChildState[6] newChild = Node(currentNodeState, tempChildState) allChildren.append(newChild) tempChildState = copy.deepcopy(currentNodeState) # child 7-8 tempChildState[7], tempChildState[8] = tempChildState[8], tempChildState[7] newChild = Node(currentNodeState, tempChildState) allChildren.append(newChild) return allChildren
def add(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node
fdict = {} lowestF = 99999999 for node in self.A: #fscore = node.getF() fdict[node] = fscore if fscore < lowestF: lowestF = fscore ''' #iterates thru all nodes, gets all their fscores, lowest fscore will be given value lowestF def bubbledown(self, pos): # write the code to bubble the values down the heap pass def __len__(self): return len(self.A) def __str__(self): ret = "" for x in self.A: ret += str(x) + "," return ret #tests f = PriorityQueue() f.insert(Node(3, 4, 5)) f.remove()
def main(): tower = open('input.txt', 'r') ''' length = 0 for program in tower: list1 = program.split() weight = int(list1[1].lstrip('(').rstrip(')')) if len(list1) > length: length = len(list1) bottom = list1 print(bottom) ''' nodeList = [] nameList = [] for program in tower: list1 = program.split() name = list1[0] weight = int(list1[1].lstrip('(').rstrip(')')) subTowerNames = [] if len(list1) > 2: for i in range(3, len(list1)): subTowerNames.append(list1[i].rstrip(',')) newNode = Node(name, weight, subTowerNames) nodeList.append(newNode) nameList.append(name) for node in nodeList: if not node.isTopTower(): for name in node.getSubTowerNames(): index = nameList.index(name) node.setSubTowerLink(nodeList[index]) nodeList[index].setLinked() for node in nodeList: if not node.isTopTower(): if not node.isLinked(): print(node.getName()) bottomNode = node ''' nodePtr = bottomNode found = False while not found: if not node.isTopTower(): first = True for node in nodePtr.getSubTowerLinks(): if first: weight = node.getWeight() first = False continue if node.getWeight() != weight: found = True unbalancedTower = nodePtr break ''' # unbalancedTower = checkWeight2(bottomNode) # print(unbalancedTower) # print(bottomNode.getWeight()) # print(getTrueWeight(bottomNode)) for node1 in bottomNode.getSubTowerLinks(): for node2 in node1.getSubTowerLinks(): if getTrueWeight(node2) == 15378: for node3 in node2.getSubTowerLinks(): if getTrueWeight(node3) == 1060: print(node3.getWeight() - 9) ''' for program in unbalancedTower.getSubTowerLinks(): print(program.getWeight()) ''' tower.close()
directory = os.path.join(COMPOSITIONS_DIR, self.topology) os.makedirs(directory, exist_ok=True) filename = os.path.join(directory, COMPOSE_FILE_NAME) with open(filename, 'w+') as f: f.write(composeFileString) return composeFileString class ServiceBuilder: def __init__(self, topology: str, node: Node): self.node = node self.topology = topology self.nlsrConfig = NLSR_CONFIG_FORMAT.format(topology=topology, nodeName=node.nodeName) self.gameCommand = "" if node.router else GAME_COMMAND_FORMAT.format( nodeName=node.nodeName) def buildServiceString(self) -> str: return serviceFormat.format( nodeId=self.node.nodeId, nlsrConfig=self.nlsrConfig, gameCommand=self.gameCommand, volumes="" if self.topology in NO_VOLUME else volumes, nodeName=self.node.nodeName, nodeHostname=self.node.hostname) if __name__ == "__main__": composeBuilder = ComposeBuilder( "tree", [Node("A"), Node("G", router=True)]) print(composeBuilder.buildComposeFile())
def node(): return Node()
def main(): bayesian_vars, required_probabilities, expected_probabilities = parser.read_input( ) bayesian_graph, Phi = build_bayesian_graph(bayesian_vars) # 2.1: Build undirected graph U based on the Bayesian graph G undirected_graph = bayesian_graph.make_undirected_copy() # 2.2: Build "moral" graph H based on U for node in bayesian_graph.nodes.values(): u_parents = [ undirected_graph.get_node(parent_name) for parent_name in node.parents ] if len(u_parents) < 2: continue for combo in combinations(u_parents, 2): node1, node2 = combo if not undirected_graph.check_edge(node1, node2): undirected_graph.add_edge(node1, node2) # 2.3: Build "chordal" graph H* based on H(the old U) copy_graph = deepcopy(undirected_graph) sorted_nodes = list(copy_graph.nodes.values()) sorted_nodes.sort( key=(lambda n: copy_graph.count_not_connected_parents(n.name))) while sorted_nodes and copy_graph.count_not_connected_parents( sorted_nodes[-1].name) > 0: node = sorted_nodes[0] for parents_name_combo in combinations( node.parents, 2): # check if 2 by 2 parents are connected parent_name1, parent_name2 = parents_name_combo parent_node1, parent_node2 = copy_graph.nodes[ parent_name1], copy_graph.nodes[parent_name2] if not copy_graph.check_edge( parent_node1, parent_node2): # if they are not linked copy_graph.add_edge(parent_node1, parent_node2) # add edge # also add it to the H* graph undirected_graph.add_edge(undirected_graph.nodes[parent_name1], undirected_graph.nodes[parent_name2]) copy_graph.remove_node(node.name) sorted_nodes = list(copy_graph.nodes.values()) sorted_nodes.sort( key=(lambda n: copy_graph.count_not_connected_parents(n.name))) # 2.4: Build "cliques" graph C using H* cliques = [] bron_kerbosch(cliques, [], list(undirected_graph.nodes.values()), []) # Extract maximal cliques # Create the Graph cliques_graph = Graph(False) for clique in cliques: # clique is a list of Nodes sorted_nodes_list = [node.name for node in clique] sorted_nodes_list.sort() node_name = ''.join(sorted_nodes_list) node_phi = None for phi in Phi: # Compute a factor for each node in C if contains_string(node_name, phi.vars): # phi contains only vars from this Node if node_phi is None: node_phi = phi else: node_phi = multiply_factors(node_phi, phi) node = Node(node_name, [], node_phi) cliques_graph.add_node(node) for nodes_combo in combinations(cliques_graph.nodes.values(), 2): node1, node2 = nodes_combo edge_name = ''.join(intersect_strings(node1.name, node2.name)) if edge_name: cliques_graph.add_edge(node1, node2) # 2.5: Build maximum spanning tree/graph T using Kruskal on C maxspangraph = kruskal(cliques_graph) maxspangraph.fix_nodes_parents( ) # remove nodes that are not neighbours anymore from a Node's parents list # 2.6: Convert probabilities to factors and associate these factors to each # node in the T graph/tree. # I've already done that at the 2.4 step # 3.1: BFS to create tree hierarchy maxspangraph.treeify() for prob in required_probabilities: copy_graph = deepcopy(maxspangraph) # 3.2: Keep only the factors that meet Z = z print(prob) observed = prob.split("|")[1].strip() observed = observed.split() observed = [tuple(obs.split("=")) for obs in observed] # [(val, var)] observed = {obs[0]: int(obs[1]) for obs in observed} for node in copy_graph.nodes.values(): if not node.factor: continue new_factor = condition_factors([node.factor], observed) if new_factor: node.factor = new_factor[0] else: node.factor = None # 3.3: Send messages from leafs to root gather_messages(list(copy_graph.nodes.values())[0], []) # 3.4: Send messages from root to leafs scatter_messages(list(copy_graph.nodes.values())[0], None) # 3.5: Compute required prob required_phi = None conditions = prob.split("|")[0].strip() conditions = conditions.split() conditions = [tuple(condition.split("=")) for condition in conditions] conditions = {condition[0]: condition[1] for condition in conditions} conditions_vars = ''.join(list(conditions.keys())) for node in copy_graph.nodes.values(): if node.factor: if contains_string(''.join(node.factor.vars), conditions_vars): # print("Found one") required_phi = deepcopy(node.factor) break if not required_phi: continue # Bonus reached s = sum(required_phi.values.values()) required_phi = Factor( required_phi.vars, {k: v / s for k, v in required_phi.values.items()}) # Normalize other_vars = [ var for var in required_phi.vars if var not in conditions_vars ] for var in other_vars: required_phi = sum_out(var, required_phi) required_value = [] for var in required_phi.vars: required_value.append(int(conditions[var])) required_value = tuple(required_value) print("Required value:", required_phi.values[required_value]) print("Expected:", expected_probabilities[required_probabilities.index(prob)])
def p_H6(p): 'body_data : body_data H6_O body_data H6_E data' node=Node("H6") node.add_children(p[3]) p[0]=sum([p[1],[node],p[5]],[])
def toAFD(self): # Si el AF ya es un AFD devolvemos la instancia if self.isAFD(): return self # Iniciamos un contador para los nodos que usaremos para eliminar # las secuencias con longitud mayor que 1 tempNodeID = 1 # Iteramos sobre los nodos for nodeName, node in self.nodes.iteritems(): # Obtenemos las transiciones de cada nodo for symbol, transition in node.getTransitions().iteritems(): # Revisamos si a secuencia tiene longitud mayor que 1 if len(symbol) > 1: # Invertimos la secuencia reverseSymbol = symbol[::-1] # Cada nodo que vayamos creando apuntara al ultimo creado # en el primer caso es a la transicion completa del simbolo lastNode = transition # Seteamos una variable con el nombre del ultmo nodo temporal creado # para usarlo en la transicion del nodo inicial tempNodeName = None # Leemos la secuencia invertida caracter a caracter, excepto por el ultimo # (o sea, el primero de la secuencia) ya que ese lo usaremos en el nodo inicial for i in range(0, (len(reverseSymbol) - 1)): # Obtenemos el caracter de la secuencia singleSymbol = reverseSymbol[i] # Creamos un nodo temporal de nombre "tempID", donde ID lo obtenemos # de un contador incremental. El nodo no es final. tempNodeName = "temp%s" % (tempNodeID) tempNode = Node(tempNodeName, False) # Si es la primera iteracion haremos la transicion desde el nodo # a todos los que apuntaba la secuencia inicial, si es un una iteracion mayor # apuntaremos el nodo al ultimo nodo temporal creado for nextNode in lastNode: tempNode.addTransition(singleSymbol, nextNode) # Agregamos el nodo al AF self.addNode(tempNode) # Seteamos la variable lastNode con el nodo recien creado para la siguiente iteracion lastNode = [tempNodeName] #Aumentamos el contador del nodo intermedio tempNodeID += 1 # Luego de desarmar la secuencia eliminamos la transicion del nodo original # y creamos una transicion al ultimo nodo temporal creado node.removeTransition(symbol) node.addTransition(symbol[0], tempNodeName) # Actualizamos el listado de simbolos validos self.symbols = [] self.updateSymbols() # Instanciamos un nuevo AF para el AFD newAF = AF() # Creamos un contados para los nombres de los nodos nodesCounter = 0 # Creamos diccionarios para asociar grupos de nodos con su nombre y vice-versa nodeNameByTransitions = {} # Get nodeName using the group of nodes transitionsByNodeName = {} # Get group of Nodes using the nodeName # Creamos un directorio de nodos nodes = {} # Creamos una lista con los nuevos nodos que crearemos, como solo agregaremos # nodos no hay problemas en modificarlo mientras iteramos nodesToIterate = [] # Asumimos que el primer nodo del AFD es el nodo inicial (Premisa) firstNode = self.nodes.itervalues().next() # Obtenemos la clausura del nodo inicial transitions = self._getClausura([firstNode.getName()]) # Creamos un string con los nodos obtenidos en la clausura, porque las llaves de los # diccionarios no pueden ser mutables transitionString = '|'.join(str(v) for v in transitions) # Seteamos el nombre del nodo inicial nodeName = "Q" + str(nodesCounter) # Asociamos el nombre del nuevo nodo con los nodos primitivos que lo componen nodeNameByTransitions[transitionString] = nodeName transitionsByNodeName[nodeName] = transitions # Agregamos el nodo al listado de nodos por iterar nodesToIterate.append(nodeName) # Determinamos si el nuevo nodo sera final isFinal = self._newNodeIsFinal(transitions) # Creamos un nuevo nodo y lo agregamos al AFD node = Node(nodeName, isFinal) newAF.addNode(node) # Agregamos el nodo al listado de nodos usango el nombre como llave nodes[nodeName] = node # Aumentamos el contador de nodos nodesCounter += 1 # Iteramos sobre los nodos que vamos creando for nodeToIterate in nodesToIterate: # Iteramos sobre los simbolos validos for symbol in self.symbols: # Obtenemos las transiciones de los nodos primitivos que componen el nuevo nodo # usando un simbolo especifico. Este metodo tambien devuelve la clausura. transitions = self._getTransitions(transitionsByNodeName[nodeToIterate], symbol) transitionString = '|'.join(str(v) for v in transitions) # Verificamos si tenemos un "nuevo nodo" compuesto por el listado # de "nodos primitivos" que obtuvimos if transitionString in nodeNameByTransitions: # Si ya hemos creado el nuevo nodo solo agregamos la transicion nodes[nodeToIterate].addTransition(symbol, nodeNameByTransitions[transitionString]) else: # Si no tenemos un "nodo nuevo" compuesto por el listado de nodos primitivos lo creamos # Creamos el nombre del nodo usando el iterador nodeName = "Q" + str(nodesCounter) # Asociamos el nombre del nodo al listado de nodos primitivo y vice-versa nodeNameByTransitions[transitionString] = nodeName transitionsByNodeName[nodeName] = transitions # Agregamos el nuevo nodo al listado de nodos por iterar nodesToIterate.append(nodeName) # Verificamos si el nuevo nodo va a ser final isFinal = self._newNodeIsFinal(transitions) # Creamos el nuevo nodo y lo agregamos al AFD node = Node(nodeName, isFinal) newAF.addNode(node) # Agregamos el nuevo nodo al listado de nodos nodes[nodeName] = node # Aumentamos el contador de nuevos nodos nodesCounter += 1 # Agregamos la transicion al nodo recien creado nodes[nodeToIterate].addTransition(symbol, nodeName) # Actualizamos los simbolos validos en el AFD newAF.updateSymbols() # Devolvemos el AFD return newAF