Chemical Data Processing Library C++ API - Version 1.4.0
MLRModel.hpp
Go to the documentation of this file.
1 /*
2  * MLRModel.hpp
3  *
4  * This file is part of the Chemical Data Processing Toolkit
5  *
6  * Copyright (C) 2003 Thomas Seidel <thomas.seidel@univie.ac.at>
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this library; see the file COPYING. If not, write to
20  * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23 
29 #ifndef CDPL_MATH_MLRMODEL_HPP
30 #define CDPL_MATH_MLRMODEL_HPP
31 
32 #include <limits>
33 
34 #include "CDPL/Math/Vector.hpp"
35 #include "CDPL/Math/Matrix.hpp"
36 #include "CDPL/Math/CommonType.hpp"
37 #include "CDPL/Math/TypeTraits.hpp"
40 #include "CDPL/Base/Exceptions.hpp"
41 
42 
43 namespace CDPL
44 {
45 
46  namespace Math
47  {
48 
78  template <typename T = double>
79  class MLRModel
80  {
81 
82  public:
90  typedef T ValueType;
99 
104  chiSquare(0), Q(0), r(0), stdDeviation(0) {}
105 
111  void resizeDataSet(SizeType num_points, SizeType num_vars);
112 
118  void clearDataSet();
119 
133  template <typename V>
134  void setXYData(SizeType i, const VectorExpression<V>& x_vars, ValueType y);
135 
150  template <typename V>
151  void addXYData(const VectorExpression<V>& x_vars, ValueType y);
152 
159 
165  const MatrixType& getXMatrix() const;
166 
173 
179  const VectorType& getYValues() const;
180 
187  void buildModel();
188 
197  template <typename V>
199 
211  template <typename V>
213 
219  const VectorType& getCoefficients() const;
220 
233  ValueType getChiSquare() const;
234 
250  ValueType getGoodnessOfFit() const;
251 
274 
288 
297  void calcStatistics();
298 
299  private:
300  MatrixType xMatrix;
301  VectorType yValues;
302  VectorType calcYValues;
303  VectorType coefficients;
304  MatrixType svdU;
305  MatrixType svdV;
306  VectorType svdW;
307  ValueType chiSquare;
308  ValueType Q;
309  ValueType r;
310  ValueType stdDeviation;
311  };
312  } // namespace Math
313 } // namespace CDPL
314 
315 
316 // Implementation
317 
318 template <typename T>
320 {
321  if (num_points == xMatrix.getSize1() && num_vars == xMatrix.getSize2())
322  return;
323 
324  xMatrix.resize(num_points, num_vars, true, ValueType());
325  yValues.resize(num_points, ValueType());
326 }
327 
328 template <typename T>
330 {
331  yValues.resize(0);
332  xMatrix.resize(0, 0, false);
333 }
334 
335 template <typename T>
336 template <typename V>
338 {
339  SizeType x_mtx_size1 = xMatrix.getSize1();
340  SizeType x_mtx_size2 = xMatrix.getSize2();
341  SizeType x_vars_size = x_vars().getSize();
342  SizeType y_vals_size = yValues.getSize();
343 
344  resizeDataSet(std::max(i + 1, std::max(x_mtx_size1, y_vals_size)), std::max(x_vars_size, x_mtx_size2));
345 
346  for (SizeType j = 0; j < x_vars_size; j++)
347  xMatrix(i, j) = x_vars()(j);
348 
349  if (x_vars_size < x_mtx_size2)
350  for (SizeType j = x_vars_size; j < x_mtx_size2; j++)
351  xMatrix(i, j) = ValueType();
352 
353  yValues(i) = y;
354 }
355 
356 template <typename T>
357 template <typename V>
359 {
360  SizeType i = xMatrix.getSize1();
361  SizeType x_mtx_size2 = xMatrix.getSize2();
362  SizeType x_vars_size = x_vars().getSize();
363 
364  resizeDataSet(i + 1, std::max(x_mtx_size2, x_vars_size));
365 
366  for (SizeType j = 0; j < x_vars_size; j++)
367  xMatrix(i, j) = x_vars()(j);
368 
369  if (x_vars_size < x_mtx_size2)
370  for (SizeType j = x_vars_size; j < x_mtx_size2; j++)
371  xMatrix(i, j) = ValueType();
372 
373  yValues(i) = y;
374 }
375 
376 template <typename T>
379 {
380  return xMatrix;
381 }
382 
383 template <typename T>
386 {
387  return xMatrix;
388 }
389 
390 template <typename T>
393 {
394  return yValues;
395 }
396 
397 template <typename T>
400 {
401  return yValues;
402 }
403 
404 template <typename T>
406 {
407  static const ValueType TOLERANCE(1.0e-6);
408 
409  SizeType n = xMatrix.getSize1();
410  SizeType m = xMatrix.getSize2();
411 
412  if (m == 0 || n == 0)
413  throw Base::CalculationFailed("MLRModel: empty data set");
414 
415  if (n != SizeType(yValues.getSize()))
416  resizeDataSet(std::max(SizeType(yValues.getSize()), n), m);
417 
418  svdU.resize(n, m, false);
419  svdV.resize(m, m, false);
420  svdW.resize(m, false);
421 
422  svdU = xMatrix;
423 
424  if (!svDecompose(svdU, svdW, svdV))
425  throw Base::CalculationFailed("MLRModel: singular value decomposition failed");
426 
427  ValueType w_max = svdW(0);
428 
429  for (SizeType i = 1; i < m; i++)
430  if (svdW(i) > w_max)
431  w_max = svdW(i);
432 
433  ValueType tresh = TOLERANCE * w_max;
434 
435  for (SizeType i = 0; i < m; i++)
436  if (svdW(i) < tresh)
437  svdW(i) = 0;
438 
439  coefficients.resize(m, false);
440 
441  svSubstitute(svdU, svdW, svdV, yValues, coefficients);
442 }
443 
444 template <typename T>
445 template <typename V>
448 {
449  if (SizeType(x().getSize()) != SizeType(coefficients.getSize()))
450  throw Base::CalculationFailed("MLRModel: number of regression coefficients does not match number of independent variables");
451 
452  return innerProd(coefficients, x);
453 }
454 
455 template <typename T>
456 template <typename V>
459 {
460  return calcYValue(x);
461 }
462 
463 template <typename T>
466 {
467  return coefficients;
468 }
469 
470 template <typename T>
473 {
474  return chiSquare;
475 }
476 
477 template <typename T>
480 {
481  return Q;
482 }
483 
484 template <typename T>
487 {
488  return r;
489 }
490 
491 template <typename T>
494 {
495  return stdDeviation;
496 }
497 
498 template <typename T>
500 {
501  ValueType mean_data_y = 0;
502  ValueType mean_calc_y = 0;
503 
504  chiSquare = ValueType();
505 
506  SizeType m = xMatrix.getSize2();
507  SizeType n = xMatrix.getSize1();
508 
509  if (m != SizeType(coefficients.getSize()))
510  throw Base::CalculationFailed("MLRModel: number of independent variables does not match number of regression coefficients");
511 
512  if (n != SizeType(yValues.getSize()))
513  throw Base::CalculationFailed("MLRModel: number of dependent variables does not match number of vectors with independent variables");
514 
515  calcYValues.resize(n);
516 
517  for (SizeType i = 0; i < n; i++) {
518  ValueType data_y = yValues(i);
519  ValueType calc_y = innerProd(row(xMatrix, i), coefficients);
520  ValueType y_diff = data_y - calc_y;
521 
522  mean_data_y += data_y;
523  mean_calc_y += calc_y;
524  chiSquare += y_diff * y_diff;
525 
526  calcYValues(i) = calc_y;
527  }
528 
529  mean_data_y /= n;
530  mean_calc_y /= n;
531 
532  ValueType sxx = ValueType();
533  ValueType syy = ValueType();
534  ValueType sxy = ValueType();
535 
536  for (SizeType i = 0; i < n; i++) {
537  ValueType xt = yValues(i) - mean_data_y;
538  ValueType yt = calcYValues(i) - mean_calc_y;
539 
540  sxx += xt * xt;
541  syy += yt * yt;
542  sxy += xt * yt;
543  }
544 
545  r = sxy / (TypeTraits<ValueType>::sqrt(sxx * syy) + std::numeric_limits<ValueType>::epsilon());
546 
547  stdDeviation = TypeTraits<ValueType>::sqrt(chiSquare / (n - m));
548 
549  Q = gammaQ(ValueType(n - 2) / 2, chiSquare / 2);
550 }
551 
552 #endif // CDPL_MATH_MLRMODEL_HPP
Definition of exception classes.
Common type deduction.
Definition of matrix data types.
Implementation of matrix singular value decomposition and associated operations.
Provides miscellaneous special mathematical functions.
Definition of type traits.
Definition of vector data types.
Thrown to indicate that some requested calculation has failed.
Definition: Base/Exceptions.hpp:230
Performs Multiple Linear Regression [WLIREG] on a set of data points .
Definition: MLRModel.hpp:80
ValueType operator()(const VectorExpression< V > &x_vars) const
Predicts the value of the dependent variable for a vector of independent variables given by x_vars.
ValueType getCorrelationCoefficient() const
Returns the correlation coefficient .
Definition: MLRModel.hpp:486
MLRModel()
Constructs and initializes a regression model with an empty data set.
Definition: MLRModel.hpp:103
const VectorType & getCoefficients() const
Returns a read-only vector containing the estimated regression coefficients which were calculated by...
Definition: MLRModel.hpp:465
void resizeDataSet(SizeType num_points, SizeType num_vars)
Resizes the data set to hold num_points data points with num_vars independent variables.
Definition: MLRModel.hpp:319
ValueType getGoodnessOfFit() const
Returns the goodness of fit .
Definition: MLRModel.hpp:479
CommonType< typename Vector< T >::SizeType, typename Matrix< T >::SizeType >::Type SizeType
An unsigned integral type used to represent sizes and indices.
Definition: MLRModel.hpp:86
void buildModel()
Performs linear least squares regression modeling of the set of currently stored data points .
Definition: MLRModel.hpp:405
ValueType getStandardDeviation() const
Returns the standard deviation of the residuals .
Definition: MLRModel.hpp:493
void setXYData(SizeType i, const VectorExpression< V > &x_vars, ValueType y)
Sets the i-th data point of the data set.
Definition: MLRModel.hpp:337
Vector< T > VectorType
The vector type used for the storage of response values and regression coefficients.
Definition: MLRModel.hpp:98
void calcStatistics()
Calculates various statistical parameters describing the built regression model.
Definition: MLRModel.hpp:499
void clearDataSet()
Clears the data set.
Definition: MLRModel.hpp:329
VectorType & getYValues()
Returns a vector containing the dependent variables of the currently stored data points .
Definition: MLRModel.hpp:392
T ValueType
The value type used in calculations and for the storage of data points.
Definition: MLRModel.hpp:90
ValueType calcYValue(const VectorExpression< V > &x_vars) const
Predicts the value of the dependent variable for a vector of independent variables given by x_vars.
ValueType getChiSquare() const
Returns the sum of squared residuals .
Definition: MLRModel.hpp:472
MatrixType & getXMatrix()
Returns a matrix where each row represents the vector with independent variables of the currently st...
Definition: MLRModel.hpp:378
Matrix< T > MatrixType
The matrix type used for the storage of the regression input data.
Definition: MLRModel.hpp:94
void addXYData(const VectorExpression< V > &x_vars, ValueType y)
Adds a new data point to the current data set.
Definition: MLRModel.hpp:358
Dynamically-sized dense row-major matrix with configurable underlying storage.
Definition: Matrix.hpp:510
A::size_type SizeType
The unsigned size type used by the underlying storage container.
Definition: Matrix.hpp:533
CRTP base class of all vector expression types.
Definition: Expression.hpp:68
Dynamically-sized dense vector with configurable underlying storage.
Definition: Vector.hpp:480
constexpr unsigned int T
Specifies Hydrogen (Tritium).
Definition: AtomType.hpp:67
constexpr unsigned int Q
Generic type that covers any element except hydrogen and carbon.
Definition: AtomType.hpp:647
constexpr unsigned int r
Specifies that the stereocenter has r configuration.
Definition: CIPDescriptor.hpp:76
constexpr unsigned int m
Specifies that the stereocenter has m configuration.
Definition: CIPDescriptor.hpp:116
VectorInnerProduct< E1, E2 >::ResultType innerProd(const VectorExpression< E1 > &e1, const VectorExpression< E2 > &e2)
Returns the inner (dot) product of the vector expressions e1 and e2.
Definition: VectorExpression.hpp:1033
MatrixRow< M > row(MatrixExpression< M > &e, typename MatrixRow< M >::SizeType i)
Returns a mutable row proxy for row i of the matrix expression e.
Definition: MatrixProxy.hpp:1372
void svSubstitute(const MatrixExpression< U > &u, const VectorExpression< W > &w, const MatrixExpression< V > &v, const VectorExpression< B > &b, VectorExpression< X > &x)
Solves for a vector where is given by its Singular Value Decomposition [WSVD].
Definition: SVDecomposition.hpp:466
bool svDecompose(MatrixExpression< A > &a, VectorExpression< W > &w, MatrixExpression< V > &v, std::size_t max_iter=0)
Computes the Singular Value Decomposition [WSVD] of a -dimensional matrix a.
Definition: SVDecomposition.hpp:70
T gammaQ(const T &a, const T &x)
Computes the incomplete gamma function (see [NRIC] for details).
CDPL_PHARM_API const Base::LookupKey TOLERANCE
Specifies the positional tolerance of the feature.
The namespace of the Chemical Data Processing Library.
Trait that resolves the common arithmetic type of T1 and T2 via std::common_type.
Definition: CommonType.hpp:46
Primary traits template for scalar arithmetic value types.
Definition: TypeTraits.hpp:307