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