Esempio n. 1
0
    def test_add_edge_not_valid_vertex(self):
        """Tests the add_edge method in a graph with a non-existing vertex.
        """
        graph = Graph(graph = { 'A' : [] })

        graph.add_edge('A', 'B')
        self.assertFalse(graph.has_edge('A', 'B'), 'No edge between A and non-existing B.')
Esempio n. 2
0
def test_add_edge_effect_with_weight():
    graph = Graph()
    end = graph.add_node('coffee')
    start = graph.add_node('muffin')
    graph.add_edge(start, end, 44)
    expected = (end, 44)
    actual = graph._adjacency_list[start][0]
    assert actual == expected
Esempio n. 3
0
def test_add_edge_interloper_start():
    graph = Graph()

    start = Vertex('start')

    end = graph.add_node('end')

    with pytest.raises(KeyError):
        graph.add_edge(start, end)
Esempio n. 4
0
def erdos_renyi(n, p):
	g = Graph()

	for i in xrange(n):
		g.add_node(DiscreteVariable([0,1], name=str(i)))

	for i,j in itertools.product(xrange(n), xrange(n)):
		if random.random() < p:
			g.add_edge(g.get_node_by_name(str(i)),g.get_node_by_name(str(j)))
	return g
Esempio n. 5
0
def test_get_neighbors():
    graph = Graph()
    end = graph.add_node('coffee')
    start = graph.add_node('muffin')
    graph.add_edge(start, end, 44)
    neighbors = graph.get_neighbors(start)
    assert len(neighbors) == 1
    assert neighbors[0][0].value == 'coffee'
    assert isinstance(neighbors[0][0], Vertex)
    assert neighbors[0][1] == 44
Esempio n. 6
0
    def test_add_edge_undirected(self):
        """Tests the add_edge method for an undirected graph.
        """
        graph = Graph(graph = { 'A' : [], 'B' : [] })

        self.assertFalse(graph.has_edge('A', 'B'), 'There is no edge between A and B.')

        graph.add_edge('A', 'B')

        self.assertTrue(graph.has_edge('A', 'B'), 'There is now an edge between A and B.')
def read_edge_list_graph(infile):
    """Parse an edge-list formatted graph from `infile`."""
    num_vertices = int(infile.readline())
    graph = Graph(range(num_vertices))

    for line in infile:
        source, target = line.split(' ')
        graph.add_edge(int(source), int(target))

    return graph
Esempio n. 8
0
def erdos_renyi(n, p):
    g = Graph()

    for i in xrange(n):
        g.add_node(DiscreteVariable([0, 1], name=str(i)))

    for i, j in itertools.product(xrange(n), xrange(n)):
        if random.random() < p:
            g.add_edge(g.get_node_by_name(str(i)), g.get_node_by_name(str(j)))
    return g
Esempio n. 9
0
def knight_graph(board_size):
    # Build the graph
    graph = Graph()
    for row in range(board_size):
        for col in range(board_size):
            node_id = pos_to_node_id(row, col, board_size)
            new_positions = generate_legal_moves(row, col, board_size)
            for e in new_positions:
                nid = pos_to_node_id(e[0], e[1], board_size)
                graph.add_edge(node_id, nid)
    return graph
Esempio n. 10
0
    def test_add_edge_directed(self):
        """Tests the add_edge method for a directed graph.
        """
        graph = Graph(graph = { 'A' : [], 'B' : [] }, is_directed = True)

        self.assertFalse(graph.has_edge('A', 'B'), 'There is no edge from A to B.')
        self.assertFalse(graph.has_edge('B', 'A'), 'There is no edge from B to A.')

        graph.add_edge('A', 'B')

        self.assertTrue(graph.has_edge('A', 'B'), 'There is now an edge from A to B.')
        self.assertFalse(graph.has_edge('B', 'A'), 'There is still no edge from B to A.')
