{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Perlin spontaneous\n",
    "\n",
    "Author: Sebastian Spreizer\n",
    "\n",
    "The MIT License"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib notebook\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import nest\n",
    "import noise\n",
    "import numpy as np\n",
    "\n",
    "import lib.connectivity_map as cm\n",
    "import lib.lcrn_network as lcrn\n",
    "import lib.animation as animation\n",
    "import lib.plot3d as pl3d\n",
    "import lib.colormap as cmap"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Perlin landscape for connectivity"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Network size\n",
    "nrow = ncol = 100\n",
    "npop = nrow * ncol                 # amount of neurons in population\n",
    "\n",
    "landscape = cm.Perlin(nrow, size=3)\n",
    "landscape = np.round(landscape*7).astype(int)\n",
    "move = cm.move(nrow)\n",
    "\n",
    "fig,ax = plt.subplots(1,1)\n",
    "im = ax.matshow(landscape.reshape(nrow,-1), cmap=cmap.virno())\n",
    "plt.colorbar(im, ax=ax)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Set Kernel Status"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.random.seed(0)\n",
    "nest.ResetKernel()\n",
    "nest.SetKernelStatus({\n",
    "    'local_num_threads': 4,\n",
    "    'resolution': 0.1,\n",
    "})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Create nodes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pop = nest.Create('iaf_psc_alpha', npop, params={\n",
    "    \"C_m\":      250.0,\n",
    "    \"E_L\":      -70.0,\n",
    "    \"V_reset\":  -70.0,\n",
    "    \"V_th\":     -55.0,\n",
    "    \"t_ref\":      2.0,\n",
    "    \"tau_m\":     10.0,\n",
    "    \"tau_minus\": 20.0,\n",
    "    \"tau_syn_ex\": 5.0,\n",
    "    \"tau_syn_in\": 5.0,\n",
    "})\n",
    "\n",
    "# Create input devices\n",
    "ng = nest.Create('noise_generator')\n",
    "\n",
    "# Create recording devices\n",
    "sd = nest.Create('spike_detector', params={\n",
    "    'start':      0.0,\n",
    "})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Connect nodes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "offset = pop[0]\n",
    "kappa = 4\n",
    "theta = 3\n",
    "shift = 1\n",
    "ncon = 1000\n",
    "\n",
    "# Connect neurons\n",
    "for ii in range(npop):\n",
    "    source = ii, nrow, ncol, nrow, ncol, ncon, kappa, theta\n",
    "    targets, delay = lcrn.lcrn_gamma_targets(*source)\n",
    "    if landscape is not None:          # asymmetry\n",
    "        targets = (targets + shift * move[landscape[ii] % len(move)]) % npop\n",
    "    # no selfconnections\n",
    "    targets = targets[targets != ii]\n",
    "    nest.Connect([pop[ii]], (targets + offset).tolist(), syn_spec={'weight': -10.0})\n",
    "\n",
    "# Connect device to neurons\n",
    "nest.Connect(ng, pop, syn_spec={'weight': 10.0})\n",
    "nest.Connect(pop, sd)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Warming up"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nest.SetStatus(ng, params={'std': 50.})\n",
    "nest.Simulate(250.)\n",
    "nest.SetStatus(ng, params={'mean': 70., 'std': 10.})\n",
    "nest.Simulate(250.)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Start simulation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nest.SetStatus(ng, params={'mean': 70., 'std': 10.})\n",
    "nest.Simulate(1000.)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Plot spiking activity"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sdE = nest.GetStatus(sd, 'events')[0]\n",
    "ts, gids = sdE['times'], sdE['senders']\n",
    "fig, ax = plt.subplots(1,1, dpi=100)\n",
    "ax.plot(ts, gids, 'k|')\n",
    "ax.set_xlabel('Time [ms]')\n",
    "ax.set_ylabel('Neuron')\n",
    "i = 3000\n",
    "ax.set_ylim(i,i+1000)\n",
    "ax.set_xlim(500,1500)\n",
    "#fig.savefig('sequence_raster_plot.pdf', dpi=300)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "idx = gids - offset < npop\n",
    "gids, ts = gids[idx], ts[idx]\n",
    "time = nest.GetKernelStatus('time')\n",
    "\n",
    "ts_bins = np.arange(time-1000., time, 50.)\n",
    "h = np.histogram2d(ts, gids - offset, bins=[ts_bins, range(npop + 1)])[0]\n",
    "hh = h.reshape(-1, nrow, ncol)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(1)\n",
    "ax.imshow(hh[0], vmin=0, vmax=np.max(hh))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(1)\n",
    "im = ax.imshow(hh[0], vmin=0, vmax=np.max(hh))\n",
    "\n",
    "anim = animation.imshow(fig, ax, im, hh, ts_bins)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "animation.HTML(anim.to_jshtml())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig,ax = pl3d.scatter(ts,gids%nrow,gids//nrow)\n",
    "ax.set_xlim(500,1500)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}