File: cs_case.py

package info (click to toggle)
code-saturne 7.0.2%2Brepack-1~exp1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 62,868 kB
  • sloc: ansic: 395,271; f90: 100,755; python: 86,746; cpp: 6,227; makefile: 4,247; xml: 2,389; sh: 1,091; javascript: 69
file content (2064 lines) | stat: -rw-r--r-- 68,245 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#-------------------------------------------------------------------------------

# This file is part of Code_Saturne, a general-purpose CFD tool.
#
# Copyright (C) 1998-2021 EDF S.A.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
# Street, Fifth Floor, Boston, MA 02110-1301, USA.

#-------------------------------------------------------------------------------

try:
    import ConfigParser  # Python2
    configparser = ConfigParser
except Exception:
    import configparser  # Python3
import datetime
import os
import os.path
import platform
import sys
import stat

from code_saturne import cs_exec_environment, cs_run_conf

from code_saturne.cs_case_domain import *

homard_prefix = None

#===============================================================================
# Utility functions
#===============================================================================

def check_exec_dir_stamp(d):

    """
    Return path to execution directory if present in a given directory.
    Otherwise, return given directory path
    """

    retval = d

    p = os.path.join(d, 'run_status.exec_dir')

    if os.path.isfile(p):
        f = open(p, 'r')
        l = f.readlines()
        f.close()
        d = l[0].rstrip()
        if os.path.isdir(d):
            retval = d

    return retval

#-------------------------------------------------------------------------------
# Check if an execution directory is inside a standard case structure
#
# This may not be the case if a separate staging directory or destination
# directory has been specified.
#-------------------------------------------------------------------------------

def is_exec_dir_in_case(case_dir, exec_dir):
    """
    Check if an execution directory is inside a standard case structure.
    """

    in_case = False

    if case_dir and exec_dir:
        r_case_dir = os.path.normpath(case_dir)
        r_exec_dir = os.path.normpath(exec_dir)
        if not os.path.isabs(r_case_dir):
            r_case_dir = os.path.abspath(r_case_dir)
        if not os.path.isabs(r_exec_dir):
            r_exec_dir = os.path.abspath(r_exec_dir)
        if r_exec_dir.find(r_case_dir) == 0:
            exec_parent_dir = os.path.split(r_exec_dir)[0]
            if os.path.basename(exec_parent_dir) in ('RESU', 'RESU_COUPLING'):
                if os.path.split(exec_parent_dir)[0] == case_dir:
                    in_case = True

    return in_case

#-------------------------------------------------------------------------------

def get_case_dir(case=None, param=None, coupling=None, id=None):

    """
    Check and return case path based on partial or sub-path.
    """

    casedir = None
    staging_dir = None
    data = None
    src = None

    if coupling:

        # Multiple domain case

        if param:
            err_str = 'Error: coupling and param options are incompatible.\n'
            raise RunCaseError(err_str)

        coupling = os.path.realpath(coupling)
        if not os.path.isfile(coupling):
            err_str = 'Error: coupling parameters: ' + coupling + '\n' \
                      'not found or not a file.\n'
            raise RunCaseError(err_str)

        if id:
            cwd = os.path.split(coupling)[0]
            if os.path.basename(cwd) == str(id):
                d = os.path.split(cwd)[0]
                if os.path.basename(d) == 'RESU_COUPLING':
                    staging_dir = cwd

        if case:
            casedir = os.path.realpath(case)
        else:
            casedir = os.path.split(coupling)[0]
            if staging_dir:
                casedir = os.path.split(os.path.split(staging_dir)[0])[0]

    else:

        cwd = os.getcwd()

        # Single domain case

        if param:
            param = os.path.basename(param)
            if param != param:
                datadir = os.path.split(os.path.realpath(param))[0]
                (casedir, data) = os.path.split(datadir)
                if data != 'DATA': # inconsistent paramaters location.
                    casedir = None

        if id:
            if os.path.basename(cwd) == str(id):
                d = os.path.split(cwd)[0]
                if os.path.basename(d) == 'RESU':
                    staging_dir = cwd

        if case:
            if os.path.isabs(case):
                casedir = os.path.realpath(case)
            else:
                casedir = os.path.realpath(os.path.join(cwd, case))
            data = os.path.join(casedir, 'DATA')
            src = os.path.join(casedir, 'SRC')
        else:
            casedir = cwd
            while os.path.basename(casedir):
                data = os.path.join(casedir, 'DATA')
                src = os.path.join(casedir, 'SRC')
                cfg = os.path.join(data, 'run.cfg')
                if (os.path.isdir(data) and os.path.isdir(src)) \
                   or os.path.isfile(cfg):
                    break
                casedir = os.path.split(casedir)[0]

        if not (os.path.isdir(data) and os.path.isdir(src)):
            casedir = None

    # Return casedir or None

    return casedir, staging_dir


#===============================================================================
# Main class
#===============================================================================

