示例#1
0
文件: test.py 项目: powerllamas/MiOIB
class TestLocalSearch(unittest.TestCase):

    def setUp(self):
        self.flow = [
                [0, 1, 2],
                [4, 0, 5],
                [7, 2, 0]]
        self.distance = [
                [0, 5, 2],
                [1, 0, 1],
                [6, 2, 0]]
        self.i = Instance(None, self.distance, self.flow)
        self.ls_steepest = LocalSearch()
        self.ls_greedy = LocalSearch(greedy=True)
        self.startpoint = Solution((0, 1, 2))

    def test_solve_steepest_with_startpoint(self):
        expected = (2, 1, 0)
        actual = self.ls_steepest.solve(self.i, self.startpoint).sequence
        self.assertEqual(expected, actual)

    def test_solve_greedy_with_startpoint(self):
        expected = (2, 1, 0)
        actual = self.ls_greedy.solve(self.i, self.startpoint).sequence
        self.assertEqual(expected, actual)
def run_local_search(seconds):
    print('Running Local Search algoritm for ' + str(seconds) + ' seconds...')
    print()

    ls = LocalSearch(states, seconds, inc_support, dec_support)
    ls.run()
    print('Found optimal route with value of ' + str(ls.best_solution.value) +
          '.')
    print(
        str(ls.best_solution.calculate_real_value()) +
        ' electoral votes were collected.')
    ls.best_solution.print()
    print()
示例#3
0
文件: test.py 项目: powerllamas/MiOIB
 def setUp(self):
     self.flow = [
             [0, 1, 2],
             [4, 0, 5],
             [7, 2, 0]]
     self.distance = [
             [0, 5, 2],
             [1, 0, 1],
             [6, 2, 0]]
     self.i = Instance(None, self.distance, self.flow)
     self.ls_steepest = LocalSearch()
     self.ls_greedy = LocalSearch(greedy=True)
     self.startpoint = Solution((0, 1, 2))
示例#4
0
    def parse_cmd(self):
        parser = argparse.ArgumentParser()
        parser.add_argument(
            '-ST',
            default=0,
            help=
            'Search type: 0 for backward or forward search and 2 for local search.'
        )
        parser.add_argument(
            '-AT',
            default=0,
            help=
            'Algorithm type: 0 for backtracking, 1 for back jumping, 2 for forward checking, '
            '3 for arc consistency.')
        parser.add_argument(
            '-LS',
            default=0,
            help=
            'Local search: 0 for feasibility, 1 for KEMPE chains and  2 for hybrid.'
        )
        args = parser.parse_args()

        try:
            search_type = int(args.ST)
            if search_type != 0 and search_type != 1:
                print("Search type can only be 0 or 1.")
                sys.exit()
        except ValueError:
            print("Search type can only be 0 or 1.")
            sys.exit()
        self.search_type = SearchType(search_type)

        try:
            algorithm_type = int(args.AT)
            if algorithm_type != 0 and algorithm_type != 1 and algorithm_type != 2 and algorithm_type != 3:
                print("Algorithm type can only be 0, 1, 2 or 3.")
                sys.exit()
        except ValueError:
            print("Algorithm type can only be 0, 1, 2 or 3.")
            sys.exit()
        self.algorithm_type = AlgorithmType(algorithm_type)

        try:
            local_search = int(args.LS)
            if local_search != 0 and local_search != 1 and local_search != 2:
                print("Local search can only be 0, 1 or 2.")
                sys.exit()
        except ValueError:
            print("Local search can only be 0, 1 or 2.")
            sys.exit()
        self.local_search = LocalSearch(local_search)
