-
Notifications
You must be signed in to change notification settings - Fork 3
/
logit.py
823 lines (731 loc) · 30.7 KB
/
logit.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
import numpy
import pandas
import math
from parameters.destination_choice import destination_choice, distance_boundary
from parameters.mode_choice import mode_choice
from parameters.car import car_usage
import parameters.tour_generation as generation_params
import parameters.zone as zone_param
class LogitModel:
"""Generic logit model with mode/destination choice.
Parameters
----------
zone_data : ZoneData
Data used for all demand calculations
purpose : TourPurpose
Tour purpose (type of tour)
resultdata : ResultData
Writer object to result directory
is_agent_model : bool (optional)
Whether the model is used for agent-based simulation
"""
def __init__(self, zone_data, purpose, resultdata, is_agent_model):
self.resultdata = resultdata
self.purpose = purpose
self.bounds = purpose.bounds
self.zone_data = zone_data
self.dest_exps = {}
self.mode_exps = {}
self.dest_choice_param = destination_choice[purpose.name]
self.mode_choice_param = mode_choice[purpose.name]
if is_agent_model:
self.dtype = float
else:
self.dtype = None
def _calc_mode_util(self, impedance):
expsum = numpy.zeros_like(next(iter(impedance["car"].values())), self.dtype)
for mode in self.mode_choice_param:
b = self.mode_choice_param[mode]
utility = numpy.zeros_like(expsum)
self._add_constant(utility, b["constant"])
utility = self._add_zone_util(
utility.T, b["generation"], generation=True).T
self._add_zone_util(utility, b["attraction"])
self._add_impedance(utility, impedance[mode], b["impedance"])
exps = numpy.exp(utility)
self._add_log_impedance(exps, impedance[mode], b["log"])
self.mode_exps[mode] = exps
expsum += exps
return expsum
def _calc_dest_util(self, mode, impedance):
b = self.dest_choice_param[mode]
utility = numpy.zeros_like(next(iter(impedance.values())), self.dtype)
self._add_zone_util(utility, b["attraction"])
self._add_impedance(utility, impedance, b["impedance"])
self.dest_exps[mode] = numpy.exp(utility)
size = numpy.zeros_like(utility)
self._add_zone_util(size, b["size"])
impedance["size"] = size
if "transform" in b:
b_transf = b["transform"]
transimp = numpy.zeros_like(utility)
self._add_zone_util(transimp, b_transf["attraction"])
self._add_impedance(transimp, impedance, b_transf["impedance"])
impedance["transform"] = transimp
self._add_log_impedance(self.dest_exps[mode], impedance, b["log"])
if mode != "logsum":
threshold = distance_boundary[mode]
self.dest_exps[mode][impedance["dist"] > threshold] = 0
try:
return self.dest_exps[mode].sum(1)
except ValueError:
return self.dest_exps[mode].sum()
def _calc_sec_dest_util(self, mode, impedance, orig, dest):
b = self.dest_choice_param[mode]
utility = numpy.zeros_like(next(iter(impedance.values())), self.dtype)
self._add_sec_zone_util(utility, b["attraction"], orig, dest)
self._add_impedance(utility, impedance, b["impedance"])
dest_exps = numpy.exp(utility)
size = numpy.zeros_like(utility)
self._add_sec_zone_util(size, b["size"])
impedance["size"] = size
self._add_log_impedance(dest_exps, impedance, b["log"])
if mode != "logsum":
threshold = distance_boundary[mode]
dest_exps[impedance["dist"] > threshold] = 0
return dest_exps
def _add_constant(self, utility, b):
"""Calculates constant term for utility function.
Parameters
----------
shape : ndarray
An example numpy array which tells the function to what shape the
result will be broadcasted to.
b : float
The value of the constant.
Returns
-------
ndarray
A numpy array of the same size and type as `shape` but filled with
the constant value. The result is to be added to utility.
"""
try: # If only one parameter
utility += b
except ValueError: # Separate params for cap region and surrounding
k = self.zone_data.first_surrounding_zone
if utility.ndim == 1: # 1-d array calculation
utility[:k] += b[0]
utility[k:] += b[1]
else: # 2-d matrix calculation
utility[:k, :] += b[0]
utility[k:, :] += b[1]
def _add_impedance(self, utility, impedance, b):
"""Calculates simple linear impedance terms for utility function.
Parameters
----------
shape : ndarray
An example numpy array which tells the function to what shape the
result will be broadcasted to.
impedance : dict
A dictionary of time-averaged impedance matrices. Includes keys
`time`, `cost`, and `dist` of which values are all ndarrays.
b : float
The parameters for different impedance matrices.
Returns
-------
ndarray
A numpy array of the same size and type as `shape` but filled with
the impedance terms. The result is to be added to utility.
"""
for i in b:
try: # If only one parameter
utility += b[i] * impedance[i]
except ValueError: # Separate params for cap region and surrounding
k = self.zone_data.first_surrounding_zone
utility[:k, :] += b[i][0] * impedance[i][:k, :]
utility[k:, :] += b[i][1] * impedance[i][k:, :]
return utility
def _add_log_impedance(self, exps, impedance, b):
"""Calculates log transformations of impedance for utility function.
This is an optimized way of calculating log terms. Calculates
impedance1^b1 * ... * impedanceN^bN in the following equation:
e^(linear_terms + b1*log(impedance1) + ... + bN*log(impedanceN))
= e^(linear_terms) * impedance1^b1 * ... * impedanceN^bN
Parameters
----------
shape : ndarray
An example numpy array which tells the function to what shape the
result will be broadcasted to.
impedance : dict
A dictionary of time-averaged impedance matrices. Includes keys
`time`, `cost`, and `dist` of which values are all ndarrays.
b : float
The parameters for different impedance matrices.
Returns
-------
ndarray
A numpy array of the same size and type as `shape` but filled with
the impedance terms. The result is to be multiplied with the
exponents of utility.
"""
for i in b:
try: # If only one parameter
exps *= numpy.power(impedance[i] + 1, b[i])
except ValueError: # Separate params for cap region and surrounding
k = self.zone_data.first_surrounding_zone
exps[:k, :] *= numpy.power(impedance[i][:k, :] + 1, b[i][0])
exps[k:, :] *= numpy.power(impedance[i][k:, :] + 1, b[i][1])
return exps
def _add_zone_util(self, utility, b, generation=False):
"""Calculates simple linear zone terms for utility function.
Parameters
----------
shape : ndarray
An example numpy array which tells the function to what shape the
result will be broadcasted to.
b : float
The parameters for different zone data.
generation : bool
Whether the effect of the zone term is added only to the
geographical area in which this model is used based on the
`self.bounds` attribute of this class.
Returns
-------
ndarray
A numpy array of the same size and type as `shape` but filled with
the zone terms. The result is to be added to utility.
"""
zdata = self.zone_data
for i in b:
try: # If only one parameter
utility += b[i] * zdata.get_data(i, self.bounds, generation)
except ValueError: # Separate params for cap region and surrounding
k = self.zone_data.first_surrounding_zone
data_capital_region = zdata.get_data(
i, self.bounds, generation, zdata.CAPITAL_REGION)
data_surrounding = zdata.get_data(
i, self.bounds, generation, zdata.SURROUNDING_AREA)
if utility.ndim == 1: # 1-d array calculation
utility[:k] += b[i][0] * data_capital_region
utility[k:] += b[i][1] * data_surrounding
else: # 2-d matrix calculation
utility[:k, :] += b[i][0] * data_capital_region
utility[k:, :] += b[i][1] * data_surrounding
return utility
def _add_sec_zone_util(self, utility, b, orig=None, dest=None):
zdata = self.zone_data
for i in b:
data = zdata.get_data(i, self.bounds, generation=True)
try: # If only one parameter
utility += b[i] * data
except ValueError: # Separate params for orig and dest
u = self.zone_data.first_peripheral_zone
utility += b[i][0] * data[orig, :u]
utility += b[i][1] * data[dest, :u]
return utility
def _add_log_zone_util(self, exps, b, generation=False):
"""Calculates log transformations of zone data for utility function.
This is an optimized way of calculating log terms. Calculates
zonedata1^b1 * ... * zonedataN^bN in the following equation:
e^(linear_terms + b1*log(zonedata1) + ... + bN*log(zonedataN))
= e^(linear_terms) * zonedata1^b1 * ... * zonedataN^bN
Parameters
----------
shape : ndarray
An example numpy array which tells the function to what shape the
result will be broadcasted to.
b : float
The parameters for different zone data.
generation : bool
Whether the effect of the zone term is added only to the
geographical area in which this model is used based on the
`self.bounds` attribute of this class.
Returns
-------
ndarray
A numpy array of the same size and type as `shape` but filled with
the zone terms. The result is to be multiplied with the
exponents of utility.
"""
zdata = self.zone_data
for i in b:
exps *= numpy.power(
zdata.get_data(i, self.bounds, generation) + 1, b[i])
return exps
class ModeDestModel(LogitModel):
"""Nested logit model with mode choice in upper level.
Uses logsums from destination choice model as utility
in mode choice model.
choice
/ \\
m1 m2
/ \\ / \\
d1 d2 d1 d2
Parameters
----------
zone_data : ZoneData
Data used for all demand calculations
purpose : TourPurpose
Tour purpose (type of tour)
resultdata : ResultData
Writer object to result directory
is_agent_model : bool (optional)
Whether the model is used for agent-based simulation
"""
def calc_prob(self, impedance):
"""Calculate matrix of choice probabilities.
First calculates basic probabilities. Then inserts individual
dummy variables by calling `calc_individual_prob()`.
Parameters
----------
impedance : dict
Mode (car/transit/bike/walk) : dict
Type (time/cost/dist) : numpy 2-d matrix
Impedances
Returns
-------
dict
Mode (car/transit/bike/walk) : numpy 2-d matrix
Choice probabilities
"""
prob = self.calc_basic_prob(impedance)
for mod_mode in self.mode_choice_param:
for i in self.mode_choice_param[mod_mode]["individual_dummy"]:
dummy_share = self.zone_data.get_data(
i, self.bounds, generation=True)
ind_prob = self.calc_individual_prob(mod_mode, i)
for mode in prob:
no_dummy = (1 - dummy_share) * prob[mode]
dummy = dummy_share * ind_prob[mode]
prob[mode] = no_dummy + dummy
return prob
def calc_basic_prob(self, impedance):
"""Calculate matrix of mode and destination choice probabilities.
Individual dummy variables are not included.
Parameters
----------
impedance : dict
Mode (car/transit/bike/walk) : dict
Type (time/cost/dist) : numpy 2-d matrix
Impedances
Returns
-------
dict
Mode (car/transit/bike/walk) : numpy 2-d matrix
Choice probabilities
"""
mode_expsum = self._calc_utils(impedance)
logsum = numpy.log(mode_expsum)
self.resultdata.print_data(
pandas.Series(logsum, self.purpose.zone_numbers),
"accessibility.txt", self.zone_data.zone_numbers, self.purpose.name)
return self._calc_prob(mode_expsum)
def calc_individual_prob(self, mod_mode, dummy):
"""Calculate matrix of probabilities with individual dummies.
Calculate matrix of mode and destination choice probabilities
with individual dummy variable included.
Parameters
----------
mod_mode : str
The mode for which the utility will be modified
dummy : str
The name of the individual dummy
Returns
-------
dict
Mode (car/transit/bike/walk) : numpy 2-d matrix
Choice probabilities
"""
k = self.zone_data.first_surrounding_zone
b = self.mode_choice_param[mod_mode]["individual_dummy"][dummy]
try:
self.mode_exps[mod_mode] *= numpy.exp(b)
except ValueError:
self.mode_exps[mod_mode][:k] *= numpy.exp(b[0])
self.mode_exps[mod_mode][k:] *= numpy.exp(b[1])
mode_expsum = numpy.zeros_like(self.mode_exps[mod_mode])
for mode in self.mode_choice_param:
mode_expsum += self.mode_exps[mode]
return self._calc_prob(mode_expsum)
def calc_individual_mode_prob(self, is_car_user, zone):
"""Calculate individual choice probabilities with individual dummies.
Calculate mode choice probabilities for individual
agent with individual dummy variable included.
Parameters
----------
is_car_user : bool
Whether the agent is car user or not
zone : int
Index of zone where the agent lives
Returns
-------
list
float
Choice probabilities for purpose modes
"""
mode_exps = {}
mode_expsum = 0
for mode in self.mode_choice_param:
mode_exps[mode] = self.mode_exps[mode][zone]
b = self.mode_choice_param[mode]["individual_dummy"]
if is_car_user and "car_users" in b:
try:
mode_exps[mode] *= math.exp(b["car_users"])
except TypeError:
if zone < self.zone_data.first_surrounding_zone:
mode_exps[mode] *= math.exp(b["car_users"][0])
else:
mode_exps[mode] *= math.exp(b["car_users"][1])
mode_expsum += mode_exps[mode]
probs = []
for mode in self.purpose.modes:
probs.append(mode_exps[mode] / mode_expsum)
return probs
def _calc_utils(self, impedance):
self.dest_expsums = {}
for mode in self.dest_choice_param:
expsum = self._calc_dest_util(mode, impedance[mode])
self.dest_expsums[mode] = {}
self.dest_expsums[mode]["logsum"] = expsum
logsum = pandas.Series(numpy.log(expsum), self.purpose.zone_numbers)
label = self.purpose.name + "_" + mode[0]
self.zone_data._values[label] = logsum
self.resultdata.print_data(
logsum, "accessibility.txt",
self.zone_data.zone_numbers, label)
return self._calc_mode_util(self.dest_expsums)
def _calc_prob(self, mode_expsum):
prob = {}
self.mode_prob = {}
self.dest_prob = {}
for mode in self.mode_choice_param:
self.mode_prob[mode] = self.mode_exps[mode] / mode_expsum
dest_expsum = self.dest_expsums[mode]["logsum"]
self.dest_prob[mode] = self.dest_exps[mode].T / dest_expsum
prob[mode] = self.mode_prob[mode] * self.dest_prob[mode]
return prob
class DestModeModel(LogitModel):
"""Nested logit model with destination choice in upper level.
Used only in peripheral non-home source model.
Uses logsums from mode choice model as utility
in destination choice model.
choice
/ \\
d1 d2
/ \\ / \\
m1 m2 m1 m2
Parameters
----------
zone_data : ZoneData
Data used for all demand calculations
purpose : TourPurpose
Tour purpose (type of tour)
resultdata : ResultData
Writer object to result directory
is_agent_model : bool (optional)
Whether the model is used for agent-based simulation
"""
def calc_prob(self, impedance):
"""Calculate matrix of choice probabilities.
Parameters
----------
impedance : dict
Mode (car/transit/bike/walk) : dict
Type (time/cost/dist) : numpy 2-d matrix
Impedances
Returns
-------
dict
Mode (car/transit/bike/walk) : numpy 2-d matrix
Choice probabilities
"""
mode_expsum = self._calc_mode_util(impedance)
logsum = {"logsum": mode_expsum}
dest_expsum = self._calc_dest_util("logsum", logsum)
prob = {}
dest_prob = self.dest_exps["logsum"].T / dest_expsum
for mode in self.mode_choice_param:
mode_prob = (self.mode_exps[mode] / mode_expsum).T
prob[mode] = mode_prob * dest_prob
return prob
class SecDestModel(LogitModel):
"""Logit model for secondary destination choice.
Attaches secondary destinations to tours with already calculated
modes and destinations.
Parameters
----------
zone_data : ZoneData
Data used for all demand calculations
purpose : TourPurpose
Tour purpose (type of tour)
resultdata : ResultData
Writer object to result directory
is_agent_model : bool (optional)
Whether the model is used for agent-based simulation
"""
def calc_prob(self, mode, impedance, origin, destination=None):
"""Calculate matrix of choice probabilities.
Parameters
----------
mode : str
Mode (car/transit/bike)
impedance : dict
Type (time/cost/dist) : numpy 2d matrix
Impedances
origin: int
Origin zone index
destination: int or ndarray (optional)
Destination zone index or boolean array (if calculation for
all primary destinations is performed in parallel)
Returns
-------
numpy 2-d matrix
Choice probabilities
"""
dest_exps = self._calc_sec_dest_util(mode, impedance, origin, destination)
try:
expsum = dest_exps.sum(1)
except ValueError:
expsum = dest_exps.sum()
prob = dest_exps.T / expsum
return prob
class OriginModel(DestModeModel):
pass
class TourCombinationModel:
"""Nested logit model for tour combination choice.
Number of tours per day is the upper level of the model and each
number-of-tour nest can have different combinations of tours
(e.g., a two-tour combination can be hw-ho, hw-hs or ho-ho, etc.).
Base for tour generation.
Parameters
----------
zone_data : ZoneData
Data used for all demand calculations
"""
def __init__(self, zone_data):
self.zone_data = zone_data
self.param = generation_params.tour_combinations
self.conditions = generation_params.tour_conditions
self.increases = generation_params.tour_number_increase
def calc_prob(self, age_group, is_car_user, zones):
"""Calculate choice probabilities for each tour combination.
Calculation is done for one specific population group
(age + is car user or not) and probabilities are returned for every
possible tour combination.
Parameters
----------
age_group : str
Age group (age_7-17/age_18-29/...)
is_car_user : bool
True if is car user
zones : int or slice
Zone number (for agent model) or zone data slice
Returns
-------
dict
key : tuple of str
Tour combination (-/hw/hw-ho/...)
value : float or numpy 1-d array
Choice probability
"""
prob = {}
nr_tours_exps = {}
nr_tours_expsum = 0
for nr_tours in self.param:
# Upper level of nested logit model
combination_exps = {}
combination_expsum = 0
for tour_combination in self.param[nr_tours]:
# Lower level of nested logit model
if tour_combination in self.conditions:
if self.conditions[tour_combination][0]:
# If this tour pattern is exclusively for one age group
if age_group == self.conditions[tour_combination][1]:
is_allowed = True
else:
is_allowed = False
else:
# If one age group is excluded from this tour pattern
if age_group == self.conditions[tour_combination][1]:
is_allowed = False
else:
is_allowed = True
else:
is_allowed = True
if is_allowed:
param = self.param[nr_tours][tour_combination]
util = 0
util += param["constant"]
for i in param["zone"]:
util += param["zone"][i] * self.zone_data[i][zones]
dummies = param["individual_dummy"]
if age_group in dummies:
util += dummies[age_group]
if is_car_user and "car_users" in dummies:
util += dummies["car_users"]
combination_exps[tour_combination] = numpy.exp(util)
else:
combination_exps[tour_combination] = 0
combination_expsum += combination_exps[tour_combination]
for tour_combination in self.param[nr_tours]:
try:
prob[tour_combination] = ( combination_exps[tour_combination]
/ combination_expsum)
except ZeroDivisionError:
# Specifically, no 4-tour patterns are allowed for
# 7-17-year-olds, so sum will be zero in this case
prob[tour_combination] = 0
util = 0
nr_tours_exps[nr_tours] = numpy.exp(util)
scale_param = generation_params.tour_number_scale
nr_tours_exps[nr_tours] *= numpy.power(combination_expsum, scale_param)
nr_tours_expsum += nr_tours_exps[nr_tours]
# Probability of no tours at all (empty tuple) is deduced from
# other combinations (after calibration)
prob[()] = 1
for nr_tours in self.param:
if nr_tours != 0:
nr_tours_prob = nr_tours_exps[nr_tours] / nr_tours_expsum
# Tour number probability is calibrated
nr_tours_prob *= self.increases[nr_tours]
prob[()] -= nr_tours_prob
for tour_combination in self.param[nr_tours]:
# Upper and lower level probabilities are combined
prob[tour_combination] *= nr_tours_prob
return prob
class CarUseModel(LogitModel):
"""Binary logit model for car use.
Parameters
----------
zone_data : ZoneData
Data used for all demand calculations
bounds : slice
Zone bounds
age_groups : tuple
tuple
int
Age intervals
resultdata : ResultData
Writer object to result directory
"""
def __init__(self, zone_data, bounds, age_groups, resultdata):
self.resultdata = resultdata
self.zone_data = zone_data
self.bounds = bounds
self.genders = ("female", "male")
self.age_groups = age_groups
self.param = car_usage
for i in self.param["individual_dummy"]:
self._check(i)
def _check(self, dummy):
try:
age_interval = dummy.split('_')[1]
except AttributeError:
# If the dummy is for a compound segment (age + gender)
age_interval = dummy[0].split('_')[1]
if dummy[1] not in self.genders:
raise AttributeError(
"Car use dummy name {} not valid".format(dummy[1]))
if tuple(map(int, age_interval.split('-'))) not in self.age_groups:
raise AttributeError(
"Car use dummy name {} not valid".format(age_interval))
def calc_basic_prob(self):
"""Calculate car user probabilities without individual dummies.
Returns
-------
numpy.ndarray
Choice probabilities
"""
b = self.param
utility = numpy.zeros(self.bounds.stop)
self._add_constant(utility, b["constant"])
self._add_zone_util(utility, b["generation"], True)
self.exps = numpy.exp(utility)
self._add_log_zone_util(self.exps, b["log"], True)
prob = self.exps / (self.exps+1)
return prob
def calc_prob(self):
"""Calculate car user probabilities with individual dummies included.
Returns
-------
pandas.Series
Choice probabilities
"""
prob = self.calc_basic_prob()
no_dummy_share = 1
dummy_prob = 0
b = self.param
for i in b["individual_dummy"]:
try:
dummy_share = self.zone_data.get_data(
"share_"+i, self.bounds, generation=True)
except TypeError:
# If the dummy is for a compound segment (age + gender)
dummy_share = numpy.ones_like(prob)
for j in i:
dummy_share *= self.zone_data.get_data(
"share_"+j, self.bounds, generation=True)
no_dummy_share -= dummy_share
ind_exps = numpy.exp(b["individual_dummy"][i]) * self.exps
ind_prob = ind_exps / (ind_exps+1)
dummy_prob += dummy_share * ind_prob
no_dummy_prob = no_dummy_share * prob
prob = no_dummy_prob + dummy_prob
prob = pandas.Series(
prob, self.zone_data.zone_numbers[self.bounds])
self.print_results(prob)
return prob
def calc_individual_prob(self, age_group, gender, zone=None):
"""Calculate car user probability with individual dummies included.
Uses results from previously run `calc_basic_prob()`.
Parameters
----------
age_group : str
Agent/segment age group
gender : str
Agent/segment gender (female/male)
zone : int (optional)
Index of zone where the agent lives, if no zone index is given,
calculation is done for all zones
Returns
-------
numpy.ndarray
Choice probabilities
"""
self._check((age_group, gender))
if zone is None:
exp = self.exps
else:
exp = self.exps[self.zone_data.zone_index(zone)]
b = self.param
if age_group in b["individual_dummy"]:
exp = numpy.exp(b["individual_dummy"][age_group]) * exp
if (age_group, gender) in b["individual_dummy"]:
exp = numpy.exp(b["individual_dummy"][(age_group, gender)]) * exp
prob = exp / (exp+1)
return prob
def print_results(self, prob):
""" Print results, mainly for calibration purposes"""
population = self.zone_data["population"]
population_7_99 = ( population[:self.zone_data.first_peripheral_zone]
* self.zone_data["share_age_7-99"] )
car_users = prob * population_7_99
# Print car user share by zone
self.resultdata.print_data(prob,
"car_use.txt",
self.zone_data.zone_numbers[self.bounds],
"car_use")
# print car use share by municipality
prob_municipality = []
for municipality in zone_param.municipalities:
i = slice(zone_param.municipalities[municipality][0],
zone_param.municipalities[municipality][1])
# comparison data has car user shares of population
# over 6 years old (from HEHA)
prob_municipality.append(car_users.loc[i].sum() / population_7_99.loc[i].sum())
self.resultdata.print_data(prob_municipality,
"car_use_per_municipality.txt",
zone_param.municipalities.keys(),
"car_use")
# print car use share by area (to get Helsinki CBD vs. Helsinki other)
prob_area = []
for area in zone_param.areas:
i = slice(zone_param.areas[area][0],
zone_param.areas[area][1])
# comparison data has car user shares of population
# over 6 years old (from HEHA)
prob_area.append(car_users.loc[i].sum() / population_7_99.loc[i].sum())
self.resultdata.print_data(prob_area,
"car_use_per_area.txt",
zone_param.areas.keys(),
"car_use")