Exemplo n.º 1
0
def solve(problem):
    proc_times, weights, due_times, opt_sol = problem

    memo = {}
    def total_weighted_tardiness(schedule):
        key = tuple(schedule)
        if not key in memo:
            res = 0.0
            t = 0
            for j in schedule:
                s_j = t
                T_j = s_j + proc_times[j] - due_times[j]
                if T_j > 0:
                    res += weights[j] * T_j
                t += proc_times[j]
            memo[key] = res
        return memo[key]

    def eval_fitness(solution):
        schedule = numpy.argsort(solution)
        best = total_weighted_tardiness(schedule)
        return best

    def local_search(p):
        if random.random() < .9:
            return
        orig_sol = numpy.array(p.pos, copy=True)
        best_score = eval_fitness(orig_sol)
        best = orig_sol
        for k in range(15):
            v = random.randint(0, len(orig_sol)-1)
            w = random.randint(0, len(orig_sol)-1)
            s = numpy.array(orig_sol)
            s[v], s[w] = s[w], s[v]
            score = eval_fitness(s)
            if score < best_score:
                best_score = score
                best = s
        p.pos = best

    N = len(proc_times)
    best_sol = optimize(eval_fitness,
                        N * ((-1.0, 1.0,),),
                        num_particles=80, neighborhood_size=5,
                        start_inertia=1,
                        trust_self=1.5,
                        trust_neighbors=1.5,
                        max_time=40,
                        #particle_mod_fn=local_search,
                        should_clamp_vel=True,
                        should_clamp_pos=False)[0]

    print 1.05*opt_sol
    #raw_input()
    return eval_fitness(best_sol)
Exemplo n.º 2
0
def main():
    args_parser = build_args_parser()
    args = args_parser.parse_args()

    results_dir_path = args.output_path

    if not os.path.exists(results_dir_path):
        os.makedirs(results_dir_path)

    for function_type in [f.value for f in FunctionType]:
        function = build_function(function_type)
        best_fitness_history_by_topology_type = {}

        for topology_type in [t.value for t in TopologyType]:
            best_fitness_history = []

            for i in range(args.num_simulations):
                start_time = time.time()

                population = Population(args.population_size, args.dimension,
                                        function.lower_limit,
                                        function.upper_limit, topology_type)

                if args.use_clerc:
                    best_fitness = pso.optimize_with_clerc(
                        function, population, args.num_iterations,
                        args.cognitive_coeff, args.social_coeff)
                else:
                    best_fitness = pso.optimize(function, population,
                                                args.num_iterations,
                                                args.initial_inertia_coeff,
                                                args.final_inertia_coeff,
                                                args.cognitive_coeff,
                                                args.social_coeff)

                elapsed_time = time.time() - start_time

                print(function_type + ", " + topology_type + ", simulação: " +
                      str(i + 1) + ", fitness: " +
                      str(round(best_fitness, 2)) + "(" +
                      str(round(elapsed_time, 2)) + " s)")

                best_fitness_history.append(best_fitness)

            best_fitness_history_by_topology_type[
                topology_type] = best_fitness_history

        plt.clf()
        plt.boxplot(list(best_fitness_history_by_topology_type.values()),
                    labels=list(best_fitness_history_by_topology_type.keys()))
        plt.title(function_type)
        plt.savefig(os.path.join(results_dir_path,
                                 function_type + "_box_plot.png"),
                    bbox_inches='tight')
Exemplo n.º 3
0
def test(filepath, max_num_fitness_evaluations, num_hidden):
    data, num_features, num_classes = read_and_normalize_file(filepath)

    num_inputs = num_features+1
    num_outputs = num_classes

    build_classifier = ann_classifier_meta_factory(
                            num_inputs, num_hidden, num_outputs)
    num_weights = num_inputs*num_hidden+num_hidden*num_outputs

    random.shuffle(data)

    cut = int(3*len(data)/5.0)
    training, testing = data[:cut], data[cut:]
    print len(data), cut, len(training), len(testing)

    memo = {}
    def evalit(xs):
        t = tuple(xs)
        if not t in memo:
            c = build_classifier(xs)
            memo[t] = evaluate_classifier(c, training)
        return memo[t]

    weights = pso.optimize(
        evalit,
        domains=num_weights*[[-8, 8]],
        num_particles=60, neighborhood_size=5,
        start_inertia=1, trust_self=2.4, trust_neighbors=2.4,
        #max_time=60,
        #accepted_minima=0,
        max_vel_scale=2.0,
        inertia_dec_factor=0.99,
        should_clamp_vel=False,
        max_num_fitness_evaluations=max_num_fitness_evaluations
    )[0]
    print weights
    c = build_classifier(weights)

    testing_err = evaluate_classifier(c, testing)/float(len(testing))
    training_err = evaluate_classifier(c, training)/float(len(training))
    print 'TRAINING ERRORS:', evaluate_classifier(c, training), '/', len(training), training_err
    print 'TEST     ERRORS:', evaluate_classifier(c, testing), '/', len(testing), testing_err
    return ( (int(evaluate_classifier(c, training)),
              int(evaluate_classifier(c, testing))) )
