From dc8d96aefa04d75acd72f32a2e53cd3bdc8411e0 Mon Sep 17 00:00:00 2001 From: Christopher Lackner Date: Tue, 6 Aug 2019 14:16:13 +0200 Subject: [PATCH 1/3] move flags to ngcore --- libsrc/core/CMakeLists.txt | 4 +- libsrc/core/flags.cpp | 620 ++++++++++++++++++++++++ libsrc/core/flags.hpp | 189 ++++++++ libsrc/core/ngcore.hpp | 2 + libsrc/core/xbool.hpp | 37 ++ libsrc/csg/csgeom.cpp | 4 +- libsrc/csg/csgparser.cpp | 24 +- libsrc/csg/identify.hpp | 4 +- libsrc/csg/python_csg.cpp | 2 +- libsrc/csg/zrefine.cpp | 6 +- libsrc/general/CMakeLists.txt | 4 +- libsrc/general/flags.cpp | 330 ------------- libsrc/general/flags.hpp | 88 ---- libsrc/general/myadt.hpp | 1 - libsrc/visualization/importsolution.cpp | 10 +- ng/ngpkg.cpp | 2 +- 16 files changed, 876 insertions(+), 451 deletions(-) create mode 100644 libsrc/core/flags.cpp create mode 100644 libsrc/core/flags.hpp create mode 100644 libsrc/core/xbool.hpp delete mode 100644 libsrc/general/flags.cpp delete mode 100644 libsrc/general/flags.hpp diff --git a/libsrc/core/CMakeLists.txt b/libsrc/core/CMakeLists.txt index 15e00ce0..bf4b0bff 100644 --- a/libsrc/core/CMakeLists.txt +++ b/libsrc/core/CMakeLists.txt @@ -3,6 +3,7 @@ add_library(ngcore SHARED archive.cpp localheap.cpp logging.cpp + flags.cpp paje_trace.cpp profiler.cpp taskmanager.cpp @@ -43,7 +44,8 @@ target_link_libraries(ngcore PUBLIC netgen_mpi PRIVATE ${CMAKE_THREAD_LIBS_INIT} install(FILES ngcore.hpp archive.hpp type_traits.hpp version.hpp ngcore_api.hpp logging.hpp exception.hpp symboltable.hpp paje_trace.hpp utils.hpp profiler.hpp mpi_wrapper.hpp - array.hpp taskmanager.hpp concurrentqueue.h localheap.hpp python_ngcore.hpp + array.hpp taskmanager.hpp concurrentqueue.h localheap.hpp python_ngcore.hpp flags.hpp + xbool.hpp DESTINATION ${NG_INSTALL_DIR_INCLUDE}/core COMPONENT netgen_devel) if(ENABLE_CPP_CORE_GUIDELINES_CHECK) diff --git a/libsrc/core/flags.cpp b/libsrc/core/flags.cpp new file mode 100644 index 00000000..eef9362a --- /dev/null +++ b/libsrc/core/flags.cpp @@ -0,0 +1,620 @@ +/**************************************************************************/ +/* File: flags.cpp */ +/* Author: Joachim Schoeberl */ +/* Date: 10. Oct. 96 */ +/**************************************************************************/ + +#include "flags.hpp" + +#ifdef WIN32 +#include +#endif + +#include + +namespace ngcore +{ + using std::string; + using std::endl; + Flags :: Flags () { ; } + + Flags :: Flags (const Flags & flags) + { + string name; + for (int i = 0; i < flags.GetNStringFlags(); i++) + { + string str = flags.GetStringFlag (i, name); + SetFlag (name, str); + } + for (int i = 0; i < flags.GetNNumFlags(); i++) + { + double val = flags.GetNumFlag (i, name); + SetFlag (name, val); + } + for (int i = 0; i < flags.GetNDefineFlags(); i++) + { + bool val = flags.GetDefineFlag (i, name); + SetFlag (name, val); + } + for (int i = 0; i < flags.GetNNumListFlags(); i++) + { + auto numa = flags.GetNumListFlag (i, name); + SetFlag (name, *numa); + } + for (int i = 0; i < flags.GetNStringListFlags(); i++) + { + auto stra = flags.GetStringListFlag (i, name); + SetFlag (name, *stra); + } + for (int i = 0; i < flags.GetNFlagsFlags(); i++) + { + auto lflags = flags.GetFlagsFlag (i, name); + SetFlag (name, lflags); + } + } + + Flags :: Flags (Flags && flags) + : strflags(flags.strflags), numflags(flags.numflags), + defflags(flags.defflags), strlistflags(flags.strlistflags), + numlistflags(flags.numlistflags) { ; } + + Flags :: Flags (std::initializer_list list) + { + for (auto i = list.begin(); i < list.end(); i++) + SetCommandLineFlag ((string("-")+*i).c_str()); + } + + + Flags :: Flags (string f1, string f2, string f3, string f4, string f5) + { + SetCommandLineFlag ((string("-")+f1).c_str()); + if (f2.length()) SetCommandLineFlag ( (string("-")+f2).c_str() ); + if (f3.length()) SetCommandLineFlag ( (string("-")+f3).c_str() ); + if (f4.length()) SetCommandLineFlag ( (string("-")+f4).c_str() ); + if (f5.length()) SetCommandLineFlag ( (string("-")+f5).c_str() ); + } + + Flags :: ~Flags () + { + DeleteFlags (); + } + + void Flags :: DeleteFlags () + { + strflags.DeleteAll(); + numflags.DeleteAll(); + defflags.DeleteAll(); + strlistflags.DeleteAll(); + numlistflags.DeleteAll(); + } + + + Flags Flags :: SetFlag (const char * name, bool b) && + { + this -> SetFlag (name, b); + return std::move(*this); + } + + Flags Flags :: SetFlag (const char * name, double val) && + { + this -> SetFlag (name, val); + return std::move(*this); + } + + + + Flags & Flags :: SetFlag (const char * name, const string & val) + { + strflags.Set (name, val); + return *this; + } + + Flags & Flags :: SetFlag (const char * name, double val) & + { + numflags.Set (name, val); + return *this; + } + + Flags & Flags :: SetFlag (const char * name, bool b) & + { + defflags.Set (name, b); + return *this; + } + + Flags & Flags :: SetFlag (const char * name, Flags & val) & + { + flaglistflags.Set (name, val); + return *this; + } + + + + Flags & Flags :: SetFlag (const string & name, const string & val) + { + // char * hval = new char[strlen (val) + 1]; + // strcpy (hval, val); + strflags.Set (name, val); + return *this; + } + + Flags & Flags :: SetFlag (const string & name, double val) + { + numflags.Set (name, val); + return *this; + } + + Flags & Flags :: SetFlag (const string & name, bool b) + { + defflags.Set (name, b); + return *this; + } + + Flags & Flags :: SetFlag (const string & name, Flags & val) + { + flaglistflags.Set (name, val); + return *this; + } + + Flags & Flags :: SetFlag (const string & name, const Array & val) + { + auto strarray = std::make_shared>(val); + /* + for (int i = 0; i < val.Size(); i++) + { + strarray->Append (new char[strlen(val[i])+1]); + strcpy (strarray->Last(), val[i]); + } + */ + strlistflags.Set (name, strarray); + return *this; + } + + Flags & Flags :: SetFlag (const string & name, const Array & val) + { + // Array * numarray = new Array(val); + auto numarray = std::make_shared> (val); + + numlistflags.Set (name, numarray); + return *this; + } + + + + string Flags :: GetStringFlag (const string & name, const char * def) const + { + if (strflags.Used (name)) + return strflags[name]; + else + { + if (!def) return string(""); + return def; + } + } + + string Flags :: GetStringFlag (const string & name, string def) const + { + if (strflags.Used (name)) + return strflags[name]; + else + return def; + } + + + double Flags :: GetNumFlag (const string & name, double def) const + { + if (numflags.Used (name)) + return numflags[name]; + else + return def; + } + + const double * Flags :: GetNumFlagPtr (const string & name) const + { + if (numflags.Used (name)) + return & ((SymbolTable&)numflags)[name]; + else + return NULL; + } + + double * Flags :: GetNumFlagPtr (const string & name) + { + if (numflags.Used (name)) + return & ((SymbolTable&)numflags)[name]; + else + return NULL; + } + + /* + int Flags :: GetDefineFlag (const char * name) const + { + return defflags.Used (name); + } + */ + bool Flags :: GetDefineFlag (const string & name) const throw() + { + if (!defflags.Used (name)) return false; + return defflags[name]; + } + + xbool Flags :: GetDefineFlagX (const string & name) const throw() + { + if (!defflags.Used (name)) return maybe; + return bool(defflags[name]); + } + + + const Array & + Flags :: GetStringListFlag (const string & name) const + { + if (strlistflags.Used (name)) + return *strlistflags[name]; + else + { + static Array hstra(0); + return hstra; + } + } + + const Array & + Flags ::GetNumListFlag (const string & name) const + { + if (numlistflags.Used (name)) + return *numlistflags[name]; + else + { + static Array hnuma(0); + return hnuma; + } + } + + const Flags & + Flags ::GetFlagsFlag (const string & name) const + { + if (flaglistflags.Used (name)) + return flaglistflags[name]; + else + { + static Flags empty; + return empty; + } + } + + bool Flags :: StringFlagDefined (const string & name) const + { + return strflags.Used (name); + } + + bool Flags :: NumFlagDefined (const string &name) const + { + return numflags.Used (name); + } + + bool Flags :: FlagsFlagDefined (const string &name) const + { + return flaglistflags.Used (name); + } + + bool Flags :: StringListFlagDefined (const string & name) const + { + return strlistflags.Used (name); + } + + bool Flags :: NumListFlagDefined (const string & name) const + { + return numlistflags.Used (name); + } + + void Flags :: SaveFlags (ostream & str) const + { + for (int i = 0; i < strflags.Size(); i++) + str << strflags.GetName(i) << " = " << strflags[i] << endl; + for (int i = 0; i < numflags.Size(); i++) + str << numflags.GetName(i) << " = " << numflags[i] << endl; + for (int i = 0; i < defflags.Size(); i++) + str << defflags.GetName(i) << " = " << (defflags[i] ? "_TRUE" : "_FALSE") << endl; + for (int i = 0; i < flaglistflags.Size(); i++) + str << flaglistflags.GetName(i) << " =*" << flaglistflags[i] << endl; + for (int i = 0; i < numlistflags.Size(); i++) + { + str << numlistflags.GetName(i) << " = ["; + int j = 0; + for (j = 0; j + 1 < numlistflags[i]->Size(); ++j) + str << (*numlistflags[i])[j] << ", "; + if (numlistflags[i]->Size()) + str << (*numlistflags[i])[j]; + str << "]" << endl; + } + } + + void Flags :: SaveFlags (const char * filename) const + { + std::ofstream outfile (filename); + SaveFlags(outfile); + } + + + + void Flags :: PrintFlags (ostream & ost) const + { + for (int i = 0; i < strflags.Size(); i++) + ost << strflags.GetName(i) << " = " << strflags[i] << endl; + for (int i = 0; i < numflags.Size(); i++) + ost << numflags.GetName(i) << " = " << numflags[i] << endl; + for (int i = 0; i < defflags.Size(); i++) + ost << defflags.GetName(i) << endl; + for (int i = 0; i < strlistflags.Size(); i++) + ost << strlistflags.GetName(i) << " = " << strlistflags[i] << endl; + for (int i = 0; i < numlistflags.Size(); i++) + ost << numlistflags.GetName(i) << " = " << numlistflags[i] << endl; + for (int i = 0; i < flaglistflags.Size(); i++) + ost << flaglistflags.GetName(i) << " = " << flaglistflags[i] << endl; + } + + void Flags :: LoadFlags (const char * filename, SymbolTable * sf) + { + std::ifstream str(filename); + LoadFlags(str,sf); + } + + void Flags :: LoadFlags (std::istream & istr, SymbolTable * sf ) + { + char str[100]; + char ch; + // double val; + + while (istr.good()) + { + string name; + string content; + string line; + getline(istr, line); + std::istringstream line_stream(line); + + getline(line_stream, name, '='); + name.erase(std::remove(name.begin(), name.end(), ' '), name.end()); + + getline(line_stream, content); + content.erase(std::remove(content.begin(), content.end(), ' '), content.end()); + + // if (name[0] == '/' && name[1] == '/') + // { + // ch = 0; + // while (ch != '\n' && istr.good()) + // { + // ch = istr.get(); + // } + // continue; + // } + + if (strlen(content.c_str())==0) + { + SetFlag (name); + continue; + } + else + { + std::istringstream content_stream(content); + + content_stream >> ch; + if (ch != '*') + { + if (ch == '[') + { + // content_stream.putback (ch); + // content_stream >> ch; + string inner_string; + getline(content_stream, inner_string, ']'); + std::istringstream inner_string_stream(inner_string); + + Array values; + Array strings; + + string cur; + while (getline(inner_string_stream, cur, ',')) + { + char* endptr; + double vald = strtod (cur.c_str(), &endptr); + + if (endptr != cur.c_str() && strings.Size() == 0) + values.Append(vald); + else + strings.Append(cur); + } + if (strings.Size() > 0) + SetFlag(name, strings); + else + SetFlag(name, values); + } + else + { + if(content == "_TRUE" || content == "_FALSE") + { + SetFlag(name, (content =="_TRUE") ? true : false); + continue; + } + char* endptr; + double vald = strtod (content.c_str(), &endptr); + if (endptr != content.c_str()) + SetFlag (name, vald); + else + SetFlag (name, content); + } + } + else + { + content_stream.clear(); + content_stream >> str; + if (sf) + SetFlag (name, (*sf)[str]); + else + throw Exception (" no symboltable of flags "); + } + } + } + } + + void Flags :: DoArchive(Archive & archive) + { + archive & strflags & numflags & defflags & numlistflags & strlistflags & flaglistflags; + } + + void Flags :: Update(const Flags& other) + { + strflags.Update(other.strflags); + numflags.Update(other.numflags); + defflags.Update(other.defflags); + numlistflags.Update(other.numlistflags); + strlistflags.Update(other.strlistflags); + flaglistflags.Update(other.flaglistflags); + } + + void Flags :: SetCommandLineFlag (const char * st, SymbolTable * sf ) + { + //cout << "SetCommandLineFlag: flag = " << st << endl; + std::istringstream inst( (char *)st); + + char name[100]; + double val; + + + if (st[0] != '-') + { + std::cerr << "flag must start with '-'" << endl; + return; + } + + // flag with double -- + if (st[1] == '-') st++; + + const char * pos = strchr (st, '='); + const char * posstar = strchr (st, '*'); + const char * posbrack = strchr (st, '['); + + if (!pos) + { + // (cout) << "Add def flag: " << st+1 << endl; + SetFlag (st+1); + } + else + { + //cout << "pos = " << pos << endl; + + strncpy (name, st+1, (pos-st)-1); + name[pos-st-1] = 0; + + //cout << "name = " << name << endl; + + pos++; + char * endptr = NULL; + val = strtod (pos, &endptr); + + /* + cout << "val = " << val << endl; + cout << "isfinite = " << std::isfinite (val) << endl; + cout << "isinf = " << std::isinf (val) << endl; + cout << "pos = " << pos << ", endpos = " << endptr << endl; + */ + if (endptr != pos && !std::isfinite (val)) + endptr = const_cast(pos); + + /* +#ifdef WIN32 + if(endptr != pos && !_finite(val)) + endptr = const_cast(pos); +#else +#ifdef MACOS + if(endptr != pos && (__isnand(val) || __isinfd(val))) + endptr = const_cast(pos); +#else +#ifdef SUN +#else + if(endptr != pos && (std::isnan(val) || std::isinf(val))) + endptr = const_cast(pos); +#endif +#endif +#endif + */ + + //cout << "val = " << val << endl; + + if (!posbrack) + { + if (posstar) + { + pos++; + if (sf) + SetFlag (name, (*sf)[pos]); + else + throw Exception (" no symboltable of flags "); + } + else if (endptr == pos) + { + // string-flag + //(cout) << "Add String Flag: " << name << " = " << pos << endl; + SetFlag (name, pos); + } + else + { + // num-flag + //(cout) << "Add Num Flag: " << name << " = " << val << endl; + SetFlag (name, val); + } + } + else + { + // list-flag + char hc; + double val; + + val = strtod (posbrack+1, &endptr); + if (endptr != posbrack+1) + { + Array values; + + std::istringstream ist(posbrack); + ist >> hc; // '[' + ist >> val; + while (ist.good()) + { + values.Append (val); + ist >> hc; // ',' + ist >> val; + } + SetFlag (name, values); + } + else + { + // to be cleand up ... + Array strs; + + posbrack++; + char * hstr = new char[strlen(posbrack)+1]; + strcpy (hstr, posbrack); + + char * chp = hstr; + + bool start = 1; + while (*chp && *chp != ']') + { + if (start) + strs.Append (chp); + start = 0; + if (*chp == ',') + { + *chp = 0; + start = 1; + } + chp++; + } + *chp = 0; + + Array strings; + for (int i = 0; i < strs.Size(); i++) + strings.Append (string (strs[i])); + SetFlag (name, strings); + delete [] hstr; + } + } + } + } +} // namespace ngcore diff --git a/libsrc/core/flags.hpp b/libsrc/core/flags.hpp new file mode 100644 index 00000000..ea4a093c --- /dev/null +++ b/libsrc/core/flags.hpp @@ -0,0 +1,189 @@ +#ifndef NETGEN_CORE_FLAGS_HPP +#define NETGEN_CORE_FLAGS_HPP + + +/**************************************************************************/ +/* File: flags.hpp */ +/* Author: Joachim Schoeberl */ +/* Date: 10. Oct. 96 */ +/**************************************************************************/ + +#include +#include +#include + +#include "array.hpp" +#include "symboltable.hpp" +#include "xbool.hpp" + +namespace ngcore +{ + + /** + A storage for command-line flags. + The flag structure maintains string flags, numerical flags, + define flags, string list flags, num list flags. + */ + class NGCORE_API Flags + { + /// string flags + SymbolTable strflags; + /// numerical flags + SymbolTable numflags; + /// define flags + SymbolTable defflags; + /// string list flags + SymbolTable>> strlistflags; + /// numerical list flags + SymbolTable>> numlistflags; + /// flags list flags + SymbolTable flaglistflags; + public: + /// no flags + Flags (); + /// copy flags + Flags (const Flags & flags); + /// steal flags + Flags (Flags && flags); + /// + Flags (std::initializer_list list); + /// + Flags (std::string f1, std::string f2 = "", std::string f3 = "", std::string f4 = "", std::string f5 = ""); + /// delete mem + ~Flags (); + + Flags & operator= (const Flags & f2) = default; + Flags & operator= (Flags && f2) = default; + + void DoArchive(Archive& ar); + + void Update(const Flags& other); + + /// Deletes all flags + void DeleteFlags (); + + /// Sets string flag, overwrite if exists + Flags & SetFlag (const char * name, const std::string & val); + /// Sets string flag, overwrite if exists + Flags & SetFlag (const char * name, const char * str) + { return SetFlag (name, std::string(str)); } + /// Sets numerical flag, overwrite if exists + Flags & SetFlag (const char * name, double val) &; + /// Sets numerical flag, overwrite if exists + Flags & SetFlag (const char * name, int val) + { return SetFlag (name, double(val)); } + /// Sets boolean flag + Flags & SetFlag (const char * name, bool b = true) &; + /// Sets numerical flag, overwrite if exists + Flags & SetFlag (const char * name, Flags & val) &; + + /// Sets string flag, overwrite if exists + Flags & SetFlag (const std::string & name, const std::string & val); + Flags & SetFlag (const std::string & name, const char * str) + { return SetFlag (name, std::string(str)); } + /// Sets numerical flag, overwrite if exists + Flags & SetFlag (const std::string & name, double val); + /// Sets numerical flag, overwrite if exists + Flags & SetFlag (const std::string & name, int val) + { return SetFlag (name, double(val)); } + /// Sets boolean flag + Flags & SetFlag (const std::string & name, bool b = true); + /// Sets numerical flag, overwrite if exists + Flags & SetFlag (const std::string & name, Flags & val); + /// Sets string array flag + Flags & SetFlag (const std::string & name, const Array & val); + /// Sets double array flag + Flags & SetFlag (const std::string & name, const Array & val); + + + Flags SetFlag (const char * name, bool b = true) &&; + Flags SetFlag (const char * name, double val) &&; + + + + /// Save flags to file + void SaveFlags (const char * filename) const; + void SaveFlags (ostream & str) const; + /// write flags to stream + void PrintFlags (ostream & ost) const; + /// Load flags from file + void LoadFlags (const char * filename, SymbolTable * sf = nullptr); + void LoadFlags (std::istream & str, SymbolTable * sf = nullptr); + /** + Set command line flag. + Flag must be in form: -name=hello -val=0.5 -defflag + -names=[Joe,Jim] -values=[1,3,4] -solverflags=*abc + */ + void SetCommandLineFlag (const char * st, SymbolTable * sf = nullptr); + /// Returns string flag, default value if not exists + std::string GetStringFlag (const std::string & name, const char * def) const; + /// Returns std::string flag, default value if not exists + std::string GetStringFlag (const std::string & name, std::string def = "") const; + /// Returns numerical flag, default value if not exists + double GetNumFlag (const std::string & name, double def) const; + /// Returns address of numerical flag, null if not exists + const double * GetNumFlagPtr (const std::string & name) const; + /// Returns address of numerical flag, null if not exists + double * GetNumFlagPtr (const std::string & name); + /// Returns boolean flag + // int GetDefineFlag (const char * name) const; + bool GetDefineFlag (const std::string & name) const throw(); + xbool GetDefineFlagX (const std::string & name) const throw(); + /// Returns string list flag, empty array if not exist + const Array & GetStringListFlag (const std::string & name) const; + /// Returns num list flag, empty array if not exist + const Array & GetNumListFlag (const std::string & name) const; + /// Returns flag list flag, empty flag if not exist + const Flags & GetFlagsFlag (const std::string & name) const; + + + /// Test, if string flag is defined + bool StringFlagDefined (const std::string & name) const; + /// Test, if num flag is defined + bool NumFlagDefined (const std::string & name) const; + /// Test, if num flag is defined + bool FlagsFlagDefined (const std::string & name) const; + /// Test, if string list flag is defined + bool StringListFlagDefined (const std::string & name) const; + /// Test, if num list flag is defined + bool NumListFlagDefined (const std::string & name) const; + + /// number of string flags + int GetNStringFlags () const { return strflags.Size(); } + /// number of num flags + int GetNNumFlags () const { return numflags.Size(); } + /// number of num flags + int GetNFlagsFlags () const { return flaglistflags.Size(); } + /// number of define flags + int GetNDefineFlags () const { return defflags.Size(); } + /// number of string-list flags + int GetNStringListFlags () const { return strlistflags.Size(); } + /// number of num-list flags + int GetNNumListFlags () const { return numlistflags.Size(); } + + /// + const std::string & GetStringFlag (int i, std::string & name) const + { name = strflags.GetName(i); return strflags[i]; } + double GetNumFlag (int i, std::string & name) const + { name = numflags.GetName(i); return numflags[i]; } + bool GetDefineFlag (int i, std::string & name) const + { name = defflags.GetName(i); return defflags[i]; } + const std::shared_ptr> GetNumListFlag (int i, std::string & name) const + { name = numlistflags.GetName(i).c_str(); return numlistflags[i]; } + const std::shared_ptr> GetStringListFlag (int i, std::string & name) const + { name = strlistflags.GetName(i); return strlistflags[i]; } + const Flags & GetFlagsFlag (int i, std::string & name) const + { name = flaglistflags.GetName(i); return flaglistflags[i]; } + }; + + /// Print flags + inline std::ostream & operator<< (std::ostream & s, const Flags & flags) + { + flags.PrintFlags (s); + return s; + } +} // namespace ngcore + + +#endif // NETGEN_CORE_FLAGS_HPP + diff --git a/libsrc/core/ngcore.hpp b/libsrc/core/ngcore.hpp index 5de0bd20..166e8de7 100644 --- a/libsrc/core/ngcore.hpp +++ b/libsrc/core/ngcore.hpp @@ -4,6 +4,7 @@ #include "archive.hpp" #include "array.hpp" #include "exception.hpp" +#include "flags.hpp" #include "localheap.hpp" #include "logging.hpp" #include "mpi_wrapper.hpp" @@ -11,5 +12,6 @@ #include "symboltable.hpp" #include "taskmanager.hpp" #include "version.hpp" +#include "xbool.hpp" #endif // NETGEN_CORE_NGCORE_HPP diff --git a/libsrc/core/xbool.hpp b/libsrc/core/xbool.hpp new file mode 100644 index 00000000..31ca8730 --- /dev/null +++ b/libsrc/core/xbool.hpp @@ -0,0 +1,37 @@ +#ifndef NETGEN_CORE_XBOOL_HPP +#define NETGEN_CORE_XBOOL_HPP + +/**************************************************************************/ +/* File: xbool.hpp */ +/* Author: Joachim Schoeberl */ +/* Date: 14. Nov. 07 */ +/**************************************************************************/ + + +namespace ngcore +{ + // an extended bool with values false/maybe/true + + enum TMAYBE { maybe }; + + class xbool + { + uint8_t state; + + public: + xbool (bool b) : state(b ? 2 : 0) { ; } + xbool (TMAYBE x) : state(1) { ; } + xbool () = default; + xbool (const xbool &) = default; + + xbool & operator= (bool b) { state = b ? 2 : 0; return *this; } + xbool & operator= (TMAYBE x) { state = 1; return *this; } + + bool IsTrue () const { return state == 2; } + bool IsMaybe () const { return state == 1; } + bool IsFalse () const { return state == 0; } + }; + +} // namespace ngcore + +#endif // NETGEN_CORE_XBOOL_HPP diff --git a/libsrc/csg/csgeom.cpp b/libsrc/csg/csgeom.cpp index 2d222ce5..b4004a41 100644 --- a/libsrc/csg/csgeom.cpp +++ b/libsrc/csg/csgeom.cpp @@ -752,7 +752,7 @@ namespace netgen if (flags.StringListFlagDefined ("bcname")) { - const NgArray & bcname = flags.GetStringListFlag("bcname"); + auto& bcname = flags.GetStringListFlag("bcname"); Polyhedra * polyh; if(solid->S1()) @@ -806,7 +806,7 @@ namespace netgen if (flags.NumListFlagDefined ("bc")) { - const NgArray & bcnum = flags.GetNumListFlag("bc"); + const auto& bcnum = flags.GetNumListFlag("bc"); Polyhedra * polyh; if(solid->S1()) diff --git a/libsrc/csg/csgparser.cpp b/libsrc/csg/csgparser.cpp index 142bf04a..4e3c1786 100644 --- a/libsrc/csg/csgparser.cpp +++ b/libsrc/csg/csgparser.cpp @@ -786,7 +786,7 @@ namespace netgen if(scan.GetToken() == '-' || scan.GetToken() == TOK_NUM) { - NgArray vals; + Array vals; vals.Append (ParseNumber(scan)); while (scan.GetToken() == ',') { @@ -794,28 +794,22 @@ namespace netgen vals.Append (ParseNumber(scan)); } ParseChar (scan, ']'); - flags.SetFlag (name.c_str(), vals); + flags.SetFlag (name, vals); } else { // string list - NgArray vals; - string val = scan.GetStringValue(); - vals.Append(new char[val.size()+1]); - strcpy(vals.Last(),val.c_str()); + Array vals; + vals.Append(scan.GetStringValue()); scan.ReadNext(); while (scan.GetToken() == ',') { scan.ReadNext(); - val = scan.GetStringValue(); - vals.Append(new char[val.size()+1]); - strcpy(vals.Last(),val.c_str()); + vals.Append(scan.GetStringValue()); scan.ReadNext(); } ParseChar (scan, ']'); - flags.SetFlag (name.c_str(), vals); - for(int i=0; i & col = + const Array & col = flags.GetNumListFlag ("col"); tlo->SetRGB (col[0], col[1], col[2]); } @@ -942,8 +936,8 @@ namespace netgen TopLevelObject * tlo = geom->GetTopLevelObject (tlonr); if (flags.NumListFlagDefined ("col")) { - const NgArray & col = flags.GetNumListFlag ("col"); - tlo->SetRGB (col.Get(1), col.Get(2), col.Get(3)); + const auto& col = flags.GetNumListFlag ("col"); + tlo->SetRGB (col[0], col[1], col[2]); } if (flags.GetDefineFlag ("transparent")) tlo->SetTransparent (1); diff --git a/libsrc/csg/identify.hpp b/libsrc/csg/identify.hpp index 361e6025..abd63c6c 100644 --- a/libsrc/csg/identify.hpp +++ b/libsrc/csg/identify.hpp @@ -123,7 +123,7 @@ namespace netgen int ref_levels_s2; /// double eps_n; - NgArray slices; + Array slices; /// used only for domain-local identification: NgArray domain_surfaces; /// @@ -154,7 +154,7 @@ namespace netgen virtual int IdentifyableCandidate (const SpecialPoint & sp1) const; virtual int ShortEdge (const SpecialPoint & sp1, const SpecialPoint & sp2) const; virtual int GetIdentifiedPoint (class Mesh & mesh, int pi1); - const NgArray & GetSlices () const { return slices; } + const Array & GetSlices () const { return slices; } virtual void IdentifyPoints (class Mesh & mesh); virtual void IdentifyFaces (class Mesh & mesh); virtual void BuildSurfaceElements (NgArray & segs, diff --git a/libsrc/csg/python_csg.cpp b/libsrc/csg/python_csg.cpp index 7319d8e7..17458b90 100644 --- a/libsrc/csg/python_csg.cpp +++ b/libsrc/csg/python_csg.cpp @@ -509,7 +509,7 @@ However, when r = 0, the top part becomes a point(tip) and meshing fails! try { int n = py::len(aslices); - NgArray slices(n); + Array slices(n); for(int i=0; i(aslices[i])(); diff --git a/libsrc/csg/zrefine.cpp b/libsrc/csg/zrefine.cpp index 4fbebb82..10091520 100644 --- a/libsrc/csg/zrefine.cpp +++ b/libsrc/csg/zrefine.cpp @@ -389,12 +389,12 @@ namespace netgen edge.Sort(); if (!refedges.Used(edge)) { - const NgArray & slices = csid->GetSlices(); + const auto& slices = csid->GetSlices(); //(*testout) << "idnr " << idnr << " i " << i << endl; //(*testout) << "slices " << slices << endl; - double slicefac = slices.Get(slicenr); + double slicefac = slices[slicenr-1]; double slicefaclast = - (slicenr == slices.Size()) ? 1 : slices.Get(slicenr+1); + (slicenr == slices.Size()) ? 1 : slices[slicenr]; Point3d np = p1 + (slicefac / slicefaclast) * (p2-p1); //(*testout) << "slicenr " << slicenr << " slicefac " << slicefac << " quot " << (slicefac / slicefaclast) << " np " << np << endl; diff --git a/libsrc/general/CMakeLists.txt b/libsrc/general/CMakeLists.txt index a9620cbc..a7410f16 100644 --- a/libsrc/general/CMakeLists.txt +++ b/libsrc/general/CMakeLists.txt @@ -2,7 +2,7 @@ add_definitions(-DNGINTERFACE_EXPORTS) add_library(gen INTERFACE) set(sdir ${CMAKE_CURRENT_SOURCE_DIR}) target_sources(gen INTERFACE - ${sdir}/ngarray.cpp ${sdir}/bitarray.cpp ${sdir}/dynamicmem.cpp ${sdir}/flags.cpp + ${sdir}/ngarray.cpp ${sdir}/bitarray.cpp ${sdir}/dynamicmem.cpp ${sdir}/hashtabl.cpp ${sdir}/mystring.cpp ${sdir}/optmem.cpp ${sdir}/parthreads.cpp ${sdir}/seti.cpp ${sdir}/sort.cpp ${sdir}/spbita2d.cpp ${sdir}/table.cpp ${sdir}/mpi_interface.cpp ${sdir}/gzstream.cpp @@ -10,7 +10,7 @@ target_sources(gen INTERFACE install(FILES ngarray.hpp autodiff.hpp autoptr.hpp bitarray.hpp - dynamicmem.hpp flags.hpp hashtabl.hpp mpi_interface.hpp myadt.hpp + dynamicmem.hpp hashtabl.hpp mpi_interface.hpp myadt.hpp ngsimd.hpp mystring.hpp netgenout.hpp ngpython.hpp optmem.hpp parthreads.hpp seti.hpp sort.hpp spbita2d.hpp stack.hpp table.hpp template.hpp diff --git a/libsrc/general/flags.cpp b/libsrc/general/flags.cpp deleted file mode 100644 index f284f7d0..00000000 --- a/libsrc/general/flags.cpp +++ /dev/null @@ -1,330 +0,0 @@ -/**************************************************************************/ -/* File: flags.cc */ -/* Author: Joachim Schoeberl */ -/* Date: 10. Oct. 96 */ -/**************************************************************************/ - -/* - Datatype Flags -*/ - -#include -#include - -namespace netgen -{ - //using namespace netgen; - - Flags :: Flags () - { - ; - } - - Flags :: ~Flags () - { - DeleteFlags (); - } - - void Flags :: DeleteFlags () - { - for (int i = 0; i < strflags.Size(); i++) - delete [] strflags[i]; - for (int i = 0; i < numlistflags.Size(); i++) - delete numlistflags[i]; - strflags.DeleteAll(); - numflags.DeleteAll(); - defflags.DeleteAll(); - strlistflags.DeleteAll(); - numlistflags.DeleteAll(); - } - - void Flags :: SetFlag (const char * name, const char * val) - { - char * hval = new char[strlen (val) + 1]; - strcpy (hval, val); - strflags.Set (name, hval); - } - - void Flags :: SetFlag (const char * name, double val) - { - numflags.Set (name, val); - } - - void Flags :: SetFlag (const char * name) - { - defflags.Set (name, 1); - } - - - void Flags :: SetFlag (const char * name, const NgArray & val) - { - NgArray * strarray = new NgArray; - for (int i = 1; i <= val.Size(); i++) - { - strarray->Append (new char[strlen(val.Get(i))+1]); - strcpy (strarray->Last(), val.Get(i)); - } - strlistflags.Set (name, strarray); - } - - void Flags :: SetFlag (const char * name, const NgArray & val) - { - NgArray * numarray = new NgArray; - for (int i = 1; i <= val.Size(); i++) - numarray->Append (val.Get(i)); - numlistflags.Set (name, numarray); - } - - - - - - const char * - Flags :: GetStringFlag (const char * name, const char * def) const - { - if (strflags.Used (name)) - return strflags[name]; - else - return def; - } - - double Flags :: GetNumFlag (const char * name, double def) const - { - if (numflags.Used (name)) - return numflags[name]; - else - return def; - } - - const double * Flags :: GetNumFlagPtr (const char * name) const - { - if (numflags.Used (name)) - return & ((SymbolTable&)numflags)[name]; - else - return NULL; - } - - double * Flags :: GetNumFlagPtr (const char * name) - { - if (numflags.Used (name)) - return & ((SymbolTable&)numflags)[name]; - else - return NULL; - } - - bool Flags :: GetDefineFlag (const char * name) const - { - return defflags.Used (name); - } - - - const NgArray & - Flags :: GetStringListFlag (const char * name) const - { - if (strlistflags.Used (name)) - return *strlistflags[name]; - else - { - static NgArray dummy_array(0); - return dummy_array; - } - } - - const NgArray & - Flags ::GetNumListFlag (const char * name) const - { - if (numlistflags.Used (name)) - return *numlistflags[name]; - else - { - static NgArray dummy_array(0); - return dummy_array; - } - } - - - bool Flags :: StringFlagDefined (const char * name) const - { - return strflags.Used (name); - } - - bool Flags :: NumFlagDefined (const char * name) const - { - return numflags.Used (name); - } - - bool Flags :: StringListFlagDefined (const char * name) const - { - return strlistflags.Used (name); - } - - bool Flags :: NumListFlagDefined (const char * name) const - { - return numlistflags.Used (name); - } - - - void Flags :: SaveFlags (const char * filename) const - { - int i; - ofstream outfile (filename); - - for (i = 1; i <= strflags.Size(); i++) - outfile << strflags.GetName(i) << " = " << strflags[i] << endl; - for (i = 1; i <= numflags.Size(); i++) - outfile << numflags.GetName(i) << " = " << numflags[i] << endl; - for (i = 1; i <= defflags.Size(); i++) - outfile << defflags.GetName(i) << endl; - } - - - - void Flags :: PrintFlags (ostream & ost) const - { - int i; - - for (i = 1; i <= strflags.Size(); i++) - ost << strflags.GetName(i) << " = " << strflags[i] << endl; - for (i = 1; i <= numflags.Size(); i++) - ost << numflags.GetName(i) << " = " << numflags[i] << endl; - for (i = 1; i <= defflags.Size(); i++) - ost << defflags.GetName(i) << endl; - } - - - void Flags :: LoadFlags (const char * filename) - { - char name[100], str[100]; - char ch; - double val; - ifstream infile(filename); - - // (*logout) << "Load flags from " << filename << endl << endl; - while (infile.good()) - { - infile >> name; - if (strlen (name) == 0) break; - - if (name[0] == '/' && name[1] == '/') - { - // (*logout) << "comment: "; - ch = 0; - while (ch != '\n' && infile.good()) - { - ch = infile.get(); - // (*logout) << ch; - } - continue; - } - - // (*logout) << name; - ch = 0; - infile >> ch; - if (ch != '=') - { - // (*logout) << endl; - infile.putback (ch); - SetFlag (name); - } - else - { - infile >> val; - if (!infile.good()) - { - infile.clear(); - infile >> str; - SetFlag (name, str); - // (*logout) << " = " << str << endl; - } - else - { - SetFlag (name, val); - // (*logout) << " = " << val << endl; - } - } - } - // (*logout) << endl; - } - - - void Flags :: SetCommandLineFlag (const char * st) - { - // cout << "clflag = " << st << endl; - istringstream inst( (char *)st); - // istrstream defined with char * (not const char * ?????) - - char name[100]; - double val; - - - if (st[0] != '-') - { - cerr << "flag must start with '-'" << endl; - return; - } - - const char * pos = strchr (st, '='); - - if (!pos) - { - // (cout) << "Add def flag: " << st+1 << endl; - SetFlag (st+1); - } - else - { - // cout << "pos = " << pos << endl; - - strncpy (name, st+1, (pos-st)-1); - name[pos-st-1] = 0; - - // cout << "name = " << name << endl; - - pos++; - char * endptr = NULL; - - val = strtod (pos, &endptr); - - // cout << "val = " << val << endl; - - if (endptr == pos) - { - // (cout) << "Add String Flag: " << name << " = " << pos << endl; - SetFlag (name, pos); - } - else - { - // (cout) << "Add Num Flag: " << name << " = " << val << endl; - SetFlag (name, val); - } - } - - - /* - inst >> name; - (*mycout) << "name = " << name << endl; - - ch = 0; - inst >> ch; - if (ch != '=') - { - SetFlag (name); - } - else - { - inst >> val; - if (!inst.good()) - { - inst.clear(); - inst >> str; - SetFlag (name, str); - (*mycout) << "str = " << str << endl; - } - else - { - SetFlag (name, val); - (*mycout) << "val = " << val << endl; - } - } - */ - } -} diff --git a/libsrc/general/flags.hpp b/libsrc/general/flags.hpp deleted file mode 100644 index 1f5ec3ba..00000000 --- a/libsrc/general/flags.hpp +++ /dev/null @@ -1,88 +0,0 @@ -#ifndef FILE_FLAGS -#define FILE_FLAGS - - -/**************************************************************************/ -/* File: flags.hh */ -/* Author: Joachim Schoeberl */ -/* Date: 10. Oct. 96 */ -/**************************************************************************/ - -namespace netgen -{ - -/** - Flag - Table. - A flag table maintains string variables, numerical - variables and boolean flags. -*/ -class Flags -{ - /// - SymbolTable strflags; - /// - SymbolTable numflags; - /// - SymbolTable defflags; - /// - SymbolTable*> strlistflags; - /// - SymbolTable*> numlistflags; -public: - /// - DLL_HEADER Flags (); - /// - DLL_HEADER ~Flags (); - - /// Deletes all flags - DLL_HEADER void DeleteFlags (); - /// Sets string flag, overwrite if exists - DLL_HEADER void SetFlag (const char * name, const char * val); - /// Sets numerical flag, overwrite if exists - DLL_HEADER void SetFlag (const char * name, double val); - /// Sets boolean flag - DLL_HEADER void SetFlag (const char * name); - /// Sets string arary flag - DLL_HEADER void SetFlag (const char * name, const NgArray & val); - /// Sets double array flag - DLL_HEADER void SetFlag (const char * name, const NgArray & val); - - /// Save flags to file - DLL_HEADER void SaveFlags (const char * filename) const; - /// write flags to stream - DLL_HEADER void PrintFlags (ostream & ost) const; - /// Load flags from file - DLL_HEADER void LoadFlags (const char * filename); - /// set flag of form -name=hello -val=0.5 -defined - DLL_HEADER void SetCommandLineFlag (const char * st); - - /// Returns string flag, default value if not exists - DLL_HEADER const char * GetStringFlag (const char * name, const char * def) const; - /// Returns numerical flag, default value if not exists - DLL_HEADER double GetNumFlag (const char * name, double def) const; - /// Returns address of numerical flag, null if not exists - DLL_HEADER const double * GetNumFlagPtr (const char * name) const; - /// Returns address of numerical flag, null if not exists - DLL_HEADER double * GetNumFlagPtr (const char * name); - /// Returns boolean flag - DLL_HEADER bool GetDefineFlag (const char * name) const; - /// Returns string list flag, empty array if not exist - DLL_HEADER const NgArray & GetStringListFlag (const char * name) const; - /// Returns num list flag, empty array if not exist - DLL_HEADER const NgArray & GetNumListFlag (const char * name) const; - - - /// Test, if string flag is defined - DLL_HEADER bool StringFlagDefined (const char * name) const; - /// Test, if num flag is defined - DLL_HEADER bool NumFlagDefined (const char * name) const; - /// Test, if string list flag is defined - DLL_HEADER bool StringListFlagDefined (const char * name) const; - /// Test, if num list flag is defined - DLL_HEADER bool NumListFlagDefined (const char * name) const; -}; - -} - -#endif - diff --git a/libsrc/general/myadt.hpp b/libsrc/general/myadt.hpp index 493bc7b4..8d290e88 100644 --- a/libsrc/general/myadt.hpp +++ b/libsrc/general/myadt.hpp @@ -34,7 +34,6 @@ namespace netgen #include "bitarray.hpp" -#include "flags.hpp" #include "spbita2d.hpp" #include "seti.hpp" diff --git a/libsrc/visualization/importsolution.cpp b/libsrc/visualization/importsolution.cpp index 0532f2c9..9ccb9253 100644 --- a/libsrc/visualization/importsolution.cpp +++ b/libsrc/visualization/importsolution.cpp @@ -24,7 +24,7 @@ DLL_HEADER void ImportSolution2 (const char * filename) char buf[100], name[1000]; int i, size, comps, order; bool iscomplex; - const char * type; + std::string type; Flags flags; while (1) @@ -83,19 +83,19 @@ DLL_HEADER void ImportSolution2 (const char * filename) soldata.soltype = NG_SOLUTION_NODAL; soldata.draw_surface = 1; soldata.draw_volume = 1; - if (strcmp (type, "element") == 0) + if (type == "element") { soldata.soltype = NG_SOLUTION_ELEMENT; soldata.draw_surface = 0; } - if (strcmp (type, "surfaceelement") == 0) + if (type == "surfaceelement") { soldata.soltype = NG_SOLUTION_SURFACE_ELEMENT; soldata.draw_volume = 0; } - if (strcmp (type, "noncontinuous") == 0) + if (type == "noncontinuous") soldata.soltype = NG_SOLUTION_NONCONTINUOUS; - if (strcmp (type, "surfacenoncontinuous") == 0) + if (type == "surfacenoncontinuous") soldata.soltype = NG_SOLUTION_SURFACE_NONCONTINUOUS; Ng_SetSolutionData (&soldata); diff --git a/ng/ngpkg.cpp b/ng/ngpkg.cpp index d5a9f533..102208c2 100644 --- a/ng/ngpkg.cpp +++ b/ng/ngpkg.cpp @@ -1302,7 +1302,7 @@ namespace netgen if (parameters.StringFlagDefined (argv[1])) Tcl_SetResult (interp, - (char*)parameters.GetStringFlag (argv[1], NULL), TCL_STATIC); + (char*)parameters.GetStringFlag (argv[1], NULL).c_str(), TCL_STATIC); else if (parameters.NumFlagDefined (argv[1])) { sprintf (buf, "%lf", parameters.GetNumFlag (argv[1], 0)); From 262f1ea12cba75dbe1868d3fb19f6060a939ecd8 Mon Sep 17 00:00:00 2001 From: Christopher Lackner Date: Tue, 6 Aug 2019 15:50:08 +0200 Subject: [PATCH 2/3] move python export of flags to ngcore --- libsrc/core/CMakeLists.txt | 6 +- libsrc/core/python_ngcore.cpp | 133 ++++++++++++++++++++++----- libsrc/core/python_ngcore.hpp | 28 +++++- libsrc/core/python_ngcore_export.cpp | 87 ++++++++++++++++++ 4 files changed, 230 insertions(+), 24 deletions(-) create mode 100644 libsrc/core/python_ngcore_export.cpp diff --git a/libsrc/core/CMakeLists.txt b/libsrc/core/CMakeLists.txt index bf4b0bff..7eefdacb 100644 --- a/libsrc/core/CMakeLists.txt +++ b/libsrc/core/CMakeLists.txt @@ -10,6 +10,10 @@ add_library(ngcore SHARED utils.cpp ) +if(USE_PYTHON) + target_sources(ngcore PRIVATE python_ngcore.cpp) +endif(USE_PYTHON) + target_compile_definitions(ngcore PRIVATE NGCORE_EXPORTS) if(NOT WIN32) target_compile_options(ngcore PRIVATE -fvisibility=hidden) @@ -53,7 +57,7 @@ if(ENABLE_CPP_CORE_GUIDELINES_CHECK) endif(ENABLE_CPP_CORE_GUIDELINES_CHECK) if(USE_PYTHON) - pybind11_add_module(pyngcore SHARED python_ngcore.cpp) + pybind11_add_module(pyngcore SHARED python_ngcore_export.cpp) target_link_libraries(pyngcore PUBLIC ngcore ${PYTHON_LIBRARIES}) set_target_properties(pyngcore PROPERTIES INSTALL_RPATH "${NG_RPATH_TOKEN}/${NETGEN_PYTHON_RPATH}") install(TARGETS pyngcore DESTINATION ${NG_INSTALL_DIR_PYTHON} COMPONENT netgen) diff --git a/libsrc/core/python_ngcore.cpp b/libsrc/core/python_ngcore.cpp index 47c16740..a0810ca6 100644 --- a/libsrc/core/python_ngcore.cpp +++ b/libsrc/core/python_ngcore.cpp @@ -1,30 +1,119 @@ - #include +#include "python_ngcore.hpp" + +#include "array.hpp" +#include "flags.hpp" #include "logging.hpp" namespace py = pybind11; -using namespace ngcore; +using std::string; -PYBIND11_MODULE(pyngcore, m) // NOLINT +namespace ngcore { - py::enum_(m, "LOG_LEVEL", "Logging level") - .value("Trace", level::trace) - .value("Debug", level::debug) - .value("Info", level::info) - .value("Warn", level::warn) - .value("Error", level::err) - .value("Critical", level::critical) - .value("Off", level::off); - m.def("SetLoggingLevel", &SetLoggingLevel, py::arg("level"), py::arg("logger")="", - "Set logging level, if name is given only to the specific logger, else set the global logging level"); - m.def("AddFileSink", &AddFileSink, py::arg("filename"), py::arg("level"), py::arg("logger")="", - "Add File sink, either only to logger specified or globally to all loggers"); - m.def("AddConsoleSink", &AddConsoleSink, py::arg("level"), py::arg("logger")="", - "Add console output for specific logger or all if none given"); - m.def("ClearLoggingSinks", &ClearLoggingSinks, py::arg("logger")="", - "Clear sinks of specific logger, or all if none given"); - m.def("FlushOnLoggingLevel", &FlushOnLoggingLevel, py::arg("level"), py::arg("logger")="", - "Flush every message with level at least `level` for specific logger or all loggers if none given."); -} + void SetFlag(Flags &flags, string s, py::object value) + { + if (py::isinstance(value)) + { + py::dict vdd(value); + // call recursively to set dictionary + for (auto item : vdd) { + string name = item.first.cast(); + py::object val = py::reinterpret_borrow(item.second); + SetFlag(flags, name, val); + } + return; + } + + if (py::isinstance(value)) + flags.SetFlag(s, value.cast()); + + if (py::isinstance(value)) + flags.SetFlag(s, value.cast()); + + if (py::isinstance(value)) + flags.SetFlag(s, double(value.cast())); + + if (py::isinstance(value)) + flags.SetFlag(s, value.cast()); + + if (py::isinstance(value)) + { + py::list vdl(value); + if (py::len(vdl) > 0) + { + if(py::isinstance(vdl[0])) + flags.SetFlag(s, makeCArray(vdl)); + if(py::isinstance(vdl[0])) + flags.SetFlag(s, makeCArray(vdl)); + } + else + { + Array dummystr; + Array dummydbl; + flags.SetFlag(s,dummystr); + flags.SetFlag(s,dummydbl); + } + } + + if (py::isinstance(value)) + { + py::tuple vdt(value); + if (py::isinstance(value)) + flags.SetFlag(s, makeCArray(vdt)); + if (py::isinstance(value)) + flags.SetFlag(s, makeCArray(vdt)); + if (py::isinstance(value)) + flags.SetFlag(s, makeCArray(vdt)); + } + } + + Flags CreateFlagsFromKwArgs(py::object pyclass, const py::kwargs& kwargs, py::list info) + { + static std::shared_ptr logger = GetLogger("Flags"); + auto flags_doc = pyclass.attr("__flags_doc__")(); + py::dict flags_dict; + + if (kwargs.contains("flags")) + { + logger->warn("WARNING: using flags as kwarg is deprecated in {}, use the flag arguments as kwargs instead!", + std::string(py::str(pyclass))); + auto addflags = py::cast(kwargs["flags"]); + for (auto item : addflags) + flags_dict[item.first.cast().c_str()] = item.second; + } + for (auto item : kwargs) + if (!flags_doc.contains(item.first.cast().c_str()) && + !(item.first.cast() == "flags")) + logger->warn("WARNING: kwarg '{}' is an undocumented flags option for class {}, maybe there is a typo?", + item.first.cast(), std::string(py::str(pyclass))); + + py::dict special; + if(py::hasattr(pyclass,"__special_treated_flags__")) + special = pyclass.attr("__special_treated_flags__")(); + for (auto item : kwargs) + { + auto name = item.first.cast(); + if (name != "flags") + { + if(!special.contains(name.c_str())) + flags_dict[name.c_str()] = item.second; + } + } + + auto flags = py::cast(flags_dict); + + for (auto item : kwargs) + { + auto name = item.first.cast(); + if (name != "flags") + { + if(special.contains(name.c_str())) + special[name.c_str()](item.second, &flags, info); + } + } + return flags; + } + +} // namespace ngcore diff --git a/libsrc/core/python_ngcore.hpp b/libsrc/core/python_ngcore.hpp index 07f348c7..9c283589 100644 --- a/libsrc/core/python_ngcore.hpp +++ b/libsrc/core/python_ngcore.hpp @@ -3,11 +3,37 @@ #include +#include "array.hpp" #include "archive.hpp" - +#include "flags.hpp" +#include "ngcore_api.hpp" namespace ngcore { + namespace py = pybind11; + + template + Array makeCArray(const py::object& obj) + { + Array arr; + arr.SetAllocSize(py::len(obj)); + if(py::isinstance(obj)) + for(auto& val : py::cast(obj)) + arr.Append(py::cast(val)); + else if(py::isinstance(obj)) + for(auto& val : py::cast(obj)) + arr.Append(py::cast(val)); + else + throw py::type_error("Cannot convert Python object to C Array"); + return arr; + } + + void NGCORE_API SetFlag(Flags &flags, std::string s, py::object value); + // Parse python kwargs to flags + Flags NGCORE_API CreateFlagsFromKwArgs(py::object pyclass, const py::kwargs& kwargs, py::list info = py::list()); + + // *************** Archiving functionality ************** + template Archive& Archive :: Shallow(T& val) { diff --git a/libsrc/core/python_ngcore_export.cpp b/libsrc/core/python_ngcore_export.cpp new file mode 100644 index 00000000..90dbf72f --- /dev/null +++ b/libsrc/core/python_ngcore_export.cpp @@ -0,0 +1,87 @@ + +#include "python_ngcore.hpp" + +using namespace ngcore; +using namespace std; + +PYBIND11_MODULE(pyngcore, m) // NOLINT +{ + py::class_(m, "Flags") + .def(py::init<>()) + .def("__str__", &ToString) + .def(py::init([](py::object & obj) { + Flags flags; + py::dict d(obj); + SetFlag (flags, "", d); + return flags; + }), py::arg("obj"), "Create Flags by given object") + .def(py::pickle([] (const Flags& self) + { + std::stringstream str; + self.SaveFlags(str); + return py::make_tuple(py::cast(str.str())); + }, + [] (py::tuple state) + { + string s = state[0].cast(); + std::stringstream str(s); + Flags flags; + flags.LoadFlags(str); + return flags; + } + )) + .def("Set",[](Flags & self,const py::dict & aflags)->Flags& + { + SetFlag(self, "", aflags); + return self; + }, py::arg("aflag"), "Set the flags by given dict") + + .def("Set",[](Flags & self, const char * akey, const py::object & value)->Flags& + { + SetFlag(self, akey, value); + return self; + }, py::arg("akey"), py::arg("value"), "Set flag by given value.") + + .def("__getitem__", [](Flags & self, const string& name) -> py::object { + + if(self.NumListFlagDefined(name)) + return py::cast(self.GetNumListFlag(name)); + + if(self.StringListFlagDefined(name)) + return py::cast(self.GetStringListFlag(name)); + + if(self.NumFlagDefined(name)) + return py::cast(*self.GetNumFlagPtr(name)); + + if(self.StringFlagDefined(name)) + return py::cast(self.GetStringFlag(name)); + + if(self.FlagsFlagDefined(name)) + return py::cast(self.GetFlagsFlag(name)); + + return py::cast(self.GetDefineFlag(name)); + }, py::arg("name"), "Return flag by given name") + ; + py::implicitly_convertible(); + + + py::enum_(m, "LOG_LEVEL", "Logging level") + .value("Trace", level::trace) + .value("Debug", level::debug) + .value("Info", level::info) + .value("Warn", level::warn) + .value("Error", level::err) + .value("Critical", level::critical) + .value("Off", level::off); + + m.def("SetLoggingLevel", &SetLoggingLevel, py::arg("level"), py::arg("logger")="", + "Set logging level, if name is given only to the specific logger, else set the global logging level"); + m.def("AddFileSink", &AddFileSink, py::arg("filename"), py::arg("level"), py::arg("logger")="", + "Add File sink, either only to logger specified or globally to all loggers"); + m.def("AddConsoleSink", &AddConsoleSink, py::arg("level"), py::arg("logger")="", + "Add console output for specific logger or all if none given"); + m.def("ClearLoggingSinks", &ClearLoggingSinks, py::arg("logger")="", + "Clear sinks of specific logger, or all if none given"); + m.def("FlushOnLoggingLevel", &FlushOnLoggingLevel, py::arg("level"), py::arg("logger")="", + "Flush every message with level at least `level` for specific logger or all loggers if none given."); +} From 575e863e4ac8367f1299e46a4c3e3c99ef702425 Mon Sep 17 00:00:00 2001 From: Christopher Lackner Date: Tue, 6 Aug 2019 15:58:15 +0200 Subject: [PATCH 3/3] fix ambiguous namespace --- libsrc/core/python_ngcore.hpp | 2 +- libsrc/general/ngpython.hpp | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/libsrc/core/python_ngcore.hpp b/libsrc/core/python_ngcore.hpp index 9c283589..562467cc 100644 --- a/libsrc/core/python_ngcore.hpp +++ b/libsrc/core/python_ngcore.hpp @@ -7,10 +7,10 @@ #include "archive.hpp" #include "flags.hpp" #include "ngcore_api.hpp" +namespace py = pybind11; namespace ngcore { - namespace py = pybind11; template Array makeCArray(const py::object& obj) diff --git a/libsrc/general/ngpython.hpp b/libsrc/general/ngpython.hpp index 722709c5..e13533c1 100644 --- a/libsrc/general/ngpython.hpp +++ b/libsrc/general/ngpython.hpp @@ -4,10 +4,11 @@ #include #include #include -namespace py = pybind11; #include #include +#include +using namespace ngcore; template py::array MoveToNumpy(std::vector& vec)