Some Bits: Nelson's log

97 posts about python

Python packaging, pytest, click, VS.Code

I’m working on my blog engine. I want to package it nicely as a Python package. I also want to be able to run my code from a command line using the click library, and write and run tests using pytest, and be able to do all this with the debugger in VS.Code. I’ve never made my peace with Python packaging, for many many years now I’ve avoided it. Because it’s a mess.

Anyway I just tried again here in April 2024 and more or less succeeded in just an hour or so. This is where I would write clear docs with a github repo with the code but.. nah. I’m not confident it’s right and I don’t understand it well enough to present coherently. But I’ll write up what I learned.

I mostly followed the Packaging Python Projects tutorial which explains the creation of this sample project. Following that gets you a basic Python project which you can install with pip install -e. The key thing here is everything’s driven by the pyproject.toml file. If you are reading any docs that talk about setup.py they are old and outdated; the TOML is the new way.

Some subtleties in the pyproject.toml:

  • My project has dependencies that I specified in the TOML. It depends on pytest and click.
  • I had to pick a build backend; I’m using setuptools as the old non-fancy default.
  • My project has console scripts. You can specify these in entry points or in a scripts section.

Getting click working was not hard. There’s docs for click + setuptools. Note these are in terms of the old setup.py style but translating to pyproject.toml isn’t too hard.

Here’s my source tree for a toy package called “whir”

  • pyproject.toml in the root directory
  • Python code in sys/whir/.
  • src/whir/__init__.py that imports all the public functions, particularly the click commands.
  • src/whir/lib.py is simple library code that other stuff imports.
  • src/whir/main.py contains a main_cli() function that’s a click command. __init__.py imports it so it can be used as a script in pyproject.toml. It also imports the lib code via import whir.lib, not a relative import.
  • tests/test_lib is a pytest function that tests the lib code. It imports it with from whir import lib.

Getting pytest working was not hard either. The default setup worked just fine from a shell. Getting it to work inside VS.Code’s extension for it required adding something to pyproject.toml to get pytest to use importlib, as described here. But now I can just press a button the IDE GUI and all my tests run with a nice display. Yay!

Getting the VS.Code debugger to work with click was tricky. AFAICT there’s no easy way to get VS.Code to invoke a click command. But there’s a hack where you call the click command with string command line arguments inside a if __name__ == '__main__'; then VS.Code can be used to just debug the file and it will work.

Edit: thanks to Claude I’ve now found two more ways to invoke a click command from a function. The intended way to just invoke it is to use main_cli().callback(args): the click decorator adds a callback function to the command function you can use. There’s also a whole library for testing invocation of Click commands, CliRunner, that will mimic a command line call. It sets up a special environment that captures stdout and stderr, can mock up a filesystem, etc. It’s for using in a unit test framework.

Ranting reflection

It all worked pretty straightforwardly! But I have no idea at all how it works. If something goes wrong I won’t understand what is happening or how to fi x it. And the tools are creating little files and shims that get between me and my code. It’s always like this with packaging and build systems and I hate it.

Live reloading HTTP servers

Pressing reload in a browser while developing a web page is for chumps! A very popular trick is to serve the site under development with a special server and put a little Javascript in the page to get a reload signal when it should reload. Saves a lot of time, I love live previews.

five-server is the most mature tool for this I could find. It’s written in Node but you can run it as a standalone server unconnected to the code you’re developing. This is a fork of an older live-server that was abandoned. There’s a VS.Code version too that has some integration that looks useful if you’re editing HTML files.

LiveReload is a Python server to do the same thing. It has a Python API so you can integrate it with your own Python code to help while developing a webapp. I hit a confusing problem because of less-than-robust error handling related to my malformed HTML input (the script injection failed) but it seems to work well.

There must be a zillion other tools that do the same thing.

Markdown processing in Python

I’m mad enough about Hugo I spent an hour writing a very minimal blog engine. Lots to go to make it usable, but as a piece of it I had to look for a Markdown processor for Python. Here’s what I’ve found, there are probably more. I want something that supports CommonMark and has a decent extension story. (A lot of folks support GitHub flavored markdown, perhaps that’s coherent enough to also be reasonable.)

mistletoe. 652 GitHub stars. I’ve used this already and it works but haven’t gotten in deep. Docs and PyPI niceties are not great. Says it’s the fastest implementation but all of these are pretty close (except Mistune which is way faster). Supports rendering to other targets like LaTeX, not just HTML.

markdown-it-py. 517 GitHub stars. Looks comprehensive, has a bunch of plugins. It’s a port from NodeJS code. Plugin code looks pretty complicated.

mdformat. 263 stars. Has plugins and code is connected somehow to markdown-it.

marko. 249 stars. Says it has very easy plugins and is not very fast but correct.

Mistune. 2300 stars. Not CommonMark but maybe reasonably so. Very fast. Plugins look awkward.

Not CommonMark: Markdown, Markdown2,

No real conclusion here. I’ll stick with mistletoe since I already have it working, then look to jump when I get to the part where I need my own plugins. marko or Mistune look most promising to me if mistletoe won’t work.

Update: some very simple evaluation

I did some quick tests comparing mistletoe, marko, markdown_it, and Mistune.

The output of all three were substantially similar. mistletoe emits actual ” ASCII quotes whereas the other two are outputing ". Which reminds me I need to enable typographic quotes.

Some very simple benchmarks show mistletoe and markdown_it takes 2-3x as long as mistune, marko is about 4x.
timeit 9000 byte input: mistune (1.13ms), markdown_it (2.78ms), mistletoe (3.60ms), marko (4.84ms)
1800 HTML posts: mistune (490ms), mistletoe (860ms), markdown_it (925ms), marko (2000ms)

Update 2: markdown_it

After reading docs and setting up typographical quotes I think I’ll go with markdown_it. I was turned off at first because it was a NodeJS port and its code seems quite complicated, they really want to explore details of parsers, ASTs, renderers to you. But it does typographical quotes right! And it’s fast and popular. Now that I’m over the learning hump it seems a good choice. I haven’t tried writing a plugin for it yet though.

Python venv brittleness (with fix?)

I just upgraded from Ubuntu 22.10 to 23.04. Which means I upgraded from Python 3.10 to 3.11. Which means all my old Python programs don’t work anymore. Because each has a virtual environment and the venv is hardcoded to Python 3.10.

Am I doing it wrong? Yes, I was doing it wrong.

In the old days I’d create a venv with a command like python3.10 -m venv venv. This results in a venv/bin directory where python3 is a symlink to python3.10 in the same directory, which in turn is a symlink to /usr/bin/python3.10 (which no longer exists).

Awhile back I changed to running python3 -m venv venv. This results in all the binaries in venv/bin being symlinks to python3, which in turn is a symlink to /usr/bin/python3. That should be robust to upgrades. And Python is good about backward compatibility so using 3.11 to run a venv built for 3.10 should mostly be fine.

FWIW the docs just have you invoking python on the command line, so I guess that’s what the intended usage was. More generally it looks like venv is doing its best to set up an environment with the exact same Python pathname you used to create the environment, which seems reasonable enough.

Python and Ubuntu versions

I’m upgrading from Ubuntu 20.04 to 22.04 which means Python versions are changing. Ubuntu 20.04’s last version they distribute is Python 3.9. Ubuntu 22.04 starts with Python 3.10. My own code isn’t particularly version sensitive but venv makes it a mess. I’ve chosen to go ahead and move to Python 3.10 for everything.

My main problem is when you create a virtual environment it’s locked to a specific verison of Python. All venv is doing is installing stuff to venv/lib/python3.9 or whatever. If you created the venv in python3.9 and try to use it with python3.10, it will not work. So you have two choices: either rebuild the venv for the Python version you have, or install the Python version the venv was set up for.

Installing Python versions is very easy thanks to the deadsnakes PPA. They port older and newer versions of Python to older and newer Ubuntu. Their 3.10 build works just fine in Ubuntu 20.04.

The other problem is the venv needs to have been set up to invoke the right Python binary. If you create a venv with python -m venv venv, then the important symlink in venv/bin/ will be to /usr/bin/python. No version number. But the rest of the venv is version specific, so that’s really the wrong thing. The solution is to create the venv with python3.10 -m venv venv. That way the symlink for the binary is to /usr/bin/python3.10 which will work whatever a system’s default Python version is. Also pays to be careful with pip; I now invoke pip as python3.10 -m pip instead of relying on /usr/bin/pip or whatever.

Here’s my “create venv” bash function now

python3.10 -m venv venv;
source venv/bin/activate;
python3.10 -m pip install -U setuptools pip wheel

Reading a file inside a zip as text in Python 3

I have a zipfile. It has a text file inside it. I want to read the first file as text. Here’s how to get a file-like object that has a text stream.

with zipfile.ZipFile(fn) as zf:
  data_fn = zf.namelist()[0]
  bfp = zf.open(data_fn)
  fp = io.TextIOWrapper(bfp, encoding='utf_8_sig')

The tricky bit is all the last line. The problem is ZipFile.open returns a bytes stream. So you have to wrap it in TextIOWrapper to decode it to text. Also my source data has a Unicode byte order mark in it, so utf_8_sig is a magic decoder that will strip out the BOM if present.

This is very remedial Python but I had a hard time figuring it out.

Very simple Python ORMs

Starting a new project and want something to take the tedium out of a small sqlite database (like 2 tables, a few thousand rows). I don’t want to write wrappers for SQL to insert and select rows. OTOH I don’t want a complex ORM like SQLAlchemy or Django. What are my options?

  • Peewee. Well established, seems to be the consensus choice. Don’t love the code examples but they’re fine. Docs are good. Supports migrations.
  • PonyORM. The other frequently mentioned option. Has nifty metaprogramming so you can write queries in Python. But it does not support migrations.
  • Datalite. A very small binding between Python Dataclass types and sqlite tables. Docs are thin but code is small and readable. Supports migrations, surprisingly.

Based on my last project with SQLAlchemy, migration support is important. So that rules out PonyORM. Peewee and Datalite are very different in scale. I’ll start with Datalite and if it’s too limiting, consider moving to Peewee.

Update: Dan reminds me of PugSQL which is a wrapper for easy SQL execution in Python. Not really an ORM but does take the tedium out of simple SQL queries. And avoids ORM magic.

Python static blog generators

Once again contemplating moving my blog away from the ancient Blosxom setup I have. Static generators are clearly the way to go. Here’s what I found among Python options.

Pelican looks to be the most popular. Nikola is also compelling. Lektor may also be an option. Cactus and Hyde are abandonware.

I may also consider using Hugo. Go, not Python.

2d noise functions

Somehow I’ve done generative art experiments for 30 years without every really understanding noise functions. I mean I’ve certainly used some but never directly, generally by incorporating someone else’s noise-derived textures or something. So here’s some notes.

Noise functions

Processing’s noise function is probably how most generative artists first encounter noise. It is straight up Perlin noise, the classic 1985 algorithm. It’s defined for any number of dimensions but let’s just focus on 2D noise for now. You give it an x, y and it gives back a random number 0-1. The key feature of Perlin noise is it’s smooth; two x, y points near each other will have a similar value. Note there’s an implicit scale in Perlin noise; is (100, 100) “near” (0, 0)? Or do you have to go as close as (10, 10) or (1, 1)? This scale factor is not very interesting but you do want to dial in a scale that has features of the size you want. Perlin noise implementations often provide other tuning like how many octaves to calculate and how much each contributes.

https://64.media.tumblr.com/b62a80853b5aa8509c95c25cf3dc9b6d/tumblr_inline_pc0ohslzM81seaucq_500.png
Top: Perlin. Bottom: Simplex. Source

Perlin noise has a problem in that it’s somewhat directional; you can see horizontal and vertical artifacts in the top 4 images above. (Taken from this blog post). The bottom 4 images are similar treatments of OpenSimplex noise. Simplex noise is a different algorithm Ken Perlin made in 2001; see here for an explication. Unfortunately Simplex noise has some worry about a patent (expires January 2022!). So that’s why there’s OpenSimplex: it has similar features but was designed to be avoid the patent. (Patents on math: so stupid.) In addition to being isotropic both kinds of simplex noise are also faster to calculate.

FastNoise is really a collection of different noise functions with an emphasis on fast implementations. Includes Perlin, Simplex, and a bunch of other choices. The project is ambitiously multi-language and has several iterations as the author has supported SIMD first and then rewritten everything as FastNoise 2. Note the author Jordan Peck works on No Man’s Sky, one of the most ambitious procedurally generated videogames out there. It’s full of noise functions.

There’s a bunch of other noise functions out there too. Worley noise, Fractal noise, Gabor noise... It’s like after Perlin got an Oscar for his noise function everyone wanted their own ;-) There’s also a lot of work in making fast implementations, running on GPUs, etc. I’m getting in the weeds now so I’m just going to look at some simple things to use with Python implementations.

Python implementations

perlin-noise, a basic Python implementation of Perlin noise. Works with any number of dimensions.

OpenSimplex has a nice Python implementation with tests and everything. It defines 2d, 3d, and 4d functions.

noise, a native code implementation of Perlin noise and true Simplex noise. 1-3 dimensions for Perlin, 2-4 for Simplex. Also includes a GLSL implementation for shaders that I did not test. This code is mostly 9 years old! But there’s no reason that should matter for something this simple. Note it has no API support for setting a seed. You can override the entire random integer function though which would let you also control seeding.

pyfastnoisesimd is a SIMD optimized, parallelized implementation of FastNoise. There’s no simple API for generating a single sample; it’s designed to generate large grids of numbers all at once (very quickly).

I’m currently using OpenSimplex in my projects, mostly because it’s the first library I found. It’s easy to use and fast enough for me.

Benchmarks

I don’t really much care about speed in my applications but I was curious, so here’s some simple timeit statistics to generate a single 2d noise sample.

Constant
50000000 loops, best of 5: 0.00469 usec per loop
math.random()
10000000 loops, best of 5: 0.0359 usec per loop
OpenSimplex
100000 loops, best of 5: 2.34 usec per loop
perlin-noise with 6 octaves
5000 loops, best of 5: 90.6 usec per loop
noise.pnoise2
5000000 loops, best of 5: 0.1 usec per loop
noise.snoise2
5000000 loops, best of 5: 0.0844 usec per loop

So there you have it. About 0.1 microseconds per sample for the C implementations, 2.3 for OpenSimplex (Python), 90 for Perlin (Python). To it it another way, that’s roughly 10M samples a second for the C code. For comparison pyfastnoisesimd says it’s a few nanoseconds / sample, or 200M+ samples / second.

Using noise for art

Noise functions are just random number generators; how do you make art with them? Ha, as if there were a simple answer to that question.

I did make one simple demo that a zillion people have done; making a grid of OpenSimplex noise and then visualizing the number with a short line segment rotated by the noise value. You have to fiddle the scaling to get it to look interesting. Here’s a result that looks pretty nice plotted, although drawing all ~5900 line segments took 90 minutes.

Another classic plotter use of noise is to draw “flow fields”. It’s a simple physics simulation; you drop a particle at a point and then interpret the noise value as an angle of force. Then you draw the trace of the particle as its buffeted around your grid. I’ll probably do that next, it’s a classic with a lot of interpretations.

Seeds

An aside on seeds. It’s nice to use words as seeds instead of numbers. There’s a zillion ways to do that but one easy way to turn a string into an int is zlib.crc32(seed.encode('utf-8')). Note that’s a 32 bit int; 64 would be nicer. Oddly there are precious few 64 bit checksum and hash functions, I don’t think any are installed into Python by default.

Benchmark script

#!/bin/bash
TIMEIT='python3 -m timeit -p -u usec '

echo 'Constant'
$TIMEIT '0.13'

echo 'math.random()'
$TIMEIT -s 'import random' 'random.random()'

echo 'OpenSimplex'
$TIMEIT -s 'from opensimplex import OpenSimplex; os = OpenSimplex()' 'os.noise2d(1.1,1.1)'

echo 'perlin-noise with 6 octaves'
$TIMEIT -s 'from perlin_noise import PerlinNoise; pn = PerlinNoise(octaves=6)' 'pn.noise([1.1, 1.1])'

echo 'noise.pnoise2'
$TIMEIT -s 'from noise import pnoise2' 'pnoise2(1.1, 1.1)'

echo 'noise.snoise2'
$TIMEIT -s 'from noise import snoise2' 'snoise2(1.1, 1.1)'

Typesetting multiline text in SVG

Having worked on rendering text on my AxiDraw, the next question is how to typeset text. The challenge is SVG 1.1 text elements are explicitly single line, no automatic wrapping. There’s no text flow in an SVG renderer, you have to do it yourself. (SVG 2.0 promises to add this, and I guess there was an ill fated effort in SVG 1.2).

There is a nice way to express multiline text in SVG using the <tspan> element.

    <text class="verse">                                   
        <tspan dy="1.2em" x="10"
               >How doth the little crocodile</tspan>      
        <tspan dy="1.2em" x="10" dx="1em"
               >Improve his shining tail,</tspan>          
        <tspan dy="1.2em" x="10"
               >And pour the waters of the Nile</tspan>
        <tspan dy="1.2em" x="10" dx="1em"
               >On every golden scale!</tspan>
    </text>

Note the use of dy to do the line spacing; that’s nearly automatic. (the dx parts are for some fancy indentation. Not sure why x is being set explicitly every time.) All you have to do is decide where to break the lines! Ha.

There’s also some support for automated kerning with the textLength attribute.

I can’t find a Python library that will break lines for you or do more fancy automated typesetting. It is possible in Javascript, or at least you can write code to do it, using the getBBox() function to inspect the pixel size of some text and use that to break lines.

One approach in Python would be to calculate metrics for a font and then use that to estimate the width of a word. That won’t work if the kerning isn’t predictable. Also it’s a lot of work to do right for arbitrary fonts.

A second approach is to use something to render SVG in Python and use that to measure widths. Something like the pyrsvg wrapper for librsvg. That’s a lot of code to bring in though and I’m not confident it would perform very well. py3rsvg looks promising as a lighter / standalone option. See also this discussion.

A third option is to skip SVG text entirely and work directly with HersheyFonts generated paths in Python. The library has support for inspecting the width of glyphs; bounding box, etc. But this library is a separate work from the Evil Mad Scientist / AxiDraw code for Hershey text, the one that’s an Inkscape extension. They’ve done some nice work on fonts, etc so I’m not sure how much you’re giving up going with this other code instead. SVG Fonts, for one; I think the HersheyFonts library is using the actual Hershey format. That means no Unicode. I’m not sure the ESM HersheyText Inkscape code can be repurposed though, it seems to be written in a very Inkscape-specific way and relying on their renderer. I could be wrong about that though.

I think that last option may be best; it’s closer to the actual SVG I want to send to the plotter.

Starlink monitoring and hacking notes

Some collected information and what I’m doing about monitoring Starlink / Dishy’s performance. Note most of this stuff works with just Dishy, not the Starlink-supplied router.

Some facts

  • Dishy listens at 192.168.100.1 on ports 22, 80, and 9200. ssh, http, and gRPC. It also uses port 9201 for a different flavor of gPRC HTTP (for Android?)
  • The mobile app works by fetching web pages and/or gRPC data from Dishy.
  • Starlink’s router does gRPC on port 9000 and is the preferred source for the mobile app. It implements the ping interface, the thing that tells you your Fortnite lag.
  • You can view the stats direct from Dishy in any browser at http://192.168.100.1/support/statistics
    Note you have to open the browser window to max width; it’s formatting for the screen size, not window size.
  • Another Dishy URL: http://192.168.100.1/support/debug

Docs

Software

  • pinginfoview: nice lightweight Windows tool for testing if the connection is down
  • Starlink gRPC tools: Python code for reading gRPC stats off Dishy
    This seems to give very complete data from Dishy, including the history of dropped packets
  • dishyworld: a working dashboard based on Prometheus and Grafana.
    Has ambitious goals of collecting data from many users.
  • starlink-cli: Go code for getting Starlink data. I think it’s the base for dishyworld?
    This seems to give less data than the Python library above, at least by default
  • Better than Nothing Web Interface: a PHP dashboard
  • Better than Nothing stats: a mockup of a planned Javascript dashboard, successor to above
  • Obstruction view. Takes the debug info from Dishy about obstructions and draws it. I know the mobile app can do this but I can’t figure out how to do it again!
