Some Bits: Nelson's log

27 posts about postgres

Google Cloud Postgres connections

I’m using Google Cloud’s Postgres implementation. I thought I had it all working except my AppEngine server couldn’t connect to it in production. For dev work I’d just authorized my home IP address and connected directly to it from my dev box. But that didn’t work in production.

Turns out there’s complex docs for connection to Google Cloud SQL. Here’s what I had to do when following those instructions. (This was made significantly more different by intermittent outages either at Google or in my network connection; lots of failures and timeouts.)

  1. Download cloud_sql_proxy to my dev box
  2. Get some application default credentials on my dev box
    gcloud auth application-default login
    This does some OAuth thing with my Google account. In retrospect I have no idea how I was able to gcloud deploy, etc before doing this.
  3. Authorize my home IP address to connect to the SQL instance via the cloud console.
  4. Run the gcloud_sql_proxy and have it listen on 127.0.0.1:6432 (port 5432 is busy with my own Postgres instance.)
    ./cloud_sql_proxy -instances=projectname:us-central1:dbhost=tcp:6432
    Note the instance connection name has three parts separated by colons. “gcloud sql instances list” does not show you names in this format, but the console does in the “Instance details” page for that specific SQL server.
  5. Test I can connect to the database via local proxy
    psql postgresql://postgres:password@127.0.0.1:6432/postgres
    The proxy will log a line about the connection.
  6. Add the beta_settings / cloud_sql_instance stuff to my app.yaml. I have no idea what this does or if it’s necessary, but the docs said I should.
  7. In my dev environment, configure my code to connect to its database via 127.0.0.1:6432, so it uses the proxy. It’s not clear the proxy is necessary. I can connect directly to the database machine via IP address. I guess it’s nice in that the proxy is configured just with the instance connection string, not an IP address.
  8. In prod configure my code to connect to
    postgresql://postgres:{password}@/{dbName}?host=/cloudsql/projectname:us-central1:dbhost
    I have no idea what this ?host= argument does or why it works. Is this a standard thing or did Google fiddle with its Postgres drivers somehow?

That’s more or less the process described in Google’s docs, but it took me an hour of trial and error to make it work.

Update: I asked Stack Overflow about how cloud SQL connections worked and got a very quick answer from a Google Cloud engineer named Vadim. “It’s a UNIX socket backed by Cloud SQL Proxy”.

In detail, /cloudsql/projectname:us-central1:dbhost is a Unix domain socket, not a TCP socket. There’s an actual file (or directory?) named /cloudsql/projectname:us-central1:dbhost in the Unix machine’s filesystem. The ability to connect to Unix domain sockets with a special host= parameter is implemented in libpq, the Postgres connection library. The Cloud SQL Proxy code talks about how it can proxy from a Unix domain socket.

It’s a nice optimization; it’s silly to use a TCP/IP stack for passing data between two processes on the same computer. I assume Linux has a highly optimized localhost driver, even so Unix domain sockets should be better. This discussion suggests 1.5-2x the throughput.

GeoAlchemy and SQLAlchemy thoughts

I’m doing a new geo-project, a GPS tracker sort of thing. My database is very simple, just a Users table and a Locations table holding points. But I figured I’d front-load the work and use SQLAlchemy and Alembic and PostGIS and everything right now, not pay the pain of migrating later when I realize I need the fancier stuff.

Only SQLAlchemy doesn’t support PostGIS. GeoAlchemy2 does though. After an hour with it I can’t decide if it’s good or bad. It seems very simple.

In GeoAlchemy2 all geodata is represented in Python by just a few types; Geometry, Geography, Raster. You can’t do much with those things other than get the WKB or WKT for them. They’re not Points or Polygons or something, there’s no Python code for working with the shapes. You can pass them back to PostGIS though, to call functions like ST_Area to have PostGIS do a calculation. Requires a database round trip though. Alternately you can also convert them to Shapely shapes, use that excellent GIS library to do work in Python.

I guess that’s a reasonable compromise; GeoAlchemy2 is really just bridging to SQL, they’re not going to implement their own GEOS equivalent. It also has spatial functions declared in a SQLAlchemy-friendly way you so you can use SQLAlchemy syntax to do your work. That’s kinda neat.

Still I’m looking at a lot of third party Python code: SQLAlchemy, Shapely, GeoAlchemy, Alembic. All to manage a database with two tables and nothing more complex than a list of points. I may blow it all off and go to raw SQL. OTOH I may end up regretting that choice in a few months if I want to do more complex things.

 

Moving forward with lolslackbot and Django

I’m very encouraged with how my little Django experiment has worked out. I’m ready to start using it with lolslackbot. A big breakthrough was realizing that I can start using Django as soon as I trust it not to corrupt my database. Keep the existing Python cron job in old code, not using Django, and then have a separate webapp that also uses the same database. The cron job and the webapp will be reading the same tables but in general not writing the same tables. It seems like a good transition plan.

Only now I really have to face the sqlite question. I’m confident that ultimately I need to be using PostgreSQL. I’m envisioning thousands of web users updating the database; there’s no way that works with sqlite’s database-level locking. Even with low traffic the cron job and the webapp will be stepping on each other. I need to switch. But when?

Do I switch databases first, porting my cron job code over to a Postgres-backed system? That seems really painful and not much fun. Lots of backend work with no visible features.

Or do I use Django first, having it talk to the sqlite database? The lock contention won’t be a real problem if I’m the only webapp user. It lets me build fun / useful features sooner. And it gives me some more experience with data modelling. I’m pretty sure I’m going to want to refactor the schema along with the Postgres update, it’d be better to do that after doing some of the webapp work. The risk with Django-first is I do a lot of sqlite-specific work that is ultimately wasted. But Django’s ORM insulates you from the underlying database pretty well, so maybe that doesn’t matter?

Also curious how the Django ORM is going to work for me. I use a couple of non-standard SQL things now. Mostly “insert or replace”, which is sqlite’s upsert-like extension. Does the ORM expose those? Also very curious how testing will work. sqlite is so simple when managing test environments. But I know the Django folks have thought this through.

sqlite3 vs postgres: uneasy feeling

I continue to write my LoL Slack bot with sqlite3. I can live with the primary drawback of sqlite3, which is that writes require a database level lock (ie: no table or row locking). In normal use I should only ever have one writer to the database anyway. But I still have a nagging feeling I should use “a real database”. Ie: Postgres

