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