Merge from Justin
[selectricity-live] / app / controllers / graph_controller.rb
1 require 'date'
2 class GraphController < ApplicationController
3   
4   class GruffGraff
5   
6     def initialize(options)
7       size = "700x400"
8       @graph = options[:graph_type].new(size)
9
10       @graph.theme = { :colors => ['#000000', '#00FFFF', '#FFCC00', '#990033'],
11                        :background_colors => ['#74ce00', '#ffffff'] }
12       @graph.font = File.expand_path('/usr/X11R6/lib/X11/fonts/TTF/Vera.ttf',
13                                    RAILS_ROOT)
14       
15       # fill in the data with the optional data name
16       #Check to see if multiple datasets, if so, fill them all!
17       if options[:data].is_a?(Hash) 
18         options[:data].each_pair do |name, array|
19           @graph.data( name, array)
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     #pref_tally = make_preference_tally(@election)
83     
84     #@borda_result = BordaVote.new(pref_tally).result
85     data, labels = get_borda_points(@election.borda_result)
86     
87     graph = GruffGraff.new( :graph_type => Gruff::Bar,
88                             :data_name => @election.name,
89                             :data => data,
90                             :interval_labels => labels,
91                             :title => "Points Per Candidate",
92                             :y_axis_label => "Points",
93                             :x_axis_label => "Candidate")
94     send_data(*graph.output)
95   end
96   #Acording to Tufte, small, concomparitive, highly labeled data sets usually
97   # belong in tables. The following is a bar graph...but would it be better
98   #as a table?
99   def choices_positions 
100     @election = Election.find(params[:id])
101     pref_tally = make_preference_tally(@election)
102     
103     fulldata, labels = get_positions_info(@election)
104     legend = Hash.new
105     
106     @election.candidates.each_with_index do |candidate, index|
107       legend[candidate.name] = fulldata[index]
108     end
109     
110     graph = GruffGraff.new( :graph_type => Gruff::Bar,
111                             :data => legend,
112                             :interval_labels => labels,
113                             :title => "Times Voted in Each Position",
114                             :y_axis_label => "Number of Times Ranked",
115                             :x_axis_label => "Rank")
116     send_data(*graph.output) 
117   end
118   
119  private 
120  
121   def get_positions_info(election)
122     buckets = Hash.new
123     buckets2= Hash.new
124     rank_labels = Hash.new
125   
126     election.candidates.each do |candidate|
127       buckets[candidate.id] = []
128       buckets2[candidate.id] = []
129     end
130      
131     election.votes.each do |vote|
132       vote.rankings.each do |ranking|
133         buckets[ranking.candidate_id] << ranking.rank
134       end
135     end
136        
137     buckets.each_pair do |id, array|
138       (1..election.candidates.size).each do |i|
139         buckets2[id] << (array.find_all {|rank| rank == i}).size
140       end
141     end
142     
143     election.votes.each do |vote|
144       vote.rankings.size.times do |i|
145         rank_labels[i] = (i+1).to_s
146       end
147     end
148     
149     return buckets2.values, rank_labels
150     
151   end
152    
153   # generate the data and labels for each graph
154   def get_votes_per_day_data(election)
155     voter_days = Array.new
156     unique_days = Array.new
157     total_per_day = Array.new
158     election_days = Hash.new
159     
160     #turn election startdate into date object, and create the range of election
161     startdate = Date.parse(election.startdate.to_s)
162     election_range = startdate..Date.today
163     
164     # create a hash with all the dates of the election in String format
165     # referenced by their order in the election
166     election_range.each_with_index do |day, index|
167       election_days[index] = day.to_s
168     end
169     
170     # Now I need to create an array with all the times votes were made
171     election.votes.each do |vote|
172         voter_days << Date.parse(vote.time.to_s)
173     end
174     voter_days.sort!
175     
176     # Now I need to count how many times each each date appears in voter_days,
177     # and put that number into a votes_per_day array, the 'data' for the graph    
178     #Create an array of unique days from voter_days
179     voter_days.each do |day|
180       unless unique_days.any? {|date| date.eql?(day)}
181         unique_days << day
182       end
183     end
184     unique_days.sort!
185     
186     #find all dates where those days = date at current index, put size of returned
187     #array into total_per_day
188     unique_days.each_with_index do |date, index|
189       total_per_day << (voter_days.select {|day| day.eql?(date)}).size
190     end    
191
192     # return the data and the labels
193     return total_per_day, election_days
194    
195   end
196   
197   def get_votes_per_interval_data(election)
198     labels_hash = Hash.new
199     buckets = Hash.new
200     total_per_interval = Array.new
201     interval_type = ""
202     
203     starttime = election.startdate
204     timedelta = Time.now - starttime
205     numcols = 10
206     interval_length = timedelta/numcols
207     
208     # Make a hash, buckets, indexed by time intervals and containing empty arrays
209     # The time object must come first in addition! 
210     # i would start at 0, i+1 goes from 1 up till numcols
211     numcols.times {|i| buckets[starttime + ((i+1)*interval_length)] = []}
212      
213     # Put votes into bucket according to the time interval to which they belong,
214     # referenced by their key
215     # Will build a graph over time, as each successive interval will have more
216     # vote objects  
217     election.votes.each do |vote|
218       buckets.keys.sort.each do |inter|
219         if vote.time < inter
220           buckets[inter] << vote
221         end
222       end
223     end
224   
225     total_per_interval = buckets.keys.sort.collect {|key| buckets[key].size}
226     
227     # Create the hash for the labels. Each graph has ten columns, and three
228     # will be labeled
229     if timedelta < 2.hours #under two hours use minutes for labels
230       labels_hash[0] = starttime.min.to_s
231       labels_hash[(numcols/2)-1] = (starttime + (timedelta/2)).min.to_s
232       labels_hash[numcols-1] = Time.now.min.to_s
233       interval_type = "Minute of the Hour"
234     elsif timedelta < 2.days #more than 2 hours means use hours for labels
235       labels_hash[0] = starttime.hour.to_s
236       labels_hash[(numcols/2)-1] = (starttime + (timedelta/2)).hour.to_s
237       labels_hash[numcols-1] = Time.now.hour.to_s
238       interval_type = "Hour of the Day on 24 hour scale"
239     else #more than 2 days means use dates for labels
240       labels_hash[0] = (Date.parse(starttime.to_s)).to_s
241       labels_hash[(numcols/2)-1] = (Date.parse((starttime + (timedelta/2)).to_s)).to_s
242       labels_hash[numcols-1] = (Date.today).to_s
243       interval_type = "The Date"
244     end
245     
246     # Make sure to return an array for data and hash for labels
247     return total_per_interval, labels_hash, interval_type   
248   end
249   
250   def get_borda_points(result)
251     points = Array.new
252     labels = Hash.new
253
254     #Populate points with an sorted array from election.votes hash
255     #biggest to smallest will go from left to right
256     points = result.election.votes.sort do |a, b|
257       b[1] <=> a[1]
258     end.collect {|i| i[1]}
259
260     #make the labels  
261     result.ranked_candidates.each_with_index do |candidate, index|
262       labels[index] = Candidate.find(candidate).name
263     end
264
265     return points, labels
266   end
267
268   #most vote result objects require an array of vote arrays, which this will make
269   def make_preference_tally(election)
270     preference_tally = Array.new
271     @election.voters.each do |voter|
272       next unless voter.voted?
273       preference_tally << voter.vote.rankings.sort.collect \
274         { |ranking| ranking.candidate.id }
275     end
276   return preference_tally
277   end
278
279 end

Benjamin Mako Hill || Want to submit a patch?