#!/usr/bin/python """ Find the average population density of a set of GPS coordinates. """ import sys import os import site # Basically, add '../src' to our path. # Needed for the imports that follow. site.addsitedir(os.path.dirname(os.path.abspath(sys.argv[0])) + '/../src') import Census import CLI import Configuration.Defaults import ExitCodes import GPS import StringUtils """ Parse the command line options. There's some magic involved here; otherwise, optparse woule like nothing more than to interpret GPS coordinates such as '-78.000000' as options. """ for idx, value in enumerate(sys.argv): # Please oh please don't rename this script to something which # validates as a negative float. if (StringUtils.is_negative_float(value)): sys.argv.insert(idx, '--') # We have to break here, otherwise the negative argument # will get shifted down the list, and we'll hit it again # in the next iteration of enumerate(). And then it'll # get shifted down the list... break usage = '%prog [options] ' parser = CLI.default_option_parser(usage) # Use this module's docstring as the description. parser.description = __doc__ parser.add_option('-s', '--srid', type="int", help="SRID of the input geometry. Defaults to %s." % Configuration.Defaults.SRID, default=Configuration.Defaults.SRID) (options, args) = parser.parse_args() if len(args) < 2: print "\nERROR: You must supply a longitude and latitude.\n" parser.print_help() print '' # Print a newline raise SystemExit(ExitCodes.NOT_ENOUGH_ARGS) coords = GPS.Coordinates() coords.longitude = float(args[0]) coords.latitude = float(args[1]) cdb = Census.Database(options.host, options.database, options.username, options.srid) avg_density = cdb.find_average_population_density(coords) if (avg_density != None): print str(avg_density) else: print 'Error: No rows returned.' print 'Did you pass (longitude, latitude) in the correct order?' raise SystemExit(ExitCodes.NO_RESULTS)