Esempio n. 1
0
        public GEArtificialAntProblem()
            : base(new GEArtificialAntEvaluator(), new UniformRandomIntegerVectorCreator())
        {
            BoolMatrix world = new BoolMatrix(santaFeAntTrail);

            Parameters.Add(new ValueParameter <IntValue>("MaximumExpressionLength", "Maximal length of the expression to control the artificial ant (genotype length).", new IntValue(30)));
            Parameters.Add(new ValueParameter <ISymbolicExpressionGrammar>("ArtificialAntExpressionGrammar", "The grammar that should be used for artificial ant expressions.", new ArtificialAntExpressionGrammar()));
            Parameters.Add(new ValueParameter <BoolMatrix>("World", "The world for the artificial ant with scattered food items.", world));
            Parameters.Add(new ValueParameter <IntValue>("MaximumTimeSteps", "The number of time steps the artificial ant has available to collect all food items.", new IntValue(600)));
            IntMatrix m = new IntMatrix(new int[, ] {
                { 0, 100 }
            });

            Parameters.Add(new ValueParameter <IntMatrix>("Bounds", "The integer number range in which the single genomes of a genotype are created.", m));
            Parameters.Add(new ValueParameter <IGenotypeToPhenotypeMapper>("GenotypeToPhenotypeMapper", "Maps the genotype (an integer vector) to the phenotype (a symbolic expression tree).", new DepthFirstMapper()));

            Maximization.Value           = true;
            MaximizationParameter.Hidden = true;
            BestKnownQuality             = new DoubleValue(89);

            SolutionCreator.IntegerVectorParameter.ActualName           = "AntTrailSolutionIntegerVector";
            Evaluator.SymbolicExpressionTreeParameter.ActualName        = "AntTrailSolutionTree";
            Evaluator.SymbolicExpressionTreeGrammarParameter.ActualName = "ArtificialAntExpressionGrammar";
            Evaluator.QualityParameter.ActualName = "FoodEaten";

            InitializeOperators();
            RegisterEventHandlers();
        }
        protected GESymbolicDataAnalysisProblem(T problemData, U evaluator, V solutionCreator)
            : base(evaluator, solutionCreator)
        {
            Parameters.Add(new ValueParameter <T>(ProblemDataParameterName, ProblemDataParameterDescription, problemData));
            Parameters.Add(new ValueParameter <ISymbolicDataAnalysisGrammar>(SymbolicExpressionTreeGrammarParameterName, SymbolicExpressionTreeGrammarParameterDescription));
            Parameters.Add(new ValueParameter <ISymbolicDataAnalysisExpressionTreeInterpreter>(SymbolicExpressionTreeInterpreterParameterName, SymbolicExpressionTreeInterpreterParameterDescription));
            Parameters.Add(new FixedValueParameter <IntValue>(MaximumSymbolicExpressionTreeLengthParameterName, MaximumSymbolicExpressionTreeLengthParameterDescription));
            Parameters.Add(new FixedValueParameter <IntRange>(FitnessCalculationPartitionParameterName, FitnessCalculationPartitionParameterDescription));
            Parameters.Add(new FixedValueParameter <IntRange>(ValidationPartitionParameterName, ValidationPartitionParameterDescription));
            Parameters.Add(new FixedValueParameter <PercentValue>(RelativeNumberOfEvaluatedSamplesParameterName, RelativeNumberOfEvaluatedSamplesParameterDescription, new PercentValue(1)));
            Parameters.Add(new FixedValueParameter <BoolValue>(ApplyLinearScalingParameterName, ApplyLinearScalingParameterDescription, new BoolValue(false)));
            IntMatrix m = new IntMatrix(new int[, ] {
                { 0, 100 }
            });

            Parameters.Add(new ValueParameter <IntMatrix>(BoundsParameterName, BoundsParameterDescription, m));
            Parameters.Add(new ValueParameter <IGenotypeToPhenotypeMapper>(GenotypeToPhenotypeMapperParameterName, GenotypeToPhenotypeMapperParameterDescription, new DepthFirstMapper()));

            SymbolicExpressionTreeInterpreterParameter.Hidden = true;
            ApplyLinearScalingParameter.Hidden = true;

            SymbolicExpressionTreeGrammar     = new GESymbolicExpressionGrammar(problemData.AllowedInputVariables, problemData.AllowedInputVariables.Count() * 3);
            SymbolicExpressionTreeInterpreter = new SymbolicDataAnalysisExpressionTreeLinearInterpreter();

            FitnessCalculationPartition.Start = ProblemData.TrainingPartition.Start;
            FitnessCalculationPartition.End   = ProblemData.TrainingPartition.End;

            InitializeOperators();

            UpdateGrammar();
            RegisterEventHandlers();
        }
Esempio n. 3
0
        private static IntegerVector GetNontVector(IRandom random, IntMatrix bounds, int length)
        {
            IntegerVector v = new IntegerVector(length);

            v.Randomize(random, bounds);
            return(v);
        }
Esempio n. 4
0
        public IntegerVectorEncoding(string name, int length, int min = int.MinValue, int max = int.MaxValue, int?step = null)
            : base(name)
        {
            if (min >= max)
            {
                throw new ArgumentException("min must be less than max", "min");
            }
            if (step.HasValue && step.Value <= 0)
            {
                throw new ArgumentException("step must be greater than zero or null", "step");
            }

            var bounds = new IntMatrix(1, step.HasValue ? 3 : 2);

            bounds[0, 0] = min;
            bounds[0, 1] = max;
            if (step.HasValue)
            {
                bounds[0, 2] = step.Value;
            }

            lengthParameter = new FixedValueParameter <IntValue>(Name + ".Length", new IntValue(length));
            boundsParameter = new ValueParameter <IntMatrix>(Name + ".Bounds", bounds);
            Parameters.Add(lengthParameter);
            Parameters.Add(boundsParameter);

            SolutionCreator = new UniformRandomIntegerVectorCreator();
            RegisterParameterEvents();
            DiscoverOperators();
        }
Esempio n. 5
0
        public static IntMatrix ToBinaryMap(Image i_GrayScaleImage, Color i_Treshold, Size i_newCanvasSize)
        {
            IntMatrix retBinaryMap = new IntMatrix(i_newCanvasSize.Height, i_newCanvasSize.Width);
            Bitmap    bitmap       = new Bitmap(i_GrayScaleImage);
            ///Logic for single cell
            Func <int, int, int, int> filterBlacks = (row, col, val) =>
            {
                if (row < bitmap.Height && col < bitmap.Width)
                {
                    Color currColor = bitmap.GetPixel(col, row);
                    if (currColor.R < i_Treshold.R &&
                        currColor.G < i_Treshold.G &&
                        currColor.B < i_Treshold.B)
                    {
                        return(sr_Line);
                    }
                    else
                    {
                        return(sr_NoLine);
                    }
                }
                else
                {
                    return(sr_NoLine);
                }
            };

            ///Applying logic for whole matrix
            retBinaryMap.Iterate(filterBlacks);

            return(retBinaryMap);
        }
        public static void Manipulate(IRandom random, IntegerVector vector, IntMatrix bounds, int index)
        {
            if (bounds == null || bounds.Rows == 0 || bounds.Columns < 2)
            {
                throw new ArgumentException("UniformOnePositionManipulator: Invalid bounds specified", "bounds");
            }
            int min = bounds[index % bounds.Rows, 0], max = bounds[index % bounds.Rows, 1], step = 1;

            if (min == max)
            {
                vector[index] = min;
            }
            else
            {
                if (bounds.Columns > 2)
                {
                    step = bounds[index % bounds.Rows, 2];
                }
                // max has to be rounded to the lower feasible value
                // e.g. min...max / step = 0...100 / 5, max is exclusive so it would be 0..99
                // but 99 is not a feasible value, so max needs to be adjusted => min = 0, max = 95
                max           = FloorFeasible(min, max, step, max - 1);
                vector[index] = RoundFeasible(min, max, step, random.Next(min, max));
            }
        }
        private void InitDistances(ref IntMatrix o_DistMatrix, IntMatrix i_BinaryMapBase)
        {
            Func <int, int, int, int> ToDifferentSizedCopy = (row, col, val) =>
            {///Building a logic for one cell
                if (row <= i_BinaryMapBase.RowsCount && col <= i_BinaryMapBase.ColumnsCount)
                {
                    int baseVale = i_BinaryMapBase[row, col];
                    if (baseVale == 1)
                    {
                        return(0);
                    }
                    else if (baseVale == 0)
                    {
                        return(Int16.MaxValue);
                    }
                    else
                    {
                        throw new HausdorffMatchingException("A non binary value found in a binary matrix!!! Non binary values are not allowed!");
                    }
                }
                else
                {
                    return(0);
                }
            };

            ///Apllying the logic for whole matrix
            o_DistMatrix.Iterate(ToDifferentSizedCopy);
        }
