• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# IntValue类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中IntValue的典型用法代码示例。如果您正苦于以下问题:C# IntValue类的具体用法?C# IntValue怎么用?C# IntValue使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



IntValue类属于命名空间,在下文中一共展示了IntValue类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: AntTrail

 public AntTrail(BoolMatrix world, SymbolicExpressionTree expression, IntValue maxTimeSteps)
   : this() {
   this.world = world;
   this.expression = expression;
   this.maxTimeSteps = maxTimeSteps;
   Initialize();
 }
开发者ID:thunder176,项目名称:HeuristicLab,代码行数:7,代码来源:AntTrail.cs


示例2: TestUpdateBranchingNameSpaces

        public void TestUpdateBranchingNameSpaces()
        {
            Dictionary dictionary = CreateDictionary("Test");
            NameSpace nameSpace = CreateNameSpace(dictionary, "N");
            NameSpace nameSpace1 = CreateNameSpace(nameSpace, "N1");
            NameSpace nameSpace2 = CreateNameSpace(nameSpace, "N2");

            Function function1 = CreateFunction(nameSpace1, "f", "Bool");
            Case cas1 = CreateCase(function1, "Case 1", "N2.q()");

            Function function2 = CreateFunction(nameSpace2, "q", "Bool");
            Case cas2 = CreateCase(function2, "Case 1", "True");

            Dictionary dictionary2 = CreateDictionary("TestUpdate");
            dictionary2.setUpdates(dictionary.Guid);

            Function updateFunction1 = function1.CreateFunctionUpdate(dictionary2);
            updateFunction1.TypeName = "Integer";
            Case updcas1 = (Case) updateFunction1.Cases[0];
            updcas1.ExpressionText = "2";
            PreCondition precond = CreatePreCondition(updcas1, "N2.q()");
            Case newCase = CreateCase(updateFunction1, "Case 2", "1");

            Function updateFunction2 = function2.CreateFunctionUpdate(dictionary2);
            ((Case) updateFunction2.Cases[0]).ExpressionText = "False";

            Compiler.Compile_Synchronous(true);

            Expression expression = Parser.Expression(dictionary, "N.N1.f()");
            IValue value = expression.GetValue(new InterpretationContext(), null);
            IValue refVal = new IntValue(System.IntegerType, 1);
            Assert.AreEqual(refVal.LiteralName, value.LiteralName);
        }
开发者ID:JamesOakey,项目名称:ERTMSFormalSpecs,代码行数:33,代码来源:UpdateNameSpaceTest.cs


示例3: read

 public Value read(BinaryReader reader)
 {
   IntValue ret = new IntValue();
   int val = reader.ReadInt32();
   ret.value = val;
   return ret;
 }
开发者ID:Logeshkumar,项目名称:Projects,代码行数:7,代码来源:Program.cs


示例4: Add

 public void Add()
 {
     var three = new IntValue(3);
     var five = new IntValue(5);
     var threePlusFive = three + five;
     AssertEquals(threePlusFive.Value, 8);
 }
开发者ID:x335,项目名称:WootzJs,代码行数:7,代码来源:OperatorOverloadTests.cs


示例5: MichalewiczNonUniformAllPositionsManipulatorApplyTest

 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);
 }
开发者ID:thunder176,项目名称:HeuristicLab,代码行数:34,代码来源:MichalewiczNonUniformAllPositionsManipulatorTest.cs


