Some Bits: Nelson's log

62 posts in 2011

Sublime Text 2 and Python

I’m working on replacing my existing IDE (WingIDE) with Sublime Text 2. I prefer Sublime as an editor, particularly since WingIDE runs under X11 on MacOS (yuck). Also I don’t use most IDE features of Wing; just a bit of smart completion, unit test integration, pdb integration, .. OK, several things.

Anyway, here’s a list of Sublime Text modifications I’m finding useful for Python. I’ll update this post over time. (As an aside it’s hard to search for plugins for Python developers, because the plugins themselves are written in Python and so you get lots of false matches.)

  • sublimetext_python_checker: one of several linter plugins. I like this one because I can set it up to run PyFlakes in an unobtrusive way.
  • PdbSublimeTextSupport 0.2: a tiny shim to have Sublime show you what line of your source code it currently is in. I’ve never been good with PDB, I immediately miss all the graphical support of a full IDE like Wing. So this may not be enough.

I’ve also set up my own build command to use to run unit tests. It’s not complete, I need to figure out Sublime’s support for showing where errors occurred. But it’s a start.

{
 "cmd": ["python", "-m", "unittest", "discover", "-p", "*.py"]
}

Things that look promising that I haven’t tried:

Python linters

I was playing around with Python lint tools. There’s a lot of terrific info in this StackOverflow question, so all I really have to offer is some very simple knee jerk opinions.

  • pyflakes is very brief, but did a good job finding actual errors
  • pep8 is a nice way to check specifically for code style issues and nothing else.
  • pychecker is useless, since it executes the code
  • pylint is amazingly detailed and anal. Also useless because it prints way way too much. I really don’t care that my test functions don’t have docstrings or that my comments are more than 80 characters. Maybe if I were working on more team projects I’d build up a set of “ignore this message” rules and turn it into a useful tool to me.
Conclusion: pyflakes. If I cared more, I’d use pylint. If I were contributing code to libraries, pep8.

Trying out Riak on MacOS with Homebrew

Homebrew install notes

I decided to try out Riak on MacOS, using Homebrew to install. Here’s some rough notes.

“brew install riak” worked. However, it didn’t leave you the Makefile you need to do “make devrel” in order to set up the 3 node test cluster. So I interrupted Homebrew during the install, copied the patched sources, did “make all rel devrel” in my own source tree, then copied the “dev/dev?” directories off. Still using the Homebrew binaries. Lot of work for 4 lousy config files :-P

The Python client you want is riak-python from Basho. Unfortunately “pip install riak” doesn’t quite work, because Pip first tries to install protobuf and there’s a three year old bug open on Google’s protobuf client about how it doesn’t install right in Python. Some helpful soul forked Google’s library and his version can be installed witih pip install “git+http://github.com/rem/python-protobuf.git@v2.4.1#egg=protobuf”

With that you have a working Riak and Python environment that you can use to work with the tutorials online.

Insert notes

Trying to insert my weather data: millions of rows of 4 tuples: (station name, timestamp, speed, direction). Testing with 3 Riak nodes running on my single fast iMac. This data is not a good match for document oriented stores: I already learned that Mongo was not good and expect Riak not to be, either. Still, it’s real data I have and I want to try it.

Wow, is Riak slow if you just use it as a naive user. 3 node cluster running on a fast iMac, inserting 45,000 records one at a time with a store() between each took 120 seconds.

Some write optimization.. there appears to be no batch insert in the Python library I’m using (although see this). Riak’s exposure of consistency via the W parameter is really neat, but what I need is to commit 10,000 records at once. I’ve tried optimizing my writes (ie: windData.store(w = 0, dw = 0, return_body = False)). Switching from HTTP to Protocol Buffers gives about a 4x increase. Still, no matter what I do, I can’t do better than 1900 records / second. Compare Mongo’s 30,000 records / second or Postgres’ 10,000 rows a second. Am I doing something terribly wrong?

Sadly, I get a 10% speed increase (from 1900 to 2100 records / second) if I only have one node in the cluster. Not useful in the real world, but interesting.

With just a single node running Riak seems to use about 1 kilobyte / document (650,000 rows, 720 megs on disk). Not good, since the docs themselves are like 20 bytes of data. Compare about 50 bytes / row for both Postgres and Mongo. With 3 nodes the combined disk usage is about the same size; I’m surprised, I thought the default config was three copies of all data.

I sure miss the ability to drop a whole bucket. I don’t really have a way to reset my database while testing.

Query Notes

Once again I petulantly note that raw map/reduce is awfully low level if you just want a damn SQL function. Of course it gets wonderful when you want to query using 100 machines and a distributed data store.

Trying to list 50,000 keys in a bucket (via /keys?keys=true) kills both Chrome and curl: they complain the HTTP header returned is too big. Also the docs warn you to never do this in production. In other words, queries over the whole dataset are difficult. I think you need to use links or some extra indexing system to do queries. Riak has a search capability, btw, but it looks more full text oriented than simple data iteration.

I wrote some simple mapreduce code to do “select count(*) from bucket” and “select count(*) from bucket where parameter > 30”. It takes 16 seconds to run over 60,000 rows, that’s just unacceptable. Also the answer it gives is wrong; 43561 instead of 59072. Huh. While it’s cool I could run this query while nodes were dropping out, it’s uncool that the answer it gave varied as data was moved around.

I don’t think I have a bug in my query code, but you never know... Here it is.

import riak

client = riak.RiakClient(port=8081, transport_class=riak.RiakPbcTransport)

# select count(*) from KSFO
query= client.add('KSFO')
query.map("function(v) { return [1] }")
query.reduce("Riak.reduceSum")
for result in query.run(): print result

query = client.add('KSFO')
query.map('''function(v) {
    var data = JSON.parse(v.values[0].data);
    if (data[1] > 20) {
        return [1];
    } else {
        return [];
    }}''')
query.reduce("Riak.reduceSum")
for result in query.run(): print result

Evaluation

I knew this data was a poor match for Riak and now I’m doubly sure. The 1k / row is the real problem. I don’t think Riak is bad or anything, quite the opposite. Just curious how it feels to try it out on some data.

I really admire how Riak is distributed to the core. Most datastores design for a single server, then later add replication and partitioning. It’s a total mess. Riak started distributed, and if they did it right it should be significantly more robust for real network usage. Also for parallel data analysis. I also think it’s freaking amazing how you can do “riak-admin join” and “riak-admin leave” and the data transparently repartitions while the cluster is still up and serving write requests.

I wonder how robust Riak is in recovering if a node drops offline without a clean shutdown, then joins later with inconsistent data? The docs on CAP mention some voting and validation protocols, so they’ve thought about it. More a question of convenience than usability.

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.

Alternate terrain shading

Mike pointed me to an interesting slide deck by Leland Brown in October 2010, about using a fractional Laplacian to colour a terrain map instead of the usual altitude greyscale or hill shading. The results are pretty nice and the presentation of how he did it is quite clear.

Conceptually, what he’s doing is a bit like a standard altitude greyscale. Ie: 0′ is black, 15,000′ is white, and use a grey ramp inbetween. But the transform he applies highlights local terrain differences. Ie: the shade of a pixel isn’t just its absolute altitude, but also how it differs based on its neighboring pixels. It’s a little analagous to edge enhancement on an image: find regions of high variance and highlight them. The result is a map that’s essentially altitude coloured, but with highlighting of local terrain details.

One nice aspect of the math he’s using is that it’s scale invariant. That means the algorithm makes sense at all scales and, also, doesn’t need to be recalculated at different scales.

The computation is more expensive than hill shading but not terrible: he says he can do 10,000 x 10,000 pixels in a few minutes. He notes at the end it’s a bit tricky to do this with tiled data, because you should consider data outside the tile itself when doing the rendering.

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.

NFS notes

I set up some NFS mounts from my Linux (Debian) box to my Mac. Some notes.

Servers: install nfs-kernel-server. Configure it along these lines. NFSv4 seems to want to serve all its fileshares from a single directory, which seems weird, so you do this “mount --bind” thing to collect them on the server. Options on the server are ro,nohide,insecure,no_subtree_check,async

Client: Use MacOS Disk Utility (File / NFS Mounts..) to add static mount points. They seem to mount automatically once you exit the tool, but I’m not sure. I set the following advanced options: ro,intr,soft,nfsvers=4. Here’s some Mac docs.

NFSv4 is the new hotness. You can verify you’re using it with “nfsstat -4 -s” on the server and count the numbers.

These notes are all for a read-only export of world readable data. Next step is to export read-write, which requires synchronizing users. Unless you go some authenticated route (ie: Kerberos) the best bet is to be sure numeric user IDs are the same on the client and the server. On MacOS you can change your uid by right clicking on your name in the Users & Groups preferences pane. I’m guessing you’ll have to manually chown the files afterwards.

MongoDB size notes

I’m playing with using MongoDB to store a bunch of wind time series data for my wind map. First time trying it out. Some quick notes:

I have a bunch of data that’s 4-tuples like this:

“KSQL”, 2011-09-23 11:47:00, 200, 7

That says that at KSQL at a specific time the wind was 7kts from 200 degrees. In an ideal encoding each row would take 10 bytes. In a comfortable encoding it’ll take 20. I’ll settle for 50 bytes per row in the unindexed database. MongoDB is taking 67 bytes per object. Or more!

Sample input: KDTW and KMDS. 116,000 rows total, 2 megs of CSV, 400k of csv.gz. After import, Mono is reporting a 7.8 meg data size, or 68 bytes / object. That’s with very short element names (“d”, “s”, etc). If I use long element names (“direction”, “speed”) it balloons to 87 bytes / object. And yes, the extra 19 bytes is exactly the # of characters I added to my element name.

Lame! Apparently Mongo compresses nothing, it doesn’t even try to use a lookup table to avoid storing a zillion copies of element names? (See this user request to tokenize field names.) That seems very bizarre; not only would a simple table save space, wouldn’t it save time by making the memory working set smaller?

