]> jaekl.net Git - oct_sched.git/blob - lib/stats.rb
Add basic reporting on cancellations and annual (scheduled) trip totals.
[oct_sched.git] / lib / stats.rb
1 # frozen_string_literal: true
2
3 require "sqlite3"
4
5 require "database"
6 require "gtfs"
7 require "pry"
8
9 class Stats
10   # Warning:  doesn't account for leap years
11   #                     J   F   M   A   M   J   J   A   S   O   N   D
12   DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
13
14   def initialize
15     @db = Database.new.db
16     @gtfs = Gtfs.new
17   end
18
19   def report(year:)
20     route_totals = {}
21
22     (1..12).each do |month|
23       last_day = DAYS_IN_MONTH[month]
24       last_day += 1 if (month == 2) && (0 == year % 4) # leap year (doesn't account for 2000)
25
26       (1..last_day).each do |day|
27         date_hash = {year: year, month: month, day: day}
28         date_string = "#{year}-#{month.to_s.rjust(2, "0")}-#{day.to_s.rjust(2, "0")}"
29
30         counts = trip_counts(date_hash: date_hash)
31
32         daily_total = 0
33         counts.each do |route, count|
34           route_total = route_totals[route] || 0
35           route_total += count
36           route_totals[route] = route_total
37
38           daily_total += count
39         end
40
41         puts "#{date_string};#{daily_total};#{counts.inspect}"
42       end
43     end
44
45     annual_total = 0
46     route_totals.each do |_route, count|
47       annual_total += count
48     end
49
50     puts "ANNUAL_TOTAL;#{annual_total};#{route_totals.inspect}"
51   end
52
53   def route_origin_stop_ids
54     @route_origin_stop_ids ||= @db.query(
55       "SELECT stop_id FROM stop_times WHERE stop_sequence=1 GROUP BY 1 ORDER BY 1;"
56     ).to_a.flatten
57   end
58
59   # Returns a hash of route_num => trip_count for the given date
60   def trip_counts(date_hash: nil)
61     result = {}
62
63     print "Checking for trips on #{date_hash[:year]}-#{date_hash[:month]}-#{date_hash[:day]}"
64
65     route_origin_stop_ids.each do |stop_id|
66       print "."
67       $stdout.flush
68
69       route_trips = @gtfs.trips(stop_id: stop_id, date_hash: date_hash).map do |k, v|
70         [
71           k.first,
72           v.map do |x|
73             x.first
74           end,
75         ]
76       end.to_h.each do |route, trips|
77         count = result[route] || 0
78         count += trips.count
79         result[route] = count
80       end
81     end
82     puts " done."
83
84     result
85   end
86 end