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

Benjamin Mako Hill || Want to submit a patch?