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