Exemple #1
0
def NSGAII_Experiment():
    NSGAII_results = {}
    hypNS2 = [0]
    random.seed(0)
    for p in [5,8,10,20]:
        hyp = []
        for i in range(100):
            problem = Problem(7,2,11)
            problem.types[:] = [Real(2.6,3.6),Real(0.7,0.8),Real(17,28),Real(7.3,8.3),Real(7.3,8.3),Real(2.9,3.9),Real(5,5.5)]
            problem.constraints[:] = "<=0"
            problem.function = SRD
            algorithm = NSGAII(problem, p*problem.nvars)
            algorithm.run(40*problem.nvars)
            funcname = 'SRD'
            nondominated_solutions = nondominated(algorithm.result)
            ref = np.array([7000,1700])
            obj = []
            for s in nondominated_solutions:
                lijst = str(s.objectives)
                obj.append(ast.literal_eval(lijst))
            obj = np.array(obj)
            hyp.append(hypervolume(obj,ref))
        if np.mean(hyp) > np.mean(hypNS2):
            hypNS2 = hyp
    print(funcname, np.mean(hypNS2), '(', np.std(hypNS2), ')')
    NSGAII_results[funcname] = hypNS2


    hypNS2 = [0]
    random.seed(0)
    for p in [5,8,10,20]:
        hyp = []
        for i in range(100):
            problem = Problem(3,2,3)
            problem.types[:] = [Real(1,3),Real(0.0005,0.05),Real(0.0005,0.05)]
            problem.constraints[:] = "<=0"
            problem.function = TBTD
            algorithm = NSGAII(problem, p*problem.nvars)
            algorithm.run(40*problem.nvars)
            funcname = 'TBTD'
            nondominated_solutions = nondominated(algorithm.result)
            ref = np.array([0.1,50000])
            obj = []
            for s in nondominated_solutions:
                lijst = str(s.objectives)
                obj.append(ast.literal_eval(lijst))
            obj = np.array(obj)
            hyp.append(hypervolume(obj,ref))
        if np.mean(hyp) > np.mean(hypNS2):
            hypNS2 = hyp
    print(funcname, np.mean(hypNS2), '(', np.std(hypNS2), ')')
    NSGAII_results[funcname] = hypNS2

    hypNS2 = [0]
    random.seed(0)
    for p in [5,8,10,20]:
        hyp = []
        for i in range(100):
            problem = Problem(4,2,5)
            problem.types[:] = [Real(0.125,5),Real(0.1,10),Real(0.1,10),Real(0.125,5)]
            problem.constraints[:] = "<=0"
            problem.function = WB
            algorithm = NSGAII(problem, p*problem.nvars)
            algorithm.run(40*problem.nvars)
            funcname = 'WB'
            nondominated_solutions = nondominated(algorithm.result)
            ref = np.array([350,0.1])
            obj = []
            for s in nondominated_solutions:
                lijst = str(s.objectives)
                obj.append(ast.literal_eval(lijst))
            obj = np.array(obj)
            hyp.append(hypervolume(obj,ref))
        if np.mean(hyp) > np.mean(hypNS2):
            hypNS2 = hyp
    print(funcname, np.mean(hypNS2), '(', np.std(hypNS2), ')')
    NSGAII_results[funcname] = hypNS2

    hypNS2 = [0]
    random.seed(0)
    for p in [5,8,10,20]:
        hyp = []
        for i in range(100):
            problem = Problem(4,2,5)
            problem.types[:] = [Real(55,80),Real(75,110),Real(1000,3000),Real(2,20)]
            problem.constraints[:] = "<=0"
            problem.function = DBD
            algorithm = NSGAII(problem, p*problem.nvars)
            algorithm.run(40*problem.nvars)
            funcname = 'DBD'
            nondominated_solutions = nondominated(algorithm.result)
            ref = np.array([5,50])
            obj = []
            for s in nondominated_solutions:
                lijst = str(s.objectives)
                obj.append(ast.literal_eval(lijst))
            obj = np.array(obj)
            hyp.append(hypervolume(obj,ref))
        if np.mean(hyp) > np.mean(hypNS2):
            hypNS2 = hyp
    print(funcname, np.mean(hypNS2), '(', np.std(hypNS2), ')')
    NSGAII_results[funcname] = hypNS2

    hypNS2 = [0]
    random.seed(0)
    for p in [5,8,10,20]:
        hyp = []
        for i in range(100):
            problem = Problem(2,2,5)
            problem.types[:] = [Real(20,250),Real(10,50)]
            problem.constraints[:] = "<=0"
            problem.function = NBP
            algorithm = NSGAII(problem, p*problem.nvars)
            algorithm.run(40*problem.nvars)
            funcname = 'NBP'
            nondominated_solutions = nondominated(algorithm.result)
            ref =  np.array([11150, 12500])
            obj = []
            for s in nondominated_solutions:
                lijst = str(s.objectives)
                obj.append(ast.literal_eval(lijst))
            obj = np.array(obj)
            hyp.append(hypervolume(obj,ref))
        if np.mean(hyp) > np.mean(hypNS2):
            hypNS2 = hyp
    print(funcname, np.mean(hypNS2), '(', np.std(hypNS2), ')')
    NSGAII_results[funcname] = hypNS2

    hypNS2 = [0]
    random.seed(0)
    for p in [5,8,10,20]:
        hyp = []
        for i in range(100):
            problem = Problem(6,3,9)
            problem.types[:] = [Real(150,274.32),Real(25,32.31),Real(12,22),Real(8,11.71),Real(14,18),Real(0.63,0.75)]
            problem.constraints[:] = "<=0"
            problem.function = SPD
            algorithm = NSGAII(problem, p*problem.nvars)
            algorithm.run(40*problem.nvars)
            funcname = 'SPD'
            nondominated_solutions = nondominated(algorithm.result)
            ref = np.array([16,19000,-260000])
            obj = []
            for s in nondominated_solutions:
                lijst = str(s.objectives)
                obj.append(ast.literal_eval(lijst))
            obj = np.array(obj)
            hyp.append(hypervolume(obj,ref))
        if np.mean(hyp) > np.mean(hypNS2):
            hypNS2 = hyp
    print(funcname, np.mean(hypNS2), '(', np.std(hypNS2), ')')
    NSGAII_results[funcname] = hypNS2

    hypNS2 = [0]
    random.seed(0)
    for p in [5,8,10,20]:
        hyp = []
        for i in range(100):
            problem = Problem(7,3,10)
            problem.types[:] = [Real(0.5,1.5),Real(0.45,1.35),Real(0.5,1.5),Real(0.5,1.5),Real(0.875,2.625),Real(0.4,1.2),Real(0.4,1.2)]
            problem.constraints[:] = "<=0"
            problem.function = CSI
            algorithm = NSGAII(problem, p*problem.nvars)
            algorithm.run(40*problem.nvars)
            funcname = 'CSI'
            nondominated_solutions = nondominated(algorithm.result)
            ref = np.array([42,4.5,13])
            obj = []
            for s in nondominated_solutions:
                lijst = str(s.objectives)
                obj.append(ast.literal_eval(lijst))
            obj = np.array(obj)
            hyp.append(hypervolume(obj,ref))
        if np.mean(hyp) > np.mean(hypNS2):
            hypNS2 = hyp
    print(funcname, np.mean(hypNS2), '(', np.std(hypNS2), ')')
    NSGAII_results[funcname] = hypNS2

    hypNS2 = [0]
    random.seed(0)
    for p in [5,8,10,20]:
        hyp = []
        for i in range(100):
            problem = Problem(3,5,7)
            problem.types[:] = [Real(0.01,0.45),Real(0.01,0.1),Real(0.01,0.1)]
            problem.constraints[:] = "<=0"
            problem.function = WP
            algorithm = NSGAII(problem, p*problem.nvars)
            algorithm.run(40*problem.nvars)
            funcname = 'WP'
            nondominated_solutions = nondominated(algorithm.result)
            ref = np.array([83000, 1350, 2.85, 15989825, 25000])
            obj = []
            for s in nondominated_solutions:
                lijst = str(s.objectives)
                obj.append(ast.literal_eval(lijst))
            obj = np.array(obj)
            hyp.append(hypervolume(obj,ref))
        if np.mean(hyp) > np.mean(hypNS2):
            hypNS2 = hyp
    print(funcname, np.mean(hypNS2), '(', np.std(hypNS2), ')')
    NSGAII_results[funcname] = hypNS2

    hypNS2 = [0]
    random.seed(0)
    for p in [5,8,10,20]:
        hyp = []
        for i in range(100):
            problem = Problem(2,2,2)
            problem.types[:] = [Real(0,5),Real(0,3)]
            problem.constraints[:] = "<=0"
            problem.function = BNH
            algorithm = NSGAII(problem, p*problem.nvars)
            algorithm.run(40*problem.nvars)
            funcname = 'BNH'
            nondominated_solutions = nondominated(algorithm.result)
            ref = np.array([140,50])
            obj = []
            for s in nondominated_solutions:
                lijst = str(s.objectives)
                obj.append(ast.literal_eval(lijst))
            obj = np.array(obj)
            hyp.append(hypervolume(obj,ref))
        if np.mean(hyp) > np.mean(hypNS2):
            hypNS2 = hyp
    print(funcname, np.mean(hypNS2), '(', np.std(hypNS2), ')')
    NSGAII_results[funcname] = hypNS2

    hypNS2 = [0]
    random.seed(0)
    for p in [5,8,10,20]:
        hyp = []
        for i in range(100):
            problem = Problem(2,2,2)
            problem.types[:] = [Real(0.1,1),Real(0,5)]
            problem.constraints[:] = "<=0"
            problem.function = CEXP
            algorithm = NSGAII(problem,  p*problem.nvars)
            algorithm.run(40*problem.nvars)
            funcname = 'CEXP'
            nondominated_solutions = nondominated(algorithm.result)
            ref = np.array([1,9])
            obj = []
            for s in nondominated_solutions:
                lijst = str(s.objectives)
                obj.append(ast.literal_eval(lijst))
            obj = np.array(obj)
            hyp.append(hypervolume(obj,ref))
        if np.mean(hyp) > np.mean(hypNS2):
            hypNS2 = hyp
    print(funcname, np.mean(hypNS2), '(', np.std(hypNS2), ')')
    NSGAII_results[funcname] = hypNS2

    hypNS2 = [0]
    random.seed(0)
    for p in [5,8,10,20]:
        hyp = []
        for i in range(100):
            problem = Problem(6,2,2)
            problem.types[:] = [Real(0,1),Real(0,1),Real(0,1),Real(0,1),Real(0,1),Real(0,1)]
            problem.constraints[:] = "<=0"
            problem.function = C3DTLZ4
            algorithm = NSGAII(problem, p*problem.nvars)
            algorithm.run(40*problem.nvars)
            funcname = 'C3DTLZ4'
            nondominated_solutions = nondominated(algorithm.result)
            ref = np.array([3,3])
            obj = []
            for s in nondominated_solutions:
                lijst = str(s.objectives)
                obj.append(ast.literal_eval(lijst))
            obj = np.array(obj)
            hyp.append(hypervolume(obj,ref))
        if np.mean(hyp) > np.mean(hypNS2):
            hypNS2 = hyp
    print(funcname, np.mean(hypNS2), '(', np.std(hypNS2), ')')
    NSGAII_results[funcname] = hypNS2

    hypNS2 = [0]
    random.seed(0)
    for p in [5,8,10,20]:
        hyp = []
        for i in range(100):
            problem = Problem(2,2,2)
            problem.types[:] = [Real(-20,20),Real(-20,20)]
            problem.constraints[:] = "<=0"
            problem.function = SRN
            algorithm = NSGAII(problem,  p*problem.nvars)
            algorithm.run(40*problem.nvars)
            funcname = 'SRN'
            nondominated_solutions = nondominated(algorithm.result)
            ref = np.array([301,72])
            obj = []
            for s in nondominated_solutions:
                lijst = str(s.objectives)
                obj.append(ast.literal_eval(lijst))
            obj = np.array(obj)
            hyp.append(hypervolume(obj,ref))
        if np.mean(hyp) > np.mean(hypNS2):
            hypNS2 = hyp
    print(funcname, np.mean(hypNS2), '(', np.std(hypNS2), ')')
    NSGAII_results[funcname] = hypNS2

    hypNS2 = [0]
    random.seed(0)
    for p in [5,8,10,20]:
        hyp = []
        for i in range(100):
            problem = Problem(2,2,2)
            problem.types[:] = [Real(1e-5,np.pi),Real(1e-5,np.pi)]
            problem.constraints[:] = "<=0"
            problem.function = TNK
            algorithm = NSGAII(problem,  p*problem.nvars)
            algorithm.run( 40*problem.nvars)
            funcname = 'TNK'
            nondominated_solutions = nondominated(algorithm.result)
            ref = np.array([3,3])
            obj = []
            for s in nondominated_solutions:
                lijst = str(s.objectives)
                obj.append(ast.literal_eval(lijst))
            obj = np.array(obj)
            hyp.append(hypervolume(obj,ref))
        if np.mean(hyp) > np.mean(hypNS2):
            hypNS2 = hyp
    print(funcname, np.mean(hypNS2), '(', np.std(hypNS2), ')')
    NSGAII_results[funcname] = hypNS2

    hypNS2 = [0]
    random.seed(0)
    for p in [5,8,10,20]:
        hyp = []
        for i in range(100):
            problem = Problem(6,2,6)
            problem.types[:] = [Real(0,10),Real(0,10),Real(1,5),Real(0,6),Real(1,5),Real(0,10)]
            problem.constraints[:] = "<=0"
            problem.function = OSY
            algorithm = NSGAII(problem,  p*problem.nvars)
            algorithm.run( 40*problem.nvars)
            funcname = 'OSY'
            nondominated_solutions = nondominated(algorithm.result)
            ref = np.array([0,386])
            obj = []
            for s in nondominated_solutions:
                lijst = str(s.objectives)
                obj.append(ast.literal_eval(lijst))
            obj = np.array(obj)
            hyp.append(hypervolume(obj,ref))
        if np.mean(hyp) > np.mean(hypNS2):
            hypNS2 = hyp
    print(funcname, np.mean(hypNS2), '(', np.std(hypNS2), ')')
    NSGAII_results[funcname] = hypNS2

    hypNS2 = [0]
    random.seed(0)
    for p in [5,8,10,20]:
        hyp = []
        for i in range(100):
            problem = Problem(2,2,2)
            problem.types[:] = [Real(0,1),Real(0,1)]
            problem.constraints[:] = "<=0"
            problem.function = CTP1
            algorithm = NSGAII(problem, p*problem.nvars)
            algorithm.run( 40*problem.nvars)
            funcname = 'CTP1'
            nondominated_solutions = nondominated(algorithm.result)
            ref = np.array([1,2])
            obj = []
            for s in nondominated_solutions:
                lijst = str(s.objectives)
                obj.append(ast.literal_eval(lijst))
            obj = np.array(obj)
            hyp.append(hypervolume(obj,ref))
        if np.mean(hyp) > np.mean(hypNS2):
            hypNS2 = hyp
    print(funcname, np.mean(hypNS2), '(', np.std(hypNS2), ')')
    NSGAII_results[funcname] = hypNS2

    hypNS2 = [0]
    random.seed(0)
    for p in [5,8,10,20]:
        hyp = []
        for i in range(100):
            problem = Problem(10,2,1)
            problem.types[:] = [Real(0,1),Real(0,1),Real(0,1),Real(0,1),Real(0,1),Real(0,1),Real(0,1),Real(0,1),Real(0,1),Real(0,1)]
            problem.constraints[:] = "<=0"
            problem.function = BICOP1
            algorithm = NSGAII(problem, p*problem.nvars)
            algorithm.run(40*problem.nvars)
            funcname = 'BICOP1'
            nondominated_solutions = nondominated(algorithm.result)
            ref = np.array([9,9])
            obj = []
            for s in nondominated_solutions:
                lijst = str(s.objectives)
                obj.append(ast.literal_eval(lijst))
            obj = np.array(obj)
            hyp.append(hypervolume(obj,ref))
        if np.mean(hyp) > np.mean(hypNS2):
            hypNS2 = hyp
    print(funcname, np.mean(hypNS2), '(', np.std(hypNS2), ')')
    NSGAII_results[funcname] = hypNS2

    hypNS2 = [0]
    random.seed(0)
    for p in [5,8,10,20]:
        hyp = []
        for i in range(100):
            problem = Problem(10,2,2)
            problem.types[:] = [Real(0,1),Real(0,1),Real(0,1),Real(0,1),Real(0,1),Real(0,1),Real(0,1),Real(0,1),Real(0,1),Real(0,1)]
            problem.constraints[:] = "<=0"
            problem.function = BICOP2
            algorithm = NSGAII(problem, p*problem.nvars)
            algorithm.run(40*problem.nvars)
            funcname = 'BICOP2'
            nondominated_solutions = nondominated(algorithm.result)
            ref = np.array([70,70])
            obj = []
            for s in nondominated_solutions:
                lijst = str(s.objectives)
                obj.append(ast.literal_eval(lijst))
            obj = np.array(obj)
            hyp.append(hypervolume(obj,ref))
        if np.mean(hyp) > np.mean(hypNS2):
            hypNS2 = hyp
    print(funcname, np.mean(hypNS2), '(', np.std(hypNS2), ')')
    NSGAII_results[funcname] = hypNS2

    hypNS2 = [0]
    random.seed(0)
    for p in [5,8,10,20]:
        hyp = []
        for i in range(100):
            problem = Problem(2,3,3)
            problem.types[:] = [Real(-4,4),Real(-4,4)]
            problem.constraints[:] = "<=0"
            problem.function = TRICOP
            algorithm = NSGAII(problem, p*problem.nvars)
            algorithm.run(40*problem.nvars)
            funcname = 'TRICOP'
            nondominated_solutions = nondominated(algorithm.result)
            ref = np.array([34,-4,90])
            obj = []
            for s in nondominated_solutions:
                lijst = str(s.objectives)
                obj.append(ast.literal_eval(lijst))
            obj = np.array(obj)
            hyp.append(hypervolume(obj,ref))
        if np.mean(hyp) > np.mean(hypNS2):
            hypNS2 = hyp
    print(funcname, np.mean(hypNS2), '(', np.std(hypNS2), ')')
    NSGAII_results[funcname] = hypNS2

    return NSGAII_results
