File size: 10,298 Bytes
b1b3bae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/// ------------------------------------------------------
/// SwarmOps - Numeric and heuristic optimization for C#
/// Copyright (C) 2003-2011 Magnus Erik Hvass Pedersen.
/// Please see the file license.txt for license details.
/// SwarmOps on the internet: http://www.Hvass-Labs.org/
/// ------------------------------------------------------

using System.Diagnostics;

namespace SwarmOps.Optimizers
{
    /// <summary>
    /// Optimizer that iterates over all possible combinations
    /// of parameters fitting a mesh of a certain size. This is
    /// particularly useful for displaying performance
    /// landscapes from meta-optimization, relating choices of
    /// control parameters to the performance of the optimizer.
    /// </summary>
    public class MESH : Optimizer
    {
        #region Constructors.
        /// <summary>
        /// Construct the object.
        /// </summary>
        public MESH()

            : base()
        {
        }

        /// <summary>
        /// Construct the object.
        /// </summary>
        /// <param name="mask">Fix certain parameters or leave null.</param>
        /// <param name="problem">Problem to optimize.</param>
        public MESH(double?[] mask, Problem problem)

            : base(problem)
        {
            Debug.Assert(mask == null || mask.Length == problem.Dimensionality);

            Mask = mask;
        }
        #endregion

        #region Get control parameters.
        /// <summary>
        /// Get parameter, Number of iterations per dimension.
        /// </summary>
        /// <param name="parameters">Optimizer parameters.</param>
        public int GetNumIterationsPerDim(double[] parameters)
        {
            return (int)System.Math.Round(parameters[0], System.MidpointRounding.AwayFromZero);
        }
        #endregion

        #region Base-class overrides, Problem.
        /// <summary>
        /// Name of the optimizer.
        /// </summary>
        public override string Name
        {
            get { return "MESH"; }
        }

        /// <summary>
        /// Number of control parameters for optimizer.
        /// </summary>
        public override int Dimensionality
        {
            get { return 1; }
        }

        string[] _parameterName = { "NumIterationsPerDim" };

        /// <summary>
        /// Control parameter names.
        /// </summary>
        public override string[] ParameterName
        {
            get { return _parameterName; }
        }

        static readonly double[] _defaultParameters = { 8.0 };

        /// <summary>
        /// Default control parameters.
        /// </summary>
        public override double[] DefaultParameters
        {
            get { return _defaultParameters; }
        }

        static readonly double[] _lowerBound = { 1 };

        /// <summary>
        /// Lower search-space boundary for control parameters.
        /// </summary>
        public override double[] LowerBound
        {
            get { return _lowerBound; }
        }

        static readonly double[] _upperBound = { 1000.0 };

        /// <summary>
        /// Upper search-space boundary for control parameters.
        /// </summary>
        public override double[] UpperBound
        {
            get { return _upperBound; }
        }
        #endregion

        #region Base-class overrides, Optimizer.
        /// <summary>
        /// Perform one optimization run and return the best found solution.
        /// </summary>
        /// <param name="parameters">Control parameters for the optimizer.</param>
        public override Result Optimize(double[] parameters)
        {
            Debug.Assert(parameters != null && parameters.Length == Dimensionality);

            // Signal beginning of optimization run.
            Problem.BeginOptimizationRun();

            // Retrieve parameter specific to this optimizer.
            int numIterationsPerDim = GetNumIterationsPerDim(parameters);

            Debug.Assert(numIterationsPerDim >= 1);

            // Get problem-context.
            double[] lowerBound = Problem.LowerBound;
            double[] upperBound = Problem.UpperBound;
            int n = Problem.Dimensionality;

            // Allocate mesh position and mesh-incremental values.
            double[] x = new double[n];					// Mesh position.
            double[] delta = new double[n];				// Mesh incremental values.
            double[] g = new double[n];					// Best found position for this run.
            double gFitness = Problem.MaxFitness;		// Fitness for best found position.
            bool gFeasible = false;                     // Feasibility for best found position.

            // Initialize mesh position to the lower boundary.
            LowerBound.CopyTo(x, 0);

            // Compute mesh incremental values for all dimensions.
            for (int i = 0; i < n; i++)
            {
                delta[i] = (upperBound[i] - lowerBound[i]) / (numIterationsPerDim - 1);
            }

            // Start recursive traversal of mesh.
            Recursive(0, numIterationsPerDim, delta, ref x, ref g, ref gFitness, ref gFeasible);

            // Signal end of optimization run.
            Problem.EndOptimizationRun();

            // Return best-found solution and fitness.
            return new Result(g, gFitness, gFeasible, (int)System.Math.Pow(numIterationsPerDim, n));
        }
        #endregion

