1 /** @file expairseq.cpp
3 * Implementation of sequences of expression pairs. */
6 * GiNaC Copyright (C) 1999-2005 Johannes Gutenberg University Mainz, Germany
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 #include "expairseq.h"
32 #include "relational.h"
35 #include "operators.h"
38 #if EXPAIRSEQ_USE_HASHTAB
40 #endif // EXPAIRSEQ_USE_HASHTAB
45 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(expairseq, basic,
46 print_func<print_context>(&expairseq::do_print).
47 print_func<print_tree>(&expairseq::do_print_tree))
57 bool operator()(const epp &lh, const epp &rh) const
59 return (*lh).is_less(*rh);
64 // default constructor
69 expairseq::expairseq() : inherited(TINFO_expairseq)
70 #if EXPAIRSEQ_USE_HASHTAB
72 #endif // EXPAIRSEQ_USE_HASHTAB
78 /** For use by copy ctor and assignment operator. */
79 void expairseq::copy(const expairseq &other)
82 overall_coeff = other.overall_coeff;
83 #if EXPAIRSEQ_USE_HASHTAB
85 hashtabsize = other.hashtabsize;
87 hashmask = other.hashmask;
88 hashtab.resize(hashtabsize);
89 epvector::const_iterator osb = other.seq.begin();
90 for (unsigned i=0; i<hashtabsize; ++i) {
92 for (epplist::const_iterator cit=other.hashtab[i].begin();
93 cit!=other.hashtab[i].end(); ++cit) {
94 hashtab[i].push_back(seq.begin()+((*cit)-osb));
100 #endif // EXPAIRSEQ_USE_HASHTAB
105 // other constructors
108 expairseq::expairseq(const ex &lh, const ex &rh) : inherited(TINFO_expairseq)
110 construct_from_2_ex(lh,rh);
111 GINAC_ASSERT(is_canonical());
114 expairseq::expairseq(const exvector &v) : inherited(TINFO_expairseq)
116 construct_from_exvector(v);
117 GINAC_ASSERT(is_canonical());
120 expairseq::expairseq(const epvector &v, const ex &oc)
121 : inherited(TINFO_expairseq), overall_coeff(oc)
123 GINAC_ASSERT(is_a<numeric>(oc));
124 construct_from_epvector(v);
125 GINAC_ASSERT(is_canonical());
128 expairseq::expairseq(std::auto_ptr<epvector> vp, const ex &oc)
129 : inherited(TINFO_expairseq), overall_coeff(oc)
131 GINAC_ASSERT(vp.get()!=0);
132 GINAC_ASSERT(is_a<numeric>(oc));
133 construct_from_epvector(*vp);
134 GINAC_ASSERT(is_canonical());
141 expairseq::expairseq(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
142 #if EXPAIRSEQ_USE_HASHTAB
146 for (unsigned int i=0; true; i++) {
149 if (n.find_ex("rest", rest, sym_lst, i) && n.find_ex("coeff", coeff, sym_lst, i))
150 seq.push_back(expair(rest, coeff));
155 n.find_ex("overall_coeff", overall_coeff, sym_lst);
158 GINAC_ASSERT(is_canonical());
161 void expairseq::archive(archive_node &n) const
163 inherited::archive(n);
164 epvector::const_iterator i = seq.begin(), iend = seq.end();
166 n.add_ex("rest", i->rest);
167 n.add_ex("coeff", i->coeff);
170 n.add_ex("overall_coeff", overall_coeff);
173 DEFAULT_UNARCHIVE(expairseq)
176 // functions overriding virtual functions from base classes
181 void expairseq::do_print(const print_context & c, unsigned level) const
184 printseq(c, ',', precedence(), level);
188 void expairseq::do_print_tree(const print_tree & c, unsigned level) const
190 c.s << std::string(level, ' ') << class_name() << " @" << this
191 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
192 << ", nops=" << nops()
194 size_t num = seq.size();
195 for (size_t i=0; i<num; ++i) {
196 seq[i].rest.print(c, level + c.delta_indent);
197 seq[i].coeff.print(c, level + c.delta_indent);
199 c.s << std::string(level + c.delta_indent, ' ') << "-----" << std::endl;
201 if (!overall_coeff.is_equal(default_overall_coeff())) {
202 c.s << std::string(level + c.delta_indent, ' ') << "-----" << std::endl
203 << std::string(level + c.delta_indent, ' ') << "overall_coeff" << std::endl;
204 overall_coeff.print(c, level + c.delta_indent);
206 c.s << std::string(level + c.delta_indent,' ') << "=====" << std::endl;
207 #if EXPAIRSEQ_USE_HASHTAB
208 c.s << std::string(level + c.delta_indent,' ')
209 << "hashtab size " << hashtabsize << std::endl;
210 if (hashtabsize == 0) return;
212 unsigned count[MAXCOUNT+1];
213 for (int i=0; i<MAXCOUNT+1; ++i)
215 unsigned this_bin_fill;
216 unsigned cum_fill_sq = 0;
217 unsigned cum_fill = 0;
218 for (unsigned i=0; i<hashtabsize; ++i) {
220 if (hashtab[i].size() > 0) {
221 c.s << std::string(level + c.delta_indent, ' ')
222 << "bin " << i << " with entries ";
223 for (epplist::const_iterator it=hashtab[i].begin();
224 it!=hashtab[i].end(); ++it) {
225 c.s << *it-seq.begin() << " ";
229 cum_fill += this_bin_fill;
230 cum_fill_sq += this_bin_fill*this_bin_fill;
232 if (this_bin_fill<MAXCOUNT)
233 ++count[this_bin_fill];
239 double lambda = (1.0*seq.size()) / hashtabsize;
240 for (int k=0; k<MAXCOUNT; ++k) {
243 double prob = std::pow(lambda,k)/fact * std::exp(-lambda);
245 c.s << std::string(level + c.delta_indent, ' ') << "bins with " << k << " entries: "
246 << int(1000.0*count[k]/hashtabsize)/10.0 << "% (expected: "
247 << int(prob*1000)/10.0 << ")" << std::endl;
249 c.s << std::string(level + c.delta_indent, ' ') << "bins with more entries: "
250 << int(1000.0*count[MAXCOUNT]/hashtabsize)/10.0 << "% (expected: "
251 << int((1-cum_prob)*1000)/10.0 << ")" << std::endl;
253 c.s << std::string(level + c.delta_indent, ' ') << "variance: "
254 << 1.0/hashtabsize*cum_fill_sq-(1.0/hashtabsize*cum_fill)*(1.0/hashtabsize*cum_fill)
256 c.s << std::string(level + c.delta_indent, ' ') << "average fill: "
257 << (1.0*cum_fill)/hashtabsize
258 << " (should be equal to " << (1.0*seq.size())/hashtabsize << ")" << std::endl;
259 #endif // EXPAIRSEQ_USE_HASHTAB
262 bool expairseq::info(unsigned inf) const
264 return inherited::info(inf);
267 size_t expairseq::nops() const
269 if (overall_coeff.is_equal(default_overall_coeff()))
275 ex expairseq::op(size_t i) const
278 return recombine_pair_to_ex(seq[i]);
279 GINAC_ASSERT(!overall_coeff.is_equal(default_overall_coeff()));
280 return overall_coeff;
283 ex expairseq::map(map_function &f) const
285 std::auto_ptr<epvector> v(new epvector);
286 v->reserve(seq.size()+1);
288 epvector::const_iterator cit = seq.begin(), last = seq.end();
289 while (cit != last) {
290 v->push_back(split_ex_to_pair(f(recombine_pair_to_ex(*cit))));
294 if (overall_coeff.is_equal(default_overall_coeff()))
295 return thisexpairseq(v, default_overall_coeff());
297 ex newcoeff = f(overall_coeff);
298 if(is_a<numeric>(newcoeff))
299 return thisexpairseq(v, newcoeff);
301 v->push_back(split_ex_to_pair(newcoeff));
302 return thisexpairseq(v, default_overall_coeff());
307 /** Perform coefficient-wise automatic term rewriting rules in this class. */
308 ex expairseq::eval(int level) const
310 if ((level==1) && (flags &status_flags::evaluated))
313 std::auto_ptr<epvector> vp = evalchildren(level);
317 return (new expairseq(vp, overall_coeff))->setflag(status_flags::dynallocated | status_flags::evaluated);
320 epvector* conjugateepvector(const epvector&epv)
322 epvector *newepv = 0;
323 for (epvector::const_iterator i=epv.begin(); i!=epv.end(); ++i) {
325 newepv->push_back(i->conjugate());
328 expair x = i->conjugate();
329 if (x.is_equal(*i)) {
332 newepv = new epvector;
333 newepv->reserve(epv.size());
334 for (epvector::const_iterator j=epv.begin(); j!=i; ++j) {
335 newepv->push_back(*j);
337 newepv->push_back(x);
342 ex expairseq::conjugate() const
344 epvector* newepv = conjugateepvector(seq);
345 ex x = overall_coeff.conjugate();
346 if (!newepv && are_ex_trivially_equal(x, overall_coeff)) {
349 ex result = thisexpairseq(newepv ? *newepv : seq, x);
356 bool expairseq::match(const ex & pattern, lst & repl_lst) const
358 // This differs from basic::match() because we want "a+b+c+d" to
359 // match "d+*+b" with "*" being "a+c", and we want to honor commutativity
361 if (this->tinfo() == ex_to<basic>(pattern).tinfo()) {
363 // Check whether global wildcard (one that matches the "rest of the
364 // expression", like "*" above) is present
365 bool has_global_wildcard = false;
367 for (size_t i=0; i<pattern.nops(); i++) {
368 if (is_exactly_a<wildcard>(pattern.op(i))) {
369 has_global_wildcard = true;
370 global_wildcard = pattern.op(i);
375 // Unfortunately, this is an O(N^2) operation because we can't
376 // sort the pattern in a useful way...
381 for (size_t i=0; i<nops(); i++)
382 ops.push_back(op(i));
384 // Now, for every term of the pattern, look for a matching term in
385 // the expression and remove the match
386 for (size_t i=0; i<pattern.nops(); i++) {
387 ex p = pattern.op(i);
388 if (has_global_wildcard && p.is_equal(global_wildcard))
390 exvector::iterator it = ops.begin(), itend = ops.end();
391 while (it != itend) {
392 lst::const_iterator last_el = repl_lst.end();
394 if (it->match(p, repl_lst)) {
399 lst::const_iterator next_el = last_el;
401 if(next_el == repl_lst.end())
404 repl_lst.remove_last();
408 return false; // no match found
412 if (has_global_wildcard) {
414 // Assign all the remaining terms to the global wildcard (unless
415 // it has already been matched before, in which case the matches
417 size_t num = ops.size();
418 std::auto_ptr<epvector> vp(new epvector);
420 for (size_t i=0; i<num; i++)
421 vp->push_back(split_ex_to_pair(ops[i]));
422 ex rest = thisexpairseq(vp, default_overall_coeff());
423 for (lst::const_iterator it = repl_lst.begin(); it != repl_lst.end(); ++it) {
424 if (it->op(0).is_equal(global_wildcard))
425 return rest.is_equal(it->op(1));
427 repl_lst.append(global_wildcard == rest);
432 // No global wildcard, then the match fails if there are any
433 // unmatched terms left
437 return inherited::match(pattern, repl_lst);
440 ex expairseq::subs(const exmap & m, unsigned options) const
442 std::auto_ptr<epvector> vp = subschildren(m, options);
444 return ex_to<basic>(thisexpairseq(vp, overall_coeff));
445 else if ((options & subs_options::algebraic) && is_exactly_a<mul>(*this))
446 return static_cast<const mul *>(this)->algebraic_subs_mul(m, options);
448 return subs_one_level(m, options);
453 int expairseq::compare_same_type(const basic &other) const
455 GINAC_ASSERT(is_a<expairseq>(other));
456 const expairseq &o = static_cast<const expairseq &>(other);
460 // compare number of elements
461 if (seq.size() != o.seq.size())
462 return (seq.size()<o.seq.size()) ? -1 : 1;
464 // compare overall_coeff
465 cmpval = overall_coeff.compare(o.overall_coeff);
469 #if EXPAIRSEQ_USE_HASHTAB
470 GINAC_ASSERT(hashtabsize==o.hashtabsize);
471 if (hashtabsize==0) {
472 #endif // EXPAIRSEQ_USE_HASHTAB
473 epvector::const_iterator cit1 = seq.begin();
474 epvector::const_iterator cit2 = o.seq.begin();
475 epvector::const_iterator last1 = seq.end();
476 epvector::const_iterator last2 = o.seq.end();
478 for (; (cit1!=last1)&&(cit2!=last2); ++cit1, ++cit2) {
479 cmpval = (*cit1).compare(*cit2);
480 if (cmpval!=0) return cmpval;
483 GINAC_ASSERT(cit1==last1);
484 GINAC_ASSERT(cit2==last2);
487 #if EXPAIRSEQ_USE_HASHTAB
490 // compare number of elements in each hashtab entry
491 for (unsigned i=0; i<hashtabsize; ++i) {
492 unsigned cursize=hashtab[i].size();
493 if (cursize != o.hashtab[i].size())
494 return (cursize < o.hashtab[i].size()) ? -1 : 1;
497 // compare individual (sorted) hashtab entries
498 for (unsigned i=0; i<hashtabsize; ++i) {
499 unsigned sz = hashtab[i].size();
501 const epplist &eppl1 = hashtab[i];
502 const epplist &eppl2 = o.hashtab[i];
503 epplist::const_iterator it1 = eppl1.begin();
504 epplist::const_iterator it2 = eppl2.begin();
505 while (it1!=eppl1.end()) {
506 cmpval = (*(*it1)).compare(*(*it2));
516 #endif // EXPAIRSEQ_USE_HASHTAB
519 bool expairseq::is_equal_same_type(const basic &other) const
521 const expairseq &o = static_cast<const expairseq &>(other);
523 // compare number of elements
524 if (seq.size()!=o.seq.size())
527 // compare overall_coeff
528 if (!overall_coeff.is_equal(o.overall_coeff))
531 #if EXPAIRSEQ_USE_HASHTAB
532 // compare number of elements in each hashtab entry
533 if (hashtabsize!=o.hashtabsize) {
534 std::cout << "this:" << std::endl;
535 print(print_tree(std::cout));
536 std::cout << "other:" << std::endl;
537 other.print(print_tree(std::cout));
540 GINAC_ASSERT(hashtabsize==o.hashtabsize);
542 if (hashtabsize==0) {
543 #endif // EXPAIRSEQ_USE_HASHTAB
544 epvector::const_iterator cit1 = seq.begin();
545 epvector::const_iterator cit2 = o.seq.begin();
546 epvector::const_iterator last1 = seq.end();
548 while (cit1!=last1) {
549 if (!(*cit1).is_equal(*cit2)) return false;
555 #if EXPAIRSEQ_USE_HASHTAB
558 for (unsigned i=0; i<hashtabsize; ++i) {
559 if (hashtab[i].size() != o.hashtab[i].size())
563 // compare individual sorted hashtab entries
564 for (unsigned i=0; i<hashtabsize; ++i) {
565 unsigned sz = hashtab[i].size();
567 const epplist &eppl1 = hashtab[i];
568 const epplist &eppl2 = o.hashtab[i];
569 epplist::const_iterator it1 = eppl1.begin();
570 epplist::const_iterator it2 = eppl2.begin();
571 while (it1!=eppl1.end()) {
572 if (!(*(*it1)).is_equal(*(*it2))) return false;
580 #endif // EXPAIRSEQ_USE_HASHTAB
583 unsigned expairseq::return_type() const
585 return return_types::noncommutative_composite;
588 unsigned expairseq::calchash() const
590 unsigned v = golden_ratio_hash(this->tinfo());
591 epvector::const_iterator i = seq.begin();
592 const epvector::const_iterator end = seq.end();
594 v ^= i->rest.gethash();
595 #if !EXPAIRSEQ_USE_HASHTAB
596 // rotation spoils commutativity!
598 v ^= i->coeff.gethash();
599 #endif // !EXPAIRSEQ_USE_HASHTAB
603 v ^= overall_coeff.gethash();
605 // store calculated hash value only if object is already evaluated
606 if (flags &status_flags::evaluated) {
607 setflag(status_flags::hash_calculated);
614 ex expairseq::expand(unsigned options) const
616 std::auto_ptr<epvector> vp = expandchildren(options);
618 return thisexpairseq(vp, overall_coeff);
620 // The terms have not changed, so it is safe to declare this expanded
621 return (options == 0) ? setflag(status_flags::expanded) : *this;
626 // new virtual functions which can be overridden by derived classes
631 /** Create an object of this type.
632 * This method works similar to a constructor. It is useful because expairseq
633 * has (at least) two possible different semantics but we want to inherit
634 * methods thus avoiding code duplication. Sometimes a method in expairseq
635 * has to create a new one of the same semantics, which cannot be done by a
636 * ctor because the name (add, mul,...) is unknown on the expaiseq level. In
637 * order for this trick to work a derived class must of course override this
639 ex expairseq::thisexpairseq(const epvector &v, const ex &oc) const
641 return expairseq(v, oc);
644 ex expairseq::thisexpairseq(std::auto_ptr<epvector> vp, const ex &oc) const
646 return expairseq(vp, oc);
649 void expairseq::printpair(const print_context & c, const expair & p, unsigned upper_precedence) const
652 p.rest.print(c, precedence());
654 p.coeff.print(c, precedence());
658 void expairseq::printseq(const print_context & c, char delim,
659 unsigned this_precedence,
660 unsigned upper_precedence) const
662 if (this_precedence <= upper_precedence)
664 epvector::const_iterator it, it_last = seq.end() - 1;
665 for (it=seq.begin(); it!=it_last; ++it) {
666 printpair(c, *it, this_precedence);
669 printpair(c, *it, this_precedence);
670 if (!overall_coeff.is_equal(default_overall_coeff())) {
672 overall_coeff.print(c, this_precedence);
675 if (this_precedence <= upper_precedence)
680 /** Form an expair from an ex, using the corresponding semantics.
681 * @see expairseq::recombine_pair_to_ex() */
682 expair expairseq::split_ex_to_pair(const ex &e) const
684 return expair(e,_ex1);
688 expair expairseq::combine_ex_with_coeff_to_pair(const ex &e,
691 GINAC_ASSERT(is_exactly_a<numeric>(c));
697 expair expairseq::combine_pair_with_coeff_to_pair(const expair &p,
700 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
701 GINAC_ASSERT(is_exactly_a<numeric>(c));
703 return expair(p.rest,ex_to<numeric>(p.coeff).mul_dyn(ex_to<numeric>(c)));
707 /** Form an ex out of an expair, using the corresponding semantics.
708 * @see expairseq::split_ex_to_pair() */
709 ex expairseq::recombine_pair_to_ex(const expair &p) const
711 return lst(p.rest,p.coeff);
714 bool expairseq::expair_needs_further_processing(epp it)
716 #if EXPAIRSEQ_USE_HASHTAB
717 //# error "FIXME: expair_needs_further_processing not yet implemented for hashtabs, sorry. A.F."
718 #endif // EXPAIRSEQ_USE_HASHTAB
722 ex expairseq::default_overall_coeff() const
727 void expairseq::combine_overall_coeff(const ex &c)
729 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
730 GINAC_ASSERT(is_exactly_a<numeric>(c));
731 overall_coeff = ex_to<numeric>(overall_coeff).add_dyn(ex_to<numeric>(c));
734 void expairseq::combine_overall_coeff(const ex &c1, const ex &c2)
736 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
737 GINAC_ASSERT(is_exactly_a<numeric>(c1));
738 GINAC_ASSERT(is_exactly_a<numeric>(c2));
739 overall_coeff = ex_to<numeric>(overall_coeff).
740 add_dyn(ex_to<numeric>(c1).mul(ex_to<numeric>(c2)));
743 bool expairseq::can_make_flat(const expair &p) const
750 // non-virtual functions in this class
753 void expairseq::construct_from_2_ex_via_exvector(const ex &lh, const ex &rh)
759 construct_from_exvector(v);
760 #if EXPAIRSEQ_USE_HASHTAB
761 GINAC_ASSERT((hashtabsize==0)||(hashtabsize>=minhashtabsize));
762 GINAC_ASSERT(hashtabsize==calc_hashtabsize(seq.size()));
763 #endif // EXPAIRSEQ_USE_HASHTAB
766 void expairseq::construct_from_2_ex(const ex &lh, const ex &rh)
768 if (ex_to<basic>(lh).tinfo()==this->tinfo()) {
769 if (ex_to<basic>(rh).tinfo()==this->tinfo()) {
770 #if EXPAIRSEQ_USE_HASHTAB
771 unsigned totalsize = ex_to<expairseq>(lh).seq.size() +
772 ex_to<expairseq>(rh).seq.size();
773 if (calc_hashtabsize(totalsize)!=0) {
774 construct_from_2_ex_via_exvector(lh,rh);
776 #endif // EXPAIRSEQ_USE_HASHTAB
777 construct_from_2_expairseq(ex_to<expairseq>(lh),
778 ex_to<expairseq>(rh));
779 #if EXPAIRSEQ_USE_HASHTAB
781 #endif // EXPAIRSEQ_USE_HASHTAB
784 #if EXPAIRSEQ_USE_HASHTAB
785 unsigned totalsize = ex_to<expairseq>(lh).seq.size()+1;
786 if (calc_hashtabsize(totalsize)!=0) {
787 construct_from_2_ex_via_exvector(lh, rh);
789 #endif // EXPAIRSEQ_USE_HASHTAB
790 construct_from_expairseq_ex(ex_to<expairseq>(lh), rh);
791 #if EXPAIRSEQ_USE_HASHTAB
793 #endif // EXPAIRSEQ_USE_HASHTAB
796 } else if (ex_to<basic>(rh).tinfo()==this->tinfo()) {
797 #if EXPAIRSEQ_USE_HASHTAB
798 unsigned totalsize=ex_to<expairseq>(rh).seq.size()+1;
799 if (calc_hashtabsize(totalsize)!=0) {
800 construct_from_2_ex_via_exvector(lh,rh);
802 #endif // EXPAIRSEQ_USE_HASHTAB
803 construct_from_expairseq_ex(ex_to<expairseq>(rh),lh);
804 #if EXPAIRSEQ_USE_HASHTAB
806 #endif // EXPAIRSEQ_USE_HASHTAB
810 #if EXPAIRSEQ_USE_HASHTAB
811 if (calc_hashtabsize(2)!=0) {
812 construct_from_2_ex_via_exvector(lh,rh);
816 #endif // EXPAIRSEQ_USE_HASHTAB
818 if (is_exactly_a<numeric>(lh)) {
819 if (is_exactly_a<numeric>(rh)) {
820 combine_overall_coeff(lh);
821 combine_overall_coeff(rh);
823 combine_overall_coeff(lh);
824 seq.push_back(split_ex_to_pair(rh));
827 if (is_exactly_a<numeric>(rh)) {
828 combine_overall_coeff(rh);
829 seq.push_back(split_ex_to_pair(lh));
831 expair p1 = split_ex_to_pair(lh);
832 expair p2 = split_ex_to_pair(rh);
834 int cmpval = p1.rest.compare(p2.rest);
836 p1.coeff = ex_to<numeric>(p1.coeff).add_dyn(ex_to<numeric>(p2.coeff));
837 if (!ex_to<numeric>(p1.coeff).is_zero()) {
838 // no further processing is necessary, since this
839 // one element will usually be recombined in eval()
856 void expairseq::construct_from_2_expairseq(const expairseq &s1,
859 combine_overall_coeff(s1.overall_coeff);
860 combine_overall_coeff(s2.overall_coeff);
862 epvector::const_iterator first1 = s1.seq.begin();
863 epvector::const_iterator last1 = s1.seq.end();
864 epvector::const_iterator first2 = s2.seq.begin();
865 epvector::const_iterator last2 = s2.seq.end();
867 seq.reserve(s1.seq.size()+s2.seq.size());
869 bool needs_further_processing=false;
871 while (first1!=last1 && first2!=last2) {
872 int cmpval = (*first1).rest.compare((*first2).rest);
875 const numeric &newcoeff = ex_to<numeric>(first1->coeff).
876 add(ex_to<numeric>(first2->coeff));
877 if (!newcoeff.is_zero()) {
878 seq.push_back(expair(first1->rest,newcoeff));
879 if (expair_needs_further_processing(seq.end()-1)) {
880 needs_further_processing = true;
885 } else if (cmpval<0) {
886 seq.push_back(*first1);
889 seq.push_back(*first2);
894 while (first1!=last1) {
895 seq.push_back(*first1);
898 while (first2!=last2) {
899 seq.push_back(*first2);
903 if (needs_further_processing) {
906 construct_from_epvector(v);
910 void expairseq::construct_from_expairseq_ex(const expairseq &s,
913 combine_overall_coeff(s.overall_coeff);
914 if (is_exactly_a<numeric>(e)) {
915 combine_overall_coeff(e);
920 epvector::const_iterator first = s.seq.begin();
921 epvector::const_iterator last = s.seq.end();
922 expair p = split_ex_to_pair(e);
924 seq.reserve(s.seq.size()+1);
925 bool p_pushed = false;
927 bool needs_further_processing=false;
929 // merge p into s.seq
930 while (first!=last) {
931 int cmpval = (*first).rest.compare(p.rest);
934 const numeric &newcoeff = ex_to<numeric>(first->coeff).
935 add(ex_to<numeric>(p.coeff));
936 if (!newcoeff.is_zero()) {
937 seq.push_back(expair(first->rest,newcoeff));
938 if (expair_needs_further_processing(seq.end()-1))
939 needs_further_processing = true;
944 } else if (cmpval<0) {
945 seq.push_back(*first);
955 // while loop exited because p was pushed, now push rest of s.seq
956 while (first!=last) {
957 seq.push_back(*first);
961 // while loop exited because s.seq was pushed, now push p
965 if (needs_further_processing) {
968 construct_from_epvector(v);
972 void expairseq::construct_from_exvector(const exvector &v)
974 // simplifications: +(a,+(b,c),d) -> +(a,b,c,d) (associativity)
975 // +(d,b,c,a) -> +(a,b,c,d) (canonicalization)
976 // +(...,x,*(x,c1),*(x,c2)) -> +(...,*(x,1+c1+c2)) (c1, c2 numeric())
977 // (same for (+,*) -> (*,^)
980 #if EXPAIRSEQ_USE_HASHTAB
981 combine_same_terms();
984 combine_same_terms_sorted_seq();
985 #endif // EXPAIRSEQ_USE_HASHTAB
988 void expairseq::construct_from_epvector(const epvector &v)
990 // simplifications: +(a,+(b,c),d) -> +(a,b,c,d) (associativity)
991 // +(d,b,c,a) -> +(a,b,c,d) (canonicalization)
992 // +(...,x,*(x,c1),*(x,c2)) -> +(...,*(x,1+c1+c2)) (c1, c2 numeric())
993 // (same for (+,*) -> (*,^)
996 #if EXPAIRSEQ_USE_HASHTAB
997 combine_same_terms();
1000 combine_same_terms_sorted_seq();
1001 #endif // EXPAIRSEQ_USE_HASHTAB
1004 /** Combine this expairseq with argument exvector.
1005 * It cares for associativity as well as for special handling of numerics. */
1006 void expairseq::make_flat(const exvector &v)
1008 exvector::const_iterator cit;
1010 // count number of operands which are of same expairseq derived type
1011 // and their cumulative number of operands
1012 int nexpairseqs = 0;
1016 while (cit!=v.end()) {
1017 if (ex_to<basic>(*cit).tinfo()==this->tinfo()) {
1019 noperands += ex_to<expairseq>(*cit).seq.size();
1024 // reserve seq and coeffseq which will hold all operands
1025 seq.reserve(v.size()+noperands-nexpairseqs);
1027 // copy elements and split off numerical part
1029 while (cit!=v.end()) {
1030 if (ex_to<basic>(*cit).tinfo()==this->tinfo()) {
1031 const expairseq &subseqref = ex_to<expairseq>(*cit);
1032 combine_overall_coeff(subseqref.overall_coeff);
1033 epvector::const_iterator cit_s = subseqref.seq.begin();
1034 while (cit_s!=subseqref.seq.end()) {
1035 seq.push_back(*cit_s);
1039 if (is_exactly_a<numeric>(*cit))
1040 combine_overall_coeff(*cit);
1042 seq.push_back(split_ex_to_pair(*cit));
1048 /** Combine this expairseq with argument epvector.
1049 * It cares for associativity as well as for special handling of numerics. */
1050 void expairseq::make_flat(const epvector &v)
1052 epvector::const_iterator cit;
1054 // count number of operands which are of same expairseq derived type
1055 // and their cumulative number of operands
1056 int nexpairseqs = 0;
1060 while (cit!=v.end()) {
1061 if (ex_to<basic>(cit->rest).tinfo()==this->tinfo()) {
1063 noperands += ex_to<expairseq>(cit->rest).seq.size();
1068 // reserve seq and coeffseq which will hold all operands
1069 seq.reserve(v.size()+noperands-nexpairseqs);
1071 // copy elements and split off numerical part
1073 while (cit!=v.end()) {
1074 if (ex_to<basic>(cit->rest).tinfo()==this->tinfo() &&
1075 this->can_make_flat(*cit)) {
1076 const expairseq &subseqref = ex_to<expairseq>(cit->rest);
1077 combine_overall_coeff(ex_to<numeric>(subseqref.overall_coeff),
1078 ex_to<numeric>(cit->coeff));
1079 epvector::const_iterator cit_s = subseqref.seq.begin();
1080 while (cit_s!=subseqref.seq.end()) {
1081 seq.push_back(expair(cit_s->rest,
1082 ex_to<numeric>(cit_s->coeff).mul_dyn(ex_to<numeric>(cit->coeff))));
1083 //seq.push_back(combine_pair_with_coeff_to_pair(*cit_s,
1088 if (cit->is_canonical_numeric())
1089 combine_overall_coeff(cit->rest);
1091 seq.push_back(*cit);
1097 /** Brings this expairseq into a sorted (canonical) form. */
1098 void expairseq::canonicalize()
1100 std::sort(seq.begin(), seq.end(), expair_rest_is_less());
1104 /** Compact a presorted expairseq by combining all matching expairs to one
1105 * each. On an add object, this is responsible for 2*x+3*x+y -> 5*x+y, for
1107 void expairseq::combine_same_terms_sorted_seq()
1112 bool needs_further_processing = false;
1114 epvector::iterator itin1 = seq.begin();
1115 epvector::iterator itin2 = itin1+1;
1116 epvector::iterator itout = itin1;
1117 epvector::iterator last = seq.end();
1118 // must_copy will be set to true the first time some combination is
1119 // possible from then on the sequence has changed and must be compacted
1120 bool must_copy = false;
1121 while (itin2!=last) {
1122 if (itin1->rest.compare(itin2->rest)==0) {
1123 itin1->coeff = ex_to<numeric>(itin1->coeff).
1124 add_dyn(ex_to<numeric>(itin2->coeff));
1125 if (expair_needs_further_processing(itin1))
1126 needs_further_processing = true;
1129 if (!ex_to<numeric>(itin1->coeff).is_zero()) {
1138 if (!ex_to<numeric>(itin1->coeff).is_zero()) {
1144 seq.erase(itout,last);
1146 if (needs_further_processing) {
1149 construct_from_epvector(v);
1153 #if EXPAIRSEQ_USE_HASHTAB
1155 unsigned expairseq::calc_hashtabsize(unsigned sz) const
1158 unsigned nearest_power_of_2 = 1 << log2(sz);
1159 // if (nearest_power_of_2 < maxhashtabsize/hashtabfactor) {
1160 // size = nearest_power_of_2*hashtabfactor;
1161 size = nearest_power_of_2/hashtabfactor;
1162 if (size<minhashtabsize)
1165 // hashtabsize must be a power of 2
1166 GINAC_ASSERT((1U << log2(size))==size);
1170 unsigned expairseq::calc_hashindex(const ex &e) const
1172 // calculate hashindex
1174 if (is_a<numeric>(e)) {
1175 hashindex = hashmask;
1177 hashindex = e.gethash() & hashmask;
1178 // last hashtab entry is reserved for numerics
1179 if (hashindex==hashmask) hashindex = 0;
1181 GINAC_ASSERT((hashindex<hashtabsize)||(hashtabsize==0));
1185 void expairseq::shrink_hashtab()
1187 unsigned new_hashtabsize;
1188 while (hashtabsize!=(new_hashtabsize=calc_hashtabsize(seq.size()))) {
1189 GINAC_ASSERT(new_hashtabsize<hashtabsize);
1190 if (new_hashtabsize==0) {
1197 // shrink by a factor of 2
1198 unsigned half_hashtabsize = hashtabsize/2;
1199 for (unsigned i=0; i<half_hashtabsize-1; ++i)
1200 hashtab[i].merge(hashtab[i+half_hashtabsize],epp_is_less());
1201 // special treatment for numeric hashes
1202 hashtab[0].merge(hashtab[half_hashtabsize-1],epp_is_less());
1203 hashtab[half_hashtabsize-1] = hashtab[hashtabsize-1];
1204 hashtab.resize(half_hashtabsize);
1205 hashtabsize = half_hashtabsize;
1206 hashmask = hashtabsize-1;
1210 void expairseq::remove_hashtab_entry(epvector::const_iterator element)
1213 return; // nothing to do
1215 // calculate hashindex of element to be deleted
1216 unsigned hashindex = calc_hashindex((*element).rest);
1218 // find it in hashtab and remove it
1219 epplist &eppl = hashtab[hashindex];
1220 epplist::iterator epplit = eppl.begin();
1221 bool erased = false;
1222 while (epplit!=eppl.end()) {
1223 if (*epplit == element) {
1231 std::cout << "tried to erase " << element-seq.begin() << std::endl;
1232 std::cout << "size " << seq.end()-seq.begin() << std::endl;
1234 unsigned hashindex = calc_hashindex(element->rest);
1235 epplist &eppl = hashtab[hashindex];
1236 epplist::iterator epplit = eppl.begin();
1237 bool erased = false;
1238 while (epplit!=eppl.end()) {
1239 if (*epplit == element) {
1246 GINAC_ASSERT(erased);
1248 GINAC_ASSERT(erased);
1251 void expairseq::move_hashtab_entry(epvector::const_iterator oldpos,
1252 epvector::iterator newpos)
1254 GINAC_ASSERT(hashtabsize!=0);
1256 // calculate hashindex of element which was moved
1257 unsigned hashindex=calc_hashindex((*newpos).rest);
1259 // find it in hashtab and modify it
1260 epplist &eppl = hashtab[hashindex];
1261 epplist::iterator epplit = eppl.begin();
1262 while (epplit!=eppl.end()) {
1263 if (*epplit == oldpos) {
1269 GINAC_ASSERT(epplit!=eppl.end());
1272 void expairseq::sorted_insert(epplist &eppl, epvector::const_iterator elem)
1274 epplist::const_iterator current = eppl.begin();
1275 while ((current!=eppl.end()) && ((*current)->is_less(*elem))) {
1278 eppl.insert(current,elem);
1281 void expairseq::build_hashtab_and_combine(epvector::iterator &first_numeric,
1282 epvector::iterator &last_non_zero,
1283 std::vector<bool> &touched,
1284 unsigned &number_of_zeroes)
1286 epp current = seq.begin();
1288 while (current!=first_numeric) {
1289 if (is_exactly_a<numeric>(current->rest)) {
1291 iter_swap(current,first_numeric);
1293 // calculate hashindex
1294 unsigned currenthashindex = calc_hashindex(current->rest);
1296 // test if there is already a matching expair in the hashtab-list
1297 epplist &eppl=hashtab[currenthashindex];
1298 epplist::iterator epplit = eppl.begin();
1299 while (epplit!=eppl.end()) {
1300 if (current->rest.is_equal((*epplit)->rest))
1304 if (epplit==eppl.end()) {
1305 // no matching expair found, append this to end of list
1306 sorted_insert(eppl,current);
1309 // epplit points to a matching expair, combine it with current
1310 (*epplit)->coeff = ex_to<numeric>((*epplit)->coeff).
1311 add_dyn(ex_to<numeric>(current->coeff));
1313 // move obsolete current expair to end by swapping with last_non_zero element
1314 // if this was a numeric, it is swapped with the expair before first_numeric
1315 iter_swap(current,last_non_zero);
1317 if (first_numeric!=last_non_zero) iter_swap(first_numeric,current);
1320 // test if combined term has coeff 0 and can be removed is done later
1321 touched[(*epplit)-seq.begin()] = true;
1327 void expairseq::drop_coeff_0_terms(epvector::iterator &first_numeric,
1328 epvector::iterator &last_non_zero,
1329 std::vector<bool> &touched,
1330 unsigned &number_of_zeroes)
1332 // move terms with coeff 0 to end and remove them from hashtab
1333 // check only those elements which have been touched
1334 epp current = seq.begin();
1336 while (current!=first_numeric) {
1340 } else if (!ex_to<numeric>((*current).coeff).is_zero()) {
1344 remove_hashtab_entry(current);
1346 // move element to the end, unless it is already at the end
1347 if (current!=last_non_zero) {
1348 iter_swap(current,last_non_zero);
1350 bool numeric_swapped = first_numeric!=last_non_zero;
1351 if (numeric_swapped)
1352 iter_swap(first_numeric,current);
1353 epvector::iterator changed_entry;
1355 if (numeric_swapped)
1356 changed_entry = first_numeric;
1358 changed_entry = last_non_zero;
1363 if (first_numeric!=current) {
1365 // change entry in hashtab which referred to first_numeric or last_non_zero to current
1366 move_hashtab_entry(changed_entry,current);
1367 touched[current-seq.begin()] = touched[changed_entry-seq.begin()];
1376 GINAC_ASSERT(i==current-seq.begin());
1379 /** True if one of the coeffs vanishes, otherwise false.
1380 * This would be an invariant violation, so this should only be used for
1381 * debugging purposes. */
1382 bool expairseq::has_coeff_0() const
1384 epvector::const_iterator i = seq.begin(), end = seq.end();
1386 if (i->coeff.is_zero())
1393 void expairseq::add_numerics_to_hashtab(epvector::iterator first_numeric,
1394 epvector::const_iterator last_non_zero)
1396 if (first_numeric == seq.end()) return; // no numerics
1398 epvector::const_iterator current = first_numeric, last = last_non_zero + 1;
1399 while (current != last) {
1400 sorted_insert(hashtab[hashmask], current);
1405 void expairseq::combine_same_terms()
1407 // combine same terms, drop term with coeff 0, move numerics to end
1409 // calculate size of hashtab
1410 hashtabsize = calc_hashtabsize(seq.size());
1412 // hashtabsize is a power of 2
1413 hashmask = hashtabsize-1;
1417 hashtab.resize(hashtabsize);
1419 if (hashtabsize==0) {
1421 combine_same_terms_sorted_seq();
1422 GINAC_ASSERT(!has_coeff_0());
1426 // iterate through seq, move numerics to end,
1427 // fill hashtab and combine same terms
1428 epvector::iterator first_numeric = seq.end();
1429 epvector::iterator last_non_zero = seq.end()-1;
1431 size_t num = seq.size();
1432 std::vector<bool> touched(num);
1434 unsigned number_of_zeroes = 0;
1436 GINAC_ASSERT(!has_coeff_0());
1437 build_hashtab_and_combine(first_numeric,last_non_zero,touched,number_of_zeroes);
1439 // there should not be any terms with coeff 0 from the beginning,
1440 // so it should be safe to skip this step
1441 if (number_of_zeroes!=0) {
1442 drop_coeff_0_terms(first_numeric,last_non_zero,touched,number_of_zeroes);
1445 add_numerics_to_hashtab(first_numeric,last_non_zero);
1447 // pop zero elements
1448 for (unsigned i=0; i<number_of_zeroes; ++i) {
1452 // shrink hashtabsize to calculated value
1453 GINAC_ASSERT(!has_coeff_0());
1457 GINAC_ASSERT(!has_coeff_0());
1460 #endif // EXPAIRSEQ_USE_HASHTAB
1462 /** Check if this expairseq is in sorted (canonical) form. Useful mainly for
1463 * debugging or in assertions since being sorted is an invariance. */
1464 bool expairseq::is_canonical() const
1466 if (seq.size() <= 1)
1469 #if EXPAIRSEQ_USE_HASHTAB
1470 if (hashtabsize > 0) return 1; // not canoncalized
1471 #endif // EXPAIRSEQ_USE_HASHTAB
1473 epvector::const_iterator it = seq.begin(), itend = seq.end();
1474 epvector::const_iterator it_last = it;
1475 for (++it; it!=itend; it_last=it, ++it) {
1476 if (!(it_last->is_less(*it) || it_last->is_equal(*it))) {
1477 if (!is_exactly_a<numeric>(it_last->rest) ||
1478 !is_exactly_a<numeric>(it->rest)) {
1479 // double test makes it easier to set a breakpoint...
1480 if (!is_exactly_a<numeric>(it_last->rest) ||
1481 !is_exactly_a<numeric>(it->rest)) {
1482 printpair(std::clog, *it_last, 0);
1484 printpair(std::clog, *it, 0);
1486 std::clog << "pair1:" << std::endl;
1487 it_last->rest.print(print_tree(std::clog));
1488 it_last->coeff.print(print_tree(std::clog));
1489 std::clog << "pair2:" << std::endl;
1490 it->rest.print(print_tree(std::clog));
1491 it->coeff.print(print_tree(std::clog));
1501 /** Member-wise expand the expairs in this sequence.
1503 * @see expairseq::expand()
1504 * @return pointer to epvector containing expanded pairs or zero pointer,
1505 * if no members were changed. */
1506 std::auto_ptr<epvector> expairseq::expandchildren(unsigned options) const
1508 const epvector::const_iterator last = seq.end();
1509 epvector::const_iterator cit = seq.begin();
1511 const ex &expanded_ex = cit->rest.expand(options);
1512 if (!are_ex_trivially_equal(cit->rest,expanded_ex)) {
1514 // something changed, copy seq, eval and return it
1515 std::auto_ptr<epvector> s(new epvector);
1516 s->reserve(seq.size());
1518 // copy parts of seq which are known not to have changed
1519 epvector::const_iterator cit2 = seq.begin();
1521 s->push_back(*cit2);
1525 // copy first changed element
1526 s->push_back(combine_ex_with_coeff_to_pair(expanded_ex,
1531 while (cit2!=last) {
1532 s->push_back(combine_ex_with_coeff_to_pair(cit2->rest.expand(options),
1541 return std::auto_ptr<epvector>(0); // signalling nothing has changed
1545 /** Member-wise evaluate the expairs in this sequence.
1547 * @see expairseq::eval()
1548 * @return pointer to epvector containing evaluated pairs or zero pointer,
1549 * if no members were changed. */
1550 std::auto_ptr<epvector> expairseq::evalchildren(int level) const
1552 // returns a NULL pointer if nothing had to be evaluated
1553 // returns a pointer to a newly created epvector otherwise
1554 // (which has to be deleted somewhere else)
1557 return std::auto_ptr<epvector>(0);
1559 if (level == -max_recursion_level)
1560 throw(std::runtime_error("max recursion level reached"));
1563 epvector::const_iterator last = seq.end();
1564 epvector::const_iterator cit = seq.begin();
1566 const ex &evaled_ex = cit->rest.eval(level);
1567 if (!are_ex_trivially_equal(cit->rest,evaled_ex)) {
1569 // something changed, copy seq, eval and return it
1570 std::auto_ptr<epvector> s(new epvector);
1571 s->reserve(seq.size());
1573 // copy parts of seq which are known not to have changed
1574 epvector::const_iterator cit2=seq.begin();
1576 s->push_back(*cit2);
1580 // copy first changed element
1581 s->push_back(combine_ex_with_coeff_to_pair(evaled_ex,
1586 while (cit2!=last) {
1587 s->push_back(combine_ex_with_coeff_to_pair(cit2->rest.eval(level),
1596 return std::auto_ptr<epvector>(0); // signalling nothing has changed
1600 /** Member-wise substitute in this sequence.
1602 * @see expairseq::subs()
1603 * @return pointer to epvector containing pairs after application of subs,
1604 * or NULL pointer if no members were changed. */
1605 std::auto_ptr<epvector> expairseq::subschildren(const exmap & m, unsigned options) const
1607 // When any of the objects to be substituted is a product or power
1608 // we have to recombine the pairs because the numeric coefficients may
1609 // be part of the search pattern.
1610 if (!(options & (subs_options::pattern_is_product | subs_options::pattern_is_not_product))) {
1612 // Search the list of substitutions and cache our findings
1613 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
1614 if (is_exactly_a<mul>(it->first) || is_exactly_a<power>(it->first)) {
1615 options |= subs_options::pattern_is_product;
1619 if (!(options & subs_options::pattern_is_product))
1620 options |= subs_options::pattern_is_not_product;
1623 if (options & subs_options::pattern_is_product) {
1625 // Substitute in the recombined pairs
1626 epvector::const_iterator cit = seq.begin(), last = seq.end();
1627 while (cit != last) {
1629 const ex &orig_ex = recombine_pair_to_ex(*cit);
1630 const ex &subsed_ex = orig_ex.subs(m, options);
1631 if (!are_ex_trivially_equal(orig_ex, subsed_ex)) {
1633 // Something changed, copy seq, subs and return it
1634 std::auto_ptr<epvector> s(new epvector);
1635 s->reserve(seq.size());
1637 // Copy parts of seq which are known not to have changed
1638 s->insert(s->begin(), seq.begin(), cit);
1640 // Copy first changed element
1641 s->push_back(split_ex_to_pair(subsed_ex));
1645 while (cit != last) {
1646 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit).subs(m, options)));
1657 // Substitute only in the "rest" part of the pairs
1658 epvector::const_iterator cit = seq.begin(), last = seq.end();
1659 while (cit != last) {
1661 const ex &subsed_ex = cit->rest.subs(m, options);
1662 if (!are_ex_trivially_equal(cit->rest, subsed_ex)) {
1664 // Something changed, copy seq, subs and return it
1665 std::auto_ptr<epvector> s(new epvector);
1666 s->reserve(seq.size());
1668 // Copy parts of seq which are known not to have changed
1669 s->insert(s->begin(), seq.begin(), cit);
1671 // Copy first changed element
1672 s->push_back(combine_ex_with_coeff_to_pair(subsed_ex, cit->coeff));
1676 while (cit != last) {
1677 s->push_back(combine_ex_with_coeff_to_pair(cit->rest.subs(m, options),
1688 // Nothing has changed
1689 return std::auto_ptr<epvector>(0);
1693 // static member variables
1696 #if EXPAIRSEQ_USE_HASHTAB
1697 unsigned expairseq::maxhashtabsize = 0x4000000U;
1698 unsigned expairseq::minhashtabsize = 0x1000U;
1699 unsigned expairseq::hashtabfactor = 1;
1700 #endif // EXPAIRSEQ_USE_HASHTAB
1702 } // namespace GiNaC