Esempio n. 8
0
 public IntMatrix(IntMatrix orig) : this(modshogunPINVOKE.new_IntMatrix__SWIG_5(IntMatrix.getCPtr(orig)), true)
 {
     if (modshogunPINVOKE.SWIGPendingException.Pending)
     {
         throw modshogunPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Esempio n. 9
0
        /// <summary>
        /// Generates a new random integer vector with the given <paramref name="length"/>.
        /// </summary>
        /// <param name="random">The random number generator.</param>
        /// <param name="length">The length of the int vector.</param>
        /// <param name="bounds">A matrix containing the inclusive lower and inclusive upper bound in the first and second column and a step size in the third column.
        /// Each line represents the bounds for a certain dimension. If fewer lines are given, the lines are cycled.</param>
        /// <returns>The newly created integer vector.</returns>
        public static IntegerVector Apply(IRandom random, int length, IntMatrix bounds)
        {
            var result = new IntegerVector(length);

            result.Randomize(random, bounds);
            return(result);
        }
    /// <summary>
    /// Performs the rounded blend alpha crossover (BLX-a) of two integer vectors.<br/>
    /// It creates new offspring by sampling a new value in the range [min_i - d * alpha, max_i + d * alpha) at each position i
    /// and rounding the result to the next integer.
    /// Here min_i and max_i are the smaller and larger value of the two parents at position i and d is max_i - min_i.
    /// </summary>
    /// <exception cref="ArgumentException">
    /// Thrown when <paramref name="parent1"/> and <paramref name="parent2"/> are of different length or<br/>
    /// when <paramref name="alpha"/> is less than 0.
    /// </exception>
    /// <param name="random">The random number generator.</param>
    /// <param name="parent1">The first parent for the crossover operation.</param>
    /// <param name="parent2">The second parent for the crossover operation.</param>
    /// <param name="bounds">The bounds and step size for each dimension (will be cycled in case there are less rows than elements in the parent vectors).</param>
    /// <param name="alpha">The alpha value for the crossover.</param>
    /// <returns>The newly created integer vector resulting from the crossover operation.</returns>
    public static IntegerVector Apply(IRandom random, IntegerVector parent1, IntegerVector parent2, IntMatrix bounds, DoubleValue alpha) {
      if (parent1.Length != parent2.Length) throw new ArgumentException("RoundedBlendAlphaCrossover: The parents' vectors are of different length.", "parent1");
      if (alpha.Value < 0) throw new ArgumentException("RoundedBlendAlphaCrossover: Paramter alpha must be greater or equal than 0.", "alpha");
      if (bounds == null || bounds.Rows < 1 || bounds.Columns < 2) throw new ArgumentException("RoundedBlendAlphaCrossover: Invalid bounds specified.", "bounds");

      int length = parent1.Length;
      var result = new IntegerVector(length);
      double max = 0, min = 0, d = 0, resMin = 0, resMax = 0;
      int minBound, maxBound, step = 1;

      for (int i = 0; i < length; i++) {
        minBound = bounds[i % bounds.Rows, 0];
        maxBound = bounds[i % bounds.Rows, 1];
        if (bounds.Columns > 2) step = bounds[i % bounds.Rows, 2];
        maxBound = FloorFeasible(minBound, maxBound, step, maxBound - 1);

        max = Math.Max(parent1[i], parent2[i]);
        min = Math.Min(parent1[i], parent2[i]);
        d = Math.Abs(max - min);
        resMin = FloorFeasible(minBound, maxBound, step, min - d * alpha.Value);
        resMax = CeilingFeasible(minBound, maxBound, step, max + d * alpha.Value);

        result[i] = RoundFeasible(minBound, maxBound, step, resMin + random.NextDouble() * Math.Abs(resMax - resMin));
      }
      return result;
    }
        /// <summary>
        /// Performs a normally distributed all position manipulation on the given
        /// <paramref name="vector"/> and rounds the result to the next feasible value.
        /// </summary>
        /// <exception cref="InvalidOperationException">Thrown when the sigma vector is null or of length 0.</exception>
        /// <param name="sigma">The sigma vector determining the strength of the mutation.</param>
        /// <param name="random">A random number generator.</param>
        /// <param name="vector">The integer vector to manipulate.</param>#
        /// <param name="bounds">The bounds and step size for each dimension (will be cycled in case there are less rows than elements in the parent vectors).</param>
        /// <returns>The manipulated integer vector.</returns>
        public static void Apply(IRandom random, IntegerVector vector, IntMatrix bounds, DoubleArray sigma)
        {
            if (sigma == null || sigma.Length == 0)
            {
                throw new ArgumentException("RoundedNormalAllPositionsManipulator: Vector containing the standard deviations is not defined.", "sigma");
            }
            if (bounds == null || bounds.Rows == 0 || bounds.Columns < 2)
            {
                throw new ArgumentException("RoundedNormalAllPositionsManipulator: Invalid bounds specified.", "bounds");
            }
            var N = new NormalDistributedRandom(random, 0.0, 1.0);

            for (int i = 0; i < vector.Length; i++)
            {
                int min = bounds[i % bounds.Rows, 0], max = bounds[i % bounds.Rows, 1], step = 1;
                if (bounds.Columns > 2)
                {
                    step = bounds[i % bounds.Rows, 2];
                }

                int value = (vector[i] + (int)Math.Round((N.NextDouble() * sigma[i % sigma.Length])) - min) / step;
                max       = FloorFeasible(min, max, step, max - 1);
                vector[i] = RoundFeasible(min, max, step, value);
            }
        }
Esempio n. 12
0
 public HausdorffMatchingResult(IntMatrix i_Side1, IntMatrix i_Side2, IntMatrix i_Result)
 {
     m_Side1          = i_Side1;
     m_Side2          = i_Side2;
     m_Result         = i_Result;
     ColoringFunction = defaultColoringConvension;
 }
Esempio n. 13
0
        private static void run()
        {
            int[,] Matrix = ReadIntMatrix();
            IntMatrix intMatrix = new IntMatrix(Matrix);

            int[] Arr = intMatrix.GetArr();
            WriteArr(Arr);
        }
Esempio n. 14
0
 public virtual void Randomize(IRandom random, int startIndex, int length, IntMatrix bounds) {
   if (length > 0) {
     for (int i = startIndex; i < startIndex + length; i++) {
       int min = bounds[i % bounds.Rows, 0], max = bounds[i % bounds.Rows, 1], step = 1;
       if (bounds.Columns > 2) step = bounds[i % bounds.Rows, 2];
       int numbers = (int)Math.Floor((max - min) / (double)step);
       array[i] = random.Next(numbers) * step + min;
     }
     OnReset();
   }
 }
        public override ICData Run()
        {
            Size CommonCanvasSize = new Size(Math.Max(m_Image1.Width, m_Image2.Width), Math.Max(m_Image1.Height, m_Image2.Height));

            m_BinaryMap1 = Utilities.ToBinaryMap(m_Image1, TresholdColor, CommonCanvasSize);
            m_BinaryMap2 = Utilities.ToBinaryMap(m_Image2, TresholdColor, CommonCanvasSize);

            HausdorffMatching matching = new HausdorffMatching(m_BinaryMap1, m_BinaryMap2);
            m_Result = matching.CalculateTwoSides();

            return new HausdorffMatchingResult(matching.ResultMap1, matching.ResultMap2, m_Result);
        }
Esempio n. 16
0
        public static int DetermineMax(IntMatrix i_Matrix)
        {
            int             retMax    = int.MinValue;
            Func <int, int> maxFinder = (Value) =>
            {
                retMax = Math.Max(retMax, Value);
                return(Value);
            };

            i_Matrix.Iterate(maxFinder);
            return(retMax);
        }
    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());
    }
    /// <summary>
    /// Performs a normally distributed all position manipulation on the given 
    /// <paramref name="vector"/> and rounds the result to the next feasible value.
    /// </summary>
    /// <exception cref="InvalidOperationException">Thrown when the sigma vector is null or of length 0.</exception>
    /// <param name="sigma">The sigma vector determining the strength of the mutation.</param>
    /// <param name="random">A random number generator.</param>
    /// <param name="vector">The integer vector to manipulate.</param>#
    /// <param name="bounds">The bounds and step size for each dimension (will be cycled in case there are less rows than elements in the parent vectors).</param>
    /// <returns>The manipulated integer vector.</returns>
    public static void Apply(IRandom random, IntegerVector vector, IntMatrix bounds, DoubleArray sigma) {
      if (sigma == null || sigma.Length == 0) throw new ArgumentException("RoundedNormalAllPositionsManipulator: Vector containing the standard deviations is not defined.", "sigma");
      if (bounds == null || bounds.Rows == 0 || bounds.Columns < 2) throw new ArgumentException("RoundedNormalAllPositionsManipulator: Invalid bounds specified.", "bounds");
      var N = new NormalDistributedRandom(random, 0.0, 1.0);
      for (int i = 0; i < vector.Length; i++) {
        int min = bounds[i % bounds.Rows, 0], max = bounds[i % bounds.Rows, 1], step = 1;
        if (bounds.Columns > 2) step = bounds[i % bounds.Rows, 2];

        int value = (vector[i] + (int)Math.Round((N.NextDouble() * sigma[i % sigma.Length])) - min) / step;
        max = FloorFeasible(min, max, step, max - 1);
        vector[i] = RoundFeasible(min, max, step, value);
      }
    }
