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