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