forked from silq-lang/silq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dexpr.d
4593 lines (4347 loc) · 145 KB
/
dexpr.d
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
// Written in the D programming language
// License: http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0
// TODO: the caches should use weak references
import std.conv;
import options, util.hashtable, util;
alias Q=TupleX, q=tuplex;
static import std.typecons;
import std.algorithm, std.array;
import std.datetime.stopwatch;
struct RecursiveStopWatch{
StopWatch sw;
int started=0;
void stop(){
if(--started==0) sw.stop();
}
void start(){
if(++started==1) sw.start();
}
auto peek(){ return sw.peek(); }
}
/+RecursiveStopWatch sw;
int swCount=0;
static ~this(){
writeln("time: ",sw.peek().total!"hnsecs"/1e7);
writeln("freq: ",swCount);
}
enum measure="swCount++;sw.start();scope(exit)sw.stop();";+/
//version=DISABLE_INTEGRATION;
enum Precedence{
none,
lambda,
bind,
bitOr,
bitXor,
bitAnd,
plus,
uminus,
lim,
intg,
mult,
div,
diff,
pow,
apply,
index,
field=index,
subscript,
invalid,
}
hash_t g_hash=0;
abstract class DExpr{
hash_t hash;
this(){ hash = ++g_hash; }
final override hash_t toHash()@trusted{ return hash; }
final override bool opEquals(Object r){ return this is r; }
final override string toString(){ return toString(Format.default_); }
string toString(Format formatting){
auto r=toStringImpl(formatting,Precedence.none,0);
if(formatting==Format.sympy) r=text("limit(",r,",pZ,0,'+')"); // pZ: positive zero
else if(formatting==Format.maple) r=text("limit(",r,",pZ=0,right)");
return r;
}
abstract string toStringImpl(Format formatting,Precedence prec,int binders);
abstract int forEachSubExpr(scope int delegate(DExpr) dg);
abstract DExpr simplifyImpl(DExpr facts);
/+static RecursiveStopWatch[DExpr] simplificationTimer;
static ~this(){
Q!(double,DExpr)[] x;
foreach(k,v;simplificationTimer) x~=q(v.peek().to!("seconds",double),k);
sort!"a[0]>b[0]"(x);
double tot=0;
foreach(k;x){
writeln(k[1],": ",k[0]);
writeln(k[1].simplify(one));
writeln();
writeln();
// if(k[0]<0.01) break;
tot+=k[0];
}
writeln("tot: ",tot);
}+/
static MapX!(Q!(DExpr,DExpr),DExpr) simplifyCache;
final DExpr simplify(string file=__FILE__,int line=__LINE__)(DExpr facts){
/+static int nested=0;nested++; scope(exit) nested--;
if(nested==1){
if(this !in simplificationTimer){
simplificationTimer[this]=RecursiveStopWatch();
}
simplificationTimer[this].start();
}
scope(exit) if(nested==1) simplificationTimer[this].stop();+/
assert(!cast(DPlus)facts,text(facts));
if(q(this,facts) in simplifyCache) return simplifyCache[q(this,facts)];
if(facts==zero) return zero;
auto r=simplifyImpl(facts);
assert(!!r,text(typeid(this)));
simplifyCache[q(this,facts)]=r;
simplifyCache[q(r,facts)]=r;
/+foreach(ivr;r.allOf!DIvr){ // TODO: remove?
assert(ivr == ivr.simplify(facts),text(this," ",r," ",facts));
assert(ivr.type != DIvr.Type.lZ);
}+/
return r;
}
// TODO: implement in terms of 'forEachSubExpr'?
static MapX!(Q!(DExpr,DVar,DExpr),DExpr) substituteCache;
final DExpr substitute(DVar var,DExpr e){
auto t=q(this,var,e);
if(t in substituteCache) return substituteCache[t];
auto r=substituteImpl(var,e);
substituteCache[t]=r;
return r;
}
abstract DExpr substituteImpl(DVar var,DExpr e);
static MapX!(Q!(DExpr,int,int),DExpr) incDeBruijnVarCache;
final DExpr incDeBruijnVar(int di,int bound){
auto t=q(this,di,bound);
if(t in incDeBruijnVarCache) return incDeBruijnVarCache[t];
auto r=incDeBruijnVarImpl(di,bound);
incDeBruijnVarCache[t]=r;
return r;
}
abstract DExpr incDeBruijnVarImpl(int di,int bound);
abstract int freeVarsImpl(scope int delegate(DVar),ref DExprSet visited);
final freeVars(){
static struct FreeVars{ // TODO: move to util?
DExpr self;
DExprSet visited;
@disable this(this);
int opApply(scope int delegate(DVar) dg){
visited=DExprSet.init;
return self.freeVarsImpl(dg,visited);
}
}
return FreeVars(this);
}
final bool hasFreeVar(DVar var){
foreach(v;freeVars) if(v == var) return true;
return false;
}
final Dℚ isFractional(){
auto q=cast(Dℚ)this;
if(q&&q.c.den!=1) return q;
return null;
}
final Dℚ isInteger(){
auto q=cast(Dℚ)this;
if(q&&q.c.den==1) return q;
if(auto f=cast(DFloat)this){
import std.math: floor;
import std.format: format;
if(f.c==floor(f.c)) return ℤ(format("%.0f",floor(f.c))).dℚ;
}
return null;
}
// helpers for construction of DExprs:
enum ValidUnary(string s)=s=="-";
enum ValidBinary(string s)=["+","-","*","/","%","^^","~"].canFind(s);
template UnaryCons(string s)if(ValidUnary!s){
static assert(s=="-");
alias UnaryCons=dUMinus;
}
template BinaryCons(string s)if(ValidBinary!s){
static if(s=="+") alias BinaryCons=dPlus;
else static if(s=="-") alias BinaryCons=dMinus;
else static if(s=="*") alias BinaryCons=dMult;
else static if(s=="/") alias BinaryCons=dDiv;
else static if(s=="%") alias BinaryCons=dMod;
else static if(s=="^^") alias BinaryCons=dPow;
else static if(s=="~") alias BinaryCons=dCat;
else static assert(0);
}
final opUnary(string op)()if(op=="-"){
return UnaryCons!op(this);
}
final DExpr opBinary(string op)(DExpr e)if(ValidBinary!op){
return BinaryCons!op(this,e);
}
final DExpr opBinary(string op)(long e)if(ValidBinary!op){
return mixin("this "~op~" e.dℚ");
}
final DExpr opBinaryRight(string op)(long e)if(ValidBinary!op){
return mixin("e.dℚ "~op~" this");
}
final DExpr opBinary(string op)(ℤ e)if(ValidBinary!op&&op!="~"){
return mixin("this "~op~" e.dℚ");
}
final DExpr opBinary(string op)(ℚ e)if(ValidBinary!op&&op!="~"){
return mixin("this "~op~" e.dℚ");
}
final DExpr opBinaryRight(string op)(ℤ e)if(ValidBinary!op&&op!="~"){
return mixin("e.dℚ "~op~" this");
}
final DExpr opBinaryRight(string op)(ℚ e)if(ValidBinary!op&&op!="~"){
return mixin("e.dℚ "~op~" this");
}
final DExpr opBinary(string op)(real e)if(ValidBinary!op&&op!="~"){
return mixin("this "~op~" e.dFloat");
}
final DExpr opBinaryRight(string op)(real e)if(ValidBinary!op&&op!="~"){
return mixin("e.dFloat "~op~" this");
}
final DExpr opIndex(DExpr rhs){ return dIndex(this,rhs); }
mixin template Constant(){
static if(!is(subExprs==Seq!()))
this(typeof(subExprs) args){ subExprs=args; }
override int forEachSubExpr(scope int delegate(DExpr) dg){ return 0; }
override int freeVarsImpl(scope int delegate(DVar) dg,ref DExprSet visited){ return 0; }
override DExpr substituteImpl(DVar var,DExpr e){ assert(var != this); return this; }
override DExpr incDeBruijnVarImpl(int di,int bound){ return this; }
override DExpr simplifyImpl(DExpr facts){ return this; }
}
}
// attributes
struct binder{} struct even{} struct conditionallyEven(alias cond){ } struct isAbstract{}
enum forEachSubExprImpl(string code)=mixin(X!q{
foreach(i,se;subExprs){
//import dp: Dist;
static if(is(typeof(se):DExpr)/+||is(typeof(se)==Dist)+/){
alias x=se;
@(code)
}else static if(is(typeof(se)==SetX!DExpr)||is(typeof(se)==DExpr[])||is(typeof(se)==DExpr[2])){
foreach(x;se) @(code)
}else static if(is(typeof(se)==DExpr[string])){
foreach(k,x;values) @(code)
}else{
import ast.type: Type;
import ast.declaration: FunctionDef;
static assert(is(typeof(se)==string)||is(typeof(se)==int)||is(typeof(se)==DIvr.Type)||is(typeof(se)==Type)||is(typeof(se)==FunctionDef)||is(typeof(se)==Dist), "foreachSubExprImpl is not exhaustive.");
}
}
});
template IncDeBruijnVarType(T){
static if(is(T:DVar)||is(T==DLambda)||is(T==DDistLambda)) alias IncDeBruijnVarType=T;
else alias IncDeBruijnVarType=DExpr;
}
template SubstituteType(T){
static if(is(T==DLambda)||is(T==DDistLambda)) alias SubstituteType=T;
else alias SubstituteType=DExpr;
}
import std.traits: hasUDA;
enum IsAbstract(T) = hasUDA!(T,isAbstract);
mixin template Visitors(){
this(typeof(subExprs) args)in{
static if(is(typeof(this)==DDeBruijnVar))
assert(args[0]>=0);
static if(is(typeof(this):DAssocOp)||is(typeof(this):DCommutAssocOp))
assert(args[0].length>1);
static if(is(typeof(this)==DIvr)){
foreach(d;args[1].allOf!DDelta) assert(0,text(args[1]));
}
}body{
subExprs=args;
}
static if(is(typeof(subExprs)==Seq!(DExpr[2])))
this(DExpr e1,DExpr e2){ this([e1,e2]); }
static if(!IsAbstract!(typeof(this))):
override int forEachSubExpr(scope int delegate(DExpr) dg){
// TODO: fix this.
//import dp: DDPDist;
static if(!(/+is(typeof(this)==DDPDist)||+/is(typeof(this)==DLambda)||is(typeof(this)==DDistLambda)||is(typeof(this)==DInt)||is(typeof(this)==DSum)||is(typeof(this)==DLim)||is(typeof(this)==DDiff)||is(typeof(this)==DDelta)||is(typeof(this)==DDiscDelta)))
mixin(forEachSubExprImpl!"if(auto r=dg(x)) return r;");
return 0;
}
override int freeVarsImpl(scope int delegate(DVar) dg,ref DExprSet visited){
// TODO: improve performance (this method uses ~10% of total running time)
if(this in visited) return 0;
visited.insert(this);
static if(is(typeof(this):DVar)) return dg(this);
else{
mixin(forEachSubExprImpl!q{{
import std.traits: hasUDA;
static if(hasUDA!(subExprs[i],binder)){
foreach(v;x.freeVars())
if(v!=db1)
if(auto r=dg(v.incDeBruijnVar(-1,0)))
return r;
}else{ if(auto r=x.freeVarsImpl(dg,visited)) return r; }
}});
return 0;
}
}
override SubstituteType!(typeof(this)) substituteImpl(DVar var,DExpr e){
static if(is(typeof(this):DVar)) return this==var?e:this;
else{
Q!(typeof(subExprs)) nsubs;
//import dp: Dist;
foreach(i,sub;subExprs){
auto cvar=var,ce=e;
import std.traits: hasUDA;
static if(hasUDA!(subExprs[i],binder)){
cvar=cvar.incDeBruijnVar(1,0);
ce=ce.incDeBruijnVar(1,0);
}
static if(is(typeof(sub):DExpr)/+||is(typeof(sub)==Dist)+/){
nsubs[i]=sub.substitute(cvar,ce);
}else static if(is(typeof(sub)==DExprSet)){
if(auto evar=cast(DVar)e){ // TODO: make this unnecessary, this is a hack to improve performance
if(!hasFreeVar(evar)){
foreach(f;sub) nsubs[i].insert(f.substitute(cvar,ce));
continue;
}
}
foreach(f;sub) typeof(this).insert(nsubs[i],f.substitute(cvar,ce));
}else static if(is(typeof(sub)==DExpr[])||is(typeof(sub)==DExpr[2])){
nsubs[i]=sub.dup;
foreach(ref x;nsubs[i]) x=x.substitute(cvar,ce);
}else static if(is(typeof(sub)==DExpr[string])){
foreach(k,v;sub) nsubs[i][k]=v.substitute(cvar,ce);
}else{
import ast.type: Type;
import ast.declaration: FunctionDef;
static assert(is(typeof(sub)==string)||is(typeof(sub)==int)||is(typeof(sub)==DIvr.Type)||is(typeof(sub)==Type)||is(typeof(sub)==FunctionDef));
nsubs[i]=sub;
}
}
if(nsubs==q(subExprs)) return this;
return mixin(lowerf(typeof(this).stringof))(nsubs.expand);
}
}
override IncDeBruijnVarType!(typeof(this)) incDeBruijnVarImpl(int di,int bound){
static if(is(typeof(this)==DDeBruijnVar)){
if(i<=bound) return this;
assert((i<=bound) == (i+di <= bound)); // (otherwise bound variables can be captured);
return dDeBruijnVar(i+di);
}else{
Q!(typeof(subExprs)) nsubs;
alias subs=subExprs;
foreach(i,sub;subExprs){
auto cdi=di,cbound=bound;
import std.traits: hasUDA;
static if(hasUDA!(subExprs[i],binder)){
cbound++;
}
static if(is(typeof(sub):DExpr)){
nsubs[i]=cast(typeof(nsubs[i]))sub.incDeBruijnVar(cdi,cbound);
}else static if(is(typeof(sub)==SetX!DExpr)){
foreach(f;sub) nsubs[i].insert(f.incDeBruijnVar(cdi,cbound));
}else static if(is(typeof(sub)==DExpr[])||is(typeof(sub)==DExpr[2])){
nsubs[i]=sub.dup;
foreach(ref x;nsubs[i]) x=x.incDeBruijnVar(cdi,cbound);
}else static if(is(typeof(sub)==DExpr[string])){
foreach(k,v;sub) nsubs[i][k]=v.incDeBruijnVar(cdi,cbound);
}else nsubs[i]=sub;
}
if(nsubs==q(subExprs)) return this;
return mixin(lowerf(typeof(this).stringof))(nsubs.expand);
}
}
}
mixin template FactoryFunction(T){
static if(is(T==DIvr)){
DExpr dIvr(DIvr.Type type,DExpr e){
static MapX!(DExpr,DExpr)[DIvr.Type.max+1] cache;
if(e in cache[type]) return cache[type][e];
auto r=new DIvr(type,e);
cache[type][e]=r;
return r;
}
DExpr dEqZ(DExpr e){ return dIvr(DIvr.Type.eqZ,e); }
DExpr dNeqZ(DExpr e){ return dIvr(DIvr.Type.neqZ,e); }
DExpr dLeZ(DExpr e){ return dIvr(DIvr.Type.leZ,e); }
DExpr dGeZ(DExpr e){ return dIvr(DIvr.Type.leZ,-e); }
DExpr dLtZ(DExpr e){ return dIvr(DIvr.Type.lZ,e); }
DExpr dGtZ(DExpr e){ return dIvr(DIvr.Type.lZ,-e); }
DExpr dEq(DExpr e1,DExpr e2){ return dEqZ(e1-e2); }
DExpr dNeq(DExpr e1,DExpr e2){ return dNeqZ(e1-e2); }
DExpr dLe(DExpr e1,DExpr e2){ return dLeZ(e1-e2); }
DExpr dGe(DExpr e1,DExpr e2){ return dLeZ(e2-e1); }
DExpr dLt(DExpr e1,DExpr e2){ return dLtZ(e1-e2); }
DExpr dGt(DExpr e1,DExpr e2){ return dLtZ(e2-e1); }
}else:
static if(is(T==DDelta)){
import ast.expression; // TODO: remove this import
DExpr dDelta(DExpr e,DExpr var,Expression ty){ // TODO: dexpr shouldn't know about expression/type, but this is most convenient for overloading
import ast.type;
if(isSubtype(ty,ℝ(true))) return dDelta(e-var);
assert(cast(TupleTy)ty||cast(ArrayTy)ty||cast(AggregateTy)ty||cast(ContextTy)ty||cast(FunTy)ty||cast(TypeTy)ty||cast(Identifier)ty||cast(CallExp)ty,text(ty)); // TODO: add more supported types
return dDiscDelta(e,var);
}
}else static if(is(T==DInt)){ // TODO: generalize over DInt, DSum, DLim, DLambda, (DDiff)
@disable DExpr dIntSmp(DVar var,DExpr expr);
DExpr dIntSmp(DExpr expr,DExpr facts){
return dInt(expr).simplify(facts);
}
DExpr dIntSmp(DVar var,DExpr expr,DExpr facts){
return dInt(var,expr).simplify(facts);
}
DExpr dInt(DVar var,DExpr expr)in{assert(var&&expr&&!cast(DDeBruijnVar)var);}body{
return dInt(expr.incDeBruijnVar(1,0).substitute(var,db1));
}
}else static if(is(T==DSum)){
@disable DExpr dSumSmp(DVar var,DExpr expr);
DExpr dSumSmp(DExpr expr,DExpr facts){
return dSum(expr).simplify(facts);
}
DExpr dSumSmp(DVar var,DExpr expr,DExpr facts){
return dSum(var,expr).simplify(facts);
}
DExpr dSum(DVar var,DExpr expr)in{assert(var&&expr&&!cast(DDeBruijnVar)var);}body{
return dSum(expr.incDeBruijnVar(1,0).substitute(var,db1));
}
}else static if(is(T==DLim)){
@disable DExpr dLimSmp(DVar var,DExpr e,DExpr x);
DExpr dLimSmp(DExpr e,DExpr x,DExpr facts){
return dLim(e,x).simplify(facts);
}
DExpr dLimSmp(DVar v,DExpr e,DExpr x,DExpr facts){
return dLim(v,e,x).simplify(facts);
}
DExpr dLim(DVar v,DExpr e,DExpr x)in{assert(v&&e&&x&&(!cast(DDeBruijnVar)v||v==db1));}body{
if(v==db1) return dLim(e,x.incDeBruijnVar(1,1));
return dLim(e,x.incDeBruijnVar(1,0).substitute(v,db1));
}
}else static if(is(T==DDiff)){
DExpr dDiff(DVar v,DExpr e,DExpr x)in{assert(v&&e&&x&&(!cast(DDeBruijnVar)v||v==db1));}body{
if(v==db1) return dDiff(e.incDeBruijnVar(1,1),x);
return dDiff(e.incDeBruijnVar(1,0).substitute(v,db1),x);
}
DExpr dDiff(DVar v,DExpr e){ return dDiff(v,e,v); }
}else static if(is(T==DLambda)){
@disable DExpr dLambdaSmp(DVar var,DExpr expr);
DLambda dLambdaSmp(DExpr expr,DExpr facts)in{assert(expr);}body{
auto r=dLambda(expr).simplify(facts);
assert(!!cast(DLambda)r);
return cast(DLambda)cast(void*)r;
}
DLambda dLambdaSmp(DVar var,DExpr expr,DExpr facts)in{assert(var&&expr);}body{
auto r=dLambda(var,expr).simplify(facts);
assert(!!cast(DLambda)r);
return cast(DLambda)cast(void*)r;
}
DLambda dLambda(DVar var,DExpr expr)in{assert(var&&expr&&(!cast(DDeBruijnVar)var||var==db1));}body{
if(var==db1) return dLambda(expr);
return dLambda(expr.incDeBruijnVar(1,0).substitute(var,db1));
}
}else static if(is(T==DDistLambda)){
@disable DExpr dDistLambdaSmp(DVar var,DExpr expr);
DDistLambda dDistLambdaSmp(DExpr expr,DExpr facts)in{assert(expr);}body{
auto r=dDistLambda(expr).simplify(facts);
assert(!!cast(DDistLambda)r);
return cast(DDistLambda)cast(void*)r;
}
DDistLambda dDistLambdaSmp(DVar var,DExpr expr,DExpr facts)in{assert(var&&expr);}body{
auto r=dDistLambda(var,expr).simplify(facts);
assert(!!cast(DDistLambda)r);
return cast(DDistLambda)cast(void*)r;
}
DDistLambda dDistLambda(DVar var,DExpr expr)in{assert(var&&expr&&(!cast(DDeBruijnVar)var||var==db1));}body{
if(var==db1) return dDistLambda(expr);
return dDistLambda(expr.incDeBruijnVar(1,0).substitute(var,db1));
}
}else static if(is(T==DRecord)){
auto dRecord(){ return dRecord((DExpr[string]).init); }
}else static if(is(T==DArray)){
auto dArray(DExpr length){ return dArray(length,dLambda(zero)); }
auto dConstArray(DExpr length,DExpr default_){
assert(!cast(DLambda)default_);
return dArray(length,dLambda(default_.incDeBruijnVar(1,0)));
}
auto dArray(DExpr[] entries){
auto dbv=db1;
// TODO: not necessarily very clean for types that are not real numbers, but can be interpreted in terms of linear algebra
DExpr body_=zero;
foreach(i,e;entries) body_=body_+dEq(dbv,i.dℚ)*entries[i].incDeBruijnVar(1,0);
return dArray(dℚ(ℤ(entries.length)),dLambda(body_));
}
}else static if(is(T==Dℚ)){
DExpr dℚ(long c){ return dℚ(ℚ(c)); }
Dℚ dℚ(ℤ c){ return dℚ(ℚ(c)); }
}
static if(is(T.subExprs==Seq!())){
mixin(mixin(X!q{
auto @(lowerf(T.stringof))(){
static T cache=null;
if(cache) return cache;
cache=new T();
return cache;
}
}));
}else:
mixin(mixin(X!q{
auto @(lowerf(T.stringof))(typeof(T.subExprs) args){
static if(is(T:DCommutAssocOp)){
static assert(is(typeof(args)==Seq!DExprSet));
if(args[0].length==1) return args[0].element;
}
static if(is(T:DAssocOp)){
static assert(is(typeof(args)==Seq!(DExpr[])));
if(args[0].length==1) return args[0][0];
}
static if(__traits(hasMember,T,"constructHook"))
if(auto r=T.constructHook(args)) return r;
static if(is(T==DFloat)) if(args[0]==0) return zero;
static MapX!(TupleX!(typeof(T.subExprs)),T) cache;
auto t=tuplex(args);
if(t in cache) return cache[t];
auto r=new T(args);
cache[t]=r;
return r;
}
}));
static if(is(T:DBinaryOp)||is(T:DAssocOp)){
mixin(mixin(X!q{
auto @(lowerf(T.stringof))(DExpr e1,DExpr e2){
return @(lowerf(T.stringof))([e1,e2]);
}
}));
}
static if(is(T:DCommutAssocOp)){
mixin(mixin(X!q{
auto @(lowerf(T.stringof))(DExpr e1,DExpr e2){
DExprSet a;
T.insert(a,e1);
T.insert(a,e2);
return @(lowerf(T.stringof))(a);
}
}));
}
}
mixin template FactoryFunction(string name,string value){
mixin(mixin(X!q{
auto @(name)(){
static typeof(@(value)) cache=null;
if(cache) return cache;
cache=@(value);
return cache;
}
}));
}
alias DExprSet=SetX!DExpr;
abstract class DVar: DExpr{
static string fixName(string name,Format formatting){
if(formatting==Format.gnuplot||formatting==Format.python||formatting==Format.sympy||formatting==Format.matlab||formatting==Format.mathematica){
return asciify(name);
auto nname=name.to!dstring; // TODO: why necessary? Phobos bug?
nname=nname.replace("ξ"d,"xi"d);
//pragma(msg, cast(dchar)('₀'+1));
foreach(x;0..10)
nname=nname.replace(""d~cast(dchar)('₀'+x),""d~cast(dchar)('0'+x));
return nname.to!string;
}
return name;
}
override abstract DVar incDeBruijnVarImpl(int di,int bound);
final DVar incDeBruijnVar(int di,int bound){
auto r=cast(DVar)super.incDeBruijnVar(di,bound); // TODO: get rid of cast?
assert(!!r);
return r;
}
override DExpr simplifyImpl(DExpr facts){
// TODO: make more efficient! (e.g. keep hash table in product expressions)
foreach(f;facts.factors){
if(auto ivr=cast(DIvr)f){
if(ivr.type!=DIvr.Type.eqZ) continue;
if(ivr.e.getCanonicalFreeVar()!=this) continue; // TODO: make canonical var smart
SolutionInfo info;
SolUse usage={caseSplit:false,bound:false};
auto sol=ivr.e.solveFor(this,zero,usage,info);
if(!sol||info.needCaseSplit) continue; // TODO: make more efficient!
// TODO: we probably want to do a case split here.
// TODO: allow this simplification to be disabled temporarily (for delta expressions)
return sol.simplify(facts);
}
}
return this;
}
}
class DNVar: DVar{ // named variables
string name;
alias subExprs=Seq!(name);
override string toStringImpl(Format formatting,Precedence prec,int binders){
return fixName(name,formatting);
}
mixin Visitors;
}
DNVar[string] dVarCache; // TODO: caching desirable? (also need to update parser if not)
DNVar dNVar(string name){
if(name in dVarCache) return dVarCache[name];
return dVarCache[name]=new DNVar(name);
}
alias dVar=dNVar;
class DDeBruijnVar: DVar{
int i;
alias subExprs=Seq!i;
static string displayName(int i,Format formatting,int binders){
return DVar.fixName("ξ"~lowNum(1+binders-i),formatting);
}
override string toStringImpl(Format formatting,Precedence prec,int binders){
return displayName(i,formatting,binders);
}
mixin Visitors;
}
mixin FactoryFunction!DDeBruijnVar;
@property db1(){ return dDeBruijnVar(1); }
@property db2(){ return dDeBruijnVar(2); }
@property db3(){ return dDeBruijnVar(3); }
// substitute all variables from 'from' by the respective expressions in 'to' at the same time (avoiding capture)
DExpr substituteAll(DExpr e,DVar[] from, DExpr[] to)in{assert(from.length==to.length);}body{
assert(from.length<int.max);
auto ne=e;
auto vars=from.map!(a=>freshVar).array; // TODO: get rid of this!
foreach(i,v;from) ne=ne.substitute(v,vars[i]);
foreach(i,t;to) ne=ne.substitute(vars[i],t);
return ne;
}
class DTmpDeBruijnVar: DNVar{
int i;
static int curi=0;
this(string name){ super(name); i=curi++; }
override string toStringImpl(Format formatting,Precedence prec,int binders){
if(name=="tmp") // Can be convenient for debugging. TODO: get rid of "tmp" vars
return name~(cast(void*)this).to!string;
return super.toStringImpl(formatting,prec,binders);
}
override DExpr simplifyImpl(DExpr facts){
return this;
}
} // TODO: get rid of this!
DNVar freshVar(string name="tmp"){ return new DTmpDeBruijnVar(name); } // TODO: get rid of this!
DVar theDε;
DVar dε(){ return theDε?theDε:(theDε=new DNVar("ε")); }
class Dℚ: DExpr{
ℚ c;
alias subExprs=Seq!c;
override string toStringImpl(Format formatting,Precedence prec,int binders){
string r;
if(c.den==1){
r=text(c.num);
}else{
if(formatting==Format.matlab||formatting==Format.gnuplot)
r=text(c.num,"./",c.den);
else if(formatting==Format.lisp){
return text("(/ ",c.num," ",c.den,")");
}else r=text(c.num,"/",c.den);
}
if(formatting==Format.maple && c<0){
r="("~r~")";
}else if(c.den!=1&&prec>Precedence.div||prec>Precedence.uminus&&c<0)
r="("~r~")";
return r;
}
mixin Constant;
}
mixin FactoryFunction!Dℚ;
Dℚ nthRoot(ℤ x,ℤ n){ // TODO: return Maybe!ℤ or something.
ℤ k=1,r=0;
while(k<x) k*=2;
for(;k;k/=2){
ℤ c=r+k;
if(pow(c,n)<=x)
r=c;
}
return pow(r,n)==x?dℚ(r):null;
}
Dℚ nthRoot(ℚ x,ℤ n){
if(auto rnum=nthRoot(x.num,n))
if(auto rden=nthRoot(x.den,n)){
assert(rnum.c.den==1 && rden.c.den==1);
return dℚ(ℚ(rnum.c.num,rden.c.num));
}
return null;
}
ℤ ceilLog2(ℤ x)in{assert(x>=1);}body{
ℤ r=0;
for(ℤ y=1;y<x;y*=2) ++r;
return r;
}
Dℚ[2] isPower(ℤ x,size_t bound=-1)in{assert(x>=0);}body{ // TODO: return Maybe!(ℤ[2])
if(x<4) return [null,null];
ℤ i = ceilLog2(x);
if(bound!=-1) if(i>bound) return [null,null];
for(;i>1;--i)
if(auto r=nthRoot(x,i))
return [r,dℚ(i)];
return [null,null];
}
Dℚ integerLog(ℤ x,ℤ b)in{assert(x>0);}body{ // TODO: return Maybe!ℤ
if(x==1) return cast(Dℚ)zero;
if(x%b) return null;
ℤ r=0,d=1;
ℤ[] p=[b];
while(!(x%p[$-1])){
p~=p[$-1]*p[$-1];
d*=2;
}
ℤ c=x;
for(size_t i=p.length;i--;d/=2){
if(!(c%p[i])){
c/=p[i];
r+=d;
}
}
return c==1?dℚ(r):null;
}
class DFloat: DExpr{
real c;
alias subExprs=Seq!c;
override string toStringImpl(Format formatting,Precedence prec,int binders){
import std.format;
string r=format("%.16e",c);
assert(all!(c=>'0'<=c&&c<='9'||c=='-'||c=='+'||c=='.'||c=='e')(r),r);
if(formatting==Format.mathematica){
if(r.canFind("e"))
r="("~r.replace("e","*10^")~")";
}else if(formatting==Format.maple){
if(c<0) r="("~r~")";
}else if(formatting==Format.lisp){
long e=0;
if(r.canFind("e")){
auto x=r.split("e");
assert(x.length==2);
e=to!long(x[1]);
r=x[0];
}
if(r.canFind(".")){
auto y=r.split('.');
while(!y[1].empty && y[1][$-1]=='0') y[1].popBack();
assert(y[1].length<=long.max);
auto exp="(^ 10 "~text(e-cast(long)y[1].length)~")";
e-=cast(long)y[1].length;
r=y[0]~y[1];
}
//if(e!=0) r="(* "~r~" (^ 10 "~text(e)~"))";
if(e!=0){
import std.range: repeat;
r="("~(e<0?"/":"*")~" "~r~" 1"~'0'.repeat(e<0?-e:e).to!string~")";
}
}else if(prec>Precedence.uminus&&c<0)
r="("~r~")";
return r;
}
mixin Constant;
}
mixin FactoryFunction!DFloat;
class DE: DExpr{
alias subExprs=Seq!();
override string toStringImpl(Format formatting,Precedence prec,int binders){
if(formatting==Format.gnuplot) return "exp(1)";
if(formatting==Format.maple) return "exp(1)";
if(formatting==Format.mathematica) return "E";
if(formatting==Format.sympy) return "E";
return "e";
} // TODO: maple
mixin Constant;
}
mixin FactoryFunction!DE;
class DΠ: DExpr{
alias subExprs=Seq!();
override string toStringImpl(Format formatting,Precedence prec,int binders){ // TODO: maple
if(formatting==Format.gnuplot) return "pi";
if(formatting==Format.matlab) return "pi";
if(formatting==Format.maple) return "Pi";
if(formatting==Format.mathematica) return "Pi";
if(formatting==Format.sympy) return "pi";
else return "π";
}
mixin Constant;
}
mixin FactoryFunction!DΠ;
mixin FactoryFunction!("one","dℚ(1)");
mixin FactoryFunction!("mone","dℚ(-1)");
mixin FactoryFunction!("zero","dℚ(0)");
abstract class DOp: DExpr{
abstract @property string symbol(Format formatting,int binders);
bool rightAssociative(){ return false; }
abstract @property Precedence precedence();
/+protected+/ final string addp(Precedence prec, string s, Precedence myPrec=Precedence.invalid){ // TODO: add protected
if(myPrec==Precedence.invalid) myPrec=precedence;
return prec > myPrec||rightAssociative&&prec==precedence? "(" ~ s ~ ")":s;
}
}
@isAbstract
abstract class DAssocOp: DOp{
DExpr[] operands;
alias subExprs=Seq!operands;
override string toStringImpl(Format formatting,Precedence prec,int binders){
string r;
if(formatting==Format.lisp){
r~="(";
r~=symbol(formatting,binders);
foreach(o;operands){
r~=" ";
r~=o.toStringImpl(formatting,prec,binders);
}
r~=")";
return r;
}
foreach(o;operands) r~=symbol(formatting,binders)~o.toStringImpl(formatting,prec,binders);
return addp(prec, r[symbol(formatting,binders).length..$]);
}
}
abstract class DCommutAssocOp: DOp{
/+protected+/ final string toStringImplImpl(DExprSet operands,Format formatting,Precedence prec,int binders){
string r;
if(formatting==Format.lisp){
r~="(";
r~=symbol(formatting,binders);
foreach(o;operands){
r~=" ";
r~=o.toStringImpl(formatting,prec,binders);
}
r~=")";
return r;
}
auto ops=operands.array.map!(a=>a.toStringImpl(formatting,precedence,binders)).array;
sort(ops);
foreach(o;ops) r~=symbol(formatting,binders)~o;
return addp(prec, r[symbol(formatting,binders).length..$]);
}
mixin template ToString(){
override string toStringImpl(Format formatting,Precedence prec,int binders){
return toStringImplImpl(operands,formatting,prec,binders);
}
}
}
class DPlus: DCommutAssocOp{
DExprSet operands;
alias subExprs=Seq!operands;
mixin ToString;
override @property Precedence precedence(){ return Precedence.plus; }
override @property string symbol(Format formatting,int binders){ return "+"; }
mixin Visitors;
static void insert(ref DExprSet summands,DExpr summand)in{assert(!!summand);}body{
if(summand==zero) return;
if(summand in summands){
summands.remove(summand);
insert(summands,2*summand);
}else{
summands.insert(summand);
}
}
static void insertAndSimplify(ref DExprSet summands,DExpr summand,DExpr facts){
// swCount++;sw.start(); scope(exit) sw.stop();
foreach(i;0..2){
if(auto dp=cast(DPlus)summand){
foreach(s;dp.summands)
insertAndSimplify(summands,s,facts);
return;
}
if(!i) summand=summand.simplify(facts);
}
if(auto p=cast(DPow)summand){
if(cast(DPlus)p.operands[0]){
auto expanded=expandPow(p);
if(expanded != p){
insertAndSimplify(summands,expanded,facts);
return;
}
}
}
DExpr combine(DExpr e1,DExpr e2,DExpr facts){
if(e1==zero) return e2;
if(e2==zero) return e1;
if(e1==e2) return (2*e1).simplify(facts);
static DExpr combineFractions(DExpr e1,DExpr e2){
if(auto q1=cast(Dℚ)e1)
if(auto q2=cast(Dℚ)e2)
return dℚ(q1.c+q2.c);
return null;
}
if(auto r=combineFractions(e1,e2)) return r.simplify(facts);
static DExpr combineWithFloat(DExpr e1,DExpr e2){
if(auto f=cast(DFloat)e1){
if(auto g=cast(DFloat)e2)
return (f.c+g.c).dFloat;
if(auto q2=cast(Dℚ)e2)
return (f.c+toReal(q2.c)).dFloat;
}
return null;
}
static DExpr combineFloat(DExpr e1,DExpr e2){
if(auto r=combineWithFloat(e1,e2)) return r;
if(auto r=combineWithFloat(e2,e1)) return r;
return null;
}
if(auto p1=cast(DPow)e1){
if(p1.operands[0]==mone){
if(auto p2=cast(DPow)e2){
if(p2.operands[0]==mone){
auto diff=(p1.operands[1]-p2.operands[1]).simplify(facts);
if(auto z=diff.isInteger()){
assert(z.c.den==1);
if(z.c.num&1) return zero;
return (2*e1).simplify(facts);
}
}
}
}
}
if(auto r=combineFloat(e1,e2)) return r;
if(auto r=recursiveCombine(e1,e2,facts))
return r;
static DExpr combineIvr(DExpr e1,DExpr e2,DExpr facts){
if(auto ivr1=cast(DIvr)e1){
if(ivr1.type==DIvr.Type.eqZ){
if(e2==dLtZ(ivr1.e).simplify(facts))
return dLeZ(ivr1.e);
if(e2==dGtZ(ivr1.e).simplify(facts))
return dGeZ(ivr1.e);
if(e2==dNeqZ(ivr1.e).simplify(facts))
return one;
}else if(ivr1.type==DIvr.Type.leZ){
if(e2==dGeZ(ivr1.e).simplify(facts))
return 2*dEqZ(ivr1.e)+dNeqZ(ivr1.e);
if(e2==dGtZ(ivr1.e).simplify(facts))
return one;
}
}
return null;
}
if(auto r=combineIvr(e1,e2,facts)) return r.simplify(facts);
if(auto r=combineIvr(e2,e1,facts)) return r.simplify(facts);
static DExpr combineIvr2(DExpr e1,DExpr e2,DExpr facts){
// If B → A and B ⇔ ¬C: [A∧ C] + [B] = [A]
if(cast(DIvr)e1 && cast(DIvr)e2) return null;
foreach(f;e1.factors) if(!cast(DIvr)f) return null;
foreach(f;e2.factors) if(!cast(DIvr)f) return null;
auto implied=one, notImplied=one;
foreach(f;e1.factors){
if(f.simplify(e2)==one) implied=implied*f;
else notImplied=notImplied*f;
}
if(implied != one){
notImplied=notImplied.simplify(facts); // C
static DExprSet active;
if(notImplied in active) return null; // detect cycles (TODO: can this be avoided?)
active.insert(notImplied); scope(exit) active.remove(notImplied);
if(dEqZ(notImplied).simplify(facts)==e2) // B ⇔ ¬ C
return implied.simplify(facts);
}
return null;
}
if(auto r=combineIvr2(e1,e2,facts)) return r.simplify(facts);
if(auto r=combineIvr2(e2,e1,facts)) return r.simplify(facts);
if(auto c1=cast(DMCase)e1)
if(auto c2=cast(DMCase)e2)