]> gitweb.michael.orlitzky.com - dead/census-tools.git/blob - bin/wkt_n-gon
Added the wkt_n-gon script.
[dead/census-tools.git] / bin / wkt_n-gon
1 #!/usr/bin/python
2
3 """
4 Output the Well-Known-Text[1] representation of an n-gon, centered at
5 (0,0).
6
7 The parameter n is passed as a required command-line option. The
8 radius of the n-gon is an optional argument.
9
10 [1] http://en.wikipedia.org/wiki/Well-known_text
11 """
12
13 import math
14 import site
15 import sys
16 from optparse import OptionParser
17 import os
18
19 # Basically, add '../src' to our path.
20 # Needed for the imports that follow.
21 site.addsitedir(os.path.dirname(os.path.abspath(sys.argv[0])) + '/../src')
22
23 import CLI
24 import ExitCodes
25 import Geometry
26 import StringUtils
27
28 usage = '%prog [options] <number of sides>'
29 fmtr = CLI.VerbatimHelpFormatter()
30 parser = OptionParser(usage, formatter=fmtr)
31
32 # Use this module's docstring as the description.
33 parser.description = __doc__
34
35
36 parser.add_option('-r',
37 '--radius',
38 type="float",
39 help="The radius of the n-gon. Defaults to 1.0.",
40 default=1.0)
41
42
43 (options, args) = parser.parse_args()
44
45 if (len(args) < 1) or (not StringUtils.is_integer(args[0])):
46 print "\nERROR: You must supply the number of sides, n.\n"
47 parser.print_help()
48 print '' # Print a newline.
49 raise SystemExit(ExitCodes.NOT_ENOUGH_ARGS)
50
51 # The conversion of n to int is safe, since it passed is_integer
52 # above.
53 n = int(args[0])
54 r = options.radius
55
56 # Each new coordinate is going to be separated from the previous by
57 # angle_delta radians.
58 angle_delta = 2*math.pi / float(n)
59
60 # The set of coordinates, as two-tuples. We already know the first
61 # one--it's just cos/sin of 0.
62 coords = [(r, 0)]
63
64 for coord_idx in range(1, n):
65 angle = coord_idx * angle_delta
66 x = r * math.cos(angle)
67 y = r * math.sin(angle)
68 coords.append((x, y))
69
70 # A well-known-text polygon must be closed, i.e. the last coordinate
71 # must equal the first. So, we're missing a coordinate, but the
72 # Polygon class will handle it for us.
73 p = Geometry.Polygon(coords)
74 print p.wkt()