Esempio n. 1
0
    def __init__(self, algorithm='quadtree', quarantine_enabled=True):
        # Creando manager de entidades
        self.__entity_manager = Population(
            algorithm=algorithm, quarantine_enabled=quarantine_enabled)
        self.algorithm = algorithm

        # Inicializando graficador
        self.__done = False
        pygame.init()

        # Configurando ventana
        self.__screen = pygame.display.set_mode(
            (self.SCREEN_WIDTH, self.SCREEN_HEIGHT))
        pygame.display.set_caption("Pandemic Simulator")

        self.__clock = pygame.time.Clock()

        # Agregando graficos
        self.chart1 = Chart([600, 10], [300, 50])
        self.chart2 = Chart([600, 100], [300, 50])
        self.chart3 = Chart([600, 190], [300, 50])

        # Renderizando el texto de cuarentena
        self.__quarantine_font = pygame.font.SysFont(None, 32)
        self.__quarantine_rendered = self.__quarantine_font.render(
            'Quarantine Zone', True, (255, 0, 0))
Esempio n. 2
0
    def __init__(self):
        """

        """

        super().__init__()
        self.setSceneRect(self.ALLOWED_AREA)
        self._population = Population(self)
        self._generationCountItem = self.addSimpleText(
            'gen: ' + str(self._population.generationCount))
        self._generationCountItem.setPos(
            QPointF(-self.WIDTH / 2 + 20, -self.HEIGHT / 2 + 20))
        self._wonCountItem = self.addSimpleText('won: ' +
                                                str(self._population.wonCount))
        self._wonCountItem.setPos(
            QPointF(-self.WIDTH / 2 + 20, -self.HEIGHT / 2 + 40))
        self._exhaustedCountItem = self.addSimpleText(
            'exh: ' + str(self._population.exhaustedCount))
        self._exhaustedCountItem.setPos(
            QPointF(-self.WIDTH / 2 + 20, -self.HEIGHT / 2 + 60))
        self._deadCountItem = self.addSimpleText(
            'ded: ' + str(self._population.deadCount))
        self._deadCountItem.setPos(
            QPointF(-self.WIDTH / 2 + 20, -self.HEIGHT / 2 + 80))
        self._population.updateCounters.connect(self._updateCounters)
        self._ctrlFlag = False
Esempio n. 3
0
def discover_Equation(tokens, evolutionary_operator, basic_terms, **kwargs): 
    t1 = datetime.datetime.now()
    
    iter_number = set_argument('iter_number', kwargs, 100)
    pop_size = set_argument('pop_size', kwargs, 8)
    eq_len = set_argument('eq_len', kwargs, 6)
    max_factors = set_argument('max_factors', kwargs, 2)
    test_output = set_argument('test_output', kwargs, True)

    population = Population(evolutionary_operator, tokens, pop_size = pop_size, basic_terms = basic_terms, 
                            eq_len = eq_len, max_factors_in_terms = max_factors)

    best_fitnesses = population.Initiate_Evolution(iter_number = iter_number,
                                                   log_file = None, test_indicators = test_output)
#    filename = 'Fitness_alpha_' + str(alpha) + '.npy'
#    save_fitness(filename, best_fitnesses)
    
    print('Achieved best fitness:', best_fitnesses[-1])#, 'with alpha =', alpha)
    
    population.Calculate_True_Weights()
                    
    t2 = datetime.datetime.now()

    eq_text_form = population.text_form()
    print(eq_text_form)
 def setUp(self) -> None:
     self.pop = Population(size=10)
     logging.basicConfig(
         format='\n%(asctime)s:%(module)s:%(levelname)s:%(message)s',
         level=logging.DEBUG)
     logging.info('Testing Movements class')
     self.movement = Movement()
class PopulationTest(unittest.TestCase):
    def setUp(self) -> None:
        self.target = Individual(5, [1, 1, 1, 1, 1])
        self.individual1 = Individual(5, [0, 0, 0, 0, 0])
        self.individual2 = Individual(5, [1, 0, 1, 0, 0])
        self.individual3 = Individual(5, [0, 1, 0, 1, 1])
        self.individual4 = Individual(5, [1, 1, 1, 1, 1])
        self.population = Population(self.target, 4, [self.individual1, self.individual2, self.individual3,
                                                      self.individual4])
        self.population.calc_fitness_scores()
        self.ga_engine = GAEngine(5, 4)

    def test_cross_over(self):
        individual = self.ga_engine.cross_over(self.individual1, self.individual2, [2, 5], [0, 3])
        self.assertEqual(individual.get_value(), [0, 0, 1, 0, 1])

        individual = self.ga_engine.cross_over(self.individual2, self.individual3, [1, 4], [2, 5])
        self.assertEqual(individual.get_value(), [1, 0, 1, 1, 0])

        individual = self.ga_engine.cross_over(self.individual4, self.individual3, [1, 2], [2, 3])
        self.assertEqual(individual.get_value(), [1, 0, 1, 1, 1])

        individual = self.ga_engine.cross_over(self.individual3, self.individual1, [0, 5], [0, 5])
        self.assertEqual(individual.get_value(), [0, 0, 1, 0, 1])  # self.individual1 has changed above

    def tearDown(self) -> None:
        pass
 def setUp(self) -> None:
     self.target = Individual(5, [1, 1, 1, 1, 1])
     self.individual1 = Individual(5, [0, 0, 0, 0, 0])
     self.individual2 = Individual(5, [1, 0, 1, 0, 0])
     self.individual3 = Individual(5, [0, 1, 0, 1, 1])
     self.individual4 = Individual(5, [1, 1, 1, 1, 1])
     self.population = Population(self.target, 4, [self.individual1, self.individual2, self.individual3,
                                                   self.individual4])
     self.population.calc_fitness_scores()
     self.ga_engine = GAEngine(5, 4)
