-
Notifications
You must be signed in to change notification settings - Fork 64
/
mkstatic.py
executable file
·1847 lines (1637 loc) · 92.1 KB
/
mkstatic.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
#!/usr/bin/env python3
#
import collections
import copy
import getopt
import filecmp
import logging
import os
import re
import sys
import types
import xml.etree.ElementTree as ET
from common import encode_container
from common import CCPP_STAGES
from common import CCPP_T_INSTANCE_VARIABLE, CCPP_ERROR_CODE_VARIABLE, CCPP_ERROR_MSG_VARIABLE, CCPP_LOOP_COUNTER, CCPP_LOOP_EXTENT
from common import CCPP_BLOCK_NUMBER, CCPP_BLOCK_COUNT, CCPP_BLOCK_SIZES, CCPP_THREAD_NUMBER, CCPP_INTERNAL_VARIABLES
from common import CCPP_CONSTANT_ONE, CCPP_HORIZONTAL_DIMENSION, CCPP_HORIZONTAL_LOOP_EXTENT, CCPP_NUM_INSTANCES
from common import FORTRAN_CONDITIONAL_REGEX_WORDS, FORTRAN_CONDITIONAL_REGEX
from common import CCPP_TYPE, STANDARD_VARIABLE_TYPES, STANDARD_CHARACTER_TYPE
from common import CCPP_STATIC_API_MODULE, CCPP_STATIC_SUBROUTINE_NAME
from metadata_parser import CCPP_MANDATORY_VARIABLES
from mkcap import Var
###############################################################################
# Limit suite names to 37 characters; this keeps cap names below 64 characters
# Cap names of 64 characters or longer can cause issues with some compilers.
SUITE_NAME_MAX_CHARS = 37
# Maximum number of dimensions of an array allowed by the Fortran 2008 standard
FORTRAN_ARRAY_MAX_DIMS = 15
# These variables always need to be present for creating suite and group caps
CCPP_SUITE_VARIABLES = { **CCPP_MANDATORY_VARIABLES,
CCPP_LOOP_COUNTER : Var(local_name = 'loop_cnt',
standard_name = CCPP_LOOP_COUNTER,
long_name = 'loop counter for subcycling loops in CCPP',
units = 'index',
type = 'integer',
dimensions = [],
rank = '',
kind = '',
intent = 'in',
active = 'T',
),
CCPP_LOOP_EXTENT : Var(local_name = 'loop_max',
standard_name = CCPP_LOOP_EXTENT,
long_name = 'loop counter for subcycling loops in CCPP',
units = 'count',
type = 'integer',
dimensions = [],
rank = '',
kind = '',
intent = 'in',
active = 'T',
),
}
###############################################################################
def extract_parents_and_indices_from_local_name(local_name):
"""Break apart local_name into the different components (members of DDTs)
to determine all variables that are required; this must work for complex
constructs such as Atm(mytile)%q(:,:,:,Atm2(mytile2)%graupel), with
result parent = 'Atm', indices = [mytile, Atm2, mytile2]"""
# First, extract all variables/indices in parentheses (used for subsetting)
indices = []
while '(' in local_name:
for i in range(len(local_name)):
if local_name[i] == '(':
last_open = i
elif local_name[i] == ')':
last_closed = i
break
index_set = local_name[last_open+1:last_closed].split(',')
for index_group in index_set:
for index in index_group.split(':'):
if index:
if '%' in index:
indices.append(index[:index.find('%')])
else:
# Skip hard-coded integers that are not variables
try:
int(index)
except ValueError:
indices.append(index)
# Remove this innermost index group (...) from local_name
local_name = local_name.replace(local_name[last_open:last_closed+1], '')
# Remove duplicates from indices
indices = list(set(indices))
# Derive parent of actual variable (now that all subsets have been processed)
if '%' in local_name:
parent = local_name[:local_name.find('%')]
else:
parent = local_name
# Remove whitespaces
parent = parent.strip()
indices = [ x.strip() for x in indices ]
return (parent, indices)
def create_argument_list_wrapped(arguments):
"""Create a wrapped argument list, remove trailing ',' """
argument_list = ''
length = 0
for argument in arguments:
argument_list += argument + ','
length += len(argument)+1
# Split args so that lines don't exceed 260 characters (for PGI)
if length > 70 and not argument == arguments[-1]:
argument_list += ' &\n '
length = 0
if argument_list:
argument_list = argument_list.rstrip(',')
return argument_list
def create_argument_list_wrapped_explicit(arguments, additional_vars_following = False):
"""Create a wrapped argument list with explicit arguments x=y. If no additional
variables are added (additional_vars_following == False), remove trailing ',' """
argument_list = ''
length = 0
for argument in arguments:
argument_list += argument + '=' + argument + ','
length += 2*len(argument)+2
# Split args so that lines don't exceed 260 characters (for PGI)
if length > 70 and not argument == arguments[-1]:
argument_list += ' &\n '
length = 0
if argument_list and not additional_vars_following:
argument_list = argument_list.rstrip(',')
return argument_list
def create_arguments_module_use_var_defs(variable_dictionary, metadata_define, tmpvars = None):
"""Given a dictionary of standard names and variables, and a metadata
dictionary with the variable definitions by the host model, create a list
of arguments (local names), module use statements (for derived data types
and non-standard kinds), and the variable definition statements."""
arguments = []
module_use = []
var_defs = []
local_kind_and_type_vars = []
# We need to run through this loop twice. In the first pass, process all scalars.
# In the second pass, process all arrays. This is so that any potential dimension
# that is used in the following array variable definitions is defined first to avoid
# violating the Fortran 2008 standard.
# https://community.intel.com/t5/Intel-Fortran-Compiler/Order-of-declaration-statements-with-and-without-implicit-typing/td-p/1176155
iteration = 1
while iteration <= 2:
for standard_name in variable_dictionary.keys():
if iteration == 1 and variable_dictionary[standard_name].dimensions:
continue
elif iteration == 2 and not variable_dictionary[standard_name].dimensions:
continue
# Add variable local name and variable definitions
arguments.append(variable_dictionary[standard_name].local_name)
var_defs.append(variable_dictionary[standard_name].print_def_intent(metadata_define))
# Add special kind variables and derived data type definitions to module use statements
if variable_dictionary[standard_name].type in STANDARD_VARIABLE_TYPES and variable_dictionary[standard_name].kind \
and not variable_dictionary[standard_name].type == STANDARD_CHARACTER_TYPE:
kind_var_standard_name = variable_dictionary[standard_name].kind
if not kind_var_standard_name in local_kind_and_type_vars:
if not kind_var_standard_name in metadata_define.keys():
raise Exception("Kind {kind} not defined by host model".format(kind=kind_var_standard_name))
kind_var = metadata_define[kind_var_standard_name][0]
module_use.append(kind_var.print_module_use())
local_kind_and_type_vars.append(kind_var_standard_name)
elif not variable_dictionary[standard_name].type in STANDARD_VARIABLE_TYPES:
type_var_standard_name = variable_dictionary[standard_name].type
if not type_var_standard_name in local_kind_and_type_vars:
if not type_var_standard_name in metadata_define.keys():
raise Exception("Type {type} not defined by host model".format(type=type_var_standard_name))
type_var = metadata_define[type_var_standard_name][0]
module_use.append(type_var.print_module_use())
local_kind_and_type_vars.append(type_var_standard_name)
iteration += 1
# Add any local variables (required for unit conversions, array transformations, ...)
if tmpvars:
var_defs.append('')
var_defs.append('! Local variables for unit conversions, array transformations, ...')
for tmpvar in tmpvars:
var_defs.append(tmpvar.print_def_local(metadata_define))
# Add special kind variables
if tmpvar.type in STANDARD_VARIABLE_TYPES and tmpvar.kind and not tmpvar.type == STANDARD_CHARACTER_TYPE:
kind_var_standard_name = tmpvar.kind
if not kind_var_standard_name in local_kind_and_type_vars:
if not kind_var_standard_name in metadata_define.keys():
raise Exception("Kind {kind} not defined by host model".format(kind=kind_var_standard_name))
kind_var = metadata_define[kind_var_standard_name][0]
module_use.append(kind_var.print_module_use())
local_kind_and_type_vars.append(kind_var_standard_name)
return (arguments, module_use, var_defs)
class API(object):
header='''
!
! This work (Common Community Physics Package), identified by NOAA, NCAR,
! CU/CIRES, is free of known copyright restrictions and is placed in the
! public domain.
!
! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
! THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
! IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
! CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
!
!>
!! @brief Auto-generated API for the CCPP static build
!!
!
module {module}
{module_use}
implicit none
private
public :: {subroutines}
contains
'''
sub = '''
subroutine {subroutine}({ccpp_var_name}, suite_name, group_name, ierr)
use ccpp_types, only : ccpp_t
implicit none
type(ccpp_t), intent(inout) :: {ccpp_var_name}
character(len=*), intent(in) :: suite_name
character(len=*), optional, intent(in) :: group_name
integer, intent(out) :: ierr
ierr = 0
{suite_switch}
else
write({ccpp_var_name}%errmsg,'(*(a))') 'Invalid suite ' // trim(suite_name)
ierr = 1
end if
{ccpp_var_name}%errflg = ierr
end subroutine {subroutine}
'''
footer = '''
end module {module}
'''
def __init__(self, **kwargs):
self._filename = CCPP_STATIC_API_MODULE + '.F90'
self._module = CCPP_STATIC_API_MODULE
self._subroutines = None
self._suites = []
self._directory = '.'
self._update_api = True
for key, value in kwargs.items():
setattr(self, "_"+key, value)
@property
def filename(self):
'''Get the filename to write API to.'''
return self._filename
@filename.setter
def filename(self, value):
self._filename = value
@property
def directory(self):
'''Get the directory to write API to.'''
return self._directory
@directory.setter
def directory(self, value):
self._directory = value
@property
def update_api(self):
'''Get the update_api flag.'''
return self._update_api
@update_api.setter
def update_api(self, value):
self._update_api = value
@property
def module(self):
'''Get the module name of the API.'''
return self._module
@module.setter
def module(self, value):
self._module = value
@property
def subroutines(self):
'''Get the subroutines names of the API to.'''
return self._subroutines
def write(self):
"""Write API for static build"""
if not self._suites:
raise Exception("No suites specified for generating API")
suites = self._suites
# Module use statements for suite and group caps
module_use = ''
for suite in suites:
for subroutine in suite.subroutines:
module_use += ' use {module}, only: {subroutine}\n'.format(module=suite.module, subroutine=subroutine)
for group in suite.groups:
for subroutine in group.subroutines:
module_use += ' use {module}, only: {subroutine}\n'.format(module=group.module, subroutine=subroutine)
# Add all variables required to module use statements. This is for the API only,
# because the static API imports all variables from modules instead of receiving them
# via the argument list. Special handling for a single variable of type CCPP_TYPE (ccpp_t),
# which comes in as a scalar for any potential block/thread via the argument list.
ccpp_var = None
parent_standard_names = []
for ccpp_stage in CCPP_STAGES.keys():
for suite in suites:
for parent_standard_name in suite.parents[ccpp_stage].keys():
if not parent_standard_name in parent_standard_names:
parent_var = suite.parents[ccpp_stage][parent_standard_name]
# Identify which variable is of type CCPP_TYPE (need local name)
if parent_var.type == CCPP_TYPE:
if ccpp_var and not ccpp_var.local_name==parent_var.local_name:
raise Exception('There can be only one variable of type {0}, found {1} and {2}'.format(
CCPP_TYPE, ccpp_var.local_name, parent_var.local_name))
ccpp_var = parent_var
continue
module_use += ' {0}\n'.format(parent_var.print_module_use())
parent_standard_names.append(parent_standard_name)
if not ccpp_var:
raise Exception('No variable of type {0} found - need a scalar instance.'.format(CCPP_TYPE))
elif not ccpp_var.rank == '':
raise Exception('CCPP variable {0} of type {1} must be a scalar.'.format(ccpp_var.local_name, CCPP_TYPE))
del parent_standard_names
# Create a subroutine for each stage
self._subroutines=[]
subs = ''
for ccpp_stage in CCPP_STAGES.keys():
suite_switch = ''
for suite in suites:
# Calls to groups of schemes for this stage
group_calls = ''
for group in suite.groups:
# The <init></init> and <finalize></finalize> groups require special treatment,
# since they can only be run in the respective stage (init/finalize)
if (group.init and not ccpp_stage == 'init') or \
(group.finalize and not ccpp_stage == 'finalize'):
continue
if not group_calls:
clause = 'if'
else:
clause = 'else if'
argument_list_group = create_argument_list_wrapped_explicit(group.arguments[ccpp_stage])
group_calls += '''
{clause} (trim(group_name)=="{group_name}") then
ierr = {suite_name}_{group_name}_{stage}_cap({arguments})'''.format(clause=clause,
suite_name=group.suite,
group_name=group.name,
stage=CCPP_STAGES[ccpp_stage],
arguments=argument_list_group)
group_calls += '''
else
write({ccpp_var_name}%errmsg, '(*(a))') 'Group ' // trim(group_name) // ' not found'
ierr = 1
end if
'''.format(ccpp_var_name=ccpp_var.local_name, group_name=group.name)
# Call to entire suite for this stage
# Create argument list for calling the full suite
argument_list_suite = create_argument_list_wrapped_explicit(suite.arguments[ccpp_stage])
suite_call = '''
ierr = {suite_name}_{stage}_cap({arguments})
'''.format(suite_name=suite.name, stage=CCPP_STAGES[ccpp_stage], arguments=argument_list_suite)
# Add call to all groups of this suite and to the entire suite
if not suite_switch:
clause = 'if'
else:
clause = 'else if'
suite_switch += '''
{clause} (trim(suite_name)=="{suite_name}") then
if (present(group_name)) then
{group_calls}
else
{suite_call}
end if
'''.format(clause=clause, suite_name=suite.name, group_calls=group_calls, suite_call=suite_call)
subroutine = CCPP_STATIC_SUBROUTINE_NAME.format(stage=ccpp_stage)
self._subroutines.append(subroutine)
subs += API.sub.format(subroutine=subroutine,
ccpp_var_name=ccpp_var.local_name,
suite_switch=suite_switch)
# Write output to stdout or file
if (self.filename is not sys.stdout):
filepath = os.path.split(self.filename)[0]
if filepath and not os.path.isdir(filepath):
os.makedirs(filepath)
# If the file exists, write to temporary file first and compare them:
# - if identical, delete the temporary file and keep the existing one
# and set the API update flag to false
# - if different, replace existing file with temporary file and set
# the API update flag to true (default value)
# - always replace the file if any of the suite caps has changed
# If the file does not exist, write the API an set the flag to true
if os.path.isfile(self.filename) and \
not any([suite.update_cap for suite in suites]):
write_to_test_file = True
test_filename = self.filename + '.test'
f = open(test_filename, 'w')
else:
write_to_test_file = False
f = open(self.filename, 'w')
else:
f = sys.stdout
f.write(API.header.format(module=self._module,
module_use=module_use,
subroutines=','.join(self._subroutines)))
f.write(subs)
f.write(Suite.footer.format(module=self._module))
if (f is not sys.stdout):
f.close()
# See comment above on updating the API or not
if write_to_test_file:
if filecmp.cmp(self.filename, test_filename):
# Files are equal, delete the test API and set update flag to False
os.remove(test_filename)
self.update_api = False
else:
# Files are different, replace existing API with
# the test API and set update flag to True
# Python 3 only: os.replace(test_filename, self.filename)
os.remove(self.filename)
os.rename(test_filename, self.filename)
self.update_api = True
else:
self.update_api = True
return
def write_includefile(self, source_filename, type):
success = True
filepath = os.path.split(source_filename)[0]
if filepath and not os.path.isdir(filepath):
os.makedirs(filepath)
# If the file exists, write to temporary file first and compare them:
# - if identical, delete the temporary file and keep the existing one
# - if different, replace existing file with temporary file
# - however, always replace the file if the API update flag is true
if os.path.isfile(source_filename) and not self.update_api:
write_to_test_file = True
test_filename = source_filename + '.test'
f = open(test_filename, 'w')
else:
write_to_test_file = False
f = open(source_filename, 'w')
if type == 'shell':
# Contents of shell/source file
contents = """# The CCPP static API is defined here.
#
# This file is auto-generated using ccpp_prebuild.py
# at compile time, do not edit manually.
#
export CCPP_STATIC_API=\"{filename}\"
""".format(filename=os.path.abspath(os.path.join(self.directory,self.filename)))
elif type == 'cmake':
# Contents of cmake include file
contents = """# The CCPP static API is defined here.
#
# This file is auto-generated using ccpp_prebuild.py
# at compile time, do not edit manually.
#
set(API \"{filename}\")
""".format(filename=os.path.abspath(os.path.join(self.directory,self.filename)))
else:
logging.error('Encountered unknown type of file "{type}" when writing include file for static API'.format(type=type))
success = False
return
f.write(contents)
f.close()
# See comment above on updating the API or not
if write_to_test_file:
if filecmp.cmp(source_filename, test_filename):
# Files are equal, delete the test file
os.remove(test_filename)
else:
# Files are different, replace existing file
# Python 3 only: os.replace(test_filename, source_filename)
os.remove(source_filename)
os.rename(test_filename, source_filename)
return success
class Suite(object):
header='''
!
! This work (Common Community Physics Package), identified by NOAA, NCAR,
! CU/CIRES, is free of known copyright restrictions and is placed in the
! public domain.
!
! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
! THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
! IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
! CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
!
!>
!! @brief Auto-generated cap module for the CCPP suite
!!
!
module {module}
{module_use}
implicit none
private
public :: {subroutines}
contains
'''
sub = '''
function {subroutine}({arguments}) result(ierr)
{module_use}
implicit none
integer :: ierr
{var_defs}
ierr = 0
{body}
end function {subroutine}
'''
footer = '''
end module {module}
'''
def __init__(self, **kwargs):
self._name = None
self._filename = sys.stdout
self._sdf_name = None
self._all_schemes_called = None
self._all_subroutines_called = None
self._call_tree = {}
self._caps = None
self._module = None
self._subroutines = None
self._parents = { ccpp_stage : collections.OrderedDict() for ccpp_stage in CCPP_STAGES.keys() }
self._arguments = { ccpp_stage : [] for ccpp_stage in CCPP_STAGES.keys() }
self._update_cap = True
for key, value in kwargs.items():
setattr(self, "_"+key, value)
@property
def name(self):
'''Get the name of the suite.'''
return self._name
@property
def sdf_name(self):
'''Get the name of the suite definition file.'''
return self._sdf_name
@sdf_name.setter
def sdf_name(self, value):
self._sdf_name = value
@property
def filename(self):
'''Get the filename of write the output to.'''
return self._filename
@filename.setter
def filename(self, value):
self._filename = value
@property
def update_cap(self):
'''Get the update_cap flag.'''
return self._update_cap
@update_cap.setter
def update_cap(self, value):
self._update_cap = value
def parse(self, make_call_tree=False):
'''Parse the suite definition file.'''
success = True
if not os.path.exists(self._sdf_name):
logging.critical("Suite definition file {0} not found.".format(self._sdf_name))
success = False
return success
tree = ET.parse(self._sdf_name)
suite_xml = tree.getroot()
self._name = suite_xml.get('name')
# Validate name of suite in XML tag against filename; could be moved to common.py
if not (os.path.basename(self._sdf_name) == 'suite_{}.xml'.format(self._name)):
logging.critical("Invalid suite name {0} in suite definition file {1}.".format(
self._name, self._sdf_name))
success = False
return success
# Check if suite name is too long
if len(self._name) > SUITE_NAME_MAX_CHARS:
logging.critical(f"Suite name {self._name} has more than the allowed {SUITE_NAME_MAX_CHARS} characters")
success = False
return success
# Flattened lists of all schemes and subroutines in SDF
self._all_schemes_called = []
self._all_subroutines_called = []
if make_call_tree:
# Call tree of all schemes in SDF. call_tree is a dictionary, with keys corresponding to each group in a suite, and
# the value associated with each key being an ordered list of the schemes in each group (with duplicates and subcycles)
self._call_tree = {}
# Build hierarchical structure as in SDF
self._groups = []
for group_xml in suite_xml:
subcycles = []
self._call_tree[group_xml.attrib['name']] = []
# Add suite-wide init scheme to group 'init', similar for finalize
if group_xml.tag.lower() == 'init' or group_xml.tag.lower() == 'finalize':
self._all_schemes_called.append(group_xml.text)
self._all_subroutines_called.append(group_xml.text + '_' + group_xml.tag.lower())
schemes = [group_xml.text]
subcycles.append(Subcycle(loop=1, schemes=schemes))
if group_xml.tag.lower() == 'init':
self._groups.append(Group(name=group_xml.tag.lower(), subcycles=subcycles, suite=self._name, init=True))
elif group_xml.tag.lower() == 'finalize':
self._groups.append(Group(name=group_xml.tag.lower(), subcycles=subcycles, suite=self._name, finalize=True))
continue
# Parse subcycles of all regular groups
for subcycle_xml in group_xml:
schemes = []
for scheme_xml in subcycle_xml:
self._all_schemes_called.append(scheme_xml.text)
schemes.append(scheme_xml.text)
loop=int(subcycle_xml.get('loop'))
for ccpp_stage in CCPP_STAGES:
self._all_subroutines_called.append(scheme_xml.text + '_' + CCPP_STAGES[ccpp_stage])
subcycles.append(Subcycle(loop=loop, schemes=schemes))
if make_call_tree:
# Populate call tree from SDF's heirarchical structure, including multiple calls in subcycle loops
for loop in range(0,int(subcycle_xml.get('loop'))):
for scheme_xml in subcycle_xml:
self._call_tree[group_xml.attrib['name']].append(scheme_xml.text)
self._groups.append(Group(name=group_xml.get('name'), subcycles=subcycles, suite=self._name))
# Remove duplicates from list of all subroutines an schemes
self._all_schemes_called = list(set(self._all_schemes_called))
self._all_subroutines_called = list(set(self._all_subroutines_called))
return success
def print_debug(self):
'''Basic debugging output about the suite.'''
print("ALL SUBROUTINES:")
print(self._all_subroutines_called)
print("STRUCTURED:")
print(self._groups)
for group in self._groups:
group.print_debug()
@property
def all_schemes_called(self):
'''Get the list of all schemes.'''
return self._all_schemes_called
@property
def call_tree(self):
'''Get the call tree of the suite (all schemes, in order, with duplicates and loops).'''
return self._call_tree
@property
def all_subroutines_called(self):
'''Get the list of all subroutines.'''
return self._all_subroutines_called
@property
def module(self):
'''Get the list of the module generated for this suite.'''
return self._module
@property
def subroutines(self):
'''Get the list of all subroutines generated for this suite.'''
return self._subroutines
@property
def caps(self):
'''Get the list of all caps.'''
return self._caps
@property
def groups(self):
'''Get the list of groups in this suite.'''
return self._groups
@property
def parents(self):
'''Get the parent variables for the suite.'''
return self._parents
@parents.setter
def parents(self, value):
self._parents = value
@property
def arguments(self):
'''Get the argument list for the suite.'''
return self._arguments
@arguments.setter
def arguments(self, value):
self._arguments = value
def write(self, metadata_request, metadata_define, arguments, debug):
"""Create caps for all groups in the suite and for the entire suite
(calling the group caps one after another). Add additional code for
debugging if debug flag is True."""
# Set name of module and filename of cap
self._module = 'ccpp_{suite_name}_cap'.format(suite_name=self._name)
self.filename = '{module_name}.F90'.format(module_name=self._module)
# Init
self._subroutines = []
# Write group caps and generate module use statements; combine the argument lists
# and variable definitions for all groups into a suite argument list. This may
# require adjusting the intent of the variables.
module_use = ''
for group in self._groups:
group.write(metadata_request, metadata_define, arguments, debug)
for subroutine in group.subroutines:
module_use += ' use {m}, only: {s}\n'.format(m=group.module, s=subroutine)
for ccpp_stage in CCPP_STAGES.keys():
for parent_standard_name in group.parents[ccpp_stage].keys():
if parent_standard_name in self.parents[ccpp_stage]:
if self.parents[ccpp_stage][parent_standard_name].intent == 'in' and \
not group.parents[ccpp_stage][parent_standard_name].intent == 'in':
self.parents[ccpp_stage][parent_standard_name].intent = 'inout'
elif self.parents[ccpp_stage][parent_standard_name].intent == 'out' and \
not group.parents[ccpp_stage][parent_standard_name].intent == 'out':
self.parents[ccpp_stage][parent_standard_name].intent = 'inout'
else:
self.parents[ccpp_stage][parent_standard_name] = copy.deepcopy(group.parents[ccpp_stage][parent_standard_name])
subs = ''
for ccpp_stage in CCPP_STAGES.keys():
# Create a wrapped argument list for calling the suite,
# get module use statements and variable definitions
(self.arguments[ccpp_stage], sub_module_use, sub_var_defs) = \
create_arguments_module_use_var_defs(self.parents[ccpp_stage], metadata_define)
argument_list_suite = create_argument_list_wrapped(self.arguments[ccpp_stage])
body = ''
for group in self._groups:
# Groups 'init'/'finalize' are only run in stages 'init'/'finalize'
if (group.init and not ccpp_stage == 'init') or \
(group.finalize and not ccpp_stage == 'finalize'):
continue
# Create a wrapped argument list for calling the group
(arguments_group, dummy, dummy) = create_arguments_module_use_var_defs(group.parents[ccpp_stage], metadata_define)
argument_list_group = create_argument_list_wrapped_explicit(arguments_group)
# Write to body that calls the groups for this stage
body += '''
ierr = {suite_name}_{group_name}_{stage}_cap({arguments})
if (ierr/=0) return
'''.format(suite_name=self._name, group_name=group.name, stage=CCPP_STAGES[ccpp_stage], arguments=argument_list_group)
# Add name of subroutine in the suite cap to list of subroutine names
subroutine = '{name}_{stage}_cap'.format(name=self._name, stage=CCPP_STAGES[ccpp_stage])
self._subroutines.append(subroutine)
# Add subroutine to output
subs += Suite.sub.format(subroutine=subroutine,
arguments=argument_list_suite,
module_use='\n '.join(sub_module_use),
var_defs='\n '.join(sub_var_defs),
body=body)
# Write cap to stdout or file
if (self.filename is not sys.stdout):
filepath = os.path.split(self.filename)[0]
if filepath and not os.path.isdir(filepath):
os.makedirs(filepath)
# If the file exists, write to temporary file first and compare them:
# - if identical, delete the temporary file and keep the existing one
# and set the suite cap update flag to false
# - if different, replace existing file with temporary file and set
# the suite cap update flag to true (default value)
# - however, if any of the group caps has changed, rewrite the suite
# cap as well and set the suite cap update flag to true
# If the file does not exist, write the cap an set the flag to true
if os.path.isfile(self.filename) and \
not any([group.update_cap for group in self._groups]):
write_to_test_file = True
test_filename = self.filename + '.test'
f = open(test_filename, 'w')
else:
write_to_test_file = False
f = open(self.filename, 'w')
else:
f = sys.stdout
f.write(Suite.header.format(module=self._module,
module_use=module_use,
subroutines=', &\n '.join(self._subroutines)))
f.write(subs)
f.write(Suite.footer.format(module=self._module))
if (f is not sys.stdout):
f.close()
# See comment above on updating the suite cap or not
if write_to_test_file:
if filecmp.cmp(self.filename, test_filename):
# Files are equal, delete the test cap
# and set update flag to False
os.remove(test_filename)
self.update_cap = False
else:
# Files are different, replace existing cap
# with test cap and set flag to True
# Python 3 only: os.replace(test_filename, self.filename)
os.remove(self.filename)
os.rename(test_filename, self.filename)
self.update_cap = True
else:
self.update_cap = True
# Create list of all caps generated (for groups and suite)
self._caps = [ self.filename ]
for group in self._groups:
self._caps.append(group.filename)
###############################################################################
class Group(object):
header='''
!
! This work (Common Community Physics Package), identified by NOAA, NCAR,
! CU/CIRES, is free of known copyright restrictions and is placed in the
! public domain.
!
! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
! THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
! IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
! CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
!
!>
!! @brief Auto-generated cap module for the CCPP {group} group
!!
!
module {module}
{module_use}
implicit none
private
public :: {subroutines}
logical, dimension({num_instances}), save :: initialized = .false.
contains
'''
sub = '''
function {subroutine}({argument_list}) result(ierr)
{module_use}
implicit none
! Error handling
integer :: ierr
{var_defs}
ierr = 0
{initialized_test_block}
{body}
{initialized_set_block}
end function {subroutine}
'''
footer = '''
end module {module}
'''
initialized_test_blocks = {
'init' : '''
if (initialized({ccpp_var_name}%ccpp_instance)) return
''',
'timestep_init' : '''
if (.not.initialized({ccpp_var_name}%ccpp_instance)) then
write({target_name_msg},'(*(a))') '{name}_timestep_init called before {name}_init'
{target_name_flag} = 1
return
end if
''',
'run' : '''
if (.not.initialized({ccpp_var_name}%ccpp_instance)) then
write({target_name_msg},'(*(a))') '{name}_run called before {name}_init'
{target_name_flag} = 1
return
end if
''',
'timestep_finalize' : '''
if (.not.initialized({ccpp_var_name}%ccpp_instance)) then
write({target_name_msg},'(*(a))') '{name}_timestep_finalize called before {name}_init'
{target_name_flag} = 1
return
end if
''',
'finalize' : '''
if (.not.initialized({ccpp_var_name}%ccpp_instance)) return
''',
}
initialized_set_blocks = {
'init' : '''
initialized({ccpp_var_name}%ccpp_instance) = .true.
''',
'timestep_init' : '',
'run' : '',
'timestep_finalize' : '',
'finalize' : '''
initialized = .false.
''',
}
def __init__(self, **kwargs):
self._name = ''
self._suite = None
self._filename = sys.stdout
self._init = False
self._finalize = False
self._module = None
self._subroutines = None
self._pset = None
self._parents = { ccpp_stage : collections.OrderedDict() for ccpp_stage in CCPP_STAGES }
self._arguments = { ccpp_stage : [] for ccpp_stage in CCPP_STAGES }
self._update_cap = True
for key, value in kwargs.items():
setattr(self, "_"+key, value)
def write(self, metadata_request, metadata_define, arguments, debug):
"""Create caps for all stages of this group. Add additional code for
debugging if debug flag is True."""
# Create an inverse lookup table of local variable names defined (by the host model) and standard names
standard_name_by_local_name_define = collections.OrderedDict()
for standard_name in metadata_define.keys():
standard_name_by_local_name_define[metadata_define[standard_name][0].local_name] = standard_name
# First get target names of standard CCPP variables for subcycling and error handling
ccpp_loop_counter_target_name = metadata_request[CCPP_LOOP_COUNTER][0].target
ccpp_loop_extent_target_name = metadata_request[CCPP_LOOP_EXTENT][0].target
ccpp_error_code_target_name = metadata_request[CCPP_ERROR_CODE_VARIABLE][0].target