Some Bits: Nelson's log

16 posts in July 2012

Artisinal integers

Mission Integers and Brooklyn Integers are hipster web services that generate unique integers. Cleverly, they cooperate so the integers are unique across both sites. They did it the easy way; Mission returns even numbers, Brooklyn returns odd ones. I wanted to add a third site but there’s no way to do that, they’ve claimed all of the integers already.

So... can you generate integer sequences such that there can be an infinite number of generators with no collision? Supporting any predetermined number N of sites is easy; have site S generate s + n, s + 2n, s + 3n, s + 4n. But what if you don’t know N ahead of time? Yes, with maths!

Let’s say the Nth number that site S generates is the pair (S, N). We need an algorithm that creates a bijective mapping between (S, N) and the integers. Ie, for the current setup, Mission, even numbers, is site 0. Brooklyn, odd numbers, is site 1. The algorithm for number (S, N) is currently return n*2 + s

The trick is creating a bijection from the set of all integers to the set of all pairs of integers. I remember from college math this is possible (the cardinality of the set of all integers Z is the same as the cardinality of the cross product ZxZ) but I’d forgotten the constructive proof. Happily, Wikipedia remembers: something like the Cantor pairing function. http://en.wikipedia.org/wiki/Cantor_pairing_function

And the function for (s, n) is...

return ((s + n) * (s + n + 1))/2 + n

The picture is the useful intuition; basically you’re laying the tuples down on a square, then counting off cells.<

This kind of bijection comes in handy as a way to code large 2d spaces into 1d. I feel certain there’s an application for maps.

Here’s my implementation.

The drawback to this approach is the size of the Nth integer is O(N²). Mission integer 18,225,714 is 41,522,085,907,653 or about 2⁴⁵ in the cantor numbering.

See also Part 2

OpenPaths passive location tracking

There’s a bunch of passive location trackers out there. Mobile phone clients that watch your location all the time and upload reports of where you are every 15 minutes, hour, whatever. Three I’ve tried are OpenPaths, Google Latitude, and Geoloqi. Of the three I like OpenPaths the best. It’s by Jer Thorp, a very smart information visualization guy. It’s simple and does its thing well and nothing more. And it has the right goals and attitude. Google Latitude is opaque, corporate, and seemingly abandoned; it also has a terrible UI that only lets you get 30 days of data at a time. Geoloqi is nice but the tracker is more of a demo for their very capable platform. So OpenPaths is the one I’ll keep around.

 

That’s about three months of data, my travels around California. I like how the data shows all the different roads I’ve drive on my trips out of SF, particularly highway 12 across to Lodi. The couple of points east of Concord make me laugh, that’s when I was in Ken’s airplane and forgot to turn off my cell phone.

I’m not sure what I will end up doing with this data, but I intend to keep collecting it.

Simple XMLHttpRequest

I’ve never written my own XMLHttpRequest; I’ve always used jQuery or D3’s libraries. I had some sneaking suspicion one could do better than those wrappers in a modern HTML 5 setting, particularly for error handling, so for this project I wrote my own XHR code.

And turns out, nope, I’m not doing anything clever that those other libraries doesn’t. I’m doing less, really, my error handling is just as bad and there’s some clumsy stuff. Also this code only handles a really well behaved service; hasn’t been battle hardened against perverse replies or old browser versions. It does work for me though.

// Make AJAX calls, assuming JSON replies
function jsonRequest(url, callback) {
    console.log(url);
    var req = new XMLHttpRequest;
    req.open("GET", url, true);
    req.onreadystatechange = function() {
        if (req.readyState === 4) {
            if ((req.status >= 200 && req.status < 300) || req.status == 304) {
                var d = JSON.parse(req.responseText);
                callback(d);
            } else {
                // Bogus error handling
                callback(req);
            }
        }
    }
    req.send();
}

GeoNames web services

I always forget about the GeoNames web services. They’re awesome, a set of very simple REST like services for geodata. They also distribute a database. I don’t really understand the business, but they’ve been around some six years and seem to do their thing right. I used them for my WikiHere hack a few years ago and am about to use their elevation service for another quick hack.

They publish things right. Data is available in XML or JSON or JSONP formats and they set the CORS header so you can do cross-site javascript with no drama. I was originally going to use Google’s elevation service but they have no cross-site solution, not to mention my use would be unlicensed. So screw em.

