Made also ncmuls rename dummy indices.
[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         make_flat_inserter mf(evaledseq, true);
339         while (cit != citend)
340         {       ex factor = mf.handle_factor(*(cit++), 1);
341                 append_factors(assocseq, factor);
342         }
343         
344         // ncmul(x) -> x
345         if (assocseq.size()==1) return *(seq.begin());
346  
347         // ncmul() -> 1
348         if (assocseq.empty()) return _ex1;
349
350         // determine return types
351         unsignedvector rettypes;
352         rettypes.reserve(assocseq.size());
353         size_t i = 0;
354         size_t count_commutative=0;
355         size_t count_noncommutative=0;
356         size_t count_noncommutative_composite=0;
357         cit = assocseq.begin(); citend = assocseq.end();
358         while (cit != citend) {
359                 switch (rettypes[i] = cit->return_type()) {
360                 case return_types::commutative:
361                         count_commutative++;
362                         break;
363                 case return_types::noncommutative:
364                         count_noncommutative++;
365                         break;
366                 case return_types::noncommutative_composite:
367                         count_noncommutative_composite++;
368                         break;
369                 default:
370                         throw(std::logic_error("ncmul::eval(): invalid return type"));
371                 }
372                 ++i; ++cit;
373         }
374         GINAC_ASSERT(count_commutative+count_noncommutative+count_noncommutative_composite==assocseq.size());
375
376         // ncmul(...,c1,...,c2,...) ->
377         //     *(c1,c2,ncmul(...)) (pull out commutative elements)
378         if (count_commutative!=0) {
379                 exvector commutativeseq;
380                 commutativeseq.reserve(count_commutative+1);
381                 exvector noncommutativeseq;
382                 noncommutativeseq.reserve(assocseq.size()-count_commutative);
383                 size_t num = assocseq.size();
384                 for (size_t i=0; i<num; ++i) {
385                         if (rettypes[i]==return_types::commutative)
386                                 commutativeseq.push_back(assocseq[i]);
387                         else
388                                 noncommutativeseq.push_back(assocseq[i]);
389                 }
390                 commutativeseq.push_back((new ncmul(noncommutativeseq,1))->setflag(status_flags::dynallocated));
391                 return (new mul(commutativeseq))->setflag(status_flags::dynallocated);
392         }
393                 
394         // ncmul(x1,y1,x2,y2) -> *(ncmul(x1,x2),ncmul(y1,y2))
395         //     (collect elements of same type)
396
397         if (count_noncommutative_composite==0) {
398                 // there are neither commutative nor noncommutative_composite
399                 // elements in assocseq
400                 GINAC_ASSERT(count_commutative==0);
401
402                 size_t assoc_num = assocseq.size();
403                 exvectorvector evv;
404                 std::vector<tinfo_t> rttinfos;
405                 evv.reserve(assoc_num);
406                 rttinfos.reserve(assoc_num);
407
408                 cit = assocseq.begin(), citend = assocseq.end();
409                 while (cit != citend) {
410                         tinfo_t ti = cit->return_type_tinfo();
411                         size_t rtt_num = rttinfos.size();
412                         // search type in vector of known types
413                         for (i=0; i<rtt_num; ++i) {
414                                 if(ti == rttinfos[i]) {
415                                         evv[i].push_back(*cit);
416                                         break;
417                                 }
418                         }
419                         if (i >= rtt_num) {
420                                 // new type
421                                 rttinfos.push_back(ti);
422                                 evv.push_back(exvector());
423                                 (evv.end()-1)->reserve(assoc_num);
424                                 (evv.end()-1)->push_back(*cit);
425                         }
426                         ++cit;
427                 }
428
429                 size_t evv_num = evv.size();
430 #ifdef DO_GINAC_ASSERT
431                 GINAC_ASSERT(evv_num == rttinfos.size());
432                 GINAC_ASSERT(evv_num > 0);
433                 size_t s=0;
434                 for (i=0; i<evv_num; ++i)
435                         s += evv[i].size();
436                 GINAC_ASSERT(s == assoc_num);
437 #endif // def DO_GINAC_ASSERT
438                 
439                 // if all elements are of same type, simplify the string
440                 if (evv_num == 1) {
441                         return evv[0][0].eval_ncmul(evv[0]);
442                 }
443                 
444                 exvector splitseq;
445                 splitseq.reserve(evv_num);
446                 for (i=0; i<evv_num; ++i)
447                         splitseq.push_back((new ncmul(evv[i]))->setflag(status_flags::dynallocated));
448                 
449                 return (new mul(splitseq))->setflag(status_flags::dynallocated);
450         }
451         
452         return (new ncmul(assocseq))->setflag(status_flags::dynallocated |
453                                                                                   status_flags::evaluated);
454 }
455
456 ex ncmul::evalm() const
457 {
458         // Evaluate children first
459         std::auto_ptr<exvector> s(new exvector);
460         s->reserve(seq.size());
461         exvector::const_iterator it = seq.begin(), itend = seq.end();
462         while (it != itend) {
463                 s->push_back(it->evalm());
464                 it++;
465         }
466
467         // If there are only matrices, simply multiply them
468         it = s->begin(); itend = s->end();
469         if (is_a<matrix>(*it)) {
470                 matrix prod(ex_to<matrix>(*it));
471                 it++;
472                 while (it != itend) {
473                         if (!is_a<matrix>(*it))
474                                 goto no_matrix;
475                         prod = prod.mul(ex_to<matrix>(*it));
476                         it++;
477                 }
478                 return prod;
479         }
480
481 no_matrix:
482         return (new ncmul(s))->setflag(status_flags::dynallocated);
483 }
484
485 ex ncmul::thiscontainer(const exvector & v) const
486 {
487         return (new ncmul(v))->setflag(status_flags::dynallocated);
488 }
489
490 ex ncmul::thiscontainer(std::auto_ptr<exvector> vp) const
491 {
492         return (new ncmul(vp))->setflag(status_flags::dynallocated);
493 }
494
495 ex ncmul::conjugate() const
496 {
497         if (return_type() != return_types::noncommutative) {
498                 return exprseq::conjugate();
499         }
500
501         if (!is_clifford_tinfo(return_type_tinfo())) {
502                 return exprseq::conjugate();
503         }
504
505         exvector ev;
506         ev.reserve(nops());
507         for (const_iterator i=end(); i!=begin();) {
508                 --i;
509                 ev.push_back(i->conjugate());
510         }
511         return (new ncmul(ev, true))->setflag(status_flags::dynallocated).eval();
512 }
513
514 ex ncmul::real_part() const
515 {
516         return basic::real_part();
517 }
518
519 ex ncmul::imag_part() const
520 {
521         return basic::imag_part();
522 }
523
524 // protected
525
526 /** Implementation of ex::diff() for a non-commutative product. It applies
527  *  the product rule.
528  *  @see ex::diff */
529 ex ncmul::derivative(const symbol & s) const
530 {
531         size_t num = seq.size();
532         exvector addseq;
533         addseq.reserve(num);
534         
535         // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
536         exvector ncmulseq = seq;
537         for (size_t i=0; i<num; ++i) {
538                 ex e = seq[i].diff(s);
539                 e.swap(ncmulseq[i]);
540                 addseq.push_back((new ncmul(ncmulseq))->setflag(status_flags::dynallocated));
541                 e.swap(ncmulseq[i]);
542         }
543         return (new add(addseq))->setflag(status_flags::dynallocated);
544 }
545
546 int ncmul::compare_same_type(const basic & other) const
547 {
548         return inherited::compare_same_type(other);
549 }
550
551 unsigned ncmul::return_type() const
552 {
553         if (seq.empty())
554                 return return_types::commutative;
555
556         bool all_commutative = true;
557         exvector::const_iterator noncommutative_element; // point to first found nc element
558
559         exvector::const_iterator i = seq.begin(), end = seq.end();
560         while (i != end) {
561                 unsigned rt = i->return_type();
562                 if (rt == return_types::noncommutative_composite)
563                         return rt; // one ncc -> mul also ncc
564                 if ((rt == return_types::noncommutative) && (all_commutative)) {
565                         // first nc element found, remember position
566                         noncommutative_element = i;
567                         all_commutative = false;
568                 }
569                 if ((rt == return_types::noncommutative) && (!all_commutative)) {
570                         // another nc element found, compare type_infos
571                         if(noncommutative_element->return_type_tinfo() != i->return_type_tinfo())
572                                         return return_types::noncommutative_composite;
573                 }
574                 ++i;
575         }
576         // all factors checked
577         GINAC_ASSERT(!all_commutative); // not all factors should commutate, because this is a ncmul();
578         return all_commutative ? return_types::commutative : return_types::noncommutative;
579 }
580    
581 tinfo_t ncmul::return_type_tinfo() const
582 {
583         if (seq.empty())
584                 return this;
585
586         // return type_info of first noncommutative element
587         exvector::const_iterator i = seq.begin(), end = seq.end();
588         while (i != end) {
589                 if (i->return_type() == return_types::noncommutative)
590                         return i->return_type_tinfo();
591                 ++i;
592         }
593
594         // no noncommutative element found, should not happen
595         return this;
596 }
597
598 //////////
599 // new virtual functions which can be overridden by derived classes
600 //////////
601
602 // none
603
604 //////////
605 // non-virtual functions in this class
606 //////////
607
608 std::auto_ptr<exvector> ncmul::expandchildren(unsigned options) const
609 {
610         const_iterator cit = this->seq.begin(), end = this->seq.end();
611         while (cit != end) {
612                 const ex & expanded_ex = cit->expand(options);
613                 if (!are_ex_trivially_equal(*cit, expanded_ex)) {
614
615                         // copy first part of seq which hasn't changed
616                         std::auto_ptr<exvector> s(new exvector(this->seq.begin(), cit));
617                         reserve(*s, this->seq.size());
618
619                         // insert changed element
620                         s->push_back(expanded_ex);
621                         ++cit;
622
623                         // copy rest
624                         while (cit != end) {
625                                 s->push_back(cit->expand(options));
626                                 ++cit;
627                         }
628
629                         return s;
630                 }
631
632                 ++cit;
633         }
634
635         return std::auto_ptr<exvector>(0); // nothing has changed
636 }
637
638 const exvector & ncmul::get_factors() const
639 {
640         return seq;
641 }
642
643 //////////
644 // friend functions
645 //////////
646
647 ex reeval_ncmul(const exvector & v)
648 {
649         return (new ncmul(v))->setflag(status_flags::dynallocated);
650 }
651
652 ex hold_ncmul(const exvector & v)
653 {
654         if (v.empty())
655                 return _ex1;
656         else if (v.size() == 1)
657                 return v[0];
658         else
659                 return (new ncmul(v))->setflag(status_flags::dynallocated |
660                                                status_flags::evaluated);
661 }
662
663 } // namespace GiNaC