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