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