Exemplo n.º 1
0
	def init_map(self):
		graph = DirectedGraph()
		orientations = [Orientation.up, Orientation.left, Orientation.down, Orientation.right]
		
		if self.debug:
			print '> Mapper::init_map Adding all nodes'

		# Add all nodes to graph
		for r in xrange(0, self.max_rows):
			for c in xrange(0, self.max_cols):
				for o in orientations:
					graph.add_node((r,c,o))

		# Add turn right and left to all node. 
		# Add move to all posible nodes
		for node in graph.nodes:
			graph.add_edge(node, (node[0], node[1], (node[2]+1)%4))
			graph.add_edge(node, (node[0], node[1], (node[2]-1)%4))

			if node[2] == Orientation.up and (node[0]+1, node[1], node[2]) in graph.nodes:
				graph.add_edge(node, (node[0]+1, node[1], node[2]))
			elif node[2] == Orientation.left and (node[0], node[1]-1, node[2]) in graph.nodes:
				graph.add_edge(node, (node[0], node[1]-1, node[2]))
			elif node[2] == Orientation.down and (node[0]-1, node[1], node[2]) in graph.nodes: 
				graph.add_edge(node, (node[0]-1, node[1], node[2]))
			elif node[2] == Orientation.right and (node[0], node[1]+1, node[2]) in graph.nodes:
				graph.add_edge(node, (node[0], node[1]+1, node[2]))
		return graph
Exemplo n.º 2
0
def load_linqs_data(content_file, cites_file):
    '''
    Create a DirectedGraph object and add Nodes and Edges
    This is specific to the data files provided at http://linqs.cs.umd.edu/projects/projects/lbc/index.html
    Return two items 1. graph object, 2. the list of domain labels (e.g., ['AI', 'IR'])
    '''
    linqs_graph=DirectedGraph()
    domain_labels=[]
    id_obj_map={}

    with open(content_file, 'r') as node_file:
        for line in node_file:
            line_info=line.split('\n')[0].split('\t')
            n=Node(line_info[0],map(float,line_info[1:-1]),line_info[-1])# id, feature vector, label
            linqs_graph.add_node(n)
            if line_info[-1] not in domain_labels:
                domain_labels.append(line_info[-1])
            id_obj_map[line_info[0]]=n

    with open(cites_file,'r') as edge_file:
        for line in edge_file:
            line_info=line.split('\n')[0].split('\t')
            if line_info[0] in id_obj_map.keys() and line_info[1] in id_obj_map.keys():
                from_node=id_obj_map[line_info[1]]
                to_node=id_obj_map[line_info[0]]
                linqs_graph.add_edge(Edge(from_node,to_node))

    return linqs_graph,domain_labels
Exemplo n.º 3
0
def test_ford_fulkerson_multiple_sources_two_sources_with_limit():

    graph = DirectedGraph()

    graph.add_node('s')
    graph.add_node('s2')
    graph.add_node('a')
    graph.add_node('b')
    graph.add_node('c')
    graph.add_node('d')
    graph.add_node('t')

    graph.add_edge('s', 'a', 10)
    graph.add_edge('s', 'c', 10)
    graph.add_edge('a', 'b', 4)
    graph.add_edge('a', 'c', 2)
    graph.add_edge('a', 'd', 8)
    graph.add_edge('b', 't', 10)
    graph.add_edge('c', 'd', 9)
    graph.add_edge('d', 'b', 6)
    graph.add_edge('d', 't', 10)

    graph.add_edge('s2', 'b', 5)

    sources_limit = {'s': 14, 's2': 1}

    flux = ford_fulkerson_multiple_sources_and_limits(graph, ['s', 's2'], 't',
                                                      sources_limit)
    assert flux == 15, 'Flux expected was 15, found: {}'.format(flux)
Exemplo n.º 4
0
def test_ford_fulkerson_multiple_sources_two_sources():

    graph = DirectedGraph()

    graph.add_node('s')
    graph.add_node('s2')
    graph.add_node('a')
    graph.add_node('b')
    graph.add_node('c')
    graph.add_node('d')
    graph.add_node('t')

    graph.add_edge('s', 'a', 10)
    graph.add_edge('s', 'c', 10)
    graph.add_edge('a', 'b', 4)
    graph.add_edge('a', 'c', 2)
    graph.add_edge('a', 'd', 8)
    graph.add_edge('b', 't', 10)
    graph.add_edge('c', 'd', 9)
    graph.add_edge('d', 'b', 6)
    graph.add_edge('d', 't', 10)

    graph.add_edge('s2', 'b', 5)

    flux = ford_fulkerson_multiple_sources(graph, ['s', 's2'], 't')
    assert flux == 20, 'Flux expected was 19, found: {}'.format(flux)
