-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathexpose_real.cpp
2844 lines (2350 loc) · 105 KB
/
expose_real.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020-2025 Francesco Biscani ([email protected]), Dario Izzo ([email protected])
//
// This file is part of the heyoka.py library.
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <heyoka/config.hpp>
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#if defined(HEYOKA_HAVE_REAL)
#include <algorithm>
#include <array>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <functional>
#include <iterator>
#include <limits>
#include <memory>
#include <new>
#include <optional>
#include <sstream>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <boost/safe_numerics/safe_integer.hpp>
#include <fmt/format.h>
#include <fmt/ranges.h>
#define NO_IMPORT_ARRAY
#define NO_IMPORT_UFUNC
#define PY_ARRAY_UNIQUE_SYMBOL heyoka_py_ARRAY_API
#define PY_UFUNC_UNIQUE_SYMBOL heyoka_py_UFUNC_API
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#define NPY_TARGET_VERSION NPY_1_22_API_VERSION
#include <Python.h>
#include <numpy/arrayobject.h>
#include <numpy/arrayscalars.h>
#include <numpy/ndarraytypes.h>
#include <numpy/ufuncobject.h>
#include <mp++/integer.hpp>
#include <mp++/real.hpp>
#if defined(HEYOKA_HAVE_REAL128)
#include <mp++/real128.hpp>
#endif
#include "common_utils.hpp"
#endif
#include "custom_casters.hpp"
#include "dtypes.hpp"
#include "expose_real.hpp"
#include "numpy_memory.hpp"
#if defined(HEYOKA_HAVE_REAL128)
#include "expose_real128.hpp"
#endif
namespace heyoka_py
{
namespace py = pybind11;
#if defined(HEYOKA_HAVE_REAL)
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#pragma GCC diagnostic ignored "-Wcast-align"
#if !defined(__clang__)
#pragma GCC diagnostic ignored "-Wcast-function-type"
#endif
#endif
// NOTE: more type properties will be filled in when initing the module.
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
PyTypeObject py_real_type = {PyVarObject_HEAD_INIT(nullptr, 0)};
// NOTE: this is an integer used to represent the
// real type *after* it has been registered in the
// NumPy dtype system. This is needed to expose
// ufuncs and it will be set up during module
// initialisation.
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
int npy_registered_py_real = 0;
namespace detail
{
namespace
{
// Double check that malloc() aligns memory suitably
// for py_real. See:
// https://en.cppreference.com/w/cpp/types/max_align_t
static_assert(alignof(py_real) <= alignof(std::max_align_t));
// A few function object to implement basic mathematical
// operations in a generic fashion.
const auto identity_func = [](const mppp::real &x) { return x; };
const auto identity_func2 = [](mppp::real &ret, const mppp::real &x) { ret = x; };
const auto negation_func = [](const mppp::real &x) { return -x; };
const auto negation_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::neg(ret, x); };
const auto abs_func = [](const mppp::real &x) { return mppp::abs(x); };
const auto abs_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::abs(ret, x); };
const auto floor_divide_func = [](const mppp::real &x, const mppp::real &y) { return mppp::floor(x / y); };
const auto floor_divide_func3 = [](mppp::real &ret, const mppp::real &x, const mppp::real &y) {
mppp::div(ret, x, y);
mppp::floor(ret, ret);
};
const auto pow_func = [](const mppp::real &x, const mppp::real &y) { return mppp::pow(x, y); };
const auto pow_func3 = [](mppp::real &ret, const mppp::real &x, const mppp::real &y) { mppp::pow(ret, x, y); };
const auto sqrt_func = [](const mppp::real &x) { return mppp::sqrt(x); };
const auto sqrt_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::sqrt(ret, x); };
const auto cbrt_func = [](const mppp::real &x) { return mppp::cbrt(x); };
const auto cbrt_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::cbrt(ret, x); };
const auto sin_func = [](const mppp::real &x) { return mppp::sin(x); };
const auto sin_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::sin(ret, x); };
const auto cos_func = [](const mppp::real &x) { return mppp::cos(x); };
const auto cos_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::cos(ret, x); };
const auto tan_func = [](const mppp::real &x) { return mppp::tan(x); };
const auto tan_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::tan(ret, x); };
const auto asin_func = [](const mppp::real &x) { return mppp::asin(x); };
const auto asin_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::asin(ret, x); };
const auto acos_func = [](const mppp::real &x) { return mppp::acos(x); };
const auto acos_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::acos(ret, x); };
const auto atan_func = [](const mppp::real &x) { return mppp::atan(x); };
const auto atan_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::atan(ret, x); };
const auto atan2_func = [](const mppp::real &x, const mppp::real &y) { return mppp::atan2(x, y); };
const auto atan2_func3 = [](mppp::real &ret, const mppp::real &x, const mppp::real &y) { mppp::atan2(ret, x, y); };
const auto sinh_func = [](const mppp::real &x) { return mppp::sinh(x); };
const auto sinh_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::sinh(ret, x); };
const auto cosh_func = [](const mppp::real &x) { return mppp::cosh(x); };
const auto cosh_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::cosh(ret, x); };
const auto tanh_func = [](const mppp::real &x) { return mppp::tanh(x); };
const auto tanh_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::tanh(ret, x); };
const auto asinh_func = [](const mppp::real &x) { return mppp::asinh(x); };
const auto asinh_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::asinh(ret, x); };
const auto acosh_func = [](const mppp::real &x) { return mppp::acosh(x); };
const auto acosh_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::acosh(ret, x); };
const auto atanh_func = [](const mppp::real &x) { return mppp::atanh(x); };
const auto atanh_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::atanh(ret, x); };
const auto deg2rad_func = [](const mppp::real &x) {
using safe_mpfr_prec_t = boost::safe_numerics::safe<mpfr_prec_t>;
// Compute 2*pi/360 with a few extra bits of precition wrt x.
const mpfr_prec_t prec = safe_mpfr_prec_t(x.get_prec()) + 10;
auto fact = mppp::real_pi(prec);
fact /= 180;
fact.prec_round(x.get_prec());
return x * std::move(fact);
};
const auto deg2rad_func2 = [](mppp::real &ret, const mppp::real &x) {
using safe_mpfr_prec_t = boost::safe_numerics::safe<mpfr_prec_t>;
// Compute 2*pi/360 with a few extra bits of precition wrt x.
const mpfr_prec_t prec = safe_mpfr_prec_t(x.get_prec()) + 10;
ret.set_prec(prec);
mppp::real_pi(ret);
ret /= 180;
ret.prec_round(x.get_prec());
ret *= x;
};
const auto rad2deg_func = [](const mppp::real &x) {
using safe_mpfr_prec_t = boost::safe_numerics::safe<mpfr_prec_t>;
// Compute 360/(2*pi) with a few extra bits of precition wrt x.
static const mppp::real c180(180);
const mpfr_prec_t prec = safe_mpfr_prec_t(x.get_prec()) + 10;
auto fact = mppp::real_pi(prec);
mppp::div(fact, c180, fact);
fact.prec_round(x.get_prec());
return x * std::move(fact);
};
const auto rad2deg_func2 = [](mppp::real &ret, const mppp::real &x) {
using safe_mpfr_prec_t = boost::safe_numerics::safe<mpfr_prec_t>;
// Compute 360/(2*pi) with a few extra bits of precition wrt x.
static const mppp::real c180(180);
const mpfr_prec_t prec = safe_mpfr_prec_t(x.get_prec()) + 10;
ret.set_prec(prec);
mppp::real_pi(ret);
mppp::div(ret, c180, ret);
ret.prec_round(x.get_prec());
ret *= x;
};
const auto exp_func = [](const mppp::real &x) { return mppp::exp(x); };
const auto exp_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::exp(ret, x); };
const auto exp2_func = [](const mppp::real &x) { return mppp::exp2(x); };
const auto exp2_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::exp2(ret, x); };
const auto expm1_func = [](const mppp::real &x) { return mppp::expm1(x); };
const auto expm1_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::expm1(ret, x); };
const auto log_func = [](const mppp::real &x) { return mppp::log(x); };
const auto log_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::log(ret, x); };
const auto log2_func = [](const mppp::real &x) { return mppp::log2(x); };
const auto log2_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::log2(ret, x); };
const auto log10_func = [](const mppp::real &x) { return mppp::log10(x); };
const auto log10_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::log10(ret, x); };
const auto log1p_func = [](const mppp::real &x) { return mppp::log1p(x); };
const auto log1p_func2 = [](mppp::real &ret, const mppp::real &x) { mppp::log1p(ret, x); };
const auto sign_func = [](const mppp::real &x) {
if (x.nan_p()) {
return x;
}
const auto sgn = x.sgn();
if (sgn == 0) {
return mppp::real(0, x.get_prec());
}
if (sgn < 0) {
return mppp::real(-1, x.get_prec());
}
return mppp::real(1, x.get_prec());
};
const auto sign_func2 = [](mppp::real &ret, const mppp::real &x) {
// NOTE: this already sets to nan.
ret.set_prec(x.get_prec());
if (!x.nan_p()) {
const auto sgn = x.sgn();
if (sgn == 0) {
ret.set_zero();
} else if (sgn == -1) {
ret.set(-1);
} else {
ret.set(1);
}
}
};
const auto min_func = [](const mppp::real &x, const mppp::real &y) { return std::min(x, y); };
const auto min_func3 = [](mppp::real &ret, const mppp::real &x, const mppp::real &y) { ret = std::min(x, y); };
const auto max_func = [](const mppp::real &x, const mppp::real &y) { return std::max(x, y); };
const auto max_func3 = [](mppp::real &ret, const mppp::real &x, const mppp::real &y) { ret = std::max(x, y); };
const auto isnan_func = [](const mppp::real &x) { return mppp::isnan(x); };
const auto isinf_func = [](const mppp::real &x) { return mppp::isinf(x); };
const auto isfinite_func = [](const mppp::real &x) { return mppp::isfinite(x); };
const auto square_func = [](const mppp::real &x) { return mppp::sqr(x); };
const auto square2_func = [](mppp::real &ret, const mppp::real &x) { mppp::sqr(ret, x); };
// Ternary arithmetic primitives.
const auto add3_func = [](mppp::real &ret, const mppp::real &a, const mppp::real &b) { mppp::add(ret, a, b); };
const auto sub3_func = [](mppp::real &ret, const mppp::real &a, const mppp::real &b) { mppp::sub(ret, a, b); };
const auto mul3_func = [](mppp::real &ret, const mppp::real &a, const mppp::real &b) { mppp::mul(ret, a, b); };
const auto div3_func = [](mppp::real &ret, const mppp::real &a, const mppp::real &b) { mppp::div(ret, a, b); };
// Methods for the number protocol.
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
PyNumberMethods py_real_as_number = {};
// Create a py_real containing an mppp::real
// constructed from the input set of arguments.
template <typename... Args>
PyObject *py_real_from_args(Args &&...args)
{
// Acquire the storage for a py_real.
void *pv = py_real_type.tp_alloc(&py_real_type, 0);
if (pv == nullptr) {
return nullptr;
}
// Construct the py_real instance.
// NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
auto *p = ::new (pv) py_real;
if (with_pybind11_eh([&]() {
// Setup its internal data.
::new (p->m_storage) mppp::real(std::forward<Args>(args)...);
})) {
// Clean up.
py_real_type.tp_free(pv);
return nullptr;
}
return reinterpret_cast<PyObject *>(p);
}
// __new__() implementation.
PyObject *py_real_new([[maybe_unused]] PyTypeObject *type, PyObject *, PyObject *)
{
assert(type == &py_real_type);
return py_real_from_args();
}
// Small helper to fetch the number of digits and the sign
// of a Python integer. The integer must be nonzero.
auto py_int_size_sign(PyLongObject *nptr)
{
#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION <= 11
// Fetch the signed size.
const auto ob_size = nptr->ob_base.ob_size;
assert(ob_size != 0);
// Is it negative?
const auto neg = ob_size < 0;
// Compute the unsigned size.
using size_type = std::make_unsigned_t<std::remove_const_t<decltype(ob_size)>>;
static_assert(std::is_same_v<size_type, decltype(static_cast<size_type>(0) + static_cast<size_type>(0))>);
auto abs_ob_size = neg ? -static_cast<size_type>(ob_size) : static_cast<size_type>(ob_size);
#else
// NOTE: these shifts and mask values come from here:
// https://github.com/python/cpython/blob/main/Include/internal/pycore_long.h
// Not sure if we can rely on this moving on, probably needs to be checked
// at every new Python release. Also, note that lv_tag is unsigned, so
// here we are always getting directly the absolute value of the size,
// unlike in Python<3.12 where we get out a signed size.
const auto abs_ob_size = nptr->long_value.lv_tag >> 3;
assert(abs_ob_size != 0u);
// Is it negative?
const auto neg = (nptr->long_value.lv_tag & 3) == 2;
#endif
return std::make_pair(abs_ob_size, neg);
}
// Helper to convert a Python integer to an mp++ real.
// The precision of the result is inferred from the
// bit size of the integer.
// NOTE: for better performance if needed, it would be better
// to avoid the construction of an intermediate mppp::integer
// (perhaps via determining the bit length of arg beforehand?).
std::optional<mppp::real> py_int_to_real(PyObject *arg)
{
assert(PyObject_IsInstance(arg, reinterpret_cast<PyObject *>(&PyLong_Type)));
// Prepare the return value.
std::optional<mppp::real> retval;
with_pybind11_eh([&]() {
// Try to see if arg fits in a long or a long long.
int overflow = 0;
const auto cand_l = PyLong_AsLongAndOverflow(arg, &overflow);
// NOTE: PyLong_AsLongAndOverflow() can raise exceptions in principle.
if (PyErr_Occurred() != nullptr) {
return;
}
if (overflow == 0) {
retval.emplace(cand_l);
return;
}
overflow = 0;
const auto cand_ll = PyLong_AsLongLongAndOverflow(arg, &overflow);
// NOTE: PyLong_AsLongLongAndOverflow() can raise exceptions in principle.
if (PyErr_Occurred() != nullptr) {
return;
}
if (overflow == 0) {
retval.emplace(cand_ll);
return;
}
// Need to construct a multiprecision integer from the limb array.
auto *nptr = reinterpret_cast<PyLongObject *>(arg);
// Get the size and sign of nptr.
auto [abs_ob_size, neg] = py_int_size_sign(nptr);
// Get the limbs array.
#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION <= 11
const auto *ob_digit = nptr->ob_digit;
#else
const auto *ob_digit = nptr->long_value.ob_digit;
#endif
// Init the retval with the first (most significant) limb. The Python integer is nonzero, so this is safe.
mppp::integer<1> retval_int = ob_digit[--abs_ob_size];
// Keep on reading limbs until we run out of limbs.
while (abs_ob_size != 0u) {
retval_int <<= PyLong_SHIFT;
retval_int += ob_digit[--abs_ob_size];
}
// Turn into an mppp::real.
mppp::real ret(retval_int);
// Negate if necessary.
if (neg) {
retval.emplace(-std::move(ret));
} else {
retval.emplace(std::move(ret));
}
});
// NOTE: if exceptions are raised in the C++ code,
// retval will remain empty.
return retval;
}
// Helper to convert a Python integer to an mp++ real.
// The precision of the result is provided explicitly.
// NOTE: this currently uses a string conversion for
// large integers.
std::optional<mppp::real> py_int_to_real_with_prec(PyObject *arg, mpfr_prec_t prec)
{
assert(PyObject_IsInstance(arg, reinterpret_cast<PyObject *>(&PyLong_Type)));
// Prepare the return value.
std::optional<mppp::real> retval;
with_pybind11_eh([&]() {
// Try to see if arg fits in a long long.
int overflow = 0;
const auto cand_ll = PyLong_AsLongLongAndOverflow(arg, &overflow);
// NOTE: PyLong_AsLongLongAndOverflow() can raise exceptions in principle.
if (PyErr_Occurred() != nullptr) {
return;
}
if (overflow == 0) {
retval.emplace(cand_ll, prec);
return;
}
// Go through a string conversion.
auto *str_rep = PyObject_Str(arg);
if (str_rep == nullptr) {
return;
}
assert(PyUnicode_Check(str_rep) != 0);
// NOTE: str remains valid as long as str_rep is alive.
const auto *str = PyUnicode_AsUTF8(str_rep);
if (str == nullptr) {
Py_DECREF(str_rep);
return;
}
try {
retval.emplace(str, prec);
} catch (...) {
// Ensure proper cleanup of str_rep
// before continuing.
Py_DECREF(str_rep);
throw;
}
Py_DECREF(str_rep);
});
// NOTE: if exceptions are raised in the C++ code,
// retval will remain empty.
return retval;
}
// __init__() implementation.
int py_real_init(PyObject *self, PyObject *args, PyObject *kwargs)
{
PyObject *arg = nullptr;
PyObject *prec_arg = nullptr;
const char *kwlist[] = {"value", "prec", nullptr};
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
if (PyArg_ParseTupleAndKeywords(args, kwargs, "|OO", const_cast<char **>(&kwlist[0]), &arg, &prec_arg) == 0) {
return -1;
}
// If no arguments are passed, leave the object as constructed
// by py_real_new() - that is, the value is zero and the precision
// is the minimum possible.
if (arg == nullptr) {
if (prec_arg != nullptr) {
PyErr_SetString(PyExc_ValueError,
"Cannot construct a real from a precision only - a value must also be supplied");
return -1;
}
return 0;
}
// Init the precision argument, if provided.
std::optional<mpfr_prec_t> prec;
if (prec_arg != nullptr) {
// Attempt to turn the precision supplied by the
// user into a long long.
const auto prec_arg_val = PyLong_AsLongLong(prec_arg);
if (PyErr_Occurred() != nullptr) {
return -1;
}
// Check it.
if (prec_arg_val < std::numeric_limits<mpfr_prec_t>::min()
|| prec_arg_val > std::numeric_limits<mpfr_prec_t>::max()) {
PyErr_Format(PyExc_OverflowError, "A precision of %lli is too large in magnitude and results in overflow",
prec_arg_val);
return -1;
}
prec.emplace(static_cast<mpfr_prec_t>(prec_arg_val));
}
// Cache a real pointer to self.
auto *rval = get_real_val(self);
// Handle the supported types for the input value.
if (PyFloat_Check(arg)) {
// Double.
const auto d_val = PyFloat_AsDouble(arg);
if (PyErr_Occurred() == nullptr) {
const auto err = with_pybind11_eh([&]() {
if (prec) {
rval->set_prec(*prec);
mppp::set(*rval, d_val);
} else {
*rval = d_val;
}
});
if (err) {
return -1;
}
} else {
return -1;
}
} else if (PyLong_Check(arg)) {
// Int.
if (auto opt = prec ? py_int_to_real_with_prec(arg, *prec) : py_int_to_real(arg)) {
// NOTE: it's important to move here, so that we don't have to bother
// with exception handling.
*rval = std::move(*opt);
} else {
return -1;
}
} else if (PyObject_IsInstance(arg, reinterpret_cast<PyObject *>(&PyFloat32ArrType_Type)) != 0) {
const auto f32_val = reinterpret_cast<PyFloat32ScalarObject *>(arg)->obval;
const auto err = with_pybind11_eh([&]() {
if (prec) {
rval->set_prec(*prec);
mppp::set(*rval, f32_val);
} else {
*rval = f32_val;
}
});
if (err) {
return -1;
}
} else if (PyObject_IsInstance(arg, reinterpret_cast<PyObject *>(&PyLongDoubleArrType_Type)) != 0) {
const auto ld_val = reinterpret_cast<PyLongDoubleScalarObject *>(arg)->obval;
const auto err = with_pybind11_eh([&]() {
if (prec) {
rval->set_prec(*prec);
mppp::set(*rval, ld_val);
} else {
*rval = ld_val;
}
});
if (err) {
return -1;
}
#if defined(HEYOKA_HAVE_REAL128)
} else if (py_real128_check(arg)) {
const auto f128_val = *get_real128_val(arg);
const auto err = with_pybind11_eh([&]() {
if (prec) {
rval->set_prec(*prec);
mppp::set(*rval, f128_val);
} else {
*rval = f128_val;
}
});
if (err) {
return -1;
}
#endif
} else if (py_real_check(arg)) {
auto *rval2 = get_real_val(arg);
const auto err = with_pybind11_eh([&]() {
if (prec) {
rval->set_prec(*prec);
mppp::set(*rval, *rval2);
} else {
*rval = *rval2;
}
});
if (err) {
return -1;
}
} else if (PyUnicode_Check(arg)) {
if (!prec) {
PyErr_SetString(PyExc_ValueError, "Cannot construct a real from a string without a precision value");
return -1;
}
const auto *str = PyUnicode_AsUTF8(arg);
if (str == nullptr) {
return -1;
}
const auto err = with_pybind11_eh([&]() {
rval->set_prec(*prec);
mppp::set(*rval, str);
});
if (err) {
return -1;
}
} else {
PyErr_Format(PyExc_TypeError, "Cannot construct a real from an object of type \"%s\"", Py_TYPE(arg)->tp_name);
return -1;
}
return 0;
}
// __repr__().
PyObject *py_real_repr(PyObject *self)
{
PyObject *retval = nullptr;
// NOTE: C++ exceptions here can be thrown only *before*
// the invocation of PyUnicode_FromString(). Hence, in case of
// exceptions, retval will remain nullptr.
with_pybind11_eh([&]() { retval = PyUnicode_FromString(get_real_val(self)->to_string().c_str()); });
return retval;
}
// Deallocation.
void py_real_dealloc(PyObject *self)
{
assert(py_real_check(self));
// Invoke the destructor.
get_real_val(self)->~real();
// Free the memory.
Py_TYPE(self)->tp_free(self);
}
// Helper to construct a real from one of the
// supported Pythonic numerical types:
// - int,
// - float32,
// - float,
// - long double,
// - real128.
// If the conversion is successful, returns {x, true}. If some error
// is encountered, returns {<empty>, false}. If the type of arg is not
// supported, returns {<empty>, true}.
std::pair<std::optional<mppp::real>, bool> real_from_ob(PyObject *arg)
{
std::pair<std::optional<mppp::real>, bool> ret;
with_pybind11_eh([&]() {
if (PyFloat_Check(arg)) {
auto fp_arg = PyFloat_AsDouble(arg);
if (PyErr_Occurred() == nullptr) {
ret.first.emplace(fp_arg);
ret.second = true;
} else {
ret.second = false;
}
} else if (PyLong_Check(arg)) {
if (auto opt = py_int_to_real(arg)) {
ret.first.emplace(std::move(*opt));
ret.second = true;
} else {
ret.second = false;
}
} else if (PyObject_IsInstance(arg, reinterpret_cast<PyObject *>(&PyFloat32ArrType_Type)) != 0) {
ret.first.emplace(reinterpret_cast<PyFloat32ScalarObject *>(arg)->obval);
ret.second = true;
} else if (PyObject_IsInstance(arg, reinterpret_cast<PyObject *>(&PyLongDoubleArrType_Type)) != 0) {
ret.first.emplace(reinterpret_cast<PyLongDoubleScalarObject *>(arg)->obval);
ret.second = true;
#if defined(HEYOKA_HAVE_REAL128)
} else if (py_real128_check(arg)) {
ret.first.emplace(*get_real128_val(arg));
ret.second = true;
#endif
} else {
ret.second = true;
}
});
return ret;
}
// The precision getter.
PyObject *py_real_prec_getter(PyObject *self, void *)
{
assert(py_real_check(self));
return PyLong_FromLongLong(static_cast<long long>(get_real_val(self)->get_prec()));
}
// The limb address getter.
PyObject *py_real_limb_address_getter(PyObject *self, void *)
{
assert(py_real_check(self));
return PyLong_FromUnsignedLongLong(
static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(get_real_val(self)->get_mpfr_t()->_mpfr_d)));
}
// The array for computed attribute instances. See:
// https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_getset
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
PyGetSetDef py_real_get_set[] = {{"prec", py_real_prec_getter, nullptr, nullptr, nullptr},
{"_limb_address", py_real_limb_address_getter, nullptr, nullptr, nullptr},
{nullptr}};
// Implementation of several methods for real.
PyObject *py_real_set_prec(PyObject *self, PyObject *args)
{
long long prec = 0;
if (PyArg_ParseTuple(args, "L", &prec) == 0) {
return nullptr;
}
const auto err = with_pybind11_eh([&]() { get_real_val(self)->set_prec(boost::numeric_cast<mpfr_prec_t>(prec)); });
if (err) {
return nullptr;
}
Py_RETURN_NONE;
}
PyObject *py_real_prec_round(PyObject *self, PyObject *args)
{
long long prec = 0;
if (PyArg_ParseTuple(args, "L", &prec) == 0) {
return nullptr;
}
const auto err
= with_pybind11_eh([&]() { get_real_val(self)->prec_round(boost::numeric_cast<mpfr_prec_t>(prec)); });
if (err) {
return nullptr;
}
Py_RETURN_NONE;
}
PyObject *py_real_copy(PyObject *self, [[maybe_unused]] PyObject *args)
{
assert(args == nullptr);
PyObject *retval = nullptr;
with_pybind11_eh([&]() { retval = py_real_from_args(*get_real_val(self)); });
return retval;
}
PyObject *py_real_deepcopy(PyObject *self, PyObject *args, PyObject *kwargs)
{
PyObject *memo_arg = nullptr;
const char *kwlist[] = {"memo", nullptr};
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
if (PyArg_ParseTupleAndKeywords(args, kwargs, "|O", const_cast<char **>(&kwlist[0]), &memo_arg) == 0) {
return nullptr;
}
PyObject *retval = nullptr;
with_pybind11_eh([&]() { retval = py_real_from_args(*get_real_val(self)); });
return retval;
}
// Get the internal state of a real for serialisation purposes. The internal
// state is returned as a binary blob.
PyObject *py_real_getstate(PyObject *self, [[maybe_unused]] PyObject *args)
{
assert(args == nullptr);
PyObject *retval = nullptr;
with_pybind11_eh([&]() {
std::ostringstream ss;
{
boost::archive::binary_oarchive oa(ss);
oa << *get_real_val(self);
}
// NOTE: we might be able to avoid a copy here if we manage to operate
// directly on the stringstream.
const auto str = ss.str();
retval = PyBytes_FromStringAndSize(str.c_str(), boost::numeric_cast<Py_ssize_t>(str.size()));
});
return retval;
}
// Set the internal state of a real from a binary blob.
PyObject *py_real_setstate(PyObject *self, PyObject *args)
{
PyBytesObject *bytes_obj = nullptr;
if (PyArg_ParseTuple(args, "S", &bytes_obj) == 0) {
return nullptr;
}
assert(bytes_obj != nullptr);
auto *ob_ptr = reinterpret_cast<PyObject *>(bytes_obj);
const auto err = with_pybind11_eh([&]() {
std::stringstream ss;
std::copy(PyBytes_AsString(ob_ptr), PyBytes_AsString(ob_ptr) + PyBytes_Size(ob_ptr),
std::ostreambuf_iterator<char>(ss));
boost::archive::binary_iarchive ia(ss);
ia >> *get_real_val(self);
});
if (err) {
return nullptr;
}
Py_RETURN_NONE;
}
// Implementation of the reduce protocol. See:
// https://docs.python.org/3/library/pickle.html#object.__reduce__
PyObject *py_real_reduce(PyObject *self, [[maybe_unused]] PyObject *args)
{
assert(args == nullptr);
// Fetch the factory function.
auto *hy_mod = PyImport_ImportModule("heyoka");
if (hy_mod == nullptr) {
return nullptr;
}
auto *fact = PyObject_GetAttrString(hy_mod, "_real_reduce_factory");
Py_DECREF(hy_mod);
if (fact == nullptr) {
return nullptr;
}
// The factory function requires no arguments.
auto *fact_args = PyTuple_New(0);
if (fact_args == nullptr) {
Py_DECREF(fact);
return nullptr;
}
// Get the state of self.
auto *state = py_real_getstate(self, nullptr);
if (state == nullptr) {
Py_DECREF(fact);
Py_DECREF(fact_args);
return nullptr;
}
// Assemble the return value.
auto *ret = PyTuple_New(3);
if (ret == nullptr) {
Py_DECREF(fact);
Py_DECREF(fact_args);
Py_DECREF(state);
return nullptr;
}
PyTuple_SetItem(ret, 0, fact);
PyTuple_SetItem(ret, 1, fact_args);
PyTuple_SetItem(ret, 2, state);
return ret;
}
// Same as py_real_reduce(), but takes in input a protocol version
// number which we ignore.
PyObject *py_real_reduce_ex(PyObject *self, PyObject *args)
{
int version = 0;
if (PyArg_ParseTuple(args, "i", &version) == 0) {
return nullptr;
}
return py_real_reduce(self, nullptr);
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
PyMethodDef py_real_methods[]
= {{"set_prec", py_real_set_prec, METH_VARARGS, nullptr},
{"prec_round", py_real_prec_round, METH_VARARGS, nullptr},
{"__copy__", py_real_copy, METH_NOARGS, nullptr},
{"__deepcopy__", reinterpret_cast<PyCFunction>(reinterpret_cast<void *>(py_real_deepcopy)),
METH_VARARGS | METH_KEYWORDS, nullptr},
// NOTE: for pickling support we need to override the reduce/reduce_ex functions, as they
// are implemented in the base NumPy class and they take the precedence over get/set state.
{"__setstate__", py_real_setstate, METH_VARARGS, nullptr},
{"__reduce__", py_real_reduce, METH_NOARGS, nullptr},
{"__reduce_ex__", py_real_reduce_ex, METH_VARARGS, nullptr},
{nullptr}};
// Generic implementation of unary operations.
template <typename F>