def test_simulation_consistency(self):
        """
        Copied from NB1-PoolExploration-0x8b6
        """
        # Spot price reference must be a symbol of a token in the pool in ALL_CAPS, you can ignore the spot price parameter for the simulations in this notebook.
        parameters = {
            'spot_price_reference': ['DAI'],
            'decoding_type': ['SIMPLIFIED']
        }

        initial_values = generate_initial_state(
            initial_values_json=
            '../data/0x8b6e6e7b5b3801fed2cafd4b22b8a16c2f2db21a-initial_pool_states-prices.json',
            spot_price_base_currency=parameters['spot_price_reference'][0])

        result = generate_partial_state_update_blocks(
            '../data/0x8b6e6e7b5b3801fed2cafd4b22b8a16c2f2db21a-actions-prices.json'
        )
        partial_state_update_blocks = result['partial_state_update_blocks']

        steps_number = result['steps_number']
        sim_config = config_sim({
            'N': 1,  # number of monte carlo runs
            'T': range(steps_number - 1),  # number of timesteps
            'M': parameters,  # simulation parameters
        })

        df = run(initial_values, partial_state_update_blocks, sim_config)
        p_df = post_processing(df, include_spot_prices=False)
        p_df_ref = pd.read_pickle(
            "0x8b6-reference-p_df-commit-886b55321957449d6cbf3afafdf57b9e64a8cadb.pickle"
        )
        if not p_df_ref.equals(p_df):
            for i in range(len(p_df)):
                if not p_df_ref.loc[i].equals(p_df.loc[i]):
                    print("Discrepancy starts at timestep", i)
                    refrow = p_df_ref.loc[i]
                    row = p_df.loc[i]
                    print(refrow.compare(row))
                    break
        final_row = len(p_df) - 1
        print("Discrepancy at end of simulation", final_row)
        print(p_df_ref.iloc[final_row].compare(p_df.iloc[final_row]))
Esempio n. 2
0
def test_simulation_dataframe_structure():
    states = basic.states
    state_update_blocks = basic.state_update_blocks
    params = basic.params
    TIMESTEPS = 1000
    RUNS = 1

    model = Model(initial_state=states,
                  state_update_blocks=state_update_blocks,
                  params=params)
    simulation = Simulation(model=model, timesteps=TIMESTEPS, runs=RUNS)
    experiment = Experiment([simulation, simulation, simulation])
    data_radcad = experiment.run()

    df_radcad = pd.DataFrame(data_radcad).drop(['run'], axis=1)

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

    exp = cadCADExperiment()
    exp.append_configs(model_id='a',
                       initial_state=states,
                       partial_state_update_blocks=state_update_blocks,
                       sim_configs=c)
    exp.append_configs(model_id='b',
                       initial_state=states,
                       partial_state_update_blocks=state_update_blocks,
                       sim_configs=c)
    exp.append_configs(model_id='c',
                       initial_state=states,
                       partial_state_update_blocks=state_update_blocks,
                       sim_configs=c)

    exec_mode = ExecutionMode()
    local_mode_ctx = ExecutionContext(context=exec_mode.local_mode)
    simulation = Executor(exec_context=local_mode_ctx, configs=exp.configs)

    data_cadcad, tensor_field, sessions = simulation.execute()
    df_cadcad = pd.DataFrame(data_cadcad).drop(['run'], axis=1)

    assert_frame_equal(df_radcad, df_cadcad)
    assert df_radcad.equals(df_cadcad)
Esempio n. 3
0
from cadCAD.configuration import Experiment
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

sim_config = config_sim({
    'N': 1,  # number of monte carlo runs
    'T': range(
        1060000 - 2
    ),  # number of timesteps - 147439 is the length of uniswap_events 3438 // 899703
    'M': sys_params,  # simulation parameters
})

exp = Experiment()

exp.append_configs(sim_configs=sim_config,
                   initial_state=genesis_states,
                   partial_state_update_blocks=partial_state_update_block)
Esempio n. 4
0
from cadCAD.configuration import Experiment
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)
Esempio n. 5
0
# import libraries
from decimal import Decimal
import numpy as np
from datetime import timedelta
from cadCAD.configuration import append_configs
from cadCAD.configuration.utils import bound_norm_random, ep_time_step, config_sim

