- introduced info_flags::cinteger, info_flags::crational,
[ginac.git] / ginac / ncmul.cpp
1 /** @file ncmul.cpp
2  *
3  *  Implementation of GiNaC's non-commutative products of expressions. */
4
5 /*
6  *  GiNaC Copyright (C) 1999 Johannes Gutenberg University Mainz, Germany
7  *
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.
12  *
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.
17  *
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
21  */
22
23 #include <algorithm>
24 #include <iostream>
25 #include <stdexcept>
26
27 #include "ncmul.h"
28 #include "ex.h"
29 #include "add.h"
30 #include "mul.h"
31 #include "debugmsg.h"
32
33 #ifndef NO_GINAC_NAMESPACE
34 namespace GiNaC {
35 #endif // ndef NO_GINAC_NAMESPACE
36
37 //////////
38 // default constructor, destructor, copy constructor assignment operator and helpers
39 //////////
40
41 // public
42
43 ncmul::ncmul()
44 {
45     debugmsg("ncmul default constructor",LOGLEVEL_CONSTRUCT);
46     tinfo_key = TINFO_ncmul;
47 }
48
49 ncmul::~ncmul()
50 {
51     debugmsg("ncmul destructor",LOGLEVEL_DESTRUCT);
52     destroy(0);
53 }
54
55 ncmul::ncmul(ncmul const & other)
56 {
57     debugmsg("ncmul copy constructor",LOGLEVEL_CONSTRUCT);
58     copy(other);
59 }
60
61 ncmul const & ncmul::operator=(ncmul const & other)
62 {
63     debugmsg("ncmul operator=",LOGLEVEL_ASSIGNMENT);
64     if (this != &other) {
65         destroy(1);
66         copy(other);
67     }
68     return *this;
69 }
70
71 // protected
72
73 void ncmul::copy(ncmul const & other)
74 {
75     exprseq::copy(other);
76 }
77
78 void ncmul::destroy(bool call_parent)
79 {
80     if (call_parent) exprseq::destroy(call_parent);
81 }
82
83 //////////
84 // other constructors
85 //////////
86
87 // public
88
89 ncmul::ncmul(ex const & lh, ex const & rh) :
90     exprseq(lh,rh)
91 {
92     debugmsg("ncmul constructor from ex,ex",LOGLEVEL_CONSTRUCT);
93     tinfo_key = TINFO_ncmul;
94 }
95
96 ncmul::ncmul(ex const & f1, ex const & f2, ex const & f3) :
97     exprseq(f1,f2,f3)
98 {
99     debugmsg("ncmul constructor from 3 ex",LOGLEVEL_CONSTRUCT);
100     tinfo_key = TINFO_ncmul;
101 }
102
103 ncmul::ncmul(ex const & f1, ex const & f2, ex const & f3,
104       ex const & f4) : exprseq(f1,f2,f3,f4)
105 {
106     debugmsg("ncmul constructor from 4 ex",LOGLEVEL_CONSTRUCT);
107     tinfo_key = TINFO_ncmul;
108 }
109
110 ncmul::ncmul(ex const & f1, ex const & f2, ex const & f3,
111       ex const & f4, ex const & f5) : exprseq(f1,f2,f3,f4,f5)
112 {
113     debugmsg("ncmul constructor from 5 ex",LOGLEVEL_CONSTRUCT);
114     tinfo_key = TINFO_ncmul;
115 }
116
117 ncmul::ncmul(ex const & f1, ex const & f2, ex const & f3,
118       ex const & f4, ex const & f5, ex const & f6) :
119     exprseq(f1,f2,f3,f4,f5,f6)
120 {
121     debugmsg("ncmul constructor from 6 ex",LOGLEVEL_CONSTRUCT);
122     tinfo_key = TINFO_ncmul;
123 }
124
125 ncmul::ncmul(exvector const & v, bool discardable) : exprseq(v,discardable)
126 {
127     debugmsg("ncmul constructor from exvector,bool",LOGLEVEL_CONSTRUCT);
128     tinfo_key = TINFO_ncmul;
129 }
130
131 ncmul::ncmul(exvector * vp) : exprseq(vp)
132 {
133     debugmsg("ncmul constructor from exvector *",LOGLEVEL_CONSTRUCT);
134     tinfo_key = TINFO_ncmul;
135 }
136     
137 //////////
138 // functions overriding virtual functions from bases classes
139 //////////
140
141 // public
142
143 basic * ncmul::duplicate() const
144 {
145     debugmsg("ncmul duplicate",LOGLEVEL_ASSIGNMENT);
146     return new ncmul(*this);
147 }
148
149 void ncmul::print(ostream & os, unsigned upper_precedence) const
150 {
151     debugmsg("ncmul print",LOGLEVEL_PRINT);
152     printseq(os,'(','%',')',precedence,upper_precedence);
153 }
154
155 void ncmul::printraw(ostream & os) const
156 {
157     debugmsg("ncmul printraw",LOGLEVEL_PRINT);
158
159     os << "%(";
160     for (exvector::const_iterator it=seq.begin(); it!=seq.end(); ++it) {
161         (*it).bp->printraw(os);
162         os << ",";
163     }
164     os << ",hash=" << hashvalue << ",flags=" << flags;
165     os << ")";
166 }
167
168 void ncmul::printcsrc(ostream & os, unsigned upper_precedence) const
169 {
170     debugmsg("ncmul print csrc",LOGLEVEL_PRINT);
171     exvector::const_iterator it;
172     exvector::const_iterator itend = seq.end()-1;
173     os << "ncmul(";
174     for (it=seq.begin(); it!=itend; ++it) {
175         (*it).bp->printcsrc(os,precedence);
176         os << ",";
177     }
178     (*it).bp->printcsrc(os,precedence);
179     os << ")";
180 }
181
182 bool ncmul::info(unsigned inf) const
183 {
184     throw(std::logic_error("which flags have to be implemented in ncmul::info()?"));
185 }
186
187 typedef vector<int> intvector;
188
189 ex ncmul::expand(unsigned options) const
190 {
191     exvector sub_expanded_seq;
192     intvector positions_of_adds;
193     intvector number_of_add_operands;
194
195     exvector expanded_seq=expandchildren(options);
196
197     positions_of_adds.resize(expanded_seq.size());
198     number_of_add_operands.resize(expanded_seq.size());
199
200     int number_of_adds=0;
201     int number_of_expanded_terms=1;
202
203     unsigned current_position=0;
204     exvector::const_iterator last=expanded_seq.end();
205     for (exvector::const_iterator cit=expanded_seq.begin(); cit!=last; ++cit) {
206         if (is_ex_exactly_of_type((*cit),add)) {
207             positions_of_adds[number_of_adds]=current_position;
208             add const & expanded_addref=ex_to_add(*cit);
209             number_of_add_operands[number_of_adds]=expanded_addref.seq.size();
210             number_of_expanded_terms *= expanded_addref.seq.size();
211             number_of_adds++;
212         }
213         current_position++;
214     }
215
216     if (number_of_adds==0) {
217         return (new ncmul(expanded_seq,1))->setflag(status_flags::dynallocated ||
218                                                     status_flags::expanded);
219     }
220
221     exvector distrseq;
222     distrseq.reserve(number_of_expanded_terms);
223
224     intvector k;
225     k.resize(number_of_adds);
226     
227     int l;
228     for (l=0; l<number_of_adds; l++) {
229         k[l]=0;
230     }
231
232     while (1) {
233         exvector term;
234         term=expanded_seq;
235         for (l=0; l<number_of_adds; l++) {
236             GINAC_ASSERT(is_ex_exactly_of_type(expanded_seq[positions_of_adds[l]],add));
237             add const & addref=ex_to_add(expanded_seq[positions_of_adds[l]]);
238             term[positions_of_adds[l]]=addref.recombine_pair_to_ex(addref.seq[k[l]]);
239         }
240         distrseq.push_back((new ncmul(term,1))->setflag(status_flags::dynallocated |
241                                                         status_flags::expanded));
242
243         // increment k[]
244         l=number_of_adds-1;
245         while ((l>=0)&&((++k[l])>=number_of_add_operands[l])) {
246             k[l]=0;    
247             l--;
248         }
249         if (l<0) break;
250     }
251
252     return (new add(distrseq))->setflag(status_flags::dynallocated |
253                                         status_flags::expanded);
254 }
255
256 int ncmul::degree(symbol const & s) const
257 {
258     int deg_sum=0;
259     for (exvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
260         deg_sum+=(*cit).degree(s);
261     }
262     return deg_sum;
263 }
264
265 int ncmul::ldegree(symbol const & s) const
266 {
267     int deg_sum=0;
268     for (exvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
269         deg_sum+=(*cit).ldegree(s);
270     }
271     return deg_sum;
272 }
273
274 ex ncmul::coeff(symbol const & s, int const n) const
275 {
276     exvector coeffseq;
277     coeffseq.reserve(seq.size());
278
279     if (n==0) {
280         // product of individual coeffs
281         // if a non-zero power of s is found, the resulting product will be 0
282         exvector::const_iterator it=seq.begin();
283         while (it!=seq.end()) {
284             coeffseq.push_back((*it).coeff(s,n));
285             ++it;
286         }
287         return (new ncmul(coeffseq,1))->setflag(status_flags::dynallocated);
288     }
289          
290     exvector::const_iterator it=seq.begin();
291     bool coeff_found=0;
292     while (it!=seq.end()) {
293         ex c=(*it).coeff(s,n);
294         if (!c.is_zero()) {
295             coeffseq.push_back(c);
296             coeff_found=1;
297         } else {
298             coeffseq.push_back(*it);
299         }
300         ++it;
301     }
302
303     if (coeff_found) return (new ncmul(coeffseq,1))->setflag(status_flags::dynallocated);
304     
305     return exZERO();
306 }
307
308 unsigned ncmul::count_factors(ex const & e) const
309 {
310     if ((is_ex_exactly_of_type(e,mul)&&(e.return_type()!=return_types::commutative))||
311         (is_ex_exactly_of_type(e,ncmul))) {
312         unsigned factors=0;
313         for (int i=0; i<e.nops(); i++) {
314             factors += count_factors(e.op(i));
315         }
316         return factors;
317     }
318     return 1;
319 }
320         
321 void ncmul::append_factors(exvector & v, ex const & e) const
322 {
323     if ((is_ex_exactly_of_type(e,mul)&&(e.return_type()!=return_types::commutative))||
324         (is_ex_exactly_of_type(e,ncmul))) {
325         for (int i=0; i<e.nops(); i++) {
326             append_factors(v,e.op(i));
327         }
328         return;
329     }
330     v.push_back(e);
331 }
332
333 typedef vector<unsigned> unsignedvector;
334 typedef vector<exvector> exvectorvector;
335
336 ex ncmul::eval(int level) const
337 {
338     // simplifications: ncmul(...,*(x1,x2),...,ncmul(x3,x4),...) ->
339     //                      ncmul(...,x1,x2,...,x3,x4,...) (associativity)
340     //                  ncmul(x) -> x
341     //                  ncmul() -> 1
342     //                  ncmul(...,c1,...,c2,...) ->
343     //                      *(c1,c2,ncmul(...)) (pull out commutative elements)
344     //                  ncmul(x1,y1,x2,y2) -> *(ncmul(x1,x2),ncmul(y1,y2))
345     //                      (collect elements of same type)
346     //                  ncmul(x1,x2,x3,...) -> x::eval_ncmul(x1,x2,x3,...)
347     // the following rule would be nice, but produces a recursion,
348     // which must be trapped by introducing a flag that the sub-ncmuls()
349     // are already evaluated (maybe later...)
350     //                  ncmul(x1,x2,...,X,y1,y2,...) ->
351     //                      ncmul(ncmul(x1,x2,...),X,ncmul(y1,y2,...)
352     //                      (X noncommutative_composite)
353
354     if ((level==1)&&(flags & status_flags::evaluated)) {
355         return *this;
356     }
357
358     exvector evaledseq=evalchildren(level);
359
360     // ncmul(...,*(x1,x2),...,ncmul(x3,x4),...) ->
361     //     ncmul(...,x1,x2,...,x3,x4,...) (associativity)
362     unsigned factors=0;
363     for (exvector::const_iterator cit=evaledseq.begin(); cit!=evaledseq.end(); ++cit) {
364         factors += count_factors(*cit);
365     }
366
367     exvector assocseq;
368     assocseq.reserve(factors);
369     for (exvector::const_iterator cit=evaledseq.begin(); cit!=evaledseq.end(); ++cit) {
370         append_factors(assocseq,*cit);
371     }
372
373     // ncmul(x) -> x
374     if (assocseq.size()==1) return *(seq.begin());
375
376     // ncmul() -> 1
377     if (assocseq.size()==0) return exONE();
378
379     // determine return types
380     unsignedvector rettypes;
381     rettypes.reserve(assocseq.size());
382     unsigned i=0;
383     unsigned count_commutative=0;
384     unsigned count_noncommutative=0;
385     unsigned count_noncommutative_composite=0;
386     for (exvector::const_iterator cit=assocseq.begin(); cit!=assocseq.end(); ++cit) {
387         switch (rettypes[i]=(*cit).return_type()) {
388         case return_types::commutative:
389             count_commutative++;
390             break;
391         case return_types::noncommutative:
392             count_noncommutative++;
393             break;
394         case return_types::noncommutative_composite:
395             count_noncommutative_composite++;
396             break;
397         default:
398             throw(std::logic_error("ncmul::eval(): invalid return type"));
399         }
400         ++i;
401     }
402     GINAC_ASSERT(count_commutative+count_noncommutative+count_noncommutative_composite==assocseq.size());
403
404     // ncmul(...,c1,...,c2,...) ->
405     //     *(c1,c2,ncmul(...)) (pull out commutative elements)
406     if (count_commutative!=0) {
407         exvector commutativeseq;
408         commutativeseq.reserve(count_commutative+1);
409         exvector noncommutativeseq;
410         noncommutativeseq.reserve(assocseq.size()-count_commutative);
411         for (i=0; i<assocseq.size(); ++i) {
412             if (rettypes[i]==return_types::commutative) {
413                 commutativeseq.push_back(assocseq[i]);
414             } else {
415                 noncommutativeseq.push_back(assocseq[i]);
416             }
417         }
418         commutativeseq.push_back((new ncmul(noncommutativeseq,1))->
419                                   setflag(status_flags::dynallocated));
420         return (new mul(commutativeseq))->setflag(status_flags::dynallocated);
421     }
422         
423     // ncmul(x1,y1,x2,y2) -> *(ncmul(x1,x2),ncmul(y1,y2))
424     //     (collect elements of same type)
425
426     if (count_noncommutative_composite==0) {
427         // there are neither commutative nor noncommutative_composite
428         // elements in assocseq
429         GINAC_ASSERT(count_commutative==0);
430
431         exvectorvector evv;
432         unsignedvector rttinfos;
433         evv.reserve(assocseq.size());
434         rttinfos.reserve(assocseq.size());
435
436         for (exvector::const_iterator cit=assocseq.begin(); cit!=assocseq.end(); ++cit) {
437             unsigned ti=(*cit).return_type_tinfo();
438             // search type in vector of known types
439             for (i=0; i<rttinfos.size(); ++i) {
440                 if (ti==rttinfos[i]) {
441                     evv[i].push_back(*cit);
442                     break;
443                 }
444             }
445             if (i>=rttinfos.size()) {
446                 // new type
447                 rttinfos.push_back(ti);
448                 evv.push_back(exvector());
449                 (*(evv.end()-1)).reserve(assocseq.size());
450                 (*(evv.end()-1)).push_back(*cit);
451             }
452         }
453
454 #ifdef DO_GINAC_ASSERT
455         GINAC_ASSERT(evv.size()==rttinfos.size());
456         GINAC_ASSERT(evv.size()>0);
457         unsigned s=0;
458         for (i=0; i<evv.size(); ++i) {
459             s += evv[i].size();
460         }
461         GINAC_ASSERT(s==assocseq.size());
462 #endif // def DO_GINAC_ASSERT
463         
464         // if all elements are of same type, simplify the string
465         if (evv.size()==1) {
466             return evv[0][0].simplify_ncmul(evv[0]);
467         }
468         
469         exvector splitseq;
470         splitseq.reserve(evv.size());
471         for (i=0; i<evv.size(); ++i) {
472             splitseq.push_back((new ncmul(evv[i]))->
473                                setflag(status_flags::dynallocated));
474         }
475
476         return (new mul(splitseq))->setflag(status_flags::dynallocated);
477     }
478     
479     return (new ncmul(assocseq))->setflag(status_flags::dynallocated |
480                                           status_flags::evaluated);
481 }
482
483 exvector ncmul::get_indices(void) const
484 {
485     // return union of indices of factors
486     exvector iv;
487     for (exvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
488         exvector subiv=(*cit).get_indices();
489         iv.reserve(iv.size()+subiv.size());
490         for (exvector::const_iterator cit2=subiv.begin(); cit2!=subiv.end(); ++cit2) {
491             iv.push_back(*cit2);
492         }
493     }
494     return iv;
495 }
496
497 ex ncmul::subs(lst const & ls, lst const & lr) const
498 {
499     return ncmul(subschildren(ls, lr));
500 }
501
502 ex ncmul::thisexprseq(exvector const & v) const
503 {
504     return (new ncmul(v))->setflag(status_flags::dynallocated);
505 }
506
507 ex ncmul::thisexprseq(exvector * vp) const
508 {
509     return (new ncmul(vp))->setflag(status_flags::dynallocated);
510 }
511
512 // protected
513
514 int ncmul::compare_same_type(basic const & other) const
515 {
516     return exprseq::compare_same_type(other);
517 }
518
519 unsigned ncmul::return_type(void) const
520 {
521     if (seq.size()==0) {
522         // ncmul without factors: should not happen, but commutes
523         return return_types::commutative;
524     }
525
526     bool all_commutative=1;
527     unsigned rt;
528     exvector::const_iterator cit_noncommutative_element; // point to first found nc element
529
530     for (exvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
531         rt=(*cit).return_type();
532         if (rt==return_types::noncommutative_composite) return rt; // one ncc -> mul also ncc
533         if ((rt==return_types::noncommutative)&&(all_commutative)) {
534             // first nc element found, remember position
535             cit_noncommutative_element=cit;
536             all_commutative=0;
537         }
538         if ((rt==return_types::noncommutative)&&(!all_commutative)) {
539             // another nc element found, compare type_infos
540             if ((*cit_noncommutative_element).return_type_tinfo()!=(*cit).return_type_tinfo()) {
541                 // diffent types -> mul is ncc
542                 return return_types::noncommutative_composite;
543             }
544         }
545     }
546     // all factors checked
547     GINAC_ASSERT(!all_commutative); // not all factors should commute, because this is a ncmul();
548     return all_commutative ? return_types::commutative : return_types::noncommutative;
549 }
550    
551 unsigned ncmul::return_type_tinfo(void) const
552 {
553     if (seq.size()==0) {
554         // mul without factors: should not happen
555         return tinfo_key;
556     }
557     // return type_info of first noncommutative element
558     for (exvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
559         if ((*cit).return_type()==return_types::noncommutative) {
560             return (*cit).return_type_tinfo();
561         }
562     }
563     // no noncommutative element found, should not happen
564     return tinfo_key;
565 }
566
567 //////////
568 // new virtual functions which can be overridden by derived classes
569 //////////
570
571 // none
572
573 //////////
574 // non-virtual functions in this class
575 //////////
576
577 exvector ncmul::expandchildren(unsigned options) const
578 {
579     exvector s;
580     s.reserve(seq.size());
581
582     for (exvector::const_iterator it=seq.begin(); it!=seq.end(); ++it) {
583         s.push_back((*it).expand(options));
584     }
585     return s;
586 }
587
588 exvector const & ncmul::get_factors(void) const
589 {
590     return seq;
591 }
592
593 //////////
594 // static member variables
595 //////////
596
597 // protected
598
599 unsigned ncmul::precedence=50;
600
601
602 //////////
603 // global constants
604 //////////
605
606 const ncmul some_ncmul;
607 type_info const & typeid_ncmul=typeid(some_ncmul);
608
609 //////////
610 // friend functions
611 //////////
612
613 ex nonsimplified_ncmul(exvector const & v)
614 {
615     return (new ncmul(v))->setflag(status_flags::dynallocated);
616 }
617
618 ex simplified_ncmul(exvector const & v)
619 {
620     if (v.size()==0) {
621         return exONE();
622     } else if (v.size()==1) {
623         return v[0];
624     }
625     return (new ncmul(v))->setflag(status_flags::dynallocated |
626                                    status_flags::evaluated);
627 }
628
629 #ifndef NO_GINAC_NAMESPACE
630 } // namespace GiNaC
631 #endif // ndef NO_GINAC_NAMESPACE