21f7730c841fe13ce9b41083058ced5e7b68d6f3
[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-2006 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  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 "clifford.h"
32 #include "matrix.h"
33 #include "archive.h"
34 #include "indexed.h"
35 #include "utils.h"
36
37 namespace GiNaC {
38
39 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(ncmul, exprseq,
40   print_func<print_context>(&ncmul::do_print).
41   print_func<print_tree>(&ncmul::do_print_tree).
42   print_func<print_csrc>(&ncmul::do_print_csrc).
43   print_func<print_python_repr>(&ncmul::do_print_csrc))
44
45
46 //////////
47 // default constructor
48 //////////
49
50 ncmul::ncmul()
51 {
52         tinfo_key = &ncmul::tinfo_static;
53 }
54
55 //////////
56 // other constructors
57 //////////
58
59 // public
60
61 ncmul::ncmul(const ex & lh, const ex & rh) : inherited(lh,rh)
62 {
63         tinfo_key = &ncmul::tinfo_static;
64 }
65
66 ncmul::ncmul(const ex & f1, const ex & f2, const ex & f3) : inherited(f1,f2,f3)
67 {
68         tinfo_key = &ncmul::tinfo_static;
69 }
70
71 ncmul::ncmul(const ex & f1, const ex & f2, const ex & f3,
72              const ex & f4) : inherited(f1,f2,f3,f4)
73 {
74         tinfo_key = &ncmul::tinfo_static;
75 }
76
77 ncmul::ncmul(const ex & f1, const ex & f2, const ex & f3,
78              const ex & f4, const ex & f5) : inherited(f1,f2,f3,f4,f5)
79 {
80         tinfo_key = &ncmul::tinfo_static;
81 }
82
83 ncmul::ncmul(const ex & f1, const ex & f2, const ex & f3,
84              const ex & f4, const ex & f5, const ex & f6) : inherited(f1,f2,f3,f4,f5,f6)
85 {
86         tinfo_key = &ncmul::tinfo_static;
87 }
88
89 ncmul::ncmul(const exvector & v, bool discardable) : inherited(v,discardable)
90 {
91         tinfo_key = &ncmul::tinfo_static;
92 }
93
94 ncmul::ncmul(std::auto_ptr<exvector> vp) : inherited(vp)
95 {
96         tinfo_key = &ncmul::tinfo_static;
97 }
98
99 //////////
100 // archiving
101 //////////
102
103 DEFAULT_ARCHIVING(ncmul)
104         
105 //////////
106 // functions overriding virtual functions from base classes
107 //////////
108
109 // public
110
111 void ncmul::do_print(const print_context & c, unsigned level) const
112 {
113         printseq(c, '(', '*', ')', precedence(), level);
114 }
115
116 void ncmul::do_print_csrc(const print_context & c, unsigned level) const
117 {
118         c.s << class_name();
119         printseq(c, '(', ',', ')', precedence(), precedence());
120 }
121
122 bool ncmul::info(unsigned inf) const
123 {
124         return inherited::info(inf);
125 }
126
127 typedef std::vector<int> intvector;
128
129 ex ncmul::expand(unsigned options) const
130 {
131         // First, expand the children
132         std::auto_ptr<exvector> vp = expandchildren(options);
133         const exvector &expanded_seq = vp.get() ? *vp : this->seq;
134         
135         // Now, look for all the factors that are sums and remember their
136         // position and number of terms.
137         intvector positions_of_adds(expanded_seq.size());
138         intvector number_of_add_operands(expanded_seq.size());
139
140         size_t number_of_adds = 0;
141         size_t number_of_expanded_terms = 1;
142
143         size_t current_position = 0;
144         exvector::const_iterator last = expanded_seq.end();
145         for (exvector::const_iterator cit=expanded_seq.begin(); cit!=last; ++cit) {
146                 if (is_exactly_a<add>(*cit)) {
147                         positions_of_adds[number_of_adds] = current_position;
148                         size_t num_ops = cit->nops();
149                         number_of_add_operands[number_of_adds] = num_ops;
150                         number_of_expanded_terms *= num_ops;
151                         number_of_adds++;
152                 }
153                 ++current_position;
154         }
155
156         // If there are no sums, we are done
157         if (number_of_adds == 0) {
158                 if (vp.get())
159                         return (new ncmul(vp))->
160                                 setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
161                 else
162                         return *this;
163         }
164
165         // Now, form all possible products of the terms of the sums with the
166         // remaining factors, and add them together
167         exvector distrseq;
168         distrseq.reserve(number_of_expanded_terms);
169
170         intvector k(number_of_adds);
171
172         /* Rename indices in the static members of the product */
173         exvector expanded_seq_mod;
174         size_t j = 0;
175         exvector va;
176
177         for (size_t i=0; i<expanded_seq.size(); i++) {
178                 if (i == positions_of_adds[j]) {
179                         expanded_seq_mod.push_back(_ex1);
180                         j++;
181                 } else {
182                         expanded_seq_mod.push_back(rename_dummy_indices_uniquely(va, expanded_seq[i], true));
183                 }
184         }
185
186         while (true) {
187                 exvector term = expanded_seq_mod;
188                 for (size_t i=0; i<number_of_adds; i++) {
189                         term[positions_of_adds[i]] = rename_dummy_indices_uniquely(va, expanded_seq[positions_of_adds[i]].op(k[i]), true);
190                 }
191
192                 distrseq.push_back((new ncmul(term, true))->
193                                     setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0)));
194
195                 // increment k[]
196                 int l = number_of_adds-1;
197                 while ((l>=0) && ((++k[l]) >= number_of_add_operands[l])) {
198                         k[l] = 0;
199                         l--;
200                 }
201                 if (l<0)
202                         break;
203         }
204
205         return (new add(distrseq))->
206                 setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
207 }
208
209 int ncmul::degree(const ex & s) const
210 {
211         if (is_equal(ex_to<basic>(s)))
212                 return 1;
213
214         // Sum up degrees of factors
215         int deg_sum = 0;
216         exvector::const_iterator i = seq.begin(), end = seq.end();
217         while (i != end) {
218                 deg_sum += i->degree(s);
219                 ++i;
220         }
221         return deg_sum;
222 }
223
224 int ncmul::ldegree(const ex & s) const
225 {
226         if (is_equal(ex_to<basic>(s)))
227                 return 1;
228
229         // Sum up degrees of factors
230         int deg_sum = 0;
231         exvector::const_iterator i = seq.begin(), end = seq.end();
232         while (i != end) {
233                 deg_sum += i->degree(s);
234                 ++i;
235         }
236         return deg_sum;
237 }
238
239 ex ncmul::coeff(const ex & s, int n) const
240 {
241         if (is_equal(ex_to<basic>(s)))
242                 return n==1 ? _ex1 : _ex0;
243
244         exvector coeffseq;
245         coeffseq.reserve(seq.size());
246
247         if (n == 0) {
248                 // product of individual coeffs
249                 // if a non-zero power of s is found, the resulting product will be 0
250                 exvector::const_iterator it=seq.begin();
251                 while (it!=seq.end()) {
252                         coeffseq.push_back((*it).coeff(s,n));
253                         ++it;
254                 }
255                 return (new ncmul(coeffseq,1))->setflag(status_flags::dynallocated);
256         }
257                  
258         exvector::const_iterator i = seq.begin(), end = seq.end();
259         bool coeff_found = false;
260         while (i != end) {
261                 ex c = i->coeff(s,n);
262                 if (c.is_zero()) {
263                         coeffseq.push_back(*i);
264                 } else {
265                         coeffseq.push_back(c);
266                         coeff_found = true;
267                 }
268                 ++i;
269         }
270
271         if (coeff_found) return (new ncmul(coeffseq,1))->setflag(status_flags::dynallocated);
272         
273         return _ex0;
274 }
275
276 size_t ncmul::count_factors(const ex & e) const
277 {
278         if ((is_exactly_a<mul>(e)&&(e.return_type()!=return_types::commutative))||
279                 (is_exactly_a<ncmul>(e))) {
280                 size_t factors=0;
281                 for (size_t i=0; i<e.nops(); i++)
282                         factors += count_factors(e.op(i));
283                 
284                 return factors;
285         }
286         return 1;
287 }
288                 
289 void ncmul::append_factors(exvector & v, const ex & e) const
290 {
291         if ((is_exactly_a<mul>(e)&&(e.return_type()!=return_types::commutative))||
292                 (is_exactly_a<ncmul>(e))) {
293                 for (size_t i=0; i<e.nops(); i++)
294                         append_factors(v, e.op(i));
295         } else 
296                 v.push_back(e);
297 }
298
299 typedef std::vector<unsigned> unsignedvector;
300 typedef std::vector<exvector> exvectorvector;
301
302 /** Perform automatic term rewriting rules in this class.  In the following
303  *  x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
304  *  stand for such expressions that contain a plain number.
305  *  - ncmul(...,*(x1,x2),...,ncmul(x3,x4),...) -> ncmul(...,x1,x2,...,x3,x4,...)  (associativity)
306  *  - ncmul(x) -> x
307  *  - ncmul() -> 1
308  *  - ncmul(...,c1,...,c2,...) -> *(c1,c2,ncmul(...))  (pull out commutative elements)
309  *  - ncmul(x1,y1,x2,y2) -> *(ncmul(x1,x2),ncmul(y1,y2))  (collect elements of same type)
310  *  - ncmul(x1,x2,x3,...) -> x::eval_ncmul(x1,x2,x3,...)
311  *
312  *  @param level cut-off in recursive evaluation */
313 ex ncmul::eval(int level) const
314 {
315         // The following additional rule would be nice, but produces a recursion,
316         // which must be trapped by introducing a flag that the sub-ncmuls()
317         // are already evaluated (maybe later...)
318         //                  ncmul(x1,x2,...,X,y1,y2,...) ->
319         //                      ncmul(ncmul(x1,x2,...),X,ncmul(y1,y2,...)
320         //                      (X noncommutative_composite)
321
322         if ((level==1) && (flags & status_flags::evaluated)) {
323                 return *this;
324         }
325
326         exvector evaledseq=evalchildren(level);
327
328         // ncmul(...,*(x1,x2),...,ncmul(x3,x4),...) ->
329         //     ncmul(...,x1,x2,...,x3,x4,...)  (associativity)
330         size_t factors = 0;
331         exvector::const_iterator cit = evaledseq.begin(), citend = evaledseq.end();
332         while (cit != citend)
333                 factors += count_factors(*cit++);
334         
335         exvector assocseq;
336         assocseq.reserve(factors);
337         cit = evaledseq.begin();
338         while (cit != citend)
339                 append_factors(assocseq, *cit++);
340         
341         // ncmul(x) -> x
342         if (assocseq.size()==1) return *(seq.begin());
343  
344         // ncmul() -> 1
345         if (assocseq.empty()) return _ex1;
346
347         // determine return types
348         unsignedvector rettypes;
349         rettypes.reserve(assocseq.size());
350         size_t i = 0;
351         size_t count_commutative=0;
352         size_t count_noncommutative=0;
353         size_t count_noncommutative_composite=0;
354         cit = assocseq.begin(); citend = assocseq.end();
355         while (cit != citend) {
356                 switch (rettypes[i] = cit->return_type()) {
357                 case return_types::commutative:
358                         count_commutative++;
359                         break;
360                 case return_types::noncommutative:
361                         count_noncommutative++;
362                         break;
363                 case return_types::noncommutative_composite:
364                         count_noncommutative_composite++;
365                         break;
366                 default:
367                         throw(std::logic_error("ncmul::eval(): invalid return type"));
368                 }
369                 ++i; ++cit;
370         }
371         GINAC_ASSERT(count_commutative+count_noncommutative+count_noncommutative_composite==assocseq.size());
372
373         // ncmul(...,c1,...,c2,...) ->
374         //     *(c1,c2,ncmul(...)) (pull out commutative elements)
375         if (count_commutative!=0) {
376                 exvector commutativeseq;
377                 commutativeseq.reserve(count_commutative+1);
378                 exvector noncommutativeseq;
379                 noncommutativeseq.reserve(assocseq.size()-count_commutative);
380                 size_t num = assocseq.size();
381                 for (size_t i=0; i<num; ++i) {
382                         if (rettypes[i]==return_types::commutative)
383                                 commutativeseq.push_back(assocseq[i]);
384                         else
385                                 noncommutativeseq.push_back(assocseq[i]);
386                 }
387                 commutativeseq.push_back((new ncmul(noncommutativeseq,1))->setflag(status_flags::dynallocated));
388                 return (new mul(commutativeseq))->setflag(status_flags::dynallocated);
389         }
390                 
391         // ncmul(x1,y1,x2,y2) -> *(ncmul(x1,x2),ncmul(y1,y2))
392         //     (collect elements of same type)
393
394         if (count_noncommutative_composite==0) {
395                 // there are neither commutative nor noncommutative_composite
396                 // elements in assocseq
397                 GINAC_ASSERT(count_commutative==0);
398
399                 size_t assoc_num = assocseq.size();
400                 exvectorvector evv;
401                 std::vector<tinfo_t> rttinfos;
402                 evv.reserve(assoc_num);
403                 rttinfos.reserve(assoc_num);
404
405                 cit = assocseq.begin(), citend = assocseq.end();
406                 while (cit != citend) {
407                         tinfo_t ti = cit->return_type_tinfo();
408                         size_t rtt_num = rttinfos.size();
409                         // search type in vector of known types
410                         for (i=0; i<rtt_num; ++i) {
411                                 if(ti == rttinfos[i]) {
412                                         evv[i].push_back(*cit);
413                                         break;
414                                 }
415                         }
416                         if (i >= rtt_num) {
417                                 // new type
418                                 rttinfos.push_back(ti);
419                                 evv.push_back(exvector());
420                                 (evv.end()-1)->reserve(assoc_num);
421                                 (evv.end()-1)->push_back(*cit);
422                         }
423                         ++cit;
424                 }
425
426                 size_t evv_num = evv.size();
427 #ifdef DO_GINAC_ASSERT
428                 GINAC_ASSERT(evv_num == rttinfos.size());
429                 GINAC_ASSERT(evv_num > 0);
430                 size_t s=0;
431                 for (i=0; i<evv_num; ++i)
432                         s += evv[i].size();
433                 GINAC_ASSERT(s == assoc_num);
434 #endif // def DO_GINAC_ASSERT
435                 
436                 // if all elements are of same type, simplify the string
437                 if (evv_num == 1) {
438                         return evv[0][0].eval_ncmul(evv[0]);
439                 }
440                 
441                 exvector splitseq;
442                 splitseq.reserve(evv_num);
443                 for (i=0; i<evv_num; ++i)
444                         splitseq.push_back((new ncmul(evv[i]))->setflag(status_flags::dynallocated));
445                 
446                 return (new mul(splitseq))->setflag(status_flags::dynallocated);
447         }
448         
449         return (new ncmul(assocseq))->setflag(status_flags::dynallocated |
450                                                                                   status_flags::evaluated);
451 }
452
453 ex ncmul::evalm() const
454 {
455         // Evaluate children first
456         std::auto_ptr<exvector> s(new exvector);
457         s->reserve(seq.size());
458         exvector::const_iterator it = seq.begin(), itend = seq.end();
459         while (it != itend) {
460                 s->push_back(it->evalm());
461                 it++;
462         }
463
464         // If there are only matrices, simply multiply them
465         it = s->begin(); itend = s->end();
466         if (is_a<matrix>(*it)) {
467                 matrix prod(ex_to<matrix>(*it));
468                 it++;
469                 while (it != itend) {
470                         if (!is_a<matrix>(*it))
471                                 goto no_matrix;
472                         prod = prod.mul(ex_to<matrix>(*it));
473                         it++;
474                 }
475                 return prod;
476         }
477
478 no_matrix:
479         return (new ncmul(s))->setflag(status_flags::dynallocated);
480 }
481
482 ex ncmul::thiscontainer(const exvector & v) const
483 {
484         return (new ncmul(v))->setflag(status_flags::dynallocated);
485 }
486
487 ex ncmul::thiscontainer(std::auto_ptr<exvector> vp) const
488 {
489         return (new ncmul(vp))->setflag(status_flags::dynallocated);
490 }
491
492 ex ncmul::conjugate() const
493 {
494         if (return_type() != return_types::noncommutative) {
495                 return exprseq::conjugate();
496         }
497
498         if (!is_clifford_tinfo(return_type_tinfo())) {
499                 return exprseq::conjugate();
500         }
501
502         exvector ev;
503         ev.reserve(nops());
504         for (const_iterator i=end(); i!=begin();) {
505                 --i;
506                 ev.push_back(i->conjugate());
507         }
508         return (new ncmul(ev, true))->setflag(status_flags::dynallocated).eval();
509 }
510
511 ex ncmul::real_part() const
512 {
513         return basic::real_part();
514 }
515
516 ex ncmul::imag_part() const
517 {
518         return basic::imag_part();
519 }
520
521 // protected
522
523 /** Implementation of ex::diff() for a non-commutative product. It applies
524  *  the product rule.
525  *  @see ex::diff */
526 ex ncmul::derivative(const symbol & s) const
527 {
528         size_t num = seq.size();
529         exvector addseq;
530         addseq.reserve(num);
531         
532         // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
533         exvector ncmulseq = seq;
534         for (size_t i=0; i<num; ++i) {
535                 ex e = seq[i].diff(s);
536                 e.swap(ncmulseq[i]);
537                 addseq.push_back((new ncmul(ncmulseq))->setflag(status_flags::dynallocated));
538                 e.swap(ncmulseq[i]);
539         }
540         return (new add(addseq))->setflag(status_flags::dynallocated);
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() const
549 {
550         if (seq.empty())
551                 return return_types::commutative;
552
553         bool all_commutative = true;
554         exvector::const_iterator noncommutative_element; // point to first found nc element
555
556         exvector::const_iterator i = seq.begin(), end = seq.end();
557         while (i != end) {
558                 unsigned rt = i->return_type();
559                 if (rt == return_types::noncommutative_composite)
560                         return rt; // one ncc -> mul also ncc
561                 if ((rt == return_types::noncommutative) && (all_commutative)) {
562                         // first nc element found, remember position
563                         noncommutative_element = i;
564                         all_commutative = false;
565                 }
566                 if ((rt == return_types::noncommutative) && (!all_commutative)) {
567                         // another nc element found, compare type_infos
568                         if(noncommutative_element->return_type_tinfo() != i->return_type_tinfo())
569                                         return return_types::noncommutative_composite;
570                 }
571                 ++i;
572         }
573         // all factors checked
574         GINAC_ASSERT(!all_commutative); // not all factors should commutate, because this is a ncmul();
575         return all_commutative ? return_types::commutative : return_types::noncommutative;
576 }
577    
578 tinfo_t ncmul::return_type_tinfo() const
579 {
580         if (seq.empty())
581                 return this;
582
583         // return type_info of first noncommutative element
584         exvector::const_iterator i = seq.begin(), end = seq.end();
585         while (i != end) {
586                 if (i->return_type() == return_types::noncommutative)
587                         return i->return_type_tinfo();
588                 ++i;
589         }
590
591         // no noncommutative element found, should not happen
592         return this;
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 std::auto_ptr<exvector> ncmul::expandchildren(unsigned options) const
606 {
607         const_iterator cit = this->seq.begin(), end = this->seq.end();
608         while (cit != end) {
609                 const ex & expanded_ex = cit->expand(options);
610                 if (!are_ex_trivially_equal(*cit, expanded_ex)) {
611
612                         // copy first part of seq which hasn't changed
613                         std::auto_ptr<exvector> s(new exvector(this->seq.begin(), cit));
614                         reserve(*s, this->seq.size());
615
616                         // insert changed element
617                         s->push_back(expanded_ex);
618                         ++cit;
619
620                         // copy rest
621                         while (cit != end) {
622                                 s->push_back(cit->expand(options));
623                                 ++cit;
624                         }
625
626                         return s;
627                 }
628
629                 ++cit;
630         }
631
632         return std::auto_ptr<exvector>(0); // nothing has changed
633 }
634
635 const exvector & ncmul::get_factors() const
636 {
637         return seq;
638 }
639
640 //////////
641 // friend functions
642 //////////
643
644 ex reeval_ncmul(const exvector & v)
645 {
646         return (new ncmul(v))->setflag(status_flags::dynallocated);
647 }
648
649 ex hold_ncmul(const exvector & v)
650 {
651         if (v.empty())
652                 return _ex1;
653         else if (v.size() == 1)
654                 return v[0];
655         else
656                 return (new ncmul(v))->setflag(status_flags::dynallocated |
657                                                status_flags::evaluated);
658 }
659
660 } // namespace GiNaC