Exemple #2
0
from platypus import NSGAII, DTLZ2

# define the problem definition
problem = DTLZ2()

# instantiate the optimization algorithm
algorithm = NSGAII(problem)

# optimize the problem using 10,000 function evaluations
algorithm.run(10000)

# display the results
for solution in algorithm.result:
    print(solution.objectives)
    mmax = 1000.0
    problem = Problem(2,2,1)
    problem.types[:] = [Real(umin_min,umin_max),Real(mmin,mmax)]
    problem.constraints[:] = "<=0"
    problem.function = uswitch_objective

    # Run optimization in parallel
    n_proc = 4
    n_evals = 100000
    alg_name = 'NSGAII'
    #alg_name = 'NSGAIII'
    #alg_name = 'SPEA2'
    start_time = time.time()
    with ProcessPoolEvaluator(n_proc) as evaluator:
        if alg_name=='NSGAII':
            algorithm = NSGAII(problem,evaluator=evaluator)
        elif alg_name=='NSGAIII':
            divs = 20
            alg_name=alg_name+str(divs)
            algorithm = NSGAIII(problem,divisions_outer=div,evaluator=evaluator)
        elif alg_name=='SPEA2':
            algorithm = SPEA2(problem,evaluator=evaluator)
        else:
            print("Using NSGAII algorithm by default")
            algorithm = NSGAII(problem,evaluator=evaluator)
        algorithm.run(n_evals)
    print("Total run time = {:.2f} hours".format((time.time()-start_time)/3600.))

    # Save Results
    save_dir = "./Data/U_switch/plat/"
    pareto_file_name = save_dir + "pareto_front_{0}_{1}_{2}_".format(d,tau_p,n_evals) + alg_name + "_dtmax{0}.npy".format(dtmax)
Exemple #4
0
def grid_multi_GA(nx=20,
                  ny=20,
                  volume_frac=0.5,
                  parent=400,
                  generation=100,
                  path="data"):
    PATH = os.path.join(path, "grid_nx_{}_ny_{}".format(nx, ny),
                        "gen_{}_pa_{}".format(generation, parent))
    os.makedirs(PATH, exist_ok=True)
    start = time.time()

    def objective(vars):
        rho = np.array(vars)
        rho = rho.reshape(ny, nx - 1)
        rho = np.concatenate([rho, np.ones((ny, 1))], 1)
        volume = np.sum(rho) / (nx * ny)

        return [calc_E(rho), calc_G(rho)], [volume]

    # 2変数2目的の問題
    problem = Problem(ny * (nx - 1), 2, 1)
    # 最小化or最大化を設定
    problem.directions[:] = Problem.MAXIMIZE

    # 決定変数の範囲を設定
    int1 = Integer(0, 1)
    problem.types[:] = int1
    problem.constraints[:] = "<=" + str(volume_frac)
    problem.function = objective
    problem.directions[:] = Problem.MAXIMIZE
    algorithm = NSGAII(problem, population_size=parent)
    algorithm.run(generation)

    # グラフを描画

    fig = plt.figure()
    plt.scatter([s.objectives[0] for s in algorithm.result],
                [s.objectives[1] for s in algorithm.result],
                c="blue",
                label="infeasible solution")

    plt.scatter([s.objectives[0] for s in algorithm.result if s.feasible],
                [s.objectives[1] for s in algorithm.result if s.feasible],
                c="red",
                label='feasible solution')

    # 非劣解をとりだす
    nondominated_solutions = nondominated(algorithm.result)
    plt.scatter(
        [s.objectives[0] for s in nondominated_solutions if s.feasible],
        [s.objectives[1] for s in nondominated_solutions if s.feasible],
        c="green",
        label="pareto solution")
    plt.legend(loc='lower left')

    plt.xlabel("$E$")
    plt.ylabel("$G$")
    fig.savefig(os.path.join(PATH, "graph.png"))
    plt.close()

    for solution in [s for s in nondominated_solutions if s.feasible]:
        image_list = []
        for j in solution.variables:
            image_list.append(j)
        image = np.array(image_list).reshape(ny, nx - 1)
        image = np.concatenate([image, np.ones((ny, 1))], 1)
        np.save(
            os.path.join(
                PATH, 'E_{}_G_{}.npy'.format(solution.objectives[0],
                                             solution.objectives[1])), image)

    convert_folder_npy_to_image(PATH)

    elapsed_time = time.time() - start

    with open("time.txt", mode='a') as f:
        f.writelines("grid_nx_{}_ny_{}_gen_{}_pa_{}:{}sec\n".format(
            nx, ny, generation, parent, elapsed_time))
Exemple #5
0
from platypus import NSGAII, Problem, Integer
import CustomProblem

algorithm = NSGAII(CustomProblem.my_mo_problem())
algorithm.run(2000)

feasible_solutions = [s for s in algorithm.result if s.feasible]

