예제 #1
0
 public Value read(BinaryReader reader)
 {
   IntValue ret = new IntValue();
   int val = reader.ReadInt32();
   ret.value = val;
   return ret;
 }
        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);
        }
예제 #3
0
 public void Add()
 {
     var three = new IntValue(3);
     var five = new IntValue(5);
     var threePlusFive = three + five;
     AssertEquals(threePlusFive.Value, 8);
 }
 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);
 }
예제 #5
0
 public AntTrail(BoolMatrix world, SymbolicExpressionTree expression, IntValue maxTimeSteps)
   : this() {
   this.world = world;
   this.expression = expression;
   this.maxTimeSteps = maxTimeSteps;
   Initialize();
 }
    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);
    }
예제 #7
0
 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";
 }
    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());
    }
        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);
        }
예제 #10
0
    /// <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);
    }
예제 #11
0
    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);
    }
예제 #12
0
        public override IOperation Apply()
        {
            double maxSelPress    = MaximumSelectionPressureParameter.ActualValue.Value;
            double successRatio   = SuccessRatioParameter.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;
            ItemList <IScope> virtual_population = OffspringVirtualPopulationParameter.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;

                virtual_population = new ItemList <IScope>();
                OffspringVirtualPopulationParameter.ActualValue = virtual_population;
            }
            else
            {
                successfulOffspring = OffspringPopulationWinnersParameter.ActualValue;
            }

            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;
            double 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.RemoveAt(i);
                    i--; // next loop should continue with the subscope at index i which replaced currentOffspring
                    population.Add(currentOffspring);
                    successfulOffspringAdded++;
                }
                else
                {
                    IScope currentOffspring = offspring.SubScopes[i];
                    offspring.SubScopes.RemoveAt(i);
                    i--;
                    virtual_population.Add(currentOffspring); // add to losers pool
                }
                tmpSelPress += tmpSelPressInc;

                double tmpSuccessRatio = (successfulOffspring.Value + successfulOffspringAdded) / ((double)populationSize);
                if (tmpSuccessRatio >= successRatio && (population.Count + virtual_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 (or limit of selection pressure or evaluted solutions is reached)
            if (((EvaluatedSolutionsParameter.ActualValue.Value < MaximumEvaluatedSolutionsParameter.ActualValue.Value) &&
                 (selectionPressure.Value < maxSelPress) &&
                 (currentSuccessRatio.Value < successRatio)) ||
                ((population.Count + virtual_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); // TODO: repeated call of RemoveAt(0) is inefficient?
                    scope.SubScopes.Add(parent);   // order of subscopes is reversed
                }

                IOperator offspringCreator = OffspringCreatorParameter.ActualValue as IOperator;
                if (offspringCreator == null)
                {
                    throw new InvalidOperationException(Name + ": More offspring are required, but no operator specified for creating them.");
                }
                return(ExecutionContext.CreateOperation(offspringCreator)); // this assumes that this operator will be called again indirectly or directly
            }
            else
            {
                // enough children generated
                var fitnessComparer = new FitnessComparer(QualityParameter.TranslatedName, MaximizationParameter.ActualValue.Value);
                population.Sort(fitnessComparer); // sort individuals by descending fitness

                // keeps only the best successRatio * populationSize solutions in the population (the remaining ones are added to the virtual population)
                int removed = 0;
                for (int i = 0; i < population.Count; i++)
                {
                    double tmpSuccessRatio = i / (double)populationSize;
                    if (tmpSuccessRatio > successRatio)
                    {
                        virtual_population.Add(population[i]);
                        removed++;
                    }
                }
                population.RemoveRange(population.Count - removed, removed);

                //fill up population with best remaining children (successful or unsuccessful)
                virtual_population.Sort(fitnessComparer);
                int offspringNeeded = populationSize - population.Count;
                for (int i = 0; i < offspringNeeded && i < virtual_population.Count; i++)
                {
                    population.Add(virtual_population[i]); // children are sorted by descending fitness
                }

                offspring.SubScopes.Clear();
                offspring.SubScopes.AddRange(population);

                scope.Variables.Remove(OffspringPopulationParameter.TranslatedName);
                scope.Variables.Remove(OffspringVirtualPopulationParameter.TranslatedName);
                scope.Variables.Remove(OffspringPopulationWinnersParameter.TranslatedName);
                return(base.Apply());
            }
        }
예제 #13
0
    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();
      }
    }
    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++;
      }
    }
        /// <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;
        }
        /// <summary>
        ///     Provides the value associated to this Expression
        /// </summary>
        /// <param name="context">The context on which the value must be found</param>
        /// <param name="explain">The explanation to fill, if any</param>
        /// <returns></returns>
        protected internal override IValue GetValue(InterpretationContext context, ExplanationPart explain)
        {
            IValue retVal = null;

            if (Term != null)
            {
                retVal = Term.GetValue(context, explain);
            }
            else
            {
                if (Not.Equals(UnaryOp))
                {
                    BoolValue b = Expression.GetValue(context, explain) as BoolValue;
                    if (b != null)
                    {
                        if (b.Val)
                        {
                            retVal = EfsSystem.Instance.BoolType.False;
                        }
                        else
                        {
                            retVal = EfsSystem.Instance.BoolType.True;
                        }
                    }
                    else
                    {
                        AddError("Expression " + Expression + " does not evaluate to boolean");
                    }
                }
                else if (Minus.Equals(UnaryOp))
                {
                    IValue val = Expression.GetValue(context, explain);
                    IntValue intValue = val as IntValue;
                    if (intValue != null)
                    {
                        retVal = new IntValue(intValue.Type, -intValue.Val);
                    }
                    else
                    {
                        DoubleValue doubleValue = val as DoubleValue;
                        if (doubleValue != null)
                        {
                            retVal = new DoubleValue(doubleValue.Type, -doubleValue.Val);
                        }
                    }

                    if (retVal == null)
                    {
                        AddError("Cannot negate value for " + Expression);
                    }
                }
                else
                {
                    retVal = Expression.GetValue(context, explain);
                }
            }

            return retVal;
        }
 /// <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);
 }
예제 #18
0
 public static PRVEncoding Apply(int jobs, int resources, IRandom random, IntValue nrOfRules)
 {
     return(new PRVEncoding(jobs * resources, random, 0, nrOfRules.Value, nrOfRules));
 }
예제 #19
0
        /// <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;
        }
        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++)
            {
                TwoPointFiveMove 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 ExhaustiveTwoPointFiveMoveGenerator.Generate(assignment))
                {
                    var moveQuality = PTSPAnalyticalTwoPointFiveMoveEvaluator.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;
                }
                TwoPointFiveMoveMaker.Apply(assignment, bestMove);
                quality.Value = bestQuality;
                localIterations.Value++;
                cancellation.ThrowIfCancellationRequested();
            }
        }
