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