# plot the results using matplotlib
'''
import matplotlib.pyplot as plt

plt.scatter([s.objectives[0] for s in feasible_solutions],
            [s.objectives[1] for s in feasible_solutions])
plt.xlabel("$PRI(x)$")
plt.ylabel("$Cost(x)$")
plt.show()
'''
Exemple #6
0
def N_Rp_Op():
    def Op_ABC(C_all_points):
        #len(C_all_points) = 10 (2 * Num_of_Points)
        #    for i in range(len(C_all_points)/2):
        #        i = i * 2
        #        print C_all_points[i],',',C_all_points[i+1]
        #    print ' '

        #Point in Polygon?
        for i in range(len(C_all_points) / 2):
            i = i * 2
            if g.point_in_polygon(
                    vg.Point(C_all_points[i], C_all_points[i + 1])) == -1:
                pass
            else:
                return float('inf'), float('inf'), float('inf')
        #change[a,b,c,d] to [[a,b],[c,d]]
        CABC_all_points = []
        for i in range(len(C_all_points) / 2):
            i = i * 2
            Temp_CABC = [C_all_points[i], C_all_points[i + 1]]
            CABC_all_points.append(Temp_CABC)

        ap = [Point(p) for p in CABC_all_points]
        co = [LRF_(p.x, p.y, Radius) for p in ap]
        #A: The intersect part of path coverage (Enclude polygons)
        Sa = getIntersection(co).area
        #B:  The rest of the map's area except path coverage
        Sb = getUnscanned(co).area

        #C: The shortest distance
        def Dis_PosC(x):
            Dist_ = 0
            Store_Comb = []
            Permutation_list = []
            list_ = []
            for i in range(len(C_all_points) / 2):
                list_.append(i)
            list_Num = len(list_)
            x_list = []

            for i in range(len(C_all_points) / 2):
                x[i] = math.floor(x[i])
                x_list.append(int(round(x[i])))

            for i in range(list_Num):
                Permutation_list.append(list_[x_list[i]])
                del list_[x_list[i]]

    #        for i in range(len(C_all_points)/2):
    #            print Permutation_list[i]
    #        print ' '
            for i in range(len(C_all_points) / 2):
                Store_Comb.append(CABC_all_points[Permutation_list[i]])

            for i in range(len(C_all_points) / 2 - 1):
                Dis_0 = vg.Point(Store_Comb[i][0], Store_Comb[i][1])
                Dis_1 = vg.Point(Store_Comb[i + 1][0], Store_Comb[i + 1][1])
                Dist = g.shortest_path(Dis_0, Dis_1)
                _Dist_ = LineString(sp2list(Dist)).length
                Dist_ = Dist_ + _Dist_
            return Dist_

        bounds_C = []
        for i in range(len(C_all_points) / 2):
            bounds_C.append((0.1, len(C_all_points) / 2 - i - 0.1))
        Nearest_Dis = differential_evolution(Dis_PosC,
                                             bounds_C,
                                             maxiter=5,
                                             polish=False)
        Dc = Nearest_Dis.fun
        #        for i in range(len(C_all_points)/2):
        #            New_Nearest_Dis.append(Nearest_Dis.x[i])

        #A - Sa; B - Sb; C - Dc
        return Sa, Sb, Dc

    min_x = po.bounds[0] + 10
    max_x = po.bounds[2] - 10
    min_y = po.bounds[1] + 10
    max_y = po.bounds[3] - 10
    Store_Adjust_fun = []
    Store_Adjust_x = []

    for Num_of_Random_ in range(3, 7):
        Num_of_Random = Num_of_Random_
        print Num_of_Random
        bounds_ABC = []
        for i in range(Num_of_Random * 2):
            if (i % 2 == 0):
                bounds_ABC.append((min_x, max_x))
            else:
                bounds_ABC.append((min_y, max_y))

        problem = Problem(Num_of_Random_ * 2, 3)
        problem.types = []
        for i in range(Num_of_Random_ * 2):
            if (i % 2 == 0):
                problem.types.append(Real(min_x, max_x))
            else:
                problem.types.append(Real(min_y, max_y))

        problem.function = Op_ABC
        #Execute MO-NSGAII
        algorithm = NSGAII(problem)
        algorithm.run(1000)
        # display the results
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1, projection='3d')
        ax.scatter([s.objectives[0] for s in algorithm.result],
                   [s.objectives[1] for s in algorithm.result],
                   [s.objectives[2] for s in algorithm.result])
        ax.set_title(algorithm)
        ax.set_xlim([0, 6000])
        ax.set_ylim([0, 6000])
        ax.set_zlim([0, 250])
        ax.view_init(elev=30.0, azim=45.0)
        ax.locator_params(nbins=6)
        plt.show()
        # display the results
        Result_Random_fun = []
        Result_Random_x = []
        for solution in algorithm.result:
            Result_Random_fun.append(solution.objectives)
            Result_Random_x.append(solution.variables)

        Show_Result_Random_fun = []
        Add_Result_Random_fun = []
        for i in range(100):
            Show_Result_Random_fun.append([
                Result_Random_fun[i][0], Result_Random_fun[i][1],
                Result_Random_fun[i][2]
            ])
            Add_Result_Random_fun.append(Result_Random_fun[i][0] +
                                         Result_Random_fun[i][1] +
                                         Result_Random_fun[i][2])
        #Find the minimum
        Min_Result_Random_x = Add_Result_Random_fun.index(
            min(Add_Result_Random_fun))
        Store_Adjust_x.append(Result_Random_x[Min_Result_Random_x])
        Store_Adjust_fun.append(Add_Result_Random_fun[Min_Result_Random_x])
    #Find the Global minimum
    GlobalMin_Result_Random_x = Store_Adjust_fun.index(min(Store_Adjust_fun))
    Adjust_x.append(Store_Adjust_x[GlobalMin_Result_Random_x])

    print Adjust_x

    return Adjust_x
Exemple #7
0
    print('cego', funcName, np.mean(gdCEGO))


problem = Problem(7, 2, 11)
problem.types[:] = [
    Real(2.6, 3.6),
    Real(0.7, 0.8),
    Real(17, 28),
    Real(7.3, 8.3),
    Real(7.3, 8.3),
    Real(2.9, 3.9),
    Real(5, 5.5)
]
problem.constraints[:] = "<=0"
problem.function = SRD
algorithm = NSGAII(problem, 200)
algorithm.run(100000)
funcname = 'SRD'
nondominated_solutions = nondominated(algorithm.result)
ref = np.array([7000, 1700])
refPF = []
for s in nondominated_solutions:
    lijst = str(s.objectives)
    refPF.append(ast.literal_eval(lijst))
refPF = np.array(refPF)
doMeasurement(refPF, funcname, ref)

problem = Problem(3, 2, 3)
problem.types[:] = [Real(1, 3), Real(0.0005, 0.05), Real(0.0005, 0.05)]
problem.constraints[:] = "<=0"
problem.function = TBTD
    ProcessPoolExecutor(max_workers=8)
    print("-------EMSGMOP:")
    problem = EMSGMOP_problem(n, m, s_i, SA_i, p_i, d_hat_j_tmp, t_hat_ij_tmp,
                              d_ij, e_ij, theat_ij, fr_ij)

    # 默认求最小目标值
    problem.directions[:] = Problem.MINIMIZE

    # algorithm = EpsMOEA(problem, epsilons=0.5)
    # algorithm = MOEAD(problem)
    # algorithm = SMPSO(problem)
    # algorithm = OMOPSO(problem, epsilons=0.5)
    # algorithm  = EpsNSGAII(problem, epsilons=0.5)
    # algorithm = SPEA2(problem)
    # algorithm = GDE3(problem)
    algorithm = NSGAII(problem)
    # algorithm = NSGAIII(problem,divisions_outer=25)
    algorithm.population_size = 10
    algorithm.run(Algorithm_Run_NUM)

    # feasible_solutions = [s for s in algorithm.result if s.feasible]
    # if len(feasible_solutions) > 0:
    #     print(feasible_solutions.objectives)
    # print("------------------")

    # print("Population size: ")
    # print(len(algorithm.result))
    # # The output shows on each line the objectives for a Pareto optimal solution:
    # for solution in algorithm.result:
    #     print(solution.variables)
Exemple #9
0
    Model_Input = (S0, I0, 0.0)

    # GA Parameters
    number_of_generations = 10000
    ga_population_size = 100
    number_of_objective_targets = 1  # The MSE
    number_of_constraints = 0
    number_of_input_variables = 2  # beta and gamma
    problem = Problem(number_of_input_variables, number_of_objective_targets,
                      number_of_constraints)
    problem.function = functools.partial(fitness_function,
                                         model=model,
                                         Model_Input=Model_Input,
                                         t_range=t_range)

    algorithm = NSGAII(problem, population_size=ga_population_size)

    problem.types[0] = Real(0, 1)  # beta initial Range
    problem.types[1] = Real(1 / 5, 1 / 14)  # gamma initial Range

    # Running the GA
    algorithm.run(number_of_generations)

    # Getting the feasible solutions only just to be safe
    # The GA may generate bad solutions if number_of_generations is not enough or there are too many contraints
    feasible_solutions = [s for s in algorithm.result if s.feasible]

    beta = feasible_solutions[0].variables[0]
    print('Beta Optimsed = {}'.format(beta))
    gamma = feasible_solutions[0].variables[1]
    print('Gamma Optimsed = {}'.format(gamma))
Exemple #10
0
def my_graph(points, edges):
    global n_dim
    global fig
    number = 0
    d1 = pd.read_csv(points)
    d2 = pd.read_csv(edges)
    n_dim = len(d1.columns)
    m1 = 'MDS'
    m2 = 'MOPSO-NSGAII'
    m3 = 'MOPSO-NSGAIII'

    # ## MDS
    mds = MDS(n_components=2)
    dat = pd.DataFrame(mds.fit(d1).embedding_, columns=["x1", "x2"])

    dij = manhattan_distances(d1.values, d1.values)
    dis2 = manhattan_distances(dat.values, dat.values)
    mds_stress = (np.sum((dij - dis2)**2))**0.5
    mds_inter = number_of_intersection(dat["x1"], dat["x2"], d2)
    graph(dat, d2, m1, number, 1, mds_stress, mds_inter)
    print "MDS Stress : ", mds_stress
    print "Total Intersection MDS = ", mds_inter

    # ## Multi Objective Particle Swarm Optimization (MOPSO)
    def objective_mopso(x):
        twoD = np.reshape(x, (-1, 2))
        dis = manhattan_distances(twoD, twoD)
        stress = (np.sum((dij - dis)**2))**0.5
        mopso_inter = number_of_intersection(x[0:][::2], x[1:][::2], d2)
        return [stress, mopso_inter]

    problem = Problem(len(d1) * 2, 2)
    problem.types[:] = Real(-50, 50)
    problem.function = objective_mopso

    ngsaii = NSGAII(problem, population_size=100)
    ngsaii.run(10000)
    result = ngsaii.result

    ngsaiii = NSGAIII(problem, population_size=100, divisions_outer=100)
    ngsaiii.run(10000)
    result2 = ngsaiii.result

    ax = fig.add_subplot(1, 4, 4)

    lngsaii = plt.scatter([s.objectives[0] for s in ngsaii.result],
                          [s.objectives[1] for s in ngsaii.result],
                          color='b')
    lngsaiii = plt.scatter([s.objectives[0] for s in ngsaiii.result],
                           [s.objectives[1] for s in ngsaiii.result],
                           color='g')
    lmds, = plt.plot(mds_stress, mds_inter, 'ro', markersize=8)
    y_min, y_max = ax.get_ylim()
    x_min, x_max = ax.get_xlim()
    plt.xticks(
        np.arange(math.floor(x_min), math.ceil(x_max),
                  math.ceil((math.ceil(x_max) - math.ceil(x_min)) / 5)))

    if math.ceil(y_min) == math.floor(y_max):
        plt.yticks(np.arange(math.ceil(y_min - 1.1), math.ceil(y_max + 1.1),
                             1))
    else:
        plt.yticks(
            np.arange(
                math.floor(y_min - .1), math.ceil(y_max + .1),
                math.ceil(
                    (math.ceil(y_max + .1) - math.ceil(y_min - .1)) / 5)))

    plt.savefig('./output/graph' + str(number) + '.png', bbox_inches='tight')

    count = 0
    out = {}
    ngsaii_inter = result[0].objectives[1]
    ngsaii_stress = result[0].objectives[0]
    val = 0
    for solution in ngsaii.result:
        out[solution.objectives] = solution.variables
        if solution.objectives[1] < ngsaii_inter:
            ngsaii_inter = solution.objectives[1]
            ngsaii_stress = solution.objectives[0]
            val = count
        count += 1
    sample = out[result[val].objectives]
    x = sample[0:][::2]
    y = sample[1:][::2]
    newD = pd.DataFrame({"x1": x, "x2": y})
    print "Stress for NGSAII = ", ngsaii_stress
    print "Total Intersection NGSAII = ", ngsaii_inter
    graph(newD, d2, m2, number, 2, ngsaii_stress, ngsaii_inter)

    count = 0
    out = {}
    ngsaiii_inter = result2[0].objectives[1]
    ngsaiii_stress = result2[0].objectives[0]
    val = 0
    for solution in ngsaiii.result:
        out[solution.objectives] = solution.variables
        if solution.objectives[1] < ngsaiii_inter:
            ngsaiii_inter = solution.objectives[1]
            ngsaiii_stress = solution.objectives[0]
            val = count
        count += 1
    sample = out[result2[val].objectives]
    x = sample[0:][::2]
    y = sample[1:][::2]
    newD = pd.DataFrame({"x1": x, "x2": y})
    print "Stress for NGSAIII = ", ngsaiii_stress
    print "Total Intersection NGSAIII = ", ngsaiii_inter
    graph(newD, d2, m3, number, 3, ngsaiii_stress, ngsaiii_inter)
