1 /** @file expairseq.cpp
3 * Implementation of sequences of expression pairs. */
6 * GiNaC Copyright (C) 1999-2004 Johannes Gutenberg University Mainz, Germany
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.
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.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28 #include "expairseq.h"
32 #include "relational.h"
35 #include "operators.h"
38 #if EXPAIRSEQ_USE_HASHTAB
40 #endif // EXPAIRSEQ_USE_HASHTAB
45 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(expairseq, basic,
46 print_func<print_context>(&expairseq::do_print).
47 print_func<print_tree>(&expairseq::do_print_tree))
57 bool operator()(const epp &lh, const epp &rh) const
59 return (*lh).is_less(*rh);
64 // default constructor
69 expairseq::expairseq() : inherited(TINFO_expairseq)
70 #if EXPAIRSEQ_USE_HASHTAB
72 #endif // EXPAIRSEQ_USE_HASHTAB
78 /** For use by copy ctor and assignment operator. */
79 void expairseq::copy(const expairseq &other)
82 overall_coeff = other.overall_coeff;
83 #if EXPAIRSEQ_USE_HASHTAB
85 hashtabsize = other.hashtabsize;
87 hashmask = other.hashmask;
88 hashtab.resize(hashtabsize);
89 epvector::const_iterator osb = other.seq.begin();
90 for (unsigned i=0; i<hashtabsize; ++i) {
92 for (epplist::const_iterator cit=other.hashtab[i].begin();
93 cit!=other.hashtab[i].end(); ++cit) {
94 hashtab[i].push_back(seq.begin()+((*cit)-osb));
100 #endif // EXPAIRSEQ_USE_HASHTAB
105 // other constructors
108 expairseq::expairseq(const ex &lh, const ex &rh) : inherited(TINFO_expairseq)
110 construct_from_2_ex(lh,rh);
111 GINAC_ASSERT(is_canonical());
114 expairseq::expairseq(const exvector &v) : inherited(TINFO_expairseq)
116 construct_from_exvector(v);
117 GINAC_ASSERT(is_canonical());
120 expairseq::expairseq(const epvector &v, const ex &oc)
121 : inherited(TINFO_expairseq), overall_coeff(oc)
123 GINAC_ASSERT(is_a<numeric>(oc));
124 construct_from_epvector(v);
125 GINAC_ASSERT(is_canonical());
128 expairseq::expairseq(std::auto_ptr<epvector> vp, const ex &oc)
129 : inherited(TINFO_expairseq), overall_coeff(oc)
132 GINAC_ASSERT(is_a<numeric>(oc));
133 construct_from_epvector(*vp);
134 GINAC_ASSERT(is_canonical());
141 expairseq::expairseq(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
142 #if EXPAIRSEQ_USE_HASHTAB
146 for (unsigned int i=0; true; i++) {
149 if (n.find_ex("rest", rest, sym_lst, i) && n.find_ex("coeff", coeff, sym_lst, i))
150 seq.push_back(expair(rest, coeff));
155 n.find_ex("overall_coeff", overall_coeff, sym_lst);
158 GINAC_ASSERT(is_canonical());
161 void expairseq::archive(archive_node &n) const
163 inherited::archive(n);
164 epvector::const_iterator i = seq.begin(), iend = seq.end();
166 n.add_ex("rest", i->rest);
167 n.add_ex("coeff", i->coeff);
170 n.add_ex("overall_coeff", overall_coeff);
173 DEFAULT_UNARCHIVE(expairseq)
176 // functions overriding virtual functions from base classes
181 void expairseq::do_print(const print_context & c, unsigned level) const
184 printseq(c, ',', precedence(), level);
188 void expairseq::do_print_tree(const print_tree & c, unsigned level) const
190 c.s << std::string(level, ' ') << class_name() << " @" << this
191 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
192 << ", nops=" << nops()
194 size_t num = seq.size();
195 for (size_t i=0; i<num; ++i) {
196 seq[i].rest.print(c, level + c.delta_indent);
197 seq[i].coeff.print(c, level + c.delta_indent);
199 c.s << std::string(level + c.delta_indent, ' ') << "-----" << std::endl;
201 if (!overall_coeff.is_equal(default_overall_coeff())) {
202 c.s << std::string(level + c.delta_indent, ' ') << "-----" << std::endl
203 << std::string(level + c.delta_indent, ' ') << "overall_coeff" << std::endl;
204 overall_coeff.print(c, level + c.delta_indent);
206 c.s << std::string(level + c.delta_indent,' ') << "=====" << std::endl;
207 #if EXPAIRSEQ_USE_HASHTAB
208 c.s << std::string(level + c.delta_indent,' ')
209 << "hashtab size " << hashtabsize << std::endl;
210 if (hashtabsize == 0) return;
212 unsigned count[MAXCOUNT+1];
213 for (int i=0; i<MAXCOUNT+1; ++i)
215 unsigned this_bin_fill;
216 unsigned cum_fill_sq = 0;
217 unsigned cum_fill = 0;
218 for (unsigned i=0; i<hashtabsize; ++i) {
220 if (hashtab[i].size() > 0) {
221 c.s << std::string(level + c.delta_indent, ' ')
222 << "bin " << i << " with entries ";
223 for (epplist::const_iterator it=hashtab[i].begin();
224 it!=hashtab[i].end(); ++it) {
225 c.s << *it-seq.begin() << " ";
229 cum_fill += this_bin_fill;
230 cum_fill_sq += this_bin_fill*this_bin_fill;
232 if (this_bin_fill<MAXCOUNT)
233 ++count[this_bin_fill];
239 double lambda = (1.0*seq.size()) / hashtabsize;
240 for (int k=0; k<MAXCOUNT; ++k) {
243 double prob = std::pow(lambda,k)/fact * std::exp(-lambda);
245 c.s << std::string(level + c.delta_indent, ' ') << "bins with " << k << " entries: "
246 << int(1000.0*count[k]/hashtabsize)/10.0 << "% (expected: "
247 << int(prob*1000)/10.0 << ")" << std::endl;
249 c.s << std::string(level + c.delta_indent, ' ') << "bins with more entries: "
250 << int(1000.0*count[MAXCOUNT]/hashtabsize)/10.0 << "% (expected: "
251 << int((1-cum_prob)*1000)/10.0 << ")" << std::endl;
253 c.s << std::string(level + c.delta_indent, ' ') << "variance: "
254 << 1.0/hashtabsize*cum_fill_sq-(1.0/hashtabsize*cum_fill)*(1.0/hashtabsize*cum_fill)
256 c.s << std::string(level + c.delta_indent, ' ') << "average fill: "
257 << (1.0*cum_fill)/hashtabsize
258 << " (should be equal to " << (1.0*seq.size())/hashtabsize << ")" << std::endl;
259 #endif // EXPAIRSEQ_USE_HASHTAB
262 bool expairseq::info(unsigned inf) const
264 return inherited::info(inf);
267 size_t expairseq::nops() const
269 if (overall_coeff.is_equal(default_overall_coeff()))
275 ex expairseq::op(size_t i) const
278 return recombine_pair_to_ex(seq[i]);
279 GINAC_ASSERT(!overall_coeff.is_equal(default_overall_coeff()));
280 return overall_coeff;
283 ex expairseq::map(map_function &f) const
285 std::auto_ptr<epvector> v(new epvector);
286 v->reserve(seq.size());
288 epvector::const_iterator cit = seq.begin(), last = seq.end();
289 while (cit != last) {
290 v->push_back(split_ex_to_pair(f(recombine_pair_to_ex(*cit))));
294 if (overall_coeff.is_equal(default_overall_coeff()))
295 return thisexpairseq(v, default_overall_coeff());
297 return thisexpairseq(v, f(overall_coeff));
300 /** Perform coefficient-wise automatic term rewriting rules in this class. */
301 ex expairseq::eval(int level) const
303 if ((level==1) && (flags &status_flags::evaluated))
306 std::auto_ptr<epvector> vp = evalchildren(level);
310 return (new expairseq(vp, overall_coeff))->setflag(status_flags::dynallocated | status_flags::evaluated);
313 epvector* conjugateepvector(const epvector&epv)
315 epvector *newepv = 0;
316 for (epvector::const_iterator i=epv.begin(); i!=epv.end(); ++i) {
318 newepv->push_back(i->conjugate());
321 expair x = i->conjugate();
322 if (x.is_equal(*i)) {
325 newepv = new epvector;
326 newepv->reserve(epv.size());
327 for (epvector::const_iterator j=epv.begin(); j!=i; ++j) {
328 newepv->push_back(*j);
330 newepv->push_back(x);
335 ex expairseq::conjugate() const
337 epvector* newepv = conjugateepvector(seq);
338 ex x = overall_coeff.conjugate();
339 if (!newepv && are_ex_trivially_equal(x, overall_coeff)) {
342 ex result = thisexpairseq(newepv ? *newepv : seq, x);
349 bool expairseq::match(const ex & pattern, lst & repl_lst) const
351 // This differs from basic::match() because we want "a+b+c+d" to
352 // match "d+*+b" with "*" being "a+c", and we want to honor commutativity
354 if (this->tinfo() == ex_to<basic>(pattern).tinfo()) {
356 // Check whether global wildcard (one that matches the "rest of the
357 // expression", like "*" above) is present
358 bool has_global_wildcard = false;
360 for (size_t i=0; i<pattern.nops(); i++) {
361 if (is_exactly_a<wildcard>(pattern.op(i))) {
362 has_global_wildcard = true;
363 global_wildcard = pattern.op(i);
368 // Unfortunately, this is an O(N^2) operation because we can't
369 // sort the pattern in a useful way...
374 for (size_t i=0; i<nops(); i++)
375 ops.push_back(op(i));
377 // Now, for every term of the pattern, look for a matching term in
378 // the expression and remove the match
379 for (size_t i=0; i<pattern.nops(); i++) {
380 ex p = pattern.op(i);
381 if (has_global_wildcard && p.is_equal(global_wildcard))
383 exvector::iterator it = ops.begin(), itend = ops.end();
384 while (it != itend) {
385 if (it->match(p, repl_lst)) {
391 return false; // no match found
395 if (has_global_wildcard) {
397 // Assign all the remaining terms to the global wildcard (unless
398 // it has already been matched before, in which case the matches
400 size_t num = ops.size();
401 std::auto_ptr<epvector> vp(new epvector);
403 for (size_t i=0; i<num; i++)
404 vp->push_back(split_ex_to_pair(ops[i]));
405 ex rest = thisexpairseq(vp, default_overall_coeff());
406 for (lst::const_iterator it = repl_lst.begin(); it != repl_lst.end(); ++it) {
407 if (it->op(0).is_equal(global_wildcard))
408 return rest.is_equal(it->op(1));
410 repl_lst.append(global_wildcard == rest);
415 // No global wildcard, then the match fails if there are any
416 // unmatched terms left
420 return inherited::match(pattern, repl_lst);
423 ex expairseq::subs(const exmap & m, unsigned options) const
425 std::auto_ptr<epvector> vp = subschildren(m, options);
427 return ex_to<basic>(thisexpairseq(vp, overall_coeff));
428 else if ((options & subs_options::algebraic) && is_exactly_a<mul>(*this))
429 return static_cast<const mul *>(this)->algebraic_subs_mul(m, options);
431 return subs_one_level(m, options);
436 int expairseq::compare_same_type(const basic &other) const
438 GINAC_ASSERT(is_a<expairseq>(other));
439 const expairseq &o = static_cast<const expairseq &>(other);
443 // compare number of elements
444 if (seq.size() != o.seq.size())
445 return (seq.size()<o.seq.size()) ? -1 : 1;
447 // compare overall_coeff
448 cmpval = overall_coeff.compare(o.overall_coeff);
452 #if EXPAIRSEQ_USE_HASHTAB
453 GINAC_ASSERT(hashtabsize==o.hashtabsize);
454 if (hashtabsize==0) {
455 #endif // EXPAIRSEQ_USE_HASHTAB
456 epvector::const_iterator cit1 = seq.begin();
457 epvector::const_iterator cit2 = o.seq.begin();
458 epvector::const_iterator last1 = seq.end();
459 epvector::const_iterator last2 = o.seq.end();
461 for (; (cit1!=last1)&&(cit2!=last2); ++cit1, ++cit2) {
462 cmpval = (*cit1).compare(*cit2);
463 if (cmpval!=0) return cmpval;
466 GINAC_ASSERT(cit1==last1);
467 GINAC_ASSERT(cit2==last2);
470 #if EXPAIRSEQ_USE_HASHTAB
473 // compare number of elements in each hashtab entry
474 for (unsigned i=0; i<hashtabsize; ++i) {
475 unsigned cursize=hashtab[i].size();
476 if (cursize != o.hashtab[i].size())
477 return (cursize < o.hashtab[i].size()) ? -1 : 1;
480 // compare individual (sorted) hashtab entries
481 for (unsigned i=0; i<hashtabsize; ++i) {
482 unsigned sz = hashtab[i].size();
484 const epplist &eppl1 = hashtab[i];
485 const epplist &eppl2 = o.hashtab[i];
486 epplist::const_iterator it1 = eppl1.begin();
487 epplist::const_iterator it2 = eppl2.begin();
488 while (it1!=eppl1.end()) {
489 cmpval = (*(*it1)).compare(*(*it2));
499 #endif // EXPAIRSEQ_USE_HASHTAB
502 bool expairseq::is_equal_same_type(const basic &other) const
504 const expairseq &o = static_cast<const expairseq &>(other);
506 // compare number of elements
507 if (seq.size()!=o.seq.size())
510 // compare overall_coeff
511 if (!overall_coeff.is_equal(o.overall_coeff))
514 #if EXPAIRSEQ_USE_HASHTAB
515 // compare number of elements in each hashtab entry
516 if (hashtabsize!=o.hashtabsize) {
517 std::cout << "this:" << std::endl;
518 print(print_tree(std::cout));
519 std::cout << "other:" << std::endl;
520 other.print(print_tree(std::cout));
523 GINAC_ASSERT(hashtabsize==o.hashtabsize);
525 if (hashtabsize==0) {
526 #endif // EXPAIRSEQ_USE_HASHTAB
527 epvector::const_iterator cit1 = seq.begin();
528 epvector::const_iterator cit2 = o.seq.begin();
529 epvector::const_iterator last1 = seq.end();
531 while (cit1!=last1) {
532 if (!(*cit1).is_equal(*cit2)) return false;
538 #if EXPAIRSEQ_USE_HASHTAB
541 for (unsigned i=0; i<hashtabsize; ++i) {
542 if (hashtab[i].size() != o.hashtab[i].size())
546 // compare individual sorted hashtab entries
547 for (unsigned i=0; i<hashtabsize; ++i) {
548 unsigned sz = hashtab[i].size();
550 const epplist &eppl1 = hashtab[i];
551 const epplist &eppl2 = o.hashtab[i];
552 epplist::const_iterator it1 = eppl1.begin();
553 epplist::const_iterator it2 = eppl2.begin();
554 while (it1!=eppl1.end()) {
555 if (!(*(*it1)).is_equal(*(*it2))) return false;
563 #endif // EXPAIRSEQ_USE_HASHTAB
566 unsigned expairseq::return_type() const
568 return return_types::noncommutative_composite;
571 unsigned expairseq::calchash() const
573 unsigned v = golden_ratio_hash(this->tinfo());
574 epvector::const_iterator i = seq.begin();
575 const epvector::const_iterator end = seq.end();
577 v ^= i->rest.gethash();
578 #if !EXPAIRSEQ_USE_HASHTAB
579 // rotation spoils commutativity!
581 v ^= i->coeff.gethash();
582 #endif // !EXPAIRSEQ_USE_HASHTAB
586 v ^= overall_coeff.gethash();
588 // store calculated hash value only if object is already evaluated
589 if (flags &status_flags::evaluated) {
590 setflag(status_flags::hash_calculated);
597 ex expairseq::expand(unsigned options) const
599 std::auto_ptr<epvector> vp = expandchildren(options);
601 return thisexpairseq(vp, overall_coeff);
603 // The terms have not changed, so it is safe to declare this expanded
604 return (options == 0) ? setflag(status_flags::expanded) : *this;
609 // new virtual functions which can be overridden by derived classes
614 /** Create an object of this type.
615 * This method works similar to a constructor. It is useful because expairseq
616 * has (at least) two possible different semantics but we want to inherit
617 * methods thus avoiding code duplication. Sometimes a method in expairseq
618 * has to create a new one of the same semantics, which cannot be done by a
619 * ctor because the name (add, mul,...) is unknown on the expaiseq level. In
620 * order for this trick to work a derived class must of course override this
622 ex expairseq::thisexpairseq(const epvector &v, const ex &oc) const
624 return expairseq(v, oc);
627 ex expairseq::thisexpairseq(std::auto_ptr<epvector> vp, const ex &oc) const
629 return expairseq(vp, oc);
632 void expairseq::printpair(const print_context & c, const expair & p, unsigned upper_precedence) const
635 p.rest.print(c, precedence());
637 p.coeff.print(c, precedence());
641 void expairseq::printseq(const print_context & c, char delim,
642 unsigned this_precedence,
643 unsigned upper_precedence) const
645 if (this_precedence <= upper_precedence)
647 epvector::const_iterator it, it_last = seq.end() - 1;
648 for (it=seq.begin(); it!=it_last; ++it) {
649 printpair(c, *it, this_precedence);
652 printpair(c, *it, this_precedence);
653 if (!overall_coeff.is_equal(default_overall_coeff())) {
655 overall_coeff.print(c, this_precedence);
658 if (this_precedence <= upper_precedence)
663 /** Form an expair from an ex, using the corresponding semantics.
664 * @see expairseq::recombine_pair_to_ex() */
665 expair expairseq::split_ex_to_pair(const ex &e) const
667 return expair(e,_ex1);
671 expair expairseq::combine_ex_with_coeff_to_pair(const ex &e,
674 GINAC_ASSERT(is_exactly_a<numeric>(c));
680 expair expairseq::combine_pair_with_coeff_to_pair(const expair &p,
683 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
684 GINAC_ASSERT(is_exactly_a<numeric>(c));
686 return expair(p.rest,ex_to<numeric>(p.coeff).mul_dyn(ex_to<numeric>(c)));
690 /** Form an ex out of an expair, using the corresponding semantics.
691 * @see expairseq::split_ex_to_pair() */
692 ex expairseq::recombine_pair_to_ex(const expair &p) const
694 return lst(p.rest,p.coeff);
697 bool expairseq::expair_needs_further_processing(epp it)
699 #if EXPAIRSEQ_USE_HASHTAB
700 //# error "FIXME: expair_needs_further_processing not yet implemented for hashtabs, sorry. A.F."
701 #endif // EXPAIRSEQ_USE_HASHTAB
705 ex expairseq::default_overall_coeff() const
710 void expairseq::combine_overall_coeff(const ex &c)
712 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
713 GINAC_ASSERT(is_exactly_a<numeric>(c));
714 overall_coeff = ex_to<numeric>(overall_coeff).add_dyn(ex_to<numeric>(c));
717 void expairseq::combine_overall_coeff(const ex &c1, const ex &c2)
719 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
720 GINAC_ASSERT(is_exactly_a<numeric>(c1));
721 GINAC_ASSERT(is_exactly_a<numeric>(c2));
722 overall_coeff = ex_to<numeric>(overall_coeff).
723 add_dyn(ex_to<numeric>(c1).mul(ex_to<numeric>(c2)));
726 bool expairseq::can_make_flat(const expair &p) const
733 // non-virtual functions in this class
736 void expairseq::construct_from_2_ex_via_exvector(const ex &lh, const ex &rh)
742 construct_from_exvector(v);
743 #if EXPAIRSEQ_USE_HASHTAB
744 GINAC_ASSERT((hashtabsize==0)||(hashtabsize>=minhashtabsize));
745 GINAC_ASSERT(hashtabsize==calc_hashtabsize(seq.size()));
746 #endif // EXPAIRSEQ_USE_HASHTAB
749 void expairseq::construct_from_2_ex(const ex &lh, const ex &rh)
751 if (ex_to<basic>(lh).tinfo()==this->tinfo()) {
752 if (ex_to<basic>(rh).tinfo()==this->tinfo()) {
753 #if EXPAIRSEQ_USE_HASHTAB
754 unsigned totalsize = ex_to<expairseq>(lh).seq.size() +
755 ex_to<expairseq>(rh).seq.size();
756 if (calc_hashtabsize(totalsize)!=0) {
757 construct_from_2_ex_via_exvector(lh,rh);
759 #endif // EXPAIRSEQ_USE_HASHTAB
760 construct_from_2_expairseq(ex_to<expairseq>(lh),
761 ex_to<expairseq>(rh));
762 #if EXPAIRSEQ_USE_HASHTAB
764 #endif // EXPAIRSEQ_USE_HASHTAB
767 #if EXPAIRSEQ_USE_HASHTAB
768 unsigned totalsize = ex_to<expairseq>(lh).seq.size()+1;
769 if (calc_hashtabsize(totalsize)!=0) {
770 construct_from_2_ex_via_exvector(lh, rh);
772 #endif // EXPAIRSEQ_USE_HASHTAB
773 construct_from_expairseq_ex(ex_to<expairseq>(lh), rh);
774 #if EXPAIRSEQ_USE_HASHTAB
776 #endif // EXPAIRSEQ_USE_HASHTAB
779 } else if (ex_to<basic>(rh).tinfo()==this->tinfo()) {
780 #if EXPAIRSEQ_USE_HASHTAB
781 unsigned totalsize=ex_to<expairseq>(rh).seq.size()+1;
782 if (calc_hashtabsize(totalsize)!=0) {
783 construct_from_2_ex_via_exvector(lh,rh);
785 #endif // EXPAIRSEQ_USE_HASHTAB
786 construct_from_expairseq_ex(ex_to<expairseq>(rh),lh);
787 #if EXPAIRSEQ_USE_HASHTAB
789 #endif // EXPAIRSEQ_USE_HASHTAB
793 #if EXPAIRSEQ_USE_HASHTAB
794 if (calc_hashtabsize(2)!=0) {
795 construct_from_2_ex_via_exvector(lh,rh);
799 #endif // EXPAIRSEQ_USE_HASHTAB
801 if (is_exactly_a<numeric>(lh)) {
802 if (is_exactly_a<numeric>(rh)) {
803 combine_overall_coeff(lh);
804 combine_overall_coeff(rh);
806 combine_overall_coeff(lh);
807 seq.push_back(split_ex_to_pair(rh));
810 if (is_exactly_a<numeric>(rh)) {
811 combine_overall_coeff(rh);
812 seq.push_back(split_ex_to_pair(lh));
814 expair p1 = split_ex_to_pair(lh);
815 expair p2 = split_ex_to_pair(rh);
817 int cmpval = p1.rest.compare(p2.rest);
819 p1.coeff = ex_to<numeric>(p1.coeff).add_dyn(ex_to<numeric>(p2.coeff));
820 if (!ex_to<numeric>(p1.coeff).is_zero()) {
821 // no further processing is necessary, since this
822 // one element will usually be recombined in eval()
839 void expairseq::construct_from_2_expairseq(const expairseq &s1,
842 combine_overall_coeff(s1.overall_coeff);
843 combine_overall_coeff(s2.overall_coeff);
845 epvector::const_iterator first1 = s1.seq.begin();
846 epvector::const_iterator last1 = s1.seq.end();
847 epvector::const_iterator first2 = s2.seq.begin();
848 epvector::const_iterator last2 = s2.seq.end();
850 seq.reserve(s1.seq.size()+s2.seq.size());
852 bool needs_further_processing=false;
854 while (first1!=last1 && first2!=last2) {
855 int cmpval = (*first1).rest.compare((*first2).rest);
858 const numeric &newcoeff = ex_to<numeric>(first1->coeff).
859 add(ex_to<numeric>(first2->coeff));
860 if (!newcoeff.is_zero()) {
861 seq.push_back(expair(first1->rest,newcoeff));
862 if (expair_needs_further_processing(seq.end()-1)) {
863 needs_further_processing = true;
868 } else if (cmpval<0) {
869 seq.push_back(*first1);
872 seq.push_back(*first2);
877 while (first1!=last1) {
878 seq.push_back(*first1);
881 while (first2!=last2) {
882 seq.push_back(*first2);
886 if (needs_further_processing) {
889 construct_from_epvector(v);
893 void expairseq::construct_from_expairseq_ex(const expairseq &s,
896 combine_overall_coeff(s.overall_coeff);
897 if (is_exactly_a<numeric>(e)) {
898 combine_overall_coeff(e);
903 epvector::const_iterator first = s.seq.begin();
904 epvector::const_iterator last = s.seq.end();
905 expair p = split_ex_to_pair(e);
907 seq.reserve(s.seq.size()+1);
908 bool p_pushed = false;
910 bool needs_further_processing=false;
912 // merge p into s.seq
913 while (first!=last) {
914 int cmpval = (*first).rest.compare(p.rest);
917 const numeric &newcoeff = ex_to<numeric>(first->coeff).
918 add(ex_to<numeric>(p.coeff));
919 if (!newcoeff.is_zero()) {
920 seq.push_back(expair(first->rest,newcoeff));
921 if (expair_needs_further_processing(seq.end()-1))
922 needs_further_processing = true;
927 } else if (cmpval<0) {
928 seq.push_back(*first);
938 // while loop exited because p was pushed, now push rest of s.seq
939 while (first!=last) {
940 seq.push_back(*first);
944 // while loop exited because s.seq was pushed, now push p
948 if (needs_further_processing) {
951 construct_from_epvector(v);
955 void expairseq::construct_from_exvector(const exvector &v)
957 // simplifications: +(a,+(b,c),d) -> +(a,b,c,d) (associativity)
958 // +(d,b,c,a) -> +(a,b,c,d) (canonicalization)
959 // +(...,x,*(x,c1),*(x,c2)) -> +(...,*(x,1+c1+c2)) (c1, c2 numeric())
960 // (same for (+,*) -> (*,^)
963 #if EXPAIRSEQ_USE_HASHTAB
964 combine_same_terms();
967 combine_same_terms_sorted_seq();
968 #endif // EXPAIRSEQ_USE_HASHTAB
971 void expairseq::construct_from_epvector(const epvector &v)
973 // simplifications: +(a,+(b,c),d) -> +(a,b,c,d) (associativity)
974 // +(d,b,c,a) -> +(a,b,c,d) (canonicalization)
975 // +(...,x,*(x,c1),*(x,c2)) -> +(...,*(x,1+c1+c2)) (c1, c2 numeric())
976 // (same for (+,*) -> (*,^)
979 #if EXPAIRSEQ_USE_HASHTAB
980 combine_same_terms();
983 combine_same_terms_sorted_seq();
984 #endif // EXPAIRSEQ_USE_HASHTAB
987 /** Combine this expairseq with argument exvector.
988 * It cares for associativity as well as for special handling of numerics. */
989 void expairseq::make_flat(const exvector &v)
991 exvector::const_iterator cit;
993 // count number of operands which are of same expairseq derived type
994 // and their cumulative number of operands
999 while (cit!=v.end()) {
1000 if (ex_to<basic>(*cit).tinfo()==this->tinfo()) {
1002 noperands += ex_to<expairseq>(*cit).seq.size();
1007 // reserve seq and coeffseq which will hold all operands
1008 seq.reserve(v.size()+noperands-nexpairseqs);
1010 // copy elements and split off numerical part
1012 while (cit!=v.end()) {
1013 if (ex_to<basic>(*cit).tinfo()==this->tinfo()) {
1014 const expairseq &subseqref = ex_to<expairseq>(*cit);
1015 combine_overall_coeff(subseqref.overall_coeff);
1016 epvector::const_iterator cit_s = subseqref.seq.begin();
1017 while (cit_s!=subseqref.seq.end()) {
1018 seq.push_back(*cit_s);
1022 if (is_exactly_a<numeric>(*cit))
1023 combine_overall_coeff(*cit);
1025 seq.push_back(split_ex_to_pair(*cit));
1031 /** Combine this expairseq with argument epvector.
1032 * It cares for associativity as well as for special handling of numerics. */
1033 void expairseq::make_flat(const epvector &v)
1035 epvector::const_iterator cit;
1037 // count number of operands which are of same expairseq derived type
1038 // and their cumulative number of operands
1039 int nexpairseqs = 0;
1043 while (cit!=v.end()) {
1044 if (ex_to<basic>(cit->rest).tinfo()==this->tinfo()) {
1046 noperands += ex_to<expairseq>(cit->rest).seq.size();
1051 // reserve seq and coeffseq which will hold all operands
1052 seq.reserve(v.size()+noperands-nexpairseqs);
1054 // copy elements and split off numerical part
1056 while (cit!=v.end()) {
1057 if (ex_to<basic>(cit->rest).tinfo()==this->tinfo() &&
1058 this->can_make_flat(*cit)) {
1059 const expairseq &subseqref = ex_to<expairseq>(cit->rest);
1060 combine_overall_coeff(ex_to<numeric>(subseqref.overall_coeff),
1061 ex_to<numeric>(cit->coeff));
1062 epvector::const_iterator cit_s = subseqref.seq.begin();
1063 while (cit_s!=subseqref.seq.end()) {
1064 seq.push_back(expair(cit_s->rest,
1065 ex_to<numeric>(cit_s->coeff).mul_dyn(ex_to<numeric>(cit->coeff))));
1066 //seq.push_back(combine_pair_with_coeff_to_pair(*cit_s,
1071 if (cit->is_canonical_numeric())
1072 combine_overall_coeff(cit->rest);
1074 seq.push_back(*cit);
1080 /** Brings this expairseq into a sorted (canonical) form. */
1081 void expairseq::canonicalize()
1083 std::sort(seq.begin(), seq.end(), expair_rest_is_less());
1087 /** Compact a presorted expairseq by combining all matching expairs to one
1088 * each. On an add object, this is responsible for 2*x+3*x+y -> 5*x+y, for
1090 void expairseq::combine_same_terms_sorted_seq()
1095 bool needs_further_processing = false;
1097 epvector::iterator itin1 = seq.begin();
1098 epvector::iterator itin2 = itin1+1;
1099 epvector::iterator itout = itin1;
1100 epvector::iterator last = seq.end();
1101 // must_copy will be set to true the first time some combination is
1102 // possible from then on the sequence has changed and must be compacted
1103 bool must_copy = false;
1104 while (itin2!=last) {
1105 if (itin1->rest.compare(itin2->rest)==0) {
1106 itin1->coeff = ex_to<numeric>(itin1->coeff).
1107 add_dyn(ex_to<numeric>(itin2->coeff));
1108 if (expair_needs_further_processing(itin1))
1109 needs_further_processing = true;
1112 if (!ex_to<numeric>(itin1->coeff).is_zero()) {
1121 if (!ex_to<numeric>(itin1->coeff).is_zero()) {
1127 seq.erase(itout,last);
1129 if (needs_further_processing) {
1132 construct_from_epvector(v);
1136 #if EXPAIRSEQ_USE_HASHTAB
1138 unsigned expairseq::calc_hashtabsize(unsigned sz) const
1141 unsigned nearest_power_of_2 = 1 << log2(sz);
1142 // if (nearest_power_of_2 < maxhashtabsize/hashtabfactor) {
1143 // size = nearest_power_of_2*hashtabfactor;
1144 size = nearest_power_of_2/hashtabfactor;
1145 if (size<minhashtabsize)
1148 // hashtabsize must be a power of 2
1149 GINAC_ASSERT((1U << log2(size))==size);
1153 unsigned expairseq::calc_hashindex(const ex &e) const
1155 // calculate hashindex
1157 if (is_a<numeric>(e)) {
1158 hashindex = hashmask;
1160 hashindex = e.gethash() & hashmask;
1161 // last hashtab entry is reserved for numerics
1162 if (hashindex==hashmask) hashindex = 0;
1164 GINAC_ASSERT((hashindex<hashtabsize)||(hashtabsize==0));
1168 void expairseq::shrink_hashtab()
1170 unsigned new_hashtabsize;
1171 while (hashtabsize!=(new_hashtabsize=calc_hashtabsize(seq.size()))) {
1172 GINAC_ASSERT(new_hashtabsize<hashtabsize);
1173 if (new_hashtabsize==0) {
1180 // shrink by a factor of 2
1181 unsigned half_hashtabsize = hashtabsize/2;
1182 for (unsigned i=0; i<half_hashtabsize-1; ++i)
1183 hashtab[i].merge(hashtab[i+half_hashtabsize],epp_is_less());
1184 // special treatment for numeric hashes
1185 hashtab[0].merge(hashtab[half_hashtabsize-1],epp_is_less());
1186 hashtab[half_hashtabsize-1] = hashtab[hashtabsize-1];
1187 hashtab.resize(half_hashtabsize);
1188 hashtabsize = half_hashtabsize;
1189 hashmask = hashtabsize-1;
1193 void expairseq::remove_hashtab_entry(epvector::const_iterator element)
1196 return; // nothing to do
1198 // calculate hashindex of element to be deleted
1199 unsigned hashindex = calc_hashindex((*element).rest);
1201 // find it in hashtab and remove it
1202 epplist &eppl = hashtab[hashindex];
1203 epplist::iterator epplit = eppl.begin();
1204 bool erased = false;
1205 while (epplit!=eppl.end()) {
1206 if (*epplit == element) {
1214 std::cout << "tried to erase " << element-seq.begin() << std::endl;
1215 std::cout << "size " << seq.end()-seq.begin() << std::endl;
1217 unsigned hashindex = calc_hashindex(element->rest);
1218 epplist &eppl = hashtab[hashindex];
1219 epplist::iterator epplit = eppl.begin();
1220 bool erased = false;
1221 while (epplit!=eppl.end()) {
1222 if (*epplit == element) {
1229 GINAC_ASSERT(erased);
1231 GINAC_ASSERT(erased);
1234 void expairseq::move_hashtab_entry(epvector::const_iterator oldpos,
1235 epvector::iterator newpos)
1237 GINAC_ASSERT(hashtabsize!=0);
1239 // calculate hashindex of element which was moved
1240 unsigned hashindex=calc_hashindex((*newpos).rest);
1242 // find it in hashtab and modify it
1243 epplist &eppl = hashtab[hashindex];
1244 epplist::iterator epplit = eppl.begin();
1245 while (epplit!=eppl.end()) {
1246 if (*epplit == oldpos) {
1252 GINAC_ASSERT(epplit!=eppl.end());
1255 void expairseq::sorted_insert(epplist &eppl, epvector::const_iterator elem)
1257 epplist::const_iterator current = eppl.begin();
1258 while ((current!=eppl.end()) && ((*current)->is_less(*elem))) {
1261 eppl.insert(current,elem);
1264 void expairseq::build_hashtab_and_combine(epvector::iterator &first_numeric,
1265 epvector::iterator &last_non_zero,
1266 std::vector<bool> &touched,
1267 unsigned &number_of_zeroes)
1269 epp current = seq.begin();
1271 while (current!=first_numeric) {
1272 if (is_exactly_a<numeric>(current->rest)) {
1274 iter_swap(current,first_numeric);
1276 // calculate hashindex
1277 unsigned currenthashindex = calc_hashindex(current->rest);
1279 // test if there is already a matching expair in the hashtab-list
1280 epplist &eppl=hashtab[currenthashindex];
1281 epplist::iterator epplit = eppl.begin();
1282 while (epplit!=eppl.end()) {
1283 if (current->rest.is_equal((*epplit)->rest))
1287 if (epplit==eppl.end()) {
1288 // no matching expair found, append this to end of list
1289 sorted_insert(eppl,current);
1292 // epplit points to a matching expair, combine it with current
1293 (*epplit)->coeff = ex_to<numeric>((*epplit)->coeff).
1294 add_dyn(ex_to<numeric>(current->coeff));
1296 // move obsolete current expair to end by swapping with last_non_zero element
1297 // if this was a numeric, it is swapped with the expair before first_numeric
1298 iter_swap(current,last_non_zero);
1300 if (first_numeric!=last_non_zero) iter_swap(first_numeric,current);
1303 // test if combined term has coeff 0 and can be removed is done later
1304 touched[(*epplit)-seq.begin()] = true;
1310 void expairseq::drop_coeff_0_terms(epvector::iterator &first_numeric,
1311 epvector::iterator &last_non_zero,
1312 std::vector<bool> &touched,
1313 unsigned &number_of_zeroes)
1315 // move terms with coeff 0 to end and remove them from hashtab
1316 // check only those elements which have been touched
1317 epp current = seq.begin();
1319 while (current!=first_numeric) {
1323 } else if (!ex_to<numeric>((*current).coeff).is_zero()) {
1327 remove_hashtab_entry(current);
1329 // move element to the end, unless it is already at the end
1330 if (current!=last_non_zero) {
1331 iter_swap(current,last_non_zero);
1333 bool numeric_swapped = first_numeric!=last_non_zero;
1334 if (numeric_swapped)
1335 iter_swap(first_numeric,current);
1336 epvector::iterator changed_entry;
1338 if (numeric_swapped)
1339 changed_entry = first_numeric;
1341 changed_entry = last_non_zero;
1346 if (first_numeric!=current) {
1348 // change entry in hashtab which referred to first_numeric or last_non_zero to current
1349 move_hashtab_entry(changed_entry,current);
1350 touched[current-seq.begin()] = touched[changed_entry-seq.begin()];
1359 GINAC_ASSERT(i==current-seq.begin());
1362 /** True if one of the coeffs vanishes, otherwise false.
1363 * This would be an invariant violation, so this should only be used for
1364 * debugging purposes. */
1365 bool expairseq::has_coeff_0() const
1367 epvector::const_iterator i = seq.begin(), end = seq.end();
1369 if (i->coeff.is_zero())
1376 void expairseq::add_numerics_to_hashtab(epvector::iterator first_numeric,
1377 epvector::const_iterator last_non_zero)
1379 if (first_numeric == seq.end()) return; // no numerics
1381 epvector::const_iterator current = first_numeric, last = last_non_zero + 1;
1382 while (current != last) {
1383 sorted_insert(hashtab[hashmask], current);
1388 void expairseq::combine_same_terms()
1390 // combine same terms, drop term with coeff 0, move numerics to end
1392 // calculate size of hashtab
1393 hashtabsize = calc_hashtabsize(seq.size());
1395 // hashtabsize is a power of 2
1396 hashmask = hashtabsize-1;
1400 hashtab.resize(hashtabsize);
1402 if (hashtabsize==0) {
1404 combine_same_terms_sorted_seq();
1405 GINAC_ASSERT(!has_coeff_0());
1409 // iterate through seq, move numerics to end,
1410 // fill hashtab and combine same terms
1411 epvector::iterator first_numeric = seq.end();
1412 epvector::iterator last_non_zero = seq.end()-1;
1414 size_t num = seq.size();
1415 std::vector<bool> touched(num);
1417 unsigned number_of_zeroes = 0;
1419 GINAC_ASSERT(!has_coeff_0());
1420 build_hashtab_and_combine(first_numeric,last_non_zero,touched,number_of_zeroes);
1422 // there should not be any terms with coeff 0 from the beginning,
1423 // so it should be safe to skip this step
1424 if (number_of_zeroes!=0) {
1425 drop_coeff_0_terms(first_numeric,last_non_zero,touched,number_of_zeroes);
1428 add_numerics_to_hashtab(first_numeric,last_non_zero);
1430 // pop zero elements
1431 for (unsigned i=0; i<number_of_zeroes; ++i) {
1435 // shrink hashtabsize to calculated value
1436 GINAC_ASSERT(!has_coeff_0());
1440 GINAC_ASSERT(!has_coeff_0());
1443 #endif // EXPAIRSEQ_USE_HASHTAB
1445 /** Check if this expairseq is in sorted (canonical) form. Useful mainly for
1446 * debugging or in assertions since being sorted is an invariance. */
1447 bool expairseq::is_canonical() const
1449 if (seq.size() <= 1)
1452 #if EXPAIRSEQ_USE_HASHTAB
1453 if (hashtabsize > 0) return 1; // not canoncalized
1454 #endif // EXPAIRSEQ_USE_HASHTAB
1456 epvector::const_iterator it = seq.begin(), itend = seq.end();
1457 epvector::const_iterator it_last = it;
1458 for (++it; it!=itend; it_last=it, ++it) {
1459 if (!(it_last->is_less(*it) || it_last->is_equal(*it))) {
1460 if (!is_exactly_a<numeric>(it_last->rest) ||
1461 !is_exactly_a<numeric>(it->rest)) {
1462 // double test makes it easier to set a breakpoint...
1463 if (!is_exactly_a<numeric>(it_last->rest) ||
1464 !is_exactly_a<numeric>(it->rest)) {
1465 printpair(std::clog, *it_last, 0);
1467 printpair(std::clog, *it, 0);
1469 std::clog << "pair1:" << std::endl;
1470 it_last->rest.print(print_tree(std::clog));
1471 it_last->coeff.print(print_tree(std::clog));
1472 std::clog << "pair2:" << std::endl;
1473 it->rest.print(print_tree(std::clog));
1474 it->coeff.print(print_tree(std::clog));
1484 /** Member-wise expand the expairs in this sequence.
1486 * @see expairseq::expand()
1487 * @return pointer to epvector containing expanded pairs or zero pointer,
1488 * if no members were changed. */
1489 std::auto_ptr<epvector> expairseq::expandchildren(unsigned options) const
1491 const epvector::const_iterator last = seq.end();
1492 epvector::const_iterator cit = seq.begin();
1494 const ex &expanded_ex = cit->rest.expand(options);
1495 if (!are_ex_trivially_equal(cit->rest,expanded_ex)) {
1497 // something changed, copy seq, eval and return it
1498 std::auto_ptr<epvector> s(new epvector);
1499 s->reserve(seq.size());
1501 // copy parts of seq which are known not to have changed
1502 epvector::const_iterator cit2 = seq.begin();
1504 s->push_back(*cit2);
1508 // copy first changed element
1509 s->push_back(combine_ex_with_coeff_to_pair(expanded_ex,
1514 while (cit2!=last) {
1515 s->push_back(combine_ex_with_coeff_to_pair(cit2->rest.expand(options),
1524 return std::auto_ptr<epvector>(0); // signalling nothing has changed
1528 /** Member-wise evaluate the expairs in this sequence.
1530 * @see expairseq::eval()
1531 * @return pointer to epvector containing evaluated pairs or zero pointer,
1532 * if no members were changed. */
1533 std::auto_ptr<epvector> expairseq::evalchildren(int level) const
1535 // returns a NULL pointer if nothing had to be evaluated
1536 // returns a pointer to a newly created epvector otherwise
1537 // (which has to be deleted somewhere else)
1540 return std::auto_ptr<epvector>(0);
1542 if (level == -max_recursion_level)
1543 throw(std::runtime_error("max recursion level reached"));
1546 epvector::const_iterator last = seq.end();
1547 epvector::const_iterator cit = seq.begin();
1549 const ex &evaled_ex = cit->rest.eval(level);
1550 if (!are_ex_trivially_equal(cit->rest,evaled_ex)) {
1552 // something changed, copy seq, eval and return it
1553 std::auto_ptr<epvector> s(new epvector);
1554 s->reserve(seq.size());
1556 // copy parts of seq which are known not to have changed
1557 epvector::const_iterator cit2=seq.begin();
1559 s->push_back(*cit2);
1563 // copy first changed element
1564 s->push_back(combine_ex_with_coeff_to_pair(evaled_ex,
1569 while (cit2!=last) {
1570 s->push_back(combine_ex_with_coeff_to_pair(cit2->rest.eval(level),
1579 return std::auto_ptr<epvector>(0); // signalling nothing has changed
1583 /** Member-wise substitute in this sequence.
1585 * @see expairseq::subs()
1586 * @return pointer to epvector containing pairs after application of subs,
1587 * or NULL pointer if no members were changed. */
1588 std::auto_ptr<epvector> expairseq::subschildren(const exmap & m, unsigned options) const
1590 // When any of the objects to be substituted is a product or power
1591 // we have to recombine the pairs because the numeric coefficients may
1592 // be part of the search pattern.
1593 if (!(options & (subs_options::pattern_is_product | subs_options::pattern_is_not_product))) {
1595 // Search the list of substitutions and cache our findings
1596 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
1597 if (is_exactly_a<mul>(it->first) || is_exactly_a<power>(it->first)) {
1598 options |= subs_options::pattern_is_product;
1602 if (!(options & subs_options::pattern_is_product))
1603 options |= subs_options::pattern_is_not_product;
1606 if (options & subs_options::pattern_is_product) {
1608 // Substitute in the recombined pairs
1609 epvector::const_iterator cit = seq.begin(), last = seq.end();
1610 while (cit != last) {
1612 const ex &orig_ex = recombine_pair_to_ex(*cit);
1613 const ex &subsed_ex = orig_ex.subs(m, options);
1614 if (!are_ex_trivially_equal(orig_ex, subsed_ex)) {
1616 // Something changed, copy seq, subs and return it
1617 std::auto_ptr<epvector> s(new epvector);
1618 s->reserve(seq.size());
1620 // Copy parts of seq which are known not to have changed
1621 s->insert(s->begin(), seq.begin(), cit);
1623 // Copy first changed element
1624 s->push_back(split_ex_to_pair(subsed_ex));
1628 while (cit != last) {
1629 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit).subs(m, options)));
1640 // Substitute only in the "rest" part of the pairs
1641 epvector::const_iterator cit = seq.begin(), last = seq.end();
1642 while (cit != last) {
1644 const ex &subsed_ex = cit->rest.subs(m, options);
1645 if (!are_ex_trivially_equal(cit->rest, subsed_ex)) {
1647 // Something changed, copy seq, subs and return it
1648 std::auto_ptr<epvector> s(new epvector);
1649 s->reserve(seq.size());
1651 // Copy parts of seq which are known not to have changed
1652 s->insert(s->begin(), seq.begin(), cit);
1654 // Copy first changed element
1655 s->push_back(combine_ex_with_coeff_to_pair(subsed_ex, cit->coeff));
1659 while (cit != last) {
1660 s->push_back(combine_ex_with_coeff_to_pair(cit->rest.subs(m, options),
1671 // Nothing has changed
1672 return std::auto_ptr<epvector>(0);
1676 // static member variables
1679 #if EXPAIRSEQ_USE_HASHTAB
1680 unsigned expairseq::maxhashtabsize = 0x4000000U;
1681 unsigned expairseq::minhashtabsize = 0x1000U;
1682 unsigned expairseq::hashtabfactor = 1;
1683 #endif // EXPAIRSEQ_USE_HASHTAB
1685 } // namespace GiNaC