The nervousness is I’m writing more complex code that’s wedded to sqlite. I’m using sqlite’s upsert equivalent, for which there is no standard syntax. I’m also using sqlite’s Python convenience feature of not using cursor objects. And just now I’m starting to pay attention to Python’s weird transactional semantics, which I suspect might be different in Postgres. In short my code has been dating sqlite for awhile but now things are getting serious and I’m getting commitment anxiety. Also Postgres has some alluring features I could use, like JSON and array types.

The underlying question is whether Postgres is really “better” for my kind of application. I suspect not, and part of why I stick with sqlite is to test that assumption, but the cost of being wrong is getting higher. The flip side is managing a Postgres daemon is still a PITA. Particularly on Ubuntu where upgrading is scary.

PostGIS: intersections, multiple SRIDs

Someone asked me to give them a map of all the rivers in the state of Ohio. Sounded like a fun PostGIS exercise for me. Unfortunately I’ve made it more complex because my river database is in SRID 900913 by default, so intersecting that with the Natural Earth admin1 data in a different SRID is not as simple as a one line query. I could just transform Natural Earth on import but ogr2ogr pretends to not know 900913 and that seemed bogus anyway. Some notes from my goofing around:

-- state boundary data is in EPSG:4326
# select ST_SRID(wkb_geometry) from admin1 limit 1;
4326

-- Coerce the test point to the SRID that the state boundary data is in
# select name from admin1 
  where ST_Intersects(wkb_geometry, 
                      ST_Transform(ST_GeomFromEWKT('SRID=4269;POINT(-82.98 39.98)'), 4326));
Ohio

-- try querying with a point inside Ohio but with mismatching SRIDs
# select name from admin1
  where ST_Intersects(wkb_geometry,
                      ST_GeomFromEWKT('SRID=4269;POINT(-82.98 39.98)'));
ERROR:  Operation on mixed SRID geometries

-- Coerce the test point to 900913, which should not work.
-- Bafflingly does not give an error for mixed SRIDs, just returns 0 rows
# select name from admin1
  where ST_Intersects(wkb_geometry,
                      ST_Transform(ST_GeomFromEWKT('SRID=4269;POINT(-82.98 39.98)'), 900913));
(0 rows)

-- Coerce the state boundary geometry to the test point's SRID
# select name from admin1 
  where ST_Intersects(ST_Transform(wkb_geometry, 4269),
                      ST_GeomFromEWKT('SRID=4269;POINT(-82.98 39.98)'));
Ohio

postgres: setting up permissions for a user

I wanted to give a CGI script access to one specific postgres database, both read and write. This is remarkably complicated. I ended up creating a password protected role named “oarunone” and gave it access to a database named “oarunone” (yes, confusing) and one table named “queue”. Something like:

  • create role oarunone with password ‘secret’;
  • grant all privileges on database oarunone to oarunone
  • grant all privileges on table queue to oarunone

But that’s not good enough. Ubuntu’s default postgres only identifies users via the Unix UID. So you also have to add a line like this to pg_hba.conf. and it has to occur before the catch-all “all” rule.

  • local oarunone oarunone md5

That says allow the role “oarunone” to authenticate with a password (MD5ed), but only from a local Unix domain socket and only to the database “oarunone”.

inserting lots of data into a remote Postgres efficiently

Update 2017: psycopg2 now has fast execution helpers. Not sure why they didn’t just improve executemany.

I’m using a Postgres server in AWS in the us-east zone. My database client is running in California, so it’s about 150ms away. I do not expect this to be fast. However I don’t expect it to be super-slow either. Inserting 700 rows in a single transaction was taking 60 seconds. That’s absurd! (Rows are ~100 bytes each, this is not a lot of data).

Thanks to StackExchange I found a solution. Here’s some untested code that illustrates the idea:

# Clearly slow to insert one row at a time
for row in myData:
    cur.execute('insert into data values (%s,%s,%s)', row)

# Should be much faster, but isn't
cur.executemany('insert into data values (%s,%s,%s)', myData)

# This hack is much faster
dataText = ','.join(cur.mogrify('(%s,%s,%s)', row) for row in myData)
cur.execute('insert into data values ' + dataText)

That funky last idiom basically expands all of myData into one giant SQL string with multiple values. For my use case, that 60 second operation went down to 1.5 seconds. This hack works, but you’re going to bump into a query size limit at some point.

Note that mogrify() isn’t doing anything clever, it’s just doing safe expansion of SQL query strings to avoid Little Bobby Tables. (There’s a Unicode error lurking here; I switched to Python2 just to make this work.) Also note that transactions don’t seem to be to blame here. psycopg2 by default runs a transaction for every connection; nothing commits until you call commit().

I think what’s going on is that psycopg2 doesn’t optimize the implementation of executemany(). Internally it’s just doing something like a loop calling execute() for each row. I don’t have proof of that, but my research turned up other people saying that was the problem. (See here)

(As an aside, what is it with database adapters for various languages that make them so universally bad? psycopg2 isn’t terrible, but it’s hardly joyful Python software. At least it’s better than the mess we had with mysql for so many years. Back in the Java days we used to have a terrible time trying to talk to MySQL as well.)

SRID 900914

Here’s a new one on me; I used ogr2ogr to import the Australian river data into PostGIS and it ended up being labeled with SRID 900914. WTF? According to this discussion that’s what ogr2ogr does if the SRID isn’t already defined in the PostGIS tables. It adds a new entry with the CRS info gleaned from the source file. And since the largest defined SRID in most PostGIS installations is 900913 (the bogus Google entry) why, the next one created will be 900914.

The data is actually in EPSG:4283 which PostGIS already knows about.

While I’m here, this Stack Exchange answer has some useful ogr2ogr flags for big imports. -progress and --config PG_USE_COPY YES. According to the docs COPY may now be the default, but I’m not sure it is. Adding it cut my running time to 20% of without.

Vector rivers update, NHDPlus / PostGIS problem

Boy, code rots. I tried to re-generate my vector rivers map from data. The project’s well documented, it should be easy, right! Ha.

My imports failed like this:

$ shp2pgsql -a -D -t 2d -s 4269 -W LATIN1 ./NHD/NHDPlusGB/NHDPlus16/NHDSnapshot/Hydrography/NHDFlowline.shp
Shapefile type: ArcZ
Postgis type: MULTILINESTRING[2]
Error in fread() reading object of size 1112 at offset 41917076 from .shp file
Error reading shape object 43130

