Esempio n. 1
0
    def ub(self, ub):
        if not isinstance(ub, np.ndarray):
            raise e.TypeError('`ub` should be a numpy array')
        if ub.shape[0] != self.n_variables:
            raise e.SizeError('`ub` should be the same size as `n_variables`')

        self._ub = ub
Esempio n. 2
0
def test_exception_size_error():
    new_exception = exception.SizeError("error")

    try:
        raise new_exception
    except exception.SizeError:
        pass
Esempio n. 3
0
    def lb(self, lb):
        if not isinstance(lb, np.ndarray):
            raise e.TypeError('`lb` should be a numpy array')
        if lb.shape[0] != self.n_variables:
            raise e.SizeError('`lb` should be the same size as `n_variables`')

        self._lb = lb
Esempio n. 4
0
    def get(self, key, index):
        """Gets the desired key based on the input index.

        Args:
            key (str): Key's name to be retrieved.
            index (tuple): A tuple indicating which indexes should be retrieved.

        Returns:
            All key's values based on the input index.
            Note that this method returns all records, i.e., all values from the `t` iterations.

        """

        # Checks if index is a tuple
        if not isinstance(index, tuple):
            raise e.TypeError('`index` should be a tuple')

        # Gathers the numpy array from the attribute
        attr = np.asarray(getattr(self, key))

        # Checks if attribute's dimensions are equal to the length of input index
        # We use `- 1` as the method retrieves values from all iterations
        if attr.ndim - 1 != len(index):
            raise e.SizeError(
                f'`index` = {len(index)} should have one less dimension than `key` = {attr.ndim}')

        # Slices the array based on the input index
        # Again, slice(None) will retrieve values from all iterations
        attr = attr[(slice(None),) + index]

        # We use hstack to horizontally concatenate the axis,
        # allowing an easier input to the visualization package
        attr = np.hstack(attr)

        return attr
Esempio n. 5
0
def test_size_error():
    new_exception = exception.SizeError('error')

    try:
        raise new_exception
    except exception.SizeError:
        pass
Esempio n. 6
0
    def weights(self, weights):
        if not isinstance(weights, list):
            raise e.TypeError('`weights` should be a list')
        if len(weights) != len(self.functions):
            raise e.SizeError(
                '`weights` should have the same size of `functions`')

        self._weights = weights
Esempio n. 7
0
    def weights(self, weights: List[float]) -> None:
        if not isinstance(weights, list):
            raise e.TypeError("`weights` should be a list")
        if len(weights) != len(self.functions):
            raise e.SizeError(
                "`weights` should have the same size of `functions`")

        self._weights = weights
Esempio n. 8
0
def plot(
    *args,
    labels: Optional[List[str]] = None,
    title: Optional[str] = "",
    subtitle: Optional[str] = "",
    xlabel: Optional[str] = "iteration",
    ylabel: Optional[str] = "value",
    grid: Optional[bool] = True,
    legend: Optional[bool] = True,
) -> None:
    """Plots the convergence graph of desired variables.

    Essentially, each variable is a list or numpy array
    with size equals to `n_iterations`.

    Args:
        labels: Labels to be applied for each plot in legend.
        title: Title of the plot.
        subtitle: Subtitle of the plot.
        xlabel: Axis `x` label.
        ylabel: Axis `y` label.
        grid: If grid should be used or not.
        legend: If legend should be displayed or not.

    """

    # Creates the figure and axis subplots
    _, ax = plt.subplots(figsize=(7, 5))

    # Defines some properties, such as labels, title and subtitle
    ax.set(xlabel=xlabel, ylabel=ylabel)
    ax.set_title(title, loc="left", fontsize=14)
    ax.set_title(subtitle, loc="right", fontsize=8, color="grey")

    if grid:
        ax.grid()

    if labels:
        # Checks a set of pre-defined `labels` conditions
        if not isinstance(labels, list):
            raise e.TypeError("`labels` should be a list")

        if len(labels) != len(args):
            raise e.SizeError("`args` and `labels` should have the same size")

    else:
        # Creates pre-defined `labels`
        labels = [f"variable_{i}" for i in range(len(args))]

    # Plots every argument
    for (arg, label) in zip(args, labels):
        ax.plot(arg, label=label)

    if legend:
        ax.legend()

    # Displays the plot
    plt.show()
Esempio n. 9
0
    def ub(self, ub: np.ndarray) -> None:
        if not isinstance(ub, np.ndarray):
            raise e.TypeError("`ub` should be a numpy array")
        if not ub.shape:
            ub = np.expand_dims(ub, -1)
        if not ub.shape or ub.shape[0] != self.n_variables:
            raise e.SizeError("`ub` should be the same size as `n_variables`")

        self._ub = ub
Esempio n. 10
0
    def lb(self, lb: np.ndarray) -> None:
        if not isinstance(lb, np.ndarray):
            raise e.TypeError("`lb` should be a numpy array")
        if not lb.shape:
            lb = np.expand_dims(lb, -1)
        if lb.shape[0] != self.n_variables:
            raise e.SizeError("`lb` should be the same size as `n_variables`")

        self._lb = lb
