def determine_kind(self, graph : Graph, shapes, shape): if graph.get_node(shape.id).has_edges(): if graph.get_node(shape.id).has_mutual_edge(): return "mutual" else: return "one_direction" else: return "no_edges"
def test_get_node(self): try: graph = Graph('static_map', "/map") graph.nodes[10, 10].cost = 10 pose = graph.get_pose(10, 10) n = graph.get_node(pose) self.assertEquals(n.cost, 10) except Exception as e: self.fail(UtilTests.error_str(self.test_get_node.__name__, e))
def test_clean(self): try: graph = Graph('static_map', "/map") n1 = graph.nodes[10, 10] n1.cost = 10 graph.clear_graph() self.assertNotEqual(n1.cost, 10) self.assertEquals(n1.cost, float('inf')) except Exception as e: self.fail(UtilTests.error_str(self.test_clean.__name__, e))
def test_get_hamilton_path_nodes(self): self.g = Graph(["A", "B", "C", "D"]) connections = [["A", "B", 10], ["A", "C", 3], ["A", "D", 2], ["B", "C", 1], ["B", "D", 5], ["C", "D", 7]] self.g.add_not_oriented_valued_connections(connections) self.assertEqual(4, len(self.g.get_hamilton_path_nodes())) self.assertIn(self.g.get_hamilton_path_nodes(), [[Node("B"), Node("C"), Node("A"), Node("D")], [Node("A"), Node("D"), Node("C"), Node("B")]])
def perceive(self, staticObjects, dynamicObjects): ''' Receive: staticObjects, dynamicObjects, levelInfo Precondition: staticObjects is a list of StaticObject dynamicObjects is a list of DynamicObject levelInfo is a list containing the level name, x, and y PositionTest ''' self._experience.perceive(staticObjects, dynamicObjects, self._x, self._y, self._water, self._food, self._loneliness) if self.has_graph is False: self.graph = Graph(staticObjects) self.has_graph = True
def read_files(): """Traitement des fichiers du dossier 'Files' Cette fonction parcours tout les fichiers ayant l'extension '.txt', et une syntaxe correcte sous le format décrit ci-dessous pour les transformer en fichier JSON puis en automate avec graphviz Example: * La premier ligne contient les états finaux séparés par des espaces 1 2 3 * Le reste du fichier contient les transitions sous le format: <état de départ> <caractère à lire> <état d'arrivé> """ input_files = (entry for entry in files_path.iterdir() if entry.is_file()) # Parcours récursif de tout les fichiers dans le dossier Files # 1 fichier == 1 langage/graphe for filename in input_files: # ouvrir en mode lecture with codecs.open(os.path.join(os.getcwd(), filename), encoding='utf-8') as f: # parse le fichier et récupérer l'alphabet, les noeuds et états finaux graph = Graph(f) graph.parse() num_exo = filename.name.split('.')[0] name = filename.name.split('.')[0] + '.json' print(name) json_graph = getgraph(graph) write_to_json_file(name, json_graph) # Exécuter les algorithmes # synchronisation eps = synchronisation(graph) eps_json = getgraph(eps) write_to_json_file(num_exo + "-eps.json", eps_json) # determinisation det = determinisation(eps) det_json = getgraph(det) write_to_json_file(num_exo + "-det.json", det_json) # Minimisation gmin = minimisation(det) gmin_json = getgraph(gmin) write_to_json_file(num_exo + "-min.json", gmin_json) # acceptation # res = acceptation(graph, ['abab', 'bab', 'bca']) generate_automate()
def __init__(self, setup_file_path): # Setup self.setup_file_path = setup_file_path self.setup = configparser.ConfigParser() self.setup.read(setup_file_path) # Set general params self.robot_speed = float( self.setup['GENERAL']['robot_speed']) # Robot speed self.task_execution_time = float( self.setup['GENERAL'] ['task_execution_time']) # Execution time of tasks self.battery_threshold = float( self.setup['GENERAL']['battery_threshold']) self.collision_threshold = float( self.setup['GENERAL']['collision_threshold']) self.max_charging_time = float( self.setup['GENERAL']['max_charging_time']) self.max_tasks_in_task_list = float( self.setup['GENERAL']['max_tasks_in_task_list']) self.epsilon = float( self.setup['GENERAL']['epsilon']) # Objective parameter self.initial_resources = float( self.setup['GENERAL']['initial_resources']) # Set layout params self.node_locations = ast.literal_eval( self.setup['LAYOUT'] ['node_locations']) # List of locations of nodes self.node_neighbors = ast.literal_eval( self.setup['LAYOUT'] ['node_neighbors']) # List of edges between nodes self.node_names = ast.literal_eval( self.setup['LAYOUT']['node_names']) # List of node names self.charge_locations = ast.literal_eval( self.setup['LAYOUT'] ['charge_locations']) # List of charging locations self.depot_locations = ast.literal_eval( self.setup['LAYOUT']['depot_locations']) # List of depot locations self.start_locations = ast.literal_eval( self.setup['LAYOUT'] ['start_locations']) # List of starting locations self.task_locations = ast.literal_eval( self.setup['LAYOUT']['task_locations']) # List of task locations # Create layout self.graph = Graph() self.graph.create_nodes(self.node_locations, self.node_names) self.graph.create_edges(self.node_names, self.node_neighbors)
def get_graph_from_file(file_name): graph = None with open(file_name) as file: lines = file.readlines() for line in lines: words = line.split() if words[0] is preamble_symbol: graph = Graph(int(words[2])) elif words[0] is edge_symbol: graph.add_edge(int(words[1]) - 1, int(words[2]) - 1) graph.set_max_degree() graph.set_colors() graph.make_triangular() print(graph.max_degree, graph.number_vertices) return graph
def test_intersection_automata(): edges = read_graph(os.path.join(DATA_PATH, 'graph_0.txt')) regex = read_regex(os.path.join(DATA_PATH, 'regex_0.txt')) dfa = regex_to_dfa(regex) query_automaton = Automaton(dfa) graph = Graph(edges) automaton_graph = Automaton.from_graph(graph) res = automaton_graph.get_intersection(query_automaton) res_automaton = res.to_automaton() a = Symbol('a') b = Symbol('b') c = Symbol('c') assert res_automaton.accepts([a, b, c]) assert res_automaton.accepts([a, c]) assert res_automaton.accepts([a, c, c]) assert not res_automaton.accepts([a, b, b, c]) assert not res_automaton.accepts([a]) assert not res_automaton.accepts([b]) assert not res_automaton.accepts([c]) assert not res_automaton.accepts([a, b]) assert not res_automaton.accepts([b, c])
def main(): parser = argparse.ArgumentParser() parser.add_argument( "graph_path", help=('Path of file with edge list. ' 'Format: <vertice> <label> <vertice>') ) parser.add_argument( "regex_path", help=('Path of file with regexp') ) parser.add_argument( "--from_v_path", dest="start_vertices_path", help=('Path of file with set of starting vertices.'), required=False ) parser.add_argument( "--to_v_path", dest="end_vertices_path", help=('Path of file with set of ending (final) vertices set.'), required=False ) args = parser.parse_args() edges = read_graph(args.graph_path) regex = read_regex(args.regex_path) start_v = [] if args.start_vertices_path is not None: start_v = list(map(int, read_vertices(args.start_vertices_path))) end_v = [] if args.end_vertices_path is not None: end_v = list(map(int, read_vertices(args.end_vertices_path))) dfa = regex_to_dfa(regex) query_automaton = Automaton(dfa) graph = Graph(edges) automaton_graph = Automaton.from_graph(graph) if start_v != []: if end_v != []: automaton_graph.reach_from_to(query_automaton, start_v, end_v) else: automaton_graph.reach_from(query_automaton, start_v) else: automaton_graph.reach_all(query_automaton) res = automaton_graph.get_intersection(query_automaton) matrices_res = res.adj_matrices for label, matrix in matrices_res.items(): print(f'{label} {matrix.nvals}') return 0
def interpret(self, shapes: List[Shape]): logging.info( f"Creating hierarchy. There are {len(shapes)} nodes to order") graph = Graph() for shape in shapes: # Make node node = Node(shape.id) logging.info( f"Computing Node relationship {shape.id+1} of {len(shapes)}") # Find other nodes node points to for graph_node in graph.nodes: graph_node_id = graph_node.identifier graph_node_shape = shapes[graph_node_id].shape node_shape = shape.shape # Test if the two shapes overlap and have therefore a dependent relationship if node_shape.colliderect(graph_node_shape): # Test if One contains the other if node_shape.contains(graph_node_shape): # Graph node is in Node node.point_to(graph_node_id) graph_node.pointed_at(node.identifier) elif graph_node_shape.contains(node_shape): # Node is in Graph node graph_node.point_to(node.identifier) node.pointed_at(graph_node) else: # The two don't contain each other, but collide graph_node.point_to(node.identifier) graph_node.pointed_at(node.identifier) node.point_to(graph_node_id) node.pointed_at(graph_node_id) # There is no else case, since not overlapping nodes don't point to each other # Append Nodes to graph graph.add_node(node) logging.info(f"Created hierarchy!") return graph
def test_query_from_to(): edges = read_graph(os.path.join(DATA_PATH, 'graph_from_to.txt')) regex = read_regex(os.path.join(DATA_PATH, 'regex_from_to.txt')) dfa = regex_to_dfa(regex) query_automaton = Automaton(dfa) graph = Graph(edges) automaton_graph = Automaton.from_graph(graph) res = automaton_graph.reach_from_to(query_automaton, [2], [1]) expected = parse_pairs(os.path.join(DATA_PATH, 'res_from_to.txt')) assert expected == res
def dfa_to_graph(self): dfa = self.dfa edges = [] states = dict([(state, index) for index, state in enumerate(dfa.states)]) self.start_states = [states[state] for state in dfa.start_states] self.final_states = [states[state] for state in dfa.final_states] for v_from, transitions in dfa.to_dict().items(): for value, v_to in transitions.items(): edges.append((states[v_from], value, states[v_to])) return Graph(edges)
def random_data(request): vertices_num, regex = request.param edges_num = vertices_num * (vertices_num - 1) // 5 v_from = [random.randint(0, vertices_num) for _ in range(edges_num)] v_to = [random.randint(0, vertices_num) for _ in range(edges_num)] values = [random.choice(['a', 'b', 'c', 'd']) for _ in range(edges_num)] edges = zip(v_from, values, v_to) dfa = regex_to_dfa(regex) query_automaton = Automaton(dfa) graph = Graph(edges) automaton_graph = Automaton.from_graph(graph) return automaton_graph, query_automaton
def init(request): grammar_name, graph_name, algo_name, res_name = request.param grammar = CFGrammar(os.path.join(DATA_PATH, grammar_name)) rfa = RFA.create_from_cfg_regex(os.path.join(DATA_PATH, grammar_name)) graph = Graph(read_graph(os.path.join(DATA_PATH, graph_name))) expected = set(parse_pairs(os.path.join( DATA_PATH, res_name))) if res_name != [] else set([]) return { 'grammar': grammar, 'rfa': rfa, 'graph': graph, 'algo': algo_name, 'expected': expected }
def init_graph(fname): with open(fname) as f: lines = f.readlines() graph = Graph() for line in lines: [parent, child] = line.strip().split(',') graph.add_edge(parent, child) graph.sort_nodes() return graph
def main(argv=None): if argv is None: argv = sys.argv parser = argparse.ArgumentParser(description='Solve car sharing problem') parser.add_argument('--input', help='Path to input file.', required=True) parser.add_argument('--output', help='Path to output file', required=True) args = parser.parse_args() inPath = args.input outPath = args.output print("Parsing...") rides, rows, cols, numCars, numRides, bonus, maxTime = parseIn(inPath) print("numCars: {n}, numRides: {m}, gridSize: ({y},{x}), totalTime: {t}".format(n=numCars, m=numRides, x=cols, y=rows, t=maxTime)) print("Solving...") # build graph graph = Graph(rows, cols, maxTime) # add weights graph.add_rides_to_graph(rides) # build schedule greedily (car by car) schedule = [] for car in range(numCars): edges = graph.find_shortest_path() print(edges) ridesTaken = [] for edge in edges: if edge['label'] != 'none': ridesTaken.append(edge['label']) ridesTaken.sort() print("Taken rides: ", ridesTaken) schedule.append(ridesTaken) graph.remove_rides(ridesTaken) # write solution to file print("Writing solution to file...") parseOut(outPath, schedule) print("Done")
def check_equivalence(): input_files = (entry for entry in files_path.iterdir() if entry.is_file()) # Parcours récursif de tout les fichiers dans le dossier Files # 1 fichier == 1 langage/graphe number_files = len(os.listdir(files_path)) if number_files != 2: print('Veuillez mettre 2 automates dans le dossier /Files/.') else: graph1 = Graph() graph2 = Graph() num = 1 for filename in input_files: # ouvrir en mode lecture with codecs.open(os.path.join(os.getcwd(), filename), encoding='utf-8') as f: # parse le fichier et récupérer l'alphabet, les noeuds et états finaux graph = Graph(f) graph.parse() num_exo = filename.name.split('.')[0] name = filename.name.split('.')[0] + '.json' print(name) json_graph = getgraph(graph) write_to_json_file(name, json_graph) # Exécuter les algorithmes # synchronisation eps = synchronisation(graph) eps_json = getgraph(eps) write_to_json_file(num_exo + "-eps.json", eps_json) # determinisation det = determinisation(eps) det_json = getgraph(det) write_to_json_file(num_exo + "-det.json", det_json) # Minimisation gmin = minimisation(det) gmin_json = getgraph(gmin) write_to_json_file(num_exo + "-min.json", gmin_json) if num == 1: graph1 = gmin num += 1 else: graph2 = gmin equivalence(graph1, graph2) generate_automate()
def parseGraphFromFile(filename): g = Graph() graphInputFile = open(filename, "r") allLines = graphInputFile.readlines() for i in range(len(allLines)): if i == 0: try: verticeCount = int(allLines[i]) g = Graph(verticeCount) g.initAdjMatris() except: print(bcolors.ERR + "ERROR: First line as to be 1 integer representing vertice count!" + bcolors.ENDC) exit(1) else: try: attributes = allLines[i].split(",") g.addEdge(int(attributes[0]), int(attributes[1]), int(attributes[2])) # g.addEdge(int(attributes[1]), int(attributes[0]), int(attributes[2])) except: print(bcolors.ERR + "ERROR: After first line, lines should be on this format: INTEGER, INTEGER, " "INTEGER\nRepresenting: From,To,Weight" + bcolors.ENDC) return g
def test_connectivity_neighbors(self): try: graph = Graph('static_map', "/map") n1 = graph.nodes[20, 20] n2 = graph.nodes[21, 20] n3 = graph.nodes[18, 18] self.assertGreater(len(n1.neighbors), 4) self.assertGreater(len(n2.neighbors), 4) self.assertGreater(len(n3.neighbors), 4) self.assertLess(len(n3.neighbors), 9) self.assertLess(len(n2.neighbors), 9) self.assertLess(len(n1.neighbors), 9) self.assertFalse(n3 in n1.neighbors) self.assertFalse(n3 in n2.neighbors) self.assertFalse(n1 in n1.neighbors) self.assertTrue(n1 in n2.neighbors) self.assertTrue(n2 in n1.neighbors) except Exception as e: self.fail(UtilTests.error_str(self.test_connectivity_neighbors.__name__, e))
for arg in sys.argv: if not firstLoop: default[i] = arg i += 1 else: firstLoop = False return default if __name__ == '__main__': (outputFilename, instance, outerIter, innerIter, minSuccessIter, alpha) = algorithmParameters() virtual = Graph('../data/' + instance + '/vir.gtt') physical = Graph('../data/' + instance + '/sub.gtt') # DEBUG: '''solution = VirtualNetworkMapping(); vertices = {'7': '19', '1': '34', '5': '26', '2': '30', '9': '42', '4': '21', '8': '47', '6': '2', '3': '20', '0': '14'}; edges = {('5', '1'): ['34', '6', '20', '49', '26'], ('0', '8'): ['14', '47'], ('3', '6'): ['20', '6', '25', '31', '13', '2'], ('6', '3'): ['20', '6', '25', '31', '13', '2'], ('2', '4'): ['30', '10', '21'], ('7', '6'): ['2', '46', '43', '10', '19'], ('2', '5'): ['30', '46', '8', '26'], ('4', '2'): ['30', '10', '21'], ('6', '1'): ['34', '24', '2'], ('8', '0'): ['14', '47'], ('1', '5'): ['34', '6', '20', '49', '26'], ('1', '9'): ['34', '6', '20', '0', '15', '42'], ('9', '1'): ['34', '6', '20', '0', '15', '42'], ('6', '7'): ['2', '46', '43', '10', '19'], ('5', '2'): ['30', '46', '8', '26'], ('8', '5'): ['26', '23', '40', '47'], ('5', '8'): ['26', '23', '40', '47'], ('1', '6'): ['34', '24', '2']}; for k,path in edges.items(): addPartOfSolution(solution, physical, k, virtual.edge[k[0]][k[1]][0], vertices[k[0]], vertices[k[1]], path); if solution != None: print(solution.vertex); print(solution.edge);''' print('Output File Name: ', outputFilename) print('Instance Name: ', instance)
#!/usr/bin/env python3 import sys input_lines = [line for line in sys.stdin] connections = [] for line in input_lines: divided = "".join(line.split()).split(":") value = divided[1] nodes = divided[0].split("-") connections.append([nodes[0], nodes[1], value]) from src.Graph import Graph g = Graph( set([row[0] for row in connections]).union(set([row[1] for row in connections]))) g.add_not_oriented_valued_connections(connections) message = "OK" if g.is_tree() else "ERROR" print("Stav site: " + message)
from flask import Flask, request from src.Graph import Graph import json from werkzeug.wrappers import Response, Request from flask_cors import CORS app = Flask(__name__) CORS(app) global graph graph = Graph('./data/all.json') @app.route('/getTSNE') def getTSNE(): global graph # graph = Graph('./data/all.json') result = graph.getDimension() return Response(json.dumps(result), content_type="application/json") @app.route('/getLayout') def getLayout(): global graph result = graph.getLayout() return Response(json.dumps(result), content_type="application/json") @app.route('/getAll') def getAll(): global graph
#!/usr/bin/env python3 import sys input_lines = [line for line in sys.stdin] connections = [] for line in input_lines: divided = "".join(line.split()).split(":") value = divided[1] nodes = divided[0].split("-") connections.append([nodes[0], nodes[1], value]) from src.Graph import Graph g = Graph( set([row[0] for row in connections]).union(set([row[1] for row in connections]))) g.add_not_oriented_valued_connections(connections) h = g.get_minimal_spanning_tree(printing=True) print("Hodnoceni: " + str(h.total_cost()))
#!/usr/bin/env python3 import sys input_lines = [line for line in sys.stdin] connections = [] for line in input_lines: divided = "".join(line.split()).split(":") value = divided[1] nodes = divided[0].split("-") connections.append([nodes[0], nodes[1], value]) from src.Graph import Graph g = Graph( set([row[0] for row in connections]).union(set([row[1] for row in connections]))) g.add_not_oriented_valued_connections(connections) bridges = g.bridges() for bridge in bridges: print(str(bridge.begg) + " - " + str(bridge.to)) separating_set = g.separating_set() for node in separating_set: print(node)
def main(): graph_file = (open("./data/CA-GrQc.txt", "r")).read() graph = Graph(graph_file)
from playsound import playsound from src.Graph import Graph from src.exhaustive_search import test_gracefulness if __name__ == '__main__': # test of gracefulness on the Petersen graph petersen_graph = Graph([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [(0, 1), (0, 4), (0, 5), (1, 2), (1, 6), (2, 3), (2, 7), (3, 4), (3, 8), (4, 9), (5, 7), (5, 8), (6, 8), (6, 9), (7, 9)]) is_graceful = test_gracefulness(petersen_graph) if is_graceful: playsound("res/tada.mp3") else: playsound("res/fail.mp3")
for line in input_lines: divided = "".join(line.split()).split(":") sourceNode = divided[0] destinationNodes = divided[1].split(",") for node in destinationNodes: node, value = node.split("(") value = value.replace(')', '') connections.append([sourceNode, node, value]) for conn in connections: if "+" in conn[0]: conn[0] = conn[0].replace('+', '') conn[2] = int(conn[2]) + int(1) connections = [conn for conn in connections if conn[0] != conn[1]] from src.Graph import Graph g = Graph( set([row[0] for row in connections]).union(set([row[1] for row in connections]))) g.add_not_oriented_valued_connections(connections) start_node = g.get_node(connections[0][0]) end_node = g.get_node(connections[-1][0]) g.invert_connection_values() nodes_to_print = g.get_shortest_path_nodes(start_node, end_node) distance = None for node in nodes_to_print: if node == end_node: distance = -int(end_node.distance) result = "" for node in nodes_to_print: if result == "":
solution = newSolution gPhysical = newGraph successCount += 1 #end inner for temperature *= alphaCooler print(temperature) j += 1 if successCount < iterMinSuccess: break return solution if __name__ == '__main__': virtual = Graph('../data/rand1/vir.gtt') physical = Graph('../data/rand1/sub.gtt') print(virtual.edge) #solution = inicializeSolution(physical, virtual); solution = VirtualNetworkMapping() vertices = { '7': '19', '1': '34', '5': '26', '2': '30', '9': '42', '4': '21', '8': '47', '6': '2',
#!/usr/bin/env python3 import sys input_lines = [line for line in sys.stdin] from src.Graph import Graph g = Graph(set()) numbers = [] for line in input_lines: divided = "".join(line.split()) numbers.append(divided) #g.build_avl_tree(numbers) #g.search_avl_wide(printing=True)
def main(): ''' 1. We first read in the file. The challenge said that each new line is a single Venmo payment written in JSON format so we import ''' f = open("venmo_input/venmo-trans_short.txt") graph= Graph() # this holds a list of median degrees rollingMedianDegree = [] storeFile =[] for line in f: newStr = line.strip('\n') storeFile.append(newStr) for line in storeFile: #find the current max time of the graph max = findMaxTime(graph) newStr = line.strip('\n') data = json.loads(newStr) if add_to_graph(data['created_time'], max): node = Node(data['actor']) neighbor = Node(data['target']) graph.add_node(node) graph.add_node(neighbor) graph.add_edge(node, neighbor) key = data['actor'] + "->" + data['target'] metadata = data['created_time'] graph_node = graph.get_node(node.id) graph_node.add_metadata(key, metadata) else: continue #get new max max = findMaxTime(graph) # set the weight in this case it is the number of neighbors the node has setWeight(graph) #find expired edges expiredNode = findExpiredNode(graph, 60, max) #remove those relationships for actor, target in expiredNode.items(): graph.get_node(actor).remove_metadata(actor + "->" + target) graph.remove_edge(actor, target) #find the median degree degree = getMedianDegree(graph) #add to rolling median degree records. this is what will be saved in the output. rollingMedianDegree.append(degree) print(graph) print(rollingMedianDegree)