3 * Implementation of GiNaC's non-commutative products of expressions. */
6 * GiNaC Copyright (C) 1999-2025 Johannes Gutenberg University Mainz, Germany
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.
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.
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
38 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(ncmul, exprseq,
39 print_func<print_context>(&ncmul::do_print).
40 print_func<print_tree>(&ncmul::do_print_tree).
41 print_func<print_csrc>(&ncmul::do_print_csrc).
42 print_func<print_python_repr>(&ncmul::do_print_csrc))
46 // default constructor
59 ncmul::ncmul(const ex & lh, const ex & rh) : inherited{lh,rh}
63 ncmul::ncmul(const ex & f1, const ex & f2, const ex & f3) : inherited{f1,f2,f3}
67 ncmul::ncmul(const ex & f1, const ex & f2, const ex & f3,
68 const ex & f4) : inherited{f1,f2,f3,f4}
72 ncmul::ncmul(const ex & f1, const ex & f2, const ex & f3,
73 const ex & f4, const ex & f5) : inherited{f1,f2,f3,f4,f5}
77 ncmul::ncmul(const ex & f1, const ex & f2, const ex & f3,
78 const ex & f4, const ex & f5, const ex & f6) : inherited{f1,f2,f3,f4,f5,f6}
82 ncmul::ncmul(const exvector & v) : inherited(v)
86 ncmul::ncmul(exvector && v) : inherited(std::move(v))
96 // functions overriding virtual functions from base classes
101 void ncmul::do_print(const print_context & c, unsigned level) const
103 printseq(c, '(', '*', ')', precedence(), level);
106 void ncmul::do_print_csrc(const print_context & c, unsigned level) const
109 printseq(c, '(', ',', ')', precedence(), precedence());
112 bool ncmul::info(unsigned inf) const
114 return inherited::info(inf);
117 typedef std::vector<std::size_t> uintvector;
119 ex ncmul::expand(unsigned options) const
121 // First, expand the children
122 exvector v = expandchildren(options);
123 const exvector &expanded_seq = v.empty() ? this->seq : v;
125 // Now, look for all the factors that are sums and remember their
126 // position and number of terms.
127 uintvector positions_of_adds(expanded_seq.size());
128 uintvector number_of_add_operands(expanded_seq.size());
130 size_t number_of_adds = 0;
131 size_t number_of_expanded_terms = 1;
133 size_t current_position = 0;
134 for (auto & it : expanded_seq) {
135 if (is_exactly_a<add>(it)) {
136 positions_of_adds[number_of_adds] = current_position;
137 size_t num_ops = it.nops();
138 number_of_add_operands[number_of_adds] = num_ops;
139 number_of_expanded_terms *= num_ops;
145 // If there are no sums, we are done
146 if (number_of_adds == 0) {
148 return dynallocate<ncmul>(std::move(v)).setflag(options == 0 ? status_flags::expanded : 0);
153 // Now, form all possible products of the terms of the sums with the
154 // remaining factors, and add them together
156 distrseq.reserve(number_of_expanded_terms);
158 uintvector k(number_of_adds);
160 /* Rename indices in the static members of the product */
161 exvector expanded_seq_mod;
165 for (size_t i=0; i<expanded_seq.size(); i++) {
166 if (i == positions_of_adds[j]) {
167 expanded_seq_mod.push_back(_ex1);
170 expanded_seq_mod.push_back(rename_dummy_indices_uniquely(va, expanded_seq[i], true));
175 exvector term = expanded_seq_mod;
176 for (size_t i=0; i<number_of_adds; i++) {
177 term[positions_of_adds[i]] = rename_dummy_indices_uniquely(va, expanded_seq[positions_of_adds[i]].op(k[i]), true);
180 distrseq.push_back(dynallocate<ncmul>(std::move(term)).setflag(options == 0 ? status_flags::expanded : 0));
183 int l = number_of_adds-1;
184 while ((l>=0) && ((++k[l]) >= number_of_add_operands[l])) {
192 return dynallocate<add>(distrseq).setflag(options == 0 ? status_flags::expanded : 0);
195 int ncmul::degree(const ex & s) const
197 if (is_equal(ex_to<basic>(s)))
200 // Sum up degrees of factors
203 deg_sum += i.degree(s);
207 int ncmul::ldegree(const ex & s) const
209 if (is_equal(ex_to<basic>(s)))
212 // Sum up degrees of factors
215 deg_sum += i.degree(s);
219 ex ncmul::coeff(const ex & s, int n) const
221 if (is_equal(ex_to<basic>(s)))
222 return n==1 ? _ex1 : _ex0;
225 coeffseq.reserve(seq.size());
228 // product of individual coeffs
229 // if a non-zero power of s is found, the resulting product will be 0
230 for (auto & it : seq)
231 coeffseq.push_back(it.coeff(s,n));
232 return dynallocate<ncmul>(std::move(coeffseq));
235 bool coeff_found = false;
236 for (auto & i : seq) {
239 coeffseq.push_back(i);
241 coeffseq.push_back(c);
247 return dynallocate<ncmul>(std::move(coeffseq));
252 size_t ncmul::count_factors(const ex & e) const
254 if ((is_exactly_a<mul>(e)&&(e.return_type()!=return_types::commutative))||
255 (is_exactly_a<ncmul>(e))) {
257 for (size_t i=0; i<e.nops(); i++)
258 factors += count_factors(e.op(i));
265 void ncmul::append_factors(exvector & v, const ex & e) const
267 if ((is_exactly_a<mul>(e)&&(e.return_type()!=return_types::commutative))||
268 (is_exactly_a<ncmul>(e))) {
269 for (size_t i=0; i<e.nops(); i++)
270 append_factors(v, e.op(i));
275 typedef std::vector<unsigned> unsignedvector;
276 typedef std::vector<exvector> exvectorvector;
278 /** Perform automatic term rewriting rules in this class. In the following
279 * x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
280 * stand for such expressions that contain a plain number.
281 * - ncmul(...,*(x1,x2),...,ncmul(x3,x4),...) -> ncmul(...,x1,x2,...,x3,x4,...) (associativity)
284 * - ncmul(...,c1,...,c2,...) -> *(c1,c2,ncmul(...)) (pull out commutative elements)
285 * - ncmul(x1,y1,x2,y2) -> *(ncmul(x1,x2),ncmul(y1,y2)) (collect elements of same type)
286 * - ncmul(x1,x2,x3,...) -> x::eval_ncmul(x1,x2,x3,...)
288 ex ncmul::eval() const
290 // The following additional rule would be nice, but produces a recursion,
291 // which must be trapped by introducing a flag that the sub-ncmuls()
292 // are already evaluated (maybe later...)
293 // ncmul(x1,x2,...,X,y1,y2,...) ->
294 // ncmul(ncmul(x1,x2,...),X,ncmul(y1,y2,...)
295 // (X noncommutative_composite)
297 if (flags & status_flags::evaluated) {
301 // ncmul(...,*(x1,x2),...,ncmul(x3,x4),...) ->
302 // ncmul(...,x1,x2,...,x3,x4,...) (associativity)
304 for (auto & it : seq)
305 factors += count_factors(it);
308 assocseq.reserve(factors);
309 make_flat_inserter mf(seq, true);
310 for (auto & it : seq) {
311 ex factor = mf.handle_factor(it, 1);
312 append_factors(assocseq, factor);
316 if (assocseq.size()==1) return *(seq.begin());
319 if (assocseq.empty()) return _ex1;
321 // determine return types
322 unsignedvector rettypes(assocseq.size());
324 size_t count_commutative=0;
325 size_t count_noncommutative=0;
326 size_t count_noncommutative_composite=0;
327 for (auto & it : assocseq) {
328 rettypes[i] = it.return_type();
329 switch (rettypes[i]) {
330 case return_types::commutative:
333 case return_types::noncommutative:
334 count_noncommutative++;
336 case return_types::noncommutative_composite:
337 count_noncommutative_composite++;
340 throw(std::logic_error("ncmul::eval(): invalid return type"));
344 GINAC_ASSERT(count_commutative+count_noncommutative+count_noncommutative_composite==assocseq.size());
346 // ncmul(...,c1,...,c2,...) ->
347 // *(c1,c2,ncmul(...)) (pull out commutative elements)
348 if (count_commutative!=0) {
349 exvector commutativeseq;
350 commutativeseq.reserve(count_commutative+1);
351 exvector noncommutativeseq;
352 noncommutativeseq.reserve(assocseq.size()-count_commutative);
353 size_t num = assocseq.size();
354 for (size_t i=0; i<num; ++i) {
355 if (rettypes[i]==return_types::commutative)
356 commutativeseq.push_back(assocseq[i]);
358 noncommutativeseq.push_back(assocseq[i]);
360 commutativeseq.push_back(dynallocate<ncmul>(std::move(noncommutativeseq)));
361 return dynallocate<mul>(std::move(commutativeseq));
364 // ncmul(x1,y1,x2,y2) -> *(ncmul(x1,x2),ncmul(y1,y2))
365 // (collect elements of same type)
367 if (count_noncommutative_composite==0) {
368 // there are neither commutative nor noncommutative_composite
369 // elements in assocseq
370 GINAC_ASSERT(count_commutative==0);
372 size_t assoc_num = assocseq.size();
374 std::vector<return_type_t> rttinfos;
375 evv.reserve(assoc_num);
376 rttinfos.reserve(assoc_num);
378 for (auto & it : assocseq) {
379 return_type_t ti = it.return_type_tinfo();
380 size_t rtt_num = rttinfos.size();
381 // search type in vector of known types
382 for (i=0; i<rtt_num; ++i) {
383 if(ti == rttinfos[i]) {
384 evv[i].push_back(it);
390 rttinfos.push_back(ti);
391 evv.push_back(exvector());
392 (evv.end()-1)->reserve(assoc_num);
393 (evv.end()-1)->push_back(it);
397 size_t evv_num = evv.size();
398 #ifdef DO_GINAC_ASSERT
399 GINAC_ASSERT(evv_num == rttinfos.size());
400 GINAC_ASSERT(evv_num > 0);
402 for (i=0; i<evv_num; ++i)
404 GINAC_ASSERT(s == assoc_num);
405 #endif // def DO_GINAC_ASSERT
407 // if all elements are of same type, simplify the string
409 return evv[0][0].eval_ncmul(evv[0]);
413 splitseq.reserve(evv_num);
414 for (i=0; i<evv_num; ++i)
415 splitseq.push_back(dynallocate<ncmul>(evv[i]));
417 return dynallocate<mul>(splitseq);
420 return dynallocate<ncmul>(assocseq).setflag(status_flags::evaluated);
423 ex ncmul::evalm() const
425 // Evaluate children first
427 s.reserve(seq.size());
428 for (auto & it : seq)
429 s.push_back(it.evalm());
431 // If there are only matrices, simply multiply them
432 auto it = s.begin(), itend = s.end();
433 if (is_a<matrix>(*it)) {
434 matrix prod(ex_to<matrix>(*it));
436 while (it != itend) {
437 if (!is_a<matrix>(*it))
439 prod = prod.mul(ex_to<matrix>(*it));
446 return dynallocate<ncmul>(std::move(s));
449 ex ncmul::thiscontainer(const exvector & v) const
451 return dynallocate<ncmul>(v);
454 ex ncmul::thiscontainer(exvector && v) const
456 return dynallocate<ncmul>(std::move(v));
459 ex ncmul::conjugate() const
461 if (return_type() != return_types::noncommutative) {
462 return exprseq::conjugate();
465 if (!is_clifford_tinfo(return_type_tinfo())) {
466 return exprseq::conjugate();
471 for (auto i=end(); i!=begin();) {
473 ev.push_back(i->conjugate());
475 return dynallocate<ncmul>(std::move(ev));
478 ex ncmul::real_part() const
480 return basic::real_part();
483 ex ncmul::imag_part() const
485 return basic::imag_part();
490 /** Implementation of ex::diff() for a non-commutative product. It applies
493 ex ncmul::derivative(const symbol & s) const
495 size_t num = seq.size();
499 // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
500 exvector ncmulseq = seq;
501 for (size_t i=0; i<num; ++i) {
502 ex e = seq[i].diff(s);
504 addseq.push_back(dynallocate<ncmul>(ncmulseq));
507 return dynallocate<add>(addseq);
510 int ncmul::compare_same_type(const basic & other) const
512 return inherited::compare_same_type(other);
515 unsigned ncmul::return_type() const
518 return return_types::commutative;
520 bool all_commutative = true;
521 exvector::const_iterator noncommutative_element; // point to first found nc element
523 auto i = seq.begin(), end = seq.end();
525 unsigned rt = i->return_type();
526 if (rt == return_types::noncommutative_composite)
527 return rt; // one ncc -> mul also ncc
528 if ((rt == return_types::noncommutative) && (all_commutative)) {
529 // first nc element found, remember position
530 noncommutative_element = i;
531 all_commutative = false;
533 if ((rt == return_types::noncommutative) && (!all_commutative)) {
534 // another nc element found, compare type_infos
535 if(noncommutative_element->return_type_tinfo() != i->return_type_tinfo())
536 return return_types::noncommutative_composite;
540 // all factors checked
541 GINAC_ASSERT(!all_commutative); // not all factors should commutate, because this is a ncmul();
542 return all_commutative ? return_types::commutative : return_types::noncommutative;
545 return_type_t ncmul::return_type_tinfo() const
548 return make_return_type_t<ncmul>();
550 // return type_info of first noncommutative element
552 if (i.return_type() == return_types::noncommutative)
553 return i.return_type_tinfo();
555 // no noncommutative element found, should not happen
556 return make_return_type_t<ncmul>();
560 // new virtual functions which can be overridden by derived classes
566 // non-virtual functions in this class
569 exvector ncmul::expandchildren(unsigned options) const
571 auto cit = this->seq.begin(), end = this->seq.end();
573 const ex & expanded_ex = cit->expand(options);
574 if (!are_ex_trivially_equal(*cit, expanded_ex)) {
576 // copy first part of seq which hasn't changed
577 exvector s(this->seq.begin(), cit);
578 s.reserve(this->seq.size());
580 // insert changed element
581 s.push_back(expanded_ex);
586 s.push_back(cit->expand(options));
596 return exvector(); // nothing has changed
599 const exvector & ncmul::get_factors() const
608 ex reeval_ncmul(const exvector & v)
610 return dynallocate<ncmul>(v);
613 ex hold_ncmul(const exvector & v)
617 else if (v.size() == 1)
620 return dynallocate<ncmul>(v).setflag(status_flags::evaluated);
623 GINAC_BIND_UNARCHIVER(ncmul);