Exemple #1
0
def run_simulation(c: CommonsSimulationConfiguration):
    initial_conditions, simulation_parameters = bootstrap_simulation(c)

    exp = Experiment()
    exp.append_configs(
        initial_state=initial_conditions,
        partial_state_update_blocks=partial_state_update_blocks,
        sim_configs=simulation_parameters
    )

    # Do not use multi_proc, breaks ipdb.set_trace()
    exec_mode = ExecutionMode()
    single_proc_context = ExecutionContext(exec_mode.local_mode)
    executor = Executor(single_proc_context, configs)

    raw_system_events, tensor_field, sessions = executor.execute()

    df = pd.DataFrame(raw_system_events)
    df_final = df[df.substep.eq(2)]

    result = {
        "timestep": list(df_final["timestep"]),
        "funding_pool": list(df_final["funding_pool"]),
        "token_supply": list(df_final["token_supply"]),
        "collateral": list(df_final["collateral_pool"]),
        "sentiment": list(df_final["sentiment"])
    }
    return result, df_final
def run(initial_state, partial_state_update_block, sim_configs):
    exp = Experiment()
    exp.append_configs(initial_state=initial_state,
                       partial_state_update_blocks=partial_state_update_block,
                       sim_configs=sim_configs)

    # Do not use multi_proc, breaks ipdb.set_trace()
    exec_mode = ExecutionMode()
    single_proc_context = ExecutionContext(exec_mode.single_proc)
    executor = Executor(single_proc_context, configs)

    raw_system_events, tensor_field, sessions = executor.execute()

    df = pd.DataFrame(raw_system_events)

    return df
Exemple #3
0
def run_simulation(c: CommonsSimulationConfiguration):
    initial_conditions, simulation_parameters = bootstrap_simulation(c)

    exp = Experiment()
    exp.append_configs(initial_state=initial_conditions,
                       partial_state_update_blocks=partial_state_update_blocks,
                       sim_configs=simulation_parameters)

    # Do not use multi_proc, breaks ipdb.set_trace()
    exec_mode = ExecutionMode()
    single_proc_context = ExecutionContext(exec_mode.local_mode)
    executor = Executor(single_proc_context, configs)

    raw_system_events, tensor_field, sessions = executor.execute()

    df = pd.DataFrame(raw_system_events)
    return df
Exemple #4
0
from cadCAD.configuration import Experiment

exp = Experiment()
Exemple #5
0
}
env_processes = {}
"""
Exogenous Processes
update price, timestamp, block
"""
ts_format = '%Y-%m-%d %H:%M:%S'
t_delta = timedelta(days=7, minutes=0, seconds=0)


def time_model(_g, step, sL, s, _input):
    x = ep_time_step(s,
                     dt_str=s['timestamp'],
                     fromat_str=ts_format,
                     _timedelta=t_delta)
    return ('timestamp', x)


raw_exogenous_states = {'timestamp': time_model}

env_processes = {}

exp = Experiment()
exp.append_configs(
    sim_configs=sim_config,
    initial_state=genesis_states,
    seeds=seeds,
    # raw_exogenous_states=raw_exogenous_states,
    env_processes=env_processes,
    partial_state_update_blocks=partial_state_update_block)
Exemple #6
0
from cadCAD.configuration.utils import config_sim

from .psub import psubs
from .state import genesis_state
from .sys_params import params
from .sim_setup import SIMULATION_TIME_STEPS, MONTE_CARLO_RUNS

# Parameters
# Values are lists because they support sweeping.
simulation_config = config_sim({
        'N': MONTE_CARLO_RUNS, 
        'T': range(SIMULATION_TIME_STEPS), # number of timesteps
        'M': params,
})

exp = Experiment()

exp.append_configs(sim_configs=simulation_config,
                   initial_state=genesis_state,
                   partial_state_update_blocks=psubs)


# from cadCAD import configuration

# from .psub import psubs
# from .state import genesis_state
# from .sys_params import params

# # Parameters
# # Values are lists because they support sweeping.
# simulation_config = configuration.utils.config_sim({
Exemple #7
0
MONTE_CARLO_RUNS = 1  # N monte carlo runs

from cadCAD.configuration import Experiment
from cadCAD.configuration.utils import config_sim
from .model.state_variables import genesis_states
from .model.partial_state_update_block import partial_state_update_block
from .model.sys_params import sys_params as sys_params
from .sim_params import SIMULATION_TIME_STEPS

sim_config = config_sim({
    'N': MONTE_CARLO_RUNS,
    'T': range(SIMULATION_TIME_STEPS),  # number of timesteps
    'M': sys_params,
})

