-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathSimPathsModel.java
More file actions
3436 lines (2795 loc) · 158 KB
/
SimPathsModel.java
File metadata and controls
3436 lines (2795 loc) · 158 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// define package
package simpaths.model;
// import Java packages
import java.io.*;
import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.random.RandomGenerator;
// import plug-in packages
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.Persistence;
import jakarta.persistence.Transient;
import org.apache.commons.lang3.ArrayUtils;
import org.jetbrains.annotations.NotNull;
import simpaths.data.*;
import simpaths.data.startingpop.Processed;
import simpaths.experiment.SimPathsCollector;
import simpaths.model.decisions.DecisionParams;
import microsim.alignment.outcome.ResamplingAlignment;
import microsim.event.*;
import microsim.event.EventListener;
import org.apache.commons.collections4.keyvalue.MultiKey;
import org.apache.commons.collections4.MapIterator;
import org.apache.commons.collections4.map.LinkedMap;
import org.apache.commons.collections4.map.MultiKeyMap;
import org.apache.commons.lang3.tuple.Triple;
import org.apache.commons.math3.util.Pair;
import org.apache.log4j.Logger;
import org.apache.commons.lang3.time.StopWatch;
// import JAS-mine packages
import microsim.alignment.outcome.AlignmentOutcomeClosure;
import microsim.annotation.GUIparameter;
import microsim.data.MultiKeyCoefficientMap;
import microsim.data.db.DatabaseUtils;
import microsim.engine.AbstractSimulationManager;
import microsim.engine.SimulationEngine;
import microsim.matching.IterativeSimpleMatching;
import microsim.matching.MatchingClosure;
import microsim.matching.MatchingScoreClosure;
// import LABOURsim packages
import simpaths.model.decisions.ManagerPopulateGrids;
import simpaths.model.enums.*;
import simpaths.model.taxes.DonorTaxUnit;
import simpaths.model.taxes.DonorTaxUnitPolicy;
import simpaths.model.taxes.Match;
import simpaths.model.taxes.Matches;
import simpaths.model.taxes.database.DatabaseExtension;
import simpaths.model.taxes.database.TaxDonorDataParser;
/**
*
* CLASS TO MANAGE SIMULATION PROJECTIONS
*
*/
public class SimPathsModel extends AbstractSimulationManager implements EventListener {
public static String getPersistDatabasePath() {
return PersistDatabasePath;
}
public static void setPersistDatabasePath(String persistDatabasePath) {
PersistDatabasePath = persistDatabasePath;
}
public static void setPersistPopulation(boolean persistPopulation) {
PersistPopulation = persistPopulation;
}
public boolean isFirstRun() {
return isFirstRun;
}
public void setFirstRun(boolean firstRun) {
isFirstRun = firstRun;
}
private boolean isFirstRun = true; // set default to true - this is required to support single run simulations
// default simulation parameters
private static Logger log = Logger.getLogger(SimPathsModel.class);
//@GUIparameter(description = "Country to be simulated")
private Country country; // = Country.UK;
private boolean flagUpdateCountry = false; // set to true if switch between countries
@GUIparameter(description = "Simulated population size (base year)")
private Integer popSize = 170000;
@GUIparameter(description = "Simulation first year [valid range 2011-2019]")
private Integer startYear = 2011;
@GUIparameter(description = "Simulation ends at year")
private Integer endYear = 2026;
@GUIparameter(description = "Maximum simulated age")
private Integer maxAge = 130;
//@GUIparameter(description = "Fix year used in the regressions to one specified below")
private boolean fixTimeTrend = true;
@GUIparameter(description = "Fix year used in the regressions to")
private Integer timeTrendStopsIn = 2021;
private Integer timeTrendStopsInMonetaryProcesses = 2021; // For monetary processes, time trend always continues to 2017 (last observed year in the estimation sample) and then values are grown at the growth rate read from Excel
// @GUIparameter(description="Age at which people in initial population who are not employed are forced to retire")
// private Integer ageNonWorkPeopleRetire = 65; //The problem is that it is difficult to find donor benefitUnits for non-zero labour supply for older people who are in the Nonwork category but not Retired. They should, in theory, still enter the Labour Market Module, but if we cannot find donor benefitUnits, how should we proceed? We avoid this problem by defining that people over the age specified here are retired off if they have activity_status equal to Nonwork.
// @GUIparameter(description="Minimum age for males to retire")
// private Integer minRetireAgeMales = 45;
//
// @GUIparameter(description="Maximum age for males to retire")
// private Integer maxRetireAgeMales = 75;
//
// @GUIparameter(description="Minimum age for females to retire")
// private Integer minRetireAgeFemales = 45;
//
// @GUIparameter(description="Maximum age for females to retire")
// private Integer maxRetireAgeFemales = 75;
@GUIparameter(description = "Fix random seed?")
private Boolean fixRandomSeed = true;
@GUIparameter(description = "If random seed is fixed, set to this number")
private Long randomSeedIfFixed = 606L;
@GUIparameter(description = "Time window in years for (in)security index calculation")
private Integer sIndexTimeWindow = 5;
@GUIparameter(description = "Value of risk aversion parameter (alpha)")
private Double sIndexAlpha = 2.;
@GUIparameter(description = "Value of discount factor (delta)")
private Double sIndexDelta = 0.98;
//The data comes from here: https://data.oecd.org/hha/household-savings.htm
@GUIparameter(description = "Value of saving rate (s). The default value is based on average % of household disposable income saved between 2000 - 2019 reported by the OECD")
private Double savingRate = 0.056;
private double interestRateInnov = 0.0; // used to explore behavioural sensitivity to assumed interest rates (intertemporal elasticity of substitution)
private double disposableIncomeFromLabourInnov = 0.0; // used to explore behavioural sensitivity to disposable income (Marshallian labour supply elasticity)
// @GUIparameter(description = "Force recreation of input database based on the data provided by the population_[country].csv file")
// private boolean refreshInputDatabase = false; //Tables can be constructed in GUI dialog in launch, before JAS-mine GUI appears. However, if skipping that, and manually altering the EUROMODpolicySchedule.xlsx file, this will need to be set to true to build new input database before simulation is run (though the new input database will only be viewable in the output/input/input.h2.db file).
// @GUIparameter(description = "If true, set initial earnings from data in input population, otherwise, set using the wage equation regression estimates")
private boolean initialisePotentialEarningsFromDatabase = true;
// @GUIparameter(description = "If unchecked, will expand population and not use weights")
private boolean useWeights = false;
private boolean ignoreTargetsAtPopulationLoad = false;
@GUIparameter(description = "If unchecked, will use the standard matching method")
// private boolean useSBAMMatching = false;
private UnionMatchingMethod unionMatchingMethod = UnionMatchingMethod.ParametricNoRegion;
@GUIparameter(description = "tick to project mortality based on gender, age, and year specific probabilities")
private boolean projectMortality = true;
private boolean alignPopulation = true; //TODO: routine fails to replicate results for minor variations between simulations
// @GUIparameter(description = "If checked, will align fertility")
private boolean alignFertility = false;
private boolean alignEducation = false; //Set to true to align level of education
private boolean alignInSchool = false; //Set to true to align share of students among 16-29 age group
private boolean alignCohabitation = false; //Set to true to align share of couples (cohabiting individuals)
private boolean alignEmployment = false; //Set to true to align employment share
public boolean addRegressionStochasticComponent = true; //If set to true, and regression contains ResStanDev variable, will evaluate the regression score including stochastic part, and omits the stochastic component otherwise.
public boolean fixRegressionStochasticComponent = false; // If true, only draw stochastic component once and use the same value throughout the simulation. Currently applies to wage equations.
public boolean commentsOn = true;
public boolean debugCommentsOn = true;
public boolean donorFinderCommentsOn = true;
@GUIparameter(description = "If checked, will use Covid-19 labour supply module")
public boolean labourMarketCovid19On = false; // Set to true to use reduced-form labour market module for years affected by Covid-19 (2020, 2021)
@GUIparameter(description = "Simulate formal childcare costs")
public boolean projectFormalChildcare = true;
@GUIparameter(description = "Average over donor pool when imputing transfer payments")
public boolean donorPoolAveraging = true;
private int ordering = Parameters.MODEL_ORDERING; //Used in Scheduling of model events. Schedule model events at the same time as the collector and observer events, but a lower order, so will be fired before the collector and observer have updated.
private Set<Person> persons;
//For marriage matching - types based on region and gender:
//private Map<Gender, LinkedHashMap<Region, Double>> marriageTargetsGenderRegion;
private MultiKeyMap<Object, Double> marriageTargetsByGenderAndRegion;
private LinkedHashMap<String, Double> marriageTargetsByKey;
private long elapsedTime0;
private long timerStartSim;
private int year;
// generalised logit error counters
private int counterErrorH1a, counterErrorH1b;
private Set<BenefitUnit> benefitUnits;
private Set<Household> households;
private Map<Gender, LinkedHashMap<Region, Set<Person>>> personsToMatch;
private LinkedHashMap<String, Set<Person>> personsToMatch2;
private double scalingFactor;
private Map<Long, Double> initialHoursWorkedWeekly;
private LabourMarket labourMarket;
public int tmpPeopleAssigned = 0;
public int lowEd = 0;
public int medEd = 0;
public int highEd = 0;
public int nothing = 0;
Map<String, Double> policyNameIncomeMedianMap = new LinkedHashMap<>(); // Initialise a <String, Double> map to store names of policies and median incomes
private Tests tests;
@Transient
SimPathsCollector collector;
EventGroup firstYearSched = new EventGroup();
EventGroup yearlySchedule = new EventGroup();
@GUIparameter(description = "tick to project social care")
private boolean projectSocialCare = true;
private boolean flagSuppressChildcareCosts = false;
private boolean flagSuppressSocialCareCosts = false;
@GUIparameter(description = "tick to enable intertemporal optimised consumption and labour decisions")
private boolean enableIntertemporalOptimisations = false;
@GUIparameter(description = "tick to use behavioural solutions saved by a previous simulation")
private boolean useSavedBehaviour = false;
@GUIparameter(description = "simulation name to read in grids from:")
private String readGrid = "test1";
// flag to project population using time series average statistics (dampens temporal variation)
private boolean flagDefaultToTimeSeriesAverages = false;
// @GUIparameter(description = "tick to save behavioural solutions assumed for simulation")
private boolean saveBehaviour = true;
// save imperfect tax database matches to potentially expand input database
private boolean saveImperfectTaxDBMatches = false;
// @GUIparameter(description = "the number of employment options from which a household's principal wage earner can choose")
private Integer employmentOptionsOfPrincipalWorker = 3;
// @GUIparameter(description = "the number of employment options from which a household's secondary wage earner can choose")
private Integer employmentOptionsOfSecondaryWorker = 3;
@GUIparameter(description = "whether to include student and education status in state space for IO behavioural solutions")
private boolean responsesToEducation = true;
@GUIparameter(description = "whether to include private pensions in the state space for IO behavioural solutions")
private boolean responsesToPension = false;
@GUIparameter(description = "whether to include low wage offers (unemployment) in the state space for IO behavioural solutions")
private boolean responsesToLowWageOffer = true;
@GUIparameter(description = "whether to include retirement (and private pensions) in the state space for IO behavioural solutions")
private boolean responsesToRetirement = false;
@GUIparameter(description = "whether to include health in state space for IO behavioural solutions")
private boolean responsesToHealth = true;
@GUIparameter(description = "whether to include disability in state space for IO behavioural solutions")
private boolean responsesToDisability = true;
@GUIparameter(description = "minimum age for expecting less than perfect health in IO solutions")
private Integer minAgeForPoorHealth = 45;
@GUIparameter(description = "whether to include geographic region in state space for IO behavioural solutions")
private boolean responsesToRegion = false;
RandomGenerator cohabitInnov;
Random initialiseInnov1;
Random initialiseInnov2;
Random popAlignInnov;
Random educationInnov;
// private static String RunDatabasePath = RunDatabasePath;
private static String RunDatabasePath;
private static String PersistDatabasePath;
private static boolean PersistPopulation = false;
/**
*
* CONSTRUCTOR FOR SIMULATION PROJECTIONS
* @param country
* @param startYear
*
*/
public SimPathsModel(Country country, int startYear) {
super();
this.country = country;
this.startYear = startYear;
}
public SimPathsModel(Country country) {
super();
this.country = country;
}
/**
*
* METHOD TO BUILD THE MODEL SO THAT IT CAN BE EXECUTED
*
* This method is launched by JAS-mine when you press the
* 'Build simulation model' button of the GUI
*
*/
@Override
public void buildObjects() {
// time check
elapsedTime0 = System.currentTimeMillis();
timerStartSim = elapsedTime0;
// set seed for random number generator
if (fixRandomSeed) SimulationEngine.getRnd().setSeed(randomSeedIfFixed);
cohabitInnov = new Random(SimulationEngine.getRnd().nextLong());
initialiseInnov1 = new Random(SimulationEngine.getRnd().nextLong());
initialiseInnov2 = new Random(SimulationEngine.getRnd().nextLong());
educationInnov = new Random(SimulationEngine.getRnd().nextLong());
popAlignInnov = new Random(SimulationEngine.getRnd().nextLong());
// load model parameters
Parameters.loadParameters(country, maxAge, enableIntertemporalOptimisations, projectFormalChildcare,
projectSocialCare, donorPoolAveraging, fixTimeTrend, flagDefaultToTimeSeriesAverages, saveImperfectTaxDBMatches,
timeTrendStopsIn, startYear, endYear, interestRateInnov, disposableIncomeFromLabourInnov, flagSuppressChildcareCosts,
flagSuppressSocialCareCosts);
if (enableIntertemporalOptimisations) {
alignEmployment = false;
DecisionParams.loadParameters(employmentOptionsOfPrincipalWorker, employmentOptionsOfSecondaryWorker,
responsesToHealth, minAgeForPoorHealth, responsesToDisability, responsesToRegion, responsesToEducation,
responsesToPension, responsesToLowWageOffer, responsesToRetirement, saveBehaviour,
readGrid, getEngine().getCurrentExperiment().getOutputFolder(), startYear, endYear);
//DecisionTests.compareGrids();
//DatabaseExtension.extendInputData();
}
long elapsedTime1 = System.currentTimeMillis();
System.out.println("Time to load parameters: " + (elapsedTime1 - elapsedTime0)/1000. + " seconds.");
RunDatabasePath = DatabaseUtils.databaseInputUrl;
if (null == PersistDatabasePath) setPersistDatabasePath(RunDatabasePath);
elapsedTime0 = elapsedTime1;
// populate tax donor references
if (flagUpdateCountry) {
taxDatabaseUpdate();
TaxDonorDataParser.populateDonorTaxUnitTables(country, false); // Populate tax unit donor tables from person data
}
populateTaxdbReferences();
// run pre-simulation diagnostic tests
//TestTaxRoutine.run();
//TestRegressions.run(RegressionName.EducationE2a);
elapsedTime1 = System.currentTimeMillis();
System.out.println("Time to load tax database references: " + (elapsedTime1 - elapsedTime0)/1000. + " seconds.");
elapsedTime0 = elapsedTime1;
// set start year for simulation
year = startYear;
// EUROMODpolicyNameForThisYear = Parameters.getEUROMODpolicyForThisYear(year);
//Display current country and start year in the console
System.out.println("Country: " + country + ". Running simulation from: " + startYear + " to " + endYear);
// creates initial population (Person and BenefitUnit objects) based on data in input database.
// Note that the population may be cropped to simulate a smaller population depending on user choices in the GUI.
createInitialPopulationDataStructures();
elapsedTime1 = System.currentTimeMillis();
System.out.println("Time to create initial population structures: " + (elapsedTime1 - elapsedTime0)/1000. + " seconds.");
elapsedTime0 = elapsedTime1;
// initialise variables used to match marriage unions
createDataStructuresForMarriageMatching();
// earnings potential
labourMarket = new LabourMarket(benefitUnits);
if (!initialisePotentialEarningsFromDatabase) initialisePotentialEarningsByWageEquationAndEmployerSocialInsurance();
// calculate the scaling factor for population alignment
double popSizeBaseYear = 0;
for (Gender gender : Gender.values()) {
for (Region region : Parameters.getCountryRegions()) {
for (int age = 0; age < maxAge; age++) {
popSizeBaseYear += Parameters.getPopulationProjections(gender, region, age, year);
}
}
}
scalingFactor = (double)popSizeBaseYear / (double)persons.size();
System.out.println("Scaling factor is " + scalingFactor);
//Set up tests class
tests = new Tests();
// save current simulation parameters
saveRunParameters();
// finalise
elapsedTime1 = System.currentTimeMillis();
log.debug("Time to build objects: " + (elapsedTime1 - timerStartSim)/1000. + " seconds.");
System.out.println("Time to complete initialisation " + (System.currentTimeMillis() - timerStartSim)/1000.0/60.0 + " minutes.");
elapsedTime0 = elapsedTime1;
}
/**
*
* METHOD TO PROJECT THE POPULATION THROUGH TIME
*
* This method is run once for each simulated year after
* the simulation is launched by JAS-mine when you press the
* 'Start simulation' button of the GUI. This method defines
* the order that simulated processes are executed. There are
* three key categories of processes:
* Processes These are processes applicable to the simulation population in aggregate
* Person.Processes Defined in Person Class of model package. These modules define processes specific to simulated 'individuals'
* BenefitUnit.Processes Defined in BenefitUnit Class of model package. These modules define processes specific to simulated 'benefitUnits'
*
* All processes are initialised as 'Events' within the JAS-mine simulation engine
*
* First year involves fewer processes than subsequent years, as many of the simulated characteristics are described by the input data
* Characteristics simulated in the first year limited to control variables for the utility maximisation problem and states affected by
* control variables (time use, transfer system, consumption/savings, and mental health 2 modules).
* First year also allows for alignment routines
*
*/
@Override
public void buildSchedule() {
addEventToAllYears(Processes.StartYear);
if (enableIntertemporalOptimisations)
firstYearSched.addEvent(this, Processes.RationalOptimisation);
addEventToAllYears(Processes.UpdateParameters);
addEventToAllYears(Processes.GarbageCollection);
if (enableIntertemporalOptimisations)
yearlySchedule.addCollectionEvent(benefitUnits, BenefitUnit.Processes.UpdateWealth);
addCollectionEventToAllYears(benefitUnits, BenefitUnit.Processes.Update);
addCollectionEventToAllYears(persons, Person.Processes.Update);
yearlySchedule.addCollectionEvent(persons, Person.Processes.Aging);
// Health Alignment - redrawing alignment used adjust state of individuals to projections by Gender and Age
//Turned off for now as health determined below based on individual characteristics
//yearlySchedule.addEvent(this, Processes.HealthAlignment);
//yearlySchedule.addEvent(this, Processes.CheckForEmptyHouseholds);
// Check whether persons have reached retirement Age
addCollectionEventToAllYears(persons, Person.Processes.ConsiderRetirement, false);
// EDUCATION MODULE
// Check In School - check whether still in education, and if leaving school, reset Education Level
yearlySchedule.addCollectionEvent(persons, Person.Processes.InSchool);
// In School alignment
addEventToAllYears(Processes.InSchoolAlignment);
addCollectionEventToAllYears(persons, Person.Processes.LeavingSchool);
// Align the level of education if required
addEventToAllYears(Processes.EducationLevelAlignment);
// Homeownership status
yearlySchedule.addCollectionEvent(benefitUnits, BenefitUnit.Processes.Homeownership);
// HEALTH MODULE
// Update Health - determine health (continuous) based on regression models: done here because health depends on education
yearlySchedule.addCollectionEvent(persons, Person.Processes.Health);
// // Update mental health - determine (continuous) mental health level based on regression models
// yearlySchedule.addCollectionEvent(persons, Person.Processes.HealthMentalHM1); //Step 1 of mental health
//
// //Update SF12 MCS and PCS health scores step 1
// yearlySchedule.addCollectionEvent(persons, Person.Processes.HealthMCS1);
// yearlySchedule.addCollectionEvent(persons, Person.Processes.HealthPCS1);
// yearlySchedule.addCollectionEvent(persons, Person.Processes.LifeSatisfaction1);
// HOUSEHOLD COMPOSITION MODULE: Decide whether to enter into a union (marry / cohabit), and then perform union matching (marriage) between a male and female
// Update potential earnings so that as up to date as possible to decide partner in union matching.
yearlySchedule.addCollectionEvent(persons, Person.Processes.UpdatePotentialHourlyEarnings);
// Consider whether in consensual union (cohabiting)
yearlySchedule.addEvent(this, Processes.CohabitationAlignment);
yearlySchedule.addCollectionEvent(persons, Person.Processes.Cohabitation);
// partnership variation
yearlySchedule.addCollectionEvent(persons, Person.Processes.PartnershipDissolution);
yearlySchedule.addEvent(this, Processes.UnionMatching);
//yearlySchedule.addEvent(this, Processes.CheckForEmptyHouseholds);
//yearlySchedule.addEvent(this, Processes.Timer);
// Fertility
yearlySchedule.addEvent(this, Processes.FertilityAlignment); //Align to fertility rates implied by projected population statistics.
yearlySchedule.addCollectionEvent(persons, Person.Processes.Fertility);
yearlySchedule.addCollectionEvent(persons, Person.Processes.GiveBirth, false); //Cannot use read-only collection schedule as newborn children cause concurrent modification exception. Need to specify false in last argument of Collection event.
// TIME USE MODULE
// Social care
if (projectSocialCare) {
addCollectionEventToAllYears(persons, Person.Processes.SocialCareReceipt);
addCollectionEventToAllYears(persons, Person.Processes.SocialCareProvision);
//yearlySchedule.addEvent(this, Processes.SocialCareMarketClearing);
}
// Unemployment
addCollectionEventToAllYears(persons, Person.Processes.Unemployment);
// update references for optimising behaviour
// needs to be positioned after all decision states for the current period have been simulated
if (enableIntertemporalOptimisations)
addCollectionEventToAllYears(benefitUnits, BenefitUnit.Processes.UpdateStates, false);
addEventToAllYears(Processes.LabourMarketAndIncomeUpdate);
// Assign benefit status to individuals in benefit units, from donors. Based on donor tax unit status.
addCollectionEventToAllYears(benefitUnits, BenefitUnit.Processes.ReceivesBenefits);
// CONSUMPTION AND SAVINGS MODULE
if (enableIntertemporalOptimisations)
addCollectionEventToAllYears(benefitUnits, BenefitUnit.Processes.ProjectDiscretionaryConsumption);
addCollectionEventToAllYears(persons, Person.Processes.ProjectEquivConsumption);
// equivalised disposable income
addCollectionEventToAllYears(benefitUnits, BenefitUnit.Processes.CalculateChangeInEDI);
// MENTAL HEALTH MODULE
// Update mental health - determine (continuous) mental health level based on regression models + caseness
yearlySchedule.addCollectionEvent(persons, Person.Processes.HealthMentalHM1); //Step 1 of mental health
// modify the outcome of Step 1 depending on individual's exposures + caseness
yearlySchedule.addCollectionEvent(persons, Person.Processes.HealthMentalHM2); //Step 2 of mental health.
// update case-based measure
yearlySchedule.addCollectionEvent(persons, Person.Processes.HealthMentalHM1HM2Cases);
// HEALTH and LIFE SATISFACTION 2
yearlySchedule.addCollectionEvent(persons, Person.Processes.HealthMCS1); //Step 1 of mental health
yearlySchedule.addCollectionEvent(persons, Person.Processes.HealthPCS1); //Step 1 of mental health
yearlySchedule.addCollectionEvent(persons, Person.Processes.LifeSatisfaction1); //Step 1 of mental health
yearlySchedule.addCollectionEvent(persons, Person.Processes.HealthMCS2);
yearlySchedule.addCollectionEvent(persons, Person.Processes.HealthPCS2);
yearlySchedule.addCollectionEvent(persons, Person.Processes.LifeSatisfaction2);
addCollectionEventToAllYears(persons, Person.Processes.HealthEQ5D);
// mortality (migration) and population alignment at year's end
addCollectionEventToAllYears(persons, Person.Processes.ConsiderMortality);
addEventToAllYears(Processes.PopulationAlignment);
// END OF YEAR PROCESSES
addEventToAllYears(Processes.CheckForImperfectTaxDBMatches);
addEventToAllYears(tests, Tests.Processes.RunTests); //Run tests
addEventToAllYears(Processes.EndYear);
// UPDATE YEAR
addEventToAllYears(Processes.UpdateYear);
// UPDATE EVENT QUEUE
getEngine().getEventQueue().scheduleOnce(firstYearSched, startYear, ordering);
getEngine().getEventQueue().scheduleRepeat(yearlySchedule, startYear+1, ordering, 1.);
// at termination of simulation
int orderEarlier = -1; //Set less than order so that this is called before the yearlySchedule in the endYear.
getEngine().getEventQueue().scheduleOnce(new SingleTargetEvent(this, Processes.CleanUp), endYear+1, orderEarlier);
SystemEvent end = new SystemEvent(SimulationEngine.getInstance(), SystemEventType.End);
getEngine().getEventQueue().scheduleOnce(end, endYear+1, orderEarlier);
log.debug("Time to build schedule " + (System.currentTimeMillis() - elapsedTime0)/1000. + " seconds.");
elapsedTime0 = System.currentTimeMillis();
}
private void addEventToAllYears(Tests tt, Enum ee) {
firstYearSched.addEvent(tt, ee);
yearlySchedule.addEvent(tt, ee);
}
private void addEventToAllYears(SimPathsCollector cc, Enum ee) {
firstYearSched.addEvent(cc, ee);
yearlySchedule.addEvent(cc, ee);
}
void addEventToAllYears(Enum ee) {
firstYearSched.addEvent(this, ee);
yearlySchedule.addEvent(this, ee);
}
private void addCollectionEventToAllYears(Set set, Enum ee, boolean readOnly) {
firstYearSched.addCollectionEvent(set, ee, readOnly);
yearlySchedule.addCollectionEvent(set, ee, readOnly);
}
private void addCollectionEventToAllYears(Set set, Enum ee) {
firstYearSched.addCollectionEvent(set, ee);
yearlySchedule.addCollectionEvent(set, ee);
}
private void saveRunParameters() {
String filePath = DatabaseUtils.databaseInputUrl;
filePath = filePath.substring(0, filePath.length()-5) + "options.txt";
try ( FileWriter fw = new FileWriter(filePath, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw)
) {
String line;
line = "---------------------------------------------------";
pw.println(line);
line = "country: " + country;
pw.println(line);
line = "startYear: " + startYear;
pw.println(line);
line = "endYear: " + endYear;
pw.println(line);
line = "popSize: " + popSize;
pw.println(line);
line = "maxAge: " + maxAge;
pw.println(line);
line = "fixTimeTrend: " + fixTimeTrend;
pw.println(line);
line = "timeTrendStopsIn: " + timeTrendStopsIn;
pw.println(line);
line = "timeTrendStopsInMonetaryProcesses: " + timeTrendStopsInMonetaryProcesses;
pw.println(line);
line = "flagDefaultToTimeSeriesAverages: " + flagDefaultToTimeSeriesAverages;
pw.println(line);
line = "fixRandomSeed: " + fixRandomSeed;
pw.println(line);
line = "randomSeedIfFixed: " + randomSeedIfFixed;
pw.println(line);
line = "sIndexAlpha: " + sIndexAlpha;
pw.println(line);
line = "sIndexDelta: " + sIndexDelta;
pw.println(line);
line = "savingRate: " + savingRate;
pw.println(line);
line = "addRegressionStochasticComponent: " + addRegressionStochasticComponent;
pw.println(line);
line = "fixRegressionStochasticComponent: " + fixRegressionStochasticComponent;
pw.println(line);
line = "commentsOn: " + commentsOn;
pw.println(line);
line = "debugCommentsOn: " + debugCommentsOn;
pw.println(line);
line = "donorFinderCommentsOn: " + donorFinderCommentsOn;
pw.println(line);
line = "labourMarketCovid19On: " + labourMarketCovid19On;
pw.println(line);
line = "projectFormalChildcare: " + projectFormalChildcare;
pw.println(line);
line = "donorPoolAveraging: " + donorPoolAveraging;
pw.println(line);
line = "initialisePotentialEarningsFromDatabase: " + initialisePotentialEarningsFromDatabase;
pw.println(line);
line = "useWeights: " + useWeights;
pw.println(line);
line = "projectMortality: " + projectMortality;
pw.println(line);
line = "alignPopulation: " + alignPopulation;
pw.println(line);
line = "alignFertility: " + alignFertility;
pw.println(line);
line = "alignEducation: " + alignEducation;
pw.println(line);
line = "alignInSchool: " + alignInSchool;
pw.println(line);
line = "alignCohabitation: " + alignCohabitation;
pw.println(line);
line = "alignEmployment: " + alignEmployment;
pw.println(line);
line = "saveImperfectTaxDBMatches: " + saveImperfectTaxDBMatches;
pw.println(line);
line = "enableIntertemporalOptimisations: " + enableIntertemporalOptimisations;
pw.println(line);
line = "useSavedBehaviour: " + useSavedBehaviour;
pw.println(line);
line = "readGrid: " + readGrid;
pw.println(line);
line = "saveBehaviour: " + saveBehaviour;
pw.println(line);
line = "employmentOptionsOfPrincipalWorker: " + employmentOptionsOfPrincipalWorker;
pw.println(line);
line = "employmentOptionsOfSecondaryWorker: " + employmentOptionsOfSecondaryWorker;
pw.println(line);
line = "responsesToLowWageOffer: " + responsesToLowWageOffer;
pw.println(line);
line = "responsesToEducation: " + responsesToEducation;
pw.println(line);
line = "responsesToHealth: " + responsesToHealth;
pw.println(line);
line = "minAgeForPoorHealth: " + minAgeForPoorHealth;
pw.println(line);
line = "responsesToDisability: " + responsesToDisability;
pw.println(line);
line = "projectSocialCare: " + projectSocialCare;
pw.println(line);
line = "flagSuppressChildcareCosts: " + flagSuppressChildcareCosts;
pw.println(line);
line = "flagSuppressSocialCareCosts: " + flagSuppressSocialCareCosts;
pw.println(line);
line = "responsesToRegion: " + responsesToRegion;
pw.println(line);
line = "responsesToPension: " + responsesToPension;
pw.println(line);
line = "responsesToRetirement: " + responsesToRetirement;
pw.println(line);
line = "interestRateInnov: " + interestRateInnov;
pw.println(line);
line = "disposableIncomeInnov: " + disposableIncomeFromLabourInnov;
pw.println(line);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
/**
*
* METHOD DEFINING PROCESSES APPLICABLE TO THE SIMULATED POPULATION IN AGGREGATE
*
*/
public enum Processes {
StartYear,
EndYear,
UnionMatching,
LabourMarketAndIncomeUpdate,
SocialCareMarketClearing,
//Alignment Processes
FertilityAlignment,
PopulationAlignment,
CohabitationAlignment,
// HealthAlignment,
InSchoolAlignment,
EducationLevelAlignment,
//Other processes
Timer,
UpdateParameters,
RationalOptimisation,
UpdateYear,
CheckForEmptyBenefitUnits,
GarbageCollection,
CheckForImperfectTaxDBMatches,
CleanUp,
}
@Override
public void onEvent(Enum<?> type) {
switch ((Processes) type) {
case StartYear -> {
elapsedTime0 = System.currentTimeMillis();
System.out.println("Starting year " + year);
if (commentsOn) log.info("Starting year " + year);
}
case EndYear -> {
long elapsedTime1 = System.currentTimeMillis();
double timerForYear = (elapsedTime1 - elapsedTime0)/1000.0;
System.out.println("Finished year " + year + " (in " + timerForYear + " seconds)");
if (commentsOn) log.info("Finished year " + year + " (in " + timerForYear + " seconds)");
elapsedTime0 = elapsedTime1;
}
case PopulationAlignment -> {
if (alignPopulation) {
if ( year <= Parameters.getPopulationProjectionsMaxYear() ) {
if (useWeights) {
populationAlignmentWeighted();
} else {
populationAlignmentUnweighted();
}
if (commentsOn) log.info("Population alignment complete.");
} else {
if (commentsOn) log.info("Population alignment skipped as simulated year exceeds period covered by population projections.");
}
}
}
case CohabitationAlignment -> {
if (alignCohabitation) {
partnershipAlignment();
if (commentsOn) log.info("Cohabitation alignment complete.");
}
clearPersonsToMatch();
}
// case HealthAlignment -> {
// healthAlignment();
// if (commentsOn) log.info("Health alignment complete.");
// }
case UnionMatching -> {
if(UnionMatchingMethod.SBAM.equals(unionMatchingMethod)) {
unionMatchingSBAM();
} else if (UnionMatchingMethod.Parametric.equals(unionMatchingMethod)) {
unionMatching(false);
} else {
unionMatching(false);
unionMatchingNoRegion(false); //Run matching again relaxing regions this time
}
if (commentsOn) log.info("Union matching complete.");
}
case SocialCareMarketClearing -> {
socialCareMarketClearing();
}
case FertilityAlignment -> {
if (alignFertility) {
fertilityAlignment(); //Then align to meet the numbers implied by population projections by region
if (commentsOn) log.info("Fertility alignment complete.");
}
}
case InSchoolAlignment -> {
if (alignInSchool) {
inSchoolAlignment();
System.out.println("Proportion of students will be aligned.");
}
}
case EducationLevelAlignment -> {
if (alignEducation) {
educationLevelAlignment();
System.out.println("Education levels will be aligned.");
}
}
case LabourMarketAndIncomeUpdate -> {
labourMarket.update(year);
if (commentsOn) log.info("Labour market update complete.");
}
case Timer -> {
printElapsedTime();
}
case RationalOptimisation -> {
Parameters.grids = ManagerPopulateGrids.run(this, useSavedBehaviour, saveBehaviour);
}
case UpdateParameters -> {
updateParameters();
if (commentsOn) log.info("Update Parameters Complete.");
}
case UpdateYear -> {
if (commentsOn) log.info("It's New Year's Eve of " + year);
System.out.println("It's New Year's Eve of " + year);
if (year==endYear) {
double timerForSim = (System.currentTimeMillis() - timerStartSim)/1000.0/60.0;
System.out.println("Finished simulating population in " + timerForSim + " minutes");
if (commentsOn) log.info("Finished simulating population in " + timerForSim + " minutes");
}
year++;
}
case GarbageCollection -> {
screenForExitingObjects();
}
case CheckForImperfectTaxDBMatches -> {
if (Parameters.saveImperfectTaxDBMatches) {
screenForImperfectTaxDbMatches();
}
}
case CleanUp -> {
if (Parameters.saveImperfectTaxDBMatches)
DatabaseExtension.extendInputData(getEngine().getCurrentExperiment().getOutputFolder());
}
default -> {
throw new RuntimeException("failed to identify process type in SimPathsModel.onEvent");
}
}
}
/**
*
* METHODS IMPLEMENTING PROCESS LEVEL COMPUTATIONS
*
*/
private void screenForExitingObjects() {
// screen for persons exiting the sample
persons.removeIf(person -> (!SampleExit.NotYet.equals(person.getSampleExit())));
for (BenefitUnit benefitUnit: benefitUnits) {
benefitUnit.getMembers().removeIf(person -> !persons.contains(person));
}
// screen for empty benefit units
benefitUnits.removeIf(benefitUnit -> (benefitUnit.getMale()==null && benefitUnit.getFemale()==null));
for (Household household: households) {
household.getBenefitUnits().removeIf(benefitUnit -> !benefitUnits.contains(benefitUnit));
}
// screen for empty households
households.removeIf(household -> household.getBenefitUnits().isEmpty());
// screen for benefit units not associated with a valid household
benefitUnits.removeIf(benefitUnit -> (!households.contains(benefitUnit.getHousehold())));
// screen for persons not associated with a valid benefit unit
persons.removeIf(person -> (!benefitUnits.contains(person.getBenefitUnit())));
// screen for residual problems
for (Person person : persons) {
if (!benefitUnits.contains(person.getBenefitUnit()))
throw new RuntimeException("person included in model in benefit unit that is not included in model");
}
for (BenefitUnit benefitUnit: benefitUnits) {
if (!households.contains(benefitUnit.getHousehold()))
throw new RuntimeException("benefit unit included in model in household that is not included in model");
if (benefitUnit.getMale()==null && benefitUnit.getFemale()==null)
throw new RuntimeException("problem screening out benefit units with no responsible adults");
int male = 0;
int female = 0;
for (Person person: benefitUnit.getMembers()) {
if (!person.getBenefitUnit().equals(benefitUnit))
throw new RuntimeException("inconsistent linkages between benefit units and members");
if (person.getDag()>=Parameters.AGE_TO_BECOME_RESPONSIBLE) {
if (Gender.Male.equals(person.getDgn()))
male++;
else
female++;
}
}
if (male>1)
throw new RuntimeException("more than one mature male in benefit unit");
if (female>1)
throw new RuntimeException("more than one mature female in benefit unit");
if (male+female<1)
throw new RuntimeException("no mature adults in benefit unit");
}
for (Household household: households) {
for (BenefitUnit benefitUnit : household.getBenefitUnits()) {
if (!benefitUnit.getHousehold().equals(household))
throw new RuntimeException("inconsistent linkages between households and benefit units");
}
}
}
private void screenForImperfectTaxDbMatches() {
Matches imperfectMatches = new Matches();
for (BenefitUnit benefitUnit: benefitUnits) {
Match match = benefitUnit.getTaxDbMatch();
if (match==null)
throw new RuntimeException("failed to identify tax database match");
if (match.getMatchCriterion()>Parameters.IMPERFECT_THRESHOLD) {