/// <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; } } }
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); }
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); }
public void PolynomialOnePositionManipulatorApplyTest() { TestRandom random = new TestRandom(); RealVector parent, expected; DoubleValue contiguity, maxManipulation; bool exceptionFired; // The following test is not based on published examples random.Reset(); random.IntNumbers = new int[] { 3 }; random.DoubleNumbers = new double[] { 0.2 }; parent = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1 }); expected = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.1261980542102, 0.1 }); contiguity = new DoubleValue(0.2); maxManipulation = new DoubleValue(0.7); PolynomialOnePositionManipulator.Apply(random, parent, contiguity, maxManipulation); Assert.IsTrue(Auxiliary.RealVectorIsAlmostEqualByPosition(expected, parent)); // The following test is not based on published examples exceptionFired = false; random.Reset(); random.IntNumbers = new int[] { 3 }; random.DoubleNumbers = new double[] { 0.2 }; parent = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1 }); contiguity = new DoubleValue(-1); //Contiguity value < 0 maxManipulation = new DoubleValue(0.2); try { PolynomialOnePositionManipulator.Apply(random, parent, contiguity, maxManipulation); } catch (System.ArgumentException) { exceptionFired = true; } Assert.IsTrue(exceptionFired); }
/// <summary> /// Performs the some positions bitflip mutation on a binary vector. /// </summary> /// <param name="random">The random number generator to use.</param> /// <param name="vector">The vector that should be manipulated.</param> /// <param name="pm">The probability a bit is flipped.</param> public static void Apply(IRandom random, BinaryVector vector, DoubleValue pm) { for (int i = 0; i < vector.Length; i++) { if (random.NextDouble() < pm.Value) { vector[i] = !vector[i]; } } }
public void PolynomialAllPositionManipulatorApplyTest() { TestRandom random = new TestRandom(); RealVector parent, expected; DoubleValue contiguity, maxManipulation; bool exceptionFired; // The following test is not based on published examples random.Reset(); random.DoubleNumbers = new double[] { 0.2, 0.7, 0.8, 0.01, 0.1 }; parent = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1 }); expected = new RealVector(new double[] { 0.120213215256006, 0.249415354697564, 0.379786784743994, 0.322759240811056, -0.0182075293954083 }); contiguity = new DoubleValue(0.8); maxManipulation = new DoubleValue(0.2); PolynomialAllPositionManipulator.Apply(random, parent, contiguity, maxManipulation); 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.7, 0.8, 0.01, 0.1 }; parent = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1 }); contiguity = new DoubleValue(-1); //Contiguity value < 0 maxManipulation = new DoubleValue(0.2); try { PolynomialAllPositionManipulator.Apply(random, parent, contiguity, maxManipulation); } catch (System.ArgumentException) { exceptionFired = true; } Assert.IsTrue(exceptionFired); }
public override IOperation Apply() { bool maximization = MaximizationParameter.ActualValue.Value; double quality = QualityParameter.ActualValue.Value, max = MaximumQualityParameter.ActualValue.Value, min = MinimumQualityParameter.ActualValue.Value; double difference; difference = ((quality - min) / (max - min)); if (maximization) difference = 1.0 - difference; DoubleValue differenceValue = ScaledDifferenceParameter.ActualValue; if (differenceValue == null) { differenceValue = new DoubleValue(difference); ScaledDifferenceParameter.ActualValue = differenceValue; } else differenceValue.Value = difference; ResultCollection results = ResultsParameter.ActualValue; if (results != null) { IResult r; if (!results.TryGetValue(ScaledDifferenceParameter.TranslatedName, out r)) { r = new Result(ScaledDifferenceParameter.TranslatedName, differenceValue); results.Add(r); } } return base.Apply(); }
public void ConvertToZeroOneScaleZeroTest() { DoubleValue value1 = new DoubleValue(50); DoubleValue value2 = new DoubleValue(0); var convertToZeroOneScale = value1.ConvertToZeroOneScale(value2); Assert.AreEqual(0.0, convertToZeroOneScale); }
/// <summary> /// Performs the rounded blend alpha crossover (BLX-a) of two integer vectors.<br/> /// It creates new offspring by sampling a new value in the range [min_i - d * alpha, max_i + d * alpha) at each position i /// and rounding the result to the next integer. /// Here min_i and max_i are the smaller and larger value of the two parents at position i and d is max_i - min_i. /// </summary> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="parent1"/> and <paramref name="parent2"/> are of different length or<br/> /// when <paramref name="alpha"/> is less than 0. /// </exception> /// <param name="random">The random number generator.</param> /// <param name="parent1">The first parent for the crossover operation.</param> /// <param name="parent2">The second parent for the crossover operation.</param> /// <param name="bounds">The bounds and step size for each dimension (will be cycled in case there are less rows than elements in the parent vectors).</param> /// <param name="alpha">The alpha value for the crossover.</param> /// <returns>The newly created integer vector resulting from the crossover operation.</returns> public static IntegerVector Apply(IRandom random, IntegerVector parent1, IntegerVector parent2, IntMatrix bounds, DoubleValue alpha) { if (parent1.Length != parent2.Length) throw new ArgumentException("RoundedBlendAlphaCrossover: The parents' vectors are of different length.", "parent1"); if (alpha.Value < 0) throw new ArgumentException("RoundedBlendAlphaCrossover: Paramter alpha must be greater or equal than 0.", "alpha"); if (bounds == null || bounds.Rows < 1 || bounds.Columns < 2) throw new ArgumentException("RoundedBlendAlphaCrossover: Invalid bounds specified.", "bounds"); int length = parent1.Length; var result = new IntegerVector(length); double max = 0, min = 0, d = 0, resMin = 0, resMax = 0; int minBound, maxBound, step = 1; for (int i = 0; i < length; i++) { minBound = bounds[i % bounds.Rows, 0]; maxBound = bounds[i % bounds.Rows, 1]; if (bounds.Columns > 2) step = bounds[i % bounds.Rows, 2]; maxBound = FloorFeasible(minBound, maxBound, step, maxBound - 1); max = Math.Max(parent1[i], parent2[i]); min = Math.Min(parent1[i], parent2[i]); d = Math.Abs(max - min); resMin = FloorFeasible(minBound, maxBound, step, min - d * alpha.Value); resMax = CeilingFeasible(minBound, maxBound, step, max + d * alpha.Value); result[i] = RoundFeasible(minBound, maxBound, step, resMin + random.NextDouble() * Math.Abs(resMax - resMin)); } return result; }
public SamplingCriteriaContext(UintValue maxTopStackOccurrence, DoubleValue maxDuration) { Contract.Requires(maxTopStackOccurrence != null); Contract.Requires(maxDuration != null); _maxTopStackOccurrence = maxTopStackOccurrence; _maxDuration = maxDuration; _availableCriteria = new Criterion[]{TopStackOccurrenceCriterion, DurationCriterion}; }
public VRPSolution(IVRPProblemInstance problemInstance, IVRPEncoding solution, DoubleValue quality) : base() { this.problemInstance = problemInstance; this.solution = solution; this.quality = quality; Initialize(); }
public void SetUp() { _enterCount = new UintValue(1); _wallClockDurationHns = new Uint64Value(2); _activeTime = new DoubleValue(3); Mock<IEnumerable<Method>> mockCallingMethods = new Mock<IEnumerable<Method>>(MockBehavior.Strict); Mock<IEnumerable<Method>> mockCalledMethods = new Mock<IEnumerable<Method>>(MockBehavior.Strict); _method = new TracingMethod(1,"stub", 20, 50, "MethodFull", @"C:\code\source.cs",_enterCount,_wallClockDurationHns,_activeTime );//, mockCallingMethods.Object, //mockCalledMethods.Object); }
/// <summary> /// Performs the arithmetic crossover on all positions by calculating x = alpha * p1 + (1 - alpha) * p2. /// </summary> /// <exception cref="ArgumentException">Thrown when the parent vectors are of different length or alpha is outside the range [0;1].</exception> /// <param name="random">The random number generator.</param> /// <param name="parent1">The first parent vector.</param> /// <param name="parent2">The second parent vector.</param> /// <param name="alpha">The alpha parameter (<see cref="AlphaParameter"/>).</param> /// <returns>The vector resulting from the crossover.</returns> public static RealVector Apply(IRandom random, RealVector parent1, RealVector parent2, DoubleValue alpha) { int length = parent1.Length; if (length != parent2.Length) throw new ArgumentException("UniformAllPositionsArithmeticCrossover: The parent vectors are of different length.", "parent1"); if (alpha.Value < 0 || alpha.Value > 1) throw new ArgumentException("UniformAllPositionsArithmeticCrossover: Parameter alpha must be in the range [0;1]", "alpha"); RealVector result = new RealVector(length); for (int i = 0; i < length; i++) { result[i] = alpha.Value * parent1[i] + (1 - alpha.Value) * parent2[i]; } return result; }
public TracingCriteriaContext(UintValue maxCallCount, Uint64Value maxTimeWallClock, DoubleValue maxTimeActive) { Contract.Requires(maxCallCount != null); Contract.Requires(maxTimeWallClock != null); Contract.Requires(maxTimeActive != null); _maxCallCount = maxCallCount; _maxTimeWallClock = maxTimeWallClock; _maxTimeWallClock = maxTimeWallClock; _maxTimeActive = maxTimeActive; _availableCriteria = new Criterion[] { CallCountCriterion, TimeWallClockCriterion, TimeActiveCriterion }; }
public void BlendAlphaCrossoverApplyTest() { TestRandom random = new TestRandom(); RealVector parent1, parent2, expected, actual; DoubleValue alpha; bool exceptionFired; // The following test is not based on published examples random.Reset(); random.DoubleNumbers = new double[] { 0.5, 0.5, 0.5, 0.5, 0.5 }; alpha = new DoubleValue(0.5); parent1 = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1 }); parent2 = new RealVector(new double[] { 0.4, 0.1, 0.3, 0.2, 0.8 }); expected = new RealVector(new double[] { 0.3, 0.15, 0.3, 0.35, 0.45 }); actual = BlendAlphaCrossover.Apply(random, parent1, parent2, alpha); Assert.IsTrue(Auxiliary.RealVectorIsAlmostEqualByPosition(actual, expected)); // The following test is not based on published examples random.Reset(); random.DoubleNumbers = new double[] { 0.25, 0.75, 0.25, 0.75, 0.25 }; alpha = new DoubleValue(0.25); parent1 = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1 }); parent2 = new RealVector(new double[] { 0.4, 0.1, 0.3, 0.2, 0.8 }); expected = new RealVector(new double[] { 0.225, 0.1875, 0.3, 0.4625, 0.1875 }); actual = BlendAlphaCrossover.Apply(random, parent1, parent2, alpha); Assert.IsTrue(Auxiliary.RealVectorIsAlmostEqualByPosition(actual, expected)); // The following test is not based on published examples random.Reset(); random.DoubleNumbers = new double[] { 0.25, 0.75, 0.25, 0.75, 0.25 }; alpha = new DoubleValue(-0.25); // negative values for alpha are not allowed parent1 = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1 }); parent2 = new RealVector(new double[] { 0.4, 0.1, 0.3, 0.2, 0.8 }); expected = new RealVector(new double[] { 0.225, 0.1875, 0.3, 0.4625, 0.1875 }); exceptionFired = false; try { actual = BlendAlphaCrossover.Apply(random, parent1, parent2, alpha); } catch (System.ArgumentException) { exceptionFired = true; } Assert.IsTrue(exceptionFired); // The following test is not based on published examples random.Reset(); random.DoubleNumbers = new double[] { 0.25, 0.75, 0.25, 0.75, 0.25, .75 }; alpha = new DoubleValue(0.25); parent1 = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1, 0.9 }); // this parent is longer parent2 = new RealVector(new double[] { 0.4, 0.1, 0.3, 0.2, 0.8 }); expected = new RealVector(new double[] { 0.225, 0.1875, 0.3, 0.4625, 0.1875 }); exceptionFired = false; try { actual = BlendAlphaCrossover.Apply(random, parent1, parent2, alpha); } catch (System.ArgumentException) { exceptionFired = true; } Assert.IsTrue(exceptionFired); }
public override IOperation Apply() { if (Cache == null) return base.Apply(); if (Quality == null) Quality = new DoubleValue(0); Quality.Value = Cache.GetValue(BuildSolutionMessage(), m => EvaluateOnNextAvailableClient(m).Quality); if (Successor != null) return ExecutionContext.CreateOperation(Successor); else return null; }
public void SetUp() { _callCountCriterion = new CallCountCriterion(); _timeActiveCriterion = new TimeActiveCriterion(); _timeWallClockCriterion = new TimeWallClockCriterion(); _maxCallCount = new UintValue(50); _maxTimeWallClock = new Uint64Value(100); _maxTimeActive = new DoubleValue(150); _tracingCriteriaContext = new TracingCriteriaContext(_maxCallCount, _maxTimeWallClock, _maxTimeActive); }
public void SomePositionsBitflipManipulatorApplyTest() { TestRandom random = new TestRandom(); BinaryVector parent, expected; DoubleValue pm; // The following test is based on Michalewicz, Z. 1999. Genetic Algorithms + Data Structures = Evolution Programs. Third, Revised and Extended Edition, Spring-Verlag Berlin Heidelberg, p. 21. random.Reset(); random.DoubleNumbers = new double[] { 0.3, 0.3, 0.1, 0.1, 0.3, 0.3, 0.3, 0.1, 0.3 }; pm = new DoubleValue(0.2); parent = new BinaryVector(new bool[] { true, false, true, false, false, false, false, true, false }); expected = new BinaryVector(new bool[] { true, false, false, true, false, false, false, false, false }); SomePositionsBitflipManipulator.Apply(random, parent, pm); Assert.IsTrue(Auxiliary.BinaryVectorIsEqualByPosition(expected, parent)); }
public SamplingMethod( uint id, string name, int firstLineNumber, int lineExtend, string classFullName, string sourceFile, UintValue topStackOccurrence, DoubleValue duration) : base(id, name, firstLineNumber, lineExtend, classFullName, sourceFile) { _topStackOccurrence = topStackOccurrence; _duration = duration; }
/// <summary> /// Performs the polynomial mutation on a single position in the real vector. /// </summary> /// <param name="random">The random number generator to use.</param> /// <param name="vector">The vector that should be manipulated.</param> /// <param name="contiguity">A parameter describing the shape of the probability density function which influences the strength of the manipulation.</param> /// <param name="maxManipulation">The maximum strength of the manipulation.</param> public static void Apply(IRandom random, RealVector vector, DoubleValue contiguity, DoubleValue maxManipulation) { if (contiguity.Value < 0) throw new ArgumentException("PolynomialAllPositionManipulator: Contiguity value is smaller than 0", "contiguity"); double u, delta = 0; for (int index = 0; index < vector.Length; index++) { u = random.NextDouble(); if (u < 0.5) { delta = Math.Pow(2 * u, 1.0 / (contiguity.Value + 1)) - 1.0; } else if (u >= 0.5) { delta = 1.0 - Math.Pow(2.0 - 2.0 * u, 1.0 / (contiguity.Value + 1)); } vector[index] += delta * maxManipulation.Value; } }
public ReportRow(Worksheet worksheet, int rowIndex, FomsReportRowType rowType) : base(worksheet) { RowIndex = rowIndex; RowType = rowType; var colIndex = 1; Name = new StringValue(worksheet, rowIndex, colIndex++); StacFullCount = new DoubleValue(worksheet, rowIndex, colIndex++); StacDayCount = new DoubleValue(worksheet, rowIndex, colIndex++); EmergencyCount = new DoubleValue(worksheet, rowIndex, colIndex++); TreatmentCount = new DoubleValue(worksheet, rowIndex, colIndex++); VisitCount = new DoubleValue(worksheet, rowIndex, colIndex++); AmbulanceCount = new DoubleValue(worksheet, rowIndex, colIndex++); }
public TracingMethod( uint id, string name, int firstLineNumber, int lineExtend, string classFullName, string sourceFile, UintValue callCountValue, Uint64Value timeWallClockValue, DoubleValue timeActiveValue) : base(id, name, firstLineNumber, lineExtend,classFullName,sourceFile) { _callCountValue = callCountValue; _timeWallClockValue = timeWallClockValue; _timeActiveValue = timeActiveValue; }
public void BlendAlphaBetaCrossoverApplyTest() { TestRandom random = new TestRandom(); RealVector parent1, parent2, expected, actual; DoubleValue alpha; DoubleValue beta; bool exceptionFired; // The following test is not based on published examples random.Reset(); random.DoubleNumbers = new double[] { 0.5, 0.5, 0.5, 0.5, 0.5 }; alpha = new DoubleValue(0.5); beta = new DoubleValue(0.5); parent1 = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1 }); parent2 = new RealVector(new double[] { 0.4, 0.1, 0.3, 0.2, 0.8 }); expected = new RealVector(new double[] { 0.3, 0.15, 0.3, 0.35, 0.45 }); actual = BlendAlphaBetaCrossover.Apply(random, parent1, parent2, alpha, beta); Assert.IsTrue(Auxiliary.RealVectorIsAlmostEqualByPosition(actual, expected)); // The following test is not based on published examples random.Reset(); random.DoubleNumbers = new double[] { 0.25, 0.75, 0.25, 0.75, 0.25 }; alpha = new DoubleValue(-0.25); // negative values for alpha are not allowed parent1 = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1 }); parent2 = new RealVector(new double[] { 0.4, 0.1, 0.3, 0.2, 0.8 }); exceptionFired = false; try { actual = BlendAlphaBetaCrossover.Apply(random, parent1, parent2, alpha, beta); } catch (System.ArgumentException) { exceptionFired = true; } Assert.IsTrue(exceptionFired); // The following test is not based on published examples random.Reset(); random.DoubleNumbers = new double[] { 0.25, 0.75, 0.25, 0.75, 0.25, .75 }; alpha = new DoubleValue(0.25); parent1 = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1, 0.9 }); // this parent is longer parent2 = new RealVector(new double[] { 0.4, 0.1, 0.3, 0.2, 0.8 }); exceptionFired = false; try { actual = BlendAlphaBetaCrossover.Apply(random, parent1, parent2, alpha, beta); } catch (System.ArgumentException) { exceptionFired = true; } Assert.IsTrue(exceptionFired); }
private double?GetValue(IRun run, string columnName) { if (run == null || string.IsNullOrEmpty(columnName)) { return(null); } if (Enum.IsDefined(typeof(AxisDimension), columnName)) { AxisDimension axisDimension = (AxisDimension)Enum.Parse(typeof(AxisDimension), columnName); return(GetValue(run, axisDimension)); } int columnIndex = Matrix.ColumnNames.ToList().IndexOf(columnName); IItem value = Content.GetValue(run, columnIndex); if (value == null) { return(null); } DoubleValue doubleValue = value as DoubleValue; IntValue intValue = value as IntValue; TimeSpanValue timeSpanValue = value as TimeSpanValue; double? ret = null; if (doubleValue != null) { if (!double.IsNaN(doubleValue.Value) && !double.IsInfinity(doubleValue.Value)) { ret = doubleValue.Value; } } else if (intValue != null) { ret = intValue.Value; } else if (timeSpanValue != null) { ret = timeSpanValue.Value.TotalSeconds; } else { ret = GetCategoricalValue(columnIndex, value.ToString()); } return(ret); }
private static Object ParseNumber(IRuleNode number, int factor) { var tokenType = GetSingleChildTokenType(number); if (tokenType == EsperEPL2GrammarLexer.IntegerLiteral) { return ParseIntLongByte(number.GetText(), factor); } else if (tokenType == EsperEPL2GrammarLexer.FloatingPointLiteral) { var numberText = number.GetText(); if (numberText.EndsWith("f") || numberText.EndsWith("F")) { return FloatValue.ParseString(number.GetText()) * factor; } else { return DoubleValue.ParseString(number.GetText()) * factor; } } throw ASTWalkException.From("Encountered unrecognized constant", number.GetText()); }
public override IOperation Apply() { ItemArray <BinaryVector> binaryVectors = BinaryVectorParameter.ActualValue; ItemArray <DoubleValue> qualities = QualityParameter.ActualValue; ResultCollection results = ResultsParameter.ActualValue; bool max = MaximizationParameter.ActualValue.Value; DoubleValue bestKnownQuality = BestKnownQualityParameter.ActualValue; int i = -1; if (!max) { i = qualities.Select((x, index) => new { index, x.Value }).OrderBy(x => x.Value).First().index; } else { i = qualities.Select((x, index) => new { index, x.Value }).OrderByDescending(x => x.Value).First().index; } if (bestKnownQuality == null || max && qualities[i].Value > bestKnownQuality.Value || !max && qualities[i].Value < bestKnownQuality.Value) { BestKnownQualityParameter.ActualValue = new DoubleValue(qualities[i].Value); } OneMaxSolution solution = BestSolutionParameter.ActualValue; if (solution == null) { solution = new OneMaxSolution((BinaryVector)binaryVectors[i].Clone(), new DoubleValue(qualities[i].Value)); BestSolutionParameter.ActualValue = solution; results.Add(new Result("Best OneMax Solution", solution)); } else { if (max && qualities[i].Value > solution.Quality.Value || !max && qualities[i].Value < solution.Quality.Value) { solution.BinaryVector = (BinaryVector)binaryVectors[i].Clone(); solution.Quality = new DoubleValue(qualities[i].Value); } } return(base.Apply()); }
private List<IFilter> CreateFilters(string match, ComparisonOperation comparisonOperation, int columnIndex) { IPreprocessingData preprocessingData = Content.PreprocessingData; IStringConvertibleValue value; if (preprocessingData.VariableHasType<double>(columnIndex)) { value = new DoubleValue(); } else if (preprocessingData.VariableHasType<String>(columnIndex)) { value = new StringValue(); } else if (preprocessingData.VariableHasType<DateTime>(columnIndex)) { value = new DateTimeValue(); } else { throw new ArgumentException("unsupported type"); } value.SetValue(match); var comparisonFilter = new ComparisonFilter(preprocessingData, GetConstraintOperation(comparisonOperation), value, true); comparisonFilter.ConstraintColumn = columnIndex; return new List<Filter.IFilter>() { comparisonFilter }; }
private bool ParseDU(string v, string unitName, Qualities q) { if (String.IsNullOrEmpty(v)) { return(false); } v = StringEx.RemoveReferences(v); ValueQualifier vq = DoubleValue.FindQualifier(ref v); double d; if (UnitValue.TryParse(v, unitName, out d)) { UnitValue uv = new UnitValue(d, unitName, vq); return(SetValue(q, uv)); } return(false); }
public CompiledConstStringValue(char ch, LongValue longValue, DoubleValue doubleValue, ValueType valueType, int hashCode) : base(ch) { setString(String.valueOf(ch)); setLongValue(longValue); setDoubleValue(doubleValue); setValueType(valueType); setKey(super.toKey()); setLowerCase(toLowerCase(Locale.ENGLISH)); _compiledHashCode = hashCode; }
public override string ToString() { switch (Type) { case UniversalClassType.Numeric: return(DoubleValue.ToString(CultureInfo.InvariantCulture)); case UniversalClassType.TimeSpan: return(TimespanValue.ToString()); case UniversalClassType.String: return(StringValue); default: throw new Exception("Unknown type " + Type); } }
public override string ToString() { switch (genValue) { case GeneratorSettings.GeneratedValue.EnumerableValue: return("Constant" + '\'' + EnumerableValue.ToString() + '\''); case GeneratorSettings.GeneratedValue.IntegerValue: return("Constant" + IntegerValue.ToString()); case GeneratorSettings.GeneratedValue.DoubleValue: return("Constant" + DoubleValue.ToString()); default: return(string.Empty); } }
public override string GetStringStartValue() { switch (genValue) { case GeneratorSettings.GeneratedValue.EnumerableValue: return('\'' + EnumerableValue.ToString() + '\''); case GeneratorSettings.GeneratedValue.IntegerValue: return(IntegerValue.ToString()); case GeneratorSettings.GeneratedValue.DoubleValue: return(DoubleValue.ToString()); default: return(string.Empty); } }
protected override void Run(CancellationToken cancellationToken) { var BestQuality = new DoubleValue(double.NaN); Results.Add(new Result("Best quality", BestQuality)); for (int iteration = 0; iteration < Iterations; iteration++) { var solution = new BinaryVector(Problem.Length); for (int i = 0; i < solution.Length; i++) { solution[i] = random.Next(2) == 1; } var fitness = Problem.Evaluate(solution, random); fitness = ImproveToLocalOptimum(Problem, solution, fitness, random); if (double.IsNaN(BestQuality.Value) || Problem.IsBetter(fitness, BestQuality.Value)) { BestQuality.Value = fitness; } } }
private VRPSolution(VRPSolution original, Cloner cloner) : base(original, cloner) { this.solution = (IVRPEncoding)cloner.Clone(original.solution); this.quality = (DoubleValue)cloner.Clone(original.quality); if (original.ProblemInstance != null && cloner.ClonedObjectRegistered(original.ProblemInstance)) { this.ProblemInstance = (IVRPProblemInstance)cloner.Clone(original.ProblemInstance); } else { this.ProblemInstance = original.ProblemInstance; } this.Initialize(); }
public override int GetHashCode() { unchecked { var result = GuidValue.GetHashCode(); result = (result * 397) ^ (StringValue != null ? StringValue.GetHashCode() : 0); result = (result * 397) ^ IntValue; result = (result * 397) ^ LongValue.GetHashCode(); result = (result * 397) ^ BoolValue.GetHashCode(); result = (result * 397) ^ ByteValue.GetHashCode(); result = (result * 397) ^ DecimalValue.GetHashCode(); result = (result * 397) ^ DoubleValue.GetHashCode(); result = (result * 397) ^ DateTimeValue.GetHashCode(); result = (result * 397) ^ MaybeMoney.GetHashCode(); return(result); } }
/// <summary> /// Ensures that the length of the section is consistent with EFS's length scale /// </summary> /// <param name="length"></param> /// <returns></returns> private IValue SegmentLength(double length) { IValue retVal = new DoubleValue(EFSSystem.DoubleType, length); NameSpace defaultNameSpace = OverallNameSpaceFinder.INSTANCE.findByName(EFSSystem.Dictionaries[0], "Default.BaseTypes"); Range LengthType = defaultNameSpace.findTypeByName("Length") as Range; EnumValue infinity = LengthType.findEnumValue("Infinity"); if (!LengthType.Less(retVal, infinity)) { retVal = infinity; } return(retVal); }
public override IOperation Apply() { DoubleArray[] qualities = QualitiesParameter.ActualValue.ToArray(); int populationSize = qualities.Length; DoubleValue[] distances = new DoubleValue[populationSize]; for (int i = 0; i < populationSize; i++) { distances[i] = new DoubleValue(0); } CrowdingDistanceParameter.ActualValue = new ItemArray <DoubleValue>(distances); Apply(qualities, distances); return(base.Apply()); }
public override IOperation Apply() { DoubleValue left = LeftSideParameter.ActualValue; DoubleValue right = RightSideParameter.ActualValue; BoolValue maximization = MaximizationParameter.ActualValue; bool better = Compare(maximization.Value, left.Value, right.Value); if (ResultParameter.ActualValue == null) { ResultParameter.ActualValue = new BoolValue(better); } else { ResultParameter.ActualValue.Value = better; } return(base.Apply()); }
private IOperation UpdateVelocityBounds() { if (CurrentVelocityBounds == null) { CurrentVelocityBounds = (DoubleMatrix)VelocityBounds.Clone(); } if (VelocityBoundsScalingOperator == null) { return new OperationCollection() { ExecutionContext.CreateChildOperation(ResultsCollector), base.Apply() } } ; DoubleMatrix matrix = CurrentVelocityBounds; if (VelocityBoundsScale == null && VelocityBoundsStartValue != null) { VelocityBoundsScale = new DoubleValue(VelocityBoundsStartValue.Value); } for (int i = 0; i < matrix.Rows; i++) { for (int j = 0; j < matrix.Columns; j++) { if (matrix[i, j] >= 0) { matrix[i, j] = VelocityBoundsScale.Value; } else { matrix[i, j] = (-1) * VelocityBoundsScale.Value; } } } return(new OperationCollection() { ExecutionContext.CreateChildOperation(ResultsCollector), ExecutionContext.CreateChildOperation(VelocityBoundsScalingOperator), base.Apply() }); } }
public int CompareTo(IndexValue other) { if (ReferenceEquals(this, other)) { return(0); } if (ReferenceEquals(null, other)) { return(1); } var typeComparison = Type.CompareTo(other.Type); if (typeComparison != 0) { return(typeComparison); } switch (Type) { case IndexValueType.String: return(string.Compare(StringValue, other.StringValue, StringComparison.Ordinal)); case IndexValueType.StringArray: return(string.Compare(ValueAsString, other.ValueAsString, StringComparison.Ordinal)); case IndexValueType.Bool: return(BooleanValue.CompareTo(other.BooleanValue)); case IndexValueType.Int: return(IntegerValue.CompareTo(other.IntegerValue)); case IndexValueType.Long: return(LongValue.CompareTo(other.LongValue)); case IndexValueType.Float: return(SingleValue.CompareTo(other.SingleValue)); case IndexValueType.Double: return(DoubleValue.CompareTo(other.DoubleValue)); case IndexValueType.DateTime: return(DateTimeValue.CompareTo(other.DateTimeValue)); default: throw new ArgumentOutOfRangeException(); } }
private void UpdateParameterValues() { Permutation lbSolution; // calculate the optimum of a LAP relaxation and use it as lower bound of our QAP LowerBound = new DoubleValue(GilmoreLawlerBoundCalculator.CalculateLowerBound(Weights, Distances, out lbSolution)); // evalute the LAP optimal solution as if it was a QAP solution var lbSolutionQuality = QAPEvaluator.Apply(lbSolution, Weights, Distances); // in case both qualities are the same it means that the LAP optimum is also a QAP optimum if (LowerBound.Value.IsAlmost(lbSolutionQuality)) { BestKnownSolution = lbSolution; BestKnownQuality = new DoubleValue(LowerBound.Value); } AverageQuality = new DoubleValue(ComputeAverageQuality()); }
public OneMaxProblem() : base(new OneMaxEvaluator(), new RandomBinaryVectorCreator()) { Parameters.Add(new ValueParameter <IntValue>("Length", "The length of the BinaryVector.", new IntValue(5))); Maximization.Value = true; MaximizationParameter.Hidden = true; BestKnownQuality = new DoubleValue(5); SolutionCreator.BinaryVectorParameter.ActualName = "OneMaxSolution"; Evaluator.QualityParameter.ActualName = "NumberOfOnes"; ParameterizeSolutionCreator(); ParameterizeEvaluator(); InitializeOperators(); RegisterEventHandlers(); }
/// <summary> /// Provides the value of the function /// </summary> /// <param name="context"></param> /// <param name="actuals">the actual parameters values</param> /// <param name="explain"></param> /// <returns>The value for the function application</returns> public override IValue Evaluate(InterpretationContext context, Dictionary <Actual, IValue> actuals, ExplanationPart explain) { IValue retVal = null; int token = context.LocalScope.PushContext(); AssignParameters(context, actuals); Function function = context.FindOnStack(Function).Value as Function; if (function != null) { double speed = GetDoubleValue(context.FindOnStack(Speed).Value); Parameter parameter = (Parameter)function.FormalParameters[0]; int token2 = context.LocalScope.PushContext(); context.LocalScope.SetGraphParameter(parameter); Graph graph = function.CreateGraph(context, (Parameter)function.FormalParameters[0], explain); context.LocalScope.PopContext(token2); if (graph != null) { double solutionX = graph.SolutionX(speed); if (solutionX == double.MaxValue) { Range distanceType = (Range)EFSSystem.FindByFullName("Default.BaseTypes.Distance"); retVal = distanceType.findEnumValue("Unknown"); } else { retVal = new DoubleValue(EFSSystem.DoubleType, solutionX); } } else { Function.AddError("Cannot evaluate graph for function while computing the distance for the given speed"); } } else { Function.AddError("Cannot get function for " + Function); } context.LocalScope.PopContext(token); return(retVal); }
public double?Calcular() { int cont = 0; double fx, fxk, x; bool refinou = false; dados.parser = new ExpressionParser(); var xParser = new DoubleValue(); xParser.Value = x = dados.a; dados.parser.Values.Add("x", xParser); fx = dados.parser.Parse(dados.func); Iterações += "------- " + dados.func + " -------" + Environment.NewLine; do { xParser.Value = x + dados.delta; fxk = dados.parser.Parse(dados.func); Iterações += "Iter. " + cont + "->" + Environment.NewLine; Iterações += "x = " + x + Environment.NewLine + "fx = " + fx + Environment.NewLine + "xk = " + xParser.Value + Environment.NewLine + "fxk = " + fxk + Environment.NewLine; if (fxk < fx) { fx = fxk; x = xParser.Value; } else if (!refinou) { xParser.Value = xParser.Value - (2 * dados.delta); dados.delta = dados.delta / 10; refinou = true; } else { OnFinishCalculating(); return(x); } cont++; } while (xParser.Value <= dados.b); OnFinishCalculating(); return(x); }
public double?Calcular() { int cont = 0; double fn = F((infos.b - infos.a) / infos.l); double mi = infos.a + ((fib[n - cont - 2] / fib[n - cont]) * (infos.b - infos.a)), lamb = infos.a + ((fib[n - cont - 1] / fib[n - cont]) * (infos.b - infos.a)), fmi, flamb; infos.parser = new ExpressionParser(); var valueParser = new DoubleValue(); infos.parser.Values.Add("x", valueParser); Iterações += "------- " + infos.func + " -------" + Environment.NewLine; while (cont < n - 1 && Math.Abs(infos.b - infos.a) > infos.l) { valueParser.Value = mi; fmi = infos.parser.Parse(infos.func); valueParser.Value = lamb; flamb = infos.parser.Parse(infos.func); Iterações += "Iter. " + (cont + 1) + " ->" + Environment.NewLine; Iterações += "a = " + infos.a + Environment.NewLine; Iterações += "b = " + infos.b + Environment.NewLine; Iterações += "mi = " + mi + Environment.NewLine; Iterações += "fmi = " + fmi + Environment.NewLine; Iterações += "lamb = " + lamb + Environment.NewLine; Iterações += "flamb = " + flamb + Environment.NewLine; if (fmi > flamb) { infos.a = mi; mi = lamb; lamb = infos.a + ((fib[n - cont - 1] / fib[n - cont]) * (infos.b - infos.a)); } else if (fmi < flamb) { infos.b = lamb; lamb = mi; mi = infos.a + ((fib[n - cont - 2] / fib[n - cont]) * (infos.b - infos.a)); } cont++; } OnFinishCalculating(); return((infos.a + infos.b) / 2); }
public void SimulatedBinaryCrossoverApplyTest() { TestRandom random = new TestRandom(); RealVector parent1, parent2, expected, actual; DoubleValue contiguity; bool exceptionFired; // The following test is not based on published examples random.Reset(); random.DoubleNumbers = new double[] { 0.3, 0.9, 0.7, 0.2, 0.8, 0.1, 0.2, 0.3, 0.4, 0.8, 0.7 }; contiguity = new DoubleValue(0.3); parent1 = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1 }); parent2 = new RealVector(new double[] { 0.4, 0.1, 0.3, 0.2, 0.8 }); expected = new RealVector(new double[] { 0.644880972204315, 0.0488239539275703, 0.3, 0.5, 0.1 }); actual = SimulatedBinaryCrossover.Apply(random, parent1, parent2, contiguity); Assert.IsTrue(Auxiliary.RealVectorIsAlmostEqualByPosition(actual, expected)); // The following test is not based on published examples random.Reset(); random.DoubleNumbers = new double[] { 0.3, 0.9, 0.7, 0.2, 0.8, 0.1, 0.2, 0.3, 0.4, 0.8, 0.7 }; contiguity = new DoubleValue(0.3); parent1 = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1, 0.9 }); // this parent is longer parent2 = new RealVector(new double[] { 0.4, 0.1, 0.3, 0.2, 0.8 }); exceptionFired = false; try { actual = SimulatedBinaryCrossover.Apply(random, parent1, parent2, contiguity); } catch (System.ArgumentException) { exceptionFired = true; } Assert.IsTrue(exceptionFired); // The following test is not based on published examples random.Reset(); random.DoubleNumbers = new double[] { 0.3, 0.9, 0.7, 0.2, 0.8, 0.1, 0.2, 0.3, 0.4, 0.8, 0.7 }; contiguity = new DoubleValue(-0.3); // contiguity < 0 parent1 = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1 }); parent2 = new RealVector(new double[] { 0.4, 0.1, 0.3, 0.2, 0.8 }); exceptionFired = false; try { actual = SimulatedBinaryCrossover.Apply(random, parent1, parent2, contiguity); } catch (System.ArgumentException) { exceptionFired = true; } Assert.IsTrue(exceptionFired); }
/// <summary> /// Performs the blend alpha crossover (BLX-a) of two real vectors.<br/> /// It creates new offspring by sampling a new value in the range [min_i - d * alpha, max_i + d * alpha) at each position i. /// Here min_i and max_i are the smaller and larger value of the two parents at position i and d is max_i - min_i. /// </summary> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="parent1"/> and <paramref name="parent2"/> are of different length or<br/> /// when <paramref name="alpha"/> is less than 0. /// </exception> /// <param name="random">The random number generator.</param> /// <param name="parent1">The first parent for the crossover operation.</param> /// <param name="parent2">The second parent for the crossover operation.</param> /// <param name="alpha">The alpha value for the crossover.</param> /// <returns>The newly created real vector resulting from the crossover operation.</returns> public static RealVector Apply(IRandom random, RealVector parent1, RealVector parent2, DoubleValue alpha) { if (parent1.Length != parent2.Length) throw new ArgumentException("BlendAlphaCrossover: The parents' vectors are of different length.", "parent1"); if (alpha.Value < 0) throw new ArgumentException("BlendAlphaCrossover: Paramter alpha must be greater or equal than 0.", "alpha"); int length = parent1.Length; RealVector result = new RealVector(length); double max = 0, min = 0, d = 0, resMin = 0, resMax = 0; for (int i = 0; i < length; i++) { max = Math.Max(parent1[i], parent2[i]); min = Math.Min(parent1[i], parent2[i]); d = Math.Abs(max - min); resMin = min - d * alpha.Value; resMax = max + d * alpha.Value; result[i] = resMin + random.NextDouble() * Math.Abs(resMax - resMin); } return result; }
public void DoubleValue_IsEqual_True() { // reference equality Assert.IsTrue(_nonzeroValue.IsEqual(_nonzeroValue)); Assert.IsTrue(_zeroValue.IsEqual(_zeroValue)); Assert.IsTrue(_defaultValue.IsEqual(_defaultValue)); DoubleValue anotherValue = new DoubleValue(aDouble); Assert.IsTrue(_nonzeroValue.IsEqual(anotherValue)); anotherValue.Value = 0.0; Assert.IsTrue(_zeroValue.IsEqual(anotherValue)); anotherValue.IsVaries = true; _nonzeroValue.IsVaries = true; Assert.IsTrue(_nonzeroValue.IsEqual(anotherValue)); anotherValue.IsIndeterminate = true; Assert.IsTrue(_defaultValue.IsEqual(anotherValue)); }
private bool ParseVanDerWaalsRadius(string s, Qualities q) { const string UNIT = "pm"; ValueQualifier vq = DoubleValue.FindQualifier(ref s); int n = s.IndexOf(UNIT); if (n > 0) { s = s.Substring(0, n - 1).Trim(); double d; if (UnitValue.TryParse(s, out d)) { q.VanDerWaalsRadius = new UnitValue(d, UNIT, vq); return(true); } } return(false); }
public CompiledConstStringValue(String s, LongValue longValue, DoubleValue doubleValue, ValueType valueType, Value key, int hashCode) : base(s) { setString(s); setLongValue(longValue); setDoubleValue(doubleValue); setValueType(valueType); setKey(key); setLowerCase(toLowerCase(Locale.ENGLISH)); _compiledHashCode = hashCode; }
protected void CreateCriteriaContext() { var maxTopStackOccurrence = new UintValue(uint.MinValue); var maxDuration = new DoubleValue(uint.MinValue); foreach (Method method in _methodDictionary.Values) { maxTopStackOccurrence = (UintValue) Max(method.GetValueFor(SamplingCriteriaContext.TopStackOccurrenceCriterion), maxTopStackOccurrence); maxDuration = (DoubleValue) Max(method.GetValueFor(SamplingCriteriaContext.DurationCriterion), maxDuration); } CriteriaContext = new SamplingCriteriaContext( maxTopStackOccurrence, maxDuration); }
private bool ParseAtomicRadius(string s, Qualities q) { const string UNIT = Units.PicoMeter; ValueQualifier vq = DoubleValue.FindQualifier(ref s); int ndx = s.IndexOf(UNIT); if (ndx > 0) { s = s.Substring(0, ndx - 1).Trim(); double d; if (UnitValue.TryParse(s, out d)) { q.AtomicRadius = new UnitValue(d, UNIT, vq); return(true); } } return(false); }
private bool ParseShearModulus(string s, Qualities q) { const string UNIT = "GPa"; s = StringEx.RemoveReferences(s); double d; if (s.IndexOf("–") > 0) { double d1, d2; if (DoubleValue.TryParseRange(s, out d1, out d2)) { d = (d1 + d2) / 2; q.ShearModulus = new UnitValue(d, UNIT); } } return(ParseDU(s, UNIT, q)); }
protected bool Equals(ClassWithAllTypes other) { return(CharValue == other.CharValue && ByteValue == other.ByteValue && SByteValue == other.SByteValue && ShortValue == other.ShortValue && UShortValue == other.UShortValue && IntValue == other.IntValue && UIntValue == other.UIntValue && LongValue == other.LongValue && ULongValue == other.ULongValue && FloatValue.Equals(other.FloatValue) && DoubleValue.Equals(other.DoubleValue) && DecimalValue == other.DecimalValue && DateTimeValue.Equals(other.DateTimeValue) && GuidValue.Equals(other.GuidValue) && StringValue.Equals(other.StringValue)); }
/// <summary> /// Performs the arithmetic crossover on some positions by taking either x = alpha * p1 + (1 - alpha) * p2 or x = p1 depending on the probability for a gene to be crossed. /// </summary> /// <param name="random">The random number generator.</param> /// <param name="parent1">The first parent vector.</param> /// <param name="parent2">The second parent vector.</param> /// <param name="bounds">The bounds and step size for each dimension (will be cycled in case there are less rows than elements in the parent vectors).</param> /// <param name="alpha">The alpha parameter (<see cref="AlphaParameter"/>).</param> /// <param name="probability">The probability parameter (<see cref="ProbabilityParameter"/>).</param> /// <returns>The vector resulting from the crossover.</returns> public static IntegerVector Apply(IRandom random, IntegerVector parent1, IntegerVector parent2, IntMatrix bounds, DoubleValue alpha, DoubleValue probability) { int length = parent1.Length; if (length != parent2.Length) throw new ArgumentException("RoundedUniformArithmeticCrossover: The parent vectors are of different length.", "parent1"); if (alpha.Value < 0 || alpha.Value > 1) throw new ArgumentException("RoundedUniformArithmeticCrossover: Parameter alpha must be in the range [0;1]", "alpha"); if (probability.Value < 0 || probability.Value > 1) throw new ArgumentException("RoundedUniformArithmeticCrossover: Parameter probability must be in the range [0;1]", "probability"); var result = new IntegerVector(length); for (int i = 0; i < length; i++) { if (random.NextDouble() < probability.Value) { int min = bounds[i % bounds.Rows, 0], max = bounds[i % bounds.Rows, 1], step = 1; if (bounds.Columns > 2) step = bounds[i % bounds.Rows, 2]; max = FloorFeasible(min, max, step, max - 1); double value = alpha.Value * parent1[i] + (1 - alpha.Value) * parent2[i]; result[i] = RoundFeasible(min, max, step, value); } else result[i] = parent1[i]; } return result; }
public void ReadRow_AutoMappedDouble_Success() { using (var importer = Helpers.GetImporter("Doubles.xlsx")) { ExcelSheet sheet = importer.ReadSheet(); sheet.ReadHeading(); // Valid cell value. DoubleValue row1 = sheet.ReadRow <DoubleValue>(); Assert.Equal(2.2345, row1.Value); // Empty cell value. Assert.Throws <ExcelMappingException>(() => sheet.ReadRow <DoubleValue>()); // Invalid cell value. Assert.Throws <ExcelMappingException>(() => sheet.ReadRow <DoubleValue>()); } }
public void SimulatedBinaryCrossoverApplyTest() { TestRandom random = new TestRandom(); RealVector parent1, parent2, expected, actual; DoubleValue contiguity; bool exceptionFired; // The following test is not based on published examples random.Reset(); random.DoubleNumbers = new double[] { 0.3, 0.9, 0.7, 0.2, 0.8, 0.1, 0.2, 0.3, 0.4, 0.8, 0.7 }; contiguity = new DoubleValue(0.3); parent1 = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1 }); parent2 = new RealVector(new double[] { 0.4, 0.1, 0.3, 0.2, 0.8 }); expected = new RealVector(new double[] { 0.644880972204315, 0.0488239539275703, 0.3, 0.5, 0.1 }); actual = SimulatedBinaryCrossover.Apply(random, parent1, parent2, contiguity); Assert.IsTrue(Auxiliary.RealVectorIsAlmostEqualByPosition(actual, expected)); // The following test is not based on published examples random.Reset(); random.DoubleNumbers = new double[] { 0.3, 0.9, 0.7, 0.2, 0.8, 0.1, 0.2, 0.3, 0.4, 0.8, 0.7 }; contiguity = new DoubleValue(0.3); parent1 = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1, 0.9 }); // this parent is longer parent2 = new RealVector(new double[] { 0.4, 0.1, 0.3, 0.2, 0.8 }); exceptionFired = false; try { actual = SimulatedBinaryCrossover.Apply(random, parent1, parent2, contiguity); } catch (System.ArgumentException) { exceptionFired = true; } Assert.IsTrue(exceptionFired); // The following test is not based on published examples random.Reset(); random.DoubleNumbers = new double[] { 0.3, 0.9, 0.7, 0.2, 0.8, 0.1, 0.2, 0.3, 0.4, 0.8, 0.7 }; contiguity = new DoubleValue(-0.3); // contiguity < 0 parent1 = new RealVector(new double[] { 0.2, 0.2, 0.3, 0.5, 0.1 }); parent2 = new RealVector(new double[] { 0.4, 0.1, 0.3, 0.2, 0.8 }); exceptionFired = false; try { actual = SimulatedBinaryCrossover.Apply(random, parent1, parent2, contiguity); } catch (System.ArgumentException) { exceptionFired = true; } Assert.IsTrue(exceptionFired); }
public override List<Tour> GetTours() { List<Tour> tours = new List<Tour>(); foreach (Tour tour in base.Tours) { Tour newTour = new Tour(); double currentDemand = 0; DoubleValue capacity = new DoubleValue(double.MaxValue); if (ProblemInstance is IHomogenousCapacitatedProblemInstance) { capacity.Value = (ProblemInstance as IHomogenousCapacitatedProblemInstance).Capacity.Value; } foreach (int city in tour.Stops) { currentDemand += ProblemInstance.GetDemand(city); if (currentDemand > capacity.Value) { if (newTour.Stops.Count > 0) tours.Add(newTour); newTour = new Tour(); newTour.Stops.Add(city); currentDemand = ProblemInstance.GetDemand(city); } else { newTour.Stops.Add(city); } } if (newTour.Stops.Count > 0) tours.Add(newTour); } //repair if there are too many vehicles used while (tours.Count > ProblemInstance.Vehicles.Value) { Tour tour = tours[tours.Count - 1]; tours[tours.Count - 2].Stops.AddRange(tour.Stops); tours.Remove(tour); } return tours; }
protected void CreateCriteriaContext() { var maxCallCount = new UintValue(uint.MinValue); var maxWallClockDuration = new Uint64Value(uint.MinValue); var maxActiveTime = new DoubleValue(double.MinValue); foreach (Method method in _methodDictionary.Values) { maxCallCount = (UintValue) Max(method.GetValueFor(TracingCriteriaContext.CallCountCriterion), maxCallCount); maxWallClockDuration = (Uint64Value) Max(method.GetValueFor(TracingCriteriaContext.TimeWallClockCriterion), maxWallClockDuration); maxActiveTime = (DoubleValue) Max(method.GetValueFor(TracingCriteriaContext.TimeActiveCriterion), maxActiveTime); } CriteriaContext = new TracingCriteriaContext( maxCallCount, maxWallClockDuration, maxActiveTime); }
/// <summary> /// Performs the simulated binary crossover on a real vector. Each position is crossed with a probability of 50% and if crossed either a contracting crossover or an expanding crossover is performed, again with equal probability. /// For more details refer to the paper by Deb and Agrawal. /// </summary> /// <exception cref="ArgumentException">Thrown when the parents' vectors are of unequal length or when <paramref name="contiguity"/> is smaller than 0.</exception> /// <remarks> /// The manipulated value is not restricted by the (possibly) specified lower and upper bounds. Use the <see cref="BoundsChecker"/> to correct the values after performing the crossover. /// </remarks> /// <param name="random">The random number generator to use.</param> /// <param name="parent1">The first parent vector.</param> /// <param name="parent2">The second parent vector.</param> /// <param name="contiguity">The contiguity value that specifies how close a child should be to its parents (larger value means closer). The value must be greater or equal than 0. Typical values are in the range [2;5].</param> /// <returns>The vector resulting from the crossover.</returns> public static RealVector Apply(IRandom random, RealVector parent1, RealVector parent2, DoubleValue contiguity) { if (parent1.Length != parent2.Length) throw new ArgumentException("SimulatedBinaryCrossover: Parents are of unequal length"); if (contiguity.Value < 0) throw new ArgumentException("SimulatedBinaryCrossover: Contiguity value is smaller than 0", "contiguity"); int length = parent1.Length; RealVector result = new RealVector(length); for (int i = 0; i < length; i++) { if (length == 1 || random.NextDouble() < 0.5) { // cross this variable double u = random.NextDouble(); double beta = 0; if (u < 0.5) { // if u is smaller than 0.5 perform a contracting crossover beta = Math.Pow(2 * u, 1.0 / (contiguity.Value + 1)); } else if (u > 0.5) { // otherwise perform an expanding crossover beta = Math.Pow(0.5 / (1.0 - u), 1.0 / (contiguity.Value + 1)); } else if (u == 0.5) beta = 1; if (random.NextDouble() < 0.5) result[i] = ((parent1[i] + parent2[i]) / 2.0) - beta * 0.5 * Math.Abs(parent1[i] - parent2[i]); else result[i] = ((parent1[i] + parent2[i]) / 2.0) + beta * 0.5 * Math.Abs(parent1[i] - parent2[i]); } else result[i] = parent1[i]; } return result; }