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 <SALOME_NamingService.hxx>
34 #include <Utils_SALOME_Exception.hxx>
35 #include "Utils_CorbaException.hxx"
37 #include <utilities.h>
40 #include <TCollection_AsciiString.hxx>
43 #include <boost/filesystem.hpp>
45 using namespace MG_ADAPT;
46 static std::string removeFile(std::string fileName, int& notOk)
49 notOk = std::remove(fileName.c_str());
50 if (notOk) errStr = ToComment("\n error while removing file : ") << fileName;
51 else errStr = ToComment("\n file : ") << fileName << " succesfully deleted! \n ";
55 std::string remove_extension(const std::string& filename) {
56 size_t lastdot = filename.find_last_of(".");
57 if (lastdot == std::string::npos) return filename;
58 return filename.substr(0, lastdot);
62 struct GET_DEFAULT // struct used to get default value from GetOptionValue()
71 //----------------------------------------------------------------------------------------
74 data = new MgAdaptHypothesisData();
75 data->myInMeshName = "";
76 data->fromMedFile = defaultFromMedFile();
77 data->myFileInDir = defaultWorkingDirectory();
78 data->myMeshFileIn = "";
79 data->myFileOutDir = defaultWorkingDirectory();
80 data->myOutMeshName = "";
81 data->myMeshFileOut = "";
82 data->myMeshOutMed = defaultMeshOutMed();
83 data->myPublish = defaultPublish();
84 data->myUseLocalMap = defaultUseLocalMap();
85 data->myUseBackgroundMap = defaultUseBackgroundMap();
86 data->myFileSizeMapDir = defaultWorkingDirectory();
87 data->myMeshFileBackground = "";
88 data->myUseConstantValue = defaultUseConstantValue();
89 data->myConstantValue = 0.0;
90 data->myFieldName = "";
91 data->myUseNoTimeStep = defaultUseNoTimeStep();
92 data->myUseLastTimeStep = defaultUseLastTimeStep();
93 data->myUseChosenTimeStep = defaultUseChosenTimeStep();
94 data->myTimeStep = -2;
96 data->myWorkingDir = defaultWorkingDirectory();
97 data->myLogFile = defaultLogFile();
98 data->myVerboseLevel = defaultVerboseLevel();
99 data->myPrintLogInFile = defaultPrintLogInFile();
100 data->myKeepFiles = defaultKeepFiles();
101 data->myRemoveLogOnSuccess = defaultRemoveLogOnSuccess();
106 MgAdapt::MgAdapt(MgAdaptHypothesisData* myData)
108 data = new MgAdaptHypothesisData();
113 MgAdapt::MgAdapt( const MgAdapt& copy)
115 data = new MgAdaptHypothesisData();
116 MgAdaptHypothesisData *copyData = copy.getData();
117 copyMgAdaptHypothesisData(copyData);
120 this->_option2value = copy._option2value;
121 this->_customOption2value = copy._customOption2value;
122 this->_defaultOptionValues = copy._defaultOptionValues;
123 this->_doubleOptions = copy._doubleOptions;
124 this->_charOptions = copy._charOptions;
125 this->_boolOptions = copy._boolOptions;
128 //-----------------------------------------------------------------------------------------
133 void MgAdapt::buildModel()
136 const char* boolOptionNames[] = { "compute_ridges", // yes
139 // const char* intOptionNames[] = { "max_number_of_errors_printed", // 1
140 // "max_number_of_threads", // 4
143 const char* doubleOptionNames[] = { "max_memory", // 0
146 const char* charOptionNames[] = { "components", // "yes"
147 "adaptation", // both
152 while (boolOptionNames[i][0])
154 _boolOptions.insert( boolOptionNames[i] );
155 _option2value[boolOptionNames[i++]].clear();
158 // while (intOptionNames[i][0])
159 // _option2value[intOptionNames[i++]].clear();
162 while (doubleOptionNames[i][0]) {
163 _doubleOptions.insert(doubleOptionNames[i]);
164 _option2value[doubleOptionNames[i++]].clear();
167 while (charOptionNames[i][0]) {
168 _charOptions.insert(charOptionNames[i]);
169 _option2value[charOptionNames[i++]].clear();
172 // default values to be used while MG-Adapt
174 _defaultOptionValues["adaptation" ] = "both";
175 _defaultOptionValues["components" ] = "outside components";
176 _defaultOptionValues["compute_ridges"] = "yes";
177 _defaultOptionValues["max_memory" ] = ToComment(defaultMaximumMemory());
180 //=============================================================================
181 TOptionValues MgAdapt::getOptionValues() const
184 TOptionValues::const_iterator op_val = _option2value.begin();
185 for ( ; op_val != _option2value.end(); ++op_val )
186 vals.insert( make_pair( op_val->first, getOptionValue( op_val->first, GET_DEFAULT() )));
191 std::vector <std::string> MgAdapt::getOptionValuesStrVec() const
193 std::vector <std::string> vals;
194 TOptionValues::const_iterator op_val = _option2value.begin();
195 for ( ; op_val != _option2value.end(); ++op_val )
196 vals.push_back(op_val->first+":"+getOptionValue( op_val->first, GET_DEFAULT() ));
201 std::vector <std::string> MgAdapt::getCustomOptionValuesStrVec() const
203 std::vector <std::string> vals;
204 TOptionValues::const_iterator op_val;
205 for ( op_val = _customOption2value.begin(); op_val != _customOption2value.end(); ++op_val )
207 vals.push_back(op_val->first+":"+getOptionValue( op_val->first, GET_DEFAULT() ));
211 const TOptionValues& MgAdapt::getCustomOptionValues() const
213 return _customOption2value;
215 void MgAdapt::setData(MgAdaptHypothesisData* myData)
217 copyMgAdaptHypothesisData(myData);
220 MgAdaptHypothesisData* MgAdapt::getData() const
224 void MgAdapt::setMedFileIn(std::string fileName)
226 if ( isFileExist(fileName) )
228 medFileIn = fileName;
230 if (medFileOut == "") // default MED file Out
231 medFileOut = remove_extension( fileName )+ ".adapt.med";
235 SALOME::ExceptionStruct es;
236 es.type = SALOME::BAD_PARAM;
237 std::string text = "\nThe file " + fileName + " does not exist.\n" ;
238 es.text = CORBA::string_dup(text.c_str());
239 throw SALOME::SALOME_Exception(es);
243 std::string MgAdapt::getMedFileIn()
248 void MgAdapt::setMedFileOut(std::string fileOut)
250 medFileOut = fileOut;
252 std::string MgAdapt::getMedFileOut()
256 void MgAdapt::setMeshOutMed(bool mybool)
260 bool MgAdapt::getMeshOutMed()
264 void MgAdapt::setPublish(bool mybool)
268 bool MgAdapt::getPublish()
272 void MgAdapt::setFieldName(std::string myFieldName)
274 fieldName = myFieldName;
276 std::string MgAdapt::getFieldName()
280 void MgAdapt::setTimeStep(int time)
284 int MgAdapt::getTimeStep() const
289 void MgAdapt::setRankTimeStep(int time, int myRank)
295 int MgAdapt::getRank()
299 void MgAdapt::setTimeStepRankLast()
301 myUseLastTimeStep = true;
302 myUseChosenTimeStep = false;
303 myUseNoTimeStep = false;
304 //~med_int aRank, tmst;
305 //~std::string fieldFile = useBackgroundMap ? sizeMapFile : medFileIn;
306 //~getTimeStepInfos(fieldFile, tmst, aRank);
307 //~setRankTimeStep((int) tmst, (int) aRank);
309 void MgAdapt::setNoTimeStep()
311 myUseLastTimeStep = false;
312 myUseChosenTimeStep = false;
313 myUseNoTimeStep = true;
314 //~int aRank = (int)MED_NO_IT;
315 //~int tmst = (int)MED_NO_DT ;
316 //~setRankTimeStep(tmst, aRank);
318 void MgAdapt::setChosenTimeStepRank()
320 myUseLastTimeStep = false;
321 myUseChosenTimeStep = true;
322 myUseNoTimeStep = false;
323 //~int aRank = (int)MED_NO_IT;
324 //~int tmst = (int)MED_NO_DT ;
325 //~setRankTimeStep(tmst, aRank);
327 void MgAdapt::setUseLocalMap(bool myLocal)
329 useLocalMap = myLocal;
332 bool MgAdapt::getUseLocalMap()
337 void MgAdapt::setUseBackgroundMap(bool bckg)
339 useBackgroundMap = bckg;
342 bool MgAdapt::getUseBackgroundMap()
344 return useBackgroundMap;
347 void MgAdapt::setUseConstantValue(bool cnst)
349 useConstantValue = cnst;
351 bool MgAdapt::getUseConstantValue()
353 return useConstantValue;
355 void MgAdapt::setLogFile(std::string myLogFile)
359 std::string MgAdapt::getLogFile()
363 void MgAdapt::setVerbosityLevel(int verboLevel)
365 verbosityLevel = verboLevel;
367 int MgAdapt::getVerbosityLevel()
369 return verbosityLevel;
371 void MgAdapt::setRemoveOnSuccess(bool rmons)
373 removeOnSuccess = rmons;
375 bool MgAdapt::getRemoveOnSuccess()
377 return removeOnSuccess;
379 void MgAdapt::setSizeMapFile(std::string mapFile)
381 if ( mapFile == "" || isFileExist(mapFile) )
383 sizeMapFile = mapFile;
387 SALOME::ExceptionStruct es;
388 es.type = SALOME::BAD_PARAM;
389 std::string text = "\nThe file " + mapFile + " does not exist.\n" ;
390 es.text = CORBA::string_dup(text.c_str());
391 throw SALOME::SALOME_Exception(es);
394 std::string MgAdapt::getSizeMapFile()
399 void MgAdapt::setMeshName(std::string name)
403 std::string MgAdapt::getMeshName()
407 void MgAdapt::setMeshNameOut(std::string name)
411 std::string MgAdapt::getMeshNameOut()
415 void MgAdapt::setFromMedFile(bool mybool)
417 fromMedFile = mybool;
419 bool MgAdapt::isFromMedFile()
423 void MgAdapt::setConstantValue(double cnst)
425 constantValue = cnst;
427 double MgAdapt::getConstantValue() const
429 return constantValue;
432 void MgAdapt::setWorkingDir(std::string dir)
436 std::string MgAdapt::getWorkingDir() const
440 void MgAdapt::setKeepWorkingFiles(bool mybool)
442 toKeepWorkingFiles = mybool;
444 bool MgAdapt::getKeepWorkingFiles()
446 return toKeepWorkingFiles;
448 void MgAdapt::setPrintLogInFile(bool print)
450 printLogInFile = print;
452 bool MgAdapt::getPrintLogInFile()
454 return printLogInFile;
457 bool MgAdapt::setAll()
460 setFromMedFile(data->fromMedFile);
462 checkDirPath(data->myFileInDir);
463 file = data->myFileInDir+data->myMeshFileIn;
465 setMeshName(data->myInMeshName);
466 setMeshNameOut(data->myOutMeshName);
467 checkDirPath(data->myFileOutDir);
468 std::string out = data->myFileOutDir+data->myMeshFileOut;
470 setPublish(data->myPublish);
471 setMeshOutMed(data->myMeshOutMed);
472 setUseLocalMap(data->myUseLocalMap);
473 setUseBackgroundMap(data->myUseBackgroundMap);
474 setUseConstantValue(data->myUseConstantValue);
477 if (useBackgroundMap)
479 checkDirPath(data->myFileSizeMapDir);
480 mapfile = data->myFileSizeMapDir+data->myMeshFileBackground;
481 setFieldName(data->myFieldName);
483 else if (useConstantValue)
485 setConstantValue(data->myConstantValue);
490 setConstantValue(0.0);
491 setFieldName(data->myFieldName);
494 setSizeMapFile(mapfile);
495 if (data->myUseNoTimeStep)
497 else if (data->myUseLastTimeStep)
498 setTimeStepRankLast();
501 setChosenTimeStepRank();
502 setRankTimeStep(data->myTimeStep, data->myRank);
504 /* Advanced options */
505 setWorkingDir(data->myWorkingDir);
506 checkDirPath(data->myWorkingDir);
507 setLogFile(data->myWorkingDir+defaultLogFile());
508 setVerbosityLevel(data->myVerboseLevel);
509 setRemoveOnSuccess(data->myRemoveLogOnSuccess);
510 setPrintLogInFile(data->myPrintLogInFile);
511 setKeepWorkingFiles(data->myKeepFiles);
516 void MgAdapt::checkDirPath(std::string& dirPath)
518 const char lastChar = *dirPath.rbegin();
520 if(lastChar != '\\') dirPath+='\\';
522 if(lastChar != '/') dirPath+='/';
525 //=============================================================================
526 void MgAdapt::setOptionValue(const std::string& optionName,
527 const std::string& optionValue)
528 throw (std::invalid_argument)
530 // INFOS("setOptionValue");
531 // std::cout << "optionName: " << optionName << ", optionValue: " << optionValue << std::endl;
532 TOptionValues::iterator op_val = _option2value.find(optionName);
533 if (op_val == _option2value.end())
535 op_val = _customOption2value.find( optionName );
536 _customOption2value[ optionName ] = optionValue;
540 if (op_val->second != optionValue)
543 std::string lowerOptionValue = toLowerStr(optionValue);
544 const char* ptr = lowerOptionValue.c_str();
545 // strip white spaces
546 while (ptr[0] == ' ')
549 while (i != 0 && ptr[i - 1] == ' ')
553 std::string typeName;
558 else if (_charOptions.count(optionName))
560 // do not check strings
562 else if (_doubleOptions.count(optionName))
564 // check if value is double
568 else if (_boolOptions.count(optionName))
570 // check if value is bool
571 toBool(ptr, &typeOk);
576 // check if value is int
578 typeName = "integer";
580 if ( typeOk ) // check some specific values ?
585 std::string msg = "Advanced option '" + optionName + "' = '" + optionValue + "' but must be " + typeName;
586 throw std::invalid_argument(msg);
588 std::string value( ptr, i );
589 if ( _defaultOptionValues[ optionName ] == value ) value.clear();
591 // std::cout << "==> value: " << value << std::endl;
592 op_val->second = value;
596 //=============================================================================
597 //! Return option value. If isDefault provided, it can be a default value,
598 // then *isDefault == true. If isDefault is not provided, the value will be
599 // empty if it equals a default one.
600 std::string MgAdapt::getOptionValue(const std::string& optionName, bool* isDefault) const
601 throw (std::invalid_argument)
603 // INFOS("getOptionValue");
604 // std::cout << "optionName: " << optionName << ", isDefault: " << isDefault << std::endl;
605 TOptionValues::const_iterator op_val = _option2value.find(optionName);
606 if (op_val == _option2value.end())
608 op_val = _customOption2value.find(optionName);
609 if (op_val == _customOption2value.end())
611 std::string msg = "Unknown MG-Adapt option: <" + optionName + ">";
612 throw std::invalid_argument(msg);
615 std::string val = op_val->second;
616 if ( isDefault ) *isDefault = ( val.empty() );
618 if ( val.empty() && isDefault )
620 op_val = _defaultOptionValues.find( optionName );
621 if (op_val != _defaultOptionValues.end()) val = op_val->second;
623 // std::cout << "==> val: " << val << std::endl;
627 //================================================================================
629 * \brief Converts a string to a real value
631 //================================================================================
633 double MgAdapt::toDbl(const std::string& str, bool* isOk )
634 throw (std::invalid_argument)
636 if ( str.empty() ) throw std::invalid_argument("Empty value provided");
639 double val = strtod(&str[0], &endPtr);
640 bool ok = (&str[0] != endPtr);
642 if ( isOk ) *isOk = ok;
646 std::string msg = "Not a real value:'" + str + "'";
647 throw std::invalid_argument(msg);
651 //================================================================================
653 * \brief Converts a string to a lower
655 //================================================================================
656 std::string MgAdapt::toLowerStr(const std::string& str)
659 for ( size_t i = 0; i <= s.size(); ++i )
660 s[i] = tolower( s[i] );
663 //================================================================================
665 * \brief Converts a string to a bool
667 //================================================================================
669 bool MgAdapt::toBool(const std::string& str, bool* isOk )
670 throw (std::invalid_argument)
673 if ( isOk ) *isOk = true;
675 for ( size_t i = 0; i <= s.size(); ++i )
676 s[i] = tolower( s[i] );
678 if ( s == "1" || s == "true" || s == "active" || s == "yes" )
681 if ( s == "0" || s == "false" || s == "inactive" || s == "no" )
688 std::string msg = "Not a Boolean value:'" + str + "'";
689 throw std::invalid_argument(msg);
693 //================================================================================
695 * \brief Converts a string to a integer value
697 //================================================================================
699 int MgAdapt::toInt(const std::string& str, bool* isOk )
700 throw (std::invalid_argument)
702 if ( str.empty() ) throw std::invalid_argument("Empty value provided");
705 int val = (int)strtol( &str[0], &endPtr, 10);
706 bool ok = (&str[0] != endPtr);
708 if ( isOk ) *isOk = ok;
712 std::string msg = "Not an integer value:'" + str + "'";
713 throw std::invalid_argument(msg);
717 //=============================================================================
718 bool MgAdapt::hasOptionDefined( const std::string& optionName ) const
720 bool isDefault = false;
723 getOptionValue( optionName, &isDefault );
725 catch ( std::invalid_argument )
731 //================================================================================
733 * \brief Return command to run MG-Tetra mesher excluding file prefix (-f)
735 //================================================================================
737 std::string MgAdapt::getCommandToRun(MgAdapt* hyp)
739 return hyp ? hyp->getCommandToRun() : ToComment("error with hypothesis!");
744 int MgAdapt::compute(std::string& errStr)
746 std::string cmd = getCommandToRun();
748 execCmd( cmd.c_str(), err ); // run
752 errStr = ToComment("system(mg-adapt.exe ...) command failed with error: ") << strerror( errno );
756 convertMeshFile(meshFormatOutputMesh, solFormatOutput);
762 void MgAdapt::execCmd( const char* cmd, int& err)
765 std::array <char, 128> buffer;
767 outFileStream fileStream;
770 fileStream.open(logFile);
771 buf = fileStream.rdbuf();
775 buf = std::cout.rdbuf();
777 std::ostream logStream(buf);
779 std::unique_ptr <FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose );
782 throw std::runtime_error("popen() failed!");
784 while(fgets(buffer.data(), buffer.size(), pipe.get()) !=nullptr )
786 logStream<<buffer.data() ;
791 * to delete tmp files .mesh, .sol and if needed
795 void MgAdapt::cleanUp()
799 if(toKeepWorkingFiles)
801 if(removeOnSuccess && printLogInFile)
802 tmpFilesToBeDeleted.push_back(logFile);
804 std::vector< std::string>::iterator it = tmpFilesToBeDeleted.begin();
805 for (; it!=tmpFilesToBeDeleted.end(); ++it)
807 errStr=removeFile(*it, notOk);
810 appendMsgToLogFile(errStr);
816 void MgAdapt::appendMsgToLogFile(std::string& msg)
818 std::ofstream logStream;
819 logStream.open(logFile, std::ofstream::out | std::ofstream::app);
823 //================================================================================
825 * \brief Return command to run MG-Tetra mesher excluding file prefix (-f)
827 //================================================================================
829 std::string MgAdapt::getCommandToRun()
832 || return system command with args and options
836 std::string cmd = getExeName();
837 std::string meshIn(""), sizeMapIn(""), solFileIn("");
838 updateTimeStepRank();
839 convertMedFile(meshIn, solFileIn, sizeMapIn);
840 if (!isFileExist(meshIn) || !isFileExist(solFileIn))
842 errStr = ToComment(" failed to find .mesh or .sol file from converter ")<< strerror( errno );
845 tmpFilesToBeDeleted.push_back(meshIn);
846 tmpFilesToBeDeleted.push_back(solFileIn);
847 if(useBackgroundMap && !isFileExist(sizeMapIn))
849 errStr = ToComment(" failed to find .mesh size map file from converter ")<< strerror( errno );
853 cmd+= " --in "+ meshIn;
854 meshFormatOutputMesh = getFileName()+".mesh";
855 tmpFilesToBeDeleted.push_back(meshFormatOutputMesh);
856 cmd+= " --out "+ meshFormatOutputMesh;
857 if (useLocalMap || useConstantValue) cmd+= " --sizemap "+ solFileIn;
858 else // (useBackgroundMap)
860 cmd+= " --background_mesh "+ sizeMapIn ;
861 cmd+= " --background_sizemap "+ solFileIn;
862 tmpFilesToBeDeleted.push_back(sizeMapIn);
866 //~// constant value TODO
868 std::string adapOp = "adaptation";
869 std::string adpOpVal = getOptionValue(adapOp);
870 // Check coherence between mesh dimension and option
871 // checkDimensionOption(adpOpVal);
872 /* sizemap file is not adapted in case of only surface adaptation see MeshGems docs */
873 std::string surfaceAdapt = "surface";
874 if(surfaceAdapt != adpOpVal )
876 std::string solFileOut = getFileName()+".sol";
877 cmd+= " --write_sizemap "+ solFileOut;
878 solFormatOutput.push_back(solFileOut);
879 tmpFilesToBeDeleted.push_back(solFileOut);
882 std::string option, value;
884 const TOptionValues* options[] = { &_option2value, &_customOption2value };
885 for ( int iOp = 0; iOp < 2; ++iOp )
887 TOptionValues::const_iterator o2v = options[iOp]->begin();
888 for ( ; o2v != options[iOp]->end(); ++o2v )
891 value = getOptionValue( option, &isDefault );
895 if ( value.empty() )//value == NoValue() )
897 if ( _defaultOptionValues.count( option ))
898 continue; // non-custom option with no value
901 if ( strncmp( "no", option.c_str(), 2 ) == 0 ) // options w/o values: --no_*
903 if ( !value.empty() && toBool( value ) == false )
907 if ( option[0] != '-' )
911 cmd += option + " " + value;
916 if (verbosityLevel != defaultVerboseLevel())
918 cmd+= " --verbose "+ ToComment(verbosityLevel);
929 bool MgAdapt::isFileExist(const std::string& fName)
932 if ( fName.empty() ) return false;
934 boost::system::error_code err;
935 bool res = boost::filesystem::exists( fName, err );
937 return err ? false : res;
939 //=======================================================================
940 //function : defaultMaximumMemory
941 //=======================================================================
945 #elif !defined(__APPLE__)
946 #include <sys/sysinfo.h>
949 double MgAdapt::defaultMaximumMemory()
952 // See http://msdn.microsoft.com/en-us/library/aa366589.aspx
953 MEMORYSTATUSEX statex;
954 statex.dwLength = sizeof (statex);
955 long err = GlobalMemoryStatusEx (&statex);
958 double totMB = (double)statex.ullAvailPhys / 1024. / 1024.;
959 return (double)( 0.7 * totMB );
961 #elif !defined(__APPLE__)
963 long err = sysinfo( &si );
966 long ramMB = si.totalram * si.mem_unit / 1024 / 1024;
967 return ( 0.7 * ramMB );
973 //=======================================================================
974 //function : defaultWorkingDirectory
975 //=======================================================================
977 std::string MgAdapt::defaultWorkingDirectory()
979 TCollection_AsciiString aTmpDir;
981 char *Tmp_dir = getenv("SALOME_TMP_DIR");
988 aTmpDir = TCollection_AsciiString("C:\\");
990 aTmpDir = TCollection_AsciiString("/tmp/");
993 return aTmpDir.ToCString();
995 //================================================================================
997 * \brief Return a unique file name
999 //================================================================================
1001 std::string MgAdapt::getFileName() const
1003 std::string aTmpDir = workingDir;
1004 const char lastChar = *aTmpDir.rbegin();
1006 if(lastChar != '\\') aTmpDir+='\\';
1008 if(lastChar != '/') aTmpDir+='/';
1011 TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
1012 aGenericName += "MgAdapt_";
1013 aGenericName += getpid();
1014 aGenericName += "_";
1015 aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
1017 return aGenericName.ToCString();
1019 //=======================================================================
1020 //function : defaultLogFile
1021 //=======================================================================
1023 std::string MgAdapt::defaultLogFile()
1025 std::string alogFile("MG_ADAPT.log");
1028 //=======================================================================
1029 //function : defaultUseConstantValue
1030 //=======================================================================
1032 bool MgAdapt::defaultUseConstantValue()
1036 //=======================================================================
1037 //function : defaultUseNoTimeStep
1038 //=======================================================================
1040 bool MgAdapt::defaultUseNoTimeStep()
1044 //=======================================================================
1045 //function : defaultRemoveLogOnSuccess
1046 //=======================================================================
1048 bool MgAdapt::defaultRemoveLogOnSuccess()
1052 //=======================================================================
1053 //function : defaultPrintLogInFile
1054 //=======================================================================
1056 bool MgAdapt::defaultPrintLogInFile()
1060 //=======================================================================
1061 //function : defaultUseChosenTimeStep
1062 //=======================================================================
1064 bool MgAdapt::defaultUseChosenTimeStep()
1068 //=======================================================================
1069 //function : UseLastTimeStep
1070 //=======================================================================
1072 bool MgAdapt::defaultUseLastTimeStep()
1076 //=======================================================================
1077 //function : defaultUseBackgroundMap
1078 //=======================================================================
1080 bool MgAdapt::defaultUseBackgroundMap()
1084 //=======================================================================
1085 //function : defaultKeepFiles
1086 //=======================================================================
1088 bool MgAdapt::defaultKeepFiles()
1092 //=======================================================================
1093 //function : defaultUseLocalMap
1094 //=======================================================================
1096 bool MgAdapt::defaultUseLocalMap()
1100 //=======================================================================
1101 //function : defaultPublish
1102 //=======================================================================
1104 bool MgAdapt::defaultPublish()
1108 //=======================================================================
1109 //function : defaultMeshOutMed
1110 //=======================================================================
1112 bool MgAdapt::defaultMeshOutMed()
1116 //=======================================================================
1117 //function : defaultFromMedFile
1118 //=======================================================================
1120 bool MgAdapt::defaultFromMedFile()
1124 //=======================================================================
1125 //function : defaultVerboseLevel
1126 //=======================================================================
1128 int MgAdapt::defaultVerboseLevel()
1132 std::string MgAdapt::getExeName()
1134 return "mg-adapt.exe";
1136 void MgAdapt::copyMgAdaptHypothesisData( const MgAdaptHypothesisData* from)
1138 data->myFileInDir = from->myFileInDir;
1139 data->myMeshFileIn = from->myMeshFileIn;
1140 data->myMeshFileBackground = from->myMeshFileBackground;
1141 data->myOutMeshName = from->myOutMeshName;
1142 data->myMeshFileOut = from->myMeshFileOut;
1143 data->myFileOutDir = from->myFileOutDir;
1144 data->myFileSizeMapDir = from->myFileSizeMapDir;
1145 data->myFieldName = from->myFieldName;
1146 data->fromMedFile = from->fromMedFile;
1147 data->myPublish = from->myPublish;
1148 data->myMeshOutMed = from->myMeshOutMed;
1149 data->myUseLocalMap = from->myUseLocalMap;
1150 data->myUseBackgroundMap = from->myUseBackgroundMap;
1151 data->myUseConstantValue = from->myUseConstantValue;
1152 data->myConstantValue = from->myConstantValue;
1153 data->myTimeStep = from->myTimeStep;
1154 data->myRank = from->myRank;
1155 data->myUseNoTimeStep = from->myUseNoTimeStep;
1156 data->myUseLastTimeStep = from->myUseLastTimeStep;
1157 data->myUseChosenTimeStep = from->myUseChosenTimeStep;
1158 data->myWorkingDir = from->myWorkingDir;
1159 data->myLogFile = from->myLogFile;
1160 data->myPrintLogInFile = from->myPrintLogInFile;
1161 data->myKeepFiles = from->myKeepFiles;
1162 data->myRemoveLogOnSuccess = from->myRemoveLogOnSuccess;
1163 data->myVerboseLevel = from->myVerboseLevel;
1166 std::vector<std::string> MgAdapt::getListFieldsNames(std::string fileIn)
1168 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = MEDCoupling::MEDFileData::New(fileIn);
1169 std::vector<std::string> listFieldsNames(mfd->getFields()->getFieldsNames());
1170 return listFieldsNames ;
1173 void MgAdapt::checkDimensionOption(std::string adpOpVal)
1176 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = MEDCoupling::MEDFileData::New(medFileIn);
1177 int meshdim = mfd->getMeshes()->getMeshAtPos(0)->getMeshDimension() ;
1179 if ( ( meshdim == 2 ) & ( adpOpVal != "surface" ) )
1181 SALOME::ExceptionStruct es;
1182 es.type = SALOME::BAD_PARAM;
1183 std::string text = "Mesh dimension is 2; the option should be 'surface' instead of '" + adpOpVal + "'." ;
1184 es.text = CORBA::string_dup(text.c_str());
1185 throw SALOME::SALOME_Exception(es);
1189 void MgAdapt::checkFieldName(std::string fileIn)
1192 std::vector<std::string> listFieldsNames = getListFieldsNames(fileIn);
1193 std::size_t jaux(listFieldsNames.size());
1194 for(std::size_t j=0;j<jaux;j++)
1196 if ( fieldName == listFieldsNames[j] )
1204 std::cout << "Available field names:" << std::endl;
1205 for(std::size_t j=0;j<jaux;j++)
1206 { std::cout << listFieldsNames[j] << std::endl;}
1207 SALOME::ExceptionStruct es;
1208 es.type = SALOME::BAD_PARAM;
1209 std::string text = "Field " + fieldName + " is not found." ;
1210 es.text = CORBA::string_dup(text.c_str());
1211 throw SALOME::SALOME_Exception(es);
1215 void MgAdapt::checkTimeStepRank(std::string fileIn)
1218 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = MEDCoupling::MEDFileData::New(fileIn);
1219 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeFieldMultiTS> fts = dynamic_cast<MEDCoupling::MEDFileFieldMultiTS *>( mfd->getFields()->getFieldWithName(fieldName) );
1220 // std::cout << "--- timeStep " << timeStep << std::endl;
1221 // std::cout << "--- rank " << rank << std::endl;
1222 std::vector<double> timevalue;
1223 std::vector< std::pair<int,int> > timesteprank = fts->getTimeSteps(timevalue);
1224 std::size_t jaux(timesteprank.size());
1225 for(std::size_t j=0;j<jaux;j++)
1227 if ( ( timeStep == timesteprank[j].first ) & ( rank == timesteprank[j].second ) )
1235 std::cout << "Available (Time step, Rank):" << std::endl;
1236 for(std::size_t j=0;j<jaux;j++)
1237 { std::cout << "(Time step = " << timesteprank[j].first << ", Rank = " << timesteprank[j].second << ")" << std::endl;}
1238 SALOME::ExceptionStruct es;
1239 es.type = SALOME::BAD_PARAM;
1240 std::string text = "(Time step = " + std::to_string(timeStep) + ", Rank = " + std::to_string(rank) + ") is not found." ;
1241 es.text = CORBA::string_dup(text.c_str());
1242 throw SALOME::SALOME_Exception(es);
1246 void MgAdapt::convertMedFile(std::string& meshFormatMeshFileName, std::string& solFormatFieldFileName, std::string& meshFormatsizeMapFile)
1248 std::vector<std::string> fieldFileNames;
1249 MEDCoupling::MeshFormatWriter writer;
1250 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = MEDCoupling::MEDFileData::New(medFileIn);
1251 MEDCoupling::MEDFileMeshes* meshes = mfd->getMeshes();
1252 MEDCoupling::MEDFileMesh* fileMesh = meshes->getMeshAtPos(0); // ok only one mesh in file!
1253 if (meshNameOut =="")
1254 meshNameOut = fileMesh->getName();
1255 storeGroupsAndFams(fileMesh);
1257 MEDCoupling::MCAuto<MEDCoupling::MEDFileFields> fields = MEDCoupling::MEDFileFields::New();
1258 solFormatFieldFileName = getFileName();
1259 solFormatFieldFileName+=".sol";
1260 fieldFileNames.push_back(solFormatFieldFileName);
1262 if (useBackgroundMap)
1264 checkFieldName(sizeMapFile) ;
1265 checkTimeStepRank(sizeMapFile) ;
1266 meshFormatsizeMapFile = getFileName();
1267 meshFormatsizeMapFile += ".mesh";
1268 buildBackGroundMeshAndSolFiles(fieldFileNames, meshFormatsizeMapFile);
1270 else if(useLocalMap)
1272 checkFieldName(medFileIn) ;
1273 checkTimeStepRank(medFileIn) ;
1274 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeFieldMultiTS> fts = dynamic_cast<MEDCoupling::MEDFileFieldMultiTS *>( mfd->getFields()->getFieldWithName(fieldName) );
1275 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeField1TS> f = fts->getTimeStep(timeStep, rank);
1276 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> tmFts = MEDCoupling::MEDFileFieldMultiTS::New();
1277 tmFts->pushBackTimeStep(f);
1279 fields->pushField(tmFts);
1281 writer.setFieldFileNames( fieldFileNames);
1285 MEDCoupling::MCAuto<MEDCoupling::MEDCouplingMesh> mesh = fileMesh->getMeshAtLevel(1); // nodes mesh
1286 MEDCoupling::MCAuto<MEDCoupling::MEDCouplingUMesh> umesh = mesh->buildUnstructured(); // nodes mesh
1287 int dim = umesh->getSpaceDimension();
1288 int version = sizeof(double) < 8 ? 1 : 2;
1289 mcIdType nbNodes = umesh->getNumberOfNodes();
1290 buildConstantSizeMapSolFile(solFormatFieldFileName, dim, version, nbNodes);
1293 mfd->setFields( fields );
1294 meshFormatMeshFileName = getFileName();
1295 meshFormatMeshFileName+=".mesh";
1296 writer.setMeshFileName(meshFormatMeshFileName);
1297 writer.setMEDFileDS( mfd);
1302 void MgAdapt::convertMeshFile(std::string& meshFormatIn, std::vector< std::string>& solFieldFileNames) const
1304 MEDCoupling::MeshFormatReader reader(meshFormatIn, solFieldFileNames);
1306 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = reader.loadInMedFileDS();
1308 MEDCoupling::MEDFileMeshes* meshes = mfd->getMeshes();
1309 MEDCoupling::MEDFileMesh* fileMesh = meshes->getMeshAtPos(0); // ok only one mesh in file!
1310 fileMesh->setName(meshNameOut);
1311 restoreGroupsAndFams(fileMesh);
1312 mfd->write(medFileOut, 2);
1315 void MgAdapt::storeGroupsAndFams(MEDCoupling::MEDFileMesh* fileMesh)
1317 storefams(fileMesh);
1318 storeGroups(fileMesh);
1321 void MgAdapt::restoreGroupsAndFams(MEDCoupling::MEDFileMesh* fileMesh) const
1323 restorefams(fileMesh);
1324 restoreGroups(fileMesh);
1326 void MgAdapt::storeGroups(MEDCoupling::MEDFileMesh* fileMesh)
1328 std::map<std::string, std::vector<std::string> > grpFams = fileMesh->getGroupInfo();
1329 std::map<std::string, std::vector<std::string> >::iterator g2ff = grpFams.begin();
1331 for ( ; g2ff != grpFams.end(); ++g2ff )
1333 std::string groupName = g2ff->first;
1334 std::vector<std::string> famNames = g2ff->second;
1336 if ( famNames.empty() ) continue;
1338 std::vector< mcIdType> famListId;
1339 for ( size_t i = 0; i < famNames.size(); ++i )
1341 famListId.push_back( fileMesh->getFamilyId( famNames[i].c_str() ) );
1343 group grp(groupName, famListId, famNames);
1344 groupVec.push_back(grp);
1348 void MgAdapt::storefams(MEDCoupling::MEDFileMesh* fileMesh)
1350 std::map<std::string, mcIdType> grpFams = fileMesh->getFamilyInfo();
1351 std::map<std::string, mcIdType >::iterator f = grpFams.begin();
1353 for ( ; f != grpFams.end(); ++f )
1355 if(!f->second) continue; // FAMILLE_ZERO
1356 family fs(f->first, f->second);
1357 famVec.push_back(fs);
1362 void MgAdapt::restorefams(MEDCoupling::MEDFileMesh* fileMesh) const
1364 std::vector<family>::const_iterator fIt = famVec.begin();
1366 for (; fIt!=famVec.end(); ++fIt)
1370 std::string givenFamNameFromMeshGemConverter = fileMesh->getFamilyNameGivenId( std::abs(fIt->_famId) );
1371 fileMesh->changeFamilyId(std::abs(fIt->_famId), fIt->_famId);
1372 fileMesh->changeFamilyName(givenFamNameFromMeshGemConverter, fIt->_famName);
1374 catch (const std::exception& e)
1376 std::cerr<<e.what();
1381 void MgAdapt::restoreGroups(MEDCoupling::MEDFileMesh* fileMesh) const
1383 std::map<std::string, std::vector<std::string> > info;
1384 std::vector <group>::const_iterator grpFams = groupVec.begin();
1386 for (; grpFams!=groupVec.end(); ++grpFams)
1388 info.insert(std::pair <std::string, std::vector<std::string> > (grpFams->_name, grpFams->_famNames) );
1391 fileMesh->setGroupInfo(info);
1394 void MgAdapt::buildConstantSizeMapSolFile(const std::string& solFormatFieldFileName, const int dim, const int version, const mcIdType nbNodes) const
1396 MeshFormat::Localizer loc;
1397 MeshFormat::MeshFormatParser writer;
1398 int fileId = writer.GmfOpenMesh( solFormatFieldFileName.c_str(), GmfWrite, version, dim);
1399 int typTab[] = {GmfSca};
1400 writer.GmfSetKwd(fileId, MeshFormat::GmfSolAtVertices, (int)nbNodes, 1, typTab);
1401 for (mcIdType i = 0; i<nbNodes; i++)
1403 double valTab[1] = {constantValue};
1404 writer.GmfSetLin( fileId, MeshFormat::GmfSolAtVertices, valTab);
1406 writer.GmfCloseMesh(fileId);
1409 void MgAdapt::buildBackGroundMeshAndSolFiles(const std::vector<std::string>& fieldFileNames, const std::string& meshFormatsizeMapFile) const
1411 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> tmpMfd = MEDCoupling::MEDFileData::New(sizeMapFile);
1412 MEDCoupling::MEDFileFields* tmpFields = tmpMfd->getFields();
1413 MEDCoupling::MEDFileAnyTypeFieldMultiTS* fts = tmpFields->getFieldWithName(fieldName);
1414 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> fts1 = dynamic_cast<MEDCoupling::MEDFileFieldMultiTS *>(fts);
1415 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeField1TS> f = fts1->getTimeStep(timeStep, rank);
1416 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> tmFts = MEDCoupling::MEDFileFieldMultiTS::New();
1417 tmFts->pushBackTimeStep(f);
1419 MEDCoupling::MCAuto<MEDCoupling::MEDFileFields> tmp_fields = MEDCoupling::MEDFileFields::New();
1420 tmp_fields->pushField(tmFts);
1422 tmpMfd->setFields( tmp_fields );
1423 MEDCoupling::MeshFormatWriter tmpWriter;
1424 tmpWriter.setMeshFileName(meshFormatsizeMapFile);
1425 tmpWriter.setFieldFileNames( fieldFileNames);
1426 tmpWriter.setMEDFileDS(tmpMfd);
1429 // =======================================================================
1430 med_idt MgAdapt::openMedFile(const std::string aFile)
1431 // =======================================================================
1432 // renvoie le medId associe au fichier Med apres ouverture
1434 med_idt medIdt = MEDfileOpen(aFile.c_str(),MED_ACC_RDONLY);
1437 SALOME::ExceptionStruct es;
1438 es.type = SALOME::BAD_PARAM;
1439 std::string text = "\nThe med file " + aFile + " cannot be opened.\n" ;
1440 es.text = CORBA::string_dup(text.c_str());
1441 throw SALOME::SALOME_Exception(es);
1446 MgAdapt::Status MgAdapt::addMessage(const std::string& msg,
1447 const bool isFatal/*=false*/)
1450 _myErrorMessages.clear(); // warnings are useless if a fatal error encounters
1452 _myErrorMessages.push_back( msg );
1456 std::cout << msg << std::endl;
1458 return ( _myStatus = isFatal ? MgAdapt::DRS_FAIL : MgAdapt::DRS_WARN_SKIP_ELEM );
1461 // =======================================================================
1462 void MgAdapt::getTimeStepInfos(std::string aFile, med_int& numdt, med_int& numit)
1463 // =======================================================================
1465 // Il faut voir si plusieurs maillages
1471 // Ouverture du fichier
1472 //~SCRUTE(aFile.toStdString());
1473 medIdt = openMedFile(aFile);
1474 if ( medIdt < 0 ) return ;
1475 // Lecture du nombre de champs
1476 med_int ncha = MEDnField(medIdt) ;
1479 //~addMessage( ToComment(" error: there is no field in ") << aFile, /*fatal=*/true );
1482 // Lecture des caracteristiques du champs
1484 // Lecture du type du champ, des noms des composantes et du nom de l'unite
1485 char nomcha [MED_NAME_SIZE+1];
1486 strcpy(nomcha, fieldName.c_str());
1487 // Lecture du nombre de composantes
1488 med_int ncomp = MEDfieldnComponentByName(medIdt, nomcha);
1489 char meshname[MED_NAME_SIZE+1];
1490 char * comp = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
1491 char * unit = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
1492 char dtunit[MED_SNAME_SIZE+1];
1494 med_field_type typcha;
1496 erreur = MEDfieldInfoByName (medIdt, nomcha, meshname,&local,&typcha,comp,unit,dtunit, &nbofcstp);
1501 //~addMessage( ToComment(" error: error while reading field ") << nomcha << " in file " << aFile , /*fatal=*/true );
1506 med_int tmp_numdt, tmp_numit;
1508 //~med_int step = data->myUseLastTimeStep ? nbofcstp : data->myTimeStep+1;
1509 //~myPrint("step ", step);
1510 erreur = MEDfieldComputingStepInfo ( medIdt, nomcha, 1, &numdt, &numit, &dt );
1511 for(med_int step = 1; step <= nbofcstp; step++ )
1513 erreur = MEDfieldComputingStepInfo ( medIdt, nomcha, step, &tmp_numdt, &tmp_numit, &dt );
1514 if(tmp_numdt > numdt)
1522 //~addMessage( ToComment(" error: error while reading field ") << nomcha << "step (numdt, numit) = " <<"("<< numdt<< ", " \
1523 numit<< ")" <<" in file " << aFile , /*fatal=*/true );
1527 // Fermeture du fichier
1528 if ( medIdt > 0 ) MEDfileClose(medIdt);
1532 void MgAdapt::updateTimeStepRank()
1537 if (myUseNoTimeStep)
1541 setRankTimeStep((int)tmst, (int)arank);
1543 else if (myUseLastTimeStep)
1545 std::string fieldFile = useBackgroundMap ? sizeMapFile : medFileIn;
1546 getTimeStepInfos(fieldFile, tmst, arank);
1547 setRankTimeStep((int)tmst, (int)arank);