Beispiel #1
0
        public override void Initialization(PSO algorithm)
        {
            base.Initialization(algorithm);
            Domain domain = algorithm.Problem.ProblemDomain;

            _initialVelocity = domain[0].Range / 2; //TODO: this assumes bounds are always equal for all dimensions.
        }
    public void StartTraining()
    {
        last_q_values  = new float[actions.Length];
        abort_learning = false;
        current_step   = 0;
        current_reward = 0;
        particle_step  = 0;

        //Setup car components
        car_camera     = GetComponent <CarCamera>();
        car_controller = GetComponent <CarController>();
        car_body       = transform.GetChild(0).GetComponent <Rigidbody>();

        //Setup PSO
        working_particle = 0;
        particles        = new MFNN[max_particles];
        for (int i = 0; i < particles.Length; i++)
        {
            particles[i] = CreateMFNN();
        }
        particle_swarm = new PSO(particles);
        network_target = CreateMFNN();

        StartCoroutine(TakeStep());
    }
Beispiel #3
0
    public void Initialize(Vector3 targetCoordinates)
    {
        this.targetCoordinates = targetCoordinates;
        this.initialized       = true;
        //Initialize
        int counter = 0;

        foreach (AlienController controller in alienControllers)
        {
            controller.Initialize(counter);
            controller.SetTargetCoordinates(targetCoordinates);
            counter++;
        }

        //Ensure we have a min and max speed entities
        float maxSpeedAlien = DataBetweenScenes.getMaxSpeedAlien();
        float minSpeedAlien = 1.75f;
        int   alienIdMin    = Random.Range(0, 7); alienControllers[alienIdMin].SetSpeed(minSpeedAlien);
        int   alienIdMax    = Random.Range(0, 7); alienControllers[alienIdMax].SetSpeed(maxSpeedAlien);

        SetAliensInPlace();
        pso = new PSO(alienControllers);
        attackAstronauts = new AttackAstronauts(astronautControllers, alienControllers);
        //Start looking for astronauts
        startPSO = true;
        pso.SetInertiaAlien(inertia);
    }
        private List <IParticle> GetRandomParticles()
        {
            PSO pso = AbstractAlgorithm.CurrentInstance as PSO;

            if (Number > pso.Particles.Count)
            {
                Number = pso.Particles.Count;
            }

            HashSet <int> selections = new HashSet <int>();

            //get random particle indices
            while (selections.Count < Number)
            {
                selections.Add(RandomProvider.NextInt(0, pso.Particles.Count - 1));
            }

            List <IParticle> result = new List <IParticle>(Number);

            foreach (int index in selections)
            {
                result.Add(pso.Particles[index]);
            }

            return(result);
        }
        public Vector GetGuide(IParticle particle)
        {
            PSO pso = AbstractAlgorithm.CurrentInstance as PSO;

            return(CenterStrategy.GetCenter(pso.Particles)); //TODO: this recalculates for each particle... -> is this needed? For async, it makes sense
                                                             //for sync, this would be affected by each particle update though...
        }
    // Use this for initialization
    void Start()
    {
        numAstronauts = astronauts.Length;
        gameOverMenu.SetActive(false);
        missionsuccessMenu.SetActive(false);
        foreach (GameObject astronaut in astronauts)
        {
            astronautControllers.Add(astronaut.GetComponent <PlayerController>());
        }
        foreach (GameObject alien in aliens)
        {
            alienControllers.Add(alien.GetComponent <AlienController>());
        }
        //Initialize
        int counter = 0;

        foreach (PlayerController controller in astronautControllers)
        {
            controller.Initialize(counter);
            counter++;
        }

        //Ensure we have a min and max speed entities
        float maxSpeedAstronaut = DataBetweenScenes.getMaxSpeedAstronaut();
        float minSpeedAstronaut = 3f;
        int   astronautIdMin    = Random.Range(0, 7); astronautControllers[astronautIdMin].SetSpeed(minSpeedAstronaut);
        int   astronautIdMax    = Random.Range(0, 7); astronautControllers[astronautIdMax].SetSpeed(maxSpeedAstronaut);

        SetAstronautsInPlace();
        pso          = new PSO(astronautControllers, progressBar, StopExploringButton);
        attackAliens = new AttackAliens(astronautControllers, alienControllers, gameOverMenu, missionsuccessMenu, alienManager);
        StopExploringButton.SetActive(false);
    }
Beispiel #7
0
        private void buttonRun_Click(object sender, EventArgs e)
        {
            PSO    pso       = new PSO();
            PSOCAL psoHandle = new PSOCAL(pso.demethod);

            MessageBox.Show("Begin!");
            watch.Reset();
            watch.Start();
            IAsyncResult result = psoHandle.BeginInvoke(new AsyncCallback(decallback), null);
        }
Beispiel #8
0
 private static void PrintBestSoFar(PSO pso)
 {
     Console.Write(
         $"Evals={pso.TotalEvals} | BestFit={pso.BestSoFar.fitness:f4}");
     Console.Write($" | AvgFit={pso.AvgFitCurr:f4}");
     // Console.Write(" @ (");
     // for (int i = 0; i < pso.BestSoFar.position.Count; i++)
     //     Console.Write($"{pso.BestSoFar.position[i]:f2}, ");
     //Console.Write(")");
     Console.WriteLine();
 }