My obstructions

Starlink gRPC tools

This Python library seems to give more useful output than the other command line tool I could find so I’m pursuing it.
The full list of commands:
status, obstruction_detail, alert_detail, usage, bulk_history
ping_drop, ping_run_length, ping_latency, ping_loaded_latency

Be sure to read the code / docs for detailed notes on what all the fields mean. There’s some surprisingly sophisticated analysis going on when it’s looking at data samples to, say, characterize the latency of the last 5 minutes.

Some useful examples:

$ python dish_grpc_text.py -v status
id:                    ut01000000-00000000-000353f7
hardware_version:      rev1_pre_production
software_version:      848e54d2-015a-49cb-a814-34d7c5fc7e1a.release
state:                 CONNECTED
uptime:                130100
snr:                   9.0
seconds_to_first_nonempty_slot: 0.0
pop_ping_drop_rate:    0.0625
downlink_throughput_bps: 9143.5830078125
uplink_throughput_bps: 4387.2421875
pop_ping_latency_ms:   29.5
Alerts bit field:      0
fraction_obstructed:   0.006759106181561947
currently_obstructed:  False
seconds_obstructed:    266.0

# Dropped pings over the last hour
$ python dish_grpc_text.py -v ping_drop
current counter:       130202
All samples:           43200
Valid samples:         43200
Parsed samples:        3600
Sample counter:        130202
Total ping drop:       48.06441651657224
Count of drop == 1:    26
Obstructed:            23
Obstructed ping drop:  19.7899159938097
Obstructed drop == 1:  19
Unscheduled:           0
Unscheduled ping drop: 0.0
Unscheduled drop == 1: 0

# Bandwidth used for last 5 minutes
$ python dish_grpc_text.py -v usage -s 300
current counter:       131151
All samples:           43200
Valid samples:         43200
Parsed samples:        300
Sample counter:        131151
Bytes downloaded:      1327843
Bytes uploaded:        813427

Some of the ping_drop statistics are confusing; this github issue has notes on what they mean. “Unscheduled drop == 1” seems to exactly correlate to the stats UI’s “No Satellites” display, and “Obstructed drop == 1” is the Obstructed count. It’s less clear to me how to reconstruct the beta downtime statistics.

PugSQL: new Python/SQL bridge

One of the themes on this blog is “I want a really simple interface to databases for Python”. But then I’m never happy with the options. ORMs are too magic, Records is weird and limited, etc etc.

A friend of mine has written a new library: PugSQL. It’s inspired by Closure’s HugSQL. You write templated SQL statements in separate files, anything you want; selects, updates, etc. PugSQL wraps those so you can easily fill in the template parameters, call the SQL, and process the results as Python objects.

It seems like a good approach to me. Very little magic. Direct access to the actual SQL. You’ll probably end up writing some boring simple SQL that some ORM could have auto-generated but then again you’ll never be unpleasantly surprised, either.

Installing esridump on Windows

I just wrote these notes up for a friend. esridump is a Python tool that will take the URL from an ESRI ArcGIS REST server and dump all the data in it to a GeoJSON file. It works by doing REST queries on the predicate “where 1=1;”, the only subtle thing is you have to paginate the requests because there’s a limit to the number of results from one query. It’s a nice tool; there are several others floating around out there like it.

Installing it is basically as simple as “pip install esridump”. It has very few dependencies, no GDAL or other GIS giant libraries. But I wrote these detailed notes for a friend of mine:

ArcGIS RES

  1. Install Python 3.7.3. Make sure to click “Add Python 3.7 to PATH” when installing.
  2. open a cmd shell, everything else is in there
  3. cd Documents
  4. mkdir pyesri
  5. cd pyesri
  6. python -m venv venv
  7. venv\Scripts\activate.bat
  8. pip install esridump
  9. venv\scripts\esri2geojson.exe http://SERVER-URL/ out.json

EXIF in Python

I’m working on using my Flickr export. I naively thought that working with EXIF metadata from images in Python would be easy in 2019. I was wrong. Particularly if you want to write EXIF data. I’m tentatively trying PyExifTool, a wrapper for a Perl command line program. More on that below.

PyPI has 126 packages for EXIF. But a closer look shows a lot of them are bad in various ways and there’s no one consensus package. Lots of version 0.1s, stuff that was abandoned 4 years ago, etc. PIL/Pillow has EXIF support but it’s very low level and a clunky API. Piexif looks somewhat promising as a pure Python thing but also very clunky API.

Turns out the real problem is EXIF is a mess. When we say EXIF we actually mean three separate metadata formats: EXIF itself, the older IPTC tags, and the more modern inlineed XMP tags. Some of these formats have overlapping metadata in them. EXIF itself is a real mess of a binary format. For instance the GPS location info looks more like raw data from a GPS chip than a simple WGS location. For instance it supports multiple formats for lat/lon. Want decimals? minutes? seconds? Some mix? You can write anything!

The gold standard for good EXIF+others support is ExifTool, a 15 year old Perl library / command line program. It has an active community of developers who’ve spent a long time fiddling with all the weirdness in image metadata formats and making a bulletproof tool that can read and write them. So why try to rewrite all that code in Python?

Enter smarnach’s pyexiftool and the several separately packaged versions of it on PyPI. It’s four years old and as far as I can tell there is no active fork. Fortunately the code is pretty simple.

The main thing it does is fork a single exiftool process with the -stay_open flag. That causes the Perl program to keep reading commands. The rest of the Python code is a little wrapper around the JSON api and some convenience code if all you want is to read metadata. It seems to work.

So there we go; I’m gonna be writing EXIF tags by passing command line arguments over a file descriptor to a running Perl program. It’s a kludge, but if it works I’ll take it.

Yet more Python ORMs

I continue to fail to use ORMs with Python. They’re just so complicated and mysterious. But maybe that’s really just SQLAlchemy and I should look elsewhere.

PeeWee popped up on my radar recently, an ORM explicitly designed to be small and simple. It looks pretty good. Also have heard a couple of people mentioning PonyORM recently. It seems far too magic.

Going even simpler, I should circle back and spend more time with requests and/or dataset. They’re not even really ORMs, just convenience wrappers for database rows, and that seems fine by me. Still bugs me they both depend on SQLAlchemy even if the actual interaction is minimal.

 

Python 3 benchmarks

Discussion on Reddit led me to this official Python benchmark site. If you fiddle the settings you can get a comparison of how various Python 3 distributions compare to Python 2 on a bunch of benchmarks.

Screenshot-2018-2-12 Python Speed Center Comparison.png

Bars below 1.0 mean Python 3 is faster than Python 2. The different colors are different point releases of Python 3. The broad picture here is that Python 3 is generally about as fast as Python 2 or a little better. The big slower in the middle is Python startup; that’s 2-3x slower now. No other obvious pattern to me.

I’d had in my head Python 3 was generally about 20% slower. Partly because it does Unicode properly now, partly because some of the switch from collections to iterables in the core tuple and list types added slowness. But that opinion is not born out by this data.

PS: this screenshot brought to you by Firefox’s awesome screenshot tool. Not sure if it’s new to everyone or just me, but it makes saving an image of a DOM chunk of a page very easy.

soup-to-nuts Jupyter notebook project

I just finished a short project I was working on, an analysis of data from League of Legends about how people are using the new rune system the game just introduced. The report is here and speaks for itself; writing here to talk about how I wrote this up. For context the project consisted of scraping about 250 web pages off a site, parsing them, stuffing data into a database, then analyzing it for patterns.

I decided to do this project as a purely Jupyter notebook project. In the past I’ve used notebooks frequently for data exploration but seldom as my full workflow. In particular it’s not clear notebooks are well suited for production scripts like “scrape this website” but I decided to do it anyway, with some success.

Some notes:

  • IPython has a thing where if an output cell is too tall it will make it smaller with an internal scrollbar. You can adjust that size with some simple Javascript.
  • I wish there were a way to hide cells. I want to keep some code around but I don’t want it to show in whatever report I’m publishing.
  • I hid the code entirely so civilians don’t get overwhelmed. I did this with a “toggle code” button borrowed from here.
  • I wish notebooks had explicit named checkins. I find the commit cycle of git is good discipline for getting me to do only one thing at a time. There’s a Checkpoint feature in notebooks which is similar but it doesn’t prompt you for a comment so I never use it.
  • It seems worth noting that my virtualenv for the project was 550MB. Pandas is big but I wanted it. Somehow I ended up with all of scipy even though I just wanted a few colormaps from Seaborn.

Scraper

I wrote the scraper with BeautifulSoup. As noted before there’s a nice addon for Jupyter that gives notebook previews of scraped data. Interactively working towards robust scrapers was really nice in a notebook. I ended up creating a main loop to scrape all the pages I needed and write them to a simple shelf database. The full scrape only took a few minutes so I just ran it interactively; this wouldn’t work nearly as well for a run that takes hours or is perpetual. One clever thing I did was create a new shelf database for each run, so I could keep old data easily.

Data processor and database creator

My second notebook loaded the scraped data from a shelf and processed it down to a more query-friendly SQLite database. Like shelf files I kept one timestamped database per run so I could easily go back to old data. Interactive development for this part was nice, particularly being able to do some very simple sanity check reports along the way.

I used the dataset module to create the database for me. It’s quite nice; create a list of dicts and it just makes a schema from them and writes the data, no fuss.

Ad hoc queries

For my primary data exploration I used ipython-sql to run SQL code directly as Notebook cells, no Python requires. This was my favorite use of notebooks and no surprise, it’s exactly the kind of work Jupyter is for. Write query, see data as HTML table, done. ipython-sql allows you to mix in Python code, you can capture the results of queries as result sets and do things with them. I started trying to get fancy with that and realized that wasn’t working very well; better to stick to mostly SQL. Also the presentation options are very limited, once I started thinking about sharing this data with other people I wanted to give it more polish.

Final report

For my final report I made a new notebook using Pandas DataFrames with sql queries developed in the ad hoc notebook. Mostly used Pandas as a better table presenter; it makes it easy to round off numbers to 2 digits or color data cells based on their contents. Also I ended up using Pandas Python code to manipulate my data after it came from the database, convolutions that would be awkward to do with SQL queries. This all worked fairly well but in retrospect part of me thinks I should have gone with styling JSON blobs using D3 instead. That’s more work though.

The result of this sheet is the report itself and while it’s a fine Notebook it’s not a very nice deliverable for my target audience. LoL players are used to infographics like this, not boring tables. I’m uninterested in doing that kind of presentation though, so I stopped there.

Update: I posted this to Reddit and got on the front page, as much attention as I expect for a project like this. OTOH most of the discussion doesn’t seem informed by the data I presented. Good ol’ Internet people. Lesson for me in the value of presenting simple conclusions, not data.

simple database exploration

Following up on an earlier post wanting to be able to do database things simpler, some nice results.

I’m liking dataset as a quick way to write data from Python into a database. Basically you just insert dicts into a table; it takes care of generating a schema, selecting types for things, etc. I’m really liking it for writing data to databases. It helps read data too! But it doesn’t do much other than wrap rows in dicts which is nice, but I wanted more. (It also has support for fancy Python queries, but I just want raw SQL).

For reading data I’m liking ipython-sql. It adds a nice Jupyter interface on top of a raw SQL repl like that provided by sqlite or psql. It’s quite simple to install. And since it’s all implemented as an IPython magic you can mix it in with Python code in your notebook. I’m mostly just using it as a way to display SQL results as HTML tables; simple, but very useful. It has some support for fancier stuff like plotting and exporting the result sets into Python objects, Pandas DataFrames, and CSV files.

 

Python shelve: db type could not be determined

I hit a funny bug with the Python shelve module. I’d write a shelf database, then try to open it again and get this error:

db = shelve.open('foo.db')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/shelve.py", line 243, in open
    return DbfilenameShelf(filename, flag, protocol, writeback)
  File "/usr/lib/python3.6/shelve.py", line 227, in __init__
    Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback)
  File "/usr/lib/python3.6/dbm/__init__.py", line 88, in open
    raise error[0]("db type could not be determined")
dbm.error: db type could not be determined

Turns out this is my mistake. I created the shelf with code like this:

db = shelve.open('foo')

This creates a file named foo.db, a Berkeley DB file. And then I tried to open it:

db = shelve.open('foo.db')

See the error? The shelve module is appending the .db for me; I shouldn’t have added it myself to the filename. Simple enough mistake I made, confusing error results. It’d be nicer if the code threw an error or opened a new database file named foo.db.db, but instead you get this confusing error.

Python 3.6.3 on Ubuntu 16.04, which I think is libdb 5.3.

Note this error is different from an often-referenced bug in older Pythons not recognizing GDBM databases consistently (issue 13007).

simpler database access in Python

I continue to look for things that make working with databases simpler in Python. I keep doing projects where I end up dropping down to raw SQL, with awkward syntax for querying rows and bespoke one-off code for updating data in the database. The Python is messy but I like being able to use SQL in its full glory.

I’ve tried using SQLAlchemy a couple of times and have a hard time loving it. ORMs are a bad idea in general and SQLAlchemy is very complicated and magic. For a schema with 20+ tables and a lot of complex interactions it makes sense, but for a small project where you just want something more sane than low level DBAPI...

For my current project I’m trying to use plain psycopg2 and its NamedTupleCursor. It’s not awesome, but at least it gives you named access to the rows from the DB. So it makes reading from the database a little nicer, but does nothing for writing. It’s Postgres only.

Along these lines is the records library. It also gives sane access to results from queries; either as dicts or named tuples. Result sets also have nice export functions like “write to CSV” or “make into a Pandas DataFrame”. It doesn’t really do much for writing data, just querying, so it’s simple and small.

dataset is an effort to do even more. I love their tag line: “Because managing databases in Python should be as simple as reading and writing JSON files.” Amen! There’s a lot more going on in dataset than records. It’s more like an ORM-lite and contains support for creating schema, automatic upserts, complex queries without Python, ... It doesn’t have the export functions records has, but it does have a lot of thought for simple queries and updates. I’d have to actually use it for something to see if it’s sensible or if ORM-lite is an even worse idea than a full ORM.

Both records and dataset depend on SQLAlchemy, that turned me off at first. But they’re both mostly using it as a way to support multiple database types. In theory the Python DBAPI standard should be enough, but in practice it sucks enough I understand why they’d build on SQLAlchemy instead. With records you can mostly ignore that SQLAlchemy is there, but dataset exposes it more in the query system.

I wonder if some other programming environment has a much nicer database interface. The Microsoft world has LINQ, but that seems to have all the problems of other ORMs. I wonder if the R folks have a really nice way to work with databases, or maybe even Pandas.

I really like Python 3.6 format strings

Now that I have access to Python 3.6 I’m really enjoying the new PEP 498 format strings. Python has tried a bunch of different ways to format strings, from good ol’ %s notation to Template strings to str.format. They all seemed awkward to me because the thing you were substituting in was way far away from the string itself. Now you just embed a little python code right in the string to be formatted, maybe with a bit of presentation like how many digits to display. Done!

It’s pretty powerful under the hood. check out this example:

>>> today = datetime(year=2017, month=1, day=27)
>>> f"{today:%b %d, %Y}"  # using date format specifier
'January 27, 2017'

The format string is using the datetime-specific codes like %Y. Behind the scenes it’s calling the format() built-in which in turn can defer to the __format__() function on the object. In practice I suspect you can mostly not worry about this too much other than using basic floating point precision stuff.

I used to do this kind of thing a lot:

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

That’s gross for several reasons. Now I can just do

print(f"{date} {asin} {title}")

and be done with it.

GeoAlchemy and SQLAlchemy thoughts

I’m doing a new geo-project, a GPS tracker sort of thing. My database is very simple, just a Users table and a Locations table holding points. But I figured I’d front-load the work and use SQLAlchemy and Alembic and PostGIS and everything right now, not pay the pain of migrating later when I realize I need the fancier stuff.

Only SQLAlchemy doesn’t support PostGIS. GeoAlchemy2 does though. After an hour with it I can’t decide if it’s good or bad. It seems very simple.

In GeoAlchemy2 all geodata is represented in Python by just a few types; Geometry, Geography, Raster. You can’t do much with those things other than get the WKB or WKT for them. They’re not Points or Polygons or something, there’s no Python code for working with the shapes. You can pass them back to PostGIS though, to call functions like ST_Area to have PostGIS do a calculation. Requires a database round trip though. Alternately you can also convert them to Shapely shapes, use that excellent GIS library to do work in Python.

I guess that’s a reasonable compromise; GeoAlchemy2 is really just bridging to SQL, they’re not going to implement their own GEOS equivalent. It also has spatial functions declared in a SQLAlchemy-friendly way you so you can use SQLAlchemy syntax to do your work. That’s kinda neat.

Still I’m looking at a lot of third party Python code: SQLAlchemy, Shapely, GeoAlchemy, Alembic. All to manage a database with two tables and nothing more complex than a list of points. I may blow it all off and go to raw SQL. OTOH I may end up regretting that choice in a few months if I want to do more complex things.

 

python 3.6 on Ubuntu 16.04 LTS

I want to use python 3.6 on my Ubuntu 16.04 LTS box; they only have python3.5. It’s pretty simple following these instructions but here’s the details.

Step 1: install python 3.6 from Jonathon Fernyhough’s PPA.

add-apt-repository ppa:jonathonf/python-3.6
apt-get update
apt-get install python3.6 python3.6-venv python3.6-dev

Step 2: set up a 3.6 venv

python3.6 -m venv venv
source venv/bin/activate
pip install -U setuptools pip
python -V

Now when you activate venv, you’ll automatically get python 3.6 in that environment.

In addition to the jonathonf PPAs there’s also the deadsnakes PPA which has old versions of Python as well as new ones.

Python metaprogramming

This Reddit discussion had me looking at a couple of metaprogramming tricks used in Python code.

The standard library’s namedtuple type is generated on the fly at runtime. When a new namedtuple is created the library generates it from a template string. It fills out the template with the necessary details and then passes the class definition to exec(). Exciting! But relatively straightforward and easy to understand. (Except for that extra bit to support pickling; yuck.)

pytest is an alternative unit testing library that has you just using the assert statement everywhere, no library functions. To report test failures in a nice way, it does some dark magic:

Reporting details about a failing assertion is achieved by rewriting assert statements before they are run. ... pytest rewrites test modules on import by using an import hook to write new pyc files

I haven’t read the pytest code but from the way that’s written my impression is they’re inspecting compiled bytecode and rewriting the assert statements to instrument them. That sounds a little scary, in particular if it fails it must be completely confusing. They do warn you that “if you are messing with import yourself, the import hook may interfere”. Update here’s a description of the code rewriting as of 2011.

That second technique reminds me a bit of the way that Protovis rewrote Javascript at load time so you could use more modern Javascript syntax than the browser supported. Mike abandoned that idea in D3, I think because it made things too complicated.

 

Twitter Python clients by release date

I want to write a program using the long-suffering Twitter API. There’s a zillion Python options, here’s what I found. I used the most recent PyPI release date as my primary criteria, because I want something actively maintained.

Of course release age isn’t everything. All four libraries linked above have similar APIs for doing simple things. I believe all four now support the streaming API too. On a quick glance tweepy and python-twitter have the most reassuring test suites.

I picked tweepy to start with because it has the most recent recommendations on /r/python. Also there’s still activity on GitHub, even if no recent releases. So far so good.

Parsing fixed-width files in Python

I have some census data in a fixed width format I’d like to parse. Stuff like “columns 23-26 are the year in 4 digit form”. It’s easy enough to ad hoc parse this with string slicing. But by the time you handle naming, and type conversion, and stripping padding, and validation, etc etc you end up with a fair amount of code. You can parse CSV with just string split too, but anyone sane uses the CSV module. Is there a good fixed width module?

Not that I could find. I gave up and just did the ad hoc thing.