Exemplo n.º 5
0
def load_linqs_data(content_file, cites_file):
    '''
    Create a DirectedGraph object and add Nodes and Edges
    This is specific to the data files provided at http://linqs.cs.umd.edu/projects/projects/lbc/index.html
    Return two items 1. graph object, 2. the list of domain labels (e.g., ['AI', 'IR'])
    '''
    linqs_graph = DirectedGraph()
    domain_labels = []
    id_obj_map = {}

    with open(content_file, 'r') as node_file:
        for line in node_file:
            line_info = line.split('\n')[0].split('\t')
            n = Node(line_info[0], map(float, line_info[1:-1]),
                     line_info[-1])  # id, feature vector, label
            linqs_graph.add_node(n)
            if line_info[-1] not in domain_labels:
                domain_labels.append(line_info[-1])
            id_obj_map[line_info[0]] = n

    with open(cites_file, 'r') as edge_file:
        for line in edge_file:
            line_info = line.split('\n')[0].split('\t')
            if line_info[0] in id_obj_map.keys(
            ) and line_info[1] in id_obj_map.keys():
                from_node = id_obj_map[line_info[1]]
                to_node = id_obj_map[line_info[0]]
                linqs_graph.add_edge(Edge(from_node, to_node))

    print "domain labels"
    print domain_labels

    return linqs_graph, domain_labels
Exemplo n.º 6
0
def load_board(cities_filename, routes_filename):

    board = DirectedGraph()

    cities: dict[str, City] = _resolve_cities(cities_filename)

    for city in cities:
        board.add_node(cities[city].get_name())

    _resolve_routes(board, routes_filename)

    return board, cities
Exemplo n.º 7
0
def generate_directed_subgraph(original_graph, nodes_subset) -> DirectedGraph:

    new_graph = DirectedGraph()

    for node in original_graph.get_nodes():
        if node in nodes_subset:
            new_graph.add_node(node)

    for edge in original_graph.get_edges():
        if edge[0] in nodes_subset and edge[1] in nodes_subset:
            new_graph.add_edge(edge[0], edge[1], edge[2])

    return new_graph
Exemplo n.º 8
0
class TaskTemplateResolver():
  def __init__(self, task_templates=[]):
    self.template_graph = DirectedGraph()
    self.templates = {}
    self.template_parameters = {}
    self.namespaces = {}
    for template in task_templates:
      self.add_task_template(template)

  def add_task_template(self, template):
    template_id = _ns_template_id(template.namespace, template.id)
    self.templates[template_id] = template
    self.template_parameters[template_id] = dict(template.parameters)
    self.template_graph.add_node(template_id)
    self.namespaces[template.namespace] = True
    for task_id in template.dependencies:
      qualified_task_id = _ns_template_id(template.namespace, task_id)
      if '.' in task_id:
        self.template_graph.add_edge(task_id, template_id)
      else:
        self.template_graph.add_edge(qualified_task_id, template_id)

  def resolve_task_graph(self, template_id):
    if template_id not in self.templates:
      raise KeyError(template_id)

    reverse_graph = self.template_graph.reverse()
    nodes = reverse_graph.bfs_walk_graph(template_id)
    for node in nodes:
      template = self.templates[node]
      for parent_node in reverse_graph[node]:
        inherited_params = self.template_parameters[parent_node]
        params = self.template_parameters[node]
        inherited_params.update(params)

    task_graph = self.template_graph.subgraph(nodes)
    for node in nodes:
      template = self.templates[node]
      params = self.template_parameters[node]
      task = template.resolve_task(params)
      task_graph.node[node]['task'] = task
    return task_graph
