Some Bits: Nelson's log

10 posts in February 2011

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.