Debian Codegraph @

src/pycolmap/helpers.h

raw
1 #pragma once
2
3 #include "colmap/util/cancellation.h"
4 #include "colmap/util/logging.h"
5 #include "colmap/util/string.h"
6 #include "colmap/util/threading.h"
7
8 #include "pycolmap/feature/opaque_types.h"
9
10 #include <atomic>
11 #include <chrono>
12 #include <exception>
13 #include <functional>
14 #include <memory>
15 #include <optional>
16 #include <regex>
17 #include <sstream>
18 #include <string>
19 #include <thread>
20 #include <type_traits>
21 #include <utility>
22
23 #include <Eigen/Core>
24 #include <glog/logging.h>
25 #include <pybind11/embed.h>
26 #include <pybind11/eval.h>
27 #include <pybind11/numpy.h>
28 #include <pybind11/pybind11.h>
29 #include <pybind11/stl.h>
30 #include <pybind11/stl_bind.h>
31
32 namespace py = pybind11;
33
34 const Eigen::IOFormat vec_fmt(Eigen::StreamPrecision,
35 Eigen::DontAlignCols,
36 ", ",
37 ", ");
38
39 template <typename T>
40 T PyStringToEnum(const py::enum_<T>& enm, const std::string& value) {
41 const auto values = enm.attr("__members__").template cast<py::dict>();
42 const auto str_val = py::str(value);
43 if (!values.contains(str_val)) {
44 LOG(FATAL_THROW) << "Invalid string value " << value << " for enum "
45 << enm.attr("__name__").template cast<std::string>();
46 }
47 return T(values[str_val].template cast<T>());
48 }
49
50 template <typename T>
51 void AddStringToEnumConstructor(py::enum_<T>& enm) {
52 enm.def(py::init([enm](const std::string& value) {
53 return PyStringToEnum(enm, py::str(value)); // str constructor
54 }),
55 py::arg("name"));
56 enm.attr("__repr__") = enm.attr("__str__");
57 py::implicitly_convertible<std::string, T>();
58 }
59
60 inline void UpdateFromDict(py::object& self, const py::dict& dict) {
61 for (const auto& it : dict) {
62 if (!py::isinstance<py::str>(it.first)) {
63 LOG(FATAL_THROW) << "Dictionary key is not a string: "
64 << py::str(it.first);
65 }
66 const py::str name = py::reinterpret_borrow<py::str>(it.first);
67 const py::handle& value = it.second;
68 const auto attr = self.attr(name);
69 try {
70 if (py::hasattr(attr, "mergedict") && py::isinstance<py::dict>(value)) {
71 attr.attr("mergedict").attr("__call__")(value);
72 } else {
73 self.attr(name) = value;
74 }
75 } catch (const py::error_already_set& ex) {
76 if (ex.matches(PyExc_TypeError)) {
77 // If fail we try bases of the class
78 const py::list bases =
79 attr.attr("__class__").attr("__bases__").cast<py::list>();
80 bool success_on_base = false;
81 for (auto& base : bases) {
82 try {
83 self.attr(name) = base(value);
84 success_on_base = true;
85 break;
86 } catch (const py::error_already_set&) {
87 continue; // We anyway throw afterwards
88 }
89 }
90 if (success_on_base) {
91 continue;
92 }
93 std::ostringstream ss;
94 ss << self.attr("__class__")
95 .attr("__name__")
96 .template cast<std::string>()
97 << "." << name.template cast<std::string>() << ": Could not convert "
98 << py::type::of(value.cast<py::object>())
99 .attr("__name__")
100 .template cast<std::string>()
101 << ": " << py::str(value).template cast<std::string>() << " to '"
102 << py::type::of(attr).attr("__name__").template cast<std::string>()
103 << "'.";
104 // We write the err message to give info even if exceptions
105 // is catched outside, e.g. in function overload resolve
106 LOG(ERROR) << "Internal TypeError: " << ss.str();
107 throw(py::type_error(std::string("Failed to merge dict into class: ") +
108 "Could not assign " +
109 name.template cast<std::string>()));
110 } else if (ex.matches(PyExc_AttributeError) &&
111 py::str(ex.value()).cast<std::string>() ==
112 std::string("can't set attribute")) {
113 std::ostringstream ss;
114 ss << self.attr("__class__")
115 .attr("__name__")
116 .template cast<std::string>()
117 << "." << name.template cast<std::string>() << " defined readonly.";
118 throw py::attribute_error(ss.str());
119 } else if (ex.matches(PyExc_AttributeError)) {
120 LOG(ERROR) << "Internal AttributeError: "
121 << py::str(ex.value()).cast<std::string>();
122 throw;
123 } else {
124 LOG(ERROR) << "Internal Error: "
125 << py::str(ex.value()).cast<std::string>();
126 throw;
127 }
128 }
129 }
130 }
131
132 inline bool AttributeIsFunction(const std::string& name,
133 const py::object& value) {
134 return (name.find("__") == 0 || name.rfind("__") != std::string::npos ||
135 py::hasattr(value, "__func__") || py::hasattr(value, "__call__"));
136 }
137
138 inline std::vector<std::string> ListObjectAttributes(const py::object& pyself) {
139 std::vector<std::string> attributes;
140 for (const auto& handle : pyself.attr("__dir__")()) {
141 const py::str attribute = py::reinterpret_borrow<py::str>(handle);
142 const auto value = pyself.attr(attribute);
143 if (AttributeIsFunction(attribute, value)) {
144 continue;
145 }
146 attributes.push_back(attribute);
147 }
148 return attributes;
149 }
150
151 template <typename T, typename... options>
152 py::dict ConvertToDict(const T& self,
153 std::vector<std::string> attributes,
154 const bool recursive) {
155 const py::object pyself = py::cast(self);
156 if (attributes.empty()) {
157 attributes = ListObjectAttributes(pyself);
158 }
159 py::dict dict;
160 for (const auto& attr : attributes) {
161 const auto value = pyself.attr(attr.c_str());
162 if (recursive && py::hasattr(value, "todict")) {
163 dict[attr.c_str()] =
164 value.attr("todict").attr("__call__")().template cast<py::dict>();
165 } else {
166 dict[attr.c_str()] = value;
167 }
168 }
169 return dict;
170 }
171
172 template <typename T, typename... options>
173 std::string CreateSummary(const T& self, bool write_type) {
174 std::ostringstream ss;
175 auto pyself = py::cast(self);
176 const std::string prefix = " ";
177 bool after_subsummary = false;
178 ss << pyself.attr("__class__").attr("__name__").template cast<std::string>()
179 << ":";
180 for (auto& handle : pyself.attr("__dir__")()) {
181 const py::str name = py::reinterpret_borrow<py::str>(handle);
182 py::object attribute;
183 try {
184 attribute = pyself.attr(name);
185 } catch (const std::exception&) {
186 // Some properties are not valid for some uninitialized objects.
187 continue;
188 }
189 if (AttributeIsFunction(name, attribute)) {
190 continue;
191 }
192 ss << "\n";
193 if (!after_subsummary) {
194 ss << prefix;
195 }
196 ss << name.template cast<std::string>();
197 if (py::hasattr(attribute, "summary")) {
198 std::string summ = attribute.attr("summary")
199 .attr("__call__")(write_type)
200 .template cast<std::string>();
201 static const std::regex newline_regex("\n");
202 // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
203 summ = std::regex_replace(summ, newline_regex, "\n" + prefix);
204 ss << ": " << summ;
205 } else {
206 if (write_type) {
207 const std::string type_str =
208 py::str(py::type::of(attribute).attr("__name__"));
209 ss << ": " << type_str;
210 after_subsummary = true;
211 }
212 std::string value = py::str(attribute);
213 if (value.length() > 80 && py::hasattr(attribute, "__len__")) {
214 const int length = attribute.attr("__len__")().template cast<int>();
215 value = colmap::StringPrintf(
216 "%c ... %d elements ... %c", value.front(), length, value.back());
217 }
218 ss << " = " << value;
219 after_subsummary = false;
220 }
221 }
222 return ss.str();
223 }
224
225 template <typename T>
226 std::string CreateRepresentationFromAttributes(const T& self) {
227 std::ostringstream ss;
228 auto pyself = py::cast(self);
229 ss << pyself.attr("__class__").attr("__name__").template cast<std::string>()
230 << "(";
231 bool is_first = true;
232 for (auto& handle : pyself.attr("__dir__")()) {
233 const py::str name = py::reinterpret_borrow<py::str>(handle);
234 py::object attribute;
235 try {
236 attribute = pyself.attr(name);
237 } catch (const std::exception&) {
238 // Some properties are not valid for some uninitialized objects.
239 continue;
240 }
241 if (AttributeIsFunction(name, attribute)) {
242 continue;
243 }
244 if (!is_first) {
245 ss << ", ";
246 }
247 is_first = false;
248 ss << name.template cast<std::string>() << "=";
249 if (py::isinstance<py::str>(attribute)) {
250 ss << "'" << py::str(attribute) << "'";
251 } else {
252 ss << py::str(attribute);
253 }
254 }
255 ss << ")";
256 return ss.str();
257 }
258
259 template <typename T, typename = void>
260 struct IsOstreamable : std::false_type {};
261
262 template <typename T>
263 struct IsOstreamable<
264 T,
265 std::void_t<decltype(std::declval<std::ostream&>() << std::declval<T>())>>
266 : std::true_type {};
267
268 template <typename T>
269 std::string CreateRepresentation(const T& self) {
270 if constexpr (IsOstreamable<T>::value) {
271 std::ostringstream ss;
272 ss << self;
273 return ss.str();
274 } else {
275 return CreateRepresentationFromAttributes<T>(self);
276 }
277 }
278
279 template <typename T, typename... options>
280 void AddDefaultsToDocstrings(py::classh<T, options...> cls) {
281 auto obj = cls();
282 for (auto& handle : obj.attr("__dir__")()) {
283 const std::string attribute = py::str(handle);
284 py::object member;
285 try {
286 member = obj.attr(attribute.c_str());
287 } catch (const std::exception&) {
288 // Some properties are not valid for some uninitialized objects.
289 continue;
290 }
291 auto prop = cls.attr(attribute.c_str());
292 if (AttributeIsFunction(attribute, member)) {
293 continue;
294 }
295 const auto type_name = py::type::of(member).attr("__name__");
296 const std::string doc =
297 colmap::StringPrintf("%s (%s, default: %s)",
298 py::str(prop.doc()).cast<std::string>().c_str(),
299 type_name.template cast<std::string>().c_str(),
300 py::str(member).cast<std::string>().c_str());
301 prop.doc() = py::str(doc);
302 }
303 }
304
305 template <typename T, typename = void>
306 struct has_equality_operator : std::false_type {};
307
308 template <typename T>
309 struct has_equality_operator<
310 T,
311 std::void_t<decltype(std::declval<T&>() == std::declval<T&>())>>
312 : std::true_type {};
313
314 template <typename T, typename = void>
315 struct has_less_than_operator : std::false_type {};
316
317 template <typename T>
318 struct has_less_than_operator<
319 T,
320 std::void_t<decltype(std::declval<T&>() < std::declval<T&>())>>
321 : std::true_type {};
322
323 template <typename T, typename = void>
324 struct is_hashable : std::false_type {};
325
326 template <typename T>
327 struct is_hashable<T, std::void_t<decltype(std::hash<T>{}(std::declval<T>()))>>
328 : std::true_type {};
329
330 template <typename T, typename... options>
331 void MakeDataclass(py::classh<T, options...> cls,
332 const std::vector<std::string>& attributes = {}) {
333 AddDefaultsToDocstrings(cls);
334 if (!py::hasattr(cls, "summary")) {
335 cls.def("summary", &CreateSummary<T>, py::arg("write_type") = false);
336 }
337 if (!cls.attr("__dict__").contains("__repr__")) {
338 cls.def("__repr__", &CreateRepresentation<T>);
339 }
340 cls.def("mergedict", &UpdateFromDict, py::arg("kwargs"));
341 cls.def(
342 "todict",
343 [attributes](const T& self, const bool recursive) {
344 return ConvertToDict(self, attributes, recursive);
345 },
346 py::arg("recursive") = true);
347
348 if constexpr (std::is_copy_constructible_v<T>) {
349 cls.def(py::init([cls](const py::dict& dict) {
350 py::object self = cls();
351 self.attr("mergedict").attr("__call__")(dict);
352 return self.cast<T>();
353 }));
354 cls.def(py::init([cls](const py::kwargs& kwargs) {
355 py::dict dict = kwargs.cast<py::dict>();
356 return cls(dict).template cast<T>();
357 }));
358 py::implicitly_convertible<py::dict, T>();
359 py::implicitly_convertible<py::kwargs, T>();
360
361 if (!cls.attr("__dict__").contains("__copy__")) {
362 cls.def("__copy__", [](const T& self) { return T(self); });
363 }
364 if (!cls.attr("__dict__").contains("__deepcopy__")) {
365 cls.def("__deepcopy__",
366 [](const T& self, const py::dict&) { return T(self); });
367 }
368
369 cls.def(py::pickle(
370 [attributes](const T& self) {
371 return ConvertToDict(self, attributes, /*recursive=*/false);
372 },
373 [cls](const py::dict& dict) {
374 py::object self = cls();
375 self.attr("mergedict").attr("__call__")(dict);
376 return self.cast<T>();
377 }));
378 }
379
380 if constexpr (has_equality_operator<T>::value) {
381 cls.def(py::self == py::self);
382 if constexpr (is_hashable<T>::value) {
383 cls.def("__hash__", [](const T& self) { return std::hash<T>()(self); });
384 } else {
385 cls.attr("__hash__") = py::none();
386 }
387 } else {
388 if constexpr (std::is_copy_constructible_v<T>) {
389 cls.def("__eq__", [attributes](const T& self, const py::object& other) {
390 if (!py::isinstance<T>(other)) {
391 return false;
392 }
393 py::dict self_dict = ConvertToDict(self, attributes, true);
394 py::dict other_dict = ConvertToDict(other.cast<T>(), attributes, true);
395 return self_dict.equal(other_dict);
396 });
397 }
398 cls.attr("__hash__") = py::none();
399 }
400
401 if constexpr (has_less_than_operator<T>::value) {
402 cls.def(py::self < py::self);
403 }
404 }
405
406 // Catch python keyboard interrupts
407
408 /*
409 // single
410 if (PyInterrupt().Raised()) {
411 // stop the execution and raise an exception
412 throw py::error_already_set();
413 }
414
415 // loop
416 PyInterrupt py_interrupt = PyInterrupt(2.0)
417 for (...) {
418 if (py_interrupt.Raised()) {
419 // stop the execution and raise an exception
420 throw py::error_already_set();
421 }
422 // Do your workload here
423 }
424
425
426 */
427 struct PyInterrupt {
428 using clock = std::chrono::steady_clock;
429 using sec = std::chrono::duration<double>;
430 explicit PyInterrupt(double gap = -1.0) : start(clock::now()), gap_(gap) {}
431
432 inline bool Raised();
433
434 private:
435 std::mutex mutex_;
436 bool found = false;
437 colmap::Timer timer_;
438 clock::time_point start;
439 double gap_;
440 };
441
442 inline bool PyInterrupt::Raised() {
443 const sec duration = clock::now() - start;
444 if (!found && duration.count() > gap_) {
445 std::lock_guard<std::mutex> lock(mutex_);
446 py::gil_scoped_acquire acq;
447 found = (PyErr_CheckSignals() != 0);
448 start = clock::now();
449 }
450 return found;
451 }
452
453 [[noreturn]] inline void ThrowPythonError() {
454 py::gil_scoped_acquire acquire;
455 throw py::error_already_set();
456 }
457
458 [[noreturn]] inline void ThrowCancelled() {
459 py::gil_scoped_acquire acquire;
460 PyErr_SetString(PyExc_InterruptedError, "Operation cancelled");
461 throw py::error_already_set();
462 }
463
464 class PyInterruptChecker {
465 public:
466 explicit PyInterruptChecker(
467 std::shared_ptr<colmap::CancellationToken> cancellation_token = nullptr,
468 const double gap = 1.0)
469 : py_interrupt_(gap),
470 cancellation_token_(std::move(cancellation_token)),
471 calling_thread_id_(std::this_thread::get_id()) {}
472
473 // The callback may run on worker threads, but Python signals may only be
474 // checked from the thread that created this object. The returned callback
475 // borrows this object and must not outlive it.
476 std::function<bool()> Callback() {
477 return [this]() {
478 if (std::this_thread::get_id() == calling_thread_id_ &&
479 py_interrupt_.Raised()) {
480 python_interrupt_raised_.store(true, std::memory_order_relaxed);
481 }
482 return python_interrupt_raised_.load(std::memory_order_relaxed) ||
483 (cancellation_token_ && cancellation_token_->IsCancelled());
484 };
485 }
486
487 void CheckAndThrow() const {
488 if (python_interrupt_raised_.load(std::memory_order_relaxed)) {
489 ThrowPythonError();
490 }
491 if (cancellation_token_ && cancellation_token_->IsCancelled()) {
492 ThrowCancelled();
493 }
494 }
495
496 private:
497 PyInterrupt py_interrupt_;
498 std::shared_ptr<colmap::CancellationToken> cancellation_token_;
499 std::thread::id calling_thread_id_;
500 std::atomic<bool> python_interrupt_raised_{false};
501 };
502
503 // Instead of thread.Wait() call this to allow interrupts through Python.
504 // `poll_interval` controls lightweight thread-state and cancellation checks,
505 // while `gap` throttles Python signal checks that require acquiring the GIL.
506 inline void PyWait(colmap::Thread* thread,
507 const std::shared_ptr<colmap::CancellationToken>&
508 cancellation_token = nullptr,
509 double gap = 1.0,
510 double poll_interval = 0.05) {
511 PyInterrupt py_interrupt(gap);
512 while (thread->IsRunning()) {
513 if (cancellation_token && cancellation_token->IsCancelled()) {
514 thread->Stop();
515 thread->Wait();
516 ThrowCancelled();
517 }
518 if (py_interrupt.Raised()) {
519 LOG(ERROR) << "Stopping thread...";
520 thread->Stop();
521 thread->Wait();
522 ThrowPythonError();
523 }
524 std::this_thread::sleep_for(PyInterrupt::sec(poll_interval));
525 }
526 // after finishing join the thread to avoid abort
527 thread->Wait();
528 if (cancellation_token && cancellation_token->IsCancelled()) {
529 ThrowCancelled();
530 }
531 }
532
533 // Test if pyceres is available
534 inline bool IsPyceresAvailable() {
535 try {
536 py::module::import("pyceres");
537 } catch (const py::error_already_set&) {
538 return false;
539 }
540 return true;
541 }
542
543 template <typename Parent>
544 inline void DefDeprecation(
545 Parent& parent,
546 std::string old_name,
547 std::string new_name,
548 std::optional<std::string> custom_warning = std::nullopt) {
549 const std::string doc =
550 colmap::StringPrintf("Deprecated, use ``%s`` instead.", new_name.c_str());
551 parent.def(
552 old_name.c_str(),
553 [parent,
554 old_name,
555 new_name = std::move(new_name),
556 custom_warning = std::move(custom_warning)](const py::args& args,
557 const py::kwargs& kwargs) {
558 if (custom_warning) {
559 PyErr_WarnEx(PyExc_DeprecationWarning, custom_warning->c_str(), 1);
560 } else {
561 std::ostringstream warning;
562 warning << old_name << "() is deprecated, use " << new_name
563 << "() instead.";
564 PyErr_WarnEx(PyExc_DeprecationWarning, warning.str().c_str(), 1);
565 }
566 return parent.attr(new_name.c_str())(*args, **kwargs);
567 },
568 doc.c_str());
569 }