Пример #1
0
    def update(self, space: Space) -> None:
        """Wraps Boolean Particle Swarm Optimization over all agents and variables.

        Args:
            space: Space containing agents and update-related information.

        """

        # Iterates through all agents
        for i, agent in enumerate(space.agents):
            # Defines random binary numbers
            r1 = r.generate_binary_random_number(agent.position.shape)
            r2 = r.generate_binary_random_number(agent.position.shape)

            # Calculates the local and global partials
            local_partial = np.logical_and(
                self.c1,
                np.logical_xor(
                    r1, np.logical_xor(self.local_position[i],
                                       agent.position)),
            )
            global_partial = np.logical_and(
                self.c2,
                np.logical_xor(
                    r2,
                    np.logical_xor(space.best_agent.position, agent.position)),
            )

            # Updates current agent velocities (eq. 1)
            self.velocity[i] = np.logical_or(local_partial, global_partial)

            # Updates current agent positions (eq. 2)
            agent.position = np.logical_xor(agent.position, self.velocity[i])
Пример #2
0
    def _somersault_foraging(self, position, best_position):
        """Performs the somersault foraging procedure.

        Args:
            position (np.array): Agent's current position.
            best_position (np.array): Global best position.

        Returns:
            A new somersault foraging.

        """

        # Generates binary random numbers
        r1 = r.generate_binary_random_number(best_position.shape)
        r2 = r.generate_binary_random_number(best_position.shape)

        # Calculates the somersault foraging
        somersault_foraging = np.logical_or(
            position,
            np.logical_and(
                self.S,
                np.logical_xor(np.logical_xor(r1, best_position),
                               np.logical_xor(r2, position))))

        return somersault_foraging
Пример #3
0
    def _chain_foraging(self, agents, best_position, i):
        """Performs the chain foraging procedure.

        Args:
            agents (list): List of agents.
            best_position (np.array): Global best position.
            i (int): Current agent's index.

        Returns:
            A new chain foraging.

        """

        # Generates binary random numbers
        r1 = r.generate_binary_random_number(best_position.shape)
        alpha = r.generate_binary_random_number(best_position.shape)

        # Checks if the index is equal to zero
        if i == 0:
            # Calculates the chain foraging
            partial_one = np.logical_and(r1, np.logical_xor(best_position, agents[i].position))
            partial_two = np.logical_and(alpha, np.logical_xor(best_position, agents[i].position))
            chain_foraging = np.logical_or(agents[i].position, np.logical_or(partial_one, partial_two))

        # If index is different than zero
        else:
            # Calculates the chain foraging
            partial_one = np.logical_and(r1, np.logical_xor(agents[i - 1].position, agents[i].position))
            partial_two = np.logical_and(alpha, np.logical_xor(best_position, agents[i].position))
            chain_foraging = np.logical_or(agents[i].position, np.logical_or(partial_one, partial_two))

        return chain_foraging
Пример #4
0
    def _update_velocity(self, position, best_position, local_position):
        """Updates a particle velocity.

        Args:
            position (np.array): Agent's current position.
            best_position (np.array): Global best position.
            local_position (np.array): Agent's local best position.

        Returns:
            A new velocity based on boolean bPSO's paper velocity update equation.

        """

        # Defining a random binary number
        r1 = r.generate_binary_random_number(position.shape)

        # Defining another random binary number
        r2 = r.generate_binary_random_number(position.shape)

        # Calculating the local partial
        local_partial = np.logical_and(
            self.c1,
            np.logical_xor(r1, np.logical_xor(local_position, position)))

        # Calculating the global partial
        global_partial = np.logical_and(
            self.c2, np.logical_xor(r2, np.logical_xor(best_position,
                                                       position)))

        # Updating new velocity
        new_velocity = np.logical_or(local_partial, global_partial)

        return new_velocity
Пример #5
0
    def _cyclone_foraging(self, agents, best_position, i, iteration, n_iterations):
        """Performs the cyclone foraging procedure.

        Args:
            agents (list): List of agents.
            best_position (np.array): Global best position.
            i (int): Current agent's index.
            iteration (int): Current iteration.
            n_iterations (int): Maximum number of iterations.

        Returns:
            A new cyclone foraging.

        """

        # Generates binary random numbers
        r1 = r.generate_binary_random_number(best_position.shape)
        beta = r.generate_binary_random_number(best_position.shape)

        # Generates a uniform random number
        u = r.generate_uniform_random_number()

        # Checks if current iteration proportion is smaller than random generated number
        if iteration / n_iterations < u:
            # Generates binary random positions
            r_position = r.generate_binary_random_number(size=(agents[i].n_variables, agents[i].n_dimensions))

            # Checks if the index is equal to zero
            if i == 0:
                # Calculates the cyclone foraging
                partial_one = np.logical_or(r1, np.logical_xor(r_position, agents[i].position))
                partial_two = np.logical_or(beta, np.logical_xor(r_position, agents[i].position))
                cyclone_foraging = np.logical_and(r_position, np.logical_and(partial_one, partial_two))

            # If index is different than zero
            else:
                # Calculates the cyclone foraging
                partial_one = np.logical_or(r1, np.logical_xor(agents[i - 1].position, agents[i].position))
                partial_two = np.logical_or(beta, np.logical_xor(r_position, agents[i].position))
                cyclone_foraging = np.logical_and(r_position, np.logical_and(partial_one, partial_two))

        # If current iteration proportion is bigger than random generated number
        else:
            # Checks if the index is equal to zero
            if i == 0:
                # Calculates the cyclone foraging
                partial_one = np.logical_or(r1, np.logical_xor(best_position, agents[i].position))
                partial_two = np.logical_or(beta, np.logical_xor(best_position, agents[i].position))
                cyclone_foraging = np.logical_and(best_position, np.logical_and(partial_one, partial_two))

            # If index is different than zero
            else:
                # Calculates the cyclone foraging
                partial_one = np.logical_or(r1, np.logical_xor(agents[i - 1].position, agents[i].position))
                partial_two = np.logical_or(beta, np.logical_xor(best_position, agents[i].position))
                cyclone_foraging = np.logical_and(best_position, np.logical_and(partial_one, partial_two))

        return cyclone_foraging
Пример #6
0
def test_bpso_hyperparams():
    hyperparams = {
        'c1': r.generate_binary_random_number(size=(1, 1)),
        'c2': r.generate_binary_random_number(size=(1, 1))
    }

    new_bpso = bpso.BPSO(hyperparams=hyperparams)

    assert new_bpso.c1 == 0 or new_bpso.c1 == 1

    assert new_bpso.c2 == 0 or new_bpso.c2 == 1
Пример #7
0
def test_bpso_params():
    params = {
        "c1": r.generate_binary_random_number(size=(1, 1)),
        "c2": r.generate_binary_random_number(size=(1, 1)),
    }

    new_bpso = bpso.BPSO(params=params)

    assert new_bpso.c1 == 0 or new_bpso.c1 == 1

    assert new_bpso.c2 == 0 or new_bpso.c2 == 1
Пример #8
0
def test_bpso_hyperparams_setter():
    new_bpso = bpso.BPSO()

    try:
        new_bpso.c1 = 'a'
    except:
        new_bpso.c1 = r.generate_binary_random_number(size=(1, 1))

    assert new_bpso.c1 == 0 or new_bpso.c1 == 1

    try:
        new_bpso.c2 = 'b'
    except:
        new_bpso.c2 = r.generate_binary_random_number(size=(1, 1))

    assert new_bpso.c2 == 0 or new_bpso.c2 == 1
Пример #9
0
    def fill_with_binary(self) -> None:
        """Fills the agent's decision variables with a binary distribution."""

        # Iterates through all the decision variables
        for j in range(self.n_variables):
            # Fills the array based on a binary distribution
            self.position[j] = r.generate_binary_random_number(self.n_dimensions)
Пример #10
0
def test_bmrfo_params():
    params = {
        'S': r.generate_binary_random_number(size=(1, 1))
    }

    new_bmrfo = bmrfo.BMRFO(params=params)

    assert new_bmrfo.S == 0 or new_bmrfo.S == 1
Пример #11
0
def test_bmrfo_params_setter():
    new_bmrfo = bmrfo.BMRFO()

    try:
        new_bmrfo.S = "a"
    except:
        new_bmrfo.S = r.generate_binary_random_number(size=(1, 1))

    assert new_bmrfo.S == 0 or new_bmrfo.S == 1
