示例#1
0
def __test__():
    # global Testobj
    sys.setrecursionlimit(30)

    file = 'pooltest5.pkl'
    filecls = 'pooltest_cls.pkl'

    cls = Testobj0

    print(cls.param)

    if os.path.isfile(file):
        objs = ut.load(file)
        cls = ut.load(filecls)
        print(cls.param)

    else:
        pool = []
        for i in range(1000):
            obj = cls(pool)
        objs = [x for x in pool]
        ut.save(file, objs)
        ut.save(filecls, cls)

    print(len(objs))
    obj = objs[500]

    # print(pool[500], len(pool))
    print(obj.id, obj.data)
    obj()
    print(cls.param)
示例#2
0
文件: test_run.py 项目: Nomurad/eclib
def main(model, out):
    n_dim = 10
    popsize = 30
    epoch = 100 * 5

    problem = Problem()

    with Environment() as env:
        indiv_pool = env.register(Individual)
        indiv_pool.cls.set_weight([1, -1])
        initializer = UniformInitializer(n_dim)
        creator = Creator(initializer, indiv_pool)

        crossover = SimulatedBinaryCrossover(rate=0.9, eta=100)

        if model == 'moead':
            ksize = 10
            options = {
                "ksize": ksize,
                "normalization": True,
                "crossover": crossover
            }
            optimizer = MOEAD(problem=problem, pool=indiv_pool, **options)
            optimizer.weight_generator(nobj=4, divisions=50)
            popsize = int(popsize)
            epoch = epoch

        elif model == 'nsga2':
            optimizer = NSGA2(problem=problem,
                              pool=indiv_pool,
                              normalization=False)
        elif model == 'para':
            optimizer = NSGA2_para(problem=problem, pool=indiv_pool)

        else:
            raise Exception('Unexpected model name')

        population = optimizer.init_population(creator, popsize=popsize)
        history = [population]
        print("obj weight:", population[0].data.weight)

        for i in range(1, epoch + 1):
            if i % 50 == 0:
                print("epoch ", i)
            population = optimizer(population)
            history.append(population)

            if i == epoch:
                file = f'popsize{popsize}_epoch{epoch}_{ut.strnow("%Y%m%d_%H%M%S")}.pkl'
                file = os.path.join(out, file)
                if not os.path.exists(out):
                    os.makedirs(out)

                print('save:', file)
                ut.save(file, (env, optimizer, history))

        return env, optimizer, history
示例#3
0
    def local_main():
        n_dim = 30
        popsize = 100
        problem = zdt1

        with Environment() as env:
            # 個体クラス
            indiv_type = Individual
            # 初期個体生成クラス
            indiv_pool = env.register(indiv_type)

            # 遺伝子生成クラス
            initializer = UniformInitializer(n_dim)

            creator = Creator(initializer, indiv_pool)

            # # 適応度クラス
            # fit_type = Fitness
            # # 初期個体生成クラス
            # evaluator = env.register(fit_type)

            ###

            # optimizer = NSGA2(problem=problem, pool=indiv_pool)
            optimizer = MOEAD(problem=problem, pool=indiv_pool, ksize=5)
            # optimizer.set_initializer(Initializer(3))
            # optimizer.setup(problem)

            ### Additional setting ###
            # optimizer.initializer = initializer
            # optimizer.n_cycle = None
            # optimizer.alternation = 'replace'
            ##########################

            # indivs = [creator() for _ in range(popsize)]
            # population = Population([ind.evaluate(problem) for ind in indivs])
            # optimizer.calc_fitness(population)
            population = optimizer.init_population(creator, popsize=popsize)
            history = [population]

            # print(population[0].data.origin)
            # return

            for i in range(100):
                population = optimizer(population)
                plot(population)
                origin = population[0].data.origin.origin or []
                # print([x.id for x in origin], '->', population[0].data.id)
                history.append(population)

                if i % 50 == 50 - 1:
                    ut.save(f'result/temp{i}.pkl', history)

            plt.show()
            return env, optimizer, history
