Salome HOME
Minor documentation and code review corrections (38)
[modules/adao.git] / src / daComposant / daCore / Interfaces.py
index 08f497c6d50d3ecde9a4863851e7fa1798fa6cd3..e428417a3fea64e3b3d6c3a09eee73325c7290d9 100644 (file)
@@ -1,6 +1,6 @@
 # -*- coding: utf-8 -*-
 #
-# Copyright (C) 2008-2021 EDF R&D
+# Copyright (C) 2008-2023 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,12 +35,17 @@ import copy
 from daCore import Persistence
 from daCore import PlatformInfo
 from daCore import Templates
+from daCore import Reporting
 
 # ==============================================================================
 class GenericCaseViewer(object):
     """
     Gestion des commandes de création d'une vue de cas
     """
+    __slots__ = (
+        "_name", "_objname", "_lineSerie", "_switchoff", "_content",
+        "_numobservers", "_object", "_missing")
+    #
     def __init__(self, __name="", __objname="case", __content=None, __object=None):
         "Initialisation et enregistrement de l'entete"
         self._name         = str(__name)
@@ -51,27 +56,45 @@ 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
-        for l in self._lineSerie:
-            if "%s.execute"%(self._objname,) in l: __hasNotExecute = False
+        for __l in self._lineSerie:
+            if "%s.execute"%(self._objname,) in __l: __hasNotExecute = False
         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"
         self._lineSerie.append(line)
+    #
     def _get_objname(self):
         return self._objname
+    #
     def dump(self, __filename=None, __upa=None):
         "Restitution normalisée des commandes"
         self._finalize(__upa)
@@ -83,12 +106,14 @@ class GenericCaseViewer(object):
             __fid.write(__text)
             __fid.close()
         return __text
+    #
     def load(self, __filename=None, __content=None, __object=None):
         "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:
@@ -100,6 +125,8 @@ class _TUIViewer(GenericCaseViewer):
     """
     Établissement des commandes d'un cas ADAO TUI (Cas<->TUI)
     """
+    __slots__ = ()
+    #
     def __init__(self, __name="", __objname="case", __content=None, __object=None):
         "Initialisation et enregistrement de l'entete"
         GenericCaseViewer.__init__(self, __name, __objname, __content, __object)
@@ -111,6 +138,7 @@ class _TUIViewer(GenericCaseViewer):
         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:
@@ -131,7 +159,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
@@ -144,6 +172,7 @@ class _TUIViewer(GenericCaseViewer):
             __text = __text.rstrip(", ")
             __text += " )"
             self._addLine(__text)
+    #
     def _extract(self, __multilines="", __object=None):
         "Transformation d'enregistrement(s) en commande(s) individuelle(s)"
         __is_case = False
@@ -166,6 +195,8 @@ class _COMViewer(GenericCaseViewer):
     """
     Établissement des commandes d'un cas COMM (Eficas Native Format/Cas<-COM)
     """
+    __slots__ = ("_observerIndex", "_objdata")
+    #
     def __init__(self, __name="", __objname="case", __content=None, __object=None):
         "Initialisation et enregistrement de l'entete"
         GenericCaseViewer.__init__(self, __name, __objname, __content, __object)
@@ -178,13 +209,22 @@ class _COMViewer(GenericCaseViewer):
         if self._content is not None:
             for command in self._content:
                 self._append(*command)
+    #
     def _extract(self, __multilines=None, __object=None):
         "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,12 +264,12 @@ 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()
                     __commands.append( "set( Concept='UserPostAnalysis', Script='%s' )"%(r['SCRIPT_FILE'],) )
-                elif 'Template' in r and not 'ValueTemplate' in r:
+                elif 'Template' in r and 'ValueTemplate' not in r:
                     # AnalysisPrinter...
                     if r['Template'] not in Templates.UserPostAnalysisTemplates:
                         raise ValueError("User post-analysis template \"%s\" does not exist."%(r['Template'],))
