def ea_select_model(config, log_name):
    #####################
    # set up parameters  #
    ######################
    if isinstance(config['ctx'], list):
        ctx = [mx.gpu(i) for i in config['ctx']]
    elif isinstance(config['ctx'], int):
        ctx = mx.gpu(config['ctx'])
    else:
        raise Exception("config_ctx error:" + str(config['ctx']))
    logger = Logger(log_name, config, False)

    #######################
    # init Env #
    #######################
    env = GNNEnv(config, ctx, logger)

    ##############
    #  training  #
    ##############
    problem = MyProblem(env, logger)
    Encoding = 'RI'
    NIND = 50
    Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges,
                      problem.borders)
    population = ea.Population(Encoding, Field, NIND)
    myAlgorithm = ea.soea_DE_best_1_L_templet(problem, population)
    myAlgorithm.MAXGEN = 39
    myAlgorithm.logTras = 1
    myAlgorithm.verbose = True
    myAlgorithm.drawing = 1
    [NDSet, population] = myAlgorithm.run()
    NDSet.save()
    """==================================输出结果=============================="""
    print('用时:%f 秒' % myAlgorithm.passTime)
    print('评价次数:%d 次' % myAlgorithm.evalsNum)
    print('非支配个体数:%d 个' %
          NDSet.sizes) if NDSet.sizes != 0 else print('没有找到可行解!')
    if myAlgorithm.log is not None and NDSet.sizes != 0:
        print('eval', myAlgorithm.log['eval'][-1])
        print('f_opt', myAlgorithm.log['f_opt'][-1])
        print('f_max', myAlgorithm.log['f_max'][-1])
        print('f_avg', myAlgorithm.log['f_avg'][-1])
        print('f_min', myAlgorithm.log['f_min'][-1])
        print('f_std', myAlgorithm.log['f_std'][-1])
        """=========================进化过程指标追踪分析========================="""
        metricName = [['eval']]
        Metrics = np.array([
            myAlgorithm.log[metricName[i][0]] for i in range(len(metricName))
        ]).T
        # 绘制指标追踪分析图
        ea.trcplot(Metrics, labels=metricName, titles=metricName)
        Vars = pop.Phen
        x1 = Vars[:, [0]]
        x2 = Vars[:, [1]]
        x3 = Vars[:, [2]]
        pop.ObjV = 4 * x1 + 2 * x2 + x3
        pop.CV = np.hstack(
            [2 * x1 + x2 - 1, x1 + 2 * x3 - 2,
             np.abs(x1 + x2 + x3 - 1)])


problem = MyProblem()
Encoding = 'RI'
NIND = 50
Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges, problem.borders)
population = ea.Population(Encoding, Field, NIND)
myAlogorithm = ea.soea_DE_best_1_L_templet(problem, population)
myAlogorithm.MAXGEN = 1000
myAlogorithm.mutOper.F = 0.5
myAlogorithm.recOper.XOVR = 0.5
myAlogorithm.drawing = 1
[population, obj_trace, var_trace] = myAlogorithm.run()
best_gen = np.argmax(obj_trace[:, 1])
best_ObjV = obj_trace[best_gen, 1]
print('最优的目标函数值:%s' % (best_ObjV))
print('最优的决策变量:')
for i in range(var_trace.shape[1]):
    print(var_trace[best_gen, i])
