-
Notifications
You must be signed in to change notification settings - Fork 209
/
case.py
2550 lines (2237 loc) · 102 KB
/
case.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
# -*- coding: utf-8 -*-
"""
Wrapper around all env XML for a case.
All interaction with and between the module files in XML/ takes place
through the Case module.
"""
from copy import deepcopy
import sys
import glob, os, shutil, math, time, hashlib, socket, getpass
from CIME.XML.standard_module_setup import *
# pylint: disable=import-error,redefined-builtin
from CIME import utils
from CIME.config import Config
from CIME.status import append_status
from CIME.utils import expect, get_cime_root
from CIME.utils import convert_to_type, get_model, set_model
from CIME.utils import get_project, get_charge_account, check_name
from CIME.utils import get_current_commit, safe_copy, get_cime_default_driver
from CIME.gitinterface import GitInterface
from CIME.locked_files import LOCKED_DIR, lock_file
from CIME.XML.machines import Machines
from CIME.XML.pes import Pes
from CIME.XML.files import Files
from CIME.XML.testlist import Testlist
from CIME.XML.component import Component
from CIME.XML.compsets import Compsets
from CIME.XML.grids import Grids
from CIME.XML.batch import Batch
from CIME.XML.workflow import Workflow
from CIME.XML.pio import PIO
from CIME.XML.archive import Archive
from CIME.XML.env_test import EnvTest
from CIME.XML.env_mach_specific import EnvMachSpecific
from CIME.XML.env_case import EnvCase
from CIME.XML.env_mach_pes import EnvMachPes
from CIME.XML.env_build import EnvBuild
from CIME.XML.env_run import EnvRun
from CIME.XML.env_archive import EnvArchive
from CIME.XML.env_batch import EnvBatch
from CIME.XML.env_workflow import EnvWorkflow
from CIME.XML.generic_xml import GenericXML
from CIME.user_mod_support import apply_user_mods
from CIME.aprun import get_aprun_cmd_for_case
logger = logging.getLogger(__name__)
config = Config.instance()
class Case(object):
"""
https://github.com/ESMCI/cime/wiki/Developers-Introduction
The Case class is the heart of the CIME Case Control system. All
interactions with a Case take part through this class. All of the
variables used to create and manipulate a case are defined in xml
files and for every xml file there is a python class to interact
with that file.
XML files which are part of the CIME distribution and are meant to
be readonly with respect to a case are typically named
config_something.xml and the corresponding python Class is
Something and can be found in file CIME.XML.something.py. I'll
refer to these as the CIME config classes.
XML files which are part of a case and thus are read/write to a
case are typically named env_whatever.xml and the cooresponding
python modules are CIME.XML.env_whatever.py and classes are
EnvWhatever. I'll refer to these as the Case env classes.
The Case Class includes an array of the Case env classes, in the
configure function and it's supporting functions defined below
the case object creates and manipulates the Case env classes
by reading and interpreting the CIME config classes.
This class extends across multiple files, class members external to this file
are listed in the following imports
"""
from CIME.case.case_setup import case_setup, _create_case_repo
from CIME.case.case_clone import create_clone, _copy_user_modified_to_clone
from CIME.case.case_test import case_test
from CIME.case.case_submit import check_DA_settings, check_case, submit
from CIME.case.case_st_archive import (
case_st_archive,
restore_from_archive,
archive_last_restarts,
test_st_archive,
test_env_archive,
)
from CIME.case.case_run import case_run
from CIME.case.case_cmpgen_namelists import case_cmpgen_namelists
from CIME.case.preview_namelists import create_dirs, create_namelists
from CIME.case.check_input_data import (
check_all_input_data,
stage_refcase,
check_input_data,
)
def __init__(self, case_root=None, read_only=True, record=False, non_local=False):
if case_root is None:
case_root = os.getcwd()
expect(
not os.path.isdir(case_root)
or os.path.isfile(os.path.join(case_root, "env_case.xml")),
"Directory {} does not appear to be a valid case directory".format(
case_root
),
)
self._caseroot = case_root
logger.debug("Initializing Case.")
self._read_only_mode = True
self._force_read_only = read_only
self._primary_component = None
self._env_entryid_files = []
self._env_generic_files = []
self._files = []
self._comp_interface = None
self.gpu_enabled = False
self._non_local = non_local
self.read_xml()
srcroot = self.get_value("SRCROOT")
# Propagate `srcroot` to `GenericXML` to resolve $SRCROOT
if srcroot is not None:
utils.GLOBAL["SRCROOT"] = srcroot
# srcroot may not be known yet, in the instance of creating
# a new case
customize_path = os.path.join(srcroot, "cime_config", "customize")
config.load(customize_path)
if record:
self.record_cmd()
cimeroot = get_cime_root()
# Insert tools path to support external code trying to import
# standard_script_setup
tools_path = os.path.join(cimeroot, "CIME", "Tools")
if tools_path not in sys.path:
sys.path.insert(0, tools_path)
# Hold arbitary values. In create_newcase we may set values
# for xml files that haven't been created yet. We need a place
# to store them until we are ready to create the file. At file
# creation we get the values for those fields from this lookup
# table and then remove the entry.
self.lookups = {}
self.set_lookup_value("CIMEROOT", cimeroot)
self._cime_model = get_model()
self.set_lookup_value("MODEL", self._cime_model)
self._compsetname = None
self._gridname = None
self._pesfile = None
self._gridfile = None
self._components = []
self._component_classes = []
self._component_description = {}
self._is_env_loaded = False
self._loaded_envs = None
self._gitinterface = None
# these are user_mods as defined in the compset
# Command Line user_mods are handled seperately
# Derived attributes
self.thread_count = None
self.total_tasks = None
self.tasks_per_node = None
self.ngpus_per_node = 0
self.num_nodes = None
self.spare_nodes = None
self.tasks_per_numa = None
self.cores_per_task = None
self.srun_binding = None
self.async_io = False
self.iotasks = 0
# check if case has been configured and if so initialize derived
if self.get_value("CASEROOT") is not None:
if not self._non_local:
mach = self.get_value("MACH")
extra_machdir = self.get_value("EXTRA_MACHDIR")
if extra_machdir:
machobj = Machines(machine=mach, extra_machines_dir=extra_machdir)
else:
machobj = Machines(machine=mach)
# This check should only be done on systems with a common filesystem but separate login nodes (ncar)
if "NCAR_HOST" in os.environ:
probed_machine = machobj.probe_machine_name()
if probed_machine:
expect(
mach == probed_machine,
f"Current machine {probed_machine} does not match case machine {mach}.",
)
if os.path.exists(os.path.join(self.get_value("CASEROOT"), ".git")):
self._gitinterface = GitInterface(
self.get_value("CASEROOT"), logger
)
self.initialize_derived_attributes()
def get_baseline_dir(self):
baseline_root = self.get_value("BASELINE_ROOT")
baseline_name = self.get_value("BASECMP_CASE")
return os.path.join(baseline_root, baseline_name)
def check_if_comp_var(self, vid):
for env_file in self._env_entryid_files:
new_vid, new_comp, iscompvar = env_file.check_if_comp_var(vid)
if iscompvar:
return new_vid, new_comp, iscompvar
return vid, None, False
def initialize_derived_attributes(self):
"""
These are derived variables which can be used in the config_* files
for variable substitution using the {{ var }} syntax
"""
set_model(self.get_value("MODEL"))
env_mach_pes = self.get_env("mach_pes")
env_mach_spec = self.get_env("mach_specific")
comp_classes = self.get_values("COMP_CLASSES")
max_mpitasks_per_node = self.get_value("MAX_MPITASKS_PER_NODE")
self.async_io = {}
asyncio = False
for comp in comp_classes:
self.async_io[comp] = self.get_value("PIO_ASYNC_INTERFACE", subgroup=comp)
if self.async_io[comp]:
asyncio = True
self.iotasks = (
self.get_value("PIO_ASYNCIO_NTASKS")
if self.get_value("PIO_ASYNCIO_NTASKS")
else 0
)
self.thread_count = env_mach_pes.get_max_thread_count(comp_classes)
mpi_attribs = {
"compiler": self.get_value("COMPILER"),
"mpilib": self.get_value("MPILIB"),
"threaded": self.get_build_threaded(),
}
job = self.get_primary_job()
executable = env_mach_spec.get_mpirun(self, mpi_attribs, job, exe_only=True)[0]
if executable is not None and "aprun" in executable:
(
_,
self.num_nodes,
self.total_tasks,
self.tasks_per_node,
self.thread_count,
) = get_aprun_cmd_for_case(self, "e3sm.exe")
self.spare_nodes = env_mach_pes.get_spare_nodes(self.num_nodes)
self.num_nodes += self.spare_nodes
else:
self.total_tasks = env_mach_pes.get_total_tasks(comp_classes, asyncio)
self.tasks_per_node = env_mach_pes.get_tasks_per_node(
self.total_tasks, self.thread_count
)
self.num_nodes, self.spare_nodes = env_mach_pes.get_total_nodes(
self.total_tasks, self.thread_count
)
self.num_nodes += self.spare_nodes
logger.debug(
"total_tasks {} thread_count {}".format(self.total_tasks, self.thread_count)
)
max_gpus_per_node = self.get_value("MAX_GPUS_PER_NODE")
if max_gpus_per_node:
self.ngpus_per_node = self.get_value("NGPUS_PER_NODE")
# update the maximum MPI tasks for a GPU node (could differ from a pure-CPU node)
if self.ngpus_per_node > 0:
max_mpitasks_per_node = self.get_value("MAX_CPUTASKS_PER_GPU_NODE")
self.tasks_per_numa = int(math.ceil(self.tasks_per_node / 2.0))
smt_factor = max(
1, int(self.get_value("MAX_TASKS_PER_NODE") / max_mpitasks_per_node)
)
threads_per_node = self.tasks_per_node * self.thread_count
threads_per_core = (
1 if (threads_per_node <= max_mpitasks_per_node) else smt_factor
)
self.cores_per_task = self.thread_count / threads_per_core
os.environ["OMP_NUM_THREADS"] = str(self.thread_count)
self.srun_binding = math.floor(
smt_factor * max_mpitasks_per_node / self.tasks_per_node
)
self.srun_binding = max(1, int(self.srun_binding))
# Define __enter__ and __exit__ so that we can use this as a context manager
# and force a flush on exit.
def __enter__(self):
if not self._force_read_only:
self._read_only_mode = False
return self
def __exit__(self, *_):
self.flush()
self._read_only_mode = True
return False
def read_xml(self):
for env_file in self._files:
expect(
not env_file.needsrewrite,
"Potential loss of unflushed changes in {}".format(env_file.filename),
)
self._env_entryid_files = []
self._env_entryid_files.append(
EnvCase(self._caseroot, components=None, read_only=self._force_read_only)
)
components = self._env_entryid_files[0].get_values("COMP_CLASSES")
self._env_entryid_files.append(
EnvRun(
self._caseroot, components=components, read_only=self._force_read_only
)
)
self._env_entryid_files.append(
EnvBuild(
self._caseroot, components=components, read_only=self._force_read_only
)
)
self._comp_interface = self._env_entryid_files[-1].get_value("COMP_INTERFACE")
self._env_entryid_files.append(
EnvMachPes(
self._caseroot,
components=components,
read_only=self._force_read_only,
comp_interface=self._comp_interface,
)
)
self._env_entryid_files.append(
EnvBatch(self._caseroot, read_only=self._force_read_only)
)
self._env_entryid_files.append(
EnvWorkflow(self._caseroot, read_only=self._force_read_only)
)
if os.path.isfile(os.path.join(self._caseroot, "env_test.xml")):
self._env_entryid_files.append(
EnvTest(
self._caseroot,
components=components,
read_only=self._force_read_only,
)
)
self._env_generic_files = []
self._env_generic_files.append(
EnvMachSpecific(
self._caseroot,
read_only=self._force_read_only,
comp_interface=self._comp_interface,
)
)
self._env_generic_files.append(
EnvArchive(self._caseroot, read_only=self._force_read_only)
)
self._files = self._env_entryid_files + self._env_generic_files
def get_case_root(self):
"""Returns the root directory for this case."""
return self._caseroot
def get_env(self, short_name, allow_missing=False):
full_name = "env_{}.xml".format(short_name)
for env_file in self._files:
if os.path.basename(env_file.filename) == full_name:
return env_file
if allow_missing:
return None
expect(False, "Could not find object for {} in case".format(full_name))
def check_timestamps(self, short_name=None):
if short_name is not None:
env_file = self.get_env(short_name)
env_file.check_timestamp()
else:
for env_file in self._files:
env_file.check_timestamp()
def copy(self, newcasename, newcaseroot, newcimeroot=None, newsrcroot=None):
newcase = deepcopy(self)
for env_file in newcase._files: # pylint: disable=protected-access
basename = os.path.basename(env_file.filename)
newfile = os.path.join(newcaseroot, basename)
env_file.change_file(newfile, copy=True)
if newcimeroot is not None:
newcase.set_value("CIMEROOT", newcimeroot)
if newsrcroot is not None:
newcase.set_value("SRCROOT", newsrcroot)
newcase.set_value("CASE", newcasename)
newcase.set_value("CASEROOT", newcaseroot)
newcase.set_value("CONTINUE_RUN", "FALSE")
newcase.set_value("RESUBMIT", 0)
newcase.set_value("CASE_HASH", newcase.new_hash())
# Important, and subtle: Writability should NOT be copied because
# this allows the copy to be modified without needing a "with" statement
# which opens the door to tricky errors such as unflushed writes.
newcase._read_only_mode = True # pylint: disable=protected-access
return newcase
def flush(self, flushall=False):
if not os.path.isdir(self._caseroot):
# do not flush if caseroot wasnt created
return
for env_file in self._files:
env_file.write(force_write=flushall)
def get_values(self, item, attribute=None, resolved=True, subgroup=None):
for env_file in self._files:
# Wait and resolve in self rather than in env_file
results = env_file.get_values(
item, attribute, resolved=False, subgroup=subgroup
)
if len(results) > 0:
new_results = []
if resolved:
for result in results:
if isinstance(result, str):
result = self.get_resolved_value(result)
vtype = env_file.get_type_info(item)
if vtype is not None or vtype != "char":
result = convert_to_type(result, vtype, item)
new_results.append(result)
else:
new_results.append(result)
else:
new_results = results
return new_results
# Return empty result
return []
def get_value(self, item, attribute=None, resolved=True, subgroup=None):
if item == "GPU_ENABLED":
if not self.gpu_enabled:
if (
self.get_value("GPU_TYPE") != "none"
and self.get_value("NGPUS_PER_NODE") > 0
):
self.gpu_enabled = True
return "true" if self.gpu_enabled else "false"
result = None
for env_file in self._files:
# Wait and resolve in self rather than in env_file
result = env_file.get_value(
item, attribute, resolved=False, subgroup=subgroup
)
if result is not None:
if resolved and isinstance(result, str):
result = self.get_resolved_value(result, subgroup=subgroup)
vtype = env_file.get_type_info(item)
if vtype is not None and vtype != "char":
result = convert_to_type(result, vtype, item)
return result
# Return empty result
return result
def get_record_fields(self, variable, field):
"""get_record_fields gets individual requested field from an entry_id file
this routine is used only by xmlquery"""
# Empty result
result = []
for env_file in self._env_entryid_files:
# Wait and resolve in self rather than in env_file
logger.debug(
"(get_record_field) Searching in {}".format(env_file.__class__.__name__)
)
if field == "varid":
roots = env_file.scan_children("entry")
else:
roots = env_file.get_nodes_by_id(variable)
for root in roots:
if root is not None:
if field == "raw":
result.append(env_file.get_raw_record(root))
elif field == "desc":
result.append(env_file.get_description(root))
elif field == "varid":
result.append(env_file.get(root, "id"))
elif field == "group":
result.extend(env_file.get_groups(root))
elif field == "valid_values":
# pylint: disable=protected-access
vv = env_file._get_valid_values(root)
if vv:
result.extend(vv)
elif field == "file":
result.append(env_file.filename)
if not result:
for env_file in self._env_generic_files:
roots = env_file.scan_children(variable)
for root in roots:
if root is not None:
if field == "raw":
result.append(env_file.get_raw_record(root))
elif field == "group":
result.extend(env_file.get_groups(root))
elif field == "file":
result.append(env_file.filename)
return list(set(result))
def get_type_info(self, item):
result = None
for env_file in self._env_entryid_files:
result = env_file.get_type_info(item)
if result is not None:
return result
return result
def get_resolved_value(
self, item, recurse=0, allow_unresolved_envvars=False, subgroup=None
):
num_unresolved = item.count("$") if item else 0
recurse_limit = 10
if num_unresolved > 0 and recurse < recurse_limit:
for env_file in self._env_entryid_files:
item = env_file.get_resolved_value(
item,
allow_unresolved_envvars=allow_unresolved_envvars,
subgroup=subgroup,
)
if "$" not in item:
return item
else:
item = self.get_resolved_value(
item,
recurse=recurse + 1,
allow_unresolved_envvars=allow_unresolved_envvars,
subgroup=subgroup,
)
return item
def set_value(
self,
item,
value,
subgroup=None,
ignore_type=False,
allow_undefined=False,
return_file=False,
):
"""
If a file has been defined, and the variable is in the file,
then that value will be set in the file object and the resovled value
is returned unless return_file is True, in which case (resolved_value, filename)
is returned where filename is the name of the modified file.
"""
expect(
not self._read_only_mode,
"Cannot modify case, read_only. "
"Case must be opened with read_only=False and can only be modified within a context manager",
)
if item == "CASEROOT":
self._caseroot = value
result = None
for env_file in self._files:
result = env_file.set_value(item, value, subgroup, ignore_type)
if result is not None:
logger.debug("Will rewrite file {} {}".format(env_file.filename, item))
return (result, env_file.filename) if return_file else result
if len(self._files) == 1:
expect(
allow_undefined or result is not None,
"No variable {} found in file {}".format(item, self._files[0].filename),
)
else:
expect(
allow_undefined or result is not None,
"No variable {} found in case".format(item),
)
def set_valid_values(self, item, valid_values):
"""
Update or create a valid_values entry for item and populate it
"""
expect(
not self._read_only_mode,
"Cannot modify case, read_only. "
"Case must be opened with read_only=False and can only be modified within a context manager",
)
result = None
for env_file in self._env_entryid_files:
result = env_file.set_valid_values(item, valid_values)
if result is not None:
logger.debug("Will rewrite file {} {}".format(env_file.filename, item))
return result
def set_lookup_value(self, item, value):
if item in self.lookups and self.lookups[item] is not None:
logger.warning(
"Item {} already in lookups with value {}".format(
item, self.lookups[item]
)
)
else:
logger.debug("Setting in lookups: item {}, value {}".format(item, value))
self.lookups[item] = value
def clean_up_lookups(self, allow_undefined=False):
# put anything in the lookups table into existing env objects
for key, value in list(self.lookups.items()):
logger.debug("lookup key {} value {}".format(key, value))
result = self.set_value(key, value, allow_undefined=allow_undefined)
if result is not None:
del self.lookups[key]
def _set_compset(self, compset_name, files):
"""
Loop through all the compset files and find the compset
specifation file that matches either the input 'compset_name'.
Note that the input compset name (i.e. compset_name) can be
either a longname or an alias. This will set various compset-related
info.
Returns a tuple: (compset_alias, science_support, component_defining_compset)
(For a user-defined compset - i.e., a compset without an alias - these
return values will be None, [], None.)
"""
science_support = []
compset_alias = None
components = files.get_components("COMPSETS_SPEC_FILE")
logger.debug(
" Possible components for COMPSETS_SPEC_FILE are {}".format(components)
)
self.set_lookup_value("COMP_INTERFACE", self._comp_interface)
if config.set_comp_root_dir_cpl:
if config.use_nems_comp_root_dir:
ufs_driver = os.environ.get("UFS_DRIVER")
attribute = None
if ufs_driver:
attribute = {"component": "nems"}
comp_root_dir_cpl = files.get_value(
"COMP_ROOT_DIR_CPL", attribute=attribute
)
else:
comp_root_dir_cpl = files.get_value("COMP_ROOT_DIR_CPL")
self.set_lookup_value("COMP_ROOT_DIR_CPL", comp_root_dir_cpl)
# Loop through all of the files listed in COMPSETS_SPEC_FILE and find the file
# that has a match for either the alias or the longname in that order
for component in components:
# Determine the compsets file for this component
compsets_filename = files.get_value(
"COMPSETS_SPEC_FILE", {"component": component}
)
# If the file exists, read it and see if there is a match for the compset alias or longname
if os.path.isfile(compsets_filename):
compsets = Compsets(compsets_filename)
match, compset_alias, science_support = compsets.get_compset_match(
name=compset_name
)
if match is not None:
self._compsetname = match
logger.info("Compset longname is {}".format(match))
logger.info(
"Compset specification file is {}".format(compsets_filename)
)
break
if compset_alias is None:
logger.info(
"Did not find an alias or longname compset match for {} ".format(
compset_name
)
)
self._compsetname = compset_name
# Fill in compset name
self._compsetname, self._components = self.valid_compset(
self._compsetname, compset_alias, files
)
# if this is a valiid compset longname there will be at least 7 components.
components = self.get_compset_components()
expect(
len(components) > 6,
"No compset alias {} found and this does not appear to be a compset longname.".format(
compset_name
),
)
return compset_alias, science_support
def get_primary_component(self):
if self._primary_component is None:
self._primary_component = self._find_primary_component()
return self._primary_component
def _find_primary_component(self):
"""
try to glean the primary component based on compset name
"""
progcomps = {}
spec = {}
primary_component = None
for comp in self._component_classes:
if comp == "CPL":
continue
spec[comp] = self.get_value("COMP_{}".format(comp))
notprogcomps = ("D{}".format(comp), "X{}".format(comp), "S{}".format(comp))
if spec[comp].upper() in notprogcomps:
progcomps[comp] = False
else:
progcomps[comp] = True
expect(
"ATM" in progcomps
and "LND" in progcomps
and "OCN" in progcomps
and "ICE" in progcomps,
" Not finding expected components in {}".format(self._component_classes),
)
if (
progcomps["ATM"]
and progcomps["LND"]
and progcomps["OCN"]
and progcomps["ICE"]
):
primary_component = "allactive"
elif progcomps["LND"] and progcomps["OCN"] and progcomps["ICE"]:
# this is a "J" compset
primary_component = "allactive"
elif progcomps["ATM"] and progcomps["OCN"] and progcomps["ICE"]:
# this is a ufs s2s compset
primary_component = "allactive"
elif progcomps["ATM"]:
if "DOCN%SOM" in self._compsetname and progcomps["LND"]:
# This is an "E" compset
primary_component = "allactive"
else:
# This is an "F" or "Q" compset
primary_component = spec["ATM"]
elif progcomps["LND"]:
# This is an "I" compset
primary_component = spec["LND"]
elif progcomps["OCN"]:
# This is a "C" or "G" compset
primary_component = spec["OCN"]
elif progcomps["ICE"]:
# This is a "D" compset
primary_component = spec["ICE"]
elif "GLC" in progcomps and progcomps["GLC"]:
# This is a "TG" compset
primary_component = spec["GLC"]
elif progcomps["ROF"]:
# This is a "R" compset
primary_component = spec["ROF"]
elif progcomps["WAV"]:
# This is a "V" compset
primary_component = spec["WAV"]
else:
# This is "A", "X" or "S"
primary_component = "drv"
return primary_component
def _valid_compset_impl(self, compset_name, compset_alias, comp_classes, comp_hash):
"""Add stub models missing in <compset_name>, return full compset name.
<comp_classes> is a list of all supported component classes.
<comp_hash> is a dictionary where each key is a supported component
(e.g., datm) and the associated value is the index in <comp_classes> of
that component's class (e.g., 1 for atm).
>>> import os, shutil, tempfile
>>> workdir = tempfile.mkdtemp()
>>> caseroot = os.path.join(workdir, 'caseroot') # use non-existent caseroot to avoid error about not being a valid case directory in Case __init__ method
>>> Case(caseroot, read_only=False)._valid_compset_impl('2000_DATM%NYF_SLND_DICE%SSMI_DOCN%DOM_DROF%NYF_SGLC_SWAV', None, ['CPL', 'ATM', 'LND', 'ICE', 'OCN', 'ROF', 'GLC', 'WAV', 'ESP'], {'datm':1,'satm':1,'dlnd':2,'slnd':2,'dice':3,'sice':3,'docn':4,'socn':4,'drof':5,'srof':5,'sglc':6,'swav':7,'ww3':7,'sesp':8})
('2000_DATM%NYF_SLND_DICE%SSMI_DOCN%DOM_DROF%NYF_SGLC_SWAV_SESP', ['2000', 'DATM%NYF', 'SLND', 'DICE%SSMI', 'DOCN%DOM', 'DROF%NYF', 'SGLC', 'SWAV', 'SESP'])
>>> Case(caseroot, read_only=False)._valid_compset_impl('2000_DATM%NYF_SLND_DICE%SSMI_DOCN%DOM_DROF%NYF_SGLC_SWAV', None, ['CPL', 'ATM', 'LND', 'ICE', 'OCN', 'ROF', 'GLC', 'WAV', 'ESP'], {'datm':1,'satm':1,'dlnd':2,'slnd':2,'dice':3,'sice':3,'docn':4,'socn':4,'drof':5,'srof':5,'sglc':6,'swav':7,'ww3':7,'sesp':8})
('2000_DATM%NYF_SLND_DICE%SSMI_DOCN%DOM_DROF%NYF_SGLC_SWAV_SESP', ['2000', 'DATM%NYF', 'SLND', 'DICE%SSMI', 'DOCN%DOM', 'DROF%NYF', 'SGLC', 'SWAV', 'SESP'])
>>> Case(caseroot, read_only=False)._valid_compset_impl('atm:DATM%NYF_rof:DROF%NYF_scn:2000_ice:DICE%SSMI_ocn:DOCN%DOM', None, ['CPL', 'ATM', 'LND', 'ICE', 'OCN', 'ROF', 'GLC', 'WAV', 'ESP'], {'datm':1,'satm':1,'dlnd':2,'slnd':2,'dice':3,'sice':3,'docn':4,'socn':4,'drof':5,'srof':5,'sglc':6,'swav':7,'ww3':7,'sesp':8})
('2000_DATM%NYF_SLND_DICE%SSMI_DOCN%DOM_DROF%NYF_SGLC_SWAV_SESP', ['2000', 'DATM%NYF', 'SLND', 'DICE%SSMI', 'DOCN%DOM', 'DROF%NYF', 'SGLC', 'SWAV', 'SESP'])
>>> Case(caseroot, read_only=False)._valid_compset_impl('2000_DATM%NYF_DICE%SSMI_DOCN%DOM_DROF%NYF', None, ['CPL', 'ATM', 'LND', 'ICE', 'OCN', 'ROF', 'GLC', 'WAV', 'ESP'], {'datm':1,'satm':1,'dlnd':2,'slnd':2,'dice':3,'sice':3,'docn':4,'socn':4,'drof':5,'srof':5,'sglc':6,'swav':7,'ww3':7,'sesp':8})
('2000_DATM%NYF_SLND_DICE%SSMI_DOCN%DOM_DROF%NYF_SGLC_SWAV_SESP', ['2000', 'DATM%NYF', 'SLND', 'DICE%SSMI', 'DOCN%DOM', 'DROF%NYF', 'SGLC', 'SWAV', 'SESP'])
>>> Case(caseroot, read_only=False)._valid_compset_impl('2000_DICE%SSMI_DOCN%DOM_DATM%NYF_DROF%NYF', None, ['CPL', 'ATM', 'LND', 'ICE', 'OCN', 'ROF', 'GLC', 'WAV', 'ESP'], {'datm':1,'satm':1,'dlnd':2,'slnd':2,'dice':3,'sice':3,'docn':4,'socn':4,'drof':5,'srof':5,'sglc':6,'swav':7,'ww3':7,'sesp':8})
('2000_DATM%NYF_SLND_DICE%SSMI_DOCN%DOM_DROF%NYF_SGLC_SWAV_SESP', ['2000', 'DATM%NYF', 'SLND', 'DICE%SSMI', 'DOCN%DOM', 'DROF%NYF', 'SGLC', 'SWAV', 'SESP'])
>>> Case(caseroot, read_only=False)._valid_compset_impl('2000_DICE%SSMI_DOCN%DOM_DATM%NYF_DROF%NYF_TEST', None, ['CPL', 'ATM', 'LND', 'ICE', 'OCN', 'ROF', 'GLC', 'WAV', 'ESP'], {'datm':1,'satm':1,'dlnd':2,'slnd':2,'dice':3,'sice':3,'docn':4,'socn':4,'drof':5,'srof':5,'sglc':6,'swav':7,'ww3':7,'sesp':8})
('2000_DATM%NYF_SLND_DICE%SSMI_DOCN%DOM_DROF%NYF_SGLC_SWAV_SESP_TEST', ['2000', 'DATM%NYF', 'SLND', 'DICE%SSMI', 'DOCN%DOM', 'DROF%NYF', 'SGLC', 'SWAV', 'SESP'])
>>> Case(caseroot, read_only=False)._valid_compset_impl('1850_CAM60_CLM50%BGC-CROP_CICE_POP2%ECO%ABIO-DIC_MOSART_CISM2%NOEVOLVE_WW3_BGC%BDRD', None, ['CPL', 'ATM', 'LND', 'ICE', 'OCN', 'ROF', 'GLC', 'WAV', 'ESP'], {'datm':1,'satm':1, 'cam':1,'dlnd':2,'clm':2,'slnd':2,'cice':3,'dice':3,'sice':3,'pop':4,'docn':4,'socn':4,'mosart':5,'drof':5,'srof':5,'cism':6,'sglc':6,'ww':7,'swav':7,'ww3':7,'sesp':8})
('1850_CAM60_CLM50%BGC-CROP_CICE_POP2%ECO%ABIO-DIC_MOSART_CISM2%NOEVOLVE_WW3_SESP_BGC%BDRD', ['1850', 'CAM60', 'CLM50%BGC-CROP', 'CICE', 'POP2%ECO%ABIO-DIC', 'MOSART', 'CISM2%NOEVOLVE', 'WW3', 'SESP'])
>>> Case(caseroot, read_only=False)._valid_compset_impl('1850_CAM60_CLM50%BGC-CROP_CICE_POP2%ECO%ABIO-DIC_MOSART_CISM2%NOEVOLVE_WW3_BGC%BDRD_TEST', None, ['CPL', 'ATM', 'LND', 'ICE', 'OCN', 'ROF', 'GLC', 'WAV', 'IAC', 'ESP'], {'datm':1,'satm':1, 'cam':1,'dlnd':2,'clm':2,'slnd':2,'cice':3,'dice':3,'sice':3,'pop':4,'docn':4,'socn':4,'mosart':5,'drof':5,'srof':5,'cism':6,'sglc':6,'ww':7,'swav':7,'ww3':7,'sesp':8})
('1850_CAM60_CLM50%BGC-CROP_CICE_POP2%ECO%ABIO-DIC_MOSART_CISM2%NOEVOLVE_WW3_SIAC_SESP_BGC%BDRD_TEST', ['1850', 'CAM60', 'CLM50%BGC-CROP', 'CICE', 'POP2%ECO%ABIO-DIC', 'MOSART', 'CISM2%NOEVOLVE', 'WW3', 'SIAC', 'SESP'])
>>> Case(caseroot, read_only=False)._valid_compset_impl('1850_SATM_SLND_SICE_SOCN_SGLC_SWAV', 'S', ['CPL', 'ATM', 'LND', 'ICE', 'OCN', 'ROF', 'GLC', 'WAV', 'IAC', 'ESP'], {'datm':1,'satm':1, 'cam':1,'dlnd':2,'clm':2,'slnd':2,'cice':3,'dice':3,'sice':3,'pop':4,'docn':4,'socn':4,'mosart':5,'drof':5,'srof':5,'cism':6,'sglc':6,'ww':7,'swav':7,'ww3':7,'sesp':8})
('1850_SATM_SLND_SICE_SOCN_SROF_SGLC_SWAV_SIAC_SESP', ['1850', 'SATM', 'SLND', 'SICE', 'SOCN', 'SROF', 'SGLC', 'SWAV', 'SIAC', 'SESP'])
>>> Case(caseroot, read_only=False)._valid_compset_impl('1850_SATM_SLND_SICE_SOCN_SGLC_SWAV', None, ['CPL', 'ATM', 'LND', 'ICE', 'OCN', 'ROF', 'GLC', 'WAV', 'IAC', 'ESP'], {'datm':1,'satm':1, 'cam':1,'dlnd':2,'clm':2,'slnd':2,'cice':3,'dice':3,'sice':3,'pop':4,'docn':4,'socn':4,'mosart':5,'drof':5,'srof':5,'cism':6,'sglc':6,'ww':7,'swav':7,'ww3':7,'sesp':8}) #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
CIMEError: ERROR: Invalid compset name, 1850_SATM_SLND_SICE_SOCN_SGLC_SWAV, all stub components generated
>>> shutil.rmtree(workdir, ignore_errors=True)
"""
# Find the models declared in the compset
model_set = [None] * len(comp_classes)
components = compset_name.split("_")
noncomps = []
allstubs = True
colonformat = ":" in compset_name
if colonformat:
# make sure that scn: is component[0] as expected
for i in range(1, len(components)):
if components[i].startswith("scn:"):
tmp = components[0]
components[0] = components[i]
components[i] = tmp
break
model_set[0] = components[0][4:]
else:
model_set[0] = components[0]
for model in components[1:]:
match = Case.__mod_match_re__.match(model.lower())
expect(match is not None, "No model match for {}".format(model))
mod_match = match.group(1)
# Check for noncomponent appends (BGC & TEST)
if mod_match in ("bgc", "test"):
noncomps.append(model)
elif ":" in mod_match:
comp_ind = comp_hash[mod_match[4:]]
model_set[comp_ind] = model
else:
expect(mod_match in comp_hash, "Unknown model type, {}".format(model))
comp_ind = comp_hash[mod_match]
model_set[comp_ind] = model
# Fill in missing components with stubs
for comp_ind in range(1, len(model_set)):
if model_set[comp_ind] is None:
comp_class = comp_classes[comp_ind]
stub = "S" + comp_class
logger.info("Automatically adding {} to compset".format(stub))
model_set[comp_ind] = stub
elif ":" in model_set[comp_ind]:
model_set[comp_ind] = model_set[comp_ind][4:]
if model_set[comp_ind][0] != "S":
allstubs = False
expect(
(compset_alias is not None) or (not allstubs),
"Invalid compset name, {}, all stub components generated".format(
compset_name
),
)
# Return the completed compset
compsetname = "_".join(model_set)
for noncomp in noncomps:
compsetname = compsetname + "_" + noncomp
return compsetname, model_set
# RE to match component type name without optional piece (stuff after %).
# Drop any trailing digits (e.g., the 60 in CAM60) to ensure match
# Note, this will also drop trailing digits such as in ww3 but since it
# is handled consistenly, this should not affect functionality.
# Note: interstitial digits are included (e.g., in FV3GFS).
__mod_match_re__ = re.compile(r"([^%]*[^0-9%]+)")
def valid_compset(self, compset_name, compset_alias, files):
"""Add stub models missing in <compset_name>, return full compset name.
<files> is used to collect set of all supported components.
"""
# First, create hash of model names
# A note about indexing. Relevant component classes start at 1
# because we ignore CPL for finding model components.
# Model components would normally start at zero but since we are
# dealing with a compset, 0 is reserved for the time field
drv_config_file = files.get_value("CONFIG_CPL_FILE")
drv_comp = Component(drv_config_file, "CPL")
comp_classes = drv_comp.get_valid_model_components()
comp_hash = {} # Hash model name to component class index
for comp_ind in range(1, len(comp_classes)):
comp = comp_classes[comp_ind]
# Find list of models for component class
# List can be in different locations, check CONFIG_XXX_FILE
node_name = "CONFIG_{}_FILE".format(comp)
models = files.get_components(node_name)
if (models is None) or (None in models):
# Backup, check COMP_ROOT_DIR_XXX
node_name = "COMP_ROOT_DIR_" + comp
models = files.get_components(node_name)
expect(
(models is not None) and (None not in models),
"Unable to find list of supported components",
)
for model in models:
mod_match = Case.__mod_match_re__.match(model.lower()).group(1)
comp_hash[mod_match] = comp_ind
return self._valid_compset_impl(
compset_name, compset_alias, comp_classes, comp_hash
)
def _set_info_from_primary_component(self, files, pesfile=None):
"""
Sets file and directory paths that depend on the primary component of
this compset.
Assumes that self._primary_component has already been set.
"""
component = self.get_primary_component()
compset_spec_file = files.get_value(
"COMPSETS_SPEC_FILE", {"component": component}, resolved=False
)
self.set_lookup_value("COMPSETS_SPEC_FILE", compset_spec_file)
if pesfile is None:
self._pesfile = files.get_value("PES_SPEC_FILE", {"component": component})
pesfile_unresolved = files.get_value(
"PES_SPEC_FILE", {"component": component}, resolved=False
)
logger.info("Pes specification file is {}".format(self._pesfile))
else:
self._pesfile = pesfile
pesfile_unresolved = pesfile
expect(
self._pesfile is not None,
"No pesfile found for component {}".format(component),
)
self.set_lookup_value("PES_SPEC_FILE", pesfile_unresolved)
tests_filename = files.get_value(
"TESTS_SPEC_FILE", {"component": component}, resolved=False
)
tests_mods_dir = files.get_value(
"TESTS_MODS_DIR", {"component": component}, resolved=False
)
user_mods_dir = files.get_value(
"USER_MODS_DIR", {"component": component}, resolved=False
)
self.set_lookup_value("TESTS_SPEC_FILE", tests_filename)
self.set_lookup_value("TESTS_MODS_DIR", tests_mods_dir)
self.set_lookup_value("USER_MODS_DIR", user_mods_dir)
def get_compset_components(self):
# If are doing a create_clone then, self._compsetname is not set yet
components = []
compset = self.get_value("COMPSET")
if compset is None:
compset = self._compsetname
expect(compset is not None, "compset is not set")
# the first element is always the date operator - skip it
elements = compset.split("_")[1:] # pylint: disable=maybe-no-member
for element in elements:
if ":" in element:
element = element[4:]
# ignore the possible BGC or TEST modifier
if element.startswith("BGC%") or element.startswith("TEST"):
continue
else:
element_component = element.split("%")[0].lower()