{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Microcircuit firing rates\n\nHere we calculate the firing rates of the :cite:t:`potjans2014` microcircuit\nmodel.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import nnmt\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\n\n# import svgutils for inserting sketch if available\ntry:\n    import os\n    import svgutils.transform as sg\n    insert_sketch = True\nexcept ImportError:\n    insert_sketch = False\n\n# use matplotlib style file\nplt.style.use('frontiers.mplstyle')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "First we create a network model of the microcircuit, passing the parameter\nyaml file.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "microcircuit = nnmt.models.Microcircuit(\n    '../../tests/fixtures/integration/config/Bos2016_network_params.yaml')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Then we simply calculate the firing rates for exponentially shape post\nsynaptic currents, by calling the respective function and passing the\nmicrocircuit. Here we chose to use the 'taylor' method for calculating the\nfiring rates.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "firing_rates = nnmt.lif.exp.firing_rates(microcircuit, method='shift')\n\nprint(f'Mean rates: {firing_rates}')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Then we compare the rates to the publicated data from :cite:t:`bos2016`. We\nload the simulated rates using the data stored as integration test fixtures.\nNote that the original data use rates in 1/ms, which we need to convert to\nHz.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fix_path = '../../tests/fixtures/integration/data/'\nresult = nnmt.input_output.load_h5(\n    fix_path + 'Bos2016_publicated_and_converted_data.h5')\nsimulated_rates = result['fig_microcircuit']['rates_sim'] * 1000\n\nprint(f'Mean simulated rates: {simulated_rates}')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Finally, we plot the rates together in one plot.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "width = 0.03937007874 * 85\nheight = width * 1.3\n\nfig = plt.figure(figsize=(width, height),\n                 tight_layout=True)\n\nsim_colors = ['#4c72b0', '#c44e52']\nthy_color = '#ff8f2fff'\n\nax0 = plt.subplot2grid((5, 1), (0, 0), rowspan=3, colspan=1)\nax0.set_axis_off()\nax1 = plt.subplot2grid((5, 1), (3, 0), rowspan=2, colspan=1)\n\n# add labels to panels\naxs = [ax0, ax1]\nlabel = ['(A)', '(B)']\ny_pos = [1.25, 1.1]\nfor n, ax in enumerate(axs):\n    ax.text(-0.1, y_pos[n], label[n], transform=ax.transAxes,\n            size=11, weight='bold')\n\n\nbars = ax1.bar(np.arange(8), simulated_rates,\n               align='center', color=sim_colors[1])\n\nfor i in [0, 2, 4, 6]:\n    bars[i].set_color(sim_colors[0])\n\nnnmt_handle = ax1.scatter(np.arange(8), firing_rates, marker='X',\n                          color=thy_color, s=50, zorder=10)\nax1.set_xticks(np.arange(8))\nax1.set_xticklabels(['2/3E', '2/3I', '4E', '4I', '5E', '5I', '6E', '6I'])\nax1.set_yticks([1, 3, 5, 7])\nax1.set_ylabel(r'rate $\\nu\\,(1/s)$')\n\nplt.legend([bars[0], nnmt_handle, bars[1]],\n           [None, 'theory', 'simulation'],\n           loc='upper left', fontsize=9, ncol=2,\n           columnspacing=-2.8, handletextpad=0.2)\n\n# insert sketch using svgutil, try saving as pdf using inkscape\nif insert_sketch:\n    sketch_fn = 'microcircuit_sketch.svg'\n    plot_fn = 'microcircuit_rates'\n    svg_mpl = sg.from_mpl(fig, savefig_kw=dict(transparent=False))\n    w_svg, h_svg = svg_mpl.get_size()\n    svg_mpl.set_size((w_svg+'pt', h_svg+'pt'))\n    svg_sketch = sg.fromfile(sketch_fn).getroot()\n    svg_sketch.moveto(x=30, y=10, scale_x=0.61, scale_y=0.61)\n    svg_mpl.append(svg_sketch)\n    svg_mpl.save(f'{plot_fn}.svg')\n    os_return = os.system(f'inkscape --export-pdf={plot_fn}.pdf {plot_fn}.svg')\n    if os_return == 0:\n        os.remove(f'{plot_fn}.svg')\n    else:\n        print('Conversion to pdf using inkscape failed, keeping svg...')\n\nax0.annotate('(sketch)', xy=(0.35, 0.6))\nplt.show()"
      ]
    }
  ],
  "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.9.12"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}