Esempio n. 7
0
def main():
    # Parse command line args
    parser = argparse.ArgumentParser()
    parser.add_argument("config")
    args = parser.parse_args()
    config = args.config
    head, tail = os.path.split(config)
    if not head:
        # If directory was not specified assume the file is in the configurations folder
        # (one above where we are now).
        head = os.path.abspath(
            os.path.join(os.path.dirname(__file__), 'configurations')
        )  # put '..', before configrations to go up one
        config = os.path.join(head, tail)

    # Load the config file
    with open(config, 'r') as f:
        CFG = yaml.safe_load(f)

    # resolve save location for output images
    save_loc = CFG['save_location']
    save_loc = os.path.abspath(
        save_loc)  # because path in config file is relative.
    if not os.path.exists(
            save_loc):  # If the output folder doesn't exist, create it now.
        os.mkdir(save_loc)

    # set up components
    image_creator = ImageCreator(save_loc=save_loc, **CFG['image_settings'])
    seed_genome = Genome(image_creator.n_in,
                         image_creator.n_out,
                         settings=CFG['genome_settings'])
    population = Population(seed_genome=seed_genome,
                            **CFG['population_settings'])

    # set up the correct evaluator
    evaluation = CFG['evaluation'].lower()
    if evaluation == 'interactive':
        evaluator = InteractiveEvaluator(image_creator)
    elif evaluation == 'target':
        target = Image.load(CFG['target_img'],
                            CFG['image_settings']['colour_channels'])
        evaluator = PixelPctEvaluator(image_creator,
                                      target_img=target,
                                      visible=CFG['visible'])
    elif evaluation == 'imagenet':
        evaluator = ImageNetEvaluator(
            image_creator, fade_factor=0.98, visible=CFG['visible']
        )  # TODO: fade_factor magic number - could load from config??
    evaluator.breed_method = population.breed_method
    evaluator.thresh = population._thresh
    evaluator.show_gens = CFG['max_generations']
    # run the population
    population.run(evaluator=evaluator, generations=CFG['max_generations'])
    def setUp(self) -> None:
        self.target = Individual(5, [1, 1, 1, 1, 1])
        self.individual1 = Individual(5, [0, 0, 0, 0, 0])
        self.individual2 = Individual(5, [1, 0, 1, 0, 0])
        self.individual3 = Individual(5, [0, 1, 0, 1, 1])
        self.individual4 = Individual(5, [1, 1, 1, 1, 1])

        self.population = Population(self.target, 4, [
            self.individual1, self.individual2, self.individual3,
            self.individual4
        ])
Esempio n. 9
0
    def run(self, max_iter, show=None):
        """
        
        Run the optimisation loop until ...
        If show="convergence", the convergence curve will be printed at each step.
        If show="best", the best individue of the current population will be shown.

        """
        population = Population()
        population.random_population(self.city2travel, param.population_size)
        self.best_fitness = [population.best_performer.fitness]
        x_convergence = [0]
        if show:
            if show == "best":
                (x, y) = population.best_performer.get_plot_data()
                x_min = self.x_min
                x_max = self.x_max
                y_min = self.y_min
                y_max = self.y_max
            elif show == "convergence":
                (x, y) = (x_convergence, self.best_fitness)
                x_min = 0
                x_max = max_iter
                y_min = 0
                y_max = self.best_fitness[0]
            else:
                raise ValueError("Wrong option for show")
            plt.show()
            plt.axis([x_min, x_max, y_min, y_max])
            axes = plt.gca()
            line, = axes.plot(x, y, 'r-')
        for i in range(1, max_iter):
            population = population.next_generation()
            if Population.final:
                break
            self.best_fitness.append(population.best_performer.fitness)
            if show:
                x_convergence.append(i)
                if show == "best":
                    (x, y) = population.best_performer.get_plot_data()
                elif show == "convergence":
                    (x, y) = (x_convergence, self.best_fitness)
                line.set_xdata(x)
                line.set_ydata(y)
                plt.draw()
                plt.pause(1e-17)
                time.sleep(0.01)
        if show:
            plt.show()
        return population
    def __init__(self, size: int, r: float, k: float, min_age: int,
                 max_age: int, mortality_rate: int, social_distance_per: int,
                 infection_range: float, recovery_time: int,
                 total_healthcare_capacity: int, mask_effectiveness: dict,
                 speed: float, social_distancing_at: int,
                 mask_wearing_at: int):
        """
        Constructor used for initializing the bound for the x axis, y axis, the k and R value for the particular population

        Parameters
        ----------
        size : int
            Size of the population
        x_bounds : list
            The list containing the lower and upper bound for the x axis of the population map
        y_bounds : list
            The list containing the lower and upper bound for the y axis of the population map
        r : float
            Disease reproduction (R0) rate for the virus
        k : float
            The k value for the virus
        """
        self.population = Population(size)
        self.virus = Virus(infection_range, recovery_time,
                           total_healthcare_capacity)
        self.recovery_time = recovery_time
        self.total_healthcare_capacity = total_healthcare_capacity
        self.movement = Movement()
        self.size = size
        self.x_bounds = [0, 1]
        self.y_bounds = [0, 1]
        self.k = k
        self.r = r
        self.destinations = np.random.uniform(low=0,
                                              high=1,
                                              size=(self.size, 2))
        self.min_age = min_age
        self.max_age = max_age
        self.mortality_rate = mortality_rate
        self.social_distance_per = social_distance_per
        self.mask_effectiveness = mask_effectiveness
        self.speed = speed
        self.persons = self.population.get_person()
        self.enforce_social_distance_at = social_distancing_at
        self.enforce_mask_wearing_at = mask_wearing_at
        self.social_distancing_enforced = False
        self.mask_wearing_enforced = False

        self.initialize_persons()
Esempio n. 11
0
def load_populacja(params: Parameters) -> Population:
    temp_employee_number = 0
    temp_company_number = 0
    population_size = 0
    solutions = []
    f = open("populacja.txt", "r")
    f_lines = f.readlines()
    for i in range(len(f_lines)):
        if f_lines[i] == 'EMPLOYEE_NUMBER' + '\n':
            temp_employee_number = int(f_lines[i + 1])
        if f_lines[i] == 'COMPANY_NUMBER' + '\n':
            temp_company_number = int(f_lines[i + 1])
        if f_lines[i] == 'POPULATION_NUMBER' + '\n':
            population_size = int(f_lines[i + 1])
        if f_lines[i] == 'POPULATION_MEMBERS' + '\n':
            for j in range(population_size):
                solutions.append(line2list(f_lines[i + 1 + j]))
    f.close()
    solution_list = []
    for j in range(population_size):
        solution_list.append(
            Solution(temp_employee_number,
                     temp_company_number,
                     premade_list=solutions[j]))
    return Population(params, solution_list)