I don’t have any need for queries across multiple station names. So instead of having one giant table (er, “collection”) for all my data, I’m going to make one collection per station. That’ll give me some 5000 collections. I’m still at 47 bytes per row, which I said was acceptable but seems awfully wasteful. I’m beginning to wonder if MongoDB is a good match for this data. All those ObjectIds aren’t doing me any good, that’s for sure.

Notes on getting TileStache renders working on MacOS

Personal work notes for this project I’m working on. Mac DLL hell included. Unlikely to be of interest to any unfortunate reader who found this post.

I’m trying to run some tile generation software that generates odd TIFFs. The TIFFs have two separate images in one single file. This is a legitimate TIFF but it’s unusual and I’m having a hard time producing it on my Mac. The exact same end code works fine on Linux.

There’s a bunch of software involved here. Python, gdal, boost, MapNik, Cairo, swig, TileStache, ... When it’s all mashed up the code I’m running is basically a Python program with a lot of bindings to geo and image C libraries, using boost and swig. Ie: a big fucking hairball.

If I use MacOS Lion’s version of libtiff, the code all runs fine but the images it produces are corrupted. Same error as this discussion. gdalinfo can’t load them:

gdalinfo out/10/000/163/000/395.tiff
ERROR 1: out/10/000/163/000/395.tiff:Failed to allocate memory for to read TIFF directory (0 elements of 12 bytes each)
ERROR 1: TIFFReadDirectory:Failed to read directory at offset 52744
gdalinfo failed - unable to open 'out/10/000/163/000/395.tiff'.

If I use homebrew’s default libtiff (3.9.5) the code hangs. Poking at it with gdb I see the program is spinning at 100% CPU deep inside some error binding between libtiff, Python, and either Boost or Swig. Yuck!

If I build my own tiff-4.0.0beta7 in homebrew and use it, it runs and produces the same corrupted TIFFs as Lion. (To build in Homebrew, you have to edit the libtiff.rb formula and add an option to configure, “--x-includes=/usr/X11/include”. Otherwise, it can’t find some of the GLheader files when compiling.). tiff-4.0.0beta5 is no better.

A big confounding issue has been getting the Python environment right in Homebrew. More notes on that here. I think everything’s working anyway, various Python and gdal programs do, but you never know.

Another confounding issue has been compiling things correctly. The transition in C compilers on Lion makes a mess. Homebrew gamely tries to use LLVM but some stuff only works with gcc-4.2 (including Numpy). I was worried that mixing the two compilers might have been causing problems, so finally rebuilt everything with just gcc using this environment:

export HOMEBREW_USE_GCC=true
export CC=gcc-4.2
export CXX=g++-4.2
export FFLAGS=-ff2c
export HOMEBREW_BUILD_FROM_SOURCE=true

Extra notes: “man dyld” is very useful for manipulating shared libraries. In particular the DYLD_INSERT_LIBRARIES and DYLD_PRINT_LIBRARIES environment variables let you see and control which versions of libraries are being used.

Serving mbtiles tiles for slippy maps

I’m playing with TileMill (see my blog post here). TileMill publishes to an mbtiles file, a sqlite3 database that contains the rendered image tiles. One simple file, so nice! Now, how to serve it? The simplest solution is TileStream hosting, but I’m too cheap and hackish to pay the very reasonable $50 / month.

So I set up a tile server on TileStache instead, a Python system. You can see the setup on GitHub. It took about four hours to get working, even though none of it is too complex. Here’s my notes.

  1. Install TileStache via Python easy_install and configure. It’s pretty simple, the only subtle thing is that TileStache wants a cache. This may not be necessary with pre-rendered mbtiles bundles but it was easy enough to set up memcached and configure it.
  2. Set up TileStache to render via CGI, with a CGI script and a bit of Apache config. CGI is a bad way to serve things, but I’d hoped it was sufficient and it was easy to get going. Turns out to be unacceptably slow.
  3. I tried a couple of failed approaches for WSGI. First I tried TileStache’s built in WerkZeug server. This works and is faster than CGI, but lacks administrative scripts to wrap it. Then I tried Apache WSGI and ran into an error with no useful debug output. Gave up on that.
  4. Set up gunicorn, the excellent Python asynchronous server for WSGI. It’s easy to set up on Debian if you get version 0.13 from Backports, it comes with nice administration scripts. Just needs a little config file. I also installed python-gevent for an async worker.
Doing all this, my crappy old single CPU server with 1 gig of RAM can handle serving a map to a single user at acceptable speed. It can probably do more than that, I haven’t load tested it.
I left some things not done, this was intended as a quick hack:
  • gunicorn really wants a proxy HTTP server like nginx in front of it. Good idea, but I didn’t want to bother. The bummer is gunicorn doesn’t set any caching headers at all; really need those for a real deployment.
  • The cool kids building TileMill are doing everything with Node.js these days. Their TileStream server would be another option, but getting Node running on Debian was too much work for a quick hack.
It’s a little surprising that MBTiles is so complex to serve. It’s basically just a big archive of JPG images, it’d be nice to have a little C program to serve it blindingly fast. “mbserv foo.mbtiles --port 8989”. TileStache is a big program that does a lot of stuff, but even TileStream is 900+ lines of code and all it does is serve MBTiles.

svg:text - baseline considered harmful

SVG has a bunch of properties for laying out text. Two really handy ones are “dominant-baseline” and “baseline-shift”, which together let you move text up and down a bit. “dominant-baseline: central” seems particularly useful because it lets you lay out text where 0, 0 is the middle of the text, not the baseline underneath the letters. Ie: visually center things vertically.

Unfortunately those properties don’t work in many SVG implementations. They work in Safari and Chrome, but not in Mobile Safari, IE, or Firefox.

A workaround is to use the dy parameter on the text nodes to move them around. dy: .35em is about like centering. I don’t think this works via CSS, though, only in the DOM.

Before and After

I’ve added some new code to my wind history project to show winds based on month of year. With all 12 months selected the new code should produce similar results to the old code. I don’t really have any proper tests for this stuff, though, so I’m just kinda looking at the pictures and saying “yeah, looks about right”. Here’s a before and after: do the wind roses look the same to you? (Note that I moved the location of one wind rose, San Jose. That’s a bug fix).

 

 

 

Update: Seth was nice enough to register the images and do a difference calculation for me. Which is awesome and sad all at once :-P

Geolocation API tests

I’m adding geolocation to my windhistory project. It’s a very easy API. Some quick notes based on a call to getCurrentPosition() with a few options: { maximumAge: 1000*60*60, timeout: 1000*2, enableHighAccuracy: false}

Chrome on MacOS seems to use IP address to identify what city I’m in. It puts me at 37.775/-122.419, the middle of San Francisco, whether my WiFi is on or not.

Safari on MacOS seems to require WiFi location. It won’t geolocate at all if wifi is turned off; the Javascript API returns error -2 (no position available). With WiFi on it seems to use the same airhook style location as the iPhone. It puts me at 37.749/-122.428, which is just about where I’m sitting. MacOS has privacy System Preferences for location services. The geolocation API stops working if you disable location services entirely, but it’s not necessary to have “Safari” checked in order for Safari to geolocate you. That seems like a bug, even if Safari itself is doing some privacy protection.

Firefox 6 on MacOS also seems to use WiFi location, 37.749/-122.428. Didn’t test what it did without wifi.

MSIE 9 on Windows 7, running in a VirtualBox VM on my Mac, gives me a slightly different location of 37.748/-122.416. I’ve got no idea where it got that idea, but it’s a pretty good fix. Certainly not wifi! Maybe Microsoft has a geolocation service guessing based on external IP?

Firefox 4 on Windows 7 (in the VM) puts me at 37.775/-122.419, just like Chrome.

Bottom line: Chrome seems to use an IP database, Safari and Firefox use the Mac API, and who knows what IE is doing.

Quick thoughts on writing Objective C

Playing with my new Mac, this is my first time writing Objective C code in 15 years, and C or C++ code in nearly 10. Some quick thoughts after finishing Your First Mac Application.

  • Header files? In 2011? That require forward declarations of classes? Ugh.
  • Objective C properties are handy syntactic sugar. I have no idea what “synthesize” really does, but I like the result.
  • Static typing is awkward. I’m prefering dot style for properties
    self.track.volume = sender.floatValue;
    But if the type of “sender” is id that doesn’t work. I have to fall back to
    self.track.volume = [sender floatValue]
    and rely on Objective C magically not type checking method names on id. Objective C has duck typing, sorta, but not everywhere.
  • Manual memory management continues to suck. Apple has papered over it in various ways, with retained properties and autorelease and now ARC. But the fact that the programmer is even aware of reference counts is a serious flaw in the language. Seriously, every other OO language for 20 years has had garbage collection. Hell, even C languages have had automatic garbage collection via a conservative collector like the Boehm collector. WTF is wrong with Apple that their development language requires manual memory management?
  • Xcode 4.1 is a pretty solid IDE. I could drop into it with just a basic tutorial and understand most of what was going on quickly. The Interface Builder stuff so far seems OK, although we’ll see how it works with real code. I’m impressed with how one can do complex user interface constraints entirely graphically.

The size of an empty Mac app

I created my first Macintosh application today, following Apple’s excellent docs. I didn’t write any code yet, just the default Cocoa application template. I’m always fascinated what the size of empty apps is; it often indicates how simple and clean the underlying architecture is.

I did “Build for Run” and stripped the binary. The compiled app is 44k. The binary is 14k, the NIB is 26k. It takes 10M of memory (80+M if you count shared).

Xcode created 13 files in my source directory: 14,000 lines of source totalling some 400k. Almost all of that is an XML bloated NIB file I’ll never look at as text. There’s 51 lines of ObjC code in 3 files. Pretty much all that is boilerplate; the important bits are

