Ejemplo n.º 1
0
def main():
    da_solver = DASolver()
    simanneal_solver = ClassicalNeal()
    F, D = data.readqaplib(os.path.join("qaplib","sko42.dat"))
    size = F.shape[0]

    problem = PlacementQAP(
        size,
        size,
        F,
        D,
        weight0=5,
        alpha0=5,
        const_weight_inc=False
    )
    method = ExteriorPenaltyMethod(problem, da_solver, 10000)
    method.run()
    test_mtx = problem.flow + problem.cts[2]
    da_ans=da_solver.solve(test_mtx,test_mode=True)
    for answer in da_ans:
        solution_dict = answer[0]
        sample_solution_mtx = PlacementQAP.solution_matrix(da_ans[0][0], size,size)
        if all(problem.check_mtx(sample_solution_mtx)):
            print(solution_dict, answer[1])

    input()
    sw_ans=simanneal_solver.solve(test_mtx,test_mode=True)
Ejemplo n.º 2
0
    def run(self):
        size = self.F.shape[0]
        problem = PlacementQAP(size,
                               size,
                               self.F,
                               self.D,
                               weight0=50,
                               alpha0=2)

        solver = ExactSolv()
        method = ExteriorPenaltyMethod(problem, solver, 1)

        solution = PlacementQAP.solution_matrix((method.run())[0], size, size)
        return solution
Ejemplo n.º 3
0
    def run(self):
        start = time.time()
        print("start running pure QAP.")
        size = self.F.shape[0]
        problem = PlacementQAP(size,
                               size,
                               self.F,
                               self.D,
                               weight0=50000,
                               alpha0=1.1,
                               const_weight_inc=True,
                               initial_weight_estimate=True)
        self.timing.append(problem.timing)
        solver = ClassicalNeal()
        method = ExteriorPenaltyMethod(problem, solver, 1000)

        solution = PlacementQAP.solution_matrix((method.run())[0], size, size)
        self.timing.append(method.get_timing())
        end = time.time()
        self.timing.append(end - start)
        return solution
Ejemplo n.º 4
0
import numpy as np
from ports.classical_simanneal import ClassicalNeal
from ports.dwave import Dwave
from ports.da.da_solver import DASolver
from problems.placement import PlacementQAP

mtx = np.loadtxt("mtx.txt")

port = DASolver()
solution = port.solve(mtx)
input()

port = ClassicalNeal()
solution = port.solve(mtx)
solution_mtx = PlacementQAP.solution_matrix(solution[0], 8,8)
np.set_printoptions(threshold=np.inf)
print(solution_mtx)
input()
port = Dwave()
solution = port.solve(mtx)
solution_mtx = PlacementQAP.solution_matrix(solution[0], 8,8)
np.set_printoptions(threshold=np.inf)
print(solution_mtx)
Ejemplo n.º 5
0
def get_canonical_weights():
    ret = {}
    with open('canonical_weights.txt','r') as f:
        for line in f.read().splitlines():
            info = line.split()
            ret[info[0]] = float(info[1])
    return ret

canonical_weights = get_canonical_weights()
for filename in os.listdir('qaplib'):
    with open("canonical_weights.txt", 'a+') as f:
        if filename.endswith('.dat') and filename not in canonical_weights:
            print(filename)
            F, D = qaplib.readqaplib(os.path.join('qaplib',filename))
            size = F.shape[0]
            solver = DASolver()
            weight0 = size * size * 25600 / (30*30)
            problem = PlacementQAP(
                size,
                size,
                F,
                D,
                weight0=weight0,
                alpha0=2,
                const_weight_inc=True
            )
            method = ExteriorPenaltyMethod(problem,solver,1000)
            method.run()
            
            result_string = filename + " " + str(np.max(problem.ms)) + " " + str(method.get_timing()) + '\n'
            f.write(result_string)
