Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integrate Hotelling Law Extension into Mesa Examples #120

Merged
merged 30 commits into from
Apr 20, 2024

Conversation

aumashankar
Copy link
Contributor

@aumashankar aumashankar commented Apr 9, 2024

Closes issue #119: Hotelling Law Extension using Mesa (NetLego example using mesa)

  • Include new agents, models, and visualization modules specific to the Hotelling Law simulation.
  • Update requirements.txt with necessary dependencies for running the Hotelling Law model.
  • Ensure compatibility with existing Mesa framework and examples.
  • Add documentation for setting up and running the Hotelling Law model.

Online demo: http://178.128.112.142:8521/

@EwoutH EwoutH requested review from rht and tpike3 April 9, 2024 12:01
@EwoutH
Copy link
Member

EwoutH commented Apr 9, 2024

Thanks a lot for the PR! Looks like an interesting model to have in our example library. I requested two of our maintainers to review it.

@jackiekazil jackiekazil requested review from jackiekazil and removed request for jackiekazil April 9, 2024 13:31
@aumashankar
Copy link
Contributor Author

Thanks a lot for the PR! Looks like an interesting model to have in our example library. I requested two of our maintainers to review it.

Thanks a lot @EwoutH
We've developed it as a standalone, I'm seeing integration errors related to imports with build run tried to fix as I see
Looking forward to reviewer comments / feedback

)
new_position = self.random.choice(possible_steps)
self.model.grid.move_agent(self, new_position)
elif self.model.environment_type == "line":
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could simplify the movement code by using the branch for "grid" (above), and for line environment, you simply initialize the grid with a width of 1.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rht Please help me understand and elaborate this
You could simplify the movement code by using the branch for "grid" (above)

you simply initialize the grid with a width of 1.
It's only visualization, just wanted to show the single in center, added that way, adding width 1 it's displaying towards left with remaining grid visible, i'm not sure how it works

Need your help in explaining this

Thank you so much for the review @rht

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If your concern is the centering of the visualization of the grid, it shouldn't complicate the core logic implementation. I recommend using the newer experimental visualization, https://mesa.readthedocs.io/en/stable/tutorials/visualization_tutorial.html (the current visualization you are using will be deprecated in Mesa 3.0). By default, you will get something like
default_jupyterviz
This is because the size auto-adjust algorithm doesn't cover extreme case when width << height yet.
But if you pass in a specific size, e.g. 10 to the agent portrayal, you will get
jupyterviz_fixed_size

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm going through visualization with Jupyter - Does that mean visualization can only work with the Jupyter environment, and currently built-in server visualization will be deprecated? no standalone execution?
So models should be jupyter notebooks going forward...?

I'm a bit confused with API documentation and comments. I believe the current stable version of API is 2.2.4, which is what we have used in the project. Does this mean that 3.0 is an overhaul of the complete API?

Please advise if there is any document, detailing 2.2.4 vs 3.0 api, mean while I'm going through project code on mesa

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

gone through new UI with JupyterViz and Solara, working with new way

however, I'm facing issues with accepting params (like we have in our model, mode, Rules and mobility rate ) with choice dropdown, looks like only param it can take is no of agents with slider
Annotation on 2024-04-15 at 06-24-01

screencapture-localhost-8765-2024-04-15-06_19_40

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rht please help advise

Copy link
Contributor

@rht rht Apr 15, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All the controls in the old viz have been implemented in the new viz. See https://github.com/projectmesa/mesa/blob/4cc03a4300ce2f0600efa3ef45a61f16d2290dc0/mesa/experimental/jupyter_viz.py#L365-L371 for the checkbox. You specify as

"layout": {"type": "Select", "value": "grid", "values": ["grid", "line"]}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rht thank you. I appreciate the patience explaining to me the required details
I've added new UI. Kindly review

# Function to compute the average price of all store agents in the model.
def compute_average_price(model):
"""Compute the average price of all stores."""
store_prices = [agent.price for agent in model.schedule.agents]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

model.agents is the new API, and is simpler.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The whole function can be simplified to return np.mean(model.agents.get("price")).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The intermediate variables are not necessary, because the docstring is already sufficiently descriptive.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed these comments

@rht
Copy link
Contributor

rht commented Apr 10, 2024

If you could add a test that check's for the prediction of the Hotelling's law, e.g.

