Report abuse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import getopt, sys, csv
from BeautifulSoup import BeautifulSoup

def colorize(paths,legend,colors,data):
	path_style = 'fill-opacity:1;fill:'
	for p in paths:
		if p['id'].startswith('RU-'):
			try:
				rate = data[p['id']]
			except:
				continue
			i = len(colors)-1
			color_class = 0
			for lv in legend:		
				if rate > lv:
					color_class = i
					color = colors[color_class]
					p['style'] = path_style + color
					continue
				i -= 1
def main():
	try:
		opts, args = getopt.getopt(sys.argv[1:], "vd:c:l:i:o:", ["data-file=", "colors-file=", "legend-file", "input-file=", "output-file="] )
	except getopt.GetoptError:
		print str(err)
		sys.exit(2)
	verbose = False
	datafile = ""
	colorsfile = ""
	legendfile = ""
	inputfile = ""
	outputfile = ""
	for o, a in opts:
		if o == "-v":
			verbose = True
		elif o in ("-d", "--data-file"):
			datafile = a
		elif o in ("-c", "--colors-file"):
			colorsfile = a
		elif o in ("-l", "--legend-file"):
			legendfile = a
		elif o in ("-i", "--input-file"):
			inputfile = a
		elif o in ("-o", "--output-file"):
			outputfile = a
		else:
			assert False, "unhandled option"
	if datafile == "":
		print "No input file specified"
		sys.exit(2)
	if colorsfile == "":
		print "No colors file specified"
		sys.exit(2)
	if legendfile == "":
		print "No legend file specified"
		sys.exit(2)
	if inputfile == "":
		print "No input file specified"
		sys.exit(2)
	if outputfile == "":
		print "No output file specified"
		sys.exit(2)

	# read the color scheme
	f = file(colorsfile, "r")
	colors = list()
	for line in f.readlines():
		colors.extend(line.split())
	f.close()

	#read the legend values
	l = file(legendfile, "r")
	legend = list()
	for line in l.readlines():
		legend.extend(map(float,line.split()))
	l.close()

	#read data
	data = {}
	csvReader = csv.reader(open(datafile), delimiter=",")
	for row in csvReader:
		fips = row[0]
		data[fips] = float( row[1] )

	#read SVG map
	svg = open(inputfile, 'r').read()
	soup = BeautifulSoup(svg)
	paths = soup.findAll('path')
	gs = soup.findAll('g')

	#print "%s: %s" % ('Colors', colors)
	#print "%s: %s" % ('Legend', legend)
	colorize(paths,legend,colors,data)
	colorize(gs,legend,colors,data)
	
	outsvg = open(outputfile, 'wt')
	outsvg.write(soup.prettify())
	outsvg.close()

if __name__ == "__main__":
	main()