Salome HOME
Get classification
[modules/adao.git] / src / daComposant / daCore / Persistence.py
index 2b8608717c69a44108aa7c89873cce87622e53d8..ecaa30405a19dfea13b726bcce618b72b75c94c0 100644 (file)
@@ -1,6 +1,6 @@
 # -*- coding: utf-8 -*-
 #
-# Copyright (C) 2008-2018 EDF R&D
+# Copyright (C) 2008-2020 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
 __author__ = "Jean-Philippe ARGAUD"
 __all__ = []
 
-import sys, numpy, copy
+import os, sys, numpy, copy
+import gzip, bz2
 
 from daCore.PlatformInfo import PathManagement ; PathManagement()
+from daCore.PlatformInfo import has_gnuplot, PlatformInfo
+mfp = PlatformInfo().MaximumPrecision()
+if has_gnuplot:
+    import Gnuplot
 
 if sys.version_info.major < 3:
     range = xrange
@@ -67,7 +72,6 @@ class Persistence(object):
         self.__tags     = []
         #
         self.__dynamic  = False
-        self.__gnuplot  = None
         self.__g        = None
         self.__title    = None
         self.__ltitle   = None
@@ -143,6 +147,9 @@ class Persistence(object):
         "x.__len__() <==> len(x)"
         return len(self.__values)
 
+    def name(self):
+        return self.__name
+
     def __getitem__(self, index=None ):
         "x.__getitem__(y) <==> x[y]"
         return copy.copy(self.__values[index])
@@ -273,7 +280,7 @@ class Persistence(object):
         élémentaires numpy.
         """
         try:
-            return [numpy.matrix(item).mean() for item in self.__values]
+            return [numpy.mean(item, dtype=mfp) for item in self.__values]
         except:
             raise TypeError("Base type is incompatible with numpy")
 
@@ -288,9 +295,9 @@ class Persistence(object):
         """
         try:
             if numpy.version.version >= '1.1.0':
-                return [numpy.matrix(item).std(ddof=ddof) for item in self.__values]
+                return [numpy.array(item).std(ddof=ddof) for item in self.__values]
             else:
-                return [numpy.matrix(item).std() for item in self.__values]
+                return [numpy.array(item).std() for item in self.__values]
         except:
             raise TypeError("Base type is incompatible with numpy")
 
@@ -301,7 +308,7 @@ class Persistence(object):
         numpy.
         """
         try:
-            return [numpy.matrix(item).sum() for item in self.__values]
+            return [numpy.array(item).sum() for item in self.__values]
         except:
             raise TypeError("Base type is incompatible with numpy")
 
@@ -312,7 +319,7 @@ class Persistence(object):
         numpy.
         """
         try:
-            return [numpy.matrix(item).min() for item in self.__values]
+            return [numpy.array(item).min() for item in self.__values]
         except:
             raise TypeError("Base type is incompatible with numpy")
 
@@ -323,7 +330,7 @@ class Persistence(object):
         numpy.
         """
         try:
-            return [numpy.matrix(item).max() for item in self.__values]
+            return [numpy.array(item).max() for item in self.__values]
         except:
             raise TypeError("Base type is incompatible with numpy")
 
@@ -339,21 +346,18 @@ class Persistence(object):
         "Préparation des plots"
         #
         # Vérification de la disponibilité du module Gnuplot
-        try:
-            import Gnuplot
-            self.__gnuplot = Gnuplot
-        except:
+        if not 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
         if persist:
-            self.__gnuplot.GnuplotOpts.gnuplot_command = 'gnuplot -persist -geometry '+geometry
+            Gnuplot.GnuplotOpts.gnuplot_command = 'gnuplot -persist -geometry '+geometry
         else:
-            self.__gnuplot.GnuplotOpts.gnuplot_command = 'gnuplot -geometry '+geometry
+            Gnuplot.GnuplotOpts.gnuplot_command = 'gnuplot -geometry '+geometry
         if ltitle is None:
             ltitle = ""
-        self.__g = self.__gnuplot.Gnuplot() # persist=1
-        self.__g('set terminal '+self.__gnuplot.GnuplotOpts.default_term)
+        self.__g = Gnuplot.Gnuplot() # persist=1
+        self.__g('set terminal '+Gnuplot.GnuplotOpts.default_term)
         self.__g('set style data lines')
         self.__g('set grid')
         self.__g('set autoscale')
@@ -412,7 +416,6 @@ class Persistence(object):
                          attendant un Return
                          Par défaut, pause = True
         """
-        import os
         if not self.__dynamic:
             self.__preplots(title, xlabel, ylabel, ltitle, geometry, persist, pause )
             if dynamic:
@@ -436,7 +439,7 @@ class Persistence(object):
             else:
                 Steps = list(range(len(self.__values[index])))
             #
-            self.__g.plot( self.__gnuplot.Data( Steps, self.__values[index], title=ltitle ) )
+            self.__g.plot( Gnuplot.Data( Steps, self.__values[index], title=ltitle ) )
             #
             if filename != "":
                 i += 1
@@ -455,12 +458,13 @@ class Persistence(object):
         #
         self.__g('set title  "'+str(self.__title))
         Steps = list(range(len(self.__values)))
