-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmodels.py
2486 lines (2159 loc) · 91.5 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import time
import yaml
import operator
from multiprocessing import Pool
from collections import defaultdict
import pickle
import numpy as np
import orca
import pandana as pdna
import pandas as pd
from urbansim.models import transition, relocation
from urbansim.utils import misc, networks
from urbansim_parcels import utils as parcel_utils
import utils
import lcm_utils
import dataset
import variables
from functools import reduce
# Set up location choice model objects.
# Register as injectable to be used throughout simulation
location_choice_models = {}
hlcm_step_names = []
elcm_step_names = []
model_configs = lcm_utils.get_model_category_configs()
for model_category_name, model_category_attributes in model_configs.items():
if model_category_attributes["model_type"] == "location_choice":
model_config_files = model_category_attributes["config_filenames"]
for model_config in model_config_files:
model = lcm_utils.create_lcm_from_config(
model_config, model_category_attributes
)
location_choice_models[model.name] = model
if model_category_name == "hlcm":
hlcm_step_names.append(model.name)
if model_category_name == "elcm":
elcm_step_names.append(model.name)
orca.add_injectable("location_choice_models", location_choice_models)
orca.add_injectable("hlcm_step_names", sorted(hlcm_step_names, reverse=True))
# run elcm by specific job_sector sequence defined below
elcm_sector_order = [3, 6, 10, 11, 14, 9, 4, 2, 5, 16, 17, 8]
elcm_sector_order = {sector: idx for idx, sector in enumerate(elcm_sector_order)}
orca.add_injectable(
"elcm_step_names",
sorted(elcm_step_names, key=lambda x: elcm_sector_order[int(x[5:]) // 100000]),
)
for name, model in list(location_choice_models.items()):
lcm_utils.register_choice_model_step(model.name, model.choosers)
@orca.step()
def elcm_home_based(jobs, households):
wrap_jobs = jobs
_print_number_unplaced(wrap_jobs, "building_id")
jobs = wrap_jobs.to_frame(["building_id", "home_based_status", "large_area_id"])
jobs = jobs[(jobs.home_based_status >= 1) & (jobs.building_id == -1)]
hh = households.to_frame(["building_id", "large_area_id", "sp_filter"])
hh = hh[(hh.building_id > 0) & (hh.sp_filter >= 0)]
for la, la_job in jobs.groupby("large_area_id"):
la_hh = hh[hh.large_area_id == la]
la_job["building_id"] = la_hh.sample(
len(la_job), replace=True
).building_id.values
wrap_jobs.update_col_from_series(
"building_id", la_job["building_id"], cast=True
)
_print_number_unplaced(wrap_jobs, "building_id")
@orca.injectable("mcd_hu_sampling_config")
def mcd_hu_sampling_config():
# load mcd_hu_sampling step config file
with open(os.path.join(misc.configs_dir(), "mcd_hu_sampling.yaml")) as f:
cfg = yaml.load(f, Loader=yaml.FullLoader)
return cfg
@orca.step()
def mcd_hu_sampling(buildings, households, mcd_total, bg_hh_increase):
"""
Apply the mcd total forecast to Limit and calculate the pool of housing
units to match the distribution of the mcd_total growth table for the MCD
Parameters
----------
buildings : orca.DataFrameWrapper
Buildings table
households : orca.DataFrameWrapper
Households table
mcd_total : orca.DataFrameWrapper
MCD total table
bg_hh_increase : orca.DataFrameWrapper
hh growth trend by block groups
Returns
-------
None
"""
# get current year
year = orca.get_injectable("year")
# get config
config = orca.get_injectable("mcd_hu_sampling_config")
vacant_variable = config["vacant_variable"]
# get housing unit table from buildings
blds = buildings.to_frame(
[
"building_id",
"semmcd",
vacant_variable,
"building_age",
"geoid",
"mcd_model_quota",
"hu_filter",
"sp_filter",
]
)
# get vacant units with index and value >0
vacant_units = blds[vacant_variable]
vacant_units = vacant_units[vacant_units.index.values >= 0]
vacant_units = vacant_units[vacant_units > 0]
# generate housing units from vacant units
indexes = np.repeat(vacant_units.index.values, vacant_units.values.astype("int"))
housing_units = blds.loc[indexes]
# the mcd_total for year
mcd_total = mcd_total.to_frame([str(year)])
# get current inplaced households
hh = households.to_frame(["semmcd", "building_id"])
hh = hh[hh.building_id != -1]
# groupby semmcd and get count
hh_by_city = hh.groupby("semmcd").size()
# get the expected growth
# growth = target_year_hh - current_hh
mcd_growth = mcd_total[str(year)] - hh_by_city
# temp set NaN growth to 0
if mcd_growth.isna().sum() > 0:
print("Warning: NaN exists in mcd_growth, replaced them with 0")
mcd_growth = mcd_growth.fillna(0).astype(int)
# Calculate using Block group HH count trend data
bg_hh_increase = bg_hh_increase.to_frame()
# use occupied, 3 year window trend = y_i - y_i-3
bg_trend = bg_hh_increase.occupied - bg_hh_increase.previous_occupied
bg_trend_norm_by_bg = (bg_trend - bg_trend.mean()) / bg_trend.std()
bg_trend_norm_by_bg.name = "bg_trend"
# init output mcd_model_quota Series
new_units = pd.Series()
# only selecting growth > 0
mcd_growth = mcd_growth[mcd_growth > 0]
# loop through mcd growth target
for city in mcd_growth.index:
# for each city, make n_units = n_choosers
# sorted housing units by year built and bg growth trend
# get valid city housing units for sampling
city_units = housing_units[
(housing_units.semmcd == city)
& (
# only sampling hu_filter == 0
housing_units.hu_filter
== 0
)
& (
# only sampling sp_filter >= 0
housing_units.sp_filter
>= 0
)
]
# building_age normalized
building_age = city_units.building_age
building_age_norm = (building_age - building_age.mean()) / building_age.std()
# bg trend normalized
bg_trend_norm = (
city_units[["geoid"]]
.join(bg_trend_norm_by_bg, how="left", on="geoid")
.bg_trend
).fillna(0)
# sum of normalized score
normalized_score = (-building_age_norm) + bg_trend_norm
# set name to score
normalized_score.name = "score"
# use absolute index for sorting
normalized_score = normalized_score.reset_index()
# sorted by the score from high to low
normalized_score = normalized_score.sort_values(
by="score", ascending=False, ignore_index=False
)
# apply sorted index back to city_units
city_units = city_units.iloc[normalized_score.index]
# .sort_values(by='building_age', ascending=True)
# pick the top k units
growth = mcd_growth.loc[city]
selected_units = city_units.iloc[:growth]
if selected_units.shape[0] != growth:
# mcd didn't match target due to lack of HU
print(
"MCD %s have %s housing unit but expected growth is %s"
% (city, selected_units.shape[0], growth)
)
new_units = pd.concat([new_units, selected_units])
# add mcd model quota to building table
quota = new_units.index.value_counts()
# !!important!! clean-up mcd_model_quota from last year before updating it
buildings.update_col_from_series(
"mcd_model_quota", pd.Series(0, index=blds.index), cast=True
)
# init new mcd_model_quota
mcd_model_quota = pd.Series(0, index=blds.index)
mcd_model_quota.loc[quota.index] = quota.values
# update mcd_model_quota in buildings table
buildings.update_col_from_series("mcd_model_quota", mcd_model_quota, cast=True)
@orca.step()
def update_bg_hh_increase(bg_hh_increase, households):
"""
Update the block group household growth trend table used in the MCD sampling process.
Args:
bg_hh_increase (DataFrameWrapper): Blockgroup household growth trend table.
households (DataFrameWrapper): Households table.
Returns:
None
"""
# Base year 2020
base_year = 2020
year = orca.get_injectable("year")
year_diff = year - base_year
hh = households.to_frame(["geoid"]).reset_index()
hh_by_bg = hh.groupby("geoid").count().household_id
bg_hh = bg_hh_increase.to_frame()
# Move occupied hh count one year down
# 2->3, 1->2, 0->1
bg_hh["occupied_year_minus_3"] = bg_hh["occupied_year_minus_2"]
bg_hh["occupied_year_minus_2"] = bg_hh["occupied_year_minus_1"]
bg_hh["occupied_year_minus_1"] = hh_by_bg.fillna(0).astype("int")
# If the first few years, save the bg summary and use 2014 and 2019 data
if year_diff > 4:
# Update columns used for trend analysis
bg_hh["occupied"] = hh_by_bg
bg_hh["previous_occupied"] = bg_hh["occupied_year_minus_3"]
# Update bg_hh_increase table
orca.add_table("bg_hh_increase", bg_hh)
@orca.step()
def diagnostic(parcels, buildings, jobs, households, nodes, iter_var):
parcels = parcels.to_frame()
buildings = buildings.to_frame()
jobs = jobs.to_frame()
households = households.to_frame()
nodes = nodes.to_frame()
import pdb
pdb.set_trace()
def make_repm_func(model_name, yaml_file, dep_var):
"""
Generator function for single-model REPMs.
"""
@orca.step(model_name)
def func():
buildings = orca.get_table("buildings")
nodes_walk = orca.get_table("nodes_walk")
print(yaml_file)
return utils.hedonic_simulate(yaml_file, buildings, nodes_walk, dep_var)
return func
repm_step_names = []
for repm_config in os.listdir(os.path.join(misc.models_dir(), "repm_2050")):
model_name = repm_config.split(".")[0]
if repm_config.startswith("res"):
dep_var = "sqft_price_res"
elif repm_config.startswith("nonres"):
dep_var = "sqft_price_nonres"
make_repm_func(model_name, "repm_2050/" + repm_config, dep_var)
repm_step_names.append(model_name)
orca.add_injectable("repm_step_names", repm_step_names)
@orca.step()
def increase_property_values(buildings, income_growth_rates):
# Hack to make more feasibility
# dfinc = pd.read_csv("income_growth_rates.csv", index_col=['year'])
dfinc = income_growth_rates.to_frame().loc[: orca.get_injectable("year")]
dfrates = (
dfinc.prod().to_frame(name="cumu_rates").fillna(1.0)
) # get cumulative increase from base to current year
dfrates.index = dfrates.index.astype(float)
bd = buildings.to_frame(["large_area_id", "sqft_price_res", "sqft_price_nonres"])
bd = pd.merge(bd, dfrates, left_on="large_area_id", right_index=True, how="left")
buildings.update_col_from_series(
"sqft_price_res", bd.sqft_price_res * bd.cumu_rates
)
buildings.update_col_from_series(
"sqft_price_nonres", bd.sqft_price_nonres * bd.cumu_rates
)
@orca.step()
def households_relocation(households, annual_relocation_rates_for_households):
relocation_rates = annual_relocation_rates_for_households.to_frame()
relocation_rates = relocation_rates.rename(
columns={"age_max": "age_of_head_max", "age_min": "age_of_head_min"}
)
relocation_rates.probability_of_relocating *= 0.2
reloc = relocation.RelocationModel(relocation_rates, "probability_of_relocating")
_print_number_unplaced(households, "building_id")
print("un-placing")
hh = households.to_frame(households.local_columns)
idx_reloc = reloc.find_movers(hh)
households.update_col_from_series(
"building_id", pd.Series(-1, index=idx_reloc), cast=True
)
_print_number_unplaced(households, "building_id")
@orca.step()
def households_relocation_2050(households, annual_relocation_rates_for_households):
relocation_rates = annual_relocation_rates_for_households.to_frame()
relocation_rates = relocation_rates.rename(
columns={"age_max": "age_of_head_max", "age_min": "age_of_head_min"}
)
relocation_rates.probability_of_relocating *= 0.2
reloc = relocation.RelocationModel(relocation_rates, "probability_of_relocating")
_print_number_unplaced(households, "building_id")
print("un-placing")
hh = households.to_frame(households.local_columns)
# block all event buildings and special buildings (sp_filter<0)
bb = orca.get_table("buildings").to_frame(orca.get_table("buildings").local_columns)
blocklst = bb.loc[bb.sp_filter < 0].index
hh = hh.loc[~hh.building_id.isin(blocklst)]
idx_reloc = reloc.find_movers(hh)
households.update_col_from_series(
"building_id", pd.Series(-1, index=idx_reloc), cast=True
)
_print_number_unplaced(households, "building_id")
@orca.step()
def jobs_relocation_2050(jobs, annual_relocation_rates_for_jobs):
relocation_rates = annual_relocation_rates_for_jobs.to_frame().reset_index()
reloc = relocation.RelocationModel(relocation_rates, "job_relocation_probability")
_print_number_unplaced(jobs, "building_id")
print("un-placing")
j = jobs.to_frame(jobs.local_columns)
# block all event buildings and special buildings (sp_filter<0)
bb = orca.get_table("buildings").to_frame(orca.get_table("buildings").local_columns)
blocklst = bb.loc[bb.sp_filter < 0].index
j = j.loc[~j.building_id.isin(blocklst)]
idx_reloc = reloc.find_movers(j[j.home_based_status <= 0])
jobs.update_col_from_series(
"building_id", pd.Series(-1, index=idx_reloc), cast=True
)
_print_number_unplaced(jobs, "building_id")
@orca.step()
def jobs_relocation(jobs, annual_relocation_rates_for_jobs):
relocation_rates = annual_relocation_rates_for_jobs.to_frame().reset_index()
reloc = relocation.RelocationModel(relocation_rates, "job_relocation_probability")
_print_number_unplaced(jobs, "building_id")
print("un-placing")
j = jobs.to_frame(jobs.local_columns)
idx_reloc = reloc.find_movers(j[j.home_based_status <= 0])
jobs.update_col_from_series(
"building_id", pd.Series(-1, index=idx_reloc), cast=True
)
_print_number_unplaced(jobs, "building_id")
def presses_trans(xxx_todo_changeme1):
(ct, hh, p, target, iter_var) = xxx_todo_changeme1
ct_finite = ct[ct.persons_max <= 100]
ct_inf = ct[ct.persons_max > 100]
tran = transition.TabularTotalsTransition(ct_finite, "total_number_of_households")
model = transition.TransitionModel(tran)
new, added_hh_idx, new_linked = model.transition(
hh, iter_var, linked_tables={"linked": (p, "household_id")}
)
new.loc[added_hh_idx, "building_id"] = -1
pers = new_linked["linked"]
pers = pers[pers.household_id.isin(new.index)]
new.index.name = "household_id"
pers.index.name = "person_id"
out = [[new, pers]]
target -= len(pers)
best_qal = np.inf
best = []
for _ in range(3):
# if there is no HH to transition for ct_inf, break
if (
sum(
[
utils.filter_table(
hh, r, ignore={"total_number_of_households"}
).shape[0]
for _, r in ct_inf.loc[iter_var].iterrows()
]
)
== 0
):
# add empty hh and persons dh
new = hh.loc[[]]
pers = p.loc[[]]
best = (new, pers)
break
tran = transition.TabularTotalsTransition(ct_inf, "total_number_of_households")
model = transition.TransitionModel(tran)
new, added_hh_idx, new_linked = model.transition(
hh, iter_var, linked_tables={"linked": (p, "household_id")}
)
new.loc[added_hh_idx, "building_id"] = -1
pers = new_linked["linked"]
pers = pers[pers.household_id.isin(new.index)]
qal = abs(target - len(pers))
if qal < best_qal:
new.index.name = "household_id"
pers.index.name = "person_id"
best = (new, pers)
best_qal = qal
out.append(best)
return out
@orca.step()
def households_transition(
households, persons, annual_household_control_totals, remi_pop_total, iter_var
):
region_ct = annual_household_control_totals.to_frame()
max_cols = region_ct.columns[region_ct.columns.str.endswith("_max")]
region_ct[max_cols] = region_ct[max_cols].replace(-1, np.inf)
region_ct[max_cols] += 1
region_hh = households.to_frame(households.local_columns + ["large_area_id"])
region_p = persons.to_frame(persons.local_columns)
region_p.index = region_p.index.astype(int)
if "changed_hhs" in orca.list_tables():
## add changed hhs and persons from previous year back (ensure transition sample availability )
changed_hhs = orca.get_table("changed_hhs").local
changed_hhs.index += region_hh.index.max()
changed_ps = orca.get_table("changed_ps").local
changed_ps.index += region_p.index.max()
changed_ps["household_id"] = changed_ps["household_id"] + region_hh.index.max()
region_hh = pd.concat([region_hh, changed_hhs])
region_p = pd.concat([region_p, changed_ps])
region_hh.index = region_hh.index.astype(int)
region_p.index = region_p.index.astype(int)
region_target = remi_pop_total.to_frame()
def cut_to_la(xxx_todo_changeme):
(large_area_id, hh) = xxx_todo_changeme
p = region_p[region_p.household_id.isin(hh.index)]
target = int(region_target.loc[large_area_id, str(iter_var)])
ct = region_ct[region_ct.large_area_id == large_area_id]
del ct["large_area_id"]
return ct, hh, p, target, iter_var
arg_per_la = list(map(cut_to_la, region_hh.groupby("large_area_id")))
pool = Pool(6)
cunks_per_la = pool.map(presses_trans, arg_per_la)
pool.close()
pool.join()
out = reduce(operator.concat, cunks_per_la)
# Sync for testing
# out = []
# for la_arg in arg_per_la:
# out.append(presses_trans(la_arg))
# fix indexes
hhidmax = region_hh.index.values.max() + 1
pidmax = region_p.index.values.max() + 1
## create {old_hh_id => new_hh_id} mapping
hh_id_mapping = [x[0]["building_id"] for x in out]
# list of number of hh added for each df in the hh_id_mapping
hh_new_added = [(x == -1).sum() for x in hh_id_mapping]
# cumulative sum for hh_new_added, add 0 at front
hh_new_added_cumsum = [0] + list(np.cumsum(hh_new_added))
for i, hhmap in enumerate(hh_id_mapping):
## create seperate mapping for each df in the list
hhmap = hhmap.reset_index()
hhmap["household_id_old"] = hhmap["household_id"]
# assign hh_id to those newly added
hhmap.loc[hhmap["building_id"] == -1, "household_id"] = list(
range(
hhidmax + hh_new_added_cumsum[i], hhidmax + hh_new_added_cumsum[i + 1]
)
)
hh_id_mapping[i] = hhmap[["household_id_old", "household_id"]].set_index(
"household_id_old"
)
## hh df
# merge with hh_id mapping and concat all hh dfs and reset their index
out_hh = pd.concat(
[
pd.merge(
x[0].reset_index(),
hh_id_mapping[i],
left_on="household_id",
right_index=True,
)
for i, x in enumerate(out)
],
verify_integrity=True,
ignore_index=True,
copy=False,
)
# sort
out_hh = out_hh.sort_values(by="household_id")
# set index to hh_id
out_hh = out_hh.set_index("household_id_y")
out_hh = out_hh[households.local_columns]
out_hh.index.name = "household_id"
## persons df
# merge with hh_id mapping and concat and reset their index
out_person = pd.concat(
[
pd.merge(
x[1].reset_index(),
hh_id_mapping[i],
left_on="household_id",
right_index=True,
)
for i, x in enumerate(out)
],
verify_integrity=True,
ignore_index=True,
copy=False,
)
new_p = (out_person.household_id_x != out_person.household_id_y).sum()
out_person.loc[
out_person.household_id_x != out_person.household_id_y, "person_id"
] = list(range(pidmax, pidmax + new_p))
out_person["household_id"] = out_person["household_id_y"]
out_person = out_person.set_index("person_id")
orca.add_table("households", out_hh[households.local_columns])
orca.add_table("persons", out_person[persons.local_columns])
def get_lpr_hh_seed_id_mapping(hh, p, hh_seeds, p_seeds):
# get hh swapping mapping
# 2hr runtime
# recommend using cached result
seeds = np.sort(hh.seed_id.unique())
# get adding new worker seed_id mapping
add_worker_dict = defaultdict(dict)
drop_worker_dict = defaultdict(dict)
for seed in seeds:
print('seed: ', seed)
# for each seed, find a counter seed which has 1 more worker and similar other attributes
seed_hh = hh_seeds[hh_seeds.seed_id== seed].iloc[0]
seed_p = p_seeds[p_seeds.seed_id == seed]
hh_pool = hh_seeds
hh_pool = hh_pool[hh_pool.persons == seed_hh.persons]
hh_pool = hh_pool[hh_pool.race_id == seed_hh.race_id]
hh_pool = hh_pool[hh_pool.aoh_bin == seed_hh.aoh_bin]
hh_pool = hh_pool[hh_pool.children == seed_hh.children]
seed_age_dist = np.sort(seed_p.age_bin.values)
if seed_hh.workers + seed_hh.children < seed_hh.persons:
hh_pool_add_worker = hh_pool[hh_pool.workers == seed_hh.workers + 1]
# add worker with more hh income
hh_pool_add_worker = hh_pool_add_worker[hh_pool_add_worker.inc_qt >= seed_hh.inc_qt]
N = hh_pool_add_worker.shape[0]
for i in range(N):
local_p_seeds = p_seeds[p_seeds.seed_id == hh_pool_add_worker['seed_id'].iloc[i]]
if all(np.sort(local_p_seeds.age_bin.values) == seed_age_dist):
new_age_bins = local_p_seeds.query('worker==1').age_bin.value_counts()
prev_age_bins = seed_p.query('worker==1').age_bin.value_counts()
for k, v in new_age_bins.items():
if k in prev_age_bins and v <= prev_age_bins[k]:
continue
add_age_bin = k
add_worker_dict[add_age_bin][seed] = hh_pool_add_worker.iloc[i].seed_id
break
if seed_hh.workers > 0:
hh_pool_drop_worker = hh_pool[hh_pool.workers == seed_hh.workers - 1]
N = hh_pool_drop_worker.shape[0]
for i in range(N):
local_p_seeds = p_seeds[p_seeds.seed_id == hh_pool_drop_worker['seed_id'].iloc[i]]
if all(np.sort(local_p_seeds.age_bin.values) == seed_age_dist):
new_age_bins = local_p_seeds.query('worker==1').age_bin.value_counts()
prev_age_bins = seed_p.query('worker==1').age_bin.value_counts()
for k, v in prev_age_bins.items():
if k in new_age_bins and v <= new_age_bins[k]:
continue
drop_age_bin = k
drop_worker_dict[drop_age_bin][seed] = hh_pool_drop_worker.iloc[i].seed_id
break
# clean up some key with more than 1 worker added/removed in a single hh
add_list = defaultdict(list)
for age, add_swappable in add_worker_dict.items():
for orig, target in add_swappable.items():
q = '(worker == 1)&(age_bin==%s)'%age
if p_seeds.loc[[orig]].query(q).shape[0]+1 != p_seeds.loc[[target]].query(q).shape[0]:
add_list[age].append(orig)
for age, ll in add_list.items():
for dk in ll:
del add_worker_dict[age][dk]
drop_list = defaultdict(list)
for age, drop_swappable in drop_worker_dict.items():
for orig, target in drop_swappable.items():
q = '(worker == 1)&(age_bin==%s)'%age
if p_seeds.loc[[orig]].query(q).shape[0] != p_seeds.loc[[target]].query(q).shape[0]+1:
drop_list[age].append(orig)
for age, ll in drop_list.items():
for dk in ll:
del drop_worker_dict[age][dk]
return add_worker_dict, drop_worker_dict
@orca.step()
def cache_hh_seeds(households, persons, iter_var):
if iter_var != 2021:
print('skipping cache_hh_seeds for forecast year')
return
# caching hh and persons seeds at the start of the model run
hh = households.to_frame(households.local_columns + ["large_area_id"])
hh["target_workers"] = 0
hh['inc_qt'] = pd.qcut(hh.income, 4, labels=[1, 2, 3, 4])
hh['aoh_bin'] = pd.cut(hh.age_of_head, [-1, 4, 17, 24, 34, 64, 200], labels=[1, 2, 3, 4, 5, 6])
# generate age bins
age_bin = [-1, 15, 19, 21, 24, 29, 34, 44, 54, 59, 61, 64, 69, 74, 199]
age_bin_labels = [0,16,20,22,25,30,35,45,55,60,62,65,70,75,200]
p = persons.to_frame(persons.local_columns + ["large_area_id"])
p['age_bin'] = pd.cut(p.age, age_bin, labels=age_bin_labels[:-1])
p['age_bin'] = p['age_bin'].fillna(0).astype(int)
p = p.join(hh.seed_id, on='household_id')
hh_seeds = hh.groupby('seed_id').first()
p_seeds = p.groupby(['seed_id', 'member_id']).first()
print('running cache_hh_seeds for base year')
orca.add_table('hh_seeds', hh_seeds)
orca.add_table('p_seeds', p_seeds)
# TODO:
# - Add worker by swapping hh with 1 worker more hh
# - try to limit the impact to other variables
# - same persons, children, income within range(?), car(?), race with worker + 1
# - update persons table(optional) and households table
@orca.step()
def fix_lpr(households, persons, hh_seeds, p_seeds, iter_var, employed_workers_rate):
from numpy.random import choice
hh = households.to_frame(households.local_columns + ["large_area_id"])
hh_seeds = hh_seeds.to_frame()
p_seeds = p_seeds.to_frame()
changed_hhs = hh.copy()
hh["target_workers"] = 0
hh['inc_qt'] = pd.qcut(hh.income, 4, labels=[1, 2, 3, 4])
hh['aoh_bin'] = pd.cut(hh.age_of_head, [-1, 4, 17, 24, 34, 64, 200], labels=[1, 2, 3, 4, 5, 6])
# generate age bins
age_bin = [-1, 15, 19, 21, 24, 29, 34, 44, 54, 59, 61, 64, 69, 74, 199]
age_bin_labels = [0,16,20,22,25,30,35,45,55,60,62,65,70,75,200]
p = persons.to_frame(persons.local_columns + ["large_area_id"])
p['age_bin'] = pd.cut(p.age, age_bin, labels=age_bin_labels[:-1])
p['age_bin'] = p['age_bin'].fillna(0).astype(int)
p = p.join(hh.seed_id, on='household_id')
changed_ps = p.copy()
lpr = employed_workers_rate.to_frame(["age_min", "age_max", str(iter_var)])
colls = [
"persons",
"race_id",
"workers",
"children",
"large_area_id",
] # , 'age_of_head'
same = {tuple(idx): df[["income", "cars"]] for idx, df in hh.groupby(colls)}
# reset seeds index for generating mappings
hh_seeds = hh_seeds.reset_index()
p_seeds = p_seeds.reset_index()
USE_SWAPPING_SEED_MAPPING = True
aw_path = 'data/add_worker_dict.pkl'
dw_path = 'data/drop_worker_dict.pkl'
if not os.path.exists(aw_path):
USE_SWAPPING_SEED_MAPPING = False
print(aw_path, ' not found. running get_lpr_hh_seed_id_mapping')
if not os.path.exists(dw_path):
USE_SWAPPING_SEED_MAPPING = False
print(dw_path, ' not found. running get_lpr_hh_seed_id_mapping')
if USE_SWAPPING_SEED_MAPPING:
add_worker_df = pd.read_csv('data/add_worker_dict.csv', index_col=0)
add_worker_df.columns = add_worker_df.columns.astype(int)
drop_worker_df = pd.read_csv('data/drop_worker_dict.csv', index_col=0)
drop_worker_df.columns = drop_worker_df.columns.astype(int)
else:
add_worker_dict, drop_worker_dict = get_lpr_hh_seed_id_mapping(hh, p, hh_seeds, p_seeds)
add_worker_df = pd.DataFrame(add_worker_dict)
add_worker_df.to_csv(aw_path, index=True)
drop_worker_df = pd.DataFrame(drop_worker_dict)
drop_worker_df.to_csv(aw_path, index=True)
hh_seeds = hh_seeds.set_index('seed_id')
p_seeds = p_seeds.set_index('seed_id')
# p = p.reset_index().set_index('household_id')
pg = p.groupby('household_id')
hh_cols_to_swap = [col for col in hh.columns if col not in ['blkgrp', 'building_id', 'large_area_id']]
p_cols_to_swap = [col for col in p.columns if col not in ['person_id', 'household_id', 'large_area_id', 'weight']]
for large_area_id, row in lpr.iterrows():
select = (
(p.large_area_id == large_area_id)
& (p.age >= row.age_min)
& (p.age <= row.age_max)
)
emp_wokers_rate = row[str(iter_var)]
lpr_workers = int(select.sum() * emp_wokers_rate)
num_workers = (select & (p.worker == 1)).sum()
# get dict for seeds mapping
add_swappable = add_worker_df[row.age_min]
add_swappable = add_swappable[add_swappable.notna()].astype(int).to_dict()
drop_swappable = drop_worker_df[row.age_min]
drop_swappable = drop_swappable[drop_swappable.notna()].astype(int).to_dict()
if lpr_workers > num_workers:
# employ some persons
num_new_employ = int(lpr_workers - num_workers)
while num_new_employ > 0:
hh_swap_pool = hh[(hh.large_area_id == large_area_id) & (hh.seed_id.isin(add_swappable))]
if hh_swap_pool.shape[0] == 0:
break
to_add = min(hh_swap_pool.shape[0], num_new_employ)
# sample num_new_employ
hh_to_swap = hh_swap_pool.sample(to_add, replace=False)
# target seed_ids
target_hh_seed_id = hh_to_swap.seed_id.map(add_swappable)
# overwrite old attributes except building_id, large_area_id, blkgrp
hh.loc[hh_to_swap.index, hh_cols_to_swap] = hh_seeds.loc[target_hh_seed_id].reset_index()[hh_cols_to_swap].values
# hh persons overwrite
p_idx_to_update = np.array([], dtype=int)
for hh_id in hh_to_swap.index:
hh_members = pg.get_group(hh_id)
p_idx_to_update = np.concatenate((p_idx_to_update, hh_members.index))
p.loc[p_idx_to_update, p_cols_to_swap] = p_seeds.loc[target_hh_seed_id].reset_index()[p_cols_to_swap].values
# update added_employ
num_new_employ = int(lpr_workers - (
(p.large_area_id == large_area_id)
& (p.age >= row.age_min)
& (p.age <= row.age_max)
& (p.worker == 1)
).sum())
else:
# unemploy some persons
num_drop_employ = int(num_workers - lpr_workers)
while num_drop_employ > 0:
hh_swap_pool = hh[(hh.large_area_id == large_area_id) & (hh.seed_id.isin(drop_swappable))]
if hh_swap_pool.shape[0] == 0:
break
to_drop = min(hh_swap_pool.shape[0], num_drop_employ)
# sample num_new_employ
hh_to_swap = hh_swap_pool.sample(to_drop, replace=False)
# target seed_ids
target_hh_seed_id = hh_to_swap.seed_id.map(drop_swappable)
# overwrite old attributes except building_id, large_area_id, blkgrp
hh.loc[hh_to_swap.index, hh_cols_to_swap] = hh_seeds.loc[target_hh_seed_id].reset_index()[hh_cols_to_swap].values
# hh persons overwrite
p_idx_to_update = np.array([], dtype=int)
for hh_id in hh_to_swap.index:
hh_members = pg.get_group(hh_id)
p_idx_to_update = np.concatenate((p_idx_to_update, hh_members.index))
p.loc[p_idx_to_update, p_cols_to_swap] = p_seeds.loc[target_hh_seed_id].reset_index()[p_cols_to_swap].values
# update num_drop_employ
num_drop_employ = int((
(p.large_area_id == large_area_id)
& (p.age >= row.age_min)
& (p.age <= row.age_max)
& (p.worker == 1)
).sum() - lpr_workers)
after_selected = (
(p.large_area_id == large_area_id)
& (p.age >= row.age_min)
& (p.age <= row.age_max)
& (p.worker == True)
)
print(large_area_id, row.age_min, row.age_max, num_workers, lpr_workers, after_selected.sum())
hh["old_workers"] = hh.workers
hh.workers = p.groupby("household_id").worker.sum()
hh.workers = hh.workers.fillna(0)
changed = hh.workers != hh.old_workers
print(f"changed number of HHs from LPR is {len(changed)})")
# TODO: using hh controls to test out each segment number
# save changed HHs and persons as valid samples for future transition model
if len(changed[changed == True]) > 0:
changed_hhs = changed_hhs[changed]
changed_hhs["old_hhid"] = changed_hhs.index
changed_hhs.index = range(1, 1 + len(changed_hhs))
changed_hhs.index.name = "household_id"
changed_hhs = changed_hhs.reset_index().set_index("old_hhid")
changed_ps = changed_ps.loc[
changed_ps.household_id.isin(changed_hhs[changed].index)
]
changed_ps = changed_ps.rename(columns={"household_id": "old_hhid"})
changed_ps = changed_ps.merge(
changed_hhs[["household_id"]],
left_on="old_hhid",
right_index=True,
how="left",
)
changed_ps.index = range(1, 1 + len(changed_ps))
changed_ps = changed_ps.drop("old_hhid", axis=1)
changed_hhs = changed_hhs.set_index("household_id")
changed_hhs["building_id"] = -1
print(f"saved {len(changed_hhs)} households for future samples")
else:
changed_hhs = hh.iloc[0:0]
changed_ps = changed_ps.iloc[0:0]
orca.add_table("changed_hhs", changed_hhs[households.local_columns])
orca.add_table("changed_ps", changed_ps[persons.local_columns])
for match_colls, chh in hh[changed].groupby(colls):
try:
match = same[tuple(match_colls)]
new_workers = choice(match.index, len(chh), True)
hh.loc[chh.index, ["income", "cars"]] = match.loc[
new_workers, ["income", "cars"]
].values
except KeyError:
pass
# todo: something better!?
orca.add_table("households", hh[households.local_columns])
orca.add_table("persons", p[persons.local_columns])
@orca.step()
def jobs_transition(jobs, annual_employment_control_totals, iter_var):
ct_emp = annual_employment_control_totals.to_frame()
ct_emp = ct_emp.reset_index().set_index("year")
tran = transition.TabularTotalsTransition(ct_emp, "total_number_of_jobs")
model = transition.TransitionModel(tran)
j = jobs.to_frame(jobs.local_columns + ["large_area_id"])
new, added_jobs_idx, _ = model.transition(j, iter_var)
orca.add_injectable(
"jobs_large_area_lookup", new.large_area_id, autocall=False, cache=True
)
new.loc[added_jobs_idx, "building_id"] = -1
orca.add_table("jobs", new[jobs.local_columns])
@orca.step()
def jobs_scaling_model(jobs):
wrap_jobs = jobs
jobs = jobs.to_frame(jobs.local_columns + ["large_area_id"])
regional_sectors = {1, 7, 12, 13, 15, 18}
la_sectors = []
def random_choice(chooser_ids, alternative_ids, probabilities):
return pd.Series(
np.random.choice(
alternative_ids, size=len(chooser_ids), replace=True, p=probabilities
),
index=chooser_ids,
)
jobs_to_place = jobs[jobs.building_id.isnull() | (jobs.building_id == -1)]
selected = jobs_to_place.sector_id.isin(regional_sectors)
for (sec, la) in la_sectors:
selected |= (jobs_to_place.sector_id == sec) & (
jobs_to_place.large_area_id == la
)
jobs_to_place = jobs_to_place[selected]
if len(jobs_to_place) > 0:
for (large_area_id, sector), segment in jobs_to_place.groupby(
["large_area_id", "sector_id"]
):
counts_by_bid = (
jobs[
(jobs.sector_id == sector)
& (jobs.large_area_id == large_area_id)
& (jobs.building_id != -1)
]
.groupby(["building_id"])
.size()
)
# !! filter out -1 from the building pool
counts_by_bid = counts_by_bid[counts_by_bid.index != -1]
prop_by_bid = counts_by_bid / counts_by_bid.sum()
choices = random_choice(
segment.index.values, prop_by_bid.index.values, prop_by_bid.values
)
wrap_jobs.update_col_from_series("building_id", choices, cast=True)
j_after_run = wrap_jobs.to_frame(wrap_jobs.local_columns)
print(
"done running job_scaling, remaining jobs in sectors",
regional_sectors,
"with -1 building_id: ",
(
(j_after_run.building_id == -1)
& (j_after_run.sector_id.isin(regional_sectors))
).sum(),
)
@orca.step()
def gq_pop_scaling_model(group_quarters, group_quarters_control_totals, parcels, year):
def filter_local_gq(local_gqpop):
protected = (
((local_gqpop.gq_code > 100) & (local_gqpop.gq_code < 200))
| ((local_gqpop.gq_code > 500) & (local_gqpop.gq_code < 600))
| (local_gqpop.gq_code == 701)
)
return local_gqpop[~protected]
parcels = parcels.to_frame(parcels.local_columns)
city_large_area = (
parcels[["city_id", "large_area_id"]].drop_duplicates().set_index("city_id")
)
gqpop = group_quarters.to_frame(
group_quarters.local_columns + ["city_id", "large_area_id"]
)
print("%s gqpop before scaling" % gqpop.shape[0])
# gqhh = group_quarters_households.to_frame(group_quarters_households.local_columns)
target_gq = group_quarters_control_totals.to_frame()
target_gq = target_gq[target_gq.year == year]
# add gq target to city table to iterate
city_large_area["gq_target"] = target_gq["count"]
city_large_area = city_large_area.fillna(0).sort_index()
# if no control found, skip this year
if target_gq.shape[0] == 0:
print("Warning: No gq controls found for year %s, skipping..." % year)
return
for city_id, row in city_large_area.iterrows():
local_gqpop = gqpop.loc[gqpop.city_id == city_id]
diff = int(row.gq_target - len(local_gqpop))
# diff = target_gq.loc[city_id]["count"] - len(local_gqpop)
# keep certain GQ pop unchanged