示例6: Apply

    public static ItemArray<IItem> Apply(IItem initiator, IItem guide, IntValue k, PercentValue n) {
      if (!(initiator is RealVector) || !(guide is RealVector))
        throw new ArgumentException("Cannot relink path because one of the provided solutions or both have the wrong type.");
      if (n.Value <= 0.0)
        throw new ArgumentException("RelinkingAccuracy must be greater than 0.");

      RealVector v1 = initiator.Clone() as RealVector;
      RealVector v2 = guide as RealVector;

      if (v1.Length != v2.Length)
        throw new ArgumentException("The solutions are of different length.");

      IList<RealVector> solutions = new List<RealVector>();
      for (int i = 0; i < k.Value; i++) {
        RealVector solution = v1.Clone() as RealVector;
        for (int j = 0; j < solution.Length; j++)
          solution[j] = v1[j] + 1 / (k.Value - i) * (v2[j] - v1[j]);
        solutions.Add(solution);
      }

      IList<IItem> selection = new List<IItem>();
      if (solutions.Count > 0) {
        int noSol = (int)(solutions.Count * n.Value);
        if (noSol <= 0) noSol++;
        double stepSize = (double)solutions.Count / (double)noSol;
        for (int i = 0; i < noSol; i++)
          selection.Add(solutions.ElementAt((int)((i + 1) * stepSize - stepSize * 0.5)));
      }

      return new ItemArray<IItem>(selection);
    }
开发者ID:thunder176,项目名称:HeuristicLab,代码行数:31,代码来源:SingleObjectiveTestFunctionPathRelinker.cs


示例7: PRVRandomCreator

 public PRVRandomCreator()
   : base() {
   NrOfRules = new IntValue(10);
   Parameters.Add(new LookupParameter<IRandom>("Random", "The pseudo random number generator."));
   Parameters.Add(new ValueLookupParameter<IntValue>("Jobs", "The number of jobs handled in this problem instance."));
   Parameters.Add(new ValueLookupParameter<IntValue>("Resources", "The number of resources used in this problem instance."));
   ScheduleEncodingParameter.ActualName = "PriorityRulesVector";
 }
开发者ID:t-h-e,项目名称:HeuristicLab,代码行数:8,代码来源:PRVRandomCreator.cs


示例8: Create

    protected override IntegerVector Create(IRandom random, IntValue length, IntMatrix bounds) {
      int startPoint = StartingPointParameter.ActualValue.Value;
      int endPoint = TerminalPointParameter.ActualValue.Value;
      int numPoints = ScoresParameter.ActualValue.Length;
      var distances = DistanceMatrixParameter.ActualValue;
      double pointVisitingCosts = PointVisitingCostsParameter.ActualValue.Value;
      double maxDistance = MaximumDistanceParameter.ActualValue.Value;
      var scores = ScoresParameter.ActualValue;

      // Find all points within the maximum distance allowed (ellipse)
      var feasiblePoints = (
        from point in Enumerable.Range(0, numPoints)
        let distance = distances[startPoint, point] + distances[point, endPoint] + pointVisitingCosts
        let score = scores[point]
        where distance <= maxDistance
        where point != startPoint && point != endPoint
        orderby score descending
        select point
      ).ToList();

      // Add the starting and terminus point
      var tour = new List<int> {
        startPoint,
        endPoint
      };
      double tourLength = distances[startPoint, endPoint];

      // Add points in a greedy way
      bool insertionPerformed = true;
      while (insertionPerformed) {
        insertionPerformed = false;

        for (int i = 0; i < feasiblePoints.Count; i++) {
          for (int insertPosition = 1; insertPosition < tour.Count; insertPosition++) {
            // Create the candidate tour
            double detour = distances.CalculateInsertionCosts(tour, insertPosition, feasiblePoints[i], pointVisitingCosts);

            // If the insertion would be feasible, perform it
            if (tourLength + detour <= maxDistance) {
              tour.Insert(insertPosition, feasiblePoints[i]);
              tourLength += detour;
              feasiblePoints.RemoveAt(i);
              insertionPerformed = true;
              break;
            }
          }
          if (insertionPerformed) break;
        }
      }

      return new IntegerVector(tour.ToArray());
    }
开发者ID:t-h-e,项目名称:HeuristicLab,代码行数:52,代码来源:GreedyOrienteeringTourCreator.cs


示例9: Ints

        public void Ints()
        {
            IntValue value1 = new IntValue();
            IntValue value2 = new IntValue();
            IntValue value3 = new IntValue();

            value1.Value = 1;
            value2.Value = 1;
            value3.Value = 2;

            Assert.That(value1 == value2);
            Assert.That(value1 != value3);
        }
