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