{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Aragon Conviction Voting Model - Version 2\n",
    "\n",
    "New to this model are the following elements:\n",
    "\n",
    "* Influence - Participant social network where participants influence each others perception of a a proposal.\n",
    "* Conflict - A network with the notion of supporting one proposal may mean going against an alternative proposal. For proposals with conflicts, an edge is created between them with a function to calculate the degree of conflict.\n",
    "* Sentiment - Participant sentiment\n",
    "* Updated trigger function to better represent 1Hive's implementation\n",
    "* Updated plotting\n",
    "* Updated affinity distribution to between -1, 1\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# An Introduction to Conviction Voting\n",
    "\n",
    "Conviction Voting is an approach to organizing a communities preferences into discrete decisions in the management of that communities resources. Strictly speaking conviction voting is less like voting and more like signal processing. Framing the approach and the initial algorithm design was done by Michael Zargham and published in a short research proposal [Social Sensor Fusion](https://github.com/BlockScience/conviction/blob/master/social-sensorfusion.pdf). This work is based on a dynamic resource allocation algorithm presented in Zargham's PhD Thesis.\n",
    "\n",
    "The work proceeded in collaboration with the Commons Stack, including expanding on the pythin implementation to makeup part of the Commons Simulator game. An implemention of Conviction Voting as a smart contract within the Aragon Framework was developed by 1hive.org and is currently being used for community decision making around allocations their community currency, Honey.\n",
    "\n",
    "\n",
    "## The Word Problem\n",
    "\n",
    "Suppose a group of people want to coordinate to make a collective decision. Social dynamics such as discussions, signaling, and even changing ones mind based on feedback from others input play an important role in these processes. While the actual decision making process involves a lot of informal processes, in order to be fair the ultimate decision making process still requires a set of formal rules that the community collecively agrees to, which serves to functionally channel a plurality of preferences into a discrete outcomes. In our case we are interested in a procedure which supports asynchronous interactions, an provides visibility into likely outcomes prior to their resolution to serve as a driver of good faith, debate and healthy forms of coalition building. Furthermore, participations should be able to show support for multiple initiatives, and to vary the level of support shown. Participants a quantity of signaling power which may be fixed or variable, homogenous or heterogenous. For the purpose of this document, we'll focus on the case where the discrete decisions to be made are decisions to allocate funds from a shared funding pool towards projects of interest to the community.\n",
    "\n",
    "## Converting to a Math Problem\n",
    "\n",
    "Let's start taking these words and constructing a mathematical representation that supports a design that meets the description above. To start we need to define participants.\n",
    "\n",
    "### Participants\n",
    "Let $\\mathcal{A}$ be the set of participants. Consider a participant $a\\in \\mathcal{A}$. Any participant $a$ has some capacity to participate in the voting process $h[a]$. In a fixed quantity, homogenous system $h[a] = h$ for all $a\\in \\mathcal{A}$ where $h$ is a constant. The access control process managing how one becomes a participant determines the total supply of \"votes\" $S = \\sum_{a\\in \\mathcal{A}} = n\\cdot h$ where the number of participants is $n = |\\mathcal{A}|$. In a smart contract setting, the set $\\mathcal{A}$ is a set of addresses, and $h[a]$ is a quantity of tokens held by each address $a\\in \\mathcal{A}$. \n",
    "\n",
    "### Proposals & Shares Resources\n",
    "Next, we introduce the idea of proposals.  Consider a proposal $i\\in \\mathcal{C}$. Any proposal $i$ is associated with a request for resources $r[i]$. Those requested resources would be allocated from a constrained pool of communal resources currently totaling $R$. The pool of resources may become depleted because when a proposal $i$ passes $R^+= R-r[i]$. Therefore it makes sense for us to consider what fraction of the shared resources are being request $\\mu_i = \\frac{r[i]}{R}$, which means that thre resource depletion from passing proposals can be bounded by requiring $\\mu_i < \\mu$ where $\\mu$ is a constant representing the maximum fraction of the shared resources which can be dispersed by any one proposal. In order for the system to be sustainable a source of new resources is required. In the case where $R$ is funding, new funding can come from revenues, donations, or in some DAO use cases minting tokens.\n",
    "\n",
    "### Participants Preferences for Proposals\n",
    "\n",
    "Most of the interesting information in this system is distributed amongst the participants and it manifests as preferences over the proposals. This can be thought of as a matrix $W\\in \\mathbb{R}^{n \\times m}$.\n",
    "![Replace this later](https://i.imgur.com/vxKNtxi.png)\n",
    "\n",
    "These private hidden signals drive discussions and voting actions. Each participant individually decides how to allocate their votes across the available proposals. Participant $a$ supports proposal $i$ by setting $x[a,i]>0$ but they are limited by their capacity $\\sum_{k\\in \\mathcal{C}} x[a,k] \\le h[a]$.  Assuming each participant chooses a subset of the proposals to support, a support graph is formed.\n",
    "![](https://i.imgur.com/KRh8tKn.png)\n",
    "\n",
    "## Aggregating Information\n",
    "\n",
    "In order to break out of the synchronous voting model, a dynamical systems model of this system is introduced.\n",
    "\n",
    "### Participants Allocate Voting Power\n",
    "![](https://i.imgur.com/DZRDwk6.png)\n",
    "\n",
    "### System Accounts Proposal Conviction\n",
    "![](https://i.imgur.com/euAei5R.png)\n",
    "\n",
    "### Understanding Alpha\n",
    "* https://www.desmos.com/calculator/x9uc6w72lm\n",
    "* https://www.desmos.com/calculator/0lmtia9jql\n",
    "\n",
    "\n",
    "## Converting Signals to Discrete Decisions\n",
    "\n",
    "Conviction as kinetic energy and Trigger function as required activation energy.\n",
    "\n",
    "### The Trigger Function\n",
    "\n",
    "https://www.desmos.com/calculator/yxklrjs5m3\n",
    "\n",
    "Below we show a sweep of the trigger function threshold:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "for reference: max conviction = 5.239669785665982in log10 units\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/aclarkdata/anaconda3/lib/python3.7/site-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.\n",
      "  import pandas.util.testing as tm\n"
     ]
    }
   ],
   "source": [
    "from model.model.conviction_helper_functions import *\n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "\n",
    "beta = .2 #later we should set this to be param so we can sweep it\n",
    "# tuning param for the trigger function\n",
    "rho = .001\n",
    "#alpha = 1 - 0.9999599 #native timescale for app as in contract code\n",
    "alpha = 1-.5**3 #timescale set in days with 3 day halflife (from comments in contract comments)\n",
    "supply= 21706 \n",
    "\n",
    "mcv = supply/(1-alpha)\n",
    "print('for reference: max conviction = '+str(np.log10(mcv))+'in log10 units')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "supply_sweep = trigger_sweep('effective_supply',trigger_threshold,beta,rho,alpha, supply)\n",
    "alpha_sweep = trigger_sweep('alpha',trigger_threshold,beta,rho,alpha, supply)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 113544 characters]\n",
      "text/plain": [
       "<Figure size 1440x1440 with 4 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "trigger_grid(supply_sweep, alpha_sweep)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Resolving Passed Proposals\n",
    "\n",
    "![image](.\\images\\stockflow_cv_trigger.png)\n",
    "\n",
    "\n",
    "## Social Systems Modeling\n",
    "\n",
    "Subjective, exploratory modeling of the social system interacting through the conviction voting algorithm.\n",
    "\n",
    "### Sentiment\n",
    "\n",
    "Global Sentiment -- the outside world appreciating the output of the community\n",
    "Local Sentiment -- agents within the system feeling good about the community\n",
    "\n",
    "### Social Networks\n",
    "\n",
    "Preferences as mixing process (social influence)\n",
    "\n",
    "### Relationships between Proposals\n",
    "\n",
    "Some proposals are synergistic (passing one makes the other more desireable)\n",
    "Some proposals are (parially) substitutable (passing one makes the other less desirable)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## cadCAD Overview\n",
    "\n",
    "In the cadCAD simulation [methodology](https://community.cadcad.org/t/differential-specification-syntax-key/31), we operate on four layers: **Policies, Mechanisms, States**, and **Metrics**. Information flows do not have explicit feedback loop unless noted. **Policies** determine the inputs into the system dynamics, and can come from user input, observations from the exogenous environment, or algorithms. **Mechanisms** are functions that take the policy decisions and update the States to reflect the policy level changes. **States** are variables that represent the system quantities at the given point in time, and **Metrics** are computed from state variables to assess the health of the system. Metrics can often be thought of as KPIs, or Key Performance Indicators. \n",
    "\n",
    "At a more granular level, to setup a model, there are system conventions and configurations that must be [followed.](https://community.cadcad.org/t/introduction-to-simulation-configurations/34)\n",
    "\n",
    "The way to think of cadCAD modeling is analogous to machine learning pipelines which normally consist of multiple steps when training and running a deployed model. There is preprocessing, which includes segregating features between continuous and categorical, transforming or imputing data, and then instantiating, training, and running a machine learning model with specified hyperparameters. cadCAD modeling can be thought of in the same way as states, roughly translating into features, are fed into pipelines that have built-in logic to direct traffic between different mechanisms, such as scaling and imputation. Accuracy scores, ROC, etc. are analogous to the metrics that can be configured on a cadCAD model, specifying how well a given model is doing in meeting its objectives. The parameter sweeping capability of cadCAD can be thought of as a grid search, or way to find the optimal hyperparameters for a system by running through alternative scenarios. A/B style testing that cadCAD enables is used in the same way machine learning models are A/B tested, except out of the box, in providing a side by side comparison of muliple different models to compare and contrast performance. Utilizing the field of Systems Identification, dynamical systems models can be used to \"online learn\" by providing a feedback loop to generative system mechanisms. \n",
    "\n",
    "\n",
    "## Differential Specification \n",
    "![](images/Aragon_v2.png)\n",
    "\n",
    "## Schema of the states \n",
    "The model consists of a temporal in memory graph database called *network* containing nodes of type **Participant** and type **Proposal**. Participants will have *holdings* and *sentiment* and Proposals will have *funds_required, status*(candidate or active), *conviction* Tthe model as three kinds of edges:\n",
    "* (Participant, participant), we labeled this edge type \"influencer\" and it contains information about how the preferences and sentiment of one participant influence another \n",
    "* (Proposal, Proposal), we labeled this edge type \"conflict\" and it contains information about how synergistic or anti-synergistic two proposals are; basically people are likely to support multiple things that have synergy (meaning once one is passed there is more utility from the other) but they are not likely to pass things that have antisynergy (meaning once one is passed there is less utility from the other).\n",
    "* The edges between Participant and Proposal, which are described below.\n",
    "    \n",
    "\n",
    "Edges in the network go from nodes of type Participant to nodes of type Proposal with the edges having the key *type*, of which all will be set to *support*. Edges from participant $i$ to proposal $j$ will have the following additional characteristics:\n",
    "* Each pairing (i,j) will have *affinity*, which determines how much $i$ likes or dislikes proposal $j$.\n",
    "* Each participant $i$, assigns its $tokens$ over the edges (i,j) for all $j$ such that the summation of all $j$ such that ```Sum_j = network.edges[(i,j)]['tokens'] = network.nodes[i]['holdings']```. This value of tokens for participants on proposals must be less than or equal to the total number of tokens held by the participant.\n",
    "* Each pairing (i,j) will have *conviction* local to that edge whose update at each timestep is computed using the value of *tokens* at that edge.\n",
    "* Each proposal *j* will have a *conviction* which is equal to the sum of the conviction on its inbound edges: ```network.nodes[j]['conviction'] = Sum_i  network.edges[(i,j)]['conviction']```. \n",
    "\n",
    "\n",
    "The other state variable in the model is *funds*, which is a numpy floating point. \n",
    "\n",
    "The system consists of 100 time steps without a parameter sweep or monte carlo.\n",
    "\n",
    "\n",
    "## Partial State Update Blocks\n",
    "\n",
    "Each partial state update block is kind of a like a phase in a phased based board game. Everyone decides what to do and it reconciles all decisions. One timestep is a full turn, with each block being a phase of a timestep or turn. We will walk through the individaul Partial State update blocks one by one below."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "{\n",
    "# system.py: \n",
    "'policies': { \n",
    "    'random': driving_process\n",
    "},\n",
    "'variables': {\n",
    "    'network': update_network,\n",
    "    'funds':increment_funds,\n",
    "}\n",
    "```\n",
    "\n",
    "To simulate the arrival of participants and proposal into the system, we have a driving process to represent the arrival of individual agents. We use a random uniform distribution generator, over [0, 1), to calculate the number of new participants. We then use an exponential distribution to calculate the particpant's tokens by using a loc of 0.0 and a scale of expected holdings, which is calculated by .1*supply/number of existing participants. We calculate the number of new proposals by     \n",
    "```\n",
    "proposal_rate = 1/median_affinity * (1+total_funds_requested/funds)\n",
    "rv2 = np.random.rand()\n",
    "new_proposal = bool(rv2<1/proposal_rate)\n",
    "```\n",
    "The network state variable is updated to include the new participants and proposals, while the funds state variable is updated for the increase in system funds. \n",
    "[To see the partial state update code, click here](model/model/system.py)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "{\n",
    "  # participants.py   \n",
    "  'policies': {\n",
    "      'completion': check_progress \n",
    "    },\n",
    "    'variables': { \n",
    "        'sentiment': update_sentiment_on_completion, #not completing projects decays sentiment, completing bumps it\n",
    "        'network': complete_proposal\n",
    "    }\n",
    "},\n",
    "```\n",
    "\n",
    "In the next phase of the turn, [to see the logic code, click here](model/model/participants.py), the *check_progress* behavior checks for the completion of previously funded proposals. The code calculates the completion and failure rates as follows:\n",
    "\n",
    "```\n",
    "likelihood = 1.0/(base_completion_rate+np.log(grant_size))\n",
    "\n",
    "failure_rate = 1.0/(base_failure_rate+np.log(grant_size))\n",
    "if np.random.rand() < likelihood:\n",
    "    completed.append(j)\n",
    "elif np.random.rand() < failure_rate:\n",
    "    failed.append(j)\n",
    "```\n",
    "With the base_completion_rate being 100 and the base_failure_rate as 200. \n",
    "\n",
    "The mechanism then updates the respective *network* nodes and updates the sentiment variable on proposal completion. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "  # proposals.py\n",
    "  'policies': {\n",
    "      'release': trigger_function \n",
    "    },\n",
    "    'variables': { \n",
    "        'funds': decrement_funds, \n",
    "        'sentiment': update_sentiment_on_release, #releasing funds can bump sentiment\n",
    "        'network': update_proposals \n",
    "    }\n",
    "},\n",
    " ```\n",
    " \n",
    "The [trigger release function](model/model/proposals.py) checks to see if each proposal passes or not. If a proposal passes, funds are decremented by the amount of the proposal, while the proposal's status is changed in the network object."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "{ \n",
    "    # participants.py\n",
    "    'policies': { \n",
    "        'participants_act': participants_decisions\n",
    "    },\n",
    "    'variables': {\n",
    "        'network': update_tokens \n",
    "    }\n",
    "}\n",
    "```\n",
    "\n",
    "The Participants decide based on their affinity if which proposals they would like to support,[to see the logic code, click here](model/model/participants.py). Proposals that participants have high affinity for receive more support and pledged tokens than proposals with lower affinity and sentiment. We then update everyone's holdings and their conviction for each proposal.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model next steps\n",
    "\n",
    "The the model described above is the second iteration model that covers the core mechanisms of the Aragon Conviction Voting model. Below are next additional dynamics we can attend to enrich the model, and provide workstreams for subsequent iterations of this lab notebook.\n",
    "\n",
    "* Mixing of token holdings among participants\n",
    "* Departure of participants\n",
    "* Proposals which are good or no good together\n",
    "* Affects of outcomes on sentiment"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Simulation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Configuration\n",
    "Let's factor out into its own notebook where we review the config object and its partial state update blocks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "from model import economyconfig"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# pull out configurations to illustrate\n",
    "sim_config,genesis_states,seeds,partial_state_update_blocks = economyconfig.get_configs()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'N': 1,\n",
       " 'T': range(0, 100),\n",
       " 'M': [{}],\n",
       " 'subset_id': 0,\n",
       " 'subset_window': deque([0, None]),\n",
       " 'simulation_id': 0,\n",
       " 'run_id': 0}"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sim_config"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'policies': {'random': <function model.model.system.driving_process(params, step, sL, s)>},\n",
       "  'variables': {'network': <function model.model.system.update_network(params, step, sL, s, _input)>,\n",
       "   'funds': <function model.model.system.increment_funds(params, step, sL, s, _input)>}},\n",
       " {'policies': {'completion': <function model.model.participants.check_progress(params, step, sL, s)>},\n",
       "  'variables': {'sentiment': <function model.model.participants.update_sentiment_on_completion(params, step, sL, s, _input)>,\n",
       "   'network': <function model.model.participants.complete_proposal(params, step, sL, s, _input)>}},\n",
       " {'policies': {'release': <function model.model.proposals.trigger_function(params, step, sL, s)>},\n",
       "  'variables': {'funds': <function model.model.proposals.decrement_funds(params, step, sL, s, _input)>,\n",
       "   'sentiment': <function model.model.proposals.update_sentiment_on_release(params, step, sL, s, _input)>,\n",
       "   'network': <function model.model.proposals.update_proposals(params, step, sL, s, _input)>}},\n",
       " {'policies': {'participants_act': <function model.model.participants.participants_decisions(params, step, sL, s)>},\n",
       "  'variables': {'network': <function model.model.participants.update_tokens(params, step, sL, s, _input)>}}]"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "partial_state_update_blocks"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Initialization\n",
    "To create the genesis_states, we create our in-memory graph database within networkx. \n",
    "\n",
    "\n",
    "### Hyperparameters\n",
    "* $\\beta$ = .2 # maximum share of funds a proposal can take\n",
    "* $\\rho$ = 0.002 # tuning param for the trigger function\n",
    "* $\\alpha$ = 1/8 = 1/2^3 = 3 day half-life when timestep is 1 day \n",
    "* supply = 21706 # Honey supply balance as of 7-17-2020  \n",
    "* initial_sentiment = .9\n",
    "* n= 24 #initial participants\n",
    "* m= 3 #initial proposals\n",
    "* sensitivity = .75\n",
    "* tmin = 7 #unit days; minimum periods passed before a proposal can pass\n",
    "* min_supp = 50 #number of tokens that must be stake for a proposal to be a candidate\n",
    "* base_completion_rate = 100\n",
    "* base_failure_rate = 200 \n",
    "* initial_funds = 48000 # in xDai\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# import libraries\n",
    "import networkx as nx\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "from model.model.conviction_helper_functions import * \n",
    "\n",
    "# # Parameters\n",
    "# # maximum share of funds a proposal can take\n",
    "# beta = .2\n",
    "# # tuning param for the trigger function\n",
    "# rho = 0.002\n",
    "# #alpha = 1 - 0.9999599 #native timescale for app as in contract code\n",
    "# alpha = 1/2**7 #timescale set in days with 7 day halflife\n",
    "\n",
    "# supply = 21706 # Honey supply balance as of 7-17-2020  \n",
    "# initial_sentiment = .9\n",
    "\n",
    "\n",
    "# n= 24 #initial participants\n",
    "# m= 5 #initial proposals\n",
    "\n",
    "\n",
    "# sensitivity = .75\n",
    "# tmin = 0 #unit days; minimum periods passed before a proposal can pass\n",
    "# min_supp = 50 #number of tokens that must be stake for a proposal to be a candidate\n",
    "# base_completion_rate = 100\n",
    "# base_failure_rate = 200 \n",
    "\n",
    "# initial_funds = 48000 # in xDai\n",
    "\n",
    "\n",
    "#initializers\n",
    "network = genesis_states['network']\n",
    "initial_funds = genesis_states['funds']\n",
    "initial_sentiment = genesis_states['sentiment']\n",
    "\n",
    "# Create initial states\n",
    "# genesis_states = { \n",
    "#                 'network':network,\n",
    "#                 'funds':initial_funds,\n",
    "#                 'sentiment':initial_sentiment,\n",
    "#}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'network': <networkx.classes.digraph.DiGraph at 0x7fc80a501950>,\n",
       " 'funds': 48000,\n",
       " 'sentiment': 0.6,\n",
       " 'supply': 21706}"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "genesis_states"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Exploring the State Data Structure\n",
    "\n",
    "A graph is a type of temporal data structure that evolves over time. A graph $\\mathcal{G}(\\mathcal{V},\\mathcal{E})$ consists of vertices or nodes, $\\mathcal{V} = \\{1...\\mathcal{V}\\}$ and is connected by edges  $\\mathcal{E} \\subseteq \\mathcal{V} \\times \\mathcal{V}$.\n",
    "\n",
    "See *Schema of the states* above for more details\n",
    "\n",
    "\n",
    "Let's explore!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "# To explore our model prior to the simulation, we extract key components from our networkX object into lists.\n",
    "proposals = get_nodes_by_type(network, 'proposal')\n",
    "participants = get_nodes_by_type(network, 'participant')\n",
    "supporters = get_edges_by_type(network, 'support')\n",
    "influencers = get_edges_by_type(network, 'influence')\n",
    "competitors = get_edges_by_type(network, 'conflict')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'type': 'participant',\n",
       " 'holdings': 1167.7851309333748,\n",
       " 'sentiment': 0.8149097874053217}"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#sample a participant\n",
    "network.nodes[participants[0]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0, 0.5, 'Count of Participants')"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 10744 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Let's look at the distribution of participant holdings at the start of the sim\n",
    "plt.hist([ network.nodes[i]['holdings'] for i in participants])\n",
    "plt.title('Histogram of Participants Token Holdings')\n",
    "plt.xlabel('Amount of Honey')\n",
    "plt.ylabel('Count of Participants')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0.5, 1.0, 'Participants Social Network')"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 108048 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "nx.draw_spring(network, nodelist = participants, edgelist=influencers)\n",
    "plt.title('Participants Social Network')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'type': 'proposal',\n",
       " 'conviction': 0,\n",
       " 'status': 'candidate',\n",
       " 'age': 0,\n",
       " 'funds_requested': 1326.515044968538,\n",
       " 'trigger': 14641.659578307832}"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#lets look at proposals\n",
    "network.nodes[proposals[0]]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Proposals initially start without any conviction, and with the status of a candidate. If the proposal's amount of  conviction is greater than it's trigger, then the proposal moves to active and it's funds requested are granted. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "All initial proposal start with 0 conviction and state 'candidate'we can simply examine the amounts of funds requested"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "funds_array = np.array([ network.nodes[i]['funds_requested'] for i in proposals])\n",
    "conviction_required = np.array([trigger_threshold(r, initial_funds, supply, beta, rho, alpha) for r in funds_array])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0, 0.5, 'Amount of Honey requested(as a Fraction of Funds available)')"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 15772 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.bar( proposals, funds_array/initial_funds)\n",
    "plt.title('Bar chart of Proposals Funds Requested')\n",
    "plt.xlabel('Proposal identifier')\n",
    "plt.ylabel('Amount of Honey requested(as a Fraction of Funds available)')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0, 0.5, 'Amount of Conviction')"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 11872 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.bar( proposals, conviction_required)\n",
    "plt.title('Bar chart of Proposals Conviction Required')\n",
    "plt.xlabel('Proposal identifier')\n",
    "plt.ylabel('Amount of Conviction')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Conviction is a concept that arises in the edges between participants and proposals in the initial conditions there are no votes yet so we can look at that later however, the voting choices are driven by underlying affinities which we can see now."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0.5, 55.73999999999998, 'participant_id')"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 19144 characters]\n",
      "text/plain": [
       "<Figure size 1440x360 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "m = len(proposals)\n",
    "n = len(participants)\n",
    "\n",
    "affinities = np.empty((n,m))\n",
    "for i_ind in range(n):\n",
    "    for j_ind in range(m):\n",
    "        i = participants[i_ind]\n",
    "        j = proposals[j_ind]\n",
    "        affinities[i_ind][j_ind] = network.edges[(i,j)]['affinity']\n",
    "\n",
    "dims = (20, 5)\n",
    "fig, ax = plt.subplots(figsize=dims)\n",
    "\n",
    "sns.heatmap(affinities.T,\n",
    "            xticklabels=participants,\n",
    "            yticklabels=proposals,\n",
    "            square=True,\n",
    "            cbar=True,\n",
    "            cmap = plt.cm.RdYlGn,\n",
    "            ax=ax)\n",
    "\n",
    "plt.title('affinities between participants and proposals')\n",
    "plt.ylabel('proposal_id')\n",
    "plt.xlabel('participant_id')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Run simulation\n",
    "\n",
    "Now we will create the final system configuration, append the genesis states we created, and run our simulation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "from cadCAD.configuration import Experiment\n",
    "\n",
    "# Create configuration\n",
    "exp = Experiment()\n",
    "\n",
    "exp.append_configs(\n",
    "    sim_configs=sim_config,\n",
    "    initial_state=genesis_states,\n",
    "    seeds=seeds,\n",
    "    partial_state_update_blocks=partial_state_update_blocks\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "                  ___________    ____\n",
      "  ________ __ ___/ / ____/   |  / __ \\\n",
      " / ___/ __` / __  / /   / /| | / / / /\n",
      "/ /__/ /_/ / /_/ / /___/ ___ |/ /_/ /\n",
      "\\___/\\__,_/\\__,_/\\____/_/  |_/_____/\n",
      "by cadCAD\n",
      "\n",
      "Execution Mode: local_proc\n",
      "Configuration Count: 2\n",
      "Dimensions of the first simulation: (Timesteps, Params, Runs, Vars) = (100, 1, 1, 4)\n",
      "Execution Method: local_simulations\n",
      "SimIDs   : [0, 1]\n",
      "SubsetIDs: [0, 0]\n",
      "Ns       : [0, 0]\n",
      "ExpIDs   : [0, 0]\n",
      "Total execution time: 325.88s\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from model.model.conviction_helper_functions import *\n",
    "from model import run\n",
    "from cadCAD import configs\n",
    "pd.options.display.float_format = '{:.2f}'.format\n",
    "\n",
    "%matplotlib inline\n",
    "\n",
    "rdf = run.run(configs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "After the simulation has run successfully, we perform some postprocessing to extract node and edge values from the network object and add as columns to the pandas dataframe. For the rdf, we take only the values at the last substep of each timestep in the simulation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "df= run.postprocessing(rdf,0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>network</th>\n",
       "      <th>funds</th>\n",
       "      <th>sentiment</th>\n",
       "      <th>supply</th>\n",
       "      <th>simulation</th>\n",
       "      <th>subset</th>\n",
       "      <th>run</th>\n",
       "      <th>substep</th>\n",
       "      <th>timestep</th>\n",
       "      <th>conviction</th>\n",
       "      <th>...</th>\n",
       "      <th>funds_requested</th>\n",
       "      <th>share_of_funds_requested</th>\n",
       "      <th>share_of_funds_requested_all</th>\n",
       "      <th>triggers</th>\n",
       "      <th>conviction_share_of_trigger</th>\n",
       "      <th>age</th>\n",
       "      <th>age_all</th>\n",
       "      <th>conviction_all</th>\n",
       "      <th>triggers_all</th>\n",
       "      <th>conviction_share_of_trigger_all</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...</td>\n",
       "      <td>48000.14</td>\n",
       "      <td>0.60</td>\n",
       "      <td>21706</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "      <td>1</td>\n",
       "      <td>[329.74734182304195, 400.7758642017258, 37.785...</td>\n",
       "      <td>...</td>\n",
       "      <td>[1326.515044968538, 1996.245003278849, 1538.78...</td>\n",
       "      <td>[0.027635646875748886, 0.03205789146983426, 0....</td>\n",
       "      <td>[0.027635646875748886, 0.04158831232057447, 0....</td>\n",
       "      <td>[14612.189847462627, 15391.85951042984, 12279....</td>\n",
       "      <td>[0.022566593047673947, 0.02603817062715209, 0....</td>\n",
       "      <td>[1, 1, 1, 1]</td>\n",
       "      <td>[1, 1, 1, 1, 1, 1, 1, 1, 1]</td>\n",
       "      <td>[329.74734182304195, 0.0, 400.7758642017258, 0...</td>\n",
       "      <td>[14612.189847462627, 17299.5991173582, 15391.8...</td>\n",
       "      <td>[0.022566593047673947, 0.0, 0.0260381706271520...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...</td>\n",
       "      <td>48003.33</td>\n",
       "      <td>0.60</td>\n",
       "      <td>21706</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>[1074.1723943242607, 875.1321563386, 59.897548...</td>\n",
       "      <td>...</td>\n",
       "      <td>[1326.515044968538, 1996.245003278849, 1538.78...</td>\n",
       "      <td>[0.027633811370698504, 0.032055762248037425, 0...</td>\n",
       "      <td>[0.027633811370698504, 0.041585550107059284, 0...</td>\n",
       "      <td>[14612.175736197183, 15391.84181362352, 12279....</td>\n",
       "      <td>[0.07351214587868171, 0.05685688346692916, 0.0...</td>\n",
       "      <td>[2, 2, 2, 2, 1]</td>\n",
       "      <td>[2, 2, 2, 2, 2, 2, 2, 2, 2, 1]</td>\n",
       "      <td>[1074.1723943242607, 0.0, 875.1321563386, 0.0,...</td>\n",
       "      <td>[14612.175736197183, nan, 15391.84181362352, n...</td>\n",
       "      <td>[0.07351214587868171, nan, 0.05685688346692916...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...</td>\n",
       "      <td>48005.31</td>\n",
       "      <td>0.60</td>\n",
       "      <td>21706</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>[3037.6044741709347, 1290.1939119583649, 79.24...</td>\n",
       "      <td>...</td>\n",
       "      <td>[1326.515044968538, 1996.245003278849, 1538.78...</td>\n",
       "      <td>[0.027632671170568814, 0.03205443959356236, 0....</td>\n",
       "      <td>[0.027632671170568814, 0.04158383424351121, 0....</td>\n",
       "      <td>[14611.864531548885, 15391.45153601979, 12279....</td>\n",
       "      <td>[0.2078861645351528, 0.08382535649344008, 0.00...</td>\n",
       "      <td>[3, 3, 3, 3, 2]</td>\n",
       "      <td>[3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 1]</td>\n",
       "      <td>[3037.6044741709347, 0.0, 1290.1939119583649, ...</td>\n",
       "      <td>[14611.864531548885, nan, 15391.45153601979, n...</td>\n",
       "      <td>[0.2078861645351528, nan, 0.08382535649344008,...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>16</th>\n",
       "      <td>(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...</td>\n",
       "      <td>48007.93</td>\n",
       "      <td>0.60</td>\n",
       "      <td>21706</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "      <td>4</td>\n",
       "      <td>[4539.327212112606, 1645.0121346599128, 308.74...</td>\n",
       "      <td>...</td>\n",
       "      <td>[1326.515044968538, 1996.245003278849, 1538.78...</td>\n",
       "      <td>[0.02763116701849185, 0.032052694747702434, 0....</td>\n",
       "      <td>[0.02763116701849185, 0.041581570676219454, 0....</td>\n",
       "      <td>[14611.671218873644, 15391.20910636533, 12279....</td>\n",
       "      <td>[0.31066447801324976, 0.10687998085735749, 0.0...</td>\n",
       "      <td>[4, 4, 4, 4, 3, 1]</td>\n",
       "      <td>[4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1]</td>\n",
       "      <td>[4539.327212112606, 0.0, 1645.0121346599128, 0...</td>\n",
       "      <td>[14611.671218873644, nan, 15391.20910636533, n...</td>\n",
       "      <td>[0.31066447801324976, nan, 0.10687998085735749...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>20</th>\n",
       "      <td>(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...</td>\n",
       "      <td>48008.78</td>\n",
       "      <td>0.60</td>\n",
       "      <td>21706</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "      <td>5</td>\n",
       "      <td>[5843.990746076446, 1823.8155725217277, 509.55...</td>\n",
       "      <td>...</td>\n",
       "      <td>[1326.515044968538, 1996.245003278849, 1538.78...</td>\n",
       "      <td>[0.027630673896173377, 0.03205212271615789, 0....</td>\n",
       "      <td>[0.027630673896173377, 0.04158082858666081, 0....</td>\n",
       "      <td>[14611.416206649721, 15390.889301913036, 12279...</td>\n",
       "      <td>[0.39996059679805845, 0.1184996874933688, 0.04...</td>\n",
       "      <td>[5, 5, 5, 5, 4, 2, 1]</td>\n",
       "      <td>[5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1]</td>\n",
       "      <td>[5843.990746076446, 0.0, 1823.8155725217277, 0...</td>\n",
       "      <td>[14611.416206649721, nan, 15390.889301913036, ...</td>\n",
       "      <td>[0.39996059679805845, nan, 0.1184996874933688,...</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>5 rows × 31 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "                                              network    funds  sentiment  \\\n",
       "4   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... 48000.14       0.60   \n",
       "8   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... 48003.33       0.60   \n",
       "12  (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... 48005.31       0.60   \n",
       "16  (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... 48007.93       0.60   \n",
       "20  (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... 48008.78       0.60   \n",
       "\n",
       "    supply  simulation  subset  run  substep  timestep  \\\n",
       "4    21706           0       0    1        4         1   \n",
       "8    21706           0       0    1        4         2   \n",
       "12   21706           0       0    1        4         3   \n",
       "16   21706           0       0    1        4         4   \n",
       "20   21706           0       0    1        4         5   \n",
       "\n",
       "                                           conviction  ...  \\\n",
       "4   [329.74734182304195, 400.7758642017258, 37.785...  ...   \n",
       "8   [1074.1723943242607, 875.1321563386, 59.897548...  ...   \n",
       "12  [3037.6044741709347, 1290.1939119583649, 79.24...  ...   \n",
       "16  [4539.327212112606, 1645.0121346599128, 308.74...  ...   \n",
       "20  [5843.990746076446, 1823.8155725217277, 509.55...  ...   \n",
       "\n",
       "                                      funds_requested  \\\n",
       "4   [1326.515044968538, 1996.245003278849, 1538.78...   \n",
       "8   [1326.515044968538, 1996.245003278849, 1538.78...   \n",
       "12  [1326.515044968538, 1996.245003278849, 1538.78...   \n",
       "16  [1326.515044968538, 1996.245003278849, 1538.78...   \n",
       "20  [1326.515044968538, 1996.245003278849, 1538.78...   \n",
       "\n",
       "                             share_of_funds_requested  \\\n",
       "4   [0.027635646875748886, 0.03205789146983426, 0....   \n",
       "8   [0.027633811370698504, 0.032055762248037425, 0...   \n",
       "12  [0.027632671170568814, 0.03205443959356236, 0....   \n",
       "16  [0.02763116701849185, 0.032052694747702434, 0....   \n",
       "20  [0.027630673896173377, 0.03205212271615789, 0....   \n",
       "\n",
       "                         share_of_funds_requested_all  \\\n",
       "4   [0.027635646875748886, 0.04158831232057447, 0....   \n",
       "8   [0.027633811370698504, 0.041585550107059284, 0...   \n",
       "12  [0.027632671170568814, 0.04158383424351121, 0....   \n",
       "16  [0.02763116701849185, 0.041581570676219454, 0....   \n",
       "20  [0.027630673896173377, 0.04158082858666081, 0....   \n",
       "\n",
       "                                             triggers  \\\n",
       "4   [14612.189847462627, 15391.85951042984, 12279....   \n",
       "8   [14612.175736197183, 15391.84181362352, 12279....   \n",
       "12  [14611.864531548885, 15391.45153601979, 12279....   \n",
       "16  [14611.671218873644, 15391.20910636533, 12279....   \n",
       "20  [14611.416206649721, 15390.889301913036, 12279...   \n",
       "\n",
       "                          conviction_share_of_trigger                    age  \\\n",
       "4   [0.022566593047673947, 0.02603817062715209, 0....           [1, 1, 1, 1]   \n",
       "8   [0.07351214587868171, 0.05685688346692916, 0.0...        [2, 2, 2, 2, 1]   \n",
       "12  [0.2078861645351528, 0.08382535649344008, 0.00...        [3, 3, 3, 3, 2]   \n",
       "16  [0.31066447801324976, 0.10687998085735749, 0.0...     [4, 4, 4, 4, 3, 1]   \n",
       "20  [0.39996059679805845, 0.1184996874933688, 0.04...  [5, 5, 5, 5, 4, 2, 1]   \n",
       "\n",
       "                                    age_all  \\\n",
       "4               [1, 1, 1, 1, 1, 1, 1, 1, 1]   \n",
       "8            [2, 2, 2, 2, 2, 2, 2, 2, 2, 1]   \n",
       "12        [3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 1]   \n",
       "16     [4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1]   \n",
       "20  [5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1]   \n",
       "\n",
       "                                       conviction_all  \\\n",
       "4   [329.74734182304195, 0.0, 400.7758642017258, 0...   \n",
       "8   [1074.1723943242607, 0.0, 875.1321563386, 0.0,...   \n",
       "12  [3037.6044741709347, 0.0, 1290.1939119583649, ...   \n",
       "16  [4539.327212112606, 0.0, 1645.0121346599128, 0...   \n",
       "20  [5843.990746076446, 0.0, 1823.8155725217277, 0...   \n",
       "\n",
       "                                         triggers_all  \\\n",
       "4   [14612.189847462627, 17299.5991173582, 15391.8...   \n",
       "8   [14612.175736197183, nan, 15391.84181362352, n...   \n",
       "12  [14611.864531548885, nan, 15391.45153601979, n...   \n",
       "16  [14611.671218873644, nan, 15391.20910636533, n...   \n",
       "20  [14611.416206649721, nan, 15390.889301913036, ...   \n",
       "\n",
       "                      conviction_share_of_trigger_all  \n",
       "4   [0.022566593047673947, 0.0, 0.0260381706271520...  \n",
       "8   [0.07351214587868171, nan, 0.05685688346692916...  \n",
       "12  [0.2078861645351528, nan, 0.08382535649344008,...  \n",
       "16  [0.31066447801324976, nan, 0.10687998085735749...  \n",
       "20  [0.39996059679805845, nan, 0.1184996874933688,...  \n",
       "\n",
       "[5 rows x 31 columns]"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.head(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.axes._subplots.AxesSubplot at 0x7fc82f5aae90>"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 11556 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "df.plot('timestep','sentiment')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.axes._subplots.AxesSubplot at 0x7fc80d01aa90>"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 16484 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "df.plot('timestep',['funds', 'candidate_funds'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 70852 characters]\n",
      "text/plain": [
       "<Figure size 612x792 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "affinities_plot(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.legend.Legend at 0x7fc854fcd150>"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 32908 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "df.plot(x='timestep',y=['candidate_count','active_count','completed_count', 'killed_count', 'failed_count'],\n",
    "         kind='area')\n",
    "plt.title('Proposal Status')\n",
    "plt.ylabel('count of proposals')\n",
    "plt.legend(ncol = 3,loc='upper center', bbox_to_anchor=(0.5, -0.15))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.legend.Legend at 0x7fc854bfaed0>"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 36992 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "df.plot(x='timestep',y=['candidate_funds','active_funds','completed_funds', 'killed_funds', 'failed_funds'], kind='area')\n",
    "plt.title('Proposal Status weighted by funds requested')\n",
    "plt.ylabel('Funds worth of proposals')\n",
    "plt.legend(ncol = 3,loc='upper center', bbox_to_anchor=(0.5, -0.15))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "nets = df.network.values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 119612 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "K = 55\n",
    "N = 56\n",
    "\n",
    "snap_plot(nets[K:N], size_scale = 1/10,savefigs=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Conclusion\n",
    "\n",
    "We have created a simplified conviction voting model that illustrates the state objects, and provides descriptions of how the model fits together. In subsequent notebooks, we will expand the model to introduce additional complexity to more fit real world implementations. "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
