<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Azavea Labs</title>
	<atom:link href="http://www.azavea.com/blogs/labs/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.azavea.com/blogs/labs</link>
	<description>Insight on what our engineers are doing</description>
	<lastBuildDate>Thu, 10 May 2012 17:35:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>Modeling Urban Forest Growth</title>
		<link>http://www.azavea.com/blogs/labs/2012/05/modeling-urban-forest-growth/</link>
		<comments>http://www.azavea.com/blogs/labs/2012/05/modeling-urban-forest-growth/#comments</comments>
		<pubDate>Thu, 10 May 2012 17:35:02 +0000</pubDate>
		<dc:creator>Deb Boyer</dc:creator>
				<category><![CDATA[Posts]]></category>
		<category><![CDATA[urban forestry]]></category>

		<guid isPermaLink="false">http://www.azavea.com/blogs/labs/?p=1940</guid>
		<description><![CDATA[As part of a USDA Small Business Innovation Research Phase 1 grant, we recently developed the Urban Forest Modeling and Prioritization Toolkit, a prototype web-based tool that enables users to select and weight various parameters such as population density, urban heat island temperatures, health data, and biodiversity statistics that could potentially affect where trees were [...]]]></description>
			<content:encoded><![CDATA[<p>As part of a <a href="http://www.csrees.usda.gov/funding/sbir/sbir.html">USDA Small Business Innovation Research Phase 1 grant</a>, we recently developed the Urban Forest Modeling and Prioritization Toolkit, a prototype web-based tool that enables users to select and weight various parameters such as population density, urban heat island temperatures, health data, and biodiversity statistics that could potentially affect where trees were planted. A more general overview of the project is available in <a href="http://www.azavea.com/blogs/atlas/2012/04/exploring-urban-forestry-modeling/">an entry on Azavea Atlas</a>, but we wanted to go into more detail here about some of the calculations used in the software. Thanks to <a href="http://www.azavea.com/about-us/staff-profiles/carissa-brittain/">Carissa Brittain</a> and <a href="http://www.azavea.com/about-us/staff-profiles/adam-hinz/">Adam Hinz</a>, the developers on the project, for pulling together these notes.</p>
<p>The application is divided into two areas: modeling location (determining where to plant trees) and modeling growth (extrapolating future benefits).</p>
<p><strong>Modeling Location</strong></p>
<p>To create heat maps that would indicate the best planting locations based on selected factors, we used a two-level weighted overlay algorithm that takes the following parameters:</p>
<p><a href="http://www.azavea.com/blogs/labs/2012/05/modeling-urban-forest-growth/location_parameters/" rel="attachment wp-att-1947"><img class="alignnone size-medium wp-image-1947" title="Location_Parameters" src="http://www.azavea.com/blogs/labs/wp-content/uploads/2012/05/Location_Parameters-475x109.png" alt="" width="475" height="109" /></a></p>
<p>Using these parameters, we define a decision raster as any function <img src='http://s0.wp.com/latex.php?latex=R%3A%5Cmathbb%7BZ%7D%5Ctimes%5Cmathbb%7BZ%7D%5Crightarrow%5Cmathbb%7BZ%7D%5Ccup%5C%7B+%5Cemptyset+%5C%7D&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='R:&#92;mathbb{Z}&#92;times&#92;mathbb{Z}&#92;rightarrow&#92;mathbb{Z}&#92;cup&#92;{ &#92;emptyset &#92;}' title='R:&#92;mathbb{Z}&#92;times&#92;mathbb{Z}&#92;rightarrow&#92;mathbb{Z}&#92;cup&#92;{ &#92;emptyset &#92;}' class='latex' /> where <img src='http://s0.wp.com/latex.php?latex=%5Cemptyset&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;emptyset' title='&#92;emptyset' class='latex' /> represents the &#8220;no data&#8221; element of the raster. Operations <img src='http://s0.wp.com/latex.php?latex=%28%2B%2C-%2C%5Ctimes%2C%2F%29&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='(+,-,&#92;times,/)' title='(+,-,&#92;times,/)' class='latex' /> involving <img src='http://s0.wp.com/latex.php?latex=%5Cemptyset&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;emptyset' title='&#92;emptyset' class='latex' /> as a parameter always return <img src='http://s0.wp.com/latex.php?latex=%5Cemptyset&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;emptyset' title='&#92;emptyset' class='latex' />. We also define other convenience operations:</p>
<p><img src='http://s0.wp.com/latex.php?latex=Max%28R%29&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='Max(R)' title='Max(R)' class='latex' /> returns maximum value in the raster,</p>
<p><img src='http://s0.wp.com/latex.php?latex=Min%28R%29&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='Min(R)' title='Min(R)' class='latex' /> returns the minimum value in the raster,</p>
<p><img src='http://s0.wp.com/latex.php?latex=R%27%28x%2Cy%29+%3D+%5Ctext%7BNorm%7D%28R%28x%2Cy%29%29&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='R&#039;(x,y) = &#92;text{Norm}(R(x,y))' title='R&#039;(x,y) = &#92;text{Norm}(R(x,y))' class='latex' /> normalizes the input raster <img src='http://s0.wp.com/latex.php?latex=R&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='R' title='R' class='latex' /> such that <img src='http://s0.wp.com/latex.php?latex=R%27%28x%2Cy%29+%3D+%5Cfrac%7BR%28x%2Cy%29+-+%5Ctext%7BMin%7D%28R%29%7D%7B%5Ctext%7BMax%7D%28R%29+-+%5Ctext%7BMin%7D%28R%29%7D%5Ctimes+100&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='R&#039;(x,y) = &#92;frac{R(x,y) - &#92;text{Min}(R)}{&#92;text{Max}(R) - &#92;text{Min}(R)}&#92;times 100' title='R&#039;(x,y) = &#92;frac{R(x,y) - &#92;text{Min}(R)}{&#92;text{Max}(R) - &#92;text{Min}(R)}&#92;times 100' class='latex' /></p>
<p>&nbsp;<br />
The weighted overlay algorithm has two phases. The first phase calculates the weighted average of each group as a new raster and then normalizes the result to between 0 and 100.</p>
<p style="text-align: center;"><a href="http://www.azavea.com/blogs/labs/2012/05/modeling-urban-forest-growth/location_algorithm/" rel="attachment wp-att-1953"><img class="size-full wp-image-1953 aligncenter" title="Location_Algorithm" src="http://www.azavea.com/blogs/labs/wp-content/uploads/2012/05/Location_Algorithm.png" alt="" width="365" height="135" /></a></p>
<p>Then we calculate the final weighted raster:</p>
<pre><img src='http://s0.wp.com/latex.php?latex=W%28x%2Cy%29+%3D+%5Cfrac%7B1%7D%7B%5Csum_%7Bg%5Cin+G%7D%5Cbeta_g%7D%5Csum_%7Bg%5Cin+G%7D%5Cbeta_%7Bg%7DW_g%28x%2Cy%29&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='W(x,y) = &#92;frac{1}{&#92;sum_{g&#92;in G}&#92;beta_g}&#92;sum_{g&#92;in G}&#92;beta_{g}W_g(x,y)' title='W(x,y) = &#92;frac{1}{&#92;sum_{g&#92;in G}&#92;beta_g}&#92;sum_{g&#92;in G}&#92;beta_{g}W_g(x,y)' class='latex' /></pre>
<p style="text-align: center;">
<p>For Philadelphia, we created rasters from the data shown in the last equation. Our general process was to rasterize each dataset (if not already rasterized) and resample to a 10 meter resolution. To allow for comparability between disjointed datasets, we chose to normalize data to a 0-100 range and picked 100 to mean &#8220;an ideal place to plant trees.&#8221;</p>
<p>The goal the decision model is to allow the end user to prioritize the factors that they would like to affect by planting trees. Perhaps an organization wants to impact crime and heat island effects. Figure 1 shows the base crime raster. Green indicates good places to plant according to this raster, meaning areas of high crime rates that could be effected by the existence of more trees. As studies (by Kuo and Sullivan (2001) among others) have shown that additional tree planting can result in reduced crime, we would plant in the green areas of this raster in order to potentially reduce crime.</p>
<div id="attachment_1963" class="wp-caption alignnone" style="width: 485px"><a href="http://www.azavea.com/blogs/labs/2012/05/modeling-urban-forest-growth/fig_crime/" rel="attachment wp-att-1963"><img class="size-medium wp-image-1963" title="fig_crime" src="http://www.azavea.com/blogs/labs/wp-content/uploads/2012/05/fig_crime-475x471.png" alt="" width="475" height="471" /></a><p class="wp-caption-text">Figure 1: Crime Raster for Philadelphia</p></div>
<p>Figure 2 shows the scaled temperature of the city based on average summer temperatures calculated using Landsat data. Green areas indicate high temperatures and thus ideal places to plant trees in order to reduce those temperatures. Planting trees can result in a general decrease of temperature, helping to reduce the heat island effect (Akbari et al. (1990)).</p>
<div id="attachment_1966" class="wp-caption alignnone" style="width: 485px"><a href="http://www.azavea.com/blogs/labs/2012/05/modeling-urban-forest-growth/fig_uhi/" rel="attachment wp-att-1966"><img class="size-medium wp-image-1966" title="fig_uhi" src="http://www.azavea.com/blogs/labs/wp-content/uploads/2012/05/fig_uhi-475x460.png" alt="" width="475" height="460" /></a><p class="wp-caption-text">Figure 2: Heat Raster for Philadelphia</p></div>
<p>Figure 3 shows both crime and heat equally weighted. Areas highlighted in green are recommended for planting and represent the areas that contribute the most, on average, to both high crime rates and high temperatures. Planting trees in these locations would thus have the greatest impact on both factors.</p>
<div id="attachment_1967" class="wp-caption alignnone" style="width: 485px"><a href="http://www.azavea.com/blogs/labs/2012/05/modeling-urban-forest-growth/fig_crime_temp/" rel="attachment wp-att-1967"><img class="size-medium wp-image-1967" title="fig_crime_temp" src="http://www.azavea.com/blogs/labs/wp-content/uploads/2012/05/fig_crime_temp-475x496.png" alt="" width="475" height="496" /></a><p class="wp-caption-text">Figure 3: Combined Crime and Heat Raster for Philadelphia</p></div>
<p>After identifying key planting locations, the modeling growth component of the system enables users to determine the long-term economic and ecosystem benefits of trees planted in a certain location. We&#8217;ll walk through the algorithms for that feature in another blog entry.</p>
<p>The USDA grant funded the creation of a prototype application. While we won&#8217;t be releasing a public version of the prototype, you can <a href="http://www.azavea.com/a/urban-forestry-modeling/">sign up for a free demo</a> or contact Deb Boyer at dboyer@azavea.com or 215-701-7506.</p>
<p><strong>The development of the Urban Forestry Modeling and Prioritization Toolkit was funded by a Small Business Innovation Research grant (2011-33610-30511) from the U.S. Department of Agriculture National Institute of Food and Agriculture.  </strong></p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.azavea.com/blogs/labs/2012/05/modeling-urban-forest-growth/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sometimes you feel like using modules</title>
		<link>http://www.azavea.com/blogs/labs/2012/02/sometimes-you-feel-like-using-modules/</link>
		<comments>http://www.azavea.com/blogs/labs/2012/02/sometimes-you-feel-like-using-modules/#comments</comments>
		<pubDate>Tue, 14 Feb 2012 14:25:40 +0000</pubDate>
		<dc:creator>David Middlecamp</dc:creator>
				<category><![CDATA[Posts]]></category>

		<guid isPermaLink="false">http://www.azavea.com/blogs/labs/?p=1874</guid>
		<description><![CDATA[I&#8217;m going to go out on a limb here, and admit I enjoy Javascript. *deep sigh* Okay, now that that&#8217;s out of the way, lets talk about writing good code. As javascript apps mature, the need for organization and modularity becomes more important. The days of simply inlining your code in the HTML, or keeping [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m going to go out on a limb here, and admit I enjoy Javascript.</p>
<p>*deep sigh* Okay, now that that&#8217;s out of the way, lets talk about writing good code.</p>
<p>As javascript apps mature, the need for organization and modularity becomes more important. The days of simply inlining your code in the HTML, or keeping all your code in one giant file, or rolling your own class system are fading. If you&#8217;re experienced with Javascript, you&#8217;ve probably written your own class system at some point, or code loading solution, or had to stitch together plugins for one framework all while your code is written in another. These are all simple solutions to a complex problem, and as is a common theme in software, you probably missed some edge cases. Inlining your code is hard to maintain, and isn&#8217;t modular, developing with a team in a single giant file is a nightmare, and rolling your own class loader means lack of compatibility and dealing with cross browser issues. The truth is until recently your new jQuery plugin was written differently than your nice custom layer for Openlayers, was different from your custom Dojo widget, was&#8230; well you get the point. You couldn&#8217;t expect to write them in the same way, or expect them to arrive at the browser in the same file at the same time. (If you&#8217;ve used Dojo, Ext, OpenLayers, jQuery, or Node.JS then I hope you know what I mean)</p>
<p>So, what&#8217;s a Javascript developer to do? The language is flexible and forgiving, and there hasn&#8217;t been something to standardize your code around, until recently. You might have noticed that the internet is pretty good at coming up with standards for sharing information and software. That&#8217;s why I was excited to see the proposal and development of the AMD API. AMD in this case stands for Asynchronous Module Definition. Basically it&#8217;s a consistent way to package your code, and it makes it significantly easier to reuse later down the road. A number of major Javascript frameworks have already embraced AMD, including jQuery, Node.JS, Dojo, and others, and I&#8217;d like to give you a preview here to hopefully inspire developers to give it a try. More importantly modules, and module loaders are proposed to be part of the spec for the next version of Javascript named &#8220;<a title="Harmony" href="http://wiki.ecmascript.org/doku.php?id=harmony:proposals" target="_blank">Harmony</a>&#8220;, see <a title="Modules" href="http://wiki.ecmascript.org/doku.php?id=harmony:modules" target="_blank">Modules</a>, and <a title="Module Loaders" href="http://wiki.ecmascript.org/doku.php?id=harmony:module_loaders" target="_blank">Module Loaders</a>.</p>
<p>So, you like jQuery, modules, and you&#8217;re ready to open up an example and tinker around? RequireJS has you covered with a great walkthrough here: http://requirejs.org/docs/download.html#samplejquery . I&#8217;d enjoy walking through it on this blog, but it might be beyond the scope of this article. Let me know in the comments if you&#8217;d like to see more about this.</p>
<p>So, I wanted to provide a more complicated example, which I hope will be helpful to those looking to make nicely namespaced, properly constructable objects in Javascript. Lets pretend we had the following spec:</p>
<p>1.) Our class should use a private static dictionary of globally unique names that have been booped.<br />
2.) These should be kept long-term, in localStorage when possible<br />
3.) Our class should accept verbs other than boop, and should be extendable</p>
<p>So, lets get fancy for a second, and design something that is re-usable and modular. I&#8217;m picturing&#8230; A storage class, a smart globally static list class, and our main verb class that is configurable. Lets get to it:</p>
<p>Lets define a basic reusable storage module, something like:</p>
<pre>define('storage', [ ], function( ) {
    //private static in-memory storage
    var _data = {};

    var that = {
        hasLocalStorage: function() { ... }
        set: function(key, value) { ... },
        get: function(key) { ... }
    };

    var ClassConstructor = function(name) {
        if (!name || name == "") { throw "Name not provided"; }
        this.prefix = name;
    };
    $.extend(ClassConstructor.prototype, that);
    return ClassConstructor;
});</pre>
<p><a href="http://dmiddlecamp.github.com/requirejs_example_01/js/storage.js" title="Full Source" target="_blank">Full Source for storage.js</a></p>
<p>and&#8230; lets define a class that uses that storage to maintain a globally unique list:</p>
<pre>define('unique', ['storage'], function(Storage) {
    //private _globally static_ storage object -- will be shared with other instances of "Unique"
    //you probably wouldn't want this for this implementation, but hey, it's an example, so I wanted
    //to show how to do it.
    var _storage = null;

    var that = {
        setIfUnique: function(key) { ... }
    };

    var ClassConstructor = function(name) {
        if (!name || name == "") { throw "Name not provided"; }
        _storage = new Storage(name);
    };
    $.extend(ClassConstructor.prototype, that);
    return ClassConstructor;
});</pre>
<p><a href="http://dmiddlecamp.github.com/requirejs_example_01/js/unique.js" title="Full Source" target="_blank">Full Source for unique.js</a></p>
<p>and&#8230; lets define a class that uses the unique list, and takes a verb to &#8216;boop.&#8217;</p>
<pre>define('booper', ['unique'], function(Unique) {
    var that = {
        //private storage, but not static, local to this object
        _unique: null,
        _verb: 'unset',

        verbObject: function(name) { ...  }
    };

    var ClassConstructor = function(verb) {
        this._verb =  verb || "boop";
        this._unique = new Unique(this._verb);
        this[this._verb] = this.verbObject;
    };
    $.extend(ClassConstructor.prototype, that);
    return ClassConstructor;
});</pre>
<p><a href="http://dmiddlecamp.github.com/requirejs_example_01/js/booper.js" title="Full Source" target="_blank">Full Source for booper.js</a></p>
<p>so, now we just need a basic web page to test this with:</p>
<pre>
&lt;html&gt;
    &lt;head&gt;
        &lt;script data-main="js/index-main.js" src="js/require-jquery.js"&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;h3&gt;Boop em!&lt;/h3&gt;
        &lt;input type="text" id="name" name="name"
            style="width:300px"
            placeholder="Enter name to boop, limit once per name"
        /&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>and how about some basic page code:</p>
<pre>require(["jquery", "booper"], function($, Booper) {

    //prep
    var b = new Booper();

    //events
    var doBoop = function(evt) {
        b.boop( $("#name").val() );
    };

    $("#name").on('change', doBoop);
    $("#btnBoop").on('click', doBoop);
});</pre>
<p><a href="http://dmiddlecamp.github.com/requirejs_example_01/js/index-main.js" title="Full Source" target="_blank">Full Source for index-main.js</a></p>
<p>Putting it all together with a working example:<br />
<a href="http://dmiddlecamp.github.com/requirejs_example_01/" title="Working Example" target="_blank">Working Example!</a></p>
<p>Obviously, this example didn&#8217;t need to be this complicated, but we gained a lot from a little bit of extra work. We&#8217;ve built three easy modules, that can be easily maintained, extended, and reused. We have a hugely open and flexible page, and when we&#8217;re ready for production, we can compact and minify all those files into a single optimized build.</p>
<p>So, you&#8217;ll notice I added a somewhat generic three line chunk at the end of each class module. This is just some basic constructor logic so you get the nice internal reference to &#8216;this&#8217;, and you can initialize new objects with &#8220;new Foo()&#8221;, instead of only having one copy, etc, etc.</p>
<p>I hope you enjoyed this example, and if you&#8217;re interested in Azavea&#8217;s other projects, checkout <a title="our GitHub!" href="https://github.com/azavea" target="_blank">our GitHub!</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.azavea.com/blogs/labs/2012/02/sometimes-you-feel-like-using-modules/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Geoserver Timestamp Styling and PostgreSQL DateTime Fields</title>
		<link>http://www.azavea.com/blogs/labs/2012/02/geoserver-timestamp-styling-and-postgresql-datetime-fields/</link>
		<comments>http://www.azavea.com/blogs/labs/2012/02/geoserver-timestamp-styling-and-postgresql-datetime-fields/#comments</comments>
		<pubDate>Mon, 06 Feb 2012 22:26:54 +0000</pubDate>
		<dc:creator>Carissa Brittain</dc:creator>
				<category><![CDATA[Posts]]></category>
		<category><![CDATA[Django]]></category>
		<category><![CDATA[GeoServer]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[visualization]]></category>

		<guid isPermaLink="false">http://www.azavea.com/blogs/labs/?p=1867</guid>
		<description><![CDATA[Think for a moment about how many ways we talk about dates and time. In regular language, we can say things like &#8220;last Tuesday&#8221; or &#8220;week after the week after next&#8221; or &#8220;Friday the 12th&#8221; and people generally can figure out when we&#8217;re talking about. Add time into the mix and phrases start getting strange: [...]]]></description>
			<content:encoded><![CDATA[<p>Think for a moment about how many ways we talk about <a title="Gregorian mostly" href="http://en.wikipedia.org/wiki/Calendar_date" target="_blank">dates</a> and <a title="Any time!" href="http://www.timeanddate.com/worldclock/" target="_blank">time</a>. In regular language, we can say things like &#8220;last Tuesday&#8221; or &#8220;week after the week after next&#8221; or &#8220;Friday the 12th&#8221; and people generally can figure out when we&#8217;re talking about. Add time into the mix and phrases start getting strange: &#8220;noon-thirty&#8221; and &#8220;half-past midnight&#8221; are my favorite oddities.</p>
<p>The actual date-time standard is published as <a title="Wikipedia's overview" href="http://en.wikipedia.org/wiki/ISO_8601" target="_blank">ISO 8601</a> and talks about what date-time data should look like, but programming languages, databases and other programs implement this standard with sometimes vastly different interfaces and rules.</p>
<p>PostgreSQL&#8217;s handling of date-time data takes the form of 6 different <a title="All listed out here, with max and min values." href="http://www.postgresql.org/docs/8.4/static/datatype-datetime.html" target="_blank">field types</a>, all suited to different data needs. For the OpenTreeMap project, we&#8217;re using the timestamp data type which allows us to store both dates and times for events down to the microsecond.</p>
<p>Geoserver accepts a single date-time type (also called <a title="Definition only" href="http://docs.geoserver.org/stable/en/user/filter/function_reference.html#function-argument-type-reference" target="_blank">timestamp</a>) that stores dates and times at the same resolution as PostgreSQL&#8217;s data type, so it reads PostgreSQL&#8217;s date-time data easily. Adding a date filter to Geoserver&#8217;s SLD files is also fairly easy so long as you know how Geoserver wants date-time data to be formatted. The various formats that Geoserver knows how to interpret are located <a title="Buried in the documentation..." href="http://docs.geoserver.org/latest/en/user/googleearth/tutorials/time/time.html#specifying-a-date-format">here</a>. So, if we have a field in a database table called &#8220;last_updated&#8221;, then an example SLD filter might look like this:</p>
<pre>&lt;Filter&gt;
  &lt;PropertyIsLessThan&gt;
     &lt;PropertyName&gt;last_updated&lt;/PropertyName&gt;
     &lt;Literal&gt;2012-01-01 00:00:00&lt;/Literal&gt;
  &lt;/PropertyIsLessThan&gt;
&lt;/Filter&gt;
</pre>
<p>This filter would display any updates made before midnight on January 01, 2012. Another example (from the OGC 1.0 encoding specification&#8217;s <a title="PDF - look in the example section for date filters" href="http://portal.opengeospatial.org/files/?artifact_id=1171">examples</a>) catches updates between certain dates:</p>
<pre>&lt;ogc:Filter&gt;
  &lt;ogc:PropertyIsBetween&gt;
    &lt;ogc:PropertyName&gt;last_updated&lt;/ogc:PropertyName&gt;
    &lt;ogc:LowerBoundary&gt;
      &lt;ogc:Literal&gt;2011-12-01 00:00:00&lt;/ogc:Literal&gt;
    &lt;/ogc:LowerBoundary&gt;
    &lt;ogc:UpperBoundary&gt;
      &lt;ogc:Literal&gt;2011-12-31 23:59:59&lt;/ogc:Literal&gt;
    &lt;/ogc:UpperBoundary&gt;
  &lt;/ogc:PropertyIsBetween&gt;
&lt;/ogc:Filter&gt;</pre>
<p>This filter would display any updates made during the month of December, 2011. Anything that was updated outside the specified date and time parameters would bypass these filters and go on to check any other rules in the SLD file. This works great if we&#8217;re only interested in <a title="Not this kind" href="http://www.istockphoto.com/stock-photo-1063134-real-tv-static.php" target="_blank">static</a> date comparisons. But what if we want to see updates less than a week old? Or objects that haven&#8217;t been updated for more than three months? This kind of dynamic filtering is a little harder to do.</p>
<p>After digging through the Geoserver documentation and a lot of googling, we decided to shift the dynamic part of the filter into a PostgreSQL view. Our test view included an id field, a geometry field and a field that calculates the number of days since the last update to that object. The view sql looks like this:</p>
<pre>CREATE OR REPLACE VIEW timestamp_test AS
  SELECT
    treemap_tree.id,
    date_part('days'::text, now() - treemap_tree.last_updated) AS days,
    treemap_tree.geometry
  FROM treemap_tree;</pre>
<p>So now we can add this view to Geoserver as a source layer and it will see the new days field as a static number field. We can use any of the property filters on this field and style recently added data in a dynamic fashion.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.azavea.com/blogs/labs/2012/02/geoserver-timestamp-styling-and-postgresql-datetime-fields/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introducing python-sld and django-sld</title>
		<link>http://www.azavea.com/blogs/labs/2011/12/introducing-python-sld-and-django-sld/</link>
		<comments>http://www.azavea.com/blogs/labs/2011/12/introducing-python-sld-and-django-sld/#comments</comments>
		<pubDate>Wed, 21 Dec 2011 18:23:04 +0000</pubDate>
		<dc:creator>David Zwarg</dc:creator>
				<category><![CDATA[Posts]]></category>

		<guid isPermaLink="false">http://www.azavea.com/blogs/labs/?p=1830</guid>
		<description><![CDATA[python-sld python-sld is a simple python library that enables some basic manipulation of StyledLayerDescriptor (SLD) documents. What are SLD documents?  SLD is a standard defined by the Open Geospatial Consortium, or OGC. In their words: The OpenGIS® Styled Layer Descriptor (SLD) Profile of the OpenGIS® Web Map Service (WMS) Encoding Standard defines an extends the [...]]]></description>
			<content:encoded><![CDATA[<h1>python-sld</h1>
<p><a title="python-sld on pypi.python.org" href="http://pypi.python.org/pypi/python-sld/">python-sld</a> is a simple python library that enables some basic manipulation of StyledLayerDescriptor (SLD) documents.</p>
<p>What are SLD documents?  <a title="SLD standard" href="http://www.opengeospatial.org/standards/sld">SLD</a> is a standard defined by the <a href="http://www.opengeospatial.org/">Open Geospatial Consortium</a>, or OGC. In their words:</p>
<blockquote><p>The OpenGIS® Styled Layer Descriptor (SLD) Profile of the OpenGIS® Web Map Service (WMS) Encoding Standard defines an extends the WMS standard to allow user-defined symbolization and coloring of geographic feature and coverage data.</p></blockquote>
<p>In layman&#8217;s terms, SLD is a common way to style your own maps that come from any map server that speaks <a title="WMS standard" href="http://www.opengeospatial.org/standards/wms">WMS</a> (another standard by OGC). Of all the GIS tools available, the WMS server ecosystem is exceptionally rich and diverse. There are <a href="http://www.intergraph.com/sgi/products/productFamily.aspx?family=10">many</a> <a href="http://resources.arcgis.com/content/arcims/10.0/about">proprietary</a> <a href="http://www.pbinsight.com/products/location-intelligence/developer-tools/desktop-mobile-and-internet-offering/mapxtreme-2008/">choices</a>, as <a href="http://www.qgis.org/">well</a> <a href="http://goworldwind.org/server/">as a </a>plethora <a href="http://www.resc.rdg.ac.uk/trac/ncWMS/">of</a> <a href="http://www.mapserver.org/">open</a> <a href="http://mapguide.osgeo.org/">source</a> <a href="http://mapnik.org/">options</a>.</p>
<h2>State of the Art</h2>
<p>Recently in the course of developing new features for <a href="http://www.districtbuilder.org/">DistrictBuilder</a>, we arrived at a point where we needed to generate SLDs dynamically. Looking around at the existing python libraries, we examined:</p>
<ul>
<li><a href="https://github.com/opengeogroep/pySLD">pySLD</a></li>
<li><a href="http://www.webrian.ch/2011/10/save-as-sld-030-released.html">qGIS plugin &#8220;Save as SLD&#8221;</a></li>
<li><a href="http://geoscript.org/py/">Geoscript</a></li>
</ul>
<p>What we were looking for was a pure object model access to components in the SLD, as well as XML validation, with very few dependencies. None of the above projects really fit the bill, so we started working on our own.</p>
<h2>Introducing python-sld</h2>
<p>python-sld in an open source (<a href="http://www.apache.org/licenses/LICENSE-2.0.html">Apache 2.0</a>) library for dynamic SLD creation and manipulation. The project is hosted over on <a href="https://github.com/azavea/python-sld/">github</a>, and the packages are in <a href="http://pypi.python.org/pypi/python-sld">pypi</a> (including generated inline <a href="http://packages.python.org/python-sld/sld.CssParameter-class.html">documentation</a>).</p>
<h3><strong>Features</strong></h3>
<p>Width python-sld, creating new SLD documents is as easy as creating a new instance of a <a href="http://packages.python.org/python-sld/sld.StyledLayerDescriptor-class.html">StyledLayerDescriptor</a> object:</p>
<pre>&gt;&gt;&gt; from sld import *
&gt;&gt;&gt; sld_doc = StyledLayerDescriptor()</pre>
<p>With this SLD document, all descendants are accessed as properties, and most child objects are created off the parent with &#8220;create_xxx()&#8221; methods:</p>
<pre>&gt;&gt;&gt; sld_doc.NamedLayer is None
True
&gt;&gt;&gt; nl = sld_doc.create_namedlayer('My Layer')
&gt;&gt;&gt; nl.Name
'My Layer'</pre>
<p>For most complex types, the parent&#8217;s property is an instance of the class. In our example:</p>
<pre>&gt;&gt;&gt; isinstance(nl, NamedLayer)
True
&gt;&gt;&gt; us = nl.create_userstyle()
&gt;&gt;&gt; us.Title = 'Style Title'
&gt;&gt;&gt; us.Title
'Style Title'
&gt;&gt;&gt; isinstance(us, UserStyle)
True</pre>
<p>A couple pythonic classes break up the monotony, too. For elements that contain collections of items (a <a href="http://packages.python.org/python-sld/sld.FeatureTypeStyle-class.html">FeatureTypeStyle</a> element may contain many <a href="http://packages.python.org/python-sld/sld.Rule-class.html">Rule</a> elements, and <a href="http://packages.python.org/python-sld/sld.Fill-class.html">Fill</a>, <a href="http://packages.python.org/python-sld/sld.Stroke-class.html">Stroke</a>, and <a href="http://packages.python.org/python-sld/sld.Font-class.html">Font</a> elements may contain many <a href="http://packages.python.org/python-sld/sld.CssParameter-class.html">CssParameter</a> elements), they behave as pythonic lists.</p>
<pre>&gt;&gt;&gt; fts = us.create_featuretypestyle()
&gt;&gt;&gt; len(fts.Rules)
0
&gt;&gt;&gt; r1 = fts.create_rule('Criteria 1')
&gt;&gt;&gt; len(fts.Rules)
1
&gt;&gt;&gt; fts.Rules[0].Title == r1.Title
True</pre>
<p>Another bit of pythonic syntactic sugar is the combination of <a href="http://packages.python.org/python-sld/sld.Filter-class.html">Filter</a>s. By constructing filters (with the <a href="http://packages.python.org/python-sld/sld.Rule-class.html">Rule</a> as a parent) and combining them with &#8220;+&#8221; or &#8220;|&#8221;, they create logical &#8220;AND&#8221; and &#8220;OR&#8221; filters, respectively.</p>
<pre>&gt;&gt;&gt; f1 = Filter(r1)
&gt;&gt;&gt; f1.PropertyIsGreaterThan = PropertyCriterion(f1, 'PropertyIsGreaterThan')
&gt;&gt;&gt; f1.PropertyIsGreaterThan.PropertyName = 'number'
&gt;&gt;&gt; f1.PropertyIsGreaterThan.Literal = '-10'
&gt;&gt;&gt;
&gt;&gt;&gt; f2 = Filter(r1)
&gt;&gt;&gt; f2.PropertyIsLessThanOrEqualTo = PropertyCriterion(f2, 'PropertyIsLessThanOrEqualTo')
&gt;&gt;&gt; f2.PropertyIsLessThanOrEqualTo.PropertyName = 'number'
&gt;&gt;&gt; f2.PropertyIsLessThanOrEqualTo.Literal = '10'
&gt;&gt;&gt;
&gt;&gt;&gt; r1.Filter = f1 + f2</pre>
<p>When the SLD object is serialized, it will render an &#8220;ogc:And&#8221; element that contains both property comparisons. You may have noticed that both the &#8220;PropertyIsGreaterThan&#8221; and &#8220;PropertyIsLessThanOrEqualTo&#8221; properties are assigned an instance of a <a href="http://packages.python.org/python-sld/sld.PropertyCriterion-class.html">PropertyCriterion</a> class. This is the common class for all property comparitors. The name of the comparitor determines it&#8217;s logical comparison (less than, greater than, equal to, etc.), and the class has a PropertyName and Literal property, to control which property gets compared, and which value it is compared against.</p>
<p>Finally, serialization is performed on the main StyledLayerDescriptor object, with options to &#8216;prettify&#8217; the output:</p>
<pre>&gt;&gt;&gt; content = sld_doc.as_sld(pretty_print=True)</pre>
<h3><strong>Dependencies</strong></h3>
<p>The <a href="http://lxml.de/">lxml</a> library is required by python-sld. This is the library that provides the underlying parsing and serializing of the XML document, as well as the validation steps against the canonical SLD schema.</p>
<h3><strong>Limitations</strong></h3>
<p>At the current time, only a subset of the entire SLD specification is implemented. All SLD elements are parsed and stored, but only the following elements may be manipulated as objects in python-sld:</p>
<ul>
<li>StyledLayerDescriptor</li>
<li>NamedLayer</li>
<li>Name (of NamedLayer)</li>
<li>UserStyle</li>
<li>Title (of UserStyle and Rule)</li>
<li>Abstract</li>
<li>FeatureTypeStyle</li>
<li>Rule</li>
<li>ogc:Filter (implicit ogc:And and ogc:Or)</li>
<li>ogc:PropertyIsNotEqualTo</li>
<li>ogc:PropertyIsLessThan</li>
<li>ogc:PropertyIsLessThanOrEqualTo</li>
<li>ogc:PropertyIsEqualTo</li>
<li>ogc:PropertyIsGreaterThanOrEqualTo</li>
<li>ogc:PropertyIsGreaterThan</li>
<li>ogc:PropertyIsLike</li>
<li>ogc:PropertyName</li>
<li>ogc:Literal</li>
<li>PointSymbolizer</li>
<li>LineSymbolizer</li>
<li>PolygonSymbolizer</li>
<li>TextSymbolizer</li>
<li>Mark</li>
<li>Graphic</li>
<li>Fill</li>
<li>Stroke</li>
<li>Font</li>
<li>CssParameter</li>
</ul>
<p>All other SLD elements cannot be directly manipulated in python-sld, but are accessible (from a parsed SLD that is perhaps more complex) via the parent object&#8217;s _node property. This is the lxml.Element that the python-sld class represents.</p>
<h1>django-sld</h1>
<p>django-sld builds upon the capabilities in python-sld by enabling quick SLD generation from geographic models. This library is separate from the python-sld library because of the dependencies on <a href="https://www.djangoproject.com/">django</a> and <a href="http://code.google.com/p/pysal/">pysal</a>, the Python Spatial Analysis Library.</p>
<h2>Primer on Geographic Models</h2>
<p>I gave a quick background to geographic models in django to the <a href="http://www.meetup.com/djangoboston/events/43145722/">Boston django meetup</a> last week, and the slides of my presentation are <a href="https://docs.google.com/present/view?id=ddpq33ft_104cdq773cs">available online</a> as a presentation in Google Docs. The slides are embedded here for your convenience:</p>
<p><iframe src="https://docs.google.com/present/embed?id=ddpq33ft_104cdq773cs" frameborder="0" width="410" height="342"></iframe></p>
<h2>Introducing django-sld</h2>
<p>django-sld is an open source (<a href="http://www.apache.org/licenses/LICENSE-2.0.html">Apache 2.0</a>) library for generating SLD documents from geographic querysets. The project is hosted over on <a href="https://github.com/azavea/django-sld/">github</a>, and the packages are in <a href="http://pypi.python.org/pypi/django-sld">pypi</a> (including generated inline <a href="http://packages.python.org/django-sld/">documentation</a>).</p>
<h3><strong>Features</strong></h3>
<p>django-sld enables quick classification of geographic querysets by passing the data distribution of an individual model field into the classification algorithms built into pysal. Not all classification methods in pysal are available, however. At the current version (1.0.3), the following classification algorithms are supported:</p>
<ul>
<li>Equal Interval</li>
<li>Fisher Jenks</li>
<li>Jenks Caspall</li>
<li>Jenks Caspall Forced</li>
<li>Jenks Caspall Sampled</li>
<li>Max P Classifier</li>
<li>Maximum Breaks</li>
<li>Natural Breaks</li>
<li>Quantiles</li>
</ul>
<p>To classify a django queryset, use any of the as_xxx() methods in the djsld.generator module.</p>
<pre>&gt;&gt;&gt; from djsld import generator
&gt;&gt;&gt; qs = MySpatialModel.objects.all()
&gt;&gt;&gt; sld = generator.as_quantiles(qs, 'population', 10)</pre>
<p>The above example assumes that you have a model named &#8220;MySpatialModel&#8221; in django&#8217;s models.py file. The result is a sld.<a href="http://packages.python.org/python-sld/sld.StyledLayerDescriptor-class.html">StyledLayerDescriptor</a> object, which may be serialized to a string with &#8220;as_sld()&#8221;</p>
<pre>&gt;&gt;&gt; sld_content = sld.as_sld(pretty_print=True)</pre>
<p>The &#8220;pretty_print&#8221; option is available to format the SLD in a fashion that is more readable by us humans.</p>
<p>In addition to simple models, django&#8217;s support for related fields really shines, as it&#8217;s possible to classify the distribution on any related field, using the &#8220;__&#8221; (double underscore) format preferred by django:</p>
<pre>&gt;&gt;&gt; sld = generator.as_quantiles(qs, 'city__population', 10)</pre>
<p>The one caveat is that the PropertyName in the criteria will be set to this field name (which is not the way most mapping packages refer to related fields). To accommodate this difference, you may use the &#8216;propertyname&#8217; keyword to control the output PropertyName:</p>
<pre>&gt;&gt;&gt; sld = generator.as_quantiles(qs, 'city__population', 10,
... propertyname='population')</pre>
<h3><strong>Dependencies</strong></h3>
<p>django-sld requires python-sld and the pysal library.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.azavea.com/blogs/labs/2011/12/introducing-python-sld-and-django-sld/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Putting the Fun in FOSS</title>
		<link>http://www.azavea.com/blogs/labs/2011/09/putting-the-fun-in-foss/</link>
		<comments>http://www.azavea.com/blogs/labs/2011/09/putting-the-fun-in-foss/#comments</comments>
		<pubDate>Fri, 23 Sep 2011 15:38:42 +0000</pubDate>
		<dc:creator>David Zwarg</dc:creator>
				<category><![CDATA[Posts]]></category>
		<category><![CDATA[foss4g]]></category>
		<category><![CDATA[GeoServer]]></category>
		<category><![CDATA[i2maps]]></category>
		<category><![CDATA[mapnik]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[opensource]]></category>

		<guid isPermaLink="false">http://www.azavea.com/blogs/labs/?p=1814</guid>
		<description><![CDATA[I went to the State of the Map (SotM) and Free and Open Source Software for Geospatial (FOSS4G) Conference in Denver, CO last week, where I was surrounded by geospatial users, developers, and architects. I had the opportunity to attend some workshops and learn about a slew of awesome projects &#8212; I&#8217;m itching to start [...]]]></description>
			<content:encoded><![CDATA[<p>I went to the State of the Map (<a href="http://stateofthemap.org/">SotM</a>) and Free and Open Source Software for Geospatial (<a href="http://2011.foss4g.org/">FOSS4G</a>) Conference in Denver, CO last week, where I was surrounded by geospatial users, developers, and architects. I had the opportunity to attend some workshops and learn about a slew of awesome projects &#8212; I&#8217;m itching to start incorporating many of these new tools and techniques into our solutions.</p>
<h2>Node.js</h2>
<p>I was able to attend some of the workshops &#8212; &#8220;You&#8217;ve got Javascript in your backend&#8221; with <a href="http://nodejs.org/">Node.js</a> and <a href="http://polymaps.org/">Polymaps</a> was a great beginner workshop, introducing lightweight servers and client mapping libraries. I was amazed that a basic web server in node.js is only 5 lines of code. Equally amazing was seeing what capabilities Polymaps had when it weighted in at only 32K (minified) vs. <a href="http://www.openlayers.org/">OpenLayers</a> at 1.2M (minified default build).</p>
<h2>i2maps + pico</h2>
<p>Some exciting visualization tools are coming out of the <a href="http://ncg.nuim.ie/">National Center for Geocomputation</a> at the <a href="http://www.nuim.ie/">National University of Ireland</a>, in the form of <a href="http://ncg.nuim.ie/i2maps/docs/">i2maps</a>. While it&#8217;s relatively immature (not much in the form of documentation), most the basic functionality builds off of OpenLayers.  Since I&#8217;ve already learned the OpenLayers library, I has a short learning curve, and was able to get up to speed pretty quickly.  Their library incorporates some awesome features like dynamically loading and evaluating rasters via canvas (this only works on modern browsers), and even agent-based modeling. I could have stayed in that workshop for a week.</p>
<p>A byproduct of the i2maps project is <a href="https://github.com/fergalwalsh/pico">pico</a>. Pico is a bridge between <a href="http://www.python.org/">Python</a> and Javascript, enabling you to call native Python methods directly from Javascript. It performs all the plumbing for you, allowing you to write a simple callback to handle your method&#8217;s return value. It also takes care of converting Python objects into Javascript objects, allowing you to pass all sort of data back and forth (including rasters!).</p>
<h2>mod-geocache</h2>
<p>Another new project from a contributor to the MapServer project is <a href="http://code.google.com/p/mod-geocache/">mod-geocache</a>, a tile caching service as an <a href="http://httpd.apache.org/">Apache</a> module. This skips a lot of overhead (no proxying, no interpreters, no CGI), and is very fast. In addition, the C implementation has excellent speed and performance. You can perform on the fly tile merging, quantization, and recompression. I&#8217;m excited about this module, and the promise of caching with an Apache server (looks like it has more features than <a href="http://wiki.openstreetmap.org/wiki/Mod_tile">mod_tile</a>).</p>
<h2>Geoserver</h2>
<p><a href="http://geoserver.org/display/GEOS/Welcome">Geoserver</a>&#8216;s next release is also going to include some great features. The ones that really jumped out at me:</p>
<ul>
<li>Time and elevation filters &#8212; e.g. storm tracking, where you can limit the features by a time field.</li>
<li>Styling SLDs in data units &#8212; e.g. &#8220;road is 5m wide&#8221;, and changes dynamically with scale. This greatly simplifies scale-dependent renderers.</li>
<li>Georeferencing of layers can be done in the admin interface.</li>
<li>Layers can be view definitions &#8212; you don&#8217;t have to roll your own views prior to creating the layer.</li>
<li>Virtual Services &#8212; partition the data layers by workspace.</li>
</ul>
<p>These aren&#8217;t all the new features; take a look at the <a href="http://geoserver.org/display/GEOS/State+of+GeoServer+2011">laundry list</a> yourself, and prepare to be impressed.</p>
<h2>Mapnik 2</h2>
<p>I think the reason for calling it <a href="http://trac.mapnik.org/">Mapnik2</a> is that it is literally twice as awesome as it was before. I learned about the new features in Mapnik2 in the lightning talks at SotM, and I think this was one of the few talks that made you feel like you were actually struck by lightning. I can&#8217;t remember half the slides in the talk, but the supported formats, reprojection, styling, and speed improvements left me with my head spinning.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.azavea.com/blogs/labs/2011/09/putting-the-fun-in-foss/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Django, contests and weekly voting</title>
		<link>http://www.azavea.com/blogs/labs/2011/09/django-contests-and-weekly-voting/</link>
		<comments>http://www.azavea.com/blogs/labs/2011/09/django-contests-and-weekly-voting/#comments</comments>
		<pubDate>Thu, 15 Sep 2011 13:13:14 +0000</pubDate>
		<dc:creator>Carissa Brittain</dc:creator>
				<category><![CDATA[Posts]]></category>
		<category><![CDATA[Django]]></category>

		<guid isPermaLink="false">http://www.azavea.com/blogs/labs/?p=1800</guid>
		<description><![CDATA[I&#8217;ve written before about how OpenDataPhilly uses a ratings module to drive a nomination system. Recently, we added a contest to the site to determine what kinds of data local non-profits and the public would like to see made available. Contests generally have a winner and, in this case, we&#8217;re letting the public vote on [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve written before about how <a title="OpenDataPhilly" href="http://www.opendataphilly.org" target="_blank">OpenDataPhilly</a> uses a <a title="jQuery Star Rating with Django-ratings" href="http://www.azavea.com/blogs/labs/2011/04/jquery-star-rating-with-django-ratings/" target="_blank">ratings module</a> to drive a nomination system. Recently, we added a <a title="The OpenDataRace is on!" href="http://www.opendataphilly.org/contest/" target="_blank">contest</a> to the site to determine what kinds of data local non-profits and the public would like to see made available. Contests generally have a winner and, in this case, we&#8217;re letting the public vote on data sets nominated by non-profits. At first glance this isn&#8217;t much different from our current nomination system, but there&#8217;s one catch; we wanted users to be able to vote for one entry once a week. Turns out this was more novel than it sounds.</p>
<p>Django has a few modules for rating or voting on content, one of which we&#8217;re using for the nomination and comments systems. The inner-workings of the module boil down to the following rules:</p>
<ol>
<li>A user must be logged in to rate/vote</li>
<li>A user can rate/vote for any number of items</li>
<li>A user can only rate/vote for any particular item once (though they may change their rating/vote later)</li>
</ol>
<p>Compare this with the rules we wanted to enforce for the contest:</p>
<ol>
<li>A user must be logged in to vote</li>
<li>A user can only vote once per 7 day period</li>
<li>A user can vote for an item multiple times, so long as <a title="Though not this rule 2" href="http://en.wikipedia.org/wiki/Three_Laws_of_Robotics" target="_blank">rule 2</a> is preserved</li>
</ol>
<p>Aside from the first rule, we were trying to do almost <a title="An... evil opposite? Nope." href="http://tvtropes.org/pmwiki/pmwiki.php/Main/EvilCounterpart?from=Main.EvilOpposite" target="_blank">exactly the opposite</a> of what our rating module enforced. Rather than retrofit the existing module to allow additional and sometimes <a title="Wisely avoided" href="http://en.wikipedia.org/wiki/Liar!" target="_blank">contradictory behaviour</a>, we decided to write a very small voting module of our own.</p>
<p>The code revolves around two decision points: is voting allowed and can a specific user vote now. The first question is answered by the contest object itself. A contest knows when it&#8217;s starting and ending date are, so if today is after the start date and before the end date, then voting is allowed.</p>
<p>The second question is a bit more complicated, but not by much. Because of rule 2 above, we need to know when a user last voted to know if they&#8217;re currently <a title="A legal mess in some systems" href="http://en.wikipedia.org/wiki/Voting_system" target="_blank">allowed to vote</a>. The database storage for a vote contains a datetime object, a foreign key to the user object and a foreign key to the contest entry so if we sort a user&#8217;s votes by time we can retrieve their latest vote.</p>
<pre>def user_can_vote(self, user):
    increment = datetime.timedelta(days=7)
    votes = user.vote_set.order_by('-timestamp') #latest on top
    if votes:
        next_date = votes[0].timestamp + increment
        if datetime.datetime.today() &lt; next_date and dt.today() &lt; contest.end_date:
            return False
    return True</pre>
<p>The above code gets a user&#8217;s votes and orders them by time with the most recent first. If a user has ever voted, we need to check if they&#8217;re allowed to vote again yet or if they have to wait. We calculate the earliest time that a user can vote next and check it against the date and time <a title="Now!" href="http://www.geekologie.com/2007/07/16/now-watch.jpg" target="_blank">now</a>. We also check the end of the contest against the date and time now. If &#8220;<a title="What am I looking at?" href="http://28.media.tumblr.com/5iKOt5ZqV55qd8c0MTPKKh4e_500.jpg" target="_blank">now</a>&#8221; is before the next time the user can vote or &#8220;<a title=".. or later." href="http://www.flickr.com/photos/jcorduroy/3725077603/" target="_blank">now</a>&#8221; is after the contest&#8217;s end date, we return false; the user can&#8217;t vote <a title="Now hiring! The board game!" href="http://citycyclops.com/1.04.10.php" target="_blank">now</a>. If a user has never voted before, or the dates are all ok then the user can vote. This check is done after a user clicks the &#8220;vote&#8221; button but before a vote is saved to the database. We also display a message saying why this check failed and when a user will be able to vote again.</p>
<p>So we&#8217;re taking advantage of all of the spam protection built into Django&#8217;s user registration process and running a contest on surprisingly little code: 3 database tables, 200 lines of python (blank lines included) and a few templates is all we needed!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.azavea.com/blogs/labs/2011/09/django-contests-and-weekly-voting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Restricting Zoom with Multiple OL Basemaps</title>
		<link>http://www.azavea.com/blogs/labs/2011/09/restricting-zoom-with-multiple-ol-basemap/</link>
		<comments>http://www.azavea.com/blogs/labs/2011/09/restricting-zoom-with-multiple-ol-basemap/#comments</comments>
		<pubDate>Thu, 01 Sep 2011 18:41:42 +0000</pubDate>
		<dc:creator>Kenny Shepard</dc:creator>
				<category><![CDATA[Posts]]></category>
		<category><![CDATA[Bing]]></category>
		<category><![CDATA[DistrictBuilder]]></category>
		<category><![CDATA[Django]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[openlayers]]></category>
		<category><![CDATA[openstreetmap]]></category>

		<guid isPermaLink="false">http://www.azavea.com/blogs/labs/?p=1595</guid>
		<description><![CDATA[As David recently posted, our team has been hard at work implementing DistrictBuilder, where we&#8217;ve been investing a great deal of effort on both performance and usability. One feature we added in the spring was the addition of basemaps to the user interface. Before this addition, users labored over drawing the perfect district configurations without a whole [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.azavea.com/districtbuilder"><img class="alignleft size-full wp-image-1783" style="border: 0px;" title="DistrictBuilder_logo" src="http://www.azavea.com/blogs/labs/wp-content/uploads/2011/07/DistrictBuilder_logo.png" alt="DistrictBuilder logo" width="206" height="66" align="left" hspace="4" vspace="4" /></a>As David <a title="Building Districts in Web-Time" href="http://www.azavea.com/blogs/labs/2011/08/building-districts-in-web-time/">recently posted</a>, our team has been hard at work implementing <a title="DistrictBuilder on GitHub" href="https://github.com/PublicMapping/DistrictBuilder">DistrictBuilder</a>, where we&#8217;ve been investing a great deal of effort on both performance and usability. One feature we added in the spring was the addition of basemaps to the user interface. Before this addition, users labored over drawing the perfect district configurations without a whole lot of context of the surrounding environment (e.g. roads, water boundaries, etc.). When the time came to add a basemap to the application, it didn&#8217;t feel right restricting it to a single type of map, or even a single provider. We wanted to allow for users to have the choice to select the best map for the task at hand. Could an application promoting democracy really have it any other way?</p>
<p>We set out to support several base map options as well as any combination of options, including:</p>
<ul>
<li>Bing Maps (satellite, roads and hybrid)</li>
<li>GoogleMaps (satellite, roads and hybrid)</li>
<li>ArcGIS Online (any of several maps)</li>
<li>OpenStreetMap</li>
</ul>
<p>Since DistrictBuilder needs to be flexible enough to meet the needs of users and administrators in a variety of situations, we decided on a two step approach to basemap configuration. First, the administrator specifies, in the configuration file, which of the combinations of map providers and map types are allowed to be selected. Then DistrictBuilder presents all of the configured options to the user, where they can be toggled among at any time while a plan is being viewed or edited.</p>
<p>Here&#8217;s an example of an instance configured with an <a title="OpenStreetMap" href="http://www.openstreetmap.org/" target="_blank">OpenStreetMap</a> road layer, a <a title="Bing Maps" href="http://www.bing.com/maps/">Bing</a> hybrid layer, and a <a title="Google Maps" href="http://lmgtfy.com/?q=google+maps">Google</a> satellite layer:</p>
<p style="text-align: center;"><img class="size-full wp-image-1629 aligncenter" title="Road, Hybrid, and Satellite" src="http://www.azavea.com/blogs/labs/wp-content/uploads/2011/07/rhs.png" alt="Road, Hybrid, and Satellite" width="253" height="216" /></p>
<p>Here&#8217;s another example with only road layers &#8212; one for each of the three configured providers:</p>
<p style="text-align: center;"><img class="size-full wp-image-1632 aligncenter" title="Roads for three vendors" src="http://www.azavea.com/blogs/labs/wp-content/uploads/2011/07/rrr.png" alt="Roads for three vendors" width="302" height="202" /></p>
<p>DistrictBuilder currently allows the configuration of basemaps using permutations of each of the three vendors and three map types described above. Adding more options is a relatively easy task, however. With the launch of <a title="Fix Philly Districts" href="http://fixphillydistricts.com">Fix Philly Districts</a>, we wanted the basemap colors to be slightly more muted than the above options, and ended up adding support for the <a title="ArcGIS Online" href="http://www.azavea.com/blogs/labs/2011/02/openlayers-and-arcgis-com/" target="_blank">ArcGIS Online</a> World Topographic Map. We also experimented with the Google Maps V3 custom <a title="Google Styled Maps " href="http://code.google.com/apis/maps/documentation/javascript/styling.html">styling API</a>, which looked great, but introduced performance problems when panning and zooming (animations).</p>
<p>There were, of course, some hoops that needed to be jumped through in order to get all of these basemaps behaving correctly on the same map, which will be discussed below. I&#8217;ve extracted the logic required to do so into a small demo that can be viewed/downloaded <a href="http://s3.azavea.com.s3.amazonaws.com/com.azavea.www/blogs/multiple_base_layers/demo.html">here</a>. The demo has also been embedded into this post, and can be interacted with without going anywhere:</p>
<p><iframe src="http://s3.azavea.com.s3.amazonaws.com/com.azavea.www/blogs/multiple_base_layers/demo.html" frameborder="0" width="100%" height="370"></iframe></p>
<h1></h1>
<h1>Zoom Levels</h1>
<p>Many of the challenges that needed to be overcome to get this working correctly were brought about because we needed to restrict the zoom levels to the area at hand. We wanted to eliminate superfluous zoom levels to ensure the user was always operating within the appropriate boundaries (note: it is not done in this demo, but in DistrictBuilder we also restrict the extent with the &#8216;restrictedExtent&#8217; map parameter, so users can&#8217;t even pan outside of the area).</p>
<p>One difficulty with setting zoom levels on the different layers is that the layers don&#8217;t use zoom parameters consistently. In Bing (the VirtualEarth layer), minZoomLevel and maxZoomLevel are needed. In Google, minZoomLevel is needed, but it requires numZoomLevels instead of maxZoomLevel. And in OpenStreetMap (the OSM layer), well&#8230;no combination of those seem to work &#8212; we needed to slightly modify the XYZ layer (OSM&#8217;s base class) to allow maxResolution to be changed based on the minZoomLevel. To see how this is done, view the demo source. With that change in place, the list of required layer parameters is as follows:</p>
<ul>
<li><strong>Bing</strong> &#8211; minZoomLevel, maxZoomLevel, projection, sphericalMercator, maxExtent</li>
<li><strong>Google</strong> &#8211; numZoomLevel, minZoomLevel, projection, sphericalMercator, maxExtent</li>
<li><strong>OpenStreetMap</strong> - numZoomLevel, minZoomLevel, projection</li>
</ul>
<h1>Coordinate Systems</h1>
<p>We also faced some problems related to coordinate systems. DistrictBuilder uses <a title="GeoServer" href="http://geoserver.org">GeoServer</a> and <a title="GeoWebCache" href="http://geowebcache.org/">GeoWebCache</a> to serve up WMS layers. The coordinate system of our data is one version of the the <a title="GIS Standards gone crazy" href="http://viswaug.wordpress.com/2009/04/01/gis-standards-gone-crazy-epsg-especially/">ever-changing</a> &#8220;Popular Visualization CRS / Mercator&#8221; projection. We needed to match up the OpenLayers projection to the one used on our data, or else we were seeing slight offsets on our overlays. Unfortunately, the &#8216;projection&#8217; layer parameter isn&#8217;t always used within the layers correctly. For example, any layer using the SphericalMercator class gets its projection automatically hardcoded to 900913. We needed to make a slight modification to the SphericalMercator class to allow the &#8216;projection&#8217; parameter to carry through. This can be seen by viewing the demo source.</p>
<h1>Bonus: Math Time!</h1>
<p>One interesting part about implementing zoom restriction was that we needed it to work in any instance of DistrictBuilder &#8212; from large states to small towns, which may have vastly different extents. Instead of having an administrator figure out the proper minimum zoom level, we calculate it automatically based on the extent, which requires a little bit of basic algebra.</p>
<p>For Philadelphia, the extent of our area is:</p>
<pre>[-8397913.926216, 4842467.609439, -8329120.600772, 4895973.529229]</pre>
<p>In DistrictBuilder, we calculate this dynamically on the server side (using Django) by filtering all of the geounits in the database and calling the &#8216;extent&#8217; function on the query set. For the demo, this is hardcoded. Here&#8217;s how to transform this extent into a Spherical Mercator minZoomLevel:</p>
<ul>
<li>Find the width of the area in meters.</li>
</ul>
<pre>var studyWidthMeters = extent[2] - extent[0];</pre>
<ul>
<li>Find the width of the map in pixels. In the demo, this is hardcoded, because we are setting the div size of the map. In DistrictBuilder, the map takes up the whole screen, and this value is calculated on the fly based on the size of the div in which the map occupies.</li>
</ul>
<pre>var mapWidthPixels = 450;</pre>
<ul>
<li>Find the map resolution, or meters per pixel.</li>
</ul>
<pre>var resolution = studyWidthMeters / mapWidthPixels;</pre>
<ul>
<li>Find the maximum map resolution. In Spherical Mercator, the maximum resolution is one 256&#215;256 tile taking up the entire circumference Earth. So dividing the circumference of the earth (~40,000km) by 256 gives us the maximum meters per pixel, which is a constant.</li>
</ul>
<pre>var maxResolution = 156543.033928;</pre>
<ul>
<li>Spherical Mercator zoom levels work like a pyramid. Each zoom breaks the current tile up into a 2&#215;2 group of 256&#215;256 tiles, essentially halving the resolution each time. Therefore, finding the resolution at a given zoom level looks like this:</li>
</ul>
<pre>maxresolution / 2^zoom = resolution</pre>
<ul>
<li>We know the resolution and max resolution already, and need to find the zoom:</li>
</ul>
<pre>zoom = log(maxresolution/resolution)/log(2)</pre>
<ul>
<li>Or in javascript:</li>
</ul>
<pre>var minZoom = Math.log(maxResolution / resolution) / Math.LN2;</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.azavea.com/blogs/labs/2011/09/restricting-zoom-with-multiple-ol-basemap/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Building Districts in Web-Time</title>
		<link>http://www.azavea.com/blogs/labs/2011/08/building-districts-in-web-time/</link>
		<comments>http://www.azavea.com/blogs/labs/2011/08/building-districts-in-web-time/#comments</comments>
		<pubDate>Mon, 22 Aug 2011 18:07:18 +0000</pubDate>
		<dc:creator>David Zwarg</dc:creator>
				<category><![CDATA[Posts]]></category>
		<category><![CDATA[DistrictBuilder]]></category>
		<category><![CDATA[GeoServer]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[openlayers]]></category>

		<guid isPermaLink="false">http://www.azavea.com/blogs/labs/?p=1581</guid>
		<description><![CDATA[Most recently, the Politics, Redistricting and Elections team has been working closely with the Public Mapping Project to build DistrictBuilder, an open source, web-based application that enables regular citizens to use powerful tools to draw their own legislative districts. If you&#8217;ve seen how badly the professionals can mangle districts (Exhibit A, Exhibit B, etc), it&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.azavea.com/districtbuilder"><img class="alignleft size-full wp-image-1783" style="border: 0px;" title="DistrictBuilder_logo" src="http://www.azavea.com/blogs/labs/wp-content/uploads/2011/07/DistrictBuilder_logo.png" alt="DistrictBuilder logo" width="206" height="66" align="left" hspace="4" vspace="4" />Most recently, the Politics, Redistricting and Elections team has been working closely with the <a title="The Public Mapping Project" href="http://www.publicmapping.org/">Public Mapping Project</a> to build <a title="District Builder" href="https://sourceforge.net/projects/publicmapping/">DistrictBuilder</a>, an open source, web-based application that enables regular citizens to use powerful tools to draw their own legislative districts. If you&#8217;ve seen how badly the professionals can mangle districts (<a title="Illinois Congressional District #4" href="http://www.redistrictingthenation.com/search.aspx?type=NATIONAL_LOWER&amp;id=4&amp;state=IL">Exhibit A</a>, <a title="Pennsylvanio Congressional District #12" href="http://www.redistrictingthenation.com/search.aspx?type=NATIONAL_LOWER&amp;id=12&amp;state=PA">Exhibit B</a>, <a title="Top 10 Congressional Districts" href="http://www.redistrictingthenation.com/top10.aspx">etc</a>), it&#8217;s easy to imagine that any given citizen, given the right tools, could do it better.</p>
<p>We spent quite a bit of time making the application easy to use and responsive in modern desktop web browsers.  The &#8220;easy to use&#8221; part was tackled by our excellent UI/UX design team. The &#8220;responsive&#8221; part was the domain of  our engineers.  That&#8217;s where the fun began for me.</p>
<p>DistrictBuilder is designed to use any polygon shapefile, transform it into an internal data model, then make that accessible via map tiles and geometric features.  When serving map tiles, we use <a title="Geoserver" href="http://geoserver.org/display/GEOS/Welcome">GeoServer</a> and <a title="GeoWebCache" href="http://geowebcache.org/">GeoWebCache</a> to generate the tiles and cache them, respectfully. This performance is great &#8212; pre-generated map tiles are the best we can aim for with respect to the base map tiles. Serving geometric features at full resolution, however, introduces a slew of problems. A few that stood out right away:</p>
<ul>
<li>Web Browser Limitations &#8212; 9 out of 10 experts agree: too many map features has a significant performance impact on web browsers, with the greatest impact on the Microsoft Internet Explorer browser.</li>
<li>Excessive Coordinates &#8212; delivering lots of polygon coordinate pairs that the user may never see consumes valuable bandwidth and rendering time.</li>
<li>Server Processing Time &#8212; recalculating state-wide geometric features consumes valuable CPU time.</li>
</ul>
<h1>Web Browser Limitations</h1>
<p>First, we tackled the browser performance issues. A sluggish browser is the kiss of death in the web world, and we had to make the application experience as fast as possible before looking at the server processing time.</p>
<p>We originally gave users the power to create highly detailed districts at the statewide level, but realized that no modern web browser could handle the volume of polygon features that would need to be served to represent an entire state.  In order to mitigate this limitation, we limited the size and number of features sent to the browser. With some scale-dependent logic, a user zoomed in to a detail of a district can finely tune the boundary by moving smaller geographic features (e.g. census blocks), and a user zoomed out to the state-wide level can manipulate the districts by moving large geographic features only (e.g. counties). In addition, when editing the finest details, we limit the number of features a user can move in a single edit.</p>
<h1>Excessive Coordinates</h1>
<p>The next thing to go was the set of full resolution geometries. In DistrictBuilder, users never actually see the full geometries, but an <a href="http://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm">adaptively simplified</a> (sometimes called generalized) geometry; depending on the scale of the map view, the server will deliver geometries with appropriate coordinate resolutions. Simply put: as you zoom in on the map, you get more detail in the geometries.</p>
<p>By simplifying counties, the geometries are reduced from 166,958 points to 4,821. When a user is zoomed out, there is no noticeable difference between these geometries!  However, as the user is interacting with higher resolution maps, DistrictBuilder loads in higher-resolution geometries on demand. The following images demonstrate the difference in the geometry detail:</p>
<div id="attachment_1689" class="wp-caption aligncenter" style="width: 510px"><img class="size-full wp-image-1689 " title="Low Resolution Transition" src="http://www.azavea.com/blogs/labs/wp-content/uploads/2011/08/county_vtd_transition-low1.png" alt="Low Resolution Transition" width="500" height="298" /><p class="wp-caption-text">The zoomed in County layer, with a low resolution district overlay (orange line). There are currently 1,414 coordinates in this view of the district overlay.</p></div>
<div id="attachment_1686" class="wp-caption aligncenter" style="width: 510px"><img class="size-full wp-image-1686  " title="High Resolution Transition" src="http://www.azavea.com/blogs/labs/wp-content/uploads/2011/08/county_vtd_transition-high.png" alt="High Resolution Transition" width="500" height="298" /><p class="wp-caption-text">The zoomed in VTD layer, with a high resolution district overlay (orange line). There are currently 3,253 coordinates in this view of the district overlay.</p></div>
<p>You can notice the differences in the district detail if you look closely at the orange district boundary. This transition happens seamlessly in the application, loading in the higher resolution geometries as web users zoom in to areas of interest.</p>
<p>We also eliminated coordinates that you never see.  It made no sense to serve  coordinates that were located in the opposite side of the state where a user was editing, just like you wouldn&#8217;t expect to get an encyclopedia in the mail when releasing an <a title="Request for Information" href="http://en.wikipedia.org/wiki/Request_for_information">RFI</a>. With the <a title="OpenLayers" href="http://www.openlayers.org/">OpenLayers</a> library, Strategies came in handy here, particularly <a href="http://dev.openlayers.org/apidocs/files/OpenLayers/Strategy/BBOX-js.html">BBOX</a>.</p>
<h1>Server Processing Time</h1>
<p>After we had optimized the performance of the user interface, we shifted our focus to the server-side processing.  One of the features that makes DistrictBuilder such a powerful tool is the accuracy of the underlying data and constant feedback of important district statistics. In order to calculate all these statistics on the fly, it is necessary to leverage some tricks already mentioned with respect to map tiles: caching and generalizing.</p>
<p>Computation of the district statistics must happen every time a district boundary is changed. A naive solution to this problem would be to aggregate the values within the boundary every time a change is made.  This approach results in horrible performance. Instead, we just determine what has changed &#8212; which areas were added, which areas were removed &#8212; and recompute the delta, or change, on the previous district value.</p>
<p>Another trick to optimizing performance is in the way we determine the changing boundaries.  I&#8217;ll describe the problem using the census geographies of counties, tracts, and blocks. The structure and detail of the underlying data yielded computationally expensive queries against the block geometries.  We came up with a method of searching for the geographies in a hierarchical fashion &#8212; searching the counties first, then continuing to the next smallest-scale geography only if there was any remaining geometry left in the query.  We did the same for the tracts, and took a shortcut at the block level to exclude the block geometries.  This increased server side performance considerably.</p>
<div id="attachment_1690" class="wp-caption aligncenter" style="width: 374px"><a href="http://www.azavea.com/blogs/labs/wp-content/uploads/2011/08/heirarchy-lg.png"><img class="size-full wp-image-1690" title="King William County" src="http://www.azavea.com/blogs/labs/wp-content/uploads/2011/08/heirarchy-sm.png" alt="King William County" width="364" height="258" /></a><p class="wp-caption-text">King William county is comprised of 22 Voter Tabulation Districts and 1,527 Census Blocks.</p></div>
<p>Consider the following scenario: a user wants to move King William County (highlighted in yellow) from District 1, which is over populated, to District 3, which is under populated. Changing the boundaries with all the blocks in King William County would require testing at least 4,000 blocks for spatial intersections, then aggregating 1,527 data values, and recomputing the spatial aggregate (union) of those 1,527 geometries. With our hierarchical approach, we can change the boundary of the district with the county boundary, and change the population totals by the county&#8217;s population. A few orders of magnitude fewer operations to perform, and much faster from the user&#8217;s perspective.</p>
<h1>Lessons Learned</h1>
<p>Throughout the DistrictBuilder development process, the same core performance challenge has arisen: the volume of data must be reduced. This applies to all aspects of the application:</p>
<ul>
<li>Map Tiles: pre-render tiles to keep the number of rendered tiles to a minimum at runtime.</li>
<li>Map Features: deliver to the browser only as much information as you can see (perhaps even less).</li>
<li>Database Queries: do anything possible to ensure that geometric operations are performed on simplified geometries.</li>
<li>Aggregating Statistics: cache whatever you can, and only compute the difference from the last cache state.</li>
</ul>
<p>The above steps reduced the sheer number of operations and volume of processing that both the server and browser need to complete when creating new districts. These are lessons that translate well to <em>any</em> &#8220;big data&#8221; problem, and are crucial in bringing sophisticated GIS operations to the web.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.azavea.com/blogs/labs/2011/08/building-districts-in-web-time/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Pending edit system using Django</title>
		<link>http://www.azavea.com/blogs/labs/2011/08/pending-edit-system-using-django/</link>
		<comments>http://www.azavea.com/blogs/labs/2011/08/pending-edit-system-using-django/#comments</comments>
		<pubDate>Fri, 19 Aug 2011 21:27:17 +0000</pubDate>
		<dc:creator>Carissa Brittain</dc:creator>
				<category><![CDATA[Posts]]></category>
		<category><![CDATA[Django]]></category>
		<category><![CDATA[opensource]]></category>

		<guid isPermaLink="false">http://www.azavea.com/blogs/labs/?p=1680</guid>
		<description><![CDATA[A common concern when we talk to people about OpenTreeMap is how much to trust the public with an organisation&#8217;s tree inventory. Every implementation of this open source system has a different answer. The original site, UrbanForestMap.org, allows a logged-in user to edit almost every bit of information they gather about a tree. PhillyTreeMap.org requires [...]]]></description>
			<content:encoded><![CDATA[<p>A common concern when we talk to people about <a title="Open source, wiki-style tree inventory site" href="http://www.azavea.com/products/opentreemap/" target="_blank">OpenTreeMap</a> is how much to trust the public with an organisation&#8217;s tree inventory. Every implementation of this open source system has a different answer. The original site, <a title="Originally build by Urban-Ecos for San Francisco, CA" href="http://www.urbanforest.org/" target="_blank">UrbanForestMap.org</a>, allows a logged-in user to edit almost every bit of information they gather about a tree. <a title="13 counties around Philadelphia, PA" href="http://www.phillytreemap.org" target="_blank">PhillyTreeMap.org</a> requires a certain level of reputation before a user can edit everything, but even a new user has considerable edit capabilities. The most recent implementation (still a work-in-progress) introduces a bit of oversight to public edits. The managing group wanted to double-check changes to officially inventoried trees, but didn&#8217;t want to get in the way of people adding and editing their own trees.</p>
<p>Lets look at how this changes the <a title="One way to gather requirements" href="http://en.wikipedia.org/wiki/User_story" target="_blank">user story</a> first:</p>
<p><em>A logged-in user makes an edit to a tree. The system needs to decide if these changes are applied to the tree or placed in a pending queue. If this is a publicly-entered tree, the changes are applied to the tree. (Start new requirements) If this is an inventory tree, and the user isn&#8217;t a member of a management group, add the change to the pending queue. Display any pending changes reasonably near the appropriate current value. (End new requirements)</em></p>
<p>Most of this happens behind the scenes in the saving logic. I added a bit of code to the top of our tree updater to check if the pending system <a title="It's alive!!!" href="http://www.youtube.com/watch?v=xos2MnVxe-c" target="_blank">is active</a>, the user&#8217;s permissions and the tree&#8217;s origins. If everything checks out, the change goes straight into the updater code. For changes that go into the pending queue, the path to becoming an official change is a little more tortuous.</p>
<p>Since we&#8217;re storing these changes for later review, they have to go into the database. I created a <a title="Not from old wood though.." href="http://topdesigninterior.com/wp-content/uploads/2010/12/Unique-Tree-Table-Coffe-by-Dylan-Gold-stink_tree.jpg" target="_blank">new table</a> to hold onto the original tree&#8217;s id, the field being changed and the new value as well as the user who submitted it, a date/time stamp and a status field. Each pending change is stored separately; even if the user makes more than one change to the tree, each &#8216;pend&#8217; can be applied individually.</p>
<p>The rest of the pending system is <a title="yummm..." href="http://www.lilsugar.com/Delilicious-Monster-Candy-Eyeballs-5756935" target="_blank">eye-candy</a> and a bit of slightly tedious templating. Almost every field on a tree&#8217;s detail page now needs to check two new things: are there any pending changes for this field, and does this user have permission to approve/disapprove pending edits. If there are pending edits, the new values are added below the current official value. When a managing user views the page, small approve and disapprove buttons also appear next to each pending change. Throw in a management-access-only page for some bulk evaluation and the system is complete!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.azavea.com/blogs/labs/2011/08/pending-edit-system-using-django/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Bring on the data focused basemaps, Esri</title>
		<link>http://www.azavea.com/blogs/labs/2011/08/bring-on-the-data-focused-basemaps-esri/</link>
		<comments>http://www.azavea.com/blogs/labs/2011/08/bring-on-the-data-focused-basemaps-esri/#comments</comments>
		<pubDate>Fri, 12 Aug 2011 18:33:16 +0000</pubDate>
		<dc:creator>Jeremy Heffner</dc:creator>
				<category><![CDATA[Posts]]></category>
		<category><![CDATA[ArcGIS.com]]></category>
		<category><![CDATA[Basemap]]></category>
		<category><![CDATA[ESRI]]></category>

		<guid isPermaLink="false">http://www.azavea.com/blogs/labs/?p=1660</guid>
		<description><![CDATA[It&#8217;s great to read that Esri is working on features and basemaps to include within ArcGIS.com to support data visualization.     Sometimes the map isn&#8217;t the focus; sometimes the data is the focus.  A few weeks ago, Bern Szukalski wrote an article for the Esri Insider blog that spoke about Esri&#8217;s efforts to create [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s great to read that <a href="http://www.esri.com">Esri</a> is working on features and basemaps to include within <a href="http://www.arcgis.com">ArcGIS.com</a> to support data visualization.     Sometimes the map isn&#8217;t the focus; sometimes the data is the focus.  A few weeks ago, Bern Szukalski wrote an article for the Esri Insider blog <a href="http://blogs.esri.com/Info/blogs/esri-insider/archive/2011/07/25/inside-new-basemaps.aspx">that spoke about Esri&#8217;s efforts to create new basemaps including basemaps for data visualization purposes</a>.   I think this is a great move for Esri.   Last fall, <a href="http://ideas.arcgis.com/ideaView?id=087300000008FU7AAM">I suggested such a muted basemap</a> via the <a href="http://ideas.arcgis.com">ideas.arcgis.com</a> portal, so I was quite excited to hear it is in the works.</p>
<p>A post today, also by Bern, explained a new feature within <a href="http://blogs.esri.com/Support/blogs/arcgisonline/archive/2011/08/11/using-basemap-transparency.aspx">ArcGIS.com to allow the user to mute the basemap by adjusting it&#8217;s display transparency</a>.    The <a href="http://www.azavea.com/products/hunchlab/">HunchLab</a> team stumbled upon this idea a few months back and it&#8217;s been a great way to use the existing topographic basemap.    In our demo instance of HunchLab, we are using the ArcGIS.com Topographic tiles set to a transparency of 60%.   You can see what it looks like below.</p>
<p>Kudos to Esri &#8212; keep the basemap options coming!</p>
<p><img class="aligncenter size-full wp-image-1665" title="2011-08-11_1834--basemaptransparency" src="http://www.azavea.com/blogs/labs/wp-content/uploads/2011/08/2011-08-11_1834-basemaptransparency.png" alt="" width="450" height="331" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.azavea.com/blogs/labs/2011/08/bring-on-the-data-focused-basemaps-esri/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

