]> gitweb.michael.orlitzky.com - dead/census-tools.git/blob - bin/find_avg_population_density
Added a "Related Projects" heading containing a description of TRAGIS.
[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 from optparse import OptionParser
11
12 # Basically, add '../src' to our path.
13 # Needed for the imports that follow.
14 site.addsitedir(os.path.dirname(os.path.abspath(sys.argv[0])) + '/../src')
15
16 import Census
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 # -h (help) Conflicts with -h HOSTNAME
42 parser = OptionParser(usage=usage, add_help_option = False)
43
44 # Use this module's docstring as the description.
45 parser.description = __doc__.strip()
46
47 parser.add_option('-h',
48 '--host',
49 help='The hostname/address where the database is located.',
50 default=Configuration.Defaults.DATABASE_HOST)
51
52 parser.add_option('-d',
53 '--database',
54 help='The database in which the population data are stored.',
55 default=Configuration.Defaults.DATABASE_NAME)
56
57 parser.add_option('-U',
58 '--username',
59 help='The username who has access to the database.',
60 default=Configuration.Defaults.DATABASE_USERNAME)
61
62 parser.add_option('-s',
63 '--srid',
64 type="int",
65 help="SRID of the input geometry. Defaults to %s." % Configuration.Defaults.SRID,
66 default=Configuration.Defaults.SRID)
67
68 (options, args) = parser.parse_args()
69
70 if len(args) < 2:
71 print "\nERROR: You must supply a longitude and latitude.\n"
72 parser.print_help()
73 print '' # Print a newline
74 raise SystemExit(ExitCodes.NOT_ENOUGH_ARGS)
75
76
77 coords = GPS.Coordinates()
78 coords.longitude = float(args[0])
79 coords.latitude = float(args[1])
80
81 cdb = Census.Database(options.host,
82 options.database,
83 options.username,
84 options.srid)
85
86 avg_density = cdb.find_average_population_density(coords)
87
88 if (avg_density != None):
89 print str(avg_density)
90 else:
91 print 'Error: No rows returned.'
92 print 'Did you pass (longitude, latitude) in the correct order?'
93 raise SystemExit(ExitCodes.NO_RESULTS)
94