summaryrefslogtreecommitdiffstatshomepage
path: root/src/lib/netlist/plib/mat_cr.h
blob: b21c53671a2fec92d51218cf20568771887067aa (plain) (blame)
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
// license:GPL-2.0+
// copyright-holders:Couriersud
/*
 * mat_cr.h
 *
 * Compressed row format matrices
 *
 */

#ifndef MAT_CR_H_
#define MAT_CR_H_

#include "palloc.h"
#include "parray.h"
#include "pconfig.h"
#include "pomp.h"
#include "pstate.h"
#include "ptypes.h"
#include "putil.h"

#include <algorithm>
#include <array>
#include <cmath>
#include <type_traits>
#include <vector>

namespace plib
{

	// FIXME: causes a crash with GMRES handler
	// template<typename T, int N, typename C = std::size_t>

	template<typename T, int N, typename C = uint16_t>
	struct pmatrix_cr_t
	{
		using index_type = C;
		using value_type = T;

		static constexpr const int NSQ = (N < 0 ? -N * N : N * N);
		static constexpr const int Np1 = (N == 0) ? 0 : (N < 0 ? N - 1 : N + 1);

		COPYASSIGNMOVE(pmatrix_cr_t, default)

		enum constants_e
		{
			FILL_INFINITY = 9999999
		};

		parray<index_type, N> diag;      // diagonal index pointer n
		parray<index_type, Np1> row_idx;      // row index pointer n + 1
		parray<index_type, NSQ> col_idx;       // column index array nz_num, initially (n * n)
		parray<value_type, NSQ> A;    // Matrix elements nz_num, initially (n * n)

		index_type nz_num;

		explicit pmatrix_cr_t(const index_type n)
		: diag(n)
		, row_idx(n+1)
		, col_idx(n*n)
		, A(n*n)
		, nz_num(0)
		//, nzbd(n * (n+1) / 2)
		, nzbd(n)
		, m_size(n)
		{
			for (index_type i=0; i<n+1; i++)
			{
				row_idx[i] = 0;
			}
		}

		~pmatrix_cr_t() = default;

		constexpr index_type size() const { return static_cast<index_type>((N>0) ? N : m_size); }

		void clear()
		{
			nz_num = 0;
			for (index_type i=0; i < size() + 1; i++)
				row_idx[i] = 0;
		}

		void set_scalar(const T scalar)
		{
			for (index_type i=0, e=nz_num; i<e; i++)
				A[i] = scalar;
		}

		void set(C r, C c, T val)
		{
			C ri = row_idx[r];
			while (ri < row_idx[r+1] && col_idx[ri] < c)
			  ri++;
			// we have the position now;
			if (ri < row_idx[r+1] && col_idx[ri] == c)
				A[ri] = val;
			else
			{
				for (C i = nz_num; i>ri; i--)
				{
					A[i] = A[i-1];
					col_idx[i] = col_idx[i-1];
				}
				A[ri] = val;
				col_idx[ri] = c;
				for (C i = r + 1; i < size() + 1; i++)
					row_idx[i]++;
				nz_num++;
				if (c==r)
					diag[r] = ri;
			}
		}

		template <typename M>
		void build_from_fill_mat(const M &f, std::size_t max_fill = FILL_INFINITY - 1,
			std::size_t band_width = FILL_INFINITY)
		{
			C nz = 0;
			if (nz_num != 0)
				throw pexception("build_from_mat only allowed on empty CR matrix");
			for (std::size_t k=0; k < size(); k++)
			{
				row_idx[k] = nz;

				for (std::size_t j=0; j < size(); j++)
					if (f[k][j] <= max_fill && std::abs(static_cast<int>(k)-static_cast<int>(j)) <= static_cast<int>(band_width))
					{
						col_idx[nz] = static_cast<C>(j);
						if (j == k)
							diag[k] = nz;
						nz++;
					}
			}

			row_idx[size()] = nz;
			nz_num = nz;

			/* build nzbd */

			for (std::size_t k=0; k < size(); k++)
			{
				for (std::size_t j=k + 1; j < size(); j++)
					if (f[j][k] < FILL_INFINITY)
						nzbd[k].push_back(static_cast<C>(j));
				nzbd[k].push_back(0); // end of sequence
			}

		}

