Exemple #1
0
    def tstep(self):
        '''
        takes a time step in the simulation
        '''
        start = time.time()  # start clock
        #======================================================================================#
        #check destinations if active
        #define motion vectors if destinations active and not everybody is at destination
        active_dests = len(self.population[
            self.population[:, 11] != 0])  # look op this only once

        if active_dests > 0 and len(
                self.population[self.population[:, 12] == 0]) > 0:
            self.population = set_destination(self.population,
                                              self.destinations)
            self.population = check_at_destination(
                self.population,
                self.destinations,
                wander_factor=self.Config.wander_factor_dest)

        if active_dests > 0 and len(
                self.population[self.population[:, 12] == 1]) > 0:
            #keep them at destination
            self.population = keep_at_destination(self.population,
                                                  self.Config.isolation_bounds)

        #======================================================================================#
        #gravity wells
        if self.Config.gravity_strength > 0:
            [self.population, self.last_step_change] = update_gravity_forces(
                self.population, self.time, self.last_step_change,
                self.Config.wander_step_size, self.Config.gravity_strength,
                self.Config.wander_step_duration)

        #======================================================================================#
        #activate social distancing above a certain infection threshold
        if not self.above_act_thresh and self.Config.social_distance_threshold_on > 0:
            # If not previously above infection threshold activate when threshold reached
            if self.Config.thresh_type == 'hospitalized':
                self.above_act_thresh = sum(
                    self.population[:, 11] ==
                    1) >= self.Config.social_distance_threshold_on
            elif self.Config.thresh_type == 'infected':
                self.above_act_thresh = sum(
                    self.population[:, 6] ==
                    1) >= self.Config.social_distance_threshold_on
        elif self.Config.social_distance_threshold_on == 0:
            self.above_act_thresh = True

        #deactivate social distancing after infection drops below threshold after using social distancing
        if self.above_act_thresh and not self.above_deact_thresh and self.Config.social_distance_threshold_off > 0:
            # If previously went above infection threshold deactivate when threshold reached
            self.above_deact_thresh = sum(self.population[:,6][self.population[:,11] == 0] == 1) <= \
                                       self.Config.social_distance_threshold_off

        # activate social distancing at the onset of infection
        if not self.Config.SD_act_onset:
            act_social_distancing = self.above_act_thresh and not self.above_deact_thresh and sum(
                self.population[:, 6] == 1) > 0
        # activate social distancing from start of simulation
        elif self.Config.SD_act_onset:
            act_social_distancing = self.above_act_thresh and not self.above_deact_thresh

        #activate social distancing only for compliant individuals
        if self.Config.social_distance_factor > 0 and act_social_distancing:
            self.population[(self.population[:,17] == 0) &\
                            (self.population[:,11] == 0)] = update_repulsive_forces(self.population[(self.population[:,17] == 0) &\
                                                                                                    (self.population[:,11] == 0)], self.Config.social_distance_factor)
        #======================================================================================#
        #out of bounds
        #define bounds arrays, excluding those who are marked as having a custom destination
        if len(self.population[:, 11] == 0) > 0:
            buffer = 0.0
            _xbounds = np.array([[
                self.Config.xbounds[0] + buffer,
                self.Config.xbounds[1] - buffer
            ]] * len(self.population[self.population[:, 11] == 0]))
            _ybounds = np.array([[
                self.Config.ybounds[0] + buffer,
                self.Config.ybounds[1] - buffer
            ]] * len(self.population[self.population[:, 11] == 0]))

            self.population[self.population[:, 11] == 0] = update_wall_forces(
                self.population[self.population[:, 11] == 0], _xbounds,
                _ybounds)

        #======================================================================================#
        #update velocities
        self.population[(self.population[:,11] == 0) |\
                        (self.population[:,12] == 1)] = update_velocities(self.population[(self.population[:,11] == 0) |\
                                                                                          (self.population[:,12] == 1)],
                                                                                          self.Config.max_speed,self.Config.dt)

        #for dead ones: set velocity and social distancing to 0 for dead ones
        self.population[:, 3:5][self.population[:, 6] == 3] = 0
        self.population[:, 17][self.population[:, 6] == 3] = 1

        #update positions
        self.population = update_positions(self.population, self.Config.dt)

        #======================================================================================#
        #find new infections

        if not self.above_test_thresh and self.Config.testing_threshold_on > 0:
            # If not previously above infection threshold activate when threshold reached
            self.above_test_thresh = sum(
                self.population[:, 6] == 1) >= self.Config.testing_threshold_on
            # self.above_test_thresh = sum(self.population[:,6] == 1) >= self.Config.social_distance_threshold_on
        elif self.Config.testing_threshold_on == 0:
            self.above_test_thresh = True

        act_testing = self.above_test_thresh and sum(
            self.population[:, 6] == 1) > 0

        self.population, self.destinations = infect(
            self.population,
            self.Config,
            self.frame,
            send_to_location=self.Config.self_isolate,
            location_bounds=self.Config.isolation_bounds,
            destinations=self.destinations,
            location_no=1,
            location_odds=self.Config.self_isolate_proportion,
            test_flag=act_testing)

        #recover and die
        self.population = recover_or_die(self.population, self.frame,
                                         self.Config)

        #======================================================================================#
        #send cured back to population if self isolation active
        #perhaps put in recover or die class
        #send cured back to population
        self.population[:, 11][self.population[:, 6] == 2] = 0

        #======================================================================================#
        #update population statistics
        self.pop_tracker.update_counts(self.population, self.frame)

        #======================================================================================#
        #visualise
        if self.Config.visualise and (
                self.frame % self.Config.visualise_every_n_frame) == 0:
            draw_tstep(self.Config, self.population, self.pop_tracker,
                       self.frame, self.fig, self.spec, self.ax1, self.ax2,
                       self.tight_bbox)

        #report stuff to console
        if (self.Config.verbose) and ((self.frame % self.Config.report_freq)
                                      == 0):
            end = time.time()
            time_elapsed = end - start  # elapsed time

            sys.stdout.write('\r')
            sys.stdout.write(
                '%i: S: %i, I: %i, R: %i, in treatment: %i, F: %i, of total: %i, D: %.5f, GC: %.5f, time: %.5f'
                % (self.frame, self.pop_tracker.susceptible[-1],
                   self.pop_tracker.infectious[-1],
                   self.pop_tracker.recovered[-1],
                   len(self.population[self.population[:, 10] == 1]),
                   self.pop_tracker.fatalities[-1], self.Config.pop_size,
                   self.pop_tracker.distance_travelled[-1],
                   self.pop_tracker.mean_perentage_covered[-1], time_elapsed))

        #save popdata if required
        if self.Config.save_pop and (self.frame %
                                     self.Config.save_pop_freq) == 0:
            save_population(self.population, self.frame,
                            self.Config.save_pop_folder)
        #run callback
        self.callback()

        #======================================================================================#
        #update frame
        self.frame += 1
        self.time += self.Config.dt
