This repository has been archived by the owner on Jul 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
models.py
1520 lines (1348 loc) · 58.4 KB
/
models.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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from collections import defaultdict
import csv
import logging
import re
import os
from django.contrib.gis.gdal import DataSource
from django.db import models
from django.utils import timezone
from django_extensions.db.fields.json import JSONField
from mtta.utils import haversine
from multigtfs.models import Feed
logger = logging.getLogger(__name__)
def _mockable_open(path, mode=None):
return open(path, mode)
def _force_to_file(obj):
'''Force to a file-like object
Strings are treated like file paths
None are returned
Other objects should already have a 'read' attribute.
'''
if isinstance(obj, basestring):
name = obj
elif hasattr(obj, 'name'):
name = obj.name
elif obj is None:
return None
else:
name = '<stream>'
if hasattr(obj, 'read'):
filelike = obj
else:
filelike = _mockable_open(obj, 'rb')
if not hasattr(filelike, 'name'):
filelike.name = name
return filelike
class SignUp(models.Model):
name = models.CharField(max_length=255)
created = models.DateTimeField(auto_now_add=True)
feeds = models.ManyToManyField(Feed, through='SignupExport')
_unset_name = '<unset>'
_data_file_names = (
('lines', 'line'),
('patterns', 'pattern'),
('stops', 'stop'),
('stopsbyline',),
('stopsbypattern',),
)
_names_file = 'NewFieldNames.txt'
_stop_trips_start = 'Stop Trips'
_transfers_file = 'transfers.txt'
def import_folder(self, folder):
'''Import data from an MTTA signup that's been extracted to disk'''
data_files = defaultdict(dict)
stop_trips = []
transfers = None
for path, dirs, files in os.walk(folder):
data_name = None
for f in files:
full_path = os.path.abspath(os.path.join(path, f))
full_name = f.lower()
name, ext = os.path.splitext(full_name)
ext = ext.replace('.', '')
for nameset in self._data_file_names:
if name in nameset:
data_name = nameset[0]
data_files[data_name][ext] = full_path
if full_name == self._transfers_file:
transfers = full_path
if ext == 'txt':
with open(full_path, 'r') as candidate:
first_bits = candidate.read(
len(self._stop_trips_start))
if (first_bits == self._stop_trips_start):
stop_trips.append(full_path)
if data_name and self._names_file in files:
full_path = os.path.abspath(
os.path.join(path, self._names_file))
data_files[data_name][self._names_file] = full_path
for nameset in self._data_file_names:
key = nameset[0]
if key not in data_files.keys():
raise Exception('No %s found in path %s' % (key, folder))
if not stop_trips:
raise Exception('No schedules found in path %s' % folder)
self._import(data_files, stop_trips, transfers)
def _import(self, data_files, stop_trips, transfers=None):
'''Import a set of ESRI Shapfiles and Stop Trip schedules'''
# Get the important parts, so we'll raise a KeyError early
lines_dbf = data_files['lines']['dbf']
lines_names = data_files['lines'].get(self._names_file)
patterns_dbf = data_files['patterns']['dbf']
patterns_shp = data_files['patterns']['shp']
patterns_shx = data_files['patterns'].get('shx')
stops_dbf = data_files['stops']['dbf']
stops_names = data_files['stops'].get(self._names_file)
stopsbyline_dbf = data_files['stopsbyline']['dbf']
stopsbyline_names = data_files['stopsbyline'].get(self._names_file)
stopsbypattern_dbf = data_files['stopsbypattern']['dbf']
stopsbypattern_names = data_files['stopsbypattern'].get(
self._names_file)
# Run the model-specific imports
if not self.service_set.exists():
Service.create_from_defaults(self)
Line.import_dbf(self, lines_dbf, lines_names)
Pattern.import_shp(
self, dbf=patterns_dbf, shp=patterns_shp, shx=patterns_shx)
Stop.import_dbf(self, stops_dbf, stops_names)
StopByLine.import_dbf(self, stopsbyline_dbf, stopsbyline_names)
StopByPattern.import_dbf(
self, stopsbypattern_dbf, stopsbypattern_names)
for schedule in stop_trips:
TripDay.import_schedule(self, schedule)
if transfers:
Transfer.import_transfers(self, transfers)
def copy_to_feed(self):
feed = Feed.objects.create(name=self.name)
signup_export = SignupExport.objects.create(
signup=self, feed=feed, started=feed.created)
agency = AgencyInfo.objects.get(pk=1)
agency.copy_to_feed(feed)
feedinfo = FeedInfo.objects.get(pk=1)
feedinfo.copy_to_feed(feed)
for line in self.line_set.all():
logger.info('Exporting data for line %s...' % line)
line.copy_to_feed(feed)
if self.transfer_set.exists():
logger.info(
'Exporting %d transfers...' % self.transfer_set.count())
for transfer in self.transfer_set.all():
transfer.copy_to_feed(feed)
signup_export.finished = timezone.now()
signup_export.save()
return feed
def __unicode__(self):
return "%s-%s" % (self.id, self.name or '(No Name)')
class SignupExport(models.Model):
signup = models.ForeignKey(SignUp)
feed = models.ForeignKey(Feed)
started = models.DateTimeField()
finished = models.DateTimeField(null=True, blank=True)
def __unicode__(self):
return "%s to %s" % (self.signup, self.feed)
class ShapeAttribute(models.Model):
signup = models.ForeignKey(SignUp)
name = models.CharField(max_length=20)
attributes = JSONField(default=[])
def __unicode__(self):
return "%s-%s" % (self.signup.id, self.name)
class AgencyInfo(models.Model):
'''MTTA information used by GTFS feed'''
name = models.CharField(max_length=20)
url = models.URLField()
timezone = models.CharField(max_length=20)
lang = models.CharField(max_length=2)
phone = models.CharField(max_length=20)
fare_url = models.URLField()
def __unicode__(self):
return self.name
class Meta:
verbose_name_plural = 'agency info'
def copy_to_feed(self, feed):
feed.agency_set.get_or_create(
name=self.name, url=self.url, timezone=self.timezone,
lang=self.lang, phone=self.phone, fare_url=self.fare_url)
class FeedInfo(models.Model):
'''Tulsa Web Devs information used by GTFS feed'''
name = models.CharField(max_length=20)
url = models.URLField()
lang = models.CharField(max_length=2)
version = models.CharField(max_length=20, null=True, blank=True)
def __unicode__(self):
return self.name
class Meta:
verbose_name_plural = 'feed info'
def copy_to_feed(self, feed):
feed.feedinfo_set.get_or_create(
publisher_name=self.name, publisher_url=self.url, lang=self.lang)
class Fare(models.Model):
name = models.CharField(max_length=20)
cost = models.DecimalField(
max_digits=5, decimal_places=2,
help_text='Cost for ride in dollars')
line_name_ipattern = models.CharField(
max_length=20, blank=True,
help_text='Case-insenstive string to look for in line name')
def __unicode__(self):
return self.name
def copy_to_feed(self, feed):
gtfs_fare, created = feed.fare_set.get_or_create(
fare_id=self.name, defaults=dict(
price=self.cost, currency_type='USD',
payment_method=0, transfers=None,
transfer_duration=2 * 60 * 60))
return gtfs_fare
class DbfBase(models.Model):
'''Base class for models from .DBF data'''
attributes = JSONField(default=[])
class Meta:
abstract = True
@classmethod
def read_dbf(cls, signup, dbf_file, names_file):
'''Read and summarize data from a DBF file
Kwargs:
signup: The sign-up to associate this item with
dbf_file: The DBF file
names_file: The 'NewFieldNames.txt' file
Returns: tuple of:
fields - List of dictionaries describing the DBF fields, stored in
ShapeAttribute as well
rows - List of dictionaries for each DBF row, with only the
important values (either used in the model fields, or value is
different from 50% of the other values for that field)
Uses the class variable _dbf_mapping to decide if a
low-information variable should be included.
'''
# Get the field names we're looking to store in the database
assert hasattr(cls, '_dbf_mapping')
used_names = dict([(a, 0) for a, b in cls._dbf_mapping])
# Parse the names file for long names
if hasattr(names_file, 'seek'):
names_file.seek(0)
names_content = names_file.read()
long_name_pairs = re.findall('(\w+) for (\w+)', names_content)
long_names = dict(
[(k.upper(), v.upper()) for (k, v) in long_name_pairs])
# Load the data
ds = DataSource(dbf_file, encoding='latin-1')
layer = ds[0]
# Read the field info, count value frequencies
field_names = layer.fields
fields = []
for index, name in enumerate(field_names):
# Long names come from the names file
long_name = long_names.get(name.upper())
if not long_name and name.upper().startswith('TPFIELD'):
# Line has both line directions in same table
long_name = long_names.get(name.upper()[:-1])
if long_name:
long_name += name[-1]
# Find the value variance
value_counts = defaultdict(int)
for val in layer.get_fields(name):
value_counts[val] += 1
# Find the top values
values_by_count = [(c, v) for v, c in value_counts.items()]
values_by_count.sort(reverse=True)
top_count, top_value = values_by_count[0]
# Decide if a default value should be used for the field
if name in used_names:
used_names[name] += 1
default_value = None
elif long_name in used_names:
used_names[long_name] += 1
default_value = None
elif top_count > (0.5 * layer.num_feat):
default_value = top_value
else:
default_value = None
# Store the field definition
field_params = dict(
name=name, default_value=default_value, index=index,
top_values=values_by_count[:5])
if long_name:
field_params['long_name'] = long_name
fields.append(field_params)
# Check used fields:
for name, count in used_names.items():
if count == 0:
raise Exception('No data for name %s' % name)
elif count > 1:
dup_fields = []
no_problem = True
for field in fields:
if field['name'] == name or field.get('long_name') == name:
if dup_fields and len(field['top_values']) > 1:
no_problem = False
dup_fields.append(field)
msg = (' %s appears %d times in DBF fields' % (name, count))
if no_problem:
msg += ", but only the first has data, so we're OK."
logger.info(msg)
else:
msg += (
', and several have data! (only first will be used):')
for field in dup_fields:
msg += '\n ' + str(field)
logger.warning(msg)
# Store the field definitions in the database
ShapeAttribute.objects.create(
signup=signup, attributes=fields, name=cls.__name__)
# Convert the rows to minimized dicts
row_summaries = []
for feature in layer:
row = [c.value for c in feature]
summary = list()
assert len(row) == len(fields)
for val, field in zip(row, fields):
default = field['default_value']
if (default is None) or (val != default):
summary.append(dict(
name=field['name'], index=field['index'], value=val))
if 'long_name' in field:
summary[-1]['long_name'] = field['long_name']
row_summaries.append(summary)
return fields, row_summaries
@classmethod
def import_dbf(cls, signup, dbf, names):
'''Import a DBF as several objects for an instance
Kwargs:
signup: The sign-up to associate this item with
dbf: The DBF file or the path to the file
names: The 'NewFieldNames.txt' file or the path to the file
This function uses class items to customize behaviour:
- _dbf_mapping (required) maps DBF column names to model field names
- funtions named like 'convert_DBFNAME' convert the DBF value to the
field value
- create_from_dbf is used instead of create when associated models
need to be created
'''
assert hasattr(cls, '_dbf_mapping')
names_file = _force_to_file(names)
my_name = cls.__name__
logger.info(
'Reading %s data from %s...' % (my_name, dbf))
dbf_fields, dbf_rows = cls.read_dbf(signup, dbf, names_file)
model_params = []
for row in dbf_rows:
# Collect DBF values from row
values = dict()
for item in row:
name = item['name']
long_name = item.get('long_name')
value = item['value']
if name not in values:
values[name] = value
if long_name and long_name not in values:
values[long_name] = value
# Map to model fields
params = dict(attributes=row)
for dbf_name, field_name in cls._dbf_mapping:
value = values[dbf_name]
converter = getattr(cls, 'convert_' + dbf_name.upper(), None)
if converter:
value = converter(value)
params[field_name] = value
model_params.append(params)
# Create the database entries
creator = getattr(cls, 'create_from_dbf', cls.objects.create)
created_counts = defaultdict(int)
for params in model_params:
obj = creator(signup=signup, **params)
if isinstance(obj, DbfBase):
created_counts[obj.__class__.__name__] += 1
else:
for o in obj:
created_counts[o.__class__.__name__] += 1
# Report on what was done
counts = [(created_counts.pop(my_name), my_name)]
for name in sorted(created_counts.keys()):
counts.append((created_counts[name], name))
msg = 'Read '
fmt = lambda c, n: '%d %s%s' % (c, n, 's' if c > 1 else '')
if len(counts) > 2:
msg += ', '.join(fmt(*c) for c in counts[:-1])
msg += ', and %s' % fmt(*counts[-1])
else:
msg += fmt(*counts[0])
if len(counts) == 2:
msg += ' and %s' % fmt(*counts[1])
msg += ' from %s' % dbf
logger.info(msg)
@classmethod
def convert_latlon(cls, value):
'''Convert a DBF lat/lon to a string'''
raw = str(value)
return raw[:-6] + '.' + raw[-6:]
class Line(DbfBase):
'''A transit line from lines.dbf'''
signup = models.ForeignKey(SignUp)
line_id = models.IntegerField(db_index=True)
line_abbr = models.CharField(max_length=8, db_index=True)
line_name = models.CharField(max_length=30)
line_color = models.IntegerField()
line_type = models.CharField(max_length=2)
fare = models.ForeignKey(Fare, null=True, blank=True)
class Meta:
unique_together = ('signup', 'line_id')
ordering = ('line_id',)
def __unicode__(self):
return "%s-%s" % (self.line_id, self.line_abbr)
# Map DBF source columns to model fields
_dbf_mapping = (
('LineId0', 'line_id'),
('LineAbbr', 'line_abbr'),
('LineName', 'line_name'),
('LineColor', 'line_color'),
('LineType', 'line_type'),
('LineDirId0', 'linedirid0'),
('DIRECTIONNAME0', 'directionname0'),
('LineDirId1', 'linedirid1'),
('DIRECTIONNAME1', 'directionname1'))
@classmethod
def create_from_dbf(cls, **params):
'''Create Line and associated LineDirections from DBF data'''
ld0_params = dict(
linedir_id=params.pop('linedirid0'),
name=params.pop('directionname0'))
ld1_params = dict(
linedir_id=params.pop('linedirid1'),
name=params.pop('directionname1'))
line = cls.objects.create(**params)
linedirs = []
if ld0_params['linedir_id']:
linedir0 = LineDirection.objects.create(line=line, **ld0_params)
linedirs.append(linedir0)
if ld1_params['linedir_id']:
linedir1 = LineDirection.objects.create(line=line, **ld1_params)
linedirs.append(linedir1)
return [line] + linedirs
def color_as_hex(self):
'''Convert integer value into a hex color value
Because SQLite strips leading 0's from numbers, we store strangely.
'''
try:
return '%06x' % self.line_color
except:
return self.color
def text_color_as_hex(self):
'''Convert integer value into a contrasting hex color value
'''
back_color = self.color_as_hex()
# http://www.webmasterworld.com/forum88/9769.htm
r = int(back_color[:2], 16)
g = int(back_color[2:4], 16)
b = int(back_color[4:6], 16)
color_value = ((r * 299) + (g * 587) + (b * 114)) / 1000
if color_value > 130:
text_color = '000000'
else:
text_color = 'ffffff'
return text_color
def short_name(self):
return self.line_abbr.replace('FLEX', 'FL').replace('SFLX', 'SF')
def pick_fare(self):
if self.fare:
return self.fare
for fare in Fare.objects.exclude(line_name_ipattern=''):
if fare.line_name_ipattern.lower() in self.line_name.lower():
self.fare = fare
self.save()
return self.fare
default_fare_query = Fare.objects.filter(line_name_ipattern='')
if default_fare_query.exists():
self.fare = default_fare_query.latest('id')
self.save()
return self.fare
def copy_to_feed(self, feed):
gtfs_route, created = feed.route_set.get_or_create(
route_id=self.line_id, defaults=dict(
short_name=self.short_name(),
long_name=self.line_name.replace(self.line_abbr, ''),
rtype=3, color=self.color_as_hex(),
text_color=self.text_color_as_hex()))
fare = self.pick_fare()
gtfs_fare = fare.copy_to_feed(feed)
gtfs_fare.farerule_set.get_or_create(route=gtfs_route)
for linedir in self.linedirection_set.all():
linedir.copy_to_feed(feed, gtfs_route)
class LineDirection(models.Model):
'''The two line directions for a Line from lines.dbf'''
linedir_id = models.IntegerField(db_index=True)
line = models.ForeignKey(Line)
name = models.CharField(max_length=20)
_facing_dir = {
'To Downtown': 'in',
'From Downtown': 'out',
'CounterClock': 'CC',
'Clock': 'CL',
'Clockwise': 'CL',
}
class Meta:
unique_together = ('linedir_id', 'line')
ordering = ('linedir_id',)
def __unicode__(self):
return "%s-%s" % (self.linedir_id, self.name)
def copy_to_feed(self, feed, gtfs_route):
for tripday in self.tripday_set.all():
tripday.copy_to_feed(feed, gtfs_route)
def to_facing_dir(self):
'''Map name to a facing direction'''
return self._facing_dir.get(self.name)
class Pattern(models.Model):
'''The path the bus takes along the streets from pattern.*'''
pattern_id = models.IntegerField(db_index=True)
name = models.CharField(max_length=5)
linedir = models.ForeignKey(LineDirection)
raw_pattern = JSONField(default=[])
fixed_pattern = JSONField(blank=True, default=[])
class Meta:
unique_together = ('linedir', 'pattern_id')
def __unicode__(self):
return "%s-%s" % (self.pattern_id, self.name)
@classmethod
def import_shp(cls, signup, dbf, shp, shx=None):
dbf_file = _force_to_file(dbf)
shp_file = _force_to_file(shp)
shx_file = _force_to_file(shx)
logger.info(
'Parsing Pattern Shapes (dbf=%s, shp=%s, %s)' %
(dbf_file.name, shp_file.name,
('shx=%s' % shx_file.name) if shx_file else 'no shx'))
ds = DataSource(shp)
layer = ds[0]
assert layer.geom_type.name == 'LineString'
shapes = layer.get_geoms()
pattern_cnt, point_cnt = 0, 1
for feature, shape in zip(layer, shapes):
assert shape.geom_name == 'MULTILINESTRING'
pattern_id = feature['PatternId'].value
pattern = feature['Pattern'].value
linedir_id = feature['LineDirId'].value
linedir = LineDirection.objects.get(
line__signup=signup, linedir_id=linedir_id)
# Pattern is a sequence of point pairs
parts = []
for pt1, pt2 in shape.coords:
if pt1 != pt2:
part = sorted((pt1, pt2))
parts.append((part[0], part[1]))
point_cnt += 2 * len(parts)
cls.objects.create(
pattern_id=pattern_id, name=pattern, linedir=linedir,
raw_pattern=parts)
pattern_cnt += 1
logger.info(
'Parsed %d Shapes with a total of %d points.' % (
pattern_cnt, point_cnt))
def copy_to_feed(self, feed):
shape_id = "%s_%s" % (self.pattern_id, self.name)
gtfs_shape, created = feed.shape_set.get_or_create(shape_id=shape_id)
if created:
for seq, (lon, lat) in enumerate(self.get_points()):
point = 'POINT(%s %s)' % (lon, lat)
gtfs_shape.points.create(sequence=seq, point=point)
return gtfs_shape
def get_points(self):
def node_dist(node1, node2):
return haversine(node1[0], node1[1], node2[0], node2[1])
if not self.fixed_pattern:
# For debugging adding and discarding segments
def log_action(msg, n1, n2):
logger.info(
' Pattern %s for linedir %s of line %s: %s'
' (%0.5f, %0.5f)->(%0.5f, %0.5f) (%0.1f meters)' % (
self, self.linedir, self.linedir.line, msg,
n2[0], n2[1], n3[0], n3[1],
1000.0 * node_dist(n2, n3)))
# Create line
line = []
parts = self.raw_pattern
first_nodes = None
min_add_dist = 0.140
for seq, (node1, node2) in enumerate(parts):
if first_nodes:
first_node1, first_node2 = first_nodes
# Sort node orders by shortest distance between segments
node_orders = sorted([
(node_dist(first_node1, node1),
(first_node2, first_node1, node1, node2)),
(node_dist(first_node1, node2),
(first_node2, first_node1, node2, node1)),
(node_dist(first_node2, node1),
(first_node1, first_node2, node1, node2)),
(node_dist(first_node2, node2),
(first_node1, first_node2, node2, node1))])
dist, (n1, n2, n3, n4) = node_orders[0]
# Optimize for shared point in the two segements
if n2 == n3:
line.extend((n1, n2, n4))
elif node_dist(n2, n3) < min_add_dist:
line.extend((n1, n2, n3, n4))
else:
log_action('Discarding first segment', n2, n3)
first_nodes = None
elif line:
last_node = line[-1]
# Sort node orders by shortest distance to tail point
node_orders = sorted([
(node_dist(last_node, node1),
(last_node, node1, node2)),
(node_dist(last_node, node2),
(last_node, node2, node1))])
n1, n2, n3 = node_orders[0][1]
# Optimize for tail point in the new segment
if n1 == n2:
line.append(n3)
elif n2 == n3:
line.append(n3)
elif node_dist(n1, n2) < min_add_dist:
log_action('Adding segment', n1, n2)
line.extend((n2, n3))
else:
log_action('Discarding segment', n2, n2)
else:
# Collect the first segment for later
first_nodes = (node1, node2)
self.fixed_pattern = line
self.save()
return self.fixed_pattern
class Stop(DbfBase):
'''A stop from stops.dbf'''
signup = models.ForeignKey(SignUp)
stop_id = models.IntegerField(db_index=True)
stop_abbr = models.CharField(max_length=8, db_index=True)
stop_name = models.CharField(max_length=100)
node_abbr = models.CharField(max_length=8, blank=True)
site_name = models.CharField(max_length=80, blank=True)
facing_dir = models.CharField(max_length=3, blank=True)
lat = models.DecimalField(
'Latitude', max_digits=13, decimal_places=8,
help_text='WGS 84 latitude of stop or station')
lon = models.DecimalField(
'Longitude', max_digits=13, decimal_places=8,
help_text='WGS 84 longtitude of stop or station')
in_service = models.BooleanField()
class Meta:
unique_together = ('signup', 'stop_id')
ordering = ('signup', 'stop_id')
def __unicode__(self):
return "%s-%s" % (self.stop_id, self.stop_abbr)
# Map DBF source columns to model fields
_dbf_mapping = (
('StopId', 'stop_id'),
('StopAbbr', 'stop_abbr'),
('StopName', 'stop_name'),
('NodeAbbr', 'node_abbr'),
('SiteName', 'site_name'),
('Lat', 'lat'),
('Lon', 'lon'),
('InService', 'in_service'),
('FacingDir', 'facing_dir'))
convert_LAT = DbfBase.convert_latlon
convert_LON = DbfBase.convert_latlon
@property
def gtfs_stop_id(self):
return '%04d' % self.stop_id
def copy_to_feed(self, feed):
point = 'POINT(%s %s)' % (self.lon, self.lat)
gtfs_stop, created = feed.stop_set.get_or_create(
stop_id=self.gtfs_stop_id, defaults=dict(
code=self.stop_id, name=self.stop_name, point=point,
desc=self.site_name, location_type=0))
return gtfs_stop
class Node(models.Model):
'''A node inferred from StopsByLine or StopsByPattern
We don't have a direct database of nodes, but some stops are identified as
nodes in the StopsBy* data.
'''
signup = models.ForeignKey(SignUp)
stops = models.ManyToManyField(Stop, related_name='nodes')
node_id = models.IntegerField(db_index=True)
node_abbr = models.CharField(max_length=8)
node_name = models.CharField(max_length=50)
def __unicode__(self):
return "%s-%s" % (self.node_id, self.node_abbr)
class Meta:
ordering = ('node_id',)
class StopByLine(DbfBase):
stop = models.ForeignKey(Stop)
linedir = models.ForeignKey(LineDirection)
seq = models.IntegerField()
node = models.ForeignKey(Node, null=True, blank=True)
class Meta:
unique_together = ('stop', 'linedir', 'seq')
ordering = ('linedir', 'seq')
verbose_name_plural = "stops by line"
def __unicode__(self):
return '%s-%02d' % (self.linedir.linedir_id, self.seq)
# Map DBF source columns to model fields
_dbf_mapping = (
('StopId', 'stop_id'),
('LineDirId', 'linedir_id'),
('Sequence', 'seq'),
('StopType', 'stop_type'),
('NodeId', 'node_id'),
('NodeAbbr', 'node_abbr'),
('NodeName', 'node_name'))
@classmethod
def create_from_dbf(cls, **params):
signup = params.pop('signup')
stop_id = params.pop('stop_id')
stop = Stop.objects.get(signup=signup, stop_id=stop_id)
linedir_id = params.pop('linedir_id')
linedir = LineDirection.objects.get(
line__signup=signup, linedir_id=linedir_id)
seq = params.pop('seq')
stop_type = params.pop('stop_type')
attributes = params.pop('attributes')
node = None
node_created = False
if stop_type == 'N':
node, node_created = signup.node_set.get_or_create(**params)
node.stops.add(stop)
sbl = cls.objects.create(
stop=stop, linedir=linedir, seq=seq, node=node,
attributes=attributes)
if node_created:
return [sbl, node]
else:
return sbl
class StopByPattern(DbfBase):
stop = models.ForeignKey(Stop)
linedir = models.ForeignKey(LineDirection)
pattern = models.ForeignKey(Pattern)
seq = models.IntegerField()
node = models.ForeignKey(Node, null=True, blank=True)
class Meta:
unique_together = ('stop', 'linedir', 'pattern', 'seq')
ordering = ('pattern', 'seq',)
verbose_name_plural = "stops by pattern"
def __unicode__(self):
return '%s-%02d' % (self.pattern.pattern_id, self.seq)
# Map DBF source columns to model fields
_dbf_mapping = (
('StopId', 'stop_id'),
('LineDirId', 'linedir_id'),
('PatternId', 'pattern_id'),
('Sequence', 'seq'),
('StopType', 'stop_type'),
('NodeId', 'node_id'),
('NodeAbbr', 'node_abbr'),
('NodeName', 'node_name'))
@classmethod
def create_from_dbf(cls, **params):
signup = params.pop('signup')
stop_id = params.pop('stop_id')
stop = Stop.objects.get(signup=signup, stop_id=stop_id)
linedir_id = params.pop('linedir_id')
linedir = LineDirection.objects.get(
line__signup=signup, linedir_id=linedir_id)
pattern_id = params.pop('pattern_id')
pattern = Pattern.objects.get(
linedir=linedir, pattern_id=pattern_id)
seq = params.pop('seq')
stop_type = params.pop('stop_type')
attributes = params.pop('attributes')
node = None
node_created = False
if stop_type == 'N':
node, node_created = signup.node_set.get_or_create(**params)
node.stops.add(stop)
sbp = cls.objects.create(
stop=stop, linedir=linedir, pattern=pattern, seq=seq, node=node,
attributes=attributes)
if node_created:
return [sbp, node]
else:
return sbp
class Service(models.Model):
signup = models.ForeignKey(SignUp, null=True, blank=True)
service_id = models.IntegerField(
choices=((1, 'Weekday'), (2, 'Saturday')))
monday = models.BooleanField()
tuesday = models.BooleanField()
wednesday = models.BooleanField()
thursday = models.BooleanField()
friday = models.BooleanField()
saturday = models.BooleanField()
sunday = models.BooleanField()
start_date = models.DateField()
end_date = models.DateField()
@classmethod
def create_from_defaults(cls, signup):
for default in cls.objects.filter(signup=None):
service = cls.objects.create(
signup=signup, service_id=default.service_id,
monday=default.monday, tuesday=default.tuesday,
wednesday=default.wednesday, thursday=default.thursday,
friday=default.friday, saturday=default.saturday,
sunday=default.sunday, start_date=default.start_date,
end_date=default.end_date)
for def_exception in default.serviceexception_set.filter(
date__gte=default.start_date, date__lte=default.end_date):
service.serviceexception_set.create(
date=def_exception.date,
exception_type=def_exception.exception_type)
class Meta:
unique_together = ordering = ('signup', 'service_id')
def __unicode__(self):
return '%s-%s' % (self.service_id, self.get_service_id_display())
def copy_to_feed(self, feed):
gtfs_service, created = feed.service_set.get_or_create(
service_id=str(self.service_id), defaults=dict(
monday=self.monday, tuesday=self.tuesday,
wednesday=self.wednesday, thursday=self.thursday,
friday=self.friday, saturday=self.saturday,
sunday=self.sunday, start_date=self.start_date,
end_date=self.end_date))
for exception in self.serviceexception_set.filter(
date__gte=self.start_date, date__lte=self.end_date):
exception.copy_to_feed(feed, gtfs_service)
return gtfs_service
class ServiceException(models.Model):
service = models.ForeignKey(Service)
date = models.DateField()
exception_type = models.IntegerField(
choices=((1, 'Add Service'), (2, 'Remove Service')))
def __unicode__(self):
return '%s on %s for %s' % (
self.get_exception_type_display(), self.date, self.service)
def copy_to_feed(self, feed, gtfs_service):
servicedate_set = gtfs_service.servicedate_set
gtfs_service_exception, created = servicedate_set.get_or_create(
service=gtfs_service, date=self.date,
exception_type=self.exception_type)
class TripDay(models.Model):
'''A set of trips for a line direction by service day'''
linedir = models.ForeignKey(LineDirection)
service = models.ForeignKey(Service)
class Meta:
unique_together = ordering = ('linedir', 'service')
def __unicode__(self):
return '%s-%s' % (self.linedir.linedir_id, self.service.service_id)
@classmethod
def import_schedule(cls, signup, path_or_file):
schedule = _force_to_file(path_or_file)
logger.info('Parsing Trips from %s...' % schedule.name)
in_intro = 0 # Make sure we're in a Stop Trips file
in_meta = 1 # Get Line and Service, fix SignUp name
in_dir = 2 # Get / switch the LineDirection
in_cols = 3 # Get the TripStops
in_data = 4 # Get the Trip and TripTimes
in_error = 5 # Some error, cease processing
phase = in_intro
linedir = None
meta = dict()
tripday_cnt, tripstop_cnt, trip_cnt, triptimes_cnt = 0, 0, 0, 0
for linenum, linein in enumerate(schedule.readlines()):
linein = linein.rstrip()
if phase == in_intro:
# Make sure we're in a Stop Trips file
if linenum == 0:
assert(linein == 'Stop Trips')
elif linenum == 1:
assert(linein == '~~~~~~~~~~')
elif linenum == 2:
assert(linein == '')
phase = in_meta
else:
raise ValueError(
'Got lost in intro phase at line %d:\n.%s' %
(linenum, linein))
elif phase == in_meta:
# Get Line and Service, fix SignUp name
if ':' in linein:
name, val = linein.split(':', 1)
meta[name] = val.strip()
elif linein == '':