Beispiel #1
1
 private PathTSPTour(PathTSPTour original, Cloner cloner)
   : base(original, cloner) {
   this.coordinates = cloner.Clone(original.coordinates);
   this.permutation = cloner.Clone(original.permutation);
   this.quality = cloner.Clone(original.quality);
   Initialize();
 }
 public static void MyClassInitialize(TestContext testContext) {
   random = new MersenneTwister();
   symmetricDistances = new DoubleMatrix(ProblemSize, ProblemSize);
   symmetricWeights = new DoubleMatrix(ProblemSize, ProblemSize);
   asymmetricDistances = new DoubleMatrix(ProblemSize, ProblemSize);
   asymmetricWeights = new DoubleMatrix(ProblemSize, ProblemSize);
   nonZeroDiagonalDistances = new DoubleMatrix(ProblemSize, ProblemSize);
   nonZeroDiagonalWeights = new DoubleMatrix(ProblemSize, ProblemSize);
   for (int i = 0; i < ProblemSize - 1; i++) {
     for (int j = i + 1; j < ProblemSize; j++) {
       symmetricDistances[i, j] = random.Next(ProblemSize * 100);
       symmetricDistances[j, i] = symmetricDistances[i, j];
       symmetricWeights[i, j] = random.Next(ProblemSize * 100);
       symmetricWeights[j, i] = symmetricWeights[i, j];
       asymmetricDistances[i, j] = random.Next(ProblemSize * 100);
       asymmetricDistances[j, i] = random.Next(ProblemSize * 100);
       asymmetricWeights[i, j] = random.Next(ProblemSize * 100);
       asymmetricWeights[j, i] = random.Next(ProblemSize * 100);
       nonZeroDiagonalDistances[i, j] = random.Next(ProblemSize * 100);
       nonZeroDiagonalDistances[j, i] = random.Next(ProblemSize * 100);
       nonZeroDiagonalWeights[i, j] = random.Next(ProblemSize * 100);
       nonZeroDiagonalWeights[j, i] = random.Next(ProblemSize * 100);
     }
     nonZeroDiagonalDistances[i, i] = random.Next(ProblemSize * 100);
     nonZeroDiagonalWeights[i, i] = random.Next(ProblemSize * 100);
   }
   int index = random.Next(ProblemSize);
   if (nonZeroDiagonalDistances[index, index] == 0)
     nonZeroDiagonalDistances[index, index] = random.Next(1, ProblemSize * 100);
   index = random.Next(ProblemSize);
   if (nonZeroDiagonalWeights[index, index] == 0)
     nonZeroDiagonalWeights[index, index] = random.Next(1, ProblemSize * 100);
   assignment = new Permutation(PermutationTypes.Absolute, ProblemSize, random);
 }
		public void Current()
		{
			DoubleMatrix test = new DoubleMatrix(new double[2, 2] { { 1, 2 }, { 3, 4 } });
			IEnumerator enumerator = test.GetEnumerator();
			bool movenextresult;

			movenextresult = enumerator.MoveNext();
			Assert.IsTrue(movenextresult);
			Assert.AreEqual(enumerator.Current, test[0, 0]);

			movenextresult = enumerator.MoveNext();
			Assert.IsTrue(movenextresult);
			Assert.AreEqual(enumerator.Current, test[1, 0]);

			movenextresult = enumerator.MoveNext();
			Assert.IsTrue(movenextresult);
			Assert.AreEqual(enumerator.Current, test[0, 1]);

			movenextresult = enumerator.MoveNext();
			Assert.IsTrue(movenextresult);
			Assert.AreEqual(enumerator.Current, test[1, 1]);

			movenextresult = enumerator.MoveNext();
			Assert.IsFalse(movenextresult);
		}
Beispiel #4
0
 /***********************/
 /* PUBLIC CONSTRUCTORS */
 /***********************/
 /// <summary>Instantiates a new 2d point with the specified x and y 
 /// coordinates. Creates a new underlying matrix data source</summary>
 /// <param name="x">x-coordinate of this 2d point</param>
 /// <param name="y">y-coordinate of this 2d point</param>
 public Point2D(Double x, Double y)
 {
     _matrix = new DoubleMatrix(1, 3);
     _matrix[0, 0] = x;
     _matrix[0, 1] = y;
     _matrix[0, 2] = 1F;
 }
Beispiel #5
0
        public static DoubleMatrix ShiftToPositives(ref DoubleMatrix io_Coordinates,params DoubleMatrix[] io_AffectedAlso)
        {
            DoubleMatrix retMinMax = MinMaxByRow(io_Coordinates);
            DoubleMatrix growByMatrix = new DoubleMatrix(retMinMax.RowsCount, 1);
            growByMatrix.Init(0);

            Func<int, int, double, double> prepareGrowingCell = (row, col, value) =>
            {
                if (retMinMax[row, sr_MinCol] < 0)
                {
                    retMinMax[row, sr_MinCol] = Math.Abs(retMinMax[row, sr_MinCol]);
                    retMinMax[row, sr_MaxCol] += retMinMax[row, sr_MinCol];
                    return retMinMax[row, sr_MinCol];
                }
                else
                {
                    retMinMax[row, sr_MinCol] = value;
                    return value;
                }
            };

            growByMatrix.Iterate(prepareGrowingCell);

            AddScalarsByDims(ref io_Coordinates, growByMatrix);

            for (int i = 0; i < io_AffectedAlso.Length; ++i)
            {
                AddScalarsByDims(ref io_AffectedAlso[i], growByMatrix);
            }

            return retMinMax;
        }
    /// <summary>
    /// Performs a breeder genetic algorithm manipulation on the given <paramref name="vector"/>.
    /// </summary>
    /// <param name="random">A random number generator.</param>
    /// <param name="vector">The real vector to manipulate.</param>
    /// <param name="bounds">The lower and upper bound (1st and 2nd column) of the positions in the vector. If there are less rows than dimensions, the rows are cycled.</param>
    /// <param name="searchIntervalFactor">The factor determining the size of the search interval.</param>
    public static void Apply(IRandom random, RealVector vector, DoubleMatrix bounds, DoubleValue searchIntervalFactor) {
      int length = vector.Length;
      double prob, value;
      do {
        value = Sigma(random);
      } while (value == 0);

      prob = 1.0 / (double)length;
      bool wasMutated = false;

      for (int i = 0; i < length; i++) {
        if (random.NextDouble() < prob) {
          double range = bounds[i % bounds.Rows, 1] - bounds[i % bounds.Rows, 0];
          if (random.NextDouble() < 0.5) {
            vector[i] = vector[i] + value * searchIntervalFactor.Value * range;
          } else {
            vector[i] = vector[i] - value * searchIntervalFactor.Value * range;
          }
          wasMutated = true;
        }
      }

      // make sure at least one gene was mutated
      if (!wasMutated) {
        int pos = random.Next(length);
        double range = bounds[pos % bounds.Rows, 1] - bounds[pos % bounds.Rows, 0];
        if (random.NextDouble() < 0.5) {
          vector[pos] = vector[pos] + value * searchIntervalFactor.Value * range;
        } else {
          vector[pos] = vector[pos] - value * searchIntervalFactor.Value * range;
        }
      }
    }
    public static double EvaluateByCoordinates(Permutation permutation, TranslocationMove move, DoubleMatrix coordinates, TSPTranslocationMovePathEvaluator evaluator) {
      if (move.Index1 == move.Index3
        || move.Index2 == permutation.Length - 1 && move.Index3 == 0
        || move.Index1 == 0 && move.Index3 == permutation.Length - 1 - move.Index2) return 0;

      int edge1source = permutation.GetCircular(move.Index1 - 1);
      int edge1target = permutation[move.Index1];
      int edge2source = permutation[move.Index2];
      int edge2target = permutation.GetCircular(move.Index2 + 1);
      int edge3source, edge3target;
      if (move.Index3 > move.Index1) {
        edge3source = permutation.GetCircular(move.Index3 + move.Index2 - move.Index1);
        edge3target = permutation.GetCircular(move.Index3 + move.Index2 - move.Index1 + 1);
      } else {
        edge3source = permutation.GetCircular(move.Index3 - 1);
        edge3target = permutation[move.Index3];
      }
      double moveQuality = 0;
      // remove three edges
      moveQuality -= evaluator.CalculateDistance(coordinates[edge1source, 0], coordinates[edge1source, 1],
        coordinates[edge1target, 0], coordinates[edge1target, 1]);
      moveQuality -= evaluator.CalculateDistance(coordinates[edge2source, 0], coordinates[edge2source, 1],
        coordinates[edge2target, 0], coordinates[edge2target, 1]);
      moveQuality -= evaluator.CalculateDistance(coordinates[edge3source, 0], coordinates[edge3source, 1],
        coordinates[edge3target, 0], coordinates[edge3target, 1]);
      // add three edges
      moveQuality += evaluator.CalculateDistance(coordinates[edge3source, 0], coordinates[edge3source, 1],
        coordinates[edge1target, 0], coordinates[edge1target, 1]);
      moveQuality += evaluator.CalculateDistance(coordinates[edge2source, 0], coordinates[edge2source, 1],
        coordinates[edge3target, 0], coordinates[edge3target, 1]);
      moveQuality += evaluator.CalculateDistance(coordinates[edge1source, 0], coordinates[edge1source, 1],
        coordinates[edge2target, 0], coordinates[edge2target, 1]);
      return moveQuality;
    }
 public static double Apply(Permutation assignment, TranslocationMove move, DoubleMatrix weights, DoubleMatrix distances) {
   double moveQuality = 0;
   int min = Math.Min(move.Index1, move.Index3);
   int max = Math.Max(move.Index2, move.Index3 + (move.Index2 - move.Index1));
   int iOffset, changeOffset;
   if (move.Index1 < move.Index3) {
     iOffset = move.Index2 - move.Index1 + 1;
     changeOffset = min + max - move.Index2;
   } else {
     iOffset = move.Index1 - move.Index3;
     changeOffset = min + move.Index2 - move.Index1 + 1;
   }
   for (int i = min; i <= max; i++) {
     if (i == changeOffset) iOffset -= (max - min + 1);
     int jOffset = ((move.Index1 < move.Index3) ? (move.Index2 - move.Index1 + 1) : (move.Index1 - move.Index3));
     for (int j = 0; j < assignment.Length; j++) {
       moveQuality -= weights[i, j] * distances[assignment[i], assignment[j]];
       if (j < min || j > max) {
         moveQuality -= weights[j, i] * distances[assignment[j], assignment[i]];
         moveQuality += weights[i, j] * distances[assignment[i + iOffset], assignment[j]];
         moveQuality += weights[j, i] * distances[assignment[j], assignment[i + iOffset]];
       } else {
         if (j == changeOffset) jOffset -= (max - min + 1);
         moveQuality += weights[i, j] * distances[assignment[i + iOffset], assignment[j + jOffset]];
       }
     }
   }
   return moveQuality;
 }
        public static DoubleMatrix GetChannel(this MatrixBase<YCbCrColor> matrix,  ChannelType channelType)
        {
            var ret = new DoubleMatrix(matrix.RowCount, matrix.ColumnCount);

            for (int i = 0; i < matrix.RowCount; i++)
            {
                for (int j = 0; j < matrix.ColumnCount; j++)
                {
                    switch (channelType)
                    {
                        case ChannelType.Y:
                            ret[i, j] = matrix[i, j].Y;
                            break;
                        case ChannelType.Cr:
                            ret[i, j] = matrix[i, j].Cr;
                            break;
                        case ChannelType.Cb:
                            ret[i, j] = matrix[i, j].Cb;
                            break;
                        default:
                            throw new ArgumentOutOfRangeException("channelType");
                    }
                }
            }

            return ret;
        }
 /// <summary>
 /// Checks if all elements of the given <paramref name="vector"/> are inside the bounds and if not, elements are set to the respective values of the bounds.
 /// </summary>
 /// <param name="bounds">The lower and upper bound (1st and 2nd column) of the positions in the vector. If there are less rows than dimensions, the rows are cycled.</param>
 /// <param name="vector">The vector to check.</param>
 /// <returns>The corrected real vector.</returns>
 public static void Apply(RealVector vector, DoubleMatrix bounds) {
   for (int i = 0; i < vector.Length; i++) {
     double min = bounds[i % bounds.Rows, 0], max = bounds[i % bounds.Rows, 1];
     if (vector[i] < min) vector[i] = min;
     if (vector[i] > max) vector[i] = max;
   }
 }
    /// <summary>
    /// Performs the Kruskal-Shepard algorithm and applies a gradient descent method
    /// to fit the coordinates such that the difference between the fit distances
    /// and the dissimilarities is minimal.
    /// </summary>
    /// <remarks>
    /// It will use a pre-initialized x,y-coordinates matrix as a starting point of the gradient descent.
    /// </remarks>
    /// <param name="dissimilarities">A symmetric NxN matrix that specifies the dissimilarities between each element i and j. Diagonal elements are ignored.</param>
    /// <param name="coordinates">The Nx2 matrix of initial coordinates.</param>
    /// <param name="maximumIterations">The number of iterations for which the algorithm should run.
    /// In every iteration it tries to find the best location for every item.</param>
    /// <returns>A Nx2 matrix where the first column represents the x- and the second column the y coordinates.</returns>
    public static DoubleMatrix KruskalShepard(DoubleMatrix dissimilarities, DoubleMatrix coordinates, int maximumIterations = 10) {
      int dimension = dissimilarities.Rows;
      if (dimension != dissimilarities.Columns || coordinates.Rows != dimension) throw new ArgumentException("The number of coordinates and the number of rows and columns in the dissimilarities matrix do not match.");

      double epsg = 1e-7;
      double epsf = 0;
      double epsx = 0;
      int maxits = 0;

      alglib.minlmstate state;
      alglib.minlmreport rep;
      for (int iterations = 0; iterations < maximumIterations; iterations++) {
        bool changed = false;
        for (int i = 0; i < dimension; i++) {
          double[] c = new double[] { coordinates[i, 0], coordinates[i, 1] };

          try {
            alglib.minlmcreatevj(dimension - 1, c, out state);
            alglib.minlmsetcond(state, epsg, epsf, epsx, maxits);
            alglib.minlmoptimize(state, StressFitness, StressJacobian, null, new Info(coordinates, dissimilarities, i));
            alglib.minlmresults(state, out c, out rep);
          } catch (alglib.alglibexception) { }
          if (!double.IsNaN(c[0]) && !double.IsNaN(c[1])) {
            changed = changed || (coordinates[i, 0] != c[0]) || (coordinates[i, 1] != c[1]);
            coordinates[i, 0] = c[0];
            coordinates[i, 1] = c[1];
          }
        }
        if (!changed) break;
      }
      return coordinates;
    }
    static DoubleQRDecompTest()
    {        
      DoubleMatrix a = new DoubleMatrix(3);
      a[0,0] = -1.0;
      a[0,1] = 5.0;
      a[0,2] = 6.0;
      a[1,0] = 3.0;
      a[1,1] = -6.0;
      a[1,2] = 1.0;
      a[2,0] = 6.0;
      a[2,1] = 8.0;
      a[2,2] = 9.0;
      qr = new DoubleQRDecomp(a);

      a = new DoubleMatrix(2,3);
      a[0,0] = -1.0;
      a[0,1] = 5.0;
      a[0,2] = 6.0;
      a[1,0] = 3.0;
      a[1,1] = -6.0;
      a[1,2] = 1.0;
      wqr = new DoubleQRDecomp(a);

      a = new DoubleMatrix(3,2);
      a[0,0] = -1.0;
      a[0,1] = 5.0;
      a[1,0] = 3.0;
      a[1,1] = -6.0;
      a[2,0] = 6.0;
      a[2,1] = 8.0;
      lqr = new DoubleQRDecomp(a);
    }
    public static double CalculatePhenotypeDistance(Permutation a, Permutation b, DoubleMatrix weights, DoubleMatrix distances) {
      Dictionary<double, Dictionary<double, int>> alleles = new Dictionary<double, Dictionary<double, int>>();
      int distance = 0, len = a.Length;
      for (int x = 0; x < len; x++) {
        for (int y = 0; y < len; y++) {
          // there's a limited universe of double values as they're all drawn from the same matrix
          double dA = distances[a[x], a[y]], dB = distances[b[x], b[y]];
          if (dA == dB) continue;

          Dictionary<double, int> dAlleles;
          if (!alleles.ContainsKey(weights[x, y])) {
            dAlleles = new Dictionary<double, int>();
            alleles.Add(weights[x, y], dAlleles);
          } else dAlleles = alleles[weights[x, y]];

          int countA = 1, countB = -1;

          if (dAlleles.ContainsKey(dA)) countA += dAlleles[dA];
          if (dAlleles.ContainsKey(dB)) countB += dAlleles[dB];

          if (countA <= 0) distance--; // we've found in A an allele that was present in B
          else distance++; // we've found in A a new allele
          dAlleles[dA] = countA;

          if (countB >= 0) distance--; // we've found in B an allele that was present in A
          else distance++; // we've found in B a new allele
          dAlleles[dB] = countB;
        }
      }
      return distance / (double)(2 * len * len);
    }
 public void MichalewiczNonUniformAllPositionsManipulatorApplyTest() {
   TestRandom random = new TestRandom();
   RealVector parent, expected;
   DoubleValue generationsDependency;
   DoubleMatrix bounds;
   IntValue currentGeneration, maximumGenerations;
   bool exceptionFired;
   // The following test is not based on published examples
   random.Reset();
   random.DoubleNumbers = new double[] { 0.2, 0.5, 0.7, 0.8, 0.9, 0.5, 0.2, 0.5, 0.7, 0.8 };
   parent = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1 });
   expected = new RealVector(new double[] { 0.45, 0.22, 0.3, 0.6, 0.14 });
   bounds = new DoubleMatrix(new double[,] { { 0.3, 0.7 } });
   generationsDependency = new DoubleValue(0.1);
   currentGeneration = new IntValue(1);
   maximumGenerations = new IntValue(4);
   MichalewiczNonUniformAllPositionsManipulator.Apply(random, parent, bounds, currentGeneration, maximumGenerations, generationsDependency);
   Assert.IsTrue(Auxiliary.RealVectorIsAlmostEqualByPosition(expected, parent));
   // The following test is not based on published examples
   exceptionFired = false;
   random.Reset();
   random.DoubleNumbers = new double[] { 0.2, 0.5, 0.7, 0.8, 0.9, 0.5, 0.2, 0.5, 0.7, 0.8 };
   parent = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1 });
   bounds = new DoubleMatrix(new double[,] { { 0.3, 0.7 } });
   generationsDependency = new DoubleValue(0.1);
   currentGeneration = new IntValue(5); //current generation > max generation
   maximumGenerations = new IntValue(4);
   try {
     MichalewiczNonUniformAllPositionsManipulator.Apply(random, parent, bounds, currentGeneration, maximumGenerations, generationsDependency);
   } catch (System.ArgumentException) {
     exceptionFired = true;
   }
   Assert.IsTrue(exceptionFired);
 }
 private DoubleArray Randomize(IRandom random, int length, DoubleMatrix bounds) {
   var result = new DoubleArray(length);
   for (int i = 0; i < length; i++) {
     result[i] = random.NextDouble() * bounds[i % bounds.Rows, 1] - bounds[i % bounds.Rows, 0];
   }
   return result;
 }