		template <typename VTV, typename VTR>
		void mult_vec(VTR & res, const VTV & x)
		{
			/*
			 * res = A * x
			 */
#if 0
			//plib::omp::set_num_threads(4);
			plib::omp::for_static(0, constants<index_type>::zero(), m_size, [this, &res, &x](index_type row)
			{
				T tmp(0.0);
				const index_type e(row_idx[row+1]);
				for (index_type k = row_idx[row]; k < e; k++)
					tmp += A[k] * x[col_idx[k]];
				res[row] = tmp;
			});
#else
			// this is a bit faster than the version above
			std::size_t row = 0;
			std::size_t k = 0;
			const std::size_t oe = nz_num;
			while (k < oe)
			{
				T tmp = 0.0;
				const std::size_t e = row_idx[row+1];
				for (; k < e; k++)
					tmp += A[k] * x[col_idx[k]];
				res[row++] = tmp;
			}
#endif
		}

		/* throws error if P(source)>P(destination) */
		template <typename LUMAT>
		void slim_copy_from(LUMAT & src)
		{
			for (std::size_t r=0; r<src.size(); r++)
			{
				C dp = row_idx[r];
				for (C sp = src.row_idx[r]; sp < src.row_idx[r+1]; sp++)
				{
					/* advance dp to source column and fill 0s if necessary */
					while (col_idx[dp] < src.col_idx[sp])
						A[dp++] = 0;
					if (row_idx[r+1] <= dp || col_idx[dp] != src.col_idx[sp])
						throw plib::pexception("slim_copy_from error");
					A[dp++] = src.A[sp];
				}
				/* fill remaining elements in row */
				while (dp < row_idx[r+1])
					A[dp++] = 0;
			}
		}

		/* only copies common elements */
		template <typename LUMAT>
		void reduction_copy_from(LUMAT & src)
		{
			C sp(0);
			for (index_type r=0; r<src.size(); r++)
			{
				C dp(row_idx[r]);
				while(sp < src.row_idx[r+1])
				{
					/* advance dp to source column and fill 0s if necessary */
					if (col_idx[dp] < src.col_idx[sp])
						A[dp++] = 0;
					else if (col_idx[dp] == src.col_idx[sp])
						A[dp++] = src.A[sp++];
					else
						sp++;
				}
				/* fill remaining elements in row */
				while (dp < row_idx[r+1])
					A[dp++] = 0;
			}
		}

		/* no checks at all - may crash */
		template <typename LUMAT>
		void raw_copy_from(LUMAT & src)
		{
			for (index_type k = 0; k < nz_num; k++)
				A[k] = src.A[k];
		}

	protected:
		parray<std::vector<index_type>, N > nzbd;    // Support for gaussian elimination
	private:
		//parray<C, N < 0 ? -N * (N-1) / 2 : N * (N+1) / 2 > nzbd;    // Support for gaussian elimination
		index_type m_size;
	};

	template<typename B>
	struct pGEmatrix_cr_t : public B
	{
		using base = B;
		using index_type = typename base::index_type;

		COPYASSIGNMOVE(pGEmatrix_cr_t, default)

		explicit pGEmatrix_cr_t(const index_type n)
		: B(n)
		{
		}

		~pGEmatrix_cr_t() = default;

