2 // Copyright (c) 2018-2019, Cem Bassoy, cem.bassoy@gmail.com
4 // Distributed under the Boost Software License, Version 1.0. (See
5 // accompanying file LICENSE_1_0.txt or copy at
6 // http://www.boost.org/LICENSE_1_0.txt)
8 // The authors gratefully acknowledge the support of
9 // Fraunhofer IOSB, Ettlingen, Germany
13 #ifndef BOOST_UBLAS_TENSOR_FUNCTIONS_HPP
14 #define BOOST_UBLAS_TENSOR_FUNCTIONS_HPP
23 #include "multiplication.hpp"
24 #include "algorithms.hpp"
25 #include "expression.hpp"
26 #include "expression_evaluation.hpp"
27 #include "storage_traits.hpp"
33 template<class Value, class Format, class Allocator>
36 template<class Value, class Format, class Allocator>
39 template<class Value, class Allocator>
45 /** @brief Computes the m-mode tensor-times-vector product
47 * Implements C[i1,...,im-1,im+1,...,ip] = A[i1,i2,...,ip] * b[im]
49 * @note calls ublas::ttv
51 * @param[in] m contraction dimension with 1 <= m <= p
52 * @param[in] a tensor object A with order p
53 * @param[in] b vector object B
55 * @returns tensor object C with order p-1, the same storage format and allocator type as A
57 template<class V, class F, class A1, class A2>
58 auto prod(tensor<V,F,A1> const& a, vector<V,A2> const& b, const std::size_t m)
61 using tensor_type = tensor<V,F,A1>;
62 using extents_type = typename tensor_type::extents_type;
63 using ebase_type = typename extents_type::base_type;
64 using value_type = typename tensor_type::value_type;
65 using size_type = typename extents_type::value_type;
67 auto const p = std::size_t(a.rank());
70 throw std::length_error("error in boost::numeric::ublas::prod(ttv): contraction mode must be greater than zero.");
73 throw std::length_error("error in boost::numeric::ublas::prod(ttv): rank of tensor must be greater than or equal to the modus.");
76 throw std::length_error("error in boost::numeric::ublas::prod(ttv): rank of tensor must be greater than zero.");
79 throw std::length_error("error in boost::numeric::ublas::prod(ttv): first argument tensor should not be empty.");
82 throw std::length_error("error in boost::numeric::ublas::prod(ttv): second argument vector should not be empty.");
85 auto nc = ebase_type(std::max(p-1, size_type(2)) , size_type(1));
86 auto nb = ebase_type{b.size(),1};
89 for(auto i = 0u, j = 0u; i < p; ++i)
91 nc[j++] = a.extents().at(i);
93 auto c = tensor_type(extents_type(nc),value_type{});
98 c.data(), c.extents().data(), c.strides().data(),
99 a.data(), a.extents().data(), a.strides().data(),
100 bb, nb.data(), nb.data());
108 /** @brief Computes the m-mode tensor-times-matrix product
110 * Implements C[i1,...,im-1,j,im+1,...,ip] = A[i1,i2,...,ip] * B[j,im]
112 * @note calls ublas::ttm
114 * @param[in] a tensor object A with order p
115 * @param[in] b vector object B
116 * @param[in] m contraction dimension with 1 <= m <= p
118 * @returns tensor object C with order p, the same storage format and allocator type as A
120 template<class V, class F, class A1, class A2>
121 auto prod(tensor<V,F,A1> const& a, matrix<V,F,A2> const& b, const std::size_t m)
124 using tensor_type = tensor<V,F,A1>;
125 using extents_type = typename tensor_type::extents_type;
126 using strides_type = typename tensor_type::strides_type;
127 using value_type = typename tensor_type::value_type;
130 auto const p = a.rank();
133 throw std::length_error("error in boost::numeric::ublas::prod(ttm): contraction mode must be greater than zero.");
135 if( p < m || m > a.extents().size())
136 throw std::length_error("error in boost::numeric::ublas::prod(ttm): rank of the tensor must be greater equal the modus.");
139 throw std::length_error("error in boost::numeric::ublas::prod(ttm): rank of the tensor must be greater than zero.");
142 throw std::length_error("error in boost::numeric::ublas::prod(ttm): first argument tensor should not be empty.");
144 if( b.size1()*b.size2() == 0)
145 throw std::length_error("error in boost::numeric::ublas::prod(ttm): second argument matrix should not be empty.");
148 auto nc = a.extents().base();
149 auto nb = extents_type {b.size1(),b.size2()};
150 auto wb = strides_type (nb);
154 auto c = tensor_type(extents_type(nc),value_type{});
159 c.data(), c.extents().data(), c.strides().data(),
160 a.data(), a.extents().data(), a.strides().data(),
161 bb, nb.data(), wb.data());
170 /** @brief Computes the q-mode tensor-times-tensor product
172 * Implements C[i1,...,ir,j1,...,js] = sum( A[i1,...,ir+q] * B[j1,...,js+q] )
174 * @note calls ublas::ttt
176 * na[phia[x]] = nb[phib[x]] for 1 <= x <= q
178 * @param[in] phia one-based permutation tuple of length q for the first input tensor a
179 * @param[in] phib one-based permutation tuple of length q for the second input tensor b
180 * @param[in] a left-hand side tensor with order r+q
181 * @param[in] b right-hand side tensor with order s+q
182 * @result tensor with order r+s
184 template<class V, class F, class A1, class A2>
185 auto prod(tensor<V,F,A1> const& a, tensor<V,F,A2> const& b,
186 std::vector<std::size_t> const& phia, std::vector<std::size_t> const& phib)
189 using tensor_type = tensor<V,F,A1>;
190 using extents_type = typename tensor_type::extents_type;
191 using value_type = typename tensor_type::value_type;
192 using size_type = typename extents_type::value_type;
194 auto const pa = a.rank();
195 auto const pb = b.rank();
197 auto const q = size_type(phia.size());
200 throw std::runtime_error("error in ublas::prod: order of left-hand side tensor must be greater than 0.");
202 throw std::runtime_error("error in ublas::prod: order of right-hand side tensor must be greater than 0.");
204 throw std::runtime_error("error in ublas::prod: number of contraction dimensions cannot be greater than the order of the left-hand side tensor.");
206 throw std::runtime_error("error in ublas::prod: number of contraction dimensions cannot be greater than the order of the right-hand side tensor.");
209 throw std::runtime_error("error in ublas::prod: permutation tuples must have the same length.");
212 throw std::runtime_error("error in ublas::prod: permutation tuple for the left-hand side tensor cannot be greater than the corresponding order.");
214 throw std::runtime_error("error in ublas::prod: permutation tuple for the right-hand side tensor cannot be greater than the corresponding order.");
217 auto const& na = a.extents();
218 auto const& nb = b.extents();
220 for(auto i = 0ul; i < q; ++i)
221 if( na.at(phia.at(i)-1) != nb.at(phib.at(i)-1))
222 throw std::runtime_error("error in ublas::prod: permutations of the extents are not correct.");
224 auto const r = pa - q;
225 auto const s = pb - q;
228 std::vector<std::size_t> phia1(pa), phib1(pb);
229 std::iota(phia1.begin(), phia1.end(), 1ul);
230 std::iota(phib1.begin(), phib1.end(), 1ul);
232 std::vector<std::size_t> nc( std::max ( r+s , size_type(2) ), size_type(1) );
234 for(auto i = 0ul; i < phia.size(); ++i)
235 * std::remove(phia1.begin(), phia1.end(), phia.at(i)) = phia.at(i);
237 //phia1.erase( std::remove(phia1.begin(), phia1.end(), phia.at(i)), phia1.end() ) ;
239 assert(phia1.size() == pa);
241 for(auto i = 0ul; i < r; ++i)
242 nc[ i ] = na[ phia1[ i ] - 1 ];
244 for(auto i = 0ul; i < phib.size(); ++i)
245 * std::remove(phib1.begin(), phib1.end(), phib.at(i)) = phib.at(i) ;
246 //phib1.erase( std::remove(phib1.begin(), phib1.end(), phia.at(i)), phib1.end() ) ;
248 assert(phib1.size() == pb);
250 for(auto i = 0ul; i < s; ++i)
251 nc[ r + i ] = nb[ phib1[ i ] - 1 ];
253 // std::copy( phib.begin(), phib.end(), phib1.end() );
255 assert( phia1.size() == pa );
256 assert( phib1.size() == pb );
258 auto c = tensor_type(extents_type(nc), value_type{});
261 phia1.data(), phib1.data(),
262 c.data(), c.extents().data(), c.strides().data(),
263 a.data(), a.extents().data(), a.strides().data(),
264 b.data(), b.extents().data(), b.strides().data());
269 //template<class V, class F, class A1, class A2, std::size_t N, std::size_t M>
270 //auto operator*( tensor_index<V,F,A1,N> const& lhs, tensor_index<V,F,A2,M> const& rhs)
275 /** @brief Computes the q-mode tensor-times-tensor product
277 * Implements C[i1,...,ir,j1,...,js] = sum( A[i1,...,ir+q] * B[j1,...,js+q] )
279 * @note calls ublas::ttt
281 * na[phi[x]] = nb[phi[x]] for 1 <= x <= q
283 * @param[in] phi one-based permutation tuple of length q for bot input tensors
284 * @param[in] a left-hand side tensor with order r+q
285 * @param[in] b right-hand side tensor with order s+q
286 * @result tensor with order r+s
288 template<class V, class F, class A1, class A2>
289 auto prod(tensor<V,F,A1> const& a, tensor<V,F,A2> const& b,
290 std::vector<std::size_t> const& phi)
292 return prod(a, b, phi, phi);
296 /** @brief Computes the inner product of two tensors
298 * Implements c = sum(A[i1,i2,...,ip] * B[i1,i2,...,jp])
300 * @note calls inner function
302 * @param[in] a tensor object A
303 * @param[in] b tensor object B
305 * @returns a value type.
307 template<class V, class F, class A1, class A2>
308 auto inner_prod(tensor<V,F,A1> const& a, tensor<V,F,A2> const& b)
310 using value_type = typename tensor<V,F,A1>::value_type;
312 if( a.rank() != b.rank() )
313 throw std::length_error("error in boost::numeric::ublas::inner_prod: Rank of both tensors must be the same.");
315 if( a.empty() || b.empty())
316 throw std::length_error("error in boost::numeric::ublas::inner_prod: Tensors should not be empty.");
318 if( a.extents() != b.extents())
319 throw std::length_error("error in boost::numeric::ublas::inner_prod: Tensor extents should be the same.");
321 return inner(a.rank(), a.extents().data(),
322 a.data(), a.strides().data(),
323 b.data(), b.strides().data(), value_type{0});
326 /** @brief Computes the outer product of two tensors
328 * Implements C[i1,...,ip,j1,...,jq] = A[i1,i2,...,ip] * B[j1,j2,...,jq]
330 * @note calls outer function
332 * @param[in] a tensor object A
333 * @param[in] b tensor object B
335 * @returns tensor object C with the same storage format F and allocator type A1
337 template<class V, class F, class A1, class A2>
338 auto outer_prod(tensor<V,F,A1> const& a, tensor<V,F,A2> const& b)
340 using tensor_type = tensor<V,F,A1>;
341 using extents_type = typename tensor_type::extents_type;
343 if( a.empty() || b.empty() )
344 throw std::runtime_error("error in boost::numeric::ublas::outer_prod: tensors should not be empty.");
346 auto nc = typename extents_type::base_type(a.rank() + b.rank());
347 for(auto i = 0u; i < a.rank(); ++i)
348 nc.at(i) = a.extents().at(i);
350 for(auto i = 0u; i < b.rank(); ++i)
351 nc.at(a.rank()+i) = b.extents().at(i);
353 auto c = tensor_type(extents_type(nc));
355 outer(c.data(), c.rank(), c.extents().data(), c.strides().data(),
356 a.data(), a.rank(), a.extents().data(), a.strides().data(),
357 b.data(), b.rank(), b.extents().data(), b.strides().data());
364 /** @brief Transposes a tensor according to a permutation tuple
366 * Implements C[tau[i1],tau[i2]...,tau[ip]] = A[i1,i2,...,ip]
368 * @note calls trans function
370 * @param[in] a tensor object of rank p
371 * @param[in] tau one-based permutation tuple of length p
372 * @returns a transposed tensor object with the same storage format F and allocator type A
374 template<class V, class F, class A>
375 auto trans(tensor<V,F,A> const& a, std::vector<std::size_t> const& tau)
377 using tensor_type = tensor<V,F,A>;
378 using extents_type = typename tensor_type::extents_type;
379 // using strides_type = typename tensor_type::strides_type;
382 return tensor<V,F,A>{};
384 auto const p = a.rank();
385 auto const& na = a.extents();
387 auto nc = typename extents_type::base_type (p);
388 for(auto i = 0u; i < p; ++i)
389 nc.at(tau.at(i)-1) = na.at(i);
391 // auto wc = strides_type(extents_type(nc));
393 auto c = tensor_type(extents_type(nc));
396 trans( a.rank(), a.extents().data(), tau.data(),
397 c.data(), c.strides().data(),
398 a.data(), a.strides().data());
400 // auto wc_pi = typename strides_type::base_type (p);
401 // for(auto i = 0u; i < p; ++i)
402 // wc_pi.at(tau.at(i)-1) = c.strides().at(i);
406 // a.extents().data(),
407 // c.data(), wc_pi.data(),
408 // a.data(), a.strides().data() );
413 /** @brief Computes the frobenius norm of a tensor expression
415 * @note evaluates the tensor expression and calls the accumulate function
418 * Implements the two-norm with
419 * k = sqrt( sum_(i1,...,ip) A(i1,...,ip)^2 )
421 * @param[in] a tensor object of rank p
422 * @returns the frobenius norm of the tensor
424 //template<class V, class F, class A>
425 //auto norm(tensor<V,F,A> const& a)
426 template<class T, class D>
427 auto norm(detail::tensor_expression<T,D> const& expr)
430 using tensor_type = typename detail::tensor_expression<T,D>::tensor_type;
431 using value_type = typename tensor_type::value_type;
433 auto a = tensor_type( expr );
436 throw std::runtime_error("error in boost::numeric::ublas::norm: tensors should not be empty.");
438 return std::sqrt( accumulate( a.order(), a.extents().data(), a.data(), a.strides().data(), value_type{},
439 [](auto const& l, auto const& r){ return l + r*r; } ) ) ;
444 /** @brief Extract the real component of tensor elements within a tensor expression
446 * @param[in] lhs tensor expression
447 * @returns unary tensor expression
449 template<class T, class D>
450 auto real(detail::tensor_expression<T,D> const& expr) {
451 return detail::make_unary_tensor_expression<T> (expr(), [] (auto const& l) { return std::real( l ); } );
454 /** @brief Extract the real component of tensor elements within a tensor expression
456 * @param[in] lhs tensor expression
457 * @returns unary tensor expression
459 template<class V, class F, class A, class D>
460 auto real(detail::tensor_expression<tensor<std::complex<V>,F,A>,D> const& expr)
462 using tensor_complex_type = tensor<std::complex<V>,F,A>;
463 using tensor_type = tensor<V,F,typename storage_traits<A>::template rebind<V>>;
465 if( detail::retrieve_extents( expr ).empty() )
466 throw std::runtime_error("error in boost::numeric::ublas::real: tensors should not be empty.");
468 auto a = tensor_complex_type( expr );
469 auto c = tensor_type( a.extents() );
471 std::transform( a.begin(), a.end(), c.begin(), [](auto const& l){ return std::real(l) ; } );
477 /** @brief Extract the imaginary component of tensor elements within a tensor expression
479 * @param[in] lhs tensor expression
480 * @returns unary tensor expression
482 template<class T, class D>
483 auto imag(detail::tensor_expression<T,D> const& lhs) {
484 return detail::make_unary_tensor_expression<T> (lhs(), [] (auto const& l) { return std::imag( l ); } );
488 /** @brief Extract the imag component of tensor elements within a tensor expression
490 * @param[in] lhs tensor expression
491 * @returns unary tensor expression
493 template<class V, class A, class F, class D>
494 auto imag(detail::tensor_expression<tensor<std::complex<V>,F,A>,D> const& expr)
496 using tensor_complex_type = tensor<std::complex<V>,F,A>;
497 using tensor_type = tensor<V,F,typename storage_traits<A>::template rebind<V>>;
499 if( detail::retrieve_extents( expr ).empty() )
500 throw std::runtime_error("error in boost::numeric::ublas::real: tensors should not be empty.");
502 auto a = tensor_complex_type( expr );
503 auto c = tensor_type( a.extents() );
505 std::transform( a.begin(), a.end(), c.begin(), [](auto const& l){ return std::imag(l) ; } );
510 /** @brief Computes the complex conjugate component of tensor elements within a tensor expression
512 * @param[in] expr tensor expression
513 * @returns complex tensor
515 template<class T, class D>
516 auto conj(detail::tensor_expression<T,D> const& expr)
518 using tensor_type = T;
519 using value_type = typename tensor_type::value_type;
520 using layout_type = typename tensor_type::layout_type;
521 using array_type = typename tensor_type::array_type;
523 using new_value_type = std::complex<value_type>;
524 using new_array_type = typename storage_traits<array_type>::template rebind<new_value_type>;
526 using tensor_complex_type = tensor<new_value_type,layout_type, new_array_type>;
528 if( detail::retrieve_extents( expr ).empty() )
529 throw std::runtime_error("error in boost::numeric::ublas::conj: tensors should not be empty.");
531 auto a = tensor_type( expr );
532 auto c = tensor_complex_type( a.extents() );
534 std::transform( a.begin(), a.end(), c.begin(), [](auto const& l){ return std::conj(l) ; } );
540 /** @brief Computes the complex conjugate component of tensor elements within a tensor expression
542 * @param[in] lhs tensor expression
543 * @returns unary tensor expression
545 template<class V, class A, class F, class D>
546 auto conj(detail::tensor_expression<tensor<std::complex<V>,F,A>,D> const& expr)
548 return detail::make_unary_tensor_expression<tensor<std::complex<V>,F,A>> (expr(), [] (auto const& l) { return std::conj( l ); } );