Esempio n. 1
0
def run(num_chromosomes, generations):
    random.seed()

    type1 = ['q12', 'q23', 'q34', 'q41']
    type2 = ['q1', 'q2', 'q3', 'q4']

    sample = SimpleChromosome([
        SimpleGene('q12', type1, 'unit-1'),
        SimpleGene('q12', type1, 'unit-2'),
        SimpleGene('q1', type2, 'unit-3'),
        SimpleGene('q1', type2, 'unit-4'),
        SimpleGene('q1', type2, 'unit-5'),
        SimpleGene('q1', type2, 'unit-6'),
        SimpleGene('q1', type2, 'unit-7')
    ])

    self_path = os.path.dirname(os.path.abspath(__file__))
    f = open(os.path.join(self_path, 'power.cl'), 'r')
    fstr = ''.join(f.readlines())
    f.close()

    import threading
    evt = threading.Event()
    evt.clear()

    def state_changed(state):
        if 'stopped' == state:
            evt.set()

    ga_cl = OpenCLGA(
        {
            'sample_chromosome': sample,
            'termination': {
                'type': 'count',
                'count': generations
            },
            'population': num_chromosomes,
            'fitness_kernel_str': fstr,
            'fitness_func': 'power_station_fitness',
            'opt_for_max': 'max',
            'debug': True,
            'generation_callback': show_generation_info
        },
        action_callbacks={'state': state_changed})

    ga_cl.prepare()

    prob_mutate = 0.05
    prob_cross = 0.8
    ga_cl.run(prob_mutate, prob_cross)
    evt.wait()

    utils.plot_ga_result(ga_cl.get_statistics())
    print('run took', ga_cl.elapsed_time, 'seconds')
    best_chromosome, best_fitness, best_info = ga_cl.get_the_best()
    print('Best Fitness: %f' % (best_fitness))
    print('1 ~ 7 units are maintained at: ' +
          ', '.join(str(g.dna) for g in best_info.genes))
Esempio n. 2
0
def run(num_chromosomes, generations):
    value_ranges = [10, 20, 50, 150, 250, 300, 250, 150, 50, 20, 10]

    sample = SimpleChromosome(
        [SimpleGene(0, list(range(v))) for v in value_ranges])

    algebra_path = os.path.dirname(os.path.abspath(__file__))
    ocl_kernels = os.path.realpath(
        os.path.join(algebra_path, '..', '..', 'kernel'))
    algebra_kernels = os.path.join(algebra_path, 'kernel')

    f = open(os.path.join(algebra_kernels, 'expansion.cl'), 'r')
    fstr = ''.join(f.readlines())
    f.close()

    import threading
    evt = threading.Event()
    evt.clear()

    def state_changed(state):
        if 'stopped' == state:
            evt.set()

    ga_cl = OpenCLGA(
        {
            'sample_chromosome': sample,
            'termination': {
                'type': 'count',
                'count': generations
            },
            'population': num_chromosomes,
            'fitness_kernel_str': fstr,
            'fitness_func': 'expansion_fitness',
            'extra_include_path': [ocl_kernels],
            'opt_for_max': 'min',
            'generation_callback': show_generation_info
        },
        action_callbacks={'state': state_changed})

    ga_cl.prepare()

    prob_mutate = 0.1
    prob_cross = 0.8
    ga_cl.run(prob_mutate, prob_cross)
    evt.wait()

    utils.plot_ga_result(ga_cl.get_statistics())
    print('run took', ga_cl.elapsed_time, 'seconds')
    best_chromosome, best_fitness, best_info = ga_cl.get_the_best()
    print('Best Fitness: %f' % (best_fitness))
    print('Expansion of (x + y)^10 is: ' +
          ' '.join(str(g) for g in best_chromosome))
Esempio n. 3
0
def get_taiwan_travel_info():
    '''
    NOTE : Config TaiwanTravel GA parameters in dictionary 'dict_info'.
    '''
    cities, city_info, city_infoX, city_infoY = read_all_cities('TW319_368Addresses-no-far-islands.json')
    city_ids = list(range(len(cities)))
    random.seed()

    tsp_path = os.path.dirname(os.path.abspath(__file__))
    tsp_kernels = os.path.join(tsp_path, 'kernel')

    sample = ShufflerChromosome([SimpleGene(v, cities) for v in city_ids])
    f = open(os.path.join(tsp_kernels, 'taiwan_fitness.cl'), 'r')
    fstr = ''.join(f.readlines())
    f.close()

    # It seems we don't need to use this helper if we enlarge the population size. Please
    # re-evaluate and remove or uncomment the following line:
    # sample.use_improving_only_mutation('improving_only_mutation_helper')
    dict_info = { 'sample_chromosome' : sample,
                  'termination' : { 'type' : 'count',
                                   'count' : 100 },
                  'population' : 10240,
                  'fitness_kernel_str' : fstr,
                  'fitness_func' : 'taiwan_fitness',
                  'fitness_args' : [{ 't' : 'float', 'v' : city_infoX, 'n' : 'x' },
                                   { 't' : 'float', 'v' : city_infoY, 'n' : 'y' }],
                  'opt_for_max' : 'min',
                  'saved_filename' : 'test%d%d.pickle',
                  'prob_mutation' : 0.1,
                  'prob_crossover' : 0.8,
                  'extinction' : { 'type' : 'best_avg',
                                  'diff' : 1,
                                  'ratio' : 0.9 },
                  'elitism_mode' : { 'every' : 2, 'interval' : 10, 'compress' : False },
                  'serializer': serializer}
    return dict_info
