Фрагмент для ознакомления
Add(chromosome_to_fitness); } fitness_list = fitness_list.OrderByDescending(x => x.Item2).ToList();return fitness_list; } Chromosome choose_random_parent(List> fitness_list) { int till_index = (int)Math.Floor(fitness_list.Count * top_percentage); Tuple parent_to_fitness = fitness_list[rnd.Next(0, till_index)];return parent_to_fitness.Item1; } Chromosome crossover(Chromosome parent1, Chromosome parent2) {int split_size = 0;if (crossover_split_random) { split_size = rnd.Next(0, parent1.Length); }else {double fraction = crossover_split_size; split_size = (int)Math.Floor(fraction * parent1.Length); }return Chromosome.crossover(parent1, parent2, split_size); } List generate_population(List path_points, Dictionary path_validity) {int population_size = GeneticAlgorithm.population_size; List population = new List(); Chromosome chromosome = null;for (int i = 0; i < population_size; i++) {while (true) { chromosome = generate_chromosome(path_points, path_validity);if (chromosome!=null)break; } population.Add(chromosome); } return population; } Chromosome generate_chromosome(List path_points, Dictionary path_validity) { Chromosome chromosome = new Chromosome(path_points.Count);chromosome[0] = 1; //'1' начало пути всегда входит в хромосомуPoint previous_path_point = path_points[0];for (int i = 1; i < path_points.Count; i++) { Point path_point = path_points[i];if (i == (path_points.Count - 1) && !path_validity[previous_path_point][i])returnnull;if (path_validity[previous_path_point][i]) {int gene = 0;if (i == (path_points.Count - 1)) gene = 1;else gene = (rnd.Next(1, 10) > 5) ? 0 : 1;if (gene == 1) previous_path_point = path_point; chromosome[i] = gene; }else { chromosome[i] = 0; } }return chromosome; }bool chromosome_valid(Chromosome chromosome, IEnumerable obstacles, List path_points) { Point? path_point_1 = null, path_point_2 = null;for (int i = 0; i < chromosome.Length; i++) {int gene = chromosome[i];if (gene == 1) {if (null == path_point_1) path_point_1 = path_points[i];else path_point_2 = path_points[i];if (path_point_1.HasValue && path_point_2.HasValue) {if (path_overlaps_obstacle(path_point_1.Value, path_point_2.Value, obstacles))returnfalse; path_point_1 = path_point_2; path_point_2 = null; } } }returntrue; }publicstaticbool path_overlaps_obstacle(Point path_point_1, Point path_point_2, IEnumerable obstacles) { foreach (Obstacle obstacle in obstacles) { if(obstacle.is_intersects(path_point_1, path_point_2))returntrue; }returnfalse; }double calculate_path_length(Chromosome chromosome, List path_points) { Point? path_point_1 = null, path_point_2 = null;double length = 0;for (int i = 0; i < chromosome.Length; i++) {int gene = chromosome[i];if (gene == 1) {if (path_point_1 == null) path_point_1 = path_points[i];else path_point_2 = path_points[i];if (path_point_1.HasValue && path_point_2.HasValue) { length += distance(path_point_1.Value, path_point_2.Value); path_point_1 = path_point_2; path_point_2 = null; } } }return length; }double distance(Point path_point_1, Point path_point_2) {return Math.Sqrt(Math.Pow(path_point_2.X - path_point_1.X, 2) + Math.Pow(path_point_2.Y - path_point_1.Y, 2)); } }}Simulate.csusing System;using System.Collections.Generic;using System.Diagnostics.Contracts;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Xml.Linq;namespace GeneticAlgorithmVisualization{publicclassSimulate { IEnumerable obstacles = null; List path_points = null; Dictionary path_validity = null; Point pointStart, pointFinish;publicSimulate(IEnumerable obstacles, Point pointStart, Point pointFinish) {this.obstacles = obstacles;this.pointStart = pointStart;this.pointFinish = pointFinish; }publicvoid execute() { init_path_points(); init_path_validity();new GeneticAlgorithm().start(obstacles, path_points, path_validity); }void init_path_points() {this.path_points = PathPoints.generate_grid_random_mix(this.obstacles, this.pointStart, this.pointFinish, 100, 10, 10); }void init_path_validity() {this.path_validity = new Dictionary();for (int i = 0; i < path_points.Count; i++) { Point path_point_start = path_points[i];if(!path_validity.ContainsKey(path_point_start)) {bool[] ar = newbool[path_points.Count]; Array.Fill(ar, true); path_validity[path_point_start] = ar; }for (int j = 0; j < path_points.Count; j++) { Point path_point_end = path_points[j];if (!path_validity.ContainsKey(path_point_end)) {bool[] ar = newbool[path_points.Count]; Array.Fill(ar, true); path_validity[path_point_end] = ar; }if (GeneticAlgorithm.path_overlaps_obstacle(path_point_start, path_point_end, obstacles)) { path_validity[path_point_start][j] = false; path_validity[path_point_end][i] = false; } } } } }}Form1.csnamespace GeneticAlgorithmVisualization{publicpartialclassForm1 : Form {privateint Grid_X = 10;privateint Grid_Y = 10;privateint Grid_Step = 100;privatebool[,] obsMap = null;private CircleObstacle[,] obsObjs = null;private Point? lastMouseLoc = null;private Point? startPoint = null;private Point? endPoint = null;enumProgramState { SetStart, SetEnd, SetObstacles, Calculation, Finish } ProgramState programState = ProgramState.SetStart;publicForm1() { InitializeComponent(); obsMap = newbool[Grid_X, Grid_Y]; obsObjs = new CircleObstacle[Grid_X, Grid_Y];for (int i = 0; i < Grid_X; i++)for (int j = 0; j < Grid_Y; j++) { obsMap[i, j] = false; obsObjs[i, j] = new CircleObstacle(new Point(Grid_Step + i * Grid_Step, Grid_Step + j * Grid_Step), Grid_Step / 2); } buttonReset_Click(this, new EventArgs()); Plotter.Size = this.pictureBox1.Size;this.timer1.Start(); }privatevoid reDraw() { Graphics graphics = pictureBox1.CreateGraphics(); graphics.Clear(Color.White);for (int i = 0; i < Grid_X; i++) {for (int j = 0; j < Grid_Y; j++) {if (obsMap[i, j]) obsObjs[i, j].Draw(graphics);else obsObjs[i, j].DrawContour(graphics); } } SizeF sizeOfString = new SizeF(); String s = "Старт"; sizeOfString = graphics.MeasureString(s, Font); graphics.DrawString(s, Font, new SolidBrush(Color.Blue), new Point(this.startPoint.Value.X - (int)sizeOfString.Width / 2, this.startPoint.Value.Y - (int)sizeOfString.Height / 2)); s = "Финиш"; sizeOfString = graphics.MeasureString(s, Font); graphics.DrawString(s, Font, new SolidBrush(Color.Blue), new Point(this.endPoint.Value.X - (int)sizeOfString.Width / 2, this.endPoint.Value.Y - (int)sizeOfString.Height / 2)); }privatevoid buttonReset_Click(object sender, EventArgs e) {for (int i = 0; i < Grid_X; i++)for (int j = 0; j < Grid_Y; j++) obsMap[i, j] = false;this.programState = ProgramState.SetStart;//reDraw(); }privatevoid pictureBox1_Click(object sender, EventArgs e) { }privatevoid buttonStart_Click(object sender, EventArgs e) {this.programState = ProgramState.Calculation; List listObstacles = new List();for (int i = 0; i < Grid_X; i++)for (int j = 0; j < Grid_Y; j++) {if (obsMap[i, j]) listObstacles.Add(obsObjs[i, j]); } Simulate simulate = new Simulate(listObstacles, this.startPoint.Value, this.endPoint.Value); Thread thread = new Thread(() => { simulate.execute();this.programState = ProgramState.Finish; //?? }); thread.Start(); }privatevoid pictureBox1_MouseClick(object sender, MouseEventArgs e) {if (this.programState == ProgramState.SetObstacles) {for (int i = 0; i < Grid_X; i++)for (int j = 0; j < Grid_Y; j++) {if (obsObjs[i, j].is_intersects(e.Location)) {if (new List() { this.startPoint.Value, this.endPoint.Value }.Contains(obsObjs[i, j].Center))continue; obsMap[i, j] = !obsMap[i, j]; reDraw();return; } } } }privatevoid timer1_Tick(object sender, EventArgs e) { Bitmap b = Plotter.getNextBitmap();if (b != null) {this.pictureBox1.Image = b; }switch (this.programState) {case ProgramState.SetStart:this.labelInfo.Text = "Укажитеточкустарта";break;case ProgramState.SetEnd:this.labelInfo.Text = "Укажитеточкуфиниша";break;case ProgramState.SetObstacles:this.labelInfo.Text = "Установитепрепятствия";break;case ProgramState.Calculation:this.labelInfo.Text = "Выполняетсяпоискпути...";break;case ProgramState.Finish:this.labelInfo.Text = "Поискпутизавершен";break; }this.buttonStart.Enabled = this.programState == ProgramState.SetObstacles || this.programState == ProgramState.Finish; }privatevoid pictureBox1_MouseMove(object sender, MouseEventArgs e) {if (this.programState == ProgramState.SetStart || this.programState == ProgramState.SetEnd) {for (int i = 0; i < Grid_X; i++) {for (int j = 0; j < Grid_Y; j++) {if (obsObjs[i, j].is_intersects(e.Location)) {if (!lastMouseLoc.HasValue || (lastMouseLoc.HasValue && lastMouseLoc.Value != obsObjs[i, j].Center)) { lastMouseLoc = obsObjs[i, j].Center; Graphics graphics = this.pictureBox1.CreateGraphics(); graphics.Clear(Color.White); obsObjs[i, j].DrawContour(graphics); } } } } } }privatevoid pictureBox1_DoubleClick(object sender, EventArgs e) {if (this.programState == ProgramState.SetStart) {if (lastMouseLoc.HasValue) {this.startPoint = lastMouseLoc.Value;this.programState = ProgramState.SetEnd; } }elseif (this.programState == ProgramState.SetEnd) {if (lastMouseLoc.HasValue) {this.endPoint = lastMouseLoc.Value;this.programState = ProgramState.SetObstacles; reDraw(); } } }privatevoid Form1_Load(object sender, EventArgs e) { }privatevoidсправкаToolStripMenuItem_Click(object sender, EventArgs e){ MessageBox.Show("Визуализация генетического алгоритма");}privatevoidоРазработчикеToolStripMenuItem_Click(object sender, EventArgs e){ MessageBox.Show("2023г. Информатика и программирование"); } }}Program.csnamespace GeneticAlgorithmVisualization{internalstaticclassProgram {////// The main entry point for the application./// [STAThread]staticvoid Main() {// To customize application configuration such as set high DPI settings or default font,// see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); Application.Run(new Form1());} }}
1 Генетические алгоритмы : учеб. пособие / Л. А. Гладков, В. В. Курейчик, В. М. Курейчик. – 2-е изд. – М. : Физматлит, 2006. – 320 с.
2 Зыков, С. В. Программирование. Объектно-ориентированный подход : учебник и практикум для академического бакалавриата / С. В. Зыков. — М. : Издательство Юрайт, 2019. — 155 с.
3 Кудрина, Е. В. Основы алгоритмизации и программирования на языке c# : учеб. пособие для бакалавриата и специалитета / Е. В. Кудрина, М. В. Огнева. — М. : Издательство Юрайт, 2019. — 322 с.
4 Введение в программирование на языке Visual C# : учеб. пособие / С.Р. Гуриков. — М. : ФОРУМ : ИНФРА-М, 2019. — 447 с. — (Высшее образование: Бакалавриат). - Режим доступа: http://znanium.com/catalog/product/1017998
5 Казанский А. А. - ПРОГРАММИРОВАНИЕ НА VISUAL C# 2-е изд., пер. и доп. Учебное пособие для вузов - М.:Издательство Юрайт - 2020 - 192с. - ISBN: 978-5-534-12338-8 - Текст электронный // ЭБС ЮРАЙТ - URL: https://urait.ru/book/programmirovanie-na-visual-c-451467
6 Прайс, М. С# 9 и .NET 5 : разработка и оптимизация / М. Прайс. – 5-е изд. – Санкт-Петербург : Питер, 2022. – 832 с.
7 Рихтер, Д. CLR via C#. Программирование на платформе Microsoft.NET Framework 4.5 на языке C# / Д. Рихтер. – 4-е изд. – Санкт-Петербург : Питер, 2019. – 896 с.