Upgrade origin-src to google transit feed 1.2.6
[bus.git] / origin-src / kmlwriter.py
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
#!/usr/bin/python
#
# Copyright 2008 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
 
"""A module for writing GTFS feeds out into Google Earth KML format.
 
For usage information run kmlwriter.py --help
 
If no output filename is specified, the output file will be given the same
name as the feed file (with ".kml" appended) and will be placed in the same
directory as the input feed.
 
The resulting KML file has a folder hierarchy which looks like this:
 
    - Stops
      * stop1
      * stop2
    - Routes
      - route1
        - Shapes
          * shape1
          * shape2
        - Patterns
          - pattern1
          - pattern2
        - Trips
          * trip1
          * trip2
    - Shapes
      * shape1
      - Shape Points
        * shape_point1
        * shape_point2
      * shape2
      - Shape Points
        * shape_point1
        * shape_point2
 
where the hyphens represent folders and the asteriks represent placemarks.
 
In a trip, a vehicle visits stops in a certain sequence. Such a sequence of
stops is called a pattern. A pattern is represented by a linestring connecting
the stops. The "Shapes" subfolder of a route folder contains placemarks for
each shape used by a trip in the route. The "Patterns" subfolder contains a
placemark for each unique pattern used by a trip in the route. The "Trips"
subfolder contains a placemark for each trip in the route.
 
Since there can be many trips and trips for the same route are usually similar,
they are not exported unless the --showtrips option is used. There is also
another option --splitroutes that groups the routes by vehicle type resulting
in a folder hierarchy which looks like this at the top level:
 
    - Stops
    - Routes - Bus
    - Routes - Tram
    - Routes - Rail
    - Shapes
"""
 
try:
  import xml.etree.ElementTree as ET  # python 2.5
except ImportError, e:
  import elementtree.ElementTree as ET  # older pythons
