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