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