-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathsimulate.py
More file actions
2642 lines (2348 loc) · 118 KB
/
simulate.py
File metadata and controls
2642 lines (2348 loc) · 118 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import itertools
import json
import logging
import random
import sys
import uuid
from datetime import date, datetime
from pathlib import Path
import numpy as np
import pandas as pd
from tqdm.auto import tqdm
from machine.law_parameter_config import (
_ensure_registry_initialized,
create_overrides,
find_law_config_by_technical_name,
)
from machine.service import Services
# Create a logger for this module
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)
# Directory for storing populations
POPULATIONS_DIR = Path("data/populations")
class LawSimulator:
def __init__(self, simulation_date="2025-03-01", law_parameters=None) -> None:
self.simulation_date = simulation_date
self.services = Services(simulation_date)
# Initialize the law parameter registry with our Services instance
# This prevents eventsourcing conflicts in subprocess contexts
_ensure_registry_initialized(services=self.services)
self.results = []
self.used_bsns = set() # Track used BSNs
self.law_parameters = law_parameters or {}
# DEBUG: Log received law parameters
if self.law_parameters:
logger.info(f"Received law_parameters with keys: {list(self.law_parameters.keys())}")
for law_name, params in self.law_parameters.items():
if params:
logger.info(f" {law_name}: {len(params)} parameters")
# CBS demographic data for more realistic simulation
self.age_distribution = {
(18, 30): 0.18, # 18-30 year olds: 18%
(30, 45): 0.25, # 30-45 year olds: 25%
(45, 67): 0.32, # 45-67 year olds: 32%
(67, 85): 0.20, # 67-85 year olds: 20%
(85, 100): 0.05, # 85+ year olds: 5%
}
# Income distribution (log-normal parameters) based on income deciles
# Adjusted to create more variation
self.income_distribution_params = {
"low": {"mean": 9.9, "sigma": 0.5}, # Lower incomes (avg ~€20k)
"middle": {"mean": 10.7, "sigma": 0.3}, # Middle incomes (avg ~€44k)
"high": {"mean": 11.3, "sigma": 0.45}, # Higher incomes (avg ~€80k)
}
# Add some people with zero income to qualify for bijstand
self.zero_income_prob = 0.05 # 5% chance of having zero income
# Housing information based on CBS data
self.housing_distribution = {
"rent": 0.43, # 43% renters
"own": 0.57, # 57% homeowners
}
# Rent cost distributions (in euros) for rent calculation
# Updated to reflect 2025 Dutch rental market
# Social housing: €650-€808 (liberalization threshold 2025)
# Private sector: €900-€1500+
self.rent_distribution = {
"low": (550, 700), # Social housing range
"medium": (700, 850), # Upper social/lower private
"high": (850, 1200), # Private sector (some eligible for huurtoeslag)
}
@staticmethod
def save_population(population_id: str, people: list, params: dict) -> None:
"""Save a population to disk for reuse."""
POPULATIONS_DIR.mkdir(parents=True, exist_ok=True)
# Convert dates to ISO format for JSON serialization
serializable_people = []
for person in people:
person_copy = person.copy()
person_copy["birth_date"] = person["birth_date"].isoformat()
# Convert children data
if "children_data" in person_copy:
for child in person_copy["children_data"]:
child["birth_date"] = child["birth_date"].isoformat()
serializable_people.append(person_copy)
# Save population data
population_file = POPULATIONS_DIR / f"{population_id}.json"
with open(population_file, "w") as f:
json.dump(serializable_people, f, indent=2)
# Save metadata
metadata = {
"population_id": population_id,
"created_at": datetime.now().isoformat(),
"num_people": len(people),
"params": params,
"demographics": {
"avg_age": sum(p["age"] for p in people) / len(people),
"with_partners_pct": sum(1 for p in people if p["has_partner"]) / len(people) * 100,
"students_pct": sum(1 for p in people if p["is_student"]) / len(people) * 100,
"renters_pct": sum(1 for p in people if p["housing_type"] == "rent") / len(people) * 100,
"with_children_pct": sum(1 for p in people if p["has_children"]) / len(people) * 100,
},
}
metadata_file = POPULATIONS_DIR / f"{population_id}.meta.json"
with open(metadata_file, "w") as f:
json.dump(metadata, f, indent=2)
logger.info(f"Saved population {population_id} with {len(people)} people")
@staticmethod
def load_population(population_id: str) -> list:
"""Load a previously saved population from disk."""
population_file = POPULATIONS_DIR / f"{population_id}.json"
if not population_file.exists():
raise FileNotFoundError(f"Population {population_id} not found")
with open(population_file) as f:
people_data = json.load(f)
# Convert ISO format strings back to date objects
for person in people_data:
person["birth_date"] = date.fromisoformat(person["birth_date"])
# Convert children data
if "children_data" in person:
for child in person["children_data"]:
child["birth_date"] = date.fromisoformat(child["birth_date"])
logger.info(f"Loaded population {population_id} with {len(people_data)} people")
return people_data
@staticmethod
def list_populations() -> list[dict]:
"""List all saved populations with their metadata."""
if not POPULATIONS_DIR.exists():
return []
populations = []
for meta_file in POPULATIONS_DIR.glob("*.meta.json"):
try:
with open(meta_file) as f:
metadata = json.load(f)
populations.append(metadata)
except Exception as e:
logger.error(f"Error reading metadata file {meta_file}: {e}")
# Sort by creation date, newest first
populations.sort(key=lambda x: x.get("created_at", ""), reverse=True)
return populations
@staticmethod
def delete_population(population_id: str) -> bool:
"""Delete a saved population and its metadata."""
population_file = POPULATIONS_DIR / f"{population_id}.json"
metadata_file = POPULATIONS_DIR / f"{population_id}.meta.json"
deleted = False
if population_file.exists():
population_file.unlink()
deleted = True
if metadata_file.exists():
metadata_file.unlink()
deleted = True
if deleted:
logger.info(f"Deleted population {population_id}")
return deleted
def generate_bsn(self):
while True:
bsn = f"999{random.randint(100000, 999999)}"
if bsn not in self.used_bsns:
self.used_bsns.add(bsn)
return bsn
def generate_person(self, birth_year_range=None):
"""Generate a realistic person with demographics based on CBS data"""
# Select age range based on distribution
if not birth_year_range:
age_range = random.choices(
list(self.age_distribution.keys()), weights=list(self.age_distribution.values())
)[0]
current_year = datetime.strptime(self.simulation_date, "%Y-%m-%d").year
birth_year_range = (current_year - age_range[1], current_year - age_range[0])
birth_date = date(
random.randint(*birth_year_range),
random.randint(1, 12),
random.randint(1, 28),
)
age = (datetime.strptime(self.simulation_date, "%Y-%m-%d").date() - birth_date).days // 365
# Select income level based on age (simplified model)
if age < 30:
income_level = random.choices(["low", "middle", "high"], weights=[0.6, 0.3, 0.1])[0]
elif age < 45:
income_level = random.choices(["low", "middle", "high"], weights=[0.3, 0.5, 0.2])[0]
elif age < 67:
income_level = random.choices(["low", "middle", "high"], weights=[0.25, 0.45, 0.3])[0]
else:
income_level = random.choices(["low", "middle", "high"], weights=[0.5, 0.4, 0.1])[0]
# Generate income based on selected level
# Chance for zero income (to qualify for bijstand)
if random.random() < self.zero_income_prob:
annual_income = 0
else:
income_params = self.income_distribution_params[income_level]
annual_income = (
min(max(int(np.random.lognormal(mean=income_params["mean"], sigma=income_params["sigma"])), 0), 200000)
* 100
)
# If person is above retirement age, adjust income to reflect pension
if age >= 67:
annual_income = min(annual_income, 50000 * 100) # Cap at €50,000 for retirees
annual_income = max(annual_income, 15000 * 100) # Minimum €15,000 for retirees (AOW)
# For students, income is much lower
if age < 30 and random.random() < 0.4: # 40% chance for young people to be students
is_student = True
annual_income = min(annual_income, 20000 * 100) # Cap student income at €20,000
annual_income = max(annual_income, 5000 * 100) # Minimum student income €5,000
study_grant = random.randint(2000, 4500) * 100 # €2,000 - €4,500 annual study grant
else:
is_student = False
study_grant = 0
# Calculate net worth based on age and income
# Young people have less wealth, older people have more
net_worth_multiplier = max(0.5, min(age / 25, 8)) # Ranges from 0.5 to 8
# Students have much less net worth
if is_student:
net_worth_multiplier *= 0.4
net_worth = annual_income * net_worth_multiplier * random.uniform(0.8, 1.2)
net_worth = min(max(net_worth, 0), 2000000 * 100) # Cap at €2,000,000
# Determine housing situation
# Students and young people are more likely to rent
rent_probability = self.housing_distribution["rent"]
if age < 30:
rent_probability = 0.8
elif age < 40:
rent_probability = 0.55
elif age > 67:
rent_probability = 0.35 # Elderly often own their homes
# People with lower incomes are more likely to rent
if annual_income < 2500000: # Less than €25,000
rent_probability += 0.2
housing_type = "rent" if random.random() < rent_probability else "own"
# Calculate rent or mortgage
if housing_type == "rent":
# Determine appropriate rent range based on income
# Make rents lower for lower incomes to qualify for huurtoeslag
if annual_income < 2000000: # Less than €20,000
rent_range = self.rent_distribution["low"]
# Give some people exactly the values from the feature file
if random.random() < 0.3: # 30% chance
rent_amount = 65000 # €650 as in feature file
rent_service_costs = 5000 # €50 as in feature file
eligible_service_costs = 4800 # €48 as in feature file
else:
# Calculate monthly rent
rent_amount = int(random.randint(*rent_range) * 100) # Convert to cents
rent_service_costs = int(random.randint(80, 120) * 100) # €80-€120 service costs
eligible_service_costs = min(rent_service_costs, 3000) # Max €30 eligible for most
elif annual_income < 4000000: # Less than €40,000
rent_range = self.rent_distribution["medium"]
# Calculate monthly rent
rent_amount = int(random.randint(*rent_range) * 100) # Convert to cents
rent_service_costs = int(random.randint(100, 150) * 100) # €100-€150 service costs
eligible_service_costs = min(rent_service_costs, 3000) # Max €30 eligible
else:
rent_range = self.rent_distribution["high"]
# Calculate monthly rent
rent_amount = int(random.randint(*rent_range) * 100) # Convert to cents
rent_service_costs = int(random.randint(120, 200) * 100) # €120-€200 service costs
eligible_service_costs = min(rent_service_costs, 3000) # Max €30 eligible
else:
# For homeowners, estimate mortgage payment
rent_amount = 0
rent_service_costs = 0
eligible_service_costs = 0
# Generate more data for other laws
is_detained = random.random() < 0.002 # 0.2% chance of being detained
is_incarcerated = is_detained
# Has Dutch nationality (random with high probability)
has_dutch_nationality = random.random() < 0.9
# Generate children data only for adults 23-55
has_children = False
children_data = []
if 23 <= age <= 55:
has_children_prob = min(0.7, (age - 23) * 0.03) # Increases with age up to 0.7
has_children = random.random() < has_children_prob
if has_children:
num_children = random.choices([1, 2, 3, 4], weights=[0.4, 0.4, 0.15, 0.05])[0]
for i in range(num_children):
child_age = random.randint(0, min(20, age - 23))
child_birth_year = datetime.now().year - child_age
children_data.append(
{
"bsn": self.generate_bsn(), # Generate BSN for child
"birth_date": date(child_birth_year, random.randint(1, 12), random.randint(1, 28)),
"age": child_age,
"zorgbehoefte": random.random() < 0.05, # 5% chance of special care needs
}
)
# Health insurance: virtually everyone in NL is insured
is_health_insured = not is_detained and age >= 18
# Receives child benefit: nearly all parents with children <18
receives_child_benefit = has_children and any(c["age"] < 18 for c in children_data)
# Receives study financing: most students get it
receives_study_financing = is_student and random.random() < 0.85
# Self-employment income: ~12% of workforce is self-employed
is_self_employed = not is_student and 18 <= age < 67 and random.random() < 0.12
business_income = annual_income if is_self_employed else 0
# Work hours per week (derived from income and employment status)
if is_student:
work_hours_per_week = random.choice([0, 8, 12, 16, 20])
elif age < 18 or age >= 67 or is_detained:
work_hours_per_week = 0
elif annual_income < 500000: # <€5k: likely unemployed or minimal work
work_hours_per_week = random.choice([0, 0, 0, 8, 12])
elif annual_income < 2000000: # <€20k: part-time
work_hours_per_week = random.randint(12, 28)
elif annual_income < 4000000: # <€40k: near full-time
work_hours_per_week = random.randint(28, 40)
else: # >€40k: full-time
work_hours_per_week = random.randint(32, 45)
# Childcare data for parents with young children who work
childcare_hours_per_child = 0
childcare_hourly_rate = 0
childcare_type = "none"
if has_children and work_hours_per_week >= 12:
young_children = [c for c in children_data if c["age"] < 12]
if young_children:
youngest = min(c["age"] for c in young_children)
childcare_type = "dagopvang" if youngest < 4 else "bso"
# Hours roughly proportional to work hours, 2-5 days
childcare_days = min(5, max(2, work_hours_per_week // 8))
hours_per_day = 10 if childcare_type == "dagopvang" else 4
childcare_hours_per_child = childcare_days * hours_per_day * 46 # ~46 weeks/year
# Hourly rate: €8-9 for dagopvang, €7-8 for bso
if childcare_type == "dagopvang":
childcare_hourly_rate = random.randint(800, 920) # eurocents
else:
childcare_hourly_rate = random.randint(700, 780) # eurocents
return {
"bsn": self.generate_bsn(),
"birth_date": birth_date,
"age": age,
"annual_income": annual_income,
"net_worth": net_worth,
"work_years": min(max(0, (age - 18) * random.uniform(0.5, 0.9)), 50),
"residence_years": min(max(0, (age - 15) * random.uniform(0.8, 1.0)), 50),
"is_student": is_student,
"study_grant": study_grant,
"is_detained": is_detained,
"is_incarcerated": is_incarcerated,
"has_dutch_nationality": has_dutch_nationality,
"has_children": has_children,
"children_data": children_data,
"housing_type": housing_type,
"rent_amount": rent_amount,
"rent_service_costs": rent_service_costs,
"eligible_service_costs": eligible_service_costs,
"standaardpremie": 211200, # €2.112/year, fixed for 2025
"is_health_insured": is_health_insured,
"receives_child_benefit": receives_child_benefit,
"receives_study_financing": receives_study_financing,
"business_income": business_income,
"work_hours_per_week": work_hours_per_week,
"childcare_hours_per_child": childcare_hours_per_child,
"childcare_hourly_rate": childcare_hourly_rate,
"childcare_type": childcare_type,
}
def generate_paired_people(self, num_people):
pairs = [] # Store people in pairs (person, partner or None)
while True:
current_count = len([p for pair in pairs for p in pair if p is not None])
if current_count >= num_people:
break
person = self.generate_person()
# Check if we need only one more person
if current_count + 1 == num_people:
# Just add the single person without a partner
pairs.append((person, None))
break
# Partnership probability based on age
partner_prob = 0.1
if 25 <= person["age"] < 35:
partner_prob = 0.4
elif 35 <= person["age"] < 60:
partner_prob = 0.7
elif person["age"] >= 60:
partner_prob = 0.6
# Check if adding a partner would exceed our target
if current_count + 2 > num_people:
# Don't add a partner if it would exceed num_people
pairs.append((person, None))
elif random.random() < partner_prob: # Chance of partner
age_diff = random.gauss(0, 5)
birth_year_min = person["birth_date"].year + int(age_diff) - 1
birth_year_max = person["birth_date"].year + int(age_diff) + 1
# Ensure birth years are reasonable
birth_year_min = max(birth_year_min, 1925)
birth_year_max = max(birth_year_max, birth_year_min + 1)
partner = self.generate_person(birth_year_range=(birth_year_min, birth_year_max))
pairs.append((person, partner))
else:
pairs.append((person, None))
return pairs
def setup_test_data(self, pairs, random_seed=None):
# Set random seed if provided (for reproducibility with loaded populations)
if random_seed is not None:
# Convert string seed to integer if needed (e.g., UUID strings)
if isinstance(random_seed, str):
# Convert UUID string to integer using hash
random_seed = int(uuid.UUID(random_seed).int % (2**32))
random.seed(random_seed)
np.random.seed(random_seed)
# Flatten pairs into list of people with partner references
people = []
for person, partner in pairs:
person["partner_bsn"] = partner["bsn"] if partner else None
person["has_partner"] = partner is not None
people.append(person)
if partner:
partner["partner_bsn"] = person["bsn"]
partner["has_partner"] = True
people.append(partner)
# Prepare CBS demographic data
sources = {
("CBS", "levensverwachting"): [{"jaar": "2025", "verwachting_65": 20.5}],
# KIESRAAD data for elections
("KIESRAAD", "verkiezingen"): [{"type": "TWEEDE_KAMER", "verkiezingsdatum": "2025-10-29"}],
# RvIG data (Personal Information)
("RvIG", "personen"): [
{
"bsn": p["bsn"],
"geboortedatum": p["birth_date"].isoformat(),
"verblijfsadres": "Amsterdam",
"land_verblijf": "NEDERLAND",
"nationaliteit": "NEDERLANDS" if p["has_dutch_nationality"] else "BUITENLANDS",
"age": p["age"],
"has_dutch_nationality": p["has_dutch_nationality"],
"has_partner": p["has_partner"],
"residence_address": p.get("residence_address")
or f"Teststraat {random.randint(1, 999)}, {random.randint(1000, 9999)}AB Amsterdam",
"has_fixed_address": True,
"household_size": 1 + (1 if p["has_partner"] else 0) + len(p.get("children_data", [])),
}
for p in people
],
# RvIG relationship data
("RvIG", "relaties"): [
{
"bsn": p["bsn"],
"partnerschap_type": "HUWELIJK" if p["has_partner"] else "GEEN",
"partner_bsn": p["partner_bsn"],
# Add children directly in the format expected by features (Dutch field name!)
"kinderen": [{"bsn": child["bsn"]} for child in p.get("children_data", [])]
if p.get("children_data")
else [],
}
for p in people
],
# RvIG Address data
("RvIG", "verblijfplaats"): [
{
"bsn": p["bsn"],
"straat": p.get("straat") or ("Kalverstraat" if random.random() < 0.7 else "Teststraat"),
"huisnummer": p.get("huisnummer") or str(random.randint(1, 999)),
"postcode": p.get("postcode") or f"{random.randint(1000, 9999)}AB",
"woonplaats": "Amsterdam",
"type": p.get("address_type") or ("WOONADRES" if random.random() < 0.95 else "BRIEFADRES"),
}
for p in people
],
# RvIG data for werkloosheidsuitkering (nationality and residence)
("RvIG", "heeft_nederlandse_nationaliteit"): [
{
"bsn": p["bsn"],
"value": p["has_dutch_nationality"],
}
for p in people
],
("RvIG", "woont_in_nederland"): [
{
"bsn": p["bsn"],
"value": True, # All simulated people live in Netherlands
}
for p in people
],
# Tax data
("BELASTINGDIENST", "box1"): [
{
"bsn": p["bsn"],
"loon_uit_dienstbetrekking": p["annual_income"] if not p["is_student"] else p["annual_income"] // 2,
"uitkeringen_en_pensioenen": p["annual_income"] // 2 if p["age"] >= 67 else 0,
"winst_uit_onderneming": 0,
"resultaat_overige_werkzaamheden": 0,
"eigen_woning": -int(p["annual_income"] * 0.1) if p["housing_type"] == "own" else 0,
}
for p in people
],
# Income data (used by huurtoeslag)
("UWV", "income"): [
{
"bsn": p["bsn"],
"value": p["annual_income"],
}
for p in people
],
# Partner income data (used by huurtoeslag)
("UWV", "partner_income"): [
{
"bsn": p["bsn"],
"value": people[i + 1]["annual_income"]
if i + 1 < len(people) and p.get("partner_bsn") == people[i + 1]["bsn"]
else 0,
}
for i, p in enumerate(people)
if i % 2 == 0
# Only do this for first of each potential pair
]
+ [
{
"bsn": p["bsn"],
"value": people[i - 1]["annual_income"]
if i - 1 >= 0 and p.get("partner_bsn") == people[i - 1]["bsn"]
else 0,
}
for i, p in enumerate(people)
if i % 2 == 1
# Only do this for second of each potential pair
],
("BELASTINGDIENST", "box2"): [
{"bsn": p["bsn"], "reguliere_voordelen": 0, "vervreemdingsvoordelen": 0} for p in people
],
("BELASTINGDIENST", "box3"): [
{
"bsn": p["bsn"],
"spaargeld": int(p["net_worth"] * 0.4),
"beleggingen": int(p["net_worth"] * 0.1),
"onroerend_goed": int(p["net_worth"] * 0.5) if p["housing_type"] == "own" else 0,
"schulden": int(p["annual_income"] * 0.05) if random.random() < 0.2 else 0,
}
for p in people
],
("BELASTINGDIENST", "monthly_income"): [
{
"bsn": p["bsn"],
"bedrag": p["annual_income"] // 12,
}
for p in people
],
("BELASTINGDIENST", "assets"): [
{
"bsn": p["bsn"],
"bedrag": p["net_worth"],
}
for p in people
],
# Net worth data (used by huurtoeslag)
("BELASTINGDIENST", "net_worth"): [
{
"bsn": p["bsn"],
"value": p["net_worth"],
}
for p in people
],
# Combined net worth data (used by huurtoeslag for people with partners)
("BELASTINGDIENST", "combined_net_worth"): [
{
"bsn": p["bsn"],
"value": p["net_worth"]
+ (
people[i + 1]["net_worth"]
if i + 1 < len(people) and p.get("partner_bsn") == people[i + 1]["bsn"]
else 0
),
}
for i, p in enumerate(people)
if i % 2 == 0
# Only do this for first of each potential pair
]
+ [
{
"bsn": p["bsn"],
"value": p["net_worth"]
+ (
people[i - 1]["net_worth"] if i - 1 >= 0 and p.get("partner_bsn") == people[i - 1]["bsn"] else 0
),
}
for i, p in enumerate(people)
if i % 2 == 1
# Only do this for second of each potential pair
],
# Buitenlands inkomen (missing in warnings)
("UWV", "FOREIGN_INCOME"): [
{
"bsn": p["bsn"],
"value": 0, # Geen buitenlands inkomen
}
for p in people
],
# Partner buitenlands inkomen
("UWV", "PARTNER_FOREIGN_INCOME"): [
{
"bsn": p["bsn"],
"value": 0, # Partner geen buitenlands inkomen
}
for p in people
],
# HOUSEHOLD veld dat ontbreekt - met members array dat age en income bevat
("RvIG", "HOUSEHOLD"): [
{
"bsn": p["bsn"],
"value": {
"size": 1 + (1 if p["has_partner"] else 0) + len(p.get("children_data", [])),
"composition": "ALLEENSTAANDE"
if not p["has_partner"] and not p.get("children_data")
else "ALLEENSTAANDE_MET_KINDEREN"
if not p["has_partner"] and p.get("children_data")
else "PARTNERS_ZONDER_KINDEREN"
if p["has_partner"] and not p.get("children_data")
else "PARTNERS_MET_KINDEREN",
"members": [{"age": p["age"], "income": p["annual_income"]}]
+ (
[
{
"age": next(
(partner for partner in people if partner["bsn"] == p["partner_bsn"]),
{"age": 30},
)["age"],
"income": next(
(partner for partner in people if partner["bsn"] == p["partner_bsn"]),
{"annual_income": 0},
)["annual_income"],
}
]
if p["has_partner"] and p["partner_bsn"]
else []
),
},
}
for p in people
],
# Employment data
("UWV", "dienstverbanden"): [
{
"bsn": p["bsn"],
"start_date": (p["birth_date"].replace(year=p["birth_date"].year + 18)).isoformat(),
"end_date": datetime.strptime(self.simulation_date, "%Y-%m-%d").date().isoformat(),
"uren_per_week": random.randint(8, 40) if not p["is_student"] else random.randint(4, 16),
"worked_hours": (1920 if random.random() < 0.8 else random.randint(1000, 1920))
if not p["is_student"]
else random.randint(500, 1000),
}
for p in people
],
# Add worked_hours for UWV that's required by kinderopvangtoeslag
("UWV", "worked_hours"): [
{
"bsn": p["bsn"],
"value": (1920 if random.random() < 0.8 else random.randint(1000, 1920))
if not p["is_student"]
else random.randint(500, 1000),
}
for p in people
],
# Add insured_years for kinderopvangtoeslag
("UWV", "insured_years"): [
{
"bsn": p["bsn"],
"value": min(max(3, int(p["work_years"])), 30), # Minimum 3 years, max 30
}
for p in people
],
# UWV work data for werkloosheidsuitkering (WW) - table structure
("UWV", "uwv_werkgegevens"): [
{
"bsn": p["bsn"],
"gemiddeld_uren_per_week": float(
random.randint(32, 40) if not p["is_student"] else random.randint(12, 24)
),
# Simulate some unemployment: 10% of non-students are currently unemployed (0 hours)
"huidige_uren_per_week": float(
0
if not p["is_student"] and random.random() < 0.10
else random.randint(32, 40)
if not p["is_student"]
else random.randint(12, 24)
),
# Most people (80%) meet the requirement of 26+ weeks out of 36
"gewerkte_weken_36": random.randint(26, 36) if random.random() < 0.80 else random.randint(10, 25),
"arbeidsverleden_jaren": int(p["work_years"]),
"jaarloon": p["annual_income"],
}
for p in people
],
# UWV ziektewet data - table name must match feature test
("UWV", "ziektewet"): [
{
"bsn": p["bsn"],
"heeft_ziektewet_uitkering": False, # Very few people receive sickness benefits
}
for p in people
],
# UWV WIA data - table name must match feature test
("UWV", "WIA"): [
{
"bsn": p["bsn"],
"heeft_wia_uitkering": False, # Very few people receive disability benefits
}
for p in people
],
# SVB insurance data
("SVB", "verzekerde_tijdvakken"): [
{
"bsn": p["bsn"],
"woonperiodes": p["residence_years"],
}
for p in people
],
# SVB retirement age
("SVB", "retirement_age"): [
{
"bsn": p["bsn"],
"leeftijd": 67 + random.randint(0, 3) / 10, # 67.0-67.3
}
for p in people
],
# SVB kinderbijslag data for kindgebonden budget (table structure)
("SVB", "algemene_kinderbijslagwet"): [
{
"ouder_bsn": p["bsn"],
"aantal_kinderen": len(p.get("children_data", [])),
"kinderen_leeftijden": [child["age"] for child in p.get("children_data", [])],
"ontvangt_kinderbijslag": p["has_children"],
}
for p in people
],
# SVB pension age data for WW eligibility check (table structure)
("SVB", "algemene_ouderdomswet_gegevens"): [
{
"bsn": p["bsn"],
"pensioenleeftijd": 67, # AOW retirement age in 2025
}
for p in people
],
# Healthcare insurance data
("RVZ", "verzekeringen"): [
{
"bsn": p["bsn"],
"polis_status": "ACTIEF" if random.random() < 0.95 else "INACTIEF",
"verdrag_status": "GEEN",
"zorg_type": "BASIS",
"has_insurance": random.random() < 0.95,
"has_act_insurance": random.random() < 0.05,
}
for p in people
],
# Healthcare treaty data
("RVZ", "verdragsverzekeringen"): [
{
"bsn": p["bsn"],
"registratie": "INACTIEF",
}
for p in people
],
# Detention data
("DJI", "detenties"): [
{
"bsn": p["bsn"],
"status": "GEDETINEERD" if p["is_detained"] else "VRIJ",
"inrichting_type": "REGULIER" if p["is_detained"] else "GEEN",
"is_gedetineerd": p["is_detained"],
"is_detainee": p["is_detained"],
}
for p in people
],
("DJI", "forensische_zorg"): [
{
"bsn": p["bsn"],
"zorgtype": "KLINISCH" if p["is_detained"] and random.random() < 0.1 else "GEEN",
"juridische_titel": "TBS" if p["is_detained"] and random.random() < 0.1 else "GEEN",
"is_forensic": p["is_detained"] and random.random() < 0.1,
}
for p in people
],
# Education data
("DUO", "inschrijvingen"): [
{
"bsn": p["bsn"],
"onderwijstype": ("HBO" if random.random() < 0.5 else "WO") if p["is_student"] else "GEEN",
"onderwijssoort": ("HBO" if random.random() < 0.5 else "WO") if p["is_student"] else "GEEN",
"niveau": 4 if p["is_student"] else 0,
}
for p in people
],
("DUO", "studiefinanciering"): [
{
"bsn": p["bsn"],
"aantal_studerend_gezin": random.randint(0, 3) if p["age"] < 30 else 0,
"ontvangt_studiefinanciering": p["is_student"],
"aantal_studerende_broers_zussen": random.randint(0, 2) if p["age"] < 30 else 0,
}
for p in people
],
("DUO", "is_student"): [
{
"bsn": p["bsn"],
"waarde": p["is_student"],
}
for p in people
],
("DUO", "receives_study_grant"): [
{
"bsn": p["bsn"],
"waarde": p["is_student"],
}
for p in people
],
# Municipal data (Amsterdam)
("GEMEENTE_AMSTERDAM", "werk_en_re_integratie"): [
{
"bsn": p["bsn"],
"arbeidsvermogen": random.choices(
["VOLLEDIG", "GEDEELTELIJK", "MEDISCH_VOLLEDIG", "GEEN"], weights=[0.8, 0.1, 0.05, 0.05]
)[0],
"re_integratie_traject": random.choice(
["Werkstage", "Ondernemerscoaching", "Zelfstandigentraject", "Geen"]
),
"ontheffing_reden": "Chronische ziekte" if random.random() < 0.05 else None,
"ontheffing_einddatum": (
datetime.strptime(self.simulation_date, "%Y-%m-%d").date() + pd.Timedelta(days=365)
).isoformat()
if random.random() < 0.05
else None,
}
for p in people
],
# IND data (residence permits)
("IND", "verblijfsvergunningen"): [
{
"bsn": p["bsn"],
"type": "PERMANENT" if not p["has_dutch_nationality"] else "NEDERLANDS",
"status": "VERLEEND",
"ingangsdatum": (
p["birth_date"].replace(year=p["birth_date"].year + max(0, 18 - random.randint(0, 5)))
).isoformat(),
"einddatum": None,
}
for p in people
],
("IND", "residence_permit_type"): [
{
"bsn": p["bsn"],
"type": "PERMANENT" if not p["has_dutch_nationality"] else "NEDERLANDS",
}
for p in people
],
# KVK data (Chamber of Commerce)
("KVK", "is_entrepreneur"): [
{
"bsn": p["bsn"],
"waarde": random.random() < 0.1, # 10% chance of being entrepreneur
}
for p in people
],
("KVK", "is_active_entrepreneur"): [
{
"bsn": p["bsn"],
"waarde": random.random() < 0.1, # 10% chance of being active entrepreneur
}
for p in people
],
# KVK inschrijvingen data for bijstand
("KVK", "inschrijvingen"): [
{
"bsn": p["bsn"],
"rechtsvorm": random.choice(["EENMANSZAAK", "BV", "VOF"]),
"status": "ACTIEF" if random.random() < 0.9 else "INACTIEF",
"activiteit": random.choice(["Webdesign", "Consultancy", "Horeca", "Retail", "Transport"]),
}
for p in people
if random.random() < 0.1 # Only 10% of people have KVK registrations
],
# JenV data (ministry of Justice)
("JenV", "jurisdicties"): [
{"gemeente": "Amsterdam", "arrondissement": "AMSTERDAM", "rechtbank": "RECHTBANK_AMSTERDAM"},
{"gemeente": "Amstelveen", "arrondissement": "AMSTERDAM", "rechtbank": "RECHTBANK_AMSTERDAM"},
{"gemeente": "Haarlem", "arrondissement": "NOORD-HOLLAND", "rechtbank": "RECHTBANK_NOORD_HOLLAND"},
{"gemeente": "Rotterdam", "arrondissement": "ROTTERDAM", "rechtbank": "RECHTBANK_ROTTERDAM"},
{
"gemeente": "Utrecht",
"arrondissement": "MIDDEN-NEDERLAND",
"rechtbank": "RECHTBANK_MIDDEN_NEDERLAND",
},
{"gemeente": "Den Haag", "arrondissement": "DEN_HAAG", "rechtbank": "RECHTBANK_DEN_HAAG"},
],
}
# Add housing data for rent calculation
[
{
"bsn": p["bsn"],
"huur": p["rent_amount"],
"servicekosten": p["rent_service_costs"],
"subsidiabeleservicekosten": p["eligible_service_costs"],
}
for p in people
if p["housing_type"] == "rent"
]
# IMPORTANT: Huurtoeslag requires CLAIMS, not regular data sources
# We'll submit these as claims after loading all other data
# Add household members and children required by huurtoeslag with the correct format
# Voorbeeld uit de feature file toont dat deze velden niet als 'value' worden verwacht, maar direct
# Voor elk persoon, maak huishoudleden en kinderen data aan als VALUE object (niet als directe velden)
household_members = []
for p in people:
# Verzamel huishoudleden (anderen dan de persoon zelf)
household_data = []
if p["has_partner"] and p["partner_bsn"]:
# Vind de partner in de people list
partner = next((partner for partner in people if partner["bsn"] == p["partner_bsn"]), None)
if partner:
household_data.append({"age": partner["age"], "income": partner["annual_income"]})
# Value field zoals in YAML verwacht
household_members.append({"bsn": p["bsn"], "value": household_data})
sources[("RvIG", "household_members")] = household_members
# Add children with correct format based on feature file
children_data = []
for p in people:
child_list = []
if p.get("children_data"):
# Format children data correctly for the law
for child in p["children_data"]:
child_list.append(
{
"age": child["age"],
"income": 0, # Assume children have no income for simplicity
}
)
# Value field zoals in YAML verwacht
children_data.append({"bsn": p["bsn"], "value": child_list})
sources[("RvIG", "children")] = children_data