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