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/ or email : webmaster.salome@opencascade.com
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 using namespace MG_ADAPT;
42 static std::string removeFile(std::string fileName, int& notOk)
45 notOk = std::remove(fileName.c_str());
46 if (notOk) errStr = ToComment("\n error while removing file : ") << fileName;
47 else errStr = ToComment("\n file : ") << fileName << " succesfully deleted! \n ";
51 std::string remove_extension(const std::string& filename) {
52 size_t lastdot = filename.find_last_of(".");
53 if (lastdot == std::string::npos) return filename;
54 return filename.substr(0, lastdot);
58 struct GET_DEFAULT // struct used to get default value from GetOptionValue()
67 //----------------------------------------------------------------------------------------
70 data = new MgAdaptHypothesisData();
71 data->myInMeshName = "";
72 data->fromMedFile = defaultFromMedFile();
73 data->myFileInDir = defaultWorkingDirectory();
74 data->myMeshFileIn = "";
75 data->myFileOutDir = defaultWorkingDirectory();
76 data->myOutMeshName = "";
77 data->myMeshFileOut = "";
78 data->myMeshOutMed = defaultMeshOutMed();
79 data->myPublish = defaultPublish();
80 data->myUseLocalMap = defaultUseLocalMap();
81 data->myUseBackgroundMap = defaultUseBackgroundMap();
82 data->myFileSizeMapDir = defaultWorkingDirectory();
83 data->myMeshFileBackground = "";
84 data->myUseConstantValue = defaultUseConstantValue();
85 data->myConstantValue = 0.0;
86 data->myFieldName = "";
87 data->myUseNoTimeStep = defaultUseNoTimeStep();
88 data->myUseLastTimeStep = defaultUseLastTimeStep();
89 data->myUseChosenTimeStep = defaultUseChosenTimeStep();
90 data->myTimeStep = -2;
92 data->myWorkingDir = defaultWorkingDirectory();
93 data->myLogFile = defaultLogFile();
94 data->myVerboseLevel = defaultVerboseLevel();
95 data->myPrintLogInFile = defaultPrintLogInFile();
96 data->myKeepFiles = defaultKeepFiles();
97 data->myRemoveLogOnSuccess = defaultRemoveLogOnSuccess();
102 MgAdapt::MgAdapt(MgAdaptHypothesisData* myData)
104 data = new MgAdaptHypothesisData();
109 MgAdapt::MgAdapt( const MgAdapt& copy)
111 data = new MgAdaptHypothesisData();
112 MgAdaptHypothesisData *copyData = copy.getData();
113 copyMgAdaptHypothesisData(copyData);
116 this->_option2value = copy._option2value;
117 this->_customOption2value = copy._customOption2value;
118 this->_defaultOptionValues = copy._defaultOptionValues;
119 this->_doubleOptions = copy._doubleOptions;
120 this->_charOptions = copy._charOptions;
121 this->_boolOptions = copy._boolOptions;
124 //-----------------------------------------------------------------------------------------
129 void MgAdapt::buildModel()
132 const char* boolOptionNames[] = { "compute_ridges", // yes
135 // const char* intOptionNames[] = { "max_number_of_errors_printed", // 1
136 // "max_number_of_threads", // 4
139 const char* doubleOptionNames[] = { "max_memory", // 0
142 const char* charOptionNames[] = { "components", // "yes"
143 "adaptation", // both
148 while (boolOptionNames[i][0])
150 _boolOptions.insert( boolOptionNames[i] );
151 _option2value[boolOptionNames[i++]].clear();
154 // while (intOptionNames[i][0])
155 // _option2value[intOptionNames[i++]].clear();
158 while (doubleOptionNames[i][0]) {
159 _doubleOptions.insert(doubleOptionNames[i]);
160 _option2value[doubleOptionNames[i++]].clear();
163 while (charOptionNames[i][0]) {
164 _charOptions.insert(charOptionNames[i]);
165 _option2value[charOptionNames[i++]].clear();
168 // default values to be used while MG-Adapt
170 _defaultOptionValues["adaptation" ] = "both";
171 _defaultOptionValues["components" ] = "outside components";
172 _defaultOptionValues["compute_ridges" ] = "yes";
173 _defaultOptionValues["max_memory" ] = ToComment(defaultMaximumMemory());
176 //=============================================================================
177 TOptionValues MgAdapt::getOptionValues() const
180 TOptionValues::const_iterator op_val = _option2value.begin();
181 for ( ; op_val != _option2value.end(); ++op_val )
182 vals.insert( make_pair( op_val->first, getOptionValue( op_val->first, GET_DEFAULT() )));
187 std::vector <std::string> MgAdapt::getOptionValuesStrVec() const
189 std::vector <std::string> vals;
190 TOptionValues::const_iterator op_val = _option2value.begin();
191 for ( ; op_val != _option2value.end(); ++op_val )
192 vals.push_back(op_val->first+":"+getOptionValue( op_val->first, GET_DEFAULT() ));
197 std::vector <std::string> MgAdapt::getCustomOptionValuesStrVec() const
199 std::vector <std::string> vals;
200 TOptionValues::const_iterator op_val;
201 for ( op_val = _customOption2value.begin(); op_val != _customOption2value.end(); ++op_val )
203 vals.push_back(op_val->first+":"+getOptionValue( op_val->first, GET_DEFAULT() ));
207 const TOptionValues& MgAdapt::getCustomOptionValues() const
209 return _customOption2value;
211 void MgAdapt::setData(MgAdaptHypothesisData* myData)
213 copyMgAdaptHypothesisData(myData);
216 MgAdaptHypothesisData* MgAdapt::getData() const
220 void MgAdapt::setMedFileIn(std::string fileName)
222 medFileIn = fileName;
223 if (medFileOut == "") // default MED file Out
224 medFileOut = remove_extension( fileName )+ ".adapt.med";
227 std::string MgAdapt::getMedFileIn()
232 void MgAdapt::setMedFileOut(std::string fileOut)
234 medFileOut = fileOut;
237 std::string MgAdapt::getMedFileOut()
241 void MgAdapt::setMeshOutMed(bool mybool)
245 bool MgAdapt::getMeshOutMed()
249 void MgAdapt::setPublish(bool mybool)
253 bool MgAdapt::getPublish()
257 void MgAdapt::setFieldName(std::string myFieldName)
259 fieldName = myFieldName;
261 std::string MgAdapt::getFieldName()
265 void MgAdapt::setTimeStep(int time)
269 int MgAdapt::getTimeStep() const
274 void MgAdapt::setRankTimeStep(int time, int myRank)
280 int MgAdapt::getRank()
284 void MgAdapt::setTimeStepRankLast()
286 myUseLastTimeStep = true;
287 myUseChosenTimeStep = false;
288 myUseNoTimeStep = false;
289 //~med_int aRank, tmst;
290 //~std::string fieldFile = useBackgroundMap ? sizeMapFile : medFileIn;
291 //~getTimeStepInfos(fieldFile, tmst, aRank);
292 //~setRankTimeStep((int) tmst, (int) aRank);
294 void MgAdapt::setNoTimeStep()
296 myUseLastTimeStep = false;
297 myUseChosenTimeStep = false;
298 myUseNoTimeStep = true;
299 //~int aRank = (int)MED_NO_IT;
300 //~int tmst = (int)MED_NO_DT ;
301 //~setRankTimeStep(tmst, aRank);
303 void MgAdapt::setChosenTimeStepRank()
305 myUseLastTimeStep = false;
306 myUseChosenTimeStep = true;
307 myUseNoTimeStep = false;
308 //~int aRank = (int)MED_NO_IT;
309 //~int tmst = (int)MED_NO_DT ;
310 //~setRankTimeStep(tmst, aRank);
312 void MgAdapt::setUseLocalMap(bool myLocal)
314 useLocalMap = myLocal;
317 bool MgAdapt::getUseLocalMap()
322 void MgAdapt::setUseBackgroundMap(bool bckg)
324 useBackgroundMap = bckg;
327 bool MgAdapt::getUseBackgroundMap()
329 return useBackgroundMap;
332 void MgAdapt::setUseConstantValue(bool cnst)
334 useConstantValue = cnst;
336 bool MgAdapt::getUseConstantValue()
338 return useConstantValue;
340 void MgAdapt::setLogFile(std::string myLogFile)
344 std::string MgAdapt::getLogFile()
348 void MgAdapt::setVerbosityLevel(int verboLevel)
350 verbosityLevel = verboLevel;
352 int MgAdapt::getVerbosityLevel()
354 return verbosityLevel;
356 void MgAdapt::setRemoveOnSuccess(bool rmons)
358 removeOnSuccess = rmons;
360 bool MgAdapt::getRemoveOnSuccess()
362 return removeOnSuccess;
364 void MgAdapt::setSizeMapFile(std::string mapFile)
366 sizeMapFile = mapFile;
368 std::string MgAdapt::getSizeMapFile()
373 void MgAdapt::setMeshName(std::string name)
377 std::string MgAdapt::getMeshName()
381 void MgAdapt::setMeshNameOut(std::string name)
385 std::string MgAdapt::getMeshNameOut()
389 void MgAdapt::setFromMedFile(bool mybool)
391 fromMedFile = mybool;
393 bool MgAdapt::isFromMedFile()
397 void MgAdapt::setConstantValue(double cnst)
399 constantValue = cnst;
401 double MgAdapt::getConstantValue() const
403 return constantValue;
406 void MgAdapt::setWorkingDir(std::string dir)
410 std::string MgAdapt::getWorkingDir() const
414 void MgAdapt::setKeepWorkingFiles(bool mybool)
416 toKeepWorkingFiles = mybool;
418 bool MgAdapt::getKeepWorkingFiles()
420 return toKeepWorkingFiles;
422 void MgAdapt::setPrintLogInFile(bool print)
424 printLogInFile = print;
426 bool MgAdapt::getPrintLogInFile()
428 return printLogInFile;
432 bool MgAdapt::setAll()
435 setFromMedFile(data->fromMedFile);
437 checkDirPath(data->myFileInDir);
438 file = data->myFileInDir+data->myMeshFileIn;
440 setMeshName(data->myInMeshName);
441 setMeshNameOut(data->myOutMeshName);
442 checkDirPath(data->myFileOutDir);
443 std::string out = data->myFileOutDir+data->myMeshFileOut;
445 setPublish(data->myPublish);
446 setMeshOutMed(data->myMeshOutMed);
447 setUseLocalMap(data->myUseLocalMap);
448 setUseBackgroundMap(data->myUseBackgroundMap);
449 setUseConstantValue(data->myUseConstantValue);
452 if (useBackgroundMap)
454 checkDirPath(data->myFileSizeMapDir);
455 mapfile = data->myFileSizeMapDir+data->myMeshFileBackground;
456 setFieldName(data->myFieldName);
458 else if (useConstantValue)
460 setConstantValue(data->myConstantValue);
465 setConstantValue(0.0);
466 setFieldName(data->myFieldName);
469 setSizeMapFile(mapfile);
470 if (data->myUseNoTimeStep)
472 else if (data->myUseLastTimeStep)
473 setTimeStepRankLast();
476 setChosenTimeStepRank();
477 setRankTimeStep(data->myTimeStep, data->myRank);
479 /* Advanced options */
480 setWorkingDir(data->myWorkingDir);
481 checkDirPath(data->myWorkingDir);
482 setLogFile(data->myWorkingDir+defaultLogFile());
483 setVerbosityLevel(data->myVerboseLevel);
484 setRemoveOnSuccess(data->myRemoveLogOnSuccess);
485 setPrintLogInFile(data->myPrintLogInFile);
486 setKeepWorkingFiles(data->myKeepFiles);
491 void MgAdapt::checkDirPath(std::string& dirPath)
493 const char lastChar = *dirPath.rbegin();
495 if(lastChar != '\\') dirPath+='\\';
497 if(lastChar != '/') dirPath+='/';
500 //=============================================================================
501 void MgAdapt::setOptionValue(const std::string& optionName,
502 const std::string& optionValue)
503 throw (std::invalid_argument)
505 TOptionValues::iterator op_val = _option2value.find(optionName);
506 if (op_val == _option2value.end())
508 op_val = _customOption2value.find( optionName );
509 _customOption2value[ optionName ] = optionValue;
513 if (op_val->second != optionValue)
516 std::string lowerOptionValue = toLowerStr(optionValue);
517 const char* ptr = lowerOptionValue.c_str();
518 // strip white spaces
519 while (ptr[0] == ' ')
522 while (i != 0 && ptr[i - 1] == ' ')
526 std::string typeName;
531 else if (_charOptions.count(optionName))
533 // do not check strings
535 else if (_doubleOptions.count(optionName))
537 // check if value is double
541 else if (_boolOptions.count(optionName))
543 // check if value is bool
544 toBool(ptr, &typeOk);
549 // check if value is int
551 typeName = "integer";
553 if ( typeOk ) // check some specific values ?
558 std::string msg = "Advanced option '" + optionName + "' = '" + optionValue + "' but must be " + typeName;
559 throw std::invalid_argument(msg);
561 std::string value( ptr, i );
562 if ( _defaultOptionValues[ optionName ] == value ) value.clear();
564 op_val->second = value;
568 //=============================================================================
569 //! Return option value. If isDefault provided, it can be a default value,
570 // then *isDefault == true. If isDefault is not provided, the value will be
571 // empty if it equals a default one.
572 std::string MgAdapt::getOptionValue(const std::string& optionName, bool* isDefault) const
573 throw (std::invalid_argument)
575 TOptionValues::const_iterator op_val = _option2value.find(optionName);
576 if (op_val == _option2value.end())
578 op_val = _customOption2value.find(optionName);
579 if (op_val == _customOption2value.end())
581 std::string msg = "Unknown MG-Adapt option: <" + optionName + ">";
582 throw std::invalid_argument(msg);
585 std::string val = op_val->second;
586 if ( isDefault ) *isDefault = ( val.empty() );
588 if ( val.empty() && isDefault )
590 op_val = _defaultOptionValues.find( optionName );
591 if (op_val != _defaultOptionValues.end()) val = op_val->second;
595 //================================================================================
597 * \brief Converts a string to a real value
599 //================================================================================
601 double MgAdapt::toDbl(const std::string& str, bool* isOk )
602 throw (std::invalid_argument)
604 if ( str.empty() ) throw std::invalid_argument("Empty value provided");
607 double val = strtod(&str[0], &endPtr);
608 bool ok = (&str[0] != endPtr);
610 if ( isOk ) *isOk = ok;
614 std::string msg = "Not a real value:'" + str + "'";
615 throw std::invalid_argument(msg);
619 //================================================================================
621 * \brief Converts a string to a lower
623 //================================================================================
624 std::string MgAdapt::toLowerStr(const std::string& str)
627 for ( size_t i = 0; i <= s.size(); ++i )
628 s[i] = tolower( s[i] );
631 //================================================================================
633 * \brief Converts a string to a bool
635 //================================================================================
637 bool MgAdapt::toBool(const std::string& str, bool* isOk )
638 throw (std::invalid_argument)
641 if ( isOk ) *isOk = true;
643 for ( size_t i = 0; i <= s.size(); ++i )
644 s[i] = tolower( s[i] );
646 if ( s == "1" || s == "true" || s == "active" || s == "yes" )
649 if ( s == "0" || s == "false" || s == "inactive" || s == "no" )
656 std::string msg = "Not a Boolean value:'" + str + "'";
657 throw std::invalid_argument(msg);
661 //================================================================================
663 * \brief Converts a string to a integer value
665 //================================================================================
667 int MgAdapt::toInt(const std::string& str, bool* isOk )
668 throw (std::invalid_argument)
670 if ( str.empty() ) throw std::invalid_argument("Empty value provided");
673 int val = (int)strtol( &str[0], &endPtr, 10);
674 bool ok = (&str[0] != endPtr);
676 if ( isOk ) *isOk = ok;
680 std::string msg = "Not an integer value:'" + str + "'";
681 throw std::invalid_argument(msg);
685 //=============================================================================
686 bool MgAdapt::hasOptionDefined( const std::string& optionName ) const
688 bool isDefault = false;
691 getOptionValue( optionName, &isDefault );
693 catch ( std::invalid_argument )
699 //================================================================================
701 * \brief Return command to run MG-Tetra mesher excluding file prefix (-f)
703 //================================================================================
705 std::string MgAdapt::getCommandToRun(MgAdapt* hyp)
707 return hyp ? hyp->getCommandToRun() : ToComment("error with hypothesis!");
712 int MgAdapt::compute(std::string& errStr)
714 std::string cmd = getCommandToRun();
716 execCmd( cmd.c_str(), err ); // run
720 errStr = ToComment("system(mg-adapt.exe ...) command failed with error: ") << strerror( errno );
724 convertMeshFile(meshFormatOutputMesh, solFormatOutput);
730 void MgAdapt::execCmd( const char* cmd, int& err)
733 std::array <char, 128> buffer;
735 outFileStream fileStream;
738 fileStream.open(logFile);
739 buf = fileStream.rdbuf();
743 buf = std::cout.rdbuf();
745 std::ostream logStream(buf);
747 std::unique_ptr <FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose );
750 throw std::runtime_error("popen() failed!");
752 while(fgets(buffer.data(), buffer.size(), pipe.get()) !=nullptr )
754 logStream<<buffer.data() ;
759 * to delete tmp files .mesh, .sol and if needed
763 void MgAdapt::cleanUp()
767 if(toKeepWorkingFiles)
769 if(removeOnSuccess && printLogInFile)
770 tmpFilesToBeDeleted.push_back(logFile);
772 std::vector< std::string>::iterator it = tmpFilesToBeDeleted.begin();
773 for (; it!=tmpFilesToBeDeleted.end(); ++it)
775 errStr=removeFile(*it, notOk);
778 appendMsgToLogFile(errStr);
784 void MgAdapt::appendMsgToLogFile(std::string& msg)
786 std::ofstream logStream;
787 logStream.open(logFile, std::ofstream::out | std::ofstream::app);
791 //================================================================================
793 * \brief Return command to run MG-Tetra mesher excluding file prefix (-f)
795 //================================================================================
797 std::string MgAdapt::getCommandToRun()
800 || return system command with args and options
804 std::string cmd = getExeName();
805 std::string meshIn(""), sizeMapIn(""), solFileIn("");
806 updateTimeStepRank();
807 convertMedFile(meshIn, solFileIn, sizeMapIn);
808 if (!isFileExist(meshIn) || !isFileExist(solFileIn))
810 errStr = ToComment(" failed to find .mesh or .sol file from converter ")<< strerror( errno );
813 tmpFilesToBeDeleted.push_back(meshIn);
814 tmpFilesToBeDeleted.push_back(solFileIn);
815 if(useBackgroundMap && !isFileExist(sizeMapIn))
817 errStr = ToComment(" failed to find .mesh size map file from converter ")<< strerror( errno );
821 cmd+= " --in "+ meshIn;
822 meshFormatOutputMesh = getFileName()+".mesh";
823 tmpFilesToBeDeleted.push_back(meshFormatOutputMesh);
824 cmd+= " --out "+ meshFormatOutputMesh;
825 if (useLocalMap || useConstantValue) cmd+= " --sizemap "+ solFileIn;
826 else // (useBackgroundMap)
828 cmd+= " --background_mesh "+ sizeMapIn ;
829 cmd+= " --background_sizemap "+ solFileIn;
830 tmpFilesToBeDeleted.push_back(sizeMapIn);
834 //~// constant value TODO
836 /* sizemap file is not adapted in case of only surface adaptation see MeshGems docs */
837 std::string adapOp = "adaptation";
838 std::string adpOpVal = getOptionValue(adapOp);
839 std::string surfaceAdapt = "surface";
840 if(surfaceAdapt != adpOpVal )
842 std::string solFileOut = getFileName()+".sol";
843 cmd+= " --write_sizemap "+ solFileOut;
844 solFormatOutput.push_back(solFileOut);
845 tmpFilesToBeDeleted.push_back(solFileOut);
847 if (verbosityLevel != defaultVerboseLevel())
849 cmd+= " --verbose "+ ToComment(verbosityLevel);
852 std::string option, value;
854 const TOptionValues* options[] = { &_option2value, &_customOption2value };
855 for ( int iOp = 0; iOp < 2; ++iOp )
857 TOptionValues::const_iterator o2v = options[iOp]->begin();
858 for ( ; o2v != options[iOp]->end(); ++o2v )
861 value = getOptionValue( option, &isDefault );
865 if ( value.empty() )//value == NoValue() )
867 if ( _defaultOptionValues.count( option ))
868 continue; // non-custom option with no value
871 if ( strncmp( "no", option.c_str(), 2 ) == 0 ) // options w/o values: --no_*
873 if ( !value.empty() && toBool( value ) == false )
877 if ( option[0] != '-' )
881 cmd += option + " " + value;
893 bool MgAdapt::isFileExist(const std::string& fName)
896 if ( fName.empty() ) return false;
898 boost::system::error_code err;
899 bool res = boost::filesystem::exists( fName, err );
901 return err ? false : res;
903 //=======================================================================
904 //function : defaultMaximumMemory
905 //=======================================================================
909 #elif !defined(__APPLE__)
910 #include <sys/sysinfo.h>
913 double MgAdapt::defaultMaximumMemory()
916 // See http://msdn.microsoft.com/en-us/library/aa366589.aspx
917 MEMORYSTATUSEX statex;
918 statex.dwLength = sizeof (statex);
919 long err = GlobalMemoryStatusEx (&statex);
922 double totMB = (double)statex.ullAvailPhys / 1024. / 1024.;
923 return (double)( 0.7 * totMB );
925 #elif !defined(__APPLE__)
927 long err = sysinfo( &si );
930 long ramMB = si.totalram * si.mem_unit / 1024 / 1024;
931 return ( 0.7 * ramMB );
937 //=======================================================================
938 //function : defaultWorkingDirectory
939 //=======================================================================
941 std::string MgAdapt::defaultWorkingDirectory()
943 TCollection_AsciiString aTmpDir;
945 char *Tmp_dir = getenv("SALOME_TMP_DIR");
952 aTmpDir = TCollection_AsciiString("C:\\");
954 aTmpDir = TCollection_AsciiString("/tmp/");
957 return aTmpDir.ToCString();
959 //================================================================================
961 * \brief Return a unique file name
963 //================================================================================
965 std::string MgAdapt::getFileName() const
967 std::string aTmpDir = workingDir;
968 const char lastChar = *aTmpDir.rbegin();
970 if(lastChar != '\\') aTmpDir+='\\';
972 if(lastChar != '/') aTmpDir+='/';
975 TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
976 aGenericName += "MgAdapt_";
977 aGenericName += getpid();
979 aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
981 return aGenericName.ToCString();
983 //=======================================================================
984 //function : defaultLogFile
985 //=======================================================================
987 std::string MgAdapt::defaultLogFile()
989 std::string alogFile("MG_ADAPT.log");
992 //=======================================================================
993 //function : defaultUseConstantValue
994 //=======================================================================
996 bool MgAdapt::defaultUseConstantValue()
1000 //=======================================================================
1001 //function : defaultUseNoTimeStep
1002 //=======================================================================
1004 bool MgAdapt::defaultUseNoTimeStep()
1008 //=======================================================================
1009 //function : defaultRemoveLogOnSuccess
1010 //=======================================================================
1012 bool MgAdapt::defaultRemoveLogOnSuccess()
1016 //=======================================================================
1017 //function : defaultPrintLogInFile
1018 //=======================================================================
1020 bool MgAdapt::defaultPrintLogInFile()
1024 //=======================================================================
1025 //function : defaultUseChosenTimeStep
1026 //=======================================================================
1028 bool MgAdapt::defaultUseChosenTimeStep()
1032 //=======================================================================
1033 //function : UseLastTimeStep
1034 //=======================================================================
1036 bool MgAdapt::defaultUseLastTimeStep()
1040 //=======================================================================
1041 //function : defaultUseBackgroundMap
1042 //=======================================================================
1044 bool MgAdapt::defaultUseBackgroundMap()
1048 //=======================================================================
1049 //function : defaultKeepFiles
1050 //=======================================================================
1052 bool MgAdapt::defaultKeepFiles()
1056 //=======================================================================
1057 //function : defaultUseLocalMap
1058 //=======================================================================
1060 bool MgAdapt::defaultUseLocalMap()
1064 //=======================================================================
1065 //function : defaultPublish
1066 //=======================================================================
1068 bool MgAdapt::defaultPublish()
1072 //=======================================================================
1073 //function : defaultMeshOutMed
1074 //=======================================================================
1076 bool MgAdapt::defaultMeshOutMed()
1080 //=======================================================================
1081 //function : defaultFromMedFile
1082 //=======================================================================
1084 bool MgAdapt::defaultFromMedFile()
1088 //=======================================================================
1089 //function : defaultVerboseLevel
1090 //=======================================================================
1092 int MgAdapt::defaultVerboseLevel()
1096 std::string MgAdapt::getExeName()
1098 return "mg-adapt.exe";
1100 void MgAdapt::copyMgAdaptHypothesisData( const MgAdaptHypothesisData* from)
1102 data->myFileInDir = from->myFileInDir;
1103 data->myMeshFileIn = from->myMeshFileIn;
1104 data->myMeshFileBackground = from->myMeshFileBackground;
1105 data->myOutMeshName = from->myOutMeshName;
1106 data->myMeshFileOut = from->myMeshFileOut;
1107 data->myFileOutDir = from->myFileOutDir;
1108 data->myFileSizeMapDir = from->myFileSizeMapDir;
1109 data->myFieldName = from->myFieldName;
1110 data->fromMedFile = from->fromMedFile;
1111 data->myPublish = from->myPublish;
1112 data->myMeshOutMed = from->myMeshOutMed;
1113 data->myUseLocalMap = from->myUseLocalMap;
1114 data->myUseBackgroundMap = from->myUseBackgroundMap;
1115 data->myUseConstantValue = from->myUseConstantValue;
1116 data->myConstantValue = from->myConstantValue;
1117 data->myTimeStep = from->myTimeStep;
1118 data->myRank = from->myRank;
1119 data->myUseNoTimeStep = from->myUseNoTimeStep;
1120 data->myUseLastTimeStep = from->myUseLastTimeStep;
1121 data->myUseChosenTimeStep = from->myUseChosenTimeStep;
1122 data->myWorkingDir = from->myWorkingDir;
1123 data->myLogFile = from->myLogFile;
1124 data->myPrintLogInFile = from->myPrintLogInFile;
1125 data->myKeepFiles = from->myKeepFiles;
1126 data->myRemoveLogOnSuccess = from->myRemoveLogOnSuccess;
1127 data->myVerboseLevel = from->myVerboseLevel;
1131 void MgAdapt::convertMedFile(std::string& meshFormatMeshFileName, std::string& solFormatFieldFileName, std::string& meshFormatsizeMapFile)
1133 std::vector<std::string> fieldFileNames;
1134 MEDCoupling::MeshFormatWriter writer;
1135 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = MEDCoupling::MEDFileData::New(medFileIn);
1136 MEDCoupling::MEDFileMeshes* meshes = mfd->getMeshes();
1137 MEDCoupling::MEDFileMesh* fileMesh = meshes->getMeshAtPos(0); // ok only one mesh in file!
1138 if (meshNameOut =="")
1139 meshNameOut = fileMesh->getName();
1140 storeGroupsAndFams(fileMesh);
1142 MEDCoupling::MCAuto<MEDCoupling::MEDFileFields> fields = MEDCoupling::MEDFileFields::New();
1143 solFormatFieldFileName = getFileName();
1144 solFormatFieldFileName+=".sol";
1145 fieldFileNames.push_back(solFormatFieldFileName);
1147 if (useBackgroundMap)
1149 meshFormatsizeMapFile = getFileName();
1150 meshFormatsizeMapFile += ".mesh";
1151 buildBackGroundMeshAndSolFiles(fieldFileNames, meshFormatsizeMapFile);
1153 else if(useLocalMap)
1155 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeFieldMultiTS> fts = dynamic_cast<MEDCoupling::MEDFileFieldMultiTS *>( mfd->getFields()->getFieldWithName(fieldName) );
1156 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeField1TS> f = fts->getTimeStep(timeStep, rank);
1157 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> tmFts = MEDCoupling::MEDFileFieldMultiTS::New();
1158 tmFts->pushBackTimeStep(f);
1160 fields->pushField(tmFts);
1162 writer.setFieldFileNames( fieldFileNames);
1166 MEDCoupling::MCAuto<MEDCoupling::MEDCouplingMesh> mesh = fileMesh->getMeshAtLevel(1); // nodes mesh
1167 MEDCoupling::MCAuto<MEDCoupling::MEDCouplingUMesh> umesh = mesh->buildUnstructured(); // nodes mesh
1168 int dim = umesh->getSpaceDimension();
1169 int version = sizeof(double) < 8 ? 1 : 2;
1170 mcIdType nbNodes = umesh->getNumberOfNodes();
1171 buildConstantSizeMapSolFile(solFormatFieldFileName, dim, version, nbNodes);
1174 mfd->setFields( fields );
1175 meshFormatMeshFileName = getFileName();
1176 meshFormatMeshFileName+=".mesh";
1177 writer.setMeshFileName(meshFormatMeshFileName);
1178 writer.setMEDFileDS( mfd);
1183 void MgAdapt::convertMeshFile(std::string& meshFormatIn, std::vector< std::string>& solFieldFileNames) const
1185 MEDCoupling::MeshFormatReader reader(meshFormatIn, solFieldFileNames);
1187 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = reader.loadInMedFileDS();
1189 MEDCoupling::MEDFileMeshes* meshes = mfd->getMeshes();
1190 MEDCoupling::MEDFileMesh* fileMesh = meshes->getMeshAtPos(0); // ok only one mesh in file!
1191 fileMesh->setName(meshNameOut);
1192 restoreGroupsAndFams(fileMesh);
1193 mfd->write(medFileOut, 2);
1196 void MgAdapt::storeGroupsAndFams(MEDCoupling::MEDFileMesh* fileMesh)
1198 storefams(fileMesh);
1199 storeGroups(fileMesh);
1202 void MgAdapt::restoreGroupsAndFams(MEDCoupling::MEDFileMesh* fileMesh) const
1204 restorefams(fileMesh);
1205 restoreGroups(fileMesh);
1207 void MgAdapt::storeGroups(MEDCoupling::MEDFileMesh* fileMesh)
1209 std::map<std::string, std::vector<std::string> > grpFams = fileMesh->getGroupInfo();
1210 std::map<std::string, std::vector<std::string> >::iterator g2ff = grpFams.begin();
1212 for ( ; g2ff != grpFams.end(); ++g2ff )
1214 std::string groupName = g2ff->first;
1215 std::vector<std::string> famNames = g2ff->second;
1217 if ( famNames.empty() ) continue;
1219 std::vector< mcIdType> famListId;
1220 for ( size_t i = 0; i < famNames.size(); ++i )
1222 famListId.push_back( fileMesh->getFamilyId( famNames[i].c_str() ) );
1224 group grp(groupName, famListId, famNames);
1225 groupVec.push_back(grp);
1229 void MgAdapt::storefams(MEDCoupling::MEDFileMesh* fileMesh)
1231 std::map<std::string, mcIdType> grpFams = fileMesh->getFamilyInfo();
1232 std::map<std::string, mcIdType >::iterator f = grpFams.begin();
1234 for ( ; f != grpFams.end(); ++f )
1236 if(!f->second) continue; // FAMILLE_ZERO
1237 family fs(f->first, f->second);
1238 famVec.push_back(fs);
1243 void MgAdapt::restorefams(MEDCoupling::MEDFileMesh* fileMesh) const
1245 std::vector<family>::const_iterator fIt = famVec.begin();
1247 for (; fIt!=famVec.end(); ++fIt)
1251 std::string givenFamNameFromMeshGemConverter = fileMesh->getFamilyNameGivenId( std::abs(fIt->_famId) );
1252 fileMesh->changeFamilyId(std::abs(fIt->_famId), fIt->_famId);
1253 fileMesh->changeFamilyName(givenFamNameFromMeshGemConverter, fIt->_famName);
1255 catch (const std::exception& e)
1257 std::cerr<<e.what();
1262 void MgAdapt::restoreGroups(MEDCoupling::MEDFileMesh* fileMesh) const
1264 std::map<std::string, std::vector<std::string> > info;
1265 std::vector <group>::const_iterator grpFams = groupVec.begin();
1267 for (; grpFams!=groupVec.end(); ++grpFams)
1269 info.insert(std::pair <std::string, std::vector<std::string> > (grpFams->_name, grpFams->_famNames) );
1272 fileMesh->setGroupInfo(info);
1275 void MgAdapt::buildConstantSizeMapSolFile(const std::string& solFormatFieldFileName, const int dim, const int version, const mcIdType nbNodes) const
1277 MeshFormat::Localizer loc;
1278 MeshFormat::MeshFormatParser writer;
1279 int fileId = writer.GmfOpenMesh( solFormatFieldFileName.c_str(), GmfWrite, version, dim);
1280 int typTab[] = {GmfSca};
1281 writer.GmfSetKwd(fileId, MeshFormat::GmfSolAtVertices, (int)nbNodes, 1, typTab);
1282 for (mcIdType i = 0; i<nbNodes; i++)
1284 double valTab[1] = {constantValue};
1285 writer.GmfSetLin( fileId, MeshFormat::GmfSolAtVertices, valTab);
1287 writer.GmfCloseMesh(fileId);
1290 void MgAdapt::buildBackGroundMeshAndSolFiles(const std::vector<std::string>& fieldFileNames, const std::string& meshFormatsizeMapFile) const
1292 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> tmpMfd = MEDCoupling::MEDFileData::New(sizeMapFile);
1293 MEDCoupling::MEDFileFields* tmpFields = tmpMfd->getFields();
1294 MEDCoupling::MEDFileAnyTypeFieldMultiTS* fts = tmpFields->getFieldWithName(fieldName);
1295 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> fts1 = dynamic_cast<MEDCoupling::MEDFileFieldMultiTS *>(fts);
1296 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeField1TS> f = fts1->getTimeStep(timeStep, rank);
1297 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> tmFts = MEDCoupling::MEDFileFieldMultiTS::New();
1298 tmFts->pushBackTimeStep(f);
1300 MEDCoupling::MCAuto<MEDCoupling::MEDFileFields> tmp_fields = MEDCoupling::MEDFileFields::New();
1301 tmp_fields->pushField(tmFts);
1303 tmpMfd->setFields( tmp_fields );
1304 MEDCoupling::MeshFormatWriter tmpWriter;
1305 tmpWriter.setMeshFileName(meshFormatsizeMapFile);
1306 tmpWriter.setFieldFileNames( fieldFileNames);
1307 tmpWriter.setMEDFileDS(tmpMfd);
1310 // =======================================================================
1311 med_idt MgAdapt::openMedFile(const std::string aFile)
1312 // =======================================================================
1313 // renvoie le medId associe au fichier Med apres ouverture
1315 med_idt medIdt = MEDfileOpen(aFile.c_str(),MED_ACC_RDONLY);
1318 //~addMessage( ToComment(" error: Can't open ") << aFile, /*fatal=*/true );
1324 MgAdapt::Status MgAdapt::addMessage(const std::string& msg,
1325 const bool isFatal/*=false*/)
1328 _myErrorMessages.clear(); // warnings are useless if a fatal error encounters
1330 _myErrorMessages.push_back( msg );
1334 std::cout << msg << std::endl;
1336 return ( _myStatus = isFatal ? MgAdapt::DRS_FAIL : MgAdapt::DRS_WARN_SKIP_ELEM );
1339 // =======================================================================
1340 void MgAdapt::getTimeStepInfos(std::string aFile, med_int& numdt, med_int& numit)
1341 // =======================================================================
1343 // Il faut voir si plusieurs maillages
1349 // Ouverture du fichier
1350 //~SCRUTE(aFile.toStdString());
1351 medIdt = openMedFile(aFile);
1352 if ( medIdt < 0 ) return ;
1353 // Lecture du nombre de champs
1354 med_int ncha = MEDnField(medIdt) ;
1357 //~addMessage( ToComment(" error: there is no field in ") << aFile, /*fatal=*/true );
1360 // Lecture des caracteristiques du champs
1362 // Lecture du type du champ, des noms des composantes et du nom de l'unite
1363 char nomcha [MED_NAME_SIZE+1];
1364 strcpy(nomcha, fieldName.c_str());
1365 // Lecture du nombre de composantes
1366 med_int ncomp = MEDfieldnComponentByName(medIdt, nomcha);
1367 char meshname[MED_NAME_SIZE+1];
1368 char * comp = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
1369 char * unit = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
1370 char dtunit[MED_SNAME_SIZE+1];
1372 med_field_type typcha;
1374 erreur = MEDfieldInfoByName (medIdt, nomcha, meshname,&local,&typcha,comp,unit,dtunit, &nbofcstp);
1379 //~addMessage( ToComment(" error: error while reading field ") << nomcha << " in file " << aFile , /*fatal=*/true );
1384 med_int tmp_numdt, tmp_numit;
1386 //~med_int step = data->myUseLastTimeStep ? nbofcstp : data->myTimeStep+1;
1387 //~myPrint("step ", step);
1388 erreur = MEDfieldComputingStepInfo ( medIdt, nomcha, 1, &numdt, &numit, &dt );
1389 for(med_int step = 1; step <= nbofcstp; step++ )
1391 erreur = MEDfieldComputingStepInfo ( medIdt, nomcha, step, &tmp_numdt, &tmp_numit, &dt );
1392 if(tmp_numdt > numdt)
1400 //~addMessage( ToComment(" error: error while reading field ") << nomcha << "step (numdt, numit) = " <<"("<< numdt<< ", " \
1401 numit<< ")" <<" in file " << aFile , /*fatal=*/true );
1405 // Fermeture du fichier
1406 if ( medIdt > 0 ) MEDfileClose(medIdt);
1410 void MgAdapt::updateTimeStepRank()
1415 if (myUseNoTimeStep)
1419 setRankTimeStep((int)tmst, (int)arank);
1421 else if (myUseLastTimeStep)
1423 std::string fieldFile = useBackgroundMap ? sizeMapFile : medFileIn;
1424 getTimeStepInfos(fieldFile, tmst, arank);
1425 setRankTimeStep((int)tmst, (int)arank);