Debian Codegraph @

dune/python/istl/bcrsmatrix.hh

raw
1 // SPDX-FileCopyrightText: Copyright © DUNE Project contributors, see file LICENSE.md in module root
2 // SPDX-License-Identifier: LicenseRef-GPL-2.0-only-with-DUNE-exception
3 #ifndef DUNE_PYTHON_ISTL_BCRSMATRIX_HH
4 #define DUNE_PYTHON_ISTL_BCRSMATRIX_HH
5
6 #include <memory>
7 #include <stdexcept>
8 #include <string>
9 #include <tuple>
10
11 #include <dune/python/common/fvecmatregistry.hh>
12
13 #include <dune/istl/bcrsmatrix.hh>
14 #include <dune/istl/bvector.hh>
15 #include <dune/istl/io.hh>
16 #include <dune/istl/matrixmarket.hh>
17 #include <dune/istl/matrixindexset.hh>
18 #include <dune/istl/operators.hh>
19
20 #include <dune/python/pybind11/pybind11.h>
21 #include <dune/python/pybind11/stl.h>
22 #include <dune/python/istl/bvector.hh>
23 #include <dune/python/istl/iterator.hh>
24 #include <dune/python/istl/operators.hh>
25
26 namespace Dune
27 {
28
29 namespace Python
30 {
31
32 namespace detail
33 {
34
35 template< class Matrix >
36 struct CorrespondingVectors;
37
38 template< class B, class A >
39 struct CorrespondingVectors< BCRSMatrix< B, A > >
40 {
41 typedef BlockVector< typename CorrespondingVectors< B >::Domain, typename std::allocator_traits< A >::template rebind_alloc< typename CorrespondingVectors< B >::Domain > > Domain;
42 typedef BlockVector< typename CorrespondingVectors< B >::Range, typename std::allocator_traits< A >::template rebind_alloc< typename CorrespondingVectors< B >::Range > > Range;
43 };
44
45 template< class K, int ROWS, int COLS >
46 struct CorrespondingVectors< FieldMatrix< K, ROWS, COLS > >
47 {
48 typedef FieldVector< K, COLS > Domain;
49 typedef FieldVector< K, ROWS > Range;
50 };
51
52 } // namespace detail
53
54
55
56 // CorrespondingDomainVector
57 // -------------------------
58
59 template< class Matrix >
60 using CorrespondingDomainVector = typename detail::CorrespondingVectors< Matrix >::Domain;
61
62
63
64
65 // CorrespondingRangeVector
66 // ------------------------
67
68 template< class Matrix >
69 using CorrespondingRangeVector = typename detail::CorrespondingVectors< Matrix >::Range;
70
71
72
73 // registerBCRSMatrix
74 // ------------------
75
76 template <class BCRSMatrix, class... options>
77 void registerBCRSMatrix(pybind11::handle scope,
78 pybind11::class_<BCRSMatrix, options...> cls)
79 {
80 using pybind11::operator""_a;
81 typedef typename BCRSMatrix::block_type block_type;
82 typedef typename BCRSMatrix::field_type field_type;
83 typedef typename BCRSMatrix::size_type Size;
84 typedef typename BCRSMatrix::row_type row_type;
85
86 typedef typename BCRSMatrix::BuildMode BuildMode;
87
88 registerFieldVecMat<block_type>::apply();
89
90 pybind11::class_< row_type > clsRow( scope, "BCRSMatrixRow" );
91 registerBlockVector( clsRow );
92
93 pybind11::enum_< typename BCRSMatrix::BuildStage > bs( cls, "BuildStage" );
94 bs.value( "notAllocated", BCRSMatrix::notAllocated );
95 bs.value( "building", BCRSMatrix::building );
96 bs.value( "rowSizesBuilt", BCRSMatrix::rowSizesBuilt );
97 bs.value( "built", BCRSMatrix::built );
98 bs.export_values();
99
100 cls.def( pybind11::init( [] () { return new BCRSMatrix(); } ) );
101 typedef Dune::BCRSMatrix< Dune::FieldMatrix< double, 1, 1 > > Matrix;
102 using BuildMode11 = Matrix::BuildMode;
103 cls.def( pybind11::init( [] ( Size rows, Size cols, Size nnz, BuildMode11 buildMode ) { return new BCRSMatrix( rows, cols, nnz, static_cast<BuildMode>(buildMode) ); } ), "rows"_a, "cols"_a, "nnz"_a = 0, "buildMode"_a );
104 cls.def( pybind11::init( [] ( std::tuple< Size, Size > shape, Size nnz, BuildMode11 buildMode ) { return new BCRSMatrix( std::get< 0 >( shape ), std::get< 1 >( shape ), nnz, static_cast<BuildMode>(buildMode) ); } ), "shape"_a, "nnz"_a = 0, "buildMode"_a );
105 cls.def( pybind11::init( [] ( Size rows, Size cols, Size average, double overflow, BuildMode11 buildMode ) { return new BCRSMatrix( rows, cols, average, overflow, static_cast<BuildMode>(buildMode) ); } ), "rows"_a, "cols"_a, "average"_a, "overflow"_a, "buildMode"_a );
106 cls.def( pybind11::init( [] ( std::tuple< Size, Size > shape, Size average, double overflow, BuildMode11 buildMode ) { return new BCRSMatrix( std::get< 0 >( shape ), std::get< 1 >( shape ), average, overflow, static_cast<BuildMode>(buildMode) ); } ), "shape"_a, "average"_a, "overflow"_a, "buildMode"_a );
107 if (!std::is_same<Matrix,BCRSMatrix>::value)
108 {
109 pybind11::enum_< BuildMode > bm( cls, "BuildMode" );
110 bm.value( "row_wise", BCRSMatrix::row_wise );
111 bm.value( "random", BCRSMatrix::random );
112 bm.value( "implicit", BCRSMatrix::implicit );
113 // bm.value( "unknown", BCRSMatrix::unknown );
114 bm.export_values();
115 cls.def( pybind11::init( [] ( Size rows, Size cols, Size nnz, BuildMode buildMode ) { return new BCRSMatrix( rows, cols, nnz, static_cast<BuildMode>(buildMode) ); } ), "rows"_a, "cols"_a, "nnz"_a = 0, "buildMode"_a );
116 cls.def( pybind11::init( [] ( std::tuple< Size, Size > shape, Size nnz, BuildMode buildMode ) { return new BCRSMatrix( std::get< 0 >( shape ), std::get< 1 >( shape ), nnz, buildMode ); } ), "shape"_a, "nnz"_a = 0, "buildMode"_a );
117 cls.def( pybind11::init( [] ( Size rows, Size cols, Size average, double overflow, BuildMode buildMode ) { return new BCRSMatrix( rows, cols, average, overflow, buildMode ); } ), "rows"_a, "cols"_a, "average"_a, "overflow"_a, "buildMode"_a );
118 cls.def( pybind11::init( [] ( std::tuple< Size, Size > shape, Size average, double overflow, BuildMode buildMode ) { return new BCRSMatrix( std::get< 0 >( shape ), std::get< 1 >( shape ), average, overflow, buildMode ); } ), "shape"_a, "average"_a, "overflow"_a, "buildMode"_a );
119 }
120
121 detail::registerISTLIterators( cls );
122
123 // shape
124 cls.def_property_readonly( "rows", [] ( const BCRSMatrix &self ) { return self.N(); } );
125 cls.def_property_readonly( "cols", [] ( const BCRSMatrix &self ) { return self.M(); } );
126 cls.def_property_readonly( "shape", [] ( const BCRSMatrix &self ) { return std::make_tuple( self.N(), self.M() ); } );
127 cls.def_property_readonly( "nonZeroes", [] ( const BCRSMatrix &self ) { return self.nonzeroes(); } );
128
129 cls.def( "setSize", [] ( BCRSMatrix &self, Size rows, Size cols, Size nnz ) { self.setSize( rows, cols, nnz ); }, "rows"_a, "cols"_a, "nnz"_a = 0 );
130 cls.def( "setSize", [] ( BCRSMatrix &self, std::tuple< Size, Size > shape, Size nnz ) { self.setSize( std::get< 0 >( shape ), std::get< 1 >( shape ), nnz ); }, "shape"_a, "nnz"_a = 0 );
131
132 // build parameters
133 cls.def_property( "buildMode", [] ( const BCRSMatrix &self ) {
134 BuildMode bm = self.buildMode();
135 if( bm == BCRSMatrix::unknown )
136 return pybind11::object();
137 else
138 return pybind11::cast( bm );
139 }, [] ( BCRSMatrix &self, BuildMode buildMode ) {
140 self.setBuildMode( buildMode );
141 } );
142 cls.def_property_readonly( "buildStage", [] ( const BCRSMatrix &self ) { return self.buildStage(); } );
143 cls.def( "setImplicitBuildModeParameters", [] ( BCRSMatrix &self, Size average, double overflow ) { self.setImplicitBuildModeParameters( average, overflow ); }, "average"_a, "overflow"_a );
144
145 // random build mode
146 cls.def( "setRowSize", [] ( BCRSMatrix &self, Size row, Size size ) { self.setrowsize( row, size ); }, "row"_a, "size"_a );
147 cls.def( "getRowSize", [] ( const BCRSMatrix &self, Size row ) { return self.getrowsize( row ); }, "row"_a );
148 cls.def( "endRowSizes", [] ( BCRSMatrix &self ) { self.endrowsizes(); } );
149
150 cls.def( "addIndex", [] ( BCRSMatrix &self, Size row, Size col ) { self.addindex( row, col ); }, "row"_a, "col"_a );
151 cls.def( "addIndex", [] ( BCRSMatrix &self, std::tuple< Size, Size > index ) { self.addindex( std::get< 0 >( index ), std::get< 1 >( index ) ); }, "index"_a );
152 cls.def( "setIndices", [] ( BCRSMatrix &self, Size row, pybind11::buffer buffer ) {
153 pybind11::buffer_info info = buffer.request();
154 if( info.format != pybind11::format_descriptor< Size >::format() )
155 throw std::invalid_argument( "Incompatible buffer format." );
156 if( (info.ndim != 1) || (static_cast< Size >( info.shape[ 0 ] ) != self.getrowsize( row )) )
157 throw std::invalid_argument( "Indices must be a flat array with length" + std::to_string( self.getrowsize( row ) ) + "." );
158 self.setIndices( row, static_cast< const Size * >( info.ptr ), static_cast< const Size * >( info.ptr ) + info.shape[ 0 ] );
159 }, "row"_a, "indices"_a );
160 cls.def( "setIndices", [] ( BCRSMatrix &self, Size row, std::vector< Size > indices ) {
161 if( static_cast< Size >( indices.size() ) != self.getrowsize( row ) )
162 throw std::invalid_argument( "len( indices ) must match previously set row size, i.e., " + std::to_string( self.getrowsize( row ) ) + "." );
163 self.setIndices( row, indices.begin(), indices.end() );
164 } );
165 cls.def( "endIndices", [] ( BCRSMatrix &self ) { self.endindices(); } );
166
167 // implicit build mode
168 cls.def( "compress", [] ( BCRSMatrix &self ) {
169 auto result = self.compress();
170 return std::make_tuple( result.maximum, result.overflow_total, result.avg, result.mem_ratio );
171 } );
172
173 // index access
174 cls.def( "__contains__", [] ( const BCRSMatrix &self, std::tuple< Size, Size > index ) { return self.exists( std::get< 0 >( index ), std::get< 1 >( index ) ); } );
175
176 cls.def( "__getitem__", [] ( BCRSMatrix &self, Size row ) -> row_type & {
177 if( row >= self.N() )
178 throw pybind11::index_error( "No such row: " + std::to_string( row ) );
179 return self[ row ];
180 }, pybind11::return_value_policy::reference); // , pybind11::keep_alive< 0, 1 >() );
181 cls.def( "__getitem__", [] ( BCRSMatrix &self, std::tuple< Size, Size > index ) -> block_type & {
182 const Size row = std::get< 0 >( index );
183 if( row >= self.N() )
184 throw pybind11::index_error( "No such row: " + std::to_string( row ) );
185
186 const Size col = std::get< 1 >( index );
187 if( col >= self.M() )
188 throw pybind11::index_error( "No such column: " + std::to_string( col ) );
189
190 if( self.buildMode() != BCRSMatrix::implicit || self.buildStage() == BCRSMatrix::built )
191 {
192 auto pos = self[ row ].find( col );
193 if( pos != self[ row ].end() )
194 return *pos;
195 else
196 throw pybind11::index_error( "Index (" + std::to_string( row ) + ", " + std::to_string( col ) + ") not in sparsity pattern." );
197 }
198 else
199 return self.entry( row, col );
200 }, pybind11::return_value_policy::reference, pybind11::keep_alive< 0, 1 >() );
201
202 cls.def( "__setitem__", [] ( BCRSMatrix &self, Size row, row_type &value ) {
203 if( row >= self.N() )
204 throw pybind11::index_error( "No such row: " + std::to_string( row ) );
205 if( &value != &self[ row ] )
206 throw pybind11::value_error( "Can only assign row to itself" );
207 } );
208 cls.def( "__setitem__", [] ( BCRSMatrix &self, std::tuple< Size, Size > index, block_type value ) {
209 const Size row = std::get< 0 >( index );
210 if( row >= self.N() )
211 throw pybind11::index_error( "No such row: " + std::to_string( row ) );
212
213 const Size col = std::get< 1 >( index );
214 if( col >= self.M() )
215 throw pybind11::index_error( "No such column: " + std::to_string( col ) );
216
217 if( self.buildMode() != BCRSMatrix::implicit || self.buildStage() == BCRSMatrix::built )
218 {
219 auto pos = self[ row ].find( col );
220 if( pos != self[ row ].end() )
221 *pos = value;
222 else
223 throw pybind11::index_error( "Index (" + std::to_string( row ) + ", " + std::to_string( col ) + ") not in sparsity pattern." );
224 }
225 else
226 self.entry( row, col ) = value;
227 } );
228 cls.def( "__setitem__", [] ( BCRSMatrix &self, std::tuple< Size, pybind11::slice > index, pybind11::iterable value ) {
229 const Size row = std::get< 0 >( index );
230 if( row > self.N() )
231 throw pybind11::index_error( "No such row" );
232
233 std::size_t cstart, cstop, cstep, clength;
234 std::get< 1 >( index ).compute( self.M(), &cstart, &cstop, &cstep, &clength );
235
236 if( self.buildMode() != BCRSMatrix::implicit || self.buildStage() == BCRSMatrix::built )
237 {
238 for( auto v : value )
239 {
240 if( cstart >= cstop )
241 throw pybind11::value_error( "too many values passed" );
242 self.entry( row, cstart ) = pybind11::cast< block_type >( v );
243 cstart += cstep;
244 }
245 if( cstart < cstop )
246 throw pybind11::value_error( "too few values passed" );
247 }
248 else
249 {
250 for( auto v : value )
251 {
252 if( cstart >= cstop )
253 throw pybind11::value_error( "too many values passed" );
254 auto pos = self[ row ].find( cstart );
255 if( pos != self[ row ].end() )
256 *pos = pybind11::cast< block_type >( v );
257 else
258 throw pybind11::index_error();
259 cstart += cstep;
260 }
261 if( cstart < cstop )
262 throw pybind11::value_error( "too few values passed" );
263 }
264 } );
265
266 // matrix-vector multiplication
267 cls.def( "mv", [] ( const BCRSMatrix &self, const CorrespondingDomainVector< BCRSMatrix > &x, CorrespondingRangeVector< BCRSMatrix > &y ) {
268 return self.mv( x, y );
269 }, "x"_a, "y"_a );
270 cls.def( "umv", [] ( const BCRSMatrix &self, const CorrespondingDomainVector< BCRSMatrix > &x, CorrespondingRangeVector< BCRSMatrix > &y ) {
271 return self.umv( x, y );
272 }, "x"_a, "y"_a );
273 cls.def( "mmv", [] ( const BCRSMatrix &self, const CorrespondingDomainVector< BCRSMatrix > &x, CorrespondingRangeVector< BCRSMatrix > &y ) {
274 return self.mmv( x, y );
275 }, "x"_a, "y"_a );
276 cls.def( "usmv", [] ( const BCRSMatrix &self, const field_type &alpha, const CorrespondingDomainVector< BCRSMatrix > &x, CorrespondingRangeVector< BCRSMatrix > &y ) {
277 return self.usmv( alpha, x, y );
278 }, "alpha"_a, "x"_a, "y"_a );
279
280 cls.def( "mtv", [] ( const BCRSMatrix &self, const CorrespondingRangeVector< BCRSMatrix > &x, CorrespondingDomainVector< BCRSMatrix > &y ) {
281 return self.mtv( x, y );
282 }, "x"_a, "y"_a );
283 cls.def( "umtv", [] ( const BCRSMatrix &self, const CorrespondingRangeVector< BCRSMatrix > &x, CorrespondingDomainVector< BCRSMatrix > &y ) {
284 return self.umtv( x, y );
285 }, "x"_a, "y"_a );
286 cls.def( "mmtv", [] ( const BCRSMatrix &self, const CorrespondingRangeVector< BCRSMatrix > &x, CorrespondingDomainVector< BCRSMatrix > &y ) {
287 return self.mmtv( x, y );
288 }, "x"_a, "y"_a );
289 cls.def( "usmtv", [] ( const BCRSMatrix &self, const field_type &alpha, const CorrespondingRangeVector< BCRSMatrix > &x, CorrespondingDomainVector< BCRSMatrix > &y ) {
290 return self.usmtv( alpha, x, y );
291 }, "alpha"_a, "x"_a, "y"_a );
292
293 // norms
294 cls.def_property_readonly( "frobenius_norm", [] ( const BCRSMatrix &self ) { return self.frobenius_norm(); } );
295 cls.def_property_readonly( "frobenius_norm2", [] ( const BCRSMatrix &self ) { return self.frobenius_norm2(); } );
296 cls.def_property_readonly( "infinity_norm", [] ( const BCRSMatrix &self ) { return self.infinity_norm(); } );
297 cls.def_property_readonly( "infinity_norm_real", [] ( const BCRSMatrix &self ) { return self.infinity_norm_real(); } );
298
299 // io
300 cls.def( "load", [] ( BCRSMatrix &self, const std::string &fileName, std::string format ) {
301 if( (format == "matrixmarket") || (format == "mm") )
302 loadMatrixMarket( self, fileName );
303 else
304 throw std::invalid_argument( "Unknown format: " + format );
305 }, "fileName"_a, "format"_a );
306 cls.def( "store", [] ( const BCRSMatrix &self, const std::string &fileName, std::string format ) {
307 if( (format == "matrixmarket") || (format == "mm") )
308 storeMatrixMarket( self, fileName );
309 else if( format == "matlab" )
310 writeMatrixToMatlab( self, fileName );
311 else
312 throw std::invalid_argument( "Unknown format: " + format );
313 }, "fileName"_a, "format"_a );
314
315 // linear operator
316 typedef Dune::LinearOperator< CorrespondingDomainVector< BCRSMatrix >, CorrespondingRangeVector< BCRSMatrix > > LinearOperator;
317
318 cls.def( "asLinearOperator", [] ( const BCRSMatrix &self ) -> LinearOperator * {
319 return new MatrixAdapter< BCRSMatrix, CorrespondingDomainVector< BCRSMatrix >, CorrespondingRangeVector< BCRSMatrix > >( self );
320 }, pybind11::keep_alive< 0, 1 >() );
321
322 //needed for import and exporting the matrix index set
323 cls.def("exportTo", [] ( BCRSMatrix &self, MatrixIndexSet &mis ) {mis.import(self); } );
324 cls.def("importFrom", [] ( BCRSMatrix &self, MatrixIndexSet &mis ) {mis.exportIdx(self); } );
325 }
326
327
328 template< class BCRSMatrix >
329 pybind11::class_< BCRSMatrix > registerBCRSMatrix ( pybind11::handle scope, const char *clsName = "BCRSMatrix" )
330 {
331 //pybind11::class_< BCRSMatrix > cls( scope, clsName );
332 int rows = BCRSMatrix::block_type::rows;
333 int cols = BCRSMatrix::block_type::cols;
334
335 std::string matrixTypename = "Dune::BCRSMatrix< Dune::FieldMatrix< double, "+ std::to_string(rows) + ", " + std::to_string(cols) + " > >";
336
337 auto cls = Dune::Python::insertClass< BCRSMatrix >( scope, clsName, Dune::Python::GenerateTypeName(matrixTypename), Dune::Python::IncludeFiles{"dune/istl/bcrsmatrix.hh","dune/python/istl/bcrsmatrix.hh"});
338 if(cls.second)
339 {
340 registerBCRSMatrix( scope, cls.first );
341 }
342 return cls.first;
343 }
344
345 } // namespace Python
346
347 } // namespace Dune
348
349 #endif // #ifndef DUNE_PYTHON_ISTL_BCRSMATRIX_HH