/// <summary> /// Cyclic crossbreeding /// </summary> /// <param name="agent1">First agent</param> /// <param name="agent2">Second agent</param> private void CyclicCrossbreeding(ref Agent agent1, ref Agent agent2) { if (agent1.Route.Count == agent2.Route.Count) { int iCount = agent1.Route.Count; int iBreakPoint = _rnd.Next(agent1.Route.Count); CitiesCollection tmpCC1 = new CitiesCollection(); CitiesCollection tmpCC2 = new CitiesCollection(); Agent agentCopy1 = new Agent(agent1.Route.Cities); Agent agentCopy2 = new Agent(agent2.Route.Cities); while (agent1.Route.Count > 1) { // Копируем города из агентов(первый из первого, последный из второго) City tmpc1 = agent1.Route.Cities[0]; tmpCC1.Add(tmpc1); agent1.Route.Cities.Cities.Remove(tmpc1); agent2.Route.Cities.Cities.Remove(tmpc1); City tmpc2 = agent2.Route.Cities[agent2.Route.Cities.Count - 1]; tmpCC1.Add(tmpc2); agent1.Route.Cities.Cities.Remove(tmpc2); agent2.Route.Cities.Cities.Remove(tmpc2); // Копируем города из копий Агентов tmpc1 = agentCopy2.Route.Cities[0]; tmpCC2.Add(tmpc1); agentCopy1.Route.Cities.Cities.Remove(tmpc1); agentCopy2.Route.Cities.Cities.Remove(tmpc1); tmpc2 = agentCopy1.Route.Cities[agentCopy1.Route.Cities.Count]; tmpCC2.Add(tmpc2); agentCopy1.Route.Cities.Cities.Remove(tmpc2); agentCopy2.Route.Cities.Cities.Remove(tmpc2); } // Если количество городов нечётное, один город остаётся в Агенте if (agent1.Route.Count == 1) { tmpCC1.Add(agent1.Route.Cities[0]); tmpCC2.Add(agent1.Route.Cities[0]); } agent1.Route = new Route(tmpCC1, "генетический алгоритм"); agent2.Route = new Route(tmpCC2, "генетический алгоритм"); } else { throw new Exception("Число городов в агентах не совпадает!"); } }
/// <summary> /// Crossbreeding with one break point in route /// </summary> /// <param name="agent1">First agent</param> /// <param name="agent2">Second agent</param> private void OnePointCrossbreeding(ref Agent agent1, ref Agent agent2) { try { if (agent1.Route.Count == agent2.Route.Count) { int iCount = agent1.Route.Count; int iBreakPoint = _rnd.Next(agent1.Route.Count); CitiesCollection tmpCC1 = new CitiesCollection(); CitiesCollection tmpCC2 = new CitiesCollection(); Agent agentCopy1 = new Agent(agent1.Route.Cities); Agent agentCopy2 = new Agent(agent2.Route.Cities); for (int i = 0; i < iBreakPoint; i++) { // Adding first city to collection and deleting it from Agent tmpCC1.Add(agent1.Route.Cities[i]); agent2.Route.Cities.Cities.Remove(agent1.Route.Cities[i]); //agent1.Route.Cities.Cities.RemoveAt(0); tmpCC2.Add(agentCopy2.Route.Cities[i]); agentCopy1.Route.Cities.Cities.Remove(agentCopy2.Route.Cities[i]); //agentCopy2.Route.Cities.Cities.RemoveAt(0); } //for (int i = 0; i < iBreakPoint; i++) //{ // agent1.Route.Cities.Cities.Remove(tmpCC1[i]); // agent2.Route.Cities.Cities.Remove(tmpCC2[i]); //} for (int i = 0; i < iCount - iBreakPoint; i++) { tmpCC1.Add(agent2.Route.Cities[i]); tmpCC2.Add(agentCopy1.Route.Cities[i]); } agent1.Route = new Route(tmpCC1, "генетический алгоритм"); agent2.Route = new Route(tmpCC2, "генетический алгоритм"); } else { throw new Exception("Число городов в агентах не совпадает!"); } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message + ex.StackTrace); throw; } }
private void tlStrpBtnLoadCities_Click(object sender, EventArgs e) { // Создаем новый файловый диалог OpenFileDialog DialogOpen = new OpenFileDialog(); // Задаема доступные расширения файлов DialogOpen.Filter = "Text file (*.txt)|*.txt|All files (*.*)|*.*"; if (DialogOpen.ShowDialog() == DialogResult.OK) { _cities.RemoveAll(); string sFileName = DialogOpen.FileName; //Получаем имя файла StreamReader sr = null; try { sr = new StreamReader(sFileName); String line; string[] param; //массив координат записи (x,y) int i = 0; while ((line = sr.ReadLine()) != "") { param = Regex.Split(line, "\t"); int PosX = Convert.ToInt32(param[0]); int PosY = Convert.ToInt32(param[1]); _cities.Add(new City(PosX, PosY)); _cities[i].Index = i; i++; } _cities.DistanceCalculate(); } catch (IOException fe) { string sDir = Directory.GetCurrentDirectory(); string s = Path.Combine(sDir, sFileName); MessageBox.Show("Ошибка в " + s + ". " + fe.Message); } // Прорисовка городов ucCP.Cities = _cities; ucCP.ClearDgvRouteList(); //Очищает лист маршрутов и DataGridView ucCP.RefreshRoutePaint(); //Перерисовывает маршруты tlStrpTxbCitiesCount.Text = _cities.Count.ToString(); liRoute.Clear(); _paramAnt.MaxCities = _cities.Count; _paramAnt.MaxAnts = _cities.Count; _cities.MaxDistance = _paramAnt.MaxDistance; tlStrpTxbCitiesCount.SelectAll(); } }
public void BackgroundCalculate() { try { tmrTimer.Interval = 10; tmrTimer.Start(); // Нужен для списка Табу AntAlgDataAnt ant = new AntAlgDataAnt(); ant.TabuInit(Cities.Count); int iCurrentCity = 0; //ccRoute = new AntAlgDataCitiesCollection(); //Cities[iCurrentCity].Index = iCurrentCity; City city = Cities[iCurrentCity]; city.Index = iCurrentCity; ccRoute.Add(city); ccRoute.MaxDistance = _parameters.MaxDistance; DateTime dtStart = DateTime.Now; string strOut; ant.TabuSet(iCurrentCity, 1); maxTime = Summ(Cities.Count); for (int i = 0; i < Cities.Count; i++) { curTime = Summ(i); double dCurrentDistance = double.MaxValue; double dMinimum = double.MaxValue; int iMinimum = -1; City CityI = Cities[iCurrentCity]; //CityI.Index = i; for (int j = 0; j < Cities.Count; j++) { //if (ant.TabuGet(j) == 0 && j != i && (ccRoute.Count == 0 || PointIsNotFound(ccRoute, j))) if (ant.TabuGet(j) != 1) { City CityJ = Cities[j]; // CityJ.Index = j; dCurrentDistance = Cities.Distance[iCurrentCity, j]; // Math.Sqrt((Math.Pow(Math.Abs(CityI.X - CityJ.X), 2) + // (Math.Pow(Math.Abs(CityI.Y - CityJ.Y), 2)))); if (dCurrentDistance < dMinimum) { dMinimum = dCurrentDistance; iMinimum = j; } } } if (iMinimum != -1) { iCurrentCity = iMinimum; City city_temp = Cities[iCurrentCity]; city_temp.Index = iCurrentCity; ccRoute.Add(city_temp); ant.TabuSet(iCurrentCity, 1); TimeSpan tsElapsed = (DateTime.Now - dtStart); strOut = String.Format("{0:00000} ", i + 1) + String.Format(" Time is {0:00}s {1:000}ms", tsElapsed.Seconds, tsElapsed.Milliseconds) + "\n"; // Дописать!!!!! listrTime.Add(strOut); } } strOut = "\nОбщее время:\n" + String.Format("{0:t}", DateTime.Now - dtStart); // Дописать!!!!! listrTime.Add(strOut); tmrTimer.Stop(); BestPath = ccRoute; OnFinally(EventArgs.Empty); } catch (ThreadAbortException taex) { listrTime.Add(taex.Message); } catch (Exception ex) { listrTime.Add(ex.Message); } }