{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import re\n",
    "\n",
    "from lxml import etree\n",
    "from path_helpers import path\n",
    "import svg_model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#  Set path to device SVG file"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# device_path = path(r'<path to>\\device.svg')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#  Open device directory in file manager"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "os.startfile(device_path.parent)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Assign `data-channels` attr of electrodes `svg:path` based on electrode index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "cre_index = re.compile(r'electrode(?P<index>\\d+)')\n",
    "xml_root = etree.parse(device_path)\n",
    "\n",
    "electrode_xpath = '//svg:g[@inkscape:label=\"Device\"]/svg:path[starts-with(@id, \"electrode\")]'\n",
    "\n",
    "# Assign `data-channels` attribute of each electrode `svg:path` based on electrode index.\n",
    "for electrode_i in xml_root.xpath(electrode_xpath, namespaces=svg_model.INKSCAPE_NSMAP):\n",
    "    match = cre_index.match(electrode_i.attrib['id'])\n",
    "    electrode_i.attrib['data-channels'] = str(int(match.group('index')))\n",
    "\n",
    "# Rename original file to `<original name>.original.svg`\n",
    "device_path.rename('%s.original.svg' % device_path.namebase)\n",
    "\n",
    "# Write result to original path.\n",
    "with device_path.open('wb') as output:\n",
    "    output.write(etree.tounicode(xml_root))"
   ]
  }
 ],
 "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
}
