-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathtrainrun.service.ts
More file actions
1001 lines (888 loc) · 36.5 KB
/
Copy pathtrainrun.service.ts
File metadata and controls
1001 lines (888 loc) · 36.5 KB
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
import {Trainrun} from "../../models/trainrun.model";
import {
LabelDto,
LabelRef,
NetzgrafikDto,
TrainrunCategory,
Direction,
TrainrunDto,
TrainrunFrequency,
TrainrunTimeCategory,
} from "../../data-structures/business.data.structures";
import {EventEmitter, Injectable} from "@angular/core";
import {BehaviorSubject} from "rxjs";
import {NodeService} from "./node.service";
import {TrainrunSectionService} from "./trainrunsection.service";
import {DataService} from "./data.service";
import {Node} from "../../models/node.model";
import {TrainrunSection} from "../../models/trainrunsection.model";
import {GeneralViewFunctions} from "../../view/util/generalViewFunctions";
import {
BackwardNonStopTrainrunIterator,
BackwardTrainrunIterator,
NonStopTrainrunIterator,
TrainrunIterator,
} from "../util/trainrun.iterator";
import {LogService} from "../../logger/log.service";
import {LabelService} from "./label.service";
import {FilterService} from "../ui/filter.service";
import {Transition} from "../../models/transition.model";
import {Port} from "../../models/port.model";
import {Connection} from "../../models/connection.model";
import {
Operation,
OperationType,
TrainrunCreateOperation,
TrainrunDeleteOperation,
TrainrunUpdateOperation,
} from "../../models/operation.model";
import {TrainrunsectionHelper} from "../util/trainrunsection.helper";
@Injectable({
providedIn: "root",
})
export class TrainrunService {
// Description of observable data service: https://coryrylan.com/blog/angular-observable-data-services
trainrunsSubject = new BehaviorSubject<Trainrun[]>([]);
readonly trainruns = this.trainrunsSubject.asObservable();
trainrunsStore: {trainruns: Trainrun[]} = {trainruns: []}; // store the data in memory
readonly operation = new EventEmitter<Operation>();
private dataService: DataService = null;
private nodeService: NodeService = null;
private trainrunSectionService: TrainrunSectionService = null;
constructor(
private logService: LogService,
private labelService: LabelService,
private filterService: FilterService,
) {}
setDataService(dataService: DataService) {
this.dataService = dataService;
}
public setNodeService(nodeService: NodeService) {
this.nodeService = nodeService;
}
public setTrainrunSectionService(trainrunSectionService: TrainrunSectionService) {
this.trainrunSectionService = trainrunSectionService;
}
setTrainrunData(trainrunsDto: TrainrunDto[]) {
this.trainrunsStore.trainruns = trainrunsDto.map((trainrunDto) => {
const trainrun = new Trainrun(trainrunDto);
trainrun.setTrainrunCategory(this.dataService.getTrainrunCategory(trainrunDto.categoryId));
trainrun.setTrainrunFrequency(this.dataService.getTrainrunFrequency(trainrunDto.frequencyId));
trainrun.setTrainrunTimeCategory(
this.dataService.getTrainrunTimeCategory(trainrunDto.trainrunTimeCategoryId),
);
return trainrun;
});
}
createNewTrainrunsFromDtoList(trainruns: TrainrunDto[]): Map<number, number> {
const trainrunMap = new Map<number, number>();
trainruns.forEach((trainrun) => {
// create new trainrun and add it to trainrun map
trainrunMap.set(trainrun.id, this.createNewTrainrunFromDto(trainrun).getId());
});
return trainrunMap;
}
mergeTrainruns(trainruns: TrainrunDto[]): Map<number, number> {
const trainrunMap = new Map<number, number>();
trainruns.forEach((trainrun) => {
const equalTrainrun = this.trainrunsStore.trainruns.find(
(tr) =>
tr.getTitle() === trainrun.name && tr.getTrainrunCategory().id === trainrun.categoryId,
);
if (equalTrainrun !== undefined) {
// just link found trainrun with existing one
trainrunMap.set(trainrun.id, equalTrainrun.getId());
} else {
// create new trainrun and add it to trainrun map
trainrunMap.set(trainrun.id, this.createNewTrainrunFromDto(trainrun).getId());
}
});
return trainrunMap;
}
mergeLabelTrainrun(netzgrafikDto: NetzgrafikDto, trainrunMap: Map<number, number>) {
netzgrafikDto.trainruns.forEach((trainrun) => {
const newTrainrunId = trainrunMap.get(trainrun.id);
const newTrainrun = this.getTrainrunFromId(newTrainrunId);
trainrun.labelIds.forEach((labelsId) => {
const labelDtos: LabelDto[] = netzgrafikDto.labels.filter((label) => label.id === labelsId);
labelDtos.forEach((labelDto) => {
const label = this.labelService.getOrCreateLabel(labelDto.label, labelDto.labelRef);
if (!newTrainrun.getLabelIds().includes(label.getId())) {
newTrainrun.getLabelIds().push(label.getId());
}
});
});
});
this.labelService.labelUpdated();
}
getTrainrunFromId(trainrunId: number): Trainrun {
return this.trainrunsStore.trainruns.find((trainrun) => trainrun.getId() === trainrunId);
}
getSelectedOrNewTrainrun(): Trainrun {
let trainrun = this.trainrunsStore.trainruns.find((tr) => tr.selected());
if (trainrun === undefined) {
trainrun = new Trainrun();
trainrun.setTrainrunCategory(
this.dataService.getTrainrunCategory(Trainrun.DEFAULT_TRAINRUN_CATEGORY),
);
trainrun.setTrainrunFrequency(
this.dataService.getTrainrunFrequency(Trainrun.DEFAULT_TRAINRUN_FREQUENCY),
);
trainrun.setTrainrunTimeCategory(
this.dataService.getTrainrunTimeCategory(Trainrun.DEFAULT_TRAINRUN_TIME_CATEGORY),
);
trainrun.select();
this.trainrunsStore.trainruns.push(trainrun);
}
return trainrun;
}
deleteTrainrun(trainrun: Trainrun, enforceUpdate = true) {
const deletetLabelIds = this.labelService.clearLabel(
trainrun.getLabelIds(),
this.makeLabelIDCounterMap(this.getTrainruns()),
);
this.filterService.clearDeletetFilterTrainrunLabels(deletetLabelIds);
this.trainrunsStore.trainruns.forEach((tr) => tr.unselect());
this.trainrunsStore.trainruns = this.trainrunsStore.trainruns.filter(
(tr) => tr.getId() !== trainrun.getId(),
);
if (enforceUpdate) {
this.trainrunsUpdated();
}
this.operation.emit(new TrainrunDeleteOperation(trainrun));
}
getSelectedTrainrun(): Trainrun {
const selectedTrainrun: Trainrun = this.trainrunsStore.trainruns.find((tr) => tr.selected());
if (selectedTrainrun !== undefined) {
return selectedTrainrun;
} else {
return null;
}
}
setTrainrunAsSelected(trainrunId: number, enforceUpdate = true) {
this.trainrunsStore.trainruns.forEach((tr) => tr.unselect());
this.trainrunSectionService.unselectAllTrainrunSections(enforceUpdate);
const trainrun = this.getTrainrunFromId(trainrunId);
if (trainrun !== undefined) {
trainrun.select();
if (enforceUpdate) {
this.trainrunsUpdated();
}
}
}
unselectAllTrainruns(enforceUpdate = true) {
this.trainrunsStore.trainruns.forEach((trainrun) => trainrun.unselect());
this.trainrunSectionService.unselectAllTrainrunSections(enforceUpdate);
if (enforceUpdate) {
this.trainrunsUpdated();
}
}
isAnyTrainrunSelected(): boolean {
const selectedTrainrun = this.trainrunsStore.trainruns.find((trainrun) => trainrun.selected());
return selectedTrainrun !== undefined;
}
updateTrainrunFrequency(
trainrun: Trainrun,
frequency: TrainrunFrequency,
offset: number,
): number {
const oldFreq = trainrun.getFrequency();
const newFreq = frequency.frequency;
const freqOffset = (frequency.offset + offset) % newFreq;
if (trainrun.getTrainrunFrequency().id === frequency.id) {
// no update needed
return freqOffset;
}
this.getTrainrunFromId(trainrun.getId()).setTrainrunFrequency(frequency);
this.trainrunSectionService
.getAllTrainrunSectionsForTrainrun(trainrun.getId())
.forEach((ts: TrainrunSection) => {
const sourceDeparture = (60 + ts.getSourceDeparture() + freqOffset) % 60;
const targetArrival = (60 + ts.getTargetArrival() + freqOffset) % 60;
this.trainrunSectionService.updateTrainrunSectionTime(
ts.getId(),
(60 - sourceDeparture) % 60,
sourceDeparture,
targetArrival,
(60 - targetArrival) % 60,
ts.getTravelTime(),
);
});
this.nodeService.reorderPortsOnNodesForTrainrun(trainrun, false);
this.propagateTrainrunInitialConsecutiveTimes(trainrun);
this.trainrunsUpdated();
this.operation.emit(new TrainrunUpdateOperation(trainrun, ["times", "frequencyId"]));
return freqOffset;
}
updateTrainrunCategory(trainrun: Trainrun, category: TrainrunCategory) {
if (trainrun.getTrainrunCategory().id === category.id) {
// no update needed
return;
}
this.getTrainrunFromId(trainrun.getId()).setTrainrunCategory(category);
this.nodeService.reorderPortsOnNodesForTrainrun(trainrun, false);
this.trainrunsUpdated();
this.operation.emit(new TrainrunUpdateOperation(trainrun, ["categoryId"]));
}
updateTrainrunTimeCategory(trainrun: Trainrun, timeCategory: TrainrunTimeCategory) {
if (trainrun.getTrainrunTimeCategory().id === timeCategory.id) {
// no update needed
return;
}
this.getTrainrunFromId(trainrun.getId()).setTrainrunTimeCategory(timeCategory);
this.nodeService.reorderPortsOnNodesForTrainrun(trainrun, false);
this.trainrunsUpdated();
this.operation.emit(new TrainrunUpdateOperation(trainrun, ["timeCategoryId"]));
}
updateTrainrunTitle(trainrun: Trainrun, title: string) {
this.getTrainrunFromId(trainrun.getId()).setTitle(title);
this.nodeService.reorderPortsOnNodesForTrainrun(trainrun, false);
this.trainrunsUpdated();
this.operation.emit(new TrainrunUpdateOperation(trainrun, ["name"]));
}
updateDirection(trainrun: Trainrun, direction: Direction, isTrainInverted?: boolean) {
const trainrunSection = this.getTrainrunFromId(trainrun.getId());
trainrunSection.setDirection(direction);
this.trainrunsUpdated();
let oneWayDirection = undefined;
if (direction === Direction.ONE_WAY) oneWayDirection = isTrainInverted ? "backward" : "forward";
this.operation.emit(
new TrainrunUpdateOperation(trainrun, ["direction", "nodes", "times"], oneWayDirection),
);
}
getTrainruns(): Trainrun[] {
return Object.assign({}, this.trainrunsStore).trainruns;
}
getVisibleTrainruns(): Trainrun[] {
return this.getTrainruns().filter((t) => this.filterService.filterTrainrun(t));
}
getAllTrainrunLabels(): string[] {
let trainrunLabels = [];
this.getTrainruns().forEach((t) =>
this.labelService
.getTextLabelsFromIds(t.getLabelIds())
.forEach((label) => trainrunLabels.push(label)),
);
trainrunLabels = trainrunLabels.filter((v, i, a) => a.indexOf(v) === i);
trainrunLabels.sort();
return trainrunLabels;
}
visibleTrainrunsDeleteLabel(labelRef: string) {
const labelObject = this.labelService.getLabelFromLabelAndLabelRef(labelRef, LabelRef.Trainrun);
if (labelObject === undefined) {
return;
}
this.getTrainruns().forEach((t: Trainrun) => {
if (this.filterService.filterTrainrun(t)) {
this.filterService.clearDeletetFilterTrainrunLabel(labelObject.getId());
t.setLabelIds(t.getLabelIds().filter((labelId: number) => labelId !== labelObject.getId()));
this.operation.emit(new TrainrunUpdateOperation(t, ["labelIds"]));
}
});
const trainruns = this.getTrainruns().find(
(t: Trainrun) =>
t.getLabelIds().find((labelId: number) => labelId === labelObject.getId()) !== undefined,
);
if (trainruns === undefined) {
this.labelService.deleteLabel(labelObject.getId());
}
this.trainrunsUpdated();
}
visibleTrainrunsSetLabel(labelRef: string) {
const labelObject = this.labelService.getLabelFromLabelAndLabelRef(labelRef, LabelRef.Trainrun);
if (labelObject === undefined) {
return;
}
this.getTrainruns().forEach((t) => {
if (this.filterService.filterTrainrun(t)) {
const labelIds: number[] = t.getLabelIds();
labelIds.push(labelObject.getId());
t.setLabelIds(labelIds.filter((v, i, a) => a.indexOf(v) === i));
}
});
this.trainrunsUpdated();
}
getConnectedTrainrunIdsFirstOrder(trainrunId: number): number[] {
const trainrunSections =
this.trainrunSectionService.getAllTrainrunSectionsForTrainrun(trainrunId);
let connectedTrainrunIds: number[] = [];
for (const trainsection of trainrunSections) {
connectedTrainrunIds = connectedTrainrunIds.concat(
trainsection.getSourceNode().getAllConnectedTrainruns(trainsection),
);
connectedTrainrunIds = connectedTrainrunIds.concat(
trainsection.getTargetNode().getAllConnectedTrainruns(trainsection),
);
}
return [...new Set(connectedTrainrunIds)];
}
getDtos() {
return this.trainrunsStore.trainruns.map((trainrun) => trainrun.getDto());
}
splitTrainrunIntoTwoParts(t: Transition) {
const trainrun2split = t.getTrainrun();
const portId1 = t.getPortId1();
const portId2 = t.getPortId2();
const node = this.nodeService.getNodeFromTransition(t);
node.removeTransitionFromId(t);
const port1 = node.getPort(portId1);
const port2 = node.getPort(portId2);
const trainrunSection2 = port2.getTrainrunSection();
const newTrainrun = this.duplicateTrainrun(trainrunSection2.getTrainrunId(), false, "-2");
trainrunSection2.setTrainrun(newTrainrun);
const iterator = this.getIterator(node, trainrunSection2);
while (iterator.hasNext()) {
iterator.next();
const trans = iterator
.current()
.node.getTransition(iterator.current().trainrunSection.getId());
if (trans) {
trans.setTrainrun(newTrainrun);
}
iterator.current().trainrunSection.setTrainrun(newTrainrun);
}
this.nodeService.checkAndFixMissingTransitions(
port1.getTrainrunSection().getSourceNodeId(),
port1.getTrainrunSection().getTargetNodeId(),
port1.getTrainrunSection().getId(),
false,
);
trainrun2split.unselect();
newTrainrun.select();
this.nodeService.transitionsUpdated();
this.trainrunsUpdated();
this.operation.emit(new TrainrunCreateOperation(newTrainrun));
this.operation.emit(
new TrainrunUpdateOperation(trainrun2split, ["nodes", "times", "numberOfStops"]),
);
}
combineTwoTrainruns(node: Node, port1: Port, port2: Port) {
const trainrun1 = port1.getTrainrunSection().getTrainrun();
const trainrun2 = port2.getTrainrunSection().getTrainrun();
if (trainrun1.getId() === trainrun2.getId()) {
return;
}
// Only the frequency position of the main train should influence the frequency position
// of the merged train, i.e. if, for example, both trains run every 30 minutes, one is in
// cycle position 0 and the second is in frequency position 30, e.g. 02 or 32, then the second
// should be shifted by 30 minutes (1 frequency ) so that both are in the same cycle position,
// i.e. 02.
const arrivalTimeAtNode =
node.getId() !== port1.getTrainrunSection().getSourceNodeId()
? port1.getTrainrunSection().getTargetArrival()
: port1.getTrainrunSection().getSourceArrival();
const departTimeAtNode =
node.getId() !== port2.getTrainrunSection().getSourceNodeId()
? port2.getTrainrunSection().getTargetDeparture()
: port2.getTrainrunSection().getSourceDeparture();
let frequencyOffset = 0;
while (60 + arrivalTimeAtNode > departTimeAtNode + frequencyOffset) {
frequencyOffset += port1.getTrainrunSection().getFrequency();
}
// update trainrun references (trainrunSections and transitions)
const trainrunSection = port2.getTrainrunSection();
trainrunSection.setTrainrun(trainrun1);
const iterator = this.getIterator(node, trainrunSection);
while (iterator.hasNext()) {
iterator.next();
const trans = iterator
.current()
.node.getTransition(iterator.current().trainrunSection.getId());
if (trans) {
trans.setTrainrun(trainrun1);
}
iterator.current().trainrunSection.setTrainrun(trainrun1);
iterator
.current()
.trainrunSection.shiftAllTimes(
frequencyOffset,
node.getId() === port2.getTrainrunSection().getSourceNodeId(),
);
}
// Enforce updating all transitions. If the train run has "holes," we must also update
// all other transitions that cannot be reached through train run iterations. However,
// we don't need to update the times, so we can skip `shiftAllTimes`.
this.trainrunSectionService
.getAllTrainrunSectionsForTrainrun(trainrun2.getId())
.forEach((ts) => {
ts.getSourceNode().getTransition(ts.getId())?.setTrainrun(trainrun1);
ts.getTargetNode().getTransition(ts.getId())?.setTrainrun(trainrun1);
});
// update trainrun references (1st transition)
const trans1 = node.getTransitionFromPortId(port1.getId());
const trans2 = node.getTransitionFromPortId(port2.getId());
if (trans1 === undefined && trans2 === undefined) {
const trans = node.addTransitionAndComputeRouting(port1, port2, trainrun1);
if (60 + arrivalTimeAtNode === departTimeAtNode + frequencyOffset) {
trans.setIsNonStopTransit(true);
} else {
trans.setIsNonStopTransit(false);
}
}
// update trainrun references (connection)
const connections2delete = node.getConnections().filter((c: Connection) => {
return (
(c.getPortId1() === port1.getId() && c.getPortId2() === port2.getId()) ||
(c.getPortId1() === port2.getId() && c.getPortId2() === port1.getId())
);
});
connections2delete.forEach((c: Connection) => {
node.removeConnection(c.getId());
});
// unselect both trainruns
trainrun1.unselect();
trainrun2.unselect();
// Change all trainrun sections' trainrunId reference from trainrun2 to trainrun1
// There can be some other "unconnected" trainrun segments left; those have to be moved to
// trainrun1, which will "survive".
this.trainrunSectionService
.getAllTrainrunSectionsForTrainrun(trainrun2.getId())
.forEach((ts: TrainrunSection) => ts.setTrainrun(trainrun1));
// remove empty trainrun
this.deleteTrainrun(trainrun2, false);
// check/correct transitions
this.trainrunSectionService.checkMissingTransitionsAfterDeletion(trainrun1);
// select
trainrun1.select();
this.nodeService.reorderPortsOnNodesForTrainrun(trainrun1, false);
// Ensure consistent section direction considering the previous ones
this.trainrunSectionService.enforceConsistentSectionDirection(trainrunSection.getTrainrunId());
// Update the cumulative times for the combined trainrun
this.propagateConsecutiveTimesForTrainrun(port1.getTrainrunSection().getId());
// update
this.trainrunsUpdated();
this.operation.emit(
new TrainrunUpdateOperation(trainrun1, ["nodes", "times", "numberOfStops"]),
);
this.nodeService.nodesUpdated();
this.nodeService.connectionsUpdated();
this.nodeService.transitionsUpdated();
}
duplicateTrainrun(trainrunId: number, enforceUpdate = true, postfix = " COPY"): Trainrun {
const trainrun = this.getTrainrunFromId(trainrunId);
const copiedtrainrun = new Trainrun();
copiedtrainrun.setTrainrunCategory(trainrun.getTrainrunCategory());
copiedtrainrun.setTrainrunFrequency(trainrun.getTrainrunFrequency());
copiedtrainrun.setTrainrunTimeCategory(trainrun.getTrainrunTimeCategory());
copiedtrainrun.setDirection(trainrun.getDirection());
copiedtrainrun.setTitle(trainrun.getTitle() + postfix);
copiedtrainrun.setLabelIds(trainrun.getLabelIds());
this.trainrunsStore.trainruns.push(copiedtrainrun);
return copiedtrainrun;
}
duplicateTrainrunAndSections(
trainrunId: number,
enforceUpdate = true,
postfix = " COPY",
): Trainrun {
const copiedtrainrun = this.duplicateTrainrun(trainrunId, enforceUpdate, postfix);
this.trainrunSectionService.copyAllTrainrunSectionsForTrainrun(
trainrunId,
copiedtrainrun.getId(),
);
this.setTrainrunAsSelected(copiedtrainrun.getId(), false);
if (enforceUpdate) {
this.nodeService.transitionsUpdated();
this.nodeService.nodesUpdated();
this.trainrunsUpdated();
}
this.operation.emit(new TrainrunCreateOperation(copiedtrainrun, trainrunId));
return copiedtrainrun;
}
setLabels(trainrunId: number, labels: string[]) {
const trainrun = this.getTrainrunFromId(trainrunId);
// ensure uniqueness of input labels
const uniqueLabels = Array.from(new Set(labels));
const labelIds = uniqueLabels.map((label) =>
this.labelService.getOrCreateLabel(label, LabelRef.Trainrun).getId(),
);
const deletedLabelIds = this.labelService.clearLabel(
this.findClearedLabel(trainrun, labelIds),
this.makeLabelIDCounterMap(this.getTrainruns()),
);
this.filterService.clearDeletetFilterTrainrunLabels(deletedLabelIds);
trainrun.setLabelIds(labelIds);
this.trainrunsUpdated();
if (uniqueLabels.length === labels.length) {
this.operation.emit(new TrainrunUpdateOperation(trainrun, ["labelIds"]));
}
}
trainrunsUpdated() {
this.trainrunsSubject.next(Object.assign({}, this.trainrunsStore).trainruns);
}
propagateInitialConsecutiveTimes() {
this.trainrunsStore.trainruns.forEach((trainrun) => {
this.propagateTrainrunInitialConsecutiveTimes(trainrun);
});
}
propagateTrainrunInitialConsecutiveTimes(trainrun: Trainrun) {
const startNode = this.getLeftOrTopNodeWithTrainrunId(trainrun.getId());
const ts = startNode.getTrainrunSection(trainrun);
this.propagateConsecutiveTimesForTrainrun(ts.getId());
}
getBothEndNodesFromTrainrunPart(trainrunSection: TrainrunSection): {
endNode1: Node;
endNode2: Node;
} {
const sourceNode = trainrunSection.getSourceNode();
const targetNode = trainrunSection.getTargetNode();
const endNode1 = this.getEndNode(sourceNode, trainrunSection);
const endNode2 = this.getEndNode(targetNode, trainrunSection);
return {endNode1, endNode2};
}
propagateConsecutiveTimesForTrainrun(trainrunSectionId: number) {
const inTrainrunSection =
this.trainrunSectionService.getTrainrunSectionFromId(trainrunSectionId);
if (inTrainrunSection === undefined) {
return;
}
let alltrainrunsections = this.trainrunSectionService.getAllTrainrunSectionsForTrainrun(
inTrainrunSection.getTrainrunId(),
);
while (alltrainrunsections.length > 0) {
// propagate Consecutive Times Forward
const trainrunSection = alltrainrunsections[0];
const bothEndNodes = this.getBothEndNodesFromTrainrunPart(trainrunSection);
const startForwardBackwardNode = GeneralViewFunctions.getStartForwardAndBackwardNode(
bothEndNodes.endNode1,
bothEndNodes.endNode2,
);
const propDataForward = this.propagateConsecutiveTimes(
startForwardBackwardNode.startForwardNode,
startForwardBackwardNode.startForwardNode.getExtremityTrainrunSection(
trainrunSection.getTrainrunId(),
true,
),
trainrunSection.getFrequencyOffset(),
);
const arrivalTime = propDataForward.cumTime;
// propagate Consecutive Times Backward
const freq = trainrunSection.getTrainrun().getTrainrunFrequency().frequency;
const restFreqArrivalTime = Math.floor(arrivalTime / freq) * freq;
const freqDependantArrivalTime = arrivalTime - restFreqArrivalTime;
let offset = freq - freqDependantArrivalTime;
offset += restFreqArrivalTime;
offset = Math.floor(offset / 60) * 60;
const propDataBackward = this.propagateConsecutiveTimes(
startForwardBackwardNode.startBackwardNode,
startForwardBackwardNode.startBackwardNode.getExtremityTrainrunSection(
trainrunSection.getTrainrunId(),
false,
),
offset,
);
// filter all still visited trainrun sections
alltrainrunsections = alltrainrunsections.filter(
(ts) =>
propDataForward.visitedTrainrunSections.indexOf(ts) === -1 &&
propDataBackward.visitedTrainrunSections.indexOf(ts) === -1,
);
}
}
getLeftOrTopNodeWithTrainrunId(trainrunId: number): Node {
const bothEndNodes = this.getBothEndNodesWithTrainrunId(trainrunId);
return GeneralViewFunctions.getLeftOrTopNode(bothEndNodes.endNode1, bothEndNodes.endNode2);
}
getRightOrBottomNodeWithTrainrunId(trainrunId: number): Node {
const bothEndNodes = this.getBothEndNodesWithTrainrunId(trainrunId);
return GeneralViewFunctions.getRightOrBottomNode(bothEndNodes.endNode1, bothEndNodes.endNode2);
}
getEndNode(node: Node, trainrunSection: TrainrunSection): Node {
const iterator = this.getIterator(node, trainrunSection);
while (iterator.hasNext()) {
iterator.next();
}
return iterator.current().node;
}
getNodePathToEnd(node: Node, trainrunSection: TrainrunSection): Node[] {
const path: Node[] = [node];
const iterator = this.getIterator(node, trainrunSection);
while (iterator.hasNext()) {
iterator.next();
path.push(iterator.current().node);
}
return path;
}
getLastNonStopNode(node: Node, trainrunSection: TrainrunSection): Node {
const iterator = this.getNonStopIterator(node, trainrunSection);
while (iterator.hasNext()) {
iterator.next();
}
return iterator.current().node;
}
getBothLastNonStopNodes(trainrunSection: TrainrunSection) {
const sourceNode = trainrunSection.getSourceNode();
const targetNode = trainrunSection.getTargetNode();
return {
lastNonStopNode1: this.getLastNonStopNode(sourceNode, trainrunSection),
lastNonStopNode2: this.getLastNonStopNode(targetNode, trainrunSection),
};
}
getLastNonStopTrainrunSection(node: Node, trainrunSection: TrainrunSection): TrainrunSection {
const iterator = this.getNonStopIterator(node, trainrunSection);
while (iterator.hasNext()) {
iterator.next();
}
return iterator.current().trainrunSection;
}
getBothLastNonStopTrainrunSections(trainrunSection: TrainrunSection) {
const sourceNode = trainrunSection.getSourceNode();
const targetNode = trainrunSection.getTargetNode();
return {
lastNonStopTrainrunSection1: this.getLastNonStopTrainrunSection(sourceNode, trainrunSection),
lastNonStopTrainrunSection2: this.getLastNonStopTrainrunSection(targetNode, trainrunSection),
};
}
getFirstTrainrunSection(trainrun: Trainrun): TrainrunSection | undefined {
const sections = this.trainrunSectionService.getAllTrainrunSectionsForTrainrun(
trainrun.getId(),
);
if (sections.length === 0) {
return undefined;
}
// sections[0] does not ensure to be the first section in the trainrun
const iterator = this.getBackwardIterator(sections[0].getTargetNode(), sections[0]);
while (iterator.hasNext()) {
iterator.next();
}
return iterator.current().trainrunSection;
}
getFirstNonStopTrainrunSection(trainrunSection: TrainrunSection): TrainrunSection {
// starts at the target node, goes backwards to find the first section that is not a non-stop section
const iterator = this.getBackwardNonStopIterator(
trainrunSection.getTargetNode(),
trainrunSection,
);
while (iterator.hasNext()) {
iterator.next();
}
return iterator.current().trainrunSection;
}
getLastTrainrunSection(trainrun: Trainrun): TrainrunSection | undefined {
const sections = this.trainrunSectionService.getAllTrainrunSectionsForTrainrun(
trainrun.getId(),
);
if (sections.length === 0) {
return undefined;
}
// sections[0] does not ensure to be the first section in the trainrun
const iterator = this.getIterator(sections[0].getSourceNode(), sections[0]);
while (iterator.hasNext()) {
iterator.next();
}
return iterator.current().trainrunSection;
}
sumTravelTimeUpToLastNonStopNode(node: Node, trainrunSection: TrainrunSection): number {
let summedTravelTime = 0;
const iterator = this.getNonStopIterator(node, trainrunSection);
while (iterator.hasNext()) {
const nextPair = iterator.next();
summedTravelTime += nextPair.trainrunSection.getTravelTime();
}
return summedTravelTime;
}
getCumulativeTravelTime(trainrunSection: TrainrunSection) {
const iterator = this.getNonStopIterator(trainrunSection.getSourceNode(), trainrunSection);
while (iterator.hasNext()) {
iterator.next();
}
return this.sumTravelTimeUpToLastNonStopNode(
iterator.current().node,
iterator.current().trainrunSection,
);
}
getCumSumTravelTimeNodePathToLastNonStopNode(n: Node, ts: TrainrunSection) {
const data = [
{
node: n,
sumTravelTime: 0,
trainrunSection: ts,
},
];
let summedTravelTime = 0;
const iterator = this.getNonStopIterator(n, ts);
while (iterator.hasNext()) {
const nextPair = iterator.next();
summedTravelTime += nextPair.trainrunSection.getTravelTime();
data.push({
node: nextPair.node,
sumTravelTime: summedTravelTime,
trainrunSection: nextPair.trainrunSection,
});
}
return data;
}
getCumulativeTravelTimeAndNodePath(trainrunSection: TrainrunSection) {
const iterator = this.getNonStopIterator(trainrunSection.getSourceNode(), trainrunSection);
while (iterator.hasNext()) {
iterator.next();
}
return this.getCumSumTravelTimeNodePathToLastNonStopNode(
iterator.current().node,
iterator.current().trainrunSection,
);
}
isStartEqualsEndNode(trainrunSectionId: number): boolean {
const trainrunSection = this.trainrunSectionService.getTrainrunSectionFromId(trainrunSectionId);
const startNode = this.getEndNode(trainrunSection.getSourceNode(), trainrunSection);
const endNode = this.getEndNode(trainrunSection.getTargetNode(), trainrunSection);
return startNode.getId() === endNode.getId();
}
public getIterator(node: Node, trainrunSection: TrainrunSection) {
return new TrainrunIterator(this.logService, node, trainrunSection);
}
public getNonStopIterator(node: Node, trainrunSection: TrainrunSection) {
return new NonStopTrainrunIterator(this.logService, node, trainrunSection);
}
public getBackwardIterator(node: Node, trainrunSection: TrainrunSection) {
return new BackwardTrainrunIterator(this.logService, node, trainrunSection);
}
public getBackwardNonStopIterator(node: Node, trainrunSection: TrainrunSection) {
return new BackwardNonStopTrainrunIterator(this.logService, node, trainrunSection);
}
// For each trainrun, get iterator from the smallest consecutiveTime.
public getRootIterators(): Map<number, TrainrunIterator> {
const trainrunSections = this.trainrunSectionService.getTrainrunSections();
const iterators = new Map<number, TrainrunIterator>();
const consecutiveTimes = new Map<number, number>();
trainrunSections.forEach((ts) => {
const trainrunId = ts.getTrainrunId();
const node = ts.getSourceNode();
const it = iterators.get(trainrunId);
const consecutiveTime = ts.getSourceDepartureDto().consecutiveTime;
if (it === undefined || consecutiveTimes.get(trainrunId) > consecutiveTime) {
iterators.set(trainrunId, this.getIterator(node, ts));
consecutiveTimes.set(trainrunId, consecutiveTime);
}
});
return iterators;
}
getBothEndNodesWithTrainrunId(trainrunId: number) {
const trainrunSections: TrainrunSection[] = this.trainrunSectionService.getTrainrunSections();
const trainrunSection = trainrunSections.find((trs) => trs.getTrainrunId() === trainrunId);
return this.getBothEndNodesFromTrainrunPart(trainrunSection);
}
private createNewTrainrunFromDto(trainrun: TrainrunDto): Trainrun {
const newTrainrun = new Trainrun();
newTrainrun.setTrainrunCategory(this.dataService.getTrainrunCategory(trainrun.categoryId));
newTrainrun.setTrainrunFrequency(this.dataService.getTrainrunFrequency(trainrun.frequencyId));
newTrainrun.setTrainrunTimeCategory(
this.dataService.getTrainrunTimeCategory(trainrun.trainrunTimeCategoryId),
);
newTrainrun.setDirection(trainrun.direction);
newTrainrun.setTitle(trainrun.name);
newTrainrun.setLabelIds(trainrun.labelIds);
this.trainrunsStore.trainruns.push(newTrainrun);
return newTrainrun;
}
private propagateConsecutiveTimes(
node: Node,
trainrunSection: TrainrunSection,
offset: number,
): {
cumTime: number;
visitedTrainrunSections: TrainrunSection[];
} {
const visitedTrainrunSections: TrainrunSection[] = [trainrunSection];
if (trainrunSection === undefined) {
return {
cumTime: 0,
visitedTrainrunSections: visitedTrainrunSections,
};
}
let accumulatedTime = node.getDepartureTime(trainrunSection) + offset;
const iterator = this.getIterator(node, trainrunSection);
while (iterator.hasNext()) {
const nextPair = iterator.next();
nextPair.node
.getOppositeNode(nextPair.trainrunSection)
.setDepartureConsecutiveTime(nextPair.trainrunSection, accumulatedTime);
const oppositeNodeDepartureTime = nextPair.node
.getOppositeNode(nextPair.trainrunSection)
.getDepartureTime(nextPair.trainrunSection);
const arrivalTime = nextPair.node.getArrivalTime(nextPair.trainrunSection);
const travelTime =
arrivalTime < oppositeNodeDepartureTime
? arrivalTime + 60 - oppositeNodeDepartureTime
: arrivalTime - oppositeNodeDepartureTime;
accumulatedTime += travelTime;
const travelTimeOffset =
nextPair.trainrunSection.getTravelTime() - (nextPair.trainrunSection.getTravelTime() % 60);
accumulatedTime += travelTimeOffset;
nextPair.node.setArrivalConsecutiveTime(nextPair.trainrunSection, accumulatedTime);
let halteZeit = 0;
if (!nextPair.node.isEndNode(nextPair.trainrunSection)) {
const oldArrival = nextPair.node.getArrivalTime(nextPair.trainrunSection);
const trs = nextPair.node.getNextTrainrunSection(nextPair.trainrunSection);
const nextDeparture = nextPair.node.getDepartureTime(trs);
halteZeit =
nextDeparture < oldArrival ? nextDeparture + 60 - oldArrival : nextDeparture - oldArrival;
}
accumulatedTime += halteZeit;
visitedTrainrunSections.push(nextPair.trainrunSection);
}
return {
cumTime: accumulatedTime,
visitedTrainrunSections: visitedTrainrunSections,
};
}
private findClearedLabel(trainrun: Trainrun, labelIds: number[]) {
return [].concat(trainrun.getLabelIds()).filter((oldlabelId) => !labelIds.includes(oldlabelId));
}
private makeLabelIDCounterMap(trainruns: Trainrun[]): Map<number, number> {
const labelIDCauntMap = new Map<number, number>();
trainruns.forEach((trainrun) => {
trainrun.getLabelIds().forEach((labelId) => {
let counter = labelIDCauntMap.get(labelId);
if (counter === undefined) {
counter = 0;
}
counter++;
labelIDCauntMap.set(labelId, counter);
});
});
return labelIDCauntMap;
}
isTrainrunTargetRightOrBottom(trainrun: Trainrun = this.getSelectedTrainrun()): boolean {
if (!trainrun) {
return false;
}
const firstNode = this.getFirstTrainrunSection(trainrun).getSourceNode();
const lastNode = this.getLastTrainrunSection(trainrun).getTargetNode();
return GeneralViewFunctions.getRightOrBottomNode(firstNode, lastNode) === lastNode;
}
getLeftOrTopExtremitySection(): TrainrunSection {
if (!this.getSelectedTrainrun()) {
return null;
}
const bothEndNodes = this.getBothEndNodesWithTrainrunId(this.getSelectedTrainrun().getId());
const leftOrTopNode = GeneralViewFunctions.getLeftOrTopNode(
bothEndNodes.endNode1,
bothEndNodes.endNode2,
);
return leftOrTopNode.getExtremityTrainrunSection(this.getSelectedTrainrun().getId());
}
getSbbArrowForTrainrunSectionDirection(): string {
if (!this.getSelectedTrainrun() || this.getSelectedTrainrun().isRoundTrip()) {
return "arrows-left-right-medium";
}
const isTargetRightOrBottom = TrainrunsectionHelper.isTargetRightOrBottom(
this.trainrunSectionService.getSelectedTrainrunSection(),
);
if (isTargetRightOrBottom) {
return "arrow-right-medium";
} else {
return "arrow-left-medium";
}
}
getSbbArrowForTrainrunDirection(): string {
if (!this.getSelectedTrainrun() || this.getSelectedTrainrun().isRoundTrip()) {
return "arrows-left-right-medium";
}
if (this.isTrainrunTargetRightOrBottom()) {
return "arrow-right-medium";
} else {
return "arrow-left-medium";
}
}