Salome HOME
[Huge] Introducing MEDCalc
[modules/med.git] / src / MEDCalc / cmp / MEDDataManager_i.cxx
1 // Copyright (C) 2007-2015  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 MEDCALC::DatasourceHandler * MEDDataManager_i::loadDatasource(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 MEDCALC::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   MEDCALC::DatasourceHandler * datasourceHandler = new MEDCALC::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     MEDCALC::MeshHandler * meshHandler = new MEDCALC::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   MEDCALC::FieldseriesHandler * fieldseriesHandler = new MEDCALC::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     MEDCALC::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 MEDCALC::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 MEDCALC::DatasourceHandler*
206 MEDDataManager_i::getDatasourceHandler(const char *filepath)
207 {
208   std::string uri(file_to_source(filepath));
209   DatasourceHandlerMapIterator it = _datasourceHandlerMap.begin();
210   while ( it != _datasourceHandlerMap.end() ) {
211     if ( strcmp(it->second->uri,uri.c_str()) == 0 ) {
212       return it->second;
213     }
214     ++it;
215   }
216   return NULL;
217 }
218
219
220 MEDCALC::MeshHandler * MEDDataManager_i::getMesh(CORBA::Long meshId) {
221   if ( _meshHandlerMap.count(meshId) == 0 ) {
222     std::string message =
223       std::string("The mesh of id=") + ToString(meshId) +
224       std::string(" does not exist in the data manager");
225     LOG(message);
226     throw KERNEL::createSalomeException(message.c_str());
227   }
228   return new MEDCALC::MeshHandler(*(_meshHandlerMap[meshId]));
229 }
230
231
232 /*!
233  * This function returns the list of mesh handlers associated to the
234  * specified datasource. It corresponds to the list ofmeshes defined
235  * in the datasource.
236  */
237 MEDCALC::MeshHandlerList * MEDDataManager_i::getMeshList(CORBA::Long datasourceId) {
238
239   // We initiate a list with the maximum lentgh
240   MEDCALC::MeshHandlerList_var meshHandlerList = new MEDCALC::MeshHandlerList();
241   meshHandlerList->length(_meshHandlerMap.size());
242
243   // Scan the map looking for meshes associated to the specified datasource
244   int itemIdx = 0;
245   MeshHandlerMapIterator meshIt;
246   for ( meshIt=_meshHandlerMap.begin(); meshIt != _meshHandlerMap.end(); meshIt++) {
247     if ( meshIt->second->sourceid == datasourceId ) {
248       meshHandlerList[itemIdx] = *(meshIt->second);
249       itemIdx++;
250     }
251   }
252
253   // Adjust the length to the real number of elements
254   meshHandlerList->length(itemIdx);
255   return meshHandlerList._retn();
256 }
257
258 /*!
259  * This function returns the list of fieldseries defined on the
260  * specified mesh.
261  */
262 MEDCALC::FieldseriesHandlerList * MEDDataManager_i::getFieldseriesListOnMesh(CORBA::Long meshId) {
263   // We initiate a list with the maximum lentgh
264   MEDCALC::FieldseriesHandlerList_var
265     fieldseriesHandlerList = new MEDCALC::FieldseriesHandlerList();
266   fieldseriesHandlerList->length(_fieldseriesHandlerMap.size());
267
268   // Scan the map looking for fieldseries defined on the specified mesh
269   int itemIdx = 0;
270   FieldseriesHandlerMapIterator it;
271   for ( it=_fieldseriesHandlerMap.begin(); it != _fieldseriesHandlerMap.end(); it++) {
272     if ( it->second->meshid == meshId ) {
273       fieldseriesHandlerList[itemIdx] = *(it->second);
274       itemIdx++;
275     }
276   }
277
278   // Adjust the length to the real number of elements
279   fieldseriesHandlerList->length(itemIdx);
280   return fieldseriesHandlerList._retn();
281 }
282
283 /*!
284  * A fieldseries is a timeseries of fields. Then the list of fields is
285  * the different time iterations defined for the specified field id.
286  */
287 MEDCALC::FieldHandlerList * MEDDataManager_i::getFieldListInFieldseries(CORBA::Long fieldseriesId) {
288
289   // We initiate a list with the maximum lentgh
290   MEDCALC::FieldHandlerList_var fieldHandlerList = new MEDCALC::FieldHandlerList();
291   fieldHandlerList->length(_fieldHandlerMap.size());
292
293   // Scan the map looking for field defined on the specified mesh
294   int itemIdx = 0;
295   FieldHandlerMapIterator it;
296   for ( it=_fieldHandlerMap.begin(); it != _fieldHandlerMap.end(); it++) {
297     if ( it->second->fieldseriesId == fieldseriesId ) {
298       fieldHandlerList[itemIdx] = *(it->second);
299       itemIdx++;
300     }
301   }
302
303   // Adjust the length to the real number of elements
304   fieldHandlerList->length(itemIdx);
305   return fieldHandlerList._retn();
306 }
307
308 /*!
309  * This returns the whole set of fields handlers for all datasource
310  * that have been loaded using loadDatasource.
311  */
312 MEDCALC::FieldHandlerList * MEDDataManager_i::getFieldHandlerList() {
313   MEDCALC::FieldHandlerList_var fieldHandlerSeq = new MEDCALC::FieldHandlerList();
314   fieldHandlerSeq->length(_fieldHandlerMap.size());
315
316   int sequenceId = 0;
317   FieldHandlerMapIterator fieldIt;
318   for ( fieldIt=_fieldHandlerMap.begin(); fieldIt != _fieldHandlerMap.end(); fieldIt++) {
319     fieldHandlerSeq[sequenceId] = *(fieldIt->second);
320     sequenceId++;
321   }
322   return fieldHandlerSeq._retn();
323 }
324
325 /*!
326  * This returns a copy of the fieldHandler associated to the specified id.
327  */
328 MEDCALC::FieldHandler * MEDDataManager_i::getFieldHandler(CORBA::Long fieldHandlerId) {
329   LOG("getFieldHandler: START")
330
331   FieldHandlerMapIterator fieldIt = _fieldHandlerMap.find(fieldHandlerId);
332   if ( fieldIt != _fieldHandlerMap.end() ) {
333     // >>> WARNING: CORBA struct specification indicates that the
334     // assignement acts as a desctructor for the structure that is
335     // pointed to. The values of the fields are copy first in the new
336     // structure that receives the assignement and finally the initial
337     // structure is destroyed. In the present case, WE WANT to keep
338     // the initial fieldHandler in the map. We must then make a deep
339     // copy of the structure found in the map and return the copy. The
340     // CORBA struct specification indicates that a deep copy can be
341     // done using the copy constructor.  <<<
342     return new MEDCALC::FieldHandler(*(fieldIt->second));
343   }
344   return NULL;
345 }
346
347 /*!
348  * This returns a string representation of the field associated to the specified id.
349  */
350 char * MEDDataManager_i::getFieldRepresentation(CORBA::Long fieldHandlerId) {
351   LOG("getFieldRepresentation: START")
352   MEDCALC::FieldHandler * fieldHandler = getFieldHandler(fieldHandlerId);
353   MEDCouplingFieldDouble* fieldDouble = getFieldDouble(fieldHandler);
354   return CORBA::string_dup(fieldDouble->getArray()->repr().c_str());
355 }
356
357 void MEDDataManager_i::saveFields(const char * filepath,
358           const MEDCALC::FieldIdList & fieldIdList)
359 {
360   LOG("saveFields to : " << filepath);
361
362   // We first have to check if the target filepath is writable
363   // (segmentation fault in med otherwise)
364   if (!Kernel_Utils::IsWritable(Kernel_Utils::GetDirName(std::string(filepath)))) {
365     std::string message =
366       std::string("The target filepath ") +
367       std::string(filepath) +
368       std::string(" is not writable");
369     LOG(message);
370     throw KERNEL::createSalomeException(message.c_str());
371   }
372
373   if ( fieldIdList.length() == 0 ) {
374     throw KERNEL::createSalomeException("No fields to save");
375   }
376
377   // Consider the first field to initiate the med file
378   CORBA::Long fieldHandlerId = fieldIdList[0];
379   MEDCALC::FieldHandler * fieldHandler = getFieldHandler(fieldHandlerId);
380   MEDCouplingFieldDouble* fieldDouble = getFieldDouble(fieldHandler);
381
382   try {
383     bool writeFromScratch = true;
384     MEDLoader::WriteField(filepath, fieldDouble, writeFromScratch);
385
386     writeFromScratch = false;
387     for(CORBA::ULong i=1; i<fieldIdList.length(); i++) {
388       fieldHandlerId = fieldIdList[i];
389       fieldHandler = getFieldHandler(fieldHandlerId);
390       fieldDouble = getFieldDouble(fieldHandler);
391       MEDLoader::WriteField(filepath, fieldDouble, writeFromScratch);
392     }
393   }
394   catch (INTERP_KERNEL::Exception &ex) {
395     std::string message =
396       std::string("Error when saving file ") +
397       std::string(filepath) + std::string(" : ") + ex.what();
398     throw KERNEL::createSalomeException(message.c_str());
399   }
400   catch (const std::exception& ex) {
401     std::string message =
402       std::string("Error when saving file ") +
403       std::string(filepath) + std::string(" : ") + ex.what();
404     throw KERNEL::createSalomeException(message.c_str());
405   }
406
407 }
408
409 /*!
410  * This function must be used to indicate that the field with the
411  * specified id must be considered as persistent (if persistent is
412  * true) or not persistent (if persistent is false). If a field is
413  * marked as persistent, then it is automatically saved when the
414  * function savePersistentFields is called.
415  */
416 void MEDDataManager_i::markAsPersistent(CORBA::Long fieldHandlerId, bool persistent) {
417   LOG("mark as persistant : id="<<fieldHandlerId);
418   _fieldPersistencyMap[fieldHandlerId] = persistent;
419 }
420
421 void MEDDataManager_i::savePersistentFields(const char * filepath) {
422   LOG("savePersistentFields to : " << filepath);
423   std::vector<long> listId;
424
425   FieldPersistencyMapIterator mapIt;
426   for ( mapIt = _fieldPersistencyMap.begin(); mapIt != _fieldPersistencyMap.end(); mapIt++) {
427     if ( mapIt->second == true ) {
428       listId.push_back(mapIt->first);
429     }
430   }
431
432   MEDCALC::FieldIdList fieldIdList;
433   fieldIdList.length(listId.size());
434   for (int i=0; i<listId.size(); i++) {
435     fieldIdList[i] = CORBA::Long(listId[i]);
436   }
437
438   try {
439     this->saveFields(filepath, fieldIdList);
440   }
441   catch (const SALOME::SALOME_Exception & ex) {
442     throw ex;
443   }
444   catch (const std::exception& ex) {
445     std::string message =
446       std::string("Error when saving file ") +
447       std::string(filepath) + std::string(" : ") + ex.what();
448     throw KERNEL::createSalomeException(message.c_str());
449   }
450 }
451
452 /*!
453  * This function is responsible for creating the FieldHandler
454  * instances. You must use this function because it manages
455  * automatically the identifier value (autoincrementation of a static
456  * variable)
457  */
458 MEDCALC::FieldHandler * MEDDataManager_i::newFieldHandler(const char * fieldname,
459               const char * meshname,
460               TypeOfField  type,
461               long         iteration,
462               long         order,
463               const char * source)
464 {
465   MEDCALC::FieldHandler * fieldHandler = new MEDCALC::FieldHandler();
466   fieldHandler->id = _fieldLastId; _fieldLastId++;
467   fieldHandler->fieldname = fieldname;
468   fieldHandler->meshname  = meshname;
469   fieldHandler->type      = type;
470   fieldHandler->iteration = iteration;
471   fieldHandler->order     = order;
472   fieldHandler->source    = source;
473   return fieldHandler;
474 }
475
476 /*!
477  * This updates the metadata of the field identified by its id with
478  * the data of the given field handler. Returns a copy of the updated
479  * handler (that should be identical to the given field handler for
480  * all data but not for the id that is an invariant for all session
481  * long).
482  * WARN: you should be warned that this function could leave the data
483  * model in a non-coherent state, by example if you change the mesh
484  * name while the mesh has not been updated.
485  */
486 MEDCALC::FieldHandler * MEDDataManager_i::updateFieldHandler(CORBA::Long fieldHandlerId,
487                  const char * fieldname,
488                  long         iteration,
489                  long         order,
490                  const char * source) {
491   FieldHandlerMapIterator fieldIt = _fieldHandlerMap.find(fieldHandlerId);
492   if ( fieldIt != _fieldHandlerMap.end() ) {
493     // Update the attributes
494     // >>> WARN: note that the id of a handler registered in the map
495     // SHOULD NEVER be modified because it is the identifier used in
496     // the whole application for this field all the session long.
497     // <<<
498     fieldIt->second->fieldname = fieldname;
499     fieldIt->second->iteration = iteration;
500     fieldIt->second->order     = order;
501     fieldIt->second->source    = source;
502     // Return a copy
503     return new MEDCALC::FieldHandler(*fieldIt->second);
504   }
505   return NULL;
506 }
507
508 MEDCouplingUMesh * MEDDataManager_i::getUMesh(long meshHandlerId) {
509
510   LOG("getUMesh: START")
511
512   MEDCouplingUMesh * myMesh = NULL;
513   if ( _meshMap.count(meshHandlerId) > 0 ) {
514     // The mesh has been found in the map
515     myMesh = _meshMap[meshHandlerId];
516   } else {
517     // The mesh is not loaded yet ==> load it and register it in the map
518     LOG("getUMesh: the mesh must be loaded. meshid="<<meshHandlerId);
519     if ( _meshHandlerMap[meshHandlerId] == NULL ) {
520       std::string message =
521   std::string("No mesh for id=") + ToString(meshHandlerId);
522       LOG("getUMesh: "<<message);
523       throw KERNEL::createSalomeException(message.c_str());
524     }
525
526     long sourceid = _meshHandlerMap[meshHandlerId]->sourceid;
527     std::string filepath(source_to_file((_datasourceHandlerMap[sourceid])->uri));
528     const char * meshName = _meshHandlerMap[meshHandlerId]->name;
529     int meshDimRelToMax = 0;
530     myMesh = MEDLoader::ReadUMeshFromFile(filepath,meshName,meshDimRelToMax);
531     _meshMap[meshHandlerId] = myMesh;
532   }
533   return myMesh;
534 }
535
536 /**
537  * Try to retrieve the id of the specified mesh, i.e. the key it is
538  * registered with in the internal meshes map.
539  */
540 long MEDDataManager_i::getUMeshId(const MEDCouplingMesh * mesh) {
541   bool found = false;
542   MeshMapIterator it = _meshMap.begin();
543   while ( it != _meshMap.end() ) {
544     found = (it->second == mesh);
545     if (found) {
546       return it->first;
547     }
548     ++it;
549   }
550   return LONG_UNDEFINED;
551 }
552
553 /*!
554  * This method returns the physical data of the specified field,
555  * i.e. the MEDCoupling field associated to the specified field
556  * handler. If the field source is a file and the data ar not loaded
557  * yet, the this function load the data from the file in a MEDCoupling
558  * field instance. Otherwize, it just returns the MEDCoupling field
559  * instance.
560  */
561 MEDCouplingFieldDouble * MEDDataManager_i::getFieldDouble(const MEDCALC::FieldHandler * fieldHandler)
562 {
563
564   LOG("getFieldDouble: START with id="<<fieldHandler->id);
565
566   if ( _fieldDoubleMap.count(fieldHandler->id) > 0 ) {
567   // The MEDCoupling field data are already loaded. Just return the
568   // reference of the MEDCouplingFieldDouble pointer
569     return _fieldDoubleMap[fieldHandler->id];
570   }
571
572   // The MEDCoupling field data are not loaded yet. Load the data and
573   // register the MEDCoupling field in our internal map an all the
574   // associated data if needed (i.e. the underlying mesh).
575
576   // At this step, the mesh handler needs a meshid correctly
577   // set. Normally, we should arrive at this step only in the case
578   // where the field is loaded from a file ==> the meshid is defined
579   // (see the loadDatasource function).
580   //
581   // >>>> __GBO__ TO BE CHECKED AND SERIOUSLY TESTED. There at least
582   // one case where we can arrive here with no previous call to
583   // loadDataSource: for example the field handler list can be obtained
584   // from a call to addFieldsFromFile instead of loadDataSource (see
585   // for exemple the getFieldRepresentation service of the
586   // dataManager, that comes here and then calls getUMesh where we
587   // need a map initialized only in loadDataSource) <<<<
588   long meshid = fieldHandler->meshid;
589
590   // We first have to check if the associated mesh is already loaded
591   // and to load it if needed. The loaded meshes are registered in a
592   // map whose key is the mesh handler id. This checking is
593   // automatically done by the function getUMesh. It's important to do
594   // it before the loading of field data to prevent from the case
595   // where the mesh would not have been loaded already (in the
596   // previous field loading).
597   MEDCouplingUMesh * myMesh =this->getUMesh(meshid);
598
599   long sourceid = _meshHandlerMap[meshid]->sourceid;
600
601   std::string filepath(source_to_file((_datasourceHandlerMap[sourceid])->uri));
602   std::string meshName(myMesh->getName());
603   LOG("getFieldDouble: field "<<fieldHandler->fieldname<<" loaded from file "<<filepath);
604   TypeOfField type = (TypeOfField)fieldHandler->type;
605   int meshDimRelToMax = 0;
606   MEDCouplingFieldDouble * myField = MEDLoader::ReadField(type,
607                 filepath,
608                 meshName,
609                 meshDimRelToMax,
610                 std::string(fieldHandler->fieldname),
611                 fieldHandler->iteration,
612                 fieldHandler->order);
613   myField->setMesh(myMesh);
614   _fieldDoubleMap[fieldHandler->id] = myField;
615   return myField;
616 }
617
618 /*!
619  * This adds the specified MEDCoupling field in the collection managed
620  * by this DataManager. The associated FieldHandler is returned. This
621  * is typically used in a context where the MEDCoupling field is
622  * created from scratch, for example by operations in the
623  * MEDCalculator.
624  * @param[in] fieldDouble   the MEDCouplingFieldDouble instance to add
625  * @param[in] meshHandlerId the id of the meshHandler this filed is associated to.
626  * @return a copy of the FieldHandler registered in the internal map for this field.
627  */
628 MEDCALC::FieldHandler * MEDDataManager_i::addField(MEDCouplingFieldDouble * fieldDouble,
629              long meshHandlerId)
630 {
631   std::string fieldName(fieldDouble->getName());
632   std::string meshName(fieldDouble->getMesh()->getName());
633   TypeOfField  type      = fieldDouble->getTypeOfField();
634
635   int iteration, order;
636   // WARN: note that the variables "iteration" and "order" are passed
637   // by reference to the function getTime (see documentation of
638   // MEDCouplingField). As a consequence, the values of these
639   // variables are updated by this function call. This is the mean to
640   // retrieve the iteration and order of the field.
641   double timestamp = fieldDouble->getTime(iteration, order);
642
643   // For the fields that are created in memory (by operations for
644   // example), the convention for the source attribute is to specify
645   // the fielddouble name, because this name describes the operation
646   // the field has been created with.
647   string * source = new string("mem://"); source->append(fieldName);
648   MEDCALC::FieldHandler * fieldHandler = newFieldHandler(fieldName.c_str(),
649                                                        meshName.c_str(),
650                                                        type,
651                                                        iteration,
652                                                        order,
653                                                        source->c_str());
654
655   if ( meshHandlerId == LONG_UNDEFINED ) {
656     // We have to gess the id of the underlying mesh to preserve data
657     // integrity (a fieldHandler must have an attribute that contains
658     // the id of its underlying mesh):
659     //
660     // WARNING: it's better to let the client code (the one who calls the
661     // function addField) to specify this meshid. This guess procedure is
662     // not reliable, it's just to have a second chance.
663     //
664     LOG("addField: The mesh id is not defined. Trying to guess from the mesh name "<<meshName);
665     long meshid = this->getUMeshId(fieldDouble->getMesh());
666     fieldHandler->meshid = meshid;
667     if ( meshid == LONG_UNDEFINED ) {
668       // No mesh has been found in the internal map
669       LOG("addField: The mesh id for the mesh "<<meshName<<" can't be retrieved from the field "<<fieldName);
670       // _GBO_ : Maybe it could be better to raise an exception
671     }
672   }
673   else {
674     fieldHandler->meshid = meshHandlerId;
675   }
676
677   _fieldHandlerMap[fieldHandler->id] = fieldHandler;
678   _fieldDoubleMap[fieldHandler->id] = fieldDouble;
679   // >>> WARNING: CORBA structure assignement specification ==> return
680   // >>> a deep copy to avoid the destruction of the fieldHandler
681   // >>> registered in the map (assignement acts as a destructor for
682   // >>> CORBA struct).
683   return new MEDCALC::FieldHandler(*fieldHandler);
684 }
685
686 /*!
687  * This function updates the meta-data "fieldname" associated to the
688  * specified field.
689  */
690 void MEDDataManager_i::updateFieldMetadata(CORBA::Long  fieldHandlerId,
691              const char * fieldname,
692              CORBA::Long  iteration,
693              CORBA::Long  order,
694              const char * source)
695 {
696   // We have to update the field handler registered in the internal
697   // map AND the associated fieldDouble loaded in memory.
698   MEDCALC::FieldHandler * fieldHandler = getFieldHandler(fieldHandlerId);
699   updateFieldHandler(fieldHandlerId,fieldname,iteration,order,source);
700
701   MEDCouplingFieldDouble* fieldDouble = getFieldDouble(fieldHandler);
702   fieldDouble->setName(fieldname);
703
704   // _GBO_ TO BE IMPLEMENTED: iteration and order
705 }
706
707 /**
708  * This can be used to associate to the specified field another mesh
709  * support than its current one. This is typically needed to operate 2
710  * fields defined on the same mesh but coming from different med
711  * files. In this case, the underlying meshes are different mesh
712  * objects (from the MEDCoupling point of view) and then no operation
713  * can be allowed by MEDCoupling. The operation of course fails if the
714  * new mesh is not identical to the old one.
715  */
716 void MEDDataManager_i::changeUnderlyingMesh(CORBA::Long fieldHandlerId, CORBA::Long meshHandlerId) {
717
718   MEDCALC::FieldHandler * fieldHandler = getFieldHandler(fieldHandlerId);
719   MEDCouplingFieldDouble* fieldDouble = getFieldDouble(fieldHandler);
720   MEDCouplingMesh * newMesh = getUMesh(meshHandlerId);
721
722   try {
723     fieldDouble->changeUnderlyingMesh(newMesh,10,1e-12);
724   }
725   catch (INTERP_KERNEL::Exception &ex) {
726     std::string * message = new std::string("Error when changing the underlying mesh : ");
727     message->append(ex.what());
728     throw KERNEL::createSalomeException(message->c_str());
729   }
730
731   // The change of mesh is OK, then we can update the meta-data
732   _fieldHandlerMap[fieldHandlerId]->meshid = meshHandlerId;
733   _fieldHandlerMap[fieldHandlerId]->meshname = _meshHandlerMap[meshHandlerId]->name;
734
735
736   // WARN: if this field has already been request by the tui for
737   // manipulation (in a fieldproxy), then the data should be
738   // synchronized
739 }
740
741 INTERP_KERNEL::IntersectionType MEDDataManager_i::_getIntersectionType(const char* intersType) {
742   std::string type(intersType);
743   if (type == "Triangulation") {
744     return INTERP_KERNEL::Triangulation;
745   }
746   else if (type == "Convex") {
747     return INTERP_KERNEL::Convex;
748   }
749   else if (type == "Geometric2D") {
750     return INTERP_KERNEL::Geometric2D;
751   }
752   else if (type == "PointLocator") {
753     return INTERP_KERNEL::PointLocator;
754   }
755   else if (type == "Barycentric") {
756     return INTERP_KERNEL::Barycentric;
757   }
758   else if (type == "BarycentricGeo2D") {
759     return INTERP_KERNEL::BarycentricGeo2D;
760   }
761
762   std::string message("Error when trying to interpolate field: ");
763   message.append("Unrecognized intersection type: ");
764   message.append(type);
765   throw KERNEL::createSalomeException(message.c_str());
766 }
767
768 ParaMEDMEM::NatureOfField MEDDataManager_i::_getNatureOfField(const char* fieldNature) {
769   std::string nature(fieldNature);
770   if (nature == "NoNature") {
771     return NoNature;
772   }
773   else if (nature == "ConservativeVolumic") {
774     return ConservativeVolumic;
775   }
776   else if (nature == "Integral") {
777     return Integral;
778   }
779   else if (nature == "IntegralGlobConstraint") {
780     return IntegralGlobConstraint;
781   }
782   else if (nature == "RevIntegral") {
783     return RevIntegral;
784   }
785
786   std::string message("Error when trying to interpolate field: ");
787   message.append("Unrecognized field nature: ");
788   message.append(nature);
789   throw KERNEL::createSalomeException(message.c_str());
790 }
791
792 MEDCALC::FieldHandler* MEDDataManager_i::interpolateField(CORBA::Long fieldHandlerId, CORBA::Long meshHandlerId, const MEDCALC::InterpolationParameters& params) {
793   MEDCALC::FieldHandler* fieldHandler = getFieldHandler(fieldHandlerId);
794   MEDCouplingFieldDouble* sourceField = getFieldDouble(fieldHandler);
795   MEDCouplingMesh* sourceMesh = getUMesh(fieldHandler->meshid);
796   MEDCouplingMesh* targetMesh = getUMesh(meshHandlerId);
797
798   double precision = params.precision;
799   INTERP_KERNEL::IntersectionType interpType = this->_getIntersectionType(params.intersectionType);
800   std::string method(params.method);
801   double defaultValue = params.defaultValue;
802   bool reverse = params.reverse;
803   ParaMEDMEM::NatureOfField nature = this->_getNatureOfField(params.nature);
804
805   // 1. Build remapper between sourceMesh and targetMesh (compute interpolation matrix)
806   MEDCouplingRemapper remapper;
807   remapper.setPrecision(precision);
808   remapper.setIntersectionType(interpType);
809   remapper.prepare(sourceMesh, targetMesh, method.c_str());
810
811   // 2. Apply interpolation to the field
812   sourceField->setNature(nature);
813   MEDCouplingFieldDouble* targetField = NULL;
814   if (reverse) {
815     targetField = remapper.reverseTransferField(sourceField, defaultValue);
816   } else {
817     targetField = remapper.transferField(sourceField, defaultValue);
818   }
819   targetField->setMesh(targetMesh);
820   targetField->setName(targetMesh->getName() + "_field");
821
822   // 3. Create and register field handler
823   MEDCALC::FieldHandler* fieldResultHandler = this->addField(targetField, this->getUMeshId(targetField->getMesh()));
824   return fieldResultHandler;
825 }
826
827
828
829 /*!
830  * This functions display the internal data of the MEDDataManager on
831  * the server side (data in the SALOME container).
832  */
833 void MEDDataManager_i::serverlog() {
834
835   LOG("==== Field Handler Map ====================================================");
836   LOG("Size = "<<_fieldHandlerMap.size());
837   FieldHandlerMapIterator fhmIt;
838   for ( fhmIt = _fieldHandlerMap.begin(); fhmIt != _fieldHandlerMap.end(); fhmIt++) {
839     long id = fhmIt->first;
840     LOG("------------------------------------- id = "<<ToString(id));
841     LOG("- id        \t= "<<fhmIt->second->id);
842     LOG("- fieldname \t= "<<fhmIt->second->fieldname);
843     LOG("- meshname  \t= "<<fhmIt->second->meshname);
844   }
845
846   LOG("==== Field Double Map ====================================================");
847   LOG("Size = "<<_fieldDoubleMap.size());
848   FieldDoubleMapIterator fdmIt;
849   for ( fdmIt = _fieldDoubleMap.begin(); fdmIt != _fieldDoubleMap.end(); fdmIt++) {
850     long id = (*fdmIt).first;
851     MEDCouplingFieldDouble * fieldDouble = (*fdmIt).second;
852     LOG("------------------------------------- id = "<<ToString(id));
853     LOG("- fieldname \t= "<<fieldDouble->getName());
854     LOG("- meshname  \t= "<<fieldDouble->getMesh()->getName());
855   }
856 }
857
858 /*!
859  * The event listener is created inside the GUI by the
860  * WorkspaceController. This function is called by the WorkspaceController to
861  * store the event listener IOR for the time of the session. Then this
862  * IOR can be available to any point of the application that can
863  * request the data manager (the python console for example).
864  */
865 void MEDDataManager_i::setEventListenerIOR(const char * ior) {
866   _medEventListenerIOR = ior;
867 }
868 /*!
869  * Return the IOR of the event listener that resides in the
870  * GUI. Having the IOR, you can restore the CORBA object by using:
871  *
872  * In a python SALOME context:
873  *
874  * >>> import salome
875  * >>> salome.salome_init()
876  * >>> myobject = salome.orb.string_to_object(ior)
877  *
878  * In a C++ SALOME context: (to do if needed)
879  */
880 char * MEDDataManager_i::getEventListenerIOR() {
881   if ( _medEventListenerIOR == "" ) {
882     throw KERNEL::createSalomeException("The event listener IOR is not defined");
883   }
884   // WARN: return a copy because the pointer memory will be released
885   // (CORBA specification)
886   return CORBA::string_dup( _medEventListenerIOR.c_str() );
887 }