File: cs_studymanager.py

package info (click to toggle)
code-saturne 6.0.2-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 63,340 kB
  • sloc: ansic: 354,724; f90: 119,812; python: 87,716; makefile: 4,653; cpp: 4,272; xml: 2,839; sh: 1,228; lex: 170; yacc: 100
file content (416 lines) | stat: -rw-r--r-- 15,136 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
#!/usr/bin/env python
# -*- 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 string
import getpass
import platform

from optparse import OptionParser
from datetime import datetime, date

import smtplib

try: # email version 3.0 (Python2 up to 2.6)
    from email.Utils import COMMASPACE, formatdate
    from email import Encoders
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email.MIMEText import MIMEText
except Exception: # email version 4.0 (Python2 from Python 2.5)
    from email.utils import COMMASPACE, formatdate
    from email import encoders
    from email.mime.multipart import MIMEMultipart
    from email.mime.base import MIMEBase
    from email.mime.text import MIMEText

#-------------------------------------------------------------------------------
# Application modules import
#-------------------------------------------------------------------------------

# Do not import studymanager yet, as it pulls Python packages such as
# matplotlib which may not be in the standard path, and may need
# sourcing of a specific environment (which itself is delayed in case
# the main and coputation packages are not the same).

#-------------------------------------------------------------------------------
# Processes the passed command line arguments
#-------------------------------------------------------------------------------

def process_cmd_line(argv, pkg):
    """
    Processes the passed command line arguments.
    """

    usage = "usage: %prog studymanager <options>"
    parser = OptionParser(usage=usage)

    parser.add_option("-f", "--file", dest="filename", type="string",
                      metavar="FILE", help="xml FILE of parameters")

    parser.add_option("-q", "--quiet",
                      action="store_true", dest="quiet", default=False,
                      help="don't print status messages to stdout")

    parser.add_option("-u", "--update",
                      action="store_true", dest="update", default=False,
                      help="update scripts in the repository")

    parser.add_option("-x", "--update-xml",
                      action="store_true", dest="update_xml", default=False,
                      help="update only xml files in the repository")

    parser.add_option("-t", "--test-compilation",
                      action="store_true", dest="test_compilation",
                      default=False, help="compile all cases")

    parser.add_option("-r", "--run",
                      action="store_true", dest="runcase", default=False,
                      help="run all cases")

    parser.add_option("--n-procs",  dest="n_procs", default=None, type="int",
                      help="Optional number of processors requested for the computations")

    parser.add_option("-n", "--n-iterations", dest="n_iterations",
                      type="int", help="maximum number of iterations for cases of the study")

    parser.add_option("-c", "--compare",
                      action="store_true", dest="compare", default=False,
                      help="compare results between repository and destination")

    parser.add_option("-d", "--ref-dir", dest="reference", type="string",
                      help="absolute reference directory to compare dest with")

    parser.add_option("-p", "--post",
                      action="store_true", dest="post", default=False,
                      help="postprocess results of computations")

    parser.add_option("-m", "--mail", dest="addresses", default="",
                      type="string", metavar="ADDRESS1 ADDRESS2 ...",
                      help="addresses for sending the reports")

    parser.add_option("-l", "--log", dest="log_file", default="studymanager.log",
                      type="string",
                      help="name of studymanager log file (default value is 'studymanager.log'")

    parser.add_option("-z", "--disable-tex",
                      action="store_true", dest="disable_tex", default=False,
                      help="disable text rendering with LaTex in Matplotlib (use Mathtext)")

    parser.add_option("--rm",
                      action="store_true", dest="remove_existing", default=False,
                      help="remove existing run directories")

    parser.add_option("--fow",
                      action="store_true", dest="force_overwrite", default=False,
                      help="overwrite files in MESH and POST directories")

    parser.add_option("-s", "--skip-pdflatex", default=False,
                      action="store_true", dest="disable_pdflatex",
                      help="disable tex reports compilation with pdflatex")

    parser.add_option("--fmt", type="string",
                      dest="default_fmt", default="pdf",
                      help="set the global format for exporting matplotlib figure (default is pdf)")

    parser.add_option("--repo", type="string",
                      dest="repo_path", default="",
                      help="Force path to repository directory")

    parser.add_option("--dest", type="string",
                      dest="dest_path", default="",
                      help="Force path to destination directory")

    parser.add_option("-g", "--debug", action="store_true",
                      dest="debug", default=False,
                      help="activate debugging mode")

    parser.add_option("--with-tags", type="string",
                      dest="with_tags", default="",
                      help="only process runs with all specified tags (separated by commas)")

    parser.add_option("--without-tags", type="string",
                      dest="without_tags", default="",
                      help="exclude any run with one of specified tags (separated by commas)")

    parser.add_option("--create-xml", action="store_true",
                      dest="create_xml", default=False,
                      help="create xml from study (current directory has to be a study)")

    if len(argv)==0:
        parser.print_help(sys.stderr)
        sys.exit(1)

    (options, args) = parser.parse_args(argv)

    return  options

