Esempio n. 1
0
def each_brake(each_wait_list,L,W):
    def get_sqare_rate(in_brake_sort, L,W):
        brake_boat=quick_sort_brake(in_brake_sort, L, W)
        s=0
        for k,v in brake_boat.items():
            s=s+v[1][0]*v[1][1]
    
        sqare_rate=s/(L*W)            
        return sqare_rate,brake_boat
    
    
    
    wait_list=each_wait_list
    """===============================实例化问题对象==========================="""
    problem = MyProblem(wait_list, L, W)  # 生成问题对象
    """=================================种群设置==============================="""
    Encoding = 'P'  # 编码方式
    NIND = 6000  # 种群规模
    # ranges还是原来的,Field会在最后一行加上1
    Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges, problem.borders)  # 创建区域描述器
    population = ea.Population(Encoding, Field, NIND)  # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化)
    """===============================算法参数设置============================="""
    myAlgorithm = ea.soea_SEGA_templet(problem, population)  # 实例化一个算法模板对象,单目标模板
    # myAlgorithm=ea.moea_NSGA2_templet(problem, population)  #多目模板
    myAlgorithm.MAXGEN = 15  # 13 # 最大进化代数
    # myAlgorithm.recOper = ea.Xovox(XOVR=0.8)  # 设置交叉算子 __init__(self, XOVR=0.7, Half=False)
    # myAlgorithm.mutOper = ea.Mutinv(Pm=0.2)  # 设置变异算子
    myAlgorithm.logTras = 1  # 设置每多少代记录日志,若设置成0则表示不记录日志
    myAlgorithm.verbose = True  # 设置是否打印输出日志信息
    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]):  # (MAXGEN,Dim),进化的总代数和决策变量的维度
        print(var_trace[best_gen, i])

    best_sort_sequence = [int(each) for each in var_trace[best_gen]]  # (4000, 12)
    #best_brake_seq={i:wait_list[i] for i in best_sort_sequence}



    # best_brake_seq = wait_list[best_sort_sequence]
    # all_brake_boat = {}
    # in_brake_sort = best_brake_seq
    # sqare_rate,brake_boat=get_sqare_rate(in_brake_sort, L,W)
    # brake_num=list(brake_boat.keys())
    # brake_boat={best_sort_sequence[k]:v for k,v in brake_boat.items()}
    # all_brake_boat[0]= {'brake_boat':brake_boat,'best_use_rate':sqare_rate}
    # print('一闸最优解:组合={} \n 面积利用率={}'.format(brake_boat,sqare_rate))
    #
    # each2=np.delete(best_sort_sequence,brake_num,axis=0)
    # in_brake_sort2=np.delete(in_brake_sort,brake_num,axis=0)
    # if len(in_brake_sort2)>0:
    #     sqare_rate2,brake_boat2=get_sqare_rate(in_brake_sort2, L,W)
    #     brake_num2=list(brake_boat2.keys())
    #     #sqare_rate=sqare_rate+sqare_rate2
    #     brake_boat2={each2[k]:v for k,v in brake_boat2.items()}
    #     all_brake_boat[1] = {'brake_boat':brake_boat2,'best_use_rate':sqare_rate2}
    #     print('二闸最优解:组合={} \n 面积利用率={}'.format(brake_boat2,sqare_rate2))
    #
    #     each3=np.delete(each2,brake_num2,axis=0)
    #     in_brake_sort3=np.delete(in_brake_sort2,brake_num2,axis=0)
    #     if len(in_brake_sort3)>0:
    #         sqare_rate3,brake_boat3=get_sqare_rate(in_brake_sort3, L,W)
    #         brake_num3=list(brake_boat3.keys())
    #
    #         brake_boat3={each3[k]:v for k,v in brake_boat3.items()}
    #         all_brake_boat[2] = {'brake_boat':brake_boat3,'best_use_rate':sqare_rate3}#brake_boat3
    #         print('三闸最优解:组合={} \n 面积利用率={}'.format(brake_boat3,sqare_rate3))
    #         #sqare_rate=sqare_rate+sqare_rate3
    # print('all_brake_boat00',all_brake_boat)




    best_brake_seq = wait_list[best_sort_sequence]
    all_brake_boat = {}
    all_brake_times = 0
    in_brake_sort = best_brake_seq
    while True:
        if len(in_brake_sort) > 0 and all_brake_times < 3:
            sqare_rate, brake_boat = get_sqare_rate(in_brake_sort, L, W)
            # 将闸室序号,映射到原始信号

            brake_num = list(brake_boat.keys())

            # 更新in_brake_sort
            ##each2=np.delete(each,brake_num,axis=0)
            in_brake_sort = np.delete(in_brake_sort, brake_num, axis=0)

            brake_boat = {best_sort_sequence[k]: v for k, v in brake_boat.items()}

            best_sort_sequence = np.delete(best_sort_sequence, brake_num, axis=0)

            all_brake_boat[all_brake_times] = {'brake_boat': brake_boat, 'best_use_rate': sqare_rate}

            print('第{}闸最优解:组合={} \n 面积利用率={}'.format(all_brake_times, brake_boat, sqare_rate))


            #绘制并保存图形
            plot_save(brake_boat, all_brake_times)

            all_brake_times = all_brake_times + 1
        else:
            break
    print(' all_brake_boat11', all_brake_boat)
    
    
    
    
    
    
    
    #brake_boat = quick_sort_brake(best_brake_seq, L, W)
    
    ##将快速入闸的顺序,对应到最优选择的顺序
    #brake_boat={best_sort_sequence[k]:v for k,v in brake_boat.items()}
    
    ##将最优选择的顺序,对应到最原始的队列中的序号
    #brake_boat={wait_list_num[k]:v for k,v in brake_boat.items()}
    
    



    print('有效进化代数:%s' % (obj_trace.shape[0]))
    print('最优的一代是第 %s 代' % (best_gen + 1))
    print('评价次数:%s' % (myAlgorithm.evalsNum))
    print('时间已过 %s 秒' % (myAlgorithm.passTime))
    return all_brake_boat
Esempio n. 2
0
ranges = np.vstack(x1)  # 生成自变量的范围矩阵
borders = np.vstack([1, 1])  # 生成自变量的边界矩阵
"""========================遗传算法参数设置========================="""
NIND = 50  # 种群规模
MAXGEN = 10  # 最大遗传代数
GGAP = 0.8  # 代沟:子代与父代个体不相同的概率为0.8
selectStyle = 'sus'
# 遗传算法的选择方式设为"sus"——随机抽样选择
recombinStyle = 'xovdp'  # 遗传算法的重组方式,设为两点交叉
recopt = 0.9  # 交叉概率
pm = 0.1  # 变异概率
SUBPOP = 1  # 设置种群数为1
maxormin = -1  # 设置最大最小化目标标记为1,表示是最小化目标,-1则表示最大化目标
"""=========================开始遗传算法进化========================"""
FieldD = ga.crtfld(ranges, borders)  # 调用函数创建区域描述器
Lind = np.sum(FieldD[0, :])  # 计算编码后的染色体长度
print(FieldD)
Chrom = ga.crtbp(NIND, FieldD)  # 根据区域描述器生成二进制种群
Phen = ga.bs2int(Chrom, FieldD)  #对初始种群进行解码
LegV = np.ones((NIND, 1))  # 初始化种群的可行性列向量
[ObjV, LegV] = aimfuc(Phen, LegV)  # 计算初始种群个体的目标函数值
# 定义进化记录器,初始值为nan
pop_trace = (np.zeros((MAXGEN, 2)) * np.nan)
# 定义种群最优个体记录器,记录每一代最优个体的染色体,初始值为nan
ind_trace = (np.zeros((MAXGEN, Lind)) * np.nan)
# 开始进化!!
start_time = time.time()  # 开始计时
for gen in range(MAXGEN):
    FitnV = ga.ranking(maxormin * ObjV, LegV)  # 根据目标函数大小分配适应度值
    SelCh = ga.selecting(selectStyle, Chrom, FitnV, GGAP, SUBPOP)  # 选择
# -*- coding: utf-8 -*-
import geatpy as ea  # import geatpy
from MyProblem import MyProblem  # 导入自定义问题接口

