/// <summary> /// Initializes a new instance of the <see cref="PartialGenomeSearchPoint"/> class. /// </summary> /// <param name="underlyingGenome">The underlying <see cref="ImmutableGenome"/>.</param> /// <param name="values"> /// The real-valued point to base continuous parameters on. /// This is the internal representation, not the one in the parameter space. /// <para>Use <see cref="CreateFromGenome"/> if starting from search space.</para> /// </param> /// <param name="genomeSearchPointConverter"> /// Responsible for converting between full-fledged <see cref="Genome"/>s and continuous values in /// parameter space. /// </param> /// <param name="genomeBuilder">Responsible for checking validity and repairing.</param> /// <param name="lowerBounds">The lower bounds by dimension.</param> /// <param name="upperBounds">The upper bounds by dimension.</param> public PartialGenomeSearchPoint( ImmutableGenome underlyingGenome, Vector <double> values, GenomeSearchPointConverter genomeSearchPointConverter, GenomeBuilder genomeBuilder, double[] lowerBounds, double[] upperBounds) : base(values, lowerBounds, upperBounds) { if (genomeSearchPointConverter == null) { throw new ArgumentNullException(nameof(genomeSearchPointConverter)); } if (genomeBuilder == null) { throw new ArgumentNullException(nameof(genomeBuilder)); } // To create the complete genome, map the continuous values into parameter search space again. var genome = genomeSearchPointConverter.MergeIntoGenome(this.MapIntoBounds(), underlyingGenome); // Remember whether there was no direct mapping to a valid genome. this.IsRepaired = false; if (!genomeBuilder.IsGenomeValid(genome)) { genomeBuilder.MakeGenomeValid(genome); this.IsRepaired = true; } this.Genome = new ImmutableGenome(genome); }
public void DetermineInitialPointsBuildsValidPointsBasedOnIncumbent() { // Create population. var population = this.CreatePopulation(); // Make sure genomes can be invalid (important: only do this after creating the population!). this._genomeBuilder = new ConfigurableGenomeBuilder( this._parameterTree, isValidFunction: g => (int)g.GetGeneValue("quasi-continuous").GetValue() < this._deConfiguration.MinimumDomainSize / 2, mutationRate: 0); var informationFlow = new LocalDifferentialEvolutionInformationFlow( this._deConfiguration, this._parameterTree, this._genomeBuilder); // Determine initial points. var incumbent = this._genomeBuilder.CreateRandomGenome(age: 2); var points = informationFlow.DetermineInitialPoints(population, incumbent); // Check validity and discrete parameter (they should stay the same). foreach (var point in points) { Assert.True(point.IsValid(), $"Created invalid point, associated genome: {point.Genome}."); Assert.Equal( incumbent.GetGeneValue(ExtractIntegerValue.ParameterName).GetValue(), point.Genome.CreateMutableGenome().GetGeneValue(ExtractIntegerValue.ParameterName).GetValue()); } }
/// <summary> /// Initializes a new instance of the <see cref="DifferentialEvolutionStrategy{TInstance, TResult}"/> class. /// </summary> /// <param name="configuration">Options used for this instance.</param> /// <param name="parameterTree">Provides the tunable parameters.</param> /// <param name="genomeBuilder">Responsible for creation, modification and crossover of genomes. /// Needs to be compatible with the given parameter tree and configuration.</param> /// <param name="genomeSorter"> /// An <see cref="IActorRef" /> to a <see cref="GenomeSorter{TInstance,TResult}" />. /// </param> /// <param name="targetRunResultStorage"> /// An <see cref="IActorRef" /> to a <see cref="ResultStorageActor{TInstance,TResult}" /> /// which knows about all executed target algorithm runs and their results. /// </param> public DifferentialEvolutionStrategy( AlgorithmTunerConfiguration configuration, ParameterTree parameterTree, GenomeBuilder genomeBuilder, IActorRef genomeSorter, IActorRef targetRunResultStorage) : base(configuration, parameterTree, targetRunResultStorage, new GenomeSearchPointSorter <TInstance>(genomeSorter)) { this._strategyConfiguration = this.Configuration.ExtractDetailedConfiguration <DifferentialEvolutionStrategyConfiguration>( DifferentialEvolutionStrategyArgumentParser.Identifier); if (this._strategyConfiguration.FocusOnIncumbent) { this._informationFlow = new LocalDifferentialEvolutionInformationFlow( this._strategyConfiguration, parameterTree, genomeBuilder); } else { this._informationFlow = new GlobalDifferentialEvolutionInformationFlow( this._strategyConfiguration, parameterTree, genomeBuilder); } this._searchPointFactory = (vector, parent) => new GenomeSearchPoint(vector, parent, genomeBuilder); this._differentialEvolutionRunner = this.CreateDifferentialEvolutionRunner( this._strategyConfiguration.DifferentialEvolutionConfiguration.InitialMeanMutationFactor, this._strategyConfiguration.DifferentialEvolutionConfiguration.InitialMeanCrossoverRate); }
/// <summary> /// Creates a <see cref="CovarianceMatrixAdaptationStrategyBase{TSearchPoint, TInstance, TResult}"/> depending /// on the <see cref="CovarianceMatrixAdaptationStrategyConfiguration"/>. /// </summary> /// <typeparam name="TInstance"> /// The instance type to use. /// </typeparam> /// <typeparam name="TResult"> /// The result for an individual evaluation. /// </typeparam> /// <param name="configuration">Options to use.</param> /// <param name="parameterTree">Provides the tunable parameters.</param> /// <param name="genomeBuilder">Responsible for creation, modification and crossover of genomes. /// Needs to be compatible with the given parameter tree and configuration.</param> /// <param name="genomeSorter"> /// An <see cref="IActorRef" /> to a <see cref="GenomeSorter{TInstance,TResult}" />. /// </param> /// <param name="targetRunResultStorage"> /// An <see cref="IActorRef" /> to a <see cref="ResultStorageActor{TInstance,TResult}" /> /// which knows about all executed target algorithm runs and their results. /// </param> /// <returns> /// The created <see cref="CovarianceMatrixAdaptationStrategyBase{TSearchPoint, TInstance, TResult}"/> instance. /// </returns> public static IPopulationUpdateStrategy <TInstance, TResult> CreateCovarianceMatrixAdaptationStrategy <TInstance, TResult>( AlgorithmTunerConfiguration configuration, ParameterTree parameterTree, GenomeBuilder genomeBuilder, IActorRef genomeSorter, IActorRef targetRunResultStorage) where TInstance : InstanceBase where TResult : ResultBase <TResult>, new() { if (StrategyShouldFocusOnIncumbent(configuration)) { return(new LocalCovarianceMatrixAdaptationStrategy <TInstance, TResult>( configuration, parameterTree, genomeBuilder, genomeSorter, targetRunResultStorage)); } else { return(new GlobalCovarianceMatrixAdaptationStrategy <TInstance, TResult>( configuration, parameterTree, genomeBuilder, genomeSorter, targetRunResultStorage)); } }
public void DefaultGenomeUsesDefaultValues() { var tree = GenomeBuilderTest.BuildParameterTree(true); var builder = new GenomeBuilder( tree, new AlgorithmTunerConfiguration.AlgorithmTunerConfigurationBuilder().Build(maximumNumberParallelEvaluations: 1)); var defaultGenome = builder.CreateDefaultGenome(1337); Assert.NotNull(defaultGenome); Assert.Equal(1337, defaultGenome.Age); // GenomeBuilderTest.ContinuousParameter should not be active, since "a" node is the default. var filteredGenes = defaultGenome.GetFilteredGenes(tree); Assert.Equal(3, filteredGenes.Count); Assert.Equal("a", filteredGenes[GenomeBuilderTest.DecisionParameter].GetValue()); Assert.Equal(1, filteredGenes[GenomeBuilderTest.SmallValueParameter].GetValue()); Assert.Equal(42, filteredGenes[GenomeBuilderTest.DiscreteParameter].GetValue()); // GenomeBuilderTest.ContinuousParameter should also have a default value, even though it is not active. var contAllele = defaultGenome.GetGeneValue(GenomeBuilderTest.ContinuousParameter); Assert.NotNull(contAllele); Assert.Equal(0.2, contAllele.GetValue()); }
/// <summary> /// Validates the parameters: /// * Null checks for every one of them. /// * Checks that the number of training instances provided is sufficient considering the given configuration. /// * Checks that configuration about whether to use run time tuning /// and the usage of the run time tuning result interface fit together /// * Checks that the parameter tree contains parameters. /// * Checks that those parameters' identifiers are unique. /// </summary> /// <param name="targetAlgorithmFactory"> /// Produces configured instances of the target algorithm to tune. /// </param> /// <param name="runEvaluator"> /// Object for evaluating target algorithm runs. /// </param> /// <param name="trainingInstances"> /// The set of instances used for tuning. /// </param> /// <param name="parameterTree"> /// The parameter tree. /// </param> /// <param name="configuration"> /// Algorithm tuner configuration parameters. /// </param> /// <param name="genomeBuilder"> /// The genome builder. /// </param> private static void ValidateParameters( ITargetAlgorithmFactory <TTargetAlgorithm, TInstance, TResult> targetAlgorithmFactory, IRunEvaluator <TResult> runEvaluator, IEnumerable <TInstance> trainingInstances, ParameterTree parameterTree, AlgorithmTunerConfiguration configuration, GenomeBuilder genomeBuilder) { // Check argument for nulls. if (targetAlgorithmFactory == null) { throw new ArgumentNullException(nameof(targetAlgorithmFactory), "You must specify a target algorithm factory."); } if (runEvaluator == null) { throw new ArgumentNullException(nameof(runEvaluator), "You must specify a run evaluator."); } if (trainingInstances == null) { throw new ArgumentNullException(nameof(trainingInstances), "You must specify a list of training instances."); } if (parameterTree == null) { throw new ArgumentNullException(nameof(parameterTree), "You must specify a parameter tree."); } if (configuration == null) { throw new ArgumentNullException(nameof(configuration), "You must specify an algorithm tuner configuration."); } if (genomeBuilder == null) { throw new ArgumentNullException(nameof(genomeBuilder), "You must specify a genome builder."); } // Check enough training instances have been provided. var numInstances = trainingInstances.Count(); if (numInstances < configuration.EndNumInstances) { throw new ArgumentException( $"In the end, {configuration.EndNumInstances} training instances should be used, but only {numInstances} have been provided.", nameof(trainingInstances)); } // Check that the parameter tree is valid. if (!parameterTree.ContainsParameters()) { throw new ArgumentException("Specified parameter tree without parameters.", nameof(parameterTree)); } if (!parameterTree.IdentifiersAreUnique()) { throw new ArgumentException("Specified parameter tree contained duplicate identifiers.", nameof(parameterTree)); } }
/// <summary> /// Initializes a new instance of the <see cref="ContinuizedGenomeSearchPoint"/> class. /// </summary> /// <param name="values"> /// The real-valued point to base this on. /// This is the internal representation, not the one in the parameter space. /// <para>Use <see cref="CreateFromGenome"/> if starting from search space.</para> /// </param> /// <param name="parameterTree">Specifies the parameters.</param> /// <param name="genomeBuilder">Responsible for checking validity and repairing.</param> /// <param name="lowerBounds">The lower bounds by dimension.</param> /// <param name="upperBounds">The upper bounds by dimension.</param> public ContinuizedGenomeSearchPoint( Vector <double> values, ParameterTree parameterTree, GenomeBuilder genomeBuilder, double[] lowerBounds, double[] upperBounds) : base(values, lowerBounds, upperBounds) { if (parameterTree == null) { throw new ArgumentNullException(nameof(parameterTree)); } if (genomeBuilder == null) { throw new ArgumentNullException(nameof(genomeBuilder)); } var transformator = new TolerantGenomeTransformation(parameterTree); var geneValues = transformator.RoundToValidValues(this.MapIntoBounds().ToArray()); var genome = transformator.ConvertBack(geneValues); // Remember whether there was no direct mapping to a valid genome. this.IsRepaired = false; if (!genomeBuilder.IsGenomeValid(genome)) { genomeBuilder.MakeGenomeValid(genome); this.IsRepaired = true; } this.Genome = new ImmutableGenome(genome); }
/// <summary> /// Initializes a new instance of the <see cref="LocalDifferentialEvolutionInformationFlow"/> class. /// </summary> /// <param name="strategyConfiguration"> /// Options used for the <see cref="DifferentialEvolutionStrategy{TInstance,TResult}"/>. /// </param> /// <param name="parameterTree">Provides the tunable parameters.</param> /// <param name="genomeBuilder">Responsible for creation, modification and crossover of genomes.</param> public LocalDifferentialEvolutionInformationFlow( DifferentialEvolutionStrategyConfiguration strategyConfiguration, ParameterTree parameterTree, GenomeBuilder genomeBuilder) { this._strategyConfiguration = strategyConfiguration ?? throw new ArgumentNullException(nameof(strategyConfiguration)); this._parameterTree = parameterTree ?? throw new ArgumentNullException(nameof(parameterTree)); this._genomeBuilder = genomeBuilder ?? throw new ArgumentNullException(nameof(genomeBuilder)); }
/// <summary> /// Initializes a new instance of the <see cref="ContinuizedGenomeSearchPointTest"/> class. /// </summary> public ContinuizedGenomeSearchPointTest() { Randomizer.Configure(); this._parameterTree = this.CreateParameterTree(); this._genomeBuilder = new GenomeBuilder( this._parameterTree, new AlgorithmTunerConfiguration.AlgorithmTunerConfigurationBuilder().SetEnableRacing(true).Build(1)); }
/// <summary> /// Initializes a new instance of the <see cref="AlgorithmTuner{TTargetAlgorithm,TInstance,TResult}"/> class. /// </summary> /// <param name="targetAlgorithmFactory"> /// The target algorithm factory. /// </param> /// <param name="runEvaluator"> /// The run evaluator. /// </param> /// <param name="trainingInstances"> /// The training instances. /// </param> /// <param name="parameterTree"> /// The parameter tree. /// </param> /// <param name="configuration"> /// The configuration. /// </param> /// <param name="genomeBuilder"> /// The genome builder. /// </param> public AlgorithmTuner( ITargetAlgorithmFactory <TTargetAlgorithm, TInstance, TResult> targetAlgorithmFactory, IRunEvaluator <TResult> runEvaluator, IEnumerable <TInstance> trainingInstances, ParameterTree parameterTree, AlgorithmTunerConfiguration configuration, GenomeBuilder genomeBuilder) : base(targetAlgorithmFactory, runEvaluator, trainingInstances, parameterTree, configuration, genomeBuilder) { }
/// <summary> /// Creates a <see cref="GenomeSearchPoint"/> which is based on a <see cref="Genome"/>, but uses /// random values for the real-valued components. /// </summary> /// <param name="genome"> /// The <see cref="Genome"/> to base the <see cref="GenomeSearchPoint"/> on. /// Components considered as real-valued are ignored. /// </param> /// <param name="parameterTree">Specification of all parameters.</param> /// <param name="minimumDomainSize">Minimum size of an integer domain to be handled as continuous.</param> /// <param name="genomeBuilder"> /// Responsible for validity checking of <see cref="Genome"/>s. /// Needs to be compatible with <paramref name="parameterTree"/>. /// </param> /// <returns>The created <see cref="GenomeSearchPoint"/>.</returns> public static GenomeSearchPoint BaseRandomPointOnGenome( Genome genome, ParameterTree parameterTree, int minimumDomainSize, GenomeBuilder genomeBuilder) { var converter = new GenomeSearchPointConverter(parameterTree, minimumDomainSize); var values = converter.RandomlyCreateRealValuedParameterValues(); return(new GenomeSearchPoint(values, converter, new ImmutableGenome(genome), genomeBuilder)); }
/// <summary> /// Initializes a new instance of the <see cref="PartialGenomeSearchPointTest"/> class. /// </summary> public PartialGenomeSearchPointTest() { Randomizer.Configure(); this._parameterTree = this.CreateParameterTree(); this._genomeBuilder = new GenomeBuilder( this._parameterTree, new AlgorithmTunerConfiguration.AlgorithmTunerConfigurationBuilder().SetEnableRacing(true).Build(1)); this._genomeSearchPointConverter = new GenomeSearchPointConverter(this._parameterTree, this._minimumDomainSize); this._baseGenome = new ImmutableGenome(this._genomeBuilder.CreateRandomGenome(age: 0)); }
public void LogFinishedGenerationThrowsForUnknownDirectory() { // Set non existing log file path, then log finished generation. this._configuration = new AlgorithmTunerConfiguration.AlgorithmTunerConfigurationBuilder() .SetLogFilePath("foo/bar.txt") .Build(maximumNumberParallelEvaluations: 1); this._genomeBuilder = new GenomeBuilder(this._parameterTree, this._configuration); this._writer = new LogWriter <InstanceFile, RuntimeResult>(this._parameterTree, this._configuration); Assert.Throws <DirectoryNotFoundException>( () => this._writer.LogFinishedGeneration(0, 1, this._genomeBuilder.CreateRandomGenome(0), LogWriterTest.EmptyResults)); }
/// <summary> /// Generates <paramref name="count"/> random genomes adhering to the given <see cref="ParameterTree"/>. /// </summary> /// <param name="tree"><see cref="ParameterTree"/> to base genomes on.</param> /// <param name="config"><see cref="AlgorithmTunerConfiguration"/> to use when creating genomes.</param> /// <param name="count">The number of genomes to create.</param> /// <returns>The created genomes.</returns> public static List <Genome> GenerateGenomes(ParameterTree tree, AlgorithmTunerConfiguration config, int count) { var result = new List <Genome>(count); var builder = new GenomeBuilder(tree, config); for (var i = 0; i < count; i++) { result.Add(builder.CreateRandomGenome(0)); } return(result); }
/// <summary> /// Initializes a new instance of the <see cref="LogWriterTest"/> class. /// </summary> public LogWriterTest() { this._configuration = new AlgorithmTunerConfiguration.AlgorithmTunerConfigurationBuilder() .SetGenerations(24) .SetGoalGeneration(17) .SetLogFilePath(LogWriterTest.LogFilePath) .Build(maximumNumberParallelEvaluations: 1); this._genomeBuilder = new GenomeBuilder(this._parameterTree, this._configuration); Randomizer.Reset(); Randomizer.Configure(0); this._writer = new LogWriter <InstanceFile, RuntimeResult>(this._parameterTree, this._configuration); }
/// <summary> /// Initializes a new instance of the <see cref="LocalCovarianceMatrixAdaptationStrategy{TInstance, TResult}"/> /// class. /// </summary> /// <param name="configuration">Options used for this instance.</param> /// <param name="parameterTree">Provides the tunable parameters.</param> /// <param name="genomeBuilder">Responsible for creation, modification and crossover of genomes. /// Needs to be compatible with the given parameter tree and configuration.</param> /// <param name="genomeSorter"> /// An <see cref="IActorRef" /> to a <see cref="GenomeSorter{TInstance,TResult}" />. /// </param> /// <param name="targetRunResultStorage"> /// An <see cref="IActorRef" /> to a <see cref="ResultStorageActor{TInstance,TResult}" /> /// which knows about all executed target algorithm runs and their results. /// </param> public LocalCovarianceMatrixAdaptationStrategy( AlgorithmTunerConfiguration configuration, ParameterTree parameterTree, GenomeBuilder genomeBuilder, IActorRef genomeSorter, IActorRef targetRunResultStorage) : base(configuration, parameterTree, genomeSorter, targetRunResultStorage) { this._genomeBuilder = genomeBuilder ?? throw new ArgumentNullException(nameof(genomeBuilder)); // Create a dummy search point factory to enable CMA-ES dumps. this._searchPointFactory = vector => throw new InvalidOperationException("Called search point factory without initialization!"); this._cmaEsRunner = new CmaEs <PartialGenomeSearchPoint>(this.SearchPointSorter, this._searchPointFactory); }
/// <summary> /// Initializes a new instance of the <see cref="GenomeSearchPointTest"/> class. /// </summary> public GenomeSearchPointTest() { Randomizer.Configure(); this._parameterTree = this.CreateParameterTree(); this._genomeBuilder = new GenomeBuilder( this._parameterTree, new AlgorithmTunerConfiguration.AlgorithmTunerConfigurationBuilder().Build(1)); this._parent = GenomeSearchPoint.CreateFromGenome( this._genomeBuilder.CreateRandomGenome(age: 1), this._parameterTree, this._minimumDomainSize, this._genomeBuilder); }
public void MutateMayChangeEveryParameter() { // Create genome builder with a mutation rate of 1. var configuration = new AlgorithmTunerConfiguration.AlgorithmTunerConfigurationBuilder() .SetMutationRate(1) .Build(maximumNumberParallelEvaluations: 1); var genomeBuilder = new GenomeBuilder(GenomeBuilderTest.BuildParameterTree(), configuration); // Create genome. var genome = GenomeBuilderTest.BuildFittingGenome(); // Prepare structure to store which values have been mutated. string[] identifiers = { GenomeBuilderTest.DecisionParameter, GenomeBuilderTest.SmallValueParameter, GenomeBuilderTest.DiscreteParameter, GenomeBuilderTest.ContinuousParameter, }; Dictionary <string, bool> hasBeenMutated = identifiers.ToDictionary( identifier => identifier, identifier => false); Dictionary <string, IAllele> originalValues = identifiers.ToDictionary( identifier => identifier, identifier => genome.GetGeneValue(identifier)); // Do a lot of mutations. for (int i = 0; i < GenomeBuilderTest.loopCountForRandomTests; i++) { genomeBuilder.Mutate(genome); // After each one, check which genes have changed... foreach (string identifier in identifiers) { bool valueChanged = !object.Equals(originalValues[identifier], genome.GetGeneValue(identifier)); if (valueChanged) { // ...and store them. hasBeenMutated[identifier] = true; } } } // Finally check that everything has been changed at least once. Assert.True( hasBeenMutated.All(keyValuePair => keyValuePair.Value), $"Genes {TestUtils.PrintList(hasBeenMutated.Where(keyValuePair => !keyValuePair.Value).Select(keyValuePair => keyValuePair.Key))} have not been mutated."); }
public void AllDummyParametersAreFiltered() { Randomizer.Reset(); Randomizer.Configure(0); var parameterTree = GurobiUtils.CreateParameterTree(); var config = new AlgorithmTunerConfiguration.AlgorithmTunerConfigurationBuilder().Build(1); var genomeBuilder = new GenomeBuilder(parameterTree, config); var genome = genomeBuilder.CreateRandomGenome(0); var filteredGenes = genome.GetFilteredGenes(parameterTree); foreach (var filteredGenesKey in filteredGenes.Keys) { filteredGenesKey.ShouldNotContain("Indicator"); } }
/// <summary> /// Initializes a new instance of the <see cref="GgaStrategy{TInstance, TResult}"/> class. /// </summary> /// <param name="configuration">Options used for this instance.</param> /// <param name="parameterTree">Provides the tuneable parameters.</param> /// <param name="genomeBuilder">Responsible for creation, modification and crossover of genomes. /// Needs to be compatible with the given parameter tree and configuration.</param> /// <param name="tournamentSelector">An <see cref="IActorRef" /> to a /// <see cref="GenerationEvaluationActor{TTargetAlgorithm,TInstance,TResult}" /> which decides which competitive /// genomes are allowed to reproduce.</param> /// <param name="geneticEngineering">Object which trains a model and enables model-based crossovers.</param> public GgaStrategy( AlgorithmTunerConfiguration configuration, ParameterTree parameterTree, GenomeBuilder genomeBuilder, IActorRef tournamentSelector, IGeneticEngineering geneticEngineering) { this._configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); this._parameterTree = parameterTree ?? throw new ArgumentNullException(nameof(parameterTree)); this._genomeBuilder = genomeBuilder ?? throw new ArgumentNullException(nameof(genomeBuilder)); this._tournamentSelector = tournamentSelector ?? throw new ArgumentNullException(nameof(tournamentSelector)); this._geneticEngineering = geneticEngineering ?? throw new ArgumentNullException(nameof(geneticEngineering)); this.AllKnownRanks = new Dictionary <Genome, List <GenomeTournamentRank> >( 3 * this._configuration.PopulationSize, Genome.GenomeComparer); }
/// <summary> /// Called before every test. /// </summary> protected override void InitializeDefault() { base.InitializeDefault(); this._completeConfiguration = LocalDifferentialEvolutionInformationFlowTest.CreateConfiguration(replacementRate: 0.25); this._deConfiguration = this._completeConfiguration.ExtractDetailedConfiguration <DifferentialEvolutionStrategyConfiguration>( DifferentialEvolutionStrategyArgumentParser.Identifier); var root = new AndNode(); root.AddChild(new ValueNode <int>(ExtractIntegerValue.ParameterName, new IntegerDomain(-1, 3))); root.AddChild(new ValueNode <int>("quasi-continuous", new IntegerDomain(0, this._deConfiguration.MinimumDomainSize + 1))); this._parameterTree = new ParameterTree(root); this._genomeBuilder = new GenomeBuilder(this._parameterTree, this._completeConfiguration); }
/// <summary> /// Called before every test case. /// </summary> protected override void InitializeDefault() { var parameterTree = this.GetDefaultParameterTree(); var configuration = this.GetDefaultAlgorithmTunerConfiguration(); var genomeBuilder = new GenomeBuilder(parameterTree, configuration); this._originalIncumbent = genomeBuilder.CreateRandomGenome(age: 2); for (int i = 0; i < 5; i++) { var searchPoint = PartialGenomeSearchPoint.CreateFromGenome( genomeBuilder.CreateRandomGenome(age: 0), parameterTree, minimumDomainSize: 0); this._mostRecentSorting.Add(searchPoint); this._currentEvaluationInstances.Add(new TestInstance(i.ToString())); } }
/// <summary> /// Initializes a new instance of the /// <see cref="GlobalCovarianceMatrixAdaptationStrategy{TInstance, TResult}"/> class. /// </summary> /// <param name="configuration">Options used for this instance.</param> /// <param name="parameterTree">Provides the tunable parameters.</param> /// <param name="genomeBuilder">Responsible for creation, modification and crossover of genomes. /// Needs to be compatible with the given parameter tree and configuration.</param> /// <param name="generationEvaluationActor"> /// An <see cref="IActorRef" /> to a <see cref="GenerationEvaluationActor{TTargetAlgorithm,TInstance,TResult}"/>. /// </param> /// <param name="targetRunResultStorage"> /// An <see cref="IActorRef" /> to a <see cref="ResultStorageActor{TInstance,TResult}" /> /// which knows about all executed target algorithm runs and their results. /// </param> public GlobalCovarianceMatrixAdaptationStrategy( AlgorithmTunerConfiguration configuration, ParameterTree parameterTree, GenomeBuilder genomeBuilder, IActorRef generationEvaluationActor, IActorRef targetRunResultStorage) : base(configuration, parameterTree, generationEvaluationActor, targetRunResultStorage) { if (genomeBuilder == null) { throw new ArgumentNullException(nameof(genomeBuilder)); } ContinuizedGenomeSearchPoint.ObtainParameterBounds(parameterTree, out var lowerBounds, out var upperBounds); this._searchPointFactory = vector => new ContinuizedGenomeSearchPoint(vector, parameterTree, genomeBuilder, lowerBounds, upperBounds); this._cmaEsRunner = new CmaEs <ContinuizedGenomeSearchPoint>(this.SearchPointSorter, this._searchPointFactory); }
public void MutateChangesGivenGenomeIfMutationRateIs1() { // Create genome builder with a mutation rate of 1. var configuration = new AlgorithmTunerConfiguration.AlgorithmTunerConfigurationBuilder() .SetMutationRate(1) .Build(maximumNumberParallelEvaluations: 1); var genomeBuilder = new GenomeBuilder(GenomeBuilderTest.BuildParameterTree(), configuration); // Build a fitting genome and store original description. var genome = GenomeBuilderTest.BuildFittingGenome(); string originalDescription = genome.ToString(); // Call mutate and check genome changed. genomeBuilder.Mutate(genome); Assert.NotEqual( originalDescription, genome.ToString()); }
public void DetermineInitialPointsThrowsIfNoValidPointExists() { // First generate some genomes. var population = this.CreatePopulation(); var incumbent = this._genomeBuilder.CreateRandomGenome(age: 2); // Then make sure all subsequent genomes are invalid. this._genomeBuilder = new ConfigurableGenomeBuilder( this._parameterTree, isValidFunction: g => false, mutationRate: 0); var informationFlow = new LocalDifferentialEvolutionInformationFlow( this._deConfiguration, this._parameterTree, this._genomeBuilder); // Try to call the method. Assert.Throws <TimeoutException>(() => informationFlow.DetermineInitialPoints(population, incumbent)); }
public void CrossoverRandomlyDecidesOnParentToTakeGeneValueFromForSingleGene() { // Build genome builder with a parameter tree that consists of a single continuous parameter. string parameterName = "parameter"; IParameterNode parameter = new ValueNode <double>(parameterName, new ContinuousDomain()); var genomeBuilder = new GenomeBuilder( new ParameterTree(parameter), new AlgorithmTunerConfiguration.AlgorithmTunerConfigurationBuilder().Build(maximumNumberParallelEvaluations: 1)); // Build genomes with different parameter values. var parent1 = new Genome(); var parent2 = new Genome(); Allele <double> parent1Allele = new Allele <double>(0); Allele <double> parent2Allele = new Allele <double>(1); parent1.SetGene(parameterName, parent1Allele); parent2.SetGene(parameterName, parent2Allele); // Observe what gene value the children's genes have. int numberLoops = 1000; int observedInheritanceFromParent1 = 0; for (int i = 0; i < numberLoops; i++) { var child = genomeBuilder.Crossover(parent1, parent2); if (object.Equals(parent1Allele, child.GetGeneValue(parameterName))) { observedInheritanceFromParent1++; } } double[] observed = { observedInheritanceFromParent1, numberLoops - observedInheritanceFromParent1 }; // We would expect each value the same number of times: double[] expected = { numberLoops / 2, numberLoops / 2 }; // Use Chi-Squared Test. var equalProbabilityTest = new ChiSquareTest(expected, observed, degreesOfFreedom: numberLoops - 1); Assert.False( equalProbabilityTest.Significant, $"Single gene was found to be not equally distributed in crossovers by the Chi-Squared test with significance level of {equalProbabilityTest.Size}."); }
/// <summary> /// Creates a <see cref="GenomeSearchPoint"/> from <see cref="Genome"/>. /// </summary> /// <param name="genome">The <see cref="Genome"/> to base the <see cref="GenomeSearchPoint"/> on.</param> /// <param name="parameterTree">Specification of all parameters.</param> /// <param name="minimumDomainSize">Minimum size of an integer domain to be handled as continuous.</param> /// <param name="genomeBuilder"> /// Responsible for validity checking of <see cref="Genome"/>s. /// Needs to be compatible with <paramref name="parameterTree"/>. /// </param> /// <returns>The created <see cref="GenomeSearchPoint"/>.</returns> public static GenomeSearchPoint CreateFromGenome( Genome genome, ParameterTree parameterTree, int minimumDomainSize, GenomeBuilder genomeBuilder) { if (genome == null) { throw new ArgumentNullException(nameof(genome)); } var converter = new GenomeSearchPointConverter(parameterTree, minimumDomainSize); var values = converter.TransformGenomeIntoValues(genome); return(new GenomeSearchPoint( Vector <double> .Build.DenseOfArray(values), converter, new ImmutableGenome(genome), genomeBuilder)); }
/// <summary> /// Called before every test case. /// </summary> protected override void InitializeDefault() { this._configuration = this.GetDefaultAlgorithmTunerConfiguration(); this._genomeBuilder = new ValueGenomeBuilder(this._parameterTree, this._configuration, this._genomeValues); this._geneticEngineering = new GeneticEngineering <StandardRandomForestLearner <ReuseOldTreesStrategy>, GenomePredictionForestModel <GenomePredictionTree>, ReuseOldTreesStrategy>( this._parameterTree, this._configuration); this.ActorSystem = ActorSystem.Create(TestBase.ActorSystemName, this._configuration.AkkaConfiguration); this._resultStorageActor = this.ActorSystem.ActorOf( Props.Create( () => new ResultStorageActor <TestInstance, IntegerResult>()), AkkaNames.ResultStorageActor); this._generationEvaluationActor = this.CreateTournamentSelector( this.ActorSystem, new ExtractIntegerValueCreator(), new TargetAlgorithm.InterfaceImplementations.ValueConsideration.SortByDescendingIntegerValue <TestInstance>()); }
public void DetermineInitialPointsUsesRepairOperationIfRequired() { // Create a parameter tree with a discrete and a continuous aspect. var root = new AndNode(); root.AddChild(new ValueNode <int>(ExtractIntegerValue.ParameterName, new IntegerDomain(-1, 3))); root.AddChild(new ValueNode <int>("quasi-continuous", new IntegerDomain(0, this._deConfiguration.MinimumDomainSize + 1))); root.AddChild(new ValueNode <double>("continuous", new ContinuousDomain(0, 1))); this._parameterTree = new ParameterTree(root); // Generate some genomes. this._genomeBuilder = new GenomeBuilder(this._parameterTree, this._completeConfiguration); var population = this.CreatePopulation(); var incumbent = this._genomeBuilder.CreateRandomGenome(age: 2); // Then setup a condition which only accepts a single value for the continuous parameter. this._genomeBuilder = new ConfigurableGenomeBuilder( this._parameterTree, isValidFunction: g => (double)g.GetGeneValue("continuous").GetValue() == 0.125, makeValidFunction: g => g.SetGene("continuous", new Allele <double>(0.125)), mutationRate: 0); // Try to create points. Due to the strict validity constraint, they will most likely use the repair // operation. var informationFlow = new LocalDifferentialEvolutionInformationFlow( this._deConfiguration, this._parameterTree, this._genomeBuilder); var points = informationFlow.DetermineInitialPoints(population, incumbent); // For each point not looking like the incumbent: Check it is valid. bool IndividualRepresentsIncumbent(GenomeSearchPoint point) { return(object.Equals(point.Genome.CreateMutableGenome().ToString(), incumbent.ToString())); } foreach (var point in points.Where(point => !IndividualRepresentsIncumbent(point))) { Assert.True(point.IsValid(), $"{point} is not valid."); } }
public void MutateRespectsMutationRate() { // Create genome builder with a mutation rate of 0.35. double mutationRate = 0.35; var configuration = new AlgorithmTunerConfiguration.AlgorithmTunerConfigurationBuilder() .SetMutationRate(mutationRate) .Build(maximumNumberParallelEvaluations: 1); var genomeBuilder = new GenomeBuilder(GenomeBuilderTest.BuildParameterTree(), configuration); // Create genome. var genome = GenomeBuilderTest.BuildFittingGenome(); // For a lot of iterations: IAllele oldGeneValue = genome.GetGeneValue(GenomeBuilderTest.ContinuousParameter); int changeCount = 0; int numberLoops = 1000; for (int i = 0; i < numberLoops; i++) { // Mutate the genome ... genomeBuilder.Mutate(genome); // ... compare the continuous parameter gene... IAllele newGeneValue = genome.GetGeneValue(GenomeBuilderTest.ContinuousParameter); if (!object.Equals(newGeneValue, oldGeneValue)) { changeCount++; } // ... and count the number of times it changes. oldGeneValue = newGeneValue; } // Finally compare the number of mutations with the expected number. double expectedNumberMutations = mutationRate * numberLoops; Assert.True( Math.Abs(expectedNumberMutations - changeCount) <= 0.1 * expectedNumberMutations, "Number of mutations was not as expected."); }