Some Bits: Nelson's log

69 posts in 2013

Make for data

A recurring theme for me: I need something like make, but good at managing data. Make is all about compiling files and testing filestamps. I need something that’s about download data, and inserting into databases, and testing whether data needs to be regenerated. It’s possible to coerce make into doing this with lots of touching sentinel files but it’s kind of a mess.

Some quick links on this topic:

Battlefield 4 dogtag notes

I’m sort of obssessed with the FPS game Battlefield 4, particularly all the online stats tracking. Here’s my profile. One of the things buried in there is a list of dog tags I’ve taken from other soldiers by cutting their throats with my knife (a totally awesome and challenging feat.) Naturally the webapp uses a JSON file for delivering the list of dogtags to the user, here’s a bit of what’s in it:

data/seenDogTags: tags I’ve taken. basic is for left tags, advanced is for right tags. Example right tag I’ve taken:

"235": {
  "index": 235,
  "isAdvanced": false,
  "name": "THE SACHAL",
  "timestamp": 1385955351,
  "counter": 7,
  "statValue": null,
  "clanTag": "WDD"
}

I believe this means I’ve taken left dogtag #235 a total of 7 times. My last victim was THE SACHAL of clan WDD at the given timestamp. I haven’t found the mapping of indices to tag names but that shouldn’t be too hard. I think left #235 is probably the USA flag dogtag. It’d be a fun little project to draw a map of all the tags you’ve taken, although I have no idea how many people really set their countries. I have mine set to Ascension Island just to be perverse.

The JSON file also has some other stuff in it. data/unlockedDogTagsIndices seems to be the list of tags I can equip. data/basic and data/advanced look like what I have equipped now. And data/seenDogTagsIndices is just a list of tags I’ve taken, a simplified form of what’s in data/seenDogTags.

I love how modern webapps that use JSON data are so easily scrapable.

bf4stats is a third party site that shows my dogtags as a list.

Schematic of rivers

Inspired by this discussion I tried to bang out a quick map of just the biggest rivers in the US in schematic form. My idea was to sort them all by length and draw them side by side, like this awesome 19th century visualization, but without straightening them first. I counted up which gnis_ids in NHDPlus had the most rows (as a proxy for river size), then made a special vector map source with just those rivers.

select geometry, name, strahler, huc8 from merged_rivers where gnis_id in (  354236, 591690, 465582, 1034981, 78762, 517018, 42838, 1384150, 517033, 400069, 201759, 1091369,  425264,  485443, 1035255,  835960, 1428399, 1101881,   78956, 1385432,  837263, 1533479, 1629903,   45730,  756398)

Sadly the resulting image (attached here) doesn’t really work. Some things are screwed up, like the Platte River in Nebraska which just kind of ends. Also you run into the question of defining what a river is; why do we call the Missouri a separate river as opposed to folding it into the MIssissippi? I could show every single watershed that has a unique drainage to the oceans, but then that’s a fanned out watershed map instead of a nice linear river map. Needs more thinking.

Screen Shot 2013-11-21 at 3.14.05 PM

Vector rivers update, NHDPlus / PostGIS problem

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

My imports failed like this:

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

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

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

Address schema for OSM

It’s lovely that OpenStreetMap has such a.. diverse schema. But it makes it hard to figure out how to encode stuff sometimes. I’m looking at importing a bunch of address data from other sources. What’s the right format?

The source data is diverse, but a common thing seems to be a Point mapped to a street name. Ie, the SF address database I downloaded says POINT(-122.408292 37.747785) 660 PRECITA AVE. Cool! There’s a lot of other data and ambiguity about exactly what that POINT encodes (street front? centroid of parcel? building?). But that’s a good place to start.

The OSM schema for addresses is reasonably well defined. Here are the most important tags, based on the Wiki pages for key:addr and Karlsruhe Schema

  • Parsed address: addr:housenumber, addr:street
  • Unparsed address: addr:full
  • Larger scale data: addr:city, addr:state, addr:country, addr:postcode

There’s additional complications for buildings with multiple addresses, and regions that don’t use city/state addressing (ie, addr:subdistrict), and interpolation, etc. Gonna punt on that and focus to what’s relevant for major US cities.

Another significant question is whether you tag the address data onto a building, or do you create a separate standalone address node. The latter approach seems necessary in the US where we don’t have building footprints for so many places. Although MapBox’s analysis is that the majority of addresses are on buildings.

Here’s a list of top address keys culled from TagInfo. I’ll note the majority of these are tags on nodes, not ways.

  • 26M: addr:housenumber
  • 23M: addr:street
  • 18M: addr:city
  • 14M: addr:postcode
  • 13M: addr:country

There’s a second group of keys that have hundreds of thousands of entries, but many fewer than those top 5 above

  • 1967k: addr:conscriptionnumber. (German addresses?)
  • 1605k: addr:interpolation
  • 842k: addr:state
  • 608k: addr:place
  • 500k-600k: addr:street:name, addr:street:type, addr:street:prefix
  • 463k: addr:streetnumber
  • 3896: addr:full
  • 280k-370k: addr:region, addr:district, addr:suburb

Here’s a bunch of maps of address data that people have made that are relevant. Some of these may not be for public consumption.

I’d like to double back and see what they do in Denmark. That country has very good geocoding data and an ongoing process to sync up with the official government data.

Live streaming LoL with low bandwidth

Trying to watch League of Legends live broadcasts (Youtube) in Grass Valley on my slow fixed wireless link. My link is throttled at 768kbps, with a burst up front up to 2500kbps for a short time (15 seconds?). In San Francisco with the faster DSL I can watch 720p no problem and generally think Twitch is the most reliable. How about on a slow link? Conclusion: YouTube 360p Azubu 360p.

All tests are using Google Chrome on a Mac. Bandwidth is me eyeballing the median off of Tomato’s realtime bandwidth graphs. Numbers may be limited by my ISP’s 768kbps hard cap, I’m not entirely sure when the throttle applies. Measurements were taken during the game when the whole screen is live with scrolling backgrounds; bandwidth is lower if most of the screen is static.

  • 340kbps   youtube 240 live   fmt=92
  • 450kbps   twitch low (240?)
  • 530kbps   azubu 360p
  • 800kbps     youtube 360 live   fmt=93
  • 900kbps     twitch medium (360?)
  • 1100kbps? azubu 480p

All but the last option are reasonably reliable for at least a few minutes watching. Quality is not great. The lower 240p category is hard to watch, 360p isn’t bad. Audio is mostly fine (except Twitch low.) My impression is YouTube quality is better in both speed categories. It also seems to handle stream glitches a bit better. I think Azubu is stretching the truth in their reported resolution. (Update: it’s 360p, just more loss on the compression.)

I wish I knew which codecs everyone was using. No easy way to get that info from the Flash players, although presumably it’s determinable on inspection. YouTube’s debug info has those fmt= codes but there are no entries for that on the Wikipedia page for YouTube formats. This YouTube help page on how to broadcast suggests they’re using H.264 for video and AAC for audio. (The bandwidths line up with my observation, too.) A bit surprised they’re not using WebM/VP8, but maybe it’s a hardware support thing.

The video content is a bit rough for codecs, btw. Rendered graphics. And the whole screen is constantly scrolling, not many static parts of the screen. Even the background alters on scrolling because of the perspective projection the game uses.

lolss

My ISP’s burst interacts strangely with the streaming services. My thinking is that my 768kbps sustained network is just not quite fast enough for Youtube 360 or Twitch Medium, but my ISP doesn’t actually enforce that throttle for 15-30 minutes. Maybe because I’m only a tiny bit above my limit? Dunno.

Also worth noting that only Youtube has the weird sawtooth bandwidth thing. Azubu and Twitch both deliver a more consistent stream. I’m not sure if this really matters, given buffering in the network. I’m willing to bet Youtube is doing what they do on purpose, but I don’t understand why. The “stats for nerds” in YouTube’s player hangs at 0kbps, then bursts up to 1400kbps about 1.5s every 5s or so.

Graph below: YouTube 240p is the jagged line. The smooth line is either Twitch or Azubu, forget which.

Screen Shot 2013-08-31 at 1.29.14 PM Update: after watching a couple of hours I’m using the Azubu 360p stream. The YouTube 360p stream is better quality, but it’s just a tiny bit too much bandwidth for my link; the stream pauses every minute or so, very annoying. Azubu has the stream that’s just right for my bandwidth. They’re a bit odd in they’re serving a 530kbps 360p stream instead of 800kbps. The compression artifacts are awfully visible. But it’s better than the 240p options.

I think Azubu is using the same codec as everyone else. OTOH my Macbook Air’s fan is running pretty hard now, the Flash player seems to be using double the CPU of YouTube’s when viewing full screen. Not a big deal, but something’s different.

It’s 2013 and remote filesystems still suck

About once a month my AFS mounted file systems fail on my Mac. This is from one Mac to another, both running 10.8

[nelson:~] $ mount
/dev/disk2 on / (hfs, local, journaled)
devfs on /dev (devfs, local, nobrowse)
map -hosts on /net (autofs, nosuid, automounted, nobrowse)
map auto_home on /home (autofs, automounted, nobrowse)
//media@gvmini/media on /Volumes/media (afpfs, nodev, nosuid, mounted by nelson)
[nelson:~] $ sudo bash
Password:
[root:~] # umount /Volumes/media
^C^Z^C^Z^C^C^C^C^C^C^Z^C^C

Every process that’s touched that filesystem is marked uninterruptible. There’s a -f flag for forcing umount but it doesn’t work either, just hangs.

Hilariously, the man page for umount on the Mac says “Due to the complex and interwoven nature of Mac OS X, umount may fail often. It is recommended that diskutil(1) (as in, ``diskutil unmount /mnt’‘) be used instead.” No, diskutil unmount doesn’t work either, even with a force.

At least the Finder doesn’t hang when you click the little eject arrow.

Update: naturally you can’t shut the machine down in this state either. Power switch for you!

YouTube video bandwidth

I’ve been watching some League of Legends gamecasts, live video. They offer several streams including Twitch.tv and Youtube. Here’s the bandwidth for a 720p stream; from Twitch first (a steady 2500kbps) and then YouTube (variable, averages 1600kbps). My network caps out about 6000kbps.

 

Image

 

 

It’s great that YouTube uses so much less bandwidth, but I’ve had real problems with reliability. In San Francisco it’s nearly unwatchable on WiFi. And in Grass Valley with the 2500kbps burst to 800kbps sustain network, YouTube’s stupid bandwidth estimator gets all confused by the burst and fails to deliver a reliable stream (at any quality). In general I think YouTube is trying to be too clever. That sawtooth pattern is sure weird.

Rectangular artifacts in rivers map

Lots of interest in my “all rivers” map, thanks in large part to a post on kottke.org. And several requests for a poster print. I’d like to do that, would be fun to have one for myself, but before I do that I’d want to fix a few things.

The simple thing is to fix the projection, use an Albers USA. It might make sense to use Mike’s code, he’s already got the projection and a nice offline renderer instead of my goofy “screenshot the browser” approach.

The hard thing is to fix these annoying rectangular artifacts in the data. They’re visible in many places, specifically in eastern Oklahoma. I asked the NHDPlus guys and they said the NHD source data was digitized from USGS quads and that some of the quads are different than others, but they couldn’t characterize how. Looking at a zoomed view I think it’s just fewer flowlines; you can see fewer lines on the right than the left.

Taking a suggestion from Seth F I tried to only draw things with a Strahler number > 2; it softens the artifacts, but doesn’t eliminate them. Top is a whole US map, bottom is zoomed in on eastern Oklahoma. Artifacts are still visible. If some quads just have fewer flowlines that’s going to affect the Strahler calculation too. Maybe there’s some other property to filter on to remove the bias, like only rendering things with a gnis_id.

all flowlines, strahler >= 2 rectangular bias

Leaflet GeoJSON vector tiles

Half-finished notes, but I don’t want to lose them.

