1 // Copyright (C) 2020-2021 CEA/DEN, EDF R&D
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #include "MG_ADAPT.hxx"
22 #include <DriverGMF_Read.hxx>
23 #include <SMESH_Comment.hxx>
24 #include <SMESH_File.hxx>
25 #include <SMESH_MGLicenseKeyGen.hxx>
26 #include <SMESH_TypeDefs.hxx>
28 #include <MEDFileData.hxx>
29 #include <MEDFileField.hxx>
30 #include <MEDFileMesh.hxx>
31 #include <MeshFormatReader.hxx>
32 #include <MeshFormatWriter.hxx>
34 #include <Utils_SALOME_Exception.hxx>
35 #include <Basics_Utils.hxx>
36 #include "SMESH_TypeDefs.hxx"
39 #include <unistd.h> // getpid()
45 #include <memory> // unique_ptr
47 typedef SMESH_Comment ToComment;
49 using namespace MG_ADAPT;
50 static std::string removeFile(std::string fileName, int& notOk)
53 notOk = std::remove(fileName.c_str());
54 if (notOk) errStr = ToComment("\n error while removing file : ") << fileName;
55 else errStr = ToComment("\n file : ") << fileName << " succesfully deleted! \n ";
59 std::string MG_ADAPT::remove_extension(const std::string& filename)
61 size_t lastdot = filename.find_last_of(".");
62 if (lastdot == std::string::npos) return filename;
63 return filename.substr(0, lastdot);
68 bool isFileExist( const std::string& fName )
70 return SMESH_File( fName ).exists();
73 // =======================================================================
74 med_idt openMedFile(const std::string aFile)
75 // =======================================================================
76 // renvoie le medId associe au fichier Med apres ouverture
78 med_idt medIdt = MEDfileOpen(aFile.c_str(),MED_ACC_RDONLY);
81 THROW_SALOME_EXCEPTION("\nThe med file " << aFile << " cannot be opened.\n");
86 // =======================================================================
87 void getTimeStepInfos(std::string aFile, med_int& numdt, med_int& numit, std::string fieldName)
88 // =======================================================================
90 // Il faut voir si plusieurs maillages
95 // Ouverture du fichier
96 //~SCRUTE(aFile.toStdString());
97 medIdt = openMedFile(aFile);
98 if ( medIdt < 0 ) return ;
99 // Lecture du nombre de champs
100 med_int ncha = MEDnField(medIdt) ;
103 //~addMessage( ToComment(" error: there is no field in ") << aFile, /*fatal=*/true );
106 // Lecture des caracteristiques du champs
108 // Lecture du type du champ, des noms des composantes et du nom de l'unite
109 char nomcha [MED_NAME_SIZE+1];
110 strcpy(nomcha, fieldName.c_str());
111 // Lecture du nombre de composantes
112 med_int ncomp = MEDfieldnComponentByName(medIdt, nomcha);
113 char meshname[MED_NAME_SIZE+1];
114 char * comp = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
115 char * unit = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
116 char dtunit[MED_SNAME_SIZE+1];
118 med_field_type typcha;
120 erreur = MEDfieldInfoByName (medIdt, nomcha, meshname,&local,&typcha,comp,unit,dtunit, &nbofcstp);
125 //~addMessage( ToComment(" error: error while reading field ") << nomcha << " in file " << aFile , /*fatal=*/true );
130 med_int tmp_numdt, tmp_numit;
132 //~med_int step = data->myUseLastTimeStep ? nbofcstp : data->myTimeStep+1;
133 //~myPrint("step ", step);
134 erreur = MEDfieldComputingStepInfo ( medIdt, nomcha, 1, &numdt, &numit, &dt );
135 for( int step = 1; step <= nbofcstp; step++ )
137 erreur = MEDfieldComputingStepInfo ( medIdt, nomcha, step, &tmp_numdt, &tmp_numit, &dt );
138 if(tmp_numdt > numdt)
146 //~addMessage( ToComment(" error: error while reading field ") << nomcha << "step (numdt, numit) = " <<"("<< numdt<< ", "
147 //numit<< ")" <<" in file " << aFile , /*fatal=*/true );
151 // Fermeture du fichier
152 if ( medIdt > 0 ) MEDfileClose(medIdt);
156 struct GET_DEFAULT // struct used to get default value from GetOptionValue()
164 class outFileStream : public std::ofstream{
166 ~outFileStream(){close();} //to close file at dtor
169 } // anonymous namespace
171 //----------------------------------------------------------------------------------------
174 data = new MgAdaptHypothesisData();
175 data->myInMeshName = "";
176 data->fromMedFile = defaultFromMedFile();
177 data->myFileInDir = defaultWorkingDirectory();
178 data->myMeshFileIn = "";
179 data->myFileOutDir = defaultWorkingDirectory();
180 data->myOutMeshName = "";
181 data->myMeshFileOut = "";
182 data->myMeshOutMed = defaultMeshOutMed();
183 data->myPublish = defaultPublish();
184 data->myUseLocalMap = defaultUseLocalMap();
185 data->myUseBackgroundMap = defaultUseBackgroundMap();
186 data->myFileSizeMapDir = defaultWorkingDirectory();
187 data->myMeshFileBackground = "";
188 data->myUseConstantValue = defaultUseConstantValue();
189 data->myConstantValue = 0.0;
190 data->myFieldName = "";
191 data->myUseNoTimeStep = defaultUseNoTimeStep();
192 data->myUseLastTimeStep = defaultUseLastTimeStep();
193 data->myUseChosenTimeStep = defaultUseChosenTimeStep();
194 data->myTimeStep = -2;
196 data->myWorkingDir = defaultWorkingDirectory();
197 data->myLogFile = defaultLogFile();
198 data->myVerboseLevel = defaultVerboseLevel();
199 data->myPrintLogInFile = defaultPrintLogInFile();
200 data->myKeepFiles = defaultKeepFiles();
201 data->myRemoveLogOnSuccess = defaultRemoveLogOnSuccess();
206 MgAdapt::MgAdapt(MgAdaptHypothesisData* myData)
208 data = new MgAdaptHypothesisData();
213 MgAdapt::MgAdapt( const MgAdapt& copy)
215 data = new MgAdaptHypothesisData();
216 MgAdaptHypothesisData *copyData = copy.getData();
217 copyMgAdaptHypothesisData(copyData);
220 this->_option2value = copy._option2value;
221 this->_customOption2value = copy._customOption2value;
222 this->_defaultOptionValues = copy._defaultOptionValues;
223 this->_doubleOptions = copy._doubleOptions;
224 this->_charOptions = copy._charOptions;
225 this->_boolOptions = copy._boolOptions;
228 //-----------------------------------------------------------------------------------------
233 void MgAdapt::buildModel()
236 const char* boolOptionNames[] = { "compute_ridges", // yes
239 // const char* intOptionNames[] = { "max_number_of_errors_printed", // 1
240 // "max_number_of_threads", // 4
243 const char* doubleOptionNames[] = { "max_memory", // 0
246 const char* charOptionNames[] = { "components", // "yes"
247 "adaptation", // both
252 while (boolOptionNames[i][0])
254 _boolOptions.insert( boolOptionNames[i] );
255 _option2value[boolOptionNames[i++]].clear();
258 // while (intOptionNames[i][0])
259 // _option2value[intOptionNames[i++]].clear();
262 while (doubleOptionNames[i][0]) {
263 _doubleOptions.insert(doubleOptionNames[i]);
264 _option2value[doubleOptionNames[i++]].clear();
267 while (charOptionNames[i][0]) {
268 _charOptions.insert(charOptionNames[i]);
269 _option2value[charOptionNames[i++]].clear();
272 // default values to be used while MG-Adapt
274 _defaultOptionValues["adaptation" ] = "both";
275 _defaultOptionValues["components" ] = "outside components";
276 _defaultOptionValues["compute_ridges"] = "yes";
277 _defaultOptionValues["max_memory" ] = ToComment(defaultMaximumMemory());
280 //=============================================================================
281 TOptionValues MgAdapt::getOptionValues() const
284 TOptionValues::const_iterator op_val = _option2value.begin();
285 for ( ; op_val != _option2value.end(); ++op_val )
286 vals.insert( make_pair( op_val->first, getOptionValue( op_val->first, GET_DEFAULT() )));
291 std::vector <std::string> MgAdapt::getOptionValuesStrVec() const
293 std::vector <std::string> vals;
294 TOptionValues::const_iterator op_val = _option2value.begin();
295 for ( ; op_val != _option2value.end(); ++op_val )
296 vals.push_back(op_val->first+":"+getOptionValue( op_val->first, GET_DEFAULT() ));
301 std::vector <std::string> MgAdapt::getCustomOptionValuesStrVec() const
303 std::vector <std::string> vals;
304 TOptionValues::const_iterator op_val;
305 for ( op_val = _customOption2value.begin(); op_val != _customOption2value.end(); ++op_val )
307 vals.push_back(op_val->first+":"+getOptionValue( op_val->first, GET_DEFAULT() ));
311 const TOptionValues& MgAdapt::getCustomOptionValues() const
313 return _customOption2value;
315 void MgAdapt::setData(MgAdaptHypothesisData* myData)
317 copyMgAdaptHypothesisData(myData);
320 MgAdaptHypothesisData* MgAdapt::getData() const
324 void MgAdapt::setMedFileIn(std::string fileName)
326 if ( isFileExist( fileName ))
328 medFileIn = fileName;
330 if (medFileOut == "") // default MED file Out
331 medFileOut = remove_extension( fileName )+ ".adapt.med";
335 THROW_SALOME_EXCEPTION("\nThe file "<< fileName <<" does not exist.\n");
339 std::string MgAdapt::getMedFileIn()
344 void MgAdapt::setMedFileOut(std::string fileOut)
346 medFileOut = fileOut;
348 std::string MgAdapt::getMedFileOut()
352 void MgAdapt::setMeshOutMed(bool mybool)
356 bool MgAdapt::getMeshOutMed()
360 void MgAdapt::setPublish(bool mybool)
364 bool MgAdapt::getPublish()
368 void MgAdapt::setFieldName(std::string myFieldName)
370 fieldName = myFieldName;
372 std::string MgAdapt::getFieldName()
376 void MgAdapt::setTimeStep(int time)
380 int MgAdapt::getTimeStep() const
385 void MgAdapt::setRankTimeStep(int time, int myRank)
391 int MgAdapt::getRank()
395 void MgAdapt::setTimeStepRankLast()
397 myUseLastTimeStep = true;
398 myUseChosenTimeStep = false;
399 myUseNoTimeStep = false;
400 //~med_int aRank, tmst;
401 //~std::string fieldFile = useBackgroundMap ? sizeMapFile : medFileIn;
402 //~getTimeStepInfos(fieldFile, tmst, aRank);
403 //~setRankTimeStep((int) tmst, (int) aRank);
405 void MgAdapt::setNoTimeStep()
407 myUseLastTimeStep = false;
408 myUseChosenTimeStep = false;
409 myUseNoTimeStep = true;
410 //~int aRank = (int)MED_NO_IT;
411 //~int tmst = (int)MED_NO_DT ;
412 //~setRankTimeStep(tmst, aRank);
414 void MgAdapt::setChosenTimeStepRank()
416 myUseLastTimeStep = false;
417 myUseChosenTimeStep = true;
418 myUseNoTimeStep = false;
419 //~int aRank = (int)MED_NO_IT;
420 //~int tmst = (int)MED_NO_DT ;
421 //~setRankTimeStep(tmst, aRank);
423 void MgAdapt::setUseLocalMap(bool myLocal)
425 useLocalMap = myLocal;
428 bool MgAdapt::getUseLocalMap()
433 void MgAdapt::setUseBackgroundMap(bool bckg)
435 useBackgroundMap = bckg;
438 bool MgAdapt::getUseBackgroundMap()
440 return useBackgroundMap;
443 void MgAdapt::setUseConstantValue(bool cnst)
445 useConstantValue = cnst;
447 bool MgAdapt::getUseConstantValue()
449 return useConstantValue;
451 void MgAdapt::setLogFile(std::string myLogFile)
455 std::string MgAdapt::getLogFile()
459 void MgAdapt::setVerbosityLevel(int verboLevel)
461 verbosityLevel = verboLevel;
463 int MgAdapt::getVerbosityLevel()
465 return verbosityLevel;
467 void MgAdapt::setRemoveOnSuccess(bool rmons)
469 removeOnSuccess = rmons;
471 bool MgAdapt::getRemoveOnSuccess()
473 return removeOnSuccess;
475 void MgAdapt::setSizeMapFile(std::string mapFile)
477 if ( mapFile == "" || isFileExist(mapFile) )
479 sizeMapFile = mapFile;
483 THROW_SALOME_EXCEPTION("\nThe file "<< mapFile <<" does not exist.\n");
486 std::string MgAdapt::getSizeMapFile()
491 void MgAdapt::setMeshName(std::string name)
495 std::string MgAdapt::getMeshName()
499 void MgAdapt::setMeshNameOut(std::string name)
503 std::string MgAdapt::getMeshNameOut()
507 void MgAdapt::setFromMedFile(bool mybool)
509 fromMedFile = mybool;
511 bool MgAdapt::isFromMedFile()
515 void MgAdapt::setConstantValue(double cnst)
517 constantValue = cnst;
519 double MgAdapt::getConstantValue() const
521 return constantValue;
524 void MgAdapt::setWorkingDir(std::string dir)
528 std::string MgAdapt::getWorkingDir() const
532 void MgAdapt::setKeepWorkingFiles(bool mybool)
534 toKeepWorkingFiles = mybool;
536 bool MgAdapt::getKeepWorkingFiles()
538 return toKeepWorkingFiles;
540 void MgAdapt::setPrintLogInFile(bool print)
542 printLogInFile = print;
544 bool MgAdapt::getPrintLogInFile()
546 return printLogInFile;
549 bool MgAdapt::setAll()
552 setFromMedFile(data->fromMedFile);
554 checkDirPath(data->myFileInDir);
555 file = data->myFileInDir+data->myMeshFileIn;
557 setMeshName(data->myInMeshName);
558 setMeshNameOut(data->myOutMeshName);
559 checkDirPath(data->myFileOutDir);
560 std::string out = data->myFileOutDir+data->myMeshFileOut;
562 setPublish(data->myPublish);
563 setMeshOutMed(data->myMeshOutMed);
564 setUseLocalMap(data->myUseLocalMap);
565 setUseBackgroundMap(data->myUseBackgroundMap);
566 setUseConstantValue(data->myUseConstantValue);
569 if (useBackgroundMap)
571 checkDirPath(data->myFileSizeMapDir);
572 mapfile = data->myFileSizeMapDir+data->myMeshFileBackground;
573 setFieldName(data->myFieldName);
575 else if (useConstantValue)
577 setConstantValue(data->myConstantValue);
582 setConstantValue(0.0);
583 setFieldName(data->myFieldName);
586 setSizeMapFile(mapfile);
587 if (data->myUseNoTimeStep)
589 else if (data->myUseLastTimeStep)
590 setTimeStepRankLast();
593 setChosenTimeStepRank();
594 setRankTimeStep(data->myTimeStep, data->myRank);
596 /* Advanced options */
597 setWorkingDir(data->myWorkingDir);
598 checkDirPath(data->myWorkingDir);
599 setLogFile(data->myWorkingDir+defaultLogFile());
600 setVerbosityLevel(data->myVerboseLevel);
601 setRemoveOnSuccess(data->myRemoveLogOnSuccess);
602 setPrintLogInFile(data->myPrintLogInFile);
603 setKeepWorkingFiles(data->myKeepFiles);
608 void MgAdapt::checkDirPath(std::string& dirPath)
610 const char lastChar = *dirPath.rbegin();
612 if(lastChar != '\\') dirPath+='\\';
614 if(lastChar != '/') dirPath+='/';
617 //=============================================================================
618 void MgAdapt::setOptionValue(const std::string& optionName,
619 const std::string& optionValue)
621 // INFOS("setOptionValue");
622 // std::cout << "optionName: " << optionName << ", optionValue: " << optionValue << std::endl;
623 TOptionValues::iterator op_val = _option2value.find(optionName);
624 if (op_val == _option2value.end())
626 op_val = _customOption2value.find( optionName );
627 _customOption2value[ optionName ] = optionValue;
631 if (op_val->second != optionValue)
633 std::string lowerOptionValue = toLowerStr(optionValue);
634 const char* ptr = lowerOptionValue.c_str();
635 // strip white spaces
636 while (ptr[0] == ' ')
638 size_t i = strlen(ptr);
639 while (i != 0 && ptr[i - 1] == ' ')
643 std::string typeName;
648 else if (_charOptions.count(optionName))
650 // do not check strings
652 else if (_doubleOptions.count(optionName))
654 // check if value is double
658 else if (_boolOptions.count(optionName))
660 // check if value is bool
661 toBool(ptr, &typeOk);
666 // check if value is int
668 typeName = "integer";
670 if ( typeOk ) // check some specific values ?
675 std::string msg = "Advanced option '" + optionName + "' = '" + optionValue + "' but must be " + typeName;
676 throw std::invalid_argument(msg);
678 std::string value( ptr, i );
679 // std::cout << "==> value: " << value << std::endl;
680 if ( _defaultOptionValues[ optionName ] == value ) value.clear();
682 // std::cout << "==> value: " << value << std::endl;
683 op_val->second = value;
686 //=============================================================================
687 //! Return option value. If isDefault provided, it can be a default value,
688 // then *isDefault == true. If isDefault is not provided, the value will be
689 // empty if it equals a default one.
690 std::string MgAdapt::getOptionValue(const std::string& optionName, bool* isDefault) const
692 // INFOS("getOptionValue");
693 // std::cout << "optionName: " << optionName << ", isDefault: " << isDefault << std::endl;
694 TOptionValues::const_iterator op_val = _option2value.find(optionName);
695 if (op_val == _option2value.end())
697 op_val = _customOption2value.find(optionName);
698 if (op_val == _customOption2value.end())
700 std::string msg = "Unknown MG-Adapt option: <" + optionName + ">";
701 throw std::invalid_argument(msg);
704 std::string val = op_val->second;
705 if ( isDefault ) *isDefault = ( val.empty() );
707 if ( val.empty() && isDefault )
709 op_val = _defaultOptionValues.find( optionName );
710 if (op_val != _defaultOptionValues.end()) val = op_val->second;
712 // std::cout << "==> val: " << val << std::endl;
716 //================================================================================
718 * \brief Converts a string to a real value
720 //================================================================================
722 double MgAdapt::toDbl(const std::string& str, bool* isOk )
724 if ( str.empty() ) throw std::invalid_argument("Empty value provided");
727 double val = strtod(&str[0], &endPtr);
728 bool ok = (&str[0] != endPtr);
730 if ( isOk ) *isOk = ok;
734 std::string msg = "Not a real value:'" + str + "'";
735 throw std::invalid_argument(msg);
739 //================================================================================
741 * \brief Converts a string to a lower
743 //================================================================================
744 std::string MgAdapt::toLowerStr(const std::string& str)
747 for ( size_t i = 0; i <= s.size(); ++i )
748 s[i] = (char) tolower( s[i] );
751 //================================================================================
753 * \brief Converts a string to a bool
755 //================================================================================
757 bool MgAdapt::toBool(const std::string& str, bool* isOk )
760 if ( isOk ) *isOk = true;
762 for ( size_t i = 0; i <= s.size(); ++i )
763 s[i] = (char) tolower( s[i] );
765 if ( s == "1" || s == "true" || s == "active" || s == "yes" )
768 if ( s == "0" || s == "false" || s == "inactive" || s == "no" )
775 std::string msg = "Not a Boolean value:'" + str + "'";
776 throw std::invalid_argument(msg);
780 //================================================================================
782 * \brief Converts a string to a integer value
784 //================================================================================
786 int MgAdapt::toInt(const std::string& str, bool* isOk )
788 if ( str.empty() ) throw std::invalid_argument("Empty value provided");
791 int val = (int)strtol( &str[0], &endPtr, 10);
792 bool ok = (&str[0] != endPtr);
794 if ( isOk ) *isOk = ok;
798 std::string msg = "Not an integer value:'" + str + "'";
799 throw std::invalid_argument(msg);
803 //=============================================================================
804 bool MgAdapt::hasOptionDefined( const std::string& optionName ) const
806 bool isDefault = false;
809 getOptionValue( optionName, &isDefault );
811 catch ( std::invalid_argument )
817 //================================================================================
819 * \brief Return command to run MG-Adapt mesher excluding file prefix (-f)
821 //================================================================================
823 std::string MgAdapt::getCommandToRun(MgAdapt* hyp)
825 return hyp ? hyp->getCommandToRun() : ToComment("error with hypothesis!");
828 int MgAdapt::compute(std::string& errStr)
830 std::string cmd = getCommandToRun();
831 // std::cout << cmd << std::endl;
834 execCmd( cmd.c_str(), err ); // run
838 errStr = ToComment("system(mg-adapt.exe ...) command failed with error: ") << strerror( errno );
840 else if ( !isFileExist( meshFormatOutputMesh ))
842 errStr = ToComment(" failed to find file ") << meshFormatOutputMesh
843 << " output from MG-Adapt run";
847 convertMeshFile(meshFormatOutputMesh, solFormatOutput);
853 void MgAdapt::execCmd( const char* cmd, int& err)
856 std::array <char, 128> buffer;
858 outFileStream fileStream;
861 fileStream.open(logFile);
862 buf = fileStream.rdbuf();
866 buf = std::cout.rdbuf();
868 std::ostream logStream(buf);
872 # if defined(UNICODE)
873 const wchar_t * aCmd = Kernel_Utils::utf8_decode(cmd);
874 SMESHUtils::ArrayDeleter<const wchar_t> deleter( aCmd );
875 std::unique_ptr <FILE, decltype(&_pclose)> pipe(_wpopen(aCmd, O_RDONLY), _pclose );
877 std::unique_ptr <FILE, decltype(&_pclose)> pipe(_popen(cmd, "r"), _pclose );
880 std::unique_ptr <FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose );
885 throw std::runtime_error("popen() failed!");
887 while(fgets(buffer.data(), buffer.size(), pipe.get()) !=nullptr )
889 logStream<<buffer.data() ;
894 * to delete tmp files .mesh, .sol and if needed
898 void MgAdapt::cleanUp()
902 if(toKeepWorkingFiles)
904 if(removeOnSuccess && printLogInFile)
905 tmpFilesToBeDeleted.push_back(logFile);
907 std::vector< std::string>::iterator it = tmpFilesToBeDeleted.begin();
908 for (; it!=tmpFilesToBeDeleted.end(); ++it)
910 errStr=removeFile(*it, notOk);
913 appendMsgToLogFile(errStr);
919 void MgAdapt::appendMsgToLogFile(std::string& msg)
921 std::ofstream logStream;
922 logStream.open(logFile, std::ofstream::out | std::ofstream::app);
926 //================================================================================
928 * \brief Return command to run MG-Tetra mesher excluding file prefix (-f)
930 //================================================================================
932 std::string MgAdapt::getCommandToRun()
935 || return system command with args and options
939 std::string cmd = getExeName();
940 std::string meshIn(""), sizeMapIn(""), solFileIn("");
941 updateTimeStepRank();
942 convertMedFile(meshIn, solFileIn, sizeMapIn);
943 if (!isFileExist(meshIn) || !isFileExist(solFileIn))
945 errStr = ToComment(" failed to find .mesh or .sol file from converter ")<< strerror( errno );
948 tmpFilesToBeDeleted.push_back(meshIn);
949 tmpFilesToBeDeleted.push_back(solFileIn);
950 if(useBackgroundMap && !isFileExist(sizeMapIn))
952 errStr = ToComment(" failed to find .mesh size map file from converter ")<< strerror( errno );
956 cmd+= " --in "+ meshIn;
957 meshFormatOutputMesh = getFileName()+".mesh";
958 tmpFilesToBeDeleted.push_back(meshFormatOutputMesh);
959 cmd+= " --out "+ meshFormatOutputMesh;
960 if (useLocalMap || useConstantValue) cmd+= " --sizemap "+ solFileIn;
961 else // (useBackgroundMap)
963 cmd+= " --background_mesh "+ sizeMapIn ;
964 cmd+= " --background_sizemap "+ solFileIn;
965 tmpFilesToBeDeleted.push_back(sizeMapIn);
969 //~// constant value TODO
971 // Check coherence between mesh dimension and option fo adaptation
972 checkDimensionOptionAdaptation();
974 // sizemap file is written only if level is higher than 3
975 if ( verbosityLevel > 3)
977 std::string solFileOut = getFileName()+".sol";
978 cmd+= " --write_sizemap "+ solFileOut;
979 solFormatOutput.push_back(solFileOut);
980 tmpFilesToBeDeleted.push_back(solFileOut);
983 std::string option, value;
985 const TOptionValues* options[] = { &_option2value, &_customOption2value };
986 for ( int iOp = 0; iOp < 2; ++iOp )
988 TOptionValues::const_iterator o2v = options[iOp]->begin();
989 for ( ; o2v != options[iOp]->end(); ++o2v )
992 value = getOptionValue( option, &isDefault );
996 if ( value.empty() )//value == NoValue() )
998 if ( _defaultOptionValues.count( option ))
999 continue; // non-custom option with no value
1002 if ( strncmp( "no", option.c_str(), 2 ) == 0 ) // options w/o values: --no_*
1004 if ( !value.empty() && toBool( value ) == false )
1008 if ( option[0] != '-' )
1012 // std::cout << "--- option: '" << option << ", value: '" << value <<"'"<< std::endl;
1013 cmd += option + " " + value;
1018 if (verbosityLevel != defaultVerboseLevel())
1020 cmd+= " --verbose "+ ToComment(verbosityLevel);
1024 smIdType nbVertex, nbEdge, nbFace, nbVol;
1025 DriverGMF_Read gmfReader;
1026 gmfReader.SetFile( meshIn );
1027 gmfReader.GetMeshInfo( nbVertex, nbEdge, nbFace, nbVol );
1029 std::string errorTxt;
1030 std::string key = SMESHUtils_MGLicenseKeyGen::GetKey( meshIn,
1031 FromSmIdType<int>( nbVertex ),
1032 FromSmIdType<int>( nbEdge ),
1033 FromSmIdType<int>( nbFace ),
1034 FromSmIdType<int>( nbVol ),
1037 return ToComment( "Problem with library SalomeMeshGemsKeyGenerator: " + errorTxt );
1039 cmd += " --key " + key;
1045 // std::cout << "--- cmd :"<< std::endl;
1046 // std::cout << cmd << std::endl;
1051 //=======================================================================
1052 //function : defaultMaximumMemory
1053 //=======================================================================
1056 #include <windows.h>
1057 #elif !defined(__APPLE__)
1058 #include <sys/sysinfo.h>
1061 double MgAdapt::defaultMaximumMemory()
1064 // See http://msdn.microsoft.com/en-us/library/aa366589.aspx
1065 MEMORYSTATUSEX statex;
1066 statex.dwLength = sizeof (statex);
1067 long err = GlobalMemoryStatusEx (&statex);
1070 double totMB = (double)statex.ullAvailPhys / 1024. / 1024.;
1071 return (double)( 0.7 * totMB );
1073 #elif !defined(__APPLE__)
1075 long err = sysinfo( &si );
1078 long ramMB = si.totalram * si.mem_unit / 1024 / 1024;
1079 return ( 0.7 * double( ramMB ));
1085 //=======================================================================
1086 //function : defaultWorkingDirectory
1087 //=======================================================================
1089 std::string MgAdapt::defaultWorkingDirectory()
1091 std::string aTmpDir;
1093 char *Tmp_dir = getenv("SALOME_TMP_DIR");
1099 if ( ! isFileExist( aTmpDir ))
1109 //================================================================================
1111 * \brief Return a unique file name
1113 //================================================================================
1115 std::string MgAdapt::getFileName() const
1117 std::string aTmpDir = workingDir;
1118 const char lastChar = *aTmpDir.rbegin();
1120 if(lastChar != '\\') aTmpDir+='\\';
1122 if(lastChar != '/') aTmpDir+='/';
1125 SMESH_Comment aGenericName( aTmpDir );
1126 aGenericName << "MgAdapt_";
1128 aGenericName << getpid();
1130 aGenericName << _getpid();
1132 aGenericName << "_";
1133 aGenericName << std::abs((int)(long) aGenericName.data());
1135 return aGenericName;
1137 //=======================================================================
1138 //function : defaultLogFile
1139 //=======================================================================
1141 std::string MgAdapt::defaultLogFile()
1143 std::string alogFile("MG_ADAPT.log");
1146 //=======================================================================
1147 //function : defaultUseConstantValue
1148 //=======================================================================
1150 bool MgAdapt::defaultUseConstantValue()
1154 //=======================================================================
1155 //function : defaultUseNoTimeStep
1156 //=======================================================================
1158 bool MgAdapt::defaultUseNoTimeStep()
1162 //=======================================================================
1163 //function : defaultRemoveLogOnSuccess
1164 //=======================================================================
1166 bool MgAdapt::defaultRemoveLogOnSuccess()
1170 //=======================================================================
1171 //function : defaultPrintLogInFile
1172 //=======================================================================
1174 bool MgAdapt::defaultPrintLogInFile()
1178 //=======================================================================
1179 //function : defaultUseChosenTimeStep
1180 //=======================================================================
1182 bool MgAdapt::defaultUseChosenTimeStep()
1186 //=======================================================================
1187 //function : UseLastTimeStep
1188 //=======================================================================
1190 bool MgAdapt::defaultUseLastTimeStep()
1194 //=======================================================================
1195 //function : defaultUseBackgroundMap
1196 //=======================================================================
1198 bool MgAdapt::defaultUseBackgroundMap()
1202 //=======================================================================
1203 //function : defaultKeepFiles
1204 //=======================================================================
1206 bool MgAdapt::defaultKeepFiles()
1210 //=======================================================================
1211 //function : defaultUseLocalMap
1212 //=======================================================================
1214 bool MgAdapt::defaultUseLocalMap()
1218 //=======================================================================
1219 //function : defaultPublish
1220 //=======================================================================
1222 bool MgAdapt::defaultPublish()
1226 //=======================================================================
1227 //function : defaultMeshOutMed
1228 //=======================================================================
1230 bool MgAdapt::defaultMeshOutMed()
1234 //=======================================================================
1235 //function : defaultFromMedFile
1236 //=======================================================================
1238 bool MgAdapt::defaultFromMedFile()
1242 //=======================================================================
1243 //function : defaultVerboseLevel
1244 //=======================================================================
1246 int MgAdapt::defaultVerboseLevel()
1250 std::string MgAdapt::getExeName()
1252 return "mg-adapt.exe";
1254 void MgAdapt::copyMgAdaptHypothesisData( const MgAdaptHypothesisData* from)
1256 data->myFileInDir = from->myFileInDir;
1257 data->myMeshFileIn = from->myMeshFileIn;
1258 data->myMeshFileBackground = from->myMeshFileBackground;
1259 data->myOutMeshName = from->myOutMeshName;
1260 data->myMeshFileOut = from->myMeshFileOut;
1261 data->myFileOutDir = from->myFileOutDir;
1262 data->myFileSizeMapDir = from->myFileSizeMapDir;
1263 data->myFieldName = from->myFieldName;
1264 data->fromMedFile = from->fromMedFile;
1265 data->myPublish = from->myPublish;
1266 data->myMeshOutMed = from->myMeshOutMed;
1267 data->myUseLocalMap = from->myUseLocalMap;
1268 data->myUseBackgroundMap = from->myUseBackgroundMap;
1269 data->myUseConstantValue = from->myUseConstantValue;
1270 data->myConstantValue = from->myConstantValue;
1271 data->myTimeStep = from->myTimeStep;
1272 data->myRank = from->myRank;
1273 data->myUseNoTimeStep = from->myUseNoTimeStep;
1274 data->myUseLastTimeStep = from->myUseLastTimeStep;
1275 data->myUseChosenTimeStep = from->myUseChosenTimeStep;
1276 data->myWorkingDir = from->myWorkingDir;
1277 data->myLogFile = from->myLogFile;
1278 data->myPrintLogInFile = from->myPrintLogInFile;
1279 data->myKeepFiles = from->myKeepFiles;
1280 data->myRemoveLogOnSuccess = from->myRemoveLogOnSuccess;
1281 data->myVerboseLevel = from->myVerboseLevel;
1284 std::vector<std::string> MgAdapt::getListFieldsNames(std::string fileIn)
1286 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = MEDCoupling::MEDFileData::New(fileIn);
1287 std::vector<std::string> listFieldsNames(mfd->getFields()->getFieldsNames());
1288 return listFieldsNames ;
1291 void MgAdapt::checkDimensionOptionAdaptation()
1293 // Quand le maillage est 3D, tout est possible
1294 // Quand le maillage est 2D, il faut 'surface' sauf si carte de fonds 3D
1295 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = MEDCoupling::MEDFileData::New(medFileIn);
1296 int meshdim = mfd->getMeshes()->getMeshAtPos(0)->getMeshDimension() ;
1297 // std::cout << "meshdim = " << meshdim << std::endl;
1301 std::string optionName = "adaptation";
1302 std::string optionValue = getOptionValue(optionName);
1303 // std::cout << "optionValue = '" << optionValue <<"'"<< std::endl;
1304 bool a_tester = false ;
1305 // carte locale ou constante : impératif d'avoir "surface"
1306 if ( useLocalMap || useConstantValue) a_tester = true ;
1307 // carte de fond : impératif d'avoir "surface" si le fonds est aussi 2D
1310 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfdbg = MEDCoupling::MEDFileData::New(sizeMapFile);
1311 int meshdimbg = mfdbg->getMeshes()->getMeshAtPos(0)->getMeshDimension() ;
1312 // std::cout << "meshdimbg = " << meshdimbg << std::endl;
1313 if ( meshdimbg == 2 ) a_tester = true ;
1317 if ( optionValue == "" ) setOptionValue (optionName, "surface");
1320 if ( optionValue != "surface" )
1322 THROW_SALOME_EXCEPTION("Mesh dimension is 2; the option should be 'surface'"
1323 " instead of '" << optionValue << "'.");
1330 void MgAdapt::checkFieldName(std::string fileIn)
1333 std::vector<std::string> listFieldsNames = getListFieldsNames(fileIn);
1334 std::size_t jaux(listFieldsNames.size());
1335 for(std::size_t j=0;j<jaux;j++)
1337 if ( fieldName == listFieldsNames[j] )
1345 std::cout << "Available field names:" << std::endl;
1346 for(std::size_t j=0;j<jaux;j++)
1347 { std::cout << listFieldsNames[j] << std::endl;}
1348 THROW_SALOME_EXCEPTION( "Field " << fieldName << " is not found.");
1352 void MgAdapt::checkTimeStepRank(std::string fileIn)
1355 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = MEDCoupling::MEDFileData::New(fileIn);
1356 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeFieldMultiTS> fts( mfd->getFields()->getFieldWithName(fieldName) );
1357 std::vector<double> timevalue;
1358 std::vector< std::pair<int,int> > timesteprank = fts->getTimeSteps(timevalue);
1359 std::size_t jaux(timesteprank.size());
1360 for(std::size_t j=0;j<jaux;j++)
1362 if ( ( timeStep == timesteprank[j].first ) & ( rank == timesteprank[j].second ) )
1370 std::cout << "Available (Time step, Rank):" << std::endl;
1371 for(std::size_t j=0;j<jaux;j++)
1372 { std::cout << "(Time step = " << timesteprank[j].first << ", Rank = " << timesteprank[j].second << ")" << std::endl;}
1373 THROW_SALOME_EXCEPTION("(Time step = " << timeStep << ", Rank = " << rank << ") is not found.");
1377 void MgAdapt::convertMedFile(std::string& meshFormatMeshFileName, std::string& solFormatFieldFileName, std::string& meshFormatsizeMapFile)
1379 std::vector<std::string> fieldFileNames;
1380 MEDCoupling::MeshFormatWriter writer;
1381 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = MEDCoupling::MEDFileData::New(medFileIn);
1382 MEDCoupling::MEDFileMeshes* meshes = mfd->getMeshes();
1383 MEDCoupling::MEDFileMesh* fileMesh = meshes->getMeshAtPos(0); // ok only one mesh in file!
1384 if (meshNameOut =="")
1385 meshNameOut = fileMesh->getName();
1386 storeGroupsAndFams(fileMesh);
1388 MEDCoupling::MCAuto<MEDCoupling::MEDFileFields> fields = MEDCoupling::MEDFileFields::New();
1389 solFormatFieldFileName = getFileName();
1390 solFormatFieldFileName+=".sol";
1391 fieldFileNames.push_back(solFormatFieldFileName);
1393 if (useBackgroundMap)
1395 checkFieldName(sizeMapFile) ;
1396 checkTimeStepRank(sizeMapFile) ;
1397 meshFormatsizeMapFile = getFileName();
1398 meshFormatsizeMapFile += ".mesh";
1399 buildBackGroundMeshAndSolFiles(fieldFileNames, meshFormatsizeMapFile);
1401 else if(useLocalMap)
1403 checkFieldName(medFileIn) ;
1404 checkTimeStepRank(medFileIn) ;
1405 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeFieldMultiTS> fts( mfd->getFields()->getFieldWithName(fieldName) );
1406 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeField1TS> f = fts->getTimeStep(timeStep, rank);
1407 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> tmFts = MEDCoupling::DynamicCast<MEDCoupling::MEDFileAnyTypeFieldMultiTS,MEDCoupling::MEDFileFieldMultiTS>(fts);
1409 // if not able to cast to double field, try float field
1412 MEDCoupling::MCAuto<MEDCoupling::MEDFileFloatFieldMultiTS> tmFtsFloat = MEDCoupling::DynamicCast<MEDCoupling::MEDFileAnyTypeFieldMultiTS,MEDCoupling::MEDFileFloatFieldMultiTS>(fts);
1414 THROW_SALOME_EXCEPTION("\nUnexpected field type.\n");
1415 // convert float field to double
1416 tmFts = tmFtsFloat->convertToDouble();
1419 fields->pushField(tmFts);
1421 writer.setFieldFileNames( fieldFileNames);
1425 MEDCoupling::MCAuto<MEDCoupling::MEDCouplingMesh> mesh = fileMesh->getMeshAtLevel(1); // nodes mesh
1426 MEDCoupling::MCAuto<MEDCoupling::MEDCouplingUMesh> umesh = mesh->buildUnstructured(); // nodes mesh
1427 int dim = umesh->getSpaceDimension();
1428 int version = sizeof(double) < 8 ? 1 : 2;
1429 mcIdType nbNodes = umesh->getNumberOfNodes();
1430 buildConstantSizeMapSolFile(solFormatFieldFileName, dim, version, nbNodes);
1433 mfd->setFields( fields );
1434 meshFormatMeshFileName = getFileName();
1435 meshFormatMeshFileName+=".mesh";
1436 writer.setMeshFileName(meshFormatMeshFileName);
1437 writer.setMEDFileDS( mfd);
1442 void MgAdapt::convertMeshFile(std::string& meshFormatIn, std::vector< std::string>& solFieldFileNames) const
1444 MEDCoupling::MeshFormatReader reader(meshFormatIn, solFieldFileNames);
1446 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = reader.loadInMedFileDS();
1448 MEDCoupling::MEDFileMeshes* meshes = mfd->getMeshes();
1449 MEDCoupling::MEDFileMesh* fileMesh = meshes->getMeshAtPos(0); // ok only one mesh in file!
1450 fileMesh->setName(meshNameOut);
1451 restoreGroupsAndFams(fileMesh);
1452 mfd->write(medFileOut, 2);
1455 void MgAdapt::storeGroupsAndFams(MEDCoupling::MEDFileMesh* fileMesh)
1457 storefams(fileMesh);
1458 storeGroups(fileMesh);
1461 void MgAdapt::restoreGroupsAndFams(MEDCoupling::MEDFileMesh* fileMesh) const
1463 restorefams(fileMesh);
1464 restoreGroups(fileMesh);
1466 void MgAdapt::storeGroups(MEDCoupling::MEDFileMesh* fileMesh)
1468 std::map<std::string, std::vector<std::string> > grpFams = fileMesh->getGroupInfo();
1469 std::map<std::string, std::vector<std::string> >::iterator g2ff = grpFams.begin();
1471 for ( ; g2ff != grpFams.end(); ++g2ff )
1473 std::string groupName = g2ff->first;
1474 std::vector<std::string> famNames = g2ff->second;
1476 if ( famNames.empty() ) continue;
1477 std::vector< int> famListId;
1478 for ( size_t i = 0; i < famNames.size(); ++i )
1480 famListId.push_back( FromIdType<int>( fileMesh->getFamilyId( famNames[i].c_str() )));
1482 group grp(groupName, famListId, famNames);
1483 groupVec.push_back(grp);
1487 void MgAdapt::storefams(MEDCoupling::MEDFileMesh* fileMesh)
1489 std::map<std::string, mcIdType> grpFams = fileMesh->getFamilyInfo();
1490 std::map<std::string, mcIdType >::iterator f = grpFams.begin();
1492 for ( ; f != grpFams.end(); ++f )
1494 if(!f->second) continue; // FAMILLE_ZERO
1495 family fs(f->first, FromIdType<int>( f->second ));
1496 famVec.push_back(fs);
1501 void MgAdapt::restorefams(MEDCoupling::MEDFileMesh* fileMesh) const
1503 std::vector<family>::const_iterator fIt = famVec.begin();
1505 for (; fIt!=famVec.end(); ++fIt)
1509 std::string givenFamNameFromMeshGemConverter = fileMesh->getFamilyNameGivenId( std::abs(fIt->_famId) );
1510 fileMesh->changeFamilyId(std::abs(fIt->_famId), fIt->_famId);
1511 fileMesh->changeFamilyName(givenFamNameFromMeshGemConverter, fIt->_famName);
1513 catch (const std::exception& e)
1515 std::cerr<<e.what();
1520 void MgAdapt::restoreGroups(MEDCoupling::MEDFileMesh* fileMesh) const
1522 std::map<std::string, std::vector<std::string> > info;
1523 std::vector <group>::const_iterator grpFams = groupVec.begin();
1525 for (; grpFams!=groupVec.end(); ++grpFams)
1527 info.insert(std::pair <std::string, std::vector<std::string> > (grpFams->_name, grpFams->_famNames) );
1530 fileMesh->setGroupInfo(info);
1533 void MgAdapt::buildConstantSizeMapSolFile(const std::string& solFormatFieldFileName, const int dim, const int version, const size_t nbNodes) const
1535 MeshFormat::Localizer loc;
1536 MeshFormat::MeshFormatParser writer;
1537 int fileId = writer.GmfOpenMesh( solFormatFieldFileName.c_str(), GmfWrite, version, dim);
1538 int typTab[] = {GmfSca};
1539 writer.GmfSetKwd(fileId, MeshFormat::GmfSolAtVertices, (int)nbNodes, 1, typTab);
1540 for (size_t i = 0; i<nbNodes; i++)
1542 double valTab[1] = {constantValue};
1543 writer.GmfSetLin( fileId, MeshFormat::GmfSolAtVertices, valTab);
1545 writer.GmfCloseMesh(fileId);
1548 void MgAdapt::buildBackGroundMeshAndSolFiles(const std::vector<std::string>& fieldFileNames, const std::string& meshFormatsizeMapFile) const
1550 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> tmpMfd = MEDCoupling::MEDFileData::New(sizeMapFile);
1551 MEDCoupling::MEDFileFields* tmpFields = tmpMfd->getFields();
1552 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeFieldMultiTS> fts( tmpFields->getFieldWithName(fieldName) );
1553 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> fts1 = MEDCoupling::DynamicCastSafe<MEDCoupling::MEDFileAnyTypeFieldMultiTS,MEDCoupling::MEDFileFieldMultiTS>(fts);
1554 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeField1TS> f = fts1->getTimeStep(timeStep, rank);
1555 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> tmFts = MEDCoupling::MEDFileFieldMultiTS::New();
1556 tmFts->pushBackTimeStep(f);
1558 MEDCoupling::MCAuto<MEDCoupling::MEDFileFields> tmp_fields = MEDCoupling::MEDFileFields::New();
1559 tmp_fields->pushField(tmFts);
1561 tmpMfd->setFields( tmp_fields );
1562 MEDCoupling::MeshFormatWriter tmpWriter;
1563 tmpWriter.setMeshFileName(meshFormatsizeMapFile);
1564 tmpWriter.setFieldFileNames( fieldFileNames);
1565 tmpWriter.setMEDFileDS(tmpMfd);
1569 MgAdapt::Status MgAdapt::addMessage(const std::string& msg,
1570 const bool isFatal/*=false*/)
1573 _errorMessages.clear(); // warnings are useless if a fatal error encounters
1575 _errorMessages.push_back( msg );
1579 std::cout << msg << std::endl;
1581 return ( _status = isFatal ? MgAdapt::DRS_FAIL : MgAdapt::DRS_WARN_SKIP_ELEM );
1584 void MgAdapt::updateTimeStepRank()
1589 if (myUseNoTimeStep)
1593 setRankTimeStep((int)tmst, (int)arank);
1595 else if (myUseLastTimeStep)
1597 std::string fieldFile = useBackgroundMap ? sizeMapFile : medFileIn;
1598 getTimeStepInfos(fieldFile, tmst, arank, fieldName);
1599 setRankTimeStep((int)tmst, (int)arank);