print('有效进化代数:%s' % (obj_trace.shape[0]))
print('最优的一代是第%s代' % (best_gen + 1))
print('评价次数:%s' % (myAlogorithm.evalsNum))
print('时间已过%s秒' % (myAlogorithm.passTime))
if __name__ == '__main__':
    """================================实例化问题对象==========================="""
    problemName = 'Rastrigrin'  # 问题名称
    fileName = problemName  # 这里因为目标函数写在与之同名的文件里,所以文件名也是问题名称
    MyProblem = getattr(__import__(fileName), problemName)  # 获得自定义问题类
    problem = MyProblem(30)  # 生成问题对象
    """==================================种群设置=============================="""
    Encoding = 'RI'  # 编码方式
    NIND = 60  # 种群规模
    precisions = [50] * problem.Dim  # 编码精度(适用于二进制/格雷编码)
    Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges,
                      problem.borders, precisions)  # 创建区域描述器
    population = ea.Population(Encoding, Field,
                               NIND)  # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化)
    """================================算法参数设置============================"""
    myAlgorithm = ea.soea_DE_best_1_L_templet(problem,
                                              population)  # 实例化一个算法模板对象
    myAlgorithm.mutOper.F = 0.5
    myAlgorithm.recOper.XOVR = 0.2
    myAlgorithm.MAXGEN = 1000  # 最大进化代数
    myAlgorithm.drawing = 1  # 设置绘图方式(0:不绘图;1:绘制结果图;2:绘制目标空间过程动画;3:绘制决策空间过程动画)
    """===========================调用算法模板进行种群进化======================"""
    [population, obj_trace,
     var_trace] = myAlgorithm.run()  # 执行算法模板,得到最后一代种群以及进化记录器
    population.save()  # 把最后一代种群的信息保存到文件中
    # 输出结果
    best_gen = np.argmin(problem.maxormins * obj_trace[:, 1])  # 记录最优种群个体是在哪一代
    best_ObjV = obj_trace[best_gen, 1]
    print('最优的目标函数值为:%s' % (best_ObjV))
    print('最优的控制变量值为:')
    for i in range(var_trace.shape[1]):
        print(var_trace[best_gen, i])
Exemple #4
0
def solve_ea(problem, matrix_shape, retain_a, retain_e):
    Encoding = 'RI'  # 编码方式
    NIND = 500  # 种群规模
    Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges,
                      problem.borders)  # 创建区域描述器
    population = ea.Population(Encoding, Field,
                               NIND)  # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化)
    """================================算法参数设置============================="""
    myAlgorithm = ea.soea_DE_best_1_L_templet(problem,
                                              population)  # 实例化一个算法模板对象
    myAlgorithm.MAXGEN = 20  # 最大进化代数
    myAlgorithm.mutOper.F = 0.5  # 差分进化中的参数F
    myAlgorithm.recOper.XOVR = 0.3  # 重组概率
    myAlgorithm.mutOper.FixType = 1
    myAlgorithm.mutOper.Parallel = True
    myAlgorithm.logTras = 500  # 设置每隔多少代记录日志,若设置成0则表示不记录日志
    myAlgorithm.verbose = True  # 设置是否打印输出日志信息
    myAlgorithm.drawing = 1  # 设置绘图方式(0:不绘图;1:绘制结果图;2:绘制目标空间过程动画;3:绘制决策空间过程动画)
    """===========================调用算法模板进行种群进化========================"""
    print("开始使用遗传算法")
    #生成先验种群
    # =============================================================================
    #     if max(matrix_shape[0],matrix_shape[1]) < NIND:
    #         m = max(matrix_shape[0],matrix_shape[1])
    #         n = min(matrix_shape[0],matrix_shape[1])
    #         if matrix_shape[0] > matrix_shape[1]:
    #             chrom = np.hstack([np.identity(m),np.vstack([np.identity(n),np.zeros((m-n,n))]),
    #                                2*np.ones((m,2))])
    #         else:
    #             chrom = np.hstack([np.vstack([np.identity(n),np.zeros((m-n,n))]),np.identity(m),
    #                                2*np.ones((m,2))])
    #         prepop = ea.Population(Encoding, Field, m, chrom)
    #     else:
    #
    # =============================================================================

    prenind = int(NIND / 4)
    Chrom = np.vstack([
        np.tile(
            np.hstack([
                np.ones((matrix_shape[0])) / matrix_shape[0],
                np.ones((matrix_shape[1])) / matrix_shape[1], 2, 2
            ]), [prenind, 1]),
        np.tile(
            np.hstack([
                1,
                np.zeros((matrix_shape[0] - 1)), 1,
                np.zeros((matrix_shape[1] - 1)), 2, 2
            ]), [prenind, 1]),
        np.tile(
            np.hstack([
                np.zeros((matrix_shape[0] - 1)), 1,
                np.zeros((matrix_shape[1] - 1)), 1, 2, 2
            ]), [prenind, 1])
    ])
    #print(chrom.shape)
    #Chrom = ea.ri2bs(Chrom, Field)
    prepop = ea.Population(Encoding, Field, prenind * 3, Chrom)
    myAlgorithm.call_aimFunc(prepop)
    # =============================================================================
    [BestIndi, population] = myAlgorithm.run(prepop)  # 执行算法模板,得到最优个体以及最后一代种群
    BestIndi.save()  # 把最优个体的信息保存到文件中
    """==================================输出结果=============================="""
    print('评价次数:%s' % myAlgorithm.evalsNum)
    print('时间已过 %s 秒' % myAlgorithm.passTime)
    if BestIndi.sizes != 0:
        print('最优的目标函数值为:%s' % BestIndi.ObjV[0][0])
        print('最优的控制变量值为:')
        for i in range(BestIndi.Phen.shape[1]):
            print(BestIndi.Phen[0, i])
        print(matrix_shape)
        x = np.argmax(BestIndi.Phen[0, 0:matrix_shape[0]])
        y = np.argmax(BestIndi.Phen[0, matrix_shape[0]:matrix_shape[0] +
                                    matrix_shape[1]])
        print("最优解序号与值分别为:")
        print(int(retain_a[x]), BestIndi.Phen[0, x])
        print(int(retain_e[y]), BestIndi.Phen[0, y + matrix_shape[0]])
        return int(retain_a[x]), int(retain_e[y])
    else:
        print('没找到可行解。')
        return 0, 0
