]>
gitweb.michael.orlitzky.com - dead/census-tools.git/blob - find_avg_population_density
e6d8ac75906c7bf722e0dd310c309d2a26d820f5
4 Find the average population density of a set of GPS coordinates.
11 from optparse
import OptionParser
13 # Basically, add '../src' to our path.
14 # Needed for the imports that follow.
15 site
.addsitedir(os
.path
.dirname(os
.path
.abspath(sys
.argv
[0])) + '/../src')
17 import Configuration
.Defaults
25 Parse the command line options. There's some magic involved here;
26 otherwise, optparse woule like nothing more than to interpret GPS
27 coordinates such as '-78.000000' as options.
29 for idx
, value
in enumerate(sys
.argv
):
30 # Please oh please don't rename this script to something which
31 # validates as a negative float.
32 if (StringUtils
.is_negative_float(value
)):
33 sys
.argv
.insert(idx
, '--')
34 # We have to break here, otherwise the negative argument
35 # will get shifted down the list, and we'll hit it again
36 # in the next iteration of enumerate(). And then it'll
37 # get shifted down the list...
40 usage
= '%prog [options] <longitude> <latitude>'
42 # -h (help) Conflicts with -h HOSTNAME
43 parser
= OptionParser(usage
=usage
, add_help_option
= False)
45 # Use this module's docstring as the description.
46 parser
.description
= __doc__
48 parser
.add_option('-h',
50 help='The hostname/address where the database is located.',
51 default
=Configuration
.Defaults
.DATABASE_HOST
)
53 parser
.add_option('-d',
55 help='The database in which the population data are stored.',
56 default
=Configuration
.Defaults
.DATABASE_NAME
)
58 parser
.add_option('-U',
60 help='The username who has access to the database.',
61 default
=Configuration
.Defaults
.DATABASE_USERNAME
)
63 (options
, args
) = parser
.parse_args()
66 print "\nERROR: You must supply a longitude and latitude.\n"
68 print '' # Print a newline
69 raise SystemExit(ExitCodes
.NOT_ENOUGH_ARGS
)
72 coords
= GPS
.Coordinates()
73 coords
.longitude
= float(args
[0])
74 coords
.latitude
= float(args
[1])
76 conn
= pgdb
.connect(host
=options
.host
,
77 database
=options
.database
,
78 user
=options
.username
)
80 cursor
= conn
.cursor()
86 # Most GIS software, including PostGIS and the associated libraries,
87 # store and manipulate GPS coordinates in (longitude, latitude) format
88 # rather than (latitude, longitude) format.
92 SELECT population_density
93 FROM (sf1_blocks INNER JOIN tiger
94 ON sf1_blocks.tiger_blkidfp00=tiger.blkidfp00)
95 WHERE ST_Contains(tiger.the_geom,
96 ST_SetSRID(ST_Point(%.6f, %.6f), 4269));
97 """ % (coords
.longitude
, coords
.latitude
)
100 rows
= cursor
.fetchall()
103 avg_density
= rows
[0][0]
104 print str(avg_density
)
106 print 'Error: No rows returned.'
107 print 'Did you pass (longitude, latitude) in the correct order?'
108 raise SystemExit(ExitCodes
.NO_RESULTS
)