{
 "metadata": {
  "name": ""
 },
 "nbformat": 3,
 "nbformat_minor": 0,
 "worksheets": [
  {
   "cells": [
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "# IPython Notebook\n",
      "\n",
      "This is an IPython Notebook, an online scientific notebook which combines, text, data, images, and programming. It is amazing, and could be a fantastic way to do and communicate advanced LCA work.\n",
      "\n",
      "* [Documentation](http://ipython.org/ipython-doc/dev/interactive/htmlnotebook.html)\n",
      "* [Very long awesomeness](https://www.youtube.com/watch?v=2G5YTlheCbw)\n",
      "* [Sharable awesomeness](http://nbviewer.ipython.org/)\n",
      "* [Just plain amazing awesomeness](http://nbviewer.ipython.org/url/epi.whoi.edu/esr/GIS_GRASS-R_Example.ipynb)\n",
      "* [Gallery of awesomeness](https://github.com/ipython/ipython/wiki/A-gallery-of-interesting-IPython-Notebooks)\n",
      "* [Hacker News discussion](http://news.ycombinator.com/item?id=4909070)\n",
      "\n",
      "You can also download the [ipython file](/examples/export-matrices.ipynb) and run it yourself."
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "# Export technosphere and biosphere matrices\n",
      "\n",
      "This notebook shows how it is at least relatively easy to export matrices from an LCA calculation."
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Import needed functionality"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "from brightway2 import *\n",
      "from openpyxl.workbook import Workbook\n",
      "from openpyxl.writer.excel import ExcelWriter\n",
      "from openpyxl.cell import get_column_letter"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 1
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Create a workbook and first worksheet"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "wb = Workbook()\n",
      "ws = wb.worksheets[0]\n",
      "ws.title = \"tech-matrix\""
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 2
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Helper function to write spreadsheet cell"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "def write_cell(ws, x, y, value):\n",
      "    \"\"\"Write `value` to cell (x,y), translating to column letters\"\"\"\n",
      "    col = get_column_letter(y)\n",
      "    code = \"%s%s\" % (col, x)\n",
      "    ws.cell(code).value = value"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 3
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Set up LCA object to get technosphere and biosphere matrices"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "ecoinvent = Database(\"ecoinvent 2.2\")\n",
      "key = ecoinvent.random()\n",
      "ei = ecoinvent.load()\n",
      "lca = LCA({key: 1})\n",
      "lca.lci()\n",
      "lca.fix_dictionaries()"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 4
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "print repr(lca.technosphere_matrix)\n",
      "print repr(lca.biosphere_matrix)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "<4087x4087 sparse matrix of type '<type 'numpy.float64'>'\n",
        "\twith 43045 stored elements in Compressed Sparse Row format>\n",
        "<1613x4087 sparse matrix of type '<type 'numpy.float64'>'\n",
        "\twith 92847 stored elements in Compressed Sparse Row format>\n"
       ]
      }
     ],
     "prompt_number": 5
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "The technosphere rows and columns are not ordered - lets sort them to make our output nicer"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "HEADERS = [\"name\", \"categories\", \"unit\", \"location\", \"ecoinvent code\"]\n",
      "\n",
      "def get_metadata(key):\n",
      "    ds = Database(key[0]).load()[key]\n",
      "    return [\n",
      "        ds['name'],\n",
      "        \"-\".join(ds.get('categories', [])),\n",
      "        ds.get('unit', ''),\n",
      "        ds.get('location', 'GLO'),\n",
      "        ds.get('code', '')\n",
      "    ]\n",
      "\n",
      "# translate ('ecoinvent 2.2', 'some-id') to [name, categories, etc.]\n",
      "technosphere_keys_to_metadata = {key: get_metadata(key) for key in lca.technosphere_dict}\n",
      "# translate ('ecoinvent 2.2', 'some-id') to some integer [0, 4086] based on sort order (name, categories, etc.)\n",
      "technosphere_keys_to_order = {j[1]: i for i, j in \n",
      "                              enumerate(sorted([\n",
      "                                      (v, k) for k, v in technosphere_keys_to_metadata.iteritems()\n",
      "                                      ]))\n",
      "                              }\n",
      "# Translate sort order to ('ecoinvent 2.2', 'some-id')\n",
      "technosphere_order_to_keys = {v: k for k, v in technosphere_keys_to_order.iteritems()}\n",
      "# translate technosphere row/col index to sort order\n",
      "technosphere_rows_to_order = {lca.technosphere_dict[key]: technosphere_keys_to_order[key] for key in lca.technosphere_dict}"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 6
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "## Write technosphere"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "for row in xrange(lca.technosphere_matrix.shape[0]):\n",
      "    if row and not row % 500:\n",
      "        print row\n",
      "    for col in xrange(lca.technosphere_matrix.shape[0]):\n",
      "        if row == col:\n",
      "            continue\n",
      "        value = lca.technosphere_matrix[row, col]\n",
      "        if value:\n",
      "            x = technosphere_rows_to_order[row] + 1\n",
      "            y = technosphere_rows_to_order[col] + 1\n",
      "            write_cell(ws, x, y, -1 * value)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "500\n",
        "1000"
       ]
      },
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "\n",
        "1500"
       ]
      },
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "\n",
        "2000"
       ]
      },
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "\n",
        "2500"
       ]
      },
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "\n",
        "3000"
       ]
      },
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "\n",
        "3500"
       ]
      },
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "\n",
        "4000"
       ]
      },
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "\n"
       ]
      }
     ],
     "prompt_number": 7
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Write index sheet, linking rows/columns to process metadata"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "ws = wb.create_sheet()\n",
      "ws.title = 'tech-key'\n",
      "\n",
      "# Rows start at 1, not 0\n",
      "def write_row(ws, row, data):\n",
      "    for i in xrange(len(data)):\n",
      "        write_cell(ws, row, i + 1, data[i])\n",
      "\n",
      "write_row(ws, 1, HEADERS)\n",
      "\n",
      "# + 2 because rows start at 1, row 1 already taken by headers\n",
      "for index in xrange(lca.technosphere_matrix.shape[0]):\n",
      "    key = technosphere_order_to_keys[index]\n",
      "    metadata = technosphere_keys_to_metadata[key]\n",
      "    write_row(ws, index + 2, metadata)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 8
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "## Write biosphere"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "biosphere_keys_to_metadata = {key: get_metadata(key) for key in lca.biosphere_dict}\n",
      "biosphere_keys_to_order = {j[1]: i for i, j in \n",
      "                              enumerate(sorted([\n",
      "                                      (v, k) for k, v in biosphere_keys_to_metadata.iteritems()\n",
      "                                      ]))\n",
      "                              }\n",
      "biosphere_order_to_keys = {v: k for k, v in biosphere_keys_to_order.iteritems()}\n",
      "biosphere_rows_to_order = {lca.biosphere_dict[key]: biosphere_keys_to_order[key] for key in lca.biosphere_dict}"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 9
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "ws = wb.create_sheet()\n",
      "ws.title = \"bio-matrix\""
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 10
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "for row in xrange(lca.biosphere_matrix.shape[0]):\n",
      "    if row and not row % 200:\n",
      "        print row\n",
      "    for col in xrange(lca.biosphere_matrix.shape[1]):\n",
      "        if row == col:\n",
      "            continue\n",
      "        value = lca.biosphere_matrix[row, col]\n",
      "        if value:\n",
      "            x = biosphere_rows_to_order[row] + 1\n",
      "            y = technosphere_rows_to_order[col] + 1\n",
      "            write_cell(ws, x, y, value)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "200\n",
        "400"
       ]
      },
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "\n",
        "600"
       ]
      },
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "\n",
        "800"
       ]
      },
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "\n",
        "1000"
       ]
      },
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "\n",
        "1200"
       ]
      },
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "\n",
        "1400"
       ]
      },
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "\n",
        "1600"
       ]
      },
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "\n"
       ]
      }
     ],
     "prompt_number": 14
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "ws = wb.create_sheet()\n",
      "ws.title = 'bio-key'\n",
      "\n",
      "write_row(ws, 1, HEADERS)\n",
      "\n",
      "# + 2 because rows start at 1, row 1 already taken by headers\n",
      "for index in xrange(lca.biosphere_matrix.shape[0]):\n",
      "    key = biosphere_order_to_keys[index]\n",
      "    metadata = biosphere_keys_to_metadata[key]\n",
      "    write_row(ws, index + 2, metadata)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 15
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "wb.save(filename=\"ecoinvent 2.2.xlsx\")"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 16
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 16
    }
   ],
   "metadata": {}
  }
 ]
}