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