]> www.ginac.de Git - ginac.git/blob - ginac/ncmul.cpp
745cf96b0b5992a40bb9e33dab373d6690dcf837
[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 exvector ncmul::get_indices(void) const
475 {
476         // return union of indices of factors
477         exvector iv;
478         for (exvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
479                 exvector subiv=(*cit).get_indices();
480                 iv.reserve(iv.size()+subiv.size());
481                 for (exvector::const_iterator cit2=subiv.begin(); cit2!=subiv.end(); ++cit2) {
482                         iv.push_back(*cit2);
483                 }
484         }
485         return iv;
486 }
487
488 ex ncmul::subs(const lst & ls, const lst & lr) const
489 {
490         return ncmul(subschildren(ls, lr));
491 }
492
493 ex ncmul::thisexprseq(const exvector & v) const
494 {
495         return (new ncmul(v))->setflag(status_flags::dynallocated);
496 }
497
498 ex ncmul::thisexprseq(exvector * vp) const
499 {
500         return (new ncmul(vp))->setflag(status_flags::dynallocated);
501 }
502
503 // protected
504
505 /** Implementation of ex::diff() for a non-commutative product. It always returns 0.
506  *  @see ex::diff */
507 ex ncmul::derivative(const symbol & s) const
508 {
509         return _ex0();
510 }
511
512 int ncmul::compare_same_type(const basic & other) const
513 {
514         return inherited::compare_same_type(other);
515 }
516
517 unsigned ncmul::return_type(void) const
518 {
519         if (seq.size()==0) {
520                 // ncmul without factors: should not happen, but commutes
521                 return return_types::commutative;
522         }
523
524         bool all_commutative=1;
525         unsigned rt;
526         exvector::const_iterator cit_noncommutative_element; // point to first found nc element
527
528         for (exvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
529                 rt=(*cit).return_type();
530                 if (rt==return_types::noncommutative_composite) return rt; // one ncc -> mul also ncc
531                 if ((rt==return_types::noncommutative)&&(all_commutative)) {
532                         // first nc element found, remember position
533                         cit_noncommutative_element=cit;
534                         all_commutative=0;
535                 }
536                 if ((rt==return_types::noncommutative)&&(!all_commutative)) {
537                         // another nc element found, compare type_infos
538                         if ((*cit_noncommutative_element).return_type_tinfo()!=(*cit).return_type_tinfo()) {
539                                 // diffent types -> mul is ncc
540                                 return return_types::noncommutative_composite;
541                         }
542                 }
543         }
544         // all factors checked
545         GINAC_ASSERT(!all_commutative); // not all factors should commute, because this is a ncmul();
546         return all_commutative ? return_types::commutative : return_types::noncommutative;
547 }
548    
549 unsigned ncmul::return_type_tinfo(void) const
550 {
551         if (seq.size()==0) {
552                 // mul without factors: should not happen
553                 return tinfo_key;
554         }
555         // return type_info of first noncommutative element
556         for (exvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
557                 if ((*cit).return_type()==return_types::noncommutative) {
558                         return (*cit).return_type_tinfo();
559                 }
560         }
561         // no noncommutative element found, should not happen
562         return tinfo_key;
563 }
564
565 //////////
566 // new virtual functions which can be overridden by derived classes
567 //////////
568
569 // none
570
571 //////////
572 // non-virtual functions in this class
573 //////////
574
575 exvector ncmul::expandchildren(unsigned options) const
576 {
577         exvector s;
578         s.reserve(seq.size());
579
580         for (exvector::const_iterator it=seq.begin(); it!=seq.end(); ++it) {
581                 s.push_back((*it).expand(options));
582         }
583         return s;
584 }
585
586 const exvector & ncmul::get_factors(void) const
587 {
588         return seq;
589 }
590
591 //////////
592 // static member variables
593 //////////
594
595 // protected
596
597 unsigned ncmul::precedence = 50;
598
599 //////////
600 // friend functions
601 //////////
602
603 ex nonsimplified_ncmul(const exvector & v)
604 {
605         return (new ncmul(v))->setflag(status_flags::dynallocated);
606 }
607
608 ex simplified_ncmul(const exvector & v)
609 {
610         if (v.size()==0) {
611                 return _ex1();
612         } else if (v.size()==1) {
613                 return v[0];
614         }
615         return (new ncmul(v))->setflag(status_flags::dynallocated |
616                                        status_flags::evaluated);
617 }
618
619 } // namespace GiNaC