예제 #1
0
        public static void Main(string[] args)
        {
            /*
             * The context of this tutorial is that you have an existing time stepping simulation
             * model.
             */
            IClonableObjectiveEvaluator <IHyperCube <double> > evaluator;
            IEvolutionEngine <IHyperCube <double> >            uniformRandomSampling;


            var simulation = SimulationFactory.CreateAwbmSimulation();
            var data       = DataHandling.GetSampleClimate();

            SimulationFactory.SetSampleSimulation(simulation, data);
            int from = simulation.GetStart();
            int to   = simulation.GetEnd();

            evaluator = BuildUrsEvaluator(simulation, data.Runoff, from, to);

            var paramSpace = CreateFeasibleAwbmParameterSpace(simulation);

            uniformRandomSampling = new UniformRandomSampling <IHyperCube <double> >(evaluator, new BasicRngFactory(0), paramSpace, 3000);
            var ursResults = uniformRandomSampling.Evolve();

            Console.WriteLine(MetaheuristicsHelper.GetHumanReadable(ursResults));
        }
예제 #2
0
        static void Main(string[] args)
        {
            /*
             * This program primarily demonstrates how to wrap and calibrate a model written
             * in a native language. While technological aspects of what it demonstrates
             * are not inherently limited nor specific to optimisation, this is
             * a use case often encountered (e.g. to calibrate existing models written in
             * C++ , C, or Fortran)
             */
            IClonableObjectiveEvaluator <IHyperCube <double> > evaluator;
            IEvolutionEngine <IHyperCube <double> >            uniformRandomSampling;

            NativeModelWrapper.AwbmWrapper.PermitMultiThreading = true;

            using (var simulation = new AwbmWrapper())
            {
                var data = DataHandling.GetSampleClimate();
                SimulationFactory.SetSampleSimulation(simulation, data);
                int from = simulation.GetStart();
                int to   = simulation.GetEnd();

                evaluator = AWBM_URS.MainClass.BuildUrsEvaluator(simulation, data.Runoff, from, to);

                var paramSpace = AWBM_URS.MainClass.CreateFeasibleAwbmParameterSpace(simulation);
                uniformRandomSampling = new UniformRandomSampling <IHyperCube <double> >(evaluator, new BasicRngFactory(0), paramSpace, 3000);
                var ursResults = uniformRandomSampling.Evolve();
                Console.WriteLine(MetaheuristicsHelper.GetHumanReadable(ursResults));
            }
        }
예제 #3
0
        protected override void Convert(System.IO.TextWriter writer, object state)
        {
            LoggingEvent     logEvent  = state as LoggingEvent;
            SysConfigLogInfo sysConfig = logEvent.MessageObject as SysConfigLogInfo;

            if (sysConfig == null)
            {
                throw new ArgumentException("Object is not of type SysConfigLogInfo");
            }

            Tuple <string, string>[] prepend = new Tuple <string, string>[]
            {
                Tuple.Create("Category", sysConfig.Tags["Category"])
            };
            //prepend = null; // Not sure how to prevent repeats reliably.
            IEnumerable <IHyperCube <double> > points = sysConfig.Scores as IEnumerable <IHyperCube <double> >;
            IEnumerable <IObjectiveScores>     scores = sysConfig.Scores as IEnumerable <IObjectiveScores>;

            if (points != null)
            {
                writer.Write(MetaheuristicsHelper.BuildCsvFileContent <IHyperCube <double> >(points, false, prepend));
            }
            if (scores != null)
            {
                writer.Write(MetaheuristicsHelper.BuildCsvFileContent <IHyperCube <double> >(scores, false, prepend));
            }
        }
예제 #4
0
        public void TestPopulationSeeding()
        {
            var fTmp             = Path.GetTempFileName();
            var f                = Path.Combine(Path.GetDirectoryName(fTmp), Path.GetFileNameWithoutExtension(fTmp) + ".csv");
            int numScores        = 5;
            var pSet             = new ParameterSet(new MockTimeModel());
            var expectedMaxBound = 3.0;

            pSet.paramSpec("x").max = expectedMaxBound;
            var pSpaceReference = new MpiSysConfigTIME(pSet);

            IObjectiveScores[] scores = createScores(numScores);
            try
            {
                MetaheuristicsHelper.SaveAsCsv <MpiSysConfig>(scores, f);
                var seeds = GridModelHelper.LoadParameterSets(f, pSpaceReference);
                Assert.AreEqual(numScores, seeds.Length);
                Assert.AreEqual(expectedMaxBound, seeds[0].GetMaxValue("x"));
                Assert.AreEqual(MockTimeModel.getX(4), seeds[4].GetValue("x"), 1e-9);
                Assert.AreEqual(MockTimeModel.getY(3), seeds[3].GetValue("y"), 1e-9);
            }
            finally
            {
                if (File.Exists(f))
                {
                    File.Delete(f);
                }
                if (File.Exists(fTmp))
                {
                    File.Delete(fTmp);
                }
            }
        }