Beispiel #9
0
        private void button1_Click(object sender, EventArgs e)
        {
            double[]    lb            = new double[] { -100, -100 };
            double[]    ub            = new double[] { 100, 100 };
            PSOSettings optimSettings = new PSOSettings();

            PSO    myPSO = new PSO(optimSettings, 2, G, lb, ub);
            double best  = myPSO.Optimize();

            Bitmap bmp = new Bitmap(750, 750);



            for (int numIters = 0; numIters < 1000; numIters++)
            {
                for (int i = 0; i < 750; i++)
                {
                    for (int j = 0; j < 750; j++)
                    {
                        bmp.SetPixel(i, j, Color.White);
                    }
                }


                for (int j = 0; j < 20; j++)
                {
                    int x = ScaleDim(myPSO.particleHistory[numIters][j][0], lb[0], ub[0], 750);
                    int y = ScaleDim(myPSO.particleHistory[numIters][j][1], lb[1], ub[1], 750);

                    if (x > 2 && x < 748 && y > 2 && y < 748)
                    {
                        for (int q = x - 2; q < x + 2; q++)
                        {
                            for (int r = y - 2; r < y + 2; r++)
                            {
                                bmp.SetPixel(q, r, Color.Red);
                            }
                        }
                    }
                    else
                    {
                        bmp.SetPixel(x, y, Color.Red);
                    }
                }

                //bmp.Save("C:\\Users\\fista\\Documents\\pso\\" + numIters.ToString() + ".png", System.Drawing.Imaging.ImageFormat.Png);

                pictureBox1.Image = bmp;
                pictureBox1.Invalidate();
                pictureBox1.Refresh();
                textBox1.Text = numIters.ToString();
            }
        }
Beispiel #10
0
        static void RunPSO(TravellingSalesmanMap TSP)
        {
            //cria novo PSO
            PSO pso = new PSO(TSP, 100, 10000, TSP.OptimalTravelDistance);

            //roda o PSO
            TSPSolution s = (TSPSolution)pso.Run();

            //imprime a solução
            Console.WriteLine("Optimal Solution: " + TSP.OptimalTravelDistance);
            Console.WriteLine("Solution Found: " + s.Fitness);
            Console.ReadKey();
        }
Beispiel #11
0
        private double AverageAbsoluteVelocity(PSO algorithm)
        {
            double sum = 0;

            //find the average absolute velocity
            for (int i = 0; i < algorithm.SwarmSize; i++)
            {
                Vector velocity = (Vector)algorithm.Particles[i].Velocity;

                //sum the elements of this particles velocity.
                for (int j = 0; j < velocity.Length; j++)
                {
                    sum += Math.Abs(velocity[j]);
                }
            }

            return(sum / (algorithm.SwarmSize * algorithm.Problem.Dimensions));
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            OptimTests myGoal = new StyblinskiTang(2);// (4, 100);

            double[] lb = new double[] { -100, -100, -100, -100, -100 };
            double[] ub = new double[] { 100, 100, 100, 100, 100 };

            PSOSettings optimSettings = new PSOSettings();
            PSO         myPSO         = new PSO(optimSettings, myGoal.numDims, myGoal.goalFunc, myGoal.lbounds, myGoal.ubounds);
            double      best          = myPSO.Optimize();

            Console.WriteLine("Best: " + best);
            Console.ReadLine();

            for (int i = 0; i < myPSO.gBestHistory.Count; i++)
            {
                Console.WriteLine(i + " " + myPSO.gBestHistory[i]);
            }
            Console.ReadLine();
        }
Beispiel #13
0
        public override void Adapt(PSO algorithm)
        {
            double avgVelocity   = AverageAbsoluteVelocity(algorithm);
            double idealVelocity = IdealVelocity(algorithm);

            for (int i = 0; i < algorithm.SwarmSize; i++)
            {
                StandardParticle particle = algorithm.Particles[i] as StandardParticle;
                double           newInertia;
                if (avgVelocity >= idealVelocity)
                {
                    newInertia = Math.Max(particle.Parameters.InertiaWeight.Parameter - Delta, Minimum);
                }
                else
                {
                    newInertia = Math.Min(particle.Parameters.InertiaWeight.Parameter + Delta, Maximum);
                }

                particle.Parameters.InertiaWeight = new ConstantControlParameter(newInertia);
            }
        }
    private void ThreadShession()
    {
        functions_queued.Add(ResetCars);
        thread_wait.WaitOne();
        thread_wait.Reset();

        BaseTechnique training;

        switch (training_technique)
        {
        case Techniques.PSO:
            training = new PSO(car_networks);
            break;

        case Techniques.GA:
            training = new GA(car_networks);
            break;

        default:
            log.Add("ERROR: Unkown training technique...");
            return;
        }

        while (!signal_session_stop)
        {
            log.Add("Reseting Cars");
            //Update car positions
            functions_queued.Add(() => {
                for (int i = 0; i < current_cars.Length; i++)
                {
                    car_body[i].velocity           = Vector3.zero;
                    car_body[i].angularVelocity    = Vector3.zero;
                    car_body[i].transform.position = spawner_position.transform.position;
                    car_body[i].transform.rotation = spawner_position.transform.rotation;
                    car_score_manager[i].ResetScore();
                    Debug.Log(i);
                }
                thread_wait.Set();
            });
            thread_wait.WaitOne();
            thread_wait.Reset();
            log.Add("Updating Weights");
            //Update car weights & biases
            training.UpdateWeights();
            //Start session to get car score
            for (int i = 0; i < agents_amount; i++)
            {
                car_intelligence[i].activate_car  = true;
                car_score_manager[i].activate_car = true;
                car_intelligence[i].GetNetwork().SetWeightsData(car_networks[i].GetWeightsData());
            }
            log.Add("Session Started");
            thread_session_wait.Reset();
            session_timer = session_length;
            thread_session_wait.WaitOne();
            if (!signal_session_stop)
            {
                //Stop session
                for (int i = 0; i < agents_amount; i++)
                {
                    car_intelligence[i].activate_car  = false;
                    car_score_manager[i].activate_car = false;
                    car_networks[i].SetNetworkScore(car_intelligence[i].GetNetwork().GetNetworkScore());
                }
                log.Add("Comparing Results");
                //Compare all cars scores
                training.ComputeEpoch();
                //Update log info
                best_score   = training.GetBestScore();
                best_weights = training.GetBestWeights();
                current_epoch++;
            }
        }
        session_activated = false;
    }
 public bool Detect(PSO algorithm)
 {
     return(true);
 }
