-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapyfixedarray.cc
More file actions
2101 lines (1880 loc) · 80.7 KB
/
Copy pathapyfixedarray.cc
File metadata and controls
2101 lines (1880 loc) · 80.7 KB
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
// Python details. These should be included before standard header files:
// https://docs.python.org/3/c-api/intro.html#include-files
#include <Python.h> // PYLONG_BITS_IN_DIGIT, PyLongObject
#include "apybuffer.h"
#include "apyfixed.h"
#include "apyfixed_util.h"
#include "apyfixedarray.h"
#include "apytypes_common.h"
#include "apytypes_mp.h"
#include "apytypes_simd.h"
#include "apytypes_util.h"
#include "array_utils.h"
#include "python_util.h"
// Python object access through Nanobind
#include <nanobind/nanobind.h>
#include <nanobind/ndarray.h>
#include <nanobind/stl/variant.h> // std::variant (with nanobind support)
namespace nb = nanobind;
// Standard header includes
#include <algorithm> // std::copy, std::max, std::transform, etc...
#include <cstddef> // std::size_t
#include <cstdint> // std::int16, std::int32, std::int64, etc...
#include <iterator> // std::iterator
#include <optional> // std::optional
#include <set> // std::set
#include <stdexcept> // std::length_error
#include <string> // std::string
#include <utility> // std::move
#include <variant> // std::variant
#include <vector> // std::vector, std::swap
#include <fmt/format.h>
/* ********************************************************************************** *
* * Python constructors * *
* ********************************************************************************** */
APyFixedArray::APyFixedArray(
const nb::typed<nb::iterable, nb::any>& bit_pattern_sequence,
std::optional<int> int_bits,
std::optional<int> frac_bits,
std::optional<int> bits
)
: APyFixedArray(
python_iterable_extract_shape(bit_pattern_sequence, "APyFixedArray.__init__"),
int_bits,
frac_bits,
bits
)
{
// Specialized initialization for NDArray
if (nb::isinstance<nb::ndarray<>>(bit_pattern_sequence)) {
auto ndarray = nb::cast<nb::ndarray<nb::c_contig>>(bit_pattern_sequence);
_set_bits_from_ndarray(ndarray);
return; // initialization completed
}
// 1D vector of Python int object (`nb::int_` objects)
auto python_ints = python_iterable_walk<nb::int_>(
bit_pattern_sequence, "APyFixedArray.__init__"
);
for (std::size_t i = 0; i < _data.size() / _itemsize; i++) {
nb::int_ python_int = nb::cast<nb::int_>(python_ints[i]);
auto limb_vec = python_long_to_limb_vec(python_int, _itemsize);
_overflow_twos_complement(
std::begin(limb_vec), std::end(limb_vec), _bits, _int_bits
);
std::copy_n(std::begin(limb_vec), _itemsize, std::begin(_data) + i * _itemsize);
}
}
/* ********************************************************************************** *
* * More C++ accessible constructors * *
* ********************************************************************************** */
APyFixedArray::APyFixedArray(
const std::vector<std::size_t>& shape, int bits, int int_bits
)
: APyArray(shape, bits_to_limbs(bits))
, _bits { bits }
, _int_bits { int_bits }
{
}
APyFixedArray::APyFixedArray(
const std::vector<std::size_t>& shape, int bits, int int_bits, vector_type&& v
)
: APyArray(shape, bits_to_limbs(bits), std::move(v))
, _bits { bits }
, _int_bits { int_bits }
{
}
APyFixedArray::APyFixedArray(
const std::vector<std::size_t>& shape,
std::optional<int> int_bits,
std::optional<int> frac_bits,
std::optional<int> bits
)
: APyArray(shape, bits_to_limbs(bits_from_optional(bits, int_bits, frac_bits)))
, _bits { bits.has_value() ? *bits : *int_bits + *frac_bits }
, _int_bits { int_bits.has_value() ? *int_bits : *bits - *frac_bits }
{
}
/* ********************************************************************************** *
* * Binary arithmetic operators * *
* ********************************************************************************** */
template <class ripple_carry_op, class simd_op, class simd_shift_op>
inline APyFixedArray
APyFixedArray::_apyfixedarray_base_add_sub(const APyFixedArray& rhs) const
{
// Increase word length of result by one
const int res_int_bits = std::max(rhs.int_bits(), int_bits()) + 1;
const int res_frac_bits = std::max(rhs.frac_bits(), frac_bits());
const int res_bits = res_int_bits + res_frac_bits;
// Resulting vector
APyFixedArray result(_shape, res_bits, res_int_bits);
// Special case #1: Operands and result fit in single limb
if (unsigned(res_bits) <= APY_LIMB_SIZE_BITS) {
if (frac_bits() == rhs.frac_bits()) {
// Operands have equally many fractional bits.
simd_op {}(
_data.begin(),
rhs._data.begin(),
result._data.begin(),
result._data.size()
);
} else {
auto rhs_shift_amount = unsigned(res_frac_bits - rhs.frac_bits());
auto lhs_shift_amount = unsigned(res_frac_bits - frac_bits());
simd_shift_op {}(
_data.begin(),
rhs._data.begin(),
result._data.begin(),
lhs_shift_amount,
rhs_shift_amount,
result._data.size()
);
}
return result; // early exit
}
// Special case #2: Operands and result have equally many limbs
if (result._itemsize == _itemsize && result._itemsize == rhs._itemsize) {
const apy_limb_t* src1_ptr;
const apy_limb_t* src2_ptr;
if (frac_bits() == rhs.frac_bits()) {
// Right-hand side and left-hand side have equally many fractional bits
src1_ptr = &_data[0];
src2_ptr = &rhs._data[0];
} else if (frac_bits() <= rhs.frac_bits()) {
// Right-hand side has more fractional bits. Upsize `*this`
_cast_no_quantize_no_overflow(
std::begin(_data), // src
std::begin(result._data), // dst
_itemsize, // src_limbs
result._itemsize, // dst_limbs
_nitems, // n_items
result.frac_bits() - frac_bits() // left_shift_amount
);
src1_ptr = &result._data[0];
src2_ptr = &rhs._data[0];
} else {
// Left-hand side has more fractional bits. Upsize `rhs`
_cast_no_quantize_no_overflow(
std::begin(rhs._data), // src
std::begin(result._data), // dst
rhs._itemsize, // src_limbs
result._itemsize, // dst_limbs
rhs._nitems, // n_items
result.frac_bits() - rhs.frac_bits() // left_shift_amount
);
src1_ptr = &_data[0];
src2_ptr = &result._data[0];
}
for (std::size_t i = 0; i < result._data.size(); i += result._itemsize) {
ripple_carry_op {}(
&result._data[i], // dst
&src1_ptr[i], // src1
&src2_ptr[i], // src2
result._itemsize // limb vector length
);
}
return result; // early exit
}
// Most general case: Works in any situation, but is slowest
APyFixedArray imm(_shape, res_bits, res_int_bits);
_cast_no_quantize_no_overflow(
std::begin(_data), // src
std::begin(result._data), // dst
_itemsize, // src_limbs
result._itemsize, // dst_limbs
_nitems, // n_items
result.frac_bits() - frac_bits() // left_shift_amount
);
_cast_no_quantize_no_overflow(
std::begin(rhs._data), // src
std::begin(imm._data), // dst
rhs._itemsize, // src_limbs
imm._itemsize, // dst_limbs
rhs._nitems, // n_items
imm.frac_bits() - rhs.frac_bits() // left_shift_amount
);
// Perform ripple-carry operation for each element
for (std::size_t i = 0; i < result._data.size(); i += result._itemsize) {
ripple_carry_op {}(
&result._data[i], // dst
&result._data[i], // src1
&imm._data[i], // src2
result._itemsize // limb vector length
);
}
return result;
}
template <class ripple_carry_op, class simd_op_const, class simd_shift_op_const>
inline APyFixedArray APyFixedArray::_apyfixed_base_add_sub(const APyFixed& rhs) const
{
// Increase word length of result by one
const int res_int_bits = std::max(rhs.int_bits(), int_bits()) + 1;
const int res_frac_bits = std::max(rhs.frac_bits(), frac_bits());
const int res_bits = res_int_bits + res_frac_bits;
// Resulting vector
APyFixedArray result(_shape, res_bits, res_int_bits);
// Special case #1: Operands and result fit in single limb
if (unsigned(res_bits) <= APY_LIMB_SIZE_BITS) {
if (frac_bits() == rhs.frac_bits()) {
// Operands have equally many fractional bits.
simd_op_const {}(
_data.begin(), rhs._data[0], result._data.begin(), result._data.size()
);
} else {
auto rhs_shift_amount = unsigned(res_frac_bits - rhs.frac_bits());
auto lhs_shift_amount = unsigned(res_frac_bits - frac_bits());
simd_shift_op_const {}(
std::begin(_data), // src1
rhs._data[0] << rhs_shift_amount, // constant
std::begin(result._data), // dst
lhs_shift_amount, // src1 shift amount
result._data.size()
);
}
return result; // early exit
}
// Most general case: Works in any situation, but is slowest
APyFixed imm(res_bits, res_int_bits);
auto rhs_shift_amount = unsigned(res_frac_bits - rhs.frac_bits());
auto lhs_shift_amount = unsigned(res_frac_bits - frac_bits());
_cast_no_quantize_no_overflow(
std::begin(_data), // src
std::begin(result._data), // dst
_itemsize, // src_limbs
result._itemsize, // dst_limbs
_nitems, // n_items
lhs_shift_amount // left_shift_amount
);
_cast_no_quantize_no_overflow(
std::begin(rhs._data),
std::end(rhs._data),
std::begin(imm._data),
std::end(imm._data),
rhs_shift_amount
);
for (std::size_t i = 0; i < result._data.size(); i += result._itemsize) {
// Perform ripple-carry operation
ripple_carry_op {}(
&result._data[i], // dst
&result._data[i], // src1
&imm._data[0], // src2
result._itemsize // limb vector length
);
}
return result;
}
APyFixedArray APyFixedArray::operator+(const APyFixedArray& rhs) const
{
if (_shape != rhs._shape) {
return try_broadcast_and_then<std::plus<>>(rhs, "__add__");
}
return _apyfixedarray_base_add_sub<
apy_add_n_functor<>,
simd::add_functor<>,
simd::shift_add_functor<>>(rhs);
}
APyFixedArray APyFixedArray::operator+(const APyFixed& rhs) const
{
return _apyfixed_base_add_sub<
apy_add_n_functor<>,
simd::add_const_functor<>,
simd::shift_add_const_functor<>>(rhs);
}
APyFixedArray APyFixedArray::operator-(const APyFixedArray& rhs) const
{
if (_shape != rhs._shape) {
return try_broadcast_and_then<std::minus<>>(rhs, "__sub__");
}
return _apyfixedarray_base_add_sub<
apy_sub_n_functor<>,
simd::sub_functor<>,
simd::shift_sub_functor<>>(rhs);
}
APyFixedArray APyFixedArray::operator-(const APyFixed& rhs) const
{
return _apyfixed_base_add_sub<
apy_sub_n_functor<>,
simd::sub_const_functor<>,
simd::shift_sub_const_functor<>>(rhs);
}
// Scalar - Array
APyFixedArray APyFixedArray::rsub(const APyFixed& lhs) const
{
// Increase word length of result by one
const int res_int_bits = std::max(lhs.int_bits(), int_bits()) + 1;
const int res_frac_bits = std::max(lhs.frac_bits(), frac_bits());
const int res_bits = res_int_bits + res_frac_bits;
// Adjust binary point
APyFixedArray result(_shape, res_bits, res_int_bits);
_cast_no_quantize_no_overflow(
std::begin(_data), // src
std::begin(result._data), // dst
_itemsize, // src_limbs
result._itemsize, // dst_limbs
_nitems, // n_items
result.frac_bits() - frac_bits() // left_shift_amount
);
auto lhs_shift_amount = unsigned(res_frac_bits - lhs.frac_bits());
if (unsigned(res_bits) <= APY_LIMB_SIZE_BITS) {
apy_limb_t operand = lhs._data[0] << lhs_shift_amount;
simd::vector_rsub_const(
result._data.begin(), operand, result._data.begin(), result._data.size()
);
} else {
APyFixed imm(res_bits, res_int_bits);
_cast_no_quantize_no_overflow(
std::begin(lhs._data), // src_begin
std::end(lhs._data), // src_end
std::begin(imm._data), // dst_begin
std::end(imm._data), // dst_end
lhs_shift_amount
);
// Perform subtraction
for (std::size_t i = 0; i < result._data.size(); i += result._itemsize) {
apy_inplace_reversed_subtraction_same_length(
&result._data[i], // dst/src2
&imm._data[0], // src1
result._itemsize // limb vector length
);
}
}
// Return result
return result;
}
APyFixedArray APyFixedArray::operator*(const APyFixedArray& rhs) const
{
if (_shape != rhs._shape) {
return try_broadcast_and_then<std::multiplies<>>(rhs, "__mul__");
}
const int res_int_bits = int_bits() + rhs.int_bits();
const int res_bits = bits() + rhs.bits();
// Resulting `APyFixedArray` fixed-point tensor
APyFixedArray result(_shape, res_bits, res_int_bits);
if (unsigned(res_bits) <= APY_LIMB_SIZE_BITS) {
// Special case #1: The resulting number of bits fit in a single limb
simd::vector_mul(
std::begin(_data), // src1
std::begin(rhs._data), // src2
std::begin(result._data), // dst
result._data.size() // elements
);
} else if (unsigned(bits()) <= APY_LIMB_SIZE_BITS
&& unsigned(rhs.bits()) <= APY_LIMB_SIZE_BITS) {
// Special case #2: Both arguments are single limb, result two limbs
for (std::size_t i = 0; i < _nitems; i++) {
auto [high, low] = long_signed_mult(_data[i], rhs._data[i]);
result._data[i * 2 + 1] = high;
result._data[i * 2 + 0] = low;
}
} else {
// General case: This always works but is slower than the special cases.
fixed_point_hadamard_product(
std::begin(_data), // src1
std::begin(rhs._data), // src2
std::begin(result._data), // dst
_itemsize, // src1_limbs
rhs._itemsize, // src2_limbs
result._itemsize, // dst_limbs
_nitems // n_items
);
}
return result;
}
APyFixedArray APyFixedArray::operator*(const APyFixed& rhs) const
{
const int res_int_bits = int_bits() + rhs.int_bits();
const int res_bits = bits() + rhs.bits();
// Resulting `APyFixedArray` fixed-point tensor
APyFixedArray result(_shape, res_bits, res_int_bits);
// Special case #1: The resulting number of bits fit in a single limb
if (unsigned(res_bits) <= APY_LIMB_SIZE_BITS) {
simd::vector_mul_const(
std::begin(_data), // src1
rhs._data[0], // src2
std::begin(result._data), // dst
result._data.size() // elements
);
return result; // early exit
}
// Special case #2: Both arguments are single limb, result two limbs
if (unsigned(bits()) <= APY_LIMB_SIZE_BITS
&& unsigned(rhs.bits()) <= APY_LIMB_SIZE_BITS) {
for (std::size_t i = 0; i < _nitems; i++) {
auto [high, low] = long_signed_mult(_data[i], rhs._data[0]);
result._data[i * 2 + 1] = high;
result._data[i * 2 + 0] = low;
}
return result;
}
// General case: This always works but is slower than the special cases.
auto op2_begin = rhs._data.begin();
auto op2_end = rhs._data.begin() + rhs.vector_size();
std::vector<apy_limb_t> op2_abs(rhs.vector_size());
// Compute the absolute value of operand, as required by multiplication algorithm
bool sign2 = limb_vector_abs(op2_begin, op2_end, op2_abs.begin());
// Perform multiplication for each element in the tensor.
// `apy_unsigned_multiplication` requires: "The destination has to have space for
// `s1n` + `s2n` limbs, even if the product’s most significant limbs are zero."
std::vector<apy_limb_t> res_tmp_vec(_itemsize + rhs.vector_size(), 0);
std::vector<apy_limb_t> op1_abs(_itemsize);
auto op1_begin = _data.begin();
for (std::size_t i = 0; i < _nitems; i++) {
// Current working operands
auto op1_end = op1_begin + _itemsize;
// Compute the absolute value of operand, as required by multiplication
// algorithm
bool sign1 = limb_vector_abs(op1_begin, op1_end, op1_abs.begin());
// Evaluate resulting sign
bool result_sign = sign1 ^ sign2;
// Perform the multiplication
if (op1_abs.size() < op2_abs.size()) {
apy_unsigned_multiplication(
&res_tmp_vec[0], // dst
&op2_abs[0], // src1
op2_abs.size(), // src1 limb vector length
&op1_abs[0], // src2
op1_abs.size() // src2 limb vector length
);
} else {
apy_unsigned_multiplication(
&res_tmp_vec[0], // dst
&op1_abs[0], // src1
op1_abs.size(), // src1 limb vector length
&op2_abs[0], // src2
op2_abs.size() // src2 limb vector length
);
}
// Handle sign
if (result_sign) {
limb_vector_negate(
res_tmp_vec.begin(),
res_tmp_vec.begin() + result._itemsize,
result._data.begin() + (i + 0) * result._itemsize
);
} else {
// Copy into resulting vector
std::copy_n(
res_tmp_vec.begin(),
result._itemsize,
result._data.begin() + (i + 0) * result._itemsize
);
}
op1_begin = op1_end;
}
return result;
}
APyFixedArray APyFixedArray::operator/(const APyFixedArray& rhs) const
{
if (_shape != rhs._shape) {
return try_broadcast_and_then<std::divides<>>(rhs, "__truediv__");
}
const int res_int_bits = int_bits() + rhs.frac_bits() + 1;
const int res_frac_bits = frac_bits() + rhs.int_bits();
const int res_bits = res_int_bits + res_frac_bits;
APyFixedArray result(_shape, res_bits, res_int_bits);
// Special case #1: The resulting number of bits fit in a single limb
if (unsigned(res_bits) <= APY_LIMB_SIZE_BITS) {
simd::vector_shift_div_signed(
std::begin(_data), // src1 (numerator)
std::begin(rhs._data), // src2 (denominator)
std::begin(result._data), // dst
rhs.bits(), // numerator shift amount
_data.size() // vector elements
);
return result; // early exit
}
// General case: This always works but is slower than the special cases.
// Absolute value denominator
ScratchVector<apy_limb_t> abs_den(rhs._itemsize);
// Absolute value left-shifted numerator
ScratchVector<apy_limb_t> abs_num(result._itemsize);
for (std::size_t i = 0; i < _nitems; i++) {
std::fill(std::begin(abs_num), std::end(abs_num), 0);
if (limb_vector_is_zero(
std::begin(rhs._data) + (i + 0) * rhs._itemsize,
std::begin(rhs._data) + (i + 1) * rhs._itemsize
)) {
continue;
}
bool den_sign = limb_vector_abs(
std::begin(rhs._data) + (i + 0) * rhs._itemsize,
std::begin(rhs._data) + (i + 1) * rhs._itemsize,
std::begin(abs_den)
);
bool num_sign = limb_vector_abs(
std::begin(_data) + (i + 0) * _itemsize,
std::begin(_data) + (i + 1) * _itemsize,
std::begin(abs_num)
);
limb_vector_lsl(abs_num.begin(), abs_num.end(), rhs.bits());
// `apy_unsigned_division` requires the number of *significant* limbs in
// denominator
std::size_t den_significant_limbs
= significant_limbs(std::begin(abs_den), std::end(abs_den));
apy_unsigned_division(
&result._data[i * result._itemsize], // Quotient
&abs_num[0], // Numerator
abs_num.size(), // Numerator limbs
&abs_den[0], // Denominator
den_significant_limbs // Denominator significant limbs
);
// Negate result if negative
if (num_sign ^ den_sign) {
limb_vector_negate_inplace(
std::begin(result._data) + (i + 0) * result._itemsize,
std::begin(result._data) + (i + 1) * result._itemsize
);
}
}
return result;
}
APyFixedArray APyFixedArray::operator/(const APyFixed& rhs) const
{
const int res_int_bits = int_bits() + rhs.frac_bits() + 1;
const int res_frac_bits = frac_bits() + rhs.int_bits();
const int res_bits = res_int_bits + res_frac_bits;
APyFixedArray result(_shape, res_bits, res_int_bits);
// Special case #1: The resulting number of bits fit in a single limb
if (unsigned(res_bits) <= APY_LIMB_SIZE_BITS) {
simd::vector_shift_div_const_signed(
std::begin(_data), // src1 (numerator)
rhs._data[0], // src2 (constant denominator)
std::begin(result._data), // dst
rhs.bits(), // numerator shift amount
_data.size() // vector elements
);
return result; // early exit
}
// General case: This always works but is slower than the special cases.
// Absolute value denominator. `apy_unsigned_division` requires the number of
// *significant* limbs in denominator
ScratchVector<apy_limb_t> abs_den(rhs.vector_size());
bool den_sign = limb_vector_abs(
std::begin(rhs._data), std::end(rhs._data), std::begin(abs_den)
);
std::size_t den_significant_limbs
= significant_limbs(std::begin(abs_den), std::end(abs_den));
assert(den_significant_limbs > 0);
assert(result._itemsize >= den_significant_limbs);
// Absolute value left-shifted numerator
ScratchVector<apy_limb_t> abs_num(result._itemsize);
// Compute inverse
auto inv = APyDivInverse(&abs_den[0], den_significant_limbs);
// Normalize denominator
apy_limb_t carry
= apy_inplace_left_shift(&abs_den[0], den_significant_limbs, inv.norm_shift);
assert(carry == 0);
(void)carry; // Avoid unused-warning
for (std::size_t i = 0; i < _nitems; i++) {
std::fill(std::begin(abs_num), std::end(abs_num), 0);
bool num_sign = limb_vector_abs(
std::begin(_data) + (i + 0) * _itemsize,
std::begin(_data) + (i + 1) * _itemsize,
std::begin(abs_num)
);
limb_vector_lsl(abs_num.begin(), abs_num.end(), rhs.bits());
auto quotient = &result._data[i * result._itemsize];
apy_unsigned_division_preinverted(
quotient, // Quotient
&abs_num[0], // Numerator
result._itemsize, // Numerator limbs
&abs_den[0], // Denominator
den_significant_limbs, // Denominator limbs
&inv // Inverse
);
// Negate result if negative
if (num_sign ^ den_sign) {
limb_vector_negate_inplace(
std::begin(result._data) + (i + 0) * result._itemsize,
std::begin(result._data) + (i + 1) * result._itemsize
);
}
}
return result;
}
APyFixedArray APyFixedArray::rdiv(const APyFixed& lhs) const
{
const int res_int_bits = lhs.int_bits() + frac_bits() + 1;
const int res_frac_bits = lhs.frac_bits() + int_bits();
const int res_bits = res_int_bits + res_frac_bits;
APyFixedArray result(_shape, res_bits, res_int_bits);
// Special case #1: The resulting number of bits fit in a single limb
if (unsigned(res_bits) <= APY_LIMB_SIZE_BITS) {
simd::vector_rdiv_const_signed(
std::begin(_data), // src2 (denominator)
lhs._data[0] << bits(), // src1 (constant numerator)
std::begin(result._data), // dst
_data.size() // vector elements
);
return result;
}
// General case: This always works but is slower than the special cases.
// Absolute value denominator
ScratchVector<apy_limb_t> abs_den(_itemsize);
// Absolute value left-shifted numerator. As `apy_unsigned_division` alters the
// numerator on call, we allocate twice its size. The first half [ `0`,
// `result._itemsize` ) is passed to `apy_unsigned_division` and [
// `result._item_size`, `2*result._itemsize` ) is used to cache the left-shifted
// absolute numerator.
ScratchVector<apy_limb_t> abs_num(2 * result._itemsize);
bool num_sign = limb_vector_abs(
std::begin(lhs._data),
std::end(lhs._data),
std::begin(abs_num) + result._itemsize
);
limb_vector_lsl(std::begin(abs_num) + result._itemsize, std::end(abs_num), bits());
for (std::size_t i = 0; i < _nitems; i++) {
bool den_sign = limb_vector_abs(
std::begin(_data) + (i + 0) * _itemsize,
std::begin(_data) + (i + 1) * _itemsize,
std::begin(abs_den)
);
std::copy_n(
std::begin(abs_num) + result._itemsize,
result._itemsize,
std::begin(abs_num)
);
// `apy_unsigned_division` requires the number of *significant* limbs in
// denominator
std::size_t den_significant_limbs
= significant_limbs(std::begin(abs_den), std::end(abs_den));
apy_unsigned_division(
&result._data[i * result._itemsize], // Quotient
&abs_num[0], // Numerator
result._itemsize, // Numerator limbs
&abs_den[0], // Denominator
den_significant_limbs // Denominator significant limbs
);
// Negate result if negative
if (num_sign ^ den_sign) {
limb_vector_negate_inplace(
std::begin(result._data) + (i + 0) * result._itemsize,
std::begin(result._data) + (i + 1) * result._itemsize
);
}
}
return result;
}
APyFixedArray APyFixedArray::operator<<(const int shift_val) const
{
// Left and right shift of data only affects the binary point in the data
APyFixedArray result = *this;
result._int_bits += shift_val;
return result;
}
APyFixedArray APyFixedArray::operator>>(const int shift_val) const
{
// Left and right shift of data only affects the binary point in the data
APyFixedArray result = *this;
result._int_bits -= shift_val;
return result;
}
APyFixedArray& APyFixedArray::operator<<=(const int shift_val)
{
// Left shift in place
_int_bits += shift_val;
return *this;
}
APyFixedArray& APyFixedArray::operator>>=(const int shift_val)
{
// Right shift in place
_int_bits -= shift_val;
return *this;
}
template <typename T>
ThirdPartyArray<bool> APyFixedArray::operator==(const T& rhs) const
{
auto is_zero = [](auto begin, auto end) { return limb_vector_is_zero(begin, end); };
return make_third_party_ndarray(
(*this - rhs).template to_ndarray<bool>(is_zero, "__eq__"),
get_preferred_array_lib()
);
}
template <typename T>
ThirdPartyArray<bool> APyFixedArray::operator!=(const T& rhs) const
{
auto is_non_zero
= [](auto begin, auto end) { return !limb_vector_is_zero(begin, end); };
return make_third_party_ndarray(
(*this - rhs).template to_ndarray<bool>(is_non_zero, "__ne__"),
get_preferred_array_lib()
);
}
template <typename T> ThirdPartyArray<bool> APyFixedArray::operator<(const T& rhs) const
{
auto is_negative
= [](auto begin, auto end) { return limb_vector_is_negative(begin, end); };
return make_third_party_ndarray(
(*this - rhs).template to_ndarray<bool>(is_negative, "__lt__"),
get_preferred_array_lib()
);
}
template <typename T>
ThirdPartyArray<bool> APyFixedArray::operator<=(const T& rhs) const
{
auto is_negative_or_zero = [](auto begin, auto end) {
return limb_vector_is_negative(begin, end) || limb_vector_is_zero(begin, end);
};
return make_third_party_ndarray(
(*this - rhs).template to_ndarray<bool>(is_negative_or_zero, "__le__"),
get_preferred_array_lib()
);
}
template <typename T> ThirdPartyArray<bool> APyFixedArray::operator>(const T& rhs) const
{
auto is_strict_positive = [](auto begin, auto end) {
return !limb_vector_is_negative(begin, end) && !limb_vector_is_zero(begin, end);
};
return make_third_party_ndarray(
(*this - rhs).template to_ndarray<bool>(is_strict_positive, "__gt__"),
get_preferred_array_lib()
);
}
template <typename T>
ThirdPartyArray<bool> APyFixedArray::operator>=(const T& rhs) const
{
auto is_non_negative
= [](auto begin, auto end) { return !limb_vector_is_negative(begin, end); };
return make_third_party_ndarray(
(*this - rhs).template to_ndarray<bool>(is_non_negative, "__ge__"),
get_preferred_array_lib()
);
}
using ComparissonArray = ThirdPartyArray<bool>;
// Explicit instantiation of needed comparison functions
template ComparissonArray APyFixedArray::operator==(const APyFixedArray& rhs) const;
template ComparissonArray APyFixedArray::operator==(const APyFixed& rhs) const;
template ComparissonArray APyFixedArray::operator!=(const APyFixedArray& rhs) const;
template ComparissonArray APyFixedArray::operator!=(const APyFixed& rhs) const;
template ComparissonArray APyFixedArray::operator<(const APyFixedArray& rhs) const;
template ComparissonArray APyFixedArray::operator<(const APyFixed& rhs) const;
template ComparissonArray APyFixedArray::operator<=(const APyFixedArray& rhs) const;
template ComparissonArray APyFixedArray::operator<=(const APyFixed& rhs) const;
template ComparissonArray APyFixedArray::operator>(const APyFixedArray& rhs) const;
template ComparissonArray APyFixedArray::operator>(const APyFixed& rhs) const;
template ComparissonArray APyFixedArray::operator>=(const APyFixedArray& rhs) const;
template ComparissonArray APyFixedArray::operator>=(const APyFixed& rhs) const;
std::variant<APyFixedArray, APyFixed>
APyFixedArray::matmul(const APyFixedArray& rhs) const
{
if (ndim() == 1 && rhs.ndim() == 1) {
if (_shape[0] == rhs._shape[0]) {
// Dimensionality for a standard scalar inner product checks out. Perform
// the checked inner product.
return _checked_inner_product(rhs, get_accumulator_mode_fixed());
}
}
if (ndim() == 2 && (rhs.ndim() == 2 || rhs.ndim() == 1)) {
if (_shape[1] == rhs._shape[0]) {
// Dimensionality for a standard 2D matrix multiplication checks out.
// Perform the checked 2D matrix
return _checked_2d_matmul(rhs, get_accumulator_mode_fixed());
}
}
// Unsupported `__matmul__` dimensionality, raise exception
throw std::length_error(
fmt::format(
"APyFixedArray.__matmul__: input shape mismatch, lhs: {}, rhs: {}",
tuple_string_from_vec(_shape),
tuple_string_from_vec(rhs._shape)
)
);
}
/* ********************************************************************************** *
* * Other methods * *
* ********************************************************************************** */
std::variant<APyFixedArray, APyFixed>
APyFixedArray::sum(const std::optional<PyShapeParam_t>& py_axis) const
{
// Extract axes to sum over
std::vector<std::size_t> axes = cpp_axes_from_python(py_axis, _ndim);
// Retrieve how many elements will be summed together
std::size_t n_elems = array_fold_get_elements(axes);
// Compute the result word length
int pad_bits = n_elems ? bit_width(n_elems - 1) : 0;
int bits = _bits + pad_bits;
int int_bits = _int_bits + pad_bits;
std::size_t res_limbs = bits_to_limbs(bits);
// Accumulation function
auto fold = fold_accumulate<vector_type>(_itemsize, res_limbs);
return array_fold(axes, fold, std::nullopt /* no init */, bits, int_bits);
}
APyFixedArray APyFixedArray::cumsum(std::optional<nb::int_> py_axis) const
{
std::optional<std::size_t> axis = py_axis.has_value()
? std::optional<std::size_t>(nb::cast<std::size_t>(*py_axis))
: std::nullopt;
if (axis.has_value() && axis >= _ndim) {
std::string msg = fmt::format(
"APyFixedArray.cumsum: axis {} out of range (ndim = {})", *axis, _ndim
);
throw nb::index_error(msg.c_str());
}
// Retrieve how many elements will be summed together
std::size_t n_elems = axis.has_value() ? _shape[*axis] : _nitems;
// Compute the result word length
int pad_bits = n_elems ? bit_width(n_elems - 1) : 0;
int bits = _bits + pad_bits;
int int_bits = _int_bits + pad_bits;
std::size_t res_limbs = bits_to_limbs(bits);
// Accumulation function
auto fold = fold_accumulate<vector_type>(_itemsize, res_limbs);
auto post_proc = [](auto, auto) { /* no post processing */ };
return array_fold_cumulative(axis, fold, post_proc, std::nullopt, bits, int_bits);
}
std::variant<APyFixedArray, APyFixed>
APyFixedArray::prod(const std::optional<PyShapeParam_t>& py_axis) const
{
// Extract axes to sum over
std::vector<std::size_t> axes = cpp_axes_from_python(py_axis, _ndim);
// Retrieve how many elements will be summed together
std::size_t n_elems = array_fold_get_elements(axes);
// Compute the result word length
if (n_elems == 0) {
// Empty array, return scalar one (NumPy semantics)
return APyFixed::one(_bits, _int_bits);
} else {
// Non-empty array
int int_bits = n_elems * _int_bits;
int frac_bits = n_elems * (_bits - _int_bits);
int bits = int_bits + frac_bits;
std::size_t res_limbs = bits_to_limbs(bits);
// Multiplicative fold function function
ScratchVector<apy_limb_t, 32> scratch(2 * res_limbs + 2 * _itemsize);
auto fold_func = fold_multiply<vector_type>(_itemsize, res_limbs, scratch);
APyFixed init_one(_bits, _int_bits, { apy_limb_t(1) });
return array_fold(axes, fold_func, init_one, bits, int_bits);
}
}
APyFixedArray APyFixedArray::cumprod(std::optional<nb::int_> py_axis) const
{
std::optional<std::size_t> axis = py_axis.has_value()
? std::optional<std::size_t>(nb::cast<std::size_t>(*py_axis))
: std::nullopt;
if (axis.has_value() && axis >= _ndim) {
std::string msg = fmt::format(
"APyFixedArray.cumprod: axis {} out of range (ndim = {})", *axis, _ndim
);
throw nb::index_error(msg.c_str());
}
// Retrieve how many elements will be folded together
std::size_t n_elems = axis.has_value() ? _shape[*axis] : _nitems;
// Compute the result word length
int int_bits = std::max(int(_int_bits * n_elems), _int_bits);
int frac_bits = std::max(int((_bits - _int_bits) * n_elems), _bits - _int_bits);
int bits = int_bits + frac_bits;
std::size_t res_limbs = bits_to_limbs(bits);
// Multiplicative fold function
ScratchVector<apy_limb_t, 32> scratch(2 * res_limbs + 2 * _itemsize);
auto fold_func = fold_multiply<vector_type>(_itemsize, res_limbs, scratch);
// Post processing: adjust the binary point of each partial product
auto post_proc = [&](auto dst_it, std::size_t n) {
int frac_bits = _bits - _int_bits;
int shift_amnt = frac_bits < 0 ? -frac_bits * n : frac_bits * (n_elems - 1 - n);
limb_vector_lsl(dst_it, dst_it + res_limbs, shift_amnt);
};
APyFixed init_one(_bits, _int_bits, { apy_limb_t(1) });
return array_fold_cumulative(axis, fold_func, post_proc, init_one, bits, int_bits);
}
APyFixedArray
APyFixedArray::convolve(const APyFixedArray& other, const std::string& conv_mode) const
{
if (ndim() != 1 || other.ndim() != 1) {
auto msg = fmt::format(
"can only convolve 1D arrays (lhs.ndim = {}, rhs.ndim = {})",
ndim(),
other.ndim()