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