seeds = {
    # 'z': np.random.RandomState(1),
    # 'a': np.random.RandomState(2)
}

sim_config = config_sim({
    'T': range(10), #number of discrete iterations in each experiement
    'N': 1, #number of times the simulation will be run (Monte Carlo runs)
    #'M': g #parameter sweep dictionary
})


# define the time deltas for the discrete increments in the model
# ts_format = '%Y-%m-%d %H:%M:%S'
# t_delta = timedelta(days=0, minutes=1, seconds=0)
# def time_model(_g, step, sL, s, _input):
#     y = 'time'
#     x = ep_time_step(s, dt_str=s['time'], fromat_str=ts_format, _timedelta=t_delta)
#     return (y, x)

# Behaviors

# Mechanisms
def update_A(_g, step, sL, s, _input):
Esempio n. 6
0
    's4': 1.0,
    'timestamp': '2018-10-01 15:16:24'
}


# Environment Process
# ToDo: Validate - make env proc trigger field agnostic
env_process["s3"] = [lambda _g, x: _g['beta'], lambda _g, x: x + 1]
env_process["s4"] = env_timestep_trigger(trigger_field='timestep', trigger_vals=[5], funct_list=[lambda _g, x: _g['beta']])


# config_sim Necessary
sim_config = config_sim(
    {
        "N": 1,
        "T": range(5),
        "M": g, # Optional
    }
)

# New Convention
partial_state_update_blocks = psub_list(psu_block, psu_steps)
append_configs(
    # user_id='user_a',
    sim_configs=sim_config,
    initial_state=genesis_states,
    seeds=seeds,
    env_processes=env_process,
    partial_state_update_blocks=partial_state_update_blocks
)
Esempio n. 7
0
from cadCAD.configuration import Experiment
from cadCAD.configuration.utils import config_sim
from .state_variables import genesis_states
from .partial_state_update_block import PSUBs
from .sys_params import sys_params as sys_params
from .sim_params import *

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

exp = Experiment()
exp.append_configs(
    sim_configs=sim_config,
    initial_state=genesis_states,
    partial_state_update_blocks=PSUBs
)
    },
    "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
)
Esempio n. 9
0
# import libraries
from decimal import Decimal
import numpy as np
from datetime import timedelta
from cadCAD.configuration import append_configs
from cadCAD.configuration.utils import proc_trigger, bound_norm_random, ep_time_step, config_sim

seeds = {
    # 'z': np.random.RandomState(1),
    # 'a': np.random.RandomState(2)
}

sim_config = config_sim({
    'T': range(360),  #number of discrete iterations in each experiement
    'N': 1,  #number of times the simulation will be run (Monte Carlo runs)
})

# parameters (later add tuning)
eta = .04  # for tx_volume_generator
tampw = 10000  # transactions limit
alpha = .5  # for data acquisition cost
beta = .2  # for data acquisition cost
cost = 2.5
periodInvestment = 1000


# external states
#cell defines the model function for the tx_volume generator stochastic process
def tx_volume_generator(_g, step, sL, s, _input):
    y = 'tx_volume'
    x = s['tx_volume'] * (1 + 2 * eta * np.random.rand() *
Esempio n. 10
0
import unittest
from cadCAD.configuration.utils import config_sim

val_error_indicator = False
try:
    sim_config = config_sim(
        {
            "N": 0,
            "T": range(5)
        }
    )
except ValueError:
    val_error_indicator = True


class RunExceptionTest(unittest.TestCase):
    def test_multi_model(self):
        self.assertEqual(val_error_indicator, True, "ValueError raised when runs (N) < 1")


if __name__ == '__main__':
    unittest.main()
Esempio n. 11
0
    },
    {
        "policies": {
            "b1": p1m3,
            "b2": p2m3
        },
        "variables": {
            "s1": s1m3,
            "s2": s2m3,
            # "s3": es3p1,
            # "s4": es4p2,
        }
    }
]


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

