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