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