Example #1
0
 def __call__(self, v):
     """
     @param v: a vector
     @return: the cost of this vector
     """
     n = len(self.z_points)
     assert len(v) == 2*n
     # first split v into its two constituent vectors
     va, vb = v[:n], v[n:]
     # get the augmented list of points
     augmented_points = self.z_points + [va, vb]
     # get the distance matrix
     distance_matrix = get_euclidean_distance_matrix(augmented_points)
     # define the vertices of the graph
     V = range(len(augmented_points))
     # define the weighted edges of the graph
     E = []
     for i in range(len(distance_matrix)):
         for j in range(len(distance_matrix)):
             if i < j:
                 distance = distance_matrix[i][j]
                 weight = distance ** 2
                 edge = (weight, i, j)
                 E.append(edge)
     # find the minimum spanning tree
     T = MST.kruskal(V, E)
     # find the total weight of the minimum spanning tree
     total_weight = sum(weight for weight, a, b in T)
     # track the best found so far
     state = (total_weight, T)
     if self.best is None:
         self.best = state
     self.best = min(self.best, state)
     # return the total weight that we want minimized
     return total_weight
Example #2
0
def main():
    algorithm: str = ""

    if len(argv) < 2:
        print('Not enough arguments!')
        print('Usage: main (-k|-p)')
        return
    elif argv[1] == '-k':
        algorithm = KRUSKAL
    elif argv[1] == "-p":
        algorithm = PRIM
    else:
        print('Unknown algorithm')
        return

    n: int = 0
    try:
        n = int(stdin.readline())
    except ValueError:
        print("Wrong \'n\' input format")
        return

    G: Graph = Graph(n, directed=False)

    m: int = 0
    try:
        m = int(stdin.readline())
    except ValueError:
        print("Wrong \'m\' input format")
        return

    try:
        for _ in range(m):
            line = stdin.readline()
            u, v, w = getEdge(line)
            edge = Edge(u, v, w)
            G.add_edge(edge)
    except ValueError:
        print("Wrong \'u v w\' input format")
        return

    mst: List[Edge] = None
    weight: float = 0
    if algorithm == KRUSKAL:
        mst, weight = MST.kruskal(G)
    elif algorithm == PRIM:
        mst, weight = MST.prim(G, 1)
    else:
        raise Exception('Unsupported algorithm')

    for e in mst:
        fst, snd, w = e.unpack()
        u, v = (fst, snd) if fst < snd else (snd, fst)
        print(u, v, w)

    print(weight)
Example #3
0
def get_mst(query_edges, allpoints):
    """
    Return a sublist of the query edges which forms a minimum spanning tree.
    @param query_edges: point index pairs
    @param allpoints: ordered points as pairs of coordinates
    @return: minimum spanning tree edges
    """
    # get the point indices occurring in at least one query edge
    V = list(sorted(set(itertools.chain.from_iterable(query_edges))))
    # get the weighted edges
    E = []
    for edge in query_edges:
        ax, ay = allpoints[edge[0]]
        bx, by = allpoints[edge[1]]
        weight = math.hypot(bx - ax, by - ay)
        E.append((weight, edge[0], edge[1]))
    # get the minimum spanning tree weighted edges
    E_mst = MST.kruskal(V, E)
    # get the minimum spanning tree edges
    return [(va, vb) for w, va, vb in E_mst]
Example #4
0
def get_mst(query_edges, allpoints):
    """
    Return a sublist of the query edges which forms a minimum spanning tree.
    @param query_edges: point index pairs
    @param allpoints: ordered points as pairs of coordinates
    @return: minimum spanning tree edges
    """
    # get the point indices occurring in at least one query edge
    V = list(sorted(set(itertools.chain.from_iterable(query_edges))))
    # get the weighted edges
    E = []
    for edge in query_edges:
        ax, ay = allpoints[edge[0]]
        bx, by = allpoints[edge[1]]
        weight = math.hypot(bx - ax, by - ay)
        E.append((weight, edge[0], edge[1]))
    # get the minimum spanning tree weighted edges
    E_mst = MST.kruskal(V, E)
    # get the minimum spanning tree edges
    return [(va, vb) for w, va, vb in E_mst]