Leaflet doesn’t have a stock plugin for GeoJSON vector tiles. I believe Glen Robertson’s leaflet-tilelayer-geojson is the most complete and correct plugin, but it renders pretty slowly (several seconds for cached data). My river vector tiles tutorial includes a TileLayer.d3_geoJSON.js that renders about 10x faster, but because it uses D3 instead of Leaflet to do the GeoJSON rendering it lacks full Leaflet integration. For instance, there’s no way to bind a Leaflet popup to a LineString.

Over on the Leaflet-js mailing list I started a discussion “GeoJSON performance? River vector tile map, trying to figure out how to make Glen’s approach using Leaflet GeoJSON faster. Norbert Renner responded with some terrific experimental work that made rendering much faster, but it was sort of a one-off spike rather than a reusable improvement. Someone should spend some time with his optimizations and see if they can be ported to work in the general purpose library.

 

Examining the schema of a shapefile

Given a shapefile, how do you tell roughly what’s in it? ogrinfo -al -so

$ ogrinfo -al -so NHDFlowline.shp

INFO: Open of `NHDFlowline.shp'
      using driver `ESRI Shapefile' successful.

Layer name: NHDFlowline
Geometry: Line String
Feature Count: 178868
Extent: (-124.409586, 32.500058) - (-114.588485, 43.336272)
Layer SRS WKT:
GEOGCS["GCS_North_American_1983",
    DATUM["North_American_Datum_1983",
        SPHEROID["GRS_1980",6378137.0,298.257222101]],
    PRIMEM["Greenwich",0.0],
    UNIT["Degree",0.0174532925199433]]
COMID: Integer (9.0)
FDATE: Date (10.0)
RESOLUTION: String (7.0)
GNIS_ID: String (10.0)
GNIS_NAME: String (65.0)
LENGTHKM: Real (19.11)
REACHCODE: String (14.0)
FLOWDIR: String (15.0)
WBAREACOMI: Integer (9.0)
FTYPE: String (24.0)
FCODE: Integer (9.0)
SHAPE_LENG: Real (19.11)
ENABLED: String (6.0)
GNIS_NBR: Integer (9.0)

Small boot partition considered harmful

df-year

 

Ubuntu happily installs new kernels automatically into /boot. It never prunes them automatically though. So every few months I have to notice /boot is nearly full and clean it up. There are theoretical arguments why having a separate small boot partition is a good idea, but here’s a practical reason it isn’t.

 

Cloning a gist via ssh

For some reason GitHub really wants you to clone gists via https. But I’m all set up with ssh keys and would prefer to check out that way. Here’s how:

git clone git@github.com:5624141.git

Replace the number with your gist id, of course. Your username is not part of the URL.

nginx proxy buffering

It took a lot of head scratching, but I think I figured out nginx and how to configure buffering of proxies. Long story short, here’s where I ended up:

location /rivers {
  proxy_pass http://localhost:8000;
  proxy_buffering on;
  proxy_buffers 32 16k;
}

If I did that right, it means “proxy to this other HTTP server and buffer 512kb of data from it”. The default configuration is to buffer only 32k, which in the modern world seems awfully small. But nginx allocates this memory per request, so if I were expecting a lot of requests that would be a bad idea. nginx will also buffer to disk if it runs out of memory buffer, up to 1G or so, but I wanted to avoid that. Note that nginx is buffering uncompressed data.

With this setup I can have 9 clients slowly loading the big tile 4/3/6.json even though I only have four Gunicorn workers. And I verified via sudo inotifywait -m -r /var/lib/nginx/ that it wasn’t using the file cache. Good enough for me.

Here’s a quicky slow client I used to test the buffering:

#!/usr/bin/env python

import socket, time, sys

req = [
'GET /rivers/4/3/6.json HTTP/1.1',
'Host: www.somebits.com',
'Accept-Encoding: gzip',
'Connection: close',
'', '']
readSize = 1600

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('somebits.com', 8001))
s.sendall('\r\n'.join(req))
l = 0
while True:
    time.sleep(1)
    d = s.recv(readSize)
    l += len(d)
    if len(d) == 0:
        break
    sys.stdout.write("%s" % "*" if len(d) == readSize else ".")

s.close()
print '\nReceived', l, "bytes"

Vector tile page sizes

I instrumented the Leaflet version of my vector tile client to show me the size of the vector tiles for the page. Chrome developer tools will do this measurement, but it’s easier to have it in console.log. All measures are uncompressed and uncached times, and for my relatively limited set of rivers (based on Strahler filtering). I intend to add more data to the vector tiles; measuring this as a baseline.

All measurements taken with a browser window about 1000 x 1000, loading about 25 tiles for the view. I slowly zoomed in on St. Louis, a fairly dense area to load.

  Size    Time   View                 Cutoff
1113kB  1237ms   4/38.89/-98.75       strahler >= 6
1117kb  1494ms   5/37.892/-94.241
1741kb  1798ms   6/38.100/-92.230     strahler >= 5
 830kb  1047ms   7/38.376/-91.214
 334kb   479ms   8/38.565/-90.722
 283kb   427ms   9/38.6340/-90.4738   strahler >= 4
 239kb   332ms  10/38.7701/-90.3962   strahler >= 3
  90kb   233ms  11/38.8445/-90.5332
  60kb   301ms  12/38.8691/-90.5842   strahler >= 2
  53kb   686ms  13/38.8697/-90.6169   strahler >= 1

I guess I knew that the map got lighter weight as I zoomed in, but not how much. Too bad; I’m most excited to load data in the zoomed out views. But looking at this I can move the cutoffs some and show more rivers. Update: I updated some of the thresholds around z=8 to z=13.

A large tile like 4/3/5.json gzips from 384k to 92k. A smaller tile like 8/40/97.json gzips from  29k to 7k. So let’s say GeoJSON gzips to 25% the original size; that means the biggest views will take about 500k of data on the wire to download. That’s pretty reasonable.

A whole separate question is render time. The Leaflet render is really bad and I don’t know why. The new D3 client is so fast it gives me some aspiration.

 

TopoJSON for rivers

Mike Bostock took a crack at using TopoJSON to encode the NHDFlowline dataset. Just the geometry for rivers in 2 dimensions; no properties, etc. Tested just for California. All sizes are one million byte megabytes.

  • Source shapefile: 132M, 72M gzipped.
  • Naive GeoJSON conversion: 184M, 56M gzipped.
    ogr2ogr -dim 2 -f GeoJSON -select ‘’ new.geojson NHDFlowline.shp
  • GeoJSON rounded to 5 digits: 95M, 21M gzipped.
    liljson -p 5 < new.geojson
  • GeoJSON rounded to 3 digits: 80M, 9M gzipped.
    liljson -p 3 < new.geojson
  • TopoJSON: 20M, 3.3M gzipped.

So for this data TopoJSON is about 1/4 - 1/5 the size of the equivalent GeoJSON. And those advantages persist through gzip. And that’s for a pathologically bad case, where there’s no shared topology along polygon boundaries. Pretty much all the savings here must be coming from the delta encoding. Neat!

Update: Mike converted the whole US. 2.5G of .shp file input, 327M of topojson output.

Note that TopoJSON quantizes. Mike used the default TopoJSON settings which I think work out to about 10,000 x 10,000 resolution, which makes the comparison to GeoJSON rounding to 3 digits about fair. Here’s a snapshot of a render of the TopoJSON that Mike gave me. It looks right.

TEMP-Image_1_1

Moar detail

I love this one screenshot from when I first got nice rendering implemented, showing all sorts of detailed rivers. I’ve backed way off that because it’s so much data, etc. But in filtering so much I’ve lost something.

Mike Bostock did a pure-D3 vector tile renderer, so I bashed up a river renderer. And it’s fast. So I made some screenshots where I don’t filter the data on Strahler number at all; all rivers, all the time!

The server generation time is acceptable once you rely on caching. Data sizes are pretty bad though, 27 megs a tile :-P

 7/25/49:   1684 ms    640 kb   1928 features
 6/13/23:   6243 ms   2308 kb   5405 features
  5/6/11:  21221 ms   8841 kb  24139 features
  5/7/12:  37041 ms  15146 kb  42131 features
   4/3/6:  64572 ms  26870 kb  75744 features

 

ms

Yet more merge strategy timings

To complement my previous timings, some more measurements of new merge strategies.

Merge by (huc8, gnis_id, strahler)
 7/25/49:    275 ms     30 kb     50 features
 6/13/23:    453 ms     95 kb    148 features
  5/6/11:    783 ms    209 kb    238 features
  5/7/12:   1048 ms    202 kb    434 features
   4/3/6:   1333 ms    376 kb    783 features

Merge by (gnis_id, strahler) if gnis_id is not null,
otherwise merge by (huc8, strahler)
 7/25/49:    103 ms     29 kb     45 features
 6/13/23:    262 ms     91 kb    131 features
  5/6/11:    543 ms    199 kb    178 features
  5/7/12:    534 ms    186 kb    339 features
   4/3/6:    958 ms    346 kb    600 features

That second strategy seems like the right compromise. The performance numbers are pretty good, the map is accurate, and the actual SQL queries are reasonably simple. It takes 11 minutes for me to merge all 2.7M rivers this way. The resulting table has 332,615 rows in it; that’s 322,621 rows with a gnis_id of some sort and 9994 without.

I sure wish Postgres could do this merging with a single query. The query planner seems to be doing the wrong thing and Postgres infamously has no syntax for giving hints to it. So I issue 170,000 queries, one per gnis_id, instead of doing a single insert. Here’s the query that doesn’t run in a reasonable time, combined with the explain for it. I have indices on gnis_id and strahler both, but maybe the group by on the pair confuses it.

insert into m(gnis_id, name, strahler, huc8, geometry)
       select
         MAX(gnis_id) as gnis_id,
         MAX(name) as name,
         MAX(strahler) as strahler,
         MIN(huc8) as huc8,
         ST_LineMerge(ST_Union(geometry)) as geometry
       from rivers
       group by (gnis_id, strahler);

                                        QUERY PLAN
-------------------------------------------------------------------------------------------
 Insert on m  (cost=2863631.25..2944365.87 rows=124821 width=102)
   -&gt;  Subquery Scan on &quot;*SELECT*&quot;  (cost=2863631.25..2944365.87 rows=124821 width=102)
         -&gt;  GroupAggregate  (cost=2863631.25..2943117.66 rows=124821 width=491)
               -&gt;  Sort  (cost=2863631.25..2870305.66 rows=2669766 width=491)
                     Sort Key: (ROW(rivers.gnis_id, rivers.strahler))
                     -&gt;  Seq Scan on rivers  (cost=0.00..206104.66 rows=2669766 width=491)
(6 rows)

Notes on NHDPlus contents, grouping criteria

Basic stats about the tables from NHD I’m working with

NHDFlowline

  • 2,993,526 rows
  • 2,993,525 distinct ComIDs
    (the duplicate is ComID 17029298, Squaw Creek, and it’s not quite a duplicate row.)
  • 2,527,374 distinct ReachCodes
  • 181,685 distinct GNIS_IDs
  • 70,822 distinct GNIS_names
  • Almost all the flowlines are < 5km in length
    737,072: 0-1km
    767,064: 1-2km
    696,161: 2-3km
    366,717: 3-4km
    184,901: 4-5km

PlusFlowlineVAA

Pages 101 and following of the NHDPlusV2 User Guide are very useful in understanding how the PlusFlowlineVAA data is calculated.

  • 2,691,346 rows (one for each flowdir == “with digitized”, according to docs)
  • 2,691,345 distinct ComIDs (17029298 is duplicated again)
  • 2,691,346 HydroSeqs. This number acts like a flowline ID for a lot of the VAA data, with the added advantage that the numbers are sorted upstream to downstream.
  • 2,626,049 distinct FromNodes
  • 1,686,246 distinct ToNodes
  • 1,013,062 distinct LevelPathIDs
  • 14,676 distinct TerminalPathIDs. None are null.
  • There are 663,408 rows with gnis_id of null and a terminalpathid of 350002977. I’m guessing these are poorly labelled tributaries for the Mississippi, but I’m not sure. It’s too many to merge!

Reachcodes