예제 #21
0
        public string GetPreviewString(RSTriggerInfo inTriggerContext, RSLibrary inLibrary)
        {
            switch (m_Type)
            {
            case InnerType.String:
                return(string.Format("\"{0}\"", m_StringValue));

            case InnerType.Color:
                return(ColorValue.ToString());

            case InnerType.Bool:
                return(BoolValue ? "true" : "false");

            case InnerType.Float:
                return(FloatValue.ToString());

            case InnerType.Int32:
                return(IntValue.ToString());

            case InnerType.Null:
                return("null");

            case InnerType.Vector2:
                return(AsVector2.ToString());

            case InnerType.Vector3:
                return(AsVector3.ToString());

            case InnerType.Vector4:
                return(AsVector4.ToString());

            case InnerType.EntityScope:
                return(EntityValue.GetPreviewString(inTriggerContext, inLibrary));

            case InnerType.GroupId:
                return(GroupIdValue.ToString(inLibrary));

            case InnerType.TriggerId:
                return(TriggerIdValue.ToString(inLibrary));

            case InnerType.Enum:
            {
                Type enumType = Type.GetType(m_StringValue);
                if (enumType == null)
                {
                    Debug.LogErrorFormat("Enum type {0} no longer exists", m_StringValue);
                    return(m_IntValue.ToString());
                }

                try
                {
                    return(Enum.ToObject(enumType, m_IntValue).ToString());
                }
                catch (Exception e)
                {
                    Debug.LogException(e);
                    Debug.LogErrorFormat("Enum {0} cannot be represented as type {1}", m_IntValue, enumType);
                    return(m_IntValue.ToString());
                }
            }

            case InnerType.Invalid:
                return("INVALID");

            default:
                ThrowInvalidCastException(m_Type, typeof(string));
                return(null);
            }
        }
        public override IOperation Apply()
        {
            int      updateInterval = UpdateIntervalParameter.Value.Value;
            IntValue updateCounter  = UpdateCounterParameter.ActualValue;

            // if counter does not yet exist then initialize it with update interval
            // to make sure the solutions are analyzed on the first application of this operator
            if (updateCounter == null)
            {
                updateCounter = new IntValue(updateInterval);
                UpdateCounterParameter.ActualValue = updateCounter;
            }
            else
            {
                updateCounter.Value++;
            }

            //analyze solutions only every 'updateInterval' times
            if (updateCounter.Value == updateInterval)
            {
                updateCounter.Value = 0;

                bool                    max          = MaximizationParameter.ActualValue.Value;
                ItemArray <T>           solutions    = SolutionParameter.ActualValue;
                ItemArray <DoubleValue> qualities    = QualityParameter.ActualValue;
                bool                    storeHistory = StoreHistoryParameter.Value.Value;
                int count = solutions.Length;

                if (count > 1)
                {
                    // sort solutions by quality
                    T[] sortedSolutions = null;
                    if (max)
                    {
                        sortedSolutions = solutions
                                          .Select((x, index) => new { Solution = x, Quality = qualities[index] })
                                          .OrderByDescending(x => x.Quality)
                                          .Select(x => x.Solution)
                                          .ToArray();
                    }
                    else
                    {
                        sortedSolutions = solutions
                                          .Select((x, index) => new { Solution = x, Quality = qualities[index] })
                                          .OrderBy(x => x.Quality)
                                          .Select(x => x.Solution)
                                          .ToArray();
                    }

                    // calculate solution similarities
                    double[,] similarities = CalculateSimilarities(sortedSolutions);

                    // calculate minimum, average and maximum similarities
                    double   similarity;
                    double[] minSimilarities = new double[count];
                    double[] avgSimilarities = new double[count];
                    double[] maxSimilarities = new double[count];
                    for (int i = 0; i < count; i++)
                    {
                        minSimilarities[i] = 1;
                        avgSimilarities[i] = 0;
                        maxSimilarities[i] = 0;
                        for (int j = 0; j < count; j++)
                        {
                            if (i != j)
                            {
                                similarity = similarities[i, j];

                                if ((similarity < 0) || (similarity > 1))
                                {
                                    throw new InvalidOperationException("Solution similarities have to be in the interval [0;1].");
                                }

                                if (minSimilarities[i] > similarity)
                                {
                                    minSimilarities[i] = similarity;
                                }
                                avgSimilarities[i] += similarity;
                                if (maxSimilarities[i] < similarity)
                                {
                                    maxSimilarities[i] = similarity;
                                }
                            }
                        }
                        avgSimilarities[i] = avgSimilarities[i] / (count - 1);
                    }
                    double avgMinSimilarity = minSimilarities.Average();
                    double avgAvgSimilarity = avgSimilarities.Average();
                    double avgMaxSimilarity = maxSimilarities.Average();

                    // fetch results collection
                    ResultCollection results;
                    if (!ResultsParameter.ActualValue.ContainsKey(Name + " Results"))
                    {
                        results = new ResultCollection();
                        ResultsParameter.ActualValue.Add(new Result(Name + " Results", results));
                    }
                    else
                    {
                        results = (ResultCollection)ResultsParameter.ActualValue[Name + " Results"].Value;
                    }

                    // store similarities
                    HeatMap similaritiesHeatMap = new HeatMap(similarities, "Solution Similarities", 0.0, 1.0);
                    if (!results.ContainsKey("Solution Similarities"))
                    {
                        results.Add(new Result("Solution Similarities", similaritiesHeatMap));
                    }
                    else
                    {
                        results["Solution Similarities"].Value = similaritiesHeatMap;
                    }

                    // store similarities history
                    if (storeHistory)
                    {
                        if (!results.ContainsKey("Solution Similarities History"))
                        {
                            HeatMapHistory history = new HeatMapHistory();
                            history.Add(similaritiesHeatMap);
                            results.Add(new Result("Solution Similarities History", history));
                        }
                        else
                        {
                            ((HeatMapHistory)results["Solution Similarities History"].Value).Add(similaritiesHeatMap);
                        }
                    }

                    // store average minimum, average and maximum similarity
                    if (!results.ContainsKey("Average Minimum Solution Similarity"))
                    {
                        results.Add(new Result("Average Minimum Solution Similarity", new DoubleValue(avgMinSimilarity)));
                    }
                    else
                    {
                        ((DoubleValue)results["Average Minimum Solution Similarity"].Value).Value = avgMinSimilarity;
                    }

                    if (!results.ContainsKey("Average Average Solution Similarity"))
                    {
                        results.Add(new Result("Average Average Solution Similarity", new DoubleValue(avgAvgSimilarity)));
                    }
                    else
                    {
                        ((DoubleValue)results["Average Average Solution Similarity"].Value).Value = avgAvgSimilarity;
                    }

                    if (!results.ContainsKey("Average Maximum Solution Similarity"))
                    {
                        results.Add(new Result("Average Maximum Solution Similarity", new DoubleValue(avgMaxSimilarity)));
                    }
                    else
                    {
                        ((DoubleValue)results["Average Maximum Solution Similarity"].Value).Value = avgMaxSimilarity;
                    }

                    // store average minimum, average and maximum solution similarity data table
                    DataTable minAvgMaxSimilarityDataTable;
                    if (!results.ContainsKey("Average Minimum/Average/Maximum Solution Similarity"))
                    {
                        minAvgMaxSimilarityDataTable = new DataTable("Average Minimum/Average/Maximum Solution Similarity");
                        minAvgMaxSimilarityDataTable.VisualProperties.XAxisTitle = "Iteration";
                        minAvgMaxSimilarityDataTable.VisualProperties.YAxisTitle = "Solution Similarity";
                        minAvgMaxSimilarityDataTable.Rows.Add(new DataRow("Average Minimum Solution Similarity", null));
                        minAvgMaxSimilarityDataTable.Rows["Average Minimum Solution Similarity"].VisualProperties.StartIndexZero = true;
                        minAvgMaxSimilarityDataTable.Rows.Add(new DataRow("Average Average Solution Similarity", null));
                        minAvgMaxSimilarityDataTable.Rows["Average Average Solution Similarity"].VisualProperties.StartIndexZero = true;
                        minAvgMaxSimilarityDataTable.Rows.Add(new DataRow("Average Maximum Solution Similarity", null));
                        minAvgMaxSimilarityDataTable.Rows["Average Maximum Solution Similarity"].VisualProperties.StartIndexZero = true;
                        results.Add(new Result("Average Minimum/Average/Maximum Solution Similarity", minAvgMaxSimilarityDataTable));
                    }
                    else
                    {
                        minAvgMaxSimilarityDataTable = (DataTable)results["Average Minimum/Average/Maximum Solution Similarity"].Value;
                    }
                    minAvgMaxSimilarityDataTable.Rows["Average Minimum Solution Similarity"].Values.Add(avgMinSimilarity);
                    minAvgMaxSimilarityDataTable.Rows["Average Average Solution Similarity"].Values.Add(avgAvgSimilarity);
                    minAvgMaxSimilarityDataTable.Rows["Average Maximum Solution Similarity"].Values.Add(avgMaxSimilarity);

                    // store minimum, average, maximum similarities data table
                    DataTable minAvgMaxSimilaritiesDataTable = new DataTable("Minimum/Average/Maximum Solution Similarities");
                    minAvgMaxSimilaritiesDataTable.VisualProperties.XAxisTitle = "Solution Index";
                    minAvgMaxSimilaritiesDataTable.VisualProperties.YAxisTitle = "Solution Similarity";
                    minAvgMaxSimilaritiesDataTable.Rows.Add(new DataRow("Minimum Solution Similarity", null, minSimilarities));
                    minAvgMaxSimilaritiesDataTable.Rows["Minimum Solution Similarity"].VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
                    minAvgMaxSimilaritiesDataTable.Rows.Add(new DataRow("Average Solution Similarity", null, avgSimilarities));
                    minAvgMaxSimilaritiesDataTable.Rows["Average Solution Similarity"].VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
                    minAvgMaxSimilaritiesDataTable.Rows.Add(new DataRow("Maximum Solution Similarity", null, maxSimilarities));
                    minAvgMaxSimilaritiesDataTable.Rows["Maximum Solution Similarity"].VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
                    if (!results.ContainsKey("Minimum/Average/Maximum Solution Similarities"))
                    {
                        results.Add(new Result("Minimum/Average/Maximum Solution Similarities", minAvgMaxSimilaritiesDataTable));
                    }
                    else
                    {
                        results["Minimum/Average/Maximum Solution Similarities"].Value = minAvgMaxSimilaritiesDataTable;
                    }

                    // store minimum, average, maximum similarities history
                    if (storeHistory)
                    {
                        if (!results.ContainsKey("Minimum/Average/Maximum Solution Similarities History"))
                        {
                            DataTableHistory history = new DataTableHistory();
                            history.Add(minAvgMaxSimilaritiesDataTable);
                            results.Add(new Result("Minimum/Average/Maximum Solution Similarities History", history));
                        }
                        else
                        {
                            ((DataTableHistory)results["Minimum/Average/Maximum Solution Similarities History"].Value).Add(minAvgMaxSimilaritiesDataTable);
                        }
                    }
                }
            }
            return(base.Apply());
        }
