1 // Copyright (C) 2007-2020 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
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.
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.
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
20 // See http://www.salome-platform.org/
21 // file : MG_ADAPT.cxx
23 #include "MG_ADAPT.hxx"
25 #include "MeshFormatReader.hxx"
26 #include "MeshFormatWriter.hxx"
27 #include "MEDFileMesh.hxx"
29 #include "MEDFileData.hxx"
30 #include "MEDFileField.hxx"
31 #include "MEDCouplingFieldDouble.hxx"
33 #include <utilities.h>
36 #include <TCollection_AsciiString.hxx>
39 #include <boost/filesystem.hpp>
41 static std::string removeFile(std::string fileName, int& notOk)
44 notOk = std::remove(fileName.c_str());
45 if (notOk) errStr = ToComment(" \n error while removing file : ")
47 else errStr= ToComment("\n file : ")<< fileName << " succesfully deleted! \n ";
53 struct GET_DEFAULT // struct used to get default value from GetOptionValue()
62 //----------------------------------------------------------------------------------------
65 data = new MgAdaptHypothesisData();
66 data->myInMeshName = "";
67 data->fromMedFile = defaultFromMedFile();
68 data->myFileInDir = defaultWorkingDirectory();
69 data->myMeshFileIn = "";
70 data->myFileOutDir = defaultWorkingDirectory();
71 data->myOutMeshName = "";
72 data->myMeshFileOut = "";
73 data->myMeshOutMed = defaultMeshOutMed();
74 data->myPublish = defaultPublish();
75 data->myUseLocalMap = defaultUseLocalMap();
76 data->myUseBackgroundMap = defaultUseBackgroundMap();
77 data->myFileSizeMapDir = defaultWorkingDirectory();
78 data->myMeshFileBackground = "";
79 data->myUseConstantValue = defaultUseConstantValue();
80 data->myConstantValue = 0.0;
81 data->myFieldName = "";
82 data->myUseNoTimeStep = defaultUseNoTimeStep();
83 data->myUseLastTimeStep = defaultUseLastTimeStep();
84 data->myUseChosenTimeStep = defaultUseChosenTimeStep();
85 data->myTimeStep = -2;
87 data->myWorkingDir = defaultWorkingDirectory();
88 data->myLogFile = defaultLogFile();
89 data->myVerboseLevel = defaultVerboseLevel();
90 data->myPrintLogInFile = defaultPrintLogInFile();
91 data->myKeepFiles = defaultKeepFiles();
92 data->myRemoveLogOnSuccess = defaultRemoveLogOnSuccess();
97 MgAdapt::MgAdapt(MgAdaptHypothesisData* myData)
99 data = new MgAdaptHypothesisData();
104 MgAdapt::MgAdapt( const MgAdapt& copy)
107 data = new MgAdaptHypothesisData();
108 MgAdaptHypothesisData *copyData = copy.getData();
109 copyMgAdaptHypothesisData(copyData);
112 this->_option2value = copy._option2value;
113 this->_customOption2value = copy._customOption2value;
114 this->_defaultOptionValues = copy._defaultOptionValues;
115 this->_doubleOptions = copy._doubleOptions;
116 this->_charOptions = copy._charOptions;
117 this->_boolOptions = copy._boolOptions;
123 //-----------------------------------------------------------------------------------------
130 void MgAdapt::buildModel()
133 const char* boolOptionNames[] = { "compute_ridges", // yes
136 // const char* intOptionNames[] = { "max_number_of_errors_printed", // 1
137 // "max_number_of_threads", // 4
140 const char* doubleOptionNames[] = { "max_memory", // 0
143 const char* charOptionNames[] = { "components", // "yes"
144 "adaptation", // both
149 while (boolOptionNames[i][0])
151 _boolOptions.insert( boolOptionNames[i] );
152 _option2value[boolOptionNames[i++]].clear();
155 // while (intOptionNames[i][0])
156 // _option2value[intOptionNames[i++]].clear();
159 while (doubleOptionNames[i][0]) {
160 _doubleOptions.insert(doubleOptionNames[i]);
161 _option2value[doubleOptionNames[i++]].clear();
164 while (charOptionNames[i][0]) {
165 _charOptions.insert(charOptionNames[i]);
166 _option2value[charOptionNames[i++]].clear();
169 // default values to be used while MG-Adapt
171 _defaultOptionValues["adaptation" ] = "both";
172 _defaultOptionValues["components" ] = "outside components";
173 _defaultOptionValues["compute_ridges" ] = "yes";
174 _defaultOptionValues["max_memory" ] = ToComment(defaultMaximumMemory());
177 //=============================================================================
178 TOptionValues MgAdapt::getOptionValues() const
181 TOptionValues::const_iterator op_val = _option2value.begin();
182 for ( ; op_val != _option2value.end(); ++op_val )
183 vals.insert( make_pair( op_val->first, getOptionValue( op_val->first, GET_DEFAULT() )));
188 std::vector <std::string> MgAdapt::getOptionValuesStrVec() const
190 std::vector <std::string> vals;
191 TOptionValues::const_iterator op_val = _option2value.begin();
192 for ( ; op_val != _option2value.end(); ++op_val )
193 vals.push_back(op_val->first+":"+getOptionValue( op_val->first, GET_DEFAULT() ));
198 std::vector <std::string> MgAdapt::getCustomOptionValuesStrVec() const
200 std::vector <std::string> vals;
201 TOptionValues::const_iterator op_val;
202 for ( op_val = _customOption2value.begin(); op_val != _customOption2value.end(); ++op_val )
204 vals.push_back(op_val->first+":"+getOptionValue( op_val->first, GET_DEFAULT() ));
208 const TOptionValues& MgAdapt::getCustomOptionValues() const
210 return _customOption2value;
212 void MgAdapt::setData(MgAdaptHypothesisData* myData)
214 copyMgAdaptHypothesisData(myData);
217 MgAdaptHypothesisData* MgAdapt::getData() const
221 void MgAdapt::setMedFileIn(std::string fileName)
223 medFileIn = fileName;
226 std::string MgAdapt::getMedFileIn()
231 void MgAdapt::setMedFileOut(std::string fileOut)
233 medFileOut = fileOut;
236 std::string MgAdapt::getMedFileOut()
240 void MgAdapt::setMeshOutMed(bool mybool)
244 bool MgAdapt::getMeshOutMed()
248 void MgAdapt::setPublish(bool mybool)
252 bool MgAdapt::getPublish()
256 void MgAdapt::setFieldName(std::string myFieldName)
258 fieldName = myFieldName;
260 std::string MgAdapt::getFieldName()
264 void MgAdapt::setTimeStep(int time)
268 int MgAdapt::getTimeStep() const
273 void MgAdapt::setRankTimeStep(int time, int myRank)
279 int MgAdapt::getRank()
283 void MgAdapt::setUseLocalMap(bool myLocal)
285 useLocalMap = myLocal;
288 bool MgAdapt::getUseLocalMap()
293 void MgAdapt::setUseBackgroundMap(bool bckg)
295 useBackgroundMap = bckg;
298 bool MgAdapt::getUseBackgroundMap()
300 return useBackgroundMap;
303 void MgAdapt::setUseConstantValue(bool cnst)
305 useConstantValue = cnst;
308 bool MgAdapt::getUseConstantValue()
310 return useConstantValue;
312 void MgAdapt::setLogFile(std::string myLogFile)
316 std::string MgAdapt::getLogFile()
320 void MgAdapt::setVerbosityLevel(int verboLevel)
322 verbosityLevel = verboLevel;
324 int MgAdapt::getVerbosityLevel()
326 return verbosityLevel;
328 void MgAdapt::setRemoveOnSuccess(bool rmons)
330 removeOnSuccess = rmons;
332 bool MgAdapt::getRemoveOnSuccess()
334 return removeOnSuccess;
336 void MgAdapt::setSizeMapFile(std::string mapFile)
338 sizeMapFile = mapFile;
340 std::string MgAdapt::getSizeMapFile()
345 void MgAdapt::setMeshName(std::string name)
349 std::string MgAdapt::getMeshName()
353 void MgAdapt::setMeshNameOut(std::string name)
357 std::string MgAdapt::getMeshNameOut()
361 void MgAdapt::setFromMedFile(bool mybool)
363 fromMedFile = mybool;
365 bool MgAdapt::isFromMedFile()
369 void MgAdapt::setConstantValue(double cnst)
371 constantValue = cnst;
373 double MgAdapt::getConstantValue() const
375 return constantValue;
378 void MgAdapt::setWorkingDir(std::string dir)
382 std::string MgAdapt::getWorkingDir() const
386 void MgAdapt::setKeepWorkingFiles(bool mybool)
388 toKeepWorkingFiles = mybool;
390 bool MgAdapt::getKeepWorkingFiles()
392 return toKeepWorkingFiles;
394 void MgAdapt::setPrintLogInFile(bool print)
396 printLogInFile = print;
398 bool MgAdapt::getPrintLogInFile()
400 return printLogInFile;
403 bool MgAdapt::setAll()
406 setFromMedFile(data->fromMedFile);
408 checkDirPath(data->myFileInDir);
409 file = data->myFileInDir+data->myMeshFileIn;
411 setMeshName(data->myInMeshName);
412 setMeshNameOut(data->myOutMeshName);
413 checkDirPath(data->myFileOutDir);
414 std::string out = data->myFileOutDir+data->myMeshFileOut;
416 setPublish(data->myPublish);
417 setMeshOutMed(data->myMeshOutMed);
418 setUseLocalMap(data->myUseLocalMap);
419 setUseBackgroundMap(data->myUseBackgroundMap);
420 setUseConstantValue(data->myUseConstantValue);
423 if (useBackgroundMap)
426 checkDirPath(data->myFileSizeMapDir);
427 mapfile = data->myFileSizeMapDir+data->myMeshFileBackground;
428 setFieldName(data->myFieldName);
430 else if (useConstantValue)
432 setConstantValue(data->myConstantValue);
437 setConstantValue(0.0);
438 setFieldName(data->myFieldName);
442 setSizeMapFile(mapfile);
445 if (data->myUseNoTimeStep)
450 else if (data->myUseLastTimeStep)
452 std::string fieldFile = useBackgroundMap ? sizeMapFile : medFileIn;
453 getTimeStepInfos(fieldFile, tmst, rank);
458 tmst = data->myTimeStep;
460 setRankTimeStep((int)tmst, (int)rank);
462 /* Advanced options */
463 setWorkingDir(data->myWorkingDir);
464 checkDirPath(data->myWorkingDir);
465 setLogFile(data->myWorkingDir+defaultLogFile());
466 setVerbosityLevel(data->myVerboseLevel);
467 setRemoveOnSuccess(data->myRemoveLogOnSuccess);
468 setPrintLogInFile(data->myPrintLogInFile);
469 setKeepWorkingFiles(data->myKeepFiles);
474 void MgAdapt::checkDirPath(std::string& dirPath)
476 const char lastChar = *dirPath.rbegin();
478 if(lastChar != '\\') dirPath+='\\';
480 if(lastChar != '/') dirPath+='/';
483 //=============================================================================
484 void MgAdapt::setOptionValue(const std::string& optionName,
485 const std::string& optionValue)
486 throw (std::invalid_argument)
488 TOptionValues::iterator op_val = _option2value.find(optionName);
489 if (op_val == _option2value.end())
491 op_val = _customOption2value.find( optionName );
492 _customOption2value[ optionName ] = optionValue;
496 if (op_val->second != optionValue)
499 std::string lowerOptionValue = toLowerStr(optionValue);
500 const char* ptr = lowerOptionValue.c_str();
501 // strip white spaces
502 while (ptr[0] == ' ')
505 while (i != 0 && ptr[i - 1] == ' ')
509 std::string typeName;
512 } else if (_charOptions.count(optionName)) {
513 // do not check strings
514 } else if (_doubleOptions.count(optionName)) {
515 // check if value is double
518 } else if (_boolOptions.count(optionName)) {
519 // check if value is bool
520 toBool(ptr, &typeOk);
523 // check if value is int
525 typeName = "integer";
527 if ( typeOk ) // check some specific values ?
532 std::string msg = "Advanced option '" + optionName + "' = '" + optionValue + "' but must be " + typeName;
533 throw std::invalid_argument(msg);
535 std::string value( ptr, i );
536 if ( _defaultOptionValues[ optionName ] == value )
540 op_val->second = value;
544 //=============================================================================
545 //! Return option value. If isDefault provided, it can be a default value,
546 // then *isDefault == true. If isDefault is not provided, the value will be
547 // empty if it equals a default one.
548 std::string MgAdapt::getOptionValue(const std::string& optionName, bool* isDefault) const
549 throw (std::invalid_argument)
551 TOptionValues::const_iterator op_val = _option2value.find(optionName);
552 if (op_val == _option2value.end())
554 op_val = _customOption2value.find(optionName);
555 if (op_val == _customOption2value.end())
557 std::string msg = "Unknown MG-Adapt option: <" + optionName + ">";
558 throw std::invalid_argument(msg);
561 std::string val = op_val->second;
562 if ( isDefault ) *isDefault = ( val.empty() );
564 if ( val.empty() && isDefault )
566 op_val = _defaultOptionValues.find( optionName );
567 if (op_val != _defaultOptionValues.end())
568 val = op_val->second;
572 //================================================================================
574 * \brief Converts a string to a real value
576 //================================================================================
578 double MgAdapt::toDbl(const std::string& str, bool* isOk )
579 throw (std::invalid_argument)
581 if ( str.empty() ) throw std::invalid_argument("Empty value provided");
584 double val = strtod(&str[0], &endPtr);
585 bool ok = (&str[0] != endPtr);
587 if ( isOk ) *isOk = ok;
591 std::string msg = "Not a real value:'" + str + "'";
592 throw std::invalid_argument(msg);
596 //================================================================================
598 * \brief Converts a string to a lower
600 //================================================================================
601 std::string MgAdapt::toLowerStr(const std::string& str)
604 for ( size_t i = 0; i <= s.size(); ++i )
605 s[i] = tolower( s[i] );
608 //================================================================================
610 * \brief Converts a string to a bool
612 //================================================================================
614 bool MgAdapt::toBool(const std::string& str, bool* isOk )
615 throw (std::invalid_argument)
618 if ( isOk ) *isOk = true;
620 for ( size_t i = 0; i <= s.size(); ++i )
621 s[i] = tolower( s[i] );
623 if ( s == "1" || s == "true" || s == "active" || s == "yes" )
626 if ( s == "0" || s == "false" || s == "inactive" || s == "no" )
632 std::string msg = "Not a Boolean value:'" + str + "'";
633 throw std::invalid_argument(msg);
637 //================================================================================
639 * \brief Converts a string to a integer value
641 //================================================================================
643 int MgAdapt::toInt(const std::string& str, bool* isOk )
644 throw (std::invalid_argument)
646 if ( str.empty() ) throw std::invalid_argument("Empty value provided");
649 int val = (int)strtol( &str[0], &endPtr, 10);
650 bool ok = (&str[0] != endPtr);
652 if ( isOk ) *isOk = ok;
656 std::string msg = "Not an integer value:'" + str + "'";
657 throw std::invalid_argument(msg);
661 //=============================================================================
662 bool MgAdapt::hasOptionDefined( const std::string& optionName ) const
664 bool isDefault = false;
667 getOptionValue( optionName, &isDefault );
669 catch ( std::invalid_argument )
675 //================================================================================
677 * \brief Return command to run MG-Tetra mesher excluding file prefix (-f)
679 //================================================================================
681 std::string MgAdapt::getCommandToRun(MgAdapt* hyp)
683 return hyp ? hyp->getCommandToRun() : ToComment("error with hypothesis!");
688 int MgAdapt::compute(std::string& errStr)
690 std::string cmd = getCommandToRun();
692 execCmd( cmd.c_str(), err ); // run
696 errStr = ToComment("system(mg-adapt.exe ...) command failed with error: ")
697 << strerror( errno );
701 convertMeshFile(meshFormatOutputMesh, solFormatOutput);
703 //~if (!err) cleanUp();
707 void MgAdapt::execCmd( const char* cmd, int& err)
710 std::array <char, 128> buffer;
712 outFileStream fileStream;
715 fileStream.open(logFile);
716 buf = fileStream.rdbuf();
720 buf = std::cout.rdbuf();
722 std::ostream logStream(buf);
724 std::unique_ptr <FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose );
727 throw std::runtime_error("popen() failed!");
729 while(fgets(buffer.data(), buffer.size(), pipe.get()) !=nullptr )
731 logStream<<buffer.data() ;
736 void MgAdapt::cleanUp()
740 if(removeOnSuccess) tmpFilesToBeDeleted.push_back(logFile);
742 std::vector< std::string>::iterator it = tmpFilesToBeDeleted.begin();
743 for (; it!=tmpFilesToBeDeleted.end(); ++it)
745 errStr=removeFile(*it, notOk);
748 appendMsgToLogFile(errStr);
754 void MgAdapt::appendMsgToLogFile(std::string& msg)
756 std::ofstream logStream;
757 logStream.open(logFile, std::ofstream::out | std::ofstream::app);
761 //================================================================================
763 * \brief Return command to run MG-Tetra mesher excluding file prefix (-f)
765 //================================================================================
767 std::string MgAdapt::getCommandToRun()
770 || return system command with args and options
774 std::string cmd = getExeName();
775 std::string meshIn(""), sizeMapIn(""), solFileIn("");
776 convertMedFile(meshIn, solFileIn, sizeMapIn);
777 if (!isFileExist(meshIn) || !isFileExist(solFileIn))
779 errStr = ToComment(" failed to find .mesh or .sol file from converter ")<< strerror( errno );
782 tmpFilesToBeDeleted.push_back(meshIn);
783 tmpFilesToBeDeleted.push_back(solFileIn);
784 if(useBackgroundMap && !isFileExist(sizeMapIn))
787 errStr = ToComment(" failed to find .mesh size map file from converter ")<< strerror( errno );
793 cmd+= " --in "+ meshIn;
794 meshFormatOutputMesh = getFileName()+".mesh";
795 cmd+= " --out "+ meshFormatOutputMesh;
796 if (useLocalMap || useConstantValue) cmd+= " --sizemap "+ solFileIn;
797 else // (useBackgroundMap)
799 cmd+= " --background_mesh "+ sizeMapIn ;
800 cmd+= " --background_sizemap "+ solFileIn;
801 tmpFilesToBeDeleted.push_back(sizeMapIn);
805 //~// constant value TODO
807 /* sizemap file is not adapted in case of only surface adaptation see MeshGems docs */
808 std::string adapOp = "adaptation";
809 std::string adpOpVal = getOptionValue(adapOp);
810 std::string surfaceAdapt = "surface";
811 if(surfaceAdapt != adpOpVal )
813 std::string solFileOut = getFileName()+".sol";
814 cmd+= " --write_sizemap "+ solFileOut;
815 solFormatOutput.push_back(solFileOut);
817 if (verbosityLevel != defaultVerboseLevel())
820 cmd+= " --verbose "+ ToComment(verbosityLevel);
823 std::string option, value;
825 const TOptionValues* options[] = { &_option2value, &_customOption2value };
826 for ( int iOp = 0; iOp < 2; ++iOp )
828 TOptionValues::const_iterator o2v = options[iOp]->begin();
829 for ( ; o2v != options[iOp]->end(); ++o2v )
832 value = getOptionValue( option, &isDefault );
836 if ( value.empty() )//value == NoValue() )
838 if ( _defaultOptionValues.count( option ))
839 continue; // non-custom option with no value
842 if ( strncmp( "no", option.c_str(), 2 ) == 0 ) // options w/o values: --no_*
844 if ( !value.empty() && toBool( value ) == false )
848 if ( option[0] != '-' )
852 cmd += option + " " + value;
865 bool MgAdapt::isFileExist(std::string& fName) const
871 boost::system::error_code err;
872 bool res = boost::filesystem::exists( fName, err );
874 return err ? false : res;
876 //=======================================================================
877 //function : defaultMaximumMemory
878 //=======================================================================
882 #elif !defined(__APPLE__)
883 #include <sys/sysinfo.h>
886 double MgAdapt::defaultMaximumMemory()
889 // See http://msdn.microsoft.com/en-us/library/aa366589.aspx
890 MEMORYSTATUSEX statex;
891 statex.dwLength = sizeof (statex);
892 long err = GlobalMemoryStatusEx (&statex);
894 double totMB = (double)statex.ullAvailPhys / 1024. / 1024.;
895 return (double)( 0.7 * totMB );
897 #elif !defined(__APPLE__)
899 long err = sysinfo( &si );
901 long ramMB = si.totalram * si.mem_unit / 1024 / 1024;
902 return ( 0.7 * ramMB );
909 //=======================================================================
910 //function : defaultWorkingDirectory
911 //=======================================================================
913 std::string MgAdapt::defaultWorkingDirectory()
915 TCollection_AsciiString aTmpDir;
917 char *Tmp_dir = getenv("SALOME_TMP_DIR");
918 if(Tmp_dir != NULL) {
923 aTmpDir = TCollection_AsciiString("C:\\");
925 aTmpDir = TCollection_AsciiString("/tmp/");
928 return aTmpDir.ToCString();
930 //================================================================================
932 * \brief Return a unique file name
934 //================================================================================
936 std::string MgAdapt::getFileName() const
938 std::string aTmpDir = workingDir;
939 const char lastChar = *aTmpDir.rbegin();
941 if(lastChar != '\\') aTmpDir+='\\';
943 if(lastChar != '/') aTmpDir+='/';
946 TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
947 aGenericName += "MgAdapt_";
948 aGenericName += getpid();
950 aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
952 return aGenericName.ToCString();
954 //=======================================================================
955 //function : defaultLogFile
956 //=======================================================================
958 std::string MgAdapt::defaultLogFile()
960 std::string alogFile("MG_ADAPT.log");
963 //=======================================================================
964 //function : defaultUseConstantValue
965 //=======================================================================
967 bool MgAdapt::defaultUseConstantValue()
971 //=======================================================================
972 //function : defaultUseNoTimeStep
973 //=======================================================================
975 bool MgAdapt::defaultUseNoTimeStep()
979 //=======================================================================
980 //function : defaultRemoveLogOnSuccess
981 //=======================================================================
983 bool MgAdapt::defaultRemoveLogOnSuccess()
987 //=======================================================================
988 //function : defaultPrintLogInFile
989 //=======================================================================
991 bool MgAdapt::defaultPrintLogInFile()
995 //=======================================================================
996 //function : defaultUseChosenTimeStep
997 //=======================================================================
999 bool MgAdapt::defaultUseChosenTimeStep()
1003 //=======================================================================
1004 //function : UseLastTimeStep
1005 //=======================================================================
1007 bool MgAdapt::defaultUseLastTimeStep()
1011 //=======================================================================
1012 //function : defaultUseBackgroundMap
1013 //=======================================================================
1015 bool MgAdapt::defaultUseBackgroundMap()
1019 //=======================================================================
1020 //function : defaultKeepFiles
1021 //=======================================================================
1023 bool MgAdapt::defaultKeepFiles()
1027 //=======================================================================
1028 //function : defaultUseLocalMap
1029 //=======================================================================
1031 bool MgAdapt::defaultUseLocalMap()
1035 //=======================================================================
1036 //function : defaultPublish
1037 //=======================================================================
1039 bool MgAdapt::defaultPublish()
1043 //=======================================================================
1044 //function : defaultMeshOutMed
1045 //=======================================================================
1047 bool MgAdapt::defaultMeshOutMed()
1051 //=======================================================================
1052 //function : defaultFromMedFile
1053 //=======================================================================
1055 bool MgAdapt::defaultFromMedFile()
1059 //=======================================================================
1060 //function : defaultVerboseLevel
1061 //=======================================================================
1063 int MgAdapt::defaultVerboseLevel()
1067 std::string MgAdapt::getExeName()
1069 return "mg-adapt.exe";
1071 void MgAdapt::copyMgAdaptHypothesisData( MgAdaptHypothesisData* from)
1074 data->myFileInDir = from->myFileInDir;
1075 data->myMeshFileIn = from->myMeshFileIn;
1076 data->myMeshFileBackground = from->myMeshFileBackground;
1077 data->myOutMeshName = from->myOutMeshName;
1078 data->myMeshFileOut = from->myMeshFileOut;
1079 data->myFileOutDir = from->myFileOutDir;
1080 data->myFileSizeMapDir = from->myFileSizeMapDir;
1081 data->myFieldName = from->myFieldName;
1082 data->fromMedFile = from->fromMedFile;
1083 data->myPublish = from->myPublish;
1084 data->myMeshOutMed = from->myMeshOutMed;
1085 data->myUseLocalMap = from->myUseLocalMap;
1086 data->myUseBackgroundMap = from->myUseBackgroundMap;
1087 data->myUseConstantValue = from->myUseConstantValue;
1088 data->myConstantValue = from->myConstantValue;
1089 data->myTimeStep = from->myTimeStep;
1090 data->myRank = from->myRank;
1091 data->myUseNoTimeStep = from->myUseNoTimeStep;
1092 data->myUseLastTimeStep = from->myUseLastTimeStep;
1093 data->myUseChosenTimeStep = from->myUseChosenTimeStep;
1094 data->myWorkingDir = from->myWorkingDir;
1095 data->myLogFile = from->myLogFile;
1096 data->myPrintLogInFile = from->myPrintLogInFile;
1097 data->myKeepFiles = from->myKeepFiles;
1098 data->myRemoveLogOnSuccess = from->myRemoveLogOnSuccess;
1099 data->myVerboseLevel = from->myVerboseLevel;
1104 void MgAdapt::convertMedFile(std::string& meshFormatMeshFileName, std::string& solFormatFieldFileName, std::string& meshFormatsizeMapFile)
1107 std::vector<std::string> fieldFileNames;
1108 MEDCoupling::MeshFormatWriter writer;
1109 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = MEDCoupling::MEDFileData::New(medFileIn);
1110 MEDCoupling::MEDFileMeshes* meshes = mfd->getMeshes();
1111 MEDCoupling::MEDFileMesh* fileMesh = meshes->getMeshAtPos(0); // ok only one mesh in file!
1112 storeGroupsAndFams(fileMesh);
1114 MEDCoupling::MCAuto<MEDCoupling::MEDFileFields> fields = MEDCoupling::MEDFileFields::New();
1115 solFormatFieldFileName = getFileName();
1116 solFormatFieldFileName+=".sol";
1117 fieldFileNames.push_back(solFormatFieldFileName);
1119 if (useBackgroundMap)
1122 meshFormatsizeMapFile = getFileName();
1123 meshFormatsizeMapFile += ".mesh";
1124 buildBackGroundMeshAndSolFiles(fieldFileNames, meshFormatsizeMapFile);
1127 else if(useLocalMap)
1130 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeFieldMultiTS> fts = dynamic_cast<MEDCoupling::MEDFileFieldMultiTS *>( mfd->getFields()->getFieldWithName(fieldName) );
1131 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeField1TS> f = fts->getTimeStep(timeStep, rank);
1132 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> tmFts = MEDCoupling::MEDFileFieldMultiTS::New();
1133 tmFts->pushBackTimeStep(f);
1135 fields->pushField(tmFts);
1137 writer.setFieldFileNames( fieldFileNames);
1142 MEDCoupling::MCAuto<MEDCoupling::MEDCouplingMesh> mesh = fileMesh->getMeshAtLevel(1); // nodes mesh
1143 MEDCoupling::MCAuto<MEDCoupling::MEDCouplingUMesh> umesh = mesh->buildUnstructured(); // nodes mesh
1144 int dim = umesh->getSpaceDimension();
1145 int version = sizeof(double) < 8 ? 1 : 2;
1146 mcIdType nbNodes = umesh->getNumberOfNodes();
1147 buildConstantSizeMapSolFile(solFormatFieldFileName, dim, version, nbNodes);
1151 mfd->setFields( fields );
1152 meshFormatMeshFileName = getFileName();
1153 meshFormatMeshFileName+=".mesh";
1154 writer.setMeshFileName(meshFormatMeshFileName);
1155 writer.setMEDFileDS( mfd);
1160 void MgAdapt::convertMeshFile(std::string& meshFormatIn, std::vector< std::string>& solFieldFileNames) const
1162 MEDCoupling::MeshFormatReader reader(meshFormatIn, solFieldFileNames);
1164 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = reader.loadInMedFileDS();
1166 MEDCoupling::MEDFileMeshes* meshes = mfd->getMeshes();
1167 MEDCoupling::MEDFileMesh* fileMesh = meshes->getMeshAtPos(0); // ok only one mesh in file!
1168 fileMesh->setName(meshNameOut);
1169 restoreGroupsAndFams(fileMesh);
1170 mfd->write(medFileOut, 2);
1174 void MgAdapt::storeGroupsAndFams(MEDCoupling::MEDFileMesh* fileMesh)
1176 storefams(fileMesh);
1177 storeGroups(fileMesh);
1180 void MgAdapt::restoreGroupsAndFams(MEDCoupling::MEDFileMesh* fileMesh) const
1182 restorefams(fileMesh);
1183 restoreGroups(fileMesh);
1185 void MgAdapt::storeGroups(MEDCoupling::MEDFileMesh* fileMesh)
1187 std::map<std::string, std::vector<std::string> > grpFams = fileMesh->getGroupInfo();
1188 std::map<std::string, std::vector<std::string> >::iterator g2ff = grpFams.begin();
1190 for ( ; g2ff != grpFams.end(); ++g2ff )
1192 std::string groupName = g2ff->first;
1193 std::vector<std::string> famNames = g2ff->second;
1195 if ( famNames.empty() ) continue;
1197 std::vector< mcIdType> famListId;
1198 for ( size_t i = 0; i < famNames.size(); ++i )
1200 famListId.push_back( fileMesh->getFamilyId( famNames[i].c_str() ) );
1202 group grp(groupName, famListId, famNames);
1203 groupVec.push_back(grp);
1207 void MgAdapt::storefams(MEDCoupling::MEDFileMesh* fileMesh)
1209 std::map<std::string, mcIdType> grpFams = fileMesh->getFamilyInfo();
1210 std::map<std::string, mcIdType >::iterator f = grpFams.begin();
1212 for ( ; f != grpFams.end(); ++f )
1214 if(!f->second) continue; // FAMILLE_ZERO
1215 family fs(f->first, f->second);
1216 famVec.push_back(fs);
1221 void MgAdapt::restorefams(MEDCoupling::MEDFileMesh* fileMesh) const
1223 std::vector<family>::const_iterator fIt = famVec.begin();
1225 for (; fIt!=famVec.end(); ++fIt)
1227 try // safety : FAMILY could be lost P2-->P1
1229 std::string givenFamNameFromMeshGemConverter = fileMesh->getFamilyNameGivenId( std::abs(fIt->_famId) );
1230 fileMesh->changeFamilyId(std::abs(fIt->_famId), fIt->_famId);
1231 fileMesh->changeFamilyName(givenFamNameFromMeshGemConverter, fIt->_famName);
1233 catch (const std::exception& e)
1235 std::cerr<<e.what();
1240 void MgAdapt::restoreGroups(MEDCoupling::MEDFileMesh* fileMesh) const
1242 std::map<std::string, std::vector<std::string> > info;
1243 std::vector <group>::const_iterator grpFams = groupVec.begin();
1245 for (; grpFams!=groupVec.end(); ++grpFams)
1247 info.insert(std::pair <std::string, std::vector<std::string> > (grpFams->_name, grpFams->_famNames) );
1250 fileMesh->setGroupInfo(info);
1253 void MgAdapt::buildConstantSizeMapSolFile(const std::string& solFormatFieldFileName, const int dim, const int version, const mcIdType nbNodes) const
1255 MeshFormat::Localizer loc;
1256 MeshFormat::MeshFormatParser writer;
1257 int fileId = writer.GmfOpenMesh( solFormatFieldFileName.c_str(), GmfWrite, version, dim);
1258 int typTab[] = {GmfSca};
1259 writer.GmfSetKwd(fileId, MeshFormat::GmfSolAtVertices, (int)nbNodes, 1, typTab);
1260 for (mcIdType i = 0; i<nbNodes; i++)
1262 double valTab[1] = {constantValue};
1263 writer.GmfSetLin( fileId, MeshFormat::GmfSolAtVertices, valTab);
1265 writer.GmfCloseMesh(fileId);
1268 void MgAdapt::buildBackGroundMeshAndSolFiles(const std::vector<std::string>& fieldFileNames, const std::string& meshFormatsizeMapFile) const
1270 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> tmpMfd = MEDCoupling::MEDFileData::New(sizeMapFile);
1271 MEDCoupling::MEDFileFields* tmpFields = tmpMfd->getFields();
1272 MEDCoupling::MEDFileAnyTypeFieldMultiTS* fts = tmpFields->getFieldWithName(fieldName);
1273 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> fts1 = dynamic_cast<MEDCoupling::MEDFileFieldMultiTS *>(fts);
1274 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeField1TS> f = fts1->getTimeStep(timeStep, rank);
1275 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> tmFts = MEDCoupling::MEDFileFieldMultiTS::New();
1276 tmFts->pushBackTimeStep(f);
1278 MEDCoupling::MCAuto<MEDCoupling::MEDFileFields> tmp_fields = MEDCoupling::MEDFileFields::New();
1279 tmp_fields->pushField(tmFts);
1282 tmpMfd->setFields( tmp_fields );
1283 MEDCoupling::MeshFormatWriter tmpWriter;
1284 tmpWriter.setMeshFileName(meshFormatsizeMapFile);
1285 tmpWriter.setFieldFileNames( fieldFileNames);
1286 tmpWriter.setMEDFileDS(tmpMfd);
1289 // =======================================================================
1290 med_idt MgAdapt::openMedFile(const std::string aFile)
1291 // =======================================================================
1292 // renvoie le medId associe au fichier Med apres ouverture
1294 med_idt medIdt = MEDfileOpen(aFile.c_str(),MED_ACC_RDONLY);
1297 //~addMessage( ToComment(" error: Can't open ") << aFile, /*fatal=*/true );
1303 MgAdapt::Status MgAdapt::addMessage(const std::string& msg,
1304 const bool isFatal/*=false*/)
1307 _myErrorMessages.clear(); // warnings are useless if a fatal error encounters
1309 _myErrorMessages.push_back( msg );
1313 std::cout << msg << std::endl;
1315 return ( _myStatus = isFatal ? MgAdapt::DRS_FAIL : MgAdapt::DRS_WARN_SKIP_ELEM );
1321 // =======================================================================
1322 void MgAdapt::getTimeStepInfos(std::string aFile, med_int& numdt, med_int& numit)
1323 // =======================================================================
1325 // Il faut voir si plusieurs maillages
1332 // Ouverture du fichier
1333 //~SCRUTE(aFile.toStdString());
1334 medIdt = openMedFile(aFile);
1335 if ( medIdt < 0 ) return ;
1336 // Lecture du nombre de champs
1337 med_int ncha = MEDnField(medIdt) ;
1340 //~addMessage( ToComment(" error: there is no field in ") << aFile, /*fatal=*/true );
1343 // Lecture des caracteristiques du champs
1345 // Lecture du type du champ, des noms des composantes et du nom de l'unite
1346 char nomcha [MED_NAME_SIZE+1];
1347 strcpy(nomcha, fieldName.c_str());
1348 // Lecture du nombre de composantes
1349 med_int ncomp = MEDfieldnComponentByName(medIdt, nomcha);
1350 char meshname[MED_NAME_SIZE+1];
1351 char * comp = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
1352 char * unit = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
1353 char dtunit[MED_SNAME_SIZE+1];
1355 med_field_type typcha;
1357 erreur = MEDfieldInfoByName (medIdt, nomcha, meshname,&local,&typcha,comp,unit,dtunit, &nbofcstp);
1362 //~addMessage( ToComment(" error: error while reading field ") << nomcha << " in file " << aFile , /*fatal=*/true );
1367 med_int tmp_numdt, tmp_numit;
1369 //~med_int step = data->myUseLastTimeStep ? nbofcstp : data->myTimeStep+1;
1370 //~myPrint("step ", step);
1371 erreur = MEDfieldComputingStepInfo ( medIdt, nomcha, 1, &numdt, &numit, &dt );
1372 for(med_int step = 1; step <= nbofcstp; step++ )
1374 erreur = MEDfieldComputingStepInfo ( medIdt, nomcha, step, &tmp_numdt, &tmp_numit, &dt );
1375 if(tmp_numdt > numdt)
1384 //~addMessage( ToComment(" error: error while reading field ") << nomcha << "step (numdt, numit) = " <<"("<< numdt<< ", " \
1385 numit<< ")" <<" in file " << aFile , /*fatal=*/true );
1391 // Fermeture du fichier
1392 if ( medIdt > 0 ) MEDfileClose(medIdt);