Example #1
0
def start_tt_server():
    print('Press 1 + <Enter> to run as a OCL GA Server for remote clients.')
    print('Press 2 + <Enter> to run Taiwan Travel OCL GA L-O-C-A-L-L-Y.')

    best = None
    city_info = None
    statistics = None
    def callback_from_client(info):
        nonlocal statistics, best, city_info
        if 'best' in info:
            cities = info['best'].dna
            best = list(range(len(cities)))
            city_info = [(float(c['x']), float(c['y'])) for c in cities]
        if 'statistics' in info:
            statistics = info['statistics']
            pass

    tt_info = get_taiwan_travel_info()
    while True:
        user_input = get_input()
        if user_input == '1':
            ui = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'ui')
            start_ocl_ga_server(tt_info, 12345, { 'message' : callback_from_client }, ui)
            break
        elif user_input == '2':
            start_ocl_ga_local(tt_info)
            break
        elif user_input == 'exit':
            break

    if best and city_info:
        utils.plot_tsp_result(city_info, best)
    if statistics:
        utils.plot_ga_result(statistics)
def start_ocl_ga_local(info):
    info['saved_filename'] = info['saved_filename'] % (0, 0)
    info['generation_callback'] = show_generation_info
    prob_mutation = info['prob_mutation']
    prob_crossover = info['prob_crossover']

    ga_target = OpenCLGA(info)
    ga_target.prepare()
    try:
        print('Press run       + <Enter> to run')
        print('Press pause     + <Enter> to pause')
        print('Press restore   + <Enter> to restore')
        print('Press save      + <Enter> to save')
        print('Press stop      + <Enter> to stop')
        print('Press get_st    + <Enter> to get statistics information')
        print('Press get_best  + <Enter> to get best information')
        print('Press ctrl      + c       to exit')
        while True:
            user_input = get_input()
            if user_input == 'pause':
                ga_target.pause()
            elif user_input == 'run':
                ga_target.run(prob_mutation, prob_crossover)
            elif user_input == 'stop':
                ga_target.stop()
            elif user_input == 'get_st':
                st = ga_target.get_statistics()
                utils.plot_ga_result(st)
            elif user_input == 'get_best':
                best_chromosome, best_fitness, best_info = ga_target.get_the_best(
                )
                cities, city_info, city_infoX, city_infoY = read_all_cities(
                    'TW319_368Addresses-no-far-islands.json')
                utils.plot_tsp_result(city_info, best_chromosome)
            elif user_input == 'exit':
                break
            elif user_input == 'save':
                ga_target.save()
            elif user_input == 'restore':
                ga_target.restore()
    except KeyboardInterrupt:
        traceback.print_exc()
def start_tt_server():
    print('Press 1 + <Enter> to run as a OCL GA Server for remote clients.')
    print('Press 2 + <Enter> to run Taiwan Travel OCL GA L-O-C-A-L-L-Y.')

    best = None
    city_info = None
    statistics = None

    def callback_from_client(info):
        nonlocal statistics, best, city_info
        if 'best' in info:
            cities, city_info, city_infoX, city_infoY = read_all_cities(
                'TW319_368Addresses-no-far-islands.json')
            best = info['best']
        if 'statistics' in info:
            statistics = info['statistics']
            pass

    tt_info = get_taiwan_travel_info()
    while True:
        user_input = get_input()
        if user_input == '1':
            ui = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'ui')
            start_ocl_ga_server(tt_info, 12345,
                                {'message': callback_from_client}, ui)
            break
        elif user_input == '2':
            start_ocl_ga_local(tt_info)
            break
        elif user_input == 'exit':
            break

    if best and city_info:
        utils.plot_tsp_result(city_info, best)
    if statistics:
        utils.plot_ga_result(statistics)
Example #4
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)
Example #5
0
        for generation in range(self.__iterations):
            self.__execute_single_generation(generation)
            print('best fitness #{}: {}'.format(generation,
                                                self.__best_fitness))

        return (self.__best_result, self.__best_fitness)


if __name__ == '__main__':
    random.seed(1)
    city_info = {
        city_id: (random.random() * 100, random.random() * 100)
        for city_id in range(30)
    }
    print('cities:')
    print(city_info)
    ant = PythonAntTSP({
        'iterations': 20,
        'ants': 100,
        'alpha': 1,
        'beta': 9,
        'evaporation': 0.9,
        'q': 10000,
        'nodes': city_info
    })

    result = ant.run()
    print('Length: {}'.format(result[1]))
    print('Shortest Path: ' + ' => '.join(str(g) for g in result[0]))
    utils.plot_tsp_result(city_info, result[0])