@@ -328,6 +368,10 @@ class _SCDViewer(GenericCaseViewer):
 
     Remarque : le fichier généré est différent de celui obtenu par EFICAS
     """
+    __slots__ = (
+        "__DebugCommandNotSet", "__ObserverCommandNotSet",
+        "__UserPostAnalysisNotSet", "__hasAlgorithm")
+    #
     def __init__(self, __name="", __objname="case", __content=None, __object=None):
         "Initialisation et enregistrement de l'entête"
         GenericCaseViewer.__init__(self, __name, __objname, __content, __object)
@@ -361,6 +405,7 @@ class _SCDViewer(GenericCaseViewer):
         if __content is not None:
             for command in __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 == "set": __command = __local["Concept"]
@@ -429,8 +474,10 @@ class _SCDViewer(GenericCaseViewer):
                 __local.pop(__k)
             for __k,__v in __local.items():
                 if __k == "Concept": continue
-                if __k in ['ScalarSparseMatrix','DiagonalSparseMatrix','Matrix','OneFunction','ThreeFunctions'] and 'Script' in __local and __local['Script'] is not None: continue
-                if __k in ['Vector','VectorSerie'] and 'DataFile' in __local and __local['DataFile'] is not None: continue
+                if __k in ['ScalarSparseMatrix','DiagonalSparseMatrix','Matrix','OneFunction','ThreeFunctions'] \
+                    and 'Script' in __local and __local['Script'] is not None: continue
+                if __k in ['Vector','VectorSerie'] \
+                    and 'DataFile' in __local and __local['DataFile'] is not None: continue
                 if __k == 'Parameters' and not (__command in ['AlgorithmParameters','SupplementaryParameters']): continue
                 if __k == 'Algorithm':
                     __text += "study_config['Algorithm'] = %s\n"%(repr(__v))
@@ -482,7 +529,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:
@@ -504,6 +551,7 @@ class _SCDViewer(GenericCaseViewer):
         if __text is not None: self._addLine(__text)
         if not __switchoff:
             self._switchoff = False
+    #
     def _finalize(self, *__args):
         self.__loadVariablesByScript()
         if self.__DebugCommandNotSet:
@@ -513,9 +561,10 @@ 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):
         __ExecVariables = {} # Necessaire pour recuperer la variable
         exec("\n".join(self._lineSerie), __ExecVariables)
@@ -565,11 +614,14 @@ class _YACSViewer(GenericCaseViewer):
     """
     Etablissement des commandes d'un cas YACS (Cas->SCD->YACS)
     """
+    __slots__ = ("__internalSCD", "_append")
+    #
     def __init__(self, __name="", __objname="case", __content=None, __object=None):
         "Initialisation et enregistrement de l'entete"
         GenericCaseViewer.__init__(self, __name, __objname, __content, __object)
         self.__internalSCD = _SCDViewer(__name, __objname, __content, __object)
         self._append       = self.__internalSCD._append
+    #
     def dump(self, __filename=None, __upa=None):
         "Restitution normalisée des commandes"
         # -----
@@ -583,7 +635,7 @@ class _YACSViewer(GenericCaseViewer):
         if not PlatformInfo.has_salome or \
             not PlatformInfo.has_adao:
             raise ImportError(
-                "Unable to get SALOME or ADAO environnement for YACS conversion.\n"+\
+                "Unable to get SALOME (%s) or ADAO (%s) environnement for YACS conversion.\n"%(PlatformInfo.has_salome,PlatformInfo.has_adao)+\
                 "Please load the right SALOME environnement before trying to use it.")
         else:
             from daYacsSchemaCreator.run import create_schema_from_content
@@ -604,18 +656,101 @@ class _YACSViewer(GenericCaseViewer):
         __fid.close()
         return __text
 
+# ==============================================================================
+class _ReportViewer(GenericCaseViewer):
+    """
+    Partie commune de restitution simple
+    """
+    __slots__ = ("_r")
+    #
+    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
+    """
+    __slots__ = ()
+    #
+    def _finalize(self, __upa=None):
+        self._lineSerie.append(Reporting.ReportViewInRst(self._r).__str__())
+
+class _SimpleReportInHtmlViewer(_ReportViewer):
+    """
+    Restitution simple en HTML
+    """
+    __slots__ = ()
+    #
+    def _finalize(self, __upa=None):
+        self._lineSerie.append(Reporting.ReportViewInHtml(self._r).__str__())
+
+class _SimpleReportInPlainTxtViewer(_ReportViewer):
+    """
+    Restitution simple en TXT
+    """
+    __slots__ = ()
+    #
+    def _finalize(self, __upa=None):
+        self._lineSerie.append(Reporting.ReportViewInPlainTxt(self._r).__str__())
+
 # ==============================================================================
 class ImportFromScript(object):
     """
     Obtention d'une variable nommee depuis un fichier script importé
     """
     __slots__ = ("__basename", "__filenspace", "__filestring")