Esempio n. 12
0
 def setUp(self) -> None:
     logging.basicConfig(
         format='\n%(asctime)s:%(module)s:%(levelname)s:%(message)s',
         level=logging.DEBUG)
     logging.info('Testing virus util class.....')
     self.config_util = ConfigUtil('config/test_config.ini')
     self.k = self.config_util.getFloatValue("virus.stats", "k_value")
     self.r = self.config_util.getFloatValue("virus.stats", "r_value")
     self.size = 10
     self.min_age = self.config_util.getIntegerValue(
         "people.stats", "min_age")
     self.max_age = self.config_util.getIntegerValue(
         "people.stats", "min_age")
     self.mortality_rate = self.config_util.getDictionary(
         "virus.stats", "mortality_rate")
     self.social_distance_per = self.config_util.getFloatValue(
         "people.stats", "social_distancing_percent")
     self.infection_range = self.config_util.getFloatValue(
         "virus.stats", "infection_range")
     self.recovery_time = self.config_util.getFloatValue(
         "virus.stats", "recovery_time")
     self.total_healthcare_capacity = self.size * (
         self.config_util.getIntegerValue(
             "area.stats", "healthcare_capacity_ratio") / 100)
     self.mask_effectiveness = self.config_util.getDictionary(
         "virus.stats", "mask_effectiveness")
     self.speed = self.config_util.getFloatValue("people.stats", "speed")
     self.x_bounds = [0, 1]
     self.y_bounds = [0, 1]
     self.population = Population(self.size)
     self.population.initialize_id(0, self.size)
     self.population.initialize_ages(self.min_age, self.max_age, self.size)
     self.population.initialize_positions(self.x_bounds, self.y_bounds,
                                          self.size)
     self.population.initialize_g_value(self.r, 1 / self.k, self.size)
     self.population.initialize_mortality_rate(self.size,
                                               self.mortality_rate)
     self.population.initialize_susceptibility()
     self.virus_util = Virus(1, self.recovery_time,
                             self.total_healthcare_capacity)
     self.population.persons[:, 7] = 1
     self.population.persons[:, 10] = 0.1
     self.population.persons[:, 11] = 0.1
     self.movement = Movement()
Esempio n. 13
0
 def test_population_init(self):
     rating1 = [1, 2, 3.5, 4, 5]  # 5 firm
     skill1 = [[2, 2, 1, 3, 2], [1, 1, 1, 2, 1], [2, 3, 2, 1,
                                                  1]]  # 3 pracowników
     emp_time1 = [1.8, 2, 0.7]
     comp_time1 = [1, 2, 2.5, 1.5, 0.8]
     params = Parameters(rating=rating1,
                         skills_matrix=skill1,
                         employee_time=emp_time1,
                         company_time=comp_time1)
     current_population = Population(parameters=params)
     self.assertEqual(len(current_population.main_list), 10)
     custom_list = [
         Solution(employee_number=len(params.skills_matrix),
                  company_number=len(params.skills_matrix[0]))
         for i in range(5)
     ]
     with self.assertRaises(MeasuresError):
         Population(parameters=params, test_list=custom_list)
Esempio n. 14
0
def main(population_size, max_weight, num_iterations):
    """
    starts logging and insert data to population to initiate the genetic algorithm
    :param population_size: int, how many items are allowed in the knapsack
    :param max_weight: int, what is the maximum weight allowed in the knapsack
    :param num_iterations: how many iterations can the genetic algorithm perform
    :return:
    """
    pytest.main()
    configure_logging()
    logger = logging.getLogger(__name__)
    logger.info('## Started ##')

    try:
        pop = Population(population_size, cnf.KNAPSACK_FILE_NAME, max_weight,
                         logger)
        pop.circle_of_life(num_iterations)

    except IOError:
        logger.error('Failed to open file', exc_info=True)

    logger.info('## Finished ##')
    return
Esempio n. 15
0
def run_simulation(n_steps, n_clusters=5):
    components = [Population(), Location(), FlockKMeans(), Infection()]
    sim = setup_simulation(components)

    # Set parameters
    sim.configuration.flock.n_clusters = n_clusters

    # pop = sim.get_population()
    # pop['color'] = pop.infected.map({0: 'black', 1: 'red'})
    # pops = [sim.get_population()]
    # for i in range(0, n_steps):
    #     sim.step()
    # pop = sim.get_population()
    # pop['color'] = pop.infected.map({0: 'black', 1: 'red'})
    # pops.append(pop)

    sim.take_steps(n_steps)
    pop = sim.get_population()
    pop['color'] = pop.infected.map({0: 'black', 1: 'red'})

    return pop
Esempio n. 16
0
    def infect(self, population: Population, frame):

        #Get the index of all the people who were infected in the previous step
        infected_idx = population.get_all_infected()
        persons = population.get_person()

        infected_counter = 0
        for idx in infected_idx:
            infected_counter += 1
            if (population.get_time_infected(int(idx[0]), frame) >=
                    self.recovery_time):
                population = self.die_or_immune(population, int(idx[0]))

            x_bounds = [
                persons[int(idx[0])][index.x_axis] -
                math.sqrt(self.infection_range),
                persons[int(idx[0])][index.x_axis] +
                math.sqrt(self.infection_range)
            ]
            y_bounds = [
                persons[int(idx[0])][index.y_axis] -
                math.sqrt(self.infection_range),
                persons[int(idx[0])][index.y_axis] +
                math.sqrt(self.infection_range)
            ]
            # print(population.get_time_infected(int(idx[0]), frame))
            tmp = self.find_nearby(persons, x_bounds, y_bounds)
            for i in tmp:
                chance = np.random.uniform(low=0.0001, high=1)
                if chance < persons[int(i)][index.susceptibility] and persons[
                        int(idx[0])][index.g_value] > 0:
                    population.persons[int(i)][9] = 1
                    population.persons[int(i)][index.infected_by] = idx[0]
                    population.set_infected_at(int(i), frame)
                    population.persons[int(idx[0])][index.g_value] -= 1
                    if (len(population.persons[
                            population.persons[:, index.hospitalized] == 1]) <
                            self.total_healthcare_capacity):
                        population.persons[int(i)][index.hospitalized] = 1

        return population