def load_linqs_data(content_file, cites_file):
    
    if not os.path.isfile(content_file):
        raise IOError('No content file')
        return
    
    if not os.path.isfile(cites_file):
        raise IOError('No cites file')
        return
        
    graph = DirectedGraph()
    domain_labels = []


    content_file_reader = open(content_file, 'r')


    for line_str in content_file_reader:
        tokens = line_str.split('\t')
        
        node_id = tokens[0]
        feature_vector = tokens[1:-1]
        label = tokens[-1].strip()
        
        new_node = Node(node_id, feature_vector, label)
        graph.add_node(new_node)

        domain_labels.append(tokens[-1].strip())
    
    cites_file_reader = open(cites_file, 'r')
    citations = dict()

    for line in cites_file_reader:
        tokens2 = line.split('\t')

        from_node = tokens2[1].strip()
        to_node = tokens2[0].strip()
        endge = Edge(from_node, to_node)
        graph.add_edge(endge)    

    return graph, set(domain_labels)
Exemplo n.º 10
0
class GraphTests(unittest.TestCase):
    def setUp(self):
        self.graph = DirectedGraph()

    def test_add_node(self):
        self.graph.add_node("Rado")
        self.assertTrue(self.graph.has_node("Rado"))

    def test_add_edge(self):
        self.graph.add_edge("Rado", "Ivo")
        self.assertEqual(self.graph.info, {"Rado": ["Ivo"], "Ivo": []})

    def test_get_neighbors_for(self):
        self.graph.add_edge("Rado", "Gosho")
        self.assertEqual(self.graph.get_neighbors_for("Rado"), ["Gosho"])

    def test_path_between(self):
        self.graph.add_edge("Rado", "Gosho")
        self.graph.add_edge("Rado", "Ani")
        self.graph.add_edge("Gosho", "Ivo")
        self.assertTrue(self.graph.path_between("Rado", "Ani"))
        self.assertFalse(self.graph.path_between("Ani", "Ivo"))
        self.assertTrue(self.graph.path_between("Rado", "Ivo"))
Exemplo n.º 11
0
def test_ford_fulkerson():

    graph = DirectedGraph()

    graph.add_node('s')
    graph.add_node('a')
    graph.add_node('b')
    graph.add_node('c')
    graph.add_node('d')
    graph.add_node('t')

    graph.add_edge('s', 'a', 10)
    graph.add_edge('s', 'c', 10)
    graph.add_edge('a', 'b', 4)
    graph.add_edge('a', 'c', 2)
    graph.add_edge('a', 'd', 8)
    graph.add_edge('b', 't', 10)
    graph.add_edge('c', 'd', 9)
    graph.add_edge('d', 'b', 6)
    graph.add_edge('d', 't', 10)

    flux = ford_fulkerson(graph, 's', 't')
    assert flux == 19, 'Flux expected was 19, found: {}'.format(flux)
Exemplo n.º 12
0
    route = [goal_node]
    
    while goal_node != initial_node:
        route.append(paths[goal_node])
        goal_node = paths[goal_node]
 
    route.reverse()
    return route
 
 
 # Testing algorithm
if __name__ == '__main__':
    import math
    sldist = lambda c1, c2: math.sqrt((c2[0] - c1[0])**2 + (c2[1] - c1[1])**2)
    g = DirectedGraph()
    g.add_node((0, 0))
    g.add_node((1, 1))
    g.add_node((1, 0))
    g.add_node((0, 1))
    g.add_node((2, 2))
 
    g.add_edge((0, 0), (1, 1), 1.5)
    g.add_edge((0, 0), (0, 1), 1.2)
    g.add_edge((0, 0), (1, 0), 1)
    g.add_edge((1, 0), (2, 2), 2)
    g.add_edge((0, 1), (2, 2), 2)
    g.add_edge((1, 1), (2, 2), 1.5)
 
    assert shortest_path(g, (0, 0), (2, 2), sldist) == [(0, 0), (1, 1), (2, 2)]
 
    g.distances[((0, 0), (1, 1))] = 2
