-
-
Notifications
You must be signed in to change notification settings - Fork 100
/
Matrix.mqh
2265 lines (1910 loc) · 67 KB
/
Matrix.mqh
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
//+------------------------------------------------------------------+
//| EA31337 framework |
//| Copyright 2016-2023, EA31337 Ltd |
//| https://github.com/EA31337 |
//+------------------------------------------------------------------+
/*
* This file is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
// Prevents processing this includes file for the second time.
#ifndef MATRIX_MQH
#define MATRIX_MQH
#ifdef USE_MQL_MATH_STAT
#ifdef __MQL5__
#include <Math/Stat/Normal.mqh>
#endif
#endif
#include "Math.h"
#define MATRIX_DIMENSIONS 6
#define MATRIX_VALUES_ARRAY_INCREMENT 500
// Forward declarations.
template <typename X>
class MatrixDimension;
template <typename X>
class Matrix;
#define MATRIX_STRIDE_AS_POOL -1
enum ENUM_MATRIX_VECTOR_REDUCE { MATRIX_VECTOR_REDUCE_COSINE_SIMILARITY, MATRIX_VECTOR_REDUCE_HINGE_LOSS };
// Types of matrix pool padding.
// @see https://keras.io/api/layers/pooling_layers/average_pooling2d/
enum ENUM_MATRIX_PADDING {
// No padding.
MATRIX_PADDING_VALID,
// Results in padding evenly to the left/right or up/down of the input such that output has the same height/width
// dimension as the input.
MATRIX_PADDING_SAME
};
// Types of matrix dimensions.
enum ENUM_MATRIX_DIMENSION_TYPE {
MATRIX_DIMENSION_TYPE_UNKNOWN,
MATRIX_DIMENSION_TYPE_CONTAINERS,
MATRIX_DIMENSION_TYPE_VALUES
};
// Matrix operation types.
enum ENUM_MATRIX_OPERATION {
MATRIX_OPERATION_ADD,
MATRIX_OPERATION_SUBTRACT,
MATRIX_OPERATION_MULTIPLY,
MATRIX_OPERATION_DIVIDE,
MATRIX_OPERATION_ABS,
MATRIX_OPERATION_FILL,
MATRIX_OPERATION_FILL_RANDOM,
MATRIX_OPERATION_FILL_RANDOM_RANGE,
MATRIX_OPERATION_FILL_POS_ADD,
MATRIX_OPERATION_FILL_POS_MUL,
MATRIX_OPERATION_POWER,
MATRIX_OPERATION_SUM,
MATRIX_OPERATION_MIN,
MATRIX_OPERATION_MAX,
MATRIX_OPERATION_AVG,
MATRIX_OPERATION_MED,
MATRIX_OPERATION_POISSON, // b - a * log(b)
MATRIX_OPERATION_LOG_COSH, // log((exp((b-a)) + exp(-(b-a)))/2)
MATRIX_OPERATION_ABS_DIFF,
MATRIX_OPERATION_ABS_DIFF_SQUARE,
MATRIX_OPERATION_ABS_DIFF_SQUARE_LOG,
MATRIX_OPERATION_RELU,
};
/**
* Return minimum value of double.
*/
double MinOf(double value) { return -DBL_MAX; }
/**
* Return minimum value of double.
*/
float MinOf(float value) { return -FLT_MAX; }
/**
* Return minimum value of integer.
*/
int MinOf(int value) { return INT_MIN; }
/**
* Return maximum value of double.
*/
double MaxOf(double value) { return DBL_MAX; }
/**
* Return maximum value of double.
*/
float MaxOf(float value) { return FLT_MAX; }
/**
* Return minimum value of integer.
*/
int MaxOf(int value) { return INT_MAX; }
/**
* Matrix's dimension accessor. Used by matrix's index operator.
*/
template <typename X>
struct MatrixDimensionAccessor {
// Pointer to matrix instance.
Matrix<X>* ptr_matrix;
// Pointer to matrix's dimension instance.
MatrixDimension<X>* ptr_dimension;
// Index of container or value pointed by accessor.
int index;
/**
* Constructor.
*/
MatrixDimensionAccessor(Matrix<X>* _ptr_matrix = NULL, MatrixDimension<X>* _ptr_dimension = NULL, int _index = 0)
: ptr_matrix(_ptr_matrix), ptr_dimension(_ptr_dimension), index(_index) {}
/**
* Index operator. Returns container or value accessor.
*/
MatrixDimensionAccessor<X> operator[](int _index) {
return MatrixDimensionAccessor(ptr_matrix, ptr_dimension.containers[index], _index);
}
/**
* Returns target dimension type.
*/
ENUM_MATRIX_DIMENSION_TYPE Type() const { return ptr_dimension.type; }
#define MATRIX_ACCESSOR_OPERATOR(OP) \
void operator OP(X _value) { \
if (ptr_dimension.type != MATRIX_DIMENSION_TYPE_VALUES) { \
Print("Error: Trying to use matrix", ptr_matrix.Repr(), \
"'s value operator " #OP " in a dimension which doesn't contain values!"); \
return; \
} \
\
ptr_dimension.values[index] OP _value; \
}
MATRIX_ACCESSOR_OPERATOR(+=)
MATRIX_ACCESSOR_OPERATOR(-=)
MATRIX_ACCESSOR_OPERATOR(*=)
MATRIX_ACCESSOR_OPERATOR(/=)
/**
* Assignment operator. Sets value for this dimensions.
*/
void operator=(X _value) {
if (ptr_dimension.type != MATRIX_DIMENSION_TYPE_VALUES) {
Print("Error: Trying to set matrix", ptr_matrix.Repr(), "'s value in a dimension which doesn't contain values!");
return;
}
ptr_dimension.values[index] = _value;
}
/**
* Returns value pointed by this accessor.
*/
X Val() {
if (ptr_dimension.type != MATRIX_DIMENSION_TYPE_VALUES) {
Print("Error: Trying to get value from matrix", ptr_matrix.Repr(), "'s dimension which doesn't contain values!");
return (X)EMPTY_VALUE;
}
return ptr_dimension.values[index];
}
/**
* Returns value pointed by this accessor or first value if it holds only one value or zero if index is above the
* dimension length.
*/
X ValOrZero() {
if (ptr_dimension.type != MATRIX_DIMENSION_TYPE_VALUES) {
Print("Error: Trying to get value from matrix", ptr_matrix.Repr(), "'s dimension which doesn't contain values!");
return (X)EMPTY_VALUE;
}
int _num_values = ArraySize(ptr_dimension.values);
if (_num_values == 0 || index >= _num_values) return (X)0;
return ptr_dimension.values[index];
}
};
/**
* A single matrix's dimension. Contains array of containers or values.
*/
template <typename X>
class MatrixDimension {
public:
ENUM_MATRIX_DIMENSION_TYPE type;
// Values array if type is "Values".
X values[];
// Physical position of the dimension in the matrix.
int position[MATRIX_DIMENSIONS - 1];
// Containers array if type is "Containers"
MatrixDimension<X>* containers[];
/**
* Constructor.
*/
MatrixDimension(ENUM_MATRIX_DIMENSION_TYPE _type = MATRIX_DIMENSION_TYPE_UNKNOWN) { type = _type; }
/**
* Destructor.
*/
~MatrixDimension() {
for (int i = 0; i < ArraySize(containers); ++i) {
delete containers[i];
}
}
/**
* Makes a clone of this and child dimensions.
*/
MatrixDimension<X>* Clone() const {
MatrixDimension<X>* _clone = new MatrixDimension<X>(type);
int i;
if (type == MATRIX_DIMENSION_TYPE_CONTAINERS) {
ArrayResize(_clone.containers, ArraySize(containers));
for (i = 0; i < ArraySize(containers); ++i) {
_clone.containers[i] = containers[i].Clone();
}
} else {
ArrayCopy(_clone.values, values);
}
return _clone;
}
/**
* Adds container to the list.
*/
void AddContainer(MatrixDimension* _dimension) {
ArrayResize(containers, ArraySize(containers) + 1);
containers[ArraySize(containers) - 1] = _dimension;
}
/**
* Adds value to the list.
*/
void AddValue(X value) {
ArrayResize(
values, ArraySize(values) + 1,
(ArraySize(values) - ArraySize(values) % MATRIX_VALUES_ARRAY_INCREMENT) + MATRIX_VALUES_ARRAY_INCREMENT);
values[ArraySize(values) - 1] = value;
}
/**
* Sets physical position of the dimension in the matrix.
*/
void SetPosition(int& _position[], int _level) {
for (int i = 0; i < ArraySize(_position); ++i) {
position[i] = i < _level ? _position[i] : -1;
}
}
string Spaces(int _num) {
string _padding;
StringInit(_padding, _num, ' ');
return _padding;
}
string ToString(bool _whitespaces = false, int _precision = 3, int level = 1) {
string out = "";
int i;
if (ArraySize(containers) != 0) {
out += (_whitespaces ? Spaces((level - 1) * 2) : "") + (_whitespaces ? "[\n" : "[");
for (i = 0; i < ArraySize(containers); ++i) {
out += containers[i].ToString(_whitespaces, _precision, level + 1) +
(i != ArraySize(containers) - 1 ? "," : "") + (_whitespaces ? "\n" : "");
}
out += (_whitespaces ? Spaces((level - 1) * 2) : "") + "]";
} else {
out += (_whitespaces ? Spaces(level * 2) : "") + (_whitespaces ? "[ " : "[");
for (i = 0; i < ArraySize(values); ++i) {
if (values[i] > -MaxOf(values[i]) && values[i] < MaxOf(values[i])) {
out += DoubleToString((double)values[i], _precision);
} else {
out += (values[i] < 0 ? "-inf" : "inf");
}
out += (i != ArraySize(values) - 1) ? (_whitespaces ? ", " : ",") : "";
}
out += (_whitespaces ? " ]" : "]");
}
return out;
}
/**
* Reduces dimension if it contains values. Goes recursively up to _level.
*/
void ReduceSimple(int _level = 0, ENUM_MATRIX_OPERATION _reduce_op = MATRIX_OPERATION_SUM, int _current_level = 0) {
int i;
if (type == MATRIX_DIMENSION_TYPE_CONTAINERS && _current_level <= _level) {
for (i = 0; i < ArraySize(containers); ++i) {
containers[i].ReduceSimple(_level, _reduce_op, _current_level + 1);
}
}
if (type == MATRIX_DIMENSION_TYPE_CONTAINERS && ArraySize(containers) > 0 &&
containers[0].type == MATRIX_DIMENSION_TYPE_VALUES && ArraySize(containers[0].values) == 1) {
type = MATRIX_DIMENSION_TYPE_VALUES;
for (i = 0; i < ArraySize(containers); ++i) {
X _sum = 0;
for (int k = 0; k < ArraySize(containers[i].values); ++k) {
_sum += containers[i].values[k];
}
AddValue(_sum);
delete containers[i];
}
ArrayResize(containers, 0);
}
}
/**
* Reduces (aggregates) dimensions up to _level.
*/
void Reduce(int _level = 0, ENUM_MATRIX_OPERATION _reduce_op = MATRIX_OPERATION_SUM, int _current_level = 0) {
int i;
if (type == MATRIX_DIMENSION_TYPE_CONTAINERS && _current_level < _level) {
for (i = 0; i < ArraySize(containers); ++i) {
containers[i].Reduce(_level, _reduce_op, _current_level + 1);
}
}
if (type == MATRIX_DIMENSION_TYPE_CONTAINERS && _current_level >= _level) {
// There will be as many values as containers.
ArrayResize(values, ArraySize(containers));
for (i = 0; i < ArraySize(containers); ++i) {
X _sum = 0;
X _out1 = 0, _out2;
int _out3;
containers[i].Op(_reduce_op, 0, 0, 0, _out1, _out2, _out3);
values[i] = _out1;
delete containers[i];
}
ArrayResize(containers, 0);
type = MATRIX_DIMENSION_TYPE_VALUES;
}
}
/**
* Reduces dimension if it contains values. Goes recursively up to _level.
* Returns initial dimensions size for the given level.
*/
int DuplicateDimension(int _level, int _num, int _current_level = 0) {
int i, k, num_initial_containers = 0;
if (type == MATRIX_DIMENSION_TYPE_CONTAINERS && _current_level < _level) {
for (i = 0; i < ArraySize(containers); ++i) {
num_initial_containers = containers[i].DuplicateDimension(_level, _num, _current_level + 1);
}
return num_initial_containers;
}
if (type == MATRIX_DIMENSION_TYPE_CONTAINERS) {
num_initial_containers = ArraySize(containers);
for (i = 0; i < _num; ++i) {
for (k = 0; k < num_initial_containers; ++k) {
MatrixDimension<X>* _new_dim = containers[k].Clone();
AddContainer(_new_dim);
}
}
return num_initial_containers;
}
return 0;
}
/**
* Initializes dimension data from another dimension.
*/
void CopyFrom(MatrixDimension<X>& _r) {
if (type == MATRIX_DIMENSION_TYPE_CONTAINERS) {
for (int i = 0; i < ArraySize(containers); ++i) {
containers[i].CopyFrom(_r.containers[i]);
}
} else if (type == MATRIX_DIMENSION_TYPE_VALUES) {
ArrayCopy(values, _r.values);
}
}
/**
* Resizes this dimension and sets its type (containers or values array).
*/
virtual void Resize(int _num_items, ENUM_MATRIX_DIMENSION_TYPE _type = MATRIX_DIMENSION_TYPE_VALUES) {
int i, _last_size;
if (_type != MATRIX_DIMENSION_TYPE_CONTAINERS) {
// Removing containers if there's any.
for (i = 0; i < ArraySize(containers); ++i) {
delete containers[i];
}
ArrayResize(containers, 0);
}
if (_type != MATRIX_DIMENSION_TYPE_VALUES) {
// Removing values.
ArrayResize(values, 0);
}
switch (_type) {
case MATRIX_DIMENSION_TYPE_CONTAINERS:
if (type == MATRIX_DIMENSION_TYPE_CONTAINERS) {
// There already were containers, resizing.
if (_num_items < ArraySize(containers)) {
// Deleting not needed containers.
for (i = _num_items; i < ArraySize(containers); ++i) {
delete containers[i];
}
}
}
ArrayResize(containers, _num_items);
break;
case MATRIX_DIMENSION_TYPE_VALUES:
_last_size = ArraySize(values);
ArrayResize(values, _num_items);
if (_num_items > _last_size) {
// Clearing new values.
ArrayFill(values, _last_size, _num_items - _last_size, (X)0);
}
break;
}
type = _type;
}
/**
* Initializes dimensions deeply.
*
* @todo Allow of resizing containers instead of freeing them firstly.
*/
static MatrixDimension<X>* SetDimensions(MatrixDimension<X>* _ptr_parent_dimension, int& _dimensions[], int index,
int& _current_position[]) {
if (_ptr_parent_dimension == NULL) _ptr_parent_dimension = new MatrixDimension();
if (index == 0 && _dimensions[0] == 0) {
// Matrix without any dimensions.
_ptr_parent_dimension.type = MATRIX_DIMENSION_TYPE_VALUES;
}
_ptr_parent_dimension.SetPosition(_current_position, index);
int i;
if (_dimensions[index + 1] == 0) {
_ptr_parent_dimension.Resize(_dimensions[index], MATRIX_DIMENSION_TYPE_VALUES);
} else {
_ptr_parent_dimension.Resize(_dimensions[index], MATRIX_DIMENSION_TYPE_CONTAINERS);
for (i = 0; i < _dimensions[index]; ++i) {
_ptr_parent_dimension.containers[i] =
SetDimensions(_ptr_parent_dimension.containers[i], _dimensions, index + 1, _current_position);
++_current_position[index];
}
}
return _ptr_parent_dimension;
}
/**
* Executes operation on a single value.
*/
X OpSingle(ENUM_MATRIX_OPERATION _op, X _src = (X)0, X _arg1 = (X)0, X _arg2 = (X)0, X _arg3 = (X)0) {
int _pos = 0;
switch (_op) {
case MATRIX_OPERATION_ABS:
return MathAbs(_src);
case MATRIX_OPERATION_ADD:
return _src + _arg1;
case MATRIX_OPERATION_SUBTRACT:
return _src - _arg1;
case MATRIX_OPERATION_MULTIPLY:
return _src * _arg1;
case MATRIX_OPERATION_DIVIDE:
return _src / _arg1;
break;
case MATRIX_OPERATION_FILL:
return _arg1;
case MATRIX_OPERATION_FILL_RANDOM:
if (_arg1 != -1) {
srand((int)_arg3);
}
return -(X)1 + (X)MathRand() / 32767 * 2;
case MATRIX_OPERATION_FILL_RANDOM_RANGE:
if (_arg3 != -1) {
srand((int)_arg3);
}
return (X)MathRand() / 32767 * (_arg2 - _arg1) + _arg1;
case MATRIX_OPERATION_ABS_DIFF:
return MathAbs(_src - _arg1);
case MATRIX_OPERATION_ABS_DIFF_SQUARE:
return (X)pow(MathAbs(_src - _arg1), (X)2);
case MATRIX_OPERATION_ABS_DIFF_SQUARE_LOG:
return (X)pow(log(_src + 1) - log(_arg1 + 1), (X)2);
case MATRIX_OPERATION_POISSON:
return (X)(_arg1 - _src * log(_arg1));
case MATRIX_OPERATION_LOG_COSH:
// log((exp((b-a)) + exp(-(b-a)))/2)
return (X)log((exp((_arg1 - _src)) + exp(-(_arg1 - _src))) / (X)2);
case MATRIX_OPERATION_RELU:
return Math::ReLU(_src);
default:
Print("MatrixDimension::OpSingle(): Invalid operation ", EnumToString(_op), "!");
}
return (X)0;
}
/**
* Executes operation on all matrix's values.
*/
void Op(ENUM_MATRIX_OPERATION _op, X _arg1, X _arg2, X _arg3, X& _out1, X& _out2, int& _out3) {
int i, k;
if (type == MATRIX_DIMENSION_TYPE_CONTAINERS) {
for (i = 0; i < ArraySize(containers); ++i) {
containers[i].Op(_op, _arg1, _arg2, _arg3, _out1, _out2, _out3);
}
} else {
for (i = 0; i < ArraySize(values); ++i) {
switch (_op) {
case MATRIX_OPERATION_ABS:
case MATRIX_OPERATION_ADD:
case MATRIX_OPERATION_SUBTRACT:
case MATRIX_OPERATION_MULTIPLY:
case MATRIX_OPERATION_DIVIDE:
case MATRIX_OPERATION_FILL:
case MATRIX_OPERATION_FILL_RANDOM:
case MATRIX_OPERATION_FILL_RANDOM_RANGE:
case MATRIX_OPERATION_POISSON:
case MATRIX_OPERATION_LOG_COSH:
case MATRIX_OPERATION_RELU:
values[i] = OpSingle(_op, values[i], _arg1, _arg2, _arg3);
break;
case MATRIX_OPERATION_FILL_POS_ADD:
values[i] = 0;
for (k = 0; k < ArraySize(position); ++k) {
if (position[k] == -1) {
break;
}
values[i] += (X)position[k];
}
values[i] += (X)i;
break;
case MATRIX_OPERATION_FILL_POS_MUL:
values[i] = MinOf((X)0);
for (k = 0; k < ArraySize(position); ++k) {
if (position[k] == -1) {
break;
}
values[i] = (values[i] == MinOf((X)0)) ? position[k] : values[i] * position[k];
}
values[i] = (values[i] == MinOf((X)0)) ? i : values[i] * i;
break;
case MATRIX_OPERATION_POWER:
values[i] = (X)pow(values[i], _arg1);
break;
case MATRIX_OPERATION_SUM:
_out1 += values[i];
break;
case MATRIX_OPERATION_MIN:
if (values[i] < _out1) {
_out1 = values[i];
}
break;
case MATRIX_OPERATION_MAX:
if (values[i] > _out1) {
_out1 = values[i];
}
break;
case MATRIX_OPERATION_ABS_DIFF:
values[i] = MathAbs(values[i] - _arg1);
break;
default:
Print("MatrixDimension::Op(): Invalid operation ", EnumToString(_op), "!");
}
}
}
}
/**
* Executes operation on the children containers and values. Used internally.
*/
void Op(ENUM_MATRIX_OPERATION _op, X _arg1 = (X)0, X _arg2 = (X)0, X _arg3 = (X)0) {
X _out1, _out2;
int _out3;
Op(_op, _arg1, _arg2, _arg3, _out1, _out2, _out3);
}
/**
* Extracts dimensions's values to the given array. Used internally.
*/
void FillArray(X& array[], int& offset) {
int i;
if (type == MATRIX_DIMENSION_TYPE_CONTAINERS) {
for (i = 0; i < ArraySize(containers); ++i) {
containers[i].FillArray(array, offset);
}
} else {
for (i = 0; i < ArraySize(values); ++i, ++offset) {
array[offset] = values[i];
}
}
}
void FromArray(X& _array[], int& offset) {
int i;
switch (type) {
case MATRIX_DIMENSION_TYPE_CONTAINERS:
for (i = 0; i < ArraySize(containers); ++i) {
containers[i].FromArray(_array, offset);
}
break;
case MATRIX_DIMENSION_TYPE_VALUES:
for (i = 0; i < ArraySize(values); ++i, ++offset) {
values[i] = _array[offset];
}
break;
}
}
/**
* Performs operation between current matrix/tensor and another one of the same or lower level.
*/
void Op(MatrixDimension<X>* _r, ENUM_MATRIX_OPERATION _op, X _arg1 = (X)0, int _only_value_index = -1) {
int i;
bool r_is_single = ArraySize(_r.values) == 1;
if (_r.type == MATRIX_DIMENSION_TYPE_VALUES && ArraySize(_r.values) == 1) {
// There is only one value in the right container, we will use that value for all operations.
_only_value_index = 0;
}
switch (type) {
case MATRIX_DIMENSION_TYPE_CONTAINERS:
switch (_r.type) {
case MATRIX_DIMENSION_TYPE_CONTAINERS:
// Both dimensions have containers.
for (i = 0; i < ArraySize(containers); ++i) {
containers[i].Op(_r.containers[ArraySize(_r.containers) == 1 ? 0 : i], _op, _arg1);
}
break;
case MATRIX_DIMENSION_TYPE_VALUES:
// Left dimension have containers, but right dimension have values.
for (i = 0; i < ArraySize(containers); ++i) {
// If there is only a single value in the right dimension, use it for all operations inside current
// container.
containers[i].Op(_r, _op, _arg1, _only_value_index != -1 ? _only_value_index : i);
}
break;
}
break;
case MATRIX_DIMENSION_TYPE_VALUES:
switch (_r.type) {
case MATRIX_DIMENSION_TYPE_CONTAINERS:
// Right dimension have containers.
if (ArraySize(_r.containers) != 1) {
Alert("Right container must have exactly one element!");
return;
}
Op(_r.containers[0], _op, _arg1);
break;
case MATRIX_DIMENSION_TYPE_VALUES:
// Left and right dimensions have values or we use single right value.
for (i = 0; i < ArraySize(values); ++i) {
values[i] = OpSingle(_op, values[i], _r.values[_only_value_index != -1 ? _only_value_index : i]);
}
break;
}
break;
}
}
};
/**
* Matrix class.
*/
template <typename X>
class Matrix {
public:
// First/root dimension.
MatrixDimension<X>* ptr_first_dimension;
// Array with declaration of items per matrix's dimension.
int dimensions[MATRIX_DIMENSIONS];
// Current size of the matrix (all dimensions multiplied).
int size;
// Number of matrix dimensions.
int num_dimensions;
/**
* Constructor.
*/
Matrix(string _data) { FromString(_data); }
/**
* Constructor.
*/
Matrix(const int num_1d = 0, const int num_2d = 0, const int num_3d = 0, const int num_4d = 0, const int num_5d = 0) {
ptr_first_dimension = NULL;
SetShape(num_1d, num_2d, num_3d, num_4d, num_5d);
}
/**
* Constructor.
*/
Matrix(MatrixDimension<X>* _dimension) : ptr_first_dimension(NULL) { Initialize(_dimension); }
/**
* Copy constructor.
*/
Matrix(const Matrix<X>& _right) {
if (_right.ptr_first_dimension == NULL) {
return;
}
Initialize(_right.ptr_first_dimension.Clone());
}
/**
* Private copy constructor. We don't want to assign Matrix via pointer due to memory leakage.
*/
private:
Matrix(const Matrix<X>* _right) {}
public:
/**
* Matrix initializer.
*/
void Initialize(MatrixDimension<X>* _dimension) {
if (ptr_first_dimension != NULL) delete ptr_first_dimension;
ptr_first_dimension = _dimension;
// Calculating dimensions.
int i;
for (i = 0; i < MATRIX_DIMENSIONS; ++i) {
dimensions[i] = 0;
}
for (i = 0; i < MATRIX_DIMENSIONS; ++i) {
if (_dimension == NULL) break;
if (_dimension.type == MATRIX_DIMENSION_TYPE_CONTAINERS) {
dimensions[i] = ArraySize(_dimension.containers);
_dimension = _dimension.containers[0];
} else if (_dimension.type == MATRIX_DIMENSION_TYPE_VALUES) {
dimensions[i++] = ArraySize(_dimension.values);
break;
} else {
Print("Internal error: unknown dimension type!");
}
}
num_dimensions = i;
RecalculateSize();
}
void RecalculateSize() {
size = 0;
for (int i = 0; i < ArraySize(dimensions); ++i) {
if (dimensions[i] != 0) {
if (size == 0) {
size = 1;
}
size *= dimensions[i];
}
}
}
/**
* Assignment operator.
*/
void operator=(const Matrix<X>& _right) { Initialize(_right.ptr_first_dimension.Clone()); }
/**
* Assignment operator. Initializes matrix using given dimension.
*/
Matrix(MatrixDimensionAccessor<X>& accessor) {
if (accessor.Type() == MATRIX_DIMENSION_TYPE_CONTAINERS) {
Initialize(accessor.ptr_dimension.containers[accessor.index].Clone());
} else if (accessor.Type() == MATRIX_DIMENSION_TYPE_VALUES) {
SetShape(1);
this[0] = accessor.Val();
}
}
/**
* Assignment operator.
*/
void operator=(string _data) { FromString(_data); }
/**
* Destructor.
*/
~Matrix() {
if (ptr_first_dimension != NULL) {
delete ptr_first_dimension;
}
}
/**
* Index operator. Returns container or value accessor.
*/
MatrixDimensionAccessor<X> operator[](int index) {
MatrixDimensionAccessor<X> accessor(&this, ptr_first_dimension, index);
return accessor;
}
/**
* Sets or changes matrix's dimensions.
*/
void SetShape(const int num_1d = 0, const int num_2d = 0, const int num_3d = 0, const int num_4d = 0,
const int num_5d = 0) {
dimensions[0] = num_1d;
dimensions[1] = num_2d;
dimensions[2] = num_3d;
dimensions[3] = num_4d;
dimensions[4] = num_5d;
dimensions[5] = 0;
int _current_position[] = {0, 0, 0, 0};
ptr_first_dimension = MatrixDimension<X>::SetDimensions(ptr_first_dimension, dimensions, 0, _current_position);
// Calculating size.
size = 0;
num_dimensions = (num_1d != 0 ? 1 : 0) + (num_2d != 0 ? 1 : 0) + (num_3d != 0 ? 1 : 0) + (num_4d != 0 ? 1 : 0) +
(num_5d != 0 ? 1 : 0);
// Calculating size.
for (int i = 0; i < MATRIX_DIMENSIONS; ++i) {
if (dimensions[i] != 0) {
if (size == 0) {
size = 1;
}
size *= dimensions[i];
}
}
}
/**
* Returns length of the given dimension.
*/
int GetRange(int _dimension) {
if (_dimension >= MATRIX_DIMENSIONS) {
Print("Matrix::GetRange(): Dimension should be between 0 and ", MATRIX_DIMENSIONS - 1, ". Got ", _dimension, "!");
return -1;
}
return dimensions[_dimension];
}
/**
* Returns total number of values the matrix contain of.
*/
int GetSize() { return size; }
/**
* Returns number of matrix dimensions.
*/
int GetDimensions() { return num_dimensions; }
void DuplicateDimension(int _level, int _num, int _current_level = 0) {
if (_num < 1) {
return;
}
if (_level >= GetDimensions()) {
return;
}
int initial_container_size = ptr_first_dimension.DuplicateDimension(_level, _num);
dimensions[_level] += _num * initial_container_size;
RecalculateSize();
}
/**
* Returns value at the given position.
*/
X GetValue(int _pos_1d, int _pos_2d = -1, int _pos_3d = -1, int _pos_4d = -1, int _pos_5d = -1) {
MatrixDimensionAccessor<X> accessor = this[_pos_1d];
if (accessor.Type() == MATRIX_DIMENSION_TYPE_CONTAINERS) {
accessor = accessor[_pos_2d];
if (accessor.Type() == MATRIX_DIMENSION_TYPE_CONTAINERS) {
accessor = accessor[_pos_3d];
if (accessor.Type() == MATRIX_DIMENSION_TYPE_CONTAINERS) {
accessor = accessor[_pos_4d];
if (accessor.Type() == MATRIX_DIMENSION_TYPE_CONTAINERS) {
Alert("Matrix::GetValue(): Internal error. Last dimensions shouldn't be a container!");
}
}
}
}
return accessor.Val();
}
/**
* Returns value at the given position (or parent one for missing dimensions, or zero for missing indices).
*/
X GetValueLossely(int _source_dimensions, int _pos_1d, int _pos_2d = -1, int _pos_3d = -1, int _pos_4d = -1,
int _pos_5d = -1) {
int _shift_dimensions = _source_dimensions - GetDimensions();
while (_shift_dimensions-- > 0) {
_pos_1d = _pos_2d;
_pos_2d = _pos_3d;
_pos_3d = _pos_4d;
_pos_4d = _pos_5d;
_pos_5d = 0;
}
if (GetDimensions() < 1) return 0;
MatrixDimensionAccessor<X> accessor;
if (_pos_1d >= dimensions[0]) {
if (dimensions[0] == 1)
_pos_1d = 0;
else
return 0;
}
accessor = this[_pos_1d];
// Returning prematurely if we experienced value instead of a container.
if (accessor.Type() == MATRIX_DIMENSION_TYPE_VALUES) return accessor.Val();
if (_pos_2d >= dimensions[1]) {
if (dimensions[1] == 1)
_pos_2d = 0;
else
return 0;
}
accessor = accessor[_pos_2d];
// Returning prematurely if we experienced value instead of a container.
if (accessor.Type() == MATRIX_DIMENSION_TYPE_VALUES) return accessor.Val();
if (_pos_3d >= dimensions[2]) {
if (dimensions[2] == 1)
_pos_3d = 0;