Пример #1
0
    def test_threshold(self):
        p = Prim(TestPrimInitMethod.df,
                 lambda x: x["x1"] * x["x2"] + 0.3 * x["x3"] > 0.5)
        box = p.find_box()
        output = str(box)

        self.assertEqual(output, TestPrimInitMethod.expected_output)
Пример #2
0
 def test_threshold(self):
     p = Prim(TestPrimInitMethod.df,
              lambda x : x["x1"]*x["x2"] + 0.3*x["x3"] > 0.5)
     box = p.find_box()
     output = str(box)
     
     self.assertEqual(output, TestPrimInitMethod.expected_output)
Пример #3
0
 def test_init_numpy(self):
     df = TestPrimInitMethod.df.to_records(index=False)
     response = TestPrimInitMethod.response.values
     p = Prim(df, response, threshold=0.5, threshold_type=">")
     box = p.find_box()
     output = str(box)
     
     self.assertEqual(output, TestPrimInitMethod.expected_output)
Пример #4
0
    def setUpClass(cls):
        cls.df = pd.DataFrame(np.random.rand(1000, 3),
                              columns=["x1", "x2", "x3"])
        cls.response = cls.df["x1"] * cls.df["x2"] + 0.3 * cls.df["x3"]

        p = Prim(cls.df, cls.response, threshold=0.5, threshold_type=">")
        box = p.find_box()
        cls.expected_output = str(box)
Пример #5
0
    def test_init_numpy(self):
        df = TestPrimInitMethod.df.to_records(index=False)
        response = TestPrimInitMethod.response.values
        p = Prim(df, response, threshold=0.5, threshold_type=">")
        box = p.find_box()
        output = str(box)

        self.assertEqual(output, TestPrimInitMethod.expected_output)
Пример #6
0
 def setUpClass(cls):
     cls.df = pd.DataFrame(np.random.rand(1000, 3),
                           columns=["x1", "x2", "x3"])
     cls.response = cls.df["x1"]*cls.df["x2"] + 0.3*cls.df["x3"]
     
     p = Prim(cls.df, cls.response, threshold=0.5, threshold_type=">")
     box = p.find_box()
     cls.expected_output = str(box)
Пример #7
0
 def test_function(self):
     p = Prim(TestPrimInitMethod.df,
              lambda x : x["x1"]*x["x2"] + 0.3*x["x3"],
              threshold=0.5,
              threshold_type=">")
     box = p.find_box()
     output = str(box)
     
     self.assertEqual(output, TestPrimInitMethod.expected_output)
Пример #8
0
 def test_string(self):
     df = copy.deepcopy(TestPrimInitMethod.df)
     df["y"] = df["x1"]*df["x2"] + 0.3*df["x3"]
     
     p = Prim(df, "y", threshold=0.5, threshold_type=">")
     box = p.find_box()
     output = str(box)
     
     self.assertEqual(output, TestPrimInitMethod.expected_output)
Пример #9
0
    def test_string(self):
        df = copy.deepcopy(TestPrimInitMethod.df)
        df["y"] = df["x1"] * df["x2"] + 0.3 * df["x3"]

        p = Prim(df, "y", threshold=0.5, threshold_type=">")
        box = p.find_box()
        output = str(box)

        self.assertEqual(output, TestPrimInitMethod.expected_output)
Пример #10
0
    def test_function(self):
        p = Prim(TestPrimInitMethod.df,
                 lambda x: x["x1"] * x["x2"] + 0.3 * x["x3"],
                 threshold=0.5,
                 threshold_type=">")
        box = p.find_box()
        output = str(box)

        self.assertEqual(output, TestPrimInitMethod.expected_output)
