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

Benjamin Mako Hill || Want to submit a patch?