The reach code is an alternate ID for a flow that hierarchically encodes its watershed. For instance the South Yuba River has reach codes like 18020125000030, 18020125000031, etc. The first 8 characters of a reach code are separable and are either identical to or closely related to the HUC8 that the WBD datasets use. Grouping flows by HUC8 makes a lot of sense, they are geographically clustered and related. Note that reachcode shows up both in nhdflowline and plusflowlinevaa; I’m not sure if they are identical or not.

  • There are 2,239,489 distinct reachcodes in PlusFlowlinesVAA. The biggest is 10150005000096 which matches 100 rows.
  • There are 2117 distinct HUC8s in the reachcodes. The biggest HUC8 is 09030001 which has 5784 rows in it.
  • There are 32,439 distinct 12 character prefixes for reachcodes. The biggest one 020801110150 has 457 rows. This seems like the right size of blob for me to merge geometry on. I’m not positive it’s really correct to group by this 12 character prefix; while you see HUC12 hierarchical data in watershed boundaries, I’m not certain these reachcodes are doing the same thing. OTOH our grouping criterion can be a bit arbitrary; all we really need is some geographic locality.

Grouping criteria

So grouping by gnis_id isn’t sufficient because so many flows have that as null. How about grouping by some combination of a substring of reachcode, gnis_id, and strahler number? Here’s the sizes of various grouping options:

  • 322,625 groups, biggest is 1153 rows
    where gnis_id is not null group by (gnis_id, strahler)
    this is the flawed grouping I was using. It leaves out 1.5M flows where gnis_id is null
  • 333,405 groups, biggest is 2882 rows
    group by (substring(reachcode from 1 for 8),gnis_id,strahler)
    Grouping by HUC8, gnis_id, and Strahler number. Most “correct”?
  • 454,018 groups, biggest is 391 rows
    group by (substring(reachcode from 1 for 12),gnis_id,strahler)
    Grouping by first 12 of reachcode, gnis_is, strahler.

Based on that analysis, the HUC8 is the right choice. There’s a reasonable number of groups, no group is too enormous, and HUC8 is a meaningful thing to group on.

So now for every single HUC8, I’m executing this insert:

insert into merged_rivers(gnis_id, name, strahler, huc8, geometry)
select
  MAX(gnis_id) as gnis_id,
  MAX(name) as name,
  MAX(strahler),
  MAX(huc8) as huc8,
  ST_LineMerge(ST_Union(geometry)) as geometry
from rivers
where huc8 = %s
group by (gnis_id,strahler)

I’d rather do this as one big create table with a group by (huc8, gnis_id, strahler) but last time I tried something like that Postgres was still choking on it 18 hours later. This way I can watch it as it goes.

Postgres bug report

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

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

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

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

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

Vector tile success!

I think I’ve finally wrangled my vector tile data problem, the one where my server was seeing rivers as lots of little tiny line segments instead of one giant linestring. It took me a long time to work this out; merging with ST_Union() at query time was too slow, I think because the subselect that TileStache issues confuses the gist. I tried creating a merged river database in one fell swoop with a select ST_Union(geometry)... group by gnis_id but that query didn’t complete after 18 hours, Postgres wasn’t using the gnis_id index correctly. I finally wrote a Python script to merge stuff one river at a time and create a new database that way and it runs in < 4 minutes. Some data:

  • 2,667,758 rows in the rivers database. Each one has a simple LineString for geometry.
  • 1,086,512 rows with a gnis_id. Another 1,581,246 where gnis_id is null. Those nulls seem to be causing a problem, see below. (There’s 1,899,204 gnis_id nulls in the source nhdflowline database; I must have tossed some when joining on comid to make the rivers table in the first place.)
  • 322,621 rows in the merged database (“rivers2”, for this discussion). Each has a MultiLineString for the geometry, just ST_Union().
  • 178,906 unique rivers in the dataset (identified by gnis_id). I don’t merge all this way in rivers2 because I want to keep them separated by Strahler number. Ie: the Missisippis has 7 rows in rivers2, the little tiny part at Strahler=2, the bigger part at Strahler=3, ... all the way to Strahler=8 at the Gulf.

I later improved on things by making a rivers3, which is an ST_LineMerge(ST_Union(geometry)); that stitches together LineStrings where possible. Adds about 10% overhead to the table building, but significantly better results on serving.

One failure of this approach is gnis_id is sometimes null. Right now I’m just throwing those geometries away in the merging process and the result is broken lines, bits of rivers are missing. Visual inspection suggests its in places where gnis_id is null, and there’s a lot of those. I took a shot at a rivers4 where I just copied all those nulls in. It looks correct, which is a virtue, but we’re back to bloated data and query times. Need to dig more into NHDPlus and figure out why gnis_id is null in so many places, what to do about it.

Old way (rivers)
 7/25/49:    577 ms    258 kb   1715 features
 6/13/23:   2281 ms   1048 kb   6911 features
  5/6/11:   5421 ms   2549 kb  16953 features
  5/7/12:   6457 ms   2659 kb  17781 features
   4/3/6:  10359 ms   4855 kb  32439 features

New way (rivers2, with ST_Union)
 7/25/49:    436 ms     58 kb     25 features
 6/13/23:    874 ms    243 kb     90 features
  5/6/11:   1648 ms    538 kb     81 features
  5/7/12:   2236 ms    649 kb    162 features
   4/3/6:   3435 ms   1175 kb    275 features

Newer way (rivers3, with ST_LineMerge(ST_Union()))
 7/25/49:     48 ms      9 kb     25 features
 6/13/23:     86 ms     23 kb     90 features
  5/6/11:     89 ms     21 kb     81 features
  5/7/12:    162 ms     41 kb    162 features
   4/3/6:    216 ms     53 kb    275 features

Newerer way (rivers3, with nulls included)
 7/25/49:    244 ms     98 kb    613 features
 6/13/23:    814 ms    347 kb   2223 features
  5/6/11:   2017 ms    946 kb   6188 features
  5/7/12:   1648 ms    691 kb   4499 features
   4/3/6:   2934 ms   1316 kb   8664 features

Huge improvements, very happy.

Window resizing vs. Gunicorn

Weirdest behavior I’ve seen in a Unix server in the longest time. Here’s what happens when I’m running a GUnicorn server (with Tilestache) and resize the iTerm2 it’s attached to.

2013-05-13 18:59:20 [7941] [INFO] Handling signal: winch
2013-05-13 18:59:20 [7941] [INFO] graceful stop of workers
2013-05-13 18:59:20 [7944] [INFO] Worker exiting (pid: 7944)
INFO:gunicorn.error:Worker exiting (pid: 7944)

I thought this was some sort of sick joke, but it’s for real. GUnicorn interprets SIGWINCH to mean “gracefully stops workers but keep the master running”. Which is absolutely terrible in an interactive environment where I might deliberately resize a window while debugging. Particularly with tabbed terminal windows. UI actions in the controlling terminal = kill server, how intuitive!

I can’t even figure out when I’d actually want the documented behavior. The workers don’t restart; is there some way to manually start them? What’s left in a GUnicorn server after you shut down the workers?

Update: this was fixed in GUnicorn, see issue 500. SIGWINCH now only shuts stuff down if in daemon mode. Which seems reasonably safe. Still seems an odd choice of signal to me, but I see there’s precedent with Nginx and maybe they were running out of signals.

Debugging vector tiles performance

My vector river tiles app is unacceptably slow when drawing maps way out, like at zoom=6. I know what the problem is; there’s just too many rivers and geometry. But I’d hoped that it would magically work anyway. Some notes on where the time is going.

