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