exp = Experiment()

exp.append_configs(model_id='sys_model',
                   sim_configs=sim_config,
                   initial_state=genesis_states,
                   partial_state_update_blocks=partial_state_update_block)
Exemple #8
0
from cadCAD.configuration import Experiment

system_model_AB_exp = Experiment()
Exemple #9
0
        }
    },
    "m3": {
        "policies": {
            "b1": p1m3,
            "b2": p2m3
        },
        "states": {
            "s1": s1m3,
            "s2": s2m3
        }
    }
}

sim_config_dict = {
        "N": 3,
        "T": range(5),
}


sim_config = config_sim(sim_config_dict)

exp = Experiment()
exp.append_model(
    model_id='sys_model_1',
    sim_configs=sim_config,
    initial_state=genesis_states,
    env_processes=env_processes,
    partial_state_update_blocks=partial_state_update_block
)
Exemple #10
0
        "policies": {
            "b1": p1m2,
            # "b2": p2m2
        },
        "states": {
            "s1": s1m2,
            # "s2": s2m2
        }
    },
    {
        "policies": {
            "b1": p1m3,
            "b2": p2m3
        },
        "states": {
            "s1": s1m3,
            "s2": s2m3
        }
    }
]

sim_config = config_sim({
    "N": 2,
    "T": range(5),
})

exp = Experiment()
exp.append_configs(sim_configs=sim_config,
                   initial_state=genesis_states,
                   env_processes=env_processes,
                   partial_state_update_blocks=psubs)
import json
import os
import unittest, pandas as pd
from cadCAD.configuration import Experiment
from cadCAD.engine import ExecutionMode, ExecutionContext, Executor
from testing.models import param_sweep, policy_aggregation

exp = Experiment()
sys_model_A_id = "sys_model_A"
exp.append_model(
    model_id=sys_model_A_id,
    sim_configs=param_sweep.sim_config,
    initial_state=param_sweep.genesis_states,
    env_processes=param_sweep.env_process,
    partial_state_update_blocks=param_sweep.partial_state_update_blocks
)
sys_model_B_id = "sys_model_B"
exp.append_model(
    model_id=sys_model_B_id,
    sim_configs=param_sweep.sim_config,
    initial_state=param_sweep.genesis_states,
    env_processes=param_sweep.env_process,
    partial_state_update_blocks=param_sweep.partial_state_update_blocks
)
sys_model_C_id = "sys_model_C"
exp.append_model(
    model_id=sys_model_C_id,
    sim_configs=policy_aggregation.sim_config,
    initial_state=policy_aggregation.genesis_states,
    partial_state_update_blocks=policy_aggregation.partial_state_update_block,
    policy_ops=[lambda a, b: a + b, lambda y: y * 2] # Default: lambda a, b: a + b
Exemple #12
0
    'last_x': [],
    '2nd_to_last_x': [],
    '3rd_to_last_x': [],
    '4th_to_last_x': []
}

PSUB = {"policies": policies, "variables": variables}

psubs = {"PSUB1": PSUB, "PSUB2": PSUB, "PSUB3": PSUB}

sim_config = config_sim({
    "N": 1,
    "T": range(3),
})

exp = Experiment()
exp.append_model(model_id='hist_state_access',
                 sim_configs=sim_config,
                 initial_state=genesis_states,
                 partial_state_update_blocks=psubs)

exec_mode = ExecutionMode()
local_proc_ctx = ExecutionContext(context=exec_mode.local_mode)
run = Executor(exec_context=local_proc_ctx, configs=exp.configs)

raw_result, tensor_field, sessions = run.execute()
result = pd.DataFrame(raw_result)
cols = [
    'run', 'substep', 'timestep', 'x', 'nonexsistant', 'last_x',
    '2nd_to_last_x', '3rd_to_last_x', '4th_to_last_x'
]
from .state_variables import state_variables
from .partial_state_update_block import partial_state_update_blocks
from .parts.sys_params import *
from .parts.utils import *

sim_config = config_sim({
    'T': range(100),  #day 
    'N': 1,
    'M': params,
})

seeds = {
    'p': np.random.RandomState(1),
}

exp = Experiment()

exp.append_configs(sim_configs=sim_config,
                   initial_state=state_variables,
                   seeds=seeds,
                   partial_state_update_blocks=partial_state_update_blocks)

# Initialize network x
config_initialization(configs, initial_values)


def get_configs():
    '''
    Function to extract the configuration information for display in a notebook.
    '''
