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