]> gitweb.michael.orlitzky.com - dead/census-tools.git/blob - bin/path2pop
Added the path2pop script.
[dead/census-tools.git] / bin / path2pop
1 #!/usr/bin/env python
2
3 """
4 We take a Well-Known Text string and one or more KML files as
5 parameters. We convert the WKT string to a polygon, and drag that
6 polygon along the paths defined within the KML files. For each path,
7 the result is another (longer) polygon, whose contained population is
8 output.
9 """
10
11 import os
12 import site
13 import sys
14
15
16 # Basically, add '../src' to our path.
17 # Needed for the imports that follow.
18 site.addsitedir(os.path.dirname(os.path.abspath(sys.argv[0])) + '/../src')
19
20 import Census
21 import CLI
22 import Configuration.Defaults
23 import ExitCodes
24 import Geometry
25 import KML
26
27 usage = '%prog [options] <well-known text> <kml file #1>, [kml file #2,...]'
28
29 # -h (help) Conflicts with -h HOSTNAME
30 parser = CLI.default_option_parser(usage)
31
32 # Use this module's docstring as the description.
33 parser.description = __doc__.strip()
34
35 parser.add_option('-s',
36 '--srid',
37 type="int",
38 help="SRID of the input geometry. Defaults to %s." % Configuration.Defaults.SRID,
39 default=Configuration.Defaults.SRID)
40
41 (options, args) = parser.parse_args()
42
43 if len(args) < 2:
44 print """
45 ERROR: You must supply both a Well-Known Text string, and a KML file
46 containing a linestring.
47 """
48 parser.print_help()
49 print '' # Print a newline
50 raise SystemExit(ExitCodes.NOT_ENOUGH_ARGS)
51
52
53 wkt_string = args[0]
54 paths = args[1:]
55
56 for path in paths:
57 f = open(path, 'r')
58 kml = f.read()
59 f.close()
60
61 coords = KML.LineString.tuples_from_kml(kml)
62 p = Geometry.Polygon.from_wkt(wkt_string)
63
64 death_tube = None
65
66 for i in range(len(coords) - 1):
67 # For each coordinate (except the last), we want to:
68 # a) Translate our polygon to the coordinate.
69 # b) Drag the polygon to the next coordinate.
70 this_coord = Geometry.TwoVector(coords[i][0], coords[i][1])
71 next_coord = Geometry.TwoVector(coords[i+1][0], coords[i+1][1])
72 drag_vector = (next_coord - this_coord)
73 tp = p.translate(this_coord)
74
75 if (death_tube == None):
76 death_tube = tp.drag(drag_vector)
77 else:
78 death_tube = death_tube.union(tp.drag(drag_vector))
79
80 cdb = Census.Database(options.host,
81 options.database,
82 options.username,
83 options.srid)
84
85 pop = cdb.find_contained_population(death_tube.wkt())
86
87 print "Path: %s; Population: %d" % (path, pop)