/
schedule.go
549 lines (473 loc) · 17 KB
/
schedule.go
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
package gtfs
import (
"archive/zip"
"bytes"
"encoding/csv"
"fmt"
"io"
"sort"
"strconv"
"strings"
"time"
"github.com/gocarina/gocsv"
"github.com/rs/zerolog/log"
"github.com/travigo/travigo/pkg/ctdf"
"github.com/travigo/travigo/pkg/dataimporter/datasets"
"github.com/travigo/travigo/pkg/transforms"
"github.com/travigo/travigo/pkg/util"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"golang.org/x/exp/maps"
)
type Schedule struct {
Agencies []Agency
Stops []Stop
Routes []Route
Trips []Trip
StopTimes []StopTime
Calendars []Calendar
CalendarDates []CalendarDate
Frequencies []Frequency
Shapes []Shape
}
func (gtfs *Schedule) ParseFile(reader io.Reader) error {
// Allow us to ignore those naughty records that have missing columns
gocsv.SetCSVReader(func(in io.Reader) gocsv.CSVReader {
r := csv.NewReader(in)
r.FieldsPerRecord = -1
return r
})
fileMap := map[string]interface{}{
"agency.txt": >fs.Agencies,
"stops.txt": >fs.Stops,
"routes.txt": >fs.Routes,
"trips.txt": >fs.Trips,
"stop_times.txt": >fs.StopTimes,
"calendar.txt": >fs.Calendars,
"calendar_dates.txt": >fs.CalendarDates,
// "frequencies.txt": >fs.Frequencies,
"shapes.txt": >fs.Shapes,
}
// TODO this uses a load of ram :(
body, err := io.ReadAll(reader)
if err != nil {
return err
}
archive, err := zip.NewReader(bytes.NewReader(body), int64(len(body)))
if err != nil {
return err
}
for _, zipFile := range archive.File {
file, err := zipFile.Open()
if err != nil {
log.Fatal().Err(err).Msg("Failed to open file")
}
defer file.Close()
fileName := zipFile.Name
if destination, exists := fileMap[fileName]; exists {
log.Info().Str("file", fileName).Msg("Loading file")
fileReader, _ := zipFile.Open()
defer fileReader.Close()
err = gocsv.Unmarshal(fileReader, destination)
if err != nil {
log.Error().Str("file", fileName).Err(err).Msg("Failed to parse csv file")
return err
}
} else {
log.Error().Str("file", fileName).Msg("Unknown gtfs file")
}
}
return nil
}
func (g *Schedule) Import(dataset datasets.DataSet, datasource *ctdf.DataSource) error {
log.Info().Msg("Converting & Importing as CTDF into MongoDB")
// Agencies / Operators
// TODO this mapping is hardcoding for the 1 UK datset and will need replacing later on to be more generic
agencyNOCMapping := map[string]string{}
for _, agency := range g.Agencies {
if agency.NOC == "" {
log.Debug().Str("agency", agency.ID).Msg("has no NOC mapping")
continue
}
agencyNOCMapping[agency.ID] = fmt.Sprintf("GB:NOC:%s", agency.NOC)
}
log.Info().Int("length", len(g.Agencies)).Msg("Starting Operators")
agenciesQueue := NewDatabaseBatchProcessingQueue("operators", 1*time.Second, 10*time.Second, 500)
if dataset.SupportedObjects.Operators {
agenciesQueue.Process()
}
agenciesMap := map[string]*Agency{}
for _, gtfsAgency := range g.Agencies {
agenciesMap[gtfsAgency.ID] = >fsAgency
operatorID := fmt.Sprintf("%s-operator-%s", dataset.Identifier, gtfsAgency.ID)
ctdfOperator := &ctdf.Operator{
PrimaryIdentifier: operatorID,
CreationDateTime: time.Now(),
ModificationDateTime: time.Now(),
DataSource: datasource,
PrimaryName: gtfsAgency.Name,
Website: gtfsAgency.URL,
}
if dataset.SupportedObjects.Operators {
// Insert
bsonRep, _ := bson.Marshal(bson.M{"$set": ctdfOperator})
updateModel := mongo.NewUpdateOneModel()
updateModel.SetFilter(bson.M{"primaryidentifier": operatorID})
updateModel.SetUpdate(bsonRep)
updateModel.SetUpsert(true)
agenciesQueue.Add(updateModel)
}
}
log.Info().Msg("Finished Operators")
if dataset.SupportedObjects.Operators {
agenciesQueue.Wait()
}
// Stops
log.Info().Int("length", len(g.Stops)).Msg("Starting Stops")
stopsQueue := NewDatabaseBatchProcessingQueue("stops", 1*time.Second, 10*time.Second, 500)
if dataset.SupportedObjects.Stops {
stopsQueue.Process()
}
for _, gtfsStop := range g.Stops {
timezone := gtfsStop.Timezone
if timezone == "" {
timezone = g.Agencies[0].Timezone
}
stopID := fmt.Sprintf("%s-stop-%s", dataset.Identifier, gtfsStop.ID)
ctdfStop := &ctdf.Stop{
PrimaryIdentifier: stopID,
OtherIdentifiers: map[string]string{
"GTFS-ID": gtfsStop.ID,
},
CreationDateTime: time.Now(),
ModificationDateTime: time.Now(),
DataSource: datasource,
PrimaryName: gtfsStop.Name,
OtherNames: map[string]string{},
Location: &ctdf.Location{
Type: "Point",
Coordinates: []float64{gtfsStop.Longitude, gtfsStop.Latitude},
},
Active: true,
Timezone: timezone,
}
if dataset.SupportedObjects.Stops {
// Insert
bsonRep, _ := bson.Marshal(bson.M{"$set": ctdfStop})
updateModel := mongo.NewUpdateOneModel()
updateModel.SetFilter(bson.M{"primaryidentifier": stopID})
updateModel.SetUpdate(bsonRep)
updateModel.SetUpsert(true)
stopsQueue.Add(updateModel)
}
}
log.Info().Msg("Finished Stops")
if dataset.SupportedObjects.Stops {
stopsQueue.Wait()
}
// Calendars
calendarMapping := map[string]*Calendar{}
calendarDateMapping := map[string][]*CalendarDate{}
for _, calendar := range g.Calendars {
calendarMapping[calendar.ServiceID] = &calendar
}
for _, calendarDate := range g.CalendarDates {
calendarDateMapping[calendarDate.ServiceID] = append(calendarDateMapping[calendarDate.ServiceID], &calendarDate)
}
// Shapes
shapsMapping := map[string][]*Shape{}
for _, shape := range g.Shapes {
shapsMapping[shape.ID] = append(shapsMapping[shape.ID], &shape)
}
// Routes / Services
routeTypeMapping := map[int]ctdf.TransportType{
0: ctdf.TransportTypeTram,
1: ctdf.TransportTypeMetro,
2: ctdf.TransportTypeRail,
3: ctdf.TransportTypeBus,
4: ctdf.TransportTypeFerry,
5: ctdf.TransportTypeTram,
6: ctdf.TransportTypeCableCar,
7: ctdf.TransportTypeUnknown, // Furnicular
11: ctdf.TransportTypeTram,
12: ctdf.TransportTypeUnknown, // Monorail
200: ctdf.TransportTypeCoach,
}
log.Info().Int("length", len(g.Routes)).Msg("Starting Services")
servicesQueue := NewDatabaseBatchProcessingQueue("services", 1*time.Second, 10*time.Second, 500)
if dataset.SupportedObjects.Services {
servicesQueue.Process()
}
ctdfServices := map[string]*ctdf.Service{}
routeMap := map[string]Route{}
for _, gtfsRoute := range g.Routes {
routeMap[gtfsRoute.ID] = gtfsRoute
serviceID := fmt.Sprintf("%s-service-%s", dataset.Identifier, gtfsRoute.ID)
serviceName := gtfsRoute.ShortName
if serviceName == "" {
serviceName = gtfsRoute.LongName
}
operatorRef := agencyNOCMapping[gtfsRoute.AgencyID]
if operatorRef == "" {
operatorRef = fmt.Sprintf("%s-operator-%s", dataset.Identifier, gtfsRoute.AgencyID)
}
ctdfService := &ctdf.Service{
PrimaryIdentifier: serviceID,
OtherIdentifiers: map[string]string{
"GTFS-ID": gtfsRoute.ID,
},
CreationDateTime: time.Now(),
ModificationDateTime: time.Now(),
DataSource: datasource,
ServiceName: serviceName,
OperatorRef: operatorRef,
Routes: []ctdf.Route{},
BrandColour: gtfsRoute.Colour,
SecondaryBrandColour: gtfsRoute.TextColour,
TransportType: routeTypeMapping[gtfsRoute.Type],
}
transforms.Transform(ctdfService, 1, "gb-dft-bods-gtfs-schedule")
ctdfServices[gtfsRoute.ID] = ctdfService
if dataset.SupportedObjects.Services {
// Insert
bsonRep, _ := bson.Marshal(bson.M{"$set": ctdfService})
updateModel := mongo.NewUpdateOneModel()
updateModel.SetFilter(bson.M{"primaryidentifier": serviceID})
updateModel.SetUpdate(bsonRep)
updateModel.SetUpsert(true)
servicesQueue.Add(updateModel)
}
}
log.Info().Msg("Finished Services")
if dataset.SupportedObjects.Services {
servicesQueue.Wait()
}
ctdfJourneys := map[string]*ctdf.Journey{}
// fullJourneyTracks := map[string][]ctdf.Location{}
// Journeys
journeysQueue := NewDatabaseBatchProcessingQueue("journeys", 1*time.Second, 1*time.Minute, 1000)
if dataset.SupportedObjects.Journeys {
journeysQueue.Process()
}
log.Info().Int("length", len(g.Trips)).Msg("Starting Journeys")
for _, trip := range g.Trips {
journeyID := fmt.Sprintf("%s-journey-%s", dataset.Identifier, trip.ID)
serviceID := fmt.Sprintf("%s-service-%s", dataset.Identifier, trip.RouteID)
availability := &ctdf.Availability{}
// Calendar availability
calendar, exists := calendarMapping[trip.ServiceID]
if exists {
for _, day := range calendar.GetRunningDays() {
availability.Match = append(availability.Match, ctdf.AvailabilityRule{
Type: ctdf.AvailabilityDayOfWeek,
Value: day,
})
}
dateRunsFrom, _ := time.Parse("20060102", calendar.Start)
dateRunsTo, _ := time.Parse("20060102", calendar.End)
availability.Condition = append(availability.Condition, ctdf.AvailabilityRule{
Type: ctdf.AvailabilityDateRange,
Value: fmt.Sprintf("%s:%s", dateRunsFrom.Format("2006-01-02"), dateRunsTo.Format("2006-01-02")),
})
}
// Calendar dates availability
for _, calendarDate := range calendarDateMapping[trip.ServiceID] {
date, _ := time.Parse("20060102", calendarDate.Date)
rule := ctdf.AvailabilityRule{
Type: ctdf.AvailabilityDate,
Value: date.Format("2006-01-02"),
}
if calendarDate.ExceptionType == 1 {
availability.Match = append(availability.Match, rule)
} else if calendarDate.ExceptionType == 2 {
availability.Exclude = append(availability.Exclude, rule)
}
}
// Put it all together again
ctdfJourneys[trip.ID] = &ctdf.Journey{
PrimaryIdentifier: journeyID,
OtherIdentifiers: map[string]string{
"GTFS-TripID": trip.ID,
"GTFS-RouteID": trip.RouteID,
},
CreationDateTime: time.Now(),
ModificationDateTime: time.Now(),
DataSource: datasource,
ServiceRef: serviceID,
OperatorRef: ctdfServices[trip.RouteID].OperatorRef,
// Direction: trip.DirectionID,
DestinationDisplay: trip.Headsign,
DepartureTimezone: agenciesMap[routeMap[trip.RouteID].AgencyID].Timezone,
Availability: availability,
Path: []*ctdf.JourneyPathItem{},
}
if trip.BlockID != "" {
ctdfJourneys[trip.ID].OtherIdentifiers["BlockNumber"] = trip.BlockID
}
if trip.ShapeID != "" {
journeyTrack := []ctdf.Location{}
shapes := shapsMapping[trip.ShapeID]
// Make sure its in order
sort.Slice(shapes, func(i, j int) bool {
return shapes[i].PointSequence < shapes[j].PointSequence
})
for _, shape := range shapes {
journeyTrack = append(journeyTrack, ctdf.Location{
Type: "Point",
Coordinates: []float64{shape.PointLongitude, shape.PointLatitude},
})
}
// fullJourneyTracks[trip.ID] = journeyTrack
ctdfJourneys[trip.ID].Track = journeyTrack
}
}
// Stop Times
// Build the actual path of the journeys
tripStopSequenceMap := map[string]map[int]*StopTime{}
for _, stopTime := range g.StopTimes {
if _, exists := tripStopSequenceMap[stopTime.TripID]; !exists {
tripStopSequenceMap[stopTime.TripID] = map[int]*StopTime{}
}
tripStopSequenceMap[stopTime.TripID][stopTime.StopSequence] = &stopTime
}
for tripID, tripSequencyMap := range tripStopSequenceMap {
sequenceIDs := maps.Keys(tripSequencyMap)
sort.Ints(sequenceIDs)
for index := 1; index < len(sequenceIDs); index += 1 {
sequenceID := sequenceIDs[index]
stopTime := tripSequencyMap[sequenceID]
previousSequenceID := sequenceIDs[index-1]
previousStopTime := tripSequencyMap[previousSequenceID]
originArrivalTime, err := time.Parse("15:04:05", fixTimestamp(previousStopTime.ArrivalTime))
if err != nil {
log.Error().Err(err).Msg("Failed to parse previousStopTime.ArrivalTime")
}
originDeparturelTime, err := time.Parse("15:04:05", fixTimestamp(previousStopTime.DepartureTime))
if err != nil {
log.Error().Err(err).Msg("Failed to parse previousStopTime.DepartureTime")
}
destinationArrivalTime, err := time.Parse("15:04:05", fixTimestamp(stopTime.ArrivalTime))
if err != nil {
log.Error().Err(err).Msg("Failed to parse stopTime.ArrivalTime")
}
var originStopRef string
var destinationStopRef string
// TODO no hardocded nonsense!!
if dataset.Identifier == "gb-dft-bods-gtfs-schedule" {
originStopRef = fmt.Sprintf("GB:ATCO:%s", previousStopTime.StopID)
destinationStopRef = fmt.Sprintf("GB:ATCO:%s", stopTime.StopID)
} else {
originStopRef = fmt.Sprintf("%s-stop-%s", dataset.Identifier, previousStopTime.StopID)
destinationStopRef = fmt.Sprintf("%s-stop-%s", dataset.Identifier, stopTime.StopID)
}
journeyPathItem := &ctdf.JourneyPathItem{
OriginStopRef: originStopRef,
DestinationStopRef: destinationStopRef,
OriginArrivalTime: originArrivalTime,
DestinationArrivalTime: destinationArrivalTime,
OriginDepartureTime: originDeparturelTime,
DestinationDisplay: stopTime.StopHeadsign,
OriginActivity: []ctdf.JourneyPathItemActivity{},
DestinationActivity: []ctdf.JourneyPathItemActivity{},
}
if previousStopTime.DropOffType == 0 {
journeyPathItem.OriginActivity = append(journeyPathItem.OriginActivity, ctdf.JourneyPathItemActivitySetdown)
}
if previousStopTime.PickupType == 0 {
journeyPathItem.OriginActivity = append(journeyPathItem.OriginActivity, ctdf.JourneyPathItemActivityPickup)
}
if stopTime.DropOffType == 0 {
journeyPathItem.DestinationActivity = append(journeyPathItem.DestinationActivity, ctdf.JourneyPathItemActivitySetdown)
}
if stopTime.PickupType == 0 {
journeyPathItem.DestinationActivity = append(journeyPathItem.DestinationActivity, ctdf.JourneyPathItemActivityPickup)
}
ctdfJourneys[tripID].Path = append(ctdfJourneys[tripID].Path, journeyPathItem)
if index == 1 {
ctdfJourneys[tripID].DepartureTime = originDeparturelTime
}
}
// TODO fix transforms here
// transforms.Transform(ctdfJourneys[tripID], 1, "gb-dft-bods-gtfs-schedule")
if util.ContainsString([]string{
"GB:NOC:LDLR", "GB:NOC:LULD", "GB:NOC:TRAM", "gb-dft-bods-gtfs-schedule-operator-OPTEMP454",
"GB:NOC:ABLO", "gb-dft-bods-gtfs-schedule-operator-OP12046", "GB:NOC:ALNO", "GB:NOC:ALSO", "gb-dft-bods-gtfs-schedule-operator-OPTEMP450", "gb-dft-bods-gtfs-schedule-operator-OP11684",
"GB:NOC:ELBG", "gb-dft-bods-gtfs-schedule-operator-OPTEMP456", "gb-dft-bods-gtfs-schedule-operator-OP3039", "GB:NOC:LSOV", "GB:NOC:LUTD", "gb-dft-bods-gtfs-schedule-operator-OP2974",
"GB:NOC:MTLN", "GB:NOC:SULV",
}, ctdfJourneys[tripID].OperatorRef) || (ctdfJourneys[tripID].OperatorRef == "GB:NOC:UNIB" && util.ContainsString([]string{
"gb-dft-bods-gtfs-schedule-service-14023", "gb-dft-bods-gtfs-schedule-service-13950", "gb-dft-bods-gtfs-schedule-service-14053", "gb-dft-bods-gtfs-schedule-service-13966", "gb-dft-bods-gtfs-schedule-service-13968", "gb-dft-bods-gtfs-schedule-service-82178",
}, ctdfJourneys[tripID].ServiceRef)) {
ctdfJourneys[tripID].OperatorRef = "GB:NOC:TFLO"
}
// Insert
if dataset.SupportedObjects.Journeys {
bsonRep, _ := bson.Marshal(bson.M{"$set": ctdfJourneys[tripID]})
updateModel := mongo.NewUpdateOneModel()
updateModel.SetFilter(bson.M{"primaryidentifier": ctdfJourneys[tripID].PrimaryIdentifier})
updateModel.SetUpdate(bsonRep)
updateModel.SetUpsert(true)
journeysQueue.Add(updateModel)
}
ctdfJourneys[tripID] = nil
}
log.Info().Msg("Finished Journeys")
if dataset.SupportedObjects.Journeys {
journeysQueue.Wait()
}
return nil
}
func fixTimestamp(timestamp string) string {
splitTimestamp := strings.Split(timestamp, ":")
if len(splitTimestamp) != 3 {
return timestamp
}
hour, err := strconv.Atoi(splitTimestamp[0])
if err != nil {
return timestamp
}
if hour >= 24 {
splitTimestamp[0] = fmt.Sprintf("%d", hour%24)
return strings.Join(splitTimestamp, ":")
} else {
return timestamp
}
}
/////// THE DEAD ZONE ////////
// r := csv.NewReader(fileReader)
// r.FieldsPerRecord = -1
// if _, err := r.Read(); err != nil { //read header
// log.Fatal().Err(err).Msg("csv header read")
// }
// for {
// rec, err := r.Read()
// if err != nil {
// if err == io.EOF {
// break
// }
// log.Fatal().Err(err).Msg("csv row read")
// }
// stopSequence, _ := strconv.Atoi(rec[4])
// var stopHeadsign string
// if len(rec) >= 6 {
// stopHeadsign = rec[5]
// }
// var pickupType int
// if len(rec) >= 7 {
// pickupType, _ = strconv.Atoi(rec[6])
// }
// var dropOffType int
// if len(rec) >= 8 {
// dropOffType, _ = strconv.Atoi(rec[7])
// }
// gtfs.StopTimes = append(gtfs.StopTimes, &StopTime{
// // trip_id,arrival_time,departure_time,stop_id,stop_sequence,stop_headsign,pickup_type,drop_off_type,shape_dist_traveled,timepoint,stop_direction_name
// TripID: rec[0],
// ArrivalTime: rec[1],
// DepartureTime: rec[2],
// StopID: rec[3],
// StopSequence: stopSequence,
// StopHeadsign: stopHeadsign,
// PickupType: pickupType,
// DropOffType: dropOffType,
// })
// }