Пример #11
0
def get_output_shared(config1):
    """Generate output in desired format given a configuration.
    
    Take into account that grid lines can be shared.
    """

    prim = Prim(config1.batteries)
    output = []
    for j, mst in enumerate(prim.mst_container):
        battery = config1.batteries[j]
        battery_info = {
            "locatie": f"{battery.x},{battery.y}",
            "capaciteit": f"{battery.real_capacity}",
            "huizen": []
        }
        for branch in mst.keys():
            x, y = branch.path
            kabels = []
            for i in range(len(x)):
                coordinate = f"({x[i]},{y[i]})"
                kabels.append(coordinate)
            kabels.reverse()
            for house in config1.district:
                if (house.x, house.y) == (branch.end_x, branch.end_y):
                    output = house.power
                    break
            house_info = {
                "locatie": f"{branch.end_x},{branch.end_y}",
                "output": f"{output}",
                "kabels": kabels
            }
            battery_info["huizen"].append(house_info)
        output.append(battery_info)

    return output
Пример #12
0
    def get_costs(self):
        """
        Get costs for current configuration depending
        on grid sharing possibilities.
        """

        costs = 0
        if self.share_grid == False:

            for battery in self.batteries:
                for house in battery.houses:
                    costs += (abs(house.x - battery.x) +
                              abs(house.y - battery.y)) * 9

                costs += battery.costs

            self.all_costs.append(costs)

        else:
            prim = Prim(self.batteries)

            for battery in self.batteries:
                costs += battery.costs

            self.all_costs.append(prim.costs + costs)
Пример #13
0
    def test_categorical_paste(self):
        dtype = [('a', np.float), ('b', np.object)]
        x = np.empty((10, ), dtype=dtype)

        x['a'] = np.random.rand(10, )
        x['b'] = ['a', 'b', 'a', 'b', 'a', 'a', 'b', 'a', 'b', 'a']
        y = np.random.randint(0, 2, (10, ))
        y = y.astype(np.int)

        prim_obj = Prim(x, y, threshold=0.8)
        box_lims = np.array([(0, set(['a'])), (1, set(['a']))], dtype=dtype)

        yi = np.where(x['b'] == 'a')

        box = PrimBox(prim_obj, box_lims, yi)

        u = 'b'
        pastes = categorical_paste(prim_obj, box, u)

        self.assertEquals(len(pastes), 1)

        for paste in pastes:
            indices, box_lims = paste
            self.assertEquals(indices.shape[0], 10)
            self.assertEqual(box_lims[u][0], set(['a', 'b']))
Пример #14
0
    def test_drop_restriction(self):
        x = np.array([(0, 1, 2), (2, 5, 6), (3, 2, 1)],
                     dtype=[('a', np.float), ('b', np.float), ('c', np.float)])
        y = np.array([1, 1, 0])

        prim_obj = Prim(x, y, threshold=0.8)
        box = PrimBox(prim_obj, prim_obj._box_init, prim_obj.yi)

        new_box_lim = np.array([(0, 1, 1), (2, 2, 6)],
                               dtype=[('a', np.float), ('b', np.float),
                                      ('c', np.float)])
        indices = np.array([0, 1], dtype=np.int)
        box.update(new_box_lim, indices)

        box.drop_restriction('b')

        correct_box_lims = np.array([(0, 1, 1), (2, 5, 6)],
                                    dtype=[('a', np.float), ('b', np.float),
                                           ('c', np.float)])

        box_lims = box._box_lims[-1]
        names = recfunctions.get_names(correct_box_lims.dtype)

        for entry in names:
            lim_correct = correct_box_lims[entry]
            lim_box = box_lims[entry]
            for i in range(len(lim_correct)):
                self.assertEqual(lim_correct[i], lim_box[i])

        self.assertEqual(box.peeling_trajectory['mean'][2], 1)
        self.assertEqual(box.peeling_trajectory['coverage'][2], 1)
        self.assertEqual(box.peeling_trajectory['density'][2], 1)
        self.assertEqual(box.peeling_trajectory['res dim'][2], 1)
        self.assertEqual(box.peeling_trajectory['mass'][2], 2 / 3)