Esempio n. 17
0
class VirusUtilTest(unittest.TestCase):
    """
    Test case to test the Virus class
    """
    def setUp(self) -> None:
        logging.basicConfig(
            format='\n%(asctime)s:%(module)s:%(levelname)s:%(message)s',
            level=logging.DEBUG)
        logging.info('Testing virus util class.....')
        self.config_util = ConfigUtil('config/test_config.ini')
        self.k = self.config_util.getFloatValue("virus.stats", "k_value")
        self.r = self.config_util.getFloatValue("virus.stats", "r_value")
        self.size = 10
        self.min_age = self.config_util.getIntegerValue(
            "people.stats", "min_age")
        self.max_age = self.config_util.getIntegerValue(
            "people.stats", "min_age")
        self.mortality_rate = self.config_util.getDictionary(
            "virus.stats", "mortality_rate")
        self.social_distance_per = self.config_util.getFloatValue(
            "people.stats", "social_distancing_percent")
        self.infection_range = self.config_util.getFloatValue(
            "virus.stats", "infection_range")
        self.recovery_time = self.config_util.getFloatValue(
            "virus.stats", "recovery_time")
        self.total_healthcare_capacity = self.size * (
            self.config_util.getIntegerValue(
                "area.stats", "healthcare_capacity_ratio") / 100)
        self.mask_effectiveness = self.config_util.getDictionary(
            "virus.stats", "mask_effectiveness")
        self.speed = self.config_util.getFloatValue("people.stats", "speed")
        self.x_bounds = [0, 1]
        self.y_bounds = [0, 1]
        self.population = Population(self.size)
        self.population.initialize_id(0, self.size)
        self.population.initialize_ages(self.min_age, self.max_age, self.size)
        self.population.initialize_positions(self.x_bounds, self.y_bounds,
                                             self.size)
        self.population.initialize_g_value(self.r, 1 / self.k, self.size)
        self.population.initialize_mortality_rate(self.size,
                                                  self.mortality_rate)
        self.population.initialize_susceptibility()
        self.virus_util = Virus(1, self.recovery_time,
                                self.total_healthcare_capacity)
        self.population.persons[:, 7] = 1
        self.population.persons[:, 10] = 0.1
        self.population.persons[:, 11] = 0.1
        self.movement = Movement()

    def test_infect(self):
        """
        Test to test the infect() method; compares the number of infected people before and after calling the infect method to see if healthy people within the infection range get infected
        """
        before_infect_population = self.population.get_all_infected()
        self.population.persons = self.movement.update_persons(
            self.population.persons, self.size, self.speed, 1)
        self.infected_person = np.random.randint(0, self.size)
        self.population.persons[self.infected_person, index.g_value] = 3
        self.population.set_infected_at(1, 0)
        self.population.persons[self.infected_person,
                                index.social_distance] = 0
        self.population.persons[self.infected_person, 9] = 1
        _xbounds = np.array([[0, 1]] * self.size)
        _ybounds = np.array([[0, 1]] * self.size)

        for i in range(1, self.size):
            self.population.persons = self.movement.out_of_bounds(
                self.population.persons, _xbounds, _ybounds)

            self.population.persons = self.movement.update_persons(
                self.population.persons, self.size, self.speed, 1)

            self.population.persons = self.movement.update_pop(
                self.population.persons)

            self.population = self.virus_util.infect(self.population, i)

        self.assertTrue(
            len(before_infect_population[:, 9]) != len(
                self.population.get_all_infected()[:, 9])
            and len(self.population.get_all_infected()[:, 9]) > 1,
            "Test failed, infect did not work")

    def test_die_or_immune(self):
        """
        Test case to test the die_or_immune() method; check if the people passing the recovery time die or recover according to their mortality rate chance
        """
        dead_frame_1 = self.population.get_all_dead()
        self.assertEqual(len(dead_frame_1), 0)

        self.population.persons = self.movement.update_persons(
            self.population.persons, self.size, self.speed, 1)
        self.infected_person = np.random.randint(0, self.size)
        self.population.persons[self.infected_person, index.g_value] = 3
        self.population.set_infected_at(1, 0)
        self.population.persons[self.infected_person,
                                index.social_distance] = 0
        self.population.persons[self.infected_person, 9] = 1
        _xbounds = np.array([[0, 1]] * self.size)
        _ybounds = np.array([[0, 1]] * self.size)

        for i in range(1, self.size):
            self.population.persons = self.movement.out_of_bounds(
                self.population.persons, _xbounds, _ybounds)

            self.population.persons = self.movement.update_persons(
                self.population.persons, self.size, self.speed, 1)

            self.population.persons = self.movement.update_pop(
                self.population.persons)

            self.population = self.virus_util.infect(self.population, i)
        self.population.persons[:, index.mortality_rate] = 1.00
        self.virus_util.die_or_immune(
            self.population, int(self.population.get_all_infected()[0][0]))
        self.assertNotEqual(len(self.population.get_all_dead()), 0)
Esempio n. 18
0
from src.population import Population

pop = Population(2, 2, 150, max_hidden=10, fitness_fn=None)

for _ in range(1000):
    pop.update()
