private object InnerGet(Type expectType, bool autoResolving, params object[] lastMappingValues) { if (expectType == null) { throw new ArgumentNullException(nameof(expectType)); } using (GA.Lock(this.UUID + expectType.AssemblyQualifiedName)) { var callSite = GetCallSite(this, expectType); if (callSite == null && autoResolving) { callSite = this.AutoResolving(expectType, null); if (callSite == null) { return(null); } CacheType.TryAdd(expectType, new List <ICallSite>(1) { callSite }); } return(callSite?.Invoke(lastMappingValues)); } }
public void Remove(Type expectType, string name, bool promote = false) { if (expectType == null) { throw new ArgumentNullException(nameof(expectType)); } if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException(nameof(name)); } ConcurrentDictionary <string, ICallSite> dict; using (GA.Lock(expectType)) { if (CacheTypeName.TryGetValue(expectType, out dict)) { ICallSite callSite; dict.TryRemove(name, out callSite); } } if (this._hasParent && promote) { this.Parent.Remove(expectType, name, promote); } }
private static void SumTo50() { Console.WriteLine("Sum to 50:..."); GA ga = new GA( 20, // Number of individuals 3, // Number of genes in the genotype individual => // Fitness function Math.Abs(50 - individual.Genotype.Sum(val => val)) ); ga.RunEpoch( 500, // Number of generations to run for null, // Action to perform for each generation () => // Action to perform once fitness has improved { Console.WriteLine( "Gen {2}: Fit={1}, Genotype={0}", string.Join( " ", ga.BestIndividual.Genotype.Select(val => val.ToString("0.00"))), ga.BestIndividual.Fitness.ToString("0.00"), ga.CurrentEpochGeneration); }); Console.WriteLine("Sum to 5: done!"); Console.WriteLine(""); }
private static void Find12345() { Console.WriteLine("Find 1 2 3 4 5:..."); GA ga = new GA( 200, // Number of individuals 5, // Number of genes in the genotype individual => // Fitness function Math.Abs(individual.Genotype[0] - 1) + Math.Abs(individual.Genotype[1] - 2) + Math.Abs(individual.Genotype[2] - 3) + Math.Abs(individual.Genotype[3] - 4) + Math.Abs(individual.Genotype[4] - 5)); ga.RunEpoch(500, null, () => { Console.WriteLine( "Gen {2}: Fit={1}, Genotype={0}", string.Join( " ", ga.BestIndividual.Genotype.Select( val => val.ToString("0.00"))), ga.BestIndividual.Fitness.ToString("0.00"), ga.CurrentEpochGeneration); }); Console.WriteLine("Find 1 2 3 4 5: done!"); Console.WriteLine(""); }
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { if (e.ExceptionObject is Exception) { GA.OnGlobalError(sender, e.ExceptionObject as Exception); } else { WriteUnhandledException("应用崩溃了:{0}", e.ExceptionObject); } }
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { //System.Runtime.CompilerServices.RuntimeWrappedException if (e.ExceptionObject is Exception) { GA.OnGlobalError(sender, e.ExceptionObject as Exception); } else { WriteUnhandledException("应用崩溃了:{0}", e.ExceptionObject); } }
public void FindProjectionMatrix() { List<WorldToScreenCase> cases = new List<WorldToScreenCase> { new WorldToScreenCase(688, 349, 0,0 ,0), // 1 new WorldToScreenCase(454, 155, 52.5,0,0), // 2 new WorldToScreenCase(353, 70, 105,0,0), // 3 new WorldToScreenCase(127, 169, 52.5, 34,0), // 4 new WorldToScreenCase(155, 411, 0, 34,0), // 5 new WorldToScreenCase(220, 364, 0, 34 - 7.32*0.5, 2.44), // 6 new WorldToScreenCase(80, 378, 0, 34+7.32*0.5,2.44), // 7 new WorldToScreenCase(92, 57, 105, 34 + 7.32*0.5, 2.44), // 8 new WorldToScreenCase(145, 56, 105, 34-7.32*0.5,2.44), // 9 }; GA ga = new GA( 5000, // Number of individuals 16, // Number of genes in the genotype individual => // Fitness function { double errorSum = 0; foreach (WorldToScreenCase test in cases) { Point3D testScreen = ProjectCase(test.World, individual.Genotype); double sqrError = (testScreen - test.Screen).LengthSquared; errorSum += sqrError; } return errorSum; }); ga.RunEpoch(100000, () => { ga.BreakEpochRun = ga.BestIndividual.Fitness <= 1.0 || stopButton.Enabled == false; Application.DoEvents(); }, () => { generationLabel.Text = string.Format( "Gen {2}: Fit={1}, Genotype={0}", string.Join( " ", ga.BestIndividual.Genotype.Select(val => val.ToString("0.00"))), ga.BestIndividual.Fitness.ToString("0.00"), ga.CurrentEpochGeneration); DrawCasesToBitmap(cases, ga.BestIndividual.Genotype); }); }
static void Main(string[] args) { GA Ga; TravellingSalesman1dObjective Objective; Galib.Mutation.IntegerSwapMutator Mutator; IntegerChromosomeSpecifier ChromosomeSpecifier; // // Create the objective. // int[] cities = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; Objective = new TravellingSalesman1dObjective(cities); // // Create the mutator // Mutator = new Galib.Mutation.IntegerSwapMutator(); // // Create the chromosome specifier. // ChromosomeSpecifier = new IntegerChromosomeSpecifier(); ChromosomeSpecifier.Length = numberOfCities; ChromosomeSpecifier.MinValue = 0; ChromosomeSpecifier.MaxValue = numberOfCities; ChromosomeSpecifier.PositionDependent = true; // // Create the recombinator // Galib.Recombination.PartiallyMatchedRecombinator Recombinator; Recombinator = new Galib.Recombination.PartiallyMatchedRecombinator(); Ga = new GA(); Ga.PopulationSize = 100; Ga.Mutator = Mutator; Ga.ChromosomeSpecifier = ChromosomeSpecifier; Ga.Objective = Objective; Ga.InvertedObjective = true; Ga.Recombinator = Recombinator; Ga.MaxGenerations = 500; Ga.Run(); Console.WriteLine("Best Individual:"); Console.WriteLine( Ga.Population.BestChromosome ); Console.WriteLine("Finished. Hit return."); Console.ReadLine(); }
/// <summary> /// 如果结果出现异常则抛出错误,否则不做任何处理。 /// </summary> /// <typeparam name="TResult">结果的数据类型。</typeparam> /// <param name="result"><see cref="System.Result"/> 的派生类实例。</param> public static TResult ThrowIfFailded <TResult>(this TResult result) where TResult : Result { if (result == null) { throw new ArgumentNullException("result"); } if (result.IsFailed) { GA.OnGlobalError(result, result.Exception); throw result.Exception; } return(result); }
private static void OnceInvoke(object state) { AsyncJob tme = state as AsyncJob; if (tme.WaitForNextTask()) { return; } try { tme.RunTask(); } catch (Exception ex) { GA.OnGlobalError(tme, ex); throw; } }
/// <summary> /// 写入未捕获的异常。该异常不记录到日志管理器,而是独立出一个 LogError{yyyy-MM-dd}.txt 文件。 /// </summary> /// <param name="message">复合格式的错误消息。</param> /// <param name="args">一个对象数组,其中包含零个或多个要设置格式的对象。</param> public static void WriteUnhandledException(string message, params object[] args) { var path = GA.IsWebRuntime ? System.Web.Webx.MapUrl("~/LogError" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt") : GA.FullPath("LogError" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt"); System.IO.File.AppendAllText(path, DateTime.Now + " " + string.Format(message, args)); }
private void ShowTestResult(GA ga, WorldToScreenCase test) { Point3D p = ProjectCase(test.World, ga.BestIndividual.Genotype); }
public static extern HWND GetAncestor(HWND hwnd, GA gaFlags);
public static extern IntPtr GetAncestor(IntPtr hWnd, GA gaFlags);
/// <summary> /// 创建一个模拟对象。 /// </summary> /// <typeparam name="TModel">对象的数据类型。</typeparam> /// <returns>要一个模拟的对象。</returns> protected virtual TModel CreateMock <TModel>() => GA.CreateMockModel <TModel>();
private void bw_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; GaTask task = (GaTask)e.Argument; try { task.ProgressPercent = 0; task.State = TaskState.Launched; task.LaunchTime = DateTime.Now; IList<IIndividual<Wrapper<LearningObject>>> individualsList = new List<IIndividual<Wrapper<LearningObject>>>(); //Individuals initializing for (int i = 0; i < task.GaConfigs.PopulationSize; i++) { //Wrap source LOs to pass to GA //List<Wrapper<LearningObject>> wrappedListOfLo = new List<Wrapper<LearningObject>>(); = task.SourceLearningObjects.Select(sourceLearningObject => new Wrapper<LearningObject>(GAUtils.GetProbability(0.5), sourceLearningObject)).ToList(); List<Wrapper<LearningObject>> wrappedListOfLo = new List<Wrapper<LearningObject>>(); foreach (var sourceLearningObject in task.SourceLearningObjects) { wrappedListOfLo.Add(new Wrapper<LearningObject>(GAUtils.GetProbability(0.5), sourceLearningObject)); } wrappedListOfLo = GAUtils.Shuffle(wrappedListOfLo).ToList(); individualsList.Add(new Individual<Wrapper<LearningObject>>(wrappedListOfLo)); } var population = new Population<Wrapper<LearningObject>>(individualsList, IndividualEvaluateFunc, MutationFunc, CrossoverFunc, SelectionFunc); IGeneticAlgorithm<Wrapper<LearningObject>> ga = new GA<Wrapper<LearningObject>>(population); IGAconfiguration configuration = new GAConfiguration(task.GaConfigs.GAIterationsNumber, task.GaConfigs.MutationProbability, task.GaConfigs.MutationPeriod, task.GaConfigs.CrossoverProbability, task.GaConfigs.ElitismPercentage); ga.Run(StopCondition, configuration, task.Id, worker); if (worker != null && worker.CancellationPending) { task.State = TaskState.Cancelled; e.Result = task; } else { task.State = TaskState.Finished; } if (task.State == TaskState.Finished) { if (worker != null) worker.ReportProgress(100, task.Id); } //Put result data to task task.AverageFFvalues = ga.Statistics.AverageFitnessFunctionValues; task.BestFfValues = ga.Statistics.BestFitnessFunctionValues; task.WorstFfValues = ga.Statistics.WorstFitnessFunctionValues; List<LearningObject> resultList = new List<LearningObject>(); foreach (var wrapper in ga.BestIndividual.Chromosome.Genes) { if (wrapper.Used) { resultList.Add(wrapper.Value); } } task.ResultLearningObjects = resultList; e.Result = task; } catch (Exception ex) { Console.WriteLine(ex.Message); task.State = TaskState.Error; task.ErrorMessage = ex.Message; e.Result = task; } }
public static void FindProjectionMatrix() { List<WorldToScreenCase> cases = new List<WorldToScreenCase> { // New image /*new WorldToScreenCase(690, 350, 0, 0), new WorldToScreenCase(455, 155, 105*0.5, 0), new WorldToScreenCase(353, 70, 105, 0), new WorldToScreenCase(128, 169, 105*0.5, 68*0.5), new WorldToScreenCase(153, 412, 0, 68*0.5),*/ // Old Image new WorldToScreenCase(165,178 , 0, 0), new WorldToScreenCase(377,120 , 52.5, 0), new WorldToScreenCase(513,85 , 105, 0), new WorldToScreenCase(473,157 , 52.5, 34), new WorldToScreenCase(611,208 , 52.5, 68), new WorldToScreenCase(735,136 , 105, 68), }; GA ga = new GA( 2000, // Number of individuals 16, // Number of genes in the genotype individual => // Fitness function { double errorSum = 0; foreach (WorldToScreenCase test in cases) { Point3D testScreen = ProjectCase(test.World, individual.Genotype); double sqrError = (testScreen - test.Screen).LengthSquared; errorSum += sqrError; } return errorSum; }); ga.RunEpoch(10000, () => { ga.BreakEpochRun = ga.BestIndividual.Fitness <= 1.0 || Console.KeyAvailable; }, () => { Console.WriteLine( "Gen {2}: Fit={1}, Genotype={0}", string.Join( " ", ga.BestIndividual.Genotype.Take(5).Select( val => val.ToString("0.00"))), ga.BestIndividual.Fitness.ToString("0.00"), ga.CurrentEpochGeneration); }); if (Console.KeyAvailable) { Console.ReadKey(); } Console.WriteLine("Results for training set:"); foreach (WorldToScreenCase test in cases) { ShowTestResult(ga, test); } Console.WriteLine(""); Console.WriteLine("Additional tests:"); ShowTestResult(ga, new WorldToScreenCase(120, 73, 105, 34)); Console.WriteLine("Find ProjectionMatrix: done!"); Console.WriteLine(""); }
private static void ShowTestResult(GA ga, WorldToScreenCase test) { Point3D p = ProjectCase(test.World, ga.BestIndividual.Genotype); Console.WriteLine( " World ({0:0.00}, {1:0.00}) => \n" + " Wanted:({2:0.00}, {3:0.00}) \n" + " Received:({4:0.00}, {5:0.00})", test.World.X, test.World.Y, test.Screen.X, test.Screen.Y, p.X, p.Y); }
private void Hoskin(int n, double L, double H, bool cum, double startPoint, double volatiles) { int m = n;// (int)Math.Pow(n, 2); double[] phi=new double[m]; double[] cov = new double[m]; double[] psi = new double[m]; double[] output = new double[m]; double[] output2 = new double[m]; while (true) { double v = 1; output[0]=snorm(); phi[0]=0; for (int i = 0; i < m; i++) cov[i]=covariance(i, H); /* simulation */ for (int i = 1; i < m; i++) { phi[i - 1] = cov[i]; for (int j = 0; j < i - 1; j++) { psi[j] = phi[j]; phi[i - 1] -= psi[j] * cov[i - j - 1]; } phi[i - 1] /= v; for (int j = 0; j < i - 1; j++) { phi[j] = psi[j] - phi[i - 1] * psi[i - j - 2]; } v *= (1 - phi[i - 1] * phi[i - 1]); output[i] = 0; for (int j = 0; j < i; j++) { output[i] += phi[j] * output[i - j - 1]; } output[i] += Math.Sqrt(v) * snorm(); } /* rescale to obtain a sample of size 2^(*n) on [0,L] */ double scaling = Math.Pow(L / m, H); for (int i = 0; i < m; i++) { output2[i] = scaling * (output[i]); if (cum && i > 0) { output2[i] += output[i - 1]; } } //Start the stopwatch Stopwatch s = new Stopwatch(); s.Start(); //Set up the Model List<double>outputv=new List<double>(); List<double>outputv2=new List<double>(); for (int i = 0; i < m; i++) { outputv.Add(output[i]); outputv2.Add(output2[i]); } Model model = new Model(startPoint, H, outputv, outputv2, startPoint + 0.01000, m, volatiles); //Set up the GA and run it Int32 threads = 10; GA ga = new GA(model,threads, 0.8, 0.0005, 1000); ga.Go(); //=============================================================================================== //In this example we have set the model, progress reporter delegate (which is optional), number //of threads, crossover rate, mutation rate, population size, number of generations //=============================================================================================== //Get the results s.Stop(); Console.WriteLine(); Console.WriteLine("Optimisation run finished in " + s.ElapsedMilliseconds.ToString() + " ms."); double[] bestGenes; double bestFitness; ga.GetBest(out bestGenes, out bestFitness); if (bestFitness > 0.1) { double old_price = startPoint;//clo->stock_price; double old_volatilities = volatiles; //bestGenes[0];//clo->variance; double mean_reversion_rate = bestGenes[0] / 10000000; double mean_reversion_level = bestGenes[1] / 1000000; double dt = bestGenes[2] / 10000000; double variance_variance = bestGenes[3] / 10000000; double risk_free_rate = bestGenes[4] / 10000000; for (int i = 0; i < n; i++) { double new_volatilities = old_volatilities + mean_reversion_rate * (mean_reversion_level - old_volatilities) * dt + variance_variance * output[i]; double new_price = old_price + risk_free_rate * old_price * dt + new_volatilities * old_price * output2[i]; //These are already scaled via hoskin */ Ticks.Add(new_price); old_price = new_price; old_volatilities = new_volatilities; } break; } } /**/ /* for (int i = 0; i < n; i++) { /* double new_volatilities = old_volatilities + mean_reversion_rate * (mean_reversion_level - old_volatilities) * dt + variance_variance * output[i]; double new_price = old_price + risk_free_rate * old_price * dt + new_volatilities * old_price * output2[i]; //These are already scaled via hoskin */ /*double new_volatilities = old_volatilities + variance_variance*output[i]; double new_price = old_price + new_volatilities * output2[i]; Ticks.Add(new_price); old_price = new_price; old_volatilities = new_volatilities; }*/ }
static void Main() { IGAconfiguration configuration = new GAConfiguration(100, 0.9, null, 0.6, 0.3); IList<IIndividual<Wrapper<MyValuableClass>>> individualsList = new List<IIndividual<Wrapper<MyValuableClass>>>(); //Individuals initializing for (int i = 0; i < 1000; i++) { //Wrap source LOs to pass to GA List<Wrapper<MyValuableClass>> wrappedList = new List<Wrapper<MyValuableClass>>(); for (int j = 0; j < 5; j++) { wrappedList.Add(new Wrapper<MyValuableClass>(new MyValuableClass(GAUtils.GetRandom(0, 100)))); } individualsList.Add(new Individual<Wrapper<MyValuableClass>>(wrappedList)); } Console.WriteLine("Population creating"); var population = new Population<Wrapper<MyValuableClass>>(individualsList, IndividualEvaluateFunc, MutationFunc, CrossoverFunc, SelectionFunc); IGeneticAlgorithm<Wrapper<MyValuableClass>> ga = new GA<Wrapper<MyValuableClass>>(population); ObjectId id = new ObjectId(); Console.WriteLine("GA launching"); BackgroundWorker bgBackgroundWorker = new BackgroundWorker(); ga.Run(StopCondition, configuration, id, bgBackgroundWorker, WriteToCOnsole); foreach (var val in ga.Statistics.AverageFitnessFunctionValues) { Console.WriteLine(val); } string fileName = "data.txt"; using (StreamWriter outfile = new StreamWriter(fileName)) { foreach (var averageFitnessFunctionValue in ga.Statistics.AverageFitnessFunctionValues) { outfile.WriteLine(averageFitnessFunctionValue); } } //ga.Run(statistics => statistics.CurrentIteration > configuration.IterationsNumber, configuration, id, bgBackgroundWorker, WriteToCOnsole); }
private void Optimize() { SortedList<int, int> Result = new SortedList<int, int>(); lblScanCount.Text = "ScanCount:---"; lblScanMaxCount.Text = "ScanMaxCount:---"; for (nudAWin.Value = 500; nudAWin.Value > 0; nudAWin.Value--) { Simulate(gPairList,20, 30, 100, 0, (double)nudAWin.Value); int AWCount = 0; int ScanCount = 0; int ScanMaxCount = 0; Analyze(gPairList,out AWCount, out ScanCount, out ScanMaxCount); //lblAWC.Text = "AWCount: " + AWCount.ToString(); Result.Add((int)nudAWin.Value, AWCount); } KeyValuePair<int, int> Best = Result.First(x => (x.Value == Result.Values.Min())); nudAWin.Value = Best.Key; lblAWC.Text = "AWCount: " + Best.Value.ToString(); Random rand = new Random(); GA ga = new GA(500, 3, individual => { List<Pair> PairList = gPairList.ToList(); ; Simulate(PairList,Math.Abs(individual.Genotype[0] * 100), Math.Abs(individual.Genotype[1] * 100), Math.Abs(individual.Genotype[2] * 100), 0/* Math.Abs(individual.Genotype[3] * 100)*/, (double)nudAWin.Value); int AWCount = 0; int ScanCount = 0; int ScanMaxCount = 0; Analyze(PairList,out AWCount, out ScanCount, out ScanMaxCount); return ((Math.Pow(AWCount - ScanMaxCount, 2) / 4) + Math.Pow(AWCount - ScanCount, 2) + Math.Abs(individual.Genotype[2]) * 10 + Math.Abs(individual.Genotype[1]) * 100 + Math.Abs(individual.Genotype[0]) * 100 + (Math.Abs(individual.Genotype[1]) < Math.Abs(individual.Genotype[0]) ? 100 : 0)); }, individual => { individual.Genotype[0] = 2 * rand.NextDouble(); individual.Genotype[1] = 2 * rand.NextDouble(); individual.Genotype[2] = 2 * rand.NextDouble(); }); backgroundWorker1.RunWorkerAsync(ga); /* nudScanTime.Value=(decimal)Math.Abs(ga.BestIndividual.Genotype[0]*100); nudMaskTime.Value = (decimal)Math.Abs(ga.BestIndividual.Genotype[1]*100); nudThresold.Value = (decimal)Math.Abs(ga.BestIndividual.Genotype[2]*100); nudRet.Value = 0;//(decimal)Math.Abs(ga.BestIndividual.Genotype[3] * 100); */ //double ScanTime = (double); //double MaskTime = (double) //double Thresold = (double) }
private void btn_Run_Click(object sender, System.EventArgs e) { try { if (Points.Count < 2) { MessageBox.Show("No Enough cities"); return; } this.m_chro = null; Refresh(); //�¼ӵIJ��� points.Clear(); temps.Clear(); DrawPoints(); GALib.Initializer newItializer = new GALib.Initializer(this.Initializer); GALib.Mutate mutater = new GALib.Mutate(this. ChromoseCompraror); GALib.Fitness fitmethod = new GALib.Fitness(this.Fitness); GALib.CrossOver CrossMethod = new GALib.CrossOver(this.CrossOver); GALib.GA GAAlgo = new GA(newItializer,fitmethod,mutater,CrossMethod); GAAlgo.Generations = long.Parse(this.num_Gnr.Value.ToString()); GAAlgo.PopulationSize = ushort.Parse(this.num_PopSiz.Value.ToString()); GAAlgo.Mutation = double.Parse(this.num_Mutation.Value.ToString()); GAAlgo.CrossOver = double.Parse(this.numCO.Value.ToString()); if(Tool_MainBar.Buttons[1].Pushed) { GAAlgo.EnableLogging = true; GAAlgo.LogFilePath = this.openFileDialog.FileName; } GAAlgo.Initialize(); while (!GAAlgo.IsDone()) GAAlgo.CreateNextGeneration(); m_chro = GAAlgo.GetBestChromosome(); DrawCitiesPath(); } catch(System.FormatException exp) { MessageBox.Show("Please check your Input Parameters "+exp); } }
public GenomePair(string id, GA.Genome gen) { Id = id; Genome = gen; }