Beispiel #16
0
 public void Calculate(DoubleMatrix i_TargetMapping)
 {
     if (m_SourceMapping != null)
     {
         m_PixelMapping = pixelMapping(m_SourceMapping, i_TargetMapping, m_MeshSize);
     }
 }
    internal static ArrayList run(IList para)
    {
        modshogun.init_shogun_with_defaults();
        int degree = (int)((int?)para[0]);

        string[] fm_train_dna = Load.load_dna("../data/fm_train_dna.dat");
        string[] fm_test_dna = Load.load_dna("../data/fm_test_dna.dat");

        StringCharFeatures feats_train = new StringCharFeatures(fm_train_dna, DNA);
        StringCharFeatures feats_test = new StringCharFeatures(fm_test_dna, DNA);

        WeightedDegreeStringKernel kernel = new WeightedDegreeStringKernel(feats_train, feats_train, degree);
        double[] w = new double[degree];
        double sum = degree * (degree + 1)/2;
        for (int i = 0; i < degree; i++)
        {
            w[i] = (degree - i)/sum;
        }

        DoubleMatrix weights = new DoubleMatrix(1, degree, w);
        kernel.set_wd_weights(weights);

        DoubleMatrix km_train = kernel.get_kernel_matrix();
        kernel.init(feats_train, feats_test);
        DoubleMatrix km_test = kernel.get_kernel_matrix();

        ArrayList result = new ArrayList();
        result.Add(km_train);
        result.Add(km_test);
        result.Add(kernel);
        modshogun.exit_shogun();
        return result;
    }
    /// <summary>
    /// Calculates the quality of the move <paramref name="move"/> by evaluating the changes.
    /// The runtime complexity of this method is O(N) with N being the size of the permutation.
    /// </summary>
    /// <param name="assignment">The current permutation.</param>
    /// <param name="move">The move that is to be evaluated if it was applied to the current permutation.</param>
    /// <param name="weights">The weights matrix.</param>
    /// <param name="distances">The distances matrix.</param>
    /// <returns>The relative change in quality if <paramref name="move"/> was applied to <paramref name="assignment"/>.</returns>
    public static double Apply(Permutation assignment, ScrambleMove move, DoubleMatrix weights, DoubleMatrix distances) {
      double moveQuality = 0;
      int min = move.StartIndex;
      int max = min + move.ScrambledIndices.Length - 1;

      for (int i = min; i <= max; i++) {
        int locI = assignment[i];
        int newlocI = assignment[min + move.ScrambledIndices[i - min]];
        if (locI == newlocI) continue;

        for (int j = 0; j < assignment.Length; j++) {
          int locJ = assignment[j];
          if (j >= min && j <= max) {
            int newlocJ = assignment[min + move.ScrambledIndices[j - min]];
            moveQuality += weights[i, j] * (distances[newlocI, newlocJ] - distances[locI, locJ]);
            if (locJ == newlocJ)
              moveQuality += weights[j, i] * (distances[newlocJ, newlocI] - distances[locJ, locI]);
          } else {
            moveQuality += weights[i, j] * (distances[newlocI, locJ] - distances[locI, locJ]);
            moveQuality += weights[j, i] * (distances[locJ, newlocI] - distances[locJ, locI]);
          }
        }
      }
      return moveQuality;
    }
Beispiel #19
0
 private QAPAssignment(QAPAssignment original, Cloner cloner)
   : base(original, cloner) {
   distances = cloner.Clone(original.distances);
   weights = cloner.Clone(original.weights);
   assignment = cloner.Clone(original.assignment);
   quality = cloner.Clone(original.quality);
 }
Beispiel #20
0
		/// <summary>Performs the QR factorization.</summary>
		protected override void InternalCompute()
		{
			int m = matrix.Rows;
			int n = matrix.Columns;

#if MANAGED
			int minmn = m < n ? m : n;
			r_ = new DoubleMatrix(matrix); // create a copy
			DoubleVector[] u = new DoubleVector[minmn];
			for (int i = 0; i < minmn; i++)
			{
				u[i] = Householder.GenerateColumn(r_, i, m - 1, i);
				Householder.UA(u[i], r_, i, m - 1, i + 1, n - 1);
			}
			q_ = DoubleMatrix.CreateIdentity(m);
			for (int i = minmn - 1; i >= 0; i--)
			{
				Householder.UA(u[i], q_, i, m - 1, i, m - 1);
			}
#else
      qr = new double[matrix.data.Length];
      Array.Copy(matrix.data, qr, matrix.data.Length);
      jpvt = new int[n];
      jpvt[0] = 1;
      Lapack.Geqp3.Compute(m, n, qr, m, jpvt, out tau);
      r_ = new DoubleMatrix(m, n);
      // Populate R
      for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
          if (i <= j) {
            r_.data[j * m + i] = qr[(jpvt[j]-1) * m + i];
          }
          else {
            r_.data[j * m + i] = 0.0;
          }
        }
      }
      q_ = new DoubleMatrix(m, m);
      for (int i = 0; i < m; i++) {
        for (int j = 0; j < m; j++) {
          if (j < n)
            q_.data[j * m + i] = qr[j * m + i];
          else
            q_.data[j * m + i] = 0.0;
        }
      }

      if( m < n ){
        Lapack.Orgqr.Compute(m, m, m, q_.data, m, tau);
      } else{
        Lapack.Orgqr.Compute(m, m, n, q_.data, m, tau);
      }