class MovementTest(unittest.TestCase):
    def setUp(self) -> None:
        self.pop = Population(size=10)
        logging.basicConfig(
            format='\n%(asctime)s:%(module)s:%(levelname)s:%(message)s',
            level=logging.DEBUG)
        logging.info('Testing Movements class')
        self.movement = Movement()

    def tearDown(self) -> None:
        self.pop = None
        self.movement = None
        pass

    def test_update_person(self) -> None:
        """

        Tests update_person() method of Movement class and movements module to check data is getting updated randomly
        """

        self.assertIsInstance(
            self.movement.update_persons(self.pop.get_person(),
                                         len(self.pop.get_person())),
            np.ndarray)
        self.pop.persons[:, idx.speed] = 0.1
        self.assertNotEqual(
            self.movement.update_persons(
                self.pop.get_person(),
                len(self.pop.get_person()),
                heading_update_chance=1)[:, idx.y_dir].any(), 0)
        self.assertNotEqual(
            self.movement.update_persons(
                self.pop.get_person(),
                len(self.pop.get_person()),
                heading_update_chance=1)[:, idx.x_dir].any(), 0)
        self.assertNotEqual(
            self.movement.update_persons(
                self.pop.get_person(),
                len(self.pop.get_person()),
                heading_update_chance=1)[:, idx.speed].any(), 0.1)

    def test_out_of_bounds(self) -> None:
        """
        
        Tests out_of_bounds() method of Movement class and movements module to check directions are updated accordingly to prevent a person from going out of bounds
        """

        self.assertIsInstance(
            self.movement.out_of_bounds(self.pop.get_person(),
                                        np.array([[0, 1]] * 10),
                                        np.array([[0, 1]] * 10)), np.ndarray)
        self.pop.persons[:, idx.speed] = 1
        self.pop.persons[:, idx.x_axis] = 1.1
        self.pop.persons[:, idx.y_axis] = 1.1
        self.pop.persons[:, idx.x_dir] = 0.5
        self.pop.persons[:, idx.y_dir] = 0.5

        self.assertLess(
            list(
                self.movement.out_of_bounds(
                    self.pop.get_person(), np.array([[0, 1]] * 10),
                    np.array([[0, 1]] * 10))[:, idx.x_dir]), [0] * 10)
        self.assertLess(
            list(
                self.movement.out_of_bounds(
                    self.pop.get_person(), np.array([[0, 1]] * 10),
                    np.array([[0, 1]] * 10))[:, idx.x_dir]), [0] * 10)

        self.pop.persons[:, idx.x_axis] = -0.1
        self.pop.persons[:, idx.y_axis] = -0.1
        self.pop.persons[:, idx.x_dir] = -0.5
        self.pop.persons[:, idx.y_dir] = -0.5
        self.assertGreater(
            list(
                self.movement.out_of_bounds(
                    self.pop.get_person(), np.array([[0, 1]] * 10),
                    np.array([[0, 1]] * 10))[:, idx.x_dir]), [0] * 10)
        self.assertGreater(
            list(
                self.movement.out_of_bounds(
                    self.pop.get_person(), np.array([[0, 1]] * 10),
                    np.array([[0, 1]] * 10))[:, idx.x_dir]), [0] * 10)

    def test_update_pop(self) -> None:
        """

        Tests the update_pop() method of Movement class and movements module to check if the position of the population members are getting updated according to the arguments
        """
        self.pop.persons[:, idx.x_dir] = 0.1
        self.pop.persons[:, idx.y_dir] = 0.1
        self.pop.persons[:, idx.speed] = 1

        expectd_x = list(self.pop.persons[:, idx.x_axis] + 0.1)
        expectd_y = list(self.pop.persons[:, idx.y_axis] + 0.1)

        self.pop.persons = self.movement.update_pop(self.pop.persons)

        self.assertIsInstance(self.pop.get_person(), np.ndarray)
        self.assertListEqual(list(self.pop.get_x_axis()), expectd_x)
        self.assertListEqual(list(self.pop.get_y_axis()), expectd_y)
class PopulationTest(unittest.TestCase):
    def setUp(self) -> None:
        self.target = Individual(5, [1, 1, 1, 1, 1])
        self.individual1 = Individual(5, [0, 0, 0, 0, 0])
        self.individual2 = Individual(5, [1, 0, 1, 0, 0])
        self.individual3 = Individual(5, [0, 1, 0, 1, 1])
        self.individual4 = Individual(5, [1, 1, 1, 1, 1])

        self.population = Population(self.target, 4, [
            self.individual1, self.individual2, self.individual3,
            self.individual4
        ])

    def test_calc_fitness_score(self):
        self.population.calc_fitness_scores()
        self.assertTrue(
            self.population.calc_fitness_score(self.target,
                                               self.individual1) == 0,
            "ind 1 score wrong")
        self.assertTrue(
            self.population.calc_fitness_score(self.target,
                                               self.individual3) == 3,
            "ind 3 score wrong")
        self.assertTrue(
            self.population.calc_fitness_score(self.target,
                                               self.individual4) == 5,
            "ind 4 score wrong")

    def test_calc_fitness_scores(self):
        self.assertEqual(self.population.fitness_scores, [0, 2, 3, 5],
                         "fitness scores list wrong")

    def test_get_n_best_individual(self):
        self.assertEqual(self.population.get_n_best_individual(1),
                         (self.individual4, 5), "best ind returned wrong")
        self.assertEqual(self.population.get_n_best_individual(3),
                         (self.individual2, 2), "3rd best ind returned wrong")

    def test_add_individual(self):
        temp_individual = Individual(5, [1, 0, 0, 0, 0])
        self.population.add_individual(temp_individual)
        self.assertEqual(self.population.individuals, [
            temp_individual, self.individual2, self.individual3,
            self.individual4
        ], "post addition scores wrong")
        self.assertEqual(self.population.fitness_scores, [1, 2, 3, 5],
                         "post addition scores wrong")

        temp_individual = Individual(5, [1, 0, 1, 1, 1])
        self.population.add_individual(temp_individual)
        self.assertEqual(self.population.individuals, [
            temp_individual, self.individual2, self.individual3,
            self.individual4
        ], "post addition scores wrong")
        self.assertEqual(self.population.fitness_scores, [4, 2, 3, 5],
                         "post addition scores wrong")

    def tearDown(self) -> None:
        pass
Esempio n. 21
0
    def __init__(self):
        self.year: int = 0
        self.inland_population: Population = Population()
        self.current_iq_distribution = self.starting_iq_distribution

        self.create_starting_population()
Esempio n. 22
0
class Grapher:
    __done: bool
    __screen: pygame.surface.Surface

    __entity_manager: Population

    # Constantes
    SCREEN_WIDTH = 900
    SCREEN_HEIGHT = 600

    def __init__(self, algorithm='quadtree', quarantine_enabled=True):
        # Creando manager de entidades
        self.__entity_manager = Population(
            algorithm=algorithm, quarantine_enabled=quarantine_enabled)
        self.algorithm = algorithm

        # Inicializando graficador
        self.__done = False
        pygame.init()

        # Configurando ventana
        self.__screen = pygame.display.set_mode(
            (self.SCREEN_WIDTH, self.SCREEN_HEIGHT))
        pygame.display.set_caption("Pandemic Simulator")

        self.__clock = pygame.time.Clock()

        # Agregando graficos
        self.chart1 = Chart([600, 10], [300, 50])
        self.chart2 = Chart([600, 100], [300, 50])
        self.chart3 = Chart([600, 190], [300, 50])

        # Renderizando el texto de cuarentena
        self.__quarantine_font = pygame.font.SysFont(None, 32)
        self.__quarantine_rendered = self.__quarantine_font.render(
            'Quarantine Zone', True, (255, 0, 0))

    def add_entities(self, population, infected, masks=0, quarantine=None):
        """
        Agrega la cantidad de entidades solicitadas
        :param quarantine: Habilita o deshabilita la cuarentena en la poblacion
        :param population: Cantidad de entidades totales sanos + infectados
        :param infected: Cantidad de entidades infectadas
        :param masks: Probabilidad de que una entidad use mascarilla
        """
        self.__entity_manager.add_entities(population, infected, masks,
                                           quarantine)

    def run(self):
        """
        Bucle del graficador. Es necesario correr esta funcion para que el
        graficador funcione.
        """
        while not self.__done:
            # Actualizando eventos
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.__done = True
                    break

            # Actualizando pantalla
            self._draw_and_update()

    #  Metodo de dibujo protegido
    def _draw_and_update(self):
        """
        Dibuja y actualiza todos los elementos dentro del graficador
        """
        self.__screen.fill((33, 33, 33))
        self.__clock.tick(60)

        # Dibujando y actualizando entidades
        self.__draw_population()

        # Dibujando y actualizando graficos
        cantidad_update = self.__entity_manager.get_update_count()
        if cantidad_update % 10 == 0:
            self.chart1.add(
                Data(cantidad_update, self.__entity_manager.get_infected()))
            self.chart2.add(
                Data(cantidad_update, self.__entity_manager.get_healthy()))
            self.chart3.add(
                Data(cantidad_update, self.__entity_manager.get_deads()))
        self.chart1.draw(self.__screen)
        self.chart2.draw(self.__screen)
        self.chart3.draw(self.__screen)

        # cuarentena
        pygame.draw.rect(
            self.__screen, (255, 0, 0),
            pygame.Rect(self.SCREEN_WIDTH * 0.7, self.SCREEN_HEIGHT * 0.5,
                        self.SCREEN_WIDTH * 0.26, self.SCREEN_HEIGHT * 0.4), 2)
        # Texto de cuarentena. (Este texto causa el loading del principio)

        self.__screen.blit(
            self.__quarantine_rendered,
            (self.SCREEN_WIDTH * 0.73, self.SCREEN_HEIGHT * 0.91))

        pygame.display.update()

    # Metodos de dibujo privados

    def __draw_population(self):
        """
        Dibuja la poblacion y la actualiza
        """
        for entity in self.__entity_manager.entities:
            self.__entity_manager.update_entity(entity)
            # Dibujando entidad
            self.__draw_entity(entity)
        self.__entity_manager.update()

    def __draw_entity(self, entity: Entity):
        """
        Dibuja la entidad seleccionada.

        :param entity: Entidad seleccionada
        """
        status, infecting, position, radius = entity.get_status()

        if infecting:
            pygame.draw.circle(self.__screen, STATUS_COLORS[status], position,
                               int(radius))
        pygame.draw.circle(self.__screen, STATUS_COLORS[status], position, 2)
class PopulationUtil(object):
    """
    Class representing the self.person.persons 
    """

    #_instance = Population()
    # def getInstance():
    #     return Population._instance

    def __init__(self, size: int, r: float, k: float, min_age: int,
                 max_age: int, mortality_rate: int, social_distance_per: int,
                 infection_range: float, recovery_time: int,
                 total_healthcare_capacity: int, mask_effectiveness: dict,
                 speed: float, social_distancing_at: int,
                 mask_wearing_at: int):
        """
        Constructor used for initializing the bound for the x axis, y axis, the k and R value for the particular population

        Parameters
        ----------
        size : int
            Size of the population
        x_bounds : list
            The list containing the lower and upper bound for the x axis of the population map
        y_bounds : list
            The list containing the lower and upper bound for the y axis of the population map
        r : float
            Disease reproduction (R0) rate for the virus
        k : float
            The k value for the virus
        """
        self.population = Population(size)
        self.virus = Virus(infection_range, recovery_time,
                           total_healthcare_capacity)
        self.recovery_time = recovery_time
        self.total_healthcare_capacity = total_healthcare_capacity
        self.movement = Movement()
        self.size = size
        self.x_bounds = [0, 1]
        self.y_bounds = [0, 1]
        self.k = k
        self.r = r
        self.destinations = np.random.uniform(low=0,
                                              high=1,
                                              size=(self.size, 2))
        self.min_age = min_age
        self.max_age = max_age
        self.mortality_rate = mortality_rate
        self.social_distance_per = social_distance_per
        self.mask_effectiveness = mask_effectiveness
        self.speed = speed
        self.persons = self.population.get_person()
        self.enforce_social_distance_at = social_distancing_at
        self.enforce_mask_wearing_at = mask_wearing_at
        self.social_distancing_enforced = False
        self.mask_wearing_enforced = False

        self.initialize_persons()

    def initialize_persons(self):
        """
        Method which initializes the person list in the population and further calls another method to update other 
        properties of the individual persons
        """
        self.population.initialize_id(0, self.size)
        self.population.initialize_ages(self.min_age, self.max_age, self.size)
        self.population.initialize_positions(self.x_bounds, self.y_bounds,
                                             self.size)
        self.population.initialize_g_value(self.r, 1 / self.k, self.size)
        self.population.initialize_mortality_rate(self.size,
                                                  self.mortality_rate)
        self.population.initialize_susceptibility()
        self.population.initialize_infected_by()

        self.persons[:, 7] = 1
        self.persons[:, 10] = 0.1
        self.persons[:, 11] = 0.1

        #Update the destination each person is headed to and corresponding speed randomly
        self.persons = self.movement.update_persons(self.persons, self.size,
                                                    self.speed, 1)

        self.infected_person = np.random.randint(0, self.size)
        self.persons[self.infected_person, index.g_value] = 3
        self.population.set_infected_at(self.infected_person, 0)
        self.persons[self.infected_person,
                     index.infected_by] = self.infected_person
        self.persons[self.infected_person, index.social_distance] = 0
        self.persons[self.infected_person, 9] = 1

    def move(self, frame):
        if frame == self.enforce_mask_wearing_at:
            self.population.initialize_mask_eff(self.size,
                                                self.mask_effectiveness)
            self.population.initialize_susceptibility()
            self.mask_wearing_enforced = True

        if frame == self.enforce_social_distance_at:
            self.population.initialize_social_distancing(
                self.social_distance_per)
            self.persons[self.infected_person, index.social_distance] = 0
            self.social_distancing_enforced = True

        if frame >= self.enforce_social_distance_at and frame % 300 == 0 and self.enforce_social_distance_at >= 0:
            self.population.initialize_social_distancing(
                self.social_distance_per)

        _xbounds = np.array([[0, 1]] * self.size)
        _ybounds = np.array([[0, 1]] * self.size)

        self.persons = self.movement.out_of_bounds(self.persons, _xbounds,
                                                   _ybounds)

        self.persons = self.movement.update_persons(self.persons, self.size,
                                                    self.speed)

        self.persons = self.movement.update_pop(self.persons)

        self.population = self.virus.infect(self.population, frame)