Exemple #11
0
                            state,
                            g(0),
                            num_steps,
                            energy_weight=0.0,
                            max_energy=4.439301)

problem = Problem(6 * num_steps, 2)
problem.types[:3 * num_steps] = Real(0, pi)
problem.types[3 * num_steps:] = Real(-pi, pi)
problem.function = lambda p: (optim.infidelity(array(p)),
                              optim.param_vec_energy(array(p)) / 1.9169321)

# instantiate the optimization algorithm

# optimize the problem using 10,000 function evaluations

# plot the results using matplotlib
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
algorithm = NSGAII(problem)
algorithm.run(10000)
ax.scatter([s.objectives[0] for s in algorithm.result],
           [s.objectives[1] for s in algorithm.result])
algorithm = NSGAII(problem, population_size=200)
algorithm.run(20000)
ax.scatter([s.objectives[0] for s in algorithm.result],
           [s.objectives[1] for s in algorithm.result])
ax.set_xlabel("$f_1(x)$")
ax.set_ylabel("$f_2(x)$")

fig.show()
    def fit(self, x, y, bound=None, name=''):

        self.y = np.array(y)
        self.x = x

        TS = 1
        ND = len(y) - 1

        t_start = 0.0
        t_end = ND
        t_inc = TS
        t_range = np.arange(t_start, t_end + t_inc, t_inc)

        Model_Input = (self.S0,self.E0,self.Q0,self.I0,self.J0, \
                       self.R0,self.N0,self.D0)

        input_variables = [
            'beta', 'epsilon_E', 'epsilon_Q', 'epsilon_J', 'Pi', 'mu', 'v',
            'gamma1', 'gamma2', 'kappa1', 'kappa2', 'd1', 'd2', 'sigma1',
            'sigma2'
        ]

        number_of_generations = 1000
        ga_population_size = 100
        number_of_objective_targets = 1
        number_of_constraints = 0
        number_of_input_variables = len(input_variables)

        problem = Problem(number_of_input_variables,
                          number_of_objective_targets, number_of_constraints)

        problem.types[0] = Real(
            0, 0.4
        )  # beta      - Infectiousness and contact rate between a susceptible and an infectious individual
        problem.types[1] = Real(
            0, 0.5
        )  # epsilon_E - Modification parameter associated with infection from an exposed asymptomatic individual
        problem.types[2] = Real(
            0, 0.5
        )  # epsilon_Q - Modification parameter associated with infection from a quarantined individual
        problem.types[3] = Real(
            0, 1
        )  # epsilon_J - Modification parameter associated with infection from an isolated individual
        problem.types[4] = Real(
            0, 500
        )  # Pi        - Rate of inflow of susceptible individuals into a region or community through birth or migration.
        problem.types[5] = Real(
            0, 0.00005
        )  # mu        - The natural death rate for disease-free individuals
        problem.types[6] = Real(
            0,
            0.1)  # v         - Rate of immunization of susceptible individuals
        problem.types[7] = Real(
            0, 0.3
        )  # gamma1    - Rate of quarantine of exposed asymptomatic individuals
        problem.types[8] = Real(
            0, 0.7
        )  # gamma2    - Rate of isolation of infectious symptomatic individuals
        problem.types[9] = Real(
            0, 0.3
        )  # kappa1    - Rate of development of symptoms in asymptomatic individuals
        problem.types[10] = Real(
            0, 0.3
        )  # kappa2    - Rate of development of symptoms in quarantined individuals
        problem.types[11] = Real(
            0, 0.1
        )  # d1        - Rate of disease-induced death for symptomatic individuals
        problem.types[12] = Real(
            0, 0.1
        )  # d2        - Rate of disease-induced death for isolated individuals
        problem.types[13] = Real(
            0, 0.1)  # sigma1    - Rate of recovery of symptomatic individuals
        problem.types[14] = Real(
            0, 0.1)  # sigma2    - Rate of recovery of isolated individuals

        problem.function = functools.partial(self.fitness_function,
                                             y=y,
                                             Model_Input=Model_Input,
                                             t_range=t_range)
        algorithm = NSGAII(problem, population_size=ga_population_size)
        algorithm.run(number_of_generations)

        feasible_solutions = [s for s in algorithm.result if s.feasible]

        self.beta = feasible_solutions[0].variables[
            0]  # Infectiousness and contact rate between a susceptible and an infectious individual
        self.epsilon_E = feasible_solutions[0].variables[
            1]  # Modification parameter associated with infection from an exposed asymptomatic individual
        self.epsilon_Q = feasible_solutions[0].variables[
            2]  # Modification parameter associated with infection from a quarantined individual
        self.epsilon_J = feasible_solutions[0].variables[
            3]  # Modification parameter associated with infection from an isolated individual
        self.Pi = feasible_solutions[0].variables[
            4]  # Rate of inflow of susceptible individuals into a region or community through birth or migration.
        self.mu = feasible_solutions[0].variables[
            5]  # The natural death rate for disease-free individuals
        self.v = feasible_solutions[0].variables[
            6]  # Rate of immunization of susceptible individuals
        self.gamma1 = feasible_solutions[0].variables[
            7]  # Rate of quarantine of exposed asymptomatic individuals
        self.gamma2 = feasible_solutions[0].variables[
            8]  # Rate of isolation of infectious symptomatic individuals
        self.kappa1 = feasible_solutions[0].variables[
            9]  # Rate of development of symptoms in asymptomatic individuals
        self.kappa2 = feasible_solutions[0].variables[
            10]  # Rate of development of symptoms in quarantined individuals
        self.d1 = feasible_solutions[0].variables[
            11]  # Rate of disease-induced death for symptomatic individuals
        self.d2 = feasible_solutions[0].variables[
            12]  # Rate of disease-induced death for isolated individuals
        self.sigma1 = feasible_solutions[0].variables[
            13]  # Rate of recovery of symptomatic individuals
        self.sigma2 = feasible_solutions[0].variables[
            14]  # Rate of recovery of isolated individuals

        self.DS = self.mu + self.v
        self.DE = self.gamma1 + self.kappa1 + self.mu
        self.DI = self.gamma2 + self.d1 + self.sigma1 + self.mu
        self.DJ = self.sigma2 + self.d2 + self.mu
        self.DQ = self.mu + self.kappa2

        file_address = 'optimised_coefficients/'
        filename = "ParametrosAjustados_Modelo_{}_{}_{}_Dias.txt".format(
            'SEQIJR_EDO', name, len(x))
        if not os.path.exists(file_address):
            os.makedirs(file_address)
        file_optimised_parameters = open(file_address + filename, "w")
        file_optimised_parameters.close()

        with open(file_address + filename, "a") as file_optimised_parameters:
            for i in range(len(input_variables)):
                message = '{}:{:.4f}\n'.format(
                    input_variables[i], feasible_solutions[0].variables[i])
                file_optimised_parameters.write(message)
    def fit(self, x, y, bound=None, name=''):

        self.y = np.array(y)
        self.x = x

        TS = 1
        ND = len(y) - 1

        t_start = 0.0
        t_end = ND
        t_inc = TS
        t_range = np.arange(t_start, t_end + t_inc, t_inc)

        INPUT = (self.S, self.I, self.E, self.D, self.C, self.R, self.N)

        input_variables = [
            'beta0', 'alpha', 'kappa', 'gamma', 'sigma', 'lamb', 'mu', 'd'
        ]

        # GA Parameters
        number_of_generations = 1000
        ga_population_size = 100
        number_of_objective_targets = 1
        number_of_constraints = 0
        number_of_input_variables = len(input_variables)

        problem = Problem(number_of_input_variables,
                          number_of_objective_targets, number_of_constraints)

        problem.types[0] = Real(0, 2)  #beta0
        problem.types[1] = Real(0, 2)  #alpha
        problem.types[2] = Real(0, 2000)  #kappa
        problem.types[3] = Real(0, 2)  #gamma
        problem.types[4] = Real(0, 2)  #sigma
        problem.types[5] = Real(0, 2)  #lamb
        problem.types[6] = Real(0, 2)  #mu
        problem.types[7] = Real(0, 2)  #d

        problem.function = functools.partial(self.fitness_function,
                                             y=y,
                                             Model_Input=INPUT,
                                             t_range=t_range)
        algorithm = NSGAII(problem, population_size=ga_population_size)
        algorithm.run(number_of_generations)

        feasible_solutions = [s for s in algorithm.result if s.feasible]

        self.beta0 = feasible_solutions[0].variables[0]
        self.alpha = feasible_solutions[0].variables[1]
        self.kappa = feasible_solutions[0].variables[2]
        self.gamma = feasible_solutions[0].variables[3]
        self.sigma = feasible_solutions[0].variables[4]
        self.lamb = feasible_solutions[0].variables[5]
        self.mu = feasible_solutions[0].variables[6]
        self.d = feasible_solutions[0].variables[7]

        file_address = 'optimised_coefficients/'
        filename = "ParametrosAjustados_Modelo_{}_{}_{}_Dias.txt".format(
            'SEIR_EDO', name, len(x))
        if not os.path.exists(file_address):
            os.makedirs(file_address)
        file_optimised_parameters = open(file_address + filename, "w")
        file_optimised_parameters.close()

        with open(file_address + filename, "a") as file_optimised_parameters:
            for i in range(len(input_variables)):
                message = '{}:{:.4f}\n'.format(
                    input_variables[i], feasible_solutions[0].variables[i])
                file_optimised_parameters.write(message)

        result_fit = spi.odeint(
            self.SEIR_diff_eqs,
            (self.S, self.I, self.E, self.D, self.C, self.R, self.N),
            t_range,
            args=(self.beta0, self.alpha, self.kappa, self.gamma, self.sigma,
                  self.lamb, self.mu, self.d))

        plt.plot(result_fit[:, 1], c='b', label='Predição Infectados')
        plt.plot(self.y, c='r', marker='o', markersize=3, label='Infectados')
        plt.legend(fontsize=15)
        plt.ylabel('Casos COnfirmados', fontsize=15)
        plt.xlabel('Dias', fontsize=15)
        plt.show()
