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"
33 #if EXPAIRSEQ_USE_HASHTAB
35 #endif // EXPAIRSEQ_USE_HASHTAB
39 GINAC_IMPLEMENT_REGISTERED_CLASS_NO_CTORS(expairseq, basic)
48 bool operator()(const epp &lh, const epp &rh) const
50 return (*lh).is_less(*rh);
55 // default ctor, dtor, copy ctor assignment operator and helpers
60 expairseq::expairseq(const expairseq &other)
62 debugmsg("expairseq copy ctor",LOGLEVEL_CONSTRUCT);
66 const expairseq &expairseq::operator=(const expairseq &other)
68 debugmsg("expairseq operator=",LOGLEVEL_ASSIGNMENT);
78 /** For use by copy ctor and assignment operator. */
79 void expairseq::copy(const expairseq &other)
81 inherited::copy(other);
83 overall_coeff = other.overall_coeff;
84 #if EXPAIRSEQ_USE_HASHTAB
86 hashtabsize = other.hashtabsize;
88 hashmask = other.hashmask;
89 hashtab.resize(hashtabsize);
90 epvector::const_iterator osb = other.seq.begin();
91 for (unsigned i=0; i<hashtabsize; ++i) {
93 for (epplist::const_iterator cit=other.hashtab[i].begin();
94 cit!=other.hashtab[i].end(); ++cit) {
95 hashtab[i].push_back(seq.begin()+((*cit)-osb));
101 #endif // EXPAIRSEQ_USE_HASHTAB
104 void expairseq::destroy(bool call_parent)
107 basic::destroy(call_parent);
114 expairseq::expairseq(const ex &lh, const ex &rh) : inherited(TINFO_expairseq)
116 debugmsg("expairseq ctor from ex,ex",LOGLEVEL_CONSTRUCT);
117 construct_from_2_ex(lh,rh);
118 GINAC_ASSERT(is_canonical());
121 expairseq::expairseq(const exvector &v) : inherited(TINFO_expairseq)
123 debugmsg("expairseq ctor from exvector",LOGLEVEL_CONSTRUCT);
124 construct_from_exvector(v);
125 GINAC_ASSERT(is_canonical());
128 expairseq::expairseq(const epvector &v, const ex &oc)
129 : inherited(TINFO_expairseq), overall_coeff(oc)
131 debugmsg("expairseq ctor from epvector,ex",LOGLEVEL_CONSTRUCT);
132 construct_from_epvector(v);
133 GINAC_ASSERT(is_canonical());
136 expairseq::expairseq(epvector *vp, const ex &oc)
137 : inherited(TINFO_expairseq), overall_coeff(oc)
139 debugmsg("expairseq ctor from epvector *,ex",LOGLEVEL_CONSTRUCT);
141 construct_from_epvector(*vp);
143 GINAC_ASSERT(is_canonical());
150 /** Construct object from archive_node. */
151 expairseq::expairseq(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
152 #if EXPAIRSEQ_USE_HASHTAB
156 debugmsg("expairseq ctor from archive_node", LOGLEVEL_CONSTRUCT);
157 for (unsigned int i=0; true; i++) {
160 if (n.find_ex("rest", rest, sym_lst, i) && n.find_ex("coeff", coeff, sym_lst, i))
161 seq.push_back(expair(rest, coeff));
165 n.find_ex("overall_coeff", overall_coeff, sym_lst);
168 /** Unarchive the object. */
169 ex expairseq::unarchive(const archive_node &n, const lst &sym_lst)
171 return (new expairseq(n, sym_lst))->setflag(status_flags::dynallocated);
174 /** Archive the object. */
175 void expairseq::archive(archive_node &n) const
177 inherited::archive(n);
178 epvector::const_iterator i = seq.begin(), iend = seq.end();
180 n.add_ex("rest", i->rest);
181 n.add_ex("coeff", i->coeff);
184 n.add_ex("overall_coeff", overall_coeff);
188 // functions overriding virtual functions from bases classes
193 basic *expairseq::duplicate() const
195 debugmsg("expairseq duplicate",LOGLEVEL_DUPLICATE);
196 return new expairseq(*this);
199 void expairseq::print(std::ostream &os, unsigned upper_precedence) const
201 debugmsg("expairseq print",LOGLEVEL_PRINT);
203 printseq(os,',',precedence,upper_precedence);
207 void expairseq::printraw(std::ostream &os) const
209 debugmsg("expairseq printraw",LOGLEVEL_PRINT);
212 for (epvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
214 (*cit).rest.printraw(os);
216 (*cit).coeff.printraw(os);
222 void expairseq::printtree(std::ostream &os, unsigned indent) const
224 debugmsg("expairseq printtree",LOGLEVEL_PRINT);
226 os << std::string(indent,' ') << "type=" << class_name()
227 << ", hash=" << hashvalue
228 << " (0x" << std::hex << hashvalue << std::dec << ")"
229 << ", flags=" << flags
230 << ", nops=" << nops() << std::endl;
231 for (unsigned i=0; i<seq.size(); ++i) {
232 seq[i].rest.printtree(os,indent+delta_indent);
233 seq[i].coeff.printtree(os,indent+delta_indent);
235 os << std::string(indent+delta_indent,' ') << "-----" << std::endl;
237 if (!overall_coeff.is_equal(default_overall_coeff())) {
238 os << std::string(indent+delta_indent,' ') << "-----" << std::endl;
239 os << std::string(indent+delta_indent,' ') << "overall_coeff" << std::endl;
240 overall_coeff.printtree(os,indent+delta_indent);
242 os << std::string(indent+delta_indent,' ') << "=====" << std::endl;
243 #if EXPAIRSEQ_USE_HASHTAB
244 os << std::string(indent+delta_indent,' ')
245 << "hashtab size " << hashtabsize << std::endl;
246 if (hashtabsize==0) return;
248 unsigned count[MAXCOUNT+1];
249 for (int i=0; i<MAXCOUNT+1; ++i)
251 unsigned this_bin_fill;
252 unsigned cum_fill_sq = 0;
253 unsigned cum_fill = 0;
254 for (unsigned i=0; i<hashtabsize; ++i) {
256 if (hashtab[i].size()>0) {
257 os << std::string(indent+delta_indent,' ')
258 << "bin " << i << " with entries ";
259 for (epplist::const_iterator it=hashtab[i].begin();
260 it!=hashtab[i].end(); ++it) {
261 os << *it-seq.begin() << " ";
265 cum_fill += this_bin_fill;
266 cum_fill_sq += this_bin_fill*this_bin_fill;
268 if (this_bin_fill<MAXCOUNT)
269 ++count[this_bin_fill];
275 double lambda = (1.0*seq.size())/hashtabsize;
276 for (int k=0; k<MAXCOUNT; ++k) {
279 double prob = std::pow(lambda,k)/fact * std::exp(-lambda);
281 os << std::string(indent+delta_indent,' ') << "bins with " << k << " entries: "
282 << int(1000.0*count[k]/hashtabsize)/10.0 << "% (expected: "
283 << int(prob*1000)/10.0 << ")" << std::endl;
285 os << std::string(indent+delta_indent,' ') << "bins with more entries: "
286 << int(1000.0*count[MAXCOUNT]/hashtabsize)/10.0 << "% (expected: "
287 << int((1-cum_prob)*1000)/10.0 << ")" << std::endl;
289 os << std::string(indent+delta_indent,' ') << "variance: "
290 << 1.0/hashtabsize*cum_fill_sq-(1.0/hashtabsize*cum_fill)*(1.0/hashtabsize*cum_fill)
292 os << std::string(indent+delta_indent,' ') << "average fill: "
293 << (1.0*cum_fill)/hashtabsize
294 << " (should be equal to " << (1.0*seq.size())/hashtabsize << ")" << std::endl;
295 #endif // EXPAIRSEQ_USE_HASHTAB
298 bool expairseq::info(unsigned inf) const
300 return inherited::info(inf);
303 unsigned expairseq::nops() const
305 if (overall_coeff.is_equal(default_overall_coeff()))
311 ex expairseq::op(int i) const
313 if (unsigned(i)<seq.size())
314 return recombine_pair_to_ex(seq[i]);
315 GINAC_ASSERT(!overall_coeff.is_equal(default_overall_coeff()));
316 return overall_coeff;
319 ex &expairseq::let_op(int i)
321 throw(std::logic_error("let_op not defined for expairseq and derived classes (add,mul,...)"));
324 ex expairseq::eval(int level) const
326 if ((level==1) && (flags &status_flags::evaluated))
329 epvector *vp = evalchildren(level);
333 return (new expairseq(vp,overall_coeff))->setflag(status_flags::dynallocated | status_flags::evaluated);
336 ex expairseq::evalf(int level) const
338 return thisexpairseq(evalfchildren(level),overall_coeff.evalf(level-1));
341 ex expairseq::normal(lst &sym_lst, lst &repl_lst, int level) const
343 ex n = thisexpairseq(normalchildren(level),overall_coeff);
344 return n.bp->basic::normal(sym_lst,repl_lst,level);
347 ex expairseq::subs(const lst &ls, const lst &lr) const
349 epvector *vp = subschildren(ls,lr);
353 return thisexpairseq(vp,overall_coeff);
358 /** Implementation of ex::diff() for an expairseq.
359 * It differentiates all elements of the sequence.
361 ex expairseq::derivative(const symbol &s) const
363 return thisexpairseq(diffchildren(s),overall_coeff);
366 int expairseq::compare_same_type(const basic &other) const
368 GINAC_ASSERT(is_of_type(other, expairseq));
369 const expairseq &o = static_cast<const expairseq &>(const_cast<basic &>(other));
373 // compare number of elements
374 if (seq.size() != o.seq.size())
375 return (seq.size()<o.seq.size()) ? -1 : 1;
377 // compare overall_coeff
378 cmpval = overall_coeff.compare(o.overall_coeff);
382 #if EXPAIRSEQ_USE_HASHTAB
383 GINAC_ASSERT(hashtabsize==o.hashtabsize);
384 if (hashtabsize==0) {
385 #endif // EXPAIRSEQ_USE_HASHTAB
386 epvector::const_iterator cit1 = seq.begin();
387 epvector::const_iterator cit2 = o.seq.begin();
388 epvector::const_iterator last1 = seq.end();
389 epvector::const_iterator last2 = o.seq.end();
391 for (; (cit1!=last1)&&(cit2!=last2); ++cit1, ++cit2) {
392 cmpval = (*cit1).compare(*cit2);
393 if (cmpval!=0) return cmpval;
396 GINAC_ASSERT(cit1==last1);
397 GINAC_ASSERT(cit2==last2);
400 #if EXPAIRSEQ_USE_HASHTAB
403 // compare number of elements in each hashtab entry
404 for (unsigned i=0; i<hashtabsize; ++i) {
405 unsigned cursize=hashtab[i].size();
406 if (cursize != o.hashtab[i].size())
407 return (cursize < o.hashtab[i].size()) ? -1 : 1;
410 // compare individual (sorted) hashtab entries
411 for (unsigned i=0; i<hashtabsize; ++i) {
412 unsigned sz = hashtab[i].size();
414 const epplist &eppl1 = hashtab[i];
415 const epplist &eppl2 = o.hashtab[i];
416 epplist::const_iterator it1 = eppl1.begin();
417 epplist::const_iterator it2 = eppl2.begin();
418 while (it1!=eppl1.end()) {
419 cmpval = (*(*it1)).compare(*(*it2));
429 #endif // EXPAIRSEQ_USE_HASHTAB
432 bool expairseq::is_equal_same_type(const basic &other) const
434 const expairseq &o = dynamic_cast<const expairseq &>(const_cast<basic &>(other));
436 // compare number of elements
437 if (seq.size()!=o.seq.size())
440 // compare overall_coeff
441 if (!overall_coeff.is_equal(o.overall_coeff))
444 #if EXPAIRSEQ_USE_HASHTAB
445 // compare number of elements in each hashtab entry
446 if (hashtabsize!=o.hashtabsize) {
447 std::cout << "this:" << std::endl;
448 printtree(std::cout,0);
449 std::cout << "other:" << std::endl;
450 other.printtree(std::cout,0);
453 GINAC_ASSERT(hashtabsize==o.hashtabsize);
455 if (hashtabsize==0) {
456 #endif // EXPAIRSEQ_USE_HASHTAB
457 epvector::const_iterator cit1 = seq.begin();
458 epvector::const_iterator cit2 = o.seq.begin();
459 epvector::const_iterator last1 = seq.end();
461 while (cit1!=last1) {
462 if (!(*cit1).is_equal(*cit2)) return false;
468 #if EXPAIRSEQ_USE_HASHTAB
471 for (unsigned i=0; i<hashtabsize; ++i) {
472 if (hashtab[i].size() != o.hashtab[i].size())
476 // compare individual sorted hashtab entries
477 for (unsigned i=0; i<hashtabsize; ++i) {
478 unsigned sz = hashtab[i].size();
480 const epplist &eppl1 = hashtab[i];
481 const epplist &eppl2 = o.hashtab[i];
482 epplist::const_iterator it1 = eppl1.begin();
483 epplist::const_iterator it2 = eppl2.begin();
484 while (it1!=eppl1.end()) {
485 if (!(*(*it1)).is_equal(*(*it2))) return false;
493 #endif // EXPAIRSEQ_USE_HASHTAB
496 unsigned expairseq::return_type(void) const
498 return return_types::noncommutative_composite;
501 unsigned expairseq::calchash(void) const
503 unsigned v = golden_ratio_hash(tinfo());
504 for (epvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
505 #if !EXPAIRSEQ_USE_HASHTAB
506 v = rotate_left_31(v); // rotation would spoil commutativity
507 #endif // EXPAIRSEQ_USE_HASHTAB
508 v ^= cit->rest.gethash();
509 #if !EXPAIRSEQ_USE_HASHTAB
510 v = rotate_left_31(v);
511 v ^= cit->coeff.gethash();
512 #endif // EXPAIRSEQ_USE_HASHTAB
515 v ^= overall_coeff.gethash();
518 // store calculated hash value only if object is already evaluated
519 if (flags &status_flags::evaluated) {
520 setflag(status_flags::hash_calculated);
527 ex expairseq::expand(unsigned options) const
529 epvector *vp = expandchildren(options);
531 // the terms have not changed, so it is safe to declare this expanded
532 setflag(status_flags::expanded);
536 return thisexpairseq(vp,overall_coeff);
540 // new virtual functions which can be overridden by derived classes
545 /** Create an object of this type.
546 * This method works similar to a constructor. It is useful because expairseq
547 * has (at least) two possible different semantics but we want to inherit
548 * methods thus avoiding code duplication. Sometimes a method in expairseq
549 * has to create a new one of the same semantics, which cannot be done by a
550 * ctor because the name (add, mul,...) is unknown on the expaiseq level. In
551 * order for this trick to work a derived class must of course override this
553 ex expairseq::thisexpairseq(const epvector &v, const ex &oc) const
555 return expairseq(v,oc);
558 ex expairseq::thisexpairseq(epvector *vp, const ex &oc) const
560 return expairseq(vp,oc);
563 void expairseq::printpair(std::ostream &os, const expair &p, unsigned upper_precedence) const
566 p.rest.bp->print(os,precedence);
568 p.coeff.bp->print(os,precedence);
572 void expairseq::printseq(std::ostream &os, char delim,
573 unsigned this_precedence,
574 unsigned upper_precedence) const
576 if (this_precedence<=upper_precedence)
578 epvector::const_iterator it,it_last;
581 for (it=seq.begin(); it!=it_last; ++it) {
582 printpair(os,*it,this_precedence);
585 printpair(os,*it,this_precedence);
586 if (!overall_coeff.is_equal(default_overall_coeff()))
587 os << delim << overall_coeff;
589 if (this_precedence<=upper_precedence)
594 /** Form an expair from an ex, using the corresponding semantics.
595 * @see expairseq::recombine_pair_to_ex() */
596 expair expairseq::split_ex_to_pair(const ex &e) const
598 return expair(e,_ex1());
602 expair expairseq::combine_ex_with_coeff_to_pair(const ex &e,
605 GINAC_ASSERT(is_ex_exactly_of_type(c,numeric));
611 expair expairseq::combine_pair_with_coeff_to_pair(const expair &p,
614 GINAC_ASSERT(is_ex_exactly_of_type(p.coeff,numeric));
615 GINAC_ASSERT(is_ex_exactly_of_type(c,numeric));
617 return expair(p.rest,ex_to_numeric(p.coeff).mul_dyn(ex_to_numeric(c)));
621 /** Form an ex out of an expair, using the corresponding semantics.
622 * @see expairseq::split_ex_to_pair() */
623 ex expairseq::recombine_pair_to_ex(const expair &p) const
625 return lst(p.rest,p.coeff);
628 bool expairseq::expair_needs_further_processing(epp it)
630 #if EXPAIRSEQ_USE_HASHTAB
631 //# error "FIXME: expair_needs_further_processing not yet implemented for hashtabs, sorry. A.F."
632 #endif // EXPAIRSEQ_USE_HASHTAB
636 ex expairseq::default_overall_coeff(void) const
641 void expairseq::combine_overall_coeff(const ex &c)
643 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
644 GINAC_ASSERT(is_ex_exactly_of_type(c,numeric));
645 overall_coeff = ex_to_numeric(overall_coeff).add_dyn(ex_to_numeric(c));
648 void expairseq::combine_overall_coeff(const ex &c1, const ex &c2)
650 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
651 GINAC_ASSERT(is_ex_exactly_of_type(c1,numeric));
652 GINAC_ASSERT(is_ex_exactly_of_type(c2,numeric));
653 overall_coeff = ex_to_numeric(overall_coeff).
654 add_dyn(ex_to_numeric(c1).mul(ex_to_numeric(c2)));
657 bool expairseq::can_make_flat(const expair &p) const
664 // non-virtual functions in this class
667 void expairseq::construct_from_2_ex_via_exvector(const ex &lh, const ex &rh)
673 construct_from_exvector(v);
674 #if EXPAIRSEQ_USE_HASHTAB
675 GINAC_ASSERT((hashtabsize==0)||(hashtabsize>=minhashtabsize));
676 GINAC_ASSERT(hashtabsize==calc_hashtabsize(seq.size()));
677 #endif // EXPAIRSEQ_USE_HASHTAB
680 void expairseq::construct_from_2_ex(const ex &lh, const ex &rh)
682 if (lh.bp->tinfo()==tinfo()) {
683 if (rh.bp->tinfo()==tinfo()) {
684 #if EXPAIRSEQ_USE_HASHTAB
685 unsigned totalsize = ex_to_expairseq(lh).seq.size() +
686 ex_to_expairseq(rh).seq.size();
687 if (calc_hashtabsize(totalsize)!=0) {
688 construct_from_2_ex_via_exvector(lh,rh);
690 #endif // EXPAIRSEQ_USE_HASHTAB
691 construct_from_2_expairseq(ex_to_expairseq(lh),
692 ex_to_expairseq(rh));
693 #if EXPAIRSEQ_USE_HASHTAB
695 #endif // EXPAIRSEQ_USE_HASHTAB
698 #if EXPAIRSEQ_USE_HASHTAB
699 unsigned totalsize = ex_to_expairseq(lh).seq.size()+1;
700 if (calc_hashtabsize(totalsize)!=0) {
701 construct_from_2_ex_via_exvector(lh, rh);
703 #endif // EXPAIRSEQ_USE_HASHTAB
704 construct_from_expairseq_ex(ex_to_expairseq(lh), rh);
705 #if EXPAIRSEQ_USE_HASHTAB
707 #endif // EXPAIRSEQ_USE_HASHTAB
710 } else if (rh.bp->tinfo()==tinfo()) {
711 #if EXPAIRSEQ_USE_HASHTAB
712 unsigned totalsize=ex_to_expairseq(rh).seq.size()+1;
713 if (calc_hashtabsize(totalsize)!=0) {
714 construct_from_2_ex_via_exvector(lh,rh);
716 #endif // EXPAIRSEQ_USE_HASHTAB
717 construct_from_expairseq_ex(ex_to_expairseq(rh),lh);
718 #if EXPAIRSEQ_USE_HASHTAB
720 #endif // EXPAIRSEQ_USE_HASHTAB
724 #if EXPAIRSEQ_USE_HASHTAB
725 if (calc_hashtabsize(2)!=0) {
726 construct_from_2_ex_via_exvector(lh,rh);
730 #endif // EXPAIRSEQ_USE_HASHTAB
732 if (is_ex_exactly_of_type(lh,numeric)) {
733 if (is_ex_exactly_of_type(rh,numeric)) {
734 combine_overall_coeff(lh);
735 combine_overall_coeff(rh);
737 combine_overall_coeff(lh);
738 seq.push_back(split_ex_to_pair(rh));
741 if (is_ex_exactly_of_type(rh,numeric)) {
742 combine_overall_coeff(rh);
743 seq.push_back(split_ex_to_pair(lh));
745 expair p1 = split_ex_to_pair(lh);
746 expair p2 = split_ex_to_pair(rh);
748 int cmpval = p1.rest.compare(p2.rest);
750 p1.coeff=ex_to_numeric(p1.coeff).add_dyn(ex_to_numeric(p2.coeff));
751 if (!ex_to_numeric(p1.coeff).is_zero()) {
752 // no further processing is necessary, since this
753 // one element will usually be recombined in eval()
770 void expairseq::construct_from_2_expairseq(const expairseq &s1,
773 combine_overall_coeff(s1.overall_coeff);
774 combine_overall_coeff(s2.overall_coeff);
776 epvector::const_iterator first1 = s1.seq.begin();
777 epvector::const_iterator last1 = s1.seq.end();
778 epvector::const_iterator first2 = s2.seq.begin();
779 epvector::const_iterator last2 = s2.seq.end();
781 seq.reserve(s1.seq.size()+s2.seq.size());
783 bool needs_further_processing=false;
785 while (first1!=last1 && first2!=last2) {
786 int cmpval = (*first1).rest.compare((*first2).rest);
789 const numeric &newcoeff = ex_to_numeric((*first1).coeff).
790 add(ex_to_numeric((*first2).coeff));
791 if (!newcoeff.is_zero()) {
792 seq.push_back(expair((*first1).rest,newcoeff));
793 if (expair_needs_further_processing(seq.end()-1)) {
794 needs_further_processing = true;
799 } else if (cmpval<0) {
800 seq.push_back(*first1);
803 seq.push_back(*first2);
808 while (first1!=last1) {
809 seq.push_back(*first1);
812 while (first2!=last2) {
813 seq.push_back(*first2);
817 if (needs_further_processing) {
820 construct_from_epvector(v);
824 void expairseq::construct_from_expairseq_ex(const expairseq &s,
827 combine_overall_coeff(s.overall_coeff);
828 if (is_ex_exactly_of_type(e,numeric)) {
829 combine_overall_coeff(e);
834 epvector::const_iterator first = s.seq.begin();
835 epvector::const_iterator last = s.seq.end();
836 expair p = split_ex_to_pair(e);
838 seq.reserve(s.seq.size()+1);
839 bool p_pushed = false;
841 bool needs_further_processing=false;
843 // merge p into s.seq
844 while (first!=last) {
845 int cmpval=(*first).rest.compare(p.rest);
848 const numeric &newcoeff = ex_to_numeric((*first).coeff).
849 add(ex_to_numeric(p.coeff));
850 if (!newcoeff.is_zero()) {
851 seq.push_back(expair((*first).rest,newcoeff));
852 if (expair_needs_further_processing(seq.end()-1)) {
853 needs_further_processing = true;
859 } else if (cmpval<0) {
860 seq.push_back(*first);
870 // while loop exited because p was pushed, now push rest of s.seq
871 while (first!=last) {
872 seq.push_back(*first);
876 // while loop exited because s.seq was pushed, now push p
880 if (needs_further_processing) {
883 construct_from_epvector(v);
887 void expairseq::construct_from_exvector(const exvector &v)
889 // simplifications: +(a,+(b,c),d) -> +(a,b,c,d) (associativity)
890 // +(d,b,c,a) -> +(a,b,c,d) (canonicalization)
891 // +(...,x,*(x,c1),*(x,c2)) -> +(...,*(x,1+c1+c2)) (c1, c2 numeric())
892 // (same for (+,*) -> (*,^)
895 #if EXPAIRSEQ_USE_HASHTAB
896 combine_same_terms();
899 combine_same_terms_sorted_seq();
900 #endif // EXPAIRSEQ_USE_HASHTAB
904 void expairseq::construct_from_epvector(const epvector &v)
906 // simplifications: +(a,+(b,c),d) -> +(a,b,c,d) (associativity)
907 // +(d,b,c,a) -> +(a,b,c,d) (canonicalization)
908 // +(...,x,*(x,c1),*(x,c2)) -> +(...,*(x,1+c1+c2)) (c1, c2 numeric())
909 // (same for (+,*) -> (*,^)
912 #if EXPAIRSEQ_USE_HASHTAB
913 combine_same_terms();
916 combine_same_terms_sorted_seq();
917 #endif // EXPAIRSEQ_USE_HASHTAB
921 /** Combine this expairseq with argument exvector.
922 * It cares for associativity as well as for special handling of numerics. */
923 void expairseq::make_flat(const exvector &v)
925 exvector::const_iterator cit;
927 // count number of operands which are of same expairseq derived type
928 // and their cumulative number of operands
933 while (cit!=v.end()) {
934 if (cit->bp->tinfo()==this->tinfo()) {
936 noperands += ex_to_expairseq(*cit).seq.size();
941 // reserve seq and coeffseq which will hold all operands
942 seq.reserve(v.size()+noperands-nexpairseqs);
944 // copy elements and split off numerical part
946 while (cit!=v.end()) {
947 if (cit->bp->tinfo()==this->tinfo()) {
948 const expairseq &subseqref = ex_to_expairseq(*cit);
949 combine_overall_coeff(subseqref.overall_coeff);
950 epvector::const_iterator cit_s = subseqref.seq.begin();
951 while (cit_s!=subseqref.seq.end()) {
952 seq.push_back(*cit_s);
956 if (is_ex_exactly_of_type(*cit,numeric))
957 combine_overall_coeff(*cit);
959 seq.push_back(split_ex_to_pair(*cit));
967 /** Combine this expairseq with argument epvector.
968 * It cares for associativity as well as for special handling of numerics. */
969 void expairseq::make_flat(const epvector &v)
971 epvector::const_iterator cit;
973 // count number of operands which are of same expairseq derived type
974 // and their cumulative number of operands
979 while (cit!=v.end()) {
980 if (cit->rest.bp->tinfo()==this->tinfo()) {
982 noperands += ex_to_expairseq((*cit).rest).seq.size();
987 // reserve seq and coeffseq which will hold all operands
988 seq.reserve(v.size()+noperands-nexpairseqs);
990 // copy elements and split off numerical part
992 while (cit!=v.end()) {
993 if (cit->rest.bp->tinfo()==this->tinfo() &&
994 this->can_make_flat(*cit)) {
995 const expairseq &subseqref = ex_to_expairseq((*cit).rest);
996 combine_overall_coeff(ex_to_numeric(subseqref.overall_coeff),
997 ex_to_numeric((*cit).coeff));
998 epvector::const_iterator cit_s = subseqref.seq.begin();
999 while (cit_s!=subseqref.seq.end()) {
1000 seq.push_back(expair((*cit_s).rest,
1001 ex_to_numeric((*cit_s).coeff).mul_dyn(ex_to_numeric((*cit).coeff))));
1002 //seq.push_back(combine_pair_with_coeff_to_pair(*cit_s,
1007 if (cit->is_canonical_numeric())
1008 combine_overall_coeff(cit->rest);
1010 seq.push_back(*cit);
1018 /** Brings this expairseq into a sorted (canonical) form. */
1019 void expairseq::canonicalize(void)
1022 sort(seq.begin(),seq.end(),expair_is_less());
1027 /** Compact a presorted expairseq by combining all matching expairs to one
1028 * each. On an add object, this is responsible for 2*x+3*x+y -> 5*x+y, for
1030 void expairseq::combine_same_terms_sorted_seq(void)
1032 bool needs_further_processing = false;
1035 epvector::iterator itin1 = seq.begin();
1036 epvector::iterator itin2 = itin1+1;
1037 epvector::iterator itout = itin1;
1038 epvector::iterator last = seq.end();
1039 // must_copy will be set to true the first time some combination is
1040 // possible from then on the sequence has changed and must be compacted
1041 bool must_copy = false;
1042 while (itin2!=last) {
1043 if ((*itin1).rest.compare((*itin2).rest)==0) {
1044 (*itin1).coeff = ex_to_numeric((*itin1).coeff).
1045 add_dyn(ex_to_numeric((*itin2).coeff));
1046 if (expair_needs_further_processing(itin1))
1047 needs_further_processing = true;
1050 if (!ex_to_numeric((*itin1).coeff).is_zero()) {
1059 if (!ex_to_numeric((*itin1).coeff).is_zero()) {
1065 seq.erase(itout,last);
1068 if (needs_further_processing) {
1071 construct_from_epvector(v);
1076 #if EXPAIRSEQ_USE_HASHTAB
1078 unsigned expairseq::calc_hashtabsize(unsigned sz) const
1081 unsigned nearest_power_of_2 = 1 << log2(sz);
1082 // if (nearest_power_of_2 < maxhashtabsize/hashtabfactor) {
1083 // size = nearest_power_of_2*hashtabfactor;
1084 size = nearest_power_of_2/hashtabfactor;
1085 if (size<minhashtabsize)
1087 GINAC_ASSERT(hashtabsize<=0x8000000U); // really max size due to 31 bit hashing
1088 // hashtabsize must be a power of 2
1089 GINAC_ASSERT((1U << log2(size))==size);
1093 unsigned expairseq::calc_hashindex(const ex &e) const
1095 // calculate hashindex
1096 unsigned hash = e.gethash();
1098 if (is_a_numeric_hash(hash)) {
1099 hashindex = hashmask;
1101 hashindex = hash &hashmask;
1102 // last hashtab entry is reserved for numerics
1103 if (hashindex==hashmask) hashindex = 0;
1105 GINAC_ASSERT(hashindex>=0);
1106 GINAC_ASSERT((hashindex<hashtabsize)||(hashtabsize==0));
1110 void expairseq::shrink_hashtab(void)
1112 unsigned new_hashtabsize;
1113 while (hashtabsize!=(new_hashtabsize=calc_hashtabsize(seq.size()))) {
1114 GINAC_ASSERT(new_hashtabsize<hashtabsize);
1115 if (new_hashtabsize==0) {
1122 // shrink by a factor of 2
1123 unsigned half_hashtabsize = hashtabsize/2;
1124 for (unsigned i=0; i<half_hashtabsize-1; ++i)
1125 hashtab[i].merge(hashtab[i+half_hashtabsize],epp_is_less());
1126 // special treatment for numeric hashes
1127 hashtab[0].merge(hashtab[half_hashtabsize-1],epp_is_less());
1128 hashtab[half_hashtabsize-1] = hashtab[hashtabsize-1];
1129 hashtab.resize(half_hashtabsize);
1130 hashtabsize = half_hashtabsize;
1131 hashmask = hashtabsize-1;
1135 void expairseq::remove_hashtab_entry(epvector::const_iterator element)
1138 return; // nothing to do
1140 // calculate hashindex of element to be deleted
1141 unsigned hashindex = calc_hashindex((*element).rest);
1143 // find it in hashtab and remove it
1144 epplist &eppl = hashtab[hashindex];
1145 epplist::iterator epplit = eppl.begin();
1146 bool erased = false;
1147 while (epplit!=eppl.end()) {
1148 if (*epplit == element) {
1157 cout << "tried to erase " << element-seq.begin() << std::endl;
1158 cout << "size " << seq.end()-seq.begin() << std::endl;
1160 unsigned hashindex = calc_hashindex((*element).rest);
1161 epplist &eppl = hashtab[hashindex];
1162 epplist::iterator epplit=eppl.begin();
1164 while (epplit!=eppl.end()) {
1165 if (*epplit == element) {
1172 GINAC_ASSERT(erased);
1174 GINAC_ASSERT(erased);
1177 void expairseq::move_hashtab_entry(epvector::const_iterator oldpos,
1178 epvector::iterator newpos)
1180 GINAC_ASSERT(hashtabsize!=0);
1182 // calculate hashindex of element which was moved
1183 unsigned hashindex=calc_hashindex((*newpos).rest);
1185 // find it in hashtab and modify it
1186 epplist &eppl = hashtab[hashindex];
1187 epplist::iterator epplit = eppl.begin();
1188 while (epplit!=eppl.end()) {
1189 if (*epplit == oldpos) {
1195 GINAC_ASSERT(epplit!=eppl.end());
1198 void expairseq::sorted_insert(epplist &eppl, epp elem)
1200 epplist::iterator current = eppl.begin();
1201 while ((current!=eppl.end())&&((*(*current)).is_less(*elem))) {
1204 eppl.insert(current,elem);
1207 void expairseq::build_hashtab_and_combine(epvector::iterator &first_numeric,
1208 epvector::iterator &last_non_zero,
1209 vector<bool> &touched,
1210 unsigned &number_of_zeroes)
1212 epp current=seq.begin();
1214 while (current!=first_numeric) {
1215 if (is_ex_exactly_of_type((*current).rest,numeric)) {
1217 iter_swap(current,first_numeric);
1219 // calculate hashindex
1220 unsigned currenthashindex = calc_hashindex((*current).rest);
1222 // test if there is already a matching expair in the hashtab-list
1223 epplist &eppl=hashtab[currenthashindex];
1224 epplist::iterator epplit = eppl.begin();
1225 while (epplit!=eppl.end()) {
1226 if ((*current).rest.is_equal((*(*epplit)).rest))
1230 if (epplit==eppl.end()) {
1231 // no matching expair found, append this to end of list
1232 sorted_insert(eppl,current);
1235 // epplit points to a matching expair, combine it with current
1236 (*(*epplit)).coeff = ex_to_numeric((*(*epplit)).coeff).
1237 add_dyn(ex_to_numeric((*current).coeff));
1239 // move obsolete current expair to end by swapping with last_non_zero element
1240 // if this was a numeric, it is swapped with the expair before first_numeric
1241 iter_swap(current,last_non_zero);
1243 if (first_numeric!=last_non_zero) iter_swap(first_numeric,current);
1246 // test if combined term has coeff 0 and can be removed is done later
1247 touched[(*epplit)-seq.begin()]=true;
1253 void expairseq::drop_coeff_0_terms(epvector::iterator &first_numeric,
1254 epvector::iterator &last_non_zero,
1255 vector<bool> &touched,
1256 unsigned &number_of_zeroes)
1258 // move terms with coeff 0 to end and remove them from hashtab
1259 // check only those elements which have been touched
1260 epp current = seq.begin();
1262 while (current!=first_numeric) {
1266 } else if (!ex_to_numeric((*current).coeff).is_zero()) {
1270 remove_hashtab_entry(current);
1272 // move element to the end, unless it is already at the end
1273 if (current!=last_non_zero) {
1274 iter_swap(current,last_non_zero);
1276 bool numeric_swapped=first_numeric!=last_non_zero;
1277 if (numeric_swapped) iter_swap(first_numeric,current);
1278 epvector::iterator changed_entry;
1280 if (numeric_swapped)
1281 changed_entry = first_numeric;
1283 changed_entry = last_non_zero;
1288 if (first_numeric!=current) {
1290 // change entry in hashtab which referred to first_numeric or last_non_zero to current
1291 move_hashtab_entry(changed_entry,current);
1292 touched[current-seq.begin()] = touched[changed_entry-seq.begin()];
1301 GINAC_ASSERT(i==current-seq.begin());
1304 /** True if one of the coeffs vanishes, otherwise false.
1305 * This would be an invariant violation, so this should only be used for
1306 * debugging purposes. */
1307 bool expairseq::has_coeff_0(void) const
1309 for (epvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
1310 if ((*cit).coeff.is_zero())
1316 void expairseq::add_numerics_to_hashtab(epvector::iterator first_numeric,
1317 epvector::const_iterator last_non_zero)
1319 if (first_numeric==seq.end()) return; // no numerics
1321 epvector::iterator current = first_numeric;
1322 epvector::const_iterator last = last_non_zero+1;
1323 while (current!=last) {
1324 sorted_insert(hashtab[hashmask],current);
1329 void expairseq::combine_same_terms(void)
1331 // combine same terms, drop term with coeff 0, move numerics to end
1333 // calculate size of hashtab
1334 hashtabsize = calc_hashtabsize(seq.size());
1336 // hashtabsize is a power of 2
1337 hashmask = hashtabsize-1;
1341 hashtab.resize(hashtabsize);
1343 if (hashtabsize==0) {
1345 combine_same_terms_sorted_seq();
1346 GINAC_ASSERT(!has_coeff_0());
1350 // iterate through seq, move numerics to end,
1351 // fill hashtab and combine same terms
1352 epvector::iterator first_numeric = seq.end();
1353 epvector::iterator last_non_zero = seq.end()-1;
1355 vector<bool> touched;
1356 touched.reserve(seq.size());
1357 for (unsigned i=0; i<seq.size(); ++i) touched[i]=false;
1359 unsigned number_of_zeroes = 0;
1361 GINAC_ASSERT(!has_coeff_0());
1362 build_hashtab_and_combine(first_numeric,last_non_zero,touched,number_of_zeroes);
1364 cout << "in combine:" << std::endl;
1366 cout << "size=" << seq.end() - seq.begin() << std::endl;
1367 cout << "first_numeric=" << first_numeric - seq.begin() << std::endl;
1368 cout << "last_non_zero=" << last_non_zero - seq.begin() << std::endl;
1369 for (unsigned i=0; i<seq.size(); ++i) {
1370 if (touched[i]) cout << i << " is touched" << std::endl;
1372 cout << "end in combine" << std::endl;
1375 // there should not be any terms with coeff 0 from the beginning,
1376 // so it should be safe to skip this step
1377 if (number_of_zeroes!=0) {
1378 drop_coeff_0_terms(first_numeric,last_non_zero,touched,number_of_zeroes);
1380 cout << "in combine after drop:" << std::endl;
1382 cout << "size=" << seq.end() - seq.begin() << std::endl;
1383 cout << "first_numeric=" << first_numeric - seq.begin() << std::endl;
1384 cout << "last_non_zero=" << last_non_zero - seq.begin() << std::endl;
1385 for (unsigned i=0; i<seq.size(); ++i) {
1386 if (touched[i]) cout << i << " is touched" << std::endl;
1388 cout << "end in combine after drop" << std::endl;
1392 add_numerics_to_hashtab(first_numeric,last_non_zero);
1394 // pop zero elements
1395 for (unsigned i=0; i<number_of_zeroes; ++i) {
1399 // shrink hashtabsize to calculated value
1400 GINAC_ASSERT(!has_coeff_0());
1404 GINAC_ASSERT(!has_coeff_0());
1407 #endif // EXPAIRSEQ_USE_HASHTAB
1409 /** Check if this expairseq is in sorted (canonical) form. Useful mainly for
1410 * debugging or in assertions since being sorted is an invariance. */
1411 bool expairseq::is_canonical() const
1416 #if EXPAIRSEQ_USE_HASHTAB
1417 if (hashtabsize>0) return 1; // not canoncalized
1418 #endif // EXPAIRSEQ_USE_HASHTAB
1420 epvector::const_iterator it = seq.begin();
1421 epvector::const_iterator it_last = it;
1422 for (++it; it!=seq.end(); it_last=it, ++it) {
1423 if (!((*it_last).is_less(*it)||(*it_last).is_equal(*it))) {
1424 if (!is_ex_exactly_of_type((*it_last).rest,numeric)||
1425 !is_ex_exactly_of_type((*it).rest,numeric)) {
1426 // double test makes it easier to set a breakpoint...
1427 if (!is_ex_exactly_of_type((*it_last).rest,numeric)||
1428 !is_ex_exactly_of_type((*it).rest,numeric)) {
1429 printpair(std::clog,*it_last,0);
1431 printpair(std::clog,*it,0);
1433 std::clog << "pair1:" << std::endl;
1434 (*it_last).rest.printtree(std::clog);
1435 (*it_last).coeff.printtree(std::clog);
1436 std::clog << "pair2:" << std::endl;
1437 (*it).rest.printtree(std::clog);
1438 (*it).coeff.printtree(std::clog);
1448 /** Member-wise expand the expairs in this sequence.
1450 * @see expairseq::expand()
1451 * @return pointer to epvector containing expanded pairs or zero pointer,
1452 * if no members were changed. */
1453 epvector * expairseq::expandchildren(unsigned options) const
1455 epvector::const_iterator last = seq.end();
1456 epvector::const_iterator cit = seq.begin();
1458 const ex &expanded_ex = (*cit).rest.expand(options);
1459 if (!are_ex_trivially_equal((*cit).rest,expanded_ex)) {
1461 // something changed, copy seq, eval and return it
1462 epvector *s = new epvector;
1463 s->reserve(seq.size());
1465 // copy parts of seq which are known not to have changed
1466 epvector::const_iterator cit2 = seq.begin();
1468 s->push_back(*cit2);
1471 // copy first changed element
1472 s->push_back(combine_ex_with_coeff_to_pair(expanded_ex,
1476 while (cit2!=last) {
1477 s->push_back(combine_ex_with_coeff_to_pair((*cit2).rest.expand(options),
1486 return 0; // signalling nothing has changed
1490 /** Member-wise evaluate the expairs in this sequence.
1492 * @see expairseq::eval()
1493 * @return pointer to epvector containing evaluated pairs or zero pointer,
1494 * if no members were changed. */
1495 epvector * expairseq::evalchildren(int level) const
1497 // returns a NULL pointer if nothing had to be evaluated
1498 // returns a pointer to a newly created epvector otherwise
1499 // (which has to be deleted somewhere else)
1504 if (level == -max_recursion_level)
1505 throw(std::runtime_error("max recursion level reached"));
1508 epvector::const_iterator last=seq.end();
1509 epvector::const_iterator cit=seq.begin();
1511 const ex &evaled_ex = (*cit).rest.eval(level);
1512 if (!are_ex_trivially_equal((*cit).rest,evaled_ex)) {
1514 // something changed, copy seq, eval and return it
1515 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);
1524 // copy first changed element
1525 s->push_back(combine_ex_with_coeff_to_pair(evaled_ex,
1529 while (cit2!=last) {
1530 s->push_back(combine_ex_with_coeff_to_pair((*cit2).rest.eval(level),
1539 return 0; // signalling nothing has changed
1543 /** Member-wise evaluate numerically all expairs in this sequence.
1545 * @see expairseq::evalf()
1546 * @return epvector with all entries evaluated numerically. */
1547 epvector expairseq::evalfchildren(int level) const
1552 if (level==-max_recursion_level)
1553 throw(std::runtime_error("max recursion level reached"));
1556 s.reserve(seq.size());
1559 for (epvector::const_iterator it=seq.begin(); it!=seq.end(); ++it) {
1560 s.push_back(combine_ex_with_coeff_to_pair((*it).rest.evalf(level),
1561 (*it).coeff.evalf(level)));
1567 /** Member-wise normalize all expairs in this sequence.
1569 * @see expairseq::normal()
1570 * @return epvector with all entries normalized. */
1571 epvector expairseq::normalchildren(int level) const
1576 if (level==-max_recursion_level)
1577 throw(std::runtime_error("max recursion level reached"));
1580 s.reserve(seq.size());
1583 for (epvector::const_iterator it=seq.begin(); it!=seq.end(); ++it) {
1584 s.push_back(combine_ex_with_coeff_to_pair((*it).rest.normal(level),
1591 /** Member-wise differentiate all expairs in this sequence.
1593 * @see expairseq::diff()
1594 * @return epvector with all entries differentiated. */
1595 epvector expairseq::diffchildren(const symbol &y) const
1598 s.reserve(seq.size());
1600 for (epvector::const_iterator it=seq.begin(); it!=seq.end(); ++it) {
1601 s.push_back(combine_ex_with_coeff_to_pair((*it).rest.diff(y),
1608 /** Member-wise substitute in this sequence.
1610 * @see expairseq::subs()
1611 * @return pointer to epvector containing pairs after application of subs or zero
1612 * pointer, if no members were changed. */
1613 epvector * expairseq::subschildren(const lst &ls, const lst &lr) const
1615 // returns a NULL pointer if nothing had to be substituted
1616 // returns a pointer to a newly created epvector otherwise
1617 // (which has to be deleted somewhere else)
1618 GINAC_ASSERT(ls.nops()==lr.nops());
1620 epvector::const_iterator last = seq.end();
1621 epvector::const_iterator cit = seq.begin();
1623 const ex &subsed_ex=(*cit).rest.subs(ls,lr);
1624 if (!are_ex_trivially_equal((*cit).rest,subsed_ex)) {
1626 // something changed, copy seq, subs and return it
1627 epvector *s = new epvector;
1628 s->reserve(seq.size());
1630 // copy parts of seq which are known not to have changed
1631 epvector::const_iterator cit2 = seq.begin();
1633 s->push_back(*cit2);
1636 // copy first changed element
1637 s->push_back(combine_ex_with_coeff_to_pair(subsed_ex,
1641 while (cit2!=last) {
1642 s->push_back(combine_ex_with_coeff_to_pair((*cit2).rest.subs(ls,lr),
1651 return 0; // signalling nothing has changed
1655 // static member variables
1660 unsigned expairseq::precedence = 10;
1662 #if EXPAIRSEQ_USE_HASHTAB
1663 unsigned expairseq::maxhashtabsize = 0x4000000U;
1664 unsigned expairseq::minhashtabsize = 0x1000U;
1665 unsigned expairseq::hashtabfactor = 1;
1666 #endif // EXPAIRSEQ_USE_HASHTAB
1668 } // namespace GiNaC