#!/usr/bin/python """ Output the Well-Known-Text[1] representation of an n-gon, centered at (0,0). The parameter n is passed as a required command-line option. The radius of the n-gon is an optional argument. [1] http://en.wikipedia.org/wiki/Well-known_text """ import math import site import sys from optparse import OptionParser import os # Basically, add '../src' to our path. # Needed for the imports that follow. site.addsitedir(os.path.dirname(os.path.abspath(sys.argv[0])) + '/../src') import CLI import ExitCodes import Geometry import StringUtils usage = '%prog [options] ' fmtr = CLI.VerbatimHelpFormatter() parser = OptionParser(usage, formatter=fmtr) # Use this module's docstring as the description. parser.description = __doc__ parser.add_option('-r', '--radius', type="float", help="The radius of the n-gon. Defaults to 1.0.", default=1.0) (options, args) = parser.parse_args() if (len(args) < 1) or (not StringUtils.is_integer(args[0])): print "\nERROR: You must supply the number of sides, n.\n" parser.print_help() print '' # Print a newline. raise SystemExit(ExitCodes.NOT_ENOUGH_ARGS) # The conversion of n to int is safe, since it passed is_integer # above. n = int(args[0]) r = options.radius # Each new coordinate is going to be separated from the previous by # angle_delta radians. angle_delta = 2*math.pi / float(n) # The set of coordinates, as two-tuples. We already know the first # one--it's just cos/sin of 0. coords = [(r, 0)] for coord_idx in range(1, n): angle = coord_idx * angle_delta x = r * math.cos(angle) y = r * math.sin(angle) coords.append((x, y)) # A well-known-text polygon must be closed, i.e. the last coordinate # must equal the first. So, we're missing a coordinate, but the # Polygon class will handle it for us. p = Geometry.Polygon(coords) print p.wkt()