/// <summary> /// Obtém a solução do problema a partir das variáveis de compatibilidade. /// </summary> /// <param name="resultCosts">Os custos por componente.</param> /// <param name="variables">A lista das variáveis escolhidas.</param> /// <param name="costsMatrices">As matrizes de custos.</param> /// <returns>A solução.</returns> private GreedyAlgSolution <CostsType>[] GetSolution( CostsType[] resultCosts, List <CoordsElement>[] variables, List <ILongSparseMathMatrix <CostsType> > costsMatrices) { var result = new GreedyAlgSolution <CostsType> [variables.Length]; for (int i = 0; i < result.Length; ++i) { var integerSequence = new IntegerSequence(); integerSequence.Add(0, costsMatrices[i].GetLength(0) - 1); var currentVariables = variables[i]; for (int j = 0; j < currentVariables.Count; ++j) { var column = currentVariables[j].Column; integerSequence.Remove(column); } var algSol = new GreedyAlgSolution <CostsType>(integerSequence); algSol.Cost = resultCosts[i]; result[i] = algSol; } return(result); }
public void Statistics_DicModeAlgTest() { var target = new DicModeAlgorithm <int>(); var source = new IntegerSequence(); for (var i = 0; i < 1000; ++i) { source.Clear(); source.Add(0, i); var innerActual = target.Run(source); Assert.AreEqual(source.Count, innerActual.Count); innerActual.Sort(); for (var j = 0; j < source.Count; ++j) { Assert.AreEqual(source[j], innerActual[j]); } } var arraySource = new int[] { 1, 3, 2, 2, 1, 3, 3, 3, 3, 4, 2 }; var expected = 3; var actual = target.Run(arraySource); Assert.AreEqual(1, actual.Count); Assert.AreEqual(expected, actual[0]); }
public void Statistics_DicMedianAlgTest() { var target = new DicMedianAlgorithm <int>(); var source = new IntegerSequence(); var expected = 1; for (var i = 1; i < 1000; i += 2) { source.Clear(); source.Add(1, i); var actual = target.Run(source); Assert.AreEqual(expected, actual.Item1); Assert.AreEqual(expected, actual.Item2); ++expected; } expected = 1; for (var i = 2; i < 1000; i += 2) { source.Clear(); source.Add(1, i); var actual = target.Run(source); Assert.AreEqual(expected++, actual.Item1); Assert.AreEqual(expected, actual.Item2); } var arraySource = new int[] { 1, 3, 2, 2, 1, 3, 3, 3, 3, 4, 2 }; expected = 3; var outerActual = target.Run(arraySource); Assert.AreEqual(expected, outerActual.Item1); Assert.AreEqual(expected, outerActual.Item2); arraySource = new int[] { 1, 3, 2, 2, 1, 3, 3, 3, 4, 2 }; expected = 2; outerActual = target.Run(arraySource); Assert.AreEqual(expected++, outerActual.Item1); Assert.AreEqual(expected, outerActual.Item2); }
/// <summary> /// Determina o polinómio característico de uma matriz. /// </summary> /// <param name="data">A matriz.</param> /// <returns>O polinómio característico.</returns> public UnivariatePolynomialNormalForm <ElementType> Run(ISquareMathMatrix <ElementType> data) { if (data == null) { return(new UnivariatePolynomialNormalForm <ElementType>(this.variableName)); } else { var lines = data.GetLength(0); if (lines == 0) { return(new UnivariatePolynomialNormalForm <ElementType>(this.variableName)); } else if (lines == 1) { var entry = data[0, 0]; var result = new UnivariatePolynomialNormalForm <ElementType>( this.ring.MultiplicativeUnity, 1, this.variableName, this.ring); result = result.Add(this.ring.AdditiveInverse(entry), 0, this.ring); return(result); } else if (lines == 2) { var variablePol = new UnivariatePolynomialNormalForm <ElementType>( this.ring.MultiplicativeUnity, 1, this.variableName, this.ring); var firstDiagonalElement = variablePol.Add( this.ring.AdditiveInverse(data[0, 0]), this.ring); var secondDiagonalElement = variablePol.Add( this.ring.AdditiveInverse(data[1, 1]), this.ring); var result = firstDiagonalElement.Multiply(secondDiagonalElement, this.ring); result = result.Add( this.ring.AdditiveInverse(this.ring.Multiply(data[0, 1], data[1, 0])), this.ring); return(result); } else { var matrixFactory = new ArrayMathMatrixFactory <ElementType>(); var matrixMultiplicator = new MatrixMultiplicationOperation <ElementType>( matrixFactory, this.ring, this.ring); var subMatrixSequence = new IntegerSequence(); var singleValueSequence = new IntegerSequence(); IMatrix <ElementType> multiplicationMatrix = new ArrayMathMatrix <ElementType>( lines + 1, lines, this.ring.AdditiveUnity); subMatrixSequence.Add(1, lines - 1); singleValueSequence.Add(0); this.FillMultiplicationMatrix( data, data[0, 0], subMatrixSequence, singleValueSequence, matrixMultiplicator, multiplicationMatrix); var currentDimension = 1; while (currentDimension < lines - 1) { subMatrixSequence.Clear(); singleValueSequence.Clear(); subMatrixSequence.Add(currentDimension + 1, lines - 1); singleValueSequence.Add(currentDimension); var otherLines = lines - currentDimension; var otherMultiplicationMatrix = new ArrayMathMatrix <ElementType>( otherLines + 1, otherLines, this.ring.AdditiveUnity); this.FillMultiplicationMatrix( data, data[currentDimension, currentDimension], subMatrixSequence, singleValueSequence, matrixMultiplicator, otherMultiplicationMatrix); multiplicationMatrix = matrixMultiplicator.Multiply( multiplicationMatrix, otherMultiplicationMatrix); ++currentDimension; } var lastOtherMultiplicationMatrix = new ArrayMathMatrix <ElementType>( 2, 1, this.ring.AdditiveUnity); lastOtherMultiplicationMatrix[0, 0] = this.ring.MultiplicativeUnity; lastOtherMultiplicationMatrix[1, 0] = this.ring.AdditiveInverse(data[currentDimension, currentDimension]); multiplicationMatrix = matrixMultiplicator.Multiply( multiplicationMatrix, lastOtherMultiplicationMatrix); var result = new UnivariatePolynomialNormalForm <ElementType>( multiplicationMatrix[0, 0], lines, this.variableName, this.ring); for (int i = 1; i <= lines; ++i) { result = result.Add(multiplicationMatrix[i, 0], lines - i, this.ring); } return(result); } } }
/// <summary> /// Obtém uma solução a partir duma aproximação inicial. /// </summary> /// <param name="approximateMedians">As medianas.</param> /// <param name="costs">Os custos.</param> /// <param name="niter">O número máximo melhoramentos a serem aplicados à solução encontrada.</param> /// <returns>A solução construída a partir da aproximação.</returns> public GreedyAlgSolution <CoeffType> Run( CoeffType[] approximateMedians, ILongSparseMathMatrix <CoeffType> costs, int niter) { if (approximateMedians == null) { throw new ArgumentNullException("approximateMedians"); } else if (costs == null) { throw new ArgumentNullException("costs"); } else if (approximateMedians.Length != costs.GetLength(1)) { throw new ArgumentException("The number of medians must match the number of columns in costs matrix."); } else { var settedSolutions = new IntegerSequence(); var approximateSolutions = new List <int>(); var sum = this.coeffsField.AdditiveUnity; for (int i = 0; i < approximateMedians.Length; ++i) { var currentMedian = approximateMedians[i]; if (!this.coeffsField.IsAdditiveUnity(currentMedian)) { sum = this.coeffsField.Add(sum, approximateMedians[i]); if (this.converter.CanApplyDirectConversion(currentMedian)) { var converted = this.converter.DirectConversion(currentMedian); if (converted == 1) { settedSolutions.Add(i); } else { throw new OdmpProblemException(string.Format( "The median {0} at position {1} of medians array can't be converted to the unity.", currentMedian, i)); } } else { approximateSolutions.Add(i); } } } if (this.converter.CanApplyDirectConversion(sum)) { var convertedSum = this.converter.DirectConversion(sum); if (convertedSum <= 0 || convertedSum > approximateMedians.Length) { throw new IndexOutOfRangeException(string.Format( "The medians sum {0} is out of bounds. It must be between 1 and the number of elements in medians array.", convertedSum)); } var solutionBoard = new CoeffType[approximateMedians.Length]; var marked = new BitArray(approximateMedians.Length, false); if (settedSolutions.Count == convertedSum) { var result = new GreedyAlgSolution <CoeffType>(settedSolutions); result.Cost = this.ComputeCost(settedSolutions, costs, solutionBoard, marked); return(result); } else { // Partição das mediana em dois conjuntos: as que vão falzer parte da solução e as restantes // entre as soluções aproximadas. var recoveredMedians = new List <int>(); var unrecoveredMedians = new List <int>(); var innerComparer = new InnerComparer(approximateMedians, this.comparer); approximateSolutions.Sort(innerComparer); var count = convertedSum - settedSolutions.Count; var i = 0; for (; i < count; ++i) { recoveredMedians.Add(approximateSolutions[i]); settedSolutions.Add(approximateSolutions[i]); } for (; i < approximateSolutions.Count; ++i) { unrecoveredMedians.Add(approximateSolutions[i]); } var currentCost = this.ComputeCost(settedSolutions, costs, solutionBoard, marked); // Processa as melhorias de uma forma simples caso seja possível if (unrecoveredMedians.Count > 0 && niter > 0) { var exchangeSolutionBoard = new CoeffType[solutionBoard.Length]; var currentBestBoard = new CoeffType[solutionBoard.Length]; for (i = 0; i < niter; ++i) { var itemToExchange = -1; var itemToExchangeIndex = -1; var itemToExchangeWith = -1; var itemToExchangeWithIndex = -1; var minimumCost = this.coeffsField.AdditiveUnity; for (int j = 0; j < recoveredMedians.Count; ++j) { for (int k = 0; k < unrecoveredMedians.Count; ++k) { var replacementCost = this.ComputeReplacementCost( unrecoveredMedians[k], recoveredMedians[j], settedSolutions, costs, solutionBoard, exchangeSolutionBoard); if (this.comparer.Compare(replacementCost, minimumCost) < 0) { // Aceita a troca itemToExchange = recoveredMedians[j]; itemToExchangeIndex = j; itemToExchangeWith = unrecoveredMedians[k]; itemToExchangeWithIndex = k; minimumCost = replacementCost; var swapBestBoard = currentBestBoard; currentBestBoard = exchangeSolutionBoard; exchangeSolutionBoard = swapBestBoard; } } } if (itemToExchange == -1 || itemToExchangeWith == -1) { i = niter - 1; } else { // Efectua a troca var swapSolutionBoard = solutionBoard; solutionBoard = currentBestBoard; currentBestBoard = swapSolutionBoard; currentCost = this.coeffsField.Add(currentCost, minimumCost); settedSolutions.Remove(itemToExchange); settedSolutions.Add(itemToExchangeWith); var swap = recoveredMedians[itemToExchangeIndex]; recoveredMedians[itemToExchangeIndex] = unrecoveredMedians[itemToExchangeWithIndex]; unrecoveredMedians[itemToExchangeWithIndex] = swap; } } } return(new GreedyAlgSolution <CoeffType>(settedSolutions) { Cost = currentCost }); } } else { throw new OdmpProblemException("The sum of medians can't be converted to an integer."); } } }
public void Statistcs_EnumGeneralizeMeanAlgorithmTest() { var integerNumb = new IntegerDomain(); var target = new EnumGeneralizedMeanAlgorithm <int, double, int>( i => i, d => d, (d, i) => d / i, new DoubleField(), integerNumb); var integerSequence = new IntegerSequence(); for (var i = 1; i < 5000; ++i) { integerSequence.Add(i); var expected = (i + 1) / 2.0; var actual = target.Run(integerSequence); Assert.AreEqual(expected, actual); } integerSequence = new IntegerSequence(); var n = 1000000; integerSequence.Add(1, n); var outerExpected = (n + 1) / 2.0; var outerActual = target.Run(integerSequence); Assert.AreEqual(outerExpected, outerActual); var bigIntegerDomain = new BigIntegerDomain(); var fractionField = new FractionField <BigInteger>(bigIntegerDomain); var fractionTarget = new EnumGeneralizedMeanAlgorithm <int, Fraction <BigInteger>, int>( i => new Fraction <BigInteger>(i, 1, bigIntegerDomain), d => d, (d, i) => d.Divide(i, bigIntegerDomain), fractionField, integerNumb); var fractionExpected = new Fraction <BigInteger>(n + 1, 2, bigIntegerDomain); var fractionActual = fractionTarget.Run(integerSequence); Assert.AreEqual(fractionExpected, fractionActual); // Teste com alteração da função directa fractionTarget.DirectFunction = i => new Fraction <BigInteger>(new BigInteger(i) * i, 1, bigIntegerDomain); fractionExpected = new Fraction <BigInteger>( (new BigInteger(n) + BigInteger.One) * (2 * new BigInteger(n) + 1), 6, bigIntegerDomain); fractionActual = fractionTarget.Run(integerSequence); Assert.AreEqual(fractionExpected, fractionActual); // Teste com transformação var transformedTarget = new EnumGeneralizedMeanAlgorithm <BigInteger, Fraction <BigInteger>, int>( i => new Fraction <BigInteger>(i, 1, bigIntegerDomain), d => d, (d, i) => d.Divide(i, bigIntegerDomain), fractionField, integerNumb); var transformedSeq = new TransformEnumerable <int, BigInteger>( integerSequence, i => new BigInteger(i) * i); var transformedExpected = new Fraction <BigInteger>( (new BigInteger(n) + BigInteger.One) * (2 * new BigInteger(n) + 1), 6, bigIntegerDomain); var transformedActual = transformedTarget.Run(transformedSeq); Assert.AreEqual(transformedExpected, transformedActual); }
public void Statistcs_EnumGeneralizeMeanBlockAlgorithmTest() { var integerNumb = new IntegerDomain(); var target = new EnumGeneralizedMeanAlgorithm <int, double, int>( i => i, d => d, (d, i) => d / i, new DoubleField(), integerNumb); var blockNumber = 2500; var integerSequence = new IntegerSequence(); for (var i = 1; i < 5500; ++i) { integerSequence.Add(i); var expected = (i + 1) / 2.0; var actual = target.Run <double>( integerSequence, blockNumber, (j, k) => j / (double)k, (d1, d2) => d1 * d2); Assert.IsTrue(Math.Abs(expected - actual) < 0.0001); } integerSequence = new IntegerSequence(); var n = 1000500; integerSequence.Add(1, n); var outerExpected = (n + 1) / 2.0; var outerActual = target.Run <double>( integerSequence, blockNumber, (j, k) => j / (double)k, (d1, d2) => d1 * d2); Assert.AreEqual(outerExpected, outerActual); var integerDomain = new BigIntegerDomain(); var fractionField = new FractionField <BigInteger>(integerDomain); var fracTarget = new EnumGeneralizedMeanAlgorithm <int, Fraction <BigInteger>, int>( i => new Fraction <BigInteger>(i, 1, integerDomain), d => d, (d, i) => d.Divide(i, integerDomain), fractionField, integerNumb); var fractionExpected = new Fraction <BigInteger>(n + 1, 2, integerDomain); var fractionActual = fracTarget.Run <Fraction <BigInteger> >( integerSequence, blockNumber, (j, k) => new Fraction <BigInteger>(j, k, integerDomain), (d1, d2) => d1.Multiply(d2, integerDomain)); Assert.AreEqual(fractionExpected, fractionActual); // Teste com alteração da função directa fracTarget.DirectFunction = i => new Fraction <BigInteger>(new BigInteger(i) * i, 1, integerDomain); fractionExpected = new Fraction <BigInteger>( (new BigInteger(n) + BigInteger.One) * (2 * new BigInteger(n) + 1), 6, integerDomain); fractionActual = fracTarget.Run <Fraction <BigInteger> >( integerSequence, blockNumber, (j, k) => new Fraction <BigInteger>(j, k, integerDomain), (d1, d2) => d1.Multiply(d2, integerDomain)); // Teste com transformação var transformedTarget = new EnumGeneralizedMeanAlgorithm <BigInteger, Fraction <BigInteger>, int>( i => new Fraction <BigInteger>(i, 1, integerDomain), d => d, (d, i) => d.Divide(i, integerDomain), fractionField, integerNumb); var transformedSeq = new TransformEnumerable <int, BigInteger>( integerSequence, i => new BigInteger(i) * i); var transformedExpected = new Fraction <BigInteger>( (new BigInteger(n) + BigInteger.One) * (2 * new BigInteger(n) + 1), 6, integerDomain); var transformedActual = transformedTarget.Run <Fraction <BigInteger> >( transformedSeq, blockNumber, (j, k) => new Fraction <BigInteger>(j, k, integerDomain), (d1, d2) => d1.Multiply(d2, integerDomain)); Assert.AreEqual(transformedExpected, transformedActual); }