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 <utilities.h>
36 #include <TCollection_AsciiString.hxx>
38 #include <boost/filesystem.hpp>
42 struct GET_DEFAULT // struct used to get default value from GetOptionValue()
51 //----------------------------------------------------------------------------------------
54 data = new MgAdaptHypothesisData();
55 data->myInMeshName = "";
56 data->fromMedFile = defaultFromMedFile();
57 data->myFileInDir = defaultWorkingDirectory();
58 data->myMeshFileIn = "";
59 data->myFileOutDir = defaultWorkingDirectory();
60 data->myOutMeshName = "";
61 data->myMeshFileOut = "";
62 data->myMeshOutMed = defaultMeshOutMed();
63 data->myPublish = defaultPublish();
64 data->myUseLocalMap = defaultUseLocalMap();
65 data->myUseBackgroundMap = defaultUseBackgroundMap();
66 data->myFileSizeMapDir = defaultWorkingDirectory();
67 data->myMeshFileBackground = "";
68 data->myUseConstantValue = defaultUseConstantValue();
69 data->myConstantValue = 0.0;
70 data->myFieldName = "";
71 data->myUseNoTimeStep = defaultUseNoTimeStep();
72 data->myUseLastTimeStep = defaultUseLastTimeStep();
73 data->myUseChosenTimeStep = defaultUseChosenTimeStep();
74 data->myTimeStep = -2;
76 data->myWorkingDir = defaultWorkingDirectory();
77 data->myLogFile = defaultLogFile();
78 data->myVerboseLevel = defaultVerboseLevel();
79 data->myPrintLogInFile = defaultPrintLogInFile();
80 data->myKeepFiles = defaultKeepFiles();
81 data->myRemoveLogOnSuccess = defaultRemoveLogOnSuccess();
86 MgAdapt::MgAdapt(MgAdaptHypothesisData* myData)
88 data = new MgAdaptHypothesisData();
93 MgAdapt::MgAdapt( const MgAdapt& copy)
96 data = new MgAdaptHypothesisData();
97 MgAdaptHypothesisData *copyData = copy.getData();
98 copyMgAdaptHypothesisData(copyData);
101 this->_option2value = copy._option2value;
102 this->_customOption2value = copy._customOption2value;
103 this->_defaultOptionValues = copy._defaultOptionValues;
104 this->_doubleOptions = copy._doubleOptions;
105 this->_charOptions = copy._charOptions;
106 this->_boolOptions = copy._boolOptions;
112 //-----------------------------------------------------------------------------------------
119 void MgAdapt::buildModel()
122 const char* boolOptionNames[] = { "compute_ridges", // yes
125 // const char* intOptionNames[] = { "max_number_of_errors_printed", // 1
126 // "max_number_of_threads", // 4
129 const char* doubleOptionNames[] = { "max_memory", // 0
132 const char* charOptionNames[] = { "components", // "yes"
133 "adaptation", // both
138 while (boolOptionNames[i][0])
140 _boolOptions.insert( boolOptionNames[i] );
141 _option2value[boolOptionNames[i++]].clear();
144 // while (intOptionNames[i][0])
145 // _option2value[intOptionNames[i++]].clear();
148 while (doubleOptionNames[i][0]) {
149 _doubleOptions.insert(doubleOptionNames[i]);
150 _option2value[doubleOptionNames[i++]].clear();
153 while (charOptionNames[i][0]) {
154 _charOptions.insert(charOptionNames[i]);
155 _option2value[charOptionNames[i++]].clear();
158 // default values to be used while MG-Adapt
160 _defaultOptionValues["adaptation" ] = "both";
161 _defaultOptionValues["components" ] = "outside components";
162 _defaultOptionValues["compute_ridges" ] = "yes";
163 _defaultOptionValues["max_memory" ] = ToComment(defaultMaximumMemory());
166 //=============================================================================
167 TOptionValues MgAdapt::getOptionValues() const
170 TOptionValues::const_iterator op_val = _option2value.begin();
171 for ( ; op_val != _option2value.end(); ++op_val )
172 vals.insert( make_pair( op_val->first, getOptionValue( op_val->first, GET_DEFAULT() )));
177 std::vector <std::string> MgAdapt::getOptionValuesStrVec() const
179 std::vector <std::string> vals;
180 TOptionValues::const_iterator op_val = _option2value.begin();
181 for ( ; op_val != _option2value.end(); ++op_val )
182 vals.push_back(op_val->first+":"+getOptionValue( op_val->first, GET_DEFAULT() ));
187 std::vector <std::string> MgAdapt::getCustomOptionValuesStrVec() const
189 std::vector <std::string> vals;
190 TOptionValues::const_iterator op_val;
191 for ( op_val = _customOption2value.begin(); op_val != _customOption2value.end(); ++op_val )
193 vals.push_back(op_val->first+":"+getOptionValue( op_val->first, GET_DEFAULT() ));
197 const TOptionValues& MgAdapt::getCustomOptionValues() const
199 return _customOption2value;
201 void MgAdapt::setData(MgAdaptHypothesisData* myData)
203 copyMgAdaptHypothesisData(myData);
206 MgAdaptHypothesisData* MgAdapt::getData() const
210 void MgAdapt::setMedFileIn(std::string fileName)
212 medFileIn = fileName;
215 std::string MgAdapt::getMedFileIn()
220 void MgAdapt::setMedFileOut(std::string fileOut)
222 medFileOut = fileOut;
225 std::string MgAdapt::getMedFileOut()
229 void MgAdapt::setMeshOutMed(bool mybool)
233 bool MgAdapt::getMeshOutMed()
237 void MgAdapt::setPublish(bool mybool)
241 bool MgAdapt::getPublish()
245 void MgAdapt::setFieldName(std::string myFieldName)
247 fieldName = myFieldName;
249 std::string MgAdapt::getFieldName()
253 void MgAdapt::setTimeStep(int time)
257 int MgAdapt::getTimeStep() const
262 void MgAdapt::setRankTimeStep(int time, int myRank)
268 int MgAdapt::getRank()
272 void MgAdapt::setUseLocalMap(bool myLocal)
274 useLocalMap = myLocal;
277 bool MgAdapt::getUseLocalMap()
282 void MgAdapt::setUseBackgroundMap(bool bckg)
284 useBackgroundMap = bckg;
287 bool MgAdapt::getUseBackgroundMap()
289 return useBackgroundMap;
292 void MgAdapt::setUseConstantValue(bool cnst)
294 useConstantValue = cnst;
297 bool MgAdapt::getUseConstantValue()
299 return useConstantValue;
301 void MgAdapt::setLogFile(std::string myLogFile)
305 std::string MgAdapt::getLogFile()
309 void MgAdapt::setVerbosityLevel(int verboLevel)
311 verbosityLevel = verboLevel;
313 int MgAdapt::getVerbosityLevel()
315 return verbosityLevel;
317 void MgAdapt::setRemoveOnSuccess(bool rmons)
319 removeOnSuccess = rmons;
321 bool MgAdapt::getRemoveOnSuccess()
323 return removeOnSuccess;
325 void MgAdapt::setSizeMapFile(std::string mapFile)
327 sizeMapFile = mapFile;
329 std::string MgAdapt::getSizeMapFile()
334 void MgAdapt::setMeshName(std::string name)
338 std::string MgAdapt::getMeshName()
342 void MgAdapt::setMeshNameOut(std::string name)
346 std::string MgAdapt::getMeshNameOut()
350 void MgAdapt::setFromMedFile(bool mybool)
352 fromMedFile = mybool;
354 bool MgAdapt::isFromMedFile()
358 void MgAdapt::setConstantValue(double cnst)
360 constantValue = cnst;
362 bool MgAdapt::getConstantValue()
364 return constantValue;
367 void MgAdapt::setWorkingDir(std::string dir)
371 std::string MgAdapt::getWorkingDir() const
375 void MgAdapt::setKeepWorkingFiles(bool mybool)
377 toKeepWorkingFiles = mybool;
379 bool MgAdapt::getKeepWorkingFiles()
381 return toKeepWorkingFiles;
383 void MgAdapt::setPrintLogInFile(bool print)
385 printLogInFile = print;
387 bool MgAdapt::getPrintLogInFile()
389 return printLogInFile;
392 bool MgAdapt::setAll()
395 setFromMedFile(data->fromMedFile);
397 checkDirPath(data->myFileInDir);
398 file = data->myFileInDir+data->myMeshFileIn;
400 setMeshName(data->myInMeshName);
401 setMeshNameOut(data->myOutMeshName);
402 checkDirPath(data->myFileOutDir);
403 std::string out = data->myFileOutDir+data->myMeshFileOut;
405 setPublish(data->myPublish);
406 setMeshOutMed(data->myMeshOutMed);
407 setUseLocalMap(data->myUseLocalMap);
408 setUseBackgroundMap(data->myUseBackgroundMap);
409 setUseConstantValue(data->myUseConstantValue);
412 if (useBackgroundMap)
415 checkDirPath(data->myFileSizeMapDir);
416 mapfile = data->myFileSizeMapDir+data->myMeshFileBackground;
417 setFieldName(data->myFieldName);
419 else if (useConstantValue)
421 setConstantValue(data->myConstantValue);
426 setConstantValue(0.0);
427 setFieldName(data->myFieldName);
431 setSizeMapFile(mapfile);
434 if (data->myUseNoTimeStep)
439 else if (data->myUseLastTimeStep)
441 std::string fieldFile = useBackgroundMap ? sizeMapFile : medFileIn;
442 getTimeStepInfos(fieldFile, tmst, rank);
447 tmst = data->myTimeStep;
449 setRankTimeStep((int)tmst, (int)rank);
451 /* Advanced options */
452 setWorkingDir(data->myWorkingDir);
453 checkDirPath(data->myWorkingDir);
454 setLogFile(data->myWorkingDir+defaultLogFile());
455 setVerbosityLevel(data->myVerboseLevel);
456 setRemoveOnSuccess(data->myRemoveLogOnSuccess);
457 setPrintLogInFile(data->myPrintLogInFile);
458 setKeepWorkingFiles(data->myKeepFiles);
463 void MgAdapt::checkDirPath(std::string& dirPath)
465 const char lastChar = *dirPath.rbegin();
467 if(lastChar != '\\') dirPath+='\\';
469 if(lastChar != '/') dirPath+='/';
472 //=============================================================================
473 void MgAdapt::setOptionValue(const std::string& optionName,
474 const std::string& optionValue)
475 throw (std::invalid_argument)
477 TOptionValues::iterator op_val = _option2value.find(optionName);
478 if (op_val == _option2value.end())
480 op_val = _customOption2value.find( optionName );
481 _customOption2value[ optionName ] = optionValue;
485 if (op_val->second != optionValue)
487 const char* ptr = optionValue.c_str();
488 // strip white spaces
489 while (ptr[0] == ' ')
492 while (i != 0 && ptr[i - 1] == ' ')
496 std::string typeName;
499 } else if (_charOptions.count(optionName)) {
500 // do not check strings
501 } else if (_doubleOptions.count(optionName)) {
502 // check if value is double
505 } else if (_boolOptions.count(optionName)) {
506 // check if value is bool
507 toBool(ptr, &typeOk);
510 // check if value is int
512 typeName = "integer";
514 if ( typeOk ) // check some specific values ?
519 std::string msg = "Advanced option '" + optionName + "' = '" + optionValue + "' but must be " + typeName;
520 throw std::invalid_argument(msg);
522 std::string value( ptr, i );
523 if ( _defaultOptionValues[ optionName ] == value )
527 op_val->second = value;
531 //=============================================================================
532 //! Return option value. If isDefault provided, it can be a default value,
533 // then *isDefault == true. If isDefault is not provided, the value will be
534 // empty if it equals a default one.
535 std::string MgAdapt::getOptionValue(const std::string& optionName, bool* isDefault) const
536 throw (std::invalid_argument)
538 TOptionValues::const_iterator op_val = _option2value.find(optionName);
539 if (op_val == _option2value.end())
541 op_val = _customOption2value.find(optionName);
542 if (op_val == _customOption2value.end())
544 std::string msg = "Unknown MG-Adapt option: <" + optionName + ">";
545 throw std::invalid_argument(msg);
548 std::string val = op_val->second;
549 if ( isDefault ) *isDefault = ( val.empty() );
551 if ( val.empty() && isDefault )
553 op_val = _defaultOptionValues.find( optionName );
554 if (op_val != _defaultOptionValues.end())
555 val = op_val->second;
559 //================================================================================
561 * \brief Converts a string to a real value
563 //================================================================================
565 double MgAdapt::toDbl(const std::string& str, bool* isOk )
566 throw (std::invalid_argument)
568 if ( str.empty() ) throw std::invalid_argument("Empty value provided");
571 double val = strtod(&str[0], &endPtr);
572 bool ok = (&str[0] != endPtr);
574 if ( isOk ) *isOk = ok;
578 std::string msg = "Not a real value:'" + str + "'";
579 throw std::invalid_argument(msg);
583 //================================================================================
585 * \brief Converts a string to a bool
587 //================================================================================
589 bool MgAdapt::toBool(const std::string& str, bool* isOk )
590 throw (std::invalid_argument)
593 if ( isOk ) *isOk = true;
595 for ( size_t i = 0; i <= s.size(); ++i )
596 s[i] = tolower( s[i] );
598 if ( s == "1" || s == "true" || s == "active" || s == "yes" )
601 if ( s == "0" || s == "false" || s == "inactive" || s == "no" )
607 std::string msg = "Not a Boolean value:'" + str + "'";
608 throw std::invalid_argument(msg);
612 //================================================================================
614 * \brief Converts a string to a integer value
616 //================================================================================
618 int MgAdapt::toInt(const std::string& str, bool* isOk )
619 throw (std::invalid_argument)
621 if ( str.empty() ) throw std::invalid_argument("Empty value provided");
624 int val = (int)strtol( &str[0], &endPtr, 10);
625 bool ok = (&str[0] != endPtr);
627 if ( isOk ) *isOk = ok;
631 std::string msg = "Not an integer value:'" + str + "'";
632 throw std::invalid_argument(msg);
636 //=============================================================================
637 bool MgAdapt::hasOptionDefined( const std::string& optionName ) const
639 bool isDefault = false;
642 getOptionValue( optionName, &isDefault );
644 catch ( std::invalid_argument )
650 //================================================================================
652 * \brief Return command to run MG-Tetra mesher excluding file prefix (-f)
654 //================================================================================
656 std::string MgAdapt::getCommandToRun(MgAdapt* hyp)
658 return hyp ? hyp->getCommandToRun() : ToComment("error with hypothesis!");
663 int MgAdapt::compute(std::string& errStr)
665 std::string cmd= getCommandToRun();
667 execCmd( cmd.c_str(), err ); // run
671 errStr = ToComment("system(mg-adapt.exe ...) command failed with error: ")
672 << strerror( errno );
676 convertMeshFile(meshFormatOutputMesh, solFormatOutput);
681 void MgAdapt::execCmd( const char* cmd, int& err)
684 std::array <char, 128> buffer;
685 std:: ofstream logStream;
686 logStream.open(logFile);
687 std::unique_ptr <FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose );
690 throw std::runtime_error("popen() failed!");
692 while(fgets(buffer.data(), buffer.size(), pipe.get()) !=nullptr )
694 logStream<<buffer.data() ;
699 //================================================================================
701 * \brief Return command to run MG-Tetra mesher excluding file prefix (-f)
703 //================================================================================
705 std::string MgAdapt::getCommandToRun()
708 || return system command with args and options
712 std::string cmd = getExeName();
713 std::string meshIn(""), sizeMapIn(""), solFileIn("");
714 convertMedFile(meshIn, solFileIn, sizeMapIn);
715 if (!isFileExist(meshIn) || !isFileExist(solFileIn))
717 errStr = ToComment(" failed to find .mesh or .sol file from converter ")<< strerror( errno );
720 if(useBackgroundMap && !isFileExist(sizeMapIn))
723 errStr = ToComment(" failed to find .mesh size map file from converter ")<< strerror( errno );
727 meshFormatOutputMesh = meshIn;
728 solFormatOutput.push_back(solFileIn);
730 cmd+= " --in "+ meshIn;
731 meshFormatOutputMesh = getFileName()+".mesh";
732 cmd+= " --out "+ meshFormatOutputMesh;
733 if (useLocalMap) cmd+= " --sizemap "+ solFileIn;
734 else if (useBackgroundMap)
736 cmd+= " --background_mesh "+ sizeMapIn ;
737 cmd+= " --background_sizemap "+ solFileIn;
741 // constant value TODO
744 if (verbosityLevel != defaultVerboseLevel())
747 cmd+= " --verbose "+ ToComment(verbosityLevel);
750 std::string option, value;
752 const TOptionValues* options[] = { &_option2value, &_customOption2value };
753 for ( int iOp = 0; iOp < 2; ++iOp )
755 TOptionValues::const_iterator o2v = options[iOp]->begin();
756 for ( ; o2v != options[iOp]->end(); ++o2v )
759 value = getOptionValue( option, &isDefault );
763 if ( value.empty() )//value == NoValue() )
765 if ( _defaultOptionValues.count( option ))
766 continue; // non-custom option with no value
769 if ( strncmp( "no", option.c_str(), 2 ) == 0 ) // options w/o values: --no_*
771 if ( !value.empty() && toBool( value ) == false )
775 if ( option[0] != '-' )
779 cmd += option + " " + value;
792 bool MgAdapt::isFileExist(std::string& fName) const
798 boost::system::error_code err;
799 bool res = boost::filesystem::exists( fName, err );
801 return err ? false : res;
803 //=======================================================================
804 //function : defaultMaximumMemory
805 //=======================================================================
809 #elif !defined(__APPLE__)
810 #include <sys/sysinfo.h>
813 double MgAdapt::defaultMaximumMemory()
816 // See http://msdn.microsoft.com/en-us/library/aa366589.aspx
817 MEMORYSTATUSEX statex;
818 statex.dwLength = sizeof (statex);
819 long err = GlobalMemoryStatusEx (&statex);
821 double totMB = (double)statex.ullAvailPhys / 1024. / 1024.;
822 return (double)( 0.7 * totMB );
824 #elif !defined(__APPLE__)
826 long err = sysinfo( &si );
828 long ramMB = si.totalram * si.mem_unit / 1024 / 1024;
829 return ( 0.7 * ramMB );
836 //=======================================================================
837 //function : defaultWorkingDirectory
838 //=======================================================================
840 std::string MgAdapt::defaultWorkingDirectory()
842 TCollection_AsciiString aTmpDir;
844 char *Tmp_dir = getenv("SALOME_TMP_DIR");
845 if(Tmp_dir != NULL) {
850 aTmpDir = TCollection_AsciiString("C:\\");
852 aTmpDir = TCollection_AsciiString("/tmp/");
855 return aTmpDir.ToCString();
857 //================================================================================
859 * \brief Return a unique file name
861 //================================================================================
863 std::string MgAdapt::getFileName() const
865 std::string aTmpDir = workingDir;
866 const char lastChar = *aTmpDir.rbegin();
868 if(lastChar != '\\') aTmpDir+='\\';
870 if(lastChar != '/') aTmpDir+='/';
873 TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
874 aGenericName += "MgAdapt_";
875 aGenericName += getpid();
877 aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
879 return aGenericName.ToCString();
881 //=======================================================================
882 //function : defaultLogFile
883 //=======================================================================
885 std::string MgAdapt::defaultLogFile()
887 std::string alogFile("MG_ADAPT.log");
890 //=======================================================================
891 //function : defaultUseConstantValue
892 //=======================================================================
894 bool MgAdapt::defaultUseConstantValue()
898 //=======================================================================
899 //function : defaultUseNoTimeStep
900 //=======================================================================
902 bool MgAdapt::defaultUseNoTimeStep()
906 //=======================================================================
907 //function : defaultRemoveLogOnSuccess
908 //=======================================================================
910 bool MgAdapt::defaultRemoveLogOnSuccess()
914 //=======================================================================
915 //function : defaultPrintLogInFile
916 //=======================================================================
918 bool MgAdapt::defaultPrintLogInFile()
922 //=======================================================================
923 //function : defaultUseChosenTimeStep
924 //=======================================================================
926 bool MgAdapt::defaultUseChosenTimeStep()
930 //=======================================================================
931 //function : UseLastTimeStep
932 //=======================================================================
934 bool MgAdapt::defaultUseLastTimeStep()
938 //=======================================================================
939 //function : defaultUseBackgroundMap
940 //=======================================================================
942 bool MgAdapt::defaultUseBackgroundMap()
946 //=======================================================================
947 //function : defaultKeepFiles
948 //=======================================================================
950 bool MgAdapt::defaultKeepFiles()
954 //=======================================================================
955 //function : defaultUseLocalMap
956 //=======================================================================
958 bool MgAdapt::defaultUseLocalMap()
962 //=======================================================================
963 //function : defaultPublish
964 //=======================================================================
966 bool MgAdapt::defaultPublish()
970 //=======================================================================
971 //function : defaultMeshOutMed
972 //=======================================================================
974 bool MgAdapt::defaultMeshOutMed()
978 //=======================================================================
979 //function : defaultFromMedFile
980 //=======================================================================
982 bool MgAdapt::defaultFromMedFile()
986 //=======================================================================
987 //function : defaultVerboseLevel
988 //=======================================================================
990 int MgAdapt::defaultVerboseLevel()
994 std::string MgAdapt::getExeName()
996 return "mg-adapt.exe";
998 void MgAdapt::copyMgAdaptHypothesisData( MgAdaptHypothesisData* from)
1001 data->myFileInDir = from->myFileInDir;
1002 data->myMeshFileIn = from->myMeshFileIn;
1003 data->myMeshFileBackground = from->myMeshFileBackground;
1004 data->myOutMeshName = from->myOutMeshName;
1005 data->myMeshFileOut = from->myMeshFileOut;
1006 data->myFileOutDir = from->myFileOutDir;
1007 data->myFileSizeMapDir = from->myFileSizeMapDir;
1008 data->myFieldName = from->myFieldName;
1009 data->fromMedFile = from->fromMedFile;
1010 data->myPublish = from->myPublish;
1011 data->myMeshOutMed = from->myMeshOutMed;
1012 data->myUseLocalMap = from->myUseLocalMap;
1013 data->myUseBackgroundMap = from->myUseBackgroundMap;
1014 data->myUseConstantValue = from->myUseConstantValue;
1015 data->myConstantValue = from->myConstantValue;
1016 data->myTimeStep = from->myTimeStep;
1017 data->myRank = from->myRank;
1018 data->myUseNoTimeStep = from->myUseNoTimeStep;
1019 data->myUseLastTimeStep = from->myUseLastTimeStep;
1020 data->myUseChosenTimeStep = from->myUseChosenTimeStep;
1021 data->myWorkingDir = from->myWorkingDir;
1022 data->myLogFile = from->myLogFile;
1023 data->myPrintLogInFile = from->myPrintLogInFile;
1024 data->myKeepFiles = from->myKeepFiles;
1025 data->myRemoveLogOnSuccess = from->myRemoveLogOnSuccess;
1026 data->myVerboseLevel = from->myVerboseLevel;
1031 void MgAdapt::convertMedFile(std::string& meshFormatMeshFileName, std::string& solFormatFieldFileName, std::string& meshFormatsizeMapFile)
1034 std::vector<std::string> fieldFileNames;
1035 MeshFormatWriter writer;
1036 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = MEDCoupling::MEDFileData::New(medFileIn);
1037 MEDCoupling::MEDFileMeshes* meshes = mfd->getMeshes();
1038 MEDCoupling::MEDFileMesh* fileMesh = meshes->getMeshAtPos(0); // ok only one mesh in file!
1039 storeGroupsAndFams(fileMesh);
1041 MEDCoupling::MCAuto<MEDCoupling::MEDFileFields> fields = MEDCoupling::MEDFileFields::New();
1042 solFormatFieldFileName = getFileName();
1043 solFormatFieldFileName+=".sol";
1044 fieldFileNames.push_back(solFormatFieldFileName);
1046 if (useBackgroundMap)
1049 meshFormatsizeMapFile = getFileName();
1050 meshFormatsizeMapFile += ".mesh";
1051 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> tmpMfd = MEDCoupling::MEDFileData::New(sizeMapFile);
1052 MEDCoupling::MEDFileFields* tmpFields = tmpMfd->getFields();
1053 MEDCoupling::MEDFileAnyTypeFieldMultiTS* fts = tmpFields->getFieldWithName(fieldName);
1054 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> fts1 = dynamic_cast<MEDCoupling::MEDFileFieldMultiTS *>(fts);
1055 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeField1TS> f = fts1->getTimeStep(timeStep, rank);
1056 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> tmFts = MEDCoupling::MEDFileFieldMultiTS::New();
1057 tmFts->pushBackTimeStep(f);
1059 MEDCoupling::MCAuto<MEDCoupling::MEDFileFields> tmp_fields = MEDCoupling::MEDFileFields::New();
1060 tmp_fields->pushField(tmFts);
1063 tmpMfd->setFields( tmp_fields );
1064 MeshFormatWriter tmpWriter;
1065 tmpWriter.setMeshFileName(meshFormatsizeMapFile);
1066 tmpWriter.setFieldFileNames( fieldFileNames);
1067 tmpWriter.setMEDFileDS(tmpMfd);
1072 else if(useLocalMap)
1075 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeFieldMultiTS> fts = dynamic_cast<MEDCoupling::MEDFileFieldMultiTS *>( mfd->getFields()->getFieldWithName(fieldName) );
1076 MEDCoupling::MCAuto<MEDCoupling::MEDFileAnyTypeField1TS> f = fts->getTimeStep(timeStep, rank);
1077 MEDCoupling::MCAuto<MEDCoupling::MEDFileFieldMultiTS> tmFts = MEDCoupling::MEDFileFieldMultiTS::New();
1078 tmFts->pushBackTimeStep(f);
1080 fields->pushField(tmFts);
1082 writer.setFieldFileNames( fieldFileNames);
1087 MEDCoupling::MEDCouplingMesh* mesh = fileMesh->getMeshAtLevel(1); // nodes mesh
1088 MEDCoupling::MEDCouplingFieldDouble* fieldOnNodes=MEDCoupling::MEDCouplingFieldDouble::New(MEDCoupling::ON_NODES,MEDCoupling::NO_TIME);
1089 fieldOnNodes->setName("MyScalarFieldOnNodeNoTime");
1090 fieldOnNodes->setMesh(mesh);
1091 mesh->decrRef(); // no more need of mesh because mesh has been attached to fieldOnNodes
1092 MEDCoupling::DataArrayDouble *array=MEDCoupling::DataArrayDouble::New();
1093 array->alloc(fieldOnNodes->getMesh()->getNumberOfNodes(),1);//Implicitly fieldOnNodes will be a 1 component field.
1094 array->fillWithValue(constantValue);
1095 fieldOnNodes->setArray(array);
1097 // fieldOnNodes is now usable
1099 // fieldOnNodes is no more useful h
1103 mfd->setFields( fields );
1104 meshFormatMeshFileName = getFileName();
1105 meshFormatMeshFileName+=".mesh";
1106 writer.setMeshFileName(meshFormatMeshFileName);
1107 writer.setMEDFileDS( mfd);
1112 void MgAdapt::convertMeshFile(std::string& meshFormatIn, std::vector< std::string>& solFieldFileNames) const
1114 MeshFormatReader reader(meshFormatIn, solFieldFileNames);
1116 MEDCoupling::MCAuto<MEDCoupling::MEDFileData> mfd = reader.loadInMedFileDS();
1118 MEDCoupling::MEDFileMeshes* meshes = mfd->getMeshes();
1119 MEDCoupling::MEDFileMesh* fileMesh = meshes->getMeshAtPos(0); // ok only one mesh in file!
1120 fileMesh->setName(meshNameOut);
1121 restoreGroupsAndFams(fileMesh);
1122 mfd->write(medFileOut, 2);
1126 void MgAdapt::storeGroupsAndFams(MEDCoupling::MEDFileMesh* fileMesh)
1128 storefams(fileMesh);
1129 storeGroups(fileMesh);
1132 void MgAdapt::restoreGroupsAndFams(MEDCoupling::MEDFileMesh* fileMesh) const
1134 restorefams(fileMesh);
1135 restoreGroups(fileMesh);
1137 void MgAdapt::storeGroups(MEDCoupling::MEDFileMesh* fileMesh)
1139 std::map<std::string, std::vector<std::string> > grpFams = fileMesh->getGroupInfo();
1140 std::map<std::string, std::vector<std::string> >::iterator g2ff = grpFams.begin();
1142 for ( ; g2ff != grpFams.end(); ++g2ff )
1144 std::string groupName = g2ff->first;
1145 std::vector<std::string> famNames = g2ff->second;
1147 if ( famNames.empty() ) continue;
1149 std::vector< mcIdType> famListId;
1150 for ( size_t i = 0; i < famNames.size(); ++i )
1152 famListId.push_back( fileMesh->getFamilyId( famNames[i].c_str() ) );
1154 group grp(groupName, famListId, famNames);
1155 groupVec.push_back(grp);
1159 void MgAdapt::storefams(MEDCoupling::MEDFileMesh* fileMesh)
1161 std::map<std::string, mcIdType> grpFams = fileMesh->getFamilyInfo();
1162 std::map<std::string, mcIdType >::iterator f = grpFams.begin();
1164 for ( ; f != grpFams.end(); ++f )
1166 if(!f->second) continue; // FAMILLE_ZERO
1167 family fs(f->first, f->second);
1168 famVec.push_back(fs);
1173 void MgAdapt::restorefams(MEDCoupling::MEDFileMesh* fileMesh) const
1175 std::vector<family>::const_iterator fIt = famVec.begin();
1177 for (; fIt!=famVec.end(); ++fIt)
1179 try // safety : FAMILY could be lost P2-->P1
1181 std::string givenFamNameFromMeshGemConverter = fileMesh->getFamilyNameGivenId( fIt->_famId );
1182 fileMesh->changeFamilyName(givenFamNameFromMeshGemConverter, fIt->_famName);
1184 catch (const std::exception& e)
1186 std::cerr<<e.what();
1191 void MgAdapt::restoreGroups(MEDCoupling::MEDFileMesh* fileMesh) const
1193 std::map<std::string, std::vector<std::string> > info;
1194 std::vector <group>::const_iterator grpFams = groupVec.begin();
1196 for (; grpFams!=groupVec.end(); ++grpFams)
1198 info.insert(std::pair <std::string, std::vector<std::string> > (grpFams->_name, grpFams->_famNames) );
1201 fileMesh->setGroupInfo(info);
1203 // =======================================================================
1204 med_idt MgAdapt::openMedFile(const std::string aFile)
1205 // =======================================================================
1206 // renvoie le medId associe au fichier Med apres ouverture
1208 med_idt medIdt = MEDfileOpen(aFile.c_str(),MED_ACC_RDONLY);
1211 //~addMessage( ToComment(" error: Can't open ") << aFile, /*fatal=*/true );
1217 MgAdapt::Status MgAdapt::addMessage(const std::string& msg,
1218 const bool isFatal/*=false*/)
1221 _myErrorMessages.clear(); // warnings are useless if a fatal error encounters
1223 _myErrorMessages.push_back( msg );
1227 std::cout << msg << std::endl;
1229 return ( _myStatus = isFatal ? MgAdapt::DRS_FAIL : MgAdapt::DRS_WARN_SKIP_ELEM );
1235 // =======================================================================
1236 void MgAdapt::getTimeStepInfos(std::string aFile, med_int& numdt, med_int& numit)
1237 // =======================================================================
1239 // Il faut voir si plusieurs maillages
1246 // Ouverture du fichier
1247 //~SCRUTE(aFile.toStdString());
1248 medIdt = openMedFile(aFile);
1249 if ( medIdt < 0 ) return ;
1250 // Lecture du nombre de champs
1251 med_int ncha = MEDnField(medIdt) ;
1254 //~addMessage( ToComment(" error: there is no field in ") << aFile, /*fatal=*/true );
1257 // Lecture des caracteristiques du champs
1259 // Lecture du type du champ, des noms des composantes et du nom de l'unite
1260 char nomcha [MED_NAME_SIZE+1];
1261 strcpy(nomcha, fieldName.c_str());
1262 // Lecture du nombre de composantes
1263 med_int ncomp = MEDfieldnComponentByName(medIdt, nomcha);
1264 char meshname[MED_NAME_SIZE+1];
1265 char * comp = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
1266 char * unit = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
1267 char dtunit[MED_SNAME_SIZE+1];
1269 med_field_type typcha;
1271 erreur = MEDfieldInfoByName (medIdt, nomcha, meshname,&local,&typcha,comp,unit,dtunit, &nbofcstp);
1276 //~addMessage( ToComment(" error: error while reading field ") << nomcha << " in file " << aFile , /*fatal=*/true );
1281 med_int tmp_numdt, tmp_numit;
1283 med_int step = data->myUseLastTimeStep ? nbofcstp : data->myTimeStep+1;
1284 //~myPrint("step ", step);
1285 erreur = MEDfieldComputingStepInfo ( medIdt, nomcha, step, &tmp_numdt, &tmp_numit, &dt );
1289 //~addMessage( ToComment(" error: error while reading field last time step ") << nomcha << " in file " << aFile , /*fatal=*/true );
1297 // Fermeture du fichier
1298 if ( medIdt > 0 ) MEDfileClose(medIdt);