-
Notifications
You must be signed in to change notification settings - Fork 1
/
Qlib.bas
2750 lines (2544 loc) · 95.9 KB
/
Qlib.bas
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
'*******************************************************************
' Q - A MATLAB-like matrix parser for Microsoft Excel
'
' Q features a single public function, Q(), containing an expression parser.
' Q() is able to parse and evaluate a subset of the MATLAB programming language.
' It features almost all MATLAB operators, selected standard functions
' and has complete support for submatrices, '()', and concatenation, '[]'.
'
' Example usage:
' - =Q("2+2") -> 4
' - =Q("A+B+C",3,4,5) -> 12
' - =Q("eye(3)") -> the 3x3 identity matrix
' - =Q("mean(A)",A1:D5) -> vector with the mean of each column in cells A1:D5
' - =Q("A.*B",A1:D5,F1:I5) -> element wise multiplication of cells A1:D5 and F1:I5
' - =Q("A([1 3],end)",A1:D5) -> get the last entries in row 1 and 3 of cells A1:D5
' - =Q("sort(A)",A1:D5) -> sort each column of cells A1:D5
' - =Q("3+4;ans^2") -> 49
' Multiple expressions are separated by ";" or linebreak.
' "ans" returns the last result and the very last
' result is then returned by Q().
'
' Features:
' - All standard MATLAB operators: :,::,+,-,*,/,.*,./,^,.^,||,&&,|,&,<,<=,>,>=,==,~=,~,'
' - Most used MATLAB functions: eye,zeros,ones,sum,cumsum,cumprod,prod,mean,median,corr,
' cov,prctile,std,isequal,fix,rand,randn,repmat,find,sqrt,exp,sort and many more...
' - Indexing via A(2,:) or A(5,3:end)
' - Concatenate matrices with '[]', i.e. [ A B; C D]
' - Multiple expressions separated by ";" or a linebreak.
' The variable ans contains the result of the previous expression
' - Excel functions: if,iferror
' - Prefix function calls with ! to call external VBA functions not found in Q.
'
' For the newest version, go to:
' http://github.com/nielsls/Q
'
' 2017, Niels Lykke Sørensen
Option Explicit
Option Base 1
Private Const version = "2.21"
Private Const NUMERICS = "0123456789"
Private Const ALPHAS = "abcdefghijklmnopqrstuvwxyz"
Private Const SINGLE_OPS = "()[],;:+-#'"
Private Const COMBO_OPS = ".|&<>~=*/^!"
Private Const DOUBLE_MAX = 1.79769313486231E+308
Private Const DOUBLE_MIN = -1.79769313486231E+308
Private expression As String
Private expressionIndex As Long
Private currentToken As String
Private previousTokenIsSpace As Boolean
Private arguments As Variant
Private endValues As Variant ' A stack of numbers providing the right value of the "end" constant
Private ans As Variant ' Result of last answer when multiple expressions are used as input
' Entry point - the only public function in the library
Public Function Q(expr As Variant, ParamArray args() As Variant) As Variant
On Error GoTo ErrorHandler
expression = expr
arguments = args
endValues = Empty
ans = Empty
expressionIndex = 1
Tokens_Next ' Find first token in input string
Dim root As Variant
While currentToken <> ""
If currentToken = ";" Or currentToken = vbLf Then
Tokens_Next
Else
root = Parse_Binary()
'Utils_DumpTree root 'Uncomment for debugging
ans = calc_tree(root)
Utils_Assert _
currentToken = "" Or currentToken = ";" Or currentToken = vbLf, _
"'" & currentToken & "' not allowed here"
End If
Wend
Select Case Utils_Numel(ans)
Case 0
'If an empty matrix is returned from Q() and
'used in a cell it must be converted to #N/A
'to avoid being converted to 0.
If Utils_WasCalledFromCell() Then Q = [NA()]
Case 1
Q = ans(1, 1)
Case Else
Q = ans
End Select
Exit Function
ErrorHandler:
' If Q was called from cell, fail silently with an error msg.
' Else, raise a new error.
Utils_Assert _
Utils_WasCalledFromCell(), _
Err.Description & " in """ & expression & """"
Q = "ERROR - " & Err.Description
End Function
Private Function Utils_WasCalledFromCell() As Boolean
Utils_WasCalledFromCell = TypeName(Application.Caller) <> "Error"
End Function
'*******************************************************************
' Evaluator invariants:
' - All variables, including scalars, are represented internally
' as 2-dimensional matrices
' - All matrices are 1-based just as in MATLAB.
' - Variable names: [A-Z]
' - Function names: [a-z][a-z0-9_]*
' - Numbers support e/E exponent
' - The empty matrix/scalar [] has per definition 0 rows, 0 cols,
' dimension 0 and is internally represented by the default
' Variant value Empty
' Missing parameters in function calls are given the value Empty
'*******************************************************************
'*********************
'*** TOKEN CONTROL ***
'*********************
Private Sub Tokens_Next()
previousTokenIsSpace = Tokens_MoveCharPointer(" ")
If expressionIndex > Len(expression) Then currentToken = "": Exit Sub
Dim startIndex As Long: startIndex = expressionIndex
Select Case Asc(Mid(expression, expressionIndex, 1))
Case Asc("A") To Asc("Z")
expressionIndex = expressionIndex + 1
Case Asc("a") To Asc("z")
Tokens_MoveCharPointer NUMERICS & ALPHAS & "_"
Case Asc("0") To Asc("9")
Tokens_MoveCharPointer NUMERICS
If Tokens_MoveCharPointer(".", False, True) Then
Tokens_MoveCharPointer NUMERICS
End If
If Tokens_MoveCharPointer("eE", False, True) Then
Tokens_MoveCharPointer NUMERICS & "-", False, True
Tokens_MoveCharPointer NUMERICS
End If
Case Asc("""")
expressionIndex = expressionIndex + 1
Tokens_MoveCharPointer """", True
Utils_Assert expressionIndex <= Len(expression), "missing '""'"
expressionIndex = expressionIndex + 1
Case Asc(vbLf) 'New line
expressionIndex = expressionIndex + 1
Case Else
If Not Tokens_MoveCharPointer(SINGLE_OPS, False, True) Then
Tokens_MoveCharPointer COMBO_OPS
End If
End Select
currentToken = Mid(expression, startIndex, expressionIndex - startIndex)
Utils_Assert expressionIndex > startIndex Or expressionIndex > Len(expression), _
"Illegal char: " & Mid(expression, expressionIndex, 1)
End Sub
Private Sub Tokens_AssertAndNext(Token As String)
Utils_Assert Token = currentToken, "missing token: " & Token
Tokens_Next
End Sub
Private Function Tokens_MoveCharPointer(str As String, _
Optional stopWhenFound As Boolean = False, _
Optional singleCharOnly As Boolean = False) As Boolean
While expressionIndex <= Len(expression) _
And stopWhenFound <> (InStr(str, Mid(expression, expressionIndex, 1)) > 0)
expressionIndex = expressionIndex + 1
Tokens_MoveCharPointer = True
If singleCharOnly Then Exit Function
Wend
End Function
'Returns true if token is a suitable operator
Private Function Parse_FindBinaryOp(Token As String, ByRef op As Variant) As Boolean
Parse_FindBinaryOp = True
Select Case Token
'op = Array( <function name>, <precedence level>, <left associative> )
Case "||": op = Array("orshortcircuit", 1, True)
Case "&&": op = Array("andshortcircuit", 2, True)
Case "|": op = Array("or", 3, True)
Case "&": op = Array("and", 4, True)
Case "<": op = Array("lt", 5, True)
Case "<=": op = Array("lte", 5, True)
Case ">": op = Array("gt", 5, True)
Case ">=": op = Array("gte", 5, True)
Case "==": op = Array("eq", 5, True)
Case "=": op = Array("eq", 5, True)
Case "~=": op = Array("ne", 5, True)
Case "<>": op = Array("ne", 5, True)
Case ":": op = Array("colon", 6, False)
Case "+": op = Array("plus", 7, True)
Case "-": op = Array("minus", 7, True)
Case "*": op = Array("mtimes", 8, True)
Case ".*": op = Array("times", 8, True)
Case "/": op = Array("mdivide", 8, True)
Case "./": op = Array("divide", 8, True)
Case "^": op = Array("mpower", 9, True)
Case ".^": op = Array("power", 9, True)
Case Else: Parse_FindBinaryOp = False
End Select
End Function
Private Function Parse_FindUnaryPrefixOp(Token As String, ByRef op As Variant) As Boolean
Parse_FindUnaryPrefixOp = True
Select Case Token
Case "+": op = "uplus"
Case "-": op = "uminus"
Case "~": op = "negate"
Case "#": op = "numel"
Case "!": op = "extern"
Case Else: Parse_FindUnaryPrefixOp = False
End Select
End Function
Private Function Parse_FindUnaryPostfixOp(Token As String, ByRef op As Variant) As Boolean
Parse_FindUnaryPostfixOp = True
Select Case Token
Case "'": op = "transpose"
Case Else: Parse_FindUnaryPostfixOp = False
End Select
End Function
Private Function Parse_Matrix() As Variant
While currentToken <> "]"
Utils_Stack_Push Array("fn_hcat", Parse_List(True)), Parse_Matrix
If currentToken = ";" Then Tokens_Next
Utils_Assert currentToken <> "", "Missing ']'"
Wend
End Function
Private Function Parse_List(Optional isSpaceSeparator As Boolean = False) As Variant
Do While InStr(";)]", currentToken) = 0
If currentToken = "," Then
Utils_Stack_Push Array("eval_constant", Empty), Parse_List
Else
Utils_Stack_Push Parse_Binary(), Parse_List
End If
If currentToken = "," Then
Tokens_Next
ElseIf Not (previousTokenIsSpace And isSpaceSeparator) Then
Exit Do
End If
Loop
End Function
Private Function Parse_Binary(Optional lastPrec As Long = -999) As Variant
Parse_Binary = Parse_Prefix()
Dim op: Do While Parse_FindBinaryOp(currentToken, op)
If op(2) + CLng(op(3)) < lastPrec Then Exit Do
Tokens_Next
Parse_Binary = Array("op_" & op(1), Array(Parse_Binary, Parse_Binary(CLng(op(2)))))
Loop
End Function
Private Function Parse_Prefix() As Variant
Dim op
If Parse_FindUnaryPrefixOp(currentToken, op) Then
Tokens_Next
Parse_Prefix = Array("op_" & op, Array(Parse_Prefix()))
Else
Parse_Prefix = Parse_Postfix()
End If
End Function
Private Function Parse_Postfix() As Variant
Parse_Postfix = Parse_Atomic()
Dim op: Do
If Parse_FindUnaryPostfixOp(currentToken, op) Then
Tokens_Next
Parse_Postfix = Array("op_" & op, Array(Parse_Postfix))
ElseIf currentToken = "(" Then
Tokens_Next
Parse_Postfix = Array("op_index", Array(Parse_Postfix, Parse_List()))
Tokens_AssertAndNext ")"
Else
Exit Do
End If
Loop While True
End Function
Private Function Parse_Atomic() As Variant
Utils_Assert currentToken <> "", "missing argument"
Select Case Asc(currentToken) ' Filter on first char of token
Case Asc("(")
Tokens_Next
Parse_Atomic = Parse_Binary()
Tokens_AssertAndNext ")"
Case Asc(":")
Parse_Atomic = Array("eval_colon")
Tokens_Next
Case Asc("0") To Asc("9") ' Found a numeric constant
Parse_Atomic = Array("eval_constant", Utils_ToMatrix(val(currentToken)))
Tokens_Next
Case Asc("A") To Asc("Z") ' Found an input variable
Parse_Atomic = Array("eval_variable", Asc(currentToken) - Asc("A"))
Tokens_Next
Case Asc("a") To Asc("z")
If currentToken = "end" Then
Parse_Atomic = Array("eval_end")
Tokens_Next
ElseIf currentToken = "ans" Then
Parse_Atomic = Array("eval_ans")
Tokens_Next
Else ' Found a function call
Parse_Atomic = "fn_" & currentToken
Tokens_Next
If currentToken = "(" Then
Tokens_AssertAndNext "("
Parse_Atomic = Array(Parse_Atomic, Parse_List())
Tokens_AssertAndNext ")"
Else
Parse_Atomic = Array(Parse_Atomic, Empty)
End If
End If
Case Asc("[") ' Found a matrix concatenation
Tokens_Next
Parse_Atomic = Array("fn_vcat", Parse_Matrix())
Tokens_AssertAndNext "]"
Case Asc("""") ' Found a string constant
Parse_Atomic = Array("eval_constant", Utils_ToMatrix(Mid(currentToken, 2, Len(currentToken) - 2)))
Tokens_Next
Case Else
Utils_Fail "unexpected token: " & currentToken
End Select
End Function
'*************
'*** UTILS ***
'*************
Private Function MAX(a As Variant, b As Variant) As Variant
If a > b Then MAX = a Else MAX = b
End Function
Private Function MIN(a As Variant, b As Variant) As Variant
If a < b Then MIN = a Else MIN = b
End Function
Private Function IFF(expr As Boolean, alt1 As Variant, alt2 As Variant) As Variant
If expr Then IFF = alt1 Else IFF = alt2
End Function
Private Sub Utils_DumpTree(tree As Variant, Optional spacer As String = "")
If Utils_Dimensions(tree) > 0 Then
Dim leaf: For Each leaf In tree
Utils_DumpTree leaf, spacer & " "
Next leaf
Else
Debug.Print spacer & tree
End If
End Sub
Private Function Utils_Dimensions(v As Variant) As Long
Dim dimnum As Long, errorCheck As Integer
On Error GoTo FinalDimension
For dimnum = 1 To 60000
errorCheck = LBound(v, dimnum)
Next
FinalDimension:
Utils_Dimensions = dimnum - 1
End Function
Private Function Utils_Numel(v As Variant) As Long
If Not IsEmpty(v) Then Utils_Numel = UBound(v, 1) * UBound(v, 2)
End Function
Private Function Utils_Rows(ByRef v As Variant) As Long
If Not IsEmpty(v) Then Utils_Rows = UBound(v, 1)
End Function
Private Function Utils_Cols(ByRef v As Variant) As Long
If Not IsEmpty(v) Then Utils_Cols = UBound(v, 2)
End Function
Private Sub Utils_Size(v As Variant, ByRef r As Variant, ByRef c As Variant)
If IsEmpty(v) Then
r = 0
c = 0
Else
r = UBound(v, 1)
c = UBound(v, 2)
End If
End Sub
' From linear index to subscripts in a column-major matrix
Private Sub Utils_Ind2Sub(rows As Long, ind As Long, ByRef i As Long, ByRef j As Long)
j = (ind - 1) \ rows + 1
i = ind - rows * (j - 1)
End Sub
Private Function Utils_ToMatrix(val As Variant) As Variant
Utils_ToMatrix = val
Utils_Conform Utils_ToMatrix
End Function
' Makes sure that a scalar is transformed to a 1x1 matrix
' and a 1-dim vector is transformed to a 2-dim vector of size 1xN
Private Sub Utils_Conform(ByRef v As Variant)
If IsEmpty(v) Then Exit Sub
Dim r
Select Case Utils_Dimensions(v)
Case 0:
ReDim r(1, 1)
r(1, 1) = v
v = r
Case 1:
ReDim r(1, UBound(v))
Dim i As Long
For i = 1 To UBound(r, 2)
r(1, i) = v(i)
Next i
v = r
Case Is > 2:
Utils_Fail "dimension > 2"
End Select
End Sub
Private Sub Utils_Stack_Push(item As Variant, stack As Variant)
On Error GoTo NotInitiated
ReDim Preserve stack(LBound(stack) To UBound(stack) + 1)
stack(UBound(stack)) = item
Exit Sub
NotInitiated:
stack = Array(item)
End Sub
Private Function Utils_Stack_Pop(stack As Variant) As Variant
Dim ub As Long: ub = UBound(stack)
Dim lb As Long: lb = LBound(stack)
Utils_Stack_Pop = stack(ub)
If ub > lb Then ReDim Preserve stack(lb To ub - 1) Else stack = Null
End Function
Private Function Utils_Stack_Peek(stack As Variant) As Variant
Utils_Stack_Peek = stack(UBound(stack))
End Function
Private Function Utils_Stack_Size(stack As Variant) As Long
On Error Resume Next
Utils_Stack_Size = UBound(stack)
End Function
Private Function Utils_RepScalar(ByRef out As Variant, val As Variant, n As Long, m As Long) As Variant
Utils_Assert n >= 0 And m >= 0, "cannot create matrix with negative size"
If n = 0 Or m = 0 Then Exit Function
ReDim out(n, m)
For n = 1 To UBound(out, 1)
For m = 1 To UBound(out, 2)
out(n, m) = val
Next m
Next n
End Function
' Transforms all entries in the vector from trees to values
Private Sub Utils_CalcArgs(args As Variant)
Dim i As Long: For i = 1 To Utils_Stack_Size(args)
args(i) = calc_tree(args(i))
Next i
End Sub
' Test if a flag was supplied in the args, i.e. such as "descend" in the sort function
Private Function Utils_IsFlagSet(args As Variant, flag As String) As Boolean
Dim i As Long
For i = UBound(args) To 1 Step -1
If StrComp(TypeName(args(i)(1, 1)), "String") = 0 Then
If StrComp(args(i)(1, 1), flag, vbTextCompare) = 0 Then
Utils_IsFlagSet = True
Exit Function
End If
End If
Next i
End Function
'do cols -> return 0, do rows -> return 1
Private Function Utils_CalcDimDirection(args As Variant, Optional dimIndex As Long = 2) As Long
If UBound(args) >= dimIndex Then
If IsNumeric(args(dimIndex)(1, 1)) Then
Utils_CalcDimDirection = args(dimIndex)(1, 1) - 1
Exit Function
End If
End If
Utils_CalcDimDirection = -(Utils_Rows(args(1)) = 1)
End Function
' Returns the size of the return matrix in functions like zeros, rand, repmat, ...
' Size must be last in the args and can be either nothing, 1 scalar, 2 scalars or a vector with two scalars
Private Function Utils_GetSizeFromArgs(args As Variant, ByRef n As Long, ByRef m As Long, Optional index As Long = 2)
Select Case Utils_Stack_Size(args)
Case Is < index
n = 1: m = 1
Case Is = index
Select Case Utils_Numel(args(index))
Case 1
n = args(index)(1, 1)
m = n
Case 2
n = args(index)(1, 1)
m = args(index)(MIN(2, UBound(args(index), 1)), MIN(2, UBound(args(index), 2)))
Case Else
Utils_Fail "bad size input"
End Select
Case Is = index + 1
n = args(index)(1, 1)
m = args(index + 1)(1, 1)
Case Else
Utils_Fail "bad size input"
End Select
End Function
' Easy way of obtaining the value of an optional argument
Private Function Utils_GetOptionalScalarArg(args As Variant, index As Long, defaultValue As Variant) As Variant
If index <= Utils_Stack_Size(args) Then
If IsEmpty(args(index)) Then
Utils_GetOptionalScalarArg = Empty
Else
Utils_GetOptionalScalarArg = args(index)(1, 1)
End If
Else
Utils_GetOptionalScalarArg = defaultValue
End If
End Function
' Do the initial calculations that are the same for every binary operation
' Broadcasting is done, st. a matrix with size (n,m) will match all
' matrices with size (1,1), (1,m), (n,1) or (n,m).
Private Function Utils_SetupBinaryOperation( _
args As Variant, out As Variant, _
ByRef r As Long, ByRef c As Long, _
ByRef arg1_r As Long, ByRef arg1_c As Long, _
ByRef arg2_r As Long, ByRef arg2_c As Long, _
Optional preCalcArgs As Boolean = True) As Variant
If preCalcArgs Then Utils_CalcArgs args
Utils_Size args(1), arg1_r, arg1_c
Utils_Size args(2), arg2_r, arg2_c
Utils_Assert _
(arg1_r = 1 Or arg2_r = 1 Or arg1_r = arg2_r) And (arg1_c = 1 Or arg2_c = 1 Or arg1_c = arg2_c), _
"dimension mismatch"
If arg1_r > 0 And arg2_r > 0 Then
r = MAX(arg1_r, arg2_r)
c = MAX(arg1_c, arg2_c)
ReDim out(r, c)
Else
r = 0: c = 0
End If
End Function
' Do the initial processing for operations which reduce the dimension of a matrix.
' These includes sum, prod, mean, any, all, count etc...
Private Sub Utils_SetupReducedDimOperation(ByRef args As Variant, ByRef mat As Variant, ByRef x As Long, Optional dimIndex As Long = 2)
x = Utils_CalcDimDirection(args, dimIndex)
ReDim mat(x * UBound(args(1), 1) + (1 - x), (1 - x) * UBound(args(1), 2) + x)
End Sub
' Is called from each Q function to ensure the given function has
' has been called with the right number of arguments
Private Sub Utils_AssertArgsCount(args As Variant, lb As Long, ub As Long)
Dim size As Long: size = Utils_Stack_Size(args)
Utils_Assert size >= lb, "too few arguments"
Utils_Assert size <= ub, "too many arguments"
End Sub
' Allows each Q function to fail gracefully with a nice error message.
Private Sub Utils_Assert(expr As Boolean, Optional msg As String = "unknown error")
If expr Then Exit Sub
Err.Raise 999, , msg
End Sub
Private Sub Utils_Fail(msg As String)
Utils_Assert False, msg
End Sub
'*****************
'*** CALC ROOT ***
'*****************
' calc_tree is responsible for turning the
' abstract syntax tree (AST) into an actual
' result.
' It does this by recursively calling the
' different functions and operators needed.
'
' Branches of "select case" statements are
' used to determine which function to call.
' A more elegant solution would be to just
' invoke Application.Run().
' However, Application.Run is not feasible
' as it is both slow and fucks up error
' propagation.
Private Function calc_tree(root As Variant) As Variant
Dim prefix As String, name As String
root(1) = Split(root(1), "_")
prefix = root(1)(0)
name = root(1)(1)
Select Case prefix
' Non-functions
Case "eval":
Select Case name
Case "constant":
calc_tree = root(2)
Case "variable":
Utils_Assert root(2) <= UBound(arguments), "variable '" & Chr(Asc("A") + root(2)) & "' not found."
calc_tree = CVar(arguments(root(2)))
Utils_Conform calc_tree
Case "end":
Utils_Assert Utils_Stack_Size(endValues) > 0, """end"" not allowed here."
calc_tree = Utils_ToMatrix(Utils_Stack_Peek(endValues))
Case "ans":
calc_tree = ans
Case "colon":
Utils_Fail "colon not allowed here"
End Select
' Operators
Case "op"
Select Case name
Case "and": calc_tree = op_and(root(2))
Case "andshortcircuit": calc_tree = op_andshortcircuit(root(2))
Case "colon": calc_tree = op_colon(root(2))
Case "divide": calc_tree = op_divide(root(2))
Case "eq": calc_tree = op_eq(root(2))
Case "extern": calc_tree = op_extern(root(2))
Case "gt": calc_tree = op_gt(root(2))
Case "gte": calc_tree = op_gte(root(2))
Case "index": calc_tree = op_index(root(2))
Case "lt": calc_tree = op_lt(root(2))
Case "lte": calc_tree = op_lte(root(2))
Case "minus": calc_tree = op_minus(root(2))
Case "mdivide": calc_tree = op_mdivide(root(2))
Case "mpower": calc_tree = op_mpower(root(2))
Case "mtimes": calc_tree = op_mtimes(root(2))
Case "ne": calc_tree = op_ne(root(2))
Case "negate": calc_tree = op_negate(root(2))
Case "numel": calc_tree = op_numel(root(2))
Case "or": calc_tree = op_or(root(2))
Case "orshortcircuit": calc_tree = op_orshortcircuit(root(2))
Case "plus": calc_tree = op_plus(root(2))
Case "power": calc_tree = op_power(root(2))
Case "times": calc_tree = op_times(root(2))
Case "transpose": calc_tree = op_transpose(root(2))
Case "uplus": calc_tree = op_uplus(root(2))
Case "uminus": calc_tree = op_uminus(root(2))
End Select
' Functions
Case "fn"
If name <> "if" And name <> "iferror" And name <> "expand" Then Utils_CalcArgs root(2)
Select Case name
Case "all": calc_tree = fn_all(root(2))
Case "any": calc_tree = fn_any(root(2))
Case "arrayfun": calc_tree = fn_arrayfun(root(2))
Case "binom": calc_tree = fn_binom(root(2))
Case "ceil": calc_tree = fn_ceil(root(2))
Case "cols": calc_tree = fn_cols(root(2))
Case "corr": calc_tree = fn_corr(root(2))
Case "count": calc_tree = fn_count(root(2))
Case "counta": calc_tree = fn_counta(root(2))
Case "cov": calc_tree = fn_cov(root(2))
Case "cummax": calc_tree = fn_cummax(root(2))
Case "cummin": calc_tree = fn_cummin(root(2))
Case "cumprod": calc_tree = fn_cumprod(root(2))
Case "cumsum": calc_tree = fn_cumsum(root(2))
Case "diag": calc_tree = fn_diag(root(2))
Case "diff": calc_tree = fn_diff(root(2))
Case "droperror": calc_tree = fn_droperror(root(2))
Case "e": calc_tree = fn_e(root(2))
Case "exp": calc_tree = fn_exp(root(2))
Case "expand": calc_tree = fn_expand(root(2))
Case "eye": calc_tree = fn_eye(root(2))
Case "fact": calc_tree = fn_fact(root(2))
Case "false": calc_tree = fn_false(root(2))
Case "find": calc_tree = fn_find(root(2))
Case "fix": calc_tree = fn_fix(root(2))
Case "floor": calc_tree = fn_floor(root(2))
Case "hcat": calc_tree = fn_hcat(root(2))
Case "if": calc_tree = fn_if(root(2))
Case "iferror": calc_tree = fn_iferror(root(2))
Case "inv": calc_tree = fn_inv(root(2))
Case "isempty": calc_tree = fn_isempty(root(2))
Case "isequal": calc_tree = fn_isequal(root(2))
Case "iserror": calc_tree = fn_iserror(root(2))
Case "islogical": calc_tree = fn_islogical(root(2))
Case "isnum": calc_tree = fn_isnum(root(2))
Case "join": calc_tree = fn_join(root(2))
Case "linspace": calc_tree = fn_linspace(root(2))
Case "log": calc_tree = fn_log(root(2))
Case "match": calc_tree = fn_match(root(2))
Case "max": calc_tree = fn_max(root(2))
Case "mean": calc_tree = fn_mean(root(2))
Case "median": calc_tree = fn_median(root(2))
Case "min": calc_tree = fn_min(root(2))
Case "normcdf": calc_tree = fn_normcdf(root(2))
Case "numel": calc_tree = fn_numel(root(2))
Case "ones": calc_tree = fn_ones(root(2))
Case "percentrank": calc_tree = fn_percentrank(root(2))
Case "pi": calc_tree = fn_pi(root(2))
Case "prctile": calc_tree = fn_prctile(root(2))
Case "prod": calc_tree = fn_prod(root(2))
Case "rand": calc_tree = fn_rand(root(2))
Case "randi": calc_tree = fn_randi(root(2))
Case "randn": calc_tree = fn_randn(root(2))
Case "repmat": calc_tree = fn_repmat(root(2))
Case "ret2tick": calc_tree = fn_ret2tick(root(2))
Case "reshape": calc_tree = fn_reshape(root(2))
Case "round": calc_tree = fn_round(root(2))
Case "rows": calc_tree = fn_rows(root(2))
Case "size": calc_tree = fn_size(root(2))
Case "sort": calc_tree = fn_sort(root(2))
Case "sorttable": calc_tree = fn_sorttable(root(2))
Case "sqrt": calc_tree = fn_sqrt(root(2))
Case "std": calc_tree = fn_std(root(2))
Case "sum": calc_tree = fn_sum(root(2))
Case "tick2ret": calc_tree = fn_tick2ret(root(2))
Case "tostring": calc_tree = fn_tostring(root(2))
Case "true": calc_tree = fn_true(root(2))
Case "unique": calc_tree = fn_unique(root(2))
Case "var": calc_tree = fn_var(root(2))
Case "vcat": calc_tree = fn_vcat(root(2))
Case "version": calc_tree = fn_version(root(2))
Case "xor": calc_tree = fn_xor(root(2))
Case "zeros": calc_tree = fn_zeros(root(2))
Case Else:
Utils_Assert _
False, _
"unknown function """ & name & """" _
& IFF(Len(name) = 1, "; did you mean variable " & UCase(name) & "?", "")
End Select
End Select
End Function
'*****************
'*** OPERATORS ***
'*****************
Private Function Utils_IsVectorShape(r As Long, c As Long) As Boolean
Utils_IsVectorShape = (r = 1 And c > 1) Or (r > 1 And c = 1)
End Function
Private Sub op_indexarg(root As Variant, endValue As Long, ByRef idx As Variant, ByRef r As Long, ByRef c As Long, ByRef t As Long)
If root(1) = "eval_colon" Then
t = 1
r = endValue
c = 1
ElseIf root(1) = "op_colon" Then
t = 2
ReDim idx(3)
Utils_Stack_Push endValue, endValues
idx(1) = calc_tree(root(2)(1))(1, 1)
If root(2)(2)(1) <> "op_colon" Then
idx(2) = 1
idx(3) = calc_tree(root(2)(2))(1, 1)
Else
idx(2) = calc_tree(root(2)(2)(2)(1))(1, 1)
idx(3) = calc_tree(root(2)(2)(2)(2))(1, 1)
End If
Utils_Stack_Pop endValues
r = 1
c = MAX(0, 1 + WorksheetFunction.RoundDown((idx(3) - idx(1)) / idx(2), 0))
Else
t = 3
Utils_Stack_Push endValue, endValues
idx = calc_tree(root)
Utils_Stack_Pop endValues
Utils_Size idx, r, c
Dim i As Long, j As Long
For i = 1 To r
For j = 1 To c
If Not WorksheetFunction.IsLogical(idx(i, j)) Then Exit Sub
Next j
Next i
idx = fn_find(Array(idx))
Utils_Size idx, r, c
End If
End Sub
' Evaluates matrix indexing/subsetting
Private Function op_index(args As Variant) As Variant
Dim out As Variant, out_i As Long, out_j As Long
Dim arg_r As Long, arg_c As Long
Dim arg_i As Long, arg_j As Long
Dim idx1 As Variant, idx2 As Variant
Dim idx1_i As Long, idx2_i As Long
Dim idx1_j As Long, idx2_j As Long
Dim idx1_r As Long, idx2_r As Long
Dim idx1_c As Long, idx2_c As Long
Dim t1 As Long, t2 As Long ' t=1 for colon only, t=2 for sequence, t=3 for vector/mat
args(1) = calc_tree(args(1))
Utils_Size args(1), arg_r, arg_c
Select Case Utils_Stack_Size(args(2))
Case 0:
out = args(1)
Case 1:
op_indexarg args(2)(1), arg_r * arg_c, idx1, idx1_r, idx1_c, t1
If idx1_r * idx1_c = 0 Then Exit Function
If Utils_IsVectorShape(idx1_r, idx1_c) And Utils_IsVectorShape(arg_r, arg_c) Then
If arg_r > 1 Or t1 = 1 Then ReDim out(idx1_r * idx1_c, 1) Else ReDim out(1, idx1_r * idx1_c)
Else
ReDim out(idx1_r, idx1_c)
End If
Dim k As Long
For k = 1 To UBound(out, 1) * UBound(out, 2)
Select Case t1
Case 1: Utils_Ind2Sub arg_r, k, arg_i, arg_j
Case 2: Utils_Ind2Sub arg_r, idx1(1) + (k - 1) * idx1(2), arg_i, arg_j
Case 3: Utils_Ind2Sub idx1_r, k, idx1_i, idx1_j
Utils_Ind2Sub arg_r, CLng(idx1(idx1_i, idx1_j)), arg_i, arg_j
End Select
Utils_Ind2Sub UBound(out, 1), k, out_i, out_j
out(out_i, out_j) = args(1)(arg_i, arg_j)
Next k
Case 2:
op_indexarg args(2)(1), arg_r, idx1, idx1_r, idx1_c, t1
op_indexarg args(2)(2), arg_c, idx2, idx2_r, idx2_c, t2
If idx1_r * idx1_c = 0 Or idx2_r * idx2_c = 0 Then Exit Function
ReDim out(idx1_r * idx1_c, idx2_r * idx2_c)
For out_i = 1 To UBound(out, 1)
For out_j = 1 To UBound(out, 2)
Select Case t1
Case 1: arg_i = out_i
Case 2: arg_i = idx1(1) + (out_i - 1) * idx1(2)
Case 3: Utils_Ind2Sub idx1_r, out_i, idx1_i, idx1_j
arg_i = idx1(idx1_i, idx1_j)
End Select
Select Case t2
Case 1: arg_j = out_j
Case 2: arg_j = idx2(1) + (out_j - 1) * idx2(2)
Case 3: Utils_Ind2Sub idx2_r, out_j, idx2_i, idx2_j
arg_j = idx2(idx2_i, idx2_j)
End Select
out(out_i, out_j) = args(1)(arg_i, arg_j)
Next out_j
Next out_i
Case Else:
Utils_Fail "too many indices"
End Select
op_index = out
End Function
' Matches operator !
Private Function op_extern(args As Variant) As Variant
args(1)(1) = Mid(args(1)(1), 4)
Dim a: a = args(1)(2)
Utils_CalcArgs a
Select Case UBound(a)
Case 0: op_extern = Run(args(1)(1))
Case 1: op_extern = Run(args(1)(1), a(1))
Case 2: op_extern = Run(args(1)(1), a(1), a(2))
Case 3: op_extern = Run(args(1)(1), a(1), a(2), a(3))
Case 4: op_extern = Run(args(1)(1), a(1), a(2), a(3), a(4))
Case 5: op_extern = Run(args(1)(1), a(1), a(2), a(3), a(4), a(5))
Case 6: op_extern = Run(args(1)(1), a(1), a(2), a(3), a(4), a(5), a(6))
Case 7: op_extern = Run(args(1)(1), a(1), a(2), a(3), a(4), a(5), a(6), a(7))
Case 8: op_extern = Run(args(1)(1), a(1), a(2), a(3), a(4), a(5), a(6), a(7), a(8))
Case 9: op_extern = Run(args(1)(1), a(1), a(2), a(3), a(4), a(5), a(6), a(7), a(8), a(9))
Case 10: op_extern = Run(args(1)(1), a(1), a(2), a(3), a(4), a(5), a(6), a(7), a(8), a(9), a(10))
Case Else: Utils_Fail "cannot evaluate " & args(1)(1) & ": too many arguments"
End Select
Utils_Conform op_extern
End Function
' Matches operator ||
Private Function op_orshortcircuit(args As Variant) As Variant
args(1) = calc_tree(args(1))
Utils_Assert Utils_Numel(args(1)) = 1, "||: 1st argument must be scalar"
On Error GoTo ErrorHandler
If CBool(args(1)(1, 1)) Then
op_orshortcircuit = Utils_ToMatrix(True)
Else
On Error GoTo 0
args(2) = calc_tree(args(2))
Utils_Assert Utils_Numel(args(2)) = 1, "||: 2nd argument must be scalar"
On Error GoTo ErrorHandler
op_orshortcircuit = Utils_ToMatrix(CBool(args(2)(1, 1)))
End If
Exit Function
ErrorHandler:
Utils_Fail "||: could not convert argument to boolean value"
End Function
' Matches operator &&
Private Function op_andshortcircuit(args As Variant) As Variant
args(1) = calc_tree(args(1))
Utils_Assert Utils_Numel(args(1)) = 1, "&&: 1st argument must be scalar"
On Error GoTo ErrorHandler
If Not CBool(args(1)(1, 1)) Then
op_andshortcircuit = Utils_ToMatrix(False)
Else
On Error GoTo 0
args(2) = calc_tree(args(2))
Utils_Assert Utils_Numel(args(2)) = 1, "&&: 2nd argument must be scalar"
On Error GoTo ErrorHandler
op_andshortcircuit = Utils_ToMatrix(CBool(args(2)(1, 1)))
End If
Exit Function
ErrorHandler:
Utils_Fail "&&: could not convert argument to boolean value"
End Function
' Matches operator &
Private Function op_and(args As Variant) As Variant
Dim out, r As Long, c As Long, i As Long, j As Long
Dim arg1_r As Long, arg1_c As Long, arg2_r As Long, arg2_c As Long
Utils_SetupBinaryOperation args, out, r, c, arg1_r, arg1_c, arg2_r, arg2_c
For i = 1 To r
For j = 1 To c
out(i, j) = CBool(args(1)(MIN(i, arg1_r), MIN(j, arg1_c))) _
And CBool(args(2)(MIN(i, arg2_r), MIN(j, arg2_c)))
Next j
Next i
op_and = out
End Function
' Matches operator |
Private Function op_or(args As Variant) As Variant
Dim out, r As Long, c As Long, i As Long, j As Long
Dim arg1_r As Long, arg1_c As Long, arg2_r As Long, arg2_c As Long
Utils_SetupBinaryOperation args, out, r, c, arg1_r, arg1_c, arg2_r, arg2_c
For i = 1 To r
For j = 1 To c
out(i, j) = CBool(args(1)(MIN(i, arg1_r), MIN(j, arg1_c))) _
Or CBool(args(2)(MIN(i, arg2_r), MIN(j, arg2_c)))
Next j
Next i
op_or = out
End Function
' Matches operator <
Private Function op_lt(args As Variant) As Variant
Dim out, r As Long, c As Long, i As Long, j As Long
Dim arg1_r As Long, arg1_c As Long, arg2_r As Long, arg2_c As Long
Utils_SetupBinaryOperation args, out, r, c, arg1_r, arg1_c, arg2_r, arg2_c
For i = 1 To r
For j = 1 To c
out(i, j) = args(1)(MIN(i, arg1_r), MIN(j, arg1_c)) _
< args(2)(MIN(i, arg2_r), MIN(j, arg2_c))
Next j
Next i
op_lt = out
End Function
' Matches operator <=
Private Function op_lte(args As Variant) As Variant
Dim out, r As Long, c As Long, i As Long, j As Long
Dim arg1_r As Long, arg1_c As Long, arg2_r As Long, arg2_c As Long
Utils_SetupBinaryOperation args, out, r, c, arg1_r, arg1_c, arg2_r, arg2_c
For i = 1 To r
For j = 1 To c
out(i, j) = args(1)(MIN(i, arg1_r), MIN(j, arg1_c)) _
<= args(2)(MIN(i, arg2_r), MIN(j, arg2_c))
Next j
Next i
op_lte = out
End Function
' Matches operator >
Private Function op_gt(args As Variant) As Variant
Dim out, r As Long, c As Long, i As Long, j As Long
Dim arg1_r As Long, arg1_c As Long, arg2_r As Long, arg2_c As Long
Utils_SetupBinaryOperation args, out, r, c, arg1_r, arg1_c, arg2_r, arg2_c
For i = 1 To r
For j = 1 To c
out(i, j) = args(1)(MIN(i, arg1_r), MIN(j, arg1_c)) _
> args(2)(MIN(i, arg2_r), MIN(j, arg2_c))
Next j
Next i
op_gt = out