Exemplo n.º 4
0
def solve(problem):
    proc_times, weights, due_times, opt_sol = problem

    memo = {}

    def total_weighted_tardiness(schedule):
        key = tuple(schedule)
        if not key in memo:
            res = 0.0
            t = 0
            for j in schedule:
                s_j = t
                T_j = s_j + proc_times[j] - due_times[j]
                if T_j > 0:
                    res += weights[j] * T_j
                t += proc_times[j]
            memo[key] = res
        return memo[key]

    def eval_fitness(solution):
        schedule = numpy.argsort(solution)
        best = total_weighted_tardiness(schedule)
        return best

    def local_search(p):
        if random.random() < .9:
            return
        orig_sol = numpy.array(p.pos, copy=True)
        best_score = eval_fitness(orig_sol)
        best = orig_sol
        for k in range(15):
            v = random.randint(0, len(orig_sol) - 1)
            w = random.randint(0, len(orig_sol) - 1)
            s = numpy.array(orig_sol)
            s[v], s[w] = s[w], s[v]
            score = eval_fitness(s)
            if score < best_score:
                best_score = score
                best = s
        p.pos = best

    N = len(proc_times)
    best_sol = optimize(
        eval_fitness,
        N * ((
            -1.0,
            1.0,
        ), ),
        num_particles=80,
        neighborhood_size=5,
        start_inertia=1,
        trust_self=1.5,
        trust_neighbors=1.5,
        max_time=40,
        #particle_mod_fn=local_search,
        should_clamp_vel=True,
        should_clamp_pos=False)[0]

    print 1.05 * opt_sol
    #raw_input()
    return eval_fitness(best_sol)
import pso

# matplotlib.use("TkAgg")  # uncomment for use on MAC

if __name__ == '__main__':
    pso.optimize(n_particles=20,                   # population size
                 n_iterations=130,                 # number of iterations / updates
                 benchmark_function='rastrigin',   # rastrigin, rosenbrock
                 a=0.9,                            # learning constant: conservative = "continue with current velocity"
                 b=2,                              # learning constant: brave = "direction to local best location"
                 c=2,                              # learning constant: swarm = "direction to global best location"
                 r_max=1,                          # random factor maximum
                 delta_t=1,                        # euler integration
                 frame_range=[-5, 5],              # size of (squared) frame
                 random_init_v=False,              # random initialization of velocity, if False init. with 0
                 v_max=5,                          # maximum velocity
                 oof_strategy=4                    # out of frame strategy:
                 )                                  # 0: old position,
                                                    # 1: change direction,
                                                    # 2: new random factors (r1, r2),
                                                    # 3: only small step in new direction,
                                                    # 4: old coordinate
Exemplo n.º 6
0
import math

# Minimize f(x) = x^2 + y^2
# where -inf < x < inf,
#	-inf < y < inf
# such that x + y >= 10


def penalty(k, x):
    if x > 0:
        return k * x**2
    else:
        return 0


def f1(x):
    return (x[0]**2 + x[1]**2) + penalty(100, 10 - (x[0] + x[1]))


sol = pso.optimize(objective_function=f1,
                   swarm_size=5000,
                   tolerance=0.005,
                   number_of_dimensions=2,
                   omega=0.05,
                   c1=0.05,
                   c2=0.85,
                   lower_bound=[-99999, -99999],
                   upper_bound=[99999, 99999],
                   max_iteration=1000)
print "Solution is", sol
Exemplo n.º 7
0
    recombine = ga.recombine_simpleCrossover
    mutate = partial(ga.mutate_permuteSubsequence, max_shuffle_fraction=8)
    cost, solution = ga.engine(jobs,
                               select=select,
                               recombine=recombine,
                               mutate=mutate,
                               maxTime=20)
    jobshop.printSchedule(jobs, solution)
    print('==============GENETIC ALGORITHM=================')
    jobshop.prettyPrintSchedule(jobs, solution)
    print('===============================')

    # DIFFERENTIAL EVOLUTION
    cost, solution = de.engine(jobs)
    jobshop.printSchedule(jobs, solution)
    print('===============DIFFERENTIAL EVOLUTION================')
    jobshop.prettyPrintSchedule(jobs, solution)
    print('===============================')

    # PSO
    mask = jobshop.makeMask(jobs)
    pso = pso.ParticleSwarmOptimizer(j * m, mask, jobs)
    solution = pso.optimize()
    jobshop.printSchedule(jobs, solution.posRep)
    print('===============PSO================')
    jobshop.prettyPrintSchedule(jobs, solution.posRep)
    print('===============================')

    # a solution for vorlesungsbeispiel
    prettyPrintSchedule(jobs, [0, 0, 1, 2, 1, 1, 2, 2, 0])