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>
36 #include <utilities.h>
39 #include <TCollection_AsciiString.hxx>
42 #include <boost/filesystem.hpp>
44 using namespace MG_ADAPT;
45 static std::string removeFile(std::string fileName, int& notOk)
48 notOk = std::remove(fileName.c_str());
49 if (notOk) errStr = ToComment("\n error while removing file : ") << fileName;
50 else errStr = ToComment("\n file : ") << fileName << " succesfully deleted! \n ";
54 std::string remove_extension(const std::string& filename) {
55 size_t lastdot = filename.find_last_of(".");
56 if (lastdot == std::string::npos) return filename;
57 return filename.substr(0, lastdot);
61 struct GET_DEFAULT // struct used to get default value from GetOptionValue()
70 //----------------------------------------------------------------------------------------
73 data = new MgAdaptHypothesisData();
74 data->myInMeshName = "";
75 data->fromMedFile = defaultFromMedFile();
76 data->myFileInDir = defaultWorkingDirectory();
77 data->myMeshFileIn = "";
78 data->myFileOutDir = defaultWorkingDirectory();
79 data->myOutMeshName = "";
80 data->myMeshFileOut = "";
81 data->myMeshOutMed = defaultMeshOutMed();
82 data->myPublish = defaultPublish();
83 data->myUseLocalMap = defaultUseLocalMap();
84 data->myUseBackgroundMap = defaultUseBackgroundMap();
85 data->myFileSizeMapDir = defaultWorkingDirectory();
86 data->myMeshFileBackground = "";
87 data->myUseConstantValue = defaultUseConstantValue();
88 data->myConstantValue = 0.0;
89 data->myFieldName = "";
90 data->myUseNoTimeStep = defaultUseNoTimeStep();
91 data->myUseLastTimeStep = defaultUseLastTimeStep();
92 data->myUseChosenTimeStep = defaultUseChosenTimeStep();
93 data->myTimeStep = -2;
95 data->myWorkingDir = defaultWorkingDirectory();
96 data->myLogFile = defaultLogFile();
97 data->myVerboseLevel = defaultVerboseLevel();
98 data->myPrintLogInFile = defaultPrintLogInFile();
99 data->myKeepFiles = defaultKeepFiles();
100 data->myRemoveLogOnSuccess = defaultRemoveLogOnSuccess();
105 MgAdapt::MgAdapt(MgAdaptHypothesisData* myData)
107 data = new MgAdaptHypothesisData();
112 MgAdapt::MgAdapt( const MgAdapt& copy)
114 data = new MgAdaptHypothesisData();
115 MgAdaptHypothesisData *copyData = copy.getData();
116 copyMgAdaptHypothesisData(copyData);
119 this->_option2value = copy._option2value;
120 this->_customOption2value = copy._customOption2value;
121 this->_defaultOptionValues = copy._defaultOptionValues;
122 this->_doubleOptions = copy._doubleOptions;
123 this->_charOptions = copy._charOptions;
124 this->_boolOptions = copy._boolOptions;
127 //-----------------------------------------------------------------------------------------
132 void MgAdapt::buildModel()
135 const char* boolOptionNames[] = { "compute_ridges", // yes
138 // const char* intOptionNames[] = { "max_number_of_errors_printed", // 1
139 // "max_number_of_threads", // 4
142 const char* doubleOptionNames[] = { "max_memory", // 0
145 const char* charOptionNames[] = { "components", // "yes"
146 "adaptation", // both
151 while (boolOptionNames[i][0])
153 _boolOptions.insert( boolOptionNames[i] );
154 _option2value[boolOptionNames[i++]].clear();
157 // while (intOptionNames[i][0])
158 // _option2value[intOptionNames[i++]].clear();
161 while (doubleOptionNames[i][0]) {
162 _doubleOptions.insert(doubleOptionNames[i]);
163 _option2value[doubleOptionNames[i++]].clear();
166 while (charOptionNames[i][0]) {
167 _charOptions.insert(charOptionNames[i]);
168 _option2value[charOptionNames[i++]].clear();
171 // default values to be used while MG-Adapt
173 _defaultOptionValues["adaptation" ] = "both";
174 _defaultOptionValues["components" ] = "outside components";
175 _defaultOptionValues["compute_ridges" ] = "yes";
176 _defaultOptionValues["max_memory" ] = ToComment(defaultMaximumMemory());
179 //=============================================================================
180 TOptionValues MgAdapt::getOptionValues() const
183 TOptionValues::const_iterator op_val = _option2value.begin();
184 for ( ; op_val != _option2value.end(); ++op_val )
185 vals.insert( make_pair( op_val->first, getOptionValue( op_val->first, GET_DEFAULT() )));
190 std::vector <std::string> MgAdapt::getOptionValuesStrVec() const
192 std::vector <std::string> vals;
193 TOptionValues::const_iterator op_val = _option2value.begin();
194 for ( ; op_val != _option2value.end(); ++op_val )
195 vals.push_back(op_val->first+":"+getOptionValue( op_val->first, GET_DEFAULT() ));
200 std::vector <std::string> MgAdapt::getCustomOptionValuesStrVec() const
202 std::vector <std::string> vals;
203 TOptionValues::const_iterator op_val;
204 for ( op_val = _customOption2value.begin(); op_val != _customOption2value.end(); ++op_val )
206 vals.push_back(op_val->first+":"+getOptionValue( op_val->first, GET_DEFAULT() ));
210 const TOptionValues& MgAdapt::getCustomOptionValues() const
212 return _customOption2value;
214 void MgAdapt::setData(MgAdaptHypothesisData* myData)
216 copyMgAdaptHypothesisData(myData);
219 MgAdaptHypothesisData* MgAdapt::getData() const
223 void MgAdapt::setMedFileIn(std::string fileName)
225 if ( isFileExist(fileName) )
227 medFileIn = fileName;
229 if (medFileOut == "") // default MED file Out
230 medFileOut = remove_extension( fileName )+ ".adapt.med";
234 std::cout << "\nThe file " + fileName + " does not exist.\n" << std::endl;
235 // SALOME::ExceptionStruct es;
236 // es.type = SALOME::BAD_PARAM;
237 // std::string text = "\nThe file " + fileName + " does not exist.\n" ;
238 // std::cout << text << std::endl;
239 // es.text = "The mesh file does not exist.";
240 // es.text = CORBA::string_dup(text.c_str());
241 // throw SALOME::SALOME_Exception(es);
242 throw SALOME_Exception(("The file " + fileName + " does not exist." ).c_str() );
246 std::string MgAdapt::getMedFileIn()
251 void MgAdapt::setMedFileOut(std::string fileOut)
253 medFileOut = fileOut;
255 std::string MgAdapt::getMedFileOut()
259 void MgAdapt::setMeshOutMed(bool mybool)
263 bool MgAdapt::getMeshOutMed()
267 void MgAdapt::setPublish(bool mybool)
271 bool MgAdapt::getPublish()
275 void MgAdapt::setFieldName(std::string myFieldName)
277 fieldName = myFieldName;
279 std::string MgAdapt::getFieldName()
283 void MgAdapt::setTimeStep(int time)
287 int MgAdapt::getTimeStep() const
292 void MgAdapt::setRankTimeStep(int time, int myRank)
298 int MgAdapt::getRank()
302 void MgAdapt::setTimeStepRankLast()
304 myUseLastTimeStep = true;
305 myUseChosenTimeStep = false;
306 myUseNoTimeStep = false;
307 //~med_int aRank, tmst;
308 //~std::string fieldFile = useBackgroundMap ? sizeMapFile : medFileIn;
309 //~getTimeStepInfos(fieldFile, tmst, aRank);
310 //~setRankTimeStep((int) tmst, (int) aRank);
312 void MgAdapt::setNoTimeStep()
314 myUseLastTimeStep = false;
315 myUseChosenTimeStep = false;
316 myUseNoTimeStep = true;
317 //~int aRank = (int)MED_NO_IT;
318 //~int tmst = (int)MED_NO_DT ;
319 //~setRankTimeStep(tmst, aRank);
321 void MgAdapt::setChosenTimeStepRank()
323 myUseLastTimeStep = false;
324 myUseChosenTimeStep = true;
325 myUseNoTimeStep = false;
326 //~int aRank = (int)MED_NO_IT;
327 //~int tmst = (int)MED_NO_DT ;
328 //~setRankTimeStep(tmst, aRank);
330 void MgAdapt::setUseLocalMap(bool myLocal)
332 useLocalMap = myLocal;
335 bool MgAdapt::getUseLocalMap()
340 void MgAdapt::setUseBackgroundMap(bool bckg)
342 useBackgroundMap = bckg;
345 bool MgAdapt::getUseBackgroundMap()
347 return useBackgroundMap;
350 void MgAdapt::setUseConstantValue(bool cnst)
352 useConstantValue = cnst;
354 bool MgAdapt::getUseConstantValue()
356 return useConstantValue;
358 void MgAdapt::setLogFile(std::string myLogFile)
362 std::string MgAdapt::getLogFile()
366 void MgAdapt::setVerbosityLevel(int verboLevel)
368 verbosityLevel = verboLevel;
370 int MgAdapt::getVerbosityLevel()
372 return verbosityLevel;
374 void MgAdapt::setRemoveOnSuccess(bool rmons)
376 removeOnSuccess = rmons;
378 bool MgAdapt::getRemoveOnSuccess()
380 return removeOnSuccess;
382 void MgAdapt::setSizeMapFile(std::string mapFile)
384 if ( mapFile == "" || isFileExist(mapFile) )
386 sizeMapFile = mapFile;
390 std::cout << "\nThe file " + mapFile + " does not exist.\n" << std::endl;
391 throw SALOME_Exception(("The file " + mapFile + " does not exist." ).c_str() );
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;
1156 void MgAdapt::convertMedFile(std::string& meshFormatMeshFileName, std::string& solFormatFieldFileName, std::string& meshFormatsizeMapFile)
1158 std::vector<std::string> fieldFileNames;
1159 MEDCoupling::MeshFormatWriter writer;
1160 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = MEDCoupling::MEDFileData::New(medFileIn);
1161 MEDCoupling::MEDFileMeshes* meshes = mfd->getMeshes();
1162 MEDCoupling::MEDFileMesh* fileMesh = meshes->getMeshAtPos(0); // ok only one mesh in file!
1163 if (meshNameOut =="")
1164 meshNameOut = fileMesh->getName();
1165 storeGroupsAndFams(fileMesh);
1167 MEDCoupling::MCAuto<MEDCoupling::MEDFileFields> fields = MEDCoupling::MEDFileFields::New();
1168 solFormatFieldFileName = getFileName();
1169 solFormatFieldFileName+=".sol";
1170 fieldFileNames.push_back(solFormatFieldFileName);
1172 if (useBackgroundMap)
1174 meshFormatsizeMapFile = getFileName();
1175 meshFormatsizeMapFile += ".mesh";
1176 buildBackGroundMeshAndSolFiles(fieldFileNames, meshFormatsizeMapFile);
1178 else if(useLocalMap)
1180 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeFieldMultiTS> fts = dynamic_cast<MEDCoupling::MEDFileFieldMultiTS *>( mfd->getFields()->getFieldWithName(fieldName) );
1181 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeField1TS> f = fts->getTimeStep(timeStep, rank);
1182 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> tmFts = MEDCoupling::MEDFileFieldMultiTS::New();
1183 tmFts->pushBackTimeStep(f);
1185 fields->pushField(tmFts);
1187 writer.setFieldFileNames( fieldFileNames);
1191 MEDCoupling::MCAuto<MEDCoupling::MEDCouplingMesh> mesh = fileMesh->getMeshAtLevel(1); // nodes mesh
1192 MEDCoupling::MCAuto<MEDCoupling::MEDCouplingUMesh> umesh = mesh->buildUnstructured(); // nodes mesh
1193 int dim = umesh->getSpaceDimension();
1194 int version = sizeof(double) < 8 ? 1 : 2;
1195 mcIdType nbNodes = umesh->getNumberOfNodes();
1196 buildConstantSizeMapSolFile(solFormatFieldFileName, dim, version, nbNodes);
1199 mfd->setFields( fields );
1200 meshFormatMeshFileName = getFileName();
1201 meshFormatMeshFileName+=".mesh";
1202 writer.setMeshFileName(meshFormatMeshFileName);
1203 writer.setMEDFileDS( mfd);
1208 void MgAdapt::convertMeshFile(std::string& meshFormatIn, std::vector< std::string>& solFieldFileNames) const
1210 MEDCoupling::MeshFormatReader reader(meshFormatIn, solFieldFileNames);
1212 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = reader.loadInMedFileDS();
1214 MEDCoupling::MEDFileMeshes* meshes = mfd->getMeshes();
1215 MEDCoupling::MEDFileMesh* fileMesh = meshes->getMeshAtPos(0); // ok only one mesh in file!
1216 fileMesh->setName(meshNameOut);
1217 restoreGroupsAndFams(fileMesh);
1218 mfd->write(medFileOut, 2);
1221 void MgAdapt::storeGroupsAndFams(MEDCoupling::MEDFileMesh* fileMesh)
1223 storefams(fileMesh);
1224 storeGroups(fileMesh);
1227 void MgAdapt::restoreGroupsAndFams(MEDCoupling::MEDFileMesh* fileMesh) const
1229 restorefams(fileMesh);
1230 restoreGroups(fileMesh);
1232 void MgAdapt::storeGroups(MEDCoupling::MEDFileMesh* fileMesh)
1234 std::map<std::string, std::vector<std::string> > grpFams = fileMesh->getGroupInfo();
1235 std::map<std::string, std::vector<std::string> >::iterator g2ff = grpFams.begin();
1237 for ( ; g2ff != grpFams.end(); ++g2ff )
1239 std::string groupName = g2ff->first;
1240 std::vector<std::string> famNames = g2ff->second;
1242 if ( famNames.empty() ) continue;
1244 std::vector< mcIdType> famListId;
1245 for ( size_t i = 0; i < famNames.size(); ++i )
1247 famListId.push_back( fileMesh->getFamilyId( famNames[i].c_str() ) );
1249 group grp(groupName, famListId, famNames);
1250 groupVec.push_back(grp);
1254 void MgAdapt::storefams(MEDCoupling::MEDFileMesh* fileMesh)
1256 std::map<std::string, mcIdType> grpFams = fileMesh->getFamilyInfo();
1257 std::map<std::string, mcIdType >::iterator f = grpFams.begin();
1259 for ( ; f != grpFams.end(); ++f )
1261 if(!f->second) continue; // FAMILLE_ZERO
1262 family fs(f->first, f->second);
1263 famVec.push_back(fs);
1268 void MgAdapt::restorefams(MEDCoupling::MEDFileMesh* fileMesh) const
1270 std::vector<family>::const_iterator fIt = famVec.begin();
1272 for (; fIt!=famVec.end(); ++fIt)
1276 std::string givenFamNameFromMeshGemConverter = fileMesh->getFamilyNameGivenId( std::abs(fIt->_famId) );
1277 fileMesh->changeFamilyId(std::abs(fIt->_famId), fIt->_famId);
1278 fileMesh->changeFamilyName(givenFamNameFromMeshGemConverter, fIt->_famName);
1280 catch (const std::exception& e)
1282 std::cerr<<e.what();
1287 void MgAdapt::restoreGroups(MEDCoupling::MEDFileMesh* fileMesh) const
1289 std::map<std::string, std::vector<std::string> > info;
1290 std::vector <group>::const_iterator grpFams = groupVec.begin();
1292 for (; grpFams!=groupVec.end(); ++grpFams)
1294 info.insert(std::pair <std::string, std::vector<std::string> > (grpFams->_name, grpFams->_famNames) );
1297 fileMesh->setGroupInfo(info);
1300 void MgAdapt::buildConstantSizeMapSolFile(const std::string& solFormatFieldFileName, const int dim, const int version, const mcIdType nbNodes) const
1302 MeshFormat::Localizer loc;
1303 MeshFormat::MeshFormatParser writer;
1304 int fileId = writer.GmfOpenMesh( solFormatFieldFileName.c_str(), GmfWrite, version, dim);
1305 int typTab[] = {GmfSca};
1306 writer.GmfSetKwd(fileId, MeshFormat::GmfSolAtVertices, (int)nbNodes, 1, typTab);
1307 for (mcIdType i = 0; i<nbNodes; i++)
1309 double valTab[1] = {constantValue};
1310 writer.GmfSetLin( fileId, MeshFormat::GmfSolAtVertices, valTab);
1312 writer.GmfCloseMesh(fileId);
1315 void MgAdapt::buildBackGroundMeshAndSolFiles(const std::vector<std::string>& fieldFileNames, const std::string& meshFormatsizeMapFile) const
1317 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> tmpMfd = MEDCoupling::MEDFileData::New(sizeMapFile);
1318 MEDCoupling::MEDFileFields* tmpFields = tmpMfd->getFields();
1319 MEDCoupling::MEDFileAnyTypeFieldMultiTS* fts = tmpFields->getFieldWithName(fieldName);
1320 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> fts1 = dynamic_cast<MEDCoupling::MEDFileFieldMultiTS *>(fts);
1321 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeField1TS> f = fts1->getTimeStep(timeStep, rank);
1322 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> tmFts = MEDCoupling::MEDFileFieldMultiTS::New();
1323 tmFts->pushBackTimeStep(f);
1325 MEDCoupling::MCAuto<MEDCoupling::MEDFileFields> tmp_fields = MEDCoupling::MEDFileFields::New();
1326 tmp_fields->pushField(tmFts);
1328 tmpMfd->setFields( tmp_fields );
1329 MEDCoupling::MeshFormatWriter tmpWriter;
1330 tmpWriter.setMeshFileName(meshFormatsizeMapFile);
1331 tmpWriter.setFieldFileNames( fieldFileNames);
1332 tmpWriter.setMEDFileDS(tmpMfd);
1335 // =======================================================================
1336 med_idt MgAdapt::openMedFile(const std::string aFile)
1337 // =======================================================================
1338 // renvoie le medId associe au fichier Med apres ouverture
1340 med_idt medIdt = MEDfileOpen(aFile.c_str(),MED_ACC_RDONLY);
1343 SALOME::ExceptionStruct es;
1344 es.type = SALOME::BAD_PARAM;
1345 std::string text = "The med file " + aFile + " cannot be opened." ;
1346 // es.text = "The mesh file does not exist.";
1347 es.text = CORBA::string_dup(text.c_str());
1348 throw SALOME::SALOME_Exception(es);
1354 MgAdapt::Status MgAdapt::addMessage(const std::string& msg,
1355 const bool isFatal/*=false*/)
1358 _myErrorMessages.clear(); // warnings are useless if a fatal error encounters
1360 _myErrorMessages.push_back( msg );
1364 std::cout << msg << std::endl;
1366 return ( _myStatus = isFatal ? MgAdapt::DRS_FAIL : MgAdapt::DRS_WARN_SKIP_ELEM );
1369 // =======================================================================
1370 void MgAdapt::getTimeStepInfos(std::string aFile, med_int& numdt, med_int& numit)
1371 // =======================================================================
1373 // Il faut voir si plusieurs maillages
1379 // Ouverture du fichier
1380 //~SCRUTE(aFile.toStdString());
1381 medIdt = openMedFile(aFile);
1382 if ( medIdt < 0 ) return ;
1383 // Lecture du nombre de champs
1384 med_int ncha = MEDnField(medIdt) ;
1387 //~addMessage( ToComment(" error: there is no field in ") << aFile, /*fatal=*/true );
1390 // Lecture des caracteristiques du champs
1392 // Lecture du type du champ, des noms des composantes et du nom de l'unite
1393 char nomcha [MED_NAME_SIZE+1];
1394 strcpy(nomcha, fieldName.c_str());
1395 // Lecture du nombre de composantes
1396 med_int ncomp = MEDfieldnComponentByName(medIdt, nomcha);
1397 char meshname[MED_NAME_SIZE+1];
1398 char * comp = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
1399 char * unit = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
1400 char dtunit[MED_SNAME_SIZE+1];
1402 med_field_type typcha;
1404 erreur = MEDfieldInfoByName (medIdt, nomcha, meshname,&local,&typcha,comp,unit,dtunit, &nbofcstp);
1409 //~addMessage( ToComment(" error: error while reading field ") << nomcha << " in file " << aFile , /*fatal=*/true );
1414 med_int tmp_numdt, tmp_numit;
1416 //~med_int step = data->myUseLastTimeStep ? nbofcstp : data->myTimeStep+1;
1417 //~myPrint("step ", step);
1418 erreur = MEDfieldComputingStepInfo ( medIdt, nomcha, 1, &numdt, &numit, &dt );
1419 for(med_int step = 1; step <= nbofcstp; step++ )
1421 erreur = MEDfieldComputingStepInfo ( medIdt, nomcha, step, &tmp_numdt, &tmp_numit, &dt );
1422 if(tmp_numdt > numdt)
1430 //~addMessage( ToComment(" error: error while reading field ") << nomcha << "step (numdt, numit) = " <<"("<< numdt<< ", " \
1431 numit<< ")" <<" in file " << aFile , /*fatal=*/true );
1435 // Fermeture du fichier
1436 if ( medIdt > 0 ) MEDfileClose(medIdt);
1440 void MgAdapt::updateTimeStepRank()
1445 if (myUseNoTimeStep)
1449 setRankTimeStep((int)tmst, (int)arank);
1451 else if (myUseLastTimeStep)
1453 std::string fieldFile = useBackgroundMap ? sizeMapFile : medFileIn;
1454 getTimeStepInfos(fieldFile, tmst, arank);
1455 setRankTimeStep((int)tmst, (int)arank);