def benchmark():
    REPEATS = 10
    SECONDS = [5, 10, 30, 60, 300, 1200]

    for seconds in SECONDS:
        v = 0
        time_s = datetime.now()
        for k in range(REPEATS):
            rs = RandomSearch(states, seconds, inc_support, dec_support)
            rs.run()
            v += rs.best_solution.value
        time_e = datetime.now()
        tt = (time_e - time_s).total_seconds()
        print_csv('Random Search', str(seconds), str(v / REPEATS),
                  str(tt / REPEATS))

    for seconds in SECONDS:
        v = 0
        time_s = datetime.now()
        for k in range(REPEATS):
            ls = LocalSearch(states, seconds, inc_support, dec_support)
            ls.run()
            v += ls.best_solution.value
        time_e = datetime.now()
        tt = (time_e - time_s).total_seconds()
        print_csv('Local Search', str(seconds), str(v / REPEATS),
                  str(tt / REPEATS))

    for seconds in SECONDS:
        for initial_cadence in [10, 25, 50]:
            for critical_event in [10, 25, 50]:
                v = 0
                time_s = datetime.now()
                for k in range(REPEATS):
                    ts = TabuSearch(states, seconds, initial_cadence,
                                    critical_event, inc_support, dec_support)
                    ts.run()
                    v += ts.best_solution.value
                time_e = datetime.now()
                tt = (time_e - time_s).total_seconds()
                print_csv('Tabu Search', str(seconds), str(initial_cadence),
                          str(critical_event), str(v / REPEATS),
                          str(tt / REPEATS))

    for crossover in ['pmx', 'ox']:
        for mutate in ['transposition', 'insertion', 'inversion']:
            for seconds in SECONDS:
                for population_size in [10, 25, 50]:
                    v = 0
                    time_s = datetime.now()
                    for k in range(REPEATS):
                        ga = GeneticAlgorithm(states, seconds, population_size,
                                              crossover, mutate, inc_support,
                                              dec_support)
                        ga.run()
                        v += ga.best_solution.value
                    time_e = datetime.now()
                    tt = (time_e - time_s).total_seconds()
                    print_csv('Genetic Algorithm ' + crossover + ' ' + mutate,
                              str(seconds), str(population_size),
                              str(v / REPEATS), str(tt / REPEATS))

    for initial_temperature in [100, 500, 1000]:
        for cooling_coefficient in [0.9, 0.99, 0.999, 0.9999]:
            for minimal_temperature in [
                    initial_temperature * 0.25, initial_temperature * 0.5,
                    initial_temperature * 0.75
            ]:
                v = 0
                time_s = datetime.now()
                for k in range(REPEATS):
                    sa = SimulatedAnnealing(states, initial_temperature,
                                            cooling_coefficient,
                                            minimal_temperature, inc_support,
                                            dec_support)
                    sa.run()
                    v += sa.best_solution.value
                time_e = datetime.now()
                tt = (time_e - time_s).total_seconds()
                print_csv('Simulated Annealing', str(initial_temperature),
                          str(cooling_coefficient), str(minimal_temperature),
                          str(v / REPEATS), str(tt / REPEATS))
def performance_testing():
    # Heuristics
    h_alg = [solverNN.algorithm, solverCHH.algorithm]
    h_alg_name = ["solverNN.algorithm", "solverCHH.algorithm"]
    ls_alg_name = [
        "SolverLS_close_index_route_swap",
        "SolverLS_all_combination_route_swap", "TwoOPT"
    ]
    try:
        for (idx, algo) in enumerate(h_alg):
            with open('../results/' + h_alg_name[idx] + '.dat',
                      "a") as filehandle:
                filehandle.write("{} {} {}\n".format("Instance", "Cost",
                                                     "Time"))
                for path, subdirs, files in os.walk('../data'):
                    for name in files:
                        if fnmatch.fnmatch(name, "*.xml"):
                            t0 = time.clock()
                            instance = data.Data(os.path.join(path, name))
                            ch = ConstructionHeuristics(instance, algo)
                            sol = ch.construct(60 - t0)
                            splitted_name = re.compile("^[a-zA-Z]+").findall(
                                name)
                            filehandle.write("{} {} {}".format(
                                splitted_name[0], sol.cost(), round(t0, 2)))
                            filehandle.write("\n")
                            ls_alg = [
                                SolverLS(sol).run_first,
                                SolverLS(sol).run_second,
                                TwoOPT(sol).run
                            ]

                            for (ls_idx, l_alg) in enumerate(ls_alg):
                                with open(
                                        '../results/' + ls_alg_name[ls_idx] +
                                        '_' + h_alg_name[idx] + '.dat',
                                        "a") as ls_fh:
                                    if os.stat('../results/' +
                                               ls_alg_name[ls_idx] + '_' +
                                               h_alg_name[idx] +
                                               '.dat').st_size == 0:
                                        ls_fh.write("{} {} {}\n".format(
                                            "Instance", "Cost", "Time"))
                                    t0 = time.clock()
                                    ls = LocalSearch(solution=sol, alg=l_alg)
                                    try:
                                        sol = ls.construct(60 - t0)
                                    except TimeOutExeption as e:
                                        print("timeout")
                                        sol = e.solution
                                    ls_fh.write("{} {} {}".format(
                                        splitted_name[0], sol.cost(),
                                        round(t0, 2)))
                                    ls_fh.write("\n")
                                    ls_fh.close()
                filehandle.close()
                boxplotter('../results/' + h_alg_name[idx])
                for ls_idx in range(len(ls_alg_name)):
                    boxplotter('../results/' + ls_alg_name[ls_idx] + '_' +
                               h_alg_name[idx])

    except TimeOutExeption as e:
        print("timeout")
        sol = e.solution
