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