示例#1
0
        private void button1_Click(object sender, EventArgs e)
        {
            int numSwarmsToLaunch = 50;

            Task <SwarmResult>[] TaskArr = new Task <SwarmResult> [numSwarmsToLaunch];
            for (int i = 0; i < TaskArr.Length; i++)
            {
                TaskArr[i] = Task.Factory.StartNew <SwarmResult>(
                    (obj) =>
                {
                    SwarmSystem ss = new SwarmSystem((int)obj);
                    ss.Initialize();
                    SwarmResult sr = ss.DoPSO();
                    return(sr);
                }, i);
            }
            //Task.WaitAll(TaskArr); // wait for all tasks to finish
            List <SwarmResult> RList = new List <SwarmResult>();
            Task tskFinal            = Task.Factory.ContinueWhenAll(TaskArr, (tsks) =>
            {
                Console.WriteLine(tsks.Length.ToString() + " tasks");
                for (int i = 0; i < tsks.Length; i++)
                {
                    RList.Add(tsks[i].Result);
                }
            });

            tskFinal.Wait();
            RList.Sort();
            //List<SwarmResult> Res = new List<SwarmResult>();
            //Res = RList.Distinct(new SwarmResult());
            var Res = RList.Distinct(new SwarmResult()).ToList();

            dg1.DataSource = RList;
            dg1.Refresh();
            lblResult1.Text = Res[0].ToString();
            lblResult2.Text = Res[1].ToString();
            lblResult3.Text = Res[2].ToString();
            lblResult4.Text = Res[3].ToString();
        }
示例#2
0
        public SwarmResult DoPSO() // Particle movement to achieve
        {                          // for particle swarm optimization
            Gx = PList[0].Xx;
            Gy = PList[0].Xy;
            for (int i = 0; i < 1000; i++) // ietrations
            {
                // find best position in the swarm
                Px = PList[0].Xx;
                Py = PList[0].Xy;
                foreach (Particle pt in PList)
                {
                    if (Math.Abs(FunctionToSolve(pt.Xx, pt.Xy)) <
                        Math.Abs(FunctionToSolve(Px, Py)))
                    {
                        Px = pt.Xx;
                        Py = pt.Xy;
                    }
                }
                if (Math.Abs(FunctionToSolve(Px, Py)) < Math.Abs(FunctionToSolve(Gx, Gy)))
                {
                    Gx = Px;
                    Gy = Py;
                }
                foreach (Particle pt in PList)
                {
                    pt.UpdateVelocity(Px, Py, Gx, Gy);
                    pt.UpdatePosition();
                }
            }
            //create list of solutions
            SwarmResult sr = new SwarmResult
            {
                SwarmId       = swarmNum,
                X             = Gx,
                Y             = Gy,
                FunctionValue = FunctionToSolve(Gx, Gy)
            };

            return(sr);
        }