### Example XOR Configuration JSON Source: https://context7.com/colgreen/sharpneat/llms.txt A sample JSON file defining the configuration for a NEAT experiment. This file can be loaded by an `INeatExperimentFactory` implementation. ```json { "name": "Logical XOR", "isAcyclic": true, "activationFnName": "LeakyReLU", "populationSize": 150, "connectionWeightScale": 5.0, "degreeOfParallelism": 4, "evolutionAlgorithm": { "speciesCount": 10, "elitismProportion": 0.2, "selectionProportion": 0.2, "offspringAsexualProportion": 0.5, "offspringRecombinationProportion": 0.5 }, "asexualReproduction": { "connectionWeightMutationProbability": 0.94, "addNodeMutationProbability": 0.01, "addConnectionMutationProbability": 0.025, "deleteConnectionMutationProbability": 0.025 }, "complexityRegulationStrategy": { "strategyName": "absolute", "complexityCeiling": 10, "minSimplifcationGenerations": 10 } } ``` -------------------------------- ### Create NeatEvolutionAlgorithmFactory Source: https://context7.com/colgreen/sharpneat/llms.txt Use the factory to construct a fully-wired NeatEvolutionAlgorithm. You can create it with a fresh random population or from a previously saved population for warm starts. ```csharp using SharpNeat.Neat.EvolutionAlgorithm; // Option A: create with a fresh random population. var ea = NeatEvolutionAlgorithmFactory.CreateEvolutionAlgorithm(experiment); // Option B: create from a previously saved population (warm start). var metaGenome = experiment.CreateMetaNeatGenome(); var loader = new NeatPopulationLoader(metaGenome); List> savedGenomes = loader.LoadFromFolder("saved_population/"); var neatPop = NeatPopulationFactory.CreatePopulation( metaGenome, connectionsProportion: 0.05, popSize: experiment.PopulationSize); // (Replace neatPop.GenomeList with savedGenomes for a true warm start.) var eaFromSaved = NeatEvolutionAlgorithmFactory.CreateEvolutionAlgorithm(experiment, neatPop); Console.WriteLine("EA created. Population size: " + eaFromSaved.Population.GenomeList.Count); ``` -------------------------------- ### End-to-End XOR Evolution Run with SharpNeat Source: https://context7.com/colgreen/sharpneat/llms.txt A complete example of setting up and running a neuroevolution experiment for the XOR problem. It defines the experiment, creates the evolution algorithm, subscribes to progress updates, runs the algorithm, and saves the best genome. ```csharp using SharpNeat.Experiments; using SharpNeat.EvolutionAlgorithm.Runner; using SharpNeat.Neat.ComplexityRegulation; using SharpNeat.Neat.EvolutionAlgorithm; using SharpNeat.Neat.Genome.IO; using SharpNeat.Tasks.Xor; // 1. Define experiment. var experiment = new NeatExperiment( new XorEvaluationScheme(), "xor") { Name = "XOR", IsAcyclic = true, ActivationFnName = "LeakyReLU", PopulationSize = 150, DegreeOfParallelism = -1, ComplexityRegulationStrategy = new AbsoluteComplexityRegulationStrategy(10, 10) }; // 2. Create EA with fresh population. var ea = NeatEvolutionAlgorithmFactory.CreateEvolutionAlgorithm(experiment); var runner = new EvolutionAlgorithmRunner( ea, UpdateScheme.CreateGenerationalUpdateScheme(1)); // 3. Subscribe to progress. runner.UpdateEvent += (_, _) => { if(ea.Stats.StopConditionSatisfied) { Console.WriteLine($"SOLVED at generation {ea.Stats.Generation}!"); runner.RequestPause(); } }; // 4. Run until solved or 60 s elapsed. runner.StartOrResume(); Thread.Sleep(TimeSpan.FromSeconds(60)); if(runner.RunState == RunState.Running) runner.RequestPauseAndWait(); // 5. Save best genome. NeatGenomeSaver.Save(ea.Population.BestGenome, "xor_best.net"); Console.WriteLine($"Best fitness: {ea.Population.Stats.BestFitness.PrimaryFitness:F4}"); runner.Dispose(); ``` -------------------------------- ### Custom Evaluation Scheme for Threshold Task (C#) Source: https://context7.com/colgreen/sharpneat/llms.txt Implement IBlackBoxEvaluationScheme to define a custom problem task. This example teaches a network to output 1.0 when input > 0.5. Ensure your evaluator correctly implements the fitness calculation and stop condition. ```csharp // Custom evaluation scheme: teach a network to output 1.0 when input > 0.5. public sealed class ThresholdEvaluationScheme : IBlackBoxEvaluationScheme { public int InputCount => 2; // bias + 1 signal input public int OutputCount => 1; public bool IsDeterministic => true; public bool EvaluatorsHaveState => false; public IComparer FitnessComparer => PrimaryFitnessInfoComparer.Singleton; public FitnessInfo NullFitness => FitnessInfo.DefaultFitnessInfo; public IPhenomeEvaluator> CreateEvaluator() => new ThresholdEvaluator(); // Stop when fitness reaches 10.0 (perfect score). public bool TestForStopCondition(FitnessInfo fitnessInfo) => fitnessInfo.PrimaryFitness >= 10.0; } public sealed class ThresholdEvaluator : IPhenomeEvaluator> { public FitnessInfo Evaluate(IBlackBox box) { double fitness = 0.0; // Test input below threshold (expect output <= 0.5). box.Inputs.Span[0] = 1.0; // bias box.Inputs.Span[1] = 0.2; box.Activate(); double out1 = box.Outputs.Span[0]; fitness += 1.0 - (out1 * out1); // penalize high output box.Reset(); // Test input above threshold (expect output > 0.5). box.Inputs.Span[0] = 1.0; box.Inputs.Span[1] = 0.8; box.Activate(); double out2 = box.Outputs.Span[0]; fitness += 1.0 - Math.Pow(1.0 - out2, 2); // penalize low output if (out1 <= 0.5 && out2 > 0.5) fitness += 8.0; // bonus for correct classification return new FitnessInfo(fitness); } } ``` -------------------------------- ### Custom Evaluator Returning FitnessInfo Source: https://context7.com/colgreen/sharpneat/llms.txt Example of how a custom evaluator can return FitnessInfo, handling invalid genomes by returning default fitness. Ensures valid genomes receive a score. ```csharp // Use in a custom evaluator. public FitnessInfo Evaluate(IBlackBox box) { // ... run simulation ... double score = ComputeScore(box); return score < 0 ? FitnessInfo.DefaultFitnessInfo // zero fitness for invalid genomes : new FitnessInfo(score); } ``` -------------------------------- ### Implement INeatExperimentFactory for JSON Configuration Source: https://context7.com/colgreen/sharpneat/llms.txt Create a factory to load experiment settings from a JSON file. This allows for reusable experiment configurations. The factory must implement the `INeatExperimentFactory` interface and provide an `Id` and a `CreateExperiment` method. ```csharp // --- Factory implementation --- public sealed class XorExperimentFactory : INeatExperimentFactory { public string Id => "xor"; public INeatExperiment CreateExperiment(Stream jsonConfigStream) where TScalar : unmanaged, IBinaryFloatingPointIeee754 { ExperimentConfig config = JsonUtils.Deserialize(jsonConfigStream); var evalScheme = new XorEvaluationScheme(); var experiment = new NeatExperiment(evalScheme, Id) { IsAcyclic = true, ActivationFnName = ActivationFunctionId.LeakyReLU.ToString() }; experiment.Configure(config); return experiment; } } ``` -------------------------------- ### Programmatically Configure NeatExperiment Source: https://context7.com/colgreen/sharpneat/llms.txt Build an experiment configuration directly in C# code. This is useful for custom experiments or when fine-grained control is needed. Ensure all necessary namespaces are imported. ```csharp using SharpNeat.Experiments; using SharpNeat.Neat.ComplexityRegulation; // Build experiment programmatically. var evalScheme = new XorEvaluationScheme(); var experiment = new NeatExperiment(evalScheme, factoryId: "xor-custom") { Name = "XOR Custom", Description = "Evolves a network to solve logical XOR.", IsAcyclic = true, // feed-forward network ActivationFnName = "LeakyReLU", PopulationSize = 150, InitialInterconnectionsProportion = 0.05, ConnectionWeightScale = 5.0, DegreeOfParallelism = -1, // use all CPU cores // Complexity regulation: switch to simplifying when mean complexity > 10. ComplexityRegulationStrategy = new AbsoluteComplexityRegulationStrategy( minSimplifcationGenerations: 10, complexityCeiling: 10) }; // Override EA-level settings. experiment.EvolutionAlgorithmSettings.SpeciesCount = 10; experiment.EvolutionAlgorithmSettings.ElitismProportion = 0.2; experiment.EvolutionAlgorithmSettings.SelectionProportion = 0.2; experiment.EvolutionAlgorithmSettings.OffspringAsexualProportion = 0.5; experiment.EvolutionAlgorithmSettings.OffspringRecombinationProportion = 0.5; // Override mutation probabilities. experiment.AsexualReproductionSettings.ConnectionWeightMutationProbability = 0.94; experiment.AsexualReproductionSettings.AddNodeMutationProbability = 0.01; experiment.AsexualReproductionSettings.AddConnectionMutationProbability = 0.025; experiment.AsexualReproductionSettings.DeleteConnectionMutationProbability = 0.025; ``` -------------------------------- ### Usage: Create Experiment from JSON File Source: https://context7.com/colgreen/sharpneat/llms.txt Instantiate an experiment by providing a JSON configuration file to a registered factory. This demonstrates how to use the `XorExperimentFactory` to load experiment settings. ```csharp // --- Usage: create experiment from JSON file --- var factory = new XorExperimentFactory(); var experiment = factory.CreateExperiment("xor.config.json"); Console.WriteLine($"Loaded experiment: {experiment.Name}, pop={experiment.PopulationSize}"); ``` -------------------------------- ### NeatEvolutionAlgorithmSettings Configuration Source: https://context7.com/colgreen/sharpneat/llms.txt Sets hyperparameters for NEAT selection and reproduction, including species count, elitism, selection proportion, and mating probabilities. Always call Validate() after setting values. ```csharp using SharpNeat.Neat.EvolutionAlgorithm; var settings = new NeatEvolutionAlgorithmSettings { SpeciesCount = 10, ElitismProportion = 0.2, // keep top 20% of each species SelectionProportion = 0.2, // select parents from top 20% OffspringAsexualProportion = 0.5, // 50% of offspring via mutation only OffspringRecombinationProportion = 0.5, // 50% via crossover InterspeciesMatingProportion = 0.01, // 1% of crossovers are inter-species StatisticsMovingAverageHistoryLength = 100 }; settings.Validate(); // throws InvalidOperationException if sums != 1.0 ``` -------------------------------- ### Evolution Algorithm Runner with Time-Based Updates Source: https://context7.com/colgreen/sharpneat/llms.txt Initializes and runs the EA using a time-based update scheme, logging generation progress periodically. Ensures proper disposal of resources. ```csharp // Use time-based scheme in the runner. var ea = NeatEvolutionAlgorithmFactory.CreateEvolutionAlgorithm(experiment); var runner = new EvolutionAlgorithmRunner(ea, timeScheme); runner.UpdateEvent += (_, _) => Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] Gen {ea.Stats.Generation}"); runner.StartOrResume(); Thread.Sleep(TimeSpan.FromSeconds(15)); runner.RequestTerminateAndWait(); runner.Dispose(); ``` -------------------------------- ### EvolutionAlgorithmRunner Background Execution Source: https://context7.com/colgreen/sharpneat/llms.txt Wrap an IEvolutionAlgorithm in a runner for background thread execution with start/pause/resume/terminate control. Subscribe to UpdateEvent for progress callbacks. ```csharp using SharpNeat.EvolutionAlgorithm.Runner; // Create EA (see above), then wrap it in a runner. var ea = NeatEvolutionAlgorithmFactory.CreateEvolutionAlgorithm(experiment); var scheme = UpdateScheme.CreateGenerationalUpdateScheme(generations: 1); var runner = new EvolutionAlgorithmRunner(ea, scheme); // Subscribe to progress updates. runner.UpdateEvent += (sender, _) => { var stats = ea.Stats; Console.WriteLine( $"Gen {stats.Generation,6} | " + $"Best fitness: {ea.Population.Stats.BestFitness.PrimaryFitness:F4} | " + $"Species: {((NeatEvolutionAlgorithmStatistics)stats).TotalOffspringCount} offspring | " + $"Stop: {stats.StopConditionSatisfied}"); if(stats.StopConditionSatisfied) runner.RequestPause(); }; // Start evolution on background thread. runner.StartOrResume(); // Wait for stop condition or timeout. Thread.Sleep(TimeSpan.FromSeconds(30)); runner.RequestPauseAndWait(); Console.WriteLine($"Final generation: {ea.Stats.Generation}"); runner.Dispose(); ``` -------------------------------- ### NeatEvolutionAlgorithmSettings Source: https://context7.com/colgreen/sharpneat/llms.txt Holds all NEAT selection and reproduction hyperparameters. Values can be set directly or overridden via JSON configuration. Call Validate() before use to catch misconfigured proportions. ```APIDOC ## NeatEvolutionAlgorithmSettings — EA Hyperparameters A `record` type holding all NEAT selection and reproduction hyperparameters. Values can be set directly or overridden via JSON configuration. Call `Validate()` before use to catch misconfigured proportions. ```csharp using SharpNeat.Neat.EvolutionAlgorithm; var settings = new NeatEvolutionAlgorithmSettings { SpeciesCount = 10, ElitismProportion = 0.2, // keep top 20% of each species SelectionProportion = 0.2, // select parents from top 20% OffspringAsexualProportion = 0.5, // 50% of offspring via mutation only OffspringRecombinationProportion = 0.5, // 50% via crossover InterspeciesMatingProportion = 0.01, // 1% of crossovers are inter-species StatisticsMovingAverageHistoryLength = 100 }; settings.Validate(); // throws InvalidOperationException if sums != 1.0 // Obtain simplifying-mode variant (forces 100% asexual reproduction). NeatEvolutionAlgorithmSettings simplifyingSettings = settings.CreateSimplifyingSettings(); Console.WriteLine($"Simplifying asexual proportion: {simplifyingSettings.OffspringAsexualProportion}"); // Output: Simplifying asexual proportion: 1 ``` ``` -------------------------------- ### NeatPopulationSaver / NeatPopulationLoader Source: https://context7.com/colgreen/sharpneat/llms.txt Save and reload entire populations (collections of genomes) to either a folder of .net files or a single .zip archive. Useful for checkpointing long-running experiments and warm-starting subsequent runs. ```csharp using SharpNeat.Neat.Genome.IO; using System.IO.Compression; // --- Save whole population to a folder --- IList> genomes = ea.Population.GenomeList; NeatPopulationSaver.SaveToFolder(genomes, parentPath: "checkpoints/", name: "gen_1000"); // Creates: checkpoints/gen_1000/000000.net, 000001.net, ... // --- Save population to a zip archive --- NeatPopulationSaver.SaveToZipArchive(genomes, "checkpoints/gen_1000", CompressionLevel.Fastest); // Creates: checkpoints/gen_1000.zip // --- Load population back from folder --- MetaNeatGenome meta = experiment.CreateMetaNeatGenome(); var popLoader = new NeatPopulationLoader(meta); List> loaded = popLoader.LoadFromFolder("checkpoints/gen_1000"); Console.WriteLine($"Loaded {loaded.Count} genomes from folder."); // --- Load population from zip archive --- List> fromZip = popLoader.LoadFromZipArchive("checkpoints/gen_1000.zip"); Console.WriteLine($"Loaded {fromZip.Count} genomes from archive."); ``` -------------------------------- ### CreateSimplifyingSettings Variant Source: https://context7.com/colgreen/sharpneat/llms.txt Obtains a variant of the current EA settings that forces 100% asexual reproduction, suitable for simplification-focused runs. ```csharp // Obtain simplifying-mode variant (forces 100% asexual reproduction). NeatEvolutionAlgorithmSettings simplifyingSettings = settings.CreateSimplifyingSettings(); Console.WriteLine($ ``` -------------------------------- ### Activate and Reset Neural Network (C#) Source: https://context7.com/colgreen/sharpneat/llms.txt Manually activate a decoded neural network and read its outputs. Remember to reset the network's internal state before reuse, especially for recurrent networks. ```csharp using IBlackBox box = decodedNetwork; // obtained from NeatGenomeDecoderFactory var inputs = box.Inputs.Span; var outputs = box.Outputs.Span; // Bias node is always inputs[0] = 1.0 by convention. inputs[0] = 1.0; // bias inputs[1] = 0.0; // XOR input A inputs[2] = 1.0; // XOR input B box.Activate(); double result = outputs[0]; // expected near 1.0 for XOR(0,1) Console.WriteLine($"XOR(0,1) = {result:F4}"); // Reset internal state before reuse (important for cyclic/recurrent nets). box.Reset(); ``` -------------------------------- ### NeatGenomeSaver / NeatGenomeLoader Source: https://context7.com/colgreen/sharpneat/llms.txt Serialize and deserialize individual NeatGenome instances to/from .net format files or streams. The .net format is a compact text format. ```csharp using SharpNeat.Neat.Genome.IO; // --- Save the best genome after a run --- NeatGenome bestGenome = ea.Population.BestGenome; NeatGenomeSaver.Save(bestGenome, "best_genome.net"); Console.WriteLine("Genome saved."); // --- Load it back --- MetaNeatGenome meta = experiment.CreateMetaNeatGenome(); NeatGenome loaded = NeatGenomeLoader.Load("best_genome.net", meta, genomeId: 0); Console.WriteLine($"Loaded genome ID={loaded.Id}, connections={loaded.ConnectionGenes._connArr.Length}"); // --- Save/load via stream (e.g., MemoryStream for in-memory transfer) --- using var ms = new MemoryStream(); NeatGenomeSaver.Save(bestGenome, ms); ms.Position = 0; NeatGenome fromStream = NeatGenomeLoader.Load(ms, meta, genomeId: 1); ``` -------------------------------- ### Create MetaNeatGenome for Acyclic and Cyclic Networks Source: https://context7.com/colgreen/sharpneat/llms.txt Demonstrates creating genome metadata for acyclic (feed-forward) and cyclic (recurrent) networks. Requires specifying input/output node counts and activation functions. Cyclic networks also require cycles per activation. ```csharp using SharpNeat.Neat.Genome; using SharpNeat.NeuralNets.ActivationFunctions; // Create metadata for an acyclic (feed-forward) network with 3 inputs, 1 output. var actFnFactory = new DefaultActivationFunctionFactory( enableHardwareAcceleration: false); var activationFn = actFnFactory.GetActivationFunction("LeakyReLU"); MetaNeatGenome metaAcyclic = MetaNeatGenome.CreateAcyclic( inputNodeCount: 3, outputNodeCount: 1, activationFn: activationFn, connectionWeightScale: 5.0); // Create metadata for a cyclic (recurrent) network, 2 activation cycles per step. MetaNeatGenome metaCyclic = MetaNeatGenome.CreateCyclic( inputNodeCount: 4, outputNodeCount: 2, cyclesPerActivation: 2, activationFn: activationFn); Console.WriteLine($"Acyclic I/O: {metaAcyclic.InputNodeCount}/{metaAcyclic.OutputNodeCount}"); Console.WriteLine($"Cyclic cycles/activation: {metaCyclic.CyclesPerActivation}"); // Used by NeatGenomeLoader and NeatEvolutionAlgorithmFactory to validate compatibility. ``` -------------------------------- ### Time-Based Update Scheme Source: https://context7.com/colgreen/sharpneat/llms.txt Creates a scheme that fires update events at a specified time interval. Useful for real-time monitoring or time-limited runs. ```csharp // Fire update event every 5 seconds of wall-clock time. var timeScheme = UpdateScheme.CreateTimeSpanUpdateScheme(TimeSpan.FromSeconds(5)); ``` -------------------------------- ### AbsoluteComplexityRegulationStrategy Configuration Source: https://context7.com/colgreen/sharpneat/llms.txt Configures the EA to oscillate between complexifying and simplifying modes based on a fixed complexity ceiling. Set the minimum generations for simplification before reverting. ```csharp using SharpNeat.Neat.ComplexityRegulation; // Allow up to 10 connections on average; spend at least 10 generations simplifying // before switching back to complexifying. var strategy = new AbsoluteComplexityRegulationStrategy( minSimplifcationGenerations: 10, complexityCeiling: 10.0); // Assign to experiment before creating the EA. experiment.ComplexityRegulationStrategy = strategy; // Inspect current mode during a run (read-only). Console.WriteLine($"Regulation mode: {strategy.CurrentMode}"); // Output: "Regulation mode: Complexifying" (or Simplifying) ``` -------------------------------- ### IBlackBoxEvaluationScheme - Task Definition Source: https://context7.com/colgreen/sharpneat/llms.txt Defines a problem task for SharpNEAT. Implement this interface to create custom evaluation schemes and specify stopping conditions. ```APIDOC ## IBlackBoxEvaluationScheme - Task Definition Interface ### Description Defines a problem task that SharpNEAT will evolve a solution for. Implement this interface to create custom tasks. The key method is `CreateEvaluator()`, which returns an `IPhenomeEvaluator>` instance. `TestForStopCondition` signals when a satisfactory solution has been found. ### Custom Evaluation Scheme Example (ThresholdEvaluationScheme) ```csharp // Custom evaluation scheme: teach a network to output 1.0 when input > 0.5. public sealed class ThresholdEvaluationScheme : IBlackBoxEvaluationScheme { public int InputCount => 2; // bias + 1 signal input public int OutputCount => 1; public bool IsDeterministic => true; public bool EvaluatorsHaveState => false; public IComparer FitnessComparer => PrimaryFitnessInfoComparer.Singleton; public FitnessInfo NullFitness => FitnessInfo.DefaultFitnessInfo; public IPhenomeEvaluator> CreateEvaluator() => new ThresholdEvaluator(); // Stop when fitness reaches 10.0 (perfect score). public bool TestForStopCondition(FitnessInfo fitnessInfo) => fitnessInfo.PrimaryFitness >= 10.0; } public sealed class ThresholdEvaluator : IPhenomeEvaluator> { public FitnessInfo Evaluate(IBlackBox box) { double fitness = 0.0; // Test input below threshold (expect output <= 0.5). box.Inputs.Span[0] = 1.0; // bias box.Inputs.Span[1] = 0.2; box.Activate(); double out1 = box.Outputs.Span[0]; fitness += 1.0 - (out1 * out1); // penalize high output box.Reset(); // Test input above threshold (expect output > 0.5). box.Inputs.Span[0] = 1.0; box.Inputs.Span[1] = 0.8; box.Activate(); double out2 = box.Outputs.Span[0]; fitness += 1.0 - Math.Pow(1.0 - out2, 2); // penalize low output if (out1 <= 0.5 && out2 > 0.5) fitness += 8.0; // bonus for correct classification return new FitnessInfo(fitness); } } ``` ### Methods - **CreateEvaluator()**: Returns an instance of `IPhenomeEvaluator>` for evaluating network performance. - **TestForStopCondition(FitnessInfo fitnessInfo)**: Determines if the evolution process should terminate based on the provided fitness information. ``` -------------------------------- ### IBlackBox - Neural Network Interface Source: https://context7.com/colgreen/sharpneat/llms.txt Represents an activated neural network. Users can set inputs, activate the network, and read outputs. Remember to reset the box for recurrent networks. ```APIDOC ## IBlackBox - Neural Network Interface ### Description The central abstraction representing an activated neural network (or any black-box function). Callers write to `Inputs`, call `Activate()`, then read from `Outputs`. The generic parameter `T` is typically `double` or `float`. ### Usage Example ```csharp // Obtain a black box by decoding a NeatGenome (done internally by the evaluator pipeline). // Direct usage example — manually activate a decoded network: using IBlackBox box = decodedNetwork; // obtained from NeatConsole.NeatGenomeDecoderFactory var inputs = box.Inputs.Span; var outputs = box.Outputs.Span; // Bias node is always inputs[0] = 1.0 by convention. inputs[0] = 1.0; // bias inputs[1] = 0.0; // XOR input A inputs[2] = 1.0; // XOR input B box.Activate(); double result = outputs[0]; // expected near 1.0 for XOR(0,1) Console.WriteLine($"XOR(0,1) = {result:F4}"); // Reset internal state before reuse (important for cyclic/recurrent nets). box.Reset(); ``` ### Methods - **Activate()**: Computes the network's output based on current inputs. - **Reset()**: Resets the internal state of the network (crucial for recurrent networks). ### Properties - **Inputs**: A span representing the network's input nodes. - **Outputs**: A span representing the network's output nodes. ``` -------------------------------- ### No Update Scheme Source: https://context7.com/colgreen/sharpneat/llms.txt Creates a scheme that disables update events entirely. Suitable for headless batch mode execution where progress reporting is not needed. ```csharp // Disable update events entirely (headless batch mode). var noScheme = UpdateScheme.CreateNoUpdateScheme(); ``` -------------------------------- ### FitnessInfo Compound Score Source: https://context7.com/colgreen/sharpneat/llms.txt Creates a FitnessInfo object with a primary score and auxiliary scores for additional reporting. Auxiliary scores can represent metrics like accuracy or steps taken. ```csharp // Compound fitness: primary score + auxiliary reporting values. var compound = new FitnessInfo( primaryFitness: 9.87, auxFitnessScores: new[] { 0.95, 120.0 }); // e.g. accuracy, steps Console.WriteLine($ ``` -------------------------------- ### Generational Update Scheme Source: https://context7.com/colgreen/sharpneat/llms.txt Creates a scheme that fires update events every N generations. Used to control the frequency of progress reporting in the EA runner. ```csharp using SharpNeat.EvolutionAlgorithm.Runner; // Fire update event every 10 generations. var genScheme = UpdateScheme.CreateGenerationalUpdateScheme(generations: 10); ``` -------------------------------- ### UpdateScheme Source: https://context7.com/colgreen/sharpneat/llms.txt Controls the frequency at which EvolutionAlgorithmRunner fires its UpdateEvent. Three factory methods create no-update, generational, and time-based schemes. ```APIDOC ## UpdateScheme — Progress Event Scheduling Controls the frequency at which `EvolutionAlgorithmRunner` fires its `UpdateEvent`. Three factory methods create no-update, generational, and time-based schemes. ```csharp using SharpNeat.EvolutionAlgorithm.Runner; // Fire update event every 10 generations. var genScheme = UpdateScheme.CreateGenerationalUpdateScheme(generations: 10); // Fire update event every 5 seconds of wall-clock time. var timeScheme = UpdateScheme.CreateTimeSpanUpdateScheme(TimeSpan.FromSeconds(5)); // Disable update events entirely (headless batch mode). var noScheme = UpdateScheme.CreateNoUpdateScheme(); // Use time-based scheme in the runner. var ea = NeatEvolutionAlgorithmFactory.CreateEvolutionAlgorithm(experiment); var runner = new EvolutionAlgorithmRunner(ea, timeScheme); runner.UpdateEvent += (_, _) => Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] Gen {ea.Stats.Generation}"); runner.StartOrResume(); Thread.Sleep(TimeSpan.FromSeconds(15)); runner.RequestTerminateAndWait(); runner.Dispose(); ``` ``` -------------------------------- ### RelativeComplexityRegulationStrategy Configuration Source: https://context7.com/colgreen/sharpneat/llms.txt Configures complexity regulation using a relative ceiling based on the initial mean population complexity. The ceiling is a multiplier of the initial mean. ```csharp // Relative strategy: ceiling = initial_mean_complexity * factor (e.g. 1.5×). var relativeStrategy = new RelativeComplexityRegulationStrategy( minSimplifcationGenerations: 10, relativeComplexityCeiling: 3); // ceiling = initialMean + 3 experiment.ComplexityRegulationStrategy = relativeStrategy; ``` -------------------------------- ### FitnessInfo Primary Score Source: https://context7.com/colgreen/sharpneat/llms.txt Creates an immutable FitnessInfo object with a single primary fitness score. This is the most common way to represent a genome's performance. ```csharp using SharpNeat.Evaluation; // Single fitness value (most common case). var fitness = new FitnessInfo(primaryFitness: 9.87); Console.WriteLine($ ``` -------------------------------- ### AbsoluteComplexityRegulationStrategy Source: https://context7.com/colgreen/sharpneat/llms.txt Manages the EA's complexity by oscillating between complexifying and simplifying modes. Transitions to simplifying when mean population complexity exceeds a ceiling and reverts to complexifying when simplification stalls. ```APIDOC ## AbsoluteComplexityRegulationStrategy — Complexity Control Automatically oscillates the EA between *complexifying* (adding nodes/connections) and *simplifying* (removing connections) modes to prevent genome bloat. Transitions to simplifying when mean population complexity exceeds a fixed ceiling, and reverts to complexifying when simplification stalls. ```csharp using SharpNeat.Neat.ComplexityRegulation; // Allow up to 10 connections on average; spend at least 10 generations simplifying // before switching back to complexifying. var strategy = new AbsoluteComplexityRegulationStrategy( minSimplifcationGenerations: 10, complexityCeiling: 10.0); // Assign to experiment before creating the EA. experiment.ComplexityRegulationStrategy = strategy; // Inspect current mode during a run (read-only). Console.WriteLine($"Regulation mode: {strategy.CurrentMode}"); // Output: "Regulation mode: Complexifying" (or Simplifying) ``` ``` -------------------------------- ### FitnessInfo Source: https://context7.com/colgreen/sharpneat/llms.txt An immutable struct carrying a primary fitness score and optional auxiliary scores. Evaluators return FitnessInfo from Evaluate(); the EA ranks genomes by PrimaryFitness via the scheme's FitnessComparer. ```APIDOC ## FitnessInfo — Fitness Score Container Immutable struct carrying a primary fitness score and optional auxiliary scores. Evaluators return `FitnessInfo` from `Evaluate()`; the EA ranks genomes by `PrimaryFitness` via the scheme's `FitnessComparer`. ```csharp using SharpNeat.Evaluation; // Single fitness value (most common case). var fitness = new FitnessInfo(primaryFitness: 9.87); Console.WriteLine($"Fitness: {fitness.PrimaryFitness}"); // 9.87 // Compound fitness: primary score + auxiliary reporting values. var compound = new FitnessInfo( primaryFitness: 9.87, auxFitnessScores: new[] { 0.95, 120.0 }); // e.g. accuracy, steps Console.WriteLine($"Aux[0]: {compound.AuxFitnessScores![0]}"); // 0.95 // Use in a custom evaluator. public FitnessInfo Evaluate(IBlackBox box) { // ... run simulation ... double score = ComputeScore(box); return score < 0 ? FitnessInfo.DefaultFitnessInfo // zero fitness for invalid genomes : new FitnessInfo(score); } ``` ``` -------------------------------- ### RelativeComplexityRegulationStrategy Source: https://context7.com/colgreen/sharpneat/llms.txt A complexity regulation strategy where the ceiling is a factor of the initial mean population complexity. ```APIDOC ```csharp // Relative strategy: ceiling = initial_mean_complexity * factor (e.g. 1.5×). var relativeStrategy = new RelativeComplexityRegulationStrategy( minSimplifcationGenerations: 10, relativeComplexityCeiling: 3); // ceiling = initialMean + 3 experiment.ComplexityRegulationStrategy = relativeStrategy; ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.