Esempio n. 4
0
def run(num_chromosomes, generations):
    random.seed()

    # Operations and Terminals
    terminals = [('bid', 0), ('ask', 0), ('0.5', 0), ('bidv', 0), ('askv', 0)]
    functions1 = [('^2', 1), ('neg', 1)]
    functions2 = [('+', 2), ('-', 2), ('*', 2), ('/', 2)]

    # Depth of the tree
    min_depth = 4
    max_depth = 8
    depth = random.randint(min_depth, max_depth)

    # Tree Initialization (should not require modification if the data structure is not changed)
    i = 0
    j = 0
    n = 1
    formula = []
    setList = []
    temp = []
    tempSetList = []
    numNodes = n
    for i in range(depth):
        while 1:
            tmp_choice = random.randint(0, 2)
            if tmp_choice == 0:
                k = random.randint(0, len(terminals) - 1)
                temp.append((terminals[k], terminals, terminals[k][0]))
                tempSetList.append(tmp_choice)
                j += 0
            if tmp_choice == 1:
                k = random.randint(0, len(functions1) - 1)
                temp.append((functions1[k], functions1, functions1[k][0]))
                tempSetList.append(tmp_choice)
                j += 1
            if tmp_choice == 2:
                k = random.randint(0, len(functions2) - 1)
                temp.append((functions2[k], functions2, functions2[k][0]))
                tempSetList.append(tmp_choice)
                j += 2
            if len(temp) > n:
                temp.clear()
                tempSetList.clear()
                j = 0
            if len(temp) == n:
                if (j > 0 & i + 1 == depth):
                    temp.clear()
                    tempSetList.clear()
                    j = 0
                if (j == 0 & i + 1 < depth):
                    temp.clear()
                    tempSetList.clear()
                    j = 0
                else:
                    break
        formula.extend(temp)
        setList.extend(tempSetList)
        temp = []
        tempSetList = []
        n = j
        j = 0
        numNodes = numNodes + n
        i += 1

    for i in range(0, n):
        k = random.randint(0, len(terminals) - 1)
        formula.append((terminals[k], terminals, terminals[k][0]))
        setList.append(0)
    #tree_size = numNodes;

    # GP run
    # sample chromosome - which defines the format of following generations
    # first arg - gene, second arg - mutation set
    sample = SimpleChromosome(
        [SimpleGene(node[0], node[1], node[2]) for node in formula])

    # path of the cl file
    self_path = os.path.dirname(os.path.abspath(__file__))
    f = open(os.path.join(self_path, 'theo.cl'), 'r')
    fstr = ''.join(f.readlines())
    f.close()

    import threading
    evt = threading.Event()
    evt.clear()

    def state_changed(state):
        if 'stopped' == state:
            evt.set()

    ga_cl = OpenCLGA(
        {
            'sample_chromosome':
            sample,
            'termination': {
                'type': 'count',
                'count': generations
            },
            'population':
            num_chromosomes,
            'fitness_kernel_str':
            fstr,
            'fitness_func':
            'theo_fitness',  # match this with the fitness func name in cl file
            'fitness_args': [
                {
                    't': 'float',
                    'v': theo,
                    'n': 'theo'
                },  #change here when have more inputs
                {
                    't': 'float',
                    'v': bid,
                    'n': 'bid'
                },
                {
                    't': 'float',
                    'v': ask,
                    'n': 'ask'
                },
                {
                    't': 'float',
                    'v': bidv,
                    'n': 'bidv'
                },
                {
                    't': 'float',
                    'v': askv,
                    'n': 'askv'
                },
                {
                    't': 'int',
                    'v': data_size,
                    'n': 'data_size'
                },
                {
                    't': 'int',
                    'v': numNodes,
                    'n': 'tree_size'
                },
                {
                    't': 'int',
                    'v': setList,
                    'n': 'setList'
                }
            ],
            'opt_for_max':
            'min',
            #'elitism_mode': {'top': 10,
            #                 'every': 10},
            'debug':
            False,
            'generation_callback':
            show_generation_info
        },
        action_callbacks={'state': state_changed})

    ga_cl.prepare()

    # set up the mutation/crossover probabilities
    prob_mutate = 0.6
    prob_cross = 0.3
    ga_cl.run(prob_mutate, prob_cross)
    evt.wait()

    print('run took', ga_cl.elapsed_time, 'seconds')
    best_chromosome, best_fitness, best_info = ga_cl.get_the_best()
    print(' '.join(str(g.dna) for g in best_info.genes))
    print('Fitness: %f' % (best_fitness))

    # test data output chunk, can be removed
    f = open('testdata.txt', 'a')
    value = str(best_fitness)
    time = str(ga_cl.elapsed_time)
    f.write(value + ',' + time + '\n')
    f.close()