append_configs(
    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]
)
Esempio n. 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
Esempio n. 13
0
def simulate(
        network: Network,
        parameters: SimulationParameters,
        observers: Dict[str, Callable[[BeaconState],
                                      Any]] = {}) -> pd.DataFrame:
    """
    Args:
        network (Network): Network of :py:class:`beaconrunner.validatorlib.BRValidator`
        parameters (BRSimulationParameters): Simulation parameters

    Returns:
        pandas.DataFrame: Results of the simulation contained in a pandas data frame
    """

    initial_conditions = {'network': network}

    psubs = [
        {
            'policies': {
                'action': attest_policy  # step 1
            },
            'variables': {
                'network': update_attestations  # step 2
            }
        },
        {
            'policies': {
                'action': chunk_response_policy  # step 3
            },
            'variables': {
                'network': update_chunk_responses  # step 4
            }
        },
        {
            'policies': {
                'action': bit_challenge_policy  # step 3
            },
            'variables': {
                'network': update_bit_challenges  # step 4
            }
        },
        {
            'policies': {
                'action': propose_policy  # step 3
            },
            'variables': {
                'network': update_blocks  # step 4
            }
        },
        {
            'policies': {},
            'variables': {
                'network': tick  # step 5
            }
        },
    ]

    # Determine how many steps the simulation is running for
    num_slots = parameters.num_epochs * SLOTS_PER_EPOCH
    steps = num_slots * SECONDS_PER_SLOT * parameters.frequency

    simulation_parameters = {
        'T': range(steps),
        'N': 1,
        'M': {
            "frequency": [parameters.frequency],
            "network_update_rate": [parameters.network_update_rate],
        }
    }

    print("will simulate", parameters.num_epochs, "epochs (", num_slots,
          "slots ) at frequency", parameters.frequency, "moves/second")
    print("total", steps, "simulation steps")

    # Add our observers to the simulation
    observed_ic = add_loop_ic(
        get_observed_initial_conditions(initial_conditions, observers))
    observed_psubs = add_loop_psubs(get_observed_psubs(psubs, observers))

    # Final simulation parameters and execution
    configs = []
    for sim_param in config_sim(simulation_parameters):
        config = Configuration(sim_param,
                               initial_state=observed_ic,
                               partial_state_update_blocks=observed_psubs)
        configs.append(config)

    exec_mode = ExecutionMode()
    single_proc_ctx = ExecutionContext(context=exec_mode.single_proc)
    run = Executor(exec_context=single_proc_ctx, configs=configs)
    raw_result, tensor_field = run.execute()

    return pd.DataFrame(raw_result).assign(run=parameters.num_run)
Esempio n. 14
0
# import libraries
from decimal import Decimal
import numpy as np
from datetime import timedelta
from cadCAD.configuration import append_configs
from cadCAD.configuration.utils import bound_norm_random, ep_time_step, config_sim

seeds = {}

sim_config = config_sim({'T': range(10), 'N': 1})


# Behaviors
def robot_arm(_g, step, sL, s):
    add_to_A = 0
    if (s['box_A'] > s['box_B']):
        add_to_A = -1
    elif (s['box_A'] < s['box_B']):
        add_to_A = 1
    return ({'add_to_A': add_to_A, 'add_to_B': -add_to_A})


# Mechanisms
def increment_A(_g, step, sL, s, _input):
    y = 'box_A'
    x = s['box_A'] + _input['add_to_A']
    return (y, x)


def increment_B(_g, step, sL, s, _input):
    y = 'box_B'
from datetime import timedelta
import numpy as np
from typing import Dict, List

from cadCAD.configuration import Experiment
from cadCAD.configuration.utils import bound_norm_random, ep_time_step, config_sim, access_block
from copy import deepcopy
from cadCAD import configs
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
Esempio n. 16
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)
Esempio n. 17
0
genesis_states = {
    's1': 0.0,
    's2': 0.0,
    's3': 1.0,
    's4': 1.0,
    'timestamp': '2018-10-01 15:16:24'
}

# Environment Process
env_process["s3"] = [lambda _g, x: _g['beta'], lambda _g, x: x + 1]
env_process["s4"] = env_timestep_trigger(trigger_field='timestep',
                                         trigger_vals=[5],
                                         funct_list=[lambda _g, x: _g['beta']])

# config_sim Necessary
sim_config = config_sim({
    "N": 5,
    "T": range(2),
    "M": g,  # Optional
})