First, a testing setup. This is remarkably awkward; there have never been good off the shelf tools for measuring database slowness :-( After a failed attempt to make TileStache use a LoggingCursor what I came up with is:

  • gunicorn configured for a single synchronous worker. It’s unrealistic, but much easier to follow.
  • TileStache configured to debug level INFO. It emits nice lines like
    INFO:root:TileStache.getTile() riverst/6/13/23.json via layer.render() in 2.090
  • Basic client test; load a map and when it gets slow, look in the TileStache logs for specific tiles that are taking a long time.
  • Reproducible client test: load a single tile
    /bin/time curl -s http://localhost:8000/riverst/6/13/23.json | wc -c
    Ensure that TileStache isn’t loading from cache.
  • Postgres configured with log_duration=on and log_statement=all. This gives you helpful log lines like
    LOG: statement: SELECT ....
    LOG: duration: 621.962 ms

By syncing these all up I know that the tile z=6 13/23 is taking 2.09s for TileStache to create, 620ms of which is the database. And the GeoJSON output is a megabyte. That’s already very useful data; I had no idea TileStache itself was doing so much work.

Now I can take that query and look at it. For instance, that one tile returns 6911 rows! This is the NHD schema biting me in the ass; rivers are broken up into a lot of little points. The Cheyenne River on that tile, for instance, is returning 448 different rows with little LineStrings of 2-30 points each. Way too much detail for such a broad overview tile.

Some basic timings for the slowest query I could find at various zoom levels.

Tile     Time    DBtime   Rows    GeoJSON size
7/25/49   510ms   157ms    1715     264,410
6/13/23  2090ms   620ms    6911   1,073,684
5/ 7/12  5375ms  1598ms   17781   2,723,314
4/ 3/ 6  9461ms  2940ms   32439   4,972,224

Looking at this data, I’m thinking the bigger problem may really be the GeoJSON size. The tile generation time is awful but then again there’s only a few thousand tiles at zoom 7-0, can just cache them all. But there’s no love in sending all those tiles to a web browser client! The chopped up geometry is a problem for the GeoJSON too; each little LineString gets encoded as a separate feature with its own properties, so the string “Cheyenne River” is in the GeoJSON tile 448 times. Really need to fix that.

Here’s the query TileStache issues for 4/3/6 as well as the “explain analyze” output:

SELECT q.*,
	                     ST_AsBinary(ST_Transform(ST_Intersection(ST_Simplify(q.geometry, 9783.94), ST_SetSRID(ST_MakeBox2D(ST_MakePoint(-12523442.71, 2504688.54), ST_MakePoint(-10018754.17, 5009377.09)), 900913)), 4326)) AS geometry
	              FROM (
	                select geometry, name as n, strahler as s from rivers where strahler >= 6
	                ) AS q
	              WHERE ST_IsValid(q.geometry)
	                AND q.geometry && ST_SetSRID(ST_MakeBox2D(ST_MakePoint(-12523442.71, 2504688.54), ST_MakePoint(-10018754.17, 5009377.09)), 900913)
	                AND ST_Intersects(q.geometry, ST_SetSRID(ST_MakeBox2D(ST_MakePoint(-12523442.71, 2504688.54), ST_MakePoint(-10018754.17, 5009377.09)), 900913))

 Bitmap Heap Scan on rivers  (cost=9362.71..41858.70 rows=943 width=478) (actual time=176.078..2661.831 rows=32439 loops=1)
   Recheck Cond: ((strahler >= 6) AND (geometry && '010300002031BF0D000100000005000000EC51B856F6E267C152B81E45F81B4341EC51B856F6E267C15C8FC245F81B5341D7A37045F81B63C15C8FC245F81B5341D7A37045F81B63C152B81E45F81B4341EC51B856F6E267C152B81E45F81B4341'::geometry))
   Rows Removed by Index Recheck: 65107
   Filter: (st_isvalid(geometry) AND _st_intersects(geometry, '010300002031BF0D000100000005000000EC51B856F6E267C152B81E45F81B4341EC51B856F6E267C15C8FC245F81B5341D7A37045F81B63C15C8FC245F81B5341D7A37045F81B63C152B81E45F81B4341EC51B856F6E267C152B81E45F81B4341'::geometry))
   ->  BitmapAnd  (cost=9362.71..9362.71 rows=8487 width=0) (actual time=175.357..175.357 rows=0 loops=1)
         ->  Bitmap Index Scan on rivers_strahler_idx  (cost=0.00..1904.82 rows=102971 width=0) (actual time=10.056..10.056 rows=102825 loops=1)
               Index Cond: (strahler >= 6)
         ->  Bitmap Index Scan on rivers_geometry_gist  (cost=0.00..7457.17 rows=217628 width=0) (actual time=163.464..163.464 rows=754699 loops=1)
               Index Cond: ((geometry && '010300002031BF0D000100000005000000EC51B856F6E267C152B81E45F81B4341EC51B856F6E267C15C8FC245F81B5341D7A37045F81B63C15C8FC245F81B5341D7A37045F81B63C152B81E45F81B4341EC51B856F6E267C152B81E45F81B4341'::geometry) AND (geometry && '010300002031BF0D000100000005000000EC51B856F6E267C152B81E45F81B4341EC51B856F6E267C15C8FC245F81B5341D7A37045F81B63C15C8FC245F81B5341D7A37045F81B63C152B81E45F81B4341EC51B856F6E267C152B81E45F81B4341'::geometry))
 Total runtime: 2666.323 ms

Update: I played around with merging geometries in the database by grouping on gnis_id. It’s got some problems, I think I broke the gist (every query is taking 35 seconds at any zoom level!) But the approach has some promise. At least it’s making for smaller outputs; 28k vs 264k for 7/25/49, 88k vs 1073k for 6/13/23.

explain analyze  SELECT q.*,
                     ST_AsBinary(ST_Transform(ST_Intersection(ST_Simplify(q.geometry, 2445.98), ST_SetSRID(ST_MakeBox2D(ST_MakePoint(-11897270.58, 5009377.09), ST_MakePoint(-11271098.44, 5635549.22)), 900913)), 4326)) AS geometry
              FROM (
                select ST_LineMerge(ST_Union(geometry)) as geometry, max(name) as n, max(strahler) as s from r where strahler >= 5 group by (gnis_id, strahler)
                ) AS q
              WHERE ST_IsValid(q.geometry)
                AND q.geometry && ST_SetSRID(ST_MakeBox2D(ST_MakePoint(-11897270.58, 5009377.09), ST_MakePoint(-11271098.44, 5635549.22)), 900913)
                AND ST_Intersects(q.geometry, ST_SetSRID(ST_MakeBox2D(ST_MakePoint(-11897270.58, 5009377.09), ST_MakePoint(-11271098.44, 5635549.22)), 900913))

 Subquery Scan on q  (cost=354441.41..380026.21 rows=10258 width=72) (actual time=2563.823..36912.769 rows=93 loops=1)
   ->  GroupAggregate  (cost=354441.41..377282.19 rows=10258 width=497) (actual time=2562.281..36041.899 rows=93 loops=1)
         Filter: (st_isvalid(st_linemerge(st_union(r.geometry))) AND (st_linemerge(st_union(r.geometry)) && '010300002031BF0D000100000005000000295C8FD236B166C15C8FC245F81B5341295C8FD236B166C1E17A144E777F5541E17A144E777F65C1E17A144E777F5541E17A144E777F65C15C8FC245F81B5341295C8FD236B166C15C8FC245F81B5341'::geometry) AND (st_linemerge(st_union(r.geometry)) && '010300002031BF0D000100000005000000295C8FD236B166C15C8FC245F81B5341295C8FD236B166C1E17A144E777F5541E17A144E777F65C1E17A144E777F5541E17A144E777F65C15C8FC245F81B5341295C8FD236B166C15C8FC245F81B5341'::geometry) AND _st_intersects(st_linemerge(st_union(r.geometry)), '010300002031BF0D000100000005000000295C8FD236B166C15C8FC245F81B5341295C8FD236B166C1E17A144E777F5541E17A144E777F65C1E17A144E777F5541E17A144E777F65C15C8FC245F81B5341295C8FD236B166C15C8FC245F81B5341'::geometry))
         Rows Removed by Filter: 3599
         ->  Sort  (cost=354441.41..354953.32 rows=204764 width=497) (actual time=2009.868..2244.670 rows=204904 loops=1)
               Sort Key: (ROW(r.gnis_id, r.strahler))
               Sort Method: external merge  Disk: 73896kB
               ->  Bitmap Heap Scan on r  (cost=3835.46..197798.53 rows=204764 width=497) (actual time=31.229..642.727 rows=204904 loops=1)
                     Recheck Cond: (strahler >= 5)
                     Rows Removed by Index Recheck: 1371179

Building unison on homebrew/mac

I thought I’d try Unison out, it’s a directory sync system that’s a bit like rsync but specifically targeted at keeping filesystems in sync in both directions. May solve my problem trying to keep two Macs together with no reasonable Internet to just Dropbox or whatever. OTOH, Unison hasn’t had much development in years. And it’s written in OCaml, oy.

Anyway, it doesn’t build right in Homebrew. Turns out the Makefile is trying to be clever with the variable $NAME and it was picking up my shell environment variable. A simple “unset NAME” before installing seems to have fixed it. Details at https://github.com/mxcl/homebrew/issues/11862

1090MHz antenna

Finally managed to take my software radio outside and watch airplanes overhead. Lots of fun stuff there. Also I built a crappy 1090MHz dipole antenna. I have no idea what I’m doing, but it seems to work reasonably well. I wonder if I can measure how well?

Thanks to @lemonodor I learned about http://www.airframes.org/ which lets me look up those 6 digit ICAO codes. For instance ae2923 flying at 16,300 is a US Air Force registered B350 King Air. I’m wondering if it’s a chase plane for drones. COUGR11 (ae2f5f) at 14,325 and SPARTA53 (053977) at 15,300. Neither of those show up in airframes, although ae2f5f may be another King Air and 053977 is a bogus code, 1234567 in octal.

MacOS ._* garbage

MacOS has this terrible habit of littering filesystems with ._ files (for the search engines: “dot underscore files”). Apparently Apple uses these files for some sort of extended metadata, extending Apple’s track record of overcomplicating file systems that goes back to the bad old days of Resource Forks. (Remember BinHex? Good times.)

OK, to be fair, having some out of the way place to put extra data around files is sometimes useful. What I hate is the way the ._ garbage breaks other tools. My latest example is rsync --delete; it won’t delete a directory with a ._ file in it. Somehow in my trying to sync up directories between two Macs via a USB disk I’ll end up with some stray ._ files that then escalate to whole stray directories full of ._ files.

 

MacOS doesn’t support static binaries

clang -static -g -o dump1090 dump1090.o anet.o -L/tmp/rtl-sdr/build/src/ -L/usr/homebrew/Cellar/libusb/1.0.9/lib/ -lrtlsdr -lpthread -lm
ld: library not found for -lcrt0.o
clang: error: linker command failed with exit code 1 (use -v to see invocation)

/sadtrombone. Or what’s the emotion for “Apple’s kernel team is laughing at you”?

Apple has a reasonable explanation:

A statically linked binary assumes binary compatibility at the kernel system call interface, and we do not make any guarantees on that front. Rather, we strive to ensure binary compatibility in each dynamically linked system library and framework.

So basically they moved the guarantee of compatibility from the kernel interface down into the library interfaces. I guess that sort of makes sense, only it’s different from every other Unix ever and makes simple things hard. Too bad. I have some 10 year old Linux binaries I can still run because I thought to statically link them at the time.

Next best thing is to statically link everything but the system library.

$ otool -L dump1090
dump1090:
	/tmp/rtl-sdr/build/src/librtlsdr.0.dylib (compatibility version 0.0.0, current version 0.0.0)
	/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 159.1.0)

OK, so librtlsdr was dynamically linked. I’m not sure how to tell clang to statically link just this library. I bashed around listing .a files on the linker command line and ended up here:

$ clang -g -o dump1090 dump1090.o anet.o /tmp/rtl-sdr/build/src/librtlsdr.a /usr/homebrew/Cellar/libusb/1.0.9/lib/libusb-1.0.a
Undefined symbols for architecture x86_64:
  "_CFDictionaryCreateMutable", referenced from:
      _usb_setup_device_iterator in libusb-1.0.a(libusb_1_0_la-darwin_usb.o)
  "_CFDictionarySetValue", referenced from:
      _usb_setup_device_iterator in libusb-1.0.a(libusb_1_0_la-darwin_usb.o)
...
  "_objc_registerThreadWithCollector", referenced from:
      _event_thread_main in libusb-1.0.a(libusb_1_0_la-darwin_usb.o)

Apparently linking by naming the .a suppresses the linker’s walking of library dependencies, so now I’m not getting some of the basic system stuff expected by libusb. I tried exploring what libraries were needed with otool -l and failed. I’m doing this wrong.

software radio playing

I bought a cheap software radio to plug into my Mac. I have no idea what I’m doing and no proper antenna, but just bashing around with gqrx I’m able to listen to FM radio and understand roughly what’s going on.

Even better, I just got dump1090 running; it’s a decoder for 1090S airplane transponder signals. Even better I happened to catch Air France 083 from San Francisco to Paris, a flight I’m happy to say I’ve been on myself a few times! I’m amazed at how fast they send data, many reports a second.

Getting the software working on my Mac wasn’t too hard. I installed libusb via Homebrew, then compiled librtlsdr from sources. Didn’t install that, just hacked the dump1090 Makefile to find stuff in /tmp or wherever it happened to be. My modified Makefile plus some sample output below.

Update libusbx may be a better choice than libusb. And rtlsdr is packaged in a HomeBrew fork you can tap for GNU Radio.

CFLAGS=-O2 -g -I/tmp/rtl-sdr/include/ -Wall -W `pkg-config --cflags librtlsdr`
LIBS=-L/tmp/rtl-sdr/build/src/ -L/usr/homebrew/Cellar/libusb/1.0.9/lib/ -lrtlsdr -lpthread -lm

$ ./dump1090 --interactive
Hex    Flight   Altitude  Speed   Lat       Lon       Track  Messages Seen .
--------------------------------------------------------------------------------
ac4d44          0         0       0.000     0.000     0     5         48 sec
a78dd7          0         0       0.000     0.000     0     28        17 sec
a8b805          10950     0       0.000     0.000     0     146       3 sec
3965a9 AFR083   11875     346     37.890    -122.348   48    608       23 sec

$ ./dump1090
CRC: c3e472 (ok)
DF 0: Short Air-Air Surveillance.
  Altitude       : 11300 feet
  ICAO Address   : a26fc9

*00c1879c1bd991;
CRC: 1bd991 (ok)
DF 0: Short Air-Air Surveillance.
  Altitude       : 11300 feet
  ICAO Address   : a26fc9

*00c6079cc3e472;
CRC: c3e472 (ok)
DF 0: Short Air-Air Surveillance.
  Altitude       : 11300 feet
  ICAO Address   : a26fc9

*59a26fc99c4306;
CRC: 9c4306 (ok)
DF 11: All Call Reply.
  Capability  : Level 2 (DF0,4,5,11)
  ICAO Address: a26fc9

$ ./dump1090 --raw
Found 1 device(s):
0: Realtek, RTL2838UHIDIR, SN: 00000001 (currently selected)
Found Rafael Micro R820T tuner
Max available gain is: 49.60
Setting gain to: 49.60
Exact sample rate is: 2000000.052982 Hz
Gain reported by device: 49.60
*8d4005e2583d0135f7fdf5514966;
*02c18790ae0146;
*8d4005e2200815f2e37820027da5;
*02c18790ae0146;
*8d4005e2583d04ca30ac60c73091;
*02c18790ae0146;
*20000790eda525;
*02c60790763ca5;
*5d4005e2dd7ccb;
*02c18790ae0146;
*02c18790ae0146;
*8d4005e29900c99d28060e63ed38;

Here’s a screenshot of GQRX while tuned to 1090MHz. I think there’s at least one airplane transmitting when I took this; hard to be sure. There’s some horizontal lines that I’m guessing are the signal. It’s so faint above the noise floor, I’m sort of amazed it works.

Screen Shot 2013-04-24 at 8.48.13 AM

case insensitive filenames on Macs

What clown decided to make a Unix with case insensitive filenames? Oh, Apple, that’s who. I mean seriously? It’s tripped me up twice in the last day. To be fair there is an option to make a case-sensitive filesystem on Macs, but so much application software breaks if you do that it’s not a viable option.

I happen to think case-insensitive systems are generally better for humans to use than case sensitive. But Unix file systems have been case sensitive for over 40 years. Grawr.

TileStache: crappy CGI timings

I made the mistake of doing a bunch of testing of TileStache with the simple Python CGIHTTPServer. It’s a great little test apparatus, but it’s single threaded. Also it’s slow by itself.

  • CGIHTTPServer: 750ms to load a single tile, 10,000ms to load a whole map with 24 or so tiles
  • Gunicorn with 4 workers (sync): 650ms to load a single file, 2154ms to load a whole map.

Some comparisons on Gunicorn settings to load a map with 24 tiles.

  • 1 worker, default sync worker: 4800ms
  • 2 workers, default sync worker: 2500ms
  • 4 workers, default sync worker: 2300ms
  • 24 workers, default sync worker: 1700ms

Interestingly the gevent worker seems slower, also more variable. OTOH it’s necessary if you’re serving GUnicorn direct to the web, without a proxy in front.

The backend server is mostly waiting on IO to Postgres, it’s no surprise doing that in parallel will be better. All on a single 4 core 2012 iMac with some SSD-backed storage. I should add I’m doing this all without benefit of any caching, so it’s all kind of fake.

 

faking out remote syslog via netcat

Here’s how to create UDP syslog messages via nc, netcat:

echo ‘<14>sourcehost message text’ | nc -v -u -w 0 localhost 514

Replace localhost with the syslog server, of course. “sourcehost” is a string identifying the source; can be anything. The 14 is a combination of the severity (low 3 bits) and the service (high N bits). 14 = 8 + 6 which means “user message, informational”. RFC 3164 has the relevant detail. The syslog protocol is remarkably ad hoc; you can leave out the priority and it should still work. And there’s a provision for adding timestamps to the source message too. Note that syslog may suppress duplicate messages, so that may be why subsequent tests don’t show up. Unfortunately the BusyBox version of nc bundled in to Tomato doesn’t have the -u flag.

I’m doing all this to try to debug Apple’s disastrous syslog server. It has some insane binary config file to enable remote logging, and then they couldn’t leave well enough alone with syslog so they had to rewrite the whole thing with aslmanager, a daemon so awesome that most of the Google search results for it are “why is this process taking 99% of my CPU?”. It is open source at least. Anyway, asl.conf has its own different format. And then it doesn’t fix the #1 problem with syslog, which is there’s no way to log the IP address of the originator of the message. Argh!

This annoyance may be the last straw for me trying to use MacOS as a Unix server. There’s just no good reason to leave the warm embrace of Linux / Ubuntu. A quick look suggests Ubuntu 12.04 will work fine on a late 2012 Mac Mini, albeit with some required hackery for the ethernet driver.

PostGIS upgrades in Debian / Ubuntu

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

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

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

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

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

create extension postgis
create extension postgis_topology

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

Vector tile river maps

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

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

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

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

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

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

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

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

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

Screen Shot 2013-04-12 at 2.06.57 PM

Screen Shot 2013-04-12 at 2.11.40 PM

importing an ESRI shapefile to PostGIS

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

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

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

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

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

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

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

Copying a giant file with resume on error

General rule: any computer task that takes more than an hour must be done in a way that allows resuming if aborted. So, how to copy a giant file?

rsync --partial --append --progress --bwlimit=300\
nelson@wi:~/nobackup/geodata/planet-130327.osm.pbf .

Both the --partial and --append are necessary; the --partial tells rsync not to delete when aborted, and --append tells it to pick up where it left off the next time. There’s more subtle options available too.

Python startup time

Wow, Python startup time is worse than I thought. Here’s some data from a fast Ubuntu box. I ran all commands a bunch of times to warm caches.

$ time python2.7 -c 1

real    0m0.015s
user    0m0.012s
sys     0m0.000s

$ time python3.2 -c 1

real    0m0.026s
user    0m0.024s
sys     0m0.000s

$ strace python2.7 -c 1 2>&1 | wc -l
856

$ strace python3.2 -c 1 2>&1 | wc -l
1429

$ echo >| /tmp/empty.py
$ time python2.7 -O /tmp/empty.py

real    0m0.042s
user    0m0.032s
sys     0m0.008s
$ time python2.7 -O /tmp/empty.py

real    0m0.044s
user    0m0.032s
sys     0m0.008s

$ time python2.7 -S empty.py

real    0m0.004s
user    0m0.004s
sys     0m0.000s

$ strace python2.7 -S -c 1 2>&1 | wc -l
301

That last one’s a bit of a winner; -S means “don’t load site modules” and comes from this ExpertsExchange discussion. I lose /usr/local/lib; if I manually add that in my script I get my  minimal libgit2 program down to 6ms.

scripting language timings for libgit2

Was curious if I really need to use C to write this fast git prompt thing. libgit2 has bindings for many languages, but scripting startup time can really suck. Here’s a quick test of how fast a program can be that does nothing but open the repo (on Linux, local disk).

  • C: 1ms
  • Python 2.7: 17ms
  • Python 2.7 with -S flag: 4ms
  • Lua 5.1: 2ms

No surprise Python is so slow; even the null program is 14ms or so, a weakness of stock Python. Surprisingly there is no Perl binding listed; that’d be another option for fast startup. There is one for Parrot. Also Go, which could be a suitable modern upgrade for C.

Lua’s a fun little language, I should switch my development efforts there just so I have humane strings. Can always port back to C later.

All this testing is a huge PITA because the last stable release of libgit2 is 11 months old (0.17.0) and since then they’ve changed the API in all sorts of places. My C and Python tests area against the HEAD of the github repo. Lua is against 0.17.0. This lack of stability makes me question whether libgit2 is really the right choice for something as ubiquitous and lowlevel as a shell prompt. They aren’t kidding when they say it’s alpha software, I guess.

Doesn’t help that I was in dynamic linker hell, btw. On Linux it seems to cache things pretty aggressively; I had to manually run “ldconfig” as root to get it to switch from one version of libgit to another. I used to be good at this sort of nonsense but it’s been years since I’ve worked in such primitive environments.

So, quick conclusion: Lua would work for development.

playing with libgit2

Following on my dorking around with bash prompts yesterday, I was wondering how fast one could write a program to query state from git for the command prompt. The minimal __git_ps1 function I set up there takes about 75ms to run; takes longer if I add more to my prompt. That function works by invoking git a bunch of times, maybe a custom C binary could do better?

I took a quick crack at it using libgit2. It’s been years since I wrote any C code and it was rough going. No exceptions, no useful string type, manually allocated and typed memory, ugh. Maybe I should break down and do C++. Anyway, I managed to scratch together something that prints out the branch name and hash for the current commit. With caches warm my program takes just about 30ms to run; compare 23ms for __git_ps1 if it’s only printing branch name, nothing else. Ouch, I’m slower!

Using set -x I can see what __git_ps1 is doing. The main command its forking is git symbolic-ref HEAD, which takes 10ms if I run it by itself. I wonder why my libgit2 based code is so much slower?

I still feel a custom C binary should be faster, particularly to support fancier output info. But it’s an awful lot of pain writing libgit2 code in C, I may not have the patience to press on.

Update: derp, my program isn’t slow because it’s slow. It’s slow because I was running it on my Mac off of an SMB mounted volume. If I copy my binary to local disk it’s faster than stock git as expected: 6ms vs. 10ms for git symbolic-ref HEAD. Duh.

One other note; I started playing with dtruss/dtrace to figure out what system calls the two programs were running. My code makes 135 system calls, stock git makes 178. My code opens 8 files, 3 of them from the repo (which is still SMB and therefore slow). git opens 14 files, 6 from the repo. It seems to be doing all the work on the repo files twice, not sure why. Anyway now I’m reassured my libgit2 approach could be more efficient.

#include <stdio.h>
#include <stdlib.h>
#include <git2.h>

void check_return(int rc, char * msg) {
    if (rc != 0) {
        fprintf(stderr, "%s. Code: %d\n", msg, rc);
        exit(1);
    }
}

int main(int argc, char ** args) {
    int rc;
    git_repository *repo;
    git_reference *head;

    // open the repository
    rc = git_repository_open_ext(&repo, ".", 0, NULL);
    if (rc == GIT_ENOTFOUND) {
        // No git repo; that's OK.
        exit(0);
    }
    check_return(rc, "opening repository");

    // find HEAD
    rc = git_repository_head(&head, repo);
    check_return(rc, "finding HEAD");

    int ref_type = git_reference_type(head);
    if (ref_type == GIT_REF_SYMBOLIC) {
        check_return(-999, "Cant handle symbolic targets");
        // git_reference_symbolic_target() or git_reference_resolve()??
    } else if (ref_type == GIT_REF_OID) {
        // Get the name
        const char * name = git_reference_name(head);

        // Get the hash
        const git_oid * oid = git_reference_target(head);
        char hash[7];
        git_oid_tostr(hash, 7, oid);

        // Print out what we've learned
        printf("%s %s", name, hash);
    }

    return 0;
}

git prompts for bash

I’m trying to learn more about git. I thought it’d help me to modify my bash prompt to include git status. Turns out theres lots of ways to do that. I want something simple and minimal, but maybe using color. For years my prompt has been a simple “(hostname) = “; don’t want to go crazy. (Why =? Because it doesn’t look like $ or # or %, the standard characters. I know it’s mine.) Here’s some options.

  1. Here’s a blog post with some minimal git additions to the prompt. It just invokes git symbolic-ref to figure out the branch name. Simple, easy to understand, there’s a zillion hacks like this. Here’s another.
  2. git-prompt.sh is a bash addon distributed with git that adds a shell function __git_ps1 that can be invoked from inside the shell to print state. This is as close as it gets to a “standard”. This blog post does a good job explaining it. The configuration is a mess. The code is quite complex and handles a lot of strange git situations I wouldn’t have realized were important.
  3. bash-git-prompt is a different approach that has a bit more info on the state of the repo. As nice as it looks, I’m not going to use something that invokes a Python script every time bash needs to print a prompt.
  4. GIT Prompt uses colors to convey repo state, sets the terminal title, etc. It’s a very fancy prompt, but it’s overkill for my purposes. I do like how it displays non-zero exit codes though, and it’s got a nice configuration mode.

Screen Shot 2013-04-06 at 4.34.05 PM

I settled on option #2, the “stock” git-prompt.sh. It seems to work pretty well. The biggest problem is that Ubuntu 12.04 has an old version that doesn’t support working via PROMPT_COMMAND, so there’s an ugly workaround. Also gotta love the quoting. Anyway, screenshot and configuration.

GIT_PROMPT_VERSION=`sha1sum /etc/bash_completion.d/git`
if [ "$GIT_PROMPT_VERSION" = 'c52dd44066a21660c8830f8e6bd700893e2f7569  /etc/bash_completion.d/git' ]; then
    BAD_GIT_PROMPT=1
fi

if [ -n "$PS1" ]; then
  # Figure out what prompt character to use
  P='='
  if [ $UID == 0 ]; then
    P='#'
  fi

  # Set traditional prompt
  PS1="(\h) $P ";
  PS2="> "

  # Set up git prompting if available
  declare -f -F __git_ps1 > /dev/null
  if [ $? -a \! $BAD_GIT_PROMPT ]; then
    PROMPT_COMMAND='__git_ps1 "(\h" \)\ '$P'\  " %s"'
    GIT_PS1_SHOWCOLORHINTS=1
    GIT_PS1_SHOWDIRTYSTATE=1
    GIT_PS1_SHOWUNTRACKEDFILES=1
  fi
fi

I have some concerns about running any commands at all from inside a bash prompt. First it’s notably slow, particularly on a cold cache. Even warm it’s a few hundred milliseconds, and every extra GIT_ status thing I enable makes it slower. Worse, prompt commands do bad things if the command fails. Particularly a problem if you’re inside a remotely mounted filesystem that’s hung. I don’t know if bash is smart enough to timeout commands called when printing the prompt.

Update: this prompt setup is intolerably slow for big repos like libgit2 on a network filesystem mounted via SMB from a Linux server to a mac client. I’m talking 1000-1300ms per prompt, a noticeable pause. With no GIT_PS1 environment variables (just showing branch), the git prompt takes 25ms. Adding GIT_PS1_SHOWDIRTYSTATE adds an extra 100ms. GIT_PS1_SHOWUNTRACKEDFILES is the big culprit, adding an extra 1200ms or so. No surprise, the underlying command git ls-files --others --exclude-standard is making calls to getdirentries64() for every directory, also processing .gitignore files all up and down the tree. Not sure there’s any way to make that fast on a network file system. Maybe that’s why they went through the trouble to let you override the environment variable in the local git config.

Unrelated, but also useful; git-completion.bash which adds smart completion support for the git command. Seems to rely on the bash-completion addon to bash, although the script itself is distributed with git. In Mac Homebrew it’s a separate file; on Ubuntu it’s rolled together with git-prompt.sh. Apparently that’s an upstream change from a year ago.

GitHub pull requests are too heavyweight

GitHub is a marvel. But it’s a PITA to submit pull requests. It’s too heavyweight; in particular you’re required to log in to GitHub and make a fork. Here’s what you have to do:

  1. Log in or sign up to GitHub
  2. Fork the project
  3. Check out your fork
  4. Manually “git remote add upstream”
  5. Create a branch
  6. Make your changes and commit them to the branch
  7. Push your changes back to GitHub
  8. Submit a pull request
  9. (time passes, you want to submit another patch)
  10. Pull changes from upstream to your local repo
  11. Push your merging of those changes back to GitHub
  12. Go back to step 5 for next patch.

The thing that really gets me is if I want to make a one line patch to a repo, I’m committing to creating and maintaining a fork. The necessity that I remember to pull changes from upstream and commit them if I ever revisit that project is particularly onerous. In practice I find myself deleting my forks after my pull request is done.

I’d really like to be able to do all this without GitHub, just using git’s native pull request support. Ie, let me just check out a copy of the master project (read-only), then make my changes locally and use some combination of git pull-request and git format-patch to upload my pull request to GitHub. But now that I look at it, maybe those tools aren’t robust enough. Not sure.

MacOS broken build between versions

Well this is fun; MacOS binaries built on MacOS 10.8 don’t necessarily run on 10.7. I tried copying some homebrew binaries between machines and got the useless error message “Illegal Instruction: 4”.

Turns out this is working as intended; by default clang is happy to build binaries that only work on the current OS, not older versions. Good discussion here. The fix is to build with -mmacosx-version-min=10.5 (or however far back you need to go). Homebrew doesn’t build with this flag, I imagine because their idea is you recompile code on every machine. That gets tedious with multiple macs on a slow network.

Breaking binary compatibility is a stupid thing.

 

SMASH JSON

D3 3.1 includes support for SMASH, a way to make subset builds of D3. One thing I use D3 a lot for is the XmlHttpRequest support, particularly d3.json(). Most people use JQuery for AJAX, but I like D3’s version, but in either case I don’t want a 100k library just for a wrapper for XHR. Anyway..

$ smash src/start.js src/xhr/*.js src/dsv/*.js src/end.js | uglifyjs -c -m | gzip | wc -c
2276

Just JSON support is only 1464 bytes compressed, but it’s nice to bring in the CSV/TSV parsing. It’s 12k unminimized. Nice way to build a minimal XHR library. Didn’t test that it actually works ;-P

e00 GIS format notes

Trying to work with the data files for this awesome Volcano map from USGS. They helpfully published their GIS data for free download; unhelpfully it’s in ESRI’s proprietary E00 format. Some notes.

An E00 file is a container for geography data with annotations like centroids, labels, etc. The volcano files also contain auxiliary .avl and .lyr files that seem to be graphical legend definitions, etc.

The format is mostly straightforward ASCII and somewhat documented. It’s a container format; inside it are geometries and other properties. The part I’m really interested in is the PAT section, which seems to have labels and auxilliary data for the geometries defined in the ARC section. I could probably fake out a join of my own from the ARCs to the PAT data without too much coding. To complicate things I think the geometries are line boundaries between polygons, like TopoJSON, and not the polygons themselves..

Couldn’t find any Python E00 code, but there is “version 0.05” of a Perl module.

QGIS can load an E00 file, but all it seems to do is grab the geometry as LineStrings. It loses all the metadata. It’s also super slow. Way faster loading the ARC shapefile that ogr2ogr generated. I forget, do shapefiles contain spatial indices by default?

Seth F wrote to tell me about avce00, a program that converts binary coverages to ASCII E00 and back. What’s a coverage? That’s ESRI’s name for “a bunch of spatial data with auxiliary data”, ie the bundle in the E00 file. The main thing it seems to do is covert between binary and ASCII E00; I don’t need it for the volcano data.

GDAL ogr2ogr has some E00 support. A simple ogr2ogr is doing a game job of creating multiple shapefiles with my data. It is terribly slow, 3+ hours on my 30 meg input file. But it does seem to convert the data. There’s a shapefile named ARC that contains the boundary LineStrings and a shapefile named PAL that doesn’t have any geometry in it, but contains the auxiliary data I care about from the PAT section.

Anyway, the ogr2ogr converted shapefile seems reasonable to work with. The properties for the main geometry table named ARC includes integer fields named FNODE_, TNODE_, LPOLY_, RPOLY_, BIMGEO_FN, BIMGEO___1 (copied? to UserId), and LINE-TYPE. There’s 21,563 rows in the properties table, and roughly 6745 unique LPOLY_ ids and an unknown but < 16578 unique BIMPGEO__1.

Meanwhile, the PAL table has 6744 rows with the fields I really care about: YEAR1 and YEAR2 as well as LABEL. It also has BIMPGEO_FN, which looks to be a unique ascending integer 1..6746 and a BIMPGEO__1 field, 0..6980. I’m betting one of those is a key I can join to LPOLY_ on the ARC table to associate the years and label to the geometry.

Animating CSS class changes with D3

In a previous blog post I discovered that using .style(“fill”, ...) to set colors was way, way slower than using .attr(“class”, ...) to just switch the class. Which is all well and good, but what if I want to animate the color change? Ie: not just switch from white to black but use D3 transitions to show the grey between? Here are some options.

Class hackery: create a bunch of CSS classes “grey0”, “grey1”, “grey2”, ... that are a ramp from black to white. Then set .attr(“class”, greyN) with a tweening function that uses the classes. Seems awfully inelegant and hard to get right, particularly when you consider nonlinear easing functions.

Stylesheet manipulation. You can grab the CSS stylesheet itself and modify it. I found one D3 example. I have read lots of admonishments that modifying the CSS is hacky, flaky,  and works differently in different browsers. No idea if this would be suitably fast; I can’t imagine browsers optimize this usage.

CSS transitions. Nominal support is pretty good, although I’m breaking my rule not to use vendor prefix CSS in my projects (stupid WebKit). Something as simple as rect { -webkit-transition: fill 0.4s } looks pretty good in Chrome. It does not look good in Firefox: it doesn’t seem to actually tween the color so really all you get is a 0.4s delay. No idea how it looks in Opera or IE. Oh well, I design for WebKit anyway.

CSS transitions have nice control over the easing function. However I don’t see any control over the interpolation, something that’s quite important and subtle when tweening colors. The spec says it interpolates in RGBA space which is just about the worst possible choice. Fortunately my example is tweening white and bright yellow, so I can get away with it, but a red to blue tween probably looks awful using CSS.

Optimizing zipdecode

Are there any good tools for profiling rich D3 webapps, testing the changes in Javascript, CSS, and SVG design for how much time it saves? The best I’ve come up with so far is inserting calls to Date.now() in my code and using console.log() to print numbers. It works, but it’s primitive.

Chrome’s Profile tool doesn’t help me much. The Javascript profiler does, actually, giving me detailed analysis of why something is taking so long. But that’s a forensics tool, what I need is a benchmark wrapper around what I’m doing, something like Python’s timeit. But I don’t want to measure just Javascript code; I’m more worried about the CSS selection time, the DOM manipulation time, the browser render time.

Anyway, my Zipdecode thing is too slow. I’d like to optimize it, in particular so the interaction on the user typing a zip code is faster (and ideally, animateable). My original code is intentionally naive: select all 40,000 dots and set their “fill” CSS style to a specific color. It’s bad:

    d3.select("#zipdots").selectAll("rect")
        .style("fill", function(d, i) {
            if (l > 0 && d.zip.substr(0, l) == selectedZip) {
                return selectedColor;
            } else {
                return unselectedColor;
            }
        });

This take 140ms to do the update (and 650ms for the initial render).

Short circuiting the logic test about d.zip.substr() reveals that very little time is spent doing that. Replacing the call to .style() with a call to .each() that doesn’t manipulate the style drops the time down to 6ms; all my time is spent modifying the style, not creating the selection and iterating through it.

So the problem is mutating the .style(); no big surprise, but I can measure it! Let’s see how I can change the code to be better.

The obvious thing to try is to set the CSS class instead of a style property. The drawback with classes is there’s no way to interpolate the color easily. More on this in another blog post. But it works great, dropping the update time from 140ms to 25-30ms. Feels much faster. I tried this two ways

.attr("class", function(d) { return zipSelected(d.zip) ? "selected" : "unselected" })

.classed("selected", function(d) { return zipSelected(d.zip); })
.classed("unselected", function(d) { return ! zipSelected(d.zip); })

The first way using .attr() is 25-30ms; the second way calling .classed() twice is about 40ms, probably all from the overhead of that extra iterative function. I don’t think there’s anything particularly wrong about using .attr() to set classes, and since it’s simpler and faster I’ll stick with it.

A whole different optimization is treating to be smarter about the selection, not select all 40,000 dots every time. The code is not efficient in one important way; if I change the selection from “94” to “941” only 30 dots really need to be updated, but I go ahead and modify all 40,000 dots. But I don’t much care about fixing that because the case I’m most worried about is going from “” to “9”, where a lot of dots need to be touch (at most 1/10th of all zip codes, about 4000 dots).

But apparently I’m wrong. A version of this pull request from Ziggy Jonsson drops my interaction time from 140ms to 20ms, even less if the user is selecting a very narrow range of zips like “9414”. The key improvement is he’s only modifying the dots that are affected. (In addition he’s avoiding some calls to d3.select(), but I think that’s a smaller effect). Works well, but for my tutorial purposes I don’t like how it maintains this giant cached list of  all possible zip selections.

Another way to achieve the same effect would be  to use the hierarchy of the DOM to model the hierarchy of zip codes. Ie: instead of all the dots being top level <rect> elements, have a <g id=”9″> that contains all the 9xxxx zip codes (and in turn a <g id=”94″> inside that, etc. This would allow me to select with precision just the dots that need addressing, and might make the slower .style() method acceptable. But it significantly complicates the code and I don’t feel like doing that now that I’ve got stuff running pretty well. If I do it might be worth not going for the full hierarchical thing, just break zip code dots into the 10 top level categories.

Fuck browser keyboard events

In the HTML5 era programming in Javascript with browser APIs is mostly a joy. But sometimes you find a rough edge, in particular keyboard events. My zipdecode example had a simple problem: ordinary number keys worked, but not the numeric keypad. Because I was using the event.keyCode field, this ancient bit of savagery that tells me what button was pressed as opposed to what the user typed and both 48 and 96 mean 0. So I thought I’d try to update my code to the modern HTML5 way. Some things I learned:

  • Here’s a very simple tool for exploring keyCode.
  • String.fromCharCode() sometimes works for translating keyCodes to strings, but not always.
  • Here’s a very detailed guide to keyboard event behavior in various browsers. A bit outdated. The QuirksMode guide also has useful info but doesn’t cover what’s inside the event objects. Also maybe this StackOverflow question and this one.
  • keypress is the synthetic event fired off indicating “a user meant to type this thing”. If you can use it, use it. However it’s not always fired off, depending on the browser. (Ie: no left arrow in chrome). Also you can’t use it to suppress default behavior like backspace navigation.
  • keydown is the low level event fired when the switch is depressed. if you preventDefault() the event, in Chrome it means keypress is never fired but in Firefox it is fired anyway. (I think; didn’t test carefully.)
  • Any of the following fields of the event object may contain what button was pressed: char, charCode, key, keyCode, which. Most docs say “which” is the reliable choice (except for IE), but MDN notes it’s deprecated and says you should use key instead. Only “key” is not implemented in Firefox. Ha ha! Also while these fields are likely to be fileld out in a keypress event, they’re less likely to be present in a keydown event.

I was going to finish this blog post with a summary of the right modern way to do things, but I don’t think there is one yet. Then I was going to say this is a temporary state of affairs, but most of the HTML5-era questions I’m reading date back to 2010 so, um, not new.

I suspect the browser API mavens are scared to touch keyboard events. Partly it’s hard to specify because of internationalization, and partly it’s hard to implement because of cross-OS compatibility issues. I’ll note that jQuery apparently doesn’t have a library to solve this once and for all, either.

Update consider the d3.keybinding.js library from MapBox, for the iD editor.

Extracting features from shapefiles

I tend to forget that ESRI shapefiles are more like databases than just bags of geometry. ogrinfo can extract features.

ogrinfo -geom=no -sql "select HUC_12,HU_10_NAME,HU_12_Name from WBD_Subwatershed" WBD_Subwatershed.shp

unfortunately the output is some terrible text format.

OGRFeature(WBD_Subwatershed):3
  HUC_12 (String) = 180703030303
  HU_10_NAME (String) = Lower San Luis Rey River
  HU_12_Name (String) = Pilgrim Creek

However it turns out using GDAL/OGR’s bindings to Python is relatively straightforward, even if the API is basically a straight-up rip of the C API. Decent tutorial is here.

import ogr

shapefile = ogr.Open("NHDPlusCA/NHDPlus18/WBDSnapshot/WBD/WBD_Subwatershed.shp")
layer = shapefile.GetLayerByName("WBD_Subwatershed")
for feature in layer:
    featureDefinition = layer.GetLayerDefn()
    for i in range(featureDefinition.GetFieldCount()):
        fieldDefinition = featureDefinition.GetFieldDefn(i)
        print fieldDefinition.GetName(),
        print "%s" % feature.GetFieldAsString(i)

curl / wget and gzip encoding

I had no idea that neither curl nor wget will accept gzip encoding. They’re totally ignorant of it! You can set an Accept-Encoding header manually to tell the server to compress, but then you’re on your own to decompress.

wget --header="Accept-Encoding: gzip" 
curl -H 'Accept-Encoding: gzip'

Update curl does have a --compressed flag that does the decompression for you.

Capturing backspace in D3 / Javascript

I wanted to bind backspace on a web page, for a special UI. Had a hell of a time; the default behavior of backspace is to navigate the browser back a page in the history and it’s not easy to override. but long story short:

// Interaction: handle keyboard events (keydown to capture backspace)
d3.select("body").on("keydown", key);

function key() {
    if (code == 8) {
        // Prevent the browser from going back in the URL history
        d3.event.preventDefault();

        // Do your thing here.
    }
}

Some things that don’t work: returning false in the event listener (it’s ignored), calling stopPropagation(), or binding keypress instead of keydown. Browser keyboard events are a total mess.

More TopoJSON / watershed maps

I played more with the California watershed boundary data and TopoJSON. Two nice treatments, online at least temporarily. A full-state static map in D3 with some mild interaction letting you change the depth of HUC codes used in coloring. And a zoomable map written with Leaflet that while HUC colored, emphasizes watershed boundary details over the hierarchical HUCs.

The Leaflet implementation went pretty well. The one thing that tripped me up is my watershed boundaries are stored as bunch of Geometry objects in a GeometryCollection, instead of Feature objects in a FeatureCollection. Leaflet’s GeoJSON support does nice things with FeatureCollections, letting you change the style and bind a popup for each Feature. It doesn’t seem to do that with GeometryCollections. I worked around it by just iterating through the GeometryCollection and adding each Geometry manually. But I wonder if TopoJSON should be emitting FeatureCollections instead? ogr2ogr on my source .SHP data emitted a FeatureCollection, but topojson generated a topology with an embedded GeometryCollection.

I had to regenerate the TopoJSON for the zoomable map with less simplification. 2.2 MB vs 1.4 MB, and it looks good at reasonable zoom scales. I realized too late I really should have changed the quantization from 10,000 to 100,000; but at this simplification level I can get away with it.

So that’s the result. It’s OK and a useful tool for exploring watersheds, but it’s not awesome. The file size and render times are awfully big. And the presentation is clumsy, I should do more.

Screen Shot 2013-02-19 at 6.01.27 PM Screen Shot 2013-02-19 at 6.01.45 PM

TopoJSON notes, watershed boundaries and HUCs

I played around with Mike Bostock’s TopoJSON today, a file format + Javascript library for efficiently encoding maps. It basically does the same thing as geojson, but gets amazing compression in part by identifying common line segments between polygons and only encoding them once (ie: draw the border just once) and in part by quantizing and simplifying all the data. It’s quite clever!

My test data is the Watershed Boundaries from NHDPlusV2; the California-only NHDPlusV21_CA_18_WBDSnapshot_01.7z (89MB) and the national NHDPlusV21_NationalData_WBDSnapshot_Shapefile_01.7z (1.7GB).

Converting

Converting the smaller file to TopoJSON was a snap, just

topojson WBD_Subwatershed.shp -p HU_10_NAME -p HU_12_NAME --id-property "HUC_12" >| ~/src/huc-map/WBD_California.geojson

The flags are to add some GeoJSON properties to the resulting data file.

Simplifying

Taking the default arguments, TopoJSON reduced my 89MB SHP file to a 9.3MB TopoJSON file. Not bad, particularly since the straight GeoJSON is 257MB. A lot of compression thanks to shared boundaries. But also quantization; by default the topojson tool quantizes data to 10,000 values; I’m not sure but I think that means “it’ll look right if your map isn’t more than 5000 pixels wide”.

But topojson doesn’t do any simplification by default. What if we add the -s flag to simplify? Here’s the file size for variants of the -s parameter (in steradians):

0.0001         1.0 MB
0.00001        1.0 MB
0.000001       1.0 MB
0.0000001      1.1 MB
0.00000001     1.4 MB
0.000000001    2.2 MB
0.0000000001   5.8 MB
0.00000000001  5.8 MB
0.000000000001 5.8 MB

To my eye, the 1.4 MB 0.00000001 version looks about right, at least on my 800x800 map. I’m not surprised simplifying to a gross accuracy like 0.001 doesn’t add much; the objects themselves are pretty small. Not sure why it tops out at 5.8 MB or almost half the size of no simplification; maybe the source data has some really silly little details?

Querying the JSON

Quick diversion; I wanted to query my JSON object, to see what the properties and stuff inside it were. Someone’s finally built a decent “grep for JSON”, jq, the “keys” function is particularly useful for exploring a JSON file. Some quicky bits:

# get all HUCs:
jq '.objects.WBD_Subwatershed.geometries[].id'

# get all properties:
jq '.objects.WBD_Subwatershed.geometries[0].properties | keys'

Big data

I foolishly spent half my afternoon trying to convert that 1.6 GB file for the whole country. TopoJSON is memory-hungry; the optimization it’s doing is global so it really wants to read everything in to RAM. Long story short, the main thing I learned is that just like a Java VM the V8 VM has a fixed memory pool that’s like 1 GB or something by default. The magic flag to node is ” --max-old-space-size”. If I set it to 5000 (MB) then the whole process seemed to want to take 10 GB and made my 8GB machine thrash. Unfortunately smaller numbers like 4000 or 3500 resulted in an out-of-memory error. Mike guesses I’d need 16 gigs of RAM to do the conversion. All sort of silly anyway; I’m not sure what I’d do with the giant resulting file.

On the way I learned a lot of ugly things about Mac memory management:

  • Activity Monitor reports an “inactive memory” number that’s complete nonsense. It’s supposed to be RAM available for other processes but it sat at 3GB while my user process was thrashing the swap. So either the VM is not letting me use memory, or else it’s not really inactive afterall. The “purge” command doesn’t really help here, btw.
  • The page ins / page outs numbers on Activity Monitor are hugely helpful. When it’s paging in at 30 MB/s (hard drive rate) you know something is bad.
  • The %CPU number is also useful. When thrashing my topojson process dropped to 25% CPU (from 100).
  • If you double click on a process you get some detailed data. The “memory” page is confusing; I kept ignoring the “virtual memory size” of the process when that turns out to be the most relevant number. That was the 10 GB that resulted in thrashing. The Real Memory Size never got over 6 GB despite having 8 GB of RAM; guess MacOS overhead is 2GB now.
  • The geniuses at apple renamed “vmstat” to “vm_stat” and made it work differently. But it’s somewhat adequate.

Drawing Maps

Haven’t gotten very far for actually making maps yet. I followed Mike’s Let’s Make a Map tutorial and got a maplike something up pretty quickly. Counties in red, watersheds in black outline. My main goal is to add some color interaction around the hierarchical HUC coding.

Screen Shot 2013-02-17 at 6.19.46 PM

Python 3 success

Wrote my first Python 3 program. I was trying to get a Python 2 program to read a CSV file and write it to sqlite3. Difficulty level: Unicode. After reading all the nonsense about how the Python 2 CSV module doesn’t really do Unicode but hey it’s OK it’s bytes and here’s a wrapper you can paste in your code, I got fed up and installed Python 3.

So far so good. My 20 lines of code ran exactly fine in Python 3 first try, with the benefit that Unicode didn’t suck. The only thing that really tripped me up doing things is that print is a function, not a statement, and that’s a very good change. I even tried out the new string formatting system, here’s an idiom for using locals() for quick debug printing:

print ("{date} {asin} {title}".format(**locals()))

My one concern is Python 3 co-existing with Python 2. The Homebrew install seems to name things “python3” and “pip3” and the like, so all is well? But the recommended “pip3 install --upgrade distribute” didn’t work; that fetched some version of distribute that’s not Python 3 compatible.

Now that I’m over this hump I hope to use Python 3 for more things.

IP address 0.0.0.0

The IP address 0.0.0.0 is often used to mean “all a machine’s IP addresses” or “all network interfaces”. If you configure a server to listen to 0.0.0.0 it listens on everything. If you specify 0.0.0.0 as some sort of IP restricting filter it usually applies to all addresses.

But what does 0.0.0.0 mean to a client? Surprisingly, connecting to http://0.0.0.0/ seems to work on both my Macs and Linux. On my Mac “route get 0.0.0.0” shows me it’s going to use my Ethernet interface, with a real IP address. On my Linux box “ip route get 0.0.0.0” shows it using the loopback on 127.0.0.1.

Looking at this because I need a shell script that prints out an IP address that is likely to work even if I’m remotely shelled in to something. Here’s a script I use to launch test web servers for webapp development:

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/"
}

Installing CHDK on a Canon S100 on a Mac

I wanted to install custom camera firmware CHDK on my Canon S100, using my Mac. It’s a bit tricky; basically you format the SD card with some funky proprietary byte set, then put a special DISKBOOT.BIN file on the card and the camera will load it on top of the baked in firmware. But setting up the card that way is tricky, you have to get the exact right CHDK version for your firmware, and there’s a bunch of conflicting instructions for the Mac. Here’s what worked for me. These are Java programs, they may work on any OS?

  1. Get ACID, a program to identify your camera firmware version by looking at any JPEG file. Run it and drag over a JPEG from your camera to identify the firmware. Then check “download stable CHDK fill build” and press “Download stable CHDK” to get the right CHDK version for your firmware. (There’s other ways to identify firmware version, but they didn’t work for me. It is essential you get the exact right CHDK version for your firmware. My camera is apparently 1.00E).
  2. Download SDMInst. If you’re on Mountain Lion get the special zip that runs sudo first.
  3. Run SDMInst. Drag over the “Stable CHDK” and select “Copy all files from”. Turn on “Make FAT32 bootable”, turn “debug on”.
  4. Press “Prepare Card”. Double check the volume name, then do the format and copy.
  5. Eject the card, flip the write protect switch on the card on, put in camera.
  6. Turn on camera. Be patient; hold down the on button for awhile. You should see the CHDK boot splash.
  7. Press Play and then Menu to see the CHDK menu. 

Having done all this, CHDK doesn’t do the one thing I really want; override Canon’s obnoxious requirement that any exposure over 1s is at ISO 80. Actually you can override it using the CHDK menus to set an exposure override but it’s a PITA; I just want my firmware patched so it doesn’t have that restriction.

I may still use CHDK just to set the camera up with a script to take continuous photos. (“Interval shooting”, I think they call it?)

OpenStreetMap iD editor

The new Javascript OSM editor iD is working on live data now. So I made an edit, adding a pond I know is there by tracing it on Bing. Works pretty well, it’s an impressive JS app. Interactivity is not great, need 30fps+ responsive user feedback to really feel right. But it’s an early alpha, I’m sure they’ll get there.

The CSS looks home rolled other than a stock reset. Here’s the third party JS libraries they use:

<script src=’js/lib/lodash.js’></script>
<script src=’js/lib/d3.v3.js’></script>
<script src=’js/lib/sha.js’></script>
<script src=’js/lib/ohauth.js’></script>
<script src=’js/lib/jxon.js’></script>
<script src=’js/lib/d3.typeahead.js’></script>
<script src=’js/lib/d3.geo.tile.js’></script>
<script src=’js/lib/d3.size.js’></script>
<script src=’js/lib/d3.trigger.js’></script>
<script src=’js/lib/d3.keybinding.js’></script>
<script src=’js/lib/d3.tail.js’></script>
<script src=’js/lib/d3-compat.js’></script>
<script src=’js/lib/queue.js’></script>
<script src=’js/lib/bootstrap-tooltip.js’></script>
<script src=’js/lib/rtree.js’></script>

 

Notice what’s missing? A typical slippy map library like Leaflet or OpenLayers. He’s using D3 instead. I hadn’t realized how far along d3.geo.tile has come. Works pretty well on iOS too!

In addition to D3 there’s Lo-Dash (an Underscore alternative), SHA and OAuth (for login), JXON (for XML parsing?), Queue (for async), Bootstrap tooltips, and the RTree data structure for spatial lookups.

CGI and ISO-8859-1

Oh, the shame, look at the mojibake that showed up in the Atom feed for my real blog:

In detail, what happened… I get

From⎵ SMTP envelope

 

As opposed to

In detail, what happened… I get

From⎵ SMTP envelope

 

A quick wget -S ‘http://www.somebits.com/weblog/index.atom’ and I found the Atom feed was setting “Content-Type: application/atom+xml; charset=ISO-8859-1”. Like some cretin.

I have no idea why this charset was getting set. My ancient blog software (Blosxom, with a third party Atom plugin) doesn’t seem to be setting the charset explicitly. My best guess is that either Perl or Apache’s CGI helpfully inserts ISO-8859-1 as a default if nothing was explicitly said. Anyway I kludged the problem away by creating blosxom/entries/content_type.atom with the contents “application/atom+xml; charset=UTF-8”.

The Atom document itself specifies <?xml version=”1.0″ encoding=”utf-8″?>. Annoyingly Google Reader seems to believe the HTTP transport charset over the document itself. I have no idea what the spec says you’re supposed to do in this scenario, but I bet 9 times out of 10 the document is more correct than the server.

UTF-8 only, ever, and always.

 

HTML5 template with D3 and Leaflet

I’m often making D3 pages, or Leaflet maps, or some fancy Javascript thing. I always start with a blank editor and then have to remember all the HTML 5 boilerplate. So here’s some boilerplate, a template for starting a D3 + Leaflet project. The browser window is filled with the map.

This validates HTML 5. I’m not confident I’m setting the viewport correctly but this looks right in Chrome, Firefox, and Mobile Safari so good enough for me. I hate that HTML has so much boilerplate associated with it. Update: Mike points out HTML 5 doesn’t require so much boilerplate; tags like head and body are now optional. I don’t know what that means for old browser compatibility though so I’ll stick with the extra words. (Useful reference.)

<!DOCTYPE html>
<html lang="en"><head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0"/>

<title>Leaflet template</title>

<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.5/leaflet.css" />
<!--[if lte IE 8]>
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.5/leaflet.ie.css" />
<![endif]-->
<script src="http://cdn.leafletjs.com/leaflet-0.5/leaflet.js"></script>

<script src="http://d3js.org/d3.v3.min.js"></script>

<style type="text/css">
html, body { height: 100% }
#map { min-height: 100%; }
body {
    margin: 0;
    font-family: Helvetica, Arial, sans-serif; font-size: 12px;
    overflow: hidden;
    background-color: #f00;
}
</style>

</head><body>

<div id="map"></div>

<script type="text/javascript">
var map = L.map('map');
map.setView([37.7504, -122.4425], 13);
var basemap = L.tileLayer('http://{s}.tile.stamen.com/toner/{z}/{x}/{y}.png', {
        attribution: '<a href="http://content.stamen.com/dotspotting_toner_cartography_available_for_download">Stamen Toner</a>, <a href="http://www.openstreetmap.org/">OpenStreetMap</a>, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
        maxZoom: 17
});
basemap.addTo(map);
</script>
</body></html>

Raspberry Pi notes

Raffi gave me a Raspberry Pi, the $35 ARM based Linux system. Capable little beast: 256MB RAM, 700MHz ARM processor, a GPU that can drive 1080p and decode video, it’s an interesting device. Some notes:

Hardware

Batteries not included. In addition to the board itself, I needed:

Hilariously the whole machine reboots when I plug in the WiFi adapter; my guess is a power problem. It boots fine once it’s plugged in though.

RAM is shared with the GPU. The split is (now) configurable, so I have 192MB system RAM and 64MB GPU RAM. Newer boards have 512MB on board.

Software

The primary software distribution people use is Raspbian, a giant 1.5 gig full Debian system. It’s cool that you get a full normal Unix system but boy are we a long way from an embedded OS. The architecture is “armhf” with a change, using hardware floating point in the ABI. Apparently there’s several incompatible Debian ARM versions running around; armel, armhf (soft float), armhf (hard float), etc.

There is no BIOS on the board and no LILO or GRUB bootloader has been ported to the Pi yet. The bootstrap expects a FAT filesystem that it can execute a kernel off of. Raspbian has a small FAT partition with a kernel and then a big ext4 partition for the rest. There is an effort for a bootloader called Berryboot but it boots off of SquashFS filesystems which AFAIK are read only. Haven’t tried it.

Raspbian out of the box works well. Username: pi, password: raspberry. You’ll want to use rsapi-config to set the keyboard if you have a US keyboard.

The main thing I had to do was set up wifi, which uses wpa_supplicant. I found this example config file helpful. End of the day, all I needed to do to get wifi working was add the following little block to /etc/wpa_supplicant/wpa_supplicant.conf. (Note, both my SSID and password are wrapped in quotes for the config file.)

network={
  ssid="mySsid"
  psk="my password in quotes"
}

Voila! With all that set up I now have a working underpowered Linux box. So what is this thing actually good for? To me what’s most exciting is the HDMI output; it can drive a TV! To that end I found two possible end uses. OpenELEC, for viewing videos via XBMC. Or MAME/MESS for playing games.

MAME

So what about MAME? My first try was PiMAME 0.3, a full distribution that boots right into AdvanceMAME for a chooser. Looking at it, it’s basically Raspbian with some extra software installed and a login script to launch MAME. (An annoying one, I might add; it’s awkward to get a shell and virtual consoles don’t seem to work). Also the setup isn’t usable with just a USB joystick now, you really need a keyboard to drive both AdvanceMENU and AdvanceMAME itself. Full props to the PiMAME author for working on a convenient turnkey distro, but it’s not there yet. I think I’d rather use a plain Raspbian distribution and build up my own MAME environment, using his packages.

So how to install by hand? I followed notes from this blog post, skipping over the “how to use Unix” parts and getting right to MAME. In a nutshell:

  • Install the AdvanceMAME .deb by hand, downloading from http://sheasilverman.com/rpi/raspbian/debs/
  • Create a MAME user strictly for running MAME. Put it in group video
  • Launch “mame mspacman” from a local console to play a totally legitimately acquired copy of the Ms. Pac-Man ROM.

It works! It’s very slow compared to PiMAME 0.3; I imagine I’m running into the same problem the PiMAME guy is having with the most recent raspbian distributions. Also I haven’t tried sound yet. And AdvanceMAME is some 7 years old; in theory the mainline MAME 0.147 should work on Raspberry Pi but the details of getting SDL and Sound working in this environment are rumored to be difficult.

Thoughts

The Raspberry Pi is an impressive little device. For the size, power (3W), and price it’s amazing to have a full real Unix distribution. I’m not sure what it’s actually for though. Its creators talk about education, about giving kids an affordable hackable platform. I think that’s awesome but is this really it? Maybe so, but I’d think a discarded PC would be just as good. Or something with a portable screen and input method.

As a general purpose hack thing it’s a lot of fun. What’s missing though is some sort of hardware bridge, say Arduinio.

As an embedded device it’s impressively capable. It’s nice to imagine building a whole Internet TV device on it, for instance, with a full real Unix behind it and not having to fart around with an embedded OS or iOS or something. I’m sure there’s drawbacks, but..

I’m trying to get my head around having a full Debian system on this. I’ve been conditioned to think of embedded devices as black boxes; you flash the firmware every six months and then run what’s there, no upgrading or changing. Raspbian feels more like a persistent OS to me, something I’m going to add and upgrade and change rather than wipe and start over regularly.

Uninstalling Evernote on a Mac

The official uninstall instructions for Evernote on a Mac are incomplete. They just say “trash the Application”. But that leaves behind a launchd entry that every 10 seconds tries to launch EvernoteHelper, now missing, and spams the syslog and creates lots of useless crash reports.

Anyway, the fix is to run launchctl remove com.evernote.EvernoteHelper as the user you installed Evernote as. (Not root!)

launchctl/launchd is a total mystery to me. It seems awfully complicated. “launchctl list” and “launchctl bstree” are helpful commands for inspecting the state of what’s trying to launch.

Not getting gigabit ethernet

I’m not getting gigabit ethernet at home between my Linux box and my iMac. Some previous notes suggested I got 30MB/s, at least once, so maybe this is a new problem?

I tested by running dd if=/dev/zero bs=16k count=10000 | nc -l 9999 on the Linux server and running time nc 192.168.0.65 9999 > /dev/null on the Mac. That took 13.9 seconds for the 164 megabytes, for a throughput of 11.7 megabytes = 93.6 megabits/second of useful data transfer. (MenuMeters measured 11.7MB/s as well; dd claimed 9.8MB/s, but there was a delay in starting the client). Figuring TCP overhead that’s clearly running at 100Mbps, not gigabit.

The server is my Linux box with the onboard Realtek chip (which has some issues). ethtool reports it’s running at 1000Mb/s, full duplex.

The client is my 2011 iMac with some Broadcom chip. WiFi totally turned off. MenuMeters and Network Utility both report Gigabit.

The switch is a Netgear GS116 gigabit switch. It’s unmanaged, so I don’t have much insight into what’s going on. Only one set of blinking lights on the switch indicates gigabit speed, so that’s my problem; either the Mac or the Linux box didn’t negotiate gigabit but is lying about it in the ethernet driver.

Come to think of it, this Mac has been flaky on the ethernet for awhile now, it sometimes takes minutes to come up after resume from sleep. I bet something’s gone wrong with the port or the cable and I’m only capable of 100 megabit now. Wish I had some way to diagnose it.

(the difference between 100mbps and 1000mbps is noticeable when transferring large files. The disk is capable of about 250mbps.)

Update looking at the blinking lights I figured out my Mac really has gigabit at the switch, but the Linux box didn’t. Then I looked closer and realized my Linux box had gigabit too, but only to the small gigabit switch sitting in the closet with it. The upstream link from that small switch to the main big switch was 100 megabit. Weird. Rebooting the small switch fixed it. Confounding issue: I have a 100mbps printer plugged in to the small switch. It doesn’t seem to be disrupting my gigabit right now.