Beispiel #16
0
        static void Main(string[] args)
        {
            Console.WriteLine("Testing PSO");

            //defines the number of variables needed
            //here, {x,y}
            //if more are needed, add them to the testPositionVector
            //ex. {x1, y1, z1, x2, y2, z2, ...}
            List <float> testPositionVector = new List <float>()
            {
                0, 0
            };

            //defines the boundaries for each variable in an NxM dimensional list of lists
            //ex. {{xmin, xmax}, { ymin, ymax}}
            List <List <float> > testPositionBoundaries = new List <List <float> >()
            {
                new List <float>()
                {
                    -3f, 3f
                },
                new List <float>()
                {
                    -2f, 2f
                }
            };

            //defines the maximum move rate of the particles in the swarm
            //choose wisely so that particles do not move too quickly around the solution space
            float maximumparticlevelocity = 0.0001f;

            //create and initilize the swarm
            //define the objective function based on list like the previously defined testPositionVector
            //here refer to the testObjective method
            PSO mySwarm = new PSO(testPositionVector, testPositionBoundaries, maximumparticlevelocity, testObjective);

            //define a seed based on the computers current time
            //to use a unique seed each run and record it use the following line.
            //(int)DateTime.Now.Ticks & 0x0000FFFF;
            int seed = 3611;// 10210;

            //reset the swarms random number generator; used for repeatability
            //here defined above
            mySwarm.setRNGseed(seed);

            //reset rho values tht balance personal and population cognition
            //here, more weight is placed on personal cognition
            //rho1 + rho2 should sum to 4 if using constriction (K)
            //uncomment
            //mySwarm.setRhoValues(2.25f, 1.75f);

            //use constriction parameter (K) to modify amount of modification of velocity updates
            //uncomment
            //mySwarm.setK(true);

            //run your swarm for some number of iterations with some number of particles
            List <float> output = mySwarm.Run(100000, 10);//minimize

            Console.Write("Best found solution: (");
            for (int i = 0; i < output.Count; i++)
            {
                Console.Write(mySwarm.getGlobalBestPositionVector()[i] + " ");
            }
            Console.Write(") " + mySwarm.getGlobalBestObjectiveFunctionValue());
            Console.Write("\tseed= " + seed);

            Console.WriteLine("\r\n\r\nglobal min = (0.094262, -0.71509) -1.031514");

            Console.ReadKey();  //wait for input
        }
Beispiel #17
0
        private double IdealVelocity(PSO algorithm)
        {
            double factor = algorithm.CalculateCompletion() / 0.95;

            return(_initialVelocity * ((1 + Math.Cos(factor * Math.PI)) / 2));
        }
Beispiel #18
0
    // Use this for initialization
    void Start()
    {
        // You can change that line to provide another MeshFilter
        MeshFilter filter = gameObject.GetComponent <MeshFilter>();
        Mesh       mesh   = filter.mesh;

        mesh.Clear();

        float length = 1f;
        float width  = 1f;
        int   resX   = 100; // 2 minimum
        int   resZ   = 100;

        #region Vertices
        Vector3[] vertices = new Vector3[resX * resZ];
        for (int z = 0; z < resZ; z++)
        {
            // [ -length / 2, length / 2 ]
            float zPos = ((float)z / (resZ - 1)) * length;
            for (int x = 0; x < resX; x++)
            {
                // [ -width / 2, width / 2 ]
                float xPos = ((float)x / (resX - 1)) * width;

                float y = (float)PSO.SimpleOptimFunction(new float[] { xPos, zPos });

                vertices[x + z * resX] = new Vector3(xPos, y, zPos);
            }
        }
        #endregion

        #region Normales
        Vector3[] normales = new Vector3[vertices.Length];
        for (int n = 0; n < normales.Length; n++)
        {
            normales[n] = Vector3.up;
        }
        #endregion

        #region UVs
        Vector2[] uvs = new Vector2[vertices.Length];
        for (int v = 0; v < resZ; v++)
        {
            for (int u = 0; u < resX; u++)
            {
                uvs[u + v * resX] = new Vector2((float)u / (resX - 1), (float)v / (resZ - 1));
            }
        }
        #endregion

        #region Triangles
        int   nbFaces   = (resX - 1) * (resZ - 1);
        int[] triangles = new int[nbFaces * 6];
        int   t         = 0;
        for (int face = 0; face < nbFaces; face++)
        {
            // Retrieve lower left corner from face ind
            int i = face % (resX - 1) + (face / (resZ - 1) * resX);

            triangles[t++] = i + resX;
            triangles[t++] = i + 1;
            triangles[t++] = i;

            triangles[t++] = i + resX;
            triangles[t++] = i + resX + 1;
            triangles[t++] = i + 1;
        }
        #endregion

        mesh.vertices  = vertices;
        mesh.normals   = normales;
        mesh.uv        = uvs;
        mesh.triangles = triangles;

        mesh.RecalculateBounds();
    }