#endif
			for (int i = 0; i < m; i++)
			{
				if (q_[i, i] == 0)
					isFullRank = false;
			}
		}
Beispiel #21
0
 public void Calculate(DoubleMatrix i_SourceMapping, DoubleMatrix i_TargetMapping)
 {
     if (i_TargetMapping.RowsCount >= sr_TPSminNumOfSamples)
     {
         m_SourceMapping = i_SourceMapping;
         m_PixelMapping = pixelMapping(m_SourceMapping, i_TargetMapping, m_MeshSize);
     }
 }
Beispiel #22
0
 public static double Impact(int facility, Permutation assignment, DoubleMatrix weights, DoubleMatrix distances) {
   double impact = 0;
   for (int i = 0; i < assignment.Length; i++) {
     impact += weights[facility, i] * distances[assignment[facility], assignment[i]];
     impact += weights[i, facility] * distances[assignment[i], assignment[facility]];
   }
   return impact;
 }
Beispiel #23
0
 /// <summary>Instantiates a new 2d point using the provided augmented vector
 /// matrix as the underlying data source</summary>
 /// <param name="augmentedMatrix">Augmented 3x1 matrix containing the point coordinates</param>
 public Point2D(DoubleMatrix augmentedMatrix)
 {
     if (augmentedMatrix == null) throw new ArgumentNullException("augmentedMatrix");
     if (augmentedMatrix.RowCount != 1) throw new DimensionMismatchException();
     if (augmentedMatrix.ColumnCount != 3) throw new DimensionMismatchException();
     if (augmentedMatrix[0, 2] != 1) throw new ArgumentException("Point matrix does not appear to be an augmented 3x1 2-d point matrix in form [x, y, 1]", "augmentedMatrix");
     _matrix = augmentedMatrix;
 }
 /// <summary>
 /// Creating a matching object based on two sets of points.
 /// </summary>
 /// <param name="i_Source">2 x M1 points the first row is the X value, the second is the Y value</param>
 /// <param name="i_Target">2 x M2 points the first row is the X value, the second is the Y value</param>
 public PCAMatching(DoubleMatrix i_Source, DoubleMatrix i_Target)
 {
     if (i_Source.RowsCount != i_Target.RowsCount)
     {
         throw new PCAException("Cannot match between two sets with different dimensions");
     }
     m_SourceTransform = new PCAtransform(i_Source);
     m_TargetTransform = new PCAtransform(i_Target);
 }
Beispiel #25
0
 public static double Apply(Permutation assignment, DoubleMatrix weights, DoubleMatrix distances) {
   double quality = 0;
   for (int i = 0; i < assignment.Length; i++) {
     for (int j = 0; j < assignment.Length; j++) {
       quality += weights[i, j] * distances[assignment[i], assignment[j]];
     }
   }
   return quality;
 }
Beispiel #26
0
 public void Calculate(DoubleMatrix i_SourceMapping, DoubleMatrix i_TargetMapping, ref Point[] io_FullSet)
 {
     if (i_TargetMapping.RowsCount >= sr_TPSminNumOfSamples)
     {
         m_SourceMapping = i_SourceMapping;
         m_PixelMapping = pixelMapping(m_SourceMapping, i_TargetMapping, m_MeshSize);
         interpolate2D(m_MeshSize, m_PixelMapping, ref io_FullSet);
     }
 }
 public static double Apply(TSPCoordinatesPathEvaluator evaluator, DoubleMatrix coordinates, Permutation tour) {
   DoubleMatrix c = coordinates;
   Permutation p = tour;
   double length = 0;
   for (int i = 0; i < p.Length - 1; i++)
     length += evaluator.CalculateDistance(c[p[i], 0], c[p[i], 1], c[p[i + 1], 0], c[p[i + 1], 1]);
   length += evaluator.CalculateDistance(c[p[p.Length - 1], 0], c[p[p.Length - 1], 1], c[p[0], 0], c[p[0], 1]);
   return length;
 }
 protected override void Content_CorrelationCalculationFinished(object sender, FeatureCorrelationCalculator.CorrelationCalculationFinishedArgs e) {
   if (InvokeRequired) {
     Invoke(new FeatureCorrelationCalculator.CorrelationCalculationFinishedHandler(Content_CorrelationCalculationFinished), sender, e);
     return;
   }
   correlationCache.SetCorrelation(e.Calculcator, e.Partition, e.Correlation);
   var correlation = new DoubleMatrix(e.Correlation, Content.Dataset.DoubleVariables, Content.Dataset.DoubleVariables);
   UpdateDataView(correlation);
 }
        /// <summary>
        /// returns a DoubleMatrix with the given band structure planarised in the transverse direction
        /// </summary>
        public static Band_Data Expand_BandStructure(DoubleVector structure, int ny)
        {
            DoubleMatrix result = new DoubleMatrix(ny, structure.Length);
            for (int i = 0; i < ny; i++)
                for (int j = 0; j < structure.Length; j++)
                    result[i, j] = structure[j];

            return new Band_Data(result);
        }
Beispiel #30
0
        public static void SubstractScalarsByDims(ref DoubleMatrix io_leftHandMatrix, DoubleMatrix i_rightHandVector)
        {
            if ((i_rightHandVector.ColumnsCount > 1) || (io_leftHandMatrix.RowsCount != i_rightHandVector.RowsCount))
            {
                throw new PCAException("Dimension are not meet for substraction of a vector from matrix by rows");
            }

            Func<int, int, double, double> substractByDim = (row, col, Val) => (Val - (double)i_rightHandVector[row, 0]);
            io_leftHandMatrix.Iterate(substractByDim);
        }
 public override double Calculate(int from, int to, DoubleMatrix coordinates)
 {
     return(DistanceHelper.GetDistance(DistanceMeasure.UpperEuclidean, coordinates[from, 0], coordinates[from, 1], coordinates[to, 0], coordinates[to, 1]));
 }
Beispiel #32
0
        public static double CalculatePhenotypeDistance(Permutation a, Permutation b, DoubleMatrix weights, DoubleMatrix distances)
        {
            Dictionary <double, Dictionary <double, int> > alleles = new Dictionary <double, Dictionary <double, int> >();
            int distance = 0, len = a.Length;

            for (int x = 0; x < len; x++)
            {
                for (int y = 0; y < len; y++)
                {
                    // there's a limited universe of double values as they're all drawn from the same matrix
                    double dA = distances[a[x], a[y]], dB = distances[b[x], b[y]];
                    if (dA == dB)
                    {
                        continue;
                    }

                    Dictionary <double, int> dAlleles;
                    if (!alleles.ContainsKey(weights[x, y]))
                    {
                        dAlleles = new Dictionary <double, int>();
                        alleles.Add(weights[x, y], dAlleles);
                    }
                    else
                    {
                        dAlleles = alleles[weights[x, y]];
                    }

                    int countA = 1, countB = -1;

                    if (dAlleles.ContainsKey(dA))
                    {
                        countA += dAlleles[dA];
                    }
                    if (dAlleles.ContainsKey(dB))
                    {
                        countB += dAlleles[dB];
                    }

                    if (countA <= 0)
                    {
                        distance--;    // we've found in A an allele that was present in B
                    }
                    else
                    {
                        distance++; // we've found in A a new allele
                    }
                    dAlleles[dA] = countA;

                    if (countB >= 0)
                    {
                        distance--;    // we've found in B an allele that was present in A
                    }
                    else
                    {
                        distance++; // we've found in B a new allele
                    }
                    dAlleles[dB] = countB;
                }
            }
            return(distance / (double)(2 * len * len));
        }
            internal static DoubleArray nodeSensitivity(double xValue, DoubleArray knots, DoubleMatrix coefMatrix, int dimensions, int interval, DoubleMatrix coefficientSensitivity)
            {
                double s      = xValue - knots.get(interval);
                int    nCoefs = coefficientSensitivity.rowCount();

                DoubleArray res = coefficientSensitivity.row(0);

                for (int i = 1; i < nCoefs; i++)
                {
                    res = (DoubleArray)MA.scale(res, s);
                    res = (DoubleArray)MA.add(res, coefficientSensitivity.row(i));
                }
                return(res);
            }
        static TestableSpectralDecomposition01()
        {
            double[] realArray = new double[9] {
                2,
                2,
                0,
                2,
                0,
                0,
                0,
                0,
                5
            };
            double[] imaginaryArray = new double[9] {
                0,
                1,
                0,
                -1,
                0,
                0,
                0,
                0,
                0
            };

            var complexArray = new Complex[9];

            for (int i = 0; i < 9; i++)
            {
                complexArray[i] = new Complex(realArray[i], imaginaryArray[i]);
            }

            testableMatrix = new TestableComplexMatrix(
                asColumnMajorDenseArray: complexArray,
                numberOfRows: 3,
                numberOfColumns: 3,
                isUpperHessenberg: false,
                isLowerHessenberg: false,
                isUpperTriangular: false,
                isLowerTriangular: false,
                isSymmetric: false,
                isSkewSymmetric: false,
                isHermitian: false,
                isSkewHermitian: false,
                upperBandwidth: 0,
                lowerBandwidth: 2);

            values       = DoubleMatrix.Dense(3, 3);
            values[0, 0] = -1.449489742783178;
            values[1, 1] = 3.449489742783178;
            values[2, 2] = 5;

            vectorsIfLower = ComplexMatrix.Dense(3, 3, new Complex[9] {
                -0.543944717,
                new Complex(0.750532688, 0.375266344),
                0,
                -0.839121055171381,
                new Complex(-0.486518945, -0.243259472),
                0,
                0,
                0,
                1
            });

            vectorsIfUpper = ComplexMatrix.Dense(3, 3, new Complex[9] {
                new Complex(0.486518945, -0.243259472),
                -0.839121055171381,
                0,
                new Complex(0.750532688, -0.375266344),
                0.543944717,
                0,
                0,
                0,
                1
            });
        }
Beispiel #35
0
 public LAPAssignment(DoubleMatrix costs, StringArray rowNames, StringArray columnNames, Permutation assignment)
     : this(costs, assignment)
 {
     this.rowNames    = rowNames;
     this.columnNames = columnNames;
 }
Beispiel #36
0
 public LAPAssignment(DoubleMatrix costs, Permutation assignment)
 {
     this.costs      = costs;
     this.assignment = assignment;
 }
        /// <summary>
        /// Mutates the endogenous strategy parameters.
        /// </summary>
        /// <param name="random">The random number generator to use.</param>
        /// <param name="vector">The strategy vector to manipulate.</param>
        /// <param name="generalLearningRate">The general learning rate dampens the mutation over all dimensions.</param>
        /// <param name="learningRate">The learning rate dampens the mutation in each dimension.</param>
        /// <param name="bounds">The minimal and maximal value for each component, bounds are cycled if the length of bounds is smaller than the length of vector</param>
        public static void Apply(IRandom random, DoubleArray vector, double generalLearningRate, double learningRate, DoubleMatrix bounds)
        {
            NormalDistributedRandom N = new NormalDistributedRandom(random, 0.0, 1.0);
            double generalMultiplier  = Math.Exp(generalLearningRate * N.NextDouble());

            for (int i = 0; i < vector.Length; i++)
            {
                double change = vector[i] * generalMultiplier *Math.Exp(learningRate *N.NextDouble());

                if (bounds != null)
                {
                    double min = bounds[i % bounds.Rows, 0], max = bounds[i % bounds.Rows, 1];
                    if (min == max)
                    {
                        vector[i] = min;
                    }
                    else
                    {
                        if (change < min || change > max)
                        {
                            change = Math.Max(min, Math.Min(max, change));
                        }
                        vector[i] = change;
                    }
                }
            }
        }
