Additional Data Structures

Additional data structures are special data structures such as an inventory, a registry for workers or registry for debtors. They are not included in the ‘standard’ instances, and thus not inherited from Agent.

Inventory

class sfctools.datastructs.inventory.Inventory(owner, depreciation_dict=None)

Bases: object

Inventory data structure. An Inventory consists of a collection of current assets.

Name of asset

inventory (in physical quant.)

costs ( = worth in €)

Apples

10

2.0

Oranges

9

2.1

Usage: The inventory is a non-standard feature of an agent and has to be added manually

class InventoryAgent(Agent):
    def __init__(self):
        super().__init__()
        self.inventory = Inventory(self)

my_agent = InventoryAgent()
my_agent.inventory.add_item(name,quantity,costs)
my_agent.inventory.remove_item(name, quantity)
my_agent.inventory.get_inventory(name)

Instantiates a new inventory data structure.

Parameters
  • owner – instance who owns this data structure

  • depreciation_dict – a dict with the depreciation values for the goods stored in the

add_item(name, quantity, costs)

adds an item to the inventory

Parameters
  • name – name of the item

  • quantity – quantity of the item (float or int)

  • costs – the nominal value of the items being added (= quantity x price)

depreciate(method='linear')

Depreciates the values in the balance sheet. This requires a sfctools.Settings object to be instantiated.

Parameters

method – ‘linear’ (other options not yet implemented)

get_inventory(name)

gets the current inventory of a certain item type

Param

name of the item

remove_item(name, quantity)

Takes a certain quantity of an item out of inventory

Parameters
  • name – name of the item from which you want to remove

  • quantity – physical quantity to remove

to_dataframe()

converts the inventory data to pandas dataframe format

to_string()

converts the inventory data to string format

property worth

computes total nominal worth of the inventory.

Worker Registry

class sfctools.datastructs.worker_registry.WorkerRegistry(owner, wage_attr='reservation_wage')

Bases: object

The (rudimentary) worker registry keeps track of all agents that work at a firm (or other agent)

Worker

Agent1

Agent2

AgentN

constructor for worker registry

add_worker(agent, verbose=False)

add a worker and corresponding wage to the registry

fire_all()

remove all workers from the registry

fire_random(number, verbose=False)

fire a certain number of workers at random

get(i)

get worker by index

get_avg_costs()

computes the cost of labor, i.e. the average value of all wages

log_wage_bill(t, wb)

stores a value for wage bill wb at time t

pop()

gets the last worker

remove_worker(agent)

remove a worker from registry (has been fired, retired, …)

property workers

returns a list of workers

Bank Order Book

class sfctools.datastructs.bank_order_book.BankOrderBook(owner, credit_market: Optional[sfctools.bottomup.matching.MarketMatching] = None, deposit_market: Optional[sfctools.bottomup.matching.MarketMatching] = None)

Bases: object

The order book keeps track of all agents that have deposits and loans at a bank.

loans data:

{
Agent1: list[Table],
Agent2: list[Table],
...
}

Loans:

ID

Agent

Outstanding Loans

interest on loans (r_l)

Principal

Time

Maturity

0

10.0

10.0

0.05

100.0

1

42

Deposits:

ID

Agent

Depos.

interest on deposits (r_d)

Time

Duration

0

10.0

0.05

0.01

1

42

constructor

Parameters

owner – agent instance who owns this data structure

Credit_market

a MarketMatching obect for the credit market (default None). Providing an instance will automatically unlink agents when the deposit is dissolved.

Deposit_market

a MarketMatching object or the deposit market (default None). Providing an instance will automatically unlink agents when the deposit is dissolved.

add_deposits(agent: sfctools.core.agent.Agent, new_deposits, r_d, t=inf)

add deposits of an agent at this bank

Parameters
  • agent – reference to agent

  • new_deposits – amount of new deposits

  • r_d – interest rate on deposits

  • t – time of the deposits

add_loans(agent: sfctools.core.agent.Agent, new_loans: float, r_l: float, t=20)

add loans of an agent at this bank

Parameters
  • agent – reference to agent

  • new_loans – amount of new loans

  • r_l – interest rate on loans

  • t – payback time (default 20 periods)

debt_equity_swap(agent, q)

BETA writes off a debt-equity swap

Parameters
  • agent – refrence to an agent instance

  • q – quanity to write off

property debtors: dict
property depositors: dict
deposits_data

defaultdict of deposits

get_deposit_interest_of(agent) float

compute the mean interest rate an agent is paid

get_deposits_of(agent)

get a list of dicts with the information on deposits for an agent

Parameters

agent – the reference agent

Returns

list of dicts

get_loan_interest_of(agent) float

compute the mean interest rate an agent pays

Parameters

agent – reference to an agent instance

get_loans_of(agent)

get a list of dicts with the information on loans for an agent

Parameters

agent – the reference agent

Returns

list of dicts

get_tot_deposits_of(agent) float

returns the total deposts of an agent

Parameters

agent – reference to an agent instance

get_tot_loans_of(agent) float

returns the total loans of an agent

Parameters

agent – reference to an agent instance

loans_data

defaultdata of loans

remove_deposit(idx, agent)

remove a deposit by index

Parameters
  • idx – index of entry

  • agent – agent who belongs to this deposit

remove_loan(idx, agent)

Removes a whole entry (this should be called when a loan is entirely paid back)

Parameters
  • idx – id of the loan

  • agent – agent belonging to the loan

to_dataframe()

returns pandas datafame representation of this data struture

Returns

deposits_df, loans_df (tuple)

to_string()

string representation of this data structure

withdraw_from_account(agent, quantity)

BETA withdraw money from deposit account.

Parameters
  • agent – agent who withdraws

  • quantity – quantity to withdraw

write_off_bad_debt(agent, q)

BETA books a bad debt. This means that loans are written off this data struct.

Parameters
  • agent – the agent concerning the bad debt

  • q – amount of bad debt to write off

Production Tree

class sfctools.bottomup.productiontree.Dummy
class sfctools.bottomup.productiontree.ProductionTree(production_dict, data, agent_name_dict=None)

A production tree is a set of nested dictionaries to describe a production structure (or supply chain).

Example:

from sfctools import Agent, ProductionTree

class MyProduction():
    def __init__(self,x):


my_agent_a = MyProduction("A")
my_agent_b = MyProdution("B")
my_agent_y = MyProduction("Y")

production_dict = {
        "CES_1": {"epsilon": 1.0, "alpha": [0.5,0.3,0.2]}, #...
        }

data =  {"Y;CES_1":
            {"A": {},
             "B": {}}

agent_name_dict = {
                "A": [my_agent_a],
                "B": [my_agent_b],
                "Y": [my_agent_y]
            }

my_production_tree = ProductionTree(production_dict,data,agent_name_dict)

constructor for production tree

Parameters
  • production_dict – stores production function names (str) as keys, and dicts of productino function parameters as values

  • data – a nested structure of goods and their production functions, separated by ‘;’ in the keys (see example)

  • agent_name_dict – A dictionary where the keys are the goods and the values are lists of agents. If None (default), dummy instances will be placed here

count = 0
detailed_data

one with the aggregate production tree and one detailed (unfolded one)

Type

This will create two trees

init_nodes(subject)

send production_dict to the nodes for initialization

Parameters

subject – subject for initalization trigger

plot(mode='aggregate', with_labels=True, param_name='sigma', nodecolor='mediumslateblue', show_plot=True)

generates a plot of the tree structure :param mode: ‘detailed’ or ‘aggregate’ :param param_name: name of the production function parameter to search for (default ‘sigma’, i.e. elasticity) :param nodecolor: color of the nodes of the tree :param show_plot: if True, window opens. if False, figure is returned only

Return fig

matplotlib figure

property root

returns the root node of the (unfolded) tree structure.

to_str(mode='aggregate')

returns a string representation of the production tree :param mode: ‘detailed’ or ‘aggregate’

traverse(subject, direction='up')

traverse the tree struct and execute production nodes on the way. -> Breadth-first search

Parameters
  • subject – the subject carried with the traversal signal

  • direction – the direction of the trigger signal (traversal is as in nx.bfs)

traverse_nodes(subject)

traverse the tree struct nodes

Parameters

subject – the subject carried with the traversal signal

sfctools.bottomup.productiontree.dict_depth(d)

helper function to get the depth of a nested dict

sfctools.bottomup.productiontree.extract_production_info(tree, production_dict, agent_name_dict)

extracts relevant production parameters from production_dict and agent_name_dict, see ProductionTree class for more information.

sfctools.bottomup.productiontree.full_tree_pos(G)
sfctools.bottomup.productiontree.recursive_items(dictionary)
sfctools.bottomup.productiontree.tree_to_coords(tree, rec=0, data=None, linedata=None, style='tree')

makes plotting data for a tree

Parameters
  • tree – a dict of dicts

  • style – ‘tree’ or ‘vertical’ or ‘horizontal’

  • data – recursion parameter, do not change

  • rec – recursion parameter, recursion depth, do not change

Return strtree

str, tree in string representation

sfctools.bottomup.productiontree.tree_to_str(tree, rec=0, strtree='', style='tree')

prints a tree structure (nested dict) as str

Parameters
  • tree – a dict of dicts

  • style – ‘tree’ or ‘vertical’ or ‘horizontal’

  • strtree – recursion parameter, do not change

  • rec – recursion parameter, recursion depth, do not change

Return strtree

str, tree in string representation

sfctools.bottomup.productiontree.unfold_tree(tree, agent_name_dict)

iterates through production tree and ‘unfolds it’ by inserting the appropriate agent names

Signals and Slots

class sfctools.datastructs.signalslot.Signal(name, asynchronous=False)

Bases: object

Signal is the emitter of an information stream

This is a basic signal.

Parameters
  • name – name of the signal

  • asyncronous – check_up_to_date will return True always if this is set to True

check_up_to_date()

checks if the signal is up to date, i.e. if the signal has been filled with a value in the current time step

connect_to(list_of_slots)

slots connected

Parameters

list_of_slots – a list of slots to connect to this signal

emit(verbose=False)

emit the signal to all connected slots

Parameters

verbose – enables verbose mode (default False)

classmethod retrieve(name)

find a certain signal by name

Parameters

name – name of the signal

Returns

Signal

rlch()

get relative change since last update

update(value)

insert latest value

Param

value

value()

get current value

class sfctools.datastructs.signalslot.SignalSlot(name, asynchronous=False)

Bases: object

A connection including a signal and slot

Parameters
  • name – name of the signal-slot connection

  • asynchronous – is the signal triggered in every simulation period?

trigger()

Trigger of this connection. Emits the signal to the slot.

class sfctools.datastructs.signalslot.Slot(name, asynchronous=False)

Bases: object

Slot is the receiver of an information stream

This is a slot. :param name: name of the slot :param asynchronous:

check_up_to_date()

checks if the slot is up to date, i.e. if the data has been filled with a value in the current time step

receive(signal, verbose=False)

slot receives a signal

Parameters
  • signal – a Signal instance who triggered this slot to receive

  • verbose – enables verbose mode (default False)

classmethod retrieve(name)

find a certain slot by name

Parameters

name – name of the slot

Returns

Slot

rlch()

get relative change since last update

value()

get current value