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