Salome HOME
medcalc and commands history
[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     from xmed.fieldproxy import notifyGui_addsource
159     notifyGui_addsource(filename)
160
161 def get(fieldHandlerId):
162     """
163     This return a field proxy on the field identified by the specified
164     field handler id.
165     """
166     return newFieldProxy(fieldHandlerId)
167
168 from xmed.fieldproxy import notifyGui_add
169 def put(aFieldProxy):
170     """
171     This function puts a reference to this field in the GUI data
172     model. When a field is referenced in the GUI data model, then it
173     belongs to the workspace. When the workspace is saved, all the
174     field that belongs to the workspace are saved.
175     """
176     xmed.dataManager.markAsPersistent(aFieldProxy.id, True)
177     notifyGui_add(aFieldProxy.id)
178
179 import SALOME
180 def save(filename):
181     """
182     Dump your job in a med file. Only the fields marked as persistent
183     are saved in the specified file.
184     """
185     try:
186         xmed.dataManager.savePersistentFields(filename)
187     except SALOME.SALOME_Exception, ex:
188         xmed.err(ex.details.text)
189
190 # ===================================================================
191 # Field Data visualization
192 VIEWER_VISU    = "VISU"
193 VIEWER_PARAVIS = "PARAVIS"
194 VIEWER_DEFAULT = VIEWER_PARAVIS
195
196 import tempfile
197
198 def view_using_paravis(aFieldProxy):
199     temp = tempfile.NamedTemporaryFile(prefix="medop_viewer", suffix='.med', delete=False)
200
201     # __GBO__ TO BE IMPROVED: we used a tmp file in this first step of
202     # development, but we should used at last a MEDCoupling corba
203     # object (see how to use the stuff in PARAVIS/src/Plugins)
204     xmed.dataManager.saveFields(temp.name, [aFieldProxy.id])
205
206     from xmed.driver_pvis import pvis_scalarmap
207     pvis_scalarmap(temp.name,
208                    aFieldProxy.meshname,
209                    aFieldProxy.fieldname,
210                    aFieldProxy.type,
211                    aFieldProxy.iteration)
212     temp.close()
213 #
214
215 def view_using_visu(aFieldProxy):
216     # No more used
217     raise Exception("view_using_visu: No more used")
218
219     VIEWER_TMP_FILE = "/tmp/medop_viewer.med"
220
221     # __GBO__ TO BE IMPROVED: we used a tmp file in this first step of
222     # development, but we should used at last a MEDCoupling corba
223     # object (see how to use the stuff in PARAVIS/src/Plugins)
224     xmed.dataManager.saveFields(VIEWER_TMP_FILE, [aFieldProxy.id])
225
226     # __GBO__: WARN due to a specific feature of VISU, when only one
227     # field timestamps exists in the med file, we have to specify an
228     # iteration number of 1, whatever the iteration value is in the
229     # med file.
230     iteration = 1 # __GBO__ for bug VISU
231     # instead of:
232     # iteration = aFieldProxy.iteration
233
234     from xmed.driver_visu import visu_scalarmap
235     result = visu_scalarmap(VIEWER_TMP_FILE,
236                             aFieldProxy.meshname,
237                             aFieldProxy.fieldname,
238                             aFieldProxy.type,
239                             iteration)
240     if result is False:
241         xmed.err("the field can't be displayed")
242
243 def view(aFieldProxy, using=VIEWER_DEFAULT):
244     """
245     This displays a 3D view of the field using VISU or PARAVIS,
246     depending on the configuration. This view is for quick visual
247     control of a field and is not intended to be parametrizable. For
248     custom display, you should import the fields in VISU or PARAVIS
249     and continue the job in one of this SALOME module.
250     """
251     if using == VIEWER_PARAVIS:
252         view_using_paravis(aFieldProxy)
253     else:
254         view_using_visu(aFieldProxy)
255