Salome HOME
Code improvements for warning on iteration control
[modules/adao.git] / src / daComposant / daCore / Interfaces.py
index 53070c6757f16e15b05b98a87976980cb72b919c..d0f203983573bf9d827562136c29def895c72100 100644 (file)
@@ -1,6 +1,6 @@
 # -*- coding: utf-8 -*-
 #
-# Copyright (C) 2008-2020 EDF R&D
+# Copyright (C) 2008-2022 EDF R&D
 #
 # This library is free software; you can redistribute it and/or
 # modify it under the terms of the GNU Lesser General Public
@@ -35,6 +35,7 @@ import copy
 from daCore import Persistence
 from daCore import PlatformInfo
 from daCore import Templates
+from daCore import Reporting
 
 # ==============================================================================
 class GenericCaseViewer(object):
@@ -51,12 +52,26 @@ class GenericCaseViewer(object):
         self._content      = __content
         self._object       = __object
         self._missing = """raise ValueError("This case requires beforehand to import or define the variable named <%s>. When corrected, remove this command, correct and uncomment the following one.")\n# """
+    #------------------------
     def _append(self, *args):
         "Transformation d'une commande individuelle en un enregistrement"
         raise NotImplementedError()
     def _extract(self, *args):
         "Transformation d'enregistrement(s) en commande(s) individuelle(s)"
         raise NotImplementedError()
+    #------------------------------
+    def _initialize(self, __multilines):
+        "Permet des pré-conversions automatiques simples de commandes ou clés"
+        __translation = {
+            "Study_name"          :"StudyName",
+            "Study_repertory"     :"StudyRepertory",
+            "MaximumNumberOfSteps":"MaximumNumberOfIterations",
+            "FunctionDict"        :"ScriptWithSwitch",
+            "FUNCTIONDICT_FILE"   :"SCRIPTWITHSWITCH_FILE",
+        }
+        for k,v in __translation.items():
+            __multilines = __multilines.replace(k,v)
+        return __multilines
     def _finalize(self, __upa=None):
         "Enregistrement du final"
         __hasNotExecute = True
@@ -65,7 +80,7 @@ class GenericCaseViewer(object):
         if __hasNotExecute:
             self._lineSerie.append("%s.execute()"%(self._objname,))
         if __upa is not None and len(__upa)>0:
-            __upa = __upa.replace("ADD.",str(self._objname)+".")
+            __upa = __upa.replace("ADD",str(self._objname))
             self._lineSerie.append(__upa)
     def _addLine(self, line=""):
         "Ajoute un enregistrement individuel"
@@ -87,8 +102,9 @@ class GenericCaseViewer(object):
         "Chargement normalisé des commandes"
         if __filename is not None and os.path.exists(__filename):
             self._content = open(__filename, 'r').read()
+            self._content = self._initialize(self._content)
         elif __content is not None and type(__content) is str:
-            self._content = __content
+            self._content = self._initialize(__content)
         elif __object is not None and type(__object) is dict:
             self._object = copy.deepcopy(__object)
         else:
@@ -131,7 +147,7 @@ class _TUIViewer(GenericCaseViewer):
                 if   k == "ColMajor"             and not __v: continue
                 if   k == "InputFunctionAsMulti" and not __v: continue
                 if   k == "nextStep"             and not __v: continue
-                if   k == "AvoidRC"              and     __v: continue
+                if   k == "PerformanceProfile"   and     __v: continue
                 if   k == "noDetails":                        continue
                 if isinstance(__v,Persistence.Persistence): __v = __v.values()
                 if callable(__v): __text = self._missing%__v.__name__+__text
@@ -182,9 +198,17 @@ class _COMViewer(GenericCaseViewer):
         "Transformation d'enregistrement(s) en commande(s) individuelle(s)"
         __suppparameters = {}
         if __multilines is not None:
