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