| 1 | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ |
| 2 | |
| 3 | /* |
| 4 | Copyright (C) 2012 Klaus Spanderen |
| 5 | |
| 6 | This file is part of QuantLib, a free-software/open-source library |
| 7 | for financial quantitative analysts and developers - http://quantlib.org/ |
| 8 | |
| 9 | QuantLib is free software: you can redistribute it and/or modify it |
| 10 | under the terms of the QuantLib license. You should have received a |
| 11 | copy of the license along with this program; if not, please email |
| 12 | <quantlib-dev@lists.sf.net>. The license is also available online at |
| 13 | <http://quantlib.org/license.shtml>. |
| 14 | |
| 15 | This program is distributed in the hope that it will be useful, but WITHOUT |
| 16 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
| 17 | FOR A PARTICULAR PURPOSE. See the license for more details. |
| 18 | */ |
| 19 | |
| 20 | /*! \file sparsematrix.hpp |
| 21 | \brief typedef for boost sparse matrix class |
| 22 | */ |
| 23 | |
| 24 | #ifndef quantlib_sparse_matrix_hpp |
| 25 | #define quantlib_sparse_matrix_hpp |
| 26 | |
| 27 | #include <ql/qldefines.hpp> |
| 28 | #include <ql/math/array.hpp> |
| 29 | |
| 30 | #if defined(QL_PATCH_MSVC) |
| 31 | #pragma warning(push) |
| 32 | #pragma warning(disable:4180) |
| 33 | #pragma warning(disable:4127) |
| 34 | #endif |
| 35 | |
| 36 | #if BOOST_VERSION == 106400 |
| 37 | #include <boost/serialization/array_wrapper.hpp> |
| 38 | #endif |
| 39 | |
| 40 | #include <boost/numeric/ublas/matrix_sparse.hpp> |
| 41 | |
| 42 | #if defined(QL_PATCH_MSVC) |
| 43 | #pragma warning(pop) |
| 44 | #endif |
| 45 | |
| 46 | namespace QuantLib { |
| 47 | |
| 48 | typedef boost::numeric::ublas::compressed_matrix<Real> SparseMatrix; |
| 49 | typedef boost::numeric::ublas::matrix_reference<SparseMatrix> SparseMatrixReference; |
| 50 | |
| 51 | inline Array prod(const SparseMatrix& A, const Array& x) { |
| 52 | QL_REQUIRE(x.size() == A.size2(), |
| 53 | "vectors and sparse matrices with different sizes (" |
| 54 | << x.size() << ", " << A.size1() << "x" << A.size2() << |
| 55 | ") cannot be multiplied" ); |
| 56 | |
| 57 | Array b(x.size(), 0.0); |
| 58 | |
| 59 | for (Size i=0; i < A.filled1()-1; ++i) { |
| 60 | const Size begin = A.index1_data()[i]; |
| 61 | const Size end = A.index1_data()[i+1]; |
| 62 | Real t=0; |
| 63 | for (Size j=begin; j < end; ++j) { |
| 64 | t += A.value_data()[j]*x[A.index2_data()[j]]; |
| 65 | } |
| 66 | |
| 67 | b[i]=t; |
| 68 | } |
| 69 | return b; |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | #endif |
| 74 | |