+            if 'adaoBuilder' in __multilines:
+                raise ValueError("Impossible to load given content as an ADAO COMM one (Hint: it's perhaps not a COMM input, but a TUI one).")
             if "ASSIMILATION_STUDY" in __multilines:
                 __suppparameters.update({'StudyType':"ASSIMILATION_STUDY"})
                 __multilines = __multilines.replace("ASSIMILATION_STUDY","dict")
+            elif "OPTIMIZATION_STUDY" in __multilines:
+                __suppparameters.update({'StudyType':"ASSIMILATION_STUDY"})
+                __multilines = __multilines.replace("OPTIMIZATION_STUDY",    "dict")
+            elif "REDUCTION_STUDY" in __multilines:
+                __suppparameters.update({'StudyType':"ASSIMILATION_STUDY"})
+                __multilines = __multilines.replace("REDUCTION_STUDY",    "dict")
             elif "CHECKING_STUDY" in __multilines:
                 __suppparameters.update({'StudyType':"CHECKING_STUDY"})
                 __multilines = __multilines.replace("CHECKING_STUDY",    "dict")
@@ -224,7 +248,7 @@ class _COMViewer(GenericCaseViewer):
             #
             elif __command == "UserPostAnalysis" and type(r) is dict:
                 if 'STRING' in r:
-                    __UserPostAnalysis = r['STRING'].replace("ADD.",str(self._objname)+".")
+                    __UserPostAnalysis = r['STRING'].replace("ADD",str(self._objname))
                     __commands.append( "set( Concept='UserPostAnalysis', String=\"\"\"%s\"\"\" )"%(__UserPostAnalysis,) )
                 elif 'SCRIPT_FILE' in r and os.path.exists(r['SCRIPT_FILE']):
                     __UserPostAnalysis = open(r['SCRIPT_FILE'],'r').read()
@@ -273,13 +297,13 @@ class _COMViewer(GenericCaseViewer):
                     if __idata['NodeType'] == 'Template' and 'Template' in __idata:
                         __template = __idata['Template']
                         if 'Info' in __idata:
-                            __info = ", Info='%s'"%(__idata['Info'],)
+                            __info = ", Info=\"\"\"%s\"\"\""%(__idata['Info'],)
                         else:
                             __info = ""
-                        __commands.append( "set( Concept='Observer', Variable='%s', Template='%s'%s )"%(sk,__template,__info) )
+                        __commands.append( "set( Concept='Observer', Variable='%s', Template=\"\"\"%s\"\"\"%s )"%(sk,__template,__info) )
                     if __idata['NodeType'] == 'String' and 'Value' in __idata:
                         __value =__idata['Value']
-                        __commands.append( "set( Concept='Observer', Variable='%s', String='%s' )"%(sk,__value) )
+                        __commands.append( "set( Concept='Observer', Variable='%s', String=\"\"\"%s\"\"\" )"%(sk,__value) )
             #
             # Background, ObservationError, ObservationOperator...
             elif type(r) is dict:
@@ -482,7 +506,7 @@ class _SCDViewer(GenericCaseViewer):
                 elif __k in ('Stored', 'Checked', 'ColMajor', 'InputFunctionAsMulti', 'nextStep'):
                     if bool(__v):
                         __text += "%s_config['%s'] = '%s'\n"%(__command,__k,int(bool(__v)))
-                elif __k in ('AvoidRC', 'noDetails'):
+                elif __k in ('PerformanceProfile', 'noDetails'):
                     if not bool(__v):
                         __text += "%s_config['%s'] = '%s'\n"%(__command,__k,int(bool(__v)))
                 else:
@@ -513,7 +537,7 @@ class _SCDViewer(GenericCaseViewer):
             self._addLine("Analysis_config = {}")
             self._addLine("Analysis_config['From'] = 'String'")
             self._addLine("Analysis_config['Data'] = \"\"\"import numpy")