class case:
    """Base class from which classes handling running case should inherit."""

    #---------------------------------------------------------------------------

    def __init__(self,
                 package,                     # main package
                 package_compute = None,      # package for compute environment
                 case_dir = None,
                 dest_dir = None,
                 staging_dir = None,
                 domains = None,
                 syr_domains = None,
                 py_domains = None):

        # Package specific information

        self.package = package

        if package_compute:
            self.package_compute = package_compute
        else:
            self.package_compute = self.package

        # Determine caller script path (which may contain batch directives)

        self.parent_script = cs_exec_environment.get_parent_process_path()

        # Set environment modules if present

        cs_exec_environment.set_modules(self.package_compute)
        cs_exec_environment.source_rcfile(self.package_compute)

        # Re-clean os.environment as the above calls may have indirectly
        # restored some unwanted variables (such as lmod macros).

        cs_exec_environment.clean_os_environ_for_shell()

        # Ensure we have tuples or lists to simplify later tests

        if type(domains) == list:
            self.domains = domains
        elif type(domains) == tuple:
            self.domains = list(domains)
        else:
            self.domains = [domains]

        if syr_domains == None:
            self.syr_domains = []
        elif type(syr_domains) == tuple :
            self.syr_domains = list(syr_domains)
        elif type(syr_domains) == list:
            self.syr_domains = syr_domains
        else:
            self.syr_domains = [syr_domains]

        if py_domains == None:
            self.py_domains = []
        elif type(py_domains) == tuple:
            self.py_domains = list(py_domains)
        elif type(py_domains) == list:
            self.py_domains = py_domains
        else:
            self.py_domains = [py_domains]

        # Check names in case of multiple domains (coupled by MPI)

        n_domains = len(self.domains) + len(self.syr_domains) + len(self.py_domains)

        if n_domains > 1:
            err_str = 'In case of multiple domains (i.e. code coupling), ' \
                + 'each domain must have a name.\n'
            for d in (self.domains + self.syr_domains + self.py_domains):
                if d.name == None:
                    raise RunCaseError(err_str)

        # Names, directories, and files in case structure:
        # associate case domains and set case directory

        self.case_dir = case_dir
        self.dest_dir = dest_dir
        self.__define_dest_dir__()

        self.result_dir = None

        # Determine parent (or coupling group) study directory

        if (os.path.isdir(os.path.join(case_dir, 'DATA')) and n_domains == 1):
            # Simple domain case from standard directory structure
            (self.study_dir, self.name) = os.path.split(case_dir)
            if len(self.domains) == 1:
                self.domains[0].name = None
            elif len(self.syr_domains) == 1:
                self.syr_domains[0].name = None
            elif len(self.py_domains) == 1:
                self.py_domains[0].name = None

        else:
            # Coupling or single domain run from coupling script
            self.study_dir = case_dir
            self.name = os.path.split(case_dir)[1]

        if staging_dir:
            staging_dir = check_exec_dir_stamp(staging_dir)

        n_nc_solver = 0

        for d in (self.domains + self.syr_domains + self.py_domains):
            d.set_case_dir(self.case_dir, staging_dir)
            try:
                solver_name = os.path.basename(d.solver_path)
                if solver_name == 'nc_solver':
                    n_nc_solver += 1
            except Exception:
                pass

        self.module_name = 'code_saturne'
        if n_nc_solver == len(self.domains):
            self.module_name = 'neptune_cfd'

        # Working directory

        self.exec_dir = None
        self.exec_prefix = None

        self.exec_solver = True

        n_exec_solver = 0
        for d in ( self.domains + self.syr_domains \
                 + self.py_domains):
            if d.exec_solver:
                n_exec_solver += 1

        if n_exec_solver == 0:
            self.exec_solver = False
        elif n_exec_solver <   len(self.domains) + len(self.syr_domains) \
                             + len(self.py_domains):
            err_str = 'In case of multiple domains (i.e. code coupling), ' \
                + 'all or no domains must execute their solver.\n'
            raise RunCaseError(err_str)

        # Script hooks

        self.run_prologue = None
        self.run_epilogue = None
        self.compute_prologue = None
        self.compute_epilogue = None

        # Date or other name

        self.run_id = None

        # Time limit

        self.time_limit = None

        # Error reporting
        self.error = ''
        self.error_long = ''

    #---------------------------------------------------------------------------

    def __define_dest_dir__(self):

        if self.dest_dir != None:
            if not os.path.isabs(self.dest_dir):
                dest_dir = os.path.join(os.path.split(self.case_dir)[0],
                                        self.dest_dir)
                self.dest_dir = os.path.abspath(dest_dir)

    #---------------------------------------------------------------------------

    def print_procs_distribution(self):

        """
        Print info on the processor distribution.
        """

        # Print process info

        name = self.module_name

        for d in self.domains:
            solver_name = os.path.basename(d.solver_path)
            if solver_name == 'cs_solver':
                name = 'code_saturne'
            elif solver_name == 'nc_solver':
                name = 'neptune_cfd'

            if len(self.domains) == 1:
                if d.n_procs > 1:
                    msg = ' Parallel ' + name + ' on ' \
                          + str(d.n_procs) + ' processes.\n'
                else:
                    msg = ' Single processor ' + name + ' simulation.\n'
                sys.stdout.write(msg)
            else:
                msg = ' ' + name + ' domain ' + d.name + ' on ' \
                    + str(d.n_procs) + ' process(es).\n'
                sys.stdout.write(msg)

        if len(self.syr_domains) == 1:
            if self.syr_domains[0].n_procs > 1:
                msg = ' Parallel SYRTHES on ' \
                    + str(self.syr_domains[0].n_procs) + ' processes.\n'
            else:
                msg = ' Single processor SYRTHES simulation.\n'
            sys.stdout.write(msg)
        else:
            for d in self.syr_domains:
                msg = ' SYRTHES domain ' + d.name + ' on ' \
                    + str(d.n_procs) + ' processes.\n'
                sys.stdout.write(msg)

        if len(self.py_domains) == 1:
            if self.py_domains[0].n_procs > 1:
                msg = ' Parallel Python script on ' \
                    + str(self.py_domains[0].n_procs) + ' processes.\n'
            else:
                msg = ' Single processor Python script simulation.\n'
            sys.stdout.write(msg)
        else:
            for d in self.py_domains:
                msg = ' Python script domain ' + d.name + ' on ' \
                    + str(d.n_procs) + ' processes.\n'
                sys.stdout(msg)

        sys.stdout.write('\n')

    #---------------------------------------------------------------------------

    def distribute_procs(self, n_procs=None):

        """
        Distribute number of processors to domains,
        and returns the total number of associated processes.
        """

        # Initial count

        np_list = []

        for d in (self.domains + self.syr_domains + self.py_domains):
            np_list.append(d.get_n_procs())

        n_procs_tot = 0
        n_procs_min = 0
        for np in np_list:
            n_procs_tot += np[0]
            n_procs_min += np[1]

        # If no process count is given or everything fits:

        if n_procs == None or n_procs == n_procs_tot:
            return n_procs_tot

        # If process count is given and not sufficient, abort.

        elif n_procs < n_procs_min:
            err_str = ' Error:\n' \
                '   The current calculation scheme requires at least ' \
                + str(n_procs_min) + ' processes,\n' \
                + '   while the execution environment provides only ' \
                + str(n_procs) + '.\n' \
                + '   You may either allocate more processes or try to\n' \
                + '   oversubscribe by changing the number of processes\n' \
                + '   in the run.cfg configuration file.'
            raise RunCaseError(err_str)

        # Otherwise, rebalance process counts.

        n_passes = 0
        n_fixed_procs = 0
        n_fixed_apps = 0

        while (    n_procs_tot != n_procs and n_fixed_apps != len(np_list)
               and n_passes < 5):

            mult = (n_procs - n_fixed_procs) *1.0 \
                // (n_procs_tot - n_fixed_procs)

            n_procs_tot = 0

            for np in np_list:
                if np[2] == None:
                    np[2] = n_procs
                if np[2] != 0: # marked as fixed here
                    np[0] = int(np[0]*mult)
                    if np[0] < np[1]:
                        np[0] = np[1]
                        np[2] = 0 # used as marker here
                        n_fixed_procs += np[0]
                        n_fixed_apps += 1
                    elif np[0] > np[2]:
                        np[0] = np[2]
                        np[2] = 0 # used as marker here
                        n_fixed_procs += np[0]
                        n_fixed_apps += 1
                n_procs_tot += np[0]

            n_passes += 1

        # Minor adjustments may help in case of rounding

        n_passes = 0

        while (    n_procs_tot != n_procs and n_fixed_apps != len(np_list)
               and n_passes < 5):

            delta = int(round(  (n_procs_tot - n_procs)*1.0
                              // (len(np_list) - n_fixed_apps)))

            if delta == 0:
                if n_procs_tot < n_procs:
                    delta = 1
                else:
                    delta = -1

            for np in np_list:
                if np[2] != 0: # marked as fixed here
                    n_procs_prev = np[0]
                    np[0] -= delta
                    if np[0] < np[1]:
                        np[0] = np[1]
                        np[2] = 0 # used as marker here
                        n_fixed_procs += np[0]
                        n_fixed_apps += 1
                    elif np[0] > np[2]:
                        np[0] = np[2]
                        np[2] = 0 # used as marker here
                        n_fixed_procs += np[0]
                        n_fixed_apps += 1
                    n_procs_tot += (np[0] - n_procs_prev)
                if n_procs_tot == n_procs:
                    break

            n_passes += 1

        # We are now are ready to set return values

        app_id = 0

        for d in (self.domains + self.syr_domains + self.py_domains):
            d.set_n_procs(np_list[app_id][0])
            app_id += 1

        # Warn in case of over or under-subscription

        if n_procs_tot != n_procs:
            msg =  \
                'Warning:\n' \
                + '  total number of processes used (' + str(n_procs_tot) \
                + ') is different from the\n' \
                + '  number provided by the environment. (' + str(n_procs) \
                + ').\n\n'
            sys.stderr.write(msg)

        return n_procs_tot

    #---------------------------------------------------------------------------

    def define_exec_dir(self):
        """
        Define execution directory.
        """

        if self.exec_prefix != None:
            if self.case_dir != self.study_dir:
                study_name = os.path.split(self.study_dir)[1]
                exec_dir_name = study_name + '.' + self.name
            else:
                exec_dir_name = self.name
            exec_dir_name += '.' + self.run_id
            self.exec_dir = os.path.join(self.exec_prefix, exec_dir_name)
        else:
            if not self.result_dir:
                self.define_result_dir()
            self.exec_dir = self.result_dir

    #---------------------------------------------------------------------------

    def set_exec_dir(self, force=False):
        """
        Create execution directory.
        """

        # Define execution directory name

        self.define_exec_dir()

        # Check that directory does not exist.

        if os.path.isdir(self.exec_dir):
            if not force and self.result_dir != self.exec_dir:
                err_str = \
                    '\nWorking directory: ' + self.exec_dir \
                    + ' already exists.\n' \
                    + 'Calculation will not be run.\n'
                raise RunCaseError(err_str)

        else:
            os.makedirs(self.exec_dir)

        # Set execution directory

        for d in (self.domains + self.syr_domains + self.py_domains):
            d.set_exec_dir(self.exec_dir)

    #---------------------------------------------------------------------------

    def define_result_dir(self):

        if self.dest_dir != None:
            base_dir = os.path.join(self.dest_dir,
                                    os.path.basename(self.case_dir))
        else:
            base_dir = self.case_dir

        r = os.path.join(base_dir, 'RESU')

        # Coupled case
        if len(self.domains) + len(self.syr_domains) \
         + len(self.py_domains) > 1:
            r += '_COUPLING'

        if not os.path.isdir(r):
            os.makedirs(r)

        self.result_dir = os.path.join(r, self.run_id)

    #---------------------------------------------------------------------------

    def set_result_dir(self, force=True):

        self.define_result_dir()

        if os.path.isdir(self.result_dir):
            if not force:
                err_str = \
                    '\nResults directory: ' + self.result_dir \
                    + ' already exists.\n' \
                    + 'Calculation will not be run.\n'
                raise RunCaseError(err_str)

        else:
            os.mkdir(self.result_dir)

        for d in (self.domains + self.syr_domains + self.py_domains):
            d.set_result_dir(self.run_id, self.result_dir)

    #---------------------------------------------------------------------------

    def summary_init(self, exec_env):

        """
        Build summary start.
        """

        s_path = os.path.join(self.exec_dir, 'summary')
        s = open(s_path, 'w')

        r = exec_env.resources

        date = (datetime.datetime.now()).strftime("%A %B %d %H:%M:%S CEST %Y")
        t_uname = platform.uname()
        s_uname = ''
        for t in t_uname:
            s_uname = s_uname + t + ' '
        n_procs = r.n_procs
        if n_procs == None:
            n_procs = 1

        dhline = '========================================================\n'
        hline =  '  ----------------------------------------------------\n'

        s.write(dhline)
        s.write('Start time       : ' + date + '\n')
        s.write(dhline)
        cmd = sys.argv[0]
        for arg in sys.argv[1:]:
            cmd += ' ' + arg
        s.write('  Command        : ' + cmd + '\n')
        s.write(dhline)
        s.write('  Package path   : ' + self.package.get_dir('exec_prefix') + '\n')
        s.write(hline)
        if homard_prefix != None:
            s.write('  HOMARD          : ' + homard_prefix + '\n')
            s.write(hline)
        s.write('  MPI path       : ' + self.package_compute.config.libs['mpi'].bindir + '\n')
        if len(self.package_compute.config.libs['mpi'].variant) > 0:
            s.write('  MPI type       : ' + self.package_compute.config.libs['mpi'].variant + '\n')
        s.write(hline)
        s.write('  User           : ' + exec_env.user  + '\n')
        s.write(hline)
        s.write('  Machine        : ' + s_uname  + '\n')
        s.write('  N Procs        : ' + str(n_procs)  + '\n')
        if r.manager == None and r.hosts_list != None:
            s.write('  Hosts          :')
            for p in r.hosts_list:
                s.write(' ' + p)
            s.write('\n')
        s.write(hline)

        if len(self.domains) + len(self.syr_domains) + len(self.py_domains)  > 1:
            s.write('  Exec. dir.     : ' + self.exec_dir + '\n')
            s.write(hline)

        s.write('  Environment variables\n')
        ek = list(os.environ.keys())
        ek.sort()
        for k in ek:
            s.write('    ' + k + '=' + os.environ[k] + '\n')
        s.write(hline)

        for d in (self.domains + self.syr_domains + self.py_domains):
            d.summary_info(s)
            s.write(hline)

        s.close()

    #---------------------------------------------------------------------------

    def summary_finalize(self):

        """
        Output summary body.
        """

        date = (datetime.datetime.now()).strftime("%A %B %d %H:%M:%S CEST %Y")

        dhline = '========================================================\n'
        hline =  '  ----------------------------------------------------\n'

        s_path = os.path.join(self.exec_dir, 'summary')
        s = open(s_path, 'a')

        if self.error:
            s.write('  ' + self.error + ' failed\n')

        s.write(dhline)
        s.write('Finish time      : ' + date + '\n')
        s.write(dhline)

        s.close()

    #---------------------------------------------------------------------------

    def copy_log(self, name):
        """
        Retrieve single log file from the execution directory
        """

        if self.result_dir == self.exec_dir:
            return

        src = os.path.join(self.exec_dir, name)
        dest = os.path.join(self.result_dir, name)

        if os.path.isfile(src):
            shutil.copy2(src, dest)
            if self.error == '':
                os.remove(src)

    #---------------------------------------------------------------------------

    def copy_script(self):
        """
        Retrieve script (if present) from the execution directory
        """

        src = sys.argv[0]

        if os.path.basename(src) == self.package.name:
            src = self.parent_script

        if not src:
            src = self.package.name

        # Copy single file

        dest = os.path.join(self.result_dir, os.path.basename(src))
        if os.path.isfile(src) and os.path.abspath(src) != os.path.abspath(dest):
            shutil.copy2(src, dest)

    #---------------------------------------------------------------------------

    def copy_top_run_conf(self):
        """
        Retrieve top-level run.cfg (if present) from the top directory
        """

        n = "run.cfg"

        src = os.path.join(self.case_dir, n)
        dest = os.path.join(self.result_dir, n)

        if os.path.isfile(src) and src != dest:
            shutil.copy2(src, dest)

    #---------------------------------------------------------------------------

    def solver_script_path(self):
        """
        Determine name of solver script file.
        """
        return os.path.join(self.exec_dir, self.package.runsolver)

    #---------------------------------------------------------------------------

    def generate_solver_mpmd_mpiexec(self, n_procs, mpi_env):
        """
        Generate MPMD mpiexec command.
        """

        cmd = ''

        app_id = 0

        for d in self.syr_domains:
            s_args = d.solver_command()
            if len(cmd) > 0:
                cmd += ' : '
            cmd += '-n ' + str(d.n_procs) \
                + ' -wdir ' + os.path.basename(s_args[0]) \
                + ' ' + s_args[1] + s_args[2]
            app_id += 1

        for d in self.domains:
            s_args = d.solver_command(app_id=app_id)
            if len(cmd) > 0:
                cmd += ' : '
            cmd += '-n ' + str(d.n_procs) \
                + ' -wdir ' + os.path.basename(s_args[0]) \
                + ' ' + s_args[1] + s_args[2]
            app_id += 1

        for d in self.py_domains:
            s_args = d.solver_command()
            if len(cmd) > 0:
                cmd += ' : '
            cmd += '-n ' + str(d.n_procs) \
                + ' -wdir ' + os.path.basename(s_args[0]) \
                + ' ' + s_args[1] + s_args[2]
            app_id += 1

        return cmd

    #---------------------------------------------------------------------------

    def generate_solver_mpmd_configfile(self, n_procs, mpi_env):
        """
        Generate MPMD mpiexec config file.
        """

        e_path = os.path.join(self.exec_dir, 'mpmd_configfile')
        e = open(e_path, 'w')

        app_id = 0

        for d in (self.syr_domains + self.domains + self.py_domains):
            s_args = d.solver_command()
            cmd = '-n ' + str(d.n_procs) \
                + ' -wdir ' + os.path.basename(s_args[0]) \
                + ' ' + s_args[1] + s_args[2] + '\n'
            e.write(cmd)
            app_id += 1

        e.close()

        return e_path

    #---------------------------------------------------------------------------

    def generate_solver_mpmd_configfile_srun(self, n_procs, mpi_env):
        """
        Generate MPMD mpiexec config file for SLURM's srun.
        """

        e_path = os.path.join(self.exec_dir, 'mpmd_configfile')
        e = open(e_path, 'w')

        e.write('# srun multiple program configuration file\n#\n')
        e.write('# > srun -n ' + str(n_procs) \
                + ' --multi-prog mpmd_configfile\n#\n')

        rank_id = 0

        for d in (self.syr_domains + self.domains):
            s_args = d.solver_command()
            if s_args[1][0:2] == './':
                s_path = os.path.join(s_args[0], s_args[1])
                s_path = './' + os.path.relpath(s_path, self.exec_dir)
            else:
                s_path = s_args[1]
            cmd = '%d-%d\t' % (rank_id, rank_id + d.n_procs - 1) \
                   + s_path + s_args[2] \
                   + ' -wdir ' + os.path.basename(s_args[0]) + '\n'
            e.write(cmd)
            rank_id += d.n_procs

        for d in self.py_domains:
            s_args = d.solver_command()
            _pypath, _pyscript = s_args[1].split(" ")
            _rundir = os.path.basename(s_args[0])

            cmd  = '%d-%d\t' % (rank_id, rank_id + d.n_procs - 1)
            cmd += '%s %s/%s\t' % (_pypath, _rundir, _pyscript)
            cmd += s_args[2]
            cmd += ' -wdir %s' % _rundir

            e.write(cmd)
            rank_id += d.n_procs

        e.close()

        return e_path

    #---------------------------------------------------------------------------

    def generate_solver_mpmd_script(self, n_procs, mpi_env):
        """
        Generate MPMD dispatch file.
        """

        e_path = os.path.join(self.exec_dir, 'mpmd_exec.sh')
        e = open(e_path, 'w')

        user_shell = cs_exec_environment.get_shell_type()

        e.write('#!' + user_shell + '\n\n')
        e.write('# Make sure to transmit possible additional '
                + 'arguments assigned by mpirun to\n'
                + '# the executable with some MPI-1 implementations:\n'
                + '# we use $@ to forward arguments passed to this script'
                + ' to the executable files.\n\n')

        e.write('MPI_RANK=`'
                + self.package.get_pkgdatadir_script('runcase_mpi_rank')
                + ' $@`\n')

        app_id = 0
        nr = 0
        test_pf = 'if [ $MPI_RANK -lt '
        test_sf = ' ] ; then\n'

        for d in self.syr_domains:
            nr += d.n_procs
            e.write(test_pf + str(nr) + test_sf)
            s_args = d.solver_command()
            e.write('  cd ' + s_args[0] + '\n')
            e.write('  ' + s_args[1] + s_args[2] + ' $@\n')
            if app_id == 0:
                test_pf = 'el' + test_pf
            app_id += 1

        for d in self.domains:
            nr += d.n_procs
            e.write(test_pf + str(nr) + test_sf)
            s_args = d.solver_command(app_id=app_id)
            e.write('  cd ' + s_args[0] + '\n')
            e.write('  ' + s_args[1] + s_args[2] + ' $@\n')
            if app_id == 0:
                test_pf = 'el' + test_pf
            app_id += 1

        for d in self.py_domains:
            nr += d.n_procs
            e.write(test_pf + str(nr) + test_sf)
            s_args = d.solver_command()
            e.write('  cd ' + s_args[0] + '\n')
            e.write('  ' + s_args[1] + s_args[2] + ' $@\n')
            if app_id == 0:
                test_pf = 'el' + test_pf
            app_id += 1

        e.write('fi\n'
                + 'CS_RET=$?\n'
                + 'exit $CS_RET\n')

        e.close()

        oldmode = (os.stat(e_path)).st_mode
        newmode = oldmode | (stat.S_IXUSR)
        os.chmod(e_path, newmode)

        return e_path

    #---------------------------------------------------------------------------

    def solver_script_body(self, n_procs, mpi_env, s):
        """
        Write commands to solver script.
        """

        # Determine if an MPMD syntax (mpiexec variant) will be used

        mpiexec_mpmd = False
        if len(self.domains) + len(self.syr_domains) + len(self.py_domains) > 1:
            if mpi_env.mpmd & cs_exec_environment.MPI_MPMD_mpiexec:
                mpiexec_mpmd = True
            elif mpi_env.mpmd & cs_exec_environment.MPI_MPMD_configfile:
                mpiexec_mpmd = True

        # Start assembling command

        mpi_cmd = ''
        mpi_cmd_exe = ''
        mpi_cmd_args = ''

        if mpi_env.mpiexec != None:
            if (n_procs > 1 or os.path.basename(mpi_env.mpiexec)[:4] == 'srun'):
                mpi_cmd = mpi_env.mpiexec

        if mpi_cmd:
            if mpi_env.mpiexec_opts != None:
                mpi_cmd += ' ' + mpi_env.mpiexec_opts
            if mpiexec_mpmd == False:
                if mpi_env.mpiexec_n != None:
                    mpi_cmd += mpi_env.mpiexec_n + str(n_procs)
                if mpi_env.mpiexec_n_per_node != None:
                    mpi_cmd += mpi_env.mpiexec_n_per_node
                if mpi_env.mpiexec_separator != None:
                    mpi_cmd += ' ' + mpi_env.mpiexec_separator
                mpi_cmd += ' '
                if mpi_env.mpiexec_exe != None:
                    mpi_cmd += mpi_env.mpiexec_exe + ' '
                if mpi_env.mpiexec_args != None:
                    mpi_cmd_args = mpi_env.mpiexec_args + ' '
            else:
                mpi_cmd += ' '

        # Case with only one cs_solver instance possibly under MPI

        if len(self.domains) == 1 and len(self.syr_domains) == 0 \
           and len(self.py_domains) == 0:

            s_args = self.domains[0].solver_command()

            cs_exec_environment.write_script_comment(s, 'Run solver.\n')
            s.write(mpi_cmd + s_args[1] + mpi_cmd_args + s_args[2])
            s.write(' ' + cs_exec_environment.get_script_positional_args() +
                    '\n')

        # General case

        else:

            if mpi_env.mpmd & cs_exec_environment.MPI_MPMD_mpiexec:

                if mpi_env.mpiexec_separator != None:
                    mpi_cmd += mpi_env.mpiexec_separator + ' '

                e_path = self.generate_solver_mpmd_mpiexec(n_procs,
                                                           mpi_env)

            elif mpi_env.mpmd & cs_exec_environment.MPI_MPMD_configfile:

                if mpi_env.mpiexec == 'srun':
                    e_path = self.generate_solver_mpmd_configfile_srun(n_procs,
                                                                       mpi_env)
                    mpi_cmd += '--multi-prog ' + e_path

                else:
                    e_path = self.generate_solver_mpmd_configfile(n_procs,
                                                                  mpi_env)
                    mpi_cmd += '-configfile ' + e_path

                e_path = ''

            elif mpi_env.mpmd & cs_exec_environment.MPI_MPMD_script:

                if mpi_env.mpiexec_separator != None:
                    mpi_cmd += mpi_env.mpiexec_separator + ' '

                e_path = self.generate_solver_mpmd_script(n_procs, mpi_env)

            else:
                raise RunCaseError(' No allowed MPI MPMD mode defined.\n')

            s.write(mpi_cmd + e_path + '\n')

    #---------------------------------------------------------------------------

    def generate_solver_script(self, exec_env):
        """
        Generate localexec file.
        """

        # Initialize simple solver command script

        s_path = self.solver_script_path()

        s = open(s_path, 'w')

        cs_exec_environment.write_shell_shebang(s)

        # If n_procs not already given by environment, determine it

        n_procs = exec_env.resources.n_procs
        mpi_env = exec_env.mpi_env

        if n_procs == None:
            n_procs = 0
            for d in (self.syr_domains + self.py_domains):
                n_procs += d.n_procs

        # Set PATH for Windows DLL search PATH

        if sys.platform.startswith('win'):
            cs_exec_environment.write_script_comment(s,
                'Ensure the correct command is found:\n')
            cs_exec_environment.write_prepend_path(s,
                                                   'PATH',
                                                   self.package.get_dir("bindir"))
            cs_exec_environment.write_prepend_path(s,
                                                   'PATH',
                                                   self.package.get_dir("libdir"))
            s.write('set CS_ROOT_DIR=' + self.package.get_dir("exec_prefix") + '\n')

        # Add MPI directories to PATH if in nonstandard path

        cs_exec_environment.write_script_comment(s, \
            'Export paths here if necessary or recommended.\n')
        mpi_bindir = self.package_compute.config.libs['mpi'].bindir
        if len(mpi_bindir) > 0:
            cs_exec_environment.write_prepend_path(s, 'PATH', mpi_bindir)
        mpi_libdir = self.package_compute.config.libs['mpi'].libdir
        if len(mpi_libdir) > 0:
            cs_exec_environment.write_prepend_path(s,
                                                   'LD_LIBRARY_PATH',
                                                   mpi_libdir)
        s.write('\n')

        # Handle cathare coupling
        wrote_cathare_path = False
        if self.domains:
            for d in self.domains:
                if hasattr(d, "cathare_case_file"):
                    if not wrote_cathare_path:
                        cs_exec_environment.write_script_comment(s, \
                            'Export paths necessary for CATHARE coupling.\n')
                        config = configparser.ConfigParser()
                        config.read(self.package.get_configfiles())
                        cathare_path = config.get('install', 'cathare')
                        for p in ['lib', 'ICoCo/lib']:
                            lp = os.path.join(cathare_path, p)
                            cs_exec_environment.write_prepend_path( \
                                    s, "LD_LIBRARY_PATH", lp)

                        wrote_cathare_path = True
                        s.write('\n')

        # Handle python coupling
        if self.py_domains:
            cs_exec_environment.write_script_comment(s, \
                'Export paths necessary for python coupling.\n')
            pydir = self.package_compute.get_dir("pythondir")
            cs_exec_environment.write_prepend_path(s, "PYTHONPATH", pydir)
            # This export is necessary fr PyPLE to work correctly
            libdir = self.package_compute.get_dir("libdir")
            cs_exec_environment.write_prepend_path(s,
                                                   "LD_LIBRARY_PATH",
                                                   libdir)
            s.write('\n')

        # Handle environment modules if used

        if self.package_compute.config.env_modules != "no":
            cs_exec_environment.write_script_comment(s, \
               'Load environment if this script is run directly.\n')
            s.write('if test "$CS_ENVIRONMENT_SET" != "true" ; then\n')
            if self.package_compute.config.env_modules != "no":
                s.write('  module purge\n')
                for m in self.package_compute.config.env_modules.strip().split():
                    s.write('  module load ' + m + '\n')
            s.write('fi\n\n')

        # Add additional library search paths in case DT_RUNPATH
        # is used instead of DT_RPATH in ELF library

        add_lib_dirs = get_ld_library_path_additions(self.package)
        while add_lib_dirs:
            d = add_lib_dirs.pop()
            cs_exec_environment.write_prepend_path(s,
                                                   'LD_LIBRARY_PATH',
                                                   d)

        # Add paths for plugins or dynamic library dependencies

        lib_dirs, plugin_pythonpath_dirs, plugin_env_vars \
            = self.package_compute.config.get_run_environment_dependencies()
        for d in lib_dirs:
            cs_exec_environment.write_prepend_path(s,
                                                   'LD_LIBRARY_PATH',
                                                   d)
        for d in plugin_pythonpath_dirs:
            cs_exec_environment.write_prepend_path(s,
                                                   'PYTHONPATH',
                                                   d)

        # Add paths for local libraries
        if self.package_compute.config.features['relocatable'] == "yes":
            d = self.package_compute.get_dir('libdir')
            if d != '/usr/lib' and d != '/usr/local/lib':
                cs_exec_environment.write_prepend_path(s,
                                                       'LD_LIBRARY_PATH',
                                                       d)

        # Add additional environment variables

        for v in plugin_env_vars:
            cs_exec_environment.write_export_env(s, v, plugin_env_vars[v])

        s.write('\n')

        # Handle OpenMP if needed

        n_threads = exec_env.resources.n_threads
        if self.package_compute.config.features['openmp'] == 'yes' or n_threads:
            if not n_threads:
                n_threads = 1
            cs_exec_environment.write_export_env(s, 'OMP_NUM_THREADS',
                                                 str(n_threads))
            s.write('\n')

        # Handle rcfile if used

        rcfile = cs_exec_environment.get_rcfile(self.package_compute)

        if rcfile and rcfile != "no":
            cs_exec_environment.write_script_comment(s, \
               'Load environment if this script is run directly.\n')
            s.write('if test "$CS_ENVIRONMENT_SET" != "true" ; then\n')
            if rcfile:
                s.write('  source ' + rcfile + '\n')
            s.write('fi\n\n')

        # Boot MPI daemons if necessary

        if mpi_env.gen_hostsfile != None:
            cs_exec_environment.write_script_comment(s, 'Generate hostsfile.\n')
            s.write(mpi_env.gen_hostsfile + ' || exit $?\n\n')

        if n_procs > 1 and mpi_env.mpiboot != None:
            cs_exec_environment.write_script_comment(s, 'Boot MPI daemons.\n')
            s.write(mpi_env.mpiboot + ' || exit $?\n\n')

        # Ensure we are in the correct directory

        s.write('cd ' + cs_exec_environment.enquote_arg(self.exec_dir) + '\n\n')

        # Add user-defined prologue if defined

        if self.compute_prologue:
            s.write('# Compute prologue\n')
            s.write(self.compute_prologue)
            s.write('\n\n')

        # Generate script body

        self.solver_script_body(n_procs, mpi_env, s)

        # Obtain return value (or sum thereof)

        cs_exec_environment.write_export_env(s, 'CS_RET',
                                             cs_exec_environment.get_script_return_code())

        # Halt MPI daemons if necessary

        if n_procs > 1 and mpi_env.mpihalt != None:
            cs_exec_environment.write_script_comment(s, 'Halt MPI daemons.\n')
            s.write(mpi_env.mpihalt + '\n\n')

        if mpi_env.del_hostsfile != None:
            cs_exec_environment.write_script_comment(s, 'Remove hostsfile.\n')
            s.write(mpi_env.del_hostsfile + '\n\n')

        # Add user-defined epilogue if defined

        if self.compute_epilogue:
            s.write('\n# Compute epilogue\n')
            s.write(self.compute_epilogue)
            s.write('\n')

        if sys.platform.startswith('win'):
            s.write('\nexit %CS_RET%\n')
        else:
            s.write('\nexit $CS_RET\n')
        s.close()

        oldmode = (os.stat(s_path)).st_mode
        newmode = oldmode | (stat.S_IXUSR)
        os.chmod(s_path, newmode)

        return s_path

    #---------------------------------------------------------------------------

    def update_scripts_tmp(self, src, dest, caption=None):

        """
        Create a stamp file in the execution directory, rename it, or destroy it.
        """

        # Create a temporary file to determine status

        src_tmp_name = None
        dest_tmp_name = None

        base_path = os.path.join(self.exec_dir, 'run_status.')
        if not os.path.isdir(base_path):
            base_path = os.path.join(self.result_dir, 'run_status.')

        if src != None:
            if type(src) == tuple:
                for s in src:
                    p = base_path + s
                    if os.path.isfile(p):
                        src_tmp_name = p

            else:
                p = base_path + src
                if os.path.isfile(p):
                    src_tmp_name = p

        try:
            if dest != None:
                dest_tmp_name = base_path + dest
                if src_tmp_name == None:
                    scripts_tmp = open(dest_tmp_name, 'w')
                    if not caption:
                        caption = self.case_dir
                    scripts_tmp.write(caption + '\n')
                    scripts_tmp.close()
                else:
                    os.rename(src_tmp_name, dest_tmp_name)

            else:
                os.remove(src_tmp_name)

        except Exception:
            pass

    #---------------------------------------------------------------------------

    def add_exec_dir_stamp(self):

        """
        Create a file with the execution directory path in the results directory.
        """
        p = os.path.join(self.result_dir, 'run_status.exec_dir')

        f = open(p, 'w')
        f.write(self.exec_dir + '\n')
        f.close()

    #---------------------------------------------------------------------------

    def clear_exec_dir_stamp(self):

        """
        Remove file with the execution directory path from the results directory.
        """
        p = os.path.join(self.result_dir, 'run_status.exec_dir')

        try:
            os.remove(p)
        except Exception:
            pass

    #---------------------------------------------------------------------------

    def exceeded_time_limit(self):

        """
        Check if the allocated time limit was exceeded.
        """
        p = os.path.join(self.exec_dir, 'run_status.exceeded_time_limit')

        if os.path.isfile(os.path.join(p)):
            return True
        else:
            return False

    #---------------------------------------------------------------------------

    def set_run_id(self,
                   run_id = None):

        """
        Set run id for calculation.
        """

        if run_id != None:
            self.run_id = run_id
            self.define_result_dir()

        # When id not assigned, choose an id not already present

        if self.run_id == None:
            self.run_id = self.suggest_id()
            self.define_result_dir()
            j = 1
            run_id_base = self.run_id
            while os.path.isdir(self.result_dir):
                self.run_id = run_id_base + '_' + str(j)
                self.define_result_dir()

    #---------------------------------------------------------------------------

    def prepare_data(self,
                     force_id = False):

        """
        Prepare data for calculation.
        """

        # Before creating or generating file, create stage 'marker' file.

        self.update_scripts_tmp(None, 'preparing')

        # Copy script before changing to the working directory
        # (as after that, the relative path will not be up to date).

        self.copy_script()
        self.copy_top_run_conf()

        os.chdir(self.exec_dir)

        # Set (read and possibly modify) script parameters

        sys.stdout.write('Copying base setup data\n'
                         '-----------------------\n\n')

        for d in self.domains:
            d.copy_data()

        # Compile user subroutines if necessary
        # (for some domain types, such as for Syrthes, this may be done later,
        # during the general prepare_data stage).

        need_compile = False

        for d in self.domains:
            if not hasattr(d, 'needs_compile'):
                continue
            if d.needs_compile() == True:
                if need_compile == False: # Print banner on first pass
                    need_compile = True
                    msg = \
                        "Compiling and linking user-defined functions\n" \
                        "--------------------------------------------\n\n"
                    sys.stdout.write(msg)
                    sys.stdout.flush()
                d.compile_and_link()
                if len(d.error) > 0:
                    self.error = d.error
                    if len(d.error_long) > 0:
                        self.error_long = d.error_long

        if len(self.error) > 0:
            self.update_scripts_tmp('preparing', 'failed', self.error)
            return 1

        # Setup data
        #===========

        sys.stdout.write('Preparing calculation data\n'
                         '--------------------------\n\n')
        sys.stdout.flush()

        for d in (self.domains + self.syr_domains + self.py_domains):
            d.prepare_data()
            if len(d.error) > 0:
                self.error = d.error

        # Set run_id in run.cfg as a precaution

        run_conf_path = os.path.join(self.result_dir, "run.cfg")
        if os.path.isfile(run_conf_path):
            run_conf = cs_run_conf.run_conf(run_conf_path, package=self.package)
            run_conf.set('run', 'id', str(self.run_id))
            run_conf.save()

        # Rename temporary file to indicate new status

        if len(self.error) == 0:
            status = 'prepared'
        else:
            status = 'failed'

        self.update_scripts_tmp('preparing', status, self.error)

        # Standard or error exit

        if len(self.error) > 0:
            err_str = ' Error in ' + self.error + ' stage.\n\n'
            if len(self.error_long) > 0:
                err_str += self.error_long + '\n\n'
            sys.stderr.write(err_str)
            return 1
        else:
            return 0

    #---------------------------------------------------------------------------

    def init_prepared_data(self):

        """
        Initialize prepared data for calculation.
        """

        self.copy_script()

        os.chdir(self.exec_dir)

        for d in self.domains:
            solver = os.path.basename(d.solver_path)
            if os.path.isfile(os.path.join(d.exec_dir, solver)):
                d.solver_path = os.path.join('.', solver)
            d.init_staged_data()

        for d in self.syr_domains:
            d.solver_path = os.path.join('.', 'syrthes')
            d.init_staged_data()

        for d in self.py_domains:
            d.solver_path = self.package.config.python
            d.init_staged_data()

    #---------------------------------------------------------------------------

    def preprocess(self,
                   n_procs = None,
                   n_threads = None,
                   mpiexec_options=None):

        """
        Preprocess data for and generate run script
        """

        os.chdir(self.exec_dir)

        # Adaptation should go in the future

        for d in self.domains:
            if hasattr(d, 'adaptation'):
                if d.adaptation:
                    adaptation(d.adaptation, saturne_script, self.case_dir)

        # Before creating or generating file, create stage 'marker' file.

        self.update_scripts_tmp('prepared', 'preprocessing')

        # Determine execution environment
        #================================
        # (priority for n_procs, in increasing order:
        # resource manager, method argument).

        n_procs_default = None
        if len(self.domains) == 1 and len(self.syr_domains) == 0 \
           and len(self.py_domains) == 0:
            d = self.domains[0]
            if hasattr(d, 'case_n_procs'):
                n_procs_default = int(d.case_n_procs)

        exec_env = cs_exec_environment.exec_environment(self.package_compute,
                                                        self.exec_dir,
                                                        n_procs,
                                                        n_procs_default,
                                                        n_threads)

        # Set user MPI options if required.

        if mpiexec_options != None:
            exec_env.mpi_env.mpiexec_opts = mpiexec_options

        # Transfer parameters MPI parameters from user scripts here.

        if len(self.domains) == 1 and len(self.syr_domains) == 0 \
           and len(self.py_domains) == 0:
            d = self.domains[0]
            if d.user_locals:
                m = 'define_mpi_environment'
                if m in d.user_locals.keys():
                    eval(m + '(exec_env.mpi_env)', locals(), d.user_locals)
                    del d.user_locals[m]

        # Compute number of processors.

        n_procs_tot = self.distribute_procs(exec_env.resources.n_procs)

        if n_procs_tot > 1:
            exec_env.resources.n_procs = n_procs_tot

        self.print_procs_distribution()

        # Preprocessing
        #==============

        sys.stdout.write('Preprocessing calculation\n'
                         '-------------------------\n\n')
        sys.stdout.flush()

        self.summary_init(exec_env)

        for d in (self.domains + self.syr_domains + self.py_domains):
            d.preprocess()
            if len(d.error) > 0:
                self.error = d.error

        if self.exec_solver:
            s_path = self.generate_solver_script(exec_env)

        # Rename temporary file to indicate new status

        if len(self.error) == 0:
            status = 'ready'
        else:
            status = 'failed'

        self.update_scripts_tmp('preprocessing', status, self.error)

        # Standard or error exit

        if len(self.error) > 0:
            if self.error == 'preprocess':
                error_stage = 'preprocessing'
            else:
                error_stage = self.error
            err_str = ' Error in ' + error_stage + ' stage.\n\n'
            sys.stderr.write(err_str)
            return 1
        else:
            return 0

    #---------------------------------------------------------------------------

    def run_solver(self):

        """
        Run solver proper.
        """

        if not self.exec_solver:
            return 0

        os.chdir(self.exec_dir)

        # Indicate status using temporary file for SALOME.

        self.update_scripts_tmp('ready', 'running')

        sys.stdout.write('Starting calculation\n'
                         '--------------------\n\n')
        sys.stdout.flush()

        # Maximum remaining time if defined through run configuration
        # or batch system.

        b = cs_exec_environment.batch_info()
        max_time = b.get_remaining_time()
        if self.time_limit:
            if max_time:
                if self.time_limit < max_time:
                    max_time = self.time_limit
            else:
                max_time = self.time_limit
        if max_time != None:
            os.putenv('CS_MAXTIME', str(max_time))

        # Tell the script it is being called through the main script
        # (implying environment modules are set and the environment loaded)

        rcfile = cs_exec_environment.get_rcfile(self.package_compute)

        if rcfile or self.package_compute.config.env_modules != "no":
            os.putenv('CS_ENVIRONMENT_SET', 'true')

        # Now run the calculation

        s_path = [self.solver_script_path()]

        retcode = cs_exec_environment.run_command(s_path)

        # Update error codes

        name = self.module_name

        if retcode != 0:
            self.error = 'solver'
            err_str = \
                ' solver script exited with status ' \
                + str(retcode) + '.\n\n'
            sys.stderr.write(err_str)

        if self.error == 'solver':

            if len(self.syr_domains) > 0:
                err_str = \
                    'Error running the coupled calculation.\n\n' \
                    'Either ' + name + ' or SYRTHES may have failed.\n\n' \
                    'Check ' + name + ' log (listing) and SYRTHES log (syrthes.log)\n' \
                    'for details, as well as error* files.\n\n'
            elif len(self.py_domains) > 0:
                err_str = \
                    'Error running the coupled calculation.\n\n' \
                    'Either ' + name + ' or Python script may have failed.\n\n' \
                    'Check ' + name + ' log (listing) and Python log (python.log)\n' \
                    'for details, as well as error* files.\n\n'
            else:
                err_str = \
                    'Error running the calculation.\n\n' \
                    'Check ' + name + ' log (listing) and error* files for details.\n\n'
            sys.stderr.write(err_str)

            # Update error status for domains

            for d in (self.domains + self.syr_domains + self.py_domains):
                d.error = self.error

        # Indicate status using temporary file for SALOME.

        if retcode == 0:
            status = 'finished'
        else:
            status = 'failed'

        self.update_scripts_tmp(('running',), status, self.error)

        return retcode

    #---------------------------------------------------------------------------

    def save_results(self):

        """
        Save calcultation results from execution directory to result
        directory.
        """

        os.chdir(self.exec_dir)

        self.update_scripts_tmp(('ready', 'finished'), 'saving')

        # Now save results

        sys.stdout.write('Post-calculation operations\n'
                         '---------------------------\n\n')
        sys.stdout.flush()

        self.summary_finalize()
        self.copy_log('summary')

        n_domains = len(self.domains) + len(self.syr_domains) + len(self.py_domains)
        if n_domains > 1 and self.error == '':
            dir_files = os.listdir(self.exec_dir)
            for f in [self.package.runsolver,
                      'mpmd_configfile', 'mpmd_exec.sh']:
                if f in dir_files:
                    try:
                        os.remove(f)
                    except Exception:
                        pass

        e_caption = None
        for d in (self.domains + self.syr_domains + self.py_domains):
            d.copy_results()
            if d.error:
                e_caption = d.error

        # Remove directories if empty

        try:
            os.removedirs(self.exec_dir)
            msg = ' Cleaned working directory:\n' \
                + '   ' +  str(self.exec_dir) + '\n'
            sys.stdout.write(msg)
        except Exception:
            pass

        if e_caption: # in case of error during copy/cleanup/postprocessing
            self.update_scripts_tmp('failed', 'failed', e_caption)

        self.update_scripts_tmp('saving', None)

    #---------------------------------------------------------------------------

    def run(self,
            n_procs = None,
            n_threads = None,
            time_limit = None,
            mpiexec_options=None,
            scratchdir = None,
            run_id = None,
            force_id = False,
            stages = None,
            notebook_args=None,
            parametric_args=None,
            kw_args=None):

        """
        Main script.
        """

        # Define run stages if not provided

        if not stages:
            stages = {'prepare_data':True,
                      'initialize':True,
                      'run_solver':True,
                      'save_results':True}

        # If preparation stage is not requested, it must have been done
        # previously, and the id must be forced.

        if not stages['prepare_data']:
            force_id = True

        # Run id and associated directories

        self.set_run_id(run_id)
        self.set_result_dir(force_id)

        # If preparation stage is missing, force it
        if stages['initialize'] and not stages['prepare_data']:
            self.define_exec_dir()
            if not os.path.isdir(self.exec_dir):
                stages['prepare_data'] = True

        # Define scratch directory
        # priority: argument, environment variable, preference setting.

        if scratchdir == None:
            scratchdir = os.getenv('CS_SCRATCHDIR')

        if scratchdir == None:

            # Read the possible config files

            config = configparser.ConfigParser()
            config.read(self.package.get_configfiles())

            # Determine default execution directory if not forced;
            # If the case is already in a sub-directory of the execution
            # directory determined in the configuration file, run in place.

            if config.has_option('run', 'scratchdir'):
                scratchdir = os.path.expanduser(config.get('run', 'scratchdir'))
                scratchdir = os.path.realpath(os.path.expandvars(scratchdir))
                if os.path.realpath(self.result_dir).find(scratchdir) == 0:
                    scratchdir = None

        if scratchdir != None:
            self.exec_prefix = os.path.join(scratchdir, self.package.scratchdir)

        # Define MPI execution options
        # priority: argument, environment variable, preference setting, defaults.

        if mpiexec_options == None:
            mpiexec_options = os.getenv('CS_MPIEXEC_OPTIONS')

        # Set working directory
        # (nonlocal filesystem, reachable by all the processes)

        self.set_exec_dir(force_id)

        # Optional time limit

        if time_limit != None:
            try:
                time_limit = int(time_limit)
                if time_limit >= 0:
                    self.time_limit = time_limit
            except Exception:
                pass

        # Greeting message.

        msg = \
            '\n' \
            + '                      ' + self.module_name + '\n' \
            + '                      ============\n' \
            + '\n' \
            + 'Version:   ' + self.package.version + '\n' \
            + 'Path:      ' + self.package.get_dir('exec_prefix') + '\n'
        if self.package_compute != self.package:
            msg += '  compute: ' + self.package_compute.get_dir('exec_prefix') + '\n\n'
        else:
            msg += '\n'
        msg += 'Result directory:\n' \
               + '  ' +  str(self.result_dir) + '\n\n'

        if self.exec_dir != self.result_dir:
            msg += 'Working directory (to be periodically cleaned):\n' \
                + '  ' +  str(self.exec_dir) + '\n\n'
            self.add_exec_dir_stamp()

        sys.stdout.write(msg)

        # Log user-defined notebook and keyword arguments
        # and pass them to domain structures

        if notebook_args:
            msg = 'Notebook variables:\n'
            keys = list(notebook_args.keys())
            keys.sort()
            for k in keys:
                msg += "  '" + k + "': '" + notebook_args[k] + "'\n"
            msg += '\n'
            sys.stdout.write(msg)

        if parametric_args:
            msg = 'cs_parametric filter arguments:\n'
            msg += '  ' + str(parametric_args) + '\n\n'
            sys.stdout.write(msg)

        if kw_args:
            msg = 'Additional user keyword arguments:\n'
            msg += '  ' + str(kw_args) + '\n\n'
            sys.stdout.write(msg)

        if notebook_args:
            for d in (self.domains):
                if d.notebook == None:
                    d.notebook = notebook_args
                else:
                    err_str = 'domain: + ' + str(d.name) \
                              + ' notebook already defined\n'
                    sys.stderr.write(err_str)

        if parametric_args:
            for d in (self.domains):
                if d.parametric_args == None:
                    d.parametric_args = parametric_args
                else:
                    err_str = 'domain: + ' + str(d.name) \
                              + ' parametric_args already defined\n'
                    sys.stderr.write(err_str)

        if kw_args:
            for d in (self.domains + self.syr_domains + self.py_domains):
                if d.kw_args == None:
                    d.kw_args = kw_args
                else:
                    err_str = 'domain: + ' + str(d.name) \
                              + ' kw_args already defined\n'
                    sys.stderr.write(err_str)

        sys.stdout.flush()

        # Remove possible status from previous run

        self.update_scripts_tmp(('failed,',
                                 'exceeded_time_limit'), None)

        # Now run

        if self.run_prologue:
            cwd = os.getcwd()
            os.chdir(self.exec_dir)
            retcode = cs_exec_environment.run_command(self.run_prologue)
            os.chdir(cwd)

        try:
            retcode = 0
            if stages['prepare_data']:
                retcode = self.prepare_data(force_id)
            else:
                self.init_prepared_data()

            if stages['initialize'] and  retcode == 0:
                retcode = self.preprocess(n_procs,
                                          n_threads,
                                          mpiexec_options)
            if stages['run_solver'] == True and retcode == 0:
                self.run_solver()

            if stages['save_results'] == True:
                self.save_results()
                self.clear_exec_dir_stamp()

        finally:
            if self.run_id != None:
                self.update_scripts_tmp(('preparing',
                                         'ready',
                                         'running',
                                         'finished'), None)

        # Standard or error exit

        retcode = 0

        if len(self.error) > 0:
            check_stage = {'preprocess':'preprocessing',
                           'solver':'calculation'}
            if self.error in check_stage:
                error_stage = check_stage[self.error]
            else:
                error_stage = self.error
            err_str = ' Error in ' + error_stage + ' stage.\n\n'
            if len(self.error_long) > 0:
                err_str += self.error_long + '\n\n'
            sys.stderr.write(err_str)
            retcode = 1

        if self.run_epilogue:
            cwd = os.getcwd()
            os.chdir(self.exec_dir)
            retcode = cs_exec_environment.run_command(self.run_epilogue)
            os.chdir(cwd)

        return retcode

    #---------------------------------------------------------------------------

    def suggest_id(self,
                   run_id_prefix = None,
                   run_id_suffix = None):

        """
        Suggest run id.
        """

        now = datetime.datetime.now()
        run_id_base = now.strftime('%Y%m%d-%H%M')

        if self.dest_dir != None:
            base_dir = os.path.join(self.dest_dir,
                                    os.path.basename(self.case_dir))
        else:
            base_dir = self.case_dir

        r = os.path.join(base_dir, 'RESU')

        if len(self.domains) + len(self.syr_domains) \
         + len(self.py_domains) > 1:
            r += '_COUPLING'
        elif len(self.domains) == 1 and not (run_id_prefix or run_id_suffix):
            try:
                d = self.domains[0]
                if not d.exec_solver:
                    run_id_prefix = 'import_'
                a = d.solver_args
                if a and a in ('--quality', '--preprocess', '--benchmark'):
                    run_id_prefix = a[2:] + '_'
            except Exception:
                pass

        # Make sure directory does not exist already

        j = 0

        while True:

            run_id = run_id_base
            if j > 0:
                run_id += '_' + str(j)

            if run_id_prefix:
                run_id = run_id_prefix + run_id
            if run_id_suffix:
                run_id = run_id + run_id_suffix

            result_dir = os.path.join(r, run_id)

            if os.path.isdir(result_dir):
                j += 1
            else:
                break

        return run_id

#-------------------------------------------------------------------------------
# End
#-------------------------------------------------------------------------------