summaryrefslogtreecommitdiffstatshomepage
path: root/src/lib/netlist/plib/gmres.h
blob: 0ce27faead8baf11567e24ff15502d986ac6ea99 (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
// license:GPL-2.0+
// copyright-holders:Couriersud
/*
 * gmres.h
 *
 */

#ifndef PLIB_GMRES_H_
#define PLIB_GMRES_H_

#include "mat_cr.h"
#include "parray.h"
#include "pconfig.h"
#include "vector_ops.h"

#include <algorithm>
#include <cmath>


namespace plib
{

	template <int k>
	struct do_khelper
	{
		static constexpr bool value = true;
	};

	template <>
	struct do_khelper<-1>
	{
		static constexpr float value = 0.0;
	};

	template <typename FT, int SIZE>
	struct mat_precondition_ILU
	{
		using mat_type = plib::matrix_compressed_rows_t<FT, SIZE>;

		mat_precondition_ILU(std::size_t size, std::size_t ilu_scale = 4
			, std::size_t bw = plib::matrix_compressed_rows_t<FT, SIZE>::FILL_INFINITY)
		: m_mat(static_cast<typename mat_type::index_type>(size))
		, m_LU(static_cast<typename mat_type::index_type>(size))
		, m_ILU_scale(static_cast<std::size_t>(ilu_scale))
		, m_band_width(bw)
		{
		}

		template <typename M>
		void build(M &fill)
		{
			m_mat.build_from_fill_mat(fill, 0);
			m_LU.gaussian_extend_fill_mat(fill);
			m_LU.build_from_fill_mat(fill, m_ILU_scale, m_band_width); // ILU(2)
			//m_LU.build_from_fill_mat(fill, 9999, 20); // Band matrix width 20
		}


		template<typename R, typename V>
		void calc_rhs(R &rhs, const V &v)
		{
			m_mat.mult_vec(rhs, v);
		}

		void precondition()
		{
			if (m_ILU_scale < 1)
				m_LU.raw_copy_from(m_mat);
			else
				m_LU.reduction_copy_from(m_mat);
			m_LU.incomplete_LU_factorization();
		}

		template<typename V>
		void solve_inplace(V &v)
		{
			m_LU.solveLU(v);
		}

		PALIGNAS_VECTOROPT()
		mat_type                m_mat;
		PALIGNAS_VECTOROPT()
		mat_type                m_LU;
		std::size_t             m_ILU_scale;
		std::size_t             m_band_width;
	};

	template <typename FT, int SIZE>
	struct mat_precondition_diag
	{
		mat_precondition_diag(std::size_t size, int dummy = 0)
		: m_mat(size)
		, m_diag(size)
		, nzcol(size)
		{
			plib::unused_var(dummy);
		}

		template <typename M>
		void build(M &fill)
		{
			m_mat.build_from_fill_mat(fill, 0);
			for (std::size_t i = 0; i< m_diag.size(); i++)
			{
				for (std::size_t j = 0; j< m_diag.size(); j++)
				{
					std::size_t k=m_mat.row_idx[j];
					while (m_mat.col_idx[k] < i && k < m_mat.row_idx[j+1])
						k++;
					if (m_mat.col_idx[k] == i && k < m_mat.row_idx[j+1])
						nzcol[i].push_back(k);
				}
				nzcol[i].push_back(static_cast<std::size_t>(-1));
			}
		}

		template<typename R, typename V>
		void calc_rhs(R &rhs, const V &v)
		{
			m_mat.mult_vec(rhs, v);
		}

		void precondition()
		{
			for (std::size_t i = 0; i< m_diag.size(); i++)
			{
				// ILUT: 265%
				FT v(0.0);
#if 0
				// doesn't works, Mame perforamnce drops significantly%
				// 136%
				for (std::size_t j = m_mat.row_idx[i]; j< m_mat.row_idx[i+1]; j++)
					v += m_mat.A[j] * m_mat.A[j];
				m_diag[i] = 1.0 / std::sqrt(v);
#elif 0
				// works halfway, i.e. Mame perforamnce 50%
				// 147% - lowest average solution time with 7.094
				for (std::size_t j = m_mat.row_idx[i]; j< m_mat.row_idx[i+1]; j++)
					v += m_mat.A[j] * m_mat.A[j];
				m_diag[i] = m_mat.A[m_mat.diag[i]] / v;
#elif 0
				// works halfway, i.e. Mame perforamnce 50%
				// sum over column i
				// 344% - lowest average solution time with 3.06
				std::size_t nzcolp = 0;
				const auto &nz = nzcol[i];
				std::size_t j;

				while ((j = nz[nzcolp++])!=static_cast<std::size_t>(-1)) // NOLINT(bugprone-infinite-loop)
				{
					v += m_mat.A[j] * m_mat.A[j];
				}
				m_diag[i] = m_mat.A[m_mat.diag[i]] / v;
#elif 0
				// works halfway, i.e. Mame perforamnce 50%
				// 151%
				for (std::size_t j = m_mat.row_idx[i]; j< m_mat.row_idx[i+1]; j++)
					v += std::abs(m_mat.A[j]);
				m_diag[i] =  1.0 / v;
#else
				// 124%
				for (std::size_t j = m_mat.row_idx[i]; j< m_mat.row_idx[i+1]; j++)
					v = std::max(v, std::abs(m_mat.A[j]));
				m_diag[i] = 1.0 / v;
#endif
				//m_diag[i] = 1.0 / m_mat.A[m_mat.diag[i]];
			}
		}

		template<typename V>
		void solve_inplace(V &v)
		{
			for (std::size_t i = 0; i< m_diag.size(); i++)
				v[i] = v[i] * m_diag[i];
		}

		plib::matrix_compressed_rows_t<FT, SIZE> m_mat;
		plib::parray<FT, SIZE> m_diag;
		plib::parray<std::vector<std::size_t>, SIZE > nzcol;
	};

	template <typename FT, int SIZE>
	struct mat_precondition_none
	{
		mat_precondition_none(std::size_t size, int dummy = 0)
		: m_mat(size)
		{
			plib::unused_var(dummy);
		}

		template <typename M>
		void build(M &fill)
		{
			m_mat.build_from_fill_mat(fill, 0);
		}

		template<typename R, typename V>
		void calc_rhs(R &rhs, const V &v)
		{
			m_mat.mult_vec(rhs, v);
		}

		void precondition()
		{
		}

		template<typename V>
		void solve_inplace(V &v)
		{
			plib::unused_var(v);
		}

		plib::matrix_compressed_rows_t<FT, SIZE> m_mat;
	};

	/* FIXME: hardcoding RESTART to 20 becomes an issue on very large
	 * systems.
	 */
	template <typename FT, int SIZE, int RESTART = 80>
	struct gmres_t
	{
	public:

		using float_type = FT;
		// FIXME: dirty hack to make this compile
		static constexpr const std::size_t storage_N = plib::sizeabs<FT, SIZE>::ABS();

		gmres_t(std::size_t size)
			: residual(size)
			, Ax(size)
			, m_size(size)
			, m_use_more_precise_stop_condition(false)
			{
			}

		void givens_mult( const FT c, const FT s, FT & g0, FT & g1 )
		{
			const FT g0_last(g0);

			g0 = c * g0 - s * g1;
			g1 = s * g0_last + c * g1;
		}

		std::size_t size() const { return (SIZE<=0) ? m_size : static_cast<std::size_t>(SIZE); }

		template <int k, typename OPS, typename VT>
		bool do_k(OPS &ops, VT &x, std::size_t &itr_used, FT rho_delta, bool dummy)
		{
			plib::unused_var(dummy);
			//printf("%d\n", k);
			if (do_k<k-1, OPS>(ops, x, itr_used, rho_delta, do_khelper<k-1>::value))
				return true;

			const std::size_t kp1 = k + 1;
			const    std::size_t n = size();

			ops.calc_rhs(m_v[kp1], m_v[k]);
			ops.solve_inplace(m_v[kp1]);

			for (std::size_t j = 0; j <= k; j++)
			{
				m_ht[j][k] = vec_mult<FT>(n, m_v[kp1], m_v[j]);
				vec_add_mult_scalar(n, m_v[kp1], m_v[j], -m_ht[j][k]);
			}
			m_ht[kp1][k] = std::sqrt(vec_mult2<FT>(n, m_v[kp1]));

			if (m_ht[kp1][k] != 0.0)
				vec_scale(n, m_v[kp1], constants<FT>::one() / m_ht[kp1][k]);

			for (std::size_t j = 0; j < k; j++)
				givens_mult(m_c[j], m_s[j], m_ht[j][k], m_ht[j+1][k]);

			const float_type mu = 1.0 / std::hypot(m_ht[k][k], m_ht[kp1][k]);

			m_c[k] = m_ht[k][k] * mu;
			m_s[k] = -m_ht[kp1][k] * mu;
			m_ht[k][k] = m_c[k] * m_ht[k][k] - m_s[k] * m_ht[kp1][k];
			m_ht[kp1][k] = 0.0;

			givens_mult(m_c[k], m_s[k], m_g[k], m_g[kp1]);

			FT rho = std::abs(m_g[kp1]);

			// FIXME ..
			itr_used = itr_used + 1;

			if (rho <= rho_delta || k == RESTART-1)
			{
				/* Solve the system H * y = g */
				/* x += m_v[j] * m_y[j]       */
				for (std::size_t i = k + 1; i-- > 0;)
				{
					double tmp = m_g[i];
					for (std::size_t j = i + 1; j <= k; j++)
						tmp -= m_ht[i][j] * m_y[j];
					m_y[i] = tmp / m_ht[i][i];
				}

				for (std::size_t i = 0; i <= k; i++)
					vec_add_mult_scalar(n, x, m_v[i], m_y[i]);
				return true;
			}
			else
				return false;
		}

		template <int k, typename OPS, typename VT>
		bool do_k(OPS &ops, VT &x, std::size_t &itr_used, FT rho_delta, float dummy)
		{
			plib::unused_var(ops, x, itr_used, rho_delta, dummy);
			return false;
		}

		template <typename OPS, typename VT, typename VRHS>
		std::size_t solve(OPS &ops, VT &x, const VRHS & rhs, const std::size_t itr_max, float_type accuracy)
		{
			/*-------------------------------------------------------------------------
			 * The code below was inspired by code published by John Burkardt under
			 * the LPGL here:
			 *
			 * http://people.sc.fsu.edu/~jburkardt/cpp_src/mgmres/mgmres.html
			 *
			 * The code below was completely written from scratch based on the pseudo code
			 * found here:
			 *
			 * http://de.wikipedia.org/wiki/GMRES-Verfahren
			 *
			 * The Algorithm itself is described in
			 *
			 * Yousef Saad,
			 * Iterative Methods for Sparse Linear Systems,
			 * Second Edition,
			 * SIAM, 20003,
			 * ISBN: 0898715342,
			 * LC: QA188.S17.
			 *
			 *------------------------------------------------------------------------*/

			std::size_t itr_used = 0;
			double rho_delta = 0.0;

			const    std::size_t n = size();

			ops.precondition();

			if (m_use_more_precise_stop_condition)
			{
				/* derive residual for a given delta x
				 *
				 * LU y = A dx
				 *
				 * ==> rho / accuracy = sqrt(y * y)
				 *
				 * This approach will approximate the iterative stop condition
				 * based |xnew - xold| pretty precisely. But it is slow, or expressed
				 * differently: The invest doesn't pay off.
				 */

				vec_set_scalar(n, residual, accuracy);
				ops.calc_rhs(Ax, residual);

				ops.solve_inplace(Ax);

				const float_type rho_to_accuracy = std::sqrt(vec_mult2<FT>(n, Ax)) / accuracy;

				rho_delta = accuracy * rho_to_accuracy;
			}
			else
				rho_delta = accuracy * std::sqrt(static_cast<FT>(n));

			/*
			 * Using
			 *
			 * vec_set(n, x, rhs);
			 * ops.solve_inplace(x);
			 *
			 * to get a starting point for x degrades convergence speed compared
			 * to using the last solution for x.
			 *
			 * LU x = b; solve for x;
			 *
			 */

			while (itr_used < itr_max)
			{
				float_type rho;

				ops.calc_rhs(Ax, x);

				vec_sub(n, residual, rhs, Ax);

				ops.solve_inplace(residual);

				rho = std::sqrt(vec_mult2<FT>(n, residual));

				if (rho < rho_delta)
					return itr_used + 1;

				/* FIXME: The "+" is necessary to avoid link issues
				 * on some systems / compiler versions. Issue reported by
				 * AJR, no details known yet.
				 */
				vec_set_scalar(RESTART+1, m_g, +constants<FT>::zero());
				m_g[0] = rho;

				vec_mult_scalar(n, m_v[0], residual, constants<FT>::one() / rho);

				if (do_k<RESTART-1>(ops, x, itr_used, rho_delta, true))
					// converged
					break;
			}
			return itr_used;
		}

	private:

		//typedef typename plib::mat_cr_t<FT, SIZE>::index_type mattype;

		plib::parray<float_type, SIZE> residual;
		plib::parray<float_type, SIZE> Ax;

		plib::parray<float_type, RESTART + 1> m_c;              /* mr + 1 */
		plib::parray<float_type, RESTART + 1> m_g;              /* mr + 1 */
		plib::parray<plib::parray<float_type, RESTART>, RESTART + 1> m_ht;  /* (mr + 1), mr */
		plib::parray<float_type, RESTART + 1> m_s;              /* mr + 1 */
		plib::parray<float_type, RESTART + 1> m_y;              /* mr + 1 */

		//plib::parray<float_type, SIZE> m_v[RESTART + 1];  /* mr + 1, n */
		plib::parray<plib::parray<float_type, storage_N>, RESTART + 1> m_v;  /* mr + 1, n */

		std::size_t m_size;

		bool m_use_more_precise_stop_condition;


	};


#if 0
	/* Example of a Chebyshev iteration solver. This one doesn't work yet,
	 * it needs to be extended for non-symmetric matrix operation and
	 * depends on spectral radius estimates - which we don't have.
	 *
	 * Left here as another example.
	 */

	template <typename FT, int SIZE>
	struct ch_t
	{
	public:

		typedef FT float_type;
		// FIXME: dirty hack to make this compile
		static constexpr const std::size_t storage_N = plib::sizeabs<FT, SIZE>::ABS();

		// Maximum iterations before a restart ...
		static constexpr const std::size_t restart_N = (storage_N > 0 ? 20 : 0);

		ch_t(std::size_t size)
		: residual(size)
		, Ax(size)
		, m_size(size)
		{
		}

		std::size_t size() const { return (SIZE<=0) ? m_size : static_cast<std::size_t>(SIZE); }

		template <typename OPS, typename VT, typename VRHS>
		std::size_t solve(OPS &ops, VT &x0, const VRHS & rhs, const std::size_t iter_max, float_type accuracy)
		{
			/*-------------------------------------------------------------------------
			 *
			 *
			 *------------------------------------------------------------------------*/

			ops.precondition();

			const FT lmax = 20.0;
			const FT lmin = 0.0001;

			const FT d = (lmax+lmin)/2.0;
			const FT c = (lmax-lmin)/2.0;
			FT alpha = 0;
			FT beta = 0;
			std::size_t itr_used = 0;

			plib::parray<FT, SIZE> x(size());
			plib::parray<FT, SIZE> p(size());

			plib::vec_set(size(), x, x0);

			ops.calc_rhs(Ax, x);
			vec_sub(size(), rhs, Ax, residual);

			FT rho_delta = accuracy * std::sqrt(static_cast<FT>(size()));

			rho_delta = 1e-9;

			for (int i = 0; i < iter_max; i++)
			{
				ops.solve_inplace(residual);
				if (i==0)
				{
					vec_set(size(), p, residual);
					alpha = 2.0 / d;
				}
				else
				{
					  beta = alpha * ( c / 2.0)*( c / 2.0);
					  alpha = 1.0 / (d - beta);
					  for (std::size_t k = 0; k < size(); k++)
						  p[k] = residual[k] + beta * p[k];
				}
				plib::vec_add_mult_scalar(size(), p, alpha, x);
				ops.calc_rhs(Ax, x);
				plib::vec_sub(size(), rhs, Ax, residual);
				FT rho = std::sqrt(plib::vec_mult2<FT>(size(), residual));
				if (rho < rho_delta)
					break;
				itr_used++;
			}
			return itr_used;
		}
	private:

		//typedef typename plib::mat_cr_t<FT, SIZE>::index_type mattype;

		plib::parray<float_type, SIZE> residual;
		plib::parray<float_type, SIZE> Ax;

		std::size_t m_size;

	};
#endif

} // namespace plib

#endif /* PLIB_GMRES_H_ */