I downloaded a new datafile from the source and now it works. The downloaded 7z archive is the same, I wonder if there was a problem when I extracted the data and an older version of shp2pgsql didn’t catch it? It’s not just that one file though, NHDPlusMS/NHDPlus05 is bugging out too.

Update yeah I must have had a problem extracting some of the files. Surprised my import script didn’t notice before. I wonder if earlier versions of shp2pgsql weren’t as meticulous about error reporting? Or maybe I had a clean extract last time I did a full import. The 7z archiver I have to use doesn’t handle being interrupted very well, I suspect it leaves behind incomplete files.

Postgres bug report

Ugh, I was grooving along with a solution for my vector merging when suddenly a ordinary-working query threw the most bizarre error:

ERROR: could not open file “base/16384/24738_fsm”: Invalid argument

Googling around was useless, but I managed to get some help on IRC from anders and RhodiumToad on #postgres. Long story short, our guess is a call to free() is following a call to open(), and the free() is clobbering errno before Postgres checks on the errno from open(). Good ol’ C error reporting, have to love it :-(

It’s submitted as Postgres bug #8167. Lots of details at https://gist.github.com/NelsonMinar/5588719

This is the first time I’ve used dtruss in anger. Worked nicely. In my psql repl I did “select pg_backend_pid();” to find the PID, then did “dtruss -p > /tmp/out 2>&1” to capture the output.

PostGIS upgrades in Debian / Ubuntu

Repeat after me: I will dump my databases before upgrading PostgreSQL or PostGIS. I will dump my databases before upgrading PostgreSQL or PostGIS. I will dump my databases before upgrading PostgreSQL or PostGIS.

I got fed up with the 2 year old versions of GIS software in Ubuntu 12.04 so I upgraded to versions from the awesome Ubuntu GIS PPAs. However after upgrading PostGIS any spatial query gave me the error

ERROR:  could not access file “$libdir/postgis-2.1”: No such file or directory

No idea why that says “2.1” when I installed PostGIS 2.0.1 (2.0.1-2~precise3), but there it is. Googling around I realized this is a symptom of not reinstalling the PostGIS functions in the database. There’s a variety of confusing database upgrade options, and the Debian packages are very clear about not injecting any SQL for you “for safety”.

However, there is a better way! Starting with Postgres 9.1 and PostGIS 2.0, PostGIS can be installed as a simple database extension. No more futzing with template databases on creation or importing lots of .sql files in a new database. All you need to do to spatialize a new database is

create extension postgis
create extension postgis_topology

I’m not sure you can use these commands to rescue an old database that didn’t survive an upgrade, but it works great with new databases. IIRC there’s even an upgrade path for extensions. I dropped my old template_postgis2 just so I never get confused again.

Vector tile river maps

Some notes for a quick project I did with Mike Migurski’s help, making a map of California rivers using vector tiles. The river data is from NHDPlus, about 180 megs of shapefile, imported into PostGIS. It’s served as manageably small GeoJSON tiles via a TileStache VecTiles provider which slices up the data like raster map tiles. Rendered for now in Polymaps. Works well!

TileStache is already smart about simplifying the geometries it returns to roughly pixel precision, depending on tile zoom level. It’s really pretty great. But I also want to serve fewer rivers at larger scales, only show the important rivers. Need a classifier. I don’t think the propery I need is in NHDFlowlines but may be in NHDPlusAttributes, more thoughts in this GIS tutorial. Seth F advises “PlusFlowlineVAA has value-added attributes that can be joined on ComId. streamorder is the column you’re looking for. It’s the Strahler number (http://en.wikipedia.org/wiki/Strahler_number) for a given section of river.”

I ran into some problems with queries from GDAL not working with PostGIS 2.0. Used to be you could just call functions like GetSRID() etc, now you have to do ST_GetSRID(). The old GDAL 1.7 on my Debian box doesn’t know that yet and the Vector provider in TileStache relies on it, so it doesn’t work. VecTiles generates its own queries and Mike was kind enough to patch his code to use the ST_ names.

The TileStache VecTiles code only works with a spherical mercator projection, so I had to do this in PostGIS to add a reprojected column:

select AddGeometryColumn('nhdflowline', 
  'sphgeometry', 900913, 'MULTILINESTRING', 2)

update nhdflowline
set sphgeometry = 
  ST_Transform(ST_Force_2D(geom), 900913);

Here’s the TileStache config for serving vector tiles from PostGIS:

    "riverst": {
      "provider": {
      "class": "TileStache.Goodies.VecTiles:Provider",
        "kwargs": {
              "dbinfo": {
                "host": "localhost",
                "user": "nelson",
                "password": "OMGSECRET",
                "database": "nhd"
              },
              "queries": [
                "select sphgeometry as geometry from nhdflowline"
              ],
              "clip": true
        }}}}

Some screenshots; rivers on top of the ESRI relief layer, also the “first light” with a hysterical bug where the river paths are filled, not stroked.

Screen Shot 2013-04-12 at 2.06.57 PM

Screen Shot 2013-04-12 at 2.11.40 PM

importing an ESRI shapefile to PostGIS

I don’t work with shapefiles and PostGIS enough to remember how to import a shapefile into a table. I want to import the NHDPlus dataset for rivers. There’s lots of ways to do this, here’s what’s working now in a plodding, step by step way.

  1. createdb -T template_postgis2 nhd
  2. shp2pgsql -W LATIN1 NHDFlowline.shp >| /tmp/o
  3. psql nhd < /tmp/o
  4. echo ‘CREATE INDEX “nhdflowline_geom_gist” ON “nhdflowline” USING GIST (“geom”);’ | psql nhd

This can probably be done on one line with shp2pgsql -I foo.shp | psql nhd

Getting fancier on the import (and setting the SRID to 4269):

  1. shp2pgsql -s 4269 -I -D -W LATIN1 NHDFlowline.shp | psql nhd

Related: shp2pgsql won’t look at the .prj file to figure out the projection. Figuring out a projection is still way too hard and Prj2EPSG.org failed me. This StackOverflow question and this one have a neat trick; use osgeo.osr.SpatialReference().AutoIdentifyEPSG() to guess the projection.

