예제 #1
0
    def __init__(self, city_map="random"):
        """

        Create a new class instance with a list of city to visit.
        Number of cities in the list is defined in the param package.
        Options:
        city_map="random" : cities have random coordinates
        city_map="circle" : cities are distributed around a circle.
                            The radius defined by max_x in the param package

        """
        self.city2travel = []
        if city_map == "random":
            for i in range(param.nb_of_city):
                self.city2travel.append(City(param.max_x, param.max_y))
            self.x_min = 0
            self.x_max = param.max_x
            self.y_min = 0
            self.y_max = param.max_y
        elif city_map == "circle":
            a = b = 0
            r = param.max_x
            for theta in range(0, 360, 360 // param.nb_of_city):
                x = a + r * math.cos(theta * math.pi / 180)
                y = b + r * math.sin(theta * math.pi / 180)
                new_city = City(1)
                new_city.setXY(x, y)
                self.city2travel.append(new_city)
            self.x_min = -param.max_x
            self.x_max = param.max_x
            self.y_min = -param.max_y
            self.y_max = param.max_y
        else:
            raise ValueError(
                "Wrong city map option to initialise Optimisation")
예제 #2
0
def load_data():
    import xml.etree.ElementTree as ET
    root = ET.parse('data/janos-us--D-D-M-N-S-A-N-S/janos-us.xml').getroot()
    prefix = "{http://sndlib.zib.de/network}"
    city_name = ""
    city_list = []
    index_to_name = dict()
    adjacency_dict = dict()
    index = 0
    for type_tag in root.findall(
            f"{prefix}networkStructure/{prefix}links/{prefix}link"):
        source = type_tag.find(f"{prefix}source").text
        if source != city_name:
            index_to_name[index] = source
            city_name = source
            index += 1

    city_name = "Seattle"
    index = 0
    for type_tag in root.findall(
            f"{prefix}networkStructure/{prefix}links/{prefix}link"):
        source = type_tag.find(f"{prefix}source").text
        target = type_tag.find(f"{prefix}target").text
        cost = type_tag.find(
            f"{prefix}additionalModules/{prefix}addModule/{prefix}cost").text
        if source != city_name:
            city_list.append(City(index, city_name, adjacency_dict))
            adjacency_dict = dict()
            index += 1
            city_name = source
        adjacency_dict[next(key for key, value in index_to_name.items()
                            if value == target)] = cost
    city_list.append(City(index, city_name, adjacency_dict))
    return Network(city_list), index_to_name
예제 #3
0
    def test_set_cube_colours(self):
        saved = City.cube_colours

        City.cube_colours = []
        mocked_settings = {'Colours': {'colours': 'Red,Blue,Yellow,Black'}}
        City.set_cube_colours(mocked_settings)
        self.assertIn('Yellow', City.cube_colours)
        self.assertIn('Red', City.cube_colours)

        City.cube_colours = saved
예제 #4
0
def generate_data(numb_of_cities, max_distance):
    # calculate circle params
    middle = max_distance / 2
    r = (max_distance - 2) / 2

    # generate random cities
    cities = []
    for i in range(numb_of_cities):
        alpha = random.uniform(middle, middle + r)
        x = middle + r * math.cos(alpha)
        y = middle + r * math.sin(alpha)
        cities.append(City(i, x, y))
    return cities
예제 #5
0
def initialize_cities(path):
    f = open(path, "r")
    lines = f.readlines()
    next_adjacent = False
    cities_created = {}
    adjacent_cities = {}
    current_city_id = 0
    for i, line in enumerate(lines):
        if next_adjacent:
            adjacent = line.replace("'", "").split(",")
            adjacent = [name.strip() for name in adjacent]

            if constants.DEBUG:
                print(adjacent)
            next_adjacent = False

            if city_name not in cities_created.keys():
                c = City(city_name, loc, color, city_id=current_city_id)
                current_city_id += 1
                cities_created[city_name] = c
                adjacent_cities[city_name] = adjacent
        elif "name" in line:
            city_name = line.split("'")[1].strip()
            if constants.DEBUG:
                print(city_name)

        elif "loc" in line:
            loc = line.split("'")[1].split(",")
            loc[0] = float(loc[0])
            loc[1] = float(loc[1])
            if constants.DEBUG:
                print(loc)

        elif "color" in line:
            color = line.split("'")[1]
            if constants.DEBUG:
                print(color)

        elif "adjacent" in line:
            next_adjacent = True
    for c in adjacent_cities.keys():
        adjacent = adjacent_cities[c]
        adjacent = [cities_created[name] for name in adjacent]
        cities_created[c].set_adjacent_cities(adjacent)
    return cities_created
예제 #6
0
def extract_output():
    data = [[
        "Sno", "N", "Cap", "SA", "SA-time", "ACO", "ACO-time", "ACO-SA",
        "ACO-SA-time", "Kmean-SA", "Kmean-SA-time"
    ]]
    for i in range(100):
        cities = City.generate_cities()
        n = len(cities)
        cap = 10 if n <= 60 else 20
        c_ret, t_ret, h_ret = run(cities, cap, disp=False)
        tabular_ret = [i + 1, n, cap]
        for a, b in zip(c_ret, t_ret):
            tabular_ret.append(a)
            tabular_ret.append(b)
        data.append(tabular_ret)
        print(Tabular([tabular_ret]))
    tabular = Tabular(data)
    tabular.write_json('output/out.json')
    tabular.write_xls('output/data.xls')
예제 #7
0
 def test_add_connection(self):
     another_city = City('New York', 'Yellow')
     self.city.add_connection(another_city)
     self.assertIn(another_city, self.city.connected_cities)
예제 #8
0
 def test_init(self):
     city = City('London', 'Blue')
     self.assertEqual('London', city.name)
     self.assertEqual('Blue', city.colour)
     self.assertFalse(city.has_lab)
예제 #9
0
 def setUp(self):
     self.city = City('London', 'Blue')
예제 #10
0
class CityTestCase(TestCase):
    def setUp(self):
        self.city = City('London', 'Blue')

    def test_init(self):
        city = City('London', 'Blue')
        self.assertEqual('London', city.name)
        self.assertEqual('Blue', city.colour)
        self.assertFalse(city.has_lab)

    def test_init_city_colours(self):
        self.city.cubes = {}
        cube_colours = ['Red', 'Yellow']
        self.city.init_city_colours(cube_colours)
        self.assertEqual(0, self.city.cubes['Red'])
        self.assertEqual(0, self.city.cubes['Yellow'])

    def add_cube(self, colour):
        self.city.cubes['Black'] = 2
        self.city.add_cube('Black')
        self.assertEqual(3, self.city.cubes['Black'])

    def test_remove_cube(self):
        self.city.cubes['Black'] = 2
        self.city.remove_cube('Black')
        self.assertEqual(1, self.city.cubes['Black'])

        self.city.cubes['Black'] = 0
        with self.assertRaises(GameException):
            self.city.remove_cube('Black')
        self.assertEqual(0, self.city.cubes['Black'])

    def test_remove_all_cubes(self):
        self.city.cubes['Red'] = 3
        dropped_cubes = self.city.remove_all_cubes('Red')
        self.assertEqual(3, dropped_cubes)
        self.assertEqual(0, self.city.cubes['Red'])

        with self.assertRaises(GameException):
            self.city.remove_all_cubes('Red')
        self.assertEqual(0, self.city.cubes['Red'])

    def test_build_lab(self):
        success = self.city.build_lab()
        self.assertTrue(success)
        self.assertTrue(self.city.has_lab)

        success = self.city.build_lab()
        self.assertFalse(success)
        self.assertTrue(self.city.has_lab)

    def test_add_connection(self):
        another_city = City('New York', 'Yellow')
        self.city.add_connection(another_city)
        self.assertIn(another_city, self.city.connected_cities)

    def test_get_max_cubes(self):
        self.city.cubes['Blue'] = 1
        self.city.cubes['Red'] = 2
        self.city.cubes['Yellow'] = 4
        self.assertEqual(4, self.city.get_max_cubes())

    def test_get_cubes(self):
        self.city.cubes['Blue'] = 2
        self.assertEqual(2, self.city.cubes['Blue'])
예제 #11
0
 def init_city_list(self):
     self.city_list = dict(
         (line.split(':')[0].strip(),
          City(line.split(':')[0].strip(),
               line.split(':')[1].strip())) for line in open(
                   self.code_ref_path, 'r').read().strip().split('\n'))
예제 #12
0
        round(x, 2) for x in
        [times[0], times[1], times[1] + times[2], times[3] + times[4]]
    ]
    h_ret = [sa_history, aco_history, saco_history, skmean_history]
    return c_ret, t_ret, h_ret


