/usr/include/dune/istl/bcrsmatrix.hh is in libdune-istl-dev 2.2.1-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 | // -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
// vi: set et ts=4 sw=2 sts=2:
#ifndef DUNE_BCRSMATRIX_HH
#define DUNE_BCRSMATRIX_HH
#include<cmath>
#include<complex>
#include<set>
#include<iostream>
#include<algorithm>
#include<numeric>
#include<vector>
#include "istlexception.hh"
#include "bvector.hh"
#include <dune/common/shared_ptr.hh>
#include <dune/common/stdstreams.hh>
#include <dune/common/iteratorfacades.hh>
#include <dune/common/typetraits.hh>
#include <dune/common/static_assert.hh>
/*! \file
* \brief Implementation of the BCRSMatrix class
*/
namespace Dune {
/**
* @defgroup ISTL_SPMV Sparse Matrix and Vector classes
* @ingroup ISTL
* @brief Matrix and Vector classes that support a block recursive
* structure capable of representing the natural structure from Finite
* Element discretisations.
*
*
* The interface of our matrices is designed according to what they
* represent from a mathematical point of view. The vector classes are
* representations of vector spaces:
*
* - FieldVector represents a vector space \f$V=K^n\f$ where the field \f$K\f$
* is represented by a numeric type (e.g. double, float, complex). \f$n\f$
* is known at compile time.
* - BlockVector represents a vector space \f$V=W\times W \times W \times\cdots\times W\f$
* where W is itself a vector space.
* - VariableBlockVector represents a vector space having a two-level
* block structure of the form
* \f$V=B^{n_1}\times B^{n_2}\times\ldots \times B^{n_m}\f$, i.e. it is constructed
* from \f$m\f$ vector spaces, \f$i=1,\ldots,m\f$.
*
* The matrix classes represent linear maps \f$A: V \mapsto W\f$
* from vector space \f$V\f$ to vector space \f$W\f$ the recursive block
* structure of the matrix rows and columns immediately follows
* from the recursive block structure of the vectors representing
* the domain and range of the mapping, respectively:
* - FieldMatrix represents a linear map \f$M: V_1 \to V_2\f$ where
* \f$V_1=K^n\f$ and \f$V_2=K^m\f$ are vector spaces over the same field represented by a numerix type.
* - BCRSMatrix represents a linear map \f$M: V_1 \to V_2\f$ where
* \f$V_1=W\times W \times W \times\cdots\times W\f$ and \f$V_2=W\times W \times W \times\cdots\times W\f$
* where W is itself a vector space.
* - VariableBCRSMatrix is not yet implemented.
*/
/**
@addtogroup ISTL_SPMV
@{
*/
template<typename M>
struct MatrixDimension;
/**
\brief A sparse block matrix with compressed row storage
Implements a block compressed row storage scheme. The block
type B can be any type implementing the matrix interface.
Different ways to build up a compressed row
storage matrix are supported:
1. Row-wise scheme
2. Random scheme
Error checking: no error checking is provided normally.
Setting the compile time switch DUNE_ISTL_WITH_CHECKING
enables error checking.
Details:
1. Row-wise scheme
Rows are built up in sequential order. Size of the row and
the column indices are defined. A row can be used as soon as it
is initialized. With respect to memory there are two variants of
this scheme: (a) number of non-zeroes known in advance (application
finite difference schemes), (b) number of non-zeroes not known
in advance (application: Sparse LU, ILU(n)).
\code
#include<dune/common/fmatrix.hh>
#include<dune/istl/bcrsmatrix.hh>
...
typedef FieldMatrix<double,2,2> M;
// third parameter is an optional upper bound for the number
// of nonzeros. If given the matrix will use one array for all values
// as opossed to one for each row.
BCRSMatrix<M> B(4,4,12,BCRSMatrix<M>::row_wise);
typedef BCRSMatrix<M>::CreateIterator Iter;
for(Iter row=B.createbegin(); row!=B.createend(); ++row){
// Add nonzeros for left neighbour, diagonal and right neighbour
if(row.index()>0)
row.insert(row.index()-1);
row.insert(row.index());
if(row.index()<B.N()-1)
row.insert(row.index()+1);
}
// Now the sparsity pattern is fully set up and we can add values
B[0][0]=2;
...
\endcode
2. Random scheme
For general finite element implementations the number of rows n
is known, the number of non-zeroes might also be known (e.g.
\#edges + \#nodes for P1) but the size of a row and the indices of a row
can not be defined in sequential order.
\code
#include<dune/common/fmatrix.hh>
#include<dune/istl/bcrsmatrix.hh>
...
typedef FieldMatrix<double,2,2> M;
BCRSMatrix<M> B(4,4,BCRSMatrix<M>::random);
// initially set row size for each row
B.setrowsize(0,1);
B.setrowsize(3,4);
B.setrowsize(2,1);
B.setrowsize(1,1);
// increase row size for row 2
B.incrementrowsize(2)
// finalize row setup phase
B.endrowsizes();
// add column entries to rows
B.addindex(0,0);
B.addindex(3,1);
B.addindex(2,2);
B.addindex(1,1);
B.addindex(2,0);
B.addindex(3,2);
B.addindex(3,0);
B.addindex(3,3);
// finalize column setup phase
B.endindices();
// set entries using the random access operator
B[0][0] = 1;
B[1][1] = 2;
B[2][0] = 3;
B[2][2] = 4;
B[3][1] = 5;
B[3][2] = 6;
B[3][0] = 7;
B[3][3] = 8;
\endcode
*/
template<class B, class A=std::allocator<B> >
class BCRSMatrix
{
friend struct MatrixDimension<BCRSMatrix>;
private:
enum BuildStage{
/** @brief Matrix is not built at all. */
notbuilt=0,
/** @brief The row sizes of the matrix are known.
*
* Only used in random mode.
*/
rowSizesBuilt=1,
/** @brief The matrix structure is built fully.*/
built=2
};
public:
//===== type definitions and constants
//! export the type representing the field
typedef typename B::field_type field_type;
//! export the type representing the components
typedef B block_type;
//! export the allocator type
typedef A allocator_type;
//! implement row_type with compressed vector
typedef CompressedBlockVectorWindow<B,A> row_type;
//! The type for the index access and the size
typedef typename A::size_type size_type;
//! increment block level counter
enum {
//! The number of blocklevels the matrix contains.
blocklevel = B::blocklevel+1
};
//! we support two modes
enum BuildMode {
/**
* @brief Build in a row-wise manner.
*
* Rows are built up in sequential order. Size of the row and
* the column indices are defined. A row can be used as soon as it
* is initialized. With respect to memory there are two variants of
* this scheme: (a) number of non-zeroes known in advance (application
* finite difference schemes), (b) number of non-zeroes not known
* in advance (application: Sparse LU, ILU(n)).
*/
row_wise,
/**
* @brief Build entries randomly.
*
* For general finite element implementations the number of rows n
* is known, the number of non-zeroes might also be known (e.g.
* \#edges + \#nodes for P1) but the size of a row and the indices of a row
* can not be defined in sequential order.
*/
random,
/**
* @brief Build mode not set!
*/
unknown
};
//===== random access interface to rows of the matrix
//! random access to the rows
row_type& operator[] (size_type i)
{
#ifdef DUNE_ISTL_WITH_CHECKING
if (r==0) DUNE_THROW(ISTLError,"row not initialized yet");
if (i>=n) DUNE_THROW(ISTLError,"index out of range");
if (r[i].getptr()==0) DUNE_THROW(ISTLError,"row not initialized yet");
#endif
return r[i];
}
//! same for read only access
const row_type& operator[] (size_type i) const
{
#ifdef DUNE_ISTL_WITH_CHECKING
if (built!=ready) DUNE_THROW(ISTLError,"row not initialized yet");
if (i>=n) DUNE_THROW(ISTLError,"index out of range");
#endif
return r[i];
}
//===== iterator interface to rows of the matrix
//! %Iterator access to matrix rows
template<class T>
class RealRowIterator
: public RandomAccessIteratorFacade<RealRowIterator<T>, T>
{
public:
//! \brief The unqualified value type
typedef typename remove_const<T>::type ValueType;
friend class RandomAccessIteratorFacade<RealRowIterator<const ValueType>, const ValueType>;
friend class RandomAccessIteratorFacade<RealRowIterator<ValueType>, ValueType>;
friend class RealRowIterator<const ValueType>;
friend class RealRowIterator<ValueType>;
//! constructor
RealRowIterator (row_type* _p, size_type _i)
: p(_p), i(_i)
{}
//! empty constructor, use with care!
RealRowIterator ()
: p(0), i(0)
{}
RealRowIterator(const RealRowIterator<ValueType>& it)
: p(it.p), i(it.i)
{}
//! return index
size_type index () const
{
return i;
}
std::ptrdiff_t distanceTo(const RealRowIterator<ValueType>& other) const
{
assert(other.p==p);
return (other.i-i);
}
std::ptrdiff_t distanceTo(const RealRowIterator<const ValueType>& other) const
{
assert(other.p==p);
return (other.i-i);
}
//! equality
bool equals (const RealRowIterator<ValueType>& other) const
{
assert(other.p==p);
return i==other.i;
}
//! equality
bool equals (const RealRowIterator<const ValueType>& other) const
{
assert(other.p==p);
return i==other.i;
}
private:
//! prefix increment
void increment()
{
++i;
}
//! prefix decrement
void decrement()
{
--i;
}
void advance(std::ptrdiff_t diff)
{
i+=diff;
}
T& elementAt(std::ptrdiff_t diff) const
{
return p[i+diff];
}
//! dereferencing
row_type& dereference () const
{
return p[i];
}
row_type* p;
size_type i;
};
//! The iterator over the (mutable matrix rows
typedef RealRowIterator<row_type> iterator;
typedef RealRowIterator<row_type> Iterator;
//! Get iterator to first row
Iterator begin ()
{
return Iterator(r,0);
}
//! Get iterator to one beyond last row
Iterator end ()
{
return Iterator(r,n);
}
//! @returns an iterator that is positioned before
//! the end iterator of the rows, i.e. at the last row.
Iterator beforeEnd ()
{
return Iterator(r,n-1);
}
//! @returns an iterator that is positioned before
//! the first row of the matrix.
Iterator beforeBegin ()
{
return Iterator(r,-1);
}
//! rename the iterators for easier access
typedef Iterator RowIterator;
/** \brief Iterator for the entries of each row */
typedef typename row_type::Iterator ColIterator;
//! The const iterator over the matrix rows
typedef RealRowIterator<const row_type> const_iterator;
typedef RealRowIterator<const row_type> ConstIterator;
//! Get const iterator to first row
ConstIterator begin () const
{
return ConstIterator(r,0);
}
//! Get const iterator to one beyond last row
ConstIterator end () const
{
return ConstIterator(r,n);
}
//! @returns an iterator that is positioned before
//! the end iterator of the rows. i.e. at the last row.
ConstIterator beforeEnd() const
{
return ConstIterator(r,n-1);
}
//! @returns an iterator that is positioned before
//! the first row of the matrix.
ConstIterator beforeBegin () const
{
return ConstIterator(r,-1);
}
//! rename the const row iterator for easier access
typedef ConstIterator ConstRowIterator;
//! Const iterator to the entries of a row
typedef typename row_type::ConstIterator ConstColIterator;
//===== constructors & resizers
//! an empty matrix
BCRSMatrix ()
: build_mode(unknown), ready(notbuilt), n(0), m(0), nnz(0),
r(0), a(0)
{}
//! matrix with known number of nonzeroes
BCRSMatrix (size_type _n, size_type _m, size_type _nnz, BuildMode bm)
: build_mode(bm), ready(notbuilt)
{
allocate(_n, _m, _nnz);
}
//! matrix with unknown number of nonzeroes
BCRSMatrix (size_type _n, size_type _m, BuildMode bm)
: build_mode(bm), ready(notbuilt)
{
allocate(_n, _m);
}
/**
* @brief copy constructor
*
* Does a deep copy as expected.
*/
BCRSMatrix (const BCRSMatrix& Mat)
: n(Mat.n), nnz(0)
{
// deep copy in global array
size_type _nnz = Mat.nnz;
// in case of row-wise allocation
if (_nnz<=0)
{
_nnz = 0;
for (size_type i=0; i<n; i++)
_nnz += Mat.r[i].getsize();
}
j = Mat.j; // enable column index sharing, release array in case of row-wise allocation
allocate(Mat.n, Mat.m, _nnz);
// build window structure
copyWindowStructure(Mat);
}
//! destructor
~BCRSMatrix ()
{
deallocate();
}
/**
* @brief Sets the build mode of the matrix
* @param bm The build mode to use.
*/
void setBuildMode(BuildMode bm)
{
if(ready==notbuilt)
build_mode = bm;
else
DUNE_THROW(InvalidStateException, "Matrix structure is already built (ready="<<ready<<").");
}
/**
* @brief Set the size of the matrix.
*
* Sets the number of rows and columns of the matrix and allocates
* the memory needed for the storage of the matrix entries.
*
* @warning After calling this methods on an already allocated (and probably
* setup matrix) results in all the structure and data being deleted. I.~e.
* one has to setup the matrix again.
*
* @param rows The number of rows the matrix should contain.
* @param columns the number of columns the matrix should contain.
* @param nnz The number of nonzero entries the matrix should hold (if omitted
* defaults to 0).
*/
void setSize(size_type rows, size_type columns, size_type nnz=0)
{
// deallocate already setup memory
deallocate();
// allocate matrix memory
allocate(rows, columns, nnz);
}
/**
* @brief assignment
*
* Frees and reallocates space.
* Both sparsity pattern and values are set from Mat.
*/
BCRSMatrix& operator= (const BCRSMatrix& Mat)
{
// return immediately when self-assignment
if (&Mat==this) return *this;
// make it simple: ALWAYS throw away memory for a and j
deallocate(false);
// reallocate the rows if required
if (n>0 && n!=Mat.n) {
// free rows
for(row_type *riter=r+(n-1), *rend=r-1; riter!=rend; --riter)
rowAllocator_.destroy(riter);
rowAllocator_.deallocate(r,n);
}
nnz=Mat.nnz;
if (nnz<=0)
{
for (size_type i=0; i<Mat.n; i++)
nnz += Mat.r[i].getsize();
}
// allocate a, share j
j = Mat.j;
allocate(Mat.n, Mat.m, nnz, n!=Mat.n);
// build window structure
copyWindowStructure(Mat);
return *this;
}
//! Assignment from a scalar
BCRSMatrix& operator= (const field_type& k)
{
for (size_type i=0; i<n; i++) r[i] = k;
return *this;
}
//===== row-wise creation interface
//! %Iterator class for sequential creation of blocks
class CreateIterator
{
public:
//! constructor
CreateIterator (BCRSMatrix& _Mat, size_type _i)
: Mat(_Mat), i(_i), nnz(0), current_row(Mat.a, Mat.j.get(), 0)
{
if (i==0 && Mat.ready)
DUNE_THROW(ISTLError,"creation only allowed for uninitialized matrix");
if(Mat.build_mode!=row_wise)
{
if(Mat.build_mode==unknown)
Mat.build_mode=row_wise;
else
DUNE_THROW(ISTLError,"creation only allowed if row wise allocation was requested in the constructor");
}
}
//! prefix increment
CreateIterator& operator++()
{
// this should only be called if matrix is in creation
if (Mat.ready)
DUNE_THROW(ISTLError,"matrix already built up");
// row i is defined through the pattern
// get memory for the row and initialize the j array
// this depends on the allocation mode
// compute size of the row
size_type s = pattern.size();
if(s>0){
// update number of nonzeroes including this row
nnz += s;
// alloc memory / set window
if (Mat.nnz>0)
{
// memory is allocated in one long array
// check if that memory is sufficient
if (nnz>Mat.nnz)
DUNE_THROW(ISTLError,"allocated nnz too small");
// set row i
Mat.r[i].set(s,current_row.getptr(),current_row.getindexptr());
current_row.setptr(current_row.getptr()+s);
current_row.setindexptr(current_row.getindexptr()+s);
}else{
// memory is allocated individually per row
// allocate and set row i
B* a = Mat.allocator_.allocate(s);
new (a) B[s];
size_type* j = Mat.sizeAllocator_.allocate(s);
new (j) size_type[s];
Mat.r[i].set(s,a,j);
}
}else
// setup empty row
Mat.r[i].set(0,0,0);
// initialize the j array for row i from pattern
size_type k=0;
size_type *j = Mat.r[i].getindexptr();
for (typename PatternType::const_iterator it=pattern.begin(); it!=pattern.end(); ++it)
j[k++] = *it;
// now go to next row
i++;
pattern.clear();
// check if this was last row
if (i==Mat.n)
{
Mat.ready = built;
if(Mat.nnz>0)
// Set nnz to the exact number of nonzero blocks inserted
// as some methods rely on it
Mat.nnz=nnz;
}
// done
return *this;
}
//! inequality
bool operator!= (const CreateIterator& it) const
{
return (i!=it.i) || (&Mat!=&it.Mat);
}
//! equality
bool operator== (const CreateIterator& it) const
{
return (i==it.i) && (&Mat==&it.Mat);
}
//! dereferencing
size_type index () const
{
return i;
}
//! put column index in row
void insert (size_type j)
{
pattern.insert(j);
}
//! return true if column index is in row
bool contains (size_type j)
{
if (pattern.find(j)!=pattern.end())
return true;
else
return false;
}
/**
* @brief Get the current row size.
* @return The number of indices already
* inserted for the current row.
*/
size_type size() const
{
return pattern.size();
}
private:
BCRSMatrix& Mat; // the matrix we are defining
size_type i; // current row to be defined
size_type nnz; // count total number of nonzeros
typedef std::set<size_type,std::less<size_type> > PatternType;
PatternType pattern; // used to compile entries in a row
row_type current_row; // row pointing to the current row to setup
};
//! allow CreateIterator to access internal data
friend class CreateIterator;
//! get initial create iterator
CreateIterator createbegin ()
{
return CreateIterator(*this,0);
}
//! get create iterator pointing to one after the last block
CreateIterator createend ()
{
return CreateIterator(*this,n);
}
//===== random creation interface
//! set number of indices in row i to s
void setrowsize (size_type i, size_type s)
{
if (build_mode!=random)
DUNE_THROW(ISTLError,"requires random build mode");
if (ready)
DUNE_THROW(ISTLError,"matrix row sizes already built up");
r[i].setsize(s);
}
//! get current number of indices in row i
size_type getrowsize (size_type i) const
{
#ifdef DUNE_ISTL_WITH_CHECKING
if (r==0) DUNE_THROW(ISTLError,"row not initialized yet");
if (i>=n) DUNE_THROW(ISTLError,"index out of range");
#endif
return r[i].getsize();
}
//! increment size of row i by s (1 by default)
void incrementrowsize (size_type i, size_type s = 1)
{
if (build_mode!=random)
DUNE_THROW(ISTLError,"requires random build mode");
if (ready)
DUNE_THROW(ISTLError,"matrix row sizes already built up");
r[i].setsize(r[i].getsize()+s);
}
//! indicate that size of all rows is defined
void endrowsizes ()
{
if (build_mode!=random)
DUNE_THROW(ISTLError,"requires random build mode");
if (ready)
DUNE_THROW(ISTLError,"matrix row sizes already built up");
// compute total size, check positivity
size_type total=0;
for (size_type i=0; i<n; i++)
{
if (r[i].getsize()<0)
DUNE_THROW(ISTLError,"rowsize must be nonnegative");
total += r[i].getsize();
}
if(nnz==0)
// allocate/check memory
allocate(n,m,total,false);
else if(nnz<total)
DUNE_THROW(ISTLError,"Specified number of nonzeros ("<<nnz<<") not "
<<"sufficient for calculated nonzeros ("<<total<<"! ");
// set the window pointers correctly
setWindowPointers(begin());
// initialize j array with m (an invalid column index)
// this indicates an unused entry
for (size_type k=0; k<nnz; k++)
j.get()[k] = m;
ready = rowSizesBuilt;
}
//! \brief add index (row,col) to the matrix
/*!
This method can only be used when building the BCRSMatrix
in random mode.
addindex adds a new column entry to the row. If this column
entry already exists, nothing is done.
Don't call addindex after the setup phase is finished
(after endindices is called).
*/
void addindex (size_type row, size_type col)
{
if (build_mode!=random)
DUNE_THROW(ISTLError,"requires random build mode");
if (ready==built)
DUNE_THROW(ISTLError,"matrix already built up");
if (ready==notbuilt)
DUNE_THROW(ISTLError,"matrix row sizes not built up yet");
if (col >= m)
DUNE_THROW(ISTLError,"column index exceeds matrix size");
// get row range
size_type* const first = r[row].getindexptr();
size_type* const last = first + r[row].getsize();
// find correct insertion position for new column index
size_type* pos = std::lower_bound(first,last,col);
// check if index is already in row
if (pos!=last && *pos == col) return;
// find end of already inserted column indices
size_type* end = std::lower_bound(pos,last,m);
if (end==last)
DUNE_THROW(ISTLError,"row is too small");
// insert new column index at correct position
std::copy_backward(pos,end,end+1);
*pos = col;
}
//! indicate that all indices are defined, check consistency
void endindices ()
{
if (build_mode!=random)
DUNE_THROW(ISTLError,"requires random build mode");
if (ready==built)
DUNE_THROW(ISTLError,"matrix already built up");
if (ready==notbuilt)
DUNE_THROW(ISTLError,"row sizes are not built up yet");
// check if there are undefined indices
RowIterator endi=end();
for (RowIterator i=begin(); i!=endi; ++i)
{
ColIterator endj = (*i).end();
for (ColIterator j=(*i).begin(); j!=endj; ++j){
if (j.index()<0)
{
std::cout << "j[" << j.offset() << "]=" << j.index() << std::endl;
DUNE_THROW(ISTLError,"undefined index detected");
}
if (j.index()>=m){
dwarn << "WARNING: size of row "<< i.index()<<" is "<<j.offset()<<". But was specified as being "<< (*i).end().offset()
<<". This means you are wasting valuable space and creating additional cache misses!"<<std::endl;
r[i.index()].setsize(j.offset());
break;
}
}
}
// if not, set matrix to built
ready = built;
}
//===== vector space arithmetic
//! vector space multiplication with scalar
BCRSMatrix& operator*= (const field_type& k)
{
if (nnz>0)
{
// process 1D array
for (size_type i=0; i<nnz; i++)
a[i] *= k;
}
else
{
RowIterator endi=end();
for (RowIterator i=begin(); i!=endi; ++i)
{
ColIterator endj = (*i).end();
for (ColIterator j=(*i).begin(); j!=endj; ++j)
(*j) *= k;
}
}
return *this;
}
//! vector space division by scalar
BCRSMatrix& operator/= (const field_type& k)
{
if (nnz>0)
{
// process 1D array
for (size_type i=0; i<nnz; i++)
a[i] /= k;
}
else
{
RowIterator endi=end();
for (RowIterator i=begin(); i!=endi; ++i)
{
ColIterator endj = (*i).end();
for (ColIterator j=(*i).begin(); j!=endj; ++j)
(*j) /= k;
}
}
return *this;
}
/*! \brief Add the entries of another matrix to this one.
*
* \param b The matrix to add to this one. Its sparsity pattern
* has to be subset of the sparsity pattern of this matrix.
*/
BCRSMatrix& operator+= (const BCRSMatrix& b)
{
#ifdef DUNE_ISTL_WITH_CHECKING
if(N()!=b.N() || M() != b.M())
DUNE_THROW(RangeError, "Matrix sizes do not match!");
#endif
RowIterator endi=end();
ConstRowIterator j=b.begin();
for (RowIterator i=begin(); i!=endi; ++i, ++j){
i->operator+=(*j);
}
return *this;
}
/*! \brief Substract the entries of another matrix to this one.
*
* \param b The matrix to add to this one. Its sparsity pattern
* has to be subset of the sparsity pattern of this matrix.
*/
BCRSMatrix& operator-= (const BCRSMatrix& b)
{
#ifdef DUNE_ISTL_WITH_CHECKING
if(N()!=b.N() || M() != b.M())
DUNE_THROW(RangeError, "Matrix sizes do not match!");
#endif
RowIterator endi=end();
ConstRowIterator j=b.begin();
for (RowIterator i=begin(); i!=endi; ++i, ++j){
i->operator-=(*j);
}
return *this;
}
/*! \brief Add the scaled entries of another matrix to this one.
*
* Matrix axpy operation: *this += alpha * b
*
* \param alpha Scaling factor.
* \param b The matrix to add to this one. Its sparsity pattern has to
* be subset of the sparsity pattern of this matrix.
*/
BCRSMatrix& axpy(field_type alpha, const BCRSMatrix& b)
{
#ifdef DUNE_ISTL_WITH_CHECKING
if(N()!=b.N() || M() != b.M())
DUNE_THROW(RangeError, "Matrix sizes do not match!");
#endif
RowIterator endi=end();
ConstRowIterator j=b.begin();
for(RowIterator i=begin(); i!=endi; ++i, ++j)
i->axpy(alpha, *j);
return *this;
}
//===== linear maps
//! y = A x
template<class X, class Y>
void mv (const X& x, Y& y) const
{
#ifdef DUNE_ISTL_WITH_CHECKING
if (x.N()!=M()) DUNE_THROW(ISTLError,
"Size mismatch: M: " << N() << "x" << M() << " x: " << x.N());
if (y.N()!=N()) DUNE_THROW(ISTLError,
"Size mismatch: M: " << N() << "x" << M() << " y: " << y.N());
#endif
ConstRowIterator endi=end();
for (ConstRowIterator i=begin(); i!=endi; ++i)
{
y[i.index()]=0;
ConstColIterator endj = (*i).end();
for (ConstColIterator j=(*i).begin(); j!=endj; ++j)
(*j).umv(x[j.index()],y[i.index()]);
}
}
//! y += A x
template<class X, class Y>
void umv (const X& x, Y& y) const
{
#ifdef DUNE_ISTL_WITH_CHECKING
if (x.N()!=M()) DUNE_THROW(ISTLError,"index out of range");
if (y.N()!=N()) DUNE_THROW(ISTLError,"index out of range");
#endif
ConstRowIterator endi=end();
for (ConstRowIterator i=begin(); i!=endi; ++i)
{
ConstColIterator endj = (*i).end();
for (ConstColIterator j=(*i).begin(); j!=endj; ++j)
(*j).umv(x[j.index()],y[i.index()]);
}
}
//! y -= A x
template<class X, class Y>
void mmv (const X& x, Y& y) const
{
#ifdef DUNE_ISTL_WITH_CHECKING
if (x.N()!=M()) DUNE_THROW(ISTLError,"index out of range");
if (y.N()!=N()) DUNE_THROW(ISTLError,"index out of range");
#endif
ConstRowIterator endi=end();
for (ConstRowIterator i=begin(); i!=endi; ++i)
{
ConstColIterator endj = (*i).end();
for (ConstColIterator j=(*i).begin(); j!=endj; ++j)
(*j).mmv(x[j.index()],y[i.index()]);
}
}
//! y += alpha A x
template<class X, class Y>
void usmv (const field_type& alpha, const X& x, Y& y) const
{
#ifdef DUNE_ISTL_WITH_CHECKING
if (x.N()!=M()) DUNE_THROW(ISTLError,"index out of range");
if (y.N()!=N()) DUNE_THROW(ISTLError,"index out of range");
#endif
ConstRowIterator endi=end();
for (ConstRowIterator i=begin(); i!=endi; ++i)
{
ConstColIterator endj = (*i).end();
for (ConstColIterator j=(*i).begin(); j!=endj; ++j)
(*j).usmv(alpha,x[j.index()],y[i.index()]);
}
}
//! y = A^T x
template<class X, class Y>
void mtv (const X& x, Y& y) const
{
#ifdef DUNE_ISTL_WITH_CHECKING
if (x.N()!=N()) DUNE_THROW(ISTLError,"index out of range");
if (y.N()!=M()) DUNE_THROW(ISTLError,"index out of range");
#endif
for(size_type i=0; i<y.N(); ++i)
y[i]=0;
umtv(x,y);
}
//! y += A^T x
template<class X, class Y>
void umtv (const X& x, Y& y) const
{
#ifdef DUNE_ISTL_WITH_CHECKING
if (x.N()!=N()) DUNE_THROW(ISTLError,"index out of range");
if (y.N()!=M()) DUNE_THROW(ISTLError,"index out of range");
#endif
ConstRowIterator endi=end();
for (ConstRowIterator i=begin(); i!=endi; ++i)
{
ConstColIterator endj = (*i).end();
for (ConstColIterator j=(*i).begin(); j!=endj; ++j)
(*j).umtv(x[i.index()],y[j.index()]);
}
}
//! y -= A^T x
template<class X, class Y>
void mmtv (const X& x, Y& y) const
{
#ifdef DUNE_ISTL_WITH_CHECKING
if (x.N()!=N()) DUNE_THROW(ISTLError,"index out of range");
if (y.N()!=M()) DUNE_THROW(ISTLError,"index out of range");
#endif
ConstRowIterator endi=end();
for (ConstRowIterator i=begin(); i!=endi; ++i)
{
ConstColIterator endj = (*i).end();
for (ConstColIterator j=(*i).begin(); j!=endj; ++j)
(*j).mmtv(x[i.index()],y[j.index()]);
}
}
//! y += alpha A^T x
template<class X, class Y>
void usmtv (const field_type& alpha, const X& x, Y& y) const
{
#ifdef DUNE_ISTL_WITH_CHECKING
if (x.N()!=N()) DUNE_THROW(ISTLError,"index out of range");
if (y.N()!=M()) DUNE_THROW(ISTLError,"index out of range");
#endif
ConstRowIterator endi=end();
for (ConstRowIterator i=begin(); i!=endi; ++i)
{
ConstColIterator endj = (*i).end();
for (ConstColIterator j=(*i).begin(); j!=endj; ++j)
(*j).usmtv(alpha,x[i.index()],y[j.index()]);
}
}
//! y += A^H x
template<class X, class Y>
void umhv (const X& x, Y& y) const
{
#ifdef DUNE_ISTL_WITH_CHECKING
if (x.N()!=N()) DUNE_THROW(ISTLError,"index out of range");
if (y.N()!=M()) DUNE_THROW(ISTLError,"index out of range");
#endif
ConstRowIterator endi=end();
for (ConstRowIterator i=begin(); i!=endi; ++i)
{
ConstColIterator endj = (*i).end();
for (ConstColIterator j=(*i).begin(); j!=endj; ++j)
(*j).umhv(x[i.index()],y[j.index()]);
}
}
//! y -= A^H x
template<class X, class Y>
void mmhv (const X& x, Y& y) const
{
#ifdef DUNE_ISTL_WITH_CHECKING
if (x.N()!=N()) DUNE_THROW(ISTLError,"index out of range");
if (y.N()!=M()) DUNE_THROW(ISTLError,"index out of range");
#endif
ConstRowIterator endi=end();
for (ConstRowIterator i=begin(); i!=endi; ++i)
{
ConstColIterator endj = (*i).end();
for (ConstColIterator j=(*i).begin(); j!=endj; ++j)
(*j).mmhv(x[i.index()],y[j.index()]);
}
}
//! y += alpha A^H x
template<class X, class Y>
void usmhv (const field_type& alpha, const X& x, Y& y) const
{
#ifdef DUNE_ISTL_WITH_CHECKING
if (x.N()!=N()) DUNE_THROW(ISTLError,"index out of range");
if (y.N()!=M()) DUNE_THROW(ISTLError,"index out of range");
#endif
ConstRowIterator endi=end();
for (ConstRowIterator i=begin(); i!=endi; ++i)
{
ConstColIterator endj = (*i).end();
for (ConstColIterator j=(*i).begin(); j!=endj; ++j)
(*j).usmhv(alpha,x[i.index()],y[j.index()]);
}
}
//===== norms
//! square of frobenius norm, need for block recursion
double frobenius_norm2 () const
{
double sum=0;
ConstRowIterator endi=end();
for (ConstRowIterator i=begin(); i!=endi; ++i)
{
ConstColIterator endj = (*i).end();
for (ConstColIterator j=(*i).begin(); j!=endj; ++j)
sum += (*j).frobenius_norm2();
}
return sum;
}
//! frobenius norm: sqrt(sum over squared values of entries)
double frobenius_norm () const
{
return sqrt(frobenius_norm2());
}
//! infinity norm (row sum norm, how to generalize for blocks?)
double infinity_norm () const
{
double max=0;
ConstRowIterator endi=end();
for (ConstRowIterator i=begin(); i!=endi; ++i)
{
double sum=0;
ConstColIterator endj = (*i).end();
for (ConstColIterator j=(*i).begin(); j!=endj; ++j)
sum += (*j).infinity_norm();
max = std::max(max,sum);
}
return max;
}
//! simplified infinity norm (uses Manhattan norm for complex values)
double infinity_norm_real () const
{
double max=0;
ConstRowIterator endi=end();
for (ConstRowIterator i=begin(); i!=endi; ++i)
{
double sum=0;
ConstColIterator endj = (*i).end();
for (ConstColIterator j=(*i).begin(); j!=endj; ++j)
sum += (*j).infinity_norm_real();
max = std::max(max,sum);
}
return max;
}
//===== sizes
//! number of rows (counted in blocks)
size_type N () const
{
return n;
}
//! number of columns (counted in blocks)
size_type M () const
{
return m;
}
//! number of blocks that are stored (the number of blocks that possibly are nonzero)
size_type nonzeroes () const
{
return nnz;
}
//===== query
//! return true if (i,j) is in pattern
bool exists (size_type i, size_type j) const
{
#ifdef DUNE_ISTL_WITH_CHECKING
if (i<0 || i>=n) DUNE_THROW(ISTLError,"row index out of range");
if (j<0 || j>=m) DUNE_THROW(ISTLError,"column index out of range");
#endif
if (r[i].size() && r[i].find(j)!=r[i].end())
return true;
else
return false;
}
private:
// state information
BuildMode build_mode; // row wise or whole matrix
BuildStage ready; // indicate the stage the matrix building is in
// The allocator used for memory management
typename A::template rebind<B>::other allocator_;
typename A::template rebind<row_type>::other rowAllocator_;
typename A::template rebind<size_type>::other sizeAllocator_;
// size of the matrix
size_type n; // number of rows
size_type m; // number of columns
size_type nnz; // number of nonzeros allocated in the a and j array below
// zero means that memory is allocated separately for each row.
// the rows are dynamically allocated
row_type* r; // [n] the individual rows having pointers into a,j arrays
// dynamically allocated memory
B* a; // [nnz] non-zero entries of the matrix in row-wise ordering
// If a single array of column indices is used, it can be shared
// between different matrices with the same sparsity pattern
Dune::shared_ptr<size_type> j; // [nnz] column indices of entries
void setWindowPointers(ConstRowIterator row)
{
row_type current_row(a,j.get(),0); // Pointers to current row data
for (size_type i=0; i<n; i++, ++row){
// set row i
size_type s = row->getsize();
if (s>0){
// setup pointers and size
r[i].set(s,current_row.getptr(), current_row.getindexptr());
// update pointer for next row
current_row.setptr(current_row.getptr()+s);
current_row.setindexptr(current_row.getindexptr()+s);
} else{
// empty row
r[i].set(0,0,0);
}
}
}
//! \brief Copy the window structure from another matrix
void copyWindowStructure(const BCRSMatrix& Mat)
{
setWindowPointers(Mat.begin());
// copy data
for (size_type i=0; i<n; i++) r[i] = Mat.r[i];
// finish off
build_mode = row_wise; // dummy
ready = built;
}
/**
* @brief deallocate memory of the matrix.
* @param deallocateRows Whether we have to deallocate the row pointers, too.
* If false they will not be touched. (Defaults to true).
*/
void deallocate(bool deallocateRows=true)
{
if (nnz>0)
{
// a,j have been allocated as one long vector
j.reset();
for(B *aiter=a+(nnz-1), *aend=a-1; aiter!=aend; --aiter)
allocator_.destroy(aiter);
allocator_.deallocate(a,n);
}
else
{
// check if memory for rows have been allocated individually
for (size_type i=0; i<n; i++)
if (r[i].getsize()>0)
{
for (B *col=r[i].getptr()+(r[i].getsize()-1),
*colend = r[i].getptr()-1; col!=colend; --col) {
allocator_.destroy(col);
}
sizeAllocator_.deallocate(r[i].getindexptr(),1);
allocator_.deallocate(r[i].getptr(),1);
}
}
// deallocate the rows
if (n>0 && deallocateRows) {
for(row_type *riter=r+(n-1), *rend=r-1; riter!=rend; --riter)
rowAllocator_.destroy(riter);
rowAllocator_.deallocate(r,n);
}
// Mark matrix as not built at all.
ready=notbuilt;
}
/** \brief Class used by shared_ptr to deallocate memory using the proper allocator */
class Deallocator
{
typename A::template rebind<size_type>::other& sizeAllocator_;
public:
Deallocator(typename A::template rebind<size_type>::other& sizeAllocator)
: sizeAllocator_(sizeAllocator)
{}
void operator()(size_type* p) { sizeAllocator_.deallocate(p,1); }
};
/**
* @brief Allocate memory for the matrix structure
*
* Sets the number of rows and columns of the matrix and allocates
* the memory needed for the storage of the matrix entries.
*
* @warning After calling this methods on an already allocated (and probably
* setup matrix) results in all the structure and data being lost. Please
* call deallocate() before calling allocate in this case.
*
* @param row The number of rows the matrix should contain.
* @param columns the number of columns the matrix should contain.
* @param nnz The number of nonzero entries the matrix should hold (if omitted
* defaults to 0).
* @param allocateRow Whether we have to allocate the row pointers, too. (Defaults to
* true)
*/
void allocate(size_type rows, size_type columns, size_type nnz_=0, bool allocateRows=true)
{
// Store size
n = rows;
m = columns;
nnz = nnz_;
// allocate rows
if(allocateRows){
if (n>0){
r = rowAllocator_.allocate(rows);
new (r) row_type[rows];
}else{
r = 0;
}
}
// allocate a and j array
if (nnz>0){
a = allocator_.allocate(nnz);
// allocate column indices only if not yet present (enable sharing)
if (!j.get())
j.reset(sizeAllocator_.allocate(nnz),Deallocator(sizeAllocator_));
}else{
a = 0;
j.reset();
for(row_type* ri=r; ri!=r+rows;++ri)
rowAllocator_.construct(ri, row_type());
}
// Mark the matrix as not built.
ready = notbuilt;
}
};
/** @} end documentation */
} // end namespace
#endif
|