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

Benjamin Mako Hill || Want to submit a patch?