public static void CalculatePRESS( IROMatrix <double> yLoads, IROMatrix <double> xScores, int numberOfFactors, out IROVector <double> press) { int numMeasurements = yLoads.RowCount; IExtensibleVector <double> PRESS = VectorMath.CreateExtensibleVector <double>(numberOfFactors + 1); var UtY = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(yLoads.RowCount, yLoads.ColumnCount); var predictedY = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(yLoads.RowCount, yLoads.ColumnCount); press = PRESS; MatrixMath.MultiplyFirstTransposed(xScores, yLoads, UtY); // now calculate PRESS by predicting the y // using yp = U (w*(1/w)) U' y // of course w*1/w is the identity matrix, but we use only the first factors, so using a cutted identity matrix // we precalculate the last term U'y = UtY // and multiplying with one row of U in every factor step, summing up the predictedY PRESS[0] = MatrixMath.SumOfSquares(yLoads); for (int nf = 0; nf < numberOfFactors; nf++) { for (int cn = 0; cn < yLoads.ColumnCount; cn++) { for (int k = 0; k < yLoads.RowCount; k++) { predictedY[k, cn] += xScores[k, nf] * UtY[nf, cn]; } } PRESS[nf + 1] = MatrixMath.SumOfSquaredDifferences(yLoads, predictedY); } }
/// <summary> /// Fits a data set linear to a given function base. /// </summary> /// <param name="xarr">The array of x values of the data set.</param> /// <param name="yarr">The array of y values of the data set.</param> /// <param name="stddev">The array of y standard deviations of the data set. Can be null if the standard deviation is unkown.</param> /// <param name="numberOfData">The number of data points (may be smaller than the array sizes of the data arrays).</param> /// <param name="numberOfParameter">The number of parameters to fit == size of the function base.</param> /// <param name="evaluateFunctionBase">The function base used to fit.</param> /// <param name="threshold">A treshold value (usually 1E-5) used to chop the unimportant singular values away.</param> public LinearFitBySvd( double[] xarr, double[] yarr, double[] stddev, int numberOfData, int numberOfParameter, FunctionBaseEvaluator evaluateFunctionBase, double threshold) { var u = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(numberOfData, numberOfParameter); double[] functionBase = new double[numberOfParameter]; // Fill the function base matrix (rows: numberOfData, columns: numberOfParameter) // and scale also y for (int i = 0; i < numberOfData; i++) { evaluateFunctionBase(xarr[i], functionBase); for (int j = 0; j < numberOfParameter; j++) { u[i, j] = functionBase[j]; } } Calculate( u, VectorMath.ToROVector(yarr), VectorMath.ToROVector(stddev), numberOfData, numberOfParameter, threshold); }
public static void GetSpectralResiduals( IROMatrix <double> matrixX, IROMatrix <double> xLoads, IROMatrix <double> yLoads, IROMatrix <double> xScores, IReadOnlyList <double> crossProduct, int numberOfFactors, IMatrix <double> spectralResiduals) { int numX = xLoads.ColumnCount; int numY = yLoads.ColumnCount; int numM = yLoads.RowCount; var reconstructedSpectra = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(matrixX.RowCount, matrixX.ColumnCount); MatrixMath.ZeroMatrix(reconstructedSpectra); for (int nf = 0; nf < numberOfFactors; nf++) { double scale = crossProduct[nf]; for (int m = 0; m < numM; m++) { for (int k = 0; k < numX; k++) { reconstructedSpectra[m, k] += scale * xScores[m, nf] * xLoads[nf, k]; } } } for (int m = 0; m < numM; m++) { spectralResiduals[m, 0] = MatrixMath.SumOfSquaredDifferences( MatrixMath.ToROSubMatrix(matrixX, m, 0, 1, matrixX.ColumnCount), MatrixMath.ToROSubMatrix(reconstructedSpectra, m, 0, 1, matrixX.ColumnCount)); } }
/// <summary> /// Creates an analyis from preprocessed spectra and preprocessed concentrations. /// </summary> /// <param name="matrixX">The spectral matrix (each spectrum is a row in the matrix). They must at least be centered.</param> /// <param name="matrixY">The matrix of concentrations (each experiment is a row in the matrix). They must at least be centered.</param> /// <param name="maxFactors">Maximum number of factors for analysis.</param> /// <returns>A regression object, which holds all the loads and weights neccessary for further calculations.</returns> protected override void AnalyzeFromPreprocessedWithoutReset(IROMatrix <double> matrixX, IROMatrix <double> matrixY, int maxFactors) { int numberOfFactors = _calib.NumberOfFactors = Math.Min(matrixX.ColumnCount, maxFactors); IMatrix <double> helperY = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(matrixY.RowCount, 1); _PRESS = null; for (int i = 0; i < matrixY.ColumnCount; i++) { MatrixMath.Submatrix(matrixY, helperY, 0, i); var r = PLS2Regression.CreateFromPreprocessed(matrixX, helperY, maxFactors); IPLS2CalibrationModel cal = r.CalibrationModel; _calib.NumberOfFactors = Math.Min(_calib.NumberOfFactors, cal.NumberOfFactors); _calib.XLoads[i] = cal.XLoads; _calib.YLoads[i] = cal.YLoads; _calib.XWeights[i] = cal.XWeights; _calib.CrossProduct[i] = cal.CrossProduct; if (_PRESS == null) { _PRESS = VectorMath.CreateExtensibleVector <double>(r.PRESS.Length); } VectorMath.Add(_PRESS, r.PRESS, _PRESS); } }
public static void GetPredictionScoreMatrix( IROMatrix <double> xLoads, IROMatrix <double> yLoads, IROMatrix <double> xScores, IReadOnlyList <double> crossProduct, int numberOfFactors, IMatrix <double> predictionScores) { int numX = xLoads.ColumnCount; int numY = yLoads.ColumnCount; int numM = yLoads.RowCount; var UtY = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(xScores.ColumnCount, yLoads.ColumnCount); MatrixMath.MultiplyFirstTransposed(xScores, yLoads, UtY); MatrixMath.ZeroMatrix(predictionScores); for (int nf = 0; nf < numberOfFactors; nf++) { double scale = 1 / crossProduct[nf]; for (int cn = 0; cn < numY; cn++) { for (int k = 0; k < numX; k++) { predictionScores[k, cn] += scale * xLoads[nf, k] * UtY[nf, cn]; } } } }
/// <summary> /// Calculates the prediction scores (for use withthe preprocessed spectra). /// </summary> /// <param name="numFactors">Number of factors used to calculate the prediction scores.</param> /// <param name="predictionScores">Supplied matrix for holding the prediction scores.</param> protected override void InternalGetPredictionScores(int numFactors, IMatrix <double> predictionScores) { IMatrix <double> pred = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(predictionScores.RowCount, 1); for (int i = 0; i < _calib.NumberOfY; i++) { PLS2Regression.GetPredictionScoreMatrix(_calib.XLoads[i], _calib.YLoads[i], _calib.XWeights[i], _calib.CrossProduct[i], numFactors, pred); MatrixMath.SetColumn(pred, predictionScores, i); } }
public CrossValidationResult(int numberOfPoints, int numberOfY, int numberOfFactors, bool multipleSpectralResiduals) { _predictedY = new IMatrix <double> [numberOfFactors + 1]; _spectralResidual = new IMatrix <double> [numberOfFactors + 1]; _crossPRESS = VectorMath.CreateExtensibleVector <double>(numberOfFactors + 1); for (int i = 0; i <= numberOfFactors; i++) { _predictedY[i] = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(numberOfPoints, numberOfY); _spectralResidual[i] = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(numberOfPoints, multipleSpectralResiduals ? numberOfY : 1); } }
/// <summary> /// Creates an analyis from preprocessed spectra and preprocessed concentrations. /// </summary> /// <param name="matrixX">The spectral matrix (each spectrum is a row in the matrix). They must at least be centered.</param> /// <param name="matrixY">The matrix of concentrations (each experiment is a row in the matrix). They must at least be centered.</param> /// <param name="maxFactors">Maximum number of factors for analysis.</param> /// <returns>A regression object, which holds all the loads and weights neccessary for further calculations.</returns> protected override void AnalyzeFromPreprocessedWithoutReset(IROMatrix <double> matrixX, IROMatrix <double> matrixY, int maxFactors) { int numFactors = Math.Min(matrixX.ColumnCount, maxFactors); ExecuteAnalysis(matrixX, matrixY, ref numFactors, out var xLoads, out var xScores, out var V); var yLoads = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(matrixY.RowCount, matrixY.ColumnCount); MatrixMath.Copy(matrixY, yLoads); _calib.NumberOfFactors = numFactors; _calib.XLoads = xLoads; _calib.YLoads = yLoads; _calib.XScores = xScores; _calib.CrossProduct = V; }
public static void CalculateXLeverageFromPreprocessed( IROMatrix <double> xScores, int numberOfFactors, IMatrix <double> leverage) { var subscores = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(xScores.RowCount, numberOfFactors); MatrixMath.Submatrix(xScores, subscores); var decompose = new MatrixMath.SingularValueDecomposition(subscores); for (int i = 0; i < xScores.RowCount; i++) { leverage[i, 0] = decompose.HatDiagonal[i]; } }
/// <summary> /// Creates an analyis from preprocessed spectra and preprocessed concentrations. /// </summary> /// <param name="matrixX">The spectral matrix (each spectrum is a row in the matrix). They must at least be centered.</param> /// <param name="matrixY">The matrix of concentrations (each experiment is a row in the matrix). They must at least be centered.</param> /// <param name="maxFactors">Maximum number of factors for analysis.</param> /// <returns>A regression object, which holds all the loads and weights neccessary for further calculations.</returns> protected override void AnalyzeFromPreprocessedWithoutReset(IROMatrix <double> matrixX, IROMatrix <double> matrixY, int maxFactors) { int numberOfFactors = _calib.NumberOfFactors = Math.Min(matrixX.ColumnCount, maxFactors); var _xLoads = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(0, 0); var _yLoads = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(0, 0); var _W = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(0, 0); var _V = new MatrixMath.TopSpineJaggedArrayMatrix <double>(0, 0); _PRESS = VectorMath.CreateExtensibleVector <double>(0); ExecuteAnalysis(matrixX, matrixY, ref numberOfFactors, _xLoads, _yLoads, _W, _V, _PRESS); _calib.NumberOfFactors = Math.Min(_calib.NumberOfFactors, numberOfFactors); _calib.XLoads = _xLoads; _calib.YLoads = _yLoads; _calib.XWeights = _W; _calib.CrossProduct = _V; }
public static void ExecuteAnalysis( IROMatrix <double> X, // matrix of spectra (a spectra is a row of this matrix) IROMatrix <double> Y, // matrix of concentrations (a mixture is a row of this matrix) ref int numFactors, out IROMatrix <double> xLoads, // out: the loads of the X matrix out IROMatrix <double> xScores, // matrix of weighting values out IROVector <double> V // vector of cross products ) { var matrixX = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(X.RowCount, X.ColumnCount); MatrixMath.Copy(X, matrixX); var decompose = new MatrixMath.SingularValueDecomposition(matrixX); numFactors = Math.Min(numFactors, matrixX.ColumnCount); numFactors = Math.Min(numFactors, matrixX.RowCount); xLoads = JaggedArrayMath.ToTransposedROMatrix(decompose.V, Y.RowCount, X.ColumnCount); xScores = JaggedArrayMath.ToMatrix(decompose.U, Y.RowCount, Y.RowCount); V = VectorMath.ToROVector(decompose.Diagonal, numFactors); }
private static void CalculatePRESS( IROMatrix <double> Y, // matrix of concentrations (a mixture is a row of this matrix) IROMatrix <double> xLoads, // out: the loads of the X matrix IROMatrix <double> xScores, // matrix of weighting values IReadOnlyList <double> V, // vector of cross products int maxNumberOfFactors, IVector <double> PRESS //vector of Y PRESS values ) { var U = xScores; var UtY = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(Y.RowCount, Y.ColumnCount); MatrixMath.MultiplyFirstTransposed(U, Y, UtY); var predictedY = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(Y.RowCount, Y.ColumnCount); var subU = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(Y.RowCount, 1); var subY = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(Y.RowCount, Y.ColumnCount); PRESS[0] = MatrixMath.SumOfSquares(Y); int numFactors = Math.Min(maxNumberOfFactors, V.Count); // now calculate PRESS by predicting the y // using yp = U (w*(1/w)) U' y // of course w*1/w is the identity matrix, but we use only the first factors, so using a cutted identity matrix // we precalculate the last term U'y = UtY // and multiplying with one row of U in every factor step, summing up the predictedY for (int nf = 0; nf < numFactors; nf++) { for (int cn = 0; cn < Y.ColumnCount; cn++) { for (int k = 0; k < Y.RowCount; k++) { predictedY[k, cn] += U[k, nf] * UtY[nf, cn]; } } PRESS[nf + 1] = MatrixMath.SumOfSquaredDifferences(Y, predictedY); } }
} // end partial-least-squares-predict public static void CalculateXLeverageFromPreprocessed( IROMatrix <double> matrixX, IROMatrix <double> W, // weighting matrix int numFactors, // number of factors to use for prediction IMatrix <double> leverage, // Matrix of predicted y-values, must be same number of rows as spectra int leverageColumn ) { // get the score matrix var weights = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(numFactors, W.ColumnCount); MatrixMath.Submatrix(W, weights, 0, 0); var scoresMatrix = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(matrixX.RowCount, weights.RowCount); MatrixMath.MultiplySecondTransposed(matrixX, weights, scoresMatrix); MatrixMath.SingularValueDecomposition decomposition = MatrixMath.GetSingularValueDecomposition(scoresMatrix); for (int i = 0; i < matrixX.RowCount; i++) { leverage[i, leverageColumn] = decomposition.HatDiagonal[i]; } }
public static void Predict( IROMatrix <double> matrixX, IROMatrix <double> xLoads, IROMatrix <double> yLoads, IROMatrix <double> xScores, IReadOnlyList <double> crossProduct, int numberOfFactors, IMatrix <double> predictedY, IMatrix <double> spectralResiduals) { int numX = xLoads.ColumnCount; int numY = yLoads.ColumnCount; int numM = yLoads.RowCount; var predictionScores = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(numX, numY); GetPredictionScoreMatrix(xLoads, yLoads, xScores, crossProduct, numberOfFactors, predictionScores); MatrixMath.Multiply(matrixX, predictionScores, predictedY); if (null != spectralResiduals) { GetSpectralResiduals(matrixX, xLoads, yLoads, xScores, crossProduct, numberOfFactors, spectralResiduals); } }
/// <summary> /// Partial least squares (PLS) decomposition of the matrizes X and Y. /// </summary> /// <param name="_X">The X ("spectrum") matrix, centered and preprocessed.</param> /// <param name="_Y">The Y ("concentration") matrix (centered).</param> /// <param name="numFactors">Number of factors to calculate.</param> /// <param name="xLoads">Returns the matrix of eigenvectors of X. Should be initially empty.</param> /// <param name="yLoads">Returns the matrix of eigenvectors of Y. Should be initially empty. </param> /// <param name="W">Returns the matrix of weighting values. Should be initially empty.</param> /// <param name="V">Returns the vector of cross products. Should be initially empty.</param> /// <param name="PRESS">If not null, the PRESS value of each factor is stored (vertically) here. </param> public static void ExecuteAnalysis( IROMatrix <double> _X, // matrix of spectra (a spectra is a row of this matrix) IROMatrix <double> _Y, // matrix of concentrations (a mixture is a row of this matrix) ref int numFactors, IBottomExtensibleMatrix <double> xLoads, // out: the loads of the X matrix IBottomExtensibleMatrix <double> yLoads, // out: the loads of the Y matrix IBottomExtensibleMatrix <double> W, // matrix of weighting values IRightExtensibleMatrix <double> V, // matrix of cross products IExtensibleVector <double> PRESS //vector of Y PRESS values ) { // used variables: // n: number of spectra (number of tests, number of experiments) // p: number of slots (frequencies, ..) in each spectrum // m: number of constitutents (number of y values in each measurement) // X : n-p matrix of spectra (each spectra is a horizontal row) // Y : n-m matrix of concentrations const int maxIterations = 1500; // max number of iterations in one factorization step const double accuracy = 1E-12; // accuracy that should be reached between subsequent calculations of the u-vector // use the mean spectrum as first row of the W matrix var mean = new MatrixMath.MatrixWithOneRow <double>(_X.ColumnCount); // MatrixMath.ColumnsToZeroMean(X,mean); //W.AppendBottom(mean); var X = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(_X.RowCount, _X.ColumnCount); MatrixMath.Copy(_X, X); var Y = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(_Y.RowCount, _Y.ColumnCount); MatrixMath.Copy(_Y, Y); IMatrix <double> u_prev = null; var w = new MatrixMath.MatrixWithOneRow <double>(X.ColumnCount); // horizontal vector of X (spectral) weighting var t = new MatrixMath.MatrixWithOneColumn <double>(X.RowCount); // vertical vector of X scores var u = new MatrixMath.MatrixWithOneColumn <double>(X.RowCount); // vertical vector of Y scores var p = new MatrixMath.MatrixWithOneRow <double>(X.ColumnCount); // horizontal vector of X loads var q = new MatrixMath.MatrixWithOneRow <double>(Y.ColumnCount); // horizontal vector of Y loads int maxFactors = Math.Min(X.ColumnCount, X.RowCount); numFactors = numFactors <= 0 ? maxFactors : Math.Min(numFactors, maxFactors); if (PRESS != null) { PRESS.Append(new MatrixMath.ScalarAsMatrix <double>(MatrixMath.SumOfSquares(Y))); // Press value for not decomposed Y } for (int nFactor = 0; nFactor < numFactors; nFactor++) { //Console.WriteLine("Factor_{0}:",nFactor); //Console.WriteLine("X:"+X.ToString()); //Console.WriteLine("Y:"+Y.ToString()); // 1. Use as start vector for the y score the first column of the // y-matrix MatrixMath.Submatrix(Y, u); // u is now a vertical vector of concentrations of the first constituents for (int iter = 0; iter < maxIterations; iter++) { // 2. Calculate the X (spectrum) weighting vector MatrixMath.MultiplyFirstTransposed(u, X, w); // w is a horizontal vector // 3. Normalize w to unit length MatrixMath.NormalizeRows(w); // w now has unit length // 4. Calculate X (spectral) scores MatrixMath.MultiplySecondTransposed(X, w, t); // t is a vertical vector of n numbers // 5. Calculate the Y (concentration) loading vector MatrixMath.MultiplyFirstTransposed(t, Y, q); // q is a horizontal vector of m (number of constitutents) // 5.1 Normalize q to unit length MatrixMath.NormalizeRows(q); // 6. Calculate the Y (concentration) score vector u MatrixMath.MultiplySecondTransposed(Y, q, u); // u is a vertical vector of n numbers // 6.1 Compare // Compare this with the previous one if (u_prev != null && MatrixMath.IsEqual(u_prev, u, accuracy)) { break; } if (u_prev == null) { u_prev = new MatrixMath.MatrixWithOneColumn <double>(X.RowCount); } MatrixMath.Copy(u, u_prev); // stores the content of u in u_prev } // for all iterations // Store the scores of X //factors.AppendRight(t); // 7. Calculate the inner scalar (cross product) double length_of_t = MatrixMath.LengthOf(t); var v = new MatrixMath.ScalarAsMatrix <double>(0); MatrixMath.MultiplyFirstTransposed(u, t, (IVector <double>)v); if (length_of_t != 0) { v = v / MatrixMath.Square(length_of_t); } // 8. Calculate the new loads for the X (spectral) matrix MatrixMath.MultiplyFirstTransposed(t, X, p); // p is a horizontal vector of loads // Normalize p by the spectral scores if (length_of_t != 0) { MatrixMath.MultiplyScalar(p, 1 / MatrixMath.Square(length_of_t), p); } // 9. Calculate the new residua for the X (spectral) and Y (concentration) matrix //MatrixMath.MultiplyScalar(t,length_of_t*v,t); // original t times the cross product MatrixMath.SubtractProductFromSelf(t, p, X); MatrixMath.MultiplyScalar(t, v, t); // original t times the cross product MatrixMath.SubtractProductFromSelf(t, q, Y); // to calculate residual Y // Store the loads of X and Y in the output result matrix xLoads.AppendBottom(p); yLoads.AppendBottom(q); W.AppendBottom(w); V.AppendRight(v); if (PRESS != null) { double pressValue = MatrixMath.SumOfSquares(Y); PRESS.Append(new MatrixMath.ScalarAsMatrix <double>(pressValue)); } // Calculate SEPcv. If SEPcv is greater than for the actual number of factors, // break since the optimal number of factors was found. If not, repeat the calculations // with the residual matrizes for the next factor. } // for all factors }
/// <summary> /// Fits a data set linear to a given x base. /// </summary> /// <param name="xbase">The matrix of x values of the data set. Dimensions: numberOfData x numberOfParameters. The matrix is changed during calculation!</param> /// <param name="yarr">The array of y values of the data set.</param> /// <param name="stddev">The array of y standard deviations of the data set. Can be null if the standard deviation is unkown.</param> /// <param name="numberOfData">The number of data points (may be smaller than the array sizes of the data arrays).</param> /// <param name="numberOfParameter">The number of parameters to fit == size of the function base.</param> /// <param name="threshold">A treshold value (usually 1E-5) used to chop the unimportant singular values away.</param> public LinearFitBySvd Calculate( IROMatrix <double> xbase, // NumberOfData, NumberOfParameters IReadOnlyList <double> yarr, IReadOnlyList <double> stddev, int numberOfData, int numberOfParameter, double threshold) { _numberOfParameter = numberOfParameter; _numberOfFreeParameter = numberOfParameter; _numberOfData = numberOfData; _parameter = new double[numberOfParameter]; _residual = new double[numberOfData]; _predicted = new double[numberOfData]; _reducedPredictionVariance = new double[numberOfData]; double[] scaledY = new double[numberOfData]; // Calculated some useful values _yMean = Mean(yarr, 0, _numberOfData); _yCorrectedSumOfSquares = CorrectedSumOfSquares(yarr, _yMean, 0, _numberOfData); var u = new MatrixMath.LeftSpineJaggedArrayMatrix <double>(numberOfData, numberOfParameter); // Fill the function base matrix (rows: numberOfData, columns: numberOfParameter) // and scale also y if (null == stddev) { for (int i = 0; i < numberOfData; i++) { for (int j = 0; j < numberOfParameter; j++) { u[i, j] = xbase[i, j]; } scaledY[i] = yarr[i]; } } else { for (int i = 0; i < numberOfData; i++) { double scale = 1 / stddev[i]; for (int j = 0; j < numberOfParameter; j++) { u[i, j] = scale * xbase[i, j]; } scaledY[i] = scale * yarr[i]; } } _decomposition = MatrixMath.GetSingularValueDecomposition(u); // set singular values < thresholdLevel to zero // ChopSingularValues makes only sense if all columns of the x matrix have the same variance //decomposition.ChopSingularValues(1E-5); // recalculate the parameters with the chopped singular values _decomposition.Backsubstitution(scaledY, _parameter); _chiSquare = 0; for (int i = 0; i < numberOfData; i++) { double ypredicted = 0; for (int j = 0; j < numberOfParameter; j++) { ypredicted += _parameter[j] * xbase[i, j]; } double deviation = yarr[i] - ypredicted; _predicted[i] = ypredicted; _residual[i] = deviation; _chiSquare += deviation * deviation; } _covarianceMatrix = _decomposition.GetCovariances(); //calculate the reduced prediction variance x'(X'X)^(-1)x for (int i = 0; i < numberOfData; i++) { double total = 0; for (int j = 0; j < numberOfParameter; j++) { double sum = 0; for (int k = 0; k < numberOfParameter; k++) { sum += _covarianceMatrix[j][k] * u[i, k]; } total += u[i, j] * sum; } _reducedPredictionVariance[i] = total; } return(this); }