Geonames asks for you to register and pass a user name on requests, they have a credit limit on requests. It’s 30,000 credits / day for free, most requests are a single credit, goes from 0.1 to 4 credits / request.

Their primary value add seems to be a broad database of place names, postal codes, etc. International. I don’t know how it compares to competing offerings or indeed if there even are any competitors. They also have time zones, wikipedia, some OSM data searches, etc. I’m using the elevation service, they have three to choose from: GTOPO30, SRTM3, and Aster. Too bad there’s no NED 1/9 for the US, but that’s a lot of data.

$ curl -D - 'http://api.geonames.org/astergdemJSON?lat=37.7383&lng=-122.4531&username=nelson'

HTTP/1.1 200 OK
Date: Tue, 24 Jul 2012 22:37:18 GMT
Server: Apache/2.2.17 (Linux/SUSE)
Cache-Control: no-cache
Access-Control-Allow-Origin: *
Transfer-Encoding: chunked
Content-Type: application/json;charset=UTF-8

{"astergdem":257,"lng":-122.4531,"lat":37.7383}

It’s a shame they refuse to allow caching.

Finishing the SFO Bravo lasercut

I finished up my lasercutting project, a model of SFO Bravo airspace. It’s a stack of 11 roughly circular objects, one every 1000′, that when stacked should be SFO bravo. It was a total pain finishing this out from the rough SVGs, but I think I’m there. It will be about 7in in diameter and 2in thick when assembled.

I ended up doing most of the finishing work in Inkscape. I never could get the SVG objects to scale correctly; the SVG viewpoint and scaling model is really confusing. And after calling ST_Union on the shapes I still had some interior lines I had to delete manually. But I got it close enough and could then paste all 11 objects into the Inkscape template, scale and style afterwards.

I got clever and cut a square hole in the middle of the airspace to insert a spindle. Hard to find that position, btw, it’s not really the center of any of the objects. It’s implied by the radii of the circles. Anyway I figured it out (it’s the VOR location, as expected) and added a rectangle to cut. I think I managed to make the holes 4.5mm wide, the width of the material I’m using, and even cut a 4.5mm long rod elsewhere on the sheet to use as the spindle. But it’s hard to get precise measurements out of Inkscape; it seems to be using the line width as part of the size of the object or something. And I’m in the habit of making the lines 1mm thick while editing so I can see them, then rescaling to 0.01mm for the final cut, which seems to throw off all the sizes. Oh well, if the spindle’s not perfect it’s OK.

It’ll cost of $37 + shipping in blue acrylic. Amazing how much cost depends on thickness. 4.5mm acrylic = $37, whereas 3.0mm is $20 and 5.6mm is $51. Most of that is laser time.

 

quickie VPN notes

I looked quickly into setting up a VPN server on my Ubuntu box in a datacenter, for use with MacOS and iOS clients. Unimpressed with what I learned. Here’s some options. They all suck.

  • PPTP, the venerable Microsoft protocol. Relatively easy to set up on both server and client, but has a reputation for being insecure. Plus it’s PPP and old and has a bad smell to it.
  • L2TP over IPSec. Apparently the server is doable on Ubuntu, but a bit wonky. MacOS and iOS both have clients. I probably should try this, I just don’t like the description of how it works. Update: Josh J. suggested this guide for setup (site down; Google cache).
  • Cisco IPSec. Proprietary? End of life from Cisco? Seems like a road not worth looking down.
  • OpenVPN. This is Ubuntu’s recommended server. Naturally, MacOS has no client for it; people like Tunnelblick. There’s no iOS client either other than GuizmOVPN which requires a jailbreak. I briefly tried following Ubuntu’s guide for installing OpenVPN which starts with “copy these config files and then edit some stuff”. Only the list of things to configure is incomplete, the template config files have errors in them, and after setting it all up I’m told “No /etc/openvpn/easy-rsa/openssl.cnf file could be found. Further invocations will fail”. I imagine I could power through all this stuff but it’s clear OpenVPN is not ready for casual users.

Why is this so damned hard?

Setting up to lasercut Bravo airspace

Another Ponoko project, making a 3d model of San Francisco’s Bravo airspace. It’s a bunch of roughly circular slices, should be great cutting a disc every 500′ or 1000′ to the outlines of the bravo. Some first steps to getting there, from raw data to basic (not finished) SVG files.

1. Download the FADDS database to get the FAA’s shapefiles of airspace. It contains some shapefiles for airspace.

