Пример #1
0
    def pickle_model(self, model):
        """
        Creates and serializes the pickleLight object based on previously
        defined properties.

        Parameters
        ----------
        model : Model
            An instance of the model on which the current simulation is based.
        """
        start = time.time()
        model_lite = Model(5)

        if self.pickle_schedule:
            model_lite.schedule.agents = model.schedule.agents.union(
                model.schedule.agents_to_schedule)

            for a in model_lite.schedule.agents:
                if a.__class__.__name__ == "CancerCell":
                    # Can't pickle functions
                    a.reactToDrug_ = None

        model_lite.schedule.helpers = [h for h in model.schedule.helpers if
                                       h.__class__.__name__ not in
                                       "ExitConditionWatcher"]

        if self.pickle_envs:
            model_lite.environments = copy.deepcopy(model.environments)
            env_start = time.time()
            for k, v in model_lite.environments.iteritems():
                v.grid = dict(v.grid)
            env_end = time.time()
            print("Cloning environments took %s seconds" % str(
                env_end - env_start))

        model_lite.output = model.output

        model_lite.properties = model.properties
        # Can't pickle functions
        model_lite.properties["agents"]["cancerCells"][
            "drugReactFunction"] = None
        model_lite.current_epoch = model.current_epoch

        if self.prefix is None:
            target = "%s/epoch_%s.pickle" % (self.out_dir, model.current_epoch)
        else:
            target = "%s/%s_epoch_%s.pickle" % (
                self.out_dir, self.prefix, model.current_epoch)
        with open(target, "wb") as output_file:
            pickle.dump(model_lite, output_file)
        end = time.time()
        print("Pickler lite took %s seconds" % str(end - start))
epochs = 50

model = Model(epochs)

xsize = ysize = 500
ObjectGrid2D("agent_env", xsize, ysize, model)
target_position = (12, 12)

model.properties = {
    "best_fitness": 0,  # setting global best to 0
    "best_position": (0, 0),
    "target_position": target_position
}

model.output = {"best_fitness_in_epochs": []}

num_agents = 20

for _ in range(num_agents):
    agent_position = (randint(0, xsize), randint(0, ysize))
    agent = PSOAgent(agent_position)

    model.schedule.agents.add(agent)
    agent.add_agent_to_grid("agent_env", agent_position, model)

model.schedule.helpers.append(FitnessTrackerHelper())

model.run()
plt.figure()
plt.scatter(range(model.current_epoch + 1),