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