Exemple #14
0

class AM(Problem):
    def __init__(self):
        # we call Problem(2, 2, 2) to create a problem with
        # two decision variables, two objectives, and two constraints, respectively
        super(AM, self).__init__(3, 2)
        self.types[:] = [Real(210, 280), Real(15, 50), Real(0.42, 0.7)]
        # self.constraints[:] = "<=0"

    def evaluate(self, solution):
        t = solution.variables[0]
        v = solution.variables[1]
        h = solution.variables[2]
        solution.objectives[:] = BNN_BL_obj(np.array([t, v, h]))
        # solution.constraints[:] = [-x + y - 1, x + y - 7]


algorithm = NSGAII(AM())
algorithm.run(1000)

# plot the results using matplotlib
import matplotlib.pyplot as plt

plt.scatter([-s.objectives[0] for s in algorithm.result],
            [s.objectives[1] for s in algorithm.result])
# plt.xlim([0, 1.1])
# plt.ylim([0, 1.1])
plt.xlabel("$f_1(x)$")
plt.ylabel("$f_2(x)$")
plt.show()
Exemple #15
0
    def __init__(self,
                 problem,
                 epsilons,
                 population_size=100,
                 generator=RandomGenerator(),
                 selector=TournamentSelector(2),
                 variator=None,
                 **kwargs):

        L = len(problem.nvars)
        p = 1 / L

        # Parameterization taken from
        # Borg: An Auto-Adaptive MOEA Framework - Hadka, Reed
        variators = [
            GAOperator(SBX(probability=1.0, distribution_index=15.0),
                       PM(probability=p, distribution_index=20.0)),
            GAOperator(PCX(nparents=3, noffspring=2, eta=0.1, zeta=0.1),
                       PM(probability=p, distribution_index=20.0)),
            GAOperator(
                DifferentialEvolution(crossover_rate=0.6, step_size=0.6),
                PM(probability=p, distribution_index=20.0)),
            GAOperator(
                UNDX(nparents=3,
                     noffspring=2,
                     zeta=0.5,
                     eta=0.35 / math.sqrt(L)),
                PM(probability=p, distribution_index=20.0)),
            GAOperator(
                SPX(nparents=L + 1,
                    noffspring=L + 1,
                    expansion=math.sqrt(L + 2)),
                PM(probability=p, distribution_index=20.0)),
            UM(probability=1 / L)
        ]

        variator = Multimethod(self, variators)

        super(GenerationalBorg, self).__init__(
            NSGAII(problem, population_size, generator, selector, variator,
                   EpsilonBoxArchive(epsilons), **kwargs))

        # class GeneAsGenerationalBorg(EpsilonProgressContinuation):
        #     '''A generational implementation of the BORG Framework, combined with
        #     the GeneAs appraoch for heterogenously typed decision variables
        #
        #     This algorithm adopts Epsilon Progress Continuation, and Auto Adaptive
        #     Operator Selection, but embeds them within the NSGAII generational
        #     algorithm, rather than the steady state implementation used by the BORG
        #     algorithm.
        #
        #     Note:: limited to RealParameters only.
        #
        #     '''
        #
        #     # TODO::
        #     # Addressing the limitation to RealParameters is non-trivial. The best
        #     # option seems to be to extent MultiMethod. Have a set of GAoperators
        #     # for each datatype.
        #     # next Iterate over datatypes and apply the appropriate operator.
        #     # Implementing this in platypus is non-trivial. We probably need to do some
        #     # dirty hacking to create 'views' on the relevant part of the
        #     # solution that is to be modified by the operator
        #     #
        #     # A possible solution is to create a wrapper class for the operators
        #     # This class would create the 'view' on the solution. This view should
        #     # also have a fake problem description because the number of
        #     # decision variables is sometimes used by operators. After applying the
        #     # operator to the view, we can than take the results and set these on the
        #     # actual solution
        #     #
        #     # Also: How many operators are there for Integers and Subsets?
        #
        #     def __init__(self, problem, epsilons, population_size=100,
        #                  generator=RandomGenerator(), selector=TournamentSelector(2),
        #                  variator=None, **kwargs):
        #
        #         L = len(problem.parameters)
        #         p = 1/L
        #
        #         # Parameterization taken from
        #         # Borg: An Auto-Adaptive MOEA Framework - Hadka, Reed
        #         real_variators = [GAOperator(SBX(probability=1.0, distribution_index=15.0),
        #                                PM(probability=p, distribution_index=20.0)),
        #                     GAOperator(PCX(nparents=3, noffspring=2, eta=0.1, zeta=0.1),
        #                                PM(probability =p, distribution_index=20.0)),
        #                     GAOperator(DifferentialEvolution(crossover_rate=0.6,
        #                                                      step_size=0.6),
        #                                PM(probability=p, distribution_index=20.0)),
        #                     GAOperator(UNDX(nparents= 3, noffspring=2, zeta=0.5,
        #                                     eta=0.35/math.sqrt(L)),
        #                                PM(probability= p, distribution_index=20.0)),
        #                     GAOperator(SPX(nparents=L+1, noffspring=L+1,
        #                                    expansion=math.sqrt(L+2)),
        #                                PM(probability=p, distribution_index=20.0)),
        #                     UM(probability = 1/L)]
        #
        #         # TODO
        #         integer_variators = []
        #         subset_variators = []
        #
        #         variators = [VariatorWrapper(variator) for variator in real_variators]
        #         variator = Multimethod(self, variators)
        #
        #         super(GenerationalBorg, self).__init__(
        #                 NSGAII(problem,
        #                        population_size,
        #                        generator,
        #                        selector,
        #                        variator,
        #                        EpsilonBoxArchive(epsilons),
        #                        **kwargs))
        #
        #
        # class VariatorWrapper(object):
        #     def __init__(self, actual_variator, indices, problem):
        #         '''
        #
        #         Parameters
        #         ----------
        #         actual_variator : underlying GAOperator
        #         indices : np.array
        #                   indices to which the variator should be applied
        #         probem :  a representation of the problem considering only the
        #                   same kind of Parameters
        #
        #         '''
        #         self.variator = actual_variator
        #         self.indices = indices
        #
        #     def evolve(self, parents):

        fake_parents = [self.create_view[p] for p in parents]
        fake_children = self.variator.evolve(fake_parents)

        # tricky, no 1 to 1 mapping between parents and children
        # some methods have 3 parents, one child
        children = [map_back]

        pass
Exemple #16
0
def test_platypus_nsgaii_step(two_reservoir_constrained_problem):
    """Undertake a single step of the NSGAII algorithm with a small population."""
    algorithm = NSGAII(two_reservoir_constrained_problem.problem,
                       population_size=10)
    algorithm.step()
Exemple #17
0
def run2():
    problem = Problem(40, 3)
    #输入上述每个LID的可变规模区间——交互输入,如lid1=(x,y)x为面积下限,y为上限
    problem.types[:] = [
        Real(1000, 6500),
        Real(1000, 6400),
        Real(1000, 4200),
        Real(1000, 4600),
        Real(700, 3000),
        Real(1000, 7450),
        Real(2000, 9500),
        Real(1000, 4300),
        Real(700, 3400),
        Real(1000, 4100),
        Real(1000, 4200),
        Real(1000, 5500),
        Real(700, 3600),
        Real(1000, 4000),
        Real(1000, 14000),
        Real(1000, 9500),
        Real(1000, 9600),
        Real(1000, 6100),
        Real(1000, 4900),
        Real(1000, 4500),
        Real(1000, 3900),
        Real(1000, 3600),
        Real(1000, 3400),
        Real(1000, 3400),
        Real(1000, 3400),
        Real(1000, 3200),
        Real(1000, 3200),
        Real(1000, 2900),
        Real(1000, 2700),
        Real(1000, 2700),
        Real(1000, 2700),
        Real(1000, 2500),
        Real(1000, 2400),
        Real(1000, 2400),
        Real(1000, 2400),
        Real(1000, 2200),
        Real(1000, 2200),
        Real(1000, 2200),
        Real(1000, 2200),
        Real(1000, 2200)
    ]
    problem.function = schaffer

    #
    num = int(s)

    #starttime = datetime.datetime.now()
    algorithm = NSGAII(problem)
    #输入循环次数——交互输入
    algorithm.run(num)

    for solution in algorithm.result:
        print(solution.objectives)
        print(solution)
    endtime = datetime.datetime.now()

    #
    fig = plt.figure()
    x = [s.objectives[0] for s in algorithm.result]
    y = [s.objectives[1] for s in algorithm.result]
    z = [s.objectives[2] for s in algorithm.result]
    ax = Axes3D(fig)
    ax.scatter(x, y, z)

    ax.set_zlabel('SS', fontdict={'size': 10, 'color': 'red'})
    ax.set_ylabel('RUNOFF', fontdict={'size': 10, 'color': 'red'})
    ax.set_xlabel('COST', fontdict={'size': 10, 'color': 'red'})

    plt.savefig(str(filename2) + '/result.png')
    plt.show()
