7874509e6abecf7f5a03bd4fbe63ef500ffb5328
[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         // Sum up degrees of factors
218         int deg_sum = 0;
219         exvector::const_iterator i = seq.begin(), end = seq.end();
220         while (i != end) {
221                 deg_sum += i->degree(s);
222                 ++i;
223         }
224         return deg_sum;
225 }
226
227 int ncmul::ldegree(const ex & s) const
228 {
229         // Sum up degrees of factors
230         int deg_sum = 0;
231         exvector::const_iterator i = seq.begin(), end = seq.end();
232         while (i != end) {
233                 deg_sum += i->degree(s);
234                 ++i;
235         }
236         return deg_sum;
237 }
238
239 ex ncmul::coeff(const ex & s, int 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 i = seq.begin(), end = seq.end();
256         bool coeff_found = false;
257         while (i != end) {
258                 ex c = i->coeff(s,n);
259                 if (c.is_zero()) {
260                         coeffseq.push_back(*i);
261                 } else {
262                         coeffseq.push_back(c);
263                         coeff_found = true;
264                 }
265                 ++i;
266         }
267
268         if (coeff_found) return (new ncmul(coeffseq,1))->setflag(status_flags::dynallocated);
269         
270         return _ex0();
271 }
272
273 unsigned ncmul::count_factors(const ex & 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 (unsigned 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, const ex & 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 (unsigned i=0; i<e.nops(); i++)
291                         append_factors(v,e.op(i));
292         } else 
293                 v.push_back(e);
294 }
295
296 typedef std::vector<unsigned> unsignedvector;
297 typedef std::vector<exvector> exvectorvector;
298
299 ex ncmul::eval(int level) const
300 {
301         // simplifications: ncmul(...,*(x1,x2),...,ncmul(x3,x4),...) ->
302         //                      ncmul(...,x1,x2,...,x3,x4,...) (associativity)
303         //                  ncmul(x) -> x
304         //                  ncmul() -> 1
305         //                  ncmul(...,c1,...,c2,...)
306         //                      *(c1,c2,ncmul(...)) (pull out commutative elements)
307         //                  ncmul(x1,y1,x2,y2) -> *(ncmul(x1,x2),ncmul(y1,y2))
308         //                      (collect elements of same type)
309         //                  ncmul(x1,x2,x3,...) -> x::simplify_ncmul(x1,x2,x3,...)
310         // the following rule would be nice, but produces a recursion,
311         // which must be trapped by introducing a flag that the sub-ncmuls()
312         // are already evaluated (maybe later...)
313         //                  ncmul(x1,x2,...,X,y1,y2,...) ->
314         //                      ncmul(ncmul(x1,x2,...),X,ncmul(y1,y2,...)
315         //                      (X noncommutative_composite)
316
317         if ((level==1) && (flags & status_flags::evaluated)) {
318                 return *this;
319         }
320
321         exvector evaledseq=evalchildren(level);
322
323         // ncmul(...,*(x1,x2),...,ncmul(x3,x4),...) ->
324         //     ncmul(...,x1,x2,...,x3,x4,...) (associativity)
325         unsigned factors = 0;
326         exvector::const_iterator cit = evaledseq.begin(), citend = evaledseq.end();
327         while (cit != citend)
328                 factors += count_factors(*cit++);
329         
330         exvector assocseq;
331         assocseq.reserve(factors);
332         cit = evaledseq.begin();
333         while (cit != citend)
334                 append_factors(assocseq, *cit++);
335         
336         // ncmul(x) -> x
337         if (assocseq.size()==1) return *(seq.begin());
338
339         // ncmul() -> 1
340         if (assocseq.empty()) return _ex1();
341
342         // determine return types
343         unsignedvector rettypes;
344         rettypes.reserve(assocseq.size());
345         unsigned i = 0;
346         unsigned count_commutative=0;
347         unsigned count_noncommutative=0;
348         unsigned count_noncommutative_composite=0;
349         cit = assocseq.begin(); citend = assocseq.end();
350         while (cit != citend) {
351                 switch (rettypes[i] = cit->return_type()) {
352                 case return_types::commutative:
353                         count_commutative++;
354                         break;
355                 case return_types::noncommutative:
356                         count_noncommutative++;
357                         break;
358                 case return_types::noncommutative_composite:
359                         count_noncommutative_composite++;
360                         break;
361                 default:
362                         throw(std::logic_error("ncmul::eval(): invalid return type"));
363                 }
364                 ++i; ++cit;
365         }
366         GINAC_ASSERT(count_commutative+count_noncommutative+count_noncommutative_composite==assocseq.size());
367
368         // ncmul(...,c1,...,c2,...) ->
369         //     *(c1,c2,ncmul(...)) (pull out commutative elements)
370         if (count_commutative!=0) {
371                 exvector commutativeseq;
372                 commutativeseq.reserve(count_commutative+1);
373                 exvector noncommutativeseq;
374                 noncommutativeseq.reserve(assocseq.size()-count_commutative);
375                 unsigned num = assocseq.size();
376                 for (unsigned i=0; i<num; ++i) {
377                         if (rettypes[i]==return_types::commutative)
378                                 commutativeseq.push_back(assocseq[i]);
379                         else
380                                 noncommutativeseq.push_back(assocseq[i]);
381                 }
382                 commutativeseq.push_back((new ncmul(noncommutativeseq,1))->setflag(status_flags::dynallocated));
383                 return (new mul(commutativeseq))->setflag(status_flags::dynallocated);
384         }
385                 
386         // ncmul(x1,y1,x2,y2) -> *(ncmul(x1,x2),ncmul(y1,y2))
387         //     (collect elements of same type)
388
389         if (count_noncommutative_composite==0) {
390                 // there are neither commutative nor noncommutative_composite
391                 // elements in assocseq
392                 GINAC_ASSERT(count_commutative==0);
393
394                 unsigned assoc_num = assocseq.size();
395                 exvectorvector evv;
396                 unsignedvector rttinfos;
397                 evv.reserve(assoc_num);
398                 rttinfos.reserve(assoc_num);
399
400                 cit = assocseq.begin(), citend = assocseq.end();
401                 while (cit != citend) {
402                         unsigned ti = cit->return_type_tinfo();
403                         unsigned rtt_num = rttinfos.size();
404                         // search type in vector of known types
405                         for (i=0; i<rtt_num; ++i) {
406                                 if (ti == rttinfos[i]) {
407                                         evv[i].push_back(*cit);
408                                         break;
409                                 }
410                         }
411                         if (i >= rtt_num) {
412                                 // new type
413                                 rttinfos.push_back(ti);
414                                 evv.push_back(exvector());
415                                 (evv.end()-1)->reserve(assoc_num);
416                                 (evv.end()-1)->push_back(*cit);
417                         }
418                         ++cit;
419                 }
420
421                 unsigned evv_num = evv.size();
422 #ifdef DO_GINAC_ASSERT
423                 GINAC_ASSERT(evv_num == rttinfos.size());
424                 GINAC_ASSERT(evv_num > 0);
425                 unsigned s=0;
426                 for (i=0; i<evv_num; ++i)
427                         s += evv[i].size();
428                 GINAC_ASSERT(s == assoc_num);
429 #endif // def DO_GINAC_ASSERT
430                 
431                 // if all elements are of same type, simplify the string
432                 if (evv_num == 1)
433                         return evv[0][0].simplify_ncmul(evv[0]);
434                 
435                 exvector splitseq;
436                 splitseq.reserve(evv_num);
437                 for (i=0; i<evv_num; ++i)
438                         splitseq.push_back((new ncmul(evv[i]))->setflag(status_flags::dynallocated));
439                 
440                 return (new mul(splitseq))->setflag(status_flags::dynallocated);
441         }
442         
443         return (new ncmul(assocseq))->setflag(status_flags::dynallocated |
444                                                                                   status_flags::evaluated);
445 }
446
447 ex ncmul::evalm(void) const
448 {
449         // Evaluate children first
450         exvector *s = new exvector;
451         s->reserve(seq.size());
452         exvector::const_iterator it = seq.begin(), itend = seq.end();
453         while (it != itend) {
454                 s->push_back(it->evalm());
455                 it++;
456         }
457
458         // If there are only matrices, simply multiply them
459         it = s->begin(); itend = s->end();
460         if (is_ex_of_type(*it, matrix)) {
461                 matrix prod(ex_to<matrix>(*it));
462                 it++;
463                 while (it != itend) {
464                         if (!is_ex_of_type(*it, matrix))
465                                 goto no_matrix;
466                         prod = prod.mul(ex_to<matrix>(*it));
467                         it++;
468                 }
469                 delete s;
470                 return prod;
471         }
472
473 no_matrix:
474         return (new ncmul(s))->setflag(status_flags::dynallocated);
475 }
476
477 ex ncmul::thisexprseq(const exvector & v) const
478 {
479         return (new ncmul(v))->setflag(status_flags::dynallocated);
480 }
481
482 ex ncmul::thisexprseq(exvector * vp) const
483 {
484         return (new ncmul(vp))->setflag(status_flags::dynallocated);
485 }
486
487 // protected
488
489 /** Implementation of ex::diff() for a non-commutative product. It applies
490  *  the product rule.
491  *  @see ex::diff */
492 ex ncmul::derivative(const symbol & s) const
493 {
494         unsigned num = seq.size();
495         exvector addseq;
496         addseq.reserve(num);
497         
498         // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
499         exvector ncmulseq = seq;
500         for (unsigned i=0; i<num; ++i) {
501                 ex e = seq[i].diff(s);
502                 e.swap(ncmulseq[i]);
503                 addseq.push_back((new ncmul(ncmulseq))->setflag(status_flags::dynallocated));
504                 e.swap(ncmulseq[i]);
505         }
506         return (new add(addseq))->setflag(status_flags::dynallocated);
507 }
508
509 int ncmul::compare_same_type(const basic & other) const
510 {
511         return inherited::compare_same_type(other);
512 }
513
514 unsigned ncmul::return_type(void) const
515 {
516         if (seq.empty())
517                 return return_types::commutative;
518
519         bool all_commutative = true;
520         exvector::const_iterator noncommutative_element; // point to first found nc element
521
522         exvector::const_iterator i = seq.begin(), end = seq.end();
523         while (i != end) {
524                 unsigned rt = i->return_type();
525                 if (rt == return_types::noncommutative_composite)
526                         return rt; // one ncc -> mul also ncc
527                 if ((rt == return_types::noncommutative) && (all_commutative)) {
528                         // first nc element found, remember position
529                         noncommutative_element = i;
530                         all_commutative = false;
531                 }
532                 if ((rt == return_types::noncommutative) && (!all_commutative)) {
533                         // another nc element found, compare type_infos
534                         if (noncommutative_element->return_type_tinfo() != i->return_type_tinfo()) {
535                                 // diffent types -> mul is ncc
536                                 return return_types::noncommutative_composite;
537                         }
538                 }
539                 ++i;
540         }
541         // all factors checked
542         GINAC_ASSERT(!all_commutative); // not all factors should commute, because this is a ncmul();
543         return all_commutative ? return_types::commutative : return_types::noncommutative;
544 }
545    
546 unsigned ncmul::return_type_tinfo(void) const
547 {
548         if (seq.empty())
549                 return tinfo_key;
550
551         // return type_info of first noncommutative element
552         exvector::const_iterator i = seq.begin(), end = seq.end();
553         while (i != end) {
554                 if (i->return_type() == return_types::noncommutative)
555                         return i->return_type_tinfo();
556                 ++i;
557         }
558
559         // no noncommutative element found, should not happen
560         return tinfo_key;
561 }
562
563 //////////
564 // new virtual functions which can be overridden by derived classes
565 //////////
566
567 // none
568
569 //////////
570 // non-virtual functions in this class
571 //////////
572
573 exvector ncmul::expandchildren(unsigned options) const
574 {
575         exvector s;
576         s.reserve(seq.size());
577         exvector::const_iterator it = seq.begin(), itend = seq.end();
578         while (it != itend) {
579                 s.push_back(it->expand(options));
580                 it++;
581         }
582         return s;
583 }
584
585 const exvector & ncmul::get_factors(void) const
586 {
587         return seq;
588 }
589
590 //////////
591 // friend functions
592 //////////
593
594 ex nonsimplified_ncmul(const exvector & v)
595 {
596         return (new ncmul(v))->setflag(status_flags::dynallocated);
597 }
598
599 ex simplified_ncmul(const exvector & v)
600 {
601         if (v.empty())
602                 return _ex1();
603         else if (v.size() == 1)
604                 return v[0];
605         else
606                 return (new ncmul(v))->setflag(status_flags::dynallocated |
607                                                status_flags::evaluated);
608 }
609
610 } // namespace GiNaC