op_logmat_meat.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. // Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au)
  2. // Copyright 2008-2016 National ICT Australia (NICTA)
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // ------------------------------------------------------------------------
  15. //! \addtogroup op_logmat
  16. //! @{
  17. // Partly based on algorithm 11.9 (inverse scaling and squaring algorithm with Schur decomposition) in:
  18. // Nicholas J. Higham.
  19. // Functions of Matrices: Theory and Computation.
  20. // SIAM, 2008.
  21. // ISBN 978-0-89871-646-7
  22. template<typename T1>
  23. inline
  24. void
  25. op_logmat::apply(Mat< std::complex<typename T1::elem_type> >& out, const mtOp<std::complex<typename T1::elem_type>,T1,op_logmat>& in)
  26. {
  27. arma_extra_debug_sigprint();
  28. const bool status = op_logmat::apply_direct(out, in.m, in.aux_uword_a);
  29. if(status == false)
  30. {
  31. out.soft_reset();
  32. arma_stop_runtime_error("logmat(): transformation failed");
  33. }
  34. }
  35. template<typename T1>
  36. inline
  37. bool
  38. op_logmat::apply_direct(Mat< std::complex<typename T1::elem_type> >& out, const Op<T1,op_diagmat>& expr, const uword)
  39. {
  40. arma_extra_debug_sigprint();
  41. typedef typename T1::elem_type T;
  42. const diagmat_proxy<T1> P(expr.m);
  43. arma_debug_check( (P.n_rows != P.n_cols), "logmat(): given matrix must be square sized" );
  44. const uword N = P.n_rows;
  45. out.zeros(N,N); // aliasing can't happen as op_logmat is defined as cx_mat = op(mat)
  46. for(uword i=0; i<N; ++i)
  47. {
  48. const T val = P[i];
  49. if(val >= T(0))
  50. {
  51. out.at(i,i) = std::log(val);
  52. }
  53. else
  54. {
  55. out.at(i,i) = std::log( std::complex<T>(val) );
  56. }
  57. }
  58. return true;
  59. }
  60. template<typename T1>
  61. inline
  62. bool
  63. op_logmat::apply_direct(Mat< std::complex<typename T1::elem_type> >& out, const Base<typename T1::elem_type,T1>& expr, const uword n_iters)
  64. {
  65. arma_extra_debug_sigprint();
  66. typedef typename T1::elem_type in_T;
  67. typedef typename std::complex<in_T> out_T;
  68. const quasi_unwrap<T1> expr_unwrap(expr.get_ref());
  69. const Mat<in_T>& A = expr_unwrap.M;
  70. arma_debug_check( (A.is_square() == false), "logmat(): given matrix must be square sized" );
  71. if(A.n_elem == 0)
  72. {
  73. out.reset();
  74. return true;
  75. }
  76. else
  77. if(A.n_elem == 1)
  78. {
  79. out.set_size(1,1);
  80. out[0] = std::log( std::complex<in_T>( A[0] ) );
  81. return true;
  82. }
  83. if(A.is_diagmat())
  84. {
  85. const uword N = A.n_rows;
  86. out.zeros(N,N); // aliasing can't happen as op_logmat is defined as cx_mat = op(mat)
  87. for(uword i=0; i<N; ++i)
  88. {
  89. const in_T val = A.at(i,i);
  90. if(val >= in_T(0))
  91. {
  92. out.at(i,i) = std::log(val);
  93. }
  94. else
  95. {
  96. out.at(i,i) = std::log( out_T(val) );
  97. }
  98. }
  99. return true;
  100. }
  101. #if defined(ARMA_OPTIMISE_SYMPD)
  102. const bool try_sympd = sympd_helper::guess_sympd_anysize(A);
  103. #else
  104. const bool try_sympd = false;
  105. #endif
  106. if(try_sympd)
  107. {
  108. // if matrix A is sympd, all its eigenvalues are positive
  109. Col<in_T> eigval;
  110. Mat<in_T> eigvec;
  111. const bool eig_status = eig_sym_helper(eigval, eigvec, A, 'd', "logmat()");
  112. if(eig_status)
  113. {
  114. // ensure each eigenvalue is > 0
  115. const uword N = eigval.n_elem;
  116. const in_T* eigval_mem = eigval.memptr();
  117. bool all_pos = true;
  118. for(uword i=0; i<N; ++i) { all_pos = (eigval_mem[i] <= in_T(0)) ? false : all_pos; }
  119. if(all_pos)
  120. {
  121. eigval = log(eigval);
  122. out = conv_to< Mat<out_T> >::from( eigvec * diagmat(eigval) * eigvec.t() );
  123. return true;
  124. }
  125. }
  126. arma_extra_debug_print("warning: sympd optimisation failed");
  127. // fallthrough if eigen decomposition failed or an eigenvalue is zero
  128. }
  129. Mat<out_T> S(A.n_rows, A.n_cols);
  130. const in_T* Amem = A.memptr();
  131. out_T* Smem = S.memptr();
  132. const uword n_elem = A.n_elem;
  133. for(uword i=0; i<n_elem; ++i)
  134. {
  135. Smem[i] = std::complex<in_T>( Amem[i] );
  136. }
  137. return op_logmat_cx::apply_common(out, S, n_iters);
  138. }
  139. template<typename T1>
  140. inline
  141. void
  142. op_logmat_cx::apply(Mat<typename T1::elem_type>& out, const Op<T1,op_logmat_cx>& in)
  143. {
  144. arma_extra_debug_sigprint();
  145. const bool status = op_logmat_cx::apply_direct(out, in.m, in.aux_uword_a);
  146. if(status == false)
  147. {
  148. out.soft_reset();
  149. arma_stop_runtime_error("logmat(): transformation failed");
  150. }
  151. }
  152. template<typename T1>
  153. inline
  154. bool
  155. op_logmat_cx::apply_direct(Mat<typename T1::elem_type>& out, const Op<T1,op_diagmat>& expr, const uword)
  156. {
  157. arma_extra_debug_sigprint();
  158. typedef typename T1::elem_type eT;
  159. const diagmat_proxy<T1> P(expr.m);
  160. bool status = false;
  161. if(P.is_alias(out))
  162. {
  163. Mat<eT> tmp;
  164. status = op_logmat_cx::apply_direct_noalias(tmp, P);
  165. out.steal_mem(tmp);
  166. }
  167. else
  168. {
  169. status = op_logmat_cx::apply_direct_noalias(out, P);
  170. }
  171. return status;
  172. }
  173. template<typename T1>
  174. inline
  175. bool
  176. op_logmat_cx::apply_direct_noalias(Mat<typename T1::elem_type>& out, const diagmat_proxy<T1>& P)
  177. {
  178. arma_extra_debug_sigprint();
  179. arma_debug_check( (P.n_rows != P.n_cols), "logmat(): given matrix must be square sized" );
  180. const uword N = P.n_rows;
  181. out.zeros(N,N);
  182. for(uword i=0; i<N; ++i)
  183. {
  184. out.at(i,i) = std::log(P[i]);
  185. }
  186. return true;
  187. }
  188. template<typename T1>
  189. inline
  190. bool
  191. op_logmat_cx::apply_direct(Mat<typename T1::elem_type>& out, const Base<typename T1::elem_type,T1>& expr, const uword n_iters)
  192. {
  193. arma_extra_debug_sigprint();
  194. typedef typename T1::pod_type T;
  195. typedef typename T1::elem_type eT;
  196. Mat<eT> S = expr.get_ref();
  197. arma_debug_check( (S.n_rows != S.n_cols), "logmat(): given matrix must be square sized" );
  198. if(S.n_elem == 0)
  199. {
  200. out.reset();
  201. return true;
  202. }
  203. else
  204. if(S.n_elem == 1)
  205. {
  206. out.set_size(1,1);
  207. out[0] = std::log(S[0]);
  208. return true;
  209. }
  210. if(S.is_diagmat())
  211. {
  212. const uword N = S.n_rows;
  213. out.zeros(N,N); // aliasing can't happen as S is generated
  214. for(uword i=0; i<N; ++i) { out.at(i,i) = std::log( S.at(i,i) ); }
  215. return true;
  216. }
  217. #if defined(ARMA_OPTIMISE_SYMPD)
  218. const bool try_sympd = sympd_helper::guess_sympd_anysize(S);
  219. #else
  220. const bool try_sympd = false;
  221. #endif
  222. if(try_sympd)
  223. {
  224. // if matrix S is sympd, all its eigenvalues are positive
  225. Col< T> eigval;
  226. Mat<eT> eigvec;
  227. const bool eig_status = eig_sym_helper(eigval, eigvec, S, 'd', "logmat()");
  228. if(eig_status)
  229. {
  230. // ensure each eigenvalue is > 0
  231. const uword N = eigval.n_elem;
  232. const T* eigval_mem = eigval.memptr();
  233. bool all_pos = true;
  234. for(uword i=0; i<N; ++i) { all_pos = (eigval_mem[i] <= T(0)) ? false : all_pos; }
  235. if(all_pos)
  236. {
  237. eigval = log(eigval);
  238. out = eigvec * diagmat(eigval) * eigvec.t();
  239. return true;
  240. }
  241. }
  242. arma_extra_debug_print("warning: sympd optimisation failed");
  243. // fallthrough if eigen decomposition failed or an eigenvalue is zero
  244. }
  245. return op_logmat_cx::apply_common(out, S, n_iters);
  246. }
  247. template<typename T>
  248. inline
  249. bool
  250. op_logmat_cx::apply_common(Mat< std::complex<T> >& out, Mat< std::complex<T> >& S, const uword n_iters)
  251. {
  252. arma_extra_debug_sigprint();
  253. typedef typename std::complex<T> eT;
  254. Mat<eT> U;
  255. const bool schur_ok = auxlib::schur(U,S);
  256. if(schur_ok == false) { arma_extra_debug_print("logmat(): schur decomposition failed"); return false; }
  257. //double theta[] = { 1.10e-5, 1.82e-3, 1.62e-2, 5.39e-2, 1.14e-1, 1.87e-1, 2.64e-1 };
  258. double theta[] = { 0.0, 0.0, 1.6206284795015624e-2, 5.3873532631381171e-2, 1.1352802267628681e-1, 1.8662860613541288e-1, 2.642960831111435e-1 };
  259. // theta[0] and theta[1] not really used
  260. const uword N = S.n_rows;
  261. uword p = 0;
  262. uword m = 6;
  263. uword iter = 0;
  264. while(iter < n_iters)
  265. {
  266. const T tau = norm( (S - eye< Mat<eT> >(N,N)), 1 );
  267. if(tau <= theta[6])
  268. {
  269. p++;
  270. uword j1 = 0;
  271. uword j2 = 0;
  272. for(uword i=2; i<=6; ++i) { if( tau <= theta[i]) { j1 = i; break; } }
  273. for(uword i=2; i<=6; ++i) { if((tau/2.0) <= theta[i]) { j2 = i; break; } }
  274. // sanity check, for development purposes only
  275. arma_debug_check( (j2 > j1), "internal error: op_logmat::apply_direct(): j2 > j1" );
  276. if( ((j1 - j2) <= 1) || (p == 2) ) { m = j1; break; }
  277. }
  278. const bool sqrtmat_ok = op_sqrtmat_cx::apply_direct(S,S);
  279. if(sqrtmat_ok == false) { arma_extra_debug_print("logmat(): sqrtmat() failed"); return false; }
  280. iter++;
  281. }
  282. if(iter >= n_iters) { arma_debug_warn("logmat(): reached max iterations without full convergence"); }
  283. S.diag() -= eT(1);
  284. if(m >= 1)
  285. {
  286. const bool helper_ok = op_logmat_cx::helper(S,m);
  287. if(helper_ok == false) { return false; }
  288. }
  289. out = U * S * U.t();
  290. out *= eT(eop_aux::pow(double(2), double(iter)));
  291. return true;
  292. }
  293. template<typename eT>
  294. inline
  295. bool
  296. op_logmat_cx::helper(Mat<eT>& A, const uword m)
  297. {
  298. arma_extra_debug_sigprint();
  299. if(A.is_finite() == false) { return false; }
  300. const vec indices = regspace<vec>(1,m-1);
  301. mat tmp(m,m,fill::zeros);
  302. tmp.diag(-1) = indices / sqrt(square(2.0*indices) - 1.0);
  303. tmp.diag(+1) = indices / sqrt(square(2.0*indices) - 1.0);
  304. vec eigval;
  305. mat eigvec;
  306. const bool eig_ok = eig_sym_helper(eigval, eigvec, tmp, 'd', "logmat()");
  307. if(eig_ok == false) { arma_extra_debug_print("logmat(): eig_sym() failed"); return false; }
  308. const vec nodes = (eigval + 1.0) / 2.0;
  309. const vec weights = square(eigvec.row(0).t());
  310. const uword N = A.n_rows;
  311. Mat<eT> B(N,N,fill::zeros);
  312. Mat<eT> X;
  313. for(uword i=0; i < m; ++i)
  314. {
  315. // B += weights(i) * solve( (nodes(i)*A + eye< Mat<eT> >(N,N)), A );
  316. //const bool solve_ok = solve( X, (nodes(i)*A + eye< Mat<eT> >(N,N)), A, solve_opts::fast );
  317. const bool solve_ok = solve( X, trimatu(nodes(i)*A + eye< Mat<eT> >(N,N)), A );
  318. if(solve_ok == false) { arma_extra_debug_print("logmat(): solve() failed"); return false; }
  319. B += weights(i) * X;
  320. }
  321. A = B;
  322. return true;
  323. }
  324. template<typename T1>
  325. inline
  326. void
  327. op_logmat_sympd::apply(Mat<typename T1::elem_type>& out, const Op<T1,op_logmat_sympd>& in)
  328. {
  329. arma_extra_debug_sigprint();
  330. const bool status = op_logmat_sympd::apply_direct(out, in.m);
  331. if(status == false)
  332. {
  333. out.soft_reset();
  334. arma_stop_runtime_error("logmat_sympd(): transformation failed");
  335. }
  336. }
  337. template<typename T1>
  338. inline
  339. bool
  340. op_logmat_sympd::apply_direct(Mat<typename T1::elem_type>& out, const Base<typename T1::elem_type,T1>& expr)
  341. {
  342. arma_extra_debug_sigprint();
  343. #if defined(ARMA_USE_LAPACK)
  344. {
  345. typedef typename T1::pod_type T;
  346. typedef typename T1::elem_type eT;
  347. const unwrap<T1> U(expr.get_ref());
  348. const Mat<eT>& X = U.M;
  349. arma_debug_check( (X.is_square() == false), "logmat_sympd(): given matrix must be square sized" );
  350. Col< T> eigval;
  351. Mat<eT> eigvec;
  352. const bool status = eig_sym_helper(eigval, eigvec, X, 'd', "logmat_sympd()");
  353. if(status == false) { return false; }
  354. const uword N = eigval.n_elem;
  355. const T* eigval_mem = eigval.memptr();
  356. bool all_pos = true;
  357. for(uword i=0; i<N; ++i) { all_pos = (eigval_mem[i] <= T(0)) ? false : all_pos; }
  358. if(all_pos == false) { return false; }
  359. eigval = log(eigval);
  360. out = eigvec * diagmat(eigval) * eigvec.t();
  361. return true;
  362. }
  363. #else
  364. {
  365. arma_ignore(out);
  366. arma_ignore(expr);
  367. arma_stop_logic_error("logmat_sympd(): use of LAPACK must be enabled");
  368. return false;
  369. }
  370. #endif
  371. }
  372. //! @}