Пример #15
0
def test():
    # str2d = """
    # 0 1 3 0 0 2
    # 1 0 5 1 0 0
    # 3 5 0 2 1 0
    # 0 1 2 0 4 0
    # 0 0 1 4 0 5
    # 2 0 0 0 5 0
    # """
    str2d = """
0 8 6 1 4 0 8 5 1 2 7 6 1 4 4 3 3 2 1 2
8 0 6 5 1 5 8 3 2 0 1 5 2 0 1 1 2 7 5 3
6 6 0 4 8 1 8 4 7 8 8 2 4 0 3 6 4 7 8 0
1 5 4 0 3 5 0 8 0 3 2 2 1 2 6 0 7 0 6 3
4 1 8 3 0 0 4 2 0 4 1 0 5 4 8 5 0 1 4 2
0 5 1 5 0 0 4 0 7 8 0 0 4 6 5 1 1 3 3 0
8 8 8 0 4 4 0 3 8 1 2 0 1 6 6 3 5 7 1 7
5 3 4 8 2 0 3 0 8 7 5 6 5 5 3 7 1 6 0 6
1 2 7 0 0 7 8 8 0 4 2 6 5 1 4 6 0 3 5 8
2 0 8 3 4 8 1 7 4 0 6 2 6 2 3 8 0 3 6 7
7 1 8 2 1 0 2 5 2 6 0 1 8 1 7 0 3 3 4 3
6 5 2 2 0 0 0 6 6 2 1 0 2 4 2 4 8 4 5 3
1 2 4 1 5 4 1 5 5 6 8 2 0 8 5 1 7 1 4 0
4 0 0 2 4 6 6 5 1 2 1 4 8 0 6 7 4 6 6 0
4 1 3 6 8 5 6 3 4 3 7 2 5 6 0 6 4 8 4 6
3 1 6 0 5 1 3 7 6 8 0 4 1 7 6 0 4 5 2 8
3 2 4 7 0 1 5 1 0 0 3 8 7 4 4 4 0 6 4 1
2 7 7 0 1 3 7 6 3 3 3 4 1 6 8 5 6 0 5 3
1 5 8 6 4 3 1 0 5 6 4 5 4 6 4 2 4 5 0 4
2 3 0 3 2 0 7 6 8 7 3 3 0 0 6 8 1 3 4 0
"""
    # str2d = """
    # 0 2 0 6 0
    # 2 0 3 8 5
    # 0 3 0 0 7
    # 6 8 0 0 9
    # 0 5 7 9 0
    # """
    # ==== prepare data ====
    rows = Utils.array2dFromStr(str2d)
    matrix = Matrix(rows)
    # print matrix.toString()
    # print matrix.hasEdge(1, 5)
    # print matrix.getWeight(3, 4)
    Prim.sequential(matrix)
Пример #16
0
    def test_init(self):
        x = np.array([(0, 1, 2), (2, 5, 6), (3, 2, 1)],
                     dtype=[('a', np.float), ('b', np.float), ('c', np.float)])
        y = np.array([0, 1, 2])

        prim_obj = Prim(x, y, threshold=0.8)
        box = PrimBox(prim_obj, prim_obj._box_init, prim_obj.yi)

        self.assertTrue(box.peeling_trajectory.shape == (1, 5))
Пример #17
0
    def make_plot(self, results_directory, optimization):
        """
        Make plot based on given configuration and whether 
        or not grid lines can be shared.
        """

        figure_name = f"{self.type}_{self.district_nr}_{optimization}"
        colors = ['yellowgreen',
                  'yellow', 'violet',
                  'tomato', 'turquoise',
                  'sienna', 'blue', 'pink',
                  'teal', 'tan']

        plt.figure()
        for battery in self.batteries:
            plt.plot(battery.x, battery.y, 'H', color=colors[battery.id - 1])
            for house in battery.houses:
                plt.plot(house.x, house.y, 'k*')

        costs = 0
        if self.share_grid == False:
            self.get_routes()
            i = 0
            for battery in self.batteries:
                for x, y in self.routes[battery]:
                    plt.plot(x, y, colors[i])
                i += 1

            for battery in self.batteries:
                for house in battery.houses:
                    costs += (abs(house.x - battery.x) +
                              abs(house.y - battery.y)) * 9
                costs += battery.costs
            plt.title(f"Total costs:{costs}")

        else:
            i = 0
            prim = Prim(self.batteries)

            for battery in self.batteries:
                costs += battery.costs

            for mst in prim.mst_container:
                for branch in mst.keys():
                    plt.plot(branch.path[0], branch.path[1], colors[i])
                i += 1
            plt.title(f"Total costs: {prim.costs + costs}")

        plt.xlim(-2, 55)
        plt.ylim(-2, 55)
        plt.savefig(results_directory + figure_name)
        plt.show()