-            self._addLine("xa=numpy.ravel(ADD.get('Analysis')[-1])")
+            self._addLine("xa=ADD.get('Analysis')[-1]")
             self._addLine("print('Analysis:',xa)\"\"\"")
             self._addLine("study_config['UserPostAnalysis'] = Analysis_config")
     def __loadVariablesByScript(self):
@@ -604,6 +628,76 @@ class _YACSViewer(GenericCaseViewer):
         __fid.close()
         return __text
 
+# ==============================================================================
+class _ReportViewer(GenericCaseViewer):
+    """
+    Partie commune de restitution simple
+    """
+    def __init__(self, __name="", __objname="case", __content=None, __object=None):
+        "Initialisation et enregistrement de l'entete"
+        GenericCaseViewer.__init__(self, __name, __objname, __content, __object)
+        self._r = Reporting.ReportStorage()
+        self._r.clear()
+        if self._name == "":
+            self._r.append("ADAO Study report", "title")
+        else:
+            self._r.append(str(self._name), "title")
+        if self._content is not None:
+            for command in self._content:
+                self._append(*command)
+    def _append(self, __command=None, __keys=None, __local=None, __pre=None, __switchoff=False):
+        "Transformation d'une commande individuelle en un enregistrement"
+        if __command is not None and __keys is not None and __local is not None:
+            if __command in ("set","get") and "Concept" in __keys: __command = __local["Concept"]
+            __text  = ""
+            __text += "<i>%s</i> command has been set"%str(__command.replace("set",""))
+            __ktext = ""
+            for k in __keys:
+                if k not in __local: continue
+                __v = __local[k]
+                if __v is None: continue
+                if   k == "Checked"              and not __v: continue
+                if   k == "Stored"               and not __v: continue
+                if   k == "ColMajor"             and not __v: continue
+                if   k == "InputFunctionAsMulti" and not __v: continue
+                if   k == "nextStep"             and not __v: continue
+                if   k == "PerformanceProfile"   and     __v: continue
+                if   k == "noDetails":                        continue
+                if   k == "Concept":                          continue
+                if   k == "self":                             continue
+                if isinstance(__v,Persistence.Persistence): __v = __v.values()
+                numpy.set_printoptions(precision=15,threshold=1000000,linewidth=1000*15)
+                __ktext += "\n        %s = %s,"%(k,repr(__v))
+                numpy.set_printoptions(precision=8,threshold=1000,linewidth=75)
+            if len(__ktext) > 0:
+                __text += " with values:" + __ktext
+            __text = __text.rstrip(", ")
+            self._r.append(__text, "uli")
+    def _finalize(self, __upa=None):
+        "Enregistrement du final"
+        raise NotImplementedError()
+
+class _SimpleReportInRstViewer(_ReportViewer):
+    """
+    Restitution simple en RST
+    """
+    def _finalize(self, __upa=None):
+        self._lineSerie.append(Reporting.ReportViewInRst(self._r).__str__())
+
+class _SimpleReportInHtmlViewer(_ReportViewer):
+    """
+    Restitution simple en HTML
+    """
+    def _finalize(self, __upa=None):
+        self._lineSerie.append(Reporting.ReportViewInHtml(self._r).__str__())
+
+class _SimpleReportInPlainTxtViewer(_ReportViewer):
+    """
+    Restitution simple en TXT
+    """
+    def _finalize(self, __upa=None):
+        self._lineSerie.append(Reporting.ReportViewInPlainTxt(self._r).__str__())
+
 # ==============================================================================
 class ImportFromScript(object):
     """
@@ -623,8 +717,12 @@ class ImportFromScript(object):
             __basename = __filename.rstrip(".py")
         PlatformInfo.checkFileNameImportability( __basename+".py" )
         self.__basename = __basename
-        self.__filenspace = __import__(__basename, globals(), locals(), [])
-        self.__filestring = open(__filename,'r').read()
+        try:
+            self.__filenspace = __import__(__basename, globals(), locals(), [])
+        except NameError:
+            self.__filenspace = ""
+        with open(__filename,'r') as fid:
+            self.__filestring = fid.read()
     def getvalue(self, __varname=None, __synonym=None ):
         "Renvoie la variable demandee par son nom ou son synonyme"
         if __varname is None:
@@ -681,12 +779,9 @@ class ImportDetector(object):
         else:
             return False
     def is_not_local_file(self):
-        if not os.path.isfile(os.path.realpath(self.__url)):
-            return True
-        else:
-            return False
+        return not self.is_local_file()
     def raise_error_if_not_local_file(self):
-        if not os.path.isfile(os.path.realpath(self.__url)):
+        if self.is_not_local_file():
             raise ValueError("The name or the url of the file object doesn't seem to exist. The given name is:\n  \"%s\""%str(self.__url))
         else:
             return False
@@ -699,12 +794,9 @@ class ImportDetector(object):
         else:
             return False
     def is_not_local_dir(self):
-        if not os.path.isdir(self.__url):
-            return True
-        else:
-            return False
+        return not self.is_local_dir()
     def raise_error_if_not_local_dir(self):
-        if not os.path.isdir(self.__url):
+        if self.is_not_local_dir():
             raise ValueError("The name or the url of the directory object doesn't seem to exist. The given name is:\n  \"%s\""%str(self.__url))
         else:
             return False
@@ -819,7 +911,7 @@ class ImportFromFile(object):
                     __header.append(__line)
                     __skiprows += 1
                     __line = fid.readline().strip()
-                __varsline = __line
+                __varsline = __line # Ligne de labels par convention
                 for i in range(max(0,__nblines)):
                     __header.append(fid.readline())
         return (__header, __varsline, __skiprows)
@@ -867,7 +959,7 @@ class ImportFromFile(object):
         return self.__supportedformats
 
     def getvalue(self, ColNames=None, ColIndex=None ):
-        "Renvoie la ou les variables demandees par la liste de leurs noms"
+        "Renvoie la ou les variables demandées par la liste de leurs noms"
         # Uniquement si mise à jour
         if ColNames is not None: self._colnames = tuple(ColNames)
         if ColIndex is not None: self._colindex = str(ColIndex)
@@ -978,7 +1070,7 @@ class ImportScalarLinesFromFile(ImportFromFile):
             raise ValueError("Unkown file format \"%s\""%self._format)
     #
     def getvalue(self, VarNames = None, HeaderNames=()):
-        "Renvoie la ou les variables demandees par la liste de leurs noms"
+        "Renvoie la ou les variables demandées par la liste de leurs noms"
         if VarNames is not None: __varnames = tuple(VarNames)
         else:                    __varnames = None
         #
@@ -1012,7 +1104,7 @@ class ImportScalarLinesFromFile(ImportFromFile):
             for i in range(1,len(HeaderNames)):
                 __converters[i] = __replaceNone
         else:
-            raise ValueError("Can not find names of columns for initial values. Wrong first line is:\n            \"%s\""%__firstline)
+            raise ValueError("Can not find names of columns for initial values. Wrong first line is:\n            \"%s\""%self._varsline)
         #
         if self._format == "text/plain":
             __content = numpy.loadtxt(self._filename, dtype = __dtypes, usecols = __usecols, skiprows = self._skiprows, converters = __converters)
@@ -1065,6 +1157,9 @@ class EficasGUI(object):
         if "EFICAS_ROOT" in os.environ:
             __EFICAS_ROOT = os.environ["EFICAS_ROOT"]
             __path_ok = True
+        elif "EFICAS_NOUVEAU_ROOT" in os.environ:
+            __EFICAS_ROOT = os.environ["EFICAS_NOUVEAU_ROOT"]
+            __path_ok = True
         else:
             self.__msg += "\nKeyError:\n"+\
                 "  the required environment variable EFICAS_ROOT is unknown.\n"+\