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