예제 #23
0
 public PRVEncoding(int length, IRandom random, int min, int max, IntValue nrOfRules)
     : base()
 {
     this.nrOfRules           = (IntValue)nrOfRules.Clone();
     this.PriorityRulesVector = new IntegerVector(length, random, min, max);
 }
예제 #24
0
 private void VisitIntValue(IntValue node)
 {
     EnterNode(node);
     ExitNode(node);
 }
예제 #25
0
        public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, ItemList <BoolArray> realizations, CancellationToken cancellation)
        {
            var distanceM = (DistanceMatrix)distances;
            Func <int, int, double> distance = (a, b) => distanceM[a, b];

            for (var i = localIterations.Value; i < maxIterations; i++)
            {
                InversionMove bestMove    = null;
                double        bestQuality = 0; // we have to make an improvement, so 0 is the baseline
                double        evaluations = 0.0;
                foreach (var move in ExhaustiveInversionMoveGenerator.Generate(assignment))
                {
                    double moveQuality = PTSPEstimatedInversionMoveEvaluator.EvaluateMove(assignment, move, distance, realizations);
                    evaluations += realizations.Count * 4.0 / (assignment.Length * assignment.Length);
                    if (maximization && moveQuality > bestQuality ||
                        !maximization && moveQuality < bestQuality)
                    {
                        bestQuality = moveQuality;
                        bestMove    = move;
                    }
                }
                evaluatedSolutions.Value += (int)Math.Ceiling(evaluations);
                if (bestMove == null)
                {
                    break;
                }
                InversionManipulator.Apply(assignment, bestMove.Index1, bestMove.Index2);
                quality.Value += bestQuality;
                localIterations.Value++;
                cancellation.ThrowIfCancellationRequested();
            }
        }
 public OrienteeringSolution(IntegerVector integerVector, DoubleMatrix coordinates, IntValue startingPoint, IntValue terminalPoint,
                             DoubleArray scores, DoubleValue quality = null, DoubleValue penalty = null, DoubleValue distance = null)
     : base()
 {
     this.integerVector = integerVector;
     this.coordinates   = coordinates;
     this.startingPoint = startingPoint;
     this.terminalPoint = terminalPoint;
     this.scores        = scores;
     this.quality       = quality;
     this.penalty       = penalty;
     this.distance      = distance;
     Initialize();
 }
    public override IOperation Apply() {
      IRandom random = RandomParameter.ActualValue;
      int iteration = IterationsParameter.ActualValue.Value;
      IntMatrix shortTermMemory = ShortTermMemoryParameter.ActualValue;
      DoubleMatrix weights = WeightsParameter.ActualValue;
      DoubleMatrix distances = DistancesParameter.ActualValue;
      DoubleMatrix moveQualityMatrix = MoveQualityMatrixParameter.ActualValue;

      DoubleValue quality = QualityParameter.ActualValue;
      DoubleValue bestQuality = BestQualityParameter.ActualValue;
      if (bestQuality == null) {
        BestQualityParameter.ActualValue = (DoubleValue)quality.Clone();
        bestQuality = BestQualityParameter.ActualValue;
      }
      bool allMovesTabu = false;
      if (AllMovesTabuParameter.ActualValue == null)
        AllMovesTabuParameter.ActualValue = new BoolValue(false);
      else allMovesTabu = AllMovesTabuParameter.ActualValue.Value;

      int minTenure = MinimumTabuTenureParameter.ActualValue.Value;
      int maxTenure = MaximumTabuTenureParameter.ActualValue.Value;
      int alternativeAspirationTenure = AlternativeAspirationTenureParameter.ActualValue.Value;
      bool useAlternativeAspiration = UseAlternativeAspirationParameter.ActualValue.Value;
      Permutation solution = PermutationParameter.ActualValue;
      Swap2Move lastMove = LastMoveParameter.ActualValue;

      double bestMoveQuality = double.MaxValue;
      Swap2Move bestMove = null;
      bool already_aspired = false;

      double evaluations = EvaluatedSolutionEquivalentsParameter.ActualValue.Value;
      foreach (Swap2Move move in ExhaustiveSwap2MoveGenerator.Generate(solution)) {
        double moveQuality;
        if (lastMove == null) {
          moveQuality = QAPSwap2MoveEvaluator.Apply(solution, move, weights, distances);
          evaluations += 4.0 / solution.Length;
        } else if (allMovesTabu) moveQuality = moveQualityMatrix[move.Index1, move.Index2];
        else {
          moveQuality = QAPSwap2MoveEvaluator.Apply(solution, move, moveQualityMatrix[move.Index1, move.Index2], weights, distances, lastMove);
          if (move.Index1 == lastMove.Index1 || move.Index2 == lastMove.Index1 || move.Index1 == lastMove.Index2 || move.Index2 == lastMove.Index2)
            evaluations += 4.0 / solution.Length;
          else evaluations += 2.0 / (solution.Length * solution.Length);
        }

        moveQualityMatrix[move.Index1, move.Index2] = moveQuality;
        moveQualityMatrix[move.Index2, move.Index1] = moveQuality;

        bool autorized = shortTermMemory[move.Index1, solution[move.Index2]] < iteration
                      || shortTermMemory[move.Index2, solution[move.Index1]] < iteration;

        bool aspired = (shortTermMemory[move.Index1, solution[move.Index2]] < iteration - alternativeAspirationTenure
                     && shortTermMemory[move.Index2, solution[move.Index1]] < iteration - alternativeAspirationTenure)
                  || quality.Value + moveQuality < bestQuality.Value;

        if ((aspired && !already_aspired) // the first alternative move is aspired
          || (aspired && already_aspired && moveQuality < bestMoveQuality) // an alternative move was already aspired, but this is better
          || (autorized && !aspired && !already_aspired && moveQuality < bestMoveQuality)) { // a regular better move is found
          bestMove = move;
          bestMoveQuality = moveQuality;
          if (aspired) already_aspired = true;
        }
      }

      ResultCollection results = ResultsParameter.ActualValue;
      if (results != null) {
        IntValue aspiredMoves = null;
        if (!results.ContainsKey("AspiredMoves")) {
          aspiredMoves = new IntValue(already_aspired ? 1 : 0);
          results.Add(new Result("AspiredMoves", "Counts the number of moves that were selected because of the aspiration criteria.", aspiredMoves));
        } else if (already_aspired) {
          aspiredMoves = (IntValue)results["AspiredMoves"].Value;
          aspiredMoves.Value++;
        }
      }

      EvaluatedSolutionEquivalentsParameter.ActualValue.Value = evaluations;
      EvaluatedSolutionsParameter.ActualValue.Value = (int)Math.Ceiling(evaluations);

      allMovesTabu = bestMove == null;
      if (!allMovesTabu)
        LastMoveParameter.ActualValue = bestMove;
      AllMovesTabuParameter.ActualValue.Value = allMovesTabu;

      if (allMovesTabu) return base.Apply();

      bool useNewAdaptionScheme = UseNewTabuTenureAdaptionSchemeParameter.ActualValue.Value;
      if (useNewAdaptionScheme) {
        double r = random.NextDouble();
        if (r == 0) r = 1; // transform to (0;1]
        shortTermMemory[bestMove.Index1, solution[bestMove.Index1]] = (int)(iteration + r * r * r * maxTenure);
        r = random.NextDouble();
        if (r == 0) r = 1; // transform to (0;1]
        shortTermMemory[bestMove.Index2, solution[bestMove.Index2]] = (int)(iteration + r * r * r * maxTenure);
      } else {
        shortTermMemory[bestMove.Index1, solution[bestMove.Index1]] = iteration + random.Next(minTenure, maxTenure);
        shortTermMemory[bestMove.Index2, solution[bestMove.Index2]] = iteration + random.Next(minTenure, maxTenure);
      }
      Swap2Manipulator.Apply(solution, bestMove.Index1, bestMove.Index2);
      quality.Value += bestMoveQuality;

      if (quality.Value < bestQuality.Value) bestQuality.Value = quality.Value;

      return base.Apply();
    }