Beispiel #19
0
        public Dictionary <string, double> Optimize()
        {
            double initialPortfolioValue = 100000;

            //create list containing all the forecasted values for all the indexes
            List <List <double> > forecastIndexes = new List <List <double> >();
            var path = @"Models/forecast.csv";

            using (TextFieldParser csvParser = new TextFieldParser(path))
            {
                csvParser.CommentTokens = new string[] { "#" };
                csvParser.SetDelimiters(new string[] { "," });
                csvParser.HasFieldsEnclosedInQuotes = true;

                // Skip the row with the column names, ma non c'è
                //csvParser.ReadLine();
                var index = 0;

                while (!csvParser.EndOfData)
                {
                    // Read current line fields, pointer moves to the next line.
                    string[] fields = csvParser.ReadFields();
                    Console.WriteLine(fields[0]);
                    List <double> tmpList = new List <double>();
                    for (int i = 0; i < 120; i++)
                    {
                        tmpList.Add(Double.Parse(fields[i].Replace('.', ',')));
                    }
                    forecastIndexes.Add(tmpList);
                    index++;
                }
            }
            //forecastIndexes.ForEach(a => a.ForEach(Console.Write));
            //create list of all index variations over time
            List <List <double> > variations = new List <List <double> >();
            var id = 0;

            forecastIndexes.ForEach(index =>
            {
                var variationsTmp = new List <double>();
                for (int i = 0; i < index.Count; i++)
                {
                    if (i == 0)
                    {
                        variationsTmp.Add(0);
                    }
                    else
                    {
                        variationsTmp.Add((forecastIndexes[id][i] - forecastIndexes[id][i - 1]) / forecastIndexes[id][i - 1]);
                    }
                }
                variations.Add(variationsTmp);
                id++;
            });

            //PSO pso = new PSO(2,16,1,1,1, variations, initialPortfolioValue);
            PSO pso = new PSO(2, 16, 0.25, 1, 1, variations, initialPortfolioValue);

            //pso.optimize(15, 7, 20, 4);
            pso.optimize(50, 7, 60, 10);

            Console.WriteLine(variations[0][100]);

            Dictionary <string, double> indexPerc = new Dictionary <string, double>();
            var indexes = new string[] { "SP_500", "FTSE_MIB_", "GOLD_SPOT", "MSCI_EM", "MSCI_EURO", "All_Bonds", "Us_Treasury" };
            var it      = 0;

            pso.xbest.ForEach(id =>
            {
                //fai un enum
                indexPerc.Add(indexes[it++], Math.Round(id, 2));
            });

            String csv = String.Join(
                Environment.NewLine,
                indexPerc.Select(d => $"{d.Key}: {d.Value};")
                );

            System.IO.File.WriteAllText("percs.csv", csv);

            return(indexPerc);
        }
        /// <summary>
        /// Initializes bias values of activation neurons in the activation layer.
        /// </summary>
        /// <param name="activationLayer">
        /// The activation layer to initialize
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// If <c>activationLayer</c> is <c>null</c>
        /// </exception>
        public void Initialize(PSO.ActivationLayer activationLayer)
        {
            Helper.ValidateNotNull(activationLayer, "activationLayer");

            int hiddenNeuronCount = 0;
            foreach (IConnector targetConnector in activationLayer.TargetConnectors)
            {
                hiddenNeuronCount += targetConnector.TargetLayer.NeuronCount;
            }

            double nGuyenWidrowFactor = NGuyenWidrowFactor(activationLayer.NeuronCount, hiddenNeuronCount);

            foreach (PSO.ActivationNeuron neuron in activationLayer.Neurons)
            {
                neuron.bias = Helper.GetRandom(-nGuyenWidrowFactor, nGuyenWidrowFactor);
            }
        }
        /// <summary>
        /// Initializes weights of all backpropagation synapses in the backpropagation connector.
        /// </summary>
        /// <param name="connector">
        /// The backpropagation connector to initialize.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// If <c>connector</c> is <c>null</c>
        /// </exception>
        public void Initialize(PSO.PSOConnector connector)
        {
            Helper.ValidateNotNull(connector, "connector");

            double nGuyenWidrowFactor = NGuyenWidrowFactor(
                connector.SourceLayer.NeuronCount, connector.TargetLayer.NeuronCount);

            int synapsesPerNeuron = connector.SynapseCount / connector.TargetLayer.NeuronCount;

            foreach (INeuron neuron in connector.TargetLayer.Neurons)
            {
                int i = 0;
                double[] normalizedVector = Helper.GetRandomVector(synapsesPerNeuron, nGuyenWidrowFactor);
                foreach (PSO.PSOSynapse synapse in connector.GetSourceSynapses(neuron))
                {
                    synapse.Weight = normalizedVector[i++];
                    if (i >= synapsesPerNeuron)
                    {
                        break;
                    }
                }
            }
        }
Beispiel #22
0
 /// <summary>
 /// Perform the adaptation.
 /// </summary>
 /// <param name="algorithm"></param>
 public abstract void Adapt(PSO algorithm);
Beispiel #23
0
 /// <summary>
 /// Initializes bias values of activation neurons in the activation layer.
 /// </summary>
 /// <param name="activationLayer">
 /// The activation layer to initialize
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// If <c>activationLayer</c> is <c>null</c>
 /// </exception>
 public void Initialize(PSO.ActivationLayer activationLayer)
 {
     Helper.ValidateNotNull(activationLayer, "layer");
     foreach (PSO.ActivationNeuron neuron in activationLayer.Neurons)
     {
         neuron.bias = constant;
     }
 }
Beispiel #24
0
 /// <summary>
 /// Initializes bias values of activation neurons in the activation layer.
 /// </summary>
 /// <param name="activationLayer">
 /// The activation layer to initialize
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// If <c>activationLayer</c> is <c>null</c>
 /// </exception>
 public void Initialize(PSO.ActivationLayer activationLayer)
 {
     Helper.ValidateNotNull(activationLayer, "layer");
     foreach (PSO.ActivationNeuron neuron in activationLayer.Neurons)
     {
         neuron.bias = Helper.GetRandom(minLimit, maxLimit);
     }
 }
