Salome HOME
contrĂ´les
[modules/smesh.git] / src / SMESH / MG_ADAPT.cxx
1 // Copyright (C) 2007-2020  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 // file : MG_ADAPT.cxx
22
23 #include "MG_ADAPT.hxx"
24
25 #include "MeshFormatReader.hxx"
26 #include "MeshFormatWriter.hxx"
27 #include "MEDFileMesh.hxx"
28 #include "MCAuto.hxx"
29 #include "MEDFileData.hxx"
30 #include "MEDFileField.hxx"
31 #include "MEDCouplingFieldDouble.hxx"
32
33 #include <SALOME_NamingService.hxx>
34 #include <Utils_SALOME_Exception.hxx>
35 #include "Utils_CorbaException.hxx"
36
37 #include <utilities.h>
38 #include <iostream>
39 #include <unistd.h>
40 #include <TCollection_AsciiString.hxx>
41 #include <cstring>
42 #include <cstdlib>
43 #include <boost/filesystem.hpp>
44
45 using namespace MG_ADAPT;
46 static std::string removeFile(std::string fileName, int& notOk)
47 {
48   std::string errStr;
49   notOk = std::remove(fileName.c_str());
50   if (notOk) errStr = ToComment("\n error while removing file : ") << fileName;
51         else errStr = ToComment("\n file : ") << fileName << " succesfully deleted! \n ";
52
53   return errStr;
54 }
55 std::string remove_extension(const std::string& filename) {
56   size_t lastdot = filename.find_last_of(".");
57   if (lastdot == std::string::npos) return filename;
58   return filename.substr(0, lastdot);
59 }
60 namespace
61 {
62 struct GET_DEFAULT // struct used to get default value from GetOptionValue()
63 {
64   bool isDefault;
65   operator bool* () {
66       return &isDefault;
67   }
68 };
69 }
70
71 //----------------------------------------------------------------------------------------
72 MgAdapt::MgAdapt()
73 {
74   data = new MgAdaptHypothesisData();
75   data->myInMeshName = "";
76   data->fromMedFile = defaultFromMedFile();
77   data->myFileInDir = defaultWorkingDirectory();
78   data->myMeshFileIn = "";
79   data->myFileOutDir = defaultWorkingDirectory();
80   data->myOutMeshName = "";
81   data->myMeshFileOut = "";
82   data->myMeshOutMed = defaultMeshOutMed();
83   data->myPublish = defaultPublish();
84   data->myUseLocalMap = defaultUseLocalMap();
85   data->myUseBackgroundMap = defaultUseBackgroundMap();
86   data->myFileSizeMapDir = defaultWorkingDirectory();
87   data->myMeshFileBackground = "";
88   data->myUseConstantValue = defaultUseConstantValue();
89   data->myConstantValue = 0.0;
90   data->myFieldName = "";
91   data->myUseNoTimeStep = defaultUseNoTimeStep();
92   data->myUseLastTimeStep = defaultUseLastTimeStep();
93   data->myUseChosenTimeStep = defaultUseChosenTimeStep();
94   data->myTimeStep = -2;
95   data->myRank =  -2;
96   data->myWorkingDir = defaultWorkingDirectory();
97   data->myLogFile = defaultLogFile();
98   data->myVerboseLevel = defaultVerboseLevel();
99   data->myPrintLogInFile = defaultPrintLogInFile();
100   data->myKeepFiles = defaultKeepFiles();
101   data->myRemoveLogOnSuccess = defaultRemoveLogOnSuccess();
102
103   buildModel();
104   setAll();
105 }
106 MgAdapt::MgAdapt(MgAdaptHypothesisData* myData)
107 {
108   data = new MgAdaptHypothesisData();
109   setData(myData);
110   buildModel();
111 }
112
113 MgAdapt::MgAdapt( const MgAdapt& copy)
114 {
115   data = new MgAdaptHypothesisData();
116   MgAdaptHypothesisData *copyData = copy.getData();
117   copyMgAdaptHypothesisData(copyData);
118   setAll();
119
120   this->_option2value = copy._option2value;
121   this->_customOption2value = copy._customOption2value;
122   this->_defaultOptionValues = copy._defaultOptionValues;
123   this->_doubleOptions = copy._doubleOptions;
124   this->_charOptions = copy._charOptions;
125   this->_boolOptions = copy._boolOptions;
126 }
127
128 //-----------------------------------------------------------------------------------------
129 MgAdapt::~MgAdapt()
130 {
131   delete data;
132 }
133 void MgAdapt::buildModel()
134 {
135
136   const char* boolOptionNames[] = { "compute_ridges", // yes
137                                     "" // mark of end
138                                   };
139   // const char* intOptionNames[] = { "max_number_of_errors_printed", // 1
140   //                                  "max_number_of_threads",        // 4
141   //                                  "" // mark of end
142   // };
143   const char* doubleOptionNames[] = { "max_memory",  // 0
144                                       "" // mark of end
145                                     };
146   const char* charOptionNames[] = { "components",  // "yes"
147                                     "adaptation",  // both
148                                     "" // mark of end
149                                   };
150
151   int i = 0;
152   while (boolOptionNames[i][0])
153   {
154     _boolOptions.insert( boolOptionNames[i] );
155     _option2value[boolOptionNames[i++]].clear();
156   }
157   // i = 0;
158   // while (intOptionNames[i][0])
159   //   _option2value[intOptionNames[i++]].clear();
160
161   i = 0;
162   while (doubleOptionNames[i][0]) {
163     _doubleOptions.insert(doubleOptionNames[i]);
164     _option2value[doubleOptionNames[i++]].clear();
165   }
166   i = 0;
167   while (charOptionNames[i][0]) {
168     _charOptions.insert(charOptionNames[i]);
169     _option2value[charOptionNames[i++]].clear();
170   }
171
172   // default values to be used while MG-Adapt
173
174   _defaultOptionValues["adaptation"    ] = "both";
175   _defaultOptionValues["components"    ] = "outside components";
176   _defaultOptionValues["compute_ridges"] = "yes";
177   _defaultOptionValues["max_memory"    ] = ToComment(defaultMaximumMemory());
178 }
179
180 //=============================================================================
181 TOptionValues MgAdapt::getOptionValues() const
182 {
183   TOptionValues vals;
184   TOptionValues::const_iterator op_val = _option2value.begin();
185   for ( ; op_val != _option2value.end(); ++op_val )
186     vals.insert( make_pair( op_val->first, getOptionValue( op_val->first, GET_DEFAULT() )));
187
188   return vals;
189 }
190
191 std::vector <std::string> MgAdapt::getOptionValuesStrVec() const
192 {
193   std::vector <std::string> vals;
194   TOptionValues::const_iterator op_val = _option2value.begin();
195   for ( ; op_val != _option2value.end(); ++op_val )
196     vals.push_back(op_val->first+":"+getOptionValue( op_val->first, GET_DEFAULT() ));
197
198   return vals;
199 }
200
201 std::vector <std::string> MgAdapt::getCustomOptionValuesStrVec() const
202 {
203   std::vector <std::string> vals;
204   TOptionValues::const_iterator op_val;
205   for ( op_val = _customOption2value.begin(); op_val != _customOption2value.end(); ++op_val )
206   {
207     vals.push_back(op_val->first+":"+getOptionValue( op_val->first, GET_DEFAULT() ));
208   }
209   return vals;
210 }
211 const TOptionValues& MgAdapt::getCustomOptionValues() const
212 {
213   return _customOption2value;
214 }
215 void MgAdapt::setData(MgAdaptHypothesisData* myData)
216 {
217   copyMgAdaptHypothesisData(myData);
218   setAll();
219 }
220 MgAdaptHypothesisData* MgAdapt::getData() const
221 {
222   return data;
223 }
224 void MgAdapt::setMedFileIn(std::string fileName)
225 {
226   if ( isFileExist(fileName) )
227   {
228     medFileIn = fileName;
229
230     if (medFileOut == "") // default MED file Out
231       medFileOut = remove_extension( fileName )+ ".adapt.med";
232   }
233   else
234   {
235     SALOME::ExceptionStruct es;
236     es.type = SALOME::BAD_PARAM;
237     std::string text = "\nThe file " + fileName + " does not exist.\n" ;
238     es.text = CORBA::string_dup(text.c_str());
239     throw SALOME::SALOME_Exception(es);
240   }
241 }
242
243 std::string MgAdapt::getMedFileIn()
244 {
245   return medFileIn;
246 }
247
248 void MgAdapt::setMedFileOut(std::string fileOut)
249 {
250   medFileOut = fileOut;
251 }
252 std::string MgAdapt::getMedFileOut()
253 {
254   return medFileOut;
255 }
256 void MgAdapt::setMeshOutMed(bool mybool)
257 {
258   meshOutMed = mybool;
259 }
260 bool MgAdapt::getMeshOutMed()
261 {
262   return meshOutMed;
263 }
264 void MgAdapt::setPublish(bool mybool)
265 {
266   publish = mybool;
267 }
268 bool MgAdapt::getPublish()
269 {
270   return publish;
271 }
272 void MgAdapt::setFieldName(std::string myFieldName)
273 {
274   fieldName = myFieldName;
275 }
276 std::string MgAdapt::getFieldName()
277 {
278   return fieldName;
279 }
280 void MgAdapt::setTimeStep(int time)
281 {
282   timeStep = time;
283 }
284 int MgAdapt::getTimeStep() const
285 {
286   return timeStep;
287 }
288
289 void MgAdapt::setRankTimeStep(int time, int myRank)
290 {
291   timeStep = time;
292   rank = myRank;
293 }
294
295 int MgAdapt::getRank()
296 {
297   return rank;
298 }
299 void MgAdapt::setTimeStepRankLast()
300 {
301   myUseLastTimeStep = true;
302   myUseChosenTimeStep = false;
303   myUseNoTimeStep = false;
304   //~med_int aRank, tmst;
305      //~std::string fieldFile = useBackgroundMap ? sizeMapFile : medFileIn;
306   //~getTimeStepInfos(fieldFile, tmst, aRank);
307   //~setRankTimeStep((int) tmst, (int) aRank);
308 }
309 void MgAdapt::setNoTimeStep()
310 {
311   myUseLastTimeStep = false;
312   myUseChosenTimeStep = false;
313   myUseNoTimeStep = true;
314   //~int aRank = (int)MED_NO_IT;
315   //~int tmst  = (int)MED_NO_DT ;
316   //~setRankTimeStep(tmst, aRank);
317 }
318 void MgAdapt::setChosenTimeStepRank()
319 {
320   myUseLastTimeStep = false;
321   myUseChosenTimeStep = true;
322   myUseNoTimeStep = false;
323   //~int aRank = (int)MED_NO_IT;
324   //~int tmst  = (int)MED_NO_DT ;
325   //~setRankTimeStep(tmst, aRank);
326 }
327 void MgAdapt::setUseLocalMap(bool myLocal)
328 {
329   useLocalMap = myLocal;
330 }
331
332 bool MgAdapt::getUseLocalMap()
333 {
334   return useLocalMap;
335 }
336
337 void MgAdapt::setUseBackgroundMap(bool bckg)
338 {
339   useBackgroundMap = bckg;
340 }
341
342 bool MgAdapt::getUseBackgroundMap()
343 {
344   return useBackgroundMap;
345 }
346
347 void MgAdapt::setUseConstantValue(bool cnst)
348 {
349   useConstantValue = cnst;
350 }
351 bool MgAdapt::getUseConstantValue()
352 {
353   return useConstantValue;
354 }
355 void MgAdapt::setLogFile(std::string myLogFile)
356 {
357   logFile = myLogFile;
358 }
359 std::string MgAdapt::getLogFile()
360 {
361   return logFile;
362 }
363 void MgAdapt::setVerbosityLevel(int verboLevel)
364 {
365   verbosityLevel = verboLevel;
366 }
367 int MgAdapt::getVerbosityLevel()
368 {
369   return verbosityLevel;
370 }
371 void MgAdapt::setRemoveOnSuccess(bool rmons)
372 {
373   removeOnSuccess = rmons;
374 }
375 bool MgAdapt::getRemoveOnSuccess()
376 {
377   return removeOnSuccess;
378 }
379 void MgAdapt::setSizeMapFile(std::string mapFile)
380 {
381   if ( mapFile == "" || isFileExist(mapFile) )
382   {
383     sizeMapFile = mapFile;
384   }
385   else
386   {
387     SALOME::ExceptionStruct es;
388     es.type = SALOME::BAD_PARAM;
389     std::string text = "\nThe file " + mapFile + " does not exist.\n" ;
390     es.text = CORBA::string_dup(text.c_str());
391     throw SALOME::SALOME_Exception(es);
392   }
393 }
394 std::string MgAdapt::getSizeMapFile()
395 {
396   return sizeMapFile;
397 }
398
399 void MgAdapt::setMeshName(std::string name)
400 {
401   meshName = name;
402 }
403 std::string MgAdapt::getMeshName()
404 {
405   return meshName;
406 }
407 void MgAdapt::setMeshNameOut(std::string name)
408 {
409   meshNameOut = name;
410 }
411 std::string MgAdapt::getMeshNameOut()
412 {
413   return meshNameOut;
414 }
415 void MgAdapt::setFromMedFile(bool mybool)
416 {
417   fromMedFile = mybool;
418 }
419 bool MgAdapt::isFromMedFile()
420 {
421   return fromMedFile;
422 }
423 void MgAdapt::setConstantValue(double cnst)
424 {
425   constantValue = cnst;
426 }
427 double MgAdapt::getConstantValue() const
428 {
429   return constantValue;
430 }
431
432 void MgAdapt::setWorkingDir(std::string dir)
433 {
434   workingDir = dir;
435 }
436 std::string MgAdapt::getWorkingDir() const
437 {
438   return workingDir;
439 }
440 void MgAdapt::setKeepWorkingFiles(bool mybool)
441 {
442   toKeepWorkingFiles = mybool;
443 }
444 bool MgAdapt::getKeepWorkingFiles()
445 {
446   return toKeepWorkingFiles;
447 }
448 void MgAdapt::setPrintLogInFile(bool print)
449 {
450   printLogInFile = print;
451 }
452 bool MgAdapt::getPrintLogInFile()
453 {
454   return printLogInFile;
455 }
456
457 bool MgAdapt::setAll()
458 {
459
460   setFromMedFile(data->fromMedFile);
461   std::string file;
462   checkDirPath(data->myFileInDir);
463   file = data->myFileInDir+data->myMeshFileIn;
464   setMedFileIn(file);
465   setMeshName(data->myInMeshName);
466   setMeshNameOut(data->myOutMeshName);
467   checkDirPath(data->myFileOutDir);
468   std::string out = data->myFileOutDir+data->myMeshFileOut;
469   setMedFileOut(out);
470   setPublish(data->myPublish);
471   setMeshOutMed(data->myMeshOutMed);
472   setUseLocalMap(data->myUseLocalMap);
473   setUseBackgroundMap(data->myUseBackgroundMap);
474   setUseConstantValue(data->myUseConstantValue);
475
476   std::string mapfile;
477   if (useBackgroundMap)
478   {
479     checkDirPath(data->myFileSizeMapDir);
480     mapfile = data->myFileSizeMapDir+data->myMeshFileBackground;
481     setFieldName(data->myFieldName);
482   }
483   else if (useConstantValue)
484   {
485     setConstantValue(data->myConstantValue);
486   }
487   else
488   {
489     mapfile ="";
490     setConstantValue(0.0);
491     setFieldName(data->myFieldName);
492   }
493
494   setSizeMapFile(mapfile);
495   if (data->myUseNoTimeStep)
496     setNoTimeStep();
497   else if (data->myUseLastTimeStep)
498     setTimeStepRankLast();
499   else
500   {
501     setChosenTimeStepRank();
502     setRankTimeStep(data->myTimeStep, data->myRank);
503   }
504   /* Advanced options */
505   setWorkingDir(data->myWorkingDir);
506   checkDirPath(data->myWorkingDir);
507   setLogFile(data->myWorkingDir+defaultLogFile());
508   setVerbosityLevel(data->myVerboseLevel);
509   setRemoveOnSuccess(data->myRemoveLogOnSuccess);
510   setPrintLogInFile(data->myPrintLogInFile);
511   setKeepWorkingFiles(data->myKeepFiles);
512
513   return true;
514 }
515
516 void MgAdapt::checkDirPath(std::string& dirPath)
517 {
518   const char lastChar = *dirPath.rbegin();
519 #ifdef WIN32
520   if(lastChar != '\\') dirPath+='\\';
521 #else
522   if(lastChar != '/') dirPath+='/';
523 #endif
524 }
525 //=============================================================================
526 void MgAdapt::setOptionValue(const std::string& optionName,
527                              const std::string& optionValue)
528 throw (std::invalid_argument)
529 {
530 //   INFOS("setOptionValue");
531 //   std::cout << "optionName: " << optionName << ", optionValue: " << optionValue << std::endl;
532   TOptionValues::iterator op_val = _option2value.find(optionName);
533   if (op_val == _option2value.end())
534   {
535     op_val = _customOption2value.find( optionName );
536     _customOption2value[ optionName ] = optionValue;
537     return;
538   }
539
540   if (op_val->second != optionValue)
541   {
542
543     std::string lowerOptionValue = toLowerStr(optionValue);
544     const char* ptr = lowerOptionValue.c_str();
545     // strip white spaces
546     while (ptr[0] == ' ')
547       ptr++;
548     int i = strlen(ptr);
549     while (i != 0 && ptr[i - 1] == ' ')
550       i--;
551     // check value type
552     bool typeOk = true;
553     std::string typeName;
554     if (i == 0)
555     {
556       // empty string
557     }
558     else if (_charOptions.count(optionName))
559     {
560       // do not check strings
561     }
562     else if (_doubleOptions.count(optionName))
563     {
564       // check if value is double
565       toDbl(ptr, &typeOk);
566       typeName = "real";
567     }
568     else if (_boolOptions.count(optionName))
569     {
570       // check if value is bool
571       toBool(ptr, &typeOk);
572       typeName = "bool";
573     }
574     else
575     {
576       // check if value is int
577       toInt(ptr, &typeOk);
578       typeName = "integer";
579     }
580     if ( typeOk ) // check some specific values ?
581     {
582     }
583     if ( !typeOk )
584     {
585       std::string msg = "Advanced option '" + optionName + "' = '" + optionValue + "' but must be " + typeName;
586       throw std::invalid_argument(msg);
587     }
588     std::string value( ptr, i );
589     if ( _defaultOptionValues[ optionName ] == value ) value.clear();
590
591 //     std::cout << "==> value: " << value << std::endl;
592     op_val->second = value;
593
594   }
595 }
596 //=============================================================================
597 //! Return option value. If isDefault provided, it can be a default value,
598 //  then *isDefault == true. If isDefault is not provided, the value will be
599 //  empty if it equals a default one.
600 std::string MgAdapt::getOptionValue(const std::string& optionName, bool* isDefault) const
601 throw (std::invalid_argument)
602 {
603 //   INFOS("getOptionValue");
604 //   std::cout << "optionName: " << optionName << ", isDefault: " << isDefault << std::endl;
605   TOptionValues::const_iterator op_val = _option2value.find(optionName);
606   if (op_val == _option2value.end())
607   {
608     op_val = _customOption2value.find(optionName);
609     if (op_val == _customOption2value.end())
610     {
611       std::string msg = "Unknown MG-Adapt option: <" + optionName + ">";
612       throw std::invalid_argument(msg);
613     }
614   }
615   std::string val = op_val->second;
616   if ( isDefault ) *isDefault = ( val.empty() );
617
618   if ( val.empty() && isDefault )
619   {
620     op_val = _defaultOptionValues.find( optionName );
621     if (op_val != _defaultOptionValues.end()) val = op_val->second;
622   }
623 //   std::cout << "==> val: " << val << std::endl;
624
625   return val;
626 }
627 //================================================================================
628 /*!
629  * \brief Converts a string to a real value
630  */
631 //================================================================================
632
633 double MgAdapt::toDbl(const std::string& str, bool* isOk )
634 throw (std::invalid_argument)
635 {
636   if ( str.empty() ) throw std::invalid_argument("Empty value provided");
637
638   char * endPtr;
639   double val = strtod(&str[0], &endPtr);
640   bool ok = (&str[0] != endPtr);
641
642   if ( isOk ) *isOk = ok;
643
644   if ( !ok )
645   {
646     std::string msg = "Not a real value:'" + str + "'";
647     throw std::invalid_argument(msg);
648   }
649   return val;
650 }
651 //================================================================================
652 /*!
653  * \brief Converts a string to a lower
654  */
655 //================================================================================
656 std::string MgAdapt::toLowerStr(const std::string& str)
657 {
658   std::string s = str;
659   for ( size_t i = 0; i <= s.size(); ++i )
660     s[i] = tolower( s[i] );
661   return s;
662 }
663 //================================================================================
664 /*!
665  * \brief Converts a string to a bool
666  */
667 //================================================================================
668
669 bool MgAdapt::toBool(const std::string& str, bool* isOk )
670 throw (std::invalid_argument)
671 {
672   std::string s = str;
673   if ( isOk ) *isOk = true;
674
675   for ( size_t i = 0; i <= s.size(); ++i )
676     s[i] = tolower( s[i] );
677
678   if ( s == "1" || s == "true" || s == "active" || s == "yes" )
679     return true;
680
681   if ( s == "0" || s == "false" || s == "inactive" || s == "no" )
682     return false;
683
684   if ( isOk )
685     *isOk = false;
686   else
687   {
688     std::string msg = "Not a Boolean value:'" + str + "'";
689     throw std::invalid_argument(msg);
690   }
691   return false;
692 }
693 //================================================================================
694 /*!
695  * \brief Converts a string to a integer value
696  */
697 //================================================================================
698
699 int MgAdapt::toInt(const std::string& str, bool* isOk )
700 throw (std::invalid_argument)
701 {
702   if ( str.empty() ) throw std::invalid_argument("Empty value provided");
703
704   char * endPtr;
705   int val = (int)strtol( &str[0], &endPtr, 10);
706   bool ok = (&str[0] != endPtr);
707
708   if ( isOk ) *isOk = ok;
709
710   if ( !ok )
711   {
712     std::string msg = "Not an integer value:'" + str + "'";
713     throw std::invalid_argument(msg);
714   }
715   return val;
716 }
717 //=============================================================================
718 bool MgAdapt::hasOptionDefined( const std::string& optionName ) const
719 {
720   bool isDefault = false;
721   try
722   {
723     getOptionValue( optionName, &isDefault );
724   }
725   catch ( std::invalid_argument )
726   {
727     return false;
728   }
729   return !isDefault;
730 }
731 //================================================================================
732 /*!
733  * \brief Return command to run MG-Tetra mesher excluding file prefix (-f)
734  */
735 //================================================================================
736
737 std::string MgAdapt::getCommandToRun(MgAdapt* hyp)
738 {
739   return hyp ? hyp->getCommandToRun() : ToComment("error with hypothesis!");
740 }
741
742
743
744 int MgAdapt::compute(std::string& errStr)
745 {
746   std::string cmd = getCommandToRun();
747   int err = 0;
748   execCmd( cmd.c_str(), err ); // run
749
750   if ( err )
751   {
752     errStr = ToComment("system(mg-adapt.exe ...) command failed with error: ") << strerror( errno );
753   }
754   else
755   {
756     convertMeshFile(meshFormatOutputMesh, solFormatOutput);
757   }
758   if (!err) cleanUp();
759   return err;
760 }
761
762 void MgAdapt::execCmd( const char* cmd, int& err)
763 {
764   err = 1;
765   std::array <char, 128> buffer;
766   std::streambuf* buf;
767 outFileStream fileStream;
768   if (printLogInFile)
769   {
770   fileStream.open(logFile);
771   buf = fileStream.rdbuf();
772   }
773   else
774   {
775     buf = std::cout.rdbuf();
776   }
777   std::ostream logStream(buf);
778
779   std::unique_ptr <FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose );
780   if(!pipe)
781   {
782     throw std::runtime_error("popen() failed!");
783   }
784   while(fgets(buffer.data(), buffer.size(), pipe.get()) !=nullptr )
785   {
786     logStream<<buffer.data() ;
787   }
788   err = 0;
789 }
790 /*
791  * to delete tmp files .mesh, .sol and if needed
792  * the log file
793  *
794  */
795 void MgAdapt::cleanUp()
796 {
797   int notOk;
798   std::string errStr;
799   if(toKeepWorkingFiles)
800     return;
801   if(removeOnSuccess && printLogInFile)
802     tmpFilesToBeDeleted.push_back(logFile);
803
804   std::vector< std::string>::iterator it = tmpFilesToBeDeleted.begin();
805   for (; it!=tmpFilesToBeDeleted.end(); ++it)
806   {
807     errStr=removeFile(*it, notOk);
808     if (notOk)
809     {
810       appendMsgToLogFile(errStr);
811     }
812
813   }
814 }
815
816 void MgAdapt::appendMsgToLogFile(std::string& msg)
817 {
818   std::ofstream logStream;
819   logStream.open(logFile, std::ofstream::out | std::ofstream::app);
820   logStream<< msg;
821   logStream.close();
822 }
823 //================================================================================
824 /*!
825  * \brief Return command to run MG-Tetra mesher excluding file prefix (-f)
826  */
827 //================================================================================
828
829 std::string MgAdapt::getCommandToRun()
830 {
831   /*
832   || return system command with args and options
833   ||
834   */
835   std::string errStr;
836   std::string cmd = getExeName();
837   std::string meshIn(""), sizeMapIn(""), solFileIn("");
838   updateTimeStepRank();
839   convertMedFile(meshIn, solFileIn, sizeMapIn);
840   if (!isFileExist(meshIn) || !isFileExist(solFileIn))
841   {
842     errStr = ToComment(" failed to find .mesh or .sol file from converter ")<< strerror( errno );
843     return errStr;
844   }
845   tmpFilesToBeDeleted.push_back(meshIn);
846   tmpFilesToBeDeleted.push_back(solFileIn);
847   if(useBackgroundMap && !isFileExist(sizeMapIn))
848   {
849     errStr = ToComment(" failed to find .mesh size map file from converter ")<< strerror( errno );
850     return errStr;
851   }
852
853   cmd+= " --in "+ meshIn;
854   meshFormatOutputMesh = getFileName()+".mesh";
855   tmpFilesToBeDeleted.push_back(meshFormatOutputMesh);
856   cmd+= " --out "+ meshFormatOutputMesh;
857   if (useLocalMap || useConstantValue) cmd+= " --sizemap "+ solFileIn;
858   else //  (useBackgroundMap)
859   {
860     cmd+= " --background_mesh "+ sizeMapIn ;
861     cmd+= " --background_sizemap "+ solFileIn;
862     tmpFilesToBeDeleted.push_back(sizeMapIn);
863   }
864   //~else
865   //~{
866       //~// constant value TODO
867   //~}
868   std::string adapOp   = "adaptation";
869   std::string adpOpVal = getOptionValue(adapOp);
870   // Check coherence between mesh dimension and option
871 //   checkDimensionOption(adpOpVal);
872   /* sizemap file is not adapted in case of only surface adaptation see MeshGems docs */
873   std::string surfaceAdapt = "surface";
874   if(surfaceAdapt != adpOpVal )
875   {
876     std::string solFileOut = getFileName()+".sol";
877     cmd+= " --write_sizemap "+ solFileOut;
878     solFormatOutput.push_back(solFileOut);
879     tmpFilesToBeDeleted.push_back(solFileOut);
880   }
881
882   std::string option, value;
883   bool isDefault;
884   const TOptionValues* options[] = { &_option2value, &_customOption2value };
885   for ( int iOp = 0; iOp < 2; ++iOp )
886   {
887     TOptionValues::const_iterator o2v = options[iOp]->begin();
888     for ( ; o2v != options[iOp]->end(); ++o2v )
889     {
890       option = o2v->first;
891       value = getOptionValue( option, &isDefault );
892
893       if ( isDefault )
894           continue;
895       if ( value.empty() )//value == NoValue() )
896       {
897         if ( _defaultOptionValues.count( option ))
898             continue; // non-custom option with no value
899         //value.clear();
900       }
901       if ( strncmp( "no", option.c_str(), 2 ) == 0 ) // options w/o values: --no_*
902       {
903         if ( !value.empty() && toBool( value ) == false )
904             continue;
905         value.clear();
906       }
907       if ( option[0] != '-' )
908         cmd += " --";
909       else
910         cmd += " ";
911       cmd += option + " " + value;
912     }
913   }
914
915   // Verbosity Level
916   if (verbosityLevel != defaultVerboseLevel())
917   {
918     cmd+= " --verbose "+ ToComment(verbosityLevel);
919   }
920     //~}
921 //~cmd+= " >"
922 #ifdef WIN32
923     cmd += " < NUL";
924 #endif
925
926   return cmd;
927 }
928
929 bool MgAdapt::isFileExist(const std::string& fName)
930 {
931
932   if ( fName.empty() ) return false;
933
934   boost::system::error_code err;
935   bool res = boost::filesystem::exists( fName, err );
936
937   return err ? false : res;
938 }
939 //=======================================================================
940 //function : defaultMaximumMemory
941 //=======================================================================
942
943 #if defined(WIN32)
944 #include <windows.h>
945 #elif !defined(__APPLE__)
946 #include <sys/sysinfo.h>
947 #endif
948
949 double MgAdapt::defaultMaximumMemory()
950 {
951 #if defined(WIN32)
952   // See http://msdn.microsoft.com/en-us/library/aa366589.aspx
953   MEMORYSTATUSEX statex;
954   statex.dwLength = sizeof (statex);
955   long err = GlobalMemoryStatusEx (&statex);
956   if (err != 0)
957   {
958     double totMB = (double)statex.ullAvailPhys / 1024. / 1024.;
959     return (double)( 0.7 * totMB );
960   }
961 #elif !defined(__APPLE__)
962   struct sysinfo si;
963   long err = sysinfo( &si );
964   if ( err == 0 )
965   {
966     long ramMB = si.totalram * si.mem_unit / 1024 / 1024;
967     return ( 0.7 * ramMB );
968   }
969 #endif
970   return 1024;
971 }
972
973 //=======================================================================
974 //function : defaultWorkingDirectory
975 //=======================================================================
976
977 std::string MgAdapt::defaultWorkingDirectory()
978 {
979   TCollection_AsciiString aTmpDir;
980
981   char *Tmp_dir = getenv("SALOME_TMP_DIR");
982   if(Tmp_dir != NULL)
983   {
984     aTmpDir = Tmp_dir;
985   }
986   else {
987 #ifdef WIN32
988     aTmpDir = TCollection_AsciiString("C:\\");
989 #else
990     aTmpDir = TCollection_AsciiString("/tmp/");
991 #endif
992   }
993   return aTmpDir.ToCString();
994 }
995 //================================================================================
996 /*!
997  * \brief Return a unique file name
998  */
999 //================================================================================
1000
1001 std::string MgAdapt::getFileName() const
1002 {
1003   std::string aTmpDir = workingDir;
1004   const char lastChar = *aTmpDir.rbegin();
1005 #ifdef WIN32
1006   if(lastChar != '\\') aTmpDir+='\\';
1007 #else
1008   if(lastChar != '/') aTmpDir+='/';
1009 #endif
1010
1011   TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
1012   aGenericName += "MgAdapt_";
1013   aGenericName += getpid();
1014   aGenericName += "_";
1015   aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
1016
1017   return aGenericName.ToCString();
1018 }
1019 //=======================================================================
1020 //function : defaultLogFile
1021 //=======================================================================
1022
1023 std::string MgAdapt::defaultLogFile()
1024 {
1025   std::string alogFile("MG_ADAPT.log");
1026   return alogFile;
1027 }
1028 //=======================================================================
1029 //function : defaultUseConstantValue
1030 //=======================================================================
1031
1032 bool MgAdapt::defaultUseConstantValue()
1033 {
1034   return false;
1035 }
1036 //=======================================================================
1037 //function : defaultUseNoTimeStep
1038 //=======================================================================
1039
1040 bool MgAdapt::defaultUseNoTimeStep()
1041 {
1042   return true;
1043 }
1044 //=======================================================================
1045 //function : defaultRemoveLogOnSuccess
1046 //=======================================================================
1047
1048 bool MgAdapt::defaultRemoveLogOnSuccess()
1049 {
1050   return true;
1051 }
1052 //=======================================================================
1053 //function : defaultPrintLogInFile
1054 //=======================================================================
1055
1056 bool MgAdapt::defaultPrintLogInFile()
1057 {
1058   return false;
1059 }
1060 //=======================================================================
1061 //function : defaultUseChosenTimeStep
1062 //=======================================================================
1063
1064 bool MgAdapt::defaultUseChosenTimeStep()
1065 {
1066   return false;
1067 }
1068 //=======================================================================
1069 //function : UseLastTimeStep
1070 //=======================================================================
1071
1072 bool MgAdapt::defaultUseLastTimeStep()
1073 {
1074   return false;
1075 }
1076 //=======================================================================
1077 //function : defaultUseBackgroundMap
1078 //=======================================================================
1079
1080 bool MgAdapt::defaultUseBackgroundMap()
1081 {
1082   return false;
1083 }
1084 //=======================================================================
1085 //function : defaultKeepFiles
1086 //=======================================================================
1087
1088 bool MgAdapt::defaultKeepFiles()
1089 {
1090   return false;
1091 }
1092 //=======================================================================
1093 //function : defaultUseLocalMap
1094 //=======================================================================
1095
1096 bool MgAdapt::defaultUseLocalMap()
1097 {
1098   return true;
1099 }
1100 //=======================================================================
1101 //function : defaultPublish
1102 //=======================================================================
1103
1104 bool MgAdapt::defaultPublish()
1105 {
1106   return false;
1107 }
1108 //=======================================================================
1109 //function : defaultMeshOutMed
1110 //=======================================================================
1111
1112 bool MgAdapt::defaultMeshOutMed()
1113 {
1114   return true;
1115 }
1116 //=======================================================================
1117 //function : defaultFromMedFile
1118 //=======================================================================
1119
1120 bool MgAdapt::defaultFromMedFile()
1121 {
1122   return true;
1123 }
1124 //=======================================================================
1125 //function : defaultVerboseLevel
1126 //=======================================================================
1127
1128 int  MgAdapt::defaultVerboseLevel()
1129 {
1130   return 3;
1131 }
1132 std::string MgAdapt::getExeName()
1133 {
1134   return "mg-adapt.exe";
1135 }
1136 void MgAdapt::copyMgAdaptHypothesisData( const MgAdaptHypothesisData* from)
1137 {
1138   data->myFileInDir = from->myFileInDir;
1139   data->myMeshFileIn = from->myMeshFileIn;
1140   data->myMeshFileBackground = from->myMeshFileBackground;
1141   data->myOutMeshName = from->myOutMeshName;
1142   data->myMeshFileOut = from->myMeshFileOut;
1143   data->myFileOutDir = from->myFileOutDir;
1144   data->myFileSizeMapDir = from->myFileSizeMapDir;
1145   data->myFieldName = from->myFieldName;
1146   data->fromMedFile = from->fromMedFile;
1147   data->myPublish = from->myPublish;
1148   data->myMeshOutMed = from->myMeshOutMed;
1149   data->myUseLocalMap = from->myUseLocalMap;
1150   data->myUseBackgroundMap = from->myUseBackgroundMap;
1151   data->myUseConstantValue = from->myUseConstantValue;
1152   data->myConstantValue = from->myConstantValue;
1153   data->myTimeStep = from->myTimeStep;
1154   data->myRank = from->myRank;
1155   data->myUseNoTimeStep = from->myUseNoTimeStep;
1156   data->myUseLastTimeStep = from->myUseLastTimeStep;
1157   data->myUseChosenTimeStep = from->myUseChosenTimeStep;
1158   data->myWorkingDir = from->myWorkingDir;
1159   data->myLogFile = from->myLogFile;
1160   data->myPrintLogInFile = from->myPrintLogInFile;
1161   data->myKeepFiles = from->myKeepFiles;
1162   data->myRemoveLogOnSuccess = from->myRemoveLogOnSuccess;
1163   data->myVerboseLevel = from->myVerboseLevel;
1164 }
1165
1166 std::vector<std::string> MgAdapt::getListFieldsNames(std::string fileIn)
1167 {
1168   MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = MEDCoupling::MEDFileData::New(fileIn);
1169   std::vector<std::string> listFieldsNames(mfd->getFields()->getFieldsNames());
1170   return listFieldsNames ;
1171 }
1172
1173 void MgAdapt::checkDimensionOption(std::string adpOpVal)
1174 {
1175   // Pas correct.
1176   MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = MEDCoupling::MEDFileData::New(medFileIn);
1177   int meshdim = mfd->getMeshes()->getMeshAtPos(0)->getMeshDimension() ;
1178
1179   if ( ( meshdim == 2 ) & ( adpOpVal != "surface" ) )
1180   {
1181     SALOME::ExceptionStruct es;
1182     es.type = SALOME::BAD_PARAM;
1183     std::string text = "Mesh dimension is 2; the option should be 'surface' instead of '" + adpOpVal + "'." ;
1184     es.text = CORBA::string_dup(text.c_str());
1185     throw SALOME::SALOME_Exception(es);
1186   }
1187 }
1188
1189 void MgAdapt::checkFieldName(std::string fileIn)
1190 {
1191   bool ret = false ;
1192   std::vector<std::string> listFieldsNames = getListFieldsNames(fileIn);
1193   std::size_t jaux(listFieldsNames.size());
1194   for(std::size_t j=0;j<jaux;j++)
1195   {
1196     if ( fieldName == listFieldsNames[j] )
1197     {
1198       ret = true ;
1199       break ;
1200     }
1201   }
1202   if ( ! ret )
1203   {
1204     std::cout << "Available field names:" << std::endl;
1205     for(std::size_t j=0;j<jaux;j++)
1206     { std::cout << listFieldsNames[j] << std::endl;}
1207     SALOME::ExceptionStruct es;
1208     es.type = SALOME::BAD_PARAM;
1209     std::string text = "Field " + fieldName + " is not found." ;
1210     es.text = CORBA::string_dup(text.c_str());
1211     throw SALOME::SALOME_Exception(es);
1212   }
1213 }
1214
1215 void MgAdapt::checkTimeStepRank(std::string fileIn)
1216 {
1217   bool ret = false ;
1218   MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = MEDCoupling::MEDFileData::New(fileIn);
1219   MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeFieldMultiTS> fts = dynamic_cast<MEDCoupling::MEDFileFieldMultiTS *>( mfd->getFields()->getFieldWithName(fieldName) );
1220 //   std::cout << "--- timeStep " << timeStep << std::endl;
1221 //   std::cout << "--- rank " << rank << std::endl;
1222   std::vector<double> timevalue;
1223   std::vector< std::pair<int,int> > timesteprank = fts->getTimeSteps(timevalue);
1224   std::size_t jaux(timesteprank.size());
1225   for(std::size_t j=0;j<jaux;j++)
1226   {
1227     if ( ( timeStep == timesteprank[j].first ) & ( rank == timesteprank[j].second ) )
1228     {
1229       ret = true ;
1230       break ;
1231     }
1232   }
1233   if ( ! ret )
1234   {
1235     std::cout << "Available (Time step, Rank):" << std::endl;
1236     for(std::size_t j=0;j<jaux;j++)
1237     { std::cout << "(Time step = " << timesteprank[j].first << ", Rank = " << timesteprank[j].second << ")" << std::endl;}
1238     SALOME::ExceptionStruct es;
1239     es.type = SALOME::BAD_PARAM;
1240     std::string text = "(Time step = " + std::to_string(timeStep) + ", Rank = " + std::to_string(rank) + ") is not found." ;
1241     es.text = CORBA::string_dup(text.c_str());
1242     throw SALOME::SALOME_Exception(es);
1243   }
1244 }
1245
1246 void MgAdapt::convertMedFile(std::string& meshFormatMeshFileName, std::string& solFormatFieldFileName, std::string& meshFormatsizeMapFile)
1247 {
1248   std::vector<std::string> fieldFileNames;
1249   MEDCoupling::MeshFormatWriter writer;
1250   MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = MEDCoupling::MEDFileData::New(medFileIn);
1251   MEDCoupling::MEDFileMeshes* meshes = mfd->getMeshes();
1252   MEDCoupling::MEDFileMesh* fileMesh = meshes->getMeshAtPos(0); // ok only one mesh in file!
1253   if (meshNameOut =="")
1254       meshNameOut = fileMesh->getName();
1255   storeGroupsAndFams(fileMesh);
1256
1257   MEDCoupling::MCAuto<MEDCoupling::MEDFileFields> fields = MEDCoupling::MEDFileFields::New();
1258   solFormatFieldFileName = getFileName();
1259   solFormatFieldFileName+=".sol";
1260   fieldFileNames.push_back(solFormatFieldFileName);
1261
1262   if (useBackgroundMap)
1263   {
1264     checkFieldName(sizeMapFile) ;
1265     checkTimeStepRank(sizeMapFile) ;
1266     meshFormatsizeMapFile = getFileName();
1267     meshFormatsizeMapFile += ".mesh";
1268     buildBackGroundMeshAndSolFiles(fieldFileNames, meshFormatsizeMapFile);
1269   }
1270   else if(useLocalMap)
1271   {
1272     checkFieldName(medFileIn) ;
1273     checkTimeStepRank(medFileIn) ;
1274     MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeFieldMultiTS> fts = dynamic_cast<MEDCoupling::MEDFileFieldMultiTS *>( mfd->getFields()->getFieldWithName(fieldName) );
1275     MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeField1TS> f = fts->getTimeStep(timeStep, rank);
1276     MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> tmFts = MEDCoupling::MEDFileFieldMultiTS::New();
1277     tmFts->pushBackTimeStep(f);
1278
1279     fields->pushField(tmFts);
1280
1281     writer.setFieldFileNames( fieldFileNames);
1282   }
1283   else
1284   {
1285     MEDCoupling::MCAuto<MEDCoupling::MEDCouplingMesh> mesh = fileMesh->getMeshAtLevel(1); // nodes mesh
1286     MEDCoupling::MCAuto<MEDCoupling::MEDCouplingUMesh> umesh = mesh->buildUnstructured(); // nodes mesh
1287     int dim  =  umesh->getSpaceDimension();
1288     int version =  sizeof(double) < 8 ? 1 : 2;
1289     mcIdType nbNodes =  umesh->getNumberOfNodes();
1290     buildConstantSizeMapSolFile(solFormatFieldFileName, dim, version, nbNodes);
1291   }
1292
1293   mfd->setFields( fields );
1294   meshFormatMeshFileName = getFileName();
1295   meshFormatMeshFileName+=".mesh";
1296   writer.setMeshFileName(meshFormatMeshFileName);
1297   writer.setMEDFileDS( mfd);
1298   writer.write();
1299
1300 }
1301
1302 void MgAdapt::convertMeshFile(std::string& meshFormatIn, std::vector< std::string>& solFieldFileNames) const
1303 {
1304   MEDCoupling::MeshFormatReader reader(meshFormatIn, solFieldFileNames);
1305
1306   MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = reader.loadInMedFileDS();
1307   // write MED
1308   MEDCoupling::MEDFileMeshes* meshes = mfd->getMeshes();
1309   MEDCoupling::MEDFileMesh* fileMesh = meshes->getMeshAtPos(0); // ok only one mesh in file!
1310   fileMesh->setName(meshNameOut);
1311   restoreGroupsAndFams(fileMesh);
1312   mfd->write(medFileOut, 2);
1313 }
1314
1315 void MgAdapt::storeGroupsAndFams(MEDCoupling::MEDFileMesh* fileMesh)
1316 {
1317   storefams(fileMesh);
1318   storeGroups(fileMesh);
1319 }
1320
1321 void MgAdapt::restoreGroupsAndFams(MEDCoupling::MEDFileMesh* fileMesh) const
1322 {
1323   restorefams(fileMesh);
1324   restoreGroups(fileMesh);
1325 }
1326 void MgAdapt::storeGroups(MEDCoupling::MEDFileMesh* fileMesh)
1327 {
1328   std::map<std::string, std::vector<std::string> > grpFams = fileMesh->getGroupInfo();
1329   std::map<std::string, std::vector<std::string> >::iterator g2ff = grpFams.begin();
1330
1331   for ( ; g2ff != grpFams.end(); ++g2ff )
1332   {
1333     std::string        groupName = g2ff->first;
1334     std::vector<std::string> famNames = g2ff->second;
1335
1336     if ( famNames.empty() ) continue;
1337     std::size_t k = 0;
1338     std::vector< mcIdType> famListId;
1339     for ( size_t i = 0; i < famNames.size(); ++i )
1340     {
1341       famListId.push_back( fileMesh->getFamilyId( famNames[i].c_str() ) );
1342     }
1343     group grp(groupName, famListId, famNames);
1344     groupVec.push_back(grp);
1345   }
1346 }
1347
1348 void MgAdapt::storefams(MEDCoupling::MEDFileMesh* fileMesh)
1349 {
1350   std::map<std::string, mcIdType> grpFams = fileMesh->getFamilyInfo();
1351   std::map<std::string, mcIdType >::iterator f = grpFams.begin();
1352
1353   for ( ; f != grpFams.end(); ++f )
1354   {
1355     if(!f->second) continue;  // FAMILLE_ZERO
1356     family fs(f->first, f->second);
1357     famVec.push_back(fs);
1358   }
1359
1360 }
1361
1362 void MgAdapt::restorefams(MEDCoupling::MEDFileMesh* fileMesh) const
1363 {
1364   std::vector<family>::const_iterator fIt = famVec.begin();
1365
1366   for (; fIt!=famVec.end(); ++fIt)
1367   {
1368     try  //
1369     {
1370       std::string givenFamNameFromMeshGemConverter = fileMesh->getFamilyNameGivenId( std::abs(fIt->_famId) );
1371       fileMesh->changeFamilyId(std::abs(fIt->_famId), fIt->_famId);
1372       fileMesh->changeFamilyName(givenFamNameFromMeshGemConverter, fIt->_famName);
1373     }
1374     catch (const std::exception& e)
1375     {
1376       std::cerr<<e.what();
1377     }
1378   }
1379 }
1380
1381 void MgAdapt::restoreGroups(MEDCoupling::MEDFileMesh* fileMesh) const
1382 {
1383   std::map<std::string, std::vector<std::string> > info;
1384   std::vector <group>::const_iterator grpFams = groupVec.begin();
1385
1386   for (; grpFams!=groupVec.end(); ++grpFams)
1387   {
1388     info.insert(std::pair <std::string, std::vector<std::string> > (grpFams->_name, grpFams->_famNames) );
1389   }
1390
1391   fileMesh->setGroupInfo(info);
1392 }
1393
1394 void MgAdapt::buildConstantSizeMapSolFile(const std::string& solFormatFieldFileName, const int dim, const int version, const mcIdType nbNodes) const
1395 {
1396   MeshFormat::Localizer loc;
1397   MeshFormat::MeshFormatParser writer;
1398   int fileId = writer.GmfOpenMesh( solFormatFieldFileName.c_str(), GmfWrite, version, dim);
1399   int typTab[] = {GmfSca};
1400   writer.GmfSetKwd(fileId, MeshFormat::GmfSolAtVertices, (int)nbNodes, 1, typTab);
1401   for (mcIdType i = 0; i<nbNodes; i++)
1402   {
1403     double valTab[1] = {constantValue};
1404     writer.GmfSetLin( fileId, MeshFormat::GmfSolAtVertices, valTab);
1405   }
1406   writer.GmfCloseMesh(fileId);
1407 }
1408
1409 void MgAdapt::buildBackGroundMeshAndSolFiles(const std::vector<std::string>& fieldFileNames, const std::string& meshFormatsizeMapFile) const
1410 {
1411   MEDCoupling::MCAuto<MEDCoupling::MEDFileData> tmpMfd = MEDCoupling::MEDFileData::New(sizeMapFile);
1412   MEDCoupling::MEDFileFields* tmpFields = tmpMfd->getFields();
1413   MEDCoupling::MEDFileAnyTypeFieldMultiTS* fts = tmpFields->getFieldWithName(fieldName);
1414   MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS>  fts1 = dynamic_cast<MEDCoupling::MEDFileFieldMultiTS *>(fts);
1415   MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeField1TS> f = fts1->getTimeStep(timeStep, rank);
1416   MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> tmFts = MEDCoupling::MEDFileFieldMultiTS::New();
1417   tmFts->pushBackTimeStep(f);
1418
1419   MEDCoupling::MCAuto<MEDCoupling::MEDFileFields> tmp_fields = MEDCoupling::MEDFileFields::New();
1420   tmp_fields->pushField(tmFts);
1421
1422   tmpMfd->setFields( tmp_fields );
1423   MEDCoupling::MeshFormatWriter tmpWriter;
1424   tmpWriter.setMeshFileName(meshFormatsizeMapFile);
1425   tmpWriter.setFieldFileNames( fieldFileNames);
1426   tmpWriter.setMEDFileDS(tmpMfd);
1427   tmpWriter.write();
1428 }
1429 // =======================================================================
1430 med_idt MgAdapt::openMedFile(const std::string aFile)
1431 // =======================================================================
1432 // renvoie le medId associe au fichier Med apres ouverture
1433 {
1434   med_idt medIdt = MEDfileOpen(aFile.c_str(),MED_ACC_RDONLY);
1435   if (medIdt <0)
1436   {
1437     SALOME::ExceptionStruct es;
1438     es.type = SALOME::BAD_PARAM;
1439     std::string text = "\nThe med file " + aFile + " cannot be opened.\n" ;
1440     es.text = CORBA::string_dup(text.c_str());
1441     throw SALOME::SALOME_Exception(es);
1442   }
1443   return medIdt;
1444 }
1445
1446 MgAdapt::Status MgAdapt::addMessage(const std::string& msg,
1447                                   const bool         isFatal/*=false*/)
1448 {
1449   if ( isFatal )
1450     _myErrorMessages.clear(); // warnings are useless if a fatal error encounters
1451
1452   _myErrorMessages.push_back( msg );
1453
1454 //~MESSAGE(msg);
1455 #ifdef _DEBUG_
1456   std::cout << msg << std::endl;
1457 #endif
1458   return ( _myStatus = isFatal ? MgAdapt::DRS_FAIL : MgAdapt::DRS_WARN_SKIP_ELEM );
1459 }
1460
1461 // =======================================================================
1462 void MgAdapt::getTimeStepInfos(std::string aFile, med_int& numdt, med_int& numit)
1463 // =======================================================================
1464 {
1465 // Il faut voir si plusieurs maillages
1466
1467   herr_t erreur = 0 ;
1468   med_idt medIdt ;
1469
1470
1471   // Ouverture du fichier
1472   //~SCRUTE(aFile.toStdString());
1473   medIdt = openMedFile(aFile);
1474   if ( medIdt < 0 ) return ;
1475   // Lecture du nombre de champs
1476   med_int ncha = MEDnField(medIdt) ;
1477   if (ncha < 1 )
1478   {
1479     //~addMessage( ToComment(" error: there is no field in  ") << aFile, /*fatal=*/true );
1480     return;
1481   }
1482   // Lecture des caracteristiques du champs
1483
1484   //       Lecture du type du champ, des noms des composantes et du nom de l'unite
1485   char nomcha  [MED_NAME_SIZE+1];
1486   strcpy(nomcha, fieldName.c_str());
1487 //       Lecture du nombre de composantes
1488   med_int ncomp = MEDfieldnComponentByName(medIdt, nomcha);
1489   char meshname[MED_NAME_SIZE+1];
1490   char * comp = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
1491   char * unit = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
1492   char dtunit[MED_SNAME_SIZE+1];
1493   med_bool local;
1494   med_field_type typcha;
1495   med_int nbofcstp;
1496   erreur =  MEDfieldInfoByName (medIdt, nomcha, meshname,&local,&typcha,comp,unit,dtunit, &nbofcstp);
1497   free(comp);
1498   free(unit);
1499   if ( erreur < 0 )
1500   {
1501       //~addMessage( ToComment(" error: error while reading field  ") << nomcha << " in file " << aFile , /*fatal=*/true );
1502     return;
1503   }
1504
1505   med_float dt;
1506   med_int tmp_numdt, tmp_numit;
1507
1508   //~med_int step = data->myUseLastTimeStep ? nbofcstp : data->myTimeStep+1;
1509   //~myPrint("step ", step);
1510   erreur = MEDfieldComputingStepInfo ( medIdt, nomcha, 1, &numdt, &numit, &dt );
1511   for(med_int step = 1; step <= nbofcstp; step++ )
1512   {
1513     erreur = MEDfieldComputingStepInfo ( medIdt, nomcha, step, &tmp_numdt, &tmp_numit, &dt );
1514     if(tmp_numdt > numdt)
1515     {
1516       numdt = tmp_numdt;
1517       numit = tmp_numit;
1518     }
1519   }
1520   if ( erreur < 0 )
1521   {
1522     //~addMessage( ToComment(" error: error while reading field ") << nomcha << "step (numdt, numit) = " <<"("<< numdt<< ", " \
1523     numit<< ")" <<" in file " << aFile , /*fatal=*/true );
1524     return;
1525   }
1526
1527   // Fermeture du fichier
1528   if ( medIdt > 0 ) MEDfileClose(medIdt);
1529
1530 }
1531
1532 void MgAdapt::updateTimeStepRank()
1533 {
1534
1535   med_int arank;
1536   med_int tmst;
1537   if (myUseNoTimeStep)
1538   {
1539     arank = MED_NO_IT;
1540     tmst  = MED_NO_DT ;
1541     setRankTimeStep((int)tmst, (int)arank);
1542   }
1543   else if (myUseLastTimeStep)
1544   {
1545     std::string fieldFile = useBackgroundMap ? sizeMapFile : medFileIn;
1546     getTimeStepInfos(fieldFile, tmst, arank);
1547     setRankTimeStep((int)tmst, (int)arank);
1548   }
1549 }