File: spline.h

package info (click to toggle)
mldemos 0.5.1-3
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 32,224 kB
  • ctags: 46,525
  • sloc: cpp: 306,887; ansic: 167,718; ml: 126; sh: 109; makefile: 2
file content (289 lines) | stat: -rw-r--r-- 8,162 bytes parent folder | download | duplicates (2)
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
#ifndef SPLINE_H
#define SPLINE_H

#ifdef WITHBOOST
/*  dynamo:- Event driven molecular dynamics simulator
	http://www.marcusbannerman.co.uk/dynamo
	Copyright (C) 2011  Marcus N Campbell Bannerman <m.bannerman@gmail.com>

	This program is free software: you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	version 3 as published by the Free Software Foundation.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#pragma once

#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/triangular.hpp>
#include <boost/numeric/ublas/lu.hpp>
#include <exception>

namespace ublas = boost::numeric::ublas;
namespace magnet {
  namespace math {
	class Spline : private std::vector<std::pair<double, double> >
	{
	public:
	  //The boundary conditions available
	  enum BC_type {FIXED_1ST_DERIV_BC,
			FIXED_2ND_DERIV_BC,
			PARABOLIC_RUNOUT_BC};

	  //Constructor takes the boundary conditions as arguments, this
	  //sets the first derivative (gradient) at the lower and upper
	  //end points
	  Spline():
	_valid(false),
	_BCLow(FIXED_2ND_DERIV_BC), _BCHigh(FIXED_2ND_DERIV_BC),
	_BCLowVal(0), _BCHighVal(0)
	  {}

	  typedef std::vector<std::pair<double, double> > base;
	  typedef base::const_iterator const_iterator;

	  //Standard STL read-only container stuff
	  const_iterator begin() const { return base::begin(); }
	  const_iterator end() const { return base::end(); }
	  void clear() { _valid = false; base::clear(); _data.clear(); }
	  size_t size() const { return base::size(); }
	  size_t max_size() const { return base::max_size(); }
	  size_t capacity() const { return base::capacity(); }
	  bool empty() const { return base::empty(); }

	  //Add a point to the spline, and invalidate it so its
	  //recalculated on the next access
	  inline void addPoint(double x, double y)
	  {
	_valid = false;
	base::push_back(std::pair<double, double>(x,y));
	  }

	  //Reset the boundary conditions
	  inline void setLowBC(BC_type BC, double val = 0)
	  { _BCLow = BC; _BCLowVal = val; _valid = false; }

	  inline void setHighBC(BC_type BC, double val = 0)
	  { _BCHigh = BC; _BCHighVal = val; _valid = false; }

	  //Check if the spline has been calculated, then generate the
	  //spline interpolated value
	  double operator()(double xval)
	  {
	if (!_valid) generate();

	//Special cases when we're outside the range of the spline points
	if (xval <= x(0)) return lowCalc(xval);
	if (xval >= x(size()-1)) return highCalc(xval);

	//Check all intervals except the last one
	for (std::vector<SplineData>::const_iterator iPtr = _data.begin();
		 iPtr != _data.end()-1; ++iPtr)
		if ((xval >= iPtr->x) && (xval <= (iPtr+1)->x))
		  return splineCalc(iPtr, xval);

	return splineCalc(_data.end() - 1, xval);
	  }

	private:

	  ///////PRIVATE DATA MEMBERS
	  struct SplineData { double x,a,b,c,d; };
	  //vector of calculated spline data
	  std::vector<SplineData> _data;
	  //Second derivative at each point
	  ublas::vector<double> _ddy;
	  //Tracks whether the spline parameters have been calculated for
	  //the current set of points
	  bool _valid;
	  //The boundary conditions
	  BC_type _BCLow, _BCHigh;
	  //The values of the boundary conditions
	  double _BCLowVal, _BCHighVal;

	  ///////PRIVATE FUNCTIONS
	  //Function to calculate the value of a given spline at a point xval
	  inline double splineCalc(std::vector<SplineData>::const_iterator i, double xval)
	  {
	const double lx = xval - i->x;
	return ((i->a * lx + i->b) * lx + i->c) * lx + i->d;
	  }

	  inline double lowCalc(double xval)
	  {
	const double lx = xval - x(0);
	const double firstDeriv = (y(1) - y(0)) / h(0) - 2 * h(0) * (_data[0].b + 2 * _data[1].b) / 6;
	switch(_BCLow)
	  {
	  case FIXED_1ST_DERIV_BC:
		return lx * _BCLowVal + y(0);
	  case FIXED_2ND_DERIV_BC:
		  return lx * lx * _BCLowVal + firstDeriv * lx + y(0);
	  case PARABOLIC_RUNOUT_BC:
		return lx * lx * _ddy[0] + lx * firstDeriv  + y(0);
	  }
	throw std::runtime_error("Unknown BC");
	  }

	  inline double highCalc(double xval)
	  {
	const double lx = xval - x(size() - 1);
	const double firstDeriv = 2 * h(size() - 2) * (_ddy[size() - 2] + 2 * _ddy[size() - 1]) / 6 + (y(size() - 1) - y(size() - 2)) / h(size() - 2);
	switch(_BCHigh)
	  {
	  case FIXED_1ST_DERIV_BC:
		return lx * _BCHighVal + y(size() - 1);
	  case FIXED_2ND_DERIV_BC:
		return lx * lx * _BCHighVal + firstDeriv * lx + y(size() - 1);
	  case PARABOLIC_RUNOUT_BC:
		return lx * lx * _ddy[size()-1] + lx * firstDeriv  + y(size() - 1);
	  }
	throw std::runtime_error("Unknown BC");
	  }

	  //These just provide access to the point data in a clean way
	  inline double x(size_t i) const { return operator[](i).first; }
	  inline double y(size_t i) const { return operator[](i).second; }
	  inline double h(size_t i) const { return x(i+1) - x(i); }

	  //Invert a arbitrary matrix using the boost ublas library
	  template<class T>
	  bool InvertMatrix(ublas::matrix<T> A,
			ublas::matrix<T>& inverse)
	  {
	using namespace ublas;

	// create a permutation matrix for the LU-factorization
	permutation_matrix<std::size_t> pm(A.size1());

	// perform LU-factorization
	int res = lu_factorize(A,pm);
		if( res != 0 ) return false;

	// create identity matrix of "inverse"
	inverse.assign(ublas::identity_matrix<T>(A.size1()));

	// backsubstitute to get the inverse
	lu_substitute(A, pm, inverse);

	return true;
	  }

	  //This function will recalculate the spline parameters and store
	  //them in _data, ready for spline interpolation
	  void generate()
	  {
	if (size() < 2)
	  throw std::runtime_error("Spline requires at least 2 points");


	//If any spline points are at the same x location, we have to
	//just slightly seperate them
	{
	  bool testPassed(false);
	  while (!testPassed)
		{
		  testPassed = true;
		  std::sort(base::begin(), base::end());

		  for (base::iterator iPtr = base::begin(); iPtr != base::end() - 1; ++iPtr)
		if (iPtr->first == (iPtr+1)->first)
		  {
			if ((iPtr+1)->first != 0)
			  (iPtr+1)->first += (iPtr+1)->first
			* std::numeric_limits<double>::epsilon() * 10;
			else
			  (iPtr+1)->first = std::numeric_limits<double>::epsilon() * 10;
			testPassed = false;
			break;
		  }
		}
	}

	const size_t e = size() - 1;

	ublas::matrix<double> A(size(), size());
	for (size_t yv(0); yv <= e; ++yv)
	  for (size_t xv(0); xv <= e; ++xv)
		A(xv,yv) = 0;

	for (size_t i(1); i < e; ++i)
	  {
		A(i-1,i) = h(i-1);
		A(i,i) = 2 * (h(i-1) + h(i));
		A(i+1,i) = h(i);
	  }

	ublas::vector<double> C(size());
	for (size_t xv(0); xv <= e; ++xv)
	  C(xv) = 0;

	for (size_t i(1); i < e; ++i)
	  C(i) = 6 *
		((y(i+1) - y(i)) / h(i)
		 - (y(i) - y(i-1)) / h(i-1));

	//Boundary conditions
	switch(_BCLow)
	  {
	  case FIXED_1ST_DERIV_BC:
		C(0) = 6 * ((y(1) - y(0)) / h(0) - _BCLowVal);
		A(0,0) = 2 * h(0);
		A(1,0) = h(0);
		break;
	  case FIXED_2ND_DERIV_BC:
		C(0) = _BCLowVal;
		A(0,0) = 1;
		break;
	  case PARABOLIC_RUNOUT_BC:
		C(0) = 0; A(0,0) = 1; A(1,0) = -1;
		break;
	  }

	switch(_BCHigh)
	  {
	  case FIXED_1ST_DERIV_BC:
		C(e) = 6 * (_BCHighVal - (y(e) - y(e-1)) / h(e-1));
		A(e,e) = 2 * h(e - 1);
		A(e-1,e) = h(e - 1);
		break;
	  case FIXED_2ND_DERIV_BC:
		C(e) = _BCHighVal;
		A(e,e) = 1;
		break;
	  case PARABOLIC_RUNOUT_BC:
		C(e) = 0; A(e,e) = 1; A(e-1,e) = -1;
		break;
	  }

	ublas::matrix<double> AInv(size(), size());
	InvertMatrix(A,AInv);

		_ddy = ublas::prod(C, AInv);

	_data.resize(size()-1);
	for (size_t i(0); i < e; ++i)
	  {
		_data[i].x = x(i);
		_data[i].a = (_ddy(i+1) - _ddy(i)) / (6 * h(i));
		_data[i].b = _ddy(i) / 2;
		_data[i].c = (y(i+1) - y(i)) / h(i) - _ddy(i+1) * h(i) / 6 - _ddy(i) * h(i) / 3;
		_data[i].d = y(i);
	  }
	_valid = true;
	  }
	};
  }
}

#endif // WITHBOOST
#endif // SPLINE_H