def EMSG(Algorithm_Run_NUM, n, m, s_i, SA_i, p_i, d_hat_j_tmp, t_hat_ij_tmp,
         d_ij, e_ij, theat_ij, fr_ij):
    ProcessPoolExecutor(max_workers=8)
    print("-------EMSGMOP:")
    problem = EMSGMOP_problem(n, m, s_i, SA_i, p_i, d_hat_j_tmp, t_hat_ij_tmp,
                              d_ij, e_ij, theat_ij, fr_ij)

    # 默认求最小目标值
    # problem.directions[:] = Problem.MINIMIZE

    # algorithm = EpsMOEA(problem, epsilons=0.5)
    # algorithm = MOEAD(problem)
    # algorithm = SMPSO(problem)
    # algorithm = OMOPSO(problem, epsilons=0.5)
    # algorithm  = EpsNSGAII(problem, epsilons=0.5)
    # algorithm = SPEA2(problem)
    # algorithm = GDE3(problem)
    algorithm = NSGAII(problem)
    # algorithm = NSGAIII(problem,divisions_outer=25)
    algorithm.population_size = 10
    algorithm.run(Algorithm_Run_NUM)

    # feasible_solutions = [s for s in algorithm.result if s.feasible]
    # if len(feasible_solutions) > 0:
    #     print(feasible_solutions.objectives)
    # print("------------------")

    # print("Population size: ")
    # print(len(algorithm.result))
    # # The output shows on each line the objectives for a Pareto optimal solution:
    # for solution in algorithm.result:
    #     print(solution.variables)

    objectives_result = algorithm.result[0].objectives
    x_result = algorithm.result[0].variables
    x_matrix = np.zeros([n, m])
    for i in range(n):
        for j in range(m):
            x_matrix[i][j] = round(x_result[j + i * m])
    r_s_i = x_matrix.sum(axis=1)
    r_d_j = x_matrix.sum(axis=0)
    print("objectives_result:")
    print(objectives_result)
    # print("x_matrix:")
    # print(x_matrix)
    print("r_s_i:")
    print(r_s_i)
    print("std of r_s_i-s_i:")
    print(np.std(r_s_i - s_i))
    print("r_d_j:")
    print(r_d_j)

    # plot the results using matplotlib
    import matplotlib.pyplot as plt

    plt.scatter([s.objectives[0] for s in algorithm.result],
                [s.objectives[1] for s in algorithm.result])
    plt.xlabel("$f_1(x)$")
    plt.ylabel("$f_2(x)$")
    plt.show()

    return objectives_result, x_matrix
    '''
Exemple #19
0
def Operwas2(nr_runs):

    # if not all([check.get() for check in checks]):
    #     print('Not set!!!')
    #     return
    #
    # try:
    #     nr_runs = int(nr_runs)
    # except:
    #     print('Could not convert number of runs', nr_runs, ' to an int (try again)')
    #     return

    t_start = timer()
    print('running start time: ', t_start)
    print('Running set for: ', nr_runs, 'runs')

    # Todo: set up folders

    list_of_paths = [path_results, path_temp, path_pour_points, path_outputs]
    for i in list_of_paths:
        if not os.path.exists(i):
            os.makedirs(i)

    # reset data file
    with open(file_all_generations, 'w') as f:
        pass

    # get the decision variable lists
    junc = loadtxt(file_with_possible_locations, skiprows=1, delimiter=';')
    if len(junc.shape) == 1:
        junc = np.expand_dims(junc, axis=0)
    print('junc is', junc)
    print('type of junc is ', type(junc))
    tuple_junctions = tuple(tuple(row) for row in junc)
    print(tuple_junctions)

    # set the problem via Class Problem
    class Operwa2(Problem):
        def __init__(self):
            super(Operwa2, self).__init__(1, 2)
            self.types[:] = LimitedBinary(len(junc))
            self.directions[0] = Problem.MAXIMIZE
            self.directions[1] = Problem.MAXIMIZE
            self._maria_sols = []
            self._maria_coords = []
            self._iteration = 0

        def evaluate(self, solution):
            include_junctions = solution.variables[0]
            coordinates = [
                junc[i] for i in range(len(junc)) if include_junctions[i]
            ]
            coordinates = np.array(coordinates)
            # try:
            _sol = AOKP(coordinates)
            print(("Finished iteration {}".format(self._iteration)))
            # except:
            #     _sol = (0,0)
            #     print(('iteration failed: ', sys.exc_info()[1]))
            self._iteration += 1
            _sol_tuple = tuple(_sol)
            solution.objectives[:] = _sol_tuple
            solution.constraints[:] = ">(0,0)"

            nr_wwtp = sum(include_junctions)

            to_save = "{},{},{},\"{}\"\n".format(nr_wwtp, _sol_tuple[0],
                                                 _sol_tuple[1],
                                                 include_junctions)
            with open(file_all_generations, 'a') as f:
                f.write(to_save)

    # optimize the problem using 10,000 function evaluations
    prob = Operwa2()
    if nr_runs < 100:
        nr_pop = nr_runs
    else:
        nr_pop = 100
    print("number of population is ", nr_pop)
    algorithm = NSGAII(prob,
                       nr_pop)  # second parameter is for size of population
    algorithm.run(nr_runs)

    with open(file_with_results, 'w+') as file_handler:
        for item in algorithm.result:
            file_handler.write("{}\n".format(item))

    x_coverage = [s.objectives[1] for s in algorithm.result]
    y_bencost = [s.objectives[0] for s in algorithm.result]
    z_wwtp = [sum(s.variables) for s in algorithm.result]

    w_coord = [s.variables for s in algorithm.result]

    if len(x_coverage) == 0 and len(y_bencost) == 0:
        max_x_coverage = 1
        max_y_bencost = 1
    else:
        max_x_coverage = max(x_coverage)
        max_y_bencost = max(y_bencost)

    df = pd.DataFrame(dict(x=x_coverage, y=y_bencost, s=z_wwtp, w=w_coord))
    df.to_csv(file_with_last_population, index=None, header=True)

    for key, row in df.iterrows():
        plt.scatter(row['x'], row['y'], s=row['s'] * 10, alpha=.5)
        plt.annotate(int(row['s']),
                     xy=(row['x'], row['y']),
                     ha='center',
                     va='center')

    # plt.scatter(x, y, s=z*1000, alpha=0.5)
    plt.xlim(xmin=0, xmax=1.2 * max_x_coverage)
    plt.ylim(ymin=0, ymax=1.2 * max_y_bencost)
    plt.xlabel("$Coverage$")
    plt.ylabel("$Benefits/Costs$")

    plt.grid()
    plt.show()

    # # # For each point, we add a text inside the bubble
    # for s in algorithm.result:
    #     plt.text(plt.x.iloc[s.objectives[1]], plt.y.iloc[s.objectives[0]], plt.z.iloc[sum(s.variables)], horizontalalignment='center', size='medium', color='black',
    #             weight='semibold')

    # bubbles = plt.subplots()
    # produce a legend with a cross section of sizes from the scatter
    # handles, labels = graph.legend(prop="sizes", alpha=0.5)
    # legend2 = bubbles.legend(handles, labels, loc="upper right", title="Sizes")

    print('End of optimization run')

    t_end = timer()
    print("Calculation took ", t_end - t_start, " seconds = ", \
        (t_end - t_start) / 60, "minutes = ", \
        ((t_end - t_start) / 60) / 60, "hours")

    # for solution in algorithm.result:
    #     print(solution.objectives)

    for solution in algorithm.result:
        print(df)
    _, ax = plt.subplots(figsize=(11, 11))
    ax.barh(y_pos, relevancy, align='center')
    ax.set_yticks(y_pos)
    ax.set_yticklabels(var_list)
    ax.invert_yaxis()
    ax.set_xlabel('Relevancy')
    if objective_idx == 0:
        ax.set_title('Best Variables - Sensitivity')
    else:
        ax.set_title('Best Variables - Specificity')
    plt.show()


if __name__ == "__main__":

    algorithm = NSGAII(SVM(), population_size=30)
    algorithm.run(100)

    nondominated_results = nondominated(algorithm.result)

    # prints results
    fig1 = plt.figure(figsize=[11, 11])
    plt.scatter([s.objectives[0] for s in nondominated_results],
                [s.objectives[1] for s in nondominated_results])
    plt.xlim([0, 1.1])
    plt.ylim([0, 1.1])
    plt.xlabel("Sensitivity")
    plt.ylabel("Specificity")
    plt.show()

    calculate_relevancy(nondominated_results, 0, 0.81, 15)
Exemple #21
0
def Operwa(nr_wwtp, nr_runs, checks):

    print('Optimization 1')

    # if not all([check.get() for check in checks]):
    #     print('Not set!!!')
    #     return
    #
    try:
        nr_wwtp = int(nr_wwtp)
    except:
        print('Could not convert number of wwtp', nr_wwtp,
              ' to an int (try again)')
        return
    try:
        nr_runs = int(nr_runs)
    except:
        print('Could not convert number of runs', nr_runs,
              ' to an int (try again)')
        return

    t_start = timer()
    print('running start time: ', t_start)
    print('Running set for: ', nr_runs, 'runs')

    # get the decision variable lists
    junc = loadtxt(file_with_possible_locations, skiprows=1, delimiter=';')
    #junc = loadtxt(file_with_possible_locations, delimiter=';')
    if len(junc.shape) == 1:
        junc = np.expand_dims(junc, axis=0)
    print('junc is', junc)
    print('type of junc is ', type(junc))
    tuple_junctions = tuple(tuple(row) for row in junc)

    print(tuple_junctions)

    # set the problem via Class Problem

    class Operwa(Problem):
        def __init__(self):
            super(Operwa, self).__init__(1, 2)
            self.types[:] = Subset(tuple_junctions, nr_wwtp)
            print('tuple_junctions', tuple_junctions)
            self.directions[0] = Problem.MAXIMIZE
            self.directions[1] = Problem.MAXIMIZE
            self._maria_sols = []
            self._maria_coords = []
            self._iteration = 0

        def evaluate(self, solution):
            print('solution variables', solution.variables[:])
            coordinates = solution.variables[:]
            print(coordinates)
            coordinates = np.array(coordinates[0])
            print(coordinates)
            #try:
            _sol = AOKP(coordinates)
            print(("Finished iteration {}".format(self._iteration)))
            #except:
            # sol = (0, 0)
            # print(('iteration failed: ', sys.exc_info()[1]))
            self._iteration += 1
            _sol_tuple = tuple(_sol)
            solution.objectives[:] = _sol_tuple
            solution.constraints[:] = ">(0,0)"

            to_save = "{},{},\"{}\"\n".format(_sol_tuple[0], _sol_tuple[1],
                                              coordinates)
            with open(file_all_generations, 'a') as f:
                f.write(to_save)

    # optimize the problem using function evaluations
    prob = Operwa()
    nr_runs = int(nr_runs)

    if nr_runs < 100:
        nr_pop = nr_runs
    else:
        nr_pop = 100

    print("nr_pop is ", nr_pop)
    print("type  of nr_pop is ", type(nr_pop))
    algorithm = NSGAII(
        prob, nr_pop)  # second parameter is for size of initial population
    # default initial population (without second parameter) is 100

    print('type of nr_runs is', type(nr_runs))
    print('nr_runs is ', nr_runs)
    algorithm.run(nr_runs)

    with open(file_with_results, 'w+') as file_handler:
        for item in algorithm.result:
            file_handler.write("{}\n".format(item))

    # Plot data in graph
    x_coverage = [s.objectives[1] for s in algorithm.result]
    y_bencost = [s.objectives[0] for s in algorithm.result]
    print("Nr. of calculations = ", nr_runs)
    print("Nr. of results =", len(x_coverage))
    plt.scatter(x_coverage, y_bencost)
    if len(x_coverage) == 0 and len(y_bencost) == 0:
        max_x_coverage = 1
        max_y_bencost = 1
    else:
        max_x_coverage = max(x_coverage)
        max_y_bencost = max(y_bencost)
    plt.xlim(xmin=0, xmax=1.1 * max_x_coverage)
    plt.ylim(ymin=0, ymax=1.1 * max_y_bencost)
    plt.xlabel("$Coverage$")
    plt.ylabel("$Benefit/Costs$")

    plt.grid()
    plt.show()

    print('End of optimization run')

    t_end = timer()
    print("Calculation took ", t_end - t_start, " seconds = ", \
        (t_end - t_start) / 60, "minutes = ", \
        ((t_end - t_start) / 60) / 60, "hours")

    for solution in algorithm.result:
        print((solution.objectives))
def _pick_algorithm(myproblem,
                    algorithm,
                    population,
                    mutation_probability,
                    current_solution,
                    evaluator=None):
    """
    Return a serial or parallel platypus.Algorithm object based on input string

    :param myproblem: EZFF Problem to be optimized
    :type myproblem: Problem

    :param algorithm: EZFF Algorithm to use for optimization. Allowed options are ``NSGAII``, ``NSGAIII`` and ``IBEA``
    :type algorithm: str

    :param population: Population size for genetic algorithms
    :type population: int

    :param evaluator: Platypus.Evaluator in case of parallel execution
    :type evaluator: Platypus.Evaluator
    """

    if mutation_probability is None:
        variator = GAOperator(SBX(), PM())
    else:
        variator = GAOperator(SBX(), PM(probability=mutation_probability))
        print('Using provided mutation probability')

    if algorithm.lower().upper() == 'NSGAII':
        if evaluator is None:
            if current_solution is None:
                return NSGAII(myproblem,
                              population_size=population,
                              variator=variator)
            else:
                return NSGAII(myproblem,
                              population_size=population,
                              variator=variator,
                              generator=InjectedPopulation(
                                  current_solution[0:population]))
        else:
            if current_solution is None:
                return NSGAII(myproblem,
                              population_size=population,
                              variator=variator,
                              evaluator=evaluator)
            else:
                return NSGAII(myproblem,
                              population_size=population,
                              variator=variator,
                              generator=InjectedPopulation(
                                  current_solution[0:population]),
                              evaluator=evaluator)
    elif algorithm.lower().upper() == 'NSGAIII':
        num_errors = len(myproblem.directions)
        divisions = int(
            np.power(population * np.math.factorial(num_errors - 1), 1.0 /
                     (num_errors - 1))) + 2 - num_errors
        divisions = np.maximum(1, divisions)
        if evaluator is None:
            if current_solution is None:
                return NSGAIII(myproblem,
                               divisions_outer=divisions,
                               variator=variator)
            else:
                return NSGAIII(myproblem,
                               divisions_outer=divisions,
                               variator=variator,
                               generator=InjectedPopulation(
                                   current_solution[0:population]))
        else:
            if current_solution is None:
                return NSGAIII(myproblem,
                               divisions_outer=divisions,
                               variator=variator,
                               evaluator=evaluator)
            else:
                return NSGAIII(myproblem,
                               divisions_outer=divisions,
                               variator=variator,
                               generator=InjectedPopulation(
                                   current_solution[0:population]),
                               evaluator=evaluator)
    elif algorithm.lower().upper() == 'IBEA':
        if evaluator is None:
            if current_solution is None:
                return IBEA(myproblem,
                            population_size=population,
                            variator=variator)
            else:
                return IBEA(myproblem,
                            population_size=population,
                            variator=variator,
                            generator=InjectedPopulation(
                                current_solution[0:population]))
        else:
            if current_solution is None:
                return IBEA(myproblem,
                            population_size=population,
                            variator=variator,
                            evaluator=evaluator)
            else:
                return IBEA(myproblem,
                            population_size=population,
                            variator=variator,
                            generator=InjectedPopulation(
                                current_solution[0:population]),
                            evaluator=evaluator)
    else:
        raise Exception(
            'Please enter an algorithm for optimization. NSGAII , NSGAIII , IBEA are supported'
        )
sizePop     = 3
library     = 2

pathsave    = '/home/oscar/Documents/PythonProjects/kuramotoAO/optimizationResults/'
#pathsave    = '/Users/p277634/python/kaoModel/optimResult/'
filenameTXT = 'ihsTest.txt'
filenameNPZ = 'ihsTest.npz'

print('Running: ', filenameNPZ[:-4])

# Cost function definiton
kaom = myUDPkaos.kaoSimplMultiObjContr(lib=library)
lowBound, upBound = kaom.get_bounds()

# OPtimization Prblem definition
problem = Problem(len(upBound), kaom.get_nobj(), kaom.get_nic())  # (number of decision variables, number of objectives, number of constrains)
problem.nvars = sizePop
problem.types[:] = [Real(lb, ub) for lb,ub in zip(lowBound,upBound)]
problem.constraints[:] = "<=0"
problem.function = kaom.fitness

# Evolutionary algorithm
algorithm = NSGAII(problem)
start  = time.time()
algorithm.run(generations)
print('time evolution: ',time.time()-start)


logged = kaom.get_mylogs()

Exemple #24
0
def bar_multi_GA(nx=20,
                 ny=20,
                 volume_frac=0.5,
                 parent=400,
                 generation=100,
                 path="data"):
    PATH = os.path.join(path, "bar_nx_{}_ny_{}".format(nx, ny),
                        "gen_{}_pa_{}".format(generation, parent))
    os.makedirs(PATH, exist_ok=True)
    start = time.time()

    def objective(vars):
        y_1, y_2, y_3, x_4, nodes, widths = convert_var_to_arg(vars)
        edges = make_6_bar_edges(nx, ny, y_1, y_2, y_3, x_4, nodes, widths)
        rho = make_bar_structure(nx, ny, edges)
        volume = np.sum(rho) / (nx * ny)

        return [calc_E(rho), calc_G(rho)], [volume]

    def convert_var_to_arg(vars):
        y_1 = vars[0]
        y_2 = vars[1]
        y_3 = vars[2]
        x_4 = vars[3]
        node_y_indexes = vars[4:4 + 6 * 3]
        node_x_indexes = vars[4 + 6 * 3:4 + 6 * 3 * 2]
        nodes = np.stack([node_x_indexes, node_y_indexes], axis=1)
        widths = vars[4 + 6 * 3 * 2:]
        return y_1, y_2, y_3, x_4, nodes, widths

    # 2変数2目的の問題
    problem = Problem(4 + 6 * 3 * 2 + 6 * 4, 2, 1)
    # 最小化or最大化を設定
    problem.directions[:] = Problem.MAXIMIZE

    # 決定変数の範囲を設定
    x_index_const = Integer(1, nx)  # x座標に関する制約
    y_index_const = Integer(1, ny)  # y座標に関する制約
    bar_constraint = Real(0, ny / 2)  # バーの幅に関する制約
    problem.types[0:3] = y_index_const
    problem.types[3] = x_index_const
    problem.types[4:4 + 6 * 3] = y_index_const
    problem.types[4 + 6 * 3:4 + 6 * 3 * 2] = x_index_const
    problem.types[4 + 6 * 3 * 2:] = bar_constraint

    problem.constraints[:] = "<=" + str(volume_frac)
    problem.function = objective
    problem.directions[:] = Problem.MAXIMIZE
    algorithm = NSGAII(problem,
                       population_size=parent,
                       variator=CompoundOperator(SBX(), HUX(), PM(),
                                                 BitFlip()))
    algorithm.run(generation)

    # グラフを描画

    fig = plt.figure()
    plt.scatter([s.objectives[0] for s in algorithm.result],
                [s.objectives[1] for s in algorithm.result],
                c="blue",
                label="infeasible solution")

    plt.scatter([s.objectives[0] for s in algorithm.result if s.feasible],
                [s.objectives[1] for s in algorithm.result if s.feasible],
                c="red",
                label='feasible solution')

    # 非劣解をとりだす
    nondominated_solutions = nondominated(algorithm.result)
    plt.scatter(
        [s.objectives[0] for s in nondominated_solutions if s.feasible],
        [s.objectives[1] for s in nondominated_solutions if s.feasible],
        c="green",
        label="pareto solution")
    plt.legend(loc='lower left')

    plt.xlabel("$E$")
    plt.ylabel("$G$")
    fig.savefig(os.path.join(PATH, "graph.png"))
    plt.close()

    for solution in [s for s in nondominated_solutions if s.feasible]:
        vars_list = []
        for j in solution.variables[:3]:
            vars_list.append(y_index_const.decode(j))
        vars_list.append(x_index_const.decode(solution.variables[3]))
        for j in solution.variables[4:4 + 6 * 3]:
            vars_list.append(y_index_const.decode(j))
        for j in solution.variables[4 + 6 * 3:4 + 6 * 3 * 2]:
            vars_list.append(x_index_const.decode(j))
        for j in solution.variables[4 + 6 * 3 * 2:]:
            vars_list.append(bar_constraint.decode(j))
        y_1, y_2, y_3, x_4, nodes, widths = convert_var_to_arg(vars_list)
        edges = make_6_bar_edges(nx, ny, y_1, y_2, y_3, x_4, nodes, widths)
        image = make_bar_structure(nx, ny, edges)
        np.save(
            os.path.join(
                PATH, 'E_{}_G_{}.npy'.format(solution.objectives[0],
                                             solution.objectives[1])), image)

    convert_folder_npy_to_image(PATH)

    elapsed_time = time.time() - start

    with open("time.txt", mode='a') as f:
        f.writelines("bar_nx_{}_ny_{}_gen_{}_pa_{}:{}sec\n".format(
            nx, ny, generation, parent, elapsed_time))
Exemple #25
0
def HBV_calibration(P,
                    E,
                    Case,
                    area,
                    Q_obs,
                    objective,
                    iterations,
                    population_size=1):

    if objective == 'all':  # the objective is to minimize RMSE considering all the hydrograph
        num_objectives = 1
        pass
    elif objective == 'low':  # the objective is to minimize RMSE considering only low flows
        num_objectives = 1
        low_flow_indexes = [Q_obs < np.percentile(Q_obs, 50)]
        Q_obs_low = Q_obs[tuple(low_flow_indexes)]
    elif objective == 'high':  # the objective is to minimize RMSE considering only high flows
        num_objectives = 1
        high_flow_indexes = [Q_obs > np.percentile(Q_obs, 50)]
        Q_obs_high = Q_obs[tuple(high_flow_indexes)]
    elif objective == 'double':  # two objectives (RMSE of low and high flows)
        num_objectives = 2
        low_flow_indexes = [Q_obs < np.percentile(Q_obs, 50)]
        Q_obs_low = Q_obs[tuple(low_flow_indexes)]
        high_flow_indexes = [Q_obs > np.percentile(Q_obs, 50)]
        Q_obs_high = Q_obs[tuple(high_flow_indexes)]

    def auto_calibration(vars):

        SSM0 = vars[0]
        SUZ0 = vars[1]
        SLZ0 = vars[2]

        BETA = vars[3]
        LP = vars[4]
        FC = vars[5]
        PERC = vars[6]
        K0 = vars[7]
        K1 = vars[8]
        K2 = vars[9]
        UZL = vars[10]
        MAXBAS = vars[11]

        ini = [SSM0, SUZ0, SLZ0]
        param = [BETA, LP, FC, PERC, K0, K1, K2, UZL, MAXBAS]

        Q_sim, [SM, UZ, LZ], [EA, R, RL, Q0,
                              Q1] = HBV_sim(P, E, param, Case, ini, area)

        if objective == 'all':
            # Consider the entire hydrograph
            value = np.sqrt(((Q_sim - Q_obs)**2).mean())
            return [value]
        elif objective == 'low':
            Q_sim_low = Q_sim[tuple(low_flow_indexes)]
            value = np.sqrt(((Q_sim_low - Q_obs_low)**2).mean())
            return [value]
        elif objective == 'high':
            Q_sim_high = Q_sim[tuple(high_flow_indexes)]
            value = np.sqrt(((Q_sim_high - Q_obs_high)**2).mean())
            return [value]
        elif objective == 'double':
            Q_sim_low = Q_sim[tuple(low_flow_indexes)]
            Q_sim_high = Q_sim[tuple(high_flow_indexes)]
            value = [
                np.sqrt(((Q_sim_low - Q_obs_low)**2).mean()),
                np.sqrt(((Q_sim_high - Q_obs_high)**2).mean())
            ]
            return value

    problem = Problem(12, num_objectives)
    real0 = Real(0, 400)
    real1 = Real(0, 100)
    real2 = Real(0, 100)
    real3 = Real(0, 7)
    real4 = Real(0.3, 1)
    real5 = Real(1, 2000)
    real6 = Real(0, 100)
    real7 = Real(0.05, 2)
    real8 = Real(0.01, 1)
    real9 = Real(0, 0.1)
    real10 = Real(0, 100)
    real11 = Real(1, 6)
    problem.types[:] = [real0] + [real1] + [real2] + [real3] + [real4] + [
        real5
    ] + [real6] + [real7] + [real8] + [real9] + [real10] + [real11]
    problem.function = auto_calibration

    algorithm = NSGAII(problem, population_size)
    algorithm.run(iterations)  # Number of iterations

    if objective == 'double':
        results_low = np.array([
            algorithm.result[i].objectives[0] for i in range(population_size)
        ])
        results_high = np.array([
            algorithm.result[i].objectives[1] for i in range(population_size)
        ])
    else:
        results = np.array([
            algorithm.result[i].objectives[0] for i in range(population_size)
        ])

    solution = [
        algorithm.result[i].variables[0:12] for i in range(population_size)
    ]

    RMSE = [
        np.sqrt(((
            HBV_sim(P, E, solution[i][3:12], Case, solution[i][0:3], area)[0] -
            Q_obs)**2).mean()) for i in range(population_size)
    ]

    if objective == 'double':
        return results_low, results_high, solution, RMSE
    else:
        return results, solution, RMSE
Exemple #26
0
logging.basicConfig(level=logging.INFO)


# simulate an computationally expensive problem
class DTLZ2_Slow(DTLZ2):
    def evaluate(self, solution):
        sum(range(1000000))
        super(DTLZ2_Slow, self).evaluate(solution)


if __name__ == "__main__":
    # define the problem definition
    problem = DTLZ2_Slow()
    pool = MPIPool()

    # only run the algorithm on the master process
    if not pool.is_master():
        pool.wait()
        sys.exit(0)

    # instantiate the optimization algorithm to run in parallel
    with PoolEvaluator(pool) as evaluator:
        algorithm = NSGAII(problem, evaluator=evaluator)
        algorithm.run(10000)

    # display the results
    for solution in algorithm.result:
        print(solution.objectives)

    pool.close()
Exemple #27
0
def optimizer(fixedParameters, constraints):
    """
            - fixedParameters: {gridComponents : {
                                                        "battery" : {
                                                                        "initialStorage": float between 0 and 1, the battery initial energy storage as a percentage of its maximum capacity,
                                                                        "maxInputPow": float, the maximum charging power of the battery in kW for a 1kWh battery. The real value will be obtained by multiplying by the maximum storage capacity,
                                                                        "maxOutputPow": float, the maximum discharging power of the battery in kW for a 1kWh battery. The real value will be obtained by multiplying by the maximum storage capacity,
                                                                        "SOC_min": float, the minimum amount of energy that can be stored in the battery as a percentage of the maximum storage capacity,
                                                                        "maxThroughput": float, the number by which we multiply the max storage to get the maximum amount of energy that can flow in and out of the battery during its lifetime (kWh),
                                                                        "lifetime": int, the nominal lifetime of the battery in hours. It's the time after which we must replace it if we did not exceed the maximum throughput,
                                                                        "capitalCost": float, the cost of a 1kWh battery in $,
                                                                        "replacementCost": float, the cost to replace 1kWh of batteries in $,
                                                                        "operationalCost": float, the cost PER HOUR, to operate and maintain the battery ($)
                                                                    },
                                                        "diesel" : {
                                                                        "fuelCost": float, the cost of 1l of fuel ($),
                                                                        "fuelCostGrad": float, there is a fuel curve modeling the relationship between the functionning power of the dg and it's consumption of liters fuel per kW. This parameter is the slope of the model curve,
                                                                        "fuelCostIntercept": float, there is a fuel curve modeling the relationship between the functionning power of the dg and it's consumption of liters fuel per kW. This parameter is the intercept of the model curve,
                                                                        "lifetime": int, the nominal lifetime of the dg in hours,
                                                                        "capitalCost": float, the cost of the dg in $,
                                                                        "replacementCost": float, the cost to replace the dg in $,
                                                                        "operationalCost": float, the cost PER HOUR, to operate and maintain the dg,
                                                                    },
                                                        "photovoltaic" : {
                                                                            "lifetime": int, the nominal lifetime of a pannel in hours,
                                                                            "capitalCost": float, the cost of a pannel in $,
                                                                            "replacementCost": float, the cost to replace a pannel in $,
                                                                            "operationalCost": float, the cost PER HOUR, to operate and maintain the pannel ($),
                                                                            "powerTimeVector": numpy array, the power output of the pannel at each time step (kW)
                                                                        }
                                                    },
                                    
                               timeStep : float, the time step of the simulation that generated the load in hours,
                               loadVector : numpy array of floats, the power demand on the grid (kW),
                               projectDuration : int, the duration of the whole project in hours (e.g 25 * 365 * 24),
                               discountRate: float, the discount ratio,
                               strategy : "LF" or "CC", respectively for "Load Following" or "Cycle Charging"
                - constraints : {
                                    "diesel":
                                                {
                                                        "upperBound": float, the upper Bound for the value of the generatorMaximumPower (kW),
                                                        "lowerBound": float, the lower Bound for the value of the generatorMaximumPower (kW),
                                                },
                                     "battery":
                                                {
                                                        "upperBound": float, the upper Bound for the value of the battery maximum storage capacity (kWh),
                                                        "lowerBound": float, the lower Bound for the value of the battery maximum storage capacity (kWh),
                                                },
                                     "photovoltaic":
                                                    {
                                                            "upperBound": float, the upper Bound for the value of the pvMaximumPower (kW),
                                                            "lowerBound": float, the upperlower Bound for the value of the pvMaximumPower (kW),
                                                    },           
                                }
                                                    
    OUTPUT:
        {
                "parameters":
                            {
                                    "battery": float, the battery storage capacity (kWh),
                                    "diesel": float, the generator maximum power (kW),
                                    "photovoltaic": float, the pv maximum power (kW)                                                
                            },
                "costs":
                        {
                                "dollars": float, the cost of the project in dollars,
                                "carbon": float, the carbon emissions generated by the project (kg)
                        }
                            
        }                                                    
    """        
    
    gridComponents = fixedParameters["gridComponents"]
    timeStep = fixedParameters["timeStep"]
    loadVector = fixedParameters["loadVector"]
    projectDuration = fixedParameters["projectDuration"]
    discountRate = fixedParameters["discountRate"]
    strategy = fixedParameters["strategy"]
    pvPowerTimeVector = gridComponents["photovoltaic"]["powerTimeVector"]
    normalizingFactor = 52
    maxInputPowMulti = gridComponents["battery"]["maxInputPow"] 
    maxOutputPowMulti = gridComponents["battery"]["maxOutputPow"] 
    SOC_min_multi = gridComponents["battery"]["SOC_min"] 
    
    def costFunction(x):
        global dispatchingResult, netLoadVector, pvPowerVector
        gridComponents["battery"]["maxStorage"] = x[0]
        gridComponents["diesel"]["maxPower"] = x[1]
        gridComponents["photovoltaic"]["maxPower"] = x[2]
        
        batteryInitialStorage = gridComponents["battery"]["initialStorage"] * x[0]
        battMaxInputPow = maxInputPowMulti * x[0]
        battMaxOutputPow = maxOutputPowMulti * x[0]
        SOC_min = SOC_min_multi * x[0]
        specifications = [x[0], x[1], battMaxInputPow, battMaxOutputPow, SOC_min]
        
        pvPowerVector = ((pvPowerTimeVector)/normalizingFactor)*(x[2])
        netLoadVector = loadVector - pvPowerVector
        dispatchingResult = dispatchingLoop(timeStep, netLoadVector, batteryInitialStorage, specifications, strategy)

        return [dollarCost(gridComponents, timeStep, loadVector, projectDuration, discountRate, strategy, dispatchingResult),
                carbonCost(gridComponents, timeStep, loadVector, projectDuration, discountRate, strategy, dispatchingResult)]
    
    problem = Problem(3, 2)
    problem.types[:] = [Real(constraints["battery"]["lowerBound"], constraints["battery"]["upperBound"]), Real(constraints["diesel"]["lowerBound"], constraints["diesel"]["upperBound"]), Real(constraints["photovoltaic"]["lowerBound"], constraints["photovoltaic"]["upperBound"])]
    problem.function = costFunction # lambda x: [sum(x), sum([val**2 for val in x])] #The function helped us see that the computational time of our cost functions was a problem
    
    algorithm = NSGAII(problem)
    algorithm.run(1)
    
    displayResults(netLoadVector, pvPowerVector, dispatchingResult[0], dispatchingResult[1], [solution for solution in algorithm.result if solution.feasible])
Exemple #28
0
def main():
    # One-shot objects parameters
    init_num_test_samples_per_object = 1000
    init_range = 20

    # Regularization samples parameters
    init_num_reg_samples_per_object = 10

    # Generalization generator parameters
    # TODO: num_objects = os.num_objects,
    init_num_gen_samples_per_object = 300

    # Classifier parameters
    # TODO: self.num_classes = num_classes (num_objects)
    init_learning_rate = 0.003
    init_training_epochs = 300  # 1200
    init_display_step = 100
    init_num_hidden_1 = 10  # 1st layer number of features
    init_num_hidden_2 = 10  # 2nd layer number of features

    os = OneShotObjects(
        num_test_samples_per_object=init_num_test_samples_per_object,
        range=init_range)
    rs = RegularizationSamples(
        one_shot_objects=os,
        num_reg_samples_per_object=init_num_reg_samples_per_object)
    gg = GeneralizationGenerator(
        one_shot_objects=os,
        regularization_samples=rs,
        num_objects=os.num_objects,
        num_gen_samples_per_object=init_num_gen_samples_per_object)
    cs = Classifier(num_classes=os.num_objects,
                    range=init_range,
                    learning_rate=init_learning_rate,
                    training_epochs=init_training_epochs,
                    display_step=init_display_step,
                    num_hidden_1=init_num_hidden_1,
                    num_hidden_2=init_num_hidden_2)

    gol_model = GOL(os, rs, gg, cs)

    opt_algorithm = NSGAII(gol_model)
    opt_algorithm.run(2)

    plt.figure(2)
    plt.scatter([s.objectives[0] for s in opt_algorithm.result],
                [s.objectives[1] for s in opt_algorithm.result])
    plt.xlabel("$J(\Theta, \hat{x}(t))$")
    plt.ylabel("$a(\Theta, \hat{x}(t))$")

    if animate:
        # Save pareto solutions image
        file_path = anim_path + '/_pareto_solutions.png'
        plt.savefig(file_path)
        plt.close()

        # Save the pareto solutions
        file_path = anim_path + '/_pareto_solutions.csv'

        with open(file_path, 'w', newline='') as f:
            writer = csv.writer(f)
            for s in opt_algorithm.result:
                writer.writerow((s.objectives[0], s.objectives[1]))
            f.close()
    else:
        plt.show()
    POPSIZE = 100
    DIRECTIONS = [Problem.MAXIMIZE, Problem.MINIMIZE, Problem.MINIMIZE]

    print(" * %d variables, %d objectives" % (D, OBJS))
    print(" * %d individuals, MAX_FEs %d, %d iterations" %
          (POPSIZE, FEs, FEs // POPSIZE))
    problem = Problem(D, OBJS)
    all_types = [Integer(0, 2) for _ in range(D)]
    problem.types[:] = all_types
    problem.function = SIM.fitness
    problem.directions[:] = DIRECTIONS

    # Multi-processing (4 parallel processes)
    with ProcessPoolEvaluator(4) as evaluator:
        algorithm = NSGAII(problem,
                           population_size=POPSIZE,
                           evaluator=evaluator)
        res = algorithm.run(FEs)

    final_results = [(s.objectives[0], s.objectives[1], s.objectives[2])
                     for s in algorithm.result]
    final_solutions = []
    for solution in algorithm.result:
        temp = []
        for n in range(D):
            tpe = all_types[n]
            value = tpe.decode(solution.variables[n])
            name = SIM._sorted_names[n]
            if value == 1:
                temp.append("%s IS low" % name)
            elif value == 2:
Exemple #30
0
from platypus import NSGAII, Problem, Real

class Schaffer(Problem):

    def __init__(self):
        super(Schaffer, self).__init__(1, 2)
        self.types[:] = Real(-10, 10)
    
    def evaluate(self, solution):
        x = solution.variables[:]
        solution.objectives[:] = [x[0]**2, (x[0]-2)**2]

algorithm = NSGAII(Schaffer())
algorithm.run(10000)
Exemple #31
0
    return ''.join(sb)


def evaluate(variables):
    genome = variables[0]
    phenotype = genome_to_grammar(genome)
    phenotype = phenotype.replace(' ', '')
    accuracy, f1score = 0, 0  #get_metrics(phenotype)
    # print(phenotype, accuracy, f1score)
    return accuracy, f1score


problem = Problem(1, 2)
problem.types[0] = Genome(100, 255)
problem.directions[0] = Problem.MAXIMIZE
problem.directions[1] = Problem.MAXIMIZE
problem.function = evaluate

operator = GAOperator(GenomeSinglePointCrossover(probability=0.75),
                      GenomeUniformMutation(probability=0.25))

algorithm = NSGAII(problem, population_size=50, variator=operator)
# algorithm = SPEA2(problem, population_size=50, variator=operator)

for i in range(30):
    print('Geração:', i + 1)
    algorithm.step()
    for solution in unique(nondominated(algorithm.result)):
        genome = solution.variables[0]
        phenotype = genome_to_grammar(genome)
        print(phenotype, solution.objectives)