Пример #18
0
def _prim():
    # node: [(adjacent_node, cost)]
    graph = {
        0: [(1,1), (2,2), (3,1), (4,1), (5,2), (6,1)],
        1: [(0,1), (2,2), (6,2)],
        2: [(0,2), (1,2), (3,1)],
        3: [(0,1), (2,1), (4,2)],
        4: [(0,1), (3,2), (5,2)],
        5: [(0,2), (4,2), (6,1)],
        6: [(0,1), (2,2), (5,1)]
    }

    g1 = Prim(0, graph)
    cost = g1.prim()
    print(cost)
Пример #19
0
def Otree(graph_ini, position=0, choice='Prim'):
    """Retourne un 1-tree de cout minimal."""
    # les paremetres sont initialise
    cost_1 = float('inf')  # cout modifie 1
    cost_2 = float('inf')  # cout modifie 1
    real_1 = float('inf')  # cout reel de l arete 1
    real_2 = float('inf')  # cout reel de l arete 2
    key_1 = None  # autre noeud de l arete 1
    key_2 = None  # autre noeud de l arete 2
    G = deepcopy(graph_ini)  # une copie du graphe original est faite
    mat = G.mat_adj
    # Les deux arretes de poids modifies minimales incidentes au noeud choisi
    # seront sauvegardes pour le 1-tree
    for node in G.get_neighbors(G.nodes[position]):
        if cost_1 > mat[G.nodes[position]][node].get_vcost():  # v
            cost_2 = deepcopy(cost_1)
            real_2 = deepcopy(real_1)
            key_2 = node
            cost_1 = deepcopy(mat[G.nodes[position]][node].get_vcost())  # v
            real_1 = deepcopy(mat[G.nodes[position]][node].cost)
            key_1, key_2 = key_2, key_1
        elif cost_2 > mat[G.nodes[position]][node].get_vcost():  # v
            cost_2 = deepcopy(mat[G.nodes[position]][node].get_vcost())  # v
            real_2 = deepcopy(mat[G.nodes[position]][node].cost)
            key_2 = node
    # le noeud choisi est efface
    G.delete_node(G.nodes[position])
    new_node = deepcopy(graph_ini.nodes[position])
    # un arbre de recouvrement est fait selon le choix de lutilisateur
    if str.lower(choice) == 'kruskal':
        One_tree = Kruskal(G)
    elif str.lower(choice) == 'prim':
        if position >= len(G.nodes):
            position = len(G.nodes) - 1
        One_tree = Prim(G, G.nodes[position])
    # le noeud efface est rajoute au 1-tree
    One_tree[1].add_node(new_node)
    node_OT = One_tree[1].nodes
    for node in node_OT:
        if node.get_id() == key_1.get_id():
            key_1 = node
        elif node.get_id() == key_2.get_id():
            key_2 = node
    # les deux aretes minimales sont rajoute au 1-tree pour finir sa creation
    One_tree[1].add_edge(Edge(start=new_node, end=key_1, cost=real_1))
    One_tree[1].add_edge(Edge(start=new_node, end=key_2, cost=real_2))
    # le cout modifier ainsi que le graphe sont retourne
    return One_tree[1], One_tree[1].get_vcost()
Пример #20
0
    def test_select(self):
        x = np.array([(0, 1, 2), (2, 5, 6), (3, 2, 1)],
                     dtype=[('a', np.float), ('b', np.float), ('c', np.float)])
        y = np.array([1, 1, 0])

        prim_obj = Prim(x, y, threshold=0.8)
        box = PrimBox(prim_obj, prim_obj._box_init, prim_obj.yi)

        new_box_lim = np.array([(0, 1, 1), (2, 5, 6)],
                               dtype=[('a', np.float), ('b', np.float),
                                      ('c', np.float)])
        indices = np.array([0, 1], dtype=np.int)
        box.update(new_box_lim, indices)

        box.select(0)
        self.assertTrue(np.all(box.yi == prim_obj.yi))
