private void GenerateClustersFromNnc() { PenaltyCluster = new Cluster(); if (ClustersCount >= nncClusters.Count) { Clusters = nncClusters; } else { Clusters = new List<Cluster>(); List<Cluster> newClusters = new List<Cluster>(); newClusters.AddRange(nncClusters); for (int i = 0; i != ClustersCount; i++) { int index = TaskController.Rnd.Next(newClusters.Count); Clusters.Add(newClusters[index]); newClusters.RemoveAt(index); } foreach (Cluster newCluster in newClusters) { PenaltyCluster.Merge(newCluster); } } foreach (Cluster cluster in Clusters) { cluster.Depot = Depot; } }
protected Site(List<Node> nodes) { Nodes = new List<Node>(); for (int i = 0; i != nodes.Count; i++) { Nodes.Add(nodes[i]); } }
protected SiteClusteringVrp(SiteClusteringVrp site) : base(site.Nodes) { Clusters = new List<Cluster>(); for (int i = 0; i != site.Clusters.Count; i++) { Clusters.Add(new Cluster(site.Clusters[i])); } }
public GeneralViewModel() { Boxes = new List<Box> { }; FirstGroupButtons = new List<ToolBarButtonBase> { }; FirstGroupButtons.Add(new ToolBarButtonBase(false, new BitmapImage(new Uri("Images/selectAndMove.png", UriKind.Relative)), "SelectAndMove")); FirstGroupButtons.Add(new ToolBarButtonBase(false, new BitmapImage(new Uri("Images/selectAndRotate.png", UriKind.Relative)), "SelectAndRotate")); SecondGroupButtons = new List<ToolBarButtonBase> { }; SecondGroupButtons.Add(new ToolBarButtonBase(false, new BitmapImage(new Uri("Images/selectObject.png", UriKind.Relative)), "SelectObject")); BoxPropertiesVisibility = Visibility.Collapsed; BoxPropertiesImg = new BitmapImage(new Uri("Images/plus.png", UriKind.Relative)); OnPropertyChanged("BoxPropertiesVisibility"); OnPropertyChanged("BoxPropertiesImg"); BoxListVisibility = Visibility.Collapsed; BoxListImg = new BitmapImage(new Uri("Images/plus.png", UriKind.Relative)); OnPropertyChanged("BoxListVisibility"); OnPropertyChanged("BoxListImg"); }
public Cluster(Cluster cluster) { Nodes = new List<Node>(); foreach (Node node in cluster.Nodes) { Nodes.Add(node); } Depot = cluster.Depot; CapacityLimit = cluster.CapacityLimit; }
// массив бит => массив байт public static byte[] BitsToBytes(bool[] source) { List<byte> listOfBytes = new List<byte>(); List<bool> listOfBools = source.ToList(); try { do { bool[] eightBits = listOfBools.Take(8).ToArray(); listOfBools.RemoveRange(0, 8); listOfBytes.Add(EightBitsToByte(eightBits)); } while (listOfBools.Count != 0); } catch (ArgumentException) { listOfBools.AddRange(new bool[8 - listOfBools.Count]); bool[] eightBits = listOfBools.ToArray(); listOfBytes.Add(EightBitsToByte(eightBits)); } return listOfBytes.ToArray(); }
public void CreateSites() { sites = new List<Site>(); Site.IsStartingInitialized = false; CreateNewSite().StartingInitialize(); for (int i = 0; i != ScoutsCount; i++) { sites.Add(CreateNewSite()); } }
public override List<Node> PrepareToDraw(System.Drawing.Color connectionsColor) { List<Node> drawingNodes = new List<Node>(); drawingNodes.AddRange(base.PrepareToDraw(connectionsColor)); foreach (Node node in PenaltyCluster.Nodes) { node.DisconnectFromAll(); drawingNodes.Add(node); } return drawingNodes; }
public static void SaveDrawnNodes() { Node[] currentDrawnNodes = drawingNodes.ToArray().Clone() as Node[]; List<Node> currentListDrawnNodes = new List<Node>(); foreach (Node currentDrawnNode in currentDrawnNodes) { currentListDrawnNodes.Add(new Node(currentDrawnNode)); } drawnNodes.Add(currentListDrawnNodes); }
protected void FormAllClusters() { allClusters = new List<Cluster>(); allClusters.AddRange(Clusters); allClusters.Add(PenaltyCluster); NotClusteredNodes = PenaltyCluster.Nodes; }
//получение вектора изображения public static object[] GetVector(List<byte[,]> G, List<byte[,]> G1) { if (G.Count != G1.Count) throw (new ArgumentException("G and G1 have a different number of blocks")); List<bool> RS = new List<bool>(0); //хранит тип каждого блока. R-true,S-false,U-dont has value bool?[] blockType = new bool?[G.Count]; for (int i = 0; i < G.Count; i++) { int GSum = Discriminate(G[i]); int G1Sum = Discriminate(G1[i]); if (GSum != G1Sum) { RS.Capacity++; if (G1Sum > GSum) { RS.Add(true); blockType[i] = true; } else { RS.Add(false); blockType[i] = false; } } } object[] obj = { RS.ToArray(), blockType }; return obj; }
public override List<Node> PrepareToDraw(Color connectionsColor) { DrawingNodes = new List<Node>(); foreach (Cluster cluster in Clusters) { DrawingNodes.AddRange(cluster.GetDrawingNodes(Color.LightGray)); } Node depot = Clusters[0].Depot; if (depot != null) { DrawingNodes.Add(depot); } return DrawingNodes; }
public void Calculate(int scoutsCount, int goodSitesCount, int bestSitesCount, int neighboursForGoodSites, int neighboursForBestSites) { values = new List<double>(); colonies = new List<BeesColony>(); foreach (Cluster cluster in clusters) { if (cluster.Nodes.Count == 0) { continue; } BeesColony colony = new BeesColony(); colony.Problem = BeesColony.ProblemType.VRP_TSP; colony.ClustersCount = 1; colony.IsCalcLastChange = true; colony.ScoutsCount = scoutsCount; colony.GoodSitesCount = goodSitesCount; colony.BestSitesCount = bestSitesCount; colony.NeighboursForGoodSites = neighboursForGoodSites; colony.NeighboursForBestSites = neighboursForBestSites; List<Node> colonyNodes = new List<Node>(); colonyNodes.AddRange(cluster.Nodes); if (cluster.Depot != null) { colonyNodes.Add(cluster.Depot); } colony.SetNodes(colonyNodes); colony.CreateSites(); colony.IterateToStop(); values.Add(colony.Value); colonies.Add(colony); } Stop(); }
private List<Site> GenerateNeighbours(int count) { List<Site> result = new List<Site>(); for (int i = 0; i != count; i++) { result.Add(GetNeighbour()); } return result; }
private void button_StartSeries_Click(object sender, EventArgs e) { int consumersFrom = Convert.ToInt32(numericUpDown_ConsumersCountFrom.Value); int consumersTo = Convert.ToInt32(numericUpDown_ConsumersCountTo.Value); int consumersStep = Convert.ToInt32(numericUpDown_ConsumersCountStep.Value); int volumeFrom = Convert.ToInt32(numericUpDown_GeneratingVolumeFrom.Value); int volumeTo = Convert.ToInt32(numericUpDown_GeneratingVolumeTo.Value); int startsCount = Convert.ToInt32(numericUpDown_StartsInSeriesCount.Value); int modelsCount = Convert.ToInt32(numericUpDown_ModelsCount.Value); bool currentModel = checkBox_CurrentModel.Checked; int algorithmsCount = checkedListBox_AlgorithmType.CheckedIndices.Count; int seriesCount = currentModel ? 1 : (consumersTo - consumersFrom) / consumersStep + 1; string logFileName = textBox_LogFileName.Text; if (currentModel) { modelsCount = 1; } QuickAppendToFile(logFileName, string.Format( "\n\n\n----- Series start. Clusters limit: {0}. Capacity limit: {1}. " + "Starts in each series: {2}. Models count: {3}. " + "Current model: {4}. Kilometer cost: {5:0.000}. Consumers count: {6}. Time: {7}", Convert.ToInt32(numericUpDown_ClustersCount.Value), Convert.ToInt32(numericUpDown_ClusterCapacityLimit.Value), startsCount, modelsCount, currentModel, KilometerCost, TaskController.ConsumersCount, DateTime.Now)); for (int i = 0; i != seriesCount; i++) { int consumersCount = consumersFrom + i * consumersStep; if (!currentModel) { QuickAppendToFile(logFileName, string.Format( "--- Series #{0} start. New models generate. Consumers count: {1}. Time: {2}", i, consumersCount, DateTime.Now)); } else { QuickAppendToFile(logFileName, string.Format("--- Series start. Time: {0}", DateTime.Now)); } double[] valuesAvr = new double[algorithmsCount]; double[] timesAvr = new double[algorithmsCount]; for (int k = 0; k != algorithmsCount; k++) { valuesAvr[k] = 0; timesAvr[k] = 0; } for (int j = 0; j != modelsCount; j++) { if (!currentModel) { TaskController.CreateNewModel(); GenerateNodes(consumersCount, volumeFrom, volumeTo, true); } for (int k = 0; k != algorithmsCount; k++) { checkedListBox_AlgorithmType.SelectedIndex = checkedListBox_AlgorithmType.CheckedIndices[k]; //QuickAppendToFile(logFileName, // string.Format("Starting model series for algorithm {0}. Time: {1}", // GetAlgorithmName(k), // DateTime.Now)); List<double> values = new List<double>(); List<double> times = new List<double>(); for (int l = 0; l != startsCount; l++) { StartAlgorithm(); TaskController.Algorithm.LogFileName = ""; double time = IterateToStop() + CalculateTsp(); values.Add(TaskController.Algorithm.Value); times.Add(time); //QuickAppendToFile(logFileName, // string.Format( // "Start #{0} completed. Result: {1:0.00}. During the: {2:0.00} s. Time: {3}", // l, // values[l], // times[l], // DateTime.Now)); } valuesAvr[k] += values.Average(); timesAvr[k] += times.Average(); //QuickAppendToFile(logFileName, // string.Format( // "Model series completed. Avr result: {0:0.00}. Avr time: {1:0.00} s. Time: {2}", // values.Average(), times.Average(), DateTime.Now)); } } for (int k = 0; k != algorithmsCount; k++) { valuesAvr[k] /= modelsCount; timesAvr[k] /= modelsCount; QuickAppendToFile(logFileName, string.Format("Algorithm {0}. Avr result: {1:0.00}. Avr time: {2:0.00} s", GetAlgorithmName(checkedListBox_AlgorithmType.CheckedIndices[k]), valuesAvr[k], timesAvr[k])); } QuickAppendToFile(logFileName, string.Format("--- Series #{0} completed. Time: {1}", i, DateTime.Now)); } QuickAppendToFile(logFileName, string.Format( "----- All series completed. Time: {0}", DateTime.Now)); }
public override List<Node> PrepareToDraw(Color connectionsColor) { DrawingNodes = new List<Node>(); foreach (Node node in Nodes) { DrawingNodes.Add(node); } for (int i = 0; i != Nodes.Count; i++) { Nodes[i].DisconnectFromAll(); } int[] result = Result as int[]; for (int i = 0; i != result.Length - 1; i++) { ConnectConsumerToDepot(Nodes[result[i]], Nodes[result[i + 1]], connectionsColor); } ConnectConsumerToDepot(Nodes[result[result.Length - 1]], Nodes[result[0]], connectionsColor); return DrawingNodes; }
private void GenerateSequence(int depotsCount, int clustersCount, int consumersCount) { List<int> orderedSequence = new List<int>(); for (int i = 0; i != depotsCount; i++) { for (int j = 0; j != clustersCount; j++) { orderedSequence.Add(i); } } for (int i = depotsCount; i != depotsCount + consumersCount; i++) { orderedSequence.Add(i); } nodesSequence = new int[depotsCount*clustersCount + consumersCount]; for (int i = 0; i != nodesSequence.Length; i++) { int index = TaskController.Rnd.Next(orderedSequence.Count); nodesSequence[i] = orderedSequence[index]; orderedSequence.RemoveAt(index); } }
//получение набора блоков 8х8 и их координат в изображении public static object[] GetBlocks(Bitmap bm, string colorComponent) { int x = 0, y = 0, blocksInWidth = bm.Width / 8, blocksInHeight = bm.Height / 8, allBlocks = blocksInWidth * blocksInHeight, finishedBlocksInWidth = 0; Color col; List<byte[,]> listOfBlocks = new List<byte[,]>(0); List<int[]> listOfBlocksXY = new List<int[]>(0); switch (colorComponent) { #region "Red" case "Red": for (int b = 0; b < allBlocks; b++) { byte[,] tempBlock = new byte[8, 8]; for (int j = 0; j < 8; j++, y++, x -= 8) for (int i = 0; i < 8; i++, x++) { col = bm.GetPixel(x, y); tempBlock[j, i] = col.R; } listOfBlocks.Capacity++; listOfBlocks.Add(tempBlock); listOfBlocksXY.Capacity++; int[] xy = new int[] { x, y - 8 }; listOfBlocksXY.Add(xy); // Переход к следующему блоку finishedBlocksInWidth++; if (finishedBlocksInWidth < blocksInWidth) { x += 8; y -= 8; } else { x = 0; finishedBlocksInWidth = 0; } } break; #endregion #region "Green" case "Green": for (int b = 0; b < allBlocks; b++) { byte[,] tempBlock = new byte[8, 8]; for (int j = 0; j < 8; j++, y++, x -= 8) for (int i = 0; i < 8; i++, x++) { col = bm.GetPixel(x, y); tempBlock[j, i] = col.G; } listOfBlocks.Capacity++; listOfBlocks.Add(tempBlock); listOfBlocksXY.Capacity++; int[] xy = new int[] { x, y - 8 }; listOfBlocksXY.Add(xy); // Переход к следующему блоку finishedBlocksInWidth++; if (finishedBlocksInWidth < blocksInWidth) { x += 8; y -= 8; } else { x = 0; finishedBlocksInWidth = 0; } } break; #endregion #region "Blue" case "Blue": for (int b = 0; b < allBlocks; b++) { byte[,] tempBlock = new byte[8, 8]; for (int j = 0; j < 8; j++, y++, x -= 8) for (int i = 0; i < 8; i++, x++) { col = bm.GetPixel(x, y); tempBlock[j, i] = col.B; } listOfBlocks.Capacity++; listOfBlocks.Add(tempBlock); listOfBlocksXY.Capacity++; int[] xy = new int[] { x, y - 8 }; listOfBlocksXY.Add(xy); // Переход к следующему блоку finishedBlocksInWidth++; if (finishedBlocksInWidth < blocksInWidth) { x += 8; y -= 8; } else { x = 0; finishedBlocksInWidth = 0; } } break; #endregion default: throw (new ArgumentException("Wrong color component")); } object[] obj = { listOfBlocks, listOfBlocksXY }; return obj; }
public override void DrawNodes() { List<Node> drawingNodes = new List<Node>(); for (int i = 0; i != Clusters.Count; i++) { Cluster cluster = Clusters[i]; if (cluster.Nodes.Count == 0) { continue; } Node center = new Node(-1, Node.NodeType.Auxiliary, (int)Clusters[i].Center.x, (int)Clusters[i].Center.y, Clusters[i].Center.x, Clusters[i].Center.y); if (cluster.Nodes.Count == 0) { drawingNodes.Add(center); continue; } foreach (Node node in cluster.Nodes) { center.ConnectTo(node, Color.LightGray); drawingNodes.Add(node); } drawingNodes.Add(center); } Node depot = Clusters[0].Depot; if (depot != null) { drawingNodes.Add(depot); } TaskController.DrawNodes(drawingNodes); }
async private void btnGetFreeSpace_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; //1 ПОЛУЧЕНИЕ RS-вектора изображения //получение групы блоков G их их координат в изображении object[] obj = await Task<object[]>.Factory.StartNew(()=>Functions.GetBlocks(bm, colorComponent)); listOfG = (List<byte[,]>)obj[0]; listOfGXY = (List<int[]>)obj[1]; // получение группы блоков G1 listOfG1 = new List<byte[,]>(listOfG.Count); flipLevel = (byte)trackBar1.Value; foreach (byte[,] bl in listOfG) listOfG1.Add(await Task<byte[,]>.Factory.StartNew(()=>Functions.FlipBlock(bl, flipLevel))); //получение RS-вектора //и массива хранящего тип каждого блока(R,S,U) obj = await Task<object[]>.Factory.StartNew(()=>Functions.GetVector(listOfG, listOfG1)); bool[] RS = (bool[])obj[0]; blockType = (bool?[])obj[1]; //2 СЖАТИЕ GZip И ПОЛУЧЕНИЕ RS1-ВЕКТОРА //записали в поток сжатые байты LZF lzf = new LZF(); byte[] source = Functions.BitsToBytes(RS); byte[] result = new byte[source.Length + 1000]; int c = lzf.Compress(source, source.Length, result, result.Length); byte[] temp = result.Take(c).ToArray(); RS1 = new BitArray(Functions.BytesToBits(temp)); //рассчет получившегося за счет сжатия свободного места(в битах) freeSpace = RS.Length - RS1.Length; lblFreeSpace.Text = freeSpace + " бит"; symbolCount = freeSpace / 8 - 16;// -16 символов(128 бит) на хеш if (symbolCount <= 0) { MessageBox.Show("В изображение не получится записать ни одного символа!\n" + "Выберите другое изображение или измените настройки"); lblSymbolCount.Text = symbolCount + " символов"; return; } lblSymbolCount.Text = symbolCount + " символов"; btnWrite.Enabled = tbAuthenticator.Enabled = true; Cursor.Current = Cursors.Default; }
private void btnReadAuth_Click(object sender, EventArgs e) { if (!int.TryParse(tbFreeSpace.Text, out freeSpace2)) if (MessageBox.Show("Недопустимое значение FreeSpace", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK) { tbFreeSpace.Text = ""; tbFreeSpace.Focus(); return; } if (freeSpace2 <= 0) if (MessageBox.Show("Значение FreeSpace должно быть больше 0", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK) { tbFreeSpace.Text = ""; tbFreeSpace.Focus(); return; } //получение групы блоков G их их координат в изображении object[] obj = Functions.GetBlocks(bm3, colorComponent2); List<byte[,]> listOfG = (List<byte[,]>)obj[0]; List<int[]> listOfGXY = (List<int[]>)obj[1]; // получение группы блоков G1 List<byte[,]> listOfG1 = new List<byte[,]>(listOfG.Count); flipLevel2 = (byte)trackBar2.Value; foreach (byte[,] bl in listOfG) listOfG1.Add(Functions.FlipBlock(bl, flipLevel2)); //получение RSM' вектора //и массива хранящего тип каждого блока(R,S,U) obj = Functions.GetVector(listOfG, listOfG1); bool[] RSM2 = (bool[])obj[0]; bool?[] blockType = (bool?[])obj[1]; try { //расспаковка RSM' - получаем вектор RS оригинала bool[] RSCompressed = (RSM2.Take(RSM2.Length - freeSpace2).ToArray()); byte[] source = Functions.BitsToBytes(RSCompressed); byte[] decompressedData = new byte[source.Length + 1000]; LZF lzf = new LZF(); int g = lzf.Decompress(source, source.Length, decompressedData, decompressedData.Length); byte[] temp = decompressedData.Take(g).ToArray(); bool[] RS = Functions.BytesToBits(temp); //ВЫДЕЛЕНИЕ ХЕШ КОДА И АУТЕНТИФИКАТОРА bool[] hash = new bool[128]; bool[] auth = new bool[freeSpace2 - 128]; int i, c; for (i = RSM2.Length - freeSpace2, c = 0; c < hash.Length; c++, i++) { hash[c] = RSM2[i]; } //переводим хеш в массив байт hashInBytes = new byte[16]; BitArray ba = new BitArray(hash); ba.CopyTo(hashInBytes, 0); for (c = 0; c < auth.Length; c++, i++) { auth[c] = RSM2[i]; } //переводим аутентификатор в строку byte[] authInBytes = new byte[auth.Length / 8 + 1]; ba = new BitArray(auth); ba.CopyTo(authInBytes, 0); tbAuthenticator2.Text = Encoding.Default.GetString(authInBytes); //возвращаем изображение к первоначальному виду bm4 = Functions.GetImage(bm3, colorComponent, listOfG1, listOfGXY, RS, blockType); pictureBox4.Image = bm4; btnIsImgModified.Enabled = btnSave2.Enabled = true; } catch { MessageBox.Show( "Введенное значение freeSpace не может\r\nбыть применимо к данному изображению!\r\nПовторите ввод", "Ошибка", MessageBoxButtons.OK,MessageBoxIcon.Error ); tbFreeSpace.Text = ""; tbFreeSpace.Focus(); return; } tbAuthenticator2.Enabled = true; }
public List<Node> GetDrawingNodes(Color connectionsColor) { List<Node> drawingNodes = new List<Node>(); if (Nodes.Count == 0) { return drawingNodes; } Node center = new Node(-1, Node.NodeType.Auxiliary, (int)Center.x, (int)Center.y, Center.x, Center.y); foreach (Node node in Nodes) { center.ConnectTo(node, connectionsColor); drawingNodes.Add(node); } drawingNodes.Add(center); return drawingNodes; }