예제 #28
0
 public override string ToString()
 {
     return((InTestMode ? "TEST -- " : "") + IntValue.ToString());
 }
 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();
   }
 }
예제 #30
0
 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++)
     {
         InversionMove bestMove    = null;
         double        bestQuality = 0; // we have to make an improvement, so 0 is the baseline
         double        evaluations = 0.0;
         foreach (var move in ExhaustiveInversionMoveGenerator.Generate(assignment))
         {
             double moveQuality = QAPInversionMoveEvaluator.Apply(assignment, move, weights, distances);
             evaluations += 2 * (move.Index2 - move.Index1 + 1) / (double)assignment.Length;
             if (maximization && moveQuality > bestQuality ||
                 !maximization && moveQuality < bestQuality)
             {
                 bestQuality = moveQuality;
                 bestMove    = move;
             }
         }
         evaluatedSolutions.Value += (int)Math.Ceiling(evaluations);
         if (bestMove == null)
         {
             break;
         }
         InversionManipulator.Apply(assignment, bestMove.Index1, bestMove.Index2);
         quality.Value += bestQuality;
         localIterations.Value++;
         cancellation.ThrowIfCancellationRequested();
     }
 }
        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()));
        }
예제 #32
0
 public abstract void ModifyArchitecture(
     IRandom random,
     ISymbolicExpressionTree tree,
     IntValue maxFunctionDefinitions,
     IntValue maxFunctionArguments);
    public override IOperation Apply() {
      var maxIterations = MaximumIterationsParameter.ActualValue.Value;
      var assignment = PermutationParameter.ActualValue;
      var maximization = MaximizationParameter.ActualValue.Value;
      var distances = DistanceMatrixParameter.ActualValue;
      var quality = QualityParameter.ActualValue;
      var localIterations = LocalIterationsParameter.ActualValue;
      var evaluations = EvaluatedSolutionsParameter.ActualValue;
      var realizations = RealizationsParameter.ActualValue;
      if (localIterations == null) {
        localIterations = new IntValue(0);
        LocalIterationsParameter.ActualValue = localIterations;
      }

      Improve(assignment, distances, quality, localIterations, evaluations, maximization, maxIterations, realizations, CancellationToken);

      localIterations.Value = 0;
      return base.Apply();
    }
예제 #34
0
 public ClaseDependencia GetById(IntValue param) => Invoke().GetById(param.Value);
예제 #35
0
 public Estado GetById(IntValue param) => Invoke().GetById(param.Value);
예제 #36
0
 public string Clean()
 {
     return(IsNumeric ? IntValue.ToString() : Value);
 }
        // 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;
        }