开发者ID:FlukeFan,项目名称:OfflineExample,代码行数:13,代码来源:TestParameterObject.cs


示例10: Apply

    /// <summary>
    /// Performs a N point crossover at randomly chosen positions of the two 
    /// given parent binary vectors.
    /// </summary>
    /// <exception cref="ArgumentException">Thrown when the value for N is invalid or when the parent vectors are of different length.</exception>
    /// <param name="random">A random number generator.</param>
    /// <param name="parent1">The first parent for crossover.</param>
    /// <param name="parent2">The second parent for crossover.</param>
    /// <param name="n">Number of crossover points.</param>
    /// <returns>The newly created binary vector, resulting from the N point crossover.</returns>
    public static BinaryVector Apply(IRandom random, BinaryVector parent1, BinaryVector parent2, IntValue n) {
      if (parent1.Length != parent2.Length)
        throw new ArgumentException("NPointCrossover: The parents are of different length.");

      if (n.Value > parent1.Length)
        throw new ArgumentException("NPointCrossover: There cannot be more breakpoints than the size of the parents.");

      if (n.Value < 1)
        throw new ArgumentException("NPointCrossover: N cannot be < 1.");

      int length = parent1.Length;
      bool[] result = new bool[length];
      int[] breakpoints = new int[n.Value];

      //choose break points
      List<int> breakpointPool = new List<int>();

      for (int i = 0; i < length; i++)
        breakpointPool.Add(i);

      for (int i = 0; i < n.Value; i++) {
        int index = random.Next(breakpointPool.Count);
        breakpoints[i] = breakpointPool[index];
        breakpointPool.RemoveAt(index);
      }

      Array.Sort(breakpoints);

      //perform crossover
      int arrayIndex = 0;
      int breakPointIndex = 0;
      bool firstParent = true;

      while (arrayIndex < length) {
        if (breakPointIndex < breakpoints.Length &&
          arrayIndex == breakpoints[breakPointIndex]) {
          breakPointIndex++;
          firstParent = !firstParent;
        }

        if (firstParent)
          result[arrayIndex] = parent1[arrayIndex];
        else
          result[arrayIndex] = parent2[arrayIndex];

        arrayIndex++;
      }

      return new BinaryVector(result);
    }
开发者ID:t-h-e,项目名称:HeuristicLab,代码行数:60,代码来源:NPointCrossover.cs


