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