+    #
     def __init__(self, __filename=None):
         "Verifie l'existence et importe le script"
         if __filename is None:
             raise ValueError("The name of the file, containing the variable to be read, has to be specified.")
         if not os.path.isfile(__filename):
-            raise ValueError("The file containing the variable to be imported doesn't seem to exist. Please check the file. The given file name is:\n  \"%s\""%str(__filename))
+            raise ValueError(
+                "The file containing the variable to be imported doesn't seem to"+\
+                " exist. Please check the file. The given file name is:\n  \"%s\""%str(__filename))
         if os.path.dirname(__filename) != '':
             sys.path.insert(0, os.path.dirname(__filename))
             __basename = os.path.basename(__filename).rstrip(".py")
@@ -629,19 +764,27 @@ class ImportFromScript(object):
             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:
             raise ValueError("The name of the variable to be read has to be specified. Please check the content of the file and the syntax.")
         if not hasattr(self.__filenspace, __varname):
             if __synonym is None:
-                raise ValueError("The imported script file \"%s\" doesn't contain the mandatory variable \"%s\" to be read. Please check the content of the file and the syntax."%(str(self.__basename)+".py",__varname))
+                raise ValueError(
+                    "The imported script file \"%s\""%(str(self.__basename)+".py",)+\
+                    " doesn't contain the mandatory variable \"%s\""%(__varname,)+\
+                    " to be read. Please check the content of the file and the syntax.")
             elif not hasattr(self.__filenspace, __synonym):
-                raise ValueError("The imported script file \"%s\" doesn't contain the mandatory variable \"%s\" to be read. Please check the content of the file and the syntax."%(str(self.__basename)+".py",__synonym))
+                raise ValueError(
+                    "The imported script file \"%s\""%(str(self.__basename)+".py",)+\
+                    " doesn't contain the mandatory variable \"%s\""%(__synonym,)+\
+                    " to be read. Please check the content of the file and the syntax.")
             else:
                 return getattr(self.__filenspace, __synonym)
         else:
             return getattr(self.__filenspace, __varname)
+    #
     def getstring(self):
         "Renvoie le script complet"
         return self.__filestring
@@ -651,10 +794,12 @@ class ImportDetector(object):
     """
     Détection des caractéristiques de fichiers ou objets en entrée
     """
-    __slots__ = (
-        "__url", "__usr", "__root", "__end")
-    def __enter__(self): return self
-    def __exit__(self, exc_type, exc_val, exc_tb): return False
+    __slots__ = ("__url", "__usr", "__root", "__end")
+    #
+    def __enter__(self):
+        return self
+    def __exit__(self, exc_type, exc_val, exc_tb):
+        return False
     #
     def __init__(self, __url, UserMime=""):
         if __url is None:
@@ -684,13 +829,12 @@ class ImportDetector(object):
             return True
         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
@@ -702,13 +846,12 @@ class ImportDetector(object):
             return True
         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
@@ -718,10 +861,12 @@ class ImportDetector(object):
     def get_standard_mime(self):
         (__mtype, __encoding) = mimetypes.guess_type(self.__url, strict=False)
         return __mtype
+    #
     def get_user_mime(self):
         __fake = "fake."+self.__usr.lower()
         (__mtype, __encoding) = mimetypes.guess_type(__fake, strict=False)
         return __mtype