Ejemplo n.º 6
0
                                     F,
                                     D,
                                     fine_weight0=0,
                                     fine_alpha0=0,
                                     use_dwave_da_sw='da')

            for i in range(6):
                solution_da = method_da.run()
                timing_da = method_da.get_timing()
                solution_da_df = postprocess(solution_da)
                filepath_da = generate_filepath(filename, 'da', timing_da)
                solution_da_df.to_csv(filepath_da)

                all_energy_da = [
                    evaluator.run(
                        PlacementQAP.solution_matrix(sol[0], size, size))
                    for sol in solution_da
                ]
                avg_energy_da = np.average(all_energy_da)
                std_energy_da = np.std(all_energy_da)
                #all_energy_sw = [evaluator.run(PlacementQAP.solution_matrix(sol[0],size,size)) for sol in solution_sw]
                #avg_energy_sw = np.average(all_energy_sw)
                #std_energy_sw = np.std(all_energy_sw)

                best_energy_da = evaluator.run(
                    PlacementQAP.solution_matrix(solution_da[0][0], size,
                                                 size))
                result_string = (filename + " " + str(best_energy_da) + " " +
                                 str(avg_energy_da) + " " +
                                 str(std_energy_da) + " " + str(timing_da) +
                                 '\n')
Ejemplo n.º 7
0
            ret[info[0]] = float(info[1])
    return ret


canonical_weights_dict = get_canonical_weights()

for filename in os.listdir('qaplib'):
    if filename.endswith('.dat'):
        with open('data/speed_data.csv', 'a+') as f:
            F, D = qaplib.readqaplib(os.path.join('qaplib', filename))
            size = F.shape[0]

            evaluator = QAPEvaluator(size, size, F, D)
            problem = PlacementQAP(size,
                                   size,
                                   F,
                                   D,
                                   weight0=canonical_weights_dict[filename],
                                   alpha0=0)
            solver_da = DASolver()
            solver_sw = ClassicalNeal()
            method_da = ExteriorPenaltyMethod(problem, solver_da, 1)
            method_sw = ExteriorPenaltyMethod(problem, solver_sw, 1)

            columns = [
                'problem', 'best_energy_da', 'time_da', 'best_energy_sw',
                'time_sw'
            ]
            test_result_df = pd.DataFrame(columns=columns)
            for i in range(6):
                solution_da = method_da.run(test_mode=True)
                timing_da = method_da.get_timing()