Beispiel #38
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
//ORIGINAL LINE: @Override public PiecewisePolynomialResult2D interpolate(final double[] x0Values, final double[] x1Values, final double[][] yValues)
        public override PiecewisePolynomialResult2D interpolate(double[] x0Values, double[] x1Values, double[][] yValues)
        {
            ArgChecker.notNull(x0Values, "x0Values");
            ArgChecker.notNull(x1Values, "x1Values");
            ArgChecker.notNull(yValues, "yValues");

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int nData0 = x0Values.length;
            int nData0 = x0Values.Length;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int nData1 = x1Values.length;
            int nData1 = x1Values.Length;

            DoubleMatrix yValuesMatrix = DoubleMatrix.copyOf(yValues);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final com.opengamma.strata.math.impl.function.PiecewisePolynomialFunction1D func = new com.opengamma.strata.math.impl.function.PiecewisePolynomialFunction1D();
            PiecewisePolynomialFunction1D func = new PiecewisePolynomialFunction1D();

//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] diff0 = new double[nData1][nData0];
            double[][] diff0 = RectangularArrays.ReturnRectangularDoubleArray(nData1, nData0);
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] diff1 = new double[nData0][nData1];
            double[][] diff1 = RectangularArrays.ReturnRectangularDoubleArray(nData0, nData1);
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] cross = new double[nData0][nData1];
            double[][] cross = RectangularArrays.ReturnRectangularDoubleArray(nData0, nData1);

            PiecewisePolynomialResult result0 = _method[0].interpolate(x0Values, OG_ALGEBRA.getTranspose(yValuesMatrix).toArray());

            diff0 = func.differentiate(result0, x0Values).toArray();

            PiecewisePolynomialResult result1 = _method[1].interpolate(x1Values, yValuesMatrix.toArray());

            diff1 = func.differentiate(result1, x1Values).toArray();

            const int order = 4;

            for (int i = 0; i < nData0; ++i)
            {
                for (int j = 0; j < nData1; ++j)
                {
                    if (yValues[i][j] == 0.0)
                    {
                        if (diff0[j][i] == 0.0)
                        {
                            cross[i][j] = diff1[i][j];
                        }
                        else
                        {
                            if (diff1[i][j] == 0.0)
                            {
                                cross[i][j] = diff0[j][i];
                            }
                            else
                            {
                                cross[i][j] = Math.Sign(diff0[j][i] * diff1[i][j]) * Math.Sqrt(Math.Abs(diff0[j][i] * diff1[i][j]));
                            }
                        }
                    }
                    else
                    {
                        cross[i][j] = diff0[j][i] * diff1[i][j] / yValues[i][j];
                    }
                }
            }

//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: DoubleMatrix[][] coefMat = new DoubleMatrix[nData0 - 1][nData1 - 1];
            DoubleMatrix[][] coefMat = RectangularArrays.ReturnRectangularDoubleMatrixArray(nData0 - 1, nData1 - 1);
            for (int i = 0; i < nData0 - 1; ++i)
            {
                for (int j = 0; j < nData1 - 1; ++j)
                {
                    double[] diffsVec = new double[16];
                    for (int l = 0; l < 2; ++l)
                    {
                        for (int m = 0; m < 2; ++m)
                        {
                            diffsVec[l + 2 * m] = yValues[i + l][j + m];
                        }
                    }
                    for (int l = 0; l < 2; ++l)
                    {
                        for (int m = 0; m < 2; ++m)
                        {
                            diffsVec[4 + l + 2 * m] = diff0[j + m][i + l];
                        }
                    }
                    for (int l = 0; l < 2; ++l)
                    {
                        for (int m = 0; m < 2; ++m)
                        {
                            diffsVec[8 + l + 2 * m] = diff1[i + l][j + m];
                        }
                    }
                    for (int l = 0; l < 2; ++l)
                    {
                        for (int m = 0; m < 2; ++m)
                        {
                            diffsVec[12 + l + 2 * m] = cross[i + l][j + m];
                        }
                    }
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final com.opengamma.strata.collect.array.DoubleArray diffs = com.opengamma.strata.collect.array.DoubleArray.copyOf(diffsVec);
                    DoubleArray diffs = DoubleArray.copyOf(diffsVec);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final com.opengamma.strata.collect.array.DoubleArray ansVec = ((com.opengamma.strata.collect.array.DoubleArray) OG_ALGEBRA.multiply(INV_MAT, diffs));
                    DoubleArray ansVec = ((DoubleArray)OG_ALGEBRA.multiply(INV_MAT, diffs));

                    double @ref = 0.0;
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] coefMatTmp = new double[order][order];
                    double[][] coefMatTmp = RectangularArrays.ReturnRectangularDoubleArray(order, order);
                    for (int l = 0; l < order; ++l)
                    {
                        for (int m = 0; m < order; ++m)
                        {
                            coefMatTmp[order - l - 1][order - m - 1] = ansVec.get(l + m * (order)) / Math.Pow((x0Values[i + 1] - x0Values[i]), l) / Math.Pow((x1Values[j + 1] - x1Values[j]), m);
                            ArgChecker.isFalse(double.IsNaN(coefMatTmp[order - l - 1][order - m - 1]), "Too large/small input");
                            ArgChecker.isFalse(double.IsInfinity(coefMatTmp[order - l - 1][order - m - 1]), "Too large/small input");
                            @ref += coefMatTmp[order - l - 1][order - m - 1] * Math.Pow((x0Values[i + 1] - x0Values[i]), l) * Math.Pow((x1Values[j + 1] - x1Values[j]), m);
                        }
                    }
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final double bound = Math.max(Math.abs(ref) + Math.abs(yValues[i + 1][j + 1]), 0.1);
                    double bound = Math.Max(Math.Abs(@ref) + Math.Abs(yValues[i + 1][j + 1]), 0.1);
                    ArgChecker.isTrue(Math.Abs(@ref - yValues[i + 1][j + 1]) < ERROR * bound, "Input is too large/small or data points are too close");
                    coefMat[i][j] = DoubleMatrix.copyOf(coefMatTmp);
                }
            }

            return(new PiecewisePolynomialResult2D(DoubleArray.copyOf(x0Values), DoubleArray.copyOf(x1Values), coefMat, new int[] { order, order }));
        }
Beispiel #39
0
        public static double Apply(Permutation assignment, InversionMove move, DoubleMatrix weights, DoubleMatrix distances)
        {
            if (move.Index1 == move.Index2)
            {
                return(0);
            }
            double moveQuality = 0;
            int    min         = Math.Min(move.Index1, move.Index2);
            int    max         = Math.Max(move.Index1, move.Index2);

            for (int i = min; i <= max; i++)
            {
                int locI    = assignment[i];
                int newlocI = assignment[max - i + min];

                for (int j = 0; j < assignment.Length; j++)
                {
                    int locJ = assignment[j];
                    if (j >= min && j <= max)
                    {
                        int newlocJ = assignment[max - j + min];
                        moveQuality += weights[i, j] * (distances[newlocI, newlocJ] - distances[locI, locJ]);
                    }
                    else
                    {
                        moveQuality += weights[i, j] * (distances[newlocI, locJ] - distances[locI, locJ]);
                        moveQuality += weights[j, i] * (distances[locJ, newlocI] - distances[locJ, locI]);
                    }
                }
            }
            return(moveQuality);
        }
