1 /** @file expairseq.cpp
3 * Implementation of sequences of expression pairs. */
6 * GiNaC Copyright (C) 1999-2003 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"
38 #if EXPAIRSEQ_USE_HASHTAB
40 #endif // EXPAIRSEQ_USE_HASHTAB
45 GINAC_IMPLEMENT_REGISTERED_CLASS_NO_CTORS(expairseq, basic)
54 bool operator()(const epp &lh, const epp &rh) const
56 return (*lh).is_less(*rh);
61 // default ctor, dtor, copy ctor, assignment operator and helpers
66 expairseq::expairseq(const expairseq &other)
71 const expairseq &expairseq::operator=(const expairseq &other)
82 /** For use by copy ctor and assignment operator. */
83 void expairseq::copy(const expairseq &other)
85 inherited::copy(other);
87 overall_coeff = other.overall_coeff;
88 #if EXPAIRSEQ_USE_HASHTAB
90 hashtabsize = other.hashtabsize;
92 hashmask = other.hashmask;
93 hashtab.resize(hashtabsize);
94 epvector::const_iterator osb = other.seq.begin();
95 for (unsigned i=0; i<hashtabsize; ++i) {
97 for (epplist::const_iterator cit=other.hashtab[i].begin();
98 cit!=other.hashtab[i].end(); ++cit) {
99 hashtab[i].push_back(seq.begin()+((*cit)-osb));
105 #endif // EXPAIRSEQ_USE_HASHTAB
108 DEFAULT_DESTROY(expairseq)
114 expairseq::expairseq(const ex &lh, const ex &rh) : inherited(TINFO_expairseq)
116 construct_from_2_ex(lh,rh);
117 GINAC_ASSERT(is_canonical());
120 expairseq::expairseq(const exvector &v) : inherited(TINFO_expairseq)
122 construct_from_exvector(v);
123 GINAC_ASSERT(is_canonical());
126 expairseq::expairseq(const epvector &v, const ex &oc)
127 : inherited(TINFO_expairseq), overall_coeff(oc)
129 GINAC_ASSERT(is_a<numeric>(oc));
130 construct_from_epvector(v);
131 GINAC_ASSERT(is_canonical());
134 expairseq::expairseq(epvector *vp, const ex &oc)
135 : inherited(TINFO_expairseq), overall_coeff(oc)
138 GINAC_ASSERT(is_a<numeric>(oc));
139 construct_from_epvector(*vp);
141 GINAC_ASSERT(is_canonical());
148 expairseq::expairseq(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
149 #if EXPAIRSEQ_USE_HASHTAB
154 for (unsigned int i=0; true; i++) {
157 GINAC_ASSERT(is_canonical());
160 if (n.find_ex("rest", rest, sym_lst, i) && n.find_ex("coeff", coeff, sym_lst, i))
161 seq.push_back(expair(rest, coeff));
165 n.find_ex("overall_coeff", overall_coeff, sym_lst);
168 void expairseq::archive(archive_node &n) const
170 inherited::archive(n);
171 epvector::const_iterator i = seq.begin(), iend = seq.end();
173 n.add_ex("rest", i->rest);
174 n.add_ex("coeff", i->coeff);
177 n.add_ex("overall_coeff", overall_coeff);
180 DEFAULT_UNARCHIVE(expairseq)
183 // functions overriding virtual functions from base classes
188 basic *expairseq::duplicate() const
190 return new expairseq(*this);
193 void expairseq::print(const print_context &c, unsigned level) const
195 if (is_of_type(c, print_tree)) {
197 unsigned delta_indent = static_cast<const print_tree &>(c).delta_indent;
199 c.s << std::string(level, ' ') << class_name()
200 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
201 << ", nops=" << nops()
203 unsigned num = seq.size();
204 for (unsigned i=0; i<num; ++i) {
205 seq[i].rest.print(c, level + delta_indent);
206 seq[i].coeff.print(c, level + delta_indent);
208 c.s << std::string(level + delta_indent, ' ') << "-----" << std::endl;
210 if (!overall_coeff.is_equal(default_overall_coeff())) {
211 c.s << std::string(level + delta_indent, ' ') << "-----" << std::endl
212 << std::string(level + delta_indent, ' ') << "overall_coeff" << std::endl;
213 overall_coeff.print(c, level + delta_indent);
215 c.s << std::string(level + delta_indent,' ') << "=====" << std::endl;
216 #if EXPAIRSEQ_USE_HASHTAB
217 c.s << std::string(level + delta_indent,' ')
218 << "hashtab size " << hashtabsize << std::endl;
219 if (hashtabsize == 0) return;
221 unsigned count[MAXCOUNT+1];
222 for (int i=0; i<MAXCOUNT+1; ++i)
224 unsigned this_bin_fill;
225 unsigned cum_fill_sq = 0;
226 unsigned cum_fill = 0;
227 for (unsigned i=0; i<hashtabsize; ++i) {
229 if (hashtab[i].size() > 0) {
230 c.s << std::string(level + delta_indent, ' ')
231 << "bin " << i << " with entries ";
232 for (epplist::const_iterator it=hashtab[i].begin();
233 it!=hashtab[i].end(); ++it) {
234 c.s << *it-seq.begin() << " ";
238 cum_fill += this_bin_fill;
239 cum_fill_sq += this_bin_fill*this_bin_fill;
241 if (this_bin_fill<MAXCOUNT)
242 ++count[this_bin_fill];
248 double lambda = (1.0*seq.size()) / hashtabsize;
249 for (int k=0; k<MAXCOUNT; ++k) {
252 double prob = std::pow(lambda,k)/fact * std::exp(-lambda);
254 c.s << std::string(level + delta_indent, ' ') << "bins with " << k << " entries: "
255 << int(1000.0*count[k]/hashtabsize)/10.0 << "% (expected: "
256 << int(prob*1000)/10.0 << ")" << std::endl;
258 c.s << std::string(level + delta_indent, ' ') << "bins with more entries: "
259 << int(1000.0*count[MAXCOUNT]/hashtabsize)/10.0 << "% (expected: "
260 << int((1-cum_prob)*1000)/10.0 << ")" << std::endl;
262 c.s << std::string(level + delta_indent, ' ') << "variance: "
263 << 1.0/hashtabsize*cum_fill_sq-(1.0/hashtabsize*cum_fill)*(1.0/hashtabsize*cum_fill)
265 c.s << std::string(level + delta_indent, ' ') << "average fill: "
266 << (1.0*cum_fill)/hashtabsize
267 << " (should be equal to " << (1.0*seq.size())/hashtabsize << ")" << std::endl;
268 #endif // EXPAIRSEQ_USE_HASHTAB
272 printseq(c, ',', precedence(), level);
277 bool expairseq::info(unsigned inf) const
279 return inherited::info(inf);
282 unsigned expairseq::nops() const
284 if (overall_coeff.is_equal(default_overall_coeff()))
290 ex expairseq::op(int i) const
292 if (unsigned(i)<seq.size())
293 return recombine_pair_to_ex(seq[i]);
294 GINAC_ASSERT(!overall_coeff.is_equal(default_overall_coeff()));
295 return overall_coeff;
298 ex &expairseq::let_op(int i)
300 throw(std::logic_error("let_op not defined for expairseq and derived classes (add,mul,...)"));
303 ex expairseq::map(map_function &f) const
305 epvector *v = new epvector;
306 v->reserve(seq.size());
308 epvector::const_iterator cit = seq.begin(), last = seq.end();
309 while (cit != last) {
310 v->push_back(split_ex_to_pair(f(recombine_pair_to_ex(*cit))));
314 if (overall_coeff.is_equal(default_overall_coeff()))
315 return thisexpairseq(v, default_overall_coeff());
317 return thisexpairseq(v, f(overall_coeff));
320 /** Perform coefficient-wise automatic term rewriting rules in this class. */
321 ex expairseq::eval(int level) const
323 if ((level==1) && (flags &status_flags::evaluated))
326 epvector *vp = evalchildren(level);
330 return (new expairseq(vp,overall_coeff))->setflag(status_flags::dynallocated | status_flags::evaluated);
333 bool expairseq::match(const ex & pattern, lst & repl_lst) const
335 // This differs from basic::match() because we want "a+b+c+d" to
336 // match "d+*+b" with "*" being "a+c", and we want to honor commutativity
338 if (this->tinfo() == ex_to<basic>(pattern).tinfo()) {
340 // Check whether global wildcard (one that matches the "rest of the
341 // expression", like "*" above) is present
342 bool has_global_wildcard = false;
344 for (unsigned int i=0; i<pattern.nops(); i++) {
345 if (is_ex_exactly_of_type(pattern.op(i), wildcard)) {
346 has_global_wildcard = true;
347 global_wildcard = pattern.op(i);
352 // Unfortunately, this is an O(N^2) operation because we can't
353 // sort the pattern in a useful way...
358 for (unsigned i=0; i<nops(); i++)
359 ops.push_back(op(i));
361 // Now, for every term of the pattern, look for a matching term in
362 // the expression and remove the match
363 for (unsigned i=0; i<pattern.nops(); i++) {
364 ex p = pattern.op(i);
365 if (has_global_wildcard && p.is_equal(global_wildcard))
367 exvector::iterator it = ops.begin(), itend = ops.end();
368 while (it != itend) {
369 if (it->match(p, repl_lst)) {
375 return false; // no match found
379 if (has_global_wildcard) {
381 // Assign all the remaining terms to the global wildcard (unless
382 // it has already been matched before, in which case the matches
384 unsigned num = ops.size();
385 epvector *vp = new epvector();
387 for (unsigned i=0; i<num; i++)
388 vp->push_back(split_ex_to_pair(ops[i]));
389 ex rest = thisexpairseq(vp, default_overall_coeff());
390 for (unsigned i=0; i<repl_lst.nops(); i++) {
391 if (repl_lst.op(i).op(0).is_equal(global_wildcard))
392 return rest.is_equal(repl_lst.op(i).op(1));
394 repl_lst.append(global_wildcard == rest);
399 // No global wildcard, then the match fails if there are any
400 // unmatched terms left
404 return inherited::match(pattern, repl_lst);
407 ex expairseq::subs(const lst &ls, const lst &lr, bool no_pattern) const
409 epvector *vp = subschildren(ls, lr, no_pattern);
411 return ex_to<basic>(thisexpairseq(vp, overall_coeff));
413 return basic::subs(ls, lr, no_pattern);
418 int expairseq::compare_same_type(const basic &other) const
420 GINAC_ASSERT(is_a<expairseq>(other));
421 const expairseq &o = static_cast<const expairseq &>(other);
425 // compare number of elements
426 if (seq.size() != o.seq.size())
427 return (seq.size()<o.seq.size()) ? -1 : 1;
429 // compare overall_coeff
430 cmpval = overall_coeff.compare(o.overall_coeff);
434 #if EXPAIRSEQ_USE_HASHTAB
435 GINAC_ASSERT(hashtabsize==o.hashtabsize);
436 if (hashtabsize==0) {
437 #endif // EXPAIRSEQ_USE_HASHTAB
438 epvector::const_iterator cit1 = seq.begin();
439 epvector::const_iterator cit2 = o.seq.begin();
440 epvector::const_iterator last1 = seq.end();
441 epvector::const_iterator last2 = o.seq.end();
443 for (; (cit1!=last1)&&(cit2!=last2); ++cit1, ++cit2) {
444 cmpval = (*cit1).compare(*cit2);
445 if (cmpval!=0) return cmpval;
448 GINAC_ASSERT(cit1==last1);
449 GINAC_ASSERT(cit2==last2);
452 #if EXPAIRSEQ_USE_HASHTAB
455 // compare number of elements in each hashtab entry
456 for (unsigned i=0; i<hashtabsize; ++i) {
457 unsigned cursize=hashtab[i].size();
458 if (cursize != o.hashtab[i].size())
459 return (cursize < o.hashtab[i].size()) ? -1 : 1;
462 // compare individual (sorted) hashtab entries
463 for (unsigned i=0; i<hashtabsize; ++i) {
464 unsigned sz = hashtab[i].size();
466 const epplist &eppl1 = hashtab[i];
467 const epplist &eppl2 = o.hashtab[i];
468 epplist::const_iterator it1 = eppl1.begin();
469 epplist::const_iterator it2 = eppl2.begin();
470 while (it1!=eppl1.end()) {
471 cmpval = (*(*it1)).compare(*(*it2));
481 #endif // EXPAIRSEQ_USE_HASHTAB
484 bool expairseq::is_equal_same_type(const basic &other) const
486 const expairseq &o = static_cast<const expairseq &>(other);
488 // compare number of elements
489 if (seq.size()!=o.seq.size())
492 // compare overall_coeff
493 if (!overall_coeff.is_equal(o.overall_coeff))
496 #if EXPAIRSEQ_USE_HASHTAB
497 // compare number of elements in each hashtab entry
498 if (hashtabsize!=o.hashtabsize) {
499 std::cout << "this:" << std::endl;
500 print(print_tree(std::cout));
501 std::cout << "other:" << std::endl;
502 other.print(print_tree(std::cout));
505 GINAC_ASSERT(hashtabsize==o.hashtabsize);
507 if (hashtabsize==0) {
508 #endif // EXPAIRSEQ_USE_HASHTAB
509 epvector::const_iterator cit1 = seq.begin();
510 epvector::const_iterator cit2 = o.seq.begin();
511 epvector::const_iterator last1 = seq.end();
513 while (cit1!=last1) {
514 if (!(*cit1).is_equal(*cit2)) return false;
520 #if EXPAIRSEQ_USE_HASHTAB
523 for (unsigned i=0; i<hashtabsize; ++i) {
524 if (hashtab[i].size() != o.hashtab[i].size())
528 // compare individual sorted hashtab entries
529 for (unsigned i=0; i<hashtabsize; ++i) {
530 unsigned sz = hashtab[i].size();
532 const epplist &eppl1 = hashtab[i];
533 const epplist &eppl2 = o.hashtab[i];
534 epplist::const_iterator it1 = eppl1.begin();
535 epplist::const_iterator it2 = eppl2.begin();
536 while (it1!=eppl1.end()) {
537 if (!(*(*it1)).is_equal(*(*it2))) return false;
545 #endif // EXPAIRSEQ_USE_HASHTAB
548 unsigned expairseq::return_type(void) const
550 return return_types::noncommutative_composite;
553 unsigned expairseq::calchash(void) const
555 unsigned v = golden_ratio_hash(this->tinfo());
556 epvector::const_iterator i = seq.begin(), end = seq.end();
558 #if !EXPAIRSEQ_USE_HASHTAB
559 v = rotate_left_31(v); // rotation would spoil commutativity
560 #endif // EXPAIRSEQ_USE_HASHTAB
561 v ^= i->rest.gethash();
562 #if !EXPAIRSEQ_USE_HASHTAB
563 v = rotate_left_31(v);
564 v ^= i->coeff.gethash();
565 #endif // EXPAIRSEQ_USE_HASHTAB
569 v ^= overall_coeff.gethash();
572 // store calculated hash value only if object is already evaluated
573 if (flags &status_flags::evaluated) {
574 setflag(status_flags::hash_calculated);
581 ex expairseq::expand(unsigned options) const
583 epvector *vp = expandchildren(options);
585 // The terms have not changed, so it is safe to declare this expanded
586 return (options == 0) ? setflag(status_flags::expanded) : *this;
588 return thisexpairseq(vp, overall_coeff);
592 // new virtual functions which can be overridden by derived classes
597 /** Create an object of this type.
598 * This method works similar to a constructor. It is useful because expairseq
599 * has (at least) two possible different semantics but we want to inherit
600 * methods thus avoiding code duplication. Sometimes a method in expairseq
601 * has to create a new one of the same semantics, which cannot be done by a
602 * ctor because the name (add, mul,...) is unknown on the expaiseq level. In
603 * order for this trick to work a derived class must of course override this
605 ex expairseq::thisexpairseq(const epvector &v, const ex &oc) const
607 return expairseq(v,oc);
610 ex expairseq::thisexpairseq(epvector *vp, const ex &oc) const
612 return expairseq(vp,oc);
615 void expairseq::printpair(const print_context & c, const expair & p, unsigned upper_precedence) const
618 p.rest.print(c, precedence());
620 p.coeff.print(c, precedence());
624 void expairseq::printseq(const print_context & c, char delim,
625 unsigned this_precedence,
626 unsigned upper_precedence) const
628 if (this_precedence <= upper_precedence)
630 epvector::const_iterator it, it_last = seq.end() - 1;
631 for (it=seq.begin(); it!=it_last; ++it) {
632 printpair(c, *it, this_precedence);
635 printpair(c, *it, this_precedence);
636 if (!overall_coeff.is_equal(default_overall_coeff())) {
638 overall_coeff.print(c, this_precedence);
641 if (this_precedence <= upper_precedence)
646 /** Form an expair from an ex, using the corresponding semantics.
647 * @see expairseq::recombine_pair_to_ex() */
648 expair expairseq::split_ex_to_pair(const ex &e) const
650 return expair(e,_ex1);
654 expair expairseq::combine_ex_with_coeff_to_pair(const ex &e,
657 GINAC_ASSERT(is_exactly_a<numeric>(c));
663 expair expairseq::combine_pair_with_coeff_to_pair(const expair &p,
666 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
667 GINAC_ASSERT(is_exactly_a<numeric>(c));
669 return expair(p.rest,ex_to<numeric>(p.coeff).mul_dyn(ex_to<numeric>(c)));
673 /** Form an ex out of an expair, using the corresponding semantics.
674 * @see expairseq::split_ex_to_pair() */
675 ex expairseq::recombine_pair_to_ex(const expair &p) const
677 return lst(p.rest,p.coeff);
680 bool expairseq::expair_needs_further_processing(epp it)
682 #if EXPAIRSEQ_USE_HASHTAB
683 //# error "FIXME: expair_needs_further_processing not yet implemented for hashtabs, sorry. A.F."
684 #endif // EXPAIRSEQ_USE_HASHTAB
688 ex expairseq::default_overall_coeff(void) const
693 void expairseq::combine_overall_coeff(const ex &c)
695 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
696 GINAC_ASSERT(is_exactly_a<numeric>(c));
697 overall_coeff = ex_to<numeric>(overall_coeff).add_dyn(ex_to<numeric>(c));
700 void expairseq::combine_overall_coeff(const ex &c1, const ex &c2)
702 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
703 GINAC_ASSERT(is_exactly_a<numeric>(c1));
704 GINAC_ASSERT(is_exactly_a<numeric>(c2));
705 overall_coeff = ex_to<numeric>(overall_coeff).
706 add_dyn(ex_to<numeric>(c1).mul(ex_to<numeric>(c2)));
709 bool expairseq::can_make_flat(const expair &p) const
716 // non-virtual functions in this class
719 void expairseq::construct_from_2_ex_via_exvector(const ex &lh, const ex &rh)
725 construct_from_exvector(v);
726 #if EXPAIRSEQ_USE_HASHTAB
727 GINAC_ASSERT((hashtabsize==0)||(hashtabsize>=minhashtabsize));
728 GINAC_ASSERT(hashtabsize==calc_hashtabsize(seq.size()));
729 #endif // EXPAIRSEQ_USE_HASHTAB
732 void expairseq::construct_from_2_ex(const ex &lh, const ex &rh)
734 if (ex_to<basic>(lh).tinfo()==this->tinfo()) {
735 if (ex_to<basic>(rh).tinfo()==this->tinfo()) {
736 #if EXPAIRSEQ_USE_HASHTAB
737 unsigned totalsize = ex_to<expairseq>(lh).seq.size() +
738 ex_to<expairseq>(rh).seq.size();
739 if (calc_hashtabsize(totalsize)!=0) {
740 construct_from_2_ex_via_exvector(lh,rh);
742 #endif // EXPAIRSEQ_USE_HASHTAB
743 construct_from_2_expairseq(ex_to<expairseq>(lh),
744 ex_to<expairseq>(rh));
745 #if EXPAIRSEQ_USE_HASHTAB
747 #endif // EXPAIRSEQ_USE_HASHTAB
750 #if EXPAIRSEQ_USE_HASHTAB
751 unsigned totalsize = ex_to<expairseq>(lh).seq.size()+1;
752 if (calc_hashtabsize(totalsize)!=0) {
753 construct_from_2_ex_via_exvector(lh, rh);
755 #endif // EXPAIRSEQ_USE_HASHTAB
756 construct_from_expairseq_ex(ex_to<expairseq>(lh), rh);
757 #if EXPAIRSEQ_USE_HASHTAB
759 #endif // EXPAIRSEQ_USE_HASHTAB
762 } else if (ex_to<basic>(rh).tinfo()==this->tinfo()) {
763 #if EXPAIRSEQ_USE_HASHTAB
764 unsigned totalsize=ex_to<expairseq>(rh).seq.size()+1;
765 if (calc_hashtabsize(totalsize)!=0) {
766 construct_from_2_ex_via_exvector(lh,rh);
768 #endif // EXPAIRSEQ_USE_HASHTAB
769 construct_from_expairseq_ex(ex_to<expairseq>(rh),lh);
770 #if EXPAIRSEQ_USE_HASHTAB
772 #endif // EXPAIRSEQ_USE_HASHTAB
776 #if EXPAIRSEQ_USE_HASHTAB
777 if (calc_hashtabsize(2)!=0) {
778 construct_from_2_ex_via_exvector(lh,rh);
782 #endif // EXPAIRSEQ_USE_HASHTAB
784 if (is_ex_exactly_of_type(lh,numeric)) {
785 if (is_ex_exactly_of_type(rh,numeric)) {
786 combine_overall_coeff(lh);
787 combine_overall_coeff(rh);
789 combine_overall_coeff(lh);
790 seq.push_back(split_ex_to_pair(rh));
793 if (is_ex_exactly_of_type(rh,numeric)) {
794 combine_overall_coeff(rh);
795 seq.push_back(split_ex_to_pair(lh));
797 expair p1 = split_ex_to_pair(lh);
798 expair p2 = split_ex_to_pair(rh);
800 int cmpval = p1.rest.compare(p2.rest);
802 p1.coeff = ex_to<numeric>(p1.coeff).add_dyn(ex_to<numeric>(p2.coeff));
803 if (!ex_to<numeric>(p1.coeff).is_zero()) {
804 // no further processing is necessary, since this
805 // one element will usually be recombined in eval()
822 void expairseq::construct_from_2_expairseq(const expairseq &s1,
825 combine_overall_coeff(s1.overall_coeff);
826 combine_overall_coeff(s2.overall_coeff);
828 epvector::const_iterator first1 = s1.seq.begin();
829 epvector::const_iterator last1 = s1.seq.end();
830 epvector::const_iterator first2 = s2.seq.begin();
831 epvector::const_iterator last2 = s2.seq.end();
833 seq.reserve(s1.seq.size()+s2.seq.size());
835 bool needs_further_processing=false;
837 while (first1!=last1 && first2!=last2) {
838 int cmpval = (*first1).rest.compare((*first2).rest);
841 const numeric &newcoeff = ex_to<numeric>(first1->coeff).
842 add(ex_to<numeric>(first2->coeff));
843 if (!newcoeff.is_zero()) {
844 seq.push_back(expair(first1->rest,newcoeff));
845 if (expair_needs_further_processing(seq.end()-1)) {
846 needs_further_processing = true;
851 } else if (cmpval<0) {
852 seq.push_back(*first1);
855 seq.push_back(*first2);
860 while (first1!=last1) {
861 seq.push_back(*first1);
864 while (first2!=last2) {
865 seq.push_back(*first2);
869 if (needs_further_processing) {
872 construct_from_epvector(v);
876 void expairseq::construct_from_expairseq_ex(const expairseq &s,
879 combine_overall_coeff(s.overall_coeff);
880 if (is_ex_exactly_of_type(e,numeric)) {
881 combine_overall_coeff(e);
886 epvector::const_iterator first = s.seq.begin();
887 epvector::const_iterator last = s.seq.end();
888 expair p = split_ex_to_pair(e);
890 seq.reserve(s.seq.size()+1);
891 bool p_pushed = false;
893 bool needs_further_processing=false;
895 // merge p into s.seq
896 while (first!=last) {
897 int cmpval = (*first).rest.compare(p.rest);
900 const numeric &newcoeff = ex_to<numeric>(first->coeff).
901 add(ex_to<numeric>(p.coeff));
902 if (!newcoeff.is_zero()) {
903 seq.push_back(expair(first->rest,newcoeff));
904 if (expair_needs_further_processing(seq.end()-1))
905 needs_further_processing = true;
910 } else if (cmpval<0) {
911 seq.push_back(*first);
921 // while loop exited because p was pushed, now push rest of s.seq
922 while (first!=last) {
923 seq.push_back(*first);
927 // while loop exited because s.seq was pushed, now push p
931 if (needs_further_processing) {
934 construct_from_epvector(v);
938 void expairseq::construct_from_exvector(const exvector &v)
940 // simplifications: +(a,+(b,c),d) -> +(a,b,c,d) (associativity)
941 // +(d,b,c,a) -> +(a,b,c,d) (canonicalization)
942 // +(...,x,*(x,c1),*(x,c2)) -> +(...,*(x,1+c1+c2)) (c1, c2 numeric())
943 // (same for (+,*) -> (*,^)
946 #if EXPAIRSEQ_USE_HASHTAB
947 combine_same_terms();
950 combine_same_terms_sorted_seq();
951 #endif // EXPAIRSEQ_USE_HASHTAB
954 void expairseq::construct_from_epvector(const epvector &v)
956 // simplifications: +(a,+(b,c),d) -> +(a,b,c,d) (associativity)
957 // +(d,b,c,a) -> +(a,b,c,d) (canonicalization)
958 // +(...,x,*(x,c1),*(x,c2)) -> +(...,*(x,1+c1+c2)) (c1, c2 numeric())
959 // (same for (+,*) -> (*,^)
962 #if EXPAIRSEQ_USE_HASHTAB
963 combine_same_terms();
966 combine_same_terms_sorted_seq();
967 #endif // EXPAIRSEQ_USE_HASHTAB
970 /** Combine this expairseq with argument exvector.
971 * It cares for associativity as well as for special handling of numerics. */
972 void expairseq::make_flat(const exvector &v)
974 exvector::const_iterator cit;
976 // count number of operands which are of same expairseq derived type
977 // and their cumulative number of operands
982 while (cit!=v.end()) {
983 if (ex_to<basic>(*cit).tinfo()==this->tinfo()) {
985 noperands += ex_to<expairseq>(*cit).seq.size();
990 // reserve seq and coeffseq which will hold all operands
991 seq.reserve(v.size()+noperands-nexpairseqs);
993 // copy elements and split off numerical part
995 while (cit!=v.end()) {
996 if (ex_to<basic>(*cit).tinfo()==this->tinfo()) {
997 const expairseq &subseqref = ex_to<expairseq>(*cit);
998 combine_overall_coeff(subseqref.overall_coeff);
999 epvector::const_iterator cit_s = subseqref.seq.begin();
1000 while (cit_s!=subseqref.seq.end()) {
1001 seq.push_back(*cit_s);
1005 if (is_ex_exactly_of_type(*cit,numeric))
1006 combine_overall_coeff(*cit);
1008 seq.push_back(split_ex_to_pair(*cit));
1014 /** Combine this expairseq with argument epvector.
1015 * It cares for associativity as well as for special handling of numerics. */
1016 void expairseq::make_flat(const epvector &v)
1018 epvector::const_iterator cit;
1020 // count number of operands which are of same expairseq derived type
1021 // and their cumulative number of operands
1022 int nexpairseqs = 0;
1026 while (cit!=v.end()) {
1027 if (ex_to<basic>(cit->rest).tinfo()==this->tinfo()) {
1029 noperands += ex_to<expairseq>(cit->rest).seq.size();
1034 // reserve seq and coeffseq which will hold all operands
1035 seq.reserve(v.size()+noperands-nexpairseqs);
1037 // copy elements and split off numerical part
1039 while (cit!=v.end()) {
1040 if (ex_to<basic>(cit->rest).tinfo()==this->tinfo() &&
1041 this->can_make_flat(*cit)) {
1042 const expairseq &subseqref = ex_to<expairseq>(cit->rest);
1043 combine_overall_coeff(ex_to<numeric>(subseqref.overall_coeff),
1044 ex_to<numeric>(cit->coeff));
1045 epvector::const_iterator cit_s = subseqref.seq.begin();
1046 while (cit_s!=subseqref.seq.end()) {
1047 seq.push_back(expair(cit_s->rest,
1048 ex_to<numeric>(cit_s->coeff).mul_dyn(ex_to<numeric>(cit->coeff))));
1049 //seq.push_back(combine_pair_with_coeff_to_pair(*cit_s,
1054 if (cit->is_canonical_numeric())
1055 combine_overall_coeff(cit->rest);
1057 seq.push_back(*cit);
1063 /** Brings this expairseq into a sorted (canonical) form. */
1064 void expairseq::canonicalize(void)
1066 std::sort(seq.begin(), seq.end(), expair_rest_is_less());
1070 /** Compact a presorted expairseq by combining all matching expairs to one
1071 * each. On an add object, this is responsible for 2*x+3*x+y -> 5*x+y, for
1073 void expairseq::combine_same_terms_sorted_seq(void)
1078 bool needs_further_processing = false;
1080 epvector::iterator itin1 = seq.begin();
1081 epvector::iterator itin2 = itin1+1;
1082 epvector::iterator itout = itin1;
1083 epvector::iterator last = seq.end();
1084 // must_copy will be set to true the first time some combination is
1085 // possible from then on the sequence has changed and must be compacted
1086 bool must_copy = false;
1087 while (itin2!=last) {
1088 if (itin1->rest.compare(itin2->rest)==0) {
1089 itin1->coeff = ex_to<numeric>(itin1->coeff).
1090 add_dyn(ex_to<numeric>(itin2->coeff));
1091 if (expair_needs_further_processing(itin1))
1092 needs_further_processing = true;
1095 if (!ex_to<numeric>(itin1->coeff).is_zero()) {
1104 if (!ex_to<numeric>(itin1->coeff).is_zero()) {
1110 seq.erase(itout,last);
1112 if (needs_further_processing) {
1115 construct_from_epvector(v);
1119 #if EXPAIRSEQ_USE_HASHTAB
1121 unsigned expairseq::calc_hashtabsize(unsigned sz) const
1124 unsigned nearest_power_of_2 = 1 << log2(sz);
1125 // if (nearest_power_of_2 < maxhashtabsize/hashtabfactor) {
1126 // size = nearest_power_of_2*hashtabfactor;
1127 size = nearest_power_of_2/hashtabfactor;
1128 if (size<minhashtabsize)
1130 GINAC_ASSERT(hashtabsize<=0x8000000U); // really max size due to 31 bit hashing
1131 // hashtabsize must be a power of 2
1132 GINAC_ASSERT((1U << log2(size))==size);
1136 unsigned expairseq::calc_hashindex(const ex &e) const
1138 // calculate hashindex
1139 unsigned hash = e.gethash();
1141 if (is_a_numeric_hash(hash)) {
1142 hashindex = hashmask;
1144 hashindex = hash &hashmask;
1145 // last hashtab entry is reserved for numerics
1146 if (hashindex==hashmask) hashindex = 0;
1148 GINAC_ASSERT(hashindex>=0);
1149 GINAC_ASSERT((hashindex<hashtabsize)||(hashtabsize==0));
1153 void expairseq::shrink_hashtab(void)
1155 unsigned new_hashtabsize;
1156 while (hashtabsize!=(new_hashtabsize=calc_hashtabsize(seq.size()))) {
1157 GINAC_ASSERT(new_hashtabsize<hashtabsize);
1158 if (new_hashtabsize==0) {
1165 // shrink by a factor of 2
1166 unsigned half_hashtabsize = hashtabsize/2;
1167 for (unsigned i=0; i<half_hashtabsize-1; ++i)
1168 hashtab[i].merge(hashtab[i+half_hashtabsize],epp_is_less());
1169 // special treatment for numeric hashes
1170 hashtab[0].merge(hashtab[half_hashtabsize-1],epp_is_less());
1171 hashtab[half_hashtabsize-1] = hashtab[hashtabsize-1];
1172 hashtab.resize(half_hashtabsize);
1173 hashtabsize = half_hashtabsize;
1174 hashmask = hashtabsize-1;
1178 void expairseq::remove_hashtab_entry(epvector::const_iterator element)
1181 return; // nothing to do
1183 // calculate hashindex of element to be deleted
1184 unsigned hashindex = calc_hashindex((*element).rest);
1186 // find it in hashtab and remove it
1187 epplist &eppl = hashtab[hashindex];
1188 epplist::iterator epplit = eppl.begin();
1189 bool erased = false;
1190 while (epplit!=eppl.end()) {
1191 if (*epplit == element) {
1199 std::cout << "tried to erase " << element-seq.begin() << std::endl;
1200 std::cout << "size " << seq.end()-seq.begin() << std::endl;
1202 unsigned hashindex = calc_hashindex(element->rest);
1203 epplist &eppl = hashtab[hashindex];
1204 epplist::iterator epplit = eppl.begin();
1205 bool erased = false;
1206 while (epplit!=eppl.end()) {
1207 if (*epplit == element) {
1214 GINAC_ASSERT(erased);
1216 GINAC_ASSERT(erased);
1219 void expairseq::move_hashtab_entry(epvector::const_iterator oldpos,
1220 epvector::iterator newpos)
1222 GINAC_ASSERT(hashtabsize!=0);
1224 // calculate hashindex of element which was moved
1225 unsigned hashindex=calc_hashindex((*newpos).rest);
1227 // find it in hashtab and modify it
1228 epplist &eppl = hashtab[hashindex];
1229 epplist::iterator epplit = eppl.begin();
1230 while (epplit!=eppl.end()) {
1231 if (*epplit == oldpos) {
1237 GINAC_ASSERT(epplit!=eppl.end());
1240 void expairseq::sorted_insert(epplist &eppl, epvector::const_iterator elem)
1242 epplist::const_iterator current = eppl.begin();
1243 while ((current!=eppl.end()) && ((*current)->is_less(*elem))) {
1246 eppl.insert(current,elem);
1249 void expairseq::build_hashtab_and_combine(epvector::iterator &first_numeric,
1250 epvector::iterator &last_non_zero,
1251 std::vector<bool> &touched,
1252 unsigned &number_of_zeroes)
1254 epp current = seq.begin();
1256 while (current!=first_numeric) {
1257 if (is_ex_exactly_of_type(current->rest,numeric)) {
1259 iter_swap(current,first_numeric);
1261 // calculate hashindex
1262 unsigned currenthashindex = calc_hashindex(current->rest);
1264 // test if there is already a matching expair in the hashtab-list
1265 epplist &eppl=hashtab[currenthashindex];
1266 epplist::iterator epplit = eppl.begin();
1267 while (epplit!=eppl.end()) {
1268 if (current->rest.is_equal((*epplit)->rest))
1272 if (epplit==eppl.end()) {
1273 // no matching expair found, append this to end of list
1274 sorted_insert(eppl,current);
1277 // epplit points to a matching expair, combine it with current
1278 (*epplit)->coeff = ex_to<numeric>((*epplit)->coeff).
1279 add_dyn(ex_to<numeric>(current->coeff));
1281 // move obsolete current expair to end by swapping with last_non_zero element
1282 // if this was a numeric, it is swapped with the expair before first_numeric
1283 iter_swap(current,last_non_zero);
1285 if (first_numeric!=last_non_zero) iter_swap(first_numeric,current);
1288 // test if combined term has coeff 0 and can be removed is done later
1289 touched[(*epplit)-seq.begin()] = true;
1295 void expairseq::drop_coeff_0_terms(epvector::iterator &first_numeric,
1296 epvector::iterator &last_non_zero,
1297 std::vector<bool> &touched,
1298 unsigned &number_of_zeroes)
1300 // move terms with coeff 0 to end and remove them from hashtab
1301 // check only those elements which have been touched
1302 epp current = seq.begin();
1304 while (current!=first_numeric) {
1308 } else if (!ex_to<numeric>((*current).coeff).is_zero()) {
1312 remove_hashtab_entry(current);
1314 // move element to the end, unless it is already at the end
1315 if (current!=last_non_zero) {
1316 iter_swap(current,last_non_zero);
1318 bool numeric_swapped = first_numeric!=last_non_zero;
1319 if (numeric_swapped)
1320 iter_swap(first_numeric,current);
1321 epvector::iterator changed_entry;
1323 if (numeric_swapped)
1324 changed_entry = first_numeric;
1326 changed_entry = last_non_zero;
1331 if (first_numeric!=current) {
1333 // change entry in hashtab which referred to first_numeric or last_non_zero to current
1334 move_hashtab_entry(changed_entry,current);
1335 touched[current-seq.begin()] = touched[changed_entry-seq.begin()];
1344 GINAC_ASSERT(i==current-seq.begin());
1347 /** True if one of the coeffs vanishes, otherwise false.
1348 * This would be an invariant violation, so this should only be used for
1349 * debugging purposes. */
1350 bool expairseq::has_coeff_0(void) const
1352 epvector::const_iterator i = seq.begin(), end = seq.end();
1354 if (i->coeff.is_zero())
1361 void expairseq::add_numerics_to_hashtab(epvector::iterator first_numeric,
1362 epvector::const_iterator last_non_zero)
1364 if (first_numeric == seq.end()) return; // no numerics
1366 epvector::const_iterator current = first_numeric, last = last_non_zero + 1;
1367 while (current != last) {
1368 sorted_insert(hashtab[hashmask], current);
1373 void expairseq::combine_same_terms(void)
1375 // combine same terms, drop term with coeff 0, move numerics to end
1377 // calculate size of hashtab
1378 hashtabsize = calc_hashtabsize(seq.size());
1380 // hashtabsize is a power of 2
1381 hashmask = hashtabsize-1;
1385 hashtab.resize(hashtabsize);
1387 if (hashtabsize==0) {
1389 combine_same_terms_sorted_seq();
1390 GINAC_ASSERT(!has_coeff_0());
1394 // iterate through seq, move numerics to end,
1395 // fill hashtab and combine same terms
1396 epvector::iterator first_numeric = seq.end();
1397 epvector::iterator last_non_zero = seq.end()-1;
1399 unsigned num = seq.size();
1400 std::vector<bool> touched(num);
1402 unsigned number_of_zeroes = 0;
1404 GINAC_ASSERT(!has_coeff_0());
1405 build_hashtab_and_combine(first_numeric,last_non_zero,touched,number_of_zeroes);
1407 // there should not be any terms with coeff 0 from the beginning,
1408 // so it should be safe to skip this step
1409 if (number_of_zeroes!=0) {
1410 drop_coeff_0_terms(first_numeric,last_non_zero,touched,number_of_zeroes);
1413 add_numerics_to_hashtab(first_numeric,last_non_zero);
1415 // pop zero elements
1416 for (unsigned i=0; i<number_of_zeroes; ++i) {
1420 // shrink hashtabsize to calculated value
1421 GINAC_ASSERT(!has_coeff_0());
1425 GINAC_ASSERT(!has_coeff_0());
1428 #endif // EXPAIRSEQ_USE_HASHTAB
1430 /** Check if this expairseq is in sorted (canonical) form. Useful mainly for
1431 * debugging or in assertions since being sorted is an invariance. */
1432 bool expairseq::is_canonical() const
1434 if (seq.size() <= 1)
1437 #if EXPAIRSEQ_USE_HASHTAB
1438 if (hashtabsize > 0) return 1; // not canoncalized
1439 #endif // EXPAIRSEQ_USE_HASHTAB
1441 epvector::const_iterator it = seq.begin(), itend = seq.end();
1442 epvector::const_iterator it_last = it;
1443 for (++it; it!=itend; it_last=it, ++it) {
1444 if (!(it_last->is_less(*it) || it_last->is_equal(*it))) {
1445 if (!is_ex_exactly_of_type(it_last->rest,numeric) ||
1446 !is_ex_exactly_of_type(it->rest,numeric)) {
1447 // double test makes it easier to set a breakpoint...
1448 if (!is_ex_exactly_of_type(it_last->rest,numeric) ||
1449 !is_ex_exactly_of_type(it->rest,numeric)) {
1450 printpair(std::clog, *it_last, 0);
1452 printpair(std::clog, *it, 0);
1454 std::clog << "pair1:" << std::endl;
1455 it_last->rest.print(print_tree(std::clog));
1456 it_last->coeff.print(print_tree(std::clog));
1457 std::clog << "pair2:" << std::endl;
1458 it->rest.print(print_tree(std::clog));
1459 it->coeff.print(print_tree(std::clog));
1469 /** Member-wise expand the expairs in this sequence.
1471 * @see expairseq::expand()
1472 * @return pointer to epvector containing expanded pairs or zero pointer,
1473 * if no members were changed. */
1474 epvector * expairseq::expandchildren(unsigned options) const
1476 const epvector::const_iterator last = seq.end();
1477 epvector::const_iterator cit = seq.begin();
1479 const ex &expanded_ex = cit->rest.expand(options);
1480 if (!are_ex_trivially_equal(cit->rest,expanded_ex)) {
1482 // something changed, copy seq, eval and return it
1483 epvector *s = new epvector;
1484 s->reserve(seq.size());
1486 // copy parts of seq which are known not to have changed
1487 epvector::const_iterator cit2 = seq.begin();
1489 s->push_back(*cit2);
1492 // copy first changed element
1493 s->push_back(combine_ex_with_coeff_to_pair(expanded_ex,
1497 while (cit2!=last) {
1498 s->push_back(combine_ex_with_coeff_to_pair(cit2->rest.expand(options),
1507 return 0; // signalling nothing has changed
1511 /** Member-wise evaluate the expairs in this sequence.
1513 * @see expairseq::eval()
1514 * @return pointer to epvector containing evaluated pairs or zero pointer,
1515 * if no members were changed. */
1516 epvector * expairseq::evalchildren(int level) const
1518 // returns a NULL pointer if nothing had to be evaluated
1519 // returns a pointer to a newly created epvector otherwise
1520 // (which has to be deleted somewhere else)
1525 if (level == -max_recursion_level)
1526 throw(std::runtime_error("max recursion level reached"));
1529 epvector::const_iterator last = seq.end();
1530 epvector::const_iterator cit = seq.begin();
1532 const ex &evaled_ex = cit->rest.eval(level);
1533 if (!are_ex_trivially_equal(cit->rest,evaled_ex)) {
1535 // something changed, copy seq, eval and return it
1536 epvector *s = new epvector;
1537 s->reserve(seq.size());
1539 // copy parts of seq which are known not to have changed
1540 epvector::const_iterator cit2=seq.begin();
1542 s->push_back(*cit2);
1545 // copy first changed element
1546 s->push_back(combine_ex_with_coeff_to_pair(evaled_ex,
1550 while (cit2!=last) {
1551 s->push_back(combine_ex_with_coeff_to_pair(cit2->rest.eval(level),
1560 return 0; // signalling nothing has changed
1564 /** Member-wise substitute in this sequence.
1566 * @see expairseq::subs()
1567 * @return pointer to epvector containing pairs after application of subs,
1568 * or NULL pointer if no members were changed. */
1569 epvector * expairseq::subschildren(const lst &ls, const lst &lr, bool no_pattern) const
1571 GINAC_ASSERT(ls.nops()==lr.nops());
1573 // The substitution is "complex" when any of the objects to be substituted
1574 // is a product or power. In this case we have to recombine the pairs
1575 // because the numeric coefficients may be part of the search pattern.
1576 bool complex_subs = false;
1577 for (unsigned i=0; i<ls.nops(); ++i)
1578 if (is_ex_exactly_of_type(ls.op(i), mul) || is_ex_exactly_of_type(ls.op(i), power)) {
1579 complex_subs = true;
1585 // Substitute in the recombined pairs
1586 epvector::const_iterator cit = seq.begin(), last = seq.end();
1587 while (cit != last) {
1589 const ex &orig_ex = recombine_pair_to_ex(*cit);
1590 const ex &subsed_ex = orig_ex.subs(ls, lr, no_pattern);
1591 if (!are_ex_trivially_equal(orig_ex, subsed_ex)) {
1593 // Something changed, copy seq, subs and return it
1594 epvector *s = new epvector;
1595 s->reserve(seq.size());
1597 // Copy parts of seq which are known not to have changed
1598 s->insert(s->begin(), seq.begin(), cit);
1600 // Copy first changed element
1601 s->push_back(split_ex_to_pair(subsed_ex));
1605 while (cit != last) {
1606 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit).subs(ls, lr, no_pattern)));
1617 // Substitute only in the "rest" part of the pairs
1618 epvector::const_iterator cit = seq.begin(), last = seq.end();
1619 while (cit != last) {
1621 const ex &subsed_ex = cit->rest.subs(ls, lr, no_pattern);
1622 if (!are_ex_trivially_equal(cit->rest, subsed_ex)) {
1624 // Something changed, copy seq, subs and return it
1625 epvector *s = new epvector;
1626 s->reserve(seq.size());
1628 // Copy parts of seq which are known not to have changed
1629 s->insert(s->begin(), seq.begin(), cit);
1631 // Copy first changed element
1632 s->push_back(combine_ex_with_coeff_to_pair(subsed_ex, cit->coeff));
1636 while (cit != last) {
1637 s->push_back(combine_ex_with_coeff_to_pair(cit->rest.subs(ls, lr, no_pattern),
1648 // Nothing has changed
1653 // static member variables
1656 #if EXPAIRSEQ_USE_HASHTAB
1657 unsigned expairseq::maxhashtabsize = 0x4000000U;
1658 unsigned expairseq::minhashtabsize = 0x1000U;
1659 unsigned expairseq::hashtabfactor = 1;
1660 #endif // EXPAIRSEQ_USE_HASHTAB
1662 } // namespace GiNaC