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