Update: Seth F has a nice shell script for importing a lot of useful NHD data and creating important indices.

A friendlier PostGIS

Nathaniel Kelso has an awesome post about how to make PostGIS more friendly for users. I mostly agree with his points, it’s a friendly todo list, although there’s always the question of who has time to do the work. Some specific thoughts (I can’t figure out how to comment on his blog):

  • 1 Installation: I’d love updated Debian/Ubuntu packages. But it’s a lot of packaging work, I could see why PostGIS would rather defer to some third party to do the packaging. But someone’s got to do it! Upgrades are particularly hard to get right; Postgres and PostGIS mostly leave it up to users to figure out how to do upgrades right now.
  • 2.1 imports: is ogr2ogr any better than shp2pgsql in general?
  • 2.1g importing shapefiles: yes, absolutely, automatic inference of SRID from PRJ files. Is that a solved technical problem though, or is it arbitrarily difficult?

The #1 thing I want to make PostGIS easier is some better graphical query tool / front end to explore geometry queries. I’m used to being able to experiment with SQL in something like pgAdmin to build up my complex queries, but you can’t do that meaningfully with spatial data. I’d love a geo-aware SQL tool, one that draws geometries and stuff. I use QGIS like this a little bit but the UI for refining queries is awful. TileMill is a little better for query tinkering, but still awkward. Wouldn’t it be awesome if Induction were geo-aware, maybe using GeoJSON as a lingua franca?

Ubuntu upgrade to PostGIS 2 with data preservation

I thought it’d be “fun” to upgrade from PostGIS 1.5 to 2.x on my Ubuntu box. I forgot how byzantine Postgres extensions are and the fundamental rule of database upgrades; you have to take a dump with the old version first. I didn’t take careful notes, but here’s what sort of worked for me.

  • Read the PostGIS instructions on upgrading, in particular the notes about doing a “hard upgrade”. Create a dump before changing PostGIS 1.5.
  • Follow these instructions on installing PostGIS 2.x from sharpie’s PPA. You really need postgis-nightly; he has a PPA called postgis-stable too but I don’t think it’s fully populated.
  • Restore the dump with pg_restore, to a new database name. Pay close attention to stderr.
  • I got an error about ST_* functions being “not unique”. This report suggested that the restore brought over some 1.5 versions of functions and the solution is to run postgis_upgrade_20_minor.sql. Running that threw errors because I had a view depending on some of the functions; I ended up just dropping the view.

Honestly this is all pretty messy and I don’t have full confidence that PostGIS 2 is really installed properly. There’s too many spooky places PostGIS stuff gets loaded into the database. But all my old code still seems to work and gives the same results (at least, visually) so maybe it worked out.

I tried playing with ST_ConcaveHull that I wanted. It’s very, very slow on a GPS track with 50 points in it. Like 1.5 seconds to do a single track to a target percent of 0.5. I guess it’s doing some optimization algorithm? target percent of 0 doesn’t even work, throws a TopologyException. This function may not be what I need to do my calculation.

select
ogc_fid,
ST_NPoints(ST_Simplify(wkb_geometry, 0.0002)),
ST_ConcaveHull(ST_Simplify(wkb_geometry, 0.0002), 0.5) as wkb_geometry,
name
from tracks
limit 1;

Playing with OSM data

I’m playing with OpenStreetMap data in PostGIS, drawing maps in QGIS. No serious cartography, mind you, just trying to get a feel for the data. I’m starting with Mike Migurski’s metro extracts, the .osm.bz2 file for San Francisco

Import that into PostGIS, which gives this schema which describes these map features.

osm2pgsql -d walks --style /usr/share/osm2pgsql/default.style san-francisco.osm.bz2

For the SF metro, there’s 8000 roads, 40,000 polygons, 31,000 points, and 62,000 lines. You can import all these tables directly from pgsql into QGIS and render them for a basic view. The lines contain the street grid; roads contains just the larger highways, etc.

QGIS makes it easy to explore the tables. When you add a new PostGIS layer and choose a table, you can then choose specific fields and sample their values. Exploring around you can find that “leisure=park” is an interesting subset of polygons, for instance.

Roads are terribly complicated, so to simplify I tried using Migurski’s High Road. It creates custom views with names like “planet_osm_line_z14” where just roads relevant at that zoom level are present. Also some fancy stuff to make drawing casings vs. road surfaces easier. z15plus is the big set of all roads (170,000); _big is 24000 roads and _small is the other 144,000 lines (footpaths and such). Unfortunately QGIS can’t use the High Road views; details in this issue I filed.

I was able to use the High Road code as a guide for categorizing road by size, though. The “highway” field is the key one. It’s a messy schema, there’s about 7 synonyms for “street”.

Here’s a map of the walks I’ve taken in my neighborhood, with streets and parks.

 

Scraping GPX files out of RunKeeper into Postgres and QGIS

I’ve been using RunKeeper to track my walking. I wanted to work with the 40+ GPS tracks they’ve logged for me and didn’t want to download them one at a time. Some quick notes on how to scrape them all out.

  1. Log into the website in your browser and go to your Activities page. It has a URL like http://runkeeper.com/user/USERNAME/activity/70000177
  2. Save that big HTML page to a file named activities.html
  3. Capture the IDs of all your activities from that page with a regexp like this:
    printMatches  ‘link=”/user/USERNAME/activity/([0-9]+)’< activities.html > ids
  4. You can now download a GPX for that ID with a URL like http://runkeeper.com/download/activity?activityId=70000177&downloadType=gpx. However, the download requires a URL, at least if your activities are private.
  5. Look in your browser for your JSESSIONID cookie. That’ll stand in for a login.
  6. Use wget with that cookie. Here’s my little shell script to get them all
cat ids | while read id; do
  wget --no-cookies \
       --header 'Cookie: JSESSIONID=C~2BF2D2156284732CE8D8BDA900000000' \
       -O $id.gpx \
       "http://runkeeper.com/download/activity?activityId="$id"&downloadType=gpx";
done

Set up a PostGIS database with all the data

  1. createdb walks
  2. psql -d walks -f postgis.sql
  3. psql -d walks -f spatial_ref_sys.sql
  4. psql -d walks -f postgis_comments.sql
  5. for f in *gpx; do echo $f; ogr2ogr -append -f “PostgreSQL” PG:dbname=walks $f; done

