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 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 : ")
48 else errStr= ToComment("\n file : ")<< fileName << " succesfully deleted! \n ";
52 std::string remove_extension(const std::string& filename) {
53 size_t lastdot = filename.find_last_of(".");
54 if (lastdot == std::string::npos) return filename;
55 return filename.substr(0, lastdot);
59 struct GET_DEFAULT // struct used to get default value from GetOptionValue()
68 //----------------------------------------------------------------------------------------
71 data = new MgAdaptHypothesisData();
72 data->myInMeshName = "";
73 data->fromMedFile = defaultFromMedFile();
74 data->myFileInDir = defaultWorkingDirectory();
75 data->myMeshFileIn = "";
76 data->myFileOutDir = defaultWorkingDirectory();
77 data->myOutMeshName = "";
78 data->myMeshFileOut = "";
79 data->myMeshOutMed = defaultMeshOutMed();
80 data->myPublish = defaultPublish();
81 data->myUseLocalMap = defaultUseLocalMap();
82 data->myUseBackgroundMap = defaultUseBackgroundMap();
83 data->myFileSizeMapDir = defaultWorkingDirectory();
84 data->myMeshFileBackground = "";
85 data->myUseConstantValue = defaultUseConstantValue();
86 data->myConstantValue = 0.0;
87 data->myFieldName = "";
88 data->myUseNoTimeStep = defaultUseNoTimeStep();
89 data->myUseLastTimeStep = defaultUseLastTimeStep();
90 data->myUseChosenTimeStep = defaultUseChosenTimeStep();
91 data->myTimeStep = -2;
93 data->myWorkingDir = defaultWorkingDirectory();
94 data->myLogFile = defaultLogFile();
95 data->myVerboseLevel = defaultVerboseLevel();
96 data->myPrintLogInFile = defaultPrintLogInFile();
97 data->myKeepFiles = defaultKeepFiles();
98 data->myRemoveLogOnSuccess = defaultRemoveLogOnSuccess();
103 MgAdapt::MgAdapt(MgAdaptHypothesisData* myData)
105 data = new MgAdaptHypothesisData();
110 MgAdapt::MgAdapt( const MgAdapt& copy)
113 data = new MgAdaptHypothesisData();
114 MgAdaptHypothesisData *copyData = copy.getData();
115 copyMgAdaptHypothesisData(copyData);
118 this->_option2value = copy._option2value;
119 this->_customOption2value = copy._customOption2value;
120 this->_defaultOptionValues = copy._defaultOptionValues;
121 this->_doubleOptions = copy._doubleOptions;
122 this->_charOptions = copy._charOptions;
123 this->_boolOptions = copy._boolOptions;
129 //-----------------------------------------------------------------------------------------
136 void MgAdapt::buildModel()
139 const char* boolOptionNames[] = { "compute_ridges", // yes
142 // const char* intOptionNames[] = { "max_number_of_errors_printed", // 1
143 // "max_number_of_threads", // 4
146 const char* doubleOptionNames[] = { "max_memory", // 0
149 const char* charOptionNames[] = { "components", // "yes"
150 "adaptation", // both
155 while (boolOptionNames[i][0])
157 _boolOptions.insert( boolOptionNames[i] );
158 _option2value[boolOptionNames[i++]].clear();
161 // while (intOptionNames[i][0])
162 // _option2value[intOptionNames[i++]].clear();
165 while (doubleOptionNames[i][0]) {
166 _doubleOptions.insert(doubleOptionNames[i]);
167 _option2value[doubleOptionNames[i++]].clear();
170 while (charOptionNames[i][0]) {
171 _charOptions.insert(charOptionNames[i]);
172 _option2value[charOptionNames[i++]].clear();
175 // default values to be used while MG-Adapt
177 _defaultOptionValues["adaptation" ] = "both";
178 _defaultOptionValues["components" ] = "outside components";
179 _defaultOptionValues["compute_ridges" ] = "yes";
180 _defaultOptionValues["max_memory" ] = ToComment(defaultMaximumMemory());
183 //=============================================================================
184 TOptionValues MgAdapt::getOptionValues() const
187 TOptionValues::const_iterator op_val = _option2value.begin();
188 for ( ; op_val != _option2value.end(); ++op_val )
189 vals.insert( make_pair( op_val->first, getOptionValue( op_val->first, GET_DEFAULT() )));
194 std::vector <std::string> MgAdapt::getOptionValuesStrVec() const
196 std::vector <std::string> vals;
197 TOptionValues::const_iterator op_val = _option2value.begin();
198 for ( ; op_val != _option2value.end(); ++op_val )
199 vals.push_back(op_val->first+":"+getOptionValue( op_val->first, GET_DEFAULT() ));
204 std::vector <std::string> MgAdapt::getCustomOptionValuesStrVec() const
206 std::vector <std::string> vals;
207 TOptionValues::const_iterator op_val;
208 for ( op_val = _customOption2value.begin(); op_val != _customOption2value.end(); ++op_val )
210 vals.push_back(op_val->first+":"+getOptionValue( op_val->first, GET_DEFAULT() ));
214 const TOptionValues& MgAdapt::getCustomOptionValues() const
216 return _customOption2value;
218 void MgAdapt::setData(MgAdaptHypothesisData* myData)
220 copyMgAdaptHypothesisData(myData);
223 MgAdaptHypothesisData* MgAdapt::getData() const
227 void MgAdapt::setMedFileIn(std::string fileName)
229 medFileIn = fileName;
230 if (medFileOut == "") // default MED file Out
231 medFileOut = remove_extension( fileName )+ ".adapt.med";
234 std::string MgAdapt::getMedFileIn()
239 void MgAdapt::setMedFileOut(std::string fileOut)
241 medFileOut = fileOut;
244 std::string MgAdapt::getMedFileOut()
248 void MgAdapt::setMeshOutMed(bool mybool)
252 bool MgAdapt::getMeshOutMed()
256 void MgAdapt::setPublish(bool mybool)
260 bool MgAdapt::getPublish()
264 void MgAdapt::setFieldName(std::string myFieldName)
266 fieldName = myFieldName;
268 std::string MgAdapt::getFieldName()
272 void MgAdapt::setTimeStep(int time)
276 int MgAdapt::getTimeStep() const
281 void MgAdapt::setRankTimeStep(int time, int myRank)
287 int MgAdapt::getRank()
291 void MgAdapt::setTimeStepRankLast()
293 myUseLastTimeStep = true;
294 myUseChosenTimeStep = false;
295 myUseNoTimeStep = false;
296 //~med_int aRank, tmst;
297 //~std::string fieldFile = useBackgroundMap ? sizeMapFile : medFileIn;
298 //~getTimeStepInfos(fieldFile, tmst, aRank);
299 //~setRankTimeStep((int) tmst, (int) aRank);
301 void MgAdapt::setNoTimeStep()
303 myUseLastTimeStep = false;
304 myUseChosenTimeStep = false;
305 myUseNoTimeStep = true;
306 //~int aRank = (int)MED_NO_IT;
307 //~int tmst = (int)MED_NO_DT ;
308 //~setRankTimeStep(tmst, aRank);
310 void MgAdapt::setChosenTimeStepRank()
312 myUseLastTimeStep = false;
313 myUseChosenTimeStep = true;
314 myUseNoTimeStep = false;
315 //~int aRank = (int)MED_NO_IT;
316 //~int tmst = (int)MED_NO_DT ;
317 //~setRankTimeStep(tmst, aRank);
319 void MgAdapt::setUseLocalMap(bool myLocal)
321 useLocalMap = myLocal;
324 bool MgAdapt::getUseLocalMap()
329 void MgAdapt::setUseBackgroundMap(bool bckg)
331 useBackgroundMap = bckg;
334 bool MgAdapt::getUseBackgroundMap()
336 return useBackgroundMap;
339 void MgAdapt::setUseConstantValue(bool cnst)
341 useConstantValue = cnst;
343 bool MgAdapt::getUseConstantValue()
345 return useConstantValue;
347 void MgAdapt::setLogFile(std::string myLogFile)
351 std::string MgAdapt::getLogFile()
355 void MgAdapt::setVerbosityLevel(int verboLevel)
357 verbosityLevel = verboLevel;
359 int MgAdapt::getVerbosityLevel()
361 return verbosityLevel;
363 void MgAdapt::setRemoveOnSuccess(bool rmons)
365 removeOnSuccess = rmons;
367 bool MgAdapt::getRemoveOnSuccess()
369 return removeOnSuccess;
371 void MgAdapt::setSizeMapFile(std::string mapFile)
373 sizeMapFile = mapFile;
375 std::string MgAdapt::getSizeMapFile()
380 void MgAdapt::setMeshName(std::string name)
384 std::string MgAdapt::getMeshName()
388 void MgAdapt::setMeshNameOut(std::string name)
392 std::string MgAdapt::getMeshNameOut()
396 void MgAdapt::setFromMedFile(bool mybool)
398 fromMedFile = mybool;
400 bool MgAdapt::isFromMedFile()
404 void MgAdapt::setConstantValue(double cnst)
406 constantValue = cnst;
408 double MgAdapt::getConstantValue() const
410 return constantValue;
413 void MgAdapt::setWorkingDir(std::string dir)
417 std::string MgAdapt::getWorkingDir() const
421 void MgAdapt::setKeepWorkingFiles(bool mybool)
423 toKeepWorkingFiles = mybool;
425 bool MgAdapt::getKeepWorkingFiles()
427 return toKeepWorkingFiles;
429 void MgAdapt::setPrintLogInFile(bool print)
431 printLogInFile = print;
433 bool MgAdapt::getPrintLogInFile()
435 return printLogInFile;
439 bool MgAdapt::setAll()
442 setFromMedFile(data->fromMedFile);
444 checkDirPath(data->myFileInDir);
445 file = data->myFileInDir+data->myMeshFileIn;
447 setMeshName(data->myInMeshName);
448 setMeshNameOut(data->myOutMeshName);
449 checkDirPath(data->myFileOutDir);
450 std::string out = data->myFileOutDir+data->myMeshFileOut;
452 setPublish(data->myPublish);
453 setMeshOutMed(data->myMeshOutMed);
454 setUseLocalMap(data->myUseLocalMap);
455 setUseBackgroundMap(data->myUseBackgroundMap);
456 setUseConstantValue(data->myUseConstantValue);
459 if (useBackgroundMap)
462 checkDirPath(data->myFileSizeMapDir);
463 mapfile = data->myFileSizeMapDir+data->myMeshFileBackground;
464 setFieldName(data->myFieldName);
466 else if (useConstantValue)
468 setConstantValue(data->myConstantValue);
473 setConstantValue(0.0);
474 setFieldName(data->myFieldName);
478 setSizeMapFile(mapfile);
479 if (data->myUseNoTimeStep)
481 else if (data->myUseLastTimeStep)
482 setTimeStepRankLast();
485 setChosenTimeStepRank();
486 setRankTimeStep(data->myTimeStep, data->myRank);
488 /* Advanced options */
489 setWorkingDir(data->myWorkingDir);
490 checkDirPath(data->myWorkingDir);
491 setLogFile(data->myWorkingDir+defaultLogFile());
492 setVerbosityLevel(data->myVerboseLevel);
493 setRemoveOnSuccess(data->myRemoveLogOnSuccess);
494 setPrintLogInFile(data->myPrintLogInFile);
495 setKeepWorkingFiles(data->myKeepFiles);
500 void MgAdapt::checkDirPath(std::string& dirPath)
502 const char lastChar = *dirPath.rbegin();
504 if(lastChar != '\\') dirPath+='\\';
506 if(lastChar != '/') dirPath+='/';
509 //=============================================================================
510 void MgAdapt::setOptionValue(const std::string& optionName,
511 const std::string& optionValue)
512 throw (std::invalid_argument)
514 TOptionValues::iterator op_val = _option2value.find(optionName);
515 if (op_val == _option2value.end())
517 op_val = _customOption2value.find( optionName );
518 _customOption2value[ optionName ] = optionValue;
522 if (op_val->second != optionValue)
525 std::string lowerOptionValue = toLowerStr(optionValue);
526 const char* ptr = lowerOptionValue.c_str();
527 // strip white spaces
528 while (ptr[0] == ' ')
531 while (i != 0 && ptr[i - 1] == ' ')
535 std::string typeName;
538 } else if (_charOptions.count(optionName)) {
539 // do not check strings
540 } else if (_doubleOptions.count(optionName)) {
541 // check if value is double
544 } else if (_boolOptions.count(optionName)) {
545 // check if value is bool
546 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 )
566 op_val->second = value;
570 //=============================================================================
571 //! Return option value. If isDefault provided, it can be a default value,
572 // then *isDefault == true. If isDefault is not provided, the value will be
573 // empty if it equals a default one.
574 std::string MgAdapt::getOptionValue(const std::string& optionName, bool* isDefault) const
575 throw (std::invalid_argument)
577 TOptionValues::const_iterator op_val = _option2value.find(optionName);
578 if (op_val == _option2value.end())
580 op_val = _customOption2value.find(optionName);
581 if (op_val == _customOption2value.end())
583 std::string msg = "Unknown MG-Adapt option: <" + optionName + ">";
584 throw std::invalid_argument(msg);
587 std::string val = op_val->second;
588 if ( isDefault ) *isDefault = ( val.empty() );
590 if ( val.empty() && isDefault )
592 op_val = _defaultOptionValues.find( optionName );
593 if (op_val != _defaultOptionValues.end())
594 val = op_val->second;
598 //================================================================================
600 * \brief Converts a string to a real value
602 //================================================================================
604 double MgAdapt::toDbl(const std::string& str, bool* isOk )
605 throw (std::invalid_argument)
607 if ( str.empty() ) throw std::invalid_argument("Empty value provided");
610 double val = strtod(&str[0], &endPtr);
611 bool ok = (&str[0] != endPtr);
613 if ( isOk ) *isOk = ok;
617 std::string msg = "Not a real value:'" + str + "'";
618 throw std::invalid_argument(msg);
622 //================================================================================
624 * \brief Converts a string to a lower
626 //================================================================================
627 std::string MgAdapt::toLowerStr(const std::string& str)
630 for ( size_t i = 0; i <= s.size(); ++i )
631 s[i] = tolower( s[i] );
634 //================================================================================
636 * \brief Converts a string to a bool
638 //================================================================================
640 bool MgAdapt::toBool(const std::string& str, bool* isOk )
641 throw (std::invalid_argument)
644 if ( isOk ) *isOk = true;
646 for ( size_t i = 0; i <= s.size(); ++i )
647 s[i] = tolower( s[i] );
649 if ( s == "1" || s == "true" || s == "active" || s == "yes" )
652 if ( s == "0" || s == "false" || s == "inactive" || s == "no" )
658 std::string msg = "Not a Boolean value:'" + str + "'";
659 throw std::invalid_argument(msg);
663 //================================================================================
665 * \brief Converts a string to a integer value
667 //================================================================================
669 int MgAdapt::toInt(const std::string& str, bool* isOk )
670 throw (std::invalid_argument)
672 if ( str.empty() ) throw std::invalid_argument("Empty value provided");
675 int val = (int)strtol( &str[0], &endPtr, 10);
676 bool ok = (&str[0] != endPtr);
678 if ( isOk ) *isOk = ok;
682 std::string msg = "Not an integer value:'" + str + "'";
683 throw std::invalid_argument(msg);
687 //=============================================================================
688 bool MgAdapt::hasOptionDefined( const std::string& optionName ) const
690 bool isDefault = false;
693 getOptionValue( optionName, &isDefault );
695 catch ( std::invalid_argument )
701 //================================================================================
703 * \brief Return command to run MG-Tetra mesher excluding file prefix (-f)
705 //================================================================================
707 std::string MgAdapt::getCommandToRun(MgAdapt* hyp)
709 return hyp ? hyp->getCommandToRun() : ToComment("error with hypothesis!");
714 int MgAdapt::compute(std::string& errStr)
716 std::string cmd = getCommandToRun();
718 execCmd( cmd.c_str(), err ); // run
722 errStr = ToComment("system(mg-adapt.exe ...) command failed with error: ")
723 << strerror( errno );
727 convertMeshFile(meshFormatOutputMesh, solFormatOutput);
733 void MgAdapt::execCmd( const char* cmd, int& err)
736 std::array <char, 128> buffer;
738 outFileStream fileStream;
741 fileStream.open(logFile);
742 buf = fileStream.rdbuf();
746 buf = std::cout.rdbuf();
748 std::ostream logStream(buf);
750 std::unique_ptr <FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose );
753 throw std::runtime_error("popen() failed!");
755 while(fgets(buffer.data(), buffer.size(), pipe.get()) !=nullptr )
757 logStream<<buffer.data() ;
762 void MgAdapt::cleanUp()
766 if(removeOnSuccess) tmpFilesToBeDeleted.push_back(logFile);
768 std::vector< std::string>::iterator it = tmpFilesToBeDeleted.begin();
769 for (; it!=tmpFilesToBeDeleted.end(); ++it)
771 errStr=removeFile(*it, notOk);
774 appendMsgToLogFile(errStr);
780 void MgAdapt::appendMsgToLogFile(std::string& msg)
782 std::ofstream logStream;
783 logStream.open(logFile, std::ofstream::out | std::ofstream::app);
787 //================================================================================
789 * \brief Return command to run MG-Tetra mesher excluding file prefix (-f)
791 //================================================================================
793 std::string MgAdapt::getCommandToRun()
796 || return system command with args and options
800 std::string cmd = getExeName();
801 std::string meshIn(""), sizeMapIn(""), solFileIn("");
802 updateTimeStepRank();
803 convertMedFile(meshIn, solFileIn, sizeMapIn);
804 if (!isFileExist(meshIn) || !isFileExist(solFileIn))
806 errStr = ToComment(" failed to find .mesh or .sol file from converter ")<< strerror( errno );
809 tmpFilesToBeDeleted.push_back(meshIn);
810 tmpFilesToBeDeleted.push_back(solFileIn);
811 if(useBackgroundMap && !isFileExist(sizeMapIn))
814 errStr = ToComment(" failed to find .mesh size map file from converter ")<< strerror( errno );
820 cmd+= " --in "+ meshIn;
821 meshFormatOutputMesh = getFileName()+".mesh";
822 cmd+= " --out "+ meshFormatOutputMesh;
823 if (useLocalMap || useConstantValue) cmd+= " --sizemap "+ solFileIn;
824 else // (useBackgroundMap)
826 cmd+= " --background_mesh "+ sizeMapIn ;
827 cmd+= " --background_sizemap "+ solFileIn;
828 tmpFilesToBeDeleted.push_back(sizeMapIn);
832 //~// constant value TODO
834 /* sizemap file is not adapted in case of only surface adaptation see MeshGems docs */
835 std::string adapOp = "adaptation";
836 std::string adpOpVal = getOptionValue(adapOp);
837 std::string surfaceAdapt = "surface";
838 if(surfaceAdapt != adpOpVal )
840 std::string solFileOut = getFileName()+".sol";
841 cmd+= " --write_sizemap "+ solFileOut;
842 solFormatOutput.push_back(solFileOut);
844 if (verbosityLevel != defaultVerboseLevel())
847 cmd+= " --verbose "+ ToComment(verbosityLevel);
850 std::string option, value;
852 const TOptionValues* options[] = { &_option2value, &_customOption2value };
853 for ( int iOp = 0; iOp < 2; ++iOp )
855 TOptionValues::const_iterator o2v = options[iOp]->begin();
856 for ( ; o2v != options[iOp]->end(); ++o2v )
859 value = getOptionValue( option, &isDefault );
863 if ( value.empty() )//value == NoValue() )
865 if ( _defaultOptionValues.count( option ))
866 continue; // non-custom option with no value
869 if ( strncmp( "no", option.c_str(), 2 ) == 0 ) // options w/o values: --no_*
871 if ( !value.empty() && toBool( value ) == false )
875 if ( option[0] != '-' )
879 cmd += option + " " + value;
892 bool MgAdapt::isFileExist(const std::string& fName)
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);
921 double totMB = (double)statex.ullAvailPhys / 1024. / 1024.;
922 return (double)( 0.7 * totMB );
924 #elif !defined(__APPLE__)
926 long err = sysinfo( &si );
928 long ramMB = si.totalram * si.mem_unit / 1024 / 1024;
929 return ( 0.7 * ramMB );
936 //=======================================================================
937 //function : defaultWorkingDirectory
938 //=======================================================================
940 std::string MgAdapt::defaultWorkingDirectory()
942 TCollection_AsciiString aTmpDir;
944 char *Tmp_dir = getenv("SALOME_TMP_DIR");
945 if(Tmp_dir != NULL) {
950 aTmpDir = TCollection_AsciiString("C:\\");
952 aTmpDir = TCollection_AsciiString("/tmp/");
955 return aTmpDir.ToCString();
957 //================================================================================
959 * \brief Return a unique file name
961 //================================================================================
963 std::string MgAdapt::getFileName() const
965 std::string aTmpDir = workingDir;
966 const char lastChar = *aTmpDir.rbegin();
968 if(lastChar != '\\') aTmpDir+='\\';
970 if(lastChar != '/') aTmpDir+='/';
973 TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
974 aGenericName += "MgAdapt_";
975 aGenericName += getpid();
977 aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
979 return aGenericName.ToCString();
981 //=======================================================================
982 //function : defaultLogFile
983 //=======================================================================
985 std::string MgAdapt::defaultLogFile()
987 std::string alogFile("MG_ADAPT.log");
990 //=======================================================================
991 //function : defaultUseConstantValue
992 //=======================================================================
994 bool MgAdapt::defaultUseConstantValue()
998 //=======================================================================
999 //function : defaultUseNoTimeStep
1000 //=======================================================================
1002 bool MgAdapt::defaultUseNoTimeStep()
1006 //=======================================================================
1007 //function : defaultRemoveLogOnSuccess
1008 //=======================================================================
1010 bool MgAdapt::defaultRemoveLogOnSuccess()
1014 //=======================================================================
1015 //function : defaultPrintLogInFile
1016 //=======================================================================
1018 bool MgAdapt::defaultPrintLogInFile()
1022 //=======================================================================
1023 //function : defaultUseChosenTimeStep
1024 //=======================================================================
1026 bool MgAdapt::defaultUseChosenTimeStep()
1030 //=======================================================================
1031 //function : UseLastTimeStep
1032 //=======================================================================
1034 bool MgAdapt::defaultUseLastTimeStep()
1038 //=======================================================================
1039 //function : defaultUseBackgroundMap
1040 //=======================================================================
1042 bool MgAdapt::defaultUseBackgroundMap()
1046 //=======================================================================
1047 //function : defaultKeepFiles
1048 //=======================================================================
1050 bool MgAdapt::defaultKeepFiles()
1054 //=======================================================================
1055 //function : defaultUseLocalMap
1056 //=======================================================================
1058 bool MgAdapt::defaultUseLocalMap()
1062 //=======================================================================
1063 //function : defaultPublish
1064 //=======================================================================
1066 bool MgAdapt::defaultPublish()
1070 //=======================================================================
1071 //function : defaultMeshOutMed
1072 //=======================================================================
1074 bool MgAdapt::defaultMeshOutMed()
1078 //=======================================================================
1079 //function : defaultFromMedFile
1080 //=======================================================================
1082 bool MgAdapt::defaultFromMedFile()
1086 //=======================================================================
1087 //function : defaultVerboseLevel
1088 //=======================================================================
1090 int MgAdapt::defaultVerboseLevel()
1094 std::string MgAdapt::getExeName()
1096 return "mg-adapt.exe";
1098 void MgAdapt::copyMgAdaptHypothesisData( const MgAdaptHypothesisData* from)
1101 data->myFileInDir = from->myFileInDir;
1102 data->myMeshFileIn = from->myMeshFileIn;
1103 data->myMeshFileBackground = from->myMeshFileBackground;
1104 data->myOutMeshName = from->myOutMeshName;
1105 data->myMeshFileOut = from->myMeshFileOut;
1106 data->myFileOutDir = from->myFileOutDir;
1107 data->myFileSizeMapDir = from->myFileSizeMapDir;
1108 data->myFieldName = from->myFieldName;
1109 data->fromMedFile = from->fromMedFile;
1110 data->myPublish = from->myPublish;
1111 data->myMeshOutMed = from->myMeshOutMed;
1112 data->myUseLocalMap = from->myUseLocalMap;
1113 data->myUseBackgroundMap = from->myUseBackgroundMap;
1114 data->myUseConstantValue = from->myUseConstantValue;
1115 data->myConstantValue = from->myConstantValue;
1116 data->myTimeStep = from->myTimeStep;
1117 data->myRank = from->myRank;
1118 data->myUseNoTimeStep = from->myUseNoTimeStep;
1119 data->myUseLastTimeStep = from->myUseLastTimeStep;
1120 data->myUseChosenTimeStep = from->myUseChosenTimeStep;
1121 data->myWorkingDir = from->myWorkingDir;
1122 data->myLogFile = from->myLogFile;
1123 data->myPrintLogInFile = from->myPrintLogInFile;
1124 data->myKeepFiles = from->myKeepFiles;
1125 data->myRemoveLogOnSuccess = from->myRemoveLogOnSuccess;
1126 data->myVerboseLevel = from->myVerboseLevel;
1131 void MgAdapt::convertMedFile(std::string& meshFormatMeshFileName, std::string& solFormatFieldFileName, std::string& meshFormatsizeMapFile)
1134 std::vector<std::string> fieldFileNames;
1135 MEDCoupling::MeshFormatWriter writer;
1136 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = MEDCoupling::MEDFileData::New(medFileIn);
1137 MEDCoupling::MEDFileMeshes* meshes = mfd->getMeshes();
1138 MEDCoupling::MEDFileMesh* fileMesh = meshes->getMeshAtPos(0); // ok only one mesh in file!
1139 if (meshNameOut =="")
1140 meshNameOut = fileMesh->getName();
1141 storeGroupsAndFams(fileMesh);
1143 MEDCoupling::MCAuto<MEDCoupling::MEDFileFields> fields = MEDCoupling::MEDFileFields::New();
1144 solFormatFieldFileName = getFileName();
1145 solFormatFieldFileName+=".sol";
1146 fieldFileNames.push_back(solFormatFieldFileName);
1148 if (useBackgroundMap)
1151 meshFormatsizeMapFile = getFileName();
1152 meshFormatsizeMapFile += ".mesh";
1153 buildBackGroundMeshAndSolFiles(fieldFileNames, meshFormatsizeMapFile);
1156 else if(useLocalMap)
1159 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeFieldMultiTS> fts = dynamic_cast<MEDCoupling::MEDFileFieldMultiTS *>( mfd->getFields()->getFieldWithName(fieldName) );
1160 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeField1TS> f = fts->getTimeStep(timeStep, rank);
1161 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> tmFts = MEDCoupling::MEDFileFieldMultiTS::New();
1162 tmFts->pushBackTimeStep(f);
1164 fields->pushField(tmFts);
1166 writer.setFieldFileNames( fieldFileNames);
1171 MEDCoupling::MCAuto<MEDCoupling::MEDCouplingMesh> mesh = fileMesh->getMeshAtLevel(1); // nodes mesh
1172 MEDCoupling::MCAuto<MEDCoupling::MEDCouplingUMesh> umesh = mesh->buildUnstructured(); // nodes mesh
1173 int dim = umesh->getSpaceDimension();
1174 int version = sizeof(double) < 8 ? 1 : 2;
1175 mcIdType nbNodes = umesh->getNumberOfNodes();
1176 buildConstantSizeMapSolFile(solFormatFieldFileName, dim, version, nbNodes);
1180 mfd->setFields( fields );
1181 meshFormatMeshFileName = getFileName();
1182 meshFormatMeshFileName+=".mesh";
1183 writer.setMeshFileName(meshFormatMeshFileName);
1184 writer.setMEDFileDS( mfd);
1189 void MgAdapt::convertMeshFile(std::string& meshFormatIn, std::vector< std::string>& solFieldFileNames) const
1191 MEDCoupling::MeshFormatReader reader(meshFormatIn, solFieldFileNames);
1193 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = reader.loadInMedFileDS();
1195 MEDCoupling::MEDFileMeshes* meshes = mfd->getMeshes();
1196 MEDCoupling::MEDFileMesh* fileMesh = meshes->getMeshAtPos(0); // ok only one mesh in file!
1197 fileMesh->setName(meshNameOut);
1198 restoreGroupsAndFams(fileMesh);
1199 mfd->write(medFileOut, 2);
1203 void MgAdapt::storeGroupsAndFams(MEDCoupling::MEDFileMesh* fileMesh)
1205 storefams(fileMesh);
1206 storeGroups(fileMesh);
1209 void MgAdapt::restoreGroupsAndFams(MEDCoupling::MEDFileMesh* fileMesh) const
1211 restorefams(fileMesh);
1212 restoreGroups(fileMesh);
1214 void MgAdapt::storeGroups(MEDCoupling::MEDFileMesh* fileMesh)
1216 std::map<std::string, std::vector<std::string> > grpFams = fileMesh->getGroupInfo();
1217 std::map<std::string, std::vector<std::string> >::iterator g2ff = grpFams.begin();
1219 for ( ; g2ff != grpFams.end(); ++g2ff )
1221 std::string groupName = g2ff->first;
1222 std::vector<std::string> famNames = g2ff->second;
1224 if ( famNames.empty() ) continue;
1226 std::vector< mcIdType> famListId;
1227 for ( size_t i = 0; i < famNames.size(); ++i )
1229 famListId.push_back( fileMesh->getFamilyId( famNames[i].c_str() ) );
1231 group grp(groupName, famListId, famNames);
1232 groupVec.push_back(grp);
1236 void MgAdapt::storefams(MEDCoupling::MEDFileMesh* fileMesh)
1238 std::map<std::string, mcIdType> grpFams = fileMesh->getFamilyInfo();
1239 std::map<std::string, mcIdType >::iterator f = grpFams.begin();
1241 for ( ; f != grpFams.end(); ++f )
1243 if(!f->second) continue; // FAMILLE_ZERO
1244 family fs(f->first, f->second);
1245 famVec.push_back(fs);
1250 void MgAdapt::restorefams(MEDCoupling::MEDFileMesh* fileMesh) const
1252 std::vector<family>::const_iterator fIt = famVec.begin();
1254 for (; fIt!=famVec.end(); ++fIt)
1256 try // safety : FAMILY could be lost P2-->P1
1258 std::string givenFamNameFromMeshGemConverter = fileMesh->getFamilyNameGivenId( std::abs(fIt->_famId) );
1259 fileMesh->changeFamilyId(std::abs(fIt->_famId), fIt->_famId);
1260 fileMesh->changeFamilyName(givenFamNameFromMeshGemConverter, fIt->_famName);
1262 catch (const std::exception& e)
1264 std::cerr<<e.what();
1269 void MgAdapt::restoreGroups(MEDCoupling::MEDFileMesh* fileMesh) const
1271 std::map<std::string, std::vector<std::string> > info;
1272 std::vector <group>::const_iterator grpFams = groupVec.begin();
1274 for (; grpFams!=groupVec.end(); ++grpFams)
1276 info.insert(std::pair <std::string, std::vector<std::string> > (grpFams->_name, grpFams->_famNames) );
1279 fileMesh->setGroupInfo(info);
1282 void MgAdapt::buildConstantSizeMapSolFile(const std::string& solFormatFieldFileName, const int dim, const int version, const mcIdType nbNodes) const
1284 MeshFormat::Localizer loc;
1285 MeshFormat::MeshFormatParser writer;
1286 int fileId = writer.GmfOpenMesh( solFormatFieldFileName.c_str(), GmfWrite, version, dim);
1287 int typTab[] = {GmfSca};
1288 writer.GmfSetKwd(fileId, MeshFormat::GmfSolAtVertices, (int)nbNodes, 1, typTab);
1289 for (mcIdType i = 0; i<nbNodes; i++)
1291 double valTab[1] = {constantValue};
1292 writer.GmfSetLin( fileId, MeshFormat::GmfSolAtVertices, valTab);
1294 writer.GmfCloseMesh(fileId);
1297 void MgAdapt::buildBackGroundMeshAndSolFiles(const std::vector<std::string>& fieldFileNames, const std::string& meshFormatsizeMapFile) const
1299 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> tmpMfd = MEDCoupling::MEDFileData::New(sizeMapFile);
1300 MEDCoupling::MEDFileFields* tmpFields = tmpMfd->getFields();
1301 MEDCoupling::MEDFileAnyTypeFieldMultiTS* fts = tmpFields->getFieldWithName(fieldName);
1302 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> fts1 = dynamic_cast<MEDCoupling::MEDFileFieldMultiTS *>(fts);
1303 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeField1TS> f = fts1->getTimeStep(timeStep, rank);
1304 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> tmFts = MEDCoupling::MEDFileFieldMultiTS::New();
1305 tmFts->pushBackTimeStep(f);
1307 MEDCoupling::MCAuto<MEDCoupling::MEDFileFields> tmp_fields = MEDCoupling::MEDFileFields::New();
1308 tmp_fields->pushField(tmFts);
1311 tmpMfd->setFields( tmp_fields );
1312 MEDCoupling::MeshFormatWriter tmpWriter;
1313 tmpWriter.setMeshFileName(meshFormatsizeMapFile);
1314 tmpWriter.setFieldFileNames( fieldFileNames);
1315 tmpWriter.setMEDFileDS(tmpMfd);
1318 // =======================================================================
1319 med_idt MgAdapt::openMedFile(const std::string aFile)
1320 // =======================================================================
1321 // renvoie le medId associe au fichier Med apres ouverture
1323 med_idt medIdt = MEDfileOpen(aFile.c_str(),MED_ACC_RDONLY);
1326 //~addMessage( ToComment(" error: Can't open ") << aFile, /*fatal=*/true );
1332 MgAdapt::Status MgAdapt::addMessage(const std::string& msg,
1333 const bool isFatal/*=false*/)
1336 _myErrorMessages.clear(); // warnings are useless if a fatal error encounters
1338 _myErrorMessages.push_back( msg );
1342 std::cout << msg << std::endl;
1344 return ( _myStatus = isFatal ? MgAdapt::DRS_FAIL : MgAdapt::DRS_WARN_SKIP_ELEM );
1350 // =======================================================================
1351 void MgAdapt::getTimeStepInfos(std::string aFile, med_int& numdt, med_int& numit)
1352 // =======================================================================
1354 // Il faut voir si plusieurs maillages
1361 // Ouverture du fichier
1362 //~SCRUTE(aFile.toStdString());
1363 medIdt = openMedFile(aFile);
1364 if ( medIdt < 0 ) return ;
1365 // Lecture du nombre de champs
1366 med_int ncha = MEDnField(medIdt) ;
1369 //~addMessage( ToComment(" error: there is no field in ") << aFile, /*fatal=*/true );
1372 // Lecture des caracteristiques du champs
1374 // Lecture du type du champ, des noms des composantes et du nom de l'unite
1375 char nomcha [MED_NAME_SIZE+1];
1376 strcpy(nomcha, fieldName.c_str());
1377 // Lecture du nombre de composantes
1378 med_int ncomp = MEDfieldnComponentByName(medIdt, nomcha);
1379 char meshname[MED_NAME_SIZE+1];
1380 char * comp = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
1381 char * unit = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
1382 char dtunit[MED_SNAME_SIZE+1];
1384 med_field_type typcha;
1386 erreur = MEDfieldInfoByName (medIdt, nomcha, meshname,&local,&typcha,comp,unit,dtunit, &nbofcstp);
1391 //~addMessage( ToComment(" error: error while reading field ") << nomcha << " in file " << aFile , /*fatal=*/true );
1396 med_int tmp_numdt, tmp_numit;
1398 //~med_int step = data->myUseLastTimeStep ? nbofcstp : data->myTimeStep+1;
1399 //~myPrint("step ", step);
1400 erreur = MEDfieldComputingStepInfo ( medIdt, nomcha, 1, &numdt, &numit, &dt );
1401 for(med_int step = 1; step <= nbofcstp; step++ )
1403 erreur = MEDfieldComputingStepInfo ( medIdt, nomcha, step, &tmp_numdt, &tmp_numit, &dt );
1404 if(tmp_numdt > numdt)
1413 //~addMessage( ToComment(" error: error while reading field ") << nomcha << "step (numdt, numit) = " <<"("<< numdt<< ", " \
1414 numit<< ")" <<" in file " << aFile , /*fatal=*/true );
1420 // Fermeture du fichier
1421 if ( medIdt > 0 ) MEDfileClose(medIdt);
1426 void MgAdapt::updateTimeStepRank()
1431 if (myUseNoTimeStep)
1435 setRankTimeStep((int)tmst, (int)arank);
1437 else if (myUseLastTimeStep)
1439 std::string fieldFile = useBackgroundMap ? sizeMapFile : medFileIn;
1440 getTimeStepInfos(fieldFile, tmst, arank);
1441 setRankTimeStep((int)tmst, (int)arank);