示例11: NPointCrossoverApplyTest

    public void NPointCrossoverApplyTest() {
      TestRandom random = new TestRandom();
      BinaryVector parent1, parent2, expected, actual;
      IntValue n;
      bool exceptionFired;
      // The following test is based on Eiben, A.E. and Smith, J.E. 2003. Introduction to Evolutionary Computation. Natural Computing Series, Springer-Verlag Berlin Heidelberg, p. 48
      random.Reset();
      n = new IntValue(1);
      random.IntNumbers = new int[] { 4 };
      parent1 = new BinaryVector(new bool[] { false, false, false, false, true, false, false, false, false });
      parent2 = new BinaryVector(new bool[] { true, true, false, true, false, false, false, false, true });
      expected = new BinaryVector(new bool[] { false, false, false, false, false, false, false, false, true });
      actual = NPointCrossover.Apply(random, parent1, parent2, n);
      Assert.IsTrue(Auxiliary.BinaryVectorIsEqualByPosition(actual, expected));

      // The following test is based on Eiben, A.E. and Smith, J.E. 2003. Introduction to Evolutionary Computation. Natural Computing Series, Springer-Verlag Berlin Heidelberg, p. 48
      random.Reset();
      n = new IntValue(2);
      random.IntNumbers = new int[] { 4, 5 };
      parent1 = new BinaryVector(new bool[] { false, false, false, false, true, false, false, false, false });
      parent2 = new BinaryVector(new bool[] { true, true, false, true, false, false, false, false, true });
      expected = new BinaryVector(new bool[] { false, false, false, false, false, false, false, false, false });
      actual = NPointCrossover.Apply(random, parent1, parent2, n);
      Assert.IsTrue(Auxiliary.BinaryVectorIsEqualByPosition(actual, expected));

      // The following test is based on Eiben, A.E. and Smith, J.E. 2003. Introduction to Evolutionary Computation. Natural Computing Series, Springer-Verlag Berlin Heidelberg, p. 48
      random.Reset();
      n = new IntValue(2);
      random.IntNumbers = new int[] { 4, 5 };
      parent2 = new BinaryVector(new bool[] { false, false, false, false, true, false, false, false, false });
      parent1 = new BinaryVector(new bool[] { true, true, false, true, false, false, false, false, true });
      expected = new BinaryVector(new bool[] { true, true, false, true, true, false, false, false, true });
      actual = NPointCrossover.Apply(random, parent1, parent2, n);
      Assert.IsTrue(Auxiliary.BinaryVectorIsEqualByPosition(actual, expected));

      // The following test is not based on any published examples
      random.Reset();
      random.IntNumbers = new int[] { 2 };
      parent1 = new BinaryVector(new bool[] { false, true, true, false, false }); // this parent is longer
      parent2 = new BinaryVector(new bool[] { false, true, true, false });
      exceptionFired = false;
      try {
        actual = NPointCrossover.Apply(random, parent1, parent2, n);
      }
      catch (System.ArgumentException) {
        exceptionFired = true;
      }
      Assert.IsTrue(exceptionFired);
    }
开发者ID:t-h-e,项目名称:HeuristicLab,代码行数:49,代码来源:NPointCrossoverTest.cs


示例12: Create

 /// <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);
 }
开发者ID:thunder176,项目名称:HeuristicLab,代码行数:10,代码来源:NormalDistributedRealVectorCreator.cs


示例13: Apply

 /// <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;
 }
开发者ID:thunder176,项目名称:HeuristicLab,代码行数:54,代码来源:NormalDistributedRealVectorCreator.cs


示例14: getValue

        /// <summary>
        ///     Gets a value based on its image
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public override IValue getValue(string image)
        {
            IValue retVal = null;

            try
            {
                retVal = new IntValue(this, Decimal.Parse(image));
            }
            catch (Exception e)
            {
                AddException(e);
            }

            return retVal;
        }
开发者ID:ERTMSSolutions,项目名称:ERTMSFormalSpecs,代码行数:20,代码来源:PredefinedTypes.cs


示例15: Improve

 public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, DoubleArray probabilities, CancellationToken cancellation) {
   var distanceM = (DistanceMatrix)distances;
   Func<int, int, double> distance = (a, b) => distanceM[a, b];
   for (var i = localIterations.Value; i < maxIterations; i++) {
     TranslocationMove bestMove = null;
     var bestQuality = quality.Value; // we have to make an improvement, so current quality is the baseline
     var evaluations = 0.0;
     foreach (var move in ExhaustiveInsertionMoveGenerator.Generate(assignment)) {
       var moveQuality = PTSPAnalyticalInsertionMoveEvaluator.EvaluateMove(assignment, move, distance, probabilities);
       evaluations++;
       if (maximization && moveQuality > bestQuality
         || !maximization && moveQuality < bestQuality) {
         bestQuality = moveQuality;
         bestMove = move;
       }
     }
     evaluatedSolutions.Value += (int)Math.Ceiling(evaluations);
     if (bestMove == null) break;
     TranslocationManipulator.Apply(assignment, bestMove.Index1, bestMove.Index2, bestMove.Index3);
     quality.Value = bestQuality;
     localIterations.Value++;
     cancellation.ThrowIfCancellationRequested();
   }
 }
开发者ID:t-h-e,项目名称:HeuristicLab,代码行数:24,代码来源:PTSPAnalyticalInsertionLocalImprovement.cs