def extract_output():
    data = [[
        "Sno", "N", "Cap", "SA", "SA-time", "ACO", "ACO-time", "ACO-SA",
        "ACO-SA-time", "Kmean-SA", "Kmean-SA-time"
    ]]
    for i in range(100):
        cities = City.generate_cities()
        n = len(cities)
        cap = 10 if n <= 60 else 20
        c_ret, t_ret, h_ret = run(cities, cap, disp=False)
        tabular_ret = [i + 1, n, cap]
        for a, b in zip(c_ret, t_ret):
            tabular_ret.append(a)
            tabular_ret.append(b)
        data.append(tabular_ret)
        print(Tabular([tabular_ret]))
    tabular = Tabular(data)
    tabular.write_json('output/out.json')
    tabular.write_xls('output/data.xls')


if __name__ == '__main__':
    run(City.load_cities('data/data60.txt'), cap=10)
    # extract_output() # only to extract data
예제 #13
0

if __name__ == '__main__':
    news_processor = NewsProcessor()
    print(news_processor.neg_words)
    print(news_processor.pos_words)
    print(news_processor.stop_words)
    news_dicts, stop_dicts = news_processor.count_words(os.path.join('..', 'res', 'news', 'ATL'))
    print()
    [print(d) for d in news_dicts]
    [print(d) for d in stop_dicts]
    print()
    print(news_processor.combine_dicts(stop_dicts))
    neg = [news_processor.filter_neg(news_dict) for news_dict in news_dicts]
    print()
    [print(d) for d in neg]
    pos = [news_processor.filter_pos(news_dict) for news_dict in news_dicts]
    print()
    [print(d) for d in pos]
    neutral = [news_processor.filter_neutral(news_dict) for news_dict in news_dicts]
    print()
    [print(d) for d in neutral]
    print()
    # full code
    ref_code = os.path.join('..', 'res', 'airport code references.txt')
    city_ref = dict(
        (line.split(':')[0].strip(), City(line.split(':')[0].strip(), line.split(':')[1].strip())) for line in
        open(ref_code, 'r').read().strip().split('\n'))
    news_processor.process_all(city_ref)
    [print(v) for c, v in city_ref.items()]
