Salome HOME
Correcting A-shape verification
[modules/adao.git] / src / daComposant / daDiagnostics / PlotVectors.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2012 EDF R&D
4 #
5 #  This library is free software; you can redistribute it and/or
6 #  modify it under the terms of the GNU Lesser General Public
7 #  License as published by the Free Software Foundation; either
8 #  version 2.1 of the License.
9 #
10 #  This library is distributed in the hope that it will be useful,
11 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 #  Lesser General Public License for more details.
14 #
15 #  You should have received a copy of the GNU Lesser General Public
16 #  License along with this library; if not, write to the Free Software
17 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18 #
19 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #
21
22 import numpy
23 from daCore import BasicObjects
24 import os.path
25
26 # ==============================================================================
27 class ElementaryDiagnostic(BasicObjects.Diagnostic):
28     """
29     Classe pour tracer simplement une liste de vecteurs à chaque pas
30     """
31     def __init__(self, name = "", unit = "", basetype = None, parameters = {}):
32         BasicObjects.Diagnostic.__init__(self, name, parameters)
33         try:
34             import Gnuplot
35             self.__gnuplot = Gnuplot
36         except:
37             raise ImportError("The Gnuplot module is required to plot the vector")
38
39     def _formula(self,
40             Vector, Steps,
41             title, xlabel, ylabel, ltitle,
42             geometry,
43             filename,
44             persist,
45             pause ):
46         """
47         Trace en gnuplot chaque vecteur de la liste Vector, avec une légende
48         générale, en X et en Y
49         """
50         if persist:
51             self.__gnuplot.GnuplotOpts.gnuplot_command = 'gnuplot -persist -geometry '+geometry
52         else:
53             self.__gnuplot.GnuplotOpts.gnuplot_command = 'gnuplot -geometry '+geometry
54         #
55         self.__g = self.__gnuplot.Gnuplot() # persist=1
56         self.__g('set terminal '+self.__gnuplot.GnuplotOpts.default_term)
57         self.__g('set style data lines')
58         self.__g('set grid')
59         self.__g('set autoscale')
60         self.__g('set title  "'+title +'"')
61         self.__g('set xlabel "'+xlabel+'"')
62         self.__g('set ylabel "'+ylabel+'"')
63         self.__g.plot( self.__gnuplot.Data( Steps, Vector.pop(0), title=ltitle.pop(0) ) )
64         for vector in Vector:
65             self.__g.replot( self.__gnuplot.Data( Steps, vector, title=ltitle.pop(0) ) )
66         if filename != "":
67             self.__g.hardcopy(filename=filename, color=1)
68         if pause:
69             raw_input('Please press return to continue...\n')
70         #
71         return 1
72
73     def calculate(self, vector = None, steps = None,
74                         title = "", xlabel = "", ylabel = "", ltitle = None,
75                         geometry = "600x400",
76                         filename = "",
77                         persist  = False,
78                         pause    = True ):
79         """
80         Arguments :
81             - vector   : liste des vecteurs à tracer, chacun étant en liste ou
82                          en numpy.array
83             - steps    : liste unique des pas, ou None si c'est la numérotation
84                          par défaut
85             - title    : titre général du dessin
86             - xlabel   : label de l'axe des X
87             - ylabel   : label de l'axe des Y
88             - ltitle   : liste des titres associés à chaque vecteur, dans le
89                          même ordre que les vecteurs eux-mêmes
90             - geometry : taille en pixels de la fenêtre et position du coin haut
91                          gauche, au format X11 : LxH+X+Y (défaut : 600x400)
92             - filename : nom de fichier Postscript pour une sauvegarde à 1 pas
93                          Attention, il faut changer le nom à l'appel pour
94                          plusieurs pas de sauvegarde
95             - persist  : booléen indiquant que la fenêtre affichée sera
96                          conservée lors du passage au dessin suivant
97                          Par défaut, persist = False
98             - pause    : booléen indiquant une pause après chaque tracé, et
99                          attendant un Return
100                          Par défaut, pause = True
101         """
102         if vector is None:
103             raise ValueError("One vector must be given to plot it.")
104         if type(vector) is not type([]) and type(vector) is not type(()):
105             raise ValueError("The vector(s) must be given as a list/tuple.")
106         if ltitle is None or len(ltitle) != len(vector):
107             ltitle = ["" for i in range(len(vector))]
108         VectorList = []
109         for onevector in vector:
110             VectorList.append( numpy.array( onevector ) )
111             if VectorList[-1].size < 1:
112                 raise ValueError("Each given vector must not be empty.")
113         if steps is None:
114             Steps = range(len(vector[0]))
115         elif not ( type(steps) is type([]) or type(steps) is not type(numpy.array([])) ):
116             raise ValueError("The steps must be given as a list/tuple.")
117         else:
118             Steps = list(steps)
119         if os.path.isfile(filename):
120             raise ValueError("Error: a file with this name \"%s\" already exists."%filename)
121         #
122         value = self._formula(
123             Vector   = VectorList,
124             Steps    = Steps,
125             title    = str(title).encode('ascii','replace'),
126             xlabel   = str(xlabel).encode('ascii','replace'),
127             ylabel   = str(ylabel).encode('ascii','replace'),
128             ltitle   = [str(lt) for lt in ltitle],
129             geometry = str(geometry),
130             filename = str(filename),
131             persist  = bool(persist),
132             pause    = bool(pause),
133             )
134
135 # ==============================================================================
136 if __name__ == "__main__":
137     print '\n AUTODIAGNOSTIC \n'
138
139     D = ElementaryDiagnostic("Mon Plot")
140
141     vect1 = [1, 2, 1, 2, 1]
142     D.calculate([vect1,], title = "Vecteur 1", xlabel = "Axe X", ylabel = "Axe Y" )
143     vect2 = [1, 3, 1, 3, 1]
144     D.calculate([vect1,vect2], title = "Vecteurs 1 et 2", filename = "liste_de_vecteurs.ps")
145     vect3 = [-1, 1, -1, 1, -1]
146     D.calculate((vect1,vect2,vect3), title = "Vecteurs 1 a 3")
147     vect4 = 100*[0.29, 0.97, 0.73, 0.01, 0.20]
148     D.calculate([vect4,], title = "Vecteur 4 : long construit par repetition")
149     D.calculate(
150         (vect1,vect2,vect3),
151         [0.1,0.2,0.3,0.4,0.5],
152         title = "Vecteurs 1 a 3, temps modifie",
153         ltitle = ["Vecteur 1","Vecteur 2","Vecteur 3"])
154     print