-
Notifications
You must be signed in to change notification settings - Fork 96
/
trip_destination.py
1664 lines (1426 loc) · 57.8 KB
/
trip_destination.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
# ActivitySim
# See full license in LICENSE.txt.
from __future__ import annotations
import logging
import warnings
from pathlib import Path
import numpy as np
import pandas as pd
from pydantic import root_validator
from activitysim.abm.models.util.school_escort_tours_trips import (
split_out_school_escorting_trips,
)
from activitysim.abm.models.util.trip import (
cleanup_failed_trips,
flag_failed_trip_leg_mates,
)
from activitysim.abm.tables.size_terms import tour_destination_size_terms
from activitysim.core import (
chunk,
config,
estimation,
expressions,
los,
simulate,
tracing,
workflow,
)
from activitysim.core.configuration.base import PreprocessorSettings
from activitysim.core.configuration.logit import LocationComponentSettings
from activitysim.core.interaction_sample import interaction_sample
from activitysim.core.interaction_sample_simulate import interaction_sample_simulate
from activitysim.core.skim_dictionary import DataFrameMatrix
from activitysim.core.tracing import print_elapsed_time
from activitysim.core.util import assign_in_place, reindex
logger = logging.getLogger(__name__)
NO_DESTINATION = -1
# TRIP_ORIG_TAZ = 'TAZ'
ALT_DEST_TAZ = "ALT_DEST_TAZ"
# PRIMARY_DEST_TAZ = 'PRIMARY_DEST_TAZ'
# DEST_MAZ = 'dest_maz'
class TripDestinationSettings(LocationComponentSettings, extra="forbid"):
"""Settings for the trip_destination component.
.. versionadded:: 1.2
"""
DEST_CHOICE_LOGSUM_COLUMN_NAME: str = None
DEST_CHOICE_SAMPLE_TABLE_NAME: str = None
TRIP_ORIGIN: str = "origin"
ALT_DEST_COL_NAME: str = "dest_taz"
PRIMARY_ORIGIN: str = "origin"
PRIMARY_DEST: str = "tour_leg_dest" # must be created in preprocessor
REDUNDANT_TOURS_MERGED_CHOOSER_COLUMNS: list[str] | None = None
preprocessor: PreprocessorSettings | None = None
alts_preprocessor: PreprocessorSettings | None = None
CLEANUP: bool
fail_some_trips_for_testing: bool = False
"""This setting is used by testing code to force failed trip_destination."""
@root_validator(pre=True)
def deprecated_destination_prefix(cls, values):
replacements = {
"DESTINATION_SAMPLE_SPEC": "SAMPLE_SPEC",
"DESTINATION_SPEC": "SPEC",
}
for badkey, goodkey in replacements.items():
if badkey in values:
if goodkey in values:
if values[badkey] != values[goodkey]:
# both keys are given, with different values -> error
raise ValueError(
f"Deprecated `{badkey}` field must have the "
f"same value as `{goodkey}` if both are provided."
)
else:
# both keys are given, with same values -> warning
warnings.warn(
f"Use of the field `{badkey}` in the "
"trip_destination configuration file is deprecated, use "
f"just `{goodkey}` instead (currently both are given).",
FutureWarning,
stacklevel=2,
)
values.pop(badkey)
else:
# only the wrong key is given -> warning
warnings.warn(
f"Use of the field `{badkey}` in the "
"trip_destination configuration file is deprecated, use "
f"`{goodkey}` instead.",
FutureWarning,
stacklevel=2,
)
values[goodkey] = values[badkey]
values.pop(badkey)
return values
@property
def DESTINATION_SAMPLE_SPEC(self) -> Path:
"""Alias for `SAMPLE_SPEC`.
.. deprecated:: 1.3
"""
warnings.warn(
"DESTINATION_SAMPLE_SPEC is deprecated, use SAMPLE_SPEC",
DeprecationWarning,
stacklevel=2,
)
return self.SAMPLE_SPEC
@property
def DESTINATION_SPEC(self) -> Path:
"""Alias for `SPEC`.
.. deprecated:: 1.3
"""
warnings.warn(
"DESTINATION_SPEC is deprecated, use SPEC",
DeprecationWarning,
stacklevel=2,
)
return self.SPEC
@workflow.func
def _destination_sample(
state: workflow.State,
primary_purpose,
trips,
alternatives,
model_settings: TripDestinationSettings,
size_term_matrix,
skims,
alt_dest_col_name,
estimator,
chunk_tag: str,
trace_label: str,
zone_layer=None,
):
"""
Note: trips with no viable destination receive no sample rows
(because we call interaction_sample with allow_zero_probs=True)
All other trips will have one or more rows with pick_count summing to sample_size
returns
choices: pandas.DataFrame
alt_dest prob pick_count
trip_id
102829169 2898 0.002333 1
102829169 2901 0.004976 1
102829169 3193 0.002628 1
"""
spec = simulate.spec_for_segment(
state,
None,
spec_id="SAMPLE_SPEC",
segment_name=primary_purpose,
estimator=estimator,
spec_file_name=model_settings.SAMPLE_SPEC,
coefficients_file_name=model_settings.COEFFICIENTS,
)
sample_size = model_settings.SAMPLE_SIZE
if state.settings.disable_destination_sampling or (
estimator and estimator.want_unsampled_alternatives
):
# FIXME interaction_sample will return unsampled complete alternatives with probs and pick_count
logger.info(
f"Estimation mode for {trace_label} using "
f"unsampled alternatives short_circuit_choices"
)
sample_size = 0
locals_dict = state.get_global_constants().copy()
locals_dict.update(model_settings.CONSTANTS)
# size_terms of destination zones are purpose-specific, and trips have various purposes
# so the relevant size_term for each interaction_sample row
# cannot be determined until after choosers are joined with alternatives
# (unless we iterate over trip.purpose - which we could, though we are already iterating over trip_num)
# so, instead, expressions determine row-specific size_term by a call to: size_terms.get(df.alt_dest, df.purpose)
locals_dict.update(
{
"size_terms": size_term_matrix,
"size_terms_array": size_term_matrix.df.to_numpy(),
"timeframe": "trip",
"land_use": state.get_dataframe("land_use"),
}
)
locals_dict.update(skims)
log_alt_losers = state.settings.log_alt_losers
choices = interaction_sample(
state,
choosers=trips,
alternatives=alternatives,
sample_size=sample_size,
alt_col_name=alt_dest_col_name,
log_alt_losers=log_alt_losers,
allow_zero_probs=True,
spec=spec,
skims=skims,
locals_d=locals_dict,
chunk_size=state.settings.chunk_size,
chunk_tag=chunk_tag,
trace_label=trace_label,
zone_layer=zone_layer,
compute_settings=model_settings.compute_settings.subcomponent_settings(
"sample"
),
)
return choices
@workflow.func
def destination_sample(
state: workflow.State,
primary_purpose,
trips,
alternatives,
model_settings: TripDestinationSettings,
size_term_matrix,
skim_hotel,
estimator,
chunk_size,
trace_label,
):
chunk_tag = "trip_destination.sample"
skims = skim_hotel.sample_skims(presample=False)
alt_dest_col_name = model_settings.ALT_DEST_COL_NAME
choices = _destination_sample(
state,
primary_purpose,
trips,
alternatives,
model_settings,
size_term_matrix,
skims,
alt_dest_col_name,
estimator,
chunk_tag=chunk_tag,
trace_label=trace_label,
)
return choices
def aggregate_size_term_matrix(maz_size_term_matrix, network_los):
df = maz_size_term_matrix.df
assert ALT_DEST_TAZ not in df
dest_taz = network_los.map_maz_to_taz(df.index)
taz_size_term_matrix = df.groupby(dest_taz).sum()
taz_size_term_matrix = DataFrameMatrix(taz_size_term_matrix)
return taz_size_term_matrix
def choose_MAZ_for_TAZ(
state,
taz_sample,
MAZ_size_terms,
trips,
network_los,
alt_dest_col_name,
trace_label,
):
"""
Convert taz_sample table with TAZ zone sample choices to a table with a MAZ zone chosen for each TAZ
choose MAZ probabilistically (proportionally by size_term) from set of MAZ zones in parent TAZ
Parameters
----------
taz_sample: dataframe with duplicated index <chooser_id_col> and columns: <alt_dest_col_name>, prob, pick_count
MAZ_size_terms: dataframe with duplicated index <chooser_id_col> and columns: zone_id, dest_TAZ, size_term
Returns
-------
dataframe with with duplicated index <chooser_id_col> and columns: <alt_dest_col_name>, prob, pick_count
"""
if len(taz_sample) == 0:
# it can happen that all trips have no viable destinations (and so are dropped from the sample)
# in which case we can just return the empty taz_sample, since it has the same columns
return taz_sample.copy()
# we had to use alt_dest_col_name as specified in model_settings for interaction_sample
# because expressions reference it to look up size_terms by trip purpose
DEST_MAZ = alt_dest_col_name
DEST_TAZ = f"{alt_dest_col_name}_TAZ"
taz_sample.rename(columns={alt_dest_col_name: DEST_TAZ}, inplace=True)
trace_hh_id = state.settings.trace_hh_id
have_trace_targets = trace_hh_id and state.tracing.has_trace_targets(taz_sample)
if have_trace_targets:
trace_label = tracing.extend_trace_label(trace_label, "choose_MAZ_for_TAZ")
# write taz choices, pick_counts, probs
trace_targets = state.tracing.trace_targets(taz_sample)
state.tracing.trace_df(
taz_sample[trace_targets],
label=tracing.extend_trace_label(trace_label, "taz_sample"),
transpose=False,
)
# print(f"taz_sample\n{taz_sample}")
# alt_dest_TAZ prob pick_count
# trip_id
# 4343721 12 0.000054 1
# 4343721 20 0.001864 2
taz_choices = taz_sample[[DEST_TAZ, "prob"]].reset_index(drop=False)
taz_choices = taz_choices.reindex(
taz_choices.index.repeat(taz_sample.pick_count)
).reset_index(drop=True)
taz_choices = taz_choices.rename(columns={"prob": "TAZ_prob"})
# print(f"taz_choices\n{taz_choices}")
# trip_id alt_dest_TAZ prob
# 0 4343721 12 0.000054
# 1 4343721 20 0.001864
# 2 4343721 20 0.001864
# print(f"MAZ_size_terms\n{MAZ_size_terms.df}")
# work escort shopping eatout othmaint social othdiscr univ
# alt_dest
# 2 31.0 9.930 0.042 0.258 0.560 0.520 10.856 0.042
# 3 0.0 3.277 0.029 0.000 0.029 0.029 7.308 0.029
# 4 0.0 1.879 0.023 0.000 0.023 0.023 5.796 0.023
# just to make it clear we are siloing choices by chooser_id
chooser_id_col = (
taz_sample.index.name
) # should be canonical chooser index name (e.g. 'trip_id')
# for random_for_df, we need df with de-duplicated chooser canonical index
chooser_df = pd.DataFrame(index=taz_sample.index[~taz_sample.index.duplicated()])
num_choosers = len(chooser_df)
assert chooser_df.index.name == chooser_id_col
# to make choices, <taz_sample_size> rands for each chooser (one rand for each sampled TAZ)
# taz_sample_size will be model_settings['SAMPLE_SIZE'] samples, except if we are estimating
taz_sample_size = taz_choices.groupby(chooser_id_col)[DEST_TAZ].count().max()
# taz_choices index values should be contiguous
assert (
taz_choices[chooser_id_col] == np.repeat(chooser_df.index, taz_sample_size)
).all()
# we need to choose a MAZ for each DEST_TAZ choice
# probability of choosing MAZ based on MAZ size_term fraction of TAZ total
# there will be a different set (and number) of candidate MAZs for each TAZ
# (preserve index, which will have duplicates as result of join)
maz_taz = (
network_los.get_maz_to_taz_series(state)
.rename(DEST_TAZ)
.rename_axis(index=DEST_MAZ)
.to_frame()
.reset_index()
)
maz_sizes = pd.merge(
taz_choices[[chooser_id_col, DEST_TAZ]].reset_index(),
maz_taz,
how="left",
on=DEST_TAZ,
).set_index("index")
purpose = maz_sizes["trip_id"].map(trips.purpose) # size term varies by purpose
maz_sizes["size_term"] = MAZ_size_terms.get(maz_sizes[DEST_MAZ], purpose)
# print(f"maz_sizes\n{maz_sizes}")
# trip_id alt_dest_TAZ alt_dest size_term
# index
# 0 4343721 12 3445 0.019
# 0 4343721 12 11583 0.017
# 0 4343721 12 21142 0.020
if have_trace_targets:
# write maz_sizes: maz_sizes[index,trip_id,dest_TAZ,zone_id,size_term]
maz_sizes_trace_targets = state.tracing.trace_targets(
maz_sizes, slicer="trip_id"
)
trace_maz_sizes = maz_sizes[maz_sizes_trace_targets]
state.tracing.trace_df(
trace_maz_sizes,
label=tracing.extend_trace_label(trace_label, "maz_sizes"),
transpose=False,
)
# number of DEST_TAZ candidates per chooser
maz_counts = maz_sizes.groupby(maz_sizes.index).size().values
# print(maz_counts)
# max number of MAZs for any TAZ
max_maz_count = maz_counts.max()
# print(f"max_maz_count {max_maz_count}")
# offsets of the first and last rows of each chooser in sparse interaction_utilities
last_row_offsets = maz_counts.cumsum()
first_row_offsets = np.insert(last_row_offsets[:-1], 0, 0)
# repeat the row offsets once for each dummy utility to insert
# (we want to insert dummy utilities at the END of the list of alternative utilities)
# inserts is a list of the indices at which we want to do the insertions
inserts = np.repeat(last_row_offsets, max_maz_count - maz_counts)
# insert zero filler to pad each alternative set to same size
padded_maz_sizes = np.insert(maz_sizes.size_term.values, inserts, 0.0)
padded_maz_sizes = padded_maz_sizes.reshape(-1, max_maz_count)
# prob array with one row TAZ_choice, one column per alternative
row_sums = padded_maz_sizes.sum(axis=1)
maz_probs = np.divide(padded_maz_sizes, row_sums.reshape(-1, 1))
assert maz_probs.shape == (num_choosers * taz_sample_size, max_maz_count)
rands = (
state.get_rn_generator()
.random_for_df(chooser_df, n=taz_sample_size)
.reshape(-1, 1)
)
assert len(rands) == num_choosers * taz_sample_size
assert len(rands) == maz_probs.shape[0]
# make choices
# positions is array with the chosen alternative represented as a column index in probs
# which is an integer between zero and max_maz_count
positions = np.argmax((maz_probs.cumsum(axis=1) - rands) > 0.0, axis=1)
# shouldn't have chosen any of the dummy pad positions
assert (positions < maz_counts).all()
taz_choices[DEST_MAZ] = maz_sizes[DEST_MAZ].take(positions + first_row_offsets)
taz_choices["MAZ_prob"] = maz_probs[np.arange(maz_probs.shape[0]), positions]
taz_choices["prob"] = taz_choices["TAZ_prob"] * taz_choices["MAZ_prob"]
if have_trace_targets:
taz_choices_trace_targets = state.tracing.trace_targets(
taz_choices, slicer="trip_id"
)
trace_taz_choices_df = taz_choices[taz_choices_trace_targets]
state.tracing.trace_df(
trace_taz_choices_df,
label=tracing.extend_trace_label(trace_label, "taz_choices"),
transpose=False,
)
lhs_df = trace_taz_choices_df[["trip_id", DEST_TAZ]]
alt_dest_columns = [f"dest_maz_{c}" for c in range(max_maz_count)]
# following the same logic as the full code, but for trace cutout
trace_maz_counts = maz_counts[taz_choices_trace_targets]
trace_last_row_offsets = maz_counts[taz_choices_trace_targets].cumsum()
trace_inserts = np.repeat(
trace_last_row_offsets, max_maz_count - trace_maz_counts
)
# trace dest_maz_alts
padded_maz_sizes = np.insert(
trace_maz_sizes[DEST_MAZ].values, trace_inserts, 0.0
).reshape(-1, max_maz_count)
df = pd.DataFrame(
data=padded_maz_sizes,
columns=alt_dest_columns,
index=trace_taz_choices_df.index,
)
df = pd.concat([lhs_df, df], axis=1)
state.tracing.trace_df(
df,
label=tracing.extend_trace_label(trace_label, "dest_maz_alts"),
transpose=False,
)
# trace dest_maz_size_terms
padded_maz_sizes = np.insert(
trace_maz_sizes["size_term"].values, trace_inserts, 0.0
).reshape(-1, max_maz_count)
df = pd.DataFrame(
data=padded_maz_sizes,
columns=alt_dest_columns,
index=trace_taz_choices_df.index,
)
df = pd.concat([lhs_df, df], axis=1)
state.tracing.trace_df(
df,
label=tracing.extend_trace_label(trace_label, "dest_maz_size_terms"),
transpose=False,
)
# trace dest_maz_probs
df = pd.DataFrame(
data=maz_probs[taz_choices_trace_targets],
columns=alt_dest_columns,
index=trace_taz_choices_df.index,
)
df = pd.concat([lhs_df, df], axis=1)
df["rand"] = rands[taz_choices_trace_targets]
state.tracing.trace_df(
df,
label=tracing.extend_trace_label(trace_label, "dest_maz_probs"),
transpose=False,
)
taz_choices = taz_choices.drop(columns=["TAZ_prob", "MAZ_prob"])
taz_choices = taz_choices.groupby([chooser_id_col, DEST_MAZ]).agg(
prob=("prob", "max"), pick_count=("prob", "count")
)
taz_choices.reset_index(level=DEST_MAZ, inplace=True)
return taz_choices
@workflow.func
def destination_presample(
state: workflow.State,
primary_purpose,
trips,
alternatives,
model_settings: TripDestinationSettings,
size_term_matrix,
skim_hotel,
network_los,
estimator,
trace_label,
):
trace_label = tracing.extend_trace_label(trace_label, "presample")
chunk_tag = "trip_destination.presample" # distinguish from trip_destination.sample
alt_dest_col_name = model_settings.ALT_DEST_COL_NAME
TAZ_size_term_matrix = aggregate_size_term_matrix(size_term_matrix, network_los)
TRIP_ORIGIN = model_settings.TRIP_ORIGIN
PRIMARY_DEST = model_settings.PRIMARY_DEST
trips_taz = trips.copy()
trips_taz[TRIP_ORIGIN] = network_los.map_maz_to_taz(trips_taz[TRIP_ORIGIN])
trips_taz[PRIMARY_DEST] = network_los.map_maz_to_taz(trips_taz[PRIMARY_DEST])
# alternatives is just an empty dataframe indexed by maz with index name <alt_dest_col_name>
# but logically, we are aggregating so lets do it, as there is no particular gain in being clever
alternatives = alternatives.groupby(
network_los.map_maz_to_taz(alternatives.index)
).sum()
# # i did this but after changing alt_dest_col_name to 'trip_dest' it
# # shouldn't be needed anymore
# alternatives.index.name = ALT_DEST_TAZ
skims = skim_hotel.sample_skims(presample=True)
taz_sample = _destination_sample(
state,
primary_purpose,
trips_taz,
alternatives,
model_settings,
TAZ_size_term_matrix,
skims,
alt_dest_col_name,
estimator,
chunk_tag=chunk_tag,
trace_label=trace_label,
zone_layer="taz",
)
# choose a MAZ for each DEST_TAZ choice, choice probability based on MAZ size_term fraction of TAZ total
maz_sample = choose_MAZ_for_TAZ(
state,
taz_sample,
size_term_matrix,
trips,
network_los,
alt_dest_col_name,
trace_label,
)
assert alt_dest_col_name in maz_sample
return maz_sample
def trip_destination_sample(
state: workflow.State,
primary_purpose,
trips,
alternatives,
model_settings,
size_term_matrix,
skim_hotel,
estimator,
chunk_size,
trace_label,
):
"""
Returns
-------
destination_sample: pandas.dataframe
choices_df from interaction_sample with (up to) sample_size alts for each chooser row
index (non unique) is trip_id from trips (duplicated for each alt)
and columns dest_zone_id, prob, and pick_count
dest_zone_id: int
alt identifier from alternatives[<alt_col_name>]
prob: float
the probability of the chosen alternative
pick_count : int
number of duplicate picks for chooser, alt
"""
trace_label = tracing.extend_trace_label(trace_label, "sample")
assert len(trips) > 0
assert len(alternatives) > 0
# by default, enable presampling for multizone systems, unless they disable it in settings file
network_los = state.get_injectable("network_los")
pre_sample_taz = network_los.zone_system != los.ONE_ZONE
if pre_sample_taz and not state.settings.want_dest_choice_presampling:
pre_sample_taz = False
logger.info(
f"Disabled destination zone presampling for {trace_label} "
f"because 'want_dest_choice_presampling' setting is False"
)
if pre_sample_taz:
logger.info(
"Running %s trip_destination_presample with %d trips"
% (trace_label, len(trips))
)
choices = destination_presample(
state,
primary_purpose,
trips,
alternatives,
model_settings,
size_term_matrix,
skim_hotel,
network_los,
estimator,
trace_label,
)
else:
choices = destination_sample(
state,
primary_purpose,
trips,
alternatives,
model_settings,
size_term_matrix,
skim_hotel,
estimator,
chunk_size,
trace_label,
)
return choices
@workflow.func
def compute_ood_logsums(
state: workflow.State,
choosers,
logsum_settings,
nest_spec,
logsum_spec,
od_skims,
locals_dict,
chunk_size,
trace_label,
chunk_tag,
):
"""
Compute one (of two) out-of-direction logsums for destination alternatives
Will either be trip_origin -> alt_dest or alt_dest -> primary_dest
"""
locals_dict.update(od_skims)
# if preprocessor contains tvpb logsums term, `pathbuilder.get_tvpb_logsum()`
# will get called before a ChunkSizers class object has been instantiated,
# causing pathbuilder to throw an error at L815 due to the assert statement
# in `chunk.chunk_log()` at chunk.py L927. To avoid failing this assertion,
# the preprocessor must be called from within a "null chunker" as follows:
with chunk.chunk_log(
state,
tracing.extend_trace_label(trace_label, "annotate_preprocessor"),
base=True,
):
expressions.annotate_preprocessors(
state, choosers, locals_dict, od_skims, logsum_settings, trace_label
)
logsums = simulate.simple_simulate_logsums(
state,
choosers,
logsum_spec,
nest_spec,
skims=od_skims,
locals_d=locals_dict,
chunk_size=chunk_size,
trace_label=trace_label,
chunk_tag=chunk_tag,
)
assert logsums.index.equals(choosers.index)
# FIXME not strictly necessary, but would make trace files more legible?
# logsums = logsums.replace(-np.inf, -999)
return logsums
def compute_logsums(
state: workflow.State,
primary_purpose,
trips: pd.DataFrame,
destination_sample,
tours_merged: pd.DataFrame,
model_settings: TripDestinationSettings,
skim_hotel,
trace_label: str,
):
"""
Calculate mode choice logsums using the same recipe as for trip_mode_choice, but do it twice
for each alternative since we need out-of-direction logsum
(i.e . origin to alt_dest, and alt_dest to half-tour destination)
Returns
-------
adds od_logsum and dp_logsum columns to trips (in place)
"""
trace_label = tracing.extend_trace_label(trace_label, "compute_logsums")
logger.info("Running %s with %d samples", trace_label, destination_sample.shape[0])
# chunk usage is uniform so better to combine
chunk_tag = "trip_destination.compute_logsums"
# FIXME should pass this in?
network_los = state.get_injectable("network_los")
# - trips_merged - merge trips and tours_merged
trips_merged = pd.merge(
trips, tours_merged, left_on="tour_id", right_index=True, how="left"
)
assert trips_merged.index.equals(trips.index)
# - choosers - merge destination_sample and trips_merged
# re/set index because pandas merge does not preserve left index if it has duplicate values!
choosers = pd.merge(
destination_sample,
trips_merged.reset_index(),
left_index=True,
right_on="trip_id",
how="left",
suffixes=("", "_r"),
).set_index("trip_id")
assert choosers.index.equals(destination_sample.index)
logsum_settings = state.filesystem.read_model_settings(
model_settings.LOGSUM_SETTINGS
)
coefficients = state.filesystem.get_segment_coefficients(
logsum_settings, primary_purpose
)
nest_spec = config.get_logit_model_settings(logsum_settings)
nest_spec = simulate.eval_nest_coefficients(nest_spec, coefficients, trace_label)
logsum_spec = state.filesystem.read_model_spec(file_name=logsum_settings["SPEC"])
logsum_spec = simulate.eval_coefficients(
state, logsum_spec, coefficients, estimator=None
)
locals_dict = {}
locals_dict.update(config.get_model_constants(logsum_settings))
# coefficients can appear in expressions
locals_dict.update(coefficients)
skims = skim_hotel.logsum_skims()
if network_los.zone_system == los.THREE_ZONE:
# TVPB constants can appear in expressions
if logsum_settings.get("use_TVPB_constants", True):
locals_dict.update(
network_los.setting("TVPB_SETTINGS.tour_mode_choice.CONSTANTS")
)
# - od_logsums
od_skims = {
"ORIGIN": model_settings.TRIP_ORIGIN,
"DESTINATION": model_settings.ALT_DEST_COL_NAME,
"odt_skims": skims["odt_skims"],
"dot_skims": skims["dot_skims"],
"od_skims": skims["od_skims"],
"timeframe": "trip",
}
if network_los.zone_system == los.THREE_ZONE:
od_skims.update(
{
"tvpb_logsum_odt": skims["tvpb_logsum_odt"],
"tvpb_logsum_dot": skims["tvpb_logsum_dot"],
}
)
destination_sample["od_logsum"] = compute_ood_logsums(
state,
choosers,
logsum_settings,
nest_spec,
logsum_spec,
od_skims,
locals_dict,
state.settings.chunk_size,
trace_label=tracing.extend_trace_label(trace_label, "od"),
chunk_tag=chunk_tag,
)
# - dp_logsums
dp_skims = {
"ORIGIN": model_settings.ALT_DEST_COL_NAME,
"DESTINATION": model_settings.PRIMARY_DEST,
"odt_skims": skims["dpt_skims"],
"dot_skims": skims["pdt_skims"],
"od_skims": skims["dp_skims"],
}
if network_los.zone_system == los.THREE_ZONE:
dp_skims.update(
{
"tvpb_logsum_odt": skims["tvpb_logsum_dpt"],
"tvpb_logsum_dot": skims["tvpb_logsum_pdt"],
}
)
destination_sample["dp_logsum"] = compute_ood_logsums(
state,
choosers,
logsum_settings,
nest_spec,
logsum_spec,
dp_skims,
locals_dict,
state.settings.chunk_size,
trace_label=tracing.extend_trace_label(trace_label, "dp"),
chunk_tag=chunk_tag,
)
return destination_sample
def trip_destination_simulate(
state: workflow.State,
primary_purpose,
trips,
destination_sample,
model_settings: TripDestinationSettings,
want_logsums,
size_term_matrix,
skim_hotel,
estimator,
trace_label,
):
"""
Chose destination from destination_sample (with od_logsum and dp_logsum columns added)
Returns
-------
choices - pandas.Series
destination alt chosen
"""
trace_label = tracing.extend_trace_label(trace_label, "trip_dest_simulate")
chunk_tag = "trip_destination.simulate"
spec = simulate.spec_for_segment(
state,
None,
spec_id="SPEC",
segment_name=primary_purpose,
estimator=estimator,
spec_file_name=model_settings.SPEC,
coefficients_file_name=model_settings.COEFFICIENTS,
)
if estimator:
estimator.write_choosers(trips)
alt_dest_col_name = model_settings.ALT_DEST_COL_NAME
logger.info("Running trip_destination_simulate with %d trips", len(trips))
skims = skim_hotel.sample_skims(presample=False)
if isinstance(trips["trip_period"].dtype, pd.api.types.CategoricalDtype):
if hasattr(skims["odt_skims"], "map_time_periods"):
trip_period_idx = skims["odt_skims"].map_time_periods(trips)
if trip_period_idx is not None:
trips["trip_period"] = trip_period_idx
elif not np.issubdtype(trips["trip_period"].dtype, np.integer):
if hasattr(skims["odt_skims"], "map_time_periods"):
trip_period_idx = skims["odt_skims"].map_time_periods(trips)
if trip_period_idx is not None:
trips["trip_period"] = trip_period_idx
else:
None
locals_dict = model_settings.CONSTANTS.copy()
locals_dict.update(
{
"size_terms": size_term_matrix,
"size_terms_array": size_term_matrix.df.to_numpy(),
"timeframe": "trip",
"land_use": state.get_dataframe("land_use"),
}
)
locals_dict.update(skims)
log_alt_losers = state.settings.log_alt_losers
destinations = interaction_sample_simulate(
state,
choosers=trips,
alternatives=destination_sample,
spec=spec,
choice_column=alt_dest_col_name,
log_alt_losers=log_alt_losers,
want_logsums=want_logsums,
allow_zero_probs=True,
zero_prob_choice_val=NO_DESTINATION,
skims=skims,
locals_d=locals_dict,
chunk_size=state.settings.chunk_size,
chunk_tag=chunk_tag,
trace_label=trace_label,
trace_choice_name="trip_dest",
estimator=estimator,
)
if not want_logsums:
# for consistency, always return a dataframe with canonical column name
assert isinstance(destinations, pd.Series)
destinations = destinations.to_frame("choice")
if estimator:
# need to overwrite choices here before any failed choices are suppressed
estimator.write_choices(destinations.choice)
destinations.choice = estimator.get_survey_values(
destinations.choice, "trips", "destination"
)
estimator.write_override_choices(destinations.choice)
# drop any failed zero_prob destinations
if (destinations.choice == NO_DESTINATION).any():
# logger.debug("dropping %s failed destinations", (destinations == NO_DESTINATION).sum())
destinations = destinations[destinations.choice != NO_DESTINATION]
return destinations
@workflow.func
def choose_trip_destination(
state: workflow.State,
primary_purpose,
trips,
alternatives,
tours_merged,
model_settings: TripDestinationSettings,
want_logsums,
want_sample_table,
size_term_matrix,
skim_hotel,
estimator,
chunk_size,
trace_label,
):
logger.info("choose_trip_destination %s with %d trips", trace_label, trips.shape[0])
t0 = print_elapsed_time()