1 /** @file expairseq.cpp
3 * Implementation of sequences of expression pairs. */
6 * GiNaC Copyright (C) 1999-2005 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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)
131 GINAC_ASSERT(vp.get()!=0);
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 lst::const_iterator last_el = repl_lst.end();
387 if (it->match(p, repl_lst)) {
392 lst::const_iterator next_el = last_el;
394 if(next_el == repl_lst.end())
397 repl_lst.remove_last();
401 return false; // no match found
405 if (has_global_wildcard) {
407 // Assign all the remaining terms to the global wildcard (unless
408 // it has already been matched before, in which case the matches
410 size_t num = ops.size();
411 std::auto_ptr<epvector> vp(new epvector);
413 for (size_t i=0; i<num; i++)
414 vp->push_back(split_ex_to_pair(ops[i]));
415 ex rest = thisexpairseq(vp, default_overall_coeff());
416 for (lst::const_iterator it = repl_lst.begin(); it != repl_lst.end(); ++it) {
417 if (it->op(0).is_equal(global_wildcard))
418 return rest.is_equal(it->op(1));
420 repl_lst.append(global_wildcard == rest);
425 // No global wildcard, then the match fails if there are any
426 // unmatched terms left
430 return inherited::match(pattern, repl_lst);
433 ex expairseq::subs(const exmap & m, unsigned options) const
435 std::auto_ptr<epvector> vp = subschildren(m, options);
437 return ex_to<basic>(thisexpairseq(vp, overall_coeff));
438 else if ((options & subs_options::algebraic) && is_exactly_a<mul>(*this))
439 return static_cast<const mul *>(this)->algebraic_subs_mul(m, options);
441 return subs_one_level(m, options);
446 int expairseq::compare_same_type(const basic &other) const
448 GINAC_ASSERT(is_a<expairseq>(other));
449 const expairseq &o = static_cast<const expairseq &>(other);
453 // compare number of elements
454 if (seq.size() != o.seq.size())
455 return (seq.size()<o.seq.size()) ? -1 : 1;
457 // compare overall_coeff
458 cmpval = overall_coeff.compare(o.overall_coeff);
462 #if EXPAIRSEQ_USE_HASHTAB
463 GINAC_ASSERT(hashtabsize==o.hashtabsize);
464 if (hashtabsize==0) {
465 #endif // EXPAIRSEQ_USE_HASHTAB
466 epvector::const_iterator cit1 = seq.begin();
467 epvector::const_iterator cit2 = o.seq.begin();
468 epvector::const_iterator last1 = seq.end();
469 epvector::const_iterator last2 = o.seq.end();
471 for (; (cit1!=last1)&&(cit2!=last2); ++cit1, ++cit2) {
472 cmpval = (*cit1).compare(*cit2);
473 if (cmpval!=0) return cmpval;
476 GINAC_ASSERT(cit1==last1);
477 GINAC_ASSERT(cit2==last2);
480 #if EXPAIRSEQ_USE_HASHTAB
483 // compare number of elements in each hashtab entry
484 for (unsigned i=0; i<hashtabsize; ++i) {
485 unsigned cursize=hashtab[i].size();
486 if (cursize != o.hashtab[i].size())
487 return (cursize < o.hashtab[i].size()) ? -1 : 1;
490 // compare individual (sorted) hashtab entries
491 for (unsigned i=0; i<hashtabsize; ++i) {
492 unsigned sz = hashtab[i].size();
494 const epplist &eppl1 = hashtab[i];
495 const epplist &eppl2 = o.hashtab[i];
496 epplist::const_iterator it1 = eppl1.begin();
497 epplist::const_iterator it2 = eppl2.begin();
498 while (it1!=eppl1.end()) {
499 cmpval = (*(*it1)).compare(*(*it2));
509 #endif // EXPAIRSEQ_USE_HASHTAB
512 bool expairseq::is_equal_same_type(const basic &other) const
514 const expairseq &o = static_cast<const expairseq &>(other);
516 // compare number of elements
517 if (seq.size()!=o.seq.size())
520 // compare overall_coeff
521 if (!overall_coeff.is_equal(o.overall_coeff))
524 #if EXPAIRSEQ_USE_HASHTAB
525 // compare number of elements in each hashtab entry
526 if (hashtabsize!=o.hashtabsize) {
527 std::cout << "this:" << std::endl;
528 print(print_tree(std::cout));
529 std::cout << "other:" << std::endl;
530 other.print(print_tree(std::cout));
533 GINAC_ASSERT(hashtabsize==o.hashtabsize);
535 if (hashtabsize==0) {
536 #endif // EXPAIRSEQ_USE_HASHTAB
537 epvector::const_iterator cit1 = seq.begin();
538 epvector::const_iterator cit2 = o.seq.begin();
539 epvector::const_iterator last1 = seq.end();
541 while (cit1!=last1) {
542 if (!(*cit1).is_equal(*cit2)) return false;
548 #if EXPAIRSEQ_USE_HASHTAB
551 for (unsigned i=0; i<hashtabsize; ++i) {
552 if (hashtab[i].size() != o.hashtab[i].size())
556 // compare individual sorted hashtab entries
557 for (unsigned i=0; i<hashtabsize; ++i) {
558 unsigned sz = hashtab[i].size();
560 const epplist &eppl1 = hashtab[i];
561 const epplist &eppl2 = o.hashtab[i];
562 epplist::const_iterator it1 = eppl1.begin();
563 epplist::const_iterator it2 = eppl2.begin();
564 while (it1!=eppl1.end()) {
565 if (!(*(*it1)).is_equal(*(*it2))) return false;
573 #endif // EXPAIRSEQ_USE_HASHTAB
576 unsigned expairseq::return_type() const
578 return return_types::noncommutative_composite;
581 unsigned expairseq::calchash() const
583 unsigned v = golden_ratio_hash(this->tinfo());
584 epvector::const_iterator i = seq.begin();
585 const epvector::const_iterator end = seq.end();
587 v ^= i->rest.gethash();
588 #if !EXPAIRSEQ_USE_HASHTAB
589 // rotation spoils commutativity!
591 v ^= i->coeff.gethash();
592 #endif // !EXPAIRSEQ_USE_HASHTAB
596 v ^= overall_coeff.gethash();
598 // store calculated hash value only if object is already evaluated
599 if (flags &status_flags::evaluated) {
600 setflag(status_flags::hash_calculated);
607 ex expairseq::expand(unsigned options) const
609 std::auto_ptr<epvector> vp = expandchildren(options);
611 return thisexpairseq(vp, overall_coeff);
613 // The terms have not changed, so it is safe to declare this expanded
614 return (options == 0) ? setflag(status_flags::expanded) : *this;
619 // new virtual functions which can be overridden by derived classes
624 /** Create an object of this type.
625 * This method works similar to a constructor. It is useful because expairseq
626 * has (at least) two possible different semantics but we want to inherit
627 * methods thus avoiding code duplication. Sometimes a method in expairseq
628 * has to create a new one of the same semantics, which cannot be done by a
629 * ctor because the name (add, mul,...) is unknown on the expaiseq level. In
630 * order for this trick to work a derived class must of course override this
632 ex expairseq::thisexpairseq(const epvector &v, const ex &oc) const
634 return expairseq(v, oc);
637 ex expairseq::thisexpairseq(std::auto_ptr<epvector> vp, const ex &oc) const
639 return expairseq(vp, oc);
642 void expairseq::printpair(const print_context & c, const expair & p, unsigned upper_precedence) const
645 p.rest.print(c, precedence());
647 p.coeff.print(c, precedence());
651 void expairseq::printseq(const print_context & c, char delim,
652 unsigned this_precedence,
653 unsigned upper_precedence) const
655 if (this_precedence <= upper_precedence)
657 epvector::const_iterator it, it_last = seq.end() - 1;
658 for (it=seq.begin(); it!=it_last; ++it) {
659 printpair(c, *it, this_precedence);
662 printpair(c, *it, this_precedence);
663 if (!overall_coeff.is_equal(default_overall_coeff())) {
665 overall_coeff.print(c, this_precedence);
668 if (this_precedence <= upper_precedence)
673 /** Form an expair from an ex, using the corresponding semantics.
674 * @see expairseq::recombine_pair_to_ex() */
675 expair expairseq::split_ex_to_pair(const ex &e) const
677 return expair(e,_ex1);
681 expair expairseq::combine_ex_with_coeff_to_pair(const ex &e,
684 GINAC_ASSERT(is_exactly_a<numeric>(c));
690 expair expairseq::combine_pair_with_coeff_to_pair(const expair &p,
693 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
694 GINAC_ASSERT(is_exactly_a<numeric>(c));
696 return expair(p.rest,ex_to<numeric>(p.coeff).mul_dyn(ex_to<numeric>(c)));
700 /** Form an ex out of an expair, using the corresponding semantics.
701 * @see expairseq::split_ex_to_pair() */
702 ex expairseq::recombine_pair_to_ex(const expair &p) const
704 return lst(p.rest,p.coeff);
707 bool expairseq::expair_needs_further_processing(epp it)
709 #if EXPAIRSEQ_USE_HASHTAB
710 //# error "FIXME: expair_needs_further_processing not yet implemented for hashtabs, sorry. A.F."
711 #endif // EXPAIRSEQ_USE_HASHTAB
715 ex expairseq::default_overall_coeff() const
720 void expairseq::combine_overall_coeff(const ex &c)
722 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
723 GINAC_ASSERT(is_exactly_a<numeric>(c));
724 overall_coeff = ex_to<numeric>(overall_coeff).add_dyn(ex_to<numeric>(c));
727 void expairseq::combine_overall_coeff(const ex &c1, const ex &c2)
729 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
730 GINAC_ASSERT(is_exactly_a<numeric>(c1));
731 GINAC_ASSERT(is_exactly_a<numeric>(c2));
732 overall_coeff = ex_to<numeric>(overall_coeff).
733 add_dyn(ex_to<numeric>(c1).mul(ex_to<numeric>(c2)));
736 bool expairseq::can_make_flat(const expair &p) const
743 // non-virtual functions in this class
746 void expairseq::construct_from_2_ex_via_exvector(const ex &lh, const ex &rh)
752 construct_from_exvector(v);
753 #if EXPAIRSEQ_USE_HASHTAB
754 GINAC_ASSERT((hashtabsize==0)||(hashtabsize>=minhashtabsize));
755 GINAC_ASSERT(hashtabsize==calc_hashtabsize(seq.size()));
756 #endif // EXPAIRSEQ_USE_HASHTAB
759 void expairseq::construct_from_2_ex(const ex &lh, const ex &rh)
761 if (ex_to<basic>(lh).tinfo()==this->tinfo()) {
762 if (ex_to<basic>(rh).tinfo()==this->tinfo()) {
763 #if EXPAIRSEQ_USE_HASHTAB
764 unsigned totalsize = ex_to<expairseq>(lh).seq.size() +
765 ex_to<expairseq>(rh).seq.size();
766 if (calc_hashtabsize(totalsize)!=0) {
767 construct_from_2_ex_via_exvector(lh,rh);
769 #endif // EXPAIRSEQ_USE_HASHTAB
770 construct_from_2_expairseq(ex_to<expairseq>(lh),
771 ex_to<expairseq>(rh));
772 #if EXPAIRSEQ_USE_HASHTAB
774 #endif // EXPAIRSEQ_USE_HASHTAB
777 #if EXPAIRSEQ_USE_HASHTAB
778 unsigned totalsize = ex_to<expairseq>(lh).seq.size()+1;
779 if (calc_hashtabsize(totalsize)!=0) {
780 construct_from_2_ex_via_exvector(lh, rh);
782 #endif // EXPAIRSEQ_USE_HASHTAB
783 construct_from_expairseq_ex(ex_to<expairseq>(lh), rh);
784 #if EXPAIRSEQ_USE_HASHTAB
786 #endif // EXPAIRSEQ_USE_HASHTAB
789 } else if (ex_to<basic>(rh).tinfo()==this->tinfo()) {
790 #if EXPAIRSEQ_USE_HASHTAB
791 unsigned totalsize=ex_to<expairseq>(rh).seq.size()+1;
792 if (calc_hashtabsize(totalsize)!=0) {
793 construct_from_2_ex_via_exvector(lh,rh);
795 #endif // EXPAIRSEQ_USE_HASHTAB
796 construct_from_expairseq_ex(ex_to<expairseq>(rh),lh);
797 #if EXPAIRSEQ_USE_HASHTAB
799 #endif // EXPAIRSEQ_USE_HASHTAB
803 #if EXPAIRSEQ_USE_HASHTAB
804 if (calc_hashtabsize(2)!=0) {
805 construct_from_2_ex_via_exvector(lh,rh);
809 #endif // EXPAIRSEQ_USE_HASHTAB
811 if (is_exactly_a<numeric>(lh)) {
812 if (is_exactly_a<numeric>(rh)) {
813 combine_overall_coeff(lh);
814 combine_overall_coeff(rh);
816 combine_overall_coeff(lh);
817 seq.push_back(split_ex_to_pair(rh));
820 if (is_exactly_a<numeric>(rh)) {
821 combine_overall_coeff(rh);
822 seq.push_back(split_ex_to_pair(lh));
824 expair p1 = split_ex_to_pair(lh);
825 expair p2 = split_ex_to_pair(rh);
827 int cmpval = p1.rest.compare(p2.rest);
829 p1.coeff = ex_to<numeric>(p1.coeff).add_dyn(ex_to<numeric>(p2.coeff));
830 if (!ex_to<numeric>(p1.coeff).is_zero()) {
831 // no further processing is necessary, since this
832 // one element will usually be recombined in eval()
849 void expairseq::construct_from_2_expairseq(const expairseq &s1,
852 combine_overall_coeff(s1.overall_coeff);
853 combine_overall_coeff(s2.overall_coeff);
855 epvector::const_iterator first1 = s1.seq.begin();
856 epvector::const_iterator last1 = s1.seq.end();
857 epvector::const_iterator first2 = s2.seq.begin();
858 epvector::const_iterator last2 = s2.seq.end();
860 seq.reserve(s1.seq.size()+s2.seq.size());
862 bool needs_further_processing=false;
864 while (first1!=last1 && first2!=last2) {
865 int cmpval = (*first1).rest.compare((*first2).rest);
868 const numeric &newcoeff = ex_to<numeric>(first1->coeff).
869 add(ex_to<numeric>(first2->coeff));
870 if (!newcoeff.is_zero()) {
871 seq.push_back(expair(first1->rest,newcoeff));
872 if (expair_needs_further_processing(seq.end()-1)) {
873 needs_further_processing = true;
878 } else if (cmpval<0) {
879 seq.push_back(*first1);
882 seq.push_back(*first2);
887 while (first1!=last1) {
888 seq.push_back(*first1);
891 while (first2!=last2) {
892 seq.push_back(*first2);
896 if (needs_further_processing) {
899 construct_from_epvector(v);
903 void expairseq::construct_from_expairseq_ex(const expairseq &s,
906 combine_overall_coeff(s.overall_coeff);
907 if (is_exactly_a<numeric>(e)) {
908 combine_overall_coeff(e);
913 epvector::const_iterator first = s.seq.begin();
914 epvector::const_iterator last = s.seq.end();
915 expair p = split_ex_to_pair(e);
917 seq.reserve(s.seq.size()+1);
918 bool p_pushed = false;
920 bool needs_further_processing=false;
922 // merge p into s.seq
923 while (first!=last) {
924 int cmpval = (*first).rest.compare(p.rest);
927 const numeric &newcoeff = ex_to<numeric>(first->coeff).
928 add(ex_to<numeric>(p.coeff));
929 if (!newcoeff.is_zero()) {
930 seq.push_back(expair(first->rest,newcoeff));
931 if (expair_needs_further_processing(seq.end()-1))
932 needs_further_processing = true;
937 } else if (cmpval<0) {
938 seq.push_back(*first);
948 // while loop exited because p was pushed, now push rest of s.seq
949 while (first!=last) {
950 seq.push_back(*first);
954 // while loop exited because s.seq was pushed, now push p
958 if (needs_further_processing) {
961 construct_from_epvector(v);
965 void expairseq::construct_from_exvector(const exvector &v)
967 // simplifications: +(a,+(b,c),d) -> +(a,b,c,d) (associativity)
968 // +(d,b,c,a) -> +(a,b,c,d) (canonicalization)
969 // +(...,x,*(x,c1),*(x,c2)) -> +(...,*(x,1+c1+c2)) (c1, c2 numeric())
970 // (same for (+,*) -> (*,^)
973 #if EXPAIRSEQ_USE_HASHTAB
974 combine_same_terms();
977 combine_same_terms_sorted_seq();
978 #endif // EXPAIRSEQ_USE_HASHTAB
981 void expairseq::construct_from_epvector(const epvector &v)
983 // simplifications: +(a,+(b,c),d) -> +(a,b,c,d) (associativity)
984 // +(d,b,c,a) -> +(a,b,c,d) (canonicalization)
985 // +(...,x,*(x,c1),*(x,c2)) -> +(...,*(x,1+c1+c2)) (c1, c2 numeric())
986 // (same for (+,*) -> (*,^)
989 #if EXPAIRSEQ_USE_HASHTAB
990 combine_same_terms();
993 combine_same_terms_sorted_seq();
994 #endif // EXPAIRSEQ_USE_HASHTAB
997 /** Combine this expairseq with argument exvector.
998 * It cares for associativity as well as for special handling of numerics. */
999 void expairseq::make_flat(const exvector &v)
1001 exvector::const_iterator cit;
1003 // count number of operands which are of same expairseq derived type
1004 // and their cumulative number of operands
1005 int nexpairseqs = 0;
1009 while (cit!=v.end()) {
1010 if (ex_to<basic>(*cit).tinfo()==this->tinfo()) {
1012 noperands += ex_to<expairseq>(*cit).seq.size();
1017 // reserve seq and coeffseq which will hold all operands
1018 seq.reserve(v.size()+noperands-nexpairseqs);
1020 // copy elements and split off numerical part
1022 while (cit!=v.end()) {
1023 if (ex_to<basic>(*cit).tinfo()==this->tinfo()) {
1024 const expairseq &subseqref = ex_to<expairseq>(*cit);
1025 combine_overall_coeff(subseqref.overall_coeff);
1026 epvector::const_iterator cit_s = subseqref.seq.begin();
1027 while (cit_s!=subseqref.seq.end()) {
1028 seq.push_back(*cit_s);
1032 if (is_exactly_a<numeric>(*cit))
1033 combine_overall_coeff(*cit);
1035 seq.push_back(split_ex_to_pair(*cit));
1041 /** Combine this expairseq with argument epvector.
1042 * It cares for associativity as well as for special handling of numerics. */
1043 void expairseq::make_flat(const epvector &v)
1045 epvector::const_iterator cit;
1047 // count number of operands which are of same expairseq derived type
1048 // and their cumulative number of operands
1049 int nexpairseqs = 0;
1053 while (cit!=v.end()) {
1054 if (ex_to<basic>(cit->rest).tinfo()==this->tinfo()) {
1056 noperands += ex_to<expairseq>(cit->rest).seq.size();
1061 // reserve seq and coeffseq which will hold all operands
1062 seq.reserve(v.size()+noperands-nexpairseqs);
1064 // copy elements and split off numerical part
1066 while (cit!=v.end()) {
1067 if (ex_to<basic>(cit->rest).tinfo()==this->tinfo() &&
1068 this->can_make_flat(*cit)) {
1069 const expairseq &subseqref = ex_to<expairseq>(cit->rest);
1070 combine_overall_coeff(ex_to<numeric>(subseqref.overall_coeff),
1071 ex_to<numeric>(cit->coeff));
1072 epvector::const_iterator cit_s = subseqref.seq.begin();
1073 while (cit_s!=subseqref.seq.end()) {
1074 seq.push_back(expair(cit_s->rest,
1075 ex_to<numeric>(cit_s->coeff).mul_dyn(ex_to<numeric>(cit->coeff))));
1076 //seq.push_back(combine_pair_with_coeff_to_pair(*cit_s,
1081 if (cit->is_canonical_numeric())
1082 combine_overall_coeff(cit->rest);
1084 seq.push_back(*cit);
1090 /** Brings this expairseq into a sorted (canonical) form. */
1091 void expairseq::canonicalize()
1093 std::sort(seq.begin(), seq.end(), expair_rest_is_less());
1097 /** Compact a presorted expairseq by combining all matching expairs to one
1098 * each. On an add object, this is responsible for 2*x+3*x+y -> 5*x+y, for
1100 void expairseq::combine_same_terms_sorted_seq()
1105 bool needs_further_processing = false;
1107 epvector::iterator itin1 = seq.begin();
1108 epvector::iterator itin2 = itin1+1;
1109 epvector::iterator itout = itin1;
1110 epvector::iterator last = seq.end();
1111 // must_copy will be set to true the first time some combination is
1112 // possible from then on the sequence has changed and must be compacted
1113 bool must_copy = false;
1114 while (itin2!=last) {
1115 if (itin1->rest.compare(itin2->rest)==0) {
1116 itin1->coeff = ex_to<numeric>(itin1->coeff).
1117 add_dyn(ex_to<numeric>(itin2->coeff));
1118 if (expair_needs_further_processing(itin1))
1119 needs_further_processing = true;
1122 if (!ex_to<numeric>(itin1->coeff).is_zero()) {
1131 if (!ex_to<numeric>(itin1->coeff).is_zero()) {
1137 seq.erase(itout,last);
1139 if (needs_further_processing) {
1142 construct_from_epvector(v);
1146 #if EXPAIRSEQ_USE_HASHTAB
1148 unsigned expairseq::calc_hashtabsize(unsigned sz) const
1151 unsigned nearest_power_of_2 = 1 << log2(sz);
1152 // if (nearest_power_of_2 < maxhashtabsize/hashtabfactor) {
1153 // size = nearest_power_of_2*hashtabfactor;
1154 size = nearest_power_of_2/hashtabfactor;
1155 if (size<minhashtabsize)
1158 // hashtabsize must be a power of 2
1159 GINAC_ASSERT((1U << log2(size))==size);
1163 unsigned expairseq::calc_hashindex(const ex &e) const
1165 // calculate hashindex
1167 if (is_a<numeric>(e)) {
1168 hashindex = hashmask;
1170 hashindex = e.gethash() & hashmask;
1171 // last hashtab entry is reserved for numerics
1172 if (hashindex==hashmask) hashindex = 0;
1174 GINAC_ASSERT((hashindex<hashtabsize)||(hashtabsize==0));
1178 void expairseq::shrink_hashtab()
1180 unsigned new_hashtabsize;
1181 while (hashtabsize!=(new_hashtabsize=calc_hashtabsize(seq.size()))) {
1182 GINAC_ASSERT(new_hashtabsize<hashtabsize);
1183 if (new_hashtabsize==0) {
1190 // shrink by a factor of 2
1191 unsigned half_hashtabsize = hashtabsize/2;
1192 for (unsigned i=0; i<half_hashtabsize-1; ++i)
1193 hashtab[i].merge(hashtab[i+half_hashtabsize],epp_is_less());
1194 // special treatment for numeric hashes
1195 hashtab[0].merge(hashtab[half_hashtabsize-1],epp_is_less());
1196 hashtab[half_hashtabsize-1] = hashtab[hashtabsize-1];
1197 hashtab.resize(half_hashtabsize);
1198 hashtabsize = half_hashtabsize;
1199 hashmask = hashtabsize-1;
1203 void expairseq::remove_hashtab_entry(epvector::const_iterator element)
1206 return; // nothing to do
1208 // calculate hashindex of element to be deleted
1209 unsigned hashindex = calc_hashindex((*element).rest);
1211 // find it in hashtab and remove it
1212 epplist &eppl = hashtab[hashindex];
1213 epplist::iterator epplit = eppl.begin();
1214 bool erased = false;
1215 while (epplit!=eppl.end()) {
1216 if (*epplit == element) {
1224 std::cout << "tried to erase " << element-seq.begin() << std::endl;
1225 std::cout << "size " << seq.end()-seq.begin() << std::endl;
1227 unsigned hashindex = calc_hashindex(element->rest);
1228 epplist &eppl = hashtab[hashindex];
1229 epplist::iterator epplit = eppl.begin();
1230 bool erased = false;
1231 while (epplit!=eppl.end()) {
1232 if (*epplit == element) {
1239 GINAC_ASSERT(erased);
1241 GINAC_ASSERT(erased);
1244 void expairseq::move_hashtab_entry(epvector::const_iterator oldpos,
1245 epvector::iterator newpos)
1247 GINAC_ASSERT(hashtabsize!=0);
1249 // calculate hashindex of element which was moved
1250 unsigned hashindex=calc_hashindex((*newpos).rest);
1252 // find it in hashtab and modify it
1253 epplist &eppl = hashtab[hashindex];
1254 epplist::iterator epplit = eppl.begin();
1255 while (epplit!=eppl.end()) {
1256 if (*epplit == oldpos) {
1262 GINAC_ASSERT(epplit!=eppl.end());
1265 void expairseq::sorted_insert(epplist &eppl, epvector::const_iterator elem)
1267 epplist::const_iterator current = eppl.begin();
1268 while ((current!=eppl.end()) && ((*current)->is_less(*elem))) {
1271 eppl.insert(current,elem);
1274 void expairseq::build_hashtab_and_combine(epvector::iterator &first_numeric,
1275 epvector::iterator &last_non_zero,
1276 std::vector<bool> &touched,
1277 unsigned &number_of_zeroes)
1279 epp current = seq.begin();
1281 while (current!=first_numeric) {
1282 if (is_exactly_a<numeric>(current->rest)) {
1284 iter_swap(current,first_numeric);
1286 // calculate hashindex
1287 unsigned currenthashindex = calc_hashindex(current->rest);
1289 // test if there is already a matching expair in the hashtab-list
1290 epplist &eppl=hashtab[currenthashindex];
1291 epplist::iterator epplit = eppl.begin();
1292 while (epplit!=eppl.end()) {
1293 if (current->rest.is_equal((*epplit)->rest))
1297 if (epplit==eppl.end()) {
1298 // no matching expair found, append this to end of list
1299 sorted_insert(eppl,current);
1302 // epplit points to a matching expair, combine it with current
1303 (*epplit)->coeff = ex_to<numeric>((*epplit)->coeff).
1304 add_dyn(ex_to<numeric>(current->coeff));
1306 // move obsolete current expair to end by swapping with last_non_zero element
1307 // if this was a numeric, it is swapped with the expair before first_numeric
1308 iter_swap(current,last_non_zero);
1310 if (first_numeric!=last_non_zero) iter_swap(first_numeric,current);
1313 // test if combined term has coeff 0 and can be removed is done later
1314 touched[(*epplit)-seq.begin()] = true;
1320 void expairseq::drop_coeff_0_terms(epvector::iterator &first_numeric,
1321 epvector::iterator &last_non_zero,
1322 std::vector<bool> &touched,
1323 unsigned &number_of_zeroes)
1325 // move terms with coeff 0 to end and remove them from hashtab
1326 // check only those elements which have been touched
1327 epp current = seq.begin();
1329 while (current!=first_numeric) {
1333 } else if (!ex_to<numeric>((*current).coeff).is_zero()) {
1337 remove_hashtab_entry(current);
1339 // move element to the end, unless it is already at the end
1340 if (current!=last_non_zero) {
1341 iter_swap(current,last_non_zero);
1343 bool numeric_swapped = first_numeric!=last_non_zero;
1344 if (numeric_swapped)
1345 iter_swap(first_numeric,current);
1346 epvector::iterator changed_entry;
1348 if (numeric_swapped)
1349 changed_entry = first_numeric;
1351 changed_entry = last_non_zero;
1356 if (first_numeric!=current) {
1358 // change entry in hashtab which referred to first_numeric or last_non_zero to current
1359 move_hashtab_entry(changed_entry,current);
1360 touched[current-seq.begin()] = touched[changed_entry-seq.begin()];
1369 GINAC_ASSERT(i==current-seq.begin());
1372 /** True if one of the coeffs vanishes, otherwise false.
1373 * This would be an invariant violation, so this should only be used for
1374 * debugging purposes. */
1375 bool expairseq::has_coeff_0() const
1377 epvector::const_iterator i = seq.begin(), end = seq.end();
1379 if (i->coeff.is_zero())
1386 void expairseq::add_numerics_to_hashtab(epvector::iterator first_numeric,
1387 epvector::const_iterator last_non_zero)
1389 if (first_numeric == seq.end()) return; // no numerics
1391 epvector::const_iterator current = first_numeric, last = last_non_zero + 1;
1392 while (current != last) {
1393 sorted_insert(hashtab[hashmask], current);
1398 void expairseq::combine_same_terms()
1400 // combine same terms, drop term with coeff 0, move numerics to end
1402 // calculate size of hashtab
1403 hashtabsize = calc_hashtabsize(seq.size());
1405 // hashtabsize is a power of 2
1406 hashmask = hashtabsize-1;
1410 hashtab.resize(hashtabsize);
1412 if (hashtabsize==0) {
1414 combine_same_terms_sorted_seq();
1415 GINAC_ASSERT(!has_coeff_0());
1419 // iterate through seq, move numerics to end,
1420 // fill hashtab and combine same terms
1421 epvector::iterator first_numeric = seq.end();
1422 epvector::iterator last_non_zero = seq.end()-1;
1424 size_t num = seq.size();
1425 std::vector<bool> touched(num);
1427 unsigned number_of_zeroes = 0;
1429 GINAC_ASSERT(!has_coeff_0());
1430 build_hashtab_and_combine(first_numeric,last_non_zero,touched,number_of_zeroes);
1432 // there should not be any terms with coeff 0 from the beginning,
1433 // so it should be safe to skip this step
1434 if (number_of_zeroes!=0) {
1435 drop_coeff_0_terms(first_numeric,last_non_zero,touched,number_of_zeroes);
1438 add_numerics_to_hashtab(first_numeric,last_non_zero);
1440 // pop zero elements
1441 for (unsigned i=0; i<number_of_zeroes; ++i) {
1445 // shrink hashtabsize to calculated value
1446 GINAC_ASSERT(!has_coeff_0());
1450 GINAC_ASSERT(!has_coeff_0());
1453 #endif // EXPAIRSEQ_USE_HASHTAB
1455 /** Check if this expairseq is in sorted (canonical) form. Useful mainly for
1456 * debugging or in assertions since being sorted is an invariance. */
1457 bool expairseq::is_canonical() const
1459 if (seq.size() <= 1)
1462 #if EXPAIRSEQ_USE_HASHTAB
1463 if (hashtabsize > 0) return 1; // not canoncalized
1464 #endif // EXPAIRSEQ_USE_HASHTAB
1466 epvector::const_iterator it = seq.begin(), itend = seq.end();
1467 epvector::const_iterator it_last = it;
1468 for (++it; it!=itend; it_last=it, ++it) {
1469 if (!(it_last->is_less(*it) || it_last->is_equal(*it))) {
1470 if (!is_exactly_a<numeric>(it_last->rest) ||
1471 !is_exactly_a<numeric>(it->rest)) {
1472 // double test makes it easier to set a breakpoint...
1473 if (!is_exactly_a<numeric>(it_last->rest) ||
1474 !is_exactly_a<numeric>(it->rest)) {
1475 printpair(std::clog, *it_last, 0);
1477 printpair(std::clog, *it, 0);
1479 std::clog << "pair1:" << std::endl;
1480 it_last->rest.print(print_tree(std::clog));
1481 it_last->coeff.print(print_tree(std::clog));
1482 std::clog << "pair2:" << std::endl;
1483 it->rest.print(print_tree(std::clog));
1484 it->coeff.print(print_tree(std::clog));
1494 /** Member-wise expand the expairs in this sequence.
1496 * @see expairseq::expand()
1497 * @return pointer to epvector containing expanded pairs or zero pointer,
1498 * if no members were changed. */
1499 std::auto_ptr<epvector> expairseq::expandchildren(unsigned options) const
1501 const epvector::const_iterator last = seq.end();
1502 epvector::const_iterator cit = seq.begin();
1504 const ex &expanded_ex = cit->rest.expand(options);
1505 if (!are_ex_trivially_equal(cit->rest,expanded_ex)) {
1507 // something changed, copy seq, eval and return it
1508 std::auto_ptr<epvector> s(new epvector);
1509 s->reserve(seq.size());
1511 // copy parts of seq which are known not to have changed
1512 epvector::const_iterator cit2 = seq.begin();
1514 s->push_back(*cit2);
1518 // copy first changed element
1519 s->push_back(combine_ex_with_coeff_to_pair(expanded_ex,
1524 while (cit2!=last) {
1525 s->push_back(combine_ex_with_coeff_to_pair(cit2->rest.expand(options),
1534 return std::auto_ptr<epvector>(0); // signalling nothing has changed
1538 /** Member-wise evaluate the expairs in this sequence.
1540 * @see expairseq::eval()
1541 * @return pointer to epvector containing evaluated pairs or zero pointer,
1542 * if no members were changed. */
1543 std::auto_ptr<epvector> expairseq::evalchildren(int level) const
1545 // returns a NULL pointer if nothing had to be evaluated
1546 // returns a pointer to a newly created epvector otherwise
1547 // (which has to be deleted somewhere else)
1550 return std::auto_ptr<epvector>(0);
1552 if (level == -max_recursion_level)
1553 throw(std::runtime_error("max recursion level reached"));
1556 epvector::const_iterator last = seq.end();
1557 epvector::const_iterator cit = seq.begin();
1559 const ex &evaled_ex = cit->rest.eval(level);
1560 if (!are_ex_trivially_equal(cit->rest,evaled_ex)) {
1562 // something changed, copy seq, eval and return it
1563 std::auto_ptr<epvector> s(new epvector);
1564 s->reserve(seq.size());
1566 // copy parts of seq which are known not to have changed
1567 epvector::const_iterator cit2=seq.begin();
1569 s->push_back(*cit2);
1573 // copy first changed element
1574 s->push_back(combine_ex_with_coeff_to_pair(evaled_ex,
1579 while (cit2!=last) {
1580 s->push_back(combine_ex_with_coeff_to_pair(cit2->rest.eval(level),
1589 return std::auto_ptr<epvector>(0); // signalling nothing has changed
1593 /** Member-wise substitute in this sequence.
1595 * @see expairseq::subs()
1596 * @return pointer to epvector containing pairs after application of subs,
1597 * or NULL pointer if no members were changed. */
1598 std::auto_ptr<epvector> expairseq::subschildren(const exmap & m, unsigned options) const
1600 // When any of the objects to be substituted is a product or power
1601 // we have to recombine the pairs because the numeric coefficients may
1602 // be part of the search pattern.
1603 if (!(options & (subs_options::pattern_is_product | subs_options::pattern_is_not_product))) {
1605 // Search the list of substitutions and cache our findings
1606 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
1607 if (is_exactly_a<mul>(it->first) || is_exactly_a<power>(it->first)) {
1608 options |= subs_options::pattern_is_product;
1612 if (!(options & subs_options::pattern_is_product))
1613 options |= subs_options::pattern_is_not_product;
1616 if (options & subs_options::pattern_is_product) {
1618 // Substitute in the recombined pairs
1619 epvector::const_iterator cit = seq.begin(), last = seq.end();
1620 while (cit != last) {
1622 const ex &orig_ex = recombine_pair_to_ex(*cit);
1623 const ex &subsed_ex = orig_ex.subs(m, options);
1624 if (!are_ex_trivially_equal(orig_ex, subsed_ex)) {
1626 // Something changed, copy seq, subs and return it
1627 std::auto_ptr<epvector> s(new epvector);
1628 s->reserve(seq.size());
1630 // Copy parts of seq which are known not to have changed
1631 s->insert(s->begin(), seq.begin(), cit);
1633 // Copy first changed element
1634 s->push_back(split_ex_to_pair(subsed_ex));
1638 while (cit != last) {
1639 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit).subs(m, options)));
1650 // Substitute only in the "rest" part of the pairs
1651 epvector::const_iterator cit = seq.begin(), last = seq.end();
1652 while (cit != last) {
1654 const ex &subsed_ex = cit->rest.subs(m, options);
1655 if (!are_ex_trivially_equal(cit->rest, subsed_ex)) {
1657 // Something changed, copy seq, subs and return it
1658 std::auto_ptr<epvector> s(new epvector);
1659 s->reserve(seq.size());
1661 // Copy parts of seq which are known not to have changed
1662 s->insert(s->begin(), seq.begin(), cit);
1664 // Copy first changed element
1665 s->push_back(combine_ex_with_coeff_to_pair(subsed_ex, cit->coeff));
1669 while (cit != last) {
1670 s->push_back(combine_ex_with_coeff_to_pair(cit->rest.subs(m, options),
1681 // Nothing has changed
1682 return std::auto_ptr<epvector>(0);
1686 // static member variables
1689 #if EXPAIRSEQ_USE_HASHTAB
1690 unsigned expairseq::maxhashtabsize = 0x4000000U;
1691 unsigned expairseq::minhashtabsize = 0x1000U;
1692 unsigned expairseq::hashtabfactor = 1;
1693 #endif // EXPAIRSEQ_USE_HASHTAB
1695 } // namespace GiNaC