Salome HOME
Correcting A-shape verification
[modules/adao.git] / src / daComposant / daDiagnostics / PlotVector.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 un vecteur à 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 le vecteur Vector, avec une légende générale, en X et
48         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, title=ltitle ) )
64         if filename != "":
65             self.__g.hardcopy(filename=filename, color=1)
66         if pause:
67             raw_input('Please press return to continue...\n')
68         #
69         return 1
70
71     def calculate(self, vector = None, steps = None,
72                         title = "", xlabel = "", ylabel = "", ltitle = "",
73                         geometry = "600x400",
74                         filename = "",
75                         persist  = False,
76                         pause    = True ):
77         """
78         Arguments :
79             - vector   : le vecteur à tracer, en liste ou en numpy.array
80             - steps    : liste unique des pas de l'axe des X, ou None si c'est
81                          la numérotation par défaut
82             - title    : titre général du dessin
83             - xlabel   : label de l'axe des X
84             - ylabel   : label de l'axe des Y
85             - ltitle   : titre associé au vecteur tracé
86             - geometry : taille en pixels de la fenêtre et position du coin haut
87                          gauche, au format X11 : LxH+X+Y (défaut : 600x400)
88             - filename : nom de fichier Postscript pour une sauvegarde à 1 pas
89                          Attention, il faut changer le nom à l'appel pour
90                          plusieurs pas de sauvegarde
91             - persist  : booléen indiquant que la fenêtre affichée sera
92                          conservée lors du passage au dessin suivant
93                          Par défaut, persist = False
94             - pause    : booléen indiquant une pause après chaque tracé, et
95                          attendant un Return
96                          Par défaut, pause = True
97         """
98         if vector is None:
99             raise ValueError("One vector must be given to plot it.")
100         Vector = numpy.array(vector)
101         if Vector.size < 1:
102             raise ValueError("The given vector must not be empty")
103         if steps is None:
104             Steps = range(len( vector ))
105         elif not ( type(steps) is type([]) or type(steps) is not type(numpy.array([])) ):
106             raise ValueError("The steps must be given as a list/tuple.")
107         else:
108             Steps = list(steps)
109         if os.path.isfile(filename):
110             raise ValueError("Error: a file with this name \"%s\" already exists."%filename)
111         #
112         value = self._formula(
113             Vector   = Vector,
114             Steps    = Steps,
115             title    = str(title).encode('ascii','replace'),
116             xlabel   = str(xlabel).encode('ascii','replace'),
117             ylabel   = str(ylabel).encode('ascii','replace'),
118             ltitle   = str(ltitle),
119             geometry = str(geometry),
120             filename = str(filename),
121             persist  = bool(persist),
122             pause    = bool(pause) )
123
124 # ==============================================================================
125 if __name__ == "__main__":
126     print '\n AUTODIAGNOSTIC \n'
127
128     D = ElementaryDiagnostic("Mon Plot")
129
130     vect = [1, 2, 1, 2, 1]
131     D.calculate(vect, title = "Vecteur 1", xlabel = "Axe X", ylabel = "Axe Y" )
132     vect = [1, 3, 1, 3, 1]
133     D.calculate(vect, title = "Vecteur 2", filename = "vecteur.ps")
134     vect = [1, 1, 1, 1, 1]
135     D.calculate(vect, title = "Vecteur 3")
136     vect = [0.29, 0.97, 0.73, 0.01, 0.20]
137     D.calculate(vect, title = "Vecteur 4")
138     vect = [-0.23262176, 1.36065207,  0.32988102, 0.24400551, -0.66765848, -0.19088483, -0.31082575,  0.56849814,  1.21453443,  0.99657516]
139     D.calculate(vect, title = "Vecteur 5")
140     vect = [0.29, 0.97, 0.73, 0.01, 0.20]
141     D.calculate(vect, title = "Vecteur 6 affiche avec une autre geometrie et position", geometry="800x200+50+50")
142     vect = 100*[0.29, 0.97, 0.73, 0.01, 0.20]
143     D.calculate(vect, title = "Vecteur 7 : long construit par repetition")
144     vect = [0.29, 0.97, 0.73, 0.01, 0.20]
145     D.calculate(vect, title = "Vecteur 8", ltitle = "Vecteur 8")
146     temps = [0.1,0.2,0.3,0.4,0.5]
147     D.calculate(vect, temps, title = "Vecteur 8 avec axe du temps modifie")
148     print