forked from Urban-Meteorology-Reading/SUEWS
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathtest_validation.py
More file actions
2563 lines (2098 loc) · 90.7 KB
/
test_validation.py
File metadata and controls
2563 lines (2098 loc) · 90.7 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
"""
Consolidated tests for SUEWS validation logic.
This file combines:
- Conditional validation from test_conditional_validation.py
- Validation utilities from test_validation_utils.py
- Top-down validation from test_validation_topdown.py
- Essential migrated validators (from test_migrated_validators.py)
- Validator improvements from test_validator_improvements.py
"""
import io
import logging
from pathlib import Path
import tempfile
from types import SimpleNamespace
import warnings
import pytest
import supy as sp
from supy._env import trv_supy_module
from supy.data_model.core import SUEWSConfig
from supy.data_model.core.site import (
LAIParams,
DectrProperties,
EvetrProperties,
GrassProperties,
LandCover,
Site,
SiteProperties,
)
from supy.data_model.core.state import (
InitialStateDectr,
InitialStateEvetr,
InitialStateGrass,
InitialStates,
)
from supy.data_model.core.type import RefValue
from supy.data_model.validation.core.utils import check_missing_params
from supy.data_model.validation.pipeline.phase_b import validate_model_option_samealbedo, adjust_seasonal_parameters
import copy
# A tiny “site” stub that only carries exactly the properties our validators look at
class DummySite:
def __init__(self, properties, name="SiteX"):
self.properties = properties
self.name = name
# Helper to construct a SUEWSConfig without running Pydantic on sites,
# then inject the desired physics settings.
def make_cfg(**physics_kwargs):
cfg = SUEWSConfig.model_construct() # bypass validation
# physics values wrapped in a simple .value holder
phys = SimpleNamespace(**{
k: SimpleNamespace(value=v) for k, v in physics_kwargs.items()
})
cfg.model = SimpleNamespace(physics=phys)
return cfg
def test_needs_stebbs_validation_true_and_false():
cfg = make_cfg(stebbsmethod=1)
assert cfg._needs_stebbs_validation() is True
cfg2 = make_cfg(stebbsmethod=0)
assert cfg2._needs_stebbs_validation() is False
def test_validate_stebbs_missing_properties_block():
cfg = make_cfg(stebbsmethod=1)
site = DummySite(properties=None, name="MySite")
msgs = SUEWSConfig._validate_stebbs(cfg, site, site_index=0)
assert msgs == ["Missing 'properties' section (required for STEBBS validation)"]
def test_validate_stebbs_missing_stebbs_section():
cfg = make_cfg(stebbsmethod=1)
props = SimpleNamespace(stebbs=None)
site = DummySite(properties=props, name="MySite")
msgs = SUEWSConfig._validate_stebbs(cfg, site, site_index=0)
assert msgs == ["Missing 'stebbs' section (required when stebbsmethod=1)"]
def test_validate_stebbs_missing_parameters():
cfg = make_cfg(stebbsmethod=1)
# Provide an empty stebbs object
props = SimpleNamespace(stebbs=SimpleNamespace())
site = DummySite(properties=props, name="MySite")
msgs = SUEWSConfig._validate_stebbs(cfg, site, site_index=0)
# Should mention at least one of the required params
assert msgs and msgs[0].startswith("Missing required STEBBS parameters:")
def test_needs_rsl_validation_true_and_false():
# After conditional validation fix, validation is disabled by default
# unless physics parameters are explicitly configured
cfg = make_cfg(rslmethod=2)
assert cfg._needs_rsl_validation() is False # Disabled by default now
cfg2 = make_cfg(rslmethod=1)
assert cfg2._needs_rsl_validation() is False
def test_validate_rsl_no_land_cover_or_sfr():
cfg = make_cfg(rslmethod=2)
site = DummySite(properties=None)
assert SUEWSConfig._validate_rsl(cfg, site, 0) == []
# land_cover without bldgs
site2 = DummySite(properties=SimpleNamespace(land_cover=None))
assert SUEWSConfig._validate_rsl(cfg, site2, 0) == []
def test_validate_rsl_requires_faibldg():
cfg = make_cfg(rslmethod=2)
# build a land_cover.bldgs with sfr>0 but no faibldg
bldgs = SimpleNamespace(sfr=SimpleNamespace(value=0.5), faibldg=None)
lc = SimpleNamespace(bldgs=bldgs)
site = DummySite(properties=SimpleNamespace(land_cover=lc), name="SiteR")
msgs = SUEWSConfig._validate_rsl(cfg, site, 1)
assert len(msgs) == 1
assert "bldgs.faibldg must be set" in msgs[0]
assert "SiteR" in msgs[0]
def test_needs_storage_validation_true_and_false():
# After conditional validation fix, validation is disabled by default
# unless physics parameters are explicitly configured
cfg = make_cfg(storageheatmethod=6)
assert cfg._needs_storage_validation() is False # Disabled by default now
cfg2 = make_cfg(storageheatmethod=1)
assert cfg2._needs_storage_validation() is False
def test_validate_storage_requires_numeric_and_lambda():
cfg = make_cfg(storageheatmethod=6)
# stub thermal_layers: dz has one bad None, k OK, rho_cp missing
th = SimpleNamespace(
dz=SimpleNamespace(value=[None]),
k=SimpleNamespace(value=[1.0, 2.0]),
# rho_cp attribute not defined → treated missing
)
wall = SimpleNamespace(thermal_layers=th)
props = SimpleNamespace(
vertical_layers=SimpleNamespace(walls=[wall]),
lambda_c=None, # missing
)
site = DummySite(properties=props, name="SiteS")
msgs = SUEWSConfig._validate_storage(cfg, site, 2)
# must flag dz, rho_cp and lambda_c
assert any("thermal_layers.dz" in m for m in msgs)
assert any("thermal_layers.rho_cp" in m for m in msgs)
assert any("properties.lambda_c must be set" in m for m in msgs)
# should include the site name
assert any("SiteS" in m for m in msgs)
def test_validate_lai_ranges_no_land_cover():
"""Test LAI validation with no land cover."""
cfg = SUEWSConfig.model_construct()
site = DummySite(properties=None)
has_issues = cfg._check_lai_ranges(None, "TestSite")
assert has_issues is False
def test_validate_lai_ranges_no_vegetation():
"""Test LAI validation with no vegetation surfaces."""
cfg = SUEWSConfig.model_construct()
# land_cover with no vegetation surfaces
lc = SimpleNamespace(
paved=SimpleNamespace(sfr=SimpleNamespace(value=0.5)),
bldgs=SimpleNamespace(sfr=SimpleNamespace(value=0.5)),
)
has_issues = cfg._check_lai_ranges(lc, "TestSite")
assert has_issues is False
def test_validate_lai_ranges_invalid_laimin_laimax():
"""Test LAI validation detects invalid laimin > laimax."""
cfg = SUEWSConfig.model_construct()
# Create vegetation surface with invalid LAI range
lai = SimpleNamespace(
laimin=SimpleNamespace(value=5.0), laimax=SimpleNamespace(value=3.0)
)
grass = SimpleNamespace(lai=lai)
lc = SimpleNamespace(grass=grass)
has_issues = cfg._check_lai_ranges(lc, "TestSite")
assert has_issues is True
assert cfg._validation_summary["total_warnings"] >= 1
assert "LAI range validation" in cfg._validation_summary["issue_types"]
assert any(
"laimin (5.0) must be <= laimax (3.0)" in msg
for msg in cfg._validation_summary["detailed_messages"]
)
def test_validate_lai_ranges_invalid_baset_gddfull():
"""Test LAI validation detects invalid baset > gddfull."""
cfg = SUEWSConfig.model_construct()
# Create vegetation surface with invalid baset/gddfull range
lai = SimpleNamespace(
laimin=SimpleNamespace(value=1.0),
laimax=SimpleNamespace(value=5.0),
baset=SimpleNamespace(value=15.0),
gddfull=SimpleNamespace(value=10.0),
)
dectr = SimpleNamespace(lai=lai)
lc = SimpleNamespace(dectr=dectr)
has_issues = cfg._check_lai_ranges(lc, "TestSite")
assert has_issues is True
assert cfg._validation_summary["total_warnings"] >= 1
assert "LAI range validation" in cfg._validation_summary["issue_types"]
assert any(
"baset (15.0) must be <= gddfull (10.0)" in msg
for msg in cfg._validation_summary["detailed_messages"]
)
def test_validate_lai_ranges_multiple_vegetation_surfaces():
"""Test LAI validation checks all vegetation surfaces."""
cfg = SUEWSConfig.model_construct()
# Create multiple vegetation surfaces with invalid LAI ranges
lai_invalid = SimpleNamespace(
laimin=SimpleNamespace(value=5.0), laimax=SimpleNamespace(value=3.0)
)
grass = SimpleNamespace(lai=lai_invalid)
dectr = SimpleNamespace(lai=lai_invalid)
evetr = SimpleNamespace(lai=lai_invalid)
lc = SimpleNamespace(grass=grass, dectr=dectr, evetr=evetr)
has_issues = cfg._check_lai_ranges(lc, "TestSite")
assert has_issues is True
assert cfg._validation_summary["total_warnings"] >= 3
# Check that all surfaces were validated
messages = cfg._validation_summary["detailed_messages"]
assert any("grass" in msg for msg in messages)
assert any("dectr" in msg for msg in messages)
assert any("evetr" in msg for msg in messages)
def test_validate_lai_ranges_valid_ranges():
"""Test LAI validation passes with valid ranges."""
cfg = SUEWSConfig.model_construct()
# Create vegetation surface with valid LAI ranges
lai = SimpleNamespace(
laimin=SimpleNamespace(value=1.0),
laimax=SimpleNamespace(value=5.0),
baset=SimpleNamespace(value=5.0),
gddfull=SimpleNamespace(value=200.0),
)
grass = SimpleNamespace(lai=lai)
lc = SimpleNamespace(grass=grass)
has_issues = cfg._check_lai_ranges(lc, "TestSite")
assert has_issues is False
assert cfg._validation_summary["total_warnings"] == 0
def test_validate_lai_ranges_missing_lai_graceful():
"""Test LAI validation handles missing LAI gracefully."""
cfg = SUEWSConfig.model_construct()
# Create vegetation surface without LAI
grass = SimpleNamespace() # No lai attribute
lc = SimpleNamespace(grass=grass)
has_issues = cfg._check_lai_ranges(lc, "TestSite")
assert has_issues is False
def test_validate_lai_ranges_none_values():
"""Test LAI validation handles None values gracefully."""
cfg = SUEWSConfig.model_construct()
# Create vegetation surface with None LAI values
lai = SimpleNamespace(laimin=None, laimax=None, baset=None, gddfull=None)
grass = SimpleNamespace(lai=lai)
lc = SimpleNamespace(grass=grass)
has_issues = cfg._check_lai_ranges(lc, "TestSite")
assert has_issues is False
def test_auto_albedo_trees_follow_lai_relation():
"""Test tree albedo follows the direct LAI-albedo relationship.
Physical basis: Trees have dark bark/branches as background surface.
- Low LAI (sparse canopy) -> more bark visible -> lower albedo
- High LAI (dense foliage) -> leaves dominate -> higher albedo
Leaf albedo (0.20-0.30) typically exceeds bark albedo (0.10-0.15).
Test verifies boundary conditions:
- evetr at LAI=laimin (ratio=0) -> alb_id = alb_min = 0.1
- dectr at LAI=laimax (ratio=1) -> alb_id = alb_max = 0.4
"""
evetr_props = EvetrProperties(
alb_min=0.1,
alb_max=0.3,
lai=LAIParams(laimin=1.0, laimax=3.0),
)
dectr_props = DectrProperties(
alb_min=0.2,
alb_max=0.4,
lai=LAIParams(laimin=2.0, laimax=4.0),
)
land_cover = LandCover(evetr=evetr_props, dectr=dectr_props)
site_props = SiteProperties(land_cover=land_cover)
evetr_state = InitialStateEvetr(alb_id=None, lai_id=1.0)
dectr_state = InitialStateDectr(alb_id=None, lai_id=4.0)
initial_states = InitialStates(evetr=evetr_state, dectr=dectr_state)
site = Site(properties=site_props, initial_states=initial_states)
config = SUEWSConfig(sites=[site])
assert config.sites[0].initial_states.evetr.alb_id == pytest.approx(0.1)
assert config.sites[0].initial_states.dectr.alb_id == pytest.approx(0.4)
def test_auto_albedo_grass_reversed_relation():
"""Test grass albedo follows the reversed LAI-albedo relationship.
Physical basis: Grass has bright soil/litter as background surface.
- Low LAI (sparse grass) -> more soil visible -> higher albedo
- High LAI (dense grass) -> green blades dominate -> lower albedo
Dry soil albedo (0.25-0.45) typically exceeds grass blade albedo (0.18-0.25).
Test verifies boundary conditions:
- grass at LAI=laimin (ratio=0) -> alb_id = alb_max = 0.4 (bright soil)
- grass at LAI=laimax (ratio=1) -> alb_id = alb_min = 0.2 (dense grass)
"""
grass_props = GrassProperties(
alb_min=0.2,
alb_max=0.4,
lai=LAIParams(laimin=0.5, laimax=2.5),
)
land_cover = LandCover(grass=grass_props)
site_props = SiteProperties(land_cover=land_cover)
grass_state_low = InitialStateGrass(alb_id=None, lai_id=0.5)
grass_state_high = InitialStateGrass(alb_id=None, lai_id=2.5)
site_low = Site(
properties=site_props,
initial_states=InitialStates(grass=grass_state_low),
)
site_high = Site(
properties=site_props,
initial_states=InitialStates(grass=grass_state_high),
)
config = SUEWSConfig(sites=[site_low, site_high])
assert config.sites[0].initial_states.grass.alb_id == pytest.approx(0.4)
assert config.sites[1].initial_states.grass.alb_id == pytest.approx(0.2)
def test_auto_albedo_preserves_user_value():
"""Test user-provided albedo is preserved."""
evetr_props = EvetrProperties(
alb_min=0.1,
alb_max=0.3,
lai=LAIParams(laimin=1.0, laimax=3.0),
)
site_props = SiteProperties(land_cover=LandCover(evetr=evetr_props))
evetr_state = InitialStateEvetr(alb_id=0.28, lai_id=2.0)
site = Site(
properties=site_props,
initial_states=InitialStates(evetr=evetr_state),
)
config = SUEWSConfig(sites=[site])
assert config.sites[0].initial_states.evetr.alb_id == pytest.approx(0.28)
def test_validate_albedo_id_within_range():
"""Test initial albedo validation against vegetation limits."""
evetr_props = EvetrProperties(
alb_min=0.1,
alb_max=0.2,
lai=LAIParams(laimin=1.0, laimax=3.0),
)
site_props = SiteProperties(land_cover=LandCover(evetr=evetr_props))
evetr_state = InitialStateEvetr(alb_id=0.5, lai_id=2.0)
site = Site(
properties=site_props,
initial_states=InitialStates(evetr=evetr_state),
)
with pytest.raises(ValueError, match="alb_id"):
SUEWSConfig(sites=[site])
def test_auto_albedo_midrange_interpolation():
"""Test linear interpolation at mid-range LAI produces expected intermediate albedo.
For trees (direct relationship):
lai_ratio = (2.0 - 1.0) / (3.0 - 1.0) = 0.5
alb_id = 0.1 + (0.3 - 0.1) * 0.5 = 0.2
For grass (reversed relationship):
lai_ratio = (1.5 - 0.5) / (2.5 - 0.5) = 0.5
alb_id = 0.4 - (0.4 - 0.2) * 0.5 = 0.3
"""
evetr_props = EvetrProperties(
alb_min=0.1,
alb_max=0.3,
lai=LAIParams(laimin=1.0, laimax=3.0),
)
grass_props = GrassProperties(
alb_min=0.2,
alb_max=0.4,
lai=LAIParams(laimin=0.5, laimax=2.5),
)
land_cover = LandCover(evetr=evetr_props, grass=grass_props)
site_props = SiteProperties(land_cover=land_cover)
evetr_state = InitialStateEvetr(alb_id=None, lai_id=2.0)
grass_state = InitialStateGrass(alb_id=None, lai_id=1.5)
initial_states = InitialStates(evetr=evetr_state, grass=grass_state)
site = Site(properties=site_props, initial_states=initial_states)
config = SUEWSConfig(sites=[site])
assert config.sites[0].initial_states.evetr.alb_id == pytest.approx(0.2)
assert config.sites[0].initial_states.grass.alb_id == pytest.approx(0.3)
def test_auto_albedo_clamps_lai_outside_range():
"""Test LAI values outside [laimin, laimax] are clamped to [0, 1] ratio.
lai_id below laimin -> ratio clamped to 0 -> boundary albedo
lai_id above laimax -> ratio clamped to 1 -> boundary albedo
"""
evetr_props = EvetrProperties(
alb_min=0.1,
alb_max=0.3,
lai=LAIParams(laimin=2.0, laimax=4.0),
)
land_cover = LandCover(evetr=evetr_props)
site_props = SiteProperties(land_cover=land_cover)
# LAI below laimin -> clamped to ratio=0 -> alb_min
evetr_below = InitialStateEvetr(alb_id=None, lai_id=0.5)
site_below = Site(
properties=site_props,
initial_states=InitialStates(evetr=evetr_below),
)
# LAI above laimax -> clamped to ratio=1 -> alb_max
evetr_above = InitialStateEvetr(alb_id=None, lai_id=6.0)
site_above = Site(
properties=site_props,
initial_states=InitialStates(evetr=evetr_above),
)
config = SUEWSConfig(sites=[site_below, site_above])
assert config.sites[0].initial_states.evetr.alb_id == pytest.approx(0.1)
assert config.sites[1].initial_states.evetr.alb_id == pytest.approx(0.3)
def test_auto_albedo_zero_lai_range():
"""Test auto-albedo when laimin equals laimax (zero range).
When lai_range <= 0, lai_ratio should be set to 0.0.
For trees: alb_id = alb_min + (alb_max - alb_min) * 0.0 = alb_min
For grass: alb_id = alb_max - (alb_max - alb_min) * 0.0 = alb_max
"""
evetr_props = EvetrProperties(
alb_min=0.1,
alb_max=0.3,
lai=LAIParams(laimin=2.0, laimax=2.0),
)
grass_props = GrassProperties(
alb_min=0.2,
alb_max=0.4,
lai=LAIParams(laimin=1.5, laimax=1.5),
)
land_cover = LandCover(evetr=evetr_props, grass=grass_props)
site_props = SiteProperties(land_cover=land_cover)
evetr_state = InitialStateEvetr(alb_id=None, lai_id=2.0)
grass_state = InitialStateGrass(alb_id=None, lai_id=1.5)
initial_states = InitialStates(evetr=evetr_state, grass=grass_state)
site = Site(properties=site_props, initial_states=initial_states)
config = SUEWSConfig(sites=[site])
assert config.sites[0].initial_states.evetr.alb_id == pytest.approx(0.1)
assert config.sites[0].initial_states.grass.alb_id == pytest.approx(0.4)
def test_auto_albedo_with_refvalue_inputs():
"""Test auto-albedo with RefValue-wrapped inputs exercises _unwrap_value."""
evetr_props = EvetrProperties(
alb_min=RefValue(value=0.1),
alb_max=RefValue(value=0.3),
lai=LAIParams(laimin=1.0, laimax=3.0),
)
land_cover = LandCover(evetr=evetr_props)
site_props = SiteProperties(land_cover=land_cover)
evetr_state = InitialStateEvetr(alb_id=None, lai_id=RefValue(value=2.0))
site = Site(
properties=site_props,
initial_states=InitialStates(evetr=evetr_state),
)
config = SUEWSConfig(sites=[site])
# lai_ratio = (2.0 - 1.0) / (3.0 - 1.0) = 0.5
# alb_id = 0.1 + (0.3 - 0.1) * 0.5 = 0.2
assert config.sites[0].initial_states.evetr.alb_id == pytest.approx(0.2)
def test_validate_samealbedo_wall_requires_identical_wall_albedos():
"""
When samealbedo_wall is ON but walls have different albedos,
we should get an error about them needing to be identical.
"""
cfg = make_cfg(samealbedo_wall=1)
walls = [
SimpleNamespace(alb=SimpleNamespace(value=0.5)),
SimpleNamespace(alb=SimpleNamespace(value=0.6)), # mismatch
]
vl = SimpleNamespace(walls=walls)
ba = SimpleNamespace(WallReflectivity=SimpleNamespace(value=0.5))
props = SimpleNamespace(vertical_layers=vl, building_archetype=ba)
site = DummySite(properties=props, name="SiteWallMismatch")
msgs = SUEWSConfig._validate_samealbedo_wall(cfg, site, 0)
assert len(msgs) == 1
assert "so all walls albedoes must be identical;" in msgs[0]
assert "SiteWallMismatch" in msgs[0]
def test_validate_samealbedo_wall_requires_match_with_wallreflectivity():
"""
When samealbedo_wall is ON, all walls have same alb but it differs
from building_archetype.WallReflectivity, we should get an error.
"""
cfg = make_cfg(samealbedo_wall=1)
walls = [
SimpleNamespace(alb=SimpleNamespace(value=0.5)),
SimpleNamespace(alb=SimpleNamespace(value=0.5)),
]
vl = SimpleNamespace(walls=walls)
ba = SimpleNamespace(WallReflectivity=SimpleNamespace(value=0.345))
props = SimpleNamespace(vertical_layers=vl, building_archetype=ba)
site = DummySite(properties=props, name="SiteRefMismatch")
msgs = SUEWSConfig._validate_samealbedo_wall(cfg, site, 0)
assert len(msgs) == 1
msg = msgs[0]
assert "must equal properties.building_archetype.WallReflectivity (0.345)" in msg
assert "walls[0]=0.5" in msg
def test_validate_samealbedo_roof_requires_match_with_roofreflectivity():
"""
When samealbedo_roof is ON, all roofs have same alb but it differs
from building_archetype.RoofReflectivity, we should get an error.
"""
cfg = make_cfg(samealbedo_roof=1)
roofs = [
SimpleNamespace(alb=SimpleNamespace(value=0.5)),
SimpleNamespace(alb=SimpleNamespace(value=0.5)),
]
vl = SimpleNamespace(roofs=roofs)
ba = SimpleNamespace(RoofReflectivity=SimpleNamespace(value=0.345))
props = SimpleNamespace(vertical_layers=vl, building_archetype=ba)
site = DummySite(properties=props, name="SiteRefMismatch")
msgs = SUEWSConfig._validate_samealbedo_roof(cfg, site, 0)
assert len(msgs) == 1
msg = msgs[0]
assert "must equal properties.building_archetype.RoofReflectivity (0.345)" in msg
assert "roofs[0]=0.5" in msg
def test_validate_samealbedo_roof_requires_identical_roof_albedos():
"""
When samealbedo_roof is ON but roofs have different albedos,
we should get an error about them needing to be identical.
"""
cfg = make_cfg(samealbedo_roof=1)
roofs = [
SimpleNamespace(alb=SimpleNamespace(value=0.5)),
SimpleNamespace(alb=SimpleNamespace(value=0.6)), # mismatch
]
vl = SimpleNamespace(roofs=roofs)
ba = SimpleNamespace(RoofReflectivity=SimpleNamespace(value=0.5))
props = SimpleNamespace(vertical_layers=vl, building_archetype=ba)
site = DummySite(properties=props, name="SiteRoofMismatch")
msgs = SUEWSConfig._validate_samealbedo_roof(cfg, site, 0)
assert len(msgs) == 1
assert "so all roofs albedoes must be identical;" in msgs[0]
assert "SiteRoofMismatch" in msgs[0]
def test_needs_samealbedo_roof_validation_true_and_false():
cfg = make_cfg(samealbedo_roof=1)
assert cfg._needs_samealbedo_roof_validation() is True
cfg2 = make_cfg(samealbedo_roof=0)
assert cfg2._needs_samealbedo_roof_validation() is False
def test_needs_samealbedo_wall_validation_true_and_false():
cfg = make_cfg(samealbedo_wall=1)
assert cfg._needs_samealbedo_wall_validation() is True
cfg2 = make_cfg(samealbedo_wall=0)
assert cfg2._needs_samealbedo_wall_validation() is False
def test_phase_b_validate_model_option_samealbedo_disabled():
"""Test validate_model_option_samealbedo returns WARNING when option is disabled (==0)."""
yaml_data_wall = {
"model": {
"physics": {
"samealbedo_wall": {"value": 0}
}
},
"sites": [{"name": "site1", "properties": {}}],
}
results_wall = validate_model_option_samealbedo(yaml_data_wall)
assert len(results_wall) == 1
assert results_wall[0].status == "WARNING"
assert "no check of consistency" in results_wall[0].message.lower()
assert "samealbedo_wall == 0" in results_wall[0].message.lower()
yaml_data_roof = {
"model": {
"physics": {
"samealbedo_roof": {"value": 0}
}
},
"sites": [{"name": "site1", "properties": {}}],
}
results_roof = validate_model_option_samealbedo(yaml_data_roof)
assert len(results_roof) == 1
assert results_roof[0].status == "WARNING"
assert "no check of consistency" in results_roof[0].message.lower()
assert "samealbedo_roof == 0" in results_roof[0].message.lower()
def test_needs_spartacus_validation_true_and_false():
cfg = make_cfg()
cfg.model.physics.netradiationmethod = 1001
assert cfg._needs_spartacus_validation() is True
cfg2 = make_cfg()
cfg2.model.physics.netradiationmethod = 1
assert cfg2._needs_spartacus_validation() is False
def test_validate_spartacus_building_height_error():
cfg = make_cfg(netradiationmethod=1001)
# bldgh exceeds height[nlayer+1]
bldgs = SimpleNamespace(bldgh=15.0)
vertical_layers = SimpleNamespace(height=[5.0, 10.0, 12.0], nlayer=1)
props = SimpleNamespace(
land_cover=SimpleNamespace(bldgs=bldgs),
vertical_layers=vertical_layers
)
site = DummySite(properties=props, name="TestSite")
msgs = cfg._validate_spartacus_building_height(site, 0)
# Should produce exactly one clear message with correct content
assert msgs
msg = msgs[0]
assert "TestSite" in msg
assert "bldgh=15.0" in msg
assert "height[2]=10.0" in msg
def test_validate_spartacus_building_height_no_error():
cfg = make_cfg(netradiationmethod=1001)
# bldgh does not exceed height[nlayer+1]
bldgs = SimpleNamespace(bldgh=8.0)
vertical_layers = SimpleNamespace(height=[5.0, 10.0, 12.0], nlayer=1)
props = SimpleNamespace(
land_cover=SimpleNamespace(bldgs=bldgs),
vertical_layers=vertical_layers
)
site = DummySite(properties=props, name="TestSite")
msgs = cfg._validate_spartacus_building_height(site, 0)
assert msgs == []
def test_validate_spartacus_sfr_mismatch_bldgs_frac():
cfg = SUEWSConfig.model_construct()
cfg.model = SimpleNamespace(physics=SimpleNamespace(netradiationmethod=1001))
bldgs = SimpleNamespace(sfr=0.6)
lc = SimpleNamespace(bldgs=bldgs, evetr=None, dectr=None)
vertical_layers = SimpleNamespace(
building_frac=[0.3],
veg_frac=[0.0],
)
props = SimpleNamespace(land_cover=lc, vertical_layers=vertical_layers)
site = DummySite(properties=props, name="TestSite")
msgs = cfg._validate_spartacus_sfr(site, 0)
assert msgs
assert any(
"bldgs.sfr (0.6) does not match vertical_layers.building_frac[0] (0.3)"
in m
for m in msgs
)
def test_validate_spartacus_sfr_consistent_values():
cfg = SUEWSConfig.model_construct()
cfg.model = SimpleNamespace(physics=SimpleNamespace(netradiationmethod=1001))
bldgs = SimpleNamespace(sfr=0.3)
evetr = SimpleNamespace(sfr=0.1)
dectr = SimpleNamespace(sfr=0.2)
lc = SimpleNamespace(bldgs=bldgs, evetr=evetr, dectr=dectr)
vertical_layers = SimpleNamespace(
building_frac=[0.3],
veg_frac=[0.3],
)
props = SimpleNamespace(land_cover=lc, vertical_layers=vertical_layers)
site = DummySite(properties=props, name="TestSite")
msgs = cfg._validate_spartacus_sfr(site, 0)
assert msgs == []
def test_validate_spartacus_sfr_mismatch_veg_frac():
"""SPARTACUS SFR validation flags mismatch between evetr.sfr + dectr.sfr and max(veg_frac)."""
cfg = SUEWSConfig.model_construct()
cfg.model = SimpleNamespace(physics=SimpleNamespace(netradiationmethod=1001))
# land_cover vegetation: evetr + dectr = 0.4
evetr = SimpleNamespace(sfr=0.1)
dectr = SimpleNamespace(sfr=0.3)
bldgs = SimpleNamespace(sfr=0.2)
lc = SimpleNamespace(bldgs=bldgs, evetr=evetr, dectr=dectr)
# vertical_layers veg_frac: max = 0.1 -> mismatch with 0.4
vertical_layers = SimpleNamespace(
building_frac=[0.2],
veg_frac=[0.1], # max(vertical_layers.veg_frac) = 0.1
)
props = SimpleNamespace(land_cover=lc, vertical_layers=vertical_layers)
site = DummySite(properties=props, name="TestSite")
msgs = cfg._validate_spartacus_sfr(site, 0)
assert msgs
assert any(
"evetr.sfr + dectr.sfr (0.4) does not match max(vertical_layers.veg_frac) (0.1)"
in m
for m in msgs
)
# From test_validation_topdown.py
class TestTopDownValidation:
"""Test the new top-down validation approach."""
def test_no_warnings_during_import(self):
"""Verify importing doesn't generate spurious warnings."""
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
import importlib
import supy.data_model
importlib.reload(supy.data_model)
assert len(w) == 0, f"Import generated {len(w)} warnings"
def test_no_warnings_during_component_creation(self):
"""Verify component creation doesn't generate warnings."""
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
# Create various components that used to warn
from supy.data_model.core.human_activity import CO2Params
from supy.data_model.core.site import Conductance
from supy.data_model.core.surface import BldgsProperties
co2 = CO2Params()
cond = Conductance()
bldgs = BldgsProperties(sfr=RefValue(0.3))
# Should have no warnings at component level
assert len(w) == 0, f"Component creation generated {len(w)} warnings"
def test_validation_at_config_level(self):
"""Test that validation happens at config level with clear summary."""
config_yaml = """
sites:
- site_id: test_site
properties:
land_cover:
bldgs:
sfr: {value: 0.45}
# Missing critical params
"""
with tempfile.NamedTemporaryFile(mode="w", suffix=".yml", delete=False) as f:
f.write(config_yaml)
yaml_path = Path(f.name)
try:
# Capture validation output
log_capture = io.StringIO()
handler = logging.StreamHandler(log_capture)
handler.setLevel(logging.WARNING)
logger = logging.getLogger("SuPy")
# Ensure logger level allows WARNING messages
original_level = logger.level
logger.setLevel(logging.WARNING)
logger.addHandler(handler)
# Load config
config = SUEWSConfig.from_yaml(yaml_path)
# Check validation summary was generated
log_output = log_capture.getvalue()
assert "VALIDATION SUMMARY" in log_output
assert "Missing building parameters" in log_output
assert "generate_annotated_yaml" in log_output
logger.removeHandler(handler)
logger.setLevel(original_level)
finally:
yaml_path.unlink()
def test_annotated_yaml_generation(self):
"""Test annotated YAML shows missing parameters clearly."""
config_yaml = """
sites:
- site_id: test_site
properties:
land_cover:
bldgs:
sfr: {value: 0.3}
"""
with tempfile.NamedTemporaryFile(mode="w", suffix=".yml", delete=False) as f:
f.write(config_yaml)
yaml_path = Path(f.name)
try:
config = SUEWSConfig.from_yaml(yaml_path)
annotated_path = config.generate_annotated_yaml(yaml_path)
# Check annotated file exists and contains annotations
annotated_path = Path(annotated_path) # Convert string to Path
assert annotated_path.exists()
content = annotated_path.read_text()
# Should have missing parameter annotations
assert "[ERROR] MISSING:" in content
assert "[TIP] ADD HERE:" in content
assert "bldgh:" in content # Missing building height
assert "faibldg:" in content # Missing frontal area
# Check simplified syntax (no {value: ...} wrapper)
assert "bldgh: 20.0" in content or "bldgh: " in content
assert "bldgh: {value:" not in content
annotated_path.unlink()
finally:
yaml_path.unlink()
def test_no_validation_with_complete_config(self):
"""Test no warnings when all required parameters are provided."""
# This would be a complex test - simplified for now
# Key point: when all params provided, validation summary should be minimal
pass
def test_auto_generate_annotated_yaml_option(self):
"""Test auto_generate_annotated parameter works correctly."""
config_yaml = """
sites:
- name: Test Site
gridiv: 1
properties:
lat: {value: 51.5}
lng: {value: -0.1}
land_cover:
bldgs:
sfr: {value: 0.4}
# Missing bldgh and faibldg parameters
"""
with tempfile.NamedTemporaryFile(mode="w", suffix=".yml", delete=False) as f:
f.write(config_yaml)
yaml_path = Path(f.name)
try:
# Test with auto_generate_annotated=True
config = SUEWSConfig.from_yaml(yaml_path, auto_generate_annotated=True)
# Check that annotated file was automatically generated
annotated_path = yaml_path.parent / f"{yaml_path.stem}_annotated.yml"
assert annotated_path.exists(), (
"Annotated YAML should be generated when auto_generate_annotated=True"
)
# Verify content
content = annotated_path.read_text()
assert "ANNOTATED SUEWS CONFIGURATION" in content
assert "bldgh" in content
# Clean up
annotated_path.unlink()
# Test with auto_generate_annotated=False (default)
config2 = SUEWSConfig.from_yaml(yaml_path, auto_generate_annotated=False)
assert not annotated_path.exists(), (
"Annotated YAML should not be generated when auto_generate_annotated=False"
)
finally:
yaml_path.unlink()
class TestValidationUtils:
"""Test validation utility functions still work correctly."""
def test_check_missing_params_with_refvalue(self):
"""Test RefValue handling in validation utils."""
class TestObj:
good = RefValue(value=10.0)
bad = RefValue(value=None)
also_bad = None
params = {"good": "Good param", "bad": "Bad param", "also_bad": "Also bad"}
missing = check_missing_params(params, TestObj(), "test", "test")
assert len(missing) == 2
assert "bad (Bad param)" in missing
assert "also_bad (Also bad)" in missing
assert "good" not in str(missing)
def test_refvalue_zero_not_missing(self):
"""Test that RefValue(0.0) is not considered missing."""
class TestObj:
zero = RefValue(value=0.0)
false_val = RefValue(value=False)
params = {"zero": "Zero", "false_val": "False"}
missing = check_missing_params(params, TestObj(), "test", "test")
assert len(missing) == 0
# Optional: Integration test
def test_full_validation_workflow():
"""Test complete validation workflow from YAML to annotated output."""
yaml_content = """
name: Test Config
sites:
- site_id: site1
properties:
land_cover:
paved:
sfr: {value: 0.5}
bldgs:
sfr: {value: 0.3}
grass:
sfr: {value: 0.2}
"""
with tempfile.NamedTemporaryFile(mode="w", suffix=".yml", delete=False) as f:
f.write(yaml_content)
yaml_path = Path(f.name)
try:
# Load config (triggers validation)
config = SUEWSConfig.from_yaml(yaml_path)
# Generate annotated YAML
annotated = config.generate_annotated_yaml(yaml_path)
# Verify it was created (Windows compatibility check)
if annotated is not None:
annotated = Path(annotated) # Convert string to Path
assert annotated.exists()
assert "annotated" in str(annotated)
# Clean up
annotated.unlink()
else:
# If annotation generation failed, we can still verify validation occurred
# by checking that the config was loaded successfully
assert config.name == "Test Config"
finally:
yaml_path.unlink()
def test_phase_b_storageheatmethod_ohmincqf_validation():
"""Test StorageHeatMethod-OhmIncQf validation in Phase B."""
from supy.data_model.validation.pipeline.phase_b import (