Beispiel #25
0
 /// <summary>
 /// Initializes weights of all backpropagation synapses in the backpropagation connector.
 /// </summary>
 /// <param name="connector">
 /// The backpropagation connector to initialize.
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// If <c>connector</c> is <c>null</c>
 /// </exception>
 public void Initialize(PSO.PSOConnector connector)
 {
     Helper.ValidateNotNull(connector, "connector");
     foreach (PSO.PSOSynapse synapse in connector.Synapses)
     {
         synapse.Weight = constant;
     }
 }
 public override void Adapt(PSO algorithm)
 {
     //do nothing!
 }
Beispiel #27
0
        private void TrataF4Linhas(int col, int row)
        {
            // Artigos
            if (col == priGrelha1.Cols.GetEdita(colArtigo).Number)
            {
                PSO.AbreLista(1, ConstantesPrimavera100.Categorias.Artigo, "Artigo", this.ParentForm, priGrelha1.Grelha, "mnuTabArtigo", row, col, false, "(ArtigoAnulado = 0)");
            }
            else
            {
                string artigo = PSO.Utils.FStr(priGrelha1.GetGRID_GetValorCelula(row, colArtigo));

                if (!string.IsNullOrWhiteSpace(artigo))
                {
                    // Lotes
                    if (col == priGrelha1.Cols.GetEdita(colLote).Number)
                    {
                        PSO.AbreLista(1, ConstantesPrimavera100.Categorias.ArtigoLote, "Lote", this.ParentForm, priGrelha1.Grelha, ConstantesPrimavera100.Audit.TAB_ARTIGOS, row, col, false, string.Format("([ARTIGOLOTE].Artigo = '{0}')", artigo));
                    }

                    // Entidade
                    if (col == priGrelha1.Cols.GetEdita(colEntidade).Number)
                    {
                        string categoria = ConstantesPrimavera100.Categorias.Cliente;
                        string audit     = ConstantesPrimavera100.Audit.TAB_CLIENTES;
                        string campo     = "Cliente";
                        string where = "(ClienteAnulado = 0)";

                        switch (PSO.Utils.FInt(priGrelha1.GetGRID_GetValorCelula(row, colTipoEntidade)))
                        {
                        case 1:
                            categoria = ConstantesPrimavera100.Categorias.Fornecedor;
                            audit     = ConstantesPrimavera100.Audit.TAB_FORNECEDORES;
                            campo     = "Fornecedor";
                            where     = "(FornecedorAnulado = 0)";
                            break;

                        case 2:
                            categoria = ConstantesPrimavera100.Categorias.OutroTerceiro;
                            audit     = ConstantesPrimavera100.Audit.TAB_OUTROSTERC;
                            campo     = "Terceiro";
                            where     = "(Anulado = 0)";
                            break;

                        default:
                            break;
                        }
                        PSO.AbreLista(1, categoria, campo, this.ParentForm, priGrelha1.Grelha, audit, row, col, false, where);
                    }

                    // Armazém
                    if (col == priGrelha1.Cols.GetEdita(colArmazem).Number)
                    {
                        PSO.AbreLista(1, ConstantesPrimavera100.Categorias.Armazem, "Armazem", this.ParentForm, priGrelha1.Grelha, ConstantesPrimavera100.Audit.TAB_ARMAZENS, row, col, false);
                    }

                    // Localização
                    if (col == priGrelha1.Cols.GetEdita(colLocalizacao).Number)
                    {
                        string armazem = PSO.Utils.FStr(priGrelha1.GetGRID_GetValorCelula(row, colArmazem));
                        PSO.AbreLista(1, ConstantesPrimavera100.Categorias.ArmazemLocalizacoes, "Localizacao", this.ParentForm, priGrelha1.Grelha, ConstantesPrimavera100.Audit.TAB_ARMAZEMLOCALIZACAO, row, col, false, string.Format("(Armazem = '{0}')", armazem));
                    }

                    // Estado
                    if (col == priGrelha1.Cols.GetEdita(colEstado).Number)
                    {
                        PSO.AbreLista(1, ConstantesPrimavera100.Categorias.EstadosInventario, "Estado", this.ParentForm, priGrelha1.Grelha, ConstantesPrimavera100.Audit.TAB_ESTADOS_INVENTARIO, row, col, false, "Disponivel = 0 AND EstadoReserva = 0 AND Previsto = 0 AND Transito = 0");
                    }
                }
            }
        }
Beispiel #28
0
 /// <summary>
 /// Called before the adaptation phase occurs.
 /// </summary>
 /// <param name="algorithm"></param>
 public virtual void PreAdaptation(PSO algorithm)
 {
 }
Beispiel #29
0
 /// <summary>
 /// Initializes weights of all backpropagation synapses in the backpropagation connector.
 /// </summary>
 /// <param name="connector">
 /// The backpropagation connector to initialize.
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// If <c>connector</c> is <c>null</c>
 /// </exception>
 public void Initialize(PSO.PSOConnector connector)
 {
     Helper.ValidateNotNull(connector, "connector");
     foreach (PSO.PSOSynapse synapse in connector.Synapses)
     {
         synapse.Weight = Helper.GetRandom(minLimit, maxLimit);
     }
 }
Beispiel #30
0
 /// <summary>
 /// Called on the first iteration.
 /// </summary>
 /// <param name="algorithm"></param>
 public virtual void Initialization(PSO algorithm)
 {
 }
Beispiel #31
0
 public bool Detect(PSO algorithm)
 {
     return(algorithm.Iteration % Period.Parameter == 0);
 }
Beispiel #32
0
 /// <summary>
 /// Called after the adaptation occurs.
 /// </summary>
 /// <param name="algorithm"></param>
 public virtual void PostIteration(PSO algorithm)
 {
 }
