1433a3a883132a36a3c3e744a0bafa9ba7ce1fa7
[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 << "%(";
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
360         exvector assocseq;
361         assocseq.reserve(factors);
362         for (exvector::const_iterator cit=evaledseq.begin(); cit!=evaledseq.end(); ++cit) {
363                 append_factors(assocseq,*cit);
364         }
365
366         // ncmul(x) -> x
367         if (assocseq.size()==1) return *(seq.begin());
368
369         // ncmul() -> 1
370         if (assocseq.size()==0) return _ex1();
371
372         // determine return types
373         unsignedvector rettypes;
374         rettypes.reserve(assocseq.size());
375         unsigned i=0;
376         unsigned count_commutative=0;
377         unsigned count_noncommutative=0;
378         unsigned count_noncommutative_composite=0;
379         for (exvector::const_iterator cit=assocseq.begin(); cit!=assocseq.end(); ++cit) {
380                 switch (rettypes[i]=(*cit).return_type()) {
381                 case return_types::commutative:
382                         count_commutative++;
383                         break;
384                 case return_types::noncommutative:
385                         count_noncommutative++;
386                         break;
387                 case return_types::noncommutative_composite:
388                         count_noncommutative_composite++;
389                         break;
390                 default:
391                         throw(std::logic_error("ncmul::eval(): invalid return type"));
392                 }
393                 ++i;
394         }
395         GINAC_ASSERT(count_commutative+count_noncommutative+count_noncommutative_composite==assocseq.size());
396
397         // ncmul(...,c1,...,c2,...) ->
398         //     *(c1,c2,ncmul(...)) (pull out commutative elements)
399         if (count_commutative!=0) {
400                 exvector commutativeseq;
401                 commutativeseq.reserve(count_commutative+1);
402                 exvector noncommutativeseq;
403                 noncommutativeseq.reserve(assocseq.size()-count_commutative);
404                 for (i=0; i<assocseq.size(); ++i) {
405                         if (rettypes[i]==return_types::commutative) {
406                                 commutativeseq.push_back(assocseq[i]);
407                         } else {
408                                 noncommutativeseq.push_back(assocseq[i]);
409                         }
410                 }
411                 commutativeseq.push_back((new ncmul(noncommutativeseq,1))->setflag(status_flags::dynallocated));
412                 return (new mul(commutativeseq))->setflag(status_flags::dynallocated);
413         }
414                 
415         // ncmul(x1,y1,x2,y2) -> *(ncmul(x1,x2),ncmul(y1,y2))
416         //     (collect elements of same type)
417
418         if (count_noncommutative_composite==0) {
419                 // there are neither commutative nor noncommutative_composite
420                 // elements in assocseq
421                 GINAC_ASSERT(count_commutative==0);
422
423                 exvectorvector evv;
424                 unsignedvector rttinfos;
425                 evv.reserve(assocseq.size());
426                 rttinfos.reserve(assocseq.size());
427
428                 for (exvector::const_iterator cit=assocseq.begin(); cit!=assocseq.end(); ++cit) {
429                         unsigned ti=(*cit).return_type_tinfo();
430                         // search type in vector of known types
431                         for (i=0; i<rttinfos.size(); ++i) {
432                                 if (ti==rttinfos[i]) {
433                                         evv[i].push_back(*cit);
434                                         break;
435                                 }
436                         }
437                         if (i>=rttinfos.size()) {
438                                 // new type
439                                 rttinfos.push_back(ti);
440                                 evv.push_back(exvector());
441                                 (*(evv.end()-1)).reserve(assocseq.size());
442                                 (*(evv.end()-1)).push_back(*cit);
443                         }
444                 }
445
446 #ifdef DO_GINAC_ASSERT
447                 GINAC_ASSERT(evv.size()==rttinfos.size());
448                 GINAC_ASSERT(evv.size()>0);
449                 unsigned s=0;
450                 for (i=0; i<evv.size(); ++i) {
451                         s += evv[i].size();
452                 }
453                 GINAC_ASSERT(s==assocseq.size());
454 #endif // def DO_GINAC_ASSERT
455                 
456                 // if all elements are of same type, simplify the string
457                 if (evv.size()==1) {
458                         return evv[0][0].simplify_ncmul(evv[0]);
459                 }
460                 
461                 exvector splitseq;
462                 splitseq.reserve(evv.size());
463                 for (i=0; i<evv.size(); ++i) {
464                         splitseq.push_back((new ncmul(evv[i]))->setflag(status_flags::dynallocated));
465                 }
466
467                 return (new mul(splitseq))->setflag(status_flags::dynallocated);
468         }
469         
470         return (new ncmul(assocseq))->setflag(status_flags::dynallocated |
471                                                                                   status_flags::evaluated);
472 }
473
474 ex ncmul::subs(const lst & ls, const lst & lr) const
475 {
476         return ncmul(subschildren(ls, lr));
477 }
478
479 ex ncmul::thisexprseq(const exvector & v) const
480 {
481         return (new ncmul(v))->setflag(status_flags::dynallocated);
482 }
483
484 ex ncmul::thisexprseq(exvector * vp) const
485 {
486         return (new ncmul(vp))->setflag(status_flags::dynallocated);
487 }
488
489 // protected
490
491 /** Implementation of ex::diff() for a non-commutative product. It always returns 0.
492  *  @see ex::diff */
493 ex ncmul::derivative(const symbol & s) const
494 {
495         return _ex0();
496 }
497
498 int ncmul::compare_same_type(const basic & other) const
499 {
500         return inherited::compare_same_type(other);
501 }
502
503 unsigned ncmul::return_type(void) const
504 {
505         if (seq.size()==0) {
506                 // ncmul without factors: should not happen, but commutes
507                 return return_types::commutative;
508         }
509
510         bool all_commutative=1;
511         unsigned rt;
512         exvector::const_iterator cit_noncommutative_element; // point to first found nc element
513
514         for (exvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
515                 rt=(*cit).return_type();
516                 if (rt==return_types::noncommutative_composite) return rt; // one ncc -> mul also ncc
517                 if ((rt==return_types::noncommutative)&&(all_commutative)) {
518                         // first nc element found, remember position
519                         cit_noncommutative_element=cit;
520                         all_commutative=0;
521                 }
522                 if ((rt==return_types::noncommutative)&&(!all_commutative)) {
523                         // another nc element found, compare type_infos
524                         if ((*cit_noncommutative_element).return_type_tinfo()!=(*cit).return_type_tinfo()) {
525                                 // diffent types -> mul is ncc
526                                 return return_types::noncommutative_composite;
527                         }
528                 }
529         }
530         // all factors checked
531         GINAC_ASSERT(!all_commutative); // not all factors should commute, because this is a ncmul();
532         return all_commutative ? return_types::commutative : return_types::noncommutative;
533 }
534    
535 unsigned ncmul::return_type_tinfo(void) const
536 {
537         if (seq.size()==0) {
538                 // mul without factors: should not happen
539                 return tinfo_key;
540         }
541         // return type_info of first noncommutative element
542         for (exvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
543                 if ((*cit).return_type()==return_types::noncommutative) {
544                         return (*cit).return_type_tinfo();
545                 }
546         }
547         // no noncommutative element found, should not happen
548         return tinfo_key;
549 }
550
551 //////////
552 // new virtual functions which can be overridden by derived classes
553 //////////
554
555 // none
556
557 //////////
558 // non-virtual functions in this class
559 //////////
560
561 exvector ncmul::expandchildren(unsigned options) const
562 {
563         exvector s;
564         s.reserve(seq.size());
565
566         for (exvector::const_iterator it=seq.begin(); it!=seq.end(); ++it) {
567                 s.push_back((*it).expand(options));
568         }
569         return s;
570 }
571
572 const exvector & ncmul::get_factors(void) const
573 {
574         return seq;
575 }
576
577 //////////
578 // static member variables
579 //////////
580
581 // protected
582
583 unsigned ncmul::precedence = 50;
584
585 //////////
586 // friend functions
587 //////////
588
589 ex nonsimplified_ncmul(const exvector & v)
590 {
591         return (new ncmul(v))->setflag(status_flags::dynallocated);
592 }
593
594 ex simplified_ncmul(const exvector & v)
595 {
596         if (v.size()==0) {
597                 return _ex1();
598         } else if (v.size()==1) {
599                 return v[0];
600         }
601         return (new ncmul(v))->setflag(status_flags::dynallocated |
602                                        status_flags::evaluated);
603 }
604
605 } // namespace GiNaC