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