def __init__(self,
              myView,
              gridWidth=5,
              gridHeight=4,
              hIsZero=True,
              directNeighbors=False):
     self.view = myView
     self.width = gridWidth
     self.height = gridHeight
     self.directNeighbors = directNeighbors  # false=8, true=4
     self.vertexGrid = [[vertex.Vertex(x, y) for y in range(gridHeight)]
                        for x in range(gridWidth)]
     print("Creating vertex grid with height:", gridHeight, "and width:",
           gridWidth, "\n")
     self.startCoordinates = [float('inf'), float('inf')]
     self.goalCoordinates = [float('inf'), float('inf')]
     self.obstacles = set()
     self.startNode = None
     self.goalNode = None
     self.lastNode = None
     self.hIsZero = hIsZero
     self.priorityQueue = pq.PriorityQueue()  #The priority queue U
     self.planReady = False  #True if a plan (= a path) is present
     self.actualPath = []  #Sequence of vertices from start to goal
     self.executer = None  #Planexecuter
Beispiel #2
0
 def process_vert_line(self, vert):
     id = vert[0]
     x = float(vert[1])
     y = float(vert[2])
     pos = vector2.Vector2(x, y)
     self.verts[id] = vertex.Vertex(id, pos)  # store vertex
     self.edges[id] = []  # set up adjacency list
Beispiel #3
0
    def parse(self):
        in_file = open(self.input_file, "r")
        first_couple = map(int, in_file.readline().split())
        node_dictionnary = {}
        self.number_of_verticle = first_couple[0]
        self.number_of_edge = first_couple[1]
        print "Verticle"
        for i in range(0, self.number_of_verticle):
            parsed_line = map(float, in_file.readline().split())
            vertex_id = parsed_line[0]
            vertex_x = parsed_line[1]
            vertex_y = parsed_line[2]
            self.max_x = vertex_x if vertex_x > self.max_x else self.max_x
            self.max_y = vertex_y if vertex_y > self.max_y else self.max_y
            self.min_x = vertex_x if vertex_x < self.min_x else self.min_x
            self.min_y = vertex_y if vertex_y < self.min_y else self.min_y

            vertex_instance = vertex.Vertex(vertex_id, vertex_x, vertex_y)
            node_dictionnary[vertex_id] = vertex_instance
            self.vertex_list.append(vertex_instance)
        print "Edge"
        for i in range(0, self.number_of_edge):
            edge = map(int, in_file.readline().split())
            node_dictionnary[edge[0]].add_child(node_dictionnary[edge[1]])
        return self.vertex_list
Beispiel #4
0
def read_vertices(cursor, build):
    """ Extracts vertices and their positions in the provided genome build from 
        the database and organizes them in the following data structure:
    
        chromosome -> location -> list of vertices (tuples)

        Note: Vertex and gene IDs are integers here
    """

    vertex_dict = {}
    query = """SELECT vertex_ID, chromosome, position, strand, gene_ID FROM
            vertex LEFT JOIN location ON vertex.vertex_id = location.location_ID
                  WHERE genome_build = """ + str_wrap_double(build)
    cursor.execute(query)
    db_vertices = cursor.fetchall()

    for v in db_vertices:
        curr_chrom = v['chromosome']
        # Add new chromosome if necessary
        if curr_chrom not in vertex_dict:
            vertex_dict[curr_chrom] = {}

        # Add location
        pos = int(v['position'])
        new_vertex = Vertex.Vertex(v["vertex_ID"], curr_chrom, pos,
                                   v["strand"], v["gene_ID"])
        if pos in vertex_dict[curr_chrom]:
            vertex_dict[curr_chrom][pos].append(new_vertex)
        else:
            vertex_dict[curr_chrom][pos] = [new_vertex]
    return vertex_dict
def g_1(no_of_vertices):
    V = []
    a_l = []
    for i in range(no_of_vertices + 1):
        a_l.append(vtx.Vertex(i))

    for i in range(no_of_vertices + 1):
        V.append(i)

    g = gp.Graph(no_of_vertices)

    g.add_vertices(V[1:])

    edge_count = 0
    for i in range(1, no_of_vertices):
        g.add_edge(a_l[i], a_l[i + 1], i, i + 1)
        #print i,i+1
        edge_count = edge_count + 1

    g.add_edge(a_l[no_of_vertices], a_l[1], no_of_vertices, 1)
    edge_count = edge_count + 1

    #Sparse graph
    avg_vertex_degree = 8
    no_of_edges = (avg_vertex_degree / 2) * no_of_vertices
    start = time.time()

    def non_adjacent_vertices(index):
        p = []
        if (index != no_of_vertices and index != 1):
            p = V[index + 2:]
        if (index == 1):
            p = V[index + 2:-1]
        return p

    non_adj_V = []
    non_adj_V.append([])

    for i in range(no_of_vertices):
        non_adj_V.append(non_adjacent_vertices(i + 1))

    comb = []
    for i in range(1, len(non_adj_V)):
        for j in range(len(non_adj_V[i])):
            comb.append([i, non_adj_V[i][j]])
    ee = random.sample(comb, no_of_edges - no_of_vertices)

    for i in range(len(ee)):
        g.add_edge(a_l[ee[i][0]], a_l[ee[i][1]], ee[i][0], ee[i][1])
        edge_count = edge_count + 1
    adj_list = g.adjacencyList()
    adj_mat = g.adjacency_matrix

    print 'Sparse graph generated. edge_count =', edge_count
    print 'It took', time.time() - start, 'seconds to generate the graph.'
    ret = [adj_list, adj_mat]
    return ret
