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