ogr2ogr will create a fancy schema for you that contains every field ever seen in a GPX file. For RunKeeper data, the salient things are:

  • tracks.wkb_geometry: one row per track, multiline string
  • track_points: one row per point with a point, elevation, timestamp, etc.

QGIS did a fine job rendering the tracks table for me. I also pulled in a raster OSM map for a base layer from http://wms.latlon.org/.

Here’s a quicky query to get the length of a track in miles. Need to understand the ST_Transform better, also join to something else to get proper data about each imported track.

select name, ST_Length(ST_Transform(wkb_geometry, 2163)) /1609 as miles from tracks order by name;

A quicky view to simplify the tracks a bit, plus a query that compares the length of the original and simplified views.

create or replace view simple as
select
 ogc_fid,
 ST_Simplify(wkb_geometry,0.00005) as track,
 name
from tracks;

select
  tracks.name,
  ST_Length(ST_Transform(simple.track, 2163)) /1609 as miles,
  ST_Length(ST_Transform(tracks.wkb_geometry, 2163)) /1609 as miles
from simple inner join tracks
on simple.name = tracks.name order by name;

Trying to recover a Postgres database

When my old server died I had some data in Postgres. I don’t think it was anything important but I can’t really be sure, I’d like to recover it. All I have are the binary files Postgres stores its data in. Turns out recovering from those sucks. Lesson learned: if you care about recovering your data, back it up into a SQL dump.

Postgres makes no effort to make its binary files compatible between versions. A 9.0 database can’t be used in a 9.1 install; when you upgrade, you have to run a funky recovery tool which dumps the 9.0 db and imports it to 9.1. A 9.0 database on a 32 bit machine can’t be imported into 9.0 built for a 64 bit machine, either. I’ve also seen problems in the past trying to work with data from a PostGIS database in a non-PostGIS install. I’m sure this format flexibility makes it easier to build a fast database engine, but it sure makes data recovery difficult.

I tried building 9.0 sources on my amd64 box and running it. That was easy enough, although setting up users and permissions is a bit finicky when installing by hand. But the DB was generated on an i386 box (32 bit) so it won’t load. At least it failed quickly, “FATAL:  incorrect checksum in control file”. Then I started looking in to cross-compiling and realized the last thing I want is to set up a whole separate build toolchain. (A quick try with the linux32 command didn’t work.)

So screw it, what was I really storing in Postgres anyway? Not much, I did a quick test to see:

find . -type f -name \*py | xargs egrep -i ‘psycopg2|postgres’

Only one Python program I wrote even imports the Postgres driver. And I can recover that data from original sources. I think I have some geodata I imported with shp2pgsql, too, but I can redo all that. So I give up on recovering data.

Cross-compiling

Maybe I gave up too fast. Building a 32 bit version of Postgres on Ubuntu was as easy as

./configure CC=’gcc -m32′ --prefix=/tmp/pgsql90i386  --without-readline --without-libz

(there’s probably 32 bit versions of readline and libz, but I don’t really need them). Building a server this way, my amd64 machine can load the database binaries generated on the i386 machine. I had no idea the 64 bit Linux distributions could build 32 bit code so easily.

And it works! “psql -l” to find what databases were there, then “pg_dump database” to get the data out, then “psql” to get the data back into my 9.1 database. Yay!

Backups

Lesson learned, I’m now doing some simple nightly SQL backups of my databases. There are fancy ways to do this, I’m going very simple:

DEST=/mnt/sdb1/BACKUPS/postgres

set -eu
renice 10 $$ > /dev/null

pg_dumpall --lock-wait-timeout=$[5*60*1000] | gzip -9 >| $DEST/dumpall-sql.gz

 

Postgres 9.0 to 9.1 upgrade with Mac / Homebrew

I just had a terrible time trying to upgrade PostgreSQL 9.0 to 9.1. I finally gave up and am still running the old one.

pg_upgrade is the recommended upgrade path. It’s pretty ugly, and among other things requires you have the old server binaries around. But it looks like it’d do the job. I had a few minor problems, like I ran “--check” and the check failed but left something around that made Postgres think a server was running. (Fortunately pg_ctl start just ignored that and started a server anyway, then pg_ctl stop fixed it.)

Then I hit a bigger problem: PostGIS I’ve got that installed in my 9.0. I *think* it’s installed in 9.1, too, but I can’t be sure with Homebrew. In any event pg_upgrade doesn’t think it’s there so I’m SOL for now.

An alternative is to do pg_dump on the old server, then pg_restore on the new. I suspect that’s what pg_upgrade does behind the scenes anyway. And I still have to resolve my PostGIS problem.

Quick PostgreSQL tuning notes

My little database became a big database, 100 gigs, and I never bothered to tune PostgreSQL. The defaults look tuned for a machine with about 1 gig of RAM total. I’ve got 8 gigs. Here’s a quick stab at some tuning:

shared_buffers = 256MB
work_mem = 16MB
maintenance_work_mem = 256MB
wal_buffers = 16MB
checkpoint_segments = 10
effective_cache_size = 1024MB

I’m just guessing, not testing. Got some hints from

Those defaults blow out MacOS’ default shared memory limits. I bumped them up with notes from here and here
$ sudo sysctl -w kern.sysv.shmmax=536870912
$ sudo sysctl -w kern.sysv.shmall=131072

Contours

I wanted to play with contours for some mapping. Ie: a shapefile of where the 8000′ or higher terrain is across the US. Turns out to be pretty simple to generate something basically working from SRTM data. The gdal_contour program does the work. The OpenStreetMap folks have some nice notes on how to use it with SRTM data. The details, however, are much harder.

Basics

$ gdal_contour -a elevation N40W108.hgt N40W108.shp -i 304.8 -snodata 32767

That generates 1000′ contours, very fast, maybe 150ms with the data in cache. The output file size varies wildly: for that hilly part of Colorado it’s 1 meg. Generating 100′ contours instead takes about 6x as long and results in 10x the resulting file size. (gdal_contour is dumb about files: if the output file already exists, the error you get is “ERROR 1: N40W108.shp is not a directory”)

North America has 2415 data files so even on a slow computer 1000′ contours can be generated in about an hour. Once you have the contour shapefiles, you can import them into PostGIS. It goes pretty easily, but is slower than generating the shape files themselves. Should probably create an index, too.