Exemple #2
0
    def tstep(self):
        """
        takes a time step in the simulation
        """

        # check destinations if active
        # define motion vectors if destinations active and not everybody is at destination
        active_dests = len(
            self.population[self.population[:, 11] != 0]
        )  # look op this only once

        if active_dests > 0 and len(self.population[self.population[:, 12] == 0]) > 0:
            self.population = set_destination(self.population, self.destinations)
            self.population = check_at_destination(
                self.population,
                self.destinations,
                wander_factor=self.Config.wander_factor_dest,
                speed=self.Config.speed,
            )

        if active_dests > 0 and len(self.population[self.population[:, 12] == 1]) > 0:
            # keep them at destination
            self.population = keep_at_destination(
                self.population, self.destinations, self.Config.wander_factor
            )

        # out of bounds
        # define bounds arrays, excluding those who are marked as having a custom destination
        if len(self.population[:, 11] == 0) > 0:
            _xbounds = np.array(
                [[self.Config.xbounds[0] + 0.02, self.Config.xbounds[1] - 0.02]]
                * len(self.population[self.population[:, 11] == 0])
            )
            _ybounds = np.array(
                [[self.Config.ybounds[0] + 0.02, self.Config.ybounds[1] - 0.02]]
                * len(self.population[self.population[:, 11] == 0])
            )
            self.population[self.population[:, 11] == 0] = out_of_bounds(
                self.population[self.population[:, 11] == 0], _xbounds, _ybounds
            )

        # set randoms
        if self.Config.lockdown:
            if len(self.pop_tracker.infectious) == 0:
                mx = 0
            else:
                mx = np.max(self.pop_tracker.infectious)

            if len(self.population[self.population[:, 6] == 1]) >= len(
                self.population
            ) * self.Config.lockdown_percentage or mx >= (
                len(self.population) * self.Config.lockdown_percentage
            ):
                # reduce speed of all members of society
                self.population[:, 5] = np.clip(
                    self.population[:, 5], a_min=None, a_max=0.001
                )
                # set speeds of complying people to 0
                self.population[:, 5][self.Config.lockdown_vector == 0] = 0
            else:
                # update randoms
                self.population = update_randoms(
                    self.population, self.Config.pop_size, self.Config.speed
                )
        else:
            # update randoms
            self.population = update_randoms(
                self.population, self.Config.pop_size, self.Config.speed
            )

        # for dead ones: set speed and heading to 0
        self.population[:, 3:5][self.population[:, 6] == 3] = 0

        # update positions
        self.population = update_positions(self.population)

        # find new infections
        self.population, self.destinations = infect(
            self.population,
            self.Config,
            self.frame,
            send_to_location=self.Config.self_isolate,
            location_bounds=self.Config.isolation_bounds,
            destinations=self.destinations,
            location_no=1,
            location_odds=self.Config.self_isolate_proportion,
        )

        # recover and die
        self.population = recover_or_die(self.population, self.frame, self.Config)

        # send cured back to population if self isolation active
        # perhaps put in recover or die class
        # send cured back to population
        self.population[:, 11][self.population[:, 6] == 2] = 0

        # update population statistics
        self.pop_tracker.update_counts(self.population)

        # visualise
        if self.Config.visualise:
            draw_tstep(
                self.Config,
                self.population,
                self.pop_tracker,
                self.frame,
                self.fig,
                self.spec,
                self.ax1,
                self.ax2,
            )

        # report stuff to console
        sys.stdout.write("\r")
        sys.stdout.write(
            "%i: healthy: %i, infected: %i, immune: %i, in treatment: %i, \
dead: %i, of total: %i"
            % (
                self.frame,
                self.pop_tracker.susceptible[-1],
                self.pop_tracker.infectious[-1],
                self.pop_tracker.recovered[-1],
                len(self.population[self.population[:, 10] == 1]),
                self.pop_tracker.fatalities[-1],
                self.Config.pop_size,
            )
        )

        # save popdata if required
        if self.Config.save_pop and (self.frame % self.Config.save_pop_freq) == 0:
            save_population(self.population, self.frame, self.Config.save_pop_folder)
        # run callback
        self.callback()

        # update frame
        self.frame += 1
