-
Notifications
You must be signed in to change notification settings - Fork 38
/
test_recipe.py
3186 lines (2802 loc) · 98.4 KB
/
test_recipe.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import re
from collections import defaultdict
from pathlib import Path
from pprint import pformat
from textwrap import dedent
from unittest.mock import create_autospec
import iris
import pytest
import yaml
from nested_lookup import get_occurrence_of_value
from PIL import Image
import esmvalcore
import esmvalcore._task
from esmvalcore._recipe.recipe import (
_get_input_datasets,
_representative_datasets,
read_recipe_file,
)
from esmvalcore._task import DiagnosticTask
from esmvalcore.config import Session
from esmvalcore.config._config import TASKSEP
from esmvalcore.config._diagnostics import TAGS
from esmvalcore.dataset import Dataset
from esmvalcore.exceptions import RecipeError
from esmvalcore.local import _get_output_file
from esmvalcore.preprocessor import DEFAULT_ORDER, PreprocessingTask
from tests.integration.test_provenance import check_provenance
TAGS_FOR_TESTING = {
'authors': {
'andela_bouwe': {
'name': 'Bouwe, Andela',
},
},
'projects': {
'c3s-magic': 'C3S MAGIC project',
},
'themes': {
'phys': 'physics',
},
'realms': {
'atmos': 'atmosphere',
},
'statistics': {
'mean': 'mean',
'var': 'variability',
},
'domains': {
'et': 'extra tropics',
'trop': 'tropics',
},
'plot_types': {
'zonal': 'zonal',
},
}
MANDATORY_DATASET_KEYS = (
'dataset',
'diagnostic',
'frequency',
'institute',
'long_name',
'mip',
'modeling_realm',
'preprocessor',
'project',
'short_name',
'standard_name',
'timerange',
'units',
)
MANDATORY_SCRIPT_SETTINGS_KEYS = (
'log_level',
'script',
'plot_dir',
'run_dir',
'work_dir',
)
DEFAULT_PREPROCESSOR_STEPS = (
'remove_supplementary_variables',
'save',
)
INITIALIZATION_ERROR_MSG = 'Could not create all tasks'
def create_test_file(filename, tracking_id=None):
dirname = os.path.dirname(filename)
if not os.path.exists(dirname):
os.makedirs(dirname)
attributes = {}
if tracking_id is not None:
attributes['tracking_id'] = tracking_id
cube = iris.cube.Cube([], attributes=attributes)
iris.save(cube, filename)
def _get_default_settings_for_chl(save_filename):
"""Get default preprocessor settings for chl."""
defaults = {
'remove_supplementary_variables': {},
'save': {
'compress': False,
'filename': save_filename,
}
}
return defaults
@pytest.fixture
def patched_tas_derivation(monkeypatch):
def get_required(short_name, _):
if short_name != 'tas':
assert False
required = [
{
'short_name': 'pr'
},
{
'short_name': 'areacella',
'mip': 'fx',
'optional': True
},
]
return required
monkeypatch.setattr(
esmvalcore._recipe.to_datasets,
'get_required',
get_required,
)
DEFAULT_DOCUMENTATION = dedent("""
documentation:
title: Test recipe
description: This is a test recipe.
authors:
- andela_bouwe
references:
- contact_authors
- acknow_project
projects:
- c3s-magic
""")
def get_recipe(tempdir: Path, content: str, session: Session):
"""Save and load recipe content."""
recipe_file = tempdir / 'recipe_test.yml'
# Add mandatory documentation section
content = str(DEFAULT_DOCUMENTATION + content)
recipe_file.write_text(content)
recipe = read_recipe_file(recipe_file, session)
return recipe
def test_recipe_missing_scripts(tmp_path, session):
content = dedent("""
datasets:
- dataset: bcc-csm1-1
diagnostics:
diagnostic_name:
variables:
ta:
project: CMIP5
mip: Amon
exp: historical
ensemble: r1i1p1
timerange: 1999/2002
""")
exc_message = ("Missing scripts section in diagnostic 'diagnostic_name'.")
with pytest.raises(RecipeError) as exc:
get_recipe(tmp_path, content, session)
assert str(exc.value) == exc_message
def test_recipe_duplicate_var_script_name(tmp_path, session):
content = dedent("""
datasets:
- dataset: bcc-csm1-1
diagnostics:
diagnostic_name:
variables:
ta:
project: CMIP5
mip: Amon
exp: historical
ensemble: r1i1p1
start_year: 1999
end_year: 2002
scripts:
ta:
script: tmp_path / 'diagnostic.py'
""")
exc_message = ("Invalid script name 'ta' encountered in diagnostic "
"'diagnostic_name': scripts cannot have the same "
"name as variables.")
with pytest.raises(RecipeError) as exc:
get_recipe(tmp_path, content, session)
assert str(exc.value) == exc_message
def test_recipe_no_script(tmp_path, session):
content = dedent("""
datasets:
- dataset: bcc-csm1-1
diagnostics:
diagnostic_name:
variables:
ta:
project: CMIP5
mip: Amon
exp: historical
ensemble: r1i1p1
start_year: 1999
end_year: 2002
scripts:
script_name:
argument: 1
""")
exc_message = ("No script defined for script 'script_name' in "
"diagnostic 'diagnostic_name'.")
with pytest.raises(RecipeError) as exc:
get_recipe(tmp_path, content, session)
assert str(exc.value) == exc_message
def test_recipe_no_datasets(tmp_path, session):
content = dedent("""
diagnostics:
diagnostic_name:
variables:
ta:
project: CMIP5
mip: Amon
exp: historical
ensemble: r1i1p1
start_year: 1999
end_year: 2002
scripts: null
""")
exc_message = ("You have not specified any dataset "
"or additional_dataset groups for variable "
"'ta' in diagnostic 'diagnostic_name'.")
with pytest.raises(RecipeError) as exc:
get_recipe(tmp_path, content, session)
assert str(exc.value) == exc_message
def test_recipe_duplicated_datasets(tmp_path, session):
content = dedent("""
datasets:
- dataset: bcc-csm1-1
- dataset: bcc-csm1-1
diagnostics:
diagnostic_name:
variables:
ta:
project: CMIP5
mip: Amon
exp: historical
ensemble: r1i1p1
timerange: 1999/2002
scripts: null
""")
exc_message = ("Duplicate dataset\n{'dataset': 'bcc-csm1-1'}\n"
"for variable 'ta' in diagnostic 'diagnostic_name'.")
with pytest.raises(RecipeError) as exc:
get_recipe(tmp_path, content, session)
assert str(exc.value) == exc_message
def test_recipe_var_missing_args(tmp_path, session):
content = dedent("""
datasets:
- dataset: bcc-csm1-1
diagnostics:
diagnostic_name:
variables:
ta:
project: CMIP5
exp: historical
ensemble: r1i1p1
timerange: 1999/2002
scripts: null
""")
exc_message = ("Missing keys {'mip'} in\n{'dataset': 'bcc-csm1-1',"
"\n 'ensemble': 'r1i1p1',\n 'exp': 'historical',\n"
" 'project': 'CMIP5',\n 'short_name': 'ta',\n "
"'timerange': '1999/2002'}\nfor variable 'ta' "
"in diagnostic 'diagnostic_name'.")
with pytest.raises(RecipeError) as exc:
get_recipe(tmp_path, content, session)
assert str(exc.value) == exc_message
@pytest.mark.parametrize('skip_nonexistent', [True, False])
def test_recipe_no_data(tmp_path, session, skip_nonexistent):
content = dedent("""
datasets:
- dataset: GFDL-ESM2G
diagnostics:
diagnostic_name:
variables:
ta:
project: CMIP5
mip: Amon
exp: historical
ensemble: r1i1p1
start_year: 1999
end_year: 2002
scripts: null
""")
session['skip_nonexistent'] = skip_nonexistent
with pytest.raises(RecipeError) as error:
get_recipe(tmp_path, content, session)
if skip_nonexistent:
msg = ("Did not find any input data for task diagnostic_name/ta")
else:
msg = ("Missing data for preprocessor diagnostic_name/ta:\n"
"- Missing data for Dataset: .*")
assert re.match(msg, error.value.failed_tasks[0].message)
@pytest.mark.parametrize('script_file', ['diagnostic.py', 'diagnostic.ncl'])
def test_simple_recipe(
tmp_path,
patched_datafinder,
session,
script_file,
monkeypatch,
):
def ncl_version():
return '6.5'
monkeypatch.setattr(esmvalcore._recipe.check, 'ncl_version', ncl_version)
def which(interpreter):
return interpreter
monkeypatch.setattr(esmvalcore._task, 'which', which)
script = tmp_path / script_file
script.write_text('')
content = dedent("""
datasets:
- dataset: bcc-csm1-1
preprocessors:
preprocessor_name:
extract_levels:
levels: 85000
scheme: nearest
diagnostics:
diagnostic_name:
additional_datasets:
- dataset: GFDL-ESM2G
variables:
ta:
preprocessor: preprocessor_name
project: CMIP5
mip: Amon
exp: historical
ensemble: r1i1p1
timerange: 1999/2002
additional_datasets:
- dataset: MPI-ESM-LR
scripts:
script_name:
script: {}
custom_setting: 1
""".format(script))
recipe = get_recipe(tmp_path, content, session)
# Check that datasets have been read and updated
assert len(recipe.datasets) == 3
for dataset in recipe.datasets:
for key in MANDATORY_DATASET_KEYS:
assert key in dataset.facets and dataset.facets[key]
# Check that the correct tasks have been created
datasets = recipe.datasets
tasks = {t for task in recipe.tasks for t in task.flatten()}
preproc_tasks = {t for t in tasks if isinstance(t, PreprocessingTask)}
diagnostic_tasks = {t for t in tasks if isinstance(t, DiagnosticTask)}
assert len(preproc_tasks) == 1
for task in preproc_tasks:
print("Task", task.name)
assert task.order == list(DEFAULT_ORDER)
for product in task.products:
dataset = [
d for d in datasets if _get_output_file(
d.facets, session.preproc_dir) == product.filename
][0]
assert product.datasets == [dataset]
attributes = dict(dataset.facets)
attributes['filename'] = product.filename
attributes['start_year'] = 1999
attributes['end_year'] = 2002
assert product.attributes == attributes
for step in DEFAULT_PREPROCESSOR_STEPS:
assert step in product.settings
assert len(dataset.files) == 2
assert len(diagnostic_tasks) == 1
for task in diagnostic_tasks:
print("Task", task.name)
assert task.ancestors == list(preproc_tasks)
assert task.script == str(script)
for key in MANDATORY_SCRIPT_SETTINGS_KEYS:
assert key in task.settings and task.settings[key]
assert task.settings['custom_setting'] == 1
# Check that NCL interface is enabled for NCL scripts.
write_ncl_interface = script.suffix == '.ncl'
assert datasets[0].session['write_ncl_interface'] == write_ncl_interface
def test_write_filled_recipe(tmp_path, patched_datafinder, session):
script = tmp_path / 'diagnostic.py'
script.write_text('')
content = dedent("""
datasets:
- dataset: bcc-csm1-1
preprocessors:
preprocessor_name:
extract_levels:
levels: 85000
scheme: nearest
diagnostics:
diagnostic_name:
additional_datasets:
- dataset: GFDL-ESM2G
variables:
ta:
preprocessor: preprocessor_name
project: CMIP5
mip: Amon
exp: historical
ensemble: r1i1p1
timerange: '*'
additional_datasets:
- dataset: MPI-ESM-LR
timerange: '*/P2Y'
scripts:
script_name:
script: {}
custom_setting: 1
""".format(script))
recipe = get_recipe(tmp_path, content, session)
session.run_dir.mkdir(parents=True)
esmvalcore._recipe.recipe.Recipe.write_filled_recipe(recipe)
recipe_file = session.run_dir / 'recipe_test_filled.yml'
assert recipe_file.is_file()
updated_recipe_object = read_recipe_file(recipe_file, session)
updated_recipe = updated_recipe_object._raw_recipe
print(pformat(updated_recipe))
assert get_occurrence_of_value(updated_recipe, value='*') == 0
assert get_occurrence_of_value(updated_recipe, value='1990/2019') == 2
assert get_occurrence_of_value(updated_recipe, value='1990/P2Y') == 1
assert len(updated_recipe_object.datasets) == 3
def test_fx_preproc_error(tmp_path, patched_datafinder, session):
script = tmp_path / 'diagnostic.py'
script.write_text('')
content = dedent("""
datasets:
- dataset: bcc-csm1-1
preprocessors:
preprocessor_name:
extract_season:
season: MAM
diagnostics:
diagnostic_name:
variables:
sftlf:
preprocessor: preprocessor_name
project: CMIP5
mip: fx
exp: historical
ensemble: r0i0p0
start_year: 1999
end_year: 2002
additional_datasets:
- dataset: MPI-ESM-LR
scripts: null
""")
msg = ("Time coordinate preprocessor step(s) ['extract_season'] not "
"permitted on fx vars, please remove them from recipe")
with pytest.raises(Exception) as rec_err_exp:
get_recipe(tmp_path, content, session)
assert str(rec_err_exp.value) == INITIALIZATION_ERROR_MSG
assert str(rec_err_exp.value.failed_tasks[0].message) == msg
def test_default_preprocessor(tmp_path, patched_datafinder, session):
content = dedent("""
diagnostics:
diagnostic_name:
variables:
chl:
project: CMIP5
mip: Oyr
exp: historical
start_year: 2000
end_year: 2005
ensemble: r1i1p1
additional_datasets:
- {dataset: CanESM2}
scripts: null
""")
recipe = get_recipe(tmp_path, content, session)
assert len(recipe.tasks) == 1
task = recipe.tasks.pop()
assert len(task.products) == 1
product = task.products.pop()
preproc_dir = os.path.dirname(product.filename)
assert preproc_dir.startswith(str(tmp_path))
defaults = _get_default_settings_for_chl(product.filename)
assert product.settings == defaults
def test_default_preprocessor_custom_order(tmp_path, patched_datafinder,
session):
"""Test if default settings are used when ``custom_order`` is ``True``."""
content = dedent("""
preprocessors:
default_custom_order:
custom_order: true
diagnostics:
diagnostic_name:
variables:
chl:
preprocessor: default_custom_order
project: CMIP5
mip: Oyr
exp: historical
start_year: 2000
end_year: 2005
ensemble: r1i1p1
additional_datasets:
- {dataset: CanESM2}
scripts: null
""")
recipe = get_recipe(tmp_path, content, session)
assert len(recipe.tasks) == 1
task = recipe.tasks.pop()
assert len(task.products) == 1
product = task.products.pop()
preproc_dir = os.path.dirname(product.filename)
assert preproc_dir.startswith(str(tmp_path))
defaults = _get_default_settings_for_chl(product.filename)
assert product.settings == defaults
def test_invalid_preprocessor(tmp_path, patched_datafinder, session):
"""Test the error message when the named prepreprocesor is not defined."""
content = dedent("""
diagnostics:
diagnostic_name:
variables:
chl:
preprocessor: not_defined
project: CMIP5
mip: Oyr
exp: historical
start_year: 2000
end_year: 2005
ensemble: r1i1p1
additional_datasets:
- {dataset: CanESM2}
scripts: null
""")
with pytest.raises(RecipeError) as error:
get_recipe(tmp_path, content, session)
msg = "Unknown preprocessor 'not_defined' in .*"
assert re.match(msg, error.value.failed_tasks[0].message)
def test_disable_preprocessor_function(tmp_path, patched_datafinder, session):
"""Test if default settings are used when ``custom_order`` is ``True``."""
content = dedent("""
datasets:
- dataset: HadGEM3-GC31-LL
ensemble: r1i1p1f1
exp: historical
grid: gn
preprocessors:
keep_supplementaries:
remove_supplementary_variables: False
diagnostics:
diagnostic_name:
variables:
tas:
preprocessor: keep_supplementaries
project: CMIP6
mip: Amon
timerange: 2000/2005
supplementaries:
- short_name: areacella
mip: fx
scripts: null
""")
recipe = get_recipe(tmp_path, content, session)
assert len(recipe.tasks) == 1
task = recipe.tasks.pop()
assert len(task.products) == 1
product = task.products.pop()
assert 'remove_supplementary_variables' not in product.settings
def test_default_fx_preprocessor(tmp_path, patched_datafinder, session):
content = dedent("""
diagnostics:
diagnostic_name:
variables:
sftlf:
project: CMIP5
mip: fx
exp: historical
ensemble: r0i0p0
additional_datasets:
- {dataset: CanESM2}
scripts: null
""")
recipe = get_recipe(tmp_path, content, session)
assert len(recipe.tasks) == 1
task = recipe.tasks.pop()
assert len(task.products) == 1
product = task.products.pop()
preproc_dir = os.path.dirname(product.filename)
assert preproc_dir.startswith(str(tmp_path))
defaults = {
'remove_supplementary_variables': {},
'save': {
'compress': False,
'filename': product.filename,
}
}
assert product.settings == defaults
def test_empty_variable(tmp_path, patched_datafinder, session):
"""Test that it is possible to specify all information in the dataset."""
content = dedent("""
diagnostics:
diagnostic_name:
additional_datasets:
- dataset: CanESM2
project: CMIP5
mip: Amon
exp: historical
start_year: 2000
end_year: 2005
ensemble: r1i1p1
variables:
pr:
scripts: null
""")
recipe = get_recipe(tmp_path, content, session)
assert len(recipe.tasks) == 1
task = recipe.tasks.pop()
assert len(task.products) == 1
product = task.products.pop()
assert product.attributes['short_name'] == 'pr'
assert product.attributes['dataset'] == 'CanESM2'
TEST_ISO_TIMERANGE = [
('*', '1990-2019'),
('1990/1992', '1990-1992'),
('19900101/19920101', '19900101-19920101'),
('19900101T12H00M00S/19920101T12H00M00',
'19900101T12H00M00S-19920101T12H00M00'),
('1990/*', '1990-2019'),
('*/1992', '1990-1992'),
('1990/P2Y', '1990-P2Y'),
('19900101/P2Y2M1D', '19900101-P2Y2M1D'),
('19900101TH00M00S/P2Y2M1DT12H00M00S',
'19900101TH00M00S-P2Y2M1DT12H00M00S'),
('P2Y/1992', 'P2Y-1992'),
('P1Y2M1D/19920101', 'P1Y2M1D-19920101'),
('P1Y2M1D/19920101T12H00M00S', 'P1Y2M1D-19920101T12H00M00S'),
('P2Y/*', 'P2Y-2019'),
('P2Y2M1D/*', 'P2Y2M1D-2019'),
('P2Y21DT12H00M00S/*', 'P2Y21DT12H00M00S-2019'),
('*/P2Y', '1990-P2Y'),
('*/P2Y2M1D', '1990-P2Y2M1D'),
('*/P2Y21DT12H00M00S', '1990-P2Y21DT12H00M00S'),
]
@pytest.mark.parametrize('input_time,output_time', TEST_ISO_TIMERANGE)
def test_recipe_iso_timerange(tmp_path, patched_datafinder, session,
input_time, output_time):
"""Test recipe with timerange tag."""
content = dedent(f"""
diagnostics:
test:
additional_datasets:
- dataset: HadGEM3-GC31-LL
project: CMIP6
exp: historical
ensemble: r2i1p1f1
grid: gn
variables:
pr:
mip: 3hr
timerange: '{input_time}'
areacella:
mip: fx
scripts: null
""")
recipe = get_recipe(tmp_path, content, session)
assert len(recipe.tasks) == 2
pr_task = [t for t in recipe.tasks if t.name.endswith('pr')][0]
assert len(pr_task.products) == 1
pr_product = pr_task.products.pop()
filename = ('CMIP6_HadGEM3-GC31-LL_3hr_historical_r2i1p1f1_'
f'pr_gn_{output_time}.nc')
assert pr_product.filename.name == filename
areacella_task = [t for t in recipe.tasks
if t.name.endswith('areacella')][0]
assert len(areacella_task.products) == 1
areacella_product = areacella_task.products.pop()
filename = 'CMIP6_HadGEM3-GC31-LL_fx_historical_r2i1p1f1_areacella_gn.nc'
assert areacella_product.filename.name == filename
@pytest.mark.parametrize('input_time,output_time', TEST_ISO_TIMERANGE)
def test_recipe_iso_timerange_as_dataset(tmp_path, patched_datafinder, session,
input_time, output_time):
"""Test recipe with timerange tag in the datasets section."""
content = dedent(f"""
datasets:
- dataset: HadGEM3-GC31-LL
project: CMIP6
exp: historical
ensemble: r2i1p1f1
grid: gn
timerange: '{input_time}'
diagnostics:
test:
variables:
pr:
mip: 3hr
supplementary_variables:
- short_name: areacella
mip: fx
scripts: null
""")
recipe = get_recipe(tmp_path, content, session)
assert len(recipe.tasks) == 1
task = recipe.tasks.pop()
assert len(task.products) == 1
product = task.products.pop()
filename = ('CMIP6_HadGEM3-GC31-LL_3hr_historical_r2i1p1f1_'
f'pr_gn_{output_time}.nc')
assert product.filename.name == filename
assert len(product.datasets) == 1
dataset = product.datasets[0]
assert len(dataset.supplementaries) == 1
supplementary_ds = dataset.supplementaries[0]
assert supplementary_ds.facets['short_name'] == 'areacella'
assert 'timerange' not in supplementary_ds.facets
def test_reference_dataset(tmp_path, patched_datafinder, session, monkeypatch):
levels = [100]
get_reference_levels = create_autospec(
esmvalcore._recipe.recipe.get_reference_levels, return_value=levels)
monkeypatch.setattr(esmvalcore._recipe.recipe, 'get_reference_levels',
get_reference_levels)
content = dedent("""
preprocessors:
test_from_reference:
regrid:
target_grid: reference_dataset
scheme: linear
extract_levels:
levels: reference_dataset
scheme: linear
test_from_cmor_table:
extract_levels:
levels:
cmor_table: CMIP6
coordinate: alt16
scheme: nearest
diagnostics:
diagnostic_name:
variables:
ta: &var
preprocessor: test_from_reference
project: CMIP5
mip: Amon
exp: historical
start_year: 2000
end_year: 2005
ensemble: r1i1p1
additional_datasets:
- dataset: GFDL-CM3
- dataset: MPI-ESM-LR
reference_dataset: MPI-ESM-LR
ch4:
<<: *var
preprocessor: test_from_cmor_table
additional_datasets:
- dataset: GFDL-CM3
scripts: null
""")
recipe = get_recipe(tmp_path, content, session)
assert len(recipe.tasks) == 2
# Check that the reference dataset has been used
task = next(t for t in recipe.tasks
if t.name == 'diagnostic_name' + TASKSEP + 'ta')
assert len(task.products) == 2
product = next(p for p in task.products
if p.attributes['dataset'] == 'GFDL-CM3')
reference = next(p for p in task.products
if p.attributes['dataset'] == 'MPI-ESM-LR')
assert product.settings['regrid']['target_grid'] == reference.datasets[0]
assert product.settings['extract_levels']['levels'] == levels
get_reference_levels.assert_called_once_with(reference.datasets[0])
assert 'regrid' not in reference.settings
assert 'extract_levels' not in reference.settings
# Check that levels have been read from CMOR table
task = next(t for t in recipe.tasks
if t.name == 'diagnostic_name' + TASKSEP + 'ch4')
assert len(task.products) == 1
product = next(iter(task.products))
assert product.settings['extract_levels']['levels'] == [
0,
250,
750,
1250,
1750,
2250,
2750,
3500,
4500,
6000,
8000,
10000,
12000,
14500,
16000,
18000,
]
def test_reference_dataset_undefined(tmp_path, monkeypatch, session):
content = dedent("""
preprocessors:
test_from_reference:
extract_levels:
levels: reference_dataset
scheme: linear
diagnostics:
diagnostic_name:
variables:
ta: &var
preprocessor: test_from_reference
project: CMIP5
mip: Amon
exp: historical
start_year: 2000
end_year: 2005
ensemble: r1i1p1
additional_datasets:
- dataset: GFDL-CM3
- dataset: MPI-ESM-LR
scripts: null
""")
with pytest.raises(RecipeError) as error:
get_recipe(tmp_path, content, session)
msg = ("Preprocessor 'test_from_reference' uses 'reference_dataset', but "
"'reference_dataset' is not defined")
assert msg in error.value.failed_tasks[0].message
def test_custom_preproc_order(tmp_path, patched_datafinder, session):
content = dedent("""
preprocessors:
default: &default
multi_model_statistics:
span: overlap
statistics: [mean ]
area_statistics:
operator: mean
custom:
custom_order: true
<<: *default
empty_custom:
custom_order: true
with_extract_time:
custom_order: true
extract_time:
start_year: 2001
start_month: 3
start_day: 14
end_year: 2002
end_month: 6
end_day: 28
diagnostics:
diagnostic_name:
variables:
chl_default: &chl
short_name: chl
preprocessor: default
project: CMIP5
mip: Oyr
exp: historical
start_year: 2000
end_year: 2005
ensemble: r1i1p1
additional_datasets:
- {dataset: CanESM2}
chl_custom:
<<: *chl
preprocessor: custom
chl_empty_custom:
<<: *chl
preprocessor: empty_custom
chl_with_extract_time:
<<: *chl
preprocessor: with_extract_time
scripts: null
""")
recipe = get_recipe(tmp_path, content, session)
assert len(recipe.tasks) == 4
for task in recipe.tasks: