コード例 #1
0
    def run_opencl_model(i: int, iterations: int, snapshot_filepath: str, params,
                         opencl_dir: str, use_gpu: bool,
                         use_healthier_pop: bool,
                         store_detailed_counts: bool = True, quiet=False) -> (np.ndarray, np.ndarray):
        """
        Run the OpenCL model.

        :param i: Simulation number (i.e. if run as part of an ensemble)
        :param iterations: Number of iterations to ru the model for
        :param snapshot_filepath: Location of the snapshot (the model must have already been initialised)
        :param params: a Params object containing the parameters used to define how the model behaves
        :param opencl_dir: Location of the OpenCL code
        :param use_gpu: Whether to use the GPU to process it or not
        :param store_detailed_counts: Whether to store the age distributions for diseases (default True, if
          false then the model runs much more quickly).
        :param quiet: Whether to print a message when the model starts
        :return: A summary python array that contains the results for each iteration and a final state

        """

        # load snapshot
        snapshot = Snapshot.load_full_snapshot(path=snapshot_filepath)
        prev_obesity = np.copy(snapshot.buffers.people_obesity)
        if use_healthier_pop:
            snapshot.switch_to_healthier_population()
        
        print("testing obesity arrays not equal")
        print(np.mean(prev_obesity))
        print(np.mean(snapshot.buffers.people_obesity))
       # assert not np.array_equal(prev_obesity, snapshot.buffers.people_obesity)
       # print("arrays not equal")

        # set params
        snapshot.update_params(params)

        # set the random seed of the model for each repetition, otherwise it is completely deterministic
        snapshot.seed_prngs(i)

        # Create a simulator and upload the snapshot data to the OpenCL device
        simulator = Simulator(snapshot, opencl_dir=opencl_dir, gpu=use_gpu)
        simulator.upload_all(snapshot.buffers)

        if not quiet:
            print(f"Running simulation {i + 1}.")
        summary, final_state = run_headless(simulator, snapshot, iterations, quiet=True,
                                            store_detailed_counts=store_detailed_counts)
        return summary, final_state
コード例 #2
0
ファイル: main.py プロジェクト: Urban-Analytics/RAMP-UA
def run_opencl_model(individuals_df, activity_locations,
                     time_activity_multiplier, iterations, data_dir, base_dir,
                     use_gui, use_gpu, use_cache, initialise,
                     calibration_params, disease_params):
    snapshot_cache_filepath = base_dir + "/microsim/opencl/snapshots/cache.npz"

    # Choose whether to load snapshot file from cache, or create a snapshot from population data
    if not use_cache or not os.path.exists(snapshot_cache_filepath):
        print("\nGenerating Snapshot for OpenCL model")
        snapshot_converter = SnapshotConvertor(individuals_df,
                                               activity_locations,
                                               time_activity_multiplier,
                                               data_dir)
        snapshot = snapshot_converter.generate_snapshot()
        snapshot.save(snapshot_cache_filepath
                      )  # store snapshot in cache so we can load later
    else:  # load cached snapshot
        snapshot = Snapshot.load_full_snapshot(path=snapshot_cache_filepath)

    # set the random seed of the model
    snapshot.seed_prngs(42)

    # set params
    if calibration_params is not None and disease_params is not None:
        snapshot.update_params(
            create_params(calibration_params, disease_params))

        if disease_params["improve_health"]:
            print("Switching to healthier population")
            snapshot.switch_to_healthier_population()
    if initialise:
        print(
            "Have finished initialising model. -init flag is set so not running it. Exitting"
        )
        return

    run_mode = "GUI" if use_gui else "headless"
    print(f"\nRunning OpenCL model in {run_mode} mode")
    run_opencl(snapshot,
               iterations,
               data_dir,
               use_gui,
               use_gpu,
               num_seed_days=disease_params["seed_days"],
               quiet=False)