예제 #38
0
 public void LogIntValue() => _logger.Log(IntValue.ToString());
    protected override void Run(CancellationToken cancellationToken) {
      // Set up the algorithm
      if (SetSeedRandomly) Seed = new System.Random().Next();
      var rand = new MersenneTwister((uint)Seed);

      // Set up the results display
      var iterations = new IntValue(0);
      Results.Add(new Result("Iterations", iterations));

      var table = new DataTable("Qualities");
      table.Rows.Add(new DataRow("R² (train)"));
      table.Rows.Add(new DataRow("R² (test)"));
      Results.Add(new Result("Qualities", table));
      var curLoss = new DoubleValue();
      var curTestLoss = new DoubleValue();
      Results.Add(new Result("R² (train)", curLoss));
      Results.Add(new Result("R² (test)", curTestLoss));
      var runCollection = new RunCollection();
      if (StoreRuns)
        Results.Add(new Result("Runs", runCollection));

      // init
      var problemData = Problem.ProblemData;
      var targetVarName = problemData.TargetVariable;
      var activeVariables = problemData.AllowedInputVariables.Concat(new string[] { problemData.TargetVariable });
      var modifiableDataset = new ModifiableDataset(
        activeVariables,
        activeVariables.Select(v => problemData.Dataset.GetDoubleValues(v).ToList()));

      var trainingRows = problemData.TrainingIndices;
      var testRows = problemData.TestIndices;
      var yPred = new double[trainingRows.Count()];
      var yPredTest = new double[testRows.Count()];
      var y = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices).ToArray();
      var curY = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices).ToArray();

      var yTest = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TestIndices).ToArray();
      var curYTest = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TestIndices).ToArray();
      var nu = Nu;
      var mVars = (int)Math.Ceiling(M * problemData.AllowedInputVariables.Count());
      var rRows = (int)Math.Ceiling(R * problemData.TrainingIndices.Count());
      var alg = RegressionAlgorithm;
      List<IRegressionModel> models = new List<IRegressionModel>();
      try {

        // Loop until iteration limit reached or canceled.
        for (int i = 0; i < Iterations; i++) {
          cancellationToken.ThrowIfCancellationRequested();

          modifiableDataset.RemoveVariable(targetVarName);
          modifiableDataset.AddVariable(targetVarName, curY.Concat(curYTest));

          SampleTrainingData(rand, modifiableDataset, rRows, problemData.Dataset, curY, problemData.TargetVariable, problemData.TrainingIndices); // all training indices from the original problem data are allowed 
          var modifiableProblemData = new RegressionProblemData(modifiableDataset,
            problemData.AllowedInputVariables.SampleRandomWithoutRepetition(rand, mVars),
            problemData.TargetVariable);
          modifiableProblemData.TrainingPartition.Start = 0;
          modifiableProblemData.TrainingPartition.End = rRows;
          modifiableProblemData.TestPartition.Start = problemData.TestPartition.Start;
          modifiableProblemData.TestPartition.End = problemData.TestPartition.End;

          if (!TrySetProblemData(alg, modifiableProblemData))
            throw new NotSupportedException("The algorithm cannot be used with GBM.");

          IRegressionModel model;
          IRun run;

          // try to find a model. The algorithm might fail to produce a model. In this case we just retry until the iterations are exhausted
          if (TryExecute(alg, rand.Next(), RegressionAlgorithmResult, out model, out run)) {
            int row = 0;
            // update predictions for training and test
            // update new targets (in the case of squared error loss we simply use negative residuals)
            foreach (var pred in model.GetEstimatedValues(problemData.Dataset, trainingRows)) {
              yPred[row] = yPred[row] + nu * pred;
              curY[row] = y[row] - yPred[row];
              row++;
            }
            row = 0;
            foreach (var pred in model.GetEstimatedValues(problemData.Dataset, testRows)) {
              yPredTest[row] = yPredTest[row] + nu * pred;
              curYTest[row] = yTest[row] - yPredTest[row];
              row++;
            }
            // determine quality
            OnlineCalculatorError error;
            var trainR = OnlinePearsonsRCalculator.Calculate(yPred, y, out error);
            var testR = OnlinePearsonsRCalculator.Calculate(yPredTest, yTest, out error);

            // iteration results
            curLoss.Value = error == OnlineCalculatorError.None ? trainR * trainR : 0.0;
            curTestLoss.Value = error == OnlineCalculatorError.None ? testR * testR : 0.0;

            models.Add(model);


          }

          if (StoreRuns)
            runCollection.Add(run);
          table.Rows["R² (train)"].Values.Add(curLoss.Value);
          table.Rows["R² (test)"].Values.Add(curTestLoss.Value);
          iterations.Value = i + 1;
        }

        // produce solution 
        if (CreateSolution) {
          // when all our models are symbolic models we can easily combine them to a single model
          if (models.All(m => m is ISymbolicRegressionModel)) {
            Results.Add(new Result("Solution", CreateSymbolicSolution(models, Nu, (IRegressionProblemData)problemData.Clone())));
          }
          // just produce an ensemble solution for now (TODO: correct scaling or linear regression for ensemble model weights)

          var ensembleSolution = CreateEnsembleSolution(models, (IRegressionProblemData)problemData.Clone());
          Results.Add(new Result("EnsembleSolution", ensembleSolution));
        }
      }
      finally {
        // reset everything
        alg.Prepare(true);
      }
    }
        /// <summary>
        /// 实时数据
        /// </summary>
        /// <param name="b"></param>
        /// 发送7e 7e 0e 01 00 12 34 56 00 00 00 00 17 09 27 10 12 10 01 00 00 00 02 00 00 00 03 00 04 00 05 00 06 00 01 00 02 00 03 00 04 00 05 00 02 00 00 00 00 00 00 01 00 02 00 03 00 00 00 04 00 00 00 00 7d 7d
        public static Byte[] OnResolveRealData(byte[] b, int bCount, TcpSocketClient client)
        {
            string tStr = ConvertData.ToHexString(b, 0, 2);

            if (tStr != "7E7E")
            {
                return(null);
            }
            Zhgd_iot_tower_current data = new Zhgd_iot_tower_current();

            #region 原协议
            //设备号
            data.sn = ConvertData.ToHexString(b, 5, 3);
            //司机卡号
            data.driver_id_code = ConvertData.ToHexString(b, 8, 4);
            //日期
            tStr = ConvertData.ToHexString(b, 12, 6);
            try
            {
                data.@timestamp = DPC_Tool.GetTimeStamp(DateTime.ParseExact(tStr, "yyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture));
            }
            catch
            {
                data.@timestamp = DPC_Tool.GetTimeStamp();
            }
            IntValue iv = new IntValue();
            //经度
            iv.bValue1 = b[18];
            iv.bValue2 = b[19];
            iv.bValue3 = b[20];
            iv.bValue4 = b[21];
            //data.Current.Longitude = (iv.iValue / 100000.0).ToString("0.00");
            //纬度
            iv.bValue1 = b[22];
            iv.bValue2 = b[23];
            iv.bValue3 = b[24];
            iv.bValue4 = b[25];
            //data.Current.Latitude = (iv.iValue / 100000.0).ToString("0.00");
            UShortValue s = new UShortValue();
            //高度
            s.bValue1   = b[26];
            s.bValue2   = b[27];
            data.height = double.Parse((s.sValue / 100.00).ToString("0.00"));
            //幅度
            s.bValue1  = b[28];
            s.bValue2  = b[29];
            data.range = double.Parse((s.sValue / 100.00).ToString("0.00"));
            ShortValue sv = new ShortValue();
            //转角
            sv.bValue1    = b[30];
            sv.bValue2    = b[31];
            data.rotation = double.Parse((sv.sValue / 10.00).ToString("0.00"));
            //重量
            s.bValue1   = b[32];
            s.bValue2   = b[33];
            data.weight = double.Parse((s.sValue / 100.00).ToString("0.00"));
            //风速
            s.bValue1       = b[34];
            s.bValue2       = b[35];
            data.wind_speed = double.Parse((s.sValue / 100.00).ToString("0.00"));
            data.wind_grade = ConvertWind.WindToLeve(s.sValue / 100.0f);
            if (data.wind_grade >= 13)
            {
                data.wind_grade = 12;
            }
            //倾角X
            sv.bValue1 = b[36];
            sv.bValue2 = b[37];
            data.dip_x = double.Parse((sv.sValue / 100.00).ToString("0.00"));
            //倾角Y
            sv.bValue1 = b[38];
            sv.bValue2 = b[39];
            data.dip_y = double.Parse((sv.sValue / 100.00).ToString("0.00"));
            //安全力矩
            s.bValue1 = b[40];
            s.bValue2 = b[41];
            //data.Current.Safetorque = (s.sValue / 10.00).ToString("0.00");
            //安全起重量
            s.bValue1 = b[42];
            s.bValue2 = b[43];
            //data.Current.SafeWeight = (s.sValue / 100.00).ToString("0.00");
            //倍率
            //data.Current.Times = Convert.ToInt32(b[44]).ToString();

            //限位控制器状态
            //s.bValue1 = b[51];
            //s.bValue2 = b[52];
            //data.Current.LimitStatus = Convert.ToString(s.sValue, 2).PadLeft(16, '0');
            //LimitFlag(data, data.Current.LimitStatus);

            ////传感器状态
            //s.bValue1 = b[53];
            //s.bValue2 = b[54];
            //data.Current.SensorStatus = Convert.ToString(s.sValue, 2).PadLeft(16, '0');

            //预警告码
            IntValue i = new IntValue();
            //i.bValue1 = b[55];
            //i.bValue2 = b[56];
            //i.bValue3 = b[57];
            //i.bValue4 = b[58];
            //string WarnType = Convert.ToString(i.iValue, 2).PadLeft(32, '0');

            //WarnFlag(data, WarnType);
            //报警告码
            i.bValue1 = b[59];
            i.bValue2 = b[60];
            i.bValue3 = b[61];
            i.bValue4 = b[62];
            string AlarmType = Convert.ToString(i.iValue, 2).PadLeft(32, '0'); //总共是32位右对齐
            AlarmFlag(data, AlarmType);                                        //报警码解析
            tStr = ConvertData.ToHexString(b, 64, 2);
            if (tStr != "7D7D")
            {
                return(null);
            }
            #endregion

            //进行数据put
            Tower_operation.Send_tower_Current(data);
            return(null);
        }
 protected abstract IntegerVector Create(IRandom random, IntValue length, IntMatrix bounds);
예제 #42
0
    public void OnButtonClicked()
    {
        IntValue money = AssetBundleManager.Instance.GetAsset <IntValue>("configs", "Money");

        money.Value += add;
    }
예제 #43
0
 protected abstract BinaryVector Create(IRandom random, IntValue length);
예제 #44
0
        private void AfterDeserialization()
        {
            #region conversion of old NSM parameters
            if (Parameters.ContainsKey(SelectorParameterName)) // change SelectorParameter type from ISelector to ISingleObjectiveSelector
            {
                ValueParameter <ISelector> param = Parameters[SelectorParameterName] as ValueParameter <ISelector>;
                if (param != null)
                {
                    ISingleObjectiveSelector selector = param.Value as ISingleObjectiveSelector;
                    if (selector == null)
                    {
                        selector = new TournamentSelector();
                    }
                    Parameters.Remove(SelectorParameterName);
                    Parameters.Add(new ValueParameter <ISingleObjectiveSelector>(SelectorParameterName, "The inner selection operator to select the parents.", selector));
                }
            }
            // FixedValueParameter for quality difference percentage, max attempts, use range
            if (Parameters.ContainsKey(QualityDifferencePercentageParameterName))
            {
                ValueParameter <PercentValue> param = Parameters[QualityDifferencePercentageParameterName] as ValueParameter <PercentValue>;
                if (!(param is FixedValueParameter <PercentValue>))
                {
                    PercentValue diff = param != null ? param.Value as PercentValue : null;
                    if (diff == null)
                    {
                        diff = new PercentValue(0.05);
                    }
                    Parameters.Remove(QualityDifferencePercentageParameterName);
                    Parameters.Add(new FixedValueParameter <PercentValue>(QualityDifferencePercentageParameterName, "The minimum quality difference from parent1 to parent2 to accept the selection.", diff));
                }
            }
            if (Parameters.ContainsKey(QualityDifferenceMaxAttemptsParameterName))
            {
                ValueParameter <IntValue> param = Parameters[QualityDifferenceMaxAttemptsParameterName] as ValueParameter <IntValue>;
                if (!(param is FixedValueParameter <IntValue>))
                {
                    IntValue attempts = param != null ? param.Value as IntValue : null;
                    if (attempts == null)
                    {
                        attempts = new IntValue(5);
                    }
                    Parameters.Remove(QualityDifferenceMaxAttemptsParameterName);
                    Parameters.Add(new FixedValueParameter <IntValue>(QualityDifferenceMaxAttemptsParameterName, "The maximum number of attempts to find parents which differ in quality.", attempts));
                }
            }
            if (Parameters.ContainsKey(QualityDifferenceUseRangeParameterName))
            {
                ValueParameter <BoolValue> param = Parameters[QualityDifferenceUseRangeParameterName] as ValueParameter <BoolValue>;
                if (!(param is FixedValueParameter <BoolValue>))
                {
                    BoolValue range = param != null ? param.Value as BoolValue : null;
                    if (range == null)
                    {
                        range = new BoolValue(true);
                    }
                    Parameters.Remove(QualityDifferenceUseRangeParameterName);
                    Parameters.Add(new FixedValueParameter <BoolValue>(QualityDifferenceUseRangeParameterName, "Use the range from minimum to maximum quality as basis for QualityDifferencePercentage.", range));
                }
            }
            if (!Parameters.ContainsKey(QualityDifferenceUseRangeParameterName)) // add use range parameter
            {
                Parameters.Add(new FixedValueParameter <BoolValue>(QualityDifferenceUseRangeParameterName, "Use the range from minimum to maximum quality as basis for QualityDifferencePercentage.", new BoolValue(true)));
            }
            #endregion

            RegisterParameterEventHandlers();
        }
예제 #45
0
        /// <summary>
        ///     Converts a value in this type
        /// </summary>
        /// <param name="value">The value to convert</param>
        /// <returns></returns>
        public override IValue convert(IValue value)
        {
            IValue retVal = null;

            EnumValue enumValue = value as EnumValue;
            if (enumValue != null && enumValue.Range != null)
            {
                retVal = findEnumValue(enumValue.Name);
                if (retVal == null)
                {
                    Log.Error("Cannot convert " + enumValue.Name + " to " + FullName);
                }
            }
            else
            {
                try
                {
                    switch (getPrecision())
                    {
                        case acceptor.PrecisionEnum.aIntegerPrecision:
                        {
                            Decimal val = getValueAsInt(value);
                            Decimal min = MinValueAsLong;
                            Decimal max = MaxValueAsLong;
                            if (val >= min && val <= max)
                            {
                                retVal = new IntValue(this, val);
                            }
                        }
                            break;
                        case acceptor.PrecisionEnum.aDoublePrecision:
                        {
                            double val = getValueAsDouble(value);
                            double min = MinValueAsDouble;
                            double max = MaxValueAsDouble;
                            if (val >= min && val <= max)
                            {
                                retVal = new DoubleValue(this, val);
                            }
                            break;
                        }
                    }
                }
                catch (Exception exception)
                {
                    Log.Error("Cannot convert range value", exception);
                }
            }

            return retVal;
        }
예제 #46
0
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyUp(KeyCode.Escape))
        {
            if (DialogBase.Actived())
            {
                DebugConsole.Log("Hide");
                DialogBase.Hide();
            }
            else
            {
                DebugConsole.Log("Show");
                DialogBase.Show("ESC", "Are you sure to exit game?", QuitGame);
            }
        }

        if (m_broadcastMsg != "")
        {
            // 有系统消息,平移吧
            GameObject goBroadcast = GameObject.Find("BroadcastText");
            Vector3    pos         = goBroadcast.transform.localPosition;
            pos.x -= 50 * Time.deltaTime;
            goBroadcast.transform.localPosition = pos;

            // 从600~-600
            if (goBroadcast.transform.localPosition.x < -600)
            {
                m_broadcastMsg = "";
            }
        }
        else
        {
            m_broadcastMsg = Lobby.getInstance().GetBroadcast();
            if (m_broadcastMsg != "")
            {
                GameObject goBroadcast = GameObject.Find("BroadcastText");
                goBroadcast.GetComponent <Text>().text = m_broadcastMsg;
                goBroadcast.transform.localPosition    = new Vector3(600, 0, 0);
            }
        }

        if (m_net == null || !m_net.IsRunning())
        {
            // 主动结束了
            return;
        }

        if (m_net.CheckReconnect())
        {
            CheckLogin();

            DialogReconnect.Hide();
        }

        ProtoPacket packet = new ProtoPacket();

        if (m_net.RecvTryDequeue(ref packet))
        {
            DebugConsole.Log("Reception handle cmdId:" + packet.cmdId);
            switch (packet.cmdId)
            {
            case Constants.Lion_QuickLoginInfo:
            {
                Lobby.getInstance().UserInfo = (LionUserInfo)packet.proto; // 更新LionUser
                m_login = true;
                UpdateUserInfoUI();                                        // 更新大厅主界面中信息
                if (packet.callback != null)
                {
                    packet.callback();
                }
            }
            break;

            case Constants.Lion_GetProfile:
            {
                LionUserInfo usrInfo = (LionUserInfo)packet.proto;        // 更新LionUser
                if (usrInfo.UserId == Lobby.getInstance().UId)
                {
                    Lobby.getInstance().UserInfo = usrInfo;
                }
                Lobby.getInstance().QueryUserInfo = usrInfo;

                if (packet.callback != null)
                {
                    // 通常这里显示个人信息对话框
                    packet.callback();
                }
            }
            break;

            case Constants.Lion_GetTigerStat:
            {
                Lobby.getInstance().TigerStatInfo = (TigerStat)packet.proto;
                if (packet.callback != null)
                {
                    packet.callback();
                }
            }
            break;

            case Constants.Lion_GetFriendRequests:
            case Constants.Lion_GetFriends:
            {
                Lobby.getInstance().FriendIDArray = (LongArray)packet.proto;
                if (packet.callback != null)
                {
                    GetFriendSummary(packet.callback);
                }
                else
                {
                    GetFriendSummary(ShowFriendsDlg);
                }
            }
            break;

            case Constants.Lion_GetFriendSummary:
            {
                Lobby.getInstance().CurrentSummaryList = (FriendSummaryList)packet.proto;
                DebugConsole.Log("Summary count:" + Lobby.getInstance().CurrentSummaryList.Data.Count);
                if (packet.callback != null)
                {
                    packet.callback();
                }
            }
            break;

            case Constants.Lion_IgnoreFriend:
            case Constants.Lion_AcceptFriend:
            case Constants.Lion_AddFriend:
            case Constants.Lion_DeleteFriend:
            {
                Status stat = (Status)packet.proto;
                if (stat.Code == 0)        // successful
                {
                    if (packet.callback != null)
                    {
                        packet.callback();
                    }
                }
                else
                {
                    DebugConsole.Log(stat.Desc);
                }
            }
            break;

            case Constants.Lion_Redirect:
            {
                Lobby.getInstance().RedirectInfo = (RedirectResp)packet.proto;
                // 切换到游戏场景中
                //m_net.Close();
                DebugConsole.Log("Reception enter slot scene");
                Global.NextSceneName = "slot";
                SceneManager.LoadScene("loading");
            }
            break;

            case Constants.Lion_UpdateProfile:
            {
                DebugConsole.Log("Lion_UpdateProfile");
                Status stat = (Status)packet.proto;
                if (stat.Code == 0)        // successful
                {
                    if (packet.callback != null)
                    {
                        packet.callback();
                    }
                }
                else
                {
                    DebugConsole.Log(stat.Desc);
                }
            }
            break;

            case Constants.Lion_NotifyWeeklyLogin:
            {
                // 连续登录奖励
                // NotifyWeeklyLogin 返回的intvalue是0-6,0表示今天登陆了(昨天没登录)
                IntValue iv = (IntValue)packet.proto;
                DialogDailyBonus.Show(iv.Value);

                //ExplodeCoin.Show();
            }
            break;

            case Constants.Lion_TakeLoginBonus:
            {
                LongArray la = (LongArray)packet.proto;
                // la[0] 奖励金币数
                // la[1] 最终总数
                if (la.Data.Count >= 2)
                {
                    Lobby.getInstance().UserInfo.Gold = la.Data[1];
                    // 若有动画,在此添加
                    JumpAndMoveCoins(6, UpdateUserInfoUI);
                }
            }
            break;

            case Constants.Lion_NotifyFreeBonus:
            {
                // 第一次登陆的时候,数据库里面没有数据,所以返回0
                // 后端推送,倒计时剩余时间长度(毫秒),如果小于等于0,直接显示奖励
                // 免费奖励
                LongValue lv       = (LongValue)packet.proto;
                long      curEpoch = (System.DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000;
                Lobby.getInstance().FreeBonusEpoch = curEpoch + lv.Value;
                UpdateCountDown();
            }
            break;

            case Constants.Lion_TakeFreeBonus:
            {
                LongArray la = (LongArray)packet.proto;
                if (la.Data.Count >= 2)
                {
                    Lobby.getInstance().UserInfo.Gold = la.Data[1];
                    // 若有动画,在此添加
                    FlyCoin(Constants.Bonus_Free);
                    UpdateUserInfoUI();
                }
            }
            break;

            case Constants.Lion_BuyItem:
            {
                Status stat = (Status)packet.proto;
                // 更新购买相关的:金币 or 背包
                DebugConsole.Log("Buy item return:" + stat.Code.ToString());
                if (stat.Code == 0)        // successful
                {
                    if (packet.callback != null)
                    {
                        packet.callback();
                    }
                }
                else
                {
                    DebugConsole.Log(stat.Desc);
                }
            }
            break;

            case Constants.Lion_Register:
            {
                Status stat = (Status)packet.proto;
                DebugConsole.Log("Register by email return:" + stat.Code.ToString());
                if (stat.Code == 0)        // successful
                {
                    if (packet.callback != null)
                    {
                        packet.callback();
                    }
                }
                else
                {
                    DebugConsole.Log(stat.Desc);
                    DialogBase.Show("Register by email", "Error:" + stat.Desc);
                }
            }
            break;

            case Constants.Lion_ModPass:
            {
                Status stat = (Status)packet.proto;
                DebugConsole.Log("Modify password return:" + stat.Code.ToString());
                if (stat.Code == 0)        // successful
                {
                    if (packet.callback != null)
                    {
                        packet.callback();
                    }
                }
                else
                {
                    DebugConsole.Log(stat.Desc);
                    DialogBase.Show("Modify password", "Error:" + stat.Desc);
                }
            }
            break;

            case Constants.Lion_RefreshGold:
            {
                LongValue lv = (LongValue)packet.proto;
                DebugConsole.Log("Refresh gold:" + lv.ToString());
                Lobby.getInstance().UserInfo.Gold = lv.Value;
                UpdateUserInfoUI();
            }
            break;

            case Constants.Lion_GetShopItems:
            {
                Lobby.getInstance().ShopList = (ShopList)packet.proto;
                DebugConsole.Log("ShopName:" + Lobby.getInstance().ShopList.ShopName);
                if (packet.callback != null)
                {
                    packet.callback();
                }
            }
            break;

            case Constants.Lion_BroadcastSystemMessage:
            {
                Tools.PlayNotification(Constants.Audio.Audio_Notification);
                StringValue sv = (StringValue)packet.proto;
                Lobby.getInstance().AddBroadcast(sv.Value);
            }
            break;

            case Constants.Lion_GetItems:
            {
                //
                Lobby.getInstance().UserItemList = (UserItemList)packet.proto;

                if (packet.callback != null)
                {
                    packet.callback();
                }
                else
                {
                    DialogBag.Show(null);
                }
            }
            break;

            case Constants.Reconnect:
            {
                // 展示重连对话框,直到重连成功
                if (packet.msgId == 1)
                {
                    ProtoNet.WriteLog("Reconnecting...");
                    // 3s后Display中重连
                    m_net.CheckReconnect(3);
                    DialogReconnect.Show();
                }
            }
            break;

            case Constants.Error:
            {
                // 展示错误
                Status stat = (Status)packet.proto;
                string err  = "Error:" + stat.Code.ToString() + "-" + stat.Desc;
                DialogBase.Show("ERROR", err);
            }
            break;

            default:
            {
                DebugConsole.Log("Reception invalid cmdId:" + packet.cmdId);
            }
            break;
            }
        }
    }
 public override sealed void ModifyArchitecture(
   IRandom random,
   ISymbolicExpressionTree symbolicExpressionTree,
   IntValue maxFunctionDefinitions, IntValue maxFunctionArguments) {
   DuplicateSubroutine(random, symbolicExpressionTree, maxFunctionDefinitions.Value, maxFunctionArguments.Value);
 }
예제 #48
0
        public override IOperation Apply()
        {
            var N      = DimensionParameter.ActualValue.Value;
            var lambda = PopulationSizeParameter.ActualValue.Value;
            var mu     = MuParameter.ActualValue;

            var sp = new CMAParameters();

            sp.Mu = mu == null ? (int)Math.Floor(lambda / 2.0) : mu.Value;
            sp.QualityHistorySize = 10 + 30 * N / lambda;
            sp.QualityHistory     = new Queue <double>(sp.QualityHistorySize + 1);

            var s = InitialSigmaParameter.ActualValue;

            if (s == null || s.Length == 0)
            {
                throw new InvalidOperationException("Initial standard deviation (sigma) must be given.");
            }
            var sigma = s.Max();

            if (sigma <= 0)
            {
                throw new InvalidOperationException("Initial standard deviation (sigma) must be > 0.");
            }

            var    pc = new double[N];   // evolution paths for C
            var    ps = new double[N];   // evolution paths for sigma
            var    B = new double[N, N]; // B defines the coordinate system
            var    D = new double[N];    // diagonal D defines the scaling
            var    C = new double[N, N]; // covariance matrix C
            var    BDz = new double[N];
            double minSqrtdiagC = int.MaxValue, maxSqrtdiagC = int.MinValue;

            for (int i = 0; i < N; i++)
            {
                B[i, i] = 1;
                if (s.Length == 1)
                {
                    D[i] = 1;
                }
                else if (s.Length == N)
                {
                    D[i] = s[i] / sigma;
                }
                else
                {
                    throw new InvalidOperationException("Initial standard deviation (sigma) must either contain only one value for all dimension or for every dimension.");
                }
                if (D[i] <= 0)
                {
                    throw new InvalidOperationException("Initial standard deviation (sigma) values must all be > 0.");
                }
                C[i, i] = D[i] * D[i];
                if (Math.Sqrt(C[i, i]) < minSqrtdiagC)
                {
                    minSqrtdiagC = Math.Sqrt(C[i, i]);
                }
                if (Math.Sqrt(C[i, i]) > maxSqrtdiagC)
                {
                    maxSqrtdiagC = Math.Sqrt(C[i, i]);
                }
            }

            // ensure maximal and minimal standard deviations
            var sigmaBounds = SigmaBoundsParameter.ActualValue;

            if (sigmaBounds != null && sigmaBounds.Rows > 0)
            {
                for (int i = 0; i < N; i++)
                {
                    var d = sigmaBounds[Math.Min(i, sigmaBounds.Rows - 1), 0];
                    if (d > sigma * minSqrtdiagC)
                    {
                        sigma = d / minSqrtdiagC;
                    }
                }
                for (int i = 0; i < N; i++)
                {
                    var d = sigmaBounds[Math.Min(i, sigmaBounds.Rows - 1), 1];
                    if (d > sigma * maxSqrtdiagC)
                    {
                        sigma = d / maxSqrtdiagC;
                    }
                }
            }
            // end ensure ...

            // testAndCorrectNumerics
            double fac = 1;

            if (D.Max() < 1e-6)
            {
                fac = 1.0 / D.Max();
            }
            else if (D.Min() > 1e4)
            {
                fac = 1.0 / D.Min();
            }

            if (fac != 1.0)
            {
                sigma /= fac;
                for (int i = 0; i < N; i++)
                {
                    pc[i] *= fac;
                    D[i]  *= fac;
                    for (int j = 0; j < N; j++)
                    {
                        C[i, j] *= fac * fac;
                    }
                }
            }
            // end testAndCorrectNumerics

            var initialIterations = InitialIterationsParameter.ActualValue;

            if (initialIterations == null)
            {
                initialIterations = new IntValue(0);
            }

            double maxD = D.Max(), minD = D.Min();

            if (minD == 0)
            {
                sp.AxisRatio = double.PositiveInfinity;
            }
            else
            {
                sp.AxisRatio = maxD / minD;
            }
            sp.PC    = pc;
            sp.PS    = ps;
            sp.B     = B;
            sp.D     = D;
            sp.C     = C;
            sp.BDz   = BDz;
            sp.Sigma = sigma;
            if (sigmaBounds != null)
            {
                sp.SigmaBounds = new double[sigmaBounds.Rows, sigmaBounds.Columns];
                for (int i = 0; i < sigmaBounds.Rows; i++)
                {
                    for (int j = 0; j < sigmaBounds.Columns; j++)
                    {
                        sp.SigmaBounds[i, j] = sigmaBounds[i, j];
                    }
                }
            }
            sp.InitialIterations = initialIterations.Value;

            StrategyParametersParameter.ActualValue = sp;
            return(base.Apply());
        }
예제 #49
0
 protected abstract RealVector Create(IRandom random, IntValue length, DoubleMatrix bounds);
예제 #50
0
 protected abstract BinaryVector Create(IRandom random, IntValue length);
예제 #51
0
 void IValueVisitor.Visit(IntValue attr)
 {
     _value.Value = attr.Value;
 }
예제 #52
0
 protected PRVEncoding(PRVEncoding original, Cloner cloner)
     : base(original, cloner)
 {
     this.nrOfRules           = cloner.Clone(original.NrOfRules);
     this.PriorityRulesVector = cloner.Clone(original.PriorityRulesVector);
 }
 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();
   }
 }