        #region Protected methods.
        /// <summary>
        /// Fix certain parameters or leave null.
        /// </summary>
        double?[] Mask;

        /// <summary>
        /// Helper function for recursive traversal of the mesh in a depth-first order.
        /// </summary>
        /// <param name="curDim">Current dimension being processed.</param>
        /// <param name="numIterationsPerDim">Number of mesh iterations per dimension.</param>
        /// <param name="delta">Distance between points in mesh.</param>
        /// <param name="x">Current mesh point.</param>
        /// <param name="g">Best found point in mesh.</param>
        /// <param name="gFitness">Fitness of best found point.</param>
        /// <param name="gFeasible">Feasibility of best found point.</param>
        void Recursive(

            int curDim,

            int numIterationsPerDim,

            double[] delta,

            ref double[] x,

            ref double[] g,

            ref double gFitness,

            ref bool gFeasible)
        {
            // Get problem-context.
            double[] lowerBound = Problem.LowerBound;
            double[] upperBound = Problem.UpperBound;
            int n = Problem.Dimensionality;

            Debug.Assert(curDim >= 0 && curDim < n);

            // Should parameters be mesh-computed?
            if (Mask == null || Mask[curDim] == null)
            {
                // Iterate over all mesh-entries for current dimension.
                int i;
                for (i = 0; i < numIterationsPerDim; i++)
                {
                    // Update mesh position for current dimension.
                    x[curDim] = lowerBound[curDim] + delta[curDim] * i;

                    // Bound mesh position for current dimension.
                    x[curDim] = Tools.Bound(x[curDim], lowerBound[curDim], upperBound[curDim]);

                    // Do actual recursion or fitness evaluation.
                    RecursiveInner(curDim, numIterationsPerDim, delta, ref x, ref g, ref gFitness, ref gFeasible);
                }
            }
            else
            {
                // Use fixed parameter instead of mesh-computed.
                x[curDim] = Mask[curDim].Value;

                // Do actual recursion or fitness evaluation.
                RecursiveInner(curDim, numIterationsPerDim, delta, ref x, ref g, ref gFitness, ref gFeasible);
            }
        }
 
        /// <summary>
        /// Helper function for recursive traversal of the mesh in a depth-first order.
        /// </summary>
        /// <param name="curDim">Current dimension being processed.</param>
        /// <param name="numIterationsPerDim">Number of mesh iterations per dimension.</param>
        /// <param name="delta">Distance between points in mesh.</param>
        /// <param name="x">Current mesh point.</param>
        /// <param name="g">Best found point in mesh.</param>
        /// <param name="gFitness">Fitness of best found point.</param>
        /// <param name="gFeasible">Feasibility of best found point.</param>
        void RecursiveInner(

            int curDim,

            int numIterationsPerDim,

            double[] delta,

            ref double[] x,

            ref double[] g,

            ref double gFitness,

            ref bool gFeasible)
        {
            int n = Problem.Dimensionality;

            Debug.Assert(curDim >= 0 && curDim < n);

            // Either recurse or compute fitness for mesh position.
            if (curDim < n - 1)
            {
                // Recurse for next dimension.
                Recursive(curDim + 1, numIterationsPerDim, delta, ref x, ref g, ref gFitness, ref gFeasible);
            }
            else
            {
                // Compute feasibility (constraint satisfaction).
                bool feasible = Problem.Feasible(x);

                // Compute fitness for current mesh position.
                // This is done regardless of feasibility.
                double fitness = Problem.Fitness(x, feasible);

                // Update best position and fitness found in this run.
                if (Tools.BetterFeasibleFitness(gFeasible, feasible, gFitness, fitness))
                {
                    // Update this run's best known position.
                    x.CopyTo(g, 0);

                    // Update this run's best know fitness.
                    gFitness = fitness;

                    // Update best known feasibility.
                    gFeasible = feasible;
                }
            }
        }
        #endregion
    }
}