summaryrefslogtreecommitdiff
path: root/blatube.rb
blob: 1930db5a5c60b579e2b31bc475fb931681681e98 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
require 'optparse'
require 'open-uri'
require 'nokogiri'
require 'yaml'
require 'json'

@output = []
@line = nil
@from_station = nil
@to_station = nil
@weight = 'peak_time'
@change_time = 5
@colour = false
debug = false
help = false
ops = nil
VERSION = 'v1.3.0'
INFINITY = 1 << 64
WEIGHTS = ['distance','peak_time','off_peak_time','unimpeded_time']

STDIN.gets.split(' ').each{|arg| ARGV << arg} if ARGV == []
args = ARGV.dup

options = OptionParser.new do |opts|
  opts.banner = "Usage: #{File.basename($0)} -h"
  opts.on( '-s', '--status [LINE]', 'Get the current status of a tube line.' ) {|l| @line = l || 'SUMMARY' }
  opts.on( '-f', '--from-station STATION', 'Find route from this station.' ) {|f| @from_station = f }
  opts.on( '-t', '--to-station STATION', 'Find route to this station.' ) {|t| @to_station = t }
  opts.on( '-w', '--weight WEIGHT', 'Shortest route using either distance, peak_time, off_peak_time or unimpeded_time.' ) {|w| @weight = WEIGHTS.include?(w) ? w : 'peak_time' }
  opts.on( '-c', '--change-time TIME', 'Your expected average change time in minutes.' ) {|c| @change_time = c.to_f.round(2) }
  opts.on( '-C', '--colour', 'Enable line colours in the output.' ) { @colour = true }
  opts.on( '-d', '--debug', 'Display debug info.' ) { debug = true }
  opts.on( '-v', '--version', 'blatube version number.' ) { puts VERSION; exit }
  opts.on( '-h', '--help', 'Display this screen.' ) { help = true; ops = opts }
end;options.parse!

@output << "args: #{args.inspect}" if debug
if args == []
  @output << "Usage: #{File.basename($0)} -h"
  puts @output.join ' '
  exit -1
end

class Array
  def pairs
    pairs = []
    self.each_with_index do |element, index|
      pairs << [element,self[index+1]]
    end
    pairs.pop
    pairs
  end
end

#TODO: add via_station
def calculate_shortest_route
  return unless interpret_user_input
  @shortest_route = []
  add_terminals
  calculate_routes
  traverse_route @to_station.upcase
  build_route_output
end

def interpret_user_input
  stations = @graph.keys.map {|station| station.split('_')[0]}.uniq.sort
  found_from_station, @from_station = interpret stations, @from_station
  found_to_station, @to_station = interpret stations, @to_station
  return found_from_station && found_to_station
end

def interpret options, input
  found_station = false
  if options.include?(input.upcase)
    found_input = true
  elsif (most_likely = options.map {|option| option.match("^#{input.upcase}.*") ? option : nil}.compact) != []
    if most_likely.size == 1
      input = most_likely.first
      found_input = true
    else
      @output << "Did you mean: #{most_likely.map {|option| option.split(' ').map {|word| word.capitalize}.join(' ')}.join(', ')}?"
    end
  elsif (less_likely = options.map {|option| option.match(".*#{input.upcase}.*") ? option : nil}.compact) != []
    if less_likely.size == 1
      input = less_likely.first
      found_input = true
    else
      @output << "Did you mean: #{less_likely.map {|option| option.split(' ').map {|word| word.capitalize}.join(' ')}.join(', ')}?"
    end
  else
    @output << "Could not find a match for '#{input}'."
  end
  return found_input, input
end

def add_terminals
  @graph.find_all {|station, data| station.match /^#{@to_station.upcase}_|^#{@from_station.upcase}_/}.each do |station, data|
    if station.match @from_station.upcase
      @graph[station][@from_station.upcase] = {'line' => station.split('_')[1], 'direction' => nil, 'distance' => 0, 'unimpeded_time' => 0, 'peak_time' => 0, 'off_peak_time' => 0}
      @graph[@from_station.upcase] ||= {}
      @graph[@from_station.upcase][station] = {'line' => station.split('_')[1], 'direction' => nil, 'distance' => 0, 'unimpeded_time' => 0, 'peak_time' => 0, 'off_peak_time' => 0}
    elsif station.match @to_station.upcase
      @graph[station][@to_station.upcase] = {'line' => station.split('_')[1], 'direction' => nil, 'distance' => 0, 'unimpeded_time' => 0, 'peak_time' => 0, 'off_peak_time' => 0}
      @graph[@to_station.upcase] ||= {}
      @graph[@to_station.upcase][station] = {'line' => station.split('_')[1], 'direction' => nil, 'distance' => 0, 'unimpeded_time' => 0, 'peak_time' => 0, 'off_peak_time' => 0}
    end
  end
end

def calculate_routes
  add_change_time unless @weight == 'distance'
  run_algorithm @graph, @graph.keys, @from_station.upcase
end

#TODO: changes on the same line (eg. 'CAMDEN TOWN')
def add_change_time
  @graph.each do |from_station,to_stations|
    next unless current_line = from_station.split('_')[1]
    to_stations.each do |to_station,data|
      data[@weight] += @change_time unless data['line'] == current_line
    end
  end
end

def run_algorithm graph, nodes, start_node
  @distances = Hash.new INFINITY
  @routes = Hash.new -1
  @distances[start_node] = 0
  nodes_size = nodes.size
  while nodes_size > 0
    current_node = nodes.first
    nodes.each {|node| current_node = node if @distances[node] < @distances[current_node]}
    break if @distances[current_node] == INFINITY
    nodes.delete current_node
    nodes_size -= 1
    graph[current_node].keys.each do |next_node|
      new_distance = @distances[current_node] + graph[current_node][next_node][@weight]
      if new_distance < @distances[next_node]
        @distances[next_node] = new_distance
        @routes[next_node] = current_node
      end
    end
  end
  @distances.delete_if {|node, distance| distance == INFINITY}
end

def traverse_route to_station
  if @routes[to_station] != -1
    traverse_route @routes[to_station]
  end
  @shortest_route << to_station
end

#TODO: a nicer way of doing this
def build_route_output
  line_colours = @colour ? YAML::load(File.open('line_colours.yaml')) : Hash.new('')
  verbose_route = ''
  pairs = @shortest_route[1..-2].pairs
  from,to = pairs.first
  current_line = @graph[from][to]['line']
  verbose_route << "#{line_colours[current_line]}#{from.split('_')[0]} - #{current_line} (#{@graph[from][to]['direction']})"
  pairs[1..-2].each do |from,to|
    next if (new_line = @graph[from][to]['line']) == current_line || @graph[from][to]['direction'] == nil
    current_line = new_line
    from_s = from.split('_')[0]
    from_1 = from_s[0..(from_s.length/2.0 - 1)]
    from_2 = from_s[(from_s.length/2.0)..-1]
    verbose_route << " - #{from_1}#{line_colours['reset_colour']}#{line_colours[new_line]}#{from_2} - #{new_line} (#{@graph[from][to]['direction']})"
  end
  from,to = pairs.last
  new_line = @graph[from][to]['line']
  from_s = from.split('_')[0]
  from_1 = from_s[0..(from_s.length/2.0 - 1)]
  from_2 = from_s[(from_s.length/2.0)..-1]
  verbose_route << " - #{from_1}#{line_colours['reset_colour']}#{line_colours[new_line]}#{from_2} - #{new_line} (#{@graph[from][to]['direction']})" unless new_line == current_line
  verbose_route << " - #{to.split('_')[0]}#{line_colours['reset_colour']}"
  @output << verbose_route
  if @weight == 'distance'
    @output << "Distance: #{@distances[@to_station.upcase].round(2)} km"
  else
    minutes = @distances[@to_station.upcase].round(2)
    seconds = (minutes - minutes.to_i) * 60
    @output << "Travel Time: #{minutes.to_i}:#{seconds.round}"
  end
end

def get_line_status
  xml = Nokogiri::HTML(open('http://cloud.tfl.gov.uk/TrackerNet/LineStatus')).remove_namespaces!
  sorted_lines = xml.xpath('//linestatus').sort_by {|xml| xml.xpath('.//line/@name').text}
  found_line, line = interpret sorted_lines.map{|xml| xml.xpath('.//line/@name').text.upcase} << 'SUMMARY', @line.upcase
  return unless found_line
  if @line == 'SUMMARY'
    line_summary = ''
    sorted_lines.each {|xml| line_summary << "#{xml.xpath('.//line/@name').text}: #{xml.xpath('./@statusdetails').text} " unless xml.xpath('./@statusdetails').text == ''}
    @output << (line_summary == '' ? 'Good Serice on all lines.' : "#{line_summary}Good Service on all other lines.")
  else
    l_s_xml = sorted_lines.find {|xml| xml.xpath('.//line/@name').text.upcase.match line}
    @output << ("#{l_s_xml.xpath('.//line/@name').text}: #{l_s_xml.xpath('.//status/@description').text}. #{l_s_xml.xpath('./@statusdetails').text}")
  end
end

#TODO: store graph as yaml in a way that works with add_change_time
begin
  if help
    ops.to_s.split(/\n\s*|\s{2,}/).each{|opt| @output << opt}
  elsif @line
    get_line_status
  elsif @from_station && @to_station
    #@graph = YAML::load(File.open('graph.yaml'))
    @graph = JSON.parse(File.open('graph.json').read)
    calculate_shortest_route
  elsif @from_station || @to_station
    @output << 'Please specify the station you are travelling from (-f) and the station you are travelling to (-t).'
  elsif ARGV.size == 2
    #@graph = YAML::load(File.open('graph.yaml'))
    @graph = JSON.parse(File.open('graph.json').read)
    @from_station = ARGV[0]
    @to_station = ARGV[1]
    calculate_shortest_route
  elsif ARGV.size == 1
    @line = ARGV[0]
    get_line_status
  else
    get_line_status
  end
rescue StandardError => e
  @output << e.message
  puts e.message
  puts e.backtrace
ensure
  puts @output.join ' '
end