$ shp2pgsql -p N20W076.hgt.shp srtm_contours | psql contours
$ shp2pgsql -a N20W076.hgt.shp srtm_contours | psql contours
$ shp2pgsql -a N20W075.hgt.shp srtm_contours | psql contours
$ shp2pgsql -a N19W075.hgt.shp srtm_contours | psql contours
$ shp2pgsql -a N19W076.hgt.shp srtm_contours | psql contours

The import of all of North America took a couple of hours and the table is 14 gigs on disk. 32,865,353 rows. Some quick efforts to make maps with TileMill suggest it’s too much data. Need indexing on elevation and the geometry, also would really like to simplify those contour lines.

Thinking in feet

The elevations are in meters, stored as a double, but I think in feet and it’d be nice to simplify. So let’s convert them to integer feet and index on elevation.

alter table srtm_contours add column elevation_feet integer;
update srtm_contours set elevation_feet = round(3.28084*elevation);

This is very slow, over an hour. PostgreSQL is completely copying the whole table to make rows with the new column. Maybe it would have been better to update the value in place.

Indexing the data

Let’s create a basic spatial index!

create index idx_srtm_contours_the_geom on srtm_contours using gist(the_geom);  -- about 30 minutes, 2 gigs
vacuum analyze srtm_contours; -- 30+ minutes, at least before database tuning

Subsetting for TileMill

Even with the index the contours are just way, way too much for TileMill. I’m not sure how smart TileMill is about querying only data it needs. A different solution is to create a special table with just rows for the 8000′ elevation level (the one we care about). It also seems to help to simplify the contours some.

create table contour_8000_simple (
  gid integer,
  id integer,
  the_geom geometry,
  constraint contour_8000_pk primary key (gid)
 );

insert into contour_8000_simple
select gid, id, ST_SimplifyPreserveTopology(the_geom, 0.001) from srtm_contours where elevation_feet = 8000;

(SQL is approximate, not cut-and-paste ready). The 0.001 parameter means “simplify to 0.001 degree”, in this case.

Next Steps

After all the selecting and simplifying the resulting data works OK in TileMill. It renders at an acceptable speed, at least, and if you draw big fat lines you can schmudge over the awkward too-detailed contour. But this work has gotten pretty hacky. I really need polygons, not linestrings, so I can fill the 8000′+ range. But because the contours were calculated on 1degree square tiles in the first place, closing the polygons takes a bit of work. Also I haven’t dealt properly with NODATA regions. Need to sit down and re-do it with more time.

Here’s what it looks like, for a region of mountains SE of Salt Lake City, UT.

Special use airspace for mapping

I’m playing around with drawing airspace. The FADDS database has nice ESRI shapefiles for B, C, D, and E. Easy to use them directly with QuantumGIS or TileMill, or import them into PostGIS, or whatever. But they don’t publish special use airspace in shapefile format.

One option is to download the SUA data from the SoaringWeb community in OpenAir format, then convert and import it. It seems to work.

$ ogr2ogr -f "ESRI Shapefile" allusa allusa.v11.08-25.1.txt
$ shp2pgsql -s 4326 airspaces.shp | psql faadata
$ echo '\d airspaces' | psql faadata

 gid      | integer               |
 class    | character varying(80) |
 name     | character varying(80) |
 floor    | character varying(80) |
 ceiling  | character varying(80) |
 the_geom | geometry              |

$ echo 'select class, count(*) from airspaces group by class' | psql faadata

 class | count
-------+-------
 Q     |   456
 B     |   341
 P     |    12
 C     |   321
 R     |   417
 D     |   550

Classes.. B, C, and D are Bravo, Charlie, and Delta. P is prohibited, R is restricted, Q is “danger” (MOAs and Alert areas, I think). Name is free text. Floor and ceiling are also free text, things like “SFC”, “12500 MSL”, “300 AGL”, and “FL 180”.

FADDS does provide the special use airspace geometry in a couple of formats. There’s SUA.txt (10 megs), an old text format that ogr2ogr doesn’t seem to support. (The “SUA” driver is something else). There’s also the new SAA AIXM files. They are in FADDS and ogr2ogr has some support for them, but a quick test made it seem pretty inconvenient to use the data. (Update: I wrote Lynn, who makes the Soaring Web files, and she says she wrote her own complex code to handle SUA.txt)

Postgres professionalism

I’m an old MySQL guy, it’s the only relational database I’ve used a lot. So it’s been fun to learn about Postgres. It’s like a database for grownups! Constraints! Views! Transactions!

MySQL has gotten better over the years, particularly with InnoDB. But fundamentally it was designed as a fast and loose database and it shows. Does it still coerce any string to an integer on insert rather than throwing errors? I can’t tell you how many 0s corrupted my database because someone inserted “apple” into an integer column, or even better null (when the column was marked not null). Also the MySQL driver for Python has always been pretty cryptic and poorly documented. It got the job done, but it didn’t lend a lot of confidence.

The psycopg2 docs are terrific, really well thought out Python driver. I love that it supports asynchronous queries, including with various coroutine libraries. The way you can extend the cursor and connection classes is quite spiffy, too. (DictCursors and named tuples! Logging cursors!) And lots of nice caveats about using the library properly, including what resources are held by cursors and connections and the like. Docs written by someone who’s really used the library in production.

I’m told MySQL is still faster than Postgres for big data. I’ve also heard Postgres replication is error prone. Nothing’s perfect, I guess. Looking forward to finding out. Of course my #1 reason to use Postgres is PostGIS: MySQL really can’t touch Postgres for geodata, it’s not even an option.

 

Comparing Mongo and Postgres for wind calculation

I’m playing around with my weather data, CSV files containing things like “KSQL 1136073600 270 10”. (Station name, timestamp, wind direction, wind speed). Each row is 10 bytes of honest data and I have oh, 300 million rows.

I would like a sophisticated query language for doing aggregate stats, like “show me a histogram of directions for winds > 5kts on Tuesday mornings”. I have been hacking reports up by hand in Python by loading CSV files into lists and doing lots of dict and slices, which is just awful.

Insert

I tried Mongo first because it was new and fun, but I think its query facilities are too limited to be useful to me. More on that in a bit. But it’s sure fast for inserts: 30,000 rows a second, 47 bytes / row on disk. It’s also fun to work with a schema-free database, it always takes me 20 minutes to get a SQL create table right.