def searchSoea(net_path, save_path, upper_limit=None, lower_limit=None):
    """单目标优化搜索,输入为预训练模型的权重所在路径,输出为遗传算法搜索结果的.csv保存的目录路径"""
    """==============================环境参数设置和问题类的初始化==========================="""
    # get options
    opt = BaseOptions().parse()
    if not (upper_limit is None):
        opt.max_rate = upper_limit
    if not (lower_limit is None):
        opt.min_rate = lower_limit
    # basic settings
    os.environ["CUDA_VISIBLE_DEVICES"] = str(opt.gpu_ids)[1:-1]
    if torch.cuda.is_available():
        device = "cuda"
        torch.backends.cudnn.benchmark = False
    else:
        device = "cpu"
    ##################### Get Dataloader ####################
    dataloader_train, dataloader_val = custom_get_dataloaders(opt)
    # dummy_input is sample input of dataloaders
    if hasattr(dataloader_val, "dataset"):
        dummy_input = dataloader_val.dataset.__getitem__(0)
        dummy_input = dummy_input[0]
        dummy_input = dummy_input.unsqueeze(0)
    else:
        # for imagenet dali loader
        dummy_input = torch.rand(1, 3, 224, 224)
    #####################  Create Baseline Model  ####################
    net = ModelWrapper(opt)
    # 预训练模型的权重导入
    load(net, net_path)
    flops_before, params_before = model_summary(net.get_compress_part(),
                                                dummy_input)
    compression_scheduler = distiller.file_config(net.get_compress_part(),
                                                  net.optimizer,
                                                  opt.compress_schedule_path)
    num_layer = len(compression_scheduler.policies[1])
    #####################  定义问题,并进行遗传算法 ####################
    args = dict()
    args["dataloader_train"] = dataloader_train
    args["dataloader_val"] = dataloader_val
    args["dummy_input"] = dummy_input
    args["flops_before"] = flops_before
    args["device"] = device
    args["num_layer"] = num_layer
    problem = SoeaProblem(opt, net_path, args)
    """==============================种群设置==========================="""
    Encoding = 'RI'  #编码方式,此处为整数实数混合编码
    NIND = 10  #种群规模
    Field = gp.crtfld(Encoding, problem.varTypes, problem.ranges,
                      problem.borders)  #创建区域描述器
    population = gp.Population(Encoding, Field, NIND)
    """===========================算法参数设置=========================="""
    myAlgorithm = gp.soea_DE_best_1_L_templet(problem, population)
    #实例化算法模板
    myAlgorithm.MAXGEN = 100  # 最大进化代数
    myAlgorithm.mutOper.F = 0.5  # 差分进化中的参数F
    myAlgorithm.recOper.XOVR = 0.7  # 设置交叉概率
    myAlgorithm.logTras = 10  # 设置每隔多少代记录日志,若设置成0则表示不记录日志
    myAlgorithm.verbose = True  # 设置是否打印输出日志信息
    myAlgorithm.drawing = 1  # 设置绘图方式(0:不绘图;1:绘制结果图;2:绘制目标空间过程动画)
    """==========================根据先验知识创建先知种群==============="""
    #data = pd.read_csv('/eagle_eye/search_results/old_dataset/pop_get_search_result_moea2/Phen.csv')
    #well_config=np.array(data)[5:,:]
    #prophetpop=gp.Population(Encoding,Field,5,well_config)# 实例化种群对象
    #myAlgorithm.call_aimFunc(prophetpop)# 计算先知种群的目标函数值及约束(假如有约束)
    #myAlgorithm.call_aimFunc()# 计算先知种群的目标函数值及约束(假如有约束)
    """==========================调用算法模板进行种群进化==============="""
    #[BestIndi, population] = myAlgorithm.run(prophetpop)  # 执行带先验种群的算法模板,得到最优个体以及最后一代种群
    [BestIndi, population] = myAlgorithm.run()  # 执行算法模板,得到最优个体以及最后一代种群
    BestIndi.save(os.path.join(save_path, "BestIndi"))  # 把最优个体的信息保存到文件中
    population.save(os.path.join(save_path, "Population"))  # save population
    """=================================输出结果======================="""
    print('评价次数:%s' % myAlgorithm.evalsNum)
    print('时间已过%s秒' % myAlgorithm.passTime)
    if BestIndi.sizes != 0:
        print('最优的目标函数值为: ')
        print(BestIndi.ObjV[0, :])
        print('最优的控制变量值为:')
        print(BestIndi.Phen[0, :])
        return BestIndi.ObjV[0, :], BestIndi.Phen[0, :]
    else:
        print('没找到可行解。')
        return -1, -1