I thought FixedWidth was a candidate but after 20 minutes trying it, gave up on it. There’s packaging problems and the docs are poor. The tests are incomplete. The API is weird and seems more designed for emitting fixed width than parsing it. The final reason I gave up is it seems to require you specify a full schema; you can’t parse columns 99-103 unless you’ve said what to do with columns 1-98 forst. That was a nuisance.

The other option I found was Pandas read_fwf. I didn’t try it because Pandas is overkill for my project. But I know from CSV work that DataFrame is really nice, and the Pandas CSV module is quite comprehensive. I also know that even after parsing with read_csv you still have to do a lot of work to get it into a clean DataFrame. I’d definitely look into using this for more serious work.

Related question: are there standard metadata descriptions for fixed width formats? The census data has this thing called data dictionaries that are clearly meant to be parseable. But they’re in at least two formats right on the site. I feel like I’ve seen other government records with similar metadata descriptions.

Further reading: Extract, transform, and load census data with Python.

 

Python Pyramid framework

Interesting conversation on Reddit about scalable webapp frameworks. Lots of endorsements for Pyramids, the successor to the old Pylons project. After a brief review it looks like it’s similar to Flask. The Reddit discussion says it scales better, that it’s thread safe and there’s a hope of running it async.

I like what Pyramids says about philosophy:

Megaframeworks make decisions for you. But if you don’t fit their viewpoint, you end up fighting their decisions. Microframeworks force no decisions, making it easy to start. But as your application grows, you’re on your own.

In both cases, the focus is on the start: either too much or too little. Either way, finishing and staying finished is hard. You need a finishing-focused framework with an architectural design that scales down to getting started, then up as your application grows.

It seems to mostly be focussed on URL dispatch, with a structure for web views and sessions. And support for logging and testing! Also has some connectivity to various template libraries in Python. No database code at all, but there’s extensive docs on using SQLAlchemy. Also the note “Pyramid has a strong orientation towards support for transactions”.

Setting up a new Jupyter data exploration notebook

Been a month since I had to set up Jupyter for a new project. Here’s all the steps, which seems awfully complicated for a “standard setup”. Some of that is idiosyncratic to me though.

  1. newvenv
    a shell alias I have. What it does:
    python3 -m venv venv;
    source venv/bin/activate;
    pip install -U setuptools pip
  2. pip3 install jupyter
  3. pip3 install matplotlib numpy pandas seaborn requests
    these are standard visualization libraries, plus a sane HTTP client. Fortunately these install from precompiled wheel files so it’s quick
  4. jupyter notebook --no-browser >> jupyter.log 2>&1 &
    Jupyter really, really wants to be an interactive program. This sort of makes it headless.
  5. ssh -L 8888:localhost:8888 my-server.example.com
    I’ve installed and run Jupyter on a server. I run this command on my local development machine to forward the port to access it.
  6. open http://localhost:8888/ in a browser
  7. %matplotlib inline
    Be sure to run this as the first command in the notebook

 

Pandas DataFrames: MultiIndex and slicing

Diving more in to using Pandas DataFrames, I spent some time learning about MultiIndex. Long story short it’s a way to have a composite key for your data, to say “these two columns of my CSV file are the name for the row”. Or more complex things.

Pandas has some fairly powerful mechanisms to subset your DataFrame based on aspects of its MultiIndex composite key. They’re a bit confusing though, the slicing syntax is abstruse. Also there’s a hidden gotcha: you really have to sort your DataFrame before you can slice it if it has a MultiIndex.

Anyway, there’s a demo notebook program here. I also uploaded the ipynb file as a gist but GitHub’s viewer is buggy.

For the search engines: if you see any of the following error messages, this sample notebook will help you figure them out. Summary; call DataFrame.sortlevel()


PerformanceWarning: indexing past lexsort depth may impact performance.

KeyError: 'Key length (1) was greater than MultiIndex lexsort depth (0)'

KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (2), lexsort depth (1)'

PS: if you want to get the series of index labels for a DataFrame with a MultiIndex, use get_level_values(). I keep forgetting how to do this.

Notes from a Jupyter/Dataframe project

I’m looking at some League of Legends data; champion win rates by player tier. I’m curious which champions have higher win rates with skilled players, and/or which are more popular. You can see the resulting report here, notebook (without nice CSS) is here.

Learning me some Jupyter and Pandas

Really I’m using this project to get more comfortable with using Jupyter and Pandas DataFrames to analyze data. The DataFrames part is overkill; I’ve got about 10k of data, not the 10G of numbers DataFrames’ highly optimized code is for. But DataFrames have lots of functions that replicate SQL’s analysis capabilities and they display nicely in Jupyter, so here I am.

My data starts as web pages of HTML tables. I imported those into a single Google Spreadsheet with multiple tabs.For a single sheet, rows are champions (120 or so) and columns are statistics like win rate or games played (5 of them). There’s 7 sheets, one per tier Bronze / Silver / Gold / ... I then exported those sheets as CSV files, one per tier, for analysis. (Google Spreadsheets turns out to be a remarkably good HTML table data scraper.)

I then played with various forms of Python code for reading those CSV files and doing some statistics on them. Starting with simple raw Python data structures, a bunch of dicts and tuples all the way up to a full Panda Panel. Along the way I learned how to analyze the data using Pandas a bit, and to format the results nicely in Jupyter. My real goal here is to make interactive reporting as natural as if I’d loaded all the data into a SQL database. Being able to do natural things like sum all values, or get the average of numbers grouped by some criterion.

Data loading

One thing I found is that the more I whipped my data into Pandas shape, the simpler my code got. I finally settled on doing all the parsing way up front, when I read the CSV files, to make clean DataFrame objects with well named columns and rows. That makes the later analysis code much simpler.

The read_csv() function has a lot of options to configure parsing, it’s worth the time to set them. “thousands=,” for instance will allow it to parse things like “1,523,239” as an integer and not a string. I also ended up doing “header=0” and specifying my own “names=[...]” for columns, just so I could make the names valid Python identifiers. (You can access named things in a DataFrame with attribute syntax; either df[“winrate”] or df.winrate.)

But the most important thing for read_csv was index_col. The concept of index in a DataFrame is particularly important. That’s the unique key that names each row; in my data the index is the champion name. In a CSV file this would probably be the column named “label” or the like. In a database table it’d be the primary key. The word index is used all over the docs and it confuses me all the time. Once I set up my data index correctly the code got a lot better.

The thing I find most confusing is the shape of data. DataFrames, for instance, mostly seem to want to treat a column of numbers as a single feature. But I really need to work row-rise most of the time. Slicing a DataFrame is particularly bizarre. df[n] gives you the nth column from the dataframe df. But df[n:n+2] gives you rows n to n+2. I find I often have to transpose my dataframe to make operations convenient, or use the “axis” parameter to functions like sum() to indicate whether I want to sum over columns or over rows.

The final fillip was using a Pandas Panel to store my data. A Panel is a collection of DataFrames; in my case one per tier. This 3 dimensional data structure is a bit confusing, the docs apologize for the names and it’s not clear that Panel adds a lot of value over a dict of DataFrame objects. But it’s Pandas’ way of representing a collection of spreadsheets, so I am going with it. My panels “items” are the tier names, the major_axis is champion rows (named by the index) and the minor_axis is the stats (the columns.)

Data analysis

So now I have my data loaded into a panel, time to analyze. The pattern I’ve settled on is generating a new DataFrame that’s a report table. For instance I’m interested in average statistics per tier. So I start with a 3d Panel of tiers x champions x stats, and I boil that down to a 2d DataFrame of tiers x average(stats). When I do ad-hoc Python report generation I usually just iteratively print out report lines, or maybe make an array of dicts for my data. Those are still fine too, but I wanted to go full Pandas.

I started out by writing lots of laborious loops over panel.iteritems() and the like. See cell 7 and how I first build up a dict named ‘spreads’ and then converted it to a DataFrame. Over time I’ve refined to simply doing operations like dividing a DataFrame by a Series and the like. Cell 8 shows that style, the creation of pick_rates is about the same computation as spreads before, but it’s less code. The whole process feels a lot like vectorizing code, like I did for my machine learning class in Octave/MatLab. The code gets shorter, which is nice, but it should also be more efficient which matters for large datasets.

Presentation

My final goal was to make nice-looking reports right in Jupyter. That proves to be quite difficult. Pandas is amazing at inlining graphs and visualizations with matplotlib and friends. But it’s not quite as good at textual reports. I mean Jupyter will display any HTML you make in python, but I haven’t found any good HTML generation convenience libraries out there for, say, DataFrames.

Fortunately the default DataFrame presentation HTML is pretty good. Labelled columns and rows, decent formatting of numbers. All that’s really missing is right alignment of numbers (and why is that not the default?!) But I want more control, for instance rounding floating point numbers to specific precision. For that I used the DataFrame.style object, which gives you a D3-esque ability to apply per-datum CSS styles to cells. I mostly used .format() to control text formatting of numbers and .set_table_styles() to add some CSS to the HTML table. The .applymap() function is the really powerful one that lets you control things per-datum.

I also threw in the background_gradient style, to give a sort of heatmap coloring to the number cells. That required installing a bunch of crap like python-tk and numpy just to get the colormaps. But it’s pretty painless in the end.

Conclusion

Pandas + Jupyter is a pretty good platform for ad hoc exploration of data, and with some learning and effort you can produce pretty clean code and reports. I love the way notebooks are reproducible and shareable. I think using SQL for this kind of work is probably more effective, but there’s a lot of overhead in getting set up with a database. And the interactive exploration isn’t as nice as a Jupyter notebook. (Hmmm, there’s no reason Jupyter cells couldn’t contain SQL code!)

Non-cryptographic hashes

 

About once a year I need to hash some data to give it a name / short checksum. I don’t need a cryptographic hash. But I end up using SHA-1 or MD5 anyway because it’s so available. A non-crypto hash should be ~100x faster to process data, which could actually matter. But finding a standard, portable, non-cryptographic hash with optimized implementations for Python, Node, etc is a challenge.

A lot of history of hash functions is producing 32 bit values on 32 bit CPUs. That stuff is mostly obsolete. 32 bit hashes are not useful for many applications; you expect hash collisions after just 2^16 ~= 65,000 objects. And 32 bit CPUs are largely irrelevant now. You really want a micro-optimized machine code implementation for AMD64 that is aware of cache geometry, pipeline optimizations, etc. It may be now that you want a GPU implementation; you certainly do for high throughput crypto hashes. Not clear if it matters as much for non-crypto hashes and deployment realities mean you may not have a GPU at all.

Stock Python has the hashlib library, which includes crypto hashes like MD5 and SHA-1. It’s highly optimized. There’s also CRC32 and Adler32 hiding in the zlib library, but they are only 32 bit hashes and therefore not useful.

MurmurHash3 is the usual recommendation for a non-cryptographic hash. It’s been around a long time and widely implemented. It’s also a bit confusing, with both 32 and 128 bit versions and multiple Python implementations.

There’s a bunch of “nextgen” hash functions out there. Metrohash and xxHash both look promising on first glance.

SMHasher is the standard test and benchmark suite for hash performance. I’d love to read a carefully done comparison of hash functions out there in contemporary languages and deployment environments.

Stack traces from running Python programs

My lolslackbot program occasionally hangs forever and I’d like to know what failed when I kill it. Starting with Python 3.3 it’s relatively easy using the faulthandler built-in library. You have to set it up ahead of time (it’s not on by default), but once you do you can send the process a SIGABRT and it will display a slightly spartan stack trace and abort the program.

You can get a stack trace without killing the Python process by registering another signal, like faulthandler.register(signal.SIGUSR1). That signal is not entirely unobtrusive; it interrupts time.sleep() for instance. But the program does seem to keep running after printing the stack trace. All the signals registered by default seem to also kill your program; USR1 won’t. (Unless I’m confused.)

It’s all implemented in C to enable printing useful stack traces even if the Python VM itself is broken. Also you can enable it just by setting an environment variable, before any Python code is run, which I imagine is useful for debugging problems at startup.

There’s also an interesting faulthandler.dump_traceback_later() function which seems to basically be a watchdog. It sets a timeout with a separate thread that results in a stack trace dump and, optionally, your program exiting. It calls _exit() which is the hard exit, which has pluses and minuses.

It’s sure a lot easier than the only other way I knew to do this, which was to attach gdb and inspect the interpreter’s state. But I wish it were enabled by default like Java’s old built-in behavior on SIGQUIT (Ctrl-\). Maybe they were afraid it was too radical a backwards-incompatible change.

2016 Python webapps

I want to build a webapp for my lolslackbot project. What do I use?

Django is the clear consensus choice for large, grownup projects. I used it once a couple years back and thought it was fairly good, if not exciting or lovely. But I have in the back of my head the Django ORM doesn’t play nice with homegrown schemas, that it really wants to control the schema itself. Also I have the impression that Django is kind of big and clunky, although maybe that’s unfair.

The cool kids all use Flask. I like the idea of a microframework, something simple. Flask doesn’t inspire a lot of confidence though. The last release is 0.10.1, released nearly three years ago. And while Python 3 is supported its use is discouraged. That may have made sense in 2013 but it’s a backward opinion in 2016 (IMHO). (The author reiterated that opinion as much as 8 months ago.) OTOH my friends who use Flask say not to worry about it, that it works fine with Python 3 and it’s simple.

Only no one just uses Flask. They combine it with Jinja2 templates, and WTForms, and SQLAlchemy for an ORM. Add in logins, sessions, and some CSS frameworks and you’re looking at a lot of software. Is it better to glue together your own custom assemblage of small components or should you just use a full framework like Django?

Full Stack Python has some useful advice.

My friend Brad G. recommended starting with cookiecutter-flask as a set of components + structure and customize from there. Man, it’s been years since I used a Visual Studio wizard! It looks like a good way to get up and running though.

Successfully installed Blinker-1.4 Flask-0.10.1 Flask-Assets-0.11 Flask-Bcrypt-0.7.1 Flask-Cache-0.13.1 Flask-DebugToolbar-0.10.0 Flask-Login-0.3.2 Flask-Migrate-1.8.0 Flask-SQLAlchemy-2.1 Flask-Script-2.0.5 Flask-WTF-0.12 Mako-1.0.4 SQLAlchemy-1.0.12 WTForms-2.1 WebOb-1.6.0 WebTest-2.0.20 Werkzeug-0.11.4 alembic-0.8.6 bcrypt-2.0.0 beautifulsoup4-4.4.1 cffi-1.5.2 cssmin-0.2.0 factory-boy-2.6.1 fake-factory-0.5.7 flake8-2.5.4 flake8-blind-except-0.1.0 flake8-debugger-1.4.0 flake8-docstrings-0.2.5 flake8-isort-1.2 flake8-quotes-0.2.4 gunicorn-19.4.5 isort-4.2.2 itsdangerous-0.24 jsmin-2.2.1 mccabe-0.4.0 pep257-0.7.0 pep8-1.7.0 pep8-naming-0.3.3 psycopg2-2.6.1 py-1.4.31 pycparser-2.14 pyflakes-1.0.0 pytest-2.9.0 python-editor-1.0 setuptools-20.2.2 testfixtures-4.9.1 waitress-0.8.10 webassets-0.11.1 wheel-0.29.0

Thinking for real about a webapp is making me once again consider whether SQLite is a good choice going forward. The lack of fine grained locks is going to make multiple writers unacceptable. I sure wish it had per-table locking, that would probably be good enough for now.

Python3: no len() for iterators

Python 3 has an odd oversight; there’s no function for finding the length of an iterable. You can do len(aList) of course, and len(aTuple). But there’s no len(anIterator). What’s really surprising is there’s no itertools.len(anIterator), some function implementation.

The naive solution is len(tuple(anIterator)). But that’s inefficient because it constructs a tuple in memory. This discussion suggests sum(1 for e in anIterator), which if I understand generators correctly should be pretty efficient and involve no allocation of new collections. Surprised this function isn’t in itertools.

Update: see also cardinality.count() for a clever faster implementation.

Update 2: I had some yak-shaving time, so I made an iPython notebook timing three different solutions for counting the length of an iterable.

  •  1x: len of tuple of iterable
  •  7x: deque an enumerate of iterable
  • 11x: sum 1 over the iterable

The results are roughly the same for iterables of size 1000 to 1,000,000 to 100,000,000 and hold whether the iterable is a list or an ephemeral itertools iterable.

What’s astonishing is how much faster the len(tuple(iterable)) method is than the others. Naively it should be slower, it’s doing a lot more work building that tuple in memory. But perhaps this is a highly optimized codepath in Python. The tradeoff is it temporarily allocates memory to consume the whole iterable, so it’s using O(n) memory compared to the O(1) memory for the other solutions.

Python packaging in March 2016

Hooray! I finally finished porting my lolslacktest code over to be a proper Python module, installable with pip, and with a virtual environment. What a pain! Some notes on what I learned. But first, some reflection.

This project has been one of the least fun things I’ve done in a long time. I can tell by the way I’ve been foot dragging. It’s confusing and hard to debug packages. The docs are inconsistent and suffer from years of accretion. Some things are genuinely confusing, like Python’s surprise lack of support for circular imports. And in the end result is my product works just like it did before. No user visible changes. Behind the scenes things are better; the install is cleaner, I have a virtual environment for proper external dependencies, etc. But nothing fun, just slightly less crappy ops.

The state of the art for Python Packaging

As of March 2016 the Python 3 state of the art for package installation is pip, pyvenv, and setuptools. pyvenv and pip comes with Python 3.4 but setuptools is still extra. (On Ubuntu you have to install python3.4-venv with apt.)

The state of the art for managing Python packages keeps changing. This Stack answer explains the landscape as of September 2014. This packaging user guide is updated as of September 2015 and is mostly very good, but even it references things that don’t work such as “python setup.py bdist_wheel”. I also found this guide useful but it was mostly written in 2012 (although occasionally updated).

The pip installed by python 3.4 (Ubuntu) is version 1.5.4, you want version 8.0 or later if you want to do things like install gevent with a precompiled wheel file. setuptools is old too. So first thing you should do after setting up a pyvenv is “pip install -U pip setuptools”.

The setuptools docs are not very good. They assume you know how distutils works. Also they spend a lot of time talking about easy_install and none at all talking about pip.

Honestly all this Python packaging stuff is a big mess, I feel like you have to understand the history to be able to use the current state of the art. It’s a shame Distutils2 didn’t work out for Python 3.3 and rationalize it all. To be fair, packaging in almost every system sucks: npm, rvm, homebrew, they’re all a mess. All but my beloved apt, and that’s because the Ubuntu package management team works super hard.

Some hacks and code things

I had to do a few hacks and other things to make my project work.

The biggest code change was just wholesale replacing absolute imports like “import lib” with relative imports “from . import lib”. I think that’s actually correct, but I was doing it kind of blind for every single file.

I had to modify my code because Python really doesn’t support circular import dependencies. You don’t really notice until you are using relative imports. The accepted solution for circular imports is to break the circularity, refactor code. Screw that. My workaround was to move some of the import statements inside functions, so they execute at run time and not import time. That’s bad and inefficient but expedient.

There’s two similar-looking ways for a Python package to specify dependencies. You can add an install_requires stanza to your setuptools setup() method, or you can use pip to install a bunch of stuff listed in a requirements.txt file. The setup() dependencies are installed automatically when a package is installed, but nothing installs requirements.txt automatically. OTOH the requirements.txt option is more powerful, for instance pip can install things from github URLs whereas setuptools can’t. (The setuptools docs say you can do this with dependency_links, but I couldn’t make it work.) I’ve ended up using a mix of both, preferring setuptools where I can.

I have some shell scripts named in the “scripts” section of my setup.py, so they are installed in the virtualenv bin directory. But I want them to work even if the virtualenv isn’t activated, so those scripts have to source their own virtualenv. Mostly for execution in cron; getting cron to activate a virtualenv is not easy. The hack I did for this was this shim of code at the top of each script:

VENVDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source $VENVDIR/activate

The bash magic in the first line sets VENVDIR to be the directory where the bash script itself is. Conveniently, that’s the same directory that has the activate script.

I have no idea how to put version numbers on my program. It’s a private thing only I’m installing, so for now I’m going with the dbschema version. Part of me wants to just put the git commit nonce there.