# New Convention
partial_state_update_blocks = psub_list(psu_block, psu_steps)
sweep_exp.append_configs(
    # user_id='user_a',
    sim_configs=sim_config,
    initial_state=genesis_states,
    seeds=seeds,
    env_processes=env_process,
    partial_state_update_blocks=partial_state_update_blocks)
Esempio n. 18
0
from cadCAD.configuration.utils import config_sim
from cadCAD.configuration import Experiment

from model.state_variables import initial_states
from model.sys_params import sys_params
from model.sys_params import CONTRIBUTIONS_SEQUENCE
from model.partial_state_update_block import partial_state_update_blocks

sim_params = {'N': 1, 'T': range(len(CONTRIBUTIONS_SEQUENCE)), 'M': sys_params}

sim_config = config_sim(sim_params)

exp = Experiment()
exp.append_configs(sim_configs=sim_config,
                   initial_state=initial_states,
                   partial_state_update_blocks=partial_state_update_blocks)
Esempio n. 19
0
from cadCAD.configuration import Experiment
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 

sim_config = config_sim (
    {
        'N': 5, # number of monte carlo runs
        'T': range(300), # number of timesteps
        'M': sys_params, # simulation parameters
    }
)

exp = Experiment()

exp.append_configs(
    sim_configs=sim_config,
    initial_state=genesis_states,
    partial_state_update_blocks=partial_state_update_block
)
Esempio n. 20
0
def cadcad():
    try:
        n = getInteger('participants')  #initial participants
        m = getInteger('proposals')  #initial proposals

        alpha = getFloat('alpha')
        beta = getFloat('beta')

        exit_tribute = getFloat('exit_tribute')
        theta = getFloat('theta')

        initial_sentiment = 0.1  # getFloat('initial_sentiment')
        hatch_price = 0.1  # getFloat('hatch_price')
        kappa = 6  # getFloat('kappa')
        rho = 0.05  # getFloat('rho')

    except Exception as err:
        return str(err), 422

    #initializer
    network, initial_supply, total_requested = initialize_network(n, m)

    initial_funds = total_funds_given_total_supply(initial_supply, theta,
                                                   hatch_price)

    initial_reserve, invariant, starting_price = initialize_bonding_curve(
        initial_supply, initial_price=hatch_price, kappa=kappa, theta=theta)

    initial_conditions = {
        'supply': initial_supply,
        'funds': initial_funds,
        'reserve': initial_reserve,
        'spot_price': starting_price,
        'sentiment': initial_sentiment,
        'network': network
    }

    def trigger_threshold(requested, funds, supply, beta=beta, rho=rho):

        share = requested / funds
        if share < beta:
            return rho * supply / (beta - share)**2
        else:
            return np.inf

    params = {
        'sensitivity': [.75],
        'tmin':
        [7],  #unit days; minimum periods passed before a proposal can pass
        'min_supp': [
            50
        ],  #number of tokens that must be stake for a proposal to be a candidate
        'sentiment_decay': [.01],  #termed mu in the state update function
        'alpha': [alpha],
        'base_completion_rate': [100],
        'base_failure_rate': [200],
        'trigger_func': [trigger_threshold],
        'kappa': [kappa],  #bonding curve curvature
        'invariant': [invariant],  #set by bonding curve choices
        'tax_rate': [exit_tribute]
    }

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    # Settings of general simulation parameters, unrelated to the system itself
    # `T` is a range with the number of discrete units of time the simulation will run for;
    # `N` is the number of times the simulation will be run (Monte Carlo runs)
    time_periods_per_run = 100
    monte_carlo_runs = 1

    from cadCAD.configuration.utils import config_sim
    simulation_parameters = config_sim({
        'T': range(time_periods_per_run),
        'N': monte_carlo_runs,
        'M': params
    })

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    # The Partial State Update Blocks
    partial_state_update_blocks = [
        {
            'policies': {
                #new proposals or new participants
                'random': driving_process
            },
            'variables': {
                'network': update_network,
                'funds': increment_funds,
                'supply': increment_supply,
                'reserve': increment_reserve
            }
        },
        {
            'policies': {
                'completion':
                check_progress  #see if any of the funded proposals completes
            },
            'variables':
            {  # The following state variables will be updated simultaneously
                'sentiment':
                update_sentiment_on_completion,  #note completing decays sentiment, completing bumps it
                'network': complete_proposal  #book-keeping
            }
        },
        {
            'policies': {
                'release':
                trigger_function  #check each proposal to see if it passes
            },
            'variables':
            {  # The following state variables will be updated simultaneously
                'funds': decrement_funds,  #funds expended
                'sentiment':
                update_sentiment_on_release,  #releasing funds can bump sentiment
                'network':
                update_proposals  #reset convictions, and participants sentiments
                #update based on affinities
            }
        },
        {
            'policies': {
                #currently naive decisions; future: strategic
                'participants_act':
                participants_decisions,  #high sentiment, high affinity =>buy
                #low sentiment, low affinities => burn
                #assign tokens to top affinities
            },
            'variables': {
                'supply':
                update_supply,  #book-keeping from participants decisions
                'reserve': update_reserve,  #funds under the bonding curve
                'spot_price': update_price,  #new bonding curve spot price
                'funds': update_funds,  #capture taxes
                'network': update_tokens  #update everyones holdings
                #and their conviction for each proposal
            }
        }
    ]

    from cadCAD import configs
    configs.clear()

    from cadCAD.configuration import append_configs
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    # The configurations above are then packaged into a `Configuration` object
    append_configs(
        initial_state=
        initial_conditions,  #dict containing variable names and initial values
        partial_state_update_blocks=
        partial_state_update_blocks,  #dict containing state update functions
        sim_configs=simulation_parameters  #dict containing simulation parameters
    )

    from tabulate import tabulate
    from cadCAD.engine import ExecutionMode, ExecutionContext, Executor
    from cadCAD import configs
    import pandas as pd

    exec_mode = ExecutionMode()
    multi_proc_ctx = ExecutionContext(context=exec_mode.multi_proc)
    run = Executor(exec_context=multi_proc_ctx, configs=configs)

    i = 0
    verbose = False
    results = {}
    for raw_result, tensor_field in run.execute():
        result = pd.DataFrame(raw_result)
        if verbose:
            print()
            print(f"Tensor Field: {type(tensor_field)}")
            print(tabulate(tensor_field, headers='keys', tablefmt='psql'))
            print(f"Output: {type(result)}")
            print(tabulate(result, headers='keys', tablefmt='psql'))
            print()
        results[i] = {}
        results[i]['result'] = result
        results[i]['simulation_parameters'] = simulation_parameters[i]
        i += 1

    for ind in range(len(results)):
        r = results[ind]['result']
        #print(results[ind]['simulation_parameters'])
        r.plot(x='timestep', y='funds')
        plt.savefig('static/plot8-' + str(ind) + '.png')
        plt.clf()

        fig, ax1 = plt.subplots()
        ax2 = ax1.twinx(
        )  # instantiate a second axes that shares the same x-axis
        df = r
        rdf = df[df.substep == 4].copy()

        rdf.plot(x='timestep', y=['funds', 'reserve', 'supply'], ax=ax1)
        rdf.plot(x='timestep',
                 y='spot_price',
                 style='--',
                 color='red',
                 ax=ax2,
                 legend=False)
        ax2.set_ylabel('Price in xDAI per Token', color='red')
        ax1.set_ylabel('Quantity of Assets')
        ax2.tick_params(axis='y', labelcolor='red')
        plt.title('Summary of Local Economy')
        plt.savefig('static/plot9-' + str(ind) + '.png')
        plt.clf()

    return jsonify({'results': ['plot8-0.png', 'plot9-0.png']})