def Meme_IM(args):
     
    Candidate = args['Candidate']    
    MaximumGeneration = args['maxgen']
    PopulationSize = args['pop_size']
    MatingPoolSize = args['pool']
    TournamentSize = args['tour']
    CrossoverProbability = args['pc']
    MutationProbability = args['pm']
    SpreadProbability = args['p']
    SeedSize = args['k']
    TheCandidateNodesPool = args['Candidate']
    TheConnectionMatrix = args['A']
    NumberOfGenerations = args['NumberOfGenerations']
    gmat = args['gmat']
    
    pop_x = args['pop_size']
    pop_y = SeedSize
    ### should be removed only for test
    
    #    1:Step 1) Initialization
    #    3: Step 1.2) Best individual initialization: Pbest = xi ;
    population = PopulationInitialization(args)
    population = np.reshape(population, (pop_x,pop_y))
    
    fitnesses = cal_fitnesses(population, args)
    fitnesses = np.reshape(fitnesses, (pop_x))
    
    population, fitnesses = sortpopulation(population, fitnesses, args)
     
    Pbest,_ = BestIndividualInitialization(population, fitnesses, args)
    
      
    #    4: Step 2) Set t = 0; // the number of generations
    #    5: Step 3) Repeat
    #    6: Step 3.1) Select parental chromosomes for mating;
    #    Pparent ! Selection(P, pool, tour);
    #    7: Step 3.2) Perform genetic operators:
    #    Pchild ! GeneticOperation(Pparent , pc, pm);
    #    8: Step 3.3) Perform local search:
    #    Pnew ! LocalSearch(Pchild );
    #    9: Step 3.4) Update population:
    #    P ! UpdatePopulation(P, Pnew );
    #    10: Step 3.5) Update the best individual Pbest ;
    #    11: Step 4) Stopping criterion: If t < maxgen, then
    #    t = t +1 and go to Step 3), otherwise, stop the
    #    algorithm and output.

    for t in range(MaximumGeneration):
        #print("generation = ", t)
                
        Pparent = Selection(population,fitnesses, TournamentSize, args)
        
        Pparent, fit  = LocalSearch(Pparent, Candidate, args)
        cross_child1, cross_child2, mute_child1,mute_child2  = GeneticOperation(Pbest, Pparent, Candidate, args)