Beispiel #33
0
        public static void Main(string[] args)
        {
            #region Read input from file
            int   NoJob;
            int   NoMc;
            int[] NoOp;
            job[] Job;
            ReadInput.ReadfromFile(out NoJob, out NoMc, out NoOp, out Job);
            #endregion
            #region calculateDimension
            int[]     NoOpPerMc = new int[NoMc];
            machine[] Machine   = new machine[NoMc];
            ReadInput.MachineInfo(NoJob, NoOp, ref NoOpPerMc, Job);
            JSPdata JD        = new JSPdata(NoJob, NoMc, NoOp, Job, NoOpPerMc, Machine);
            int     Dimension = 0; //To calculate Dimension = Sum of all NoOp
            for (int j = 0; j < NoJob; j++)
            {
                Dimension += NoOp[j];
            }
            #endregion
            #region set PSO's parameters
            int    noPar  = 50;
            int    noIter = 1000;
            int    noNB   = 5;
            double wMax   = 0.9;
            double wMin   = 0.4;
            double cP     = 1.6;
            double cG     = 0;
            double cL     = 1.6;
            double cN     = 0;

            string oFile = "MyPSO.xls";

            double MigrateProp = 0.1;
            bool   multiSwarm  = false;
            int    noSwarm     = 5;

            int startReinit   = 1000000;
            int ReInitIterval = 1000;
            int startLS       = 100000;
            int LSinterval    = 100;
            #endregion

            //Number of replication
            int noRep = 30;
            // starting time and finish time using DateTime datatype
            DateTime start, finish;
            // elapsed time using TimeSpan datatype

            TimeSpan elapsed;
            #region createoutputFile
            // opening output file
            TextWriter tw = new StreamWriter(oFile);
            tw.WriteLine("{0} Number of Particle  ", noPar);
            tw.WriteLine("{0} Number of Iteration ", noIter);
            tw.WriteLine("{0} Number of Neighbor  ", noNB);
            tw.WriteLine("{0} Parameter wmax      ", wMax);
            tw.WriteLine("{0} Parameter wmin      ", wMin);
            tw.WriteLine("{0} Parameter cp        ", cP);
            tw.WriteLine("{0} Parameter cg        ", cG);
            tw.WriteLine("{0} Parameter cl        ", cL);
            tw.WriteLine("{0} Parameter cn        ", cN);
            tw.WriteLine("{0} Output File Name    ", oFile);
            tw.WriteLine("");
            #endregion

            for (int i = 0; i < noRep; i++)
            {
                tw.WriteLine("Replication {0}", i + 1);
                // get the starting time from CPU clock
                start = DateTime.Now;

                // main program ...
                PSO[] subSwarm = new PSO[noSwarm - 1];
                #region Activate sub-swarms
                if (multiSwarm)
                {
                    for (int s = 0; s < noSwarm - 1; s++)
                    {
                        Console.WriteLine("Start swarm {0}", s);
                        subSwarm[s] = new spPSO(noPar, noIter, noNB, wMax, wMin, cP, cG, cL, cN, Dimension, JD, startReinit, ReInitIterval, startLS, LSinterval);
                        if (s != 0)
                        {
                            subSwarm[s].Migrate(subSwarm[s - 1].sSwarm, subSwarm[s].sSwarm, MigrateProp);
                        }
                        subSwarm[s].Run(tw, true);

                        subSwarm[s].DisplayResult(tw);
                        Console.WriteLine("Obj {0} ", subSwarm[s].sSwarm.pParticle[subSwarm[s].sSwarm.posBest].ObjectiveP);
                    }
                }
                #endregion
                PSO globalSwarm = new spPSO(noPar, noIter, noNB, wMax, wMin, cP, cG, cL, cN, Dimension, JD, startReinit, ReInitIterval, startLS, LSinterval);
                Console.WriteLine("Start final swarm");
                Console.WriteLine("Replication {0}", i + 1);
                if (multiSwarm)
                {
                    for (int s = 0; s < noSwarm - 1; s++)
                    {
                        globalSwarm.MigrateBest(subSwarm[s].sSwarm, globalSwarm.sSwarm, 1 / ((double)noSwarm - 1));
                    }
                }
                globalSwarm.Run(tw, true);

                globalSwarm.DisplayResult(tw);
                Console.WriteLine("Obj {0} ", globalSwarm.sSwarm.pParticle[globalSwarm.sSwarm.posBest].ObjectiveP);
                // get the finishing time from CPU clock
                #region createreport
                finish  = DateTime.Now;
                elapsed = finish - start;

                // display the elapsed time in hh:mm:ss.milli
                tw.WriteLine("{0} is the computational time", elapsed.Duration());
                Console.WriteLine("{0} is the computational time", elapsed.Duration());
                tw.WriteLine("");
                #endregion
            }
            Console.ReadKey();
            tw.Close();
        }