Postgres is slower on inserts, about 10,000 rows a second and 52 bytes / row. (The Postgres FAQ says there’s about 28 bytes of overhead per row.) This is with naive Python executemany() insert; a bulk CSV import would be faster.

But I don’t much care about speed, and less about scalability. This is all one off calculations I’m running by myself. And I’m not equipped to do proper benchmarking anyway.

One caveat: I’m doing all of this measurement without indices. Well, not entirely, Mongo gets a sort of implicit index because I’m storing each station in a separate collection. In the real world of course you’d want an index on station, maybe also on aspects of the timestamp.

Queries

Mongo has very limited query support. It has a basic query predicate language that’s awkward and verbose, no date and time calculations, and precious little aggregation capability like SQL’s AVERAGE() operator. You can write all your queries in Javascript to run on the server. And Mongo has a nifty mapreduce capability for big processing. Only mapreduce doesn’t actually run in parallel in a single Mongo instance, so there’s not much benefit to that computing paradigm unless you have a sharded database.

The big drawback with Mongo is a lot of code to do something that’d be a one liner in SQL. For instance, here’s getting the average wind speed at a station.

# select average(s) from KSFO
# This map reduce version is slow, about 1s on 50,000 rows. It's single threaded :-(
# http://www.mongodb.org/display/DOCS/MapReduce#MapReduce-Parallelism

# Map function: turn a document into the value (1, speed)
# The key for this map is a constant, the number 1: we're summing over the whole collection
mapFunction = bson.Code("""
function() {
  emit(1, { count: 1, sum: this.s });
}""")

# Reduce function: sum up the counts and sums
# Note this can be called on its own output, so have to match types from map
reduceFunction = bson.Code("""
function(key, values) {
    var result = {count: 0, sum: 0};

    values.forEach(function(value) {
      result.count += value.count;
      result.sum += value.sum;
    });

    return result;
}""")

# Execute the query and grab the results. Up to us to do the average calculation.
result = coll.map_reduce(mapFunction, reduceFunction, "myresults")
total = result.find_one()["value"]["sum"]
count = result.find_one()["value"]["count"]

print "Average speed: %.1fkts (%d samples)" % ((total / count), count)

That’s a lot of code just to do an average! Code I have to test, and maintain. It’s not particularly fast, either, 1000ms.

By contrast Postgres really is just one line of code for averages select avg(speed) from winds where station = 'KPAO'. And SQL has great complex date math, stuff I’d have to write myself for Mongo. Postgres is faster on this query, too: 600ms to do the average and that’s on a full table scan of millions of rows without even an index on the station. (It goes to 5ms with the index).

Conclusion

I’m not trying to say Postgres good Mongo bad, not at all. But Mongo’s not a good match for what I’m doing. I don’t have terabytes of data I need to shard across multiple servers. I don’t need sophisticated schema agility. I don’t really need relations, either. All I really need is efficient storage and a fast, convenient query language. Postgres and SQL are pretty good at that.

SRIDs, GeoDjango, PostGIS, and me

Now that I have GeoDjango up and running I was able to import a bunch of airport data using Adam’s code. Back to PostGIS to play!

select facility_name,
  floor(ST_Distance_Sphere(point,
    ST_GeomFromText('POINT(-122.4522 37.7555)')))
    as distance
  from airports_airport
  where control_tower = true
  order by distance
  limit 10;

ERROR:  geometry_distance_spheroid: Operation on two GEOMETRIES with different SRIDs

Frowny. Face. What’s that mean?

Long story short, an SRID identifies which Spatial Reference System the coordinates are with reference to. It’s a bit like units: it’s not enough to say something “weighs 100”, you have to specifiy if you mean 100 lbs, or 100 kgs, or whatever. For more theoretical background, see Geodesy. There’s a giant database of SRIDs at http://spatialreference.org/. (Related keyword: EPSG). Greatest hits:

  • 4326: WGS 84, the reference most GPSes use. I think many people assume this is the SRID by default.
  • 4269: NAD83, a popular North American standard
  • 54004: World Mercator
  • 900913: Google Maps’ modified Mercator. (It spells “google” in l33t).

So the problem is I’m trying to do arithmetic with points in two different SRIDs.

select ST_SRID(point) from airports_airport limit 1;
4326

select ST_SRID(ST_GeomFromText('POINT(-122.4522 37.7555)'));
-1

select ST_SRID(ST_GeomFromEWKT('SRID=4326; POINT(-122.4522 37.7555)'));
4326

GeoDjango defaults to SRID 4326; you can use others, details here. PostGIS ST_GeomFromText defaults to an SRID of -1, which I guess means unknown. But if you’re explicit then it works fine. You can also use PostGIS to transform from one SRID to another, I believe underneath it uses PROJ.4

SELECT ST_AsEWKT(
  ST_Transform(
    ST_GeomFromText('POINT(743238 2967416)', 2249),
  4326
));
SRID=4326;POINT(-71.1776848522251 42.3902896512902)

Personally I find this all frustrating; can’t we just use WGS 84 everywhere and be done with it? Sure, you still need to project when rendering a flat map, but consider that a separate thing entirely.

Fun fact: the reference points for WGS 84 move. And are remeasured roughly yearly. Apparently Greenwich is not at 0 longitude in WGS 84.

Django 1.2 and GeoDjango on Windows

I’ve been trying to develop code on my Windows box. It’s the machine I sit in front of, it’s fast, and I like WingIDE. I have a Linux box for “real work”, but think there’s some discipline in moving back and forth between the two systems.

For GeoDjango hacking I decided to run the PostGIS database on my Linux box and the Django webapp on my Windows box. I’d hoped this would avoid having to install a bunch of funky binaries on Windows. No such luck. The GeoDjango docs are a bit out of date and the official GeoDjango Windows installer binary is for an old version.  Here’s what I’ve learned doing it myself.

The first step is getting regular Django working. Here’s what I did:

  • Installed PostGIS + dependencies on Debian (testing) via
    aptitude install postgresql-8.4-postgis
  • Installed stock Python2.5 on Windows from Python.org
  • Installed Django 1.2 on Windows. I forget how I did this, I think using easy_install, which in turn requires installation as well. It wasn’t hard, just followed the tutorial. Django 1.2 includes GeoDjango Python libraries.
  • Installed psychopg2, the database driver, on Windows. There’s binaries at http://stickpeople.com/projects/python/win-psycopg/