int main(int argc, char *argv[]) {
    return NSApplicationMain(argc, (const char **)argv);
}
@interface TrackMixAppDelegate : NSObject <NSApplicationDelegate> {
    NSWindow *window;
}
@property (assign) IBOutlet NSWindow *window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application
}

It’s certainly nicer than the 400+ lines of unmaintainable garbage that Visual Studio’s wizard generates doing a similar task. I’m optimistic that the NIB system will work out well. MacApp’s version of this was a fucking disaster in the OS 6 days, but NextStep Interface Builder was always pretty impressive.

Whitespace in HTML

I forget this about once a year. These two kinds of markup do not render equivalently:

<div>
<span></span>
</div>

<div><span></span></div>

The problem is the whitespace in the line breaks; those get rendered. In Chrome, they seem to add 1 pixel of spacing.

Digital elevation models

Doing some research on Digital Elevation Models, for making terrain maps.

SRTM

(Wikipedia, OSM Wiki) sourced from a space shuttle overflight in 2000. Comes in several flavours and sources.

Sources:

  • NASA source (download link). Original data. Version 2.1 is their latest, cleaned up by NGA. The NASA has some data voids, particularly at mountains and lakes. Documentation of the dataset.
    License: Data said to be fully open for any use; don’t have a specific reference.
  • CGIAR-CSI Data processed to remove voids. SRTM3 only. They publish it as “version 4.1”, version number reflects their data cleaning. Also available as an Amazon EBS volume.
    License: non-commercial with attribution.
  • HydroSHEDS. SRTM data with voids filled, SRTM3 only. Also vector data on watersheds. Technical documentation.
    License: “free for non-commercial use”
Details on NASA source:
SRTM1:
  • Resolution: 1 arc second, roughly 30m, z=12
  • Format: .HGT files, 3601x3601 per one degree square file. Each sample is 16 bits, height in meters (-32768 for no data). GDAL supports this format.
  • Coverage: Continental US, a bit of Alaska, and various US territories. Coverage map.
  • Size: 1117 files of 25 megs each, or 27 GB uncompressed. 2:1 compression with gzip.
SRTM3:
  • Resolution: 3 arc seconds, roughly 90m, z=10
  • Format: .HGT files as SRTM, 1201x1201 per one degree square file.
  • Coverage: global land mass from 60N to 56S. (Missing Antarctica, significant Northern parts of North America, Europe and Asia).  Coverage map.
  • Size: 14546 files of 2.8 megs each, or 39 GB. 2:1 compression with gzip.
SRTM30:
  • Resolution: 30 arc seconds, roughly 1km, z=7
  • Coverage: global from 90N to 60S. (Missing Antarctica). Coverage map. See also GTOPO30.

National Elevation Dataset

Wikipedia. Also NED FAQ. USGS data from various sources.
  • Resolution: 1 arc-second (z=12), 1/3 arc-second (z=14), and 1/9 arc-second (z=15).
  • Format: accessible via WMS. Data downloads provided in ArcGrid format and “float format”, looks like 32 bits / sample.
  • Coverage: United States and Mexico only. 1/3 for the 48 states, 1/9 in some detailed places. Coverage maps: 1 arcsecond, 1/3, 1/9
  • Size: files appear to be double the size of equivalent SRTM data. Rough guess: 50GB for 1 arc-second, 450GB for 1/3 arc-second.

Viewfinder Panoramas

Eclectic collection of more detailed / patched data than SRTM in certain spots. Unclear licensing.

ASTER GDEM

Joint NASA/Japan METI project, produces a 30m DEM. (Wikipedia, OSM Wiki) Has coverage between 83N to 83S and some holes filled compared to SRTM. Some question on quality; the data comes with a “quality assessment file”. May be free to use, but some concern on the OSM Wiki that its license is not consistent.

OpenDEM

Well intentioned but small project to provide better DEM data. Some useful notes.

GMTED2010

USGS project. Global data: 90S to 83N. 7.5 arc second (30m). Looks to be a combination of SRTM data and other sources. License is presumably public domainish. The metadata page says “Metadata access constraints: No restrictions, All GMTED2010 data products and associated metadata are publically available”.

Notes on building a slippy map of the Fisk maps

I got interested in these Fisk maps of the Mississippi, so I’m making a slippy map. Here’s what I did.

  1. Downloaded the rectified TIFFs from the Army. These have already been rotated and georeferenced and are pretty high resolution. The p22* files are the maps I worked with.
  2. Created pyramidal overviews for the TIFFs so I could explore them in QuantumGIS more quickly. Not strictly necessary, and in fact may be harmful: gdal2tiles seems to pick up the JPG compression.
    gdaladdo -r average --config COMPRESS_OVERVIEW JPEG --config PHOTOMETRIC_OVERVIEW YCBCR --config INTERLEAVE_OVERVIEW PIXEL -ro p22_s12.tif 2 4 8 16 32
  3. Created a virtual raster layer including properly annotated sections of no data
    gdalbuildvrt -srcnodata “255 255 255” fisk.vrt *.tif
  4. Generated slippy map tiles
    gdal2tiles.py -z 4-13 fisk.vrt
At that point, I was done! gdal2tiles.py includes a Google maps interface that works. Of course I couldn’t leave well enough alone, so I wrote my own Javascript interface using Polymaps.
Some other caveats and notes:
Data quickly gets big and slow. The source map is only 32 megs of TIFFs, maybe 10,000 x 150,000 pixels. But all the cutting and repackaging and uploading is going to take hours. I did OK experimenting with a small subset (just 2 TIFFs of 15). I decided to cut the render to z=13 instead of going full resolution to z=14: 4x speedup! (Final result: roughly 6 hours CPU, 230 megs of GIFs for the tiles).
The source TIFFs include page margins. A proper seamless map would require cutting those off by hand. I didn’t bother for this quick hack.
Output image format is a problem. The default PNG output of gdal2tiles is enormous. Some details, including file size of the tileset for a sample input of only 2 of the TIFFs
  1. 32 megs: source TIFFs (sheets 12 and 13 only)
  2. 60 megs: gdal2tiles output, 24 bit PNGs with transparency. (was 220 megs at z=14)
  3. 50 megs: optipng. Doesn’t help as much as I need, only 10-20%.
  4. 15 megs: JPG. These would be awesome, but I need transparency because the source maps aren’t rectangular
  5. 24 megs: 8 bit PNGs with transparency. Unfortunately imagemagick’s PNG8 conversion is buggy, particularly with transparency, and I can’t use it.
    convert foo.png PNG8:foo-8.png
  6. 28 megs: GIFs. imagemagick does a good job emitting GIFs with transparency.

iPhone consolidated.db location tracking notes

I’m trying to understand the consolidated.db iPhone location database, which means understanding how iOS stores and managing data. Here’s some notes.

Resources

  1. @aallan’s original announcement
  2. iPhone Tracker (Objective C code)
  3. Technical instructions from howto.wired
  4. nphonetrack (.NET code)
  5. iPhoneLs.py
  6. iphone-tracker.py
  7. Quick start for sqlite3
Notes
  • When you make a backup of an iPhone, it creates a big directory full of files with random 160 bit filenames. These are named files in the iPhone that iphonels.py can display. My 3 biggest files are named
    HomeDomain::Library/Caches/com.apple.WebAppCache/ApplicationCache.db
    AppDomain-com.foreflight.ForeFlightMobile::Documents/Procedures.zip
    RootDomain::Library/Caches/locationd/consolidated.db
  • consolidated.db is the file with the location data in it. It’s a sqlite3 database.
  • The juicy tables are (apparently) CellLocation and WifiLocation. The *Counts tables seem to contain just a row count. Presumably the Boxes tables are some sort of spatial index. I can find no record of how often I was at a specific location other than what’s implicit in the timestamps and density of cell/wifi locations.
  • I have 32,013 rows in CellLocation, 171,040 rows in WifiLocation
  • Timestamps are like 309803342: I believe this is NSDate seconds since 1 Jan 2001. Add 978307200 to get it in seconds since Unix 1970 epoch.
  • HorizontalAccuracy varies from 50-300 for WifiLocation, and up to 80,000 for CellLocation.
  • Confidence is 0, 50, 60, 65, 68, or 70
  • Speed and Course are always -1 (no surprise).
Some quicky sqlite3 shell code
.mode csv
.output wifilocation.csv
select Timestamp, Latitude, Longitude from WifiLocation order by Timestamp;
.output CellLocation.csv
select Timestamp, Latitude, Longitude from CellLocation order by Timestamp;
Some pasted info from sqlite3
sqlite> .tables
CdmaCellLocation                   CellLocationCounts
CdmaCellLocationBoxes              CellLocationHarvest
CdmaCellLocationBoxes_node         CellLocationHarvestCounts
CdmaCellLocationBoxes_parent       CellLocationLocal
CdmaCellLocationBoxes_rowid        CellLocationLocalBoxes
CdmaCellLocationCounts             CellLocationLocalBoxes_node
CdmaCellLocationHarvest            CellLocationLocalBoxes_parent
CdmaCellLocationHarvestCounts      CellLocationLocalBoxes_rowid
CdmaCellLocationLocal              CellLocationLocalCounts
CdmaCellLocationLocalBoxes         CompassCalibration
CdmaCellLocationLocalBoxes_node    Fences
CdmaCellLocationLocalBoxes_parent  Location
CdmaCellLocationLocalBoxes_rowid   LocationHarvest
CdmaCellLocationLocalCounts        LocationHarvestCounts
Cell                               TableInfo
CellLocation                       Wifi
CellLocationBoxes                  WifiLocation
CellLocationBoxes_node             WifiLocationCounts
CellLocationBoxes_parent           WifiLocationHarvest
CellLocationBoxes_rowid            WifiLocationHarvestCounts

