private void btnParallelSwarms_Click(object sender, EventArgs e) { int launchSwams = 10; // An Array of List Task <SwarmResult>[] arrTask = new Task <SwarmResult> [launchSwams]; // for loop for (int i = 0; i < arrTask.Length; i++) { arrTask[i] = Task.Factory.StartNew <SwarmResult>((obj) => { SwarmSystem ss = new SwarmSystem((int)obj); ss.Initialize(); SwarmResult sr = ss.DoPSO(); return(sr); }, i); } List <SwarmResult> resultList = new List <SwarmResult>(); Task finalTask = Task.Factory.ContinueWhenAll(arrTask, (tks) => { Console.WriteLine(tks.Length.ToString() + " tasks"); for (int i = 0; i < tks.Length; i++) { resultList.Add(tks[i].Result); } }); finalTask.Wait(); resultList.Sort(); dataGridView1.DataSource = resultList; dataGridView1.Refresh(); lblResult.Text = resultList[0].ToString(); }
private void btnSolveBySwarm_Click(object sender, EventArgs e) { SwarmSystem ss = new SwarmSystem(0); ss.Initialize(); SwarmResult sr = ss.DoPSO(); //txtGValue.Text = ss.funcValue.ToString(); lblResult.Text = sr.ToString(); //double res = ss.FunctionValue(-1.14); //MessageBox.Show(res.ToString()); }
public SwarmResult DoPSO() { Gx = PList[0].Xx; Gy = PList[0].Xy; for (int i = 0; i < 1000; i++) { // find best position in the swarm Px = PList[0].Xx; Py = PList[0].Xy; foreach (Particle pt in PList) { if (Math.Abs(FunctionValue(pt.Xx, pt.Xy)) < Math.Abs(FunctionValue(Px, Py))) { Px = pt.Xx; Py = pt.Xy; } } if (Math.Abs(FunctionValue(Px, Py)) < Math.Abs(FunctionValue(Gx, Gy))) { Gx = Px; Gy = Py; Console.WriteLine("Gx & Gy = " + FunctionValue(Gx, Gy).ToString()); } foreach (Particle pt in PList) { pt.UpdateVelocity(Px, Py, Gx, Gy); pt.UpdatePosition(); } } SwarmResult sr = new SwarmResult { swarmId = swamnumb, X = Gx, Y = Gy, funcValue = FunctionValue(Gx, Gy) }; return(sr); //MessageBox.Show("Root = " + G.ToString() + " function value = " + FunctionValue(G).ToString()); }