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

Benjamin Mako Hill || Want to submit a patch?