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