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"
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)
68 debugmsg("expairseq copy ctor",LOGLEVEL_CONSTRUCT);
72 const expairseq &expairseq::operator=(const expairseq &other)
74 debugmsg("expairseq operator=",LOGLEVEL_ASSIGNMENT);
84 /** For use by copy ctor and assignment operator. */
85 void expairseq::copy(const expairseq &other)
87 inherited::copy(other);
89 overall_coeff = other.overall_coeff;
90 #if EXPAIRSEQ_USE_HASHTAB
92 hashtabsize = other.hashtabsize;
94 hashmask = other.hashmask;
95 hashtab.resize(hashtabsize);
96 epvector::const_iterator osb = other.seq.begin();
97 for (unsigned i=0; i<hashtabsize; ++i) {
99 for (epplist::const_iterator cit=other.hashtab[i].begin();
100 cit!=other.hashtab[i].end(); ++cit) {
101 hashtab[i].push_back(seq.begin()+((*cit)-osb));
107 #endif // EXPAIRSEQ_USE_HASHTAB
110 DEFAULT_DESTROY(expairseq)
116 expairseq::expairseq(const ex &lh, const ex &rh) : inherited(TINFO_expairseq)
118 debugmsg("expairseq ctor from ex,ex",LOGLEVEL_CONSTRUCT);
119 construct_from_2_ex(lh,rh);
120 GINAC_ASSERT(is_canonical());
123 expairseq::expairseq(const exvector &v) : inherited(TINFO_expairseq)
125 debugmsg("expairseq ctor from exvector",LOGLEVEL_CONSTRUCT);
126 construct_from_exvector(v);
127 GINAC_ASSERT(is_canonical());
130 expairseq::expairseq(const epvector &v, const ex &oc)
131 : inherited(TINFO_expairseq), overall_coeff(oc)
133 debugmsg("expairseq ctor from epvector,ex",LOGLEVEL_CONSTRUCT);
134 construct_from_epvector(v);
135 GINAC_ASSERT(is_canonical());
138 expairseq::expairseq(epvector *vp, const ex &oc)
139 : inherited(TINFO_expairseq), overall_coeff(oc)
141 debugmsg("expairseq ctor from epvector *,ex",LOGLEVEL_CONSTRUCT);
143 construct_from_epvector(*vp);
145 GINAC_ASSERT(is_canonical());
152 expairseq::expairseq(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
153 #if EXPAIRSEQ_USE_HASHTAB
157 debugmsg("expairseq ctor from archive_node", LOGLEVEL_CONSTRUCT);
158 for (unsigned int i=0; true; i++) {
161 if (n.find_ex("rest", rest, sym_lst, i) && n.find_ex("coeff", coeff, sym_lst, i))
162 seq.push_back(expair(rest, coeff));
166 n.find_ex("overall_coeff", overall_coeff, sym_lst);
169 void expairseq::archive(archive_node &n) const
171 inherited::archive(n);
172 epvector::const_iterator i = seq.begin(), iend = seq.end();
174 n.add_ex("rest", i->rest);
175 n.add_ex("coeff", i->coeff);
178 n.add_ex("overall_coeff", overall_coeff);
181 DEFAULT_UNARCHIVE(expairseq)
184 // functions overriding virtual functions from base classes
189 basic *expairseq::duplicate() const
191 debugmsg("expairseq duplicate",LOGLEVEL_DUPLICATE);
192 return new expairseq(*this);
195 void expairseq::print(const print_context &c, unsigned level) const
197 debugmsg("expairseq print",LOGLEVEL_PRINT);
199 if (is_of_type(c, print_tree)) {
201 unsigned delta_indent = static_cast<const print_tree &>(c).delta_indent;
203 c.s << std::string(level, ' ') << class_name()
204 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
205 << ", nops=" << nops()
207 unsigned num = seq.size();
208 for (unsigned i=0; i<num; ++i) {
209 seq[i].rest.print(c, level + delta_indent);
210 seq[i].coeff.print(c, level + delta_indent);
212 c.s << std::string(level + delta_indent, ' ') << "-----" << std::endl;
214 if (!overall_coeff.is_equal(default_overall_coeff())) {
215 c.s << std::string(level + delta_indent, ' ') << "-----" << std::endl
216 << std::string(level + delta_indent, ' ') << "overall_coeff" << std::endl;
217 overall_coeff.print(c, level + delta_indent);
219 c.s << std::string(level + delta_indent,' ') << "=====" << std::endl;
220 #if EXPAIRSEQ_USE_HASHTAB
221 c.s << std::string(level + delta_indent,' ')
222 << "hashtab size " << hashtabsize << std::endl;
223 if (hashtabsize == 0) return;
225 unsigned count[MAXCOUNT+1];
226 for (int i=0; i<MAXCOUNT+1; ++i)
228 unsigned this_bin_fill;
229 unsigned cum_fill_sq = 0;
230 unsigned cum_fill = 0;
231 for (unsigned i=0; i<hashtabsize; ++i) {
233 if (hashtab[i].size() > 0) {
234 c.s << std::string(level + delta_indent, ' ')
235 << "bin " << i << " with entries ";
236 for (epplist::const_iterator it=hashtab[i].begin();
237 it!=hashtab[i].end(); ++it) {
238 c.s << *it-seq.begin() << " ";
242 cum_fill += this_bin_fill;
243 cum_fill_sq += this_bin_fill*this_bin_fill;
245 if (this_bin_fill<MAXCOUNT)
246 ++count[this_bin_fill];
252 double lambda = (1.0*seq.size()) / hashtabsize;
253 for (int k=0; k<MAXCOUNT; ++k) {
256 double prob = std::pow(lambda,k)/fact * std::exp(-lambda);
258 c.s << std::string(level + delta_indent, ' ') << "bins with " << k << " entries: "
259 << int(1000.0*count[k]/hashtabsize)/10.0 << "% (expected: "
260 << int(prob*1000)/10.0 << ")" << std::endl;
262 c.s << std::string(level + delta_indent, ' ') << "bins with more entries: "
263 << int(1000.0*count[MAXCOUNT]/hashtabsize)/10.0 << "% (expected: "
264 << int((1-cum_prob)*1000)/10.0 << ")" << std::endl;
266 c.s << std::string(level + delta_indent, ' ') << "variance: "
267 << 1.0/hashtabsize*cum_fill_sq-(1.0/hashtabsize*cum_fill)*(1.0/hashtabsize*cum_fill)
269 c.s << std::string(level + delta_indent, ' ') << "average fill: "
270 << (1.0*cum_fill)/hashtabsize
271 << " (should be equal to " << (1.0*seq.size())/hashtabsize << ")" << std::endl;
272 #endif // EXPAIRSEQ_USE_HASHTAB
276 printseq(c, ',', precedence(), level);
281 bool expairseq::info(unsigned inf) const
283 return inherited::info(inf);
286 unsigned expairseq::nops() const
288 if (overall_coeff.is_equal(default_overall_coeff()))
294 ex expairseq::op(int i) const
296 if (unsigned(i)<seq.size())
297 return recombine_pair_to_ex(seq[i]);
298 GINAC_ASSERT(!overall_coeff.is_equal(default_overall_coeff()));
299 return overall_coeff;
302 ex &expairseq::let_op(int i)
304 throw(std::logic_error("let_op not defined for expairseq and derived classes (add,mul,...)"));
307 ex expairseq::map(map_function &f) const
309 epvector *v = new epvector;
310 v->reserve(seq.size());
312 epvector::const_iterator cit = seq.begin(), last = seq.end();
313 while (cit != last) {
314 v->push_back(split_ex_to_pair(f(recombine_pair_to_ex(*cit))));
318 if (overall_coeff.is_equal(default_overall_coeff()))
319 return thisexpairseq(v, default_overall_coeff());
321 return thisexpairseq(v, f(overall_coeff));
324 /** Perform coefficient-wise automatic term rewriting rules in this class. */
325 ex expairseq::eval(int level) const
327 if ((level==1) && (flags &status_flags::evaluated))
330 epvector *vp = evalchildren(level);
334 return (new expairseq(vp,overall_coeff))->setflag(status_flags::dynallocated | status_flags::evaluated);
337 bool expairseq::match(const ex & pattern, lst & repl_lst) const
339 // This differs from basic::match() because we want "a+b+c+d" to
340 // match "d+*+b" with "*" being "a+c", and we want to honor commutativity
342 if (this->tinfo() == ex_to<basic>(pattern).tinfo()) {
344 // Check whether global wildcard (one that matches the "rest of the
345 // expression", like "*" above) is present
346 bool has_global_wildcard = false;
348 for (unsigned int i=0; i<pattern.nops(); i++) {
349 if (is_ex_exactly_of_type(pattern.op(i), wildcard)) {
350 has_global_wildcard = true;
351 global_wildcard = pattern.op(i);
356 // Unfortunately, this is an O(N^2) operation because we can't
357 // sort the pattern in a useful way...
362 for (unsigned i=0; i<nops(); i++)
363 ops.push_back(op(i));
365 // Now, for every term of the pattern, look for a matching term in
366 // the expression and remove the match
367 for (unsigned i=0; i<pattern.nops(); i++) {
368 ex p = pattern.op(i);
369 if (has_global_wildcard && p.is_equal(global_wildcard))
371 exvector::iterator it = ops.begin(), itend = ops.end();
372 while (it != itend) {
373 if (it->match(p, repl_lst)) {
379 return false; // no match found
383 if (has_global_wildcard) {
385 // Assign all the remaining terms to the global wildcard (unless
386 // it has already been matched before, in which case the matches
388 unsigned num = ops.size();
389 epvector *vp = new epvector();
391 for (unsigned i=0; i<num; i++)
392 vp->push_back(split_ex_to_pair(ops[i]));
393 ex rest = thisexpairseq(vp, default_overall_coeff());
394 for (unsigned i=0; i<repl_lst.nops(); i++) {
395 if (repl_lst.op(i).op(0).is_equal(global_wildcard))
396 return rest.is_equal(repl_lst.op(i).op(1));
398 repl_lst.append(global_wildcard == rest);
403 // No global wildcard, then the match fails if there are any
404 // unmatched terms left
408 return inherited::match(pattern, repl_lst);
411 ex expairseq::subs(const lst &ls, const lst &lr, bool no_pattern) const
413 epvector *vp = subschildren(ls, lr, no_pattern);
415 return ex_to<basic>(thisexpairseq(vp, overall_coeff)).basic::subs(ls, lr, no_pattern);
417 return basic::subs(ls, lr, no_pattern);
422 int expairseq::compare_same_type(const basic &other) const
424 GINAC_ASSERT(is_a<expairseq>(other));
425 const expairseq &o = static_cast<const expairseq &>(other);
429 // compare number of elements
430 if (seq.size() != o.seq.size())
431 return (seq.size()<o.seq.size()) ? -1 : 1;
433 // compare overall_coeff
434 cmpval = overall_coeff.compare(o.overall_coeff);
438 #if EXPAIRSEQ_USE_HASHTAB
439 GINAC_ASSERT(hashtabsize==o.hashtabsize);
440 if (hashtabsize==0) {
441 #endif // EXPAIRSEQ_USE_HASHTAB
442 epvector::const_iterator cit1 = seq.begin();
443 epvector::const_iterator cit2 = o.seq.begin();
444 epvector::const_iterator last1 = seq.end();
445 epvector::const_iterator last2 = o.seq.end();
447 for (; (cit1!=last1)&&(cit2!=last2); ++cit1, ++cit2) {
448 cmpval = (*cit1).compare(*cit2);
449 if (cmpval!=0) return cmpval;
452 GINAC_ASSERT(cit1==last1);
453 GINAC_ASSERT(cit2==last2);
456 #if EXPAIRSEQ_USE_HASHTAB
459 // compare number of elements in each hashtab entry
460 for (unsigned i=0; i<hashtabsize; ++i) {
461 unsigned cursize=hashtab[i].size();
462 if (cursize != o.hashtab[i].size())
463 return (cursize < o.hashtab[i].size()) ? -1 : 1;
466 // compare individual (sorted) hashtab entries
467 for (unsigned i=0; i<hashtabsize; ++i) {
468 unsigned sz = hashtab[i].size();
470 const epplist &eppl1 = hashtab[i];
471 const epplist &eppl2 = o.hashtab[i];
472 epplist::const_iterator it1 = eppl1.begin();
473 epplist::const_iterator it2 = eppl2.begin();
474 while (it1!=eppl1.end()) {
475 cmpval = (*(*it1)).compare(*(*it2));
485 #endif // EXPAIRSEQ_USE_HASHTAB
488 bool expairseq::is_equal_same_type(const basic &other) const
490 const expairseq &o = static_cast<const expairseq &>(other);
492 // compare number of elements
493 if (seq.size()!=o.seq.size())
496 // compare overall_coeff
497 if (!overall_coeff.is_equal(o.overall_coeff))
500 #if EXPAIRSEQ_USE_HASHTAB
501 // compare number of elements in each hashtab entry
502 if (hashtabsize!=o.hashtabsize) {
503 std::cout << "this:" << std::endl;
504 print(print_tree(std::cout));
505 std::cout << "other:" << std::endl;
506 other.print(print_tree(std::cout));
509 GINAC_ASSERT(hashtabsize==o.hashtabsize);
511 if (hashtabsize==0) {
512 #endif // EXPAIRSEQ_USE_HASHTAB
513 epvector::const_iterator cit1 = seq.begin();
514 epvector::const_iterator cit2 = o.seq.begin();
515 epvector::const_iterator last1 = seq.end();
517 while (cit1!=last1) {
518 if (!(*cit1).is_equal(*cit2)) return false;
524 #if EXPAIRSEQ_USE_HASHTAB
527 for (unsigned i=0; i<hashtabsize; ++i) {
528 if (hashtab[i].size() != o.hashtab[i].size())
532 // compare individual sorted hashtab entries
533 for (unsigned i=0; i<hashtabsize; ++i) {
534 unsigned sz = hashtab[i].size();
536 const epplist &eppl1 = hashtab[i];
537 const epplist &eppl2 = o.hashtab[i];
538 epplist::const_iterator it1 = eppl1.begin();
539 epplist::const_iterator it2 = eppl2.begin();
540 while (it1!=eppl1.end()) {
541 if (!(*(*it1)).is_equal(*(*it2))) return false;
549 #endif // EXPAIRSEQ_USE_HASHTAB
552 unsigned expairseq::return_type(void) const
554 return return_types::noncommutative_composite;
557 unsigned expairseq::calchash(void) const
559 unsigned v = golden_ratio_hash(this->tinfo());
560 epvector::const_iterator i = seq.begin(), end = seq.end();
562 #if !EXPAIRSEQ_USE_HASHTAB
563 v = rotate_left_31(v); // rotation would spoil commutativity
564 #endif // EXPAIRSEQ_USE_HASHTAB
565 v ^= i->rest.gethash();
566 #if !EXPAIRSEQ_USE_HASHTAB
567 v = rotate_left_31(v);
568 v ^= i->coeff.gethash();
569 #endif // EXPAIRSEQ_USE_HASHTAB
573 v ^= overall_coeff.gethash();
576 // store calculated hash value only if object is already evaluated
577 if (flags &status_flags::evaluated) {
578 setflag(status_flags::hash_calculated);
585 ex expairseq::expand(unsigned options) const
587 epvector *vp = expandchildren(options);
589 // The terms have not changed, so it is safe to declare this expanded
590 return (options == 0) ? setflag(status_flags::expanded) : *this;
592 return thisexpairseq(vp, overall_coeff);
596 // new virtual functions which can be overridden by derived classes
601 /** Create an object of this type.
602 * This method works similar to a constructor. It is useful because expairseq
603 * has (at least) two possible different semantics but we want to inherit
604 * methods thus avoiding code duplication. Sometimes a method in expairseq
605 * has to create a new one of the same semantics, which cannot be done by a
606 * ctor because the name (add, mul,...) is unknown on the expaiseq level. In
607 * order for this trick to work a derived class must of course override this
609 ex expairseq::thisexpairseq(const epvector &v, const ex &oc) const
611 return expairseq(v,oc);
614 ex expairseq::thisexpairseq(epvector *vp, const ex &oc) const
616 return expairseq(vp,oc);
619 void expairseq::printpair(const print_context & c, const expair & p, unsigned upper_precedence) const
622 p.rest.print(c, precedence());
624 p.coeff.print(c, precedence());
628 void expairseq::printseq(const print_context & c, char delim,
629 unsigned this_precedence,
630 unsigned upper_precedence) const
632 if (this_precedence <= upper_precedence)
634 epvector::const_iterator it, it_last = seq.end() - 1;
635 for (it=seq.begin(); it!=it_last; ++it) {
636 printpair(c, *it, this_precedence);
639 printpair(c, *it, this_precedence);
640 if (!overall_coeff.is_equal(default_overall_coeff())) {
642 overall_coeff.print(c, this_precedence);
645 if (this_precedence <= upper_precedence)
650 /** Form an expair from an ex, using the corresponding semantics.
651 * @see expairseq::recombine_pair_to_ex() */
652 expair expairseq::split_ex_to_pair(const ex &e) const
654 return expair(e,_ex1);
658 expair expairseq::combine_ex_with_coeff_to_pair(const ex &e,
661 GINAC_ASSERT(is_exactly_a<numeric>(c));
667 expair expairseq::combine_pair_with_coeff_to_pair(const expair &p,
670 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
671 GINAC_ASSERT(is_exactly_a<numeric>(c));
673 return expair(p.rest,ex_to<numeric>(p.coeff).mul_dyn(ex_to<numeric>(c)));
677 /** Form an ex out of an expair, using the corresponding semantics.
678 * @see expairseq::split_ex_to_pair() */
679 ex expairseq::recombine_pair_to_ex(const expair &p) const
681 return lst(p.rest,p.coeff);
684 bool expairseq::expair_needs_further_processing(epp it)
686 #if EXPAIRSEQ_USE_HASHTAB
687 //# error "FIXME: expair_needs_further_processing not yet implemented for hashtabs, sorry. A.F."
688 #endif // EXPAIRSEQ_USE_HASHTAB
692 ex expairseq::default_overall_coeff(void) const
697 void expairseq::combine_overall_coeff(const ex &c)
699 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
700 GINAC_ASSERT(is_exactly_a<numeric>(c));
701 overall_coeff = ex_to<numeric>(overall_coeff).add_dyn(ex_to<numeric>(c));
704 void expairseq::combine_overall_coeff(const ex &c1, const ex &c2)
706 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
707 GINAC_ASSERT(is_exactly_a<numeric>(c1));
708 GINAC_ASSERT(is_exactly_a<numeric>(c2));
709 overall_coeff = ex_to<numeric>(overall_coeff).
710 add_dyn(ex_to<numeric>(c1).mul(ex_to<numeric>(c2)));
713 bool expairseq::can_make_flat(const expair &p) const
720 // non-virtual functions in this class
723 void expairseq::construct_from_2_ex_via_exvector(const ex &lh, const ex &rh)
729 construct_from_exvector(v);
730 #if EXPAIRSEQ_USE_HASHTAB
731 GINAC_ASSERT((hashtabsize==0)||(hashtabsize>=minhashtabsize));
732 GINAC_ASSERT(hashtabsize==calc_hashtabsize(seq.size()));
733 #endif // EXPAIRSEQ_USE_HASHTAB
736 void expairseq::construct_from_2_ex(const ex &lh, const ex &rh)
738 if (ex_to<basic>(lh).tinfo()==this->tinfo()) {
739 if (ex_to<basic>(rh).tinfo()==this->tinfo()) {
740 #if EXPAIRSEQ_USE_HASHTAB
741 unsigned totalsize = ex_to<expairseq>(lh).seq.size() +
742 ex_to<expairseq>(rh).seq.size();
743 if (calc_hashtabsize(totalsize)!=0) {
744 construct_from_2_ex_via_exvector(lh,rh);
746 #endif // EXPAIRSEQ_USE_HASHTAB
747 construct_from_2_expairseq(ex_to<expairseq>(lh),
748 ex_to<expairseq>(rh));
749 #if EXPAIRSEQ_USE_HASHTAB
751 #endif // EXPAIRSEQ_USE_HASHTAB
754 #if EXPAIRSEQ_USE_HASHTAB
755 unsigned totalsize = ex_to<expairseq>(lh).seq.size()+1;
756 if (calc_hashtabsize(totalsize)!=0) {
757 construct_from_2_ex_via_exvector(lh, rh);
759 #endif // EXPAIRSEQ_USE_HASHTAB
760 construct_from_expairseq_ex(ex_to<expairseq>(lh), rh);
761 #if EXPAIRSEQ_USE_HASHTAB
763 #endif // EXPAIRSEQ_USE_HASHTAB
766 } else if (ex_to<basic>(rh).tinfo()==this->tinfo()) {
767 #if EXPAIRSEQ_USE_HASHTAB
768 unsigned totalsize=ex_to<expairseq>(rh).seq.size()+1;
769 if (calc_hashtabsize(totalsize)!=0) {
770 construct_from_2_ex_via_exvector(lh,rh);
772 #endif // EXPAIRSEQ_USE_HASHTAB
773 construct_from_expairseq_ex(ex_to<expairseq>(rh),lh);
774 #if EXPAIRSEQ_USE_HASHTAB
776 #endif // EXPAIRSEQ_USE_HASHTAB
780 #if EXPAIRSEQ_USE_HASHTAB
781 if (calc_hashtabsize(2)!=0) {
782 construct_from_2_ex_via_exvector(lh,rh);
786 #endif // EXPAIRSEQ_USE_HASHTAB
788 if (is_ex_exactly_of_type(lh,numeric)) {
789 if (is_ex_exactly_of_type(rh,numeric)) {
790 combine_overall_coeff(lh);
791 combine_overall_coeff(rh);
793 combine_overall_coeff(lh);
794 seq.push_back(split_ex_to_pair(rh));
797 if (is_ex_exactly_of_type(rh,numeric)) {
798 combine_overall_coeff(rh);
799 seq.push_back(split_ex_to_pair(lh));
801 expair p1 = split_ex_to_pair(lh);
802 expair p2 = split_ex_to_pair(rh);
804 int cmpval = p1.rest.compare(p2.rest);
806 p1.coeff = ex_to<numeric>(p1.coeff).add_dyn(ex_to<numeric>(p2.coeff));
807 if (!ex_to<numeric>(p1.coeff).is_zero()) {
808 // no further processing is necessary, since this
809 // one element will usually be recombined in eval()
826 void expairseq::construct_from_2_expairseq(const expairseq &s1,
829 combine_overall_coeff(s1.overall_coeff);
830 combine_overall_coeff(s2.overall_coeff);
832 epvector::const_iterator first1 = s1.seq.begin();
833 epvector::const_iterator last1 = s1.seq.end();
834 epvector::const_iterator first2 = s2.seq.begin();
835 epvector::const_iterator last2 = s2.seq.end();
837 seq.reserve(s1.seq.size()+s2.seq.size());
839 bool needs_further_processing=false;
841 while (first1!=last1 && first2!=last2) {
842 int cmpval = (*first1).rest.compare((*first2).rest);
845 const numeric &newcoeff = ex_to<numeric>(first1->coeff).
846 add(ex_to<numeric>(first2->coeff));
847 if (!newcoeff.is_zero()) {
848 seq.push_back(expair(first1->rest,newcoeff));
849 if (expair_needs_further_processing(seq.end()-1)) {
850 needs_further_processing = true;
855 } else if (cmpval<0) {
856 seq.push_back(*first1);
859 seq.push_back(*first2);
864 while (first1!=last1) {
865 seq.push_back(*first1);
868 while (first2!=last2) {
869 seq.push_back(*first2);
873 if (needs_further_processing) {
876 construct_from_epvector(v);
880 void expairseq::construct_from_expairseq_ex(const expairseq &s,
883 combine_overall_coeff(s.overall_coeff);
884 if (is_ex_exactly_of_type(e,numeric)) {
885 combine_overall_coeff(e);
890 epvector::const_iterator first = s.seq.begin();
891 epvector::const_iterator last = s.seq.end();
892 expair p = split_ex_to_pair(e);
894 seq.reserve(s.seq.size()+1);
895 bool p_pushed = false;
897 bool needs_further_processing=false;
899 // merge p into s.seq
900 while (first!=last) {
901 int cmpval = (*first).rest.compare(p.rest);
904 const numeric &newcoeff = ex_to<numeric>(first->coeff).
905 add(ex_to<numeric>(p.coeff));
906 if (!newcoeff.is_zero()) {
907 seq.push_back(expair(first->rest,newcoeff));
908 if (expair_needs_further_processing(seq.end()-1))
909 needs_further_processing = true;
914 } else if (cmpval<0) {
915 seq.push_back(*first);
925 // while loop exited because p was pushed, now push rest of s.seq
926 while (first!=last) {
927 seq.push_back(*first);
931 // while loop exited because s.seq was pushed, now push p
935 if (needs_further_processing) {
938 construct_from_epvector(v);
942 void expairseq::construct_from_exvector(const exvector &v)
944 // simplifications: +(a,+(b,c),d) -> +(a,b,c,d) (associativity)
945 // +(d,b,c,a) -> +(a,b,c,d) (canonicalization)
946 // +(...,x,*(x,c1),*(x,c2)) -> +(...,*(x,1+c1+c2)) (c1, c2 numeric())
947 // (same for (+,*) -> (*,^)
950 #if EXPAIRSEQ_USE_HASHTAB
951 combine_same_terms();
954 combine_same_terms_sorted_seq();
955 #endif // EXPAIRSEQ_USE_HASHTAB
958 void expairseq::construct_from_epvector(const epvector &v)
960 // simplifications: +(a,+(b,c),d) -> +(a,b,c,d) (associativity)
961 // +(d,b,c,a) -> +(a,b,c,d) (canonicalization)
962 // +(...,x,*(x,c1),*(x,c2)) -> +(...,*(x,1+c1+c2)) (c1, c2 numeric())
963 // (same for (+,*) -> (*,^)
966 #if EXPAIRSEQ_USE_HASHTAB
967 combine_same_terms();
970 combine_same_terms_sorted_seq();
971 #endif // EXPAIRSEQ_USE_HASHTAB
974 /** Combine this expairseq with argument exvector.
975 * It cares for associativity as well as for special handling of numerics. */
976 void expairseq::make_flat(const exvector &v)
978 exvector::const_iterator cit;
980 // count number of operands which are of same expairseq derived type
981 // and their cumulative number of operands
986 while (cit!=v.end()) {
987 if (ex_to<basic>(*cit).tinfo()==this->tinfo()) {
989 noperands += ex_to<expairseq>(*cit).seq.size();
994 // reserve seq and coeffseq which will hold all operands
995 seq.reserve(v.size()+noperands-nexpairseqs);
997 // copy elements and split off numerical part
999 while (cit!=v.end()) {
1000 if (ex_to<basic>(*cit).tinfo()==this->tinfo()) {
1001 const expairseq &subseqref = ex_to<expairseq>(*cit);
1002 combine_overall_coeff(subseqref.overall_coeff);
1003 epvector::const_iterator cit_s = subseqref.seq.begin();
1004 while (cit_s!=subseqref.seq.end()) {
1005 seq.push_back(*cit_s);
1009 if (is_ex_exactly_of_type(*cit,numeric))
1010 combine_overall_coeff(*cit);
1012 seq.push_back(split_ex_to_pair(*cit));
1018 /** Combine this expairseq with argument epvector.
1019 * It cares for associativity as well as for special handling of numerics. */
1020 void expairseq::make_flat(const epvector &v)
1022 epvector::const_iterator cit;
1024 // count number of operands which are of same expairseq derived type
1025 // and their cumulative number of operands
1026 int nexpairseqs = 0;
1030 while (cit!=v.end()) {
1031 if (ex_to<basic>(cit->rest).tinfo()==this->tinfo()) {
1033 noperands += ex_to<expairseq>(cit->rest).seq.size();
1038 // reserve seq and coeffseq which will hold all operands
1039 seq.reserve(v.size()+noperands-nexpairseqs);
1041 // copy elements and split off numerical part
1043 while (cit!=v.end()) {
1044 if (ex_to<basic>(cit->rest).tinfo()==this->tinfo() &&
1045 this->can_make_flat(*cit)) {
1046 const expairseq &subseqref = ex_to<expairseq>(cit->rest);
1047 combine_overall_coeff(ex_to<numeric>(subseqref.overall_coeff),
1048 ex_to<numeric>(cit->coeff));
1049 epvector::const_iterator cit_s = subseqref.seq.begin();
1050 while (cit_s!=subseqref.seq.end()) {
1051 seq.push_back(expair(cit_s->rest,
1052 ex_to<numeric>(cit_s->coeff).mul_dyn(ex_to<numeric>(cit->coeff))));
1053 //seq.push_back(combine_pair_with_coeff_to_pair(*cit_s,
1058 if (cit->is_canonical_numeric())
1059 combine_overall_coeff(cit->rest);
1061 seq.push_back(*cit);
1067 /** Brings this expairseq into a sorted (canonical) form. */
1068 void expairseq::canonicalize(void)
1070 sort(seq.begin(), seq.end(), expair_is_less());
1074 /** Compact a presorted expairseq by combining all matching expairs to one
1075 * each. On an add object, this is responsible for 2*x+3*x+y -> 5*x+y, for
1077 void expairseq::combine_same_terms_sorted_seq(void)
1079 bool needs_further_processing = false;
1082 epvector::iterator itin1 = seq.begin();
1083 epvector::iterator itin2 = itin1+1;
1084 epvector::iterator itout = itin1;
1085 epvector::iterator last = seq.end();
1086 // must_copy will be set to true the first time some combination is
1087 // possible from then on the sequence has changed and must be compacted
1088 bool must_copy = false;
1089 while (itin2!=last) {
1090 if (itin1->rest.compare(itin2->rest)==0) {
1091 itin1->coeff = ex_to<numeric>(itin1->coeff).
1092 add_dyn(ex_to<numeric>(itin2->coeff));
1093 if (expair_needs_further_processing(itin1))
1094 needs_further_processing = true;
1097 if (!ex_to<numeric>(itin1->coeff).is_zero()) {
1106 if (!ex_to<numeric>(itin1->coeff).is_zero()) {
1112 seq.erase(itout,last);
1115 if (needs_further_processing) {
1118 construct_from_epvector(v);
1122 #if EXPAIRSEQ_USE_HASHTAB
1124 unsigned expairseq::calc_hashtabsize(unsigned sz) const
1127 unsigned nearest_power_of_2 = 1 << log2(sz);
1128 // if (nearest_power_of_2 < maxhashtabsize/hashtabfactor) {
1129 // size = nearest_power_of_2*hashtabfactor;
1130 size = nearest_power_of_2/hashtabfactor;
1131 if (size<minhashtabsize)
1133 GINAC_ASSERT(hashtabsize<=0x8000000U); // really max size due to 31 bit hashing
1134 // hashtabsize must be a power of 2
1135 GINAC_ASSERT((1U << log2(size))==size);
1139 unsigned expairseq::calc_hashindex(const ex &e) const
1141 // calculate hashindex
1142 unsigned hash = e.gethash();
1144 if (is_a_numeric_hash(hash)) {
1145 hashindex = hashmask;
1147 hashindex = hash &hashmask;
1148 // last hashtab entry is reserved for numerics
1149 if (hashindex==hashmask) hashindex = 0;
1151 GINAC_ASSERT(hashindex>=0);
1152 GINAC_ASSERT((hashindex<hashtabsize)||(hashtabsize==0));
1156 void expairseq::shrink_hashtab(void)
1158 unsigned new_hashtabsize;
1159 while (hashtabsize!=(new_hashtabsize=calc_hashtabsize(seq.size()))) {
1160 GINAC_ASSERT(new_hashtabsize<hashtabsize);
1161 if (new_hashtabsize==0) {
1168 // shrink by a factor of 2
1169 unsigned half_hashtabsize = hashtabsize/2;
1170 for (unsigned i=0; i<half_hashtabsize-1; ++i)
1171 hashtab[i].merge(hashtab[i+half_hashtabsize],epp_is_less());
1172 // special treatment for numeric hashes
1173 hashtab[0].merge(hashtab[half_hashtabsize-1],epp_is_less());
1174 hashtab[half_hashtabsize-1] = hashtab[hashtabsize-1];
1175 hashtab.resize(half_hashtabsize);
1176 hashtabsize = half_hashtabsize;
1177 hashmask = hashtabsize-1;
1181 void expairseq::remove_hashtab_entry(epvector::const_iterator element)
1184 return; // nothing to do
1186 // calculate hashindex of element to be deleted
1187 unsigned hashindex = calc_hashindex((*element).rest);
1189 // find it in hashtab and remove it
1190 epplist &eppl = hashtab[hashindex];
1191 epplist::iterator epplit = eppl.begin();
1192 bool erased = false;
1193 while (epplit!=eppl.end()) {
1194 if (*epplit == element) {
1202 std::cout << "tried to erase " << element-seq.begin() << std::endl;
1203 std::cout << "size " << seq.end()-seq.begin() << std::endl;
1205 unsigned hashindex = calc_hashindex(element->rest);
1206 epplist &eppl = hashtab[hashindex];
1207 epplist::iterator epplit = eppl.begin();
1208 bool erased = false;
1209 while (epplit!=eppl.end()) {
1210 if (*epplit == element) {
1217 GINAC_ASSERT(erased);
1219 GINAC_ASSERT(erased);
1222 void expairseq::move_hashtab_entry(epvector::const_iterator oldpos,
1223 epvector::iterator newpos)
1225 GINAC_ASSERT(hashtabsize!=0);
1227 // calculate hashindex of element which was moved
1228 unsigned hashindex=calc_hashindex((*newpos).rest);
1230 // find it in hashtab and modify it
1231 epplist &eppl = hashtab[hashindex];
1232 epplist::iterator epplit = eppl.begin();
1233 while (epplit!=eppl.end()) {
1234 if (*epplit == oldpos) {
1240 GINAC_ASSERT(epplit!=eppl.end());
1243 void expairseq::sorted_insert(epplist &eppl, epvector::const_iterator elem)
1245 epplist::const_iterator current = eppl.begin();
1246 while ((current!=eppl.end()) && ((*current)->is_less(*elem))) {
1249 eppl.insert(current,elem);
1252 void expairseq::build_hashtab_and_combine(epvector::iterator &first_numeric,
1253 epvector::iterator &last_non_zero,
1254 std::vector<bool> &touched,
1255 unsigned &number_of_zeroes)
1257 epp current = seq.begin();
1259 while (current!=first_numeric) {
1260 if (is_ex_exactly_of_type(current->rest,numeric)) {
1262 iter_swap(current,first_numeric);
1264 // calculate hashindex
1265 unsigned currenthashindex = calc_hashindex(current->rest);
1267 // test if there is already a matching expair in the hashtab-list
1268 epplist &eppl=hashtab[currenthashindex];
1269 epplist::iterator epplit = eppl.begin();
1270 while (epplit!=eppl.end()) {
1271 if (current->rest.is_equal((*epplit)->rest))
1275 if (epplit==eppl.end()) {
1276 // no matching expair found, append this to end of list
1277 sorted_insert(eppl,current);
1280 // epplit points to a matching expair, combine it with current
1281 (*epplit)->coeff = ex_to<numeric>((*epplit)->coeff).
1282 add_dyn(ex_to<numeric>(current->coeff));
1284 // move obsolete current expair to end by swapping with last_non_zero element
1285 // if this was a numeric, it is swapped with the expair before first_numeric
1286 iter_swap(current,last_non_zero);
1288 if (first_numeric!=last_non_zero) iter_swap(first_numeric,current);
1291 // test if combined term has coeff 0 and can be removed is done later
1292 touched[(*epplit)-seq.begin()] = true;
1298 void expairseq::drop_coeff_0_terms(epvector::iterator &first_numeric,
1299 epvector::iterator &last_non_zero,
1300 std::vector<bool> &touched,
1301 unsigned &number_of_zeroes)
1303 // move terms with coeff 0 to end and remove them from hashtab
1304 // check only those elements which have been touched
1305 epp current = seq.begin();
1307 while (current!=first_numeric) {
1311 } else if (!ex_to<numeric>((*current).coeff).is_zero()) {
1315 remove_hashtab_entry(current);
1317 // move element to the end, unless it is already at the end
1318 if (current!=last_non_zero) {
1319 iter_swap(current,last_non_zero);
1321 bool numeric_swapped = first_numeric!=last_non_zero;
1322 if (numeric_swapped)
1323 iter_swap(first_numeric,current);
1324 epvector::iterator changed_entry;
1326 if (numeric_swapped)
1327 changed_entry = first_numeric;
1329 changed_entry = last_non_zero;
1334 if (first_numeric!=current) {
1336 // change entry in hashtab which referred to first_numeric or last_non_zero to current
1337 move_hashtab_entry(changed_entry,current);
1338 touched[current-seq.begin()] = touched[changed_entry-seq.begin()];
1347 GINAC_ASSERT(i==current-seq.begin());
1350 /** True if one of the coeffs vanishes, otherwise false.
1351 * This would be an invariant violation, so this should only be used for
1352 * debugging purposes. */
1353 bool expairseq::has_coeff_0(void) const
1355 epvector::const_iterator i = seq.begin(), end = seq.end();
1357 if (i->coeff.is_zero())
1364 void expairseq::add_numerics_to_hashtab(epvector::iterator first_numeric,
1365 epvector::const_iterator last_non_zero)
1367 if (first_numeric == seq.end()) return; // no numerics
1369 epvector::const_iterator current = first_numeric, last = last_non_zero + 1;
1370 while (current != last) {
1371 sorted_insert(hashtab[hashmask], current);
1376 void expairseq::combine_same_terms(void)
1378 // combine same terms, drop term with coeff 0, move numerics to end
1380 // calculate size of hashtab
1381 hashtabsize = calc_hashtabsize(seq.size());
1383 // hashtabsize is a power of 2
1384 hashmask = hashtabsize-1;
1388 hashtab.resize(hashtabsize);
1390 if (hashtabsize==0) {
1392 combine_same_terms_sorted_seq();
1393 GINAC_ASSERT(!has_coeff_0());
1397 // iterate through seq, move numerics to end,
1398 // fill hashtab and combine same terms
1399 epvector::iterator first_numeric = seq.end();
1400 epvector::iterator last_non_zero = seq.end()-1;
1402 unsigned num = seq.size();
1403 std::vector<bool> touched(num);
1405 unsigned number_of_zeroes = 0;
1407 GINAC_ASSERT(!has_coeff_0());
1408 build_hashtab_and_combine(first_numeric,last_non_zero,touched,number_of_zeroes);
1410 // there should not be any terms with coeff 0 from the beginning,
1411 // so it should be safe to skip this step
1412 if (number_of_zeroes!=0) {
1413 drop_coeff_0_terms(first_numeric,last_non_zero,touched,number_of_zeroes);
1416 add_numerics_to_hashtab(first_numeric,last_non_zero);
1418 // pop zero elements
1419 for (unsigned i=0; i<number_of_zeroes; ++i) {
1423 // shrink hashtabsize to calculated value
1424 GINAC_ASSERT(!has_coeff_0());
1428 GINAC_ASSERT(!has_coeff_0());
1431 #endif // EXPAIRSEQ_USE_HASHTAB
1433 /** Check if this expairseq is in sorted (canonical) form. Useful mainly for
1434 * debugging or in assertions since being sorted is an invariance. */
1435 bool expairseq::is_canonical() const
1437 if (seq.size() <= 1)
1440 #if EXPAIRSEQ_USE_HASHTAB
1441 if (hashtabsize > 0) return 1; // not canoncalized
1442 #endif // EXPAIRSEQ_USE_HASHTAB
1444 epvector::const_iterator it = seq.begin(), itend = seq.end();
1445 epvector::const_iterator it_last = it;
1446 for (++it; it!=itend; it_last=it, ++it) {
1447 if (!(it_last->is_less(*it) || it_last->is_equal(*it))) {
1448 if (!is_ex_exactly_of_type(it_last->rest,numeric) ||
1449 !is_ex_exactly_of_type(it->rest,numeric)) {
1450 // double test makes it easier to set a breakpoint...
1451 if (!is_ex_exactly_of_type(it_last->rest,numeric) ||
1452 !is_ex_exactly_of_type(it->rest,numeric)) {
1453 printpair(std::clog, *it_last, 0);
1455 printpair(std::clog, *it, 0);
1457 std::clog << "pair1:" << std::endl;
1458 it_last->rest.print(print_tree(std::clog));
1459 it_last->coeff.print(print_tree(std::clog));
1460 std::clog << "pair2:" << std::endl;
1461 it->rest.print(print_tree(std::clog));
1462 it->coeff.print(print_tree(std::clog));
1472 /** Member-wise expand the expairs in this sequence.
1474 * @see expairseq::expand()
1475 * @return pointer to epvector containing expanded pairs or zero pointer,
1476 * if no members were changed. */
1477 epvector * expairseq::expandchildren(unsigned options) const
1479 epvector::const_iterator last = seq.end();
1480 epvector::const_iterator cit = seq.begin();
1482 const ex &expanded_ex = cit->rest.expand(options);
1483 if (!are_ex_trivially_equal(cit->rest,expanded_ex)) {
1485 // something changed, copy seq, eval and return it
1486 epvector *s = new epvector;
1487 s->reserve(seq.size());
1489 // copy parts of seq which are known not to have changed
1490 epvector::const_iterator cit2 = seq.begin();
1492 s->push_back(*cit2);
1495 // copy first changed element
1496 s->push_back(combine_ex_with_coeff_to_pair(expanded_ex,
1500 while (cit2!=last) {
1501 s->push_back(combine_ex_with_coeff_to_pair(cit2->rest.expand(options),
1510 return 0; // signalling nothing has changed
1514 /** Member-wise evaluate the expairs in this sequence.
1516 * @see expairseq::eval()
1517 * @return pointer to epvector containing evaluated pairs or zero pointer,
1518 * if no members were changed. */
1519 epvector * expairseq::evalchildren(int level) const
1521 // returns a NULL pointer if nothing had to be evaluated
1522 // returns a pointer to a newly created epvector otherwise
1523 // (which has to be deleted somewhere else)
1528 if (level == -max_recursion_level)
1529 throw(std::runtime_error("max recursion level reached"));
1532 epvector::const_iterator last = seq.end();
1533 epvector::const_iterator cit = seq.begin();
1535 const ex &evaled_ex = cit->rest.eval(level);
1536 if (!are_ex_trivially_equal(cit->rest,evaled_ex)) {
1538 // something changed, copy seq, eval and return it
1539 epvector *s = new epvector;
1540 s->reserve(seq.size());
1542 // copy parts of seq which are known not to have changed
1543 epvector::const_iterator cit2=seq.begin();
1545 s->push_back(*cit2);
1548 // copy first changed element
1549 s->push_back(combine_ex_with_coeff_to_pair(evaled_ex,
1553 while (cit2!=last) {
1554 s->push_back(combine_ex_with_coeff_to_pair(cit2->rest.eval(level),
1563 return 0; // signalling nothing has changed
1567 /** Member-wise substitute in this sequence.
1569 * @see expairseq::subs()
1570 * @return pointer to epvector containing pairs after application of subs,
1571 * or NULL pointer if no members were changed. */
1572 epvector * expairseq::subschildren(const lst &ls, const lst &lr, bool no_pattern) const
1574 GINAC_ASSERT(ls.nops()==lr.nops());
1576 // The substitution is "complex" when any of the objects to be substituted
1577 // is a product or power. In this case we have to recombine the pairs
1578 // because the numeric coefficients may be part of the search pattern.
1579 bool complex_subs = false;
1580 for (unsigned i=0; i<ls.nops(); ++i)
1581 if (is_ex_exactly_of_type(ls.op(i), mul) || is_ex_exactly_of_type(ls.op(i), power)) {
1582 complex_subs = true;
1588 // Substitute in the recombined pairs
1589 epvector::const_iterator cit = seq.begin(), last = seq.end();
1590 while (cit != last) {
1592 const ex &orig_ex = recombine_pair_to_ex(*cit);
1593 const ex &subsed_ex = orig_ex.subs(ls, lr, no_pattern);
1594 if (!are_ex_trivially_equal(orig_ex, subsed_ex)) {
1596 // Something changed, copy seq, subs and return it
1597 epvector *s = new epvector;
1598 s->reserve(seq.size());
1600 // Copy parts of seq which are known not to have changed
1601 s->insert(s->begin(), seq.begin(), cit);
1603 // Copy first changed element
1604 s->push_back(split_ex_to_pair(subsed_ex));
1608 while (cit != last) {
1609 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit).subs(ls, lr, no_pattern)));
1620 // Substitute only in the "rest" part of the pairs
1621 epvector::const_iterator cit = seq.begin(), last = seq.end();
1622 while (cit != last) {
1624 const ex &subsed_ex = cit->rest.subs(ls, lr, no_pattern);
1625 if (!are_ex_trivially_equal(cit->rest, subsed_ex)) {
1627 // Something changed, copy seq, subs and return it
1628 epvector *s = new epvector;
1629 s->reserve(seq.size());
1631 // Copy parts of seq which are known not to have changed
1632 s->insert(s->begin(), seq.begin(), cit);
1634 // Copy first changed element
1635 s->push_back(combine_ex_with_coeff_to_pair(subsed_ex, cit->coeff));
1639 while (cit != last) {
1640 s->push_back(combine_ex_with_coeff_to_pair(cit->rest.subs(ls, lr, no_pattern),
1651 // Nothing has changed
1656 // static member variables
1659 #if EXPAIRSEQ_USE_HASHTAB
1660 unsigned expairseq::maxhashtabsize = 0x4000000U;
1661 unsigned expairseq::minhashtabsize = 0x1000U;
1662 unsigned expairseq::hashtabfactor = 1;
1663 #endif // EXPAIRSEQ_USE_HASHTAB
1665 } // namespace GiNaC