예제 #5
0
            public IObjectiveScores <IHyperCube <double> > EvaluateScore(IHyperCube <double> systemConfiguration)
            {
                apply(systemConfiguration, simulation);
                simulation.Execute();
                double result = sumSquares(simulation.GetRecorded("Runoff"), this.observedData);

                return(MetaheuristicsHelper.CreateSingleObjective(systemConfiguration, result, "Sum Squares"));
            }
예제 #6
0
        protected void SetValue(string variableName, T value, bool throwOnOutOfBounds)
        {
            checkCorrectArg(variableName);
            T maxValue = GetMaxValue(variableName);
            T minValue = GetMinValue(variableName);

            if (throwOnOutOfBounds)
            {
                MetaheuristicsHelper.CheckInBounds(value, minValue, maxValue, throwOnOutOfBounds);
            }
            this.values[variableName].Val = value;
        }
예제 #7
0
        /// <summary>
        ///   Writes the results.
        /// </summary>
        public void WriteResults()
        {
            Log.InfoFormat("Writing in-memory log to '{0}'", LogFileName);
            InMemoryLogger.CsvSerialise(LogFileName, "GriddedCalib");

            Log.InfoFormat("Root: saving final parameters to '{0}'", OutputFileName);
            MetaheuristicsHelper.SaveAsCsv <MpiSysConfig>(Results, OutputFileName);

            string parameterSetPath = Path.Combine(OutputPath.FullName, "BestParamSet.xml");

            Log.InfoFormat("Root: saving reseed parameters to '{0}'", parameterSetPath);
            GridModelHelper.WriteParameters <MpiSysConfig>(Results, SeedParametersFile, parameterSetPath);
        }
예제 #8
0
        public void TestParseCsvScores()
        {
            var template   = createPoint(3, 2, 1);
            var csvContent = @"0,1,2,Score:0-0,Score:0-1
4.4,3.3,2.2,0,3.14159265358979
4.5,3.4,2.1,3.14159265358979,6.28318530717959
";
            var points     = MetaheuristicsHelper.ParseConfigsFromCsv(csvContent, template);

            Assert.AreEqual(4.4, points[0].GetValue("0"));
            Assert.AreEqual(3.3, points[0].GetValue("1"));
            Assert.AreEqual(3.4, points[1].GetValue("1"));
        }
        private void GetSmallestIntervalForValues(IHyperCube <double>[] points, string varName, out double minimum, out double maximum)
        {
            int n = points.Length;

            double[] values = new double[n];

            for (int j = 0; j < n; j++)
            {
                values[j] = points[j].GetValue(varName);
            }

            minimum = MetaheuristicsHelper.GetMinimum(values);
            maximum = MetaheuristicsHelper.GetMaximum(values);
        }
예제 #10
0
        public void TestMakeBins()
        {
            int[] population = new int[13];
            for (int i = 0; i < population.Length; i++)
            {
                population[i] = i + 1;
            }

            var result = MetaheuristicsHelper.MakeBins(population, 2);

            Assert.AreEqual(2, result.Length);
            Assert.AreEqual(new[] { 1, 2, 3, 4, 5, 6, 7 }, result[0]);
            Assert.AreEqual(new[] { 8, 9, 10, 11, 12, 13 }, result[1]);
        }
예제 #11
0
        public void TestInterpolator()
        {
            var evaluator = new IdentityObjEval();
            var inPoints  = new List <TestHyperCube>();

            inPoints.Add(createPoint(1.0, 2.0, 3.0));
            inPoints.Add(createPoint(1.0, 2.0, 4.0));
            inPoints.Add(createPoint(2.0, 3.0, 5.0));
            var inScores  = Array.ConvertAll(inPoints.ToArray(), (x => evaluator.EvaluateScore(x)));
            var outPoints = MetaheuristicsHelper.InterpolateBetweenPoints <TestHyperCube>(evaluator, inScores, 0.1 + 1e-11);

            Assert.AreEqual(21, outPoints.Length);
            assertPoint(outPoints[0], 1.0, 2.0, 3.0);
            assertPoint(outPoints[1], 1.0, 2.0, 3.1);
            assertPoint(outPoints[10], 1.0, 2.0, 4.0);
            assertPoint(outPoints[15], 1.5, 2.5, 4.5);
        }
예제 #12
0
 protected void performHomoteticTransform(IHyperCube <T> point, T factor, ref HyperCube <T> result)
 {
     foreach (var varName in this.GetVariableNames())
     {
         var min = this.GetMinValue(varName);
         var max = this.GetMaxValue(varName);
         result.SetMinValue(varName, min);
         result.SetMaxValue(varName, max);
         var newVal     = reflect(point.GetValue(varName), this.GetValue(varName), factor);
         var isInBounds = MetaheuristicsHelper.CheckInBounds(newVal, min, max, throwIfFalse: this.ThrowOnOutOfBounds);
         if (!isInBounds)
         {
             result = null;
             break;
         }
         result.SetValue(varName, newVal);
     }
 }