def test_decreasing_price_variance():
# The variance of the average trade price should decrease over time (figure IV-3)
# See Growing Artificial Societies p. 109.
model = SugarscapeG1mt()
model.datacollector._new_model_reporter(
"price_variance",
lambda m: np.var(
flatten([a.prices for a in m.schedule.agents_by_type[Trader].values()])
),
)
model.run_model(step_count=50)
df_model = model.datacollector.get_model_vars_dataframe()
check_slope(df_model.price_variance, increasing=False)
. The test is run by pytest tests.py. The functions with prefix of test_* are automatically run by pytest. Also, in the visualization, you are meant to show that the standard deviation of the price is decreasing over time.

aumashankar and others added 3 commits April 11, 2024 09:16
-fixing review comments
1. The self.can_move check is redundant here, because it's already done in self.move
2. model.agents is the new API, and is simpler.
3. The whole function can be simplified to return np.mean(model.agents.get("price")).
4. The intermediate variables are not necessary, because the docstring is already sufficiently descriptive.
5. added tests for slope
@aumashankar
Copy link
Contributor Author

If you could add a test that check's for the prediction of the Hotelling's law, e.g.

def test_decreasing_price_variance():
# The variance of the average trade price should decrease over time (figure IV-3)
# See Growing Artificial Societies p. 109.
model = SugarscapeG1mt()
model.datacollector._new_model_reporter(
"price_variance",
lambda m: np.var(
flatten([a.prices for a in m.schedule.agents_by_type[Trader].values()])
),
)
model.run_model(step_count=50)
df_model = model.datacollector.get_model_vars_dataframe()
check_slope(df_model.price_variance, increasing=False)

. The test is run by pytest tests.py. The functions with prefix of test_* are automatically run by pytest. Also, in the visualization, you are meant to show that the standard deviation of the price is decreasing over time.

Added tests.py

@EwoutH
Copy link
Member

EwoutH commented Apr 16, 2024

@aumashankar and @rht, thanks for the hard work in the past days. I'm curious, how far along the review process are we? Is there anything I can do to help?

@aumashankar
Copy link
Contributor Author

@aumashankar and @rht, thanks for the hard work in the past days. I'm curious, how far along the review process are we? Is there anything I can do to help?

@EwoutH we've used old UI and some old api's with agent schedule @rht directed me to new mesa3.0 UI, helping review it in the process. last commit includes the feedback changes from @rht which can further help with review if it's good