예제 #54
0
 public PRVEncoding(int nrOfRules)
     : base()
 {
     this.nrOfRules           = new IntValue(nrOfRules);
     this.PriorityRulesVector = new IntegerVector();
 }
 /// <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;
 }
예제 #56
0
 public PRVEncoding(IntegerVector iv, IntValue nrOfRules)
     : base()
 {
     this.nrOfRules           = (IntValue)nrOfRules.Clone();
     this.PriorityRulesVector = (IntegerVector)iv.Clone();
 }
 public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, ItemList<BoolArray> realizations, CancellationToken cancellation) {
   var distanceM = (DistanceMatrix)distances;
   Func<int, int, double> distance = (a, b) => distanceM[a, b];
   for (var i = localIterations.Value; i < maxIterations; i++) {
     InversionMove bestMove = null;
     double bestQuality = 0; // we have to make an improvement, so 0 is the baseline
     double evaluations = 0.0;
     foreach (var move in ExhaustiveInversionMoveGenerator.Generate(assignment)) {
       double moveQuality = PTSPEstimatedInversionMoveEvaluator.EvaluateMove(assignment, move, distance, realizations);
       evaluations += realizations.Count * 4.0 / (assignment.Length * assignment.Length);
       if (maximization && moveQuality > bestQuality
         || !maximization && moveQuality < bestQuality) {
         bestQuality = moveQuality;
         bestMove = move;
       }
     }
     evaluatedSolutions.Value += (int)Math.Ceiling(evaluations);
     if (bestMove == null) break;
     InversionManipulator.Apply(assignment, bestMove.Index1, bestMove.Index2);
     quality.Value += bestQuality;
     localIterations.Value++;
     cancellation.ThrowIfCancellationRequested();
   }
 }
