Salome HOME
33beb86415e46dcc3496b1637b29aa6cbd8ea4b3
[modules/med.git] / src / MEDOP / tui / xmedpy / fieldtools.py
1 #  -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2011-2015  CEA/DEN, EDF R&D
3 #
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License, or (at your option) any later version.
8 #
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 # Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 #
18 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 #
20 # Author : Guillaume Boulant (EDF)
21
22 #
23 # ===================================================================
24 # The functions of this module must be imported as global functions in
25 # the SALOME python console. It provides the console context with Tool
26 # functions to manipulate field throw there fieldproxy.
27 # ===================================================================
28 #
29
30 import xmed
31 from xmed.fieldproxy import FieldProxy, newFieldProxy
32
33 # ===================================================================
34 # Operations on fields
35
36 def dup(aFieldProxy):
37     """
38     This function returns a duplicate of the specified field.
39     It's equivalent to the call '>>> copy = f.dup()'.
40     """
41     try:
42         clone = aFieldProxy.dup()
43     except Exception:
44         print "ERR: the argument can't be duplicated as a field object"
45         return None
46     return clone
47
48 # ===================================================================
49 # Get list a field with information using the commands ls and/or la
50
51 # IMPORTANT NOTE:
52 # the pyConsoleGlobals variable should holds the globals() dictionnary of
53 # the python console context
54 pyConsoleGlobals=None
55
56 def status(local=True,remote=False):
57     """
58     This function return the status of the medop context, i.e. the
59     list of fields defined in this python session.
60     """
61     status=""
62     if local is True:
63         dvars = pyConsoleGlobals
64         if dvars is None:
65             xmed.wrn("The stat function required the specification of the python context")
66             xmed.inf("Type this command \"import xmed; xmed.setConsoleGlobals(globals())")
67         if remote is True:
68             status="========= Fields used in the current context ===\n"
69         for varkey in dvars.keys():
70             var = dvars[varkey]
71             if isinstance(var, FieldProxy):
72                 status+="%s \t(id=%s, name=%s)\n"%(varkey,var.id,var.fieldname)
73
74     if remote is True:
75         if local is True:
76             status+="\n========= Fields available in the data manager ===\n"
77         fieldHandlerList = xmed.dataManager.getFieldHandlerList()
78         for fieldHandler in fieldHandlerList:
79             status+="id=%s\tname\t= %s\n\tmesh\t= %s\n\t(it,dt)\t= (%s,%s)\n\tsource\t= %s\n"%(
80                 fieldHandler.id,
81                 fieldHandler.fieldname,
82                 fieldHandler.meshname,
83                 fieldHandler.iteration,
84                 fieldHandler.order,
85                 fieldHandler.source)
86             status+="---------\n"
87
88         if len(fieldHandlerList) > 0:
89             status+="(use 'f=get(id)' to get a field in the current context)"
90
91     return status
92
93 # For simpler typing, one can create a python command for status
94 # (avoid to type "print status()")
95 class ListFields(object):
96     """
97     A stat object displays the status of the med operating context, i.e. the
98     list of fields defined in this python session.
99     """
100     def __init__(self,all=False):
101         self.__local  = True
102         self.__remote = all
103         # all = True means that the local metadata (fieldproxy) and the
104         # remote metadata on the engine (MEDCouplingFieldDouble) are
105         # displayed by the stat command. Otherwise, only the local
106         # metadata are displayed.
107
108     def __repr__(self):
109         return status(self.__local, self.__remote)
110
111 # Creating the commands list (ls) and list all (la)
112 ls=ListFields(all=False)
113 la=ListFields(all=True)
114
115 # ===================================================================
116 # Remove variable from console
117 from xmed.fieldproxy import notifyGui_remove
118 def remove(aFieldProxy):
119     dvars = pyConsoleGlobals
120     if dvars is None:
121         return
122     for varkey, var in dvars.items():
123         if isinstance(var, FieldProxy) and var.id == aFieldProxy.id:
124             exec("del %s"%varkey) in pyConsoleGlobals
125     notifyGui_remove(aFieldProxy.id)
126 #
127
128 # Clean workspace
129 from xmed.fieldproxy import notifyGui_clean
130 def clean():
131     dvars = pyConsoleGlobals
132     if dvars is None:
133         return
134     all_keys = []
135     for varkey, var in dvars.items():
136         if isinstance(var, FieldProxy):
137             all_keys.append("%s"%varkey)
138     if len(all_keys) > 0:
139         exec "del "+",".join(all_keys) in pyConsoleGlobals
140     notifyGui_clean()
141 #
142
143 # ===================================================================
144 # Field Data Management
145 from xmed import properties
146 filepath  = properties.testFilePath
147
148 def load(medFileName=filepath):
149     """
150     This function indicates that we want to use the fields from the
151     specified med file. The fields meta-data are loaded in the engine
152     part of the module. To get a fieldproxy on a field, call the get
153     function with the id of the required field. To display the whole
154     list of fields loaded in the engine, type 'ls' (la verbose).
155     """
156     xmed.dataManager.addDatasource(filepath)
157     print status(local=False,remote=True)
158
159 def get(fieldHandlerId):
160     """
161     This return a field proxy on the field identified by the specified
162     field handler id.
163     """
164     return newFieldProxy(fieldHandlerId)
165
166 from xmed.fieldproxy import notifyGui_add
167 def put(aFieldProxy):
168     """
169     This function puts a reference to this field in the GUI data
170     model. When a field is referenced in the GUI data model, then it
171     belongs to the workspace. When the workspace is saved, all the
172     field that belongs to the workspace are saved.
173     """
174     xmed.dataManager.markAsPersistent(aFieldProxy.id, True)
175     notifyGui_add(aFieldProxy.id)
176
177 import SALOME
178 def save(filename):
179     """
180     Dump your job in a med file. Only the fields marked as persistent
181     are saved in the specified file.
182     """
183     try:
184         xmed.dataManager.savePersistentFields(filename)
185     except SALOME.SALOME_Exception, ex:
186         xmed.err(ex.details.text)
187
188 # ===================================================================
189 # Field Data visualization
190 VIEWER_VISU    = "VISU"
191 VIEWER_PARAVIS = "PARAVIS"
192 VIEWER_DEFAULT = VIEWER_PARAVIS
193
194 import tempfile
195
196 def view_using_paravis(aFieldProxy):
197     temp = tempfile.NamedTemporaryFile(prefix="medop_viewer", suffix='.med', delete=False)
198
199     # __GBO__ TO BE IMPROVED: we used a tmp file in this first step of
200     # development, but we should used at last a MEDCoupling corba
201     # object (see how to use the stuff in PARAVIS/src/Plugins)
202     xmed.dataManager.saveFields(temp.name, [aFieldProxy.id])
203
204     from xmed.driver_pvis import pvis_scalarmap
205     pvis_scalarmap(temp.name,
206                    aFieldProxy.meshname,
207                    aFieldProxy.fieldname,
208                    aFieldProxy.type,
209                    aFieldProxy.iteration)
210     temp.close()
211 #
212
213 def view_using_visu(aFieldProxy):
214     # No more used
215     raise Exception("view_using_visu: No more used")
216
217     VIEWER_TMP_FILE = "/tmp/medop_viewer.med"
218
219     # __GBO__ TO BE IMPROVED: we used a tmp file in this first step of
220     # development, but we should used at last a MEDCoupling corba
221     # object (see how to use the stuff in PARAVIS/src/Plugins)
222     xmed.dataManager.saveFields(VIEWER_TMP_FILE, [aFieldProxy.id])
223
224     # __GBO__: WARN due to a specific feature of VISU, when only one
225     # field timestamps exists in the med file, we have to specify an
226     # iteration number of 1, whatever the iteration value is in the
227     # med file.
228     iteration = 1 # __GBO__ for bug VISU
229     # instead of:
230     # iteration = aFieldProxy.iteration
231
232     from xmed.driver_visu import visu_scalarmap
233     result = visu_scalarmap(VIEWER_TMP_FILE,
234                             aFieldProxy.meshname,
235                             aFieldProxy.fieldname,
236                             aFieldProxy.type,
237                             iteration)
238     if result is False:
239         xmed.err("the field can't be displayed")
240
241 def view(aFieldProxy, using=VIEWER_DEFAULT):
242     """
243     This displays a 3D view of the field using VISU or PARAVIS,
244     depending on the configuration. This view is for quick visual
245     control of a field and is not intended to be parametrizable. For
246     custom display, you should import the fields in VISU or PARAVIS
247     and continue the job in one of this SALOME module.
248     """
249     if using == VIEWER_PARAVIS:
250         view_using_paravis(aFieldProxy)
251     else:
252         view_using_visu(aFieldProxy)
253