Esempio n. 21
0
from cadCAD.configuration.utils import config_sim
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()
Esempio n. 22
0
from cadCAD.configuration import Experiment
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.
Esempio n. 23
0
    "m2": {
        "policies": {
            "b1": p1m2,
            # "b2": p2m2
        },
        "states": {
            "s1": s1m2,
            # "s2": s2m2
        }
    },
    "m3": {
        "policies": {
            "b1": p1m3,
            "b2": p2m3
        },
        "states": {
            "s1": s1m3,
            "s2": s2m3
        }
    }
}

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

append_configs(sim_configs=sim_config,
               initial_state=genesis_states,
               env_processes=env_processes,
               partial_state_update_blocks=partial_state_update_block)
Esempio n. 24
0
import pandas as pd

from cadCAD.configuration.utils import config_sim
from cadCAD.configuration import Experiment as cadCADExperiment
from cadCAD.engine import ExecutionMode, ExecutionContext
from cadCAD.engine import Executor
from cadCAD import configs

from tests.test_cases import benchmark_model

states = benchmark_model.states
state_update_blocks = benchmark_model.state_update_blocks
params = benchmark_model.params
TIMESTEPS = 100_000
RUNS = 5

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

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

exec_mode = ExecutionMode()
local_mode_ctx = ExecutionContext(context=exec_mode.local_mode)
simulation = Executor(exec_context=local_mode_ctx, configs=configs)