Beispiel #40
0
 /// <summary>
 /// Obtains an instance of the raw data with error for shifted Black (log-normal) volatility.
 /// </summary>
 /// <param name="expiries">  the expiries </param>
 /// <param name="strikes">  the strikes-like data </param>
 /// <param name="strikeType">  the value type of the strike-like dimension </param>
 /// <param name="data">  the data </param>
 /// <param name="error">  the error </param>
 /// <param name="shift">  the shift </param>
 /// <returns> the instance </returns>
 public static RawOptionData ofBlackVolatility(IList <Period> expiries, DoubleArray strikes, ValueType strikeType, DoubleMatrix data, DoubleMatrix error, double?shift)
 {
     ArgChecker.isTrue(expiries.Count == data.rowCount(), "expiries list should be of the same size as the external data dimension");
     for (int i = 0; i < expiries.Count; i++)
     {
         ArgChecker.isTrue(strikes.size() == data.columnCount(), "strikes should be of the same size as the inner data dimension");
     }
     return(new RawOptionData(expiries, strikes, strikeType, data, error, ValueType.BLACK_VOLATILITY, shift));
 }
        public void Load(TSPData data)
        {
            if (data.Coordinates == null && data.Distances == null)
            {
                throw new System.IO.InvalidDataException("The given instance specifies neither coordinates nor distances!");
            }
            if (data.Dimension > DistanceMatrixSizeLimit && (data.DistanceMeasure == DistanceMeasure.Att ||
                                                             data.DistanceMeasure == DistanceMeasure.Manhattan ||
                                                             data.DistanceMeasure == DistanceMeasure.Maximum))
            {
                throw new System.IO.InvalidDataException("The given instance uses an unsupported distance measure and is too large for using a distance matrix.");
            }
            if (data.Coordinates != null && data.Coordinates.GetLength(1) != 2)
            {
                throw new System.IO.InvalidDataException("The coordinates of the given instance are not in the right format, there need to be one row for each customer and two columns for the x and y coordinates.");
            }

            Name        = data.Name;
            Description = data.Description;

            bool clearCoordinates = false, clearDistanceMatrix = false;

            if (data.Coordinates != null && data.Coordinates.GetLength(0) > 0)
            {
                Coordinates = new DoubleMatrix(data.Coordinates);
            }
            else
            {
                clearCoordinates = true;
            }

            TSPEvaluator evaluator;

            if (data.DistanceMeasure == DistanceMeasure.Att ||
                data.DistanceMeasure == DistanceMeasure.Manhattan ||
                data.DistanceMeasure == DistanceMeasure.Maximum)
            {
                evaluator         = new TSPDistanceMatrixEvaluator();
                UseDistanceMatrix = new BoolValue(true);
                DistanceMatrix    = new DistanceMatrix(data.GetDistanceMatrix());
            }
            else if (data.DistanceMeasure == DistanceMeasure.Direct && data.Distances != null)
            {
                evaluator         = new TSPDistanceMatrixEvaluator();
                UseDistanceMatrix = new BoolValue(true);
                DistanceMatrix    = new DistanceMatrix(data.Distances);
            }
            else
            {
                clearDistanceMatrix = true;
                UseDistanceMatrix   = new BoolValue(data.Dimension <= DistanceMatrixSizeLimit);
                switch (data.DistanceMeasure)
                {
                case DistanceMeasure.Euclidean:
                    evaluator = new TSPEuclideanPathEvaluator();
                    break;

                case DistanceMeasure.RoundedEuclidean:
                    evaluator = new TSPRoundedEuclideanPathEvaluator();
                    break;

                case DistanceMeasure.UpperEuclidean:
                    evaluator = new TSPUpperEuclideanPathEvaluator();
                    break;

                case DistanceMeasure.Geo:
                    evaluator = new TSPGeoPathEvaluator();
                    break;

                default:
                    throw new InvalidDataException("An unknown distance measure is given in the instance!");
                }
            }
            evaluator.QualityParameter.ActualName = "TSPTourLength";
            Evaluator = evaluator;

            // reset them after assigning the evaluator
            if (clearCoordinates)
            {
                Coordinates = null;
            }
            if (clearDistanceMatrix)
            {
                DistanceMatrix = null;
            }

            BestKnownSolution = null;
            BestKnownQuality  = null;

            if (data.BestKnownTour != null)
            {
                try {
                    EvaluateAndLoadTour(data.BestKnownTour);
                } catch (InvalidOperationException) {
                    if (data.BestKnownQuality.HasValue)
                    {
                        BestKnownQuality = new DoubleValue(data.BestKnownQuality.Value);
                    }
                }
            }
            else if (data.BestKnownQuality.HasValue)
            {
                BestKnownQuality = new DoubleValue(data.BestKnownQuality.Value);
            }
            OnReset();
        }
        public void SolveMatrix()
        {
            DoubleMatrix b = new DoubleMatrix(3);

            b[0, 0] = 2;
            b[0, 1] = 2;
            b[0, 2] = 2;
            b[1, 0] = 13;
            b[1, 1] = 13;
            b[1, 2] = 13;
            b[2, 0] = 25;
            b[2, 1] = 25;
            b[2, 2] = 25;
            DoubleMatrix x = qr.Solve(b);

            Assert.AreEqual(x[0, 0], 2.965, TOLERENCE);
            Assert.AreEqual(x[0, 1], 2.965, TOLERENCE);
            Assert.AreEqual(x[0, 2], 2.965, TOLERENCE);
            Assert.AreEqual(x[1, 0], -0.479, TOLERENCE);
            Assert.AreEqual(x[1, 1], -0.479, TOLERENCE);
            Assert.AreEqual(x[1, 2], -0.479, TOLERENCE);
            Assert.AreEqual(x[2, 0], 1.227, TOLERENCE);
            Assert.AreEqual(x[2, 1], 1.227, TOLERENCE);
            Assert.AreEqual(x[2, 2], 1.227, TOLERENCE);

            b       = new DoubleMatrix(3, 2);
            b[0, 0] = 2;
            b[0, 1] = 2;
            b[1, 0] = 13;
            b[1, 1] = 13;
            b[2, 0] = 25;
            b[2, 1] = 25;
            x       = qr.Solve(b);
            Assert.AreEqual(x[0, 0], 2.965, TOLERENCE);
            Assert.AreEqual(x[0, 1], 2.965, TOLERENCE);
            Assert.AreEqual(x[1, 0], -0.479, TOLERENCE);
            Assert.AreEqual(x[1, 1], -0.479, TOLERENCE);
            Assert.AreEqual(x[2, 0], 1.227, TOLERENCE);
            Assert.AreEqual(x[2, 1], 1.227, TOLERENCE);

            b       = new DoubleMatrix(3, 4);
            b[0, 0] = 2;
            b[0, 1] = 2;
            b[0, 2] = 2;
            b[0, 3] = 2;
            b[1, 0] = 13;
            b[1, 1] = 13;
            b[1, 2] = 13;
            b[1, 3] = 13;
            b[2, 0] = 25;
            b[2, 1] = 25;
            b[2, 2] = 25;
            b[2, 3] = 25;
            x       = qr.Solve(b);
            Assert.AreEqual(x[0, 0], 2.965, TOLERENCE);
            Assert.AreEqual(x[0, 1], 2.965, TOLERENCE);
            Assert.AreEqual(x[0, 2], 2.965, TOLERENCE);
            Assert.AreEqual(x[0, 3], 2.965, TOLERENCE);
            Assert.AreEqual(x[1, 0], -0.479, TOLERENCE);
            Assert.AreEqual(x[1, 1], -0.479, TOLERENCE);
            Assert.AreEqual(x[1, 2], -0.479, TOLERENCE);
            Assert.AreEqual(x[1, 3], -0.479, TOLERENCE);
            Assert.AreEqual(x[2, 0], 1.227, TOLERENCE);
            Assert.AreEqual(x[2, 1], 1.227, TOLERENCE);
            Assert.AreEqual(x[2, 2], 1.227, TOLERENCE);
            Assert.AreEqual(x[2, 3], 1.227, TOLERENCE);

            DoubleMatrix A = new DoubleMatrix(4, 3);

            A[0, 0] = -4.18;
            A[0, 1] = -5.011;
            A[0, 2] = -5.841;
            A[1, 0] = 4.986;
            A[1, 1] = 5.805;
            A[1, 2] = 6.624;
            A[2, 0] = 3.695;
            A[2, 1] = 3.687;
            A[2, 2] = 3.679;
            A[3, 0] = -5.489;
            A[3, 1] = -7.024;
            A[3, 2] = 8.56;

            DoubleQRDecomp qrd = new DoubleQRDecomp(A);
            DoubleMatrix   B   = new DoubleMatrix(4, 1);

            B[0, 0] = 1;
            B[1, 0] = 4;
            B[2, 0] = 2;
            B[3, 0] = 1;

            x = qrd.Solve(B);
            Assert.AreEqual(x[0, 0], 2.73529, TOLERENCE);
            Assert.AreEqual(x[1, 0], -2.15822, TOLERENCE);
            Assert.AreEqual(x[2, 0], 0.0998564, TOLERENCE);

            B       = new DoubleMatrix(4, 3);
            B[0, 0] = 1;
            B[1, 0] = 4;
            B[2, 0] = 2;
            B[3, 0] = 1;
            B[0, 1] = 1;
            B[1, 1] = 4;
            B[2, 1] = 2;
            B[3, 1] = 1;
            B[0, 2] = 1;
            B[1, 2] = 4;
            B[2, 2] = 2;
            B[3, 2] = 1;

            x = qrd.Solve(B);
            Assert.AreEqual(x[0, 0], 2.73529, TOLERENCE);
            Assert.AreEqual(x[1, 0], -2.15822, TOLERENCE);
            Assert.AreEqual(x[2, 0], 0.0998564, TOLERENCE);
            Assert.AreEqual(x[0, 1], 2.73529, TOLERENCE);
            Assert.AreEqual(x[1, 1], -2.15822, TOLERENCE);
            Assert.AreEqual(x[2, 1], 0.0998564, TOLERENCE);
            Assert.AreEqual(x[0, 2], 2.73529, TOLERENCE);
            Assert.AreEqual(x[1, 2], -2.15822, TOLERENCE);
            Assert.AreEqual(x[2, 2], 0.0998564, TOLERENCE);
        }
        public void Main()
        {
            // Create the context.
            var context = new RareShortestPathProbabilityEstimation();

            // Create the estimator.
            var estimator = new RareEventProbabilityEstimator()
            {
                PerformanceEvaluationParallelOptions = { MaxDegreeOfParallelism = 1 },
                SampleGenerationParallelOptions      = { MaxDegreeOfParallelism = 1 }
            };

            // Set estimation parameters.
            double rarity          = 0.1;
            int    sampleSize      = 1000;
            int    finalSampleSize = 10000;

            // Solve the problem.
            var results = estimator.Estimate(
                context,
                rarity,
                sampleSize,
                finalSampleSize);

            // Show the results.
            Console.WriteLine("Under the nominal parameter:");
            Console.WriteLine(context.InitialParameter);
            Console.WriteLine("the estimated probability of observing");
            Console.WriteLine("a shortest path greater than 2.0 is:");
            Console.WriteLine(results.RareEventProbability);

            Console.WriteLine();
            Console.WriteLine("Details on iterations:");

            var info = DoubleMatrix.Dense(
                -1 + results.Parameters.Count,
                1 + results.Parameters.Last.Value.Count);

            info.SetColumnName(0, "Level");
            for (int j = 1; j < info.NumberOfColumns; j++)
            {
                info.SetColumnName(j, "Param" + (j - 1).ToString());
            }

            int i = 0;

            foreach (var level in results.Levels)
            {
                info[i++, 0] = level;
            }

            var referenceParameters = results.Parameters.Skip(1).ToList();
            var paramIndexes        = IndexCollection.Range(1, info.NumberOfColumns - 1);

            for (i = 0; i < info.NumberOfRows; i++)
            {
                info[i, paramIndexes] = referenceParameters[i];
            }

            Console.WriteLine();
            Console.WriteLine(info);
        }
Beispiel #44
0
 //-------------------------------------------------------------------------
 /// <summary>
 /// Obtains an instance of the raw volatility.
 /// <para>
 /// The data values can be model parameters (like Black or normal volatilities) or direct option prices.
 ///
 /// </para>
 /// </summary>
 /// <param name="expiries">  the expiries </param>
 /// <param name="strikes">  the strikes-like data </param>
 /// <param name="strikeType">  the value type of the strike-like dimension </param>
 /// <param name="data">  the data </param>
 /// <param name="dataType">  the data type </param>
 /// <returns> the instance </returns>
 public static RawOptionData of(IList <Period> expiries, DoubleArray strikes, ValueType strikeType, DoubleMatrix data, ValueType dataType)
 {
     ArgChecker.isTrue(expiries.Count == data.rowCount(), "expiries list should be of the same size as the external data dimension");
     for (int i = 0; i < expiries.Count; i++)
     {
         ArgChecker.isTrue(strikes.size() == data.columnCount(), "strikes should be of the same size as the inner data dimension");
     }
     return(new RawOptionData(expiries, strikes, strikeType, data, null, dataType, 0.0));
 }
Beispiel #45
0
        public virtual void sensitivity_multi_combined_curve()
        {
            CrossGammaParameterSensitivities sensiCrossComputed = CENTRAL.calculateCrossGammaCrossCurve(RatesProviderDataSets.MULTI_CPI_USD_COMBINED, this.sensiCombinedFn);
            DoubleArray times1      = RatesProviderDataSets.TIMES_1; // ois
            DoubleArray times2      = RatesProviderDataSets.TIMES_2; // l3
            DoubleArray times3      = RatesProviderDataSets.TIMES_3; // l6
            DoubleArray times4      = RatesProviderDataSets.TIMES_4; // cpi
            int         paramsTotal = times1.size() + times2.size() + times3.size() + times4.size();

            double[]    timesTotal  = new double[paramsTotal];
            DoubleArray times1Twice = times1.multipliedBy(2d);

            Array.Copy(times4.toArray(), 0, timesTotal, 0, times4.size());
            Array.Copy(times1Twice.toArray(), 0, timesTotal, times4.size(), times1.size());
            Array.Copy(times2.toArray(), 0, timesTotal, times1.size() + times4.size(), times2.size());
            Array.Copy(times3.toArray(), 0, timesTotal, times1.size() + times2.size() + times4.size(), times3.size());

            assertEquals(sensiCrossComputed.size(), 4);
            DoubleMatrix s1 = sensiCrossComputed.getSensitivity(RatesProviderDataSets.USD_DSC_NAME, USD).Sensitivity;

            assertEquals(s1.columnCount(), paramsTotal);
            for (int i = 0; i < times1.size(); i++)
            {
                for (int j = 0; j < paramsTotal; j++)
                {
                    double expected = 4d * times1.get(i) * timesTotal[j];
                    assertEquals(s1.get(i, j), expected, Math.Max(Math.Abs(expected), 1d) * EPS * 10d);
                }
            }
            DoubleMatrix s2 = sensiCrossComputed.getSensitivity(RatesProviderDataSets.USD_L3_NAME, USD).Sensitivity;

            assertEquals(s2.columnCount(), paramsTotal);
            for (int i = 0; i < times2.size(); i++)
            {
                for (int j = 0; j < paramsTotal; j++)
                {
                    double expected = 8d * times2.get(i) * timesTotal[j];
                    assertEquals(s2.get(i, j), expected, Math.Max(Math.Abs(expected), 1d) * EPS * 10d);
                }
            }
            DoubleMatrix s3 = sensiCrossComputed.getSensitivity(RatesProviderDataSets.USD_L6_NAME, USD).Sensitivity;

            assertEquals(s3.columnCount(), paramsTotal);
            for (int i = 0; i < times3.size(); i++)
            {
                for (int j = 0; j < paramsTotal; j++)
                {
                    double expected = 2d * times3.get(i) * timesTotal[j];
                    assertEquals(s3.get(i, j), expected, Math.Max(Math.Abs(expected), 1d) * EPS * 10d);
                }
            }
            DoubleMatrix s4 = sensiCrossComputed.getSensitivity(RatesProviderDataSets.USD_CPI_NAME, USD).Sensitivity;

            assertEquals(s4.columnCount(), paramsTotal);
            for (int i = 0; i < times4.size(); i++)
            {
                for (int j = 0; j < paramsTotal; j++)
                {
                    double expected = 2d * times4.get(i) * timesTotal[j];
                    assertEquals(s4.get(i, j), expected, Math.Max(Math.Abs(expected), 1d) * EPS * 20d);
                }
            }

            CrossGammaParameterSensitivities sensiIntraComputed = CENTRAL.calculateCrossGammaIntraCurve(RatesProviderDataSets.MULTI_CPI_USD_COMBINED, this.sensiCombinedFn);
            DoubleMatrix s1Intra   = sensiIntraComputed.getSensitivity(RatesProviderDataSets.USD_DSC_NAME, USD).Sensitivity;
            DoubleMatrix s2Intra   = sensiIntraComputed.getSensitivity(RatesProviderDataSets.USD_L3_NAME, USD).Sensitivity;
            DoubleMatrix s3Intra   = sensiIntraComputed.getSensitivity(RatesProviderDataSets.USD_L6_NAME, USD).Sensitivity;
            DoubleMatrix s4Intra   = sensiIntraComputed.getSensitivity(RatesProviderDataSets.USD_CPI_NAME, USD).Sensitivity;
            int          offsetOis = times4.size();

            for (int i = 0; i < times1.size(); i++)
            {
                for (int j = 0; j < times1.size(); j++)
                {
                    assertEquals(s1Intra.get(i, j), s1.get(i, offsetOis + j), TOL);
                }
            }
            int offset3m = times4.size() + times1.size();

            for (int i = 0; i < times2.size(); i++)
            {
                for (int j = 0; j < times2.size(); j++)
                {
                    assertEquals(s2Intra.get(i, j), s2.get(i, offset3m + j), TOL);
                }
            }
            int offset6m = times4.size() + times1.size() + times2.size();

            for (int i = 0; i < times3.size(); i++)
            {
                for (int j = 0; j < times3.size(); j++)
                {
                    assertEquals(s3Intra.get(i, j), s3.get(i, offset6m + j), TOL);
                }
            }
            for (int i = 0; i < times4.size(); i++)
            {
                for (int j = 0; j < times4.size(); j++)
                {
                    assertEquals(s4Intra.get(i, j), s4.get(i, j), TOL);
                }
            }
        }
