projectmesa / mesa-examples

Seminal agent-based models developed using Mesa
Other
105 stars 123 forks source link

fix: Ensure schedule.steps is always incremented before data collection #93

Closed rht closed 5 months ago

rht commented 5 months ago

This replaces #92.

EwoutH commented 5 months ago

Could you describe the problem and why this solution fixed it, for clarity?

rht commented 5 months ago

The problem is when trade is disabled, the steps never get incremented because the code exits early in this code branch. Needs a manual self.schedule.steps += 1, because there is no self.schedule.step() call. The trading Sugarscape needs custom scheduling that is beyond staged activation, and is more easily expressed by the AgentSet API.

EwoutH commented 5 months ago

Would this work? If so, I think it's more elegant:

def step(self):
    """
    Unique step function that does staged activation of sugar and spice
    and then randomly activates traders
    """
    # Step Resource agents
    for resource in self.schedule.agents_by_type[Resource]:
        resource.step()

    # Step trader agents
    trader_shuffle = self.randomize_traders()
    for agent in trader_shuffle:
        agent.prices = []
        agent.trade_partners = []
        agent.move()
        agent.eat()
        agent.maybe_die()

    if self.enable_trade:
        # If trade is enabled, shuffle and proceed with trading
        trader_shuffle = self.randomize_traders()
        for agent in trader_shuffle:
            agent.trade_with_neighbors()

    # Update step count and collect data
    self.schedule.steps += 1
    self.datacollector.collect(self)
rht commented 5 months ago

No it doesn't, because there are more lines of code beyond self.datacollector.collect(self) when trade is enabled: https://github.com/projectmesa/mesa-examples/blob/cf38477725771d4658ea6dcf393766f1feefcc88/examples/sugarscape_g1mt/sugarscape_g1mt/model.py#L188-L205.

rht commented 5 months ago

We can optimize the code clarity later. This PR's scope is to fix the test issue with a very localized patch.