Esempio n. 11
0
def best_first_search_1(initial_state, goal_state=GOAL_STATE):
  """
  Description
  -----------
  Best search algorithm using the number of tiles out of place as heuristic.
  
  Example
  -------
  >>> initial_state = [1,2,3,8,5,6,7,4,0]
  >>> best_first_search_1(initial_state)
  [[1, 2, 3, 8, 5, 6, 7, 4, 0], [1, 2, 3, 8, 5, 0, 7, 4, 6], [1, 2, 3, 8, 0, 5, 7, 4, 6], ... ]
  """
  
  graph = Graph(directed = True, root = initial_state)
  # Uses a priority queue for a best search algorithm
  stack = queue.PriorityQueue()
  stack.put((0,initial_state,0))
  visited = []
  found_goal = False

  while (stack.qsize() > 0) and (not found_goal):

    priority, current_state, depth_counter = stack.get(block=False)

    if not current_state in visited:

      visited.append(current_state)

      all_possible_states = find_all_possible_states_from(current_state)

      # Compute priority based on the heuristic
      for poss_state in all_possible_states:
        out_of_place = 0
        for pos,block in enumerate(poss_state):
          if goal_state[pos] != block:
            out_of_place += 1
        priority = depth_counter + out_of_place

        graph.add_edge(current_state, poss_state)
        stack.put((priority, poss_state, depth_counter + 1))
        if poss_state == goal_state:
          visited.append(poss_state)
          found_goal = True
          break

  return visited
Esempio n. 12
0
    def test_is_connected(self):
        # Returns False for an empty graph
        v, w = self.v, self.w
        g = Graph([v, w], [])
        eq_(g.is_connected(), False)

        # Returns True for a complete graph
        g.add_all_edges()
        eq_(g.is_connected(), True)

        # Returns False when a new vertex is added
        x = Vertex('x')
        g.add_vertex(x)
        eq_(g.is_connected(), False)

        # Returns True when edge is added to connect it
        e2 = Edge(w, x)
        g.add_edge(e2)
        eq_(g.is_connected(), True)
Esempio n. 13
0
def depth_first_search(initial_state, goal_state=GOAL_STATE):
  """
  Description
  -----------
  Implements the depth first search algorithm.
  
  Example
  -------
  >>> initial_state = [1,2,3,8,5,6,7,4,0]
  >>> depth_first_search(initial_state)
  [[1, 2, 3, 8, 5, 6, 7, 4, 0], [1, 2, 3, 8, 5, 0, 7, 4, 6], ... ]
  """
  
  graph = Graph(directed = True, root = initial_state)
  # Uses a stack for the depth first search
  stack = [initial_state]
  visited = []
  found_goal = False

  while (len(stack) > 0) and (not found_goal):

    current_state = stack.pop()

    if not current_state in visited:

      visited.append(current_state)

      all_possible_states = find_all_possible_states_from(current_state)

      for state in all_possible_states:
        graph.add_edge(current_state, state)
        stack.append(state)
        if state == goal_state:
          visited.append(state)
          found_goal = True
          break

  return visited
Esempio n. 14
0
def breath_first_search(initial_state, goal_state=GOAL_STATE):
  """
  Description
  -----------
  Implements the breath first search algorithm.
  
  Example
  -------
  >>> initial_state = [1,2,3,8,5,6,7,4,0]
  >>> breath_first_search(initial_state)
  [[1, 2, 3, 8, 5, 6, 7, 4, 0], [1, 2, 3, 8, 5, 6, 7, 0, 4], [1, 2, 3, 8, 5, 0, 7, 4, 6], [1, 2, 3, 8, 5, 6, 0, 7, 4], ... ]
  """
  
  graph = Graph(directed = True, root = initial_state)
  # Using a queue for the breath first search
  queue = deque([initial_state])
  visited = []
  found_goal = False

  while (len(queue) > 0) and (not found_goal):

    current_state = queue.popleft()

    if not current_state in visited:

      visited.append(current_state)

      all_possible_states = find_all_possible_states_from(current_state)

      for state in all_possible_states:
        graph.add_edge(current_state, state)
        queue.append(state)
        if state == goal_state:
          visited.append(state)
          found_goal = True
          break

  return visited
def extract_connected_component(graph, needle):
    subgraph = Graph([needle])
    queue = [needle]

    step = 0
    while queue:
        vertex = queue.pop(0)
        step += 1
        if step % 10000 == 0:
            print(len(queue), repr(queue[0:min(5, len(queue))]))
            step = 0
        for (pred, obj) in graph.edges[vertex]:
            # examine all neighbours of vertex
            if not obj in subgraph.vertices:
                # we haven't visited this vertex before
                subgraph.add_vertex(obj)
                subgraph.add_edge(vertex, obj, label=pred)
                # we also needle to consider all new neighbours of `obj`
                queue.append(obj)
            elif (pred, obj) not in subgraph.edges[vertex]:
                # we already have `obj`, but not this edge
                subgraph.add_edge(vertex, obj, label=pred)

    return subgraph
print("The maximum degree of the graph is:")
print(graph.Delta())

print("The minimum degree of the graph is:")
print(graph.delta())

print("Edges:")
print(graph.edges())

print("Degree Sequence: ")
ds = graph.degree_sequence()
print(ds)

fullfilling = [[2, 2, 2, 2, 1, 1], [3, 3, 3, 3, 3, 3], [3, 3, 2, 1, 1]]
non_fullfilling = [[4, 3, 2, 2, 2, 1, 1], [6, 6, 5, 4, 4, 2, 1], [3, 3, 3, 1]]

for sequence in fullfilling + non_fullfilling:
    print(sequence, Graph.erdoes_gallai(sequence))

print("Add vertex 'z':")
graph.add_vertex("z")
print(graph)

print("Add edge ('x','y'): ")
graph.add_edge(('x', 'y'))
print(graph)

print("Add edge ('a','d'): ")
graph.add_edge(('a', 'd'))
print(graph)
Esempio n. 17
0
from graphs import Graph

def dfs_visit(graph, source, parent, finished):
    for u in graph.adj_list(source):
        if u not in parent:
            parent[u] = source
            dfs_visit(graph, u, parent, finished)
    finished.append(source)

def dfs(graph):
    parent = {}
    finished = []
    vertices = graph.vertices()
    for v in vertices:
        if v not in parent:
            parent[v] = None
            dfs_visit(graph, v, parent, finished)
    finished = list(reversed(finished))
    return parent, finished
    
if __name__ == '__main__':
    g = Graph()
    for key in [1, 2, 3, 4]:
        g.add_node(key)
    g.add_edge(1, 2)
    g.add_edge(2, 3)
    g.add_edge(3, 4)
    g.add_edge(4, 1)
    print(dfs(g))
Esempio n. 18
0
#!/usr/bin/python3
# Implement adjacency list
from graphs import Vertex, Graph

if __name__ == '__main__':
    g = Graph()
    for i in range(6):
        g.add_vertex(i)

    g.add_edge(0, 1, 5)
    g.add_edge(0, 5, 2)
    g.add_edge(1, 2, 4)
    g.add_edge(2, 3, 9)
    g.add_edge(3, 4, 7)
    g.add_edge(3, 5, 3)
    g.add_edge(4, 0, 1)
    g.add_edge(5, 4, 8)
    g.add_edge(5, 2, 1)

    for v in g:
        for w in v.get_connections():
            print('({}, {})'.format(v.get_id(), w.get_id()))
Esempio n. 19
0
from graphs import Graph

if __name__ == "__main__":
    g = Graph()

    g.add_edge(0, 1, 5)
    g.add_edge(0, 5, 1)
    g.add_edge(1, 2, 1)
    g.add_edge(2, 4, 5)
    g.add_edge(2, 6, 4)
    g.add_edge(3, 2, 5)
    g.add_edge(5, 8, 2)
    g.add_edge(6, 5, 7) # uncomment to create cycle
    g.add_edge(7, 5, 3)
    g.add_edge(8, 6, 3) # uncomment to create cycle
    g.add_edge(4, 1, 2) # uncomment to create cycle

    #g.DFS()
    g.BFS()
    #g.print_debug()

    #g.count_components()
Esempio n. 20
0
def textRank(tokenized_words, tag_word_dict):
    
    words_set = syntactic_filter(tag_word_dict)

    # Add the vertex to the graph
    graph_dict = {}
    for w in words_set:
        graph_dict[w] = []
    
    graph = Graph(graph_dict)

    # Add the edges
    words = nltk.Text (tokenized_words)
    doc = nltk.ConcordanceIndex(words)
    for w in words_set:
        results = get_concordance(w, doc)

        for context in results:
            left = context[0].split()
            right = context[1].split()

            for l in left:
                if l in words_set:
                    graph.add_edge((w, l))
                    graph.add_edge((l, w))

            for l in right:
                if l in words_set:
                    graph.add_edge((w, l))
                    graph.add_edge((l, w))

    # Run the text rank algorithm
    delta = 1
    i = 0
    d = 0.85
    while (delta > 0.0001 and i < 5000):
        
        for v in graph.vertices():
            degree = graph.vertex_degree(v)
            old_rank = graph.text_rank(v)

            sum = 0
            for v2 in graph.adjacency_list(v):
                degree2 = graph.vertex_degree(v2)
                # print ("Degree for " + v2 + " = " + str(degree2))

                tr = graph.text_rank(v2)

                sum += tr / degree2

            value = (1 - d) + d * sum
            graph.set_text_rank(v, value)

            if abs(value - old_rank) < delta:
                delta = abs(value - old_rank)
        i = i + 1

    text_rank_dict = {}
    for v in graph.vertices():
        text_rank_dict[v] = graph.text_rank(v)

    sorted_text_rank = sorted(text_rank_dict.items(), key=operator.itemgetter(1), reverse=True)
    return sorted_text_rank
Esempio n. 21
0
print(info)

VERTICES = info[0]
DEPOT = info[1]
REQUIRED_EDGES = info[2]
NON_REQUIRED_EDGES = info[3]
VEHICLES = info[4]
CAPACITY = info[5]
TOTAL_COST_OF_REQUIRED_EDGES = info[6]
# Build the graph
G = Graph(n=VERTICES, directed=False)
td = 0

for i in range(9, REQUIRED_EDGES + NON_REQUIRED_EDGES + 9):
    G.add_edge(Edge(int(lines[i].strip().split()[0]),
                    int(lines[i].strip().split()[1]),
                    int(lines[i].strip().split()[2]),
                    int(lines[i].strip().split()[3])))
    td += int(lines[i].strip().split()[3])

# Initialize a shortest path matrix
shortestPath = np.zeros((VERTICES + 1, VERTICES + 1))
shortestPath = np.int_(shortestPath)
for i in range(1, VERTICES+1):
    algorithm = Dijkstra(G)
    algorithm.run(i)
    for j in range(i, VERTICES+1):
        shortestPath[i][j] = algorithm.distance[j]
shortestPath = np.maximum(shortestPath, shortestPath.transpose())
shortestPath = shortestPath.tolist()

initial = time.time()
Esempio n. 22
0
DEPOT = 1
REQUIRED_EDGES = int(lines[3].strip().split()[-1])
NON_REQUIRED_EDGES = int(lines[4].strip().split()[-1])
VEHICLES = int(lines[5].strip().split()[-1])
CAPACITY = int(lines[6].strip().split()[-1])
TOTAL_COST_OF_REQUIRED_EDGES = int(lines[8].strip().split()[-1])
f.close()

G = Graph(n=VERTICES, directed=False)
td = 0

for i in range(10, REQUIRED_EDGES + 10):
    _ = re.split('[( , ) coste demanda \r\n]', lines[i])
    _ = filter(lambda x: x != '', _)
    td += int(_[3])
    G.add_edge(Edge(int(_[0]), int(_[1]), int(_[2]), int(_[3])))
for i in range(11 + REQUIRED_EDGES, 11 + REQUIRED_EDGES + NON_REQUIRED_EDGES):
    _ = re.split('[( , ) coste \r\n]', lines[i])
    _ = filter(lambda x: x != '', _)
    G.add_edge(Edge(int(_[0]), int(_[1]), int(_[2])))
'''
# def read_map(file_name):
info = np.zeros(7)
f = open('./CARP_samples/egl-s1-A.dat')
lines = f.readlines()

# Read map info to numpy array info

for i in range(1, 8):
    info[i-1] = lines[i].strip().split()[-1]
f.close()
Esempio n. 23
0
    queue.append(start)
    
    # do BFS
    while(len(queue) > 0):
        next_node = queue.pop(0)
        
        for neighbor in graph.get_edges(next_node):
            if neighbor not in visited:
                queue.append(neighbor)
        
        visited.append(next_node)
        
    # print results
    return {"reachable_nodes": visited}
    
# test
if __name__ == "__main__":
    my_graph = Graph()
    
    node1 = Node(10, 1)
    node2 = Node(13, 2)
    node3 = Node(20, 3)
    
    my_graph.add_node(node1)
    my_graph.add_edge((node2, node3))
    my_graph.add_edge((node3, node1))
    
    my_graph.print_nodes()
    my_graph.print_edges()
    
    print breadth_first_search(my_graph, node2)
Esempio n. 24
0
def best_first_search_2(initial_state, goal_state=GOAL_STATE):
  """
  Description
  -----------
  Best search algorithm using the minimum number moves to reach the goal state as heuristic.
  
  Example
  -------
  >>> initial_state = [1,2,3,8,5,6,7,4,0]
  >>> best_first_search_2(initial_state)
  [[1, 2, 3, 8, 5, 6, 7, 4, 0], [1, 2, 3, 8, 5, 6, 7, 0, 4], [1, 2, 3, 8, 5, 6, 0, 7, 4], ... ]
  """
  
  graph = Graph(directed = True, root = initial_state)
  # Uses a priority queue for a best search algorithm
  stack = queue.PriorityQueue()
  stack.put((0,initial_state,0))
  visited = []
  found_goal = False

  while (stack.qsize() > 0) and (not found_goal):

    priority, current_state, depth_counter = stack.get(block=False)

    if not current_state in visited:

      visited.append(current_state)

      all_possible_states = find_all_possible_states_from(current_state)

      # Compute priority based on the heuristic
      total_distance = 0
      for poss_state in all_possible_states:
        for pos,block in enumerate(poss_state):
          if goal_state[pos] != block:
            # Count vertical distance
            desired_pos = goal_state.index(block)
            def _get_row_level(p):
              level = 0
              if p >=0 and p < 3:
                level = 1
              elif p > 2 and p < 6:
                level = 2
              else:
                level = 9
              return level
            pos_row_lvl = _get_row_level(pos)
            des_pos_row_lvl = _get_row_level(desired_pos)
            vertical_distance = abs(des_pos_row_lvl-pos_row_lvl)
            # Count horizontal distance
            horizontal_distance = abs((pos % 3) - (desired_pos % 3))
            # Add to total distance
            total_distance += vertical_distance + horizontal_distance
        priority = depth_counter + total_distance

        graph.add_edge(current_state, poss_state)
        stack.put((priority, poss_state, depth_counter + 1))
        if poss_state == goal_state:
          visited.append(poss_state)
          found_goal = True
          break

  return visited
Esempio n. 25
0
def test_add_edge_works():
    graph = Graph()
    start = graph.add_node('start')
    end = graph.add_node('end')
    graph.add_edge(start, end)
Esempio n. 26
0
def best_first_search_3(initial_state, goal_state=GOAL_STATE):
  """
  Description
  -----------
  Best search algorithm using the total distance and sequence score as heuristic.
  The "total distance" of the eight tiles in a board position from their "home squares". We use the Manhattan distance to calculate the distance of each tile from its home square.
  The "sequence score" that measures the degree to which the tiles are already ordered in the current position with respect to the order required in the goal configuration.
  
  Example
  -------
  >>> initial_state = [1,2,3,8,5,6,7,4,0]
  >>> best_first_search_3(initial_state)
  [[1, 2, 3, 8, 5, 6, 7, 4, 0], [1, 2, 3, 8, 5, 6, 7, 0, 4], [1, 2, 3, 8, 5, 6, 0, 7, 4], ... ]
  """
  
  graph = Graph(directed = True, root = initial_state)
  # Uses a priority queue for a best search algorithm
  stack = queue.PriorityQueue()
  stack.put((0,initial_state,0))
  visited = []
  found_goal = False

  while (stack.qsize() > 0) and (not found_goal):

    priority, current_state, depth_counter = stack.get(block=False)

    if not current_state in visited:

      visited.append(current_state)

      all_possible_states = find_all_possible_states_from(current_state)

      # Compute priority based on the heuristic
      total_distance = 0
      seq = 0
      H = 0
      for poss_state in all_possible_states:
        for pos,block in enumerate(poss_state):
          if goal_state[pos] != block:
            # Compute the Total Distance for H
            # Count vertical distance
            desired_pos = goal_state.index(block)
            def _get_row_level(p):
              level = 0
              if p >=0 and p < 3:
                level = 1
              elif p > 2 and p < 6:
                level = 2
              else:
                level = 9
              return level
            pos_row_lvl = _get_row_level(pos)
            des_pos_row_lvl = _get_row_level(desired_pos)
            vertical_distance = abs(des_pos_row_lvl-pos_row_lvl)
            # Count horizontal distance
            horizontal_distance = abs((pos % 3) - (desired_pos % 3))
            # Add to total distance
            total_distance += vertical_distance + horizontal_distance
            # Compute the Sequence Score
            if pos == 4: # if it's the center block, then scores 1 to seq
              seq += 1
            else: # otherwise, scores 2 to seq
              seq += 2
        H = total_distance + 3 * seq
        priority = depth_counter + H

        graph.add_edge(current_state, poss_state)
        stack.put((priority, poss_state, depth_counter + 1))
        if poss_state == goal_state:
          visited.append(poss_state)
          found_goal = True
          break

  return visited
Esempio n. 27
0
        request = requests.get(SPARQL_ENDPOINT,
                               params={
                                   'query': paged(page),
                                   'format': 'json'
                               },
                               headers={'user-agent': USER_AGENT})
        request.raise_for_status()
        results = request.json()['results']['bindings']
        done = len(results) <= PAGE_SIZE
        page += 1

        for binding in results:
            v = ids[binding['v']['value']]
            labels[v] = binding['vLabel']['value']
            w = ids[binding['w']['value']]
            labels[w] = binding['wLabel']['value']

            edges |= {(w, v)}

    graph = Graph(vertices=ids.values())

    for (w, v) in edges:
        graph.add_edge(w, v)

    with open(args.output, 'w') as metis:
        io.write_metis_graph(metis, graph)

    with open(args.dict, 'w') as dictionary:
        for vertex_id, label in labels.items():
            print('{},"{}"'.format(vertex_id, label), file=dictionary)
Esempio n. 28
0
def get_graph(my_orfs):
	G = Graph(directed=True)
	pgap = my_orfs.pstop

	for orf in my_orfs.iter_orfs():
		if(orf.frame > 0):
			source = Node('CDS', 'start', orf.frame, orf.start)
			target = Node('CDS', 'stop', orf.frame, orf.stop)
		else:
			source = Node('CDS', 'stop', orf.frame, orf.stop)
			target = Node('CDS', 'start', orf.frame, orf.start)
		G.add_edge(Edge(source, target, orf.weight))
	#-------------------------------Check for long noncoding regions that would break the path---------#
	bases = [None] * my_orfs.contig_length
	for orfs in my_orfs.iter_in():
		for orf in orfs:
			mi = min(orf.start, orf.stop)
			ma = max(orf.start, orf.stop)
			for n in range(mi, min(ma, my_orfs.contig_length-1)):
				try:
					bases[n] = n
				except:
					sys.stderr.write("error in breaking region"+str(n))
			break
	last = 0
	for base in bases:
		if(base):
			if(base-last > 300):
				for right_node in G.iternodes():
					for left_node in G.iternodes():
						l = left_node.position
						r = right_node.position
						if(last+1 >= l > last-300 and base-1 <= r < base+300):
							if(left_node.frame*right_node.frame > 0):
								if(left_node.type == 'stop' and right_node.type =='start' and left_node.frame > 0):
									score = score_gap(r-l-3, 'same', pgap)
									G.add_edge(Edge(left_node, right_node, score))	
								elif(left_node.type == 'start' and right_node.type =='stop' and left_node.frame < 0):
									score = score_gap(r-l-3, 'same', pgap)
									G.add_edge(Edge(left_node, right_node, score ))	
							else:
								if(left_node.type == 'stop' and right_node.type =='stop' and left_node.frame > 0):
									score = score_gap(r-l-3, 'diff', pgap)
									G.add_edge(Edge(left_node, right_node, score ))	
								elif(left_node.type == 'start' and right_node.type =='start' and left_node.frame < 0):
									score = score_gap(r-l-3, 'diff',pgap)
									G.add_edge(Edge(left_node, right_node, score ))	
			last = base
	#-------------------------------Add in tRNA data---------------------------------------------------#
	
	add_trnas(my_orfs, G)
	
	#-------------------------------Connect the open reading frames to each other----------------------#
	for right_node in G.iternodes():
		r = right_node.position
		if(right_node.gene == 'CDS'):
			r_other = my_orfs.other_end[r]
		else:
			r_other = my_orfs.other_end['t'+str(r)]
		for left_node in G.iternodes():
			l = left_node.position
			if(left_node.gene == 'CDS'):
				l_other = my_orfs.other_end[l]
			else:
				l_other = my_orfs.other_end['t'+str(l)]
			if(0 < r-l < 300):
				if(l in my_orfs and my_orfs.other_end[l] in my_orfs[l]):
					o1 = my_orfs.get_orf(my_orfs.other_end[l], l).pstop
				elif(l in my_orfs):
					o1 = my_orfs.get_orf(l, my_orfs.other_end[l]).pstop
				else:
					o1 = pgap
				if(r in my_orfs and my_orfs.other_end[r] in my_orfs[r]):
					o2 = my_orfs.get_orf(my_orfs.other_end[r], r).pstop
				elif(r in my_orfs):
					o2 = my_orfs.get_orf(r, my_orfs.other_end[r]).pstop
				else:
					o2 = pgap
				pstop = ave([o1, o2])

				#trna
				if(left_node.gene == 'tRNA' or right_node.gene == 'tRNA'):
					if(left_node.frame*right_node.frame > 0 and left_node.type != right_node.type):
						if(left_node.frame > 0 and left_node.type == 'stop') or (left_node.frame < 0 and left_node.type == 'start'):
							if not G.has_edge(Edge(left_node, right_node, 1)):
								score = score_gap(r-l-3, 'same', pgap)
								G.add_edge(Edge(left_node, right_node, score ))	

					elif(left_node.frame*right_node.frame < 0 and left_node.type == right_node.type):
						if(left_node.frame > 0 and left_node.type == 'stop') or (left_node.frame < 0 and left_node.type == 'start'):
							if not G.has_edge(Edge(left_node, right_node, 1)):
								score = score_gap(r-l-3, 'same', pgap)
								G.add_edge(Edge(left_node, right_node, score ))	
				# same directions
				elif(left_node.frame*right_node.frame > 0):
					if(left_node.type == 'stop' and right_node.type =='start'):
						if(left_node.frame > 0):
							score = score_gap(r-l-3, 'same', pgap)
							G.add_edge(Edge(left_node, right_node, score ))	
						else:
							if(left_node.frame != right_node.frame):
								if(r < l_other and r_other < l):
									score = score_overlap(r-l+3, 'same', pstop)
									G.add_edge(Edge(right_node, left_node, score ))	
					if(left_node.type == 'start' and right_node.type =='stop'):
						if(left_node.frame > 0):
							if(left_node.frame != right_node.frame):
								if(r < l_other and r_other < l):
									score = score_overlap(r-l+3, 'same', pstop)
									G.add_edge(Edge(right_node, left_node, score ))	
						else:
							score = score_gap(r-l-3, 'same', pgap)
							G.add_edge(Edge(left_node, right_node, score ))	
				# different directions
				else:
					if(left_node.type == 'stop' and right_node.type =='stop'):
						if(right_node.frame > 0):
							if(r_other+3 < l and r < l_other):
								score = score_overlap(r-l+3, 'diff', pstop)
								G.add_edge(Edge(right_node, left_node, score ))	
						else:
							score = score_gap(r-l-3, 'diff', pgap)
							G.add_edge(Edge(left_node, right_node, score ))	
					if(left_node.type == 'start' and right_node.type =='start'):
						if(right_node.frame > 0 and r-l > 2):
							score = score_gap(r-l-3, 'diff', pgap)
							G.add_edge(Edge(left_node, right_node, score ))	
						elif(right_node.frame < 0):
							#print(r_other, l, r, l_other)
							if(r_other < l and r < l_other):
								score = score_overlap(r-l+3, 'diff', pstop)
								G.add_edge(Edge(right_node, left_node, score ))	
	#-------------------------------Connect open reading frames at both ends to a start and stop-------#
	source = Node('source', 'source', 0, 0)
	target = Node('target', 'target', 0, my_orfs.contig_length+1)
	G.add_node(source)
	G.add_node(target)
	for node in G.iternodes():
		if(node.position <= 2000):
			if( (node.type == 'start' and node.frame > 0) or (node.type =='stop' and node.frame < 0) ):
				score = score_gap(node.position, 'same', pgap)
				G.add_edge(Edge(source, node, score))
		if(my_orfs.contig_length - node.position <= 2000):
			if( (node.type == 'start' and node.frame < 0) or (node.type =='stop' and node.frame > 0) ):
				score = score_gap(my_orfs.contig_length-node.position, 'same', pgap)
				G.add_edge(Edge(node, target, score))

	return G