Esempio n. 19
0
        public override ICData Run()
        {
            Size CommonCanvasSize = new Size(Math.Max(m_Image1.Width, m_Image2.Width), Math.Max(m_Image1.Height, m_Image2.Height));

            m_BinaryMap1 = Utilities.ToBinaryMap(m_Image1, TresholdColor, CommonCanvasSize);
            m_BinaryMap2 = Utilities.ToBinaryMap(m_Image2, TresholdColor, CommonCanvasSize);


            HausdorffMatching matching = new HausdorffMatching(m_BinaryMap1, m_BinaryMap2);

            m_Result = matching.CalculateTwoSides();

            return(new HausdorffMatchingResult(matching.ResultMap1, matching.ResultMap2, m_Result));
        }
 public void UniformOnePositionManipulatorApplyTest() {
   TestRandom random = new TestRandom();
   IntegerVector parent, expected;
   IntMatrix bounds = new IntMatrix(1, 2);
   // The following test is not based on published examples
   random.Reset();
   random.IntNumbers = new int[] { 3, 3 };
   parent = new IntegerVector(new int[] { 2, 2, 3, 5, 1 });
   expected = new IntegerVector(new int[] { 2, 2, 3, 3, 1 });
   bounds[0, 0] = 2;
   bounds[0, 1] = 7;
   UniformOnePositionManipulator.Apply(random, parent, bounds);
   Assert.IsTrue(Auxiliary.IntegerVectorIsEqualByPosition(expected, parent));
 }
 public static void Manipulate(IRandom random, IntegerVector vector, IntMatrix bounds, int index) {
   if (bounds == null || bounds.Rows == 0 || bounds.Columns < 2) throw new ArgumentException("UniformOnePositionManipulator: Invalid bounds specified", "bounds");
   int min = bounds[index % bounds.Rows, 0], max = bounds[index % bounds.Rows, 1], step = 1;
   if (min == max) {
     vector[index] = min;
   } else {
     if (bounds.Columns > 2) step = bounds[index % bounds.Rows, 2];
     // max has to be rounded to the lower feasible value
     // e.g. min...max / step = 0...100 / 5, max is exclusive so it would be 0..99
     // but 99 is not a feasible value, so max needs to be adjusted => min = 0, max = 95
     max = FloorFeasible(min, max, step, max - 1);
     vector[index] = RoundFeasible(min, max, step, random.Next(min, max));
   }
 }
Esempio n. 22
0
        public static IntMatrix ToBinaryMap(DoubleMatrix i_PointSet, Size i_newCanvasSize)
        {
            IntMatrix retMap = new IntMatrix(i_newCanvasSize.Height, i_newCanvasSize.Width);

            retMap.Init(sr_NoLine);

            for (int col = 0; col < i_PointSet.ColumnsCount; ++col)
            {
                int PixelRow = (int)i_PointSet[sr_Yrow, col];
                int PixelCol = (int)i_PointSet[sr_Xrow, col];
                retMap[PixelRow, PixelCol] = sr_Line;
            }
            return(retMap);
        }
    /// <summary>
    /// Changes randomly several, but at least one, positions in the given integer <paramref name="vector"/>, according to the given probabilities.
    /// </summary>
    /// <param name="random">A random number generator.</param>
    /// <param name="vector">The integer vector to manipulate.</param>
    /// <param name="bounds"> Contains the minimum value (inclusive), maximum value (exclusive), and step size of the sampling range for 
    /// the vector element to change.</param>
    /// <param name="probability">The probability for each dimension to be manipulated..</param>
    public static void Apply(IRandom random, IntegerVector vector, IntMatrix bounds, double probability) {
      if (bounds == null || bounds.Rows == 0 || bounds.Columns < 2) throw new ArgumentException("UniformSomePositionsManipulator: Invalid bounds specified", "bounds");
      bool atLeastOneManipulated = false;
      for (int index = 0; index < vector.Length; index++) {
        if (random.NextDouble() < probability) {
          atLeastOneManipulated = true;
          UniformOnePositionManipulator.Manipulate(random, vector, bounds, index);
        }
      }

      if (!atLeastOneManipulated) {
        UniformOnePositionManipulator.Manipulate(random, vector, bounds, random.Next(vector.Length));
      }
    }