Exemplo n.º 13
0
class TaskGraph(Task):
    def __init__(self, *tasks):
        self._label = self.__class__.__name__
        self._graph = DirectedGraph()
        self._schema = TaskSchema.empty()
        for task in tasks:
            self.add_task(task)

    def add_task(self, task):
        self._connect_inputs(task)
        self._connect_outputs(task)
        self._extend_settings(task)
        self._graph.add_node(task)

    def _connect_inputs(self, task):
        for (name, schema) in task.schema.inputs.items():
            connected = False
            for node in self._graph.nodes:
                if name in node.schema.outputs:
                    self._graph.add_arc(src=node, dst=task, label=name)
                    del self._schema.outputs[name]
                    connected = True
            if not connected:
                self._schema.inputs[name] = schema

    def _connect_outputs(self, task):
        for (name, schema) in task.schema.outputs.items():
            connected = False
            for node in self._graph.nodes:
                if name in node.schema.inputs:
                    self._graph.add_arc(src=task, dst=node, label=name)
                    del self._schema.inputs[name]
                    connected = True
            if not connected:
                self._schema.outputs[name] = schema

    def _extend_settings(self, task):
        if task.schema.settings:
            self._schema.settings[task.label] = task.schema.settings

    @property
    def label(self):
        return self._label

    @label.setter
    def label(self, value):
        self._label = value

    @property
    def subtasks(self):
        return self._graph.nodes

    @property
    def dependencies(self):
        return self._graph.arcs

    @property
    def schema(self):
        return self._schema

    def __repr__(self):
        return f"<{self._label}>"
Exemplo n.º 14
0
from graph import DirectedGraph


#fix visted nodes flags length issue
def route_between_nodes(graph, start, goal):
    visted_nodes = [False] * 20

    def go(node, visted):
        if node == goal:
            return True
        visted[node] = True
        result = False
        for n in graph[node]:
            if visted[n] == False:
                result |= go(n, visted)
        return result

    return go(start, visted_nodes)


graph = DirectedGraph()
graph.add_node(0, 1)
graph.add_node(0, 2)
graph.add_node(2, 3)
graph.add_node(2, 5)
graph.add_node(5, 4)
graph.add_node(5, 6)

