CMS 3D CMS Logo

PulseChiSqSNNLS.cc
Go to the documentation of this file.
2 #include <cmath>
4 #include <iostream>
5 
6 void eigen_solve_submatrix(PulseMatrix& mat, PulseVector& invec, PulseVector& outvec, unsigned NP) {
7  using namespace Eigen;
8  switch( NP ) { // pulse matrix is always square.
9  case 10:
10  {
11  Matrix<double,10,10> temp = mat.topLeftCorner<10,10>();
12  outvec.head<10>() = temp.ldlt().solve(invec.head<10>());
13  }
14  break;
15  case 9:
16  {
17  Matrix<double,9,9> temp = mat.topLeftCorner<9,9>();
18  outvec.head<9>() = temp.ldlt().solve(invec.head<9>());
19  }
20  break;
21  case 8:
22  {
23  Matrix<double,8,8> temp = mat.topLeftCorner<8,8>();
24  outvec.head<8>() = temp.ldlt().solve(invec.head<8>());
25  }
26  break;
27  case 7:
28  {
29  Matrix<double,7,7> temp = mat.topLeftCorner<7,7>();
30  outvec.head<7>() = temp.ldlt().solve(invec.head<7>());
31  }
32  break;
33  case 6:
34  {
35  Matrix<double,6,6> temp = mat.topLeftCorner<6,6>();
36  outvec.head<6>() = temp.ldlt().solve(invec.head<6>());
37  }
38  break;
39  case 5:
40  {
41  Matrix<double,5,5> temp = mat.topLeftCorner<5,5>();
42  outvec.head<5>() = temp.ldlt().solve(invec.head<5>());
43  }
44  break;
45  case 4:
46  {
47  Matrix<double,4,4> temp = mat.topLeftCorner<4,4>();
48  outvec.head<4>() = temp.ldlt().solve(invec.head<4>());
49  }
50  break;
51  case 3:
52  {
53  Matrix<double,3,3> temp = mat.topLeftCorner<3,3>();
54  outvec.head<3>() = temp.ldlt().solve(invec.head<3>());
55  }
56  break;
57  case 2:
58  {
59  Matrix<double,2,2> temp = mat.topLeftCorner<2,2>();
60  outvec.head<2>() = temp.ldlt().solve(invec.head<2>());
61  }
62  break;
63  case 1:
64  {
65  Matrix<double,1,1> temp = mat.topLeftCorner<1,1>();
66  outvec.head<1>() = temp.ldlt().solve(invec.head<1>());
67  }
68  break;
69  default:
70  throw cms::Exception("MultFitWeirdState")
71  << "Weird number of pulses encountered in multifit, module is configured incorrectly!";
72  }
73 }
74 
76  _chisq(0.),
77  _computeErrors(true),
78  _maxiters(50),
79  _maxiterwarnings(true)
80 {
81 
82 }
83 
85 
86 }
87 
88 bool PulseChiSqSNNLS::DoFit(const SampleVector &samples, const SampleMatrix &samplecov, const BXVector &bxs, const FullSampleVector &fullpulse, const FullSampleMatrix &fullpulsecov, const SampleGainVector &gains, const SampleGainVector &badSamples) {
89 
90  int npulse = bxs.rows();
91 
92  _sampvec = samples;
93  _bxs = bxs;
94  _pulsemat.resize(Eigen::NoChange,npulse);
95 
96  //construct dynamic pedestals if applicable
97  int ngains = gains.maxCoeff()+1;
98  int nPedestals = 0;
99  for (int gainidx=0; gainidx<ngains; ++gainidx) {
100  SampleGainVector mask = gainidx*SampleGainVector::Ones();
101  SampleVector pedestal = (gains.array()==mask.array()).cast<SampleVector::value_type>();
102  if (pedestal.maxCoeff()>0.) {
103  ++nPedestals;
104  _bxs.resize(npulse+nPedestals);
105  _bxs[npulse+nPedestals-1] = 100 + gainidx; //bx values >=100 indicate dynamic pedestals
106  _pulsemat.resize(Eigen::NoChange, npulse+nPedestals);
107  _pulsemat.col(npulse+nPedestals-1) = pedestal;
108  }
109  }
110 
111  //construct negative step functions for saturated or potentially slew-rate-limited samples
112  for (int isample=0; isample<SampleVector::RowsAtCompileTime; ++isample) {
113  if (badSamples.coeff(isample)>0) {
114  SampleVector step = SampleVector::Zero();
115  //step correction has negative sign for saturated or slew-limited samples which have been forced to zero
116  step[isample] = -1.;
117 
118  ++nPedestals;
119  _bxs.resize(npulse+nPedestals);
120  _bxs[npulse+nPedestals-1] = -100 - isample; //bx values <=-100 indicate step corrections for saturated or slew-limited samples
121  _pulsemat.resize(Eigen::NoChange, npulse+nPedestals);
122  _pulsemat.col(npulse+nPedestals-1) = step;
123  }
124  }
125 
126  _npulsetot = npulse + nPedestals;
127 
128  _ampvec = PulseVector::Zero(_npulsetot);
129  _errvec = PulseVector::Zero(_npulsetot);
130  _nP = 0;
131  _chisq = 0.;
132 
133  if (_bxs.rows()==1 && std::abs(_bxs.coeff(0))<100) {
134  _ampvec.coeffRef(0) = _sampvec.coeff(_bxs.coeff(0) + 5);
135  }
136 
137  aTamat.resize(_npulsetot,_npulsetot);
138 
139  //initialize pulse template matrix
140  for (int ipulse=0; ipulse<npulse; ++ipulse) {
141  int bx = _bxs.coeff(ipulse);
142  int offset = 7-3-bx;
143  _pulsemat.col(ipulse) = fullpulse.segment<SampleVector::RowsAtCompileTime>(offset);
144  }
145 
146  //unconstrain pedestals already for first iteration since they should always be non-zero
147  if (nPedestals>0) {
148  for (int i=0; i<_bxs.rows(); ++i) {
149  int bx = _bxs.coeff(i);
150  if (bx>=100) {
152  }
153  }
154  }
155 
156  //do the actual fit
157  bool status = Minimize(samplecov,fullpulsecov);
159  _bxsmin = _bxs;
160 
161  if (!status) return status;
162 
163  if(!_computeErrors) return status;
164 
165  //compute MINOS-like uncertainties for in-time amplitude
166  bool foundintime = false;
167  unsigned int ipulseintime = 0;
168  for (unsigned int ipulse=0; ipulse<_npulsetot; ++ipulse) {
169  if (_bxs.coeff(ipulse)==0) {
170  ipulseintime = ipulse;
171  foundintime = true;
172  break;
173  }
174  }
175  if (!foundintime) return status;
176 
177  const unsigned int ipulseintimemin = ipulseintime;
178 
179  double approxerr = ComputeApproxUncertainty(ipulseintime);
180  double chisq0 = _chisq;
181  double x0 = _ampvecmin[ipulseintime];
182 
183  //move in time pulse first to active set if necessary
184  if (ipulseintime<_nP) {
185  _pulsemat.col(_nP-1).swap(_pulsemat.col(ipulseintime));
186  std::swap(_ampvec.coeffRef(_nP-1),_ampvec.coeffRef(ipulseintime));
187  std::swap(_bxs.coeffRef(_nP-1),_bxs.coeffRef(ipulseintime));
188  ipulseintime = _nP - 1;
189  --_nP;
190  }
191 
192 
193  SampleVector pulseintime = _pulsemat.col(ipulseintime);
194  _pulsemat.col(ipulseintime).setZero();
195 
196  //two point interpolation for upper uncertainty when amplitude is away from boundary
197  double xplus100 = x0 + approxerr;
198  _ampvec.coeffRef(ipulseintime) = xplus100;
199  _sampvec = samples - _ampvec.coeff(ipulseintime)*pulseintime;
200  status &= Minimize(samplecov,fullpulsecov);
201  if (!status) return status;
202  double chisqplus100 = ComputeChiSq();
203 
204  double sigmaplus = std::abs(xplus100-x0)/sqrt(chisqplus100-chisq0);
205 
206  //if amplitude is sufficiently far from the boundary, compute also the lower uncertainty and average them
207  if ( (x0/sigmaplus) > 0.5 ) {
208  for (unsigned int ipulse=0; ipulse<_npulsetot; ++ipulse) {
209  if (_bxs.coeff(ipulse)==0) {
210  ipulseintime = ipulse;
211  break;
212  }
213  }
214  double xminus100 = std::max(0.,x0-approxerr);
215  _ampvec.coeffRef(ipulseintime) = xminus100;
216  _sampvec = samples - _ampvec.coeff(ipulseintime)*pulseintime;
217  status &= Minimize(samplecov,fullpulsecov);
218  if (!status) return status;
219  double chisqminus100 = ComputeChiSq();
220 
221  double sigmaminus = std::abs(xminus100-x0)/sqrt(chisqminus100-chisq0);
222  _errvec[ipulseintimemin] = 0.5*(sigmaplus + sigmaminus);
223 
224  }
225  else {
226  _errvec[ipulseintimemin] = sigmaplus;
227  }
228 
229  _chisq = chisq0;
230 
231  return status;
232 
233 }
234 
235 bool PulseChiSqSNNLS::Minimize(const SampleMatrix &samplecov, const FullSampleMatrix &fullpulsecov) {
236 
237  const unsigned int npulse = _bxs.rows();
238 
239  int iter = 0;
240  bool status = false;
241  while (true) {
242 
243  if (iter>=_maxiters) {
244  if (_maxiterwarnings) {
245  LogDebug("PulseChiSqSNNLS::Minimize") << "Max Iterations reached at iter " << iter;
246  }
247  break;
248  }
249 
250  status = updateCov(samplecov,fullpulsecov);
251  if (!status) break;
252  if (npulse>1) {
253  status = NNLS();
254  }
255  else {
256  //special case for one pulse fit (performance optimized)
257  status = OnePulseMinimize();
258  }
259  if (!status) break;
260 
261  double chisqnow = ComputeChiSq();
262  double deltachisq = chisqnow-_chisq;
263 
264  _chisq = chisqnow;
265  if (std::abs(deltachisq)<1e-3) {
266  break;
267  }
268  ++iter;
269  }
270 
271  return status;
272 
273 }
274 
275 bool PulseChiSqSNNLS::updateCov(const SampleMatrix &samplecov, const FullSampleMatrix &fullpulsecov) {
276 
277  const unsigned int nsample = SampleVector::RowsAtCompileTime;
278  const unsigned int npulse = _bxs.rows();
279 
280  _invcov = samplecov; //
281 
282  for (unsigned int ipulse=0; ipulse<npulse; ++ipulse) {
283  if (_ampvec.coeff(ipulse)==0.) continue;
284  int bx = _bxs.coeff(ipulse);
285  if (std::abs(bx)>=100) continue; //no contribution to covariance from pedestal or saturation/slew step correction
286 
287  int firstsamplet = std::max(0,bx + 3);
288  int offset = 7-3-bx;
289 
290  const double ampveccoef = _ampvec.coeff(ipulse);
291  const double ampsq = ampveccoef*ampveccoef;
292 
293  const unsigned int nsamplepulse = nsample-firstsamplet;
294  _invcov.block(firstsamplet,firstsamplet,nsamplepulse,nsamplepulse) +=
295  ampsq*fullpulsecov.block(firstsamplet+offset,firstsamplet+offset,nsamplepulse,nsamplepulse);
296  }
297 
298  _covdecomp.compute(_invcov);
299 
300  bool status = true;
301  return status;
302 
303 }
304 
306 
307 // SampleVector resvec = _pulsemat*_ampvec - _sampvec;
308 // return resvec.transpose()*_covdecomp.solve(resvec);
309 
310  return _covdecomp.matrixL().solve(_pulsemat*_ampvec - _sampvec).squaredNorm();
311 
312 }
313 
314 double PulseChiSqSNNLS::ComputeApproxUncertainty(unsigned int ipulse) {
315  //compute approximate uncertainties
316  //(using 1/second derivative since full Hessian is not meaningful in
317  //presence of positive amplitude boundaries.)
318 
319  return 1./_covdecomp.matrixL().solve(_pulsemat.col(ipulse)).norm();
320 
321 }
322 
324 
325  //Fast NNLS (fnnls) algorithm as per http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.157.9203&rep=rep1&type=pdf
326 
327  const unsigned int npulse = _bxs.rows();
328  constexpr unsigned int nsamples = SampleVector::RowsAtCompileTime;
329 
330  invcovp = _covdecomp.matrixL().solve(_pulsemat);
331  aTamat.noalias() = invcovp.transpose().lazyProduct(invcovp);
332  aTbvec.noalias() = invcovp.transpose().lazyProduct(_covdecomp.matrixL().solve(_sampvec));
333 
334  int iter = 0;
335  Index idxwmax = 0;
336  double wmax = 0.0;
337  double threshold = 1e-11;
338  while (true) {
339  //can only perform this step if solution is guaranteed viable
340  if (iter>0 || _nP==0) {
341  if ( _nP==std::min(npulse,nsamples) ) break;
342 
343  const unsigned int nActive = npulse - _nP;
344 
346  Index idxwmaxprev = idxwmax;
347  double wmaxprev = wmax;
348  wmax = updatework.tail(nActive).maxCoeff(&idxwmax);
349 
350  //convergence
351  if (wmax<threshold || (idxwmax==idxwmaxprev && wmax==wmaxprev)) break;
352 
353  //worst case protection
354  if (iter>=500) {
355  LogDebug("PulseChiSqSNNLS::NNLS()") << "Max Iterations reached at iter " << iter;
356  break;
357  }
358 
359  //unconstrain parameter
360  Index idxp = _nP + idxwmax;
362  }
363 
364 
365  while (true) {
366  //printf("iter in, idxsP = %i\n",int(_idxsP.size()));
367 
368  if (_nP==0) break;
369 
371 
372  //solve for unconstrained parameters
373  //need to have specialized function to call optimized versions
374  // of matrix solver... this is truly amazing...
376 
377  //check solution
378  bool positive = true;
379  for (unsigned int i = 0; i < _nP; ++i)
380  positive &= (ampvecpermtest(i) > 0);
381  if (positive) {
382  _ampvec.head(_nP) = ampvecpermtest.head(_nP);
383  break;
384  }
385 
386  //update parameter vector
387  Index minratioidx=0;
388 
389  // no realizable optimization here (because it autovectorizes!)
390  double minratio = std::numeric_limits<double>::max();
391  for (unsigned int ipulse=0; ipulse<_nP; ++ipulse) {
392  if (ampvecpermtest.coeff(ipulse)<=0.) {
393  const double c_ampvec = _ampvec.coeff(ipulse);
394  const double ratio = c_ampvec/(c_ampvec-ampvecpermtest.coeff(ipulse));
395  if (ratio<minratio) {
396  minratio = ratio;
397  minratioidx = ipulse;
398  }
399  }
400  }
401 
402  _ampvec.head(_nP) += minratio*(ampvecpermtest.head(_nP)- _ampvec.head(_nP));
403 
404  //avoid numerical problems with later ==0. check
405  _ampvec.coeffRef(minratioidx) = 0.;
406 
407  //printf("removing index %i, orig idx %i\n",int(minratioidx),int(_bxs.coeff(minratioidx)));
408  NNLSConstrainParameter(minratioidx);
409  }
410  ++iter;
411 
412  //adaptive convergence threshold to avoid infinite loops but still
413  //ensure best value is used
414  if (iter % 16 == 0) {
415  threshold *= 2;
416  }
417  }
418 
419  return true;
420 
421 
422 }
423 
425 
426  aTamat.col(_nP).swap(aTamat.col(idxp));
427  aTamat.row(_nP).swap(aTamat.row(idxp));
428  _pulsemat.col(_nP).swap(_pulsemat.col(idxp));
429  std::swap(aTbvec.coeffRef(_nP),aTbvec.coeffRef(idxp));
430  std::swap(_ampvec.coeffRef(_nP),_ampvec.coeffRef(idxp));
431  std::swap(_bxs.coeffRef(_nP),_bxs.coeffRef(idxp));
432  ++_nP;
433 }
434 
436  aTamat.col(_nP-1).swap(aTamat.col(minratioidx));
437  aTamat.row(_nP-1).swap(aTamat.row(minratioidx));
438  _pulsemat.col(_nP-1).swap(_pulsemat.col(minratioidx));
439  std::swap(aTbvec.coeffRef(_nP-1),aTbvec.coeffRef(minratioidx));
440  std::swap(_ampvec.coeffRef(_nP-1),_ampvec.coeffRef(minratioidx));
441  std::swap(_bxs.coeffRef(_nP-1),_bxs.coeffRef(minratioidx));
442  --_nP;
443 
444 }
445 
447 
448  //Fast NNLS (fnnls) algorithm as per http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.157.9203&rep=rep1&type=pdf
449 
450 // const unsigned int npulse = 1;
451 
452  invcovp = _covdecomp.matrixL().solve(_pulsemat);
453 // aTamat = invcovp.transpose()*invcovp;
454 // aTbvec = invcovp.transpose()*_covdecomp.matrixL().solve(_sampvec);
455 
456  SingleMatrix aTamatval = invcovp.transpose()*invcovp;
457  SingleVector aTbvecval = invcovp.transpose()*_covdecomp.matrixL().solve(_sampvec);
458  _ampvec.coeffRef(0) = std::max(0.,aTbvecval.coeff(0)/aTamatval.coeff(0));
459 
460  return true;
461 
462 }
#define LogDebug(id)
PulseMatrix aTamat
void NNLSUnconstrainParameter(Index idxp)
unsigned int _npulsetot
unsigned int _nP
PulseVector _ampvecmin
PulseVector aTbvec
PulseVector ampvecpermtest
bool DoFit(const SampleVector &samples, const SampleMatrix &samplecov, const BXVector &bxs, const FullSampleVector &fullpulse, const FullSampleMatrix &fullpulsecov, const SampleGainVector &gains=-1 *SampleGainVector::Ones(), const SampleGainVector &badSamples=SampleGainVector::Zero())
#define constexpr
SamplePulseMatrix _pulsemat
Eigen::Matrix< char, SampleVectorSize, 1 > SampleGainVector
Eigen::Matrix< double, FullSampleVectorSize, 1 > FullSampleVector
double ComputeApproxUncertainty(unsigned int ipulse)
void swap(edm::DataFrameContainer &lhs, edm::DataFrameContainer &rhs)
T sqrt(T t)
Definition: SSEVec.h:18
Eigen::Matrix< double, 1, 1 > SingleVector
SampleDecompLLT _covdecomp
Abs< T >::type abs(const T &t)
Definition: Abs.h:22
T min(T a, T b)
Definition: MathUtil.h:58
bool updateCov(const SampleMatrix &samplecov, const FullSampleMatrix &fullpulsecov)
bool Minimize(const SampleMatrix &samplecov, const FullSampleMatrix &fullpulsecov)
Eigen::Matrix< double, SampleVectorSize, 1 > SampleVector
PulseVector updatework
SampleVector _sampvec
Eigen::Matrix< double, FullSampleVectorSize, FullSampleVectorSize > FullSampleMatrix
void resize(int bx, unsigned size)
Eigen::Matrix< double, SampleVectorSize, SampleVectorSize > SampleMatrix
Eigen::Matrix< double, Eigen::Dynamic, 1, 0, PulseVectorSize, 1 > PulseVector
SampleMatrix _invcov
#define ngains
void eigen_solve_submatrix(PulseMatrix &mat, PulseVector &invec, PulseVector &outvec, unsigned NP)
PulseVector _errvec
BXVector::Index Index
step
Eigen::Matrix< double, 1, 1 > SingleMatrix
void NNLSConstrainParameter(Index minratioidx)
SamplePulseMatrix invcovp
PulseVector _ampvec
Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, 0, PulseVectorSize, PulseVectorSize > PulseMatrix