2. Identify the coordinate reference system because shp2pgsql isn’t smart enough to guess. Class_b.prj says:

GEOGCS["GCS_North_American_1983",DATUM["D_North_American_1983",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]

A quick lookup lets me know this is NAD83, EPSG:4269. That’s what I would have guessed, it’s quite close to WGS84, the GPS reference everyone sane uses. US government prefers NAD83 for some complex historical reason.

3. Load a database.

createdb faa -T template_postgis2
shp2pgsql -s 4269 class_b.shp | psql faa

4. Try loading the data into QGIS and see if it looks right. This is where projections start to matter. The Project Properties dialog lets you reproject the data on rendering; you have to check “Enable on the fly CRS transformation”. The SF bravo looks wrong when projected to WGS 84 (EPSG: 4326), too squashed. They should look like circles, using some projection local to San Francisco. There’s a few NAD 83 / California Albers projections that do pretty well, like EPSG: 3310.

Even better is grab Aeronav’s GeoTIFF for San Francisco and see what they use; pilots expect the airspace to look like it does on the chart. Here’s what gdalinfo and QGIS identify it as:

+proj=lcc +lat_1=45 +lat_2=33 +lat_0=37.6 +lon_0=-122.25 +x_0=0 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs

PROJCS["San Francisco TAC",
    GEOGCS["NAD83",
        DATUM["North_American_Datum_1983",
            SPHEROID["GRS 1980",6378137,298.2572221010002,
                AUTHORITY["EPSG","7019"]],
            AUTHORITY["EPSG","6269"]],
        PRIMEM["Greenwich",0],
        UNIT["degree",0.0174532925199433],
        AUTHORITY["EPSG","4269"]],
    PROJECTION["Lambert_Conformal_Conic_2SP"],
    PARAMETER["standard_parallel_1",45],
    PARAMETER["standard_parallel_2",33],
    PARAMETER["latitude_of_origin",37.6],
    PARAMETER["central_meridian",-122.25],
    PARAMETER["false_easting",0],
    PARAMETER["false_northing",0],
    UNIT["metre",1,
        AUTHORITY["EPSG","9001"]]]
Origin = (-144533.795827518420992,71334.980332990919123)
Pixel Size = (31.819676000000001,-31.819676000000001)

Here’s a gallery of what the airspace shape looks like in WGS 84 (the squished one), that California Albers, and the “correct” Lambert projection the FAA uses (with the raster backdrop). The latter two are pretty close, but I could make things hard for myself and use the custom Lambert projection. Instead I’m going to use EPSG:26942, a Lambert that’s centered more or less on San Francisco. Visually the result looks very similar to the FAA’s projection, with the advantage I don’t have to figure out how to add a custom CRS to PostGIS.

5. Create an SVG file with some code. Naively this is as simple as ST_AsSVG(geom) and pasting the path into a skeleton SVG document. This actually works, but is a bit awkward since without reprojection the coordinates are all lat/lon values and stuff’s in a box from 37, -115 to 40, -118 or so. Quick workaround for that in Inkscape: select all (Ctrl-A) then zoom to selection (3). Also need to set the stroke width to something sensible for the coordinates.

 

Having to stop work on this here; I’m now generating reasonable SVG files, one per chunk of Bravo. Two main things left to do. First, use SVG transforms to scale the shapes from the default extent numbers like x=2,000,000 y=464,000 to something like 7cm square Ponoko uses. And second, do some topology calculations with ST_Union or the like so I render each slice of the airspace cake for every elevation.

A second try at Ponoko for my walks

Giving a second try at using Ponoko for my walking tracks after this moderate success. Sha and Rachel of Meshu suggested etching the actual GPS traces on top of the blob, which I thought was clever. So here’s what I’m doing step by step.

1. Create a view for my tracks with simplification

CREATE OR REPLACE VIEW simple_tracks AS
 SELECT tracks.ogc_fid, st_simplify(tracks.wkb_geometry, 0.0002) AS wkb_geometry, tracks.name
   FROM tracks;

2. Use QGIS to make a map of all those tracks, then use “Save as Image” to get a PNG raster image. I made the lines of the tracks be 1mm solid black and zoomed in. Note QGIS exports the image at the size visible on screen, so make that window big first!

 

 

3. Use Pixelmator as a paint program to calculate the concave hull of all my walks. Basically I did a flood fill of the background of the image to some random color, then selected all the pixels of that flood fill color, then inverted the selection. Now my selection is my concave hull! I then used a black brush to fill in the selection so I have a basically monochrome image, also erased some hanging bits to have a cleaner shape. This is the step I wish I could just use ST_ConcaveHull() in PostGIS to do, or some other topology algorithm.

4. Convert the raster blob into a path. Load the painted image into Inkscape, choose Path / Trace Bitmap, and use the default Brightness cutoff. Click “OK”. Nothing visible happens, but now if you move the raster out of the way you’ll see there’s a second black shape. This one is a vector object. Edit the style so it has no fill and a black outline, just to make it obvious.

5. Create a new Inkscape document from the Ponoko starter kit.

6. Copy and paste my outline from step 4 into the new document, then update the stroke style to a cutting line (0.01mm, #0000ff). Note the caution about XQuartz and the Mac clipboard not copying vector objects.

7. Reload my GPS tracks into QGIS. Be careful to load the simplified tracks, for fewer points. Then use the QGIS Print Composer to save the map as an SVG. That tool is really confusing, basically you use the “add map” button to swipe out a rectangle on the page. Scale and centering doesn’t much matter, all we really want is the SVG bits.

8. Load the QGIS generated tracks SVG into Inkscape. Break the group and select the hairball of individual tracks. Copy and paste it into the main document from step 6. Adjust the style of the track hairballs to a light engraving line (0.01mm, #ff00ff). Then, the sadness, scale and align the track hairballs so they just match the outline from step 6. Visual process, non-exact, we’ll see how it looks.

9. Save the SVG and send to Ponoko!

This took me a couple of hours. All this paint program fiddling is terrible; the right thing is to do this all with code. Calculate that concave hull, dump it as SVG. Calculate the union of simplified tracks, clip it to fit inside the concave hull, dump it also as SVG. Combine with the same reference and done! PostGIS has an ST_AsSVG that helps, but until I can get it to calculate the outline of my tracks the way I need there’s not much point.

Ubuntu upgrade to PostGIS 2 with data preservation

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

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

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

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

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

visitors apache log analyzer

It’s irritating but there’s still no great solution for analyzing Apache log files. webalizer and analog both suck. One nice lightweight tool is visitors; it’s simple, fast, and mostly stateless. sample output, sample usage:

grep tweetchive /var/log/apache2/access.log{,-20120715} |
visitors -A -r 100 /dev/stdin
>| tweetchive.html

(cat /var/log/apache2/access.log{,-20120715};
  zcat /var/log/apache2/access.log*gz) |
visitors -A -r 100 -p 100 --prefix http://www.somebits.com --prefix http://somebits.com /dev/stdin
>| vis.html

# 4432363 lines processed in 41 seconds

Here’s some six years of weblog traffic. The breakdown reports are surprisingly uninteresting. I did learn my top Google search phrases: [chiller], [python xpath], [bash read], [spidermangame], [nelson minar], [bash read command]. I could make an SEO fortune!

tweetchive in IE9

Cross-platform Javascript has gotten a whole lot better in the HTML5 era. I developed all of Tweetchive without testing it at all in anything other than Chrome. It just worked in Firefox and Safari and Mobile Safari. IE9 still takes a bit of work, had to make two changes:

  • Added <!DOCTYPE html>. Other browsers don’t care, but IE9 runs in quirks mode without this and leaves out useful things like the JSON functions.
  • Dropped in Moment.js to parse dates. new Date(“some random localized string”) does a good job of parsing dates in most browsers, but not in IE.
    moment(fullTweet.created_at, “ddd MMM DD HH:mm:ss Z YYYY”).valueOf()

JSONP Ajax error handling

I’m using the Twitter API for a project. The results it returns are.. awkward. In particular you often get errors for legitimate requests, but if you try the exact same request again a few seconds later it will work. Presumably their internal caching / timeouts.

Anyway, I need a good way to do error handling of AJAX calls in Javascript. But because I’m doing cross-origin stuff (and Twitter doesn’t set the CORS header) I’m stuck using JSONP. And JSONP error handling sucks, presumably because the crazy <script> eval hack that makes JSONP work doesn’t let Javascript code handle errors.

Options:

  1. jQuery Timeouts. Since version 1.5, jQuery will throw a timeout after N seconds if the JSONP call did not succeed. This gives you limited error notification, albeit asynchronously.
  2. suppress_response_codes. This is a special hack to the Twitter API to always have them return HTTP 200 OK, even on errors, and let you figure out the error in the body. Using this lets you bypass the browser’s own handling of, say, a 400 error and let your Javascript code handle it. Ie when I’m rate limited I get a “400 (Bad Request)” from the API which Chrome intercepts and all I see is a timeout. Presumably with this Twitter API setting, I’ll get a 200 reply immediately that contains info on the error I can parse.
  3. Try Zepto. Their JSONP code is different from jQuery and a preliminary look suggests it might have a better error handling strategy. Seems unlikely, but worth a look?

JSONP is such a horrible hack. I wish Twitter would just set the CORS header and I could use a proper JSON call with XmlHttpRequest with proper error handling. I could do that myself if I proxy the traffic on my server, but then it’s my bandwidth and my IP address being rate limited.

Alternate way of filling browser with a div

A few weeks back I wrote up a trick for making a div fill the remaining browser height using Javascript to calculate a pixel height for the div on resize events. That seemed clunky to me and I just stumbled on a StackExchange question with an alternate method that’s CSS only using absolute positioning. Basically you create a box with top/left/right/bottom set to 0, then save a fixed amount of space at the top. The example uses padding-top, but I found I had to use margin-top instead, at least for a Leaflet map.

In retrospect I should have thought about this absolute positioning idea before! it makes much more sense. And it’s simpler not running any event code.

Animated temperature map

It’s hot. Here’s an animated map of temperatures for the day, from the aviation forecast. Normally this kind of angry rainbow palette is the worst sort of visualization sin, but it’s sort of appropriate for a hot day like today.

Making an animated GIF well is harder than I remember if you care about filesize.

#!/bin/bash
# Source: http://weather.aero/tools/weatherproducts/windstemps
for n in 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18; do
    wget -O $n.gif "http://weather.aero/data/winds/ruc"$n"hr_sfc_temp.gif"
done
gm convert -filter box -resize 315x -loop 0 -delay 25 ??.gif animation.gif

Lasercutting results

I got my lasercut test back. It worked out pretty well.

I was surprised at how well the fine detail came out on the GPS track. One blob is missing; I had a widowed little lozenge at bottom right that was detached. Fair enough. But all the fine details came out surprisingly well on the cardstock. The letters came out great too; all I did was convert some Postscript font text to a path and it came out fine.

The thing that didn’t work was the SF Bravo space (see earlier post). Entirely because of the double lines; Ponoko warns against doing that and they’re right. I also didn’t like the cardstock itself, particularly the burnt edges from the laser. To be expected, and no big deal since this was just a test cut, but unappealing. The solid grey areas came out surprisingly well; they sort of half burn it with the laser and it looked OK. Surprisingly the results came back glued to a wax paper back that I think was attached during the burning. Nice for not losing small parts, and frankly I’m amazed they can tune the laser so it cuts through the material but not the paper backing. I wonder how well that works with something like plexiglass.

Next project will be to re-do the Bravo, but do it right this time. First, use the right projection so the circles aren’t ovals! Second, create a series of stacked objects, one layer for each 1000′ of altitude. That’ll require some union magic in PostGIS. My goal is to get a stack of plexiglass layers with a hole in the middle so I can make a proper 3d object.

 

bash function for launching a web server

I’m doing a lot of AJAX development lately so I have to serve my HTML via HTTP, because AJAX just won’t work with file: URLs. There’s a lot of ways to launch a simple HTTP server in your current directory, here’s a handy bash function to do it (using Python)

pws ()
{
    PORT="$1";
    IP=`ifconfig en0 | awk '/inet / { print $2 }'`;
    python -m SimpleHTTPServer "$PORT" >> /tmp/pws-"$PORT".log 2>&1 &
    echo "http://$IP:$PORT/"
}

There’s a bogus bit here, using “ifconfig en0” to try to guess the right IP address to show. On a Linux box that’d be “eth0”, and in general it’s hard to know which of a machine’s IP addresses you really should use.

Update: I’ve tinkered with this script a little bit. It’ll supply a random port number if one isn’t given. And it’s a bit smarter about figuring out a likely IP address.

function pws {
  PORT="$1"
  [ -z "$PORT" ] && PORT=$[RANDOM%1000 + 9000]
  IP=`ifconfig | awk '/inet / { if ($2 != "127.0.0.1") { print $2; exit 0; } }'`
  python -m CGIHTTPServer "$PORT" >> /tmp/pws-"$PORT".log 2>&1 &
  echo "http://$IP:$PORT/"
}