psu_block = {k: {"policies": {}, "variables": {}} for k in psu_steps}
for m in psu_steps:
    psu_block[m]['policies']['gamma'] = gamma
    psu_block[m]['policies']['omega'] = omega
    psu_block[m]["variables"]['alpha'] = alpha_plus_gamma
    psu_block[m]["variables"]['alpha_plus_gamma'] = alpha
    psu_block[m]["variables"]['beta'] = beta
    psu_block[m]['variables']['policies'] = policies
    psu_block[m]["variables"]['sweeped'] = var_timestep_trigger(y='sweeped', f=sweeped)

psubs = psub_list(psu_block, psu_steps)
print()
pp.pprint(psu_block)
print()

exp = Experiment()
exp.append_model(
    model_id='param_sweep',
    sim_configs=sim_config,
    initial_state=genesis_states,
    env_processes=env_process,
    partial_state_update_blocks=psubs
)

exec_mode = ExecutionMode()
local_proc_ctx = ExecutionContext(context=exec_mode.local_mode)
run = Executor(exec_context=local_proc_ctx, configs=exp.configs)

raw_result, tensor_field, sessions = run.execute()
result = pd.DataFrame(raw_result)
print()
from cadCAD.configuration import Experiment

multi_exp = Experiment()
Exemple #16
0
            "b2": p2m3
        },
        "states": {
            "s1": s1m3,
            "s2": s2m3
        }
    }
}

sim_config_dict = {
    "N": 3,
    "T": range(5),
}

sim_config = config_sim(sim_config_dict)

exp = Experiment()
exp.append_model(
    # config_list=configs,
    user_id='user_b',
    sim_configs=sim_config,
    initial_state=genesis_states,
    env_processes=env_processes,
    partial_state_update_blocks=partial_state_update_block)

multi_exp.append_model(model_id='sys_model_2',
                       sim_configs=sim_config,
                       initial_state=genesis_states,
                       env_processes=env_processes,
                       partial_state_update_blocks=partial_state_update_block)
Exemple #17
0
            "s2": s2m2,
            # "s3": es3p1,
            # "s4": es4p2,
        }
    },
    {
        "policies": {
            "b1": p1m3,
            "b2": p2m3
        },
        "variables": {
            "s1": s1m3,
            "s2": s2m3,
            # "s3": es3p1,
            # "s4": es4p2,
        }
    }
]

sim_config_dict = {"N": 1, "T": range(5)}

sim_config = config_sim(sim_config_dict)

exp = Experiment()
exp.append_model(model_id='sys_model_1',
                 sim_configs=sim_config,
                 initial_state=genesis_states,
                 env_processes=env_processes,
                 partial_state_update_blocks=partial_state_update_block,
                 policy_ops=[lambda a, b: a + b])
Exemple #18
0
def easy_run(state_variables,
             params,
             psubs,
             N_timesteps,
             N_samples,
             use_label=False,
             assign_params=True,
             drop_substeps=True) -> pd.DataFrame:
    """
    Run cadCAD simulations without headaches.
    """

    simulation_parameters = {
        'N': N_samples,
        'T': range(N_timesteps),
        'M': params
    }

    sim_config = config_sim(simulation_parameters)

    from cadCAD import configs
    del configs[:]

    exp = Experiment()
    exp.append_configs(sim_configs=sim_config,
                       initial_state=state_variables,
                       partial_state_update_blocks=psubs)

    from cadCAD import configs
    exec_mode = ExecutionMode()
    exec_context = ExecutionContext(exec_mode.local_mode)
    executor = Executor(exec_context=exec_context, configs=configs)
    (records, tensor_field, _) = executor.execute()

    df = pd.DataFrame(records)

    if drop_substeps == True:
        # Drop all intermediate substeps
        first_ind = (df.substep == 0) & (df.timestep == 0)
        last_ind = df.substep == max(df.substep)
        inds_to_drop = (first_ind | last_ind)
        df = df.loc[inds_to_drop].drop(columns=['substep'])
    else:
        pass

    if assign_params == False:
        pass
    else:
        M_dict = configs[0].sim_config['M']
        params_set = set(M_dict.keys())

        # Logic for getting the assign params criteria
        if type(assign_params) is list:
            selected_params = set(assign_params) & params_set
        elif type(assign_params) is set:
            selected_params = assign_params & params_set
        else:
            selected_params = params_set

        # Attribute parameters to each row
        df = df.assign(**select_config_M_dict(configs, 0, selected_params))
        for i, (_, n_df) in enumerate(df.groupby(['simulation', 'subset', 'run'])):
            df.loc[n_df.index] = n_df.assign(**select_config_M_dict(configs,
                                                                    i,
                                                                    selected_params))

    # Based on Vitor Marthendal (@marthendalnunes) snippet
    if use_label == True:
        psub_map = {order + 1: psub.get('label', '')
                    for (order, psub)
                    in enumerate(psubs)}
        psub_map[0] = 'Initial State'
        df['substep_label'] = df.substep.map(psub_map)

    return df
