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