1 # Selectricity: Voting Machinery for the Masses
2 # Copyright (C) 2007, 2008 Benjamin Mako Hill <mako@atdot.cc>
3 # Copyright (C) 2007 Massachusetts Institute of Technology
5 # This program is free software. Please see the COPYING file for
9 class GraphController < ApplicationController
12 COLORS = ['#74CE00', '#005CD9', '#DC0D13', '#131313', '#A214A4', '#EFF80E',
13 '#90E5E6', '#F58313', '#437D3D', '#0E026C']
14 BACKGROUND_COLORS = ['#74CE00', '#FFFFFF'] #for green and white background
16 def initialize(options)
17 size = options[:size] ? options[:size] : "400x300" #allow custom sizing
18 @graph = options[:graph_type].new(size)
20 @graph.no_data_message = "No Voters"
22 @graph.theme = { :colors => COLORS,
23 :background_colors => ['#e5e5e5', '#FFFFFF'] }
24 @graph.font = File.expand_path('/usr/X11R6/lib/X11/fonts/TTF/Vera.ttf',
27 if options[:legend_font_size]
28 @graph.legend_font_size = options[:legend_font_size]
31 if options[:title_font_size]
32 @graph.title_font_size = options[:title_font_size]
35 #marker count doesn't include minimum value line, default is 4
36 @graph.marker_count = options[:marker_count] if options[:marker_count]
38 @graph.marker_font_size = options[:marker_font_size] if options[:marker_font_size]
40 @graph.marker_color = options[:marker_color] if options[:marker_color]
42 # fill in the data with the optional data name
43 #Check to see if multiple datasets, if so, fill them all!
44 #Sort by biggest first piece of data.
45 if options[:data].is_a?(Hash)
46 options[:data].sort {|a,b| b[1][0] <=> a[1][0]}.each do |dataset|
47 @graph.data(dataset[0], dataset[1])
49 #if each dataset nameless, will have only multiple arrays
50 elsif options[:data].size > 1 && options[:data].all? {|i| i.is_a?(Array)}
51 options[:data].each do |array|
52 @graph.data( options.fetch(:data_name, "Data"), array)
54 else #one dimensional array, just pass it in
55 @graph.data( options.fetch(:data_name, "Data"), options[:data] )
56 @graph.hide_legend = true
59 # set the labels or create an empty hash
60 @graph.labels = options[:interval_labels] \
61 if options.has_key?(:interval_labels) and \
62 options[:interval_labels].class == Hash
63 @graph.x_axis_label = options[:x_axis_label] \
64 if options.has_key?(:x_axis_label)
65 @graph.y_axis_label = options[:y_axis_label] \
66 if options.has_key?(:y_axis_label)
67 @graph.title = options[:title] if options.has_key?(:title)
69 @graph.minimum_value = 0.0
74 return([@graph.to_blob, {:disposition => 'inline', :type => 'image/png'}])
79 # produce a graph of votes per day during an election
81 @election = Election.find(params[:id])
82 data, labels = get_votes_per_day_data(@election)
84 graph = GruffGraff.new( :graph_type => Gruff::Line,
85 :data_name => @election.name,
87 :interval_labels => labels,
88 :title => "Voters Per Day",
89 :x_axis_label => "Data",
90 :y_axis_label =>"Number of Votes")
91 send_data(*graph.output)
94 #will place votes in a fixed number of intervals, and shows votes over time
95 def votes_per_interval
96 @election = Election.find(params[:id])
97 data, labels, scale = get_votes_per_interval_data(@election)
101 graph = GruffGraff.new( :graph_type => Gruff::Line,
102 :data_name => @election.name,
104 :interval_labels => labels,
105 :title => "Voters Over Time",
107 :legend_font_size => 40,
108 :title_font_size => 50,
110 :marker_font_size => 30,
111 :marker_color => '#999999',
112 :x_axis_label => scale,
113 :y_axis_label => "Number of Votes")
114 send_data(*graph.output)
118 @election = Election.find(params[:id])
119 @election.results unless @election.borda_result
120 data, labels = get_borda_points(@election.borda_result)
123 #size = "580x300" if @election.candidates.size >= 5
124 size = sprintf "580x%d", @election.candidates.size*22 \
125 if @election.candidates.size >= 5
127 if @election.candidates.size >= 5
128 marker_font_size = 17
130 marker_font_size = 20
133 graph = GruffGraff.new( :graph_type => Gruff::SideBar,
134 :data_name => @election.name,
136 :interval_labels => labels,
138 :title => "Points Per Candidate",
139 :marker_color => '#999999',
140 :marker_font_size => marker_font_size,
141 :x_axis_label => "Points",
142 :y_axis_label => "Candidates")
143 send_data(*graph.output)
145 #Acording to Tufte, small, concomparitive, highly labeled data sets usually
146 #belong in tables. The following is a bar graph...but would it be better
148 def choices_positions
149 @election = Election.find(params[:id])
151 alldata, labels = get_positions_info(@election)
152 @election.results unless @election.condorcet_result || @election.ssd_result
153 ranked_candidates = @election.condorcet_result.ranked_candidates.flatten
156 candidates = @election.candidates.sort.collect {|candidate| candidate.id}
157 candidates.each do |candidate|
158 names[candidate]= (Candidate.find(candidate)).name
161 ranked_candidates.each_with_index \
162 {|candidate, index| legend[names[candidate]] = alldata[index]}
164 graph = GruffGraff.new( :graph_type => Gruff::Bar,
166 :interval_labels => labels,
167 :title => "Times Voted in Each Position",
168 :y_axis_label => "Number of Times Ranked",
169 :x_axis_label => "Rank")
170 send_data(*graph.output)
174 @election = Election.find(params[:id])
175 @election.results unless @election.plurality_result || @election.approval_result
176 votes = @election.votes.size
178 names = @election.names_by_id
180 @election.plurality_result.points.each do |candidate, votes|
181 data[names[candidate]] = votes
184 size = "520x300" if @election.candidates.size >= 8
186 if @election.candidates.size >= 8
187 marker_font_size = 20
188 legend_font_size = 17
190 marker_font_size = 17
191 legend_font_size = 17
194 pie = GruffGraff.new( :graph_type => Gruff::Pie,
195 :title => "Percentage of First Place Votes",
197 :marker_font_size => marker_font_size,
198 :legend_font_size => legend_font_size,
200 send_data(*pie.output)
205 def get_positions_info(election)
208 rank_labels = Hash.new
210 #attach the ranking to the candidate's array to which is belongs
211 #creating a key if necessary
212 election.votes.each do |vote|
213 vote.rankings.each do |ranking|
215 unless buckets.has_key?(ranking.candidate_id)
216 buckets[ranking.candidate_id] = []
218 buckets[ranking.candidate_id] << ranking.rank
223 #count how many times each candidate has been ranked at a certain level
224 buckets.each_pair do |id, array|
225 (1..election.candidates.size).each do |i|
226 buckets2[id] = [] unless buckets2.has_key?(id)
227 buckets2[id] << (array.find_all {|rank| rank == i}).size
231 #sort by amount of 1st place votes
232 sorted_data = buckets2.values.sort {|a,b| b[0] <=> a[0]}
234 election.votes.each do |vote|
235 vote.rankings.size.times do |i|
236 rank_labels[i] = (i+1).to_s
240 return sorted_data, rank_labels
243 # generate the data and labels for each graph
244 def get_votes_per_day_data(election)
245 voter_days = Array.new
246 unique_days = Array.new
247 total_per_day = Array.new
248 election_days = Hash.new
250 #turn election startdate into date object, and create the range of election
251 startdate = Date.parse(election.startdate.to_s)
252 election_range = startdate..Date.today
254 # create a hash with all the dates of the election in String format
255 # referenced by their order in the election
256 election_range.each_with_index do |day, index|
257 election_days[index] = day.to_s
260 # Now I need to create an array with all the times votes were made
261 election.votes.each do |vote|
262 next unless vote.time
263 voter_days << Date.parse(vote.time.to_s)
267 # Now I need to count how many times each each date appears in voter_days,
268 # and put that number into a votes_per_day array, the 'data' for the graph
269 #Create an array of unique days from voter_days
270 voter_days.each do |day|
271 unless unique_days.any? {|date| date.eql?(day)}
277 #find all dates where those days = date at current index, put size of returned
278 #array into total_per_day
279 unique_days.each_with_index do |date, index|
280 total_per_day << (voter_days.select {|day| day.eql?(date)}).size
283 # return the data and the labels
284 return total_per_day, election_days
288 def get_votes_per_interval_data(election)
289 labels_hash = Hash.new
291 total_per_interval = Array.new
294 starttime = election.startdate
295 timedelta = Time.now - starttime
297 interval_length = timedelta/numcols
299 # Make a hash, buckets, indexed by time intervals and containing empty arrays
300 # The time object must come first in addition!
301 # i would start at 0, i+1 goes from 1 up till numcols
302 numcols.times {|i| buckets[starttime + ((i+1)*interval_length)] = []}
304 # Put votes into bucket according to the time interval to which they belong,
305 # referenced by their key
306 # Will build a graph over time, as each successive interval will have more
308 election.votes.each do |vote|
309 next unless vote.time
310 buckets.keys.sort.each do |inter|
312 buckets[inter] << vote
317 total_per_interval = buckets.keys.sort.collect {|key| buckets[key].size}
319 # Create the hash for the labels. Each graph has ten columns, and three
321 if timedelta < 2.hours #under two hours use minutes for labels
322 labels_hash[0] = "Start"
323 labels_hash[(numcols/2)-1] = fmt_decimal((timedelta/120)) #halfway
324 labels_hash[numcols-1] = fmt_decimal((timedelta/60))
325 interval_type = "Minutes After Start"
326 elsif timedelta < 2.days #more than 2 hours means use hours for labels
327 labels_hash[0] = "Start"
328 labels_hash[(numcols/2)-1] = fmt_decimal((timedelta/7200))
329 labels_hash[numcols-1] = fmt_decimal((timedelta/3600))
330 interval_type = "Hours After Start (Up to 48)"
331 else #more than 2 days means use dates for labels
332 labels_hash[0] = (Date.parse(starttime.to_s)).to_s
333 labels_hash[(numcols/2)-1] = (Date.parse((starttime + (timedelta/2)).to_s)).to_s
334 labels_hash[numcols-1] = (Date.today).to_s
335 interval_type = "The Date"
338 # Make sure to return an array for data and hash for labels
339 return total_per_interval, labels_hash, interval_type
342 def fmt_decimal(number)
343 sprintf( "%0.1f", number)
346 def get_borda_points(result)
350 #Populate points with an sorted array from election.votes hash
351 #biggest to smallest will go from left to right
352 points = result.points.sort do |a, b|
354 end.collect {|i| i[1]}
357 result.ranked_candidates.each_with_index do |candidate, index|
358 labels[index] = Candidate.find(candidate).name
361 return points, labels
364 #most vote result objects require an array of vote arrays, which this will make
365 def make_preference_tally(election)
366 preference_tally = Array.new
367 @election.voters.each do |voter|
368 next unless voter.voted?
369 preference_tally << voter.vote.rankings.sort.collect \
370 { |ranking| ranking.candidate.id }
372 return preference_tally