Custom embeddable code works for png's except for top_bar
[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      
193     pie = GruffGraff.new( :graph_type => Gruff::Pie,
194                            :title => "Percentage of First Place Votes",
195                            :data => data)
196     send_data(*pie.output)
197                            
198   end
199   
200  private 
201   def get_positions_info(election)
202     buckets = Hash.new
203     buckets2= Hash.new
204     rank_labels = Hash.new
205     
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|
210         
211          unless buckets.has_key?(ranking.candidate_id)
212            buckets[ranking.candidate_id] = []
213          end
214         buckets[ranking.candidate_id] << ranking.rank
215         
216       end
217     end
218     
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
224       end
225     end
226     
227     #sort by amount of 1st place votes
228     sorted_data = buckets2.values.sort {|a,b| b[0] <=> a[0]}
229     
230     election.votes.each do |vote|
231       vote.rankings.size.times do |i|
232         rank_labels[i] = (i+1).to_s
233       end
234     end
235     
236     return sorted_data, rank_labels   
237   end
238    
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
245     
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
249     
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
254     end
255     
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)
260     end
261     voter_days.sort!
262     
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)}
268         unique_days << day
269       end
270     end
271     unique_days.sort!
272     
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
277     end    
278
279     # return the data and the labels
280     return total_per_day, election_days
281    
282   end
283   
284   def get_votes_per_interval_data(election)
285     labels_hash = Hash.new
286     buckets = Hash.new
287     total_per_interval = Array.new
288     interval_type = ""
289     
290     starttime = election.startdate
291     timedelta = Time.now - starttime
292     numcols = 10
293     interval_length = timedelta/numcols
294     
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)] = []}
299      
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
303     # vote objects  
304     election.votes.each do |vote|
305       next unless vote.time
306       buckets.keys.sort.each do |inter|
307         if vote.time < inter
308           buckets[inter] << vote
309         end
310       end
311     end
312   
313     total_per_interval = buckets.keys.sort.collect {|key| buckets[key].size}
314     
315     # Create the hash for the labels. Each graph has ten columns, and three
316     # will be labeled
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"
332     end
333     
334     # Make sure to return an array for data and hash for labels
335     return total_per_interval, labels_hash, interval_type   
336   end
337   
338   def fmt_decimal(number)
339     sprintf( "%0.1f", number)
340   end
341   
342   def get_borda_points(result)
343     points = Array.new
344     labels = Hash.new
345
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|
349       b[1] <=> a[1]
350     end.collect {|i| i[1]}
351
352     #make the labels  
353     result.ranked_candidates.each_with_index do |candidate, index|
354       labels[index] = Candidate.find(candidate).name
355     end
356
357     return points, labels
358   end
359
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 }
367     end
368   return preference_tally
369   end
370 end

Benjamin Mako Hill || Want to submit a patch?