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 TOptionValues::iterator op_val = _option2value.find(optionName);
531 if (op_val == _option2value.end())
533 op_val = _customOption2value.find( optionName );
534 _customOption2value[ optionName ] = optionValue;
538 if (op_val->second != optionValue)
541 std::string lowerOptionValue = toLowerStr(optionValue);
542 const char* ptr = lowerOptionValue.c_str();
543 // strip white spaces
544 while (ptr[0] == ' ')
547 while (i != 0 && ptr[i - 1] == ' ')
551 std::string typeName;
556 else if (_charOptions.count(optionName))
558 // do not check strings
560 else if (_doubleOptions.count(optionName))
562 // check if value is double
566 else if (_boolOptions.count(optionName))
568 // check if value is bool
569 toBool(ptr, &typeOk);
574 // check if value is int
576 typeName = "integer";
578 if ( typeOk ) // check some specific values ?
583 std::string msg = "Advanced option '" + optionName + "' = '" + optionValue + "' but must be " + typeName;
584 throw std::invalid_argument(msg);
586 std::string value( ptr, i );
587 if ( _defaultOptionValues[ optionName ] == value ) value.clear();
589 op_val->second = value;
593 //=============================================================================
594 //! Return option value. If isDefault provided, it can be a default value,
595 // then *isDefault == true. If isDefault is not provided, the value will be
596 // empty if it equals a default one.
597 std::string MgAdapt::getOptionValue(const std::string& optionName, bool* isDefault) const
598 throw (std::invalid_argument)
600 TOptionValues::const_iterator op_val = _option2value.find(optionName);
601 if (op_val == _option2value.end())
603 op_val = _customOption2value.find(optionName);
604 if (op_val == _customOption2value.end())
606 std::string msg = "Unknown MG-Adapt option: <" + optionName + ">";
607 throw std::invalid_argument(msg);
610 std::string val = op_val->second;
611 if ( isDefault ) *isDefault = ( val.empty() );
613 if ( val.empty() && isDefault )
615 op_val = _defaultOptionValues.find( optionName );
616 if (op_val != _defaultOptionValues.end()) val = op_val->second;
620 //================================================================================
622 * \brief Converts a string to a real value
624 //================================================================================
626 double MgAdapt::toDbl(const std::string& str, bool* isOk )
627 throw (std::invalid_argument)
629 if ( str.empty() ) throw std::invalid_argument("Empty value provided");
632 double val = strtod(&str[0], &endPtr);
633 bool ok = (&str[0] != endPtr);
635 if ( isOk ) *isOk = ok;
639 std::string msg = "Not a real value:'" + str + "'";
640 throw std::invalid_argument(msg);
644 //================================================================================
646 * \brief Converts a string to a lower
648 //================================================================================
649 std::string MgAdapt::toLowerStr(const std::string& str)
652 for ( size_t i = 0; i <= s.size(); ++i )
653 s[i] = tolower( s[i] );
656 //================================================================================
658 * \brief Converts a string to a bool
660 //================================================================================
662 bool MgAdapt::toBool(const std::string& str, bool* isOk )
663 throw (std::invalid_argument)
666 if ( isOk ) *isOk = true;
668 for ( size_t i = 0; i <= s.size(); ++i )
669 s[i] = tolower( s[i] );
671 if ( s == "1" || s == "true" || s == "active" || s == "yes" )
674 if ( s == "0" || s == "false" || s == "inactive" || s == "no" )
681 std::string msg = "Not a Boolean value:'" + str + "'";
682 throw std::invalid_argument(msg);
686 //================================================================================
688 * \brief Converts a string to a integer value
690 //================================================================================
692 int MgAdapt::toInt(const std::string& str, bool* isOk )
693 throw (std::invalid_argument)
695 if ( str.empty() ) throw std::invalid_argument("Empty value provided");
698 int val = (int)strtol( &str[0], &endPtr, 10);
699 bool ok = (&str[0] != endPtr);
701 if ( isOk ) *isOk = ok;
705 std::string msg = "Not an integer value:'" + str + "'";
706 throw std::invalid_argument(msg);
710 //=============================================================================
711 bool MgAdapt::hasOptionDefined( const std::string& optionName ) const
713 bool isDefault = false;
716 getOptionValue( optionName, &isDefault );
718 catch ( std::invalid_argument )
724 //================================================================================
726 * \brief Return command to run MG-Tetra mesher excluding file prefix (-f)
728 //================================================================================
730 std::string MgAdapt::getCommandToRun(MgAdapt* hyp)
732 return hyp ? hyp->getCommandToRun() : ToComment("error with hypothesis!");
737 int MgAdapt::compute(std::string& errStr)
739 std::string cmd = getCommandToRun();
741 execCmd( cmd.c_str(), err ); // run
745 errStr = ToComment("system(mg-adapt.exe ...) command failed with error: ") << strerror( errno );
749 convertMeshFile(meshFormatOutputMesh, solFormatOutput);
755 void MgAdapt::execCmd( const char* cmd, int& err)
758 std::array <char, 128> buffer;
760 outFileStream fileStream;
763 fileStream.open(logFile);
764 buf = fileStream.rdbuf();
768 buf = std::cout.rdbuf();
770 std::ostream logStream(buf);
772 std::unique_ptr <FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose );
775 throw std::runtime_error("popen() failed!");
777 while(fgets(buffer.data(), buffer.size(), pipe.get()) !=nullptr )
779 logStream<<buffer.data() ;
784 * to delete tmp files .mesh, .sol and if needed
788 void MgAdapt::cleanUp()
792 if(toKeepWorkingFiles)
794 if(removeOnSuccess && printLogInFile)
795 tmpFilesToBeDeleted.push_back(logFile);
797 std::vector< std::string>::iterator it = tmpFilesToBeDeleted.begin();
798 for (; it!=tmpFilesToBeDeleted.end(); ++it)
800 errStr=removeFile(*it, notOk);
803 appendMsgToLogFile(errStr);
809 void MgAdapt::appendMsgToLogFile(std::string& msg)
811 std::ofstream logStream;
812 logStream.open(logFile, std::ofstream::out | std::ofstream::app);
816 //================================================================================
818 * \brief Return command to run MG-Tetra mesher excluding file prefix (-f)
820 //================================================================================
822 std::string MgAdapt::getCommandToRun()
825 || return system command with args and options
829 std::string cmd = getExeName();
830 std::string meshIn(""), sizeMapIn(""), solFileIn("");
831 updateTimeStepRank();
832 convertMedFile(meshIn, solFileIn, sizeMapIn);
833 if (!isFileExist(meshIn) || !isFileExist(solFileIn))
835 errStr = ToComment(" failed to find .mesh or .sol file from converter ")<< strerror( errno );
838 tmpFilesToBeDeleted.push_back(meshIn);
839 tmpFilesToBeDeleted.push_back(solFileIn);
840 if(useBackgroundMap && !isFileExist(sizeMapIn))
842 errStr = ToComment(" failed to find .mesh size map file from converter ")<< strerror( errno );
846 cmd+= " --in "+ meshIn;
847 meshFormatOutputMesh = getFileName()+".mesh";
848 tmpFilesToBeDeleted.push_back(meshFormatOutputMesh);
849 cmd+= " --out "+ meshFormatOutputMesh;
850 if (useLocalMap || useConstantValue) cmd+= " --sizemap "+ solFileIn;
851 else // (useBackgroundMap)
853 cmd+= " --background_mesh "+ sizeMapIn ;
854 cmd+= " --background_sizemap "+ solFileIn;
855 tmpFilesToBeDeleted.push_back(sizeMapIn);
859 //~// constant value TODO
861 /* sizemap file is not adapted in case of only surface adaptation see MeshGems docs */
862 std::string adapOp = "adaptation";
863 std::string adpOpVal = getOptionValue(adapOp);
864 std::string surfaceAdapt = "surface";
865 if(surfaceAdapt != adpOpVal )
867 std::string solFileOut = getFileName()+".sol";
868 cmd+= " --write_sizemap "+ solFileOut;
869 solFormatOutput.push_back(solFileOut);
870 tmpFilesToBeDeleted.push_back(solFileOut);
872 if (verbosityLevel != defaultVerboseLevel())
874 cmd+= " --verbose "+ ToComment(verbosityLevel);
877 std::string option, value;
879 const TOptionValues* options[] = { &_option2value, &_customOption2value };
880 for ( int iOp = 0; iOp < 2; ++iOp )
882 TOptionValues::const_iterator o2v = options[iOp]->begin();
883 for ( ; o2v != options[iOp]->end(); ++o2v )
886 value = getOptionValue( option, &isDefault );
890 if ( value.empty() )//value == NoValue() )
892 if ( _defaultOptionValues.count( option ))
893 continue; // non-custom option with no value
896 if ( strncmp( "no", option.c_str(), 2 ) == 0 ) // options w/o values: --no_*
898 if ( !value.empty() && toBool( value ) == false )
902 if ( option[0] != '-' )
906 cmd += option + " " + value;
918 bool MgAdapt::isFileExist(const std::string& fName)
921 if ( fName.empty() ) return false;
923 boost::system::error_code err;
924 bool res = boost::filesystem::exists( fName, err );
926 return err ? false : res;
928 //=======================================================================
929 //function : defaultMaximumMemory
930 //=======================================================================
934 #elif !defined(__APPLE__)
935 #include <sys/sysinfo.h>
938 double MgAdapt::defaultMaximumMemory()
941 // See http://msdn.microsoft.com/en-us/library/aa366589.aspx
942 MEMORYSTATUSEX statex;
943 statex.dwLength = sizeof (statex);
944 long err = GlobalMemoryStatusEx (&statex);
947 double totMB = (double)statex.ullAvailPhys / 1024. / 1024.;
948 return (double)( 0.7 * totMB );
950 #elif !defined(__APPLE__)
952 long err = sysinfo( &si );
955 long ramMB = si.totalram * si.mem_unit / 1024 / 1024;
956 return ( 0.7 * ramMB );
962 //=======================================================================
963 //function : defaultWorkingDirectory
964 //=======================================================================
966 std::string MgAdapt::defaultWorkingDirectory()
968 TCollection_AsciiString aTmpDir;
970 char *Tmp_dir = getenv("SALOME_TMP_DIR");
977 aTmpDir = TCollection_AsciiString("C:\\");
979 aTmpDir = TCollection_AsciiString("/tmp/");
982 return aTmpDir.ToCString();
984 //================================================================================
986 * \brief Return a unique file name
988 //================================================================================
990 std::string MgAdapt::getFileName() const
992 std::string aTmpDir = workingDir;
993 const char lastChar = *aTmpDir.rbegin();
995 if(lastChar != '\\') aTmpDir+='\\';
997 if(lastChar != '/') aTmpDir+='/';
1000 TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
1001 aGenericName += "MgAdapt_";
1002 aGenericName += getpid();
1003 aGenericName += "_";
1004 aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
1006 return aGenericName.ToCString();
1008 //=======================================================================
1009 //function : defaultLogFile
1010 //=======================================================================
1012 std::string MgAdapt::defaultLogFile()
1014 std::string alogFile("MG_ADAPT.log");
1017 //=======================================================================
1018 //function : defaultUseConstantValue
1019 //=======================================================================
1021 bool MgAdapt::defaultUseConstantValue()
1025 //=======================================================================
1026 //function : defaultUseNoTimeStep
1027 //=======================================================================
1029 bool MgAdapt::defaultUseNoTimeStep()
1033 //=======================================================================
1034 //function : defaultRemoveLogOnSuccess
1035 //=======================================================================
1037 bool MgAdapt::defaultRemoveLogOnSuccess()
1041 //=======================================================================
1042 //function : defaultPrintLogInFile
1043 //=======================================================================
1045 bool MgAdapt::defaultPrintLogInFile()
1049 //=======================================================================
1050 //function : defaultUseChosenTimeStep
1051 //=======================================================================
1053 bool MgAdapt::defaultUseChosenTimeStep()
1057 //=======================================================================
1058 //function : UseLastTimeStep
1059 //=======================================================================
1061 bool MgAdapt::defaultUseLastTimeStep()
1065 //=======================================================================
1066 //function : defaultUseBackgroundMap
1067 //=======================================================================
1069 bool MgAdapt::defaultUseBackgroundMap()
1073 //=======================================================================
1074 //function : defaultKeepFiles
1075 //=======================================================================
1077 bool MgAdapt::defaultKeepFiles()
1081 //=======================================================================
1082 //function : defaultUseLocalMap
1083 //=======================================================================
1085 bool MgAdapt::defaultUseLocalMap()
1089 //=======================================================================
1090 //function : defaultPublish
1091 //=======================================================================
1093 bool MgAdapt::defaultPublish()
1097 //=======================================================================
1098 //function : defaultMeshOutMed
1099 //=======================================================================
1101 bool MgAdapt::defaultMeshOutMed()
1105 //=======================================================================
1106 //function : defaultFromMedFile
1107 //=======================================================================
1109 bool MgAdapt::defaultFromMedFile()
1113 //=======================================================================
1114 //function : defaultVerboseLevel
1115 //=======================================================================
1117 int MgAdapt::defaultVerboseLevel()
1121 std::string MgAdapt::getExeName()
1123 return "mg-adapt.exe";
1125 void MgAdapt::copyMgAdaptHypothesisData( const MgAdaptHypothesisData* from)
1127 data->myFileInDir = from->myFileInDir;
1128 data->myMeshFileIn = from->myMeshFileIn;
1129 data->myMeshFileBackground = from->myMeshFileBackground;
1130 data->myOutMeshName = from->myOutMeshName;
1131 data->myMeshFileOut = from->myMeshFileOut;
1132 data->myFileOutDir = from->myFileOutDir;
1133 data->myFileSizeMapDir = from->myFileSizeMapDir;
1134 data->myFieldName = from->myFieldName;
1135 data->fromMedFile = from->fromMedFile;
1136 data->myPublish = from->myPublish;
1137 data->myMeshOutMed = from->myMeshOutMed;
1138 data->myUseLocalMap = from->myUseLocalMap;
1139 data->myUseBackgroundMap = from->myUseBackgroundMap;
1140 data->myUseConstantValue = from->myUseConstantValue;
1141 data->myConstantValue = from->myConstantValue;
1142 data->myTimeStep = from->myTimeStep;
1143 data->myRank = from->myRank;
1144 data->myUseNoTimeStep = from->myUseNoTimeStep;
1145 data->myUseLastTimeStep = from->myUseLastTimeStep;
1146 data->myUseChosenTimeStep = from->myUseChosenTimeStep;
1147 data->myWorkingDir = from->myWorkingDir;
1148 data->myLogFile = from->myLogFile;
1149 data->myPrintLogInFile = from->myPrintLogInFile;
1150 data->myKeepFiles = from->myKeepFiles;
1151 data->myRemoveLogOnSuccess = from->myRemoveLogOnSuccess;
1152 data->myVerboseLevel = from->myVerboseLevel;
1155 bool MgAdapt::checkFieldName(std::string fileIn)
1158 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = MEDCoupling::MEDFileData::New(fileIn);
1159 std::vector<std::string> fieldNames(mfd->getFields()->getFieldsNames());
1160 std::size_t jaux(fieldNames.size());
1161 for(std::size_t j=0;j<jaux;j++)
1163 if ( fieldName == fieldNames[j] )
1168 std::cout << "Available field names:" << std::endl;
1169 for(std::size_t j=0;j<jaux;j++)
1170 { std::cout << fieldNames[j] << std::endl;}
1171 SALOME::ExceptionStruct es;
1172 es.type = SALOME::BAD_PARAM;
1173 std::string text = "Field " + fieldName + " is not found." ;
1174 es.text = CORBA::string_dup(text.c_str());
1175 throw SALOME::SALOME_Exception(es);
1180 bool MgAdapt::checkTimeStepRank(std::string fileIn)
1183 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = MEDCoupling::MEDFileData::New(fileIn);
1184 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeFieldMultiTS> fts = dynamic_cast<MEDCoupling::MEDFileFieldMultiTS *>( mfd->getFields()->getFieldWithName(fieldName) );
1185 // std::cout << "--- timeStep " << timeStep << std::endl;
1186 // std::cout << "--- rank " << rank << std::endl;
1187 std::vector<double> timevalue;
1188 std::vector< std::pair<int,int> > timesteprank = fts->getTimeSteps(timevalue);
1189 std::size_t jaux(timesteprank.size());
1190 for(std::size_t j=0;j<jaux;j++)
1192 if ( ( timeStep == timesteprank[j].first ) & ( rank == timesteprank[j].second ) )
1197 std::cout << "Available (Time step, Rank):" << std::endl;
1198 for(std::size_t j=0;j<jaux;j++)
1199 { std::cout << "(Time step = " << timesteprank[j].first << ", Rank = " << timesteprank[j].second << ")" << std::endl;}
1200 SALOME::ExceptionStruct es;
1201 es.type = SALOME::BAD_PARAM;
1202 std::string text = "(Time step = " + std::to_string(timeStep) + ", Rank = " + std::to_string(rank) + ") is not found." ;
1203 es.text = CORBA::string_dup(text.c_str());
1204 throw SALOME::SALOME_Exception(es);
1209 void MgAdapt::convertMedFile(std::string& meshFormatMeshFileName, std::string& solFormatFieldFileName, std::string& meshFormatsizeMapFile)
1211 std::vector<std::string> fieldFileNames;
1212 MEDCoupling::MeshFormatWriter writer;
1213 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = MEDCoupling::MEDFileData::New(medFileIn);
1214 MEDCoupling::MEDFileMeshes* meshes = mfd->getMeshes();
1215 MEDCoupling::MEDFileMesh* fileMesh = meshes->getMeshAtPos(0); // ok only one mesh in file!
1216 if (meshNameOut =="")
1217 meshNameOut = fileMesh->getName();
1218 storeGroupsAndFams(fileMesh);
1220 MEDCoupling::MCAuto<MEDCoupling::MEDFileFields> fields = MEDCoupling::MEDFileFields::New();
1221 solFormatFieldFileName = getFileName();
1222 solFormatFieldFileName+=".sol";
1223 fieldFileNames.push_back(solFormatFieldFileName);
1225 if (useBackgroundMap)
1228 ret = checkFieldName(sizeMapFile) ;
1229 ret = checkTimeStepRank(sizeMapFile) ;
1230 meshFormatsizeMapFile = getFileName();
1231 meshFormatsizeMapFile += ".mesh";
1232 buildBackGroundMeshAndSolFiles(fieldFileNames, meshFormatsizeMapFile);
1234 else if(useLocalMap)
1237 ret = checkFieldName(medFileIn) ;
1238 ret = checkTimeStepRank(medFileIn) ;
1239 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeFieldMultiTS> fts = dynamic_cast<MEDCoupling::MEDFileFieldMultiTS *>( mfd->getFields()->getFieldWithName(fieldName) );
1240 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeField1TS> f = fts->getTimeStep(timeStep, rank);
1241 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> tmFts = MEDCoupling::MEDFileFieldMultiTS::New();
1242 tmFts->pushBackTimeStep(f);
1244 fields->pushField(tmFts);
1246 writer.setFieldFileNames( fieldFileNames);
1250 MEDCoupling::MCAuto<MEDCoupling::MEDCouplingMesh> mesh = fileMesh->getMeshAtLevel(1); // nodes mesh
1251 MEDCoupling::MCAuto<MEDCoupling::MEDCouplingUMesh> umesh = mesh->buildUnstructured(); // nodes mesh
1252 int dim = umesh->getSpaceDimension();
1253 int version = sizeof(double) < 8 ? 1 : 2;
1254 mcIdType nbNodes = umesh->getNumberOfNodes();
1255 buildConstantSizeMapSolFile(solFormatFieldFileName, dim, version, nbNodes);
1258 mfd->setFields( fields );
1259 meshFormatMeshFileName = getFileName();
1260 meshFormatMeshFileName+=".mesh";
1261 writer.setMeshFileName(meshFormatMeshFileName);
1262 writer.setMEDFileDS( mfd);
1267 void MgAdapt::convertMeshFile(std::string& meshFormatIn, std::vector< std::string>& solFieldFileNames) const
1269 MEDCoupling::MeshFormatReader reader(meshFormatIn, solFieldFileNames);
1271 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = reader.loadInMedFileDS();
1273 MEDCoupling::MEDFileMeshes* meshes = mfd->getMeshes();
1274 MEDCoupling::MEDFileMesh* fileMesh = meshes->getMeshAtPos(0); // ok only one mesh in file!
1275 fileMesh->setName(meshNameOut);
1276 restoreGroupsAndFams(fileMesh);
1277 mfd->write(medFileOut, 2);
1280 void MgAdapt::storeGroupsAndFams(MEDCoupling::MEDFileMesh* fileMesh)
1282 storefams(fileMesh);
1283 storeGroups(fileMesh);
1286 void MgAdapt::restoreGroupsAndFams(MEDCoupling::MEDFileMesh* fileMesh) const
1288 restorefams(fileMesh);
1289 restoreGroups(fileMesh);
1291 void MgAdapt::storeGroups(MEDCoupling::MEDFileMesh* fileMesh)
1293 std::map<std::string, std::vector<std::string> > grpFams = fileMesh->getGroupInfo();
1294 std::map<std::string, std::vector<std::string> >::iterator g2ff = grpFams.begin();
1296 for ( ; g2ff != grpFams.end(); ++g2ff )
1298 std::string groupName = g2ff->first;
1299 std::vector<std::string> famNames = g2ff->second;
1301 if ( famNames.empty() ) continue;
1303 std::vector< mcIdType> famListId;
1304 for ( size_t i = 0; i < famNames.size(); ++i )
1306 famListId.push_back( fileMesh->getFamilyId( famNames[i].c_str() ) );
1308 group grp(groupName, famListId, famNames);
1309 groupVec.push_back(grp);
1313 void MgAdapt::storefams(MEDCoupling::MEDFileMesh* fileMesh)
1315 std::map<std::string, mcIdType> grpFams = fileMesh->getFamilyInfo();
1316 std::map<std::string, mcIdType >::iterator f = grpFams.begin();
1318 for ( ; f != grpFams.end(); ++f )
1320 if(!f->second) continue; // FAMILLE_ZERO
1321 family fs(f->first, f->second);
1322 famVec.push_back(fs);
1327 void MgAdapt::restorefams(MEDCoupling::MEDFileMesh* fileMesh) const
1329 std::vector<family>::const_iterator fIt = famVec.begin();
1331 for (; fIt!=famVec.end(); ++fIt)
1335 std::string givenFamNameFromMeshGemConverter = fileMesh->getFamilyNameGivenId( std::abs(fIt->_famId) );
1336 fileMesh->changeFamilyId(std::abs(fIt->_famId), fIt->_famId);
1337 fileMesh->changeFamilyName(givenFamNameFromMeshGemConverter, fIt->_famName);
1339 catch (const std::exception& e)
1341 std::cerr<<e.what();
1346 void MgAdapt::restoreGroups(MEDCoupling::MEDFileMesh* fileMesh) const
1348 std::map<std::string, std::vector<std::string> > info;
1349 std::vector <group>::const_iterator grpFams = groupVec.begin();
1351 for (; grpFams!=groupVec.end(); ++grpFams)
1353 info.insert(std::pair <std::string, std::vector<std::string> > (grpFams->_name, grpFams->_famNames) );
1356 fileMesh->setGroupInfo(info);
1359 void MgAdapt::buildConstantSizeMapSolFile(const std::string& solFormatFieldFileName, const int dim, const int version, const mcIdType nbNodes) const
1361 MeshFormat::Localizer loc;
1362 MeshFormat::MeshFormatParser writer;
1363 int fileId = writer.GmfOpenMesh( solFormatFieldFileName.c_str(), GmfWrite, version, dim);
1364 int typTab[] = {GmfSca};
1365 writer.GmfSetKwd(fileId, MeshFormat::GmfSolAtVertices, (int)nbNodes, 1, typTab);
1366 for (mcIdType i = 0; i<nbNodes; i++)
1368 double valTab[1] = {constantValue};
1369 writer.GmfSetLin( fileId, MeshFormat::GmfSolAtVertices, valTab);
1371 writer.GmfCloseMesh(fileId);
1374 void MgAdapt::buildBackGroundMeshAndSolFiles(const std::vector<std::string>& fieldFileNames, const std::string& meshFormatsizeMapFile) const
1376 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> tmpMfd = MEDCoupling::MEDFileData::New(sizeMapFile);
1377 MEDCoupling::MEDFileFields* tmpFields = tmpMfd->getFields();
1378 MEDCoupling::MEDFileAnyTypeFieldMultiTS* fts = tmpFields->getFieldWithName(fieldName);
1379 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> fts1 = dynamic_cast<MEDCoupling::MEDFileFieldMultiTS *>(fts);
1380 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeField1TS> f = fts1->getTimeStep(timeStep, rank);
1381 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> tmFts = MEDCoupling::MEDFileFieldMultiTS::New();
1382 tmFts->pushBackTimeStep(f);
1384 MEDCoupling::MCAuto<MEDCoupling::MEDFileFields> tmp_fields = MEDCoupling::MEDFileFields::New();
1385 tmp_fields->pushField(tmFts);
1387 tmpMfd->setFields( tmp_fields );
1388 MEDCoupling::MeshFormatWriter tmpWriter;
1389 tmpWriter.setMeshFileName(meshFormatsizeMapFile);
1390 tmpWriter.setFieldFileNames( fieldFileNames);
1391 tmpWriter.setMEDFileDS(tmpMfd);
1394 // =======================================================================
1395 med_idt MgAdapt::openMedFile(const std::string aFile)
1396 // =======================================================================
1397 // renvoie le medId associe au fichier Med apres ouverture
1399 med_idt medIdt = MEDfileOpen(aFile.c_str(),MED_ACC_RDONLY);
1402 SALOME::ExceptionStruct es;
1403 es.type = SALOME::BAD_PARAM;
1404 std::string text = "\nThe med file " + aFile + " cannot be opened.\n" ;
1405 es.text = CORBA::string_dup(text.c_str());
1406 throw SALOME::SALOME_Exception(es);
1411 MgAdapt::Status MgAdapt::addMessage(const std::string& msg,
1412 const bool isFatal/*=false*/)
1415 _myErrorMessages.clear(); // warnings are useless if a fatal error encounters
1417 _myErrorMessages.push_back( msg );
1421 std::cout << msg << std::endl;
1423 return ( _myStatus = isFatal ? MgAdapt::DRS_FAIL : MgAdapt::DRS_WARN_SKIP_ELEM );
1426 // =======================================================================
1427 void MgAdapt::getTimeStepInfos(std::string aFile, med_int& numdt, med_int& numit)
1428 // =======================================================================
1430 // Il faut voir si plusieurs maillages
1436 // Ouverture du fichier
1437 //~SCRUTE(aFile.toStdString());
1438 medIdt = openMedFile(aFile);
1439 if ( medIdt < 0 ) return ;
1440 // Lecture du nombre de champs
1441 med_int ncha = MEDnField(medIdt) ;
1444 //~addMessage( ToComment(" error: there is no field in ") << aFile, /*fatal=*/true );
1447 // Lecture des caracteristiques du champs
1449 // Lecture du type du champ, des noms des composantes et du nom de l'unite
1450 char nomcha [MED_NAME_SIZE+1];
1451 strcpy(nomcha, fieldName.c_str());
1452 // Lecture du nombre de composantes
1453 med_int ncomp = MEDfieldnComponentByName(medIdt, nomcha);
1454 char meshname[MED_NAME_SIZE+1];
1455 char * comp = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
1456 char * unit = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
1457 char dtunit[MED_SNAME_SIZE+1];
1459 med_field_type typcha;
1461 erreur = MEDfieldInfoByName (medIdt, nomcha, meshname,&local,&typcha,comp,unit,dtunit, &nbofcstp);
1466 //~addMessage( ToComment(" error: error while reading field ") << nomcha << " in file " << aFile , /*fatal=*/true );
1471 med_int tmp_numdt, tmp_numit;
1473 //~med_int step = data->myUseLastTimeStep ? nbofcstp : data->myTimeStep+1;
1474 //~myPrint("step ", step);
1475 erreur = MEDfieldComputingStepInfo ( medIdt, nomcha, 1, &numdt, &numit, &dt );
1476 for(med_int step = 1; step <= nbofcstp; step++ )
1478 erreur = MEDfieldComputingStepInfo ( medIdt, nomcha, step, &tmp_numdt, &tmp_numit, &dt );
1479 if(tmp_numdt > numdt)
1487 //~addMessage( ToComment(" error: error while reading field ") << nomcha << "step (numdt, numit) = " <<"("<< numdt<< ", " \
1488 numit<< ")" <<" in file " << aFile , /*fatal=*/true );
1492 // Fermeture du fichier
1493 if ( medIdt > 0 ) MEDfileClose(medIdt);
1497 void MgAdapt::updateTimeStepRank()
1502 if (myUseNoTimeStep)
1506 setRankTimeStep((int)tmst, (int)arank);
1508 else if (myUseLastTimeStep)
1510 std::string fieldFile = useBackgroundMap ? sizeMapFile : medFileIn;
1511 getTimeStepInfos(fieldFile, tmst, arank);
1512 setRankTimeStep((int)tmst, (int)arank);