]> gitweb.michael.orlitzky.com - dead/census-tools.git/blob - bin/find_avg_population_density
Modified the default_option_parser function to return a parser using a VerbatimHelpFo...
[dead/census-tools.git] / bin / find_avg_population_density
1 #!/usr/bin/python
2
3 """
4 Find the average population density of a set of GPS coordinates.
5 """
6
7 import sys
8 import os
9 import site
10
11 # Basically, add '../src' to our path.
12 # Needed for the imports that follow.
13 site.addsitedir(os.path.dirname(os.path.abspath(sys.argv[0])) + '/../src')
14
15 import Census
16 import CLI
17 import Configuration.Defaults
18 import ExitCodes
19 import GPS
20 import StringUtils
21
22
23 """
24 Parse the command line options. There's some magic involved here;
25 otherwise, optparse woule like nothing more than to interpret GPS
26 coordinates such as '-78.000000' as options.
27 """
28 for idx, value in enumerate(sys.argv):
29 # Please oh please don't rename this script to something which
30 # validates as a negative float.
31 if (StringUtils.is_negative_float(value)):
32 sys.argv.insert(idx, '--')
33 # We have to break here, otherwise the negative argument
34 # will get shifted down the list, and we'll hit it again
35 # in the next iteration of enumerate(). And then it'll
36 # get shifted down the list...
37 break
38
39 usage = '%prog [options] <longitude> <latitude>'
40
41 parser = CLI.default_option_parser(usage)
42
43 # Use this module's docstring as the description.
44 parser.description = __doc__
45
46 parser.add_option('-s',
47 '--srid',
48 type="int",
49 help="SRID of the input geometry. Defaults to %s." % Configuration.Defaults.SRID,
50 default=Configuration.Defaults.SRID)
51
52 (options, args) = parser.parse_args()
53
54 if len(args) < 2:
55 print "\nERROR: You must supply a longitude and latitude.\n"
56 parser.print_help()
57 print '' # Print a newline
58 raise SystemExit(ExitCodes.NOT_ENOUGH_ARGS)
59
60
61 coords = GPS.Coordinates()
62 coords.longitude = float(args[0])
63 coords.latitude = float(args[1])
64
65 cdb = Census.Database(options.host,
66 options.database,
67 options.username,
68 options.srid)
69
70 avg_density = cdb.find_average_population_density(coords)
71
72 if (avg_density != None):
73 print str(avg_density)
74 else:
75 print 'Error: No rows returned.'
76 print 'Did you pass (longitude, latitude) in the correct order?'
77 raise SystemExit(ExitCodes.NO_RESULTS)
78