Пример #21
0
    def test_update(self):
        x = np.array([(0, 1, 2), (2, 5, 6), (3, 2, 1)],
                     dtype=[('a', np.float), ('b', np.float), ('c', np.float)])
        y = np.array([1, 1, 0])

        prim_obj = Prim(x, y, threshold=0.8)
        box = PrimBox(prim_obj, prim_obj._box_init, prim_obj.yi)

        new_box_lim = np.array([(0, 1, 1), (2, 5, 6)],
                               dtype=[('a', np.float), ('b', np.float),
                                      ('c', np.float)])
        indices = np.array([0, 1], dtype=np.int)
        box.update(new_box_lim, indices)

        self.assertEqual(box.peeling_trajectory['mean'][1], 1)
        self.assertEqual(box.peeling_trajectory['coverage'][1], 1)
        self.assertEqual(box.peeling_trajectory['density'][1], 1)
        self.assertEqual(box.peeling_trajectory['res dim'][1], 1)
        self.assertEqual(box.peeling_trajectory['mass'][1], 2 / 3)
Пример #22
0
def TestPrim():
    graph_dict = {
        "a": {
            "a": 0,
            "b": 3,
            "f": 5,
            "e": 2
        },
        "b": {
            "b": 0,
            "c": 1,
            "f": 4,
            "a": 3
        },
        "c": {
            "c": 0,
            "b": 1,
            "f": 4,
            "d": 6
        },
        "d": {
            "d": 0,
            "c": 6,
            "f": 5,
            "e": 8
        },
        "e": {
            "e": 0,
            "a": 6,
            "f": 2,
            "d": 8
        },
        "f": {
            "f": 0,
            "a": 5,
            "b": 4,
            "c": 4,
            "d": 5,
            "e": 2
        },
    }
    path = Prim(graph_dict, "a")
    print(path)
Пример #23
0
    def test_categorical_peel(self):
        dtype = [('a', np.float), ('b', np.object)]
        x = np.empty((10, ), dtype=dtype)

        x['a'] = np.random.rand(10, )
        x['b'] = ['a', 'b', 'a', 'b', 'a', 'a', 'b', 'a', 'b', 'a']
        y = np.random.randint(0, 2, (10, ))
        y = y.astype(np.int)

        prim_obj = Prim(x, y, threshold=0.8)
        box_lims = np.array([(0, set(['a', 'b'])), (1, set(['a', 'b']))],
                            dtype=dtype)
        box = PrimBox(prim_obj, box_lims, prim_obj.yi)

        u = 'b'
        peels = categorical_peel(prim_obj, box, u)

        self.assertEquals(len(peels), 2)

        for peel in peels:
            pl = peel[1][u]
            self.assertEquals(len(pl[0]), 1)
            self.assertEquals(len(pl[1]), 1)
Пример #24
0
def Rsl(G, root=None, choice='prim'):
    """Retourne le parcours en preordre de larbre de recouvrement mininmal."""
    if str.lower(choice) == 'prim':
        cost, arbre_min = Prim(G, root)

    elif str.lower(choice) == 'kruskal':
        cost, arbre_min = Kruskal(G)

    if root is None:  # si la racine nest pas donne le premier noeud est pris
        order, temp = dfs_visit(arbre_min, arbre_min.nodes[0])
    else:
        order, temp = dfs_visit(arbre_min, root)
    c = 0
    cycle = Graph()  # un graphe est cree
    for node in order:  # les noeuds sont ajouter au grpahe
        cycle.add_node(node)
    for i in xrange(len(order) - 1):  # les aretes sont ajouter au graphe
        # a laide du cycle obtenue de dfs_visit
        temp_c = G.get_edge_copy(order[i], order[i + 1]).get_cost()
        cycle.add_edge(Edge(start=order[i], end=order[i + 1], cost=temp_c))
        c += temp_c

    return cycle, c
Пример #25
0
    def setUp(self):
        graph_file = "test_data/graph_data.txt"

        with open(graph_file) as stream:
            self.graph = Graph(stream)
            self.mst = Prim(self.graph).get_minimum_spaning_tree()
Пример #26
0
    def hillclimbing(self):
        """
        Find possible swaps between a randomly chosen house 
        and all other houses. If there are multiple swaps possible given, 
        pick a random swap when hillblimbing is stochastic, and pick the best
        swap when hillblimbing is steepest ascent.
        """

        chosen_battery = choice(self.batteries)
        chosen_house = choice(chosen_battery.houses)

        swap_options = []
        old_costs = self.all_costs[-1]

        for potential_battery in self.batteries:
            if potential_battery == chosen_battery:
                continue
            houses = potential_battery.houses
            for potential_house in houses:
                chosen_battery_capacity = chosen_battery.capacity + \
                    chosen_house.power

                if potential_house.power < chosen_battery_capacity and \
                        chosen_house.power < potential_battery.capacity + potential_house.power:

                    if self.share_grid == True:
                        swap(potential_house, potential_battery, chosen_house,
                             chosen_battery)

                        prim = Prim(self.batteries)

                        battery_costs = 0
                        for battery in self.batteries:
                            battery_costs += battery.costs

                        new_costs = prim.costs + battery_costs
                        cost_difference = old_costs - new_costs

                        reverse_swap(potential_house, potential_battery,
                                     chosen_house, chosen_battery)

                    else:
                        potential_distance = get_distance(potential_house, potential_battery) + \
                            get_distance(chosen_house, chosen_battery)

                        new_distance = get_distance(chosen_house, potential_battery) + \
                            get_distance(potential_house, chosen_battery)

                        cost_difference = potential_distance - new_distance

                    swap_options.append(
                        (potential_battery, potential_house, cost_difference))

        better_options = [option for option in swap_options if option[2] > 0]
        if better_options:
            if self.variant == "stochastic":
                battery, house, _ = random.choice(better_options)
            else:
                battery, house, _ = max(swap_options, key=lambda x: x[2])

            swap(house, battery, chosen_house, chosen_battery)
Пример #27
0
    # terminals = [654, 288, 315, 231, 312, 111, 609, 645, 434, 469, 186]
    terminals = [12, 88, 66, 77, 5, 33]

    suitability_graph = SuitabilityGraph()
    suitability_graph.append_graph(node_weighted)

    suitability_graph.extend_suitable_regions(seed, generator)
    suitability_graph.extend_suitable_regions(seed, generator)

    regions = suitability_graph.get_suitable_regions(generator)

    start_time = time.clock()

    terminals_mc = suitability_graph.build_metric_closure(terminals)
    mst_terminals_mc = Prim(terminals_mc).spanning_tree()
    excluded_edges = set(terminals_mc.get_edges()) - set(
        mst_terminals_mc.get_edges())

    # suitable_nodes = suitability_graph.get_suitable_nodes(generator, excluded_nodes=terminals)
    # closures_edges = set()
    # msts_edges = set()
    # for sn in suitable_nodes:
    #     t_sn = list(terminals)
    #     t_sn.append(sn)
    #     t_sn_mc = suitability_graph.build_metric_closure(t_sn)
    #     mst_t_sn_mc = Prim(t_sn_mc).spanning_tree()
    #     closures_edges.update(t_sn_mc.get_edges())
    #     msts_edges.update(mst_t_sn_mc.get_edges())
    # ee = closures_edges - msts_edges
    # excluded_edges.update(ee)
Пример #28
0
"""
main.py
"""
import graphviz

import loader
from dijkstra import Dijkstra
from graph import Graph
from kruskal import Kruskal
from prim import Prim

g = Graph(loader.load_graph_from_file('./graph_examples/graph.csv'))

kruskal = Kruskal(g)
dijkstra = Dijkstra(g)
prim = Prim(g)

algorithms = [kruskal, dijkstra, prim]