예제 #58
0
        /// <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));
        }
예제 #59
0
 public static void Improve(IRandom random, Permutation assignment, DoubleMatrix weights, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, int neighborhoodSize, CancellationToken cancellation)
 {
     for (int i = localIterations.Value; i < maxIterations; i++)
     {
         ScrambleMove bestMove    = null;
         double       bestQuality = 0; // we have to make an improvement, so 0 is the baseline
         double       evaluations = 0.0;
         for (int j = 0; j < neighborhoodSize; j++)
         {
             var    move        = StochasticScrambleMultiMoveGenerator.GenerateRandomMove(assignment, random);
             double moveQuality = QAPScrambleMoveEvaluator.Apply(assignment, move, weights, distances);
             evaluations += 2.0 * move.ScrambledIndices.Length / assignment.Length;
             if (maximization && moveQuality > bestQuality ||
                 !maximization && moveQuality < bestQuality)
             {
                 bestQuality = moveQuality;
                 bestMove    = move;
             }
         }
         evaluatedSolutions.Value += (int)Math.Ceiling(evaluations);
         if (bestMove == null)
         {
             break;
         }
         ScrambleManipulator.Apply(assignment, bestMove.StartIndex, bestMove.ScrambledIndices);
         quality.Value += bestQuality;
         localIterations.Value++;
         cancellation.ThrowIfCancellationRequested();
     }
 }
예제 #60
0
 public int CompareTo(ComparableElement1 other)
 {
     return(IntValue.CompareTo(other.IntValue));
 }