예제 #14
0
 def setUp(self):
     self.cities = City()
     self.cities._load_from_xml(cities_xml='tests/data/city.xml')
예제 #15
0
class TestCity(TestCase):
    def setUp(self):
        self.cities = City()
        self.cities._load_from_xml(cities_xml='tests/data/city.xml')

    def test_can_fetch_cities_from_the_web(self):
        self.cities.fetch()
        self.assertGreater(len(self.cities), 0)

    def test_can_get_correct_city_with_name(self):
        athabasca_dict = {
            'id': 's0000001',
            'english_name': 'Athabasca',
            'french_name': 'Athabasca',
            'province': 'AB',
        }

        athabasca = self.cities['Athabasca']

        self.assertEqual(athabasca, athabasca_dict)

    def test_cannot_get_city_that_doesnt_exist(self):
        incorrect_city = self.cities['Atlantis']

        self.assertIsNone(incorrect_city)

    def test_can_iterate_on_all_cities(self):
        expected_cities = [
            {
                "id": "s0000001",
                "english_name": "Athabasca",
                "french_name": "Athabasca",
                "province": "AB"
            },
            {
                "id": "s0000002",
                "english_name": "Clearwater",
                "french_name": "Clearwater",
                "province": "BC"
            },
            {
                "id": "s0000003",
                "english_name": "Valemount",
                "french_name": "Valemount",
                "province": "BC"
            },
            {
                "id": "s0000004",
                "english_name": "Grand Forks",
                "french_name": "Grand Forks",
                "province": "BC"
            },
        ]

        cities_list = [city for city in self.cities]

        self.assertListEqual(expected_cities, cities_list)

    def test_can_check_if_city_is_in_cities(self):
        self.assertIn('Athabasca', self.cities)
        self.assertNotIn('Atlantis', self.cities)
예제 #16
0
def get_cities_from_lists(x, y):
    cities = []
    for i in range(len(x)):
        cities.append(City(i, x[i], y[i]))
    return cities
예제 #17
0
    for i in range(0, generations):
        pop = nextGeneration(pop, eliteSize, mutationRate)

    print("Final distance: " + str(1 / rankRoutes(pop)[0][1]))
    bestRouteIndex = rankRoutes(pop)[0][0]
    bestRoute = pop[bestRouteIndex]
    return bestRoute


def geneticAlgorithmPlot(population, popSize, eliteSize, mutationRate, generations):
    pop = initialPopulation(popSize, population)
    progress = []
    progress.append(1 / rankRoutes(pop)[0][1])

    for i in range(0, generations):
        pop = nextGeneration(pop, eliteSize, mutationRate)
        progress.append(1 / rankRoutes(pop)[0][1])

    plt.plot(progress)
    plt.ylabel('Distance')
    plt.xlabel('Generation')
    plt.show()

if __name__ == "__main__":
    cityList = []

    for i in range(0, 25):
        cityList.append(City(x=int(random.random() * 200), y=int(random.random() * 200)))

    geneticAlgorithmPlot(population=cityList, popSize=100, eliteSize=20, mutationRate=0.01, generations=500)
예제 #18
0
 # Load in the arguments.
 args = Args()
 # If help needed, print dialog and exit.
 if args.need_help():
     print(HELP)
     exit(0)
 # Load args, exiting if not all required attributes are set.
 if not args.load_args():
     print('Not all parameters specified', HELP, sep='\n')
     exit(0)
 # Create a city for each entry.
 with open('cities.json') as data:
     raw_cities = json.load(data)
 cities = []
 for city in raw_cities['cities']:
     new_city = City(city['x_coord'], city['y_coord'], city['label'])
     cities.append(new_city)
 # Generate a nucleus.
 nuc = Nucleus(cities, args.population_size, args.mutation_prob)
 # Evolve it.
 nuc.evolve(args.generations_cnt)
 nuc.calculate_tour_distance()
 # If specified, plot the best tour and learning curve.
 if args.plot:
     nuc.chromosomes[0].plot()
     # Clear plot.
     plt.cla()
     nuc.plot_learning_curve()
 # If specified, print out the latest generation.
 if args.table:
     print(nuc)