My deploy script used to be rsync from dev to prod. Now it’s sshing into prod and having it do a “git pull” followed by “pip install -U”. I took this approach at migurski’s suggestion. It means I’m not using any of the fancy distribution builds and versioning stuff that setuptools/pip enables. But I don’t really need those right now, they make more sense for public code hosted at PyPI

Note to self: you can’t move a pyvenv environment once its created. They have paths hard coded.

 

 

Python modules frustration

I’m trying to turn my lolslackbot code into a proper set of Python modules, so I can manage the code with pip and venv. That means turning my moduleless code into a bunch of packaged modules. And writing setuptools.

And oh god it’s awful. Python’s handling of module namespaces and imports is confusing, particularly when circular dependencies are involved and/or command line scripts as opposed to Python libraries. I can’t even tell if this caveat applies to me or not

Note that relative imports are based on the name of the current module. Since the name of the main module is always “__main__”, modules intended for use as the main module of a Python application must always use absolute imports.

The other problem is years of cruft that’s accumulated in Python packaging tools. setuptools, disttools, easy_install, pip, wheel, egg, virtualenv, pyvenv.. To some extent this has been rationalized in modern Python: use pip and setuptools and call it a day. But the docs that are out there are hard to follow because they tend to describe the history, not the current practice.

The two best documents I’ve found so far:

Right now I’m hung up on some code where “from . import lib” works in some contexts but not others. I think it may be related to circular dependencies but am not sure.

Update: turns out Python doesn’t actually support circular imports, despite looking like it does in many circumstances. So now I’m having to refactor all my code that worked just fine to not have module A import module B which imports module A. I feel like I’m programming in C again, only without #ifndef macros. One partial solution is to only do the imports inside the running function code. That avoids the circular imports at import time, at the expense of deferring the import code machinery running in your actual execution path all the time. Maybe I’m misunderstanding how to really make this work. (There’s a bunch of arrogant advice which says “if your code has circular imports you should refactor it.” No, imports are how you manage namespaces in Python, and Python shouldn’t have this limitation.)

Upgrading sqlite3 within Python 3

Python 3 has sqlite3 baked in. That’s great! But it has an old version of sqlite3; my Ubuntu 14.04 system with Python 3.4 has sqlite 3.8.2. I want sqlite 3.9, for the new JSON hotness.

There’s a pip-installable package called “pysqlite” that should be installable in a virtualenv. But it only supports python 2 and explicitly says “use the built-in sqlite3 for python 3”. Thanks but no thanks!

This Stack Exchange thread has details on recompiling python3 with your own sqlite3, but that’s more work than I want to do. Also it appears that python3 is just loading libsqlite3.so.0 from my Ubuntu install, so I should be able to upgrade it by either upgrading libsqlite in Ubuntu or building my own shared library. But the Ubuntu upgrade looks impossible without upgrading all of Ubuntu 14.04. (I couldn’t find a PPA from a quick search).

Compiling sqlite3 into a shared library is an exercise. The source is distributed in an idiosyncratic format and the version with a Makefile doesn’t build shared libraries. I ended up making something work by following the official docs and this note about the shared library.

gcc -c -fPIC -O2 -I. -DSQLITE_THREADSAFE=0 -DSQLITE_ENABLE_FTS4    -DSQLITE_ENABLE_FTS5 -DSQLITE_ENABLE_JSON1    -DSQLITE_ENABLE_RTREE -DSQLITE_ENABLE_EXPLAIN_COMMENTS    -DHAVE_USLEEP -DHAVE_READLINE    shell.c sqlite3.c
gcc -shared -o libsqlite3.so -fPIC sqlite3.o -ldl -lpthread
ln -s libsqlite3.so libsqlite3.so.0
./sqlite3 -version
LD_LIBRARY_PATH=. /usr/bin/python3 -c 'import sqlite3; print(sqlite3.sqlite_version)'

It works! But now I’m nervous. Compiling sqlite3 correctly takes more research than I conducted. It has a whole lot of options! Also I get a bit worried about relying on LD_LIBRARY_PATH to override libraries. It’s totally fine to do of course, but it just seems too easy to forget to do it in some environment and suddenly things aren’t working consistently. If I were serious about doing this I think I’d build my own Ubuntu package for real, using Ubuntu’s Makefile as a starting point.

Python / sqlite3 query logging

When debugging database code it’s really handy to have a text log of the actual SQL being executed by the database. This output is remarkably difficult to get in many database drivers. Happily, starting with Python3.3 there is a way

connection.set_trace_callback(print)

The argument is any function, or None to disable the tracing. I think this has no access to the results, nor can you use it to time how long the query took. That requires some more ambitious thing.

I hate installing Python libraries

(Caution: intemperate angry rant follows.)

I’m wasting more than an hour figuring out the fuckup of building GDAL to run in a virtualenv on Ubuntu 14.04 LTS. This hasn’t worked well in the year+ I’ve been trying, and it’s not working well now.

  1. set up a new virtualenv and activate it
    virtualenv -p /usr/bin/python2.7 venv
    source venv/bin/activate
  2. Install the openaddresses repo I have
    cd ~/src/oa/machine/
    pip install -e .
  3. Manually install cairo cffi (shouldn’t pip have done this?)
    sudo apt-get install libffi-dev python-cffi
    pip install cairocffi
  4. Give up trying to install GDAL with pip. Even after you work through the include path packaging problems, the C compiler starts throwing errors about variable scoping.
  5. Start over with a virtualenv that also uses system packages, which somehow seem to be working.
    virtualenv --system-site-packages -p /usr/bin/python2.7 venv

I shouldn’t publish my angry rant. GDAL is great software, and I appreciate all the volunteer open source effort. But something about dealing with packages and software installation is just so maddening. I think it’s because hiding behind “pip install gdal” is about 200,000 lines of complex code in multiple languages from multiple distributers. When it works its awesome. When it fails all you can do is try searching the error message and cargo culting a solution, which only works 1/3 of the time.

grawr.

 

Turning hacky Python into a real app

I’m about to go on vacation. I just finished a bunch of improvements to lolslackbot. Also I suffered my first real outage since it started as a simple cron job six months ago. So I’m reflective on what I need to do to graduate this service into something more serious and reliable. Some projects towards making the system production quality...

Locking and timeouts. The outage was because I tried grafting lockrun into my cron job to ensure only one update runs at a time. But if the update script hangs (say, because the remote API is down) then it holds the lock forever, or at least until I wake up in the morning. I’ve removed the locking for now, running the update twice at once isn’t too bad. But I’m considering adding back the locking along with some sort of global timeout to the scripts, or at least the network requests, so they can’t hang forever. But that’s a hack on top of a hack. “Run this once and only once, reliably” is a hard problem.

Error recovery. I’m a big believer in throwing exceptions when things go wrong, then fixing the code to handle the error. But at some high level I’d rather the script kept going. I’m processing hundreds of game objects a day; it’d be better to skip a game that’s weird and breaks my code than to have the whole system fail until I can fix it.

Logging. I’ve been using Python’s logging program but I’m not logging to a file anywhere; just stderr. That makes it hard to look back at what happened. Or even notice if I skipped a weird game. I might also benefit from some contextual logging, but that may be overkill.

monitoring. I don’t exactly need a pager for 3am, but I would like some better way of knowing if stuff is working than “did cron email me?” and “have any new messages shown up in awhile?”

virtualenv. I’m naughty and don’t use venv. I should.

make code a module. I’m also naughty and don’t have my own code in a proper module. I should. Would be nice to separate the Python scripts from the precious data files, too.

test suite. A lot of my tests run based on some live data I captured a month or two ago and has baked in it things like “there are exactly 110 game objects”. That makes it hard to add new test cases. I think I’m stuck here and need to just suck it up and hand-edit in new test cases to the JSON blobs I use in my mock framework. And then update all the tests. I also had a hilarious problem yesterday where one of my test cases had enshrined the wrong expected output, basically hiding a bug I sort of knew about. That’s the hazard of starting a test suite with “I think this code is working; let’s assume its current output is correct”. Still that test suite is the single best investment I’ve made in the project, so much value.

indices / SQL performance. I haven’t done any work towards creating indices for common queries other than the implicit indices that primary keys and unique constraints give you. So far my whole database is only 20MB, hardly worth worrying about. But at some point table scans are going to stop being fast. I haven’t seen any evidence of a slow query log in sqlite, I suppose I could build my own wrapper in Python.

Distributed transactions. A closely related problem to locking; I have a sort of distributed transaction problem when I’m delivering messages to Discord. I want to mark the message delivered in my database if the message is successfully delivered to Discord. So I write the “message processed” bit after Discord accepts the message. But sometimes Discord throws an error even though the message got delivered anyway, so the message doesn’t get marked processed and later is delivered a second time. It’s sort of a distributed transaction problem I don’t quite know how to solve.

Web view. Big project, I think I’ve graduated to needing a web view for seeing and editing the objects in my database. Particularly for stuff like “add a player to a team”. I really don’t want to roll this all ad-hoc, way too much work. Currently thinking of doing this as a whole new codebase not reusing much (if any) existing code, to try out Flask and SQLAlchemy. With a plugin to generate the editing UI, maybe WTForms or Flask-Admin.

sqlite3 vs postgres. I continue to have the feeling that I should switch to postgres, but I’m now pretty in love with sqlite’s simplicity. The planned web view will be my first time with simultaneous writers, which previously I assumed was when sqlite may be too limiting. OTOH sqlite does have database-level locking, it’s not going to blow up. As long as the locks are only held for “a few milliseconds” I can live with that. Python’s driver has a 5 second timeout for connections by default. The sqlite3 command tool by default just throws an error if the database is locked, but you can specify a timeout in a somewhat awkward way. (If sqlite3 is compiled wrong, locks can last seconds.)

So that’s a big list of projects. I’m not thrilled to do any of them; they’re not features, and they’re a significant investment for a project that has very few users. OTOH they will make my life better as I work on this.

 

Am I crazy? Modern Unix security

This Python library I’m using (deliberately left nameless, not well known) has what I think is a security problem. It takes a password and generates a login token. It then writes that login token to a file in /tmp. A world readable file. That token can then be used by anyone with access to the Unix system to impersonate the user. That seems bad.

What’s baffling me is I reported the bug and the author of the code and other users of the library don’t see the problem. “If someone can read files on your computer you’re screwed anyway.” I think they’re wrong, but maybe this is just me being old?

I grew up in the era of shared Unix systems. We regularly had 40 people all logged into one machine, so of course file permissions mattered. But modern Unix systems are generally single user. Single application, for that matter. And the rise of VM and container technology makes that doubly so. So maybe it doesn’t really matter?

Of course it matters. And it’s easy enough to fix; just make the file private. Although.. Doing that correctly in Python is remarkably complicated. You can’t just create the file and then chmod it, because that creates a race condition where the file is briefly world readable. I think setting umask is better, but that’s per-process state so you can’t really do that in a thread safe manner without locking. os.open() with a file mode is also a possibility but complicated because you’re dealing with file descriptors. The tempfile package in Python does this nicely, but unfortunately I can’t use it because I need a persistent file. tempfile’s code is remarkably complex!

Python is fast opening sqlite3

I’ve got a lot of code calling sqlite3.connect() in my program now. Particularly in my test suites. In MySQL and Postgres this can be slow and you end up needing connection pooling. I had a feeling it shouldn’t be in sqlite3 given its simplicity, but I wasn’t sure.

A bit of work with timeit later I can report it’s taking about 18usec to open a database. My connection function is more complex too, doing a select into a “globals” table to test the schema version. Even with all that work it’s 170usec, or < 2ms. That’s not super fast but it’s not a problem if my test suite does it 100 times.

$ python3 -m timeit -s 'import sqlite3' "sqlite3.connect('games.sqlite')"
100000 loops, best of 3: 17.6 usec per loop

On JSON and nothingness

Python’s JSON module serializes the Python value None as the JSON value null. This is correct. However it causes odd bugs if you are not aware of it.

Specifically, I had code like this:

db.execute('insert into table values(?)', json.dumps(foo.get("bar"))

I was trying to insert a database NULL if foo didn’t have the key “bar”. But foo.get() returns None, which gets turned into the string “null”, which results in the string ‘null’ being inserted into the column. Derp.

>>> json.dumps(None)
'null'
>>> json.loads('null') == None
True
>>> json.dumps('null')
'"null"'
>>> json.loads('"null"')
'null'

>>> json.loads(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.4/json/__init__.py", line 312, in loads
    s.__class__.__name__))
TypeError: the JSON object must be str, not 'NoneType'

A simpler explanation of asyncio

Reflecting on my previous effort to understand asyncio, I think I have a simple summary:

asyncio is a cooperative multitasking system for Python based on generators. You implement your program as generator functions that yield control periodically. The asyncio event loop manages running all of your generators.

That’s it, it’s really simple. This understanding lets me build on my existing knowledge about generators / coroutines and understand what asyncio is doing.

What’s confusing is all the syntactic sugar and extra library stuff in asyncio gets in the way of understanding the simple thing. Also the Python docs are not written from the point of view of “explain the basic idea”. And the API is still in transition; in Python 3.5 they are no longer generators, they are coroutines, but the principals are the same.

Here’s a really simple program:

import asyncio

@asyncio.coroutine
def sleeper(loop):
    for i in range(10):
        print(i, loop.time())
        yield from asyncio.sleep(0.1)

loop = asyncio.get_event_loop()
task = sleeper(loop)
loop.run_until_complete(task)

That’s a toy example. In real work, you have multiple tasks running simultaneously. And instead of yielding on a sleep you yield on something more useful, network IO or something.

The confusing part is the line 10, task = sleeper(loop). Naively you’d expect that to invoke the sleeper function and do the work right then. But because it’s been decorated as a coroutine, really what calling that function does is return a generator object that encapsulates calling the function. We then pass that generator to the event loop to ask that asyncio call it for us. (In Python 3.5 using async def and await, that object is no longer a generator, it’s a member of the new type, coroutine.)

There’s a lot more complexity of course. I’m still confused about the melange of coroutine, Task, and Future, and when to use which. Combining multiple coroutines in various ways can get complex, although once you commit to the model it is easier to reason about than thread locking. And then there’s a lot of auxiliary libraries that make asyncio useful, things that help you yield from network IO or external processes or whatever. Not to mention libraries on top of asyncio like aiohttp.

But the core concept there is really simple. Generator functions that cooperatively multitask. That’s the magic, there’s not too much of it really.

Need a database abstraction

My little lolslackbot project has grown big. 11 different tables! I’m hand-writing ORM code now, silly things like “class Person” which wraps a row for the people table. The meat of the work is still hand-crafted SQL with proper relational queries, but I’m increasingly doing some really basic “get me the row with property X” and writing it all by hand is tedious. And oh boy I added some caching using functools.lru_cache, which I know from experience at Google is the beginning of the end for understandable correctness. And I continue to write increasingly elaborate schema migration scripts as I upgrade stuff.

It’s all kind of a mess. I wish now I’d started using some Python ORM tool. I still think ORMs are kind of evil, but they are a useful evil.

I’m out of date on where Python is but my impression is everyone likes SQLAlchemy. The basic tools are just a really nice upgrade from the basic Python database driver stuff. And the ORM looks like it’s made the right choices, at least based on what I read.

But do I want to port all this code over? Hell no. Hrm... I’m accumulating technical debt. I also need to wrap all my Python code in a proper module structure, and set up a real virtualenv, and...

At least I have a test suite. Although Guido help me if I ever have to regenerate the test dataset.

 

Understanding Python 3.4 asyncio

Working with discord.py has made me realize how I really don’t understand asyncio, the modern way to do asynchronous code in Python. Truthfully I barely understand any sort of async programming at all. I can sort of bash away at NodeJS a little bit. And I once wrote an asyncore program that did some neat network stuff. But mostly I’ve used threads or processes to do concurrency. It doesn’t help that I generally am starting with a single threaded synchronous program and then trying to later shoehorn it into some async context.

But soldiering on, here’s some resources:

  • Python 3.4 asyncio docs: the core reference. As with all Python docs it is well written, but unlike some Python docs it’s hard to follow. Much more of a reference than a tutorial.
  • Module of the Week: asyncio: a heroic effort to provide an overview tutorial of the complete module with lots of examples. It’s good, but I’m still confused after reading it.
  • Exploring Python 3’s Asyncio by Example and The New asyncio Module in Python 3.4: Event Loops, two more tutorial articles that just hit the highlights.
  • A Web Crawler With asyncio Coroutines: a thorough explanation of how asyncio works, building it up from first principles with generators.
  • How the heck does async/await work in Python 3.5?: a more low-level explanation focussed on the await/async keywords in Python, includes an example of implementing your own framework instead of using asyncio
  • PEP 3156 is the proposal that resulted in asyncio, written in the Python 3.3 era with a reference implementation called “Tulip”. I haven’t read this yet.
  • PEP 0492 is the proposal that resulted in the “async def” and “await” keywords being added to the language in Python 3.5. Also “async with” and “async for”. To normal coders, this is mostly syntactic sugar for stuff that worked in Python 3.4. But behind the scenes Python added a whole new concept of “coroutines” to the language, to accompany generators.
  • PEP 255, PEP 342, and PEP 380 are 5+ year old PEPs related to defining generators in Python. (The “yield” keyword.) Generators are the basis of coroutines, and coroutines are the foundation of asyncio.
  • aiohttp is the popular HTTP library for use with asyncio.

Here’s my understanding of today, with the massive caveat that I’m totally new to this and may have important aspects wrong.

The key concept in Python asyncio is the event loop. When you are writing an async program you no longer are executing functions imperatively. Instead you are creating objects that ask for your functions to be called. (The “async def” keyword or the @asyncio.coroutine decorator do this for you; they wrap your imperative functions with an object, so when you invoke the decorated function it doesn’t actually run but instead returns the callback object). You then supply these objects to the event loop through functions like “call_soon()”. Finally you set the event loop running with run_forever() or run_until_complete(), which gives the event loop control over the CPU where it blocks while it runs your code via all the callback objects you gave it.

The other key concept in Python asyncio is coroutines and/or generators. That’s where the “yield” keyword comes in, and it’s actually the same old yield keyword we’ve had since Python 2.3. It’s the way for a Python function to return CPU control back to the thing that called it, yet also keep its stack state so if that function is called again it picks up where it left off. asyncio in 3.4 is literally implemented just as a bunch of fancy generator functions and lots of yielding everywhere. 3.5 adds the new syntax support with “await”. It also makes async functions into “coroutines” instead of “generators”. But the basic concept is still the same.

So that’s the core async magic. It’s really just a sort of process scheduler for cooperative multitasking. The event loop is the CPU scheduler that invokes tasks in a single Unix process/thread. Tasks politely interrupt themselves by calling yield when they can.

But there’s a lot more in asyncio. A key thing is that there’s convenience functions for places where you are most frequently going to want to yield. Ie: waiting for a socket, or a stream, or a subprocess, there’s convenience code for saying “get me the next bytes from this socket and oh by the way go ahead and yield control until there’s something to read”. There’s also a higher level wrapper for “protocols”.

And beyond that, there’s a lot of building blocks. There are Tasks and Futures to wrap some asynchronous thing in a structure. There’s a “wait()” method for collecting results from multiple asynchronous things. There’s locks and semaphores. Many of these convenience objects seem to basically be wrappers for the basic yield/await syntax.

So I think that’s how it all fits together. Now to translate that theory into actual working code to see if it’s right.

Update: thanks to a reader comment from Luciano Ramalho I read A Web Crawler With asyncio Coroutines and basically have my understanding above confirmed and deepened. Despite the title, the article is really building up a full asyncio implementation from basic Python generators, explaining in detail how everything works. Now that I understand this much better I look forward to forgetting entirely how asyncio works and just embracing and using its abstractions. If it’s well designed, it should be usable without knowing how it was implemented.

Update 2: see A Simpler Explanation of asyncio

Discord API first use

My gaming group is switching from Slack to Discord. It’s a nice product. It’s sort of a Slack clone with voice channels as the big added feature. It’s also a product aimed at gamers, not corporate use, so there’s some hope the pricing and features will make more sense for gamers. I like the product, it’s worth a look.