print('is there a path from 0 to 6 ? ', route_between_nodes(graph.graph, 0, 6))
Exemplo n.º 15
0
class FileLoader(object):
	def __init__(self):
		self.walls  = {}
		self.starts = []
		self.goals  = []
		self.keys   = []

		self.max_cols = None
		self.max_rows = None

		self.undirected_graph = UndirectedGraph()
		self.directed_graph = DirectedGraph()
		self.distance_node = {}
		self.node_distance = {}


	def read_map(self, file_name):
		print 'Reading File'
		f = open(file_name, 'r')

		# Reading walls: [row, col, up, left, down, right]
		print '\t> Parsing walls'

		[self.max_rows, self.max_cols] = f.readline().split(' ')
		self.max_rows = int(self.max_rows)
		self.max_cols = int(self.max_cols)

		for i in range(0, self.max_rows*self.max_cols):
			data = f.readline().split(' ')
			print 'data: ', data
			data = map(int, data)
			self.walls[(data[0],data[1])] = (data[2],data[3],data[4], data[5])

		# Reading starts
		print '\t> Parsing ', f.readline()
		MAX_START = int(f.readline())

		for i in range(0, MAX_START):
			data = f.readline().split(' ')
			if data[2][0] == 'u':
				orientation = 0
			elif data[2][0] == 'l':
				orientation = 1
			elif data[2][0] == 'd':
				orientation = 2
			else:
				orientation = 3
			self.starts.append((int(data[0]),int(data[1]),orientation))

		# Reading Goals
		print '\t> Parsing ', f.readline()
		MAX_GOALS = int(f.readline())

		for i in range(0, MAX_GOALS):
			data = f.readline().split(' ')
			row = int(data[0])
			col = int(data[1])
			self.goals.append((row,col))

		# Reading Keys
		print '\t> Parsing ', f.readline()
		MAX_KEYS = int(f.readline())

		for i in range(0, MAX_KEYS):
			data = f.readline().split(' ')
			row = int(data[0])
			col = int(data[1])
			self.keys.append((row,col))

		f.close()

	def generate_undirected_graph(self):
		orientations = [Orientation.up, Orientation.left, Orientation.down, Orientation.right]

		for w in self.walls.keys():
			row = w[0]
			col = w[1]

			for o in orientations:
				self.undirected_graph.add_node((row,col,o))

			self.undirected_graph.add_edge((row,col,Orientation.up),    (row,col,Orientation.left))
			self.undirected_graph.add_edge((row,col,Orientation.left),  (row,col,Orientation.down))
			self.undirected_graph.add_edge((row,col,Orientation.down),  (row,col,Orientation.right))
			self.undirected_graph.add_edge((row,col,Orientation.right), (row,col,Orientation.up))

		for node, ws in self.walls.items():
			if ws[0] == 0:
				self.undirected_graph.add_edge((node[0],node[1],Orientation.up), (node[0]+1,node[1],Orientation.up))
			if ws[1] == 0:
				self.undirected_graph.add_edge((node[0],node[1],Orientation.left), (node[0],node[1]-1,Orientation.left))
			if ws[2] == 0:
				self.undirected_graph.add_edge((node[0],node[1],Orientation.down), (node[0]-1,node[1],Orientation.down))
			if ws[3] == 0:
				self.undirected_graph.add_edge((node[0],node[1],Orientation.right), (node[0],node[1]+1,Orientation.right))

	def generate_directed_graph(self):
		orientations = [Orientation.up, Orientation.left, Orientation.down, Orientation.right]

		for w in self.walls.keys():
			row = w[0]
			col = w[1]

			for o in orientations:
				self.directed_graph.add_node((row,col,o))

			self.directed_graph.add_edge((row,col,Orientation.up),    (row,col,Orientation.left))
			self.directed_graph.add_edge((row,col,Orientation.left),    (row,col,Orientation.up))

			self.directed_graph.add_edge((row,col,Orientation.left),  (row,col,Orientation.down))
			self.directed_graph.add_edge((row,col,Orientation.down),  (row,col,Orientation.left))

			self.directed_graph.add_edge((row,col,Orientation.down),  (row,col,Orientation.right))
			self.directed_graph.add_edge((row,col,Orientation.right),  (row,col,Orientation.down))

			self.directed_graph.add_edge((row,col,Orientation.right), (row,col,Orientation.up))
			self.directed_graph.add_edge((row,col,Orientation.up), (row,col,Orientation.right))

		for node, ws in self.walls.items():
			if ws[0] == 0:
				self.directed_graph.add_edge((node[0],node[1],Orientation.up), (node[0]+1,node[1],Orientation.up))
			if ws[1] == 0:
				self.directed_graph.add_edge((node[0],node[1],Orientation.left), (node[0],node[1]-1,Orientation.left))
			if ws[2] == 0:
				self.directed_graph.add_edge((node[0],node[1],Orientation.down), (node[0]-1,node[1],Orientation.down))
			if ws[3] == 0:
				self.directed_graph.add_edge((node[0],node[1],Orientation.right), (node[0],node[1]+1,Orientation.right))

	def estimate_distances(self):
		#print '> Exploring distances'
		nodes = self.undirected_graph.nodes

		for node in nodes:
			#print '\t>>Localization::estimate_distances Node ', node
			distance = 0
			orientation = node[2]
			aux_node  = node
			test_node = node

			while True:
				if orientation == Orientation.up:
					test_node = (aux_node[0] + 1, aux_node[1], aux_node[2])
				elif orientation == Orientation.left:
					test_node = (aux_node[0], aux_node[1] - 1, aux_node[2])
				elif orientation == Orientation.down:
					test_node = (aux_node[0] - 1, aux_node[1], aux_node[2])
				elif orientation == Orientation.right:
					test_node = (aux_node[0], aux_node[1] + 1, aux_node[2])

				if not test_node in self.undirected_graph.edges[aux_node]: #BUG
					break
				aux_node = test_node
				distance = distance + 1

			self.distance_node.setdefault(distance, [])
			self.distance_node[distance].append(node)
			self.node_distance[node] = distance
Exemplo n.º 16
0
    def setUp(self):
        dag = DirectedGraph()
        dag.add_node(0)
        dag.add_node(1)
        dag.add_node(2)
        dag.add_node(3)
        dag.add_node(4)
        dag.add_node(5)
        dag.connect(0, 1)
        dag.connect(0, 2)
        dag.connect(0, 3)
        dag.connect(3, 4)
        dag.connect(4, 5)
        self.dag = dag

        cyclic = DirectedGraph()
        cyclic.add_node(0)
        cyclic.add_node(1)
        cyclic.add_node(2)
        cyclic.add_node(3)
        cyclic.add_node(4)
        cyclic.connect(0, 1)
        cyclic.connect(1, 2)
        cyclic.connect(1, 3)
        cyclic.connect(2, 3)
        cyclic.connect(2, 4)
        cyclic.connect(4, 0)
        self.cyclic = cyclic