-
Notifications
You must be signed in to change notification settings - Fork 20
/
EigenLab.h
2519 lines (2315 loc) · 105 KB
/
EigenLab.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
// --*- Mode: C++; c-basic-offset:4; indent-tabs-mode:t; tab-width:4 -*--
// EigenLab
// Version: 1.0.0
// Author: Dr. Marcel Paz Goldschen-Ohm
// Email: [email protected]
// Copyright (c) 2015 by Dr. Marcel Paz Goldschen-Ohm.
// Licence: MIT
//----------------------------------------
#ifndef EigenLab_H
#define EigenLab_H
#include <Eigen/Dense>
#include <iomanip>
#include <type_traits>
#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
// Define both DEBUG and EIGENLAB_DEBUG for step-by-step equation parsing printouts.
#ifndef DEBUG
//# define DEBUG
#endif
#ifndef EIGENLAB_DEBUG
//# define EIGENLAB_DEBUG 1
#endif
// Define EIGENLAB_MAXMATRIX to change the maximum matrix size
#ifndef EIGENLAB_MAXMATRIX
# define EIGENLAB_MAXMATRIX ((unsigned long)128*1024*1024) // 128 MiB
#endif
#ifdef DEBUG
# include <iostream>
#endif
namespace EigenLab
{
//----------------------------------------
// A wrapper for a matrix whose data is either stored locally or shared.
//
// Template typename Derived can be any dynamically sized matrix type supported by Eigen.
//
// !!! matrix() promises to ALWAYS return a map to the matrix data whether it's
// stored locally or externally in some shared memory.
//
// !!! local() provides direct access to the local data, but this data is
// ONLY valid when isLocal() is true. In most cases, you're best off
// accessing the matrix data via matrix() instead.
//----------------------------------------
template <typename Derived = Eigen::MatrixXd>
class Value
{
private:
// Local matrix data.
Derived mLocal;
// Map to shared matrix data (map points to mLocal if the data is local).
// !!! This map promises to ALWAYS point to the matrix data whether it's
// stored locally in mLocal or externally in some shared memory.
Eigen::Map<Derived> mShared;
// Flag indicating whether the local data is being used.
bool mIsLocal;
public:
// Access mapped data (whether its local or shared).
// !!! matrix() promises to ALWAYS return a map to the matrix data whether it's
// stored locally in mLocal or externally in some shared memory.
inline Eigen::Map<Derived> & matrix() { return mShared; }
inline const Eigen::Map<Derived> & matrix() const { return mShared; }
// Access local data.
// !!! WARNING! This data is ONLY valid if isLocal() is true.
// !!! WARNING! If you change the local data via this method, you MUST call mapLocal() immediately afterwards.
// In most cases, you're best off accessing the matrix data via matrix() instead.
inline Derived & local() { return mLocal; }
inline const Derived & local() const { return mLocal; }
// Is mapped data local?
inline bool isLocal() const { return mIsLocal; }
// Set mapped data to point to local data.
inline void mapLocal() { new (& mShared) Eigen::Map<Derived>(mLocal.data(), mLocal.rows(), mLocal.cols()); mIsLocal = true; }
// Copy shared data to local data (if needed).
inline void copySharedToLocal() { if(!isLocal()) { mLocal = mShared; mapLocal(); } }
// Set local data.
Value() : mLocal(1, 1), mShared(mLocal.data(), mLocal.rows(), mLocal.cols()), mIsLocal(true) {}
Value(const typename Derived::Scalar s) : mLocal(Derived::Constant(1, 1, s)), mShared(mLocal.data(), mLocal.rows(), mLocal.cols()), mIsLocal(true) {}
Value(const Derived & mat) : mLocal(mat), mShared(mLocal.data(), mLocal.rows(), mLocal.cols()), mIsLocal(true) {}
inline void setLocal(const typename Derived::Scalar s) { mLocal = Derived::Constant(1, 1, s); mapLocal(); }
inline void setLocal(const Eigen::MatrixBase<Derived> & mat) { mLocal = mat; mapLocal(); }
inline void setLocal(const Value & val) { mLocal = val.matrix(); mapLocal(); }
inline void setLocal(const typename Derived::Scalar * data, size_t rows = 1, size_t cols = 1) { setShared(data, rows, cols); copySharedToLocal(); }
inline Value & operator = (const typename Derived::Scalar s) { setLocal(s); return (* this); }
inline Value & operator = (const Derived & mat) { setLocal(mat); return (* this); }
// Set shared data.
Value(const typename Derived::Scalar * data, size_t rows = 1, size_t cols = 1) : mShared(const_cast<typename Derived::Scalar *>(data), rows, cols), mIsLocal(false) {}
inline void setShared(const typename Derived::Scalar * data, size_t rows = 1, size_t cols = 1) { new (& mShared) Eigen::Map<Derived>(const_cast<typename Derived::Scalar *>(data), rows, cols); mIsLocal = false; }
inline void setShared(const Derived & mat) { setShared(mat.data(), mat.rows(), mat.cols()); }
inline void setShared(const Value & val) { setShared(val.matrix().data(), val.matrix().rows(), val.matrix().cols()); }
// Set to local or shared data dependent on whether val maps its own local data or some other shared data.
Value(const Value & val) : mLocal(1, 1), mShared(mLocal.data(), mLocal.rows(), mLocal.cols()) { (* this) = val; }
inline Value & operator = (const Value & val) { if(val.isLocal()) { setLocal(val); } else { setShared(val); } return (* this); }
};
typedef Value<Eigen::MatrixXd> ValueXd;
typedef Value<Eigen::MatrixXf> ValueXf;
typedef Value<Eigen::MatrixXi> ValueXi;
// check if a class has a comparison operator (ie. std::complex does not)
template<typename T>
struct has_operator_lt_impl
{
template<class U>
static auto test(U*) -> decltype(std::declval<U>() < std::declval<U>());
template<typename>
static auto test(...) -> std::false_type;
using type = typename std::is_same<bool, decltype(test<T>(0))>::type;
};
template<typename T>
struct has_operator_lt : has_operator_lt_impl<T>::type {};
//----------------------------------------
// Equation parser.
//
// Template typename Derived can be any dynamically sized matrix type supported by Eigen.
//----------------------------------------
template <typename Derived = Eigen::MatrixXd>
class Parser
{
public:
// A map to hold named values.
typedef std::map<std::string, Value<Derived> > ValueMap;
private:
// Variables are stored in a map of named values.
ValueMap mVariables;
// Operator symbols and function names used by the parser.
std::string mOperators1, mOperators2;
std::vector<std::string> mFunctions;
// Expressions are parsed by first splitting them into chunks.
enum ChunkType { VALUE = 0, VARIABLE, OPERATOR, FUNCTION, NONE=-1 };
struct Chunk {
std::string field;
ChunkType type;
Value<Derived> value;
int row0, col0, rows, cols;
Chunk(const std::string & str = "", ChunkType t = NONE, const Value<Derived> & val = Value<Derived>()) : field(str), type(t), value(val), row0(-1), col0(-1), rows(-1), cols(-1) {}
};
typedef std::vector<Chunk> ChunkArray;
typedef typename Derived::Index Index;
bool mCacheChunkedExpressions;
std::map<std::string, ChunkArray> mCachedChunkedExpressions;
public:
// Access to named variables.
// !!! WARNING! var(name) will create the variable name if it does not already exist.
inline ValueMap & vars() { return mVariables; }
inline Value<Derived> & var(const std::string & name) { return mVariables[name]; }
// Check if a variable exists.
inline bool hasVar(const std::string & name) { return isVariable(name); }
// Delete a variable.
inline void clearVar(const std::string & name) { typename ValueMap::iterator it = mVariables.find(name); if(it != mVariables.end()) mVariables.erase(it); }
// Expression chunk caching.
inline bool cacheExpressions() const { return mCacheChunkedExpressions; }
inline void setCacheExpressions(bool b) { mCacheChunkedExpressions = b; }
inline void clearCachedExpressions() { mCachedChunkedExpressions.clear(); }
Parser();
~Parser() { clearCachedExpressions(); }
// Evaluate an expression and return the result in a value wrapper.
Value<Derived> eval(const std::string & expression);
private:
void splitEquationIntoChunks(const std::string & expression, ChunkArray & chunks, std::string & code);
std::string::const_iterator findClosingBracket(const std::string & str, const std::string::const_iterator openingBracket, const char closingBracket) const;
std::vector<std::string> splitArguments(const std::string & str, const char delimeter) const;
void evalIndexRange(const std::string & str, int * first, int * last, int numIndices);
void evalMatrixExpression(const std::string & str, Value<Derived> & mat);
void evalFunction(const std::string & name, std::vector<std::string> & args, Value<Derived> & result);
bool evalFunction_1_lt(const std::string & name, Value<Derived> & arg, Value<Derived> & result, std::false_type);
bool evalFunction_1_lt(const std::string & name, Value<Derived> & arg, Value<Derived> & result, std::true_type);
bool evalFunction_2_lt(const std::string & name, Value<Derived> & arg0, Value<Derived> & arg1, Value<Derived> & result, std::false_type);
bool evalFunction_2_lt(const std::string & name, Value<Derived> & arg0, Value<Derived> & arg1, Value<Derived> & result, std::true_type);
void evalNumericRange(const std::string & str, Value<Derived> & mat);
inline bool isVariable(const std::string & name) const { return mVariables.count(name) > 0; }
bool isBlockValid(const Derived & map, typename ChunkArray::iterator & it);
inline bool isOperator(const char c) const { return (std::find(mOperators1.begin(), mOperators1.end(), c) != mOperators1.end()); }
bool isOperator(const std::string & str) const;
inline bool isFunction(const std::string & str) const { return (std::find(mFunctions.begin(), mFunctions.end(), str) != mFunctions.end()); }
void evalIndices(ChunkArray & chunks);
void evalNegations(ChunkArray & chunks);
void evalPowers(ChunkArray & chunks);
void evalMultiplication(ChunkArray & chunks);
void evalAddition(ChunkArray & chunks);
void evalAssignment(ChunkArray & chunks);
#ifdef DEBUG
# ifdef EIGENLAB_DEBUG
void printChunks(ChunkArray & chunks, size_t maxRows = 2, size_t maxCols = 2, int precision = 0);
void printVars(size_t maxRows = 2, size_t maxCols = 2, int precision = 0);
std::string textRepresentation(Value<Derived> & val, size_t maxRows = 2, size_t maxCols = 2, int precision = 0);
# endif
#endif
public:
static std::string trim(const std::string & str);
static std::vector<std::string> split(const std::string & str, const char delimeter);
template <typename T> static bool isNumber(const std::string & str, T * num = 0);
template <typename T> static T stringToNumber(const std::string & str);
template <typename T> static std::string numberToString(T num, int precision = 0);
#ifdef DEBUG
void test_w_lt(size_t & numFails, typename Derived::Scalar & s, Derived & a34, Derived & b34, Derived & c43, Derived & v, std::true_type);
void test_w_lt(size_t & numFails, typename Derived::Scalar & s, Derived & a34, Derived & b34, Derived & c43, Derived & v, std::false_type);
size_t test();
#endif
};
typedef Parser<Eigen::MatrixXd> ParserXd;
typedef Parser<Eigen::MatrixXf> ParserXf;
typedef Parser<Eigen::MatrixXi> ParserXi;
//----------------------------------------
// Function definitions.
//----------------------------------------
template <typename Derived>
Parser<Derived>::Parser() :
mOperators1("+-*/^()[]="),
mOperators2(".+.-.*./.^"),
mCacheChunkedExpressions(false)
{
// Coefficient-wise operations.
mFunctions.push_back("abs");
mFunctions.push_back("sqrt");
mFunctions.push_back("exp");
mFunctions.push_back("log");
mFunctions.push_back("log10");
mFunctions.push_back("sin");
mFunctions.push_back("cos");
mFunctions.push_back("tan");
mFunctions.push_back("asin");
mFunctions.push_back("acos");
// Matrix reduction operations.
mFunctions.push_back("trace");
mFunctions.push_back("norm");
mFunctions.push_back("size");
if (has_operator_lt<typename Derived::Scalar>::value) {
mFunctions.push_back("min");
mFunctions.push_back("max");
mFunctions.push_back("absmax");
mFunctions.push_back("cwiseMin");
mFunctions.push_back("cwiseMax");
}
mFunctions.push_back("mean");
mFunctions.push_back("sum");
mFunctions.push_back("prod");
// Matrix operations.
mFunctions.push_back("transpose");
mFunctions.push_back("conjugate");
mFunctions.push_back("adjoint");
// Matrix initializers.
mFunctions.push_back("zeros");
mFunctions.push_back("ones");
mFunctions.push_back("eye");
}
template <typename Derived>
Value<Derived> Parser<Derived>::eval(const std::string & expression)
{
#ifdef DEBUG
# ifdef EIGENLAB_DEBUG
if (EIGENLAB_DEBUG) {
std::cout << "---" << std::endl;
std::cout << "EXPRESSION: " << expression << std::endl;
}
# endif
#endif
ChunkArray chunks;
std::string code;
splitEquationIntoChunks(trim(expression), chunks, code);
evalIndices(chunks);
evalNegations(chunks);
evalPowers(chunks);
evalMultiplication(chunks);
evalAddition(chunks);
evalAssignment(chunks);
if(chunks.size() != 1)
throw std::runtime_error("Failed to reduce expression '" + expression + "' to a single value.");
#ifdef DEBUG
# ifdef EIGENLAB_DEBUG
if (EIGENLAB_DEBUG) {
std::cout << "---" << std::endl;
}
# endif
#endif
if(chunks[0].type == VARIABLE) {
if(!isVariable(chunks[0].field))
throw std::runtime_error("Unknown variable '" + chunks[0].field + "'.");
return mVariables[chunks[0].field];
}
return chunks[0].value;
}
template <typename Derived>
void Parser<Derived>::splitEquationIntoChunks(const std::string & expression, ChunkArray & chunks, std::string & code)
{
if(cacheExpressions()) {
if(mCachedChunkedExpressions.count(expression) > 0) {
chunks = mCachedChunkedExpressions.at(expression);
#ifdef DEBUG
# ifdef EIGENLAB_DEBUG
if (EIGENLAB_DEBUG) {
std::cout << "CACHED CHUNKS: "; printChunks(chunks); std::cout << std::endl;
}
# endif
#endif
return;
}
}
for(std::string::const_iterator it = expression.begin(); it != expression.end();)
{
ChunkType prevType = (chunks.size() ? chunks.back().type : NONE);
char ci = (* it);
if(isspace(ci)) {
// Ignore whitespace.
it++;
} else if(ci == '(' && (prevType == VALUE || prevType == VARIABLE)) {
// Index group.
std::string::const_iterator jt = findClosingBracket(expression, it, ')');
if(jt == expression.end())
throw std::runtime_error("Missing closing bracket for '" + std::string(it, jt) + "'.");
std::string field = std::string(it + 1, jt); // Outer brackets stripped.
if(prevType == VARIABLE) {
if(!isVariable(chunks.back().field))
throw std::runtime_error("Unknown variable '" + chunks.back().field + "'.");
chunks.back().value.setShared(var(chunks.back().field));
}
int first, last;
int rows = int(chunks.back().value.matrix().rows());
int cols = int(chunks.back().value.matrix().cols());
std::vector<std::string> args = splitArguments(field, ',');
if(args.size() == 1) {
if(cols == 1) {
evalIndexRange(args[0], & first, & last, rows);
chunks.back().row0 = first;
chunks.back().col0 = 0;
chunks.back().rows = last + 1 - first;//(last == -1 ? int(chunks.back().value.matrix().rows()) : last + 1) - first;
chunks.back().cols = 1;
} else if(rows == 1) {
evalIndexRange(args[0], & first, & last, cols);
chunks.back().row0 = 0;
chunks.back().col0 = first;
chunks.back().rows = 1;
chunks.back().cols = last + 1 - first;//(last == -1 ? int(chunks.back().value.matrix().cols()) : last + 1) - first;
} else {
throw std::runtime_error("Missing row or column indices for '(" + chunks.back().field + "(" + field + ")'.");
}
} else if(args.size() == 2) {
evalIndexRange(args[0], & first, & last, rows);
chunks.back().row0 = first;
chunks.back().rows = last + 1 - first;//(last == -1 ? int(chunks.back().value.matrix().rows()) : last + 1) - first;
evalIndexRange(args[1], & first, & last, cols);
chunks.back().col0 = first;
chunks.back().cols = last + 1 - first;//(last == -1 ? int(chunks.back().value.matrix().cols()) : last + 1) - first;
} else {
throw std::runtime_error("Invalid index expression '" + chunks.back().field + "(" + field + ")'.");
}
code += "i";
it = jt + 1;
} else if(ci == '(' && prevType == FUNCTION) {
// Function argument group.
std::string::const_iterator jt = findClosingBracket(expression, it, ')');
if(jt == expression.end())
throw std::runtime_error("Missing closing bracket for '" + std::string(it, jt) + "'.");
std::string field = std::string(it + 1, jt); // Outer brackets stripped.
std::vector<std::string> args = splitArguments(field, ',');
evalFunction(chunks.back().field, args, chunks.back().value);
chunks.back().field += "(" + field + ")";
chunks.back().type = VALUE;
code += (chunks.back().value.matrix().size() == 1 ? "n" : "M");
it = jt + 1;
} else if(ci == '(') {
// Recursively evaluate group to a single value.
std::string::const_iterator jt = findClosingBracket(expression, it, ')');
if(jt == expression.end())
throw std::runtime_error("Missing closing bracket for '" + std::string(it, jt) + "'.");
std::string field = std::string(it + 1, jt); // Outer brackets stripped.
chunks.push_back(Chunk(field, prevType = VALUE, eval(field)));
code += (chunks.back().value.matrix().size() == 1 ? "n" : "M");
it = jt + 1;
} else if(ci == '[') {
// Evaluate matrix.
if(prevType == VALUE || prevType == VARIABLE)
throw std::runtime_error("Invalid operation '" + chunks.back().field + std::string(1, ci) + "'.");
std::string::const_iterator jt = findClosingBracket(expression, it, ']');
if(jt == expression.end())
throw std::runtime_error("Missing closing bracket for '" + std::string(it, jt) + "'.");
std::string field = std::string(it + 1, jt); // Outer brackets stripped.
chunks.push_back(Chunk("[" + field + "]", prevType = VALUE));
evalMatrixExpression(field, chunks.back().value);
code += (chunks.back().value.matrix().size() == 1 ? "n" : "M");
it = jt + 1;
} else if(ci == ')' || ci == ']') {
throw std::runtime_error("Unexpected closing '" + std::string(it, it+1) + "'.");
} else if(it + 1 != expression.end() && isOperator(std::string(it, it + 2))) {
// Double character operator.
std::string field = std::string(it, it + 2);
chunks.push_back(Chunk(field, prevType = OPERATOR));
code += field;
it += 2;
} else if(isOperator(ci)) {
// Single character operator.
std::string field = std::string(1, ci);
chunks.push_back(Chunk(field, prevType = OPERATOR));
code += field;
it++;
} else {
// Non-operator: value range, number, function, or variable name.
std::string::const_iterator jt = it + 1;
// accept fp-strings, ie [+-]
unsigned char state = 1;
for(std::string::const_iterator kt = it; state && kt != expression.end(); kt++) {
unsigned char token;
if (*kt == ' ') token = 0;
else if (*kt == '+' || *kt == '-') token = 1;
else if (isdigit(*kt)) token = 2;
else if (*kt == '.') token = 3;
else if (*kt == 'e' || *kt == 'E') token = 4;
else break;
const static char nextstate[9][5] = {{0},
{1, 2, 3, 4, 0},
{0, 0, 3, 4, 0},
{0, 0, 3, 5, 6},
{0, 0, 5, 0, 0},
{0, 0, 5, 0, 6},
{0, 7, 8, 0, 0},
{0, 0, 8, 0, 0},
{0, 0, 8, 0, 0}};
//WARN("state=" << (int)state << " token(" << *kt << ")=" << (int)token
// << " nextstate = " << (int)nextstate[state][token] << "\n");
state = nextstate[state][token];
if (state == 8) jt = kt;
}
for(; jt != expression.end(); jt++) {
if(isOperator(*jt) || (jt + 1 != expression.end() && isOperator(std::string(jt, jt + 2))))
break;
}
std::string field = trim(std::string(it, jt));
if(prevType == VALUE || prevType == VARIABLE)
throw std::runtime_error("Invalid operation '" + chunks.back().field + field + "'.");
double num;
if(field.find(":") != std::string::npos) {
// Numeric range.
chunks.push_back(Chunk(field, prevType = VALUE));
evalNumericRange(field, chunks.back().value);
code += (chunks.back().value.matrix().size() == 1 ? "n" : "M");
} else if(isNumber<double>(field, & num)) {
// Number.
chunks.push_back(Chunk(field, prevType = VALUE, Value<Derived>(num)));
code += "n";
} else if(isVariable(field)) {
// Local variable.
chunks.push_back(Chunk(field, prevType = VARIABLE));
code += (mVariables[field].matrix().size() == 1 ? "vn" : "vM");
} else if(isFunction(field)) {
// Function.
chunks.push_back(Chunk(field, prevType = FUNCTION));
} else {
// New undefined variable.
chunks.push_back(Chunk(field, prevType = VARIABLE));
code += "vU";
}
it = jt;
}
} // it
#ifdef DEBUG
# ifdef EIGENLAB_DEBUG
if (EIGENLAB_DEBUG) {
std::cout << "CHUNKS: "; printChunks(chunks); std::cout << std::endl;
std::cout << "CODE: " << code << std::endl;
}
# endif
#endif
if(cacheExpressions())
mCachedChunkedExpressions[expression] = chunks;
}
template <typename Derived>
std::string::const_iterator Parser<Derived>::findClosingBracket(const std::string & str, const std::string::const_iterator openingBracket, const char closingBracket) const
{
int depth = 1;
std::string::const_iterator it = openingBracket + 1;
for(; it != str.end(); it++) {
if((*it) == (*openingBracket)) depth++;
else if((*it) == closingBracket) depth--;
if(depth == 0) return it;
}
return str.end();
}
template <typename Derived>
std::vector<std::string> Parser<Derived>::splitArguments(const std::string & str, const char delimeter) const
{
std::vector<std::string> args;
std::string::const_iterator i0 = str.begin();
for(std::string::const_iterator it = str.begin(); it != str.end(); it++) {
if((*it) == '(') it = findClosingBracket(str, it, ')');
else if((*it) == '[') it = findClosingBracket(str, it, ']');
else if((*it) == delimeter) {
args.push_back(trim(std::string(i0, it)));
i0 = it + 1;
}
if (it == str.end())
break;
}
args.push_back(std::string(i0, str.end()));
return args;
}
template <typename Derived>
void Parser<Derived>::evalIndexRange(const std::string & str, int * first, int * last, int numIndices)
{
if(str.empty())
throw std::runtime_error("Empty index range.");
ValueXi valuei;
ParserXi parseri;
size_t pos;
for(std::string::const_iterator it = str.begin(); it != str.end(); it++) {
if((*it) == ':') {
std::string firstStr = trim(std::string(str.begin(), it));
std::string lastStr = trim(std::string(it + 1, str.end()));
if(firstStr.empty() && lastStr.empty()) {
(* first) = 0;
(* last) = numIndices - 1;
return;
}
if(firstStr.empty() || lastStr.empty())
throw std::runtime_error("Missing indices for '" + str + "'.");
pos = firstStr.find("end");
if(pos != std::string::npos) {
firstStr = firstStr.substr(0, pos) + numberToString<int>(numIndices - 1) + firstStr.substr(pos + 3);
}
pos = lastStr.find("end");
if(pos != std::string::npos) {
lastStr = lastStr.substr(0, pos) + numberToString<int>(numIndices - 1) + lastStr.substr(pos + 3);
}
valuei = parseri.eval(firstStr);
if(valuei.matrix().size() != 1)
throw std::runtime_error("Invalid indices '" + str + "'.");
(* first) = valuei.matrix()(0, 0);
valuei = parseri.eval(lastStr);
if(valuei.matrix().size() != 1)
throw std::runtime_error("Invalid indices '" + str + "'.");
(* last) = valuei.matrix()(0, 0);
return;
}
}
std::string firstStr = str;
pos = firstStr.find("end");
if(pos != std::string::npos) {
firstStr = firstStr.substr(0, pos) + numberToString<int>(numIndices - 1) + firstStr.substr(pos + 3);
}
valuei = parseri.eval(firstStr);
if(valuei.matrix().size() != 1)
throw std::runtime_error("Invalid index '" + str + "'.");
(* first) = valuei.matrix()(0, 0);
(* last) = (* first);
}
template <typename Derived>
void Parser<Derived>::evalMatrixExpression(const std::string & str, Value<Derived> & mat)
{
// !!! Expression may NOT include outer brackets, although brackets for individual rows are OK.
std::vector<std::string> rows = splitArguments(str, ';');
std::vector<std::vector<typename Derived::Scalar> > temp;
Value<Derived> submatrix;
size_t row0 = 0, col0 = 0, nrows = 0, ncols = 0;
size_t pos;
for(size_t i = 0; i < rows.size(); i++) {
// Strip row brackets if they exist.
if(rows[i][0] == '[' && rows[i].back() == ']') rows[i] = rows[i].substr(1, int(rows[i].size()) - 2);
std::vector<std::string> cols = splitArguments(rows[i], ',');
col0 = 0;
ncols = 0;
for(size_t j = 0; j < cols.size(); j++) {
pos = cols[j].find(":");
if(pos != std::string::npos) {
std::string firstStr = cols[j].substr(0, pos);
std::string lastStr = cols[j].substr(pos + 1);
pos = lastStr.find(":");
if(pos != std::string::npos) {
std::string stepStr = lastStr.substr(0, pos);
lastStr = lastStr.substr(pos + 1);
if(lastStr.find(":") != std::string::npos)
throw std::runtime_error("Invalid matrix definition '[" + str + "]'. Invalid range '" + cols[j] + "'.");
// first:step:last
Value<Derived> first = eval(firstStr);
Value<Derived> step = eval(stepStr);
Value<Derived> last = eval(lastStr);
if(first.matrix().size() != 1 || step.matrix().size() != 1 || last.matrix().size() != 1)
throw std::runtime_error("Invalid matrix definition '[" + str + "]'. Invalid range '" + cols[j] + "'.");
typename Derived::RealScalar sfirst = std::real(first.matrix()(0));
typename Derived::RealScalar sstep = std::real(step.matrix()(0));
typename Derived::RealScalar slast = std::real(last.matrix()(0));
if(sfirst == slast) {
submatrix.local().setConstant(1, 1, sfirst);
submatrix.mapLocal();
} else if((slast - sfirst >= 0 && sstep > 0) || (slast - sfirst <= 0 && sstep < 0)) {
long double n = floor((slast - sfirst) / sstep) + 1;
if (n < 0 || n > EIGENLAB_MAXMATRIX)
throw std::runtime_error("Invalid matrix size requested '" + std::to_string(n) + "', set EIGENLAB_MAXMATRIX to allow larger matrices.");
submatrix.local().resize(1, n);
for(unsigned k = 0; k < n; ++k)
submatrix.local()(0, k) = sfirst + k * sstep;
submatrix.mapLocal();
} else {
throw std::runtime_error("Invalid matrix definition '[" + str + "]'. Invalid range '" + cols[j] + "'.");
}
} else {
// first:last => first:1:last
Value<Derived> first = eval(firstStr);
Value<Derived> last = eval(lastStr);
if(first.matrix().size() != 1 || last.matrix().size() != 1)
throw std::runtime_error("Invalid matrix definition '[" + str + "]'. Invalid range '" + cols[j] + "'.");
typename Derived::RealScalar sfirst = std::real(first.matrix()(0));
typename Derived::RealScalar slast = std::real(last.matrix()(0));
if(sfirst == slast) {
submatrix.local().setConstant(1, 1, sfirst);
submatrix.mapLocal();
} else if(slast - sfirst >= 0) {
long double n = floor(slast - sfirst) + 1;
if (n < 0 || n > EIGENLAB_MAXMATRIX)
throw std::runtime_error("Invalid matrix size requested '" + std::to_string(n) + "', set EIGENLAB_MAXMATRIX to allow larger matrices.");
submatrix.local().resize(1, n);
for(int k = 0; k < n; ++k)
submatrix.local()(0, k) = sfirst + k;
submatrix.mapLocal();
} else {
throw std::runtime_error("Invalid matrix definition '[" + str + "]'. Invalid range '" + cols[j] + "'.");
}
}
} else {
submatrix = eval(cols[j]);
}
if(j > 0 && size_t(submatrix.matrix().rows()) != nrows)
throw std::runtime_error("Invalid matrix definition '[" + str + "]'. Successive column entries '" + cols[int(j) - 1] + "' and '" + cols[j] + "' do not have the same number of rows.");
nrows = submatrix.matrix().rows();
ncols += submatrix.matrix().cols();
temp.resize(row0 + submatrix.matrix().rows());
for(size_t row = 0; row < size_t(submatrix.matrix().rows()); row++) {
temp[row0 + row].resize(col0 + submatrix.matrix().cols());
for(size_t col = 0; col < size_t(submatrix.matrix().cols()); col++)
temp[row0 + row][col0 + col] = submatrix.matrix()(row, col);
}
col0 += submatrix.matrix().cols();
}
if(row0 > 0 && ncols != temp[int(row0) - 1].size())
throw std::runtime_error("Invalid matrix definition '[" + str + "]'. Successive row entries '" + rows[int(i) - 1] + "' and '" + rows[i] + "' do not have the same number of columns.");
row0 += nrows;
}
nrows = temp.size();
//if(nrows == 0) return;
ncols = temp[0].size();
mat.setLocal(Derived(nrows, ncols));
for(size_t row = 0; row < nrows; row++) {
for(size_t col = 0; col < ncols; col++)
mat.matrix()(row, col) = temp[row][col];
}
mat.mapLocal();
}
template <typename Derived>
bool Parser<Derived>::evalFunction_1_lt(const std::string & name, Value<Derived> & arg, Value<Derived> & result, std::true_type)
{
if(arg.matrix().size()==0) {
result.setLocal(Derived());
return true;
} else if(name == "min") {
result.setLocal(arg.matrix().minCoeff());
return true;
} else if(name == "max") {
result.setLocal(arg.matrix().maxCoeff());
return true;
} else if(name == "absmax") {
typename Derived::Scalar minimum = arg.matrix().minCoeff();
typename Derived::Scalar maximum = arg.matrix().maxCoeff();
result.setLocal(std::abs(maximum) >= std::abs(minimum) ? maximum : minimum);
return true;
}
return false;
}
template <typename Derived>
bool Parser<Derived>::evalFunction_1_lt(const std::string &/*name*/, Value<Derived> &/*arg0*/, Value<Derived> &/*result*/, std::false_type)
{
return false;
}
template <typename Derived>
bool Parser<Derived>::evalFunction_2_lt(const std::string & name, Value<Derived> & arg0, Value<Derived> & arg1, Value<Derived> & result, std::true_type)
{
if(name == "min") {
if(arg1.matrix().size() != 1)
throw std::runtime_error("Invalid dimension argument for function '" + name + "(...)'.");
int dim = floor(std::real(arg1.matrix()(0, 0)));
if((dim != 0 && dim != 1) || dim != std::real(arg1.matrix()(0, 0)))
throw std::runtime_error("Invalid dimension argument for function '" + name + "(...)'.");
if(dim == 0) {
result.local() = arg0.matrix().colwise().minCoeff();
result.mapLocal();
return true;
} else if(dim == 1) {
result.local() = arg0.matrix().rowwise().minCoeff();
result.mapLocal();
return true;
}
} else if(name == "max") {
if(arg1.matrix().size() != 1)
throw std::runtime_error("Invalid dimension argument for function '" + name + "(...)'.");
int dim = floor(std::real(arg1.matrix()(0, 0)));
if((dim != 0 && dim != 1) || dim != std::real(arg1.matrix()(0, 0)))
throw std::runtime_error("Invalid dimension argument for function '" + name + "(...)'.");
if(dim == 0) {
result.local() = arg0.matrix().colwise().maxCoeff();
result.mapLocal();
return true;
} else if(dim == 1) {
result.local() = arg0.matrix().rowwise().maxCoeff();
result.mapLocal();
return true;
}
} else if(name == "absmax") {
if(arg1.matrix().size() != 1)
throw std::runtime_error("Invalid dimension argument for function '" + name + "(...)'.");
int dim = floor(std::real(arg1.matrix()(0, 0)));
if((dim != 0 && dim != 1) || dim != std::real(arg1.matrix()(0, 0)))
throw std::runtime_error("Invalid dimension argument for function '" + name + "(...)'.");
if(dim == 0) {
result.local() = arg0.matrix().colwise().maxCoeff();
result.mapLocal();
Derived minimum = arg0.matrix().colwise().minCoeff();
for(size_t i = 0; i < size_t(result.matrix().size()); i++) {
if(std::abs(result.matrix()(i)) < std::abs(minimum(i)))
result.matrix()(i) = minimum(i);
}
return true;
} else if(dim == 1) {
result.local() = arg0.matrix().rowwise().maxCoeff();
result.mapLocal();
Derived minimum = arg0.matrix().rowwise().minCoeff();
for(size_t i = 0; i < size_t(result.matrix().size()); i++) {
if(std::abs(result.matrix()(i)) < std::abs(minimum(i)))
result.matrix()(i) = minimum(i);
}
return true;
}
} else if (name == "cwiseMin") {
if (arg1.matrix().size() == 1) {
typename Derived::Scalar arg1scalar = arg1.matrix()(0, 0);
Derived arg1matrix = Derived::Constant(arg0.matrix().rows(), arg0.matrix().cols(), arg1scalar);
result.local() = arg0.matrix().cwiseMin(arg1matrix);
result.mapLocal();
return true;
} else if (arg0.matrix().cols() == arg1.matrix().cols() && arg0.matrix().rows() == arg1.matrix().rows()) {
result.local() = arg0.matrix().cwiseMin(arg1.matrix());
result.mapLocal();
return true;
} else {
throw std::runtime_error("Invalid dimension argument for function '" + name + "(...)'.");
}
} else if (name == "cwiseMax") {
if (arg1.matrix().size() == 1) {
typename Derived::Scalar arg1scalar = arg1.matrix()(0, 0);
Derived arg1matrix = Derived::Constant(arg0.matrix().rows(), arg0.matrix().cols(), arg1scalar);
result.local() = arg0.matrix().cwiseMax(arg1matrix);
result.mapLocal();
return true;
} else if (arg0.matrix().cols() == arg1.matrix().cols() && arg0.matrix().rows() == arg1.matrix().rows()) {
result.local() = arg0.matrix().cwiseMax(arg1.matrix());
result.mapLocal();
return true;
} else {
throw std::runtime_error("Invalid dimension argument for function '" + name + "(...)'.");
}
}
return false;
}
template <typename Derived>
bool Parser<Derived>::evalFunction_2_lt(const std::string &/*name*/, Value<Derived> &/*arg0*/, Value<Derived> &/*arg1*/, Value<Derived> &/*result*/, std::false_type)
{
return false;
}
template <typename Derived>
void Parser<Derived>::evalFunction(const std::string & name, std::vector<std::string> & args, Value<Derived> & result)
{
if(args.size() == 1) {
Value<Derived> arg = eval(args[0]);
if(name == "abs") {
result.local() = arg.matrix().array().abs().template cast<typename Derived::Scalar>();
result.mapLocal();
return;
} else if(name == "sqrt") {
result.local() = arg.matrix().array().sqrt();
result.mapLocal();
return;
} else if(name == "exp") {
result.local() = arg.matrix().array().exp();
result.mapLocal();
return;
} else if(name == "log") {
result.local() = arg.matrix().array().log();
result.mapLocal();
return;
} else if(name == "log10") {
result.local() = arg.matrix().array().log();
result.local() *= (1.0 / log(10));
result.mapLocal();
return;
} else if(name == "sin") {
result.local() = arg.matrix().array().sin();
result.mapLocal();
return;
} else if(name == "cos") {
result.local() = arg.matrix().array().cos();
result.mapLocal();
return;
} else if(name == "tan") {
result.local() = arg.matrix().array().tan();
result.mapLocal();
return;
} else if(name == "acos") {
result.local() = arg.matrix().array().acos();
result.mapLocal();
return;
} else if(name == "asin") {
result.local() = arg.matrix().array().asin();
result.mapLocal();
return;
} else if(name == "trace") {
result.setLocal(arg.matrix().trace());
return;
} else if(name == "norm") {
result.setLocal(arg.matrix().norm());
return;
} else if (evalFunction_1_lt(name, arg, result, has_operator_lt<typename Derived::Scalar>())) {
return;
} else if(name == "mean") {
result.setLocal(arg.matrix().mean());
return;
} else if(name == "sum") {
result.setLocal(arg.matrix().sum());
return;
} else if(name == "prod") {
result.setLocal(arg.matrix().prod());
return;
} else if(name == "transpose") {
result.local() = arg.matrix().transpose();
result.mapLocal();
return;
} else if(name == "conjugate") {
result.local() = arg.matrix().conjugate();
result.mapLocal();
return;
} else if(name == "adjoint") {
result.local() = arg.matrix().adjoint();
result.mapLocal();
return;
} else if(name == "zeros") {
if(arg.matrix().size() != 1)
throw std::runtime_error("Invalid dimension argument for function '" + name + "(" + args[0] + ")'.");
long double N = floor(std::real(arg.matrix()(0, 0)));
if(N < 0 || N != std::real(arg.matrix()(0, 0)))
throw std::runtime_error("Invalid dimension argument for function '" + name + "(" + args[0] + ")'.");
if (N*N > EIGENLAB_MAXMATRIX)
throw std::runtime_error("Invalid matrix size requested '" + std::to_string(N) + "^2' set EIGENLAB_MAXMATRIX to allow larger matrices.");
result.local() = Derived::Zero(N, N);
result.mapLocal();
return;
} else if(name == "ones") {
if(arg.matrix().size() != 1)
throw std::runtime_error("Invalid dimension argument for function '" + name + "(" + args[0] + ")'.");
long double N = floor(std::real(arg.matrix()(0, 0)));
if(N < 0 || N != std::real(arg.matrix()(0, 0)))
throw std::runtime_error("Invalid dimension argument for function '" + name + "(" + args[0] + ")'.");
if (N*N > EIGENLAB_MAXMATRIX)
throw std::runtime_error("Invalid matrix size requested '" + std::to_string(N) + "^2' set EIGENLAB_MAXMATRIX to allow larger matrices.");
result.local() = Derived::Ones(N, N);
result.mapLocal();
return;
} else if(name == "eye") {
if(arg.matrix().size() != 1)
throw std::runtime_error("Invalid dimension argument for function '" + name + "(" + args[0] + ")'.");
long double N = floor(std::real(arg.matrix()(0, 0)));
if(N < 0 || N != std::real(arg.matrix()(0, 0)))
throw std::runtime_error("Invalid dimension argument for function '" + name + "(" + args[0] + ")'.");
if (N*N > EIGENLAB_MAXMATRIX)
throw std::runtime_error("Invalid matrix size requested '" + std::to_string(N) + "^2' set EIGENLAB_MAXMATRIX to allow larger matrices.");
result.local() = Derived::Identity(N, N);
result.mapLocal();
return;
}
else {
throw std::runtime_error("Invalid function '" + name + "(" + args[0] + ")'.");
}
} else if(args.size() == 2) {
Value<Derived> arg0 = eval(args[0]);
Value<Derived> arg1 = eval(args[1]);
if(name == "size") {
if(arg1.matrix().size() != 1)
throw std::runtime_error("Invalid dimension argument for function '" + name + "(" + args[0] + "," + args[1] + ")'.");
int dim = floor(std::real(arg1.matrix()(0, 0)));
if((dim != 0 && dim != 1) || dim != std::real(arg1.matrix()(0, 0)))
throw std::runtime_error("Invalid dimension argument for function '" + name + "(" + args[0] + "," + args[1] + ")'.");
if(dim == 0) {
result.setLocal((typename Derived::Scalar) arg0.matrix().rows());
return;
} else if(dim == 1) {
result.setLocal((typename Derived::Scalar) arg0.matrix().cols());
return;
}
} else if (evalFunction_2_lt(name, arg0, arg1, result, has_operator_lt<typename Derived::Scalar>())) {
return;
} else if(name == "mean") {
if(arg1.matrix().size() != 1)
throw std::runtime_error("Invalid dimension argument for function '" + name + "(" + args[0] + "," + args[1] + ")'.");
int dim = floor(std::real(arg1.matrix()(0, 0)));
if((dim != 0 && dim != 1) || dim != std::real(arg1.matrix()(0, 0)))
throw std::runtime_error("Invalid dimension argument for function '" + name + "(" + args[0] + "," + args[1] + ")'.");
if(dim == 0) {
result.local() = arg0.matrix().colwise().mean();
result.mapLocal();
return;
} else if(dim == 1) {
result.local() = arg0.matrix().rowwise().mean();
result.mapLocal();
return;
}
} else if(name == "sum") {
if(arg1.matrix().size() != 1)
throw std::runtime_error("Invalid dimension argument for function '" + name + "(" + args[0] + "," + args[1] + ")'.");
int dim = floor(std::real(arg1.matrix()(0, 0)));
if((dim != 0 && dim != 1) || dim != std::real(arg1.matrix()(0, 0)))
throw std::runtime_error("Invalid dimension argument for function '" + name + "(" + args[0] + "," + args[1] + ")'.");
if(dim == 0) {
result.local() = arg0.matrix().colwise().sum();
result.mapLocal();
return;
} else if(dim == 1) {
result.local() = arg0.matrix().rowwise().sum();
result.mapLocal();
return;
}
} else if(name == "prod") {
if(arg1.matrix().size() != 1)
throw std::runtime_error("Invalid dimension argument for function '" + name + "(" + args[0] + "," + args[1] + ")'.");
int dim = floor(std::real(arg1.matrix()(0, 0)));
if((dim != 0 && dim != 1) || dim != std::real(arg1.matrix()(0, 0)))
throw std::runtime_error("Invalid dimension argument for function '" + name + "(" + args[0] + "," + args[1] + ")'.");
if(dim == 0) {
result.local() = arg0.matrix().colwise().prod();
result.mapLocal();
return;
} else if(dim == 1) {
result.local() = arg0.matrix().rowwise().prod();
result.mapLocal();
return;
}
} else if(name == "zeros") {
if((arg0.matrix().size() != 1) || (arg1.matrix().size() != 1))
throw std::runtime_error("Invalid dimension arguments for function '" + name + "(" + args[0] + "," + args[1] + ")'.");
long int rows = floor(std::real(arg0.matrix()(0, 0)));
long int cols = floor(std::real(arg1.matrix()(0, 0)));
if(rows < 0 || cols < 0 || rows != std::real(arg0.matrix()(0, 0)) || cols != std::real(arg1.matrix()(0, 0)) || (long double)rows*cols > EIGENLAB_MAXMATRIX)
throw std::runtime_error("Invalid dimension arguments for function '" + name + "(" + args[0] + "," + args[1] + ")'.");
result.local() = Derived::Zero(rows, cols);