import optparse
import os.path
import sys
import transitfeed
from transitfeed import util
 
 
class KMLWriter(object):
  """This class knows how to write out a transit feed as KML.
 
  Sample usage:
    KMLWriter().Write(<transitfeed.Schedule object>, <output filename>)
 
  Attributes:
    show_trips: True if the individual trips should be included in the routes.
    show_trips: True if the individual trips should be placed on ground.
    split_routes: True if the routes should be split by type.
    shape_points: True if individual shape points should be plotted.
  """
 
  def __init__(self):
    """Initialise."""
    self.show_trips = False
    self.split_routes = False
    self.shape_points = False
    self.altitude_per_sec = 0.0
    self.date_filter = None
 
  def _SetIndentation(self, elem, level=0):
    """Indented the ElementTree DOM.
 
    This is the recommended way to cause an ElementTree DOM to be
    prettyprinted on output, as per: http://effbot.org/zone/element-lib.htm
 
    Run this on the root element before outputting the tree.
 
    Args:
      elem: The element to start indenting from, usually the document root.
      level: Current indentation level for recursion.
    """
    i = "\n" + level*"  "
    if len(elem):
      if not elem.text or not elem.text.strip():
        elem.text = i + "  "
      for elem in elem:
        self._SetIndentation(elem, level+1)
      if not elem.tail or not elem.tail.strip():
        elem.tail = i
    else:
      if level and (not elem.tail or not elem.tail.strip()):
        elem.tail = i
 
  def _CreateFolder(self, parent, name, visible=True, description=None):
    """Create a KML Folder element.
 
    Args:
      parent: The parent ElementTree.Element instance.
      name: The folder name as a string.
      visible: Whether the folder is initially visible or not.
      description: A description string or None.
 
    Returns:
      The folder ElementTree.Element instance.
    """
    folder = ET.SubElement(parent, 'Folder')
    name_tag = ET.SubElement(folder, 'name')
    name_tag.text = name
    if description is not None:
      desc_tag = ET.SubElement(folder, 'description')
      desc_tag.text = description
    if not visible:
      visibility = ET.SubElement(folder, 'visibility')
      visibility.text = '0'
    return folder
 
  def _CreateStyleForRoute(self, doc, route):
    """Create a KML Style element for the route.
 
    The style sets the line colour if the route colour is specified. The
    line thickness is set depending on the vehicle type.
 
    Args:
      doc: The KML Document ElementTree.Element instance.
      route: The transitfeed.Route to create the style for.
 
    Returns:
      The id of the style as a string.
    """
    style_id = 'route_%s' % route.route_id
    style = ET.SubElement(doc, 'Style', {'id': style_id})
    linestyle = ET.SubElement(style, 'LineStyle')
    width = ET.SubElement(linestyle, 'width')
    type_to_width = {0: '3',  # Tram
                     1: '3',  # Subway
                     2: '5',  # Rail
                     3: '1'}  # Bus
    width.text = type_to_width.get(route.route_type, '1')
    if route.route_color:
      color = ET.SubElement(linestyle, 'color')
      red = route.route_color[0:2].lower()
      green = route.route_color[2:4].lower()
      blue = route.route_color[4:6].lower()
      color.text = 'ff%s%s%s' % (blue, green, red)
    return style_id
 
  def _CreatePlacemark(self, parent, name, style_id=None, visible=True,
                       description=None):
    """Create a KML Placemark element.
 
    Args:
      parent: The parent ElementTree.Element instance.
      name: The placemark name as a string.
      style_id: If not None, the id of a style to use for the placemark.
      visible: Whether the placemark is initially visible or not.
      description: A description string or None.
 
    Returns:
      The placemark ElementTree.Element instance.
    """
    placemark = ET.SubElement(parent, 'Placemark')
    placemark_name = ET.SubElement(placemark, 'name')
    placemark_name.text = name
    if description is not None:
      desc_tag = ET.SubElement(placemark, 'description')
      desc_tag.text = description
    if style_id is not None:
      styleurl = ET.SubElement(placemark, 'styleUrl')
      styleurl.text = '#%s' % style_id
    if not visible:
      visibility = ET.SubElement(placemark, 'visibility')
      visibility.text = '0'
    return placemark
 
  def _CreateLineString(self, parent, coordinate_list):
    """Create a KML LineString element.
 
    The points of the string are given in coordinate_list. Every element of
    coordinate_list should be one of a tuple (longitude, latitude) or a tuple
    (longitude, latitude, altitude).
 
    Args:
      parent: The parent ElementTree.Element instance.
      coordinate_list: The list of coordinates.
 
    Returns:
      The LineString ElementTree.Element instance or None if coordinate_list is
      empty.
    """
    if not coordinate_list:
      return None
    linestring = ET.SubElement(parent, 'LineString')
    tessellate = ET.SubElement(linestring, 'tessellate')
    tessellate.text = '1'
    if len(coordinate_list[0]) == 3:
      altitude_mode = ET.SubElement(linestring, 'altitudeMode')
      altitude_mode.text = 'absolute'
    coordinates = ET.SubElement(linestring, 'coordinates')
    if len(coordinate_list[0]) == 3:
      coordinate_str_list = ['%f,%f,%f' % t for t in coordinate_list]
    else:
      coordinate_str_list = ['%f,%f' % t for t in coordinate_list]
    coordinates.text = ' '.join(coordinate_str_list)
    return linestring
 
  def _CreateLineStringForShape(self, parent, shape):
    """Create a KML LineString using coordinates from a shape.
 
    Args:
      parent: The parent ElementTree.Element instance.
      shape: The transitfeed.Shape instance.
 
    Returns:
      The LineString ElementTree.Element instance or None if coordinate_list is
      empty.
    """
    coordinate_list = [(longitude, latitude) for
                       (latitude, longitude, distance) in shape.points]
    return self._CreateLineString(parent, coordinate_list)
 
  def _CreateStopsFolder(self, schedule, doc):
    """Create a KML Folder containing placemarks for each stop in the schedule.
 
    If there are no stops in the schedule then no folder is created.
 
    Args:
      schedule: The transitfeed.Schedule instance.
      doc: The KML Document ElementTree.Element instance.
 
    Returns:
      The Folder ElementTree.Element instance or None if there are no stops.
    """
    if not schedule.GetStopList():
      return None
    stop_folder = self._CreateFolder(doc, 'Stops')
    stops = list(schedule.GetStopList())
    stops.sort(key=lambda x: x.stop_name)
    for stop in stops:
      desc_items = []
      if stop.stop_desc:
        desc_items.append(stop.stop_desc)
      if stop.stop_url:
        desc_items.append('Stop info page: <a href="%s">%s</a>' % (
            stop.stop_url, stop.stop_url))
      description = '<br/>'.join(desc_items) or None
      placemark = self._CreatePlacemark(stop_folder, stop.stop_name,
                                        description=description)
      point = ET.SubElement(placemark, 'Point')
      coordinates = ET.SubElement(point, 'coordinates')
      coordinates.text = '%.6f,%.6f' % (stop.stop_lon, stop.stop_lat)
    return stop_folder
 
  def _CreateRoutePatternsFolder(self, parent, route,
                                   style_id=None, visible=True):
    """Create a KML Folder containing placemarks for each pattern in the route.
 
    A pattern is a sequence of stops used by one of the trips in the route.
 
    If there are not patterns for the route then no folder is created and None
    is returned.
 
    Args:
      parent: The parent ElementTree.Element instance.
      route: The transitfeed.Route instance.
      style_id: The id of a style to use if not None.
      visible: Whether the folder is initially visible or not.
 
    Returns:
      The Folder ElementTree.Element instance or None if there are no patterns.
    """
    pattern_id_to_trips = route.GetPatternIdTripDict()
    if not pattern_id_to_trips:
      return None
 
    # sort by number of trips using the pattern
    pattern_trips = pattern_id_to_trips.values()
    pattern_trips.sort(lambda a, b: cmp(len(b), len(a)))
 
    folder = self._CreateFolder(parent, 'Patterns', visible)
    for n, trips in enumerate(pattern_trips):
      trip_ids = [trip.trip_id for trip in trips]
      name = 'Pattern %d (trips: %d)' % (n+1, len(trips))
      description = 'Trips using this pattern (%d in total): %s' % (
          len(trips), ', '.join(trip_ids))
      placemark = self._CreatePlacemark(folder, name, style_id, visible,
                                        description)
      coordinates = [(stop.stop_lon, stop.stop_lat)
                     for stop in trips[0].GetPattern()]
      self._CreateLineString(placemark, coordinates)
    return folder
 
  def _CreateRouteShapesFolder(self, schedule, parent, route,
                               style_id=None, visible=True):
    """Create a KML Folder for the shapes of a route.
 
    The folder contains a placemark for each shape referenced by a trip in the
    route. If there are no such shapes, no folder is created and None is
    returned.
 
    Args:
      schedule: The transitfeed.Schedule instance.
      parent: The parent ElementTree.Element instance.
      route: The transitfeed.Route instance.
      style_id: The id of a style to use if not None.
      visible: Whether the placemark is initially visible or not.
 
    Returns:
      The Folder ElementTree.Element instance or None.
    """
    shape_id_to_trips = {}
    for trip in route.trips:
      if trip.shape_id:
        shape_id_to_trips.setdefault(trip.shape_id, []).append(trip)
    if not shape_id_to_trips:
      return None
 
    # sort by the number of trips using the shape
    shape_id_to_trips_items = shape_id_to_trips.items()
    shape_id_to_trips_items.sort(lambda a, b: cmp(len(b[1]), len(a[1])))
 
    folder = self._CreateFolder(parent, 'Shapes', visible)
    for shape_id, trips in shape_id_to_trips_items:
      trip_ids = [trip.trip_id for trip in trips]
      name = '%s (trips: %d)' % (shape_id, len(trips))
      description = 'Trips using this shape (%d in total): %s' % (
          len(trips), ', '.join(trip_ids))
      placemark = self._CreatePlacemark(folder, name, style_id, visible,
                                        description)
      self._CreateLineStringForShape(placemark, schedule.GetShape(shape_id))
    return folder
 
  def _CreateRouteTripsFolder(self, parent, route, style_id=None, schedule=None):
    """Create a KML Folder containing all the trips in the route.
 
    The folder contains a placemark for each of these trips. If there are no
    trips in the route, no folder is created and None is returned.
 
    Args:
      parent: The parent ElementTree.Element instance.
      route: The transitfeed.Route instance.
      style_id: A style id string for the placemarks or None.
 
    Returns:
      The Folder ElementTree.Element instance or None.
    """
    if not route.trips:
      return None
    trips = list(route.trips)
    trips.sort(key=lambda x: x.trip_id)
    trips_folder = self._CreateFolder(parent, 'Trips', visible=False)
    for trip in trips:
      if (self.date_filter and
          not trip.service_period.IsActiveOn(self.date_filter)):
        continue
 
      if trip.trip_headsign:
        description = 'Headsign: %s' % trip.trip_headsign
      else:
        description = None
 
      coordinate_list = []
      for secs, stoptime, tp in trip.GetTimeInterpolatedStops():
        if self.altitude_per_sec > 0:
          coordinate_list.append((stoptime.stop.stop_lon, stoptime.stop.stop_lat,
                                  (secs - 3600 * 4) * self.altitude_per_sec))
        else:
          coordinate_list.append((stoptime.stop.stop_lon,
                                  stoptime.stop.stop_lat))
      placemark = self._CreatePlacemark(trips_folder,
                                        trip.trip_id,
                                        style_id=style_id,
                                        visible=False,
                                        description=description)
      self._CreateLineString(placemark, coordinate_list)
    return trips_folder
 
  def _CreateRoutesFolder(self, schedule, doc, route_type=None):
    """Create a KML Folder containing routes in a schedule.
 
    The folder contains a subfolder for each route in the schedule of type
    route_type. If route_type is None, then all routes are selected. Each
    subfolder contains a flattened graph placemark, a route shapes placemark
    and, if show_trips is True, a subfolder containing placemarks for each of
    the trips in the route.
 
    If there are no routes in the schedule then no folder is created and None
    is returned.
 
    Args:
      schedule: The transitfeed.Schedule instance.
      doc: The KML Document ElementTree.Element instance.
      route_type: The route type integer or None.
 
    Returns:
      The Folder ElementTree.Element instance or None.
    """
 
    def GetRouteName(route):
      """Return a placemark name for the route.
 
      Args:
        route: The transitfeed.Route instance.
 
      Returns:
        The name as a string.
      """
      name_parts = []
      if route.route_short_name:
        name_parts.append('<b>%s</b>' % route.route_short_name)
      if route.route_long_name:
        name_parts.append(route.route_long_name)
      return ' - '.join(name_parts) or route.route_id
 
    def GetRouteDescription(route):
      """Return a placemark description for the route.
 
      Args:
        route: The transitfeed.Route instance.
 
      Returns:
        The description as a string.
      """
      desc_items = []
      if route.route_desc:
        desc_items.append(route.route_desc)
      if route.route_url:
        desc_items.append('Route info page: <a href="%s">%s</a>' % (
            route.route_url, route.route_url))
      description = '<br/>'.join(desc_items)
      return description or None
 
    routes = [route for route in schedule.GetRouteList()
              if route_type is None or route.route_type == route_type]
    if not routes:
      return None
    routes.sort(key=lambda x: GetRouteName(x))
 
    if route_type is not None:
      route_type_names = {0: 'Tram, Streetcar or Light rail',
                          1: 'Subway or Metro',
                          2: 'Rail',
                          3: 'Bus',
                          4: 'Ferry',
                          5: 'Cable car',
                          6: 'Gondola or suspended cable car',
                          7: 'Funicular'}
      type_name = route_type_names.get(route_type, str(route_type))
      folder_name = 'Routes - %s' %