def addToEtalon(self, data): newDigraph = digraph.Digraph() #print self.keylog for item in data: #key, value = newDigraph.addModif(item) key, value = newDigraph.add(item) if key is not None and value is not None: """with open('out1.csv', "w") as file: #columns = ["key", "time"] writer = csv.DictWriter( ) #writer.writeheader() writer.writerows(item) #print row #print row1""" if self.keylog.has_key(key): self.keylog[key][2] = int(self.keylog.get(key)[2]) + 1 self.keylog[key][0] = float(self.keylog[key][0] + value) / float( self.keylog[key][2]) self.keylog[key][1] = float( (value - self.keylog[key][0])** 2) / float(self.keylog[key][2] - 1) #print self.keylog #print self.keylog[key][1] else: self.keylog[key] = [value, "0", "1"]
def cynet_from_xgmml(self, s_file, name=None, s_layout="force-directed", l_bundle=True, t_xy=None, l_digraph=False): """If t_xy is provided, s_layout is ignored return CyNetwork""" import os if not os.path.exists(s_file): import util util.warn_msg('Missing file: %s' % s_file) return None if not l_digraph: net = xgmml.Network(s_file, name=name) else: import digraph net = digraph.Digraph(s_file, name=name) if t_xy is not None: net.set_XY(t_xy) s_layout = None S = net.T_node.header() #print "---------------->", S #S=[x for x in S if x not in ('Gene','Name','Symbol')] #net.T_node.drop(S, axis=1, inplace=True) ############################## return self.cynet_from_network(net, name=name, s_layout=s_layout, l_bundle=l_bundle)
def to_network_(self, l_digraph=False): out = [] for x in self.c_node.values(): is_node = 1 if x.has_child() else 0 if x == self.root: is_node = 2 out.append({ 'Gene': x.id, 'Symbol': self.c_name.get(x.id, x.id), 'IsNode': is_node }) t_node = pd.DataFrame(out) queue = [self.root] out = [] while len(queue) > 0: x = queue.pop(0) #print ">>>", x.id, x.left.id, x.right.id if x.left is not None: #print x.left, x.left.similarity dist = abs(x.left.similarity - x.similarity) out.append({ 'Gene_A': x.id, 'Gene_B': x.left.id, 'Length': dist, 'Similarity': x.similarity, 'Length_inv': abs(1.0 - dist), 'Similarity_inv': (1 - x.similarity) }) if x.left.has_child(): queue.append(x.left) if x.right is not None: #print x.right, x.right.similarity dist = abs(x.right.similarity - x.similarity) out.append({ 'Gene_A': x.id, 'Gene_B': x.right.id, 'Length': dist, 'Similarity': x.similarity, 'Length_inv': abs(1.0 - dist), 'Similarity_inv': (1 - x.similarity) }) if x.right.has_child(): queue.append(x.right) t_edge = pd.DataFrame(out) #print t_edge[:] if l_digraph: import digraph net = digraph.Digraph(t_edge, name='Untitled', T_node=t_node, s_noa=None) else: net = xgmml.Network(t_edge, allow_indirect=False, name='Untitled', T_node=t_node, s_noa=None) return net
# the file we will use is edmonton-roads.txt digraph_file = open('edmonton-roads.txt', 'r') # For testing, just use a simple representation of set of vertices, set of # edges as ordered pairs, and dctionaries that map # vertex to (lat,long) # edge to street name V = set() E = set() V_coord = { } E_name = { } V_vert = { } # initialize digraph graph = digraph.Digraph() # process each line in the file for line in digraph_file: # strip all trailing whitespace line = line.rstrip() fields = line.split(",") type = fields[0] if type == 'V': # got a vertex record (id,lat,long) = fields[1:] # vertex id's should be ints
import digraph if __name__ == '__main__': dot = digraph.Digraph('EXAMPLE_GRAPH') dot.add_node('START') dot.add_node('n1') dot.add_node('n2') dot.add_node('n3') dot.add_node('n4') dot.add_node('n5') dot.add_node('END') dot.add_edge('START', 'n1') dot.add_edge('n1', 'n2') dot.add_edge('n2', 'n3') dot.add_edge('n2', 'n4') dot.add_edge('n4', 'n1') dot.add_edge('n3', 'n5') dot.add_edge('n5', 'END') dot.dump_to_file()
def __init__(self): self.temp = digraph.Digraph()
def main(): """ Run the server """ time1 = time.time() print("Initializing..") # Grab program arguments args = parse_args() # Load data file try: global V_coord (V, E, V_coord, E_name) = readgraph.readgraph(args.graphname) except FileNotFoundError: print("Data file {} not found!".format(args.graphname), file=sys.stderr) exit() # Initialize serial port try: if args.serialport: print("Opening serial port: {}".format(args.serialport)) serial_out = serial_in = serial.Serial(args.serialport, 9600) else: print("No serial port. Supply one with the -s port option.") exit() except serial.SerialException: print("Could not open serial port: {}".format(args.serialport), file=sys.stderr) exit() # Set debug mode if args.verbose: debug = True else: debug = False debug = True # Generate a graph from the map and grab the needed values G = digraph.Digraph(E) # Add all orphan vertices. Not really useful, and in fact detrimental # in all cases, but do it for the sake of completeness for v in V: G.add_vertex(v) # Print some debug output if debug: print("Graph loaded with {} vertices and {} edges.".format( G.num_vertices(), G.num_edges())) # initialize storage value prev_end = 0 time2 = time.time() delta_t = repr(time2 - time1) print("Done initializing, took " + delta_t + " seconds") # Parse input while True: msg = receive(serial_in) debug and print("GOT:{}:".format(msg), file=sys.stderr) fields = msg.split(" ") # Ignore malformed messages if len(fields) != 4: debug and print("Ignoring message: {}".format(msg)) continue time1 = time.time() print("Processing..") # Get start and end vertices start_v = (int(fields[0]) / 10**5, int(fields[1]) / 10**5) end_v = (int(fields[2]) / 10**5, int(fields[3]) / 10**5) start = nearest_vertex(start_v) end = nearest_vertex(end_v) debug and print("Routing path from vertex {} to {}".format(start, end)) if end is prev_end: # to speed things up, if the user wants to go to the same destination # as last time, find which point in the previous path # the user is close to, and return the shortest distance to # the next point in the previous path min_dist = float('infinity') for i in range(len(path)): print("i is: " + str(i) + " and path[i] is: " + str(path[i])) dist = distance(V_coord[start], V_coord[path[i]]) if dist < min_dist: closest_v = path[i] min_dist = dist next_dest = path[i + 1] if closest_v == prev_end: # we're there! prev_end = 0 continue secondary_path = least_cost_path(G, start, next_dest, cost_distance) send(serial_out, str(len(secondary_path))) print("The secondary path is:") for v in secondary_path: print(str(v)) print("lat: " + str(int(V_coord[v][0] * 10**5)) + " lon: " + str(int(V_coord[v][1] * 10**5))) send( serial_out, "{} {}".format(int(V_coord[v][0] * 10**5), int(V_coord[v][1] * 10**5))) print("Send path of length {}".format(len(secondary_path))) time2 = time.time() delta_t = repr(time2 - time1) print("Done processing, took " + delta_t + "seconds") continue path = least_cost_path(G, start, end, cost_distance) if path is None: send(serial_out, "0") debug and print("No path found!", file=sys.stderr) else: send(serial_out, str(len(path))) print("The path is:") for v in path: print(str(v)) print("lat: " + str(int(V_coord[v][0] * 10**5)) + " lon: " + str(int(V_coord[v][1] * 10**5))) send( serial_out, "{} {}".format(int(V_coord[v][0] * 10**5), int(V_coord[v][1] * 10**5))) print("Send path of length {}".format(len(path))) # store for optimization prev_start = start prev_end = end time2 = time.time() delta_t = repr(time2 - time1) print("Done processing, took " + delta_t + "seconds")
def main(): """ Run the server """ time1 = time.time() print("Initializing..") # Grab program arguments args = parse_args() # Load data file try: global V_coord (V, E, V_coord, E_name) = readgraph.readgraph(args.graphname) except FileNotFoundError: print("Data file {} not found!".format(args.graphname), file=sys.stderr) exit() # Initialize serial port try: if args.serialport: print("Opening serial port: {}".format(args.serialport)) serial_out = serial_in = serial.Serial(args.serialport, 9600) else: print("No serial port. Supply one with the -s port option.") exit() except serial.SerialException: print("Could not open serial port: {}".format(args.serialport), file=sys.stderr) exit() # Set debug mode if args.verbose: debug = True else: debug = False # Generate a graph from the map and grab the needed values G = digraph.Digraph(E) # Add all orphan vertices. Not really useful, and in fact detrimental # in all cases, but do it for the sake of completeness for v in V: G.add_vertex(v) # Print some debug output if debug: print("Graph loaded with {} vertices and {} edges.".format( G.num_vertices(), G.num_edges())) time2 = time.time() delta_t = repr(time2 - time1) print("Done initializing, took " + delta_t + " seconds") # Parse input while True: msg = receive(serial_in) debug and print("GOT:{}:".format(msg), file=sys.stderr) fields = msg.split(" ") # Ignore malformed messages if len(fields) != 4: debug and print("Ignoring message: {}".format(msg)) continue time1 = time.time() print("Processing..") # Get start and end vertices start_v = (int(fields[0]) / 10**5, int(fields[1]) / 10**5) end_v = (int(fields[2]) / 10**5, int(fields[3]) / 10**5) start = nearest_vertex(start_v) end = nearest_vertex(end_v) debug and print("Routing path from vertex {} to {}".format(start, end)) path = least_cost_path(G, start, end, cost_distance) if path is None: send(serial_out, "0") debug and print("No path found!", file=sys.stderr) else: send(serial_out, str(len(path))) for v in path: send( serial_out, "{} {}".format(int(V_coord[v][0] * 10**5), int(V_coord[v][1] * 10**5))) print("Send path of length {}".format(len(path))) time2 = time.time() delta_t = repr(time2 - time1) print("Done processing, took " + delta_t + "seconds")
# the adjacency list. # alternatively, iterate throught the array in reverse but this # is only to get the same output in number order # otherwise this would not be necessary adj_stack = [] while curr is not None: if not visited[curr.get_value()]: adj_stack.append(curr) curr = curr.next while len(adj_stack) > 0: stack.append(adj_stack.pop()) return False if __name__ == "__main__": digraph = digraph.Digraph(13) with open('data_structures/graphs/graph3.txt') as f: n_vertices, n_edges = map(int, f.readline().split()) for line in f: line = map(int, line.split()) digraph.insert_edge(line[0], line[1]) digraph.print_graph() print "%s, %s" % (has_route(digraph, 0, 0), has_route2(digraph, 0, 0)) print "%s, %s" % (has_route(digraph, 0, 1), has_route2(digraph, 0, 1)) print "%s, %s" % (has_route(digraph, 0, 2), has_route2(digraph, 0, 2)) print "%s, %s" % (has_route(digraph, 0, 3), has_route2(digraph, 0, 3)) print "%s, %s" % (has_route(digraph, 0, 4), has_route2(digraph, 0, 4)) print "%s, %s" % (has_route(digraph, 0, 5), has_route2(digraph, 0, 5)) print "%s, %s" % (has_route(digraph, 0, 6), has_route2(digraph, 0, 6)) print "%s, %s" % (has_route(digraph, 0, 7), has_route2(digraph, 0, 7))