forked from Urban-Meteorology-Reading/SUEWS
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathphase_b.py
More file actions
2700 lines (2344 loc) · 108 KB
/
phase_b.py
File metadata and controls
2700 lines (2344 loc) · 108 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
"""
SUEWS Physics Validation Check - Phase B
This module performs physics validation and consistency checks on YAML configurations
that have already been processed by Phase A.
Phase B focuses on:
- Physics parameter validation
- Geographic coordinate and timezone validation
- Seasonal parameter adjustments (LAI, snowalb, surface temperatures)
- Land cover fraction validation and consistency
- Model physics option interdependency checks
- Automatic physics-based corrections where appropriate
Phase B assumes Phase A has completed successfully and builds upon clean YAML output
without duplicating parameter detection or YAML structure validation.
"""
import math
import yaml
import os
import calendar
from typing import Dict, List, Optional, Union, Any, Tuple
from dataclasses import dataclass
from datetime import datetime
from copy import deepcopy
import pandas as pd
import numpy as np
# Import from validation package
from .. import logger_supy
from .report_writer import REPORT_WRITER
from ..core.yaml_helpers import (
get_mean_monthly_air_temperature as _get_mean_monthly_air_temperature,
get_mean_annual_air_temperature as _get_mean_annual_air_temperature,
nullify_co2_block_recursive,
collect_nullified_paths,
_nullify_biogenic_in_props,
DLSCheck,
get_value_safe,
HAS_TIMEZONE_FINDER,
)
# Constants
SFR_FRACTION_TOL = 1e-4
@dataclass
class ValidationResult:
"""Structured result from scientific validation checks."""
status: str # 'PASS', 'WARNING', 'ERROR'
category: str # 'PHYSICS', 'GEOGRAPHY', 'SEASONAL', 'LAND_COVER', 'MODEL_OPTIONS'
parameter: str
site_index: Optional[int] = None # Array index (for internal use)
site_gridid: Optional[int] = None # GRIDID value (for display)
message: str = ""
suggested_value: Any = None
applied_fix: bool = False
@dataclass
class ScientificAdjustment:
"""Record of automatic scientific adjustment applied."""
parameter: str
site_index: Optional[int] = None # Array index (for internal use)
site_gridid: Optional[int] = None # GRIDID value (for display)
old_value: Any = None
new_value: Any = None
reason: str = ""
def get_site_gridid(site_data: dict) -> int:
"""Extract GRIDID from site data, handling both direct and RefValue formats."""
if isinstance(site_data, dict):
gridiv = site_data.get("gridiv")
if isinstance(gridiv, dict) and "value" in gridiv:
return gridiv["value"]
elif gridiv is not None:
return gridiv
return None
def validate_phase_b_inputs(
uptodate_yaml_file: str, user_yaml_file: str, standard_yaml_file: str
) -> Tuple[dict, dict, dict]:
"""Validate Phase B inputs and load YAML files."""
for file_path in [uptodate_yaml_file, user_yaml_file, standard_yaml_file]:
if not os.path.exists(file_path):
raise FileNotFoundError(f"Required file not found: {file_path}")
try:
with open(uptodate_yaml_file, "r") as f:
uptodate_content = f.read()
uptodate_data = yaml.safe_load(uptodate_content)
is_phase_a_output = "UP TO DATE YAML" in uptodate_content
with open(user_yaml_file, "r") as f:
user_data = yaml.safe_load(f)
with open(standard_yaml_file, "r") as f:
standard_data = yaml.safe_load(f)
except yaml.YAMLError as e:
raise ValueError(f"Invalid YAML format: {e}")
return uptodate_data, user_data, standard_data
def extract_simulation_parameters(yaml_data: dict) -> Tuple[int, str, str]:
"""Extract simulation parameters for validation."""
control = yaml_data.get("model", {}).get("control", {})
start_date = control.get("start_time")
end_date = control.get("end_time")
# Collect all validation errors instead of failing on first error
errors = []
if not isinstance(start_date, str) or "-" not in str(start_date):
errors.append(
"Missing or invalid 'start_time' in model.control - must be in 'YYYY-MM-DD' format"
)
if not isinstance(end_date, str) or "-" not in str(end_date):
errors.append(
"Missing or invalid 'end_time' in model.control - must be in 'YYYY-MM-DD' format"
)
# Try to extract model year if start_date looks valid
model_year = None
if isinstance(start_date, str) and "-" in str(start_date):
try:
model_year = int(start_date.split("-")[0])
except Exception:
errors.append(
"Could not extract model year from 'start_time' - ensure 'YYYY-MM-DD' format"
)
# If we have errors, combine them into a single error message
if errors:
error_msg = "; ".join(errors)
raise ValueError(error_msg)
return model_year, start_date, end_date
def validate_physics_parameters(yaml_data: dict) -> List[ValidationResult]:
"""Validate required physics parameters."""
results = []
physics = yaml_data.get("model", {}).get("physics", {})
if not physics:
results.append(
ValidationResult(
status="WARNING",
category="PHYSICS",
parameter="model.physics",
message="Physics section is empty - skipping physics parameter validation",
)
)
return results
required_physics_params = [
"netradiationmethod",
"emissionsmethod",
"storageheatmethod",
"ohmincqf",
"roughlenmommethod",
"roughlenheatmethod",
"stabilitymethod",
"smdmethod",
"waterusemethod",
"rslmethod",
"faimethod",
"rsllevel",
"gsmodel",
"snowuse",
"stebbsmethod",
"rcmethod",
"samealbedo_wall",
"samealbedo_roof",
]
missing_params = [
param for param in required_physics_params if param not in physics
]
if missing_params:
for param in missing_params:
results.append(
ValidationResult(
status="ERROR",
category="PHYSICS",
parameter=f"model.physics.{param}",
message=f"Physics parameter '{param}' is required but missing or null. This parameter controls critical model behaviour and must be specified for the simulation to run properly.",
suggested_value=f"Set '{param}' to an appropriate value. Consult the SUEWS documentation for parameter descriptions and typical values: https://docs.suews.io/latest/",
)
)
empty_params = [
param
for param in required_physics_params
if param in physics and physics.get(param, {}).get("value") in ("", None)
]
if empty_params:
for param in empty_params:
results.append(
ValidationResult(
status="ERROR",
category="PHYSICS",
parameter=f"model.physics.{param}",
message=f"Physics parameter '{param}' has null value. This parameter controls critical model behaviour and must be set for proper simulation.",
suggested_value=f"Set '{param}' to an appropriate non-null value. Check documentation for parameter details: https://docs.suews.io/en/latest",
)
)
if not missing_params and not empty_params:
results.append(
ValidationResult(
status="PASS",
category="PHYSICS",
parameter="model.physics",
message="All required physics parameters present and non-empty",
)
)
return results
def validate_model_option_dependencies(yaml_data: dict) -> List[ValidationResult]:
"""Validate consistency between model physics options."""
results = []
physics = yaml_data.get("model", {}).get("physics", {})
rslmethod = get_value_safe(physics, "rslmethod")
stabilitymethod = get_value_safe(physics, "stabilitymethod")
storageheatmethod = get_value_safe(physics, "storageheatmethod")
ohmincqf = get_value_safe(physics, "ohmincqf")
# RSL method and stability method dependencies
if rslmethod == 2 and stabilitymethod != 3:
results.append(
ValidationResult(
status="ERROR",
category="MODEL_OPTIONS",
parameter="rslmethod-stabilitymethod",
message="If rslmethod == 2, stabilitymethod must be 3",
suggested_value="Set stabilitymethod to 3",
)
)
elif stabilitymethod == 1 and rslmethod is None:
results.append(
ValidationResult(
status="ERROR",
category="MODEL_OPTIONS",
parameter="stabilitymethod-rslmethod",
message="If stabilitymethod == 1, rslmethod parameter is required for atmospheric stability calculations",
suggested_value="Set rslmethod to appropriate value",
)
)
else:
results.append(
ValidationResult(
status="PASS",
category="MODEL_OPTIONS",
parameter="rslmethod-stabilitymethod",
message="rslmethod-stabilitymethod constraints satisfied",
)
)
# Storage heat method and OhmIncQf compatibility check
# Only method 1 (OHM_WITHOUT_QF) has specific compatibility requirements
if storageheatmethod == 1 and ohmincqf != 0:
results.append(
ValidationResult(
status="ERROR",
category="MODEL_OPTIONS",
parameter="storageheatmethod-ohmincqf",
message=f"StorageHeatMethod is set to {storageheatmethod} and OhmIncQf is set to {ohmincqf}. You should switch to OhmIncQf=0.",
suggested_value="Set OhmIncQf to 0",
)
)
else:
results.append(
ValidationResult(
status="PASS",
category="MODEL_OPTIONS",
parameter="storageheatmethod-ohmincqf",
message="StorageHeatMethod-OhmIncQf compatibility validated",
)
)
# SMDMethod and soil_observation dependency
smdmethod = get_value_safe(physics, "smdmethod")
if smdmethod: # Truthy check: skips None and 0 (modelled), validates 1+ (observed)
sites = yaml_data.get("sites", [])
sites_missing_soil_obs = []
for site in sites:
site_name = site.get("name", "Unknown")
properties = site.get("properties", {})
soil_obs = properties.get("soil_observation")
if soil_obs is None:
sites_missing_soil_obs.append(site_name)
if sites_missing_soil_obs:
results.append(
ValidationResult(
status="ERROR",
category="MODEL_OPTIONS",
parameter="smdmethod-soil_observation",
message=(
f"SMDMethod is set to {smdmethod} (observed soil moisture), "
f"but site(s) {sites_missing_soil_obs} are missing the required "
"'soil_observation' configuration block."
),
suggested_value=(
"Add 'soil_observation' block to site properties with: "
"depth, smcap, soil_not_rocks, and bulk_density"
),
)
)
else:
results.append(
ValidationResult(
status="PASS",
category="MODEL_OPTIONS",
parameter="smdmethod-soil_observation",
message="SMDMethod-soil_observation configuration validated",
)
)
# When SMDMethod=0 (modelled), no validation needed - skip adding PASS result
# to reduce noise in validation output.
return results
def validate_model_option_samealbedo(yaml_data: dict) -> List[ValidationResult]:
"""Validate consistency between model physics options, reporting site names."""
results = []
physics = yaml_data.get("model", {}).get("physics", {})
samealbedo_roof = get_value_safe(physics, "samealbedo_roof")
samealbedo_wall = get_value_safe(physics, "samealbedo_wall")
if samealbedo_wall == 0:
for site in yaml_data.get("sites", []):
site_name = site.get("name", "Unknown")
vlay = site.get("properties", {}).get("vertical_layers", {})
walls = vlay.get("walls", [])
if isinstance(walls, dict): # rare but possible
walls = [walls]
found_albedos = []
for wall in walls:
alb_val = get_value_safe(wall, "alb")
if alb_val is not None:
found_albedos.append(alb_val)
building_archetype = site.get("properties", {}).get("building_archetype", {})
wallrefl_val = get_value_safe(building_archetype, "WallReflectivity")
msg = (
f"samealbedo_wall == 0. No check of consistency between walls albedo (found values: {found_albedos}) and WallReflectivity (found value: {wallrefl_val})."
)
results.append(
ValidationResult(
status="WARNING",
category="MODEL_OPTIONS",
parameter="samealbedo_wall",
site_gridid=site_name,
site_index=None,
message=f"{msg}",
suggested_value=None,
)
)
if samealbedo_roof == 0:
for site in yaml_data.get("sites", []):
site_name = site.get("name", "Unknown")
vlay = site.get("properties", {}).get("vertical_layers", {})
roofs = vlay.get("roofs", [])
if isinstance(roofs, dict): # rare but possible
roofs = [roofs]
found_albedos = []
for roof in roofs:
alb_val = get_value_safe(roof, "alb")
if alb_val is not None:
found_albedos.append(alb_val)
building_archetype = site.get("properties", {}).get("building_archetype", {})
roofrefl_val = get_value_safe(building_archetype, "RoofReflectivity")
msg = (
f"samealbedo_roof == 0. No check of consistency between roofs albedo (found values: {found_albedos}) and RoofReflectivity (found value: {roofrefl_val})."
)
results.append(
ValidationResult(
status="WARNING",
category="MODEL_OPTIONS",
parameter="samealbedo_roof",
site_gridid=site_name,
site_index=None,
message=f"{msg}",
suggested_value=None,
)
)
return results
def validate_model_option_rcmethod(yaml_data: dict) -> List[ValidationResult]:
"""Validate RoofOuterCapFrac and WallOuterCapFrac if rcmethod == 1.
For rcmethod == 2, validate required roof/wall external parameters are not null.
If provided, emit a warning with their values for user review.
"""
results = []
physics = yaml_data.get("model", {}).get("physics", {})
rcmethod_value = get_value_safe(physics, "rcmethod")
if rcmethod_value == 1:
sites = yaml_data.get("sites", [])
for site_idx, site in enumerate(sites):
props = site.get("properties", {})
building_archetype = props.get("building_archetype", {})
site_gridid = get_site_gridid(site)
# RoofOuterCapFrac
roof_frac_entry = building_archetype.get("RoofOuterCapFrac", {})
roof_frac = roof_frac_entry.get("value") if isinstance(roof_frac_entry, dict) else roof_frac_entry
if roof_frac is None:
results.append(
ValidationResult(
status="ERROR",
category="MODEL_OPTIONS",
parameter="building_archetype.RoofOuterCapFrac",
site_index=site_idx,
site_gridid=site_gridid,
message="RoofOuterCapFrac must be explicitly provided when rcmethod == 1.",
suggested_value="Set RoofOuterCapFrac to a value between 0 and 1 (exclusive)."
)
)
elif not (0 < roof_frac < 1):
results.append(
ValidationResult(
status="ERROR",
category="MODEL_OPTIONS",
parameter="building_archetype.RoofOuterCapFrac",
site_index=site_idx,
site_gridid=site_gridid,
message=f"RoofOuterCapFrac value {roof_frac} is out of valid range (0, 1) when rcmethod == 1.",
suggested_value="Set RoofOuterCapFrac to a value strictly between 0 and 1."
)
)
# WallOuterCapFrac
wall_frac_entry = building_archetype.get("WallOuterCapFrac", {})
wall_frac = wall_frac_entry.get("value") if isinstance(wall_frac_entry, dict) else wall_frac_entry
if wall_frac is None:
results.append(
ValidationResult(
status="ERROR",
category="MODEL_OPTIONS",
parameter="building_archetype.WallOuterCapFrac",
site_index=site_idx,
site_gridid=site_gridid,
message="WallOuterCapFrac must be explicitly provided when rcmethod == 1.",
suggested_value="Set WallOuterCapFrac to a value between 0 and 1 (exclusive)."
)
)
elif not (0 < wall_frac < 1):
results.append(
ValidationResult(
status="ERROR",
category="MODEL_OPTIONS",
parameter="building_archetype.WallOuterCapFrac",
site_index=site_idx,
site_gridid=site_gridid,
message=f"WallOuterCapFrac value {wall_frac} is out of valid range (0, 1) when rcmethod == 1.",
suggested_value="Set WallOuterCapFrac to a value strictly between 0 and 1."
)
)
elif rcmethod_value == 2:
required_wall_params = [
"WallextThickness",
"WallextEffectiveConductivity",
"WallextDensity",
"WallextCp",
]
required_roof_params = [
"RoofextThickness",
"RoofextEffectiveConductivity",
"RoofextDensity",
"RoofextCp",
]
sites = yaml_data.get("sites", [])
for site_idx, site in enumerate(sites):
props = site.get("properties", {})
building_archetype = props.get("building_archetype", {})
site_gridid = get_site_gridid(site)
# Collect provided wall params
provided_wall = []
for param in required_wall_params:
entry = building_archetype.get(param, {})
value = entry.get("value") if isinstance(entry, dict) else entry
if value in (None, ""):
results.append(
ValidationResult(
status="ERROR",
category="MODEL_OPTIONS",
parameter=f"building_archetype.{param}",
site_index=site_idx,
site_gridid=site_gridid,
message=f"{param} must be provided and non-null when rcmethod == 2.",
suggested_value=f"Set {param} to a valid numeric value."
)
)
else:
provided_wall.append(f"{param}={value}")
# Collect provided roof params
provided_roof = []
for param in required_roof_params:
entry = building_archetype.get(param, {})
value = entry.get("value") if isinstance(entry, dict) else entry
if value in (None, ""):
results.append(
ValidationResult(
status="ERROR",
category="MODEL_OPTIONS",
parameter=f"building_archetype.{param}",
site_index=site_idx,
site_gridid=site_gridid,
message=f"{param} must be provided and non-null when rcmethod == 2.",
suggested_value=f"Set {param} to a valid numeric value."
)
)
else:
provided_roof.append(f"{param}={value}")
# Emit warning if any required params are provided
if provided_wall:
results.append(
ValidationResult(
status="WARNING",
category="MODEL_OPTIONS",
parameter="building_archetype.wall_external_parameters",
site_index=site_idx,
site_gridid=site_gridid,
message=f"The following wall material parameters will be used for parameterisation: {', '.join(provided_wall)}. Please check that these values are valid for your building material.",
suggested_value="Review wall material properties for accuracy."
)
)
if provided_roof:
results.append(
ValidationResult(
status="WARNING",
category="MODEL_OPTIONS",
parameter="building_archetype.roof_external_parameters",
site_index=site_idx,
site_gridid=site_gridid,
message=f"The following roof material parameters will be used for parameterisation: {', '.join(provided_roof)}. Please check that these values are valid for your building material.",
suggested_value="Review roof material properties for accuracy."
)
)
return results
def validate_model_option_stebbsmethod(yaml_data: dict) -> List[ValidationResult]:
results = []
physics = yaml_data.get("model", {}).get("physics", {})
stebbsmethod = get_value_safe(physics, "stebbsmethod")
if stebbsmethod == 1:
sites = yaml_data.get("sites", [])
for site_idx, site in enumerate(sites):
props = site.get("properties", {})
stebbs = props.get("stebbs", {})
site_gridid = get_site_gridid(site)
# --- HotWaterFlowProfile validation ---
hwfp_entry = stebbs.get("HotWaterFlowProfile", {})
for daytype in ("working_day", "holiday"):
day_profile = hwfp_entry.get(daytype, {})
if isinstance(day_profile, dict):
for hour_str, v in day_profile.items():
if v not in (0, 1, 0.0, 1.0):
results.append(
ValidationResult(
status="ERROR",
category="MODEL_OPTIONS",
parameter=f"stebbs.HotWaterFlowProfile.{daytype}.{hour_str}",
site_index=site_idx,
site_gridid=site_gridid,
message=(
f"HotWaterFlowProfile for '{daytype}' hour '{hour_str}' must be 0 or 1, got '{v}'."
),
suggested_value="Set HotWaterFlowProfile to 0 or 1"
)
)
# --- Occupants and MetabolismProfile validation ---
building_archetype = props.get("building_archetype", {})
occupants_entry = building_archetype.get("Occupants", {})
occupants = occupants_entry.get("value") if isinstance(occupants_entry, dict) else occupants_entry
metabolism_profile = building_archetype.get("MetabolismProfile", {})
# Check for inconsistency: zero occupants with nonzero metabolism
if occupants == 0.0 and isinstance(metabolism_profile, dict):
problematic_entries = []
for daytype in ("working_day", "holiday"):
profile = metabolism_profile.get(daytype, {})
if isinstance(profile, dict):
for hour_str, metab_val in profile.items():
if metab_val not in (0, 0.0, None):
problematic_entries.append(
f"{daytype}.{hour_str}={metab_val}"
)
if problematic_entries:
results.append(
ValidationResult(
status="ERROR",
category="MODEL_OPTIONS",
parameter="building_archetype.MetabolismProfile",
site_index=site_idx,
site_gridid=site_gridid,
message=(
f"Occupants is 0.0 but MetabolismProfile has nonzero entries: {', '.join(problematic_entries)} (should all be 0)."
),
suggested_value="Set all MetabolismProfile entries to 0 if Occupants is 0.0"
)
)
return results
def validate_land_cover_consistency(yaml_data: dict) -> List[ValidationResult]:
"""Validate land cover fractions and parameters."""
results = []
sites = yaml_data.get("sites", [])
for site_idx, site in enumerate(sites):
props = site.get("properties", {})
land_cover = props.get("land_cover")
site_gridid = get_site_gridid(site)
if not land_cover:
results.append(
ValidationResult(
status="ERROR",
category="LAND_COVER",
parameter="land_cover",
site_index=site_idx,
site_gridid=site_gridid,
message="Missing land_cover block",
suggested_value="Add land_cover configuration with surface fractions",
)
)
continue
# Calculate sum of all surface fractions
sfr_sum = 0.0
surface_types = []
for surface_type, surface_props in land_cover.items():
if isinstance(surface_props, dict):
sfr_value = surface_props.get("sfr", {}).get("value")
if sfr_value is not None:
sfr_sum += sfr_value
surface_types.append((surface_type, sfr_value))
if abs(sfr_sum - 1.0) > SFR_FRACTION_TOL:
if sfr_sum == 0.0:
results.append(
ValidationResult(
status="ERROR",
category="LAND_COVER",
parameter="land_cover.surface_fractions",
site_index=site_idx,
site_gridid=site_gridid,
message=f"All surface fractions are zero or missing",
suggested_value="Set surface fractions (paved.sfr, bldgs.sfr, evetr.sfr, dectr.sfr, grass.sfr, bsoil.sfr, water.sfr) that sum to 1.0",
)
)
else:
surface_list = ", ".join([
f"{surf}={val:.4f}" for surf, val in surface_types
])
# Identify the surface with the largest fraction (same as auto-correction logic)
surface_dict = dict(surface_types)
max_surface = (
max(surface_dict.keys(), key=lambda k: surface_dict[k])
if surface_dict
else "surface"
)
results.append(
ValidationResult(
status="ERROR",
category="LAND_COVER",
parameter=f"{max_surface}.sfr",
site_index=site_idx,
site_gridid=site_gridid,
message=f"Surface fractions sum to {sfr_sum:.4f}, should equal 1.0 (auto-correction range: 1.0 ± {SFR_FRACTION_TOL:.1e}, current: {surface_list}. Validator will auto‑correct small deviations in this range.)",
suggested_value=f"Adjust the max surface {max_surface}.sfr or other surface fractions so they sum to exactly 1.0",
)
)
# Determine if biogenic CO2 parameters should be required
physics = yaml_data.get("model", {}).get("physics", {})
emissionsmethod = get_value_safe(physics, "emissionsmethod")
biogenic_params = {
"alpha_bioco2",
"alpha_enh_bioco2",
"beta_bioco2",
"beta_enh_bioco2",
"min_res_bioco2",
"theta_bioco2",
"resp_a",
"resp_b",
}
biogenic_surfaces = {"dectr", "evetr", "grass"}
for surface_type, sfr_value in surface_types:
if sfr_value > 0:
surface_props = land_cover[surface_type]
missing_params = _check_surface_parameters(surface_props, surface_type)
# If emissionsmethod disables CO2, skip biogenic params for relevant surfaces
if (
emissionsmethod is not None
and emissionsmethod in [0, 1, 2, 3, 4]
and surface_type in biogenic_surfaces
):
missing_params = [
p
for p in missing_params
if p.split(".")[-1] not in biogenic_params
]
for param_name in missing_params:
readable_message = (
f"Surface '{surface_type}' is active (sfr > 0) but parameter '{param_name}' "
f"is missing or null. Active surfaces require all their parameters to be "
f"properly configured for accurate simulation results."
)
actionable_suggestion = (
f"Set parameter '{param_name}' to an appropriate non-null value. "
f"Refer to SUEWS documentation for typical values for '{surface_type}' surfaces."
)
results.append(
ValidationResult(
status="ERROR",
category="LAND_COVER",
parameter=f"{surface_type}.{param_name}",
site_index=site_idx,
site_gridid=site_gridid,
message=readable_message,
suggested_value=actionable_suggestion,
)
)
zero_sfr_surfaces = [surf for surf, sfr in surface_types if sfr == 0]
if zero_sfr_surfaces:
for surf_type in zero_sfr_surfaces:
param_list = []
surf_props = (
site.get("properties", {}).get("land_cover", {}).get(surf_type, {})
)
def collect_param_names(d: dict, prefix: str = ""):
for k, v in d.items():
if k == "sfr":
continue
current_path = f"{prefix}.{k}" if prefix else k
if isinstance(v, dict):
if "value" in v:
param_list.append(current_path)
else:
collect_param_names(v, current_path)
collect_param_names(surf_props)
if param_list:
message = f"Parameters under sites.properties.land_cover.{surf_type} are not checked because '{surf_type}' surface fraction is 0."
param_names = ", ".join(param_list)
suggested_fix = f"Either set {surf_type} surface fraction > 0 to activate validation, or remove unused parameters: {param_names}"
results.append(
ValidationResult(
status="WARNING",
category="LAND_COVER",
parameter=f"land_cover.{surf_type}",
site_index=site_idx,
site_gridid=site_gridid,
message=message,
suggested_value=suggested_fix,
)
)
if not any(r.status == "ERROR" for r in results):
results.append(
ValidationResult(
status="PASS",
category="LAND_COVER",
parameter="land_cover_validation",
message="Land cover fractions and parameters validated successfully",
)
)
return results
def _check_surface_parameters(surface_props: dict, surface_type: str) -> List[str]:
"""Check for missing/empty parameters in surface configuration."""
missing_params = []
def _check_recursively(props: dict, path: str = ""):
for key, value in props.items():
if key == "sfr":
continue
current_path = f"{path}.{key}" if path else key
if isinstance(value, dict):
if "value" in value:
param_value = value["value"]
if param_value in (None, "") or (
isinstance(param_value, list)
and any(v in (None, "") for v in param_value)
):
missing_params.append(current_path)
else:
_check_recursively(value, current_path)
_check_recursively(surface_props)
return missing_params
def validate_geographic_parameters(yaml_data: dict) -> List[ValidationResult]:
"""Validate geographic coordinates and location parameters."""
results = []
sites = yaml_data.get("sites", [])
for site_idx, site in enumerate(sites):
props = site.get("properties", {})
site_gridid = get_site_gridid(site)
lat = get_value_safe(props, "lat")
if lat is None:
results.append(
ValidationResult(
status="ERROR",
category="GEOGRAPHY",
parameter="lat",
site_index=site_idx,
site_gridid=site_gridid,
message="Latitude is missing or null",
suggested_value="Set latitude value between -90 and 90 degrees",
)
)
elif not isinstance(lat, (int, float)):
results.append(
ValidationResult(
status="ERROR",
category="GEOGRAPHY",
parameter="lat",
site_index=site_idx,
site_gridid=site_gridid,
message="Latitude must be a numeric value",
suggested_value="Set latitude as a number between -90 and 90 degrees",
)
)
elif not (-90 <= lat <= 90):
results.append(
ValidationResult(
status="ERROR",
category="GEOGRAPHY",
parameter="lat",
site_index=site_idx,
site_gridid=site_gridid,
message=f"Latitude {lat} is outside valid range [-90, 90]",
suggested_value="Set latitude between -90 and 90 degrees",
)
)
lng = get_value_safe(props, "lng")
if lng is None:
results.append(
ValidationResult(
status="ERROR",
category="GEOGRAPHY",
parameter="lng",
site_index=site_idx,
site_gridid=site_gridid,
message="Longitude is missing or null",
suggested_value="Set longitude value between -180 and 180 degrees",
)
)
elif not isinstance(lng, (int, float)):
results.append(
ValidationResult(
status="ERROR",
category="GEOGRAPHY",
parameter="lng",
site_index=site_idx,
site_gridid=site_gridid,
message="Longitude must be a numeric value",
suggested_value="Set longitude as a number between -180 and 180 degrees",
)
)
elif not (-180 <= lng <= 180):
results.append(
ValidationResult(
status="ERROR",
category="GEOGRAPHY",
parameter="lng",
site_index=site_idx,
site_gridid=site_gridid,
message=f"Longitude {lng} is outside valid range [-180, 180]",
suggested_value="Set longitude between -180 and 180 degrees",
)
)
timezone = get_value_safe(props, "timezone")
if timezone is None:
results.append(
ValidationResult(
status="WARNING",
category="GEOGRAPHY",
parameter="timezone",
site_index=site_idx,
site_gridid=site_gridid,
message="Timezone parameter is missing - will be calculated automatically from latitude and longitude (see updated parameters)",
suggested_value="Timezone will be set based on your coordinates. You can also manually set the timezone value if you prefer a specific UTC offset",
)
)
anthro_emissions = props.get("anthropogenic_emissions", {})
if anthro_emissions:
startdls = get_value_safe(anthro_emissions, "startdls")
enddls = get_value_safe(anthro_emissions, "enddls")
if startdls is None or enddls is None:
results.append(
ValidationResult(
status="WARNING",
category="GEOGRAPHY",
parameter="anthropogenic_emissions.startdls,enddls",
site_index=site_idx,
site_gridid=site_gridid,
message="Daylight saving parameters (startdls, enddls) are missing - will be calculated automatically from geographic coordinates (see updated parameters)",
suggested_value="Parameters will be set based on your location. You can also manually set startdls and enddls if you prefer specific values",
)
)
error_count = sum(1 for r in results if r.status == "ERROR")
if error_count == 0:
results.append(
ValidationResult(
status="PASS",
category="GEOGRAPHY",
parameter="geographic_coordinates",
message="Geographic coordinates validated successfully",
)
)
return results
def validate_irrigation_doy(
ie_start: Optional[float],
ie_end: Optional[float],
lat: float,
model_year: int,
site_name: str,
) -> List[ValidationResult]:
"""
Validate irrigation DOY parameters with leap year, hemisphere, and tropical awareness.
This validator ensures irrigation timing parameters are logically consistent
and appropriate for the site's location. It checks:
1. DOY values are within valid range (1-365 or 1-366 for leap years)
2. Both parameters are set together or both disabled
3. Warm season appropriateness based on hemisphere and latitude:
- Tropical regions (|lat| < 23.5): No restrictions, irrigation allowed year-round
- Northern Hemisphere (lat >= 23.5): Warm season is May-September (DOY 121-273)
- Southern Hemisphere (lat <= -23.5): Warm season is November-March (DOY 305-90)
Args:
ie_start: Irrigation start day of year
ie_end: Irrigation end day of year
lat: Site latitude (for hemisphere and tropical detection)
model_year: Simulation year (for leap year detection)
site_name: Site identifier for error messages
Returns:
List of ValidationResult objects (errors, warnings, or empty)
"""
results = []
# Helper: treat 0 and None as equivalent (both mean "disabled")
def is_disabled(value):