]> SALOME platform Git repositories - modules/med.git/blob - src/MEDOP/cmp/MEDDataManager_i.cxx
Salome HOME
Add field interpolation to GUI
[modules/med.git] / src / MEDOP / cmp / MEDDataManager_i.cxx
1 // Copyright (C) 2007-2014  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // Authors : Guillaume Boulant (EDF) - 01/06/2011
21
22 #include "MEDDataManager_i.hxx"
23 #include "SALOME_KernelServices.hxx"
24 #include "Basics_DirUtils.hxx"
25 #include "Basics_Utils.hxx"
26
27 #include "MEDLoader.hxx"
28 using namespace ParaMEDMEM;
29
30 #include <string>
31 #include <vector>
32 using namespace std;
33
34 MEDDataManager_i * MEDDataManager_i::_instance = NULL;
35 long MEDDataManager_i::LONG_UNDEFINED = -1;
36
37 MEDDataManager_i * MEDDataManager_i::getInstance() {
38   // _GBO_ we will certainly need to define one single DataManager per
39   // SALOME study and not one singleton for the whole session
40   if ( _instance == NULL ) {
41     _instance = new MEDDataManager_i();
42   }
43   return _instance;
44 }
45
46 #define IOR_UNDEF "IOR UNDEFINED"
47 MEDDataManager_i::MEDDataManager_i()
48 {
49   LOG("Creating a MEDDataManager_i instance");
50   _fieldLastId = 0;
51   _sourceLastId = 0;
52   _meshLastId = 0;
53   _fieldseriesLastId = 0;
54 }
55 MEDDataManager_i::~MEDDataManager_i()
56 {
57   LOG("Deleting MEDDataManager_i instance");
58 }
59
60 std::string MEDDataManager_i::file_to_source(const char * filepath)
61 {
62   string source("file://");
63   source.append(filepath);
64   return source;
65 }
66
67 std::string MEDDataManager_i::source_to_file(const char * source)
68 {
69   string filepath(source);
70   filepath.replace(0,7,"");
71   return filepath;
72 }
73
74 /*!
75  * This function loads the meta-data from the specified med file and
76  * returns the associated datasource handler. The data source handler
77  * is a key to retrieve all informations concerning the data (meshes,
78  * fields).
79  */
80 MEDOP::DatasourceHandler * MEDDataManager_i::addDatasource(const char *filepath) {
81
82   // We first check that this datasource is not already registered
83   long sourceid = getDatasourceId(filepath);
84   if ( sourceid != LONG_UNDEFINED ) {
85     // The file is already registered under the identifier sourceid
86     LOG("WRN: The file "<<filepath<<" is already registered with id="<<ToString(sourceid));
87     return new MEDOP::DatasourceHandler(*_datasourceHandlerMap[sourceid]);
88   }
89
90   // Then we check that the file is readable by MEDLoader
91   MEDLoader::CheckFileForRead(filepath);
92
93   // Initialise the datasource handler
94   MEDOP::DatasourceHandler * datasourceHandler = new MEDOP::DatasourceHandler();
95   datasourceHandler->id = _sourceLastId; _sourceLastId++;
96   datasourceHandler->name = (Kernel_Utils::GetBaseName(filepath)).c_str();
97   std::string tmp(file_to_source(filepath));
98   datasourceHandler->uri = CORBA::string_dup(tmp.c_str());
99   _datasourceHandlerMap[datasourceHandler->id] = datasourceHandler;
100
101   // We start by read the list of meshes (spatial supports of fields)
102   vector<string> meshNames = MEDLoader::GetMeshNames(filepath);
103   int nbOfMeshes = meshNames.size();
104   for (int iMesh = 0; iMesh < nbOfMeshes; iMesh++) {
105     const char * meshName = meshNames[iMesh].c_str();
106     LOG("name of mesh " << iMesh << " = " << meshName);
107
108     MEDOP::MeshHandler * meshHandler = new MEDOP::MeshHandler();
109     meshHandler->id       = _meshLastId; _meshLastId++;
110     meshHandler->name     = meshName;
111     meshHandler->sourceid = datasourceHandler->id;
112
113     _meshHandlerMap[meshHandler->id] = meshHandler;
114
115     // For each mesh, we can read the list of the names of the
116     // associated fields, i.e. fields whose spatial support is this
117     // mesh.
118     vector<string> fieldNames = MEDLoader::GetAllFieldNamesOnMesh(filepath,
119                   meshName);
120     int nbOfFields = fieldNames.size();
121     for (int iField = 0; iField < nbOfFields; iField++) {
122       const char * fieldName = fieldNames[iField].c_str();
123       LOG("-- name of field " << iField << " = " << fieldName);
124
125       // A field name could identify several MEDCoupling fields, that
126       // differ by their spatial discretization on the mesh (values on
127       // cells, values on nodes, ...). This spatial discretization is
128       // specified by the TypeOfField that is an integer value in this
129       // list:
130       // 0 = ON_CELLS
131       // 1 = ON_NODES
132       // 2 = ON_GAUSS_PT
133       // 3 = ON_GAUSS_NE
134
135       // As a consequence, before loading values of a field, we have
136       // to determine the types of spatial discretization defined for
137       // this field and to chooose one.
138
139       vector<TypeOfField> listOfTypes = MEDLoader::GetTypesOfField(filepath,
140                    meshName,
141                    fieldName);
142       int nbOfTypes = listOfTypes.size();
143       for (int iType = 0; iType < nbOfTypes; iType++) {
144   LOG("---- type "<<iType<<" of field "<<iField<< " = " << listOfTypes[iType]);
145
146   // Then, we can get the iterations associated to this field on
147   // this type of spatial discretization:
148   std::vector< std::pair<int,int> > fieldIterations =
149     MEDLoader::GetFieldIterations(listOfTypes[iType],
150           filepath,
151           meshName,
152           fieldName);
153
154   int nbFieldIterations = fieldIterations.size();
155   LOG("---- nb. iterations = " << nbFieldIterations);
156
157   // We can define the timeseries of fields (fieldseries) for
158   // this type. A fieldseries is a macro object that handle the whole
159   // set of time iterations of a field.
160   MEDOP::FieldseriesHandler * fieldseriesHandler = new MEDOP::FieldseriesHandler();
161   fieldseriesHandler->id     = _fieldseriesLastId; _fieldseriesLastId++;
162   fieldseriesHandler->name   = fieldName;
163   fieldseriesHandler->type   = listOfTypes[iType];
164   fieldseriesHandler->meshid = meshHandler->id;
165   fieldseriesHandler->nbIter = nbFieldIterations;
166   _fieldseriesHandlerMap[fieldseriesHandler->id] = fieldseriesHandler;
167
168   // We can then load meta-data concerning all iterations
169   for (int iterationIdx=0; iterationIdx<nbFieldIterations; iterationIdx++) {
170
171     int iteration = fieldIterations[iterationIdx].first;
172     int order = fieldIterations[iterationIdx].second;
173
174     const char * source = datasourceHandler->uri;
175     MEDOP::FieldHandler * fieldHandler = newFieldHandler(fieldName,
176                      meshName,
177                      listOfTypes[iType],
178                      iteration,
179                      order,
180                      source);
181
182     fieldHandler->meshid = meshHandler->id;
183     fieldHandler->fieldseriesId = fieldseriesHandler->id;
184     _fieldHandlerMap[fieldHandler->id] = fieldHandler;
185   }
186       }
187     }
188   }
189
190   return new MEDOP::DatasourceHandler(*datasourceHandler);
191 }
192
193 long MEDDataManager_i::getDatasourceId(const char *filepath) {
194   std::string uri(file_to_source(filepath));
195   DatasourceHandlerMapIterator it = _datasourceHandlerMap.begin();
196   while ( it != _datasourceHandlerMap.end() ) {
197     if ( strcmp(it->second->uri,uri.c_str()) == 0 ) {
198       return it->first;
199     }
200     ++it;
201   }
202   return LONG_UNDEFINED;
203 }
204
205
206 MEDOP::MeshHandler * MEDDataManager_i::getMesh(CORBA::Long meshId) {
207   if ( _meshHandlerMap.count(meshId) == 0 ) {
208     std::string message =
209       std::string("The mesh of id=") + ToString(meshId) +
210       std::string(" does not exist in the data manager");
211     LOG(message);
212     throw KERNEL::createSalomeException(message.c_str());
213   }
214   return new MEDOP::MeshHandler(*(_meshHandlerMap[meshId]));
215 }
216
217
218 /*!
219  * This function returns the list of mesh handlers associated to the
220  * specified datasource. It corresponds to the list ofmeshes defined
221  * in the datasource.
222  */
223 MEDOP::MeshHandlerList * MEDDataManager_i::getMeshList(CORBA::Long datasourceId) {
224
225   // We initiate a list with the maximum lentgh
226   MEDOP::MeshHandlerList_var meshHandlerList = new MEDOP::MeshHandlerList();
227   meshHandlerList->length(_meshHandlerMap.size());
228
229   // Scan the map looking for meshes associated to the specified datasource
230   int itemIdx = 0;
231   MeshHandlerMapIterator meshIt;
232   for ( meshIt=_meshHandlerMap.begin(); meshIt != _meshHandlerMap.end(); meshIt++) {
233     if ( meshIt->second->sourceid == datasourceId ) {
234       meshHandlerList[itemIdx] = *(meshIt->second);
235       itemIdx++;
236     }
237   }
238
239   // Adjust the length to the real number of elements
240   meshHandlerList->length(itemIdx);
241   return meshHandlerList._retn();
242 }
243
244 /*!
245  * This function returns the list of fieldseries defined on the
246  * specified mesh.
247  */
248 MEDOP::FieldseriesHandlerList * MEDDataManager_i::getFieldseriesListOnMesh(CORBA::Long meshId) {
249   // We initiate a list with the maximum lentgh
250   MEDOP::FieldseriesHandlerList_var
251     fieldseriesHandlerList = new MEDOP::FieldseriesHandlerList();
252   fieldseriesHandlerList->length(_fieldseriesHandlerMap.size());
253
254   // Scan the map looking for fieldseries defined on the specified mesh
255   int itemIdx = 0;
256   FieldseriesHandlerMapIterator it;
257   for ( it=_fieldseriesHandlerMap.begin(); it != _fieldseriesHandlerMap.end(); it++) {
258     if ( it->second->meshid == meshId ) {
259       fieldseriesHandlerList[itemIdx] = *(it->second);
260       itemIdx++;
261     }
262   }
263
264   // Adjust the length to the real number of elements
265   fieldseriesHandlerList->length(itemIdx);
266   return fieldseriesHandlerList._retn();
267 }
268
269 /*!
270  * A fieldseries is a timeseries of fields. Then the list of fields is
271  * the different time iterations defined for the specified field id.
272  */
273 MEDOP::FieldHandlerList * MEDDataManager_i::getFieldListInFieldseries(CORBA::Long fieldseriesId) {
274
275   // We initiate a list with the maximum lentgh
276   MEDOP::FieldHandlerList_var fieldHandlerList = new MEDOP::FieldHandlerList();
277   fieldHandlerList->length(_fieldHandlerMap.size());
278
279   // Scan the map looking for field defined on the specified mesh
280   int itemIdx = 0;
281   FieldHandlerMapIterator it;
282   for ( it=_fieldHandlerMap.begin(); it != _fieldHandlerMap.end(); it++) {
283     if ( it->second->fieldseriesId == fieldseriesId ) {
284       fieldHandlerList[itemIdx] = *(it->second);
285       itemIdx++;
286     }
287   }
288
289   // Adjust the length to the real number of elements
290   fieldHandlerList->length(itemIdx);
291   return fieldHandlerList._retn();
292 }
293
294 /*!
295  * This returns the whole set of fields handlers for all datasource
296  * that have been loaded using addDatasource.
297  */
298 MEDOP::FieldHandlerList * MEDDataManager_i::getFieldHandlerList() {
299   MEDOP::FieldHandlerList_var fieldHandlerSeq = new MEDOP::FieldHandlerList();
300   fieldHandlerSeq->length(_fieldHandlerMap.size());
301
302   int sequenceId = 0;
303   FieldHandlerMapIterator fieldIt;
304   for ( fieldIt=_fieldHandlerMap.begin(); fieldIt != _fieldHandlerMap.end(); fieldIt++) {
305     fieldHandlerSeq[sequenceId] = *(fieldIt->second);
306     sequenceId++;
307   }
308   return fieldHandlerSeq._retn();
309 }
310
311 /*!
312  * This returns a copy of the fieldHandler associated to the specified id.
313  */
314 MEDOP::FieldHandler * MEDDataManager_i::getFieldHandler(CORBA::Long fieldHandlerId) {
315   LOG("getFieldHandler: START")
316
317   FieldHandlerMapIterator fieldIt = _fieldHandlerMap.find(fieldHandlerId);
318   if ( fieldIt != _fieldHandlerMap.end() ) {
319     // >>> WARNING: CORBA struct specification indicates that the
320     // assignement acts as a desctructor for the structure that is
321     // pointed to. The values of the fields are copy first in the new
322     // structure that receives the assignement and finally the initial
323     // structure is destroyed. In the present case, WE WANT to keep
324     // the initial fieldHandler in the map. We must then make a deep
325     // copy of the structure found in the map and return the copy. The
326     // CORBA struct specification indicates that a deep copy can be
327     // done using the copy constructor.  <<<
328     return new MEDOP::FieldHandler(*(fieldIt->second));
329   }
330   return NULL;
331 }
332
333 /*!
334  * This returns a string representation of the field associated to the specified id.
335  */
336 char * MEDDataManager_i::getFieldRepresentation(CORBA::Long fieldHandlerId) {
337   LOG("getFieldRepresentation: START")
338   MEDOP::FieldHandler * fieldHandler = getFieldHandler(fieldHandlerId);
339   MEDCouplingFieldDouble* fieldDouble = getFieldDouble(fieldHandler);
340   return CORBA::string_dup(fieldDouble->getArray()->repr().c_str());
341 }
342
343 void MEDDataManager_i::saveFields(const char * filepath,
344           const MEDOP::FieldIdList & fieldIdList)
345 {
346   LOG("saveFields to : " << filepath);
347
348   // We first have to check if the target filepath is writable
349   // (segmentation fault in med otherwise)
350   if (!Kernel_Utils::IsWritable(Kernel_Utils::GetDirName(std::string(filepath)))) {
351     std::string message =
352       std::string("The target filepath ") +
353       std::string(filepath) +
354       std::string(" is not writable");
355     LOG(message);
356     throw KERNEL::createSalomeException(message.c_str());
357   }
358
359   if ( fieldIdList.length() == 0 ) {
360     throw KERNEL::createSalomeException("No fields to save");
361   }
362
363   // Consider the first field to initiate the med file
364   CORBA::Long fieldHandlerId = fieldIdList[0];
365   MEDOP::FieldHandler * fieldHandler = getFieldHandler(fieldHandlerId);
366   MEDCouplingFieldDouble* fieldDouble = getFieldDouble(fieldHandler);
367
368   try {
369     bool writeFromScratch = true;
370     MEDLoader::WriteField(filepath, fieldDouble, writeFromScratch);
371
372     writeFromScratch = false;
373     for(CORBA::ULong i=1; i<fieldIdList.length(); i++) {
374       fieldHandlerId = fieldIdList[i];
375       fieldHandler = getFieldHandler(fieldHandlerId);
376       fieldDouble = getFieldDouble(fieldHandler);
377       MEDLoader::WriteField(filepath, fieldDouble, writeFromScratch);
378     }
379   }
380   catch (INTERP_KERNEL::Exception &ex) {
381     std::string message =
382       std::string("Error when saving file ") +
383       std::string(filepath) + std::string(" : ") + ex.what();
384     throw KERNEL::createSalomeException(message.c_str());
385   }
386   catch (const std::exception& ex) {
387     std::string message =
388       std::string("Error when saving file ") +
389       std::string(filepath) + std::string(" : ") + ex.what();
390     throw KERNEL::createSalomeException(message.c_str());
391   }
392
393 }
394
395 /*!
396  * This function must be used to indicate that the field with the
397  * specified id must be considered as persistent (if persistent is
398  * true) or not persistent (if persistent is false). If a field is
399  * marked as persistent, then it is automatically saved when the
400  * function savePersistentFields is called.
401  */
402 void MEDDataManager_i::markAsPersistent(CORBA::Long fieldHandlerId, bool persistent) {
403   LOG("mark as persistant : id="<<fieldHandlerId);
404   _fieldPersistencyMap[fieldHandlerId] = persistent;
405 }
406
407 void MEDDataManager_i::savePersistentFields(const char * filepath) {
408   LOG("savePersistentFields to : " << filepath);
409   std::vector<long> listId;
410
411   FieldPersistencyMapIterator mapIt;
412   for ( mapIt = _fieldPersistencyMap.begin(); mapIt != _fieldPersistencyMap.end(); mapIt++) {
413     if ( mapIt->second == true ) {
414       listId.push_back(mapIt->first);
415     }
416   }
417
418   MEDOP::FieldIdList fieldIdList;
419   fieldIdList.length(listId.size());
420   for (int i=0; i<listId.size(); i++) {
421     fieldIdList[i] = CORBA::Long(listId[i]);
422   }
423
424   try {
425     this->saveFields(filepath, fieldIdList);
426   }
427   catch (const SALOME::SALOME_Exception & ex) {
428     throw ex;
429   }
430   catch (const std::exception& ex) {
431     std::string message =
432       std::string("Error when saving file ") +
433       std::string(filepath) + std::string(" : ") + ex.what();
434     throw KERNEL::createSalomeException(message.c_str());
435   }
436 }
437
438 /*!
439  * This function is responsible for creating the FieldHandler
440  * instances. You must use this function because it manages
441  * automatically the identifier value (autoincrementation of a static
442  * variable)
443  */
444 MEDOP::FieldHandler * MEDDataManager_i::newFieldHandler(const char * fieldname,
445               const char * meshname,
446               TypeOfField  type,
447               long         iteration,
448               long         order,
449               const char * source)
450 {
451   MEDOP::FieldHandler * fieldHandler = new MEDOP::FieldHandler();
452   fieldHandler->id = _fieldLastId; _fieldLastId++;
453   fieldHandler->fieldname = fieldname;
454   fieldHandler->meshname  = meshname;
455   fieldHandler->type      = type;
456   fieldHandler->iteration = iteration;
457   fieldHandler->order     = order;
458   fieldHandler->source    = source;
459   return fieldHandler;
460 }
461
462 /*!
463  * This updates the metadata of the field identified by its id with
464  * the data of the given field handler. Returns a copy of the updated
465  * handler (that should be identical to the given field handler for
466  * all data but not for the id that is an invariant for all session
467  * long).
468  * WARN: you should be warned that this function could leave the data
469  * model in a non-coherent state, by example if you change the mesh
470  * name while the mesh has not been updated.
471  */
472 MEDOP::FieldHandler * MEDDataManager_i::updateFieldHandler(CORBA::Long fieldHandlerId,
473                  const char * fieldname,
474                  long         iteration,
475                  long         order,
476                  const char * source) {
477   FieldHandlerMapIterator fieldIt = _fieldHandlerMap.find(fieldHandlerId);
478   if ( fieldIt != _fieldHandlerMap.end() ) {
479     // Update the attributes
480     // >>> WARN: note that the id of a handler registered in the map
481     // SHOULD NEVER be modified because it is the identifier used in
482     // the whole application for this field all the session long.
483     // <<<
484     fieldIt->second->fieldname = fieldname;
485     fieldIt->second->iteration = iteration;
486     fieldIt->second->order     = order;
487     fieldIt->second->source    = source;
488     // Return a copy
489     return new MEDOP::FieldHandler(*fieldIt->second);
490   }
491   return NULL;
492 }
493
494 MEDCouplingUMesh * MEDDataManager_i::getUMesh(long meshHandlerId) {
495
496   LOG("getUMesh: START")
497
498   MEDCouplingUMesh * myMesh = NULL;
499   if ( _meshMap.count(meshHandlerId) > 0 ) {
500     // The mesh has been found in the map
501     myMesh = _meshMap[meshHandlerId];
502   } else {
503     // The mesh is not loaded yet ==> load it and register it in the map
504     LOG("getUMesh: the mesh must be loaded. meshid="<<meshHandlerId);
505     if ( _meshHandlerMap[meshHandlerId] == NULL ) {
506       std::string message =
507   std::string("No mesh for id=") + ToString(meshHandlerId);
508       LOG("getUMesh: "<<message);
509       throw KERNEL::createSalomeException(message.c_str());
510     }
511
512     long sourceid = _meshHandlerMap[meshHandlerId]->sourceid;
513     std::string filepath(source_to_file((_datasourceHandlerMap[sourceid])->uri));
514     const char * meshName = _meshHandlerMap[meshHandlerId]->name;
515     int meshDimRelToMax = 0;
516     myMesh = MEDLoader::ReadUMeshFromFile(filepath,meshName,meshDimRelToMax);
517     _meshMap[meshHandlerId] = myMesh;
518   }
519   return myMesh;
520 }
521
522 /**
523  * Try to retrieve the id of the specified mesh, i.e. the key it is
524  * registered with in the internal meshes map.
525  */
526 long MEDDataManager_i::getUMeshId(const MEDCouplingMesh * mesh) {
527   bool found = false;
528   MeshMapIterator it = _meshMap.begin();
529   while ( it != _meshMap.end() ) {
530     found = (it->second == mesh);
531     if (found) {
532       return it->first;
533     }
534     ++it;
535   }
536   return LONG_UNDEFINED;
537 }
538
539 /*!
540  * This method returns the physical data of the specified field,
541  * i.e. the MEDCoupling field associated to the specified field
542  * handler. If the field source is a file and the data ar not loaded
543  * yet, the this function load the data from the file in a MEDCoupling
544  * field instance. Otherwize, it just returns the MEDCoupling field
545  * instance.
546  */
547 MEDCouplingFieldDouble * MEDDataManager_i::getFieldDouble(const MEDOP::FieldHandler * fieldHandler)
548 {
549
550   LOG("getFieldDouble: START with id="<<fieldHandler->id);
551
552   if ( _fieldDoubleMap.count(fieldHandler->id) > 0 ) {
553   // The MEDCoupling field data are already loaded. Just return the
554   // reference of the MEDCouplingFieldDouble pointer
555     return _fieldDoubleMap[fieldHandler->id];
556   }
557
558   // The MEDCoupling field data are not loaded yet. Load the data and
559   // register the MEDCoupling field in our internal map an all the
560   // associated data if needed (i.e. the underlying mesh).
561
562   // At this step, the mesh handler needs a meshid correctly
563   // set. Normally, we should arrive at this step only in the case
564   // where the field is loaded from a file ==> the meshid is defined
565   // (see the addDatasource function).
566   //
567   // >>>> __GBO__ TO BE CHECKED AND SERIOUSLY TESTED. There at least
568   // one case where we can arrive here with no previous call to
569   // addDataSource: for example the field handler list can be obtained
570   // from a call to addFieldsFromFile instead of addDataSource (see
571   // for exemple the getFieldRepresentation service of the
572   // dataManager, that comes here and then calls getUMesh where we
573   // need a map initialized only in addDataSource) <<<<
574   long meshid = fieldHandler->meshid;
575
576   // We first have to check if the associated mesh is already loaded
577   // and to load it if needed. The loaded meshes are registered in a
578   // map whose key is the mesh handler id. This checking is
579   // automatically done by the function getUMesh. It's important to do
580   // it before the loading of field data to prevent from the case
581   // where the mesh would not have been loaded already (in the
582   // previous field loading).
583   MEDCouplingUMesh * myMesh =this->getUMesh(meshid);
584
585   long sourceid = _meshHandlerMap[meshid]->sourceid;
586
587   std::string filepath(source_to_file((_datasourceHandlerMap[sourceid])->uri));
588   std::string meshName(myMesh->getName());
589   LOG("getFieldDouble: field "<<fieldHandler->fieldname<<" loaded from file "<<filepath);
590   TypeOfField type = (TypeOfField)fieldHandler->type;
591   int meshDimRelToMax = 0;
592   MEDCouplingFieldDouble * myField = MEDLoader::ReadField(type,
593                 filepath,
594                 meshName,
595                 meshDimRelToMax,
596                 std::string(fieldHandler->fieldname),
597                 fieldHandler->iteration,
598                 fieldHandler->order);
599   myField->setMesh(myMesh);
600   _fieldDoubleMap[fieldHandler->id] = myField;
601   return myField;
602 }
603
604 /*!
605  * This adds the specified MEDCoupling field in the collection managed
606  * by this DataManager. The associated FieldHandler is returned. This
607  * is typically used in a context where the MEDCoupling field is
608  * created from scratch, for example by operations in the
609  * MEDCalculator.
610  * @param[in] fieldDouble   the MEDCouplingFieldDouble instance to add
611  * @param[in] meshHandlerId the id of the meshHandler this filed is associated to.
612  * @return a copy of the FieldHandler registered in the internal map for this field.
613  */
614 MEDOP::FieldHandler * MEDDataManager_i::addField(MEDCouplingFieldDouble * fieldDouble,
615              long meshHandlerId)
616 {
617   std::string fieldName(fieldDouble->getName());
618   std::string meshName(fieldDouble->getMesh()->getName());
619   TypeOfField  type      = fieldDouble->getTypeOfField();
620
621   int iteration, order;
622   // WARN: note that the variables "iteration" and "order" are passed
623   // by reference to the function getTime (see documentation of
624   // MEDCouplingField). As a consequence, the values of these
625   // variables are updated by this function call. This is the mean to
626   // retrieve the iteration and order of the field.
627   double timestamp = fieldDouble->getTime(iteration, order);
628
629   // For the fields that are created in memory (by operations for
630   // example), the convention for the source attribute is to specify
631   // the fielddouble name, because this name describes the operation
632   // the field has been created with.
633   string * source = new string("mem://"); source->append(fieldName);
634   MEDOP::FieldHandler * fieldHandler = newFieldHandler(fieldName.c_str(),
635                                                        meshName.c_str(),
636                                                        type,
637                                                        iteration,
638                                                        order,
639                                                        source->c_str());
640
641   if ( meshHandlerId == LONG_UNDEFINED ) {
642     // We have to gess the id of the underlying mesh to preserve data
643     // integrity (a fieldHandler must have an attribute that contains
644     // the id of its underlying mesh):
645     //
646     // WARNING: it's better to let the client code (the one who calls the
647     // function addField) to specify this meshid. This guess procedure is
648     // not reliable, it's just to have a second chance.
649     //
650     LOG("addField: The mesh id is not defined. Trying to guess from the mesh name "<<meshName);
651     long meshid = this->getUMeshId(fieldDouble->getMesh());
652     fieldHandler->meshid = meshid;
653     if ( meshid == LONG_UNDEFINED ) {
654       // No mesh has been found in the internal map
655       LOG("addField: The mesh id for the mesh "<<meshName<<" can't be retrieved from the field "<<fieldName);
656       // _GBO_ : Maybe it could be better to raise an exception
657     }
658   }
659   else {
660     fieldHandler->meshid = meshHandlerId;
661   }
662
663   _fieldHandlerMap[fieldHandler->id] = fieldHandler;
664   _fieldDoubleMap[fieldHandler->id] = fieldDouble;
665   // >>> WARNING: CORBA structure assignement specification ==> return
666   // >>> a deep copy to avoid the destruction of the fieldHandler
667   // >>> registered in the map (assignement acts as a destructor for
668   // >>> CORBA struct).
669   return new MEDOP::FieldHandler(*fieldHandler);
670 }
671
672 /*!
673  * This function updates the meta-data "fieldname" associated to the
674  * specified field.
675  */
676 void MEDDataManager_i::updateFieldMetadata(CORBA::Long  fieldHandlerId,
677              const char * fieldname,
678              CORBA::Long  iteration,
679              CORBA::Long  order,
680              const char * source)
681 {
682   // We have to update the field handler registered in the internal
683   // map AND the associated fieldDouble loaded in memory.
684   MEDOP::FieldHandler * fieldHandler = getFieldHandler(fieldHandlerId);
685   updateFieldHandler(fieldHandlerId,fieldname,iteration,order,source);
686
687   MEDCouplingFieldDouble* fieldDouble = getFieldDouble(fieldHandler);
688   fieldDouble->setName(fieldname);
689
690   // _GBO_ TO BE IMPLEMENTED: iteration and order
691 }
692
693 /**
694  * This can be used to associate to the specified field another mesh
695  * support than its current one. This is typically needed to operate 2
696  * fields defined on the same mesh but coming from different med
697  * files. In this case, the underlying meshes are different mesh
698  * objects (from the MEDCoupling point of view) and then no operation
699  * can be allowed by MEDCoupling. The operation of course fails if the
700  * new mesh is not identical to the old one.
701  */
702 void MEDDataManager_i::changeUnderlyingMesh(CORBA::Long fieldHandlerId, CORBA::Long meshHandlerId) {
703
704   MEDOP::FieldHandler * fieldHandler = getFieldHandler(fieldHandlerId);
705   MEDCouplingFieldDouble* fieldDouble = getFieldDouble(fieldHandler);
706   MEDCouplingMesh * newMesh = getUMesh(meshHandlerId);
707
708   try {
709     fieldDouble->changeUnderlyingMesh(newMesh,10,1e-12);
710   }
711   catch (INTERP_KERNEL::Exception &ex) {
712     std::string * message = new std::string("Error when changing the underlying mesh : ");
713     message->append(ex.what());
714     throw KERNEL::createSalomeException(message->c_str());
715   }
716
717   // The change of mesh is OK, then we can update the meta-data
718   _fieldHandlerMap[fieldHandlerId]->meshid = meshHandlerId;
719   _fieldHandlerMap[fieldHandlerId]->meshname = _meshHandlerMap[meshHandlerId]->name;
720
721
722   // WARN: if this field has already been request by the tui for
723   // manipulation (in a fieldproxy), then the data should be
724   // synchronized
725 }
726
727 INTERP_KERNEL::IntersectionType MEDDataManager_i::_getIntersectionType(const char* intersType) {
728   std::string type(intersType);
729   if (type == "Triangulation") {
730     return INTERP_KERNEL::Triangulation;
731   }
732   else if (type == "Convex") {
733     return INTERP_KERNEL::Convex;
734   }
735   else if (type == "Geometric2D") {
736     return INTERP_KERNEL::Geometric2D;
737   }
738   else if (type == "PointLocator") {
739     return INTERP_KERNEL::PointLocator;
740   }
741   else if (type == "Barycentric") {
742     return INTERP_KERNEL::Barycentric;
743   }
744   else if (type == "BarycentricGeo2D") {
745     return INTERP_KERNEL::BarycentricGeo2D;
746   }
747
748   std::string message("Error when trying to interpolate field: ");
749   message.append("Unrecognized intersection type: ");
750   message.append(type);
751   throw KERNEL::createSalomeException(message.c_str());
752 }
753
754 ParaMEDMEM::NatureOfField MEDDataManager_i::_getNatureOfField(const char* fieldNature) {
755   std::string nature(fieldNature);
756   if (nature == "NoNature") {
757     return NoNature;
758   }
759   else if (nature == "ConservativeVolumic") {
760     return ConservativeVolumic;
761   }
762   else if (nature == "Integral") {
763     return Integral;
764   }
765   else if (nature == "IntegralGlobConstraint") {
766     return IntegralGlobConstraint;
767   }
768   else if (nature == "RevIntegral") {
769     return RevIntegral;
770   }
771
772   std::string message("Error when trying to interpolate field: ");
773   message.append("Unrecognized field nature: ");
774   message.append(nature);
775   throw KERNEL::createSalomeException(message.c_str());
776 }
777
778 MEDOP::FieldHandler* MEDDataManager_i::interpolateField(CORBA::Long fieldHandlerId, CORBA::Long meshHandlerId, const MEDOP::InterpolationParameters& params) {
779   MEDOP::FieldHandler* fieldHandler = getFieldHandler(fieldHandlerId);
780   MEDCouplingFieldDouble* sourceField = getFieldDouble(fieldHandler);
781   MEDCouplingMesh* sourceMesh = getUMesh(fieldHandler->meshid);
782   MEDCouplingMesh* targetMesh = getUMesh(meshHandlerId);
783
784   double precision = params.precision;
785   INTERP_KERNEL::IntersectionType interpType = this->_getIntersectionType(params.intersectionType);
786   std::string method(params.method);
787   double defaultValue = params.defaultValue;
788   bool reverse = params.reverse;
789   ParaMEDMEM::NatureOfField nature = this->_getNatureOfField(params.nature);
790
791   // 1. Build remapper between sourceMesh and targetMesh (compute interpolation matrix)
792   MEDCouplingRemapper remapper;
793   remapper.setPrecision(precision);
794   remapper.setIntersectionType(interpType);
795   remapper.prepare(sourceMesh, targetMesh, method.c_str());
796
797   // 2. Apply interpolation to the field
798   sourceField->setNature(nature);
799   MEDCouplingFieldDouble* targetField = NULL;
800   if (reverse) {
801     targetField = remapper.reverseTransferField(sourceField, defaultValue);
802   } else {
803     targetField = remapper.transferField(sourceField, defaultValue);
804   }
805   targetField->setMesh(targetMesh);
806   targetField->setName(targetMesh->getName() + "_field");
807
808   // 3. Create and register field handler
809   MEDOP::FieldHandler* fieldResultHandler = this->addField(targetField, this->getUMeshId(targetField->getMesh()));
810   return fieldResultHandler;
811 }
812
813
814
815 /*!
816  * This functions display the internal data of the MEDDataManager on
817  * the server side (data in the SALOME container).
818  */
819 void MEDDataManager_i::serverlog() {
820
821   LOG("==== Field Handler Map ====================================================");
822   LOG("Size = "<<_fieldHandlerMap.size());
823   FieldHandlerMapIterator fhmIt;
824   for ( fhmIt = _fieldHandlerMap.begin(); fhmIt != _fieldHandlerMap.end(); fhmIt++) {
825     long id = fhmIt->first;
826     LOG("------------------------------------- id = "<<ToString(id));
827     LOG("- id        \t= "<<fhmIt->second->id);
828     LOG("- fieldname \t= "<<fhmIt->second->fieldname);
829     LOG("- meshname  \t= "<<fhmIt->second->meshname);
830   }
831
832   LOG("==== Field Double Map ====================================================");
833   LOG("Size = "<<_fieldDoubleMap.size());
834   FieldDoubleMapIterator fdmIt;
835   for ( fdmIt = _fieldDoubleMap.begin(); fdmIt != _fieldDoubleMap.end(); fdmIt++) {
836     long id = (*fdmIt).first;
837     MEDCouplingFieldDouble * fieldDouble = (*fdmIt).second;
838     LOG("------------------------------------- id = "<<ToString(id));
839     LOG("- fieldname \t= "<<fieldDouble->getName());
840     LOG("- meshname  \t= "<<fieldDouble->getMesh()->getName());
841   }
842 }
843
844 /*!
845  * The event listener is created inside the GUI by the
846  * WorkspaceController. This function is called by the WorkspaceController to
847  * store the event listener IOR for the time of the session. Then this
848  * IOR can be available to any point of the application that can
849  * request the data manager (the python console for example).
850  */
851 void MEDDataManager_i::setEventListenerIOR(const char * ior) {
852   _medEventListenerIOR = ior;
853 }
854 /*!
855  * Return the IOR of the event listener that resides in the
856  * GUI. Having the IOR, you can restore the CORBA object by using:
857  *
858  * In a python SALOME context:
859  *
860  * >>> import salome
861  * >>> salome.salome_init()
862  * >>> myobject = salome.orb.string_to_object(ior)
863  *
864  * In a C++ SALOME context: (to do if needed)
865  */
866 char * MEDDataManager_i::getEventListenerIOR() {
867   if ( _medEventListenerIOR == "" ) {
868     throw KERNEL::createSalomeException("The event listener IOR is not defined");
869   }
870   // WARN: return a copy because the pointer memory will be released
871   // (CORBA specification)
872   return CORBA::string_dup( _medEventListenerIOR.c_str() );
873 }