Ejemplo n.º 8
0
    def run(self):
        start = time.time()
        #######bunching########
        bunch = BunchingQAP(self.n,
                            self.k,
                            self.F,
                            euqality_weight=100,
                            equality_alpha=1.2,
                            inequality_weight=100,
                            inequality_alpha=1.2,
                            initial_weight_estimate=True,
                            const_weight_inc=True)

        solver = ClassicalNeal()

        bunch_method = ExteriorPenaltyMethod(bunch, solver, 100000000)
        solution1 = bunch.solution_mtx((bunch_method.run())[0])

        self.timing.append(bunch.timing)
        self.timing.append(bunch_method.get_timing())

        #######grouping########
        group = BunchingQAP(self.m,
                            self.k,
                            -self.D,
                            euqality_weight=1000,
                            equality_alpha=1.2,
                            inequality_weight=1000,
                            inequality_alpha=1.2,
                            initial_weight_estimate=True,
                            const_weight_inc=True)
        solver_group = ClassicalNeal()
        group_method = ExteriorPenaltyMethod(group, solver_group, 100000000)
        # solution 1.5
        solution1_5 = group.solution_mtx((group_method.run())[0])

        self.timing.append(group.timing)
        self.timing.append(group_method.get_timing())

        #######bunch permutation/ aggregate QAP########
        g = np.zeros(shape=self.n)
        members = []
        for i in range(self.k):
            members.append([])
        for i in range(self.n):
            for j in range(self.k):
                if solution1[i][j]:
                    g[i] = j
                    members[j].append(i)

        bigF = np.zeros((self.k, self.k))
        for i1 in range(self.k):
            for i2 in range(i1 + 1, self.k):
                interaction = 0
                for item1, item2 in itertools.product(members[i1],
                                                      members[i2]):
                    interaction += self.F[item1][item2]
                bigF[i1][i2] = interaction

        locations = []
        for i in range(self.k):
            locations.append([])
        for i in range(self.m):
            for j in range(self.k):
                if solution1_5[i][j]:
                    locations[j].append(i)

        bigD = np.zeros((self.k, self.k))
        for j1 in range(self.k):
            for j2 in range(j1 + 1, self.k):
                distance = 0
                for loc1, loc2 in itertools.product(locations[j1],
                                                    locations[j2]):
                    distance += self.D[loc1][loc2]
                bigD[j1][j2] = distance

        aggregate_placement_problem = PlacementQAP(self.k, self.k, bigF, bigD)
        dwave_solver = ClassicalNeal()
        aggregate_method = ExteriorPenaltyMethod(aggregate_placement_problem,
                                                 dwave_solver, 100000000)
        solution2 = aggregate_placement_problem.solution_matrix(
            (aggregate_method.run())[0], self.k, self.k)

        self.timing += aggregate_method.get_timing()

        bunch_to_group = {}
        for i in range(self.k):
            for j in range(self.k):
                if solution2[i][j]:
                    bunch_to_group[i] = j

        #######placement within bunches########
        ret = np.zeros((self.n, self.m))
        s = (int)(math.floor(self.m / self.k))
        bunch_size = (int)(math.ceil(self.n / self.k))

        solution3 = {}
        # np.set_printoptions(threshold=np.inf)
        # print(members)
        # print(locations)

        initial_solution = self.get_feasible_solution(members, locations,
                                                      solution2)
        #print(initial_solution)

        timing_construction = 0
        timing_anneal = 0
        for i in range(self.k):
            bunch_i = np.sort(members[i])
            locations_i = np.sort(locations[bunch_to_group[i]])

            # idx_map is from global to local
            # inverse is from local to global
            bunch_i_idx_map = {}
            bunch_i_idx_map_inv = {}
            locations_i_idx_map = {}
            locations_i_idx_map_inv = {}
            for a in range(bunch_size):
                bunch_i_idx_map[bunch_i[a]] = a
                bunch_i_idx_map_inv[a] = bunch_i[a]
            for b in range(s):
                locations_i_idx_map[locations_i[b]] = b
                locations_i_idx_map_inv[b] = locations_i[b]
            FPrime = np.zeros((bunch_size, bunch_size))
            DPrime = np.zeros((s, s))

            for i1, i2 in itertools.product(bunch_i, bunch_i):
                FPrime[bunch_i_idx_map[i1]][
                    bunch_i_idx_map[i2]] = self.F[i1][i2]

            for j1, j2 in itertools.product(locations_i, locations_i):
                DPrime[locations_i_idx_map[j1]][
                    locations_i_idx_map[j2]] = self.D[j1][j2]

            linear = self.specialise_bunch(initial_solution, bunch_i_idx_map,
                                           locations_i_idx_map)

            print(linear)

            fine_placement_problem = PlacementQAP(bunch_size,
                                                  s,
                                                  FPrime,
                                                  DPrime,
                                                  initial_weight_estimate=True,
                                                  const_weight_inc=True,
                                                  linear=linear)
            if self.use_dwave_da_sw == 'dwave':
                solver_i = Dwave()
            elif self.use_dwave_da_sw == 'sw':
                solver_i = ClassicalNeal()
            elif self.use_dwave_da_sw == 'da':
                solver_i = DASolver()
            fine_placement_method = ExteriorPenaltyMethod(
                fine_placement_problem, solver_i, 100000000)
            timing_construction += fine_placement_problem.timing
            solution3[i] = PlacementQAP.solution_matrix(
                (fine_placement_method.run())[0], bunch_size, s)
            timing_anneal += fine_placement_method.get_timing()

            np.set_printoptions(threshold=np.inf)
            #print(bunch_i, locations_i)

            for local_item in range(bunch_size):
                for local_loc in range(s):
                    global_item = bunch_i_idx_map_inv[local_item]
                    global_loc = locations_i_idx_map_inv[local_loc]
                    # if((solution3[i])[local_item][local_loc]):
                    #     print(global_item, global_loc)
                    initial_solution[global_item][global_loc] = (
                        solution3[i])[local_item][local_loc]
                    ret[global_item][global_loc] = (
                        solution3[i])[local_item][local_loc]
        check = PlacementQAP.check_mtx(ret)
        if not all(check):
            raise ValueError("unfeasible solution error")

        self.timing.append(timing_construction)
        self.timing.append(timing_anneal)
        end = time.time()
        self.timing.append(end - start)

        return ret