Exemple #6
0
def run_wind_turbine(problem):
    """
        optimize the wind turbines solely
    """

    # settings for genetic algorithm, most parameters can be specified through the .ini file
    Encoding = "RI"  # encoding of the individuals, RI means use real numbers to encode
    NIND = int(
        problem.settings["global"]["num_individual"])  # number of individuals
    Field = ga.crtfld(Encoding, problem.varTypes, problem.ranges,
                      problem.borders)
    population = ga.Population(Encoding, Field,
                               NIND)  # generate the population instance
    myAlgo = ga.soea_DE_best_1_L_templet(problem,
                                         population)  # initialize the problem
    myAlgo.MAXGEN = int(
        problem.settings["global"]["max_generation"])  # number of generations
    myAlgo.mutOper.F = float(
        problem.settings["global"]["mut_factor"])  # mutation factor
    myAlgo.mutOper.Pm = float(
        problem.settings["global"]["mut_prob"])  # mutation probability
    myAlgo.recOper.XOVR = float(
        problem.settings["global"]["cor_factor"])  # crossover factor
    myAlgo.drawing = 0  # 0: no drawing; 1: drawing at the end of process; 2: animated drawing
    myAlgo.logTras = int(
        problem.settings["global"]["log_trace"])  # record log every * steps
    myAlgo.verbose = bool(int(
        problem.settings["global"]["log_by_print"]))  # whether print log

    # display running information for debug
    print(TIP + """
        Genetic algorithm will start with:
            Number of individuals: {},
            Number of generations: {},
            Mutation factor: {},
            Mutation Probability: {},
            Crossover factor: {}
    """.format(NIND, myAlgo.MAXGEN, myAlgo.mutOper.F, myAlgo.mutOper.Pm,
               myAlgo.recOper.XOVR) + RESET)

    # record computational time
    start_t = time.time()
    # run genetic algorithm
    [best_ind, population] = myAlgo.run()
    # delete progress bar in problem
    problem.pbar.close()
    # time interval
    end_t = time.time()
    interval_t = end_t - start_t

    # judge whether genetic algorithm failed
    if len(myAlgo.log["gen"]) == 0:
        print(ERROR + "Genetic algorithm failed!!!" + RESET)
        print(
            TIP +
            "You can re-execute these codes by amplifying your target wave farm."
            + RESET)
        exit(ga_failed)
    # otherwise, genetic algorithm succeed
    # output: optimization results of wind turbines
    best_ind.save(os.path.join(problem.settings["proj_name"], "record_array"))
    file = open(
        os.path.join(problem.settings["proj_name"], "record_array",
                     "record.txt"), "w")
    file.write("# Used time: {} s\n".format(interval_t))
    file.write("# average_objv, maximum_objv\n")
    if myAlgo.log:
        file.write("\n".join([
            "{:.6f}, {:.6f}".format(myAlgo.log["f_avg"][gen],
                                    myAlgo.log["f_max"][gen])
            for gen in range(len(myAlgo.log["gen"]))
        ]))
    file.close()

    # output: plot the objv curves
    fig = plt.figure(figsize=(10, 10))
    plt.plot(myAlgo.log["f_max"], label="max")
    plt.plot(myAlgo.log["f_avg"], label="avg")
    plt.legend()
    plt.savefig(
        os.path.join(problem.settings["proj_name"], "record_array",
                     "objvs.png"))

    # output: plot the wind turbine array figure
    fig = plt.figure(figsize=(16, 8))
    file = open(
        os.path.join(problem.settings["proj_name"], "record_array",
                     "Phen.csv"))
    # read out the best individual
    var_trace = [float(item) for item in file.readline().split(",")]
    # plot the best individual in tow sub plots
    for sub in range(1, 3):
        plt.subplot(1, 2, sub)
        for i in range(len(var_trace) // 2):
            # plt.scatter([var_trace[i]], [var_trace[i + len(var_trace) // 2]], s=100, c="k", zorder=2)
            plt.plot([var_trace[i], var_trace[i]], [
                var_trace[i + len(var_trace) // 2] -
                float(problem.settings["wind_turbine"]["rotor_diameter"]),
                var_trace[i + len(var_trace) // 2] +
                float(problem.settings["wind_turbine"]["rotor_diameter"])
            ],
                     "k-",
                     linewidth=5,
                     zorder=2)

        # tune the sub plots limits
        plt.xlim((0, problem.ub[0]))
        plt.ylim((0, problem.ub[-1]))
    # compute flow fields of the best individual
    x_array, y_array, wind_vels, turb_ints = problem.plot_field(var_trace)
    # plot wind velocity and turbulence intensity
    plt.subplot(1, 2, 1)
    plt.contourf(x_array, y_array, wind_vels, zorder=1, cmap="bwr")
    plt.subplot(1, 2, 2)
    plt.contourf(x_array, y_array, turb_ints, zorder=1, cmap="bwr")
    # output flow fields into a file
    x_array = x_array.flatten()
    y_array = y_array.flatten()
    wind_vels = wind_vels.flatten()
    turb_ints = turb_ints.flatten()
    file = open(
        os.path.join(problem.settings["proj_name"], "record_array",
                     "flow_fields.txt"), "w")
    file.write("# x, y, wind_velocity, turb_intensity\n")
    for i in range(x_array.size):
        file.write("{}, {}, {}, {}\n".format(x_array[i], y_array[i],
                                             wind_vels[i], turb_ints[i]))
    file.close()
    plt.savefig(
        os.path.join(problem.settings["proj_name"], "record_array",
                     "array.png"))
Exemple #7
0
import numpy as np
import geatpy as ea
from robot import robot
from Map import Map

Obstacle_Map = Map()
Obstacle_Map.draw_map()
robot = robot(Obstacle_Map.start, Obstacle_Map.end, Obstacle_Map, 5)
Encoding = "RI"
Field = ea.crtfld(Encoding, robot.vartype, robot.ranges, robot.borders)
population = ea.Population(Encoding, Field, robot.NIND)

Algorithm = ea.soea_DE_best_1_L_templet(robot, population)
Algorithm.MAXGEN = robot.MaxGen
Algorithm.f = 0.5
Algorithm.pc = 0.5
Algorithm.drawing = 1

[population, obj_trace, var_trace] = Algorithm.run()

best_gen = np.argmax(obj_trace[:1])
best_ObjV = obj_trace[best_gen, 1]
robot.points = var_trace[best_gen].reshape(2, robot.points_num).T

print("最优决策变量:")
for i in range(var_trace.shape[1]):
    print(var_trace[best_gen, i])
print("最优代价值:{}".format(best_ObjV))
robot.drawTrace()