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