コード例 #1
0
ファイル: config.py プロジェクト: rergueta/cadCAD-Tutorials
exogenous_states = {
    #'time': time_model
}

env_processes = {
}

#build mechanism dictionary to "wire up the circuit"
mechanisms = [
    { 
        'policies': { 
        },
        'variables': { # The following state variables will be updated simultaneously
            'box_A': update_A,
            'box_B': update_B
        }
    }
]



append_configs(
    sim_configs=sim_config,
    initial_state=genesis_states,
    seeds=seeds,
    raw_exogenous_states=exogenous_states,
    env_processes=env_processes,
    partial_state_update_blocks=mechanisms
)
コード例 #2
0
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
)


print()
print("Policie State Update Block:")
pp.pprint(partial_state_update_blocks)
print()
print()
コード例 #3
0
ファイル: config1.py プロジェクト: wilson3698/cadCAD
            "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])
コード例 #4
0
update_timestamp = time_model('timestamp',
                              substeps=3,
                              time_delta=timedelta(days=0,
                                                   minutes=0,
                                                   seconds=1),
                              ts_format='%Y-%m-%d %H:%M:%S')
states['timestamp'] = update_timestamp

PSUB = {'policies': policies, 'states': states}

# needs M1&2 need behaviors
partial_state_update_blocks = [PSUB] * substeps
# pp.pprint(partial_state_update_blocks)

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

# ToDo: Bug without specifying parameters
append_configs(
    sim_configs=sim_config,
    initial_state=state_dict,
    seeds={},
    raw_exogenous_states={},
    env_processes={},
    partial_state_update_blocks=partial_state_update_blocks,
    # policy_ops=[lambda a, b: {**a, **b}]
)

print()
print("State Updates:")
pp.pprint(partial_state_update_blocks)
print()
コード例 #5
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)
コード例 #6
0
psubs = {
    "PSUB1": PSUB,
    "PSUB2": PSUB,
    "PSUB3": PSUB
}

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

append_configs(
    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=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']
result = result[cols]

print()
print("Tensor Field:")
print(tabulate(tensor_field, headers='keys', tablefmt='psql'))
コード例 #7
0
        "policies": {
            "p1": p1m2,
            "p2": p2m2
        },
        "variables": variables
    },
    "m3": {
        "policies": {
            "p1": p1m3,
            "p2": p2m3
        },
        "variables": variables
    }
}

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

# Aggregation == Reduce Map / Reduce Map Aggregation
# using env functions (include in reg test using / for env proc)
append_configs(
    sim_configs=sim_config,
    initial_state=genesis_states,
    partial_state_update_blocks=partial_state_update_block,
    # ToDo: subsequent functions should include policy dict for access to each policy (i.e shouldnt be a map)
    policy_ops=[
        lambda a, b: a + b, lambda y: y * 2
    ]  # Default: lambda a, b: a + b ToDO: reduction function requires high lvl explanation
)
コード例 #8
0
    },
    "m3": {
        "policies": {
            "b1": p1m3,
            "b2": p2m3
        },
        "variables": {
            "s1": s1m3,
            "s2": s2m3
        }
    }
}

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

# New Convention
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
)
コード例 #9
0
ファイル: udo.py プロジェクト: wilson3698/cadCAD
for m in psu_steps:
    psu_block[m]["variables"]['udo_policy_tracker'] = udo_policy_tracker


def update_timestamp(_g, step, sL, s, _input, **kwargs):
    y = 'timestamp'
    return y, time_step(dt_str=s[y],
                        dt_format='%Y-%m-%d %H:%M:%S',
                        _timedelta=timedelta(days=0, minutes=0, seconds=1))


for m in psu_steps:
    psu_block[m]["variables"]['timestamp'] = var_timestep_trigger(
        y='timestamp', f=update_timestamp)
    # psu_block[m]["variables"]['timestamp'] = var_trigger(
    #     y='timestamp', f=update_timestamp,
    #     pre_conditions={'substep': [0, system_substeps]}, cond_op=lambda a, b: a and b
    # )
    # psu_block[m]["variables"]['timestamp'] = update_timestamp

# ToDo: Bug without specifying parameters
# New Convention
partial_state_update_blocks = psub_list(psu_block, psu_steps)
append_configs(sim_configs=sim_config,
               initial_state=state_dict,
               partial_state_update_blocks=partial_state_update_blocks)

print()
print("State Updates:")
pp.pprint(partial_state_update_blocks)
print()
コード例 #10
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']})
コード例 #11
0
            "p2": p2
        },
        "variables": {
            "ds1": s1,
            "ds2": s2
        }
    },
    "m3": {
        "policies": {
            "p1": p1,
            "p2": p2
        },
        "variables": {
            "ds1": s1,
            "ds2": s2
        }
    }
}

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

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,
               policy_ops=[lambda a, b: a + b])
コード例 #12
0
        "states": {
            "s1": s1m2,
            # "s2": s2m2
        }
    },
    "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)

append_configs(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)
コード例 #13
0
        "variables": {
            "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),
})

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])
コード例 #14
0
        "variables": variables
    },
    "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),
})

append_configs(
    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
)
コード例 #15
0
    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
               }])
コード例 #16
0
        }
    },
    {
        'policies': {
        # The following policy functions will be evaluated and their returns will be passed to the state update functions
            'p1': agent_arrival
        },
        'variables': {  # The following state variables will be updated simultaneously
            'network': update_network,
            'balls': update_network_balls,
            'robot': get_robot
        }
    }
]

simulation_parameters = {
    'T': range(T),
    'N': 1,
    'M': {}
}
append_configs(
    sim_configs=simulation_parameters, #dict containing state update functions
    initial_state=initial_conditions, #dict containing variable names and initial values
    partial_state_update_blocks= partial_state_update_blocks #, #dict containing state update functions
    # policy_ops=[lambda a, b: {**a, **b}]
)
# config = Configuration(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_config=simulation_parameters #dict containing simulation parameters
#                       )
コード例 #17
0
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
)

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
for raw_result, tensor_field in run.execute():
    result = pd.DataFrame(raw_result)
コード例 #18
0
          },
          'variables': {
              'agents': update_agents
          }
      },
      {
          'policies': {
              'natural_death': kill_agents
          },
          'variables': {
              'agents': update_agents
          }
      }
  ]

  #config and execution

  from cadCAD import configs

  append_configs(
      sim_configs=simulation_parameters,
      initial_state=initial_conditions,
      partial_state_update_blocks=partial_state_update_blocks
  )

  exec_mode = ExecutionMode()
  exec_context = ExecutionContext(exec_mode.multi_proc)
  executor = Executor(exec_context, configs)
  results = []
  for raw_result, _ in executor.execute():
      results.append(raw_result)