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