-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathwll_interface.h
2670 lines (2377 loc) · 88 KB
/
wll_interface.h
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
#pragma once
#if defined(_MSC_VER)
// disable C4996 issued by std::copy_n
#pragma warning( disable : 4996 )
#endif
#include <cassert>
#include <algorithm>
#include <array>
#include <complex>
#include <exception>
#include <initializer_list>
#include <iterator>
#include <numeric>
#include <sstream>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
#include "WolframLibrary.h"
#include "WolframSparseLibrary.h"
namespace wll
{
#if defined(__clang__)
static_assert(__clang_major__ >= 4);
#define WLL_CURRENT_FUNCTION std::string(__PRETTY_FUNCTION__)
#elif defined(__GNUC__)
static_assert(__GNUC__ >= 7);
#define WLL_CURRENT_FUNCTION std::string(__PRETTY_FUNCTION__)
#elif defined(__INTEL_COMPILER)
static_assert(__INTEL_COMPILER >= 1900);
#define WLL_CURRENT_FUNCTION std::string(__FUNCTION__)
#elif defined(_MSC_VER)
static_assert(_MSC_VER >= 1911);
#define WLL_CURRENT_FUNCTION std::string(__FUNCSIG__)
#endif
static_assert(sizeof(mint) == sizeof(size_t));
struct exception_status
{
int error_type_ = LIBRARY_NO_ERROR;
std::string message_{};
};
struct library_error
{
explicit library_error(int type, std::string message ={}) :
type_{type}, message_{std::move(message)} {}
[[nodiscard]] int type() const { return type_; }
[[nodiscard]] std::string what() const { return message_; }
int type_;
std::string message_;
};
struct library_type_error : library_error
{
explicit library_type_error(std::string message ={}) :
library_error(LIBRARY_TYPE_ERROR, std::move(message)) {}
};
struct library_rank_error : library_error
{
explicit library_rank_error(std::string message ={}) :
library_error(LIBRARY_RANK_ERROR, std::move(message)) {}
};
struct library_dimension_error : library_error
{
explicit library_dimension_error(std::string message ={}) :
library_error(LIBRARY_DIMENSION_ERROR, std::move(message)) {}
};
struct library_numerical_error : library_error
{
explicit library_numerical_error(std::string message ={}) :
library_error(LIBRARY_NUMERICAL_ERROR, std::move(message)) {}
};
struct library_memory_error : library_error
{
explicit library_memory_error(std::string message ={}) :
library_error(LIBRARY_MEMORY_ERROR, std::move(message)) {}
};
struct library_function_error : library_error
{
explicit library_function_error(std::string message ={}) :
library_error(LIBRARY_FUNCTION_ERROR, std::move(message)) {}
};
struct log_stringstream_t
{
std::stringstream ss_{};
mutable std::string string_{};
void update_string() const
{
string_ = ss_.str();
}
void clear()
{
ss_ = std::stringstream{};
string_ = std::string{};
}
template<typename Any>
auto& operator<<(Any&& any)
{
return ss_ << std::forward<Any>(any);
}
};
WolframLibraryData global_lib_data;
using sparse_fn_lib_t = decltype(global_lib_data->sparseLibraryFunctions);
sparse_fn_lib_t global_sparse_fn;
exception_status global_exception;
log_stringstream_t global_log;
std::string global_string_result;
#ifdef NDEBUG
#define WLL_DEBUG_EXECUTE(expr) ((void)0)
#define WLL_ASSERT(expr) ((void)0)
#else
#define WLL_DEBUG_EXECUTE(expr) (any)
#define WLL_ASSERT(expr) assert((expr))
#endif
template<typename LinkType, typename UserType>
struct is_same_layout :
std::false_type {};
template<typename UserType>
struct is_same_layout<mint, UserType> :
std::bool_constant<std::is_integral_v<UserType> && sizeof(mint) == sizeof(UserType)> {};
template<>
struct is_same_layout<mreal, double> :
std::true_type {};
template<>
struct is_same_layout<mcomplex, std::complex<double>> :
std::true_type {};
template<typename LinkType, typename UserType>
constexpr bool is_same_layout_v = is_same_layout<LinkType, UserType>::value;
template<typename Complex>
struct is_std_complex :
std::false_type {};
template<typename T>
struct is_std_complex<std::complex<T>> :
std::true_type {};
template<typename Complex>
constexpr bool is_std_complex_v = is_std_complex<Complex>::value;
template<typename Complex>
struct complex_value
{
using type = void;
};
template<typename T>
struct complex_value<std::complex<T>>
{
using type = T;
};
template<typename Complex>
using complex_value_t = typename complex_value<Complex>::type;
template<typename>
constexpr bool _always_false_v = false;
template<size_t Size>
size_t _flattened_size(const std::array<size_t, Size>& dims) noexcept
{
size_t size = 1;
for (size_t d : dims) size *= d;
return size;
}
template<size_t Rank, typename T>
std::array<size_t, Rank> _convert_to_dims_array(std::initializer_list<T> dims)
{
static_assert(std::is_integral_v<T>, "dimensions should be of integral types");
WLL_ASSERT(dims.size() == Rank); // dims should have size equal to the rank
std::array<size_t, Rank> dims_array;
std::copy_n(dims.begin(), Rank, dims_array.begin());
return dims_array;
}
template<typename X, typename Y>
auto _add_if_negative(X val_x, Y val_y)
{
if constexpr (std::is_signed_v<X>)
if (val_x < X(0))
return Y(val_x) + val_y;
return Y(val_x);
}
template<typename Target>
struct _mtype_cast_impl
{
template<typename Value>
constexpr Target operator()(const Value& value) noexcept
{
return static_cast<Target>(value);
}
constexpr Target operator()(const mcomplex& value)
{
throw library_type_error(WLL_CURRENT_FUNCTION + "\ncannot convert from mcomplex");
return Target{};
}
template<typename T>
constexpr Target operator()(const std::complex<T>& value)
{
throw library_type_error(WLL_CURRENT_FUNCTION + "\ncannot convert from std::complex<T>");
return Target{};
}
};
template<typename T>
struct _mtype_cast_impl<std::complex<T>>
{
template<typename Value>
constexpr std::complex<T> operator()(const Value& value) noexcept
{
return std::complex<T>(static_cast<T>(value));
}
constexpr std::complex<T> operator()(const mcomplex& value) noexcept
{
return std::complex<T>(static_cast<T>(mcreal(value)),
static_cast<T>(mcimag(value)));
}
template<typename U>
constexpr std::complex<T> operator()(const std::complex<U>& value) noexcept
{
return std::complex<T>(static_cast<T>(value.real()),
static_cast<T>(value.imag()));
}
};
template<>
struct _mtype_cast_impl<mcomplex>
{
template<typename Value>
constexpr mcomplex operator()(const Value& value) noexcept
{
mcomplex ret;
mcreal(ret) = static_cast<mreal>(value);
mcimag(ret) = mreal{};
return ret;
}
constexpr mcomplex operator()(const mcomplex& value) noexcept
{
return value;
}
template<typename T>
constexpr mcomplex operator()(const std::complex<T>& value) noexcept
{
mcomplex ret;
mcreal(ret) = static_cast<mreal>(value.real());
mcimag(ret) = static_cast<mreal>(value.imag());
return ret;
}
};
template<typename Target, typename Value>
constexpr Target _mtype_cast(const Value& value)
{
return _mtype_cast_impl<Target>()(value);
}
bool operator==(const mcomplex& a, const mcomplex& b)
{
return (mcreal(a) == mcreal(b)) && (mcimag(a) == mcimag(b));
}
bool operator!=(const mcomplex& a, const mcomplex& b)
{
return !(a == b);
}
template<typename SrcType, typename DestType>
inline void _data_copy_n(const SrcType* src_ptr, size_t count, DestType* dest_ptr)
{
if (count > 0)
{
WLL_ASSERT(src_ptr != nullptr && dest_ptr != nullptr);
WLL_ASSERT((void*)src_ptr != (void*)dest_ptr); // cannot copy to itself
for (size_t i = 0; i < count; ++i)
dest_ptr[i] = _mtype_cast<DestType>(src_ptr[i]);
}
}
template<size_t Rank>
struct _index_array
{
using _idx_t = std::array<size_t, Rank>;
explicit _index_array(const _idx_t& idx) noexcept : idx_{idx} {}
template<typename Value>
std::pair<_idx_t, Value> operator=(const Value& value) const noexcept
{
return {idx_, value};
}
_idx_t idx_;
};
template<typename... Indices>
_index_array<sizeof...(Indices)> pos(const Indices&... indices)
{
return std::array<size_t, sizeof...(Indices)>({size_t(indices)...});
}
#define MType_Void -1
template<typename T>
struct derive_tensor_data_type
{
using strict_type =
std::conditional_t<is_same_layout_v<mint, T>, mint,
std::conditional_t<is_same_layout_v<mreal, T>, mreal,
std::conditional_t<is_same_layout_v<mcomplex, T>, mcomplex, void>>>;
using convert_type =
std::conditional_t<std::is_integral_v<T>, mint,
std::conditional_t<std::is_floating_point_v<T>, mreal,
std::conditional_t<is_std_complex_v<T>, mcomplex, void>>>;
static constexpr int strict_type_v =
std::is_same_v<strict_type, mint> ? MType_Integer :
std::is_same_v<strict_type, mreal> ? MType_Real :
std::is_same_v<strict_type, mcomplex> ? MType_Complex : MType_Void;
static constexpr int convert_type_v =
std::is_same_v<convert_type, mint> ? MType_Integer :
std::is_same_v<convert_type, mreal> ? MType_Real :
std::is_same_v<convert_type, mcomplex> ? MType_Complex : MType_Void;
};
enum memory_type
{
// who has resource memory managed by
empty, // - -
owned, // wll::tensor malloc/free
proxy, // kernel -
manual, // wll::tensor MTensor_new/MTensor_free
shared // kernel/wll::tensor MTensor_disown
};
template<typename T, size_t Rank>
struct tensor_init_data
{
using type = std::initializer_list<typename tensor_init_data<T, Rank - 1>::type>;
};
template<typename T>
struct tensor_init_data<T, 0>
{
using type = T;
};
template<typename T, size_t Rank>
using tensor_init_data_t = typename tensor_init_data<T, Rank>::type;
template<typename T, size_t Rank>
class tensor
{
public:
using value_type = T;
static constexpr size_t _rank = Rank;
using _ptr_t = value_type*;
using _const_ptr_t = const value_type*;
using _dims_t = std::array<size_t, _rank>;
using _init_dims_t = std::initializer_list<size_t>;
using _init_data_t = tensor_init_data_t<value_type, _rank>;
static_assert(_rank > 0);
template<typename U, size_t URank>
friend class tensor;
tensor() noexcept = default;
tensor(MTensor mtensor, memory_type access) :
mtensor_{mtensor}, access_{access}
{
auto mtensor_rank = global_lib_data->MTensor_getRank(mtensor);
WLL_ASSERT(_rank == mtensor_rank);
WLL_ASSERT(access_ == memory_type::owned ||
access_ == memory_type::proxy ||
access_ == memory_type::shared);
const mint* dims_ptr = global_lib_data->MTensor_getDimensions(mtensor);
std::copy_n(dims_ptr, _rank, dims_.begin());
size_ = global_lib_data->MTensor_getFlattenedLength(mtensor);
void* src_ptr = nullptr;
bool do_copy = false;
int mtype = int(global_lib_data->MTensor_getType(mtensor));
WLL_ASSERT(mtype == MType_Integer || mtype == MType_Real || mtype == MType_Complex);
if (mtype == MType_Integer)
{
src_ptr = reinterpret_cast<void*>(global_lib_data->MTensor_getIntegerData(mtensor));
do_copy = !is_same_layout_v<mint, value_type>;
}
else if (mtype == MType_Real)
{
src_ptr = reinterpret_cast<void*>(global_lib_data->MTensor_getRealData(mtensor));
do_copy = !is_same_layout_v<mreal, value_type>;
}
else // mtype == MType_Complex
{
src_ptr = reinterpret_cast<void*>(global_lib_data->MTensor_getComplexData(mtensor));
do_copy = !is_same_layout_v<mcomplex, value_type>;
}
if (access_ == memory_type::owned)
do_copy = true; // do copy anyway
if (do_copy)
{
WLL_ASSERT(access_ == memory_type::owned ||
access_ == memory_type::proxy);
mtensor_ = nullptr;
access_ = memory_type::owned; // *this will own data after copy
ptr_ = reinterpret_cast<_ptr_t>(malloc(size_ * sizeof(value_type)));
if (ptr_ == nullptr)
throw library_memory_error(WLL_CURRENT_FUNCTION + "\nmalloc failed when copying data.");
if (mtype == MType_Integer)
_data_copy_n(reinterpret_cast<mint*>(src_ptr), size_, ptr_);
else if (mtype == MType_Real)
_data_copy_n(reinterpret_cast<mreal*>(src_ptr), size_, ptr_);
else // mtype == MType_Complex
_data_copy_n(reinterpret_cast<mcomplex*>(src_ptr), size_, ptr_);
}
else // do_copy == false
{
WLL_ASSERT(access_ == memory_type::proxy ||
access_ == memory_type::shared);
ptr_ = reinterpret_cast<_ptr_t>(src_ptr);
}
}
explicit tensor(_dims_t dims, memory_type access = memory_type::owned) :
dims_{dims}, size_{_flattened_size(dims)}, access_{access}
{
WLL_ASSERT(access_ == memory_type::owned ||
access_ == memory_type::manual);
if (access_ == memory_type::owned)
{
ptr_ = reinterpret_cast<_ptr_t>(calloc(size_, sizeof(value_type)));
if (ptr_ == nullptr)
throw library_memory_error(WLL_CURRENT_FUNCTION + "\ncalloc failed, access_ == owned.");
}
else // access_ == memory_type::manual
{
//throw library_dimension_error(std::to_string(dims[0]));
constexpr int mtype = derive_tensor_data_type<value_type>::strict_type_v;
if (mtype == MType_Void)
throw library_type_error(WLL_CURRENT_FUNCTION + "\nvalue_type cannot be strictly matched to any MType.");
int err = global_lib_data->MTensor_new(
mtype, _rank, reinterpret_cast<mint*>(dims_.data()), &mtensor_);
if (err != LIBRARY_NO_ERROR)
throw library_error(err, WLL_CURRENT_FUNCTION + "\nMTensor_new() failed.");
if constexpr (mtype == MType_Integer)
ptr_ = reinterpret_cast<_ptr_t>(global_lib_data->MTensor_getIntegerData(mtensor_));
else if constexpr (mtype == MType_Real)
ptr_ = reinterpret_cast<_ptr_t>(global_lib_data->MTensor_getRealData(mtensor_));
else // mtype == MType_Complex
ptr_ = reinterpret_cast<_ptr_t>(global_lib_data->MTensor_getComplexData(mtensor_));
}
}
tensor(_init_dims_t dims, memory_type access = memory_type::owned) :
tensor(_convert_to_dims_array<_rank>(dims), access) {}
tensor(_dims_t dims, const _init_data_t& data, memory_type access = memory_type::owned) :
tensor(dims, access)
{
this->_fill_init_data(data);
}
tensor(_init_dims_t dims, const _init_data_t& data, memory_type access = memory_type::owned) :
tensor(_get_init_dims(dims, data), data, access)
{
this->_fill_init_data(data);
}
tensor(const tensor& other) :
dims_{other.dims_}, size_{other.size_}, access_{memory_type::owned}
{
ptr_ = reinterpret_cast<_ptr_t>(malloc(size_ * sizeof(value_type)));
if (ptr_ == nullptr)
throw library_memory_error(WLL_CURRENT_FUNCTION + "\nmalloc failed when copying data.");
_data_copy_n(other.ptr_, size_, ptr_);
}
tensor(tensor&& other) noexcept :
dims_{other.dims_}, size_{other.size_}
{
std::swap(ptr_, other.ptr_);
std::swap(access_, other.access_);
std::swap(mtensor_, other.mtensor_);
}
template<typename U>
explicit tensor(const tensor<U, _rank>& other) :
dims_{other.dims_}, size_{other.size_}, access_{memory_type::owned}
{
ptr_ = reinterpret_cast<_ptr_t>(malloc(size_ * sizeof(value_type)));
if (ptr_ == nullptr)
throw library_memory_error(WLL_CURRENT_FUNCTION + "\nmalloc failed when copying data.");
_data_copy_n(other.ptr_, size_, ptr_);
}
template<typename U>
explicit tensor(tensor<U, _rank>&& other) :
dims_{other.dims_}, size_{other.size_}, access_{memory_type::owned}
{
ptr_ = reinterpret_cast<_ptr_t>(malloc(size_ * sizeof(value_type)));
if (ptr_ == nullptr)
throw library_memory_error(WLL_CURRENT_FUNCTION + "\nmalloc failed when copying data.");
_data_copy_n(other.ptr_, size_, ptr_);
}
tensor& operator=(const tensor& other)
{
if(this == &other) return *this;
WLL_ASSERT(other.access_ != memory_type::empty); // other is empty
WLL_ASSERT(this->access_ != memory_type::empty); // *this is empty
if (this->ptr_ != other.ptr_)
{
if (!(this->_has_same_dims(other.dims_.data())))
throw library_dimension_error(WLL_CURRENT_FUNCTION + "\ntensors have different dimensions.");
_data_copy_n(other.ptr_, size_, ptr_);
}
return *this;
}
tensor& operator=(tensor&& other)
{
if(this == &other) return *this;
WLL_ASSERT(other.access_ != memory_type::empty); // other is empty
WLL_ASSERT(this->access_ != memory_type::empty); // *this is empty
if (this->ptr_ != other.ptr_)
{
if (!(this->_has_same_dims(other.dims_.data())))
throw library_dimension_error(WLL_CURRENT_FUNCTION + "\ntensors have different dimensions.");
if (other.access_ == memory_type::proxy ||
other.access_ == memory_type::shared ||
this->access_ == memory_type::proxy ||
this->access_ == memory_type::shared)
{
_data_copy_n(other.ptr_, size_, ptr_);
}
else
{
this->_swap_pointers(std::move(other));
}
}
return *this;
}
template<typename U>
tensor& operator=(const tensor<U, _rank>& other)
{
if(this == &other) return *this;
WLL_ASSERT(other.access_ != memory_type::empty); // other is empty
WLL_ASSERT(this->access_ != memory_type::empty); // *this is empty
// tensors with difference value_type should not have the same ptr_
WLL_ASSERT((void*)(this->ptr_) != (void*)(other.ptr_));
_data_copy_n(other.ptr_, size_, ptr_);
return *this;
}
template<typename U>
tensor& operator=(tensor<U, _rank>&& other)
{
WLL_ASSERT(other.access_ != memory_type::empty); // other is empty
WLL_ASSERT(this->access_ != memory_type::empty); // *this is empty
// tensors with difference value_type should not have the same ptr_
WLL_ASSERT((void*)(this->ptr_) != (void*)(other.ptr_));
_data_copy_n(other.ptr_, size_, ptr_);
return *this;
}
[[nodiscard]] tensor clone(memory_type access = memory_type::owned) const
{
WLL_ASSERT(this->access_ != memory_type::empty); // cannot clone an empty tensor
WLL_ASSERT(access == memory_type::owned || access == memory_type::manual);
tensor ret(this->dims_, access);
_data_copy_n(ptr_, size_, ret.ptr_);
return ret;
}
~tensor()
{
this->_destroy();
}
[[nodiscard]] constexpr size_t rank() const noexcept
{
return _rank;
}
[[nodiscard]] size_t size() const noexcept
{
return size_;
}
[[nodiscard]] _dims_t dimensions() const noexcept
{
return dims_;
}
[[nodiscard]] size_t dimension(size_t level) const noexcept
{
return dims_[level];
}
_ptr_t data() noexcept
{
return this->ptr_;
}
[[nodiscard]] _const_ptr_t data() const noexcept
{
return this->ptr_;
}
bool operator==(const tensor& other) const
{
if (this->dims_ != other.dims_)
return false;
if (this->ptr_ == other.ptr_)
return true;
return std::equal(this->cbegin(), this->cend(), other.cbegin());
}
template<typename... Idx>
value_type at(Idx... idx) const
{
static_assert(sizeof...(idx) == _rank);
return (*this)[_get_flat_idx(std::make_tuple(idx...))];
}
template<typename... Idx>
value_type& at(Idx... idx)
{
static_assert(sizeof...(idx) == _rank);
return (*this)[_get_flat_idx(std::make_tuple(idx...))];
}
template<typename... Idx>
value_type operator()(Idx... idx) const
{
static_assert(sizeof...(idx) == _rank);
return (*this)[_get_flat_idx_unsafe(std::make_tuple(idx...))];
}
template<typename... Idx>
value_type& operator()(Idx... idx)
{
static_assert(sizeof...(idx) == _rank);
return (*this)[_get_flat_idx_unsafe(std::make_tuple(idx...))];
}
template<typename IdxTuple>
value_type& _tuple_at(const IdxTuple& idx_tuple)
{
static_assert(std::tuple_size_v<IdxTuple> == _rank);
return this->_tuple_at_impl(idx_tuple, std::make_index_sequence<_rank>{});
}
template<typename IdxTuple>
value_type _tuple_at(const IdxTuple& idx_tuple) const
{
static_assert(std::tuple_size_v<IdxTuple> == _rank);
return this->_tuple_at_impl(idx_tuple, std::make_index_sequence<_rank>{});
}
value_type operator[](size_t idx) const
{
WLL_ASSERT(idx < size_); // index out of range
return ptr_[idx];
}
value_type& operator[](size_t idx)
{
WLL_ASSERT(idx < size_); // index out of range
return ptr_[idx];
}
[[nodiscard]] _const_ptr_t cbegin() const noexcept
{
WLL_ASSERT(ptr_ != nullptr);
return ptr_;
}
[[nodiscard]] _const_ptr_t cend() const noexcept
{
return this->cbegin() + size_;
}
[[nodiscard]] _const_ptr_t begin() const noexcept
{
return this->cbegin();
}
[[nodiscard]] _const_ptr_t end() const noexcept
{
return this->cend();
}
_ptr_t begin() noexcept
{
WLL_ASSERT(ptr_ != nullptr);
return ptr_;
}
_ptr_t end() noexcept
{
return this->begin() + size_;
}
[[nodiscard]] MTensor get_mtensor() const &
{
return _get_mtensor_lvalue();
}
MTensor get_mtensor() &&
{
return _get_mtensor_rvalue();
}
template<typename InputIter>
void copy_data_from(InputIter src, size_t count = size_t(-1))
{
if (count == size_t(-1))
count = size_;
WLL_ASSERT(count == size_);
if (count > 0)
{
_ptr_t dest = this->ptr_;
for (size_t i = 0; i < count; ++i, ++src, ++dest)
*dest = _mtype_cast<value_type>(*src);
}
}
template<typename OutputIter>
void copy_data_to(OutputIter dest, size_t count = size_t(-1))
{
if (count == size_t(-1))
count = size_;
WLL_ASSERT(count == size_);
if (count > 0)
{
_ptr_t src = this->ptr_;
for (size_t i = 0; i < count; ++i, ++src, ++dest)
*dest = _mtype_cast<decltype(*dest)>(*src);
}
}
template<size_t Level = _rank - 1, typename IdxTuple>
size_t _get_flat_idx(const IdxTuple& idx_tuple) const
{
auto plain_idx = std::get<Level>(idx_tuple);
using plain_type = decltype(plain_idx);
static_assert(std::is_integral_v<plain_type>, "index must be of an integral type");
size_t unsigned_idx = size_t(plain_idx);
if constexpr (std::is_signed_v<plain_type>)
if (plain_idx < plain_type(0))
unsigned_idx += dims_[Level];
if (unsigned_idx >= dims_[Level])
throw std::out_of_range(WLL_CURRENT_FUNCTION + "\nindex out of range");
if constexpr (Level == 0)
return unsigned_idx;
else
return _get_flat_idx<Level - 1>(idx_tuple) * dims_[Level] + unsigned_idx;
}
template<size_t Level = _rank - 1, typename IdxTuple>
size_t _get_flat_idx_unsafe(const IdxTuple& idx_tuple) const noexcept
{
auto plain_idx = std::get<Level>(idx_tuple);
using plain_type = decltype(plain_idx);
static_assert(std::is_integral_v<plain_type>, "index must be of an integral type");
size_t unsigned_idx = size_t(plain_idx);
if constexpr (std::is_signed_v<plain_type>)
if (plain_idx < plain_type(0))
unsigned_idx += dims_[Level];
WLL_ASSERT(unsigned_idx < dims_[Level]);
if constexpr (Level == 0)
return unsigned_idx;
else
return _get_flat_idx_unsafe<Level - 1>(idx_tuple) * dims_[Level] + unsigned_idx;
}
template<typename IdxTuple, size_t... Is>
value_type& _tuple_at_impl(const IdxTuple& idx_tuple, std::index_sequence<Is...>)
{
return this->operator()(std::get<Is>(idx_tuple)...);
}
template<typename IdxTuple, size_t... Is>
value_type _tuple_at_impl(const IdxTuple& idx_tuple, std::index_sequence<Is...>) const
{
return this->operator()(std::get<Is>(idx_tuple)...);
}
private:
template<size_t I = 0, typename Dims>
bool _has_same_dims(const Dims* other_dims)
{
if constexpr (I + 1 == _rank)
return (this->dims_[I] == size_t(other_dims[I])) && _has_same_dims<I + 1, Dims>(other_dims);
else
return this->dims_[_rank - 1] == size_t(other_dims[_rank - 1]);
}
void _destroy()
{
if (access_ == memory_type::empty)
{
WLL_ASSERT(mtensor_ == nullptr);
WLL_ASSERT(ptr_ == nullptr);
}
else if (access_ == memory_type::owned)
{
WLL_ASSERT(mtensor_ == nullptr);
free(ptr_);
}
else if (access_ == memory_type::proxy)
{
// do nothing
}
else if (access_ == memory_type::manual)
{
global_lib_data->MTensor_free(mtensor_);
}
else if (access_ == memory_type::shared)
{
global_lib_data->MTensor_disown(mtensor_);
}
ptr_ = nullptr;
mtensor_ = nullptr;
access_ = memory_type::empty;
}
void _release_ownership()
{
// destruct the object without free resource, manual tensor only
WLL_ASSERT(access_ == memory_type::manual);
ptr_ = nullptr;
mtensor_ = nullptr;
access_ = memory_type::empty;
}
[[nodiscard]] MTensor _get_mtensor_lvalue() const
{
WLL_ASSERT(access_ != memory_type::empty);
using mtype = typename derive_tensor_data_type<value_type>::convert_type;
constexpr int mtype_v = derive_tensor_data_type<value_type>::convert_type_v;
static_assert(!std::is_same_v<void, mtype>, "invalid data type to convert to MType");
MTensor ret_tensor = nullptr;
int err = global_lib_data->MTensor_new(
mtype_v, _rank, reinterpret_cast<mint*>(const_cast<size_t*>(dims_.data())), &ret_tensor);
if (err != LIBRARY_NO_ERROR)
throw library_error(err, WLL_CURRENT_FUNCTION + "\nMTensor_new() failed.");
if constexpr (mtype_v == MType_Integer)
_data_copy_n(ptr_, size_, global_lib_data->MTensor_getIntegerData(ret_tensor));
else if constexpr (mtype_v == MType_Real)
_data_copy_n(ptr_, size_, global_lib_data->MTensor_getRealData(ret_tensor));
else // mtype_v == MType_Complex
_data_copy_n(ptr_, size_, global_lib_data->MTensor_getComplexData(ret_tensor));
return ret_tensor;
}
MTensor _get_mtensor_rvalue()
{
WLL_ASSERT(access_ != memory_type::empty);
if (access_ == memory_type::manual)
{
// return the containing mtensor and destroy *this
MTensor ret = this->mtensor_;
this->_release_ownership();
return ret;
}
else // access == owned / proxy / shared
{
// return a copy
return _get_mtensor_lvalue();
}
}
template<typename Other>
void _swap_pointers(Other&& other)
{
WLL_ASSERT(this->access_ == memory_type::owned ||
this->access_ == memory_type::manual); // only tensors own data can swap
WLL_ASSERT(other.access_ == memory_type::owned ||
other.access_ == memory_type::manual);
if (!(this->_has_same_dims(other.dims_.data())))
throw library_dimension_error(WLL_CURRENT_FUNCTION + "\ntensors have different dimensions.");
std::swap(this->ptr_, other.ptr_);
std::swap(this->mtensor_, other.mtensor_);
std::swap(this->access_, other.access_);
}
template<size_t Level, typename Data>
static auto _get_init_data_dims_impl(_dims_t& dims, const Data& data) noexcept
-> std::enable_if_t<Level + 1 != _rank>
{
const size_t size = data.size();
WLL_ASSERT(size > 0);
if (dims[Level] == size_t(0))
dims[Level] = size;
else
WLL_ASSERT(dims[Level] == size); // shape of the array should be regular
for (const auto& sub_data : data)
_get_init_data_dims_impl<Level + 1>(dims, sub_data);
}
template<size_t Level, typename Data>
static auto _get_init_data_dims_impl(_dims_t& dims, const Data& data) noexcept
-> std::enable_if_t<Level + 1 == _rank>
{
const size_t size = data.size();
WLL_ASSERT(size > 0);
if (dims[Level] == size_t(0))
dims[Level] = size;
else
WLL_ASSERT(dims[Level] == size); // shape of the array should be regular
}
static _dims_t _get_init_data_dims(const _init_data_t& data) noexcept
{
_dims_t dims ={};
_get_init_data_dims_impl<0>(dims, data);
return dims;
}
static _dims_t _get_init_dims(const _init_dims_t& dims, const _init_data_t& data) noexcept
{
return (dims.size() == 0) ? _get_init_data_dims(data) : _convert_to_dims_array<_rank>(dims);
}
template<size_t Level>
[[nodiscard]] size_t _size_by_level() const noexcept
{
static_assert(Level <= _rank);
if constexpr (Level == _rank)
return size_t(1);
else
return dims_[Level] * _size_by_level<Level + 1>();
}
template<size_t Level, typename Data>
void _fill_init_data_impl(_ptr_t& ptr, const Data& data)
{
static_assert(Level + 1 <= _rank);
const size_t size = data.size();
const size_t pad_size = this->dims_[Level] - size;
WLL_ASSERT(size > 0 && pad_size >= 0);
if constexpr (Level + 1 == _rank)
{
for (const auto& value : data)
*(ptr++) = value;
ptr += pad_size;
}
else
{
for (const auto& sub_data : data)
this->_fill_init_data_impl<Level + 1>(ptr, sub_data);
ptr += _size_by_level<Level + 1>() * pad_size;
}
}
void _fill_init_data(const _init_data_t& data)
{
WLL_ASSERT(this->access_ != memory_type::empty);
_ptr_t ptr = ptr_;
this->_fill_init_data_impl<0>(ptr, data);
}