Exemple #19
0
            "s1": s1m2,
            "s2": s2m2,
            # "s3": es3p1,
            # "s4": es4p2,
        }
    },
    {
        "policies": {
            "b1": p1m3,
            "b2": p2m3
        },
        "variables": {
            "s1": s1m3,
            "s2": s2m3,
            # "s3": es3p1,
            # "s4": es4p2,
        }
    }
]

sim_config = config_sim({
    "N": 2,
    "T": range(1),
})

exp = Experiment()
exp.append_configs(sim_configs=sim_config,
                   initial_state=genesis_states,
                   env_processes=env_processes,
                   partial_state_update_blocks=psubs,
                   policy_ops=[lambda a, b: a + b])
    },
    "m2": {
        "policies": {
            "p1": p1m2,
            "p2": p2m2
        },
        "variables": variables
    },
    "m3": {
        "policies": {
            "p1": p1m3,
            "p2": p2m3
        },
        "variables": variables
    }
}

sim_config = config_sim({
    "N": 1,
    "T": range(3),
})

exp = Experiment()
exp.append_model(
    sim_configs=sim_config,
    initial_state=genesis_states,
    partial_state_update_blocks=partial_state_update_block,
    policy_ops=[lambda a, b: a + b,
                lambda y: y * 2]  # Default: lambda a, b: a + b
)
Exemple #21
0
from cadCAD.configuration import Experiment

config1_exp = Experiment()
config2_exp = Experiment()
ext_ds_exp = Experiment()
hist_exp = Experiment()
policy_exp = Experiment()
sweep_exp = Experiment()
udo1_exp = Experiment()
udo2_exp = Experiment()
poc = Experiment()
Exemple #22
0
from cadCAD.configuration import Experiment
from cadCAD.engine import ExecutionMode, ExecutionContext
from cadCAD.engine import Executor

from cadCAD import configs
del configs[:] # Clear any prior configs

config = {
    "N": RUNS,
    "T": range(TIMESTEPS),
    "M": params
}

c = config_sim(config)

exp = Experiment()
exp.append_configs(
    initial_state = states,
    partial_state_update_blocks = psubs,
    sim_configs = c
)

exp.append_configs(
    initial_state = states,
    partial_state_update_blocks = psubs,
    sim_configs = c
)

exec_mode = ExecutionMode()
local_mode_ctx = ExecutionContext(context=exec_mode.local_mode)
simulation = Executor(exec_context=local_mode_ctx, configs=configs)
from cadCAD.configuration import Experiment

exp_param_sweep = Experiment()
exp_policy_agg = Experiment()
Exemple #24
0
from cadCAD.configuration.utils import config_sim
from .state_variables import genesis_states
from .partial_state_update_block import partial_state_update_block
from .sys_params import sys_params
from .parts.utils import AdoptionPool

from copy import deepcopy
from cadCAD import configs

sim_config = config_sim({
    'N': 1,  # number of monte carlo runs
    'T': range(1000),  # number of timesteps
    'M': sys_params,  # system parameters
})

exp = Experiment()

exp.append_configs(sim_configs=sim_config,
                   initial_state=genesis_states,
                   partial_state_update_blocks=partial_state_update_block)

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # GENESIS SWEEP LOGIC # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

for c in configs:  # for each configuration object
    c.initial_state = deepcopy(
        c.initial_state
    )  # make a deepcopy of the initial state dict (it's shared across configs by default)

    c.initial_state['pool'] = AdoptionPool(c.sim_config['M']['SOURCE_POOL'])
Exemple #25
0
import os, dill
from cadCAD.configuration import Experiment

name = "cadCAD"
version = "0.4.28"
experiment = Experiment()
configs = experiment.configs

if os.name == 'nt':
    dill.settings['recurse'] = True

logo = r'''
                  ___________    ____
  ________ __ ___/ / ____/   |  / __ \
 / ___/ __` / __  / /   / /| | / / / /
/ /__/ /_/ / /_/ / /___/ ___ |/ /_/ /
\___/\__,_/\__,_/\____/_/  |_/_____/
by cadCAD
'''