Пример #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
Пример #2
0
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
Пример #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
Пример #4
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'])
Пример #5
0
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)

start = time.time()
data, tensor_field, sessions = simulation.execute()
Пример #6
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)
Пример #7
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)
Пример #8
0
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({
#     "T": range(100),
#     "N": 1,
#     'M': params
Пример #9
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)
            "p2": p2m3
        },
        "variables": variables
    }
}

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

exp = Experiment()
exp.append_configs(
    sim_configs=sim_config,
    initial_state=genesis_states,
    partial_state_update_blocks=psubs,
    policy_ops=[lambda a, b: a + b,
                lambda y: y * 2]  # Default: lambda a, b: a + b
)

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

raw_result, tensor_field, sessions = run.execute()
result = pd.DataFrame(raw_result)

print()
print("Tensor Field:")
print(tabulate(tensor_field, headers='keys', tablefmt='psql'))
print("Output:")
Пример #11
0
from cadCAD.configuration import Experiment
from cadCAD.configuration.utils import config_sim
from .state_variables import initial_state
from .partial_state_update_block import partial_state_update_block
from .sys_params import params

sim_config = config_sim({
    'N': 1,  # number of monte carlo runs
    'T': range(
        1000),  # number of timesteps - 147439 is the length of uniswap_events
    'M': params,  # simulation parameters
})

exp = Experiment()

exp.append_configs(sim_configs=sim_config,
                   initial_state=initial_state,
                   partial_state_update_blocks=partial_state_update_block)
Пример #12
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
Пример #13
0
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.
    '''

    return sim_config, state_variables, partial_state_update_blocks
import json, pathlib, pandas as pd

from cadCAD import configs
from cadCAD.configuration import Experiment
from cadCAD.engine import ExecutionMode, ExecutionContext, Executor
from testing.models import param_sweep, policy_aggregation


del configs[:]
exp = Experiment()
sys_model_A_id = "sys_model_A"
exp.append_configs(
    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_configs(
    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_configs(
    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
)
Пример #15
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])