示例#1
0
def test_platypus_nsgaii_process_pool(two_reservoir_problem):
    """Undertake a single step of the NSGAII algorithm with a ProcessPool."""
    with ProcessPoolEvaluator(2) as evaluator:
        algorithm = NSGAII(two_reservoir_problem.problem,
                           population_size=50,
                           evaluator=evaluator)
        algorithm.run(10)
示例#2
0
           constraint.append(Real(0.0001,(math.pi/2-0.0001)))			#x1 (0-pi/2), but avoid 0 and pi (90 degree)
           constraint.append(Real(vd,vcap))								#x2 (range from vdead to vcapacity)
           constraint.append(Real(vd,vcap))								#x3 (range from vdead to vcapacity), check condition later
           constraint.append(Real(0.0001,(math.pi/2-0.0001)))			#x4 (0-pi/2), but avoid 0 and pi (90 degree)
        num_var+=48
        reservoirs[i][1] = 5

# Call optimization function
problem = Problem(num_var, totalobs)
problem.types[:] = constraint
problem.function = viccall
problem.constraints[:] = ">=0"
start = datetime.datetime.now()
hyp = Hypervolume(minimum=minvar, maximum=maxvar)
allresults = []
with ProcessPoolEvaluator(number_of_cores) as evaluator:
    algorithm = EpsNSGAII(problem, eps, population_size=population, evaluator = evaluator)
    while algorithm.nfe<number_of_functions:
        algorithm.step()
        one_step_result = hyp.calculate(algorithm.result)			#this param stores information of hypervolume indicator, save as a file if needed
        allresults.append(one_step_result)
end = datetime.datetime.now()
nondominated_solutions = nondominated(algorithm.result)
os.chdir('../Results')

# Finish and save results to files
print("Start",start)
print("End",end)
print("Finish running simulations! See opt_objectives.txt and opt_variables.txt for results.")
np.savetxt("optimization_objectives.txt",[s.objectives[:] for s in nondominated_solutions],fmt="%s")
np.savetxt("optimization_variables.txt",[s.variables[:] for s in nondominated_solutions],fmt="%s")
    generation = 5000
    save_interval = 100

    PATH = os.path.join(save_dir,
                        "parent_{}_gen_{}".format(parent, generation))
    os.makedirs(PATH, exist_ok=False)
    #PATH = os.path.join(save_dir, "test")
    #os.makedirs(PATH, exist_ok=True)

    problem = ConstraintIncrementalNodeIncrease_GA(2, 2)

    history = []

    start = time.time()
    # instantiate the optimization algorithm to run in parallel
    with ProcessPoolEvaluator(8) as evaluator:
        #algorithm = NSGAII(problem, population_size=parent, variator=CompoundOperator(SBX(), HUX(), PM(), BitFlip()), evaluator=evaluator)
        algorithm = GeneticAlgorithm(problem,
                                     population_size=parent,
                                     offspring_size=parent,
                                     variator=CompoundOperator(
                                         SBX(), HUX(), UM(), BitFlip()),
                                     evaluator=evaluator)
        for i in tqdm(range(generation)):
            algorithm.step()
            """
            nondominated_solutions = nondominated(algorithm.result)
            efficiency_results = [s.objectives[0] for s in nondominated_solutions]
            max_efficiency = max(efficiency_results)
            """
            max_efficiency = algorithm.fittest.objectives[0]
    umin_max = USS*1000.	# for short pulse
    mmin = 0.01
    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
 #Do we need to generate scenarios for uncertainties in ...
 #energy demands,solar irradiance, wind speed, and electricity emissions?
 if editable_data['Generate Scenarios'] == 'yes':
     print('Generate scenarios for uncertain variables')
     scenario_generation.scenario_generation_results(state)
 #Do we need to reduce the number scenarios of scenarios in ...
 #using the PCA and k-medoid algorithm?
 if editable_data['Perfrom scenario reduction'] == 'yes':
     print('Perfrom scenarios reduction using k-medoid algorithm')
     clustring_kmediod_PCA.kmedoid_clusters()
 #Do we need to perfrom the two stage stochastic programming using NSGA-II?
 if editable_data['Perform two stage optimization'] == 'yes':
     print('Perfrom two-stage stochastic optimization')
     problem = NSGA2_design_parallel_discrete.TwoStageOpt()
     with ProcessPoolEvaluator(
             int(editable_data['num_processors'])
     ) as evaluator:  #max number of accepted processors is 61 by program/ I have 8 processor on my PC
         algorithm = NSGAII(problem,
                            population_size=int(
                                editable_data['population_size']),
                            evaluator=evaluator,
                            variator=GAOperator(HUX(), BitFlip()))
         algorithm.run(int(editable_data['num_iterations']))
     NSGA2_design_parallel_discrete.results_extraction(problem, algorithm)
 #Do we need to generate Pareto-front and parallel coordinates plots for the results?
 if editable_data['Visualizing the final results'] == 'yes':
     from Two_Stage_SP.plot_results_design import parallel_plots, ParetoFront_EFs
     file_name = city_DES + '_Discrete_EF_' + str(
         float(editable_data['renewable percentage'])) + '_design_' + str(
             editable_data['num_iterations']) + '_' + str(
                 editable_data['population_size']) + '_' + str(