if __name__ == "__main__":
    results, _, _ = simulation.execute()
    assert len(results) > 0
Esempio n. 25
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_dict = {"N": 1, "T": range(5)}

sim_config = config_sim(sim_config_dict)

append_configs(config_list=configs,
               user_id='user_a',
               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])
Esempio n. 26
0
import math
from decimal import Decimal
from datetime import timedelta
import numpy as np
from typing import Dict, List

from cadCAD.configuration import Experiment
from cadCAD.configuration.utils import bound_norm_random, ep_time_step, config_sim, access_block

from .genesis_states import genesis_states
from .partial_state_update_block import partial_state_update_blocks

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

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

exp = Experiment()

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


def get_configs():
    '''
    return 'policies', _input


external_data = {'ds1': None, 'ds2': None, 'ds3': None}
state_dict = {
    'increment': 0,
    'external_data': external_data,
    'policies': external_data
}

policies = {"p1": p1, "p2": p2}
states = {
    'increment': increment,
    'external_data': integrate_ext_dataset,
    'policies': view_policies
}
PSUB = {'policies': policies, 'states': states}

# needs M1&2 need behaviors
partial_state_update_blocks = {'PSUB1': PSUB, 'PSUB2': PSUB, 'PSUB3': PSUB}

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

append_configs(sim_configs=sim_config,
               initial_state=state_dict,
               partial_state_update_blocks=partial_state_update_blocks,
               policy_ops=[lambda a, b: {
                   **a,
                   **b
               }])
Esempio n. 28
0
MONTE_CARLO_RUNS = 5  # N monte carlo runs

from cadCAD.configuration import append_configs
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': 1,
    'T': range(SIMULATION_TIME_STEPS),  # number of timesteps
    'M': sys_params,
})
append_configs(sim_configs=sim_config,
               initial_state=genesis_states,
               partial_state_update_blocks=partial_state_update_block)
Esempio n. 29
0
    'sentiment_decay': [.001],  #termed mu in the state update function
    'alpha': [0.5],
    'base_completion_rate': [10],
    'trigger_func': [trigger_threshold]
}

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Settings of general simulation parameters, unrelated to the system itself
# `T` is a range with the number of discrete units of time the simulation will run for;
# `N` is the number of times the simulation will be run (Monte Carlo runs)
time_periods_per_run = 250
monte_carlo_runs = 1

simulation_parameters = config_sim({
    'T': range(time_periods_per_run),
    'N': monte_carlo_runs,
    'M': params
})

from cadCAD.configuration import append_configs

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# The configurations above are then packaged into a `Configuration` object
append_configs(
    initial_state=
    initial_conditions,  #dict containing variable names and initial values
    partial_state_update_blocks=
    partial_state_update_blocks,  #dict containing state update functions
    sim_configs=simulation_parameters  #dict containing simulation parameters
)
Esempio n. 30
0
      'food_growth_rate': 1,
      'maximum_food_per_site': 15,
      'reproduction_probability': 1.0,
      'maximum_age': 100,
      'minimum_food': 7,
      'hungry_threshold': 5,
      'reproduction_food': 2
  }

  params = {
      'reproduction_probability': [0.75, 1.0]
  }

  simulation_parameters = config_sim({
      'T': range(50),
      'N': 1,
      'M': params
  })

  #policies

  @np.vectorize
  def augment_food(x, x_m, increment):
      if x < x_m:
          return x + increment
      else:
          return x


  def regenerate_food(params, step, sL, s):
      """