merged in licensing changes (we'll have to undo this eventually)
[selectricity-live] / app / controllers / graph_controller.rb
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
4 #
5 # This program is free software. Please see the COPYING file for
6 # details.
7
8 require 'date'
9 class GraphController < ApplicationController  
10   class GruffGraff
11     
12     COLORS = ['#74CE00', '#005CD9', '#DC0D13', '#131313', '#A214A4', '#EFF80E',
13               '#90E5E6', '#F58313', '#437D3D', '#0E026C']
14     BACKGROUND_COLORS = ['#74CE00', '#FFFFFF'] #for green and white background
15     
16     def initialize(options)
17       size = options[:size] ? options[:size] : "400x300" #allow custom sizing
18       @graph = options[:graph_type].new(size)
19       
20       @graph.no_data_message = "No Voters"
21       
22       @graph.theme = { :colors => COLORS,
23                        :background_colors => ['#e5e5e5', '#FFFFFF']  }
24       @graph.font = File.expand_path('/usr/X11R6/lib/X11/fonts/TTF/Vera.ttf',
25                                    RAILS_ROOT)
26       
27       if options[:legend_font_size]
28         @graph.legend_font_size = options[:legend_font_size] 
29       end
30       
31       if options[:title_font_size]  
32         @graph.title_font_size = options[:title_font_size]
33       end
34       
35       #marker count doesn't include minimum value line, default is 4
36       @graph.marker_count = options[:marker_count] if options[:marker_count]
37       
38       @graph.marker_font_size = options[:marker_font_size] if options[:marker_font_size]
39       
40       @graph.marker_color = options[:marker_color] if options[:marker_color]
41       
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])
48         end
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)
53         end
54       else #one dimensional array, just pass it in
55       @graph.data( options.fetch(:data_name, "Data"), options[:data] )
56       @graph.hide_legend = true
57       end
58       
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)
68       
69       @graph.minimum_value = 0.0
70
71     end
72
73     def output
74       return([@graph.to_blob, {:disposition => 'inline', :type => 'image/png'}])
75     end
76
77   end
78
79   # produce a graph of votes per day during an election
80   def votes_per_day
81     @election = Election.find(params[:id])
82     data, labels = get_votes_per_day_data(@election)
83     
84     graph = GruffGraff.new( :graph_type => Gruff::Line,
85                             :data_name => @election.name,
86                             :data => data,
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)
92   end
93   
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)
98     
99     hide_legend = true
100     
101     graph = GruffGraff.new( :graph_type => Gruff::Line,
102                             :data_name => @election.name,
103                             :data => data,
104                             :interval_labels => labels,
105                             :title => "Voters Over Time",
106                             :size => "330x232", 
107                             :legend_font_size => 40,
108                             :title_font_size => 50,
109                             :marker_count => 2,
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)
115   end
116   
117   def borda_bar
118     @election = Election.find(params[:id])
119     @election.results unless @election.borda_result
120     data, labels = get_borda_points(@election.borda_result)
121     
122     size = "400x300"
123     size = "580x300" if @election.candidates.size >= 5
124     
125    if @election.candidates.size >= 5
126      marker_font_size = 17
127    else
128      marker_font_size = 20
129    end
130     
131     graph = GruffGraff.new( :graph_type => Gruff::Bar,
132                             :data_name => @election.name,
133                             :data => data,
134                             :interval_labels => labels,
135                             :size => size,
136                             :title => "Points Per Candidate",
137                             :marker_color => '#999999',
138                             :marker_font_size => marker_font_size,
139                             :y_axis_label => "Points",
140                             :x_axis_label => "Candidates")
141     send_data(*graph.output)
142   end
143   #Acording to Tufte, small, concomparitive, highly labeled data sets usually
144   #belong in tables. The following is a bar graph...but would it be better
145   #as a table?
146   def choices_positions
147     @election = Election.find(params[:id])
148     legend = Hash.new   
149     alldata, labels = get_positions_info(@election)    
150     @election.results unless @election.condorcet_result || @election.ssd_result
151     ranked_candidates = @election.condorcet_result.ranked_candidates.flatten
152     
153     names = Hash.new
154     candidates = @election.candidates.sort.collect {|candidate| candidate.id}
155     candidates.each do |candidate|
156       names[candidate]= (Candidate.find(candidate)).name
157     end
158     
159     ranked_candidates.each_with_index \
160     {|candidate, index| legend[names[candidate]] = alldata[index]}
161     
162     graph = GruffGraff.new( :graph_type => Gruff::Bar,
163                             :data => legend,
164                             :interval_labels => labels,
165                             :title => "Times Voted in Each Position",
166                             :y_axis_label => "Number of Times Ranked",
167                             :x_axis_label => "Rank")
168     send_data(*graph.output) 
169   end
170   
171   def plurality_pie
172     @election = Election.find(params[:id])
173     @election.results unless @election.plurality_result || @election.approval_result
174     votes = @election.votes.size
175     data = Hash.new
176     names = @election.names_by_id
177     
178     @election.plurality_result.points.each do |candidate, votes|
179       data[names[candidate]] = votes
180     end
181     size = "400x300"
182     size = "520x300" if @election.candidates.size >= 8
183
184    if @election.candidates.size >= 8
185      marker_font_size = 20
186      legend_font_size = 17
187    else
188      marker_font_size = 17
189      legend_font_size = 17
190    end
191  
192     pie = GruffGraff.new( :graph_type => Gruff::Pie,
193                            :title => "Percentage of First Place Votes",
194                            :size => size,
195                            :marker_font_size => marker_font_size,
196                            :legend_font_size => legend_font_size,
197                            :data => data)
198     send_data(*pie.output)
199                            
200   end
201   
202  private 
203   def get_positions_info(election)
204     buckets = Hash.new
205     buckets2= Hash.new
206     rank_labels = Hash.new
207     
208     #attach the ranking to the candidate's array to which is belongs
209     #creating a key if necessary
210     election.votes.each do |vote|
211       vote.rankings.each do |ranking|
212         
213          unless buckets.has_key?(ranking.candidate_id)
214            buckets[ranking.candidate_id] = []
215          end
216         buckets[ranking.candidate_id] << ranking.rank
217         
218       end
219     end
220     
221     #count how many times each candidate has been ranked at a certain level
222     buckets.each_pair do |id, array|
223       (1..election.candidates.size).each do |i|
224         buckets2[id] = [] unless buckets2.has_key?(id)
225         buckets2[id] << (array.find_all {|rank| rank == i}).size
226       end
227     end
228     
229     #sort by amount of 1st place votes
230     sorted_data = buckets2.values.sort {|a,b| b[0] <=> a[0]}
231     
232     election.votes.each do |vote|
233       vote.rankings.size.times do |i|
234         rank_labels[i] = (i+1).to_s
235       end
236     end
237     
238     return sorted_data, rank_labels   
239   end
240    
241   # generate the data and labels for each graph
242   def get_votes_per_day_data(election)
243     voter_days = Array.new
244     unique_days = Array.new
245     total_per_day = Array.new
246     election_days = Hash.new
247     
248     #turn election startdate into date object, and create the range of election
249     startdate = Date.parse(election.startdate.to_s)
250     election_range = startdate..Date.today
251     
252     # create a hash with all the dates of the election in String format
253     # referenced by their order in the election
254     election_range.each_with_index do |day, index|
255       election_days[index] = day.to_s
256     end
257     
258     # Now I need to create an array with all the times votes were made
259     election.votes.each do |vote|
260       next unless vote.time
261       voter_days << Date.parse(vote.time.to_s)
262     end
263     voter_days.sort!
264     
265     # Now I need to count how many times each each date appears in voter_days,
266     # and put that number into a votes_per_day array, the 'data' for the graph    
267     #Create an array of unique days from voter_days
268     voter_days.each do |day|
269       unless unique_days.any? {|date| date.eql?(day)}
270         unique_days << day
271       end
272     end
273     unique_days.sort!
274     
275     #find all dates where those days = date at current index, put size of returned
276     #array into total_per_day
277     unique_days.each_with_index do |date, index|
278       total_per_day << (voter_days.select {|day| day.eql?(date)}).size
279     end    
280
281     # return the data and the labels
282     return total_per_day, election_days
283    
284   end
285   
286   def get_votes_per_interval_data(election)
287     labels_hash = Hash.new
288     buckets = Hash.new
289     total_per_interval = Array.new
290     interval_type = ""
291     
292     starttime = election.startdate
293     timedelta = Time.now - starttime
294     numcols = 10
295     interval_length = timedelta/numcols
296     
297     # Make a hash, buckets, indexed by time intervals and containing empty arrays
298     # The time object must come first in addition! 
299     # i would start at 0, i+1 goes from 1 up till numcols
300     numcols.times {|i| buckets[starttime + ((i+1)*interval_length)] = []}
301      
302     # Put votes into bucket according to the time interval to which they belong,
303     # referenced by their key
304     # Will build a graph over time, as each successive interval will have more
305     # vote objects  
306     election.votes.each do |vote|
307       next unless vote.time
308       buckets.keys.sort.each do |inter|
309         if vote.time < inter
310           buckets[inter] << vote
311         end
312       end
313     end
314   
315     total_per_interval = buckets.keys.sort.collect {|key| buckets[key].size}
316     
317     # Create the hash for the labels. Each graph has ten columns, and three
318     # will be labeled
319     if timedelta < 2.hours #under two hours use minutes for labels
320       labels_hash[0] = "Start"
321       labels_hash[(numcols/2)-1] = fmt_decimal((timedelta/120)) #halfway
322       labels_hash[numcols-1] = fmt_decimal((timedelta/60))
323       interval_type = "Minutes After Start"
324     elsif timedelta < 2.days #more than 2 hours means use hours for labels
325       labels_hash[0] = "Start"
326       labels_hash[(numcols/2)-1] = fmt_decimal((timedelta/7200))
327       labels_hash[numcols-1] = fmt_decimal((timedelta/3600))
328       interval_type = "Hours After Start (Up to 48)"
329     else #more than 2 days means use dates for labels
330       labels_hash[0] = (Date.parse(starttime.to_s)).to_s
331       labels_hash[(numcols/2)-1] = (Date.parse((starttime + (timedelta/2)).to_s)).to_s
332       labels_hash[numcols-1] = (Date.today).to_s
333       interval_type = "The Date"
334     end
335     
336     # Make sure to return an array for data and hash for labels
337     return total_per_interval, labels_hash, interval_type   
338   end
339   
340   def fmt_decimal(number)
341     sprintf( "%0.1f", number)
342   end
343   
344   def get_borda_points(result)
345     points = Array.new
346     labels = Hash.new
347
348     #Populate points with an sorted array from election.votes hash
349     #biggest to smallest will go from left to right
350     points = result.points.sort do |a, b|
351       b[1] <=> a[1]
352     end.collect {|i| i[1]}
353
354     #make the labels  
355     result.ranked_candidates.each_with_index do |candidate, index|
356       labels[index] = Candidate.find(candidate).name
357     end
358
359     return points, labels
360   end
361
362   #most vote result objects require an array of vote arrays, which this will make
363   def make_preference_tally(election)
364     preference_tally = Array.new
365     @election.voters.each do |voter|
366       next unless voter.voted?
367       preference_tally << voter.vote.rankings.sort.collect \
368         { |ranking| ranking.candidate.id }
369     end
370   return preference_tally
371   end
372 end

Benjamin Mako Hill || Want to submit a patch?