+    #
     def get_comprehensive_mime(self):
         if self.get_standard_mime() is not None:
             return self.get_standard_mime()
@@ -734,8 +879,10 @@ class ImportDetector(object):
     # ----------------------
     def get_user_name(self):
         return self.__url
+    #
     def get_absolute_name(self):
         return os.path.abspath(os.path.realpath(self.__url))
+    #
     def get_extension(self):
         return self.__end
 
@@ -756,8 +903,12 @@ class ImportFromFile(object):
         "_filename", "_colnames", "_colindex", "_varsline", "_format",
         "_delimiter", "_skiprows", "__url", "__filestring", "__header",
         "__allowvoid", "__binaryformats", "__supportedformats")
-    def __enter__(self): return self
-    def __exit__(self, exc_type, exc_val, exc_tb): return False
+    #
+    def __enter__(self):
+        return self
+    #
+    def __exit__(self, exc_type, exc_val, exc_tb):
+        return False
     #
     def __init__(self, Filename=None, ColNames=None, ColIndex=None, Format="Guess", AllowVoidNameList=True):
         """
@@ -808,7 +959,7 @@ class ImportFromFile(object):
         else:                    self._colindex = None
         #
         self.__allowvoid = bool(AllowVoidNameList)
-
+    #
     def __getentete(self, __nblines = 3):
         "Lit l'entête du fichier pour trouver la définition des variables"
         # La première ligne non vide non commentée est toujours considérée
@@ -823,11 +974,11 @@ 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)
-
+    #
     def __getindices(self, __colnames, __colindex, __delimiter=None ):
         "Indices de colonnes correspondants à l'index et aux variables"
         if __delimiter is None:
@@ -859,7 +1010,7 @@ class ImportFromFile(object):
             __useindex = None
         #
         return (__usecols, __useindex)
-
+    #
     def getsupported(self):
         self.__supportedformats = {}
         self.__supportedformats["text/plain"]                = True
@@ -869,9 +1020,9 @@ class ImportFromFile(object):
         self.__supportedformats["application/numpy.npz"]     = True
         self.__supportedformats["application/dymola.sdf"]    = PlatformInfo.has_sdf
         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)
@@ -941,7 +1092,7 @@ class ImportFromFile(object):
         else:
             raise ValueError("Unkown file format \"%s\" or no reader available"%self._format)
         if __columns is None: __columns = ()
-        #
+
         def toString(value):
             try:
                 return value.decode()
@@ -951,7 +1102,7 @@ class ImportFromFile(object):
             __index = tuple([toString(v) for v in __index])
         #
         return (self._colnames, __columns, self._colindex, __index)
-
+    #
     def getstring(self):
         "Renvoie le fichier texte complet"
         if self._format in self.__binaryformats:
@@ -959,7 +1110,7 @@ class ImportFromFile(object):
         else:
             with open(self._filename,'r') as fid:
                 return fid.read()
-
+    #
     def getformat(self):
         return self._format
 
@@ -973,8 +1124,13 @@ class ImportScalarLinesFromFile(ImportFromFile):
 
     Seule la méthode "getvalue" est changée.
     """
-    def __enter__(self): return self
-    def __exit__(self, exc_type, exc_val, exc_tb): return False
+    __slots__ = ()
+    #
+    def __enter__(self):
+        return self
+    #
+    def __exit__(self, exc_type, exc_val, exc_tb):
+        return False
     #
     def __init__(self, Filename=None, ColNames=None, ColIndex=None, Format="Guess"):
         ImportFromFile.__init__(self, Filename, ColNames, ColIndex, Format)
@@ -982,7 +1138,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
         #
@@ -991,9 +1147,11 @@ class ImportScalarLinesFromFile(ImportFromFile):
             __dtypes   = {'names'  : ('Name', 'Value', 'Minimum', 'Maximum'),
                           'formats': ('S128', 'g', 'g', 'g')}
             __usecols  = (0, 1, 2, 3)