Beispiel #46
0
        public static void SubstractScalarsByDims(ref DoubleMatrix io_leftHandMatrix, DoubleMatrix i_rightHandVector)
        {
            if ((i_rightHandVector.ColumnsCount > 1) || (io_leftHandMatrix.RowsCount != i_rightHandVector.RowsCount))
            {
                throw new PCAException("Dimension are not meet for substraction of a vector from matrix by rows");
            }

            Func <int, int, double, double> substractByDim = (row, col, Val) => (Val - (double)i_rightHandVector[row, 0]);

            io_leftHandMatrix.Iterate(substractByDim);
        }
Beispiel #47
0
        protected override void DrawVisualization(Bitmap bitmap)
        {
            DoubleMatrix coordinates       = Content.Coordinates;
            DoubleMatrix distanceMatrix    = Content.DistanceMatrix;
            BoolValue    useDistanceMatrix = Content.UseDistanceMatrix;
            DoubleArray  dueTime           = Content.DueTime;
            DoubleArray  serviceTime       = Content.ServiceTime;
            DoubleArray  readyTime         = Content.ReadyTime;

            if ((coordinates != null) && (coordinates.Rows > 0) && (coordinates.Columns == 2))
            {
                double xMin = double.MaxValue, yMin = double.MaxValue, xMax = double.MinValue, yMax = double.MinValue;
                for (int i = 0; i < coordinates.Rows; i++)
                {
                    if (xMin > coordinates[i, 0])
                    {
                        xMin = coordinates[i, 0];
                    }
                    if (yMin > coordinates[i, 1])
                    {
                        yMin = coordinates[i, 1];
                    }
                    if (xMax < coordinates[i, 0])
                    {
                        xMax = coordinates[i, 0];
                    }
                    if (yMax < coordinates[i, 1])
                    {
                        yMax = coordinates[i, 1];
                    }
                }

                int    border = 20;
                double xStep  = xMax != xMin ? (bitmap.Width - 2 * border) / (xMax - xMin) : 1;
                double yStep  = yMax != yMin ? (bitmap.Height - 2 * border) / (yMax - yMin) : 1;

                using (Graphics graphics = Graphics.FromImage(bitmap)) {
                    if (Solution != null)
                    {
                        int currentTour = 0;

                        List <Tour> tours = Solution.GetTours();
                        List <Pen>  pens  = GetColors(tours.Count);

                        foreach (Tour tour in tours)
                        {
                            double  t               = 0.0;
                            Point[] tourPoints      = new Point[tour.Stops.Count + 2];
                            Brush[] customerBrushes = new Brush[tour.Stops.Count];
                            int     lastCustomer    = 0;

                            for (int i = -1; i <= tour.Stops.Count; i++)
                            {
                                int location = 0;

                                if (i == -1 || i == tour.Stops.Count)
                                {
                                    location = 0; //depot
                                }
                                else
                                {
                                    location = tour.Stops[i];
                                }

                                Point locationPoint = new Point(border + ((int)((coordinates[location, 0] - xMin) * xStep)),
                                                                bitmap.Height - (border + ((int)((coordinates[location, 1] - yMin) * yStep))));
                                tourPoints[i + 1] = locationPoint;

                                if (i != -1 && i != tour.Stops.Count)
                                {
                                    Brush customerBrush = Brushes.Black;

                                    t += Content.GetDistance(
                                        lastCustomer, location, Solution);

                                    if (t < readyTime[location])
                                    {
                                        t             = readyTime[location];
                                        customerBrush = Brushes.Orange;
                                    }
                                    else if (t > dueTime[location])
                                    {
                                        customerBrush = Brushes.Red;
                                    }

                                    t += serviceTime[location];
                                    customerBrushes[i] = customerBrush;
                                }
                                lastCustomer = location;
                            }

                            graphics.DrawPolygon(pens[currentTour], tourPoints);

                            for (int i = 0; i < tour.Stops.Count; i++)
                            {
                                graphics.FillRectangle(customerBrushes[i], tourPoints[i + 1].X - 3, tourPoints[i + 1].Y - 3, 6, 6);
                            }

                            graphics.FillEllipse(Brushes.Blue, tourPoints[0].X - 5, tourPoints[0].Y - 5, 10, 10);

                            currentTour++;
                        }

                        for (int i = 0; i < pens.Count; i++)
                        {
                            pens[i].Dispose();
                        }
                    }
                    else
                    {
                        Point locationPoint;
                        //just draw customers
                        for (int i = 1; i < coordinates.Rows; i++)
                        {
                            locationPoint = new Point(border + ((int)((coordinates[i, 0] - xMin) * xStep)),
                                                      bitmap.Height - (border + ((int)((coordinates[i, 1] - yMin) * yStep))));

                            graphics.FillRectangle(Brushes.Black, locationPoint.X - 3, locationPoint.Y - 3, 6, 6);
                        }

                        locationPoint = new Point(border + ((int)((coordinates[0, 0] - xMin) * xStep)),
                                                  bitmap.Height - (border + ((int)((coordinates[0, 1] - yMin) * yStep))));
                        graphics.FillEllipse(Brushes.Blue, locationPoint.X - 5, locationPoint.Y - 5, 10, 10);
                    }
                }
            }
        }
Beispiel #48
0
        protected override void DrawVisualization(Bitmap bitmap)
        {
            DoubleMatrix coordinates       = Content.Coordinates;
            DoubleMatrix distanceMatrix    = Content.DistanceMatrix;
            BoolValue    useDistanceMatrix = Content.UseDistanceMatrix;

            if ((coordinates != null) && (coordinates.Rows > 0) && (coordinates.Columns == 2))
            {
                double xMin = double.MaxValue, yMin = double.MaxValue, xMax = double.MinValue, yMax = double.MinValue;
                for (int i = 0; i < coordinates.Rows; i++)
                {
                    if (xMin > coordinates[i, 0])
                    {
                        xMin = coordinates[i, 0];
                    }
                    if (yMin > coordinates[i, 1])
                    {
                        yMin = coordinates[i, 1];
                    }
                    if (xMax < coordinates[i, 0])
                    {
                        xMax = coordinates[i, 0];
                    }
                    if (yMax < coordinates[i, 1])
                    {
                        yMax = coordinates[i, 1];
                    }
                }

                int    border = 20;
                double xStep  = xMax != xMin ? (bitmap.Width - 2 * border) / (xMax - xMin) : 1;
                double yStep  = yMax != yMin ? (bitmap.Height - 2 * border) / (yMax - yMin) : 1;

                using (Graphics graphics = Graphics.FromImage(bitmap)) {
                    if (Solution != null)
                    {
                        for (int i = 0; i < Content.Depots.Value; i++)
                        {
                            Point locationPoint = new Point(border + ((int)((coordinates[i, 0] - xMin) * xStep)),
                                                            bitmap.Height - (border + ((int)((coordinates[i, 1] - yMin) * yStep))));
                            graphics.FillEllipse(Brushes.Blue, locationPoint.X - 5, locationPoint.Y - 5, 10, 10);
                        }

                        int currentTour = 0;

                        List <Tour> tours = Solution.GetTours();
                        List <Pen>  pens  = GetColors(tours.Count);

                        foreach (Tour tour in tours)
                        {
                            Point[] tourPoints      = new Point[tour.Stops.Count + 2];
                            Brush[] customerBrushes = new Brush[tour.Stops.Count];
                            int     lastCustomer    = 0;

                            for (int i = -1; i <= tour.Stops.Count; i++)
                            {
                                int location = 0;

                                if (i == -1 || i == tour.Stops.Count)
                                {
                                    location = 0; //depot
                                }
                                else
                                {
                                    location = tour.Stops[i];
                                }

                                Point locationPoint;

                                if (location == 0)
                                {
                                    int tourIndex = Solution.GetTourIndex(tour);
                                    int vehicle   = Solution.GetVehicleAssignment(tourIndex);
                                    int depot     = Content.VehicleDepotAssignment[vehicle];

                                    locationPoint = new Point(border + ((int)((Content.Coordinates[depot, 0] - xMin) * xStep)),
                                                              bitmap.Height - (border + ((int)((Content.Coordinates[depot, 1] - yMin) * yStep))));
                                }
                                else
                                {
                                    locationPoint = new Point(border + ((int)((Content.GetCoordinates(location)[0] - xMin) * xStep)),
                                                              bitmap.Height - (border + ((int)((Content.GetCoordinates(location)[1] - yMin) * yStep))));
                                }
                                tourPoints[i + 1] = locationPoint;

                                if (i != -1 && i != tour.Stops.Count)
                                {
                                    Brush customerBrush = Brushes.Black;
                                    customerBrushes[i] = customerBrush;
                                }
                                lastCustomer = location;
                            }

                            graphics.DrawPolygon(pens[currentTour], tourPoints);

                            for (int i = 0; i < tour.Stops.Count; i++)
                            {
                                graphics.FillRectangle(customerBrushes[i], tourPoints[i + 1].X - 3, tourPoints[i + 1].Y - 3, 6, 6);
                            }

                            graphics.FillEllipse(Brushes.DarkBlue, tourPoints[0].X - 5, tourPoints[0].Y - 5, 10, 10);

                            currentTour++;
                        }

                        for (int i = 0; i < pens.Count; i++)
                        {
                            pens[i].Dispose();
                        }
                    }
                    else
                    {
                        Point locationPoint;
                        //just draw customers
                        for (int i = 1; i <= Content.Cities.Value; i++)
                        {
                            locationPoint = new Point(border + ((int)((Content.GetCoordinates(i)[0] - xMin) * xStep)),
                                                      bitmap.Height - (border + ((int)((Content.GetCoordinates(i)[1] - yMin) * yStep))));

                            graphics.FillRectangle(Brushes.Black, locationPoint.X - 3, locationPoint.Y - 3, 6, 6);
                        }

                        for (int i = 0; i < Content.Depots.Value; i++)
                        {
                            locationPoint = new Point(border + ((int)((coordinates[i, 0] - xMin) * xStep)),
                                                      bitmap.Height - (border + ((int)((coordinates[i, 1] - yMin) * yStep))));
                            graphics.FillEllipse(Brushes.Blue, locationPoint.X - 5, locationPoint.Y - 5, 10, 10);
                        }
                    }
                }
            }
        }
Beispiel #49
0
 public LAPAssignment(DoubleMatrix costs, Permutation assignment, DoubleValue quality)
     : this(costs, assignment)
 {
     this.quality = quality;
 }
 public static AdditiveMove[] Apply(IRandom random, RealVector vector, double contiguity, int sampleSize, double maxManipulation, DoubleMatrix bounds)
 {
     AdditiveMove[] moves = new AdditiveMove[sampleSize];
     for (int i = 0; i < sampleSize; i++)
     {
         int    index = random.Next(vector.Length);
         double strength = 0, min = bounds[index % bounds.Rows, 0], max = bounds[index % bounds.Rows, 1];
         do
         {
             strength = PolynomialOnePositionManipulator.Apply(random, contiguity) * maxManipulation;
         } while (vector[index] + strength <min || vector[index] + strength> max);
         moves[i] = new AdditiveMove(index, strength);
     }
     return(moves);
 }
