forked from vermaseren/form
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptimize.cc
4965 lines (4240 loc) · 135 KB
/
optimize.cc
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
/** @file optimize.cc
*
* experimental routines for the optimization of FORTRAN or C output.
*/
/* #[ License : */
/*
* Copyright (C) 1984-2022 J.A.M. Vermaseren
* When using this file you are requested to refer to the publication
* J.A.M.Vermaseren "New features of FORM" math-ph/0010025
* This is considered a matter of courtesy as the development was paid
* for by FOM the Dutch physics granting agency and we would like to
* be able to track its scientific use to convince FOM of its value
* for the community.
*
* This file is part of FORM.
*
* FORM is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* FORM is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along
* with FORM. If not, see <http://www.gnu.org/licenses/>.
*/
/*
#] License :
#[ includes :
*/
//#define DEBUG
//#define DEBUG_MORE
//#define DEBUG_MCTS
//#define DEBUG_GREEDY
#ifdef HAVE_CONFIG_H
#ifndef CONFIG_H_INCLUDED
#define CONFIG_H_INCLUDED
#include <config.h>
#endif
#endif
#include <vector>
#include <stack>
#include <algorithm>
#include <set>
#include <map>
#include <climits>
#include <cmath>
#include <string>
#include <algorithm>
#include <iostream>
#ifdef APPLE64
#define HAVE_UNORDERED_MAP
#define HAVE_UNORDERED_SET
#endif
#ifdef HAVE_UNORDERED_MAP
#include <unordered_map>
using std::unordered_map;
#elif !defined(HAVE_TR1_UNORDERED_MAP) && defined(HAVE_BOOST_UNORDERED_MAP_HPP)
#include <boost/unordered_map.hpp>
using boost::unordered_map;
#else
#include <tr1/unordered_map>
using std::tr1::unordered_map;
#endif
#ifdef HAVE_UNORDERED_SET
#include <unordered_set>
using std::unordered_set;
#elif !defined(HAVE_TR1_UNORDERED_SET) && defined(HAVE_BOOST_UNORDERED_SET_HPP)
#include <boost/unordered_set.hpp>
using boost::unordered_set;
#else
#include <tr1/unordered_set>
using std::tr1::unordered_set;
#endif
#if defined(HAVE_BUILTIN_POPCOUNT)
static inline int popcount(unsigned int x) {
return __builtin_popcount(x);
}
#elif defined(HAVE_POPCNT)
#include <intrin.h>
static inline int popcount(unsigned int x) {
return __popcnt(x);
}
#else
static inline int popcount(unsigned int x) {
int count = 0;
while (x > 0) {
if ((x & 1) == 1) count++;
x >>= 1;
}
return count;
}
#endif
extern "C" {
#include "form3.h"
}
//#ifdef DEBUG
#include "mytime.h"
//#endif
using namespace std;
// operators
const WORD OPER_ADD = -1;
const WORD OPER_MUL = -2;
const WORD OPER_COMMA = -3;
// class for a node of the MCTS tree
class tree_node {
public:
vector<tree_node> childs;
double sum_results;
int num_visits;
WORD var;
bool finished;
PADPOINTER(1,1,1,1);
tree_node (int _var=0):
sum_results(0), num_visits(0), var(_var), finished(false) {}
};
// global variables for multithreading
WORD *optimize_expr;
vector<vector<WORD> > optimize_best_Horner_schemes;
int optimize_num_vars;
int optimize_best_num_oper;
vector<WORD> optimize_best_instr;
vector<WORD> optimize_best_vars;
// global variables for MCTS
bool mcts_factorized, mcts_separated;
vector<WORD> mcts_vars;
tree_node mcts_root;
int mcts_expr_score;
set<pair<int,vector<WORD> > > mcts_best_schemes;
#ifdef WITHPTHREADS
pthread_mutex_t optimize_lock;
#endif
/*
#] includes :
#[ print_instr :
*/
void print_instr (const vector<WORD> &instr, WORD num)
{
const WORD *tbegin = &*instr.begin();
const WORD *tend = tbegin+instr.size();
for (const WORD *t=tbegin; t!=tend; t+=*(t+2)) {
MesPrint("<%d> %a",num,t[2],t);
}
}
/*
#] print_instr :
#[ my_random_shuffle :
*/
/** Random shuffle
*
* Description
* ===========
* Randomly permutes elements in the range [fr,to). Functionality is
* the same as C++'s "random_shuffle", but it uses Form's "wranf".
*/
template <class RandomAccessIterator>
void my_random_shuffle (PHEAD RandomAccessIterator fr, RandomAccessIterator to) {
for (int i=to-fr-1; i>0; --i)
swap (fr[i],fr[wranf(BHEAD0) % (i+1)]);
}
/*
#] my_random_shuffle :
#[ get_expression :
*/
static WORD comlist[3] = {TYPETOPOLYNOMIAL,3,DOALL};
/** Get expression
*
* Description
* ===========
* Reads an expression from the input file into a buffer (called
* optimize_expr). This buffer is used during the optimization
* process. Non-symbols are removed by ConvertToPoly and are put in
* temporary symbols.
*
* The return value is the length of the expression in WORDs, or a
* negative number if it failed.
*/
LONG get_expression (int exprnr) {
GETIDENTITY;
AR.NoCompress = 1;
NewSort(BHEAD0);
EXPRESSIONS e = Expressions+exprnr;
SetScratch(AR.infile,&(e->onfile));
// get header term
WORD *term = AT.WorkPointer;
GetTerm(BHEAD term);
NewSort(BHEAD0);
// get terms
while (GetTerm(BHEAD term) > 0) {
AT.WorkPointer = term + *term;
WORD *t1 = term;
WORD *t2 = term + *term;
if (ConvertToPoly(BHEAD t1,t2,comlist,1) < 0) return -1;
int n = *t2;
NCOPY(t1,t2,n);
AT.WorkPointer = term + *term;
if (StoreTerm(BHEAD term)) return -1;
}
// sort and store in buffer
LONG len = EndSort(BHEAD (WORD *)((VOID *)(&optimize_expr)),2);
LowerSortLevel();
AT.WorkPointer = term;
return len;
}
/*
#] get_expression :
#[ PF_get_expression :
*/
#ifdef WITHMPI
// get_expression for ParFORM
LONG PF_get_expression (int exprnr) {
LONG len;
if (PF.me == MASTER) {
len = get_expression(exprnr);
}
if (PF.numtasks > 1) {
PF_BroadcastBuffer(&optimize_expr, &len);
}
return len;
}
// replace get_expression called in Optimize
#define get_expression PF_get_expression
#endif
/*
#] PF_get_expression :
#[ get_brackets :
*/
/** Get brackets
*
* Description
* ===========
* Checks whether the input expression (stored in optimize_expr)
* contains brackets. If so, this method replaces terms outside
* brackets by powers of SEPERATESYMBOL (equal brackets have equal
* powers) and the brackets are returned. If not, the result is
* empty.
*
* Brackets are used for simultaneous optimization. The symbol
* SEPARATESYMBOL is always the first one used in a Horner scheme.
*/
vector<vector<WORD> > get_brackets () {
// check for brackets in expression
bool has_brackets = false;
for (WORD *t=optimize_expr; *t!=0; t+=*t) {
WORD *tend=t+*t; tend-=ABS(*(tend-1));
for (WORD *t1=t+1; t1<tend; t1+=*(t1+1))
if (*t1 == HAAKJE)
has_brackets=true;
}
// replace brackets by SEPARATESYMBOL
vector<vector<WORD> > brackets;
if (has_brackets) {
int exprlen=10; // we need potential space for an empty bracket
for (WORD *t=optimize_expr; *t!=0; t+=*t)
exprlen += *t;
WORD *newexpr = (WORD *)Malloc1(exprlen*sizeof(WORD), "optimize newexpr");
int i=0;
int sep_power = 0;
for (WORD *t=optimize_expr; *t!=0; t+=*t) {
WORD *t1 = t+1;
// scan for bracket
vector<WORD> bracket;
for (; *t1!=HAAKJE; t1+=*(t1+1))
bracket.insert(bracket.end(), t1, t1+*(t1+1));
if (brackets.size()==0 || bracket!=brackets.back()) {
sep_power++;
brackets.push_back(bracket);
}
t1+=*(t1+1);
WORD left = t + *t - t1;
bool more_symbols = (left != ABS(*(t+*t-1)));
// add power of SEPARATESYMBOL
newexpr[i++] = 1 + left + (more_symbols ? 2 : 4);
newexpr[i++] = SYMBOL;
newexpr[i++] = (more_symbols ? *(t1+1) + 2 : 4);
newexpr[i++] = SEPARATESYMBOL;
newexpr[i++] = sep_power;
// add remaining terms
if (more_symbols) {
t1+=2;
left-=2;
}
while (left-->0)
newexpr[i++] = *(t1++);
}
/*
We insert here an empty bracket that is zero.
It is used for the case that there is only a single bracket which is
outside the notation for trees at a later stage.
There may be a problem now in that in the case of sep_power==1
newexpr is bigger than optimize_expr. We have to check that.
*/
if ( sep_power == 1 )
{
WORD *t;
vector<WORD> bracket;
bracket.push_back(0);
bracket.push_back(0);
bracket.push_back(0);
bracket.push_back(0);
sep_power++;
brackets.push_back(bracket);
newexpr[i++] = 8;
newexpr[i++] = SYMBOL;
newexpr[i++] = 4;
newexpr[i++] = SEPARATESYMBOL;
newexpr[i++] = sep_power;
newexpr[i++] = 1;
newexpr[i++] = 1;
newexpr[i++] = 3;
newexpr[i++] = 0;
for (t=optimize_expr; *t!=0; t+=*t) {}
if ( t-optimize_expr+1 < i ) { // We have to redo this
M_free(optimize_expr,"$-sort space");
optimize_expr = (WORD *)Malloc1(i*sizeof(WORD),"$-sort space");
}
}
else {
newexpr[i++] = 0;
}
memcpy(optimize_expr, newexpr, i*sizeof(WORD));
M_free(newexpr,"optimize newexpr");
// if factorized, replace SEP by FAC and remove brackets
if (brackets[0].size()>0 && brackets[0][2]==FACTORSYMBOL) {
for (WORD *t=optimize_expr; *t!=0; t+=*t) {
if (*t == ABS(*(t+*t-1))+1) continue;
if (t[1]==SYMBOL)
for (int i=3; i<t[2]; i+=2)
if (t[i]==SEPARATESYMBOL) t[i]=FACTORSYMBOL;
}
return vector<vector<WORD> >();
}
}
return brackets;
}
/*
#] get_brackets :
#[ count_operators :
*/
/** Count operators
*
* Description
* ===========
* Counts the number of operators in a Form-style expression.
*/
int count_operators (const WORD *expr, bool print=false) {
int n=0;
while (*(expr+n)!=0) n+=*(expr+n);
int cntpow=0, cntmul=0, cntadd=0, sumpow=0;
WORD maxpowfac=1, maxpowsep=1;
for (const WORD *t=expr; *t!=0; t+=*t) {
if (t!=expr) cntadd++; // new term
if (*t==ABS(*(t+*t-1))+1) continue; // only coefficient
int cntsym=0;
if (t[1]==SYMBOL)
for (int i=3; i<t[2]; i+=2) {
if (t[i]==FACTORSYMBOL) {
maxpowfac = max(maxpowfac, t[i+1]);
continue;
}
if (t[i]==SEPARATESYMBOL) {
maxpowsep = max(maxpowsep, t[i+1]);
continue;
}
if (t[i+1]>2) { // (extra)symbol power>2
cntpow++;
sumpow += (int)floor(log(t[i+1])/log(2.0)) + popcount(t[i+1]) - 1;
}
if (t[i+1]==2) cntmul++; // (extra)symbol squared
cntsym++;
}
if (ABS(*(t+*t-1))!=3 || *(t+*t-2)!=1 || *(t+*t-3)!=1) cntsym++; // non +/-1 coefficient
if (cntsym > 0) cntmul+=cntsym-1;
}
cntadd -= maxpowfac-1;
cntmul += maxpowfac-1;
cntadd -= maxpowsep-1;
if (print)
MesPrint ("*** STATS: original %lP %lM %lA : %l", cntpow,cntmul,cntadd,sumpow+cntmul+cntadd);
return sumpow+cntmul+cntadd;
}
/** Count operators
*
* Description
* ===========
* Counts the number of operators in a vector of instructions
*/
int count_operators (const vector<WORD> &instr, bool print=false) {
int cntpow=0, cntmul=0, cntadd=0, sumpow=0;
const WORD *ebegin = &*instr.begin();
const WORD *eend = ebegin+instr.size();
for (const WORD *e=ebegin; e!=eend; e+=*(e+2)) {
for (const WORD *t=e+3; *t!=0; t+=*t) {
if (t!=e+3) {
if (*(e+1)==OPER_ADD) cntadd++; // new term
if (*(e+1)==OPER_MUL) cntmul++; // new term
}
if (*t == ABS(*(t+*t-1))+1) continue; // only coefficient
if (*(t+1)==SYMBOL || *(t+1)==EXTRASYMBOL) {
if (*(t+4)==2) cntmul++; // (extra)symbol squared
if (*(t+4)>2) { // (extra)symbol power>2
cntpow++;
sumpow += (int)floor(log(*(t+4))/log(2.0)) + popcount(*(t+4)) - 1;
}
}
if (ABS(*(t+*t-1))!=3 || *(t+*t-2)!=1 || *(t+*t-3)!=1) cntmul++; // non +/-1 coefficient
}
}
if (print)
MesPrint ("*** STATS: optimized %lP %lM %lA : %l", cntpow,cntmul,cntadd,sumpow+cntmul+cntadd);
return sumpow+cntmul+cntadd;
}
/*
#] count_operators :
#[ occurrence_order :
*/
/** Occurrence order
*
* Description
* ===========
* Extracts all variables from an expression and sorts them with
* most occurring first (or last, with rev=true)
*/
vector<WORD> occurrence_order (const WORD *expr, bool rev) {
// count the number of occurrences of variables
map<WORD,int> cnt;
for (const WORD *t=expr; *t!=0; t+=*t) {
if (*t == ABS(*(t+*t-1))+1) continue; // skip constant term
if (t[1] == SYMBOL)
for (int i=3; i<t[2]; i+=2)
cnt[t[i]]++;
}
bool is_fac=false, is_sep=false;
if (cnt.count(FACTORSYMBOL)) {
is_fac=true;
cnt.erase(FACTORSYMBOL);
}
if (cnt.count(SEPARATESYMBOL)) {
is_sep=true;
cnt.erase(SEPARATESYMBOL);
}
// determine the order of the variables
vector<pair<int,WORD> > cnt_order;
for (map<WORD,int>::iterator i=cnt.begin(); i!=cnt.end(); i++)
cnt_order.push_back(make_pair(i->second, i->first));
sort(cnt_order.rbegin(), cnt_order.rend());
// create resulting order
vector<WORD> order;
for (int i=0; i<(int)cnt_order.size(); i++)
order.push_back(cnt_order[i].second);
if (rev) reverse(order.begin(),order.end());
// add FACTORSYMBOL/SEPARATESYMBOL
if (is_fac) order.insert(order.begin(), FACTORSYMBOL);
if (is_sep) order.insert(order.begin(), SEPARATESYMBOL);
return order;
}
/*
#] occurrence_order :
#[ Horner_tree :
*/
/** Horner tree building
*
* Description
* ===========
* Given a Form-style expression (in a buffer in memory), this
* builds an expression tree. The tree is determined by a
* multivariate Horner scheme, i.e., something of the form:
*
* 1+y+x*(2+y*(1+y)+x*(3-y*(...)))
*
* The order of the variables is given to the method "Horner_tree",
* which renumbers ad reorders the terms of the expression. Next,
* the recursive method "build_Horner_tree" does the actual tree
* construction.
*
* The tree is represented in postfix notation. Tokens are of the
* following forms:
*
* - SNUMBER tokenlength num den coefflength
* - SYMBOL tokenlength variable power
* - OPER_ADD or OPER_MUL
*
* Note
* ====
* Sets AN.poly_num_vars and allocates AN.poly_vars. The latter
* should be freed later.
*/
/** Get power of variable (helper function for build_Horner_tree)
*
* Description
* ===========
* Returns the power of the variable "var", which is at position
* "pos" in this term, if it is present.
*/
WORD getpower (const WORD *term, int var, int pos) {
if (*term == ABS(*(term+*term-1))+1) return 0; // constant term
if (2*pos+2 >= term[2]) return 0; // too few symbols
if (term[2*pos+3] != var) return 0; // incorrect symbol
return term[2*pos+4]; // return power
}
/** Call GcdLong/DivLong with leading zeroes
*
* Description
* ===========
* These method remove leading zeroes, so that GcdLong and DivLong
* can safely be called.
*/
void fixarg (UWORD *t, WORD &n) {
int an=ABS(n), sn=SGN(n);
while (*(t+an-1)==0) an--;
n=an*sn;
}
void GcdLong_fix_args (PHEAD UWORD *a, WORD na, UWORD *b, WORD nb, UWORD *c, WORD *nc) {
fixarg(a,na);
fixarg(b,nb);
GcdLong(BHEAD a,na,b,nb,c,nc);
}
void DivLong_fix_args(UWORD *a, WORD na, UWORD *b, WORD nb, UWORD *c, WORD *nc, UWORD *d, WORD *nd) {
fixarg(a,na);
fixarg(b,nb);
DivLong(a,na,b,nb,c,nc,d,nd);
}
/** Build the Horner tree
*
* Description
* ===========
* Constructs the Horner tree. The method processes one variable and
* continues recursively until the Horner scheme is completed.
*
* "terms" is a pointer to the starts of the terms. "numterms" is
* the number of terms to be processed. "var" is the next variable
* to be processed (index between 0 and #maxvar) and "maxvar" is the
* last variable to be processed, so that partial Horner trees can
* also be constructed. "pos" is the position that the power of
* "var" should be in (one level further in the recursion, "pos" has
* increased by 0 or 1 depending on whether the previous power was 0
* or not). The result is written at the pointer "res".
*
* This method also factors out gcds of the coefficients. The result
* should end with "gcd OPER_MUL" at all times, so that one level
* higher gcds can be extracted again.
*/
void build_Horner_tree (const WORD **terms, int numterms, int var, int maxvar, int pos, vector<WORD> *res) {
GETIDENTITY;
if (var == maxvar) {
// Horner tree is finished, so add remaining terms unfactorized
// (note: since only complete Horner schemes seem to be useful, numterms=1 here
for (int fr=0; fr<numterms; fr++) {
bool empty = true;
const WORD *t = terms[fr];
// add symbols
if (*t != ABS(*(t+*t-1))+1)
for (int i=3+2*pos; i<t[2]; i+=2) {
res->push_back(SYMBOL);
res->push_back(4);
res->push_back(t[i]);
res->push_back(t[i+1]);
if (!empty) res->push_back(OPER_MUL);
empty = false;
}
// if empty, add a 1, since the result should look like "... coeff *"
if (empty) {
res->push_back(SNUMBER);
res->push_back(5);
res->push_back(1);
res->push_back(1);
res->push_back(3);
}
// add coefficient
res->push_back(SNUMBER);
WORD n = ABS(*(t+*t-1));
res->push_back(n+2);
for (int i=0; i<n; i++)
res->push_back(*(t+*t-n+i));
res->push_back(OPER_MUL);
if (fr>0) res->push_back(OPER_ADD);
}
// result should end with gcd of the terms; right now this never
// triggers, but if one would allow for incomplete Horner schemes,
// one should extract the gcd here
if (numterms > 1) {
res->push_back(SNUMBER);
res->push_back(5);
res->push_back(1);
res->push_back(1);
res->push_back(3);
res->push_back(OPER_MUL);
}
}
else {
// extract variable "var" and the gcd and proceed recursively
WORD nnum = 0, nden = 0, ntmp = 0, ndum = 0;
UWORD *num = NumberMalloc("build_Horner_tree");
UWORD *den = NumberMalloc("build_Horner_tree");
UWORD *tmp = NumberMalloc("build_Horner_tree");
UWORD *dum = NumberMalloc("build_Horner_tree");
// previous coefficient for gcd extraction or coefficient multiplication
int prev_coeff_idx = -1;
for (int fr=0; fr<numterms;) {
// find power of current term
WORD pow = getpower(terms[fr], var, pos);
// find all terms with that power
int to=fr+1;
while (to<numterms && getpower(terms[to], var, pos) == pow) to++;
// recursively build Horner tree of all terms proportional to var^pow
build_Horner_tree (terms+fr, to-fr, var+1, maxvar, pow==0?pos:pos+1, res);
if (AN.poly_vars[var] != FACTORSYMBOL && AN.poly_vars[var] != SEPARATESYMBOL) {
// if normal symbol, find gcd(numerators) and gcd(denominators)
WORD n1 = res->at(res->size()-2) / 2;
WORD *t1 = &res->at(res->size()-2-2*ABS(n1));
WORD *t2 = fr==0 ? t1 : &res->at(prev_coeff_idx);
WORD n2 = fr==0 ? n1 : *(t2+*(t2+1)-1) / 2;
if (fr>0) t2+=2;
GcdLong_fix_args(BHEAD (UWORD *)t1,n1,(UWORD *)t2,n2,num,&nnum);
GcdLong_fix_args(BHEAD (UWORD *)t1+ABS(n1),ABS(n1),(UWORD *)t2+ABS(n2),ABS(n2),den,&nden);
// divide out gcds; note: leading zeroes can be added here
for (int i=0; i<2; i++) {
if (i==1 && fr==0) break;
WORD *t = i==0 ? t1 : t2;
WORD n = i==0 ? n1 : n2;
DivLong_fix_args((UWORD *)t, n, num, nnum, tmp, &ntmp, dum, &ndum);
for (int j=0; j<ABS(ntmp); j++) *t++ = tmp[j];
for (int j=0; j<ABS(n)-ABS(ntmp); j++) *t++ = 0;
if (SGN(ntmp) != SGN(n)) n=-n;
DivLong_fix_args((UWORD *)t, n, den, nden, tmp, &ntmp, dum, &ndum);
for (int j=0; j<ABS(ntmp); j++) *t++ = tmp[j];
for (int j=0; j<ABS(n)-ABS(ntmp); j++) *t++ = 0;
*t++ = SGN(n) * (2*ABS(n)+1);
}
// add the addition operator
if (fr>0) res->push_back(OPER_ADD);
// add the power of "var"
WORD nextpow = (to==numterms ? 0 : getpower(terms[to], var, pos));
if (pow-nextpow > 0) {
res->push_back(SYMBOL);
res->push_back(4);
res->push_back(var);
res->push_back(pow-nextpow);
res->push_back(OPER_MUL);
}
// add the extracted gcd
res->push_back(SNUMBER);
WORD n = MaX(ABS(nnum),nden);
res->push_back(n*2+3);
for (int i=0; i<ABS(nnum); i++) res->push_back(num[i]);
for (int i=0; i<n-ABS(nnum); i++) res->push_back(0);
for (int i=0; i<nden; i++) res->push_back(den[i]);
for (int i=0; i<n-ABS(nden); i++) res->push_back(0);
res->push_back(SGN(nnum)*(2*n+1));
res->push_back(OPER_MUL);
prev_coeff_idx = res->size() - ABS(res->at(res->size()-2)) - 3;
}
else if (AN.poly_vars[var]==FACTORSYMBOL) {
// if factorsymbol, multiply overall integer contents
if (fr>0) {
WORD n1 = res->at(res->size()-2) / 2;
WORD *t1 = &res->at(res->size()-2-2*ABS(n1));
WORD *t2 = &res->at(prev_coeff_idx);
WORD n2 = *(t2+*(t2+1)-1) / 2;
t2+=2;
MulRat(BHEAD (UWORD *)t1,n1,(UWORD *)t2,n2,tmp,&ntmp);
// replace previous coefficient with 1
n2=ABS(n2);
for (int i=0; i<ABS(n2); i++)
t2[i] = t2[n2+i] = i==0 ? 1 : 0;
t2[2*n2] = 2*n2+1;
// remove this coefficient
for (int i=0; i<2*ABS(n1)+2; i++)
res->pop_back();
// add product
res->back() = 2*ABS(ntmp)+3; // adjust size of term
res->insert(res->end(), tmp, tmp+2*ABS(ntmp)); // num/den coefficient
res->push_back(SGN(ntmp)*(2*ABS(ntmp)+1)); // size of coefficient
res->push_back(OPER_MUL); // operator
}
prev_coeff_idx = res->size() - ABS(res->at(res->size()-2)) - 3;
// multiply previous factors with this factor
if (fr>0)
res->push_back(OPER_MUL);
}
else { // AN.poly_vars[var]==SEPARATESYMBOL
if (fr>0)
res->push_back(OPER_COMMA);
prev_coeff_idx = -1;
}
fr=to;
}
// cleanup
NumberFree(dum,"build_Horner_tree");
NumberFree(tmp,"build_Horner_tree");
NumberFree(den,"build_Horner_tree");
NumberFree(num,"build_Horner_tree");
}
}
/** Term compare (helper function for Horner_tree)
*
* Description
* ===========
* Compares two terms of the form "L SYM 4 x n coeff" or "L
* coeff". Lower powers of lower-indexed symbols come first. This is
* used to sort the terms in correct order.
*/
bool term_compare (const WORD *a, const WORD *b) {
if (*a == ABS(*(a+*a-1))+1) return true; // coefficient comes first
if (*b == ABS(*(b+*b-1))+1) return false;
if (a[1]!=SYMBOL) return true;
if (b[1]!=SYMBOL) return false;
for (int i=3; i<a[2] && i<b[2]; i+=2) {
if (a[i] !=b[i] ) return a[i] >b[i];
if (a[i+1]!=b[i+1]) return a[i+1]<b[i+1];
}
return a[2]<b[2];
}
/** Prepare Horner tree building
*
* Description
* ===========
* This method renumbers the variables to 0...#vars-1 according to
* the specified order. Next, it stored pointer to individual terms
* and sorts the terms with higher power first. Then the sorted
* lists of power is used for the construction of the Horner tree.
*/
vector<WORD> Horner_tree (const WORD *expr, const vector<WORD> &order) {
#ifdef DEBUG
MesPrint ("*** [%s, w=%w] CALL: Horner_tree(%a)", thetime_str().c_str(), order.size(), &order[0]);
#endif
GETIDENTITY;
// find the renumbering scheme (new numbers are 0,1,...,#vars-1)
map<WORD,WORD> renum;
AN.poly_num_vars = order.size();
AN.poly_vars = (WORD *)Malloc1(AN.poly_num_vars*sizeof(WORD), "AN.poly_vars");
for (int i=0; i<AN.poly_num_vars; i++) {
AN.poly_vars[i] = order[i];
renum[order[i]] = i;
}
// sort variables in individual terms using bubble sort
WORD *sorted = AT.WorkPointer;
for (const WORD *t=expr; *t!=0; t+=*t) {
memcpy(sorted, t, *t*sizeof(WORD));
if (*t != ABS(*(t+*t-1))+1) {
// non-constant term
// renumber variables, adding new variables if necessary
for (int i=3; i<sorted[2]; i+=2) {
if (!renum.count(sorted[i])) {
renum[sorted[i]] = AN.poly_num_vars;
WORD *new_poly_vars = (WORD *)Malloc1((AN.poly_num_vars+1)*sizeof(WORD), "AN.poly_vars");
memcpy(new_poly_vars, AN.poly_vars, AN.poly_num_vars*sizeof(WORD));
M_free(AN.poly_vars,"poly_vars");
AN.poly_vars = new_poly_vars;
AN.poly_vars[AN.poly_num_vars] = sorted[i];
AN.poly_num_vars++;
}
sorted[i] = renum[sorted[i]];
}
// order variables
for (int i=0; i<sorted[2]/2; i++)
for (int j=3; j+2<sorted[2]; j+=2)
if (sorted[j] > sorted[j+2]) {
swap(sorted[j] , sorted[j+2]);
swap(sorted[j+1], sorted[j+3]);
}
}
sorted += *sorted;
}
*sorted = 0;
sorted = AT.WorkPointer;
// find pointers to all terms and sort them efficiently
vector<const WORD *> terms;
for (const WORD *t=sorted; *t!=0; t+=*t)
terms.push_back(t);
sort(terms.rbegin(),terms.rend(),term_compare);
// construct the Horner tree
vector<WORD> res;
build_Horner_tree(&terms[0], terms.size(), 0, AN.poly_num_vars, 0, &res);
// remove leading zeroes in coefficients
int j=0;
for (int i=0; i<(int)res.size();) {
if (res[i]==OPER_ADD || res[i]==OPER_MUL || res[i]==OPER_COMMA)
res[j++] = res[i++];
else if (res[i]==SYMBOL) {
memmove(&res[j], &res[i], res[i+1]*sizeof(WORD));
i+=res[j+1];
j+=res[j+1];
}
else if (res[i]==SNUMBER) {
int n = (res[i+1]-2)/2;
int dn = 0;
while (res[i+1+n-dn]==0 && res[i+1+2*n-dn]==0) dn++;
res[j++] = SNUMBER;
res[j++] = 2*(n-dn) + 3;
memmove(&res[j], &res[i+2], (n-dn)*sizeof(WORD));
j+=n-dn;
memmove(&res[j], &res[i+n+2], (n-dn)*sizeof(WORD));
j+=n-dn;
res[j++] = SGN(res[i+2*n+2])*(2*(n-dn)+1);
i+=2*n+3;
}
}
res.resize(j);
#ifdef DEBUG
MesPrint ("*** [%s, w=%w] DONE: Horner_tree(%a)", thetime_str().c_str(), order.size(), &order[0]);
#endif
return res;
}
/*
#] Horner_tree :
#[ print_tree :
*/
// print Horner tree (for debugging)
void print_tree (const vector<WORD> &tree) {
GETIDENTITY;
for (int i=0; i<(int)tree.size();) {
if (tree[i]==OPER_ADD) {
MesPrint("+%");
i++;
}
else if (tree[i]==OPER_MUL) {
MesPrint("*%");
i++;
}
else if (tree[i]==OPER_COMMA) {
MesPrint(",%");
i++;
}
else if (tree[i]==SNUMBER) {
UBYTE buf[100];
int n = tree[i+tree[i+1]-1]/2;
PrtLong((UWORD *)&tree[i+2], n, buf);
int l = strlen((char *)buf);
buf[l]='/';
n=ABS(n);
PrtLong((UWORD *)&tree[i+2+n], n, buf+l+1);
MesPrint("%s%",buf);
i+=tree[i+1];
}
else if (tree[i]==SYMBOL) {
if (AN.poly_vars[tree[i+2]] < 10000)
MesPrint("%s^%d%", VARNAME(symbols,AN.poly_vars[tree[i+2]]), tree[i+3]);
else
MesPrint("Z%d^%d%", MAXVARIABLES-AN.poly_vars[tree[i+2]], tree[i+3]);
i+=tree[i+1];
}
else {
MesPrint("error");
exit(1);
}
MesPrint(" %");
}
MesPrint("");
}