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 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102
|
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# This file is part of Code_Saturne, a general-purpose CFD tool.
#
# Copyright (C) 1998-2019 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.
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# Standard modules import
#-------------------------------------------------------------------------------
import os, sys
import shutil, re
import subprocess
import threading
import string
import time
import logging
import fnmatch
#-------------------------------------------------------------------------------
# Application modules import
#-------------------------------------------------------------------------------
from cs_exec_environment import get_shell_type, enquote_arg
from cs_compile import files_to_compile, compile_and_link
import cs_create
from cs_create import set_executable
import cs_runcase
from code_saturne.model import XMLengine
from code_saturne.studymanager.cs_studymanager_pathes_model import PathesModel
from studymanager.cs_studymanager_parser import Parser
from studymanager.cs_studymanager_texmaker import Report1, Report2
try:
from studymanager.cs_studymanager_drawing import Plotter
except Exception:
print("Warning: import studymanager Plotter failed. Plotting disabled.\n")
pass
from studymanager.cs_studymanager_run import run_studymanager_command
#-------------------------------------------------------------------------------
# log config.
#-------------------------------------------------------------------------------
logging.basicConfig()
log = logging.getLogger(__file__)
#log.setLevel(logging.DEBUG)
log.setLevel(logging.NOTSET)
#-------------------------------------------------------------------------------
def nodot(item):
return item[0] != '.'
#-------------------------------------------------------------------------------
def create_base_xml_file(filepath):
"""Create studymanager XML file.
"""
filename = os.path.basename(filepath)
if os.path.isfile(filepath):
print("Can not create XML file of parameter:\n" \
+ filepath + " already exists.")
sys.exit(1)
# using xml engine from Code_Saturne GUI
smgr = XMLengine.Case(None, studymanager=True)
smgr['xmlfile'] = filename
pm = PathesModel(smgr)
# empty repo and dest
pm.setRepositoryPath('')
pm.setDestinationPath('')
return smgr
#-------------------------------------------------------------------------------
def init_xml_file_with_study(smgr, studyp):
"""Initialize XML file with study content and save it.
"""
smgr_node = smgr.xmlGetNode('studymanager')
studyd = os.path.basename(studyp)
st_node = smgr_node.xmlInitChildNode('study', label = studyd)
st_node['status'] = "on"
cases = []
for elt in os.listdir(studyp):
eltd = os.path.join(studyp, elt)
if os.path.isdir(eltd):
if isCase(eltd):
cases.append(elt)
cases.sort()
for case in cases:
c_node = st_node.xmlInitChildNode("case", label = case)
c_node['status'] = "on"
c_node['compute'] = "on"
c_node['post'] = "on"
smgr.xmlSaveDocument()
#-------------------------------------------------------------------------------
def isStudy(dirpath):
"""Try to determine if dirpath is a Code_Saturne study directory.
"""
meshd = os.path.join(dirpath, 'MESH')
is_study = os.path.isdir(meshd)
return is_study
#-------------------------------------------------------------------------------
def isCase(dirpath):
"""Try to determine if dirpath is a Code_Saturne case directory.
"""
datad = os.path.join(dirpath, 'DATA')
scriptd = os.path.join(dirpath, 'SCRIPTS')
is_case = os.path.isdir(datad) and os.path.isdir(scriptd)
return is_case
#===============================================================================
# Case class
#===============================================================================
class Case(object):
def __init__(self, pkg, rlog, diff, parser, study, data, repo, dest):
"""
@type data: C{Dictionary}
@param data: contains all keyword and value read in the parameters file
"""
self.__log = rlog
self.__diff = diff
self.__parser = parser
self.__study = study
self.__data = data
self.__repo = repo
self.__dest = dest
self.node = data['node']
self.label = data['label']
self.compute = data['compute']
self.plot = data['post']
self.run_id = data['run_id']
self.tags = data['tags']
self.compare = data['compare']
self.is_compiled= "not done"
self.is_run = "not done"
self.is_time = None
self.is_plot = "not done"
self.is_compare = "not done"
self.threshold = "default"
self.diff_value = [] # list of differences (in case of comparison)
self.m_size_eq = True # mesh sizes equal (in case of comparison)
self.subdomains = None
self.run_dir = ""
self.resu = 'RESU'
# Specific case for coupling
coupling = os.path.join(self.__repo, self.label, "coupling_parameters.py")
if os.path.isfile(coupling):
import cs_case_coupling
try:
exec(compile(open(coupling).read(), '<string>', 'exec'))
except Exception:
execfile(coupling)
run_ref = os.path.join(self.__repo, self.label, "runcase")
self.exe, self.pkg = self.__get_exe(pkg, run_ref)
self.subdomains = []
for d in locals()['domains']:
if d['solver'] == self.pkg.code_name:
self.subdomains.append(d['domain'])
elif d['solver'].lower() == "syrthes":
syrthes = True
self.resu = 'RESU_COUPLING'
# insert syrthes path
if syrthes:
syrthes_insert = cs_create.syrthes_path_line(pkg)
if syrthes_insert:
fd = open(coupling)
fd_lines = fd.readlines()
fd.close()
fd = open(coupling, 'w')
for line in fd_lines:
if "sys.path.insert" in line:
fd.write(syrthes_insert)
else:
fd.write(line)
fd.close()
else:
run_ref = os.path.join(self.__repo, self.label, "SCRIPTS", "runcase")
self.exe, self.pkg = self.__get_exe(pkg, run_ref)
#---------------------------------------------------------------------------
def __get_exe(self, old_pkg, run_ref):
"""
Return the name of the exe of the case, in order to mix
Code_Saturne and NEPTUNE_CFD test cases in the same study.
"""
# Read the runcase script from the Repository
runcase = cs_runcase.runcase(run_ref)
if runcase.cmd_name == "code_saturne":
from cs_package import package
elif runcase.cmd_name == "neptune_cfd":
from nc_package import package
pkg = package()
return runcase.cmd_name, pkg
#---------------------------------------------------------------------------
def __update_domain(self, subdir, xmlonly=False):
"""
Update path for the script in the Repository.
"""
# 1) Load the xml file of parameters in order to update it
# with the __backwardCompatibility method.
from model.XMLengine import Case
if self.exe == "code_saturne":
from model.XMLinitialize import XMLinit
elif self.exe == "neptune_cfd":
from model.XMLinitializeNeptune import XMLinit
for fn in os.listdir(os.path.join(self.__repo, subdir, "DATA")):
fp = os.path.join(self.__repo, subdir, "DATA", fn)
if os.path.isfile(fp):
fd = os.open(fp , os.O_RDONLY)
f = os.fdopen(fd)
l = f.readline()
f.close()
if l.startswith('''<?xml version="1.0" encoding="utf-8"?><Code_Saturne_GUI''') or \
l.startswith('''<?xml version="1.0" encoding="utf-8"?><NEPTUNE_CFD_GUI'''):
try:
case = Case(package = self.pkg, file_name = fp)
except:
print("Parameters file reading error.\n")
print("This file is not in accordance with XML specifications.\n")
sys.exit(1)
case['xmlfile'] = fp
case.xmlCleanAllBlank(case.xmlRootNode())
XMLinit(case).initialize()
case.xmlSaveDocument()
# 2) Recreate missing directories which are compulsory
# git removes these usually empty directories
if not xmlonly:
git_rm_dirs = ["RESU", "SRC"]
for gd in git_rm_dirs:
r = os.path.join(self.__repo, subdir, gd)
if not os.path.isdir(r):
os.makedirs(r)
# 3) Update the GUI script from the Repository
data_subdir = os.path.join(self.__repo, subdir, "DATA")
self.update_gui_script_path(data_subdir, None, xmlonly)
# 4) Update the runcase script from the Repository
scripts_subdir = os.path.join(self.__repo, subdir, "SCRIPTS")
self.update_runcase_path(scripts_subdir, None, xmlonly)
#---------------------------------------------------------------------------
def update_gui_script_path(self, subdir, destdir=None, xmlonly=False):
"""
Update path for the script in the Repository.
"""
if not destdir:
gui_script = os.path.join(self.__repo, subdir, self.pkg.guiname)
else:
gui_script = os.path.join(destdir, subdir, self.pkg.guiname)
have_gui = 1
try:
f = open(gui_script, mode = 'r')
except IOError:
print("Warning SaturneGUI does not exist: %s\n" % gui_script)
have_gui = 0
if have_gui:
lines = f.readlines()
f.close()
for i in range(len(lines)):
if re.search(r'^export PATH=', lines[i]):
if xmlonly:
lines[i] = 'export PATH="":$PATH\n'
else:
lines[i] = 'export PATH="' + self.pkg.get_dir('bindir')\
+'":$PATH\n'
f = open(gui_script, mode = 'w')
f.writelines(lines)
f.close()
set_executable(gui_script)
#---------------------------------------------------------------------------
def update_runcase_path(self, subdir, destdir=None, xmlonly=False):
"""
Update path for the script in the Repository.
"""
if not destdir:
batch_file = os.path.join(self.__repo, subdir, "runcase")
else:
batch_file = os.path.join(destdir, subdir, "runcase")
try:
f = open(batch_file, mode = 'r')
except IOError:
print("Error: can not open %s\n" % batch_file)
sys.exit(1)
lines = f.readlines()
f.close()
for i in range(len(lines)):
if lines[i].strip()[0:1] == '#':
continue
if xmlonly:
if re.search(r'^export PATH=', lines[i]):
lines[i] = 'export PATH="":$PATH\n'
else:
if re.search(r'^export PATH=', lines[i]):
lines[i] = 'export PATH="' + self.pkg.get_dir('bindir') +'":$PATH\n'
f = open(batch_file, mode = 'w')
f.writelines(lines)
f.close()
set_executable(batch_file)
#---------------------------------------------------------------------------
def update(self, xmlonly=False):
"""
Update path for the script in the Repository.
"""
# 1) Load the xml file of parameters in order to update it
# with the __backwardCompatibility method.
if self.subdomains:
cdirs = []
for d in self.subdomains:
cdirs.append(os.path.join(self.label, d))
else:
cdirs = (self.label,)
for d in cdirs:
self.__update_domain(d, xmlonly)
# Update the runcase script from the repository in case of coupling
if self.subdomains:
case_dir = os.path.join(self.__repo, self.label)
self.update_runcase_path(case_dir, None, xmlonly)
# recreate possibly missing but compulsory directory
r = os.path.join(case_dir, "RESU_COUPLING")
if not os.path.isdir(r):
os.makedirs(r)
#---------------------------------------------------------------------------
def test_compilation(self, study_path, log):
"""
Test compilation of sources for current case (if some exist).
@rtype: C{String}
@return: compilation test status (None if no files to compile).
"""
if self.subdomains:
sdirs = []
for sd in self.subdomains:
sdirs.append(os.path.join(study_path, self.label, sd, 'SRC'))
else:
sdirs = (os.path.join(study_path, self.label, 'SRC'),)
# compilation test mode
dest_dir = None
self.is_compiled = None
retcode = 0
# loop over subdomains
for s in sdirs:
src_files = files_to_compile(s)
if len(src_files) > 0:
self.is_compiled = "OK"
retcode += compile_and_link(self.pkg, s, dest_dir,
stdout=log, stderr=log)
if retcode > 0:
self.is_compiled = "KO"
return self.is_compiled
#---------------------------------------------------------------------------
def __suggest_run_id(self):
cmd = enquote_arg(os.path.join(self.pkg.get_dir('bindir'), self.exe)) + " run --suggest-id"
if self.subdomains:
cmd += " --coupling=coupling_parameters.py"
p = subprocess.Popen(cmd,
shell=True,
executable=get_shell_type(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
i = p.communicate()[0]
run_id = " ".join(i.split())
return run_id, os.path.join(self.__dest, self.label, self.resu, run_id)
#---------------------------------------------------------------------------
def __updateRuncase(self, run_id):
"""
Update the command line in the launcher C{runcase}.
"""
from cs_exec_environment import separate_args, \
get_command_single_value
# Prepare runcase path
scripts_repo = os.path.join(self.__repo, self.label)
scripts_dest = os.path.join(self.__dest, self.label)
if not self.subdomains:
scripts_repo = os.path.join(scripts_repo, "SCRIPTS")
scripts_dest = os.path.join(scripts_dest, "SCRIPTS")
run_ref = os.path.join(scripts_repo, "runcase")
run_ref_win = os.path.join(scripts_repo, "runcase.bat")
run_new = os.path.join(scripts_dest, "runcase")
if sys.platform.startswith('win'):
run_new = os.path.join(scripts_dest, "runcase.bat")
# Read runcase from repo
path = run_ref
if not os.path.isfile(path):
path = run_ref_win
if not os.path.isfile(path):
print("Error: could not find %s (or %s)\n" % run_ref, run_ref_win)
sys.exit(1)
runcase_repo = cs_runcase.runcase(path, create_if_missing=False)
# Read runcase from dest
path = run_new
runcase_dest = cs_runcase.runcase(path, create_if_missing=False,
ignore_batch=True)
# Assign run command from repo in dest
runcase_dest.set_run_args(runcase_repo.get_run_args())
# set run_id in dest
runcase_dest.set_run_id(run_id=run_id)
# Set number of processors if provided
n_procs = self.__data['n_procs']
if n_procs:
runcase_dest.set_nprocs(n_procs)
# Write runcase
runcase_dest.save()
#---------------------------------------------------------------------------
def run(self):
"""
Check if a run with same result subdirectory name exists
and launch run if not.
"""
home = os.getcwd()
if self.subdomains:
os.chdir(os.path.join(self.__dest, self.label))
else:
os.chdir(os.path.join(self.__dest, self.label, 'SCRIPTS'))
if self.run_id:
run_id = self.run_id
run_dir = os.path.join(self.__dest, self.label, self.resu, run_id)
if os.path.isdir(run_dir):
if os.path.isfile(os.path.join(run_dir, "error")):
self.is_run = "KO"
error = 1
else:
self.is_run = "OK"
error = 0
os.chdir(home)
return error
else:
run_id, run_dir = self.__suggest_run_id()
while os.path.isdir(run_dir):
run_id, run_dir = self.__suggest_run_id()
self.run_id = run_id
self.run_dir = run_dir
self.__updateRuncase(run_id)
if sys.platform.startswith('win'):
error, self.is_time = run_studymanager_command("runcase.bat", self.__log)
else:
error, self.is_time = run_studymanager_command("./runcase", self.__log)
if not error:
self.is_run = "OK"
else:
self.is_run = "KO"
os.chdir(home)
return error
#---------------------------------------------------------------------------
def runCompare(self, studies, r, d, threshold, args, reference=None):
home = os.getcwd()
node = None
if reference:
result = os.path.join(reference, self.label, self.resu)
else:
result = os.path.join(self.__repo, self.label, self.resu)
# check_dir called again here to get run_id (possibly date-hour)
repo, msg = self.check_dir(node, result, r, "repo")
if msg:
studies.reporting(msg)
repo = os.path.join(result, repo, 'checkpoint', 'main')
result = os.path.join(self.__dest, self.label, self.resu)
# check_dir called again here to get run_id (possibly date-hour)
dest, msg = self.check_dir(node, result, d, "dest")
if msg:
studies.reporting(msg)
dest = os.path.join(result, dest, 'checkpoint', 'main')
cmd = self.__diff + ' ' + repo + ' ' + dest
self.threshold = "default"
if threshold != None:
cmd += ' --threshold ' + threshold
self.threshold = threshold
if args != None:
cmd += (" " + args)
l = args.split()
try:
i = l.index('--threshold')
self.threshold = l[i+1]
except:
pass
l = subprocess.Popen(cmd,
shell=True,
executable=get_shell_type(),
stdout=subprocess.PIPE,
universal_newlines=True).stdout
lines = l.readlines()
# list of field differences
tab = []
# meshes have same sizes
m_size_eq = True
# studymanager compare log only for field of real values
for i in range(len(lines)):
# only select line with "Type" (english and french) and ';'
# since this should be only true for heads of section
if lines[i].find("Type") != -1 and lines[i].find(";") != -1:
line = [x.replace("\""," ").strip() for x in lines[i].split(";")]
name = line[0]
info = [x.split(":") for x in line[1:]]
info = [[x[0].strip(),x[1].strip()] for x in info]
# section with at least 2 informations (location, type) after
# their name, and of type r (real)
if len(info) >= 2 and info[1][1] in ['r4', 'r8']:
# if next line contains size, this means sizes are different
if lines[i+1].find("Taille") != -1 or lines[i+1].find("Size") != -1:
m_size_eq = False
break
else:
line = [x.strip() for x in lines[i+1].split(";")]
vals = [x.split(":") for x in line]
vals = [[x[0].strip(),x[1].strip()] for x in vals]
tab.append([name.replace("_", "\_"),
vals[1][1],
vals[2][1],
self.threshold])
os.chdir(home)
return tab, m_size_eq
#---------------------------------------------------------------------------
def run_ok(self, run_dir):
"""
Check if a result directory contains an error file
or if it doesn't contain a summary file
"""
if not os.path.isdir(run_dir):
print("Error: the result directory %s does not exist." % run_dir)
sys.exit(1)
msg = ""
ok = True
f_error = os.path.join(run_dir, 'error')
if os.path.isfile(f_error):
ok = False
msg += "the result directory %s in case %s " \
"contains an error file." % (os.path.basename(run_dir),
self.label)
f_summary = os.path.join(run_dir, 'summary')
if not os.path.isfile(f_summary):
ok = False
msg += "the result directory %s in case %s " \
"does not contain any summary file." \
% (os.path.basename(run_dir), self.label)
return ok, msg
#---------------------------------------------------------------------------
def check_dir(self, node, result, rep, attr):
"""
Check coherency between xml file of parameters and repository or
destination.
"""
msg = "Warning: "
if not os.path.isdir(result):
msg += "the directory %s " \
"does not exist." % (result)
return None, msg
# 1. The result directory is given
if rep != "":
# check if it exists
rep_f = os.path.join(result, rep)
if not os.path.isdir(rep_f):
msg += "the result directory %s " \
"does not exist." % (rep_f)
return None, msg
run_ok = self.run_ok(rep_f)
if not run_ok[0]:
return None, msg+run_ok[1]
# 2. The result directory must be found/read automatically;
elif rep == "":
# check if there is at least one result directory.
if len(list(filter(nodot, os.listdir(result)))) == 0:
msg += "there is no result directory in %s." % (result)
return None, msg
# if no run_id is specified in the xml file
# only one result directory allowed in RESU
if len(list(filter(nodot, os.listdir(result)))) > 1 \
and self.run_id == "":
msg += "there are several result directories in %s " \
"and no run id specified." % (result)
return None, msg
rep = self.run_id
# if no run_id is specified in the xml file
# the only result directory present in RESU is taken
if rep == "":
rep = list(filter(nodot, os.listdir(result)))[0]
rep_f = os.path.join(result, rep)
if not os.path.isdir(rep_f):
msg += "the result directory %s " \
"does not exist." % (rep_f)
return None, msg
run_ok = self.run_ok(rep_f)
if not run_ok[0]:
return None, msg+run_ok[1]
# 3. Update the file of parameters with the name of the result directory
if node:
self.__parser.setAttribute(node, attr, rep)
return rep, None
def check_dirs(self, node, repo, dest, reference=None):
"""
Check coherency between xml file of parameters and repository and destination.
"""
msg = None
if repo != None:
# build path to RESU directory with path to study and case label in the repo
if reference:
result = os.path.join(reference, self.label, self.resu)
else:
result = os.path.join(self.__repo, self.label, self.resu)
rep, msg = self.check_dir(node, result, repo, "repo")
if dest != None:
# build path to RESU directory with path to study and case label in the dest
result = os.path.join(self.__dest, self.label, self.resu)
rep, msg = self.check_dir(node, result, dest, "dest")
return msg
#===============================================================================
# Study class
#===============================================================================
class Study(object):
"""
Create, run and compare all cases for a given study.
"""
def __init__(self, pkg, parser, study, exe, dif, rlog, n_procs=None,
force_rm=False, force_overwrite=False, with_tags=None,
without_tags=None, debug=False):
"""
Constructor.
1. initialize attributes,
2. build the list of the cases,
3. build the list of the keywords from the runcase.
@type parser: C{Parser}
@param parser: instance of the parser
@type study: C{String}
@param study: label of the current study
@type exe: C{String}
@param exe: name of the solver executable: C{code_saturne} or C{neptune_cfd}.
@type dif: C{String}
@param dif: name of the diff executable: C{cs_io_dump -d}.
@n_procs: C{int}
@param n_procs: number of requested processors
@type force_rm: C{True} or C{False}
@param force_rm: remove always existing cases
@type force_overwrite: C{True} or C{False}
@param force_overwrite: overwrite files in dest by files in repo
@type with_tags: C{List}
@param with_tags: list of tags given at the command line
@type without_tags: C{List}
@param without_tags: list of tags given at the command line
@type debug: C{True} or C{False}
@param debug: if true, increase verbosity in stdout
"""
# Initialize attributes
self.__package = pkg
self.__parser = parser
self.__main_exe = exe
self.__diff = dif
self.__log = rlog
self.__force_rm = force_rm
self.__force_ow = force_overwrite
self.__debug = debug
self.__repo = os.path.join(self.__parser.getRepository(), study)
self.__dest = os.path.join(self.__parser.getDestination(), study)
if not os.path.isdir(self.__repo):
print("Error: the directory %s does not exist" % self.__repo)
sys.exit(1)
self.label = study
self.cases = []
self.matplotlib_figures = []
self.input_figures = []
self.case_labels = []
# get list of cases in study
on_cases = parser.getStatusOnCasesLabels(study)
if not on_cases:
print("\n\n\nWarning: no case defined in %s study\n\n\n" % study)
else:
for data in self.__parser.getStatusOnCasesKeywords(self.label):
# n_procs given in smgr command line overwrites n_procs by case
if n_procs:
data['n_procs'] = str(n_procs)
# check if every tag passed by option --with-tags belongs to
# list of tags of the current case
tagged = False
if with_tags and data['tags']:
tagged = all(tag in data['tags'] for tag in with_tags)
elif not with_tags:
tagged = True
# check if none of tags passed by option --without-tags
# belong to list of tags of the current case
exclude = False
if without_tags and data['tags']:
exclude = any(tag in data['tags'] for tag in without_tags)
# do not append case if tags do not match
if tagged and not exclude:
c = Case(pkg,
self.__log,
self.__diff,
self.__parser,
self.label,
data,
self.__repo,
self.__dest)
self.cases.append(c)
self.case_labels.append(c.label)
#---------------------------------------------------------------------------
def create_case(self, c, log_lines):
"""
Create a case in a study
"""
e = os.path.join(c.pkg.get_dir('bindir'), c.exe)
if c.subdomains:
os.mkdir(c.label)
os.chdir(c.label)
refdir = os.path.join(self.__repo, c.label)
retval = 1
for node in os.listdir(refdir):
ref = os.path.join(self.__repo, c.label, node)
if node in c.subdomains:
cmd = e + " create --case " + node \
+ " --quiet --noref --copy-from " \
+ ref
node_retval, t = run_studymanager_command(cmd, self.__log)
# negative retcode is kept
retval = min(node_retval,retval)
elif os.path.isdir(ref):
shutil.copytree(ref, node, symlinks=True)
else:
shutil.copy2(ref, node)
c.update_runcase_path(c.label, destdir=self.__dest)
os.chdir(self.__dest)
else:
cmd = e + " create --case " + c.label \
+ " --quiet --noref --copy-from " \
+ os.path.join(self.__repo, c.label)
retval, t = run_studymanager_command(cmd, self.__log)
if retval == 0:
log_lines += [' - create case: ' + c.label]
else:
log_lines += [' - create case: %s --> FAILED' % c.label]
#---------------------------------------------------------------------------
def create_cases(self):
"""
Create a single study with all its cases.
"""
repbase = os.getcwd()
# Create study if necessary
if not os.path.isdir(self.__dest):
# build instance of study class from cs_create
cr_study = cs_create.Study(self.__package,
self.label,
[], # cases
[], # syrthes cases
None, # aster cases
None, # cathare case
None, # python case
None, # copy
False,# import_only
False,# use ref
0) # quiet
# TODO: copy-from for study. For now, an empty study
# is created and cases are created one by one with
# copy-from
# create empty study
cr_study.create()
# Link meshes and copy other files
ref = os.path.join(self.__repo, "MESH")
if os.path.isdir(ref):
l = os.listdir(ref)
meshes = []
for cpr in ["", ".gz"]:
for fmt in ["unv",
"med",
"ccm",
"cgns",
"neu",
"msh",
"des"]:
meshes += fnmatch.filter(l, "*." + fmt + cpr)
des = os.path.join(self.__dest, "MESH")
for m in l:
if m in meshes:
if sys.platform.startswith('win'):
shutil.copy2(os.path.join(ref, m), os.path.join(des, m))
else:
os.symlink(os.path.join(ref, m), os.path.join(des, m))
elif m != ".svn":
t = os.path.join(ref, m)
if os.path.isdir(t):
shutil.copytree(t, os.path.join(des, m))
elif os.path.isfile(t):
shutil.copy2(t, des)
# Copy external scripts for post-processing
ref = os.path.join(self.__repo, "POST")
if os.path.isdir(ref):
des = os.path.join(self.__dest, "POST")
shutil.rmtree(des)
shutil.copytree(ref, des, symlinks=True)
# Change directory to destination directory
os.chdir(self.__dest)
log_lines = []
for c in self.cases:
if not os.path.isdir(c.label):
self.create_case(c, log_lines);
else:
if self.__force_rm == True:
if self.__debug:
print("Warning: case %s exists in the destination "
"and will be overwritten." % c.label)
# Build short path to RESU dir. such as 'CASE1/RESU'
_dest_resu_dir = os.path.join(c.label, 'RESU')
if os.path.isdir(_dest_resu_dir):
shutil.rmtree(_dest_resu_dir)
os.makedirs(_dest_resu_dir)
else:
if self.__debug:
print("Warning: case %s exists in the destination. "
"It won't be overwritten." % c.label)
# if overwrite option enabled, overwrite content of DATA, SRC, SCRIPTS
if self.__force_ow:
dirs_to_overwrite = ["DATA", "SRC", "SCRIPTS"]
self.overwriteDirectories(dirs_to_overwrite,
case_label=c.label)
# update path in gui script
data_subdir = os.path.join(c.label, "DATA")
c.update_gui_script_path(data_subdir, self.__dest,
xmlonly=False)
# update path in runcase script
scripts_subdir = os.path.join(c.label, "SCRIPTS")
c.update_runcase_path(scripts_subdir, self.__dest,
xmlonly=False)
os.chdir(repbase)
if self.__force_ow:
dirs_to_overwrite = ["POST", "MESH"]
self.overwriteDirectories(dirs_to_overwrite)
return log_lines
#---------------------------------------------------------------------------
def overwriteDirectories(self, dirs_to_overwrite, case_label=""):
"""
Overwrite given directories in the Study tree.
Label of case is an empty string by default.
"""
for _dir in dirs_to_overwrite:
ref = os.path.join(self.__repo, case_label, _dir)
if os.path.isdir(ref):
dest = os.path.join(self.__dest, case_label, _dir)
for _ref_dir, _dirs, _files in os.walk(ref):
_dest_dir = _ref_dir.replace(ref, dest, 1)
for _file in _files:
_ref_file = os.path.join(_ref_dir, _file)
_dest_file = os.path.join(_dest_dir, _file)
if os.path.isfile(_dest_file):
os.remove(_dest_file)
shutil.copy2(_ref_file, _dest_dir)
#---------------------------------------------------------------------------
def getRunDirectories(self):
list_cases = []
list_dir = []
for case in self.cases:
if case.is_run != "KO":
list_cases.append(case.label)
list_dir.append(case.run_dir)
return " ".join(list_cases), " ".join(list_dir)
#---------------------------------------------------------------------------
def disable_case(self, case):
try:
self.cases.remove(case)
self.case_labels.remove(case.label)
except Exception:
pass
msg = " - Case %s" % (case.label)
if case.run_id != "":
msg += ", run id %s" % (case.run_id)
msg += " --> DISABLED"
return msg
#---------------------------------------------------------------------------
def needs_report_detailed(self, postpro):
"""
check if study needs a section in the detailed report
(for figures, comparison or input)
"""
# study has figures or input figures
needs = self.matplotlib_figures or self.input_figures
for case in self.cases:
if case.is_compare == "done":
needs = True
break
# handle the input nodes that are inside case nodes
if case.plot == "on" and case.is_run != "KO":
nodes = self.__parser.getChildren(case.node, "input")
if nodes:
needs = True
break
# handle the input nodes that are inside postpro nodes
if postpro:
script, label, nodes, args = self.__parser.getPostPro(self.label)
for i in range(len(label)):
if script[i]:
input_nodes = self.__parser.getChildren(nodes[i], "input")
if input_nodes:
needs = True
break
return needs
#===============================================================================
# Studies class
#===============================================================================
class Studies(object):
"""
Manage all Studies and all Cases described in the files of parameters.
"""
def __init__(self, pkg, options, exe, dif):
"""
Constructor.
1. create if necessary the destination directory,
2. initialize the parser and the plotter,
3. build the list of the studies,
4. start the report.
@type options: C{Structure}
@param options: structure the parameters options.
@type exe: C{String}
@param exe: name of the solver executable: C{code_saturne} or C{neptune_cfd}.
@type dif: C{String}
@param dif: name of the diff executable: C{cs_io_dump -d}.
"""
# try to determine if current directory is a study one
cwd = os.getcwd()
is_study = isStudy(cwd)
studyd = None
studyp = None
if is_study:
# default study directory is current one
studyp = cwd
# Create file of parameters
filename = options.filename
if options.create_xml and is_study:
if filename == None:
studyd = os.path.basename(studyp)
filename = "smgr_" + studyd + ".xml"
filepath = os.path.join(studyp, filename)
smgr = create_base_xml_file(filepath)
init_xml_file_with_study(smgr, studyp)
elif options.create_xml and not is_study:
msg = "Can not create XML file of parameter:\n" \
+ "current directory is apparently not a study (no MESH directory).\n"
sys.exit(msg)
if filename == None:
msg = "A file of parameters must be specified or created " \
+ "for studymanager to run.\n" \
+ "See help message and use '--file' or '--create-xml' option.\n"
sys.exit(msg)
# create a first xml parser only for
# the repository verification and
# the destination creation
if os.path.isfile(filename):
self.__parser = Parser(filename)
else:
msg = "Specified XML parameter file for studymanager does not exist.\n"
sys.exit(msg)
self.__xmlupdate = options.update_xml
# set repository
if len(options.repo_path) > 0:
self.__parser.setRepository(options.repo_path)
self.__repo = self.__parser.getRepository()
if self.__repo:
if not os.path.isdir(self.__repo):
msg="Studies.__init__() >> self.__repo = {0}\n".format(self.__repo)
sys.exit(msg+"Error: repository path is not valid.\n")
else: # default value
# if current directory is a study
# set repository as directory containing the study
if is_study:
studyd = os.path.basename(studyp)
self.__parser.setRepository(os.path.join(studyp,".."))
self.__repo = self.__parser.getRepository()
else:
msg = "Can not set a default repository directory:\n" \
+ "current directory is apparently not a study (no MESH directory).\n" \
+ "Add a repository path to the parameter file or use the command " \
+ "line option (--repo=..).\n"
sys.exit(msg)
# set destination
if self.__xmlupdate:
self.__dest = self.__repo
else:
if len(options.dest_path) > 0:
self.__parser.setDestination(options.dest_path)
self.__dest = self.__parser.getDestination()
if not self.__dest: # default value
# if current directory is a study
# set destination as a directory "../RUN_(study_name)
if is_study and studyd != None:
self.__parser.setDestination(os.path.join(studyp,
"../RUN_"+studyd))
self.__dest = self.__parser.getDestination()
else:
msg = "Can not set a default destination directory:\n" \
+ "current directory is apparently not a study (no MESH directory).\n" \
+ "Add a destination path to the parameter file or use the command " \
+ "line option (--dest=..).\n"
sys.exit(msg)
# create if necessary the destination directory
if not os.path.isdir(self.__dest):
os.makedirs(self.__dest)
# copy the xml file of parameters for update and restart
file = os.path.join(self.__dest, os.path.basename(filename))
try:
shutil.copyfile(filename, file)
except:
pass
# create a new parser, which is definitive and the plotter
self.__parser = Parser(file)
self.__parser.setDestination(self.__dest)
self.__parser.setRepository(self.__repo)
if options.debug:
print(" Studies >> Repository >> ", self.__repo)
print(" Studies >> Destination >> ", self.__dest)
try:
self.__plotter = Plotter(self.__parser)
except Exception:
self.__plotter = None
# create list of restricting and excluding tags
self.__with_tags = None
if options.with_tags:
with_tags = re.split(',', options.with_tags)
self.__with_tags = [tag.strip() for tag in with_tags]
self.__without_tags = None
if options.without_tags:
without_tags = re.split(',', options.without_tags)
self.__without_tags = [tag.strip() for tag in without_tags]
# build the list of the studies
doc = os.path.join(self.__dest, options.log_file)
self.__log = open(doc, "w")
self.labels = self.__parser.getStudiesLabel()
self.studies = []
for l in self.labels:
self.studies.append( [l, Study(pkg, self.__parser, l, \
exe, dif, self.__log, \
options.n_procs, \
options.remove_existing, \
options.force_overwrite, \
self.__with_tags, \
self.__without_tags, \
options.debug)] )
if options.debug:
print(" >> Append study ", l)
# start the report
self.report = os.path.join(self.__dest, "report.txt")
self.reportFile = open(self.report, mode='w')
self.reportFile.write('\n')
# attributes
self.__debug = options.debug
self.__quiet = options.quiet
self.__running = options.runcase
self.__n_iter = options.n_iterations
self.__compare = options.compare
self.__ref = options.reference
self.__postpro = options.post
self.__default_fmt = options.default_fmt
# do not use tex in matplotlib (built-in mathtext is used instead)
self.__dis_tex = options.disable_tex
# tex reports compilation with pdflatex
self.__pdflatex = not options.disable_pdflatex
# in case of restart
iok = 0
for l, s in self.studies:
for case in s.cases:
if case.compute == 'on':
iok+=1
if not iok:
self.__running = False
if self.__xmlupdate:
os.remove(file)
os.remove(doc)
#---------------------------------------------------------------------------
def getDestination(self):
"""
@rtype: C{String}
@return: destination directory of all studies.
"""
if self.__dest == None:
msg=" cs_studymanager_study.py >> Studies.getDestination()"
msg+=" >> self.__dest is not set"
sys.exit(msg)
return self.__dest
#---------------------------------------------------------------------------
def getRepository(self):
"""
@rtype: C{String}
@return: repository directory of all studies.
"""
if self.__repo == None:
msg=" cs_studymanager_study.py >> Studies.getRepository()"
msg+=" >> self.__repo is not set"
sys.exit(msg)
return self.__repo
#---------------------------------------------------------------------------
def reporting(self, msg, stdout=True, report=True, status=False):
"""
Write message on standard output and/or in report.
@type l: C{String}
@param l: the sentence to be written.
"""
s = ""
if not status:
s = chr(10)
if stdout and not self.__quiet:
sys.stdout.write (msg + chr(13) + s)
sys.stdout.flush()
if report:
self.reportFile.write(msg + '\n')
self.reportFile.flush()
#---------------------------------------------------------------------------
def report_action_location(self, header_msg, destination=True):
"""
Add a message to report/stdout at head of sections
specifying if action is performed in dest or repo.
"""
if destination:
header_msg = header_msg + " (in destination)"
else:
header_msg = header_msg + " (in repository)"
self.reporting(header_msg)
#---------------------------------------------------------------------------
def updateRepository(self, xml_only=False):
"""
Update all studies and all cases.
"""
for l, s in self.studies:
self.reporting(' o Update repository: ' + l)
for case in s.cases:
self.reporting(' - update %s' % case.label)
case.update(xml_only)
self.reporting('')
#---------------------------------------------------------------------------
def create_studies(self):
"""
Create all studies and all cases.
"""
for l, s in self.studies:
create_msg = " o Create study " + l
dest = True
self.report_action_location(create_msg, dest)
log_lines = s.create_cases()
for line in log_lines:
self.reporting(line)
self.reporting('')
#---------------------------------------------------------------------------
def test_compilation(self):
"""
Compile sources of all runs with compute attribute at on.
"""
iko = 0
for l, s in self.studies:
# build study dir. (in repo.)
study_path = os.path.join(self.__repo, l)
self.reporting(' o Compile study: ' + l)
for case in s.cases:
if case.compute == 'on':
# test compilation (logs are redirected to smgr log file)
is_compiled = case.test_compilation(study_path, self.__log)
# report
if is_compiled == "OK":
self.reporting(' - compile %s --> OK' % case.label)
elif is_compiled == "KO":
self.reporting(' - compile %s --> FAILED' % case.label)
iko+=1
self.reporting('')
if iko:
self.reporting('Error: compilation failed for %s case(s).\n' % iko)
sys.exit(1)
#---------------------------------------------------------------------------
def prepro(self, l, s, case):
"""
Launch external additional scripts with arguments.
"""
pre, label, nodes, args = self.__parser.getPrepro(case.node)
if self.__debug:
print(" >> prepro ", pre)
print(" >> label ", label)
print(" >> nodes ", nodes)
print(" >> args ", args)
for i in range(len(label)):
if pre[i]:
# search if the script is in the MESH directory
# if not, the script is searched in the directories
# of the current case
cmd = os.path.join(self.__dest, l, "MESH", label[i])
if self.__debug:
print("Path to prepro script ", cmd)
if not os.path.isfile(cmd):
filePath = ""
for root, dirs, fs in os.walk(os.path.join(self.__dest, l, case.label)):
if label[i] in fs:
filePath = root
break
cmd = os.path.join(filePath, label[i])
if os.path.isfile(cmd):
sc_name = os.path.basename(cmd)
# ensure script is executable
set_executable(cmd)
cmd += " " + args[i]
cmd += " -c " + os.path.join(self.__dest, l, case.label)
repbase = os.getcwd()
os.chdir(os.path.join(self.__dest, l, "MESH"))
# Prepro external script often need install python directory
# and package python directory: code_saturne or neptune_cfd
p_dir = case.pkg.get_dir('pythondir')
pkg_dir = case.pkg.get_dir('pkgpythondir')
p_dirs = p_dir + ":" + pkg_dir
# if package is neptune_cfd, prepro script often needs
# code_saturne package python directory
cs_pkg_dir = None
if case.pkg.name == 'neptune_cfd':
cs_pkg_dir = os.path.join(pkg_dir, '../code_saturne')
cs_pkg_dir = os.path.normpath(cs_pkg_dir)
p_dirs = p_dirs + ":" + cs_pkg_dir
retcode, t = run_studymanager_command(cmd,
self.__log,
pythondir = p_dirs)
stat = "FAILED" if retcode != 0 else "OK"
os.chdir(repbase)
self.reporting(' - script %s --> %s (%s s)' % (stat, sc_name, t),
stdout=True, report=False)
self.reporting(' - script %s --> %s (%s s)' % (stat, cmd, t),
stdout=False, report=True)
else:
self.reporting(' - script %s not found' % cmd)
#---------------------------------------------------------------------------
def run(self):
"""
Update and run all cases.
Warning, if the markup of the case is repeated in the xml file of parameters,
the run of the case is also repeated.
"""
for l, s in self.studies:
self.reporting(" o Prepro scripts and runs for study: " + l)
for case in s.cases:
self.prepro(l, s, case)
if self.__running:
if case.compute == 'on' and case.is_compiled != "KO":
if self.__n_iter is not None:
if case.subdomains:
case_dir = os.path.join(self.__dest, s.label, case.label,
case.subdomains[0], "DATA")
else:
case_dir = os.path.join(self.__dest, s.label, case.label, "DATA")
os.chdir(case_dir)
# Create a control_file in each case DATA
if not os.path.exists('control_file'):
control_file = open('control_file','w')
control_file.write("time_step_limit " + str(self.__n_iter) + "\n")
# Flush to ensure that control_file content is seen
# when control_file is copied to the run directory on all systems
control_file.flush()
control_file.close
self.reporting(' - running %s ...' % case.label,
stdout=True, report=False, status=True)
error = case.run()
if case.is_time:
is_time = "%s s" % case.is_time
else:
is_time = "existed already"
if not error:
if not case.run_id:
self.reporting(" - run %s --> Warning suffix"
" is not read" % case.label)
self.reporting(' - run %s --> OK (%s) in %s' \
% (case.label, \
is_time, \
case.run_id))
self.__parser.setAttribute(case.node,
"compute",
"off")
# update dest="" attribute
n1 = self.__parser.getChildren(case.node, "compare")
n2 = self.__parser.getChildren(case.node, "script")
n3 = self.__parser.getChildren(case.node, "data")
n4 = self.__parser.getChildren(case.node, "probe")
n5 = self.__parser.getChildren(case.node, "resu")
n6 = self.__parser.getChildren(case.node, "input")
for n in n1 + n2 + n3 + n4 + n5 + n6:
if self.__parser.getAttribute(n, "dest") == "":
self.__parser.setAttribute(n, "dest", case.run_id)
else:
if not case.run_id:
self.reporting(' - run %s --> FAILED (%s)' \
% (case.label, is_time))
else:
self.reporting(' - run %s --> FAILED (%s) in %s' \
% (case.label, \
is_time, \
case.run_id))
self.__log.flush()
self.reporting('')
#---------------------------------------------------------------------------
def check_compare(self, destination=True):
"""
Check coherency between xml file of parameters and repository.
Stop if you try to make a comparison with a file which does not exist.
"""
for l, s in self.studies:
check_msg = " o Check compare of study: " + l
self.report_action_location(check_msg, destination)
# reference directory passed in studymanager command line overwrites
# destination in all cases (even if compare is defined by a compare
# markup with a non empty destination)
ref = None
if self.__ref:
ref = os.path.join(self.__ref, s.label)
cases_to_disable = []
for case in s.cases:
if case.compare == 'on' and case.is_run != "KO":
compare, nodes, repo, dest, threshold, args = self.__parser.getCompare(case.node)
if compare:
is_checked = False
for i in range(len(nodes)):
if compare[i]:
is_checked = True
if destination == False:
dest[i]= None
msg = case.check_dirs(nodes[i], repo[i], dest[i], reference=ref)
if msg:
self.reporting(msg)
cases_to_disable.append(case)
if not compare or not is_checked:
node = None
repo = ""
dest = ""
if destination == False:
dest = None
msg = case.check_dirs(node, repo, dest, reference=ref)
if msg:
self.reporting(msg)
cases_to_disable.append(case)
for case in cases_to_disable:
msg = s.disable_case(case)
self.reporting(msg)
self.reporting('')
#---------------------------------------------------------------------------
def compare_case_and_report(self, case, repo, dest, threshold, args, reference=None):
"""
Compare the results for one computation and report
"""
case.is_compare = "done"
diff_value, m_size_eq = case.runCompare(self,
repo, dest,
threshold, args,
reference=reference)
case.diff_value += diff_value
case.m_size_eq = case.m_size_eq and m_size_eq
if args:
s_args = 'with args: %s' % args
else:
s_args = 'default mode'
if not m_size_eq:
self.reporting(' - compare %s (%s) --> DIFFERENT MESH SIZES FOUND' % (case.label, s_args))
elif diff_value:
self.reporting(' - compare %s (%s) --> DIFFERENCES FOUND' % (case.label, s_args))
else:
self.reporting(' - compare %s (%s) --> NO DIFFERENCES FOUND' % (case.label, s_args))
#---------------------------------------------------------------------------
def compare(self):
"""
Compare the results of the new computations with those from the Repository.
"""
if self.__compare:
for l, s in self.studies:
self.reporting(' o Compare study: ' + l)
# reference directory passed in studymanager command line overwrites
# destination in all cases (even if compare is defined by a
# compare markup with a non empty destination)
ref = None
if self.__ref:
ref = os.path.join(self.__ref, s.label)
for case in s.cases:
if case.compare == 'on' and case.is_run != "KO":
is_compare, nodes, repo, dest, t, args = self.__parser.getCompare(case.node)
if is_compare:
for i in range(len(nodes)):
if is_compare[i]:
self.compare_case_and_report(case,
repo[i],
dest[i],
t[i],
args[i],
reference=ref)
if not is_compare or case.is_compare != "done":
repo = ""
dest = ""
t = None
args = None
self.compare_case_and_report(case,
repo,
dest,
t,
args,
reference=ref)
self.reporting('')
#---------------------------------------------------------------------------
def check_script(self, destination=True):
"""
Check coherency between xml file of parameters and repository.
Stop if you try to run a script with a file which does not exist.
"""
scripts_checked = False
for l, s in self.studies:
# search for scripts to check before
check_scripts = False
for case in s.cases:
script, label, nodes, args, repo, dest = \
self.__parser.getScript(case.node)
if nodes:
check_scripts = True
break
if not check_scripts:
continue
# if scripts have to be checked
check_msg = " o Check scripts of study: " + l
self.report_action_location(check_msg, destination)
scripts_checked = True
cases_to_disable = []
for case in s.cases:
script, label, nodes, args, repo, dest = \
self.__parser.getScript(case.node)
for i in range(len(nodes)):
if script[i] and case.is_run != "KO":
if destination == False:
dest[i] = None
msg = case.check_dirs(nodes[i], repo[i], dest[i])
if msg:
self.reporting(msg)
cases_to_disable.append(case)
for case in cases_to_disable:
msg = s.disable_case(case)
self.reporting(msg)
if scripts_checked:
self.reporting('')
return scripts_checked
#---------------------------------------------------------------------------
def scripts(self):
"""
Launch external additional scripts with arguments.
"""
for l, s in self.studies:
self.reporting(" o Run scripts of study: " + l)
for case in s.cases:
script, label, nodes, args, repo, dest = self.__parser.getScript(case.node)
for i in range(len(label)):
if script[i] and case.is_run != "KO":
cmd = os.path.join(self.__dest, l, "POST", label[i])
if os.path.isfile(cmd):
sc_name = os.path.basename(cmd)
# ensure script is executable
set_executable(cmd)
cmd += " " + args[i]
if repo[i]:
r = os.path.join(self.__repo, l, case.label, "RESU", repo[i])
cmd += " -r " + r
if dest[i]:
d = os.path.join(self.__dest, l, case.label, "RESU", dest[i])
cmd += " -d " + d
retcode, t = run_studymanager_command(cmd, self.__log)
stat = "FAILED" if retcode != 0 else "OK"
self.reporting(' - script %s --> %s (%s s)' % (stat, sc_name, t),
stdout=True, report=False)
self.reporting(' - script %s --> %s (%s s)' % (stat, cmd, t),
stdout=True, report=False)
else:
self.reporting(' - script %s not found' % cmd)
self.reporting('')
#---------------------------------------------------------------------------
def postpro(self):
"""
Launch external additional scripts with arguments.
"""
for l, s in self.studies:
# fill results directories and ids for the cases of the current study
# that were not run by the current studymanager command
for case in s.cases:
if case.is_run != "KO":
if case.run_dir == "":
resu = os.path.join(self.__dest, l, case.label, case.resu)
rep, msg = case.check_dir(None, resu, "", "dest")
if msg:
self.reporting(msg)
s.disable_case(case)
else:
case.run_id = rep
case.run_dir = os.path.join(resu, rep)
script, label, nodes, args = self.__parser.getPostPro(l)
if not label:
continue
self.reporting(' o Postprocessing cases of study: ' + l)
for i in range(len(label)):
if script[i]:
cmd = os.path.join(self.__dest, l, "POST", label[i])
if os.path.isfile(cmd):
sc_name = os.path.basename(cmd)
# ensure script is executable
set_executable(cmd)
list_cases, list_dir = s.getRunDirectories()
cmd += ' ' + args[i] + ' -c "' + list_cases + '" -d "' \
+ list_dir + '" -s ' + l
self.reporting(' - running postpro %s' % sc_name,
stdout=True, report=False, status=True)
retcode, t = run_studymanager_command(cmd, self.__log)
stat = "FAILED" if retcode != 0 else "OK"
self.reporting(' - postpro %s --> %s (%s s)' \
% (stat, sc_name, t),
stdout=True, report=False)
self.reporting(' - postpro %s --> %s (%s s)' \
% (stat, cmd, t),
stdout=False, report=True)
else:
self.reporting(' - postpro %s not found' % cmd)
self.reporting('')
#---------------------------------------------------------------------------
def check_data(self, case, destination=True):
"""
Check coherency between xml file of parameters and repository
for data markups of a run.
"""
for node in self.__parser.getChildren(case.node, "data"):
plots, file, dest, repo = self.__parser.getResult(node)
if destination == False:
dest = None
msg = case.check_dirs(node, repo, dest)
if msg:
self.reporting(msg)
return False
return True
#---------------------------------------------------------------------------
def check_probes(self, case, destination=True):
"""
Check coherency between xml file of parameters and repository
for probes markups of a run.
"""
for node in self.__parser.getChildren(case.node, "probes"):
file, dest, fig = self.__parser.getProbes(node)
if destination == False:
dest = None
repo = None
msg = case.check_dirs(node, repo, dest)
if msg:
self.reporting(msg)
return False
return True
#---------------------------------------------------------------------------
def check_input(self, case, destination=True):
"""
Check coherency between xml file of parameters and repository
for probes markups of a run.
"""
for node in self.__parser.getChildren(case.node, "input"):
file, dest, repo, tex = self.__parser.getInput(node)
if destination == False:
dest = None
msg = case.check_dirs(node, repo, dest)
if msg:
self.reporting(msg)
return False
return True
#---------------------------------------------------------------------------
def check_plots_and_input(self, destination=True):
"""
Check coherency between xml file of parameters and repository.
Stop if you try to make a plot of a file which does not exist.
"""
for l, s in self.studies:
check_msg = " o Check plots and input of study: " + l
self.report_action_location(check_msg, destination)
cases_to_disable = []
for case in s.cases:
if case.plot == "on" and case.is_run != "KO":
if not self.check_data(case, destination):
cases_to_disable.append(case)
continue
if not self.check_probes(case, destination):
cases_to_disable.append(case)
continue
if not self.check_input(case, destination):
cases_to_disable.append(case)
continue
for case in cases_to_disable:
msg = s.disable_case(case)
self.reporting(msg)
self.reporting('')
#---------------------------------------------------------------------------
def plot(self):
"""
Plot data.
"""
if self.__plotter:
for l, s in self.studies:
self.reporting(' o Plot study: ' + l)
self.__plotter.plot_study(l, s,
self.__dis_tex,
self.__default_fmt)
self.reporting('')
#---------------------------------------------------------------------------
def report_input(self, doc2, i_nodes, s_label, c_label=None):
"""
Add input to report detailed.
"""
for i_node in i_nodes:
f, dest, repo, tex = self.__parser.getInput(i_node)
doc2.appendLine("\\subsubsection{%s}" % f)
if dest:
d = dest
dd = self.__dest
elif repo:
d = repo
dd = self.__repo
else:
d = ""
dd = ""
if c_label:
ff = os.path.join(dd, s_label, c_label, 'RESU', d, f)
else:
ff = os.path.join(dd, s_label, 'POST', d, f)
if not os.path.isfile(ff):
print("\n\nWarning: this file does not exist: %s\n\n" % ff)
elif ff[-4:] in ('.png', '.jpg', '.pdf') or ff[-5:] == '.jpeg':
doc2.addFigure(ff)
elif tex == 'on':
doc2.addTexInput(ff)
else:
doc2.addInput(ff)
#---------------------------------------------------------------------------
def build_reports(self, report1, report2):
"""
@type report1: C{String}
@param report1: name of the global report.
@type report2: C{String}
@param report2: name of the detailed report.
@rtype: C{List} of C{String}
@return: list of file to be attached to the report.
"""
attached_files = []
# First global report
doc1 = Report1(self.__dest,
report1,
self.__log,
self.report,
self.__parser.write(),
self.__pdflatex)
for l, s in self.studies:
for case in s.cases:
if case.diff_value or not case.m_size_eq:
is_nodiff = "KO"
else:
is_nodiff = "OK"
doc1.add_row(l,
case.label,
case.is_compiled,
case.is_run,
case.is_time,
case.is_compare,
is_nodiff)
attached_files.append(doc1.close())
# Second detailed report
if self.__compare or self.__postpro:
doc2 = Report2(self.__dest,
report2,
self.__log,
self.__pdflatex)
for l, s in self.studies:
if not s.needs_report_detailed(self.__postpro):
continue
doc2.appendLine("\\section{%s}" % l)
if s.matplotlib_figures or s.input_figures:
doc2.appendLine("\\subsection{Graphical results}")
for g in s.matplotlib_figures:
doc2.addFigure(g)
for g in s.input_figures:
doc2.addFigure(g)
for case in s.cases:
if case.is_compare == "done":
run_id = None
if case.run_id != "":
run_id = case.run_id
doc2.appendLine("\\subsection{Comparison for case "
"%s (run_id: %s)}"
% (case.label, run_id))
if not case.m_size_eq:
doc2.appendLine("Repository and destination "
"have apparently not been run "
"with the same mesh (sizes do "
"not match).")
elif case.diff_value:
doc2.add_row(case.diff_value, l, case.label)
elif self.__compare:
doc2.appendLine("No difference between the "
"repository and the "
"destination.")
# handle the input nodes that are inside case nodes
if case.plot == "on" and case.is_run != "KO":
nodes = self.__parser.getChildren(case.node, "input")
if nodes:
doc2.appendLine("\\subsection{Results for "
"case %s}" % case.label)
self.report_input(doc2, nodes, l, case.label)
# handle the input nodes that are inside postpro nodes
if self.__postpro:
script, label, nodes, args = self.__parser.getPostPro(l)
needs_pp_input = False
for i in range(len(label)):
if script[i]:
input_nodes = \
self.__parser.getChildren(nodes[i], "input")
if input_nodes:
needs_pp_input = True
break
if needs_pp_input:
doc2.appendLine("\\subsection{Results for "
"post-processing cases}")
for i in range(len(label)):
if script[i]:
input_nodes = \
self.__parser.getChildren(nodes[i], "input")
if input_nodes:
self.report_input(doc2, input_nodes, l)
attached_files.append(doc2.close())
return attached_files
#---------------------------------------------------------------------------
def getlabel(self):
return self.labels
#---------------------------------------------------------------------------
def logs(self):
try:
self.reportFile.close()
except:
pass
self.reportFile = open(self.report, mode='r')
return self.reportFile.read()
#---------------------------------------------------------------------------
def __del__(self):
try:
self.__log.close()
except:
pass
try:
self.reportFile.close()
except:
pass
#-------------------------------------------------------------------------------
|