Пример #12
0
    def _initialize_agents(self):
        """Initialize agents' position array with boolean random numbers.

        """

        logger.debug('Running private method: initialize_agents().')

        # Iterates through all agents
        for agent in self.agents:
            # Iterates through all decision variables
            for j, (lb, ub) in enumerate(zip(self.lb, self.ub)):
                # For each decision variable, we generate binary random numbers
                agent.position[j] = r.generate_binary_random_number(size=agent.n_dimensions)

                # Applies the lower bound to the agent's lower bound
                agent.lb[j] = lb

                # And also the upper bound
                agent.ub[j] = ub

        logger.debug('Agents initialized.')
Пример #13
0
    def _nomad_attack(
            self, nomads: List[Lion],
            prides: List[List[Lion]]) -> Tuple[List[Lion], List[List[Lion]]]:
        """Performs the nomad's attacking procedure (s. 2.2.6).

        Args:
            nomads: Nomad lions.
            prides: List of prides holding their corresponding lions.

        Returns:
            (Tuple[List[Lion], List[List[Lion]]]): Both updated nomad and pride lions.

        """

        # Iterates through all nomads
        for agent in nomads:
            # If current agent is female
            if agent.female:
                # Generates a binary array of prides to be attacked
                attack_prides = r.generate_binary_random_number(self.P)

                # Iterates through every pride
                for i, pride in enumerate(prides):
                    # If pride is supposed to be attacked
                    if attack_prides[i]:
                        # Gathers all the males in the pride
                        males = [agent for agent in pride if not agent.female]

                        # If there is at least a male
                        if len(males) > 0:
                            # If current nomad agent is better than male in pride
                            if agent.fit < males[0].fit:
                                # Swaps them
                                agent, males[0] = copy.deepcopy(
                                    males[0]), copy.deepcopy(agent)

        return nomads, prides
Пример #14
0
    # Predicts new data
    preds = opf.predict(X_val_selected)

    # Calculates accuracy
    acc = g.opf_accuracy(Y_val, preds)

    return 1 - acc


# Number of agents and decision variables
n_agents = 5
n_variables = 64

# Parameters for the optimizer
params = {
    'c1': r.generate_binary_random_number(size=(n_variables, 1)),
    'c2': r.generate_binary_random_number(size=(n_variables, 1))
}

# Creates the space, optimizer and function
space = BooleanSpace(n_agents, n_variables)
optimizer = BPSO()
function = Function(supervised_opf_feature_selection)

# Bundles every piece into Opytimizer class
opt = Opytimizer(space, optimizer, function)

# Runs the optimization task
opt.start(n_iterations=3)
Пример #15
0
import opytimizer.math.random as r

# Generating a binary random number array
b = r.generate_binary_random_number(size=10)
print(b)

# Generating a integer random number array
i = r.generate_integer_random_number(low=0, high=1, size=1)
print(i)

# Generating a random uniform number array
u = r.generate_uniform_random_number(low=0.0, high=1.0, size=1)
print(u)

# Generating a random gaussian number array
g = r.generate_gaussian_random_number(mean=0.5, variance=1.0, size=10)
print(g)
Пример #16
0
def test_generate_binary_random_number():
    binary_array = random.generate_binary_random_number(5)

    assert binary_array.shape == (5, )
Пример #17
0
    # Predicts new data
    preds = opf.predict(X_val_selected)

    # Calculates accuracy
    acc = g.opf_accuracy(Y_val, preds)

    return 1 - acc


# Number of agents and decision variables
n_agents = 5
n_variables = 64

# Parameters for the optimizer
params = {
    "c1": r.generate_binary_random_number(size=(n_variables, 1)),
    "c2": r.generate_binary_random_number(size=(n_variables, 1)),
}

# Creates the space, optimizer and function
space = BooleanSpace(n_agents, n_variables)
optimizer = BPSO()
function = Function(supervised_opf_feature_selection)

# Bundles every piece into Opytimizer class
opt = Opytimizer(space, optimizer, function)

# Runs the optimization task
opt.start(n_iterations=3)