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"
29 #include "relational.h"
35 #if EXPAIRSEQ_USE_HASHTAB
37 #endif // EXPAIRSEQ_USE_HASHTAB
41 GINAC_IMPLEMENT_REGISTERED_CLASS_NO_CTORS(expairseq, basic)
50 bool operator()(const epp &lh, const epp &rh) const
52 return (*lh).is_less(*rh);
57 // default ctor, dtor, copy ctor assignment operator and helpers
62 expairseq::expairseq(const expairseq &other)
64 debugmsg("expairseq copy ctor",LOGLEVEL_CONSTRUCT);
68 const expairseq &expairseq::operator=(const expairseq &other)
70 debugmsg("expairseq operator=",LOGLEVEL_ASSIGNMENT);
80 /** For use by copy ctor and assignment operator. */
81 void expairseq::copy(const expairseq &other)
83 inherited::copy(other);
85 overall_coeff = other.overall_coeff;
86 #if EXPAIRSEQ_USE_HASHTAB
88 hashtabsize = other.hashtabsize;
90 hashmask = other.hashmask;
91 hashtab.resize(hashtabsize);
92 epvector::const_iterator osb = other.seq.begin();
93 for (unsigned i=0; i<hashtabsize; ++i) {
95 for (epplist::const_iterator cit=other.hashtab[i].begin();
96 cit!=other.hashtab[i].end(); ++cit) {
97 hashtab[i].push_back(seq.begin()+((*cit)-osb));
103 #endif // EXPAIRSEQ_USE_HASHTAB
106 DEFAULT_DESTROY(expairseq)
112 expairseq::expairseq(const ex &lh, const ex &rh) : inherited(TINFO_expairseq)
114 debugmsg("expairseq ctor from ex,ex",LOGLEVEL_CONSTRUCT);
115 construct_from_2_ex(lh,rh);
116 GINAC_ASSERT(is_canonical());
119 expairseq::expairseq(const exvector &v) : inherited(TINFO_expairseq)
121 debugmsg("expairseq ctor from exvector",LOGLEVEL_CONSTRUCT);
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 debugmsg("expairseq ctor from epvector,ex",LOGLEVEL_CONSTRUCT);
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)
137 debugmsg("expairseq ctor from epvector *,ex",LOGLEVEL_CONSTRUCT);
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
153 debugmsg("expairseq ctor from archive_node", LOGLEVEL_CONSTRUCT);
154 for (unsigned int i=0; true; i++) {
157 if (n.find_ex("rest", rest, sym_lst, i) && n.find_ex("coeff", coeff, sym_lst, i))
158 seq.push_back(expair(rest, coeff));
162 n.find_ex("overall_coeff", overall_coeff, sym_lst);
165 void expairseq::archive(archive_node &n) const
167 inherited::archive(n);
168 epvector::const_iterator i = seq.begin(), iend = seq.end();
170 n.add_ex("rest", i->rest);
171 n.add_ex("coeff", i->coeff);
174 n.add_ex("overall_coeff", overall_coeff);
177 DEFAULT_UNARCHIVE(expairseq)
180 // functions overriding virtual functions from bases classes
185 basic *expairseq::duplicate() const
187 debugmsg("expairseq duplicate",LOGLEVEL_DUPLICATE);
188 return new expairseq(*this);
191 void expairseq::print(const print_context & c, unsigned level) const
193 debugmsg("expairseq print",LOGLEVEL_PRINT);
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 ex expairseq::eval(int level) const
322 if ((level==1) && (flags &status_flags::evaluated))
325 epvector *vp = evalchildren(level);
329 return (new expairseq(vp,overall_coeff))->setflag(status_flags::dynallocated | status_flags::evaluated);
332 bool expairseq::match(const ex & pattern, lst & repl_lst) const
334 // This differs from basic::match() because we want "a+b+c+d" to
335 // match "d+*+b" with "*" being "a+c", and we want to honor commutativity
337 if (tinfo() == pattern.bp->tinfo()) {
339 // Check whether global wildcard (one that matches the "rest of the
340 // expression", like "*" above) is present
341 bool has_global_wildcard = false;
343 for (unsigned int i=0; i<pattern.nops(); i++) {
344 if (is_ex_exactly_of_type(pattern.op(i), wildcard)) {
345 has_global_wildcard = true;
346 global_wildcard = pattern.op(i);
351 // Unfortunately, this is an O(N^2) operation because we can't
352 // sort the pattern in a useful way...
357 for (unsigned i=0; i<nops(); i++)
358 ops.push_back(op(i));
360 // Now, for every term of the pattern, look for a matching term in
361 // the expression and remove the match
362 for (unsigned i=0; i<pattern.nops(); i++) {
363 ex p = pattern.op(i);
364 if (has_global_wildcard && p.is_equal(global_wildcard))
366 exvector::iterator it = ops.begin(), itend = ops.end();
367 while (it != itend) {
368 if (it->match(p, repl_lst)) {
374 return false; // no match found
378 if (has_global_wildcard) {
380 // Assign all the remaining terms to the global wildcard (unless
381 // it has already been matched before, in which case the matches
383 unsigned num = ops.size();
384 epvector *vp = new epvector();
386 for (unsigned i=0; i<num; i++)
387 vp->push_back(split_ex_to_pair(ops[i]));
388 ex rest = thisexpairseq(vp, default_overall_coeff());
389 for (unsigned i=0; i<repl_lst.nops(); i++) {
390 if (repl_lst.op(i).op(0).is_equal(global_wildcard))
391 return rest.is_equal(*repl_lst.op(i).op(1).bp);
393 repl_lst.append(global_wildcard == rest);
398 // No global wildcard, then the match fails if there are any
399 // unmatched terms left
403 return inherited::match(pattern, repl_lst);
406 ex expairseq::subs(const lst &ls, const lst &lr, bool no_pattern) const
408 epvector *vp = subschildren(ls, lr, no_pattern);
410 return thisexpairseq(vp, overall_coeff).bp->basic::subs(ls, lr, no_pattern);
412 return basic::subs(ls, lr, no_pattern);
417 int expairseq::compare_same_type(const basic &other) const
419 GINAC_ASSERT(is_of_type(other, expairseq));
420 const expairseq &o = static_cast<const expairseq &>(other);
424 // compare number of elements
425 if (seq.size() != o.seq.size())
426 return (seq.size()<o.seq.size()) ? -1 : 1;
428 // compare overall_coeff
429 cmpval = overall_coeff.compare(o.overall_coeff);
433 #if EXPAIRSEQ_USE_HASHTAB
434 GINAC_ASSERT(hashtabsize==o.hashtabsize);
435 if (hashtabsize==0) {
436 #endif // EXPAIRSEQ_USE_HASHTAB
437 epvector::const_iterator cit1 = seq.begin();
438 epvector::const_iterator cit2 = o.seq.begin();
439 epvector::const_iterator last1 = seq.end();
440 epvector::const_iterator last2 = o.seq.end();
442 for (; (cit1!=last1)&&(cit2!=last2); ++cit1, ++cit2) {
443 cmpval = (*cit1).compare(*cit2);
444 if (cmpval!=0) return cmpval;
447 GINAC_ASSERT(cit1==last1);
448 GINAC_ASSERT(cit2==last2);
451 #if EXPAIRSEQ_USE_HASHTAB
454 // compare number of elements in each hashtab entry
455 for (unsigned i=0; i<hashtabsize; ++i) {
456 unsigned cursize=hashtab[i].size();
457 if (cursize != o.hashtab[i].size())
458 return (cursize < o.hashtab[i].size()) ? -1 : 1;
461 // compare individual (sorted) hashtab entries
462 for (unsigned i=0; i<hashtabsize; ++i) {
463 unsigned sz = hashtab[i].size();
465 const epplist &eppl1 = hashtab[i];
466 const epplist &eppl2 = o.hashtab[i];
467 epplist::const_iterator it1 = eppl1.begin();
468 epplist::const_iterator it2 = eppl2.begin();
469 while (it1!=eppl1.end()) {
470 cmpval = (*(*it1)).compare(*(*it2));
480 #endif // EXPAIRSEQ_USE_HASHTAB
483 bool expairseq::is_equal_same_type(const basic &other) const
485 const expairseq &o = static_cast<const expairseq &>(other);
487 // compare number of elements
488 if (seq.size()!=o.seq.size())
491 // compare overall_coeff
492 if (!overall_coeff.is_equal(o.overall_coeff))
495 #if EXPAIRSEQ_USE_HASHTAB
496 // compare number of elements in each hashtab entry
497 if (hashtabsize!=o.hashtabsize) {
498 std::cout << "this:" << std::endl;
499 print(print_tree(std::cout));
500 std::cout << "other:" << std::endl;
501 other.print(print_tree(std::cout));
504 GINAC_ASSERT(hashtabsize==o.hashtabsize);
506 if (hashtabsize==0) {
507 #endif // EXPAIRSEQ_USE_HASHTAB
508 epvector::const_iterator cit1 = seq.begin();
509 epvector::const_iterator cit2 = o.seq.begin();
510 epvector::const_iterator last1 = seq.end();
512 while (cit1!=last1) {
513 if (!(*cit1).is_equal(*cit2)) return false;
519 #if EXPAIRSEQ_USE_HASHTAB
522 for (unsigned i=0; i<hashtabsize; ++i) {
523 if (hashtab[i].size() != o.hashtab[i].size())
527 // compare individual sorted hashtab entries
528 for (unsigned i=0; i<hashtabsize; ++i) {
529 unsigned sz = hashtab[i].size();
531 const epplist &eppl1 = hashtab[i];
532 const epplist &eppl2 = o.hashtab[i];
533 epplist::const_iterator it1 = eppl1.begin();
534 epplist::const_iterator it2 = eppl2.begin();
535 while (it1!=eppl1.end()) {
536 if (!(*(*it1)).is_equal(*(*it2))) return false;
544 #endif // EXPAIRSEQ_USE_HASHTAB
547 unsigned expairseq::return_type(void) const
549 return return_types::noncommutative_composite;
552 unsigned expairseq::calchash(void) const
554 unsigned v = golden_ratio_hash(tinfo());
555 epvector::const_iterator i = seq.begin(), end = seq.end();
557 #if !EXPAIRSEQ_USE_HASHTAB
558 v = rotate_left_31(v); // rotation would spoil commutativity
559 #endif // EXPAIRSEQ_USE_HASHTAB
560 v ^= i->rest.gethash();
561 #if !EXPAIRSEQ_USE_HASHTAB
562 v = rotate_left_31(v);
563 v ^= i->coeff.gethash();
564 #endif // EXPAIRSEQ_USE_HASHTAB
568 v ^= overall_coeff.gethash();
571 // store calculated hash value only if object is already evaluated
572 if (flags &status_flags::evaluated) {
573 setflag(status_flags::hash_calculated);
580 ex expairseq::expand(unsigned options) const
582 epvector *vp = expandchildren(options);
584 // The terms have not changed, so it is safe to declare this expanded
585 return (options == 0) ? setflag(status_flags::expanded) : *this;
587 return thisexpairseq(vp, overall_coeff);
591 // new virtual functions which can be overridden by derived classes
596 /** Create an object of this type.
597 * This method works similar to a constructor. It is useful because expairseq
598 * has (at least) two possible different semantics but we want to inherit
599 * methods thus avoiding code duplication. Sometimes a method in expairseq
600 * has to create a new one of the same semantics, which cannot be done by a
601 * ctor because the name (add, mul,...) is unknown on the expaiseq level. In
602 * order for this trick to work a derived class must of course override this
604 ex expairseq::thisexpairseq(const epvector &v, const ex &oc) const
606 return expairseq(v,oc);
609 ex expairseq::thisexpairseq(epvector *vp, const ex &oc) const
611 return expairseq(vp,oc);
614 void expairseq::printpair(const print_context & c, const expair & p, unsigned upper_precedence) const
617 p.rest.bp->print(c, precedence());
619 p.coeff.bp->print(c, precedence());
623 void expairseq::printseq(const print_context & c, char delim,
624 unsigned this_precedence,
625 unsigned upper_precedence) const
627 if (this_precedence <= upper_precedence)
629 epvector::const_iterator it, it_last = seq.end() - 1;
630 for (it=seq.begin(); it!=it_last; ++it) {
631 printpair(c, *it, this_precedence);
634 printpair(c, *it, this_precedence);
635 if (!overall_coeff.is_equal(default_overall_coeff())) {
637 overall_coeff.print(c, this_precedence);
640 if (this_precedence <= upper_precedence)
645 /** Form an expair from an ex, using the corresponding semantics.
646 * @see expairseq::recombine_pair_to_ex() */
647 expair expairseq::split_ex_to_pair(const ex &e) const
649 return expair(e,_ex1());
653 expair expairseq::combine_ex_with_coeff_to_pair(const ex &e,
656 GINAC_ASSERT(is_ex_exactly_of_type(c,numeric));
662 expair expairseq::combine_pair_with_coeff_to_pair(const expair &p,
665 GINAC_ASSERT(is_ex_exactly_of_type(p.coeff,numeric));
666 GINAC_ASSERT(is_ex_exactly_of_type(c,numeric));
668 return expair(p.rest,ex_to<numeric>(p.coeff).mul_dyn(ex_to<numeric>(c)));
672 /** Form an ex out of an expair, using the corresponding semantics.
673 * @see expairseq::split_ex_to_pair() */
674 ex expairseq::recombine_pair_to_ex(const expair &p) const
676 return lst(p.rest,p.coeff);
679 bool expairseq::expair_needs_further_processing(epp it)
681 #if EXPAIRSEQ_USE_HASHTAB
682 //# error "FIXME: expair_needs_further_processing not yet implemented for hashtabs, sorry. A.F."
683 #endif // EXPAIRSEQ_USE_HASHTAB
687 ex expairseq::default_overall_coeff(void) const
692 void expairseq::combine_overall_coeff(const ex &c)
694 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
695 GINAC_ASSERT(is_ex_exactly_of_type(c,numeric));
696 overall_coeff = ex_to<numeric>(overall_coeff).add_dyn(ex_to<numeric>(c));
699 void expairseq::combine_overall_coeff(const ex &c1, const ex &c2)
701 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
702 GINAC_ASSERT(is_ex_exactly_of_type(c1,numeric));
703 GINAC_ASSERT(is_ex_exactly_of_type(c2,numeric));
704 overall_coeff = ex_to<numeric>(overall_coeff).
705 add_dyn(ex_to<numeric>(c1).mul(ex_to<numeric>(c2)));
708 bool expairseq::can_make_flat(const expair &p) const
715 // non-virtual functions in this class
718 void expairseq::construct_from_2_ex_via_exvector(const ex &lh, const ex &rh)
724 construct_from_exvector(v);
725 #if EXPAIRSEQ_USE_HASHTAB
726 GINAC_ASSERT((hashtabsize==0)||(hashtabsize>=minhashtabsize));
727 GINAC_ASSERT(hashtabsize==calc_hashtabsize(seq.size()));
728 #endif // EXPAIRSEQ_USE_HASHTAB
731 void expairseq::construct_from_2_ex(const ex &lh, const ex &rh)
733 if (lh.bp->tinfo()==tinfo()) {
734 if (rh.bp->tinfo()==tinfo()) {
735 #if EXPAIRSEQ_USE_HASHTAB
736 unsigned totalsize = ex_to<expairseq>(lh).seq.size() +
737 ex_to<expairseq>(rh).seq.size();
738 if (calc_hashtabsize(totalsize)!=0) {
739 construct_from_2_ex_via_exvector(lh,rh);
741 #endif // EXPAIRSEQ_USE_HASHTAB
742 construct_from_2_expairseq(ex_to<expairseq>(lh),
743 ex_to<expairseq>(rh));
744 #if EXPAIRSEQ_USE_HASHTAB
746 #endif // EXPAIRSEQ_USE_HASHTAB
749 #if EXPAIRSEQ_USE_HASHTAB
750 unsigned totalsize = ex_to<expairseq>(lh).seq.size()+1;
751 if (calc_hashtabsize(totalsize)!=0) {
752 construct_from_2_ex_via_exvector(lh, rh);
754 #endif // EXPAIRSEQ_USE_HASHTAB
755 construct_from_expairseq_ex(ex_to<expairseq>(lh), rh);
756 #if EXPAIRSEQ_USE_HASHTAB
758 #endif // EXPAIRSEQ_USE_HASHTAB
761 } else if (rh.bp->tinfo()==tinfo()) {
762 #if EXPAIRSEQ_USE_HASHTAB
763 unsigned totalsize=ex_to<expairseq>(rh).seq.size()+1;
764 if (calc_hashtabsize(totalsize)!=0) {
765 construct_from_2_ex_via_exvector(lh,rh);
767 #endif // EXPAIRSEQ_USE_HASHTAB
768 construct_from_expairseq_ex(ex_to<expairseq>(rh),lh);
769 #if EXPAIRSEQ_USE_HASHTAB
771 #endif // EXPAIRSEQ_USE_HASHTAB
775 #if EXPAIRSEQ_USE_HASHTAB
776 if (calc_hashtabsize(2)!=0) {
777 construct_from_2_ex_via_exvector(lh,rh);
781 #endif // EXPAIRSEQ_USE_HASHTAB
783 if (is_ex_exactly_of_type(lh,numeric)) {
784 if (is_ex_exactly_of_type(rh,numeric)) {
785 combine_overall_coeff(lh);
786 combine_overall_coeff(rh);
788 combine_overall_coeff(lh);
789 seq.push_back(split_ex_to_pair(rh));
792 if (is_ex_exactly_of_type(rh,numeric)) {
793 combine_overall_coeff(rh);
794 seq.push_back(split_ex_to_pair(lh));
796 expair p1 = split_ex_to_pair(lh);
797 expair p2 = split_ex_to_pair(rh);
799 int cmpval = p1.rest.compare(p2.rest);
801 p1.coeff=ex_to<numeric>(p1.coeff).add_dyn(ex_to<numeric>(p2.coeff));
802 if (!ex_to<numeric>(p1.coeff).is_zero()) {
803 // no further processing is necessary, since this
804 // one element will usually be recombined in eval()
821 void expairseq::construct_from_2_expairseq(const expairseq &s1,
824 combine_overall_coeff(s1.overall_coeff);
825 combine_overall_coeff(s2.overall_coeff);
827 epvector::const_iterator first1 = s1.seq.begin();
828 epvector::const_iterator last1 = s1.seq.end();
829 epvector::const_iterator first2 = s2.seq.begin();
830 epvector::const_iterator last2 = s2.seq.end();
832 seq.reserve(s1.seq.size()+s2.seq.size());
834 bool needs_further_processing=false;
836 while (first1!=last1 && first2!=last2) {
837 int cmpval = (*first1).rest.compare((*first2).rest);
840 const numeric &newcoeff = ex_to<numeric>((*first1).coeff).
841 add(ex_to<numeric>((*first2).coeff));
842 if (!newcoeff.is_zero()) {
843 seq.push_back(expair((*first1).rest,newcoeff));
844 if (expair_needs_further_processing(seq.end()-1)) {
845 needs_further_processing = true;
850 } else if (cmpval<0) {
851 seq.push_back(*first1);
854 seq.push_back(*first2);
859 while (first1!=last1) {
860 seq.push_back(*first1);
863 while (first2!=last2) {
864 seq.push_back(*first2);
868 if (needs_further_processing) {
871 construct_from_epvector(v);
875 void expairseq::construct_from_expairseq_ex(const expairseq &s,
878 combine_overall_coeff(s.overall_coeff);
879 if (is_ex_exactly_of_type(e,numeric)) {
880 combine_overall_coeff(e);
885 epvector::const_iterator first = s.seq.begin();
886 epvector::const_iterator last = s.seq.end();
887 expair p = split_ex_to_pair(e);
889 seq.reserve(s.seq.size()+1);
890 bool p_pushed = false;
892 bool needs_further_processing=false;
894 // merge p into s.seq
895 while (first!=last) {
896 int cmpval = (*first).rest.compare(p.rest);
899 const numeric &newcoeff = ex_to<numeric>(first->coeff).
900 add(ex_to<numeric>(p.coeff));
901 if (!newcoeff.is_zero()) {
902 seq.push_back(expair(first->rest,newcoeff));
903 if (expair_needs_further_processing(seq.end()-1))
904 needs_further_processing = true;
909 } else if (cmpval<0) {
910 seq.push_back(*first);
920 // while loop exited because p was pushed, now push rest of s.seq
921 while (first!=last) {
922 seq.push_back(*first);
926 // while loop exited because s.seq was pushed, now push p
930 if (needs_further_processing) {
933 construct_from_epvector(v);
937 void expairseq::construct_from_exvector(const exvector &v)
939 // simplifications: +(a,+(b,c),d) -> +(a,b,c,d) (associativity)
940 // +(d,b,c,a) -> +(a,b,c,d) (canonicalization)
941 // +(...,x,*(x,c1),*(x,c2)) -> +(...,*(x,1+c1+c2)) (c1, c2 numeric())
942 // (same for (+,*) -> (*,^)
945 #if EXPAIRSEQ_USE_HASHTAB
946 combine_same_terms();
949 combine_same_terms_sorted_seq();
950 #endif // EXPAIRSEQ_USE_HASHTAB
953 void expairseq::construct_from_epvector(const epvector &v)
955 // simplifications: +(a,+(b,c),d) -> +(a,b,c,d) (associativity)
956 // +(d,b,c,a) -> +(a,b,c,d) (canonicalization)
957 // +(...,x,*(x,c1),*(x,c2)) -> +(...,*(x,1+c1+c2)) (c1, c2 numeric())
958 // (same for (+,*) -> (*,^)
961 #if EXPAIRSEQ_USE_HASHTAB
962 combine_same_terms();
965 combine_same_terms_sorted_seq();
966 #endif // EXPAIRSEQ_USE_HASHTAB
969 /** Combine this expairseq with argument exvector.
970 * It cares for associativity as well as for special handling of numerics. */
971 void expairseq::make_flat(const exvector &v)
973 exvector::const_iterator cit;
975 // count number of operands which are of same expairseq derived type
976 // and their cumulative number of operands
981 while (cit!=v.end()) {
982 if (cit->bp->tinfo()==this->tinfo()) {
984 noperands += ex_to<expairseq>(*cit).seq.size();
989 // reserve seq and coeffseq which will hold all operands
990 seq.reserve(v.size()+noperands-nexpairseqs);
992 // copy elements and split off numerical part
994 while (cit!=v.end()) {
995 if (cit->bp->tinfo()==this->tinfo()) {
996 const expairseq &subseqref = ex_to<expairseq>(*cit);
997 combine_overall_coeff(subseqref.overall_coeff);
998 epvector::const_iterator cit_s = subseqref.seq.begin();
999 while (cit_s!=subseqref.seq.end()) {
1000 seq.push_back(*cit_s);
1004 if (is_ex_exactly_of_type(*cit,numeric))
1005 combine_overall_coeff(*cit);
1007 seq.push_back(split_ex_to_pair(*cit));
1013 /** Combine this expairseq with argument epvector.
1014 * It cares for associativity as well as for special handling of numerics. */
1015 void expairseq::make_flat(const epvector &v)
1017 epvector::const_iterator cit;
1019 // count number of operands which are of same expairseq derived type
1020 // and their cumulative number of operands
1021 int nexpairseqs = 0;
1025 while (cit!=v.end()) {
1026 if (cit->rest.bp->tinfo()==this->tinfo()) {
1028 noperands += ex_to<expairseq>(cit->rest).seq.size();
1033 // reserve seq and coeffseq which will hold all operands
1034 seq.reserve(v.size()+noperands-nexpairseqs);
1036 // copy elements and split off numerical part
1038 while (cit!=v.end()) {
1039 if (cit->rest.bp->tinfo()==this->tinfo() &&
1040 this->can_make_flat(*cit)) {
1041 const expairseq &subseqref = ex_to<expairseq>(cit->rest);
1042 combine_overall_coeff(ex_to<numeric>(subseqref.overall_coeff),
1043 ex_to<numeric>(cit->coeff));
1044 epvector::const_iterator cit_s = subseqref.seq.begin();
1045 while (cit_s!=subseqref.seq.end()) {
1046 seq.push_back(expair(cit_s->rest,
1047 ex_to<numeric>(cit_s->coeff).mul_dyn(ex_to<numeric>(cit->coeff))));
1048 //seq.push_back(combine_pair_with_coeff_to_pair(*cit_s,
1053 if (cit->is_canonical_numeric())
1054 combine_overall_coeff(cit->rest);
1056 seq.push_back(*cit);
1062 /** Brings this expairseq into a sorted (canonical) form. */
1063 void expairseq::canonicalize(void)
1065 sort(seq.begin(), seq.end(), expair_is_less());
1069 /** Compact a presorted expairseq by combining all matching expairs to one
1070 * each. On an add object, this is responsible for 2*x+3*x+y -> 5*x+y, for
1072 void expairseq::combine_same_terms_sorted_seq(void)
1074 bool needs_further_processing = false;
1077 epvector::iterator itin1 = seq.begin();
1078 epvector::iterator itin2 = itin1+1;
1079 epvector::iterator itout = itin1;
1080 epvector::iterator last = seq.end();
1081 // must_copy will be set to true the first time some combination is
1082 // possible from then on the sequence has changed and must be compacted
1083 bool must_copy = false;
1084 while (itin2!=last) {
1085 if ((*itin1).rest.compare(itin2->rest)==0) {
1086 (*itin1).coeff = ex_to<numeric>(itin1->coeff).
1087 add_dyn(ex_to<numeric>(itin2->coeff));
1088 if (expair_needs_further_processing(itin1))
1089 needs_further_processing = true;
1092 if (!ex_to<numeric>(itin1->coeff).is_zero()) {
1101 if (!ex_to<numeric>(itin1->coeff).is_zero()) {
1107 seq.erase(itout,last);
1110 if (needs_further_processing) {
1113 construct_from_epvector(v);
1117 #if EXPAIRSEQ_USE_HASHTAB
1119 unsigned expairseq::calc_hashtabsize(unsigned sz) const
1122 unsigned nearest_power_of_2 = 1 << log2(sz);
1123 // if (nearest_power_of_2 < maxhashtabsize/hashtabfactor) {
1124 // size = nearest_power_of_2*hashtabfactor;
1125 size = nearest_power_of_2/hashtabfactor;
1126 if (size<minhashtabsize)
1128 GINAC_ASSERT(hashtabsize<=0x8000000U); // really max size due to 31 bit hashing
1129 // hashtabsize must be a power of 2
1130 GINAC_ASSERT((1U << log2(size))==size);
1134 unsigned expairseq::calc_hashindex(const ex &e) const
1136 // calculate hashindex
1137 unsigned hash = e.gethash();
1139 if (is_a_numeric_hash(hash)) {
1140 hashindex = hashmask;
1142 hashindex = hash &hashmask;
1143 // last hashtab entry is reserved for numerics
1144 if (hashindex==hashmask) hashindex = 0;
1146 GINAC_ASSERT(hashindex>=0);
1147 GINAC_ASSERT((hashindex<hashtabsize)||(hashtabsize==0));
1151 void expairseq::shrink_hashtab(void)
1153 unsigned new_hashtabsize;
1154 while (hashtabsize!=(new_hashtabsize=calc_hashtabsize(seq.size()))) {
1155 GINAC_ASSERT(new_hashtabsize<hashtabsize);
1156 if (new_hashtabsize==0) {
1163 // shrink by a factor of 2
1164 unsigned half_hashtabsize = hashtabsize/2;
1165 for (unsigned i=0; i<half_hashtabsize-1; ++i)
1166 hashtab[i].merge(hashtab[i+half_hashtabsize],epp_is_less());
1167 // special treatment for numeric hashes
1168 hashtab[0].merge(hashtab[half_hashtabsize-1],epp_is_less());
1169 hashtab[half_hashtabsize-1] = hashtab[hashtabsize-1];
1170 hashtab.resize(half_hashtabsize);
1171 hashtabsize = half_hashtabsize;
1172 hashmask = hashtabsize-1;
1176 void expairseq::remove_hashtab_entry(epvector::const_iterator element)
1179 return; // nothing to do
1181 // calculate hashindex of element to be deleted
1182 unsigned hashindex = calc_hashindex((*element).rest);
1184 // find it in hashtab and remove it
1185 epplist &eppl = hashtab[hashindex];
1186 epplist::iterator epplit = eppl.begin();
1187 bool erased = false;
1188 while (epplit!=eppl.end()) {
1189 if (*epplit == element) {
1197 std::cout << "tried to erase " << element-seq.begin() << std::endl;
1198 std::cout << "size " << seq.end()-seq.begin() << std::endl;
1200 unsigned hashindex = calc_hashindex(element->rest);
1201 epplist &eppl = hashtab[hashindex];
1202 epplist::iterator epplit = eppl.begin();
1203 bool erased = false;
1204 while (epplit!=eppl.end()) {
1205 if (*epplit == element) {
1212 GINAC_ASSERT(erased);
1214 GINAC_ASSERT(erased);
1217 void expairseq::move_hashtab_entry(epvector::const_iterator oldpos,
1218 epvector::iterator newpos)
1220 GINAC_ASSERT(hashtabsize!=0);
1222 // calculate hashindex of element which was moved
1223 unsigned hashindex=calc_hashindex((*newpos).rest);
1225 // find it in hashtab and modify it
1226 epplist &eppl = hashtab[hashindex];
1227 epplist::iterator epplit = eppl.begin();
1228 while (epplit!=eppl.end()) {
1229 if (*epplit == oldpos) {
1235 GINAC_ASSERT(epplit!=eppl.end());
1238 void expairseq::sorted_insert(epplist &eppl, epvector::const_iterator elem)
1240 epplist::const_iterator current = eppl.begin();
1241 while ((current!=eppl.end()) && ((*current)->is_less(*elem))) {
1244 eppl.insert(current,elem);
1247 void expairseq::build_hashtab_and_combine(epvector::iterator &first_numeric,
1248 epvector::iterator &last_non_zero,
1249 std::vector<bool> &touched,
1250 unsigned &number_of_zeroes)
1252 epp current = seq.begin();
1254 while (current!=first_numeric) {
1255 if (is_ex_exactly_of_type(current->rest,numeric)) {
1257 iter_swap(current,first_numeric);
1259 // calculate hashindex
1260 unsigned currenthashindex = calc_hashindex(current->rest);
1262 // test if there is already a matching expair in the hashtab-list
1263 epplist &eppl=hashtab[currenthashindex];
1264 epplist::iterator epplit = eppl.begin();
1265 while (epplit!=eppl.end()) {
1266 if (current->rest.is_equal((*epplit)->rest))
1270 if (epplit==eppl.end()) {
1271 // no matching expair found, append this to end of list
1272 sorted_insert(eppl,current);
1275 // epplit points to a matching expair, combine it with current
1276 (*epplit)->coeff = ex_to<numeric>((*epplit)->coeff).
1277 add_dyn(ex_to<numeric>(current->coeff));
1279 // move obsolete current expair to end by swapping with last_non_zero element
1280 // if this was a numeric, it is swapped with the expair before first_numeric
1281 iter_swap(current,last_non_zero);
1283 if (first_numeric!=last_non_zero) iter_swap(first_numeric,current);
1286 // test if combined term has coeff 0 and can be removed is done later
1287 touched[(*epplit)-seq.begin()] = true;
1293 void expairseq::drop_coeff_0_terms(epvector::iterator &first_numeric,
1294 epvector::iterator &last_non_zero,
1295 std::vector<bool> &touched,
1296 unsigned &number_of_zeroes)
1298 // move terms with coeff 0 to end and remove them from hashtab
1299 // check only those elements which have been touched
1300 epp current = seq.begin();
1302 while (current!=first_numeric) {
1306 } else if (!ex_to<numeric>((*current).coeff).is_zero()) {
1310 remove_hashtab_entry(current);
1312 // move element to the end, unless it is already at the end
1313 if (current!=last_non_zero) {
1314 iter_swap(current,last_non_zero);
1316 bool numeric_swapped = first_numeric!=last_non_zero;
1317 if (numeric_swapped)
1318 iter_swap(first_numeric,current);
1319 epvector::iterator changed_entry;
1321 if (numeric_swapped)
1322 changed_entry = first_numeric;
1324 changed_entry = last_non_zero;
1329 if (first_numeric!=current) {
1331 // change entry in hashtab which referred to first_numeric or last_non_zero to current
1332 move_hashtab_entry(changed_entry,current);
1333 touched[current-seq.begin()] = touched[changed_entry-seq.begin()];
1342 GINAC_ASSERT(i==current-seq.begin());
1345 /** True if one of the coeffs vanishes, otherwise false.
1346 * This would be an invariant violation, so this should only be used for
1347 * debugging purposes. */
1348 bool expairseq::has_coeff_0(void) const
1350 epvector::const_iterator i = seq.begin(), end = seq.end();
1352 if (i->coeff.is_zero())
1359 void expairseq::add_numerics_to_hashtab(epvector::iterator first_numeric,
1360 epvector::const_iterator last_non_zero)
1362 if (first_numeric == seq.end()) return; // no numerics
1364 epvector::const_iterator current = first_numeric, last = last_non_zero + 1;
1365 while (current != last) {
1366 sorted_insert(hashtab[hashmask], current);
1371 void expairseq::combine_same_terms(void)
1373 // combine same terms, drop term with coeff 0, move numerics to end
1375 // calculate size of hashtab
1376 hashtabsize = calc_hashtabsize(seq.size());
1378 // hashtabsize is a power of 2
1379 hashmask = hashtabsize-1;
1383 hashtab.resize(hashtabsize);
1385 if (hashtabsize==0) {
1387 combine_same_terms_sorted_seq();
1388 GINAC_ASSERT(!has_coeff_0());
1392 // iterate through seq, move numerics to end,
1393 // fill hashtab and combine same terms
1394 epvector::iterator first_numeric = seq.end();
1395 epvector::iterator last_non_zero = seq.end()-1;
1397 unsigned num = seq.size();
1398 std::vector<bool> touched(num);
1400 unsigned number_of_zeroes = 0;
1402 GINAC_ASSERT(!has_coeff_0());
1403 build_hashtab_and_combine(first_numeric,last_non_zero,touched,number_of_zeroes);
1405 // there should not be any terms with coeff 0 from the beginning,
1406 // so it should be safe to skip this step
1407 if (number_of_zeroes!=0) {
1408 drop_coeff_0_terms(first_numeric,last_non_zero,touched,number_of_zeroes);
1411 add_numerics_to_hashtab(first_numeric,last_non_zero);
1413 // pop zero elements
1414 for (unsigned i=0; i<number_of_zeroes; ++i) {
1418 // shrink hashtabsize to calculated value
1419 GINAC_ASSERT(!has_coeff_0());
1423 GINAC_ASSERT(!has_coeff_0());
1426 #endif // EXPAIRSEQ_USE_HASHTAB
1428 /** Check if this expairseq is in sorted (canonical) form. Useful mainly for
1429 * debugging or in assertions since being sorted is an invariance. */
1430 bool expairseq::is_canonical() const
1432 if (seq.size() <= 1)
1435 #if EXPAIRSEQ_USE_HASHTAB
1436 if (hashtabsize > 0) return 1; // not canoncalized
1437 #endif // EXPAIRSEQ_USE_HASHTAB
1439 epvector::const_iterator it = seq.begin(), itend = seq.end();
1440 epvector::const_iterator it_last = it;
1441 for (++it; it!=itend; it_last=it, ++it) {
1442 if (!(it_last->is_less(*it) || it_last->is_equal(*it))) {
1443 if (!is_ex_exactly_of_type(it_last->rest,numeric) ||
1444 !is_ex_exactly_of_type(it->rest,numeric)) {
1445 // double test makes it easier to set a breakpoint...
1446 if (!is_ex_exactly_of_type(it_last->rest,numeric) ||
1447 !is_ex_exactly_of_type(it->rest,numeric)) {
1448 printpair(std::clog, *it_last, 0);
1450 printpair(std::clog, *it, 0);
1452 std::clog << "pair1:" << std::endl;
1453 it_last->rest.print(print_tree(std::clog));
1454 it_last->coeff.print(print_tree(std::clog));
1455 std::clog << "pair2:" << std::endl;
1456 it->rest.print(print_tree(std::clog));
1457 it->coeff.print(print_tree(std::clog));
1467 /** Member-wise expand the expairs in this sequence.
1469 * @see expairseq::expand()
1470 * @return pointer to epvector containing expanded pairs or zero pointer,
1471 * if no members were changed. */
1472 epvector * expairseq::expandchildren(unsigned options) const
1474 epvector::const_iterator last = seq.end();
1475 epvector::const_iterator cit = seq.begin();
1477 const ex &expanded_ex = cit->rest.expand(options);
1478 if (!are_ex_trivially_equal(cit->rest,expanded_ex)) {
1480 // something changed, copy seq, eval and return it
1481 epvector *s = new epvector;
1482 s->reserve(seq.size());
1484 // copy parts of seq which are known not to have changed
1485 epvector::const_iterator cit2 = seq.begin();
1487 s->push_back(*cit2);
1490 // copy first changed element
1491 s->push_back(combine_ex_with_coeff_to_pair(expanded_ex,
1495 while (cit2!=last) {
1496 s->push_back(combine_ex_with_coeff_to_pair(cit2->rest.expand(options),
1505 return 0; // signalling nothing has changed
1509 /** Member-wise evaluate the expairs in this sequence.
1511 * @see expairseq::eval()
1512 * @return pointer to epvector containing evaluated pairs or zero pointer,
1513 * if no members were changed. */
1514 epvector * expairseq::evalchildren(int level) const
1516 // returns a NULL pointer if nothing had to be evaluated
1517 // returns a pointer to a newly created epvector otherwise
1518 // (which has to be deleted somewhere else)
1523 if (level == -max_recursion_level)
1524 throw(std::runtime_error("max recursion level reached"));
1527 epvector::const_iterator last = seq.end();
1528 epvector::const_iterator cit = seq.begin();
1530 const ex &evaled_ex = cit->rest.eval(level);
1531 if (!are_ex_trivially_equal(cit->rest,evaled_ex)) {
1533 // something changed, copy seq, eval and return it
1534 epvector *s = new epvector;
1535 s->reserve(seq.size());
1537 // copy parts of seq which are known not to have changed
1538 epvector::const_iterator cit2=seq.begin();
1540 s->push_back(*cit2);
1543 // copy first changed element
1544 s->push_back(combine_ex_with_coeff_to_pair(evaled_ex,
1548 while (cit2!=last) {
1549 s->push_back(combine_ex_with_coeff_to_pair(cit2->rest.eval(level),
1558 return 0; // signalling nothing has changed
1562 /** Member-wise substitute in this sequence.
1564 * @see expairseq::subs()
1565 * @return pointer to epvector containing pairs after application of subs,
1566 * or NULL pointer if no members were changed. */
1567 epvector * expairseq::subschildren(const lst &ls, const lst &lr, bool no_pattern) const
1569 GINAC_ASSERT(ls.nops()==lr.nops());
1571 // The substitution is "complex" when any of the objects to be substituted
1572 // is a product or power. In this case we have to recombine the pairs
1573 // because the numeric coefficients may be part of the search pattern.
1574 bool complex_subs = false;
1575 for (unsigned i=0; i<ls.nops(); ++i)
1576 if (is_ex_exactly_of_type(ls.op(i), mul) || is_ex_exactly_of_type(ls.op(i), power)) {
1577 complex_subs = true;
1583 // Substitute in the recombined pairs
1584 epvector::const_iterator cit = seq.begin(), last = seq.end();
1585 while (cit != last) {
1587 const ex &orig_ex = recombine_pair_to_ex(*cit);
1588 const ex &subsed_ex = orig_ex.subs(ls, lr, no_pattern);
1589 if (!are_ex_trivially_equal(orig_ex, subsed_ex)) {
1591 // Something changed, copy seq, subs and return it
1592 epvector *s = new epvector;
1593 s->reserve(seq.size());
1595 // Copy parts of seq which are known not to have changed
1596 s->insert(s->begin(), seq.begin(), cit);
1598 // Copy first changed element
1599 s->push_back(split_ex_to_pair(subsed_ex));
1603 while (cit != last) {
1604 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit).subs(ls, lr, no_pattern)));
1615 // Substitute only in the "rest" part of the pairs
1616 epvector::const_iterator cit = seq.begin(), last = seq.end();
1617 while (cit != last) {
1619 const ex &subsed_ex = cit->rest.subs(ls, lr, no_pattern);
1620 if (!are_ex_trivially_equal(cit->rest, subsed_ex)) {
1622 // Something changed, copy seq, subs and return it
1623 epvector *s = new epvector;
1624 s->reserve(seq.size());
1626 // Copy parts of seq which are known not to have changed
1627 s->insert(s->begin(), seq.begin(), cit);
1629 // Copy first changed element
1630 s->push_back(combine_ex_with_coeff_to_pair(subsed_ex, cit->coeff));
1634 while (cit != last) {
1635 s->push_back(combine_ex_with_coeff_to_pair(cit->rest.subs(ls, lr, no_pattern),
1646 // Nothing has changed
1651 // static member variables
1654 #if EXPAIRSEQ_USE_HASHTAB
1655 unsigned expairseq::maxhashtabsize = 0x4000000U;
1656 unsigned expairseq::minhashtabsize = 0x1000U;
1657 unsigned expairseq::hashtabfactor = 1;
1658 #endif // EXPAIRSEQ_USE_HASHTAB
1660 } // namespace GiNaC