#        cross_child1, fitc1 = LocalSearch(cross_child1, Candidate, args)
#        cross_child2, fitc2 = LocalSearch(cross_child2, Candidate, args)
#        mute_child1,  fitm1 = LocalSearch(mute_child1, Candidate, args)
#        mute_child2,  fitm2 = LocalSearch(mute_child2, Candidate, args)
#        
        
        fitc1 = fitness(cross_child1, gmat)
        fitc2 = fitness(cross_child2, gmat)
        fitm1 = fitness(mute_child1, gmat)
        #fitm2 = fitness(mute_child2, gmat)
        
        #print(cross_child1, cross_child2,mute_child1,mute_child2)
       
        population,fitnesses = list(population), list(fitnesses)
        population.append(cross_child1)
        fitnesses.append(fitc1)
        population.append(cross_child2)
        fitnesses.append(fitc2)
        population.append(mute_child1)
        fitnesses.append(fitm1)
        #population.append(mute_child2)
        #fitnesses.append(fitm2)
        
        
        population, fitnesses = np.asarray(population), np.asarray(fitnesses)
        population, fitnesses = sortpopulation(population, fitnesses, args)
        Pbest,_ = BestIndividualInitialization(population, fitnesses, args)
        
        #print("fitnesses",fitnesses)
        print("Generation:",t," best fitnesses", fitnesses[0])
        
    return population[0], fitnesses[0]
示例#8
0
def bPSO(args):

    MaxIter = args['MaxIter']
    PopSize = args['PopSize']
    c1 = args['c1']
    c2 = args['c2']
    w = args['w']
    wdamp = args['wdamp']
    problem = args['problem']
    Candidate = args['Candidate']

    # Empty Particle Template
    empty_particle = {
        'position': None,
        'velocity': None,
        'cost': None,
        'best_position': None,
        'best_cost': None,
    }

    # Extract Problem Info
    CostFunction = problem['CostFunction']
    VarMin = problem['VarMin']
    VarMax = problem['VarMax']
    nVar = problem['nVar']

    # Initialize Global Best
    gbest = {'position': None, 'cost': np.inf}

    # Create Initial Population
    pop = []
    for i in range(0, PopSize):
        pop.append(empty_particle.copy())
        pop[i]['position'] = np.random.uniform(VarMin, VarMax, nVar)
        # convert to binary
        pop[i]['position'] = convert_to_binary(pop[i]['position'])

        pop[i]['velocity'] = np.zeros(nVar)
        pop[i]['cost'] = CostFunction(pop[i]['position'], args)
        pop[i]['best_position'] = pop[i]['position'].copy()
        pop[i]['best_cost'] = pop[i]['cost']

        if pop[i]['best_cost'] < gbest['cost']:
            gbest['position'] = pop[i]['best_position'].copy()
            gbest['cost'] = pop[i]['best_cost']

    # PSO Loop
    for it in range(0, MaxIter):
        for i in range(0, PopSize):

            pop[i]['velocity'] = w*pop[i]['velocity'] \
                + c1*np.random.rand(nVar)*(pop[i]['best_position'] - pop[i]['position']) \
                + c2*np.random.rand(nVar)*(gbest['position'] - pop[i]['position'])

            pop[i]['position'] += pop[i]['velocity']

            # convert to binary
            #pop[i]['position'] = convert_to_binary(pop[i]['position'])

            pop[i]['position'] = np.maximum(pop[i]['position'], VarMin)
            pop[i]['position'] = np.minimum(pop[i]['position'], VarMax)

            pop[i]['cost'] = CostFunction(
                convert_to_binary(pop[i]['position']), args)

            local_n, fit_local = LocalSearch(pop[i]['position'], Candidate,
                                             args)

            if fit_local < pop[i]['cost']:
                count = 0
                for itm in local_n:
                    bin_item = decimal_to_binary(itm, args['len_var'])
                    pop[i]['position'][count:count + args['len_var']] = [
                        int(x) for x in bin_item
                    ]
                    #print("L", pop[i]['position'][count:count+args['len_var']])
                    count += args['len_var']
                pop[i]['cost'] = fit_local

            if pop[i]['cost'] < pop[i]['best_cost']:
                pop[i]['best_position'] = pop[i]['position'].copy()
                pop[i]['best_cost'] = pop[i]['cost']

                if pop[i]['best_cost'] < gbest['cost']:
                    gbest['position'] = pop[i]['best_position'].copy()
                    gbest['cost'] = pop[i]['best_cost']

        w *= wdamp
        print('Iteration {}: Best Cost = {}'.format(it, -gbest['cost']))

    return gbest, pop