+
             def __replaceNoneN( s ):
                 if s.strip() == b'None': return numpy.NINF
                 else:                    return s
+
             def __replaceNoneP( s ):
                 if s.strip() == b'None': return numpy.PINF
                 else:                    return s
@@ -1009,6 +1167,7 @@ class ImportScalarLinesFromFile(ImportFromFile):
             __dtypes   = {'names'  : HeaderNames,
                           'formats': tuple(['S128',]+['g']*(len(HeaderNames)-1))}
             __usecols  = tuple(range(len(HeaderNames)))
+
             def __replaceNone( s ):
                 if s.strip() == b'None': return numpy.NAN
                 else:                    return s
@@ -1016,12 +1175,25 @@ 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)
+            __content = numpy.loadtxt(
+                self._filename,
+                dtype      = __dtypes,
+                usecols    = __usecols,
+                skiprows   = self._skiprows,
+                converters = __converters,
+                )
         elif self._format in ["text/csv", "text/tab-separated-values"]:
-            __content = numpy.loadtxt(self._filename, dtype = __dtypes, usecols = __usecols, skiprows = self._skiprows, converters = __converters, delimiter = self._delimiter)
+            __content = numpy.loadtxt(
+                self._filename,
+                dtype      = __dtypes,
+                usecols    = __usecols,
+                skiprows   = self._skiprows,
+                converters = __converters,
+                delimiter  = self._delimiter,
+                )
         else:
             raise ValueError("Unkown file format \"%s\""%self._format)
         #
@@ -1061,21 +1233,26 @@ class EficasGUI(object):
     """
     Lancement autonome de l'interface EFICAS/ADAO
     """
+    __slots__ = ("__msg", "__path_settings_ok")
+    #
     def __init__(self, __addpath = None):
         # Chemin pour l'installation (ordre important)
         self.__msg = ""
         self.__path_settings_ok = False
         #----------------
-        if "EFICAS_ROOT" in os.environ:
-            __EFICAS_ROOT = os.environ["EFICAS_ROOT"]
+        if "EFICAS_TOOLS_ROOT" in os.environ:
+            __EFICAS_TOOLS_ROOT = os.environ["EFICAS_TOOLS_ROOT"]
+            __path_ok = True
+        elif "EFICAS_NOUVEAU_ROOT" in os.environ:
+            __EFICAS_TOOLS_ROOT = os.environ["EFICAS_NOUVEAU_ROOT"]
             __path_ok = True
         else:
             self.__msg += "\nKeyError:\n"+\
-                "  the required environment variable EFICAS_ROOT is unknown.\n"+\
-                "  You have either to be in SALOME environment, or to set\n"+\
-                "  this variable in your environment to the right path \"<...>\"\n"+\
-                "  to find an installed EFICAS application. For example:\n"+\
-                "      EFICAS_ROOT=\"<...>\" command\n"
+                "  the required environment variable EFICAS_TOOLS_ROOT is unknown.\n"+\
+                "  You have either to be in SALOME environment, or to set this\n"+\
+                "  variable in your environment to the right path \"<...>\" to\n"+\
+                "  find an installed EFICAS application. For example:\n"+\
+                "      EFICAS_TOOLS_ROOT=\"<...>\" command\n"
             __path_ok = False
         try:
             import adao
@@ -1115,7 +1292,7 @@ class EficasGUI(object):
             self.__path_settings_ok = True
         #----------------
         if self.__path_settings_ok:
-            sys.path.insert(0,__EFICAS_ROOT)
+            sys.path.insert(0,__EFICAS_TOOLS_ROOT)
             sys.path.insert(0,os.path.join(adao.adao_py_dir,"daEficas"))
             if __addpath is not None and os.path.exists(os.path.abspath(__addpath)):
                 sys.path.insert(0,os.path.abspath(__addpath))
@@ -1123,7 +1300,7 @@ class EficasGUI(object):
         else:
             print(self.__msg)
             logging.debug("Errors in path settings have been found")
-
+    #
     def gui(self):
         if self.__path_settings_ok:
             logging.debug("Launching standalone EFICAS/ADAO interface...")