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

Benjamin Mako Hill || Want to submit a patch?