Esempio n. 24
0
class DataModel(QGraphicsScene):
    WIDTH = 800
    HEIGHT = 800
    WALL_THICKNESS = 5
    ALLOWED_AREA = QRectF(QPointF(-WIDTH / 2, -HEIGHT / 2),
                          QPointF(WIDTH / 2, HEIGHT / 2))
    START_POINT = QPointF(0, HEIGHT / 2 - 20)
    GOAL_POINT = QPointF(0, -HEIGHT / 2 + 20)
    GOAL_TOLERANCE = 50
    # walls around the allowed area
    WALLS_SURROUNDING = []
    # left
    WALLS_SURROUNDING.append(
        QRectF(
            QPointF(ALLOWED_AREA.left() - WALL_THICKNESS,
                    ALLOWED_AREA.top() - WALL_THICKNESS),
            QPointF(ALLOWED_AREA.left(),
                    ALLOWED_AREA.bottom() + WALL_THICKNESS)))
    # right
    WALLS_SURROUNDING.append(
        QRectF(
            QPointF(ALLOWED_AREA.right(),
                    ALLOWED_AREA.top() - WALL_THICKNESS),
            QPointF(ALLOWED_AREA.right() + WALL_THICKNESS,
                    ALLOWED_AREA.bottom() + WALL_THICKNESS)))
    # top
    WALLS_SURROUNDING.append(
        QRectF(
            QPointF(ALLOWED_AREA.left() - WALL_THICKNESS,
                    ALLOWED_AREA.top() - WALL_THICKNESS),
            QPointF(ALLOWED_AREA.right() + WALL_THICKNESS,
                    ALLOWED_AREA.top())))
    # bottom
    WALLS_SURROUNDING.append(
        QRectF(
            QPointF(ALLOWED_AREA.left() - WALL_THICKNESS,
                    ALLOWED_AREA.bottom()),
            QPointF(ALLOWED_AREA.right() + WALL_THICKNESS,
                    ALLOWED_AREA.bottom() + WALL_THICKNESS)))
    # custom walls
    WALLS_CUSTOM = []
    WALLS_CUSTOM.append(
        QRectF(
            QPointF(ALLOWED_AREA.left() - WALL_THICKNESS, HEIGHT / 4),
            QPointF(ALLOWED_AREA.left() + WIDTH - 100,
                    HEIGHT / 4 + WALL_THICKNESS)))
    WALLS_CUSTOM.append(
        QRectF(QPointF(ALLOWED_AREA.left() + 100, 0),
               QPointF(ALLOWED_AREA.right() + WALL_THICKNESS, WALL_THICKNESS)))
    VISIBILITY_GRAPH = VisibilityGraph(START_POINT, GOAL_POINT,
                                       WALLS_CUSTOM + WALLS_SURROUNDING,
                                       ALLOWED_AREA)

    ################################################################################

    def __init__(self):
        """

        """

        super().__init__()
        self.setSceneRect(self.ALLOWED_AREA)
        self._population = Population(self)
        self._generationCountItem = self.addSimpleText(
            'gen: ' + str(self._population.generationCount))
        self._generationCountItem.setPos(
            QPointF(-self.WIDTH / 2 + 20, -self.HEIGHT / 2 + 20))
        self._wonCountItem = self.addSimpleText('won: ' +
                                                str(self._population.wonCount))
        self._wonCountItem.setPos(
            QPointF(-self.WIDTH / 2 + 20, -self.HEIGHT / 2 + 40))
        self._exhaustedCountItem = self.addSimpleText(
            'exh: ' + str(self._population.exhaustedCount))
        self._exhaustedCountItem.setPos(
            QPointF(-self.WIDTH / 2 + 20, -self.HEIGHT / 2 + 60))
        self._deadCountItem = self.addSimpleText(
            'ded: ' + str(self._population.deadCount))
        self._deadCountItem.setPos(
            QPointF(-self.WIDTH / 2 + 20, -self.HEIGHT / 2 + 80))
        self._population.updateCounters.connect(self._updateCounters)
        self._ctrlFlag = False

################################################################################

    def _updateCounters(self):
        """

        """

        self._generationCountItem.setText(
            'gen: ' + str(self._population.generationCount))
        self._wonCountItem.setText('won: ' + str(self._population.wonCount))
        self._exhaustedCountItem.setText('exh: ' +
                                         str(self._population.exhaustedCount))
        self._deadCountItem.setText('ded: ' + str(self._population.deadCount))

################################################################################

    def mousePressEvent(self, event):
        """

        """

        self._population.start()
        super().mousePressEvent(event)

################################################################################

    def keyPressEvent(self, event):
        """

        """

        key = event.key()
        if key == Qt.Key_Control:
            self._ctrlFlag = True
            self.update()
        super().keyPressEvent(event)

