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

Benjamin Mako Hill || Want to submit a patch?