		template <typename M>
		std::pair<std::size_t, std::size_t> gaussian_extend_fill_mat(M &fill)
		{
			std::size_t ops = 0;
			std::size_t fill_max = 0;

			for (std::size_t k = 0; k < fill.size(); k++)
			{
				ops++; // 1/A(k,k)
				for (std::size_t row = k + 1; row < fill.size(); row++)
				{
					if (fill[row][k] < base::FILL_INFINITY)
					{
						ops++;
						for (std::size_t col = k + 1; col < fill[row].size(); col++)
							//if (fill[k][col] < FILL_INFINITY)
							{
								auto f = std::min(fill[row][col], 1 + fill[row][k] + fill[k][col]);
								if (f < base::FILL_INFINITY)
								{
									if (f > fill_max)
										fill_max = f;
									ops += 2;
								}
								fill[row][col] = f;
							}
					}
				}
			}
			build_parallel_gaussian_execution_scheme(fill);
			return { fill_max, ops };
		}

		template <typename V>
		void gaussian_elimination(V & RHS)
		{
			const std::size_t iN = base::size();

			for (std::size_t i = 0; i < iN - 1; i++)
			{
				std::size_t nzbdp = 0;
				std::size_t pi = base::diag[i];
				const typename base::value_type f = 1.0 / base::A[pi++];
				const std::size_t piie = base::row_idx[i+1];
				const auto &nz = base::nzbd[i];

				while (auto j = nz[nzbdp++]) // NOLINT(bugprone-infinite-loop)
				{
					// proceed to column i

					std::size_t pj = base::row_idx[j];
					std::size_t pje = base::row_idx[j+1];

					while (base::col_idx[pj] < i)
						pj++;

					const typename base::value_type f1 = - base::A[pj++] * f;

					// subtract row i from j
					// fill-in available assumed, i.e. matrix was prepared

					for (std::size_t pii = pi; pii<piie && pj < pje; pii++)
					{
						while (base::col_idx[pj] < base::col_idx[pii])
							pj++;
						if (base::col_idx[pj] == base::col_idx[pii])
							base::A[pj++] += base::A[pii] * f1;
					}

					RHS[j] += f1 * RHS[i];
				}
			}
		}

		int get_parallel_level(std::size_t k) const
		{
			for (std::size_t i = 0; i <  m_ge_par.size(); i++)
				if (plib::container::contains( m_ge_par[i], k))
					return static_cast<int>(i);
			return -1;
		}

		template <typename V>
		void gaussian_elimination_parallel(V & RHS)
		{
			//printf("omp: %ld %d %d\n", m_ge_par.size(), nz_num, (int)m_ge_par[m_ge_par.size()-2].size());
			for (auto l = 0ul; l < m_ge_par.size(); l++)
				plib::omp::for_static(base::nz_num, 0ul, m_ge_par[l].size(), [this, &RHS, &l] (unsigned ll)
				{
					auto &i = m_ge_par[l][ll];
					{
						std::size_t nzbdp = 0;
						std::size_t pi = base::diag[i];
						const typename base::value_type f = 1.0 / base::A[pi++];
						const std::size_t piie = base::row_idx[i+1];
						const auto &nz = base::nzbd[i];

						while (auto j = nz[nzbdp++])
						{
							// proceed to column i

							std::size_t pj = base::row_idx[j];

							while (base::col_idx[pj] < i)
								pj++;

							const typename base::value_type f1 = - base::A[pj++] * f;

							// subtract row i from j
							// fill-in available assumed, i.e. matrix was prepared
							for (std::size_t pii = pi; pii<piie; pii++)
							{
								while (base::col_idx[pj] < base::col_idx[pii])
									pj++;
								if (base::col_idx[pj] == base::col_idx[pii])
									base::A[pj++] += base::A[pii] * f1;
							}
							RHS[j] += f1 * RHS[i];
						}
					}
				});
		}

		template <typename V1, typename V2>
		void gaussian_back_substitution(V1 &V, const V2 &RHS)
		{
			const std::size_t iN = base::size();
			/* row n-1 */
			V[iN - 1] = RHS[iN - 1] / base::A[base::diag[iN - 1]];

			for (std::size_t j = iN - 1; j-- > 0;)
			{
				typename base::value_type tmp = 0;
				const auto jdiag = base::diag[j];
				const std::size_t e = base::row_idx[j+1];
				for (std::size_t pk = jdiag + 1; pk < e; pk++)
					tmp += base::A[pk] * V[base::col_idx[pk]];
				V[j] = (RHS[j] - tmp) / base::A[jdiag];
			}
		}

		template <typename V1>
		void gaussian_back_substitution(V1 &V)
		{
			const std::size_t iN = base::size();
			/* row n-1 */
			V[iN - 1] = V[iN - 1] / base::A[base::diag[iN - 1]];

			for (std::size_t j = iN - 1; j-- > 0;)
			{
				typename base::value_type tmp = 0;
				const auto jdiag = base::diag[j];
				const std::size_t e = base::row_idx[j+1];
				for (std::size_t pk = jdiag + 1; pk < e; pk++)
					tmp += base::A[pk] * V[base::col_idx[pk]];
				V[j] = (V[j] - tmp) / base::A[jdiag];
			}
		}

	private:
		template <typename M>
		void build_parallel_gaussian_execution_scheme(const M &fill)
		{
			// calculate parallel scheme for gaussian elimination
			std::vector<std::vector<index_type>> rt(base::size());
			for (index_type k = 0; k < base::size(); k++)
			{
				for (index_type j = k+1; j < base::size(); j++)
				{
					if (fill[j][k] < base::FILL_INFINITY)
					{
						rt[k].push_back(j);
					}
				}
			}

			std::vector<index_type> levGE(base::size(), 0);
			index_type cl = 0;

			for (index_type k = 0; k < base::size(); k++ )
			{
				if (levGE[k] >= cl)
				{
					std::vector<index_type> t = rt[k];
					for (index_type j = k+1; j < base::size(); j++ )
					{
						bool overlap = false;
						// is there overlap
						if (plib::container::contains(t, j))
							overlap = true;
						for (auto &x : rt[j])
							if (plib::container::contains(t, x))
							{
								overlap = true;
								break;
							}
						if (overlap)
							levGE[j] = cl + 1;
						else
						{
							t.push_back(j);
							for (auto &x : rt[j])
								t.push_back(x);
						}
					}
					cl++;
				}
			}

			m_ge_par.clear();
			m_ge_par.resize(cl+1);
			for (index_type k = 0; k < base::size(); k++)
				m_ge_par[levGE[k]].push_back(k);
			//for (std::size_t k = 0; k < m_ge_par.size(); k++)
			//  printf("%d %d\n", (int) k, (int) m_ge_par[k].size());
		}
		// contains elimination rows below the diagonal
		std::vector<std::vector<index_type>> m_ge_par; // parallel execution support for Gauss
	};

	template<typename B>
	struct pLUmatrix_cr_t : public B
	{
		using base = B;
		using index_type = typename base::index_type;

		COPYASSIGNMOVE(pLUmatrix_cr_t, default)

		explicit pLUmatrix_cr_t(const index_type n)
		: B(n)
		, ilu_rows(n+1)
		, m_ILUp(0)
		{
		}

		~pLUmatrix_cr_t() = default;

		template <typename M>
		void build(M &fill, std::size_t ilup)
		{
			index_type p(0);
			/* build ilu_rows */
			for (decltype(fill.size()) i=1; i < fill.size(); i++)
			{
				bool found(false);
				for (decltype(fill.size()) k = 0; k < i; k++)
				{
					// if (fill[i][k] < base::FILL_INFINITY)
					if (fill[i][k] <= ilup)
					{
						// assume A[k][k]!=0
						for (decltype(fill.size()) j=k+1; j < fill.size(); j++)
						{
							auto f = std::min(fill[i][j], 1 + fill[i][k] + fill[k][j]);
							if (f <= ilup)
							{
#if 0
								if (f > fill_max)
									fill_max = f;
								ops += 2;
#endif
								fill[i][j] = f;
							}
						}
						found = true;
					}
				}
				if (found)
					ilu_rows[p++] = static_cast<index_type>(i);
			}
			ilu_rows[p] = 0; // end of array
			this->build_from_fill_mat(fill, ilup); //, m_band_width); // ILU(2)
			m_ILUp = ilup;
		}