예제 #13
0
        public static void Main(string[] args)
        {
            // If you have to remember *one* thing from this tutorial, it is the three essential players
            // 1- the tunable parameters of the optimisation problem:
            //    ISystemConfiguration, here implemented by StringSpecification for this 'Hello World' problem
            // 2- the object evaluating the score(s) for a given "system configuration" (IObjectiveEvaluator<T>)
            // 3- the optimisation algorithm, implementing IEvolutionEngine<T>
            // It is recommended that you declare variables typed as interfaces, not concrete classes,
            // whenever possible including in an 'Hello World'...
            IObjectiveEvaluator <StringSpecification> evaluator;
            IEvolutionEngine <StringSpecification>    finder;

            string strToFind = args.Length == 0 ? "Hello, World!" : args[0];

            evaluator = buildEvaluator(strToFind);
            finder    = new StringFinder(evaluator, strToFind.Length, new BasicRngFactory(0));
            var result = finder.Evolve();

            Console.WriteLine(MetaheuristicsHelper.GetHumanReadable(result));
        }
        internal static MpiSysConfig[] LoadParameterSets(string filename, MpiSysConfigTIME templateParameterSet)
        {
            var ext = Path.GetExtension(filename).ToLower();

            if (ext == ".xml")
            {
                var pSets  = SerializationHelper.XmlDeserialize <ParameterSet[]>(filename, new[] { typeof(ParameterSet) });
                var result = new MpiSysConfig[pSets.Length];
                for (int i = 0; i < result.Length; i++)
                {
                    var p = new MpiSysConfigTIME(templateParameterSet);
                    p.CopyValuesFrom(pSets[i]);
                    result[i] = p;
                }
                return(result);
            }
            else if (ext == ".csv")
            {
                return(MetaheuristicsHelper.ReadConfigsFromCsv(filename, templateParameterSet));
            }
            throw new NotImplementedException();
        }
예제 #15
0
        public static IObjectiveScores[] EvaluateScores <T>(IClonableObjectiveEvaluator <T> evaluator, T[] population, Func <bool> isCancelled, ParallelOptions parallelOptions = null) where T : ISystemConfiguration
        {
            if (population.Length == 0)
            {
                return(new IObjectiveScores[0]);
            }
            if (parallelOptions == null)
            {
                parallelOptions = new ParallelOptions()
                {
                    MaxDegreeOfParallelism = -1
                }
            }
            ;

            var procCount = System.Environment.ProcessorCount;

            IObjectiveScores[] result;
            if (evaluator.SupportsThreadSafeCloning)
            {
                // There is presumably no point cloning
                // the system more times than the max level of parallelism
                int nParallel = procCount;
                if (parallelOptions.MaxDegreeOfParallelism > 0)
                {
                    nParallel = Math.Min(nParallel, parallelOptions.MaxDegreeOfParallelism);
                }
                T[][] subPop   = MetaheuristicsHelper.MakeBins(population, nParallel);
                var   taskPkgs = new List <Tuple <T[], IClonableObjectiveEvaluator <T> > >();
                taskPkgs.Add(Tuple.Create(subPop[0], evaluator));
                for (int i = 1; i < subPop.Length; i++)
                {
                    taskPkgs.Add(Tuple.Create(subPop[i], evaluator.Clone()));
                }
                // Need to use Parallel.ForEach rather than Parallel.For to work around a Parallel.For
                // oddity in Mono 3.12.1. Need an identity to iterate over...
                var ramp = new int[subPop.Length];
                // Map of index of subpopulations to indices in the variable result:
                //var offsets = new int[subPop.Length];
                var resultBins = new IObjectiveScores[ramp.Length][];
                for (int i = 1; i < ramp.Length; i++)
                {
                    ramp[i] = i;
                }
                Parallel.ForEach(ramp, parallelOptions,
                                 (i => {
                    resultBins[i] = EvaluateScoresSerial(taskPkgs[i], isCancelled);
                })
                                 );
                result = Gather(resultBins);
            }
            else
            {
                result = new IObjectiveScores[population.Length];
                for (int i = 0; i < population.Length; i++)
                {
                    if (!isCancelled())
                    {
                        result [i] = evaluator.EvaluateScore(population [i]);
                    }
                    else
                    {
                        result [i] = null;
                    }
                }
            }
            return(result);
        }
예제 #16
0
        public IObjectiveScores <T> EvalParaboloidScore <T>(T sysConfig, double bestParam) where T : IHyperCube <double>
        {
            double result = CalculateParaboloid(sysConfig, bestParam);

            return(MetaheuristicsHelper.CreateSingleObjective <T>(sysConfig, result, "Paraboloid"));
        }