Beispiel #6
0
    def add_vertex(self, name, value=None):
        "Add a new vertex to the graph"

        for key in self.__adjacent_list:
            if key.get_name() == name:
                return

        new_vertex = vertex.Vertex(name, value=None)
        self.__adjacent_list[new_vertex] = []
Beispiel #7
0
def init_model(n, bf, bu):
    p_follow = lambda opinion_distance: m.exp(-bf*opinion_distance)
    p_unfollow = lambda trust: m.exp(-bu*trust)
    vertices = []
    a, b = (0.01 - confidence_mean) / confidence_std, (0.99 - confidence_mean) / confidence_std
    for u in range(n):
        o = r.random()
        c = truncnorm.rvs(a, b, loc = confidence_mean, scale = confidence_std)
        vertices.append(v.Vertex(u, o, c, p_follow, p_unfollow, max_follow, trust_stability))
    return vertices
Beispiel #8
0
def make_vertices(spin_matrix):
    rows = len(spin_matrix)
    columns = len(spin_matrix[0])
    vertices = []
    for row in range(rows):
        for column in range(columns):
            current_vertex = vertex.Vertex(spin_matrix[row][column], None,
                                           [row, column])
            vertices.append(current_vertex)
    return vertices
def append_vertex_list(attempt, vertex_list):
    new_vertex = vertex.Vertex(attempt)

    for vertex_instance in vertex_list:
        square_number_try = new_vertex.number + vertex_instance.number

        if math.sqrt(square_number_try) % 1 == 0:
            new_vertex.edge_list.append(vertex_instance)
            vertex_instance.edge_list.append(new_vertex)

    vertex_list.append(new_vertex)
Beispiel #10
0
def parse_matrix_to_vertices(matrix, size):
    vertices = []
    for i in xrange(size):
        v = vertex.Vertex(i + 1)
        vertices.append(v)

    for row in xrange(size):
        v = vertices[row]
        for col in xrange(size):
            if matrix[row][col] == 1:
                v.add_out_vertices(vertices[col])
    return vertices
Beispiel #11
0
    def add_vertex(self, name, value=None):
        """Add a new vertex to the graph

        Args:
            name (str): a name to the new vertex
            value (float, optional): Defaults to None.
                a value to the new vertex
        """

        for key in self.__adjacent_list:
            if key.get_name() == name:
                return

        new_vertex = vertex.Vertex(name, value=None)
        self.__adjacent_list[new_vertex] = []
def g_2(no_of_vertices):
    V = []
    a_l = []

    for i in range(no_of_vertices + 1):
        a_l.append(vtx.Vertex(i))

    for i in range(no_of_vertices + 1):
        V.append(i)

    g = gp.Graph(no_of_vertices)

    g.add_vertices(V[1:])

    edge_count = 0
    for i in range(1, no_of_vertices):
        g.add_edge(a_l[i], a_l[i + 1], i, i + 1)
        #print i,i+1
        edge_count = edge_count + 1

    g.add_edge(a_l[no_of_vertices], a_l[1], no_of_vertices, 1)
    edge_count = edge_count + 1

    #Dense graph
    start = time.time()

    for i in range(no_of_vertices):
        for j in range(i + 2, no_of_vertices):
            probab = random.randint(0, 100)
            if (i == 0 and j == no_of_vertices - 1):
                continue
            if (probab <= 20):
                g.add_edge(a_l[i + 1], a_l[j + 1], i + 1, j + 1)
                edge_count = edge_count + 1
    adj_list = g.adjacencyList()
    adj_mat = g.adjacency_matrix

    print 'Dense graph generated. edge_count =', edge_count
    print 'It took', time.time() - start, 'seconds to generate the graph.'
    ret = [adj_list, adj_mat]
    return ret


#print g_2(10)
Beispiel #13
0
 def buildConnections(self, start):
     #self.connections = []
     for module in start.modules_for_redistribute:
         for iter in range(len(start.redistrib_table[module])):
             if module != iter:
                 if ((start.redistrib_table[module][iter] +
                      start.current_loading[iter]) <=
                         start.max_loading[iter]):
                     new_current_loading = copy.deepcopy(
                         start.current_loading)
                     new_current_loading[iter] += start.redistrib_table[
                         module][iter]
                     new_current_loading[module] -= start.redistrib_table[
                         module][iter]
                     # new_redistrib_table = self.redistrib_table.copy()
                     new_redistrib_table = copy.deepcopy(
                         start.redistrib_table)
                     new_redistrib_table[module][iter] = 0
                     new_modules_for_redistribute = copy.deepcopy(
                         start.modules_for_redistribute)
                     if (new_current_loading[module] <= 0):
                         new_modules_for_redistribute.remove(module)
                     #print(new_redistrib_table, new_modules_for_redistribute, new_current_loading,
                     #     start.max_loading)
                     # input()
                     v = vertex.Vertex(new_redistrib_table,
                                       new_modules_for_redistribute,
                                       new_current_loading,
                                       start.max_loading)
                     tuple_table = tuple(
                         tuple((x, tuple(start.redistrib_table[x]))
                               for x in start.redistrib_table.keys()))
                     tuple_modules = tuple(new_modules_for_redistribute)
                     tuple_loading = tuple(new_current_loading)
                     oldsize = len(self.vertexs)
                     self.vertexs.add(
                         (tuple_table, tuple_modules, tuple_loading))
                     if (oldsize != len(self.vertexs)):
                         self.buildConnections(v)
                         #self.vertexs.add((tuple_table,tuple_modules,tuple_loading))
                         start.addConnection(v)
Beispiel #14
0
 def _load_concepts(self, map_elem):
     """
     create Vertex objects from each concept found in the CMAP except those with labels in the skip list
     :param map_elem: a CXL map element used to find all the concepts in the CMAP
     """
     concepts = []
     for c in map_elem.findall("./cxl:concept-list/cxl:concept",
                               DEFAULT_NS):
         label = c.get("label")
         is_key = self._is_a_key(c)
         if is_key:
             self.keys[c.get("id")] = label
         elif label not in self.skip_concepts:
             concepts.append(c.get("id"))
             attrs = self._get_additional_attributes(c)
             node = V.Vertex(c.get("id"),
                             label.replace('\n', ''),
                             parent_id=c.get("parent-id"),
                             **attrs)
             self.vertexes[c.get("id")] = node
             self._add_codelist_subset(c, node)
     return concepts
Beispiel #15
0
 def addVertex(self, id, cords):
     vert = vertex.Vertex(id, cords)
     self.vertList.append(vert)
Beispiel #16
0
		'''
    print 'The algorithm running times are:'
    print
    print temp

if (option == 0):
    print
    print 'Random graph testing starts'
    print

    a_l = []

    n = 5

    for i in range(n + 1):
        a_l.append(vtx.Vertex(i))

    g = gp.Graph(n)
    g.add_vertices([a_l[1], a_l[2], a_l[3], a_l[4], a_l[5]])

    g.add_edge(a_l[1], a_l[2], 1, 2)
    g.add_edge(a_l[2], a_l[4], 2, 4)
    g.add_edge(a_l[1], a_l[3], 1, 3)
    g.add_edge(a_l[3], a_l[4], 3, 4)
    g.add_edge(a_l[4], a_l[5], 4, 5)

    g.man_adj_mat[0][1] = 35
    g.man_adj_mat[1][3] = 20
    g.man_adj_mat[0][2] = 35
    g.man_adj_mat[2][3] = 25
    g.man_adj_mat[3][4] = 10
Beispiel #17
0
    def find_escape_path(self, callback=lambda: None):
        """ The monkey tries to find the nearest exit and escape!

        Implemented using Djikstras

        Parameters
        ----------
        callback : func, optional
            Places the callback onto the engine event-queue

        """
        engine = self.get_engine()
        self_x, self_y = self.get_position()
        x_dim = 19
        y_dim = 19

        vertex = []
        #Accesses y then x

        for y in range(y_dim):
            new_list = []
            for x in range(x_dim):
                new_list.append(Vertex.Vertex(x, y))
            vertex.append(new_list)

        for y in range(y_dim):
            for x in range(x_dim):
                current = vertex[y][x]
                #NORTH
                if y + 1 < y_dim:
                    if not engine.is_solid((x, y + 1)):
                        current.neighbors.append(vertex[y + 1][x])
                #SOUTH
                if y - 1 >= 0:
                    if not engine.is_solid((x, y - 1)):
                        current.neighbors.append(vertex[y - 1][x])
                #EAST
                if x + 1 < x_dim:
                    if not engine.is_solid((x + 1, y)):
                        current.neighbors.append(vertex[y][x + 1])
                #WEST
                if x - 1 < x_dim:
                    if not engine.is_solid((x - 1, y)):
                        current.neighbors.append(vertex[y][x - 1])

        pq = []
        start = vertex[self_y][self_x]
        start.distance = 0
        pq.append(start)
        end = start
        start.parent = start

        while (len(pq) != 0):
            current = pq[0]
            for v in pq:
                if v < current:
                    current = v
            pq.remove(current)

            if current.x == 0 or current.x == x_dim - 1 or current.y == 0 or current.y == y_dim - 1:
                end = current
                break

            for neighbor in current.neighbors:
                if current.distance + 1 < neighbor.distance and not neighbor.visited:
                    neighbor.distance = current.distance + 1
                    neighbor.parent = current
                    if not neighbor in pq:
                        pq.append(neighbor)

            current.visited = True

        if end != start:
            while end.parent != start:
                end = end.parent
            if start.x + 1 == end.x:
                self.move_east(lambda: self.find_escape_path())
            elif start.x - 1 == end.x:
                self.move_west(lambda: self.find_escape_path())
            elif start.y + 1 == end.y:
                self.move_north(lambda: self.find_escape_path())
            elif start.y - 1 == end.y:
                self.move_south(lambda: self.find_escape_path())

        engine.add_event(callback)
 def add_vertex(self, node):
     self.num_vertices = self.num_vertices + 1  #add 1 to count
     new_vertex = vertex.Vertex(node)  #initialize new vertex
     self.vert_dict[
         node] = new_vertex  #add vertex to dictionary of all verticies
     return new_vertex
Beispiel #19
0
 def add_vertex(self, key):
     """Add a new vertex object to the graph with its respective key."""
     self.vertCount += 1
     addedVertex = vertex.Vertex(key)
     self.vertList[key] = addedVertex
     return addedVertex
Beispiel #20
0
        else:
            #print('Elements:', self.elements)
            return heapq.nsmallest(1, self.elements)[0][0]

    #Remove an element from the queue
    def remove(self, node):
        self.elements = [e for e in self.elements if e[1] != node]
        heapq.heapify(self.elements)

    #Iterator
    def __iter__(self):
        for key, node in self.elements:
            yield node


if __name__ == "__main__":
    pq = PriorityQueue()
    a = vertex.Vertex()
    a.rsh = 0
    b = vertex.Vertex()
    b.rsh = 1
    pq.insert(b, 1)
    pq.insert(a, 0)
    print('Elements:', pq.count())
    print('TopKey:', pq.top_key())
    aPop = pq.pop()
    print(aPop.rsh)
    bPop = pq.pop()
    print(bPop.rsh)
    print(pq.empty())
 def __init__(self, flights):
     self.vertices = []
     number = 0
     for flight in flights:
         number += 1
         self.vertices.append(vertex.Vertex(number, flight[0], flight[1]))
Beispiel #22
0
import graph
import vertex
import sys

v1 = vertex.Vertex('1')
v2 = vertex.Vertex('2')
v3 = vertex.Vertex('3')
v4 = vertex.Vertex('4')
g = graph.Graph([v1, v2, v3, v4], False)

g.add_edge(v1, v2)
#g.add_edge(v2, v1)
g.add_edge(v2, v3)
#g.add_edge(v3, v2)
g.add_edge(v2, v4)
#g.add_edge(v4, v2)

if (sys.argv[1] == '-bfs'):
    g.bfs()
elif (sys.argv[1] == '-dfs'):
    g.dfs()
elif (sys.argv[1] == '-c'):
    g.is_connected()
else:
    print 'Invalid args. Try: -bfs for breadth-first search, -dfs for depth first search, of -c to know if the graph is connected'
Beispiel #23
0
 def test_init(self, vertex):
     label = "a"
     vtx = vertex.Vertex(label)
     assert vtx.id == "a"
     assert any(vtx.neighbors) is False
Beispiel #24
0
 def test_add_neighbor(self):
     label = "a"
     vtx = vertex.Vertex(label)
     vtx.add_neighbor("b", 0)
     assert any(vtx.neighbors) is True
     assert vtx.neighbors == {"b": 0}
Beispiel #25
0
    def __init__(self, num_i_elem, num_j_elem, p, mesh_properties):
        """Constructor for the Quadrilateral Mesh
		
		Will generate a quadrilateral mesh (rectangular) of certain order
		elements. The mesh will initially be "structured" however it will
		be stored in memory as an unstructured mesh. Then, we will work
		with the unstructured mesh to do all solving and adaptation.
		
		Args:
		    num_i_elem (int): Number of elements to initialize along the i direction
		    num_j_elem (int): Number of elements to initialize along the j direction
		    p (int): The order of the basis functions
		    mesh_properties (dict): Dictionary holding the following parameters
		    	"x_range": List with the lower and upper x limits of the mesh (for rectangular case)
		    	"y_range": List with the lower and upper y limits of the mesh (for rectangular case)
		    	"dirichlet_bc_flag": The function for setting the dirichlet bc
		"""

        # ===========================
        #            Setup
        # ===========================

        # x and y limits of the rectangular mesh
        self.x_range = mesh_properties.get("x_range")
        self.y_range = mesh_properties.get("y_range")

        # Order of the mesh
        self.p = p

        # Generate the initial mesh by creating equal dimension elements on a
        # num_i_elem x num_j_elem grid.

        # Spacing of the elements
        dx_elem, dy_elem =  float(self.x_range[1] - self.x_range[0])/num_i_elem, \
             float(self.y_range[1] - self.y_range[0])/num_j_elem

        # ===========================
        #      Vertices Generation
        # ===========================

        # Generate the grid of vertex points
        vertex_points_grid = []

        for i in range(num_i_elem + 1):
            col = []
            for j in range(num_j_elem + 1):

                x_pt, y_pt = i * dx_elem, j * dy_elem
                vertex_pt = vertex.Vertex(x_pt, y_pt)

                col.append(vertex_pt)

            vertex_points_grid.append(col)

        # ===========================
        #   Element/DOF Generation
        # ===========================

        # As we are initially creating a structured mesh, exploit this fact
        # to be able to quickly determine the connectivity between the elements
        element_matrix = []

        for i in range(num_i_elem):
            col = []
            for j in range(num_j_elem):

                # Get the range of the element on the physical domain
                elem_x_range = [
                    i * dx_elem + self.x_range[0],
                    (i + 1) * dx_elem + self.x_range[0]
                ]
                elem_y_range = [
                    j * dy_elem + self.y_range[0],
                    (j + 1) * dy_elem + self.y_range[0]
                ]

                # The matrix of points for the vertices for this element
                vertex_pt_matrix = [[None, None], [None, None]]
                for i_vertex in range(2):
                    for j_vertex in range(2):
                        vertex_pt_matrix[i_vertex][
                            j_vertex] = vertex_points_grid[i +
                                                           i_vertex][j +
                                                                     j_vertex]

                # Create the element with these vertices
                col.append(
                    quad_finite_element.QuadFiniteElement(
                        self.p, elem_x_range, elem_y_range, vertex_pt_matrix,
                        0))

            element_matrix.append(col)

        # Set the neigbors of the elements
        for i in range(num_i_elem):
            for j in range(num_j_elem):

                elem_ij = element_matrix[i][j]

                if i == 0:
                    elem_ij.set_neighbor([element_matrix[i + 1][j]], 1, [3])
                elif i == num_i_elem - 1:
                    elem_ij.set_neighbor([element_matrix[i - 1][j]], 3, [1])
                else:
                    elem_ij.set_neighbor([element_matrix[i + 1][j]], 1, [3])
                    elem_ij.set_neighbor([element_matrix[i - 1][j]], 3, [1])

                if j == 0:
                    elem_ij.set_neighbor([element_matrix[i][j + 1]], 2, [0])
                elif j == num_j_elem - 1:
                    elem_ij.set_neighbor([element_matrix[i][j - 1]], 0, [2])
                else:
                    elem_ij.set_neighbor([element_matrix[i][j + 1]], 2, [0])
                    elem_ij.set_neighbor([element_matrix[i][j - 1]], 0, [2])

        # Now, with all the neighbors set, we place all the elements in a list
        self.element_list = []
        for i in range(num_i_elem):
            for j in range(num_j_elem):
                self.element_list.append(element_matrix[i][j])

        # Set the dofs for the elements. Exploit the structured data for now to
        # create the shared dofs
        node_points_grid = []
        for i in range(num_i_elem + 1):
            col = []

            for j in range(num_j_elem + 1):
                x_pt, y_pt = i * dx_elem, j * dy_elem
                node_pt = node.Node("dof", x_pt, y_pt)
                col.append(node_pt)

            node_points_grid.append(col)

        for i in range(num_i_elem):
            for j in range(num_j_elem):

                elem_ij = element_matrix[i][j]

                i_dof_min = i
                j_dof_min = j

                for i_node_elem in range(2):
                    for j_node_elem in range(2):

                        elem_ij.node_matrix[i_node_elem][j_node_elem] = \
                         node_points_grid[i_dof_min + i_node_elem][j_dof_min + j_node_elem]

        self.set_node_to_element_connectivity()

        # Summary:
        # - At this point in the mesh generation, we now have a list of
        # 	elements. This list makes it such that we can effectively handle
        # 	an unstructured mesh of elements.
        # - All nodes have been generated

        # ===========================
        #      Dirichlet BC Setup
        # ===========================

        # Set the Dirichlet BC on the mesh and its nodes
        self.dirichlet_bc_flag_function = mesh_properties["dirichlet_bc_flag"]
        self.set_dirichlet_boundary_condition()

        # ===========================
        #      Global DOF List
        # ===========================

        # Set the list of dofs for this mesh. This will be used for the system solve
        self.dof_list = []
        self.set_dof_list()

        self.dirichlet_bc_list = []
        self.set_dirichlet_bc_list()

        # Set the list of hanging nodes for this mesh. Will be needed during h-refinement
        self.hanging_node_list = []
        self.set_hanging_node_list()
def init_model(n):
    vertices = []
    for u in range(n):
        vertices.append(v.Vertex(u, r.random(), r.random(), p_follow, p_unfollow, max_follow))
    return vertices
Beispiel #27
0
def algo3(g, s, t):
    list = g[0]
    mat = g[1]
    no_of_vertices = len(list)
    edgesHeap = hp.maxHeap()
    for i in range(len(list)):
        for j in range(len(list[i])):

            u = i + 1
            v = list[i][j]
            wt = mat[i][list[i][j] - 1]
            edgesHeap.Insert([u, v], wt)
    ret = edgesHeap.HeapSort()
    sorted_weights = ret[0]
    sorted_edges = ret[1]

    #print 'HeapSort of edges is done'

    b_l = []
    V_1 = []

    for i in range(no_of_vertices + 1):
        b_l.append(vtx.Vertex(i))

    for i in range(no_of_vertices + 1):
        V_1.append(i)

    MST = gp.Graph(no_of_vertices)

    MST.add_vertices(V_1[1:])
    p = []
    rank = []
    dad = np.zeros(no_of_vertices + 1)
    dad1 = np.zeros(no_of_vertices + 1)

    for i in range(no_of_vertices + 1):
        p.append(0)
        rank.append(0)

    #print 'Initialization is done'

    def Find(v):
        w = v
        while (p[w] != 0):
            w = p[w]
        return w

    def Union(r1, r2):

        if (rank[r1] < rank[r2]):
            p[r1] = r2
        if (rank[r1] > rank[r2]):
            p[r2] = r1
        if (rank[r1] == rank[r2]):
            p[r1] = r2
            rank[r2] = rank[r2] + 1

    flag = []

    for i in range(no_of_vertices + 1):
        flag.append(0)
    flag[0] = -1

    #print flag
    while (len(sorted_edges) != 0
           and flag.count(1) != no_of_vertices):  #Or all vertices are joined

        #print flag
        e = sorted_edges.pop(0)

        u = e[0]
        v = e[1]

        r_u = Find(u)
        r_v = Find(v)

        if (r_u != r_v):

            dad[v] = u
            dad1[u] = v
            MST.add_edge_mst(b_l[u], b_l[v])
            flag[u] = flag[v] = 1

            Union(r_u, r_v)

    #print 'MST generated'

    mst_adj_list = (MST.adjacencyList())

    mst_adj_list.insert(0, [])

    curr = s
    queue = []
    status = np.zeros(no_of_vertices + 1)  #un-visited

    status[s] = 1  #in-tree
    queue.append(s)

    path = []
    dad = np.zeros(no_of_vertices)

    #print 'BFS started'

    while (curr != t):

        curr = queue.pop(0)
        path.append(curr)

        for i in range(len(mst_adj_list[curr])):
            nxt = mst_adj_list[curr][i]
            if (status[nxt] == 0):
                queue.append(nxt)
                status[nxt] = 1
                dad[nxt - 1] = curr - 1
    #print 'parent array generated for s to t path'
    max_bw_path = print_path(dad, mat, s, t)
    print
    print 'Using Kruskals algo'
    print 'max bw path in g from', s, 'to', t, 'is', ':', max_bw_path[0]
    print 'max bw = ', max_bw_path[1]
    print
    def refine_element(self):
        """Refine the given element. Do this by splitting it
		into 4 elements. 

		All refinement will be done locally using the element and its
		neighbors (that is all). This way, we will be able to do robust
		refinment. This means, during the refinement, there should be 
		no interaction with any other elements.
		"""

        # TODO:
        # First, check refinement level of other elements

        # =============================
        #     Split Parent Element
        # =============================

        # Split this element into 4 child elements. Store it in the children
        # data structure. Make each child have equal dimensions.

        self.children = [[None, None], [None, None]]

        child_dx = 0.5 * self.delta_x
        child_dy = 0.5 * self.delta_y

        for i in range(2):
            for j in range(2):

                # x and y range for this child
                child_x_range = [
                    self.x_range[0] + i * child_dx,
                    self.x_range[0] + (i + 1) * child_dx
                ]
                child_y_range = [
                    self.y_range[0] + j * child_dy,
                    self.y_range[0] + (j + 1) * child_dy
                ]

                # Create the matrix of vertex elements
                vertex_pt_matrix = [[None, None], [None, None]]
                for i_vertex in range(2):
                    for j_vertex in range(2):
                        vertex_pt_matrix[i_vertex][j_vertex] = vertex.Vertex(
                            child_x_range[i_vertex], child_y_range[j_vertex])

                # Create the refined element
                h_refined_element = QuadFiniteElement(
                    self.p, child_x_range, child_y_range, vertex_pt_matrix,
                    self.refinement_level + 1)

                self.children[i][j] = h_refined_element

        # =============================
        #      Set the neighbors
        # =============================

        # Set the neighbor references. Set the reference to the neighbors for
        # each child element as well as all outer neighbors (the neighbors to
        # this parent element)

        # NOTE: We do not need to check neighbor refinement levels here. This is
        # because we will, before refining this element, make sure that the mesh
        # follows the one element rule. So, if an element has only one neighbor,
        # that neighbor is of the same size as this parent element.

        # NOTE: When setting neighbors, we will set the neighboring faces for both
        # elements involved.

        # Set the neighboring faces between the children

        for i in range(2):
            for j in range(2):

                child_ij = self.children[i][j]

                if i + 1 <= 1:
                    # Set the right face (face = 1)
                    child_ij.set_neighbor([self.children[i + 1][j]], 1, [3])

                if i - 1 >= 0:
                    # Set the left face (face = 3)
                    child_ij.set_neighbor([self.children[i - 1][j]], 3, [1])

                if j + 1 <= 1:
                    # Set the top face (face = 2)
                    child_ij.set_neighbor([self.children[i][j + 1]], 2, [0])

                if j - 1 >= 0:
                    # Set the bottom face (face = 0)
                    child_ij.set_neighbor([self.children[i][j - 1]], 0, [2])

        # Set the neighboring faces to outer elements. These are the elements that
        # neighbor/touch the parent element that is being split

        for face_index in range(4):

            # Get the child elements that are on this face. The ordering of the
            # faces in each list is counterclockwise around the element.
            face_child_elements = []

            # Get the indeces for what face on the child elements is touching
            # this face. Will be the same as the parent element
            face_child_elements_face_indeces = [face_index, face_index]

            if face_index == 0:
                face_child_elements = [
                    self.children[0][0], self.children[1][0]
                ]
            elif face_index == 1:
                face_child_elements = [
                    self.children[1][0], self.children[1][1]
                ]
            elif face_index == 2:
                face_child_elements = [
                    self.children[1][1], self.children[0][1]
                ]
            elif face_index == 3:
                face_child_elements = [
                    self.children[0][1], self.children[0][0]
                ]

            # Get the index of the face of the neighbors that touches this face on this element
            neighbor_elements = self.neighbors[face_index]
            neighbors_face_index = self.neighbors_face_index[face_index]

            if neighbor_elements is None:
                # The neighbor is a boundary (so do nothing)
                pass

            elif len(neighbor_elements) == 1:
                # Only a single outer neighbor on this face. Set the reference to the face child
                # neighbors.
                # - Note: We flip the order of the elements when setting the neighbor. This is done
                # 	to stay consistent with the ordering of multiple neighbors for elements.
                neigh_elem = neighbor_elements[0]
                neigh_elem_face_index = neighbors_face_index[0]
                neigh_elem.set_neighbor(
                    [face_child_elements[1], face_child_elements[0]],
                    neigh_elem_face_index, [
                        face_child_elements_face_indeces[1],
                        face_child_elements_face_indeces[0]
                    ])

                # Set neighbor references for the children
                for face_child in face_child_elements:
                    face_child.set_neighbor([neigh_elem], face_index,
                                            [neigh_elem_face_index])

            else:
                # 2 neighbors on this face
                raise ValueError("Unsupported right now")

        # =============================
        #       Set the nodes
        # =============================

        # Set nodes for the refined elements. With the neighbors set,
        # go through each element and set the nodes (regular and hanging)
        # based on the number of neighbors. Only generate nodes that are not
        # already existing. Then, set the dof to element connecitivity.

        # 1) Get the nodes that form the corner of the element. We will take these
        # 	from the parent element. Allocate the correct node to each child
        #	element.

        for i in range(2):
            for j in range(2):
                self.children[i][j].node_matrix[i][j] = self.node_matrix[i][j]

        # 2) Create the node at the middle of the parent element. This will be
        # 	shared by all child elements. This will be a dof for the system.

        mid_node_x, mid_node_y = self.x_range[0] + child_dx, self.y_range[
            0] + child_dy
        mid_node = node.Node("dof", mid_node_x, mid_node_y)

        self.children[0][0].node_matrix[1][1] = mid_node  # Bottom left element
        self.children[1][0].node_matrix[0][
            1] = mid_node  # Bottom right element
        self.children[1][1].node_matrix[0][0] = mid_node  # Top right element
        self.children[0][1].node_matrix[1][0] = mid_node  # Top left element

        # 3) Create or get the nodes at the middle outer edges of the split element.
        # 	There are two cases here:
        # 	- Case 1: A single outer element is on the boundary. In this case,
        # 		the middle node on the face of the parent element that has been split
        #		will need to be generated and will be a hanging node.
        #	- Case 2: Two outer elements are on the boundary. In this case, the
        #		middle node on the face of the parent element is already existing
        #		as it is a hanging node. Convert this hanging node into a dof and
        #		store its reference for each new child element.
        #	- Case 3: The outer boundary has no neighboring element and is therefore
        #		on a boundary of the geometry. In this case, generate the middle node.
        #		Then, check if this node is on a dirichlet BC. If it is, set it to be
        #		a dirichlet BC node. If it is on a Neumann BC, set it to be a hanging
        #		node.

        for face_index in range(4):

            # Get the child elements on this given face

            face_outer_neighbors = self.neighbors[face_index]

            if face_outer_neighbors is None:
                # Case 3:

                if face_index == 0:

                    hanging_node_x, hanging_node_y = self.children[0][0].vertex_matrix[1][0].x, \
                     self.children[0][0].vertex_matrix[1][0].y
                    hanging_node = node.Node("hanging", hanging_node_x,
                                             hanging_node_y)

                    constraint_nodes = [
                        self.children[0][0].node_matrix[0][0],
                        self.children[1][0].node_matrix[1][0]
                    ]

                    hanging_node.set_hanging_nodes_constraint_nodes(
                        constraint_nodes)

                    # Allocate the hanging node
                    self.children[0][0].node_matrix[1][0] = hanging_node
                    self.children[1][0].node_matrix[0][0] = hanging_node

                elif face_index == 1:

                    hanging_node_x, hanging_node_y = self.children[1][0].vertex_matrix[1][1].x, \
                     self.children[1][0].vertex_matrix[1][1].y
                    hanging_node = node.Node("hanging", hanging_node_x,
                                             hanging_node_y)

                    constraint_nodes = [
                        self.children[1][0].node_matrix[1][0],
                        self.children[1][1].node_matrix[1][1]
                    ]

                    hanging_node.set_hanging_nodes_constraint_nodes(
                        constraint_nodes)

                    # Allocate the hanging node
                    self.children[1][0].node_matrix[1][1] = hanging_node
                    self.children[1][1].node_matrix[1][0] = hanging_node

                elif face_index == 2:

                    hanging_node_x, hanging_node_y = self.children[1][1].vertex_matrix[0][1].x, \
                     self.children[1][1].vertex_matrix[0][1].y
                    hanging_node = node.Node("hanging", hanging_node_x,
                                             hanging_node_y)

                    constraint_nodes = [
                        self.children[1][1].node_matrix[1][1],
                        self.children[0][1].node_matrix[0][1]
                    ]

                    hanging_node.set_hanging_nodes_constraint_nodes(
                        constraint_nodes)

                    # Allocate the hanging node
                    self.children[1][1].node_matrix[0][1] = hanging_node
                    self.children[0][1].node_matrix[1][1] = hanging_node

                elif face_index == 3:

                    hanging_node_x, hanging_node_y = self.children[0][1].vertex_matrix[0][0].x, \
                     self.children[0][1].vertex_matrix[0][0].y
                    hanging_node = node.Node("hanging", hanging_node_x,
                                             hanging_node_y)

                    constraint_nodes = [
                        self.children[0][1].node_matrix[0][1],
                        self.children[0][0].node_matrix[0][0]
                    ]

                    hanging_node.set_hanging_nodes_constraint_nodes(
                        constraint_nodes)

                    # Allocate the hanging node
                    self.children[0][1].node_matrix[0][0] = hanging_node
                    self.children[0][0].node_matrix[0][1] = hanging_node

            elif len(face_outer_neighbors) == 1:
                # Case 1:

                if face_index == 0:

                    hanging_node_x, hanging_node_y = self.children[0][0].vertex_matrix[1][0].x, \
                     self.children[0][0].vertex_matrix[1][0].y
                    hanging_node = node.Node("hanging", hanging_node_x,
                                             hanging_node_y)

                    constraint_nodes = [
                        self.children[0][0].node_matrix[0][0],
                        self.children[1][0].node_matrix[1][0]
                    ]

                    hanging_node.set_hanging_nodes_constraint_nodes(
                        constraint_nodes)

                    # Allocate the hanging node
                    self.children[0][0].node_matrix[1][0] = hanging_node
                    self.children[1][0].node_matrix[0][0] = hanging_node

                elif face_index == 1:

                    hanging_node_x, hanging_node_y = self.children[1][0].vertex_matrix[1][1].x, \
                     self.children[1][0].vertex_matrix[1][1].y
                    hanging_node = node.Node("hanging", hanging_node_x,
                                             hanging_node_y)

                    constraint_nodes = [
                        self.children[1][0].node_matrix[1][0],
                        self.children[1][1].node_matrix[1][1]
                    ]

                    hanging_node.set_hanging_nodes_constraint_nodes(
                        constraint_nodes)

                    # Allocate the hanging node
                    self.children[1][0].node_matrix[1][1] = hanging_node
                    self.children[1][1].node_matrix[1][0] = hanging_node

                elif face_index == 2:

                    hanging_node_x, hanging_node_y = self.children[1][1].vertex_matrix[0][1].x, \
                     self.children[1][1].vertex_matrix[0][1].y
                    hanging_node = node.Node("hanging", hanging_node_x,
                                             hanging_node_y)

                    constraint_nodes = [
                        self.children[1][1].node_matrix[1][1],
                        self.children[0][1].node_matrix[0][1]
                    ]

                    hanging_node.set_hanging_nodes_constraint_nodes(
                        constraint_nodes)

                    # Allocate the hanging node
                    self.children[1][1].node_matrix[0][1] = hanging_node
                    self.children[0][1].node_matrix[1][1] = hanging_node

                elif face_index == 3:

                    hanging_node_x, hanging_node_y = self.children[0][1].vertex_matrix[0][0].x, \
                     self.children[0][1].vertex_matrix[0][0].y
                    hanging_node = node.Node("hanging", hanging_node_x,
                                             hanging_node_y)

                    constraint_nodes = [
                        self.children[0][1].node_matrix[0][1],
                        self.children[0][0].node_matrix[0][0]
                    ]

                    hanging_node.set_hanging_nodes_constraint_nodes(
                        constraint_nodes)

                    # Allocate the hanging node
                    self.children[0][1].node_matrix[0][0] = hanging_node
                    self.children[0][0].node_matrix[0][1] = hanging_node

            elif len(face_outer_neighbors) == 2:
                # Case 2:

                raise ValueError("To Implement Still")