So now I need to make my Slack bot post to Discord, too. Discord currently has no formal API. There is a fantastic group of hackers doing an Unofficial API project, though, and the company seems OK with it. Compared to most hacking projects this one is particularly well documented and organized. I dove in this morning and figured out how to write my own bot that works with the Discord API.

First, some resources:

The Python client is very nicely documented and organized. If you’re starting afresh you want to get version 0.10.0a, the alpha, directly from GitHub. PyPI currently has 0.9. 0.10 has reorganized the API, no reason to use the old one now.

The client itself is entirely based on Python 3.4’s asyncio (with preference for the new 3.5 syntax if available). That means you basically have to do everything through an event loop, which is a bit of a nuisance for simple things but absolutely necessary for building real software that’s going to interact with a Discord server. it also means discord.py only works with Python 3.4 and later. I think that’s all the right choice.

Here is my demo program. It took me a couple of hours in total, half of which was me reminding myself how asyncio works. All in all pretty straightforward, once you figure out the basic paradigm of how it fits together. There’s one choice embedded in my code here, which is I subclassed discord.Client instead of using the function decorator syntax for declaring event handlers. Either works fine.

The unofficial API also makes me understand the Discord product a little better. Unlike Slack, Discord has a notion of a single User that is logged into Discord with an email/password. That user can then be a member of various Servers, each of which has its own Channels. Slack doesn’t really have a cross-Slack notion of User, every Slack is an independent domain. The Discord API’s handling of public/private/DM channels is also a bit more straightforward than Slack’s.

quicky python continuous tests

pytest-watch is a fine quick “continuously run my tests” thing for Python in a tty. It’s nothing fancy, and the default UI is not perfect. But with -c and --no-beep and using --runner to run a custom command for your tests, it’s fine. Nice to not have to switch from my editor window to a console just to run the tests.

I’m envious of the NodeJS folks and their hipster test runners, they are very nice. Alternately I wish there were a good way to turn SublimeText into a bit more of an IDE with debugging and test output parsing. But after years of trying IDEs and going back to plain text editors, I think I’m not going to try to board that ship again.

 

tuple vs list

One small thing in Python3 that continues to confound me is how dict.values, dict.keys, and zip all don’t return real collections but instead iterables. That means you have to wrap them first in a tuple or list if you want to array index the output. It’s not a huge deal, but it’s a nuisance.

So which is better? Tuple or list? Tuple should be in theory, because it’s immutable it should be a little more efficient. Seems to be that way in practice too.

$ python3 -m timeit 'tuple({"a":1}.values())[0]'
1000000 loops, best of 3: 0.266 usec per loop
$ python3 -m timeit 'list({"a":1}.values())[0]'
1000000 loops, best of 3: 0.331 usec per loop

$ python2 -m timeit 'tuple({"a":1}.values())[0]'
1000000 loops, best of 3: 0.227 usec per loop
$ python2 -m timeit 'list({"a":1}.values())[0]'
1000000 loops, best of 3: 0.256 usec per loop

(You know, every time I do a timeit on python2 vs python3, python3 is measurably slower. Some of that is due to Unicode but I don’t think that’s all of it.)

Python HTTP mocking

I need to do a better job mocking out HTTP requests to allow me to test all this web API code I’ve written. Right now I rolled my own bad mocking around a wrapper for all the REST calls, but I think it makes more sense just to mock at the HTTP level.

A quick Google search reveals three modern libraries: requests-mock, responses, and httpretty. After literally tens of minutes I’m left with the opinion any would work. responses-mock looks like the most mature and complete product. I like responses for its simplicity. The main differences between the three are the mechanism they use to intercept HTTP calls. I believe httpretty is the only one that works with an HTTP library other than Requests. OTOH why would you use any other HTTP library in Python?

Update: since doing this exercise I started using requests-mock. I’m quite happy with it.

Some detailed notes below, then my test code.

requests-mock: mocks out Requests by installing a Transport Adapter. (I’m endeared, because I came up with a similar technique on my own for Java back in 2000 or so.) Has detailed support for matching full URLs or parts of URLs or specific query strings or URL regexps. Supports all HTTP methods. Responses can be text, JSON, byte strings, or callbacks. Has a way to inspect which URLs were called. Has great docs.

Responses: mocks out Requests using the unittest.mock library, patching requests’ send function. Supports matching on regex, but no special support for query strings in URLs. Responses can be text or JSON or callbacks. Supports all HTTP methods. Optionally throws an error if not all URLs were accessed. No fancy docs, but the code is easy to read. Motivation in this blog post.

httpretty: works by monkey patching sockets. that’s terrifying, but kinda neat because it can mock out HTTP from sources other than Requests. Oddly they don’t have official Python 3 support (it seems to work though). I didn’t look at all its features in detail.

(BTW, unittest.mock was new to me, a very nice standard library for monkey patching any Python library for unit test mocking. That could come in handy in lots of places.)

Here’s my test / sample code.

#!/usr/bin/env python3

import requests, unittest
import requests_mock, responses, httpretty

def fetch():
    &quot;The method we'll be mocking&quot;
    r = requests.get('https://www.somebits.com/robots.txt')
    return r.text

