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