CREATE TABLE CellLocation (
  MCC INTEGER,
  MNC INTEGER,
  LAC INTEGER,
  CI INTEGER,
  Timestamp FLOAT,
  Latitude FLOAT,
  Longitude FLOAT,
  HorizontalAccuracy FLOAT,
  Altitude FLOAT,
  VerticalAccuracy FLOAT,
  Speed FLOAT,
  Course FLOAT,
  Confidence INTEGER,
PRIMARY KEY (MCC, MNC, LAC, CI));

CREATE TABLE WifiLocation (
  MAC TEXT,
  Timestamp FLOAT,
  Latitude FLOAT,
  Longitude FLOAT,
  HorizontalAccuracy FLOAT,
  Altitude FLOAT,
  VerticalAccuracy FLOAT,
  Speed FLOAT,
  Course FLOAT,
  Confidence INTEGER,
  PRIMARY KEY (MAC));

subverting iframe same-origin policy

I want to embed a part of a web page from a third party on to my web page. Easy, right, that’s what iframes are for! Only I don’t want to embed the whole foreign page, just a 200x200 pixel chunk in the middle of the page. You can crop 200x200 with the width and height parameters, but there’s no clean way to scroll to the middle of the embedded page. The simple Javascript scrollTo fails because the third party page in the iFrame does not have the same origin as the main page.

There’s a work around: doubling up on iframes. Your main page embeds an iframe to a shim page on your own server. The shim page in turn just embeds an iframe of the foreign page. The master page can scroll the shim page since they’re in the same origin. Ugly, but it works.

aprs.fi as a source of GPS tracks

I have some friends who track their positions via ham radio on APRS. Cool stuff. The site http//aprs.fi/ has a really nice map viewer of the data. I’m looking at extracting that data for my flight tracker.

The easy way is to have the user use the data export tool to download a file. It’s a bit awkward and manual but easy to understand. There are multiple format options, CSV seems sufficient. Fields are:

  • time: full text UTC, “when the target first reported this (current) position”
  • lasttime: identical to time in my data. “the time when the target last reported this (current) position”
  • lat: decimal degrees
  • lng: decimal degrees
  • speed: kilometers / hour
  • course: degrees, probably true?
  • altitude: meters
  • comment: empty in my examples. “APRS comment”

aprs.fi also has a simple REST API. Unfortunately it only seems to report the last fix, not a history of the track. A fetch of the last location works like http://api.aprs.fi/api/get?name=CALLSIGN&what=loc&format-JSON&apikey=KEY.

The granularity of track data is up to the APRS sender. I think one fix every 5 seconds is considered fast. My friend’s tracker is smart enough to send more rapid updates when turning, etc. 66 points for a 90 minute flight.

There are other sources of this data. aprs.fi notes you can also get the data directly from APRS-IS via a library like Ham-APRS-FAP. There’s also aprsworld.com; Adam Fast has some nice API code that relies on his having database access to aprsworld.

Ubuntu 11.04 notes

Time for my yearly experiment running Linux as a Desktop OS. I installed Ubuntu 11.04 beta1 (“Natty Narwhal”). And immediately hit graphics corruption and system crashes. To be fair I have a weird graphics card that Windows hates too, a Radeon HD 2400 PRO AGP.

So first order of business was switching from the ATI binary driver to the open source VESA driver. There are no docs on this I could find anywhere; there’s no longer an xorg.conf to edit. I finally just used apt-get to uninstall xserver-xorg-video-ati; happily, Ubuntu is smart enough to drop back to the VESA driver if the ATI driver is not around.

The second problem is Unity, the fancy new GUI, doesn’t run on the VESA driver. Too much GL or something. The old UI is there but if you want Unity the solution for that is to install unity-2d, a simpler UI.

With that all done, things sorta work. As with every time I try to use Linux as a desktop, it was a disaster. I can’t really blame Ubuntu for not handling my weird graphics card well, but I can blame it for there being no clear path to diagnose and fix the mistake. Also I’d say unity-2d ought to be a default option, not some weird thing to install.

 

D3 scales and interpolation

D3 has a notion of “scales”, transformations of data from a domain to a range. Say your data is percentages (0% to 100%) and you want to draw them as bars of length 10-20. You can easily construct a linear scale to map your domain [0,100] to a range [10,20]:

var s = d3.scale.linear.domain([0,100]).range([10,20])
d3.selectAll("rect").data(data)
  .enter().append("svg:rect")
    .attr("height", s)

If that use of s seems magic, equivalents would be

    .attr("height", function(n) { return s(n); })

    .attr("height", function(n) { return 10 + 10 * (n/100) });

D3 provides various useful scales. Numeric scales like linear, log, and pow, also discrete scales like quantize and ordinal.

One thing you can set on a scale is the interpolate function. It’s invoked when mapping the domain to the range and lets you make the range be something other than the usual numeric range.

s = d3.scale.linear()
  .domain([0,100])
  .interpolate(d3.interpolateRgb)
  .range(["#ff0000", "#0000ff"])
s(0) == "rgb(255,0,0)"
s(100) == "rgb(0,0,255)"
s(50) == "rgb(128,0,128)"

There are pre-defined interpolation functions for numbers, colours, strings, objects, etc. I believe they’re also used by D3’s transition animations, specifically to automatically warp complex things like SVG paths from one shape to another.

The application of interpolation in d3.scale.linear.interpolate is pretty simple to follow:

  interpolate = d3.interpolate,
  i = interpolate(y0, y1);

  function scale(x) {
    return i((x - x0) * kx);
  }

In the linear.js code [x0,x1] is the domain, kx is 1/(x1-x0). [y0,y1] is the range. So the above code takes the input x, maps it to the interval [0,1], then applies cached interpolation function i(). By default that function is a linear interpolation in [y0,y1], but the developer can override it.

Building node without SSL

I’m trying to build node.js from source on Debian/wheezy. There’s an RPM but it’s two major versions behind. I got an error about SSL methods not being declared when compiling. No idea why Debian’s dev environment makes node’s configure think it can build SSL when it can’t (I have libssl-dev installed), but a quick workaround is buidling Node without crypto, via ./configure --without-ssl.