#-------------------------------------------------------------------------------
# Send the report.
#-------------------------------------------------------------------------------

def send_report(code_name, report, labels, to, files):
    """
    Build the mail to be send.
    """
    # Note that the TO variable must be a list, and that you have
    # to add the From, To, and Subject headers to the message yourself.
    # The TO argument to the sendmail method is only used to route the
    # message to the right recipients, and doesn't have to match the headers
    # in the message itself. This can be used to implement Bcc headers; to send
    # a blind copy, add the address to the TO argument, but do not include
    # it in the To header.

    if code_name == "Code_Saturne":
        FROM    = "saturne-support@edf.fr"
    else:
        FROM    = "neptune-cfd-support@edf.fr"

    SERVER  = "localhost"
    TO      = to
    SUBJECT = "%s. Study Manager %s: %s " % (code_name, date.today(), labels)
    TEXT    = report
    RETOUR  = "An error occurs during the sending of the log mail"
    FILES   = files
    MESSAGE = """From: %s\nTo: %s\nSubject: %s\n\n%s""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
    retour = "\n"

    try:
        send_mail(FROM, TO, SUBJECT, MESSAGE, FILES, SERVER)
    except:
        send_mail(FROM, TO, "[ERROR] %s" % SUBJECT, retour, [], SERVER)

#-------------------------------------------------------------------------------
# Send an email
#-------------------------------------------------------------------------------

def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
    """
    Send the report by mail.
    """
    assert type(send_to) == list
    assert type(files)   == list

    msg = MIMEMultipart()
    msg['From']    = send_from
    msg['To']      = COMMASPACE.join(send_to)
    msg['Date']    = formatdate(localtime=True)
    msg['Subject'] = subject
    msg.attach( MIMEText(text) )

    for f in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(f,"rb").read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition',
                        'attachment; filename="%s"' % os.path.basename(f))
        msg.attach(part)

    smtp = smtplib.SMTP(server)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()

#-------------------------------------------------------------------------------
# Helper to find the release of Linux
#-------------------------------------------------------------------------------

def release():
    p = "/etc/issue"
    if os.path.isfile(p):
        f = open(p, 'r')
        issue = f.read()[:-1]
        f.close()
    else:
        issue = ""
    return issue

#-------------------------------------------------------------------------------
# Start point of studymanager script
#-------------------------------------------------------------------------------

def run_studymanager(pkg, options):
    """
    Main function
      1. parse the command line,
      2. read the file of parameters
      3. create all studies,
      4. compile sources
      5. run all cases
      6. compare results
      7. plot result
      8. reporting by mail
    """

    # Source environment if required before importing studymanager modules, as
    # it pulls Python packages such as matplotlib which may not be in
    # the standard path.
    from cs_exec_environment import set_modules, source_rcfile, enquote_arg
    set_modules(pkg)
    source_rcfile(pkg)

    from studymanager.cs_studymanager_study import Studies

    # Scripts

    exe = os.path.join(pkg.get_dir('bindir'), pkg.name)
    if sys.platform.startswith('win'):
        exe = exe + ".com"
    exe = enquote_arg(exe)

    dif = pkg.get_io_dump()

    for p in exe, dif:
        if not os.path.isfile(p):
            print("Error: executable %s not found." % p)
            if not sys.platform.startswith('win'):
                return 1

    dif += " -d"

    # Read the file of parameters

    studies = Studies(pkg, options, exe, dif)
    if options.debug:
        print(" run_studymanager() >> Studies are initialized")
    if options.update_xml == False:
        os.chdir(studies.getDestination())
    else:
        os.chdir(studies.getRepository())

    # Print header

    studies.reporting(" -------------")
    studies.reporting(" Study Manager")
    studies.reporting(" -------------\n")
    studies.reporting(" Code name:         " + pkg.name)
    studies.reporting(" Kernel version:    " + pkg.version)
    studies.reporting(" Install directory: " + pkg.get_dir('exec_prefix'))
    studies.reporting(" File dump:         " + dif)

    studies.reporting("\n Informations:")
    studies.reporting(" -------------\n")
    studies.reporting(" Date:                   " + datetime.now().strftime("%A %B %d %H:%M:%S %Y"))
    studies.reporting(" Platform:               " + platform.platform())
    studies.reporting(" Computer:               " + platform.uname()[1] + "  " + release())
    studies.reporting(" Process Id:             " + str(os.getpid()))
    studies.reporting(" User name:              " + getpass.getuser())
    studies.reporting(" Repository:             " + studies.getRepository())
    dest = studies.getDestination()
    studies.reporting(" Destination:            " + dest)
    doc = os.path.join(dest, options.log_file)
    studies.reporting(" Ext. subprocesses logs: " + doc)
    studies.reporting("\n")

    # Update repository if needed

    if options.update:
        studies.updateRepository()

    # Update only xml data if needed

    if options.update_xml:
        studies.updateRepository(True)

    # Test sources compilation for all cases

    if options.test_compilation:
        studies.test_compilation()

    # Check if xml for result directories in the repository are OK

    if options.compare:
        studies.check_compare(destination=False)

    if options.post:
        studies.check_script(destination=False)
        studies.check_plots_and_input(destination=False)

    # Create all studies and all cases

    if options.compare or options.post or options.runcase:
        studies.create_studies()

    # Preprocessing and run all cases
    if options.debug:
        print(" run_studymanager() >> Starts running...")

    if options.runcase:
        studies.run()

    if options.debug:
        print(" run_studymanager() >> Exits runs")

    # Compare checkpoint files

    if options.compare:
        studies.check_compare()
        studies.compare()

    # Postprocess results and probes

    if options.post:
        checked_scripts = studies.check_script()
        if checked_scripts:
            studies.scripts()
        studies.check_plots_and_input()
        studies.postpro()
        studies.plot()

    studies.reporting("\n --------------------")
    studies.reporting(" End of Study Manager")
    studies.reporting(" --------------------")

    # Reporting - attached files are either pdf or
    # raw tex files if pdflatex is disabled
    attached_file = studies.build_reports("report_global",
                                          "report_detailed")

    if len(options.addresses.split()) > 0:
        send_report(pkg.code_name, studies.logs(),
                    studies.getlabel(),
                    options.addresses.split(),
                    attached_file)

    return 0

#-------------------------------------------------------------------------------
# Main
#-------------------------------------------------------------------------------

def main(argv, pkg):
    """
    Main function.
    """

    options = process_cmd_line(argv, pkg)

    retcode = run_studymanager(pkg, options)
    sys.exit(retcode)

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