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: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Affero General Public License for more details.
15 # You should have received a copy of the GNU Affero General Public
16 # License along with this program. If not, see
17 # <http://www.gnu.org/licenses/>.
20 class GraphController < ApplicationController
23 COLORS = ['#74CE00', '#005CD9', '#DC0D13', '#131313', '#A214A4', 'EFF80E',
24 '90E5E6', 'F58313', '437D3D', '0E026C']
25 BACKGROUND_COLORS = ['#74CE00', '#FFFFFF'] #for green and white background
27 def initialize(options)
28 size = options[:size] ? options[:size] : "400x300" #allow custom sizing
29 @graph = options[:graph_type].new(size)
31 @graph.no_data_message = "No Voters"
33 @graph.theme = { :colors => COLORS,
34 :background_colors => ['#e5e5e5', '#FFFFFF'] }
35 @graph.font = File.expand_path('/usr/X11R6/lib/X11/fonts/TTF/Vera.ttf',
38 if options[:legend_font_size]
39 @graph.legend_font_size = options[:legend_font_size]
42 if options[:title_font_size]
43 @graph.title_font_size = options[:title_font_size]
46 #marker count doesn't include minimum value line, default is 4
47 @graph.marker_count = options[:marker_count] if options[:marker_count]
49 @graph.marker_font_size = options[:marker_font_size] if options[:marker_font_size]
51 @graph.marker_color = options[:marker_color] if options[:marker_color]
53 # fill in the data with the optional data name
54 #Check to see if multiple datasets, if so, fill them all!
55 #Sort by biggest first piece of data.
56 if options[:data].is_a?(Hash)
57 options[:data].sort {|a,b| b[1][0] <=> a[1][0]}.each do |dataset|
58 @graph.data(dataset[0], dataset[1])
60 #if each dataset nameless, will have only multiple arrays
61 elsif options[:data].size > 1 && options[:data].all? {|i| i.is_a?(Array)}
62 options[:data].each do |array|
63 @graph.data( options.fetch(:data_name, "Data"), array)
65 else #one dimensional array, just pass it in
66 @graph.data( options.fetch(:data_name, "Data"), options[:data] )
67 @graph.hide_legend = true
70 # set the labels or create an empty hash
71 @graph.labels = options[:interval_labels] \
72 if options.has_key?(:interval_labels) and \
73 options[:interval_labels].class == Hash
74 @graph.x_axis_label = options[:x_axis_label] \
75 if options.has_key?(:x_axis_label)
76 @graph.y_axis_label = options[:y_axis_label] \
77 if options.has_key?(:y_axis_label)
78 @graph.title = options[:title] if options.has_key?(:title)
80 @graph.minimum_value = 0.0
85 return([@graph.to_blob, {:disposition => 'inline', :type => 'image/png'}])
90 # produce a graph of votes per day during an election
92 @election = Election.find(params[:id])
93 data, labels = get_votes_per_day_data(@election)
95 graph = GruffGraff.new( :graph_type => Gruff::Line,
96 :data_name => @election.name,
98 :interval_labels => labels,
99 :title => "Voters Per Day",
100 :x_axis_label => "Data",
101 :y_axis_label =>"Number of Votes")
102 send_data(*graph.output)
105 #will place votes in a fixed number of intervals, and shows votes over time
106 def votes_per_interval
107 @election = Election.find(params[:id])
108 data, labels, scale = get_votes_per_interval_data(@election)
112 graph = GruffGraff.new( :graph_type => Gruff::Line,
113 :data_name => @election.name,
115 :interval_labels => labels,
116 :title => "Voters Over Time",
118 :legend_font_size => 40,
119 :title_font_size => 50,
121 :marker_font_size => 30,
122 :marker_color => '#999999',
123 :x_axis_label => scale,
124 :y_axis_label => "Number of Votes")
125 send_data(*graph.output)
129 @election = Election.find(params[:id])
130 @election.results unless @election.borda_result
131 data, labels = get_borda_points(@election.borda_result)
134 size = "580x300" if @election.candidates.size >= 5
136 if @election.candidates.size >= 5
137 marker_font_size = 17
139 marker_font_size = 20
142 graph = GruffGraff.new( :graph_type => Gruff::Bar,
143 :data_name => @election.name,
145 :interval_labels => labels,
147 :title => "Points Per Candidate",
148 :marker_color => '#999999',
149 :marker_font_size => marker_font_size,
150 :y_axis_label => "Points",
151 :x_axis_label => "Candidates")
152 send_data(*graph.output)
154 #Acording to Tufte, small, concomparitive, highly labeled data sets usually
155 #belong in tables. The following is a bar graph...but would it be better
157 def choices_positions
158 @election = Election.find(params[:id])
160 alldata, labels = get_positions_info(@election)
161 @election.results unless @election.condorcet_result || @election.ssd_result
162 ranked_candidates = @election.condorcet_result.ranked_candidates.flatten
165 candidates = @election.candidates.sort.collect {|candidate| candidate.id}
166 candidates.each do |candidate|
167 names[candidate]= (Candidate.find(candidate)).name
170 ranked_candidates.each_with_index \
171 {|candidate, index| legend[names[candidate]] = alldata[index]}
173 graph = GruffGraff.new( :graph_type => Gruff::Bar,
175 :interval_labels => labels,
176 :title => "Times Voted in Each Position",
177 :y_axis_label => "Number of Times Ranked",
178 :x_axis_label => "Rank")
179 send_data(*graph.output)
183 @election = Election.find(params[:id])
184 @election.results unless @election.plurality_result || @election.approval_result
185 votes = @election.votes.size
187 names = @election.names_by_id
189 @election.plurality_result.points.each do |candidate, votes|
190 data[names[candidate]] = votes
193 pie = GruffGraff.new( :graph_type => Gruff::Pie,
194 :title => "Percentage of First Place Votes",
196 send_data(*pie.output)
201 def get_positions_info(election)
204 rank_labels = Hash.new
206 #attach the ranking to the candidate's array to which is belongs
207 #creating a key if necessary
208 election.votes.each do |vote|
209 vote.rankings.each do |ranking|
211 unless buckets.has_key?(ranking.candidate_id)
212 buckets[ranking.candidate_id] = []
214 buckets[ranking.candidate_id] << ranking.rank
219 #count how many times each candidate has been ranked at a certain level
220 buckets.each_pair do |id, array|
221 (1..election.candidates.size).each do |i|
222 buckets2[id] = [] unless buckets2.has_key?(id)
223 buckets2[id] << (array.find_all {|rank| rank == i}).size
227 #sort by amount of 1st place votes
228 sorted_data = buckets2.values.sort {|a,b| b[0] <=> a[0]}
230 election.votes.each do |vote|
231 vote.rankings.size.times do |i|
232 rank_labels[i] = (i+1).to_s
236 return sorted_data, rank_labels
239 # generate the data and labels for each graph
240 def get_votes_per_day_data(election)
241 voter_days = Array.new
242 unique_days = Array.new
243 total_per_day = Array.new
244 election_days = Hash.new
246 #turn election startdate into date object, and create the range of election
247 startdate = Date.parse(election.startdate.to_s)
248 election_range = startdate..Date.today
250 # create a hash with all the dates of the election in String format
251 # referenced by their order in the election
252 election_range.each_with_index do |day, index|
253 election_days[index] = day.to_s
256 # Now I need to create an array with all the times votes were made
257 election.votes.each do |vote|
258 next unless vote.time
259 voter_days << Date.parse(vote.time.to_s)
263 # Now I need to count how many times each each date appears in voter_days,
264 # and put that number into a votes_per_day array, the 'data' for the graph
265 #Create an array of unique days from voter_days
266 voter_days.each do |day|
267 unless unique_days.any? {|date| date.eql?(day)}
273 #find all dates where those days = date at current index, put size of returned
274 #array into total_per_day
275 unique_days.each_with_index do |date, index|
276 total_per_day << (voter_days.select {|day| day.eql?(date)}).size
279 # return the data and the labels
280 return total_per_day, election_days
284 def get_votes_per_interval_data(election)
285 labels_hash = Hash.new
287 total_per_interval = Array.new
290 starttime = election.startdate
291 timedelta = Time.now - starttime
293 interval_length = timedelta/numcols
295 # Make a hash, buckets, indexed by time intervals and containing empty arrays
296 # The time object must come first in addition!
297 # i would start at 0, i+1 goes from 1 up till numcols
298 numcols.times {|i| buckets[starttime + ((i+1)*interval_length)] = []}
300 # Put votes into bucket according to the time interval to which they belong,
301 # referenced by their key
302 # Will build a graph over time, as each successive interval will have more
304 election.votes.each do |vote|
305 next unless vote.time
306 buckets.keys.sort.each do |inter|
308 buckets[inter] << vote
313 total_per_interval = buckets.keys.sort.collect {|key| buckets[key].size}
315 # Create the hash for the labels. Each graph has ten columns, and three
317 if timedelta < 2.hours #under two hours use minutes for labels
318 labels_hash[0] = "Start"
319 labels_hash[(numcols/2)-1] = fmt_decimal((timedelta/120)) #halfway
320 labels_hash[numcols-1] = fmt_decimal((timedelta/60))
321 interval_type = "Minutes After Start"
322 elsif timedelta < 2.days #more than 2 hours means use hours for labels
323 labels_hash[0] = "Start"
324 labels_hash[(numcols/2)-1] = fmt_decimal((timedelta/7200))
325 labels_hash[numcols-1] = fmt_decimal((timedelta/3600))
326 interval_type = "Hours After Start (Up to 48)"
327 else #more than 2 days means use dates for labels
328 labels_hash[0] = (Date.parse(starttime.to_s)).to_s
329 labels_hash[(numcols/2)-1] = (Date.parse((starttime + (timedelta/2)).to_s)).to_s
330 labels_hash[numcols-1] = (Date.today).to_s
331 interval_type = "The Date"
334 # Make sure to return an array for data and hash for labels
335 return total_per_interval, labels_hash, interval_type
338 def fmt_decimal(number)
339 sprintf( "%0.1f", number)
342 def get_borda_points(result)
346 #Populate points with an sorted array from election.votes hash
347 #biggest to smallest will go from left to right
348 points = result.points.sort do |a, b|
350 end.collect {|i| i[1]}
353 result.ranked_candidates.each_with_index do |candidate, index|
354 labels[index] = Candidate.find(candidate).name
357 return points, labels
360 #most vote result objects require an array of vote arrays, which this will make
361 def make_preference_tally(election)
362 preference_tally = Array.new
363 @election.voters.each do |voter|
364 next unless voter.voted?
365 preference_tally << voter.vote.rankings.sort.collect \
366 { |ranking| ranking.candidate.id }
368 return preference_tally