Merge from head
[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     graph = GruffGraff.new( :graph_type => Gruff::Bar,
112                             :data_name => @election.name,
113                             :data => data,
114                             :interval_labels => labels,
115                             :title => "Points Per Candidate",
116                             :marker_color => '#999999',
117                             :y_axis_label => "Points",
118                             :x_axis_label => "Candidate")
119     send_data(*graph.output)
120   end
121   #Acording to Tufte, small, concomparitive, highly labeled data sets usually
122   #belong in tables. The following is a bar graph...but would it be better
123   #as a table?
124   def choices_positions
125     @election = Election.find(params[:id])
126     legend = Hash.new   
127     alldata, labels = get_positions_info(@election)    
128     @election.results unless @election.condorcet_result || @election.ssd_result
129     ranked_candidates = @election.condorcet_result.ranked_candidates.flatten
130     
131     names = Hash.new
132     candidates = @election.candidates.sort.collect {|candidate| candidate.id}
133     candidates.each do |candidate|
134       names[candidate]= (Candidate.find(candidate)).name
135     end
136     
137     ranked_candidates.each_with_index \
138     {|candidate, index| legend[names[candidate]] = alldata[index]}
139     
140     graph = GruffGraff.new( :graph_type => Gruff::Bar,
141                             :data => legend,
142                             :interval_labels => labels,
143                             :title => "Times Voted in Each Position",
144                             :y_axis_label => "Number of Times Ranked",
145                             :x_axis_label => "Rank")
146     send_data(*graph.output) 
147   end
148   
149   def plurality_pie
150     @election = Election.find(params[:id])
151     @election.results unless @election.plurality_result || @election.approval_result
152     votes = @election.votes.size
153     data = Hash.new
154     names = @election.names_by_id
155     
156     @election.plurality_result.points.each do |candidate, votes|
157       data[names[candidate]] = votes
158     end
159      
160     pie = GruffGraff.new( :graph_type => Gruff::Pie,
161                            :title => "Percentage of First Place Votes",
162                            :data => data)
163     send_data(*pie.output)
164                            
165   end
166   
167  private 
168   def get_positions_info(election)
169     buckets = Hash.new
170     buckets2= Hash.new
171     rank_labels = Hash.new
172     
173     #attach the ranking to the candidate's array to which is belongs
174     #creating a key if necessary
175     election.votes.each do |vote|
176       vote.rankings.each do |ranking|
177         
178          unless buckets.has_key?(ranking.candidate_id)
179            buckets[ranking.candidate_id] = []
180          end
181         buckets[ranking.candidate_id] << ranking.rank
182         
183       end
184     end
185     
186     #count how many times each candidate has been ranked at a certain level
187     buckets.each_pair do |id, array|
188       (1..election.candidates.size).each do |i|
189         buckets2[id] = [] unless buckets2.has_key?(id)
190         buckets2[id] << (array.find_all {|rank| rank == i}).size
191       end
192     end
193     
194     #sort by amount of 1st place votes
195     sorted_data = buckets2.values.sort {|a,b| b[0] <=> a[0]}
196     
197     election.votes.each do |vote|
198       vote.rankings.size.times do |i|
199         rank_labels[i] = (i+1).to_s
200       end
201     end
202     
203     return sorted_data, rank_labels   
204   end
205    
206   # generate the data and labels for each graph
207   def get_votes_per_day_data(election)
208     voter_days = Array.new
209     unique_days = Array.new
210     total_per_day = Array.new
211     election_days = Hash.new
212     
213     #turn election startdate into date object, and create the range of election
214     startdate = Date.parse(election.startdate.to_s)
215     election_range = startdate..Date.today
216     
217     # create a hash with all the dates of the election in String format
218     # referenced by their order in the election
219     election_range.each_with_index do |day, index|
220       election_days[index] = day.to_s
221     end
222     
223     # Now I need to create an array with all the times votes were made
224     election.votes.each do |vote|
225       next unless vote.time
226       voter_days << Date.parse(vote.time.to_s)
227     end
228     voter_days.sort!
229     
230     # Now I need to count how many times each each date appears in voter_days,
231     # and put that number into a votes_per_day array, the 'data' for the graph    
232     #Create an array of unique days from voter_days
233     voter_days.each do |day|
234       unless unique_days.any? {|date| date.eql?(day)}
235         unique_days << day
236       end
237     end
238     unique_days.sort!
239     
240     #find all dates where those days = date at current index, put size of returned
241     #array into total_per_day
242     unique_days.each_with_index do |date, index|
243       total_per_day << (voter_days.select {|day| day.eql?(date)}).size
244     end    
245
246     # return the data and the labels
247     return total_per_day, election_days
248    
249   end
250   
251   def get_votes_per_interval_data(election)
252     labels_hash = Hash.new
253     buckets = Hash.new
254     total_per_interval = Array.new
255     interval_type = ""
256     
257     starttime = election.startdate
258     timedelta = Time.now - starttime
259     numcols = 10
260     interval_length = timedelta/numcols
261     
262     # Make a hash, buckets, indexed by time intervals and containing empty arrays
263     # The time object must come first in addition! 
264     # i would start at 0, i+1 goes from 1 up till numcols
265     numcols.times {|i| buckets[starttime + ((i+1)*interval_length)] = []}
266      
267     # Put votes into bucket according to the time interval to which they belong,
268     # referenced by their key
269     # Will build a graph over time, as each successive interval will have more
270     # vote objects  
271     election.votes.each do |vote|
272       next unless vote.time
273       buckets.keys.sort.each do |inter|
274         if vote.time < inter
275           buckets[inter] << vote
276         end
277       end
278     end
279   
280     total_per_interval = buckets.keys.sort.collect {|key| buckets[key].size}
281     
282     # Create the hash for the labels. Each graph has ten columns, and three
283     # will be labeled
284     if timedelta < 2.hours #under two hours use minutes for labels
285       labels_hash[0] = "Start"
286       labels_hash[(numcols/2)-1] = fmt_decimal((timedelta/120)) #halfway
287       labels_hash[numcols-1] = fmt_decimal((timedelta/60))
288       interval_type = "Minutes After Start"
289     elsif timedelta < 2.days #more than 2 hours means use hours for labels
290       labels_hash[0] = "Start"
291       labels_hash[(numcols/2)-1] = fmt_decimal((timedelta/7200))
292       labels_hash[numcols-1] = fmt_decimal((timedelta/3600))
293       interval_type = "Hours After Start (Up to 48)"
294     else #more than 2 days means use dates for labels
295       labels_hash[0] = (Date.parse(starttime.to_s)).to_s
296       labels_hash[(numcols/2)-1] = (Date.parse((starttime + (timedelta/2)).to_s)).to_s
297       labels_hash[numcols-1] = (Date.today).to_s
298       interval_type = "The Date"
299     end
300     
301     # Make sure to return an array for data and hash for labels
302     return total_per_interval, labels_hash, interval_type   
303   end
304   
305   def fmt_decimal(number)
306     sprintf( "%0.1f", number)
307   end
308   
309   def get_borda_points(result)
310     points = Array.new
311     labels = Hash.new
312
313     #Populate points with an sorted array from election.votes hash
314     #biggest to smallest will go from left to right
315     points = result.points.sort do |a, b|
316       b[1] <=> a[1]
317     end.collect {|i| i[1]}
318
319     #make the labels  
320     result.ranked_candidates.each_with_index do |candidate, index|
321       labels[index] = Candidate.find(candidate).name
322     end
323
324     return points, labels
325   end
326
327   #most vote result objects require an array of vote arrays, which this will make
328   def make_preference_tally(election)
329     preference_tally = Array.new
330     @election.voters.each do |voter|
331       next unless voter.voted?
332       preference_tally << voter.vote.rankings.sort.collect \
333         { |ranking| ranking.candidate.id }
334     end
335   return preference_tally
336   end
337 end

Benjamin Mako Hill || Want to submit a patch?