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