Monte Carlo

Running monte-carlo batches can be done via sfctools as follows

Preparation

create a folder structure which contains an empty ‘testsettings.yml’ in your main folder, and a ‘results/’ sub-folder. Fill the testsettings.yml with the following text

metainfo:
    author: your name here
    date: 2022
    info: example settings

hyperparams:
    - name: param_a
      value: 3.1418
      description: an example parameter

Code

from sfctools.automation.runner import ModelRunner
from sfctools import Settings, World, Agent
import os
import numpy as np
np.random.seed(1235)
import pandas as pd

# run this in the upper directory via pytest tests/, otherwise this will fail
settings_path = os.path.join(os.getcwd(), "testsettings.yml")
results_path = os.path.join(os.getcwd(), "results/")

# run this in the upper directory via pytest tests/, otherwise this will fail

class MyAgent(Agent):
    def __init__(self):
        super().__init__()
        self.a_param = Settings()["param_a"]

    def modify_a(self):
        self.a_param *= np.random.rand()

def builder():
    # placeholder for agent builder,
    my_agents = [MyAgent() for i in range(10)]


def iter(n): # one model iteration, repeated n times
    my_agents = World().get_agents_of_type("MyAgent")

    vals = []
    for i in range(n):
        # write agents' parameters here (just an example)
        [agent.modify_a() for agent in my_agents]
        a_param_vals = [agent.a_param for agent in my_agents]
        vals.append(np.mean(a_param_vals))

    return pd.DataFrame({"Value":vals}) # has to return a dataframe

# create model runner
mr = ModelRunner(settings_path,results_path,builder,iter)
mr.run(10,20)

# read back the output files
with open(os.path.join(results_path, "output.txt"), "r") as file:
    print("1. output.txt:\n ", file.readlines()[:3], "\n")

with open(os.path.join(results_path, "progress.txt"), "r") as file:
    print("2. progress.txt:\n ", file.readlines()[:3], "\n")

with open(os.path.join(results_path, "output.0"), "r") as file:
    print("3. values:\n ", file.readlines()[:3], "\n")

Output

1. output.txt:
['author:your name here\n', 'date:2022\n', 'info:example settings\n']

2. progress.txt:
['2023-06-23 11:44:34.510011\n', '[RUN 0]   ...SUCCESS!\n', '[RUN 1]   ...SUCCESS!\n']

3. values:
['Value\n', '2.070679637235405\n', '1.4007542281108696\n']