Ejemplo n.º 1
0
 def load_obstacle_file(self, file_name: str):
     """
     Reads in a JSON file and stores the obstacle data in the scene.
     The file must consist of one JSON object with keys 'obstacles', 'exits', and 'entrances'
     Every key must have a list of instances, each having a 'name', a 'begin' and a 'size'.
     Note that sizes are fractions of the scene size. A size of 0 is converted to 1 size unit.
     :param file_name: file name string of the JSON file
     :return: None
     """
     with open(file_name, 'r') as json_file:
         data = json.loads(json_file.read())
     margin = self.config['general'].getfloat('margin')
     cell_size = None
     if self.snap_obstacles:
         cell_size = np.array([self.config['general'].getfloat('cell_size_x'),
                               self.config['general'].getfloat('cell_size_y')])
     for obstacle_data in data["obstacles"]:
         begin = Point(self.size * obstacle_data['begin'])
         size = Size(self.size * obstacle_data['size'])
         name = obstacle_data["name"]
         self.obstacle_list.append(Obstacle(begin, size, name, margin, cell_size=cell_size))
     if len(data['exits']) == 0:
         raise AttributeError('No exits specified in %s' % file_name)
     for exit_data in data['exits']:
         begin = Point(self.size * exit_data['begin'])
         size = self.size.array * np.array(exit_data['size'])
         name = exit_data["name"]
         cap = 0
         if 'cap' in exit_data:
             cap = exit_data['cap'] * self.dt
             if cap < 1:
                 ft.warn("Exit cap of %.2f per time step is too low low; must exceed 1.0")
         for dim in range(2):
             if size[dim] == 0.:
                 size[dim] = 1.
         exit_obs = Exit(cap=cap, begin=begin, size=Size(size), name=name, margin=margin, cell_size=cell_size)
         self.exit_list.append(exit_obs)
         self.obstacle_list.append(exit_obs)
     for entrance_data in data['entrances']:
         begin = Point(self.size * entrance_data['begin'])
         size = self.size.array * np.array(entrance_data['size'])
         name = entrance_data["name"]
         spawn_rate = 2 * self.dt
         max_pedestrians = 8000
         start_time = 0
         if 'spawn_rate' in entrance_data:
             spawn_rate = entrance_data['spawn_rate'] * self.dt
         if max_pedestrians in entrance_data:
             max_pedestrians = entrance_data['max_pedestrians']
         if 'start_time' in entrance_data:
             start_time = entrance_data['start_time']
         for dim in range(2):
             if size[dim] == 0.:
                 size[dim] = 1.
         entrance_obs = Entrance(begin=begin, size=Size(size), name=name, margin=margin,spawn_rate=spawn_rate,
                                 max_pedestrians=max_pedestrians, start_time=start_time, cell_size=cell_size)
         self.entrance_list.append(entrance_obs)
         self.obstacle_list.append(entrance_obs)
     if len(data['entrances']):
         self.on_step_functions.append(self.create_new_pedestrians)
Ejemplo n.º 2
0
 def _prepare(self):
     if not self.visual_backend and not self.store_positions:
         functions.warn(
             "No results are logged. Ensure you want a headless simulation."
         )
     # The order in which the following effects are added is important.
     for population in self.populations:
         self.on_step_functions.append(population.step)
     if 'repulsion' in self.effects:
         self.on_step_functions.append(self.effects['repulsion'].step)
     if 'fire' in self.effects:
         self.on_step_functions.append(self.effects['fire'].step)
     self.on_step_functions.append(self.scene.move)
     if 'separation' in self.effects:
         self.on_step_functions.append(self.effects['separation'].step)
     self.on_step_functions.append(self.scene.correct_for_geometry)
     self.on_step_functions.append(self.scene.find_finished)
     if self.store_positions:
         self.on_step_functions.append(self.logger.step)
     if self.visual_backend:
         self.vis = VisualScene(self.scene)
         self.on_step_functions.append(self.vis.loop)
     else:
         self.vis = NoVisualScene(self.scene)
     if self.inflow:
         self.on_step_functions.append(self._add_new_pedestrian_sometimes)
     self.vis.step_callback = self.step
     self.vis.finish_callback = self.finish
     self.scene.on_pedestrian_exit_functions.append(self._check_percentage)
     if self.params.max_time > 0:
         self.scene.on_pedestrian_exit_functions.append(
             self._check_max_time)