[74/75] cxx: src/node_crypto.cc -> build/default/src/node_crypto_4.o
/usr/bin/g++ -pthread -m32 -g -O3 -DHAVE_OPENSSL=1 -DHAVE_MONOTONIC_CLOCK=1 -DEV_FORK_ENABLE=0 -DEV_EMBED_ENABLE=0 -DEV_MULTIPLICITY=0 -DX_STACKSIZE=65536 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DEV_MULTIPLICITY=0 -DHAVE_FDATASYNC=1 -DPLATFORM="linux" -D__POSIX__=1 -Wno-unused-parameter -D_FORTIFY_SOURCE=2 -DNDEBUG -Idefault/src -I../src -Idefault/deps/libeio -I../deps/libeio -Idefault/deps/http_parser -I../deps/http_parser -Idefault/deps/v8/include -I../deps/v8/include -Idefault/deps/libev -I../deps/libev -Idefault/deps/c-ares -I../deps/c-ares -Idefault/deps/c-ares/linux-ia32 -I../deps/c-ares/linux-ia32 -Ideps/v8/include ../src/node_crypto.cc -c -o default/src/node_crypto_4.o
../src/node_crypto.cc: In static member function ‘static v8::Handle<v8::Value> node::crypto::SecureContext::Init(const v8::Arguments&)’:
../src/node_crypto.cc:101:29: error: ‘SSLv2_method’ was not declared in this scope
../src/node_crypto.cc:103:36: error: ‘SSLv2_server_method’ was not declared in this scope
../src/node_crypto.cc:105:36: error: ‘SSLv2_client_method’ was not declared in this scope
Waf: Leaving directory `/usr/local/src/node/build'
Build failed:  -> task failed (err #1):
        {task: cxx node_crypto.cc -> node_crypto_4.o}
make: *** [program] Error 1

mobile safari and viewport

Apple’s mobile browser is great, but the viewport meta tag is kind of a hash. There seems to be two conflicting ways to hint to the iPhone or iPad how big to draw things.

  1. width and height. Tells the browser this content is going to render best at a certain width, so render it to that size. width=device-width or width=320 is one way to tell the iPhone not to scale at all. width=600 or the like often solves the problem of stuff looking too small on the iPhone, while still letting it scale. If you set a small width the iPad will scale content up, making it bigger.
  2. initial-scale, minimum-scale, maximum-scale. Gives an explicit scaling factor. The user can override this (unless you disable it).

What’s confusing is if you set both a width and scaling behaviour: which takes precedence?

Mike suggested what seems to work well for maps is setting initial-scale to 1.0 and maximum-scale to 1.0. This keeps Safari from doing its own scaling on the page at all. Even better, when you rotate the device it doesn’t try to scale the width to match the old view; instead it just loads some stuff that was previously off-screen. The only drawback is this effectively sets the width to 320px on an iPhone, you no longer get any in-browser scaling.

What I really want is no scaling at all on the iPad, and 1.5 scaling on the iPhone. I can’t figure out a way to do that without changing the tags depending on what device loaded the page.

Map tile licenses

I’m trying to launch a map project that uses another site’s map tiles in Polymaps. Here’s links to licensing details for various tile options, along with my very cursory understanding based on my non-expert quick read of their licenses.

Google Maps API: various limits, the most important being you are required to use their Javascript library. Or so I’m told, I didn’t read the license to find the specific language.

Microsoft Bing Maps: you can use their web services with your own code, although the way the metadata service works means you may end up having to display some Microsoft branding, links etc. Education and non-profits seem to have pretty generous usage terms. Commercial use can also proceed without a license agreement, but limited to “500,000 transactions” per year. Beyond that you email them for pricing.

OpenStreetMap: It’s Creative Commons, Attribution ShareAlike. No requirements on access code or amount of traffic beyond their tile usage policy. What “ShareAlike” means for a map that uses OSM tiles as a layer is complex: see common license interpretations. The key language I noted was

If you overlay OSM data with your own data created from other sources (for example you going out there with a GPS receiver) and the layers are kept separate and independent, and the OSM layer is unchanged, then you may have created a collective work. ... If you have created a collective work, then only the OSM component of the work must be subject to the OSM licence.

CloudMade. Their map tiles are derived from OSM so are similarly CC-A-SA. They may have further restrictions in their ToS.

D3 selections

The core datatype in the D3 Javascript library is the selection. But what exactly is a selection? What is its type and how do we work with it? It’s possible to use D3 without really understanding what selections are, but it makes a lot more sense if you understand the core type.

D3 selection type

A D3 selection is an array of arrays of DOM elements. That top level array object also has extra methods defined on it, the D3 selection methods like append(), attr(), etc.  Both select() and selectAll() return a 2d array; the difference is that select() only returns the first of the matching nodes. Most of the time your Javascript code won’t ever iterate inside these arrays; D3’s methods themselves implicitly loop over the elements.

Sample document

The rest of these notes will work on a simple sample HTML document that contains two tables each of size 2x2 for a total of 8 td nodes.

<table id="table1">
  <tr id="tr1-1">
    <td id="td1-1-1">1-1-1</td>
    <td id="td1-1-2">1-1-2</td>
  </tr>
  <tr id="tr1-2">
    <td id="td1-2-1">1-2-1</td>
    <td id="td1-2-2">1-2-2</td>
  </tr>
</table>
<table id="table2">
  <tr id="tr2-1">
    <td id="td2-1-1">2-1-1</td>
    <td id="td2-1-2">2-1-2</td>
  </tr>
  <tr id="tr2-2">
    <td id="td2-2-1">2-2-1</td>
    <td id="td2-2-2">2-2-2</td>
  </tr>
</table>

A note on developer tools

D3 selections are basically just arrays and if you look at a D3 selection in a developer tool like the Google Chrome console it only shows the array. See line 2 below. But don’t be confused! The selection doesn’t show up as having a special type or representation, but it is special. It has extra methods assigned on it and you can inspect and call them:

>>> d3.selectAll("table")
[ Array[2] ]
>>> typeof d3.select("table").attr
"function"
>>> d3.select("table").attr("id")
"table1"

Getting a D3 selection

Where does a D3 selection object come from? The select() and selectAll() methods. Those methods return a selection matching the input parameter. Often the developer selects for strings, using the selectors we know and love from the CSS specification. Selectors are a powerful mini-language worth reviewing to get the most out of D3.

>>> d3.selectAll("table")
[ Array[2] ]
>>> d3.selectAll("td")
[ Array[8] ]
>>> d3.selectAll("#td1-1-1")
[ Array[1] ]
>>> d3.selectAll("#broken")
[ Array[0] ]

In addition to strings, select() and selectAll() also work with ordinary DOM elements returned by other Javascript APIs. This capability can also be useful inside D3: inside an iterator function like each() you can use it to elevate the DOM element passed in the this parameter back into a selection object so you can then modify it with D3 methods.

>>> document.getElementById("td1-1-1")
​1-1-1​
​
>>> d3.selectAll(document.getElementById("td1-1-1"))
[ Array[0] ]

>>> d3.selectAll("td").each(function() { this.style("font-weight", "bold") })
TypeError: Property 'style' of object is not a function

>>> d3.selectAll("td").each(function() { d3.select(this).style("font-weight", "bold") })
[ Array[8] ]

Using a D3 selection

Most of your work with D3 is getting a selection and then invoking methods on it. All selection methods except call are implicitly loops, they will operate once per element in the selection.  The methods attr(), style(), property(), text(), and html() allow modification of the selected elements. each() allows you to call arbitrary functions for each element; methods like attr() are implemented by calling each(). append(), insert(), and remove() allow elements to be added to the DOM. on() allows events to be bound to the selected elements.

Subselections

D3 allows you to create a subselection within a selection, to work on a subset of elements from an initial selection. Subselections allow like elements to be grouped so you can process your data in a structured fashion. (This also explains why selections are 2d arrays; they support the nesting). I haven’t needed to use subselections yet: the scatterplot matrix example shows their use.

>>> d3.selectAll("td")
[ Array[8] ]
>>> d3.selectAll("td")[0][0].id
"td1-1-1"
>>> d3.selectAll("table").selectAll("td")
[ Array[4], Array[4] ]
>>> d3.selectAll("table").selectAll("td")[0][0].id
"td1-1-1"
>>> d3.selectAll("table").selectAll("td")[1][0].id
"td2-1-1"

Data

The data() method allows data to be stored for each element in the selection. Data is stored in a __data__ property right on the DOM node. You should normally not access this property directly, but it’s helpful to understand how D3 keeps data associated with your document elements.

>>> d3.selectAll("td").data([1, 2, 3, 4, 5, 6, 7, 8])
>>> d3.selectAll("td").each(function(d) { console.log(d); })
1 2 3 4 5 6 7 8
>>> d3.selectAll("#td2-1-1").each(function(d) { console.log(d); })
5
>>> document.getElementById("td2-1-1").__data__
5

data() returns the updating selection; you can immediately use attr(), each(), etc after calling data().

>>> d3.selectAll("td").data([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>>    .each(function(d) { console.log(d); })
1 2 3 4 5 6 7 8
[ Array[10] ]

Note how the array returned by each() is length 10? We bound 10 data items to the selection, but we only had 8 matching td elements. The extra two new elements implied by the data are accessible as the enter selection. This enter selection only has append() and insert() methods defined on it; you cannot call attr(), etc until you create DOM nodes. There is a symmetric exit selection that has the full D3 selection methods, typically used for removing nodes from the DOM.

this in javascript

Trying to understand the this magic variable in Javascript. You’d think it’d be like self or the like in most OO languages. But Javascript is barely OO and everything is so dynamic, it’s confusing. Some useful references: Quirks Mode, MDC this.

My takeaway from reading stuff is that this is generally set to the object the function is defined on. If you’re saying foo.go(), then inside go() this will be set to foo. If you don’t know what object you called a function on, say because you have a naked go() in your code, then this is probably bound to the global window object.

The usual this behaviour can be overridden in various ways. Both call and apply let you invoke a function and explicitly provide a value for this. D3’s each() function does this so that inside each, this is bound to the DOM node for the specific element being manipulated. There’s also a new ECMA function bind that lets you create a function with a new value automatically used for this.

I’m still a bit fuzzy on the mechanics of how this is assigned, in particular when you copy a function from object A to object B. In general this seems to be set dynamically at the last moment before the function is invoked, so it generally picks up the value A or B depending on how the function was invoked.

Compression

My map contains a list of 3000 weather stations. The current JSON file driving the map contains lines like “KSQL”:[-122.25,37.52,”San Carlos Airport”]. It’s 137k, or 53k gzipped. That’s 46 bytes / station, or 18 bytes/station gzipped.

I’d like to add data to this file: the probability of wind coming from each of 12 directions. Probabilities can be scaled to [0-99] so the naive text encoding (32,4,12) is 24-36 bytes. That adds 50% to my file length. I actually tried it: the file becomes 210k, 80k gzipped.

I could do a more compressed encoding, say ASCII characters from 35 to 126 for 92 distinct values in one byte with no JSON encoding challenges. That gets me to 12 bytes / station, the whole file should be 160k.

My original plan was not to ship the wind probabilities at all, but render them server-side as PNGs (see previous posts). But each PNG is about 1k compared to 12 bytes for the wind data. And while bltting a PNG ought to be faster for the browser than drawing a bunch of SVG, it may not be significantly faster. Particularly since each PNG would need to be fetched as a separate file and it’s being rendered as an svg:image anyway. Need to test.

Optimization

For my wind visualization I have a bunch of 2-3 megabyte text files containing a lot of METARs. I parse them to get the winds data, then do some statistics on them to produce a rollup.

Doing all this work in one swoop takes 5.3s for a smallish file (1.5 megs, 24000 lines).

Parsing the file and writing it to CSV takes 4.6s. Reading the CSV in and doing the rollups takes 1.4s. So I’ve added about 0.7s overhead in splitting the two steps thanks to the intermediate file. OTOH I should really only need to generate that CSV once.

Once again I learned the hard way that iterating line by line through gzip.open() is really slow; way faster to read the whole file in to RAM, a cStringIO if necessary. Terrible buffering in Python’s library.

I’m beginning to regret not just loading all this crap into a relational database.

 

Headless SVG rendering part 2

I revisted headless SVG rendering and decided to stick with PhantomJS since I already have it working. It’s rendering text poorly and path strokes not at all, probably fixable with some upgrades that are inconvenient in Debian. But I can work around that for now.

Scripting PhantomJS turns out to be pretty easy. Here’s the Javascript program I use to drive it:

if (phantom.state.length == 0) {
    phantom.state = "rasterize";
    phantom.viewportSize = { width: 64, height: 64 };
    phantom.open("vis-phantom.html");
} else {
    phantom.render("out.png");
    phantom.exit();
}

Unfortunately the input and output filenames are hard-coded. Phantom has command line argument support but I can’t figure a way to get that all the way into my HTML file (to load a specific script), so I just went with a hardcoded input file named data.js.

Here’s my shell script to render a PNG, crop it, and optipng crush it. The crop shouldn’t be necessary, but for some reason I’m ending up with 3 pixels below my SVG element.

set -e
# Render a wind rose image for the given datafile
input="$1"
output="${1%.js}.png"

# remove old crap
rm -f data.js out.png cropped.png "$output"
# Symlink the data to the expected place
ln -s "$1" data.js

# Render, crop, and crush
phantomjs/bin/phantomjs render.js
convert out.png -crop 64x64+0+0 cropped.png
optipng -force -quiet -preserve -out "$output" cropped.png

# clean up
rm -f data.js out.png cropped.png

It takes about 300ms to render a single image for my simple SVG based graphics.

Samba: get rid of stupid executable files

Editing files on Windows has an annoying habit of making them show up +x on Unix. Windows doesn’t have an idea of an execute bit, so some ambiguity is expected, but still. Turns out the real culprit is the map archive configuration option. It’s on by default, which means the Archive bit in Windows is mapped 1:1 with the U+X bit on Unix. That’s really stupid; Windows apps set the Archive bit willy-nilly (hello, Notepad++) and it gets annoying, particularly with git tracking file modes. So configure Samba with “map archive = no” for your fileshare and life gets better.

 

forking a branch on github

I’m trying to submit patches to https://github.com/mbostock/d3. Only what I want to patch is in the gh-pages branch, a special magic branch on github that is published as a website. Forking and modifying a branch is confusing if you don’t understand git. Here’s what works in my shell, after forking the repository:

# Get a copy of the forked repo
$ git clone git@github.com:NelsonMinar/d3.git
Cloning into d3...

# Link in the upstream repo you forked
$ cd d3
$ git remote add upstream https://github.com/mbostock/d3.git
$ git fetch upstream
From https://github.com/mbostock/d3
 * [new branch]      gh-pages   -> upstream/gh-pages
 * [new branch]      master     -> upstream/master
 * [new branch]      mbostock-master -> upstream/mbostock-master

# Create a local branch, somehow linked to the upstream's branch
$ git checkout -b gh-pages origin/gh-pages
Branch gh-pages set up to track remote branch gh-pages from origin.
Switched to a new branch 'gh-pages'

# Make your changes and commit them locally
$ ed README.txt
$ git commit -a -m testing

# Push to your fork on github
$ git push
To git@github.com:NelsonMinar/d3.git
   0d1679a..d351228  gh-pages -> gh-pages

The magic step is that checkout line. Other similar things like git branch gh-pages; git checkout origin/gh-pages don’t work and you can end up in weird states like “You are in ‘detached HEAD’ state.” I don’t really understand what all the working command is doing (I’ve got Matt to think for the code to copypasta) but I’m hopeful after reading the git docs on branches and remotes maybe it’ll make more sense.

Headless SVG rendering

I’m doing an S3/SVG visualization project and want an easy way to generate 3000 static images with a script. I need a headless SVG renderer. Mike suggested a couple of options: Rhino + Env.js + Batik, or maybe using node.js instead of rhino. Apparently the Protovis community does this; need to delve in their mailing list for examples.

PhantomJS happened to float across today, so I tried it out. It’s WebKit based instead of Mozilla based. It was pretty easy to get going. I had to install libqt4-dev libqt4-webkit on my Debian system to build it. I also learned it’s not really headless, requires an X server, so I installed xvfb and ran it via “Xvfb :1”. With all that in place the basic PhantomJS works. Including rasterizer.js, which loads an arbitrary URL and renders it.

To run it:

$ Xvfb :0 2> /dev/null
$ export DISPLAY=:0
$ phantomjs rasterize.js vis-phantom.html out.png

My visualization didn’t work. First I had to remove the Ajax calls from it and statically load the data. (May not be strictly necessary, not sure). Second I had to set the background to white; the default background in qt4-webkit is transparent, which is actually pretty useful. With those changes my rendering sort of worked, but the font rendering is ugly and none of my stroked lines are visible. I’m using libQtWebkit-4.6.3; apparently 4.7 may fix the stroke problem.

I think I could massage this into something usable, but I’ll probably investigate the Rhino/Batik solution or something next.

WingIDE 4.0 problem with Python 2.7.1 on Windows

My Python IDE of choice, Wing, has a capability to start the debugger when an exception is raised, but only if it “appears unhandled”. It’s great but a little delicate. It broke entirely on my recently, all exceptions appeared unhandled. I narrowed the problem down to running in Python 2.7.1. Python 2.6 works fine. The workaround Wing recommended was setting the debugger to break when exception is printed.

Javascript dictionary key types

In Javascript, the dictionary type coerces its keys to Strings:

z = { 3: "three", 4: "four" }
for (var x in z) { console.log(typeof x); }

string

This sort of makes sense because dictionaries are really just Javscript objects, and objects are typically accessed by strings. Ie: z.foo is the same thing as z[“foo”]. Worth noting that z.3 doesn’t work, though. It gets spookier when you use null:

z[null] = "foo"

for (var x in z){ console.log(x, typeof x); }
3 string
4 string
null string

Maybe it wasn’t wise to use integers and null everywhere as keys in my JSON dictionaries. In fact the JSON spec says keys have to be strings, and the Python JSON library was already serializing my keys as strings (with None mapped to “null”). Now I know.

D3 and IE9

IE9 is out, and Microsoft finally supports SVG. Early testing with D3, Mike’s new Javascript library good for doing visualizations, is encouraging. All his examples work. My own code worked once I put <!DOCTYPE html> at the start to convince IE not to use quirks mode.

gzip encoding, Chrome dev tools bug

Apache 2 on Debian does not gzip encode by default. Enabling it is as simple as doing a2enmod deflate, then restarting Apache. The default configuration is fairly conservative; if you just want to compress everything modify defalte.conf to say “SetOutputFilter DEFLATE” instead of adding a few MIME types.

Google Chrome has bug 40502 where it appears files aren’t being compressed even when they are. Serving JSON files, if they were smaller than 190k dev tools showed Transfer was much smaller than Size, indicating compression. Bigger files looked uncompressed. But checking with WireShark they were actually comprssed, dev tools just lied. Apparently Apache2 decided to use chunked encoding for the larger files and Chrome has as bug with that.

 

using git on Windows via SMB

I keep my source code on a Linux machine, but I develop on Windows. The cross-platform thing is a nuisance. I mostly prefer to work in the Unix way, and make Windows cope.

msysgit seems to be the Windows git client of choice. (Cygwin is too foreign an environment). To make it play nicely with Unix systems:

  • core.autocrlf=false
    Don’t ever modify line endings, just accept what’s there. Every Windows editor I use can handle Unix line endings just fine.
  • core.filemode=false
    Don’t mess with file modes. Works around the problem that Samba doesn’t really handle Unix file modes right, particularly +x.  Avoids the problem of “old mode 100755 new mode 100644”.  This probably means you can’t meaningfully set file modes from Windows.
  • gui.encoding=utf-8
    Not strictly a Windows thing, but a good idea.

These can be set via the msysgit bash shell with “git config core.filemode false”. You can see your settings with “git config -l”. There’s something confusing I don’t understand about system/global/local settings that I’m ignoring.

Very simple python logging

I do a lot of quick and dirty Python scripts. One thing that bites me is trying to print useful data on exceptions, where the useful data contains non-ASCII and I’m trying to write it to sys.stderr and I get an exception in my exception handler, killing my program:

try:
    process(inputString)
except:
    sys.stderr.writeln("Error with input %s" % inputString)

UnicodeEncodeError: 'ascii' codec can't encode character u'\x81' in position 0: ordinal not in range(128)

Very irritating. One workaround is to use Python’s logging package. It’s a hugely complex configurable beast, but the default config is useful: print all warnings and above to stderr. And it handles Unicode sensibly.

>>> logging.warning('u"\x81"')
WARNING:root:u"▒"
>>> logging.warning('u"\u2022"')
WARNING:root:u"\u2022"

Not sure what it’s doing; maybe trying Latin-1 and escaping anything else? I don’t care if the output is mangled as long as it doesn’t kill my program.

Python zipfiles: don’t read a line at a time

readline() inside a Python zipfile is slow. It’s much much faster to read the whole thing into memory once, then scan.

Compare:

fp = zipfile.ZipFile("foo.zip").open("data.txt")
# Iterate a line at a time
for l in fp:
    if l.startswith("FOO"): print l

# Read the whole file into memory, grep
regexp = re.compile(r'^(FOO.*)$', re.MULTILINE)
data = fp.read()
if m: print m.group(1)

I’m not surprised that the second style is faster, but I’m surprised how much. Some 25 times faster both on my test case (0.5s vs 12s) and over 3.6 gigs of real data (8 minutes vs 200 minutes). Obviously reading the whole file first takes more RAM, but in my case the files are only 500k each.

A quick profile suggests zipfile spends a lot of time calling next(); maybe it’s doing work a character at a time? Issue 7216 suggests there’s a 100 byte buffer at work; yuck! Fixed in 2.7 or 3.x or something.

What’s new since Python 2.2?

I learned Python when 2.2 was the new hotness. Since then I’ve picked up a lot of newer Python features but never really sat down to think of all the new language and library capabilities the system had. Here’s a list of some highlights in the 2.x releases I picked up off the what’s new pages. 2.6 (3.0) means the feature is available in 2.6 as a backport from 3.0. 2.6f (3.0) means the feature is only in 2.6 as a __future__.

Language

  • 2.3, 2.4, 2.5: Generators. Generator expressions. send(), throw(), close().
  • 2.4: Function and method decorators. 2.6 (3.0): Class decorators
  • 2.5: Conditional expressions (“foo” if x == 3 else “bar”)
  • 2.5: Absolute imports (default in 3.x)
  • 2.5: try/except/finally unified
  • 2.5, 2.6: with statement (this one is important; need to use it more)
  • 2.6 (3.0): except ExceptionClass as variableName:
  • 2.6 (3.0): strings are unicode. bytes type.
  • 2.7 (3.1): dictionary and set comprehensions

Libraries

  • ???: codecs.open() as a way to be explicit about character encoding
  • 2.3, 2.4: Sets. 2.7 (3.1): set literals
  • 2.3: Universal newline mode for files
  • 2.3: logging
  • 2.3: CSV files
  • 2.5: functools.partial() for closure-like partial function application
  • 2.5: ctypes, quick access to shared libraries
  • 2.5: ElementTree (xml.etree)
  • 2.5: sqlite3
  • 2.6f (3.0): str.format(). 2.7: autonumbering
  • 2.6f (3.0): print() as a function
  • 2.6 (3.0): abstract base classes, particularly for collections and numbers
  • 2.6: json (via simplejson)
  • 2.7: collections.OrderedDict
  • 2.7: argparse
  • 2.7 (3.1): dictionary views
  • 2.7: collections.Counter (replaces my accumulator.py)
  • 2.7: unittest improvements, backported to 2.4 as unittest2

Actually using some of these features is harder: Google AppEngine is stuck at 2.5 and Debian is stuck at 2.6. And of course 3.2 is the new hotness now, but largely not usable for ordinary user code.

Calculating the difference between two GPS tracks

When comparing my Bad Elf GPS track to my AMOD track, I wanted some mathematical calculation of the difference. I don’t really know even what that’d mean, but matt_c pointed me to some ideas:

  • Hausdorff Distance (PostGIS, GEOS, explanation). My quick read suggests this will calculate the maximum divergence between the two tracks, not the sum of many little errors.
  • Fréchet distance. “The Frechet distance is a measure that takes the continuity of shapes into account and, hence, is better suitedthan the Hausdorff distance for curve or surface matching” (source).

This sounds complicated.

 

Bad Elf / MotionX technical notes

I got a Bad Elf GPS for my iPhone. Some notes on using it with MotionX to record tracks:

  • It seems to work better in airplane mode. First time I tried it, I never got < 50m accuracy, maybe it was still using wifi or 3G positioning? Airplane mode guarantees the only location fix is the Bad Elf GPS.
  • MotionX seems to be the best GPS tracking software. The UI is awfully non-Apple, but it seems to track well.
  • I consumed about 60% of my iPhone 3GS battery creating a 2.5 hour long track. GPS had a good view of half the sky (on the glareshield of the plane), airplane mode, doing nothing but running MotionX. I put it manually in Flying mode.
  • The 2.5 hour track was 260kb of GPX, 132kb of KML.
  • The MotionX overview of the track says it’s 191.8nm, 2:29:13 elapsed time, avg speed 77kts, max speed 152kts. My (known buggy) calculation on the AMOD log was 196.9nm, 2.3h elapsed, 1.9h in motion.
  • The Bad Elf + MotionX track looks right. I overlapped it with the AMOD log track and they were mostly on top of each other. Tracks diverged by as much as 16m. Spot check on one specific divergence and the AMOD said it has 10 satellites and HDOP of 1.1, a very accurate fix. Hmm.
  • GPX file contains a list of fixes: (lon, lat, ele, time). Once in motion it’s one fix every 2 or 3 seconds. The timing discrepancy doesn’t seem to just be a rounding error; I’ve got a sequence of 20:07:13 20:07:15 20:07:18 20:07:20 20:07:22 20:07:24 20:07:27.
  • KMZ archive contains a “doc.kml” whose main contents are a LineString with (lon, lat, ele). No timestamps. The KML is rendered without altitude by default in Google Earth but you can change the properties to show an extruded track, elevation profile, etc. It appears the elevation is clamped to 0′. It’s not DEM corrected, just a hard-coded 0?
  • KMZ archive also contains an extra file “raw.xml” which seems to contain raw data, not relevant to Google Earth. But lots of extra data from MotionX! It contains two sections. The XML has “locations”: a list of (time, activeTime, distance, stopped, lat, lon, alt). Time looks accurate to 1ms. activeTime and delta are just deltas from previous locations (it has both 2 and 3s activeTimes)  Stopped must be MotionX’s guess of whether we’re moving? The XML also has “recordingSnapshots”, which look to be 1 minute rollups of distance and altitude.
  • The email also contained a Google Maps link, which incorporates the same KMZ archive as was mailed to me (including raw.xml) served for 6 months from share.gps.motionxlive.com.
  • MotionX does not seem to record any measure of GPS fix accuracy. Too bad, that data is available in the Apple API. It may be smart enough to automatically filter out fixes with bad data.

I’ve been meaning to measure Bad Elf + GPS when the phone isn’t moving. My first attempt recorded no track, I think because it was clever enough to not record when not moving. Need to investigate Settings / Global: Accelerometrics Assisted GPS, Accuracy Filter.

Coordinate reference systems and projections

I get confused as to the difference between coordinate reference systems (CRS) and projections. This overview clued me in some, but I still might be wrong. Here’s my current understanding.

 

CRS are all about spherical coordinates, naming points on the sphere. When I say “San Francisco is at 37.75, -122.45”, what I’m saying is it’s 37.75 degrees north of the equator of the sphere and 122.45 degrees west of the prime meridian through Greenwich. Points are defined in spherical geometric relation to absolute, fixed locations on the earth.

Only it’s not that simple. First, the earth isn’t a sphere, it’s squashed, and CRS are defined relative to a specific datum that has some oblate spheroid shape with complex geometry. Second, the prime meridian we most commonly use doesn’t go through Greenwich anymore, it goes about 100m east.

The most common CRS in use is WGS84, the basis of GPS navigation. WGS84 itself changes as measurements get more accurate, so the specific thing we all use is WGS84 (G1150). (I’m unclear on how measurement changes are managed; the earth itself is moving, too, making absolute location a slippery concept. See also ITRF2000) The other CRS I’m familiar with from NACO aviation charts is NAD83 (CORS96). It agrees with WGS84 to within two meters and I believe NACO advises treating them as interchangeable. In practice I don’t see any useful reason to do work in anything other than WGS84, unless importing data from some other source that used a different CRS.

 

Projections are all about planar geometry, warping a spherical map to a flat surface.  There’s a large variety of map projections in common use. Mercator is most popular for casual maps and shows up frequently online because it’s what Google Maps (and all slippy maps?) use. Lambert Conformal Conic shows up in NACO sectional charts and USGS sectionals; it’s sort of like a but the projection is parameterized to have the least distortion between two chosen latitudes. Also Lambert Conformal has the nice property that a straight line drawn on the map is very close to a great circle route (shortest distance); handy for airplane navigation.

In maps showing a relatively small area of the Earth, the differences between projections are relatively small. I think I’m inadvertently benefiting from this in my approach plate georeferencing experiments. I’m just treating the plate as if it were drawn in a mercator projection and it looks about right.

Extracting images from SWF files

I wanted to try to get at an image hidden inside an SWF file, a Flash game on Armor Games. Google searches for “SWF extract” and the like offer a lot of unsavoury software, but a quick search of Debian turned up SWFTools, a GPL toolchain for making and unmaking SWF files. Compiling on Linux was as easy as ./configure; make

To actually extract the images, you have to find their IDs first, then extract them one by one. The compiled SWF file doesn’t seem to keep the source filename, so you have to hunt by size or the like.

$ swfdump foo.swf | grep image 
[024]     14446 DEFINEBITSLOSSLESS2 defines id 1725 image 660x561 (32 bpp)
$ swfextract -p 1725 -o 1725.png foo.swf
$ ls -lg 1725.png
-rw-r--r-- 1 nelson nelson 14877 Feb 19 14:04 1725.png

That example is for a 600x561 lossless image, 14446 bytes long, with ID 1725. I didn’t see any quick way to get swfextract to just extract all the images, although of course it’d be easy enough to write a shell script to do it.

Javascript closures gotcha with loop variables

The way Javascript scopes “var” in loops and how it interacts with closures trips me up every time I go back to writing Javascript code. Here’s a fleshed out example that shows the confusion.

// Demonstrates using closures to capture the value to do what you meant. See also
//   http://calculist.blogspot.com/2005/12/gotcha-gotcha.html
//   http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/

var data = ["a", "b", "c"];
var wrongFunctions = [];
var rightFunctions = [];

function load() {
  console.log("Creating functions");
  for (var i = 0; i < 3; i++) {
    // X will be set to "a", then "b", then "c". But at what scope?
    var x = data[i];

    // The naive way to construction a function that returns X
    // Will not work: X is scoped to the function load() and
    // is being modified in the loop
    var wf = function() { return x };

    // A more complicated way to make a function that returns X.
    // The function execution creates a closure
    // that captures the value during the loop
    var rf = function() { 
      var t = x; 
      return function () { return t };
    }();

    // While the loop is executing and we're building functions,
    // the output of wf() and rf() will match data[i]. No problem!
    console.log ("  ", x, wf(), rf());
    // output is "a a a", "b b b", "c c c". Everything looks great!

    // Let's store both functions away, what could go wrong?
    wrongFunctions.push(wf);
    rightFunctions.push(rf);
  }
}

function play() {
  console.log("Running stored functions");
  // Let's loop through and call our stored away functions
  // and see what happens
  for (var i = 0; i < 3; i++) {
    console.log("  ", data[i], 
        wrongFunctions[i](), rightFunctions[i]());
  }
  // output is "a c a", "b c b", "c c c".
  // wrongFunctions were indeed wrong.
}

load();
play();

Slippy map coordinates

Polymaps has the ability to easily pull in raster tiles from various sources to make Slippy maps. I have code that lets me use tiles made by Google, Cloudmade, Bing, GDAL’s tile script, even Minecraft. I have no idea how it works, though. The underlying thing I don’t understand is Polymaps’ internal coordinate representation. Here’s an example, for a map tile centered on San Francisco.

This tells me Polymaps is natively using Google’s coordinate system. TMS is similar but numbered differently, here’s my cargo cult code to work with it. Mike tells me 1 << c.zoom is the number of tiles at the given zoom level, which explains why it’s used as a modulus everywhere.

    // Set X to c.column, but wrapped around in the range [0, numTiles)
    var x = c.column % (1 << c.zoom);
    if (x < 0) {
      x = x + (1 << c.zoom)
    }
    // Set Y to numTiles - c.row, to account for TMS doing lat backwards
    var y = (1 << c.zoom) - c.row - 1;
    var url = "http://example.com/tiles/" + c.zoom + "/" + y + "/" + x + ".jpg";

More info: interactive coordinate exploration tool, Google docs, OSM / TMS docs.

Map result

Below is the result of my map experiments: the track of a flight with Ken flying practice approaches at Salinas overlayed on top of two approach charts and the Google Terrain base layer. It’s a bit of a jumble.

 

  • Transparent brown line: flight track
  • Black scratchy lines: approach chart
  • Brown terrain contours: approach chart
  • Green terrain: Google maps

What I’m really trying to highlight is the juxtaposition of the GPS track to the black approach path on the procedure plate. The other stuff is context, or noise. It’s less confusing if you only draw one approach chart, not two. Making parts of the approach plate transparent is a big help too; it’d be nice to eliminate the terrain, etc entirely. Maybe just let the black lines come through.

 

More georeferencing notes

I updated Quantum GIS to 1.6.0. It claims some improvements for georeferencing. I also learned better how it works.

Transformation Types are documented in the Quantum GIS manual. The docs suggest Polynomial 3 or Helmert are the best choices. Polynomial 3 is a nonstarter since it requires at least 10 GCPs and Helmert produced an oddly rotated image that was not correct.  Linear, Polynomial 1, Projective, and Thin Plate Spline all produced very similar results. Linear isn’t even a proper transform, really, but it seems close enough for my purposes. I’m shooting in the dark here, not knowing how the source NACO plates are projected, but at this scale and for my purposes any errors are not too big a deal.

The Target SRS you set in the Georeferencer is just an annotation, it doesn’t magically cause some warping. I’d tried setting it to EPSG:900913 for the Google (scale: 1 = 1m or something) but was typing latitude and longitudes in the tool (scale: 1 = 1 degree). Works better if I set the Target SRS to EPSG:4326 for WGS 84, produce a GeoTIFF, then later warp the image to Google mercator.

Raster / Warp will let you do the warping to Google. All it’s doing is calling gdalwarp, something like gdalwarp -s_srs EPSG:4326 -t_srs EPSG:900913 -r cubicspline -of GTiff input.tif output.tif. I wonder if this is really even warping anything or it’s just rescaling?

Bottom line:

  1. Draw 4 or so georeferencing control points on the chart. Type latitude and longitude.
  2. Set Transformation Settings to Polynomial 1, Cubic Spline, LZW, EPSG:4326.
  3. Warp the image to Google mercator

Georeferencing approach plates

I’m taking a crack at quick and dirty geo-referencing of NACO approach plates for pilots. They come as PDF images, ungeoreferenced, but they contain points with precise latitude and longitude you can align by hand. The result won’t be accurate, certainly not for navigation, but maybe it’s good enough. Here’s some notes on what I’ve tried.

  1. Download a PDF plate from NACO.
  2. Convert it to PNG via pdftoppm -r 300 | pnmtopng -comp 9. The result file will be 1613x2476, about 700k.
  3. Fire up Quantum GIS (I’m using 1.5.0). Launch Plugins/Georeferencer/Georeferencer.
  4. File /Open Raster to load your PNG.
  5. Zoom in and add some georeference points via Edit / Add Point. I picked a few intermediate GPS fixes on a GPS approach and looked up their coordinates via fltplan.com. Don’t forget that X is longitude, and is negative. How many points? 2 is minimum, I entered 4. It all depends on what projection the NACO plates uses, and I don’t know what that is.
  6. File / Save GCP Points, to save your hand edited work.
  7. Settings / Transformation Settings. Lots of options I don’t understand. Target SRS is EPSG:4326 for WGS84. LZW compression gets the filesize from 12 megs to 2 megs.
  8. Look at the table of points below the view of your map. The last 3 columns (dX, dY, residual) are some sort of measurement of the error / warping requirements.
  9. File / Start georeferencing to generate the georeferenced TIFF output. Takes a few seconds.
  10. gdalinfo on the resulting .tif file to see whether the result looks reasonable.
  11. Close the georeferencer plugin.
  12. Start a new Quantum GIS project. Settings / Project Properties to set the CRS to EPSG:4326.
  13. Layer / Add Raster Layer to load the georeferenced TIFF. It should show up in the window, with coordinates of lat/long and a scale in the vicinity of 1:300,000.
  14. Add more layers to juxtapose other data on top of the georeferenced plate. State boundaries are helpful for getting oriented, I also overlayed a GPS flight track.
  15. The NACO plate background is RGB 236, 236, 236. You can make that transparent with the Transparency properties of the plate layer, adding a band for just that one RGB value with 100% transparent.

One thing I haven’t figured out how to do in Quantum GIS is draw my plates on top of some reasonable map, like Google terrain maps. I can load Google maps via the OpenLayers plugin but the coordinate system those maps use is something screwy with X/Y in the hundreds of thousands. I’m not even sure Quantum GIS will warp raster layers on the fly, nor have I figured out what target SRS I should be emitting to be in the same format.

My real goal is to end up loading this stuff in Javascript, with Polymaps.

Spot XML data

I got a Spot for Christmas. In addition to emergency use they have a tracking option where it records your position via satellite every 10 minutes, live. The website is awful and they don’t keep your data very long, but the data is there. And they have an API of sorts. Related search: [findmespot completexml]. Some notes:

  • You can get an XML view of a public shared page by going to a URL like http://share.findmespot.com/messageService/guestlinkservlet?glId=NONCE&completeXml=true. The NONCE is the same blob that’s in the glId tag in the public shared page.
  • Data comes in a custom XML format. It’s pretty simple, each message is an XML blob with a latitude, longitude, and timestamp (in some random timezone!). Also some other junk.
  • The data is cached and only updated every 15 minutes. I’ve been told there’s more latency than that.
  • The shared page only shows data for the last 7 days.
  • Spot keeps your data for only 30 days. There’s also a manual download option.
  • Spot has a fancy site for hosting trip diaries at http://www.spotadventures.com. It includes KML and GPX downloads, photos, notes, etc. It looks like a pretty complex and featureful product with very few users.

I haven’t found any sort of hacker community for Spot. There is at least one third party service, though: Spotwalla.

Sort of related: Spot’s new system includes a “Type & Send” feature where you can send arbitrary 41 character messages via the satellite network. They charge $0.10/message in bulk.

Usenet encoding technologies

Back in 1993 I ran a Usenet server. Usenet’s mostly dead now but there’s a lively trade on  Usenet still in pirated media, particularly pornography. The challenge is posting a 1 gigabyte .AVI file in a medium that’s limited to small text files. Here’s some of the tech in use these days:

  • nzb, a metadata file for downloading a large file spread across multiple posts. It serves a function analagous to .torrent files in BitTorrent; doesn’t contain any content, but describes content. There are Usenet search engines that return NZB files, you can then take one to download the actual release off your favourite NNTP server.
    An NZB file is an XML document that describes a set of files which, when combined, make the release. Each file is described by a Usenet group and a list of segments. Each segment is a single Usenet message, named by Message ID. (Note: you can’t create the NZB file until after all the message parts have been uploaded).
  • rar, a compression format. It’s like zip, but tighter. Rar also does multipart well.
  • par2, an error correcting code format. Sort of the opposite of compression; transmit redundant data so a large archive can be rebuilt even if a few little pieces are missing.
  • uuencode, the historical encoding of binary data for Usenet. It’s a base 64 encoding with some very primitive file wrapper stuff. Still in use.
  • yEnc, the modern encoding of binary data for Usenet. It’s a full 8 bit encoding with escaping for a few characters (NULL, LF, CR, =). It also has a simple file wrapper and the ability to split a file amongst multiple messages. yEnc seems like MIME-lite, not sure what problem it solves that MIME can’t do.
  • sfv files are checksums on other files, used to verify your parts.
  • nfo files are text files (well, ansi graphics), typically a README from the release group.

I took a close look at a single NZB for a 300MB AVI file. Here’s what it contains:

  • 15 files: an SFV, a PAR2, 6 .RAR parts, and 7 PAR2 pieces.
  • Each RAR part is 50 megs and consists of 201 segments of length 249600.
  • The encoding makes each RAR file 70 megs on the server. Last chunk is smaller, total RAR text size is 410MB.
  • The PAR2 chunks total another 40MB.
  • It’s roughly 450MB to post a 300MB AVI to Usenet, or 50% overhead.

Here’s some Windows software I found useful:

  • GrabIt, a free NNTP client that’s good at downloading large binaries. The client is free and will download any NZB you give it, but they really want you to pay $25/year to use their NZB search engine.
  • QuickPar takes a PAR fileset and assembles the single file out of its components.
  • YEnc Power Post seems to be what people posting to Usenet use, but I can’t find a canonical linkf or it I trust.

What I’m missing is a reliable, free NZB search engine. There’s a variety of for-pay options of varying levels of sleaziness. binsearch.info is promising.

Short names for lat/long points

I want short names to refer to a specific latitude/longitude. Mostly so I can type them easily into an aviation GPS. For my purposes I need accuracy of about 1 mile, so 1 minute or .01 degree. I only need coordinates valid in the continental US, bounded roughly by 20, -125 to 50, -65. Some options, with the encoding for San Francisco (roughly at 37.75, -122.34).

  • 377512243. Lat/long base 10. 9 characters per location, and dead-ass easy to understand.
  • 9q8yvv. Geohash, a hierarchical base 32 encoding. 6 characters per location. See here for visualization.
  • KO46D. “Grid Fixes” from FltPlan. 5 characters per location. Can’t find documentation but it seems to have a resolution of 10 minutes latitude, 1 degree longitude. Not really accurate enough.
  • CM87SR. 6 characters per location. Grid Squares, aka Maidenhead Locator System, a ham radio thing, here’s a map view. Accurate to 2.5′ latitude and 5′ longitude, or roughly 4 miles, so not good enough for my purposes. There is an 8 character extended locator option.
  • ?????. Perfect rectangular coding, base 32. 5 characters per location. Need (50-20)*60 = 1800 = 11 bits of latitude, and (125-65)*60 = 3600 = 12 bits of longitude. 23 bits can be encoded in 5 characters in a base 32 representation. A base 52 representation would get it down to 4 characters.

I think if I were actually building this I’d probably go for Geohash. It has a nice property that you can specify arbitrary precision, then lop characters off the right to make a shorter code that’s less specific.