Esempio n. 24
0
    /// <summary>
    /// Maps a genotype (an integer vector) to a phenotype (a symbolic expression tree).
    /// Random approach.
    /// </summary>
    /// <param name="random">random number generator</param>
    /// <param name="bounds">only used for PIGEMapper (ignore here)</param>
    /// <param name="length">only used for PIGEMapper (ignore here)</param>
    /// <param name="grammar">grammar definition</param>
    /// <param name="genotype">integer vector, which should be mapped to a tree</param>
    /// <returns>phenotype (a symbolic expression tree)</returns>
    public override SymbolicExpressionTree Map(IRandom random, IntMatrix bounds, int length,
                                               ISymbolicExpressionGrammar grammar,
                                               IntegerVector genotype) {

      SymbolicExpressionTree tree = new SymbolicExpressionTree();
      var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
      var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
      rootNode.AddSubtree(startNode);
      tree.Root = rootNode;

      MapRandomIteratively(startNode, genotype, grammar,
                           genotype.Length, random);

      return tree;
    }
Esempio n. 25
0
        /// <summary>
        /// Maps a genotype (an integer vector) to a phenotype (a symbolic expression tree).
        /// Random approach.
        /// </summary>
        /// <param name="random">random number generator</param>
        /// <param name="bounds">only used for PIGEMapper (ignore here)</param>
        /// <param name="length">only used for PIGEMapper (ignore here)</param>
        /// <param name="grammar">grammar definition</param>
        /// <param name="genotype">integer vector, which should be mapped to a tree</param>
        /// <returns>phenotype (a symbolic expression tree)</returns>
        public override ISymbolicExpressionTree Map(IRandom random, IntMatrix bounds, int length,
                                                    ISymbolicExpressionGrammar grammar,
                                                    IntegerVector genotype)
        {
            SymbolicExpressionTree tree = new SymbolicExpressionTree();
            var rootNode  = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
            var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();

            rootNode.AddSubtree(startNode);
            tree.Root = rootNode;

            MapRandomIteratively(startNode, genotype, grammar,
                                 genotype.Length, random);

            return(tree);
        }
Esempio n. 26
0
        void bmm_64x64x64()
        {
            var Aup = Matrix.Alloc <N64, byte>();
            var Bup = Matrix.Alloc <N64, byte>();
            var Cup = Matrix.Alloc <N64, byte>();
            var A   = Random.BitMatrix64();
            var B   = Random.BitMatrix64();
            var C   = A * B;

            BitMatrix.unpack(A, ref Aup);
            BitMatrix.unpack(B, ref Bup);
            IntMatrix.mul(Aup, Bup, ref Cup);
            Cup.Apply(x => even(x) ? (byte)0 : (byte)1);
            Trace(C.Format());
            Trace(Cup.Format());
        }
Esempio n. 27
0
 private void CalcBtn_Click(object sender, EventArgs e)
 {
     try
     {
         int[,] Matrix = DataGridViewUtils.GridToArray2 <int>(InputGrid);
         IntMatrix intMatrix = new IntMatrix(Matrix);
         int[]     Arr       = intMatrix.GetArr();
         DataGridViewUtils.ArrayToGrid(OutputGrid, Arr);
         save.Enabled = true;
     }
     catch (Exception eror)
     {
         save.Enabled = false;
         MessageBox.Show(eror.Message, "ошибка");
     }
 }
Esempio n. 28
0
        public static Bitmap ToBitmap(IntMatrix i_Matrix, HausdorffMatchingResult.ColoringConvension ColoringFunction)
        {
            Bitmap retBitmap = new Bitmap(i_Matrix.ColumnsCount, i_Matrix.RowsCount);
            int    LocalMax  = DetermineMax(i_Matrix);
            //Logic for single cell
            Func <int, int, int, int> bitmapSet = (row, col, val) =>
            {
                retBitmap.SetPixel(col, row, ColoringFunction(val, LocalMax));
                return(val);
            };

            ///Applying logic for each cell
            i_Matrix.Iterate(bitmapSet);

            return(retBitmap);
        }
Esempio n. 29
0
        public void UniformOnePositionManipulatorApplyTest()
        {
            TestRandom    random = new TestRandom();
            IntegerVector parent, expected;
            IntMatrix     bounds = new IntMatrix(1, 2);

            // The following test is not based on published examples
            random.Reset();
            random.IntNumbers = new int[] { 3, 3 };
            parent            = new IntegerVector(new int[] { 2, 2, 3, 5, 1 });
            expected          = new IntegerVector(new int[] { 2, 2, 3, 3, 1 });
            bounds[0, 0]      = 2;
            bounds[0, 1]      = 7;
            UniformOnePositionManipulator.Apply(random, parent, bounds);
            Assert.IsTrue(Auxiliary.IntegerVectorIsEqualByPosition(expected, parent));
        }
Esempio n. 30
0
 public virtual void Randomize(IRandom random, int startIndex, int length, IntMatrix bounds)
 {
     if (length > 0)
     {
         for (int i = startIndex; i < startIndex + length; i++)
         {
             int min = bounds[i % bounds.Rows, 0], max = bounds[i % bounds.Rows, 1], step = 1;
             if (bounds.Columns > 2)
             {
                 step = bounds[i % bounds.Rows, 2];
             }
             int numbers = (int)Math.Floor((max - min) / (double)step);
             array[i] = random.Next(numbers) * step + min;
         }
         OnReset();
     }
 }
    /// <summary>
    /// Performs the arithmetic crossover on some positions by taking either x = alpha * p1 + (1 - alpha) * p2 or x = p1 depending on the probability for a gene to be crossed.
    /// </summary>
    /// <param name="random">The random number generator.</param>
    /// <param name="parent1">The first parent vector.</param>
    /// <param name="parent2">The second parent vector.</param>
    /// <param name="bounds">The bounds and step size for each dimension (will be cycled in case there are less rows than elements in the parent vectors).</param>
    /// <param name="alpha">The alpha parameter (<see cref="AlphaParameter"/>).</param>
    /// <param name="probability">The probability parameter (<see cref="ProbabilityParameter"/>).</param>
    /// <returns>The vector resulting from the crossover.</returns>
    public static IntegerVector Apply(IRandom random, IntegerVector parent1, IntegerVector parent2, IntMatrix bounds, DoubleValue alpha, DoubleValue probability) {
      int length = parent1.Length;
      if (length != parent2.Length) throw new ArgumentException("RoundedUniformArithmeticCrossover: The parent vectors are of different length.", "parent1");
      if (alpha.Value < 0 || alpha.Value > 1) throw new ArgumentException("RoundedUniformArithmeticCrossover: Parameter alpha must be in the range [0;1]", "alpha");
      if (probability.Value < 0 || probability.Value > 1) throw new ArgumentException("RoundedUniformArithmeticCrossover: Parameter probability must be in the range [0;1]", "probability");

      var result = new IntegerVector(length);
      for (int i = 0; i < length; i++) {
        if (random.NextDouble() < probability.Value) {
          int min = bounds[i % bounds.Rows, 0], max = bounds[i % bounds.Rows, 1], step = 1;
          if (bounds.Columns > 2) step = bounds[i % bounds.Rows, 2];
          max = FloorFeasible(min, max, step, max - 1);
          double value = alpha.Value * parent1[i] + (1 - alpha.Value) * parent2[i];
          result[i] = RoundFeasible(min, max, step, value);
        } else result[i] = parent1[i];
      }
      return result;
    }
    /// <summary>
    /// Perfomrs a heuristic crossover on the two given parents.
    /// </summary>
    /// <exception cref="ArgumentException">Thrown when two parents are not of the same length.</exception>
    /// <param name="random">The random number generator.</param>
    /// <param name="betterParent">The first parent for the crossover operation.</param>
    /// <param name="worseParent">The second parent for the crossover operation.</param>
    /// <param name="bounds">The bounds and step size for each dimension (will be cycled in case there are less rows than elements in the parent vectors).</param>
    /// <returns>The newly created integer vector, resulting from the heuristic crossover.</returns>
    public static IntegerVector Apply(IRandom random, IntegerVector betterParent, IntegerVector worseParent, IntMatrix bounds) {
      if (betterParent.Length != worseParent.Length)
        throw new ArgumentException("HeuristicCrossover: the two parents are not of the same length");

      int length = betterParent.Length;
      var result = new IntegerVector(length);
      double factor = random.NextDouble();

      int min, max, step = 1;
      for (int i = 0; i < length; i++) {
        min = bounds[i % bounds.Rows, 0];
        max = bounds[i % bounds.Rows, 1];
        if (bounds.Columns > 2) step = bounds[i % bounds.Rows, 2];
        max = FloorFeasible(min, max, step, max - 1);
        result[i] = RoundFeasible(min, max, step, betterParent[i] + factor * (betterParent[i] - worseParent[i]));
      }
      return result;
    }
    /// <summary>
    /// Performs a local crossover on the two given parent vectors.
    /// </summary>
    /// <exception cref="ArgumentException">Thrown when two parents are not of the same length.</exception>
    /// <param name="random">The random number generator.</param>
    /// <param name="parent1">The first parent for the crossover operation.</param>
    /// <param name="parent2">The second parent for the crossover operation.</param>
    /// <returns>The newly created integer vector, resulting from the local crossover.</returns>
    public static IntegerVector Apply(IRandom random, IntegerVector parent1, IntegerVector parent2, IntMatrix bounds) {
      if (parent1.Length != parent2.Length)
        throw new ArgumentException("RoundedLocalCrossover: the two parents are not of the same length");

      double factor;
      int length = parent1.Length;
      var result = new IntegerVector(length);

      int min, max, step = 1;
      for (int i = 0; i < length; i++) {
        min = bounds[i % bounds.Rows, 0];
        max = bounds[i % bounds.Rows, 1];
        if (bounds.Columns > 2) step = bounds[i % bounds.Rows, 2];
        max = FloorFeasible(min, max, step, max - 1);
        factor = random.NextDouble();
        result[i] = RoundFeasible(min, max, step, (factor * parent1[i]) + ((1 - factor) * parent2[i]));
      }
      return result;
    }