Ejemplo n.º 3
0
 def _compute_initial_interface(self):
     """
     Compute the initial zero interface; a potential field with zeros on exits
     and infinity elsewhere. Stores inside object.
     This method also validates exits. If no exit is found, the method raises an error.
     :return: None
     """
     self.initial_interface = np.ones(self.grid_dimension) * np.inf
     valid_exits = {goal: False for goal in self.scene.exit_list}
     goals = self.scene.exit_list
     for i, j in np.ndindex(self.grid_dimension):
         cell_center = Point([(i + 0.5) * self.dx, (j + 0.5) * self.dy])
         for goal in goals:
             if cell_center in goal:
                 self.initial_interface[i, j] = 0
                 valid_exits[goal] = True
                 self.exit_cell_set.add((i, j))
         for obstacle in self.scene.obstacle_list:
             if not obstacle.accessible:
                 if cell_center in obstacle:
                     # self.initial_interface[i,j] = np.inf
                     self.obstacle_cell_set.add((i, j))
     if not any(valid_exits.values()):
         raise RuntimeError("No cell centers in exit. Redo the scene")
     if not all(valid_exits.values()):
         ft.warn("%s not properly processed" % "/"
                 .join([repr(goal) for goal in self.scene.exit_list if not valid_exits[goal]]))
Ejemplo n.º 4
0
    def __init__(self, args):
        np.seterr(all='raise')
        functions.VERBOSE = args.verbose
        self.scene = None
        self.step_functions = []
        self.on_pedestrian_exit_functions = []
        self.on_pedestrian_init_functions = []
        self.finish_functions = []
        config = configparser.ConfigParser()
        has_config = config.read(args.config_file)
        if not has_config:
            raise FileNotFoundError("Configuration file %s not found" % args.config_file)
        functions.EPS = config['general'].getfloat('epsilon')
        self.config = config

        if args.obstacle_file:
            config['general']['obstacle_file'] = args.obstacle_file

        # Initialization scene
        if args.number >= 0:
            config['general']['number_of_pedestrians'] = str(args.number)
        if args.configuration == 'uniform':
            self.scene = scene_module.Scene(config=config)
        elif args.configuration == 'top':
            self.scene = TopScene(barrier=0.8, config=config)
        elif args.configuration == 'center':
            self.scene = ImpulseScene(impulse_location=(0.5, 0.6), impulse_size=8, config=config)
        elif args.configuration == 'bottom':
            self.scene = TwoImpulseScene(impulse_locations=[(0.5, 0.4), (0.4, 0.2)], impulse_size=8, config=config)
        if not self.scene:
            raise ValueError("No scene has been initialized")

        # Initialization planner
        planner = Planner(self.scene)
        self.step_functions.append(planner.step)

        if args.store_positions:
            # filename = input('Specify storage file\n')
            import re
            filename = re.search('/([^/]+)\.json', config['general']['obstacle_file']).group(1)
            functions.log("Storing positions results in '%s%s'" % (config['general']['result_dir'], filename))
            self.step_functions.append(lambda: self.store_positions_to_file(filename))
            self.finish_functions.append(lambda: self.store_position_usage(filename))
            self.finish_functions.append(self.store_exit_logs)

        if args.results:
            results = Result(self.scene)
            self.step_functions.append(results.on_step)
            self.on_pedestrian_exit_functions.append(results.on_pedestrian_exit)
            self.on_pedestrian_init_functions.append(results.on_pedestrian_entrance)
            self.finish_functions.append(results.on_finish)
        if not args.kernel:
            self.vis = VisualScene(self.scene)
            if args.step:
                self.vis.disable_loop()
            else:
                self.step_functions.append(self.vis.loop)
        else:
            if not (args.store_positions or args.results):
                functions.warn("No results are logged. Ensure you want a headless simulation.")
            self.vis = NoVisualScene(self.scene)
        self.scene.on_pedestrian_exit_functions += self.on_pedestrian_exit_functions
        self.scene.on_pedestrian_init_functions += self.on_pedestrian_init_functions
        self.vis.step_callback = self.step
        self.vis.finish_callback = self.finish