/// <summary> /// Make a measurement of a feature. This function calls elliptical_search() to /// find the best match within three standard deviations of the predicted location. /// </summary> /// <param name="patch">The identifier for this feature (in this case an image patch)</param> /// <param name="z">The best image location match for the feature, to be filled in by this function</param> /// <param name="h">The expected image location</param> /// <param name="S">The expected location covariance, used to specify the search region.</param> /// <returns></returns> public override bool measure_feature(byte[] patch, int patchwidth, ref Vector z, Vector vz, Vector h, MatrixFixed S, Random rnd) { Cholesky S_cholesky = new Cholesky(S); MatrixFixed Sinv = S_cholesky.Inverse(); uint u_found = 0, v_found = 0; if (SceneLib.elliptical_search(image, image_width, image_height, patch, patchwidth, patchwidth, h, Sinv, ref u_found, ref v_found, vz, Camera_Constants.BOXSIZE, outputimage, outputimage_width, outputimage_height, show_ellipses, calibrating, rnd) != true) { // Feature not successfully matched return(false); } z.Put(0, (float)u_found); z.Put(1, (float)v_found); return(true); }
public void TestCholeskyDecomposition() { var m = new double[3, 3]; m[0, 0] = 25; m[0, 1] = 15; m[0, 2] = -5; m[1, 0] = 15; m[1, 1] = 18; m[1, 2] = 0; m[2, 0] = -5; m[2, 1] = 0; m[2, 2] = 11; var d = new Cholesky(); d.Calculate(m); Assert.AreEqual(d.Decomposition[0, 0], 5); Assert.AreEqual(d.Decomposition[0, 1], 3); Assert.AreEqual(d.Decomposition[0, 2], -1); Assert.AreEqual(d.Decomposition[1, 0], 3); Assert.AreEqual(d.Decomposition[1, 1], 3); Assert.AreEqual(d.Decomposition[1, 2], 1); Assert.AreEqual(d.Decomposition[2, 0], -1); Assert.AreEqual(d.Decomposition[2, 1], 1); Assert.AreEqual(d.Decomposition[2, 2], 3); }
/// <summary> /// Evaluates the probability density function for the inverse Wishart distribution. /// </summary> /// <param name="x">The matrix at which to evaluate the density at.</param> /// <exception cref="ArgumentOutOfRangeException">If the argument does not have the same dimensions as the scale matrix.</exception> /// <returns>the density at <paramref name="x"/>.</returns> public double Density(Matrix <double> x) { var p = _s.RowCount; if (x.RowCount != p || x.ColumnCount != p) { throw new ArgumentOutOfRangeException("x", Resources.ArgumentMatrixDimensions); } var chol = Cholesky <double> .Create(x); var dX = chol.Determinant; var sXi = chol.Solve(S); // Compute the multivariate Gamma function. var gp = Math.Pow(Constants.Pi, p * (p - 1.0) / 4.0); for (var j = 1; j <= p; j++) { gp *= SpecialFunctions.Gamma((_nu + 1.0 - j) / 2.0); } return(Math.Pow(dX, -(_nu + p + 1.0) / 2.0) * Math.Exp(-0.5 * sXi.Trace()) * Math.Pow(_chol.Determinant, _nu / 2.0) / Math.Pow(2.0, _nu * p / 2.0) / gp); }
/// <summary> /// Samples the distribution. /// </summary> /// <param name="rnd">The random number generator to use.</param> /// <param name="nu">The nu parameter to use.</param> /// <param name="s">The S parameter to use.</param> /// <param name="chol">The cholesky decomposition to use.</param> /// <returns>a random number from the distribution.</returns> static Matrix <double> DoSample(Random rnd, double nu, Matrix <double> s, Cholesky <double> chol) { var count = s.RowCount; // First generate a lower triangular matrix with Sqrt(Chi-Squares) on the diagonal // and normal distributed variables in the lower triangle. var a = new DenseMatrix(count, count); for (var d = 0; d < count; d++) { a.At(d, d, Math.Sqrt(Gamma.Sample(rnd, (nu - d) / 2.0, 0.5))); } for (var i = 1; i < count; i++) { for (var j = 0; j < i; j++) { a.At(i, j, Normal.Sample(rnd, 0.0, 1.0)); } } var factor = chol.Factor; return(factor * a * a.Transpose() * factor.Transpose()); }
void computeSingleStep(float[] step, float[] ATA, float[] ATb, float lambda, int dim) { int dim2 = dim * dim; //float[] tmpATA = new float[dim2]; TODO I preallocated at the top Array.Copy(ATA, tmpATA, dim2); for (int i = 0; i < dim2; i += (dim + 1)) { float ele = tmpATA[i]; if (!(Math.Abs(ele) < 1e-15f)) { ele *= (1.0f + lambda); } else { ele = lambda * 1e-10f; } tmpATA[i] = ele; } Cholesky cholA = new Cholesky(tmpATA, dim); cholA.Backsub(step, ATb); }
public override void NormalizeInPlace(ref ShoMatrix shoMatrix) { DoubleArray K = shoMatrix.DoubleArray; Cholesky tmp = K.TryCholesky(); Helper.CheckCondition(null != tmp, "Expect matrix to be positive definite"); }
public void TestCholesky() { IMatrix L; Cholesky.Factorize(A, out L); Assert.Equal(A, L.Multiply(L.Transpose())); }
/// <summary> /// Samples a Wishart distributed random variable using the method /// Algorithm AS 53: Wishart Variate Generator /// W. B. Smith and R. R. Hocking /// Applied Statistics, Vol. 21, No. 3 (1972), pp. 341-345 /// </summary> /// <param name="rnd">The random number generator to use.</param> /// <param name="degreesOfFreedom">The degrees of freedom (n) for the Wishart distribution.</param> /// <param name="scale">The scale matrix (V) for the Wishart distribution.</param> /// <returns>a sequence of samples from the distribution.</returns> public static Matrix <double> Sample(System.Random rnd, double degreesOfFreedom, Matrix <double> scale) { if (Control.CheckDistributionParameters && !IsValidParameterSet(degreesOfFreedom, scale)) { throw new ArgumentOutOfRangeException(Resources.InvalidDistributionParameters); } return(DoSample(rnd, degreesOfFreedom, scale, Cholesky <double> .Create(scale))); }
/// <summary> /// Samples a Wishart distributed random variable using the method /// Algorithm AS 53: Wishart Variate Generator /// W. B. Smith and R. R. Hocking /// Applied Statistics, Vol. 21, No. 3 (1972), pp. 341-345 /// </summary> /// <param name="rnd">The random number generator to use.</param> /// <param name="nu">The degrees of freedom.</param> /// <param name="s">The scale matrix.</param> /// <returns>a sequence of samples from the distribution.</returns> public static Matrix <double> Sample(Random rnd, double nu, Matrix <double> s) { if (Control.CheckDistributionParameters && !IsValidParameterSet(nu, s)) { throw new ArgumentOutOfRangeException(Resources.InvalidDistributionParameters); } return(DoSample(rnd, nu, s, Cholesky <double> .Create(s))); }
/// <summary> /// Samples a vector normal distributed random variable. /// </summary> /// <param name="rnd">The random number generator to use.</param> /// <param name="mean">The mean of the vector normal distribution.</param> /// <param name="covariance">The covariance matrix of the vector normal distribution.</param> /// <returns>a sequence of samples from defined distribution.</returns> static Vector <double> SampleVectorNormal(System.Random rnd, Vector <double> mean, Matrix <double> covariance) { var chol = Cholesky <double> .Create(covariance); // Sample a standard normal variable. var v = DenseVector.CreateRandom(mean.Count, new Normal(rnd)); // Return the transformed variable. return(mean + (chol.Factor * v)); }
/// <summary> /// Sets the parameters of the distribution after checking their validity. /// </summary> /// <param name="degreesOfFreedom">The degree of freedom (ν) for the inverse Wishart distribution.</param> /// <param name="scale">The scale matrix (Ψ) for the inverse Wishart distribution.</param> /// <exception cref="ArgumentOutOfRangeException">When the parameters are out of range.</exception> void SetParameters(double degreesOfFreedom, Matrix <double> scale) { if (Control.CheckDistributionParameters && !IsValidParameterSet(degreesOfFreedom, scale)) { throw new ArgumentOutOfRangeException(Resources.InvalidDistributionParameters); } _freedom = degreesOfFreedom; _scale = scale; _chol = _scale.Cholesky(); }
/// <summary> /// Sets the parameters of the distribution after checking their validity. /// </summary> /// <param name="nu">The degrees of freedom for the Wishart distribution.</param> /// <param name="s">The scale matrix for the Wishart distribution.</param> /// <exception cref="ArgumentOutOfRangeException">When the parameters don't pass the <see cref="IsValidParameterSet"/> function.</exception> private void SetParameters(double nu, Matrix <double> s) { if (Control.CheckDistributionParameters && !IsValidParameterSet(nu, s)) { throw new ArgumentOutOfRangeException(Resources.InvalidDistributionParameters); } _nu = nu; _s = s; _chol = Cholesky <double> .Create(_s); }
public void ShouldInverse() { var a = new Matrix(new double[, ] { { 4, 12, -16 }, { 12, 37, -43 }, { -16, -43, 98 } }); var m1 = Cholesky.Inverse(a); }
/// <summary> /// Initializes a new instance of the <see cref="InverseWishart"/> class. /// </summary> /// <param name="degreesOfFreedom">The degree of freedom (ν) for the inverse Wishart distribution.</param> /// <param name="scale">The scale matrix (Ψ) for the inverse Wishart distribution.</param> public InverseWishart(double degreesOfFreedom, Matrix<double> scale) { if (Control.CheckDistributionParameters && !IsValidParameterSet(degreesOfFreedom, scale)) { throw new ArgumentException(Resources.InvalidDistributionParameters); } _random = SystemRandomSource.Default; _freedom = degreesOfFreedom; _scale = scale; _chol = _scale.Cholesky(); }
/// <summary> /// Initializes a new instance of the <see cref="Wishart"/> class. /// </summary> /// <param name="degreesOfFreedom">The degrees of freedom (n) for the Wishart distribution.</param> /// <param name="scale">The scale matrix (V) for the Wishart distribution.</param> public Wishart(double degreesOfFreedom, Matrix <double> scale) { if (Control.CheckDistributionParameters && !IsValidParameterSet(degreesOfFreedom, scale)) { throw new ArgumentException("Invalid parametrization for the distribution."); } _random = SystemRandomSource.Default; _degreesOfFreedom = degreesOfFreedom; _scale = scale; _chol = _scale.Cholesky(); }
/// <summary> /// Initializes a new instance of the <see cref="InverseWishart"/> class. /// </summary> /// <param name="degreesOfFreedom">The degree of freedom (ν) for the inverse Wishart distribution.</param> /// <param name="scale">The scale matrix (Ψ) for the inverse Wishart distribution.</param> /// <param name="randomSource">The random number generator which is used to draw random samples.</param> public InverseWishart(double degreesOfFreedom, Matrix <double> scale, System.Random randomSource) { if (Control.CheckDistributionParameters && !IsValidParameterSet(degreesOfFreedom, scale)) { throw new ArgumentException(Resource.InvalidDistributionParameters); } _random = randomSource ?? SystemRandomSource.Default; _freedom = degreesOfFreedom; _scale = scale; _chol = _scale.Cholesky(); }
public void New_TestDecomposition(double[,] a, double precision) { var d = Cholesky.Decomposition(a); var test = d.Prod(d.Tranpose()); for (int i = 0; i < a.GetLength(0); i++) { for (int j = 0; j < a.GetLength(1); j++) { var err = Math.Abs(a[i, j] - test[i, j]); Assert.IsTrue(err < precision * DoubleUtils.MachineEpsilon); } } }
/// <summary> /// Evaluates the probability density function for the matrix normal distribution. /// </summary> /// <param name="x">The matrix at which to evaluate the density at.</param> /// <returns>the density at <paramref name="x"/></returns> /// <exception cref="ArgumentOutOfRangeException">If the argument does not have the correct dimensions.</exception> public double Density(Matrix <double> x) { if (x.RowCount != _m.RowCount || x.ColumnCount != _m.ColumnCount) { throw Matrix.DimensionsDontMatch <ArgumentOutOfRangeException>(x, _m, "x"); } var a = x - _m; var cholV = Cholesky <double> .Create(_v); var cholK = Cholesky <double> .Create(_k); return(Math.Exp(-0.5 * cholV.Solve(a.Transpose() * cholK.Solve(a)).Trace()) / Math.Pow(2.0 * Constants.Pi, x.RowCount * x.ColumnCount / 2.0) / Math.Pow(cholV.Determinant, x.RowCount / 2.0) / Math.Pow(cholK.Determinant, x.ColumnCount / 2.0)); }
/// <summary> /// Fits the data to the specified function. The function is meant to have <b>p</b>+<b>v</b> parameters, the first <b>p</b> of which are to be fitted, /// whereas the remaining <b>v</b> are assumed to be independent variables, whose values are picked from the lists for the independent variables. /// </summary> /// <param name="f">the function to be fitted. First derivatives w.r.t. the fit parameters are needed.</param> /// <param name="fitparameters">the number of parameters to be fitted. They must be the first parameters to be passed to the function.</param> /// <param name="indep">the list of values for the independent variables.</param> /// <param name="dep">the list of values for the dependent variable.</param> /// <param name="deperr">the list of errors for the dependent variable.</param> /// <param name="maxiterations">maximum number of iterations to find the minimum.</param> /// <returns>the parameters of the fit.</returns> public double[] Fit(NumericalTools.Minimization.ITargetFunction f, int fitparameters, double[][] indep, double[] dep, double[] deperr, int maxiterations) { m_DegreesOfFreedom = dep.Length - fitparameters; if (m_DegreesOfFreedom < 0) { throw new NumericalTools.Minimization.MinimizationException("Degrees of freedom = " + m_DegreesOfFreedom + ". Aborting."); } NumericalTools.Minimization.NewtonMinimizer MA = new NumericalTools.Minimization.NewtonMinimizer(); MA.Logger = m_TW; Chi2F chi2 = new Chi2F(f, fitparameters, indep, dep, deperr); MA.FindMinimum(chi2, maxiterations); m_EstimatedVariance = MA.Value / m_DegreesOfFreedom; m_BestFit = MA.Point; Minimization.ITargetFunction[] g = new NumericalTools.Minimization.ITargetFunction[fitparameters]; double[,] hessian = new double[fitparameters, fitparameters]; int i, j; for (i = 0; i < fitparameters; i++) { g[i] = chi2.Derive(i); for (j = 0; j < fitparameters; j++) { hessian[i, j] = g[i].Derive(j).Evaluate(m_BestFit); } } m_CorrelationMatrix = new double[fitparameters, fitparameters]; double[][] c = new Cholesky(hessian, 0.0).Inverse(0.0); for (i = 0; i < fitparameters; i++) { for (j = 0; j < i; j++) { m_CorrelationMatrix[j, i] = m_CorrelationMatrix[i, j] = c[i][j] / (Math.Sqrt(c[i][i]) * Math.Sqrt(c[j][j])); } m_CorrelationMatrix[i, j] = 1.0; } m_StandardErrors = new double[fitparameters]; for (i = 0; i < fitparameters; i++) { m_StandardErrors[i] = Math.Sqrt(m_EstimatedVariance * c[i][i]); } return(m_BestFit); }
/// <summary> /// Samples a vector normal distributed random variable. /// </summary> /// <param name="rnd">The random number generator to use.</param> /// <param name="mean">The mean of the vector normal distribution.</param> /// <param name="cholesky">The Cholesky factorization of the covariance matrix.</param> /// <returns>a sequence of samples from defined distribution.</returns> static Vector <double> SampleVectorNormal(Random rnd, Vector <double> mean, Cholesky <double> cholesky) { var count = mean.Count; // Sample a standard normal variable. var v = new DenseVector(count); for (var d = 0; d < count; d += 2) { var sample = Normal.SampleUncheckedBoxMuller(rnd); v[d] = sample.Item1; if (d + 1 < count) { v[d + 1] = sample.Item2; } } // Return the transformed variable. return(mean + (cholesky.Factor * v)); }
public void ShouldSolve() { var a = new double[, ] { { 6.0, 15.0, 55.0 }, { 15.0, 55.0, 225.0 }, { 55.0, 225.0, 979.0 } }; var rhs = new double[] { 9.5, 50.0, 237.0 }; var solution = Cholesky.Solve(a, rhs); var expected = new double[] { -0.5, -1.0, 0.5 }; Assert.AreEqual(expected.Length, solution.Length); for (var i = 0; i < solution.Length; ++i) { Assert.AreEqual(expected[i], solution[i], 0.000001); } }
public static bool KnowedMatrixTestSize3(Cholesky method) { var a = new Matrix(3); a[0, 0] = 25; a[0, 1] = 15; a[0, 2] = -5; a[1, 0] = 15; a[1, 1] = 18; a[1, 2] = 0; a[2, 0] = -5; a[2, 1] = 0; a[2, 2] = 11; var x = new Vector(3); x[0] = 1; x[1] = 1; x[2] = 1; var b = a * x; var Xnew = method.Run(a, b); return(VerifyResult(x, Xnew)); }
public void setCorrelation(Matrix acorrelation) { // Store the correlation matrix correlation = acorrelation; correlation_root = Cholesky.factorise(correlation); }
/// <summary> /// Computes the Cholesky decomposition for a matrix. /// </summary> /// <param name="matrix">The matrix to factor.</param> /// <returns>The Cholesky decomposition object.</returns> public static Cholesky Cholesky(this Matrix <float> matrix) { return((Cholesky)Cholesky <float> .Create(matrix)); }
static void Main(string[] args) { var sw = new Stopwatch(); var a = new Matrix(3); a[0, 0] = 25; a[0, 1] = 15; a[0, 2] = -5; a[1, 0] = 15; a[1, 1] = 18; a[1, 2] = 0; a[2, 0] = -5; a[2, 1] = 0; a[2, 2] = 11; var x = new Vector(3); x[0] = 1; x[1] = 1; x[2] = 1; var b = a * x; IMethod method = null; Console.WriteLine("*** Performance Test ***"); Console.WriteLine("*** Successive Overrelaxation ***"); method = new successive_overrelaxation(); method.Run(a, b); var listRes = new List <TimeSpan>(); for (int i = 0; i < 1000; i++) { sw.Start(); var res = method.Run(a, b); sw.Stop(); listRes.Add(sw.Elapsed); Console.WriteLine($"{sw.Elapsed.TotalMilliseconds} ms"); sw.Reset(); } Console.WriteLine($"Average - {listRes.Average(y => y.TotalMilliseconds)} ms"); Console.WriteLine("*** LU ***"); method = new LUmet(); listRes = new List <TimeSpan>(); for (int i = 0; i < 1000; i++) { sw.Start(); var res = method.Run(a, b); sw.Stop(); listRes.Add(sw.Elapsed); Console.WriteLine($"{sw.Elapsed.TotalMilliseconds} ms"); sw.Reset(); } Console.WriteLine($"Average - {listRes.Average(y => y.TotalMilliseconds)} ms"); Console.WriteLine("*** Gauss - Seidel ***"); method = new GaussSeidel(); listRes = new List <TimeSpan>(); for (int i = 0; i < 1000; i++) { sw.Start(); var res = method.Run(a, b); sw.Stop(); listRes.Add(sw.Elapsed); Console.WriteLine($"{sw.Elapsed.TotalMilliseconds} ms"); sw.Reset(); } Console.WriteLine($"Average - {listRes.Average(y => y.TotalMilliseconds)} ms"); Console.WriteLine("*** Cholesky ***"); method = new Cholesky(); listRes = new List <TimeSpan>(); for (int i = 0; i < 1000; i++) { sw.Start(); var res = method.Run(a, b); sw.Stop(); listRes.Add(sw.Elapsed); Console.WriteLine($"{sw.Elapsed.TotalMilliseconds} ms"); sw.Reset(); } Console.WriteLine($"Average - {listRes.Average(y => y.TotalMilliseconds)} ms"); Console.ReadLine(); }
/// <summary> /// Samples the distribution. /// </summary> /// <param name="rnd">The random number generator to use.</param> /// <param name="nu">The nu parameter to use.</param> /// <param name="s">The S parameter to use.</param> /// <param name="chol">The cholesky decomposition to use.</param> /// <returns>a random number from the distribution.</returns> private static Matrix<double> DoSample(Random rnd, double nu, Matrix<double> s, Cholesky<double> chol) { var count = s.RowCount; // First generate a lower triangular matrix with Sqrt(Chi-Squares) on the diagonal // and normal distributed variables in the lower triangle. var a = new DenseMatrix(count, count, 0.0); for (var d = 0; d < count; d++) { a[d, d] = Math.Sqrt(Gamma.Sample(rnd, (nu - d) / 2.0, 0.5)); } for (var i = 1; i < count; i++) { for (var j = 0; j < i; j++) { a[i, j] = Normal.Sample(rnd, 0.0, 1.0); } } var factor = chol.Factor; return factor * a * a.Transpose() * factor.Transpose(); }
/// <summary> /// Sets the parameters of the distribution after checking their validity. /// </summary> /// <param name="nu">The degrees of freedom for the Wishart distribution.</param> /// <param name="s">The scale matrix for the Wishart distribution.</param> /// <exception cref="ArgumentOutOfRangeException">When the parameters don't pass the <see cref="IsValidParameterSet"/> function.</exception> private void SetParameters(double nu, Matrix<double> s) { if (Control.CheckDistributionParameters && !IsValidParameterSet(nu, s)) { throw new ArgumentOutOfRangeException(Resources.InvalidDistributionParameters); } _nu = nu; _s = s; _chol = Cholesky<double>.Create(_s); }
/// <summary> /// Samples the distribution. /// </summary> /// <param name="rnd">The random number generator to use.</param> /// <param name="degreesOfFreedom">The degrees of freedom (n) for the Wishart distribution.</param> /// <param name="scale">The scale matrix (V) for the Wishart distribution.</param> /// <param name="chol">The cholesky decomposition to use.</param> /// <returns>a random number from the distribution.</returns> static Matrix<double> DoSample(System.Random rnd, double degreesOfFreedom, Matrix<double> scale, Cholesky<double> chol) { var count = scale.RowCount; // First generate a lower triangular matrix with Sqrt(Chi-Squares) on the diagonal // and normal distributed variables in the lower triangle. var a = new DenseMatrix(count, count); for (var d = 0; d < count; d++) { a.At(d, d, Math.Sqrt(Gamma.Sample(rnd, (degreesOfFreedom - d)/2.0, 0.5))); } for (var i = 1; i < count; i++) { for (var j = 0; j < i; j++) { a.At(i, j, Normal.Sample(rnd, 0.0, 1.0)); } } var factor = chol.Factor; return factor*a*a.Transpose()*factor.Transpose(); }
/// <summary> /// Samples a vector normal distributed random variable. /// </summary> /// <param name="rnd">The random number generator to use.</param> /// <param name="mean">The mean of the vector normal distribution.</param> /// <param name="cholesky">The Cholesky factorization of the covariance matrix.</param> /// <returns>a sequence of samples from defined distribution.</returns> private static Vector<double> SampleVectorNormal(Random rnd, Vector<double> mean, Cholesky<double> cholesky) { var count = mean.Count; // Sample a standard normal variable. var v = new DenseVector(count, 0.0); for (var d = 0; d < count; d += 2) { var sample = Normal.SampleBoxMuller(rnd); v[d] = sample.Item1; if (d + 1 < count) { v[d + 1] = sample.Item2; } } // Return the transformed variable. return mean + (cholesky.Factor * v); }
public override double Calcul() { int position = 0; if (Math.Floor(alpha * Actions.Lignes) == alpha * Actions.Lignes) { position = (int)(alpha * Actions.Lignes); } else { position = (int)Math.Floor(alpha * Actions.Lignes) + 1; } Matrice rendements = new Matrice(Actions.Lignes - 1, Actions.Colonnes); Matrice Er = new Matrice(Actions.Lignes); Matrice Vol = new Matrice(Actions.Lignes); Matrice Corr = new Matrice(Actions.Colonnes, Actions.Colonnes); for (int j = 0; j < Actions.Colonnes; j++) { for (int i = 1; i < Actions.Lignes; i++) { rendements[i - 1, j] = (Actions[i, j] - Actions[i - 1, j]) / Actions[i - 1, j]; } Er[j, 0] = Statistique.Moyenne(rendements, j); Vol[j, 0] = Statistique.EcartType(rendements, j); } // Calcul de la partie supérieure de la matrice de corrélation for (int j = 0; j < Actions.Colonnes; j++) { for (int k = j + 1; k < Actions.Colonnes; k++) { // Corrélation entre l'entreprise j et l'entreprise k Corr[j, k] = Statistique.Correlation(rendements, j, k); } } // Génération de la partie infèrieure par symétrie for (int j = 0; j < Actions.Colonnes; j++) { for (int k = j + 1; k < Actions.Colonnes; k++) { Corr[k, j] = Corr[j, k]; } } // Remplissage de la diagonale avec la valeur 1 for (int j = 0; j < Actions.Colonnes; j++) { Corr[j, j] = 1; } // Décomposition de Cholesky Decomposition decompo = new Cholesky(Corr); decompo.Decomposer(); Matrice L = decompo.L; rendements = Simulation(Er, Vol, decompo, rendements.Lignes); double[] VaR_actif = new double[Actions.Colonnes]; // Calcul des VaR individuelles for (int j = 0; j < Actions.Colonnes; j++) { List <double> rendement_tri = new List <double>(); for (int i = 0; i < Actions.Lignes - 1; i++) { rendement_tri.Add(rendements[i, j]); } rendement_tri.Sort(); VaR_actif[j] = rendement_tri[position - 1]; // On récupére la VaR de l'actif seul; -1 car le tableau est indexé à 0 Console.WriteLine("VaR actif " + j + " : " + VaR_actif[j]); VaR_result += VaR_actif[j] * VaR_actif[j] * CompanyTab[j].Weight * CompanyTab[j].Weight; } ; // Calcul des corrélations entre les actifs for (int j = 0; j < Actions.Colonnes; j++) { for (int k = j + 1; k < Actions.Colonnes; k++) { // Corrélation entre l'entreprise j et l'entreprise k VaR_result += 2 * Statistique.Correlation(rendements, j, k) * VaR_actif[j] * CompanyTab[j].Weight * VaR_actif[k] * CompanyTab[k].Weight; } } return(-Math.Sqrt(VaR_result)); }
/// <summary> /// Samples a vector normal distributed random variable. /// </summary> /// <param name="rnd">The random number generator to use.</param> /// <param name="mean">The mean of the vector normal distribution.</param> /// <param name="covariance">The covariance matrix of the vector normal distribution.</param> /// <returns>a sequence of samples from defined distribution.</returns> private static Vector <double> SampleVectorNormal(Random rnd, Vector <double> mean, Matrix <double> covariance) { var chol = Cholesky <double> .Create(covariance); return(SampleVectorNormal(rnd, mean, chol)); }
public MainWindowViewModel() { logger = new Logger(); logger.Write += Logger_Write; Settings.Load(); run = new RelayCommand(x => { IMethod method = null; var a = Matrix.FromArray(A); var b = Vector.FromArray(B); switch (methodIndex) { case 0: method = new Cholesky(); break; case 1: method = new GaussSeidel(); break; case 2: method = new successive_overrelaxation(); break; case 3: method = new LUmet(); break; default: logger.NewMsg("Такого методу немає"); break; } if (method != null) { method.Log = logger; X = method.Run(a, b).ToArray(); } }); random = new RelayCommand(x => { A = Matrix.GetRandomMatrix(Size).ToArray(); var randB = new double[1, Size]; var r = new Random(); for (int i = 0; i < Size; ++i) { randB[0, i] = r.Next(-1000, 1000); } B = randB; }); close = new RelayCommand(x => { App.Current.Shutdown(); }); clearLog = new RelayCommand(x => { Log = ""; }); openSettings = new RelayCommand(x => { var form = new SettingsWindow(); form.Show(); }); }
/// <summary> /// Computes the Cholesky decomposition for a matrix. /// </summary> /// <param name="matrix">The matrix to factor.</param> /// <returns>The Cholesky decomposition object.</returns> public static Cholesky Cholesky(this Matrix <Complex> matrix) { return((Cholesky)Cholesky <Complex> .Create(matrix)); }
/// <summary> /// Computes the Cholesky decomposition for a matrix. /// </summary> /// <param name="matrix">The matrix to factor.</param> /// <returns>The Cholesky decomposition object.</returns> public static Cholesky Cholesky(this Matrix <double> matrix) { return((Cholesky)Cholesky <double> .Create(matrix)); }
/// <summary> /// Sets the parameters of the distribution after checking their validity. /// </summary> /// <param name="degreesOfFreedom">The degree of freedom (ν) for the inverse Wishart distribution.</param> /// <param name="scale">The scale matrix (Ψ) for the inverse Wishart distribution.</param> /// <exception cref="ArgumentOutOfRangeException">When the parameters are out of range.</exception> void SetParameters(double degreesOfFreedom, Matrix<double> scale) { if (Control.CheckDistributionParameters && !IsValidParameterSet(degreesOfFreedom, scale)) { throw new ArgumentOutOfRangeException(Resources.InvalidDistributionParameters); } _freedom = degreesOfFreedom; _scale = scale; _chol = _scale.Cholesky(); }
/// <summary> /// Fits the data to the specified function. The function is meant to have <b>p</b>+<b>v</b> parameters, the first <b>p</b> of which are to be fitted, /// whereas the remaining <b>v</b> are assumed to be independent variables, whose values are picked from the lists for the independent variables. /// </summary> /// <param name="f">the function to be fitted. First derivatives w.r.t. the fit parameters are needed.</param> /// <param name="fitparameters">the number of parameters to be fitted. They must be the first parameters to be passed to the function.</param> /// <param name="indep">the list of values for the independent variables.</param> /// <param name="indeperr">the list of errors for the independent variable.</param> /// <param name="dep">the list of values for the dependent variable.</param> /// <param name="deperr">the list of errors for the dependent variable.</param> /// <param name="maxiterations">maximum number of iterations to find the minimum.</param> /// <returns>the parameters of the fit.</returns> /// <remarks>The method of effective variance is used to take errors on the independent variables into account. </remarks> public double[] Fit(NumericalTools.Minimization.ITargetFunction f, int fitparameters, double[][] indep, double[] dep, double [][] indeperr, double[] deperr, int maxiterations) { m_DegreesOfFreedom = dep.Length - fitparameters; if (m_DegreesOfFreedom < 0) { throw new NumericalTools.Minimization.MinimizationException("Degrees of freedom = " + m_DegreesOfFreedom + ". Aborting."); } NumericalTools.Minimization.NewtonMinimizer MA = new NumericalTools.Minimization.NewtonMinimizer(); MA.Logger = m_TW; NumericalTools.Minimization.ITargetFunction[] f_d = new NumericalTools.Minimization.ITargetFunction[f.CountParams - fitparameters]; int i, j; for (i = 0; i < f_d.Length; i++) { f_d[i] = f.Derive(i + fitparameters); } double [] c_deperr = new double[deperr.Length]; double [] xp = new double[f.CountParams]; double [] xfp = new double[fitparameters]; double dfx; for (i = 0; i < f_d.Length; i++) { xfp[i] = f.Start[i]; } int maxouteriter = maxiterations; if (maxouteriter <= 0) { maxouteriter = -1; } double f0, f1, dxchange; do { if (m_TW != null) { m_TW.WriteLine("Starting with derivative guess - remaining iterations: " + maxouteriter); } for (i = 0; i < f_d.Length; i++) { xp[i] = xfp[i]; } for (i = 0; i < c_deperr.Length; i++) { for (j = 0; j < f_d.Length; j++) { xp[j + fitparameters] = indep[i][j]; } c_deperr[i] = deperr[i] * deperr[i]; for (j = 0; j < f_d.Length; j++) { dfx = f_d[j].Evaluate(xp) * indeperr[i][j]; c_deperr[i] += dfx * dfx; } c_deperr[i] = Math.Sqrt(c_deperr[i]); } Chi2F chi2 = new Chi2F(f, fitparameters, indep, dep, c_deperr); chi2.SetStart(xfp); f0 = chi2.Evaluate(xfp); MA.FindMinimum(chi2, maxiterations); m_EstimatedVariance = MA.Value / m_DegreesOfFreedom; m_BestFit = MA.Point; Minimization.ITargetFunction[] g = new NumericalTools.Minimization.ITargetFunction[fitparameters]; double[,] hessian = new double[fitparameters, fitparameters]; for (i = 0; i < fitparameters; i++) { g[i] = chi2.Derive(i); for (j = 0; j < fitparameters; j++) { hessian[i, j] = g[i].Derive(j).Evaluate(m_BestFit); } } m_CorrelationMatrix = new double[fitparameters, fitparameters]; double[][] c = new Cholesky(hessian, 0.0).Inverse(0.0); for (i = 0; i < fitparameters; i++) { for (j = 0; j < i; j++) { m_CorrelationMatrix[j, i] = m_CorrelationMatrix[i, j] = c[i][j] / (Math.Sqrt(c[i][i]) * Math.Sqrt(c[j][j])); } m_CorrelationMatrix[i, j] = 1.0; } m_StandardErrors = new double[fitparameters]; for (i = 0; i < fitparameters; i++) { m_StandardErrors[i] = Math.Sqrt(m_EstimatedVariance * c[i][i]); } dxchange = 0.0; for (i = 0; i < f_d.Length; i++) { dxchange += (xfp[i] - m_BestFit[i]) * (xfp[i] - m_BestFit[i]); } f1 = chi2.Evaluate(m_BestFit); for (i = 0; i < xfp.Length; i++) { xfp[i] = m_BestFit[i]; } if (m_TW != null) { m_TW.WriteLine("End with derivative guess - remaining iterations: " + maxouteriter); } if (--maxouteriter < 0) { maxouteriter = -1; } }while (maxouteriter != 0 && f.StopMinimization(f1, f0, dxchange) == false); return(m_BestFit); }