		void incomplete_LU_factorization(const base &mat)
		{
			/*
			 * incomplete LU Factorization according to http://de.wikipedia.org/wiki/ILU-Zerlegung
			 *
			 * Result is stored in matrix LU
			 *
			 * For i = 1,...,N-1
			 *   For k = 0, ... , i - 1
			 *     If a[i,k] != 0
			 *       a[i,k] = a[i,k] / a[k,k]
			 *       For j = k + 1, ... , N - 1
			 *         If a[i,j] != 0
			 *           a[i,j] = a[i,j] - a[i,k] * a[k,j]
			 *         j=j+1
			 *      k=k+1
			 *    i=i+1
			 *
			 */
			if (m_ILUp < 1)
				this->raw_copy_from(mat);
			else
				this->reduction_copy_from(mat);

			index_type p(0);
			while (auto i = ilu_rows[p++]) // NOLINT(bugprone-infinite-loop)
			{
				const auto p_i_end = base::row_idx[i + 1];
				// loop over all columns k left of diag in row i
				//if (row_idx[i] < diag[i])
				//  printf("occ %d\n", (int)i);
				for (auto i_k = base::row_idx[i]; i_k < base::diag[i]; i_k++)
				{
					const auto k(base::col_idx[i_k]);
					const auto p_k_end(base::row_idx[k + 1]);
					const typename base::value_type LUp_i_k = base::A[i_k] = base::A[i_k] / base::A[base::diag[k]];

					index_type k_j(base::diag[k] + 1);
					index_type i_j(i_k + 1);

					while (i_j < p_i_end && k_j < p_k_end )  // pj = (i, j)
					{
						// we can assume that within a row ja increases continuously */
						const index_type c_i_j(base::col_idx[i_j]); // row i, column j
						const auto c_k_j(base::col_idx[k_j]); // row k, column j

						if (c_k_j == c_i_j)
							base::A[i_j] -= LUp_i_k * base::A[k_j];
						k_j += (c_k_j <= c_i_j ? 1 : 0);
						i_j += (c_k_j >= c_i_j ? 1 : 0);

					}
				}
			}
		}

		template <typename R>
		void solveLU (R &r)
		{
			/*
			 * Solve a linear equation Ax = r
			 * where
			 *      A = L*U
			 *
			 *      L unit lower triangular
			 *      U upper triangular
			 *
			 * ==> LUx = r
			 *
			 * ==> Ux = L⁻¹ r = w
			 *
			 * ==> r = Lw
			 *
			 * This can be solved for w using backwards elimination in L.
			 *
			 * Now Ux = w
			 *
			 * This can be solved for x using backwards elimination in U.
			 *
			 */
			for (index_type i = 1; i < base::size(); ++i )
			{
				typename base::value_type tmp(0);
				const auto j1(base::row_idx[i]);
				const auto j2(base::diag[i]);

				for (auto j = j1; j < j2; ++j )
					tmp +=  base::A[j] * r[base::col_idx[j]];
				r[i] -= tmp;
			}
			// i now is equal to n;
			for (index_type i = base::size(); i-- > 0; )
			{
				typename base::value_type tmp(0);
				const auto di(base::diag[i]);
				const auto j2(base::row_idx[i+1]);
				for (index_type j = di + 1; j < j2; j++ )
					tmp += base::A[j] * r[base::col_idx[j]];
				r[i] = (r[i] - tmp) / base::A[di];
			}
		}
	private:
		parray<index_type, base::Np1> ilu_rows;
		std::size_t m_ILUp;
	};

} // namespace plib

#endif /* MAT_CR_H_ */