Cantera  3.0.0
Loading...
Searching...
No Matches
utils_utils.h
1// This file is part of Cantera. See License.txt in the top-level directory or
2// at https://cantera.org/license.txt for license and copyright information.
3
4#ifndef CT_PY_UTILS_UTILS_H
5#define CT_PY_UTILS_UTILS_H
6
8
9#include "Python.h"
10
11// Warning types supported by the Python C-API.
12// See https://docs.python.org/3/c-api/exceptions.html#issuing-warnings
13static std::map<std::string, PyObject*> mapped_PyWarnings = {
14 {"", PyExc_Warning},
15 {"Bytes", PyExc_BytesWarning},
16 {"Cantera", PyExc_UserWarning}, // pre-existing warning
17 {"Deprecation", PyExc_DeprecationWarning},
18 {"Future", PyExc_FutureWarning},
19 {"Import", PyExc_ImportWarning},
20 {"PendingDeprecation", PyExc_PendingDeprecationWarning},
21 {"Resource", PyExc_ResourceWarning},
22 {"Runtime", PyExc_RuntimeWarning},
23 {"Syntax", PyExc_SyntaxWarning},
24 {"Unicode", PyExc_UnicodeWarning},
25 {"User", PyExc_UserWarning}
26};
27
28// Cantera version for Python module compilation
29inline std::string get_cantera_version_py()
30{
31 return CANTERA_VERSION;
32}
33
34// Git commit for Python module compilation
35inline std::string get_cantera_git_commit_py()
36{
37#ifdef GIT_COMMIT
38 return GIT_COMMIT;
39#else
40 return "unknown";
41#endif
42}
43
44// Wrappers for preprocessor defines
45inline int get_sundials_version()
46{
47 return CT_SUNDIALS_VERSION;
48}
49
50class PythonLogger : public Cantera::Logger
51{
52public:
53 void write(const std::string& s) override {
54 // 1000 bytes is the maximum size permitted by PySys_WriteStdout
55 static const size_t N = 999;
56 for (size_t i = 0; i < s.size(); i+=N) {
57 PySys_WriteStdout("%s", s.substr(i, N).c_str());
58 }
59 std::cout.flush();
60 }
61
62 void writeendl() override {
63 PySys_WriteStdout("%s", "\n");
64 std::cout.flush();
65 }
66
67 void warn(const std::string& warning, const std::string& msg) override {
68 if (mapped_PyWarnings.find(warning) != mapped_PyWarnings.end()) {
69 PyErr_WarnEx(mapped_PyWarnings[warning], msg.c_str(), 1);
70 } else {
71 // issue generic warning
72 PyErr_WarnEx(PyExc_Warning, msg.c_str(), 1);
73 }
74 }
75
76 void error(const std::string& msg) override {
77 PyErr_SetString(PyExc_RuntimeError, msg.c_str());
78 }
79};
80
81#endif
Base class for 'loggers' that write text messages to log files.
Definition logger.h:41
virtual void writeendl()
Write an end of line character and flush output.
Definition logger.h:66
virtual void write(const string &msg)
Write a log message.
Definition logger.h:57
virtual void error(const string &msg)
Write an error message and quit.
Definition logger.h:91
virtual void warn(const string &warning, const string &msg)
Write a warning message.
Definition logger.h:76
Header for Base class for 'loggers' that write text messages to log files (see Logging and class Logg...