class TestStuff(unittest.TestCase):
    def test_real(self):
        self.assertEqual(107, len(fetch()))

    def test_requests_mock(self):
        with requests_mock.Mocker() as m:
            m.get('https://www.somebits.com/robots.txt', text='nelson-requests-mock')
            self.assertEqual('nelson-requests-mock', fetch())

    def test_responses(self):
        with responses.RequestsMock() as r:
            r.add(responses.GET, 'https://www.somebits.com/robots.txt', 'nelson-responses-mock')
            self.assertEqual('nelson-responses-mock', fetch())

    def test_httpretty(self):
         httpretty.enable()
         httpretty.register_uri(httpretty.GET, &quot;https://www.somebits.com/robots.txt&quot;, 'nelson-response-httpretty')
         self.assertEqual('nelson-response-httpretty', fetch())
         httpretty.disable()

if __name__ == '__main__':
    unittest.main(exit=False)

    # Verify the environment is left clean
    assert 107 == len(fetch())
    print(&quot;Real requests are working again.&quot;)

A better Python object for JSON take 2

I wrote about wanting a better Python object for JSON. Now I’ve tried out a bunch of options, all inadequate, and am clearer what I want.

The best of the libraries I found was addict. Or maybe easydict because it is slightly less magic. dotmap is also OK but has one wrinkle. attrdict was the only one I couldn’t make work well.

I’ve put sample code exercising various libraries in this gist.

Here are the things I want, in order of priority:

  1. Dot access to fields instead of []
  2. Sensible default value for missing keys instead of an exception
  3. Ease of adding new nested values
  4. Ease of serializing to JSON
  5. Small performance hit

All the libraries provide #1, dot syntax for reading keys. The challenge is #2, what happens if the field is missing (like d.noObj in my code). dotmap and addict both return an empty dict {} for missing keys. That’s not a terrible default although I’d prefer None. attrdict.AttrDefault() lets you choose a different default value but has other problems. easydict just throws exceptions for missing keys; making the dot syntax of questionable usefulness.

The tricky thing is #3 and it ties to what happens if you then assign to an empty dict for a missing key. That’s required for convenient syntax for setting a deeply nested value, the ideal syntax of “d.other.nested.thing = 6”. Both dotmap and addict actually create an empty dict value in the data structure the moment you try to read an empty key. That lets nested assignment work, but leaves litter in your data structure. addict edges out dotmap here because it provides a .prune() method to remove them. easydict doesn’t create empty dict values, so nested assignment isn’t convenient but then it’s less magic.

#4, JSON serialization,is not too hard in any system. addict, easydict, and attrdict just let you pass the thing to json.dump(); their objects are subtypes of dict. dotmap requires you explicitly call .toDict().

I did not measure #5, performance. Each library has a different approach to when it copies data, would be worth examining.

I mentioned above I couldn’t make attrdict work for me. That may be my error, not the library’s. It’s neat in that there’s actually two options; AttrDefault, which provides alternate default values, and AttrDict, which is a bit simpler. But AttrDict has a mysterious / confusing design wrinkle for “Recursive attribute access” that’s a n00b trap. And I couldn’t figure out how to JSON serialize an AttrDefault, nor even how to turn it into a normal dict. Maybe I missed something.

Doing this exercise made me wonder about the wisdom of #2, sensible default values. The problem is there’s not a one-size-fits-all default. Often you want it to be None, for simple primitives. But sometimes you might want [] for an empty list or {} for an empty object. If you want to let the programmer choose those values, you might as well go fully verbose and use the dict.get() method with its default value.

I could see using EasyDict in the future if I only wanted to read JSON and weren’t worried about #2, missing values. It’s the least magic. Or else Addict if I also wanted to construct JSON and get empty dicts returned for missing keys.

Update: it strikes me that a lightweight use of JSON schema would be helpful here. If you know what types to expect, you can fill in any missing keys with appropriate empty values. Not sure anyone uses JSON schema in the wild though. I’d want to start with something that auto-infers schema from examples. And I don’t care about validation, just using type expectations as hints on what to do with ambiguity.

Update Nov 2019: see FlexDict. It has solutions for the creating-objects-for-keys problem.

A better Python object for JSON

Python’s default JSON package encodes and decodes to a dict. This works well enough, but I’ve never much loved the dict type in Python. I’d rather it were an Object with attributes. dicts are verbose: data[“foo”] instead of data.foo. Also dicts throw exceptions on unknown keys, when often what I want is it just to return None. So I’m left with data.get(“foo”, None) which is awfully wordy. Basically I want something that’s as convenient and sloppy as Javascript objects.

I asked on Twitter and got some suggestions, none awesome.

Not sure if these imply overhead from copying, etc. Also they may not serialize well in the JSON module, although I imagine you can copy out a dict view on at least one of these. (More overhead!)

A yak that needs shaving. Don’t they all?

Update: see this second post

SVMs in Python

I started trying to apply SVM machine learning to my Battlefield 4 dataset and got something that only predicted my data with 60% accuracy. I’m expecting 95% or more but I don’t really know and I realized I was trying to learn too many new things at once.

So I went back to my Coursera homework, exercise 6, and used their data and problem sets as Python exercises. Specifically I trained SVM classifiers on two datasets. The result is in this notebook.

Cells 2–4 are me simply fitting a binary classifier to the toy input data. Cells 5–9 are fitting a binary classifier to different data, in this case performing repeated training steps to pick the right parameters C and sigma for the learning system. I did it the homework’s way in cells 6–7, using an explicitly split training and test dataset. Then I used sklearn’s cross_validation library to do the training in 8–9, which is a form of resampling to produce test sets on the fly. Results were roughly the same. I’m not 100% certain it is philosophically kosher to use CV in this manner, but I think it is.

Things I learned:

  • You can load matlab arrays with scipy.io.loadmat()
  • The ‘rbf’ kernel is what sklearn.svm calls the Gaussian kernel.
  • Instead of sigma, sklearn parameterizes rbf with gamma. gamma = 0.5/sigma**2
  • Decision boundaries are plotted by simply creating a raster grid of predictions, then making a contour plot to only show the boundary.

The big thing I learned is how sensitive these systems are to choices of sigma and C. Before I had the code working right I was using bad values and getting insane results. Relatively easy to see in a 2d dataset where you can plot the data and the decision boundary, but this must be much harder to understand and debug in large multidimensional datasets.

My first iPython notebook

I finally sat down and learned some IPython for data exploration today. I re-examined some data I had for Battlefield 4 players, something I’d published as my BF4Plots visualization a year or two ago. It’s the stats on ~5000 top Battlefield 4 players, things like their win/loss ratio, skill score, etc.

You can see my notebook in this gist. That’s a static snapshot taken from my last run. If you run it yourself the results will change slightly as some of the algorithms I apply include randomization.

My main goal here was to get more comfortable using IPython. It’s awesome! I really love having the inline, easy to produce graphs. I mostly followed this tutorial for guidance.

Secondarily I was also trying to apply some cluster analysis to my BF4 data to see if I could learn any insights. Not really. This is my first foray into my own machine learning project applying stuff I’ve learned in my course. And it was interesting, I definitely felt I understood what the scikit algorithms were doing. Also a little lost how to get real meaning out of the data. No surprise, that’s the hard part!

The main IPython thing I’m still adjusting to is that it’s a notebook, not a program. I’m so used to iteratively working and re-running my program from scratch. But IPython encourages you to keep a persistent Python VM around and iteratively add to its state. I keep looking for the “Start over and run it all from scratch” button, and there sort of is one, but that’s not really how you’re supposed to work. Which got me into trouble a couple of times. Also I do wonder how IPython people transition their code to running programs for other people to reuse.

Update: a “restart and run all” button was just merged into the main codebase so that’s coming soon. And apparently I’m right that notebooks are more for exploration. When it comes time to create reusable code you create a normal module with some other code editing environment. You can certainly start by pasting your notebook-developed code over, though.

First Python library I learned was Pandas, the data management library. Really all I did was work a bit with DataFrame, which is a data container type that’s a 2d array on steroids. Columns are typed, everything’s nicely addressable and searchable, and it’s all efficient numeric spare arrays behind the scenes. I think it even supports multicore number crunching in a transparent fashion. Really nice library, a joy to use.

Second library I learned was matplotlib, some basic bashing at it to draw some graphs. It’s really great and I wish I’d invested the time to learn this before. But until I saw the HTML notebooks it wasn’t very compelling to me. It’s funny, Mathematica notebooks have been a thing for 20+ years but it’s only the last couple of years where Python caught up.

Final thing I learned was a bit of scikit-learn, in particular how to apply its PCA and K-Means algorithms. Went pretty smoothly. My only annoyance is it seems to only half-support Pandas. It will take DataFrames as inputs but then the objects it returns are basic numpy Arrays which lack column names and some of the nice slicing options. I can’t tell if I’m doing it wrong, it has to be this way, or if it’s just that Pandas is so new that scikit-learn hasn’t fully adopted it yet.

Anyway, all in all my experiment was a big success, very happy. Fun stuff!

IPython notebooks + geodata

IPython notebooks (ie: Jupyter) seem like an important innovation for me. A really nice web-native REPL for exploratory programming, including decent visualization of data. Plot data in particular, graphing with matplotlib. It’s quite capable, I think approaching what people do with R.

So I’ve been asking around about adding geodata capability to Jupyter. My first thought was a visualizer for GeoJSON, but I’ve learned now there are other approaches. I asked SeanG and he pointed me to a couple of things, which lead to some other things.

Summary: there are several geodata visualization packages that work with IPython. Some integrate with matplotlib and some are standalone geographic tools. None of them quite worked right for me after just a few minutes tinkering, but several seem worth the effort to get working.

folium is closest to what I’m looking for. It’s a Leaflet wrapper for Python with baked in support for geojson, various Stamen tilesets, etc. It seems to support inline plots in IPython notebooks but I couldn’t figure it out, there’s been some discussion that it should work. It doesn’t use matplotlib.

leafletwidget is another Leaflet-based map making tool, here’s an example notebook screenshot. It’s not packaged on PyPI and hasn’t been updated in awhile, looks like it’d take some effort to figure out how to use. But it might be a good basis for building my own thing.

mpleaflet lets you visualize matplotlib plots using Leaflet to add a geographical basemap. It looks very promising but I had some trouble using it out of the box. The key thing here is adding map capability to matplotlib, the primary charting visualization library IPython users use already. Seems good for data visualization but less map-specific.

matplotlib basemap toolkit is a more low-level tool for making maps with matplotlib. No Leaflet or otherwise fancy slippy map, it’s just helping you do map projections and draw geographic data in a single static image. Might be nice for one off visualizations!

cartopy is another non-leaflet map maker in python using matplotlib. It has support for using GoogleTiles. IPython support is not mentioned in the docs but it seems to work.

mpld3 has nothing to do with maps but is neat. It adds D3 rendering for matplotlib plots in your notebook, so you have fancy interactive javascript instead of a static image. Works great right out of the box. I want something that works like this for geodata. See also mplexporter, which seems to handle getting the data out of matplotlib.

GeoPandas is a bridge between Pandas and geographic data, including shapeley/fiona support. It uses descartes too, which is a bridge from geodata to matplotlib plots.

Python looping for n times

A Twitter friend proposed an idiom for doing something N times in Python I hadn’t seen before, Using itertools.repeat instead of range. I was curious if it was better.

$ python3 -V
Python 3.4.3
$ python2 -V
Python 2.7.10

$ python3 -m timeit 'for _ in range(10000): pass'
1000 loops, best of 3: 275 usec per loop
$ python3 -m timeit 'for _ in itertools.repeat(None, 10000): pass'
10000 loops, best of 3: 133 usec per loop
$ python3 -m timeit 'for _ in itertools.repeat(1, 10000): pass'
10000 loops, best of 3: 130 usec per loop

$ python2 -m timeit 'for _ in range(10000): pass'
1000 loops, best of 3: 218 usec per loop
$ python2 -m timeit 'for _ in xrange(10000): pass'
1000 loops, best of 3: 179 usec per loop
$ python2 -m timeit 'for _ in itertools.repeat(None, 10000): pass'
10000 loops, best of 3: 122 usec per loop

So huh, itertools.repeat is about 50% the cost of using range. We’re only talking 13ns per iteration, or roughly 50 CPU cycles. If you’re doing meaningful work in that loop it won’t matter. Still it’s neat that itertools.repeat is more efficient. Perhaps this shouldn’t surprise me, it doesn’t have to do the work of generating increasing integers. But I’d assumed no one had optimized itertools this carefully.

Note that in Python3 range is an actual type and doesn’t create a list, tuple, iterator, or generator. Also interesting that repeating an integer is 3% more efficient than repeating None; that’s a reproducible result.

Python2 is faster across the board. I see that a lot in Python and it makes me wonder. But the itertools vs. range/xrange difference is still about 50%, or meaningful.

Having now understood all this I’ll go right back to using range() like my grandpappy did.

IPython and inline matplotlib

I’m trying out IPython. I’m also playing around with machine learning which means I need some simple data visualization, so I’m playing around with matplotlib. Here’s how to display generated plots inline (as opposed to in a popup window); the docs are inconsistent.

QT: ipython qtconsole --matplotlib inline

Notebook: launch with “ipython notebook”, then run “%matplotlib inline” in a notebook.

Here’s a sample program that generates and shows a plot:

from matplotlib import pyplot as plt
years = range(1950, 2020, 10)
gdp = [300, 543, 1075, 2862, 5979, 10289, 14958]
plt.plot(years, gdp, color='green', marker='o', linestyle='solid')
plt.show()

Python3 zip() is a hassle

A Python3 annoyance; zip() now returns an Iterable, not a list. That means you can’t easily slice it.

In Python 2, this idiom for getting back the first column of a database query was useful:

cur.execute('select ...')
r = cur.fetchall()
firstColumn = zip(*r)[0]

In Python 3, this gives you an error

TypeError: 'zip' object is not subscriptable

The workaround is to wrap the zip in a tuple or list

r = cur.fetchall()
firstColumn = tuple(zip(*r))[0]

Annoying, but it doesn’t actually run any slower. I imagine you could use slice() or itertools.islice() to produce an iterator view of a slice of the zip iterator.

Python3 est arrivé

I’m now using Python3 by default for all new projects. Almost entirely because I prefer sane Unicode handling. But really because Py3 has turned the corner and is now useful for most things. Probably it turned that corner a year or more ago, but it was the OpenAddresses work that made me start using Python 3 regularly. It helps that Homebrew and Debian both make it very easy to install ‘python3’ and ‘pip3’. And of course that most packages I care about are now ported over.

It took Python five years longer than I expected for the Py3 transition to get to this point. Let’s hope we don’t have to do it again.

installing openaddresses-machine in a virtualenv

Trying to get a server up running OpenAddresses in a controlled environment. I’m normally very sloppy and install everything as root in /usr, but I figured I should use virtualenv this time. Machine actually has a very nice Chef setup and bootstraps itself regularly in EC2 and Travis contexts, but I’m stubborn and doing it my own way.

Install openaddresses-machine and it’s simple dependencies

  • Prepare a virtualenv directory and activate it
  • pip install Openaddresses-Machine

Install cairocffi. This required a C library I didn’t have

  • sudo apt-get install libffi-dev
  • pip install cairocffi

Install Python GDAL. This is a mess; I’m not sure why the simple “pip install GDAL” doesn’t work from inside the virtualenv. And I’m not sure the instructions below are correct; it’s probably installing python-gdal globally on the system via and then again in the virtualenv via pip. But that gets all the C dependencies we need somewhere on the system. There’s extra rigamarole to get the bleeding edge GDAL instead of the stock Ubuntu GDAL. Also building GDAL requires a C++ compiler.

  • apt-get install software-properties-common
  • sudo apt-add-repository ppa:ubuntugis/ubuntugis-unstable
  • sudo apt-get update
  • sudo apt-get install python-gdal libgdal-dev
  • sudo apt-get install g++
  • pip install GDAL
  • PSYCH! That won’t work. Follow the instructions in this gist for how to manually configure and install gdal. Apparently its packaging is not compatible with pip?

unicodecsv 0.11.0 speed improvement

My little Python csv parsing benchmark had one really nice effect; someone contributed a patch to remove some unnecessary calls to isinstance in certain circumstances. He claims a 2x speedup. That patch was just released in 0.11.0, so I tested it. These are the same benchmarks and data file I ran and reported before as “Python 2 results”

 61.65s unicodeCsvReader 0.9
118.64s unicodeCsvDictReader 0.9
 41.12s unicodeCsvReader 0.11
 96.34s unicodeCsvDictReader 0.11

Not quite a 2x speedup, but runs in 0.7x or 0.8x the time it used to. That’s quite good for a simple change, and a nice example of open source working well.

I should really stop using the csv DictReader. Or maybe make a new one that’s smarter. The current Python module seems to actually create a real dict object for every row. I think you could make something faster that used a class wrapper for the tuple that emulated dict-style retrieval by looking up column offsets in the row header. At least there’d be less data copied, but maybe the wrapper overhead would negate that. Have to try it to see.

Python file reading benchmarks

After doing my CSV benchmarks yesterday I decided to do something simpler and just compare how long it takes to read files with and without Unicode decoding. My test file input is a 1.8G UTF-8 text file, the actual data is dk.csv, Danish street names. It’s exactly 1,852,070,317 bytes or 1,838,573,679 characters. The file has DOS newlines, so there’s both a 0x13 and a 0x10 at the end of every line. 33,445,793 lines total.

I didn’t use timeit for a proper microbenchmark, but I did warm the cache and make sure the times were repeatable. Some weirdness; sometimes the job takes 2x as long to run. Cannot explain that, maybe some L2 cache contention in a shared CPU? I took the faster timings.

Reading the whole file at once

  • Python 2, reading bytes: 0.5s
  • Python 2, reading unicode via codecs: 5.9s
  • Python 3, reading bytes: 0.5s
  • Python 3, reading unicode via codecs: 1.6s
  • Python 3, reading unicode via open(): 3.7s
  • Python 3, reading unicode via open with no newline conversion: 2.2s

Conclusions

  • Python 2 and Python 3 read bytes at the same speed
  • In Python 2, decoding Unicode is 10x slower than reading bytes
  • In Python 3, decoding Unicode is 3–7x slower than reading bytes
  • In Python 3, universal newline conversion is ~1.5x slower than skipping it, at least if the file has DOS newlines
  • In Python 3, codecs.open() is faster than open().

That last one about codecs.open is really weird. Codecs isn’t doing newline conversion, but even so it’s still 1.6s vs 2.2s. Maybe open() also does some other processing?

Reading the file a line at a time

  • Python 2, reading bytes: 0.6s
  • Python 2, reading unicode via codecs: 43s
  • Python 3, reading bytes: 1.0s
  • Python 3, reading unicode via codecs: 58s
  • Python 3, reading unicode via open(): 3.5s
  • Python 3, reading unicode via open with no newline conversion: 3.3s

Conclusions

  • Python 3 is ~1.7x little slower reading bytes line by line than Python 2
  • In Python 2, reading lines with Unicode is hella slow. About 7x slower than reading Unicode all at once. And Unicode lines are 70x slower than byte lines!
  • In Python 3, reading lines with Unicode is quite fast. About as fast as reading the file all at once. But only if you use the built-in open, not codecs.
  • In Python 3, codecs is really slow for reading line by line. Avoid.

Overall conclusion

Python 3 UTF-8 decoding is significantly faster than Python 2. And it’s probably best to stick with the stock open() call in Py3, not codecs. It may be slower in some circumstances but it’s the recommended option going further and the difference isn’t enormous.

Some of these benchmark numbers are surprising. My guess is that someone optimized Python 3 UTF-8 decoding very intensely, which explains why it’s better than Python 2. And the really terrible times like 40-50s are because some Python code (ie: not C) is manipulating the data, or else data structures are being mutated and it’s breaking CPU caches.

The code

"""Simple benchmark of reading data in Python 2 and Python 3,
comparing overhead of string decoding"""

import sys, time, codecs

fn = sys.argv[1]

def run(f):
    "Run a function, return time to execute it."
    # timeit is complex overkill
    s = time.time()
    f()
    e = time.time()
    return e-s

def readBytesAtOnce():
    fp = open(fn, 'rb')
    fp.read()

def codecsUnicodeAtOnce():
    fp = codecs.open(fn, encoding='utf-8')
    fp.read()

def py3UnicodeAtOnce():
    fp = open(fn, encoding='utf-8')
    fp.read()

def py3UnicodeAtOnceNoNewlineConversion():
    fp = open(fn, encoding='utf-8', newline = '')
    fp.read()


def readBytesByLine():
    for l in open(fn, 'rb'):
        pass

def codecsUnicodeByLine():
    for l in codecs.open(fn, encoding='utf-8'):
        pass

def py3UnicodeByLine():
    for l in open(fn, encoding='utf-8'):
        pass

def py3UnicodeNoNewlineConversionByLine():
    for l in open(fn, encoding='utf-8', newline = ''):
        pass

atOnce = [readBytesAtOnce, codecsUnicodeAtOnce]
if sys.version_info.major == 3:
    atOnce.append(py3UnicodeAtOnce)
    atOnce.append(py3UnicodeAtOnceNoNewlineConversion)

byLine = [readBytesByLine, codecsUnicodeByLine]
if sys.version_info.major == 3:
    byLine.append(py3UnicodeByLine)
    byLine.append(py3UnicodeNoNewlineConversionByLine)

open(fn).read()    # warm cache
for f in byLine:
    t = run(f)
    print('%7.2fs %s' % (t, f.__name__))

Python CSV benchmarks

I tested various ways of reading a CSV file in python, from simply reading the file line by line to using the full unicodecsv DictReader. Here’s what I discovered. Test data is dk.csv, a 3.4M row CSV file with 46 columns. (See also: file reading benchmarks.)

  • The Python2 csv module takes 2x longer than a naive split(‘,’) on every line
  • Python2 DictReader takes 2-3x longer than the simple csv reader that returns tuples
  • Python2 unicodecsv takes 5.5x longer than csv
  • Python3 csv takes 2-3x longer than Python2 csv. However it is Unicode-correct
  • Pandas in Python2 is about the same speed as DictReader, but is Unicode-correct.

I’m not sure why unicodecsv is so slow. I did a quick look in cProfile and all the time is being spent in next() where you’d expect. All those isinstance tests add significant time (20% or so) but that’s not the majority of the 5.5x slowdown. I guess string decoding is just a lot of overhead in Python2? It’s not trivial in Python3 either; I hadn’t realized how much slower string IO was in Py3. I wonder if there’s more going on. Anyway I filed an issue on unicodecsv asking about performance.

I’ve never used Pandas before. I ran into someone else saying unicodecsv is slow who switched to Pandas. It sure is fast! I think it’s a lot of optimized C code. But Pandas is a big package and has its own model of data and I don’t know that I want to buy into all of that. Its CSV module is nicely feature-rich though.

Not sure what conclusion to draw for OpenAddresses. I think we spend ~50% of our time just parsing CSV (for a CSV source like dk or nl). Switching from DictReader to regular reader() is the least pain. Concretely, for a 60 minute job that’d bring the time down to about 40–45 minutes. A nice improvement, but not life altering. Switching to Python3 so we no longer need unicodecsv would also save about the same amount of time.

Python 2 results

 0.17s catDevNull
 0.25s wc
 1.91s pythonRead
 0.58s pythonReadLine
 6.62s dumbCsv
 10.97s csvReader
 29.63s csvDictReader
 62.82s unicodeCsvReader
120.93s unicodeCsvDictReader
 27.93s pandasCsv

Python 3 results

 0.17s catDevNull
 0.25s wc
 5.18s pythonRead
 3.50s pythonReadLine
11.83s dumbCsv
27.77s csvReader
51.37s csvDictReader

The Code

# Benchmark various ways of reading a csv file
# Code works in Python2 and Python3

import sys, time, os, csv, timeit
try:
    import unicodecsv
except: 
    unicodecsv = None
try:
    import pandas
except:
    pandas = None

fn = sys.argv[1]

def warmCache():
    os.system('cat %s &amp;gt; /dev/null' % fn)

def catDevNull():
    os.system('cat %s &amp;gt; /dev/null' % fn)

def wc():
    os.system('wc -l %s &amp;gt; /dev/null' % fn)

def pythonRead():
    fp = open(fn)
    fp.read()

def pythonReadLine():
    fp = open(fn)
    for l in fp:
        pass

def csvReader():
    reader = csv.reader(open(fn, 'r'))
    for l in reader:
        pass

def unicodeCsvReader():
    reader = unicodecsv.reader(open(fn, 'r'))
    for l in reader:
        pass

def csvDictReader():
    reader = csv.DictReader(open(fn, 'r'))
    for l in reader:
        pass

def unicodeCsvDictReader():
    reader = unicodecsv.DictReader(open(fn, 'r'))
    for l in reader:
        pass

def dumbCsv():
    'Really simplistic CSV style parsing'
    fp = open(fn, 'r')
    for l in fp:
        d = l.split(',')

def pandasCsv():
    d = pandas.read_csv(fn, encoding='utf-8')
    # Ensure pandas really read the whole thing
    d.tail(1)

def run(f):
    &amp;quot;Run a function, return time to execute it.&amp;quot;
    # timeit is complex overkill
    s = time.time()
    f()
    e = time.time()
    return e-s

warmCache()

functions = [catDevNull, wc, pythonRead, pythonReadLine, dumbCsv, csvReader, csvDictReader]
if unicodecsv:
    functions.append(unicodeCsvReader)
    functions.append(unicodeCsvDictReader)
if pandas:
    functions.append(pandasCsv)

for f in functions:
    t = run(f)
    print('%.2fs %s' % (t, f.__name__))

OpenAddresses optimization: some baseline timings

Some rough notes for optimizing openaddresses conform. These times are from a January 23 run of the Python code. The machine was busy running 8x jobs, so times may be a bit inflated from true, but it’s a start.

Here’s 3 sources that I know to be slow because of our own code. The time reported here are purely the time doing conform after the thing was downloaded.

  • nl (csv source): 35 minutes, 14.8M rows
  • dk (csv source): 43 minutes, 3.4M rows
  • au-victoria (shapefile source): 46 minutes, 3.4M rows
  • ??? ESRI source. No good examples; most of my conform code treats this as effectively CSV anyway, so going to ignore for now.

I just ran nl again and it took 31.5 minutes (26 minutes user, 5 minutes sys). Close enough, I’ll take these January 23 times as still indicative. At least for CSV sources.

Here’s some fast / short sources I can use for testing. These are total times including network.

  • us-ca-palo_alto.json (csv source) 26 seconds
  • ca-bc-north_cowichan.json (csv source) 24 seconds
  • us-wa-chelan.json (shapefile source) 33 seconds

And here’s a report of top slow jobs that didn’t actually time out. Some of this slowness is due to network download time.

3521s us-va-city_of_chesapeake.json
2807s au-victoria.json
2765s us-ca-marin_county.json
2589s dk.json
2116s nl.json
2032s us-sc-aiken.json
1660s us-va-new_kent.json
1639s es-25830.json
1541s us-nc-alexander.json
1498s us-va.json
1367s us-va-fairfax.json
1352s us-sd.json
1345s us-ca-los_angeles_county.json
1325s us-mn-ramsey.json
1216s us-al-calhoun.json
1015s us-mi-kent.json
973s us-ms-hinds.json
955s us-wa-skagit.json
937s us-tn-rutherford.json
918s us-ca-solano_county.json
918s us-nc.json
786s us-fl-palm_beach_county.json
783s us-wa-seattle.json
776s us-wa-king.json
769s be-flanders.json
762s us-sc-laurens.json
729s us-wy-natrona.json
691s us-il-mchenry.json
682s us-tx-houston.json
678s us-al-montgomery.json
656s pl.json

grep Finished *.log | sort -nr  -k 9 | cut -c 65- | sed ‘s%for /var/opt/openaddresses/sources/%%’ | head -50

Here’s some quicky cProfile output, sorted by cumulative time.

ca-bc-north_cowichan

python -m openaddr.conform ~/src/oa/profile/sources-fast/ca-bc-north_cowichan.json ~/src/oa/profile/caches/cowichan.csv /tmp/o/foo
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    6.053    6.053 <string>:1(<module>)
        1    0.000    0.000    6.053    6.053 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:723(main)
        1    0.000    0.000    6.049    6.049 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:700(conform_cli)
        1    0.000    0.000    3.628    3.628 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:652(extract_to_source_csv)
        1    0.042    0.042    3.628    3.628 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:433(csv_source_to_csv)
    30260    0.170    0.000    3.241    0.000 /usr/local/lib/python2.7/dist-packages/unicodecsv/__init__.py:187(next)
    30260    0.163    0.000    2.958    0.000 /usr/lib/python2.7/csv.py:104(next)
    30262    2.639    0.000    2.715    0.000 /usr/local/lib/python2.7/dist-packages/unicodecsv/__init__.py:105(next)
        1    0.042    0.042    2.421    2.421 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:678(transform_to_out_csv)
    15129    0.066    0.000    1.328    0.000 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:510(row_extract_and_reproject)
559802/15130    0.636    0.000    1.256    0.000 /usr/lib/python2.7/copy.py:145(deepcopy)
15132/15130    0.147    0.000    1.219    0.000 /usr/lib/python2.7/copy.py:253(_deepcopy_dict)
    30260    0.028    0.000    0.822    0.000 /usr/lib/python2.7/csv.py:151(writerow)
    30260    0.033    0.000    0.599    0.000 /usr/local/lib/python2.7/dist-packages/unicodecsv/__init__.py:82(writerow)
    15129    0.026    0.000    0.571    0.000 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:558(row_transform_and_convert)
    30262    0.085    0.000    0.402    0.000 /usr/local/lib/python2.7/dist-packages/unicodecsv/__init__.py:46(_stringify_list)
   332882    0.147    0.000    0.312    0.000 /usr/local/lib/python2.7/dist-packages/unicodecsv/__init__.py:35(_stringify)
   509313    0.236    0.000    0.309    0.000 /usr/lib/python2.7/copy.py:267(_keep_alive)
    15129    0.025    0.000    0.256    0.000 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:590(row_smash_case)
    30260    0.170    0.000    0.196    0.000 /usr/lib/python2.7/csv.py:143(_dict_to_list)

us-wa-chelan

python -m openaddr.conform ~/src/oa/profile/sources-fast/us-wa-chelan.json ~/src/oa/profile/caches/chelan/*shp /tmp/o/foo

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000   29.549   29.549 <string>:1(<module>)
        1    0.000    0.000   29.549   29.549 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:723(main)
        1    0.000    0.000   29.545   29.545 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:700(conform_cli)
        1    0.000    0.000   19.640   19.640 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:652(extract_to_source_csv)
        1    3.952    3.952   19.640   19.640 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:343(ogr_source_to_csv)
        1    0.163    0.163    9.903    9.903 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:678(transform_to_out_csv)
    44111    0.367    0.000    6.508    0.000 /usr/local/lib/python2.7/dist-packages/unicodecsv/__init__.py:187(next)
  1764400    2.433    0.000    6.275    0.000 /usr/lib/python2.7/dist-packages/osgeo/ogr.py:3012(GetField)
    44111    0.324    0.000    5.837    0.000 /usr/lib/python2.7/csv.py:104(next)
    44112    5.138    0.000    5.370    0.000 /usr/local/lib/python2.7/dist-packages/unicodecsv/__init__.py:105(next)
    88222    0.095    0.000    3.969    0.000 /usr/lib/python2.7/csv.py:151(writerow)
    88222    0.120    0.000    2.759    0.000 /usr/local/lib/python2.7/dist-packages/unicodecsv/__init__.py:82(writerow)
    44110    0.078    0.000    2.512    0.000 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:558(row_transform_and_convert)
    88224    0.450    0.000    1.791    0.000 /usr/local/lib/python2.7/dist-packages/unicodecsv/__init__.py:46(_stringify_list)
   972727    0.595    0.000    1.578    0.000 {method 'decode' of 'str' objects}
    44110    0.078    0.000    1.487    0.000 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:590(row_smash_case)
  1764440    0.502    0.000    1.328    0.000 /usr/lib/python2.7/dist-packages/osgeo/ogr.py:3183(GetFieldDefn)
  2029152    0.652    0.000    1.325    0.000 /usr/local/lib/python2.7/dist-packages/unicodecsv/__init__.py:35(_stringify)
    88222    0.933    0.000    1.114    0.000 /usr/lib/python2.7/csv.py:143(_dict_to_list)
  7149945    1.114    0.000    1.114    0.000 {isinstance}
  1764400    0.537    0.000    1.109    0.000 /usr/lib/python2.7/dist-packages/osgeo/ogr.py:3478(GetNameRef)
  1764400    0.440    0.000    0.988    0.000 /usr/lib/python2.7/dist-packages/osgeo/ogr.py:2552(IsFieldSet)
   972728    0.309    0.000    0.983    0.000 /usr/lib/python2.7/encodings/utf_8.py:15(decode)
  1764400    0.504    0.000    0.960    0.000 /usr/lib/python2.7/dist-packages/osgeo/ogr.py:2277(GetFieldCount)
    44110    0.715    0.000    0.920    0.000 /home/nelson/src/oa/openaddresses-machine/openaddr/conform.py:592(<dictcomp>)
    88222    0.848    0.000    0.848    0.000 {method 'writerow' of '_csv.writer' objects}
  1764440    0.826    0.000    0.826    0.000 {_ogr.FeatureDefn_GetFieldDefn}
   972727    0.258    0.000    0.782    0.000 /usr/lib/python2.7/dist-packages/osgeo/ogr.py:2335(GetFieldAsString)
   972728    0.674    0.000    0.674    0.000 {_codecs.utf_8_decode}
    44111    0.026    0.000    0.636    0.000 /usr/lib/python2.7/dist-packages/osgeo/ogr.py:1190(GetNextFeature)

Profile conclusions

For a CSV source, we spend roughly half the time converting source CSV to extracted and half converting extracted to final output. That’s no surprise; the two CSV files are nearly identical. A whole lot of that time is spent deep in the bowels of Python’s CSV module reading rows. Again no surprise, but it confirms my suspicion that DictReader may be doing more work than we’d like.

For a shapefile source, we spend roughly 2/3 of the time using OGR to convert to CSV and 1/3 of the time converting the intermediate CSV to the final output. The OGR code is opaque, not clear how to figure out what it’s really spending time doing inside the C module.

Not clear what conclusions to draw here; there never is with profiling tools. I think my next step should be benchmarking Python’s CSV DictReader and seeing whether some simpler parsing would work significantly faster. I also think it’d be a huge improvement to remove that intermediate CSV file entirely, there’s a lot of overhead reading and writing it. It makes the code way simpler to work with but it should be possible to stream the data in memory and retain most of the same code model.

Not clear any of this optimization is worth the effort.

OpenAddress Machine mark 3

this post is a work in progress

Motivation

When I’m back from India late February I’d like to re-design OpenAddress machine to a more decoupled architecture. Right now the system runs one big Python process which runs all sources from download all the way to output CSV. (There is some state carried over from run to run, but not much.) It works pretty well and is simple, and a full run just takes 2–3 hours. But the multiprocessing stuff is brittle and the whole system is both overkill (most sources never change, why reprocess?) and also non-responsive (no fast way to test a new source).

Proposal

Move to a decoupled architecture where tasks are run as fully independent Unix processes. They share state via some centralized database / cloud storage thingy, and also post results in S3 for web serving.

As with the current architecture, the unit of work in the job system is a single source file such as us-ca-san_francisco. It runs as an independent Unix process with no awareness of other sources. It downloads, conforms, summarizes, reports, and uploads its results to the database and to S3.

In addition we also need a task queueing system, something that decides when to run source jobs and posts them on the task queue. That process works mostly by reading the database and deciding what work needs doing. Some rules: “immediately process a new source”. “Check a source weekly for new data and reprocess”. “Clear the whole queue and re-process it”.

Finally we need a task executor that looks at the queue and launches tasks as needed. This could be part of the task queuer, but it helps to think of it as a separate entity. When a task is finished it puts the result on the task record log.

Database implementation

I’m totally agnostic about the data store we use to track runs. It’s a very low demand system just a few hundred megs of data and a handful of transactions a minute. It will require something with consistency and responsiveness. The simple choice is a PostGIS database running persistently on some 24/7 server. I’m not sure what the cloud services equivalent would be, so running with the PostGIS idea, here’s some schema sketches:

Completed task records

  • Task ID
  • Time started
  • Time finished
  • Source name
  • Success / failure
  • S3 output paths: out.csv result, debug logs, etc
  • Whatever else write_state does.

Task queue

  • There’s a zillion ways to do a task queue in a database. Rows are placed in the table by the task queuer, then removed by the task launcher when they are dispatched.

Task implementation

A task should be a single Python program. It takes a source.json specification file and any job metadata that’s needed (hopefully none?) and executes it. For debugging purposes this program should be able to be run standalone on a developer’s machine with no dependencies on the queuing system, the task manager database, or S3.

These jobs will be a natural to run on cheap EC2 spot instances. Right now tasks take 0.5 – 90 minutes to run. A bit wasteful to spin up a whole EC2 instance for 30 seconds of work, but maybe that’s OK. We could also run tasks on a single workhorse machine, that’s effectively what we’re doing now. A single mid-level Linux box can run 16 tasks in parallel. (In fact parallelism is good; the jobs are a mix of load types.)

Alternate: subtasks

This proposal assumes that a whole source from start to finish is run as a single Python process. But in fact processing a source consists of several sub tasks, and it might be good to run them as separate sub-tasks. Here’s what the subtasks are:

  • Download from source URL / ESRI store
  • Sample the source data for user inspection
  • Convert the source JSON/CSV/SHP data to an extracted.csv file
  • Conform the extracted.csv data to OpenAddresses out.csv format
  • Upload out.csv and job data to S3

There’s times i’ve wanted to be able to execute these subtasks separately. Particularly the download part, that is slow and unreliable. To some extent the current data caching strategy in Mark 1 and 2 is dealing with that, and it may be sufficient. But you could imagine breaking every source into 5 tasks and running them separately on a job queue. Worth considering.

History

Why “mark 3”?

OpenAddress Machine mark 1 was Mike’s original work, wrapping the Node code in a bunch of Python scripts to do regular runs and post results in a web dashboard. It is awesome.

We’ve been working on mark 2, the “ditch-node” branch, where we rewrote all the Node code in Python. The overall job architecture is about the same as mark 1, the management of downloads and files and stuff. It’s one big Python process with jobs run in parallel using multiprocessing. We did make some changes to how tasks are conceived and run.

Updates

Some notes after this post was written

  • Ian notes that GitHub triggers and Jenkins could trigger a build on a new source

multiprocessing worker processes dying

Python’s multiprocessing.Pool has a design wrinkle that’s a bit awkward. If you have a pool with N tasks and one of those task subprocesses dies unexpectedly (say, to a SIGTERM or something) then the pool hangs. It looks like N-1 tasks have finished and there’s still one waiting. But it will never complete and your parent process will effectively be stuck. Note that normal termination doesn’t do that, including random exceptions, SIGINT from Ctrl-C, etc. A normal “kill” triggers this though, as certainly does a “kill -9”. Probably a segfault in the Python interpreter will too.

Personally I think this is a bad design choice, but it’s not by accident. There was a huge discussion about this behavior three years ago. I haven’t read it all, but most of the comments seem to be about the wisdom and difficulty of recovering from a bad state. The ticket got closed after someone committed some changes to concurrent.futures (Python 3’s preferred new library). Nothing changed in multiprocessing.Pool.

Recently this issue was revisited for multiprocessing.Pool with a new bug filed that includes a patch. The approach there (and concurrent.futures) is if a child dies unexpectedly, you want to kill the whole Pool immediately with a BrokenProcessPool exception. I’m not wild about this choice, but it’s definitely better than hanging.

None of this applies to the Python distribution we’re running today. The pool will hang. For OpenAddresses I suggest we work around the issue by simply not killing workers. If you want to abort a worker early, try SIGALRM. We could also install a SIGTERM handler to catch the simple “kill” case from an operator, but I’m not sure that’s wise.

In addition, OpenAddresses also has a SIGUSR1 handler that allows someone externally to shut down the whole pool. It’s good for recovering from this state.

Update: we hit this bug again in a new way. Some of the worker processes were getting killed by the Linux OOM Killer. The Python code doesn’t see any exception, it’s just a SIGTERM or something. Only way you know is a record in the syslog. (And the multiprocessing debug logs show a new worker started.)

OpenAddress Machine job management

Our OpenAddresses system wants to run N jobs at once while downloading and processing our ~1000 sources. Mostly to do a bunch of network requests to various servers in parallel, but also for some CPU parallelism in multi-core systems. Normal jobs use very little RAM (100M?) but occasionally a big GeoJSON file blows up to 2G or 4G. Here’s 4 options for job management.

Unix processes. I’ve been running stuff in GNU parallel, forking off a new Python process for each job. 8 simultaneous processes on a 8 CPU system. That’s worked pretty well, see previous blog posts for notes. CPU usage around 250%, memory usage all over the place but generally under 2G. Full job finishes in 3, 4 hours.

Python threads. I just tried openaddr-process for the first time to run a full go (on the same Linux box). That code works by spawning 16 threads. So one big Python process. That’s not working quite so well. Running at a steady 120% CPU; because of Python’s GIL we can’t get more parallelism. The process also has 11G resident. I suspect much of that could be reclaimed, probably left over from when 2 or 3 big GeoJSON jobs ran at once. But that stresses the garbage collector; there’s something to be said about killing a process. (Update: the resident set size got as big as 17G at one point, enough to force swapping. It didn’t seem to thrash though. Also Python is releasing the memory again later, the RSS has gotten as small as 9G again.)

Python multiprocessing. I want to try this. It should be a relatively easy change from threading, but I am hoping gives some CPU parallelism and memory housekeeping. Also we need a way to kill jobs asynchronously and Python’s threading module is designed to make that possible. With multiprocessing you just send a SIGTERM and are done.

Decoupled task architecture. openaddr-process is structured to do the job as one big long-lived Python process. Even with multiprocessing, when an individual job finishes it’s passing Python objects back to the task manager, which waits 3+ hours to collect them all before formatting the crucial report. This is brittle. Long term I’d like to redesign the system to be more decoupled, so that individual jobs run as completely separate processes and autonomously store state in some persistent storage; files and maybe a row or two in a database. Then the overall Machine monitor can just fork off jobs as it needs and collect data off the database. That’s much more like a task queue architecture, a robust thing. I know how to build this with my own servers, less clear how to match it to the EC2 model of cloud computing.

Fiona vs Unicode

Following on my OGR/Python vs Unicode work, I took a look at what Fiona is doing. Fiona is a nice Pythonic interface to OGR with a fair amount of Cython code to bridge the gap from the OGR C library to Python idioms. Fiona explicitly returns all strings as u’Unicode Strings’ in both Python 2 and 3 and has code to handle encodings.

Fiona tries to guess encodings. In theory you can override the guess with an encoding=’foo’ parameter when you open a source, but in practice that seems to do nothing. I tried passing in obviously wrong encodings like ‘ascii’ or ‘shift-jis’ and didn’t see any of the expected errors.

Below is the repr of the string Cassiopée as it comes through from the Shapefile in Fiona, with its own guessing. These all appear correct to me. Note that Python 2 encodes Unicode string reprs as ASCII using Python \x escaping, hence the \xe9 in the output. That’s a single character, the expected Unicode codepoint U+00e9 or é.

Good file (ca-qc-gatineau)

Python2. Fiona: u’Cassiop\xe9e’  OGR: b’76 Rue de Cassiop\xc3\xa9e’
Python3: ‘Cassiopée’  OGR: u’Cassiopée’.

Bad file (be-flanders)

Python2. Fiona: u’Now\xe9lei’  OGR: b’Now\xe9lei’
Python3. Fiona: u’Nowélei’  OGR: exception.

Summary

Fiona seems to be doing the right thing with both my inputs, returning proper Unicode strings in both Python 2 and Python 3. In Python 2 OGR seems to basically not be decoding at all, just returning byte strings that I’m supposed to decode myself. In Python 3 OGR is trying to return Unicode strings but throws an exception on my bad file.

I think from here, for our OGR code I should add something to explicitly decode strings to Unicode in Python 2 and file a bug in Python 3.

Fiona code

'Extract fields from shapefiles using Fiona, a Unicode test'

import sys, fiona, logging
from pprint import pprint

logging.getLogger().setLevel(logging.DEBUG)
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)

enc = sys.argv[2] if len(sys.argv) > 2 else None
with fiona.open(sys.argv[1], 'r', encoding=enc) as source:
    for f in source:
        for field in f['properties'].values():
            sys.stdout.write('%s %r ' % (type(field), field))
        sys.stdout.write('\n')

OGR/Python vs. Unicode

I’ve been trying to figure out how OGR deals with Unicode, particularly in shapefiles, to solve this issue with OpenAddress conversion. I haven’t found clear docs. There’s something about a SHAPE_ENCODING environment variable and something else about OGR trying to guess. More details in that linked GitHub issue. Anyway, here’s what I discovered.

Good file

I have a working non-ASCII shapefile that seems to be in UTF-8. It’s ca-qc-gatineau for us, stored at http://gatineau.ca/donneesouvertes/telechargement/ADRESSE.zip, and has street names like Rue de Cassiopée that our code is working for us.

When OGR/Python opens the file, the capability OLCStringsAsUTF8 is set to True.

In Python 2, GetField() is returning Python strings of type str, which means “bytes”. Those strings appear to be sequences of UTF-8 code points, the repr() of that non-ascii street name is ’76 Rue de Cassiop\xc3\xa9e’. Basically OGR isn’t trying to handle Unicode at all for us, or rather if it is it’s returning UTF-8 encoded byte strings and all is well.

In Python 3, GetField() is also returning Python strings of type ‘str’, which now means ‘unicode’. Their repr in Py3 is a Unicode string, ‘Rue de Cassiopée’, which makes sense.

In both cases OGR/Python is doing the right thing, or at least something consistent and sensible.

Bad file

I have a non-ASCII shapefile that seems to be in Latin 1. It’s be-flanders for us, stored at https://downloadagiv.blob.core.windows.net/crab-adressenlijst/Shapefile/CRAB_Adressenlijst.zip. It has street names like ‘Nowélei (Jean Baptiste)’ although that é isn’t coming through right.

When OGR/Python opens the file, the capability OLCStringsAsUTF8 is set to False.

In Python 2, GetField still returns ‘str’. And the repr for that street is ‘Now\xe9lei (Jean Baptiste)’. That’s actually not awful; if I know to expect that behavior, I can decode that myself with ISO-8859-1 and get the Unicode string.

In Python 3, GetField() throws an exception.

Traceback (most recent call last):
  File /home/nelson/src/oa/shpenc.py, line 17, in &amp;amp;lt;module&amp;amp;gt;
    field = in_feature.GetField(i)
  File /usr/lib/python3/dist-packages/osgeo/ogr.py, line 3033, in GetField
    return self.GetFieldAsString(fld_index)
  File /usr/lib/python3/dist-packages/osgeo/ogr.py, line 2362, in GetFieldAsString
    return _ogr.Feature_GetFieldAsString(self, *args)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 3: invalid continuation byte

I don’t quite understand what is happening here, but I guess something inside the OGR code is trying to decode that sequence assuming it’s UTF-8 and failing. Note my code is not really in the stack trace here, I”m just asking for the field contents. I think this is an OGR bug. Or else I think the Shapefile is corrupt. Setting SHAPE_ENCODING before invoking my code doesn’t help.

Worth noting QGIS displays the string as Nowlei, skipping the non-ascii character.

Summary

It appears that what OGR is doing is trying to guess and cope with the source encoding, presenting UTF-8 byte strings to Python 2 code and Unicode strings to Python 3 code. Which is great! Only things go wrong with the be-flanders file. OGR presents an ISO-8859-1 byte string to Python 2, which you can cope with. OGR crashes in Python 3.

Test code

Here’s the little OGR/Python program I’m using to examine shapefiles. It runs in both Python2 and Python3.

import sys
from osgeo import ogr, osr
ogr.UseExceptions()

in_datasource = ogr.Open(sys.argv[1], 0)
in_layer = in_datasource.GetLayer()
inSpatialRef = in_layer.GetSpatialRef()

in_layer_defn = in_layer.GetLayerDefn()
in_feature = in_layer.GetNextFeature()
print('OLCStringsAsUTF8? %r' % in_layer.TestCapability(ogr.OLCStringsAsUTF8))
while in_feature:
    row = dict()
    for i in range(0, in_layer_defn.GetFieldCount()):
        field = in_feature.GetField(i)
        sys.stdout.write('%s %r ' % (type(field), field))
        in_feature = in_layer.GetNextFeature()
    sys.stdout.write('\n')

Python: logging different threads to different files

The OpenAddresses code includes a Python task manager thats spins off a lot of Python threads, one per input file describing a job. We’d like to capture the debug log records for each thread to a separate file, for presentation in a dashboard. How to do that?

This demo program I wrote shows how. The key concept here is a Python logging.Handler() object that uses some per-Thread state to decide where to write the message. In this case I use the Thread name itself, but you could also use some state stored in Thread.local().

Also this feels related.. log4j had a way to store information in ThreadLocal variables that you could then write out to log files. Ie: you could add a special per-thread variable like “job name” or “HTTP session ID” and have the formatter print it out where appropriate. It was quite handy in some use cases. Python doesn’t exactly have that, but the cookbook has notes on doing something similar with Filters.

Update: see also Mike’s alternate approach. He creates a new Handler for every thread, then uses a Filter to only show messages from the thread he cares about. I like how the approach makes more use of logging’s machinery, it is a bit weird how I had to make a whole Handler that did something odd with the output. I think Mike’s approach means for N threads we’ll end up with N Handlers seeing every log message. That’d be inefficient but if there’s not 100+ threads I doubt it matters.

Python logging: __name__

I’ve been using the recommended idiom of getLogger(__name__) to log stuff in Python code. That’s supposed to turn into your module name so you get nice names like “openaddr.conform” for the file openaddr/conform.py.

Only it totally breaks if you invoke conform.py as a main function via python -m or the like. Because of course __name__ is set to __main__ in that condition.

Wonder why none of the logging tutorials mention that gotcha?

First run of Python OpenAddress code against full source set

After a couple of weeks of steady work the Python code to process OpenAddresses is nearly feature complete. I did a big run last night over all the sources we have. It went well!

Output statistics

  • 608 input sources: 402 out.csv files, 372 sample.json files
  • 80M out.csv rows. (Compare 100M from the Node code)
  • 3 hours, 5 minutes running time
  • < 16G RAM running 8x parallel
  • 11.5G of useful output files
  • 100+G disk used (temp files left on error)
  • 7G of cached source data: 3.5G zip, 3.5G json
  • 150Wh = $0.50 of electricity

Operational behavior

I ran the whole thing with 8x parallelism using GNU Parallel on my Linux box. The box is nothing special; a quad core i7 with 16G of RAM and a very ordinary 7200RPM hard drive. Home network is 100Mbit for downloads.

I think disk contention was the primary bottleneck, an SSD might make a big difference. So would keeping data in RAM while we process it, I think I overwhelmed the disk cache. FWIW the disk has a benchmarked performance of about 120 MBytes/second. But having listened to the thing, there was an awful lot of seeking going on. Parallelism isn’t friends with a single spinning drive.

Below are some munin graphs for the day of the run. There’s two runs here; an aborted run to the disk sda (which filled), then a successful run around 04:30 to 07:30 to the disk sdb. Not sure the graphs have a whole lot of information. They do show some serious IO contention; the CPU graph shows as much time spent in IO wait as doing actual work and disk latencies hit 500ms for awhile there, ugh. The memory graph is too messy to read but I do know the system never needed to swap.

Python 2 vs 3 gotcha: dict views

Python 3 changes something subtle in the core dict data type.

$ python2 -c 'print(type({}.items()))'
type 'list'
$ python3 -c 'print(type({}.items()))'
class 'dict_items'

The return type of dict.keys(), values(), and items() is no longer a simple list, it’s some fancy iterable. Unfortunately that iterable type doesn’t support other list methods like sorted. I guess the new type is more efficient, but it sure is a nuisance.

The simple workaround is to turn the result into a list.

sorted(list(myDict.items()))

But it’s more complicated than that, in fact there’s a whole PEP 469 about it.

Update: derp, I made a mistake. There’s no need to make the list, sorted(myDict.items()) works fine. However there are still other cases where you need to turn the dict_items type in to a real list.

I’m mostly having a good experience with Python 3 but run into weird little changes like this that bite you from time to time.

 

python string formatting: truncation

Learned a new trick in python today, truncating strings in format specs using .precision.

>>>"%.2s" % "abcdef"
'ab'

Using this while yak-shaving, improving my Python logging formatting by truncating the log level name from a string like WARNING to a single character W

%(levelname).1s %(module)s:%(lineno)-4d %(message)s

W process_one:40   Nothing processed
I process_one:103  Wrote to state: /tmp/testOA-tJZweo/us-ca-oakland/index.json

openaddresses-conform Node code notes (plus bonus Python)

I’m working on porting openaddresses-conform from NodeJS to Python. First time I really sat down and read the code from start to finish. It’s remarkably clean and easy to follow, once you read past all the async-back-bending.

The basic flow of the tool is to take arbitrary source files, convert them to CSV files in a schema similar to the source, then convert that source CSV schema to the out.csv schema of OpenAddresses, the one with LON,LAT,NUMBER,STREET. It works by creating a lot of files on disk to hold intermediate results of transformations.

Here’s the core logic, which starts at processSource(). ConformCLI() is the command line tool entry point.

processSource(): download a source from the Internet, conform it, upload out.csv to S3.

conformCache() is the meat of the extract and transform process. It has comments!

  • Convert to UTF8: if source.conform.encoding is set, use iconv to convert source file to a new file with UTF8 encoding.
  • Convert to CSV: turn all types of sources in to a CSV file (see below on convert.js)
  • Merge columns if source.conform.merge is set.
  • Advanced merge columns if source.conform.advanced_merge is set.
  • Split address if source.conform.split is set.
  • Drop columns: prepare a new CSV file with just the core LON,LAT,NUMBER,STREET fields picked out of the processed source CSV.
  • Reproject to EPSG:4326. Only for CSV and GeoJSON files, creates a VRT file pointing at the processed source CSV and uses ogr2ogr to convert it to WGS 84.
  • Expand abbreviations: Fix Capitalization & drop null rows. This code is a bit woolly; it has a comment “I haven’t touched it because it’s magic” and there are no tests.

convert.js has five separate functions for converting different source types to a CSV file in the source schema.

  • shp2csv(): uses OGR2OGR to convert a shapefile to a CSV file. Also reprojects to EPSG:4326. Quite simple code.
  • polyshp2csv(): very similar to shp2csv(), but handles polygons.
  • json2csv(): uses geojson-stream to convert a GeoJSON file to a CSV file. Figure out headers from the first object’s properties. Converts polygons to points with a very simple average.
  • csv(): uses Node CSV modules to read the source CSV file and transform it into a cleaner CSV for further processing. Implements source.conform.headers and source.conform.skiplines.
  • xml(): uses ogr2ogr to convert an XML input to CSV, with reprojection. Very simple code, may not be used yet?
  • there’s code for computing the center of a polygon that’s duplicated in polyshp2csv() and json2csv().

openaddresses-conform has a small test suite. I believe it works on full source files, it’s more like functional tests than unit tests, running big chunks like conform or download and verifying the output is reasonable.

Existing Python port

Machine has its own Python code for doing the equivalent of downloadCache() and updateCache(). It’s quite different from the Node code strategy and is extra complicated because of the way Machine was a wrapper for invoking the Node code.

Very little of the extract and transform logic of conformCache() has been ported to Python but @iandees did some back in November. That code lives mostly in conform.py:ConvertToCsvTask. It works differently from the Node code. It basically takes whatever input file has been downloaded and uses Python OGR bindings to convert it to a CSV file in the schema of the source, plus an extra computed centroid. There’s no code yet to extract attributes or merge columns or anything. It’s streaming code, never loads the whole thing in to RAM.

I’m considering this choice to lean so heavily on OGR to process source files, it’s different from how the Node code is designed. I asked Ian and he said at the time all sources could be processed with ogr2ogr, so no need to write extra code for source CSV parsing, etc.

  • Check the type is .shp, .json, .csv, or .kml
  • Open source with OGR and figure out what field names are in it.
  • Set up OGR to transform the source SRS to EPSG:4326
  • Create a CSV file using csv.DictWriter with headers from the field name.
  • Iterate over features in the open OGR
  • For each feature, write a row to a CSV file with columns set to all fields from the feature. Also compute a centroid column.

I’ve never used the Python OGR bindings before. It’s pretty un-Pythonic and now I understand why Fiona exists. This list of Python Gotchas in GDAL will be a useful reference going forward. Apparently all the calls to Destroy() are unnecessary, but you do need to take care to manually dereference data sources.

Code in The OpenAddress Machine

I’m trying to help with the OpenAddress project, particularly Mike Migurski’s “machine” code for running a full analysis of the data. Particularly particularly the ditch-node branch. Managed to get the tests running after some version hassle.

Now I’m taking inventory of what all code is in the repo to understand where to work. These notes are probably only useful right about now (December 2014) and only for the ditch-node branch.

openaddr/*.py

This is the big thing, about 1700 lines of Python code. The architecture is a bit confusing. I don’t really understand how it’s managing threads / processes for parallelism. Also the actual ETL code is a bit convolved with the download and cache code, including S3.

  • __init.py__: grab bag of top level stuff. Key methods:
    • cache() and conform() are wrappers around Python code to download and process data from sources. This code wraps Python modules and uses multiprocessing.Process to run them as separate jobs. (see also jobs.py) The comments say these are Node wrappers, but they no longer are in this branch.
    • excerpt() pulls bits of data out of source files for user presentation. Contains some logic for parsing CSV, Shapefiles, etc to get a few rows out of them. See also sample.py. Excerpt does not use Process.
  • cache.py: Download from HTTP, FTP, and ESRI sources. I believe this code entirely writes to local disk and does not use S3. The ESRI code has logic about doing database-like queries on URLs and rewriting the ESRI proprietary JSON to GeoJSON
  • conform.py: python code to translate source data to the OpenAddress CSV output schema. Uses the OGR Python bindings, etc. I believe this is not complete.
  • jobs.py: script code to run a bunch of cache jobs, conform jobs, etc as separate threads. I’m not clear how this multithreading interacts with the multiprocessing code in __init.py__
  • process.py: a main program. this invokes all the work described in jobs.py, then does some processing to extract report-like information (like the map). This is doing I/O via S3 and caches, not so much local disk.
  • render.py: Cairo and geo code to draw the map of data sources
  • run.py: a wrapper for running stuff on EC2
  • sample.py: extract some sample features from a GeoJSON file, used for excerpts?
  • summarize.py: produce a report about the job run using an HTML template.
  • template/state.html: the actual HTML file that is visible at http://data.openaddresses.io/. Or rather a Jinja2 template.
  • template/user-data.sh; not sure what this is. It seems to be a templatized “run” script that installs everything from scratch on a new machine. I imagine this is what Mike runs first on a fresh EC2 instance.
  • geodata/*: shape files. I think this is used by render.py to draw pictures of FIPS codes.

openaddr-*

Not part of the Machine repo, these are four small Node projects that contain code for managing OpenAddresses data. This is the code that’s being “ditched” in the branch, and in fact I think it’s no longer used outside the tests.

  • openaddr-source: this is the openaddresses project itself. The main thing is sources/*.json, a bunch of JSON files that describe data sources and their conforms.
  • openaddr-download: code that takes a source URL as input and downloads it. lib/connectors.js has the actual code to do FTP and HTTP requests. Also is able to get data out of ESRI services using esri-dump, another program by Ian Dees that has both Python and Node versions.
  • openaddr-cache: another downloading program, this one is focussed on caching source data in S3.
  • openaddr-conform: the big program, glues together all the other scripts into a single thing that takes a source JSON as input, emits a processed CSV as output. So it has a little download and cache logic in it as well as a bunch of ETL code for extracting data out of source files and emitting it in the simple CSV schema OpenAddresses publishes. it in turn relies on ogr2ogr and other tools for extraction.

test.py, tests/

Test suite for The Machine. All the code is currently in test.py, just 11 tests. tests/ is test data files.

chef/

Scripts to set up an Ubuntu server to run The Machine. I haven’t actually run these on my dev box, just copied out bits of it as necessary. Some of the things it does:

  • run.sh: install Ruby and chef, the invoke chef-solo
  • role-ubuntu.json: spec for The Machine. Installs Python, Node, and four openaddr-* Node modules.
  • **/default.rb: specs for each package. There aren’t many interesting bits here. Node is wired to version 0.10.33. Python installs Cairo, GDAL, and PIP. The openaddr-* modules get installed in /var/opt. Only openaddr-conform is now needed for the tests to run in ditch-node, although I’m not sure about the full machine loop.

python-pip is broken in Ubuntu 14.04

Running pip on my Ubuntu 14.04 box gives the error “ImportError: cannot import name IncompleteRead” when trying to import the requests module. Turns out this is a known bug going back to at least April. It’s subtle though; a different Ubuntu box with the same versions of python-pip and python-requests is fine. It’s apparently a bug in python-requests, see also Migurski’s workaround.

A quick workaround is to remove Ubuntu’s python-pip and install pip manually.

Data storage for Logs of Lag

My little Logs of Lag project is doing pretty well, I need to create some sort of more serious datastore for it. It’s a small service, at most 1000 logfiles uploaded a day (each about 20k per file), but over time that adds up. Right now my data store is “put a file with a random name in a directory”. And I have no database or analysis of all the files.

The high-end solution would be to start putting data files in AWS and create a local Postgres database for aggregate statistics. I know how to build this. But that adds two big moving parts, one of which I have to maintain myself. And it’s kind of overkill for the relatively small amount of traffic I have (and am likely to ever have).

So I’m thinking now just to keep storing the files themselves on the filesystem, but spread it out over a bunch of directories so I don’t have a single giant directory. The Linux kernel no longer chokes on lots of files but shell tools are still a PITA. File names are base 64 encoded things so maybe hash by the first two characters, for 4096 directories. That’ll carry me to about 16M log files (4096 files per directory), good enough. The file system only has 60M inodes available anyway. (Unfortunately - is a valid leading character in the filenames. Oops.)

I definitely want a database, I’m curious about aggregate stats. I’m thinking of keeping this all asynchronous. When a user uploads a log it doesn’t go straight to the database, just written to a file. Then a cron job picks up the files and does the postprocessing. That works fine as long as the database data still isn’t needed by the user application. It’s not right now, in fact the server isn’t needed at all, the user gets 95% of the value solely in client side javascript.

What database? I should probably bite the bullet and just use Postgres, but I hate having to manage daemons. I wonder if SQLite is sufficient? It supports concurrent read access but only one writer at a time, and the writer blocks readers “for a few milliseconds”. I think that constraint isn’t a problem for me. Right now I’m tempted to go for that, just for the fun of doing something new.

Another problem to solve is the log parsing code. Right now logs are parsed by the client browser, in Javascript, and the client sends both the raw log text file and the parsed data (as JSON) to my server. (The server is a Python CGI which just writes the files to disk.) I’d like to retain that client-only capability, but also start parsing logs on my server. I don’t really want to maintain a second parser in Python.

So maybe I write the server parser / database stuff in Node to reuse the Javascript parser. Here’s MapBox’s node-sqlite. There’s zero need for me to make these scripts asynchronous, so the Node paradigm is not a great match, but I can certainly make it work.

(Naively I’d thought Node startup times would be bad, like Java, but that’s not true. From Node v0.10 on Ubuntu: “NODE_PATH=/tmp time node -e 1” is about 27ms, compare Python 15ms. Not enough difference to matter. strace shows Node makes about 230 system calls for an empty script (it’s nondeterministic!), compare Python’s 883.

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.

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.

Python: showing time in another timezone

Python’s date and time APIs are awful. Actually they’re awful in most languages, Java’s were sure terrible. But Python is worse because it has several ways to do things and none of them are really correct. The newish datetime module is better than the old time module and its bizarre “tuple that may or may not be timezone aware” type. But even datetime is stupid about time zones, only supporting UTC or the local computer’s time. You need the add-on pytz to bring in the Olson timezone database to start doing real work, and even then it’s complex.

I have some timestamps, seconds-since-Unix-epoch, which is intrinsically UTC. Unambiguous integers. Now I want to print them in Florida’s timezone, no matter what my computer’s time zone is. Here’s one way:

florida = pytz.timezone('US/Eastern')
floridaDatetime = datetime.datetime.fromtimestamp(ts, florida)
print floridaDatetime.strftime("%b %d %H:%M")

This seems to work, but the pytz docs admonish “Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones. It is safe for timezones without daylight savings trasitions though, such as UTC” The docs recommend this instead:

florida = pytz.timezone('US/Eastern')
utcDatetime = datetime.datetime.fromtimestamp(ts, pytz.utc)
floridaDatetime = utcDatetime.astimezone(florida)
print floridaDatetime.strftime("%b %d %H:%M")

I’m not positive, but I think my simpler code actually will work as long as I don’t try to do anything fancy with floridaDatetime like arithmetic. The problem is described in detail in the pytz docs: it’s some combination of datetime being limited and that certain timestamps are ambiguous because of DST. So really pytz is encouraging us to always always always only ever do math with UTC time and defer conversion to local timezone to the last possible moment before string output. Which is imminently sensible, if frustratingly verbose.

I think the right library would be a datetime type whose internal representation is always only ever seconds-since-epoch plus desired timezone. That way all the library code can do arithmetic without worrying about DST. I wonder if any other languages do it that way. Python’s got some unfortunate legacy hanging around and I don’t think Python3k tried to fix up the mess.

GeoJSON for the steps of San Francisco

I keep playing with this dataset of all the steps of San Francisco from OpenStreetMap. I made a GeoJSON file with all the steps of San Francisco. It’s a snap to add to a Web map with Leaflet. A few thoughts:

GeoJSON is a good format for geodata when you’re working cross-language. PostGIS can emit it, Python and Javascript can easily parse it, Leaflet can easily draw it. Half the time I just get a string from PostGIS and never even parse it in Python, just pass it along.

The Python geojson library doesn’t really help very much. If you’re using geopy already to work with geodata, then maybe it’s helpful. But if you’re just building up arbitrary JSON blobs with some geodata it’s not needed.

The world could use a GeoJSON validator. Extra credit if it rendered the GeoJSON blob on a map, wouldn’t be too hard. I should set this up as a web service.

JSON float precision continues to contribute to file bloat; Python’s default 15 digits precision translates to subatomic location positioning. Fortunately in Python 2.7 it’s pretty easy to round off numbers, you just have to do it.

The GeoJSON format I settled on was a FeatureCollection. Each feature has the name, length (in metres), and OSM ID of one set of steps. Then two geometries: the centroid of the steps and the path of the steps. Example:

{   "type": "Feature",
    "properties": {
        "id": 8916413,
        "length": 146.58,
        "name": "Harry Street"
    },
    "geometry": {
        "type": "GeometryCollection",
            "geometries": [
            {   "type": "Point",
                "coordinates": [ -122.431219, 37.740099 ],
            },
            {   "type": "LineString",
                "coordinates": [
                    [ -122.430741, 37.740424 ],
                    [ -122.43075,  37.740351 ],
                    [ -122.431759, 37.739803 ]]
            }
]}}

Here’s the SQL query for all the steps I’m using. There’s more Python code than I’d like to collect all these rows and emit the GeoJSON, but I’m not pasting it all here.

select
    planet_osm_line.name,
    ST_Length(planet_osm_line.way) as meters,
    ST_AsGeoJSON(ST_Transform(ST_Centroid(planet_osm_line.way),4326), 6),
    ST_AsGeoJSON(ST_Transform(planet_osm_line.way, 4326), 6),
    planet_osm_line.osm_id
from planet_osm_line
    inner join planet_osm_polygon
    on ST_Intersects(planet_osm_line.way, planet_osm_polygon.way)
where
    planet_osm_polygon.osm_id = '-111968'
    and planet_osm_line.highway = 'steps'
order by meters desc;

Bashing Unicode in Python

My whole work environment is UTF-8. Except Python. Python’s “print” will encode in UTF-8 if its printing directly to a tty. But as soon as you pipe that tty to something Python reverts to ASCII. And it’s a real PITA to overcome that.

Here’s one ugly kludge to make Python always treat stdout as UTF-8. It causes problems with some tools, but is sufficient for hacking around:

import sys, codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)

Python script to find Amazon store MP3 files

I’m working on rationalizing my MP3 collection.  Here’s a Python script to print out the names of all songs that seem to have been bought from Amazon MP3. It uses the presence of “Amazon” in the ID3v2 comment tag. It’s not entirely reliable; songs I bought in 2007, 2008 are missing that tag.

#!/usr/bin/python

"""Print out names of MP3 files that are from Amazon.
Works by looking for the Amazon ID3v2 comment tag with a song ID.
This method is not complete: some early Amazon sales don't have this."""

import sys, os
from mutagen.id3 import ID3

def isAmazon(fn):
  "Return the Amazon comment if it's an Amazon MP3, else None"
  id3=ID3(fn)
  for c in id3.getall('COMM'):
    if "Amazon" in str(c):
      return str(c)
  return None

for dirpath, dirnames, files in os.walk('.'):
  for name in files:
    if name.endswith(".mp3"):
      fn = os.path.join(dirpath, name)
      try:
        if isAmazon(fn):
          print fn
      except:
        pass # ignore errors

sys.exit(0)

Sublime Text 2 and Python

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

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

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

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

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

Things that look promising that I haven’t tried:

Python linters

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

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

Notes on getting TileStache renders working on MacOS

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

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

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

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

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

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

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

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

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

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

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

Serving mbtiles tiles for slippy maps

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

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

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

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.

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.

Django 1.2 and GeoDjango on Windows

I’ve been trying to develop code on my Windows box. It’s the machine I sit in front of, it’s fast, and I like WingIDE. I have a Linux box for “real work”, but think there’s some discipline in moving back and forth between the two systems.

For GeoDjango hacking I decided to run the PostGIS database on my Linux box and the Django webapp on my Windows box. I’d hoped this would avoid having to install a bunch of funky binaries on Windows. No such luck. The GeoDjango docs are a bit out of date and the official GeoDjango Windows installer binary is for an old version.  Here’s what I’ve learned doing it myself.

The first step is getting regular Django working. Here’s what I did:

  • Installed PostGIS + dependencies on Debian (testing) via
    aptitude install postgresql-8.4-postgis
  • Installed stock Python2.5 on Windows from Python.org
  • Installed Django 1.2 on Windows. I forget how I did this, I think using easy_install, which in turn requires installation as well. It wasn’t hard, just followed the tutorial. Django 1.2 includes GeoDjango Python libraries.
  • Installed psychopg2, the database driver, on Windows. There’s binaries at http://stickpeople.com/projects/python/win-psycopg/

GeoDjango is harder. It relies on a lot of C libraries, some of which don’t support Windows well. The main hurdle is a working GEOS DLL. The GEOS page itself doesn’t have binaries. I found binaries from three places: OSGeo4W,  the GeoDjango Windows Installer, and PostGIS. Here’s a quickie test program I wrote to try them out:

geosPath = r'.\libgeos_c-1.dll'

from django.conf import settings
settings.configure(GEOS_LIBRARY_PATH=geosPath)
from django.contrib.gis.geos import tests
tests.run()

Unfortunately, both the OSGeo4W and GeoDjango versions of the DLL don’t pass the tests. Version skew? Bug? The underlying error seems to be in memory management, something like

ERROR: test02_wktwriter (django.contrib.gis.geos.tests.test_io.GEOSIOTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "c:\Python25\lib\site-packages\django\contrib\gis\geos\tests\test_io.py", line 30, in test02_wktwriter
    self.assertEqual(ref_wkt, wkt_w.write(ref))
  File "c:\Python25\Lib\site-packages\django\contrib\gis\geos\prototypes\io.py", line 147, in write
    return wkt_writer_write(self.ptr, geom.ptr)
  File "c:\Python25\Lib\site-packages\django\contrib\gis\geos\prototypes\threadsafe.py", line 55, in __call__
    return self.cfunc(*args)
  File "c:\Python25\Lib\site-packages\django\contrib\gis\geos\prototypes\errcheck.py", line 87, in check_string
    free(result)
WindowsError: exception: access violation reading 0x02F12494

The library that did work for me was the version that came with PostGIS. I didn’t even install PostGIS, just grabbed the DLLs out of their zipfile. Unfortunately GEOS is spread into two files: libgeos_c-1.dll and libgeos-3-2-2.dll. The latter needs to be in a directory where Windows can find it as a normal DLL, I put it in the working directory of my own code.

GEOS was enough for me to get the tests working and my simple GeoDjango program working correctly. There’s more work to be done: I believe you want both GDAL and PROJ.4 available to GeoDjango on the Windows side. Or does PostGIS do the work on the database server? I haven’t tested that yet.

In addition to basic GeoDjango on Windows setup, here’s notes specific to my code:

  • Followed instructions on getting WingIDE to work with Django
  • Sweated a lot over environment considerations, specifically Python path. I hate setting up new development environments, and Django with its mix of servers and applications and developer code and third party libraries is complicated.
  • I’m trying to run a script directly, not via manage.py. To make that work you need to set the DJANGO_SETTINGS_MODULE system environment variable to point to the Python path of your settings.py
  • settings.py needs to specify a special database engine:
    ‘ENGINE’: ‘django.contrib.gis.db.backends.postgis’

There’s some more useful notes about Windows and GeoDjango in this blog post by Reinout van Rees.

Quick and dirty referer tracking

About once a month someone links to my blog and I get all excited to see how many clicks they drove. Despite 10+ years of Javascript tracking systems like Google Analytics, I still don’t have a proper tool to just quickly show me “what’s driving traffic today?”. I usually cobble together some hideous thing that starts awk { print $7, $11 } | grep -v ... and then get annoyed. So today I wrote a proper Python script:

#!/usr/bin/python

import itertools, re

skipRE = re.compile(r'(js|png|gif|jpg|css|rss091|atom|ico)$')
def skip(url, referer):
    return skipRE.search(url) is not None or \
        referer == '-' or \
        referer.startswith('http://www.somebits.com')

for l in itertools.chain(file("/var/log/apache2/access.log.1"), file("/var/log/apache2/access.log")):
    d = l.split()
    url = d[6]
    referer = d[10].strip('"')
    if not skip(url, referer):
        print url, referer

The output is then piped through a Python script I wrote years ago which counts up the most common lines.

One remaining mystery; the large majority of my pageviews have a referer of -, or empty. I know folks aren’t pasting URLs in by hand, where does this come from? Do redirectors somehow clear Referer?