GithubHelp home page GithubHelp logo

ab-ce / abce Goto Github PK

View Code? Open in Web Editor NEW
182.0 24.0 62.0 17.91 MB

Agent-based computational Economics, the Python library that makes AB modelling easier

Home Page: http://abce.readthedocs.io

Python 99.82% Shell 0.07% Cython 0.11%
python economic simulation abm agent-based economicsl

abce's Introduction

abcEconomics: the Agent-Based Computational Economy platform that makes modeling easier

abcEconomics is a Python based modeling platform for economic simulations. abcEconomics comes with standard functions to simulations of trade, production and consumption. The modeler can concentrate on implementing the logic and decisions of an agents; abcEconomics takes care of all exchange of goods and production and consumption.

Build CI Pypi version readthedocs
https://raw.githubusercontent.com/AB-CE/abce/master/docs/cheesegrater.png

In abcEconomics, goods have the physical properties of goods in reality in the sense that if agent A gives a good to agent B, then - unlike information - agent B receives the good and agent B does not have the good anymore. The ownership and transformations (production or consumption) of goods are automatically handled by the platform.

abcEconomics models are programmed in standard Python, stock functions of agents can be inherited from archetype classes (Firm or Household). The only not-so-standard Python is that agents are executed in parallel by the Simulation class (in start.py).

abcEconomics allows the modeler to program agents as ordinary Python class-objects, but run the simulation on a multi-core/processor computer. It takes no effort or intervention from the modeler to run the simulation on a multi-core system. The speed advantages of using abcEconomics with multi-processes enabled. abcEconomics are typically only observed for 10000 agents and more. Below, it might be slower than pure python implementation. abcEconomics supports pypy3, which is approximately 10 times faster than CPython.

abcEconomics is a scheduler and a set of agent classes. According to the schedule the simulation class calls - each sub-round - agents to execute some actions. Each agent executes these actions using some of the build-in functions, such as trade, production and consumption of abcEconomics. The agents can use the full set of commands of the Python general purpose language.

The audience of abcEconomics are economists that want to model agent-based models of trade and production.

abcEconomics does support an accounting framework for financial simulations: abcFinance (https://github.com/ab-ce/abcFinance).

abcEconomics runs on macOS, Windows, and Linux. abcEconomics runs 10x faster on pypy!

Install with:

pip3 install abcEconomics

The documentation is here:

http://abce.readthedocs.io/

A code example is here:

Jupyter Tutorial

More code examples are here:

https://github.com/AB-CE/examples

abce's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

abce's Issues

NotEnoughGoods called without needed arguments in Firm produce()

If a firm does not have enough goods for its production function it throws the NotEnoughGoods exception. However it does not pass the required parameters in the constructor making it impossible to handle this error.

  File "/home/a/code/econ/abce/examples/economy/bakery.py", line 41, in production
    self.produce(self.pf, self.inputs)
  File "/home/a/.local/lib/python3.8/site-packages/abcEconomics/agents/firm.py", line 130, in produce
    raise NotEnoughGoods
TypeError: __init__() missing 3 required positional arguments: '_agent_name', 'good', and 'amount_missing'

See https://github.com/AB-CE/abce/blob/master/abcEconomics/agents/firm.py#L130

Can't access individual agents in group with index

In the documentation, it says that individual agents in a group can be accessed with an index. When I tried this, it gave me a TypeError

Code used:

# Define all agents in the economy
class Citizen(abce.Agent):    
    def init(self, money):        
        # initial money balance
        self.create('money', money)
        
        # years of schooling
        self.employee_qualification = random.randint(0, 21)
        
        def get_salary():
            return 100

simulation = abce.Simulation(name='economy', processes=1)    
citizens = simulation.build_agents(Citizen, 'citizen', number=num_citizens, money = 1000)

citizens[0].get_salary()

Error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-28-459e186e15ce> in <module>()
     13 citizens = simulation.build_agents(Citizen, 'citizen', number=num_citizens, money = 1000)
     14 
---> 15 citizens[0].get_salary()

/usr/local/lib/python3.6/dist-packages/abce/group.py in __call__(self, *args, **kwargs)
     55     def __call__(self, *args, **kwargs):
     56         for group_names, ids, command, _, __ in self.actions:
---> 57             self._agents.do(group_names, ids, command, args, kwargs)
     58         return Chain([self._agents.post_messages(action[0], action[1]) for action in self.actions])
     59         # itertools.chain, does not work here

/usr/local/lib/python3.6/dist-packages/abce/singleprocess.py in do(self, groups, ids, command, args, kwargs)
     57         self.rets = []
     58         for group, iss in zip(groups, ids):
---> 59             for i in iss:
     60                 if i is not None:
     61                     ret = self.agents[group][i]._execute(command, args, kwargs)

TypeError: 'int' object is not iterable

Please let me know if I am attempting to access the agents incorrectly, or doing something wrong!

ZMQ error when try to run an exsample model

Hi,

I'm really interested with the project as an macroeconomist with skepticism to DSGE and python familiality. Instralltion seems suceeded into my "anaconda" on windows envroment. But, I've just an error when I tried to run example model "...\example\2sectors\start.py " . The error message is like below. It would be really helpful if you look at this and hint some solutions when you have time.

Best regards,

Traceback (most recent call last):
File "", line 1, in
File "C:\Python27\Anaconda\lib\multiprocessing\forking.py", line 380, in main
prepare(preparation_data)
File "C:\Python27\Anaconda\lib\multiprocessing\forking.py", line 495, in prepa
re
'parents_main', file, path_name, etc
File "M:\Takashi SHIONO\Numerical\ABCE\example\2sectors\start.py", line 11, in

w = Simulation(simulation_parameters)
File "C:\Python27\Anaconda\lib\site-packages\abce__init__.py", line 225, in _
init_
self.commands.bind(self._addresses['command_addresse'])
File "socket.pyx", line 448, in zmq.backend.cython.socket.Socket.bind (zmq\bac
kend\cython\socket.c:4126)
File "checkrc.pxd", line 21, in zmq.backend.cython.checkrc._check_rc (zmq\back
end\cython\socket.c:6174)
zmq.error.ZMQError: Address in use

installation problem

probably finger trouble at my end as a newbie to Python & abce. I hope you can help...
i am using win 8.1.
The \doc reads a little differently to the readme..
the readme states:
copy abce/example to your_model_path::

  1. cd your_model_path
    cp ../abce/template/* .
  2. In line 3 of start.py: adjust sys.path.append('your_path_to/abce/lib')
    Not sure what you mean by your model path but you can see in the TREE command below what i inferred.
    Regarding 2. i don't see "sys.path.append" in start.py.
    You can see from the path command below how i have set up paths.

When i run start.py from the copied templates i get...
C:\Programs\abce-master\template>start.py
Traceback (most recent call last):
File "C:\Programs\abce-master\template\start.py", line 2, in
from firm import Firm
File "C:\Programs\abce-master\template\firm.py", line 2, in
import abce
ImportError: No module named abce

Please advise what steps or changes i am missing, thanks...
The path and tree commands follow.....

abce path
C:\Windows\System32>path
PATH=C:\Python27\Lib\site-packages;C:\Python27\Lib\site-packages\PyQt4;
C:\Programs\Pure;C:\Programs\Pure\lib;C:\Program Files (x86)\Java\jdk1.7.0_65\bin;
C:\Python27;C:\Python27\DLLs;C:\Python27\Scripts;C:\Python27\gnuplot\binary;
C:\Program Files (x86)\pythonxy\SciTE-3.3.2-3;C:\Program Files (x86)\pythonxy\console;
C:\MinGW32-xy\bin;
C:\Programs\abce-master\abce\lib;
C:\Program Files (x86)\Vensim\Venple.exe;C:\Programs\Pure;C:\Programs\EMAworkbench-master\src;C:\Programs\EMAworkbench-master\src\examples;C:\Programs\EMAworkbench-master\src\expWorkbench

abce-tree
C:\Windows\System32>tree c:\programs\abce-master /f
Folder PATH listing for volume Windows
Volume serial number is 0000000A EE6A:1709
C:\PROGRAMS\ABCE-MASTER
│ .gitignore
│ abce-master.zip
│ ABCE.pdf
│ MANIFEST.in
│ README.rst
│ setup.py

├───abce
│ │ abcelogger.py
│ │ agent.py
│ │ database.py
│ │ db.py
│ │ firm.py
│ │ firmmultitechnologies.py
│ │ from_gams.py
│ │ household.py
│ │ logger.py
│ │ messaging.py
│ │ postprocess.py
│ │ postprocess.R
│ │ subround.py
│ │ tools.py
│ │ trade.py
│ │ init.py
│ │
│ └───lib
│ └───template
│ agents_parameters.csv
│ config.py
│ firm.py
│ firm.pyc
│ household.py
│ script.R
│ simulation_parameters.csv
│ start.py

├───doc
│ abcetools.rst
│ Agent_class.rst
│ amazon_ec2.rst
│ conf.py
│ Database.rst
│ examples.rst
│ files.rst
│ Firm.rst
│ FirmMultiTechnologies.rst
│ Household.rst
│ index.rst
│ installation.rst
│ introduction.rst
│ make.bat
│ Makefile
│ messagemodel.jpg
│ Messaging.rst
│ parameters.rst
│ simulation.rst
│ simulation_results.rst
│ sphinxarticle.cls
│ Trade.rst
│ unit_testing.rst
│ Walk_through.rst

├───example
│ │ README.rst
│ │
│ ├───2sectors
│ │ agents_parameters.csv
│ │ config.py
│ │ firm.py
│ │ household.py
│ │ script.R
│ │ simulation_parameters.csv
│ │ start.py
│ │
│ └───one_household_one_firm
│ config.py
│ firm.py
│ household.py
│ script.R
│ simulation_parameters.csv
│ start.py

├───template
│ abce_templates-0.3.zip
│ agents_parameters.csv
│ config.py
│ firm.py
│ firm.pyc
│ household.py
│ script.R
│ simulation_parameters.csv
│ start.py

└───unittest
agents_parameters.csv
buy.py
config.py
endowment.py
give.py
logger.py
nohup.out
quote_buy.py
sell.py
simulation_parameters.csv
start.py

production.csv and buy.csv are empty

Hi Davoud,

After installing, I ran the one_household_one_firm example which runs and produces the files in the results folder. Nevertheless, the production and buy csv files are empty.

I tried re-installing, but the problem persists, and imported sqlite3 beforehand.

Do you have any idea why this could occur ?

Thanks & Regards,
Tina

Walk Trough doc page is not correct/outdated?

Functions mentioned in https://abce.readthedocs.io/en/master/Walk_through.html are not found in the Simulation class, like

simulation.declare_round_endowment(resource='labor_endowment', units=1, product='labor')
simulation.declare_perishable(good='labor')

as well as also mentioned below in the text abcEconomics.Simulation.declare_service() and abcEconomics.Simulation.declare_round_endowment()

That leads to errors running examples, like CCE.

Can you clarify from the design point of view, does that mean principal changes in dealing with resources?
Thanks

abcEconomics.Trade is undefined.

Hi,

I get another issue when I trying to do the example of one household and one firm.

(page 17-19) https://readthedocs.org/projects/abce/downloads/pdf/master/

The error message is:

AttributeError: module 'abcEconomics' has no attribute 'Trader', I think the Trader class is at:

\abcEconomics\agents\trader.py or do we have another way to call Trader?

Once I load the class Trader, then a new problem comes out:

---> households.sell_labor()

abcEconomics.notenoughgoods.NotEnoughGoods: "('household', 0) 1 of good 'labor' missing"

Could you help me?

Thanks


households.sell_labor()
Traceback (most recent call last):
File "", line 1, in
File "D:\AgentBasedBench\abcEconomics\group.py", line 59, in call
self._scheduler.do(names, command, args, kwargs)
File "D:\AgentBasedBench\abcEconomics\scheduler\singleprocess.py", line 52, in do
ret = self.agents[name]._execute(command, args, kwargs)
File "D:\AgentBasedBench\abcEconomics\agent.py", line 155, in _execute
ret = getattr(self, command)(*args, **kwargs)
File "", line 17, in sell_labor
File "D:\AgentBasedBench\abcEconomics\agents\trader.py", line 469, in sell
raise NotEnoughGoods(self.name, good, quantity - available)
abcEconomics.notenoughgoods.NotEnoughGoods: "('household', 0) 1 of good 'labor' missing"

Trade logging error

File "trade.pyx", line 703, in abcEconomics.trade.Trade._log_receive_accept_agent
AttributeError: 'abcEconomics.trade.Offer' object has no attribute 'receiver_group'

I keep getting this error when attempting to log trade with either 'group' or individual'

Thanks! Let me know if you need more context.

simulation.graphs()

simulation.graphs() happend "NameError: name 'form' is not defined",If you understand, please teach me.
thank you!
1552526327(1)

OverflowError: Python int too large to convert to C long

Hi Davoud,

Thanks for your package! I just meet a problem when I run your example called '2sectors', and this error also occurs on the jupyter tutorials.

Could you give me a hand?
Thanks

system: windows 10
python version: 3.6
I install ABCE from pip
abcEconomics-0.9.7b2

households.sell_labor()
Traceback (most recent call last):
File "C:\Users\Arthu\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2910, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "", line 1, in
households.sell_labor()
File "C:\Users\Arthu\Anaconda3\lib\site-packages\abcEconomics\group.py", line 59, in call
self._scheduler.do(names, command, args, kwargs)
File "C:\Users\Arthu\Anaconda3\lib\site-packages\abcEconomics\singleprocess.py", line 51, in do
ret = self.agents[name]._execute(command, args, kwargs)
File "C:\Users\Arthu\Anaconda3\lib\site-packages\abcEconomics\agent.py", line 153, in _execute
ret = getattr(self, command)(*args, **kwargs)
File "D:\AgentBasedModelComparison\household.py", line 17, in sell_labor
self.sell(('firm', self.employer), "labor", quantity=1, price=1)
File "abcEconomics\trade.pyx", line 485, in abcEconomics.trade.Trade.sell
File "abcEconomics\trade.pyx", line 121, in abcEconomics.trade.Offer.cinit
OverflowError: Python int too large to convert to C long


from tutorial:
for r in range(2):
simulation.advance_round(r)
print('Customer offers 10 dollar:')
customers.buy_drugs()
kids.print_possessions()
print('Drug Dealer accepts or rejects the offer:')
drug_dealers.sell_to_customers()
kids.print_possessions()
print()
Customer offers 10 dollar:

OverflowError Traceback (most recent call last)
in ()
2 simulation.advance_round(r)
3 print('Customer offers 10 dollar:')
----> 4 customers.buy_drugs()
5 kids.print_possessions()
6 print('Drug Dealer accepts or rejects the offer:')

~\Anaconda3\lib\site-packages\abcEconomics\group.py in call(self, *args, **kwargs)
57 def call(self, *args, **kwargs):
58 for names, command, _, __ in self.actions:
---> 59 self._scheduler.do(names, command, args, kwargs)
60 return Chain([self._scheduler.post_messages(action[0]) for action in self.actions])
61 # itertools.chain, does not work here

~\Anaconda3\lib\site-packages\abcEconomics\singleprocess.py in do(self, names, command, args, kwargs)
50 for name in names:
51 ret = self.agents[name]._execute(command, args, kwargs)
---> 52 self.rets.append(ret)
53
54 def post_messages(self, names):

~\Anaconda3\lib\site-packages\abcEconomics\agent.py in _execute(self, command, args, kwargs)
151 self._do_message_clearing()
152 self._begin_subround()
--> 153 ret = getattr(self, command)(*args, **kwargs)
154 self._end_subround()
155 self._reject_polled_but_not_accepted_offers()

in buy_drugs(self)
6 def buy_drugs(self):
7 drug_dealer_id = randrange(self.num_dealers)
----> 8 self.buy(('drug_dealer', drug_dealer_id), good='drugs', quantity=1, price=10)
9
10 def print_possessions(self):

~\Anaconda3\lib\site-packages\abcEconomics\trade.pyx in abcEconomics.trade.Trade.buy()

~\Anaconda3\lib\site-packages\abcEconomics\trade.pyx in abcEconomics.trade.Offer.cinit()

OverflowError: Python int too large to convert to C long

simulation.finalize() must be specified at the end of simulation
simulation.finalize() must be specified at the end of simulation
simulation.finalize() must be specified at the end of simulation

Error with unequal numbers of agents

Hi,
I am somewhat new to agent based modelling and I am currently looking for good libraries. During my research I found your library which looks very useful so far. I played around with the example "2sectors". When I change the numbers of households and firms to an unequal number e.g. 2 households and 1 firm, I get the following Error:

Traceback (most recent call last):
File "P:\workspace\AgentBased\src\twosectors\start.py", line 40, in
main(simulation_parameters)
File "P:\workspace\AgentBased\src\twosectors\start.py", line 30, in main
firms.buy_inputs()
File "", line 1, in
File "C:\Anaconda2-64\envs\PetchemGlobalModel\lib\site-packages\abce\group.py", line 40, in execute_serial
self.groups, command, [], args, kwargs)
File "C:\Anaconda2-64\envs\PetchemGlobalModel\lib\site-packages\abce\processorgroup.py", line 59, in execute
self.put_messages_in_pigeonbox(messages)
File "C:\Anaconda2-64\envs\PetchemGlobalModel\lib\site-packages\abce\processorgroup.py", line 99, in put_messages_in_pigeonbox
self.agents[group][id // self.num_managers].inbox.append(message)
IndexError: list index out of range

I do not know if my changes make sense from a modelling perspective but I assume it should not cause an error.

Problem with hashing

New version of 'hash' in python give different values during execution of each thread when doing multiprocessing. Following error will accure:

50000_firms/start.py return error when running in 2 or more processess:
KeyError: ('myagent', 11980)

There is problem with three functions which use 'hash':
multiprocessing.py -- def insert_or_append
multiprocessing.py -- def do
agent.py -- def _send_multiprocessing

my proposal - replace default hash function with:

import hashlib
def new_hash(agent_key):
    return int(hashlib.md5(str(agent_key).encode()).hexdigest()[:8],16)

Individual trade log throws an exception

Hi, I enabled trade logging in the call of simulation as:
sim = abce.Simulation(name="Market model", trade_logging='individual', processes=1)

and when run, I got the exception:

...\abce\abcEconomics\trade.py in _log_receive_accept_agent(self, offer)
690 else:
691 self.trade_log[(offer.good, '%s%i' % (
--> 692 offer.receiver[0], offer.receiver[1]), self.name_without_colon, offer.price)] += offer.quantity
693
694 def _receive_reject(self, offer_id):

AttributeError: 'Buyer' object has no attribute 'name_without_colon'

Benchmarking the accuracy of the prediction of ABM-based models against DSGE

For rigor's sake, it would be effective to create a benchmark based on a real dataset that can be reused by several ABM implementations, throughout the time. This is analogous to the NIST hash function competition or ML datasets in various fields but is instead for economic models. If such benchmark exists, prediction accuracy and runtime perf can be iteratively improved over time.

I found a super relevant paper here and its implementation here. I have been diving into https://github.com/S120/benchmark, wasn't able to find how a dataset is included. The most I could find so far (in order to proceed) is from footnote-26 in the paper:

Real time series are taken from the Federal Reserve Economic Data (FRED): they are quarterly data ranging from 1955-01-01 to 2013-10-01 for unemployment (not seasonally adjusted, FRED code: LRUN64TTUSQ156N) and ranging from 1947-01-01 to 2013-10-01 for investments, consumption and GDP (FRED codes: PCECC96, GPDIC96, and GDPC1 respectively)

Even so, I can't figure any micro params from the paper, e.g. how many agents (households+firms+banks) have to be spawned (whether the number should grow organically over several decades), initial endowments/prices/wages. I could find the sequence of events for each round at section 2.1.
Do you have any recommendation on how to write the model in ABCE, @DavoudTaghawiNejad

Issue when building agents

Hi Davoud,
Thanks for writing such an innovative package.
I'm having an issue when trying to run the 'one household one firm with logic' example, specifically with the line:
firms = simulation.build_agents(Firm, 'firm', 1)
This may be a noob issue in which case apologies, but it's not letting me create a firm and stating 'TypeError: Firm() takes no arguments'. The same happens when I switch the lines to put household first. Please let me know if there's any further info I can provide to help with diagnostics,

Thanks,
Cale

Issue when running jupyter example

When running jupyter example the code breaks. I'm running the following code:

import abce

simulation = abce.Simulation(name="ipythonsimulation", processes=1)

class Agent(abce.Agent):
    def init(self, parameters, agent_parameters):
        self.family_name = agent_parameters
        self.world_size = parameters['world_size']
    def say(self):
        print("hello I am %s my id %i and my group is '%s', it is the %i round" % (self.family_name, self.id, self.group, self.round))

agents = simulation.build_agents(Agent, 'agent', 
                                parameters={"world_size": 10}, 
                                agent_parameters=['fred', 'astaire', 'altair', 'deurich'])

I get the following error:

TypeError: string indices must be integers

in

singleprocess.py

agent.init(**ChainMap(simulation_parameters,ap))

Error when running abcEconomics using the latest flexx version (0.80)

Traceback (most recent call last):
  File "start.py", line 9, in <module>
    from abcEconomics import Simulation, gui
  File "/home/rht/code/venv/lib/python3.8/site-packages/abcEconomics/gui/__init__.py", line 8, in <module>
    from .basiclayout import basiclayout
  File "/home/rht/code/venv/lib/python3.8/site-packages/abcEconomics/gui/basiclayout.py", line 9, in <module>
    from .dockpanel import DockPanel
  File "/home/rht/code/venv/lib/python3.8/site-packages/abcEconomics/gui/dockpanel.py", line 1, in <module>
    from flexx.pyscript import window
ModuleNotFoundError: No module named 'flexx.pyscript'

The flexx API has changed.

Jupyter Tutorial: dealer not selling on round 0

Hi!
I recently discovered abcEconomics and started to learn to use it by reading and running the jupyter tutorial on the website. However, I'm kind of stuck on the "Trade" section. The dealer, if I'm understanding correctly, should be selling after the consumer's offer on round 0, since they have drugs available, yet it seems, according to print_possessions(), that this is not happening. Why is that?

Here's what I'm getting (both by running my own notebook and the one on the repo):

from random import randrange

class NewKid(abce.Agent):
    def init(self, num_dealers):
        self.num_dealers = num_dealers
        self.create('money', 100)  # don't we all wish you'd this function in real live?
        
    def buy_drugs(self):
        drug_dealer_id = randrange(self.num_dealers)
        self.buy(('drug_dealer', drug_dealer_id), good='drugs', quantity=1, price=10)
    
    def print_possessions(self):
        print('    ' + self.group + str(dict(self.possessions())))

class DrugDealer(abce.Agent):
    def init(self):
        self.create('drugs', 1)
        
    def sell_to_customers(self):
        for offer in self.get_offers('drugs'):
            if offer.price >= 10 and self['drugs'] > 1:
                self.accept(offer)
    
    def print_possessions(self):
        print('    ' + self.group + str(dict(self.possessions())))

num_dealers = 1
num_customers = 1

simulation = abce.Simulation(name='school_yard', processes=1)

drug_dealers = simulation.build_agents(DrugDealer, 'drug_dealer', number=num_dealers)
customers = simulation.build_agents(NewKid, 'customer', number=num_customers, num_dealers=num_dealers)

kids = drug_dealers + customers

for r in range(2):
    print('Round', r)
    simulation.advance_round(r)
    print('Customer offers 10 dollar:')
    customers.buy_drugs()
    kids.print_possessions()
    print('Drug Dealer accepts or rejects the offer:')
    drug_dealers.sell_to_customers()
    kids.print_possessions()
    print()

Result:

Round 0
Customer offers 10 dollar:
    drug_dealer{'drugs': 1.0}
    customer{'money': 90.0}
Drug Dealer accepts or rejects the offer:
    drug_dealer{'drugs': 1.0}
    customer{'money': 100.0}

Round 1
Customer offers 10 dollar:
    drug_dealer{'drugs': 1.0}
    customer{'money': 90.0}
Drug Dealer accepts or rejects the offer:
    drug_dealer{'drugs': 1.0}
    customer{'money': 100.0}

Expected behavior:

Round 0
Customer offers 10 dollar:
    customer{'money': 90.0}
    drug_dealer{'drugs': 1.0}
Drug Dealer accepts or rejects the offer:
    customer{'money': 90.0, 'drugs': 1.0}
    drug_dealer{'drugs': 0, 'money': 10.0}

Round 1
Customer offers 10 dollar:
    customer{'money': 80.0, 'drugs': 1.0}
    drug_dealer{'drugs': 0, 'money': 10.0}
Drug Dealer accepts or rejects the offer:
    customer{'money': 90.0, 'drugs': 1.0}
    drug_dealer{'drugs': 0, 'money': 10.0}

Logging needs to configure, what kind of graphs and aggregations are created.

Logging needs to configure, what kind of graphs and aggregations are created,

simulation.logging(variables={'a': ['mean'], 'gdp': ['mean', 'aggregate', 'panel']}
possessions={'money': ['aggregate', 'panel'], ...})

simulation.panel and simulation.aggregate should be depreciated accordingly

a simple list should still be supported.

issue with printing offer

class Offer(object) in trade.py have error in __repr__ method:

  • currency should be '%s'
  • final_quantity doesn't print when None
  • status_round doesn't print with None
  • space between '%' and 'f': final_quantity: % f

My suggestion for fixing above would be:

    def __repr__(self):
        i_fin_quant = str(self.final_quantity)
        i_status_round = str(self.status_round)

        return ("""<{sender: %s, receiver: %s, good: %s, quantity: %f, price: %f, currency: %s,
                sell: %s, status: %s, final_quantity: %s, id: %i, made: %s, status_round: %s }>""" %
                (self.sender, self.receiver, self.good, self.quantity, self.price, self.currency,
                self.sell, self.status, i_fin_quant, self.id, self.made, i_status_round))

plotting None values

When there are missing values in the date, the graphs change them to zero resulting in strange graphs

RFC: General constraints on the simulations that MUST be ensured

  • (conservation of matter, SFC-specific) The AB economic model MUST be stock-flow consistent. This can be enforced by disabling Inventory.create when it is not followed by Inventory.destroy. This can be statically-checked before runtime.
  • (floating point stability, EM-specific) Monetary arithmetic MUST be conducted in long double or an
    arbitrary-precision signed decimal number in the smallest currency unit that exists in the model.
  • (repeatability, DES-specific) Agents execution order within a scheduler's step(), while randomized, MUST be deterministic, specified from a random seed.
  • (double-entry accounting, EM-specific) A = C + L.
  • (floating point rounding, EM-specific) Ensure banker's rounding.

Glossary; hierachy of scopes:

  1. simulation -> DES-specific (discrete-event simulation) -> ABM-specific (agent-based model), MAS-specific (multi-agent simulation)
  2. EM-specific (economic-modeling) -> SFC-specific, neoclassical, ACE-specific

Mesa example not working

We were trying to check out this project by running the mesa model example. Unfortunatly there is a bug in the code. The model.py file is calling the following:

    abcEconomics.Simulation.__init__(self,
                             name='abcEconomics and MESA integrated',
                             rounds=300,
                             processes=1)

but rounds is not a valid in the init function for the Simulation code.

We also tried running the start.py example it is incomparable with the current version of mesa. Mesa is not part of the requirements.txt so we are not sure which ones to try.

Let us know if you need more information to reproduce. thank you.

abce firms 50000 example

File 50000_firms/b.py contains classes that no longer exist

50000_firms/youragent.py error in:
assert self['cookie'] == 0
should be:
assert self.not_reserved('cookie') ==0

Persistence/serialization: reduce to using one data format

Currently, the complete logging data is stored as a combination of sqlite file (slow because of synchronous write to fs) + csv files for panel and aggregate. It'd be simpler to use just one format (one file) that can be readily ported to / parsed by other platforms.

The fastest out there is ujson[1] though with this, it is not possible to append/modify an entry without having to load the entire file into the memory.

[1] https://blog.hartleybrody.com/python-serialize/

[gui] Offload gui handling to jupyter

Advantages:

  • Less maintenance overhead. There are plenty features/engines that need to be implemented yet.
  • More standardized format. Most comp sci 'lab books' are stored in .ipynb.

!Advantages:

  • Less freedom in implementing temporal events because jupyter notebooks are declarative.

Increase performance

Multithreading performance could be increased:

Don't generate agents if they are not in thread:
rewrite: ProcessorGroup.insert_or_append:

      for i_id, ap in enumerate(agent_parameters, maxid):
           
           agent_name = (agent_arguments['group'],i_id)
           if hash(agent_name) % self.processes == self.batch:
               agent = Agent(i_id, simulation_parameters, ap, **agent_arguments)
               agent._send = agent._send_multiprocessing ## send method is rewriten 
               agent._out = defaultdict(list)
               agent.init(**ChainMap(simulation_parameters, ap))
               
               assert agent.name not in self.agents, agent.name
               agent._str_name = re.sub('[^0-9a-zA-Z_]', '', str(agent.name))
               names[agent.name] = agent.name
               agent._processes = self.processes
               self.agents[agent.name] = agent

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.