GeoDjango is harder. It relies on a lot of C libraries, some of which don’t support Windows well. The main hurdle is a working GEOS DLL. The GEOS page itself doesn’t have binaries. I found binaries from three places: OSGeo4W,  the GeoDjango Windows Installer, and PostGIS. Here’s a quickie test program I wrote to try them out:

geosPath = r'.\libgeos_c-1.dll'

from django.conf import settings
settings.configure(GEOS_LIBRARY_PATH=geosPath)
from django.contrib.gis.geos import tests
tests.run()

Unfortunately, both the OSGeo4W and GeoDjango versions of the DLL don’t pass the tests. Version skew? Bug? The underlying error seems to be in memory management, something like

ERROR: test02_wktwriter (django.contrib.gis.geos.tests.test_io.GEOSIOTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "c:\Python25\lib\site-packages\django\contrib\gis\geos\tests\test_io.py", line 30, in test02_wktwriter
    self.assertEqual(ref_wkt, wkt_w.write(ref))
  File "c:\Python25\Lib\site-packages\django\contrib\gis\geos\prototypes\io.py", line 147, in write
    return wkt_writer_write(self.ptr, geom.ptr)
  File "c:\Python25\Lib\site-packages\django\contrib\gis\geos\prototypes\threadsafe.py", line 55, in __call__
    return self.cfunc(*args)
  File "c:\Python25\Lib\site-packages\django\contrib\gis\geos\prototypes\errcheck.py", line 87, in check_string
    free(result)
WindowsError: exception: access violation reading 0x02F12494

The library that did work for me was the version that came with PostGIS. I didn’t even install PostGIS, just grabbed the DLLs out of their zipfile. Unfortunately GEOS is spread into two files: libgeos_c-1.dll and libgeos-3-2-2.dll. The latter needs to be in a directory where Windows can find it as a normal DLL, I put it in the working directory of my own code.

GEOS was enough for me to get the tests working and my simple GeoDjango program working correctly. There’s more work to be done: I believe you want both GDAL and PROJ.4 available to GeoDjango on the Windows side. Or does PostGIS do the work on the database server? I haven’t tested that yet.

In addition to basic GeoDjango on Windows setup, here’s notes specific to my code:

  • Followed instructions on getting WingIDE to work with Django
  • Sweated a lot over environment considerations, specifically Python path. I hate setting up new development environments, and Django with its mix of servers and applications and developer code and third party libraries is complicated.
  • I’m trying to run a script directly, not via manage.py. To make that work you need to set the DJANGO_SETTINGS_MODULE system environment variable to point to the Python path of your settings.py
  • settings.py needs to specify a special database engine:
    ‘ENGINE’: ‘django.contrib.gis.db.backends.postgis’

There’s some more useful notes about Windows and GeoDjango in this blog post by Reinout van Rees.

Learning some GIS

Today’s hacking project is getting up to speed with modern GIS. Specifically, PostGIS (Postgres with spatial features) as a database, QGis as a graphical frontend for viewing graphics data, and GeoDjango for building webapps.

QGis is awesome: you can quickly add layers, including layers that come from PostGIS. Loaded layers are on the tray to the left, you can right click them to set display options, enable a query to filter what’s displayed, etc. There’s also an edit mode for editing geometry.

PostGIS is encouraging. Some notes:

After finishing all the setup I loaded the cities and counties file referenced in that first tutorial (at USGS) It was easy to load them up into QGis for display. “Show me county outlines, and the names and locations of all cities with more than 100,000 residents”.

Playing in PostGIS, here’s some interesting queries:

select county, ST_Area(wkb_geometry) as area from us_counties
where state = 'CA'  order by area desc limit 5;
Biggest county. Units of Area are.. degrees?
                       county                       |       area
----------------------------------------------------+------------------
 San Bernardino County                              | 5.13534296766738
 Inyo County                                        | 2.66716021408502
 Kern County                                        | 2.09407653001836
 Riverside County                                   | 1.84319135357509
 Siskiyou County                                    | 1.77534424474288

select county, ST_AsText(ST_Simplify(wkb_geometry, 0.1))
  from us_counties where state = 'CA'  limit 1;
(returns a simplified polygon of the county outline)

\d us_counties
shows all the columns. The interesting one is
  wkb_geometry | geometry
Geometry is a polymorphic type, in the case of this shapefile it's a Polygon. The "WKB"
name is just a descriptive, but implies the import source was in "well known binary" format. 

select name, ST_X(wkb_geometry), ST_Y(wkb_geometry)
  from us_cities where name like 'San %' and state = 'CA';
 San Anselmo                                      | -122.561653137207 | 37.9746437072754
 San Rafael                                       | -122.531089782715 | 37.9735336303711
 San Quentin                                      | -122.487464904785 | 37.9412689208984

select name, state,
  floor(ST_Distance_Sphere(wkb_geometry, ST_GeomFromText('POINT(-122.4522 37.7555)'))) as distance_from_SF
  from us_cities where state='CA' order by distance_from_sf   limit 5;

                       name                       | state | distance_from_sf
--------------------------------------------------+-------+------------------
 San Francisco                                    | CA    |             3602
 Daly City                                        | CA    |             5596
 Broadmoor                                        | CA    |             8207
 Colma                                            | CA    |             8767
 Brisbane                                         | CA    |             9495


select county from us_counties where
  ST_Contains(wkb_geometry, ST_GeomFromText('POINT(-122.4522 37.7555)'));

shows which county contains an arbitrary lat/lon
select county, ST_Area(wkb_geometry) as area from us_counties where state = 'CA'  order by area desc limit 5;
county                       |       area
----------------------------------------------------+------------------
San Bernardino County                              | 5.13534296766738
Inyo County                                        | 2.66716021408502
Kern County                                        | 2.09407653001836
Riverside County                                   | 1.84319135357509
Siskiyou County                                    | 1.77534424474288
select county, ST_Area(wkb_geometry) as area from us_counties where state = 'CA'  order by area desc limit 5;
county                       |       area
----------------------------------------------------+------------------
San Bernardino County                              | 5.13534296766738
Inyo County                                        | 2.66716021408502
Kern County                                        | 2.09407653001836
Riverside County                                   | 1.84319135357509
Siskiyou County                                    | 1.77534424474288