23ccaa961f3f72c198f02e848069c6a2724382fc
[ginac.git] / ginac / expairseq.cpp
1 /** @file expairseq.cpp
2  *
3  *  GiNaC Copyright (C) 1999 Johannes Gutenberg University Mainz, Germany
4  *
5  *  This program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 2 of the License, or
8  *  (at your option) any later version.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with this program; if not, write to the Free Software
17  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19
20 #include <algorithm>
21 #include <string>
22 #include <stdexcept>
23
24 #include "expairseq.h"
25 #include "lst.h"
26
27 #ifdef EXPAIRSEQ_USE_HASHTAB
28 #error "!!!!!!!!TODO: expair_needs_further_processing not yet implemented for hashtabs, sorry. A.F."
29 #endif // def EXPAIRSEQ_USE_HASHTAB
30
31 //////////
32 // helper classes
33 //////////
34
35 class epp_is_less
36 {
37 public:
38     bool operator()(epp const & lh, epp const & rh) const
39     {
40         return (*lh).is_less(*rh);
41     }
42 };
43
44 //////////
45 // default constructor, destructor, copy constructor assignment operator and helpers
46 //////////
47
48 // public
49
50 expairseq::expairseq(expairseq const & other)
51 {
52     debugmsg("expairseq copy constructor",LOGLEVEL_CONSTRUCT);
53     copy(other);
54 }
55
56 expairseq const & expairseq::operator=(expairseq const & other)
57 {
58     debugmsg("expairseq operator=",LOGLEVEL_ASSIGNMENT);
59     if (this != &other) {
60         destroy(1);
61         copy(other);
62     }
63     return *this;
64 }
65
66 // protected
67
68 void expairseq::copy(expairseq const & other)
69 {
70     basic::copy(other);
71     seq=other.seq;
72     overall_coeff=other.overall_coeff;
73 #ifdef EXPAIRSEQ_USE_HASHTAB
74     // copy hashtab
75     hashtabsize=other.hashtabsize;
76     if (hashtabsize!=0) {
77     hashmask=other.hashmask;
78         hashtab.resize(hashtabsize);
79         epvector::const_iterator osb=other.seq.begin();
80         for (unsigned i=0; i<hashtabsize; ++i) {
81             hashtab[i].clear();
82             for (epplist::const_iterator cit=other.hashtab[i].begin();
83                  cit!=other.hashtab[i].end(); ++cit) {
84                 hashtab[i].push_back(seq.begin()+((*cit)-osb));
85             }
86         }
87     } else {
88         hashtab.clear();
89     }
90 #endif // def EXPAIRSEQ_USE_HASHTAB
91 }
92
93 //////////
94 // other constructors
95 //////////
96
97 expairseq::expairseq(ex const & lh, ex const & rh) : basic(TINFO_expairseq)
98 {
99     debugmsg("expairseq constructor from ex,ex",LOGLEVEL_CONSTRUCT);
100     construct_from_2_ex(lh,rh);
101     ASSERT(is_canonical());
102 }
103
104 expairseq::expairseq(exvector const & v) : basic(TINFO_expairseq)
105 {
106     debugmsg("expairseq constructor from exvector",LOGLEVEL_CONSTRUCT);
107     construct_from_exvector(v);
108     ASSERT(is_canonical());
109 }
110
111 /*
112 expairseq::expairseq(epvector const & v, bool do_not_canonicalize) :
113     basic(TINFO_expairseq)
114 {
115     debugmsg("expairseq constructor from epvector",LOGLEVEL_CONSTRUCT);
116     if (do_not_canonicalize) {
117         seq=v;
118 #ifdef EXPAIRSEQ_USE_HASHTAB
119         combine_same_terms(); // to build hashtab
120 #endif // def EXPAIRSEQ_USE_HASHTAB
121     } else {
122         construct_from_epvector(v);
123     }
124     ASSERT(is_canonical());
125 }
126 */
127
128 expairseq::expairseq(epvector const & v, ex const & oc) :
129     basic(TINFO_expairseq), overall_coeff(oc)
130 {
131     debugmsg("expairseq constructor from epvector,ex",LOGLEVEL_CONSTRUCT);
132     construct_from_epvector(v);
133     ASSERT(is_canonical());
134 }
135
136 expairseq::expairseq(epvector * vp, ex const & oc) :
137     basic(TINFO_expairseq), overall_coeff(oc)
138 {
139     debugmsg("expairseq constructor from epvector *,ex",LOGLEVEL_CONSTRUCT);
140     ASSERT(vp!=0);
141     construct_from_epvector(*vp);
142     delete vp;
143     ASSERT(is_canonical());
144 }
145
146 //////////
147 // functions overriding virtual functions from bases classes
148 //////////
149
150 // public
151
152 basic * expairseq::duplicate() const
153 {
154     debugmsg("expairseq duplicate",LOGLEVEL_DUPLICATE);
155     return new expairseq(*this);
156 }
157
158 bool expairseq::info(unsigned inf) const
159 {
160     return basic::info(inf);
161 }
162
163 int expairseq::nops() const
164 {
165     if (overall_coeff.is_equal(default_overall_coeff())) {
166         return seq.size();
167     }
168     return seq.size()+1;
169 }
170
171 ex expairseq::op(int const i) const
172 {
173     if (unsigned(i)<seq.size()) {
174         return recombine_pair_to_ex(seq[i]);
175     }
176     ASSERT(!overall_coeff.is_equal(default_overall_coeff()));
177     return overall_coeff;
178 }
179
180 ex & expairseq::let_op(int const i)
181 {
182     throw(std::logic_error("let_op not defined for expairseq and derived classes (add,mul,...)"));
183 }
184
185 ex expairseq::eval(int level) const
186 {
187     if ((level==1)&&(flags & status_flags::evaluated)) {
188         return *this;
189     }
190
191     epvector * vp=evalchildren(level);
192     if (vp==0) {
193         return this->hold();
194     }
195
196     return (new expairseq(vp,overall_coeff))
197                ->setflag(status_flags::dynallocated |
198                          status_flags::evaluated );
199 }
200
201 ex expairseq::evalf(int level) const
202 {
203     return thisexpairseq(evalfchildren(level),overall_coeff);
204 }
205
206 ex expairseq::normal(lst &sym_lst, lst &repl_lst, int level) const
207 {
208     ex n=thisexpairseq(normalchildren(level),overall_coeff);
209     return n.bp->basic::normal(sym_lst,repl_lst,level);
210 }
211
212 ex expairseq::subs(lst const & ls, lst const & lr) const
213 {
214     epvector * vp=subschildren(ls,lr);
215     if (vp==0) {
216         return *this;
217     }
218     return thisexpairseq(vp,overall_coeff);
219 }
220
221 // protected
222
223 int expairseq::compare_same_type(basic const & other) const
224 {
225     ASSERT(is_of_type(other, expairseq));
226     expairseq const & o=static_cast<expairseq const &>(const_cast<basic &>(other));
227
228     int cmpval;
229     
230     // compare number of elements
231     if (seq.size() != o.seq.size()) {
232         return (seq.size()<o.seq.size()) ? -1 : 1;
233     }
234
235     // compare overall_coeff
236     cmpval=overall_coeff.compare(o.overall_coeff);
237     if (cmpval!=0) return cmpval;
238
239     //if (seq.size()==0) return 0; // empty expairseq's are equal
240
241 #ifdef EXPAIRSEQ_USE_HASHTAB
242     ASSERT(hashtabsize==o.hashtabsize);
243     if (hashtabsize==0) {
244 #endif // def EXPAIRSEQ_USE_HASHTAB
245         epvector::const_iterator cit1=seq.begin();
246         epvector::const_iterator cit2=o.seq.begin();
247         epvector::const_iterator last1=seq.end();
248         epvector::const_iterator last2=o.seq.end();
249         
250         for (; (cit1!=last1)&&(cit2!=last2); ++cit1, ++cit2) {
251             cmpval=(*cit1).compare(*cit2);
252             if (cmpval!=0) return cmpval;
253         }
254
255         ASSERT(cit1==last1);
256         ASSERT(cit2==last2);
257         
258         return 0;
259 #ifdef EXPAIRSEQ_USE_HASHTAB
260     }
261
262     // compare number of elements in each hashtab entry
263     for (unsigned i=0; i<hashtabsize; ++i) {
264         unsigned cursize=hashtab[i].size();
265         if (cursize != o.hashtab[i].size()) {
266             return (cursize < o.hashtab[i].size()) ? -1 : 1;
267         }
268     }
269     
270     // compare individual (sorted) hashtab entries
271     for (unsigned i=0; i<hashtabsize; ++i) {
272         unsigned sz=hashtab[i].size();
273         if (sz>0) {
274             epplist const & eppl1=hashtab[i];
275             epplist const & eppl2=o.hashtab[i];
276             epplist::const_iterator it1=eppl1.begin();
277             epplist::const_iterator it2=eppl2.begin();
278             while (it1!=eppl1.end()) {
279                 cmpval=(*(*it1)).compare(*(*it2));
280                 if (cmpval!=0) return cmpval;
281                 ++it1;
282                 ++it2;
283             }
284         }
285     }
286     
287     return 0; // equal
288 #endif // def EXPAIRSEQ_USE_HASHTAB
289 }
290
291 bool expairseq::is_equal_same_type(basic const & other) const
292 {
293     expairseq const & o=dynamic_cast<expairseq const &>(const_cast<basic &>(other));
294
295     // compare number of elements
296     if (seq.size() != o.seq.size()) return false;
297
298     // compare overall_coeff
299     if (!overall_coeff.is_equal(o.overall_coeff)) return false;
300
301 #ifdef EXPAIRSEQ_USE_HASHTAB
302     // compare number of elements in each hashtab entry
303     if (hashtabsize!=o.hashtabsize) {
304         cout << "this:" << endl;
305         printtree(cout,0);
306         cout << "other:" << endl;
307         other.printtree(cout,0);
308     }
309         
310     ASSERT(hashtabsize==o.hashtabsize);
311     
312     if (hashtabsize==0) {
313 #endif // def EXPAIRSEQ_USE_HASHTAB
314         epvector::const_iterator cit1=seq.begin();
315         epvector::const_iterator cit2=o.seq.begin();
316         epvector::const_iterator last1=seq.end();
317         
318         while (cit1!=last1) {
319             if (!(*cit1).is_equal(*cit2)) return false;
320             ++cit1;
321             ++cit2;
322         }
323         
324         return true;
325 #ifdef EXPAIRSEQ_USE_HASHTAB
326     }
327
328     for (unsigned i=0; i<hashtabsize; ++i) {
329         if (hashtab[i].size() != o.hashtab[i].size()) return false;
330     }
331
332     // compare individual sorted hashtab entries
333     for (unsigned i=0; i<hashtabsize; ++i) {
334         unsigned sz=hashtab[i].size();
335         if (sz>0) {
336             epplist const & eppl1=hashtab[i];
337             epplist const & eppl2=o.hashtab[i];
338             epplist::const_iterator it1=eppl1.begin();
339             epplist::const_iterator it2=eppl2.begin();
340             while (it1!=eppl1.end()) {
341                 if (!(*(*it1)).is_equal(*(*it2))) return false;
342                 ++it1;
343                 ++it2;
344             }
345         }
346     }
347
348     return true;
349 #endif // def EXPAIRSEQ_USE_HASHTAB
350 }
351
352 unsigned expairseq::return_type(void) const
353 {
354     return return_types::noncommutative_composite;
355 }
356
357 unsigned expairseq::calchash(void) const
358 {
359     unsigned v=golden_ratio_hash(tinfo());
360     epvector::const_iterator last=seq.end();
361     for (epvector::const_iterator cit=seq.begin(); cit!=last; ++cit) {
362 #ifndef EXPAIRSEQ_USE_HASHTAB
363         v=rotate_left_31(v); // rotation would spoil commutativity
364 #endif // ndef EXPAIRSEQ_USE_HASHTAB
365         v ^= (*cit).rest.gethash();
366     }
367
368     v ^= overall_coeff.gethash();
369     v=v & 0x7FFFFFFFU;
370     
371     // store calculated hash value only if object is already evaluated
372     if (flags & status_flags::evaluated) {
373         setflag(status_flags::hash_calculated);
374         hashvalue=v;
375     }
376
377     return v;
378 }
379
380 ex expairseq::expand(unsigned options) const
381 {
382     epvector * vp=expandchildren(options);
383     if (vp==0) {
384         return *this;
385     }
386     return thisexpairseq(vp,overall_coeff);
387 }
388
389 //////////
390 // new virtual functions which can be overridden by derived classes
391 //////////
392
393 // protected
394
395 ex expairseq::thisexpairseq(epvector const & v,ex const & oc) const
396 {
397     return expairseq(v,oc);
398 }
399
400 ex expairseq::thisexpairseq(epvector * vp, ex const & oc) const
401 {
402     return expairseq(vp,oc);
403 }
404
405 expair expairseq::split_ex_to_pair(ex const & e) const
406 {
407     return expair(e,exONE());
408 }
409
410 expair expairseq::combine_ex_with_coeff_to_pair(ex const & e,
411                                                 ex const & c) const
412 {
413     ASSERT(is_ex_exactly_of_type(c,numeric));
414
415     return expair(e,c);
416 }
417
418 expair expairseq::combine_pair_with_coeff_to_pair(expair const & p,
419                                                   ex const & c) const
420 {
421     ASSERT(is_ex_exactly_of_type(p.coeff,numeric));
422     ASSERT(is_ex_exactly_of_type(c,numeric));
423     
424     return expair(p.rest,ex_to_numeric(p.coeff).mul_dyn(ex_to_numeric(c)));
425 }
426
427 ex expairseq::recombine_pair_to_ex(expair const & p) const
428 {
429     return lst(p.rest,p.coeff);
430 }
431
432 bool expairseq::expair_needs_further_processing(epp it)
433 {
434     return false;
435 }
436
437 ex expairseq::default_overall_coeff(void) const
438 {
439     return exZERO();
440 }
441
442 void expairseq::combine_overall_coeff(ex const & c)
443 {
444     ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
445     ASSERT(is_ex_exactly_of_type(c,numeric));
446     overall_coeff = ex_to_numeric(overall_coeff).add_dyn(ex_to_numeric(c));
447 }
448
449 void expairseq::combine_overall_coeff(ex const & c1, ex const & c2)
450 {
451     ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
452     ASSERT(is_ex_exactly_of_type(c1,numeric));
453     ASSERT(is_ex_exactly_of_type(c2,numeric));
454     overall_coeff = ex_to_numeric(overall_coeff).
455                         add_dyn(ex_to_numeric(c1).mul(ex_to_numeric(c2)));
456 }
457
458 bool expairseq::can_make_flat(expair const & p) const
459 {
460     return true;
461 }
462
463     
464 //////////
465 // non-virtual functions in this class
466 //////////
467
468 void expairseq::construct_from_2_ex_via_exvector(ex const & lh, ex const & rh)
469 {
470     exvector v;
471     v.reserve(2);
472     v.push_back(lh);
473     v.push_back(rh);
474     construct_from_exvector(v);
475 #ifdef EXPAIRSEQ_USE_HASHTAB
476     ASSERT((hashtabsize==0)||(hashtabsize>=minhashtabsize));
477     ASSERT(hashtabsize==calc_hashtabsize(seq.size()));
478 #endif // def EXPAIRSEQ_USE_HASHTAB
479 }
480
481 void expairseq::construct_from_2_ex(ex const & lh, ex const & rh)
482 {
483     if (lh.bp->tinfo()==tinfo()) {
484        if (rh.bp->tinfo()==tinfo()) {
485 #ifdef EXPAIRSEQ_USE_HASHTAB
486            unsigned totalsize=ex_to_expairseq(lh).seq.size()+
487                               ex_to_expairseq(rh).seq.size();
488            if (calc_hashtabsize(totalsize)!=0) {
489                construct_from_2_ex_via_exvector(lh,rh);
490            } else {
491 #endif // def EXPAIRSEQ_USE_HASHTAB
492                construct_from_2_expairseq(ex_to_expairseq(lh),
493                                           ex_to_expairseq(rh));
494 #ifdef EXPAIRSEQ_USE_HASHTAB
495            }
496 #endif // def EXPAIRSEQ_USE_HASHTAB
497            return;
498        } else {
499 #ifdef EXPAIRSEQ_USE_HASHTAB
500            unsigned totalsize=ex_to_expairseq(lh).seq.size()+1;
501            if (calc_hashtabsize(totalsize)!=0) {
502                construct_from_2_ex_via_exvector(lh,rh);
503            } else {
504 #endif // def EXPAIRSEQ_USE_HASHTAB
505                construct_from_expairseq_ex(ex_to_expairseq(lh),rh);
506 #ifdef EXPAIRSEQ_USE_HASHTAB
507            }
508 #endif // def EXPAIRSEQ_USE_HASHTAB
509            return;
510        }
511     } else if (rh.bp->tinfo()==tinfo()) {
512 #ifdef EXPAIRSEQ_USE_HASHTAB
513         unsigned totalsize=ex_to_expairseq(rh).seq.size()+1;
514         if (calc_hashtabsize(totalsize)!=0) {
515             construct_from_2_ex_via_exvector(lh,rh);
516         } else {
517 #endif // def EXPAIRSEQ_USE_HASHTAB
518             construct_from_expairseq_ex(ex_to_expairseq(rh),lh);
519 #ifdef EXPAIRSEQ_USE_HASHTAB
520         }
521 #endif // def EXPAIRSEQ_USE_HASHTAB
522         return;
523     }
524
525 #ifdef EXPAIRSEQ_USE_HASHTAB
526     if (calc_hashtabsize(2)!=0) {
527         construct_from_2_ex_via_exvector(lh,rh);
528         return;
529     }
530     hashtabsize=0;
531 #endif // def EXPAIRSEQ_USE_HASHTAB
532     
533     if (is_ex_exactly_of_type(lh,numeric)) {
534         if (is_ex_exactly_of_type(rh,numeric)) {
535             combine_overall_coeff(lh);
536             combine_overall_coeff(rh);
537         } else {
538             combine_overall_coeff(lh);
539             seq.push_back(split_ex_to_pair(rh));
540         }
541     } else {
542         if (is_ex_exactly_of_type(rh,numeric)) {
543             combine_overall_coeff(rh);
544             seq.push_back(split_ex_to_pair(lh));
545         } else {
546             expair p1=split_ex_to_pair(lh);
547             expair p2=split_ex_to_pair(rh);
548
549             int cmpval=p1.rest.compare(p2.rest);
550             if (cmpval==0) {
551                 p1.coeff=ex_to_numeric(p1.coeff).add_dyn(ex_to_numeric(p2.coeff));
552                 if (!ex_to_numeric(p1.coeff).is_zero()) {
553                     // no further processing is necessary, since this
554                     // one element will usually be recombined in eval()
555                     seq.push_back(p1);
556                 }
557             } else {
558                 seq.reserve(2);
559                 if (cmpval<0) {
560                     seq.push_back(p1);
561                     seq.push_back(p2);
562                 } else {
563                     seq.push_back(p2);
564                     seq.push_back(p1);
565                 }
566             }
567         }
568     }
569 }
570
571 void expairseq::construct_from_2_expairseq(expairseq const & s1,
572                                            expairseq const & s2)
573 {
574     combine_overall_coeff(s1.overall_coeff);
575     combine_overall_coeff(s2.overall_coeff);
576
577     epvector::const_iterator first1=s1.seq.begin();
578     epvector::const_iterator last1=s1.seq.end();
579     epvector::const_iterator first2=s2.seq.begin();
580     epvector::const_iterator last2=s2.seq.end();
581
582     seq.reserve(s1.seq.size()+s2.seq.size());
583
584     bool needs_further_processing=false;
585     
586     while (first1!=last1 && first2!=last2) {
587         int cmpval=(*first1).rest.compare((*first2).rest);
588         if (cmpval==0) {
589             // combine terms
590             numeric const & newcoeff=ex_to_numeric((*first1).coeff).
591                                      add(ex_to_numeric((*first2).coeff));
592             if (!newcoeff.is_zero()) {
593                 seq.push_back(expair((*first1).rest,newcoeff));
594                 if (expair_needs_further_processing(seq.end()-1)) {
595                     needs_further_processing = true;
596                 }
597             }
598             ++first1;
599             ++first2;
600         } else if (cmpval<0) {
601             seq.push_back(*first1);
602             ++first1;
603         } else {
604             seq.push_back(*first2);
605             ++first2;
606         }
607     }
608     
609     while (first1!=last1) {
610         seq.push_back(*first1);
611         ++first1;
612     }
613     while (first2!=last2) {
614         seq.push_back(*first2);
615         ++first2;
616     }
617
618     if (needs_further_processing) {
619         epvector v=seq;
620         seq.clear();
621         construct_from_epvector(v);
622     }
623 }
624
625 void expairseq::construct_from_expairseq_ex(expairseq const & s,
626                                             ex const & e)
627 {
628     combine_overall_coeff(s.overall_coeff);
629     if (is_ex_exactly_of_type(e,numeric)) {
630         combine_overall_coeff(e);
631         seq=s.seq;
632         return;
633     }
634
635     epvector::const_iterator first=s.seq.begin();
636     epvector::const_iterator last=s.seq.end();
637     expair p=split_ex_to_pair(e);
638
639     seq.reserve(s.seq.size()+1);
640     bool p_pushed=0;
641
642     bool needs_further_processing=false;
643
644     // merge p into s.seq
645     while (first!=last) {
646         int cmpval=(*first).rest.compare(p.rest);
647         if (cmpval==0) {
648             // combine terms
649             numeric const & newcoeff=ex_to_numeric((*first).coeff).
650                                      add(ex_to_numeric(p.coeff));
651             if (!newcoeff.is_zero()) {
652                 seq.push_back(expair((*first).rest,newcoeff));
653                 if (expair_needs_further_processing(seq.end()-1)) {
654                     needs_further_processing = true;
655                 }
656             }
657             ++first;
658             p_pushed=1;
659             break;
660         } else if (cmpval<0) {
661             seq.push_back(*first);
662             ++first;
663         } else {
664             seq.push_back(p);
665             p_pushed=1;
666             break;
667         }
668     }
669
670     if (p_pushed) {
671         // while loop exited because p was pushed, now push rest of s.seq
672         while (first!=last) {
673             seq.push_back(*first);
674             ++first;
675         }
676     } else {
677         // while loop exited because s.seq was pushed, now push p
678         seq.push_back(p);
679     }
680
681     if (needs_further_processing) {
682         epvector v=seq;
683         seq.clear();
684         construct_from_epvector(v);
685     }
686 }
687
688 void expairseq::construct_from_exvector(exvector const & v)
689 {
690     // simplifications: +(a,+(b,c),d) -> +(a,b,c,d) (associativity)
691     //                  +(d,b,c,a) -> +(a,b,c,d) (canonicalization)
692     //                  +(...,x,*(x,c1),*(x,c2)) -> +(...,*(x,1+c1+c2)) (c1, c2 numeric())
693     //                  (same for (+,*) -> (*,^)
694
695     make_flat(v);
696 #ifdef EXPAIRSEQ_USE_HASHTAB
697     combine_same_terms();
698 #else
699     canonicalize();
700     combine_same_terms_sorted_seq();
701 #endif // def EXPAIRSEQ_USE_HASHTAB
702 }
703
704 void expairseq::construct_from_epvector(epvector const & v)
705 {
706     // simplifications: +(a,+(b,c),d) -> +(a,b,c,d) (associativity)
707     //                  +(d,b,c,a) -> +(a,b,c,d) (canonicalization)
708     //                  +(...,x,*(x,c1),*(x,c2)) -> +(...,*(x,1+c1+c2)) (c1, c2 numeric())
709     //                  (same for (+,*) -> (*,^)
710
711     make_flat(v);
712 #ifdef EXPAIRSEQ_USE_HASHTAB
713     combine_same_terms();
714 #else
715     canonicalize();
716     combine_same_terms_sorted_seq();
717 #endif // def EXPAIRSEQ_USE_HASHTAB
718 }
719
720 #include <iostream>
721
722 void expairseq::make_flat(exvector const & v)
723 {
724     exvector::const_iterator cit, citend = v.end();
725
726     // count number of operands which are of same expairseq derived type
727     // and their cumulative number of operands
728     int nexpairseqs=0;
729     int noperands=0;
730     cit=v.begin();
731     while (cit!=citend) {
732         if (cit->bp->tinfo()==tinfo()) {
733             nexpairseqs++;
734             noperands+=ex_to_expairseq(*cit).seq.size();
735         }
736         ++cit;
737     }
738
739     // reserve seq and coeffseq which will hold all operands
740     seq.reserve(v.size()+noperands-nexpairseqs);
741
742     // copy elements and split off numerical part
743     cit=v.begin();
744     while (cit!=citend) {
745         if (cit->bp->tinfo()==tinfo()) {
746             expairseq const & subseqref=ex_to_expairseq(*cit);
747             combine_overall_coeff(subseqref.overall_coeff);
748             epvector::const_iterator cit_s=subseqref.seq.begin();
749             while (cit_s!=subseqref.seq.end()) {
750                 seq.push_back(*cit_s);
751                 ++cit_s;
752             }
753         } else {
754             if (is_ex_exactly_of_type(*cit,numeric)) {
755                 combine_overall_coeff(*cit);
756             } else {
757                 seq.push_back(split_ex_to_pair(*cit));
758             }
759         }
760         ++cit;
761     }
762
763     /*
764     cout << "after make flat" << endl;
765     for (epvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
766         (*cit).printraw(cout);
767     }
768     cout << endl;
769     cout.flush();
770     */
771 }
772
773 void expairseq::make_flat(epvector const & v)
774 {
775     epvector::const_iterator cit, citend = v.end();
776
777     // count number of operands which are of same expairseq derived type
778     // and their cumulative number of operands
779     int nexpairseqs=0;
780     int noperands=0;
781     cit=v.begin();
782     while (cit!=citend) {
783         if (cit->rest.bp->tinfo()==tinfo()) {
784             nexpairseqs++;
785             noperands+=ex_to_expairseq((*cit).rest).seq.size();
786         }
787         ++cit;
788     }
789
790     // reserve seq and coeffseq which will hold all operands
791     seq.reserve(v.size()+noperands-nexpairseqs);
792
793     // copy elements and split off numerical part
794     cit=v.begin();
795     while (cit!=citend) {
796         if ((cit->rest.bp->tinfo()==tinfo())&&can_make_flat(*cit)) {
797             expairseq const & subseqref=ex_to_expairseq((*cit).rest);
798             combine_overall_coeff(ex_to_numeric(subseqref.overall_coeff),
799                                   ex_to_numeric((*cit).coeff));
800             epvector::const_iterator cit_s=subseqref.seq.begin();
801             while (cit_s!=subseqref.seq.end()) {
802                 seq.push_back(expair((*cit_s).rest,
803                               ex_to_numeric((*cit_s).coeff).mul_dyn(ex_to_numeric((*cit).coeff))));
804                 //seq.push_back(combine_pair_with_coeff_to_pair(*cit_s,
805                 //                                              (*cit).coeff));
806                 ++cit_s;
807             }
808         } else {
809             if ((*cit).is_numeric_with_coeff_1()) {
810                 combine_overall_coeff((*cit).rest);
811             //if (is_ex_exactly_of_type((*cit).rest,numeric)) {
812             //    combine_overall_coeff(recombine_pair_to_ex(*cit));
813             } else {
814                 seq.push_back(*cit);
815             }
816         }
817         ++cit;
818     }
819 }
820
821 epvector * expairseq::bubblesort(epvector::iterator itbegin, epvector::iterator itend)
822 {
823     unsigned n=itend-itbegin;
824
825     epvector * sp=new epvector;
826     sp->reserve(n);
827
828     epvector::iterator last=itend-1;
829     for (epvector::iterator it1=itbegin; it1!=last; ++it1) {
830         for (epvector::iterator it2=it1+1; it2!=itend; ++it2) {
831             if ((*it2).rest.compare((*it1).rest)<0) {
832                 iter_swap(it1,it2);
833             }
834         }
835         sp->push_back(*it1);
836     }
837     sp->push_back(*last);
838     return sp;
839 }
840
841 epvector * expairseq::mergesort(epvector::iterator itbegin, epvector::iterator itend)
842 {
843     unsigned n=itend-itbegin;
844     /*
845     if (n==1) {
846         epvector * sp=new epvector;
847         sp->push_back(*itbegin);
848         return sp;
849     }
850     */
851     if (n<16) return bubblesort(itbegin, itend);
852     unsigned m=n/2;
853     
854     epvector * s1p=mergesort(itbegin, itbegin+m);
855     epvector * s2p=mergesort(itbegin+m, itend);
856
857     epvector * sp=new epvector;
858     sp->reserve(s1p->size()+s2p->size());
859
860     epvector::iterator first1=s1p->begin();
861     epvector::iterator last1=s1p->end();
862
863     epvector::iterator first2=s2p->begin();
864     epvector::iterator last2=s2p->end();
865     
866     while (first1 != last1 && first2 != last2) {
867         if ((*first1).rest.compare((*first2).rest)<0) {
868             sp->push_back(*first1);
869             ++first1;
870         } else {
871             sp->push_back(*first2);
872             ++first2;
873         }
874     }
875
876     if (first1 != last1) {
877         while (first1 != last1) {
878             sp->push_back(*first1);
879             ++first1;
880         }
881     } else {
882         while (first2 != last2) {
883             sp->push_back(*first2);
884             ++first2;
885         }
886     }
887
888     delete s1p;
889     delete s2p;
890     
891     return sp;
892 }
893             
894
895 void expairseq::canonicalize(void)
896 {
897     // canonicalize
898     sort(seq.begin(),seq.end(),expair_is_less());
899     /*
900     sort(seq.begin(),seq.end(),expair_is_less_old());
901     if (seq.size()>1) {
902         if (is_ex_exactly_of_type((*(seq.begin())).rest,numeric)) {
903             sort(seq.begin(),seq.end(),expair_is_less());
904         } else {
905             epvector::iterator last_numeric=seq.end();
906             do {
907                 last_numeric--;
908             } while (is_ex_exactly_of_type((*last_numeric).rest,numeric));
909             last_numeric++;
910             sort(last_numeric,seq.end(),expair_is_less());
911         }
912     }
913     */
914     
915     /*
916     epvector * sorted_seqp=mergesort(seq.begin(),seq.end());
917     epvector::iterator last=sorted_seqp->end();
918     epvector::iterator it2=seq.begin();
919     for (epvector::iterator it1=sorted_seqp->begin(); it1!=last; ++it1, ++it2) {
920         iter_swap(it1,it2);
921     }
922     delete sorted_seqp;
923     */
924
925     /*
926     cout << "after canonicalize" << endl;
927     for (epvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
928         (*cit).printraw(cout);
929     }
930     cout << endl;
931     cout.flush();
932     */
933 }
934
935 void expairseq::combine_same_terms_sorted_seq(void)
936 {
937     bool needs_further_processing=false;
938     
939     // combine same terms, drop term with coeff 0
940     if (seq.size()>1) {
941         epvector::iterator itin1=seq.begin();
942         epvector::iterator itin2=itin1+1;
943         epvector::iterator itout=itin1;
944         epvector::iterator last=seq.end();
945         // must_copy will be set to true the first time some combination is possible
946         // from then on the sequence has changed and must be compacted
947         bool must_copy=false;
948         while (itin2!=last) {
949             if ((*itin1).rest.compare((*itin2).rest)==0) {
950                 (*itin1).coeff=ex_to_numeric((*itin1).coeff).
951                                add_dyn(ex_to_numeric((*itin2).coeff));
952                 if (expair_needs_further_processing(itin1)) {
953                     needs_further_processing = true;
954                 }
955                 must_copy=true;
956             } else {
957                 if (!ex_to_numeric((*itin1).coeff).is_zero()) {
958                     if (must_copy) {
959                         *itout=*itin1;
960                     }
961                     ++itout;
962                 }
963                 itin1=itin2;
964             }
965             ++itin2;
966         }
967         if (!ex_to_numeric((*itin1).coeff).is_zero()) {
968             if (must_copy) {
969                 *itout=*itin1;
970             }
971             ++itout;
972         }
973         if (itout!=last) {
974             seq.erase(itout,last);
975         }
976     }
977
978     /*
979     cout << "after combine" << endl;
980     for (epvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
981         (*cit).printraw(cout);
982     }
983     cout << endl;
984     cout.flush();
985     */
986     
987     if (needs_further_processing) {
988         epvector v=seq;
989         seq.clear();
990         construct_from_epvector(v);
991     }
992 }
993
994 #ifdef EXPAIRSEQ_USE_HASHTAB
995
996 unsigned expairseq::calc_hashtabsize(unsigned sz) const
997 {
998     unsigned size;
999     unsigned nearest_power_of_2 = 1 << log2(sz);
1000     //    if (nearest_power_of_2 < maxhashtabsize/hashtabfactor) {
1001     //  size=nearest_power_of_2*hashtabfactor;
1002     size=nearest_power_of_2/hashtabfactor;
1003     if (size<minhashtabsize) return 0;
1004     ASSERT(hashtabsize<=0x8000000U); // really max size due to 31 bit hashing
1005     // hashtabsize must be a power of 2
1006     ASSERT((1U << log2(size))==size);
1007     return size;
1008 }
1009
1010 unsigned expairseq::calc_hashindex(ex const & e) const
1011 {
1012     // calculate hashindex
1013     unsigned hash=e.gethash();
1014     unsigned hashindex;
1015     if (is_a_numeric_hash(hash)) {
1016         hashindex=hashmask;
1017     } else {
1018         hashindex=hash & hashmask;
1019         // last hashtab entry is reserved for numerics
1020         if (hashindex==hashmask) hashindex=0;
1021     }
1022     ASSERT(hashindex>=0);
1023     ASSERT((hashindex<hashtabsize)||(hashtabsize==0));
1024     return hashindex;
1025 }
1026
1027 void expairseq::shrink_hashtab(void)
1028 {
1029     unsigned new_hashtabsize;
1030     while (hashtabsize!=(new_hashtabsize=calc_hashtabsize(seq.size()))) {
1031         ASSERT(new_hashtabsize<hashtabsize);
1032         if (new_hashtabsize==0) {
1033             hashtab.clear();
1034             hashtabsize=0;
1035             canonicalize();
1036             return;
1037         }
1038         
1039         // shrink by a factor of 2
1040         unsigned half_hashtabsize=hashtabsize/2;
1041         for (unsigned i=0; i<half_hashtabsize-1; ++i) {
1042             hashtab[i].merge(hashtab[i+half_hashtabsize],epp_is_less());
1043         }
1044         // special treatment for numeric hashes
1045         hashtab[0].merge(hashtab[half_hashtabsize-1],epp_is_less());
1046         hashtab[half_hashtabsize-1]=hashtab[hashtabsize-1];
1047         hashtab.resize(half_hashtabsize);
1048         hashtabsize=half_hashtabsize;
1049         hashmask=hashtabsize-1;
1050     }
1051 }
1052
1053 void expairseq::remove_hashtab_entry(epvector::const_iterator element)
1054 {
1055     if (hashtabsize==0) return; // nothing to do
1056     
1057     // calculate hashindex of element to be deleted
1058     unsigned hashindex=calc_hashindex((*element).rest);
1059
1060     // find it in hashtab and remove it
1061     epplist & eppl=hashtab[hashindex];
1062     epplist::iterator epplit=eppl.begin();
1063     bool erased=false;
1064     while (epplit!=eppl.end()) {
1065         if (*epplit == element) {
1066             eppl.erase(epplit);
1067             erased=true;
1068             break;
1069         }
1070         ++epplit;
1071     }
1072     if (!erased) {
1073         printtree(cout,0);
1074         cout << "tried to erase " << element-seq.begin() << endl;
1075         cout << "size " << seq.end()-seq.begin() << endl;
1076
1077         unsigned hashindex=calc_hashindex((*element).rest);
1078         epplist & eppl=hashtab[hashindex];
1079         epplist::iterator epplit=eppl.begin();
1080         bool erased=false;
1081         while (epplit!=eppl.end()) {
1082             if (*epplit == element) {
1083                 eppl.erase(epplit);
1084                 erased=true;
1085                 break;
1086             }
1087             ++epplit;
1088         }
1089         ASSERT(erased);
1090     }
1091     ASSERT(erased);
1092 }
1093
1094 void expairseq::move_hashtab_entry(epvector::const_iterator oldpos,
1095                                    epvector::iterator newpos)
1096 {
1097     ASSERT(hashtabsize!=0);
1098     
1099     // calculate hashindex of element which was moved
1100     unsigned hashindex=calc_hashindex((*newpos).rest);
1101
1102     // find it in hashtab and modify it
1103     epplist & eppl=hashtab[hashindex];
1104     epplist::iterator epplit=eppl.begin();
1105     while (epplit!=eppl.end()) {
1106         if (*epplit == oldpos) {
1107             *epplit=newpos;
1108             break;
1109         }
1110         ++epplit;
1111     }
1112     ASSERT(epplit!=eppl.end());
1113 }
1114
1115 void expairseq::sorted_insert(epplist & eppl, epp elem)
1116 {
1117     epplist::iterator current=eppl.begin();
1118     while ((current!=eppl.end())&&((*(*current)).is_less(*elem))) {
1119         ++current;
1120     }
1121     eppl.insert(current,elem);
1122 }    
1123
1124 void expairseq::build_hashtab_and_combine(epvector::iterator & first_numeric,
1125                                           epvector::iterator & last_non_zero,
1126                                           vector<bool> & touched,
1127                                           unsigned & number_of_zeroes)
1128 {
1129     epp current=seq.begin();
1130
1131     while (current!=first_numeric) {
1132         if (is_ex_exactly_of_type((*current).rest,numeric)) {
1133             --first_numeric;
1134             iter_swap(current,first_numeric);
1135         } else {
1136             // calculate hashindex
1137             unsigned currenthashindex=calc_hashindex((*current).rest);
1138
1139             // test if there is already a matching expair in the hashtab-list
1140             epplist & eppl=hashtab[currenthashindex];
1141             epplist::iterator epplit=eppl.begin();
1142             while (epplit!=eppl.end()) {
1143                 if ((*current).rest.is_equal((*(*epplit)).rest)) break;
1144                 ++epplit;
1145             }
1146             if (epplit==eppl.end()) {
1147                 // no matching expair found, append this to end of list
1148                 sorted_insert(eppl,current);
1149                 ++current;
1150             } else {
1151                 // epplit points to a matching expair, combine it with current
1152                 (*(*epplit)).coeff=ex_to_numeric((*(*epplit)).coeff).
1153                                    add_dyn(ex_to_numeric((*current).coeff));
1154                 
1155                 // move obsolete current expair to end by swapping with last_non_zero element
1156                 // if this was a numeric, it is swapped with the expair before first_numeric 
1157                 iter_swap(current,last_non_zero);
1158                 --first_numeric;
1159                 if (first_numeric!=last_non_zero) iter_swap(first_numeric,current);
1160                 --last_non_zero;
1161                 ++number_of_zeroes;
1162                 // test if combined term has coeff 0 and can be removed is done later
1163                 touched[(*epplit)-seq.begin()]=true;
1164             }
1165         }
1166     }
1167 }    
1168
1169 void expairseq::drop_coeff_0_terms(epvector::iterator & first_numeric,
1170                                    epvector::iterator & last_non_zero,
1171                                    vector<bool> & touched,
1172                                    unsigned & number_of_zeroes)
1173 {
1174     // move terms with coeff 0 to end and remove them from hashtab
1175     // check only those elements which have been touched
1176     epp current=seq.begin();
1177     unsigned i=0;
1178     while (current!=first_numeric) {
1179         if (!touched[i]) {
1180             ++current;
1181             ++i;
1182         } else if (!ex_to_numeric((*current).coeff).is_equal(numZERO())) {
1183             ++current;
1184             ++i;
1185         } else {
1186             remove_hashtab_entry(current);
1187
1188             // move element to the end, unless it is already at the end
1189             if (current!=last_non_zero) {
1190                 iter_swap(current,last_non_zero);
1191                 --first_numeric;
1192                 bool numeric_swapped=first_numeric!=last_non_zero;
1193                 if (numeric_swapped) iter_swap(first_numeric,current);
1194                 epvector::iterator changed_entry;
1195
1196                 if (numeric_swapped) {
1197                     changed_entry=first_numeric;
1198                 } else {
1199                     changed_entry=last_non_zero;
1200                 }
1201
1202                 --last_non_zero;
1203                 ++number_of_zeroes;
1204
1205                 if (first_numeric!=current) {
1206                 
1207                     // change entry in hashtab which referred to first_numeric or last_non_zero to current
1208                     move_hashtab_entry(changed_entry,current);
1209                     touched[current-seq.begin()]=touched[changed_entry-seq.begin()];
1210                 }
1211             } else {
1212                 --first_numeric;
1213                 --last_non_zero;
1214                 ++number_of_zeroes;
1215             }
1216         }
1217     }
1218     ASSERT(i==current-seq.begin());
1219 }
1220
1221 bool expairseq::has_coeff_0(void) const
1222 {
1223     for (epvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
1224         if ((*cit).coeff.is_equal(exZERO())) {
1225             return true;
1226         }
1227     }
1228     return false;
1229 }
1230
1231 void expairseq::add_numerics_to_hashtab(epvector::iterator first_numeric,
1232                                         epvector::const_iterator last_non_zero)
1233 {
1234     if (first_numeric==seq.end()) return; // no numerics    
1235
1236     epvector::iterator current=first_numeric;
1237     epvector::const_iterator last=last_non_zero+1;
1238     while (current!=last) {
1239         sorted_insert(hashtab[hashmask],current);
1240         ++current;
1241     }
1242 }
1243
1244 void expairseq::combine_same_terms(void)
1245 {
1246     // combine same terms, drop term with coeff 0, move numerics to end
1247     
1248     // calculate size of hashtab
1249     hashtabsize=calc_hashtabsize(seq.size());
1250
1251     // hashtabsize is a power of 2
1252     hashmask=hashtabsize-1;
1253
1254     // allocate hashtab
1255     hashtab.clear();
1256     hashtab.resize(hashtabsize);
1257
1258     if (hashtabsize==0) {
1259         canonicalize();
1260         combine_same_terms_sorted_seq();
1261         ASSERT(!has_coeff_0());
1262         return;
1263     }
1264
1265     // iterate through seq, move numerics to end,
1266     // fill hashtab and combine same terms
1267     epvector::iterator first_numeric=seq.end();
1268     epvector::iterator last_non_zero=seq.end()-1;
1269
1270     vector<bool> touched;
1271     touched.reserve(seq.size());
1272     for (unsigned i=0; i<seq.size(); ++i) touched[i]=false;
1273
1274     unsigned number_of_zeroes=0;
1275
1276     ASSERT(!has_coeff_0());
1277     build_hashtab_and_combine(first_numeric,last_non_zero,touched,number_of_zeroes);
1278     /*
1279     cout << "in combine:" << endl;
1280     printtree(cout,0);
1281     cout << "size=" << seq.end() - seq.begin() << endl;
1282     cout << "first_numeric=" << first_numeric - seq.begin() << endl;
1283     cout << "last_non_zero=" << last_non_zero - seq.begin() << endl;
1284     for (unsigned i=0; i<seq.size(); ++i) {
1285         if (touched[i]) cout << i << " is touched" << endl;
1286     }
1287     cout << "end in combine" << endl;
1288     */
1289     
1290     // there should not be any terms with coeff 0 from the beginning,
1291     // so it should be safe to skip this step
1292     if (number_of_zeroes!=0) {
1293         drop_coeff_0_terms(first_numeric,last_non_zero,touched,number_of_zeroes);
1294         /*
1295         cout << "in combine after drop:" << endl;
1296         printtree(cout,0);
1297         cout << "size=" << seq.end() - seq.begin() << endl;
1298         cout << "first_numeric=" << first_numeric - seq.begin() << endl;
1299         cout << "last_non_zero=" << last_non_zero - seq.begin() << endl;
1300         for (unsigned i=0; i<seq.size(); ++i) {
1301             if (touched[i]) cout << i << " is touched" << endl;
1302         }
1303         cout << "end in combine after drop" << endl;
1304         */
1305     }
1306
1307     add_numerics_to_hashtab(first_numeric,last_non_zero);
1308
1309     // pop zero elements
1310     for (unsigned i=0; i<number_of_zeroes; ++i) {
1311         seq.pop_back();
1312     }
1313
1314     // shrink hashtabsize to calculated value
1315     ASSERT(!has_coeff_0());
1316
1317     shrink_hashtab();
1318
1319     ASSERT(!has_coeff_0());
1320 }
1321
1322 #endif // def EXPAIRSEQ_USE_HASHTAB
1323
1324 bool expairseq::is_canonical() const
1325 {
1326     if (seq.size()<=1) return 1;
1327
1328 #ifdef EXPAIRSEQ_USE_HASHTAB
1329     if (hashtabsize>0) return 1; // not canoncalized
1330 #endif // def EXPAIRSEQ_USE_HASHTAB
1331     
1332     epvector::const_iterator it=seq.begin();
1333     epvector::const_iterator it_last=it;
1334     for (++it; it!=seq.end(); it_last=it, ++it) {
1335         if (!((*it_last).is_less(*it)||(*it_last).is_equal(*it))) {
1336             if (!is_ex_exactly_of_type((*it_last).rest,numeric)||
1337                 !is_ex_exactly_of_type((*it).rest,numeric)) {
1338                 // double test makes it easier to set a breakpoint...
1339                 if (!is_ex_exactly_of_type((*it_last).rest,numeric)||
1340                     !is_ex_exactly_of_type((*it).rest,numeric)) {
1341                     printpair(cout,*it_last,0);
1342                     cout << ">";
1343                     printpair(cout,*it,0);
1344                     cout << "\n";
1345                     cout << "pair1:" << endl;
1346                     (*it_last).rest.printtree(cout);
1347                     (*it_last).coeff.printtree(cout);
1348                     cout << "pair2:" << endl;
1349                     (*it).rest.printtree(cout);
1350                     (*it).coeff.printtree(cout);
1351                     return 0;
1352                 }
1353             }
1354         }
1355     }
1356     return 1;
1357 }
1358
1359 epvector * expairseq::expandchildren(unsigned options) const
1360 {
1361     epvector::const_iterator last=seq.end();
1362     epvector::const_iterator cit=seq.begin();
1363     while (cit!=last) {
1364         ex const & expanded_ex=(*cit).rest.expand(options);
1365         if (!are_ex_trivially_equal((*cit).rest,expanded_ex)) {
1366
1367             // something changed, copy seq, eval and return it
1368             epvector *s=new epvector;
1369             s->reserve(seq.size());
1370
1371             // copy parts of seq which are known not to have changed
1372             epvector::const_iterator cit2=seq.begin();
1373             while (cit2!=cit) {
1374                 s->push_back(*cit2);
1375                 ++cit2;
1376             }
1377             // copy first changed element
1378             s->push_back(combine_ex_with_coeff_to_pair(expanded_ex,
1379                                                        (*cit2).coeff));
1380             ++cit2;
1381             // copy rest
1382             while (cit2!=last) {
1383                 s->push_back(combine_ex_with_coeff_to_pair((*cit2).rest.expand(options),
1384                                                            (*cit2).coeff));
1385                 ++cit2;
1386             }
1387             return s;
1388         }
1389         ++cit;
1390     }
1391     
1392     return 0; // nothing has changed
1393 }
1394    
1395 epvector * expairseq::evalchildren(int level) const
1396 {
1397     // returns a NULL pointer if nothing had to be evaluated
1398     // returns a pointer to a newly created epvector otherwise
1399     // (which has to be deleted somewhere else)
1400
1401     if (level==1) {
1402         return 0;
1403     }
1404     if (level == -max_recursion_level) {
1405         throw(std::runtime_error("max recursion level reached"));
1406     }
1407
1408     --level;
1409     epvector::const_iterator last=seq.end();
1410     epvector::const_iterator cit=seq.begin();
1411     while (cit!=last) {
1412         ex const & evaled_ex=(*cit).rest.eval(level);
1413         if (!are_ex_trivially_equal((*cit).rest,evaled_ex)) {
1414
1415             // something changed, copy seq, eval and return it
1416             epvector *s=new epvector;
1417             s->reserve(seq.size());
1418
1419             // copy parts of seq which are known not to have changed
1420             epvector::const_iterator cit2=seq.begin();
1421             while (cit2!=cit) {
1422                 s->push_back(*cit2);
1423                 ++cit2;
1424             }
1425             // copy first changed element
1426             s->push_back(combine_ex_with_coeff_to_pair(evaled_ex,
1427                                                        (*cit2).coeff));
1428             ++cit2;
1429             // copy rest
1430             while (cit2!=last) {
1431                 s->push_back(combine_ex_with_coeff_to_pair((*cit2).rest.eval(level),
1432                                                            (*cit2).coeff));
1433                 ++cit2;
1434             }
1435             return s;
1436         }
1437         ++cit;
1438     }
1439     
1440     return 0; // nothing has changed
1441 }
1442
1443 epvector expairseq::evalfchildren(int level) const
1444 {
1445     epvector s;
1446     s.reserve(seq.size());
1447
1448     if (level==1) {
1449         return seq;
1450     }
1451     if (level == -max_recursion_level) {
1452         throw(std::runtime_error("max recursion level reached"));
1453     }
1454     --level;
1455     for (epvector::const_iterator it=seq.begin(); it!=seq.end(); ++it) {
1456         s.push_back(combine_ex_with_coeff_to_pair((*it).rest.evalf(level),
1457                                                   (*it).coeff));
1458     }
1459     return s;
1460 }
1461
1462 epvector expairseq::normalchildren(int level) const
1463 {
1464     epvector s;
1465     s.reserve(seq.size());
1466
1467     if (level==1) {
1468         return seq;
1469     }
1470     if (level == -max_recursion_level) {
1471         throw(std::runtime_error("max recursion level reached"));
1472     }
1473     --level;
1474     for (epvector::const_iterator it=seq.begin(); it!=seq.end(); ++it) {
1475         s.push_back(combine_ex_with_coeff_to_pair((*it).rest.normal(level),
1476                                                   (*it).coeff));
1477     }
1478     return s;
1479 }
1480
1481 epvector expairseq::diffchildren(symbol const & y) const
1482 {
1483     epvector s;
1484     s.reserve(seq.size());
1485
1486     for (epvector::const_iterator it=seq.begin(); it!=seq.end(); ++it) {
1487         s.push_back(combine_ex_with_coeff_to_pair((*it).rest.diff(y),
1488                                                   (*it).coeff));
1489     }
1490     return s;
1491 }
1492
1493 epvector * expairseq::subschildren(lst const & ls, lst const & lr) const
1494 {
1495     // returns a NULL pointer if nothing had to be substituted
1496     // returns a pointer to a newly created epvector otherwise
1497     // (which has to be deleted somewhere else)
1498
1499     epvector::const_iterator last=seq.end();
1500     epvector::const_iterator cit=seq.begin();
1501     while (cit!=last) {
1502         ex const & subsed_ex=(*cit).rest.subs(ls,lr);
1503         if (!are_ex_trivially_equal((*cit).rest,subsed_ex)) {
1504
1505             // something changed, copy seq, subs and return it
1506             epvector *s=new epvector;
1507             s->reserve(seq.size());
1508
1509             // copy parts of seq which are known not to have changed
1510             epvector::const_iterator cit2=seq.begin();
1511             while (cit2!=cit) {
1512                 s->push_back(*cit2);
1513                 ++cit2;
1514             }
1515             // copy first changed element
1516             s->push_back(combine_ex_with_coeff_to_pair(subsed_ex,
1517                                                        (*cit2).coeff));
1518             ++cit2;
1519             // copy rest
1520             while (cit2!=last) {
1521                 s->push_back(combine_ex_with_coeff_to_pair((*cit2).rest.subs(ls,lr),
1522                                                            (*cit2).coeff));
1523                 ++cit2;
1524             }
1525             return s;
1526         }
1527         ++cit;
1528     }
1529     
1530     return 0; // nothing has changed
1531 }
1532
1533 /*
1534 epvector expairseq::subschildren(lst const & ls, lst const & lr) const
1535 {
1536     epvector s;
1537     s.reserve(seq.size());
1538
1539     for (epvector::const_iterator it=seq.begin(); it!=seq.end(); ++it) {
1540         s.push_back(split_ex_to_pair((*it).rest.subs(ls,lr),(*it).coeff));
1541     }
1542     return s;
1543 }
1544 */
1545
1546 /*
1547 void expairseq::sort(epviter first, epviter last, expair_is_less comp)
1548 {
1549     if (first != last) {
1550         introsort_loop(first, last, lg(last - first) * 2, comp);
1551         __final_insertion_sort(first, last, comp);
1552     }
1553 }
1554
1555 ptrdiff_t expairseq::lg(ptrdiff_t n)
1556 {
1557     ptrdiff_t k;
1558     for (k = 0; n > 1; n >>= 1) ++k;
1559     return k;
1560 }
1561
1562 void expairseq::introsort_loop(epviter first, epviter last,
1563                                ptrdiff_t depth_limit, expair_is_less comp)
1564 {
1565     while (last - first > stl_threshold) {
1566         if (depth_limit == 0) {
1567             partial_sort(first, last, last, comp);
1568             return;
1569         }
1570         --depth_limit;
1571         epviter cut = unguarded_partition(first, last,
1572                       expair(__median(*first, *(first + (last - first)/2),
1573                       *(last - 1), comp)), comp);
1574         introsort_loop(cut, last, depth_limit, comp);
1575         last = cut;
1576     }
1577 }
1578
1579 epviter expairseq::unguarded_partition(epviter first, epviter last, 
1580                                        expair pivot, expair_is_less comp)
1581 {
1582     while (1) {
1583         while (comp(*first, pivot)) ++first;
1584         --last;
1585         while (comp(pivot, *last)) --last;
1586         if (!(first < last)) return first;
1587         iter_swap(first, last);
1588         ++first;
1589     }
1590 }
1591
1592 void expairseq::partial_sort(epviter first, epviter middle, epviter last,
1593                              expair_is_less comp) {
1594   make_heap(first, middle, comp);
1595   for (RandomAccessIterator i = middle; i < last; ++i)
1596     if (comp(*i, *first))
1597       __pop_heap(first, middle, i, T(*i), comp, distance_type(first));
1598   sort_heap(first, middle, comp);
1599 }
1600 */
1601
1602 //////////
1603 // static member variables
1604 //////////
1605
1606 // protected
1607
1608 unsigned expairseq::precedence=10;
1609
1610 #ifdef EXPAIRSEQ_USE_HASHTAB
1611 unsigned expairseq::maxhashtabsize=0x4000000U;
1612 unsigned expairseq::minhashtabsize=0x1000U;
1613 unsigned expairseq::hashtabfactor=1;
1614 #endif // def EXPAIRSEQ_USE_HASHTAB
1615
1616 //////////
1617 // global constants
1618 //////////
1619
1620 const expairseq some_expairseq;
1621 type_info const & typeid_expairseq=typeid(some_expairseq);
1622