Some Bits: Nelson's log

29 posts about openaddresses

OpenAddresses / population

Justin Meyers did an awesome treatment of OpenAddresses data. He put all the points in QGIS, then binned them by county, then put the shapefile in a repo. Nice! I wanted to see what the data looked like normalized by population, so I did two treatments. One is kinda sorta logarithmic, the other is a simple linear scale capped at 2 addresses / person.

Logarithmicish

output.png

Linear, capped at 2

linear.png

I’m not quite sure what this visualization really shows. I was hoping it’d be a proxy for data coverage; like naively I expected there’d be one address per person, more or less. But that’s clearly not what I’m seeing here. The Montana outlier is particularly baffling, there’s 10 addresses / person in many counties.

 

How many addresses are there in the world?

A question inspired by my work on OpenAddresses.. How many addresses are there in the world? By “address” I mean something that should be geocodable to a specific lat/lon, like 1600 Pennsylvania Ave NW, Washington, DC 20500. Normal people might define an address as something you can get mail delivered to, or tell a taxicab.

One address per two people. That’s the estimate Tom Lee came up with by comparing sizes of OpenAddress data we have to population. It’s not a bad estimate!

The confounding factor is that “address” is a somewhat first world concept, I imagine there’s fewer unambiguous addresses in rural / third world places. There’s a lot of the world where naming locations is much more loosely defined, “go to Tegaljaya village, go towards the mountain from the crossroads, turn left at the big banyan tree, and then five houses down”. OTOH I think every country in the world has mail delivery, which means there is some sort of system for finding people. Should do more research.

Installing openaddress-machine on a new EC2 system using Chef

No need to install stuff manually; Mike already wrapped up scripts to set up an EC2 system with Chef for us. Here’s how to use it on a brand new EC2 micro server

sudo bash
apt-get update
apt-get upgrade
apt-get install git
git clone https://github.com/openaddresses/machine.git
cd machine/chef
./run.sh

Done! The shell command openaddr-process-one now works and does stuff.

In brief, this:

  1. installs Chef and Ruby via apt
  2. runs a Python setup recipe. That installs a few Ubuntu Python packages with apt (including GDAL and Cairo), then does a “pip install” in the OpenAddress machine directory. This tells pip to install a bunch of other Python stuff we use.
  3. runs a recipe for OpenAddresses. This uses git to put the source JSON data files in /var/opt.

Update

But really, that’s so manual. If you just pip install openaddr-machine it makes a /usr/local/bin/openaddr-ec2-run script that will do the work for you. That in turn invokes a run.py script which you run on your local machine. It, among other things, runs a templated shell script to set up an EC2 instance and run the job on it.

The shell script that is run on EC2 is pretty basic. It:

  1. Updates apt (but does not upgrade)
  2. Installs git and apache2
  3. clones the openaddress-machine repo into /tmp/machine
  4. Runs scripts to setup swap on the machine, then invoke chef to set up the machine
  5. Runs openaddr-process to do the job
  6. Shuts the machine down.

The run.py script you use on your own machine is mostly about getting an EC2 instance.

  1. De-template the shell script and put it in user_data.
  2. Use boto.ec2 to bid on a spot instance
  3. Wait for up to 12 hours until we get our instance

The details of how the EC2 instance is bid for, created, and waited on are a bit funky but seem well contained.

Installing openaddresses-machine on a new EC2 instance

Just documenting some work I done. The pattern here follows my notes on making openaddresses work in virtualenv, although I didn’t use venv here. This is really how to get the minimal stuff installed on a new Ubuntu box to run our code. Just a bunch of shell commands.

Set up an Ubuntu 14.04 AMI. The smallest one will run it OK

Do the following as root:

# update  ubuntu
apt-get update
apt-get upgrade

# install pip
cd /tmp
wget https://bootstrap.pypa.io/get-pip.py
python get-pip.py

# install gcc and python dev
apt-get install gcc g++ python-dev

# install openaddresses
pip install Openaddresses-Machine

# install Cairo
apt-get install libffi-dev libcairo2
pip install cairocffi

# install GDAL
apt-add-repository ppa:ubuntugis/ubuntugis-unstable
apt-get update
apt-get install python-gdal libgdal-dev
pip install GDAL

I haven’t run these commands a second time yet, but it should be close. The last line for “pip install GDAL” is probably not necessary, and it’d probably be better to install Openaddresses-Machine last although it may not matter.

Next step: automate this with Chef Solo.

After that: set up Honcho and a Procfile to run my queue service worker.

OpenAddress machine continuous queue

Migurski and I have been working up a new architecture for OpenAddresses, specifically the python code that runs source jobs. Currently everything runs as a big batch job every two days. The primary goal is to get a system that can run a new submitted source instantly, ideally with useful feedback to the submitter.

Mike’s insight was to build a system a little like Travis; something that looks at GitHub commits with a hook, runs a new job every time something is committed, and posts back info via the GitHub status API. GitHub is nice because it provides a file store and change tracking. Ultimately we don’t want to require a GitHub login to submit sources, and we probably want a custom UI, but that can come later.

Here’s the components we’re talking about building:

  1. A GitHub webhook that submits info to our new job server when stuff is checked in.
  2. A new job server that accepts HTTP posts of GitHub events. Mike’s got one working in Flask running on Heroku.
  3. A job queue. New jobs get enqueued by the new job server, then some worker daemon process checks for jobs to run and executes them. Can be a very simple queue, but needs to support job priorities (interactive vs. batch). Right now I’m thinking of writing my own using Postgres running in Amazon RDS, but there’s got to be something I can just use that’s not super overkill. (Update: pq looks good.)
  4. Workers to run jobs. Something to look for new jobs and execute them. Current thought is a persistent Unix server running on EC2. Installs openaddr and its dependencies via pip, then runs jobs via openaddr-process-one, then posts results back to the job queue result queue.
  5. Job completion notifications back to GitHub using the GitHub status API. Mike has been tinkering with code to do this already.
  6. A batch-mode refresher. Something to run sources periodically even if no one’s edited the source specification in awhile. Mostly to catch new data on the remote server.

Here’s some open things to design.

  1. Job status reporting with humane UI. Currently we get very little info back from when a job is run. A few bits of status (did it complete, how long it took), a debug log from the process, and any actual output files. We need more. In particular I think the stuff you currently learn from the debug log needs to be expanded to useful user-level event data. Ie, events like “source JSON parsed”, “source data downloaded”, etc.
  2. UI for creating source specification JSON files. Imagining some guided wizard like UI using Javascript and forms. There’s already a pretty good one on the live site, just needs some expansion. Also ultimately we shouldn’t require a GitHub login.
  3. Security. A bit nervous running completely unreviewed source specs from anonymous people. Isolating the worker in a throwaway machine might help. Or doing some sanitization on inputs.
  4. Statistics reporting. I have a dashboard that works OK for the existing nightly batch mode, but we’ll want something different for this continuous mode thing.

See also OpenAddresses Mark 3, a proposal I sketched in January. What we’re doing here is similar but without the component of breaking any individual source run up into separate tasks.

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.

Address schema

Some stuff of possible interest to OpenAddresses. The US government’s Federal Geographic Data Committee standardized street address schema. The docs are 140 pages of text describing an XML schema, which sure seems wordy, but then it’s also very precise. They even put the XML schema online, here’s a text rendering.

It’s super wordy and contains a lot of detail, but at the core is a schema we could repurpose that says things like “a street address consists of a number, a prefix, a street name, ...”

There’s a good summary of the schema on page 3 of the executive summary. Here’s the meat of it:

Screen Shot 2015-04-09 at 10.57.41 AM

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?

Some OpenAddresses machine stats

I’ve collected the state.txt files written by OpenAddress machine and stuffed them in a database for ad hoc reporting. Here’s some queries and results

Slowest processing

select source, max(address_count), round(avg(process_time)) as time
from stats where address_count > 0
group by source order by time desc limit 10;

source                          max(addres  time
------------------------------  ----------  ----------
nl.json                         14846597    8769.0
au-victoria.json                3426983     8438.0
es-25830.json                   8778892     6450.0
us-va.json                      3504160     4377.0
dk.json                         3450853     4220.0
pl-mazowieckie.json             995946      4108.0
us-ny.json                      4229542     4047.0
pl-lodzkie.json                 685093      3575.0
pl-slaskie.json                 575596      3331.0
pl-malopolski.json              670892      3216.0

Slowest cache

source                          max(addres  time
------------------------------  ----------  ----------
us-ny.json                      4229542     5808.0
za-nl-ethekwini.json            478939      3617.0
us-va-city_of_chesapeake.json   99197       3457.0
us-ca-marin_county.json         104067      3034.0
us-mi-ottawa.json               109202      2232.0
us-fl-lee.json                  548264      1999.0
us-ne-lancaster.json            97859       1995.0
us-ia-linn.json                 95928       1519.0
dk.json                         3450853     1348.0
us-az-mesa.json                 331816      890.0

Summary of runs

For each run, print out how many sources we tried, how many cached, how many sampled, and how many processed. The counting here is a bit bogus but I think close.

select ts, count(distinct(source)), count(distinct(cache_url)), count(distinct(sample_url)), count(distinct(processed_url))
from stats group by ts;
ts               addresses        source  caches  sample  proces
---------------  ---------------  ------  ------  ------  ------
1420182459                        737     689     557     490
1420528178                        738     691     559     490
1420787323                        740     692     560     495
1421133148                        789     717     558     521
1421392045                        790     718     559     523
1421737732                        790     719     557     521
1421996867                        790     719     558     522
1422342479                        790     718     560     524
1422601615                        790     652     582     503
1422645440                        790     655     585     511
1422748762                        790     650     580     504
1422773454                        790     647     577     506
1422860989                        790     653     582     508
1423034051                        790     658     588     509
1423206384                        790     658     587     508
1423465798                        790     660     588     510
1423638409                        790     659     588     508
1423811369                        790     661     590     508
1424070358                        790     657     586     509
1424243321                        790     645     566     499
1424416039                        790     650     534     469
1424675318        88031206        790     648     563     496
1424849197       111999281        794     658     570     505
1425022188       105056481        794     653     570     508
1425280104       109864743        794     651     567     507
1425453036       111734276        786     655     573     520
1425625770       116323932        786     656     571     519
1425881358       113713353        786     644     563     528
1426054556       117771563        788     666     586     534
1426228915       117335107        788     666     584     538
1427090950       113916633        788     665     581     527

Time to complete successful runs

 select ts, round(avg(cache_time)) as cache, round(avg(process_time)) as process 
 from stats where length(processed_url) > 1 
 group by ts order by ts;
ts               cache            proces
---------------  ---------------  ------
1420182459       63.0             154.0
1420528178       50.0             147.0
1420787323       46.0             166.0
1421133148       43.0             159.0
1421392045       43.0             160.0
1421737732       43.0             163.0
1421996867       45.0             167.0
1422342479       46.0             164.0
1422601615       48.0             228.0
1422645440       56.0             314.0
1422748762       47.0             300.0
1422773454       50.0             289.0
1422860989       61.0             296.0
1423034051       66.0             263.0
1423206384       44.0             260.0
1423465798       51.0             294.0
1423638409       51.0             270.0
1423811369       50.0             260.0
1424070358       55.0             277.0
1424243321       60.0             265.0
1424416039       57.0             298.0
1424675318       51.0             265.0
1424849197       62.0             323.0
1425022188       53.0             284.0
1425280104       59.0             312.0
1425453036       55.0             325.0
1425625770       79.0             367.0
1425881358       77.0             315.0
1426054556       84.0             335.0
1426228915       76.0             361.0
1427090950       71.0             272.0

Most improved

A count of which sources have the most variance in how many address lines we got out. kinda bogus, but fun.

select source, max(address_count)-min(address_count) as diff, min(address_count) as minc, max(address_count) as maxc
from stats where address_count > 0 
group by source order by diff desc limit 15;

source                          diff        minc        maxc
------------------------------  ----------  ----------  ----------
us-mn-dakota.json               138301      27218       165519
us-pa-allegheny.json            53399       474492      527891
us-ne-lancaster.json            44996       52863       97859
us-va-salem.json                9992        614         10606
dk.json                         5258        3445595     3450853
be-flanders.json                2809        3365557     3368366
us-nc-mecklenburg.json          2117        499524      501641
us-co-larimer.json              1118        169500      170618
ca-on-hamilton.json             1112        243554      244666
us-va-james_city.json           1071        33383       34454
us-tx-austin.json               837         374854      375691
us-or-portland.json             786         415220      416006
us-nc-buncombe.json             784         147492      148276
us-nc-union.json                720         81241       81961
us-oh-williams.json             603         18496       19099

Census of US county parcel records

Fairview Industries has a great map of which US counties publish GIS parcel data. Mike got the shapefile for the database. I went ahead and extracted just the URLs and county names to a convenient CSV file.

The file lists a total of 3214 counties. 2022 have ViewURLs defined and 590 have DownURLs defined.

Here’s my extractor code.

#!/usr/bin/env python3

import fiona, sys, csv

out = csv.writer(open('extracted.csv', 'w', encoding='utf-8'))

out.writerow(('FIPS', 'State', 'County', 'ViewURL', 'DownURL'))

count = 0
gisInvLks = 0
viewUrls = 0
downUrls = 0
with fiona.drivers():
    with fiona.open('counties.shp') as counties:
        for county in counties:
            props = county['properties']
            # Fix mojibake; Fiona read these strings as ISO-Latin-1 but they are actually UTF-8
            cntyNm = props['CntyNm'].encode('latin_1')
            cntyString = cntyNm.decode('utf-8')
            out.writerow((props['StCntyFIPS'], props['StNm'], cntyString, props['ViewURL'], props['DownURL']))
            count += 1
            if props['ViewURL']:
                viewUrls += 1
            if props['DownURL']:
                downUrls += 1

sys.stderr.write('%d rows\n%d ViewURLs\n%d DownURLs\n' % (count, viewUrls, downUrls))

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 > /dev/null' % fn)

def catDevNull():
    os.system('cat %s > /dev/null' % fn)

def wc():
    os.system('wc -l %s > /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):
    "Run a function, return time to execute it."
    # 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.

Compare two OpenAddress runs

I’m re-running OpenAddress many times trying to be sure the output stays roughly consistent. It’s never the same twice; servers are unreliable and the data is changing. Also some code changes make small cosmetic differences like rounding error.

What works best for me is comparing the line counts in the output files:

wc -l out/*/out.csv > wc.txt

diff  --suppress-common-lines -y oa-full-790/wc.txt oa-new-esri/wc.txt

This only highlights sources that output different number of lines; if the contents in the columns is garbled you won’t see that. But it’s a good way to get an overview of what changed between two runs.

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.)

Happy multiprocessing

I managed to get multiprocessing working for OpenAddress job processing. Looks like it’s working pretty well. We use multiprocessing.Pool to manage worker processes, then set up a SIGALRM to abort jobs that run too long. (Using a nifty decorator to add the timeout). I also added a SIGUSR1 handler in the master job process that lets us abort the run. At least once I’ve had the pool fail where there was work being done but none of the worker processes was trying to do it.

Here’s a happy screenshot of htop showing a run going. Note the nifty custom process names courtesy of setproctitle.

Screen Shot 2015-01-18 at 3.30.17 PM

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')

Second full OpenAddress run

After the first run against 600+ sources we patched up a bunch of bugs, improved the running infrastructure. Then I ran another set last yesterday, amended a little bit today to re-run jp-* and kr-* after one more bug fix. I wasn’t quite as careful in measuring everything, but here’s some notes on output.

  • 579 input sources: 484 out.csv files, 483 sample.json files
    84% success rate; compare 66% from previous run.
  • 102M output rows.
    Compare 80M from previous run, 100M from Node
  • Roughly 3.5 hours running time, maybe less.
    3 threads stalled on bad servers so it’s not a good measure.

Throwing out the 3 stalled runs, the average source took 137s to execute. Standard deviation of 585s, so it’s a very broad distribution. That first run averaged 104s (SD 265). But a lot more of those runs failed in 1 second!

I’m curious if the new ESRI code is faster or slower than the old code. It’s definitely better in that it works with many more sources. Don’t really have data for it. The ESRI time is probably dominated by slow servers anyway.

Here’s the slowest non-ESRI sources. Given that these times include download times from some slow servers I’m pretty OK with them.

dk            CSV   2000s     3.4M rows
au-victoria   SHP   1620s     3.4M rows
es-25830      CSV   1173s     8.8M rows
nl            CSV   1156     14.8M rows

95 sources failed to produce an out.csv. Of those, 7 did succeed last time we ran, a potential regression. Here’s the cause of each failure:

  • us-il-tazewell: ESRI source, JSON parsing error after many calls
  • us-tx-colleyville us-tx-dallas us-tx-hurst: ESRI sources, found no records
  • us-nc: missing “file” attribute for multiple shapefiles
  • us-dc: bad download
  • us-ca-san_diego: bad zip download

And finally here’s the list of all 95 sources that didn’t produce an out.csv. I should go through and hand-classify the failures again, but I bet most of 88 of them are for the same reason as last time.

au-queensland
be-flanders
ca-ab-calgary
ca-ab-strathcona-county
ca-bc-kelowna
ca-bc-langley
ca-bc-nanaimo
ca-bc-okanagan_similkameen
ca-bc-surrey
ca-bc-west_kelowna
ca-ns-halifax
ca-on-niagra
ca-sk-regina
us-al-shelby
us-ar
us-ca-san_diego
us-co-sanmiguel
us-ct-avon
us-dc
us-fl-alachua
us-fl-collier
us-ga-glynn
us-ia-linn
us-ia-polk
us-id-canyon
us-il-tazewell
us-in-hamilton
us-in-madison
us-in-st_joseph
us-la-st_james
us-ma
us-mi-muskegon
us-mn-dakota
us-mn-metrogis
us-mn-polk
us-mn-pope
us-mn-yellow_medicine
us-mo-barry
us-mo-st_louis_county
us-ms-madison
us-nc
us-nc-1
us-nc-10
us-nc-2
us-nc-3
us-nc-4
us-nc-5
us-nc-6
us-nc-7
us-nc-8
us-nc-9
us-nc-charlotte
us-nc-columbus
us-nc-davie
us-nc-wake_county
us-ne-omaha
us-nm-san_juan
us-nv-henderson
us-nv-lander
us-nv-nye
us-nv-washoe_county
us-oh-clinton
us-oh-hamilton
us-pa-beaver
us-ri
us-tn-memphis
us-tx-colleyville
us-tx-dallas
us-tx-denton
us-tx-el_paso
us-tx-hurst
us-tx-keller
us-tx-north_richland_hills
us-tx-round_rock
us-va-alexandria
us-va-augusta
us-va-city_of_falls_church
us-va-city_of_petersburg
us-va-richmond_city
us-va-roanoke
us-va-stafford
us-wa-san_juan
us-wa-snohmish
us-wi-adams
us-wi-calumet
us-wi-crawford
us-wi-dodge
us-wi-jefferson
us-wi-juneau
us-wi-lincoln
us-wi-oneida
us-wi-richland
us-wi-sauk
us-wi-superior
us-wy-laramie

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.

OpenAddress run: time to process

Here’s how long it took to process each source. No idea how much of this time was network, how much processing, etc. Painful irony that many of the slowest ones were the ones that didn’t work. There’s no job-level timeout.

2162.325   us-tx-dallas
1970.223   us-al-huntsville
1843.934   us-nc-alexander
1826.809   au-victoria
1639.524   us-tx-houston
1511.907   us-ca-san_bernardino_county
1423.542   es-25830
1385.237   pl-dolnoslaskie
1255.783   nl
1238.894   us-mn-anoka
1115.263   us-va-fairfax
1100.821   be-flanders
1087.482   pl-lubelskie
932.043   pl-slaskie
852.481   pl-podlaskie
817.774   pl-pomorskie
803.326   pl-malopolski
789.957   pl-mazowieckie
781.457   pl-lubuskie
779.531   pl-kujawsko-pomorskie
779.183   us-wa-seattle
772.016   pl-swietokrzyskie
768.572   us-wa-king
766.155   pl-podkarpackie
736.996   us-tx-denton
726.582   pl-lodzkie
712.528   us-ne-omaha
681.070   us-pa-philadelphia
680.825   us-ms-hinds
639.296   pl-opolskie
611.966   us-va
608.180   us-ca-los_angeles_county
592.763   us-nc-3
591.630   pl-wielkopolskie
581.695   us-co-jefferson
576.934   pl-zachodniopomorskie
559.960   us-fl-bay
557.759   us-oh-hamilton
554.983   us-ca-solano_county
521.117   us-fl-pinellas
520.235   us-oh-franklin
496.750   us-fl-manatee
491.657   pl-warminsko-mazurskie
427.657   ca-on-welland
415.115   us-fl-palm_beach_county
394.993   us-ca-san_diego
378.344   us-or-portland_metro
356.776   us-nc-mecklenburg
356.656   us-nc-5
340.884   es-25829
340.322   us-tn-rutherford
319.549   us-mt
310.424   ca-nb
293.255   us-va-loudoun
284.713   us-fl-charlotte
284.701   us-nm-san_juan
280.506   us-ms-madison
279.436   us-nc-7
273.664   ar-ba-buenos_aires
260.210   us-fl-clay
259.266   us-ut
252.911   es-25831
252.718   no
250.454   us-nc-10
243.587   us-in-hamilton
239.786   ca-on-toronto
236.674   us-va-city_of_chesapeake
233.260   us-id-canyon
227.365   us-nm-alburquerque
226.377   us-oh-cuyahoga
224.207   us-vt
221.414   us-nc-9
213.543   us-ca-san_mateo_county
210.970   us-ca-kern
210.303   us-fl-miami
207.909   us-fl-hillsborough
197.618   us-mn-dakota
197.151   us-fl-brevard
190.312   us-me
189.663   us-il-tazewell
179.207   us-tx-el_paso
179.126   us-pa-allegheny
175.989   us-nc-6
166.787   us-nc-4
165.742   us-co-larimer
155.927   us-ca-santa_clara_county
155.580   us-ga-muscogee
155.365   us-fl-sarasota
152.921   jp-aichi
152.023   us-nc-burke
150.282   us-ca-sacramento_county
142.847   us-dc
138.299   us-nc-1
136.860   us-oh-stark
136.565   us-ca-el_dorado_county
130.320   us-ga-chatham
125.109   us-tx-north_richland_hills
123.697   us-oh-lucas
122.766   us-ca-marin_county
119.822   us-va-stafford
119.769   us-oh-butler
118.186   us-wi-kenosha
110.447   us-ca-orange
110.149   jp-hyogo
103.195   us-nc-cary
102.859   us-tx-austin
99.213   us-ca-santa_barbara_county
98.967   us-il-vermilion
98.502   us-mt-flathead
96.210   us-ms-copiah
95.000   us-nc-iredell
94.719   us-co-arvada
92.375   us-nc-2
91.884   us-fl-volusia
88.892   us-ca-contra_costa_county
88.881   us-co-denver
87.736   us-mo-st_louis
86.178   us-tx-waco
84.266   es-32628
81.907   us-tx-colleyville
80.419   us-oh-greene
78.767   us-oh-delaware
78.532   us-ca-palo_alto
77.562   us-ca-fresno
77.328   jp-nagano
76.621   us-oh-lake
76.158   jp-shizuoka
75.286   us-nc-orange
73.651   us-nc-avery
72.853   us-mt-gallatin
72.545   us-nc-montgomery
72.190   au-tasmania
69.991   us-or-portland
69.405   us-tn-franklin
69.186   be-wa-brussels-nl
68.425   jp-kanagawa
67.906   us-nc-8
65.562   ca-bc-vancouver
65.465   us-il-macoupin
65.074   us-ca-ventura_county
63.371   jp-fukuoka
62.161   ca-bc-kamloops
61.934   us-tx-hurst
60.508   us-wa-city_of_spokane
60.384   us-tx-keller
60.120   us-oh-clark
57.881   us-mt-yellowstone
57.463   us-oh-mahoning
57.326   us-nc-cabarrus
56.569   is
55.605   us-il-jackson
55.457   jp-osaka
55.022   jp-gifu
54.289   us-oh-columbiana
52.161   us-mo-greene
51.536   us-va-arlington
51.290   us-mn-roseau
51.153   us-co-westminster
50.761   jp-tokyo
50.466   us-oh-jefferson
49.832   us-oh-ashtabula
48.766   us-mt-cascade
48.682   ca-on-hamilton
46.963   us-fl-citrus
46.023   jp-ishikawa
46.003   us-oh-trumbull
45.902   us-ca-bakersfield
45.794   us-co-arapahoe
45.746   us-nd-cass
45.516   us-wa-skagit
44.664   us-id-post_falls
44.443   us-oh-richland
44.222   jp-nara
44.064   us-oh-wood
42.650   us-nc-buncombe
42.276   us-co-mesa
42.112   us-nc-alleghany
41.743   jp-mie
41.643   us-fl-lake
41.412   jp-niigata
41.096   us-tx-williamson
40.901   ca-qc-gatineau
40.548   us-va-james_city
40.118   us-tn-jefferson
39.818   us-mn-wadena
39.400   us-va-louisa
39.240   us-oh-tuscarawas
39.075   us-wy-carbon
38.982   us-mt-missoula
38.972   us-md-carroll
38.865   au-queensland
38.796   us-ca-carson
38.714   jp-hokkaido
38.390   us-oh-licking
37.633   jp-kyoto
37.205   us-oh-portage
37.197   be-wa-brussels-fr
37.180   jp-kagoshima
37.177   us-oh-allen
37.004   us-oh-muskingum
36.500   us-il-menard
36.194   us-il-morgan
36.190   us-ak-anchorage
36.092   us-wy-albany
35.545   us-md-howard
35.249   us-ga-gordon
35.069   us-oh-wayne
34.263   us-ca-san_luis_obispo_county
34.092   us-mn-aitkin
34.065   us-nc-moore
34.036   us-wi-green
33.545   jp-kagawa
33.531   jp-okayama
33.191   jp-miyagi
33.138   us-mn-clay
33.088   us-oh-knox
33.008   jp-ehime
32.773   jp-yamanashi
32.620   jp-toyama
32.552   jp-hiroshima
32.001   jp-kumamoto
31.514   us-va-amherst
30.983   us-oh-seneca
30.331   us-nc-alamance
30.328   jp-shiga
30.269   us-oh-madison
30.212   us-wi-trempealeau
29.878   us-mt-lake
29.704   us-wi-calumet
29.582   us-oh-miami
29.470   us-mt-ravalli
29.048   us-ca-placer_county
28.687   ca-on-windsor
28.651   us-oh-hancock
27.639   ca-on-kitchener
27.455   us-oh-sandusky
27.420   jp-miyazaki
26.766   us-oh-lawrence
26.677   us-oh-fairfield
26.407   us-mt-lake_county
26.376   us-mt-madison
25.683   us-oh-huron
25.242   us-oh-erie
24.702   us-il-jersey
24.532   us-oh-guernsey
24.509   ca-bc-north_cowichan
24.407   jp-yamaguchi
24.311   us-nc-lincoln
24.006   jp-aomori
23.981   us-il-mcdonough
23.644   us-il-clark
23.476   us-il-putnam
23.437   jp-nagasaki
22.700   us-oh-ashland
22.108   us-il-schuyler
22.053   us-mt-lincoln
21.906   us-ca-napa
21.409   us-ca-santa_cruz_county
21.344   jp-wakayama
21.323   us-oh-williams
21.184   us-va-nelson
21.170   us-oh-shelby
21.101   us-oh-darke
21.098   us-ca-butte_county
21.091   us-co-fort_collins
20.880   jp-okinawa
20.805   jp-oita
20.732   ca-on-waterloo
20.546   us-oh-ross
20.122   us-oh-athens
20.068   us-wa-chelan
19.955   us-mn-becker
19.913   us-oh-putnam
19.363   us-ky-lexington-fayette
19.221   us-nc-haywood
19.079   jp-shimane
18.733   us-nc-chatham
18.615   us-oh-fulton
18.565   us-md-st_marys
18.356   us-il-massac
18.256   us-mt-silverbow
17.888   us-wy-laramie
17.864   us-oh-ottawa
17.811   us-mn-mille_lacs
17.628   us-oh-gallia
17.486   us-oh-crawford
17.345   us-nc-granville
17.086   us-oh-washington
16.881   us-oh-defiance
16.858   us-oh-marion
16.675   us-ca-shasta_county
16.354   ca-ab-calgary
16.302   us-oh-morrow
16.300   us-id-teton
16.095   jp-saga
16.057   us-oh-highland
15.799   us-va-halifax
15.565   jp-kochi
15.555   us-oh-logan
15.456   us-oh-pike
15.177   us-oh-holmes
15.073   us-oh-henry
15.065   us-nh-jaffrey
14.664   us-oh-clinton
14.541   us-oh-preble
14.537   ca-yk-whitehorse
14.442   us-nc-union
14.295   us-ca-berkeley
14.214   us-co-aurora
13.914   us-nc-city_of_elizabeth_city
13.876   us-oh-perry
13.676   jp-tottori
13.539   us-co-loveland
13.351   ca-bc-kelowna
13.335   us-nc-davie
13.325   jp-tokushima
13.276   us-mt-sanders
13.198   jp-fukui
13.157   us-nc-caswell
13.154   us-nc-city_of_king
13.120   us-mt-teton
12.972   us-co-boulder
12.967   us-mt-blaine
12.919   us-md-cecil
12.675   us-mt-jefferson
12.447   ca-on-guelph
12.382   us-mt-phillips
12.360   ca-bc-prince_george
12.336   us-mt-stillwater
12.278   us-mt-powell
12.269   us-oh-pickaway
12.214   us-oh-harrison
12.183   us-nc-blowing_rock
11.910   us-oh-wyandot
11.700   ca-on-burlington
11.690   us-va-city_of_radford
11.661   us-mo-cole
11.637   us-oh-hardin
11.628   us-mt-broadwater
11.604   us-ca-nevada_county
11.486   us-oh-mercer
11.400   ca-bc-okanagan_similkameen
11.281   us-oh-hocking
11.195   us-oh-meigs
11.153   us-oh-jackson
11.105   us-mt-fergus
10.942   us-oh-carroll
10.685   jp-saitama
10.585   us-oh-paulding
10.562   us-mt-big_horn
10.338   us-oh-van_wert
10.256   us-oh-brown
10.208   us-mt-valley
10.177   us-mt-deer_lodge
10.039   ca-on-oakville
9.806   us-mt-custer
9.804   us-mt-chouteau
9.730   us-va-salem
9.624   us-mt-roosevelt
9.514   us-mt-granite
9.391   us-oh-fayette
9.380   us-mt-carbon
9.232   us-mt-hill
9.210   us-mn-pope
9.134   us-ca-yuba_county
9.118   us-va-greene
9.055   us-oh-monroe
8.944   us-oh-vinton
8.440   us-oh-noble
8.099   us-mt-glacier
8.032   it-er-rimini
8.016   us-ia-pottawattamie
7.963   us-ia-marshall
7.956   us-mn-renville
7.882   us-mt-rosebud
7.764   ca-pe
7.546   us-va-blacksburg
7.546   us-mt-toole
7.523   us-mt-judith_basin
7.382   jp-tochigi
7.328   us-oh-auglaize
7.275   us-oh-adams
7.253   us-mt-musselshell
7.058   us-sd
6.987   us-mt-dawson
6.959   us-va-madison
6.927   us-nc-madison
6.911   us-mt-wheatland
6.894   us-mt-richland
6.827   us-ia-dallas
6.812   us-va-clarke
6.694   us-co-pitkin
6.667   us-ia-dickinson
6.585   us-ia-webster
6.560   us-nc-city_of_carolina_beach
6.412   us-mt-liberty
6.314   us-ia-marion
6.286   us-oh-morgan
6.271   us-ia-sioux
6.261   us-mt-petroleum
6.253   us-ia-crawford
6.188   us-al-shelby
6.133   us-ia-boone
6.026   us-wa-douglas
5.980   us-ia-sioux_county
5.860   jp-fukushima
5.552   us-ia-madison
5.505   us-va-city_of_petersburg
5.420   us-mt-garfield
5.335   us-mt-sheridan
5.186   us-ia-jasper
5.139   us-wi-iron
5.108   us-ia-carroll
5.078   kr-seoul-yeongdeungpogu-old
5.047   us-nm-dona_ana-2
5.013   us-mt-park
5.005   us-va-city_of_emporia
4.999   us-ia-winneshiek
4.996   us-mt-mineral
4.915   us-ia-palo_alto
4.892   us-wa-snohmish
4.869   kr-seoul-seongbukku-new
4.812   us-mt-fallon
4.801   us-mt-pondera
4.767   jp-ibaraki
4.594   us-ia-montgomery
4.562   us-in-st_joseph
4.530   us-mt-sweet_grass
4.496   us-ia-monona
4.491   us-ia-guthrie
4.443   us-ia-buchanan
4.368   kr-seoul-yangcheongu-new
4.308   kr-seoul-tobonggu-new
4.281   us-mt-meagher
4.225   jp-chiba
4.214   us-mt-carter
4.213   kr-seoul-mapogu-old
4.210   us-ia-buena_vista
4.198   kr-seoul-kangseogu-old
4.188   us-ia-wright
4.152   us-mt-prairie
4.141   jp-akita
4.135   jp-yamagata
4.127   kr-seoul-tongjakku-new
4.121   us-ia-shelby
4.120   us-nv-las_vegas
4.111   us-fl-alachua
4.079   us-ia-harrison
4.064   us-mt-powder_river
4.019   jp-gunma
4.016   kr-seoul-seodaemungu-new
4.009   us-ia-clarke
4.000   us-ia-benton
3.970   kr-seoul-yeongdeungpogu-new
3.960   us-ia-greene
3.950   us-ia-hardin
3.937   us-ia-franklin
3.911   us-ia-bremer
3.871   us-mt-daniels
3.865   us-ia-winnebago
3.757   us-pa-beaver
3.747   us-va-fluvanna
3.731   us-mt-mccone
3.518   ca-ab-grande_prairie
3.516   us-mi-ottawa
3.351   us-va-city_of_falls_church
3.319   us-ia-cass
3.311   kr-seoul-kangnamgu-new
3.309   us-ia-kossuth
3.306   us-mn-otter_tail
3.296   us-ia-delaware
3.294   kr-seoul-tongdaemungu-old
3.288   us-tn-memphis
3.243   us-ia-monroe
3.236   us-ia-cherokee
3.232   us-mt-golden_valley
3.223   us-ia-ida
3.207   us-ia-sac
3.195   us-ia-hamilton
3.194   us-ia-howard
3.180   us-va-middlesex
3.134   kr-seoul-songpagu-new
3.115   ca-bc-victoria
3.111   us-ia-calhoun
3.077   us-ia-decatur
3.071   kr-seoul-tongdaemungu-new
3.032   kr-seoul-kangbukku-new
2.957   us-mt-wibaux
2.898   kr-seoul-mapogu-new
2.890   us-ia-mills
2.851   us-ia-emmet
2.801   us-ia-lucas
2.752   kr-seoul-seongbukku-old
2.601   us-co-sanmiguel
2.595   kr-seoul-tongjakku-old
2.552   us-ia-pocahontas
2.546   kr-seoul-yangcheongu-old
2.498   us-ia-humboldt
2.490   kr-seoul-keumcheongu-old
2.433   us-ia-lyon
2.430   kr-seoul-kangnamgu-old
2.424   us-ia-clarke_county
2.412   us-ia-fremont
2.407   kr-seoul-kwangjingu-old
2.405   us-co-gilpin
2.375   us-tx-round_rock
2.365   us-mt-treasure
2.342   kr-seoul-kwanakku-new
2.328   us-mi-kent
2.325   us-ga-glynn
2.325   kr-seoul-kangseogu-new
2.325   jp-iwate
2.320   kr-seoul-seochogu-old
2.312   us-fl-collier
2.240   kr-seoul-kwanakku-old
2.200   kr-seoul-noweongu-new
2.190   kr-seoul-yongsangu-new
2.170   kr-seoul-noweongu-old
2.159   us-ak-matanuska_susitna_borough
2.117   kr-seoul-seochogu-new
2.032   us-mn-wilkin
2.026   kr-seoul-yongsangu-old
2.024   kr-seoul-kwangjingu-new
1.954   kr-seoul-chungnanggu-new
1.950   us-in-marion_county
1.875   kr-seoul-chongnogu-new
1.805   us-va-augusta
1.805   kr-seoul-kangbukku-old
1.798   ca-bc-west_kelowna
1.792   kr-seoul-chunggu-new
1.779   us-wi-oneida
1.774   kr-seoul-songpagu-old
1.767   kr-seoul-seongdonggu-new
1.753   kr-seoul-kurogu-new
1.750   us-wi-superior
1.733   us-nc-wake_county
1.724   us-mn-yellow_medicine
1.706   kr-seoul-kangdonggu-old
1.705   ca-bc-vernon
1.694   kr-seoul-chungnanggu-old
1.692   kr-seoul-chunggu-old
1.673   kr-seoul-seodaemungu-old
1.671   kr-seoul-seongdonggu-old
1.667   kr-seoul-kurogu-old
1.654   us-wi-adams
1.649   kr-seoul-kangdonggu-new
1.566   us-ct-lyme
1.565   kr-seoul-chongnogu-old
1.532   us-ct-watertown
1.519   kr-seoul-tobonggu-old
1.463   us-va-richmond_city
1.407   kr-seoul-keumcheongu-new
1.149   us-la-st_james
1.141   us-sc-lexington
1.141   us-nv-nye
1.137   us-ia-polk
1.134   us-ca-san_francisco
1.127   us-ct-haddam
1.121   us-mo-st_louis_county
1.120   us-mi-muskegon
1.115   us-mo-columbia
1.113   us-ri
1.108   us-wi-sauk
1.108   us-va-city_of_norton
1.105   us-wi-dodge
1.091   us-co-gunnison
1.091   us-ca-alameda_county
1.090   ca-bc-nanaimo
1.089   us-la-acadia
1.088   us-wa-san_juan
1.081   us-va-alexandria
1.079   us-va-roanoke
1.077   us-sc-berkeley
1.073   us-mn-polk
1.072   us-nv-henderson
1.070   dk
1.067   us-wi-fond_du_lac
1.064   us-in-madison
1.057   us-wi-juneau
1.040   us-mo-barry
1.003   ca-ns-halifax
0.986   us-al-calhoun
0.980   us-ca-amador
0.979   us-nv-washoe_county
0.953   us-ky-oldham
0.889   nz
0.863   us-va-essex
0.780   us-wi-jefferson
0.754   us-wi-vernon
0.720   us-nc-columbus
0.676   us-ny-nyc
0.658   us-ia-linn
0.654   us-ar
0.645   us-wi-richland
0.615   ca-ab-strathcona-county
0.609   ca-bc-surrey
0.547   us-wi-crawford
0.545   us-ma
0.532   us-wi-lincoln
0.529   us-ct-avon
0.524   us-va-accomack
0.524   us-nc-charlotte
0.516   ca-bc-langley
0.513   us-nv-lander
0.483   ca-sk-regina

OpenAddresses run: causes of failures

206 of the 608 sources I tried with the new Python code didn’t work. I went through and hand-classified them by type of failure. (Related: we need better error reporting in the code, I could only do this by reading stderr logfiles and guessing.)

I’d guess about half the failures are problems with the source not being online at the time. And maybe only a quarter of the problems are bugs in the Python parsing code. But not sure without looking more closely.

Update: I triaged and either solved or filed issues for the following failures:

  • Parser doesn’t handle malformed CSV
  • Parser doesn’t handle GML files
  • Excerpt failed (partial fix; the conform continues)
  • Run worked but no output CSV
=== Problems with the parser ===

Parser doesn't handle malformed CSV
https://github.com/openaddresses/machine/issues/36
  48 files: kr-seoul-*

Parser doesn't handle GML files
https://github.com/openaddresses/machine/issues/38
  15 files: pl-*

Excerpt failed
https://github.com/openaddresses/machine/issues/35
  is
  jp-akita, jp-chiba, jp-fukushima, jp-gunma, jp-ibaraki, jp-iwate, jp-saitama, jp-tochigi, jp-yamagata
  au-queensland
  ca-ab-calgary
  us-mn-dakota

Shapefile parsing problem
  ca-bc-okanagan_similkameen
  10 files: us-nc-? us-nc-10
  us-nc-lincoln
  us-ne-omaha
  us-va-stafford

CSV parsing problem
  be-flanders
  ca-pe
  us-co-mesa
  us-va

JSON parsing problem
  us-al-shelby
  us-ga-muscogee
  us-id-canyon
  us-in-hamilton
  us-mn-pope
  us-mn-wadena
  us-ms-hinds
  us-ms-madison
  us-nm-san_juan
  us-oh-hamilton
  us-pa-philadelphia
  us-tx-denton us-tx-el_paso us-tx-keller us-tx-north_richland_hills
  us-va-alexandria
  us-va-city_of_emporia
  us-va-city_of_petersburg
  us-wi-adams us-wi-crawford us-wi-dodge


=== Mysteries ===

Run worked but no output CSV
  ca-bc-surrey
  us-ak-matanuska_susitna_borough
  us-al-calhoun
  us-mi-kent
  us-mi-ottawa
  us-mn-otter_tail
  us-nv-las_vegas
  us-pa-beaver
  us-sc-berkeley
  us-sc-lexington
  us-sd
  us-va-accomack
  us-va-city_of_norton
  us-va-essex
  us-va-fluvanna
  us-wi-fond_du_lac
  us-wi-vernon
  us-wy-laramie


=== Malformed sources ===

Multiple shapefiles without a file attribute
  ca-bc-kamloops
  ca-bc-kelowna
  us-nc-davie
  us-oh-clinton
  us-wi-calumet


=== Problems getting source data ===

Download failed
  dk
  ca-ab-strathcona-county
  ca-bc-nanaimo
  ca-bc-vernon
  ca-ns-halifax
  ca-sk-regina
  us-ar
  us-ca-alameda_county
  us-ca-amador
  us-ca-san_francisco
  us-co-gunnison
  us-in-st_joseph
  us-mn-metrogis
  us-nc
  us-nc-wake_county
  us-ny-nyc
  us-va-augusta
  us-va-richmond_city
  us-wa-snohmish
  us-wi-superior
  za-nl-ethekwini

ESRI download failed
  us-ct-avon us-ct-haddam us-ct-lyme us-ct-watertown
  us-fl-alachua
  us-ia-linn
  us-ia-polk
  us-in-madison
  us-in-marion_county
  us-ky-oldham
  us-la-acadia
  us-mi-muskegon
  us-mn-polk
  us-mn-yellow_medicine
  us-mo-barry us-mo-columbia us-mo-st_louis_county
  us-mt-park
  us-nv-henderson us-nv-lander us-nv-nye us-nv-washoe_county
  us-tn-memphis
  us-va-roanoke
  us-va-salem
  us-wa-san_juan
  us-wi-iron us-wi-jefferson us-wi-juneau us-wi-lincoln us-wi-oneida us-wi-richland us-wi-sauk

Bad zip file
  nz
  ca-bc-langley
  ca-bc-west_kelowna
  us-co-sanmiguel
  us-fl-collier
  us-ga-glynn
  us-la-st_james
  us-ma
  us-nc-charlotte us-nc-columbus
  us-ri
  us-tx-round_rock
  us-va-city_of_falls_church

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.

GNU parallel for openaddr-process-one

I’ve been running batches of OpenAddress conversion jobs for bulk testing with a simple shell for loop

for f in us-ca-*.json; do
  openaddr-process-one &quot;$f&quot; /tmp/oa
done

But it’s better to do this in parallel, particularly since the work is a nice mix of CPU, network, and disk IO. Below is my first ever GNU parallel script to do that.

How much parallel? My system has 16 gigs of RAM and 4 honest CPUs (looks like 8 cores because of hyperthreading). I originally tried running “--jobs 200%” but because of the hyperthreading that results in 16 jobs which feels like a lot. So I’m keeping it at 8.

With 8 jobs in parallel we process 29 files in about 14 minutes. Running that in serial took 48 minutes. Los Angeles County alone takes 11 minutes and Solano County takes 10, so a total of 14 minutes to run 29 files sounds pretty good to me.

us-ca-los_angeles_county downloads fast, all its time is being spent in my Python conform code. There’s 3M rows so it’s no wonder it’s slow, but that seems too slow. Good place to focus some code optimization effort.

Solano county takes 10 minutes to download. It’s one of those ESRI webservice things, 391 requests for 500 records at a time and each one takes 1 or 2 seconds. I’ve been thinking we ought to have a separate pre-caching process for the ESRI combining, store the GeoJSON ripped data in S3 somewhere. There’s no way to test for data changes on the ESRI services so we can’t cache if we go direct, this way we could insulate the rest of the machine from the slowness of the services and the caching problems.

We wrote the code to be careful about RAM, processing everything as streams. Most jobs only take a polite 70M to run, but us-ca-kern, us-ca-marin_county, and us-ca-solano all mapped 1G+. Those are all ESRI type services, maybe the code is buffering all the data in RAM? Need to look more closely.

I suspect the main point of contention for running in parallel is disk IO. There’s a lot of file writing and copying; my own conform code basically writes the whole dataset twice. In theory I could get that down to once but it makes the code significantly more complicated.

Running this in parallel like this makes me realize there’s still work to do on the logging configuration. I want to be able to say “log only to a file named on the command line with a configuration specified in a file named here”; my logging config code doesn’t allow that. I can use the command line config to log to a file, then we just shove all of stderr to /dev/null. It’d be nicer to ask parallel drop stderr from the jobs its running but I couldn’t figure out how to do that. Even better would be to make it so I can configure the Python logging the way I want.

#!/bin/bash

# Quickie script to run a bunch of openaddr-process-one jobs in parallel

srcdir=/home/nelson/src/oa/openaddresses-me/sources
out=/tmp/oa
sources='us-ca-*.json'

# Only try to process sources with a conform
sources=$(cd &quot;$srcdir&quot;; grep -l 'conform' $sources)
sources=$(echo &quot;$sources&quot; | sed s/\.json$//g)
mkdir -p &quot;$out&quot;

# Echo a bunch of commands to run; these could be piped in to shell to run sequentially
#for s in $sources; do
#    echo openaddr-process-one -v -l &quot;$out/$s.log&quot; &quot;$srcdir/$s.json&quot; &quot;$out&quot;
#done

start=`date +%s`
parallel -u --jobs 8 openaddr-process-one -v -l &quot;$out/{}.log&quot; &quot;$srcdir/{}.json&quot; &quot;$out&quot; ::: $sources 2&gt; /dev/null
end=`date +%s`
echo `echo $sources | wc -w` jobs run in $[end-start] seconds

GitHub collaboration notes

After my whining about pull requests Mike gave me commit access to the repo. Here’s some quick notes on some simple git stuff he helped me do. The setup is we both started working in on separate projects. He made a private branch, made a bunch of changes, then pushed them to the ditch-node branch. Meanwhile I had made my own pyconform branch off of ditch-node before his changes and wanted to bring mine in with his. We could have just merged, but Mike asked me to rebase so that my changes came after his to keep the history tidy. That was easy because there were no conflicts. Here’s how it went.

# Push my pyconform branch up to GitHub
  506  git push -u origin pyconform

# Fetch Mike's changes in ditch-node
  507  git fetch origin ditch-node

# In my pyconform banch, rebase with the changes in ditch-node.
# This happened automatically without extra work on my part, no conflicts
# No commit necessary.
  510  git rebase origin/ditch-node

# Try to push my newly altered pyconform branch to GitHub
  513  git push
# That didn't work because we've altered history and Git is confused.
# So now we have to force the push to rewrite GitHub's version of things
  514  git push -f origin pyconform

# At this point my pyconform branch is done and looks as if I'd forked it off
# of Mike's changed, even though really we were working in parallel. Now it's
# time to merge my changes back to ditch-node and get rid of the pyconform branch

# Switch to ditch-node
  515  git checkout ditch-node
# Pull in the changes that are on GitHub
  516  git pull
# Merge from my pyconform branch
  517  git merge pyconform
# Push the merged commits back up to GitHub
  519  git push
# Delete my branch locally
  520  git branch -d pyconform
# Delete the branch on GitHub.
  521  git push origin pyconform
# Ooops, that didn't work, so do this magic to remotely delete the branch
  522  git push origin :pyconform

I regret not being more comfortable with this kind of git usage. I am sort of OK with git by myself but it’s a lot more complicated when collaborating.

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.