Пример #1
0
    Velocity Solver::getRandomVelocity()
    {
        Velocity velocity;

        for (int i = 0; i < currentProblem->n; ++i) {
            double randomVariable = getRandomDoubleValue(0.0, 1.0);

            velocity.push_back(randomVariable);
        }

        return velocity;
    }
Пример #2
0
    void Solver::findSolution()
    {
        for (auto &i : swarm.getParticles()) {
            Velocity newVelocity;
            Solution newPosition;

            /**
             * Iterate through all dimensions of a Solution/position
             * to calculate the new velocity and update the position.
             *
             * j = dimension
             */
            for (int j = 0; j < currentProblem->n; ++j) {
                int currentPositionD = i.getPosition().at(j);
                double currentVelocityD = i.getVelocity().at(j);

                int pBestD = i.getBestPosition().at(j);
                int gBestD = swarm.getBestPosition().at(j);

                int randomParticleNumber = getRandomIntegerValue(0, 1);
                int randomGlobalNumber = getRandomIntegerValue(0, 1);

                double newVelocityD = parameters.getInertiaWeight() * currentVelocityD +
                                      parameters.getConstant1() * randomParticleNumber * (pBestD - currentPositionD) +
                                      parameters.getConstant2() * randomGlobalNumber * (gBestD - currentPositionD);

                if (newVelocityD > parameters.getVMax())
                    newVelocityD = parameters.getVMax();
                else if (newVelocityD < -parameters.getVMax())
                    newVelocityD = -parameters.getVMax();

                int newPositionD = updateStrategy->updatePosition(currentPositionD, newVelocityD);

                newVelocity.push_back(newVelocityD);
                newPosition.push_back(newPositionD);
            }

            i.setVelocity(newVelocity);
            i.setPosition(newPosition);

            int pBestTmp = calculateProfit(i.getPosition());
            pBestTmp -= calculatePenalty(i.getPosition(), pBestTmp);

            // Update pBest and gBest position/solution
            if (pBestTmp > i.getBestValue()) {
                i.setBestPositionAndValue(i.getPosition(), pBestTmp);

                if (pBestTmp > swarm.getBestValue())
                    swarm.setBestPositionAndValue(i.getPosition(), pBestTmp);
            }
        }
    }