{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from svg_model import svg_polygons_to_df\n",
    "from path_helpers import path\n",
    "from svg_model.tesselate import tesselate_shapes_frame\n",
    "from svg_model.plot import plot_shapes\n",
    "from svg_model.point_query import get_shapes_pymunk_space\n",
    "\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "device_svg = 'static/device.svg'\n",
    "\n",
    "# Read SVG polygons into dataframe, one row per polygon vertex.\n",
    "df_electrodes = svg_polygons_to_df(device_svg)\n",
    "\n",
    "# Tesselate electrode polygons into convex shapes (triangles), for\n",
    "# compatability with `pymunk`.\n",
    "df_electrode_tesselations = tesselate_shapes_frame(df_electrodes, ['path_id'])\n",
    "\n",
    "# Create `pymunk` space and add a body for each convex shape.  Each\n",
    "# body is mapped to the original `path_id` through `electrode_bodies`.\n",
    "electrodes_space, electrode_bodies = \\\n",
    "    get_shapes_pymunk_space(df_electrode_tesselations,\n",
    "                            ['path_id', 'triangle_i'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "axis = plot_shapes(df_electrode_tesselations, ['path_id', 'triangle_i'],\n",
    "                   fc='none')\n",
    "plot_shapes(df_electrodes, ['path_id'], alpha=.3, axis=axis)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "shape = electrodes_space.point_query_first((275, 100))\n",
    "if shape:\n",
    "    print electrode_bodies[shape.body]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def extract_channels(svg_source, shapes_canvas, electrode_layer='Device',\n",
    "                     electrode_xpath=None, namespaces=None):\n",
    "    '''\n",
    "    Load the channels associated with each electrode from the device layer of\n",
    "    an SVG source.\n",
    "    \n",
    "    For each electrode polygon, the channels are read as a\n",
    "    comma-separated list from the `\"data-channels\"` attribute.\n",
    "\n",
    "    Args:\n",
    "\n",
    "        svg_source (filepath) : Input SVG file containing connection lines.\n",
    "        shapes_canvas (shapes_canvas.ShapesCanvas) : Shapes canvas containing\n",
    "            shapes to compare against connection endpoints.\n",
    "        electrode_layer (str) : Name of layer in SVG containing electrodes.\n",
    "        electrode_xpath (str) : XPath string to iterate throught electrodes.\n",
    "        namespaces (dict) : SVG namespaces (compatible with `etree.parse`).\n",
    "\n",
    "    Returns:\n",
    "\n",
    "        (pandas.Series) : Each entry corresponds to a list of channels\n",
    "            connected to an electrode, where electrodes are indexed by `\"id\"`\n",
    "            attribute of the corresponding SVG polygon.\n",
    "    '''\n",
    "    from lxml import etree\n",
    "    from svg_model import INKSCAPE_NSMAP\n",
    "    \n",
    "    if namespaces is None:\n",
    "        namespaces = INKSCAPE_NSMAP\n",
    "\n",
    "    e_root = etree.parse(svg_source)\n",
    "    frames = []\n",
    "\n",
    "    if electrode_xpath is None:\n",
    "        electrode_xpath = (\"//svg:g[@inkscape:label='%s']/svg:polygon\"\n",
    "                           % electrode_layer)\n",
    "\n",
    "    for electrode_i in e_root.xpath(electrode_xpath, namespaces=namespaces):\n",
    "        channels_i = map(int, electrode_i.attrib.get('data-channels', '').split(','))\n",
    "        frames.append([electrode_i.attrib['id'], channels_i])\n",
    "        \n",
    "    if frames:\n",
    "        df_channels = pd.DataFrame(frames, columns=['electrode_id', 'channels'])\n",
    "    else:\n",
    "        df_channels = pd.DataFrame(None, columns=['electrode_id', 'channels'])\n",
    "        \n",
    "    electrode_channels = df_channels.set_index('electrode_id')['channels']\n",
    "    return electrode_channels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from lxml import etree\n",
    "from svg_model import INKSCAPE_NSMAP\n",
    "\n",
    "svg_source = 'static/device.svg'\n",
    "electrode_layer='Device'\n",
    "electrode_xpath=None\n",
    "namespaces=None\n",
    "\n",
    "    if namespaces is None:\n",
    "        namespaces = INKSCAPE_NSMAP\n",
    "\n",
    "    e_root = etree.parse(svg_source)\n",
    "    frames = []\n",
    "\n",
    "    if electrode_xpath is None:\n",
    "        electrode_xpath = (\"//svg:g[@inkscape:label='%s']/svg:polygon\"\n",
    "                           % electrode_layer)\n",
    "\n",
    "    for electrode_i in e_root.xpath(electrode_xpath, namespaces=namespaces):\n",
    "        channels_i = map(int, electrode_i.attrib.get('data-channels', '').split(','))\n",
    "        frames.append([electrode_i.attrib['id'], channels_i])\n",
    "\n",
    "    electrode_channels = (pd.DataFrame(frames, columns=['electrode_id', 'channels'])\n",
    "                          .set_index('electrode_id')['channels'])\n",
    "    return electrode_channels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from microdrop.dmf_device import DmfDevice\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "dmf_device = DmfDevice('static/device.svg')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "electrode_areas = dmf_device.get_electrode_areas()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0])"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "electrode_counts = dmf_device.df_electrode_channels.groupby('channel').count()\n",
    "channels = np.zeros(dmf_device.max_channel() + 1, dtype=int)\n",
    "channels[electrode_counts[electrode_counts.electrode_id > 1].index.values] = 1\n",
    "channels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "path_id\n",
       "electrode57    10547.10805\n",
       "electrode58    10543.04450\n",
       "electrode73    10546.99000\n",
       "electrode74    10551.05450\n",
       "Name: area, dtype: float64"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "actuated_channels_index = np.where(channels > 0)[0]\n",
    "actuated_electrodes = (dmf_device.df_electrode_channels.set_index('channel')\n",
    "                       ['electrode_id'].ix[actuated_channels_index])\n",
    "dmf_device.electrode_areas[actuated_electrodes.values]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import cPickle as pickle"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "len(pickle.dumps(dmf_device, -1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "np.concatenate(electrode_channels.values).max()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from svg_model.data_frame import get_shape_areas\n",
    "\n",
    "get_shape_areas(df_electrodes, 'path_id')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "np.random.seed(0)\n",
    "d = np.random.randint(0, 2, 10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "electrode_channels[np.where(d > 0)[0]]"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
