/// <include file='FactorDocs.xml' path='factor_docs/message_op_class[@name="WishartFromShapeAndRateOp_Laplace2"]/message_doc[@name="RateAverageConditional(Wishart, double, Wishart, Wishart, Wishart)"]/*'/> public static Wishart RateAverageConditional([SkipIfUniform] Wishart sample, double shape, Wishart rate, Wishart to_rate, Wishart result) { if (sample.IsPointMass) { return(WishartFromShapeAndRateOp.RateAverageConditional(sample.Point, shape, result)); } // f(Y,R) = |Y|^(a-c) |R|^a exp(-tr(YR)) // p(Y) = |Y|^(a_y-c) exp(-tr(YB_y) // p(R) = |R|^(a_r-c) exp(-tr(RB_r) // int_Y f(Y,R) p(Y) dY = |R|^a |R+B_y|^-(a+a_y-c) int dim = sample.Dimension; double c = 0.5 * (dim + 1); double shape2 = shape - c + sample.Shape; Wishart ratePost = rate * to_rate; PositiveDefiniteMatrix r = ratePost.GetMean(); PositiveDefiniteMatrix rby = r + sample.Rate; PositiveDefiniteMatrix invrby = rby.Inverse(); PositiveDefiniteMatrix rInvrby = rby; rInvrby.SetToProduct(r, invrby); double xxddlogp = Matrix.TraceOfProduct(rInvrby, rInvrby) * shape2; double delta = -xxddlogp / dim; PositiveDefiniteMatrix invR = r.Inverse(); PositiveDefiniteMatrix dlogp = invrby; dlogp.Scale(-shape2); LowerTriangularMatrix rChol = new LowerTriangularMatrix(dim, dim); rChol.SetToCholesky(r); result.SetDerivatives(rChol, invR, dlogp, xxddlogp, GammaFromShapeAndRateOp.ForceProper, shape); return(result); }
/// <summary> /// Cholesky of Kernel matrix /// </summary> /// <param name="kf">Kernel function</param> /// <param name="xData">Data with which to build the matrix</param> /// <returns></returns> public static LowerTriangularMatrix Cholesky(IKernelFunction kf, Dictionary <int, Vector> xData) { if (null == kf || null == xData) { throw new ArgumentException("Unexpected null arguments"); } int nData = xData.Count; // Allocate and fill the Kernel matrix. PositiveDefiniteMatrix K = new PositiveDefiniteMatrix(nData, nData); for (int i = 0; i < nData; i++) { for (int j = 0; j < nData; j++) { // Evaluate the kernel. All hyperparameters, including noise // variance are handled in the kernel. K[i, j] = kf.EvaluateX1X2(xData[i], xData[j]); } } LowerTriangularMatrix chol = new LowerTriangularMatrix(nData, nData); chol.SetToCholesky(K); K = null; GC.Collect(0); return(chol); }
static void begin(LowerTriangularMatrix <double> lt, int start, int antCount, double alpha, double beta, double pheromoneEvaporationCoef, double pheromoneConstant, int maxIters, Queue <IterationContext> cq) { AntColony ac = new AntColony(lt, start, antCount, alpha, beta, pheromoneEvaporationCoef, pheromoneConstant, maxIters, cq); ac.begin(); int currIter = 0; while (currIter < maxIters - 1) { IterationContext it; while (cq.TryDequeue(out it) == false) { ; } currIter = it.currIter; Console.WriteLine("" + it.currIter); } var path = string.Join("=>", ac.shortestPath); var dist = ac.shrotestDistance; Console.WriteLine($"Shortest path has length of {dist} and it is: {path}"); }
private static PositiveDefiniteMatrix GetInverse(PositiveDefiniteMatrix A) { PositiveDefiniteMatrix result = new PositiveDefiniteMatrix(A.Rows, A.Cols); LowerTriangularMatrix L = new LowerTriangularMatrix(A.Rows, A.Cols); L.SetToCholesky(A); bool[] isZero = new bool[L.Rows]; for (int i = 0; i < L.Rows; i++) { if (L[i, i] == 0) { isZero[i] = true; L[i, i] = 1; } } L.SetToInverse(L); result.SetToOuterTranspose(L); for (int i = 0; i < isZero.Length; i++) { if (isZero[i]) { result[i, i] = double.PositiveInfinity; } } return(result); }
#pragma warning disable 162 #endif /// <summary>EP message to <c>b</c>.</summary> /// <param name="product">Incoming message from <c>product</c>.</param> /// <param name="A">Constant value for <c>a</c>.</param> /// <param name="result">Modified to contain the outgoing message.</param> /// <returns> /// <paramref name="result" /> /// </returns> /// <remarks> /// <para>The outgoing message is a distribution matching the moments of <c>b</c> as the random arguments are varied. The formula is <c>proj[p(b) sum_(product) p(product) factor(product,a,b)]/p(b)</c>.</para> /// </remarks> public static VectorGaussian BAverageConditional(VectorGaussian product, Matrix A, VectorGaussian result) { if (product.IsPointMass) { return(BAverageConditional(product.Point, A, result)); } // (p.mean - A*B)'*p.prec*(p.mean - A*B) // = B'*(A'*p.prec*A)*B - B'*A'*p.prec*p.mean - ... // B.prec = A'*p.prec*A // B.precTimesMean = A'*p.precTimesMean if (true) { // this method is slower but more numerically accurate // L*L' = p.prec int dim = product.Precision.Cols; LowerTriangularMatrix L = new LowerTriangularMatrix(dim, dim); L.SetToCholesky(product.Precision); Matrix At = A.Transpose(); Matrix temp = At * L; result.Precision.SetToOuter(temp); } else { Matrix temp = (product.Precision * A).Transpose(); result.Precision.SetToProduct(temp, A); } result.MeanTimesPrecision.SetToProduct(product.MeanTimesPrecision, A); return(result); }
public PositiveDefiniteMatrix Sample(PositiveDefiniteMatrix result) { Assert.IsTrue(result.Rows == Dimension); LowerTriangularMatrix cholB = new LowerTriangularMatrix(Dimension, Dimension); LowerTriangularMatrix cholX = new LowerTriangularMatrix(Dimension, Dimension); Matrix cholXt = new Matrix(Dimension, Dimension); return(Sample(result, cholB, cholX, cholXt)); }
public IterationContext(List <List <int> > antsRoutes, List <int> iterShortestPath, LowerTriangularMatrix <double> pheromoneMatrix, int currIter, int numOfIters) { this.antsRoutes = antsRoutes; this.iterShortestPath = iterShortestPath; this.pheromoneMatrix = new LowerTriangularMatrix <double>(pheromoneMatrix); this.currIter = currIter; this.numOfIters = numOfIters; }
// Use this for initialization void Start() { timeLeft = lengthOfAnimation; cityControler = gameObject.GetComponent <CityControler>(); acoControler = gameObject.GetComponent <AcoControler>(); pathControler = gameObject.GetComponent <PathControler>(); pheromons = null; antPefab = Resources.Load <GameObject>("CityTestScene/Prefab/Ant"); distanceControler = gameObject.GetComponent <DistanceControler>(); }
public LowerTriangularMatrix(LowerTriangularMatrix <T> other) { this.size = other.size; data = new T[size * (size + 1) / 2]; //deep copy of array for (int i = 0; i < this.size * (this.size + 1) / 2; ++i) { this.data[i] = other.data[i]; } }
private static double GetSquaredLengthOfRow(LowerTriangularMatrix L, int row) { double sum = 0; for (int col = 0; col <= row; col++) { double element = L[row, col]; sum += element * element; } return(sum); }
private static double GetSquaredLengthOfColumn(LowerTriangularMatrix L, int column) { int rows = L.Rows; double sum = 0; for (int row = column; row < rows; row++) { double element = L[row, column]; sum += element * element; } return(sum); }
public Ant(int start, List <int> notVisited, LowerTriangularMatrix <double> pheromoneMatrix, LowerTriangularMatrix <double> distanceMatrix, double alpha, double beta, bool firstPass) { this.notVisited = notVisited; this.pheromoneMatrix = pheromoneMatrix; this.distanceMatrix = distanceMatrix; this.alpha = alpha; this.beta = beta; this.firstPass = firstPass; this.route = new List <int>(); updateRoute(start); this.distanceTraveled = 0; }
private void applyLinearScale(double a, double b, LowerTriangularMatrix <double> matrix) { for (int i = 0; i < matrix.size; ++i) { for (int j = i + 1; j < matrix.size; ++j) { if (matrix[i, j] != 0) { matrix[i, j] = a * matrix[i, j] + b; } } } }
private void calculateFitness(LowerTriangularMatrix <double> lt) { int threadNum = Environment.ProcessorCount * 2; ConcurrentQueue <int> unservisedColonies = new ConcurrentQueue <int>(Enumerable.Range(0, currentGeneration.Count)); Task[] tasks = new Task[threadNum]; for (int i = 0; i < threadNum; ++i) { tasks[i] = Task.Factory.StartNew(() => threadRun(unservisedColonies, lt)); } Task.WaitAll(tasks); }
public static void Main(string[] args) { Queue <IterationContext> cq = new Queue <IterationContext>(); int start = 0; int antCount = 100; double alpha = .27; double beta = 8.8; double pheromoneEvaporationCoef = 0.7; double pheromoneConstant = 250; int maxIters = 100; if (args[0] == "-genarate") { int numOfGraphs = 1; int maxNodes = 20; int minNodes = 5; int maxWeight = 3000; int minWeight = 500; Generator g = new Generator(numOfGraphs, maxNodes, minNodes, maxWeight, minWeight); var graphs = g.generate(); //array of matricies of graphs Console.WriteLine("Graphs generated"); foreach (LowerTriangularMatrix <double> lt in graphs) { lt.writeToFile("test.txt"); Console.WriteLine(lt.size); begin(lt, start, antCount, alpha, beta, pheromoneEvaporationCoef, pheromoneConstant , maxIters, cq); } } else if (args[0] == "-run") { LowerTriangularMatrix <double> lt = new LowerTriangularMatrix <double>(0); lt.readFromFile(args[1]); begin(lt, start, antCount, alpha, beta, pheromoneEvaporationCoef, pheromoneConstant , maxIters, cq); } else if (args[0] == "-genetic") { GeneticAlg g = new GeneticAlg(5000); g.start(); } else { Console.WriteLine("Need an option besides [-generate,-genetic,-run <path>]? Add it :D"); return; } }
public static PositiveDefiniteMatrix Sample(double shape, PositiveDefiniteMatrix scale, PositiveDefiniteMatrix result) { int dimension = scale.Rows; LowerTriangularMatrix cholB = new LowerTriangularMatrix(dimension, dimension); cholB.SetToCholesky(scale); LowerTriangularMatrix cholX = new LowerTriangularMatrix(dimension, dimension); Rand.Wishart(shape, cholX); cholX.SetToProduct(cholB, cholX); UpperTriangularMatrix cholXt = cholX.Transpose(); result.SetToProduct(cholX, cholXt); return(result); }
public void RandWishart() { // multivariate Gamma double a = 2.7; int d = 3; PositiveDefiniteMatrix mTrue = new PositiveDefiniteMatrix(d, d); mTrue.SetToIdentity(); mTrue.SetToProduct(mTrue, a); LowerTriangularMatrix L = new LowerTriangularMatrix(d, d); PositiveDefiniteMatrix X = new PositiveDefiniteMatrix(d, d); PositiveDefiniteMatrix m = new PositiveDefiniteMatrix(d, d); m.SetAllElementsTo(0); double s = 0; for (int i = 0; i < nsamples; i++) { Rand.Wishart(a, L); X.SetToProduct(L, L.Transpose()); m = m + X; s = s + X.LogDeterminant(); } double sTrue = 0; for (int i = 0; i < d; i++) { sTrue += MMath.Digamma(a - i * 0.5); } m.Scale(1.0 / nsamples); s = s / nsamples; Console.WriteLine(""); Console.WriteLine("Multivariate Gamma"); Console.WriteLine("-------------------"); Console.WriteLine("m = \n{0}", m); double dError = m.MaxDiff(mTrue); if (dError > TOLERANCE) { Assert.True(false, String.Format("Wishart({0}) mean: (should be {0}*I), error = {1}", a, dError)); } if (System.Math.Abs(s - sTrue) > TOLERANCE) { Assert.True(false, string.Format("E[logdet]: {0} (should be {1})", s, sTrue)); } }
void loadDistances() { distance_ = new LowerTriangularMatrix <float>(cc.citys.Length); var file = Resources.Load <TextAsset>("CityTestScene/Data/distances"); var tmp = JsonUtility.FromJson <JsonArray <Distance> >(file.text).array; foreach (var x in tmp) { int i = cc.mapNameToIndex(x.from); int j = cc.mapNameToIndex(x.to); distance_[i, j] = x.distance; //Debug.Log(i + " " + j +" " + x.distance); } }
public void start() { int iterCount = 200; int iter = 0; init(); LowerTriangularMatrix <double> lt = new LowerTriangularMatrix <double>(0); lt.readFromFile("../data/cities_dist.txt"); for (iter = 0; iter < iterCount; ++iter) { Console.WriteLine("iteration: " + iter); calculateFitness(lt); crossingSpecies(); mutateSpecies(); swapWorstParents(); if (allTimeBest.fitness > this.currentGeneration[this.currentGeneration.Count - 1].fitness) { //saving all time best Console.WriteLine("New All time best!"); allTimeBest = new Colony(this.currentGeneration[this.currentGeneration.Count - 1]); } Console.WriteLine("fitness: " + this.currentGeneration[this.currentGeneration.Count - 1] .fitness); Console.WriteLine("length: " + this.currentGeneration[this.currentGeneration.Count - 1] .shorestDistance); Console.WriteLine("time: " + this.currentGeneration[this.currentGeneration.Count - 1].time); Console.WriteLine(string.Join(" ", allTimeBest.parameters)); // if(iter % 10 == 0){ // Console.WriteLine("fitness: " + this.currentGeneration[this.currentGeneration.Count -1].fitness); // } this.newGeneration.Clear(); } Console.WriteLine("fitness: " + allTimeBest.fitness); Console.WriteLine("path: " + allTimeBest.shorestDistance); Console.WriteLine("time: " + allTimeBest.time); string outputString = string.Join(" ", allTimeBest.parameters); Console.WriteLine(outputString); string[] lines = new string[1]; lines.Append(outputString); System.IO.File.WriteAllLines("ACO_parameters.txt", lines); }
public void reset() { pheromons = null; for (int i = 0; i < cityControler.activeCitysIndex.Length; ++i) { int tmp = cityControler.activeCitysIndex[i]; for (int j = i + 1; j < cityControler.activeCitysIndex.Length; ++j) { int tmp1 = cityControler.activeCitysIndex[j]; if (pathControler.pathMatrix[tmp, tmp1]) { pathControler.pathMatrix[tmp, tmp1].startWidth = 0; pathControler.pathMatrix[tmp, tmp1].endWidth = 0; } } } }
private static void GetProductMoments(Matrix A, Vector BMean, PositiveDefiniteMatrix BVariance, Vector mean, PositiveDefiniteMatrix variance) { // P.mean = A*B.mean // P.var = A*B.var*A' mean.SetToProduct(A, BMean); if (UseAccurateMethod) { int dim = BVariance.Rows; LowerTriangularMatrix cholesky = new LowerTriangularMatrix(dim, dim); cholesky.SetToCholesky(BVariance); Matrix AL = A * cholesky; variance.SetToOuter(AL); } else { variance.SetToProduct(A, (A * BVariance).Transpose()); variance.Symmetrize(); } }
/// <include file='FactorDocs.xml' path='factor_docs/message_op_class[@name="WishartFromShapeAndRateOp_Laplace2"]/message_doc[@name="SampleAverageConditional(Wishart, double, Wishart, Wishart, Wishart, Wishart)"]/*'/> public static Wishart SampleAverageConditional([NoInit] Wishart sample, double shape, [Proper] Wishart rate, [NoInit] Wishart to_rate, [NoInit] Wishart to_sample, Wishart result) { if (sample.IsUniform()) { return(SampleAverageConditional2(shape, rate, to_rate, result)); } // f(Y,R) = |Y|^(a-c) |R|^a exp(-tr(YR)) // p(Y) = |Y|^(a_y-c) exp(-tr(YB_y) // p(R) = |R|^(a_r-c) exp(-tr(RB_r) // int_R f(Y,R) p(R) dR = |Y|^(a-c) |Y+B_r|^-(a+a_r) int dim = sample.Dimension; double c = 0.5 * (dim + 1); double shape2 = shape + rate.Shape; Wishart samplePost = sample * to_sample; if (!samplePost.IsProper()) { return(SampleAverageConditional2(shape, rate, to_rate, result)); } PositiveDefiniteMatrix y = samplePost.GetMean(); PositiveDefiniteMatrix yPlusBr = y + rate.Rate; PositiveDefiniteMatrix invyPlusBr = yPlusBr.Inverse(); PositiveDefiniteMatrix yInvyPlusBr = yPlusBr; yInvyPlusBr.SetToProduct(y, invyPlusBr); double xxddlogf = shape2 * Matrix.TraceOfProduct(yInvyPlusBr, yInvyPlusBr); PositiveDefiniteMatrix invY = y.Inverse(); //double delta = -xxddlogf / dim; //result.Shape = delta + shape; //result.Rate.SetToSum(delta, invY, shape2, invyPlusBr); LowerTriangularMatrix yChol = new LowerTriangularMatrix(dim, dim); yChol.SetToCholesky(y); PositiveDefiniteMatrix dlogp = invyPlusBr; dlogp.Scale(-shape2); result.SetDerivatives(yChol, invY, dlogp, xxddlogf, GammaFromShapeAndRateOp.ForceProper, shape - c); if (result.Rate.Any(x => double.IsNaN(x))) { throw new Exception("result.Rate is nan"); } return(result); }
private LowerTriangularMatrix <double> getMatrix() { LowerTriangularMatrix <double> matrix = new LowerTriangularMatrix <double>(cityControler.activeCitysIndex.Length); for (int i = 0; i < matrix.size; ++i) { int tmp = cityControler.activeCitysIndex[i]; for (int j = i + 1; j < matrix.size; ++j) { int tmp1 = cityControler.activeCitysIndex[j]; matrix[i, j] = distanceControler.distanceMatrix[tmp, tmp1]; } } return(matrix); }
/// <summary> /// Gets the normalizer for a Wishart density function specified by shape and rate matrix /// </summary> /// <param name="shape">Shape parameter</param> /// <param name="rate">rate matrix</param> /// <returns></returns> public static double GetLogNormalizer(double shape, PositiveDefiniteMatrix rate) { int dimension = rate.Rows; // inline call to IsProper() if (!(shape > 0.5 * (dimension - 1))) { return(0.0); } LowerTriangularMatrix rateChol = new LowerTriangularMatrix(dimension, dimension); bool isPosDef = rateChol.SetToCholesky(rate); if (!isPosDef) { return(0.0); } // LogDeterminant(rate) = 2*L.TraceLn() return(MMath.GammaLn(shape, dimension) - shape * 2 * rateChol.TraceLn()); }
private void findMinMax(LowerTriangularMatrix <double> matrix, out double min, out double max) { min = double.MaxValue; max = double.MinValue; for (int i = 0; i < matrix.size; ++i) { for (int j = i + 1; j < matrix.size; ++j) { if (matrix[i, j] < min) { min = matrix[i, j]; } if (max < matrix[i, j]) { max = matrix[i, j]; } } } }
public PositiveDefiniteMatrix Sample(PositiveDefiniteMatrix result, LowerTriangularMatrix cholB, LowerTriangularMatrix cholX, Matrix cholXt) { if (IsPointMass) { result.SetTo(Point); return(result); } // Algorithm: // X = chol(inv(B))*W*chol(inv(B))' where W is std Wishart // chol(inv(B)) = inv(chol(B)') cholB.SetToCholesky(rate); UpperTriangularMatrix cholBt = UpperTriangularMatrix.TransposeInPlace(cholB); Rand.Wishart(Shape, cholX); cholX.PredivideBy(cholBt); // cholX is no longer LowerTriangular cholXt.SetToTranspose(cholX); result.SetToProduct(cholX, cholXt); return(result); }
private void threadRun(ConcurrentQueue <int> unservisedColonies, LowerTriangularMatrix <double> lt) { while (!unservisedColonies.IsEmpty) { int index; Queue <IterationContext> cq = new Queue <IterationContext>();//unused here unservisedColonies.TryDequeue(out index); Colony tmp = currentGeneration[index]; Stopwatch sw = new Stopwatch(); //since ACO is nondeterministic, we will repeat algoritam few times and take average double[] dists = new double[this.numberOfRepetitions]; int[] times = new int[this.numberOfRepetitions]; for (int i = 0; i < this.numberOfRepetitions; ++i) { sw.Start(); AntColony ac = new AntColony(lt, 0, (int)tmp.parameters[0], tmp.parameters[1], tmp.parameters[2], tmp.parameters[3], tmp.parameters[4], (int)tmp.parameters[5], cq); ac.mainLoop(); sw.Stop(); dists[i] = ac.shrotestDistance; times[i] = (int)sw.ElapsedMilliseconds; } double averageDist = dists.Sum() / dists.Length; int averageTime = times.Sum() / times.Length; int time = (int)sw.ElapsedMilliseconds; currentGeneration[index].fitness = fitnessFunction(averageDist, averageTime); currentGeneration[index].shorestDistance = averageDist; currentGeneration[index].time = averageTime; // Console.WriteLine("index: " + index + " fitness: " + currentGeneration[index].fitness // +" for " + time + "ms"); } }
public AntColony(LowerTriangularMatrix <double> matrix, int start, int antCount, double alpha, double beta, double pheromoneEvaporationCoef, double pheromoneConstant, int numOfIters, Queue <IterationContext> cq) { this.matrix = new LowerTriangularMatrix <double>(matrix); this.start = start; this.antCount = antCount; this.alpha = alpha; this.beta = beta; this.pheromoneMatrix = new LowerTriangularMatrix <double>(matrix.size); this.pheromoneMatrixCopy = new LowerTriangularMatrix <double>(matrix.size); this.pheromoneEvaporationCoef = pheromoneEvaporationCoef; this.pheromoneConstant = pheromoneConstant; this.numOfIters = numOfIters; ants = new Ant[antCount]; this.firstPass = true; this.shortestPath = null; this.shrotestDistance = -1; initAnts(); this.resultQueue = cq; this.running = true; this.sendingStep = 5;//CAREFULL WHEN CHANGING THIS, numOfIters % sendingStep == 0(this must be true!) }
/// <summary> /// Cholesky of Kernel matrix /// </summary> /// <param name="kf">Kernel function</param> /// <param name="xData">Data with which to build the matrix</param> /// <returns></returns> public static LowerTriangularMatrix Cholesky(IKernelFunction kf, Dictionary<int, Vector> xData) { if (null == kf || null == xData) throw new ArgumentException("Unexpected null arguments"); int nData = xData.Count; // Allocate and fill the Kernel matrix. PositiveDefiniteMatrix K = new PositiveDefiniteMatrix(nData, nData); for (int i = 0; i < nData; i++) { for (int j = 0; j < nData; j++) { // Evaluate the kernel. All hyperparameters, including noise // variance are handled in the kernel. K[i, j] = kf.EvaluateX1X2(xData[i], xData[j]); } } LowerTriangularMatrix chol = new LowerTriangularMatrix(nData, nData); chol.SetToCholesky(K); K = null; #if !SILVERLIGHT GC.Collect(0); #endif return chol; }
public static Wishart ShapeOrientationAverageConditional( Vector point, Bernoulli label, Gaussian shapeX, Gaussian shapeY, Wishart shapeOrientation, Wishart result) { if (shapeOrientation.IsPointMass && shapeX.IsPointMass && shapeY.IsPointMass) { double labelProbTrue = label.GetProbTrue(); double labelProbFalse = 1.0 - labelProbTrue; double probDiff = labelProbTrue - labelProbFalse; Vector shapeLocation = Vector.FromArray(shapeX.Point, shapeY.Point); Vector diff = shapeLocation - point; Matrix diffOuter = diff.Outer(diff); Matrix orientationTimesDiffOuter = shapeOrientation.Point * diffOuter; double trace = orientationTimesDiffOuter.Trace(); double factorValue = Math.Exp(-0.5 * shapeOrientation.Point.QuadraticForm(diff)); double funcValue = factorValue * probDiff + labelProbFalse; PositiveDefiniteMatrix dLogFunc = new PositiveDefiniteMatrix(diffOuter * (-0.5 * probDiff * factorValue / funcValue)); double xxddLogFunc = -0.5 * probDiff * (-0.5 * labelProbFalse * factorValue * trace * trace / (funcValue * funcValue) + factorValue * trace / funcValue); LowerTriangularMatrix cholesky = new LowerTriangularMatrix(2, 2); cholesky.SetToCholesky(shapeOrientation.Point); PositiveDefiniteMatrix inverse = shapeOrientation.Point.Inverse(); result.SetDerivatives(cholesky, inverse, dLogFunc, xxddLogFunc, forceProper: true); return result; } else { throw new NotSupportedException(); } }
public static Wishart MatrixAverageConditional(Wishart matrix, Gaussian angle, Gaussian logScaleX, Gaussian logScaleY, Wishart result) { if (!matrix.IsPointMass) { throw new NotImplementedException(); } Func<Matrix, double> logF = p => { double lsx, lsy, a; ExtractScaleAngle(p, out lsx, out lsy, out a); return angle.GetLogProb(a) + logScaleX.GetLogProb(lsx) + logScaleY.GetLogProb(lsy); }; Func<Matrix, double> trXdLogF = p => { return (p * MatrixDerivative(p, logF)).Trace(); }; Matrix dLogF = MatrixDerivative(matrix.Point, logF); Matrix dTrXdLogF = MatrixDerivative(matrix.Point, trXdLogF); double trXdTrXdLogF = (matrix.Point * dTrXdLogF).Trace(); LowerTriangularMatrix cholesky = new LowerTriangularMatrix(2, 2); cholesky.SetToCholesky(matrix.Point); PositiveDefiniteMatrix inverse = matrix.Point.Inverse(); result.SetDerivatives(cholesky, inverse, new PositiveDefiniteMatrix(dLogF), trXdTrXdLogF, forceProper: true); return result; }
/// <summary> /// Evidence message for EP /// </summary> /// <param name="sample">Constant value for 'sample'.</param> /// <param name="mean">Constant value for 'mean'.</param> /// <param name="precision">Constant value for 'precision'.</param> /// <returns>Logarithm of the factor's average value across the given argument distributions</returns> /// <remarks><para> /// The formula for the result is <c>log(factor(sample,mean,precision))</c>. /// </para></remarks> public static double LogAverageFactor(Vector sample, Vector mean, PositiveDefiniteMatrix precision) { int Dimension = sample.Count; LowerTriangularMatrix precL = new LowerTriangularMatrix(Dimension, Dimension); Vector iLb = Vector.Zero(Dimension); Vector precisionTimesMean = precision * mean; return VectorGaussian.GetLogProb(sample, precisionTimesMean, precision, precL, iLb); }
/// <include file='FactorDocs.xml' path='factor_docs/message_op_class[@name="ArrayFromVectorOp"]/message_doc[@name="ArrayAverageConditional{GaussianList}(IList{Gaussian}, VectorGaussian, GaussianList)"]/*'/> /// <typeparam name="GaussianList">The type of the resulting array.</typeparam> public static GaussianList ArrayAverageConditional <GaussianList>( [NoInit] IList <Gaussian> array, [SkipIfUniform] VectorGaussian vector, GaussianList result) where GaussianList : IList <Gaussian> { if (result.Count != vector.Dimension) { throw new ArgumentException("vector.Dimension (" + vector.Dimension + ") != result.Count (" + result.Count + ")"); } int length = result.Count; bool allPointMass = array.All(g => g.IsPointMass); if (allPointMass) { // efficient special case for (int i = 0; i < length; i++) { double x = array[i].Point; // -prec*(x-m) = -prec*x + prec*m double dlogp = vector.MeanTimesPrecision[i]; for (int j = 0; j < length; j++) { dlogp -= vector.Precision[i, j] * array[j].Point; } double ddlogp = -vector.Precision[i, i]; result[i] = Gaussian.FromDerivatives(x, dlogp, ddlogp, false); } } else if (vector.IsPointMass) { // efficient special case Vector mean = vector.Point; for (int i = 0; i < length; i++) { result[i] = Gaussian.PointMass(mean[i]); } } else if (vector.IsUniform()) { for (int i = 0; i < length; i++) { result[i] = Gaussian.Uniform(); } } else if (array.Any(g => g.IsPointMass)) { // Z = N(m1; m2, V1+V2) // logZ = -0.5 (m1-m2)'inv(V1+V2)(m1-m2) // dlogZ = (m1-m2)'inv(V1+V2) dm2 // ddlogZ = -dm2'inv(V1+V2) dm2 Vector mean = Vector.Zero(length); PositiveDefiniteMatrix variance = new PositiveDefiniteMatrix(length, length); vector.GetMeanAndVariance(mean, variance); for (int i = 0; i < length; i++) { if (array[i].IsUniform()) { continue; } double m, v; array[i].GetMeanAndVariance(out m, out v); variance[i, i] += v; mean[i] -= m; } PositiveDefiniteMatrix precision = variance.Inverse(); Vector meanTimesPrecision = precision * mean; for (int i = 0; i < length; i++) { if (array[i].IsUniform()) { result[i] = Gaussian.FromMeanAndVariance(mean[i], variance[i, i]); } else { double alpha = meanTimesPrecision[i]; double beta = precision[i, i]; result[i] = GaussianOp.GaussianFromAlphaBeta(array[i], alpha, beta, false); } } } else { // Compute inv(V1+V2)*(m1-m2) as inv(V2)*inv(inv(V1) + inv(V2))*(inv(V1)*m1 + inv(V2)*m2) - inv(V2)*m2 = inv(V2)*(m - m2) // Compute inv(V1+V2) as inv(V2)*inv(inv(V1) + inv(V2))*inv(V2) - inv(V2) PositiveDefiniteMatrix precision = (PositiveDefiniteMatrix)vector.Precision.Clone(); Vector meanTimesPrecision = vector.MeanTimesPrecision.Clone(); for (int i = 0; i < length; i++) { Gaussian g = array[i]; precision[i, i] += g.Precision; meanTimesPrecision[i] += g.MeanTimesPrecision; } bool fastMethod = true; if (fastMethod) { bool isPosDef; // this destroys precision LowerTriangularMatrix precisionChol = precision.CholeskyInPlace(out isPosDef); if (!isPosDef) { throw new PositiveDefiniteMatrixException(); } // variance = inv(precisionChol*precisionChol') = inv(precisionChol)'*inv(precisionChol) = varianceChol*varianceChol' // this destroys meanTimesPrecision var mean = meanTimesPrecision.PredivideBy(precisionChol); mean = mean.PredivideByTranspose(precisionChol); var varianceCholTranspose = precisionChol; // this destroys precisionChol varianceCholTranspose.SetToInverse(precisionChol); for (int i = 0; i < length; i++) { Gaussian g = array[i]; double variance_ii = GetSquaredLengthOfColumn(varianceCholTranspose, i); // works when g is uniform, but not when g is point mass result[i] = Gaussian.FromMeanAndVariance(mean[i], variance_ii) / g; } } else { // equivalent to above, but slower PositiveDefiniteMatrix variance = precision.Inverse(); var mean = variance * meanTimesPrecision; for (int i = 0; i < length; i++) { Gaussian g = array[i]; // works when g is uniform, but not when g is point mass result[i] = Gaussian.FromMeanAndVariance(mean[i], variance[i, i]) / g; } } } return(result); }
void makePaths() { int n = cityControler.citys.Length; paths = new LowerTriangularMatrix <LineRenderer>(n); //Debug.Log(n); for (int i = 0; i < n; ++i) { GameObject city1 = cityControler.citys[i]; if (!city1) { continue; } for (int j = i + 1; j < n; ++j) { GameObject city2 = cityControler.citys[j]; if (!city2) { continue; } //Debug.Log("Drawing from " + i + "to " + j + " " + city1.name + "_" + city2.name); Transform child1 = findDeepChild(city1.transform, "Outter"); Transform child2 = findDeepChild(city2.transform, "Outter"); if (!child1 || !child2) { return; } GameObject path = new GameObject(); path.name = "Path_" + city1.name + "_" + city2.name; LineRenderer line = path.AddComponent <LineRenderer>(); line.material = new Material(Shader.Find("Sprites/Default")); line.startColor = new Color(1, 0, 0, 1); line.endColor = new Color(1, 0, 0, 1); paths[i, j] = line; line.startWidth = 0f; line.endWidth = 0f; int segments = 50; float xRadius = (child1.position - child2.position).magnitude / 2; float yRadius = xRadius / 2; float angle = 270f; line.positionCount = segments / 2 + 1; for (int point = 0; point <= segments / 2; ++point) { float x = Mathf.Sin(Mathf.Deg2Rad * angle) * xRadius; float z = Mathf.Cos(Mathf.Deg2Rad * angle) * yRadius; line.useWorldSpace = false; line.SetPosition(point, new Vector3(x, z, 0)); angle += (360f / segments); } path.transform.position = child1.position + (child2.position - child1.position) / 2; var rot = Quaternion.FromToRotation(path.transform.right, child2.position - child1.position); path.transform.rotation = rot; } } }