Beispiel #51
0
 public LAPAssignment(DoubleMatrix costs, StringArray rowNames, StringArray columnNames, Permutation assignment, DoubleValue quality)
     : this(costs, rowNames, columnNames, assignment)
 {
     this.quality = quality;
 }
 protected override AdditiveMove[] GenerateMoves(IRandom random, RealVector realVector, DoubleMatrix bounds)
 {
     return(Apply(random, realVector, ContiguityParameter.ActualValue.Value, SampleSizeParameter.ActualValue.Value, MaximumManipulationParameter.ActualValue.Value, bounds));
 }
        private DoubleMatrix CalculateVariableImpactMatrix(IRun[] runs, string[] runNames)
        {
            DoubleMatrix matrix = null;
            IEnumerable <DoubleMatrix> allVariableImpacts = (from run in runs
                                                             select run.Results[variableImpactResultName]).Cast <DoubleMatrix>();
            IEnumerable <string> variableNames = (from variableImpact in allVariableImpacts
                                                  from variableName in variableImpact.RowNames
                                                  select variableName)
                                                 .Distinct();
            // filter variableNames: only include names that have at least one non-zero value in a run
            List <string> variableNamesList = (from variableName in variableNames
                                               where GetVariableImpacts(variableName, allVariableImpacts).Any(x => !x.IsAlmost(0.0))
                                               select variableName)
                                              .ToList();

            List <string> statictics = new List <string> {
                "Median Rank", "Mean", "StdDev", "pValue"
            };
            List <string> columnNames = new List <string>(runNames);

            columnNames.AddRange(statictics);
            int numberOfRuns = runs.Length;

            matrix = new DoubleMatrix(variableNamesList.Count, numberOfRuns + statictics.Count);
            matrix.SortableView = true;
            matrix.ColumnNames  = columnNames;

            // calculate statistics
            List <List <double> > variableImpactsOverRuns = (from variableName in variableNamesList
                                                             select GetVariableImpacts(variableName, allVariableImpacts).ToList())
                                                            .ToList();
            List <List <double> > variableRanks = (from variableName in variableNamesList
                                                   select GetVariableImpactRanks(variableName, allVariableImpacts).ToList())
                                                  .ToList();

            if (variableImpactsOverRuns.Count() > 0)
            {
                // the variable with the worst median impact value is chosen as the reference variable
                // this is problematic if all variables are relevant, however works often in practice
                List <double> referenceImpacts = (from impacts in variableImpactsOverRuns
                                                  let avg = impacts.Median()
                                                            orderby avg
                                                            select impacts)
                                                 .First();
                // for all variables
                for (int row = 0; row < variableImpactsOverRuns.Count; row++)
                {
                    // median rank
                    matrix[row, numberOfRuns] = variableRanks[row].Median();
                    // also show mean and std.dev. of relative variable impacts to indicate the relative difference in impacts of variables
                    matrix[row, numberOfRuns + 1] = Math.Round(variableImpactsOverRuns[row].Average(), 3);
                    matrix[row, numberOfRuns + 2] = Math.Round(variableImpactsOverRuns[row].StandardDeviation(), 3);

                    double leftTail = 0; double rightTail = 0; double bothTails = 0;
                    // calc differences of impacts for current variable and reference variable
                    double[] z = new double[referenceImpacts.Count];
                    for (int i = 0; i < z.Length; i++)
                    {
                        z[i] = variableImpactsOverRuns[row][i] - referenceImpacts[i];
                    }
                    // wilcoxon signed rank test is used because the impact values of two variables in a single run are not independent
                    alglib.wsr.wilcoxonsignedranktest(z, z.Length, 0, ref bothTails, ref leftTail, ref rightTail);
                    matrix[row, numberOfRuns + 3] = Math.Round(bothTails, 4);
                }
            }

            // fill matrix with impacts from runs
            for (int i = 0; i < runs.Length; i++)
            {
                IRun         run = runs[i];
                DoubleMatrix runVariableImpacts = (DoubleMatrix)run.Results[variableImpactResultName];
                for (int j = 0; j < runVariableImpacts.Rows; j++)
                {
                    int rowIndex = variableNamesList.FindIndex(s => s == runVariableImpacts.RowNames.ElementAt(j));
                    if (rowIndex > -1)
                    {
                        matrix[rowIndex, i] = Math.Round(runVariableImpacts[j, 0], 3);
                    }
                }
            }
            // sort by median
            var sortedMatrix  = (DoubleMatrix)matrix.Clone();
            var sortedIndexes = from i in Enumerable.Range(0, sortedMatrix.Rows)
                                orderby matrix[i, numberOfRuns]
                                select i;

            int targetIndex = 0;

            foreach (var sourceIndex in sortedIndexes)
            {
                for (int c = 0; c < matrix.Columns; c++)
                {
                    sortedMatrix[targetIndex, c] = matrix[sourceIndex, c];
                }
                targetIndex++;
            }
            sortedMatrix.RowNames = sortedIndexes.Select(i => variableNamesList[i]);

            return(sortedMatrix);
        }
        /// <summary>
        /// Generates a new random real vector normally distributed around the given mean with the given <paramref name="length"/> and in the interval [min,max).
        /// </summary>
        /// <exception cref="ArgumentException">
        /// Thrown when <paramref name="random"/> is null.<br />
        /// Thrown when <paramref name="mean"/> is null or of length 0.<br />
        /// Thrown when <paramref name="sigma"/> is null or of length 0.<br />
        /// </exception>
        /// <remarks>
        /// If no bounds are given the bounds will be set to (double.MinValue;double.MaxValue).
        ///
        /// If dimensions of the mean do not lie within the given bounds they're set to either to the min or max of the bounds depending on whether the given dimension
        /// for the mean is smaller or larger than the bounds. If min and max for a certain dimension are almost the same the resulting value will be set to min.
        ///
        /// However, please consider that such static bounds are not really meaningful to optimize.
        ///
        /// The sigma vector can contain 0 values in which case the dimension will be exactly the same as the given mean.
        /// </remarks>
        /// <param name="random">The random number generator.</param>
        /// <param name="means">The mean vector around which the resulting vector is sampled.</param>
        /// <param name="sigmas">The vector of standard deviations, must have at least one row.</param>
        /// <param name="bounds">The lower and upper bound (1st and 2nd column) of the positions in the vector. If there are less rows than dimensions, the rows are cycled.</param>
        /// <param name="maximumTries">The maximum number of tries to sample a value inside the bounds for each dimension. If a valid value cannot be obtained, the mean will be used.</param>
        /// <returns>The newly created real vector.</returns>
        public static RealVector Apply(IntValue lengthValue, IRandom random, RealVector means, DoubleArray sigmas, DoubleMatrix bounds, int maximumTries = 1000)
        {
            if (lengthValue == null || lengthValue.Value == 0)
            {
                throw new ArgumentException("Length is not defined or zero");
            }
            if (random == null)
            {
                throw new ArgumentNullException("Random is not defined", "random");
            }
            if (means == null || means.Length == 0)
            {
                throw new ArgumentNullException("Mean is not defined", "mean");
            }
            if (sigmas == null || sigmas.Length == 0)
            {
                throw new ArgumentNullException("Sigma is not defined.", "sigma");
            }
            if (bounds == null || bounds.Rows == 0)
            {
                bounds = new DoubleMatrix(new[, ] {
                    { double.MinValue, double.MaxValue }
                });
            }
            var length = lengthValue.Value;
            var nd     = new NormalDistributedRandom(random, 0, 1);
            var result = new RealVector(length);

            for (int i = 0; i < result.Length; i++)
            {
                var min   = bounds[i % bounds.Rows, 0];
                var max   = bounds[i % bounds.Rows, 1];
                var mean  = means[i % means.Length];
                var sigma = sigmas[i % sigmas.Length];
                if (min.IsAlmost(max) || mean < min)
                {
                    result[i] = min;
                }
                else if (mean > max)
                {
                    result[i] = max;
                }
                else
                {
                    int  count = 0;
                    bool inRange;
                    do
                    {
                        result[i] = mean + sigma * nd.NextDouble();
                        inRange   = result[i] >= min && result[i] < max;
                        count++;
                    } while (count < maximumTries && !inRange);
                    if (count == maximumTries && !inRange)
                    {
                        result[i] = mean;
                    }
                }
            }
            return(result);
        }
Beispiel #55
0
        public void SetMassesTest()
        {
            // Valid input
            {
                var values = DoubleMatrix.Dense(3, 2,
                                                new double[6] {
                    1, 2, 3, 4, 5, 6
                });

                var distribution = FiniteDiscreteDistribution.Uniform(
                    values: values);

                var masses = DoubleMatrix.Dense(3, 2,
                                                new double[6] {
                    .1, .2, .3, .2, .1, .1
                });

                distribution.SetMasses(masses: masses);

                DoubleMatrixAssert.AreEqual(
                    expected: masses,
                    actual: (DoubleMatrix)distribution.Masses,
                    delta: DoubleMatrixTest.Accuracy);
            }

            // masses is null
            {
                var values = DoubleMatrix.Dense(3, 2,
                                                new double[6] {
                    1, 2, 3, 4, 5, 6
                });

                var distribution = FiniteDiscreteDistribution.Uniform(
                    values: values);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    distribution.SetMasses(masses: null);
                },
                    expectedType: typeof(ArgumentNullException),
                    expectedPartialMessage: ArgumentExceptionAssert.NullPartialMessage,
                    expectedParameterName: "masses");
            }

            // The number of rows in masses is not equal to that of values
            {
                string STR_EXCEPT_PAR_MUST_HAVE_SAME_NUM_OF_ROWS =
                    string.Format(
                        ImplementationServices.GetResourceString(
                            "STR_EXCEPT_PAR_MUST_HAVE_SAME_NUM_OF_ROWS"),
                        "values");

                var values = DoubleMatrix.Dense(3, 2,
                                                new double[6] {
                    1, 2, 3, 4, 5, 6
                });

                var distribution = FiniteDiscreteDistribution.Uniform(
                    values: values);

                var masses = DoubleMatrix.Dense(1, 2,
                                                new double[2] {
                    .5, .5
                });

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    distribution.SetMasses(masses: masses);
                },
                    expectedType: typeof(ArgumentException),
                    expectedPartialMessage: STR_EXCEPT_PAR_MUST_HAVE_SAME_NUM_OF_ROWS,
                    expectedParameterName: "masses");
            }

            // The number of columns in masses is not equal to that of values
            {
                string STR_EXCEPT_PAR_MUST_HAVE_SAME_NUM_OF_COLUMNS =
                    string.Format(
                        ImplementationServices.GetResourceString(
                            "STR_EXCEPT_PAR_MUST_HAVE_SAME_NUM_OF_COLUMNS"),
                        "values");

                var values = DoubleMatrix.Dense(3, 2,
                                                new double[6] {
                    1, 2, 3, 4, 5, 6
                });

                var distribution = FiniteDiscreteDistribution.Uniform(
                    values: values);

                var masses = DoubleMatrix.Dense(3, 1,
                                                new double[3] {
                    .2, .5, .3
                });

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    distribution.SetMasses(masses: masses);
                },
                    expectedType: typeof(ArgumentException),
                    expectedPartialMessage: STR_EXCEPT_PAR_MUST_HAVE_SAME_NUM_OF_COLUMNS,
                    expectedParameterName: "masses");
            }

            // At least an entry in masses is negative
            {
                string STR_EXCEPT_PAR_ENTRIES_NOT_IN_CLOSED_INTERVAL =
                    string.Format(
                        ImplementationServices.GetResourceString(
                            "STR_EXCEPT_PAR_ENTRIES_NOT_IN_CLOSED_INTERVAL"),
                        "0", "1");

                var values = DoubleMatrix.Dense(3, 2,
                                                new double[6] {
                    1, 2, 3, 4, 5, 6
                });

                var distribution = FiniteDiscreteDistribution.Uniform(
                    values: values);

                var masses = DoubleMatrix.Dense(3, 2,
                                                new double[6] {
                    .2, .5, .3, -.1, .1, 0
                });

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    distribution.SetMasses(masses: masses);
                },
                    expectedType: typeof(ArgumentOutOfRangeException),
                    expectedPartialMessage: STR_EXCEPT_PAR_ENTRIES_NOT_IN_CLOSED_INTERVAL,
                    expectedParameterName: "masses");
            }

            // The sum of the masses is not 1
            {
                string STR_EXCEPT_PAR_ENTRIES_MUST_SUM_TO_1 =
                    ImplementationServices.GetResourceString(
                        "STR_EXCEPT_PAR_ENTRIES_MUST_SUM_TO_1");

                var values = DoubleMatrix.Dense(3, 2,
                                                new double[6] {
                    1, 2, 3, 4, 5, 6
                });

                var distribution = FiniteDiscreteDistribution.Uniform(
                    values: values);

                var masses = DoubleMatrix.Dense(3, 2,
                                                new double[6] {
                    .2, .5, .3, .1, .1, 0
                });

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    distribution.SetMasses(masses: masses);
                },
                    expectedType: typeof(ArgumentOutOfRangeException),
                    expectedPartialMessage: STR_EXCEPT_PAR_ENTRIES_MUST_SUM_TO_1,
                    expectedParameterName: "masses");
            }
        }
 /// <summary>
 /// Forwards the call to <see cref="Apply(IRandom, RealVector, DoubleArray, DoubleMatrix)"/>.
 /// </summary>
 /// <param name="random">The pseudo random number generator to use.</param>
 /// <param name="length">The length of the real vector.</param>
 /// <param name="bounds">The lower and upper bound (1st and 2nd column) of the positions in the vector. If there are less rows than dimensions, the rows are cycled.</param>
 /// <returns>The newly created real vector.</returns>
 protected override RealVector Create(IRandom random, IntValue length, DoubleMatrix bounds)
 {
     return(Apply(length, random, MeanParameter.ActualValue, SigmaParameter.ActualValue, bounds, MaximumTriesParameter.Value.Value));
 }