for algorithm in algorithms:
    mst = algorithm.run()
    sum_weight = sum([int(edge.weight) for edge in mst])
    print('Sum for {}: {}'.format(algorithm.__class__.__name__, sum_weight))

    graph = graphviz.Graph(name=algorithm.__class__.__name__ + '_MST',
                           format='pdf')
    for vertex in g.vertices:
        graph.node(vertex, label=vertex)
    for edge in mst:
        graph.edge(edge.v1, edge.v2, label=edge.weight)
    graph.render(directory='mst_output')
Пример #29
0
import matplotlib.pyplot as plt
from kmeans import KMeans
from kruskal import Kruskal
from prim import Prim

K = 7

input_data = open("data/data.txt", "r")
data = np.loadtxt(input_data)

input_classes = open("data/classes.txt", "r")
classes = np.loadtxt(input_classes)

methods = dict({
    "Kruskal": Kruskal(data, K),
    "Prim": Prim(data, K),
    "KMeans": KMeans(data, K)
})

# PRINT READABLE OUTPUT
table_headers = [
    "Method", "Silhouette Coefficient", "Rand Index", "Delta Time"
]
output = []
for key, value in methods.items():
    output.append([
        key, value.silhouette,
        adjusted_rand_score(classes, value.classes), value.time
    ])

    # # PLOT GRAPH
Пример #30
0
    alg = 'kruskal'
    nclusters = 7
    try:
        if(sys.argv[1] == 'prim'):
            alg= 'prim'
        nclusters = int(sys.argv[2])
        
    except (IndexError, ValueError):
        pass
    
    if alg == 'kruskal':
        kk = Kruskall(edges, len(pv), nclusters)
        for c in kk.part.relabeled():
            print(c)
    else:
        prim = Prim(adj)
    
        treev = np.array(prim.tree_edges, dtype=object) # numpy array for easer manipulation

        small = treev[treev[:,0].argsort(0)][:npoints-nclusters] # remove unwanted edges 
        smal_adj = edges_to_adj(small, npoints)   # adjacency list with only the relevant edges
        prim_part = find_components(smal_adj)          # partition from the connected components
        for c in prim_part:
            print(c)
            
    sys.exit()
    


# ## Clustering and Analysis 
Пример #31
0
    def test_box_init(self):
        # test init box without NANS
        x = np.array([(0, 1, 2), (2, 5, 6), (3, 2, 7)],
                     dtype=[('a', np.float), ('b', np.float), ('c', np.float)])
        y = np.array([0, 1, 2])

        prim_obj = Prim(x, y, threshold=0.5)
        box_init = prim_obj._box_init

        # some test on the box
        self.assertTrue(box_init['a'][0] == 0)
        self.assertTrue(box_init['a'][1] == 3)
        self.assertTrue(box_init['b'][0] == 1)
        self.assertTrue(box_init['b'][1] == 5)
        self.assertTrue(box_init['c'][0] == 2)
        self.assertTrue(box_init['c'][1] == 7)

        # test init box with NANS
        x = np.array([(0, 1, 2), (2, 5, np.NAN), (3, 2, 7)],
                     dtype=[('a', np.float), ('b', np.float), ('c', np.float)])
        y = np.array([0, 1, 2])

        x = np.ma.array(x)
        x['a'] = np.ma.masked_invalid(x['a'])
        x['b'] = np.ma.masked_invalid(x['b'])
        x['c'] = np.ma.masked_invalid(x['c'])

        prim_obj = Prim(x, y, threshold=0.5)
        box_init = prim_obj._box_init

        # some test on the box
        self.assertTrue(box_init['a'][0] == 0)
        self.assertTrue(box_init['a'][1] == 3)
        self.assertTrue(box_init['b'][0] == 1)
        self.assertTrue(box_init['b'][1] == 5)
        self.assertTrue(box_init['c'][0] == 2)
        self.assertTrue(box_init['c'][1] == 7)

        # heterogenous without NAN
        dtype = [('a', np.float), ('b', np.int), ('c', np.object)]
        x = np.empty((10, ), dtype=dtype)

        x['a'] = [0.1, 0.2, 0.3, 0.4, 0.5, 0.5, 0.7, 0.8, 0.9, 1.0]
        x['b'] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
        x['c'] = [
            'a',
            'b',
            'a',
            'b',
            'a',
            'a',
            'b',
            'a',
            'b',
            'a',
        ]

        prim_obj = Prim(x, y, threshold=0.5)
        box_init = prim_obj._box_init

        # some test on the box
        self.assertTrue(box_init['a'][0] == 0.1)
        self.assertTrue(box_init['a'][1] == 1.0)
        self.assertTrue(box_init['b'][0] == 0)
        self.assertTrue(box_init['b'][1] == 9)
        self.assertTrue(box_init['c'][0] == set(['a', 'b']))
        self.assertTrue(box_init['c'][1] == set(['a', 'b']))

        # heterogenous with NAN
        dtype = [('a', np.float), ('b', np.int), ('c', np.object)]
        x = np.empty((10, ), dtype=dtype)

        x[:] = np.NAN
        x['a'] = [0.1, 0.2, 0.3, 0.4, 0.5, 0.5, 0.7, 0.8, np.NAN, 1.0]
        x['b'] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
        x['c'] = [
            'a',
            'b',
            'a',
            'b',
            np.NAN,
            'a',
            'b',
            'a',
            'b',
            'a',
        ]

        x = np.ma.array(x)
        x['a'] = np.ma.masked_invalid(x['a'])
        x['b'] = np.ma.masked_invalid(x['b'])
        x['c'][4] = np.ma.masked

        prim_obj = Prim(x, y, threshold=0.5)
        box_init = prim_obj._box_init

        # some test on the box
        self.assertTrue(box_init['a'][0] == 0.1)
        self.assertTrue(box_init['a'][1] == 1.0)
        self.assertTrue(box_init['b'][0] == 0)
        self.assertTrue(box_init['b'][1] == 9)
        self.assertTrue(box_init['c'][0] == set(['a', 'b']))
        self.assertTrue(box_init['c'][1] == set(['a', 'b']))