Esempio n. 11
0
 def mapping(self, mapping: List[str]) -> None:
     if mapping is not None:
         if not isinstance(mapping, list):
             raise e.TypeError("`mapping` should be a list")
         if len(mapping) != self.n_variables:
             raise e.SizeError("`mapping` should be the same size as `n_variables`")
         self._mapping = mapping
     else:
         self._mapping = [f"x{i}" for i in range(self.n_variables)]
Esempio n. 12
0
def plot(*args, labels=None, title='', subtitle='', grid=True, legend=True):
    """Plots the convergence graph of desired variables.

    Essentially, each variable is a list or numpy array
    with size equals to (iterations x 1).

    Args:
        labels (list): Labels to be applied for each plot in legend.
        title (str): The title of the plot.
        subtitle (str): The subtitle of the plot.
        grid (bool): If grid should be used or not.
        legend (bool): If legend should be displayed or not.

    """

    # Creating figure and axis subplots
    fig, ax = plt.subplots(figsize=(7, 5))

    # Defining some properties, such as axis labels
    ax.set(xlabel='iteration', ylabel='value')

    # Setting both title and subtitles
    ax.set_title(title, loc='left', fontsize=14)
    ax.set_title(subtitle, loc='right', fontsize=8, color='grey')

    # If grid usage is true
    if grid:
        # Adds the grid property to the axis
        ax.grid()

    # Check if labels argument exists
    if labels:
        # Also check if it is a list
        if not isinstance(labels, list):
            raise e.TypeError('`labels` should be a list')

        # And check if it has the same size of arguments
        if len(labels) != len(args):
            raise e.SizeError('`args` and `labels` should have the same size')

    # If labels argument does not exists
    else:
        # Creates a list with indicators
        labels = [f'variable_{i}' for i in range(len(args))]

    # Plotting the axis
    for (arg, label) in zip(args, labels):
        ax.plot(arg, label=label)

    # If legend usage is true
    if legend:
        # Adds the legend property to the axis
        ax.legend()

    # Displaying the plot
    plt.show()
Esempio n. 13
0
def plot(*args, labels=None, title='', subtitle='', xlabel='iteration', ylabel='value',
         grid=True, legend=True):
    """Plots the convergence graph of desired variables.

    Essentially, each variable is a list or numpy array
    with size equals to `n_iterations`.

    Args:
        labels (list): Labels to be applied for each plot in legend.
        title (str): Title of the plot.
        subtitle (str): Subtitle of the plot.
        xlabel (str): Axis `x` label.
        ylabel (str): Axis `y` label.
        grid (bool): If grid should be used or not.
        legend (bool): If legend should be displayed or not.

    """

    # Creates the figure and axis subplots
    _, ax = plt.subplots(figsize=(7, 5))

    # Defines some properties, such as labels, title and subtitle
    ax.set(xlabel=xlabel, ylabel=ylabel)
    ax.set_title(title, loc='left', fontsize=14)
    ax.set_title(subtitle, loc='right', fontsize=8, color='grey')

    # If grid usage is `True`
    if grid:
        # Adds the grid property to the axis
        ax.grid()

    # Checks if `labels` really exists
    if labels:
        # Checks a set of pre-defined `labels` conditions
        if not isinstance(labels, list):
            raise e.TypeError('`labels` should be a list')

        if len(labels) != len(args):
            raise e.SizeError('`args` and `labels` should have the same size')

    # If `labels` do not exists
    else:
        # Creates pre-defined `labels`
        labels = [f'variable_{i}' for i in range(len(args))]

    # Plots every argument
    for (arg, label) in zip(args, labels):
        ax.plot(arg, label=label)

    # If legend usage is `True`
    if legend:
        # Adds the legend property to the axis
        ax.legend()

    # Displays the plot
    plt.show()
Esempio n. 14
0
    def step(self, step: np.ndarray) -> None:
        if not isinstance(step, np.ndarray):
            raise e.TypeError("`step` should be a numpy array")
        if not step.shape:
            step = np.expand_dims(step, -1)
        if step.shape[0] != self.n_variables:
            raise e.SizeError(
                "`step` should be the same size as `n_variables`")

        self._step = step
Esempio n. 15
0
    def compile(self, space):
        """Compiles additional information that is used by this optimizer.

        Args:
            space (Space): A Space object containing meta-information.

        """

        # Checks if supplied number of agents has a perfect square
        if not np.sqrt(space.n_agents).is_integer():
            raise e.SizeError('`n_agents` should have a perfect square')
Esempio n. 16
0
    def fill_with_static(self, values: np.ndarray) -> None:
        """Fills the agent's decision variables with static values. Note that this
        method ignore the agent's bounds, so use it carefully.

        Args:
            values: Values to be filled.

        """

        # Makes sure that `values` is a numpy array
        # and has the same size of `n_variables`
        values = np.asarray(values)
        if not values.shape:
            values = np.expand_dims(values, -1)
        if values.shape[0] != self.n_variables:
            raise e.SizeError("`values` should be the same size as `n_variables`")

        # Iterates through all the decision variables
        for j, value in enumerate(values):
            # Fills the array based on a static value
            self.position[j] = value