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