if __name__ == '__main__':
    """================================实例化问题对象==========================="""
    problem = MyProblem()  # 生成问题对象
    """==================================种群设置=============================="""
    NIND = 30  # 种群规模
    # 创建区域描述器,这里需要创建两个,前1个变量用RI编码,剩余变量用排列编码
    Encodings = ['RI', 'P']  # 编码方式列表
    Field1 = ea.crtfld(Encodings[0], problem.varTypes[:1],
                       problem.ranges[:, :1],
                       problem.borders[:, :1])  # 创建区域描述器
    Field2 = ea.crtfld(Encodings[1], problem.varTypes[1:],
                       problem.ranges[:, 1:], problem.borders[:, 1:])
    Fields = [Field1, Field2]
    population = ea.PsyPopulation(Encodings, Fields,
                                  NIND)  # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化)
    """================================算法参数设置============================"""
    myAlgorithm = ea.moea_psy_NSGA2_templet(problem, population)  # 实例化一个算法模板对象
    myAlgorithm.MAXGEN = 200  # 最大进化代数
    """===========================调用算法模板进行种群进化======================"""
    NDSet = myAlgorithm.run()  # 执行算法模板,得到帕累托最优解集NDSet
    NDSet.save()  # 把结果保存到文件中
    # 输出
    print('用时:%s 秒' % (myAlgorithm.passTime))
    print('非支配个体数:%s 个' % (NDSet.sizes))
    print('单位时间找到帕累托前沿点个数:%s 个' % (int(NDSet.sizes // myAlgorithm.passTime)))
Esempio n. 4
0
x1 = [-1, 2]  # 自变量范围
b1 = [1, 1]  # 自变量边界
codes = [1]  # 变量的编码方式,2个变量均使用格雷编码
precisions = [5]  # 变量的精度
scales = [0]  # 采用算术刻度
ranges = np.vstack([x1]).T  # 生成自变量的范围矩阵
borders = np.vstack([b1]).T  # 生成自变量的边界矩阵
"""========================遗传算法参数设置========================="""
NIND = 40
# 种群个体数目
MAXGEN = 25
# 最大遗传代数
GGAP = 0.9
# 代沟:说明子代与父代的重复率为0.1
"""=========================开始遗传算法进化========================"""
FieldD = ga.crtfld(ranges, borders, precisions, codes, scales)  # 调用函数创建区域描述器
Lind = np.sum(FieldD[0, :])  # 计算编码后的染色体长度
Chrom = ga.crtbp(NIND, Lind)  # 根据区域描述器生成二进制种群
variable = ga.bs2rv(Chrom, FieldD)  #对初始种群进行解码
ObjV = aim(variable)  # 计算初始种群个体的目标函数值
pop_trace = (np.zeros((MAXGEN, 2)) * np.nan)  # 定义进化记录器,初始值为nan
ind_trace = (np.zeros(
    (MAXGEN, Lind)) * np.nan)  # 定义种群最优个体记录器,记录每一代最优个体的染色体,初始值为nan
# 开始进化!!
for gen in range(MAXGEN):
    FitnV = ga.ranking(-ObjV)  # 根据目标函数大小分配适应度值(由于遵循目标最小化约定,因此最大化问题要对目标函数值乘上-1)
    SelCh = ga.selecting('sus', Chrom, FitnV, GGAP)  # 选择,采用'sus'随机抽样选择
    SelCh = ga.recombin('xovsp', SelCh, 0.7)  # 重组(采用单点交叉方式,交叉概率为0.7)
    SelCh = ga.mutbin(SelCh)  # 二进制种群变异
    variable = ga.bs2rv(SelCh, FieldD)  # 对育种种群进行解码(二进制转十进制)
    ObjVSel = aim(variable)  # 求育种个体的目标函数值
Esempio n. 5
0
    def optimize(datasetX, datasetY, featureNamesAfterCombination,
                 featureOptimizationParams, datasetParams,
                 forecastModelParams):
        featureNamesAfterOptimization = []
        featureOptimizationProcess = None
        isPerformOptimization = featureOptimizationParams[
            "isPerformOptimization"]
        if isPerformOptimization:
            dim = len(featureNamesAfterCombination)
            problem = FeatureOptimizationProblem(datasetX, datasetY,
                                                 featureNamesAfterCombination,
                                                 datasetParams,
                                                 forecastModelParams)
            encoding = 'RI'
            popNum = 10
            field = ea.crtfld(encoding, problem.varTypes, problem.ranges,
                              problem.borders)
            pop = ea.Population(encoding, field, popNum)

            if dim < 7:
                # 维度不高时采用穷举
                Phen = []
                for i in range(1, pow(2, dim)):
                    numStr = MathNormalUtils.toBinaryWithFixedLength(i, dim)
                    numArray = list(map(int, numStr))
                    Phen.append(numArray)
                # 受维数灾影响 随机优化5个特征组合
                resultlist = random.sample(range(len(Phen)), 3)
                Phen = np.array(Phen)
                # Phen = Phen[resultlist, :]
                pop.Phen = Phen
                problem.aimFunc(pop)
                objTrace, varTrace = pop.ObjV, pop.Phen
                objTrace = NumpyUtils.hStackByCutHead(objTrace, objTrace)
            else:

                algorithm = ea.soea_SEGA_templet(problem, pop)
                # 算法最大进化代数
                algorithm.MAXGEN = 10
                # 0表示不绘图;1表示绘图;2表示动态绘图
                algorithm.drawing = 1

                [pop, objTrace, varTrace] = algorithm.run()
            featureOptimizationProcess = {
                "objTrace": objTrace,
                "varTrace": varTrace
            }
            bestGen = np.argmin(problem.maxormins * objTrace[:, 1])
            bestVar = varTrace[bestGen, :]
            bestVar = [int(x) for x in bestVar]
            bestVar = np.array(bestVar)

            featureCombinationParams = {
                "isPerformCombination": True,
                "featureFlags": bestVar
            }
            featureCombination = FeatureCombination(
                datasetX, datasetY, featureNamesAfterCombination,
                featureCombinationParams)
            datasetAfterOptimizationX, datasetAfterOptimizationY, featureNamesAfterOptimization = featureCombination.getDatasetAfterCombination(
            )
        else:
            datasetAfterOptimizationX = datasetX
            datasetAfterOptimizationY = datasetY
            featureNamesAfterOptimization = featureNamesAfterCombination

            dataset = Dataset(datasetAfterOptimizationX,
                              datasetAfterOptimizationY, datasetParams)
            forecastTemplate = ForecastTemplate(dataset, forecastModelParams)
            loss = forecastTemplate.getObjective()
        if (datasetAfterOptimizationX is None) or (datasetAfterOptimizationY is
                                                   None):
            raise Exception("特征优化中全部特征未被选取,请检查参数!")
        return datasetAfterOptimizationX, datasetAfterOptimizationY, featureNamesAfterOptimization, featureOptimizationProcess
Esempio n. 6
0
# -*- coding: utf-8 -*-
"""main.py"""
import numpy as np
import geatpy as ea  # import geatpy
import sys, os
sys.path.insert(0,
                os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from mix_encoder.MyProblem import MyProblem  # 导入自定义问题接口
"""===========================实例化问题对象========================"""
problem = MyProblem()  # 生成问题对象
"""=============================种群设置==========================="""
NIND = 40  # 种群规模
# 创建区域描述器,这里需要创建两个,前2个变量用RI编码,其余用排列编码
Encodings = ['RI', 'P']
Field1 = ea.crtfld(Encodings[0], problem.varTypes[:2], problem.ranges[:, :2],
                   problem.borders[:, :2])
Field2 = ea.crtfld(Encodings[1], problem.varTypes[2:], problem.ranges[:, 2:],
                   problem.borders[:, 2:])
Fields = [Field1, Field2]
population = ea.PsyPopulation(Encodings, Fields,
                              NIND)  # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化)
"""===========================算法参数设置=========================="""
myAlgorithm = ea.soea_psy_SEGA_templet(problem, population)  # 实例化一个算法模板对象
myAlgorithm.MAXGEN = 25  # 最大进化代数
"""======================调用算法模板进行种群进化===================="""
[population, obj_trace, var_trace] = myAlgorithm.run()  # 执行算法模板
population.save()  # 把最后一代种群的信息保存到文件中
# 输出结果
best_gen = np.argmax(obj_trace[:, 1])  # 记录最优种群是在哪一代
best_ObjV = obj_trace[best_gen, 1]
print('最优的目标函数值为:%s' % (best_ObjV))
Esempio n. 7
0
x = np.linspace(-1, 2, 200)
plt.plot(x, aim(x))  # 绘制目标函数图像
"""============================变量设置============================"""
x1 = [-1, 2]  # 自变量范围
b1 = [1, 1]  # 自变量边界
varTypes = np.array([0])  # 自变量的类型,0表示连续,1表示离散
Encoding = 'BG'  # 'BG'表示采用二进制/格雷编码
codes = [1]  # 变量的编码方式,2个变量均使用格雷编码
precisions = [4]  # 变量的编码精度
scales = [0]  # 采用算术刻度
ranges = np.vstack([x1]).T  # 生成自变量的范围矩阵
borders = np.vstack([b1]).T  # 生成自变量的边界矩阵
"""=========================遗传算法参数设置========================="""
NIND = 40  # 种群个体数目
MAXGEN = 25  # 最大遗传代数
FieldD = ea.crtfld(Encoding, varTypes, ranges, borders, precisions, codes,
                   scales)  # 调用函数创建区域描述器
Lind = int(np.sum(FieldD[0, :]))  # 计算编码后的染色体长度
obj_trace = np.zeros((MAXGEN, 2))  # 定义目标函数值记录器
var_trace = np.zeros((MAXGEN, Lind))  # 定义染色体记录器,记录每一代最优个体的染色体
"""=========================开始遗传算法进化========================"""
start_time = time.time()  # 开始计时
Chrom = ea.crtbp(NIND, Lind)  # 生成种群染色体矩阵
variable = ea.bs2real(Chrom, FieldD)  # 对初始种群进行解码
ObjV = aim(variable)  # 计算初始种群个体的目标函数值
best_ind = np.argmax(ObjV)  # 计算当代最优个体的序号
# 开始进化
for gen in range(MAXGEN):
    FitnV = ea.ranking(-ObjV)  # 根据目标函数大小分配适应度值(由于遵循目标最小化约定,因此最大化问题要对目标函数值乘上-1)
    SelCh = Chrom[ea.selecting('rws', FitnV, NIND - 1), :]  # 选择,采用'rws'轮盘赌选择
    SelCh = ea.recombin('xovsp', SelCh, 0.7)  # 重组(采用两点交叉方式,交叉概率为0.7)
    SelCh = ea.mutbin(Encoding, SelCh)  # 二进制种群变异
Esempio n. 8
0
    'font.serif': 'Times New Roman',
    # 'figure.dpi': 300,
    # 'savefig.dpi': 300,
    # 'font.style':'normal', # ‘normal’, ‘italic’ or ‘oblique’.
    # 'font.weight':'normal', #or 'blod'
    'font.size': 12,  #or large,small
}
rcParams.update(params)
"""================================实例化问题对象============================"""
problem = MyProblem()  # 生成问题对象
"""==================================种群设置==============================="""
NIND = 60  # 种群规模
# 创建区域描述器,这里需要创建两个,前25个变量用P编码,剩余变量用RI编码
Encodings = ['P', 'RI']
Field1 = ea.crtfld(Encodings[0], problem.varTypes[:problem.num],
                   problem.ranges[:, :problem.num],
                   problem.borders[:, :problem.num])
Field2 = ea.crtfld(Encodings[1], problem.varTypes[problem.num:],
                   problem.ranges[:, problem.num:],
                   problem.borders[:, problem.num:])
Fields = [Field1, Field2]
population = ea.PsyPopulation(Encodings, Fields,
                              NIND)  # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化)

# prophetPop = ea.PsyPopulation(Encodings, Fields, 2) # 实例化先知种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化)
# from MyFunction import Chroms_pro
# prophetPop.initChrom( NIND = 2)
# prophetPop.Chroms=Chroms_pro
"""================================算法参数设置============================="""
myAlgorithm = My_soea_psy_EGA_templet(problem, population)  # 实例化一个算法模板对象
myAlgorithm.MAXGEN = 400  # 最大进化代数
Esempio n. 9
0
    本案例通过降维的方法,将等式约束化成了不等式约束,大大拓宽了可行解的空间,方便遗传算法求解
    此外,本案例展示了利用多种群竞争的进化算法模板sga_mpc_real_templet了解决该问题。
"""

import numpy as np
import geatpy as ga

# 获取函数接口地址
AIM_M = __import__('aimfuc')
PUN_M = __import__('punishing')
# 变量设置
x1 = [0, 1]  # 自变量1的范围
x2 = [0, 1]  # 自变量2的范围
b1 = [1, 1]  # 自变量1是否包含下界
b2 = [1, 1]  # 自变量2是否包含上界
ranges = np.vstack([x1, x2]).T  # 生成自变量的范围矩阵
borders = np.vstack([b1, b2]).T  # 生成自变量的边界矩阵
precisions = [
    2
] * 2  # 在二进制/格雷码编码中代表自变量的编码精度,当控制变量是连续型时,根据crtfld参考资料,该变量只表示边界精度,故设置为一定的正数即可
newRanges = ga.meshrng(ranges, gridnum=2)  # 对控制变量范围进行网格化,网格边长为2
# 生成网格化后的区域描述器集合
FieldDRs = []
for i in range(len(newRanges)):
    FieldDRs.append(ga.crtfld(newRanges[i], borders, precisions))
# 调用编程模板
[pop_trace, var_trace, times] = ga.sga_mpc_real_templet(AIM_M, 'aimfuc', PUN_M,\
 'punishing', FieldDRs, problem = 'R', maxormin = -1, MAXGEN = 50, NIND = 50,\
 SUBPOP = 1, GGAP = 0.9, selectStyle = 'tour', recombinStyle = 'xovdprs',\
 recopt = 0.9, pm = 0.3, distribute = True, drawing = 1)
Esempio n. 10
0
def each_brake(each_wait_list, L, W, brake_num, wait_list_num):
    wait_list = each_wait_list
    """===============================实例化问题对象==========================="""
    problem = MyProblem(wait_list, L, W)  # 生成问题对象
    """=================================种群设置==============================="""
    Encoding = 'P'  # 编码方式
    NIND = 6000  #4000,6000 种群规模
    # ranges还是原来的,Field会在最后一行加上1
    Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges,
                      problem.borders)  # 创建区域描述器
    population = ea.Population(Encoding, Field,
                               NIND)  # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化)
    """===============================算法参数设置============================="""
    myAlgorithm = ea.soea_SEGA_templet(problem,
                                       population)  # 实例化一个算法模板对象,单目标模板
    # myAlgorithm=ea.moea_NSGA2_templet(problem, population)  #多目模板
    myAlgorithm.MAXGEN = 3  # 13 # 最大进化代数
    # myAlgorithm.recOper = ea.Xovox(XOVR=0.8)  # 设置交叉算子 __init__(self, XOVR=0.7, Half=False)
    # myAlgorithm.mutOper = ea.Mutinv(Pm=0.2)  # 设置变异算子
    myAlgorithm.logTras = 1  # 设置每多少代记录日志,若设置成0则表示不记录日志
    myAlgorithm.verbose = False  # 设置是否打印输出日志信息
    myAlgorithm.drawing = 0  # 设置绘图方式(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]):  # (MAXGEN,Dim),进化的总代数和决策变量的维度
        print(var_trace[best_gen, i])

    best_sort_sequence = [int(each)
                          for each in var_trace[best_gen]]  # (4000, 12)
    #best_brake_seq={i:wait_list[i] for i in best_sort_sequence}
    best_brake_seq = wait_list[best_sort_sequence]
    #闸次原始顺序
    brake_boat = quick_sort_brake(best_brake_seq, L, W)

    # #将快速入闸的顺序,对应到最优选择的顺序
    # brake_boat={best_sort_sequence[k]:v for k,v in brake_boat.items()}
    #
    # #将最优选择的顺序,对应到最原始的队列中的序号
    # brake_boat={wait_list_num[k]:v for k,v in brake_boat.items()}

    # N_e = len(brake_boat)
    # plot_example(X, Y, li_e, wi_e, N_e,brake_num=brake_num)
    best_use_rate = plot_save(brake_boat, brake_num)
    print('plot finished')

    # print('有效进化代数:%s' % (obj_trace.shape[0]))
    # print('最优的一代是第 %s 代' % (best_gen + 1))
    # print('评价次数:%s' % (myAlgorithm.evalsNum))
    # print('时间已过 %s 秒' % (myAlgorithm.passTime))
    return {
        'brake_boat': brake_boat,
        'best_sort_sequence': best_sort_sequence,
        'best_use_rate': best_use_rate
    }
Esempio n. 11
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"))
Esempio n. 12
0
def main_1(filepath_1):
    filepath_1 = 'input_1.json'
    input_1 = _get_json_(filepath_1)
    filepath_2 = input_1['filePath']  #读入csv路径
    data = pd.read_csv(filepath_2)
    # 必须添加header=None,否则默认把第一行数据处理成列名导致缺失
    data_1 = pd.DataFrame(data)

    num = len(data_1)  # 病人总的数目
    morning_time = int(input_1['startTime'].split(':')[0]) * 60 + int(
        input_1['startTime'].split(':')[1])
    afternoon_time = int(input_1['endTime'].split(':')[0]) * 60 + int(
        input_1['endTime'].split(':')[1])
    n_x = int(input_1['orNum'])  #手术室数目
    n_y = int(input_1['recoverNum'])  #复苏室数目
    t_s = int(input_1['minRecoverTime'])  #最小复苏时间

    calculte_r = calculte(data, n_x, n_y, t_s, morning_time,
                          afternoon_time)  # 实例化
    list_doctID, list_patientID, list_operation, list_sleepy, list_clean, list_start, list_index_or, list_of_all = calculte_r._process_data_(
        num)
    #   print(list_doctID, list_sleepy, list_operation, list_clean, list_patientID, list_start, list_index_or)

    Encoding = 'RI'  # 编码方式为实数
    conordis = 1  # 染色体解码后得到的变量是离散的
    NIND = 50  # 种群规模

    problem = MyProblem(num, n_x, n_y, NIND, list_of_all, morning_time,
                        afternoon_time)
    # n_o为手术室数量,n_r为复苏室数量, chrom为染色体[1,3,2]表示第一台
    # 手术在1号手术室在1号手术室内做,o_time[30,100,60]表示第一台手术时长30分钟,
    # c_time表示清洁时长,r_time表示复苏时长(0或自定义最小复苏时长默认为60min)
    # 生成问题对象
    Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges,
                      problem.borders)  # 创建区域描述器
    population = ea.Population(Encoding, Field, NIND)  # 创建种群对象
    x_chuandai = 20
    id_trace = (np.zeros(
        (x_chuandai, num)) * np.nan)  # 定义变量记录器,记录决策变量值,初始值为nan
    Algorithm_1 = Algorithm(problem, population, id_trace)  # 实例化一个算法模板对象

    Algorithm_1.MAXGEN = x_chuandai  # 最大遗传代数
    [population, obj_trace, var_trace,
     id_trace] = Algorithm_1.run()  # 执行算法模板   #如何返回最优解

    best_gen = np.argmin(obj_trace[:, 1])  # 记录最优种群是在哪一代
    best_ObjV = obj_trace[best_gen, 1]  # 目标函数值最优

    #mean_ObjV = obj_trace[best_gen, 0]                      # 均值

    best_paixu = var_trace[best_gen, :]  # 最优解
    ARRAY = id_trace[best_gen, :]
    print('最优的目标函数值为:%s' % (best_ObjV))
    print('有效进化代数:%s' % (obj_trace.shape[0]))
    print('最优的一代是第 %s 代' % (best_gen + 1))
    print('时间已过 %s 秒' % (Algorithm_1.passTime))

    # id_trace = (np.zeros((self.MAXGEN, NVAR)) * np.nan)  # 定义变量记录器,记录决策变量值,初始值为nan

    #返回一个ARRAY将list调整并传给best_result函数
    sel_data = list_of_all[:, list(ARRAY.astype(np.int))]
    #list_doctID, list_patientID, list_operation, list_sleepy, list_clean, list_start, list_index_or
    list_doctID_2 = sel_data[0]
    list_patientID_2 = sel_data[1]
    list_operation_2 = sel_data[2]
    list_sleepy_2 = sel_data[3]
    list_clean_2 = sel_data[4]
    list_start_2 = sel_data[5]
    list_index_or_2 = sel_data[6]
    ARRAY_1 = ARRAY.astype(np.int)
    best_paixu_1 = best_paixu.astype(np.int)
    print('最优解的index:', ARRAY_1)
    print('最优解的手术室号:', best_paixu_1)
    o_total_time, o_total_r_time, o_total_empty_time, overtime_work, result = calculte_r._best_result_(
        best_paixu_1, num, list_sleepy_2, list_operation_2, list_clean_2)
    # o_total_time是手术室工作的总时长// o_total_r_time是手术室总复苏时长// o_total_empty_time是手术室总空闲时长// overtime_work是手术室总超时工作时长//

    index_or_1, list_clean_1, list_sleepy_1, list_start_1 = calculte_r._get_list_(
        num, result, ARRAY_1, list_clean, list_operation)
    #用于返回数据
    data['复苏时间'] = list_sleepy_1  # 手术室内的复苏时间
    data['清洁时间'] = list_clean_1  # 手术室内的清洁时间
    data['手术开始时间'] = list_start_1  # 手术室每一台手术的开始时间
    data['手术室编码'] = index_or_1  # 手术室内的手术的编码
    #存入csv
    data.to_csv('output.csv', sep=',', header=True)
    #json输出内容
    orRatio = str((o_total_time - o_total_r_time - list_clean_1.sum()) /
                  (o_total_time + o_total_empty_time))
    cleanRatio = str(list_clean_1.sum() / (o_total_time + o_total_empty_time))
    recoverRoomratio = str(o_total_r_time /
                           (o_total_time + o_total_empty_time))
    emptyRatio = str(o_total_empty_time / (o_total_time + o_total_empty_time))
    extraHours = overtime_work
    extraHoursRatio = (extraHours / o_total_time)
    overtimeRatio = str(overtime_work.sum() / o_total_time)
    dict_2 = {}
    dict_2["filePath"] = "output.csv"
    dict_2["orRatio"] = orRatio  # 手术室利用率
    dict_2["recoverRatio"] = recoverRoomratio  # 复苏室利用率
    dict_2["cleanRatio"] = cleanRatio  # 用于清洁的时间
    dict_2["emptyRatio"] = emptyRatio  # 闲置时间比例
    dict_2["extraHours"] = extraHours.tolist()  # 加班总时间(分钟)
    dict_2["extraHoursRatio"] = extraHoursRatio.tolist()  # 每一个元素
    dict_2["overtimeRatio"] = overtimeRatio  # 额外加班时间

    # 用于饼图展示的比例:

    return dict_2
Esempio n. 13
0
import numpy as np
import geatpy as ea
from hsdn_near_optimal_performance import SOHybridNetTEOptimizeProblem
max_val = float('inf')


if __name__ == "__main__":
    # 初始化连接图
    graph = np.array([[0, 1, 1, max_val], [1, 0, 1, 1], [1, 1, 0, 1], [max_val, 1, 1, 0]])
    band_width = np.array([[0.0, 100.0, 100.0, 0.0], [0.0, 0.0, 100.0, 100.0], [0.0, 0.0, 0.0, 100.0],
                           [0.0, 0.0, 0.0, 0.0]])
    traffic = np.array([[0, 10, 15, 10], [10, 0, 9, 8], [10, 10, 0, 20], [10, 10, 10, 0]])
    sdn_node_count = 1
    problem = SOHybridNetTEOptimizeProblem(graph, sdn_node_count, traffic, band_width)
    Encodings = ['P', 'RI']
    Field1 = ea.crtfld(Encodings[0], problem.varTypes[:sdn_node_count],
                       problem.ranges[:, :sdn_node_count], problem.borders[:, :sdn_node_count])  # 创建区域描述器
    Field2 = ea.crtfld(Encodings[1], problem.varTypes[sdn_node_count:],
                       problem.ranges[:, sdn_node_count:], problem.borders[:, sdn_node_count:])  # 创建区域描述器
    Fields = [Field1, Field2]

    # 种群规模
    NIND = 50
    population = ea.PsyPopulation(Encodings, Fields, NIND)
    myAlgorithm = ea.moea_psy_NSGA3_templet(problem, population)
    myAlgorithm.MAXGEN = 20
    myAlgorithm.drawing = 2
    NDSet = myAlgorithm.run()
    NDSet.save()  # 把结果保存到文件中
    # 输出
    print('用时:%s 秒' % myAlgorithm.passTime)
    print('非支配个体数:%s 个' % NDSet.sizes)
Esempio n. 14
0
def Scheduler(input_json, input_config):
    """
    调度器
    用法:
    from MultiScheduler import Scheduler
    output_json, output_overall = Scheduler(input_json, input_config)

    输入:
    input_json:患者信息
    input_json = [
        {
            "age": "70",
            "anaesthetic": "全身麻醉",
            "department": "心血管科",
            "doctorName": "李四",
            "gender": "男",
            "id": "1",
            "key": "0",
            "name": "王小舟",
            "operatingName": "心脏搭桥手术",
            "orId": "",
            "predTime": "120",
            "rank": "2",
            "startTime": ""
        },{
            "age": "23",
            "anaesthetic": "全身麻醉",
            "department": "妇产科",
            "doctorName": "王五",
            "gender": "女",
            "id": "1",
            "key": "0",
            "name": "张小臻",
            "operatingName": "剖腹产",
            "orId": "",
            "predTime": "120",
            "rank": "2",
            "startTime": ""
        }
    ]
    input_config:环境变量,手术室数量、复苏室数量等信息
    input_config = {
        "recover_min": 60, #最小恢复时间
        "end_time": "3:30", #下班时间
        "operRoom": 3,  #手术室数目
        "recover": 3,  #恢复室数目
        "start_time": "08:30" #上班时间
    }
    输出:
    output_json:添加手术室号、开始时间等的病人信息
    output_json = [
        {
            "key": "0",
            "id": "1",
            "name": "尹小帆",
            "gender": "男",
            "age": "70",
            "department": "心血管科",
            "operatingName": "心脏搭桥手术",
            "doctorName": "李四",
            "predTime": "120",
            "anaesthetic": "全身麻醉",
            "rank": "2",
            "orId": "10",
            "startTime": "8:00",
            "recoverDuration": 15,
            "cleanDuration": 20
        }, {
            "key": "1",
            "id": "2",
            "name": "司徒",
            "gender": "女",
            "age": "23",
            "department": "妇产科",
            "operatingName": "剖腹产手术",
            "doctorName": "王小二",
            "predTime": "100",
            "anaesthetic": "局部麻醉",
            "rank": "1",
            "orId": "7",
            "startTime": "9:00",
            "recoverDuration": 15,
            "cleanDuration": 20
        }
        ]
    output_overall:手术室利用比例,恢复室利用比例、各手术室超出工作时间和比例
    output_overall = {
    "orRatio": "0.99999",
    "recoverRoomRatio": "0.8",
    "extraHours": [4, 5, 6],
    "extraHourRatio": [0.4, 0.2, 0.9]
    }
    """
    #===================以下为程序部分===================#
    if (not input_json) or (not input_config):  #判断空字符串输入,返回空字符串
        return '', ''

    data = pd.DataFrame(input_json)
    input_1 = input_config

    num = len(data)  # 病人总的数目
    morning_time = int(input_1['start_time'].split(':')[0]) * 60 + int(
        input_1['start_time'].split(':')[1])
    afternoon_time = int(input_1['end_time'].split(':')[0]) * 60 + int(
        input_1['end_time'].split(':')[1])
    n_x = int(input_1['operRoom'])  #手术室数目
    n_y = int(input_1['recover'])  #复苏室数目
    t_s = int(input_1['doctor'])  #最小复苏时间
    calculte_r = calculte(data, n_x, n_y, t_s, morning_time,
                          afternoon_time)  # 实例化
    list_doctID, list_patientID, list_operation, list_sleepy, list_clean, list_start, list_index_or, list_of_all = calculte_r._process_data_(
        num)
    list_of_all_1 = list_of_all[:]  # 复制list_of_all为list_of_all_1
    list_start_temple = list_start
    list_index_or_temple = list_index_or
    list_start_3 = np.zeros((num, ), dtype=np.int)
    list_index_or_3 = np.zeros((num, 1), dtype=np.int)
    list_clean = list_clean.astype(np.int)
    # print(list_clean)

    temple_for_startime = np.where(list_start_temple != '')[0]
    for value in temple_for_startime:
        neirong = (int((list_start[value].split(':')[0]))) * 60 + int(
            (list_start[value].split(':')[1])) - morning_time
        list_start_3[value] = neirong  # list_start_3中存入的是有开始时间病人的开始时间

    temple_for_orNum = np.where(list_index_or_temple != '')[0]
    index_index_or_temple_1 = np.array(
        [], dtype=np.int)  # list_start_3中存储的是转换后的list_start值(分钟)
    for value in temple_for_orNum:
        list_index_or_3[value] = list_index_or[
            value]  # list_index_or_3中存入的是有手术室号病人的手术室号
        # print(list_index_or_3[value][0])

    set_jiao = set(temple_for_startime) & set(temple_for_orNum)
    list_cha_start_time = list(set(temple_for_startime) - set_jiao)
    list_cha_index_or = list(set(temple_for_orNum) - set_jiao)
    list_jiao = list(set_jiao)

    list_cha_index_or_1 = list_cha_index_or[:]  # 复制仅绑定手术室号的值

    dict_for_xunhuan = {}  # 存入需要找到并确定的dict的值
    # 对仅绑定手术室号的情况进行序列调整, 这一列需要被传递
    for index, value in enumerate(list_cha_index_or):
        a = 0
        for j in temple_for_startime:
            if value > j:
                a -= 1
        list_cha_index_or_1[index] = value + a
        dict_for_xunhuan[value + a] = [list_index_or_3[value][0], value]
        # dict_for_xunhuan中存入的是每一个人对应的手术室号0
        # 和它实际的位

        # ARRAY对应的字典
    dict_for_result = {}  # 存入需要找到并确定的dict的值
    for i in range(num):
        a = 0
        for j in temple_for_startime:
            if i > j:
                a -= 1
        dict_for_result[i] = [i + a]

    for k in temple_for_startime:
        del dict_for_result[k]

    length_sum = len(temple_for_startime)  # 绑定了时间的人数
    Encoding = 'RI'  # 编码方式为实数                                           # 染色体解码后得到的变量是离散的
    NIND = 50  # 种群规模

    problem = MyProblem(num - length_sum, n_x, n_y, NIND, list_of_all_1,
                        morning_time, afternoon_time, dict_for_xunhuan)
    # n_o为手术室数量,n_r为复苏室数量, chrom为染色体[1,3,2]表示第一台
    # 手术在1号手术室在1号手术室内做,o_time[30,100,60]表示第一台手术时长30分钟,
    # c_time表示清洁时长,r_time表示复苏时长(0或自定义最小复苏时长默认为60min)
    # 生成问题对象
    Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges,
                      problem.borders)  # 创建区域描述器
    population = ea.Population(Encoding, Field, NIND)  # 创建种群对象
    x_chuandai = 30
    id_trace = (np.zeros(
        (x_chuandai, num - length_sum)) * np.nan)  # 定义变量记录器,记录决策变量值,初始值为nan
    # problem, population, id_trace, n_x, list_jiao, list_start_3, list_operation, list_sleepy, list_index_or_3, list_doctID, list_clean, list_cha_start_time
    Algorithm_1 = Algorithm(problem, population, id_trace, n_x, list_jiao,
                            list_start_3, list_operation, list_sleepy,
                            list_index_or_3, list_doctID, list_clean,
                            list_cha_start_time)  # 实例化一个算法模板对象

    Algorithm_1.MAXGEN = x_chuandai  # 最大遗传代数
    [population, obj_trace, var_trace, id_trace,
     new_fixed_dict] = Algorithm_1.run()  # 执行算法模板   #如何返回最优解

    best_gen = np.argmin(obj_trace[:, 1])  # 记录最优种群是在哪一代
    best_ObjV = obj_trace[best_gen, 1]  # 目标函数值最优

    # mean_ObjV = obj_trace[best_gen, 0]                      # 均值

    best_paixu = var_trace[best_gen, :]  # 最优解
    ARRAY = id_trace[best_gen, :]

    sel_data = list_of_all_1[:, list(ARRAY.astype(np.int))]
    # list_doctID, list_patientID, list_operation, list_sleepy, list_clean, list_start, list_index_or
    list_doctID_2 = sel_data[0]
    list_patientID_2 = sel_data[1]
    list_operation_2 = sel_data[2]
    list_sleepy_2 = sel_data[3]
    list_clean_2 = sel_data[4]
    list_start_2 = sel_data[5]
    list_index_or_2 = sel_data[6]
    ARRAY_1 = ARRAY.astype(np.int)
    best_paixu_1 = best_paixu.astype(np.int)
    o_total_time, o_total_r_time, o_total_empty_time, overtime_work, result, fixed_result, o_c_time = calculte_r._best_result_(
        best_paixu_1, new_fixed_dict, list_sleepy_2, list_operation_2,
        list_clean_2, list_doctID_2)
    # o_total_time是手术室工作的总时长// o_total_r_time是手术室总复苏时长// o_total_empty_time是手术室总空闲时长// overtime_work是手术室总超时工作时长//
    index_or_1, list_clean_1, list_sleepy_1, list_start_1 = calculte_r._get_list_(
        num, result, fixed_result, ARRAY_1, list_clean, list_operation,
        dict_for_xunhuan, list_start, dict_for_result)

    data['recoverDuration'] = list_sleepy_1  # 手术室内的复苏时间
    data['cleanDuration'] = list_clean_1  # 手术室内的清洁时间
    data['startTime'] = list_start_1  # 手术室每一台手术的开始时间
    data['orId'] = index_or_1  # 手术室内的手术的编码
    data['predTime'] = list_operation
    #存入csv
    #json输出内容
    orRatio = str(
        (o_total_time.sum() - o_total_r_time.sum() - list_clean_1.sum()) /
        (o_total_time.sum() + o_total_empty_time.sum()))
    everyorRatio = (o_total_time - o_total_r_time -
                    o_c_time) / (o_total_time + o_total_empty_time)
    cleanRatio = str(list_clean_1.sum() /
                     (o_total_time.sum() + o_total_empty_time.sum()))
    recoverRoomratio = str(o_total_r_time.sum() /
                           (o_total_time.sum() + o_total_empty_time.sum()))
    emptyRatio = o_total_empty_time / (o_total_time + o_total_empty_time)
    extraHours = overtime_work
    extraHoursRatio = (extraHours / o_total_time)
    overtimeRatio = str(overtime_work.sum() / o_total_time.sum())
    # dict_2 = {}
    # dict_2["filePath"] = "output.csv"
    # dict_2["orRatio"] = orRatio                   # 手术室利用率
    # dict_2["recoverRatio"] = recoverRoomratio     # 复苏室利用率
    # dict_2["cleanRatio"] = cleanRatio             # 用于清洁的时间
    # dict_2["emptyRatio"] = emptyRatio             # 闲置时间比例
    # dict_2["extraHours"] = extraHours.tolist()             # 加班总时间(分钟)
    # dict_2["extraHoursRatio"] = extraHoursRatio.tolist()   # 每一个元素
    # dict_2["overtimeRatio"] = overtimeRatio       # 额外加班时间

    # 用于饼图展示的比例:
    data.to_csv('output.csv', sep=',', header=True)
    output_json = data.to_json(orient='records', force_ascii=False)
    output_overall = {
        "orRatio": orRatio,
        "everyorRatio": everyorRatio.tolist(),
        "recoverRoomRatio": recoverRoomratio,
        "emptyRatio": emptyRatio.tolist(),
        "cleanRatio": cleanRatio,
        "extraHours": extraHours.tolist(),
        "extraHourRatio": extraHoursRatio.tolist(),
        "overtimeRatio": overtimeRatio
    }

    return output_json, output_overall
Esempio n. 15
0
    x3 - x1 <= 0
    x4 - x2 <= 0
    x1,x2,x3,x4均为0或1
    本案例调用了“sga_new_real_templet”这个算法模板,其详细用法可利用help命令查看,或是在github下载并查看源码
    调用算法模板时可以设置drawing=2,此时算法模板将在种群进化过程中绘制动画,但注意执行前要在Python控制台执行命令matplotlib qt5。
"""

import numpy as np
import geatpy as ga

# 获取函数接口地址
AIM_M = __import__('aimfuc')
# 变量设置
ranges = np.vstack([np.zeros((1, 4)), np.ones((1, 4))])  # 生成自变量的范围矩阵
borders = np.vstack([np.ones((1, 4)), np.ones((1, 4))])  # 生成自变量的边界矩阵
FieldDR = ga.crtfld(ranges, borders)  # 生成区域描述器
# 调用编程模板
[pop_trace, var_trace, times] = ga.sga_new_real_templet(AIM_M,
                                                        'aimfuc',
                                                        None,
                                                        None,
                                                        FieldDR,
                                                        problem='I',
                                                        maxormin=-1,
                                                        MAXGEN=50,
                                                        NIND=10,
                                                        SUBPOP=1,
                                                        GGAP=0.9,
                                                        selectStyle='sus',
                                                        recombinStyle='xovdp',
                                                        recopt=0.9,
Esempio n. 16
0
    Use GA algorithm to search the sentence: Tom is a little boy.
    Use 'help' go get more tutorials about the algorithm templet 'sga_new_real_templet' we use there, 
    or read the source codes in github.
    You can set 'drawing = 2' to get a dynamic graph. (But remember to run the command 'matplotlib qt5' in Python console before.)
"""

import numpy as np
import geatpy as ga

strs = 'Tom is a little boy.' # define the sentence
words = []
for c in strs:
    words.append(ord(c)) # change the words to ascii code.

# Attention: you had better put the aim-function in another file.
def aim(Phen, LegV): # define the aim function
    real = words
    diff = np.sum((Phen - real)**2, 1)
    return [np.array([diff]).T, LegV]

if __name__ == "__main__":
    AIM_M = __import__('main') # get the handle of aim-function
    # variables setting
    ranges = np.vstack([32 * np.ones((1, len(words))), 122 * np.ones((1, len(words)))]) # ranges of variables
    borders = np.vstack([np.ones((1, len(words))), 122 * np.ones((1, len(words)))]) # borders of variables
    FieldDR = ga.crtfld(ranges, borders) # create FieldDR
    # call the GEA algorithm template
    [pop_trace, var_trace, times] = ga.sga_new_real_templet(AIM_M, 'aim', None, None, FieldDR, problem = 'I', maxormin = 1, MAXGEN = 2000, NIND = 50, SUBPOP = 1, GGAP = 0.9, selectStyle = 'etour', recombinStyle = 'xovdprs', recopt = 0.9, pm = None, distribute = True, drawing = 1)
    # output results
    for num in var_trace[np.argmin(pop_trace[:, 1]), :]:
        print(chr(int(num)), end = '')
Esempio n. 17
0
import numpy as np 
import geatpy as ea
from MyProblem import MyProblem #导入自定义问题接口
'''=========== 实例化问题对象==========='''
steps = [3,1,4,2,3,2,2,2,2,1]
problem = MyProblem() #生成问题对象

'''=========== 种群设置==========='''
NIND = 40 #种群规模
# 创建区域描述器,这里需要创建两个,分别是工序编码 机器编码
Encodings = ['RI', 'RI']
# crtfld (生成译码矩阵,俗称“区域描述器”)
Field1 = ea.crtfld(Encodings[0], problem.varTypes[:sum(steps)], problem.ranges[:,:sum(steps)], problem.borders[:,:sum(steps)]) # 创建区域描述器
Field2 = ea.crtfld(Encodings[1], problem.varTypes[sum(steps):], problem.ranges[:,sum(steps):], problem.borders[:,sum(steps):])
Fields = [Field1, Field2]
#实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化)
population = ea.PsyPopulation(Encodings, Fields, NIND)
'''=================算法参数设置==================='''
myAlgorithm = ea.moea_psy_NSGA2_templet(problem, population) # 实例化一个算法模板对象
myAlgorithm.MAXGEN = 700    # 最大进化代数
myAlgorithm.drawing = 2   # 设置绘图方式(0:不绘图;1:绘制结果图;2:绘制过程动画)
"""===========================调用算法模板进行种群进化======================"""
NDSet = myAlgorithm.run()   # 执行算法模板,得到帕累托最优解集NDSet
NDSet.save()                # 把结果保存到文件中
# 输出
print('用时:%s 秒'%(myAlgorithm.passTime))
print('非支配个体数:%s 个'%(NDSet.sizes))
print('单位时间找到帕累托前沿点个数:%s 个'%(int(NDSet.sizes // myAlgorithm.passTime)))

def searchMoea(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 = MoeaProblem(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.moea_awGA_templet(problem, population)
    #myAlgorithm = gp.moea_MOEAD_DE_templet(problem, population)
    #myAlgorithm = gp.moea_RVEA_RES_templet(problem, population)
    myAlgorithm = gp.moea_NSGA2_archive_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
Esempio n. 19
0
# -*- coding: utf-8 -*-
import numpy as np
import geatpy as ea
from MyProblem import MyProblem
import matplotlib.pyplot as plt


if __name__ == '__main__':
    problem = MyProblem()
    Encoding = 'RI'       # Encoding
    NIND = 20           # Population size
    Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges, problem.borders) # Create a region descriptor
    population = ea.Population(Encoding, Field, NIND) # Instantiate population object
    """================================Algorithm parameter settings============================="""
    myAlgorithm = ea.moea_NSGA3_DE_templet(problem, population) # Instantiate an algorithm template object
    myAlgorithm.MAXGEN = 25 # Maximum number of evolutions
    myAlgorithm.mutOper.F = 0.5 # The parameter F in differential evolution
    myAlgorithm.recOper.XOVR = 0.7 # Reorganization Probability
    myAlgorithm.drawing = 0
    """===========================Call algorithm template for population evolution======================="""
    NDSet = myAlgorithm.run ()  #
    NDSet.save ()  #
    #drawing
    print ( 'Seconds: %s' % (myAlgorithm.passTime) )
    print ( 'Non-dominated individuals:%s ' % (NDSet.sizes) )
    print ( 'Decision variable value:%s ' % (NDSet.Phen) )
    print ( 'Decision target value:%s ' % (NDSet.ObjV) )

    ax1 = plt.Circle ( (NDSet.Phen[-1,2], 2.5), NDSet.Phen[-1,0], fill=False )
    ax2 = plt.Rectangle ( (1, 2), 18, 1, fill=False )
    ax3 = plt.Circle ( (NDSet.Phen[-1,3], 13.5), NDSet.Phen[-1,1], fill=False )
Esempio n. 20
0
def awGA_templet(AIM_M,
                 AIM_F,
                 PUN_M,
                 PUN_F,
                 ranges,
                 borders,
                 precisions,
                 maxormin,
                 MAXGEN,
                 MAXSIZE,
                 NIND,
                 SUBPOP,
                 GGAP,
                 selectStyle,
                 recombinStyle,
                 recopt,
                 pm,
                 drawing=1):
    """
awGA_templet.py - 基于awGA的多目标优化编程模板

语法:
    该函数除了参数drawing外,不设置可缺省参数。
    当某个参数需要缺省时,在调用函数时传入None即可。
    比如当没有罚函数时,则在调用编程模板时将第3、4个参数设置为None即可,如:
    awGA_templet(AIM_M, 'aimfuc', None, None, ..., maxormin)
    
输入参数:
    AIM_M - 目标函数的地址,传入该函数前通常由AIM_M = __import__('目标函数名')语句得到
    
    AIM_F : str - 目标函数名
    
    PUN_M - 罚函数的地址,传入该函数前通常由PUN_M = __import__('罚函数名')语句得到
    
    PUN_F : str - 罚函数名
    
    ranges : array  - 代表自变量的范围矩阵,要求上界必须大于下界
        例如:[[1, 2, 3],
              [3, 4, 5]]
        表示有3个控制变量,其范围分别是1-3, 2-4, 3-5
                         
    borders : list -(可选参数)代表是否包含变量范围的边界,为1代表控制变量的范围包含该边界
        当为None时,默认设置为全是1的矩阵
        例如:[[1, 0, 1],
              [0, 1, 1]]
        表示上面的三个控制变量的范围分别是:[1, 3)、(2, 4]、[3, 5]
    
    precisions : list -(可选参数)代表控制变量的精度,
        如等于4,表示对应的控制变量的编码可以精确到小数点后4位。
        当precisions为None时,默认precision为1*n的0矩阵(此时表示种群是离散编码的)
        precision的元素必须不小于0
    
    maxormin int - 最小最大化标记,1表示目标函数最小化;-1表示目标函数最大化
    
    MAXGEN : int - 最大遗传代数
    
    MAXSIZE : int - 帕累托最优集最大规模
    
    NIND : int - 种群规模,即种群中包含多少个个体
    
    SUBPOP : int - 子种群数量,即对一个种群划分多少个子种群
    
    GGAP : float - 代沟,表示子代与父代染色体及性状不相同的概率
    
    selectStyle : str - 指代所采用的低级选择算子的名称,如'rws'(轮盘赌选择算子)
    
    recombinStyle: str - 指代所采用的低级重组算子的名称,如'xovsp'(单点交叉)
    
    recopt : float - 交叉概率
    
    pm : float - 重组概率
    
    drawing : int - (可选参数),0表示不绘图,1表示绘制最终结果图,2表示绘制进化过程的动画。
                    默认drawing为1
算法描述:
    本模板实现了基于适应性权重聚合法(awGA)的多目标优化搜索,
    通过维护一个全局帕累托最优集来实现帕累托前沿的搜索,故并不需要保证种群所有个体都是非支配的
    
"""

    #==========================初始化配置===========================
    # 获取目标函数和罚函数
    aimfuc = getattr(AIM_M, AIM_F)  # 获得目标函数
    FieldDR = ga.crtfld(ranges, borders, precisions)
    #=========================开始遗传算法进化=======================
    Chrom = ga.crtrp(NIND, FieldDR)  # 创建简单离散种群
    ObjV = aimfuc(Chrom)  # 计算种群目标函数值
    NDSet = np.zeros((0, Chrom.shape[1]))  # 定义帕累托最优解记录器
    NDSetObjV = np.zeros((0, ObjV.shape[1]))  # 定义帕累托最优解的目标函数值记录器
    ax = None
    start_time = time.time()  # 开始计时
    # 开始进化!!
    for gen in range(MAXGEN):
        if NDSet.shape[0] > MAXSIZE:
            break
        [CombinObjV, weight] = ga.awGA(maxormin * ObjV)  # 计算适应性权重以及多目标的加权单目标
        FitnV = ga.ranking(maxormin * CombinObjV)  # 根据加权单目标计算适应度
        # 更新帕累托最优集以及种群非支配个体的适应度
        [FitnV, NDSet, NDSetObjV,
         repnum] = ga.upNDSet(Chrom, maxormin * ObjV, FitnV, NDSet,
                              maxormin * NDSetObjV)
        # 进行遗传操作!!
        SelCh = ga.selecting(selectStyle, Chrom, FitnV, GGAP, SUBPOP)  # 选择
        SelCh = ga.recombin(recombinStyle, SelCh, recopt, SUBPOP)  #交叉
        SelCh = ga.mutbga(SelCh, FieldDR, pm)  # 变异
        if repnum > Chrom.shape[0] * 0.1:  # 进行一次高斯变异
            SelCh = ga.mutgau(SelCh, FieldDR, pm)  # 高斯变异
        ObjVSel = aimfuc(SelCh)  # 求育种个体的目标函数值
        [CombinObjV, weight] = ga.awGA(maxormin * ObjVSel)
        FitnVSel = ga.ranking(maxormin * CombinObjV)
        [Chrom, ObjV] = ga.reins(Chrom, SelCh, SUBPOP, 1, 0.9, FitnV, FitnVSel,
                                 ObjV, ObjVSel)  #重插入
        if drawing == 2:
            ax = ga.frontplot(NDSetObjV, False, ax, gen + 1)  # 绘制动态图
    end_time = time.time()  # 结束计时
    #=========================绘图及输出结果=========================
    if drawing != 0:
        ga.frontplot(NDSetObjV, True)
    times = end_time - start_time
    print('用时:', times, '秒')
    print('帕累托前沿点个数:', NDSet.shape[0], '个')
    print('单位时间找到帕累托前沿点个数:', int(NDSet.shape[0] // times), '个')
    # 返回帕累托最优集以及执行时间
    return [ObjV, NDSet, NDSetObjV, end_time - start_time]
Esempio n. 21
0
    def optimize(self):
        """===============================实例化问题对象==========================="""
        problem = MyProblem(self.M, self.maxormins, self.Dim, self.varTypes,
                            self.lb, self.ub, self.lbin, self.ubin,
                            self.f_list)  # 生成问题对象
        """=================================种群设置==============================="""
        Encoding = 'BG'  # 编码方式,使用二进制/格雷编码
        Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges,
                          problem.borders)  # 创建区域描述器
        population = ea.Population(
            Encoding, Field, self.NIND)  # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化)
        """===============================算法参数设置============================="""
        if self.M == 1:
            myAlgorithm = ea.soea_SGA_templet(
                problem, population)  # 实例化一个算法模板对象, single objective
        else:
            myAlgorithm = ea.moea_NSGA3_templet(
                problem, population)  # 实例化一个算法模板对象, multi objective

        myAlgorithm.MAXGEN = self.MAXGEN  # 最大进化代数
        myAlgorithm.recOper.XOVR = 0.7  # 交叉概率
        myAlgorithm.mutOper.Pm = 1  # 变异概率(换算成标准变异概率为0.025)
        myAlgorithm.drawing = 0  # 设置绘图方式(0:不绘图;1:绘制结果图;2:绘制目标空间过程动画;3:绘制决策空间过程动画)
        """==========================调用算法模板进行种群进化======================="""
        if self.M == 1:  # single objective
            [population, obj_trace, var_trace] = myAlgorithm.run()  # 执行算法模板
            self.obj_trace = obj_trace  # save obj_trace for plot
            population.save()  # 把最后一代种群的信息保存到文件中
            # 输出结果
            best_gen = np.argmin(problem.maxormins *
                                 obj_trace[:, 1])  # 记录最优种群个体是在哪一代
            best_ObjV = np.array([obj_trace[best_gen, 1]])
            best_var = np.array([var_trace[best_gen]])

            if os.path.exists('best_ObjV.csv') == False:
                np.savetxt('best_ObjV.csv', best_ObjV, delimiter=',')
                np.savetxt('best_var.csv', best_var, delimiter=',')
            else:
                best_ObjV_old = self.read_csv_to_np('best_ObjV.csv')
                best_var_old = self.read_csv_to_np('best_var.csv')
                best_ObjV = np.vstack((best_ObjV_old, best_ObjV))
                best_var = np.vstack((best_var_old, best_var))
                np.savetxt('best_ObjV.csv', best_ObjV, delimiter=',')
                np.savetxt('best_var.csv', best_var, delimiter=',')

            # 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' % (myAlgorithm.evalsNum))
            # print('时间已过 %s 秒' % (myAlgorithm.passTime))
            return population
        else:  # multi objective
            NDSet = myAlgorithm.run()  # 执行算法模板,得到帕累托最优解集NDSet
            NDSet.save()  # 把结果保存到文件中
            # 输出
            # print('用时:%s 秒' % (myAlgorithm.passTime))
            # print('非支配个体数:%s 个' % (NDSet.sizes))
            # print('单位时间找到帕累托前沿点个数:%s 个' % (int(NDSet.sizes // myAlgorithm.passTime)))
            return NDSet
Esempio n. 22
0
def main(aim, n, Dim, phase):
    start = time.perf_counter()
    """===============================实例化问题对象==========================="""
    PoolType = 'Thread'
    problem = MyProblem_multiprocess(aim, n, Dim, phase, PoolType)  # 生成问题对象
    """=================================种群设置==============================="""
    Encoding = 'RI'  # 编码方式
    NIND = 1000  # 种群规模
    Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges,
                      problem.borders)  # 创建区域描述器
    population = ea.Population(Encoding, Field,
                               NIND)  # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化)
    """===============================算法参数设置============================="""
    myAlgorithm = ea.soea_SEGA_templet(problem, population)  # 实例化一个算法模板对象
    # myAlgorithm.mutOper.Pm = 1 # 修改变异算子的变异概率(原模板中breeder GA变异算子的Pm定义为1 / Dim)
    # myAlgorithm.recOper.XOVR = 0.9 # 修改交叉算子的交叉概率
    # myAlgorithm.recOper.XOVR = 0.7 # 重组概率
    # myAlgorithm.mutOper.F = 0.5 # 差分进化中的参数F
    # if n == 0:
    #     myAlgorithm.MAXGEN = 20 # 最大进化代数
    #     myAlgorithm.maxTrappedCount = 10 # 进化停滞计数器最大上限值,如果连续maxTrappedCount代被判定进化陷入停滞,则终止进化
    # else:
    #     myAlgorithm.MAXGEN = 20
    myAlgorithm.MAXGEN = 40
    myAlgorithm.trappedValue = 1e-6  # “进化停滞”判断阈值
    myAlgorithm.maxTrappedCount = 10  # 进化停滞计数器最大上限值,如果连续maxTrappedCount代被判定进化陷入停滞,则终止进化
    myAlgorithm.drawing = 2  # 设置绘图方式(0:不绘图;1:绘制结果图;2:绘制目标空间过程动画;3:绘制决策空间过程动画)
    """==========================调用算法模板进行种群进化======================="""
    [population, obj_trace, var_trace] = myAlgorithm.run()  # 执行算法模板
    population.save()  # 把最后一代种群的信息保存到文件中
    # problem.pool.close() # 及时关闭问题类中的池,否则在采用多进程运算后内存得不到释放
    # 输出结果
    best_gen = np.argmin(problem.maxormins * obj_trace[:, 1])  # 记录最优种群个体是在哪一代
    best_ObjV = obj_trace[best_gen, 1]
    print('最优的目标函数值为:%.8smm' % (best_ObjV))
    if phase == None:
        phase = [0] + [i * 10 for i in var_trace[best_gen, :]]  # 第一次算出的所有相位值
        res = aim.bias_n_li_fast(phase)
        find_index = np.where(max(res[n + 1:, 0]) == res[
            n + 1:,
            0])[0][0] + 1  # 第一次最大偏心值的索引位置(此处res内的n+1和最后面的+1表示:不考虑第一级,整体向后偏移一位)
    else:
        phase = phase + [i * 10
                         for i in var_trace[best_gen, :]]  # 所有相位值(后续几级相位值有更新)
        res = aim.bias_n_li_fast(phase)
        find_index = np.where(max(res[n:, 0]) == res[n:,
                                                     0])[0][0]  # 每次的最大偏心值的索引位置
    print('所在位置及相位偏斜角为:第%s级零件末端; %.8s°' %
          (find_index + 1 + n, res[find_index + n, 1]))
    if n == 0:
        for i in range(len(phase)):
            print('第%s级相位、偏心值及相位偏斜角为:%s°; %.8smm; %.8s°' %
                  (i + 1, phase[i], res[i, 0], res[i, 1]))
    else:
        for i in range(var_trace.shape[1]):
            print('第%s级相位、偏心值及相位偏斜角为:%s°; %.8smm; %.8s°' %
                  (i + (n + 1), phase[i + n], res[i + n, 0], res[i + n, 1]))
    print('有效进化代数:%s' % (obj_trace.shape[0]))
    print('最优的一代是第 %s 代' % (best_gen + 1))
    print('评价次数:%s' % (myAlgorithm.evalsNum))
    # print('时间已过 %s 分 %.8s 秒' % (int(myAlgorithm.passTime // 60), myAlgorithm.passTime % 60))
    n = n + int(
        (find_index + 1))  # 计算累计固定好的级数(此处find_index类型为int64,改为int类型防止后面报错!)
    end = time.perf_counter()
    print(f'时间已过 {int((end - start) // 60)} 分 {(end - start) % 60:.8f} 秒')
    return population, myAlgorithm, obj_trace, var_trace, best_gen, best_ObjV, phase, res, n
Esempio n. 23
0
# -*- coding: utf-8 -*-
import numpy as np
import geatpy as ea # import geatpy
from MyProblem import MyProblem # 导入自定义问题接口

"""==================================实例化问题对象================================"""
problem = MyProblem() # 生成问题对象
"""==================================种群设置================================"""
Encoding = 'R'             # 编码方式
conordis = 0               # 表示染色体解码后得到的变量是连续的
NIND = 100                 # 种群规模
Field = ea.crtfld(Encoding, conordis, problem.ranges, problem.borders) # 创建区域描述器
population = ea.Population(Encoding, conordis, Field, NIND) # 实例化种群对象(此时种群还没被真正初始化)
"""==================================算法参数设置================================"""
myAlgorithm = ea.soea_SEGA_templet(problem, population) # 实例化一个算法模板对象
myAlgorithm.MAXGEN = 500 # 最大遗传代数
"""=======================调用算法模板进行种群进化=============================="""
[population, obj_trace, var_trace] = myAlgorithm.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'%(myAlgorithm.evalsNum))
print('时间已过 %s 秒'%(myAlgorithm.passTime))
Esempio n. 24
0
"""

import numpy as np
import geatpy as ga  # import geatpy

AIM_M = __import__('aimfuc')  # get the address of objective function
AIM_F = 'DTLZ1'  # You can set DTL1,2,3 or 4
"""==================================variables setting================================"""
ranges = np.vstack([np.zeros((1, 7)), np.ones(
    (1, 7))])  # define the ranges of variables in DTLZ1
borders = np.vstack([np.ones((1, 7)), np.ones(
    (1, 7))])  # define the borders of variables in DTLZ1
precisions = [
    4
] * 7  # set any precision that is bigger than 0, or 'crtfld' would create a Field for integer-code.
FieldDR = ga.crtfld(ranges, borders, precisions)  # create the FieldDR
"""=======================use sga2_templet to find the Pareto front==================="""
[ObjV, NDSet, NDSetObjV,
 times] = ga.moea_nsga2_templet(AIM_M,
                                AIM_F,
                                None,
                                None,
                                FieldDR,
                                problem='R',
                                maxormin=1,
                                MAXGEN=500,
                                MAXSIZE=2000,
                                NIND=50,
                                SUBPOP=1,
                                GGAP=1,
                                selectStyle='tour',
Esempio n. 25
0
import geatpy as ga

# 获取函数接口地址
AIM_M = __import__('aimfuc')
# 变量设置
x1 = [-3, 12.1]  # 自变量1的范围
x2 = [4.1, 5.8]  # 自变量2的范围
b1 = [1, 1]  # 自变量1是否包含下界
b2 = [1, 1]  # 自变量2是否包含上界
codes = [0, 0]  # 自变量的编码方式,0表示采用标准二进制编码
precisions = [4, 4]  # 自变量的精度(精度不宜设置太高,否则影响搜索性能和效果)
scales = [0, 0]  # 是否采用对数刻度
ranges = np.vstack([x1, x2]).T  # 生成自变量的范围矩阵
borders = np.vstack([b1, b2]).T  # 生成自变量的边界矩阵
# 生成区域描述器
FieldD = ga.crtfld(ranges, borders, precisions, codes)

# 调用编程模板
[pop_trace, var_trace, times] = ga.sga_new_code_templet(AIM_M,
                                                        'aimfuc',
                                                        None,
                                                        None,
                                                        FieldD,
                                                        problem='R',
                                                        maxormin=-1,
                                                        MAXGEN=1000,
                                                        NIND=100,
                                                        SUBPOP=1,
                                                        GGAP=0.8,
                                                        selectStyle='sus',
                                                        recombinStyle='xovdp',
Esempio n. 26
0
# -*- coding: utf-8 -*-
import geatpy as ea  # import geatpy
from MyProblem import MyProblem  # 导入自定义问题接口
"""==================================实例化问题对象================================"""
problem = MyProblem()  # 生成问题对象,实例化MyProblem的对象
"""==================================种群设置================================"""
Encoding = 'I'  # 编码方式  ,这种编码方式是整数
conordis = 1  # 表示染色体解码后得到的变量是离散的   表示解码后的变量是离散的//1表示的是连续
NIND = 50  # 种群规模,总变量个数是50,解空间个数是50
Field = ea.crtfld(Encoding, conordis, problem.ranges,
                  problem.borders)  # 创建区域描述器   根据编码方式/解码后的变量类型/决策边界/
## 包含边界来确定区域描述
population = ea.Population(Encoding, conordis, Field,
                           NIND)  # 实例化种群对象(此时种群还没被真正初始化)
#用编码方式/解码后的变量类型/解空间/种群规模来初始化population
"""==================================算法参数设置================================"""
myAlgorithm = ea.moea_NSGA2_templet(
    problem, population)  # 实例化一个算法模板对象,传入problem/population,
# 也就是生成问题对象和种群对象
myAlgorithm.MAXGEN = 200  # 最大遗传代数
"""=======================调用算法模板进行种群进化=============================="""
NDSet = myAlgorithm.run()  # 执行算法模板,得到帕累托最优解集NDSet,直接输出解集
print(population.FitnV)
# 输出
#print('用时:%s 秒'%(myAlgorithm.passTime))
#print('非支配个体数:%s 个'%(NDSet.sizes))
#print(NDSet.Phen.shape)
#print(NDSet.Phen)
#patore
#print('单位时间找到帕累托前沿点个数:%s 个'%(int(NDSet.sizes // myAlgorithm.passTime)))
Esempio n. 27
0
# -*- coding: utf-8 -*-
import geatpy as ea  # import geatpy
from MyProblem import MyProblem  # 导入自定义问题接口

if __name__ == '__main__':
    """===============================实例化问题对象============================"""
    problem = MyProblem()  # 生成问题对象
    """==================================种群设置==============================="""
    Encoding = 'RI'  # 编码方式
    NIND = 50  # 种群规模
    Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges,
                      problem.borders)  # 创建区域描述器
    population = ea.Population(Encoding, Field,
                               NIND)  # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化)
    """=================================算法参数设置============================"""
    myAlgorithm = ea.moea_NSGA2_templet(problem, population)  # 实例化一个算法模板对象
    myAlgorithm.MAXGEN = 200  # 最大进化代数
    myAlgorithm.logTras = 0  # 设置每多少代记录日志,若设置成0则表示不记录日志
    myAlgorithm.verbose = False  # 设置是否打印输出日志信息
    myAlgorithm.drawing = 1  # 设置绘图方式(0:不绘图;1:绘制结果图;2:绘制目标空间过程动画;3:绘制决策空间过程动画)
    """==========================调用算法模板进行种群进化=========================
    调用run执行算法模板,得到帕累托最优解集NDSet以及最后一代种群。NDSet是一个种群类Population的对象。
    NDSet.ObjV为最优解个体的目标函数值;NDSet.Phen为对应的决策变量值。
    详见Population.py中关于种群类的定义。
    """
    [NDSet, population] = myAlgorithm.run()  # 执行算法模板,得到非支配种群以及最后一代种群
    NDSet.save()  # 把非支配种群的信息保存到文件中
    """==================================输出结果=============================="""
    print('用时:%s 秒' % myAlgorithm.passTime)
    print('非支配个体数:%d 个' %
          NDSet.sizes) if NDSet.sizes != 0 else print('没有找到可行解!')
Esempio n. 28
0
    def __init__(self, Encodings, Fields=None, NIND=None, Chroms=None, ObjV=None, FitnV=None, CV=None, Phen=None, EncoIdxs=None):

        """
        描述: 种群类的构造函数,用于实例化种群对象,例如:
             import geatpy as ea
             population = ea.PsyPopulation(Encodings, Fields, NIND),
             NIND为所需要的个体数,
             此时得到的population还没被真正初始化,仅仅是完成种群对象的实例化。
             该构造函数必须传入Chroms,才算是完成种群真正的初始化。
             因此一开始可以只传入Encodings, Fields以及NIND来完成种群对象的实例化,
             其他属性可以后面再通过计算进行赋值。
             特殊用法1:
                可以利用ea.PsyPopulation(Encodings, Fields, 0)来创建一个“空种群”,即不含任何个体的种群对象。
             特殊用法2:
                直接用ea.PsyPopulation(Encodings)构建一个只包含编码信息的空种群。
             
        """

        if NIND is None:
            NIND = 0
        if isinstance(NIND, int) and NIND >= 0:
            self.sizes = NIND
        else:
            raise RuntimeError('error in PysPopulation: Size error. (种群规模设置有误,必须为非负整数。)')
        self.EncoIdxs = EncoIdxs
        self.Encodings = Encodings
        if Encodings is None:
            self.Fields = None
            self.Chroms = None
            self.Linds = 0
            self.ChromNum = 2  # 随意设置一个大于1的值
        else:
            self.ChromNum = len(Encodings)
            if self.ChromNum == 1:
                raise RuntimeError(
                    'error in PysPopulation: ChromNum must be bigger than 1. ('
                    '使用PysPopulation类时,染色体数目必须大于1,否则应该使用Population类。)')
            if Fields is None:
                self.Fields = None
            else:
                if type(Fields) == tuple:
                    self.Fields = []
                    if len(EncoIdxs) != len(Encodings):
                        raise RuntimeError('error in PysPopulation: Dimension disagree. (EncoIdxs的元素个数与Encodings的不一致。)')
                    for i, Encoding in enumerate(Encodings):
                        params = []
                        for item in Fields:
                            if item.ndim == 1:
                                params.append(item[EncoIdxs[i]])
                            elif item.ndim == 2:
                                params.append(item[:, EncoIdxs[i]])
                            else:
                                raise RuntimeError('error in PysPopulation: Parameter error. (参数错误,详见文件头的注释。)')
                        params = tuple(params)
                        self.Fields.append(ea.crtfld(Encoding, *params))
                else:
                    self.Fields = Fields.copy()
            self.Chroms = [None] * self.ChromNum  # 初始化Chroms为元素是None的列表
            self.Linds = []
            if Chroms is None:
                self.Linds = [0] * self.ChromNum
            else:
                for i in range(self.ChromNum):
                    if Chroms[i] is not None:
                        self.Linds.append(Chroms[i].shape[1])
                        self.Chroms[i] = Chroms[i].copy() if Chroms[i] is not None else None
                    else:
                        self.Linds.append(0)
        self.ObjV = ObjV.copy() if ObjV is not None else None
        self.FitnV = FitnV.copy() if FitnV is not None else None
        self.CV = CV.copy() if CV is not None else None
        self.Phen = Phen.copy() if Phen is not None else None
Esempio n. 29
0
# 注意:不建议把目标函数放在执行脚本内,建议放在另一个文件中
def aimfuc(x, LegV):  # 定义目标函数
    f = np.array([np.sum(x**2, 1)]).T  # 注意计算结果要符合Geatpy对种群目标函数矩阵的数据结构
    return [f, LegV]  # 注意返回的参数要符合Geatpy数据结构


if __name__ == "__main__":
    AIM_M = __import__('sga_test_Sphere')  # 获取函数所在文件的地址
    # 变量设置
    ranges = np.array([[-5.12, -5.12, -5.12], [5.12, 5.12,
                                               5.12]])  # 生成自变量的范围矩阵
    borders = np.array([[1, 1, 1], [1, 1, 1]])  # 生成自变量的边界矩阵(1表示变量的区间是闭区间)
    precisions = [
        1, 1, 1
    ]  # 根据crtfld的函数特性,这里需要设置精度为任意正值,否则在生成区域描述器时会默认为整数编码,并对变量范围作出一定调整
    FieldDR = ga.crtfld(ranges, borders, precisions)  # 生成区域描述器
    # 调用编程模板
    [pop_trace, var_trace,
     times] = ga.sga_new_real_templet(AIM_M,
                                      'aimfuc',
                                      None,
                                      None,
                                      FieldDR,
                                      problem='R',
                                      maxormin=1,
                                      MAXGEN=100,
                                      NIND=50,
                                      SUBPOP=1,
                                      GGAP=0.9,
                                      selectStyle='sus',
                                      recombinStyle='xovsp',
Esempio n. 30
0
def geaty_func(func,
               dim,
               lb,
               ub,
               NIND=400,
               MAXGEN=25,
               fig_dir="",
               njobs=0,
               method="SEGA",
               n_populations=5,
               opt_res=None):
    """
    将整个遗传算法过程进行整合,编写成一整个函数,便于之后使用。当前此函数,只能处理参数是连续
    型的最优化问题。
    args:
        func: 用于最小化的函数。
        dim: 需要优化的params的个数。
        lb,ub:array或list,是params的上下限,这里默认都是闭区间。
        NIND: 种群规模
        MAXGEN: 最大进化代数
        fig_dir: 保存图片的地址,注意,需要在最后加/
        njobs: 0,1使用单核、否则使用多核,其中-1表示使用所有的核
        method: 使用的进化算法模板:
            SEGA:增强精英保留的遗传算法模板
            multiSEGA:增强精英保留的多种群协同遗传算法
            psySEGA:增强精英保留的多染色体遗传算法
            rand1lDE: 差分进化DE/rand/1/L算法
        n_populations: 如果是multiSEGA,此表示的是种群数量

    """
    """ 实例化问题对象 """
    problem = MyProblem(func, dim, lb, ub, njobs=njobs)  # 生成问题对象
    """ 种群设置 """
    # 创建区域描述器
    # (不同的方法使用不同的编码方式)
    # if "DE" in method:
    Encoding = "RI"
    # else:
    # Encoding = "BG"
    # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化)
    if method == "multiSEGA":
        one_ind = NIND // n_populations
        res_ind = NIND % n_populations
        NINDS = [one_ind] * n_populations
        NINDS[-1] = NINDS[-1] + res_ind
        population = []
        for nind in NINDS:
            Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges,
                              problem.borders)
            population.append(ea.Population(Encoding, Field, nind))
        # --------------------------------------------
        # opt_res = load("./RESULTS2/test0418_5/opt_res.pkl")
        if opt_res is not None:
            prophetChrom = np.expand_dims(opt_res["BestParam"], axis=0)
            prophetChrom = np.tile(opt_res["BestParam"], (2, 1))
            prophetPops = []
            for i in range(len(population)):
                prophetPop = ea.Population(Encoding, Field, 2, prophetChrom)
                prophetPop.Phen = prophetPop.decoding()
                problem.aimFunc(prophetPop)
                prophetPops.append(prophetPop)
        else:
            prophetPops = None
        # --------------------------------------------
    else:
        # --------------------------------------------
        # prophetPops = None
        # --------------------------------------------
        Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges,
                          problem.borders)
        if method == "psySEGA":
            raise NotImplementedError
            population = ea.PsyPopulation([Encoding], [Field], NIND)
        else:
            population = ea.Population(Encoding, Field, NIND)
    """ 算法参数设置 """
    if method == "SEGA":
        algorithm = ea.soea_SEGA_templet
    elif method == "multiSEGA":
        algorithm = ea.soea_multi_SEGA_templet
    elif method == "psySEGA":
        algorithm = ea.soea_psy_SEGA_templet
    elif method == "rand1lDE":
        algorithm = ea.soea_DE_rand_1_L_templet
    else:
        raise NotImplementedError
    # 实例化一个算法模板对象
    myAlgorithm = algorithm(problem, population)
    # 最大进化代数
    myAlgorithm.MAXGEN = MAXGEN
    # "进化停滞"判断阈值
    # myAlgorithm.trappedValue = 1e-6
    # 进化停滞计数器最大上限值,如果连续maxTrappedCount代被判定进化陷入停滞,则终止进化
    # myAlgorithm.maxTrappedCount = 100
    # 控制是否绘制图片
    myAlgorithm.drawing = 1
    # 控制绘图的路径(自己改的源码)
    myAlgorithm.drawing_file = fig_dir
    """ 调用算法模板进行种群进化 """
    [population, obj_trace, var_trace] = myAlgorithm.run(prophetPops)  # 执行算法模板
    # 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])
    print('有效进化代数:%s' % (obj_trace.shape[0]))
    print('最优的一代是第 %s 代' % (best_gen + 1))
    print('评价次数:%s' % (myAlgorithm.evalsNum))
    print('时间已过 %s 秒' % (myAlgorithm.passTime))

    return {
        "BestObjv": best_ObjV,
        "BestParam": var_trace[best_gen, :],
        "AvailableEvoluion": obj_trace.shape[0],
        "EvaluationCount": myAlgorithm.evalsNum,
        "PassTime": myAlgorithm.passTime,
        "VarTrace": var_trace,
        "ObjTrace": obj_trace,
        "population": population,
    }