```bash
python run.py

solara run app.py (mesa 3.0)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

People might misinterpret (mesa 3.0) as something to be typed. Better omit it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated

import solara
from mesa.experimental import JupyterViz

from .model import HotellingModel
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The relative import caused this error message on my machine (Python 3.11)

ImportError: attempted relative import with no known parent package

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can remove the relative imports for now.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adopted project structure removed relative imports

@rht
Copy link
Contributor

rht commented Apr 17, 2024

I ran the Solara simulation, and observed the variance going up over time instead of going down. Doesn't this contradict Hotelling's law?

@aumashankar
Copy link
Contributor Author

aumashankar commented Apr 17, 2024

I ran the Solara simulation, and observed the variance going up over time instead of going down. Doesn't this contradict Hotelling's law?

This observation is due to Initial Conditions and Randomness for the basic model
we are adjusting the price with random prices taken in the range 5 -15 . The idea of this model is to show how stores will change location based on pricing and some agents will be immobile irrespective of external conditions.

Observing an increase in price variance over time in the simulation does not necessarily contradict Hotelling's Law. as it depends on factors.

We are working further with consumer preferences and market share and no of consumers (might be another PR) where

Hotelling's Law, in the context of spatial competition, suggests that businesses will choose to locate themselves in a manner that minimizes competition,
often leading to some form of clustering or minimal differentiation Hotelling's Law can imply that firms will tend to match each other's prices to avoid price wars, which in turn could lead to a reduction in price variance over time as the firms reach a sort of equilibrium state.

Edit: changed test as variance can increase or decrease depending on factors.
For now, added another adjust_price_by_neighbour_store() in agents.py to mimic some logic however, it will be fully covered with more dynamics with consumers and market share in the next PR

aumashankar and others added 3 commits April 17, 2024 10:25
…ts and changed test for variance as for hotelling law variance need not decrease depends on factors
@rht
Copy link
Contributor

rht commented Apr 17, 2024

This observation is due to Initial Conditions and Randomness for the basic model

The basic model itself needs to display the Hotelling law, because it is what the example is named after. At least, try changing the default params until the variance reduction happens, and in the readme, tell the reader about the param range, and when and why it starts breaking down, or that the timescale could be longer. This is standard practice for sensitivity analysis.

If you want to speed up the simulation step duration, you can tweak the param play_interval, https://github.com/projectmesa/mesa/blob/4cc03a4300ce2f0600efa3ef45a61f16d2290dc0/mesa/experimental/jupyter_viz.py#L60. Or if this doesn't do, needs to investigate why it is slow for such a low number of agents.

@aumashankar
Copy link
Contributor Author

This observation is due to Initial Conditions and Randomness for the basic model

The basic model itself needs to display the Hotelling law, because it is what the example is named after. At least, try changing the default params until the variance reduction happens, and in the readme, tell the reader about the param range, and when and why it starts breaking down, or that the timescale could be longer. This is standard practice for sensitivity analysis.

If you want to speed up the simulation step duration, you can tweak the param play_interval, https://github.com/projectmesa/mesa/blob/4cc03a4300ce2f0600efa3ef45a61f16d2290dc0/mesa/experimental/jupyter_viz.py#L60. Or if this doesn't do, needs to investigate why it is slow for such a low number of agents.

There are multiple parts to it, one aspect is that, hotelling law in itself doesn't contradict as it depends on other parameters. However,
We are already working on locally with consumers and market share, I think it's better to integrate that and do sensitivity analysis.

I'll get back in a day or two to integrate those here.

umashankar-xebia and others added 3 commits April 20, 2024 09:40
@aumashankar
Copy link
Contributor Author

aumashankar commented Apr 20, 2024

This observation is due to Initial Conditions and Randomness for the basic model

The basic model itself needs to display the Hotelling law, because it is what the example is named after. At least, try changing the default params until the variance reduction happens, and in the readme, tell the reader about the param range, and when and why it starts breaking down, or that the timescale could be longer. This is standard practice for sensitivity analysis.
If you want to speed up the simulation step duration, you can tweak the param play_interval, https://github.com/projectmesa/mesa/blob/4cc03a4300ce2f0600efa3ef45a61f16d2290dc0/mesa/experimental/jupyter_viz.py#L60. Or if this doesn't do, needs to investigate why it is slow for such a low number of agents.

There are multiple parts to it, one aspect is that, hotelling law in itself doesn't contradict as it depends on other parameters. However, We are already working on locally with consumers and market share, I think it's better to integrate that and do sensitivity analysis.

I'll get back in a day or two to integrate those here.

@rht updated PR with consumer preferences, market share, visualizations and tests for simulation

kindly review. I appreciate your patience and helping us with details (we are learning the framework)

- matplotlib
- numpy
- scipy
- jupyter
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

jupyter is not needed. Everything else is auto-installed when installing mesa, except for scipy.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated requirements.txt and Readme.md

Thanks a lot for the review @rht

@rht
Copy link
Contributor

rht commented Apr 20, 2024

Everything else LGTM.

@aumashankar
Copy link
Contributor Author

Everything else LGTM.

Thank you

git+https://github.com/projectmesa/mesa-examples
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line is not needed, and is confusing to be here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah.. I was just going through other samples... I'm removing it... can you explain the context how other examples using it

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They should be removed. The experimental visualization used to live in the mesa-examples repo.

@@ -0,0 +1,34 @@
import cProfile
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Forgot to comment this: the file cprofile_test.py shouldn't be part of the example.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok. removing this file

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remvoed

@rht rht merged commit 1e0d6b8 into projectmesa:main Apr 20, 2024
3 checks passed
@rht
Copy link
Contributor

rht commented Apr 20, 2024

Merged, thank you @aumashankar.

@aumashankar
Copy link
Contributor Author

aumashankar commented Apr 20, 2024

Merged, thank you @aumashankar.

@rht Thanks a lot for the review and all the help provided in learning the mesa framework. (the old and new)
@EwoutH @jackiekazil @dmasad Thank you for the opportunity.

@jackiekazil
Copy link
Member

@aumashankar Thank you for YOUR contribution and for making requested changes. We appreciate your diligence and contribution!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants