Some Bits: Nelson's log

16 posts in March 2011

Compression

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

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

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

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

Optimization

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

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

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

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

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

 

Headless SVG rendering part 2

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

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

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

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

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

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

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

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

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

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

Samba: get rid of stupid executable files

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

 

forking a branch on github

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

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

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

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

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

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

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

Headless SVG rendering

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

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

To run it:

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

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

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

WingIDE 4.0 problem with Python 2.7.1 on Windows

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

Javascript dictionary key types

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

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

string

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

z[null] = "foo"

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

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

D3 and IE9

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

gzip encoding, Chrome dev tools bug

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

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

 

using git on Windows via SMB

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

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

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

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

Very simple python logging

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

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

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

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

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

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

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

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

Compare:

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

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

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

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

What’s new since Python 2.2?

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

Language

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

Libraries

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

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