示例16: Apply

    public override IOperation Apply() {
      double maxSelPress = MaximumSelectionPressureParameter.ActualValue.Value;
      double successRatio = SuccessRatioParameter.ActualValue.Value;
      bool fillPopulationWithParents = false;
      if (FillPopulationWithParentsParameter.ActualValue != null)
        fillPopulationWithParents = FillPopulationWithParentsParameter.ActualValue.Value;
      IScope scope = ExecutionContext.Scope;
      IScope parents = scope.SubScopes[0];
      IScope offspring = scope.SubScopes[1];
      int populationSize = parents.SubScopes.Count;

      // retrieve actual selection pressure and success ratio
      DoubleValue selectionPressure = SelectionPressureParameter.ActualValue;
      if (selectionPressure == null) {
        selectionPressure = new DoubleValue(0);
        SelectionPressureParameter.ActualValue = selectionPressure;
      }
      DoubleValue currentSuccessRatio = CurrentSuccessRatioParameter.ActualValue;
      if (currentSuccessRatio == null) {
        currentSuccessRatio = new DoubleValue(0);
        CurrentSuccessRatioParameter.ActualValue = currentSuccessRatio;
      }

      // retrieve next population
      ItemList<IScope> population = OffspringPopulationParameter.ActualValue;
      IntValue successfulOffspring;
      if (population == null) {
        population = new ItemList<IScope>();
        OffspringPopulationParameter.ActualValue = population;
        selectionPressure.Value = 0; // initialize selection pressure for this round
        currentSuccessRatio.Value = 0; // initialize current success ratio for this round
        successfulOffspring = new IntValue(0);
        OffspringPopulationWinnersParameter.ActualValue = successfulOffspring;
      } else successfulOffspring = OffspringPopulationWinnersParameter.ActualValue;

      int worseOffspringNeeded = (int)((1 - successRatio) * populationSize) - (population.Count - successfulOffspring.Value);
      int successfulOffspringAdded = 0;

      // implement the ActualValue fetch here - otherwise the parent scope would also be included, given that there may be 1000 or more parents, this is quite unnecessary
      string tname = SuccessfulOffspringParameter.TranslatedName;
      double tmpSelPress = selectionPressure.Value, tmpSelPressInc = 1.0 / populationSize;
      for (int i = 0; i < offspring.SubScopes.Count; i++) {
        // fetch value
        IVariable tmpVar;
        if (!offspring.SubScopes[i].Variables.TryGetValue(tname, out tmpVar)) throw new InvalidOperationException(Name + ": Could not determine if an offspring was successful or not.");
        BoolValue tmp = (tmpVar.Value as BoolValue);
        if (tmp == null) throw new InvalidOperationException(Name + ": The variable that indicates whether an offspring is successful or not must contain a BoolValue.");

        // add to population
        if (tmp.Value) {
          IScope currentOffspring = offspring.SubScopes[i];
          offspring.SubScopes.Remove(currentOffspring);
          i--;
          population.Add(currentOffspring);
          successfulOffspringAdded++;
        } else if (worseOffspringNeeded > 0 || tmpSelPress >= maxSelPress) {
          IScope currentOffspring;
          if (!fillPopulationWithParents || worseOffspringNeeded > 0) {
            currentOffspring = offspring.SubScopes[i];
            offspring.SubScopes.Remove(currentOffspring);
            i--;
            worseOffspringNeeded--;
          } else {
            currentOffspring = parents.SubScopes[i];
          }
          population.Add(currentOffspring);
        }
        tmpSelPress += tmpSelPressInc;
        if (population.Count == populationSize) break;
      }
      successfulOffspring.Value += successfulOffspringAdded;

      // calculate actual selection pressure and success ratio
      selectionPressure.Value = tmpSelPress;
      currentSuccessRatio.Value = successfulOffspring.Value / ((double)populationSize);

      // check if enough children have been generated
      if (((selectionPressure.Value < maxSelPress) && (currentSuccessRatio.Value < successRatio)) ||
          (population.Count < populationSize)) {
        // more children required -> reduce left and start children generation again
        scope.SubScopes.Remove(parents);
        scope.SubScopes.Remove(offspring);
        while (parents.SubScopes.Count > 0) {
          IScope parent = parents.SubScopes[0];
          parents.SubScopes.RemoveAt(0);
          scope.SubScopes.Add(parent);
        }

        IOperator moreOffspring = OffspringCreatorParameter.ActualValue as IOperator;
        if (moreOffspring == null) throw new InvalidOperationException(Name + ": More offspring are required, but no operator specified for creating them.");
        return ExecutionContext.CreateOperation(moreOffspring);
      } else {
        // enough children generated
        offspring.SubScopes.Clear();
        offspring.SubScopes.AddRange(population);

        scope.Variables.Remove(OffspringPopulationParameter.TranslatedName);
        scope.Variables.Remove(OffspringPopulationWinnersParameter.TranslatedName);
        return base.Apply();
      }
//.........这里部分代码省略.........
开发者ID:t-h-e,项目名称:HeuristicLab,代码行数:101,代码来源:OffspringSelector.cs


示例17: PerformArithmericOperation

        // left +/-/*/div/exp right
        /// <summary>
        ///     Performs the arithmetic operation based on the type of the result
        /// </summary>
        /// <param name="context">The context used to perform this operation</param>
        /// <param name="left"></param>
        /// <param name="operation"></param>
        /// <param name="right"></param>
        /// <returns></returns>
        public override IValue PerformArithmericOperation(InterpretationContext context, IValue left,
            BinaryExpression.Operator operation, IValue right)
        {
            IntValue retVal = null;

            Decimal int1 = getValue(left);
            Decimal int2 = getValue(right);

            switch (operation)
            {
                case BinaryExpression.Operator.Exp:
                    retVal = new IntValue(EFSSystem.IntegerType, (Decimal) Math.Pow((double) int1, (double) int2));
                    break;

                case BinaryExpression.Operator.Mult:
                    retVal = new IntValue(EFSSystem.IntegerType, (int1*int2));
                    break;

                case BinaryExpression.Operator.Div:
                    if (int2 == 0)
                        throw new Exception("Division by zero");
                    else
                        retVal = new IntValue(EFSSystem.IntegerType, Math.Floor(int1/int2));
                    break;

                case BinaryExpression.Operator.Add:
                    retVal = new IntValue(EFSSystem.IntegerType, (int1 + int2));
                    break;

                case BinaryExpression.Operator.Sub:
                    retVal = new IntValue(EFSSystem.IntegerType, (int1 - int2));
                    break;
            }

            return retVal;
        }
开发者ID:ERTMSSolutions,项目名称:ERTMSFormalSpecs,代码行数:45,代码来源:PredefinedTypes.cs


示例18: Improve

 public static void Improve(Permutation assignment, DoubleMatrix weights, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, CancellationToken cancellation) {
   for (int i = localIterations.Value; i < maxIterations; i++) {
     TranslocationMove bestMove = null;
     double bestQuality = 0; // we have to make an improvement, so 0 is the baseline
     double evaluations = 0.0;
     foreach (var move in ExhaustiveInsertionMoveGenerator.Generate(assignment)) {
       double moveQuality = QAPTranslocationMoveEvaluator.Apply(assignment, move, weights, distances);
       int min = Math.Min(move.Index1, move.Index3);
       int max = Math.Max(move.Index2, move.Index3 + (move.Index2 - move.Index1));
       evaluations += 2.0 * (max - min + 1) / assignment.Length
         + 4.0 * (assignment.Length - (max - min + 1)) / assignment.Length;
       if (maximization && moveQuality > bestQuality
         || !maximization && moveQuality < bestQuality) {
         bestQuality = moveQuality;
         bestMove = move;
       }
     }
     evaluatedSolutions.Value += (int)Math.Ceiling(evaluations);
     if (bestMove == null) break;
     TranslocationManipulator.Apply(assignment, bestMove.Index1, bestMove.Index2, bestMove.Index3);
     quality.Value += bestQuality;
     localIterations.Value++;
     cancellation.ThrowIfCancellationRequested();
   }
 }
开发者ID:t-h-e,项目名称:HeuristicLab,代码行数:25,代码来源:QAPExhaustiveInsertionLocalImprovement.cs


示例19: PerformMove

    protected override void PerformMove() {
      PotvinCustomerRelocationMove move = CustomerRelocationMoveParameter.ActualValue;

      PotvinEncoding newSolution = move.Individual.Clone() as PotvinEncoding;
      Apply(newSolution, move, ProblemInstance);
      newSolution.Repair();
      VRPToursParameter.ActualValue = newSolution;

      //reset move quality
      VRPEvaluation eval = ProblemInstance.Evaluate(newSolution);
      MoveQualityParameter.ActualValue.Value = eval.Quality;

      //update memory
      VariableCollection memory = MemoriesParameter.ActualValue;
      string key = AdditionFrequencyMemoryKeyParameter.Value.Value;

      if (memory != null) {
        if (!memory.ContainsKey(key)) {
          memory.Add(new Variable(key,
              new ItemDictionary<PotvinCustomerRelocationMoveAttribute, IntValue>()));
        }
        ItemDictionary<PotvinCustomerRelocationMoveAttribute, IntValue> additionFrequency =
          memory[key].Value as ItemDictionary<PotvinCustomerRelocationMoveAttribute, IntValue>;

        PotvinCustomerRelocationMoveAttribute attr = new PotvinCustomerRelocationMoveAttribute(0, move.Tour, move.City);
        if (!additionFrequency.ContainsKey(attr))
          additionFrequency[attr] = new IntValue(0);

        additionFrequency[attr].Value++;
      }
    }
开发者ID:thunder176,项目名称:HeuristicLab,代码行数:31,代码来源:PotvinCustomerRelocationMoveMaker.cs


示例20: getValue

        /// <summary>
        ///     Parses the image and provides the corresponding value
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public override IValue getValue(string image)
        {
            IValue retVal = null;

            if (Char.IsLetter(image[0]) || image[0] == '_')
            {
                int lastDotPosition = image.LastIndexOf('.');
                if (lastDotPosition > 0)
                {
                    string prefix = image.Substring(0, lastDotPosition);
                    Expression typeExpression = EFSSystem.Parser.Expression(this, prefix,
                        IsType.INSTANCE, true, null, true);
                    if (typeExpression != null && typeExpression.Ref == this)
                    {
                        image = image.Substring(lastDotPosition + 1);
                    }
                }

                retVal = findEnumValue(image);
                if (retVal == null)
                {
                    Log.Error("Cannot create range value from " + image);
                }
            }
            else
            {
                try
                {
                    switch (getPrecision())
                    {
                        case acceptor.PrecisionEnum.aIntegerPrecision:
                        {
                            Decimal val = Decimal.Parse(image);
                            Decimal min = MinValueAsLong;
                            Decimal max = MaxValueAsLong;
                            if (val >= min && val <= max)
                            {
                                retVal = new IntValue(this, val);
                            }
                        }
                            break;

                        case acceptor.PrecisionEnum.aDoublePrecision:
                        {
                            CultureInfo info = CultureInfo.InvariantCulture;

                            double val = getDouble(image);
                            double min = MinValueAsDouble;
                            double max = MaxValueAsDouble;
                            if (val >= min && val <= max && image.IndexOf('.') >= 0)
                            {
                                retVal = new DoubleValue(this, val);
                            }
                            break;
                        }
                    }
                }
                catch (Exception exception)
                {
                    Log.Error("Cannot create range value", exception);
                }
            }

            return retVal;
        }
开发者ID:JamesOakey,项目名称:ERTMSFormalSpecs,代码行数:70,代码来源:Range.cs



注:本文中的IntValue类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# IntVar类代码示例发布时间:2022-05-24
下一篇:
C# IntRef类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap