Technomancy

Entries tagged “code”

A powerset generator in python

written by rory, on Mar 17, 2009 2:09:00 PM.

The powerset of a set is the set of all possible subsets of a set. i.e. for the list [1, 2, 3], the power set is [ [], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3] ]. [wikipedia has more]. Generators in Python a powerful concept, and allow you to have lists that you can generate as you go along. So you don't need to calculate all the items in a list before using them. As you can see from the example above, the number of elements in a powerset of a list is much larger than the number of elements in the original list. If there are n items in the original list, then there are 2n items in the powerset. For example, the powerset of a 5 element list has 32 items, the powerset of a 10 element list has 1,024 items and so forth. Since powersets are so large, generators are very helpful here, since you don't have to generate (and store) a 1,024 element list before doing your calculation. Here is a simple generator function in python that will return (or 'yield') all the lists in the powerset of a list.
def powerset(seq):
    """
    Returns all the subsets of this set. This is a generator.
    """
    if len(seq) <= 1:
        yield seq
        yield []
    else:
        for item in powerset(seq[1:]):
            yield [seq[0]]+item
            yield item

Script to convert NMEA GPS traces to GPX

written by rory, on Mar 10, 2009 9:43:00 AM.

I have a Navi BGT-31 GPS reciever. I have it set to save things as NMEA, since that's a nice simple text format and it is easy to parse and save. It saves a different file every 2 hours. The following script will merge and convert NMEA TXT format files into a series of GPX tracks, with the date/time in the filename.
#! /bin/bash

FILES=$*

TMP_FILE=$(mktemp combined-traces.gpx.XXXXXX)
[ "$TMP_FILE" ] || exit 1

cat ${FILES} | gpsbabel -i nmea -f - -x sort,time -x discard,hdop=4,vdop=4 -x track,merge,sdistance=0.5k,title="track-%Y-%m-%d-%H:%M:%S" -x track,speed -o gpx -F ${TMP_FILE}

POINTS=$(xmlstarlet sel -N gpx=http://www.topografix.com/GPX/1/0  -t -m "/gpx:gpx" -v "count(//gpx:trkpt)" ${TMP_FILE})
NUM_TRACKS=$(xmlstarlet sel -N gpx=http://www.topografix.com/GPX/1/0  -t -m "/gpx:gpx" -v "count(./gpx:trk)" ${TMP_FILE})
echo "Found ${POINTS} trackpoints in ${NUM_TRACKS} tracks"

for TRACK in $(xmlstarlet sel -N gpx=http://www.topografix.com/GPX/1/0  -t -m "/gpx:gpx/gpx:trk" -v "./gpx:name" --nl ${TMP_FILE}) ; do
    echo "Extracting ${TRACK}.gpx..."
    gpsbabel -i gpx -f ${TMP_FILE} -x track,name=${TRACK} -o gpx -F ./${TRACK}.gpx
done

rm ${TMP_FILE}
echo "Done"