Salome HOME
Documentation and source minor corrections for observers
[modules/adao.git] / src / daComposant / daDiagnostics / PlotVector.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2015 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 #  Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
22
23 import numpy
24 from daCore import BasicObjects
25 import os.path
26
27 # ==============================================================================
28 class ElementaryDiagnostic(BasicObjects.Diagnostic):
29     """
30     Classe pour tracer simplement un vecteur à chaque pas
31     """
32     def __init__(self, name = "", unit = "", basetype = None, parameters = {}):
33         BasicObjects.Diagnostic.__init__(self, name, parameters)
34         try:
35             import Gnuplot
36             self.__gnuplot = Gnuplot
37         except:
38             raise ImportError("The Gnuplot module is required to plot the vector")
39
40     def _formula(self,
41             Vector, Steps,
42             title, xlabel, ylabel, ltitle,
43             geometry,
44             filename,
45             persist,
46             pause ):
47         """
48         Trace en gnuplot le vecteur Vector, avec une légende générale, en X et
49         en Y
50         """
51         if persist:
52             self.__gnuplot.GnuplotOpts.gnuplot_command = 'gnuplot -persist -geometry '+geometry
53         else:
54             self.__gnuplot.GnuplotOpts.gnuplot_command = 'gnuplot -geometry '+geometry
55         #
56         self.__g = self.__gnuplot.Gnuplot() # persist=1
57         self.__g('set terminal '+self.__gnuplot.GnuplotOpts.default_term)
58         self.__g('set style data lines')
59         self.__g('set grid')
60         self.__g('set autoscale')
61         self.__g('set title  "'+title +'"')
62         self.__g('set xlabel "'+xlabel+'"')
63         self.__g('set ylabel "'+ylabel+'"')
64         self.__g.plot( self.__gnuplot.Data( Steps, Vector, title=ltitle ) )
65         if filename != "":
66             self.__g.hardcopy(filename=filename, color=1)
67         if pause:
68             raw_input('Please press return to continue...\n')
69         #
70         return 1
71
72     def calculate(self, vector = None, steps = None,
73                         title = "", xlabel = "", ylabel = "", ltitle = "",
74                         geometry = "600x400",
75                         filename = "",
76                         persist  = False,
77                         pause    = True ):
78         """
79         Arguments :
80             - vector   : le vecteur à tracer, en liste ou en numpy.array
81             - steps    : liste unique des pas de l'axe des X, ou None si c'est
82                          la numérotation par défaut
83             - title    : titre général du dessin
84             - xlabel   : label de l'axe des X
85             - ylabel   : label de l'axe des Y
86             - ltitle   : titre associé au vecteur tracé
87             - geometry : taille en pixels de la fenêtre et position du coin haut
88                          gauche, au format X11 : LxH+X+Y (défaut : 600x400)
89             - filename : nom de fichier Postscript pour une sauvegarde à 1 pas
90                          Attention, il faut changer le nom à l'appel pour
91                          plusieurs pas de sauvegarde
92             - persist  : booléen indiquant que la fenêtre affichée sera
93                          conservée lors du passage au dessin suivant
94                          Par défaut, persist = False
95             - pause    : booléen indiquant une pause après chaque tracé, et
96                          attendant un Return
97                          Par défaut, pause = True
98         """
99         if vector is None:
100             raise ValueError("One vector must be given to plot it.")
101         Vector = numpy.array(vector)
102         if Vector.size < 1:
103             raise ValueError("The given vector must not be empty")
104         if steps is None:
105             Steps = range(len( vector ))
106         elif not ( type(steps) is type([]) or type(steps) is not type(numpy.array([])) ):
107             raise ValueError("The steps must be given as a list/tuple.")
108         else:
109             Steps = list(steps)
110         if os.path.isfile(filename):
111             raise ValueError("Error: a file with this name \"%s\" already exists."%filename)
112         #
113         value = self._formula(
114             Vector   = Vector,
115             Steps    = Steps,
116             title    = str(title).encode('ascii','replace'),
117             xlabel   = str(xlabel).encode('ascii','replace'),
118             ylabel   = str(ylabel).encode('ascii','replace'),
119             ltitle   = str(ltitle),
120             geometry = str(geometry),
121             filename = str(filename),
122             persist  = bool(persist),
123             pause    = bool(pause) )
124
125 # ==============================================================================
126 if __name__ == "__main__":
127     print '\n AUTODIAGNOSTIC \n'
128
129     D = ElementaryDiagnostic("Mon Plot")
130
131     vect = [1, 2, 1, 2, 1]
132     D.calculate(vect, title = "Vecteur 1", xlabel = "Axe X", ylabel = "Axe Y" )
133     vect = [1, 3, 1, 3, 1]
134     D.calculate(vect, title = "Vecteur 2", filename = "vecteur.ps")
135     vect = [1, 1, 1, 1, 1]
136     D.calculate(vect, title = "Vecteur 3")
137     vect = [0.29, 0.97, 0.73, 0.01, 0.20]
138     D.calculate(vect, title = "Vecteur 4")
139     vect = [-0.23262176, 1.36065207,  0.32988102, 0.24400551, -0.66765848, -0.19088483, -0.31082575,  0.56849814,  1.21453443,  0.99657516]
140     D.calculate(vect, title = "Vecteur 5")
141     vect = [0.29, 0.97, 0.73, 0.01, 0.20]
142     D.calculate(vect, title = "Vecteur 6 affiche avec une autre geometrie et position", geometry="800x200+50+50")
143     vect = 100*[0.29, 0.97, 0.73, 0.01, 0.20]
144     D.calculate(vect, title = "Vecteur 7 : long construit par repetition")
145     vect = [0.29, 0.97, 0.73, 0.01, 0.20]
146     D.calculate(vect, title = "Vecteur 8", ltitle = "Vecteur 8")
147     temps = [0.1,0.2,0.3,0.4,0.5]
148     D.calculate(vect, temps, title = "Vecteur 8 avec axe du temps modifie")
149     print