summaryrefslogtreecommitdiffstats
path: root/sbb_distance.py
blob: 04d0afb273ed77407c3eb8635b7f7ffb87dcb160 (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
#!/usr/bin/python3
# vim: set fileencoding=utf-8 ts=4 sts=4 sw=4 tw=80 expandtab :

# Copyright (C) 2012 Florian Bruhin <me@the-compiler.org>

# sbb_distance is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# sbb_distance is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with sbb_distance.  If not, see <http://www.gnu.org/licenses/>.

import pytransportapi
import coord
import time
import argparse

def init_stops(stops):
    client = pytransportapi.TransportClient()
    stoplist = []
    for stop in stops:
        loc = client.location(stop)
        lat = loc[0].coordinates.lat
        lon = loc[0].coordinates.lon
        stoplist.append((stop, lat, lon))
        time.sleep(0.2)
    # form pairs
    stoplist = [(stoplist[i:i+2]) for i in range(len(stoplist) - 1)]
    return stoplist

def get_distances(stoplist):
    distancelist = []
    for pair in stoplist:
        name1 = pair[0][0]
        name2 = pair[1][0]
        coord1 = coord.Coord(pair[0][1], pair[0][2])
        coord2 = coord.Coord(pair[1][1], pair[1][2])
        distance = coord.distance(coord1, coord2)
        distancelist.append((name1, name2, distance))
    return distancelist

def print_distances(distancelist):
    tot = 0
    for distance in distancelist:
        print("{:30.30} -> {:30.30} {:.2f} km".format(distance[0], distance[1],
                                                      distance[2] / 1000))
        tot += distance[2]
    print("=" * 58)
    print("{}Total: {:.2f} km".format(" " * 43, tot / 1000))

def parse_args():
    parser = argparse.ArgumentParser(
        description='Calculate distances between train stations')
    parser.add_argument('stations', metavar='station', nargs='+',
                        help='a name of a station')
    args = parser.parse_args()
    return(args.stations)

def main():
    stops = parse_args()
    stoplist = init_stops(stops)
    distancelist = get_distances(stoplist)
    print_distances(distancelist)

if __name__ == '__main__':
    main()