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