{
 "metadata": {
  "name": "weights_from_geojson"
 },
 "nbformat": 3,
 "nbformat_minor": 0,
 "worksheets": [
  {
   "cells": [
    {
     "cell_type": "heading",
     "level": 2,
     "metadata": {},
     "source": [
      "Prototyping the construction of PySAL weights from geojson. Supports local files, uri, and serialized objects\n",
      "\n"
     ]
    },
    {
     "cell_type": "raw",
     "metadata": {},
     "source": [
      "Author: Sergio Rey <sjsrey@gmail.com>"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "import geojson\n",
      "import pysal as ps\n",
      "import urllib2 as urllib"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 1
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "class PolygonCollection:\n",
      "    def __init__(self, polygons, bbox=None):\n",
      "        \"\"\"\n",
      "\n",
      "        Parameters\n",
      "        ==========\n",
      "        polygons: dict\n",
      "                  key is polygon Id, value is PySAL Polygon object\n",
      "        bbox: list (optional)\n",
      "              [left, lower, right, upper]\n",
      "\n",
      "        Notes\n",
      "        =====\n",
      "        bbox is supported in geojson specification at both the feature and feature collection level. However, not all geojson writers generate the bbox at the feature collection level. \n",
      "        In those cases, the bbox property will be set on initial access.\n",
      "\n",
      "        \"\"\"\n",
      "              \n",
      "        self.type=ps.cg.Polygon\n",
      "        self.n = len(polygons)\n",
      "        self.polygons = polygons\n",
      "        if bbox is None:\n",
      "            self._bbox = None\n",
      "        else:\n",
      "            self._bbox = bbox\n",
      "            \n",
      "    @property\n",
      "    def bbox(self):\n",
      "        bboxes = np.array([self.polygons[p].bbox for p in self.polygons])\n",
      "        mins = bboxes.min(axis=0)\n",
      "        maxs = bboxes.max(axis=0)\n",
      "        self._bbox = [ mins[0], mins[1], maxs[2], maxs[3] ]\n",
      "        return self._bbox\n",
      "        \n",
      "    \n",
      "    def __getitem__(self, index):\n",
      "        return self.polygons[index]\n",
      "            "
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 2
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "def queen_geojson(gjobj):\n",
      "    \"\"\"\n",
      "    Constructs a PySAL queen contiguity W from a geojson object\n",
      "\n",
      "    \"\"\"\n",
      "    polys = []\n",
      "    ids = []\n",
      "    i = 0\n",
      "    for feature in gjobj['features']:\n",
      "        polys.append(ps.cg.asShape(geojson.Polygon(feature['geometry']['coordinates'])))\n",
      "        ids.append(i)\n",
      "        i += 1\n",
      "    polygons = PolygonCollection(dict(zip(ids,polys)))\n",
      "    neighbors = ps.weights.Contiguity.ContiguityWeightsPolygons(polygons).w\n",
      "    return ps.W(neighbors)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 3
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "def queen_from_geojson(uri):\n",
      "    gjobj = geojson.load(urllib.urlopen(uri))\n",
      "    return queen_geojson(gjobj)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 4
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "def queen_from_geojsons(s):\n",
      "    return queen_geojson(info)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 5
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "def queen_from_geojsonf(fileName):\n",
      "    fp = open(fileName)\n",
      "    obj = geojson.load(fp)\n",
      "    fp.close()\n",
      "    return queen_geojson(obj)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 6
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# from a uri\n",
      "uri = \"http://toae.org/pub/columbus.json\""
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 7
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "wq = queen_from_geojson(uri)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 8
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "wq.n"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "pyout",
       "prompt_number": 9,
       "text": [
        "49"
       ]
      }
     ],
     "prompt_number": 9
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# from a local file\n",
      "wf = queen_from_geojsonf(ps.examples.get_path(\"columbus.json\"))"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 10
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "wf.n"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "pyout",
       "prompt_number": 11,
       "text": [
        "49"
       ]
      }
     ],
     "prompt_number": 11
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# from a serialized geojson object\n",
      "\n",
      "fp = open(ps.examples.get_path(\"columbus.json\"))\n",
      "info = geojson.load(fp)\n",
      "fp.close()\n",
      "infos = geojson.dumps(info)\n",
      "ws = queen_from_geojsons(infos)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 12
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "ws.n"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "pyout",
       "prompt_number": 13,
       "text": [
        "49"
       ]
      }
     ],
     "prompt_number": 13
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "wf.neighbors == ws.neighbors"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "pyout",
       "prompt_number": 14,
       "text": [
        "True"
       ]
      }
     ],
     "prompt_number": 14
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "wq.neighbors == wf.neighbors"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "pyout",
       "prompt_number": 15,
       "text": [
        "True"
       ]
      }
     ],
     "prompt_number": 15
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [],
     "language": "python",
     "metadata": {},
     "outputs": []
    }
   ],
   "metadata": {}
  }
 ]
}