Beispiel #34
0
        public void test()
        {
            string          cfile         = "C:\\Users\\Administrator\\Desktop\\Optimizer\\";
            General         G             = new General();
            JADE            JADE          = new JADE();
            Nelder_Mead     Nelder_Mead   = new Nelder_Mead();
            CMA_ES          CMA_ES        = new CMA_ES();
            CoDE            CoDE          = new CoDE();
            PSO             PSO           = new PSO();
            PatternSearch   PatternSearch = new PatternSearch();
            DE_rand_1       DE_rand_1     = new DE_rand_1();
            DE_best_1       DE_best_1     = new DE_best_1();
            DE_rand_2       DE_rand_2     = new DE_rand_2();
            DE_best_2       DE_best_2     = new DE_best_2();
            Stopwatch       stopwatch     = new Stopwatch();
            Random          rd            = new Random();
            List <string[]> comeout       = new List <string[]>();
            List <string[]> fun           = new List <string[]>();
            List <string[]> time          = new List <string[]>();

            int[] X_Dim     = new int[20];
            int   TotalRuns = 30;

            for (int i = 0; i < X_Dim.Length; i++)
            {
                X_Dim[i] = 2 * (i + 3);
            }

            string[] Table_Head2 = new string[11] {
                "X_Dim", "JADE", "Nelder_Mead", "CMA_ES", "CoDE", "PSO", "PatternSearch", "DE_rand_1", "DE_best_1", "DE_rand_2", "DE_best_2"
            };
            fun.Add(Table_Head2);
            time.Add(Table_Head2);

            for (int ii = 10; ii < X_Dim.Length; ii++)
            {
                Console.WriteLine("X_Dim: " + X_Dim[ii]);
                double[] X_Opt     = new double[X_Dim[ii]]; // 最优解
                double[] X_I       = new double[X_Dim[ii]];
                double[] X_MaxStep = new double[X_Dim[ii]];
                double[] X_Lb      = new double[X_Dim[ii]];
                double[] X_Ub      = new double[X_Dim[ii]];

                for (int k = 0; k < X_Dim[ii] - 1; k++)
                {
                    X_MaxStep[k] = 100.0;
                    X_Lb[k]      = 0;
                }
                X_MaxStep[X_Dim[ii] - 1] = 100.0;
                X_Lb[X_Dim[ii] - 1]      = Math.PI;
                for (int k = 0; k < X_Dim[ii] / 2 - 1; k++)
                {
                    X_Ub[k] = 1;
                }
                X_Ub[X_Dim[ii] / 2 - 1] = 0;
                for (int k = X_Dim[ii] / 2; k < X_Dim[ii]; k++)
                {
                    X_Ub[k] = Math.PI;
                }

                double[] JADE_Fun    = new double[TotalRuns];
                double[] JADE_Time   = new double[TotalRuns];
                string   JADE_Config = cfile + "JADE.csv";

                double[] Nelder_Mead_Fun    = new double[TotalRuns];
                double[] Nelder_Mead_Time   = new double[TotalRuns];
                string   Nelder_Mead_Config = cfile + "Nelder_Mead.csv";

                double[] CMA_ES_Fun    = new double[TotalRuns];
                double[] CMA_ES_Time   = new double[TotalRuns];
                string   CMA_ES_Config = cfile + "CMA_ES.csv";

                double[] CoDE_Fun    = new double[TotalRuns];
                double[] CoDE_Time   = new double[TotalRuns];
                string   CoDE_Config = cfile + "CoDE.csv";

                double[] PSO_Fun    = new double[TotalRuns];
                double[] PSO_Time   = new double[TotalRuns];
                string   PSO_Config = cfile + "PSO.csv";

                double[] PatternSearch_Fun    = new double[TotalRuns];
                double[] PatternSearch_Time   = new double[TotalRuns];
                string   PatternSearch_Config = cfile + "PatternSearch.csv";

                double[] DE_rand_1_Fun    = new double[TotalRuns];
                double[] DE_rand_1_Time   = new double[TotalRuns];
                string   DE_rand_1_Config = cfile + "DE_rand_1.csv";

                double[] DE_best_1_Fun    = new double[TotalRuns];
                double[] DE_best_1_Time   = new double[TotalRuns];
                string   DE_best_1_Config = cfile + "DE_best_1.csv";

                double[] DE_rand_2_Fun    = new double[TotalRuns];
                double[] DE_rand_2_Time   = new double[TotalRuns];
                string   DE_rand_2_Config = cfile + "DE_rand_2.csv";

                double[] DE_best_2_Fun    = new double[TotalRuns];
                double[] DE_best_2_Time   = new double[TotalRuns];
                string   DE_best_2_Config = cfile + "DE_best_2.csv";

                for (int i = 0; i < TotalRuns; i++)
                {
                    for (int k = 0; k < X_Dim[ii]; k++)
                    {
                        X_I[k] = G.rnd_uni(rd) * (X_Ub[k] - X_Lb[k]) + X_Lb[k];
                    }

                    stopwatch.Start();
                    X_Opt = JADE.StartOpt(JADE_Config, X_I, X_MaxStep, X_Lb, X_Ub, out JADE_Fun[i]);
                    stopwatch.Stop();
                    JADE_Time[i] = stopwatch.Elapsed.TotalSeconds;
                    Console.WriteLine("JADE: run: " + (i + 1) + ", time(s): " + stopwatch.Elapsed.TotalSeconds);
                    stopwatch.Reset();

                    stopwatch.Start();
                    X_Opt = Nelder_Mead.StartOpt(Nelder_Mead_Config, X_I, X_MaxStep, X_Lb, X_Ub, out Nelder_Mead_Fun[i]);
                    stopwatch.Stop();
                    Nelder_Mead_Time[i] = stopwatch.Elapsed.TotalSeconds;
                    Console.WriteLine("Nelder_Mead: run: " + (i + 1) + ", time(s): " + stopwatch.Elapsed.TotalSeconds);
                    stopwatch.Reset();

                    stopwatch.Start();
                    X_Opt = CMA_ES.StartOpt(CMA_ES_Config, X_I, X_MaxStep, X_Lb, X_Ub, out CMA_ES_Fun[i]);
                    stopwatch.Stop();
                    CMA_ES_Time[i] = stopwatch.Elapsed.TotalSeconds;
                    Console.WriteLine("CMA_ES: run: " + (i + 1) + ", time(s): " + stopwatch.Elapsed.TotalSeconds);
                    stopwatch.Reset();

                    stopwatch.Start();
                    X_Opt = CoDE.StartOpt(CoDE_Config, X_I, X_MaxStep, X_Lb, X_Ub, out CoDE_Fun[i]);
                    stopwatch.Stop();
                    CoDE_Time[i] = stopwatch.Elapsed.TotalSeconds;
                    Console.WriteLine("CoDE: run: " + (i + 1) + ", time(s): " + stopwatch.Elapsed.TotalSeconds);
                    stopwatch.Reset();

                    stopwatch.Start();
                    X_Opt = PSO.StartOpt(PSO_Config, X_I, X_MaxStep, X_Lb, X_Ub, out PSO_Fun[i]);
                    stopwatch.Stop();
                    PSO_Time[i] = stopwatch.Elapsed.TotalSeconds;
                    Console.WriteLine("PSO: run: " + (i + 1) + ", time(s): " + stopwatch.Elapsed.TotalSeconds);
                    stopwatch.Reset();

                    stopwatch.Start();
                    X_Opt = PatternSearch.StartOpt(PatternSearch_Config, X_I, X_MaxStep, X_Lb, X_Ub, out PatternSearch_Fun[i]);
                    stopwatch.Stop();
                    PatternSearch_Time[i] = stopwatch.Elapsed.TotalSeconds;
                    Console.WriteLine("PatternSearch: run: " + (i + 1) + ", time(s): " + stopwatch.Elapsed.TotalSeconds);
                    stopwatch.Reset();

                    stopwatch.Start();
                    X_Opt = DE_rand_1.StartOpt(DE_rand_1_Config, X_I, X_MaxStep, X_Lb, X_Ub, out DE_rand_1_Fun[i]);
                    stopwatch.Stop();
                    DE_rand_1_Time[i] = stopwatch.Elapsed.TotalSeconds;
                    Console.WriteLine("DE_rand_1: run: " + (i + 1) + ", time(s): " + stopwatch.Elapsed.TotalSeconds);
                    stopwatch.Reset();

                    stopwatch.Start();
                    X_Opt = DE_best_1.StartOpt(DE_best_1_Config, X_I, X_MaxStep, X_Lb, X_Ub, out DE_best_1_Fun[i]);
                    stopwatch.Stop();
                    DE_best_1_Time[i] = stopwatch.Elapsed.TotalSeconds;
                    Console.WriteLine("DE_best_1: run: " + (i + 1) + ", time(s): " + stopwatch.Elapsed.TotalSeconds);
                    stopwatch.Reset();

                    stopwatch.Start();
                    X_Opt = DE_rand_2.StartOpt(DE_rand_2_Config, X_I, X_MaxStep, X_Lb, X_Ub, out DE_rand_2_Fun[i]);
                    stopwatch.Stop();
                    DE_rand_2_Time[i] = stopwatch.Elapsed.TotalSeconds;
                    Console.WriteLine("DE_rand_2: run: " + (i + 1) + ", time(s): " + stopwatch.Elapsed.TotalSeconds);
                    stopwatch.Reset();

                    stopwatch.Start();
                    X_Opt = DE_best_2.StartOpt(DE_best_2_Config, X_I, X_MaxStep, X_Lb, X_Ub, out DE_best_2_Fun[i]);
                    stopwatch.Stop();
                    DE_best_2_Time[i] = stopwatch.Elapsed.TotalSeconds;
                    Console.WriteLine("DE_best_2: run: " + (i + 1) + ", time(s): " + stopwatch.Elapsed.TotalSeconds);
                    stopwatch.Reset();
                }

                if (true)
                {
                    string[] Dim = new string[2] {
                        "X_DIM", X_Dim[ii].ToString()
                    };
                    string[] Table_Head1 = new string[8] {
                        "Algorithm", "Mean", "StandardDeviation", "Min", "Max", "MeanTime(s)", "MinTime(s)", "MaxTime(s)"
                    };

                    comeout.Add(Dim);
                    comeout.Add(Table_Head1);
                    comeout.Add(data_process("JADE", JADE_Fun, JADE_Time));
                    comeout.Add(data_process("Nelder_Mead", Nelder_Mead_Fun, Nelder_Mead_Time));
                    comeout.Add(data_process("CMA_ES", CMA_ES_Fun, CMA_ES_Time));
                    comeout.Add(data_process("CoDE", CoDE_Fun, CoDE_Time));
                    comeout.Add(data_process("PSO", PSO_Fun, PSO_Time));
                    comeout.Add(data_process("PatternSearch", PatternSearch_Fun, PatternSearch_Time));
                    comeout.Add(data_process("DE_rand_1", DE_rand_1_Fun, DE_rand_1_Time));
                    comeout.Add(data_process("DE_best_1", DE_best_1_Fun, DE_best_1_Time));
                    comeout.Add(data_process("DE_rand_2", DE_rand_2_Fun, DE_rand_2_Time));
                    comeout.Add(data_process("DE_best_2", DE_best_2_Fun, DE_best_2_Time));

                    string comeoutPath = cfile + "comeout_" + X_Dim[ii].ToString() + ".csv";
                    G.WriteCSV(comeoutPath, false, comeout);

                    fun.Add(data_process1(X_Dim[ii], JADE_Fun, Nelder_Mead_Fun, CMA_ES_Fun, CoDE_Fun, PSO_Fun, PatternSearch_Fun, DE_rand_1_Fun, DE_best_1_Fun, DE_rand_2_Fun, DE_best_2_Fun));
                    time.Add(data_process1(X_Dim[ii], JADE_Time, Nelder_Mead_Time, CMA_ES_Time, CoDE_Time, PSO_Time, PatternSearch_Time, DE_rand_1_Time, DE_best_1_Time, DE_rand_2_Time, DE_best_2_Time));
                }
            }
            string comeoutPath1 = cfile + "fun.csv";

            G.WriteCSV(comeoutPath1, false, fun);
            string comeoutPath2 = cfile + "time.csv";

            G.WriteCSV(comeoutPath2, false, time);
        }