################################################################################

    def keyReleaseEvent(self, event):
        """

        """

        key = event.key()
        if key == Qt.Key_Control:
            self._ctrlFlag = False
            self.update()
        super().keyReleaseEvent(event)

################################################################################

    def drawBackground(self, painter, rect):
        """

        """

        painter.setPen(Qt.gray)
        painter.setBrush(Qt.gray)
        painter.drawRect(rect)
        painter.setBrush(Qt.white)
        painter.drawRect(self.ALLOWED_AREA)
        painter.setPen(Qt.blue)
        painter.setBrush(Qt.blue)
        painter.drawEllipse(self.START_POINT, 5, 5)
        painter.setPen(Qt.green)
        painter.setBrush(Qt.green)
        painter.drawEllipse(self.GOAL_POINT, self.GOAL_TOLERANCE,
                            self.GOAL_TOLERANCE)
        painter.setPen(Qt.black)
        super().drawBackground(painter, rect)

################################################################################

    def drawForeground(self, painter, rect):
        """

        """

        painter.setPen(QPen(Qt.red, 1, join=Qt.MiterJoin))
        painter.setBrush(Qt.red)
        for rect in self.WALLS_SURROUNDING:
            painter.drawRect(rect)
        for rect in self.WALLS_CUSTOM:
            painter.drawRect(rect)
        if self._ctrlFlag:
            painter.setPen(Qt.green)
            for edge in self.VISIBILITY_GRAPH.shortestRouteEdges:
                painter.drawLine(edge)
        else:
            painter.setPen(Qt.black)
            for edge in self.VISIBILITY_GRAPH.edges:
                painter.drawLine(edge)
        super().drawForeground(painter, rect)
Esempio n. 25
0
import os

from src.parser import TIMParser
from src.population import Population

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description='University course timetabling problem.')
    parser.add_argument('-i',
                        action='store',
                        dest='input_file',
                        type=str,
                        required=True)
    parser.add_argument('-o',
                        action='store',
                        dest='output_file',
                        type=str,
                        required=True)
    r = parser.parse_args()

    tim_parser = TIMParser()
    events, rooms, features, students = tim_parser.parseInput(r.input_file)

    population = Population(events, rooms, features, students)

    best_solution = population.getBest()

    tim_parser.dumpOutput(r.output_file, best_solution)

    print 'lala'
Esempio n. 26
0
def Discover_Equtaion(tokens, token_params, basic_terms, **kwargs):
    '''
    
    
    
    '''
    t1 = datetime.datetime.now()

    assert 'evaluator' in kwargs.keys() and 'eval_params' in kwargs.keys()

    alpha = Set_argument('alpha', kwargs, 1)
    a_proc = Set_argument('a_proc', kwargs, 0.2)
    r_crossover = Set_argument('r_crossover', kwargs, 0.3)
    r_param_mutation = Set_argument('r_param_mutation', kwargs, 0.7)
    r_mutation = Set_argument('r_mutation', kwargs, 0.3)
    mut_chance = Set_argument('mut_chance', kwargs, 0.6)
    iter_number = Set_argument('iter_number', kwargs, 100)
    pop_size = Set_argument('pop_size', kwargs, 8)
    eq_len = Set_argument('eq_len', kwargs, 6)
    max_factors = Set_argument('max_factors', kwargs, 2)
    test_output = Set_argument('test_output', kwargs, False)

    population = Population(kwargs['evaluator'],
                            kwargs['eval_params'],
                            tokens,
                            token_params,
                            pop_size=pop_size,
                            basic_terms=basic_terms,
                            a_proc=a_proc,
                            r_crossover=r_crossover,
                            r_param_mutation=r_param_mutation,
                            r_mutation=r_mutation,
                            mut_chance=mut_chance,
                            alpha=alpha,
                            eq_len=eq_len,
                            max_factors_in_terms=max_factors)

    best_fitnesses = population.Initiate_Evolution(iter_number=iter_number,
                                                   estimator_type='Lasso',
                                                   log_file=None,
                                                   test_indicators=test_output)

    print('Achieved best fitness:', best_fitnesses[-1], 'with alpha =', alpha)

    population.Calculate_True_Weights(kwargs['evaluator'],
                                      kwargs['eval_params'])

    t2 = datetime.datetime.now()
    res = ((t1, t2), (population.target_term, population.zipped_list),
           best_fitnesses)
    print('Discovered equation:')

    print('- {', end='')
    for key, value in population.target_term.items():
        if value['power'] != 0 and key != '1':
            print(' ', key, ':', value, end='')
    print('} + ', end='')

    for term_idx in range(len(population.zipped_list)):
        print(population.zipped_list[term_idx][1], '* {', end='')
        for key, value in population.zipped_list[term_idx][0].items():
            if value['power'] != 0 and key != '1':
                print(' ', key, ':', value, end='')
        if term_idx != len(population.zipped_list) - 1:
            print('} + ', end='')
        else:
            print('} = 0')
Esempio n. 27
0
import os

print(os.getcwd())
from src.gdp import GDP
from src.longlat import LongLat
from src.population import Population
from src.prices import Prices
from src.sales import Sales
from src.weather import Weather

GDP.write_gdp()
LongLat.write_longlat()
Weather.write_weather()
Population.write_population()
Prices.write_prices()
Sales.write_sales()
Esempio n. 28
0
"""
tests.population
~~~~~~~~~~~~~~~~
here we will write all of the unit test for the population class
"""

import numpy as np

from src.population import Population
from tests.test_chromosome import LoggerMock
import config.conf_file as cnf

# initialize for all tests
logger = LoggerMock()
inst = Population(2, cnf.KNAPSACK_FILE_NAME, 5, logger)


def test_natural_population():
    pop = inst.natural_population(np.array([[6, 6], [2, 2], [9, 9], [7, 7]]),
                                  1)
    assert np.array_equal(pop, [np.array([2, 2])])


def test_calc_scores():
    score = inst.calc_scores([np.array([[2, 2], [2, 2]]), np.array([2, 2])])
    assert np.array_equal(score, np.array([[4, 4], [2, 2]]))


def test_rank_and_find_best():
    rank, best = inst.rank_and_find_best(np.array(
        [[4, 4], [2, 2]]), [np.array([[2, 2], [2, 2]]),