Esempio n. 5
0
def run(num_chromosomes, generations):
    num_cities = 20
    random.seed()
    city_ids = list(range(0, num_cities))
    city_info = {
        city_id: (random.random() * 100, random.random() * 100)
        for city_id in city_ids
    }

    sample = ShufflerChromosome([SimpleGene(v, city_ids) for v in city_ids])

    tsp_path = os.path.dirname(os.path.abspath(__file__))
    tsp_kernels = os.path.join(tsp_path, 'kernel')

    f = open(os.path.join(tsp_kernels, 'simple_tsp.cl'), 'r')
    fstr = ''.join(f.readlines())
    f.close()

    pointX = [str(city_info[v][0]) for v in city_info]
    pointY = [str(city_info[v][1]) for v in city_info]

    import threading
    evt = threading.Event()
    evt.clear()

    def state_changed(state):
        if 'stopped' == state:
            evt.set()

    tsp_ga_cl = OpenCLGA(
        {
            'sample_chromosome':
            sample,
            'termination': {
                'type': 'count',
                'count': generations
            },
            'population':
            num_chromosomes,
            'fitness_kernel_str':
            fstr,
            'fitness_func':
            'simple_tsp_fitness',
            'fitness_args': [{
                't': 'float',
                'v': pointX,
                'n': 'x'
            }, {
                't': 'float',
                'v': pointY,
                'n': 'y'
            }],
            'opt_for_max':
            'min',
            'debug':
            True,
            'generation_callback':
            show_generation_info
        },
        action_callbacks={'state': state_changed})

    tsp_ga_cl.prepare()

    prob_mutate = 0.1
    prob_cross = 0.8
    tsp_ga_cl.run(prob_mutate, prob_cross)
    evt.wait()

    utils.plot_ga_result(tsp_ga_cl.get_statistics())
    print('run took', tsp_ga_cl.elapsed_time, 'seconds')
    best_chromosome, best_fitness, best_info = tsp_ga_cl.get_the_best()
    print('Best Fitness: %f' % (best_fitness))
    print('Shortest Path: ' + ' => '.join(str(g) for g in best_chromosome))
    utils.plot_tsp_result(city_info, best_chromosome)
Esempio n. 6
0
def run(num_chromosomes, generations):
    random.seed()

    # The number of points randomly generated
    num_points = 100
    random.seed()
    point_ids = list(range(0, num_points))
    point_info = {
        point_id: (random.random() * 100, random.random() * 100)
        for point_id in point_ids
    }
    pointX = [str(point_info[v][0]) for v in point_info]
    pointY = [str(point_info[v][1]) for v in point_info]

    # The number of group you want to divide.
    numOfGroups = 10
    group_id_set = list(range(0, numOfGroups))
    group_ids = [random.randint(0, numOfGroups - 1) for x in range(num_points)]

    sample = SimpleChromosome(
        [SimpleGene(groupd_id, group_id_set) for groupd_id in group_ids])

    self_path = os.path.dirname(os.path.abspath(__file__))
    f = open(os.path.join(self_path, 'grouping.cl'), 'r')
    fstr = ''.join(f.readlines())
    f.close()

    import threading
    evt = threading.Event()
    evt.clear()

    def state_changed(state):
        if 'stopped' == state:
            evt.set()

    ga_cl = OpenCLGA(
        {
            'sample_chromosome':
            sample,
            'termination': {
                'type': 'count',
                'count': generations
            },
            'population':
            num_chromosomes,
            'fitness_kernel_str':
            fstr,
            'fitness_func':
            'grouping_fitness',
            'fitness_args': [{
                't': 'int',
                'v': numOfGroups,
                'n': 'numOfGroups'
            }, {
                't': 'float',
                'v': pointX,
                'n': 'x'
            }, {
                't': 'float',
                'v': pointY,
                'n': 'y'
            }],
            'opt_for_max':
            'min',
            'debug':
            True,
            'generation_callback':
            show_generation_info
        },
        action_callbacks={'state': state_changed})

    ga_cl.prepare()

    prob_mutate = 0.1
    prob_cross = 0.8
    ga_cl.run(prob_mutate, prob_cross)
    evt.wait()

    print('run took', ga_cl.elapsed_time, 'seconds')
    best_chromosome, best_fitness, best_info = ga_cl.get_the_best()
    print(best_chromosome)
    utils.plot_grouping_result(group_id_set, best_chromosome, point_info)