示例#4
0
def main1(out='result', force=False, clear_directory=False):
    ''' 最適化実行(ミニマル)
    '''
    ''' ======== 最適化パラメータの定義 ======== '''
    problem = zdt1
    n_dim = 30
    popsize = 100
    epoch = 200

    with Environment() as env:
        ''' ======== 必要なオブジェクトの準備 ======== '''
        # 個体管理クラス
        indiv_pool = env.register(Individual)

        # 遺伝子生成クラス
        initializer = UniformInitializer(n_dim)

        # 初期個体生成クラス
        creator = Creator(initializer, indiv_pool)

        # 最適化オペレータ
        op0 = NSGA2(problem=problem, pool=indiv_pool)
        op1 = MOEAD(problem=problem, pool=indiv_pool, ksize=5)
        optimizer = op0

        ''' ======== 初期集団の作成 ======== '''
        population = optimizer.init_population(creator, popsize=popsize)
        history = [population]

        ''' ======== 最適化 ======== '''
        for i in range(epoch):
            print('epoch', i + 1)
            population = optimizer(population)
            history.append(population)

            if i % 50 == 50-1:
                ut.save(f'result/temp{i}.pkl', history)

            if i >= epoch // 2:
                optimizer = op1

        ''' ======== 結果保存 ======== '''
        data = env, optimizer, history
        ut.save(f'result/optimize_#{ut.snow}.pkl', data)
        return env, optimizer, history
示例#5
0
def main1(out='result', force=False, clear_directory=False):
    ''' GAテスト & プロット
    '''

    ###
    def ln(ind, origin):
        if not origin:
            return []
        return list(zip(origin[0].value, ind.value, origin[1].value))

    def dist(ind, origin):
        if not origin:
            return 0
        values = np.array([[ind.value, par.value] for par in origin])
        diff = values[:, :, 0] - values[:, :, 1]
        dists = np.sqrt(np.sum(diff**2, axis=1))
        return np.sum(dists)

    fig, ax = plt.subplots()

    def plot(pop):
        pairs = [(fit.data, fit.data.origin.origin or ()) for fit in pop]
        parents = list(chain(*(x[1] for x in pairs)))
        lines = [ln(ind, origin) for ind, origin in pairs]
        # print(lines)
        # exit()
        if lines and [x for x in lines if x]:
            dists = [dist(ind, origin) for ind, origin in pairs]
            print(sum(dists))

        ax.cla()
        cm = plt.get_cmap('jet')
        # print(cm(10))
        # exit()

        if parents:
            x_p, y_p = np.array([ind.value for ind in parents]).T
            ax.scatter(x_p, y_p, c='r')

            for i, l in enumerate(lines):
                if l:
                    plt.plot(*l, c=cm(i / (len(lines) + 1)), linewidth=0.5)

        x, y = np.array([fit.data.value for fit in pop]).T
        ax.scatter(x, y, c='b')
        plt.pause(1e-10)

    ###
    def local_main():
        n_dim = 30
        popsize = 100
        problem = zdt1

        with Environment() as env:
            # 個体クラス
            indiv_type = Individual
            # 初期個体生成クラス
            indiv_pool = env.register(indiv_type)

            # 遺伝子生成クラス
            initializer = UniformInitializer(n_dim)

            creator = Creator(initializer, indiv_pool)

            # # 適応度クラス
            # fit_type = Fitness
            # # 初期個体生成クラス
            # evaluator = env.register(fit_type)

            ###

            # optimizer = NSGA2(problem=problem, pool=indiv_pool)
            optimizer = MOEAD(problem=problem, pool=indiv_pool, ksize=5)
            # optimizer.set_initializer(Initializer(3))
            # optimizer.setup(problem)

            ### Additional setting ###
            # optimizer.initializer = initializer
            # optimizer.n_cycle = None
            # optimizer.alternation = 'replace'
            ##########################

            # indivs = [creator() for _ in range(popsize)]
            # population = Population([ind.evaluate(problem) for ind in indivs])
            # optimizer.calc_fitness(population)
            population = optimizer.init_population(creator, popsize=popsize)
            history = [population]

            # print(population[0].data.origin)
            # return

            for i in range(100):
                population = optimizer(population)
                plot(population)
                origin = population[0].data.origin.origin or []
                # print([x.id for x in origin], '->', population[0].data.id)
                history.append(population)

                if i % 50 == 50 - 1:
                    ut.save(f'result/temp{i}.pkl', history)

            plt.show()
            return env, optimizer, history

    ###

    def resume_main(env, optimizer, history):
        print('resume_main')
        for i, population in enumerate(history):
            plot(population)
            origin = population[0].data.origin.origin or []
            # print([x.id for x in origin], '->', population[0].data.id)
        plt.show()

    file = 'test_moead.pkl'
    if os.path.exists(file) and not force:
        env, optimizer, history = ut.load(file)
        resume_main(env, optimizer, history)

    else:
        env, optimizer, history = local_main()
        ut.save(file, (env, optimizer, history))
示例#6
0
def __test__():
    obj = TestClass('abc')
    ut.save('test.pkl', obj)
    obj = ut.load('test.pkl')