Пример #32
0
    def anneal(self):
        """Find possible swaps between a randomly chosen house and other houses. 
        
        If there are multiple swaps possible, make the best swap if it is an 
        improvement or accept a worse swap depending on an acceptance probability. 
        This in turns depends on the temperature at that time, which decreases
        after each iteration using a cooling scheme.
        """

        chosen_battery = random.choice(self.batteries)
        chosen_house = random.choice(chosen_battery.houses)

        swap_options = []
        old_costs = self.all_costs[-1]

        for potential_battery in self.batteries:
            if potential_battery == chosen_battery:
                continue
            for potential_house in potential_battery.houses:
                chosen_capacity = chosen_battery.capacity + chosen_house.power
                potential_capacity = potential_battery.capacity + potential_house.power

                if potential_house.power < chosen_capacity and \
                        chosen_house.power < potential_capacity:

                    if self.share_grid == False:
                        potential_distance = get_distance(potential_house, potential_battery) + \
                            get_distance(chosen_house, chosen_battery)

                        new_distance = get_distance(chosen_house, potential_battery) + \
                            get_distance(potential_house, chosen_battery)

                        cost_difference = potential_distance - new_distance

                    else:
                        swap(potential_house, potential_battery,
                             chosen_house, chosen_battery)

                        prim = Prim(self.batteries)

                        battery_costs = 0
                        for battery in self.batteries:
                            battery_costs += battery.costs

                        new_costs = prim.costs + battery_costs
                        cost_difference = old_costs - new_costs

                        reverse_swap(potential_house, potential_battery,
                                     chosen_house, chosen_battery)

                    swap_options.append(
                        (potential_battery, potential_house, cost_difference))

        acceptance = 0
        if swap_options:
            desired_battery, house_to_extract, cost_decrease = max(
                swap_options, key=lambda x: x[2])
            if cost_decrease > 0:
                acceptance = 1
            else:
                desired_battery, house_to_extract, cost_increase = random.choice(
                    swap_options)
                acceptance = exp(cost_increase/self.temp)
        if acceptance > random.random():
            swap(house_to_extract, desired_battery,
                 chosen_house, chosen_battery)