<?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/"
	xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule"
>

<channel>
	<title>Scratching Surfaces &#187; GIS</title>
	<atom:link href="http://www.surfaces.co.il/feed/?cat=3" rel="self" type="application/rss+xml" />
	<link>http://www.surfaces.co.il</link>
	<description>Open Source - GIS - Thoughts</description>
	<lastBuildDate>Wed, 22 May 2013 08:26:38 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
<creativeCommons:license>http://creativecommons.org/licenses/by-nc-sa/3.0/</creativeCommons:license>
		<item>
		<title>Get your phone GPS data into a GIS format</title>
		<link>http://www.surfaces.co.il/get-your-phone-gps-data-into-a-gis-format/</link>
		<comments>http://www.surfaces.co.il/get-your-phone-gps-data-into-a-gis-format/#comments</comments>
		<pubDate>Thu, 16 May 2013 19:45:57 +0000</pubDate>
		<dc:creator>Micha Silver</dc:creator>
				<category><![CDATA[GIS]]></category>
		<category><![CDATA[GPS]]></category>
		<category><![CDATA[Spatialite]]></category>

		<guid isPermaLink="false">http://www.surfaces.co.il/?p=1428</guid>
		<description><![CDATA[Nearly every new phone or tablet these days comes GPS enabled. And you can choose any of a slew of apps to capture GPS waypoints and tracks. But how do you get these data into a GIS system? Several apps save the GPS data into an sqlite database, so using Spatialite to convert the locations [...]]]></description>
				<content:encoded><![CDATA[<p>Nearly every new phone or tablet these days comes GPS enabled. And you can choose any of a slew of apps to capture GPS waypoints and tracks. But how do you get these data into a GIS system? Several apps save the GPS data into an sqlite database, so using <a href="https://www.gaia-gis.it/fossil/libspatialite/index" title="Spatialite website">Spatialite</a> to convert the locations to spatial layers is a piece of cake.<br />
<span id="more-1428"></span><br />
I tried using, for example, GPSEssentials, an Android app with all the bells and whistles. I&#8217;m not endorsing any one location app but this one (like some others) stores all its data into sqlite files. So I plugged my phone into a USB socket and copied the &#8220;waypoints&#8221; file from the gpsessentials folder over to my computer. Then I renamed the file to add the popular *.sqlite extension, and opened it in Spatialite_gui. For our purposes there are three tables of interest: Waypoint, Track, and TrackElement. The Waypoint table contains, of course, the waypoints with Longitude and Latitude coordinates, along with altitude, description, etc. The Track table is a list of tracks, and the TrackElement table is a crumb trail of Longitude/latitude values for each location along each of the tracks.<br />
To transform these tables into true spatial layers, for use in GIS, you must first make the sqlite DB spatial. So:</p>
<p><code>SELECT InitSpatialMetaData();</code></p>
<p>Now we can use the Longitude/Latitude values in the waypoints table to create actual geometries. First call the AddGeometryColumn function:</p>
<p><code>SELECT AddGeometryColumn('Waypoint','geometry',4326,'POINT','XY');<br />
UPDATE Waypoints SET geometry = MakePoint(longitude, latitude, 4326);</code></p>
<p>and Waypoint becomes a point layer ready to be opened in QGIS, for example, or exported to a shapefile.<br />
But what about the tracks? Here we need an additional step. We make the Track <strong>and </strong>TrackElement tables spatial, then use the TrackElements to create LINESTRING features in Track geometry column:</p>
<p><code>SELECT AddGeometryColumn('Track','geometry',4326,'LINESTRING','XY');<br />
SELECT AddGeometryColumn('TrackElement','geometry',4326,'POINT','XY');<br />
UPDATE TrackElement SET geometry = MakePoint(longitude, latitude, 4326);</code></p>
<p>and now do the update on the Track table:</p>
<p><code>UPDATE Track SET geometry = (SELECT MakeLine(te.geometry)<br />
FROM TrackElement as te<br />
WHERE te.trackID = Track._id<br />
GROUP BY te.trackID)<br />
</code></p>
<p>and you&#8217;re done. The Track table is now a true line feature, and can be exported as a shapefile, etc. The column names above are as they appear in the sqlite tables created by this particular app, so you might have to replace some of the ingredients. But the recipe should be similar. So get out your spatial mixing bowl, and your phone becomes a handy GIS tool.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.surfaces.co.il/get-your-phone-gps-data-into-a-gis-format/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by-nc-sa/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Creating Depth-Volume curves with GRASS-GIS</title>
		<link>http://www.surfaces.co.il/creating-depth-volume-curves-with-grass-gis/</link>
		<comments>http://www.surfaces.co.il/creating-depth-volume-curves-with-grass-gis/#comments</comments>
		<pubDate>Wed, 28 Nov 2012 20:05:17 +0000</pubDate>
		<dc:creator>Micha Silver</dc:creator>
				<category><![CDATA[GIS]]></category>
		<category><![CDATA[GRASS]]></category>

		<guid isPermaLink="false">http://www.surfaces.co.il/?p=1396</guid>
		<description><![CDATA[Our regional Drainage Authority prepared a reservoir at the mouth of a small dry riverbed to catch and regulate flood water coming from a mountain canyon. This reservoir was to act as a buffer to prevent flooding of agricultural fields and residential areas further down the valley. After a sudden rainstorm last week, the reservoir [...]]]></description>
				<content:encoded><![CDATA[<p>Our regional Drainage Authority prepared a reservoir at the mouth of a small dry riverbed to catch and regulate flood water coming from a mountain canyon. This reservoir was to act as a buffer to prevent flooding of agricultural fields and residential areas further down the valley. After a sudden rainstorm last week, the reservoir bravely fulfilled (pun intended <img src='http://www.surfaces.co.il/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  ) it&#8217;s duty. Now we want to know how much water was actually captured, and to create a depth volume curve for the small &#8220;lake&#8221; that was formed. Here&#8217;s how I did this using GRASS.<br />
<span id="more-1396"></span><br />
Luckily, we had ordered in advance LIDAR coverage of the whole area, so I have a high resolution (1 meter per pixel) DTM of the reservoir and streams which feed into it during flash floods. I first visually examined the elevation values at the spillover point where the reservoir drains when it fills, and the lowest point in the center of the depression. I then ran the GRASS module r.lake feeding it the x,y coordinates of the deepest point as the &#8220;seed&#8221; and the elevation just below the spillover as the water level parameters. The result gave me the lake&#8217;s depths as a raster. Here&#8217;s the result:</p>
<div id="attachment_1397" class="wp-caption aligncenter" style="width: 810px"><a href="http://www.surfaces.co.il/wp-content/uploads/2012/11/Amram_reservoir.png"><img class="size-full wp-image-1397" title="Amram_reservoir" src="http://www.surfaces.co.il/wp-content/uploads/2012/11/Amram_reservoir.png" alt="amram reservoir" width="800" height="600" /></a><p class="wp-caption-text">DTM and reservoir created with r.lake</p></div>
<p>Now I ran r.univar on the lake raster, to find</p>
<ul>
<li>the maximum value = water depth</li>
<li>the sum of all pixels = total volume of the reservoir</li>
<li>the number of pixels = surface area covered by water</li>
</ul>
<p>Since the region settings were 1 meter per pixel, the number of cells = area in sq.m. and the sum of all cells = volume in cubic meters.</p>
<p>Now I wanted to run the same procedure for water levels stepping down from the top spillover level to the bottom of the reservoir when it dries up due to leaching and evaporation. A script suggested itself, and here&#8217;s the <code>depth_volume.sh</code> script that I conjured up:</p>
<p><code><strong><br />
#!/bin/bash<br />
# Author: micha, 7/11/2012; copyright: GPL &gt;= 2<br />
# Purpose: calculate volume, area and depth of a reservoir<br />
# from a DEM raster and given water level using r.lake<br />
# calculate volume and area with r.univar<br />
# export the results to a text file for use in gnuplot<br />
# Usage: depth_volume.sh  {dem raster} {water level} {seed location as x,y}</p>
<p>if [ -z "$GISBASE" ] ; then<br />
echo "You must be in GRASS GIS to run this program." 1&gt;&amp;2<br />
exit 1<br />
fi</p>
<p>if [ $# -lt 3 ] ; then<br />
echo "Some inputs not defined. Usage: $0 dem_raster water_level seed_x,seed_y"<br />
exit 1<br />
fi</p>
<p>DEM=$1<br />
LEVEL=$2<br />
SEED=$3</p>
<p>g.message "Flooding lake at water level $LEVEL"<br />
# Get resolution to calculate area and volume based on pixel size<br />
NSRES=`g.region -g | grep nsres | cut -d= -f2`<br />
EWRES=`g.region -g | grep ewres | cut -d= -f2`<br />
PIXEL=`echo $NSRES*$EWRES | bc`<br />
# Run r.lake<br />
r.lake --quiet --o $DEM wl=$LEVEL xy=$SEED lake="$DEM"_tmp</p>
<p># Collect needed numbers from r.univar<br />
eval `r.univar -g "$DEM"_tmp`<br />
VOLUME=`echo $sum*PIXEL/1000 | bc`<br />
DEPTH=$max<br />
AREA=`echo $n*$PIXEL | bc`</p>
<p># Dump results into a text file<br />
echo "$LEVEL $DEPTH $VOLUME $AREA" &gt;&gt; depth_volume.txt<br />
</strong></code></p>
<p>The script takes three inputs: the DEM, water level and the X-Y coordinates for seeding the lake (as mentioned I chose the lowest spot in the depression). After running r.lake, the r.univar output is parsed to collect the needed numbers, and the results are dropped into a text file.<br />
Now I ran this script in a loop with all the water levels that interested us. We wanted water volumes for each 1/2 meter drop in the water surface, so:</p>
<p><code><strong>for level in 27 26.5 26 25.5 25 24.5 24 23.5 23 22.5; \<br />
do depth_volume.sh dem $level 194365,397295; done</strong></code></p>
<p>The depth_volume.txt file that is created has water level, volume and surface area for each of the above elevations. Now, to create a depth-volume curve, I could pull this text file into LibreOffice calc for designing a fancy chart. But for a quick and simple display, I used gnuplot with these commands:</p>
<p><code><strong>set title "Depth-Volume Curve"<br />
set xlabel "Volume 1000 m3"<br />
set ylabel "Depth m."<br />
set x2label "Area sqm."<br />
set key left box<br />
set x2tics nomirror<br />
set autoscale x2<br />
set grid y<br />
set terminal png enhanced size 800,600<br />
set output "depth_volume.png"<br />
plot "depth_volume.txt" using 3:2 title "Volume 1000 m3" with lines lw 3,  \<br />
	"depth_volume.txt" using 4:2 title "Area m2" with lines axes x2y1<br />
</strong></code></p>
<p>The graph looks like this:<br />
<div id="attachment_1399" class="wp-caption aligncenter" style="width: 810px"><a href="http://www.surfaces.co.il/wp-content/uploads/2012/11/depth_volume.png"><img src="http://www.surfaces.co.il/wp-content/uploads/2012/11/depth_volume.png" alt="depth_volume" title="depth_volume" width="800" height="600" class="size-full wp-image-1399" /></a><p class="wp-caption-text">Depth Volume curve from gnuplot</p></div></p>
<p>Once I have setup the GRASS script and gnuplot command file, running the model with other parameters or in some other location is a piece of cake.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.surfaces.co.il/creating-depth-volume-curves-with-grass-gis/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by-nc-sa/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>New Labeling in Quantum GIS</title>
		<link>http://www.surfaces.co.il/new-labeling-in-quantum-gis/</link>
		<comments>http://www.surfaces.co.il/new-labeling-in-quantum-gis/#comments</comments>
		<pubDate>Mon, 26 Nov 2012 20:55:11 +0000</pubDate>
		<dc:creator>Micha Silver</dc:creator>
				<category><![CDATA[GIS]]></category>
		<category><![CDATA[QGIS]]></category>

		<guid isPermaLink="false">http://www.surfaces.co.il/?p=1381</guid>
		<description><![CDATA[The new labeling setup in QGIS has been around for over a year now, and in the upcoming version it will become the default, replacing the old labeling. This new engine brings some advanced options that are quite worth learning, such as bulding labels from expressions, and conditional labeling. I&#8217;ll expand on some of these [...]]]></description>
				<content:encoded><![CDATA[<p>The new labeling setup in QGIS has been around for over a year now, and in the upcoming version it will become the default, replacing the old labeling. This new engine brings some advanced options that are quite worth learning, such as bulding labels from expressions, and conditional labeling. I&#8217;ll expand on some of these tricks that have already appeared in other QGIS blogs<br />
<span id="more-1381"></span><br />
The basics of the New Labeling already are included in the <a href="http://documentation.qgis.org/html/en/docs/user_manual/working_with_vector/vector_properties.html#new-labeling" title="QGIS Documentation">QGIS Documentation</a>. Data defined label placement has been improved and expanded compared with the old labeling. Now we can have columns in the layer&#8217;s attribute table for rotation of the label, buffer size and color, and even text alignment.</p>
<p>In <a href="http://woostuff.wordpress.com/2011/10/27/expression-based-labeling/" title="Nathan W Blog">Nathan W&#8217;s blog</a> he introduced Expression based labeling. Now we can construct labels using combinations of math functions and string functions to manipulate any attribute column the way we want. Currently, in versions 1.8.x, find and click the &#8220;ABC&#8221; button to access the &#8220;Layer Label settings&#8221; window. Stay tuned for the next version of QGIS, when this New Labeling will become the default, and be merged into regular Layer Properties window.  In the Layer Label settings window, after checking the checkbox to &#8220;Label this layer with&#8221; you can click the ellipsis button [...] to open the full expression builder window, and use your imagination to create a variety of informative labels.</p>
<p>Here&#8217;s a classic example. If I add an Area column (using the Field calculator, $area function) the values I get, in a projected coordinate system. are square meters. But suppose I want to label a polygon layer with hectares? The label expression will be:<br />
<code><strong>"Area" / 10000</strong></code><br />
But that&#8217;s not enough. This expression returns a real number with a long string of digits after the decimal point. So we instead can enter into the expression calculator:<br />
<code><strong>toint( "Area" / 10000)</strong></code><br />
to round the number to an integer. And one more improvement: what about adding the &#8220;ha&#8221; tag as units to the labels?<br />
<code><strong>toint( "Area" / 10000) || ' ha'</strong></code></p>
<p>We also have the ability now to create conditional labels thanks to Martin Dobias. One example appears in <a href="http://underdark.wordpress.com/2012/01/09/easier-conditional-labels-in-qgis/" title="Underdark's blog">Underdark&#8217;s blog</a>. Here&#8217;s another straight forward example: I have a point layer of rain gauges. I want to label all those gauges with precipitation greater than 2 mm. No label at all should appear when the gauge shows < 2 mm.<br />
<code><strong>CASE WHEN ("precip" >= 2) THEN "precip" END</strong></code><br />
Of course several <code><strong>WHEN {condition} THEN {label}</strong></code> pairs can be chained together to get several different categories of labels.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.surfaces.co.il/new-labeling-in-quantum-gis/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by-nc-sa/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Strahler stream order in GRASS</title>
		<link>http://www.surfaces.co.il/strahler-stream-order-in-grass/</link>
		<comments>http://www.surfaces.co.il/strahler-stream-order-in-grass/#comments</comments>
		<pubDate>Sat, 01 Sep 2012 17:02:50 +0000</pubDate>
		<dc:creator>Micha Silver</dc:creator>
				<category><![CDATA[GIS]]></category>
		<category><![CDATA[GRASS]]></category>

		<guid isPermaLink="false">http://www.surfaces.co.il/?p=1321</guid>
		<description><![CDATA[In hydrology, a stream network is composed of segments or &#8220;reaches&#8221; which are arranged in a hierachy. There are several systems of ordering the stream reaches, the most popular of which is the Strahler or Horton  number. GRASS GIS offers, alongside the watershed delineation tool r.watershed (discussed here), a set of addons for stream network [...]]]></description>
				<content:encoded><![CDATA[<p>In hydrology, a stream network is composed of segments or &#8220;reaches&#8221; which are arranged in a hierachy. There are several systems of ordering the stream reaches, the most popular of which is the <a title="Strahler" href="http://en.wikipedia.org/wiki/Strahler_number">Strahler or Horton  </a>number. <a title="GRASS GIS" href="http://grass.osgeo.org/intro/general.php">GRASS GIS</a> offers, alongside the watershed delineation tool <a title="Watershed wiki page" href="http://grass.osgeo.org/wiki/Creating_watersheds">r.watershed </a>(discussed <a title="Surfaces.co.il watershed" href="http://www.surfaces.co.il/?p=241">here</a>), a set of <a title="r.stream addons" href="http://grass.osgeo.org/wiki/R.stream.*">addons for stream network</a> analysis. We&#8217;ll examine how to use these addons, and how to use strahler ordering to improve the visual effect of a stream network map.</p>
<p><span id="more-1321"></span></p>
<p>We begin with an elevation raster call &#8216;dtm&#8217;. This could be data from the ASTER GDEM program or SRTM tiles. Zoom in to the general area of interest and (as always) set the GRASS region to match that area.<br />
<strong>
<pre>
g.region -p n=30:54N s=30N e=35:30E w=34:36E
</pre>
<p></strong></p>
<p>First we run two r.stream.* commands to create the stream network, and a database table of stream ordering.<br />
<strong>
<pre>
r.stream.extract elev=dtm thresh=25000 stream_rast=streams_25 stream_vect=streams_25 direction=fdir_25 
r.stream.order stream=streams_25 dir=fdir_25 table=stream_order
</pre>
<p></strong></p>
<p>The r.stream.extract command uses the dtm as input, together with a threshold value which we determine. The threshold represents the number of raster cells which will become a <strong>minimim</strong> drainage catchment in the resulting stream network. You need to know the size (resolution) of the cells in your dtm raster in order to do the arithmetic for this threshold value. In the example above, the dtm (based on ASTER GDEM data) has a resolution 30 meters, so 25,000 cells is about 20 sq. km.  Then the r.stream.order command uses the newly created streams_25 map of streams to create a table of stream ordering. The command places the table into the default database used by GRASS. In this case sqlite.</p>
<p>Before continuing, we&#8217;ll have a look at what we&#8217;ve got.</p>
<pre><strong>v.db.select streams_25 | head cat|stream_type|type_code 1|start|0 2|start|0 3|start|0 4|intermediate|1 5|start|0</strong></pre>
<p>So the vector stream map has only three columns &#8211; the cat value, and a name and code indicating if the stream segment is a headwater segment, or further down in the hierarchy. To examine the stream_order table, we need to have a look right in the sqlite database, so:<br />
<strong></strong></p>
<pre>eval `g.gisenv` 
sqlite3 $GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db 
sqlite&gt; .header on</pre>
<p>&nbsp;</p>
<p>A quick SELECT statement on the streams_25 table (attached to the stream_25 vector map) will show the same data as above.</p>
<pre>
sqlite&gt; SELECT * FROM streams_25 LIMIT 5; 
cat|stream_type|type_code 
1|start|0 
2|start|0 
3|start|0 
4|intermediate|1 
5|start|0
</pre>
<p>Next we do a SELECT on the <strong>stream_order</strong> table:<br />
<strong></p>
<pre>
sqlite&gt; SELECT * FROM stream_order LIMIT 10; 
cat         stream      next_str    prev_str01  prev_str02  strahler    horton      shreve      hack        topo_dim    length      cum_length  out_dist     straight    fractal 
----------  ----------  ----------  ----------  ----------  ----------  ----------  ----------  ----------  ----------  ----------  ----------  -----------  ----------  ---------- 
1           1           20          0           0           1           1           1           2           38          929.78593   929.78593   7775.778998  676.39042   1.374629 
2           2           4           0           0           1           3           1           1           29          300.43355   300.43355   8053.78109   233.019313  1.289308 
3           3           4           0           0           1           1           1           2           29          3.828427    3.828427    7757.175967  3.605551    1.061815 
4           4           10          3           2           2           3           2           1           28          667.10974   967.543289  7753.34754   549.315938  1.214437 
sqlite&gt; .quit
</pre>
<p></strong><br />
So this second table has all the good stuff &#8211; next stream cat number, previous streams, the ordering in four different systems, as well as length, cumulative length for each stream reach and so on. We want to attach this table to the streams_25 map. This is accomplished with v.db.connect. The &#8216;-o&#8217; flag indicates that we are <strong>overwriting</strong> the original table connection. And the &#8216;key=cat&#8217; parameter says that the cat values in the geometry match the &#8216;cat&#8217; column in the sqlite table. Now we quit sqlite, and back in GRASS we issue:</p>
<pre><strong>v.db.connect -o streams_25 driver=sqlite table=stream_order key=cat</strong></pre>
<p>If we now run a SELECT on the streams_25 map, we find:<br />
<strong></p>
<pre>
v.db.select streams_25 | head 
cat|stream|next_str|prev_str01|prev_str02|strahler|horton|shreve|hack|topo_dim|length|cum_length|out_dist|straight|fractal
1|1|20|0|0|1|1|1|2|38|929.78593|929.78593|7775.778998|676.39042|1.374629
2|2|4|0|0|1|3|1|1|29|300.43355|300.43355|8053.78109|233.019313|1.28930
3|3|4|0|0|1|1|1|2|29|3.828427|3.828427|7757.175967|3.605551|1.061815
4|4|10|3|2|2|3|2|1|28|667.10974|967.543289|7753.34754|549.315938|1.214437
5|5|19|0|0|1|4|1|1|39|1050.680374|1050.680374|8229.62171|817.765247|1.284819
6|6|12|0|0|1|1|1|2|26|215.865007|215.865007|7098.509878|174.103418|1.239867
</pre>
<p></strong><br />
All the stream ordering and other data is now part of the streams_25 vector map. We next run the r.stream.basins command to create a map of the basins. The &#8216;-l&#8217; flag is set so that only major basins  (with a outlet at the edge of the current region) are delineated.</p>
<p><strong>
<pre>
r.stream.basins -l dir=fdir_25 stream=streams_25 basin=major_basins
</pre>
<p></strong></p>
<p>Now we&#8217;re ready to make use of the data and maps we&#8217;ve created. We create a shaded relief, and overlay the basins with transparency.  In addition, In the GRASS GUI, you can display a line vector at varying widths, taking the width from an attribute column. We&#8217;ll use the strahler order values to make stream vector lines at the top slopes of the basin appear thin, and those nearer to the basin outlet will be thicker. Here&#8217;s the result.</p>
<div id="attachment_1359" class="wp-caption aligncenter" style="width: 810px"><a href="http://www.surfaces.co.il/wp-content/uploads/2012/09/faran_basin_strahler.png"><img class="size-full wp-image-1359" title="faran_basin_strahler" src="http://www.surfaces.co.il/wp-content/uploads/2012/09/faran_basin_strahler.png" alt="Faran basin" width="800" height="600" /></a><p class="wp-caption-text">Faran basin &#8211; wadis displayed with strahler order</p></div>
<p>Often you&#8217;ll need to isolate one particular sub-basin and display only that basin and it&#8217;s stream network. Here&#8217;s a way to do that. We first display the stream_25 raster map, and zoom in very close to the outlet of the sub-basin we&#8217;re trying to isolate. We need to get the exact X-Y coordinates at the outlet of that basin. In the GRASS GUI  Map Display window we can use the &#8220;Query raster/vector map&#8221; button (the gui version of the r.what command) to get the coordinates by clicking on the drainage point. The coordinates appear in the &#8220;Command console&#8221; of the Layer Manager window. Copy/paste these coordinates to the terminal and run r.stream.basins a second time as follows:</p>
<pre>r.stream.basins dir=fdir_25 coors=35.226820,30.632014 basin=basin_1</pre>
<p>Display this map in the Map Display to be sure it&#8217;s the basin you need. Now it&#8217;s a good idea to reset the region parameters to &#8220;close-in&#8221; on this basin, in order to avoid large raster maps with NULL cells covering large areas around your isolated basin.<br />
<strong></strong></p>
<pre>g.region n=30:45N s=30:18N e=35:15E w=34:36E -p
r.mask in=basin_1 
r.mapcalc nekarot_basin=basin_1 
r.mapcalc nekarot_dtm=dtm 
r.shaded.relief nekarot_dtm shade=nekarot_shade</pre>
<p>&nbsp;</p>
<p>We&#8217;ve created new rasters for the isolated basin, the dtm, and the shaded relief, all clipped to the area of the isolated basin by using a raster MASK. After completing those steps the mask is no longer necessary, we can remove it, and the temporary map &#8216;basin_1&#8242; as well. Then use the regular GRASS commands to create an area vector of the isolated basin, and to clip the original streams vector to this basin.</p>
<pre>r.mask -r 
g.remove rast=basin_1 
r.to.vect in=nekarot_basin out=nekarot_basin feature=area 
v.select --o ainput=streams_25 atype=line binput=nekarot_basin btype=area output=nekarot_streams operator=overlap</pre>
<p>And the result looks like this:</p>
<div id="attachment_1360" class="wp-caption aligncenter" style="width: 810px"><a href="http://www.surfaces.co.il/wp-content/uploads/2012/09/nekarot_basin_strahler.png"><img class="size-full wp-image-1360" title="nekarot_basin_strahler" src="http://www.surfaces.co.il/wp-content/uploads/2012/09/nekarot_basin_strahler.png" alt="Nekarot basin" width="800" height="600" /></a><p class="wp-caption-text">Nekarot basin &#8211; wadis displayed with strahler order</p></div>
]]></content:encoded>
			<wfw:commentRss>http://www.surfaces.co.il/strahler-stream-order-in-grass/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by-nc-sa/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>From Lat/Lon to UTM zone in Spatialite</title>
		<link>http://www.surfaces.co.il/from-latlon-to-utm-zone-in-spatialite/</link>
		<comments>http://www.surfaces.co.il/from-latlon-to-utm-zone-in-spatialite/#comments</comments>
		<pubDate>Sun, 05 Aug 2012 20:03:36 +0000</pubDate>
		<dc:creator>Micha Silver</dc:creator>
				<category><![CDATA[GIS]]></category>
		<category><![CDATA[Spatialite]]></category>

		<guid isPermaLink="false">http://www.surfaces.co.il/?p=1298</guid>
		<description><![CDATA[There are several PostGIS functions floating around to calculate the UTM zone EPSG code for points in Latitude/Longitude WGS84. However, Spatialite, based on Sqlite, does not support user created functions. So how can we get the same results in a Spatialite database? [Correction: Spatialite does, of course, have built in functions, and users can create [...]]]></description>
				<content:encoded><![CDATA[<p>There are several PostGIS functions <a title="PostGIS utmzone function" href="http://postgis.refractions.net/pipermail/postgis-users/2005-December/010262.html">floating around</a> to calculate the UTM zone EPSG code for points in Latitude/Longitude WGS84. However, Spatialite, based on Sqlite, does not support user created functions. So how can we get the same results in a Spatialite database?<br />
<span id="more-1298"></span></p>
<p><em>[Correction: Spatialite does, of course, have built in functions, and users can create their own functions using the C API. However - unlike PostGIS - there is no support for creating SQL (or other procedural languages) based functions. SQlite does not have the equivalent of the CREATE FUNCTION command in SQL]</em></p>
<p>The EPSG codes for UTM zones can be calculated as (Longitude+186)/6 + 32600. In the southern hemisphere, it&#8217;s (Long+186)/6 + 32700. The last two digits of each EPSG code are the UTM zone. The third digit, 6 or 7 indicates N or S. We can use the Sqlite CASE WHEN&#8230;ELSE&#8230;END construct to get the correct EPSG code for a table of point locations as follows:</p>
<p>We begin with the freely available geonames <a title="cities15000" href="http://download.geonames.org/export/dump/cities15000.zip">cities15000</a> file. This is a tab delimited text file of some 22,000 cities (with population over 15,000) around the world. I linked to the table, (making a virtual table in Spatialite), and used the data to create a real table with more convenient column names. I then made the table spatial, and used the latitude and longitude columns to set the Geometry for all cities.</p>
<p><code>CREATE TABLE cities (<br />
id integer primary key autoincrement, geoname_code integer, Name text, Name_en text,<br />
lat double, lon double, Country_ISO text, pop integer, Country text);</code></p>
<p>INSERT INTO cities</p>
<p style="padding-left: 20px;">(geoname_code, Name, Name_en, lat, lon, Country_ISO, pop, Country)</p>
<p>SELECT</p>
<p style="padding-left: 20px;">col001, col002, col003, col005, col006, col009, col015, col018</p>
<p>FROM cities15000;</p>
<p>Now setup the Geometry column</p>
<p><code>SELECT AddGeometryColumn('cities','Geometry',4326,'POINT','XY');<br />
UPDATE cities SET Geometry=MakePoint(lon, lat, 4326);<br />
</code><br />
And here&#8217;s how to construct a query to get the UTM zone for each city:<br />
<code><br />
SELECT Name_en AS "City", Country AS "Continent/Country",<br />
CASE WHEN ST_Y(Geometry)&gt;0 THEN</code></p>
<p style="padding-left: 20px;">CASE WHEN ST_X(Geometry)=180 THEN<br />
32660<br />
ELSE<br />
(CAST(ST_X(Geometry) AS INTEGER)+186)/6+32600<br />
END</p>
<p>ELSE</p>
<p style="padding-left: 20px;">CASE WHEN ST_X(Geometry)=180 THEN<br />
32760<br />
ELSE<br />
(CAST(ST_X(Geometry) AS INTEGER)+186)/6+32700<br />
END</p>
<p>END AS &#8220;UTM SRID&#8221;<br />
FROM cities<br />
WHERE SRID(Geometry)=4326;</p>
<p>A few comments:</p>
<ul>
<li>The final WHERE clause insures that no EPSG codes will be returned if the point layer is not in Lat/Lon WGS84 to begin with.</li>
<li>The outer CASE statement separates Northern and Southern hemispheres.</li>
<li>The inner CASE catches the edges where longitude values are 180 degrees.</li>
</ul>
<p>Here are some results:</p>
<pre>City          Continent/Country  UTM SRID  
------------  -----------------  ----------
Sao Jeronimo  America/Sao_Paulo  32722     
Jeremoabo     America/Bahia      32724     
Saint-Jerome  America/Montreal   32618     
Aguada de Pa  America/Havana     32617     
Esbjerg       Europe/Copenhagen  32632     
Jerez de la   Europe/Madrid      32630     
Jeremie       America/Port-au-P  32618     
Jerusalem     Asia/Jerusalem     32636     
West Jerusal  Asia/Jerusalem     32636     
Manjeri       Asia/Kolkata       32643     
Borujerd      Asia/Tehran        32639     
Jerada        Africa/Casablanca  32630     
San Jeronimo  America/Mexico_Ci  32615     
Jerez de Gar  America/Mexico_Ci  32613     
Jerantut      Asia/Kuala_Lumpur  32648     
Ijero-Ekiti   Africa/Lagos       32631     
Oud-Beijerla  Europe/Amsterdam   32631     
Steinkjer     Europe/Oslo        32632     
Jericho       Asia/Hebron        32636     
East Jerusal  Asia/Hebron        32636     
Oum Hadjer    Africa/Ndjamena    32634     
Tajerouine    Africa/Tunis       32632     
Njeru         Africa/Kampala     32636     
Jersey City   America/New_York   32618     
Las Tejerias  America/Caracas    32619</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.surfaces.co.il/from-latlon-to-utm-zone-in-spatialite/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by-nc-sa/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Manipulating GPS tracks in Spatialite</title>
		<link>http://www.surfaces.co.il/manipulating-gps-tracks-in-spatialite/</link>
		<comments>http://www.surfaces.co.il/manipulating-gps-tracks-in-spatialite/#comments</comments>
		<pubDate>Tue, 17 Jul 2012 20:13:41 +0000</pubDate>
		<dc:creator>Micha Silver</dc:creator>
				<category><![CDATA[GIS]]></category>
		<category><![CDATA[GPS]]></category>
		<category><![CDATA[Mountain Biking]]></category>
		<category><![CDATA[Spatialite]]></category>

		<guid isPermaLink="false">http://www.surfaces.co.il/?p=1250</guid>
		<description><![CDATA[I returned from a short bike outing with my ride captured as a GPS track. Along the way, I also grabbed the rest stops as waypoints. Both of these were downloaded from the GPS as *.gpx files. So I have tracks.gpx and waypoints.gpx. Now I want to push these layers straight into Spatialite, and do some [...]]]></description>
				<content:encoded><![CDATA[<p>I returned from a short bike outing with my ride captured as a GPS track. Along the way, I also grabbed the rest stops as waypoints. Both of these were downloaded from the GPS as <a title="gpx" href="http://www.topografix.com/gpx.asp">*.gpx</a> files. So I have tracks.gpx and waypoints.gpx. Now I want to push these layers straight into Spatialite, and do some calculations.<br />
<span id="more-1250"></span></p>
<p>I pulled the data from my GPS using <a title="GPSBabel" href="http://www.gpsbabel.org/">gpsbabel</a> but you can also choose the Quantum GIS GPSTools plugin to download GPS data in GPX format. Now to move these layers straight into a Spatialite database I use the ogr2ogr utility. This is part of the GDAL toolset, the &#8220;Swiss Army Knife&#8221; of spatial data formats. It allows me to move vector data from one format to another, with several options to filter or alter the original data along the way.<br />
Here&#8217;s how I start:</p>
<p><code>$ ogr2ogr -f SQLite -nln ride -dsco "SPATIALITE=YES" -t_srs "EPSG:4326" bike_rides.sqlite bike_rides.gpx tracks</code></p>
<p>The first option sets the output format &#8216;<code>-f</code>&#8216; as SQLite. Next I use &#8216;<code>-nln</code>&#8216; to choose a &#8220;New Layer Name&#8221; for the table to be created. The &#8216;<code>-dsco</code>&#8216; options means &#8220;DataSet Create Option&#8221; and here we dictate Spatialite. The next flag &#8216;<code>-t_srs</code>&#8216; sets the spatial reference system for the data layer. While not strictly necessary (GPS data is always Lon/Lat WGS84) it&#8217;s a good policy to always set the SRS explicitly. Now pay attention to the order of the next parameters: the target database is first, and the source (gpx file) is second. This is backwards from many other command line tools. Normally we expect first the &#8220;from&#8221; followed by the &#8220;to&#8221;. For ogr2ogr it&#8217;s: &#8220;destination&#8221; first and &#8220;source&#8221; following. And finally at the end of the above command we choose to bring only GPS <code>tracks</code> into the database.</p>
<p>If our GPX file contains several tracks (perhaps from previous bike rides) we can filter those out with a simple -sql option such as:</p>
<p><code>$ ogr2ogr -f SQLite bike_rides.sqlite bike_rides.gpx -nln amazia_ride -dsco "SPATIALITE=YES" -sql "SELECT name, number FROM tracks WHERE name='Amazia-2' " tracks<br />
</code></p>
<p>Next, I need to get the stops along the way, which were captured as waypoints. Similar to above:</p>
<p><code>$ ogr2ogr -f SQLite bike_rides.sqlite waypoints.gpx -nln stops -append waypoints</code></p>
<p>Now, I don&#8217;t user the &#8216;-dsco&#8217; parameter since the database already exists. What&#8217;s more, I must specify &#8216;<code>-append</code>&#8216; to instruct ogr2ogr to <strong>add</strong> this layer as a new table in the existing sqlite database.</p>
<p>OK, how long was the whole ride? The built in Spatialite function GeodesicLength() calculates lengths of Lon/Lat features <strong>in meters</strong>, along the WGS84 ellipsoid.</p>
<p>spatialite&gt; SELECT GeodesicLength(r.Geometry) AS &#8220;Total Length&#8221; FROM ride AS r;<br />
Total Length<br />
&#8212;&#8212;&#8212;&#8212;&#8212;<br />
9696.2803124924</p>
<p>But I want to know how much each section of the ride was. In other words, I want to see the accumulated distance at each of the stops. We have in spatialite a function ST_Line_Locate_Point() which returns the distance along a line feature for points near the line. (It actually finds the nearest point on the line for each of the input points). So we do:</p>
<p><code>spatialite&gt; SELECT s.name AS "Stop name",<br />
...&gt; ST_Line_Locate_Point(r.Geometry, s.Geometry) AS "Stop Locations"<br />
...&gt; FROM ride AS r, stops AS s<br />
...&gt; GROUP BY s.name ORDER BY s.OGC_FID;<br />
Stop name   Stop Locations<br />
----------  --------------<br />
start       0.0<br />
rest 1      0.124783450768<br />
water stop  0.361703783084<br />
rest 2      0.562004941906<br />
rest 3      0.712163267248<br />
overlook    0.850818111308<br />
end         0.996608235043<br />
</code></p>
<p>The <code>OGC_FID</code> field is automatically created by ogr2ogr as a <em>primary key</em>. So doing &#8220;<code>ORDER BY</code>&#8221; on that field insures that the stop points are displayed in the correct order. But the numbers above are not distances, but rather the <strong>fraction</strong> of the total line length where each point falls. Now multiplying these fractions by the total length from the first query above, I get:</p>
<p><code>spatialite&gt; SELECT s.name AS "Stop name",<br />
...&gt; ST_Line_Locate_Point(r.Geometry, s.Geometry)*GeodesicLength(r.Geometry) AS "Accumlulated Distances"<br />
...&gt; FROM ride AS r, stops AS s<br />
...&gt; GROUP BY s.name ORDER BY s.OGC_FID;<br />
Stop name   Accumlulated Distances<br />
----------  ----------------------<br />
start       0.0<br />
rest 1      1209.93531700926<br />
water stop  3507.18127087581<br />
rest 2      5449.35745373272<br />
rest 3      6905.3346675029<br />
overlook    8249.77090219153<br />
end         9663.3928087156</code></p>
<p><strong>Nice</strong>. One last step, let&#8217;s put these distances permanently into the &#8220;stops&#8221; table.</p>
<p><code>spatialite&gt; ALTER TABLE stops ADD COLUMN accum_dist float;<br />
spatialite&gt; UPDATE stops SET accum_dist=(SELECT<br />
...&gt; ST_Line_Locate_Point(r.Geometry, s.Geometry)*GeodesicLength(r.Geometry)<br />
...&gt; FROM tracks AS r, stops AS s<br />
...&gt; WHERE s.OGC_FID=stops.OGC_FID);</code></p>
<p>We use a subquery to UPDATE the stops table. Take note of the WHERE condition: the OGC_FID values from the stops table <strong>outside of the subquery</strong> must match the values from the same column inside the query.</p>
<p><code>spatialite&gt; SELECT name AS "Stop name",accum_dist AS "Accumulated Distance" FROM stops;<br />
Stop name Accumulated Distance<br />
---------- --------------------<br />
start       0.0<br />
rest 1      1209.93531700926<br />
water stop  3507.18127087581<br />
rest 2      5449.35745373272<br />
rest 3      6905.3346675029<br />
overlook    8249.77090219153<br />
end         9663.3928087156<br />
</code><br />
There we are: accumulated distances for waypoints along a GPS track.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.surfaces.co.il/manipulating-gps-tracks-in-spatialite/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by-nc-sa/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Getting QGIS 1.8 running on Scientific Linux 6</title>
		<link>http://www.surfaces.co.il/getting-qgis-1-8-running-on-scientific-linux-6/</link>
		<comments>http://www.surfaces.co.il/getting-qgis-1-8-running-on-scientific-linux-6/#comments</comments>
		<pubDate>Sun, 15 Jul 2012 12:33:27 +0000</pubDate>
		<dc:creator>Micha Silver</dc:creator>
				<category><![CDATA[GIS]]></category>

		<guid isPermaLink="false">http://www.surfaces.co.il/?p=1260</guid>
		<description><![CDATA[Quantum GIS is marching ahead and the latest stable version, 1.8.0, provides some new features and improvements. RPM packages are already out for Fedora, but not yet for the Red Hat 6 clones like Scientific Linux 6. Compiling on your own isn&#8217;t hard, so if you don&#8217;t want to wait for the official package, here [...]]]></description>
				<content:encoded><![CDATA[<p>Quantum GIS is marching ahead and the latest stable version, 1.8.0, provides some new features and improvements. RPM packages are already out for Fedora, but not yet for the Red Hat 6 clones like Scientific Linux 6. Compiling on your own isn&#8217;t hard, so if you don&#8217;t want to wait for the official package, here are a few pointers.<br />
<span id="more-1260"></span><br />
We&#8217;ll assume you already have a build environment with gcc-c++, flex, bison, PyQt4 etc. Check the QGIS wiki <a title="wiki page" href="http://www.qgis.org/api/INSTALL.html">wiki page</a> for details regarding dependencies. While the instructions are specific for Ubuntu systems, it&#8217;s fairly clear which parallel packages you will need to install on SL6. Also you will want to install the whole geospatial stack, all from standard repos or the <a title="EPEL" href="http://fedoraproject.org/wiki/EPEL/FAQ#How_can_I_install_the_packages_from_the_EPEL_software_repository.3F">EPEL </a> and <a title="elgis" href="http://elgis.argeo.org/">elgis </a> repos. This includes geos, proj, grass-6.4.2, gdal-1.8.1 and all the -devel packages as well.</p>
<p>Download the <a title="source code" href="http://qgis.org/downloads/qgis-1.8.0.tar.bz2">source code </a>for QGIS and untar in a directory of your choice. Before starting the configure and make steps there&#8217;s one simple edit required for EL6 and similar: under the python directory open the file CMakeLists.txt. You&#8217;ll find four lines like:<br />
<code>SET(SIP_EXTRA_OPTIONS ${PYQT4_SIP_FLAGS} -o -a ${CMAKE_BINARY_DIR}/python/qgis.core.api)</code><br />
These are lines 64, 80, 94, 100<br />
You need to remove the &#8220;-o&#8221; option from each. This is a flag for &#8220;sip&#8221; which handles bindings between c++ and python. This new flag was introduced in recent versions of sip, and it&#8217;s not available in the EL6 sip packages. Removing the extra flag has no ill effects on the compilation (I believe it&#8217;s only applicable to the comments in the source code). So each of the four lines should be:<br />
<code>SET(SIP_EXTRA_OPTIONS ${PYQT4_SIP_FLAGS} -a ${CMAKE_BINARY_DIR}/python/qgis.core.api)</code></p>
<p>If you prefer to make the above changes with &#8216;patch&#8217; here&#8217;s a <a title="diff" href="http://lists.osgeo.org/pipermail/el/attachments/20120704/dded1341/attachment.bin">diff</a> file provided by Volker Froehlich (Fedora GIS maintainer).<br />
Now, following more or less the instructions from that same wiki page above, you create a subdirectory &#8220;build&#8217;, drop into that directory and run:<br />
<code>$ cmake -L -DGRASS_PREFIX=/usr/grass-6.4.2 -DGDAL_LIBRARY=/usr/lib64/libgdal.so ..</code><br />
(Don&#8217;t skip the two dots .. at the end of the command)</p>
<p>The two specific directives to the cmake command indicate where the GRASS installation and libgdal are. These paths are based on GRASS and GDAL being installed from RPM&#8217;s. If you&#8217;ve cooked your own GRASS or GDAL, set the above appropriately. Now you&#8217;re ready to go:<br />
<code>$ make<br />
$ sudo make install<br />
</code><br />
One more step is required so that QGIS can &#8220;find&#8221; the GRASS libraries. Add a one line file into /etc/ld.so.conf.d which contains:<br />
<code>$ cat /etc/ld.so.conf.d/grass.conf<br />
/usr/grass-6.4.2/lib<br />
</code><br />
and do:<br />
<code>sudo ldconfig</code></p>
<p>Now you should be ready to enjoy the new, updated QGIS 1.8.0 &#8216;Lisboa&#8217;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.surfaces.co.il/getting-qgis-1-8-running-on-scientific-linux-6/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by-nc-sa/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Spatialite on Ubuntu</title>
		<link>http://www.surfaces.co.il/spatialite-on-ubuntu/</link>
		<comments>http://www.surfaces.co.il/spatialite-on-ubuntu/#comments</comments>
		<pubDate>Fri, 29 Jun 2012 17:39:38 +0000</pubDate>
		<dc:creator>Micha Silver</dc:creator>
				<category><![CDATA[GIS]]></category>
		<category><![CDATA[Spatialite]]></category>

		<guid isPermaLink="false">http://www.surfaces.co.il/?p=1238</guid>
		<description><![CDATA[Users of Ubuntu who want to use Spatialite for managing GIS layers are in luck. New updated packages have been released bringing to Ubuntu and derivatives all the new feature of spatialite 3.1.0. The latest spatialite includes the following improved capabilities: New functions such as ST_Expand, ST_Reverse, ST_Translate Updates to several other functions Uses the [...]]]></description>
				<content:encoded><![CDATA[<p>Users of Ubuntu who want to use Spatialite for managing GIS layers are in luck. New updated packages have been released bringing to Ubuntu and derivatives all the new feature of spatialite 3.1.0.<br />
<span id="more-1238"></span><br />
The latest spatialite includes the following improved capabilities:</p>
<ul>
<li>New functions such as ST_Expand, ST_Reverse, ST_Translate</li>
<li>Updates to several other functions</li>
<li>Uses the latest sqlite 3.7.13 with an improvement in rounding double precision numbers</li>
<li>Uses the recent geos-3.3.2</li>
<li>An easier format for using a SpatialIndex in a query</li>
</ul>
<p>To install the suite you will need the ubuntugis-unstable repository. If you haven&#8217;t yet added that repo to your software sources, follow the instructions on this <a title="OSGeo wiki page" href="http://trac.osgeo.org/ubuntugis/wiki/UbuntuGISRepository">OSGeo wiki page</a><br />
Then it&#8217;s just a matter of running:<br />
<code>sudo apt-get install --yes libspatialite spatialite-bin</code></p>
<p>This will give you the library (probably already installed if you have any GIS software at all on your system), and the CLI binary for working with spatialite data. If you&#8217;re a command line type, then you&#8217;ve got all you need to start building and querying a spatialite database. You also have the command line tools to import OSM data into a Spatialite database: spatialite_osm_raw, spatialite_osm_filter, etc. And the two utilites shp_doctor to repair shapefiles, and spatialite_tool to import and export data to/from a Spatialite database.</p>
<p>However, the GUI interface is another story. The ready built package is version 1.3 &#8211; <strong>very old</strong>. In fact, if you create a DB using the new CLI program, and add some data layers, it <em>will not open</em> in the ancient ver. 1.3 GUI program. I suggest to take a few minutes to download the sources and manually build your own spatialite_gui. Only a few standard steps in the terminal:</p>
<p>First you&#8217;ll need a bunch of development packages:<br />
<code>sudo apt-get install --yes libwxgtk2.8-dev libgeos-dev libgeos++-dev libgeotiff-dev libcairo2-dev libfreexl-dev libspatialite-dev</code></p>
<p>Now download two source packages, and unzip them in your Downloads directory. First the libgaiagraphics package:<br />
<code><br />
cd ~/Downloads<br />
wget http://www.gaia-gis.it/gaia-sins/libgaiagraphics-0.4b.tar.gz<br />
tar xzf libgaiagraphics-0.4b.tar.gz<br />
cd libgaiagraphics-0.4b<br />
./configure<br />
make<br />
sudo make install-strip<br />
sudo ldconfig<br />
cd ..</code></p>
<p>Here we download the tarball from the gaia-gis.it website, unzip, then run the usual configure, make and make install commands to compile and put everything in place.<br />
Next the GUI program itself:</p>
<p><code>wget http://www.gaia-gis.it/gaia-sins/spatialite_gui-1.5.0-stable.tar.gz<br />
tar xzf spatialite_gui-1.5.0-stable.tar.gz<br />
cd spatialite_gui-1.5.0-stable<br />
./configure<br />
make<br />
sudo make install-strip<br />
</code></p>
<p>You might want to add an item to the applications menu, and put the icon into place. While still in the spatialite_gui-1.5.0 directory:</p>
<p><code><br />
sudo cp gnome_resource/spatialite-gui.desktop /usr/share/applications/<br />
sudo cp gnome_resource/spatialite-gui.png /usr/share/pixmaps/</code></p>
<p>And off you go collecting and querying spatial data.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.surfaces.co.il/spatialite-on-ubuntu/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by-nc-sa/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Spatialite- Updating one table from another</title>
		<link>http://www.surfaces.co.il/spatialite-updating-one-table-from-another/</link>
		<comments>http://www.surfaces.co.il/spatialite-updating-one-table-from-another/#comments</comments>
		<pubDate>Mon, 14 May 2012 18:43:07 +0000</pubDate>
		<dc:creator>Micha Silver</dc:creator>
				<category><![CDATA[GIS]]></category>
		<category><![CDATA[Spatialite]]></category>

		<guid isPermaLink="false">http://www.surfaces.co.il/?p=1208</guid>
		<description><![CDATA[Users of SQL databases often get tripped up when trying to update values in one table from another table. The method involves a subquery in the UPDATE statement to extract the values from the other (source) table. We&#8217;ll review how it&#8217;s done, both with simple attribute values, and with an update based on a spatial [...]]]></description>
				<content:encoded><![CDATA[<p>Users of SQL databases often get tripped up when trying to update values in one table from another table. The method involves a subquery in the UPDATE statement to extract the values from the other (source) table. We&#8217;ll review how it&#8217;s done, both with simple attribute values, and with an update based on a spatial query.<br />
<span id="more-1208"></span><br />
In sqlite3 and spatialite the generic UPDATE statement which extracts values from another table looks like<br />
<code><br />
UPDATE target_table SET target_column=(SELECT source_column<br />
FROM source_table<br />
WHERE target_table.id=source_table.id );<br />
</code><br />
The tricky bit that sometimes gets people confused is the WHERE clause. In a simple SELECT statement you cannot put a &#8220;table.column&#8221; into the WHERE clause that doesn&#8217;t appear also in the FROM part. So a simple SELECT query would have to read:<br />
<code><br />
SELECT source_column<br />
FROM source_table AS s, target_table AS t<br />
WHERE s.id=t.id<br />
</code><br />
Both source and target tables must appear in the FROM portion.</p>
<p><span style="text-decoration: underline;"><strong>Simple UPDATE example</strong></span><br />
However, when updating the target table with a subquery you must NOT have the target table in the subquery. The WHERE clause in the subquery must refer to the table being updated <strong>outside of the subquery</strong>. Let&#8217;s look at an example. We have a table of store locations, and we receive an excel spreadsheet file with sales data for each store. The excel table has one row for each store with, and a &#8220;StoreNum&#8221; that matches the StoreID in our stores spatial layer. See the table list in the image below. We want to get the sales values into our spatial layer. We first add a column for the new data:<br />
<code><br />
ALTER TABLE Stores ADD COLUMN Sales double;<br />
</code><br />
Now we can use the support in spatialite for virtual excel sheets, and add the sales data as a virtual table. In Spatialite GUI there&#8217;s a VirtualXL button &#8211; <span style="color: #008000;">indicated in green</span> in the image &#8211; to add a sheet from an excel file. Once the sales data is available as a virtual table, we want to update the Stores layer with the values from this excel table. So:</p>
<p><a href="http://www.surfaces.co.il/wp-content/uploads/2012/05/SL_update.png"><img class="aligncenter size-full wp-image-1216" title="SL_update" src="http://www.surfaces.co.il/wp-content/uploads/2012/05/SL_update.png" alt="" width="700" /></a></p>
<p>Notice &#8211; <span style="color: #ff0000;">circled in red</span> &#8211; that the subquery refers to the Stores table being updated, and this table <strong>does not appear</strong> in the FROM clause. The FROM clause contains <strong>only</strong> the sales_summary table, aliased AS s.</p>
<p>&nbsp;</p>
<p><span style="text-decoration: underline;"><strong>UPDATE with Aggregation</strong></span><br />
On to the next example, we are given an excel spreadsheet with detailed sales data. Rather than a summary for each store, this table contains all the transactions for all the stores. So each store appears many times in the table. We must now aggregate the sales data for each store, and update the sales column in our Stores spatial layer with a sum of sales for each store. This is accomplished easily with the SQL SUM() function. We first use the VirtualXL support to add a virtual table &#8220;sales_details&#8221;, then:</p>
<div id="attachment_1212" class="wp-caption aligncenter" style="width: 710px"><a href="http://www.surfaces.co.il/wp-content/uploads/2012/05/SL_update2.png"><img class="size-full wp-image-1212" title="SL_update2" src="http://www.surfaces.co.il/wp-content/uploads/2012/05/SL_update2.png" alt="UPDATE Statement with SUM" width="700" /></a><p class="wp-caption-text">The UPDATE statement with SUM() to aggregate data for each store</p></div>
<p>Again, the Stores table, being updated, appears in the WHERE part of the subquery, but not in the FROM clause. The FROM portion has only the sales_details table. And in the SELECT subquery we use SUM(sales) to aggregate sales for each store. Since the WHERE clause matches <code>s.StoreNum</code> to <code>Stores.StoreID</code>, the SUM will be done for each store individually.</p>
<p><span style="text-decoration: underline;"><strong>UPDATE with a spatial query</strong></span><br />
For the last example, we do an UPDATE on two spatial tables, using a subquery with a spatial function. Our store locations are spread around many counties (a polygon layer). We need to summarize all sales <span style="text-decoration: underline;">for each county</span>. But wait a sec, the table being updated is in this case is the Counties, and the source data is from the Stores table. So the Stores table will now drop down to the subquery. We&#8217;ll again use the SUM() function, and our WHERE clause utilizes the ST_Within() function to find which stores are inside each county, and total up sales for those stores. In addition we deploy a SpatialIndex on each of the tables to speed up the query. See my <a title="previous post" href="http://www.surfaces.co.il/?p=1196">previous post</a> for an explanation of using spatial indices. Our spatial query now looks like:</p>
<div id="attachment_1224" class="wp-caption aligncenter" style="width: 710px"><a href="http://www.surfaces.co.il/wp-content/uploads/2012/05/SL_update3.png"><img class="size-full wp-image-1224" title="SL_update3" src="http://www.surfaces.co.il/wp-content/uploads/2012/05/SL_update3.png" alt="UPDATE with a spatial query" width="700" /></a><p class="wp-caption-text">An UPDATE with a spatial query, also using SpatialIndex</p></div>
<p>The WHERE clause of the spatial query &#8211; in green -contains both ST_Within function to find stores in each county, and the search for ROWID in the SpatialIndex limiting the search for stores which fall within each counties bounding box, thus saving lots of time. Again we see that the counties table, being updated, appears in the WHERE clause of the subquery, but not in the FROM part.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.surfaces.co.il/spatialite-updating-one-table-from-another/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by-nc-sa/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Spatialite: Speedup your query with spatial indexing</title>
		<link>http://www.surfaces.co.il/spatialite-speedup-your-query-with-spatial-indexing/</link>
		<comments>http://www.surfaces.co.il/spatialite-speedup-your-query-with-spatial-indexing/#comments</comments>
		<pubDate>Tue, 01 May 2012 09:34:05 +0000</pubDate>
		<dc:creator>Micha Silver</dc:creator>
				<category><![CDATA[GIS]]></category>
		<category><![CDATA[Spatialite]]></category>

		<guid isPermaLink="false">http://www.surfaces.co.il/?p=1196</guid>
		<description><![CDATA[Spatialite, like any good spatial data management system, can build a spatial index for your layers. Using this index in your spatial queries will dramatically shorten the runtime for that query. The latest version of Spatialite offers a nice compact format for using a spatial index. To demonstrate, I created a point layer of 20,000 [...]]]></description>
				<content:encoded><![CDATA[<p>Spatialite, like any good spatial data management system, can build a spatial index for your layers. Using this index in your spatial queries will dramatically shorten the runtime for that query. The latest version of Spatialite offers a nice compact format for using a spatial index. To demonstrate, I created a point layer of 20,000 theoretical store locations, with sales data for each store, and a polygon layer of over 280 &#8220;local councils&#8221;. My mission it to sum up the total sales in each local council. So I need to find which stores are located in each local council and aggregate sales for those stores.<br />
<span id="more-1196"></span><br />
We begin with two tables, councils (multipolygon) and stores (point) that look like this:<br />
<code><br />
spatialite> SELECT * FROM councils LIMIT 10;<br />
pk_uid      Name        Geometry<br />
----------  ----------  ----------<br />
1           Ronneby<br />
2           Sölvesbor<br />
3           Älvdalen<br />
....</p>
<p>spatialite> SELECT * FROM stores LIMIT 10;<br />
pk_uid      sales             Geometry<br />
----------  ----------------  ----------<br />
1           192617.423921806<br />
2           75489.1390022072<br />
3           163013.639152632<br />
....<br />
</code><br />
Let&#8217;s build the query. First, we are using both tables, so the FROM part of our SQL looks like:<br />
<code>FROM councils AS c, stores AS s</code><br />
and since we want to aggregate total sales for each council, we require a GROUP BY clause:<br />
<code>GROUP BY c.pk_uid</code><br />
What results do we want? The council name and total sales, so the SELECT part of our query will be:<br />
<code>SELECT c.Name AS Name, SUM(s.sales) AS "Total Sales"</code><br />
Finally, we formulate the criteria, stores contained in each council, like so:<br />
<code>WHERE ST_Contains(c.Geometry, s.Geometry)</code></p>
<p>Putting it all together, our &#8220;naive&#8221; query (no spatial index yet) goes:<br />
<code>SELECT c.Name AS Name, SUM(s.sales) AS "Total Sales"<br />
FROM councils AS c, stores AS s<br />
WHERE ST_Contains(c.Geometry, s.Geometry)<br />
GROUP BY c.pk_uid;<br />
</code><br />
Now this query will run successfully on our two tables as described, but you better go for lunch when you start the query. It might finish on a fast computer by the time you get back&#8230; The query loops thru all 20,000 store locations for each of the 280 councils. So that&#8217;s over 5,000,000 table scans, and checks for each point in each polygon. </p>
<p>So how do we utilize spatial indexing to speed things up? The R*Tree indexing and its implementation in Spatialite are covered in the <a href="http://www.gaia-gis.it/spatialite-3.0.0-BETA/spatialite-cookbook/html/rtree.html" title="Spatialite Cookbook">Spatialite Cookbook</a>. It&#8217;s important to note that Spatialite does NOT make use of a spatial index unless you <strong>explicitly</strong> incorporate it into the query statement. (BTW, this is unlike PostGIS which automatically uses a spatial index, if it&#8217;s available.)<br />
The options to implement a spatial index in a query structure were clearly explained in <a href="http://groups.google.com/group/spatialite-users/msg/86bdc09c31f91ee9?dmode=source" title="this post">this thread</a> from the spatialite maillist.</p>
<p>First we create a spatial index for both tables:<br />
<code>spatialite> SELECT CreateSpatialIndex('councils','Geometry');<br />
1<br />
spatialite> SELECT CreateSpatialIndex('stores','Geometry');<br />
1</code></p>
<p>Now the additional WHERE clause, in it&#8217;s new incarnation (requires spatialite >=3.0) looks like this for our query:<br />
<code>s.ROWID IN<br />
(SELECT ROWID FROM SpatialIndex WHERE f_table_name='stores' AND search_frame=c.Geometry)</code></p>
<p>&#8220;SpatialIndex&#8221; is a new virtual table, and using the search_frame component of that table we filter out the store locations in the bounding box (AKA Mbr=Minimum Bounding Rectangle). Searching for points in a rectangle is <strong>much</strong> faster than the full ST_Contains (or equivalent ST_Within) function. After this filtering, the ST_Contains() function runs on only a small subset of the 20,000 store locations.</p>
<p>So the spatial index enabled query will now look like:<br />
<code>SELECT c.Name AS Name, SUM(s.sales) AS "Total Sales"<br />
FROM councils AS c, stores AS s<br />
WHERE ST_Contains(c.Geometry, s.Geometry) AND<br />
    s.ROWID IN<br />
    (SELECT ROWID FROM SpatialIndex WHERE f_table_name='stores' AND search_frame=c.Geometry)<br />
GROUP BY c.pk_uid;<br />
</code><br />
On my machine, this query, aided by the spatial index, completed in less than 1.5 minutes. The first &#8220;naive&#8221; query took over 35 minutes. Pretty cool, no?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.surfaces.co.il/spatialite-speedup-your-query-with-spatial-indexing/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by-nc-sa/3.0/</creativeCommons:license>
	</item>
	</channel>
</rss>
