From: Jean-Philippe ARGAUD Date: Thu, 30 May 2024 14:37:36 +0000 (+0200) Subject: Sysinfo update and complements X-Git-Tag: V9_13_0a1~4 X-Git-Url: http://git.salome-platform.org/gitweb/?a=commitdiff_plain;h=ba10f8e363eb8fb27636cf611acc9b97742bd0fc;p=modules%2Fadao.git Sysinfo update and complements --- diff --git a/src/daComposant/daAlgorithms/DerivativeFreeOptimization.py b/src/daComposant/daAlgorithms/DerivativeFreeOptimization.py index c5c2a57..b9abbc2 100644 --- a/src/daComposant/daAlgorithms/DerivativeFreeOptimization.py +++ b/src/daComposant/daAlgorithms/DerivativeFreeOptimization.py @@ -24,6 +24,7 @@ import numpy, logging, scipy.optimize from daCore import BasicObjects, PlatformInfo from daCore.NumericObjects import ApplyBounds, ForceNumericBounds from daCore.PlatformInfo import vfloat +lpi = PlatformInfo.PlatformInfo() # ============================================================================== class ElementaryAlgorithm(BasicObjects.Algorithm): @@ -140,7 +141,7 @@ class ElementaryAlgorithm(BasicObjects.Algorithm): def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None): self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q) # - if not PlatformInfo.has_nlopt and not self._parameters["Minimizer"] in ["COBYLA", "POWELL", "SIMPLEX"]: + if not lpi.has_nlopt and not self._parameters["Minimizer"] in ["COBYLA", "POWELL", "SIMPLEX"]: logging.warning( "%s Minimization by SIMPLEX is forced because %s "%(self._name, self._parameters["Minimizer"]) + \ "is unavailable (COBYLA, POWELL are also available)") @@ -238,7 +239,7 @@ class ElementaryAlgorithm(BasicObjects.Algorithm): full_output = True, disp = self._parameters["optdisp"], ) - elif self._parameters["Minimizer"] == "COBYLA" and not PlatformInfo.has_nlopt: + elif self._parameters["Minimizer"] == "COBYLA" and not lpi.has_nlopt: def make_constraints(bounds): constraints = [] for (i, (a, b)) in enumerate(bounds): @@ -262,7 +263,7 @@ class ElementaryAlgorithm(BasicObjects.Algorithm): catol = 2. * self._parameters["StateVariationTolerance"], disp = self._parameters["optdisp"], ) - elif self._parameters["Minimizer"] == "COBYLA" and PlatformInfo.has_nlopt: + elif self._parameters["Minimizer"] == "COBYLA" and lpi.has_nlopt: import nlopt opt = nlopt.opt(nlopt.LN_COBYLA, Xini.size) @@ -289,7 +290,7 @@ class ElementaryAlgorithm(BasicObjects.Algorithm): print("%s: optimal state: %s"%(opt.get_algorithm_name(), Minimum)) print("%s: minimum of J: %s"%(opt.get_algorithm_name(), opt.last_optimum_value())) print("%s: return code: %i"%(opt.get_algorithm_name(), opt.last_optimize_result())) - elif self._parameters["Minimizer"] == "SIMPLEX" and not PlatformInfo.has_nlopt: + elif self._parameters["Minimizer"] == "SIMPLEX" and not lpi.has_nlopt: Minimum, J_optimal, niter, nfeval, rc = scipy.optimize.fmin( func = CostFunction, x0 = Xini, @@ -301,7 +302,7 @@ class ElementaryAlgorithm(BasicObjects.Algorithm): full_output = True, disp = self._parameters["optdisp"], ) - elif self._parameters["Minimizer"] == "SIMPLEX" and PlatformInfo.has_nlopt: + elif self._parameters["Minimizer"] == "SIMPLEX" and lpi.has_nlopt: import nlopt opt = nlopt.opt(nlopt.LN_NELDERMEAD, Xini.size) @@ -328,7 +329,7 @@ class ElementaryAlgorithm(BasicObjects.Algorithm): print("%s: optimal state: %s"%(opt.get_algorithm_name(), Minimum)) print("%s: minimum of J: %s"%(opt.get_algorithm_name(), opt.last_optimum_value())) print("%s: return code: %i"%(opt.get_algorithm_name(), opt.last_optimize_result())) - elif self._parameters["Minimizer"] == "BOBYQA" and PlatformInfo.has_nlopt: + elif self._parameters["Minimizer"] == "BOBYQA" and lpi.has_nlopt: import nlopt opt = nlopt.opt(nlopt.LN_BOBYQA, Xini.size) @@ -355,7 +356,7 @@ class ElementaryAlgorithm(BasicObjects.Algorithm): print("%s: optimal state: %s"%(opt.get_algorithm_name(), Minimum)) print("%s: minimum of J: %s"%(opt.get_algorithm_name(), opt.last_optimum_value())) print("%s: return code: %i"%(opt.get_algorithm_name(), opt.last_optimize_result())) - elif self._parameters["Minimizer"] == "NEWUOA" and PlatformInfo.has_nlopt: + elif self._parameters["Minimizer"] == "NEWUOA" and lpi.has_nlopt: import nlopt opt = nlopt.opt(nlopt.LN_NEWUOA, Xini.size) @@ -382,7 +383,7 @@ class ElementaryAlgorithm(BasicObjects.Algorithm): print("%s: optimal state: %s"%(opt.get_algorithm_name(), Minimum)) print("%s: minimum of J: %s"%(opt.get_algorithm_name(), opt.last_optimum_value())) print("%s: return code: %i"%(opt.get_algorithm_name(), opt.last_optimize_result())) - elif self._parameters["Minimizer"] == "SUBPLEX" and PlatformInfo.has_nlopt: + elif self._parameters["Minimizer"] == "SUBPLEX" and lpi.has_nlopt: import nlopt opt = nlopt.opt(nlopt.LN_SBPLX, Xini.size) diff --git a/src/daComposant/daAlgorithms/ReducedModelingTest.py b/src/daComposant/daAlgorithms/ReducedModelingTest.py index d94faf4..db627a7 100644 --- a/src/daComposant/daAlgorithms/ReducedModelingTest.py +++ b/src/daComposant/daAlgorithms/ReducedModelingTest.py @@ -25,8 +25,9 @@ import daCore from daCore import BasicObjects, PlatformInfo from daCore.NumericObjects import FindIndexesFromNames, SingularValuesEstimation from daAlgorithms.Atoms import eosg -mpr = PlatformInfo.PlatformInfo().MachinePrecision() -mfp = PlatformInfo.PlatformInfo().MaximumPrecision() +lpi = PlatformInfo.PlatformInfo() +mpr = lpi.MachinePrecision() +mfp = lpi.MaximumPrecision() # ============================================================================== class ElementaryAlgorithm(BasicObjects.Algorithm): @@ -315,7 +316,7 @@ class ElementaryAlgorithm(BasicObjects.Algorithm): if cut1pi > 0: msgs += __marge + "Representing more than 99.99%s of variance requires at least %i mode(s).\n"%("%", cut1pi) # - if PlatformInfo.has_matplotlib and self._parameters["PlotAndSave"]: + if lpi.has_matplotlib and self._parameters["PlotAndSave"]: # Evite les message debug de matplotlib dL = logging.getLogger().getEffectiveLevel() logging.getLogger().setLevel(logging.WARNING) diff --git a/src/daComposant/daCore/ExtendedLogging.py b/src/daComposant/daCore/ExtendedLogging.py index 8a8d226..5918581 100644 --- a/src/daComposant/daCore/ExtendedLogging.py +++ b/src/daComposant/daCore/ExtendedLogging.py @@ -117,27 +117,27 @@ class ExtendedLogging(object): # # Initialise l'affichage de logging # --------------------------------- - p = PlatformInfo.PlatformInfo() + lpi = PlatformInfo.PlatformInfo() # logging.info( "--------------------------------------------------" ) - logging.info( p.getName() + " version " + p.getVersion() ) + logging.info( lpi.getName() + " version " + lpi.getVersion() ) logging.info( "--------------------------------------------------" ) logging.info( "Library availability:" ) logging.info( "- Python.......: True" ) - logging.info( "- Numpy........: " + str(PlatformInfo.has_numpy) ) - logging.info( "- Scipy........: " + str(PlatformInfo.has_scipy) ) - logging.info( "- Matplotlib...: " + str(PlatformInfo.has_matplotlib) ) - logging.info( "- Gnuplot......: " + str(PlatformInfo.has_gnuplot) ) - logging.info( "- Sphinx.......: " + str(PlatformInfo.has_sphinx) ) - logging.info( "- Nlopt........: " + str(PlatformInfo.has_nlopt) ) + logging.info( "- Numpy........: " + str(lpi.has_numpy) ) + logging.info( "- Scipy........: " + str(lpi.has_scipy) ) + logging.info( "- Matplotlib...: " + str(lpi.has_matplotlib) ) + logging.info( "- Gnuplot......: " + str(lpi.has_gnuplot) ) + logging.info( "- Sphinx.......: " + str(lpi.has_sphinx) ) + logging.info( "- Nlopt........: " + str(lpi.has_nlopt) ) logging.info( "Library versions:" ) - logging.info( "- Python.......: " + p.getPythonVersion() ) - logging.info( "- Numpy........: " + p.getNumpyVersion() ) - logging.info( "- Scipy........: " + p.getScipyVersion() ) - logging.info( "- Matplotlib...: " + p.getMatplotlibVersion() ) - logging.info( "- Gnuplot......: " + p.getGnuplotVersion() ) - logging.info( "- Sphinx.......: " + p.getSphinxVersion() ) - logging.info( "- Nlopt........: " + p.getNloptVersion() ) + logging.info( "- Python.......: " + lpi.getPythonVersion() ) + logging.info( "- Numpy........: " + lpi.getNumpyVersion() ) + logging.info( "- Scipy........: " + lpi.getScipyVersion() ) + logging.info( "- Matplotlib...: " + lpi.getMatplotlibVersion() ) + logging.info( "- Gnuplot......: " + lpi.getGnuplotVersion() ) + logging.info( "- Sphinx.......: " + lpi.getSphinxVersion() ) + logging.info( "- Nlopt........: " + lpi.getNloptVersion() ) logging.info( "" ) def setLogfile(self, filename=LOGFILE, filemode="w", level=logging.NOTSET): diff --git a/src/daComposant/daCore/Interfaces.py b/src/daComposant/daCore/Interfaces.py index b2a2f82..eaa9024 100644 --- a/src/daComposant/daCore/Interfaces.py +++ b/src/daComposant/daCore/Interfaces.py @@ -37,6 +37,7 @@ from daCore import PlatformInfo from daCore import Templates from daCore import Reporting from daCore import version +lpi = PlatformInfo.PlatformInfo() # ============================================================================== class GenericCaseViewer(object): @@ -667,10 +668,9 @@ class _YACSViewer(GenericCaseViewer): if os.path.isfile(__file) or os.path.islink(__file): os.remove(__file) # ----- - if not PlatformInfo.has_salome or \ - not PlatformInfo.has_adao: + if not lpi.has_salome or not lpi.has_adao: raise ImportError( - "Unable to get SALOME (%s) or ADAO (%s) environnement for YACS conversion.\n"%(PlatformInfo.has_salome, PlatformInfo.has_adao) + \ + "Unable to get SALOME (%s) or ADAO (%s) environnement for YACS conversion.\n"%(lpi.has_salome, lpi.has_adao) + \ "Please load the right SALOME environnement before trying to use it.") else: from daYacsSchemaCreator.run import create_schema_from_content @@ -1070,7 +1070,7 @@ class ImportFromFile(object): self.__supportedformats["text/tab-separated-values"] = True self.__supportedformats["application/numpy.npy"] = True self.__supportedformats["application/numpy.npz"] = True - self.__supportedformats["application/dymola.sdf"] = PlatformInfo.has_sdf + self.__supportedformats["application/dymola.sdf"] = lpi.has_sdf return self.__supportedformats def getvalue(self, ColNames=None, ColIndex=None ): @@ -1111,7 +1111,7 @@ class ImportFromFile(object): if __usecols is None: # Si une variable demandée n'existe pas self._colnames = None # - elif self._format == "application/dymola.sdf" and PlatformInfo.has_sdf: + elif self._format == "application/dymola.sdf" and lpi.has_sdf: import sdf __content = sdf.load(self._filename) __columns = None diff --git a/src/daComposant/daCore/Persistence.py b/src/daComposant/daCore/Persistence.py index 92e2fbc..9bb55de 100644 --- a/src/daComposant/daCore/Persistence.py +++ b/src/daComposant/daCore/Persistence.py @@ -31,9 +31,11 @@ import os, numpy, copy, math import gzip, bz2, pickle from daCore.PlatformInfo import PathManagement ; PathManagement() # noqa: E702,E203 -from daCore.PlatformInfo import has_gnuplot, PlatformInfo -mfp = PlatformInfo().MaximumPrecision() -if has_gnuplot: +from daCore.PlatformInfo import PlatformInfo +lpi = PlatformInfo() +mfp = lpi.MaximumPrecision() + +if lpi.has_gnuplot: import Gnuplot # ============================================================================== @@ -472,7 +474,7 @@ class Persistence(object): "Préparation des plots" # # Vérification de la disponibilité du module Gnuplot - if not has_gnuplot: + if not lpi.has_gnuplot: raise ImportError("The Gnuplot module is required to plot the object.") # # Vérification et compléments sur les paramètres d'entrée @@ -704,7 +706,7 @@ class Persistence(object): """ # # Vérification de la disponibilité du module Gnuplot - if not has_gnuplot: + if not lpi.has_gnuplot: raise ImportError("The Gnuplot module is required to plot the object.") # # Vérification et compléments sur les paramètres d'entrée diff --git a/src/daComposant/daCore/PlatformInfo.py b/src/daComposant/daCore/PlatformInfo.py index c265cc1..b28bd2c 100644 --- a/src/daComposant/daCore/PlatformInfo.py +++ b/src/daComposant/daCore/PlatformInfo.py @@ -51,17 +51,56 @@ import socket import locale import logging import re +import numpy + +# ============================================================================== +def uniq( __sequence ): + """ + Fonction pour rendre unique chaque élément d'une liste, en préservant l'ordre + """ + __seen = set() + return [x for x in __sequence if x not in __seen and not __seen.add(x)] + +class PathManagement(object): + """ + Mise à jour du path système pour les répertoires d'outils + """ + __slots__ = ("__paths") + + def __init__(self): + "Déclaration des répertoires statiques" + parent = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) + self.__paths = {} + self.__paths["daNumerics"] = os.path.join(parent, "daNumerics") + # + for v in self.__paths.values(): + if os.path.isdir(v): + sys.path.insert(0, v ) + # + # Conserve en unique exemplaire chaque chemin + sys.path = uniq( sys.path ) + del parent + + def getpaths(self): + """ + Renvoie le dictionnaire des chemins ajoutés + """ + return self.__paths # ============================================================================== class PlatformInfo(object): """ Rassemblement des informations sur le code et la plateforme """ - __slots__ = () + __slots__ = ("has_salome", "has_yacs", "has_adao", "has_eficas") def __init__(self): "Sans effet" - pass + self.has_salome = bool( "SALOME_ROOT_DIR" in os.environ ) + self.has_yacs = bool( "YACS_ROOT_DIR" in os.environ ) + self.has_adao = bool( "ADAO_ROOT_DIR" in os.environ ) + self.has_eficas = bool( "EFICAS_ROOT_DIR" in os.environ ) + PathManagement() def getName(self): "Retourne le nom de l'application" @@ -178,6 +217,131 @@ class PlatformInfo(object): "Retourne la version de python disponible" return ".".join([str(x) for x in sys.version_info[0:3]]) # map(str,sys.version_info[0:3])) + # Tests des modules système + + def _has_numpy(self): + try: + import numpy # noqa: F401 + has_numpy = True + except ImportError: + raise ImportError("Numpy is not available, despites the fact it is mandatory.") + return has_numpy + has_numpy = property(fget = _has_numpy) + + def _has_scipy(self): + try: + import scipy + import scipy.version + import scipy.optimize # noqa: F401 + has_scipy = True + except ImportError: + has_scipy = False + return has_scipy + has_scipy = property(fget = _has_scipy) + + def _has_matplotlib(self): + try: + import matplotlib # noqa: F401 + has_matplotlib = True + except ImportError: + has_matplotlib = False + return has_matplotlib + has_matplotlib = property(fget = _has_matplotlib) + + def _has_sphinx(self): + try: + import sphinx # noqa: F401 + has_sphinx = True + except ImportError: + has_sphinx = False + return has_sphinx + has_sphinx = property(fget = _has_sphinx) + + def _has_nlopt(self): + try: + import nlopt # noqa: F401 + has_nlopt = True + except ImportError: + has_nlopt = False + return has_nlopt + has_nlopt = property(fget = _has_nlopt) + + def _has_sdf(self): + try: + import sdf # noqa: F401 + has_sdf = True + except ImportError: + has_sdf = False + return has_sdf + has_sdf = property(fget = _has_sdf) + + def _has_fmpy(self): + try: + import fmpy # noqa: F401 + has_fmpy = True + except ImportError: + has_fmpy = False + return has_fmpy + has_fmpy = property(fget = _has_fmpy) + + def _has_buildingspy(self): + try: + import buildingspy # noqa: F401 + has_buildingspy = True + except ImportError: + has_buildingspy = False + return has_buildingspy + has_buildingspy = property(fget = _has_buildingspy) + + def _has_control(self): + try: + import control # noqa: F401 + has_control = True + except ImportError: + has_control = False + return has_control + has_control = property(fget = _has_control) + + def _has_modelicares(self): + try: + import modelicares # noqa: F401 + has_modelicares = True + except ImportError: + has_modelicares = False + return has_modelicares + has_modelicares = property(fget = _has_modelicares) + + # Tests des modules locaux + + def _has_gnuplot(self): + try: + import Gnuplot # noqa: F401 + has_gnuplot = True + except ImportError: + has_gnuplot = False + return has_gnuplot + has_gnuplot = property(fget = _has_gnuplot) + + def _has_models(self): + try: + import Models # noqa: F401 + has_models = True + except ImportError: + has_models = False + return has_models + has_models = property(fget = _has_models) + + def _has_linkmod(self): + try: + import LinkMod # noqa: F401 + has_linkmod = True + except ImportError: + has_linkmod = False + return has_linkmod + has_linkmod = property(fget = _has_linkmod) + + # Versions + def getNumpyVersion(self): "Retourne la version de numpy disponible" import numpy.version @@ -185,7 +349,8 @@ class PlatformInfo(object): def getScipyVersion(self): "Retourne la version de scipy disponible" - if has_scipy: + if self.has_scipy: + import scipy __version = scipy.version.version else: __version = "0.0.0" @@ -193,7 +358,8 @@ class PlatformInfo(object): def getMatplotlibVersion(self): "Retourne la version de matplotlib disponible" - if has_matplotlib: + if self.has_matplotlib: + import matplotlib __version = matplotlib.__version__ else: __version = "0.0.0" @@ -201,7 +367,8 @@ class PlatformInfo(object): def getGnuplotVersion(self): "Retourne la version de gnuplotpy disponible" - if has_gnuplot: + if self.has_gnuplot: + import Gnuplot __version = Gnuplot.__version__ else: __version = "0.0" @@ -209,7 +376,8 @@ class PlatformInfo(object): def getSphinxVersion(self): "Retourne la version de sphinx disponible" - if has_sphinx: + if self.has_sphinx: + import sphinx __version = sphinx.__version__ else: __version = "0.0.0" @@ -217,7 +385,8 @@ class PlatformInfo(object): def getNloptVersion(self): "Retourne la version de nlopt disponible" - if has_nlopt: + if self.has_nlopt: + import nlopt __version = "%s.%s.%s"%( nlopt.version_major(), nlopt.version_minor(), @@ -229,7 +398,8 @@ class PlatformInfo(object): def getSdfVersion(self): "Retourne la version de sdf disponible" - if has_sdf: + if self.has_sdf: + import sdf __version = sdf.__version__ else: __version = "0.0.0" @@ -237,7 +407,8 @@ class PlatformInfo(object): def getFmpyVersion(self): "Retourne la version de fmpy disponible" - if has_fmpy: + if self.has_fmpy: + import fmpy __version = fmpy.__version__ else: __version = "0.0.0" @@ -270,65 +441,6 @@ class PlatformInfo(object): return "%s %s (%s)"%(dav.name, dav.version, dav.date) # ============================================================================== -# Tests d'importation de modules système - -try: - import numpy - has_numpy = True -except ImportError: - raise ImportError("Numpy is not available, despites the fact it is mandatory.") - -try: - import scipy - import scipy.version - import scipy.optimize - has_scipy = True -except ImportError: - has_scipy = False - -try: - import matplotlib - has_matplotlib = True -except ImportError: - has_matplotlib = False - -try: - import sphinx - has_sphinx = True -except ImportError: - has_sphinx = False - -try: - import nlopt - has_nlopt = True -except ImportError: - has_nlopt = False - -try: - import sdf - has_sdf = True -except ImportError: - has_sdf = False - -try: - import fmpy - has_fmpy = True -except ImportError: - has_fmpy = False - -has_salome = bool( "SALOME_ROOT_DIR" in os.environ ) -has_yacs = bool( "YACS_ROOT_DIR" in os.environ ) -has_adao = bool( "ADAO_ROOT_DIR" in os.environ ) -has_eficas = bool( "EFICAS_ROOT_DIR" in os.environ ) - -# ============================================================================== -def uniq( __sequence ): - """ - Fonction pour rendre unique chaque élément d'une liste, en préservant l'ordre - """ - __seen = set() - return [x for x in __sequence if x not in __seen and not __seen.add(x)] - def vt( __version ): "Version transformée pour comparaison robuste, obtenue comme un tuple" serie = [] @@ -454,33 +566,6 @@ def checkFileNameImportability( __filename, __warnInsteadOfPrint=True ): # return __conform -# ============================================================================== -class PathManagement(object): - """ - Mise à jour du path système pour les répertoires d'outils - """ - __slots__ = ("__paths") - - def __init__(self): - "Déclaration des répertoires statiques" - parent = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) - self.__paths = {} - self.__paths["daNumerics"] = os.path.join(parent, "daNumerics") - # - for v in self.__paths.values(): - if os.path.isdir(v): - sys.path.insert(0, v ) - # - # Conserve en unique exemplaire chaque chemin - sys.path = uniq( sys.path ) - del parent - - def getpaths(self): - """ - Renvoie le dictionnaire des chemins ajoutés - """ - return self.__paths - # ============================================================================== class SystemUsage(object): """ @@ -582,16 +667,6 @@ class SystemUsage(object): "Renvoie la mémoire totale maximale mesurée" return self._VmB('VmPeak:', unit) -# ============================================================================== -# Tests d'importation de modules locaux - -PathManagement() -try: - import Gnuplot - has_gnuplot = True -except ImportError: - has_gnuplot = False - # ============================================================================== if __name__ == "__main__": print("\n AUTODIAGNOSTIC\n")