]> www.ginac.de Git - ginac.git/blob - ginac/expairseq.cpp
- ginac-config.1: removed (duplicate).
[ginac.git] / ginac / expairseq.cpp
1 /** @file expairseq.cpp
2  *
3  *  Implementation of sequences of expression pairs. */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2001 Johannes Gutenberg University Mainz, Germany
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include <algorithm>
24 #include <string>
25 #include <stdexcept>
26
27 #include "expairseq.h"
28 #include "lst.h"
29 #include "relational.h"
30 #include "print.h"
31 #include "archive.h"
32 #include "debugmsg.h"
33 #include "utils.h"
34
35 #if EXPAIRSEQ_USE_HASHTAB
36 #include <cmath>
37 #endif // EXPAIRSEQ_USE_HASHTAB
38
39 namespace GiNaC {
40
41 GINAC_IMPLEMENT_REGISTERED_CLASS_NO_CTORS(expairseq, basic)
42
43 //////////
44 // helper classes
45 //////////
46
47 class epp_is_less
48 {
49 public:
50         bool operator()(const epp &lh, const epp &rh) const
51         {
52                 return (*lh).is_less(*rh);
53         }
54 };
55
56 //////////
57 // default ctor, dtor, copy ctor assignment operator and helpers
58 //////////
59
60 // public
61
62 expairseq::expairseq(const expairseq &other)
63 {
64         debugmsg("expairseq copy ctor",LOGLEVEL_CONSTRUCT);
65         copy(other);
66 }
67
68 const expairseq &expairseq::operator=(const expairseq &other)
69 {
70         debugmsg("expairseq operator=",LOGLEVEL_ASSIGNMENT);
71         if (this != &other) {
72                 destroy(true);
73                 copy(other);
74         }
75         return *this;
76 }
77
78 // protected
79
80 /** For use by copy ctor and assignment operator. */
81 void expairseq::copy(const expairseq &other)
82 {
83         inherited::copy(other);
84         seq = other.seq;
85         overall_coeff = other.overall_coeff;
86 #if EXPAIRSEQ_USE_HASHTAB
87         // copy hashtab
88         hashtabsize = other.hashtabsize;
89         if (hashtabsize!=0) {
90                 hashmask = other.hashmask;
91                 hashtab.resize(hashtabsize);
92                 epvector::const_iterator osb = other.seq.begin();
93                 for (unsigned i=0; i<hashtabsize; ++i) {
94                         hashtab[i].clear();
95                         for (epplist::const_iterator cit=other.hashtab[i].begin();
96                              cit!=other.hashtab[i].end(); ++cit) {
97                                 hashtab[i].push_back(seq.begin()+((*cit)-osb));
98                         }
99                 }
100         } else {
101                 hashtab.clear();
102         }
103 #endif // EXPAIRSEQ_USE_HASHTAB
104 }
105
106 DEFAULT_DESTROY(expairseq)
107
108 //////////
109 // other ctors
110 //////////
111
112 expairseq::expairseq(const ex &lh, const ex &rh) : inherited(TINFO_expairseq)
113 {
114         debugmsg("expairseq ctor from ex,ex",LOGLEVEL_CONSTRUCT);
115         construct_from_2_ex(lh,rh);
116         GINAC_ASSERT(is_canonical());
117 }
118
119 expairseq::expairseq(const exvector &v) : inherited(TINFO_expairseq)
120 {
121         debugmsg("expairseq ctor from exvector",LOGLEVEL_CONSTRUCT);
122         construct_from_exvector(v);
123         GINAC_ASSERT(is_canonical());
124 }
125
126 expairseq::expairseq(const epvector &v, const ex &oc)
127   : inherited(TINFO_expairseq), overall_coeff(oc)
128 {
129         debugmsg("expairseq ctor from epvector,ex",LOGLEVEL_CONSTRUCT);
130         construct_from_epvector(v);
131         GINAC_ASSERT(is_canonical());
132 }
133
134 expairseq::expairseq(epvector *vp, const ex &oc)
135   : inherited(TINFO_expairseq), overall_coeff(oc)
136 {
137         debugmsg("expairseq ctor from epvector *,ex",LOGLEVEL_CONSTRUCT);
138         GINAC_ASSERT(vp!=0);
139         construct_from_epvector(*vp);
140         delete vp;
141         GINAC_ASSERT(is_canonical());
142 }
143
144 //////////
145 // archiving
146 //////////
147
148 expairseq::expairseq(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
149 #if EXPAIRSEQ_USE_HASHTAB
150         , hashtabsize(0)
151 #endif
152 {
153         debugmsg("expairseq ctor from archive_node", LOGLEVEL_CONSTRUCT);
154         for (unsigned int i=0; true; i++) {
155                 ex rest;
156                 ex coeff;
157                 if (n.find_ex("rest", rest, sym_lst, i) && n.find_ex("coeff", coeff, sym_lst, i))
158                         seq.push_back(expair(rest, coeff));
159                 else
160                         break;
161         }
162         n.find_ex("overall_coeff", overall_coeff, sym_lst);
163 }
164
165 void expairseq::archive(archive_node &n) const
166 {
167         inherited::archive(n);
168         epvector::const_iterator i = seq.begin(), iend = seq.end();
169         while (i != iend) {
170                 n.add_ex("rest", i->rest);
171                 n.add_ex("coeff", i->coeff);
172                 ++i;
173         }
174         n.add_ex("overall_coeff", overall_coeff);
175 }
176
177 DEFAULT_UNARCHIVE(expairseq)
178
179 //////////
180 // functions overriding virtual functions from base classes
181 //////////
182
183 // public
184
185 basic *expairseq::duplicate() const
186 {
187         debugmsg("expairseq duplicate",LOGLEVEL_DUPLICATE);
188         return new expairseq(*this);
189 }
190
191 void expairseq::print(const print_context & c, unsigned level) const
192 {
193         debugmsg("expairseq print",LOGLEVEL_PRINT);
194
195         if (is_of_type(c, print_tree)) {
196
197                 unsigned delta_indent = static_cast<const print_tree &>(c).delta_indent;
198
199                 c.s << std::string(level, ' ') << class_name()
200                     << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
201                     << ", nops=" << nops()
202                     << std::endl;
203                 unsigned num = seq.size();
204                 for (unsigned i=0; i<num; ++i) {
205                         seq[i].rest.print(c, level + delta_indent);
206                         seq[i].coeff.print(c, level + delta_indent);
207                         if (i != num - 1)
208                                 c.s << std::string(level + delta_indent, ' ') << "-----" << std::endl;
209                 }
210                 if (!overall_coeff.is_equal(default_overall_coeff())) {
211                         c.s << std::string(level + delta_indent, ' ') << "-----" << std::endl
212                             << std::string(level + delta_indent, ' ') << "overall_coeff" << std::endl;
213                         overall_coeff.print(c, level + delta_indent);
214                 }
215                 c.s << std::string(level + delta_indent,' ') << "=====" << std::endl;
216 #if EXPAIRSEQ_USE_HASHTAB
217                 c.s << std::string(level + delta_indent,' ')
218                     << "hashtab size " << hashtabsize << std::endl;
219                 if (hashtabsize == 0) return;
220 #define MAXCOUNT 5
221                 unsigned count[MAXCOUNT+1];
222                 for (int i=0; i<MAXCOUNT+1; ++i)
223                         count[i] = 0;
224                 unsigned this_bin_fill;
225                 unsigned cum_fill_sq = 0;
226                 unsigned cum_fill = 0;
227                 for (unsigned i=0; i<hashtabsize; ++i) {
228                         this_bin_fill = 0;
229                         if (hashtab[i].size() > 0) {
230                                 c.s << std::string(level + delta_indent, ' ')
231                                     << "bin " << i << " with entries ";
232                                 for (epplist::const_iterator it=hashtab[i].begin();
233                                      it!=hashtab[i].end(); ++it) {
234                                         c.s << *it-seq.begin() << " ";
235                                         ++this_bin_fill;
236                                 }
237                                 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 (tinfo() == pattern.bp->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).bp);
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 thisexpairseq(vp, overall_coeff).bp->basic::subs(ls, lr, no_pattern);
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_of_type(other, expairseq));
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(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.bp->print(c, precedence());
619         c.s << ",";
620         p.coeff.bp->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_ex_exactly_of_type(c,numeric));
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_ex_exactly_of_type(p.coeff,numeric));
667         GINAC_ASSERT(is_ex_exactly_of_type(c,numeric));
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_ex_exactly_of_type(overall_coeff,numeric));
696         GINAC_ASSERT(is_ex_exactly_of_type(c,numeric));
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_ex_exactly_of_type(overall_coeff,numeric));
703         GINAC_ASSERT(is_ex_exactly_of_type(c1,numeric));
704         GINAC_ASSERT(is_ex_exactly_of_type(c2,numeric));
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 (lh.bp->tinfo()==tinfo()) {
735                 if (rh.bp->tinfo()==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 (rh.bp->tinfo()==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 (cit->bp->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 (cit->bp->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 (cit->rest.bp->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 (cit->rest.bp->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         sort(seq.begin(), seq.end(), expair_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         bool needs_further_processing = false;
1076         
1077         if (seq.size()>1) {
1078                 epvector::iterator itin1 = seq.begin();
1079                 epvector::iterator itin2 = itin1+1;
1080                 epvector::iterator itout = itin1;
1081                 epvector::iterator last = seq.end();
1082                 // must_copy will be set to true the first time some combination is 
1083                 // possible from then on the sequence has changed and must be compacted
1084                 bool must_copy = false;
1085                 while (itin2!=last) {
1086                         if (itin1->rest.compare(itin2->rest)==0) {
1087                                 itin1->coeff = ex_to<numeric>(itin1->coeff).
1088                                                add_dyn(ex_to<numeric>(itin2->coeff));
1089                                 if (expair_needs_further_processing(itin1))
1090                                         needs_further_processing = true;
1091                                 must_copy = true;
1092                         } else {
1093                                 if (!ex_to<numeric>(itin1->coeff).is_zero()) {
1094                                         if (must_copy)
1095                                                 *itout = *itin1;
1096                                         ++itout;
1097                                 }
1098                                 itin1 = itin2;
1099                         }
1100                         ++itin2;
1101                 }
1102                 if (!ex_to<numeric>(itin1->coeff).is_zero()) {
1103                         if (must_copy)
1104                                 *itout = *itin1;
1105                         ++itout;
1106                 }
1107                 if (itout!=last)
1108                         seq.erase(itout,last);
1109         }
1110         
1111         if (needs_further_processing) {
1112                 epvector v = seq;
1113                 seq.clear();
1114                 construct_from_epvector(v);
1115         }
1116 }
1117
1118 #if EXPAIRSEQ_USE_HASHTAB
1119
1120 unsigned expairseq::calc_hashtabsize(unsigned sz) const
1121 {
1122         unsigned size;
1123         unsigned nearest_power_of_2 = 1 << log2(sz);
1124         // if (nearest_power_of_2 < maxhashtabsize/hashtabfactor) {
1125         //  size = nearest_power_of_2*hashtabfactor;
1126         size = nearest_power_of_2/hashtabfactor;
1127         if (size<minhashtabsize)
1128                 return 0;
1129         GINAC_ASSERT(hashtabsize<=0x8000000U); // really max size due to 31 bit hashing
1130         // hashtabsize must be a power of 2
1131         GINAC_ASSERT((1U << log2(size))==size);
1132         return size;
1133 }
1134
1135 unsigned expairseq::calc_hashindex(const ex &e) const
1136 {
1137         // calculate hashindex
1138         unsigned hash = e.gethash();
1139         unsigned hashindex;
1140         if (is_a_numeric_hash(hash)) {
1141                 hashindex = hashmask;
1142         } else {
1143                 hashindex = hash &hashmask;
1144                 // last hashtab entry is reserved for numerics
1145                 if (hashindex==hashmask) hashindex = 0;
1146         }
1147         GINAC_ASSERT(hashindex>=0);
1148         GINAC_ASSERT((hashindex<hashtabsize)||(hashtabsize==0));
1149         return hashindex;
1150 }
1151
1152 void expairseq::shrink_hashtab(void)
1153 {
1154         unsigned new_hashtabsize;
1155         while (hashtabsize!=(new_hashtabsize=calc_hashtabsize(seq.size()))) {
1156                 GINAC_ASSERT(new_hashtabsize<hashtabsize);
1157                 if (new_hashtabsize==0) {
1158                         hashtab.clear();
1159                         hashtabsize = 0;
1160                         canonicalize();
1161                         return;
1162                 }
1163                 
1164                 // shrink by a factor of 2
1165                 unsigned half_hashtabsize = hashtabsize/2;
1166                 for (unsigned i=0; i<half_hashtabsize-1; ++i)
1167                         hashtab[i].merge(hashtab[i+half_hashtabsize],epp_is_less());
1168                 // special treatment for numeric hashes
1169                 hashtab[0].merge(hashtab[half_hashtabsize-1],epp_is_less());
1170                 hashtab[half_hashtabsize-1] = hashtab[hashtabsize-1];
1171                 hashtab.resize(half_hashtabsize);
1172                 hashtabsize = half_hashtabsize;
1173                 hashmask = hashtabsize-1;
1174         }
1175 }
1176
1177 void expairseq::remove_hashtab_entry(epvector::const_iterator element)
1178 {
1179         if (hashtabsize==0)
1180                 return; // nothing to do
1181         
1182         // calculate hashindex of element to be deleted
1183         unsigned hashindex = calc_hashindex((*element).rest);
1184
1185         // find it in hashtab and remove it
1186         epplist &eppl = hashtab[hashindex];
1187         epplist::iterator epplit = eppl.begin();
1188         bool erased = false;
1189         while (epplit!=eppl.end()) {
1190                 if (*epplit == element) {
1191                         eppl.erase(epplit);
1192                         erased = true;
1193                         break;
1194                 }
1195                 ++epplit;
1196         }
1197         if (!erased) {
1198                 std::cout << "tried to erase " << element-seq.begin() << std::endl;
1199                 std::cout << "size " << seq.end()-seq.begin() << std::endl;
1200
1201                 unsigned hashindex = calc_hashindex(element->rest);
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                 GINAC_ASSERT(erased);
1214         }
1215         GINAC_ASSERT(erased);
1216 }
1217
1218 void expairseq::move_hashtab_entry(epvector::const_iterator oldpos,
1219                                    epvector::iterator newpos)
1220 {
1221         GINAC_ASSERT(hashtabsize!=0);
1222         
1223         // calculate hashindex of element which was moved
1224         unsigned hashindex=calc_hashindex((*newpos).rest);
1225
1226         // find it in hashtab and modify it
1227         epplist &eppl = hashtab[hashindex];
1228         epplist::iterator epplit = eppl.begin();
1229         while (epplit!=eppl.end()) {
1230                 if (*epplit == oldpos) {
1231                         *epplit = newpos;
1232                         break;
1233                 }
1234                 ++epplit;
1235         }
1236         GINAC_ASSERT(epplit!=eppl.end());
1237 }
1238
1239 void expairseq::sorted_insert(epplist &eppl, epvector::const_iterator elem)
1240 {
1241         epplist::const_iterator current = eppl.begin();
1242         while ((current!=eppl.end()) && ((*current)->is_less(*elem))) {
1243                 ++current;
1244         }
1245         eppl.insert(current,elem);
1246 }    
1247
1248 void expairseq::build_hashtab_and_combine(epvector::iterator &first_numeric,
1249                                           epvector::iterator &last_non_zero,
1250                                           std::vector<bool> &touched,
1251                                           unsigned &number_of_zeroes)
1252 {
1253         epp current = seq.begin();
1254
1255         while (current!=first_numeric) {
1256                 if (is_ex_exactly_of_type(current->rest,numeric)) {
1257                         --first_numeric;
1258                         iter_swap(current,first_numeric);
1259                 } else {
1260                         // calculate hashindex
1261                         unsigned currenthashindex = calc_hashindex(current->rest);
1262
1263                         // test if there is already a matching expair in the hashtab-list
1264                         epplist &eppl=hashtab[currenthashindex];
1265                         epplist::iterator epplit = eppl.begin();
1266                         while (epplit!=eppl.end()) {
1267                                 if (current->rest.is_equal((*epplit)->rest))
1268                                         break;
1269                                 ++epplit;
1270                         }
1271                         if (epplit==eppl.end()) {
1272                                 // no matching expair found, append this to end of list
1273                                 sorted_insert(eppl,current);
1274                                 ++current;
1275                         } else {
1276                                 // epplit points to a matching expair, combine it with current
1277                                 (*epplit)->coeff = ex_to<numeric>((*epplit)->coeff).
1278                                                    add_dyn(ex_to<numeric>(current->coeff));
1279                                 
1280                                 // move obsolete current expair to end by swapping with last_non_zero element
1281                                 // if this was a numeric, it is swapped with the expair before first_numeric 
1282                                 iter_swap(current,last_non_zero);
1283                                 --first_numeric;
1284                                 if (first_numeric!=last_non_zero) iter_swap(first_numeric,current);
1285                                 --last_non_zero;
1286                                 ++number_of_zeroes;
1287                                 // test if combined term has coeff 0 and can be removed is done later
1288                                 touched[(*epplit)-seq.begin()] = true;
1289                         }
1290                 }
1291         }
1292 }
1293
1294 void expairseq::drop_coeff_0_terms(epvector::iterator &first_numeric,
1295                                    epvector::iterator &last_non_zero,
1296                                    std::vector<bool> &touched,
1297                                    unsigned &number_of_zeroes)
1298 {
1299         // move terms with coeff 0 to end and remove them from hashtab
1300         // check only those elements which have been touched
1301         epp current = seq.begin();
1302         unsigned i = 0;
1303         while (current!=first_numeric) {
1304                 if (!touched[i]) {
1305                         ++current;
1306                         ++i;
1307                 } else if (!ex_to<numeric>((*current).coeff).is_zero()) {
1308                         ++current;
1309                         ++i;
1310                 } else {
1311                         remove_hashtab_entry(current);
1312                         
1313                         // move element to the end, unless it is already at the end
1314                         if (current!=last_non_zero) {
1315                                 iter_swap(current,last_non_zero);
1316                                 --first_numeric;
1317                                 bool numeric_swapped = first_numeric!=last_non_zero;
1318                                 if (numeric_swapped)
1319                                         iter_swap(first_numeric,current);
1320                                 epvector::iterator changed_entry;
1321
1322                                 if (numeric_swapped)
1323                                         changed_entry = first_numeric;
1324                                 else
1325                                         changed_entry = last_non_zero;
1326                                 
1327                                 --last_non_zero;
1328                                 ++number_of_zeroes;
1329
1330                                 if (first_numeric!=current) {
1331
1332                                         // change entry in hashtab which referred to first_numeric or last_non_zero to current
1333                                         move_hashtab_entry(changed_entry,current);
1334                                         touched[current-seq.begin()] = touched[changed_entry-seq.begin()];
1335                                 }
1336                         } else {
1337                                 --first_numeric;
1338                                 --last_non_zero;
1339                                 ++number_of_zeroes;
1340                         }
1341                 }
1342         }
1343         GINAC_ASSERT(i==current-seq.begin());
1344 }
1345
1346 /** True if one of the coeffs vanishes, otherwise false.
1347  *  This would be an invariant violation, so this should only be used for
1348  *  debugging purposes. */
1349 bool expairseq::has_coeff_0(void) const
1350 {
1351         epvector::const_iterator i = seq.begin(), end = seq.end();
1352         while (i != end) {
1353                 if (i->coeff.is_zero())
1354                         return true;
1355                 ++i;
1356         }
1357         return false;
1358 }
1359
1360 void expairseq::add_numerics_to_hashtab(epvector::iterator first_numeric,
1361                                                                                 epvector::const_iterator last_non_zero)
1362 {
1363         if (first_numeric == seq.end()) return; // no numerics
1364         
1365         epvector::const_iterator current = first_numeric, last = last_non_zero + 1;
1366         while (current != last) {
1367                 sorted_insert(hashtab[hashmask], current);
1368                 ++current;
1369         }
1370 }
1371
1372 void expairseq::combine_same_terms(void)
1373 {
1374         // combine same terms, drop term with coeff 0, move numerics to end
1375         
1376         // calculate size of hashtab
1377         hashtabsize = calc_hashtabsize(seq.size());
1378         
1379         // hashtabsize is a power of 2
1380         hashmask = hashtabsize-1;
1381         
1382         // allocate hashtab
1383         hashtab.clear();
1384         hashtab.resize(hashtabsize);
1385         
1386         if (hashtabsize==0) {
1387                 canonicalize();
1388                 combine_same_terms_sorted_seq();
1389                 GINAC_ASSERT(!has_coeff_0());
1390                 return;
1391         }
1392         
1393         // iterate through seq, move numerics to end,
1394         // fill hashtab and combine same terms
1395         epvector::iterator first_numeric = seq.end();
1396         epvector::iterator last_non_zero = seq.end()-1;
1397         
1398         unsigned num = seq.size();
1399         std::vector<bool> touched(num);
1400         
1401         unsigned number_of_zeroes = 0;
1402         
1403         GINAC_ASSERT(!has_coeff_0());
1404         build_hashtab_and_combine(first_numeric,last_non_zero,touched,number_of_zeroes);
1405         
1406         // there should not be any terms with coeff 0 from the beginning,
1407         // so it should be safe to skip this step
1408         if (number_of_zeroes!=0) {
1409                 drop_coeff_0_terms(first_numeric,last_non_zero,touched,number_of_zeroes);
1410         }
1411         
1412         add_numerics_to_hashtab(first_numeric,last_non_zero);
1413         
1414         // pop zero elements
1415         for (unsigned i=0; i<number_of_zeroes; ++i) {
1416                 seq.pop_back();
1417         }
1418         
1419         // shrink hashtabsize to calculated value
1420         GINAC_ASSERT(!has_coeff_0());
1421         
1422         shrink_hashtab();
1423         
1424         GINAC_ASSERT(!has_coeff_0());
1425 }
1426
1427 #endif // EXPAIRSEQ_USE_HASHTAB
1428
1429 /** Check if this expairseq is in sorted (canonical) form.  Useful mainly for
1430  *  debugging or in assertions since being sorted is an invariance. */
1431 bool expairseq::is_canonical() const
1432 {
1433         if (seq.size() <= 1)
1434                 return 1;
1435         
1436 #if EXPAIRSEQ_USE_HASHTAB
1437         if (hashtabsize > 0) return 1; // not canoncalized
1438 #endif // EXPAIRSEQ_USE_HASHTAB
1439         
1440         epvector::const_iterator it = seq.begin(), itend = seq.end();
1441         epvector::const_iterator it_last = it;
1442         for (++it; it!=itend; it_last=it, ++it) {
1443                 if (!(it_last->is_less(*it) || it_last->is_equal(*it))) {
1444                         if (!is_ex_exactly_of_type(it_last->rest,numeric) ||
1445                                 !is_ex_exactly_of_type(it->rest,numeric)) {
1446                                 // double test makes it easier to set a breakpoint...
1447                                 if (!is_ex_exactly_of_type(it_last->rest,numeric) ||
1448                                         !is_ex_exactly_of_type(it->rest,numeric)) {
1449                                         printpair(std::clog, *it_last, 0);
1450                                         std::clog << ">";
1451                                         printpair(std::clog, *it, 0);
1452                                         std::clog << "\n";
1453                                         std::clog << "pair1:" << std::endl;
1454                                         it_last->rest.print(print_tree(std::clog));
1455                                         it_last->coeff.print(print_tree(std::clog));
1456                                         std::clog << "pair2:" << std::endl;
1457                                         it->rest.print(print_tree(std::clog));
1458                                         it->coeff.print(print_tree(std::clog));
1459                                         return 0;
1460                                 }
1461                         }
1462                 }
1463         }
1464         return 1;
1465 }
1466
1467
1468 /** Member-wise expand the expairs in this sequence.
1469  *
1470  *  @see expairseq::expand()
1471  *  @return pointer to epvector containing expanded pairs or zero pointer,
1472  *  if no members were changed. */
1473 epvector * expairseq::expandchildren(unsigned options) const
1474 {
1475         epvector::const_iterator last = seq.end();
1476         epvector::const_iterator cit = seq.begin();
1477         while (cit!=last) {
1478                 const ex &expanded_ex = cit->rest.expand(options);
1479                 if (!are_ex_trivially_equal(cit->rest,expanded_ex)) {
1480                         
1481                         // something changed, copy seq, eval and return it
1482                         epvector *s = new epvector;
1483                         s->reserve(seq.size());
1484                         
1485                         // copy parts of seq which are known not to have changed
1486                         epvector::const_iterator cit2 = seq.begin();
1487                         while (cit2!=cit) {
1488                                 s->push_back(*cit2);
1489                                 ++cit2;
1490                         }
1491                         // copy first changed element
1492                         s->push_back(combine_ex_with_coeff_to_pair(expanded_ex,
1493                                                                    cit2->coeff));
1494                         ++cit2;
1495                         // copy rest
1496                         while (cit2!=last) {
1497                                 s->push_back(combine_ex_with_coeff_to_pair(cit2->rest.expand(options),
1498                                                                            cit2->coeff));
1499                                 ++cit2;
1500                         }
1501                         return s;
1502                 }
1503                 ++cit;
1504         }
1505         
1506         return 0; // signalling nothing has changed
1507 }
1508
1509
1510 /** Member-wise evaluate the expairs in this sequence.
1511  *
1512  *  @see expairseq::eval()
1513  *  @return pointer to epvector containing evaluated pairs or zero pointer,
1514  *  if no members were changed. */
1515 epvector * expairseq::evalchildren(int level) const
1516 {
1517         // returns a NULL pointer if nothing had to be evaluated
1518         // returns a pointer to a newly created epvector otherwise
1519         // (which has to be deleted somewhere else)
1520
1521         if (level==1)
1522                 return 0;
1523         
1524         if (level == -max_recursion_level)
1525                 throw(std::runtime_error("max recursion level reached"));
1526         
1527         --level;
1528         epvector::const_iterator last = seq.end();
1529         epvector::const_iterator cit = seq.begin();
1530         while (cit!=last) {
1531                 const ex &evaled_ex = cit->rest.eval(level);
1532                 if (!are_ex_trivially_equal(cit->rest,evaled_ex)) {
1533                         
1534                         // something changed, copy seq, eval and return it
1535                         epvector *s = new epvector;
1536                         s->reserve(seq.size());
1537                         
1538                         // copy parts of seq which are known not to have changed
1539                         epvector::const_iterator cit2=seq.begin();
1540                         while (cit2!=cit) {
1541                                 s->push_back(*cit2);
1542                                 ++cit2;
1543                         }
1544                         // copy first changed element
1545                         s->push_back(combine_ex_with_coeff_to_pair(evaled_ex,
1546                                                                    cit2->coeff));
1547                         ++cit2;
1548                         // copy rest
1549                         while (cit2!=last) {
1550                                 s->push_back(combine_ex_with_coeff_to_pair(cit2->rest.eval(level),
1551                                                                            cit2->coeff));
1552                                 ++cit2;
1553                         }
1554                         return s;
1555                 }
1556                 ++cit;
1557         }
1558         
1559         return 0; // signalling nothing has changed
1560 }
1561
1562
1563 /** Member-wise substitute in this sequence.
1564  *
1565  *  @see expairseq::subs()
1566  *  @return pointer to epvector containing pairs after application of subs,
1567  *    or NULL pointer if no members were changed. */
1568 epvector * expairseq::subschildren(const lst &ls, const lst &lr, bool no_pattern) const
1569 {
1570         GINAC_ASSERT(ls.nops()==lr.nops());
1571
1572         // The substitution is "complex" when any of the objects to be substituted
1573         // is a product or power. In this case we have to recombine the pairs
1574         // because the numeric coefficients may be part of the search pattern.
1575         bool complex_subs = false;
1576         for (unsigned i=0; i<ls.nops(); ++i)
1577                 if (is_ex_exactly_of_type(ls.op(i), mul) || is_ex_exactly_of_type(ls.op(i), power)) {
1578                         complex_subs = true;
1579                         break;
1580                 }
1581
1582         if (complex_subs) {
1583
1584                 // Substitute in the recombined pairs
1585                 epvector::const_iterator cit = seq.begin(), last = seq.end();
1586                 while (cit != last) {
1587
1588                         const ex &orig_ex = recombine_pair_to_ex(*cit);
1589                         const ex &subsed_ex = orig_ex.subs(ls, lr, no_pattern);
1590                         if (!are_ex_trivially_equal(orig_ex, subsed_ex)) {
1591
1592                                 // Something changed, copy seq, subs and return it
1593                                 epvector *s = new epvector;
1594                                 s->reserve(seq.size());
1595
1596                                 // Copy parts of seq which are known not to have changed
1597                                 s->insert(s->begin(), seq.begin(), cit);
1598
1599                                 // Copy first changed element
1600                                 s->push_back(split_ex_to_pair(subsed_ex));
1601                                 ++cit;
1602
1603                                 // Copy rest
1604                                 while (cit != last) {
1605                                         s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit).subs(ls, lr, no_pattern)));
1606                                         ++cit;
1607                                 }
1608                                 return s;
1609                         }
1610
1611                         ++cit;
1612                 }
1613
1614         } else {
1615
1616                 // Substitute only in the "rest" part of the pairs
1617                 epvector::const_iterator cit = seq.begin(), last = seq.end();
1618                 while (cit != last) {
1619
1620                         const ex &subsed_ex = cit->rest.subs(ls, lr, no_pattern);
1621                         if (!are_ex_trivially_equal(cit->rest, subsed_ex)) {
1622                         
1623                                 // Something changed, copy seq, subs and return it
1624                                 epvector *s = new epvector;
1625                                 s->reserve(seq.size());
1626
1627                                 // Copy parts of seq which are known not to have changed
1628                                 s->insert(s->begin(), seq.begin(), cit);
1629                         
1630                                 // Copy first changed element
1631                                 s->push_back(combine_ex_with_coeff_to_pair(subsed_ex, cit->coeff));
1632                                 ++cit;
1633
1634                                 // Copy rest
1635                                 while (cit != last) {
1636                                         s->push_back(combine_ex_with_coeff_to_pair(cit->rest.subs(ls, lr, no_pattern),
1637                                                                                    cit->coeff));
1638                                         ++cit;
1639                                 }
1640                                 return s;
1641                         }
1642
1643                         ++cit;
1644                 }
1645         }
1646         
1647         // Nothing has changed
1648         return NULL;
1649 }
1650
1651 //////////
1652 // static member variables
1653 //////////
1654
1655 #if EXPAIRSEQ_USE_HASHTAB
1656 unsigned expairseq::maxhashtabsize = 0x4000000U;
1657 unsigned expairseq::minhashtabsize = 0x1000U;
1658 unsigned expairseq::hashtabfactor = 1;
1659 #endif // EXPAIRSEQ_USE_HASHTAB
1660
1661 } // namespace GiNaC