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