Esempio n. 34
0
        public override void Start(CancellationToken cancellationToken)
        {
            if (ExecutionState == ExecutionState.Prepared)
            {
                int       dim             = Problem.Weights.Rows;
                IntMatrix shortTermMemory = new IntMatrix(dim, dim);
                for (int i = 0; i < dim; i++)
                {
                    for (int j = 0; j < dim; j++)
                    {
                        shortTermMemory[i, j] = -(dim * (i + 1) + j + 1);
                    }
                }

                GlobalScope.Variables.Add(new Variable("ShortTermMemory", shortTermMemory));
                GlobalScope.Variables.Add(new Variable("MoveQualityMatrix", new DoubleMatrix(dim, dim)));
            }
            base.Start(cancellationToken);
        }
Esempio n. 35
0
    static void Main()
    {
        var(n, qc) = Read2();
        var qs = Array.ConvertAll(new bool[qc], _ => Console.ReadLine().Split());

        var d = ((decimal)n - 1) / 2;

        var r90  = new IntMatrix(new[] { new[] { 0L, -1 }, new[] { 1, 0L } });
        var r90_ = new IntMatrix(new[] { new[] { 0L, 1 }, new[] { -1, 0L } });

        var rx = new IntMatrix(new[] { new[] { -1, 0L }, new[] { 0L, 1 } });
        var ry = new IntMatrix(new[] { new[] { 1, 0L }, new[] { 0L, -1 } });

        var a = new Dictionary <(decimal, decimal), int>();

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                a[(i - d, j - d)] = 0;
Esempio n. 36
0
        public IntegerVectorEncoding(string name, int length, IList <int> min, IList <int> max, IList <int> step = null)
            : base(name)
        {
            if (min.Count == 0)
            {
                throw new ArgumentException("Bounds must be given for the integer parameters.");
            }
            if (min.Count != max.Count)
            {
                throw new ArgumentException("min must be of the same length as max", "min");
            }
            if (step != null && min.Count != step.Count)
            {
                throw new ArgumentException("step must be of the same length as min or null", "step");
            }
            if (min.Zip(max, (mi, ma) => mi >= ma).Any(x => x))
            {
                throw new ArgumentException("min must be less than max in each dimension", "min");
            }

            var bounds = new IntMatrix(min.Count, step != null ? 3 : 2);

            for (int i = 0; i < min.Count; i++)
            {
                bounds[i, 0] = min[i];
                bounds[i, 1] = max[i];
                if (step != null)
                {
                    bounds[i, 2] = step[i];
                }
            }

            lengthParameter = new FixedValueParameter <IntValue>(Name + ".Length", new IntValue(length));
            boundsParameter = new ValueParameter <IntMatrix>(Name + ".Bounds", bounds);
            Parameters.Add(lengthParameter);
            Parameters.Add(boundsParameter);

            SolutionCreator = new UniformRandomIntegerVectorCreator();
            RegisterParameterEvents();
            DiscoverOperators();
        }
        /// <summary>
        /// Changes randomly several, but at least one, positions in the given integer <paramref name="vector"/>, according to the given probabilities.
        /// </summary>
        /// <param name="random">A random number generator.</param>
        /// <param name="vector">The integer vector to manipulate.</param>
        /// <param name="bounds"> Contains the minimum value (inclusive), maximum value (exclusive), and step size of the sampling range for
        /// the vector element to change.</param>
        /// <param name="probability">The probability for each dimension to be manipulated..</param>
        public static void Apply(IRandom random, IntegerVector vector, IntMatrix bounds, double probability)
        {
            if (bounds == null || bounds.Rows == 0 || bounds.Columns < 2)
            {
                throw new ArgumentException("UniformSomePositionsManipulator: Invalid bounds specified", "bounds");
            }
            bool atLeastOneManipulated = false;

            for (int index = 0; index < vector.Length; index++)
            {
                if (random.NextDouble() < probability)
                {
                    atLeastOneManipulated = true;
                    UniformOnePositionManipulator.Manipulate(random, vector, bounds, index);
                }
            }

            if (!atLeastOneManipulated)
            {
                UniformOnePositionManipulator.Manipulate(random, vector, bounds, random.Next(vector.Length));
            }
        }
Esempio n. 38
0
        public GraphColoringProblem()
        {
            Encoding = new LinearLinkageEncoding("lle");
            Parameters.Add(adjacencyListParameter   = new ValueParameter <IntMatrix>("Adjacency List", "The adjacency list that describes the (symmetric) edges in the graph with nodes from 0 to N-1."));
            Parameters.Add(fitnessFunctionParameter = new ValueParameter <EnumValue <FitnessFunction> >("Fitness Function", "The function to use for evaluating the quality of a solution.", new EnumValue <FitnessFunction>(FitnessFunction.Penalized)));
            Parameters.Add(bestKnownColorsParameter = new OptionalValueParameter <IntValue>("BestKnownColors", "The least amount of colors in a valid coloring."));

            var imat = new IntMatrix(defaultInstance.Length, 2);

            for (var i = 0; i < defaultInstance.Length; i++)
            {
                imat[i, 0] = defaultInstance[i].Item1 - 1;
                imat[i, 1] = defaultInstance[i].Item2 - 1;
            }
            Encoding.Length = defaultInstanceNodes;
            AdjacencyListParameter.Value    = imat;
            BestKnownQualityParameter.Value = null;
            BestKnownColorsParameter.Value  = new IntValue(defaultInstanceBestColors);

            InitializeOperators();
            RegisterEventHandlers();
        }
        private Queue <Point> binaryToQueue(IntMatrix i_Surface)
        {
            Queue <Point>             retQueue     = new Queue <Point>();
            Func <int, int, int, int> onesToPoints = (row, col, val) =>
            {
                if (val == 1)
                {
                    retQueue.Enqueue(new Point(col, row));
                    return(val);
                }
                else if (val == 0)
                {
                    return(0);
                }

                throw new HausdorffMatchingException("A non binary value found in a binary matrix!!! Non binary values are not allowed!");
            };

            i_Surface.Iterate(onesToPoints);

            return(retQueue);
        }
Esempio n. 40
0
        private static HashSet <SubMatrix> IntializeCover(IntMatrix invertedAdjacency)
        {
            var cover = new HashSet <SubMatrix>();

            for (int i = 0; i < invertedAdjacency.Height; i++)
            {
                var subMatrix = new SubMatrix();

                for (int j = 0; j < invertedAdjacency.Width; j++)
                {
                    if (invertedAdjacency[i, j] == 1)
                    {
                        subMatrix.columnIndices.Add(j);
                    }
                }

                if (subMatrix.columnIndices.Count > 0)
                {
                    subMatrix.rowIndices.Add(i);
                    cover.Add(subMatrix);
                }
            }
            return(cover);
        }
Esempio n. 41
0
        /// <summary>
        /// Maps a genotype (an integer vector) to a phenotype (a symbolic expression tree).
        /// PIGE approach.
        /// </summary>
        /// <param name="random">random number generator</param>
        /// <param name="bounds">integer number range for genomes (codons) of the nont vector</param>
        /// <param name="length">length of the nont vector to create</param>
        /// <param name="grammar">grammar definition</param>
        /// <param name="genotype">integer vector, which should be mapped to a tree</param>
        /// <returns>phenotype (a symbolic expression tree)</returns>
        public override ISymbolicExpressionTree Map(IRandom random, IntMatrix bounds, int length,
                                                    ISymbolicExpressionGrammar grammar,
                                                    IntegerVector genotype)
        {
            SymbolicExpressionTree tree = new SymbolicExpressionTree();
            var rootNode  = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
            var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();

            rootNode.AddSubtree(startNode);
            tree.Root = rootNode;

            // Map can be called simultaniously on multiple threads
            lock (nontVectorLocker) {
                if (NontVector == null)
                {
                    NontVector = GetNontVector(random, bounds, length);
                }
            }

            MapPIGEIteratively(startNode, genotype, grammar,
                               genotype.Length, random);

            return(tree);
        }
Esempio n. 42
0
        /// <summary>
        /// Maps a genotype (an integer vector) to a phenotype (a symbolic expression tree).
        /// Depth-first approach.
        /// </summary>
        /// <param name="random">random number generator</param>
        /// <param name="bounds">only used for PIGEMapper (ignore here)</param>
        /// <param name="length">only used for PIGEMapper (ignore here)</param>
        /// <param name="grammar">grammar definition</param>
        /// <param name="genotype">integer vector, which should be mapped to a tree</param>
        /// <returns>phenotype (a symbolic expression tree)</returns>
        public override SymbolicExpressionTree Map(IRandom random, IntMatrix bounds, int length,
                                                   ISymbolicExpressionGrammar grammar,
                                                   IntegerVector genotype)
        {
            SymbolicExpressionTree tree = new SymbolicExpressionTree();
            var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();

            if (rootNode.HasLocalParameters)
            {
                rootNode.ResetLocalParameters(random);
            }
            var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();

            if (startNode.HasLocalParameters)
            {
                startNode.ResetLocalParameters(random);
            }
            rootNode.AddSubtree(startNode);
            tree.Root = rootNode;

            MapDepthFirstIteratively(startNode, genotype, grammar,
                                     genotype.Length, random);
            return(tree);
        }
    /// <summary>
    /// Performs an average crossover of the two given parent integer vectors.
    /// The average is rounded and mapped to the nearest valid value (e.g. if step size is > 1)
    /// </summary>
    /// <param name="random">A random number generator.</param>
    /// <param name="parents">The parents for crossover.</param>
    /// <param name="bounds">The bounds matrix that contains for each dimension one row with minimum (inclusive), maximum (exclusive), and step size columns.
    /// If the number of rows is smaller than the number of dimensions the matrix is cycled.</param>
    /// <returns>The newly created integer vector, resulting from the single point crossover.</returns>
    public static IntegerVector Apply(IRandom random, ItemArray<IntegerVector> parents, IntMatrix bounds) {
      int length = parents[0].Length, parentsCount = parents.Length;
      if (parents.Length < 2) throw new ArgumentException("RoundedAverageCrossover: The number of parents is less than 2.", "parents");
      if (bounds == null || bounds.Rows < 1 || bounds.Columns < 2) throw new ArgumentException("AverageCrossover: Invalid bounds specified.", "bounds");

      var result = new IntegerVector(length);
      try {
        double avg;
        for (int i = 0; i < length; i++) {
          avg = 0;
          for (int j = 0; j < parentsCount; j++)
            avg += parents[j][i];
          avg /= parentsCount;
          int min = bounds[i % bounds.Rows, 0], max = bounds[i % bounds.Rows, 1], step = 1;
          if (bounds.Columns > 2) step = bounds[i % bounds.Rows, 2];
          max = FloorFeasible(min, max, step, max - 1);
          result[i] = RoundFeasible(min, max, step, avg);
        }
      } catch (IndexOutOfRangeException) {
        throw new ArgumentException("RoundedAverageCrossover: The parents' vectors are of different length.", "parents");
      }

      return result;
    }
 /// <summary>
 /// Changes randomly several, but at least one, positions in the given integer <paramref name="vector"/>.
 /// </summary>
 /// <remarks>Calls <see cref="Apply"/>.</remarks>
 /// <param name="random">A random number generator.</param>
 /// <param name="vector">The integer vector to manipulate.</param>
 protected override void ManipulateBounded(IRandom random, IntegerVector vector, IntMatrix bounds) {
   Apply(random, vector, bounds, ProbabilityParameter.ActualValue.Value);
 }
 /// <summary>
 /// Performs an average crossover between two parent integer vectors.
 /// </summary>
 /// <exception cref="ArgumentException">Thrown if there are not exactly two parents.</exception>
 /// <param name="random">A random number generator.</param>
 /// <param name="parents">An array containing the two integer vectors that should be crossed.</param>
 /// <param name="bounds">The bounds and step size for each dimension (will be cycled in case there are less rows than elements in the parent vectors).</param>
 /// <returns>The newly created integer vector, resulting from the average crossover.</returns>
 protected override IntegerVector CrossBounded(IRandom random, ItemArray<IntegerVector> parents, IntMatrix bounds) {
   return Apply(random, parents, bounds);
 }
        private IntMatrix CalcDistanceMatrix(IntMatrix i_BinaryMatrix)
        {
            IntMatrix retHausdorffMatrix = new IntMatrix(i_BinaryMatrix.RowsCount,i_BinaryMatrix.ColumnsCount);

            InitDistances(ref retHausdorffMatrix,i_BinaryMatrix);
            Queue<Point> pointQueue = binaryToQueue(i_BinaryMatrix);

            int minVal = 0;
            int currPointValue = 0;
            Point currPoint;
            int RowsCount = retHausdorffMatrix.RowsCount;
            int ColsCount = retHausdorffMatrix.ColumnsCount;
            Point surrounder;

            while (pointQueue.Count != 0)
            {
                currPoint = pointQueue.Dequeue();
                currPointValue = retHausdorffMatrix[currPoint];
                ++currPointValue;

                ///walking clockwise as shown:
                /// 2 |     3     | 4
                ///-------------------
                /// 1 | currPoint | 5
                ///-------------------
                /// 8 |     7     | 6
                ///

                /// 1st location
                surrounder = currPoint;
                --surrounder.X;

                if (surrounder.X >= 0)
                {
                    if (currPointValue < retHausdorffMatrix[surrounder])
                    {
                        pointQueue.Enqueue(surrounder);
                    }

                    minVal = Math.Min(currPointValue, retHausdorffMatrix[surrounder]);
                    retHausdorffMatrix[surrounder] = minVal;
                }
                /// 2nd location
                ++surrounder.Y;
                if (surrounder.X >= 0 && surrounder.Y < RowsCount)
                {
                    if (currPointValue < retHausdorffMatrix[surrounder])
                    {
                        pointQueue.Enqueue(surrounder);
                    }

                    minVal = Math.Min(currPointValue, retHausdorffMatrix[surrounder]);
                    retHausdorffMatrix[surrounder] = minVal;
                }
                ///3rd location
                ++surrounder.X;
                if (surrounder.Y < RowsCount)
                {
                    if (currPointValue < retHausdorffMatrix[surrounder])
                    {
                        pointQueue.Enqueue(surrounder);
                    }

                    minVal = Math.Min(currPointValue, retHausdorffMatrix[surrounder]);
                    retHausdorffMatrix[surrounder] = minVal;
                }
                ///4th location
                ++surrounder.X;
                if (surrounder.Y < RowsCount && surrounder.X < ColsCount)
                {
                    if (currPointValue < retHausdorffMatrix[surrounder])
                    {
                        pointQueue.Enqueue(surrounder);
                    }

                    minVal = Math.Min(currPointValue, retHausdorffMatrix[surrounder]);
                    retHausdorffMatrix[surrounder] = minVal;
                }
                ///5th location
                --surrounder.Y;
                if (surrounder.X < ColsCount)
                {
                    if (currPointValue < retHausdorffMatrix[surrounder])
                    {
                        pointQueue.Enqueue(surrounder);
                    }

                    minVal = Math.Min(currPointValue, retHausdorffMatrix[surrounder]);
                    retHausdorffMatrix[surrounder] = minVal;
                }
                ///6th location
                --surrounder.Y;
                if (surrounder.X < ColsCount && surrounder.Y >= 0)
                {
                    if (currPointValue < retHausdorffMatrix[surrounder])
                    {
                        pointQueue.Enqueue(surrounder);
                    }

                    minVal = Math.Min(currPointValue, retHausdorffMatrix[surrounder]);
                    retHausdorffMatrix[surrounder] = minVal;
                }
                ///7th location
                --surrounder.X;
                if (surrounder.Y >= 0)
                {
                    if (currPointValue < retHausdorffMatrix[surrounder])
                    {
                        pointQueue.Enqueue(surrounder);
                    }

                    minVal = Math.Min(currPointValue, retHausdorffMatrix[surrounder]);
                    retHausdorffMatrix[surrounder] = minVal;
                }
                ///8th location
                --surrounder.X;
                if (surrounder.Y >= 0 && surrounder.X >= 0)
                {
                    if (currPointValue < retHausdorffMatrix[surrounder])
                    {
                        pointQueue.Enqueue(surrounder);
                    }

                    minVal = Math.Min(currPointValue, retHausdorffMatrix[surrounder]);
                    retHausdorffMatrix[surrounder] = minVal;
                }
            }

            return retHausdorffMatrix;
        }
Esempio n. 47
0
 public void Randomize(IRandom random, IntMatrix bounds) {
   Randomize(random, 0, Length, bounds);
 }
Esempio n. 48
0
    public override void Start() {
      if (ExecutionState == ExecutionState.Prepared) {
        int dim = Problem.Weights.Rows;
        IntMatrix shortTermMemory = new IntMatrix(dim, dim);
        for (int i = 0; i < dim; i++)
          for (int j = 0; j < dim; j++) {
            shortTermMemory[i, j] = -(dim * (i + 1) + j + 1);
          }

        GlobalScope.Variables.Add(new Variable("ShortTermMemory", shortTermMemory));
        GlobalScope.Variables.Add(new Variable("MoveQualityMatrix", new DoubleMatrix(dim, dim)));
      }
      base.Start();
    }
Esempio n. 49
0
    /// <summary>
    /// Maps a genotype (an integer vector) to a phenotype (a symbolic expression tree).
    /// PIGE approach.
    /// </summary>
    /// <param name="random">random number generator</param>
    /// <param name="bounds">integer number range for genomes (codons) of the nont vector</param>
    /// <param name="length">length of the nont vector to create</param>
    /// <param name="grammar">grammar definition</param>
    /// <param name="genotype">integer vector, which should be mapped to a tree</param>
    /// <returns>phenotype (a symbolic expression tree)</returns>
    public override ISymbolicExpressionTree Map(IRandom random, IntMatrix bounds, int length,
                                               ISymbolicExpressionGrammar grammar,
                                               IntegerVector genotype) {

      SymbolicExpressionTree tree = new SymbolicExpressionTree();
      var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
      var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
      rootNode.AddSubtree(startNode);
      tree.Root = rootNode;

      // Map can be called simultaniously on multiple threads
      lock (nontVectorLocker) {
        if (NontVector == null) {
          NontVector = GetNontVector(random, bounds, length);
        }
      }

      MapPIGEIteratively(startNode, genotype, grammar,
                         genotype.Length, random);

      return tree;
    }
        private void InitDistances(ref IntMatrix o_DistMatrix, IntMatrix i_BinaryMapBase)
        {
            Func<int, int, int, int> ToDifferentSizedCopy = (row, col, val) =>
            {///Building a logic for one cell
                if (row <= i_BinaryMapBase.RowsCount && col <= i_BinaryMapBase.ColumnsCount)
                {
                    int baseVale = i_BinaryMapBase[row, col];
                    if (baseVale == 1)
                    {
                        return 0;
                    }
                    else if (baseVale == 0)
                    {
                        return Int16.MaxValue;
                    }
                    else
                    {
                        throw new HausdorffMatchingException("A non binary value found in a binary matrix!!! Non binary values are not allowed!");
                    }
                }
                else
                {
                    return 0;
                }
            };

            ///Apllying the logic for whole matrix
            o_DistMatrix.Iterate(ToDifferentSizedCopy);
        }
 protected abstract void ManipulateBounded(IRandom random, IntegerVector integerVector, IntMatrix bounds);
    /// <summary>
    /// Checks if the number of parents is equal to 2, if all parameters are available and forwards the call to <see cref="Apply(IRandom, IntegerVector, IntegerVector, IntMatrix, DoubleValue, DoubleValue)"/>.
    /// </summary>
    /// <exception cref="ArgumentException">Thrown when the number of parents is not equal to 2.</exception>
    /// <exception cref="InvalidOperationException">
    /// Thrown when either:<br/>
    /// <list type="bullet">
    /// <item><description>Maximization parameter could not be found.</description></item>
    /// <item><description>Quality parameter could not be found or the number of quality values is not equal to the number of parents.</description></item>
    /// <item><description>Alpha parameter could not be found.</description></item>
    /// <item><description>Beta parameter could not be found.</description></item>
    /// </list>
    /// </exception>
    /// <param name="random">The random number generator to use.</param>
    /// <param name="parents">The collection of parents (must be of size 2).</param>
    /// <param name="bounds">The bounds and step size for each dimension (will be cycled in case there are less rows than elements in the parent vectors).</param>
    /// <returns>The integer vector that results from the crossover.</returns>
    protected override IntegerVector CrossBounded(IRandom random, ItemArray<IntegerVector> parents, IntMatrix bounds) {
      if (parents.Length != 2) throw new ArgumentException("RoundedBlendAlphaBetaCrossover: Number of parents is not equal to 2.", "parents");
      if (MaximizationParameter.ActualValue == null) throw new InvalidOperationException("RoundedBlendAlphaBetaCrossover: Parameter " + MaximizationParameter.ActualName + " could not be found.");
      if (QualityParameter.ActualValue == null || QualityParameter.ActualValue.Length != parents.Length) throw new InvalidOperationException("RoundedBlendAlphaBetaCrossover: Parameter " + QualityParameter.ActualName + " could not be found, or not in the same quantity as there are parents.");
      if (AlphaParameter.ActualValue == null || BetaParameter.ActualValue == null) throw new InvalidOperationException("RoundedBlendAlphaBetaCrossover: Parameter " + AlphaParameter.ActualName + " or paramter " + BetaParameter.ActualName + " could not be found.");

      ItemArray<DoubleValue> qualities = QualityParameter.ActualValue;
      bool maximization = MaximizationParameter.ActualValue.Value;
      if (maximization && qualities[0].Value >= qualities[1].Value || !maximization && qualities[0].Value <= qualities[1].Value)
        return Apply(random, parents[0], parents[1], bounds, AlphaParameter.ActualValue, BetaParameter.ActualValue);
      else {
        return Apply(random, parents[1], parents[0], bounds, AlphaParameter.ActualValue, BetaParameter.ActualValue);
      }
    }
    /// <summary>
    /// Performs the rounded blend alpha beta crossover (BLX-a-b) on two parent vectors.
    /// </summary>
    /// <exception cref="ArgumentException">
    /// Thrown when either:<br/>
    /// <list type="bullet">
    /// <item><description>The length of <paramref name="betterParent"/> and <paramref name="worseParent"/> is not equal.</description></item>
    /// <item><description>The parameter <paramref name="alpha"/> is smaller than 0.</description></item>
    /// <item><description>The parameter <paramref name="beta"/> is smaller than 0.</description></item>
    /// </list>
    /// </exception>
    /// <param name="random">The random number generator to use.</param>
    /// <param name="betterParent">The better of the two parents with regard to their fitness.</param>
    /// <param name="worseParent">The worse of the two parents with regard to their fitness.</param>
    /// <param name="bounds">The bounds and step size for each dimension (will be cycled in case there are less rows than elements in the parent vectors).</param>
    /// <param name="alpha">The parameter alpha.</param>
    /// <param name="beta">The parameter beta.</param>
    /// <returns>The integer vector that results from the crossover.</returns>
    public static IntegerVector Apply(IRandom random, IntegerVector betterParent, IntegerVector worseParent, IntMatrix bounds, DoubleValue alpha, DoubleValue beta) {
      if (betterParent.Length != worseParent.Length) throw new ArgumentException("RoundedBlendAlphaBetaCrossover: The parents' vectors are of different length.", "betterParent");
      if (alpha.Value < 0) throw new ArgumentException("RoundedBlendAlphaBetaCrossover: Parameter alpha must be greater or equal to 0.", "alpha");
      if (beta.Value < 0) throw new ArgumentException("RoundedBlendAlphaBetaCrossover: Parameter beta must be greater or equal to 0.", "beta");
      if (bounds == null || bounds.Rows < 1 || bounds.Columns < 2) throw new ArgumentException("RoundedBlendAlphaBetaCrossover: Invalid bounds specified.", "bounds");

      int length = betterParent.Length;
      double min, max, d;
      var result = new IntegerVector(length);
      int minBound, maxBound, step = 1;
      for (int i = 0; i < length; i++) {
        minBound = bounds[i % bounds.Rows, 0];
        maxBound = bounds[i % bounds.Rows, 1];
        if (bounds.Columns > 2) step = bounds[i % bounds.Rows, 2];
        maxBound = FloorFeasible(minBound, maxBound, step, maxBound - 1);

        d = Math.Abs(betterParent[i] - worseParent[i]);
        if (betterParent[i] <= worseParent[i]) {
          min = FloorFeasible(minBound, maxBound, step, betterParent[i] - d * alpha.Value);
          max = CeilingFeasible(minBound, maxBound, step, worseParent[i] + d * beta.Value);
        } else {
          min = FloorFeasible(minBound, maxBound, step, worseParent[i] - d * beta.Value);
          max = CeilingFeasible(minBound, maxBound, step, betterParent[i] + d * alpha.Value);
        }
        result[i] = RoundFeasible(minBound, maxBound, step, min + random.NextDouble() * (max - min));
      }
      return result;
    }
Esempio n. 54
0
 private static IntegerVector GetNontVector(IRandom random, IntMatrix bounds, int length) {
   IntegerVector v = new IntegerVector(length);
   v.Randomize(random, bounds);
   return v;
 }
 /// <summary>
 /// Checks that the number of parents is equal to 2 and forwards the call to <see cref="Apply(IRandom, RealVector, RealVector, DoubleValue)"/>.
 /// </summary>
 /// <exception cref="ArgumentException">Thrown when the number of parents is not equal to 2.</exception>
 /// <exception cref="InvalidOperationException">Thrown when the parameter alpha could not be found.</exception>
 /// <param name="random">The random number generator to use.</param>
 /// <param name="parents">The collection of parents (must be of size 2).</param>
 /// <param name="bounds">The bounds and step size for each dimension (will be cycled in case there are less rows than elements in the parent vectors).</param>
 /// <returns>The integer vector resulting from the crossover operation.</returns>
 protected override IntegerVector CrossBounded(IRandom random, ItemArray<IntegerVector> parents, IntMatrix bounds) {
   if (parents.Length != 2) throw new ArgumentException("RoundedBlendAlphaCrossover: The number of parents is not equal to 2", "parents");
   if (AlphaParameter.ActualValue == null) throw new InvalidOperationException("RoundedBlendAlphaCrossover: Parameter " + AlphaParameter.ActualName + " could not be found.");
   return Apply(random, parents[0], parents[1], bounds, AlphaParameter.ActualValue);
 }
 protected abstract IntegerVector CrossBounded(IRandom random, ItemArray<IntegerVector> parents, IntMatrix bounds);
 protected abstract IntegerVector Create(IRandom random, IntValue length, IntMatrix bounds);
 public HausdorffMatching(IntMatrix i_BinaryMap1, IntMatrix i_BinaryMap2)
 {
     m_BinaryMap1 = i_BinaryMap1;
     m_BinaryMap2 = i_BinaryMap2;
 }
 /// <summary>
 /// Performs a local crossover operation for two given parent integer vectors.
 /// </summary>
 /// <exception cref="ArgumentException">Thrown if there are not exactly two parents.</exception>
 /// <param name="random">A random number generator.</param>
 /// <param name="parents">An array containing the two real vectors that should be crossed.</param>
 /// <param name="bounds">The bounds and step size for each dimension (will be cycled in case there are less rows than elements in the parent vectors).</param>
 /// <returns>The newly created integer vector, resulting from the crossover operation.</returns>
 protected override IntegerVector CrossBounded(IRandom random, ItemArray<IntegerVector> parents, IntMatrix bounds) {
   if (parents.Length != 2) throw new ArgumentException("RoundedLocalCrossover: The number of parents is not equal to 2");
   return Apply(random, parents[0], parents[1], bounds);
 }
 public abstract SymbolicExpressionTree Map(IRandom random, IntMatrix bounds, int length,
                                            ISymbolicExpressionGrammar grammar,
                                            IntegerVector genotype);