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