-        self.__g.plot( self.__gnuplot.Data( Steps, self.__values, title=self.__ltitle ) )
+        self.__g.plot( Gnuplot.Data( Steps, self.__values, title=self.__ltitle ) )
         #
         if self.__pause:
             eval(input('Please press return to continue...\n'))
 
     # ---------------------------------------------------------
+    # On pourrait aussi utiliser d'autres attributs d'un "array" comme "tofile"
     def mean(self):
         """
         Renvoie la moyenne sur toutes les valeurs sans tenir compte de la
@@ -469,9 +473,9 @@ class Persistence(object):
         """
         try:
             if self.__basetype in [int, float]:
-                return float( numpy.array(self.__values).mean() )
+                return float( numpy.mean(self.__values, dtype=mfp) )
             else:
-                return numpy.array(self.__values).mean(axis=0)
+                return numpy.mean(self.__values, axis=0, dtype=mfp)
         except:
             raise TypeError("Base type is incompatible with numpy")
 
@@ -536,9 +540,6 @@ class Persistence(object):
         except:
             raise TypeError("Base type is incompatible with numpy")
 
-    # On pourrait aussi utiliser les autres attributs d'une "matrix", comme
-    # "tofile", "min"...
-
     def plot(self,
              steps    = None,
              title    = "",
@@ -578,25 +579,22 @@ class Persistence(object):
         """
         #
         # Vérification de la disponibilité du module Gnuplot
-        try:
-            import Gnuplot
-            self.__gnuplot = Gnuplot
-        except:
+        if not 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
         if persist:
-            self.__gnuplot.GnuplotOpts.gnuplot_command = 'gnuplot -persist -geometry '+geometry
+            Gnuplot.GnuplotOpts.gnuplot_command = 'gnuplot -persist -geometry '+geometry
         else:
-            self.__gnuplot.GnuplotOpts.gnuplot_command = 'gnuplot -geometry '+geometry
+            Gnuplot.GnuplotOpts.gnuplot_command = 'gnuplot -geometry '+geometry
         if ltitle is None:
             ltitle = ""
         if isinstance(steps,list) or isinstance(steps, numpy.ndarray):
             Steps = list(steps)
         else:
             Steps = list(range(len(self.__values[0])))
-        self.__g = self.__gnuplot.Gnuplot() # persist=1
-        self.__g('set terminal '+self.__gnuplot.GnuplotOpts.default_term)
+        self.__g = Gnuplot.Gnuplot() # persist=1
+        self.__g('set terminal '+Gnuplot.GnuplotOpts.default_term)
         self.__g('set style data lines')
         self.__g('set grid')
         self.__g('set autoscale')
@@ -606,9 +604,9 @@ class Persistence(object):
         #
         # Tracé du ou des vecteurs demandés
         indexes = list(range(len(self.__values)))
-        self.__g.plot( self.__gnuplot.Data( Steps, self.__values[indexes.pop(0)], title=ltitle+" (pas 0)" ) )
+        self.__g.plot( Gnuplot.Data( Steps, self.__values[indexes.pop(0)], title=ltitle+" (pas 0)" ) )
         for index in indexes:
-            self.__g.replot( self.__gnuplot.Data( Steps, self.__values[index], title=ltitle+" (pas %i)"%index ) )
+            self.__g.replot( Gnuplot.Data( Steps, self.__values[index], title=ltitle+" (pas %i)"%index ) )
         #
         if filename != "":
             self.__g.hardcopy(filename=filename, color=1)
@@ -880,7 +878,6 @@ class CompositePersistence(object):
         Enregistre l'objet dans le fichier indiqué selon le "mode" demandé,
         et renvoi le nom du fichier
         """
-        import os
         if filename is None:
             if compress == "gzip":
                 filename = os.tempnam( os.getcwd(), 'dacp' ) + ".pkl.gz"
@@ -893,10 +890,8 @@ class CompositePersistence(object):
         #
         if mode == "pickle":
             if compress == "gzip":
-                import gzip
                 output = gzip.open( filename, 'wb')
             elif compress == "bzip2":
-                import bz2
                 output = bz2.BZ2File( filename, 'wb')
             else:
                 output = open( filename, 'wb')
@@ -911,7 +906,6 @@ class CompositePersistence(object):
         """
         Recharge un objet composite sauvé en fichier
         """
-        import os
         if filename is None:
             raise ValueError("A file name if requested to load a composite.")
         else:
@@ -919,10 +913,8 @@ class CompositePersistence(object):
         #
         if mode == "pickle":
             if compress == "gzip":
-                import gzip
                 pkl_file = gzip.open( filename, 'rb')
             elif compress == "bzip2":
-                import bz2
                 pkl_file = bz2.BZ2File( filename, 'rb')
             else:
                 pkl_file = open(filename, 'rb')
@@ -936,4 +928,4 @@ class CompositePersistence(object):
 
 # ==============================================================================
 if __name__ == "__main__":
-    print('\n AUTODIAGNOSTIC \n')
+    print('\n AUTODIAGNOSTIC\n')