1 /** @file expairseq.cpp
3 * Implementation of sequences of expression pairs. */
6 * GiNaC Copyright (C) 1999-2001 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
27 #include "expairseq.h"
31 #include "relational.h"
37 #if EXPAIRSEQ_USE_HASHTAB
39 #endif // EXPAIRSEQ_USE_HASHTAB
44 GINAC_IMPLEMENT_REGISTERED_CLASS_NO_CTORS(expairseq, basic)
53 bool operator()(const epp &lh, const epp &rh) const
55 return (*lh).is_less(*rh);
60 // default ctor, dtor, copy ctor, assignment operator and helpers
65 expairseq::expairseq(const expairseq &other)
70 const expairseq &expairseq::operator=(const expairseq &other)
81 /** For use by copy ctor and assignment operator. */
82 void expairseq::copy(const expairseq &other)
84 inherited::copy(other);
86 overall_coeff = other.overall_coeff;
87 #if EXPAIRSEQ_USE_HASHTAB
89 hashtabsize = other.hashtabsize;
91 hashmask = other.hashmask;
92 hashtab.resize(hashtabsize);
93 epvector::const_iterator osb = other.seq.begin();
94 for (unsigned i=0; i<hashtabsize; ++i) {
96 for (epplist::const_iterator cit=other.hashtab[i].begin();
97 cit!=other.hashtab[i].end(); ++cit) {
98 hashtab[i].push_back(seq.begin()+((*cit)-osb));
104 #endif // EXPAIRSEQ_USE_HASHTAB
107 DEFAULT_DESTROY(expairseq)
113 expairseq::expairseq(const ex &lh, const ex &rh) : inherited(TINFO_expairseq)
115 construct_from_2_ex(lh,rh);
116 GINAC_ASSERT(is_canonical());
119 expairseq::expairseq(const exvector &v) : inherited(TINFO_expairseq)
121 construct_from_exvector(v);
122 GINAC_ASSERT(is_canonical());
125 expairseq::expairseq(const epvector &v, const ex &oc)
126 : inherited(TINFO_expairseq), overall_coeff(oc)
128 construct_from_epvector(v);
129 GINAC_ASSERT(is_canonical());
132 expairseq::expairseq(epvector *vp, const ex &oc)
133 : inherited(TINFO_expairseq), overall_coeff(oc)
136 construct_from_epvector(*vp);
138 GINAC_ASSERT(is_canonical());
145 expairseq::expairseq(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
146 #if EXPAIRSEQ_USE_HASHTAB
150 for (unsigned int i=0; true; i++) {
153 if (n.find_ex("rest", rest, sym_lst, i) && n.find_ex("coeff", coeff, sym_lst, i))
154 seq.push_back(expair(rest, coeff));
158 n.find_ex("overall_coeff", overall_coeff, sym_lst);
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 basic *expairseq::duplicate() const
183 return new expairseq(*this);
186 void expairseq::print(const print_context &c, unsigned level) const
188 if (is_of_type(c, print_tree)) {
190 unsigned delta_indent = static_cast<const print_tree &>(c).delta_indent;
192 c.s << std::string(level, ' ') << class_name()
193 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
194 << ", nops=" << nops()
196 unsigned num = seq.size();
197 for (unsigned i=0; i<num; ++i) {
198 seq[i].rest.print(c, level + delta_indent);
199 seq[i].coeff.print(c, level + delta_indent);
201 c.s << std::string(level + delta_indent, ' ') << "-----" << std::endl;
203 if (!overall_coeff.is_equal(default_overall_coeff())) {
204 c.s << std::string(level + delta_indent, ' ') << "-----" << std::endl
205 << std::string(level + delta_indent, ' ') << "overall_coeff" << std::endl;
206 overall_coeff.print(c, level + delta_indent);
208 c.s << std::string(level + delta_indent,' ') << "=====" << std::endl;
209 #if EXPAIRSEQ_USE_HASHTAB
210 c.s << std::string(level + delta_indent,' ')
211 << "hashtab size " << hashtabsize << std::endl;
212 if (hashtabsize == 0) return;
214 unsigned count[MAXCOUNT+1];
215 for (int i=0; i<MAXCOUNT+1; ++i)
217 unsigned this_bin_fill;
218 unsigned cum_fill_sq = 0;
219 unsigned cum_fill = 0;
220 for (unsigned i=0; i<hashtabsize; ++i) {
222 if (hashtab[i].size() > 0) {
223 c.s << std::string(level + delta_indent, ' ')
224 << "bin " << i << " with entries ";
225 for (epplist::const_iterator it=hashtab[i].begin();
226 it!=hashtab[i].end(); ++it) {
227 c.s << *it-seq.begin() << " ";
231 cum_fill += this_bin_fill;
232 cum_fill_sq += this_bin_fill*this_bin_fill;
234 if (this_bin_fill<MAXCOUNT)
235 ++count[this_bin_fill];
241 double lambda = (1.0*seq.size()) / hashtabsize;
242 for (int k=0; k<MAXCOUNT; ++k) {
245 double prob = std::pow(lambda,k)/fact * std::exp(-lambda);
247 c.s << std::string(level + delta_indent, ' ') << "bins with " << k << " entries: "
248 << int(1000.0*count[k]/hashtabsize)/10.0 << "% (expected: "
249 << int(prob*1000)/10.0 << ")" << std::endl;
251 c.s << std::string(level + delta_indent, ' ') << "bins with more entries: "
252 << int(1000.0*count[MAXCOUNT]/hashtabsize)/10.0 << "% (expected: "
253 << int((1-cum_prob)*1000)/10.0 << ")" << std::endl;
255 c.s << std::string(level + delta_indent, ' ') << "variance: "
256 << 1.0/hashtabsize*cum_fill_sq-(1.0/hashtabsize*cum_fill)*(1.0/hashtabsize*cum_fill)
258 c.s << std::string(level + delta_indent, ' ') << "average fill: "
259 << (1.0*cum_fill)/hashtabsize
260 << " (should be equal to " << (1.0*seq.size())/hashtabsize << ")" << std::endl;
261 #endif // EXPAIRSEQ_USE_HASHTAB
265 printseq(c, ',', precedence(), level);
270 bool expairseq::info(unsigned inf) const
272 return inherited::info(inf);
275 unsigned expairseq::nops() const
277 if (overall_coeff.is_equal(default_overall_coeff()))
283 ex expairseq::op(int i) const
285 if (unsigned(i)<seq.size())
286 return recombine_pair_to_ex(seq[i]);
287 GINAC_ASSERT(!overall_coeff.is_equal(default_overall_coeff()));
288 return overall_coeff;
291 ex &expairseq::let_op(int i)
293 throw(std::logic_error("let_op not defined for expairseq and derived classes (add,mul,...)"));
296 ex expairseq::map(map_function &f) const
298 epvector *v = new epvector;
299 v->reserve(seq.size());
301 epvector::const_iterator cit = seq.begin(), last = seq.end();
302 while (cit != last) {
303 v->push_back(split_ex_to_pair(f(recombine_pair_to_ex(*cit))));
307 if (overall_coeff.is_equal(default_overall_coeff()))
308 return thisexpairseq(v, default_overall_coeff());
310 return thisexpairseq(v, f(overall_coeff));
313 /** Perform coefficient-wise automatic term rewriting rules in this class. */
314 ex expairseq::eval(int level) const
316 if ((level==1) && (flags &status_flags::evaluated))
319 epvector *vp = evalchildren(level);
323 return (new expairseq(vp,overall_coeff))->setflag(status_flags::dynallocated | status_flags::evaluated);
326 bool expairseq::match(const ex & pattern, lst & repl_lst) const
328 // This differs from basic::match() because we want "a+b+c+d" to
329 // match "d+*+b" with "*" being "a+c", and we want to honor commutativity
331 if (this->tinfo() == ex_to<basic>(pattern).tinfo()) {
333 // Check whether global wildcard (one that matches the "rest of the
334 // expression", like "*" above) is present
335 bool has_global_wildcard = false;
337 for (unsigned int i=0; i<pattern.nops(); i++) {
338 if (is_ex_exactly_of_type(pattern.op(i), wildcard)) {
339 has_global_wildcard = true;
340 global_wildcard = pattern.op(i);
345 // Unfortunately, this is an O(N^2) operation because we can't
346 // sort the pattern in a useful way...
351 for (unsigned i=0; i<nops(); i++)
352 ops.push_back(op(i));
354 // Now, for every term of the pattern, look for a matching term in
355 // the expression and remove the match
356 for (unsigned i=0; i<pattern.nops(); i++) {
357 ex p = pattern.op(i);
358 if (has_global_wildcard && p.is_equal(global_wildcard))
360 exvector::iterator it = ops.begin(), itend = ops.end();
361 while (it != itend) {
362 if (it->match(p, repl_lst)) {
368 return false; // no match found
372 if (has_global_wildcard) {
374 // Assign all the remaining terms to the global wildcard (unless
375 // it has already been matched before, in which case the matches
377 unsigned num = ops.size();
378 epvector *vp = new epvector();
380 for (unsigned i=0; i<num; i++)
381 vp->push_back(split_ex_to_pair(ops[i]));
382 ex rest = thisexpairseq(vp, default_overall_coeff());
383 for (unsigned i=0; i<repl_lst.nops(); i++) {
384 if (repl_lst.op(i).op(0).is_equal(global_wildcard))
385 return rest.is_equal(repl_lst.op(i).op(1));
387 repl_lst.append(global_wildcard == rest);
392 // No global wildcard, then the match fails if there are any
393 // unmatched terms left
397 return inherited::match(pattern, repl_lst);
400 ex expairseq::subs(const lst &ls, const lst &lr, bool no_pattern) const
402 epvector *vp = subschildren(ls, lr, no_pattern);
404 return ex_to<basic>(thisexpairseq(vp, overall_coeff)).basic::subs(ls, lr, no_pattern);
406 return basic::subs(ls, lr, no_pattern);
411 int expairseq::compare_same_type(const basic &other) const
413 GINAC_ASSERT(is_a<expairseq>(other));
414 const expairseq &o = static_cast<const expairseq &>(other);
418 // compare number of elements
419 if (seq.size() != o.seq.size())
420 return (seq.size()<o.seq.size()) ? -1 : 1;
422 // compare overall_coeff
423 cmpval = overall_coeff.compare(o.overall_coeff);
427 #if EXPAIRSEQ_USE_HASHTAB
428 GINAC_ASSERT(hashtabsize==o.hashtabsize);
429 if (hashtabsize==0) {
430 #endif // EXPAIRSEQ_USE_HASHTAB
431 epvector::const_iterator cit1 = seq.begin();
432 epvector::const_iterator cit2 = o.seq.begin();
433 epvector::const_iterator last1 = seq.end();
434 epvector::const_iterator last2 = o.seq.end();
436 for (; (cit1!=last1)&&(cit2!=last2); ++cit1, ++cit2) {
437 cmpval = (*cit1).compare(*cit2);
438 if (cmpval!=0) return cmpval;
441 GINAC_ASSERT(cit1==last1);
442 GINAC_ASSERT(cit2==last2);
445 #if EXPAIRSEQ_USE_HASHTAB
448 // compare number of elements in each hashtab entry
449 for (unsigned i=0; i<hashtabsize; ++i) {
450 unsigned cursize=hashtab[i].size();
451 if (cursize != o.hashtab[i].size())
452 return (cursize < o.hashtab[i].size()) ? -1 : 1;
455 // compare individual (sorted) hashtab entries
456 for (unsigned i=0; i<hashtabsize; ++i) {
457 unsigned sz = hashtab[i].size();
459 const epplist &eppl1 = hashtab[i];
460 const epplist &eppl2 = o.hashtab[i];
461 epplist::const_iterator it1 = eppl1.begin();
462 epplist::const_iterator it2 = eppl2.begin();
463 while (it1!=eppl1.end()) {
464 cmpval = (*(*it1)).compare(*(*it2));
474 #endif // EXPAIRSEQ_USE_HASHTAB
477 bool expairseq::is_equal_same_type(const basic &other) const
479 const expairseq &o = static_cast<const expairseq &>(other);
481 // compare number of elements
482 if (seq.size()!=o.seq.size())
485 // compare overall_coeff
486 if (!overall_coeff.is_equal(o.overall_coeff))
489 #if EXPAIRSEQ_USE_HASHTAB
490 // compare number of elements in each hashtab entry
491 if (hashtabsize!=o.hashtabsize) {
492 std::cout << "this:" << std::endl;
493 print(print_tree(std::cout));
494 std::cout << "other:" << std::endl;
495 other.print(print_tree(std::cout));
498 GINAC_ASSERT(hashtabsize==o.hashtabsize);
500 if (hashtabsize==0) {
501 #endif // EXPAIRSEQ_USE_HASHTAB
502 epvector::const_iterator cit1 = seq.begin();
503 epvector::const_iterator cit2 = o.seq.begin();
504 epvector::const_iterator last1 = seq.end();
506 while (cit1!=last1) {
507 if (!(*cit1).is_equal(*cit2)) return false;
513 #if EXPAIRSEQ_USE_HASHTAB
516 for (unsigned i=0; i<hashtabsize; ++i) {
517 if (hashtab[i].size() != o.hashtab[i].size())
521 // compare individual sorted hashtab entries
522 for (unsigned i=0; i<hashtabsize; ++i) {
523 unsigned sz = hashtab[i].size();
525 const epplist &eppl1 = hashtab[i];
526 const epplist &eppl2 = o.hashtab[i];
527 epplist::const_iterator it1 = eppl1.begin();
528 epplist::const_iterator it2 = eppl2.begin();
529 while (it1!=eppl1.end()) {
530 if (!(*(*it1)).is_equal(*(*it2))) return false;
538 #endif // EXPAIRSEQ_USE_HASHTAB
541 unsigned expairseq::return_type(void) const
543 return return_types::noncommutative_composite;
546 unsigned expairseq::calchash(void) const
548 unsigned v = golden_ratio_hash(this->tinfo());
549 epvector::const_iterator i = seq.begin(), end = seq.end();
551 #if !EXPAIRSEQ_USE_HASHTAB
552 v = rotate_left_31(v); // rotation would spoil commutativity
553 #endif // EXPAIRSEQ_USE_HASHTAB
554 v ^= i->rest.gethash();
555 #if !EXPAIRSEQ_USE_HASHTAB
556 v = rotate_left_31(v);
557 v ^= i->coeff.gethash();
558 #endif // EXPAIRSEQ_USE_HASHTAB
562 v ^= overall_coeff.gethash();
565 // store calculated hash value only if object is already evaluated
566 if (flags &status_flags::evaluated) {
567 setflag(status_flags::hash_calculated);
574 ex expairseq::expand(unsigned options) const
576 epvector *vp = expandchildren(options);
578 // The terms have not changed, so it is safe to declare this expanded
579 return (options == 0) ? setflag(status_flags::expanded) : *this;
581 return thisexpairseq(vp, overall_coeff);
585 // new virtual functions which can be overridden by derived classes
590 /** Create an object of this type.
591 * This method works similar to a constructor. It is useful because expairseq
592 * has (at least) two possible different semantics but we want to inherit
593 * methods thus avoiding code duplication. Sometimes a method in expairseq
594 * has to create a new one of the same semantics, which cannot be done by a
595 * ctor because the name (add, mul,...) is unknown on the expaiseq level. In
596 * order for this trick to work a derived class must of course override this
598 ex expairseq::thisexpairseq(const epvector &v, const ex &oc) const
600 return expairseq(v,oc);
603 ex expairseq::thisexpairseq(epvector *vp, const ex &oc) const
605 return expairseq(vp,oc);
608 void expairseq::printpair(const print_context & c, const expair & p, unsigned upper_precedence) const
611 p.rest.print(c, precedence());
613 p.coeff.print(c, precedence());
617 void expairseq::printseq(const print_context & c, char delim,
618 unsigned this_precedence,
619 unsigned upper_precedence) const
621 if (this_precedence <= upper_precedence)
623 epvector::const_iterator it, it_last = seq.end() - 1;
624 for (it=seq.begin(); it!=it_last; ++it) {
625 printpair(c, *it, this_precedence);
628 printpair(c, *it, this_precedence);
629 if (!overall_coeff.is_equal(default_overall_coeff())) {
631 overall_coeff.print(c, this_precedence);
634 if (this_precedence <= upper_precedence)
639 /** Form an expair from an ex, using the corresponding semantics.
640 * @see expairseq::recombine_pair_to_ex() */
641 expair expairseq::split_ex_to_pair(const ex &e) const
643 return expair(e,_ex1);
647 expair expairseq::combine_ex_with_coeff_to_pair(const ex &e,
650 GINAC_ASSERT(is_exactly_a<numeric>(c));
656 expair expairseq::combine_pair_with_coeff_to_pair(const expair &p,
659 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
660 GINAC_ASSERT(is_exactly_a<numeric>(c));
662 return expair(p.rest,ex_to<numeric>(p.coeff).mul_dyn(ex_to<numeric>(c)));
666 /** Form an ex out of an expair, using the corresponding semantics.
667 * @see expairseq::split_ex_to_pair() */
668 ex expairseq::recombine_pair_to_ex(const expair &p) const
670 return lst(p.rest,p.coeff);
673 bool expairseq::expair_needs_further_processing(epp it)
675 #if EXPAIRSEQ_USE_HASHTAB
676 //# error "FIXME: expair_needs_further_processing not yet implemented for hashtabs, sorry. A.F."
677 #endif // EXPAIRSEQ_USE_HASHTAB
681 ex expairseq::default_overall_coeff(void) const
686 void expairseq::combine_overall_coeff(const ex &c)
688 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
689 GINAC_ASSERT(is_exactly_a<numeric>(c));
690 overall_coeff = ex_to<numeric>(overall_coeff).add_dyn(ex_to<numeric>(c));
693 void expairseq::combine_overall_coeff(const ex &c1, const ex &c2)
695 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
696 GINAC_ASSERT(is_exactly_a<numeric>(c1));
697 GINAC_ASSERT(is_exactly_a<numeric>(c2));
698 overall_coeff = ex_to<numeric>(overall_coeff).
699 add_dyn(ex_to<numeric>(c1).mul(ex_to<numeric>(c2)));
702 bool expairseq::can_make_flat(const expair &p) const
709 // non-virtual functions in this class
712 void expairseq::construct_from_2_ex_via_exvector(const ex &lh, const ex &rh)
718 construct_from_exvector(v);
719 #if EXPAIRSEQ_USE_HASHTAB
720 GINAC_ASSERT((hashtabsize==0)||(hashtabsize>=minhashtabsize));
721 GINAC_ASSERT(hashtabsize==calc_hashtabsize(seq.size()));
722 #endif // EXPAIRSEQ_USE_HASHTAB
725 void expairseq::construct_from_2_ex(const ex &lh, const ex &rh)
727 if (ex_to<basic>(lh).tinfo()==this->tinfo()) {
728 if (ex_to<basic>(rh).tinfo()==this->tinfo()) {
729 #if EXPAIRSEQ_USE_HASHTAB
730 unsigned totalsize = ex_to<expairseq>(lh).seq.size() +
731 ex_to<expairseq>(rh).seq.size();
732 if (calc_hashtabsize(totalsize)!=0) {
733 construct_from_2_ex_via_exvector(lh,rh);
735 #endif // EXPAIRSEQ_USE_HASHTAB
736 construct_from_2_expairseq(ex_to<expairseq>(lh),
737 ex_to<expairseq>(rh));
738 #if EXPAIRSEQ_USE_HASHTAB
740 #endif // EXPAIRSEQ_USE_HASHTAB
743 #if EXPAIRSEQ_USE_HASHTAB
744 unsigned totalsize = ex_to<expairseq>(lh).seq.size()+1;
745 if (calc_hashtabsize(totalsize)!=0) {
746 construct_from_2_ex_via_exvector(lh, rh);
748 #endif // EXPAIRSEQ_USE_HASHTAB
749 construct_from_expairseq_ex(ex_to<expairseq>(lh), rh);
750 #if EXPAIRSEQ_USE_HASHTAB
752 #endif // EXPAIRSEQ_USE_HASHTAB
755 } else if (ex_to<basic>(rh).tinfo()==this->tinfo()) {
756 #if EXPAIRSEQ_USE_HASHTAB
757 unsigned totalsize=ex_to<expairseq>(rh).seq.size()+1;
758 if (calc_hashtabsize(totalsize)!=0) {
759 construct_from_2_ex_via_exvector(lh,rh);
761 #endif // EXPAIRSEQ_USE_HASHTAB
762 construct_from_expairseq_ex(ex_to<expairseq>(rh),lh);
763 #if EXPAIRSEQ_USE_HASHTAB
765 #endif // EXPAIRSEQ_USE_HASHTAB
769 #if EXPAIRSEQ_USE_HASHTAB
770 if (calc_hashtabsize(2)!=0) {
771 construct_from_2_ex_via_exvector(lh,rh);
775 #endif // EXPAIRSEQ_USE_HASHTAB
777 if (is_ex_exactly_of_type(lh,numeric)) {
778 if (is_ex_exactly_of_type(rh,numeric)) {
779 combine_overall_coeff(lh);
780 combine_overall_coeff(rh);
782 combine_overall_coeff(lh);
783 seq.push_back(split_ex_to_pair(rh));
786 if (is_ex_exactly_of_type(rh,numeric)) {
787 combine_overall_coeff(rh);
788 seq.push_back(split_ex_to_pair(lh));
790 expair p1 = split_ex_to_pair(lh);
791 expair p2 = split_ex_to_pair(rh);
793 int cmpval = p1.rest.compare(p2.rest);
795 p1.coeff = ex_to<numeric>(p1.coeff).add_dyn(ex_to<numeric>(p2.coeff));
796 if (!ex_to<numeric>(p1.coeff).is_zero()) {
797 // no further processing is necessary, since this
798 // one element will usually be recombined in eval()
815 void expairseq::construct_from_2_expairseq(const expairseq &s1,
818 combine_overall_coeff(s1.overall_coeff);
819 combine_overall_coeff(s2.overall_coeff);
821 epvector::const_iterator first1 = s1.seq.begin();
822 epvector::const_iterator last1 = s1.seq.end();
823 epvector::const_iterator first2 = s2.seq.begin();
824 epvector::const_iterator last2 = s2.seq.end();
826 seq.reserve(s1.seq.size()+s2.seq.size());
828 bool needs_further_processing=false;
830 while (first1!=last1 && first2!=last2) {
831 int cmpval = (*first1).rest.compare((*first2).rest);
834 const numeric &newcoeff = ex_to<numeric>(first1->coeff).
835 add(ex_to<numeric>(first2->coeff));
836 if (!newcoeff.is_zero()) {
837 seq.push_back(expair(first1->rest,newcoeff));
838 if (expair_needs_further_processing(seq.end()-1)) {
839 needs_further_processing = true;
844 } else if (cmpval<0) {
845 seq.push_back(*first1);
848 seq.push_back(*first2);
853 while (first1!=last1) {
854 seq.push_back(*first1);
857 while (first2!=last2) {
858 seq.push_back(*first2);
862 if (needs_further_processing) {
865 construct_from_epvector(v);
869 void expairseq::construct_from_expairseq_ex(const expairseq &s,
872 combine_overall_coeff(s.overall_coeff);
873 if (is_ex_exactly_of_type(e,numeric)) {
874 combine_overall_coeff(e);
879 epvector::const_iterator first = s.seq.begin();
880 epvector::const_iterator last = s.seq.end();
881 expair p = split_ex_to_pair(e);
883 seq.reserve(s.seq.size()+1);
884 bool p_pushed = false;
886 bool needs_further_processing=false;
888 // merge p into s.seq
889 while (first!=last) {
890 int cmpval = (*first).rest.compare(p.rest);
893 const numeric &newcoeff = ex_to<numeric>(first->coeff).
894 add(ex_to<numeric>(p.coeff));
895 if (!newcoeff.is_zero()) {
896 seq.push_back(expair(first->rest,newcoeff));
897 if (expair_needs_further_processing(seq.end()-1))
898 needs_further_processing = true;
903 } else if (cmpval<0) {
904 seq.push_back(*first);
914 // while loop exited because p was pushed, now push rest of s.seq
915 while (first!=last) {
916 seq.push_back(*first);
920 // while loop exited because s.seq was pushed, now push p
924 if (needs_further_processing) {
927 construct_from_epvector(v);
931 void expairseq::construct_from_exvector(const exvector &v)
933 // simplifications: +(a,+(b,c),d) -> +(a,b,c,d) (associativity)
934 // +(d,b,c,a) -> +(a,b,c,d) (canonicalization)
935 // +(...,x,*(x,c1),*(x,c2)) -> +(...,*(x,1+c1+c2)) (c1, c2 numeric())
936 // (same for (+,*) -> (*,^)
939 #if EXPAIRSEQ_USE_HASHTAB
940 combine_same_terms();
943 combine_same_terms_sorted_seq();
944 #endif // EXPAIRSEQ_USE_HASHTAB
947 void expairseq::construct_from_epvector(const epvector &v)
949 // simplifications: +(a,+(b,c),d) -> +(a,b,c,d) (associativity)
950 // +(d,b,c,a) -> +(a,b,c,d) (canonicalization)
951 // +(...,x,*(x,c1),*(x,c2)) -> +(...,*(x,1+c1+c2)) (c1, c2 numeric())
952 // (same for (+,*) -> (*,^)
955 #if EXPAIRSEQ_USE_HASHTAB
956 combine_same_terms();
959 combine_same_terms_sorted_seq();
960 #endif // EXPAIRSEQ_USE_HASHTAB
963 /** Combine this expairseq with argument exvector.
964 * It cares for associativity as well as for special handling of numerics. */
965 void expairseq::make_flat(const exvector &v)
967 exvector::const_iterator cit;
969 // count number of operands which are of same expairseq derived type
970 // and their cumulative number of operands
975 while (cit!=v.end()) {
976 if (ex_to<basic>(*cit).tinfo()==this->tinfo()) {
978 noperands += ex_to<expairseq>(*cit).seq.size();
983 // reserve seq and coeffseq which will hold all operands
984 seq.reserve(v.size()+noperands-nexpairseqs);
986 // copy elements and split off numerical part
988 while (cit!=v.end()) {
989 if (ex_to<basic>(*cit).tinfo()==this->tinfo()) {
990 const expairseq &subseqref = ex_to<expairseq>(*cit);
991 combine_overall_coeff(subseqref.overall_coeff);
992 epvector::const_iterator cit_s = subseqref.seq.begin();
993 while (cit_s!=subseqref.seq.end()) {
994 seq.push_back(*cit_s);
998 if (is_ex_exactly_of_type(*cit,numeric))
999 combine_overall_coeff(*cit);
1001 seq.push_back(split_ex_to_pair(*cit));
1007 /** Combine this expairseq with argument epvector.
1008 * It cares for associativity as well as for special handling of numerics. */
1009 void expairseq::make_flat(const epvector &v)
1011 epvector::const_iterator cit;
1013 // count number of operands which are of same expairseq derived type
1014 // and their cumulative number of operands
1015 int nexpairseqs = 0;
1019 while (cit!=v.end()) {
1020 if (ex_to<basic>(cit->rest).tinfo()==this->tinfo()) {
1022 noperands += ex_to<expairseq>(cit->rest).seq.size();
1027 // reserve seq and coeffseq which will hold all operands
1028 seq.reserve(v.size()+noperands-nexpairseqs);
1030 // copy elements and split off numerical part
1032 while (cit!=v.end()) {
1033 if (ex_to<basic>(cit->rest).tinfo()==this->tinfo() &&
1034 this->can_make_flat(*cit)) {
1035 const expairseq &subseqref = ex_to<expairseq>(cit->rest);
1036 combine_overall_coeff(ex_to<numeric>(subseqref.overall_coeff),
1037 ex_to<numeric>(cit->coeff));
1038 epvector::const_iterator cit_s = subseqref.seq.begin();
1039 while (cit_s!=subseqref.seq.end()) {
1040 seq.push_back(expair(cit_s->rest,
1041 ex_to<numeric>(cit_s->coeff).mul_dyn(ex_to<numeric>(cit->coeff))));
1042 //seq.push_back(combine_pair_with_coeff_to_pair(*cit_s,
1047 if (cit->is_canonical_numeric())
1048 combine_overall_coeff(cit->rest);
1050 seq.push_back(*cit);
1056 /** Brings this expairseq into a sorted (canonical) form. */
1057 void expairseq::canonicalize(void)
1059 sort(seq.begin(), seq.end(), expair_is_less());
1063 /** Compact a presorted expairseq by combining all matching expairs to one
1064 * each. On an add object, this is responsible for 2*x+3*x+y -> 5*x+y, for
1066 void expairseq::combine_same_terms_sorted_seq(void)
1068 bool needs_further_processing = false;
1071 epvector::iterator itin1 = seq.begin();
1072 epvector::iterator itin2 = itin1+1;
1073 epvector::iterator itout = itin1;
1074 epvector::iterator last = seq.end();
1075 // must_copy will be set to true the first time some combination is
1076 // possible from then on the sequence has changed and must be compacted
1077 bool must_copy = false;
1078 while (itin2!=last) {
1079 if (itin1->rest.compare(itin2->rest)==0) {
1080 itin1->coeff = ex_to<numeric>(itin1->coeff).
1081 add_dyn(ex_to<numeric>(itin2->coeff));
1082 if (expair_needs_further_processing(itin1))
1083 needs_further_processing = true;
1086 if (!ex_to<numeric>(itin1->coeff).is_zero()) {
1095 if (!ex_to<numeric>(itin1->coeff).is_zero()) {
1101 seq.erase(itout,last);
1104 if (needs_further_processing) {
1107 construct_from_epvector(v);
1111 #if EXPAIRSEQ_USE_HASHTAB
1113 unsigned expairseq::calc_hashtabsize(unsigned sz) const
1116 unsigned nearest_power_of_2 = 1 << log2(sz);
1117 // if (nearest_power_of_2 < maxhashtabsize/hashtabfactor) {
1118 // size = nearest_power_of_2*hashtabfactor;
1119 size = nearest_power_of_2/hashtabfactor;
1120 if (size<minhashtabsize)
1122 GINAC_ASSERT(hashtabsize<=0x8000000U); // really max size due to 31 bit hashing
1123 // hashtabsize must be a power of 2
1124 GINAC_ASSERT((1U << log2(size))==size);
1128 unsigned expairseq::calc_hashindex(const ex &e) const
1130 // calculate hashindex
1131 unsigned hash = e.gethash();
1133 if (is_a_numeric_hash(hash)) {
1134 hashindex = hashmask;
1136 hashindex = hash &hashmask;
1137 // last hashtab entry is reserved for numerics
1138 if (hashindex==hashmask) hashindex = 0;
1140 GINAC_ASSERT(hashindex>=0);
1141 GINAC_ASSERT((hashindex<hashtabsize)||(hashtabsize==0));
1145 void expairseq::shrink_hashtab(void)
1147 unsigned new_hashtabsize;
1148 while (hashtabsize!=(new_hashtabsize=calc_hashtabsize(seq.size()))) {
1149 GINAC_ASSERT(new_hashtabsize<hashtabsize);
1150 if (new_hashtabsize==0) {
1157 // shrink by a factor of 2
1158 unsigned half_hashtabsize = hashtabsize/2;
1159 for (unsigned i=0; i<half_hashtabsize-1; ++i)
1160 hashtab[i].merge(hashtab[i+half_hashtabsize],epp_is_less());
1161 // special treatment for numeric hashes
1162 hashtab[0].merge(hashtab[half_hashtabsize-1],epp_is_less());
1163 hashtab[half_hashtabsize-1] = hashtab[hashtabsize-1];
1164 hashtab.resize(half_hashtabsize);
1165 hashtabsize = half_hashtabsize;
1166 hashmask = hashtabsize-1;
1170 void expairseq::remove_hashtab_entry(epvector::const_iterator element)
1173 return; // nothing to do
1175 // calculate hashindex of element to be deleted
1176 unsigned hashindex = calc_hashindex((*element).rest);
1178 // find it in hashtab and remove it
1179 epplist &eppl = hashtab[hashindex];
1180 epplist::iterator epplit = eppl.begin();
1181 bool erased = false;
1182 while (epplit!=eppl.end()) {
1183 if (*epplit == element) {
1191 std::cout << "tried to erase " << element-seq.begin() << std::endl;
1192 std::cout << "size " << seq.end()-seq.begin() << std::endl;
1194 unsigned hashindex = calc_hashindex(element->rest);
1195 epplist &eppl = hashtab[hashindex];
1196 epplist::iterator epplit = eppl.begin();
1197 bool erased = false;
1198 while (epplit!=eppl.end()) {
1199 if (*epplit == element) {
1206 GINAC_ASSERT(erased);
1208 GINAC_ASSERT(erased);
1211 void expairseq::move_hashtab_entry(epvector::const_iterator oldpos,
1212 epvector::iterator newpos)
1214 GINAC_ASSERT(hashtabsize!=0);
1216 // calculate hashindex of element which was moved
1217 unsigned hashindex=calc_hashindex((*newpos).rest);
1219 // find it in hashtab and modify it
1220 epplist &eppl = hashtab[hashindex];
1221 epplist::iterator epplit = eppl.begin();
1222 while (epplit!=eppl.end()) {
1223 if (*epplit == oldpos) {
1229 GINAC_ASSERT(epplit!=eppl.end());
1232 void expairseq::sorted_insert(epplist &eppl, epvector::const_iterator elem)
1234 epplist::const_iterator current = eppl.begin();
1235 while ((current!=eppl.end()) && ((*current)->is_less(*elem))) {
1238 eppl.insert(current,elem);
1241 void expairseq::build_hashtab_and_combine(epvector::iterator &first_numeric,
1242 epvector::iterator &last_non_zero,
1243 std::vector<bool> &touched,
1244 unsigned &number_of_zeroes)
1246 epp current = seq.begin();
1248 while (current!=first_numeric) {
1249 if (is_ex_exactly_of_type(current->rest,numeric)) {
1251 iter_swap(current,first_numeric);
1253 // calculate hashindex
1254 unsigned currenthashindex = calc_hashindex(current->rest);
1256 // test if there is already a matching expair in the hashtab-list
1257 epplist &eppl=hashtab[currenthashindex];
1258 epplist::iterator epplit = eppl.begin();
1259 while (epplit!=eppl.end()) {
1260 if (current->rest.is_equal((*epplit)->rest))
1264 if (epplit==eppl.end()) {
1265 // no matching expair found, append this to end of list
1266 sorted_insert(eppl,current);
1269 // epplit points to a matching expair, combine it with current
1270 (*epplit)->coeff = ex_to<numeric>((*epplit)->coeff).
1271 add_dyn(ex_to<numeric>(current->coeff));
1273 // move obsolete current expair to end by swapping with last_non_zero element
1274 // if this was a numeric, it is swapped with the expair before first_numeric
1275 iter_swap(current,last_non_zero);
1277 if (first_numeric!=last_non_zero) iter_swap(first_numeric,current);
1280 // test if combined term has coeff 0 and can be removed is done later
1281 touched[(*epplit)-seq.begin()] = true;
1287 void expairseq::drop_coeff_0_terms(epvector::iterator &first_numeric,
1288 epvector::iterator &last_non_zero,
1289 std::vector<bool> &touched,
1290 unsigned &number_of_zeroes)
1292 // move terms with coeff 0 to end and remove them from hashtab
1293 // check only those elements which have been touched
1294 epp current = seq.begin();
1296 while (current!=first_numeric) {
1300 } else if (!ex_to<numeric>((*current).coeff).is_zero()) {
1304 remove_hashtab_entry(current);
1306 // move element to the end, unless it is already at the end
1307 if (current!=last_non_zero) {
1308 iter_swap(current,last_non_zero);
1310 bool numeric_swapped = first_numeric!=last_non_zero;
1311 if (numeric_swapped)
1312 iter_swap(first_numeric,current);
1313 epvector::iterator changed_entry;
1315 if (numeric_swapped)
1316 changed_entry = first_numeric;
1318 changed_entry = last_non_zero;
1323 if (first_numeric!=current) {
1325 // change entry in hashtab which referred to first_numeric or last_non_zero to current
1326 move_hashtab_entry(changed_entry,current);
1327 touched[current-seq.begin()] = touched[changed_entry-seq.begin()];
1336 GINAC_ASSERT(i==current-seq.begin());
1339 /** True if one of the coeffs vanishes, otherwise false.
1340 * This would be an invariant violation, so this should only be used for
1341 * debugging purposes. */
1342 bool expairseq::has_coeff_0(void) const
1344 epvector::const_iterator i = seq.begin(), end = seq.end();
1346 if (i->coeff.is_zero())
1353 void expairseq::add_numerics_to_hashtab(epvector::iterator first_numeric,
1354 epvector::const_iterator last_non_zero)
1356 if (first_numeric == seq.end()) return; // no numerics
1358 epvector::const_iterator current = first_numeric, last = last_non_zero + 1;
1359 while (current != last) {
1360 sorted_insert(hashtab[hashmask], current);
1365 void expairseq::combine_same_terms(void)
1367 // combine same terms, drop term with coeff 0, move numerics to end
1369 // calculate size of hashtab
1370 hashtabsize = calc_hashtabsize(seq.size());
1372 // hashtabsize is a power of 2
1373 hashmask = hashtabsize-1;
1377 hashtab.resize(hashtabsize);
1379 if (hashtabsize==0) {
1381 combine_same_terms_sorted_seq();
1382 GINAC_ASSERT(!has_coeff_0());
1386 // iterate through seq, move numerics to end,
1387 // fill hashtab and combine same terms
1388 epvector::iterator first_numeric = seq.end();
1389 epvector::iterator last_non_zero = seq.end()-1;
1391 unsigned num = seq.size();
1392 std::vector<bool> touched(num);
1394 unsigned number_of_zeroes = 0;
1396 GINAC_ASSERT(!has_coeff_0());
1397 build_hashtab_and_combine(first_numeric,last_non_zero,touched,number_of_zeroes);
1399 // there should not be any terms with coeff 0 from the beginning,
1400 // so it should be safe to skip this step
1401 if (number_of_zeroes!=0) {
1402 drop_coeff_0_terms(first_numeric,last_non_zero,touched,number_of_zeroes);
1405 add_numerics_to_hashtab(first_numeric,last_non_zero);
1407 // pop zero elements
1408 for (unsigned i=0; i<number_of_zeroes; ++i) {
1412 // shrink hashtabsize to calculated value
1413 GINAC_ASSERT(!has_coeff_0());
1417 GINAC_ASSERT(!has_coeff_0());
1420 #endif // EXPAIRSEQ_USE_HASHTAB
1422 /** Check if this expairseq is in sorted (canonical) form. Useful mainly for
1423 * debugging or in assertions since being sorted is an invariance. */
1424 bool expairseq::is_canonical() const
1426 if (seq.size() <= 1)
1429 #if EXPAIRSEQ_USE_HASHTAB
1430 if (hashtabsize > 0) return 1; // not canoncalized
1431 #endif // EXPAIRSEQ_USE_HASHTAB
1433 epvector::const_iterator it = seq.begin(), itend = seq.end();
1434 epvector::const_iterator it_last = it;
1435 for (++it; it!=itend; it_last=it, ++it) {
1436 if (!(it_last->is_less(*it) || it_last->is_equal(*it))) {
1437 if (!is_ex_exactly_of_type(it_last->rest,numeric) ||
1438 !is_ex_exactly_of_type(it->rest,numeric)) {
1439 // double test makes it easier to set a breakpoint...
1440 if (!is_ex_exactly_of_type(it_last->rest,numeric) ||
1441 !is_ex_exactly_of_type(it->rest,numeric)) {
1442 printpair(std::clog, *it_last, 0);
1444 printpair(std::clog, *it, 0);
1446 std::clog << "pair1:" << std::endl;
1447 it_last->rest.print(print_tree(std::clog));
1448 it_last->coeff.print(print_tree(std::clog));
1449 std::clog << "pair2:" << std::endl;
1450 it->rest.print(print_tree(std::clog));
1451 it->coeff.print(print_tree(std::clog));
1461 /** Member-wise expand the expairs in this sequence.
1463 * @see expairseq::expand()
1464 * @return pointer to epvector containing expanded pairs or zero pointer,
1465 * if no members were changed. */
1466 epvector * expairseq::expandchildren(unsigned options) const
1468 epvector::const_iterator last = seq.end();
1469 epvector::const_iterator cit = seq.begin();
1471 const ex &expanded_ex = cit->rest.expand(options);
1472 if (!are_ex_trivially_equal(cit->rest,expanded_ex)) {
1474 // something changed, copy seq, eval and return it
1475 epvector *s = new epvector;
1476 s->reserve(seq.size());
1478 // copy parts of seq which are known not to have changed
1479 epvector::const_iterator cit2 = seq.begin();
1481 s->push_back(*cit2);
1484 // copy first changed element
1485 s->push_back(combine_ex_with_coeff_to_pair(expanded_ex,
1489 while (cit2!=last) {
1490 s->push_back(combine_ex_with_coeff_to_pair(cit2->rest.expand(options),
1499 return 0; // signalling nothing has changed
1503 /** Member-wise evaluate the expairs in this sequence.
1505 * @see expairseq::eval()
1506 * @return pointer to epvector containing evaluated pairs or zero pointer,
1507 * if no members were changed. */
1508 epvector * expairseq::evalchildren(int level) const
1510 // returns a NULL pointer if nothing had to be evaluated
1511 // returns a pointer to a newly created epvector otherwise
1512 // (which has to be deleted somewhere else)
1517 if (level == -max_recursion_level)
1518 throw(std::runtime_error("max recursion level reached"));
1521 epvector::const_iterator last = seq.end();
1522 epvector::const_iterator cit = seq.begin();
1524 const ex &evaled_ex = cit->rest.eval(level);
1525 if (!are_ex_trivially_equal(cit->rest,evaled_ex)) {
1527 // something changed, copy seq, eval and return it
1528 epvector *s = new epvector;
1529 s->reserve(seq.size());
1531 // copy parts of seq which are known not to have changed
1532 epvector::const_iterator cit2=seq.begin();
1534 s->push_back(*cit2);
1537 // copy first changed element
1538 s->push_back(combine_ex_with_coeff_to_pair(evaled_ex,
1542 while (cit2!=last) {
1543 s->push_back(combine_ex_with_coeff_to_pair(cit2->rest.eval(level),
1552 return 0; // signalling nothing has changed
1556 /** Member-wise substitute in this sequence.
1558 * @see expairseq::subs()
1559 * @return pointer to epvector containing pairs after application of subs,
1560 * or NULL pointer if no members were changed. */
1561 epvector * expairseq::subschildren(const lst &ls, const lst &lr, bool no_pattern) const
1563 GINAC_ASSERT(ls.nops()==lr.nops());
1565 // The substitution is "complex" when any of the objects to be substituted
1566 // is a product or power. In this case we have to recombine the pairs
1567 // because the numeric coefficients may be part of the search pattern.
1568 bool complex_subs = false;
1569 for (unsigned i=0; i<ls.nops(); ++i)
1570 if (is_ex_exactly_of_type(ls.op(i), mul) || is_ex_exactly_of_type(ls.op(i), power)) {
1571 complex_subs = true;
1577 // Substitute in the recombined pairs
1578 epvector::const_iterator cit = seq.begin(), last = seq.end();
1579 while (cit != last) {
1581 const ex &orig_ex = recombine_pair_to_ex(*cit);
1582 const ex &subsed_ex = orig_ex.subs(ls, lr, no_pattern);
1583 if (!are_ex_trivially_equal(orig_ex, subsed_ex)) {
1585 // Something changed, copy seq, subs and return it
1586 epvector *s = new epvector;
1587 s->reserve(seq.size());
1589 // Copy parts of seq which are known not to have changed
1590 s->insert(s->begin(), seq.begin(), cit);
1592 // Copy first changed element
1593 s->push_back(split_ex_to_pair(subsed_ex));
1597 while (cit != last) {
1598 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit).subs(ls, lr, no_pattern)));
1609 // Substitute only in the "rest" part of the pairs
1610 epvector::const_iterator cit = seq.begin(), last = seq.end();
1611 while (cit != last) {
1613 const ex &subsed_ex = cit->rest.subs(ls, lr, no_pattern);
1614 if (!are_ex_trivially_equal(cit->rest, subsed_ex)) {
1616 // Something changed, copy seq, subs and return it
1617 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(combine_ex_with_coeff_to_pair(subsed_ex, cit->coeff));
1628 while (cit != last) {
1629 s->push_back(combine_ex_with_coeff_to_pair(cit->rest.subs(ls, lr, no_pattern),
1640 // Nothing has changed
1645 // static member variables
1648 #if EXPAIRSEQ_USE_HASHTAB
1649 unsigned expairseq::maxhashtabsize = 0x4000000U;
1650 unsigned expairseq::minhashtabsize = 0x1000U;
1651 unsigned expairseq::hashtabfactor = 1;
1652 #endif // EXPAIRSEQ_USE_HASHTAB
1654 } // namespace GiNaC