Exemple #3
0
def run(input_file, output_dir, pop_size, max_gen, verbose):

    if not path.exists('Worlds'):
        mkdir('Worlds')

    if output_dir == '':
        dt = time.strftime("%Y%m%d_%H%M%S")
        output_dir = 'World_' + dt
    try:
        mkdir('Worlds\\' + output_dir)
    except FileExistsError:
        print('Directory {} Exists! Potential Data Overwrite!'.format(
            output_dir))
        ans = '1'
        while (ans != 'Y' and ans != 'N'):
            ans = input('Continue[Y/N]? ')
        if ans == 'N':
            sys.exit(0)

    # Generate Initial Population
    if input_file == '':
        pop.sixth_day(pop_size)
        #pop.clones(10)
    else:
        pop.load_population(input_file)

    generation = 0

    # Wait for User to Press 'Space' (Start)
    print('Waiting for User to Start...')
    img = np.array(sct.grab(mon))
    # cv2.imshow("img", img)
    # cv2.waitKey(0)
    while participant_lost(img):
        img = np.array(sct.grab(mon))

    print('Starting Evolution')

    generaton = 0
    while generation < max_gen:

        generation += 1
        print('\n\n***Generation {}***'.format(generation))

        participant_num = 0
        for participant in pop.participants:

            best_fitness = -1000.0
            participant_num += 1
            print('G{}: {} {} ({}/{})'.format(generation,
                                              participant.first_name,
                                              participant.last_name,
                                              participant_num,
                                              len(pop.participants)))
            for i in range(num_trials):
                participant.current_move = 0
                auto.press('space')  # Restart Race
                img = np.array(sct.grab(mon))

                # Execute Moves in Order Until Participant has Lost
                start_time = time.time()
                time.sleep(
                    .5 / speedhack)  #Wait for participant to reach the ground
                while not participant_lost(img=np.array(sct.grab(mon))):
                    if (time.time() - start_time >= time_limit):
                        kill_participant()
                    else:
                        participant.nextMove()
                    img = np.array(sct.grab(mon))

                # Read Score
                img = np.array(sct.grab(mon))
                score = read_score(img)
                if score > best_fitness:
                    best_fitness = score
                print('\t\tTrial Fitness: {}'.format(score))

            participant.fitness = best_fitness
            print('\tBest Fitness: {}'.format(best_fitness))

        pop_save_name = 'Worlds\\' + output_dir + '\\' + 'Population.csv'.format(
            generation)
        stats_save_name = 'Worlds\\' + output_dir + '\\' + 'Stats.csv'.format(
            generation)

        pop.save_population(pop_save_name, generation, verbose)
        pop.save_stats(stats_save_name, generation)
        pop.display_stats()
        pop.evolve()