コード例 #3
0
 def draw_snapshots_window(self, width, height):
     imgui.set_next_window_size(width / 6, height / 4)
     imgui.set_next_window_position(width * 5 / 6, height * 3 / 4)
     imgui.begin("Snapshots", flags=default_flags)
     clicked, self.selected_snapshot = imgui.listbox(
         "", self.selected_snapshot, self.snapshots)
     if imgui.button("Load Selected"):
         self.snapshot = Snapshot.load_full_snapshot(
             f"snapshots/{self.snapshots[self.selected_snapshot]}")
         self.simulator.upload_all(self.snapshot.buffers)
         self.simulator.time = self.snapshot.time
         self.upload_hazards(self.snapshot.buffers.place_hazards)
         self.upload_locations(self.snapshot.buffers.place_coords)
         self.upload_links(self.snapshot.buffers.people_place_ids)
         self.current_snapshot = self.selected_snapshot
     if imgui.button("Save"):
         self.simulator.download_all(self.snapshot.buffers)
         self.snapshot.time = self.simulator.time
         self.snapshot.save(
             f"snapshots/{self.snapshots[self.current_snapshot]}")
     if imgui.button("Save As..."):
         self.show_saveas = True
     imgui.end()
コード例 #4
0
ファイル: opencl_runner.py プロジェクト: mfbenitezp/RAMP-UA
    def run(self):

        # If this is the first data assimilation window, we can just run the model as normal
        if self.start_day == 0:
            assert self.current_particle_pop_df is None  # Shouldn't have any preivously-created particles
            # load snapshot
            snapshot = Snapshot.load_full_snapshot(path=self.snapshot_file)
            # set params
            snapshot.update_params(self.params)
            # Can set the random seed to make it deterministic (None means np will choose one randomly)
            snapshot.seed_prngs(seed=None)

            # Create a simulator and upload the snapshot data to the OpenCL device
            simulator = Simulator(snapshot,
                                  opencl_dir=self.opencl_dir,
                                  gpu=self.use_gpu)
            simulator.upload_all(snapshot.buffers)

            if not self.quiet:
                # print(f"Running simulation {sim_number + 1}.")
                print(f"Running simulation")

            params = Params.fromarray(
                snapshot.buffers.params
            )  # XX Why extract Params? Can't just use PARAMS?

            summary = Summary(
                snapshot,
                store_detailed_counts=self.store_detailed_counts,
                max_time=self.run_length  # Total length of the simulation
            )

            # only show progress bar in quiet mode
            timestep_iterator = range(self.run_length) if self.quiet \
                else tqdm(range(self.quiet), desc="Running simulation")

            iter_count = 0  # Count the total number of iterations
            # Run for iterations days
            for _ in timestep_iterator:
                # Update parameters based on lockdown
                params.set_lockdown_multiplier(snapshot.lockdown_multipliers,
                                               iter_count)
                simulator.upload("params", params.asarray())

                # Step the simulator
                simulator.step()
                iter_count += 1

            # Update the statuses
            simulator.download("people_statuses",
                               snapshot.buffers.people_statuses)
            summary.update(iter_count, snapshot.buffers.people_statuses)

            if not self.quiet:
                for i in range(self.run_length):
                    print(f"\nDay {i}")
                    summary.print_counts(i)

            if not self.quiet:
                print("\nFinished")

            # Download the snapshot from OpenCL to host memory
            # XX This is 'None'.
            final_state = simulator.download_all(snapshot.buffers)

            pass
        else:  # Otherwise we need to restart previous models stored in the current_particle_pop_df
            # XXXX CAN GET OLD MODEL STATES, WITH ALL DISEASE STATUSES, FROM THE DF. TWO ISSUES
            # 1. But need to work out how to draw these appropriately; can't assume they are each as good as
            # each other. THIS SHOULD BE OK, surely there's a way to go from the final particles and weights
            # to the DF of state vectors. Particle ID? Just try it out.
            # 2. Also: what to do about stochasticity. For a given (global) parameter combination, we will
            # get quite different results depending on the mode state. - I DON'T THINK THIS IS A PROBLEM.
            # ABC Commonly used with stochastic models. E.g. https://eprints.lancs.ac.uk/id/eprint/80439/1/mainR1.pdf
            #
            raise Exception("Not implemented yet")

        # Return the current state of the model in a dictionary describing what it is
        #return {"simulator": simulator}
        return {"simulator": snapshot}