]> www.ginac.de Git - ginac.git/blob - ginac/ncmul.cpp
Modernized configuration files [A.Sheplyakov].
[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         size_t i;
175         for (i=0; i<expanded_seq.size(); i++) {
176                 if (i == positions_of_adds[j]) {
177                         expanded_seq_mod.push_back(_ex1);
178                         j++;
179                 } else {
180                         expanded_seq_mod.push_back(rename_dummy_indices_uniquely(ncmul(expanded_seq_mod), expanded_seq[i]));
181                 }
182         }
183
184         while (true) {
185                 exvector term = expanded_seq_mod;
186                 for (i=0; i<number_of_adds; i++) {
187                         term[positions_of_adds[i]] = rename_dummy_indices_uniquely(ncmul(term), expanded_seq[positions_of_adds[i]].op(k[i]));
188                 }
189
190                 distrseq.push_back((new ncmul(term, true))->
191                                     setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0)));
192
193                 // increment k[]
194                 int l = number_of_adds-1;
195                 while ((l>=0) && ((++k[l]) >= number_of_add_operands[l])) {
196                         k[l] = 0;
197                         l--;
198                 }
199                 if (l<0)
200                         break;
201         }
202
203         return (new add(distrseq))->
204                 setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
205 }
206
207 int ncmul::degree(const ex & s) const
208 {
209         if (is_equal(ex_to<basic>(s)))
210                 return 1;
211
212         // Sum up degrees of factors
213         int deg_sum = 0;
214         exvector::const_iterator i = seq.begin(), end = seq.end();
215         while (i != end) {
216                 deg_sum += i->degree(s);
217                 ++i;
218         }
219         return deg_sum;
220 }
221
222 int ncmul::ldegree(const ex & s) const
223 {
224         if (is_equal(ex_to<basic>(s)))
225                 return 1;
226
227         // Sum up degrees of factors
228         int deg_sum = 0;
229         exvector::const_iterator i = seq.begin(), end = seq.end();
230         while (i != end) {
231                 deg_sum += i->degree(s);
232                 ++i;
233         }
234         return deg_sum;
235 }
236
237 ex ncmul::coeff(const ex & s, int n) const
238 {
239         if (is_equal(ex_to<basic>(s)))
240                 return n==1 ? _ex1 : _ex0;
241
242         exvector coeffseq;
243         coeffseq.reserve(seq.size());
244
245         if (n == 0) {
246                 // product of individual coeffs
247                 // if a non-zero power of s is found, the resulting product will be 0
248                 exvector::const_iterator it=seq.begin();
249                 while (it!=seq.end()) {
250                         coeffseq.push_back((*it).coeff(s,n));
251                         ++it;
252                 }
253                 return (new ncmul(coeffseq,1))->setflag(status_flags::dynallocated);
254         }
255                  
256         exvector::const_iterator i = seq.begin(), end = seq.end();
257         bool coeff_found = false;
258         while (i != end) {
259                 ex c = i->coeff(s,n);
260                 if (c.is_zero()) {
261                         coeffseq.push_back(*i);
262                 } else {
263                         coeffseq.push_back(c);
264                         coeff_found = true;
265                 }
266                 ++i;
267         }
268
269         if (coeff_found) return (new ncmul(coeffseq,1))->setflag(status_flags::dynallocated);
270         
271         return _ex0;
272 }
273
274 size_t ncmul::count_factors(const ex & e) const
275 {
276         if ((is_exactly_a<mul>(e)&&(e.return_type()!=return_types::commutative))||
277                 (is_exactly_a<ncmul>(e))) {
278                 size_t factors=0;
279                 for (size_t i=0; i<e.nops(); i++)
280                         factors += count_factors(e.op(i));
281                 
282                 return factors;
283         }
284         return 1;
285 }
286                 
287 void ncmul::append_factors(exvector & v, const ex & e) const
288 {
289         if ((is_exactly_a<mul>(e)&&(e.return_type()!=return_types::commutative))||
290                 (is_exactly_a<ncmul>(e))) {
291                 for (size_t i=0; i<e.nops(); i++)
292                         append_factors(v, e.op(i));
293         } else 
294                 v.push_back(e);
295 }
296
297 typedef std::vector<unsigned> unsignedvector;
298 typedef std::vector<exvector> exvectorvector;
299
300 /** Perform automatic term rewriting rules in this class.  In the following
301  *  x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
302  *  stand for such expressions that contain a plain number.
303  *  - ncmul(...,*(x1,x2),...,ncmul(x3,x4),...) -> ncmul(...,x1,x2,...,x3,x4,...)  (associativity)
304  *  - ncmul(x) -> x
305  *  - ncmul() -> 1
306  *  - ncmul(...,c1,...,c2,...) -> *(c1,c2,ncmul(...))  (pull out commutative elements)
307  *  - ncmul(x1,y1,x2,y2) -> *(ncmul(x1,x2),ncmul(y1,y2))  (collect elements of same type)
308  *  - ncmul(x1,x2,x3,...) -> x::eval_ncmul(x1,x2,x3,...)
309  *
310  *  @param level cut-off in recursive evaluation */
311 ex ncmul::eval(int level) const
312 {
313         // The following additional rule would be nice, but produces a recursion,
314         // which must be trapped by introducing a flag that the sub-ncmuls()
315         // are already evaluated (maybe later...)
316         //                  ncmul(x1,x2,...,X,y1,y2,...) ->
317         //                      ncmul(ncmul(x1,x2,...),X,ncmul(y1,y2,...)
318         //                      (X noncommutative_composite)
319
320         if ((level==1) && (flags & status_flags::evaluated)) {
321                 return *this;
322         }
323
324         exvector evaledseq=evalchildren(level);
325
326         // ncmul(...,*(x1,x2),...,ncmul(x3,x4),...) ->
327         //     ncmul(...,x1,x2,...,x3,x4,...)  (associativity)
328         size_t factors = 0;
329         exvector::const_iterator cit = evaledseq.begin(), citend = evaledseq.end();
330         while (cit != citend)
331                 factors += count_factors(*cit++);
332         
333         exvector assocseq;
334         assocseq.reserve(factors);
335         cit = evaledseq.begin();
336         while (cit != citend)
337                 append_factors(assocseq, *cit++);
338         
339         // ncmul(x) -> x
340         if (assocseq.size()==1) return *(seq.begin());
341
342         // ncmul() -> 1
343         if (assocseq.empty()) return _ex1;
344
345         // determine return types
346         unsignedvector rettypes;
347         rettypes.reserve(assocseq.size());
348         size_t i = 0;
349         size_t count_commutative=0;
350         size_t count_noncommutative=0;
351         size_t count_noncommutative_composite=0;
352         cit = assocseq.begin(); citend = assocseq.end();
353         while (cit != citend) {
354                 switch (rettypes[i] = cit->return_type()) {
355                 case return_types::commutative:
356                         count_commutative++;
357                         break;
358                 case return_types::noncommutative:
359                         count_noncommutative++;
360                         break;
361                 case return_types::noncommutative_composite:
362                         count_noncommutative_composite++;
363                         break;
364                 default:
365                         throw(std::logic_error("ncmul::eval(): invalid return type"));
366                 }
367                 ++i; ++cit;
368         }
369         GINAC_ASSERT(count_commutative+count_noncommutative+count_noncommutative_composite==assocseq.size());
370
371         // ncmul(...,c1,...,c2,...) ->
372         //     *(c1,c2,ncmul(...)) (pull out commutative elements)
373         if (count_commutative!=0) {
374                 exvector commutativeseq;
375                 commutativeseq.reserve(count_commutative+1);
376                 exvector noncommutativeseq;
377                 noncommutativeseq.reserve(assocseq.size()-count_commutative);
378                 size_t num = assocseq.size();
379                 for (size_t i=0; i<num; ++i) {
380                         if (rettypes[i]==return_types::commutative)
381                                 commutativeseq.push_back(assocseq[i]);
382                         else
383                                 noncommutativeseq.push_back(assocseq[i]);
384                 }
385                 commutativeseq.push_back((new ncmul(noncommutativeseq,1))->setflag(status_flags::dynallocated));
386                 return (new mul(commutativeseq))->setflag(status_flags::dynallocated);
387         }
388                 
389         // ncmul(x1,y1,x2,y2) -> *(ncmul(x1,x2),ncmul(y1,y2))
390         //     (collect elements of same type)
391
392         if (count_noncommutative_composite==0) {
393                 // there are neither commutative nor noncommutative_composite
394                 // elements in assocseq
395                 GINAC_ASSERT(count_commutative==0);
396
397                 size_t assoc_num = assocseq.size();
398                 exvectorvector evv;
399                 unsignedvector rttinfos;
400                 evv.reserve(assoc_num);
401                 rttinfos.reserve(assoc_num);
402
403                 cit = assocseq.begin(), citend = assocseq.end();
404                 while (cit != citend) {
405                         unsigned ti = cit->return_type_tinfo();
406                         size_t rtt_num = rttinfos.size();
407                         // search type in vector of known types
408                         for (i=0; i<rtt_num; ++i) {
409                                 if (ti == rttinfos[i]) {
410                                         evv[i].push_back(*cit);
411                                         break;
412                                 }
413                         }
414                         if (i >= rtt_num) {
415                                 // new type
416                                 rttinfos.push_back(ti);
417                                 evv.push_back(exvector());
418                                 (evv.end()-1)->reserve(assoc_num);
419                                 (evv.end()-1)->push_back(*cit);
420                         }
421                         ++cit;
422                 }
423
424                 size_t evv_num = evv.size();
425 #ifdef DO_GINAC_ASSERT
426                 GINAC_ASSERT(evv_num == rttinfos.size());
427                 GINAC_ASSERT(evv_num > 0);
428                 size_t s=0;
429                 for (i=0; i<evv_num; ++i)
430                         s += evv[i].size();
431                 GINAC_ASSERT(s == assoc_num);
432 #endif // def DO_GINAC_ASSERT
433                 
434                 // if all elements are of same type, simplify the string
435                 if (evv_num == 1)
436                         return evv[0][0].eval_ncmul(evv[0]);
437                 
438                 exvector splitseq;
439                 splitseq.reserve(evv_num);
440                 for (i=0; i<evv_num; ++i)
441                         splitseq.push_back((new ncmul(evv[i]))->setflag(status_flags::dynallocated));
442                 
443                 return (new mul(splitseq))->setflag(status_flags::dynallocated);
444         }
445         
446         return (new ncmul(assocseq))->setflag(status_flags::dynallocated |
447                                                                                   status_flags::evaluated);
448 }
449
450 ex ncmul::evalm() const
451 {
452         // Evaluate children first
453         std::auto_ptr<exvector> s(new exvector);
454         s->reserve(seq.size());
455         exvector::const_iterator it = seq.begin(), itend = seq.end();
456         while (it != itend) {
457                 s->push_back(it->evalm());
458                 it++;
459         }
460
461         // If there are only matrices, simply multiply them
462         it = s->begin(); itend = s->end();
463         if (is_a<matrix>(*it)) {
464                 matrix prod(ex_to<matrix>(*it));
465                 it++;
466                 while (it != itend) {
467                         if (!is_a<matrix>(*it))
468                                 goto no_matrix;
469                         prod = prod.mul(ex_to<matrix>(*it));
470                         it++;
471                 }
472                 return prod;
473         }
474
475 no_matrix:
476         return (new ncmul(s))->setflag(status_flags::dynallocated);
477 }
478
479 ex ncmul::thiscontainer(const exvector & v) const
480 {
481         return (new ncmul(v))->setflag(status_flags::dynallocated);
482 }
483
484 ex ncmul::thiscontainer(std::auto_ptr<exvector> vp) const
485 {
486         return (new ncmul(vp))->setflag(status_flags::dynallocated);
487 }
488
489 ex ncmul::conjugate() const
490 {
491         if (return_type() != return_types::noncommutative) {
492                 return exprseq::conjugate();
493         }
494
495         if ((return_type_tinfo() & 0xffffff00U) != TINFO_clifford) {
496                 return exprseq::conjugate();
497         }
498
499         exvector ev;
500         ev.reserve(nops());
501         for (const_iterator i=end(); i!=begin();) {
502                 --i;
503                 ev.push_back(i->conjugate());
504         }
505         return (new ncmul(ev, true))->setflag(status_flags::dynallocated).eval();
506 }
507
508 // protected
509
510 /** Implementation of ex::diff() for a non-commutative product. It applies
511  *  the product rule.
512  *  @see ex::diff */
513 ex ncmul::derivative(const symbol & s) const
514 {
515         size_t num = seq.size();
516         exvector addseq;
517         addseq.reserve(num);
518         
519         // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
520         exvector ncmulseq = seq;
521         for (size_t i=0; i<num; ++i) {
522                 ex e = seq[i].diff(s);
523                 e.swap(ncmulseq[i]);
524                 addseq.push_back((new ncmul(ncmulseq))->setflag(status_flags::dynallocated));
525                 e.swap(ncmulseq[i]);
526         }
527         return (new add(addseq))->setflag(status_flags::dynallocated);
528 }
529
530 int ncmul::compare_same_type(const basic & other) const
531 {
532         return inherited::compare_same_type(other);
533 }
534
535 unsigned ncmul::return_type() const
536 {
537         if (seq.empty())
538                 return return_types::commutative;
539
540         bool all_commutative = true;
541         exvector::const_iterator noncommutative_element; // point to first found nc element
542
543         exvector::const_iterator i = seq.begin(), end = seq.end();
544         while (i != end) {
545                 unsigned rt = i->return_type();
546                 if (rt == return_types::noncommutative_composite)
547                         return rt; // one ncc -> mul also ncc
548                 if ((rt == return_types::noncommutative) && (all_commutative)) {
549                         // first nc element found, remember position
550                         noncommutative_element = i;
551                         all_commutative = false;
552                 }
553                 if ((rt == return_types::noncommutative) && (!all_commutative)) {
554                         // another nc element found, compare type_infos
555                         if (noncommutative_element->return_type_tinfo() != i->return_type_tinfo()) {
556                                 // diffent types -> mul is ncc
557                                 return return_types::noncommutative_composite;
558                         }
559                 }
560                 ++i;
561         }
562         // all factors checked
563         GINAC_ASSERT(!all_commutative); // not all factors should commutate, because this is a ncmul();
564         return all_commutative ? return_types::commutative : return_types::noncommutative;
565 }
566    
567 unsigned ncmul::return_type_tinfo() const
568 {
569         if (seq.empty())
570                 return tinfo_key;
571
572         // return type_info of first noncommutative element
573         exvector::const_iterator i = seq.begin(), end = seq.end();
574         while (i != end) {
575                 if (i->return_type() == return_types::noncommutative)
576                         return i->return_type_tinfo();
577                 ++i;
578         }
579
580         // no noncommutative element found, should not happen
581         return tinfo_key;
582 }
583
584 //////////
585 // new virtual functions which can be overridden by derived classes
586 //////////
587
588 // none
589
590 //////////
591 // non-virtual functions in this class
592 //////////
593
594 std::auto_ptr<exvector> ncmul::expandchildren(unsigned options) const
595 {
596         const_iterator cit = this->seq.begin(), end = this->seq.end();
597         while (cit != end) {
598                 const ex & expanded_ex = cit->expand(options);
599                 if (!are_ex_trivially_equal(*cit, expanded_ex)) {
600
601                         // copy first part of seq which hasn't changed
602                         std::auto_ptr<exvector> s(new exvector(this->seq.begin(), cit));
603                         reserve(*s, this->seq.size());
604
605                         // insert changed element
606                         s->push_back(expanded_ex);
607                         ++cit;
608
609                         // copy rest
610                         while (cit != end) {
611                                 s->push_back(cit->expand(options));
612                                 ++cit;
613                         }
614
615                         return s;
616                 }
617
618                 ++cit;
619         }
620
621         return std::auto_ptr<exvector>(0); // nothing has changed
622 }
623
624 const exvector & ncmul::get_factors() const
625 {
626         return seq;
627 }
628
629 //////////
630 // friend functions
631 //////////
632
633 ex reeval_ncmul(const exvector & v)
634 {
635         return (new ncmul(v))->setflag(status_flags::dynallocated);
636 }
637
638 ex hold_ncmul(const exvector & v)
639 {
640         if (v.empty())
641                 return _ex1;
642         else if (v.size() == 1)
643                 return v[0];
644         else
645                 return (new ncmul(v))->setflag(status_flags::dynallocated |
646                                                status_flags::evaluated);
647 }
648
649 } // namespace GiNaC