Beispiel #57
0
        /// <summary>
        /// Runs this Cross-Entropy program designed to estimate
        /// the probability of the specified rare event context.
        /// </summary>
        /// <param name="context">The context in which the rare event
        /// probability must be estimated.</param>
        /// <param name="rarity">The rarity applied by the Cross-Entropy method.</param>
        /// <param name="sampleSize">The size of the samples drawn during the
        /// sampling step of the Cross-Entropy method.</param>
        /// <param name="estimationSampleSize">The size of the sample drawn to
        /// estimate the rare event probability.</param>
        /// <returns>The results of the Cross-Entropy estimator.</returns>
        /// <remarks>
        /// <para>
        /// For a thorough description of the method and an example
        /// of how to use it,
        /// see the remarks
        /// about the
        /// <see cref="RareEventProbabilityEstimationContext"/> class.
        /// </para>
        /// </remarks>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="context"/> is <b>null</b>.
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// <paramref name="sampleSize"/> is not positive.<br/>
        /// -or-<br/>
        /// <paramref name="rarity"/> is not positive.<br/>
        /// -or-<br/>
        /// <paramref name="rarity"/> is not less than 1.<br/>
        /// -or-<br/>
        /// <paramref name="estimationSampleSize"/> is not positive.
        /// </exception>
        public RareEventProbabilityEstimationResults Estimate(
            RareEventProbabilityEstimationContext context,
            double rarity,
            int sampleSize,
            int estimationSampleSize)
        {
            if (estimationSampleSize < 1)
            {
                throw new ArgumentOutOfRangeException(
                          nameof(estimationSampleSize),
                          ImplementationServices.GetResourceString(
                              "STR_EXCEPT_PAR_MUST_BE_POSITIVE"));
            }

            var baseResults = base.Run(
                context,
                sampleSize,
                rarity);

            var results = new RareEventProbabilityEstimationResults
            {
                Levels       = baseResults.Levels,
                Parameters   = baseResults.Parameters,
                HasConverged = true
            };

            DoubleMatrix optimalParameter = results.Parameters.Last.Value;
            DoubleMatrix finalSample      = this.Sample(
                context, estimationSampleSize, optimalParameter);

            var finalPerformances = this.EvaluatePerformances(context, finalSample);

            Predicate <double> match;

            if (context.EliteSampleDefinition == EliteSampleDefinition.LowerThanLevel)
            {
                match = (p) => { return(p <= context.ThresholdLevel); };
            }
            else
            {
                match = (p) => { return(p >= context.ThresholdLevel); };
            }

            var excessIndexes = finalPerformances.FindWhile(match);

            var ratios = DoubleMatrix.Dense(1, estimationSampleSize);

            var nominalParameter = context.InitialParameter;

            for (int i = 0; i < estimationSampleSize; i++)
            {
                var samplePoint = finalSample[i, ":"];
                ratios[i] = context.GetLikelihoodRatio(
                    samplePoint,
                    nominalParameter,
                    optimalParameter);
            }

            double rareEventProbability =
                Stat.Sum(ratios.Vec(excessIndexes)) / Convert.ToDouble(estimationSampleSize);

            results.RareEventProbability = rareEventProbability;

            return(results);
        }
Beispiel #58
0
        public virtual void sensitivity_cross_multi_curve()
        {
            CrossGammaParameterSensitivities sensiComputed = CENTRAL.calculateCrossGammaCrossCurve(RatesProviderDataSets.MULTI_CPI_USD, this.sensiFn);
            DoubleArray times1      = RatesProviderDataSets.TIMES_1;
            DoubleArray times2      = RatesProviderDataSets.TIMES_2;
            DoubleArray times3      = RatesProviderDataSets.TIMES_3;
            DoubleArray times4      = RatesProviderDataSets.TIMES_4;
            int         paramsTotal = times1.size() + times2.size() + times3.size() + times4.size();

            double[]    timesTotal  = new double[paramsTotal];
            DoubleArray times1Twice = times1.multipliedBy(2d);

            Array.Copy(times4.toArray(), 0, timesTotal, 0, times4.size());
            Array.Copy(times1Twice.toArray(), 0, timesTotal, times4.size(), times1.size());
            Array.Copy(times2.toArray(), 0, timesTotal, times1.size() + times4.size(), times2.size());
            Array.Copy(times3.toArray(), 0, timesTotal, times1.size() + times2.size() + times4.size(), times3.size());

            assertEquals(sensiComputed.size(), 4);
            DoubleMatrix s1 = sensiComputed.getSensitivity(RatesProviderDataSets.USD_DSC_NAME, USD).Sensitivity;

            assertEquals(s1.columnCount(), paramsTotal);
            for (int i = 0; i < times1.size(); i++)
            {
                for (int j = 0; j < paramsTotal; j++)
                {
                    double expected = 4d * times1.get(i) * timesTotal[j];
                    assertEquals(s1.get(i, j), expected, Math.Max(Math.Abs(expected), 1d) * EPS * 10d);
                }
            }
            DoubleMatrix s2 = sensiComputed.getSensitivity(RatesProviderDataSets.USD_L3_NAME, USD).Sensitivity;

            assertEquals(s2.columnCount(), paramsTotal);
            for (int i = 0; i < times2.size(); i++)
            {
                for (int j = 0; j < paramsTotal; j++)
                {
                    double expected = 2d * times2.get(i) * timesTotal[j];
                    assertEquals(s2.get(i, j), expected, Math.Max(Math.Abs(expected), 1d) * EPS * 10d);
                }
            }
            DoubleMatrix s3 = sensiComputed.getSensitivity(RatesProviderDataSets.USD_L6_NAME, USD).Sensitivity;

            assertEquals(s3.columnCount(), paramsTotal);
            for (int i = 0; i < times3.size(); i++)
            {
                for (int j = 0; j < paramsTotal; j++)
                {
                    double expected = 2d * times3.get(i) * timesTotal[j];
                    assertEquals(s3.get(i, j), expected, Math.Max(Math.Abs(expected), 1d) * EPS * 10d);
                }
            }
            DoubleMatrix s4 = sensiComputed.getSensitivity(RatesProviderDataSets.USD_CPI_NAME, USD).Sensitivity;

            assertEquals(s4.columnCount(), paramsTotal);
            for (int i = 0; i < times4.size(); i++)
            {
                for (int j = 0; j < paramsTotal; j++)
                {
                    double expected = 2d * times4.get(i) * timesTotal[j];
                    assertEquals(s4.get(i, j), expected, Math.Max(Math.Abs(expected), 1d) * EPS * 20d);
                }
            }
        }
        public override IOperation Apply()
        {
            DoubleMatrix            distances    = DistancesParameter.ActualValue;
            DoubleMatrix            weights      = WeightsParameter.ActualValue;
            ItemArray <Permutation> permutations = PermutationParameter.ActualValue;
            ItemArray <DoubleValue> qualities    = QualityParameter.ActualValue;
            ResultCollection        results      = ResultsParameter.ActualValue;
            bool        max = MaximizationParameter.ActualValue.Value;
            DoubleValue bestKnownQuality = BestKnownQualityParameter.ActualValue;

            var sorted = qualities.Select((x, index) => new { index, x.Value }).OrderBy(x => x.Value).ToArray();

            if (max)
            {
                sorted = sorted.Reverse().ToArray();
            }
            int i = sorted.First().index;

            if (bestKnownQuality == null ||
                max && qualities[i].Value > bestKnownQuality.Value ||
                !max && qualities[i].Value < bestKnownQuality.Value)
            {
                // if there isn't a best-known quality or we improved the best-known quality we'll add the current solution as best-known
                BestKnownQualityParameter.ActualValue   = new DoubleValue(qualities[i].Value);
                BestKnownSolutionParameter.ActualValue  = (Permutation)permutations[i].Clone();
                BestKnownSolutionsParameter.ActualValue = new ItemSet <Permutation>(new PermutationEqualityComparer());
                BestKnownSolutionsParameter.ActualValue.Add((Permutation)permutations[i].Clone());
            }
            else if (bestKnownQuality.Value == qualities[i].Value)
            {
                // if we matched the best-known quality we'll try to set the best-known solution if it isn't null
                // and try to add it to the pool of best solutions if it is different
                if (BestKnownSolutionParameter.ActualValue == null)
                {
                    BestKnownSolutionParameter.ActualValue = (Permutation)permutations[i].Clone();
                }
                if (BestKnownSolutionsParameter.ActualValue == null)
                {
                    BestKnownSolutionsParameter.ActualValue = new ItemSet <Permutation>(new PermutationEqualityComparer());
                }
                foreach (var k in sorted) // for each solution that we found check if it is in the pool of best-knowns
                {
                    if (!max && k.Value > qualities[i].Value ||
                        max && k.Value < qualities[i].Value)
                    {
                        break;                             // stop when we reached a solution worse than the best-known quality
                    }
                    Permutation p = permutations[k.index];
                    if (!BestKnownSolutionsParameter.ActualValue.Contains(p))
                    {
                        BestKnownSolutionsParameter.ActualValue.Add((Permutation)permutations[k.index].Clone());
                    }
                }
            }

            QAPAssignment assignment = BestSolutionParameter.ActualValue;

            if (assignment == null)
            {
                assignment           = new QAPAssignment(weights, (Permutation)permutations[i].Clone(), new DoubleValue(qualities[i].Value));
                assignment.Distances = distances;
                BestSolutionParameter.ActualValue = assignment;
                results.Add(new Result("Best QAP Solution", assignment));
            }
            else
            {
                if (max && assignment.Quality.Value < qualities[i].Value ||
                    !max && assignment.Quality.Value > qualities[i].Value)
                {
                    assignment.Distances     = distances;
                    assignment.Weights       = weights;
                    assignment.Assignment    = (Permutation)permutations[i].Clone();
                    assignment.Quality.Value = qualities[i].Value;
                }
            }

            return(base.Apply());
        }
Beispiel #60
0
 private RawOptionData(IList <Period> expiries, DoubleArray strikes, ValueType strikeType, DoubleMatrix data, DoubleMatrix error, ValueType dataType, double?shift)
 {
     JodaBeanUtils.notNull(expiries, "expiries");
     JodaBeanUtils.notNull(strikes, "strikes");
     JodaBeanUtils.notNull(strikeType, "strikeType");
     JodaBeanUtils.notNull(data, "data");
     JodaBeanUtils.notNull(dataType, "dataType");
     this.expiries   = ImmutableList.copyOf(expiries);
     this.strikes    = strikes;
     this.strikeType = strikeType;
     this.data       = data;
     this.error      = error;
     this.dataType   = dataType;
     this.shift      = shift;
 }