From 95c03026162457357c7cda8d0a72c10df59e7d81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Sun, 22 Feb 2026 16:03:12 -0300 Subject: [PATCH 01/40] docs(template): Add documentation template for the class. --- docs/assets/template-docs-class.md | 80 ++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 docs/assets/template-docs-class.md diff --git a/docs/assets/template-docs-class.md b/docs/assets/template-docs-class.md new file mode 100644 index 0000000..e9e3250 --- /dev/null +++ b/docs/assets/template-docs-class.md @@ -0,0 +1,80 @@ +--- +id: class-name +title: ClassName +sidebar_label: ClassName +tags: + - tag +--- + +# ClassName + +> **Package:** `aisp.[module]` + +{{ Brief description of the class. }} + +--- + +## Overview + +{{ Explain what the class. }} + +Use cases: + +- {{ Use case 1 }} + +--- + +## Example + +```python +from aisp.module import ClassName + +model = ClassName() +model.method_name() +``` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|---------------|--------|:-------:|--------------------------------| +| `attribute_1` | `Type` | - | Description of the parameters. | +| `attribute_2` | `Type` | - | Description of the parameters. | + +## Attributes + +| Name | Type | Default | Description | +|---------------|--------|:-------:|-------------------------------| +| `attribute_1` | `Type` | - | Description of the attribute. | +| `attribute_2` | `Type` | - | Description of the attribute. | + +--- + +## References + +1. + +--- + +## Public Methods + +### method_name + +Description. + +**Parameters** + +| Name | Type | Default | Description | +|---------------|--------|:-------:|-------------------------------| +| `attribute_1` | `Type` | - | Description of the attribute. | + +**Returns** + +{{ Type }} - {{ Description }}. + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + +- [example](#link) \ No newline at end of file From a1c7b84e0b4d81bca418c33504590d979cde154e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Sun, 22 Feb 2026 16:04:02 -0300 Subject: [PATCH 02/40] docs(template): Add documentation template for the class. --- docs/assets/template-docs-class.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/assets/template-docs-class.md b/docs/assets/template-docs-class.md index e9e3250..14f7b4e 100644 --- a/docs/assets/template-docs-class.md +++ b/docs/assets/template-docs-class.md @@ -37,10 +37,10 @@ model.method_name() ## Constructor Parameters -| Name | Type | Default | Description | -|---------------|--------|:-------:|--------------------------------| -| `attribute_1` | `Type` | - | Description of the parameters. | -| `attribute_2` | `Type` | - | Description of the parameters. | +| Name | Type | Default | Description | +|-----------|--------|:-------:|--------------------------------| +| `param_1` | `Type` | - | Description of the parameters. | +| `param_2` | `Type` | - | Description of the parameters. | ## Attributes @@ -65,9 +65,9 @@ Description. **Parameters** -| Name | Type | Default | Description | -|---------------|--------|:-------:|-------------------------------| -| `attribute_1` | `Type` | - | Description of the attribute. | +| Name | Type | Default | Description | +|-----------|--------|:-------:|-------------------------------| +| `param_1` | `Type` | - | Description of the attribute. | **Returns** From 1705be90f02b343f1458aa4e94ad7356132fa2b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Sun, 22 Feb 2026 17:09:51 -0300 Subject: [PATCH 03/40] docs(template): update documentation template. --- docs/assets/template-docs-class.md | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/docs/assets/template-docs-class.md b/docs/assets/template-docs-class.md index 14f7b4e..2be2244 100644 --- a/docs/assets/template-docs-class.md +++ b/docs/assets/template-docs-class.md @@ -1,17 +1,17 @@ --- id: class-name -title: ClassName sidebar_label: ClassName tags: - - tag + - tag --- # ClassName -> **Package:** `aisp.[module]` - {{ Brief description of the class. }} +> **Module:** `aisp.[module]` +> **Import:** `from aisp.[module] import [class]` + --- ## Overview @@ -37,10 +37,10 @@ model.method_name() ## Constructor Parameters -| Name | Type | Default | Description | -|-----------|--------|:-------:|--------------------------------| -| `param_1` | `Type` | - | Description of the parameters. | -| `param_2` | `Type` | - | Description of the parameters. | +| Name | Type | Default | Description | +|-----------|--------|:-------:|---------------------------| +| `param_1` | `Type` | - | Description of the param. | +| `param_2` | `Type` | - | Description of the param. | ## Attributes @@ -65,14 +65,16 @@ Description. **Parameters** -| Name | Type | Default | Description | -|-----------|--------|:-------:|-------------------------------| -| `param_1` | `Type` | - | Description of the attribute. | +| Name | Type | Default | Description | +|-----------|--------|:-------:|---------------------------| +| `param_1` | `Type` | - | Description of the param. | **Returns** {{ Type }} - {{ Description }}. +--- + ## Extended Example Complete usage examples are available in the Jupyter Notebooks: From 01155012475efe422c365cf6cb40f478fb21b9bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Sun, 22 Feb 2026 17:22:16 -0300 Subject: [PATCH 04/40] docs(base): adds the base module documentation in API format. --- docs/en/api/base/README.md | 33 +++++++ docs/en/api/base/base-classifier.md | 122 +++++++++++++++++++++++ docs/en/api/base/base-clusterer.md | 109 ++++++++++++++++++++ docs/en/api/base/base-optimizer.md | 148 ++++++++++++++++++++++++++++ 4 files changed, 412 insertions(+) create mode 100644 docs/en/api/base/README.md create mode 100644 docs/en/api/base/base-classifier.md create mode 100644 docs/en/api/base/base-clusterer.md create mode 100644 docs/en/api/base/base-optimizer.md diff --git a/docs/en/api/base/README.md b/docs/en/api/base/README.md new file mode 100644 index 0000000..9cb7f34 --- /dev/null +++ b/docs/en/api/base/README.md @@ -0,0 +1,33 @@ +--- +id: base +sidebar_label: aisp.base +tags: + - base + - immune + - abstract +--- + +# aisp.base + +Base Classes and Core Utilities. + +> **Module:** `aisp.base` + +## Overview + +This module provides the fundamental classes and utilities that serve as the basis for all +Artificial Immune Systems algorithms implemented in the AISP package. + +## Classes + +| Class | Description | +|------------------|----------------------------------------------------| +| `BaseClassifier` | Abstract base class for classification algorithms. | +| `BaseClusterer` | Abstract base class for clustering algorithms. | +| `BaseOptimizer` | Abstract base class for optimization algorithms. | + +## Submodules + +| Module | Description | +|----------|-----------------------------------------------| +| `immune` | Support Module for Artificial Immune Systems. | \ No newline at end of file diff --git a/docs/en/api/base/base-classifier.md b/docs/en/api/base/base-classifier.md new file mode 100644 index 0000000..fcd7d90 --- /dev/null +++ b/docs/en/api/base/base-classifier.md @@ -0,0 +1,122 @@ +--- +id: base-classifier +sidebar_label: BaseClassifier +tags: + - base + - classifier + - accuracy +--- + +# BaseClassifier + +Abstract base class for classification algorithms. + +> **Module:** `aisp.base` +> **Import:** `from aisp.base import BaseClassifier` + +--- + +## Overview + +This class defines the core interface for classification models. It enforces the implementation of the `fit` +and `predict` methods in all derived classes, and provides a default implementation of the `score` method. + +Use cases: + +- Abstract base class for extending classification algorithm classes. + +--- + +## Attributes + +| Name | Type | Default | Description | +|---------------|-------------------------|:-------:|------------------------------------------| +| `classes` | `Optional[npt.NDArray]` | `None` | Class labels identified during training. | + +--- + +## Abstract Methods + +### fit + +```python +@abstractmethod +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True +) -> BaseClassifier: + ... +``` + +Train the model using the input data X and corresponding labels y. +This abstract method is implemented by the class that inherits it. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Input data used for training the model. | +| `y` | `Union[npt.NDArray, list]` | - | Corresponding labels or target values for the input data. | +| `verbose` | `bool` | `True` | Flag to enable or disable detailed output during training. | + +**Returns** + +``BaseClassifier`` - Returns the instance of the class that implements this method. + +--- + +### predict + +```python +@abstractmethod +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Generate predictions based on the input data X. +This abstract method is implemented by the class that inherits it. + + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|-----------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Input data for which predictions will be generated. | + +**Returns** + +`npt.NDArray` - Predicted values for each input sample. + +--- + +## Public Methods + +### score + +```python +def score( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list] +) -> float: + ... +``` + +Score function calculates forecast accuracy. + +This function performs the prediction of X and checks how many elements are equal between vector y and y_predicted. +This function was added for compatibility with some scikit-learn functions. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|--------|:-------:|-------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Feature set with shape (n_samples, n_features). | +| `y` | `Union[npt.NDArray, list]` | - | True values with shape (n_samples,). | + +**Returns** + +`float` - The accuracy of the model. + diff --git a/docs/en/api/base/base-clusterer.md b/docs/en/api/base/base-clusterer.md new file mode 100644 index 0000000..a99e630 --- /dev/null +++ b/docs/en/api/base/base-clusterer.md @@ -0,0 +1,109 @@ +--- +id: base-clusterer +sidebar_label: BaseClusterer +tags: + - base + - clusterer +--- + +# BaseClusterer + +Abstract base class for clustering algorithms. + +> **Module:** `aisp.base` +> **Import:** `from aisp.base import BaseClusterer` + +--- + +## Overview + +This class defines the core interface for clustering models. It enforces the implementation of the `fit` and +`predict` methods in all derived classes, and provides a default implementation for `fit_predict` and `get_params`. + +Use cases: + +- Abstract base class for extending clustering algorithm classes. + +--- + +## Attributes + +| Name | Type | Default | Description | +|----------|-------------------------|:-------:|---------------------------------------------------------| +| `labels` | `Optional[npt.NDArray]` | `None` | Labels for the clusters generated during model fitting. | + +--- + +## Abstract Methods + +### fit + +```python +@abstractmethod +def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> BaseClusterer: + ... +``` + +Train the model using the input data X. +This abstract method is implemented by the class that inherits it. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Input data used for training the model. | +| `verbose` | `bool` | `True` | Flag to enable or disable detailed output during training. | + +**Returns** + +``BaseClassifier`` - Returns the instance of the class that implements this method. + +--- + +### predict + +```python +@abstractmethod +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Generate predictions based on the input data X. +This abstract method is implemented by the class that inherits it. + + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|-----------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Input data for which predictions will be generated. | + +**Returns** + +`npt.NDArray` - Predicted cluster labels for each input sample. + +--- + +## Public Methods + +### fit_predict + +```python +def fit_predict(self, X: Union[npt.NDArray, list], verbose: bool = True) -> npt.NDArray: + ... +``` + +Fit the clustering model to the data and return cluster labels. + +This is a convenience method that combines `fit` and `predict` into a single call. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Feature set with shape (n_samples, n_features). | +| `verbose` | `bool` | `True` | Flag to enable or disable detailed output during training. | + +**Returns** + +`npt.NDArray` - Predicted cluster labels for each input sample. diff --git a/docs/en/api/base/base-optimizer.md b/docs/en/api/base/base-optimizer.md new file mode 100644 index 0000000..aef864e --- /dev/null +++ b/docs/en/api/base/base-optimizer.md @@ -0,0 +1,148 @@ +--- +id: base-optimizer +sidebar_label: BaseOptimizer +tags: + - base + - optimizer +--- + +# BaseOptimizer + +Abstract base class for optimization algorithms. + +> **Module:** `aisp.base` +> **Import:** `from aisp.base import BaseOptimizer` + +--- + +## Overview + +This class defines the core interface for optimization strategies. It keeps track of cost history, evaluated +solutions, and the best solution found during the optimization process. Subclasses must implement ``optimize`` +and ``affinity_function``. + +Use cases: + +- Abstract base class for extending optimization algorithm classes. + +--- + +## Attributes + +| Name | Type | Default | Description | +|--------------------|-------------------|:-------:|-------------------------------------------------------------------------| +| `cost_history` | `List[float]` | `[]` | History of best costs found at each iteration. | +| `solution_history` | `List` | `[]` | History of the best solution found at each iteration. | +| `best_solution` | `Any` | `None` | The best solution found. | +| `best_cost` | `Optional[float]` | `None` | Cost of the best solution found. | +| `mode` | `{"min", "max"}` | `'min'` | Defines whether the algorithm minimizes or maximizes the cost function. | + +--- + +## Abstract Methods + +### optimize + +```python +@abstractmethod +def optimize( + self, + max_iters: int = 50, + n_iter_no_change: int = 10, + verbose: bool = True +) -> Any: + ... +``` + +Execute the optimization process. +This abstract method must be implemented by the subclass, defining how the optimization strategy explores the search space. + +**Parameters** + +| Name | Type | Default | Description | +|--------------------|--------|:-------:|------------------------------------------------------------| +| `max_iters` | `int` | `50` | Maximum number of iterations | +| `n_iter_no_change` | `int` | `10` | the maximum number of iterations without updating the best | +| `verbose` | `bool` | `True` | Flag to enable or disable detailed output during training. | + +**Returns** + +``BaseClassifier`` - Returns the instance of the class that implements this method. + + +--- + +### affinity_function + +```python +@abstractmethod +def affinity_function(self, solution: Any) -> float: + ... +``` + +Evaluate the affinity of a candidate solution. + +This abstract method must be implemented by the subclass to define the problem-specific. + +**Parameters** + +| Name | Type | Default | Description | +|------------|-------|:-------:|-------------------------------------| +| `solution` | `Any` | - | Candidate solution to be evaluated. | + +**Returns** + +`float` - Cost value associated with the given solution. + +--- + +## Public Methods + +### get_report + +```python +def get_report(self) -> str: + ... +``` + +Generate a formatted summary report of the optimization process. +The report includes the best solution, its associated cost, and the evolution of cost values per iteration. + +**Returns** + +`str` - A formatted string containing the optimization summary. + +--- + +### register + +```python +def register(self, alias: str, function: Callable[..., Any]) -> None: + ... +``` + +Register a function dynamically in the optimizer instance. + +**Parameters** + +| Name | Type | Default | Description | +|------------|----------------------|:-------:|---------------------------------------------------| +| `alias` | `str` | - | Name used to access the function as an attribute. | +| `function` | `Callable[..., Any]` | - | Callable to be registered. | + +**Raises** + +`TypeError` - If `function` is not callable. + +`AttributeError` - If `alias` is protected and cannot be modified. Or if `alias` does not exist in the optimizer class. + +--- + +### reset + +```python +def reset(self): + ... +``` + +Reset the object's internal state, clearing history and resetting values. From 37de9ecbbce27a9c1c1c01418dcdd242fbc97ad8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Sun, 22 Feb 2026 18:11:35 -0300 Subject: [PATCH 05/40] docs(template) update tags to keywords --- docs/assets/template-docs-class.md | 2 +- docs/en/api/base/README.md | 2 +- docs/en/api/base/base-classifier.md | 2 +- docs/en/api/base/base-clusterer.md | 2 +- docs/en/api/base/base-optimizer.md | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/assets/template-docs-class.md b/docs/assets/template-docs-class.md index 2be2244..0b34805 100644 --- a/docs/assets/template-docs-class.md +++ b/docs/assets/template-docs-class.md @@ -1,7 +1,7 @@ --- id: class-name sidebar_label: ClassName -tags: +keywords: - tag --- diff --git a/docs/en/api/base/README.md b/docs/en/api/base/README.md index 9cb7f34..bcd4501 100644 --- a/docs/en/api/base/README.md +++ b/docs/en/api/base/README.md @@ -1,7 +1,7 @@ --- id: base sidebar_label: aisp.base -tags: +keywords: - base - immune - abstract diff --git a/docs/en/api/base/base-classifier.md b/docs/en/api/base/base-classifier.md index fcd7d90..3c9d0a9 100644 --- a/docs/en/api/base/base-classifier.md +++ b/docs/en/api/base/base-classifier.md @@ -1,7 +1,7 @@ --- id: base-classifier sidebar_label: BaseClassifier -tags: +keywords: - base - classifier - accuracy diff --git a/docs/en/api/base/base-clusterer.md b/docs/en/api/base/base-clusterer.md index a99e630..28f9555 100644 --- a/docs/en/api/base/base-clusterer.md +++ b/docs/en/api/base/base-clusterer.md @@ -1,7 +1,7 @@ --- id: base-clusterer sidebar_label: BaseClusterer -tags: +keywords: - base - clusterer --- diff --git a/docs/en/api/base/base-optimizer.md b/docs/en/api/base/base-optimizer.md index aef864e..b8b740d 100644 --- a/docs/en/api/base/base-optimizer.md +++ b/docs/en/api/base/base-optimizer.md @@ -1,7 +1,7 @@ --- id: base-optimizer sidebar_label: BaseOptimizer -tags: +keywords: - base - optimizer --- From 7ade1fa720bb405b59f6c7d56b7ca061f52791ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Sun, 22 Feb 2026 18:13:11 -0300 Subject: [PATCH 06/40] docs(base): adds the mutation and populations documentation in API format. --- docs/en/api/base/immune/mutation.md | 142 +++++++++++++++++++++++++ docs/en/api/base/immune/populations.md | 52 +++++++++ 2 files changed, 194 insertions(+) create mode 100644 docs/en/api/base/immune/mutation.md create mode 100644 docs/en/api/base/immune/populations.md diff --git a/docs/en/api/base/immune/mutation.md b/docs/en/api/base/immune/mutation.md new file mode 100644 index 0000000..36c9c8b --- /dev/null +++ b/docs/en/api/base/immune/mutation.md @@ -0,0 +1,142 @@ +--- +id: mutation +sidebar_label: mutation +keywords: + - mutation + - clonal expansion + - immune system + - python numba functions + - vector mutation +--- + +# mutation + +The functions perform utilize Numba decorators for Just-In-Time compilation. + +Contains functions that generate sets of mutated clones from continuous or binary vectors, +simulating the clonal expansion process in artificial immune systems. + +> **Module:** `aisp.base.immune` +> **Import:** `from aisp.base.immune import mutation` + +## Methods + +### clone_and_mutate_continuous + +````python +@njit([(types.float64[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_continuous( + vector: npt.NDArray[np.float64], + n: int, + mutation_rate: float +) -> npt.NDArray[np.float64]: + ... +```` + +Generate a set of mutated clones from a cell represented by a continuous vector. + +This function creates `n` clones of the input vector and applies random mutations to each of them, simulating the +process of clonal expansion in artificial immune systems. Each clone will have a random number of mutations applied +in distinct positions of the original vector. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|---------------------------|:-------:|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with continuous values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `mutation_rate` | `float` | - | If 0 <= mutation_rate < 1: probability of mutating each component. If mutation_rate >= 1 or mutation_rate <= 0: the mutation randomizes a number of components between 1 and len(vector). | + +**Returns** + +`npt.NDArray[np.float64]` - An Array(n, len(vector)) containing the `n` mutated clones of the original vector. + +### clone_and_mutate_binary + +````python +@njit([(types.boolean[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_binary( + vector: npt.NDArray[np.bool_], + n: int, + mutation_rate: float +) -> npt.NDArray[np.bool_]: + ... +```` + +Generate a set of mutated clones from a cell represented by a binary vector. + +This function creates `n` clones of the input vector and applies random mutations to each of +them, changing some bits randomly. The process simulates clonal expansion in artificial +immune systems with discrete representations. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|---------------------------|:-------:|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with binary values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `mutation_rate` | `float` | - | If 0 <= mutation_rate < 1: probability of mutating each component. If mutation_rate >= 1 or mutation_rate <= 0: the mutation randomizes a number of components between 1 and len(vector). | + +**Returns** + +`npt.NDArray[np.bool_]` - An Array(n, len(vector)) containing the `n` mutated clones of the original vector. + + +### clone_and_mutate_ranged + +````python +@njit([(types.float64[:], types.int64, types.float64[:, :], types.float64)], cache=True) +def clone_and_mutate_ranged( + vector: npt.NDArray[np.float64], + n: int, + bounds: npt.NDArray[np.float64], + mutation_rate: float, +) -> npt.NDArray[np.float64]: + ... +```` + +Generate a set of mutated clones from a cell represented by custom ranges per dimension. + +This function creates `n` clones of the input vector and applies random mutations to each of +them, simulating the process of clonal expansion in artificial immune systems. Each clone +will have a random number of mutations applied in distinct positions of the original vector. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|---------------------------|:-------:|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with continuous values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `bounds` | `np.ndarray` | - | Array (n_features, 2) with min and max per dimension. | +| `mutation_rate` | `float` | - | If 0 <= mutation_rate < 1: probability of mutating each component. If mutation_rate >= 1 or mutation_rate <= 0: the mutation randomizes a number of components between 1 and len(vector). | + +**Returns** + +`npt.NDArray[np.float64]` - An Array(n, len(vector)) containing the `n` mutated clones of the original vector. + + +### clone_and_mutate_continuous + +````python +@njit([(types.int64[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_permutation( + vector: npt.NDArray[np.int64], + n: int, + mutation_rate: float +) -> npt.NDArray[np.int64]: + ... +```` + +Generate a set of mutated clones by random permutation. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|-------------------------|:-------:|----------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.int64]` | - | The original immune cell with permutation values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `mutation_rate` | `float` | - | Probability of mutating each component 0 <= mutation_rate < 1. | + +**Returns** + +`npt.NDArray[np.float64]` - An Array(n, len(vector)) containing the `n` mutated clones of the original vector. diff --git a/docs/en/api/base/immune/populations.md b/docs/en/api/base/immune/populations.md new file mode 100644 index 0000000..c7f6620 --- /dev/null +++ b/docs/en/api/base/immune/populations.md @@ -0,0 +1,52 @@ +--- +id: populations +sidebar_label: populations +keywords: + - binary + - classifying + - affinity threshold + - real-Valued + - memory B-cell + - clonal Expansion + - populations +--- + +# populations + +Provide utility functions for generating antibody populations in immunological algorithms. + +> **Module:** `aisp.base.immune` +> **Import:** `from aisp.base.immune import populations` + +## Methods + +### generate_random_antibodies + +````python +def generate_random_antibodies( + n_samples: int, + n_features: int, + feature_type: FeatureTypeAll = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None, +) -> npt.NDArray: + ... +```` + +Generate a random antibody population. + +**Parameters** + +| Name | Type | Default | Description | +|----------------|---------------------------|:-----------------------:|-------------------------------------------------------------------------------------------------------------------------| +| `n_samples` | `int` | - | Number of antibodies (samples) to generate. | +| `n_features` | `int` | - | Number of features (dimensions) for each antibody. | +| `feature_type` | `FeatureType` | `"continuous-features"` | Specifies the type of features: "continuous-features", "binary-features", "ranged-features", or "permutation-features". | +| `bounds` | `npt.NDArray[np.float64]` | `None` | Array (n_features, 2) with min and max per dimension. | + +**Raises** + +`ValueError` - If number of features must be greater than zero. + +**Returns** + +`npt.NDArray` - Array of shape (n_samples, n_features) containing the generated antibodies. From 8dc5d3355790cc144cc7d4e53005cccc24645fa1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Tue, 3 Mar 2026 12:43:27 -0300 Subject: [PATCH 07/40] docs(base): adds the immune module to the documentation in API format --- docs/assets/template-docs-class.md | 9 +++- docs/en/api/base/README.md | 16 +++---- docs/en/api/base/base-classifier.md | 7 ++- docs/en/api/base/base-clusterer.md | 7 ++- docs/en/api/base/base-optimizer.md | 7 ++- docs/en/api/base/immune/README.md | 22 +++++++++ docs/en/api/base/immune/cell/README.md | 33 +++++++++++++ docs/en/api/base/immune/cell/antibody.md | 32 +++++++++++++ docs/en/api/base/immune/cell/b-cell.md | 60 ++++++++++++++++++++++++ docs/en/api/base/immune/cell/cell.md | 26 ++++++++++ docs/en/api/base/immune/cell/detector.md | 28 +++++++++++ docs/en/api/base/immune/mutation.md | 2 +- docs/en/api/base/immune/populations.md | 2 +- docs/en/api/index.md | 7 +++ 14 files changed, 242 insertions(+), 16 deletions(-) create mode 100644 docs/en/api/base/immune/README.md create mode 100644 docs/en/api/base/immune/cell/README.md create mode 100644 docs/en/api/base/immune/cell/antibody.md create mode 100644 docs/en/api/base/immune/cell/b-cell.md create mode 100644 docs/en/api/base/immune/cell/cell.md create mode 100644 docs/en/api/base/immune/cell/detector.md create mode 100644 docs/en/api/index.md diff --git a/docs/assets/template-docs-class.md b/docs/assets/template-docs-class.md index 0b34805..0434e93 100644 --- a/docs/assets/template-docs-class.md +++ b/docs/assets/template-docs-class.md @@ -1,14 +1,19 @@ --- id: class-name sidebar_label: ClassName -keywords: - - tag +keywords: + - key --- # ClassName {{ Brief description of the class. }} +:::tip[Inheritance] +This class extends {{ class }} +::: + + > **Module:** `aisp.[module]` > **Import:** `from aisp.[module] import [class]` diff --git a/docs/en/api/base/README.md b/docs/en/api/base/README.md index bcd4501..631dcb4 100644 --- a/docs/en/api/base/README.md +++ b/docs/en/api/base/README.md @@ -20,14 +20,14 @@ Artificial Immune Systems algorithms implemented in the AISP package. ## Classes -| Class | Description | -|------------------|----------------------------------------------------| -| `BaseClassifier` | Abstract base class for classification algorithms. | -| `BaseClusterer` | Abstract base class for clustering algorithms. | -| `BaseOptimizer` | Abstract base class for optimization algorithms. | +| Class | Description | +|------------------------------------------|----------------------------------------------------| +| [`BaseClassifier`](./base-classifier.md) | Abstract base class for classification algorithms. | +| [`BaseClusterer`](./base-clusterer.md) | Abstract base class for clustering algorithms. | +| [`BaseOptimizer`](./base-optimizer.md) | Abstract base class for optimization algorithms. | ## Submodules -| Module | Description | -|----------|-----------------------------------------------| -| `immune` | Support Module for Artificial Immune Systems. | \ No newline at end of file +| Module | Description | +|--------------------------------|-----------------------------------------------| +| [`immune`](./immune/README.md) | Support Module for Artificial Immune Systems. | \ No newline at end of file diff --git a/docs/en/api/base/base-classifier.md b/docs/en/api/base/base-classifier.md index 3c9d0a9..7e10d1a 100644 --- a/docs/en/api/base/base-classifier.md +++ b/docs/en/api/base/base-classifier.md @@ -1,10 +1,13 @@ --- id: base-classifier sidebar_label: BaseClassifier -keywords: +keywords: - base - classifier - - accuracy + - classifier interface + - accuracy score + - fit + - predict --- # BaseClassifier diff --git a/docs/en/api/base/base-clusterer.md b/docs/en/api/base/base-clusterer.md index 28f9555..b092fdb 100644 --- a/docs/en/api/base/base-clusterer.md +++ b/docs/en/api/base/base-clusterer.md @@ -1,9 +1,14 @@ --- id: base-clusterer sidebar_label: BaseClusterer -keywords: +keywords: - base - clusterer + - clusterer interface + - cluster labels + - fit + - predict + - fit_predict --- # BaseClusterer diff --git a/docs/en/api/base/base-optimizer.md b/docs/en/api/base/base-optimizer.md index b8b740d..41f129b 100644 --- a/docs/en/api/base/base-optimizer.md +++ b/docs/en/api/base/base-optimizer.md @@ -1,9 +1,14 @@ --- id: base-optimizer sidebar_label: BaseOptimizer -keywords: +keywords: - base - optimizer + - optimization + - optimizer interface + - objective function + - minimization + - maximization --- # BaseOptimizer diff --git a/docs/en/api/base/immune/README.md b/docs/en/api/base/immune/README.md new file mode 100644 index 0000000..8b81302 --- /dev/null +++ b/docs/en/api/base/immune/README.md @@ -0,0 +1,22 @@ +--- +id: immune +sidebar_label: cell +keywords: + - cell + - mutation + - population +--- + +# aisp.base.immune + +Support Module for Artificial Immune Systems. + +> **Module:** `aisp.base.immune` + +## Classes + +| Class | Description | +|-----------------------------------|--------------------------------------------------------------------------------------------| +| [`cell`](./cell/README.md) | Representation of immune system cells. | +| [`mutation`](./mutation.md) | Functions to generate mutated clones and simulate clonal expansion. | +| [`populations`](./populations.md) | Provide utility functions for generating antibody populations in immunological algorithms. | \ No newline at end of file diff --git a/docs/en/api/base/immune/cell/README.md b/docs/en/api/base/immune/cell/README.md new file mode 100644 index 0000000..e35cc09 --- /dev/null +++ b/docs/en/api/base/immune/cell/README.md @@ -0,0 +1,33 @@ +--- +id: immune-cell +sidebar_label: cell +keywords: + - vector representation + - cell + - immune + - immune cell + - base class + - bcell + - antibody + - dataclass +--- + +# aisp.base.immune.cell + +Representation of immune system cells. + +> **Module:** `aisp.base.immune.cell` + +## Overview + +This module defines the representation of cells in artificial immune systems, +implements as dataclass. + +## Classes + +| Class | Description | +|-----------------------------|---------------------------------------------------| +| [`Cell`](./cell.md) | Represents a basic immune cell. | +| [`BCell`](./b-cell.md) | Represents a memory B-cell. | +| [`Antibody`](./antibody.md) | Represent an antibody. | +| [`Detector`](./detector.md) | Represents a non-self detector of the RNSA class. | \ No newline at end of file diff --git a/docs/en/api/base/immune/cell/antibody.md b/docs/en/api/base/immune/cell/antibody.md new file mode 100644 index 0000000..6f6897f --- /dev/null +++ b/docs/en/api/base/immune/cell/antibody.md @@ -0,0 +1,32 @@ +--- +id: antibody +sidebar_label: Antibody +keywords: + - antibody + - affinity + - cell + - immune + - dataclass +--- + +# Antibody + +Represent an antibody. + +:::tip[Inheritance] + +This class extends [Cell](./cell.md) + +::: + +> **Module:** `aisp.base.immune.cell` +> **Import:** `from aisp.base.immune.cell import Antibody` + +--- + +## Attributes + +| Name | Type | Default | Description | +|------------|---------------|:-------:|----------------------------------| +| `vector` | `npt.NDArray` | - | A vector of cell features. | +| `affinity` | `float` | - | Affinity value for the antibody. | diff --git a/docs/en/api/base/immune/cell/b-cell.md b/docs/en/api/base/immune/cell/b-cell.md new file mode 100644 index 0000000..0980287 --- /dev/null +++ b/docs/en/api/base/immune/cell/b-cell.md @@ -0,0 +1,60 @@ +--- +id: b-cell +sidebar_label: BCell +keywords: + - B-cell + - immune memory + - dataclass + - clonal mutation + - clonal expansion +--- + +# BCell + +Represents a memory B-cell. + +:::tip[Inheritance] + +This class extends [Cell](./cell.md) + +::: + +> **Module:** `aisp.base.immune.cell` +> **Import:** `from aisp.base.immune.cell import BCell` + +--- +## Attributes + +| Name | Type | Default | Description | +|----------|--------------|:-------:|----------------------------| +| `vector` | `np.ndarray` | - | A vector of cell features. |] + +--- + +## Public Methods + +### hyper_clonal_mutate + +```python +def hyper_clonal_mutate( + self, + n: int, + feature_type: FeatureType = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None +) -> npt.NDArray: + ... +``` + +Clones N features from a cell's features, generating a set of mutated vectors. + +**Parameters** + +| Name | Type | Default | Description | +|----------------|-------------------------------------------------------------------|:-----------------------:|-------------------------------------------------------------------------------------| +| `n` | `int` | - | Number of clones to be generated from mutations of the original cell. | +| `feature_type` | `{ "binary-features", "continuous-features", "ranged-features" }` | `"continuous-features"` | Specifies the type of feature_type to use based on the nature of the input features | +| `bounds` | `Optional[npt.NDArray[np.float64]]` | `None` | Array (n_features, 2) with min and max per dimension. | + +**Returns** + +`npt.NDArray` - An array containing N mutated vectors from the original cell. diff --git a/docs/en/api/base/immune/cell/cell.md b/docs/en/api/base/immune/cell/cell.md new file mode 100644 index 0000000..304e1af --- /dev/null +++ b/docs/en/api/base/immune/cell/cell.md @@ -0,0 +1,26 @@ +--- +id: cell +sidebar_label: Cell +keywords: + - vector representation + - cell + - immune + - immune cell + - base class + - dataclass +--- + +# Cell + +Represents a basic immune cell. + +> **Module:** `aisp.base.immune.cell` +> **Import:** `from aisp.base.immune.cell import Cell` + +--- + +## Attributes + +| Name | Type | Default | Description | +|----------|--------------|:-------:|----------------------------| +| `vector` | `np.ndarray` | - | A vector of cell features. |] diff --git a/docs/en/api/base/immune/cell/detector.md b/docs/en/api/base/immune/cell/detector.md new file mode 100644 index 0000000..520294d --- /dev/null +++ b/docs/en/api/base/immune/cell/detector.md @@ -0,0 +1,28 @@ +--- +id: detector +sidebar_label: Detector +keywords: + - detector + - cell + - immune + - radius + - non-self + - nsa + - dataclass +--- + +# Detector + +Represents a non-self detector of the RNSA class. + +> **Module:** `aisp.base.immune.cell` +> **Import:** `from aisp.base.immune.cell import Detector` + +--- + +## Attributes + +| Name | Type | Default | Description | +|------------|---------------------------|:-------:|----------------------------------------------------| +| `position` | `npt.NDArray[np.float64]` | - | Detector feature vector. | +| `radius` | `float, optional` | - | Detector radius, used in the V-detector algorithm. | diff --git a/docs/en/api/base/immune/mutation.md b/docs/en/api/base/immune/mutation.md index 36c9c8b..6c9497f 100644 --- a/docs/en/api/base/immune/mutation.md +++ b/docs/en/api/base/immune/mutation.md @@ -1,7 +1,7 @@ --- id: mutation sidebar_label: mutation -keywords: +keywords: - mutation - clonal expansion - immune system diff --git a/docs/en/api/base/immune/populations.md b/docs/en/api/base/immune/populations.md index c7f6620..9d59d9b 100644 --- a/docs/en/api/base/immune/populations.md +++ b/docs/en/api/base/immune/populations.md @@ -1,7 +1,7 @@ --- id: populations sidebar_label: populations -keywords: +keywords: - binary - classifying - affinity threshold diff --git a/docs/en/api/index.md b/docs/en/api/index.md new file mode 100644 index 0000000..e61dd24 --- /dev/null +++ b/docs/en/api/index.md @@ -0,0 +1,7 @@ +--- +tags: + - api + - documentation +--- + +# API - Reference \ No newline at end of file From aecbe4400dfc6b75773f0f2ca665a2a59fa0f69a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Tue, 3 Mar 2026 14:02:06 -0300 Subject: [PATCH 08/40] docs(csa): adds AIRS API documentation --- docs/en/api/csa/airs.md | 182 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 182 insertions(+) create mode 100644 docs/en/api/csa/airs.md diff --git a/docs/en/api/csa/airs.md b/docs/en/api/csa/airs.md new file mode 100644 index 0000000..d2f0c5d --- /dev/null +++ b/docs/en/api/csa/airs.md @@ -0,0 +1,182 @@ +--- +id: airs +sidebar_label: AIRS +keywords: + - classification + - artificial immune recognition system + - memory cells + - k-nn + - supervised learning +--- + +# AIRS + +Artificial Immune Recognition System (AIRS) + +:::tip[Inheritance] + +This class extends [BaseClassifier](../base/base-classifier.md) + +::: + + +> **Module:** `aisp.csa` +> **Import:** `from aisp.csa import AIRS` + +--- + +## Overview + +The Artificial Immune Recognition System (AIRS) is a classification algorithm inspired by the +clonal selection process of the biological immune system. This implementation is based on the +simplified AIRS2 version described in [^1]. The algorithm has been adapted to support both +real-valued (continuous) and binary feature datasets. + +:::note + +This implementation is inspired by AIRS2, a simplified version of the original AIRS algorithm. +Introducing adaptations to handle continuous and binary datasets. + +Based on Algorithm 16.5 from Brabazon et al. [^1] + +Related and noteworthy works: access here [^2]. + +::: + +--- + +## Example + +```python +import numpy as np +from aisp.csa import AIRS + +np.random.seed(1) +# Generating training data +a = np.random.uniform(high=0.5, size=(50, 2)) +b = np.random.uniform(low=0.51, size=(50, 2)) +x_train = np.vstack((a, b)) +y_train = [0] * 50 + [1] * 50 +# AIRS Instance +airs = AIRS(n_resources=5, rate_clonal=5, rate_hypermutation=0.65, seed=1) +airs = airs.fit(x_train, y_train, verbose=False) +x_test = [ + [0.15, 0.45], # Expected: Class 0 + [0.85, 0.65], # Esperado: Classe 1 +] +y_pred = airs.predict(x_test) +print(y_pred) +``` +Output: +```bash +[0 1] +``` + + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|-----------------------------|---------|:-------------:|---------------------------------------------------------------------------------------------------------------------------------------------------| +| `n_resources` | `float` | `10` | Total amount of available resources. | +| `rate_clonal` | `float` | `10` | Maximum number of possible clones of a class. This quantity is multiplied by (cell_stimulus * rate_hypermutation) to define the number of clones. | +| `rate_mc_init` | `float` | `0.2` | Percentage of samples used to initialize memory cells. | +| `rate_hypermutation` | `float` | `0.75` | The rate of mutated clones derived from rate_clonal as a scalar factor. | +| `affinity_threshold_scalar` | `float` | `0.75` | Normalized affinity threshold. | +| `k` | `int` | `3` | The number of K nearest neighbors that will be used to choose a label in the prediction. | +| `max_iters` | `int` | `100` | Maximum number of interactions in the refinement process of the ARB set exposed to aᵢ. | +| `resource_amplified` | `float` | `1.0` | Resource consumption amplifier is multiplied with the incentive to subtract resources. | +| `metric` | `str` | `"euclidean"` | Distance metric used to compute affinity between cells and samples. | +| `seed` | `int` | `None` | Seed for the random generation of detector values. Defaults to None. | +| `p` | `float` | `2` | This parameter stores the value of ``p`` used in the Minkowski distance. | + +## Attributes + +| Name | Type | Default | Description | +|----------------|-------------------------------------------|:-------:|---------------------------------------------------------| +| `cells_memory` | `Optional[Dict[str \| int, list[BCell]]]` | - | Dictionary of trained memory cells, organized by class. | + + +--- + +## References + +[^1]: Brabazon, A., O'Neill, M., & McGarraghy, S. (2015). Natural Computing Algorithms. In Natural Computing Series. + Springer Berlin Heidelberg. [https://doi.org/10.1007/978-3-662-43631-8](https://doi.org/10.1007/978-3-662-43631-8) + +[^2]: AZZOUG, Aghiles. Artificial Immune Recognition System V2. Available at: + [https://github.com/AghilesAzzoug/Artificial-Immune-System](https://github.com/AghilesAzzoug/Artificial-Immune-System) + + +--- + +## Public Methods + +### fit + +```python +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True, +) -> AIRS: + ... +``` +Fit the model to the training data using the AIRS. + +The function ``fit(...)``, performs the training according to ``X`` and ``y``, using the +method AIRS. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|---------------------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Training array, containing the samples and their characteristics, Shape: (n_samples, n_features). | +| `y` | `Union[npt.NDArray, list]` | - | Array of target classes of ``X`` with (``n_samples``). | +| `verbose` | `bool` | `True` | Feedback on which sample aᵢ the memory cells are being generated. | + +**Returns** + +`AIRS` - Returns the instance itself. + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` +Predict class labels based on the memory cells created during training. + +This method uses the trained memory cells to perform classification of the input data +using the k-nearest neighbors approach. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|-------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Array with input samples with Shape: (``n_samples, n_features``) | + +**Raises** + +* `TypeError` - If X is not a ndarray or list. +* `FeatureDimensionMismatch` - If the number of features in X does not match the expected number. +* `ModelNotFittedError` - If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions + +**Returns** + +C `npt.NDArray` - An ndarray of the form ``C`` (``n_samples``), containing the predicted classes for ``X``. + +--- + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + +- [**Iris Dataset Example**](../../../../examples/en/classification/AIRS/iris_dataBase_example_en.ipynb) +- [**Geyser Dataset Example**](../../../../examples/en/classification/AIRS/geyser_dataBase_example_en.ipynb) +- [**Mushrooms Dataset Example**](../../../../examples/en/classification/AIRS/mushrooms_dataBase_example_en.ipynb) +- [**Random Dataset Example**](../../../../examples/en/classification/AIRS/example_with_randomly_generated_dataset-en.ipynb) \ No newline at end of file From 8b6eecfb34ddd397e18736a8b9bc93d47a6b9e96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Tue, 3 Mar 2026 14:06:23 -0300 Subject: [PATCH 09/40] docs: change the position of the references --- docs/assets/template-docs-class.md | 15 ++++++++------- docs/en/api/{index.md => README.md} | 0 docs/en/api/csa/airs.md | 24 ++++++++++++------------ 3 files changed, 20 insertions(+), 19 deletions(-) rename docs/en/api/{index.md => README.md} (100%) diff --git a/docs/assets/template-docs-class.md b/docs/assets/template-docs-class.md index 0434e93..5e9ca6f 100644 --- a/docs/assets/template-docs-class.md +++ b/docs/assets/template-docs-class.md @@ -56,12 +56,6 @@ model.method_name() --- -## References - -1. - ---- - ## Public Methods ### method_name @@ -84,4 +78,11 @@ Description. Complete usage examples are available in the Jupyter Notebooks: -- [example](#link) \ No newline at end of file +- [example](#link) + + +--- + +## References + +[^1]: {{ Reference }} diff --git a/docs/en/api/index.md b/docs/en/api/README.md similarity index 100% rename from docs/en/api/index.md rename to docs/en/api/README.md diff --git a/docs/en/api/csa/airs.md b/docs/en/api/csa/airs.md index d2f0c5d..fe25de7 100644 --- a/docs/en/api/csa/airs.md +++ b/docs/en/api/csa/airs.md @@ -98,17 +98,6 @@ Output: | `cells_memory` | `Optional[Dict[str \| int, list[BCell]]]` | - | Dictionary of trained memory cells, organized by class. | ---- - -## References - -[^1]: Brabazon, A., O'Neill, M., & McGarraghy, S. (2015). Natural Computing Algorithms. In Natural Computing Series. - Springer Berlin Heidelberg. [https://doi.org/10.1007/978-3-662-43631-8](https://doi.org/10.1007/978-3-662-43631-8) - -[^2]: AZZOUG, Aghiles. Artificial Immune Recognition System V2. Available at: - [https://github.com/AghilesAzzoug/Artificial-Immune-System](https://github.com/AghilesAzzoug/Artificial-Immune-System) - - --- ## Public Methods @@ -179,4 +168,15 @@ Complete usage examples are available in the Jupyter Notebooks: - [**Iris Dataset Example**](../../../../examples/en/classification/AIRS/iris_dataBase_example_en.ipynb) - [**Geyser Dataset Example**](../../../../examples/en/classification/AIRS/geyser_dataBase_example_en.ipynb) - [**Mushrooms Dataset Example**](../../../../examples/en/classification/AIRS/mushrooms_dataBase_example_en.ipynb) -- [**Random Dataset Example**](../../../../examples/en/classification/AIRS/example_with_randomly_generated_dataset-en.ipynb) \ No newline at end of file +- [**Random Dataset Example**](../../../../examples/en/classification/AIRS/example_with_randomly_generated_dataset-en.ipynb) + + +--- + +## References + +[^1]: Brabazon, A., O'Neill, M., & McGarraghy, S. (2015). Natural Computing Algorithms. In Natural Computing Series. + Springer Berlin Heidelberg. [https://doi.org/10.1007/978-3-662-43631-8](https://doi.org/10.1007/978-3-662-43631-8) + +[^2]: AZZOUG, Aghiles. Artificial Immune Recognition System V2. Available at: + [https://github.com/AghilesAzzoug/Artificial-Immune-System](https://github.com/AghilesAzzoug/Artificial-Immune-System) From 5f38f3886c6ccbdb9cbbab70760d87b69c96ef21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Tue, 3 Mar 2026 15:16:41 -0300 Subject: [PATCH 10/40] docs(mutation): replaces <= and >= with special characters to avoid errors in Docusaurus --- aisp/base/immune/mutation.py | 14 ++++++------ docs/en/api/base/immune/mutation.md | 34 ++++++++++++++--------------- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/aisp/base/immune/mutation.py b/aisp/base/immune/mutation.py index 2450f56..081e072 100644 --- a/aisp/base/immune/mutation.py +++ b/aisp/base/immune/mutation.py @@ -30,8 +30,8 @@ def clone_and_mutate_continuous( n : int The number of mutated clones to be generated. mutation_rate : float, default=1 - If 0 <= mutation_rate < 1: probability of mutating each component. - If mutation_rate >= 1 or mutation_rate <= 0: the mutation randomizes + If 0 ≤ mutation_rate < 1: probability of mutating each component. + If mutation_rate ≥ 1 or mutation_rate ≤ 0: the mutation randomizes a number of components between 1 and len(vector). Returns @@ -78,8 +78,8 @@ def clone_and_mutate_binary( n : int The number of mutated clones to be generated. mutation_rate : float, default=1 - If 0 <= mutation_rate < 1: probability of mutating each component. - If mutation_rate >= 1 or mutation_rate <= 0: the mutation randomizes + If 0 ≤ mutation_rate < 1: probability of mutating each component. + If mutation_rate ≥ 1 or mutation_rate ≤ 0: the mutation randomizes a number of components between 1 and len(vector). Returns @@ -129,8 +129,8 @@ def clone_and_mutate_ranged( bounds : np.ndarray Array (n_features, 2) with min and max per dimension. mutation_rate : float, default=1 - If 0 <= mutation_rate < 1: probability of mutating each component. - If mutation_rate >= 1 or mutation_rate <= 0: the mutation randomizes + If 0 ≤ mutation_rate < 1: probability of mutating each component. + If mutation_rate ≥ 1 or mutation_rate ≤ 0: the mutation randomizes a number of components between 1 and len(vector). Returns @@ -175,7 +175,7 @@ def clone_and_mutate_permutation( n : int The number of mutated clones to be generated. mutation_rate : float - Probability of mutating each component 0 <= mutation_rate < 1. + Probability of mutating each component 0 ≤ mutation_rate < 1. Returns ------- diff --git a/docs/en/api/base/immune/mutation.md b/docs/en/api/base/immune/mutation.md index 6c9497f..0a40c4d 100644 --- a/docs/en/api/base/immune/mutation.md +++ b/docs/en/api/base/immune/mutation.md @@ -41,11 +41,11 @@ in distinct positions of the original vector. **Parameters** -| Name | Type | Default | Description | -|-----------------|---------------------------|:-------:|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with continuous values to be cloned and mutated. | -| `n` | `int` | - | The number of mutated clones to be generated. | -| `mutation_rate` | `float` | - | If 0 <= mutation_rate < 1: probability of mutating each component. If mutation_rate >= 1 or mutation_rate <= 0: the mutation randomizes a number of components between 1 and len(vector). | +| Name | Type | Default | Description | +|-----------------|---------------------------|:-------:|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with continuous values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `mutation_rate` | `float` | - | If 0 ≤ mutation_rate < 1: probability of mutating each component. If mutation_rate ≥ 1 or mutation_rate ≤ 0: the mutation randomizes a number of components between 1 and len(vector). | **Returns** @@ -71,11 +71,11 @@ immune systems with discrete representations. **Parameters** -| Name | Type | Default | Description | -|-----------------|---------------------------|:-------:|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with binary values to be cloned and mutated. | -| `n` | `int` | - | The number of mutated clones to be generated. | -| `mutation_rate` | `float` | - | If 0 <= mutation_rate < 1: probability of mutating each component. If mutation_rate >= 1 or mutation_rate <= 0: the mutation randomizes a number of components between 1 and len(vector). | +| Name | Type | Default | Description | +|-----------------|---------------------------|:-------:|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with binary values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `mutation_rate` | `float` | - | If 0 ≤ mutation_rate < 1: probability of mutating each component. If mutation_rate ≥ 1 or mutation_rate ≤ 0: the mutation randomizes a number of components between 1 and len(vector). | **Returns** @@ -103,12 +103,12 @@ will have a random number of mutations applied in distinct positions of the orig **Parameters** -| Name | Type | Default | Description | -|-----------------|---------------------------|:-------:|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with continuous values to be cloned and mutated. | -| `n` | `int` | - | The number of mutated clones to be generated. | -| `bounds` | `np.ndarray` | - | Array (n_features, 2) with min and max per dimension. | -| `mutation_rate` | `float` | - | If 0 <= mutation_rate < 1: probability of mutating each component. If mutation_rate >= 1 or mutation_rate <= 0: the mutation randomizes a number of components between 1 and len(vector). | +| Name | Type | Default | Description | +|-----------------|---------------------------|:-------:|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with continuous values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `bounds` | `np.ndarray` | - | Array (n_features, 2) with min and max per dimension. | +| `mutation_rate` | `float` | - | If 0 ≤ mutation_rate < 1: probability of mutating each component. If mutation_rate ≥ 1 or mutation_rate ≤ 0: the mutation randomizes a number of components between 1 and len(vector). | **Returns** @@ -135,7 +135,7 @@ Generate a set of mutated clones by random permutation. |-----------------|-------------------------|:-------:|----------------------------------------------------------------------------| | `vector` | `npt.NDArray[np.int64]` | - | The original immune cell with permutation values to be cloned and mutated. | | `n` | `int` | - | The number of mutated clones to be generated. | -| `mutation_rate` | `float` | - | Probability of mutating each component 0 <= mutation_rate < 1. | +| `mutation_rate` | `float` | - | Probability of mutating each component 0 ≤ mutation_rate < 1. | **Returns** From 8672ca5a368586d883c3a19286114ed02e20a797 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Tue, 3 Mar 2026 15:20:57 -0300 Subject: [PATCH 11/40] docs(cell): adds descriptions of the standard methods lt, eq, and getitem --- docs/en/api/base/immune/cell/antibody.md | 7 +++++++ docs/en/api/base/immune/cell/cell.md | 11 ++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/docs/en/api/base/immune/cell/antibody.md b/docs/en/api/base/immune/cell/antibody.md index 6f6897f..2a6aa20 100644 --- a/docs/en/api/base/immune/cell/antibody.md +++ b/docs/en/api/base/immune/cell/antibody.md @@ -30,3 +30,10 @@ This class extends [Cell](./cell.md) |------------|---------------|:-------:|----------------------------------| | `vector` | `npt.NDArray` | - | A vector of cell features. | | `affinity` | `float` | - | Affinity value for the antibody. | + +--- + +## Methods + +* `__lt__(other)`: Compare this cell with another Antibody cell based on affinity. +* `__eq__(other)`: Check if this cell has the same affinity as another cell. diff --git a/docs/en/api/base/immune/cell/cell.md b/docs/en/api/base/immune/cell/cell.md index 304e1af..ff94da9 100644 --- a/docs/en/api/base/immune/cell/cell.md +++ b/docs/en/api/base/immune/cell/cell.md @@ -23,4 +23,13 @@ Represents a basic immune cell. | Name | Type | Default | Description | |----------|--------------|:-------:|----------------------------| -| `vector` | `np.ndarray` | - | A vector of cell features. |] +| `vector` | `np.ndarray` | - | A vector of cell features. | + +--- + +## Methods + +* `__eq__(other)`: Check if two cells are equal based on their vectors. +* `__array__()`: Array interface to NumPy, allows the instance to be treated as a `np.ndarray`. +* `__getitem__(item)`: Get elements from the feature vector using indexing. + From f5f6fdf7c53b75f883c04f57af7cc2757c07dcfc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Tue, 3 Mar 2026 15:47:25 -0300 Subject: [PATCH 12/40] docs(base): remove old version of docs already added --- .../Core/Negative Selection.md | 94 ---------- docs/en/advanced-guides/base/base.md | 43 ----- docs/en/advanced-guides/base/classifier.md | 80 --------- docs/en/advanced-guides/base/clusterer.md | 74 -------- docs/en/advanced-guides/base/immune/cell.md | 102 ----------- .../advanced-guides/base/immune/mutation.md | 116 ------------- .../base/immune/populations.md | 31 ---- docs/en/advanced-guides/base/optimizer.md | 161 ------------------ 8 files changed, 701 deletions(-) delete mode 100644 docs/en/advanced-guides/Core/Negative Selection.md delete mode 100644 docs/en/advanced-guides/base/base.md delete mode 100644 docs/en/advanced-guides/base/classifier.md delete mode 100644 docs/en/advanced-guides/base/clusterer.md delete mode 100644 docs/en/advanced-guides/base/immune/cell.md delete mode 100644 docs/en/advanced-guides/base/immune/mutation.md delete mode 100644 docs/en/advanced-guides/base/immune/populations.md delete mode 100644 docs/en/advanced-guides/base/optimizer.md diff --git a/docs/en/advanced-guides/Core/Negative Selection.md b/docs/en/advanced-guides/Core/Negative Selection.md deleted file mode 100644 index 95ab3b8..0000000 --- a/docs/en/advanced-guides/Core/Negative Selection.md +++ /dev/null @@ -1,94 +0,0 @@ -**Negative Selection** - -The functions perform detector checks and utilize Numba decorators for Just-In-Time compilation - -### Function check_detector_bnsa_validity(...) - -```python -@njit([(types.boolean[:, :], types.boolean[:], types.float64)], cache=True) -def check_detector_bnsa_validity( - x_class: npt.NDArray[np.bool_], - vector_x: npt.NDArray[np.bool_], - aff_thresh: float -) -> bool: -``` - -Checks the validity of a candidate detector (vector_x) against samples from a class (x_class) using the Hamming distance. A detector is considered INVALID if its distance to any sample in ``x_class`` is less than or equal to ``aff_thresh``. - -**Parameters:** - -* **x_class** (``npt.NDArray[np.bool_]``): Array containing the class samples. Expected shape: (n_samples, n_features). -* **vector_x** (``npt.NDArray[np.bool_]``): Array representing the detector. Expected shape: (n_features,). -* **aff_thresh** (``float``): Affinity threshold. - -**returns**: - -* True if the detector is valid, False otherwise. - ---- - -### Function bnsa_class_prediction(...) - -```python -@njit([(types.boolean[:], types.boolean[:, :, :], types.float64)], cache=True) -def bnsa_class_prediction( - features: npt.NDArray[np.bool_], - class_detectors: npt.NDArray[np.bool_], - aff_thresh: float, -) -> int: -``` - -Defines the class of a sample from the non-self detectors. - -**Parameters:** - -* **features** (``npt.NDArray[np.bool_]``): binary sample to be classified (shape: [n_features]). -* **class_detectors** (``npt.NDArray[np.bool_]``): Array containing the detectors of all classes -Shape: (n_classes, n_detectors, n_features). -* **aff_thresh** (``float``): Affinity threshold that determines whether a detector recognizes the sample as non-self. - -**returns**: - -* int: Index of the predicted class. Returns -1 if it is non-self for all classes. - ---- - -### Function check_detector_rnsa_validity(...) - -```python -@njit( - [ - ( - types.float64[:, :], - types.float64[:], - types.float64, - types.int32, - types.float64, - ) - ], - cache=True, -) -def check_detector_rnsa_validity( - x_class: npt.NDArray[np.float64], - vector_x: npt.NDArray[np.float64], - threshold: float, - metric: int, - p: float, -) -> bool: -``` - -Checks the validity of a candidate detector (vector_x) against samples from a class (x_class) using the Hamming distance. A detector is considered INVALID if its distance to any sample in ``x_class`` is less than or equal to ``aff_thresh``. - -**Parameters:** - -* **x_class** (``npt.NDArray[np.float64]``): Array containing the class samples. Expected shape: (n_samples, n_features). -* **vector_x** (``npt.NDArray[np.float64]``): Array representing the detector. Expected shape: (n_features,). -* **threshold** (``float``): threshold. -* **metric** (``int``): Distance metric to be used. Available options: 0 (Euclidean), 1 (Manhattan), 2 (Minkowski) -* **p** (``float``): Parameter for the Minkowski distance (used only if `metric` is "minkowski"). - -**returns**: - -* `int`: Index of the predicted class. Returns -1 if it is non-self for all classes. - ---- diff --git a/docs/en/advanced-guides/base/base.md b/docs/en/advanced-guides/base/base.md deleted file mode 100644 index bbe5b2d..0000000 --- a/docs/en/advanced-guides/base/base.md +++ /dev/null @@ -1,43 +0,0 @@ -# Base Class - -Base class for parameter introspection compatible with the scikit-learn API. - -## Base - -Generic base class for models with a common interface. - -Provides the `get_params` and `set_params` methods for compatibility with the scikit-learn API, allowing access to the model's public parameters. - -### Method `set_params(...)` - -```python -def set_params(self, **params) -> Base: -``` - -Set the parameters of the instance. Ensures compatibility with scikit-learn functions. - -**Parameters**: - -* **params** (`dict`): Dictionary of parameters to set as attributes on the instance. Only public attributes (not starting with "_") are modified. - -**Returns**: - -* self (`Base`): Returns the instance itself after setting the parameters. - ---- - -### Method `get_params(...)` - -```python -def get_params(self, deep: bool = True) -> dict -``` - -Return a dictionary with the object's main parameters. Ensures compatibility with scikit-learn functions. - -**Parameters**: - -* **deep**: (`bool`, default=True)): Ignored in this implementation but included for scikit-learn compatibility. - -**Returns**: - -* params (`dict`): Dictionary containing the object's attributes that do not start with "_". diff --git a/docs/en/advanced-guides/base/classifier.md b/docs/en/advanced-guides/base/classifier.md deleted file mode 100644 index 3043940..0000000 --- a/docs/en/advanced-guides/base/classifier.md +++ /dev/null @@ -1,80 +0,0 @@ -Base class for classification algorithm. - -# BaseClassifier - -Base class for classification algorithms, defining the abstract methods ``fit`` and ``predict``, and implementing the ``get_params`` method. - -### Method `score(...)` - -```python -def score( - self, - X: Union[npt.NDArray, list], - y: Union[npt.NDArray, list] -) -> float: -``` - -Score function calculates forecast accuracy. - -This function performs the prediction of X and checks how many elements are equal between vector y and y_predicted. -This function was added for compatibility with some scikit-learn functions. - -**Parameters:** - -* **X** (`Union[npt.NDArray, list]`): Feature set with shape (n_samples, n_features). -* **y** (`Union[npt.NDArray, list]`): True values with shape (n_samples,). - -**Returns**: - -* accuracy: ``float`` The accuracy of the model. - ---- - -### Method `_slice_index_list_by_class(...)` - -The function ``_slice_index_list_by_class(...)```, separates the indices of the lines according to the output class, to go through the sample array, only in the positions that the output is the class that is being trained: - -```python -def _slice_index_list_by_class(self, y: npt.NDArray) -> dict: -``` - -Returns a dictionary with the classes as key and the indices in ``X`` of the samples. - ---- - -## Abstract methods - -### Method `fit(...)` - -```python -@abstractmethod -def fit( - self, - X: Union[npt.NDArray, list], - y: Union[npt.NDArray, list], - verbose: bool = True -) -> BaseClassifier: -``` - -Fit the model to the training data. - -Implementation: - -* [RNSA](../../classes/Negative%20Selection/RNSA.md#method-fit) -* [BNSA](../../classes/Negative%20Selection/BNSA.md#method-fit) -* [AIRS](../../classes/Clonal%20Selection%20Algorithms/AIRS.md#method-fit) - -### Method `predict(...)` - -```python -@abstractmethod -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -Performs label prediction for the given data. - -Implementation: - -* [RNSA](../../classes/Negative%20Selection/RNSA.md#method-predict) -* [BNSA](../../classes/Negative%20Selection/BNSA.md#method-predict) -* [AIRS](../../classes/Clonal%20Selection%20Algorithms/AIRS.md#method-predict) diff --git a/docs/en/advanced-guides/base/clusterer.md b/docs/en/advanced-guides/base/clusterer.md deleted file mode 100644 index 486d442..0000000 --- a/docs/en/advanced-guides/base/clusterer.md +++ /dev/null @@ -1,74 +0,0 @@ -# BaseClusterer - -Abstract base class for clustering algorithms. - -This class defines the core interface for clustering models. It enforces -the implementation of the **`fit`** and **`predict`** methods in all derived classes. - ---- - -### Method `fit(...)` - -```python -@abstractmethod -def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> BaseClusterer: -``` - -Fit the model to the training data. -This abstract method must be implemented by subclasses. - -**Parameters**: - -* **X** (`Union[npt.NDArray, list]`): Input data used for training the model. -* **verbose** (`bool`, default=True): Flag to enable or disable detailed output during training. - -**Returns**: - -* **self** (`BaseClusterer`): Instance of the class that implements this method. - -**Implementation**: - -* [AiNet](../../classes/Network%20Theory%20Algorithms/AiNet.md#method-fit) - ---- - -### Method `predict(...)` - -```python -@abstractmethod -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -Generate predictions based on the input data. -This abstract method must be implemented by subclasses. - -**Parameters**: - -* **X** (`Union[npt.NDArray, list]`): Input data for which predictions will be generated. - -**Returns**: - -* **predictions** (`npt.NDArray`): Predicted cluster labels for each input sample. - -**Implementation**: - -* [AiNet](../../classes/Network%20Theory%20Algorithms/AiNet.md#method-predict) - ---- - -### Method `fit_predict(...)` - -```python -def fit_predict(self, X: Union[npt.NDArray, list], verbose: bool = True) -> npt.NDArray: -``` - -Convenience method that combines `fit` and `predict` in a single call. - -**Parameters**: - -* **X** (`Union[npt.NDArray, list]`): Input data for which predictions will be generated. -* **verbose** (`bool`, default=True): Flag to enable or disable detailed output during training. - -**Returns**: - -* **predictions**: `npt.NDArray` - Predicted cluster labels for each input sample. diff --git a/docs/en/advanced-guides/base/immune/cell.md b/docs/en/advanced-guides/base/immune/cell.md deleted file mode 100644 index eff26fd..0000000 --- a/docs/en/advanced-guides/base/immune/cell.md +++ /dev/null @@ -1,102 +0,0 @@ -# Cell Classes - -Representation of immune system cells. - -## Cell - -Represents a basic immune cell. - -```python -@dataclass(slots=True) -class Cell: - vector: np.ndarray -``` - -### Attributes - -* **vector** (`np.ndarray`): A vector of cell features. - -### Methods - -* `__eq__(other)`: Check if two cells are equal based on their vectors. -* `__array__()`: Array interface to NumPy, allows the instance to be treated as a `np.ndarray`. -* `__getitem__(item)`: Get elements from the feature vector using indexing. - ---- - -## BCell - -Represents a memory B-cell. - -```python -@dataclass(slots=True, eq=False) -class BCell(Cell): - vector: np.ndarray -``` - -### Methods - -#### hyper_clonal_mutate(...) - -```python -def hyper_clonal_mutate( - self, - n: int, - feature_type: FeatureType = "continuous-features", - bounds: Optional[npt.NDArray[np.float64]] = None -) -> np.ndarray -``` - -Clones N features from a cell's features, generating a set of mutated vectors. - -##### Parameters - -* **n** (`int`): Number of clones to be generated from mutations of the original cell. -* **feature_type** (`Literal["binary-features", "continuous-features", "ranged-features"]`): - Specifies the type of feature_type to use based on the nature of the input features -* **bounds** (`Optional[npt.NDArray[np.float64]]`): Array (n_features, 2) with min and max per dimension. - -##### Returns - -* **npt.NDArray**: An array containing N mutated vectors from the original cell. - ---- - -## Antibody - -Represent an antibody. - -```python -@dataclass(slots=True) -class Antibody(Cell): - vector: np.ndarray - affinity: float -``` - -### Attributes - -* **vector** (`npt.NDArray`): A vector of cell features. -* **affinity** (`float`): Affinity value for the antibody. - -### Methods - -* `__lt__(other)`: Compare this cell with another Antibody cell based on affinity. -* `__eq__(other)`: Check if this cell has the same affinity as another cell. - ---- - -## Detector - -Represents a non-self detector of the RNSA class. - -```python -@dataclass(slots=True) -class Detector: - position: npt.NDArray[np.float64] - radius: Optional[float] = None -``` - -### Attributes - -* **position** (`npt.NDArray[np.float64]`): Detector feature vector. -* **radius** (`Optional[float]`): Detector radius, used in the V-detector algorithm. diff --git a/docs/en/advanced-guides/base/immune/mutation.md b/docs/en/advanced-guides/base/immune/mutation.md deleted file mode 100644 index 730ba85..0000000 --- a/docs/en/advanced-guides/base/immune/mutation.md +++ /dev/null @@ -1,116 +0,0 @@ -# Mutation - -Contains functions that generate sets of mutated clones from continuous or binary vectors, simulating the clonal expansion process in artificial immune systems. - -## clone_and_mutate_continuous - -```python -@njit([(types.float64[:], types.int64, types.float64)], cache=True) -def clone_and_mutate_continuous( - vector: npt.NDArray[np.float64], - n: int, - mutation_rate: float -) -> npt.NDArray[np.float64]: -``` - -Generates a set of mutated clones from a continuous vector. - -This function creates `n` clones of the input vector and applies random mutations to each one, simulating the clonal expansion process in artificial immune systems. Each clone receives a random number of mutations at distinct positions of the original vector. - -### Parameters - -* `vector` (`npt.NDArray[np.float64]`): The original immune cell with continuous values to be cloned and mutated. -* `n` (`int`): Number of mutated clones to be generated. -* ``mutation_rate`` : (``float``) If 0 <= mutation_rate < 1: probability of mutating each component. - If mutation_rate >= 1 or mutation_rate <= 0: the mutation randomizes - number of components between 1 and len(vector). - -### Returns - -* `clone_set` (`npt.NDArray[np.float64]`): Array with shape `(n, len(vector))` containing the `n` mutated clones of the original vector. - ---- - -## clone_and_mutate_binary - -```python -@njit([(types.boolean[:], types.int64, types.float64)], cache=True) -def clone_and_mutate_binary( - vector: npt.NDArray[np.bool_], - n: int, - mutation_rate: float -) -> npt.NDArray[np.bool_]: -``` - -Generates a set of mutated clones from a binary vector. - -This function creates `n` clones of the input binary vector and applies random mutations to some bits, simulating clonal expansion in artificial immune systems with discrete representations. - -### Parameters - -* `vector` (`npt.NDArray[np.bool_]`): The original immune cell with binary values to be cloned and mutated. -* `n` (`int`): Number of mutated clones to be generated. - -### Returns - -* `clone_set` (`npt.NDArray[np.bool_]`): Array with shape `(n, len(vector))` containing the `n` mutated clones of the original vector. - ---- - -## clone_and_mutate_ranged - -```python -@njit([(types.float64[:], types.int64, types.float64[:, :], types.float64)], cache=True) -def clone_and_mutate_ranged( - vector: npt.NDArray[np.float64], - n: int, - bounds: npt.NDArray[np.float64], - mutation_rate: float, -) -> npt.NDArray[np.float64]: -``` - -Generates a set of mutated clones from a continuous vector using custom bounds per dimension. - -This function creates `n` clones of the input vector and applies random mutations to each of them, simulating the process of clonal expansion in artificial immune systems. Each clone will have a random number of mutations applied to distinct positions of the original vector, respecting the mutation bounds defined per dimension. - -### Parameters - -* `vector` (`npt.NDArray[np.float64]`): The original immune cell with continuous values to be cloned and mutated. -* `n` (`int`): Number of mutated clones to be generated. -* `bounds` (`npt.NDArray[np.float64]`): A 2D array with shape `(len(vector), 2)` containing the minimum and maximum values for each dimension. -* ``mutation_rate`` : (``float``) If 0 <= mutation_rate < 1: probability of mutating each component. - If mutation_rate >= 1 or mutation_rate <= 0: the mutation randomizes - number of components between 1 and len(vector). - -### Returns - -* `clone_set` (`npt.NDArray[np.float64]`): Array with shape `(n, len(vector))` containing the `n` mutated clones of the original vector. - ---- - -## clone_and_mutate_permutation - -```python -@njit([(types.int64[:], types.int64, types.float64)], cache=True) -def clone_and_mutate_permutation( - vector: npt.NDArray[np.int64], - n: int, - mutation_rate: float -) -> npt.NDArray[np.int64]: -``` - -Generates a set of mutated clones from a permutation vector. - -This function creates `n` clones of the input permutation vector and applies random mutations to each one, simulating clonal expansion in artificial immune systems with discrete permutations. Each clone receives a random number of swaps according to the mutation rate. - -### Parameters - -* `vector` (`npt.NDArray[np.int64]`): The original immune cell with permutation values to be cloned and mutated. -* `n` (`int`): Number of mutated clones to be generated. -* `mutation_rate` (`float`): Probability of mutating each component (0 <= mutation_rate < 1). - -### Returns - -* `clone_set` (`npt.NDArray[np.int64]`): Array with shape `(n, len(vector))` containing the `n` mutated clones of the original vector. - ---- diff --git a/docs/en/advanced-guides/base/immune/populations.md b/docs/en/advanced-guides/base/immune/populations.md deleted file mode 100644 index cef96a2..0000000 --- a/docs/en/advanced-guides/base/immune/populations.md +++ /dev/null @@ -1,31 +0,0 @@ -# Populations Module - -Utility functions for generating antibody populations in immunological algorithms. - -## generate_random_antibodies(...) - -```python -def generate_random_antibodies( - n_samples: int, - n_features: int, - feature_type: FeatureTypeAll = "continuous-features", - bounds: Optional[npt.NDArray[np.float64]] = None -) -> npt.NDArray -``` - -Generate a random antibody population. - -### Parameters - -* **n_samples** (`int`): Number of antibodies (samples) to generate. -* **n_features** (`int`): Number of features (dimensions) for each antibody. -* **feature_type** (`FeatureTypeAll`, default="continuous-features"): Specifies the type of features: "continuous-features", "binary-features", "ranged-features", or "permutation-features". -* **bounds** (`Optional[npt.NDArray[np.float64]]`): Array (n_features, 2) with min and max per dimension. - -### Returns - -* **npt.NDArray**: Array of shape (n_samples, n_features) containing the generated antibodies. - -### Raises - -* **ValueError**: If the number of features is less than or equal to zero. \ No newline at end of file diff --git a/docs/en/advanced-guides/base/optimizer.md b/docs/en/advanced-guides/base/optimizer.md deleted file mode 100644 index e464942..0000000 --- a/docs/en/advanced-guides/base/optimizer.md +++ /dev/null @@ -1,161 +0,0 @@ -Base class for optimization algorithms. - -# BaseOptimizer - -This class defines the core interface for optimization strategies and -keeps track of the cost history, evaluated solutions, and the best solution found. Subclasses must implement -``optimize`` and ``affinity_function``. - ---- - -## Properties - -### Property `cost_history` - -```python -@property -def cost_history(self) -> List[float] -``` - -Returns the history of costs during optimization. - ---- - -### Property `solution_history` - -```python -@property -def solution_history(self) -> List -``` - -Returns the history of evaluated solutions. - ---- - -### Property `best_solution` - -```python -@property -def best_solution(self) -> Optional[Any] -``` - -Returns the best solution found so far, or `None` if unavailable. - ---- - -### Property `best_cost` - -```python -@property -def best_cost(self) -> Optional[float] -``` - -Returns the cost of the best solution found so far, or `None` if unavailable. - ---- - -## Methods - -### Method `_record_best(...)` - -```python -def _record_best(self, cost: float, best_solution: Any) -> None -``` - -Record a new cost value and update the best solution if improved. - -**Parameters**: - -* ***cost***: `float` - Cost value to be added to the history. - ---- - -### Method `get_report()` - -```python -def get_report(self) -> str -``` - -Generate a formatted summary report of the optimization process. The report includes the best solution, -its associated cost, and the evolution of cost values per iteration. - -**Returns**: - -* **report**: `str` - A formatted string containing the optimization summary. - ---- - -### Method `register(...)` - -```python -def register(self, alias: str, function: Callable[..., Any]) -> None -``` - -Register a function dynamically in the optimizer instance. - -**Parameters**: - -* ***alias***: `str` - Name used to access the function as an attribute. -* ***function***: `Callable[..., Any]` - Callable to be registered. - -**Raises**: - -* **TypeError**: If `function` is not callable. -* **AttributeError**: If `alias` is protected and cannot be modified, or if `alias` does not exist in the - optimizer class. - ---- - -### Method `reset()` - -```python -def reset(self) -``` - -Reset the object's internal state, clearing history and resetting values. - ---- - -### Abstract methods - -#### Method `optimize(...)` - -```python -@abstractmethod -def optimize( - self, - max_iters: int = 50, - n_iter_no_change: int = 10, - verbose: bool = True -) -> Any: -``` - -Execute the optimization process. This method must be implemented by the subclass to define how the optimization strategy explores the search space. - -**Parameters**: - -* ***max_iters***: `int` - Maximum number of iterations. -* ***n_iter_no_change***: `int`, default=10 - The maximum number of iterations without updating the best solution. -* ***verbose***: `bool`, default=True - Flag to enable or disable detailed output during optimization. - -**Returns**: - -* **best_solution**: `Any` - The best solution found by the optimization algorithm. - ---- - -#### Method `affinity_function(...)` - -```python -def affinity_function(self, solution: Any) -> float -``` - -Evaluate the affinity of a candidate solution. This method must be implemented by the subclass to define the problem-specific. - -**Parameters**: - -* ***solution***: `Any` - Candidate solution to be evaluated. - -**Returns**: - -* **cost**: `float` - Cost value associated with the given solution. From 70e195b5c2efdb07548f1c247691a8360358da3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Tue, 3 Mar 2026 15:47:58 -0300 Subject: [PATCH 13/40] docs(csa): adds API documentation for clonalg --- aisp/csa/_clonalg.py | 4 +- docs/en/api/csa/airs.md | 2 +- docs/en/api/csa/clonalg.md | 162 +++++++++++++++++++++++++++++++++++++ 3 files changed, 165 insertions(+), 3 deletions(-) create mode 100644 docs/en/api/csa/clonalg.md diff --git a/aisp/csa/_clonalg.py b/aisp/csa/_clonalg.py index f54284d..1c4d68f 100644 --- a/aisp/csa/_clonalg.py +++ b/aisp/csa/_clonalg.py @@ -38,7 +38,7 @@ class Clonalg(BaseOptimizer): Dimension of the problem to be minimized. N : int, default=50 Number of memory cells (antibodies) in the population. - rate_clonal : float, default=10 + rate_clonal : int, default=10 Maximum number of possible clones of a cell. This value is multiplied by cell_affinity to determine the number of clones. rate_hypermutation : float, default=1.0 @@ -182,7 +182,7 @@ def optimize( max_iters : int, default=50 Maximum number of iterations when searching for the best solution using clonalg. n_iter_no_change: int, default=10 - The maximum number of iterations without updating the best cell + The maximum number of iterations without updating the best cell. verbose : bool, default=True Feedback on iterations, indicating the best antibody. diff --git a/docs/en/api/csa/airs.md b/docs/en/api/csa/airs.md index fe25de7..af32f99 100644 --- a/docs/en/api/csa/airs.md +++ b/docs/en/api/csa/airs.md @@ -157,7 +157,7 @@ using the k-nearest neighbors approach. **Returns** -C `npt.NDArray` - An ndarray of the form ``C`` (``n_samples``), containing the predicted classes for ``X``. +**C** : `npt.NDArray` - An ndarray of the form ``C`` (``n_samples``), containing the predicted classes for ``X``. --- diff --git a/docs/en/api/csa/clonalg.md b/docs/en/api/csa/clonalg.md new file mode 100644 index 0000000..8992856 --- /dev/null +++ b/docs/en/api/csa/clonalg.md @@ -0,0 +1,162 @@ +--- +id: clonalg +sidebar_label: Clonalg +keywords: + - key +--- + +# Clonalg + +Clonal Selection Algorithm (CLONALG). + +:::tip[Inheritance] + +This class extends [BaseOptimizer](../base/base-optimizer.md) + +::: + + +> **Module:** `aisp.csa` +> **Import:** `from aisp.csa import Clonalg` + +--- + +## Overview + +The Clonal Selection Algorithm (CSA) is an optimization algorithm inspired by the biological +process of clonal selection and expansion of antibodies in the immune system [^1]. This +implementation of CLONALG has been adapted for the minimization or maximization of cost +functions in binary, continuous, ranged-value, and permutation problems. + +:::note + +This CLONALG implementation contains some changes based on the AISP context, for general +application to various problems, which may produce results different from the standard or +specific implementation. This adaptation aims to generalize CLONALG to minimization and +maximization tasks, in addition to supporting continuous, discrete, and permutation problems. + +::: + +--- + +## Example + +```python +import numpy as np +from aisp.csa import Clonalg +# Search space limits +bounds = {'low': -5.12, 'high': 5.12} +# Objective function +def rastrigin_fitness(x): + x = np.clip(x, bounds['low'], bounds['high']) + return 10 * len(x) + np.sum(x**2 - 10 * np.cos(2 * np.pi * x)) +# CLONALG Instance +clonalg = Clonalg(problem_size=2, bounds=bounds, seed=1) +clonalg.register('affinity_function', rastrigin_fitness) +population = clonalg.optimize(100, 50, False) +print('Best cost:', abs(clonalg.best_cost)) +``` +**Output:** +```bash +Best cost: 0.02623036956750724 +``` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|-------------------------|----------------------------------------|:-------------------:|------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `problem_size` | `int` | - | Dimension of the problem to be minimized. | +| `N` | `int` | `50` | Number of memory cells (antibodies) in the population. | +| `rate_clonal` | `int` | `10` | Maximum number of possible clones of a cell. This value is multiplied by cell_affinity to determine the number of clones. | +| `rate_hypermutation` | `float` | `1.0` | Hypermutation rate controls the intensity of mutations during clonal expansion. Higher values decrease mutation intensity, while lower values increase it. | +| `n_diversity_injection` | `int` | `5` | Number of new random memory cells injected to maintain diversity. | +| `selection_size` | `int` | `5` | Number of the best antibodies selected for cloning. | +| `affinity_function` | `Optional[Callable[..., npt.NDArray]]` | `None` | Objective function to evaluate candidate solutions in minimizing the problem. | +| `feature_type` | `FeatureTypeAll` | `'ranged-features'` | Type of problem samples: binary, continuous, or based on value ranges. | +| `bounds` | `Optional[Dict]` | `None` | Definition of search limits when ``feature_type='ranged-features'``. | +| `mode` | `{"min", "max"}` | `'min'` | Defines whether the algorithm minimizes or maximizes the cost function. | +| `seed` | `int` | `None` | Seed for random generation of detector values. If None, the value is random. | + +## Attributes + +| Name | Type | Default | Description | +|--------------|----------------------------|:-------:|--------------------------| +| `population` | `Optional[List[Antibody]]` | `None` | Population of antibodies | + +--- + +## Public Methods + +### optimize + +```python +def optimize( + self, max_iters: int = 50, n_iter_no_change=10, verbose: bool = True +) -> List[Antibody]: + ... +``` + +Execute the optimization process and return the population. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|--------|:-------:|----------------------------------------------------------------------------------| +| `max_iters` | `int` | `50` | Maximum number of iterations when searching for the best solution using clonalg. | +| `n_iter_no_change` | `int` | `10` | The maximum number of iterations without updating the best cell. | +| `verbose` | `bool` | `True` | Feedback on iterations, indicating the best antibody. | + +**Raises** + +* `NotImplementedError` - If no affinity function has been provided to model. + +**Returns** + +**population** : `List[Antibody]` - Antibody population after clonal expansion. + +--- + +### affinity_function + +```python +def affinity_function(self, solution: npt.NDArray) -> np.float64: + ... +``` + +Evaluate the affinity of a candidate cell. + +**Parameters** + +| Name | Type | Default | Description | +|------------|---------------|:-------:|---------------------------------| +| `solution` | `npt.NDArray` | - | Candidate solution to evaluate. | + +**Raises** + +* `NotImplementedError` - If no affinity function has been provided. + +**Returns** + +**affinity** : `np.float64` - Affinity value associated with the given cell. + +--- + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + +- [**Knapsack Problem Example**](../../../../examples/en/optimization/clonalg/knapsack_problem_example.ipynb) +- [**Rastrigin Function Example**](../../../../examples/en/optimization/clonalg/rastrigin_function_example.ipynb) +- [**Tsp Problem Example**](../../../../examples/en/optimization/clonalg/tsp_problem_example.ipynb) + + + +--- + +## References + +[^1]: BROWNLEE, Jason. Clonal Selection Algorithm. Clever Algorithms: Nature-inspired + Programming Recipes., 2011. Available at: + https://cleveralgorithms.com/nature-inspired/immune/clonal_selection_algorithm.html From 19b2332fff8f03b1080320b5a7f4eee8e13459f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Tue, 3 Mar 2026 16:36:19 -0300 Subject: [PATCH 14/40] docs(csa): adds API documentation for AiNet --- docs/en/api/csa/clonalg.md | 16 +-- docs/en/api/ina/ai-net.md | 208 +++++++++++++++++++++++++++++++++++++ 2 files changed, 217 insertions(+), 7 deletions(-) create mode 100644 docs/en/api/ina/ai-net.md diff --git a/docs/en/api/csa/clonalg.md b/docs/en/api/csa/clonalg.md index 8992856..f38b291 100644 --- a/docs/en/api/csa/clonalg.md +++ b/docs/en/api/csa/clonalg.md @@ -2,7 +2,11 @@ id: clonalg sidebar_label: Clonalg keywords: - - key + - optimization + - clonal selection + - clonalg + - antibody population + - objective function --- # Clonalg @@ -102,11 +106,11 @@ Execute the optimization process and return the population. **Parameters** -| Name | Type | Default | Description | -|-----------|--------|:-------:|----------------------------------------------------------------------------------| -| `max_iters` | `int` | `50` | Maximum number of iterations when searching for the best solution using clonalg. | +| Name | Type | Default | Description | +|--------------------|--------|:-------:|----------------------------------------------------------------------------------| +| `max_iters` | `int` | `50` | Maximum number of iterations when searching for the best solution using clonalg. | | `n_iter_no_change` | `int` | `10` | The maximum number of iterations without updating the best cell. | -| `verbose` | `bool` | `True` | Feedback on iterations, indicating the best antibody. | +| `verbose` | `bool` | `True` | Feedback on iterations, indicating the best antibody. | **Raises** @@ -151,8 +155,6 @@ Complete usage examples are available in the Jupyter Notebooks: - [**Rastrigin Function Example**](../../../../examples/en/optimization/clonalg/rastrigin_function_example.ipynb) - [**Tsp Problem Example**](../../../../examples/en/optimization/clonalg/tsp_problem_example.ipynb) - - --- ## References diff --git a/docs/en/api/ina/ai-net.md b/docs/en/api/ina/ai-net.md new file mode 100644 index 0000000..83e0b1a --- /dev/null +++ b/docs/en/api/ina/ai-net.md @@ -0,0 +1,208 @@ +--- +id: ai-net +sidebar_label: AiNet +keywords: + - immune network + - clustering + - data compression + - unsupervised learning + - Minimum Spanning Tree +--- + +# AiNet + +Artificial Immune Network (AiNet) for Compression and Clustering. + +:::tip[Inheritance] + +This class extends [BaseClusterer](../base/base-clusterer.md). + +::: + + +> **Module:** `aisp.ina` +> **Import:** `from aisp.ina import AiNet` + +--- + +## Overview + +This class implements the aiNet algorithm, an artificial immune network model designed for +clustering and data compression tasks. The aiNet algorithm uses principles from immune +network theory, clonal selection, and affinity maturation to compress high-dimensional +datasets [^1]. +For clustering, the class uses SciPy's implementation of the **Minimum Spanning Tree** +(MST) to remove the most distant nodes and separate the groups [^2]. + +--- + +## Example + +```python +import numpy as np +from aisp.ina import AiNet + +np.random.seed(1) +# Generating training data +a = np.random.uniform(high=0.4, size=(50, 2)) +b = np.random.uniform(low=0.6, size=(50, 2)) +x_train = np.vstack((a, b)) +# AiNet Instance +ai_net = AiNet( + N=150, + mst_inconsistency_factor=1, + seed=1, + affinity_threshold=0.85, + suppression_threshold=0.7 +) +ai_net = ai_net.fit(x_train, verbose=True) +x_test = [ + [0.15, 0.45], # Expected: label 0 + [0.85, 0.65], # Esperado: label 1 +] +y_pred = ai_net.predict(x_test) +print(y_pred) +``` +**Output** +```bash +[0 1] +``` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|----------------------------|-----------------|:-------------:|--------------------------------------------------------------------------------------------------------------------------------------------| +| `N` | `int` | `50` | Number of memory cells (antibodies) in the population. | +| `n_clone` | `int` | `10` | Number of clones generated for each selected memory cell. | +| `top_clonal_memory_size` | `int` | `5` | Number of highest-affinity antibodies selected per antigen for cloning and mutation. | +| `n_diversity_injection` | `int` | `5` | Number of new random memory cells injected to maintain diversity. | +| `affinity_threshold` | `float` | `0.5` | Threshold for affinity (similarity) to determine cell suppression or selection. | +| `suppression_threshold` | `float` | `0.5` | Threshold for suppressing similar memory cells | +| `mst_inconsistency_factor` | `float` | `2.0` | Factor used to determine which edges in the **Minimum Spanning Tree (MST)** are considered inconsistent. | +| `max_iterations` | `int` | `10` | Maximum number of training iterations. | +| `k` | `int` | `3` | The number of K nearest neighbors that will be used to choose a label in the prediction. | +| `metric` | `MetricType` | `"euclidean"` | Distance metric used to compute similarity between memory cells | +| `seed` | `Optional[int]` | `None` | Seed for the random generation of detector values. Defaults to None. | +| `use_mst_clustering` | `bool` | `True` | If ``True``, performs clustering with **Minimum Spanning Tree** (MST). If ``False``, does not perform clustering and predict returns None. | +| `p` | `float` | `2.0` | This parameter stores the value of ``p`` used in the Minkowski distance. | + +## Attributes + +| Name | Type | Default | Description | +|-------------------------|-------------------------|:-------:|------------------------------------------------------------------------------------| +| `memory_network` | `Dict[int, List[Cell]]` | - | The immune network representing clusters. | +| `population_antibodies` | `Optional[npt.NDArray]` | - | The set of memory antibodies. | +| `mst` | `dict` | - | The Minimum Spanning Tree and its statistics (graph, mean_distance, std_distance). | + +--- + +## Public Methods + +### fit + +```python +def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> AiNet: + ... +``` + +Train the AiNet model on input data. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Input data used for training the model. | +| `verbose` | `bool` | `True` | Feedback from the progress bar showing current training interaction details. | + +**Raises** + +* `TypeError` - If X is not a ndarray or list. +* `UnsupportedTypeError` - If the data type of the vector is not supported. + +**Returns** + +`AiNet` - Returns the instance of the class that implements this method. + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Predict cluster labels for input data. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|------------------| +| `X` | `Union[npt.NDArray, list]` | - | Data to predict. | + +**Raises** + +* `TypeError` - If X is not a ndarray or list. +* `ValueError` - If the array contains values other than 0 and 1. +* `FeatureDimensionMismatch` - If the number of features in X does not match the expected number. +* `ModelNotFittedError` - If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions + +**Returns** + +**predictions** : `npt.NDArray` - Predicted cluster labels, or None if clustering is disabled. + +--- + +### update_clusters + +```python +def update_clusters(self, mst_inconsistency_factor: Optional[float] = None): + ... +``` +Partition the clusters based on the MST inconsistency factor. + +Uses the precomputed Minimum Spanning Tree (MST) of the antibody population +to redefine clusters. Edges whose weights exceed the mean plus the +`mst_inconsistency_factor` multiplied by the standard deviation of MST edge +weights are removed. Each connected component after pruning is treated as a +distinct cluster. + +**Parameters** + +| Name | Type | Default | Description | +|----------------------------|---------|:-------:|----------------------------------------------------------| +| `mst_inconsistency_factor` | `float` | `None` | If provided, overrides the current inconsistency factor. | + +**Raises** + +* `ValueError` + * If the Minimum Spanning Tree (MST) has not yet been created + * If Population of antibodies is empty + * If MST statistics (mean or std) are not available. + +**Updates** + +* **memory_network** : `dict[int, npt.NDArray]` - + Dictionary mapping cluster labels to antibody arrays. +* **labels** : `list` - List of cluster labels. + +--- + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + +- [**Random Example**](../../../../examples/en/clustering/AiNet/example_with_randomly_generated_dataset.ipynb) +- [**Geyser Dataset Example**](../../../../examples/en/clustering/AiNet/geyser_dataBase_example.ipynb) + +--- + +## References + +[^1]: De Castro, Leandro & José, Fernando & von Zuben, Antonio Augusto. (2001). aiNet: An Artificial Immune Network for Data Analysis. + Available at: https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis + +[^2]: SciPy Documentation. *Minimum Spanning Tree*. + https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree From a93fd2df2dfa64dc4d0bb27634d1dc81ae06462c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Tue, 3 Mar 2026 17:08:17 -0300 Subject: [PATCH 15/40] docs(csa): adds API documentation Readme for csa and ina. --- docs/en/api/csa/README.md | 33 +++ docs/en/api/ina/README.md | 31 ++ .../Clonal Selection Algorithms/AIRS.md | 266 ----------------- .../Clonal Selection Algorithms/Clonalg.md | 183 ------------ .../Clonal Selection Algorithms/README.md | 24 -- .../Network Theory Algorithms/AiNet.md | 271 ------------------ .../Network Theory Algorithms/README.md | 15 - 7 files changed, 64 insertions(+), 759 deletions(-) create mode 100644 docs/en/api/csa/README.md create mode 100644 docs/en/api/ina/README.md delete mode 100644 docs/en/classes/Clonal Selection Algorithms/AIRS.md delete mode 100644 docs/en/classes/Clonal Selection Algorithms/Clonalg.md delete mode 100644 docs/en/classes/Clonal Selection Algorithms/README.md delete mode 100644 docs/en/classes/Network Theory Algorithms/AiNet.md delete mode 100644 docs/en/classes/Network Theory Algorithms/README.md diff --git a/docs/en/api/csa/README.md b/docs/en/api/csa/README.md new file mode 100644 index 0000000..e2872ed --- /dev/null +++ b/docs/en/api/csa/README.md @@ -0,0 +1,33 @@ +--- +id: csa +sidebar_label: aisp.csa +keywords: + - immune + - clonal selection + - clonalg + - airsv2 + - antibody proliferation + - mutations + - clonal selection algorithm + - artificial immune systems + - classification + - optimization +--- + +# aisp.csa + +Module (CSA) Clonal Selection Algorithm. + +> **Module:** `aisp.csa` + +## Overview + +CSAs are inspired by the process of antibody proliferation upon detecting an antigen, during which +the generated antibodies undergo mutations in an attempt to enhance pathogen recognition. + +## Classes + +| Class | Description | +|---------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [`AIRS`](./airs.md) | A supervised learning algorithm for classification tasks based on the clonal selection principle. | +| [`Clonalg`](./clonalg.md) | Implementation of the clonal selection algorithm for optimization, adapted for both minimization and maximization of cost functions in binary, continuous, and permutation problems. | diff --git a/docs/en/api/ina/README.md b/docs/en/api/ina/README.md new file mode 100644 index 0000000..59c20b7 --- /dev/null +++ b/docs/en/api/ina/README.md @@ -0,0 +1,31 @@ +--- +id: ina +sidebar_label: aisp.ina +keywords: + - immune + - clonal selection + - immune networks + - ainet + - opt-ainet + - mutations + - clonal selection + - artificial immune systems + - clustering + - optimization +--- + +# aisp.ina + +Module (ina) Immune Network Algorithm. + +> **Module:** `aisp.ina` + +## Overview + +This module implements algorithms based on Network Theory Algorithms proposed by Jerne. + +## Classes + +| Class | Description | +|------------------------|--------------------------------------------------------------------------------------------| +| [`AiNet`](./ai-net.md) | An unsupervised learning algorithm for clustering, based on the theory of immune networks. | diff --git a/docs/en/classes/Clonal Selection Algorithms/AIRS.md b/docs/en/classes/Clonal Selection Algorithms/AIRS.md deleted file mode 100644 index da7a6d8..0000000 --- a/docs/en/classes/Clonal Selection Algorithms/AIRS.md +++ /dev/null @@ -1,266 +0,0 @@ -# AIRS (Artificial Immune Recognition System) - -This class extends the [**Base**](../../advanced-guides/base/classifier.md) class. - -## AIRS Constructor - -The ``AIRS`` class aims to perform classification using metaphors of selection and clonal expansion. - -This implementation is inspired by AIRS2, a simplified version of the original AIRS algorithm. -Introducing adaptations to handle continuous and binary datasets. - -Based on Algorithm 16.5 from Brabazon et al. [1](#ref1). - -Related and noteworthy works: access here [2](#ref2). - -### Attributes - -* **n_resources** (``float``): Total amount of available resources. Defaults to 10. -* **rate_clonal** (``float``): Maximum number of possible clones of a class. This quantity is multiplied by (cell stimulus * rate_hypermutation) to define the number of clones. Defaults to 10. -* **rate_mc_init** (``float``): Percentage of samples used to initialize memory cells. Defaults to 0.2. -* **rate_hypermutation** (``float``): The rate of mutated clones derived from rate_clonal as a scalar factor. Defaults to 0.75. -* **affinity_threshold_scalar** (``float``): Normalized affinity threshold. Defaults to 0.75. -* **k** (``int``): The number of K nearest neighbors that will be used to choose a label in the prediction. Defaults to 3. -* **max_iters** (``int``): Maximum number of iterations in the refinement process of the ARB set exposed to aᵢ. Defaults to 100. -* **resource_amplified** (``float``): Resource consumption amplifier is multiplied with the incentive to subtract resources. Defaults to 1.0 without amplification. -* **metric** (`Literal["manhattan", "minkowski", "euclidean"]`): Way to calculate the distance between the detector and the sample: - * ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: - √( (x₁ - x₂)² + (y₁ - y₂)² + ... + (yn - yn)²). - * ``'minkowski'`` ➜ The calculation of the distance is given by the expression: - ( |X₁ - Y₁|p + |X₂ - Y₂|p + ... + |Xn - Yn|p) ¹/ₚ. - * ``'manhattan'`` ➜ The calculation of the distance is given by the expression: - ( |x₁ - x₂| + |y₁ - y₂| + ... + |yn - yn|). - Defaults to "Euclidean". - -* **seed** (int): Seed for the random generation of detector values. Defaults to None. - -* ``**kwargs``: - * **p** (``float``): This parameter stores the value of ``p`` used in the Minkowski distance. - The default is ``2``, which means normalized Euclidean distance. Different values of p lead to different variants of the Minkowski distance. [Learn more](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.minkowski.html). - -**Other initialized variables:** - -* **cells_memory** (``Optional[Dict[str, list[BCell]]]``): This variable stores a list of memory cells by class. -* **affinity_threshold** (``float``): Defines the affinity threshold between antigens. -* **classes** (``Optional[npt.NDArray]``): List of output classes. - ---- - -## Public Methods - -### Method `fit(...)` - -The ``fit(...)`` function generates detectors for the non-owners relative to the samples: - -```python -def fit( - self, - X: Union[npt.NDArray, list], - y: Union[npt.NDArray, list], - verbose: bool = True, -) -> AIRS: -``` - -It performs the training according to ``X`` and ``y``, using the method Artificial Immune Recognition System (``AIRS``). - -****Parameters:**** - -* **X** (``Union[npt.NDArray, list]``): Array with sample features, with **N** samples (rows) and **N** features (columns), normalized to values between [0, 1]. -* **y** (``Union[npt.NDArray, list]``): Array with output classes corresponding to **N** samples related to ``X``. -* **verbose** (``bool``): Boolean, default ``True``, determines if the feedback from the detector generation will be printed. - -*Returns the class instance.* - ---- - -### Method `predict(...)` - -The ``predict(...)`` function performs class prediction using the generated detectors: - -```python -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -**Parameters:** - -* **X** (``Union[npt.NDArray, list]``): Array with the features for prediction, with **N** samples (rows) and **N** columns. - -**Raises** - -* `TypeError` - If X is not a ndarray or list. -* `FeatureDimensionMismatch` - If the number of features in X does not match the expected number. -* `ModelNotFittedError` - If the mode has not yet been adjusted and does not have defined memory cells, it is - not able to predictions - -**Returns:** - -* **C**: An array of predictions with the output classes for the given features. - ---- - -### Method `score(...)` - -The ``score(...)`` function calculates the accuracy of the trained model by making predictions and calculating the accuracy. - -```python -def score(self, X: npt.NDArray, y: list) -> float: -``` - -Returns accuracy as a ``float``. - ---- - -## Private Methods - -### Method `_refinement_arb(...)` - -The function "_refinement_arb(...)" refines the ARB set until the average stimulation value exceeds the defined threshold (``affinity_threshold_scalar``). - -```python -def _refinement_arb( - self, - ai: npt.NDArray, - c_match_stimulation: float, - arb_list: List[_ARB] -) -> _ARB: -``` - -**Parameters:** - -* **ai** (`npt.NDArray`): The current antigen. -* **c_match_stimulation** (``float``): The highest stimulation relative to aᵢ -* **arb_list** (``List[_ARB]``): ARB set. - -Returns the cell (_ARB) with the highest ARB stimulation. - ---- - -### Method `_cells_affinity_threshold(...)` - -The function "_cells_affinity_threshold(...)" calculates the affinity threshold based on the average affinity between training instances, where aᵢ and aⱼ are a pair of antigens, and affinity is measured by distance (Euclidean, Manhattan, Minkowski, Hamming). - -```python -def _cells_affinity_threshold(self, antigens_list: npt.NDArray): -``` - -**Following the formula:** - -$$ -\text{affinity}_{\text{threshold}} = \frac{ -\sum_{i=1}^{n-1} \sum_{j=i+1}^{n} \text{affinity}(a_i, a_j)}{n(n-1)/2} -$$ - -**Parameters:** - -* **antigens_list** (``npt.NDArray``): List of training antigens. - ---- - -### Method `_affinity(...)` - -The function "_affinity(...)" calculates the stimulus between two vectors using metrics. - -```python -def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float: -``` - -**Parameters:** - -* **u** (``npt.NDArray``): Coordinates of the first point. -* **v** (``npt.NDArray``): Coordinates of the second point. - -Returns the stimulus rate between the vectors. - ---- - -### Method `_init_memory_c(...)` - -The function "_init_memory_c(...)" initializes memory cells by randomly selecting `n_antigens_selected` from the list of training antigens. - -```python -def _init_memory_c(self, antigens_list: npt.NDArray) -> List[BCell]: -``` - -**Parameters:** - -* **antigens_list** (``npt.NDArray``): List of training antigens. - ---- - -### Method `_slice_index_list_by_class(...)` - -The function ``_slice_index_list_by_class(...)`` separates the indices of the rows according to the output class, to iterate over the sample array, only at the positions where the output corresponds to the class being trained: - -```python -def _slice_index_list_by_class(self, y: npt.NDArray) -> dict: -``` - -Returns a dictionary with classes as keys and indices in ``X`` of the samples. - ---- - -### Method `__prepare_features(...)` - -The function ``__prepare_features(...)`` check the samples, specifying the type, quantity of characteristics, and other parameters. - -```python -def _prepare_features(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -* This method updates the following attributes: - * ``self._feature_type`` - * ``self.metric`` (only for binary features) - * ``self._bounds`` (only for ranged features) - * ``self._n_features`` - - -**Parameters:** - -* **X** (``Union[npt.NDArray, list]``): Array with the features for prediction, with **N** samples (rows) and **N** columns. - -Returns the processed input data. - ---- - -# Auxiliary Classes - ---- - -## _ARB Class (Inherits from [BCell](../../advanced-guides/base/immune/cell.md#bcell)) - -### Constructor - -**Parameters:** - -* vector (``npt.NDArray``): A feature vector of the cell. Defaults to None. - ---- - -### Method `consume_resource(...)` - -**Parameters:** - -* **n_resource** (```float```) : The initial amount of resources. -* **amplified** (``float``): Amplifier for resource consumption by the cell. It is multiplied by the cell's stimulus. The default value is 1. - -```python -def consume_resource(self, n_resource: float, amplified: float = 1) -> float: -``` - -Returns the remaining amount of resources after consumption. - ---- - -# References - -
- -> 1. BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: . - -
- -> 2. AZZOUG, Aghiles. Artificial Immune Recognition System V2. - Available at: diff --git a/docs/en/classes/Clonal Selection Algorithms/Clonalg.md b/docs/en/classes/Clonal Selection Algorithms/Clonalg.md deleted file mode 100644 index 2d9a063..0000000 --- a/docs/en/classes/Clonal Selection Algorithms/Clonalg.md +++ /dev/null @@ -1,183 +0,0 @@ -# Clonal Selection Algorithm (CLONALG) - -## Clonalg - -The `Clonalg` class is an **optimization algorithm** inspired by the biological process of clonal selection in the -immune system. This implementation is designed for minimizing or maximizing cost functions in various problem types, -including binary, continuous, ranged-value, and permutation problems. - -The CLONALG implementation was inspired by the description presented in [1](#ref1). - -This CLONALG implementation contains some changes based on the AISP context, for general -application to various problems, which may produce results different from the standard or -specific implementation. This adaptation aims to generalize CLONALG to minimization and -maximization tasks, in addition to supporting continuous, discrete, and permutation problems. - ---- - -### Constructor - -The constructor initializes the CLONALG instance with key parameters that define the optimization process. - -**Attributes:** - -* **problem_size** (`int`): The dimension of the problem to be optimized. -* **N** (`int`, default=50): The number of memory cells (antibodies) in the population. -* **rate_clonal** (`float`, default=10): The maximum number of possible clones of a cell. This value is multiplied by the cell's affinity to determine the number of clones. -* **rate_hypermutation** (`float`, default=1.0): The rate of mutated clones, used as a scalar factor. -* **n_diversity_injection** (`int`, default=5): The number of new random memory cells injected to maintain diversity. -* **selection_size** (`int`, default=5): The number of best antibodies selected for cloning. -* **affinity_function** (`Optional[Callable[..., npt.NDArray]]`, default=None): The objective function used to evaluate candidate solutions. -* **feature_type** (`FeatureTypeAll`, default='ranged-features'): The type of problem samples, which can be `'continuous-features'`, `'binary-features'`, `'ranged-features'`, or `'permutation-features'`. -* **bounds** (`Optional[Dict]`, default=None): A dictionary defining the search limits for `'ranged-features'` problems. Can be a single fixed range or a list of ranges for each dimension. -* **mode** (`Literal["min", "max"]`, default="min"): Specifies whether the algorithm minimizes or maximizes the cost function. -* **seed** (`Optional[int]`, default=None): A seed for random number generation. - ---- - -### Public Methods - -#### Method `optimize(...)` - -```python -def optimize( - self, - max_iters: int = 50, - n_iter_no_change=10, - verbose: bool = True -) -> List[Antibody]: -``` - -This method execute the optimization process and return the population. - -**Parameters:** - -* **max_iters** (`int`, default=50): The maximum number of iterations. -* **n_iter_no_change** (`int`, default=10): The maximum number of iterations without an improvement in the best solution. -* **verbose** (`bool`, default=True): A flag to enable or disable detailed output during the optimization process. - -**Returns:** - -* `List[Antibody]`: The best antibody population after clonal expansion. - ---- - -#### Method `affinity_function(...)` - -```python -def affinity_function(self, solution: npt.NDArray) -> np.float64: -``` - -This method evaluates the affinity of a candidate solution. It raises a `NotImplementedError` if no affinity function has been provided to the class instance. - -**Parameters:** - -* **solution** (`npt.NDArray`): The candidate solution to be evaluated. - -**Returns:** - -* `np.float64`: The affinity value associated with the solution. - ---- - -### Private Methods - -#### Method `_select_top_antibodies(...)` - -```python -def _select_top_antibodies(self, n: int, antibodies: list[Antibody]) -> list[Antibody]: -``` - -This method selects the top `n` antibodies based on their affinity scores, according to the `mode` (`'min'` or `'max'`). - -**Parameters:** - -* **n** (`int`): The number of antibodies to select. -* **antibodies** (`list[Antibody]`): A list of tuples, where each tuple represents an antibody and its associated score. - -**Returns:** - -* `list[Antibody]`: A list containing the `n` selected antibodies. - ---- - -#### Method `_init_population_antibodies(...)` - -```python -def _init_population_antibodies(self) -> npt.NDArray: -``` - -This method initializes the initial population of antibodies randomly. - -**Returns:** - -* `npt.NDArray`: A list of the initialized antibodies. - ---- - -#### Method `_diversity_introduction(...)` - -```python -def _diversity_introduction(self): -``` - -This method introduces new random antibodies into the population to maintain genetic diversity and help prevent premature convergence. - -**Returns:** - -* `npt.NDArray`: An array of new random antibodies. - ---- - -#### Method `_clone_and_mutate(...)` - -```python -def _clone_and_mutate( - self, - antibody: npt.NDArray, - n_clone: int, - rate_hypermutation: float -) -> npt.NDArray: -``` - -This method generates mutated clones from a single antibody. The mutation strategy depends on the `feature_type` specified during initialization (`'binary-features'`, `'continuous-features'`, `'ranged-features'`, or `'permutation-features'`). - -**Parameters:** - -* **antibody** (`npt.NDArray`): The original antibody vector to be cloned and mutated. -* **n_clone** (`int`): The number of clones to generate. -* **rate_hypermutation** (`float`): The hypermutation rate. - -**Returns:** - -* `npt.NDArray`: An array containing the mutated clones. - ---- - -#### Method `_clone_and_hypermutation(...)` - -```python -def _clone_and_hypermutation( - self, - population: list[Antibody] -) -> list[Antibody]: -``` - -This method clones and hypermutates a population of antibodies. It returns a list of all clones and their affinities with respect to the cost function. - -**Parameters:** - -* **population** (`list[Antibody]`): The list of antibodies to be evaluated and cloned. - -**Returns:** - -* `list[Antibody]`: A list of mutated clones. - ---- - -## References - -
- -> 1. BROWNLEE, Jason. Clonal Selection Algorithm. Clever Algorithms: Nature-inspired Programming Recipes., 2011. -> Available at: https://cleveralgorithms.com/nature-inspired/immune/clonal_selection_algorithm.html \ No newline at end of file diff --git a/docs/en/classes/Clonal Selection Algorithms/README.md b/docs/en/classes/Clonal Selection Algorithms/README.md deleted file mode 100644 index b68e78e..0000000 --- a/docs/en/classes/Clonal Selection Algorithms/README.md +++ /dev/null @@ -1,24 +0,0 @@ -# Clonal Selection Algorithm - -Clonal Selection Algorithms are inspired by the process of antibody proliferation upon detecting an antigen, during which -the generated antibodies undergo mutations in an attempt to enhance pathogen recognition. - -## classes - -1. **[Artificial Immune Recognition System (AIRS)](AIRS.md)** - -> The AIRS class aims to perform classification using metaphors of selection and clonal expansion. -> This implementation is inspired by AIRS2, a simplified version of the original AIRS algorithm. -> Introducing adaptations to handle continuous and binary datasets. - -2. **[Clonal Selection Algorithm (CLONALG)](Clonalg.md)** - -> Implementation of the clonal selection algorithm for optimization, adapted -> for both minimization and maximization of cost functions in binary, -> continuous, and permutation problems. - ---- - -### 1 -> -> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: . diff --git a/docs/en/classes/Network Theory Algorithms/AiNet.md b/docs/en/classes/Network Theory Algorithms/AiNet.md deleted file mode 100644 index 5973618..0000000 --- a/docs/en/classes/Network Theory Algorithms/AiNet.md +++ /dev/null @@ -1,271 +0,0 @@ -# AiNet (Artificial Immune Network) - -This class extends the [**Base**](../../advanced-guides/base/clusterer.md) class. - -## AiNet Constructor - -The ``AiNet`` class implements the Artificial Immune Network algorithm for **compression** and **clustering**. -It uses principles from immune network theory, clonal selection, and affinity maturation to compress datasets and find clusters. - -For clustering, it optionally uses a **Minimum Spanning Tree (MST)** to separate distant nodes into groups. - -**Attributes:** - -* **N** (``int``): Number of memory cells (antibodies) in the population. Defaults to 50. -* **n_clone** (``int``): Number of clones generated per selected memory cell. Defaults to 10. -* **top_clonal_memory_size** (``Optional[int]``): Number of highest-affinity antibodies selected for cloning. Defaults to 5. -* **n_diversity_injection** (``int``): Number of new random antibodies injected to maintain diversity. Defaults to 5. -* **affinity_threshold** (``float``): Threshold for cell selection/suppression. Defaults to 0.5. -* **suppression_threshold** (``float``): Threshold for removing similar memory cells. Defaults to 0.5. -* **mst_inconsistency_factor** (``float``): Factor to determine inconsistent MST edges. Defaults to 2.0. -* **max_iterations** (``int``): Maximum number of training iterations. Defaults to 10. -* **k** (``int``): Number of nearest neighbors used for label prediction. Defaults to 3. -* **metric** (Literal["manhattan", "minkowski", "euclidean"]): Way to calculate the distance between the detector and the sample: - * ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: - √( (x₁ - x₂)² + (y₁ - y₂)² + ... + (yn - yn)²). - * ``'minkowski'`` ➜ The calculation of the distance is given by the expression: - ( |X₁ - Y₁|p + |X₂ - Y₂|p + ... + |Xn - Yn|p) ¹/ₚ. - * ``'manhattan'`` ➜ The calculation of the distance is given by the expression: - ( |x₁ - x₂| + |y₁ - y₂| + ... + |yn - yn|). - Defaults to "Euclidean". - -* **seed** (``Optional[int]``): Seed for random number generation. Defaults to None. -* **use_mst_clustering** (``bool``): Whether to perform MST-based clustering. Defaults to True. -* **kwargs**: - * **p** (``float``): Parameter for Minkowski distance. Defaults to 2. - -**Other initialized variables:** - -* **_population_antibodies** (``Optional[npt.NDArray]``): Stores the current set of antibodies. -* **_memory_network** (``Dict[int, List[Cell]]``): Dictionary mapping clusters to antibodies. -* **_mst_structure** (``Optional[npt.NDArray]``): MST adjacency structure. -* **_mst_mean_distance** (``Optional[float]``): Mean of MST edge distances. -* **_mst_std_distance** (``Optional[float]``): Standard deviation of MST edge distances. -* **labels** (``Optional[npt.NDArray]``): List of cluster labels. - ---- - -## Public Methods - -### Method `fit(...)` - -Trains the AiNet model on input data: - -```python -def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> AiNet: -``` - -**Parameters:** - -* **X** (`Union[npt.NDArray, list]`): Array with input samples (rows) and features (columns). -* **verbose** (`bool`): Boolean, default True, enables progress feedback. - -**Raises** - -* `TypeError`: If X is not a ndarray or list. -* `UnsupportedTypeError`: If the data type of the vector is not supported. - -*Returns the class instance.* - ---- - -### Method `predict(...)` - -Predicts cluster labels for new samples: - -```python -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -**Parameters:** - -* **X** (`Union[npt.NDArray, list]`): Array of input features. - -**Raises** - -* `TypeError`: If X is not a ndarray or list. -* `ValueError`: If the array contains values other than 0 and 1. -* `FeatureDimensionMismatch`: If the number of features in X does not match the expected number. -* `ModelNotFittedError`: If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions - -**Returns:** - -* **Predictions**: Array of cluster labels, or None if clustering is disabled. - ---- - -### Method `update_clusters(...)` - -Partitions clusters using the MST: - -```python -def update_clusters(self, mst_inconsistency_factor: Optional[float] = None): -``` - -**Parameters:** - -* **mst_inconsistency_factor** (`Optional[float]`): Optional float to override the MST inconsistency factor. - -**Updates:** - -* **_memory_network**: Dictionary of cluster labels to antibody arrays. -* **labels**: List of cluster labels. - ---- - -## Private Methods - -### Method `_init_population_antibodies(...)` - -Initializes antibody population randomly. - -```python -def _init_population_antibodies(self) -> npt.NDArray: -``` - -**Returns:** Initialized antibodies (`npt.NDArray`). - ---- - -### Method `_select_and_clone_population(...)` - -Selects top antibodies and generates mutated clones: - -```python -def _select_and_clone_population(self, antigen: npt.NDArray, population: npt.NDArray) -> list: -``` - -**Parameters:** - -* **antigen** (`npt.NDArray`): Array representing the antigen to which affinities will be computed. -* **population** (`npt.NDArray`): Array of antibodies to be evaluated and cloned. - -**Returns:** List of mutated clones. - ---- - -### Method `_clonal_suppression(...)` - -Suppresses redundant clones based on thresholds: - -```python -def _clonal_suppression(self, antigen: npt.NDArray, clones: list): -``` - -**Parameters:** - -* **antigen** (`npt.NDArray`): Array representing the antigen. -* **clones** (`list`): List of candidate clones to be suppressed. - -**Returns:** List of non-redundant, high-affinity clones. - ---- - -### Method `_memory_suppression(...)` - -Removes redundant antibodies from memory pool: - -```python -def _memory_suppression(self, pool_memory: list) -> list: -``` - -**Parameters:** - -* **pool_memory** (`list`): List of antibodies currently in memory. - -**Returns:** Cleaned memory pool (`list`). - ---- - -### Method `_diversity_introduction(...)` - -Introduces new random antibodies: - -```python -def _diversity_introduction(self) -> npt.NDArray: -``` - -**Parameters:** None - -**Returns:** Array of new antibodies (`npt.NDArray`). - ---- - -### Method `_affinity(...)` - -Calculates stimulus between two vectors: - -```python -def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float: -``` - -**Parameters:** - -* **u** (`npt.NDArray`): Array representing the first point. -* **v** (`npt.NDArray`): Array representing the second point. - -**Returns:** Affinity score (`float`) in [0,1]. - ---- - -### Method `_calculate_affinities(...)` - -Calculates affinity matrix between reference and target vectors: - -```python -def _calculate_affinities(self, u: npt.NDArray, v: npt.NDArray) -> npt.NDArray: -``` - -**Parameters:** - -* **u** (`npt.NDArray`): Reference vector (`npt.NDArray`) of shape `(n_features,)`. -* **v** (`npt.NDArray`): Target vectors (`npt.NDArray`) of shape `(n_samples, n_features)`. - -**Returns:** Array of affinities (`npt.NDArray`) with shape `(n_samples,)`. - ---- - -### Method `_clone_and_mutate(...)` - -Generates mutated clones: - -```python -def _clone_and_mutate(self, antibody: npt.NDArray, n_clone: int) -> npt.NDArray: -``` - -**Parameters:** - -* **antibody** (`npt.NDArray`): Original antibody vector to clone and mutate. -* **n_clone** (`int`): Number of clones to generate. - -**Returns:** Array of mutated clones (`npt.NDArray`) of shape `(n_clone, len(antibody))`. - ---- - -### Method `_build_mst(...)` - -Constructs the MST and stores statistics. - -```python -def _build_mst(self): -``` - -**Parameters:** None - -**Raises:** ValueError if antibody population is empty. - -**Updates internal variables:** - -* **_mst_structure**: MST adjacency structure. -* **_mst_mean_distance**: Mean edge distance. -* **_mst_std_distance**: Standard deviation of MST edge distances. - ---- - -## References - -> 1. De Castro, Leandro & José, Fernando & von Zuben, Antonio Augusto. (2001). aiNet: An Artificial Immune Network for Data Analysis. -> Available at: [https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis](https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis) - -> 2. SciPy Documentation. *Minimum Spanning Tree*. -> Available at: [https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree) diff --git a/docs/en/classes/Network Theory Algorithms/README.md b/docs/en/classes/Network Theory Algorithms/README.md deleted file mode 100644 index 8171d83..0000000 --- a/docs/en/classes/Network Theory Algorithms/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# Immune Network Theory - -This technique was introduced by **Niels Jerne (1974)** and models the immune system as a dynamic network, -in which cells and molecules are capable of recognizing each other. - -## Classes - -1. **[AiNet](AiNet.md)** - -> Artificial Immune Network for unsupervised clustering and compression tasks. ---- - -## References - -> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. *Natural Computing Algorithms*. Springer Berlin Heidelberg, 2015. DOI: 10.1007/978-3-662-43631-8. Disponível em: [http://dx.doi.org/10.1007/978-3-662-43631-8](http://dx.doi.org/10.1007/978-3-662-43631-8). From 4da5c68f9e90d50f6f80d564365140dc8a804a4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Tue, 3 Mar 2026 18:31:22 -0300 Subject: [PATCH 16/40] docs(csa): adds API documentation for nsa module --- docs/en/api/nsa/README.md | 35 +++ docs/en/api/nsa/bnsa.md | 177 +++++++++++++++ docs/en/api/nsa/rnsa.md | 206 ++++++++++++++++++ docs/en/classes/Negative Selection/BNSA.md | 118 ---------- docs/en/classes/Negative Selection/README.md | 31 --- docs/en/classes/Negative Selection/RNSA.md | 215 ------------------- 6 files changed, 418 insertions(+), 364 deletions(-) create mode 100644 docs/en/api/nsa/README.md create mode 100644 docs/en/api/nsa/bnsa.md create mode 100644 docs/en/api/nsa/rnsa.md delete mode 100644 docs/en/classes/Negative Selection/BNSA.md delete mode 100644 docs/en/classes/Negative Selection/README.md delete mode 100644 docs/en/classes/Negative Selection/RNSA.md diff --git a/docs/en/api/nsa/README.md b/docs/en/api/nsa/README.md new file mode 100644 index 0000000..0b354be --- /dev/null +++ b/docs/en/api/nsa/README.md @@ -0,0 +1,35 @@ +--- +id: nsa +sidebar_label: aisp.nsa +keywords: + - immune + - artificial immune systems + - classification + - negative selection + - binary features + - anomaly detection + - non-self recognition + - pattern recognition + - multiclass + - real-valued + - v-detector +--- + +# aisp.nsa + +Module (NSA) Negative Selection Algorithm. + +> **Module:** `aisp.nsa` + +## Overview + +NSAs simulate the maturation process of T-cells in the immune system, where these cells learn to +distinguish between self and non-self. Only T-cells capable of recognizing non-self elements are +preserved. + +## Classes + +| Class | Description | +|---------------------|-------------------------------------------------------------------------------------| +| [`RNSA`](./rnsa.md) | A supervised learning algorithm for classification that uses real-valued detectors. | +| [`BNSA`](./bnsa.md) | A supervised learning algorithm for classification that uses binary detectors. | diff --git a/docs/en/api/nsa/bnsa.md b/docs/en/api/nsa/bnsa.md new file mode 100644 index 0000000..11e167b --- /dev/null +++ b/docs/en/api/nsa/bnsa.md @@ -0,0 +1,177 @@ +--- +id: bnsa +sidebar_label: BNSA +keywords: + - negative selection + - binary features + - anomaly detection + - non-self recognition + - pattern recognition + - classification + - multiclass +--- + +# BNSA + +Binary Negative Selection Algorithm (BNSA). + +:::tip[Inheritance] +This class extends [BaseClassifier](../base/base-classifier.md) +::: + + +> **Module:** `aisp.nsa` +> **Import:** `from aisp.nsa import BNSA` + +--- + +## Overview + +Algorithm for classification and anomaly detection Based on self or not self +discrimination, inspired by Negative Selection Algorithm. + +:::note + +The **Binary Negative Selection Algorithm (BNSA)** is based on the original proposal by +Forrest et al. (1994) [^1], originally developed for computer security. In the adaptation, the +algorithm use bits arrays, and it has support for multiclass classification. + +::: + +:::warning + +High `aff_thresh` values may prevent the generation of valid non-self detectors + +::: + +--- + +## Example + +```python +from aisp.nsa import BNSA +# Binary 'self' samples +x_train = [ + [0, 0, 1, 0, 1], + [0, 1, 1, 0, 1], + [0, 1, 0, 1, 0], + [0, 0, 1, 0, 1], + [0, 1, 1, 0, 1], + [0, 1, 0, 1, 0] +] +y_train = ['self', 'self', 'self', 'self', 'self', 'self'] +bnsa = BNSA(aff_thresh=0.55, seed=1) +bnsa = bnsa.fit(x_train, y_train, verbose=False) +# samples for testing +x_test = [ +... [1, 1, 1, 1, 1], # Sample of Anomaly +... [0, 1, 0, 1, 0], # self sample +... ] +y_prev = bnsa.predict(X=x_test) +print(y_prev) +``` +**Output** +```bash +['non-self' 'self'] +``` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|-----------------------------|-----------------|:--------------------------:|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `N` | `int` | `100` | Number of detectors. | +| `aff_thresh` | `float` | `0.1` | The variable represents the percentage of similarity between the T cell and the own samples. The default value is 10% (0.1), while a value of 1.0 represents 100% similarity. | +| `max_discards` | `int` | `1000` | This parameter indicates the maximum number of detector discards in sequence, which aims to avoid a possible infinite loop if a radius is defined that it is not possible to generate non-self detectors. | +| `seed` | `Optional[int]` | `None` | Seed for the random generation of values in the detectors. | +| `no_label_sample_selection` | `str` | `'max_average_difference'` | Method for selecting labels for samples designated as non-self by all detectors. | + +## Attributes + +| Name | Type | Default | Description | +|-------------|-----------------------------------------------------|:-------:|--------------------------------------------| +| `detectors` | `Optional[Dict[str \| int, npt.NDArray[np.bool_]]]` | - | The trained detectors, organized by class. | + +--- + +## Public Methods + +### fit + +```python +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True, +) -> BNSA: + ... +``` + +Training according to X and y, using the method negative selection method. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|---------------------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Training array, containing the samples and their characteristics, Shape: (n_samples, n_features). | +| `y` | `Union[npt.NDArray, list]` | - | Array of target classes of ``X`` with (``n_samples``). | +| `verbose` | `bool` | `True` | Feedback from detector generation to the user. | + + +**Raises** + +* `TypeError` - If X or y are not ndarrays or have incompatible shapes. +* `ValueError` - If the array contains values other than 0 and 1. +* `MaxDiscardsReachedError` - The maximum number of detector discards was reached during maturation. Check the defined radius value and consider reducing it. + +**Returns** + +`BNSA` - Returns the instance itself. + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Prediction of classes based on detectors created after training. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|-------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Array with input samples with Shape: (``n_samples, n_features``) | + +**Raises** + +* `TypeError` - If X is not a ndarray or list. +* `ValueError` - If the array contains values other than 0 and 1. +* `FeatureDimensionMismatch` - If the number of features in X does not match the expected number. +* `ModelNotFittedError` - If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions + +**Returns** + +**C** : `npt.NDArray` - An ndarray of the form ``C`` (``n_samples``), containing the predicted classes for ``X``. + +--- + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + +- [**Mushrooms Dataset Example**](../../../../examples/en/classification/BNSA/mushrooms_dataBase_example_en.ipynb) +- [**Random Dataset Example**](../../../../examples/en/classification/BNSA/example_with_randomly_generated_dataset-en.ipynb) + +--- + +## References + +[^1]: S. Forrest, A. S. Perelson, L. Allen and R. Cherukuri, "Self-nonself discrimination in + a computer," Proceedings of 1994 IEEE Computer Society Symposium on Research in Security + and Privacy, Oakland, CA, USA, 1994, pp. 202-212, + doi: https://dx.doi.org/10.1109/RISP.1994.296580. diff --git a/docs/en/api/nsa/rnsa.md b/docs/en/api/nsa/rnsa.md new file mode 100644 index 0000000..52d8741 --- /dev/null +++ b/docs/en/api/nsa/rnsa.md @@ -0,0 +1,206 @@ +--- +id: rnsa +sidebar_label: RNSA +keywords: + - negative selection + - anomaly detection + - non-self recognition + - pattern recognition + - classification + - real-valued + - v-detector + - multiclass +--- + +# RNSA + +Real-Valued Negative Selection Algorithm (RNSA). + +:::tip[Inheritance] + +This class extends [BaseClassifier](../base/base-classifier.md) + +::: + + +> **Module:** `aisp.nsa` +> **Import:** `from aisp.nsa import RNSA` + +--- + +## Overview + +Algorithm for classification and anomaly detection Based on self or not self +discrimination, inspired by Negative Selection Algorithm. + +:::note + +This algorithm has two different versions: one based on the canonical version [^1] and another +with variable radius detectors [^2]. Both are adapted to work with multiple classes and have +methods for predicting data present in the non-self region of all detectors and classes. + +::: + +:::warning + +The parameters `r` and `r_s` can prevent the generation of valid detectors. A very small `r` +value can limit coverage, while a very high one can hinder the generation of valid detectors. +Similarly, a high r_s can restrict detector creation. Thus, proper adjustment of `r` and `r_s` +is essential to ensure good model performance. + +::: + +--- + +## Example + +```python +import numpy as np +from aisp.nsa import RNSA + +np.random.seed(1) +class_a = np.random.uniform(high=0.5, size=(50, 2)) +class_b = np.random.uniform(low=0.51, size=(50, 2)) +``` + +**Example 1:** Multiclass classification (RNSA supports two or more classes) + +```python +x_train = np.vstack((class_a, class_b)) +y_train = ['a'] * 50 + ['b'] * 50 +rnsa = RNSA(N=150, r=0.3, seed=1) +rnsa = rnsa.fit(x_train, y_train, verbose=False) +x_test = [ + [0.15, 0.45], # Expected: Class 'a' + [0.85, 0.65], # Expected: Class 'b' +] +y_pred = rnsa.predict(x_test) +print(y_pred) +``` +**Output** +```bash +['a' 'b'] +``` +**Example 2:** Anomaly Detection (self/non-self) + +```python +rnsa = RNSA(N=150, r=0.3, seed=1) +rnsa = rnsa.fit(X=class_a, y=np.array(['self'] * 50), verbose=False) +y_pred = rnsa.predict(class_b[:5]) +print(y_pred) +``` +**Output** +```bash +['non-self' 'non-self' 'non-self' 'non-self' 'non-self'] +``` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|------------------|-------------------------------------------|:---------------:|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `N` | `int` | `100` | Number of detectors. | +| `r` | `float` | `0.05` | Radius of the detector. | +| `r_s` | `float` | `0.0001` | rₛ Radius of the ``X`` own samples. | +| `k` | `int` | `1` | Number of neighbors near the randomly generated detectors to perform the distance average calculation. | +| `metric` | `{"euclidean", "minkowski", "manhattan"}` | `'euclidean'` | Distance metric used to compute the distance between the detector and the sample. | +| `max_discards` | `int` | `1000` | This parameter indicates the maximum number of consecutive detector discards, aimed at preventing a possible infinite loop in case a radius is defined that cannot generate non-self detectors. | +| `seed` | `Optional[int]` | `None` | Seed for the random generation of values in the detectors. | +| `algorithm` | `{"default-NSA", "V-detector"}` | `'default-NSA'` | Set the algorithm version | +| `non_self_label` | `str` | `'non-self'` | This variable stores the label that will be assigned when the data has only one output class, and the sample is classified as not belonging to that class. | +| `cell_bounds` | `bool` | `False` | If set to ``True``, this option limits the generation of detectors to the space within the plane between 0 and 1. This means that any detector whose radius exceeds this limit is discarded, this variable is only used in the ``V-detector`` algorithm. | +| `p` | `bool` | `2.0` | This parameter stores the value of ``p`` used in the Minkowski distance. | + +## Attributes + +| Name | Type | Default | Description | +|-------------|----------------------------------------------|:-------:|--------------------------------------------| +| `detectors` | `Optional[Dict[str \| int, list[Detector]]]` | - | The trained detectors, organized by class. | + +--- + +## Public Methods + +### fit + +```python +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True, +) -> BNSA: + ... +``` + +Perform training according to X and y, using the negative selection method (NegativeSelect). + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|---------------------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Training array, containing the samples and their characteristics, Shape: (n_samples, n_features). | +| `y` | `Union[npt.NDArray, list]` | - | Array of target classes of ``X`` with (``n_samples``). | +| `verbose` | `bool` | `True` | Feedback from detector generation to the user. | + + +**Raises** + +* `TypeError` - If X or y are not ndarrays or have incompatible shapes. +* `ValueError` - If the array X fall outside the interval (0, 1). +* `MaxDiscardsReachedError` - The maximum number of detector discards was reached during maturation. Check the defined radius value and consider reducing it. + +**Returns** + +`RNSA` - Returns the instance itself. + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Prediction of classes based on detectors created after training. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|-------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Array with input samples with Shape: (``n_samples, n_features``) | + +**Raises** + +* `TypeError` - If X is not a ndarray or list. +* `ValueError` - If the array X fall outside the interval (0, 1). +* `FeatureDimensionMismatch` - If the number of features in X does not match the expected number. +* `ModelNotFittedError` - If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions + +**Returns** + +**C** : `npt.NDArray` - An ndarray of the form ``C`` (``n_samples``), containing the predicted classes for ``X``. + +--- + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + + +- [**Iris Dataset Example**](../../../../examples/en/classification/RNSA/iris_dataBase_example_en.ipynb) +- [**Geyser Dataset Example**](../../../../examples/en/classification/RNSA/geyser_dataBase_example_en.ipynb) +- [**Random Dataset Example**](../../../../examples/en/classification/RNSA/example_with_randomly_generated_dataset-en.ipynb) + +--- + +## References + +[^1]: BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing + Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. + Disponível em: https://dx.doi.org/10.1007/978-3-662-43631-8. + +[^2] Ji, Z.; Dasgupta, D. (2004). Real-Valued Negative Selection Algorithm with Variable-Sized Detectors. + In *Lecture Notes in Computer Science*, vol. 3025. https://doi.org/10.1007/978-3-540-24854-5_30 diff --git a/docs/en/classes/Negative Selection/BNSA.md b/docs/en/classes/Negative Selection/BNSA.md deleted file mode 100644 index 7212f38..0000000 --- a/docs/en/classes/Negative Selection/BNSA.md +++ /dev/null @@ -1,118 +0,0 @@ -# BNSA (Binary Negative Selection Algorithm) - -This class extends the [**Base**](../../advanced-guides/base/classifier.md) class. - -## Constructor BNSA - -The ``BNSA`` (Binary Negative Selection Algorithm) class has the purpose of classifying and identifying anomalies through the self and not self methods. - -**Attributes:** - -* *N* (``int``): Number of detectors. Defaults to ``100``. -* *aff_thresh* (``float``): The variable represents the percentage of similarity between the T cell and the own samples. The default value is 10% (0.1), while a value of 1.0 represents 100% dissimilarity. -* *max_discards* (``int``): This parameter indicates the maximum number of detector discards in sequence, which aims to avoid a -possible infinite loop if a radius is defined that it is not possible to generate non-self detectors. Defaults to ``1000``. -* *seed* (``int``): Seed for the random generation of values in the detectors. Defaults to ``None``. -* no_label_sample_selection (``str``): Method for selecting labels for samples designated as non-members by all non-member detectors. **Available method types:** - * (``max_average_difference``): Selects the class with the highest average difference among the detectors. - * (``max_nearest_difference``): Selects the class with the highest difference between the nearest and farthest detector from the sample. - -**Other variables initiated:** - -* *detectors* (``dict``): This variable stores a list of detectors by class. -* *classes* (``npt.NDArray``): list of output classes. - -### Method fit(...) - -The ``fit(...)`` function generates the detectors for non-fits with respect to the samples: - -```python -def fit( - self, - X: Union[npt.NDArray, list], - y: Union[npt.NDArray, list], - verbose: bool = True, -) -> BNSA: -``` - -In it, training is performed according to ``X`` and ``y``, using the negative selection method(``NegativeSelect``). - -**Parameters** - -* **X** (`Union[npt.NDArray, list]`): array with the characteristics of the samples with **N** samples (rows) and **N** characteristics (columns). - -* **y** (`Union[npt.NDArray, list]`): array with the output classes arranged in **N** samples that are related to ``X``. - -* **verbose** (`bool`): boolean with default value ``True``, determines if the feedback from the detector generation will be printed. - -**Raises** - -* ``TypeError``: If X or y are not ndarrays or have incompatible shapes. -* ``ValueError``: If the array contains values other than 0 and 1. -* ``MaxDiscardsReachedError``: The maximum number of detector discards was reached during - maturation. Check the defined radius value and consider reducing it. - -*Returns the instance of the class.* - ---- - -### Method predict(...) - -The ``predict(...)`` function performs class prediction using the generated detectors: - -```python -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -**Parameters** - -* **X** (`Union[npt.NDArray, list]`): array with the characteristics for the prediction, with **N** samples (Rows) and **N** columns. - -**Raises:** - -* ``TypeError``: If X is not an ndarray or list. -* ``ValueError``: X contains values that are not composed only of 0 and 1. -* ``FeatureDimensionMismatch``: If the number of features in X does not match the expected number. -* ``ModelNotFittedError``: If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions - -**Returns:** - -* **C** (`npt.NDArray`): A ndarray of the form ``C`` (``n_samples``), containing the predicted classes for ``X``. - ---- - -### Method score(...) - -The function ``score(...)`` calculates the accuracy of the trained model by making predictions and computing accuracy. - -```python -def score(self, X: npt.NDArray, y: list) -> float: -``` - -It returns the accuracy as a float type. - ---- - -## Private Methods - ---- - -### Method _assign_class_to_non_self_sample(...) - -This function determines the class of a sample when all detectors classify it as "non-self". Classification is performed using the ``max_average_difference`` and ``max_nearest_difference`` methods. - -```python -def _assign_class_to_non_self_sample(self, line: npt.NDArray, c: list): -``` - -**Parameters** - -* **line** (``npt.NDArray``): Sample to be classified. -* **c** (``list``): List of predictions to be updated with the new classification. - -**Raises** -* `ValueError`: If detectors is not initialized. - -**Returns:** - -``npt.NDArray``: The list of predictions `c` updated with the class assigned to the sample. diff --git a/docs/en/classes/Negative Selection/README.md b/docs/en/classes/Negative Selection/README.md deleted file mode 100644 index 0e8720b..0000000 --- a/docs/en/classes/Negative Selection/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# Negative selection - -**Negative selection** is the process in which the immune system maturates T-cells, also known as T-lymphocytes, which make them capable of detecting non-self. Thus, the Negative Selection Algorithm (NSA) uses hyperspheres symbolizing the detectors in an N-dimensional data space. [[1]](#1) - -## classes - -1. **[Binary version:](BNSA.md)** - -> The binary algorithm adapted for multiple classes in this project is based on the version proposed by [Forrest et al. (1994)](#2), originally developed for computer security. - -2. **[Real-Valued version:](RNSA.md)** - ->This algorithm has two different versions: one based on the canonical version [[1]](#1) and another with variable radius detectors [[3]](#3). Both are adapted to work with multiple classes and have methods for predicting data present in the non-self region of all detectors and classes. - -## References - ---- - -### 1 -> -> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: . - -### 2 -> -> S. Forrest, A. S. Perelson, L. Allen and R. Cherukuri, "Self-nonself discrimination in a computer," Proceedings of 1994 IEEE Computer Society Symposium on Research in Security and Privacy, Oakland, CA, USA, 1994, pp. 202-212, doi: . - -### 3 -> -> JI, Zhou; DASGUPTA, Dipankar. Real-Valued Negative Selection Algorithm with Variable-Sized Detectors. Genetic and Evolutionary Computation - GECCO 2004. [S. l.]: Springer Berlin Heidelberg, 2004. DOI 10.1007/978-3-540-24854-5_30. Disponível em: . - ---- diff --git a/docs/en/classes/Negative Selection/RNSA.md b/docs/en/classes/Negative Selection/RNSA.md deleted file mode 100644 index 2606294..0000000 --- a/docs/en/classes/Negative Selection/RNSA.md +++ /dev/null @@ -1,215 +0,0 @@ - -# RNSA (Real-Valued Negative Selection Algorithm) - -This class extends the [**Base**](../../advanced-guides/base/classifier.md) class. - -## Constructor RNSA - -The ``RNSA`` class has the purpose of classifying and identifying anomalies through the self and not self methods. - -**Attributes:** - -* **N** (``int``): Number of detectors. Defaults to ``100``. -* **r** (``float``): Radius of the detector. Defaults to ``0.05``. -* **k** (``int``): Number of neighbors near the randomly generated detectors to perform the distance average calculation. Defaults to ``1``. -* **metric** (``str``): Way to calculate the distance between the detector and the sample: - - * ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: √( (X₁ - X₂)² + (Y₁ - Y₂)² + ... + (Yn - Yn)²). - * ``'minkowski'`` ➜ The calculation of the distance is given by the expression: ( |X₁ - Y₁|p + |X₂ - Y₂|p + ... |Xn - Yn|p) ¹/ₚ , In this project ``p == 2``. - * ``'manhattan'`` ➜ The calculation of the distance is given by the expression: ( |X₁ - X₂| + |Y₁ - Y₂| + ...+ |Yn - Yn₂|) . - - Defaults to ``'euclidean'``. - -* **max_discards** (``int``): This parameter indicates the maximum number of consecutive detector discards, aimed at preventing a possible infinite loop in case a radius is defined that cannot generate non-self detectors. -* **seed** (``int``): Seed for the random generation of values in the detectors. Defaults to ``None``. - -* **algorithm** (``str``), Set the algorithm version: - - * ``'default-NSA'``: Default algorithm with fixed radius. - * ``'V-detector'``: This algorithm is based on the article "[Real-Valued Negative Selection Algorithm with Variable-Sized Detectors](https://doi.org/10.1007/978-3-540-24854-5_30)", by Ji, Z., Dasgupta, D. (2004), and uses a variable radius for anomaly detection in feature spaces. - - Defaults to ``'default-NSA'``. - -* **r_s** (``float``): rₛ Radius of the ``X`` own samples. -* ``**kwargs``: - * *non_self_label* (``str``): This variable stores the label that will be assigned when the data has only one - output class, and the sample is classified as not belonging to that class. Defaults to ``'non-self'``. - * *cell_bounds* (``bool``): If set to ``True``, this option limits the generation of detectors to the space within - the plane between 0 and 1. This means that any detector whose radius exceeds this limit is discarded, - this variable is only used in the ``V-detector`` algorithm. Defaults to ``False``. - -**Other variables initiated:** - -* **detectors** (``dict``): This variable stores a list of detectors by class. -* **classes** (``npt.NDArray``): list of output classes. - ---- - -### Method fit(...) - -The ``fit(...)`` function generates the detectors for non-fits with respect to the samples: - -```python -def fit( - self, - X: Union[npt.NDArray, list], - y: Union[npt.NDArray, list], - verbose: bool = True, -) -> RNSA: -``` - -In it, training is performed according to ``X`` and ``y``, using the negative selection method(``NegativeSelect``). - -The input parameters are: - -* **X** (`Union[npt.NDArray, list]`): array with the characteristics of the samples with **N** samples (rows) and **N** characteristics (columns). -* **y** (`Union[npt.NDArray, list]`): array with the output classes arranged in **N** samples that are related to ``X``. -* **verbose** (`bool`): boolean with default value ``True``, determines if the feedback from the detector generation will be printed. - -**Raises** - -* ``TypeError``: If X or y are not ndarrays or have incompatible shapes. -* ``MaxDiscardsReachedError``: The maximum number of detector discards was reached during - maturation. Check the defined radius value and consider reducing it. - -**Returns** - - the instance of the class. - ---- - -### Method predict(...) - -The ``predict(...)`` function performs class prediction using the generated detectors: - -```python -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -**The input parameter is:** - -* **X** (`Union[npt.NDArray, list]`): array with the characteristics for the prediction, with **N** samples (Rows) and **N** columns. - -**Raises:** - -* ``TypeError``: If X is not an ndarray or list. -* ``FeatureDimensionMismatch``: If the number of features in X does not match the expected number. -* ``ModelNotFittedError``: If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions - -**Returns:** - -* C (``npt.NDArray``): A ndarray of the form ``C`` (n_samples), containing the predicted classes for ``X``. - ---- - -### Method score(...) - -The function ``score(...)`` calculates the accuracy of the trained model by making predictions and computing accuracy. - -```python -def score(self, X: npt.NDArray, y: list) -> float: -``` - -It returns the accuracy as a float type. - ---- - -## Private Methods - ---- - -### Method _checks_valid_detector(...) - -The ``def _checks_valid_detector(...)`` function check if the detector has a valid non-proper r radius for the class. - -```python -def _checks_valid_detector( - self, - x_class: npt.NDArray, - vector_x: npt.NDArray -) -> Union[bool, tuple[bool, float]]: -``` - -**Parameters** - -* **x_class** (`npt.NDArray`): Array ``x_class`` with the samples per class. -* **vector_x** (`npt.NDArray`): Randomly generated vector x candidate detector with values between[0, 1]. - -**Returns** -* **Validity** (``bool``): Returns whether the detector is valid or not. - ---- - -### Method _compare_KnearestNeighbors_List(...) - -The ``def _compare_KnearestNeighbors_List(...)`` function compares the distance of the k-nearest neighbors, so if the distance of the new sample is smaller, replaces ``k-1`` and sorts in ascending order: - -```python -def _compare_knearest_neighbors_list(self, knn: list, distance: float) -> None: -``` - -**Parameters** -* **knn** (`list`): List of k-nearest neighbor distances. -* **distance** (`float`): Distance to check. - -Returns a list of k-nearest neighbor distances. - ---- - -### Method _compare_sample_to_detectors(...) - -Function to compare a sample with the detectors, verifying if the sample is proper. -In this function, when there is class ambiguity, it returns the class that has the greatest average distance between the detectors. - -```python -def _compare_sample_to_detectors(self, line: npt.NDArray) -> Optional[str]: -``` - -**Parameters** - -* line (`npt.NDArray`): vector with N-features - -**Returns** - -The predicted class with the detectors or None if the sample does not qualify for any class. - ---- - -### Method _detector_is_valid_to_Vdetector(...) - -Check if the distance between the detector and the samples, minus the radius of the samples, is greater than the minimum radius. - -```python -def _detector_is_valid_to_vdetector( - self, - distance: float, - vector_x: npt.NDArray -) -> Union[bool, tuple[bool, float]]: -``` - -**Parameters** - -* distance (``float``): minimum distance calculated between all samples. -* vector_x (``npt.NDArray``): randomly generated candidate detector vector x with values between 0 and 1. - -**Returns:** - -* ``False``: if the calculated radius is smaller than the minimum distance or exceeds the edge of the space, if this option is enabled. -* ``True`` and the distance minus the radius of the samples, if the radius is valid.` - ---- - -### Method _distance(...) - -The function ``def _distance(...)`` calculates the distance between two points using the technique defined in ``metric``, which are: ``'euclidean', 'norm_euclidean', or 'manhattan'`` - -```python -def _distance(self, u: npt.NDArray, v: npt.NDArray): -``` - -**Parameters** -* **u** (`npt.NDArray`): Coordinates of the first point. -* **v** (`npt.NDArray`): Coordinates of the second point. - -**Returns:** -* distance (`float`): the distance between the two points. From bf946dae6b43e01d15245bcc87036aca01cb4aac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Thu, 5 Mar 2026 14:35:03 -0300 Subject: [PATCH 17/40] docs: add tags to the class documentation --- aisp/ina/_ai_network.py | 2 +- docs/en/api/base/base-classifier.md | 3 +++ docs/en/api/base/base-clusterer.md | 3 +++ docs/en/api/base/base-optimizer.md | 3 +++ docs/en/api/csa/airs.md | 4 ++++ docs/en/api/csa/clonalg.md | 9 +++++++++ docs/en/api/ina/ai-net.md | 7 ++++++- docs/en/api/nsa/bnsa.md | 6 ++++++ docs/en/api/nsa/rnsa.md | 6 ++++++ 9 files changed, 41 insertions(+), 2 deletions(-) diff --git a/aisp/ina/_ai_network.py b/aisp/ina/_ai_network.py index fb4f09f..e8c0971 100644 --- a/aisp/ina/_ai_network.py +++ b/aisp/ina/_ai_network.py @@ -39,7 +39,7 @@ class AiNet(BaseClusterer): clustering and data compression tasks. The aiNet algorithm uses principles from immune network theory, clonal selection, and affinity maturation to compress high-dimensional datasets. [1]_ - For clustering, the class uses SciPy's implementation of the **Minimum Spanning Tree** + For clustering, the class uses SciPy implementation of the **Minimum Spanning Tree** (MST) to remove the most distant nodes and separate the groups. [2]_ Parameters diff --git a/docs/en/api/base/base-classifier.md b/docs/en/api/base/base-classifier.md index 7e10d1a..cd17541 100644 --- a/docs/en/api/base/base-classifier.md +++ b/docs/en/api/base/base-classifier.md @@ -8,6 +8,9 @@ keywords: - accuracy score - fit - predict +tags: + - classifier + - classification --- # BaseClassifier diff --git a/docs/en/api/base/base-clusterer.md b/docs/en/api/base/base-clusterer.md index b092fdb..722c7ae 100644 --- a/docs/en/api/base/base-clusterer.md +++ b/docs/en/api/base/base-clusterer.md @@ -9,6 +9,9 @@ keywords: - fit - predict - fit_predict +tags: + - clusterer + - clustering --- # BaseClusterer diff --git a/docs/en/api/base/base-optimizer.md b/docs/en/api/base/base-optimizer.md index 41f129b..001f0bc 100644 --- a/docs/en/api/base/base-optimizer.md +++ b/docs/en/api/base/base-optimizer.md @@ -9,6 +9,9 @@ keywords: - objective function - minimization - maximization +tags: + - optimizer + - optimization --- # BaseOptimizer diff --git a/docs/en/api/csa/airs.md b/docs/en/api/csa/airs.md index af32f99..e526899 100644 --- a/docs/en/api/csa/airs.md +++ b/docs/en/api/csa/airs.md @@ -7,6 +7,10 @@ keywords: - memory cells - k-nn - supervised learning +tags: + - classification + - supervised + - clonal selection --- # AIRS diff --git a/docs/en/api/csa/clonalg.md b/docs/en/api/csa/clonalg.md index f38b291..db976d7 100644 --- a/docs/en/api/csa/clonalg.md +++ b/docs/en/api/csa/clonalg.md @@ -7,6 +7,15 @@ keywords: - clonalg - antibody population - objective function +tags: + - optimization + - clonal selection + - minimization + - maximization + - binary + - continuous + - permutation + - ranged --- # Clonalg diff --git a/docs/en/api/ina/ai-net.md b/docs/en/api/ina/ai-net.md index 83e0b1a..f90aa57 100644 --- a/docs/en/api/ina/ai-net.md +++ b/docs/en/api/ina/ai-net.md @@ -7,6 +7,11 @@ keywords: - data compression - unsupervised learning - Minimum Spanning Tree +tags: + - clustering + - unsupervised + - immune network + - data compression --- # AiNet @@ -31,7 +36,7 @@ This class implements the aiNet algorithm, an artificial immune network model de clustering and data compression tasks. The aiNet algorithm uses principles from immune network theory, clonal selection, and affinity maturation to compress high-dimensional datasets [^1]. -For clustering, the class uses SciPy's implementation of the **Minimum Spanning Tree** +For clustering, the class uses SciPy implementation of the **Minimum Spanning Tree** (MST) to remove the most distant nodes and separate the groups [^2]. --- diff --git a/docs/en/api/nsa/bnsa.md b/docs/en/api/nsa/bnsa.md index 11e167b..8799459 100644 --- a/docs/en/api/nsa/bnsa.md +++ b/docs/en/api/nsa/bnsa.md @@ -9,6 +9,12 @@ keywords: - pattern recognition - classification - multiclass +tags: + - classification + - supervised + - negative selection + - binary-features + - anomaly detection --- # BNSA diff --git a/docs/en/api/nsa/rnsa.md b/docs/en/api/nsa/rnsa.md index 52d8741..a3066e3 100644 --- a/docs/en/api/nsa/rnsa.md +++ b/docs/en/api/nsa/rnsa.md @@ -10,6 +10,12 @@ keywords: - real-valued - v-detector - multiclass +tags: + - classification + - supervised + - negative selection + - real-valued + - anomaly detection --- # RNSA From 90963f2c03ef16deab696e6d5fae1521f32a645e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Thu, 5 Mar 2026 14:38:35 -0300 Subject: [PATCH 18/40] docs: adds initial readme to the API documentation --- docs/en/api/README.md | 68 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 64 insertions(+), 4 deletions(-) diff --git a/docs/en/api/README.md b/docs/en/api/README.md index e61dd24..aa8d89e 100644 --- a/docs/en/api/README.md +++ b/docs/en/api/README.md @@ -1,7 +1,67 @@ --- -tags: - - api - - documentation +id: api +sidebar_label: api +keywords: + - api + - aisp + - Artificial Immune System Package + - classification + - optimization + - clustering --- -# API - Reference \ No newline at end of file +# AISP - API + +Welcome to the **AISP** (Artificial Immune System Package) api. This documentation demonstrates the package public API. + +## Core Modules (`aisp.base`) + +Fundamental abstractions and base classes that define core interfaces of package. + +| Class | Description | +|-----------------------------------------------|----------------------------------------------------| +| [`BaseClassifier`](./base/base-classifier.md) | Abstract base class for classification algorithms. | +| [`BaseClusterer`](./base/base-clusterer.md) | Abstract base class for clustering algorithms. | +| [`BaseOptimizer`](./base/base-optimizer.md) | Abstract base class for optimization algorithms. | + +### Immune Domain components (`aisp.base.immune`) + +Core structures and support utilities for implementations immune. + +| Class | Description | +|-----------------------------------------------|--------------------------------------------------------------------------------------------| +| [`cell`](./base/immune/cell/README.md) | Representation of immune system cells. | +| [`mutation`](./base/immune/mutation.md) | Functions to generate mutated clones and simulate clonal expansion. | +| [`populations`](./base/immune/populations.md) | Provide utility functions for generating antibody populations in immunological algorithms. | + +--- + +## Algorithms + +### Negative Selection Algorithms (`aisp.nsa`) + +supervised learning algorithms based on negative selection, the immune systems process of distinguishing self from not-self. + +| Class | Description | +|-------------------------|-------------------------------------------------------------------------------------| +| [`RNSA`](./nsa/rnsa.md) | A supervised learning algorithm for classification that uses real-valued detectors. | +| [`BNSA`](./nsa/bnsa.md) | A supervised learning algorithm for classification that uses binary detectors. | + +### Clonal Selection Algorithms (`aisp.csa`) + +Algorithms inspired by the process of antibody proliferation to detecting an antigen. + +| Class | Description | +|-------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [`AIRS`](./csa/airs.md) | A supervised learning algorithm for classification tasks based on the clonal selection principle. | +| [`Clonalg`](./csa/clonalg.md) | Implementation of the clonal selection algorithm for optimization, adapted for both minimization and maximization of cost functions in binary, continuous, and permutation problems. | + +### Immune Network Algorithms (`aisp.ina`) + +Algorithms based on Network Theory Algorithms proposed by Jerne. + +| Class | Description | +|------------------------|--------------------------------------------------------------------------------------------| +| [`AiNet`](./ai-net.md) | An unsupervised learning algorithm for clustering, based on the theory of immune networks. | + +## Utils (`aisp.utils`) \ No newline at end of file From f5b9697f264aabb8d35e3a816f63dd6b2856a944 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Thu, 5 Mar 2026 14:41:42 -0300 Subject: [PATCH 19/40] docs: adds initial readme to the API documentation --- docs/en/api/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/en/api/README.md b/docs/en/api/README.md index aa8d89e..e270168 100644 --- a/docs/en/api/README.md +++ b/docs/en/api/README.md @@ -14,7 +14,7 @@ keywords: Welcome to the **AISP** (Artificial Immune System Package) api. This documentation demonstrates the package public API. -## Core Modules (`aisp.base`) +## Core Modules ([`aisp.base`](./base/README.md)) Fundamental abstractions and base classes that define core interfaces of package. @@ -24,7 +24,7 @@ Fundamental abstractions and base classes that define core interfaces of package | [`BaseClusterer`](./base/base-clusterer.md) | Abstract base class for clustering algorithms. | | [`BaseOptimizer`](./base/base-optimizer.md) | Abstract base class for optimization algorithms. | -### Immune Domain components (`aisp.base.immune`) +### Immune Domain components ([`aisp.base.immune`](./base/immune/README.md)) Core structures and support utilities for implementations immune. @@ -38,7 +38,7 @@ Core structures and support utilities for implementations immune. ## Algorithms -### Negative Selection Algorithms (`aisp.nsa`) +### Negative Selection Algorithms ([`aisp.nsa`](./nsa/README.md)) supervised learning algorithms based on negative selection, the immune systems process of distinguishing self from not-self. @@ -47,7 +47,7 @@ supervised learning algorithms based on negative selection, the immune systems p | [`RNSA`](./nsa/rnsa.md) | A supervised learning algorithm for classification that uses real-valued detectors. | | [`BNSA`](./nsa/bnsa.md) | A supervised learning algorithm for classification that uses binary detectors. | -### Clonal Selection Algorithms (`aisp.csa`) +### Clonal Selection Algorithms ([`aisp.csa`](./csa/README.md)) Algorithms inspired by the process of antibody proliferation to detecting an antigen. @@ -56,7 +56,7 @@ Algorithms inspired by the process of antibody proliferation to detecting an ant | [`AIRS`](./csa/airs.md) | A supervised learning algorithm for classification tasks based on the clonal selection principle. | | [`Clonalg`](./csa/clonalg.md) | Implementation of the clonal selection algorithm for optimization, adapted for both minimization and maximization of cost functions in binary, continuous, and permutation problems. | -### Immune Network Algorithms (`aisp.ina`) +### Immune Network Algorithms ([`aisp.ina`](./ina/README.md)) Algorithms based on Network Theory Algorithms proposed by Jerne. From 96b521e2c4c5b00bbc2f5e346b678fce52ba6630 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Mon, 9 Mar 2026 00:24:05 -0300 Subject: [PATCH 20/40] docs(template): add templates for modules and modules with only function --- aisp/__init__.py | 2 +- docs/assets/template-docs-class.md | 17 ++++++++- docs/assets/template-docs-functions.md | 49 +++++++++++++++++++++++++ docs/assets/template-docs-module.md | 51 ++++++++++++++++++++++++++ pyproject.toml | 2 +- 5 files changed, 117 insertions(+), 4 deletions(-) create mode 100644 docs/assets/template-docs-functions.md create mode 100644 docs/assets/template-docs-module.md diff --git a/aisp/__init__.py b/aisp/__init__.py index fad8f7e..61142f0 100644 --- a/aisp/__init__.py +++ b/aisp/__init__.py @@ -31,5 +31,5 @@ from . import nsa __author__ = "AISP Development Team" -__version__ = "0.5.1" +__version__ = "0.5.4" __all__ = ["csa", "nsa", "ina"] diff --git a/docs/assets/template-docs-class.md b/docs/assets/template-docs-class.md index 5e9ca6f..87c5688 100644 --- a/docs/assets/template-docs-class.md +++ b/docs/assets/template-docs-class.md @@ -3,11 +3,13 @@ id: class-name sidebar_label: ClassName keywords: - key +tags: + - tag --- # ClassName -{{ Brief description of the class. }} +{{ Brief description of the class }} :::tip[Inheritance] This class extends {{ class }} @@ -60,6 +62,13 @@ model.method_name() ### method_name +````python +def method_name( + param_1: type, +) -> type: + ... +```` + Description. **Parameters** @@ -68,9 +77,13 @@ Description. |-----------|--------|:-------:|---------------------------| | `param_1` | `Type` | - | Description of the param. | +**Raises** + +{{ Raise }} - {{ Description }}. + **Returns** -{{ Type }} - {{ Description }}. +{{ Type }} - {{ Description }}. --- diff --git a/docs/assets/template-docs-functions.md b/docs/assets/template-docs-functions.md new file mode 100644 index 0000000..4f3a60b --- /dev/null +++ b/docs/assets/template-docs-functions.md @@ -0,0 +1,49 @@ +--- +id: module +sidebar_label: module +keywords: + - key +tags: + - tag +--- + +# module + +{{ Brief description of the submodule }} + +> **Module:** `aisp.[module]` +> **Import:** `from aisp import [module]` + +## Functions + +### function_name + +````python +def function_name( + param_1: type, +) -> type: + ... +```` + +{{ description }} + +**Parameters** + +| Name | Type | Default | Description | +|-----------|--------|:-------:|---------------------------| +| `param_1` | `Type` | - | Description of the param. | + +**Raises** + +{{ Raise }} - {{ Description }}. + +**Returns** + +{{ Type }} - {{ Description }}. + + +--- + +## References + +[^1]: {{ Reference }} diff --git a/docs/assets/template-docs-module.md b/docs/assets/template-docs-module.md new file mode 100644 index 0000000..b5df15e --- /dev/null +++ b/docs/assets/template-docs-module.md @@ -0,0 +1,51 @@ +--- +id: module-name +sidebar_label: ModuleName +keywords: + - key +tags: + - tag +--- + +# ModuleName + +{{ Brief description of the module }} + +> **Module:** `aisp.[module]` +> **Import:** `from aisp import [module]` + +--- + +## Overview + +{{ Explain what the module }} + +--- + +## Classes + +| Class | Description | +|-------------|--------------| +| `ClassName` | Description. | + +--- + +## Functions + +| Function | Description | +|-----------------|--------------| +| `function_name` | Description. | + +--- + +## Submodules + +| Module | Description | +|-------------|--------------| +| `submodule` | Description. | + +--- + +## References + +[^1]: {{ Reference }} diff --git a/pyproject.toml b/pyproject.toml index a46c054..81fb952 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta" [project] name = "aisp" -version = "0.5.3" +version = "0.5.4" authors = [ { name="João Paulo da Silva Barros", email="jpsilvabarr@gmail.com" }, ] From 92860ef273e07c7fc0e953e091967d26ac4ffae6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Mon, 9 Mar 2026 01:09:56 -0300 Subject: [PATCH 21/40] docs(utils): Add documentation for the display and distance modules. --- aisp/utils/distance.py | 2 +- docs/assets/template-docs-class.md | 2 + docs/en/advanced-guides/utils.md | 618 ------------------- docs/en/api/base/immune/README.md | 4 +- docs/en/api/base/immune/mutation.md | 2 +- docs/en/api/base/immune/populations.md | 2 +- docs/en/api/utils/display/README.md | 24 + docs/en/api/utils/display/progress-table.md | 57 ++ docs/en/api/utils/display/table-formatter.md | 78 +++ docs/en/api/utils/distance.md | 228 +++++++ 10 files changed, 394 insertions(+), 623 deletions(-) delete mode 100644 docs/en/advanced-guides/utils.md create mode 100644 docs/en/api/utils/display/README.md create mode 100644 docs/en/api/utils/display/progress-table.md create mode 100644 docs/en/api/utils/display/table-formatter.md create mode 100644 docs/en/api/utils/distance.md diff --git a/aisp/utils/distance.py b/aisp/utils/distance.py index 078eae2..4b2de45 100644 --- a/aisp/utils/distance.py +++ b/aisp/utils/distance.py @@ -145,7 +145,7 @@ def compute_metric_distance( Returns ------- float64 - Distance (``float``) between the two points with the selected metric. + Distance between the two points with the selected metric. """ if metric == MANHATTAN: return cityblock(u, v) diff --git a/docs/assets/template-docs-class.md b/docs/assets/template-docs-class.md index 87c5688..a2fa292 100644 --- a/docs/assets/template-docs-class.md +++ b/docs/assets/template-docs-class.md @@ -12,7 +12,9 @@ tags: {{ Brief description of the class }} :::tip[Inheritance] + This class extends {{ class }} + ::: diff --git a/docs/en/advanced-guides/utils.md b/docs/en/advanced-guides/utils.md deleted file mode 100644 index 0bd63dd..0000000 --- a/docs/en/advanced-guides/utils.md +++ /dev/null @@ -1,618 +0,0 @@ -# Utils - -Utility functions and helpers for development. - -## Metrics - -### Function `accuracy_score(...)` - -```python -def accuracy_score( - y_true: Union[npt.NDArray, list], - y_pred: Union[npt.NDArray, list] -) -> float: -``` - -Function to calculate precision accuracy based on lists of true labels and -predicted labels. - -**Parameters:** - -* **y_true** (``Union[npt.NDArray, list]``): Ground truth (correct) labels. - Expected to be of the same length as `y_pred`. -* **y_pred** (``Union[npt.NDArray, list]``): Predicted labels. Expected to - be of the same length as `y_true`. - -Returns: - -* **Accuracy** (``float``): The ratio of correct predictions to the total -number of predictions. - -**Raises**: - -* `ValueError`: If `y_true` or `y_pred` are empty or if they do not have the same length. - ---- - -## Multiclass - -## Function `predict_knn_affinity(...)` - -```python -def predict_knn_affinity( - X: npt.NDArray, - k: int, - all_cell_vectors: List[Tuple[Union[str, int], npt.NDArray]], - affinity_func: Callable[[npt.NDArray, npt.NDArray], float] -) -> npt.NDArray: -``` - -Function to predict classes using k-nearest neighbors and trained cells. - -**Parameters:** - -* **X** (`npt.NDArray`): Input data to be classified. -* **k** (`int`): Number of nearest neighbors to consider for prediction. -* **all_cell_vectors** (`List[Tuple[Union[str, int], npt.NDArray]]`): List of tuples containing (class_name, cell vector) pairs. -* **affinity_func** (`Callable[[npt.NDArray, npt.NDArray], float]`): Function that takes two vectors and returns an affinity value. - -**Returns:** - -* `npt.NDArray`: Array of predicted labels for each sample in X, based on the k nearest neighbors. - ---- - -## Function `slice_index_list_by_class(...)` - -```python -def slice_index_list_by_class(classes: Optional[Union[npt.NDArray, list]], y: npt.NDArray) -> dict: -``` - -The function ``slice_index_list_by_class(...)``, separates the indices of the samples -according to their output class, to iterate through the sample array only at positions where -the output matches the class being trained. - -**Parameters:** - -* **classes** (`Optional[Union[npt.NDArray, list]]`): List with unique classes. If None, returns an empty dictionary. -* **y** (`npt.NDArray`): Array with output classes of the ``X`` sample array. - -**Returns:** - -* `dict`: A dictionary with the list of array positions keyed by class. - -**Examples:** - -```python ->>> import numpy as np ->>> labels = ['a', 'b', 'c'] ->>> y = np.array(['a', 'c', 'b', 'a', 'c', 'b']) ->>> slice_index_list_by_class(labels, y) -{'a': [0, 3], 'b': [2, 5], 'c': [1, 4]} -``` - ---- - -The function ``__slice_index_list_by_class(...)``, separates the indices of the lines -according to the output class, to loop through the sample array, only in positions where -the output is the class being trained. - -**Parameters:** - -* **y** (npt.NDArray): Receives a ``y`` (``n_samples``) array with the output classes of the - ``X`` sample array. - -**returns:** - -* `dict`: A dictionary with the list of array positions(``y``), with the classes as key. - ---- - -## Sanitizers - -### Function `sanitize_choice(...)` - -```python -def sanitize_choice(value: T, valid_choices: Iterable[T], default: T) -> T: -``` - -The function ``sanitize_choice(...)``, returns the value if it is present in the set of valid choices; otherwise, returns the default value. - -**Parameters:** - -* **value** (``T``): The value to be checked. -* **valid_choices** (``Iterable[T]``): A collection of valid choices. -* **default**: The default value to be returned if ``value`` is not in ``valid_choices``. - -**Returns:** - -* `T`: The original value if valid, or the default value if not. - ---- - -### Function `sanitize_param(...)` - -```python -def sanitize_param(value: T, default: T, condition: Callable[[T], bool]) -> T: -``` - -The function ``sanitize_param(...)``, returns the value if it satisfies the specified condition; otherwise, returns the default value. - -**Parameters:** - -* **value** (``T``): The value to be checked. -* **default** (``T``): The default value to be returned if the condition is not satisfied. -* **condition** (``Callable[[T], bool]``): A function that takes a value and returns a boolean, determining if the value is valid. - -**Returns:** - -* `T`: The original value if the condition is satisfied, or the default value if not. - ---- - -### Function `sanitize_seed(...)` - -```python -def sanitize_seed(seed: Any) -> Optional[int]: -``` - -The function ``sanitize_seed(...)``, returns the seed if it is a non-negative integer; otherwise, returns None. - -**Parameters:** - -* **seed** (``Any``): The seed value to be validated. - -**Returns:** - -* ``Optional[int]``: The original seed if it is a non-negative integer, or ``None`` if it is invalid. - -### Function `sanitize_bounds(...)` - -```python -def sanitize_bounds( - bounds: Any, - problem_size: int -) -> Dict[str, npt.NDArray[np.float64]]: -``` - -The function ``sanitize_bounds(...)``, validate and normalize feature bounds. - -**Parameters:** - -* **bounds** (``Any``): he input bounds, which must be either None or a dictionary with 'low' and 'high' keys. -* **problem_size** (``int``): The expected length for the normalized bounds lists, corresponding to the number of features in the problem. - -**Returns:** - -* `Dict[str, npt.NDArray[np.float64]]`: Dictionary {'low': [low_1, ..., low_N], 'high': [high_1, ..., high_N]}. - -## Distance - -Utility functions for normalized distance between arrays with numba decorators. - -### Function `hamming(...)` - -```python -def hamming(u: npt.NDArray[np.bool_], v: npt.NDArray[np.bool_]) -> float64: -``` - -The function to calculate the normalized Hamming distance between two points. - -$((x₁ ≠ x₂) + (y₁ ≠ y₂) + ... + (yn ≠ yn)) / n$ - -**Parameters:** - -* **u** (``npt.NDArray[np.bool_]``): Coordinates of the first point. -* **v** (``npt.NDArray[np.bool_]``): Coordinates of the second point. - -**Returns:** - -* Distance (``float64``) between the two points. - ---- - -### Function `euclidean(...)` - -```python -def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> float64: -``` - -Function to calculate the normalized Euclidean distance between two points. - -$√( (x₁ - x₂)² + (y₁ - y₂)² + ... + (yn - yn)²)$ - -**Parameters:** - -* **u** (``npt.NDArray[float64]``): Coordinates of the first point. -* **v** (``npt.NDArray[float64]``): Coordinates of the second point. - -**Returns:** - -* Distance (``float64``) between the two points. - ---- - -### Function `cityblock(...)` - -```python -def cityblock(u: npt.NDArray[float64], v: npt.NDArray[float64]) -> float64: -``` - -Function to calculate the normalized Manhattan distance between two points. - -$(|x₁ - x₂| + |y₁ - y₂| + ... + |yn - yn|) / n$ - -**Parameters:** - -* **u** (``npt.NDArray[float64]``): Coordinates of the first point. -* **v** (``npt.NDArray[float64]``): Coordinates of the second point. - -**Returns:** - -* Distance (``float64``) between the two points. - ---- - -### Function `minkowski(...)` - -```python -def minkowski( - u: npt.NDArray[float64], - v: npt.NDArray[float64], - p: float = 2.0 -) -> float64: -``` - -Function to calculate the normalized Minkowski distance between two points. - -$(( |X₁ - Y₁|p + |X₂ - Y₂|p + ... + |Xn - Yn|p) ¹/ₚ) / n$ - -**Parameters:** - -* **u** (``npt.NDArray[float64]``): Coordinates of the first point. -* **v** (``npt.NDArray[float64]``): Coordinates of the second point. -* **p** float: The p parameter defines the type of distance to be calculated: - * p = 1: **Manhattan** distance - sum of absolute differences. - * p = 2: **Euclidean** distance - sum of squared differences (square root). - * p > 2: **Minkowski** distance with an increasing penalty as p increases. - -**Returns:** - -* Distance (``float64``) between the two points. - ---- - -### Function `compute_metric_distance(...)` - -```python -def compute_metric_distance( - u: npt.NDArray[float64], - v: npt.NDArray[float64], - metric: int, - p: float = 2.0 -) -> float64: -``` - -Function to calculate the distance between two points by the chosen ``metric``. - -**Parameters:** - -* **u** (``npt.NDArray[float64]``): Coordinates of the first point. -* **v** (``npt.NDArray[float64]``): Coordinates of the second point. -* **metric** (``int``): Distance metric to be used. Available options: [0 (Euclidean), 1 (Manhattan), 2 (Minkowski)] -* **p** (``float``): Parameter for the Minkowski distance (used only if `metric` is "minkowski"). - -**Returns:** - -* Distance (``float64``) between the two points with the selected metric. - ---- - -### Function `min_distance_to_class_vectors(...)` - -```python -def min_distance_to_class_vectors( - x_class: npt.NDArray[float64], - vector_x: npt.NDArray[float64], - metric: int, - p: float = 2.0, -) -> float: -``` - -Calculates the minimum distance between an input vector and the vectors of a class. - -**Parameters:** - -* **x_class** (``npt.NDArray[float64]``): Array containing the class vectors to be compared with the input vector. Expected shape: (n_samples, n_features). -* **vector_x** (``npt.NDArray[float64]``): Vector to be compared with the class vectors. Expected shape: (n_features,). -* **metric** (``int``): Distance metric to be used. Available options: [0 (Euclidean), 1 (Manhattan), 2 (Minkowski), 3 (hamming)] -* **p** (``float``): Parameter for the Minkowski distance (used only if `metric` is "minkowski"). - -**Returns:** - -* float: The minimum distance calculated between the input vector and the class vectors. -* Returns -1.0 if the input dimensions are incompatible. - ---- - -### Function `get_metric_code(...)` - -```python -def get_metric_code(metric: str) -> int: -``` - -Returns the numeric code associated with a distance metric. - -**Parameters:** - -* **metric** (`str`): Name of the metric. Can be "euclidean", "manhattan", "minkowski" or "hamming". - -**Raises** - -* ``ValueError``: If the metric provided is not supported - -**Returns:** - -* ``int``: Numeric code corresponding to the metric. - ---- - -## Validation - -### Function `detect_vector_data_type(...)` - -```python -def detect_vector_data_type( - vector: npt.NDArray -) -> FeatureType: -``` - -Detects the type of data in a given vector. - -This function analyzes the input vector and classifies its data as one of the supported types: - -* **binary**: Boolean values (`True`/`False`) or integer `0`/`1`. -* **continuous**: Float values within the normalized range `[0.0, 1.0]`. -* **ranged**: Float values outside the normalized range. - -**Parameters:** - -* **vector** (`npt.NDArray`): An array containing the data to be classified. - -#### Returns - -* `FeatureType` (`Literal["binary-features", "continuous-features", "ranged-features"]`): The detected type of data in the vector. - -**Raises:** - -* `UnsupportedDataTypeError`: Raised if the vector contains an unsupported data type. - ---- - -### Function `check_array_type(...)` - -```python -def check_array_type(x, name: str = "X") -> npt.NDArray: -``` - -Ensure X is a numpy array. Convert from list if needed. - -**Parameters:** - -* **x** (`Any`): Array, containing the samples and their characteristics. Shape: (``n_samples, n_features``). -* **name** (`str`, default='X'): Variable name used in error messages. - -#### Returns - -* `npt.NDArray`: The converted or validated array. - -**Raises:** - -* `TypeError`: If X or y are not ndarrays or have incompatible shapes. - ---- - -### Function `check_shape_match(...)` - -```python -def check_shape_match(x: npt.NDArray, y: npt.NDArray): -``` - -Ensure X and y have compatible first dimensions. - -**Parameters:** - -* **x** (`npt.NDArray`): Array, containing the samples and their characteristics. Shape: (``n_samples, n_features``). -* **y** (`npt.NDArray`): Array of target classes of `x` with (``n_samples``). - -**Raises:** - -* `TypeError`: If x or y are not ndarrays or have incompatible shapes. - ---- - -### Function `check_feature_dimension(...)` - -```python -def check_feature_dimension(x: npt.NDArray, expected: int): -``` - -Ensure X has the expected number of features. - -**Parameters:** - -* `x` (`npt.NDArray`): Input array for prediction, containing the samples and their characteristics. Shape: (``n_samples, n_features``). -* `expected` (`int`): Expected number of features per sample (columns in X). - -**Raises:** - -* `FeatureDimensionMismatch`: If the number of features in X does not match the expected number. - ---- - -### Function `check_binary_array(...)` - -```python -def check_binary_array(x: npt.NDArray): -``` - -Ensure X contains only 0 and 1. - -**Raises:** - -* `ValueError`: If feature_type is binary-features and X contains values that are not composed only of 0 and 1. - ---- - -## Display - -Utility Functions for Displaying Algorithm Information - -### Function `_supports_box_drawing()` - -```python -def _supports_box_drawing() -> bool: -``` - -Function to check if the terminal supports boxed characters. - -**Returns**: - -* **bool** (`bool`): True if the terminal likely supports boxed characters, False otherwise. - ---- - -### class TableFormatter - -Class to format tabular data into strings for display in the console. - -**Parameters:** - -* **headers** (`Mapping[str, int]`): Mapping of column names to their respective widths, in the format `{column_name: column_width}`. - -**Raises**: - -* `ValueError`: If `headers` is empty or not a valid mapping. - ---- - -#### Function `_border(left, middle, right, line, new_line=True)` - -```python -def _border(self, left: str, middle: str, right: str, line: str, new_line: bool = True) -> str: -``` - -Create a horizontal border for the table. - -**Parameters:** - -* **left** (`str`): Character on the left side of the border. -* **middle** (`str`): Character separator between columns. -* **right** (`str`): Character on the right side of the border. -* **line** (`str`): Character used to fill the border. -* **new_line** (`bool`, optional): If True, adds a line break before the border (default is True). - -**Returns**: - -* **border** (`str`): String representing the horizontal border. - ---- - -#### Function `get_header()` - -```python -def get_header(self) -> str: -``` - -Generate the table header, including the top border, column headings, and separator line. - -**Returns**: - -* **header** (`str`): Formatted string of the table header. - ---- - -#### Function `get_row(values)` - -```python -def get_row(self, values: Mapping[str, Union[str, int, float]]) -> str: -``` - -Generate a formatted row for the table data. - -**Parameters:** - -* **values** (`Mapping[str, Union[str, int, float]]`): Dictionary with values for each column, in the format `{column_name: value}`. - -**Returns**: - -* **row** (`str`): Formatted string of the table row. - ---- - -#### Function `get_bottom(new_line=False)` - -```python -def get_bottom(self, new_line: bool = False) -> str: -``` - -Generate the table's bottom border. - -**Parameters:** - -* **new_line** (`bool`, optional): If True, adds a line break before the border (default is False). - -**Returns**: - -* **bottom** (`str`): Formatted string for the bottom border. - ---- - -### `class ProgressTable(TableFormatter)` - -Class to display a formatted table in the console to track the algorithm's progress. - -**Parameters:** - -* **headers** (`Mapping[str, int]`): Mapping `{column_name: column_width}`. -* **verbose** (`bool`, default=True): If False, prints nothing to the terminal. - -**Raises**: - -* `ValueError`: If `headers` is empty or not a valid mapping. - ---- - -#### Function `_print_header()` - -```python -def _print_header(self) -> None: -``` - -Print the table header. - ---- - -#### Function `update(values)` - -```python -def update(self, values: Mapping[str, Union[str, int, float]]) -> None: -``` - -Add a new row of values to the table. - -**Parameters:** - -* **values** (`Mapping[str, Union[str, int, float]]`): Keys must match the columns defined in headers. - ---- - -#### Function `finish()` - -```python -def finish(self) -> None: -``` - -End the table display, printing the bottom border and total time. - ---- diff --git a/docs/en/api/base/immune/README.md b/docs/en/api/base/immune/README.md index 8b81302..5fbdd56 100644 --- a/docs/en/api/base/immune/README.md +++ b/docs/en/api/base/immune/README.md @@ -13,9 +13,9 @@ Support Module for Artificial Immune Systems. > **Module:** `aisp.base.immune` -## Classes +## Submodules -| Class | Description | +| Module | Description | |-----------------------------------|--------------------------------------------------------------------------------------------| | [`cell`](./cell/README.md) | Representation of immune system cells. | | [`mutation`](./mutation.md) | Functions to generate mutated clones and simulate clonal expansion. | diff --git a/docs/en/api/base/immune/mutation.md b/docs/en/api/base/immune/mutation.md index 0a40c4d..7bd59d9 100644 --- a/docs/en/api/base/immune/mutation.md +++ b/docs/en/api/base/immune/mutation.md @@ -19,7 +19,7 @@ simulating the clonal expansion process in artificial immune systems. > **Module:** `aisp.base.immune` > **Import:** `from aisp.base.immune import mutation` -## Methods +## Functions ### clone_and_mutate_continuous diff --git a/docs/en/api/base/immune/populations.md b/docs/en/api/base/immune/populations.md index 9d59d9b..4efb008 100644 --- a/docs/en/api/base/immune/populations.md +++ b/docs/en/api/base/immune/populations.md @@ -18,7 +18,7 @@ Provide utility functions for generating antibody populations in immunological a > **Module:** `aisp.base.immune` > **Import:** `from aisp.base.immune import populations` -## Methods +## Functions ### generate_random_antibodies diff --git a/docs/en/api/utils/display/README.md b/docs/en/api/utils/display/README.md new file mode 100644 index 0000000..ae58b7e --- /dev/null +++ b/docs/en/api/utils/display/README.md @@ -0,0 +1,24 @@ +--- +id: module-name +sidebar_label: ModuleName +keywords: + - key +tags: + - tag +--- + +# ModuleName + +Utility functions for displaying algorithm information. + +> **Module:** `aisp.utils.display` +> **Import:** `from aisp.utils import display` + +--- + +## Classes + +| Class | Description | +|------------------------------------------|-----------------------------------------------------------------------------| +| [`TableFormatter`](./table-formatter.md) | Format tabular data into strings for display in the console. | +| [`ProgressTable`](./progress-table.md) | Display a formatted table in the console to track the algorithm's progress. | diff --git a/docs/en/api/utils/display/progress-table.md b/docs/en/api/utils/display/progress-table.md new file mode 100644 index 0000000..0d9dd45 --- /dev/null +++ b/docs/en/api/utils/display/progress-table.md @@ -0,0 +1,57 @@ +--- +id: progress-table +sidebar_label: ProgressTable +--- + +# ProgressTable + +Display a formatted table in the console to track the algorithm's progress. + +:::tip[Inheritance] + +This class extends [TableFormatter](./table-formatter.md). + +::: + + +> **Module:** `aisp.utils.display` +> **Import:** `from aisp.utils.display import ProgressTable` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|-----------|---------------------|:-------:|-------------------------------------------| +| `headers` | `Mapping[str, int]` | - | Mapping {column_name: column_width}. | +| `verbose` | `bool` | `True` | If False, prints nothing to the terminal. | + +--- + +## Public Methods + +### update + +````python +def update(self, values: Mapping[str, Union[str, int, float]]) -> None: + ... +```` + +Add a new row of values to the table. + +**Parameters** + +| Name | Type | Default | Description | +|----------|----------------------------------------|:-------:|-------------------------------------------------| +| `values` | `Mapping[str, Union[str, int, float]]` | - | Keys must match the columns defined in headers. | + +--- + +### finish + +````python +def finish(self) -> None: + ... +```` + +End the table display, printing the bottom border and total time. diff --git a/docs/en/api/utils/display/table-formatter.md b/docs/en/api/utils/display/table-formatter.md new file mode 100644 index 0000000..86263aa --- /dev/null +++ b/docs/en/api/utils/display/table-formatter.md @@ -0,0 +1,78 @@ +--- +id: table-formatter +sidebar_label: TableFormatter +--- + +# TableFormatter + +Format tabular data into strings for display in the console. + +> **Module:** `aisp.utils.display` +> **Import:** `from aisp.utils.display import TableFormatter` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|-----------|---------------------|:-------:|------------------------------------------------------------------------------------------------| +| `headers` | `Mapping[str, int]` | - | Mapping of column names to their respective widths, in the format {column_name: column_width}. | + +--- + +## Public Methods + +### get_header + +````python +def get_header(self): + ... +```` + +Generate the table header, including the top border, column headings, and separator line. + +**Returns** + +`str` - Formatted string of the table header. + +--- + +### get_row + +````python +def get_row(self, values: Mapping[str, Union[str, int, float]]): + ... +```` + +Generate a formatted row for the table data. + +**Parameters** + +| Name | Type | Default | Description | +|----------|----------------------------------------|:-------:|-----------------------------------------------------------------------------| +| `values` | `Mapping[str, Union[str, int, float]]` | - | Dictionary with values for each column, in the format {column_name: value}. | + +**Returns** + +`str` - Formatted string of the table row. + +--- + +### get_bottom + +````python +def get_bottom(self, new_line: bool = False): + ... +```` + +Generate the table's bottom border. + +**Parameters** + +| Name | Type | Default | Description | +|------------|--------|:-------:|------------------------------------------------------------------| +| `new_line` | `bool` | `False` | If True, adds a line break before the border (default is False). | + +**Returns** + +`str` - Formatted string for the bottom border. diff --git a/docs/en/api/utils/distance.md b/docs/en/api/utils/distance.md new file mode 100644 index 0000000..015e40c --- /dev/null +++ b/docs/en/api/utils/distance.md @@ -0,0 +1,228 @@ +--- +id: distance +sidebar_label: distance +keywords: + - hamming + - euclidean + - cityblock + - Manhattan + - minkowski + - distance +--- + +# distance + +Utility functions for distance between arrays with numba decorators. + +> **Module:** `aisp.[module]` +> **Import:** `from aisp import [module]` + +## Functions + +### hamming + +````python +@njit([(types.boolean[:], types.boolean[:])], cache=True) +def hamming(u: npt.NDArray[np.bool_], v: npt.NDArray[np.bool_]) -> float64: + ... +```` + +Calculate the Hamming distance between two points. + +$$ +\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} +$$ + +**Parameters** + +| Name | Type | Default | Description | +|------|-------------------------|:-------:|----------------------------------| +| `u` | `npt.NDArray[np.bool_]` | - | Coordinates of the first point. | +| `v` | `npt.NDArray[np.bool_]` | - | Coordinates of the second point. | + +**Returns** + +`float64` - Hamming distance between two points. + +--- + +### euclidean + +````python +@njit() +def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> float64: + ... +```` + +Calculate the Euclidean distance between two points. + +$$ +\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} +$$ + +**Parameters** + +| Name | Type | Default | Description | +|------|------------------------|:-------:|----------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordinates of the first point. | +| `v` | `npt.NDArray[float64]` | - | Coordinates of the second point. | + +**Returns** + +`float64` - Euclidean distance between two points. + +--- + +### cityblock + +````python +@njit() +def cityblock(u: npt.NDArray[float64], v: npt.NDArray[float64]) -> float64: + ... +```` + +Calculate the Manhattan distance between two points. + +$$ +|X_{1} - Y_{1}| + |X_{2} - Y_{2}| + \cdots + |X_{n} - Y_{n}| +$$ + +**Parameters** + +| Name | Type | Default | Description | +|------|------------------------|:-------:|----------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordinates of the first point. | +| `v` | `npt.NDArray[float64]` | - | Coordinates of the second point. | + +**Returns** + +`float64` - Manhattan distance between two points. + +--- + +### minkowski + +````python +@njit() +def minkowski( + u: npt.NDArray[float64], + v: npt.NDArray[float64], + p: float = 2.0 +) -> float64: + ... +```` + +Calculate the Minkowski distance between two points. + +$$ +(|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p}| +$$ + +**Parameters** + +| Name | Type | Default | Description | +|------|------------------------|:-------:|----------------------------------------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordinates of the first point. | +| `v` | `npt.NDArray[float64]` | - | Coordinates of the second point. | +| `p` | `float` | `2.0` | The p parameter defines the type of distance to be calculated. | + +:::note[Parameter `p`] + +- p = 1: **Manhattan** distance - sum of absolute differences. +- p = 2: **Euclidean** distance - sum of squared differences (square root). +- p > 2: **Minkowski** distance with an increasing penalty as p increases. + +::: + +**Returns** + +`float64` - Minkowski distance between two points. + +--- + +### compute_metric_distance + +````python +@njit([(types.float64[:], types.float64[:], types.int32, types.float64)], cache=True) +def compute_metric_distance( + u: npt.NDArray[float64], + v: npt.NDArray[float64], + metric: int, + p: float = 2.0 +) -> float64: + ... +```` + +Calculate the distance between two points by the chosen metric. + +**Parameters** + +| Name | Type | Default | Description | +|----------|------------------------|:-------:|--------------------------------------------------------------------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordinates of the first point. | +| `v` | `npt.NDArray[float64]` | - | Coordinates of the second point. | +| `metric` | `int` | - | Distance metric to be used. Available options: 0 (Euclidean), 1 (Manhattan), 2 (Minkowski) | +| `p` | `float` | `2.0` | The p parameter defines the type of distance to be calculated. | + +**Raises** + +{{ Raise }} - {{ Description }}. + +**Returns** + +`float64` - Distance between the two points with the selected metric. + +--- + +### min_distance_to_class_vectors + +````python +@njit([(types.float64[:, :], types.float64[:], types.int32, types.float64)], cache=True) +def min_distance_to_class_vectors( + x_class: npt.NDArray[float64], + vector_x: npt.NDArray[float64], + metric: int, + p: float = 2.0, +) -> float: + ... +```` + +Calculate the minimum distance between an input vector and the vectors of a class. + +**Parameters** + +| Name | Type | Default | Description | +|------------|------------------------|:-------:|-------------------------------------------------------------------------------------------------------------------| +| `x_class` | `npt.NDArray[float64]` | - | Array containing the class vectors to be compared with the input vector. Expected shape: (n_samples, n_features). | +| `vector_x` | `npt.NDArray[float64]` | - | Vector to be compared with the class vectors. Expected shape: (n_features,). | +| `metric` | `int` | - | Distance metric to be used. Available options: 0 ("euclidean"), 1 ("manhattan"), 2 ("minkowski") or ("hamming") | +| `p` | `float` | `2.0` | Parameter for the Minkowski distance (used only if `metric` is "minkowski"). | + +**Returns** + +**min_distance**: `float` - The minimum distance calculated between the input vector and the class vectors. Returns -1.0 if the input dimensions are incompatible. + +--- + +### get_metric_code + +````python +def get_metric_code(metric: str) -> int: + ... +```` + +Get the numeric code associated with a distance metric. + +**Parameters** + +| Name | Type | Default | Description | +|----------|-------|:-------:|----------------------------------------------------------------------------------------| +| `metric` | `str` | - | Name of the metric. Can be `"euclidean"`, `"manhattan"`, `"minkowski"` or `"hamming"`. | + +**Raises** + +* `ValueError` - If the metric provided is not supported. + +**Returns** + +`int` - Numeric code corresponding to the metric. From b2da15d548f8ef2deb0d69d929b9b54e1ff054b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Mon, 9 Mar 2026 10:19:59 -0300 Subject: [PATCH 22/40] docs(utils): Add documentation for the metrics, multiclass and sanitizers modules. --- aisp/utils/multiclass.py | 6 +- docs/assets/template-docs-class.md | 4 +- docs/assets/template-docs-functions.md | 53 ++++++++- docs/en/api/base/immune/mutation.md | 16 +-- docs/en/api/base/immune/populations.md | 4 +- docs/en/api/utils/display/progress-table.md | 8 +- docs/en/api/utils/display/table-formatter.md | 12 +- docs/en/api/utils/distance.md | 32 +++--- docs/en/api/utils/metrics.md | 43 ++++++++ docs/en/api/utils/multiclass.md | 78 +++++++++++++ docs/en/api/utils/sanitizers.md | 109 +++++++++++++++++++ 11 files changed, 322 insertions(+), 43 deletions(-) create mode 100644 docs/en/api/utils/metrics.md create mode 100644 docs/en/api/utils/multiclass.md create mode 100644 docs/en/api/utils/sanitizers.md diff --git a/aisp/utils/multiclass.py b/aisp/utils/multiclass.py index badf4fe..e382c99 100644 --- a/aisp/utils/multiclass.py +++ b/aisp/utils/multiclass.py @@ -16,12 +16,12 @@ def slice_index_list_by_class(classes: Optional[Union[npt.NDArray, list]], y: np classes: list or npt.NDArray list with unique classes. y : npt.NDArray - Receives a ``y`` (``n_samples``) array with the output classes of the ``X`` sample array. + Receives a `y` (`n_samples`) array with the output classes of the `X` sample array. Returns ------- position_samples : dict - A dictionary with the list of array positions(``y``), with the classes as key. + A dictionary with the list of array positions(`y`), with the classes as key. Examples -------- @@ -59,7 +59,7 @@ def predict_knn_affinity( k: int Number of nearest neighbors to consider for prediction. all_cell_vectors: List[Tuple[Union[str, int], npt.NDArray]] - List of tuples (class_name, cell[np.ndarray]). + List of tuples (class_name, cell(np.ndarray)). affinity_func: Callable[[npt.NDArray, npt.NDArray], float] Function that takes two vectors and returns an affinity value. diff --git a/docs/assets/template-docs-class.md b/docs/assets/template-docs-class.md index a2fa292..e575db4 100644 --- a/docs/assets/template-docs-class.md +++ b/docs/assets/template-docs-class.md @@ -64,12 +64,12 @@ model.method_name() ### method_name -````python +```python def method_name( param_1: type, ) -> type: ... -```` +``` Description. diff --git a/docs/assets/template-docs-functions.md b/docs/assets/template-docs-functions.md index 4f3a60b..feba637 100644 --- a/docs/assets/template-docs-functions.md +++ b/docs/assets/template-docs-functions.md @@ -18,12 +18,61 @@ tags: ### function_name -````python +```python def function_name( param_1: type, ) -> type: ... -```` +``` + +{{ description }} + +**Parameters** + +| Name | Type | Default | Description | +|-----------|--------|:-------:|---------------------------| +| `param_1` | `Type` | - | Description of the param. | + +**Raises** + +{{ Raise }} - {{ Description }}. + +**Returns** + +{{ Type }} - {{ Description }}. + + +--- + +## References + +[^1]: {{ Reference }} +--- +id: module +sidebar_label: module +keywords: + - key +tags: + - tag +--- + +# module + +{{ Brief description of the submodule }} + +> **Module:** `aisp.[module]` +> **Import:** `from aisp import [module]` + +## Functions + +### function_name + +```python +def function_name( + param_1: type, +) -> type: + ... +``` {{ description }} diff --git a/docs/en/api/base/immune/mutation.md b/docs/en/api/base/immune/mutation.md index 7bd59d9..a73d563 100644 --- a/docs/en/api/base/immune/mutation.md +++ b/docs/en/api/base/immune/mutation.md @@ -23,7 +23,7 @@ simulating the clonal expansion process in artificial immune systems. ### clone_and_mutate_continuous -````python +```python @njit([(types.float64[:], types.int64, types.float64)], cache=True) def clone_and_mutate_continuous( vector: npt.NDArray[np.float64], @@ -31,7 +31,7 @@ def clone_and_mutate_continuous( mutation_rate: float ) -> npt.NDArray[np.float64]: ... -```` +``` Generate a set of mutated clones from a cell represented by a continuous vector. @@ -53,7 +53,7 @@ in distinct positions of the original vector. ### clone_and_mutate_binary -````python +```python @njit([(types.boolean[:], types.int64, types.float64)], cache=True) def clone_and_mutate_binary( vector: npt.NDArray[np.bool_], @@ -61,7 +61,7 @@ def clone_and_mutate_binary( mutation_rate: float ) -> npt.NDArray[np.bool_]: ... -```` +``` Generate a set of mutated clones from a cell represented by a binary vector. @@ -84,7 +84,7 @@ immune systems with discrete representations. ### clone_and_mutate_ranged -````python +```python @njit([(types.float64[:], types.int64, types.float64[:, :], types.float64)], cache=True) def clone_and_mutate_ranged( vector: npt.NDArray[np.float64], @@ -93,7 +93,7 @@ def clone_and_mutate_ranged( mutation_rate: float, ) -> npt.NDArray[np.float64]: ... -```` +``` Generate a set of mutated clones from a cell represented by custom ranges per dimension. @@ -117,7 +117,7 @@ will have a random number of mutations applied in distinct positions of the orig ### clone_and_mutate_continuous -````python +```python @njit([(types.int64[:], types.int64, types.float64)], cache=True) def clone_and_mutate_permutation( vector: npt.NDArray[np.int64], @@ -125,7 +125,7 @@ def clone_and_mutate_permutation( mutation_rate: float ) -> npt.NDArray[np.int64]: ... -```` +``` Generate a set of mutated clones by random permutation. diff --git a/docs/en/api/base/immune/populations.md b/docs/en/api/base/immune/populations.md index 4efb008..93141ff 100644 --- a/docs/en/api/base/immune/populations.md +++ b/docs/en/api/base/immune/populations.md @@ -22,7 +22,7 @@ Provide utility functions for generating antibody populations in immunological a ### generate_random_antibodies -````python +```python def generate_random_antibodies( n_samples: int, n_features: int, @@ -30,7 +30,7 @@ def generate_random_antibodies( bounds: Optional[npt.NDArray[np.float64]] = None, ) -> npt.NDArray: ... -```` +``` Generate a random antibody population. diff --git a/docs/en/api/utils/display/progress-table.md b/docs/en/api/utils/display/progress-table.md index 0d9dd45..ba0080d 100644 --- a/docs/en/api/utils/display/progress-table.md +++ b/docs/en/api/utils/display/progress-table.md @@ -32,10 +32,10 @@ This class extends [TableFormatter](./table-formatter.md). ### update -````python +```python def update(self, values: Mapping[str, Union[str, int, float]]) -> None: ... -```` +``` Add a new row of values to the table. @@ -49,9 +49,9 @@ Add a new row of values to the table. ### finish -````python +```python def finish(self) -> None: ... -```` +``` End the table display, printing the bottom border and total time. diff --git a/docs/en/api/utils/display/table-formatter.md b/docs/en/api/utils/display/table-formatter.md index 86263aa..b20bad7 100644 --- a/docs/en/api/utils/display/table-formatter.md +++ b/docs/en/api/utils/display/table-formatter.md @@ -24,10 +24,10 @@ Format tabular data into strings for display in the console. ### get_header -````python +```python def get_header(self): ... -```` +``` Generate the table header, including the top border, column headings, and separator line. @@ -39,10 +39,10 @@ Generate the table header, including the top border, column headings, and separa ### get_row -````python +```python def get_row(self, values: Mapping[str, Union[str, int, float]]): ... -```` +``` Generate a formatted row for the table data. @@ -60,10 +60,10 @@ Generate a formatted row for the table data. ### get_bottom -````python +```python def get_bottom(self, new_line: bool = False): ... -```` +``` Generate the table's bottom border. diff --git a/docs/en/api/utils/distance.md b/docs/en/api/utils/distance.md index 015e40c..ae36d53 100644 --- a/docs/en/api/utils/distance.md +++ b/docs/en/api/utils/distance.md @@ -14,18 +14,18 @@ keywords: Utility functions for distance between arrays with numba decorators. -> **Module:** `aisp.[module]` -> **Import:** `from aisp import [module]` +> **Module:** `aisp.utils.distance` +> **Import:** `from aisp.utils import distance` ## Functions ### hamming -````python +```python @njit([(types.boolean[:], types.boolean[:])], cache=True) def hamming(u: npt.NDArray[np.bool_], v: npt.NDArray[np.bool_]) -> float64: ... -```` +``` Calculate the Hamming distance between two points. @@ -48,11 +48,11 @@ $$ ### euclidean -````python +```python @njit() def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> float64: ... -```` +``` Calculate the Euclidean distance between two points. @@ -75,11 +75,11 @@ $$ ### cityblock -````python +```python @njit() def cityblock(u: npt.NDArray[float64], v: npt.NDArray[float64]) -> float64: ... -```` +``` Calculate the Manhattan distance between two points. @@ -102,7 +102,7 @@ $$ ### minkowski -````python +```python @njit() def minkowski( u: npt.NDArray[float64], @@ -110,7 +110,7 @@ def minkowski( p: float = 2.0 ) -> float64: ... -```` +``` Calculate the Minkowski distance between two points. @@ -142,7 +142,7 @@ $$ ### compute_metric_distance -````python +```python @njit([(types.float64[:], types.float64[:], types.int32, types.float64)], cache=True) def compute_metric_distance( u: npt.NDArray[float64], @@ -151,7 +151,7 @@ def compute_metric_distance( p: float = 2.0 ) -> float64: ... -```` +``` Calculate the distance between two points by the chosen metric. @@ -176,7 +176,7 @@ Calculate the distance between two points by the chosen metric. ### min_distance_to_class_vectors -````python +```python @njit([(types.float64[:, :], types.float64[:], types.int32, types.float64)], cache=True) def min_distance_to_class_vectors( x_class: npt.NDArray[float64], @@ -185,7 +185,7 @@ def min_distance_to_class_vectors( p: float = 2.0, ) -> float: ... -```` +``` Calculate the minimum distance between an input vector and the vectors of a class. @@ -206,10 +206,10 @@ Calculate the minimum distance between an input vector and the vectors of a clas ### get_metric_code -````python +```python def get_metric_code(metric: str) -> int: ... -```` +``` Get the numeric code associated with a distance metric. diff --git a/docs/en/api/utils/metrics.md b/docs/en/api/utils/metrics.md new file mode 100644 index 0000000..6fcd4f5 --- /dev/null +++ b/docs/en/api/utils/metrics.md @@ -0,0 +1,43 @@ +--- +id: metrics +sidebar_label: metrics +keywords: + - accuracy + - score +--- + +# metrics + +Utility functions for measuring accuracy and performance. + +> **Module:** `aisp.utils.metrics` +> **Import:** `from aisp.utils import metrics` + +## Functions + +### accuracy_score + +```python +def accuracy_score( + y_true: Union[npt.NDArray, list], + y_pred: Union[npt.NDArray, list] +) -> float: + ... +``` + +Calculate the accuracy score based on true and predicted labels. + +**Parameters** + +| Name | Type | Default | Description | +|----------|----------------------------|:-------:|-------------------------------------------------------------------------------| +| `y_true` | `Union[npt.NDArray, list]` | - | Ground truth (correct) labels. Expected to be of the same length as `y_pred`. | +| `y_pred` | `Union[npt.NDArray, list]` | - | Predicted labels. Expected to be of the same length as `y_true`. | + +**Raises** + +* `ValueError` - If `y_true` or `y_pred` are empty or if they do not have the same length. + +**Returns** + +**accuracy**: `float` - The ratio of correct predictions to the total number of predictions. diff --git a/docs/en/api/utils/multiclass.md b/docs/en/api/utils/multiclass.md new file mode 100644 index 0000000..f24c155 --- /dev/null +++ b/docs/en/api/utils/multiclass.md @@ -0,0 +1,78 @@ +--- +id: multiclass +sidebar_label: multiclass +keywords: + - k-nearest neighbors + - samples + - slice + - multiclass +--- + +# multiclass + +Utility functions for handling classes with multiple categories. + +> **Module:** `aisp.utils.multiclass` +> **Import:** `from aisp.utils import multiclass` + +## Functions + +### slice_index_list_by_class + +```python +def slice_index_list_by_class(classes: Optional[Union[npt.NDArray, list]], y: npt.NDArray) -> dict: + ... +``` + +Separate indices of samples by class for targeted iteration. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|--------------------------------------|:-------:|-------------------------------------------------------------------------------------| +| `classes` | `Optional[Union[npt.NDArray, list]]` | - | list with unique classes. | +| `y` | `npt.NDArray` | - | Receives a `y` (`n_samples`) array with the output classes of the `X` sample array. | + +**Returns** + +**position_samples**: `dict` - A dictionary with the list of array positions(``y``), with the classes as key. + +**Example** + +```python +import numpy as np +from aisp.utils.multiclass import slice_index_list_by_class + +labels = ['a', 'b', 'c'] +y = np.array(['a', 'c', 'b', 'a', 'c', 'b']) +slice_index_list_by_class(labels, y) +``` + +--- + +### predict_knn_affinity + +```python +def predict_knn_affinity( + X: npt.NDArray, + k: int, + all_cell_vectors: List[Tuple[Union[str, int], npt.NDArray]], + affinity_func: Callable[[npt.NDArray, npt.NDArray], float] +) -> npt.NDArray: + ... +``` + +Predict classes using k-nearest neighbors and trained cells. + +**Parameters** + +| Name | Type | Default | Description | +|--------------------|-----------------------------------------------|:-------:|----------------------------------------------------------------| +| `X` | `npt.NDArray` | - | Input data to be classified. | +| `k` | `int` | - | Number of nearest neighbors to consider for prediction. | +| `all_cell_vectors` | `List[Tuple[Union[str, int], npt.NDArray]]` | - | List of tuples (class_name, cell(np.ndarray)). | +| `affinity_func` | `Callable[[npt.NDArray, npt.NDArray], float]` | - | Function that takes two vectors and returns an affinity value. | + +**Returns** + +**predicted_labels**: `npt.NDArray` - Array of predicted labels for each sample in X, based on the k nearest neighbors. diff --git a/docs/en/api/utils/sanitizers.md b/docs/en/api/utils/sanitizers.md new file mode 100644 index 0000000..eb62e18 --- /dev/null +++ b/docs/en/api/utils/sanitizers.md @@ -0,0 +1,109 @@ +--- +id: sanitizers +sidebar_label: sanitizers +keywords: + - sanitize +--- + +# sanitizers + +Utility functions for validation and treatment of parameters. + +> **Module:** `aisp.utils.sanitizers` +> **Import:** `from aisp.utils import sanitizers` + +## Functions + +### sanitize_choice + +```python +def sanitize_choice(value: T, valid_choices: Iterable[T], default: T) -> T: + ... +``` + +Value if present in the set of valid choices; otherwise, the default value. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|---------------|:-------:|------------------------------------------------------------------------| +| `value` | `T` | - | The value to be checked. | +| `valid_choices` | `Iterable[T]` | - | A collection of valid choices. | +| `default` | `T` | - | The default value to be returned if 'value' is not in 'valid_choices'. | + +**Returns** + +**value** : `T` - The original value if valid, or the default value if not. + +--- + +### sanitize_param + +```python +def sanitize_param(value: T, default: T, condition: Callable[[T], bool]) -> T: + ... +``` + +Value if it satisfies the specified condition; otherwise, the default value. + +**Parameters** + +| Name | Type | Default | Description | +|-------------|-----------------------|:-------:|-----------------------------------------------------------------------------------------| +| `value` | `T` | - | The value to be checked. | +| `default` | `T` | - | The default value to be returned if the condition is not satisfied. | +| `condition` | `Callable[[T], bool]` | - | A function that takes a value and returns a boolean, determining if the value is valid. | + +**Returns** + +**value**: `T` - The original value if the condition is satisfied, or the default value if not. + +--- + +### sanitize_seed + +```python +def sanitize_seed(seed: Any) -> Optional[int]: + ... +``` + +Seed if it is a non-negative integer; otherwise, None. + +**Parameters** + +| Name | Type | Default | Description | +|--------|-------|:-------:|---------------------------------| +| `seed` | `Any` | - | The seed value to be validated. | + +**Returns** + +**seed**: `Optional[int]` - The original seed if it is a non-negative integer, or None if it is invalid. + +--- + +### sanitize_bounds + +```python +def sanitize_bounds( + bounds: Any, problem_size: int +) -> Dict[str, npt.NDArray[np.float64]]: + ... +``` + +Validate and normalize feature bounds. + +**Parameters** + +| Name | Type | Default | Description | +|----------------|-------|:-------:|--------------------------------------------------------------------------------------------------------------| +| `bounds` | `Any` | - | The input bounds, which must be either None or a dictionary with 'low' and 'high' keys. | +| `problem_size` | `int` | - | The expected length for the normalized bounds lists, corresponding to the number of features in the problem. | + +**Raises** + +* `TypeError` - If `bounds` is not None and not a dict with 'low'/'high', or if items are non-numeric. +* `ValueError` - If provided iterables have the wrong length. + +**Returns** + +`Dict[str, list]` - Dictionary `{'low': [low_1, ..., low_N], 'high': [high_1, ..., high_N]}`. From 67cb48401af92571f60e961bbb191d730999e93e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Mon, 9 Mar 2026 12:02:17 -0300 Subject: [PATCH 23/40] docs(utils): Add documentation for the types modules. --- aisp/base/immune/populations.py | 2 +- aisp/utils/types.py | 2 +- docs/en/api/base/immune/cell/b-cell.md | 10 ++--- docs/en/api/base/immune/populations.md | 12 +++--- docs/en/api/csa/clonalg.md | 2 +- docs/en/api/ina/ai-net.md | 30 +++++++------- docs/en/api/utils/types.md | 57 ++++++++++++++++++++++++++ 7 files changed, 86 insertions(+), 29 deletions(-) create mode 100644 docs/en/api/utils/types.md diff --git a/aisp/base/immune/populations.py b/aisp/base/immune/populations.py index d9a1ccd..a67cbf0 100644 --- a/aisp/base/immune/populations.py +++ b/aisp/base/immune/populations.py @@ -23,7 +23,7 @@ def generate_random_antibodies( Number of antibodies (samples) to generate. n_features : int Number of features (dimensions) for each antibody. - feature_type : FeatureType, default="continuous-features" + feature_type : FeatureTypeAll, default="continuous-features" Specifies the type of features: "continuous-features", "binary-features", "ranged-features", or "permutation-features". bounds : npt.NDArray[np.float64], optional diff --git a/aisp/utils/types.py b/aisp/utils/types.py index 7f092f7..6603c3c 100644 --- a/aisp/utils/types.py +++ b/aisp/utils/types.py @@ -8,7 +8,7 @@ - "ranged-features": values defined by intervals. FeatureTypeAll: - Same as ``FeatureType``, plus: + Same as `FeatureType`, plus: - "permutation-features": values represented as permutation. MetricType: diff --git a/docs/en/api/base/immune/cell/b-cell.md b/docs/en/api/base/immune/cell/b-cell.md index 0980287..7e59085 100644 --- a/docs/en/api/base/immune/cell/b-cell.md +++ b/docs/en/api/base/immune/cell/b-cell.md @@ -49,11 +49,11 @@ Clones N features from a cell's features, generating a set of mutated vectors. **Parameters** -| Name | Type | Default | Description | -|----------------|-------------------------------------------------------------------|:-----------------------:|-------------------------------------------------------------------------------------| -| `n` | `int` | - | Number of clones to be generated from mutations of the original cell. | -| `feature_type` | `{ "binary-features", "continuous-features", "ranged-features" }` | `"continuous-features"` | Specifies the type of feature_type to use based on the nature of the input features | -| `bounds` | `Optional[npt.NDArray[np.float64]]` | `None` | Array (n_features, 2) with min and max per dimension. | +| Name | Type | Default | Description | +|----------------|------------------------------------------|:-----------------------:|-------------------------------------------------------------------------------------| +| `n` | `int` | - | Number of clones to be generated from mutations of the original cell. | +| `feature_type` | [`FeatureType`](../../../utils/types.md) | `"continuous-features"` | Specifies the type of feature_type to use based on the nature of the input features | +| `bounds` | `Optional[npt.NDArray[np.float64]]` | `None` | Array (n_features, 2) with min and max per dimension. | **Returns** diff --git a/docs/en/api/base/immune/populations.md b/docs/en/api/base/immune/populations.md index 93141ff..bf8a261 100644 --- a/docs/en/api/base/immune/populations.md +++ b/docs/en/api/base/immune/populations.md @@ -36,12 +36,12 @@ Generate a random antibody population. **Parameters** -| Name | Type | Default | Description | -|----------------|---------------------------|:-----------------------:|-------------------------------------------------------------------------------------------------------------------------| -| `n_samples` | `int` | - | Number of antibodies (samples) to generate. | -| `n_features` | `int` | - | Number of features (dimensions) for each antibody. | -| `feature_type` | `FeatureType` | `"continuous-features"` | Specifies the type of features: "continuous-features", "binary-features", "ranged-features", or "permutation-features". | -| `bounds` | `npt.NDArray[np.float64]` | `None` | Array (n_features, 2) with min and max per dimension. | +| Name | Type | Default | Description | +|----------------|------------------------------------------|:-----------------------:|-------------------------------------------------------------------------------------------------------------------------| +| `n_samples` | `int` | - | Number of antibodies (samples) to generate. | +| `n_features` | `int` | - | Number of features (dimensions) for each antibody. | +| `feature_type` | [`FeatureTypeAll`](../../utils/types.md) | `"continuous-features"` | Specifies the type of features: "continuous-features", "binary-features", "ranged-features", or "permutation-features". | +| `bounds` | `npt.NDArray[np.float64]` | `None` | Array (n_features, 2) with min and max per dimension. | **Raises** diff --git a/docs/en/api/csa/clonalg.md b/docs/en/api/csa/clonalg.md index db976d7..fee4b62 100644 --- a/docs/en/api/csa/clonalg.md +++ b/docs/en/api/csa/clonalg.md @@ -87,7 +87,7 @@ Best cost: 0.02623036956750724 | `n_diversity_injection` | `int` | `5` | Number of new random memory cells injected to maintain diversity. | | `selection_size` | `int` | `5` | Number of the best antibodies selected for cloning. | | `affinity_function` | `Optional[Callable[..., npt.NDArray]]` | `None` | Objective function to evaluate candidate solutions in minimizing the problem. | -| `feature_type` | `FeatureTypeAll` | `'ranged-features'` | Type of problem samples: binary, continuous, or based on value ranges. | +| `feature_type` | [`FeatureTypeAll`](../utils/types.md) | `'ranged-features'` | Type of problem samples: binary, continuous, or based on value ranges. | | `bounds` | `Optional[Dict]` | `None` | Definition of search limits when ``feature_type='ranged-features'``. | | `mode` | `{"min", "max"}` | `'min'` | Defines whether the algorithm minimizes or maximizes the cost function. | | `seed` | `int` | `None` | Seed for random generation of detector values. If None, the value is random. | diff --git a/docs/en/api/ina/ai-net.md b/docs/en/api/ina/ai-net.md index f90aa57..2b7ddfb 100644 --- a/docs/en/api/ina/ai-net.md +++ b/docs/en/api/ina/ai-net.md @@ -77,21 +77,21 @@ print(y_pred) ## Constructor Parameters -| Name | Type | Default | Description | -|----------------------------|-----------------|:-------------:|--------------------------------------------------------------------------------------------------------------------------------------------| -| `N` | `int` | `50` | Number of memory cells (antibodies) in the population. | -| `n_clone` | `int` | `10` | Number of clones generated for each selected memory cell. | -| `top_clonal_memory_size` | `int` | `5` | Number of highest-affinity antibodies selected per antigen for cloning and mutation. | -| `n_diversity_injection` | `int` | `5` | Number of new random memory cells injected to maintain diversity. | -| `affinity_threshold` | `float` | `0.5` | Threshold for affinity (similarity) to determine cell suppression or selection. | -| `suppression_threshold` | `float` | `0.5` | Threshold for suppressing similar memory cells | -| `mst_inconsistency_factor` | `float` | `2.0` | Factor used to determine which edges in the **Minimum Spanning Tree (MST)** are considered inconsistent. | -| `max_iterations` | `int` | `10` | Maximum number of training iterations. | -| `k` | `int` | `3` | The number of K nearest neighbors that will be used to choose a label in the prediction. | -| `metric` | `MetricType` | `"euclidean"` | Distance metric used to compute similarity between memory cells | -| `seed` | `Optional[int]` | `None` | Seed for the random generation of detector values. Defaults to None. | -| `use_mst_clustering` | `bool` | `True` | If ``True``, performs clustering with **Minimum Spanning Tree** (MST). If ``False``, does not perform clustering and predict returns None. | -| `p` | `float` | `2.0` | This parameter stores the value of ``p`` used in the Minkowski distance. | +| Name | Type | Default | Description | +|----------------------------|-----------------------------------|:-------------:|--------------------------------------------------------------------------------------------------------------------------------------------| +| `N` | `int` | `50` | Number of memory cells (antibodies) in the population. | +| `n_clone` | `int` | `10` | Number of clones generated for each selected memory cell. | +| `top_clonal_memory_size` | `int` | `5` | Number of highest-affinity antibodies selected per antigen for cloning and mutation. | +| `n_diversity_injection` | `int` | `5` | Number of new random memory cells injected to maintain diversity. | +| `affinity_threshold` | `float` | `0.5` | Threshold for affinity (similarity) to determine cell suppression or selection. | +| `suppression_threshold` | `float` | `0.5` | Threshold for suppressing similar memory cells | +| `mst_inconsistency_factor` | `float` | `2.0` | Factor used to determine which edges in the **Minimum Spanning Tree (MST)** are considered inconsistent. | +| `max_iterations` | `int` | `10` | Maximum number of training iterations. | +| `k` | `int` | `3` | The number of K nearest neighbors that will be used to choose a label in the prediction. | +| `metric` | [`MetricType`](../utils/types.md) | `"euclidean"` | Distance metric used to compute similarity between memory cells | +| `seed` | `Optional[int]` | `None` | Seed for the random generation of detector values. Defaults to None. | +| `use_mst_clustering` | `bool` | `True` | If ``True``, performs clustering with **Minimum Spanning Tree** (MST). If ``False``, does not perform clustering and predict returns None. | +| `p` | `float` | `2.0` | This parameter stores the value of ``p`` used in the Minkowski distance. | ## Attributes diff --git a/docs/en/api/utils/types.md b/docs/en/api/utils/types.md new file mode 100644 index 0000000..5407f16 --- /dev/null +++ b/docs/en/api/utils/types.md @@ -0,0 +1,57 @@ +--- +id: types +sidebar_label: types +keywords: + - types + - typing + - aliases + - type hints +--- + +# types + +Defines type aliases used throughout the project to improve readability. + +> **Module:** `aisp.utils.types` +> **Import:** `from aisp.utils import types` + +## Type aliases + +### FeatureType + +```python +FeatureType: TypeAlias = Literal[ + "binary-features", "continuous-features", "ranged-features" +] +``` + +Type of input features: +- `"binary-features"`: values like 0 or 1. +- `"continuous-features"`: numeric continuous values. +- `"ranged-features"`: values defined by intervals. + +--- + +### FeatureTypeAll + +```python +FeatureTypeAll: TypeAlias = Union[FeatureType, Literal["permutation-features"]] +``` + +Same as ``FeatureType``, plus: +- `"permutation-features"`: values represented as permutation. + +--- + +### MetricType + +```python +MetricType: TypeAlias = Literal["manhattan", "minkowski", "euclidean"] +``` + +Distance metric used in calculations: +- `"manhattan"`: the Manhattan distance between two points +- `"minkowski"`: the Minkowski distance between two points. +- `"euclidean"`: the Euclidean distance between two points. + +--- \ No newline at end of file From 66e5f8d52707d1693a1024b452245d1f3e96dd9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Mon, 9 Mar 2026 13:44:54 -0300 Subject: [PATCH 24/40] docs(utils): Add documentation for the validation modules. --- aisp/utils/validation.py | 2 +- docs/assets/template-docs-functions.md | 51 +------- docs/en/api/base/immune/cell/b-cell.md | 10 +- docs/en/api/base/immune/populations.md | 12 +- docs/en/api/csa/clonalg.md | 26 ++-- docs/en/api/ina/ai-net.md | 30 ++--- docs/en/api/utils/validation.md | 163 +++++++++++++++++++++++++ 7 files changed, 204 insertions(+), 90 deletions(-) create mode 100644 docs/en/api/utils/validation.md diff --git a/aisp/utils/validation.py b/aisp/utils/validation.py index bd044c4..4b1dc01 100644 --- a/aisp/utils/validation.py +++ b/aisp/utils/validation.py @@ -82,7 +82,7 @@ def check_shape_match(x: npt.NDArray, y: npt.NDArray): Array, containing the samples and their characteristics, Shape: (n_samples, n_features). y : npt.NDArray - Array of target classes of ``x`` with (``n_samples``). + Array of target classes of `x` with (`n_samples`). Raises ------ diff --git a/docs/assets/template-docs-functions.md b/docs/assets/template-docs-functions.md index feba637..9210799 100644 --- a/docs/assets/template-docs-functions.md +++ b/docs/assets/template-docs-functions.md @@ -46,53 +46,4 @@ def function_name( ## References -[^1]: {{ Reference }} ---- -id: module -sidebar_label: module -keywords: - - key -tags: - - tag ---- - -# module - -{{ Brief description of the submodule }} - -> **Module:** `aisp.[module]` -> **Import:** `from aisp import [module]` - -## Functions - -### function_name - -```python -def function_name( - param_1: type, -) -> type: - ... -``` - -{{ description }} - -**Parameters** - -| Name | Type | Default | Description | -|-----------|--------|:-------:|---------------------------| -| `param_1` | `Type` | - | Description of the param. | - -**Raises** - -{{ Raise }} - {{ Description }}. - -**Returns** - -{{ Type }} - {{ Description }}. - - ---- - -## References - -[^1]: {{ Reference }} +[^1]: {{ Reference }} \ No newline at end of file diff --git a/docs/en/api/base/immune/cell/b-cell.md b/docs/en/api/base/immune/cell/b-cell.md index 7e59085..a48fa93 100644 --- a/docs/en/api/base/immune/cell/b-cell.md +++ b/docs/en/api/base/immune/cell/b-cell.md @@ -49,11 +49,11 @@ Clones N features from a cell's features, generating a set of mutated vectors. **Parameters** -| Name | Type | Default | Description | -|----------------|------------------------------------------|:-----------------------:|-------------------------------------------------------------------------------------| -| `n` | `int` | - | Number of clones to be generated from mutations of the original cell. | -| `feature_type` | [`FeatureType`](../../../utils/types.md) | `"continuous-features"` | Specifies the type of feature_type to use based on the nature of the input features | -| `bounds` | `Optional[npt.NDArray[np.float64]]` | `None` | Array (n_features, 2) with min and max per dimension. | +| Name | Type | Default | Description | +|----------------|------------------------------------------------------|:-----------------------:|-------------------------------------------------------------------------------------| +| `n` | `int` | - | Number of clones to be generated from mutations of the original cell. | +| `feature_type` | [`FeatureType`](../../../utils/types.md#featuretype) | `"continuous-features"` | Specifies the type of feature_type to use based on the nature of the input features | +| `bounds` | `Optional[npt.NDArray[np.float64]]` | `None` | Array (n_features, 2) with min and max per dimension. | **Returns** diff --git a/docs/en/api/base/immune/populations.md b/docs/en/api/base/immune/populations.md index bf8a261..0586e00 100644 --- a/docs/en/api/base/immune/populations.md +++ b/docs/en/api/base/immune/populations.md @@ -36,12 +36,12 @@ Generate a random antibody population. **Parameters** -| Name | Type | Default | Description | -|----------------|------------------------------------------|:-----------------------:|-------------------------------------------------------------------------------------------------------------------------| -| `n_samples` | `int` | - | Number of antibodies (samples) to generate. | -| `n_features` | `int` | - | Number of features (dimensions) for each antibody. | -| `feature_type` | [`FeatureTypeAll`](../../utils/types.md) | `"continuous-features"` | Specifies the type of features: "continuous-features", "binary-features", "ranged-features", or "permutation-features". | -| `bounds` | `npt.NDArray[np.float64]` | `None` | Array (n_features, 2) with min and max per dimension. | +| Name | Type | Default | Description | +|----------------|---------------------------------------------------------|:-----------------------:|-------------------------------------------------------------------------------------------------------------------------| +| `n_samples` | `int` | - | Number of antibodies (samples) to generate. | +| `n_features` | `int` | - | Number of features (dimensions) for each antibody. | +| `feature_type` | [`FeatureTypeAll`](../../utils/types.md#featuretypeall) | `"continuous-features"` | Specifies the type of features: "continuous-features", "binary-features", "ranged-features", or "permutation-features". | +| `bounds` | `npt.NDArray[np.float64]` | `None` | Array (n_features, 2) with min and max per dimension. | **Raises** diff --git a/docs/en/api/csa/clonalg.md b/docs/en/api/csa/clonalg.md index fee4b62..bc2788c 100644 --- a/docs/en/api/csa/clonalg.md +++ b/docs/en/api/csa/clonalg.md @@ -78,19 +78,19 @@ Best cost: 0.02623036956750724 ## Constructor Parameters -| Name | Type | Default | Description | -|-------------------------|----------------------------------------|:-------------------:|------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `problem_size` | `int` | - | Dimension of the problem to be minimized. | -| `N` | `int` | `50` | Number of memory cells (antibodies) in the population. | -| `rate_clonal` | `int` | `10` | Maximum number of possible clones of a cell. This value is multiplied by cell_affinity to determine the number of clones. | -| `rate_hypermutation` | `float` | `1.0` | Hypermutation rate controls the intensity of mutations during clonal expansion. Higher values decrease mutation intensity, while lower values increase it. | -| `n_diversity_injection` | `int` | `5` | Number of new random memory cells injected to maintain diversity. | -| `selection_size` | `int` | `5` | Number of the best antibodies selected for cloning. | -| `affinity_function` | `Optional[Callable[..., npt.NDArray]]` | `None` | Objective function to evaluate candidate solutions in minimizing the problem. | -| `feature_type` | [`FeatureTypeAll`](../utils/types.md) | `'ranged-features'` | Type of problem samples: binary, continuous, or based on value ranges. | -| `bounds` | `Optional[Dict]` | `None` | Definition of search limits when ``feature_type='ranged-features'``. | -| `mode` | `{"min", "max"}` | `'min'` | Defines whether the algorithm minimizes or maximizes the cost function. | -| `seed` | `int` | `None` | Seed for random generation of detector values. If None, the value is random. | +| Name | Type | Default | Description | +|-------------------------|------------------------------------------------------|:-------------------:|------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `problem_size` | `int` | - | Dimension of the problem to be minimized. | +| `N` | `int` | `50` | Number of memory cells (antibodies) in the population. | +| `rate_clonal` | `int` | `10` | Maximum number of possible clones of a cell. This value is multiplied by cell_affinity to determine the number of clones. | +| `rate_hypermutation` | `float` | `1.0` | Hypermutation rate controls the intensity of mutations during clonal expansion. Higher values decrease mutation intensity, while lower values increase it. | +| `n_diversity_injection` | `int` | `5` | Number of new random memory cells injected to maintain diversity. | +| `selection_size` | `int` | `5` | Number of the best antibodies selected for cloning. | +| `affinity_function` | `Optional[Callable[..., npt.NDArray]]` | `None` | Objective function to evaluate candidate solutions in minimizing the problem. | +| `feature_type` | [`FeatureTypeAll`](../utils/types.md#featuretypeall) | `'ranged-features'` | Type of problem samples: binary, continuous, or based on value ranges. | +| `bounds` | `Optional[Dict]` | `None` | Definition of search limits when ``feature_type='ranged-features'``. | +| `mode` | `{"min", "max"}` | `'min'` | Defines whether the algorithm minimizes or maximizes the cost function. | +| `seed` | `int` | `None` | Seed for random generation of detector values. If None, the value is random. | ## Attributes diff --git a/docs/en/api/ina/ai-net.md b/docs/en/api/ina/ai-net.md index 2b7ddfb..35d2af7 100644 --- a/docs/en/api/ina/ai-net.md +++ b/docs/en/api/ina/ai-net.md @@ -77,21 +77,21 @@ print(y_pred) ## Constructor Parameters -| Name | Type | Default | Description | -|----------------------------|-----------------------------------|:-------------:|--------------------------------------------------------------------------------------------------------------------------------------------| -| `N` | `int` | `50` | Number of memory cells (antibodies) in the population. | -| `n_clone` | `int` | `10` | Number of clones generated for each selected memory cell. | -| `top_clonal_memory_size` | `int` | `5` | Number of highest-affinity antibodies selected per antigen for cloning and mutation. | -| `n_diversity_injection` | `int` | `5` | Number of new random memory cells injected to maintain diversity. | -| `affinity_threshold` | `float` | `0.5` | Threshold for affinity (similarity) to determine cell suppression or selection. | -| `suppression_threshold` | `float` | `0.5` | Threshold for suppressing similar memory cells | -| `mst_inconsistency_factor` | `float` | `2.0` | Factor used to determine which edges in the **Minimum Spanning Tree (MST)** are considered inconsistent. | -| `max_iterations` | `int` | `10` | Maximum number of training iterations. | -| `k` | `int` | `3` | The number of K nearest neighbors that will be used to choose a label in the prediction. | -| `metric` | [`MetricType`](../utils/types.md) | `"euclidean"` | Distance metric used to compute similarity between memory cells | -| `seed` | `Optional[int]` | `None` | Seed for the random generation of detector values. Defaults to None. | -| `use_mst_clustering` | `bool` | `True` | If ``True``, performs clustering with **Minimum Spanning Tree** (MST). If ``False``, does not perform clustering and predict returns None. | -| `p` | `float` | `2.0` | This parameter stores the value of ``p`` used in the Minkowski distance. | +| Name | Type | Default | Description | +|----------------------------|----------------------------------------------|:-------------:|--------------------------------------------------------------------------------------------------------------------------------------------| +| `N` | `int` | `50` | Number of memory cells (antibodies) in the population. | +| `n_clone` | `int` | `10` | Number of clones generated for each selected memory cell. | +| `top_clonal_memory_size` | `int` | `5` | Number of highest-affinity antibodies selected per antigen for cloning and mutation. | +| `n_diversity_injection` | `int` | `5` | Number of new random memory cells injected to maintain diversity. | +| `affinity_threshold` | `float` | `0.5` | Threshold for affinity (similarity) to determine cell suppression or selection. | +| `suppression_threshold` | `float` | `0.5` | Threshold for suppressing similar memory cells | +| `mst_inconsistency_factor` | `float` | `2.0` | Factor used to determine which edges in the **Minimum Spanning Tree (MST)** are considered inconsistent. | +| `max_iterations` | `int` | `10` | Maximum number of training iterations. | +| `k` | `int` | `3` | The number of K nearest neighbors that will be used to choose a label in the prediction. | +| `metric` | [`MetricType`](../utils/types.md#metrictype) | `"euclidean"` | Distance metric used to compute similarity between memory cells | +| `seed` | `Optional[int]` | `None` | Seed for the random generation of detector values. Defaults to None. | +| `use_mst_clustering` | `bool` | `True` | If ``True``, performs clustering with **Minimum Spanning Tree** (MST). If ``False``, does not perform clustering and predict returns None. | +| `p` | `float` | `2.0` | This parameter stores the value of ``p`` used in the Minkowski distance. | ## Attributes diff --git a/docs/en/api/utils/validation.md b/docs/en/api/utils/validation.md new file mode 100644 index 0000000..78de0ca --- /dev/null +++ b/docs/en/api/utils/validation.md @@ -0,0 +1,163 @@ +--- +id: validation +sidebar_label: validation +keywords: + - validation +--- + +# module + +Contains functions responsible for validating data types. + +> **Module:** `aisp.utils.validation` +> **Import:** `from aisp.utils import validation` + +## Functions + +### detect_vector_data_type + +```python +def detect_vector_data_type(vector: npt.NDArray) -> FeatureType: + ... +``` + +Detect the type of data in a vector. + +The function detects if the vector contains data of type: +- Binary features: boolean values or integers restricted to 0 and 1. +- Continuous features: floating-point values in the normalized range [0.0, 1.0]. +- Ranged features: floating-point values outside the normalized range. + +**Parameters** + +| Name | Type | Default | Description | +|----------|---------------|:-------:|------------------------------------------------| +| `vector` | `npt.NDArray` | - | An array containing the data to be classified. | + +**Raises** + +* `UnsupportedTypeError` - If the data type of the vector is not supported by the function. + +**Returns** + +[`FeatureType`](./types.md#featuretype) - The data type of the vector: "binary-features", "continuous-features", or "ranged-features". + +--- + +### check_array_type + +```python +def check_array_type(x, name: str = "X") -> npt.NDArray: + ... +``` + +Ensure X is a numpy array. Convert from list if needed. + +**Parameters** + +| Name | Type | Default | Description | +|--------|-------|:-------:|------------------------------------------------------------------------------------------| +| `x` | `Any` | - | Array, containing the samples and their characteristics, Shape: (n_samples, n_features). | +| `name` | `str` | `'X'` | Variable name used in error messages. | + +**Raises** + +* `TypeError` - If X or y are not ndarrays or a list. + +**Returns** + +`npt.NDArray` - The converted or validated array + +--- + +### check_shape_match + +```python +def check_shape_match(x: npt.NDArray, y: npt.NDArray): + ... +``` + +Ensure X and y have compatible first dimensions. + +**Parameters** + +| Name | Type | Default | Description | +|------|---------------|:-------:|------------------------------------------------------------------------------------------| +| `x` | `npt.NDArray` | - | Array, containing the samples and their characteristics, Shape: (n_samples, n_features). | +| `y` | `npt.NDArray` | - | Array of target classes of `x` with (`n_samples`). | + +**Raises** + +* `TypeError` - If x or y have incompatible shapes. + +--- + +### check_feature_dimension + +```python +def check_feature_dimension(x: npt.NDArray, expected: int): + ... +``` + +Ensure X has the expected number of features. + +**Parameters** + +| Name | Type | Default | Description | +|------------|---------------|:-------:|---------------------------------------------------------------------------------------------------------------| +| `x` | `npt.NDArray` | - | Input array for prediction, containing the samples and their characteristics, Shape: (n_samples, n_features). | +| `expected` | `int` | - | Expected number of features per sample (columns in X). | + +**Raises** + +* `FeatureDimensionMismatch` - If the number of features in X does not match the expected number. + +--- + +### check_binary_array + +```python +def check_binary_array(x: npt.NDArray): + ... +``` + +Ensure X contains only 0 and 1. + +**Parameters** + +| Name | Type | Default | Description | +|------|---------------|:-------:|--------------------------------| +| `x` | `npt.NDArray` | - | Array, containing the samples. | + +**Raises** + +* `ValueError` - If the array contains values other than 0 and 1. + +--- + +### check_value_range + +```python +def check_value_range( + x: npt.NDArray, + name: str = 'X', + min_value: float = 0.0, + max_value: float = 1.0 +) -> None: + ... +``` + +Ensure all values in the x array fall within a range. + +**Parameters** + +| Name | Type | Default | Description | +|-------------|---------------|:-------:|---------------------------------| +| `x` | `npt.NDArray` | - | Array, containing the samples. | +| `name` | `str` | `'X'` | Name used in the error message. | +| `min_value` | `float` | `0.0` | Minimum allowed value. | +| `max_value` | `float` | `1.0` | Maximum allowed value. | + +**Raises** + +* `ValueError` - If the array fall outside the interval (min_value, max_value). From d30469d196dd399a129504cbbbb49c102ff848ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Mon, 9 Mar 2026 18:19:00 -0300 Subject: [PATCH 25/40] docs(utils): Add documentation. --- docs/en/api/README.md | 16 ++++++++++++++-- docs/en/api/utils/README.md | 29 +++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) create mode 100644 docs/en/api/utils/README.md diff --git a/docs/en/api/README.md b/docs/en/api/README.md index e270168..eef3233 100644 --- a/docs/en/api/README.md +++ b/docs/en/api/README.md @@ -28,7 +28,7 @@ Fundamental abstractions and base classes that define core interfaces of package Core structures and support utilities for implementations immune. -| Class | Description | +| Module | Description | |-----------------------------------------------|--------------------------------------------------------------------------------------------| | [`cell`](./base/immune/cell/README.md) | Representation of immune system cells. | | [`mutation`](./base/immune/mutation.md) | Functions to generate mutated clones and simulate clonal expansion. | @@ -64,4 +64,16 @@ Algorithms based on Network Theory Algorithms proposed by Jerne. |------------------------|--------------------------------------------------------------------------------------------| | [`AiNet`](./ai-net.md) | An unsupervised learning algorithm for clustering, based on the theory of immune networks. | -## Utils (`aisp.utils`) \ No newline at end of file +## Utils ([`aisp.utils`](./utils/README.md)) + +Utility functions and helpers for development. + +| Module | Description | +|----------------------------------------|--------------------------------------------------------------------------| +| [`display`](./utils/display/README.md) | Utility functions for displaying algorithm information. | +| [`distance`](./utils/distance.md) | Utility functions for distance between arrays with numba decorators. | +| [`metrics`](./utils/metrics.md) | Utility functions for measuring accuracy and performance. | +| [`multiclass`](./utils/multiclass.md) | Utility functions for handling classes with multiple categories. | +| [`sanitizers`](./utils/sanitizers.md) | Utility functions for validation and treatment of parameters. | +| [`types`](./utils/types.md) | Defines type aliases used throughout the project to improve readability. | +| [`validation`](./utils/validation.md) | Contains functions responsible for validating data types. | \ No newline at end of file diff --git a/docs/en/api/utils/README.md b/docs/en/api/utils/README.md new file mode 100644 index 0000000..eae04d5 --- /dev/null +++ b/docs/en/api/utils/README.md @@ -0,0 +1,29 @@ +--- +id: utils +sidebar_label: utils +keywords: + - functions + - helpers + - utils +--- + +# utils + +Utility functions and helpers for development. + +> **Module:** `aisp.utils` +> **Import:** `from aisp import utils` + + +## Submodules + +| Module | Description | +|----------------------------------|--------------------------------------------------------------------------| +| [`display`](./display/README.md) | Utility functions for displaying algorithm information. | +| [`distance`](./distance.md) | Utility functions for distance between arrays with numba decorators. | +| [`metrics`](./metrics.md) | Utility functions for measuring accuracy and performance. | +| [`multiclass`](./multiclass.md) | Utility functions for handling classes with multiple categories. | +| [`sanitizers`](./sanitizers.md) | Utility functions for validation and treatment of parameters. | +| [`types`](./types.md) | Defines type aliases used throughout the project to improve readability. | +| [`validation`](./validation.md) | Contains functions responsible for validating data types. | + From 0a4c321137d289691d861b2519edac954662e985 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Mon, 9 Mar 2026 18:35:07 -0300 Subject: [PATCH 26/40] fix(docs): corrects documentation compatibility with docusaurus. --- aisp/utils/display.py | 6 +++--- docs/en/api/utils/display/README.md | 11 +++++------ docs/en/api/utils/display/progress-table.md | 2 +- docs/en/api/utils/display/table-formatter.md | 8 ++++---- 4 files changed, 13 insertions(+), 14 deletions(-) diff --git a/aisp/utils/display.py b/aisp/utils/display.py index 0c6885e..d72f39a 100644 --- a/aisp/utils/display.py +++ b/aisp/utils/display.py @@ -35,7 +35,7 @@ class TableFormatter: ---------- headers : Mapping[str, int] Mapping of column names to their respective widths, in the format - {column_name: column_width}. + `{column_name: column_width}`. """ def __init__(self, headers: Mapping[str, int]) -> None: @@ -108,7 +108,7 @@ def get_row(self, values: Mapping[str, Union[str, int, float]]): ---------- values : Mapping[str, Union[str, int, float]] Dictionary with values for each column, in the format - {column_name: value}. + `{column_name: value}`. Returns ------- @@ -154,7 +154,7 @@ class ProgressTable(TableFormatter): Parameters ---------- headers : Mapping[str, int] - Mapping {column_name: column_width}. + Mapping `{column_name: column_width}`. verbose : bool, default=True If False, prints nothing to the terminal. """ diff --git a/docs/en/api/utils/display/README.md b/docs/en/api/utils/display/README.md index ae58b7e..6625dc7 100644 --- a/docs/en/api/utils/display/README.md +++ b/docs/en/api/utils/display/README.md @@ -1,13 +1,12 @@ --- -id: module-name -sidebar_label: ModuleName +id: display +sidebar_label: display keywords: - - key -tags: - - tag + - table + - progress --- -# ModuleName +# display Utility functions for displaying algorithm information. diff --git a/docs/en/api/utils/display/progress-table.md b/docs/en/api/utils/display/progress-table.md index ba0080d..7823ef2 100644 --- a/docs/en/api/utils/display/progress-table.md +++ b/docs/en/api/utils/display/progress-table.md @@ -23,7 +23,7 @@ This class extends [TableFormatter](./table-formatter.md). | Name | Type | Default | Description | |-----------|---------------------|:-------:|-------------------------------------------| -| `headers` | `Mapping[str, int]` | - | Mapping {column_name: column_width}. | +| `headers` | `Mapping[str, int]` | - | Mapping `{column_name: column_width}`. | | `verbose` | `bool` | `True` | If False, prints nothing to the terminal. | --- diff --git a/docs/en/api/utils/display/table-formatter.md b/docs/en/api/utils/display/table-formatter.md index b20bad7..a3655db 100644 --- a/docs/en/api/utils/display/table-formatter.md +++ b/docs/en/api/utils/display/table-formatter.md @@ -16,7 +16,7 @@ Format tabular data into strings for display in the console. | Name | Type | Default | Description | |-----------|---------------------|:-------:|------------------------------------------------------------------------------------------------| -| `headers` | `Mapping[str, int]` | - | Mapping of column names to their respective widths, in the format {column_name: column_width}. | +| `headers` | `Mapping[str, int]` | - | Mapping of column names to their respective widths, in the format `{column_name: column_width}`. | --- @@ -48,9 +48,9 @@ Generate a formatted row for the table data. **Parameters** -| Name | Type | Default | Description | -|----------|----------------------------------------|:-------:|-----------------------------------------------------------------------------| -| `values` | `Mapping[str, Union[str, int, float]]` | - | Dictionary with values for each column, in the format {column_name: value}. | +| Name | Type | Default | Description | +|----------|----------------------------------------|:-------:|-------------------------------------------------------------------------------| +| `values` | `Mapping[str, Union[str, int, float]]` | - | Dictionary with values for each column, in the format `{column_name: value}`. | **Returns** From a489dbb9b645c8774bfd94bc0d82bcf19ee5cf81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Mon, 9 Mar 2026 19:01:29 -0300 Subject: [PATCH 27/40] docs: remove old documentation in Portuguese --- docs/en/index.md | 10 - docs/pt-br/README.md | 26 +- docs/pt-br/advanced-guides/base/base.md | 44 -- docs/pt-br/advanced-guides/base/classifier.md | 88 --- docs/pt-br/advanced-guides/base/clusterer.md | 79 --- .../pt-br/advanced-guides/base/immune/cell.md | 96 --- .../advanced-guides/base/immune/mutation.md | 115 ---- .../base/immune/populations.md | 28 - docs/pt-br/advanced-guides/base/optimizer.md | 160 ----- .../core/Negative Selection.md | 93 --- docs/pt-br/advanced-guides/utils.md | 609 ------------------ .../Clonal Selection Algorithms/AIRS.md | 280 -------- .../Clonal Selection Algorithms/Clonalg.md | 183 ------ .../Clonal Selection Algorithms/README.md | 24 - docs/pt-br/classes/Negative Selection/BNSA.md | 111 ---- .../classes/Negative Selection/README.md | 29 - docs/pt-br/classes/Negative Selection/RNSA.md | 217 ------- .../Network Theory Algorithms/AiNet.md | 271 -------- .../Network Theory Algorithms/README.md | 16 - docs/pt-br/index.md | 10 - 20 files changed, 21 insertions(+), 2468 deletions(-) delete mode 100644 docs/en/index.md delete mode 100644 docs/pt-br/advanced-guides/base/base.md delete mode 100644 docs/pt-br/advanced-guides/base/classifier.md delete mode 100644 docs/pt-br/advanced-guides/base/clusterer.md delete mode 100644 docs/pt-br/advanced-guides/base/immune/cell.md delete mode 100644 docs/pt-br/advanced-guides/base/immune/mutation.md delete mode 100644 docs/pt-br/advanced-guides/base/immune/populations.md delete mode 100644 docs/pt-br/advanced-guides/base/optimizer.md delete mode 100644 docs/pt-br/advanced-guides/core/Negative Selection.md delete mode 100644 docs/pt-br/advanced-guides/utils.md delete mode 100644 docs/pt-br/classes/Clonal Selection Algorithms/AIRS.md delete mode 100644 docs/pt-br/classes/Clonal Selection Algorithms/Clonalg.md delete mode 100644 docs/pt-br/classes/Clonal Selection Algorithms/README.md delete mode 100644 docs/pt-br/classes/Negative Selection/BNSA.md delete mode 100644 docs/pt-br/classes/Negative Selection/README.md delete mode 100644 docs/pt-br/classes/Negative Selection/RNSA.md delete mode 100644 docs/pt-br/classes/Network Theory Algorithms/AiNet.md delete mode 100644 docs/pt-br/classes/Network Theory Algorithms/README.md delete mode 100644 docs/pt-br/index.md diff --git a/docs/en/index.md b/docs/en/index.md deleted file mode 100644 index bceec53..0000000 --- a/docs/en/index.md +++ /dev/null @@ -1,10 +0,0 @@ -##

**INDEX**

- ---- - -### Class module: - -> 1. [**Negative selection**](classes/Negative%20Selection/README.md) -> 2. **Danger Theory** -> 3. [**Clonal Selection Algorithms.**](classes/Clonal%20Selection%20Algorithms/README.md) -> 4. [**Immune Network Theory**](classes/Network%20Theory%20Algorithms/README.md) \ No newline at end of file diff --git a/docs/pt-br/README.md b/docs/pt-br/README.md index cef61ec..8ba12cf 100644 --- a/docs/pt-br/README.md +++ b/docs/pt-br/README.md @@ -1,13 +1,29 @@ +

+ +![Artificial Immune Systems Package](../assets/logos/logo.svg) + +# Artificial Immune Systems Package. + +
+ +--- + ## Sumário ->1. [Introdução.](#introdução) ->2. [Instalação.](#instalação) -> 1. [Dependências](#dependências) -> 2. [Instalação do usuário](#instalação-do-usuário) ->3. [Exemplos.](#exemplos) +1. [Introdução.](#introdução) +2. [Instalação.](#instalação) + 1. [Dependências](#dependências) + 2. [Instalação do usuário](#instalação-do-usuário) +3. [Exemplos.](#exemplos) --- +## Introdução + +**AISP (Artificial Immune Systems Package)** é um pacote pacote python com algoritmos imunoinspirados, os quaios aplicam +metáforas + +
## Introdução diff --git a/docs/pt-br/advanced-guides/base/base.md b/docs/pt-br/advanced-guides/base/base.md deleted file mode 100644 index 97fc376..0000000 --- a/docs/pt-br/advanced-guides/base/base.md +++ /dev/null @@ -1,44 +0,0 @@ -# Classe Base - -Classe base para introspecção de parâmetros compatível com a API do scikit-learn. - -## Base - -Classe genérica para modelos com uma interface comum. -Fornece os métodos `get_params` e `set_params` para compatibilidade com a API do scikit-learn, permitindo acesso aos parâmetros públicos do modelo. - -### Função set_params(...) - -```python -def set_params(self, **params) -> Base: -``` - -Define os parâmetros da instância. Garante compatibilidade com funções do scikit-learn. - -**Parâmetros:** - -* **params** (`dict`): Dicionário de parâmetros que serão definidos como atributos da instância. Apenas atributos públicos (que não começam com "_") são modificados. - -**Retorna:** - -* **Base**: Retorna a própria instância após definir os parâmetros. - ---- - -### Função get_params(...) - -```python -def get_params(self, deep: bool = True) -> dict -``` - -Retorna um dicionário com os principais parâmetros do objeto. Garante compatibilidade com funções do scikit-learn. - -**Parâmetros:** - -* **deep** (`bool`, padrão=True): Ignorado nesta implementação, mas incluído para compatibilidade com scikit-learn. - -**Retorna:** - -* **dict:** Dicionário contendo os atributos do objeto que não começam com "_". - ---- diff --git a/docs/pt-br/advanced-guides/base/classifier.md b/docs/pt-br/advanced-guides/base/classifier.md deleted file mode 100644 index a833c32..0000000 --- a/docs/pt-br/advanced-guides/base/classifier.md +++ /dev/null @@ -1,88 +0,0 @@ -Classe base para algoritmo de classificação. - -# BaseClassifier - -Classe base para algoritmos de classificação, definindo os métodos abstratos ``fit`` e ``predict``. - -## Métodos - -### Método `score(...)` - -```python -def score( - self, - X: Union[npt.NDArray, list], - y: Union[npt.NDArray, list] -) -> float: -``` - -A função de pontuação (score) calcula a precisão da previsão. - -Esta função realiza a previsão de X e verifica quantos elementos são iguais entre o vetor y e y_predicted. -Esta função foi adicionada para compatibilidade com algumas funções do scikit-learn. - -**Parâmetros**: - -* **X** (`Union[npt.NDArray, list]`): Conjunto de características com formato (n_amostras, n_características). -* **y** (`Union[npt.NDArray, list]`): Valores verdadeiros com formato (n_amostras,). - -**Retorna:** - -* precisão (`float`): A precisão do modelo. - ---- - -### Método `_slice_index_list_by_class(...)` - -A função ``_slice_index_list_by_class(...)``, separa os índices das linhas conforme a classe de saída, para percorrer o array de amostra, apenas nas posições que a saída for a classe que está sendo treinada: - -```python -def _slice_index_list_by_class(self, y: npt.NDArray) -> dict: -``` - -**Parâmetros**: - -* **y** (`npt.NDArray`): Recebe um array ``n_samples`` com as classes de saída do array de amostras ``X``. - -**Retorna:** - -Retorna um dicionário com as classes como chave e os índices em ``X`` das amostras. - ---- - -## Métodos abstratos - -### Método `fit(...)` - -```python -@abstractmethod -def fit( - self, - X: Union[npt.NDArray, list], - y: Union[npt.NDArray, list], - verbose: bool = True -) -> BaseClassifier: -``` - -Ajusta o modelo aos dados de treinamento. - -Implementação: - -* [RNSA](../../classes/Negative%20Selection/RNSA.md#método-fit) -* [BNSA](../../classes/Negative%20Selection/BNSA.md#método-fit) -* [AIRS](../../classes/Clonal%20Selection%20Algorithms/AIRS.md#método-fit) - -### Método `predict(...)` - -```python -@abstractmethod -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -Realiza a previsão dos rótulos para os dados fornecidos. - -Implementação: - -* [RNSA](../../classes/Negative%20Selection/RNSA.md#método-predict) -* [BNSA](../../classes/Negative%20Selection/BNSA.md#método-predict) -* [AIRS](../../classes/Clonal%20Selection%20Algorithms/AIRS.md#método-predict) diff --git a/docs/pt-br/advanced-guides/base/clusterer.md b/docs/pt-br/advanced-guides/base/clusterer.md deleted file mode 100644 index c1ff15d..0000000 --- a/docs/pt-br/advanced-guides/base/clusterer.md +++ /dev/null @@ -1,79 +0,0 @@ -# BaseClusterer - -Classe base abstrata para algoritmos de clustering. - -Esta classe define a interface central para modelos de agrupamento. Ela exige -a implementação dos métodos **`fit`** e **`predict`** em todas as classes derivadas, -e fornece uma implementação padrão para **`fit_predict`** e **`get_params`**. - ---- - -## Métodos abstratos - -### Método `fit(...)` - -```python -@abstractmethod -def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> BaseClusterer: -``` - -Ajusta o modelo aos dados de treinamento. -Este método abstrato deve ser implementado pelas subclasses. - -**Parâmetros:** - -* **X** (`Union[npt.NDArray, list]`): Dados de entrada utilizados para treinar o modelo. -* **verbose** (`bool`): default=True - Indica se a saída detalhada durante o treinamento deve ser exibida. - -**Retorna:** - -* **self:** `BaseClusterer` - Instância da classe que implementa este método. - -**Implementações:** - -* [AiNet](../../../classes/Immune%20Network%20Theory/AiNet.md#método-fit) - ---- - -### Método `predict(...)` - -```python -@abstractmethod -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -Gera previsões com base nos dados de entrada. -Este método abstrato deve ser implementado pelas subclasses. - -**Parâmetros:** - -* **X** (`Union[npt.NDArray, list]`): Dados de entrada para os quais as previsões serão geradas. - -**Retorna:** - -* **predictions** (`npt.NDArray`): Rótulos previstos dos clusters para cada amostra de entrada. - -**Implementações:** - -* [AiNet](../../../classes/Immune%20Network%20Theory/AiNet.md#método-predict) - ---- - -## Métodos - -### Método `fit_predict(...)` - -```python -def fit_predict(self, X: Union[npt.NDArray, list], verbose: bool = True) -> npt.NDArray: -``` - -Método de conveniência que combina `fit` e `predict` em uma única chamada. - -**Parâmetros:** - -* **X** (`Union[npt.NDArray, list]`): Dados de entrada para os quais as previsões serão geradas. -* **verbose** (`bool`, default=True): Indica se a saída detalhada durante o treinamento deve ser exibida. - -**Retorna:** - -* **predictions** (`npt.NDArray`): Rótulos previstos dos clusters para cada amostra de entrada. \ No newline at end of file diff --git a/docs/pt-br/advanced-guides/base/immune/cell.md b/docs/pt-br/advanced-guides/base/immune/cell.md deleted file mode 100644 index 90b9024..0000000 --- a/docs/pt-br/advanced-guides/base/immune/cell.md +++ /dev/null @@ -1,96 +0,0 @@ -# Cell Classes - -Representação de células do sistema imunológico. - -## Cell - -Representa uma célula imune básica. - -```python -@dataclass(slots=True) -class Cell: - vector: np.ndarray -``` - -### Atributos -* **vector** (`np.ndarray`): Um vetor de características da célula. - -### Métodos -* `__eq__(other)`: Verifica se duas células são iguais com base em seus vetores. -* `__array__()`: Interface de array para NumPy, permite que a instância seja tratada como um `np.ndarray`. -* `__getitem__(item)`: Obtém elementos do vetor de características usando indexação. - ---- - -## BCell - -Representa uma célula B de memória, derivada de `Cell`. - -```python -@dataclass(slots=True, eq=False) -class BCell(Cell): - vector: np.ndarray -``` - -### Métodos - -### hyper_clonal_mutate(...) - -```python -def hyper_clonal_mutate( - self, - n: int, - feature_type: FeatureType = "continuous-features", - bounds: Optional[npt.NDArray[np.float64]] = None -) -> npt.NDArray: -``` - -Clona N características das características de uma célula, gerando um conjunto de vetores mutados. - -#### Parâmetros -* **n** (`int`): Número de clones a serem gerados a partir de mutações da célula original. -* **feature_type** (`FeatureType`, padrão="continuous-features"): Especifica o tipo de características com base na natureza das características de entrada. -* **bounds** (`Optional[npt.NDArray[np.float64]]`, padrão=None): Array (n_features, 2) com mínimo e máximo por dimensão. - -#### Retorna -* **npt.NDArray**: Um array contendo N vetores mutados da célula original. - ---- - -## Antibody - -Representa um anticorpo com afinidade, derivado de `Cell`. - -```python -@dataclass(slots=True) -class Antibody(Cell): - vector: np.ndarray - affinity: float -``` - -### Atributos -* **vector** (`npt.NDArray`): Um vetor de características da célula. -* **affinity** (`float`): Valor de afinidade do anticorpo. - -### Métodos -* `__lt__(other)`: Compara este anticorpo com outro com base na afinidade. -* `__eq__(other)`: Verifica se dois anticorpos têm a mesma afinidade. - ---- - -## Detector - -Representa um detector não-próprio da classe RNSA. - -```python -@dataclass(slots=True) -class Detector: - position: npt.NDArray[np.float64] - radius: Optional[float] = None -``` - -### Atributos -* **position** (`npt.NDArray[np.float64]`): Vetor de características do detector. -* **radius** (`Optional[float]`): Raio do detector, usado no algoritmo V-detector. - ---- \ No newline at end of file diff --git a/docs/pt-br/advanced-guides/base/immune/mutation.md b/docs/pt-br/advanced-guides/base/immune/mutation.md deleted file mode 100644 index e5504d8..0000000 --- a/docs/pt-br/advanced-guides/base/immune/mutation.md +++ /dev/null @@ -1,115 +0,0 @@ -# Mutation - -Contém funções que geram conjuntos de clones mutados a partir de vetores contínuos ou binários, simulando o processo de expansão clonal em sistemas imunológicos artificiais. - -## clone_and_mutate_continuous - -```python -@njit([(types.float64[:], types.int64, types.float64)], cache=True) -def clone_and_mutate_continuous( - vector: npt.NDArray[np.float64], - n: int, - mutation_rate: float -) -> npt.NDArray[np.float64]: -``` - -Gera um conjunto de clones mutados a partir de um vetor contínuo. - -Esta função cria `n` clones do vetor de entrada e aplica mutações aleatórias em cada um, simulando o processo de expansão clonal em sistemas imunes artificiais. Cada clone recebe um número aleatório de mutações em posições distintas do vetor original. - -### Parâmetros - -* **vector** (`npt.NDArray[np.float64]`): Vetor contínuo original que representa a célula imune a ser clonada e mutada. -* **n** (`int`): Quantidade de clones mutados a serem gerados. -* **mutation_rate** : (`float`) Se 0 <= mutation_rate < 1: probabilidade de mutação de cada componente. - Se mutation_rate >= 1 ou mutation_rate <= 0: a mutação aleatoriza a quantidade de componentes entre 1 e len(vector). - - -### Retorno - -* `clone_set` (`npt.NDArray[np.float64]`): Array com forma `(n, len(vector))` contendo os `n` clones mutados do vetor original. - ---- - -## clone_and_mutate_binary - -```python -@njit([(types.boolean[:], types.int64, types.float64)], cache=True) -def clone_and_mutate_binary( - vector: npt.NDArray[np.bool_], - n: int, - mutation_rate: float -) -> npt.NDArray[np.bool_]: -``` - -Gera um conjunto de clones mutados a partir de um vetor binário. - -Esta função cria `n` clones do vetor binário de entrada e aplica mutações aleatórias em alguns bits, simulando a expansão clonal em sistemas imunes artificiais com representações discretas. - -### Parâmetros - -* **vector** (`npt.NDArray[np.bool_]`): Vetor binário original que representa a célula imune a ser clonada e mutada. -* **n** (`int`): Quantidade de clones mutados a serem gerados. -* **mutation_rate** (`float`): Se 0 <= mutation_rate < 1: probabilidade de mutação de cada componente. - Se mutation_rate >= 1 ou mutation_rate <= 0: a mutação aleatoriza a quantidade de componentes entre 1 e len(vector). - -### Retorno - -* `clone_set` (`npt.NDArray[np.bool_]`): Array com forma `(n, len(vector))` contendo os `n` clones mutados do vetor original. - ---- - -## clone_and_mutate_ranged - -```python -@njit([(types.float64[:], types.int64, types.float64[:, :], types.float64)], cache=True) -def clone_and_mutate_ranged( - vector: npt.NDArray[np.float64], - n: int, - bounds: npt.NDArray[np.float64], - mutation_rate: float, -) -> npt.NDArray[np.float64]: -``` - -Gera um conjunto de clones mutados a partir de um vetor contínuo usando limites personalizados por dimensão. - -Esta função cria `n` clones do vetor de entrada e aplica mutações aleatórias em cada um, simulando o processo de expansão clonal em sistemas imunes artificiais. Cada clone recebe um número aleatório de mutações em posições distintas do vetor original. - -### Parâmetros - -* **vector** (`npt.NDArray[np.float64]`): Vetor contínuo original que representa a célula imune a ser clonada e mutada. -* **n** (`int`): Quantidade de clones mutados a serem gerados. -* **bounds** (`npt.NDArray[np.float64]`): Um array 2D com formato `(2, len(vector))` contendo os valores mínimo e máximo para cada dimensão. -* **mutation_rate** : (`float`) Se 0 <= mutation_rate < 1: probabilidade de mutação de cada componente. - Se mutation_rate >= 1 ou mutation_rate <= 0: a mutação aleatoriza a quantidade de componentes entre 1 e len(vector). - -### Retorna - -* `clone_set` (`npt.NDArray[np.float64]`): Array com forma `(n, len(vector))` contendo os `n` clones mutados do vetor original. - ---- - -## clone_and_mutate_permutation - -```python -@njit([(types.int64[:], types.int64, types.float64)], cache=True) -def clone_and_mutate_permutation( - vector: npt.NDArray[np.int64], - n: int, - mutation_rate: float -) -> npt.NDArray[np.int64]: -``` - -Gera um conjunto de clones mutados a partir de um vetor de permutação. - -Esta função cria `n` clones do vetor de permutação de entrada e aplica mutações aleatórias em cada um, simulando a expansão clonal em sistemas imunes artificiais com permutações discretas. Cada clone recebe um número aleatório de trocas de elementos de acordo com a taxa de mutação. - -### Parâmetros - -* **vector** (`npt.NDArray[np.int64]`): A célula imune original com valores de permutação a serem clonados e mutados. -* **n** (`int`): Número de clones mutados a serem gerados. -* **mutation_rate** (`float`): Probabilidade de mutação de cada componente (0 <= mutation_rate < 1). - -### Retorna - -* `clone_set` (`npt.NDArray[np.int64]`): Array com dimensão `(n, len(vector))` contendo os `n` clones mutados do vetor original. diff --git a/docs/pt-br/advanced-guides/base/immune/populations.md b/docs/pt-br/advanced-guides/base/immune/populations.md deleted file mode 100644 index efefca1..0000000 --- a/docs/pt-br/advanced-guides/base/immune/populations.md +++ /dev/null @@ -1,28 +0,0 @@ -# Populations Module - -Fornece funções utilitárias para gerar populações de anticorpos em algoritmos imunológicos. - -# generate_random_antibodies(...) - -```python -def generate_random_antibodies( - n_samples: int, - n_features: int, - feature_type: FeatureTypeAll = "continuous-features", - bounds: Optional[npt.NDArray[np.float64]] = None, -) -> npt.NDArray: -``` - -Gera uma população aleatória de anticorpos - -**Parâmetros**: -* **n_samples** (`int`): Número de anticorpos (amostras) a serem gerados. -* **n_features** (`int`): Número de características (dimensões) de cada anticorpo. -* **feature_type** (`FeatureTypeAll`, default="continuous-features"): Especifica o tipo de características:: "continuous-features", "binary-features", "ranged-features", or "permutation-features". -* **bounds** (`Optional[npt.NDArray[np.float64]]`, default=None): Array (2, n_features) com valores mínimo e máximo por dimensão. - -**Returns**: -* **npt.NDArray**: Array com forma (n_samples, n_features) contendo os anticorpos gerados. - -**Raises**: -* **ValueError**: Se o número de características for menor que 0. \ No newline at end of file diff --git a/docs/pt-br/advanced-guides/base/optimizer.md b/docs/pt-br/advanced-guides/base/optimizer.md deleted file mode 100644 index 066b153..0000000 --- a/docs/pt-br/advanced-guides/base/optimizer.md +++ /dev/null @@ -1,160 +0,0 @@ -# BaseOptimizer - -Classe base para algoritmos de otimização - -Esta classe define a interface central para estratégias de otimização e mantém o histórico de custos, soluções -avaliadas e a melhor solução encontrada. Subclasses devem implementar os métodos `optimize` e `affinity_function`. - ---- - -## Propriedades - -### Propriedade `cost_history` - -```python -@property -def cost_history(self) -> List[float] -``` - -Retorna o histórico de custos durante a otimização. - ---- - -### Propriedade `solution_history` - -```python -@property -def solution_history(self) -> List -``` - -Retorna o histórico de soluções avaliadas. - ---- - -### Propriedade `best_solution` - -```python -@property -def best_solution(self) -> Optional[Any] -``` - -Retorna a melhor solução encontrada até o momento, ou `None` se não disponível. - ---- - -### Propriedade `best_cost` - -```python -@property -def best_cost(self) -> Optional[float] -``` - -Retorna o custo da melhor solução encontrada até o momento, ou `None` se não disponível. - ---- - -## Métodos - -### Método `_record_best(...)` - -```python -def _record_best(self, cost: float, best_solution: Any) -> None -``` - -Registra um novo valor de custo e atualiza a melhor solução se houver melhoria. - -**Parâmetros**: - -* **cost** (`float`): Valor de custo a ser adicionado ao histórico. - ---- - -### Método `get_report()` - -```python -def get_report(self) -> str -``` - -Gera um relatório resumido e formatado do processo de otimização. O relatório inclui a melhor solução, seu custo -associado e a evolução dos valores de custo por iteração. - -**Retorna**: - -* **report** (`str`): String formatada contendo o resumo da otimização. - ---- - -### Método `register(...)` - -```python -def register(self, alias: str, function: Callable[..., Any]) -> None -``` - -Registra dinamicamente uma função na instância do otimizador. - -**Parâmetros**: - -* **alias** (`str`): Nome usado para acessar a função como atributo. -* **function** (`Callable[..., Any]`): Callable a ser registrado. - -**Exceções**: - -* **TypeError**: Se `function` não for Callable. -* **AttributeError**: Se `alias` for protegido e não puder ser modificado, ou se `alias` não existir na classe do otimizador. - ---- - -### Método `reset()` - -```python -def reset(self) -``` - -Reinicia o estado interno do objeto, limpando o histórico e resetando os valores. - ---- - -## Métodos abstratos - -### Método `optimize(...)` - -```python -@abstractmethod -def optimize( - self, - max_iters: int = 50, - n_iter_no_change: int = 10, - verbose: bool = True -) -> Any: -``` - -Executa o processo de otimização. Este método deve ser implementado pela subclasse para definir como a estratégia de -otimização explora o espaço de busca. - -**Parâmetros**: - -* **max_iters** (`int`, padrão=50): Número máximo de iterações. -* **n_iter_no_change** (`int`, padrão=10): Número máximo de iterações sem atualização da melhor solução. -* **verbose**: (`bool`, padrão=True): Flag para habilitar ou desabilitar saída detalhada durante a otimização. - -**Retorna**: - -* **best_solution** (`Any`): A melhor solução encontrada pelo algoritmo de otimização. - ---- - -### Método `affinity_function(...)` - -```python -def affinity_function(self, solution: Any) -> float -``` - -Avalia a afinidade de uma solução candidata. Este método deve ser implementado pela subclasse para definir o problema específico. - -**Parâmetros**: - -* **solution** (`Any`): Solução candidata a ser avaliada. - -**Retorna**: - -* **cost** (`float`): Valor de custo associado à solução fornecida. diff --git a/docs/pt-br/advanced-guides/core/Negative Selection.md b/docs/pt-br/advanced-guides/core/Negative Selection.md deleted file mode 100644 index d274938..0000000 --- a/docs/pt-br/advanced-guides/core/Negative Selection.md +++ /dev/null @@ -1,93 +0,0 @@ -# Seleção Negativa - -As funções realizam verificações de detectores e utilizam decoradores Numba para compilação Just-In-Time. - -## Função `check_detector_bnsa_validity(...)` - -```python -@njit([(types.boolean[:, :], types.boolean[:], types.float64)], cache=True) -def check_detector_bnsa_validity( - x_class: npt.NDArray[np.bool_], - vector_x: npt.NDArray[np.bool_], - aff_thresh: float -) -> bool: -``` - -Verifica a validade de um candidato a detector (vector_x) contra amostras de uma classe (x_class) usando a distância de Hamming. Um detector é considerado INVÁLIDO se a sua distância para qualquer amostra em ``x_class`` for menor ou igual a ``aff_thresh``. - -**Os parâmetros de entrada são:** - -* **x_class** (``npt.NDArray[np.bool_]``): Array contendo as amostras da classe. Formato esperado: (n_amostras, n_características). -* **vector_x** (``npt.NDArray[np.bool_]``): Array representando o detector. Formato esperado: (n_características,). -* **aff_thresh** (``float``): Limiar de afinidade. - -**Retorna:** - -* True se o detector for válido, False caso contrário. - ---- - -## Função `bnsa_class_prediction(...)` - -```python -@njit([(types.boolean[:], types.boolean[:, :, :], types.float64)], cache=True) -def bnsa_class_prediction( - features: npt.NDArray[np.bool_], - class_detectors: npt.NDArray[np.bool_], - aff_thresh: float, -) -> int: -``` - -Define a classe de uma amostra a partir dos detectores não-próprios. - -**Os parâmetros de entrada são:** - -* **features** (``npt.NDArray[np.bool_]``): amostra binária a ser classificada (shape: n_features). -* **class_detectors** (``npt.NDArray[np.bool_]``): Matriz contendo os detectores de todas as classes (shape: n_classes, n_detectors, n_features). -* **aff_thresh** (``float``): Limiar de afinidade que determina se um detector reconhece a amostra como não-própria. - -**Retorna:** - -* `int`: Índice da classe predita. Retorna -1 se for não-própria para todas as classes. - ---- - -## Função `check_detector_rnsa_validity(...)` - -```python -@njit( - [ - ( - types.float64[:, :], - types.float64[:], - types.float64, - types.int32, - types.float64, - ) - ], - cache=True, -) -def check_detector_rnsa_validity( - x_class: npt.NDArray[np.float64], - vector_x: npt.NDArray[np.float64], - threshold: float, - metric: int, - p: float, -) -> bool: -``` - -Verifica a validade de um candidato a detector (vector_x) contra amostras de uma classe (x_class) usando a distância de Hamming. Um detector é considerado INVÁLIDO se a sua distância para qualquer amostra em ``x_class`` for menor ou igual a ``aff_thresh``. - -**Os parâmetros de entrada são:** - -* **x_class** (``npt.NDArray[np.float64]``): Array contendo as amostras da classe. Formato esperado: (n_amostras, n_características). -* **vector_x** (``npt.NDArray[np.float64]``): Array representando o detector. Formato esperado: (n_características,). -* **threshold** (``float``): Afinidade. -* **metric** (``int``): Métrica de distância a ser utilizada. Opções disponíveis: 0 (Euclidean), 1 (Manhattan), 2 (Minkowski). -* **p** (``float``): Parâmetro da métrica de Minkowski (utilizado apenas se `metric` for "minkowski"). - -**Retorna:** - -* `True` se o detector for válido, `False` caso contrário. - ---- diff --git a/docs/pt-br/advanced-guides/utils.md b/docs/pt-br/advanced-guides/utils.md deleted file mode 100644 index b69a951..0000000 --- a/docs/pt-br/advanced-guides/utils.md +++ /dev/null @@ -1,609 +0,0 @@ -# Utils - -Funções de utilidade para o desenvolvimento. - -## Métricas (Metrics) - -### Função `accuracy_score(...)` - -```python -def accuracy_score( - y_true: Union[npt.NDArray, list], - y_pred: Union[npt.NDArray, list] -) -> float: -``` - -Função para calcular a acurácia de precisão com base em listas de rótulos -verdadeiros e nos rótulos previstos. - -**Parâmetros:** - -* **y_true** (``Union[npt.NDArray, list]``): Rótulos verdadeiros (corretos).. -* **y_pred** (``Union[npt.NDArray, list]``): Rótulos previstos. - -**Retorna:** - -* **Precisão** (``float``): A proporção de previsões corretas em relação - ao número total de previsões. - -**Exceções:** - -* `ValueError`: Se `y_true` ou `y_pred` estiverem vazios ou se não - tiverem o mesmo tamanho. - ---- - -## Multiclass - -### Função `predict_knn_affinity(...)` - -```python -def predict_knn_affinity( - X: npt.NDArray, - k: int, - all_cell_vectors: List[Tuple[Union[str, int], npt.NDArray]], - affinity_func: Callable[[npt.NDArray, npt.NDArray], float] -) -> npt.NDArray -``` - -Função para prever classes usando k-vizinhos mais próximos e células treinadas. - -**Parâmetros:** - -* **X** (`npt.NDArray`): Dados de entrada a serem classificados. -* **k** (`int`): Número de vizinhos mais próximos a considerar para a previsão. -* **all_cell_vectors** (`List[Tuple[Union[str, int], npt.NDArray]]`): Lista de tuplas contendo pares (nome_da_classe, vetor_da_célula). -* **affinity_func** (`Callable[[npt.NDArray, npt.NDArray], float]`): Função que recebe dois vetores e retorna um valor de afinidade. - -**Retorna:** - -* `npt.NDArray`: Array de rótulos previstos para cada amostra em X, baseado nos k vizinhos mais próximos. - ---- - -### Função `slice_index_list_by_class(...)` - -```python -def slice_index_list_by_class(classes: Optional[Union[npt.NDArray, list]], y: npt.NDArray) -> dict -``` - -A função ``slice_index_list_by_class(...)``, separa os índices das amostras -conforme a classe de saída, para percorrer o array de amostra apenas nas posições -onde a saída corresponde à classe sendo treinada. - -**Parâmetros:** - -* **classes** (`Optional[Union[npt.NDArray, list]]`): Lista com classes únicas. Se None, retorna um dicionário vazio. -* **y** (`npt.NDArray`): Array com as classes de saída do array de amostra ``X``. - -**Retorna:** - -* `dict`: Um dicionário com a lista de posições do array, com as classes como chave. - -**Exemplos:** - -```python ->>> import numpy as np ->>> labels = ['a', 'b', 'c'] ->>> y = np.array(['a', 'c', 'b', 'a', 'c', 'b']) ->>> slice_index_list_by_class(labels, y) -{'a': [0, 3], 'b': [2, 5], 'c': [1, 4]} -``` - -## Sanitizers - -### Função `sanitize_choice(...)` - -```python -def sanitize_choice(value: T, valid_choices: Iterable[T], default: T) -> T -``` - -A função ``sanitize_choice(...)``, retorna o valor se estiver presente no conjunto de opções válidas; caso contrário, retorna o valor padrão. - -**Parâmetros:** - -* **value** (``T``): O valor a ser verificado. -* **valid_choices** (``Iterable[T]``): Uma coleção de opções válidas. -* **default**: O valor padrão a ser retornado se ``value`` não estiver em ``valid_choices``. - -**Returns:** - -* `T`: O valor original, se válido, ou o valor padrão, se não. - ---- - -### Função `sanitize_param(...)` - -```python -def sanitize_param(value: T, default: T, condition: Callable[[T], bool]) -> T: -``` - -A função ``sanitize_param(...)``, retorna o valor se ele satisfizer a condição especificada; caso contrário, retorna o valor padrão. - -**Parâmetros:** - -* **value** (``T``): O valor a ser verificado. -* **default** (``T``): O valor padrão a ser retornado se a condição não for satisfeita. -* **condition** (``Callable[[T], bool]``): Uma função que recebe um valor e retorna um booleano, determinando se o valor é válido. - -**Returns:** - -* `T`: O valor original se a condição for satisfeita, ou o valor padrão se não for. - ---- - -### Função `sanitize_seed(...)` - -```python -def sanitize_seed(seed: Any) -> Optional[int]: -``` - -A função ``sanitize_seed(...)``, retorna a semente se for um inteiro não negativo; caso contrário, retorna Nenhum. - -**Parâmetros:** - -* **seed** (``Any``): O valor da seed a ser validado. - -**Returns:** - -* ``Optional[int]``: A seed original se for um inteiro não negativo, ou ``None`` se for inválido. - ---- - -### Função `sanitize_bounds(...)` - -```python -def sanitize_bounds(bounds: Any, problem_size: int) -> Dict[str, npt.NDArray[np.float64]] -``` - -A função `sanitize_bounds(...)` valida e normaliza os limites das características (features). - -**Parâmetros**: - -* **bounds** (`Any`): Os limites de entrada, que devem ser `None` ou um dicionário com as chaves `'low'` e `'high'`. -* **problem_size** (`int`): O tamanho esperado para as listas de limites normalizadas, correspondente ao número de features do problema. - -**Retorna**: - -* `Dict[str, list]`: Dicionário no formato `{'low': [low_1, ..., low_N], 'high': [high_1, ..., high_N]}`. - -## Distance - -Funções utilitárias para distância normalizada entre matrizes com decoradores numba. - -### Função `hamming(...)` - -```python -@njit([(types.boolean[:], types.boolean[:])], cache=True) -def hamming(u: npt.NDArray[np.bool_], v: npt.NDArray[np.bool_]) -> float64: -``` - -Função para calcular a distância de Hamming normalizada entre dois pontos. - -$((x₁ ≠ x₂) + (y₁ ≠ y₂) + ... + (yn ≠ yn)) / n$ - -**Parâmetros:** - -* **u** (``npt.NDArray[np.bool_]``): Coordenadas do primeiro ponto -* **v** (``npt.NDArray[np.bool_]``): Coordenadas do segundo ponto. - -**Returns:** - -* Distância (``float64``) entre os dois pontos. - ---- - -### Função `euclidean(...)` - -```python -@njit() -def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> float64: -``` - -Função para calcular a distância euclidiana normalizada entre dois pontos. - -$√( (x₁ - x₂)² + (y₁ - y₂)² + ... + (yn - yn)²)$ - -**Parâmetros:** - -* **u** (``npt.NDArray[np.float64]``): Coordenadas do primeiro ponto -* **v** (``npt.NDArray[np.float64]``): Coordenadas do segundo ponto. - -**Returns:** - -* Distância (``float64``) entre os dois pontos. - ---- - -### Função `cityblock(...)` - -```python -@njit() -def cityblock(u: npt.NDArray[float64], v: npt.NDArray[float64]) -> float64: -``` - -Função para calcular a distância Manhattan normalizada entre dois pontos. - -$(|x₁ - x₂| + |y₁ - y₂| + ... + |yn - yn|) / n$ - -**Parâmetros:** - -* **u** (``npt.NDArray[float64]``): Coordenadas do primeiro ponto -* **v** (``npt.NDArray[float64]``): Coordenadas do segundo ponto. - -**Returns:** - -* Distância (``float64``) entre os dois pontos. - ---- - -### Função `minkowski(...)` - -```python -@njit() -def minkowski( - u: npt.NDArray[float64], - v: npt.NDArray[float64], - p: float = 2.0 -) -> float64: -``` - -Função para calcular a distância de Minkowski normalizada entre dois pontos. - -$(( |X₁ - Y₁|p + |X₂ - Y₂|p + ... + |Xn - Yn|p) ¹/ₚ) / n$ - -**Parâmetros:** - -* **u** (``npt.NDArray[float64]``): Coordenadas do primeiro ponto. -* **v** (``npt.NDArray[float64]``): Coordenadas do segundo ponto. -* **p** (``float``, padrão=2.0): O parâmetro p define o tipo de distância a ser calculada: - * p = 1: Distância **Manhattan** - soma das diferenças absolutas. - * p = 2: Distância **Euclidiana** - soma das diferenças ao quadrado (raiz quadrada). - * p > 2: Distância **Minkowski** com uma penalidade crescente à medida que p aumenta. - -**Returns:** - -* Distância (``float``) entre os dois pontos. - ---- - -### Função `compute_metric_distance(...)` - -```python -@njit([(types.float64[:], types.float64[:], types.int32, types.float64)], cache=True) -def compute_metric_distance( - u: npt.NDArray[float64], - v: npt.NDArray[float64], - metric: int, - p: float = 2.0 -) -> float64: -``` - -Função para calcular a distância entre dois pontos pela ``métrica`` escolhida. - -**Parâmetros:** - -* **u** (``npt.NDArray[float64]``): Coordenadas do primeiro ponto. -* **v** (``npt.NDArray[float64]``): Coordenadas do segundo ponto. -* **metric** (``int``): Métrica de distância a ser utilizada. Opções disponíveis: 0 (Euclidean), 1 (Manhattan), 2 (Minkowski). -* **p** (``float``, padrão=2.0): Parâmetro da métrica de Minkowski (utilizado apenas se `metric` for "minkowski"). - -**Returns:** - -* Distância (``double``) entre os dois pontos com a métrica selecionada. - ---- - -### Função `min_distance_to_class_vectors(...)` - -```python -@njit([(types.float64[:, :], types.float64[:], types.int32, types.float64)], cache=True) -def min_distance_to_class_vectors( - x_class: npt.NDArray[float64], - vector_x: npt.NDArray[float64], - metric: int, - p: float = 2.0, -) -> float: -``` - -Calcula a menor distância entre um vetor de entrada e os vetores de uma classe. - -**Parâmetros:** - -* **x_class** (``npt.NDArray``): Array contendo os vetores da classe com os quais o vetor de entrada será comparado. Formato esperado: (n_amostras, n_características). -* **vector_x** (``npt.NDArray``): Vetor a ser comparado com os vetores da classe. Formato esperado: (n_características,). -* **metric** (``int``): Métrica de distância a ser utilizada. Opções disponíveis: 0 (Euclidean), 1 (Manhattan), 2 (Minkowski), 3 (Hamming). -* **p** (``float``): Parâmetro da métrica de Minkowski (utilizado apenas se `metric` for "minkowski"). - -**Returns:** - -* float: A menor distância calculada entre o vetor de entrada e os vetores da classe. -* Retorna -1.0 se as dimensões de entrada forem incompatíveis. - ---- - -### Função `get_metric_code(...)` - -```python -def get_metric_code(metric: str) -> int: -``` - -Retorna o código numérico associado a uma métrica de distância. - -**Parâmetros:** - -* **metric** (``str``): Nome da métrica. Pode ser "euclidean", "manhattan", "minkowski" ou "hamming". - -**Raises** - -* ``ValueError``: Se a métrica informada não for suportada. - -**Returns:** - -* ``int``: Código numérico correspondente à métrica. - ---- - -## Validation - -### Função `detect_vector_data_type(...)` - -```python -def detect_vector_data_type( - vector: npt.NDArray -) -> FeatureType: -``` - -Detecta o tipo de dado em um determinado vetor. - -Esta função analisa o vetor de entrada e classifica seus dados como um dos tipos suportados: - -* **binário**: Valores booleanos (`True`/`False`) ou inteiro `0`/`1`. -* **contínuo**: Valores float dentro do intervalo normalizado `[0.0, 1.0]`. -* **intervalo**: Valores float fora do intervalo normalizado. - -**Parâmetros:** - -* **vector** (`npt.NDArray`): Um array contendo os dados a serem classificados. - -**Retorna:** - -* `FeatureType` (`Literal["binary-features", "continuous-features", "ranged-features"]`): O tipo de dado detectado no vetor. - -**Gera:** - -* `UnsupportedDataTypeError`: Gerado se o vetor contiver um tipo de dado não suportado. - ---- - -### Função `check_array_type(...)` - -```python -def check_array_type(x, name: str = "X") -> npt.NDArray: -``` - -Garante que o parâmetro recebido é um array numpy. Converte de lista se necessário. - -**Parâmetros:** - -* **x**: Array ou lista contendo as amostras e características. -* **name**: Nome da variável para mensagens de erro. - -**Retorna:** - -* `npt.NDArray`: O array convertido ou validado. - -**Exceções:** - -* `TypeError`: Se não for possível converter para ndarray. - ---- - -### Função `check_shape_match(...)` - -```python -def check_shape_match(x: npt.NDArray, y: npt.NDArray): -``` - -Garante que os arrays `x` e `y` possuem o mesmo número de amostras (primeira dimensão). - -**Parâmetros:** - -* **x**: Array de amostras. -* **y**: Array de classes alvo. - -**Exceções:** - -* `TypeError`: Se as dimensões não forem compatíveis. - ---- - -### Função `check_feature_dimension(...)` - -```python -def check_feature_dimension(x: npt.NDArray, expected: int): -``` - -Garante que o array possui o número esperado de características (features). - -**Parâmetros:** - -* **x**: Array de entrada para predição. -* **expected**: Número esperado de características por amostra. - -**Exceções:** - -* `FeatureDimensionMismatch`: Se o número de características não corresponder ao esperado. - ---- - -### Função `check_binary_array(...)` - -```python -def check_binary_array(x: npt.NDArray): -``` - -Garante que o array contém apenas valores 0 e 1. - -**Parâmetros:** - -* **x**: Array a ser verificado. - -**Exceções:** - -* `ValueError`: Se o array contiver valores diferentes de 0 e 1. - ---- - -## Display - -Funções utilitárias para exibir informações de algoritmos - -### Função `_supports_box_drawing()` - -```python -def _supports_box_drawing() -> bool -``` - -Função para verificar se o terminal suporta caracteres de borda. - -**Retorna**: - -* **bool** (`bool`): True se o terminal provavelmente suporta caracteres de borda, False caso contrário. - ---- - -### class TableFormatter - -Classe para formatar dados tabulares em strings para exibição no console. - -**Parâmetros**: - -* **headers** (`Mapping[str, int]`): Mapeamento dos nomes das colunas para suas larguras respectivas, no formato `{nome_coluna: largura_coluna}`. - -**Exceções**: - -* `ValueError`: Se `headers` estiver vazio ou não for um mapeamento válido. - ---- - -#### Função `_border(left, middle, right, line, new_line=True)` - -```python -def _border(self, left: str, middle: str, right: str, line: str, new_line: bool = True) -> str -``` - -Cria uma borda horizontal para a tabela. - -**Parâmetros**: - -* **left** (`str`): Caractere na borda esquerda. -* **middle** (`str`): Caractere separador entre colunas. -* **right** (`str`): Caractere na borda direita. -* **line** (`str`): Caractere usado para preencher a borda. -* **new_line** (`bool`, opcional): Se True, adiciona uma quebra de linha antes da borda (padrão é True). - -**Retorna**: - -* **border** (`str`): String representando a borda horizontal. - ---- - -#### Função `get_header()` - -```python -def get_header(self) -> str -``` - -Gera o cabeçalho da tabela, incluindo a borda superior, os títulos das colunas e a linha separadora. - -**Retorna**: - -* **header** (`str`): String formatada do cabeçalho da tabela. - ---- - -#### Função `get_row(values)` - -```python -def get_row(self, values: Mapping[str, Union[str, int, float]]) -> str -``` - -Gera uma linha formatada para os dados da tabela. - -**Parâmetros**: - -* **values** (`Mapping[str, Union[str, int, float]]`): Dicionário com os valores de cada coluna, no formato `{nome_coluna: valor}`. - -**Retorna**: - -* **row** (`str`): String formatada da linha da tabela. - ---- - -#### Função `get_bottom(new_line=False)` - -```python -def get_bottom(self, new_line: bool = False) -> str -``` - -Gera a borda inferior da tabela. - -**Parâmetros**: - -* **new_line** (`bool`, opcional): Se True, adiciona uma quebra de linha antes da borda (padrão é False). - -**Retorna**: - -* **bottom** (`str`): String formatada da borda inferior. - ---- - -### class ProgressTable(TableFormatter) - -Classe para exibir uma tabela formatada no console para acompanhar o progresso de um algoritmo. - -**Parâmetros**: - -* **headers** (`Mapping[str, int]`): Mapeamento `{nome_coluna: largura_coluna}`. -* **verbose** (`bool`, padrão=True): Se False, não imprime nada no terminal. - -**Exceções**: - -* `ValueError`: Se `headers` estiver vazio ou não for um mapeamento válido. - ---- - -#### Função `_print_header()` - -```python -def _print_header(self) -> None -``` - -Imprime o cabeçalho da tabela. - ---- - -#### Função `update(values)` - -```python -def update(self, values: Mapping[str, Union[str, int, float]]) -> None -``` - -Adiciona uma nova linha de valores à tabela. - -**Parâmetros**: - -* **values** (`Mapping[str, Union[str, int, float]]`): As chaves devem corresponder às colunas definidas em `headers`. - ---- - -#### Função `finish()` - -```python -def finish(self) -> None -``` - -Encerra a exibição da tabela, imprimindo a borda inferior e o tempo total. - ---- diff --git a/docs/pt-br/classes/Clonal Selection Algorithms/AIRS.md b/docs/pt-br/classes/Clonal Selection Algorithms/AIRS.md deleted file mode 100644 index 02cac0e..0000000 --- a/docs/pt-br/classes/Clonal Selection Algorithms/AIRS.md +++ /dev/null @@ -1,280 +0,0 @@ -# AIRS (Sistema de Reconhecimento Imune Artificial) - -Esta classe estende a classe [**Base**](../../advanced-guides/base/classifier.md). - -## Construtor AIRS - -A classe `AIRS` realiza classificação utilizando metáforas de seleção e expansão clonal. - -Esta implementação é inspirada no AIRS2, uma versão simplificada do algoritmo AIRS original, introduzindo adaptações para lidar com conjuntos de dados contínuos e binários. - -Baseado no Algoritmo 16.5 de Brabazon et al. [1](#ref1). - -Estudos relacionados de destaque: [2](#ref2). - -**Atributos:** - -* **n_resources** (`float`): Quantidade total de recursos disponíveis. O padrão é 10. -* **rate_clonal** (`float`): Número máximo de clones possíveis de uma classe. Esta quantidade é multiplicada por (estímulo da célula * taxa de hipermutação) para definir o número de clones. O padrão é 10. -* **rate_mc_init** (`float`): Percentual de amostras usadas para inicializar as células de memórias. O padrão é 0,75. -* **rate_hypermutation** (`float`): Taxa de clones mutados derivada de rate_clonal como um fator escalar. O padrão é 0,2. -* **affinity_threshold_scalar** (`float`): Limiar de afinidade normalizado. O padrão é 0,75. -* **k** (`int`): Número de vizinhos mais próximos (k-NN) que será usado para escolher um rótulo na predição. O padrão é 3. -* **max_iters** (`int`): Número máximo de interações no processo de refinamento do conjunto ARB exposto a aᵢ. O padrão é 100. -* **resource_amplified** (`float`): Amplificador de consumo de recursos, multiplicado com o estímulo para subtrair recursos. O padrão é 1.0 (sem amplificação). -* **metric** (`Literal["manhattan", "minkowski", "euclidean"]`): Forma de calcular a distância entre o detector e a amostra: - * `'euclidean'` ➜ O cálculo da distância é dado pela expressão: - √( (x₁ - x₂)² + (y₁ - y₂)² + ... + (nₙ - nₙ)² ). - * `'minkowski'` ➜ O cálculo da distância é dado pela expressão: - ( |X₁ - Y₁|ᵖ + |X₂ - Y₂|ᵖ + ... + |Xₙ - Yₙ|ᵖ )¹/ᵖ. - * `'manhattan'` ➜ O cálculo da distância é dado pela expressão: - ( |x₁ - x₂| + |y₁ - y₂| + ... + |nₙ - nₙ| ). - O padrão é "euclidean". - -* **seed** (int): Semente para geração aleatória de valores dos detectores. O padrão é None. -* `**kwargs`: - * **p** (`float`): Este parâmetro armazena o valor de `p` usado na distância de Minkowski. - O padrão é `2`, que corresponde à distância euclidiana normalizada. Diferentes valores de p resultam em variantes distintas da distância de Minkowski. [Saiba mais](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.minkowski.html). - -**Outras variáveis inicializadas:** - -* **cells_memory** (`dict`): Armazena uma lista de células de memória por classe. -* **affinity_threshold** (`dict`): Define o limiar de afinidade entre antígenos. -* **classes** (`npt.NDArray`): Lista de classes de saída. - ---- - -## Métodos Públicos - -### Método `fit(...)` - -A função `fit(...)` gera detectores para os não-pertencentes em relação às amostras: - -```python -def fit( - self, - X: Union[npt.NDArray, list], - y: Union[npt.NDArray, list], - verbose: bool = True, -) -> AIRS: -``` - -Realiza o treinamento conforme `X` e `y`, utilizando o método Sistema de Reconhecimento Imune Artificial (`AIRS`). - -**Parâmetros:** - -* **X** (``Union[npt.NDArray, list]``): Array com as características das amostras, com **N** amostras (linhas) e **N** características (colunas), normalizado para valores entre [0, 1]. -* **y** (``Union[npt.NDArray, list]``): Array com as classes de saída correspondentes às **N** amostras relacionadas a `X`. -* **verbose**: (``bool``, padrão=True), determina se o feedback da geração dos detectores será impresso. - -**Retorna:** - -* `AIRS`: A instância da classe. - ---- - -### Método `predict(...)` - -A função `predict(...)` realiza a predição de classes utilizando os detectores gerados: - -```python -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -**Parâmetros:** - -* **X** (`Union[npt.NDArray, list]`): Array com as características para predição, com **N** amostras (linhas) e **N** colunas. - -**Raises** - -* `TypeError`: Se X não for um ndarray ou uma lista. -* `FeatureDimensionMismatch`: Se o número de características em X não corresponder ao número esperado. -* `ModelNotFittedError`: Se o modelo ainda não tiver sido ajustado e não possuir células de memória definidas, não conseguirá realizar predições. - - -**Retorna:** - -* **C**: Um array de predições com as classes de saída para as características fornecidas. - ---- - -### Método `score(...)` - -A função `score(...)` calcula a acurácia do modelo treinado realizando predições e calculando a precisão. - -```python -def score(self, X: npt.NDArray, y: list) -> float: -``` - -**Retorna:** - -Retorna a acurácia como um `float`. - ---- - -## Métodos Privados - -### Método `_refinement_arb(...)` - -A função "_refinement_arb(...)" refina o conjunto ARB até que o valor médio de estímulo ultrapasse o limiar definido (`affinity_threshold_scalar`). - -```python -def _refinement_arb( - self, - ai: npt.NDArray, - c_match_stimulation: float, - arb_list: List[_ARB] -) -> _ARB: -``` - -**Parâmetros:** -* **ai** (`npt.NDArray`): Antígeno atual -* **c_match_stimulation** (``float``): Célula com o maior estímulo em relação a aᵢ. -* **arb_list** (`List[_ARB]`): Conjunto ARB. - -**Retorna:** - -Retorna a célula (`_ARB`) com o maior estímulo ARB. - ---- - -### Método `_cells_affinity_threshold(...)` - -A função "_cells_affinity_threshold(...)" calcula o limiar de afinidade com base na afinidade média entre instâncias de treinamento, onde aᵢ e aⱼ são um par de antígenos, e a afinidade é medida pela distância (Euclidiana, Manhattan, Minkowski, Hamming). - -```python -def _cells_affinity_threshold(self, antigens_list: npt.NDArray): -``` - -**Seguindo a fórmula:** - -$$ -\text{affinity}_{\text{threshold}} = \frac{ -\sum_{i=1}^{n-1} \sum_{j=i+1}^{n} \text{affinity}(a_i, a_j)}{n(n-1)/2} -$$ - - -**Parâmetros:** - -* **antigens_list** (`npt.NDArray`): Lista de antígenos de treinamento. - ---- - -### Método `_affinity(...)` - -A função "_affinity(...)" calcula o estímulo entre dois vetores usando métricas. - - -```python -def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float: -``` - -**Parâmetros:** - -* **u** (`npt.NDArray`): Coordenadas do primeiro ponto. -* **v** (`npt.NDArray`): Coordenadas do segundo ponto. - -**Retorna:** - -Retorna a taxa de estímulo entre os vetores. - ---- - -### Método `_init_memory_c(...)` - -A função "_init_memory_c(...)" inicializa células de memória selecionando aleatoriamente `n_antigens_selected` da lista de antígenos de treinamento. - -```python -def _init_memory_c(self, antigens_list: npt.NDArray) -> List[Cell]: -``` - -**Parâmetros:** - -* **antigens_list** (`npt.NDArray`): Lista de antígenos de treinamento. - ---- - - -### Method `_slice_index_list_by_class(...)` - -A função ``_slice_index_list_by_class(...)``, separa os índices das linhas conforme a classe de saída, para percorrer o array de amostra, apenas nas posições que a saída for a classe que está sendo treinada: - - -```python -def _slice_index_list_by_class(self, y: npt.NDArray) -> dict: -``` - -**Parâmetros**: - -* **y** (`npt.NDArray`): Recebe um array ``n_samples`` com as classes de saída do array de amostras ``X``. - -**Retorna:** - -Retorna um dicionário com as classes como chave e os índices em ``X`` das amostras. - ---- - -### Method `__prepare_features(...)` - -A função ``__prepare_features(...)`` verifica as amostras, especificando o tipo, a quantidade de características e outros parâmetros. - -```python -def _prepare_features(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -* Este método atualiza os seguintes atributos: - * ``self._feature_type`` - * ``self.metric`` (apenas para características binárias) - * ``self._bounds`` (apenas para características com intervalo definido) - * ``self._n_features`` - - -**Parameters:** - -* **X** (``Union[npt.NDArray, list]``): Array com as características para predição, contendo N amostras (linhas) e N colunas. - -Retorna os dados de entrada processados. - ---- - -# Classes Auxiliares - ---- - -## Classe _ARB (Herdada de [BCell](../../advanced-guides/base/immune/cell.md#bcell)) - -### Construtor - -**Parâmetros:** - -* vector (`npt.NDArray`): Vetor de características da célula. Padrão é None. - ---- - -### Método `consume_resource(...)` - -```python -def consume_resource(self, n_resource: float, amplified: float = 1) -> float: -``` - -**Parâmetros:** - -* **n_resource** (`float`) : A quantidade inicial de recursos. -* **amplified** (`float`): Amplificador para o consumo de recursos pela célula. É multiplicado pelo estímulo da célula. O padrão é 1. - -**Retorna:** - -Retorna a quantidade restante de recursos após o consumo. - ---- - -# Referências - -
- -> 1. BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: [http://dx.doi.org/10.1007/978-3-662-43631-8](http://dx.doi.org/10.1007/978-3-662-43631-8). - -
- -> 2. AZZOUG, Aghiles. Artificial Immune Recognition System V2. -> Disponível em: [https://github.com/AghilesAzzoug/Artificial-Immune-System](https://github.com/AghilesAzzoug/Artificial-Immune-System) diff --git a/docs/pt-br/classes/Clonal Selection Algorithms/Clonalg.md b/docs/pt-br/classes/Clonal Selection Algorithms/Clonalg.md deleted file mode 100644 index 931dbe2..0000000 --- a/docs/pt-br/classes/Clonal Selection Algorithms/Clonalg.md +++ /dev/null @@ -1,183 +0,0 @@ -# Algoritmo de Seleção Clonal (CLONALG) - -## Clonalg - -A classe `Clonalg` é um **algoritmo de otimização** inspirado no processo biológico de seleção clonal do sistema -imunológico. Esta implementação é projetada para minimizar ou maximizar funções de custo em diversos tipos de -problemas, incluindo problemas binários, contínuos, com valores limitados (ranged) e de permutação. - -A implementação do CLONALG foi inspirada na descrição apresentada em [1](#ref1). - -Esta implementação do CLONALG contém algumas alterações baseadas no contexto do AISP, para aplicação geral -a diversos problemas, que podem produzir resultados diferentes da implementação padrão ou -específica. Esta adaptação visa generalizar o CLONALG para tarefas de minimização e -maximização, além de suportar problemas contínuos, discretos e de permutação. - ---- - -### Construtor - -O construtor inicializa a instância do CLONALG com os principais parâmetros que definem o processo de otimização. - -**Atributos:** - -* **problem_size** (`int`): Dimensão do problema a ser otimizado. -* **N** (`int`, padrão=50): Número de células de memória (anticorpos) na população. -* **rate_clonal** (`float`, padrão=10): Número máximo de clones possíveis de uma célula. Este valor é multiplicado pela afinidade da célula para determinar o número de clones. -* **rate_hypermutation** (`float`, padrão=1.0): Taxa de clones mutados, usada como fator escalar. -* **n_diversity_injection** (`int`, padrão=5): Número de novas células de memória aleatórias injetadas para manter a diversidade. -* **selection_size** (`int`, padrão=5): Número de melhores anticorpos selecionados para clonagem. -* **affinity_function** (`Optional[Callable[..., npt.NDArray]]`, padrão=None): Função objetivo usada para avaliar soluções candidatas. -* **feature_type** (`FeatureTypeAll`, padrão='ranged-features'): Tipo de amostra do problema, podendo ser `'continuous-features'`, `'binary-features'`, `'ranged-features'` ou `'permutation-features'`. -* **bounds** (`Optional[Dict]`, padrão=None): Dicionário definindo os limites de busca para problemas `'ranged-features'`. Pode ser um único intervalo ou uma lista de intervalos para cada dimensão. -* **mode** (`Literal["min", "max"]`, padrão="min"): Especifica se o algoritmo minimiza ou maximiza a função de custo. -* **seed** (`Optional[int]`, padrão=None): Semente para geração de números aleatórios. - ---- - -## Métodos Públicos - -### Função `optimize(...)` - -```python -def optimize( - self, - max_iters: int = 50, - n_iter_no_change=10, - verbose: bool = True -) -> List[Antibody]: -``` - -Este método executa o processo de otimização e retorna a população de anticorpos. - -**Parâmetros:** - -* **max_iters** (`int`, padrão=50): Número máximo de interações. -* **n_iter_no_change** (`int`, padrão=10): Número máximo de iterações sem melhoria na melhor solução. -* **verbose** (`bool`, padrão=True): Flag para habilitar ou desabilitar saída detalhada durante o processo de otimização. - -**Retorna:** - -* `List[Antibody]`: A população de anticorpos após a expansão clonal. - ---- - -#### Função `affinity_function(...)` - -```python -def affinity_function(self, solution: npt.NDArray) -> np.float64: -``` - -Este método avalia a afinidade de uma solução candidata. Levanta `NotImplementedError` se nenhuma função de afinidade tiver sido fornecida à instância da classe. - -**Parâmetros:** - -* **solution** (`npt.NDArray`): Solução candidata a ser avaliada. - -**Retorna:** - -* `np.float64`: Valor de afinidade associado à solução. - ---- - -### Métodos Privados - -#### Função `_select_top_antibodies(...)` - -```python -def _select_top_antibodies(self, n: int, antibodies: list[tuple]) -> list[tuple]: -``` - -Seleciona os `n` melhores anticorpos com base em suas pontuações de afinidade, de acordo com o `mode` (`'min'` ou `'max'`). - -**Parâmetros:** - -* **n** (`int`): Número de anticorpos a serem selecionados. -* **antibodies** (`list[Antibody]`): Lista de tuplas, onde cada tupla representa um anticorpo e sua pontuação associada. - -**Retorna:** - -* `list[Antibody]`: Lista contendo os `n` anticorpos selecionados. - ---- - -#### Função `_init_population_antibodies(...)` - -```python -def _init_population_antibodies(self) -> npt.NDArray: -``` - -Inicializa aleatoriamente a população inicial de anticorpos. - -**Retorna:** - -* `npt.NDArray`: Lista com os anticorpos inicializados. - ---- - -#### Função `_diversity_introduction(...)` - -```python -def _diversity_introduction(self): -``` - -Introduz novos anticorpos aleatórios na população para manter a diversidade genética e ajudar a evitar convergência prematura. - -**Retorna:** - -* `npt.NDArray`: Array contendo os novos anticorpos aleatórios. - ---- - -#### Função `_clone_and_mutate(...)` - -```python -def _clone_and_mutate( - self, - antibody: npt.NDArray, - n_clone: int, - rate_hypermutation: float -) -> npt.NDArray: -``` - -Gera clones mutados a partir de um único anticorpo. A estratégia de mutação depende do `feature_type` especificado durante a inicialização (`'binary-features'`, `'continuous-features'`, `'ranged-features'` ou `'permutation-features'`). - -**Parâmetros:** - -* **antibody** (`npt.NDArray`): Vetor original do anticorpo a ser clonado e mutado. -* **n_clone** (`int`): Número de clones a serem gerados. -* **rate_hypermutation** (`float`): Taxa de hipermutação. - -**Retorna:** - -* `npt.NDArray`: Array contendo os clones mutados. - ---- - -#### Função `_clone_and_hypermutation(...)` - -```python -def _clone_and_hypermutation( - self, - population: list[Antibody] -) -> list[Antibody]: -``` - -Clona e aplica hipermutação a uma população de anticorpos. Retorna uma lista de todos os clones e suas afinidades em relação à função de custo. - -**Parâmetros:** - -* **population** (`list[Antibody]`): Lista de anticorpos a serem avaliados e clonados. - -**Retorna:** - -* `list[Antibody]`: Lista contendo os clones mutados. - ---- - -## Referências - -
- -> 1. BROWNLEE, Jason. Clonal Selection Algorithm. Clever Algorithms: Nature-inspired Programming Recipes., 2011. -> Available at: diff --git a/docs/pt-br/classes/Clonal Selection Algorithms/README.md b/docs/pt-br/classes/Clonal Selection Algorithms/README.md deleted file mode 100644 index 7ffd57e..0000000 --- a/docs/pt-br/classes/Clonal Selection Algorithms/README.md +++ /dev/null @@ -1,24 +0,0 @@ -# Clonal Selection Algorithm - -Clonal Selection Algorithms são inspirados no processo biológico de proliferação de anticorpos após a detecção de um -antígeno. Durante esse processo, os anticorpos gerados passam por mutações, com o objetivo de melhorar sua capacidade -de reconhecimento do patógeno. - -## classes - -1. **[Artificial Immune Recognition System (AIRS)](AIRS.md)** - -> O objetivo da classe AIRS é realizar classificação utilizando metáforas de seleção e expansão clonal. -> Esta implementação é inspirada no AIRS2, uma versão simplificada do algoritmo original, com adaptações que permitem -> lidar tanto com conjuntos de dados contínuos quanto binários. - -2. **[Clonal Selection Algorithm (CLONALG)](Clonalg.md)** - -> Implementação do algoritmo de seleção clonal para otimização, adaptado -> para minimização e maximização das funções de custo em binário, -> Problemas contínuos e de permutação. ---- - -### Referência - -> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. *Natural Computing Algorithms*. Springer Berlin Heidelberg, 2015. DOI: 10.1007/978-3-662-43631-8. Disponível em: [http://dx.doi.org/10.1007/978-3-662-43631-8](http://dx.doi.org/10.1007/978-3-662-43631-8). diff --git a/docs/pt-br/classes/Negative Selection/BNSA.md b/docs/pt-br/classes/Negative Selection/BNSA.md deleted file mode 100644 index ccbdd2e..0000000 --- a/docs/pt-br/classes/Negative Selection/BNSA.md +++ /dev/null @@ -1,111 +0,0 @@ - -# BNSA (Algoritmo de Seleção Negativa Binária) - -Esta classe estende a classe [**Base**](../../advanced-guides/base/classifier.md). - -## Construtor BNSA - -A classe ``BNSA`` tem a finalidade de classificação e identificação de anomalias através do método self e not self. - -**Attributes:** - -* **N** (``int``): Quantidade de detectores. Defaults to ``100``. -* **aff_thresh** (``float``): A variável representa a porcentagem de não similaridade entre a célula T e as amostras próprias. O valor padrão é de 10% (0.1), enquanto que o valor de 1.0 representa 100% de não similaridade. -* **max_discards** (``int``): Este parâmetro indica o número máximo de descartes de detectores em sequência, cujo objetivo é evitar um -possível loop infinito caso seja definido um raio que não, seja possível gerar detectores do não-próprio. Defaults to ``100``. -* **seed** (``int``): Semente para a geração randômica dos valores nos detectores. Defaults to ``None``. -* no_label_sample_selection (``str``): Método para a seleção de rótulos para amostras designadas como não pertencentes por todos os detectores não pertencentes. **Tipos de métodos disponíveis:** - * (``max_average_difference``): Seleciona a classe com a maior diferença média entre os detectores. - * (``max_nearest_difference``): Seleciona a classe com a maior diferença entre o detector mais próximo e mais distante da amostra. - -**Outras variáveis iniciadas:** - -* **detectors** (``dict``): Esta variável armazena uma lista de detectores por classe. -* **classes** (``npt.NDArray``): lista de classes de saída. - -### Método `fit(...)` - -A função ``fit(...)`` gera os detectores para os não próprios com relação às amostras: - -```python -def fit( - self, - X: Union[npt.NDArray, list], - y: Union[npt.NDArray, list], - verbose: bool = True, -) -> BNSA: -``` - -Nela é realizado o treinamento de acordo com ``X`` e ``y``, usando o método de seleção negativa(``NegativeSelect``). - -**Os parâmetros de entrada são:** - -* **X** (`Union[npt.NDArray, list]`): array com as características das amostras com **N** amostras (linhas) e **N** características (colunas), normalizados para valores entre [0, 1]. -* **y** (`Union[npt.NDArray, list]`): array com as classes de saídas disposto em **N** amostras que são relacionadas ao ``X``. -* **verbose** (`bool`): boolean com valor default ``True``, determina se o feedback da geração dos detectores será imprimido. - -**Exceções:** - -* ``TypeError``: Se X ou y não forem ndarrays, ou tiverem formas incompatíveis. -* ``ValueError``: X contém valores que não são compostos apenas por 0 e 1. -* ``MaxDiscardsReachedError``: O número máximo de descartes do detector foi atingido durante a maturação. Verifique o valor do raio definido e considere reduzi-lo. - -*Retorna a instância da classe.* - ---- - -### Método `predict(...)` - -A função ``predict(...)`` realiza a previsão das classes utilizando os detectores gerados: - -```python -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -**Parâmetros:** - -* **X** (`Union[npt.NDArray, list]`): array com as características para a previsão, com **N** amostras (Linhas) e **N** colunas. - -**Exceções:** - -* `TypeError`: Se X não for um ndarray ou uma lista. -* `FeatureDimensionMismatch`: Se o número de características em X não corresponder ao número esperado. -* `ValueError`: X contém valores que não são compostos apenas por 0 e 1. -* `ModelNotFittedError`: Se o modelo ainda não tiver sido ajustado e não possuir células de memória definidas, não conseguirá realizar predições. - -**Retorna:** - -* ``C``: Um array de previsão com as classes de saída para as características informadas. - ---- - -### Método `score(...)` - -A função "score(...)" calcula a precisão do modelo treinado por meio da realização de previsões e do cálculo da acurácia. - -```python -def score(self, X: npt.NDArray, y: list) -> float: -``` - -retorna a acurácia, do tipo ``float``. - ---- - -## Métodos privados - -### Método `_assign_class_to_non_self_sample(...)` - -Essa função determina a classe de uma amostra quando todos os detectores a classificam como não-própria. A classificação é realizada utilizando os métodos ``max_average_difference`` ou ``max_nearest_difference``. - -```python -def _assign_class_to_non_self_sample(self, line: npt.NDArray, c: list): -``` - -**Parâmetros:** - -* **line** (``npt.NDArray``): Amostra a ser classificada. -* **c** (``list``): Lista de previsões para atualizar com a nova classificação. - -**Retorna:** - -``npt.NDArray``: A lista de previsões `c` atualizada com a classe atribuída à amostra. diff --git a/docs/pt-br/classes/Negative Selection/README.md b/docs/pt-br/classes/Negative Selection/README.md deleted file mode 100644 index 0efc743..0000000 --- a/docs/pt-br/classes/Negative Selection/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Seleção Negativa - -A **seleção negativa** é o processo em que o sistema imunológico faz a maturação das células-T conhecidas também por linfócitos-T, no qual tornam-as aptas na detecção dos não-próprios. Assim, o Algoritmo de seleção negativa (NSA), utilizam-se de hiperesferas simbolizando os detectores em um espaço de dados N-dimensional. [[1]](#1) - -## classes - -1. **[Binary version:](BNSA.md)** - -> O algoritmo binário adaptado para múltiplas classes neste projeto tem como base a versão proposta por [Forrest et al. (1994)](#2), originalmente desenvolvida para segurança computacional. - -2. **[Real-Valued version:](RNSA.md)** - ->Este algoritmo possui duas versões diferentes: uma baseada na versão canônica [[1]](#1) e outra com detectores de raio variável [[3]](#3). Ambas estão adaptadas para trabalhar com múltiplas classes e possuem métodos para previsão de dados presentes na região não-self de todos os detectores e classes. - -## Referências - ---- - -##### 1 -> -> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: . - -##### 2 -> -> S. Forrest, A. S. Perelson, L. Allen and R. Cherukuri, "Self-nonself discrimination in a computer," Proceedings of 1994 IEEE Computer Society Symposium on Research in Security and Privacy, Oakland, CA, USA, 1994, pp. 202-212, doi: . - -##### 3 -> -> JI, Zhou; DASGUPTA, Dipankar. Real-Valued Negative Selection Algorithm with Variable-Sized Detectors. Genetic and Evolutionary Computation - GECCO 2004. [S. l.]: Springer Berlin Heidelberg, 2004. DOI 10.1007/978-3-540-24854-5_30. Disponível em: . diff --git a/docs/pt-br/classes/Negative Selection/RNSA.md b/docs/pt-br/classes/Negative Selection/RNSA.md deleted file mode 100644 index 769e325..0000000 --- a/docs/pt-br/classes/Negative Selection/RNSA.md +++ /dev/null @@ -1,217 +0,0 @@ -# RNSA (Algoritmo de Seleção Negativa de Valor Real) - -Esta classe estende a classe [**Base**](../../advanced-guides/base/classifier.md). - -## Construtor RNSA - -A classe ``RNSA`` tem a finalidade de classificação e identificação de anomalias através do método self e not self . - -**Attributes:** - -* **N** (``int``): Quantidade de detectores. Defaults to ``100``. -* **r** (``float``): Raio do detector. Defaults to ``0.05``. -* **k** (``int``): Quantidade de vizinhos próximos dos detectores gerados aleatoriamente para efetuar o cálculo da média da distância. Defaults to ``1``. -* **metric** (``str``): Forma para se calcular a distância entre o detector e a amostra: - - * ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: √((X₁ - X₂)² + (Y₁ - Y₂)² + ... + (Yn - Yn)²). - * ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: (|X₁ - Y₁|p + |X₂ - Y₂|p + ... + |Xn - Yn|p) ¹/ₚ, Neste projeto ``p == 2``. - * ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: ( |X₁ - X₂| + |Y₁ - Y₂| + ... + |Yn - Yn₂|). - - Defaults to ``'euclidean'``. - -* **max_discards** (``int``): Este parâmetro indica o número máximo de descartes de detectores em sequência, que tem como objetivo evitar um -possível loop infinito caso seja definido um raio que não seja possível gerar detectores do não-próprio. - -* **seed** (``int``): Semente para a geração randômica dos valores nos detectores. Defaults to ``None``. -* **algorithm** (``str``), Definir a versão do algoritmo: - - * ``'default-NSA'``: Algoritmo padrão com raio fixo. - * ``'V-detector'``: Este algoritmo é baseado no artigo "[Real-Valued Negative Selection Algorithm with Variable-Sized Detectors](https://doi.org/10.1007/978-3-540-24854-5_30)", de autoria de Ji, Z., Dasgupta, D. (2004), e utiliza um raio variável para a detecção de anomalias em espaços de características. - - Defaults to ``'default-NSA'``. - -* **r_s** (``float``): O valor de ``rₛ`` é o raio das amostras próprias da matriz ``X``. -* ``**kwargs``: - * *non_self_label* (``str``): Esta variável armazena o rótulo que será atribuído quando os dados possuírem - apenas uma classe de saída, e a amostra for classificada como não pertencente a essa classe. Defaults to ``'non-self'``. - * *cell_bounds* (``bool``): Se definido como ``True``, esta opção limita a geração dos detectores ao espaço do plano - compreendido entre 0 e 1. Isso significa que qualquer detector cujo raio ultrapasse esse limite é descartado, - e esta variável é usada exclusivamente no algoritmo ``V-detector``. - -**Outras variáveis iniciadas:** - -* **detectors** (``dict``): Esta variável armazena uma lista de detectores por classe. - -* **classes** (``npt.NDArray``): lista de classes de saída. - ---- - -## Método `fit(...)` - -A função ``fit(...)`` gera os detectores para os não próprios com relação às amostras: - -```python -def fit( - self, - X: Union[npt.NDArray, list], - y: Union[npt.NDArray, list], - verbose: bool = True, -) -> RNSA: -``` - -Nela é realizado o treinamento de acordo com ``X`` e ``y``, usando o método de seleção negativa(``NegativeSelect``). - -**Parâmetros:** - -* **X** (`Union[npt.NDArray, list]`): array com as características das amostras com **N** amostras (linhas) e **N** características (colunas), normalizados para valores entre [0, 1]. -* **y** (`Union[npt.NDArray, list]`): array com as classes de saídas disposto em **N** amostras que são relacionadas ao ``X``. -* **verbose** (`bool`): boolean com valor default ``True``, determina se o feedback da geração dos detectores será impresso. - -**Exceções:** - -* ``TypeError``: Se X ou y não forem ndarrays, ou tiverem formas incompatíveis. -* ``MaxDiscardsReachedError``: O número máximo de descartes do detector foi atingido durante -a maturação. Verifique o valor do raio definido e considere reduzi-lo. - -*Retorna a instância da classe.* - ---- - -### Método `predict(...)` - -A função ``predict(...)`` realiza a previsão das classes utilizando os detectores gerados: - -```python -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -**Parâmetros:** - -* **X** (`Union[npt.NDArray, list]`): array com as características para a previsão, com **N** amostras (Linhas) e **N** colunas. - -**Exceções:** - -* ``TypeError``: Se X não for um ndarray ou lista. -* ``FeatureDimensionMismatch``: Se o número de características em X não corresponder ao número esperado. -* ``MaxDiscardsReachedError``: O número máximo de descartes do detector foi atingido durante a maturação. Verifique o valor do raio definido e considere reduzi-lo. - - -**Retorna:** - -* C (``npt.NDArray``): Um array de previsão com as classes de saída para as características informadas. - ---- - -### Método `score(...)` - -A função "score(...)" calcula a precisão do modelo treinado por meio da realização de previsões e do cálculo da acurácia. - -```python -def score(self, X: npt.NDArray, y: list) -> float: -``` - -retorna a acurácia, do tipo ``float``. - ---- - -## Métodos privados - ---- - -### Método `_checks_valid_detector(...)` - -A função ``def _checks_valid_detector(...)`` verifica se o detector possui raio ``r`` válido para o não-próprio da classe: - -```python -def _checks_valid_detector( - self, - x_class: npt.NDArray, - vector_x: npt.NDArray -) -> Union[bool, tuple[bool, float]]: -``` - -**Parâmetros:** - -* **X**(`npt.NDArray`): array com as características das amostras com **N** amostras (linhas) e **N** características (colunas), normalizados para valores entre [0, 1]. -* **vector_x**(`npt.NDArray`): Detector candidato gerado aleatoriamente. - -**Retorna:** - -* **Validity** (``bool``): Retorna se o detector é válido ou não. - ---- - -### Método `_compare_KnearestNeighbors_List(...)` - -A função ``def _compare_KnearestNeighbors_List(...)`` compara a distância dos k-vizinhos mais próximo, para isso se a distância da nova amostra for menor, substitui ``k-1`` e ordena em ordem crescente: - -```python -def _compare_knearest_neighbors_list(self, knn: list, distance: float) -> None: -``` - -**Parâmetros** -* **knn** (`list`): Lista das distâncias dos k vizinhos mais próximos. -* **distance** (`float`): Distância a ser verificada. - -**Retorna:** uma lista com as distâncias dos k-vizinhos mais próximo. - ---- - -### Método `_compare_sample_to_detectors(...)` - -Função para comparar uma amostra com os detectores, verificando se a amostra é própria. - -Nesta função, quando possui ambiguidade de classes, retorna a classe que possuir a média de distância maior entre os detectores. - -```python -def _compare_sample_to_detectors(self, line: npt.NDArray) -> Optional[str]: -``` - -**Parâmetros:** - -* **line** (`npt.NDArray`): vetor com N-características - -**Retorna:** - -A classe prevista com os detectores ou None se a amostra não se qualificar a nenhuma classe. - ---- - -### Método `_detector_is_valid_to_Vdetector(...)` - -Verifique se a distância entre o detector e as amostras, descontando o raio das amostras, é maior do que o raio mínimo. - -```python -def _detector_is_valid_to_vdetector( - self, - distance: float, - vector_x: npt.NDArray -) -> Union[bool, tuple[bool, float]]: -``` - -**Parâmetros:** - -* **distance** (``float``): distância mínima calculada entre todas as amostras. -* **vector_x** (``npt.NDArray``): vetor x candidato do detector gerado aleatoriamente, com valores entre 0 e 1. - -**Retorna:** - -* ``False``: caso o raio calculado seja menor do que a distância mínima ou ultrapasse a borda do espaço, caso essa opção esteja habilitada. -* ``True`` e a distância menos o raio das amostras, caso o raio seja válido. - ---- - -### Método `_distance(...)` - -A função ``def _distance(...)`` calcula a distância entre dois pontos utilizando a técnica definida em ``metric``, no qual são: ``'euclidiana', 'minkowski', ou 'manhattan'`` - -```python -def _distance(self, u: npt.NDArray, v: npt.NDArray): -``` -**Parameters** -* **u** (`npt.NDArray`): Coordenadas do primeiro ponto. -* **v** (`npt.NDArray`): Coordenadas do segundo ponto. - -**Retorna:** - -Retorna a distância (``float``) entre os dois pontos. diff --git a/docs/pt-br/classes/Network Theory Algorithms/AiNet.md b/docs/pt-br/classes/Network Theory Algorithms/AiNet.md deleted file mode 100644 index cc51379..0000000 --- a/docs/pt-br/classes/Network Theory Algorithms/AiNet.md +++ /dev/null @@ -1,271 +0,0 @@ -# AiNet (Artificial Immune Network) - -Esta classe estende a classe [**Base**](../../advanced-guides/base/clusterer.md). - -## Construtor AiNet - -A classe `AiNet` implementa o algoritmo de Rede Imune Artificial para **compressão** e **clustering**. -Ela utiliza princípios da teoria de redes imunes, seleção clonal e maturação por afinidade para comprimir conjuntos de dados e encontrar clusters. - -Para clustering, pode opcionalmente utilizar uma **Árvore Geradora Mínima (MST)** para separar nós distantes em grupos. - -**Atributos:** - -* **N** (`int`): Número de células de memória (anticorpos) na população. Padrão: 50. -* **n_clone** (`int`): Número de clones gerados por célula de memória selecionada. Padrão: 10. -* **top_clonal_memory_size** (`Optional[int]`): Número de anticorpos de maior afinidade selecionados para clonagem. Padrão: 5. -* **n_diversity_injection** (`int`): Número de novos anticorpos aleatórios injetados para manter a diversidade. Padrão: 5. -* **affinity_threshold** (`float`): Limite para seleção/supressão de células. Padrão: 0.5. -* **suppression_threshold** (`float`): Limite para remoção de células de memória semelhantes. Padrão: 0.5 -* **mst_inconsistency_factor** (`float`): Fator para determinar arestas inconsistentes na MST. Padrão: 2.0. -* **max_iterations** (`int`): Número máximo de iterações de treinamento. Padrão: 10. -* **k** (`int`): Número de vizinhos mais próximos usados para predição de rótulos. Padrão: 3. -* **metric** (Literal["manhattan", "minkowski", "euclidean"]): Forma de calcular a distância entre o detector e a amostra: - - * `'euclidean'` ➜ Distância dada pela expressão: - √( (x₁ - x₂)² + (y₁ - y₂)² + ... + (yn - yn)²). - * `'minkowski'` ➜ Distância dada pela expressão: - ( |X₁ - Y₁|ᵖ + |X₂ - Y₂|ᵖ + ... + |Xn - Yn|ᵖ )^(¹/ₚ). - * `'manhattan'` ➜ Distância dada pela expressão: - ( |x₁ - x₂| + |y₁ - y₂| + ... + |yn - yn|). - Padrão: "euclidean". - -* **seed** (`Optional[int]`): Semente para geração de números aleatórios. Padrão: None. -* **use_mst_clustering** (`bool`): Define se o clustering baseado em MST deve ser utilizado. Padrão: True. -* **kwargs**: - - * **p** (`float`): Parâmetro para distância de Minkowski. Padrão: 2. - -**Outras variáveis inicializadas:** - -* **_population_antibodies** (``Optional[npt.NDArray]``): Conjunto atual de anticorpos. -* **_memory_network** (``Dict[int, List[Cell]]``): Dicionário que mapeia clusters para anticorpos. -* **_mst_structure** (``Optional[npt.NDArray]``): Estrutura de adjacência da MST. -* **_mst_mean_distance** (``Optional[float]``): Média das distâncias das arestas da MST. -* **_mst_std_distance** (``Optional[float]``): Desvio padrão das distâncias das arestas da MST. -* **labels** (``Optional[npt.NDArray]``): Lista de rótulos dos clusters. - ---- - -## Métodos Públicos - -### Método `fit(...)` - -Treina o modelo AiNet com os dados de entrada: - -```python -def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> AiNet: -``` - -**Parâmetros:** - -* **X** (`Union[npt.NDArray, list]`): Matriz com amostras (linhas) e atributos (colunas). -* **verbose** (`bool`): Booleano, padrão True, habilita feedback de progresso. - -**Exceções** - -* `TypeError`: Se X não for um ndarray ou uma lista. -* `UnsupportedTypeError`: Se o tipo de dados do vetor não for suportado. - -*Retorna a instância da classe.* - ---- - -### Método `predict(...)` - -Prediz os rótulos dos clusters para novas amostras: - -```python -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -**Parâmetros:** - -* **X** (`Union[npt.NDArray, list]`): Matriz de atributos de entrada. - -**Exceções** - -* `TypeError`: Se X não for um ndarray ou uma lista. -* `ValueError`: X contém valores que não são compostos apenas por 0 e 1. -* `FeatureDimensionMismatch`: Se o número de características em X não corresponder ao número esperado. -* `ModelNotFittedError`: Se o modelo ainda não tiver sido ajustado e não possuir células de memória definidas, não conseguirá realizar predições. - -**Retorna:** - -* **Predictions**: Matriz de rótulos de clusters, ou None caso o clustering esteja desabilitado. - ---- - -### Método `update_clusters(...)` - -Particiona os clusters utilizando a MST: - -```python -def update_clusters(self, mst_inconsistency_factor: Optional[float] = None): -``` - -**Parâmetros:** - -* **mst_inconsistency_factor** (`Optional[float]`): Valor opcional (float) para sobrescrever o fator de inconsistência da MST. - -**Atualiza:** - -* **_memory_network**: Dicionário de rótulos de clusters para vetores de anticorpos. -* **labels**: Lista de rótulos de clusters. - ---- - -## Métodos Privados - -### Método `_init_population_antibodies(...)` - -Inicializa a população de anticorpos aleatoriamente. - -```python -def _init_population_antibodies(self) -> npt.NDArray: -``` - -**Retorna:** Anticorpos inicializados (`npt.NDArray`). - ---- - -### Método` _select_and_clone_population(...)` - -Seleciona os melhores anticorpos e gera clones mutados: - -```python -def _select_and_clone_population(self, antigen: npt.NDArray, population: npt.NDArray) -> list: -``` - -**Parâmetros:** - -* **antigen** (`npt.NDArray`): Vetor representando o antígeno para o qual as afinidades serão calculadas. -* **population** (`npt.NDArray`): Matriz de anticorpos a serem avaliados e clonados. - -**Retorna:** Lista de clones mutados. - ---- - -### Método `_clonal_suppression(...)` - -Suprime clones redundantes com base em limiares: - -```python -def _clonal_suppression(self, antigen: npt.NDArray, clones: list): -``` - -**Parâmetros:** - -* **antigen** (`npt.NDArray`): Vetor representando o antígeno. -* **clones** (`list`): Lista de clones candidatos a serem suprimidos. - -**Retorna:** Lista de clones não redundantes e de alta afinidade. - ---- - -### Método `_memory_suppression(...)` - -Remove anticorpos redundantes da memória: - -```python -def _memory_suppression(self, pool_memory: list) -> list: -``` - -**Parâmetros:** - -* **pool_memory** (`list`): Lista de anticorpos atualmente na memória. - -**Retorna:** - -Memória filtrada (`list`). - ---- - -### Método `_diversity_introduction(...)` - -Introduz novos anticorpos para manter a diversidade. - -```python -def _diversity_introduction(self) -> npt.NDArray: -``` - -**Retorna:** Conjunto de novos anticorpos (`npt.NDArray`). - ---- - -### Método `_affinity(...)` - -Calcula o estímulo entre dois vetores: - -```python -def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float: -``` - -**Parâmetros:** - -* **u** (`npt.NDArray`): Vetor representando o primeiro ponto. -* **v** (`npt.NDArray`): Vetor representando o segundo ponto. - -**Retorna:** Valor de afinidade (`float`) no intervalo [0,1]. - ---- - -### Método `_calculate_affinities(...)` - -Calcula a matriz de afinidades entre um vetor de referência e vetores-alvo: - -```python -def _calculate_affinities(self, u: npt.NDArray, v: npt.NDArray) -> npt.NDArray: -``` - -**Parâmetros:** - -* **u** (`npt.NDArray`): Vetor de referência (`npt.NDArray`) de formato `(n_features,)`. -* **v** (`npt.NDArray`): Vetores-alvo (`npt.NDArray`) de formato `(n_samples, n_features)`. - -**Retorna:** Vetor de afinidades (`npt.NDArray`) com formato `(n_samples,)`. - ---- - -### Método `_clone_and_mutate(...)` - -Gera clones mutados: - -```python -def _clone_and_mutate(self, antibody: npt.NDArray, n_clone: int) -> npt.NDArray: -``` - -**Parâmetros:** - -* **antibody** (`npt.NDArray`): Vetor de anticorpo original a ser clonado e mutado. -* **n_clone** (`int`): Número de clones a serem gerados. - -**Retorna:** Matriz de clones mutados (`npt.NDArray`) de formato `(n_clone, len(antibody))`. - ---- - -### Método `_build_mst(...)` - -Constrói a MST e armazena estatísticas: - -```python -def _build_mst(self): -``` - -**Exceções:** ValueError se a população de anticorpos estiver vazia. - -**Atualiza variáveis internas:** - -* **_mst_structure**: Estrutura de adjacência da MST. -* **_mst_mean_distance**: Distância média das arestas. -* **_mst_std_distance**: Desvio padrão das distâncias das arestas da MST. - ---- - -## Referências - -> 1. De Castro, Leandro & José, Fernando & von Zuben, Antonio Augusto. (2001). aiNet: An Artificial Immune Network for Data Analysis. -> 2. Disponível em: [https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis](https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis) - -> 2. SciPy Documentation. *Minimum Spanning Tree*. -> Disponível em: [https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree) diff --git a/docs/pt-br/classes/Network Theory Algorithms/README.md b/docs/pt-br/classes/Network Theory Algorithms/README.md deleted file mode 100644 index 4faa031..0000000 --- a/docs/pt-br/classes/Network Theory Algorithms/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# Immune Network Theory - -Esta técnica foi introduzida por **Niels Jerne (1974)** e modela o sistema imunológico como uma rede dinâmica, -na qual as células e moléculas, capazes de reconhecer umas às outras. - -## Classes - -1. **[AiNet](AiNet.md)** - -> Rede Imune Artificial para tarefas de clustering e compressão não-supervisionada. - ---- - -## Referências - -> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. *Natural Computing Algorithms*. Springer Berlin Heidelberg, 2015. DOI: 10.1007/978-3-662-43631-8. Disponível em: [http://dx.doi.org/10.1007/978-3-662-43631-8](http://dx.doi.org/10.1007/978-3-662-43631-8). diff --git a/docs/pt-br/index.md b/docs/pt-br/index.md deleted file mode 100644 index a8cddb4..0000000 --- a/docs/pt-br/index.md +++ /dev/null @@ -1,10 +0,0 @@ -##

**ÍNDICE**

- ---- - -### Classe do módulo: - -> 1. [**Seleção negativa**](classes/Negative%20Selection/README.md) -> 2. **Teoria do Perigo** -> 3. [**Algoritmo de Seleção Clonal.**](classes/Clonal%20Selection%20Algorithms/README.md) -> 4. [**Teoria da Rede Imune**](classes/Network%20Theory%20Algorithms/README.md) \ No newline at end of file From ab4fb0ac7448563a5f7168bc7a2e731ce91d1b52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Fri, 13 Mar 2026 12:11:53 -0300 Subject: [PATCH 28/40] feat: add example to accuracy_score docstring --- aisp/utils/metrics.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/aisp/utils/metrics.py b/aisp/utils/metrics.py index 91504f5..f3df463 100644 --- a/aisp/utils/metrics.py +++ b/aisp/utils/metrics.py @@ -28,6 +28,15 @@ def accuracy_score( ------ ValueError If `y_true` or `y_pred` are empty or if they do not have the same length. + + Examples + -------- + >>> import numpy as np + >>> from aisp.utils.metrics import accuracy_score + >>> y_true = [1, 1, 1, 1, 1] + >>> y_pred = [1, 1, 1, 0, 0] + >>> print(accuracy_score(y_true, y_pred)) + 0.6 """ n = len(y_true) if n == 0: From bdd9fa152ac99cc258aed426b18694933765598e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Fri, 13 Mar 2026 12:13:22 -0300 Subject: [PATCH 29/40] docs(exceptions): add documentation for exceptions class parameters --- aisp/base/core/_classifier.py | 4 ++-- aisp/base/core/_optimizer.py | 5 ++++- aisp/exceptions.py | 37 +++++++++++++++++++++++++++++++---- 3 files changed, 39 insertions(+), 7 deletions(-) diff --git a/aisp/base/core/_classifier.py b/aisp/base/core/_classifier.py index c5ab681..fd01d1f 100644 --- a/aisp/base/core/_classifier.py +++ b/aisp/base/core/_classifier.py @@ -83,8 +83,8 @@ def score( """ Score function calculates forecast accuracy. - Details - ------- + Notes + ----- This function performs the prediction of X and checks how many elements are equal between vector y and y_predicted. This function was added for compatibility with some scikit-learn functions. diff --git a/aisp/base/core/_optimizer.py b/aisp/base/core/_optimizer.py index 2e23825..2f1e436 100644 --- a/aisp/base/core/_optimizer.py +++ b/aisp/base/core/_optimizer.py @@ -202,7 +202,10 @@ def register(self, alias: str, function: Callable[..., Any]) -> None: setattr(self, alias, function) def reset(self): - """Reset the object's internal state, clearing history and resetting values.""" + """Reset the object's internal state. + + Clears the optimization history and resetting values. + """ self._cost_history = [] self._solution_history = [] self._best_solution = None diff --git a/aisp/exceptions.py b/aisp/exceptions.py index 4994ff2..24dcc45 100644 --- a/aisp/exceptions.py +++ b/aisp/exceptions.py @@ -4,13 +4,21 @@ class MaxDiscardsReachedError(Exception): - """Exception thrown when the maximum number of detector discards is reached.""" + """Exception thrown when the maximum number of detector discards is reached. + + Parameters + ---------- + object_name : str + The name of the instantiated class that throws the exceptions. + message : Optional[str] + Custom message to display. + """ - def __init__(self, _class_, message=None): + def __init__(self, object_name: str, message: Optional[str] = None): if message is None: message = ( "An error has been identified:\n" - f"the maximum number of discards of detectors for the {_class_} class " + f"the maximum number of discards of detectors for the {object_name} class " "has been reached.\nIt is recommended to check the defined radius and " "consider reducing its value." ) @@ -23,6 +31,15 @@ class FeatureDimensionMismatch(Exception): Exception raised when the number of input features does not match the expected number. This exception is triggered during prediction if the input features' dimension is incorrect. + + Parameters + ---------- + expected : int + The expected number of features + received : int + The actual number of features received. + variable_name : Optional[str] + The name of the variable that caused this mismatch. """ def __init__( @@ -47,9 +64,14 @@ class UnsupportedTypeError(Exception): Exception raised when the input vector type is not supported. This exception is thrown when the vector data type does not match any of the supported. + + Parameters + ---------- + message : Optional[str] + Custom message to display. """ - def __init__(self, message=None): + def __init__(self, message: Optional[str] = None): if message is None: message = ( "Type is not supported. Provide a binary, normalized, or bounded " @@ -64,6 +86,13 @@ class ModelNotFittedError(Exception): This exception is thrown when the model instance is being used without first training it via the `fit` method. + + Parameters + ---------- + object_name : str + The name of the instantiated class that throws the exceptions. + message : Optional[str] + Custom message to display. """ def __init__(self, object_name: str, message: Optional[str] = None): From 57b315842b44bf17112d350ff0c97e3e56ef8335 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Fri, 13 Mar 2026 13:00:01 -0300 Subject: [PATCH 30/40] docs(exceptions): add documentation for exceptions in the api --- docs/en/api/README.md | 7 ++- docs/en/api/csa/airs.md | 4 +- docs/en/api/exceptions.md | 89 +++++++++++++++++++++++++++++++++++++ docs/en/api/ina/ai-net.md | 6 +-- docs/en/api/nsa/bnsa.md | 6 +-- docs/en/api/nsa/rnsa.md | 6 +-- docs/en/api/utils/README.md | 4 +- 7 files changed, 108 insertions(+), 14 deletions(-) create mode 100644 docs/en/api/exceptions.md diff --git a/docs/en/api/README.md b/docs/en/api/README.md index eef3233..a8d317b 100644 --- a/docs/en/api/README.md +++ b/docs/en/api/README.md @@ -76,4 +76,9 @@ Utility functions and helpers for development. | [`multiclass`](./utils/multiclass.md) | Utility functions for handling classes with multiple categories. | | [`sanitizers`](./utils/sanitizers.md) | Utility functions for validation and treatment of parameters. | | [`types`](./utils/types.md) | Defines type aliases used throughout the project to improve readability. | -| [`validation`](./utils/validation.md) | Contains functions responsible for validating data types. | \ No newline at end of file +| [`validation`](./utils/validation.md) | Contains functions responsible for validating data types. | + + +## Exceptions ([`aisp.exceptions`](./exceptions.md)) + +Custom warnings and errors. diff --git a/docs/en/api/csa/airs.md b/docs/en/api/csa/airs.md index e526899..1146719 100644 --- a/docs/en/api/csa/airs.md +++ b/docs/en/api/csa/airs.md @@ -156,8 +156,8 @@ using the k-nearest neighbors approach. **Raises** * `TypeError` - If X is not a ndarray or list. -* `FeatureDimensionMismatch` - If the number of features in X does not match the expected number. -* `ModelNotFittedError` - If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions +* [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) - If the number of features in X does not match the expected number. +* [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) - If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions **Returns** diff --git a/docs/en/api/exceptions.md b/docs/en/api/exceptions.md new file mode 100644 index 0000000..500f7f6 --- /dev/null +++ b/docs/en/api/exceptions.md @@ -0,0 +1,89 @@ +--- +id: exceptions +sidebar_label: exceptions +keywords: + - exceptions + - raises + - warnings +--- + +# exceptions + +Custom warnings and errors. + +> **Module:** `aisp.exceptions` +> **Import:** `from aisp import exceptions` + +## Exception classes + +### MaxDiscardsReachedError + +```python +class MaxDiscardsReachedError(Exception): + ... +``` + +Exception thrown when the maximum number of detector discards is reached. + +**Parameters** + +| Name | Type | Default | Description | +|---------------|-----------------|:-------:|----------------------------------------------------------------| +| `object_name` | `str` | - | The name of the instantiated class that throws the exceptions. | +| `message` | `Optional[str]` | `None` | Custom message to display. | + +--- + +### FeatureDimensionMismatch + +```python +class FeatureDimensionMismatch(Exception): + ... +``` + +Exception raised when the number of input features does not match the expected number. +This exception is triggered during prediction if the input features' dimension is incorrect. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|-----------------|:-------:|-----------------------------------------------------| +| `expected` | `int` | - | The expected number of features | +| `received` | `int` | - | The actual number of features received. | +| `variable_name` | `Optional[str]` | `None` | The name of the variable that caused this mismatch. | + +--- +### UnsupportedTypeError + +```python +class UnsupportedTypeError(Exception): + ... +``` + +Exception raised when the input vector type is not supported. +This exception is thrown when the vector data type does not match any of the supported. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|-----------------|:-------:|----------------------------| +| `message` | `Optional[str]` | `None` | Custom message to display. | + +--- +### ModelNotFittedError + +```python +class ModelNotFittedError(Exception): + ... +``` + +Exception raised when a method is called before the model has been fit. +This exception is thrown when the model instance is being used without first training +it via the `fit` method. + +**Parameters** + +| Name | Type | Default | Description | +|---------------|-----------------|:-------:|----------------------------------------------------------------| +| `object_name` | `str` | - | The name of the instantiated class that throws the exceptions. | +| `message` | `Optional[str]` | `None` | Custom message to display. | diff --git a/docs/en/api/ina/ai-net.md b/docs/en/api/ina/ai-net.md index 35d2af7..74ccee0 100644 --- a/docs/en/api/ina/ai-net.md +++ b/docs/en/api/ina/ai-net.md @@ -124,7 +124,7 @@ Train the AiNet model on input data. **Raises** * `TypeError` - If X is not a ndarray or list. -* `UnsupportedTypeError` - If the data type of the vector is not supported. +* [`UnsupportedTypeError`](../exceptions.md#unsupportedtypeerror) - If the data type of the vector is not supported. **Returns** @@ -151,8 +151,8 @@ Predict cluster labels for input data. * `TypeError` - If X is not a ndarray or list. * `ValueError` - If the array contains values other than 0 and 1. -* `FeatureDimensionMismatch` - If the number of features in X does not match the expected number. -* `ModelNotFittedError` - If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions +* [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) - If the number of features in X does not match the expected number. +* [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) - If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions **Returns** diff --git a/docs/en/api/nsa/bnsa.md b/docs/en/api/nsa/bnsa.md index 8799459..2e4f5c7 100644 --- a/docs/en/api/nsa/bnsa.md +++ b/docs/en/api/nsa/bnsa.md @@ -130,7 +130,7 @@ Training according to X and y, using the method negative selection method. * `TypeError` - If X or y are not ndarrays or have incompatible shapes. * `ValueError` - If the array contains values other than 0 and 1. -* `MaxDiscardsReachedError` - The maximum number of detector discards was reached during maturation. Check the defined radius value and consider reducing it. +* [`MaxDiscardsReachedError`](../exceptions.md#maxdiscardsreachederror) - The maximum number of detector discards was reached during maturation. Check the defined radius value and consider reducing it. **Returns** @@ -157,8 +157,8 @@ Prediction of classes based on detectors created after training. * `TypeError` - If X is not a ndarray or list. * `ValueError` - If the array contains values other than 0 and 1. -* `FeatureDimensionMismatch` - If the number of features in X does not match the expected number. -* `ModelNotFittedError` - If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions +* [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) - If the number of features in X does not match the expected number. +* [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) - If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions **Returns** diff --git a/docs/en/api/nsa/rnsa.md b/docs/en/api/nsa/rnsa.md index a3066e3..0001eff 100644 --- a/docs/en/api/nsa/rnsa.md +++ b/docs/en/api/nsa/rnsa.md @@ -155,7 +155,7 @@ Perform training according to X and y, using the negative selection method (Nega * `TypeError` - If X or y are not ndarrays or have incompatible shapes. * `ValueError` - If the array X fall outside the interval (0, 1). -* `MaxDiscardsReachedError` - The maximum number of detector discards was reached during maturation. Check the defined radius value and consider reducing it. +* [`MaxDiscardsReachedError`](../exceptions.md#maxdiscardsreachederror) - The maximum number of detector discards was reached during maturation. Check the defined radius value and consider reducing it. **Returns** @@ -182,8 +182,8 @@ Prediction of classes based on detectors created after training. * `TypeError` - If X is not a ndarray or list. * `ValueError` - If the array X fall outside the interval (0, 1). -* `FeatureDimensionMismatch` - If the number of features in X does not match the expected number. -* `ModelNotFittedError` - If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions +* [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) - If the number of features in X does not match the expected number. +* [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) - If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions **Returns** diff --git a/docs/en/api/utils/README.md b/docs/en/api/utils/README.md index eae04d5..f5e36c8 100644 --- a/docs/en/api/utils/README.md +++ b/docs/en/api/utils/README.md @@ -1,13 +1,13 @@ --- id: utils -sidebar_label: utils +sidebar_label: aisp.utils keywords: - functions - helpers - utils --- -# utils +# aisp.utils Utility functions and helpers for development. From 2cbb35c12a516d02b840476db941fa48d91a5af8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Fri, 13 Mar 2026 18:07:28 -0300 Subject: [PATCH 31/40] docs(exceptions): add documentation for exceptions in the api --- docs/en/api/README.md | 6 +++--- docs/en/api/base/immune/README.md | 2 +- docs/en/api/exceptions.md | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/en/api/README.md b/docs/en/api/README.md index a8d317b..20af6cb 100644 --- a/docs/en/api/README.md +++ b/docs/en/api/README.md @@ -60,9 +60,9 @@ Algorithms inspired by the process of antibody proliferation to detecting an ant Algorithms based on Network Theory Algorithms proposed by Jerne. -| Class | Description | -|------------------------|--------------------------------------------------------------------------------------------| -| [`AiNet`](./ai-net.md) | An unsupervised learning algorithm for clustering, based on the theory of immune networks. | +| Class | Description | +|----------------------------|--------------------------------------------------------------------------------------------| +| [`AiNet`](./ina/ai-net.md) | An unsupervised learning algorithm for clustering, based on the theory of immune networks. | ## Utils ([`aisp.utils`](./utils/README.md)) diff --git a/docs/en/api/base/immune/README.md b/docs/en/api/base/immune/README.md index 5fbdd56..5e196cb 100644 --- a/docs/en/api/base/immune/README.md +++ b/docs/en/api/base/immune/README.md @@ -1,6 +1,6 @@ --- id: immune -sidebar_label: cell +sidebar_label: immune keywords: - cell - mutation diff --git a/docs/en/api/exceptions.md b/docs/en/api/exceptions.md index 500f7f6..48fa150 100644 --- a/docs/en/api/exceptions.md +++ b/docs/en/api/exceptions.md @@ -1,13 +1,13 @@ --- id: exceptions -sidebar_label: exceptions +sidebar_label: aisp.exceptions keywords: - exceptions - raises - warnings --- -# exceptions +# aisp.exceptions Custom warnings and errors. From e87e0839dea3859e3f37df3f443d05dd9e5f464d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Sat, 14 Mar 2026 10:47:15 -0300 Subject: [PATCH 32/40] docs(cell): adds pt-br documentation for Cell in the API --- aisp/base/immune/cell.py | 6 +-- docs/en/api/base/immune/cell/b-cell.md | 14 ++--- docs/pt-br/api/base/immune/cell/README.md | 32 +++++++++++ docs/pt-br/api/base/immune/cell/antibody.md | 39 ++++++++++++++ docs/pt-br/api/base/immune/cell/b-cell.md | 60 +++++++++++++++++++++ docs/pt-br/api/base/immune/cell/cell.md | 35 ++++++++++++ docs/pt-br/api/base/immune/cell/detector.md | 28 ++++++++++ 7 files changed, 204 insertions(+), 10 deletions(-) create mode 100644 docs/pt-br/api/base/immune/cell/README.md create mode 100644 docs/pt-br/api/base/immune/cell/antibody.md create mode 100644 docs/pt-br/api/base/immune/cell/b-cell.md create mode 100644 docs/pt-br/api/base/immune/cell/cell.md create mode 100644 docs/pt-br/api/base/immune/cell/detector.md diff --git a/aisp/base/immune/cell.py b/aisp/base/immune/cell.py index a085e3d..e991c1c 100644 --- a/aisp/base/immune/cell.py +++ b/aisp/base/immune/cell.py @@ -72,14 +72,14 @@ def hyper_clonal_mutate( bounds: Optional[npt.NDArray[np.float64]] = None ) -> npt.NDArray: """ - Clones N features from a cell's features, generating a set of mutated vectors. + Generate N clones of the current cell and apply hypermutation to the clones. Parameters ---------- n : int - Number of clones to be generated from mutations of the original cell. + Number of clones to generate from the original b-cell. feature_type : { "binary-features", "continuous-features", "ranged-features" } - Specifies the type of feature_type to use based on the nature of the input features + Specifies the type of features of the cell. bounds : npt.NDArray[np.float64], optional Array (n_features, 2) with min and max per dimension. diff --git a/docs/en/api/base/immune/cell/b-cell.md b/docs/en/api/base/immune/cell/b-cell.md index a48fa93..af312b1 100644 --- a/docs/en/api/base/immune/cell/b-cell.md +++ b/docs/en/api/base/immune/cell/b-cell.md @@ -27,7 +27,7 @@ This class extends [Cell](./cell.md) | Name | Type | Default | Description | |----------|--------------|:-------:|----------------------------| -| `vector` | `np.ndarray` | - | A vector of cell features. |] +| `vector` | `np.ndarray` | - | A vector of cell features. | --- @@ -45,15 +45,15 @@ def hyper_clonal_mutate( ... ``` -Clones N features from a cell's features, generating a set of mutated vectors. +Generate **N** clones of the current cell and apply hypermutation to the clones. **Parameters** -| Name | Type | Default | Description | -|----------------|------------------------------------------------------|:-----------------------:|-------------------------------------------------------------------------------------| -| `n` | `int` | - | Number of clones to be generated from mutations of the original cell. | -| `feature_type` | [`FeatureType`](../../../utils/types.md#featuretype) | `"continuous-features"` | Specifies the type of feature_type to use based on the nature of the input features | -| `bounds` | `Optional[npt.NDArray[np.float64]]` | `None` | Array (n_features, 2) with min and max per dimension. | +| Name | Type | Default | Description | +|----------------|------------------------------------------------------|:-----------------------:|--------------------------------------------------------| +| `n` | `int` | - | Number of clones to generate from the original b-cell. | +| `feature_type` | [`FeatureType`](../../../utils/types.md#featuretype) | `"continuous-features"` | Specifies the type of features of the cell. | +| `bounds` | `Optional[npt.NDArray[np.float64]]` | `None` | Array (n_features, 2) with min and max per dimension. | **Returns** diff --git a/docs/pt-br/api/base/immune/cell/README.md b/docs/pt-br/api/base/immune/cell/README.md new file mode 100644 index 0000000..0c4aa8a --- /dev/null +++ b/docs/pt-br/api/base/immune/cell/README.md @@ -0,0 +1,32 @@ +--- +id: immune-cell +sidebar_label: cell +keywords: + - vector representation + - cell + - immune + - immune cell + - base class + - bcell + - antibody + - dataclass +--- + +# aisp.base.immune.cell + +Representação de células do sistema imunológico. + +> **Module:** `aisp.base.immune.cell` + +## Visão geral + +Este módulo define as representações de células dos sistemas imunológicos artificiais e as implementa como dataclass. + +## Classes + +| Class | Descrição | +|-----------------------------|----------------------------------------------------| +| [`Cell`](./cell.md) | Representa uma célula imune básica. | +| [`BCell`](./b-cell.md) | Representa uma célula-B de memória. | +| [`Antibody`](./antibody.md) | Representa um anticorpo. | +| [`Detector`](./detector.md) | Representa um detector não-próprio da classe rnsa. | \ No newline at end of file diff --git a/docs/pt-br/api/base/immune/cell/antibody.md b/docs/pt-br/api/base/immune/cell/antibody.md new file mode 100644 index 0000000..5587a53 --- /dev/null +++ b/docs/pt-br/api/base/immune/cell/antibody.md @@ -0,0 +1,39 @@ +--- +id: antibody +sidebar_label: Antibody +keywords: + - anticorpo + - afinidade + - célula + - imune + - dataclass +--- + +# Antibody + +Representa um anticorpo. + +:::tip[Herança] + +Esta classe herda de [Cell](./cell.md) + +::: + +> **Módulo:** `aisp.base.immune.cell` +> **Importação:** `from aisp.base.immune.cell import Antibody` + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|------------|---------------|:------:|----------------------------------------| +| `vector` | `npt.NDArray` | - | Vetor com as características anticorpo | +| `affinity` | `float` | - | Valor da afinidade do anticorpo | + +--- + +## Métodos + +* `__lt__(other)`: Compara a célula atual com outra célula `Antibody` com base na afinidade. +* `__eq__(other)`: Verifica se o anticorpo possui a mesma afinidade do outro. diff --git a/docs/pt-br/api/base/immune/cell/b-cell.md b/docs/pt-br/api/base/immune/cell/b-cell.md new file mode 100644 index 0000000..223a28d --- /dev/null +++ b/docs/pt-br/api/base/immune/cell/b-cell.md @@ -0,0 +1,60 @@ +--- +id: b-cell +sidebar_label: BCell +keywords: + - célula-b + - memória imune + - dataclass + - mutação clonal + - expansão clonal +--- + +# BCell + +Representa uma célula-B de memória. + +:::tip[Herança] + +Esta classe herda de [Cell](./cell.md) + +::: + +> **Módulo:** `aisp.base.immune.cell` +> **Importação:** `from aisp.base.immune.cell import BCell` + +--- +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|----------|--------------|:------:|-----------------------------------------| +| `vector` | `np.ndarray` | - | Vetor com as características da célula. | + +--- + +## Métodos Públicos + +### hyper_clonal_mutate + +```python +def hyper_clonal_mutate( + self, + n: int, + feature_type: FeatureType = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None +) -> npt.NDArray: + ... +``` + +Gera **N** clones da célula atual e aplica hipermutação aos clones. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------------|------------------------------------------------------|:-----------------------:|-----------------------------------------------------------------| +| `n` | `int` | - | Numero de clones que serão gerados a partir da célula original. | +| `feature_type` | [`FeatureType`](../../../utils/types.md#featuretype) | `"continuous-features"` | Especifica o tipo de características da célula. | +| `bounds` | `Optional[npt.NDArray[np.float64]]` | `None` | Matriz (n_features, 2) com o min e o max de cada dimensão. | + +**Returns** + +`npt.NDArray` - Uma matriz contendo N clones mutados da célula original. diff --git a/docs/pt-br/api/base/immune/cell/cell.md b/docs/pt-br/api/base/immune/cell/cell.md new file mode 100644 index 0000000..0d7955c --- /dev/null +++ b/docs/pt-br/api/base/immune/cell/cell.md @@ -0,0 +1,35 @@ +--- +id: cell +sidebar_label: Cell +keywords: + - vector representation + - cell + - immune + - immune cell + - base class + - dataclass +--- + +# Cell + +Representa uma célula imune básica. + +> **Módulo:** `aisp.base.immune.cell` +> **Importação:** `from aisp.base.immune.cell import Cell` + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|----------|--------------|:------:|-----------------------------------------| +| `vector` | `np.ndarray` | - | Vetor com as características da célula. | + +--- + +## Métodos + +* `__eq__(other)`: Verifica se duas células são iguais com base nos seus vetores. +* `__array__()`: Interface de array Numpy, permite que a instância seja tratada como um `np.ndarray` +* `__getitem__(item)`: Obtém um elemento do vetor com base no index. + diff --git a/docs/pt-br/api/base/immune/cell/detector.md b/docs/pt-br/api/base/immune/cell/detector.md new file mode 100644 index 0000000..71fcfdc --- /dev/null +++ b/docs/pt-br/api/base/immune/cell/detector.md @@ -0,0 +1,28 @@ +--- +id: detector +sidebar_label: Detector +keywords: + - detector + - célula + - imune + - raio + - não-próprio + - nsa + - dataclass +--- + +# Detector + +Representa um detector não-próprio da classe rnsa. + +> **Módulo:** `aisp.base.immune.cell` +> **Importação:** `from aisp.base.immune.cell import Detector` + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|------------|---------------------------|:------:|--------------------------------------------------| +| `position` | `npt.NDArray[np.float64]` | - | Vetor com as características do detector. | +| `radius` | `float, optional` | - | Raio do detector, usado no algoritmo V-detector. | From d5d2cba37711ec34e2f2981f846025aad57cc053 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Sat, 14 Mar 2026 15:22:07 -0300 Subject: [PATCH 33/40] docs(cell): adds pt-br documentation for immune in the API --- aisp/base/immune/mutation.py | 34 +++--- docs/en/api/base/immune/mutation.md | 51 ++++---- docs/pt-br/api/base/immune/README.md | 22 ++++ docs/pt-br/api/base/immune/mutation.md | 139 ++++++++++++++++++++++ docs/pt-br/api/base/immune/populations.md | 52 ++++++++ 5 files changed, 251 insertions(+), 47 deletions(-) create mode 100644 docs/pt-br/api/base/immune/README.md create mode 100644 docs/pt-br/api/base/immune/mutation.md create mode 100644 docs/pt-br/api/base/immune/populations.md diff --git a/aisp/base/immune/mutation.py b/aisp/base/immune/mutation.py index 081e072..b6faac9 100644 --- a/aisp/base/immune/mutation.py +++ b/aisp/base/immune/mutation.py @@ -19,9 +19,8 @@ def clone_and_mutate_continuous( """ Generate a set of mutated clones from a cell represented by a continuous vector. - This function creates `n` clones of the input vector and applies random mutations to each of - them, simulating the process of clonal expansion in artificial immune systems. Each clone - will have a random number of mutations applied in distinct positions of the original vector. + This function creates `n` clones of the input vector and applies mutations to each of + them, simulating the process of clonal expansion in artificial immune systems. Parameters ---------- @@ -30,9 +29,8 @@ def clone_and_mutate_continuous( n : int The number of mutated clones to be generated. mutation_rate : float, default=1 - If 0 ≤ mutation_rate < 1: probability of mutating each component. - If mutation_rate ≥ 1 or mutation_rate ≤ 0: the mutation randomizes - a number of components between 1 and len(vector). + If 0 ≤ mutation_rate < 1, mutation probability per feature. + Otherwise, a random number of features is mutated. Returns ------- @@ -67,9 +65,8 @@ def clone_and_mutate_binary( """ Generate a set of mutated clones from a cell represented by a binary vector. - This function creates `n` clones of the input vector and applies random mutations to each of - them, changing some bits randomly. The process simulates clonal expansion in artificial - immune systems with discrete representations. + This function creates `n` clones of the input binary vector and applies mutations to the + bits, simulating clonal expansion in artificial immune systems with discrete representations. Parameters ---------- @@ -78,9 +75,8 @@ def clone_and_mutate_binary( n : int The number of mutated clones to be generated. mutation_rate : float, default=1 - If 0 ≤ mutation_rate < 1: probability of mutating each component. - If mutation_rate ≥ 1 or mutation_rate ≤ 0: the mutation randomizes - a number of components between 1 and len(vector). + If 0 ≤ mutation_rate < 1, mutation probability per feature. + Otherwise, a random number of features is mutated. Returns ------- @@ -116,9 +112,8 @@ def clone_and_mutate_ranged( """ Generate a set of mutated clones from a cell represented by custom ranges per dimension. - This function creates `n` clones of the input vector and applies random mutations to each of - them, simulating the process of clonal expansion in artificial immune systems. Each clone - will have a random number of mutations applied in distinct positions of the original vector. + This function creates `n` clones of the input vector and applies mutations to each of + them, simulating the process of clonal expansion in artificial immune systems. Parameters ---------- @@ -129,9 +124,8 @@ def clone_and_mutate_ranged( bounds : np.ndarray Array (n_features, 2) with min and max per dimension. mutation_rate : float, default=1 - If 0 ≤ mutation_rate < 1: probability of mutating each component. - If mutation_rate ≥ 1 or mutation_rate ≤ 0: the mutation randomizes - a number of components between 1 and len(vector). + If 0 ≤ mutation_rate < 1, mutation probability per feature. + Otherwise, a random number of features is mutated. Returns ------- @@ -166,7 +160,7 @@ def clone_and_mutate_permutation( n: int, mutation_rate: float ) -> npt.NDArray[np.int64]: - """Generate a set of mutated clones by random permutation. + """Generate a set of mutated clones by permutation. Parameters ---------- @@ -175,7 +169,7 @@ def clone_and_mutate_permutation( n : int The number of mutated clones to be generated. mutation_rate : float - Probability of mutating each component 0 ≤ mutation_rate < 1. + Probability of mutating each feature 0 ≤ mutation_rate < 1. Returns ------- diff --git a/docs/en/api/base/immune/mutation.md b/docs/en/api/base/immune/mutation.md index a73d563..2cae87e 100644 --- a/docs/en/api/base/immune/mutation.md +++ b/docs/en/api/base/immune/mutation.md @@ -35,17 +35,16 @@ def clone_and_mutate_continuous( Generate a set of mutated clones from a cell represented by a continuous vector. -This function creates `n` clones of the input vector and applies random mutations to each of them, simulating the -process of clonal expansion in artificial immune systems. Each clone will have a random number of mutations applied -in distinct positions of the original vector. +This function creates `n` clones of the input vector and applies mutations to each of +them, simulating the process of clonal expansion in artificial immune systems. **Parameters** -| Name | Type | Default | Description | -|-----------------|---------------------------|:-------:|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with continuous values to be cloned and mutated. | -| `n` | `int` | - | The number of mutated clones to be generated. | -| `mutation_rate` | `float` | - | If 0 ≤ mutation_rate < 1: probability of mutating each component. If mutation_rate ≥ 1 or mutation_rate ≤ 0: the mutation randomizes a number of components between 1 and len(vector). | +| Name | Type | Default | Description | +|-----------------|---------------------------|:-------:|------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with continuous values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `mutation_rate` | `float` | - | If `0 ≤ mutation_rate < 1`, mutation probability per feature. Otherwise, a random number of features is mutated. | **Returns** @@ -65,17 +64,16 @@ def clone_and_mutate_binary( Generate a set of mutated clones from a cell represented by a binary vector. -This function creates `n` clones of the input vector and applies random mutations to each of -them, changing some bits randomly. The process simulates clonal expansion in artificial -immune systems with discrete representations. +This function creates `n` clones of the input binary vector and applies mutations to the +bits, simulating clonal expansion in artificial immune systems with discrete representations. **Parameters** -| Name | Type | Default | Description | -|-----------------|---------------------------|:-------:|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with binary values to be cloned and mutated. | -| `n` | `int` | - | The number of mutated clones to be generated. | -| `mutation_rate` | `float` | - | If 0 ≤ mutation_rate < 1: probability of mutating each component. If mutation_rate ≥ 1 or mutation_rate ≤ 0: the mutation randomizes a number of components between 1 and len(vector). | +| Name | Type | Default | Description | +|-----------------|---------------------------|:-------:|------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with binary values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `mutation_rate` | `float` | - | If `0 ≤ mutation_rate < 1`, mutation probability per feature. Otherwise, a random number of features is mutated. | **Returns** @@ -97,18 +95,17 @@ def clone_and_mutate_ranged( Generate a set of mutated clones from a cell represented by custom ranges per dimension. -This function creates `n` clones of the input vector and applies random mutations to each of -them, simulating the process of clonal expansion in artificial immune systems. Each clone -will have a random number of mutations applied in distinct positions of the original vector. +This function creates `n` clones of the input vector and applies mutations to each of +them, simulating the process of clonal expansion in artificial immune systems. **Parameters** -| Name | Type | Default | Description | -|-----------------|---------------------------|:-------:|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with continuous values to be cloned and mutated. | -| `n` | `int` | - | The number of mutated clones to be generated. | -| `bounds` | `np.ndarray` | - | Array (n_features, 2) with min and max per dimension. | -| `mutation_rate` | `float` | - | If 0 ≤ mutation_rate < 1: probability of mutating each component. If mutation_rate ≥ 1 or mutation_rate ≤ 0: the mutation randomizes a number of components between 1 and len(vector). | +| Name | Type | Default | Description | +|-----------------|---------------------------|:-------:|------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with continuous values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `bounds` | `np.ndarray` | - | Array (n_features, 2) with min and max per dimension. | +| `mutation_rate` | `float` | - | If `0 ≤ mutation_rate < 1`, mutation probability per feature. Otherwise, a random number of features is mutated. | **Returns** @@ -127,7 +124,7 @@ def clone_and_mutate_permutation( ... ``` -Generate a set of mutated clones by random permutation. +Generate a set of mutated clones by permutation. **Parameters** @@ -135,7 +132,7 @@ Generate a set of mutated clones by random permutation. |-----------------|-------------------------|:-------:|----------------------------------------------------------------------------| | `vector` | `npt.NDArray[np.int64]` | - | The original immune cell with permutation values to be cloned and mutated. | | `n` | `int` | - | The number of mutated clones to be generated. | -| `mutation_rate` | `float` | - | Probability of mutating each component 0 ≤ mutation_rate < 1. | +| `mutation_rate` | `float` | - | Probability of mutating each feature 0 ≤ mutation_rate < 1. | **Returns** diff --git a/docs/pt-br/api/base/immune/README.md b/docs/pt-br/api/base/immune/README.md new file mode 100644 index 0000000..3b307af --- /dev/null +++ b/docs/pt-br/api/base/immune/README.md @@ -0,0 +1,22 @@ +--- +id: immune +sidebar_label: immune +keywords: + - célula + - mutações + - populações +--- + +# aisp.base.immune + +Módulo de suporte para sistemas imunológicos artificias. + +> **Módulo:** `aisp.base.immune` + +## Submódulos + +| Módulos | Descrição | +|-----------------------------------|------------------------------------------------------------------------------------------------------------| +| [`cell`](./cell/README.md) | Representação de células do sistema imunológico. | +| [`mutation`](./mutation.md) | Funções para gerar clones hipermutados similar a expansão clonal. | +| [`populations`](./populations.md) | Fornece funções utilitárias para gerar populações de anticorpos utilizadas em algoritmos imuno-inspirados. | \ No newline at end of file diff --git a/docs/pt-br/api/base/immune/mutation.md b/docs/pt-br/api/base/immune/mutation.md new file mode 100644 index 0000000..27f2e9c --- /dev/null +++ b/docs/pt-br/api/base/immune/mutation.md @@ -0,0 +1,139 @@ +--- +id: mutation +sidebar_label: mutation +keywords: + - mutações + - expansão clonal + - sistema imune + - funções python com numba + - vetor de mutações +--- + +# mutation + +As funções utilizam decoradores do Numba para compilação Just-In-Time(JIT). + +Contém funções que geram conjuntos de clones hipermutados a partir de vetores contínuos ou binários, simulando o processo +de expansão clonal dos sistemas imunológicos artificiais. + +> **Módulo:** `aisp.base.immune` +> **Importação:** `from aisp.base.immune import mutation` + +## Funções + +### clone_and_mutate_continuous + +```python +@njit([(types.float64[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_continuous( + vector: npt.NDArray[np.float64], + n: int, + mutation_rate: float +) -> npt.NDArray[np.float64]: + ... +``` + +Gera um conjunto de clones mutados a partir de um vetor contínuo. + +Esta função cria `n` clones do vetor de entrada e aplica mutações em cada um, simulando o processo +de expansão clonal em sistemas imunes artificiais. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------------|---------------------------|:------:|----------------------------------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | Vetor contínuo original que representa a célula imune a ser clonada e mutada. | +| `n` | `int` | - | Quantidade de clones mutados que serão gerados. | +| `mutation_rate` | `float` | - | Se 0 ≤ mutation_rate < 1, usa probabilidade de mutação por características. Caso contrario, um número aleatorio de características é mutado. | + +**Returns** + +`npt.NDArray[np.float64]` - Array com dimensões (n, len(vector)) contendo os `n` clones mutados do vetor original. + +### clone_and_mutate_binary + +```python +@njit([(types.boolean[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_binary( + vector: npt.NDArray[np.bool_], + n: int, + mutation_rate: float +) -> npt.NDArray[np.bool_]: + ... +``` + +Gera um conjunto de clones mutados a partir de um vetor binário. + +Esta função cria `n` clones do vetor binário de entrada e aplica mutações aos bits, simulando a expansão +clonal em sistemas imunes artificiais com representações discretas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------------|---------------------------|:------:|----------------------------------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | Vetor binário original que representa a célula imune a ser clonada e mutada. | +| `n` | `int` | - | Quantidade de clones mutados a serão gerados. | +| `mutation_rate` | `float` | - | Se 0 ≤ mutation_rate < 1, usa probabilidade de mutação por características. Caso contrario, um número aleatorio de características é mutado. | + +**Returns** + +`npt.NDArray[np.bool_]` - Array com dimensões (n, len(vector)) contendo os `n` clones mutados do vetor original. + + +### clone_and_mutate_ranged + +```python +@njit([(types.float64[:], types.int64, types.float64[:, :], types.float64)], cache=True) +def clone_and_mutate_ranged( + vector: npt.NDArray[np.float64], + n: int, + bounds: npt.NDArray[np.float64], + mutation_rate: float, +) -> npt.NDArray[np.float64]: + ... +``` + +Gera um conjunto de clones mutados a partir de uma célula representada pelo intervalo personalizados por dimensão.. + +Esta função cria `n` clones do vetor de entrada e aplica mutações em cada um, simulando o processo +de expansão clonal em sistemas imunes artificiais. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------------|---------------------------|:------:|----------------------------------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | Vetor contínuo original que representa a célula imune a ser clonada e mutada. | +| `n` | `int` | - | Quantidade de clones mutados a serão gerados. | +| `bounds` | `np.ndarray` | - | Array (n_features, 2) com valor mínimo e máximo por dimensão. | +| `mutation_rate` | `float` | - | Se 0 ≤ mutation_rate < 1, usa probabilidade de mutação por características. Caso contrario, um número aleatorio de características é mutado. | + +**Returns** + +`npt.NDArray[np.float64]` - Array com dimensões (n, len(vector)) contendo os `n` clones mutados do vetor original. + + +### clone_and_mutate_continuous + +```python +@njit([(types.int64[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_permutation( + vector: npt.NDArray[np.int64], + n: int, + mutation_rate: float +) -> npt.NDArray[np.int64]: + ... +``` + +Gera um conjunto de clones com mutações por permutação. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------------|-------------------------|:------:|------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.int64]` | - | Vetor de permutação original que representa a célula imune a ser clonada e mutada. | +| `n` | `int` | - | Quantidade de clones mutados a serão gerados. | +| `mutation_rate` | `float` | - | Probabilidade de mutação de uma característica. | + +**Returns** + +`npt.NDArray[np.float64]` - Array com dimensões (n, len(vector)) contendo os `n` clones mutados do vetor original. diff --git a/docs/pt-br/api/base/immune/populations.md b/docs/pt-br/api/base/immune/populations.md new file mode 100644 index 0000000..51b18ef --- /dev/null +++ b/docs/pt-br/api/base/immune/populations.md @@ -0,0 +1,52 @@ +--- +id: populations +sidebar_label: populations +keywords: + - binário + - classificação + - limiar de afinidade + - real-valor + - célula-b de memória + - expansão clonal + - população +--- + +# populations + +Fornece funções utilitárias para **gerar populações** de anticorpos utilizadas em algoritmos imuno-inspirados. + +> **Módulo:** `aisp.base.immune` +> **Importação:** `from aisp.base.immune import populations` + +## Funções + +### generate_random_antibodies + +```python +def generate_random_antibodies( + n_samples: int, + n_features: int, + feature_type: FeatureTypeAll = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None, +) -> npt.NDArray: + ... +``` + +Gera uma população aleatória de anticorpos. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------------|---------------------------------------------------------|:-----------------------:|--------------------------------------------------------------------------------------------------------------------------------| +| `n_samples` | `int` | - | Número de anticorpos (amostras) que serão gerados. | +| `n_features` | `int` | - | Número de características (dimensões) para cada anticorpo. | +| `feature_type` | [`FeatureTypeAll`](../../utils/types.md#featuretypeall) | `"continuous-features"` | Especifica o tipo das características: "continuous-features", "binary-features", "ranged-features", or "permutation-features". | +| `bounds` | `npt.NDArray[np.float64]` | `None` | Array (n_features, 2) contendo os valores mínimo e máximo por dimensão. | + +**Exceções** + +`ValueError` - Lançado caso o número de características seja menor ou igual a zero. + +**Returns** + +`npt.NDArray` - Array de dimensão (n_samples, n_features) contendo os anticorpos gerados. From 6415d920f50fb9ba2c1a1b4fa6ca210afd1c8f3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Sun, 15 Mar 2026 16:24:23 -0300 Subject: [PATCH 34/40] docs(cell): adds pt-br documentation for base in the API --- aisp/base/core/_optimizer.py | 4 +- docs/en/api/base/base-optimizer.md | 3 +- docs/pt-br/api/base/README.md | 33 +++++ docs/pt-br/api/base/base-classifier.md | 128 ++++++++++++++++++ docs/pt-br/api/base/base-clusterer.md | 115 ++++++++++++++++ docs/pt-br/api/base/base-optimizer.md | 157 ++++++++++++++++++++++ docs/pt-br/api/base/immune/README.md | 6 +- docs/pt-br/api/base/immune/cell/README.md | 2 +- docs/pt-br/api/base/immune/cell/b-cell.md | 11 +- docs/pt-br/api/base/immune/mutation.md | 17 ++- docs/pt-br/api/base/immune/populations.md | 14 +- 11 files changed, 463 insertions(+), 27 deletions(-) create mode 100644 docs/pt-br/api/base/README.md create mode 100644 docs/pt-br/api/base/base-classifier.md create mode 100644 docs/pt-br/api/base/base-clusterer.md create mode 100644 docs/pt-br/api/base/base-optimizer.md diff --git a/aisp/base/core/_optimizer.py b/aisp/base/core/_optimizer.py index 2f1e436..aff2a42 100644 --- a/aisp/base/core/_optimizer.py +++ b/aisp/base/core/_optimizer.py @@ -160,7 +160,9 @@ def optimize( def affinity_function(self, solution: Any) -> float: """Evaluate the affinity of a candidate solution. - This abstract method must be implemented by the subclass to define the problem-specific. + This method must be implemented according to the specific optimization problem, defining + how the solution will be evaluated. The returned value should represent the quality of + the evaluated solution. Parameters ---------- diff --git a/docs/en/api/base/base-optimizer.md b/docs/en/api/base/base-optimizer.md index 001f0bc..f436641 100644 --- a/docs/en/api/base/base-optimizer.md +++ b/docs/en/api/base/base-optimizer.md @@ -90,7 +90,8 @@ def affinity_function(self, solution: Any) -> float: Evaluate the affinity of a candidate solution. -This abstract method must be implemented by the subclass to define the problem-specific. +This method must be implemented according to the specific optimization problem, defining how the solution will be evaluated. +The returned value should represent the quality of the evaluated solution. **Parameters** diff --git a/docs/pt-br/api/base/README.md b/docs/pt-br/api/base/README.md new file mode 100644 index 0000000..99b354e --- /dev/null +++ b/docs/pt-br/api/base/README.md @@ -0,0 +1,33 @@ +--- +id: base +sidebar_label: aisp.base +keywords: + - base + - imune + - abstrato +--- + +# aisp.base + +Classe base e utilitários centrais + +> **Módulos:** `aisp.base` + +## Visão geral + +Este modulo fornece as classes e utilidades fundamentais para todos os algoritmos de sistemas imunológicos artificiais +implementados no AISP. + +## Classes + +| Class | Descrição | +|------------------------------------------|--------------------------------------------------------| +| [`BaseClassifier`](./base-classifier.md) | Classe base abstrata para algoritmos de classificação. | +| [`BaseClusterer`](./base-clusterer.md) | Classe base abstrata para algoritmos de clustering. | +| [`BaseOptimizer`](./base-optimizer.md) | Classe base abstrata para algoritmos de otimização. | + +## Submódulos + +| Módulo | Descrição | +|--------------------------------|----------------------------------------------------------| +| [`immune`](./immune/README.md) | Módulo de suporte para sistemas imunológicos artificias. | \ No newline at end of file diff --git a/docs/pt-br/api/base/base-classifier.md b/docs/pt-br/api/base/base-classifier.md new file mode 100644 index 0000000..2f529aa --- /dev/null +++ b/docs/pt-br/api/base/base-classifier.md @@ -0,0 +1,128 @@ +--- +id: base-classifier +sidebar_label: BaseClassifier +keywords: + - base + - classificação + - classificação interface + - pontuação de acurácia + - fit + - predict +tags: + - classificador + - classificação +--- + +# BaseClassifier + +Classe base abstrata para algoritmos de classificação. + +> **Módulo:** `aisp.base` +> **Importação:** `from aisp.base import BaseClassifier` + +--- + +## Visão geral + +Esta classe define a interface principal para algoritmos de classificação. +Ela define a implementação dos metodos `fit` e `predict` em todas as classes derivadas, e fornece uma implementação +do método `score`. + +Caso de uso: + +- Classe base abstrata para estender classes de algoritmos de classificação. + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|-----------|-------------------------|:------:|----------------------------------------------------------------| +| `classes` | `Optional[npt.NDArray]` | `None` | Rótulos das classes identificado de `y` durante o treinamento. | + +--- + +## Métodos abstratos + +### fit + +```python +@abstractmethod +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True +) -> BaseClassifier: + ... +``` + +Treine o modelo usando os dados de entrada X e seus rótulos correspondentes y. +Este método abstrato é implementado é responsabilidade das classes filhas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|----------------------------|:------:|----------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Dados de entrada utilizados para o treinamento. | +| `y` | `Union[npt.NDArray, list]` | - | Rótulos correspondentes as características dos dados de entrada. | +| `verbose` | `bool` | `True` | Indica se as mensagens de progresso do treinamento deve ser exibido. | + +**Returns** + +``BaseClassifier`` - Retorna a instancia da classe. + +--- + +### predict + +```python +@abstractmethod +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Gera previsões com base nos dados de entrada X. +Este método abstrato é implementado é responsabilidade das classes filhas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|----------------------------|:------:|---------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Dados de entrada que serão previstos pelo modelo. | + +**Returns** + +`npt.NDArray` - Array com as previsões para cada amostra de `X`. + +--- + +## Métodos públicos + +### score + +```python +def score( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list] +) -> float: + ... +``` + +A função calcula o desempenho do modelo nas previsões utilizando a métrica de acurácia. + +Esta função realiza a previsão de X e verifica quantos elementos são iguais entre o vetor y e y_predicted. +Esta função foi adicionada para compatibilidade com algumas funções do scikit-learn. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|----------------------------|:------:|--------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Conjunto de características com dimensões (n_samples, n_features). | +| `y` | `Union[npt.NDArray, list]` | - | Rótulos verdadeiros com dimensão (n_amostras,). | + +**Returns** + +`float` - A precisão do modelo. + diff --git a/docs/pt-br/api/base/base-clusterer.md b/docs/pt-br/api/base/base-clusterer.md new file mode 100644 index 0000000..952e4f0 --- /dev/null +++ b/docs/pt-br/api/base/base-clusterer.md @@ -0,0 +1,115 @@ +--- +id: base-clusterer +sidebar_label: BaseClusterer +keywords: + - base + - clusterer + - clusterer interface + - cluster labels + - fit + - predict + - fit_predict +tags: + - clusterer + - clustering +--- + +# BaseClusterer + +Classe base abstrata para algoritmos de clustering. + +> **Módulos:** `aisp.base` +> **Importação:** `from aisp.base import BaseClusterer` + +--- + +## Visão geral + +Esta classe define a interface principal para algoritmos de clusterização. +Ela define a implementação dos metodos fit e predict em todas as classes filhas, e fornece a implementação do método `fit_predict`. + +Casos de uso: + +- Classe base abstrata para estender classes de algoritmos de clusterização. + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|----------|-------------------------|:------:|---------------------------------------------------------| +| `labels` | `Optional[npt.NDArray]` | `None` | Rótulos dos clusters encontrados durante o treinamento. | + +--- + +## Métodos abstratos + +### fit + +```python +@abstractmethod +def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> BaseClusterer: + ... +``` + +Treinamento do modelo utilizando os dados de entrada `X`. +Este método abstrato é implementado é responsabilidade das classes filhas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|----------------------------|:------:|----------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Dados de entrada utilizados para o treinamento. | +| `verbose` | `bool` | `True` | Indica se as mensagens de progresso do treinamento deve ser exibido. | + +**Returns** + +``BaseClassifier`` - Retorna a instancia da classe. + +--- + +### predict + +```python +@abstractmethod +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Gera previsões com base nos dados de entrada `X`. +Este método abstrato é implementado é responsabilidade das classes filhas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|----------------------------|:------:|------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Dados de entrada para os quais as previsões serão geradas. | + +**Returns** + +`npt.NDArray` - Os labels do cluster previsto para cada amostra de entrada. + +--- + +## Métodos públicos + +### fit_predict + +```python +def fit_predict(self, X: Union[npt.NDArray, list], verbose: bool = True) -> npt.NDArray: + ... +``` + +Ajusta o modelo e com os dados de X e retorna os labels para cada amostra de X. +Este é um método que combina `fit` e `predict` em uma única chamada. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|----------------------------|:------:|----------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Conjunto de características com dimensões (n_samples, n_features). | +| `verbose` | `bool` | `True` | Indica se as mensagens de progresso do treinamento deve ser exibido. | + +**Returns** + +`npt.NDArray` - Os labels do cluster previsto para cada amostra de entrada. diff --git a/docs/pt-br/api/base/base-optimizer.md b/docs/pt-br/api/base/base-optimizer.md new file mode 100644 index 0000000..ac1ebc5 --- /dev/null +++ b/docs/pt-br/api/base/base-optimizer.md @@ -0,0 +1,157 @@ +--- +id: base-optimizer +sidebar_label: BaseOptimizer +keywords: + - base + - otimizar + - otimização + - otimizar interface + - objective function + - minimization + - maximization +tags: + - otimizar + - otimização +--- + +# BaseOptimizer + +Classe base abstrata para algoritmos de otimização. + +> **Módulos:** `aisp.base` +> **Importação:** `from aisp.base import BaseOptimizer` + +--- + +## Visão geral + +Esta classe define a interface principal para algoritmos de otimização. +Ela mantém o histórico de custos, soluções avaliadas, e a melhor solução encontrada durante a otimização. As classes +derivadas devem implementar os métodos ``optimize`` e ``affinity_function``. + +Casos de uso: + +- Classe base abstrata para estender classes de algoritmos de otimização. + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|--------------------|-------------------|:-------:|---------------------------------------------------------------| +| `cost_history` | `List[float]` | `[]` | Histórico dos melhores custos encontrados em cada iteração. | +| `solution_history` | `List` | `[]` | Histórico da melhor solução encontrada em cada iteração. | +| `best_solution` | `Any` | `None` | A melhor solução global encontrada. | +| `best_cost` | `Optional[float]` | `None` | Custo da melhor solução global encontrada. | +| `mode` | `{"min", "max"}` | `'min'` | Define se o algoritmo minimiza ou maximiza a função de custo. | + +--- + +## Métodos abstratos + +### optimize + +```python +@abstractmethod +def optimize( + self, + max_iters: int = 50, + n_iter_no_change: int = 10, + verbose: bool = True +) -> Any: + ... +``` + +Executa o processo de otimização. +Este método abstrato é implementado é responsabilidade das classes filhas, definindo a estratégia de otimização. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|--------------------|--------|:------:|----------------------------------------------------------------------| +| `max_iters` | `int` | `50` | Número máximo de iterações | +| `n_iter_no_change` | `int` | `10` | Número máximo de interações sem atualização da melhor solução. | +| `verbose` | `bool` | `True` | Indica se as mensagens de progresso do treinamento deve ser exibido. | + +**Returns** + +``BaseClassifier`` - Retorna a instância da classe. + + +--- + +### affinity_function + +```python +@abstractmethod +def affinity_function(self, solution: Any) -> float: + ... +``` + +Avalia a afinidade (qualidade) de uma solução candidata. + +Este método deve ser implementado conforme o problema de otimização específico, definindo como a solução sera medida. +O valor retornado deve representar a qualidade da solução avaliada. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------------|-------|:------:|--------------------------------------| +| `solution` | `Any` | - | Solução candidata que será avaliada. | + +**Returns** + +`float` - Valor de custo associada a solução encontrada. + +--- + +## Métodos públicos + +### get_report + +```python +def get_report(self) -> str: + ... +``` + +Gera um relatorio resumindo e formatado do processo de otimização. +O relatorio incluir a melhor solução, seu custo, e a evolução dos valores a cada iteração. + +**Returns** + +`str` - Uma string formatada contendo o resumo da otimização. + +--- + +### register + +```python +def register(self, alias: str, function: Callable[..., Any]) -> None: + ... +``` + +Registra dinamicamente uma função na instância do otimizador. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------------|----------------------|:------:|----------------------------------------------------| +| `alias` | `str` | - | Nome usado para acessar a função como um atributo. | +| `function` | `Callable[..., Any]` | - | Função que será registrada. | + +**Exceções** + +`TypeError` - Lançado quando não é uma função valida. + +`AttributeError` - Lançado quando o `alias` esta protegido e não pode ser modificado, ou se não existir na classe. + +--- + +### reset + +```python +def reset(self): + ... +``` + +Reseta o estado interno do objeto, limpando histórico e restaurando valores iniciais. diff --git a/docs/pt-br/api/base/immune/README.md b/docs/pt-br/api/base/immune/README.md index 3b307af..82f0110 100644 --- a/docs/pt-br/api/base/immune/README.md +++ b/docs/pt-br/api/base/immune/README.md @@ -2,9 +2,9 @@ id: immune sidebar_label: immune keywords: - - célula - - mutações - - populações + - célula + - mutações + - populações --- # aisp.base.immune diff --git a/docs/pt-br/api/base/immune/cell/README.md b/docs/pt-br/api/base/immune/cell/README.md index 0c4aa8a..548c41c 100644 --- a/docs/pt-br/api/base/immune/cell/README.md +++ b/docs/pt-br/api/base/immune/cell/README.md @@ -16,7 +16,7 @@ keywords: Representação de células do sistema imunológico. -> **Module:** `aisp.base.immune.cell` +> **Módulos:** `aisp.base.immune.cell` ## Visão geral diff --git a/docs/pt-br/api/base/immune/cell/b-cell.md b/docs/pt-br/api/base/immune/cell/b-cell.md index 223a28d..1f8a027 100644 --- a/docs/pt-br/api/base/immune/cell/b-cell.md +++ b/docs/pt-br/api/base/immune/cell/b-cell.md @@ -2,11 +2,11 @@ id: b-cell sidebar_label: BCell keywords: - - célula-b - - memória imune - - dataclass - - mutação clonal - - expansão clonal + - célula-b + - memória imune + - dataclass + - mutação clonal + - expansão clonal --- # BCell @@ -23,6 +23,7 @@ Esta classe herda de [Cell](./cell.md) > **Importação:** `from aisp.base.immune.cell import BCell` --- + ## Atributos | Nome | Tipo | Padrão | Descrição | diff --git a/docs/pt-br/api/base/immune/mutation.md b/docs/pt-br/api/base/immune/mutation.md index 27f2e9c..9665313 100644 --- a/docs/pt-br/api/base/immune/mutation.md +++ b/docs/pt-br/api/base/immune/mutation.md @@ -2,18 +2,19 @@ id: mutation sidebar_label: mutation keywords: - - mutações - - expansão clonal - - sistema imune - - funções python com numba - - vetor de mutações + - mutações + - expansão clonal + - sistema imune + - funções python com numba + - vetor de mutações --- # mutation As funções utilizam decoradores do Numba para compilação Just-In-Time(JIT). -Contém funções que geram conjuntos de clones hipermutados a partir de vetores contínuos ou binários, simulando o processo +Contém funções que geram conjuntos de clones hipermutados a partir de vetores contínuos ou binários, simulando o +processo de expansão clonal dos sistemas imunológicos artificiais. > **Módulo:** `aisp.base.immune` @@ -72,14 +73,13 @@ clonal em sistemas imunes artificiais com representações discretas. | Nome | Tipo | Padrão | Descrição | |-----------------|---------------------------|:------:|----------------------------------------------------------------------------------------------------------------------------------------------| | `vector` | `npt.NDArray[np.float64]` | - | Vetor binário original que representa a célula imune a ser clonada e mutada. | -| `n` | `int` | - | Quantidade de clones mutados a serão gerados. | +| `n` | `int` | - | Quantidade de clones mutados a serão gerados. | | `mutation_rate` | `float` | - | Se 0 ≤ mutation_rate < 1, usa probabilidade de mutação por características. Caso contrario, um número aleatorio de características é mutado. | **Returns** `npt.NDArray[np.bool_]` - Array com dimensões (n, len(vector)) contendo os `n` clones mutados do vetor original. - ### clone_and_mutate_ranged ```python @@ -111,7 +111,6 @@ de expansão clonal em sistemas imunes artificiais. `npt.NDArray[np.float64]` - Array com dimensões (n, len(vector)) contendo os `n` clones mutados do vetor original. - ### clone_and_mutate_continuous ```python diff --git a/docs/pt-br/api/base/immune/populations.md b/docs/pt-br/api/base/immune/populations.md index 51b18ef..9e7c140 100644 --- a/docs/pt-br/api/base/immune/populations.md +++ b/docs/pt-br/api/base/immune/populations.md @@ -2,13 +2,13 @@ id: populations sidebar_label: populations keywords: - - binário - - classificação - - limiar de afinidade - - real-valor - - célula-b de memória - - expansão clonal - - população + - binário + - classificação + - limiar de afinidade + - real-valor + - célula-b de memória + - expansão clonal + - população --- # populations From e8378cd92cbfdc6e1d391a929c29446de7598196 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Mon, 16 Mar 2026 12:37:43 -0300 Subject: [PATCH 35/40] docs: update docs --- aisp/csa/_ai_recognition_sys.py | 8 ++++---- aisp/ina/_ai_network.py | 6 +++--- aisp/nsa/_negative_selection.py | 2 +- docs/en/api/csa/airs.md | 7 ++++--- docs/en/api/ina/ai-net.md | 4 ++-- docs/en/api/nsa/rnsa.md | 2 +- 6 files changed, 15 insertions(+), 14 deletions(-) diff --git a/aisp/csa/_ai_recognition_sys.py b/aisp/csa/_ai_recognition_sys.py index b5e82ca..fd246e7 100644 --- a/aisp/csa/_ai_recognition_sys.py +++ b/aisp/csa/_ai_recognition_sys.py @@ -53,18 +53,18 @@ class AIRS(BaseClassifier): k : int, default=3 The number of K nearest neighbors that will be used to choose a label in the prediction. max_iters : int, default=100 - Maximum number of interactions in the refinement process of the ARB set exposed to aᵢ. + Maximum number of iterations in the refinement process of the ARB set exposed to aᵢ. resource_amplified : float, default=1.0 Resource consumption amplifier is multiplied with the incentive to subtract resources. Defaults to 1.0 without amplification. metric : {"euclidean", "minkowski", "manhattan"}, default="euclidean" Distance metric used to compute affinity between cells and samples. seed : int - Seed for the random generation of detector values. Defaults to None. + Seed for random generation. **kwargs p : float - This parameter stores the value of ``p`` used in the Minkowski distance. The default + This parameter stores the value of `p` used in the Minkowski distance. The default is ``2``, which represents normalized Euclidean distance.\ Different values of p lead to different variants of the Minkowski Distance. @@ -107,7 +107,7 @@ class AIRS(BaseClassifier): >>> airs = airs.fit(x_train, y_train, verbose=False) >>> x_test = [ ... [0.15, 0.45], # Expected: Class 0 - ... [0.85, 0.65], # Esperado: Classe 1 + ... [0.85, 0.65], # Esperado: Class 1 ... ] >>> y_pred = airs.predict(x_test) >>> print(y_pred) diff --git a/aisp/ina/_ai_network.py b/aisp/ina/_ai_network.py index e8c0971..60fafb0 100644 --- a/aisp/ina/_ai_network.py +++ b/aisp/ina/_ai_network.py @@ -67,13 +67,13 @@ class AiNet(BaseClusterer): metric : {"euclidean", "minkowski", "manhattan"}, default="euclidean" Distance metric used to compute similarity between memory cells seed : Optional[int] - Seed for the random generation of detector values. Defaults to None. + Seed for random generation. use_mst_clustering : bool, default=True If ``True``, performs clustering with **Minimum Spanning Tree** (MST). If ``False``, does not perform clustering and predict returns None. **kwargs p : float - This parameter stores the value of ``p`` used in the Minkowski distance. The default + This parameter stores the value of `p` used in the Minkowski distance. The default is ``2``, which represents normalized Euclidean distance.\ Different values of p lead to different variants of the Minkowski Distance. @@ -240,7 +240,7 @@ def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> AiNet: total=self.max_iterations, postfix="\n", disable=not verbose, - bar_format="{desc} ┇{bar}┇ {n}/{total} total training interactions", + bar_format="{desc} ┇{bar}┇ {n}/{total} total training iterations", ) population_p = self._init_population_antibodies() diff --git a/aisp/nsa/_negative_selection.py b/aisp/nsa/_negative_selection.py index babb4bd..1aade32 100644 --- a/aisp/nsa/_negative_selection.py +++ b/aisp/nsa/_negative_selection.py @@ -68,7 +68,7 @@ class RNSA(BaseClassifier): within the plane between 0 and 1. This means that any detector whose radius exceeds this limit is discarded, this variable is only used in the ``V-detector`` algorithm. * p : float, default=2 - This parameter stores the value of ``p`` used in the Minkowski distance. The default + This parameter stores the value of `p` used in the Minkowski distance. The default is ``2``, which represents Euclidean distance. Different values of p lead to different variants of the Minkowski Distance. diff --git a/docs/en/api/csa/airs.md b/docs/en/api/csa/airs.md index 1146719..1a814b4 100644 --- a/docs/en/api/csa/airs.md +++ b/docs/en/api/csa/airs.md @@ -7,6 +7,7 @@ keywords: - memory cells - k-nn - supervised learning + - AIRS2 tags: - classification - supervised @@ -89,11 +90,11 @@ Output: | `rate_hypermutation` | `float` | `0.75` | The rate of mutated clones derived from rate_clonal as a scalar factor. | | `affinity_threshold_scalar` | `float` | `0.75` | Normalized affinity threshold. | | `k` | `int` | `3` | The number of K nearest neighbors that will be used to choose a label in the prediction. | -| `max_iters` | `int` | `100` | Maximum number of interactions in the refinement process of the ARB set exposed to aᵢ. | +| `max_iters` | `int` | `100` | Maximum number of iterations in the refinement process of the ARB set exposed to aᵢ. | | `resource_amplified` | `float` | `1.0` | Resource consumption amplifier is multiplied with the incentive to subtract resources. | | `metric` | `str` | `"euclidean"` | Distance metric used to compute affinity between cells and samples. | -| `seed` | `int` | `None` | Seed for the random generation of detector values. Defaults to None. | -| `p` | `float` | `2` | This parameter stores the value of ``p`` used in the Minkowski distance. | +| `seed` | `int` | `None` | Seed for random generation. | +| `p` | `float` | `2` | This parameter stores the value of `p` used in the Minkowski distance. | ## Attributes diff --git a/docs/en/api/ina/ai-net.md b/docs/en/api/ina/ai-net.md index 74ccee0..1e7f089 100644 --- a/docs/en/api/ina/ai-net.md +++ b/docs/en/api/ina/ai-net.md @@ -89,9 +89,9 @@ print(y_pred) | `max_iterations` | `int` | `10` | Maximum number of training iterations. | | `k` | `int` | `3` | The number of K nearest neighbors that will be used to choose a label in the prediction. | | `metric` | [`MetricType`](../utils/types.md#metrictype) | `"euclidean"` | Distance metric used to compute similarity between memory cells | -| `seed` | `Optional[int]` | `None` | Seed for the random generation of detector values. Defaults to None. | +| `seed` | `Optional[int]` | `None` | Seed for random generation. | | `use_mst_clustering` | `bool` | `True` | If ``True``, performs clustering with **Minimum Spanning Tree** (MST). If ``False``, does not perform clustering and predict returns None. | -| `p` | `float` | `2.0` | This parameter stores the value of ``p`` used in the Minkowski distance. | +| `p` | `float` | `2.0` | This parameter stores the value of `p` used in the Minkowski distance. | ## Attributes diff --git a/docs/en/api/nsa/rnsa.md b/docs/en/api/nsa/rnsa.md index 0001eff..23268b8 100644 --- a/docs/en/api/nsa/rnsa.md +++ b/docs/en/api/nsa/rnsa.md @@ -116,7 +116,7 @@ print(y_pred) | `algorithm` | `{"default-NSA", "V-detector"}` | `'default-NSA'` | Set the algorithm version | | `non_self_label` | `str` | `'non-self'` | This variable stores the label that will be assigned when the data has only one output class, and the sample is classified as not belonging to that class. | | `cell_bounds` | `bool` | `False` | If set to ``True``, this option limits the generation of detectors to the space within the plane between 0 and 1. This means that any detector whose radius exceeds this limit is discarded, this variable is only used in the ``V-detector`` algorithm. | -| `p` | `bool` | `2.0` | This parameter stores the value of ``p`` used in the Minkowski distance. | +| `p` | `bool` | `2.0` | This parameter stores the value of `p` used in the Minkowski distance. | ## Attributes From e06a337097b48490023d8f48e56fe1042bfb1706 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Mon, 16 Mar 2026 12:43:20 -0300 Subject: [PATCH 36/40] docs: fix auto lint --- docs/assets/template-docs-class.md | 1 - docs/en/api/README.md | 4 ++-- docs/en/api/base/base-classifier.md | 15 +++++++------ docs/en/api/base/base-clusterer.md | 1 - docs/en/api/base/base-optimizer.md | 6 ++++-- docs/en/api/base/immune/cell/b-cell.md | 1 + docs/en/api/base/immune/mutation.md | 2 -- docs/en/api/csa/airs.md | 13 +++++++----- docs/en/api/csa/clonalg.md | 4 +++- docs/en/api/exceptions.md | 4 +++- docs/en/api/ina/ai-net.md | 22 ++++++++++++-------- docs/en/api/nsa/bnsa.md | 15 ++++++++----- docs/en/api/nsa/rnsa.md | 21 ++++++++++++------- docs/en/api/utils/README.md | 1 - docs/en/api/utils/display/table-formatter.md | 4 ++-- docs/en/api/utils/distance.md | 3 ++- docs/en/api/utils/types.md | 3 +++ docs/en/api/utils/validation.md | 6 ++++-- docs/pt-br/README.md | 21 +++++++++++-------- docs/pt-br/api/base/base-clusterer.md | 5 +++-- 20 files changed, 91 insertions(+), 61 deletions(-) diff --git a/docs/assets/template-docs-class.md b/docs/assets/template-docs-class.md index e575db4..fed1977 100644 --- a/docs/assets/template-docs-class.md +++ b/docs/assets/template-docs-class.md @@ -95,7 +95,6 @@ Complete usage examples are available in the Jupyter Notebooks: - [example](#link) - --- ## References diff --git a/docs/en/api/README.md b/docs/en/api/README.md index 20af6cb..7619fbc 100644 --- a/docs/en/api/README.md +++ b/docs/en/api/README.md @@ -40,7 +40,8 @@ Core structures and support utilities for implementations immune. ### Negative Selection Algorithms ([`aisp.nsa`](./nsa/README.md)) -supervised learning algorithms based on negative selection, the immune systems process of distinguishing self from not-self. +supervised learning algorithms based on negative selection, the immune systems process of distinguishing self from +not-self. | Class | Description | |-------------------------|-------------------------------------------------------------------------------------| @@ -78,7 +79,6 @@ Utility functions and helpers for development. | [`types`](./utils/types.md) | Defines type aliases used throughout the project to improve readability. | | [`validation`](./utils/validation.md) | Contains functions responsible for validating data types. | - ## Exceptions ([`aisp.exceptions`](./exceptions.md)) Custom warnings and errors. diff --git a/docs/en/api/base/base-classifier.md b/docs/en/api/base/base-classifier.md index cd17541..59c8fac 100644 --- a/docs/en/api/base/base-classifier.md +++ b/docs/en/api/base/base-classifier.md @@ -35,9 +35,9 @@ Use cases: ## Attributes -| Name | Type | Default | Description | -|---------------|-------------------------|:-------:|------------------------------------------| -| `classes` | `Optional[npt.NDArray]` | `None` | Class labels identified during training. | +| Name | Type | Default | Description | +|-----------|-------------------------|:-------:|------------------------------------------| +| `classes` | `Optional[npt.NDArray]` | `None` | Class labels identified during training. | --- @@ -84,7 +84,6 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: Generate predictions based on the input data X. This abstract method is implemented by the class that inherits it. - **Parameters** | Name | Type | Default | Description | @@ -117,10 +116,10 @@ This function was added for compatibility with some scikit-learn functions. **Parameters** -| Name | Type | Default | Description | -|-----------|--------|:-------:|-------------------------------| -| `X` | `Union[npt.NDArray, list]` | - | Feature set with shape (n_samples, n_features). | -| `y` | `Union[npt.NDArray, list]` | - | True values with shape (n_samples,). | +| Name | Type | Default | Description | +|------|----------------------------|:-------:|-------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Feature set with shape (n_samples, n_features). | +| `y` | `Union[npt.NDArray, list]` | - | True values with shape (n_samples,). | **Returns** diff --git a/docs/en/api/base/base-clusterer.md b/docs/en/api/base/base-clusterer.md index 722c7ae..b2278de 100644 --- a/docs/en/api/base/base-clusterer.md +++ b/docs/en/api/base/base-clusterer.md @@ -79,7 +79,6 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: Generate predictions based on the input data X. This abstract method is implemented by the class that inherits it. - **Parameters** | Name | Type | Default | Description | diff --git a/docs/en/api/base/base-optimizer.md b/docs/en/api/base/base-optimizer.md index f436641..9b53e21 100644 --- a/docs/en/api/base/base-optimizer.md +++ b/docs/en/api/base/base-optimizer.md @@ -63,7 +63,8 @@ def optimize( ``` Execute the optimization process. -This abstract method must be implemented by the subclass, defining how the optimization strategy explores the search space. +This abstract method must be implemented by the subclass, defining how the optimization strategy explores the search +space. **Parameters** @@ -90,7 +91,8 @@ def affinity_function(self, solution: Any) -> float: Evaluate the affinity of a candidate solution. -This method must be implemented according to the specific optimization problem, defining how the solution will be evaluated. +This method must be implemented according to the specific optimization problem, defining how the solution will be +evaluated. The returned value should represent the quality of the evaluated solution. **Parameters** diff --git a/docs/en/api/base/immune/cell/b-cell.md b/docs/en/api/base/immune/cell/b-cell.md index af312b1..6a7d297 100644 --- a/docs/en/api/base/immune/cell/b-cell.md +++ b/docs/en/api/base/immune/cell/b-cell.md @@ -23,6 +23,7 @@ This class extends [Cell](./cell.md) > **Import:** `from aisp.base.immune.cell import BCell` --- + ## Attributes | Name | Type | Default | Description | diff --git a/docs/en/api/base/immune/mutation.md b/docs/en/api/base/immune/mutation.md index 2cae87e..8ebe13c 100644 --- a/docs/en/api/base/immune/mutation.md +++ b/docs/en/api/base/immune/mutation.md @@ -79,7 +79,6 @@ bits, simulating clonal expansion in artificial immune systems with discrete rep `npt.NDArray[np.bool_]` - An Array(n, len(vector)) containing the `n` mutated clones of the original vector. - ### clone_and_mutate_ranged ```python @@ -111,7 +110,6 @@ them, simulating the process of clonal expansion in artificial immune systems. `npt.NDArray[np.float64]` - An Array(n, len(vector)) containing the `n` mutated clones of the original vector. - ### clone_and_mutate_continuous ```python diff --git a/docs/en/api/csa/airs.md b/docs/en/api/csa/airs.md index 1a814b4..afbbd91 100644 --- a/docs/en/api/csa/airs.md +++ b/docs/en/api/csa/airs.md @@ -72,12 +72,13 @@ x_test = [ y_pred = airs.predict(x_test) print(y_pred) ``` + Output: + ```bash [0 1] ``` - --- ## Constructor Parameters @@ -102,7 +103,6 @@ Output: |----------------|-------------------------------------------|:-------:|---------------------------------------------------------| | `cells_memory` | `Optional[Dict[str \| int, list[BCell]]]` | - | Dictionary of trained memory cells, organized by class. | - --- ## Public Methods @@ -118,6 +118,7 @@ def fit( ) -> AIRS: ... ``` + Fit the model to the training data using the AIRS. The function ``fit(...)``, performs the training according to ``X`` and ``y``, using the @@ -143,6 +144,7 @@ method AIRS. def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: ... ``` + Predict class labels based on the memory cells created during training. This method uses the trained memory cells to perform classification of the input data @@ -157,8 +159,10 @@ using the k-nearest neighbors approach. **Raises** * `TypeError` - If X is not a ndarray or list. -* [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) - If the number of features in X does not match the expected number. -* [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) - If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions +* [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) - If the number of features in X does not + match the expected number. +* [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) - If the mode has not yet been adjusted and does not + have defined memory cells, it is not able to predictions **Returns** @@ -175,7 +179,6 @@ Complete usage examples are available in the Jupyter Notebooks: - [**Mushrooms Dataset Example**](../../../../examples/en/classification/AIRS/mushrooms_dataBase_example_en.ipynb) - [**Random Dataset Example**](../../../../examples/en/classification/AIRS/example_with_randomly_generated_dataset-en.ipynb) - --- ## References diff --git a/docs/en/api/csa/clonalg.md b/docs/en/api/csa/clonalg.md index bc2788c..c92d0a2 100644 --- a/docs/en/api/csa/clonalg.md +++ b/docs/en/api/csa/clonalg.md @@ -69,7 +69,9 @@ clonalg.register('affinity_function', rastrigin_fitness) population = clonalg.optimize(100, 50, False) print('Best cost:', abs(clonalg.best_cost)) ``` + **Output:** + ```bash Best cost: 0.02623036956750724 ``` @@ -126,7 +128,7 @@ Execute the optimization process and return the population. * `NotImplementedError` - If no affinity function has been provided to model. **Returns** - + **population** : `List[Antibody]` - Antibody population after clonal expansion. --- diff --git a/docs/en/api/exceptions.md b/docs/en/api/exceptions.md index 48fa150..688c12e 100644 --- a/docs/en/api/exceptions.md +++ b/docs/en/api/exceptions.md @@ -53,6 +53,7 @@ This exception is triggered during prediction if the input features' dimension i | `variable_name` | `Optional[str]` | `None` | The name of the variable that caused this mismatch. | --- + ### UnsupportedTypeError ```python @@ -70,6 +71,7 @@ This exception is thrown when the vector data type does not match any of the sup | `message` | `Optional[str]` | `None` | Custom message to display. | --- + ### ModelNotFittedError ```python @@ -78,7 +80,7 @@ class ModelNotFittedError(Exception): ``` Exception raised when a method is called before the model has been fit. -This exception is thrown when the model instance is being used without first training +This exception is thrown when the model instance is being used without first training it via the `fit` method. **Parameters** diff --git a/docs/en/api/ina/ai-net.md b/docs/en/api/ina/ai-net.md index 1e7f089..077d0bf 100644 --- a/docs/en/api/ina/ai-net.md +++ b/docs/en/api/ina/ai-net.md @@ -68,7 +68,9 @@ x_test = [ y_pred = ai_net.predict(x_test) print(y_pred) ``` + **Output** + ```bash [0 1] ``` @@ -89,9 +91,9 @@ print(y_pred) | `max_iterations` | `int` | `10` | Maximum number of training iterations. | | `k` | `int` | `3` | The number of K nearest neighbors that will be used to choose a label in the prediction. | | `metric` | [`MetricType`](../utils/types.md#metrictype) | `"euclidean"` | Distance metric used to compute similarity between memory cells | -| `seed` | `Optional[int]` | `None` | Seed for random generation. | +| `seed` | `Optional[int]` | `None` | Seed for random generation. | | `use_mst_clustering` | `bool` | `True` | If ``True``, performs clustering with **Minimum Spanning Tree** (MST). If ``False``, does not perform clustering and predict returns None. | -| `p` | `float` | `2.0` | This parameter stores the value of `p` used in the Minkowski distance. | +| `p` | `float` | `2.0` | This parameter stores the value of `p` used in the Minkowski distance. | ## Attributes @@ -151,8 +153,10 @@ Predict cluster labels for input data. * `TypeError` - If X is not a ndarray or list. * `ValueError` - If the array contains values other than 0 and 1. -* [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) - If the number of features in X does not match the expected number. -* [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) - If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions +* [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) - If the number of features in X does not + match the expected number. +* [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) - If the mode has not yet been adjusted and does not + have defined memory cells, it is not able to predictions **Returns** @@ -166,6 +170,7 @@ Predict cluster labels for input data. def update_clusters(self, mst_inconsistency_factor: Optional[float] = None): ... ``` + Partition the clusters based on the MST inconsistency factor. Uses the precomputed Minimum Spanning Tree (MST) of the antibody population @@ -183,14 +188,13 @@ distinct cluster. **Raises** * `ValueError` - * If the Minimum Spanning Tree (MST) has not yet been created - * If Population of antibodies is empty - * If MST statistics (mean or std) are not available. + * If the Minimum Spanning Tree (MST) has not yet been created + * If Population of antibodies is empty + * If MST statistics (mean or std) are not available. **Updates** -* **memory_network** : `dict[int, npt.NDArray]` - - Dictionary mapping cluster labels to antibody arrays. +* **memory_network** : `dict[int, npt.NDArray]` - Dictionary mapping cluster labels to antibody arrays. * **labels** : `list` - List of cluster labels. --- diff --git a/docs/en/api/nsa/bnsa.md b/docs/en/api/nsa/bnsa.md index 2e4f5c7..dd6ee37 100644 --- a/docs/en/api/nsa/bnsa.md +++ b/docs/en/api/nsa/bnsa.md @@ -76,7 +76,9 @@ x_test = [ y_prev = bnsa.predict(X=x_test) print(y_prev) ``` + **Output** + ```bash ['non-self' 'self'] ``` @@ -125,12 +127,12 @@ Training according to X and y, using the method negative selection method. | `y` | `Union[npt.NDArray, list]` | - | Array of target classes of ``X`` with (``n_samples``). | | `verbose` | `bool` | `True` | Feedback from detector generation to the user. | - **Raises** * `TypeError` - If X or y are not ndarrays or have incompatible shapes. * `ValueError` - If the array contains values other than 0 and 1. -* [`MaxDiscardsReachedError`](../exceptions.md#maxdiscardsreachederror) - The maximum number of detector discards was reached during maturation. Check the defined radius value and consider reducing it. +* [`MaxDiscardsReachedError`](../exceptions.md#maxdiscardsreachederror) - The maximum number of detector discards was + reached during maturation. Check the defined radius value and consider reducing it. **Returns** @@ -157,8 +159,10 @@ Prediction of classes based on detectors created after training. * `TypeError` - If X is not a ndarray or list. * `ValueError` - If the array contains values other than 0 and 1. -* [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) - If the number of features in X does not match the expected number. -* [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) - If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions +* [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) - If the number of features in X does not + match the expected number. +* [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) - If the mode has not yet been adjusted and does not + have defined detectors or classes, it is not able to predictions **Returns** @@ -171,7 +175,8 @@ Prediction of classes based on detectors created after training. Complete usage examples are available in the Jupyter Notebooks: - [**Mushrooms Dataset Example**](../../../../examples/en/classification/BNSA/mushrooms_dataBase_example_en.ipynb) -- [**Random Dataset Example**](../../../../examples/en/classification/BNSA/example_with_randomly_generated_dataset-en.ipynb) +- [**Random Dataset Example + **](../../../../examples/en/classification/BNSA/example_with_randomly_generated_dataset-en.ipynb) --- diff --git a/docs/en/api/nsa/rnsa.md b/docs/en/api/nsa/rnsa.md index 23268b8..7ecc3f5 100644 --- a/docs/en/api/nsa/rnsa.md +++ b/docs/en/api/nsa/rnsa.md @@ -83,10 +83,13 @@ x_test = [ y_pred = rnsa.predict(x_test) print(y_pred) ``` + **Output** + ```bash ['a' 'b'] ``` + **Example 2:** Anomaly Detection (self/non-self) ```python @@ -95,7 +98,9 @@ rnsa = rnsa.fit(X=class_a, y=np.array(['self'] * 50), verbose=False) y_pred = rnsa.predict(class_b[:5]) print(y_pred) ``` + **Output** + ```bash ['non-self' 'non-self' 'non-self' 'non-self' 'non-self'] ``` @@ -116,7 +121,7 @@ print(y_pred) | `algorithm` | `{"default-NSA", "V-detector"}` | `'default-NSA'` | Set the algorithm version | | `non_self_label` | `str` | `'non-self'` | This variable stores the label that will be assigned when the data has only one output class, and the sample is classified as not belonging to that class. | | `cell_bounds` | `bool` | `False` | If set to ``True``, this option limits the generation of detectors to the space within the plane between 0 and 1. This means that any detector whose radius exceeds this limit is discarded, this variable is only used in the ``V-detector`` algorithm. | -| `p` | `bool` | `2.0` | This parameter stores the value of `p` used in the Minkowski distance. | +| `p` | `bool` | `2.0` | This parameter stores the value of `p` used in the Minkowski distance. | ## Attributes @@ -150,12 +155,12 @@ Perform training according to X and y, using the negative selection method (Nega | `y` | `Union[npt.NDArray, list]` | - | Array of target classes of ``X`` with (``n_samples``). | | `verbose` | `bool` | `True` | Feedback from detector generation to the user. | - **Raises** * `TypeError` - If X or y are not ndarrays or have incompatible shapes. * `ValueError` - If the array X fall outside the interval (0, 1). -* [`MaxDiscardsReachedError`](../exceptions.md#maxdiscardsreachederror) - The maximum number of detector discards was reached during maturation. Check the defined radius value and consider reducing it. +* [`MaxDiscardsReachedError`](../exceptions.md#maxdiscardsreachederror) - The maximum number of detector discards was + reached during maturation. Check the defined radius value and consider reducing it. **Returns** @@ -182,8 +187,10 @@ Prediction of classes based on detectors created after training. * `TypeError` - If X is not a ndarray or list. * `ValueError` - If the array X fall outside the interval (0, 1). -* [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) - If the number of features in X does not match the expected number. -* [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) - If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions +* [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) - If the number of features in X does not + match the expected number. +* [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) - If the mode has not yet been adjusted and does not + have defined detectors or classes, it is not able to predictions **Returns** @@ -195,10 +202,10 @@ Prediction of classes based on detectors created after training. Complete usage examples are available in the Jupyter Notebooks: - - [**Iris Dataset Example**](../../../../examples/en/classification/RNSA/iris_dataBase_example_en.ipynb) - [**Geyser Dataset Example**](../../../../examples/en/classification/RNSA/geyser_dataBase_example_en.ipynb) -- [**Random Dataset Example**](../../../../examples/en/classification/RNSA/example_with_randomly_generated_dataset-en.ipynb) +- [**Random Dataset Example + **](../../../../examples/en/classification/RNSA/example_with_randomly_generated_dataset-en.ipynb) --- diff --git a/docs/en/api/utils/README.md b/docs/en/api/utils/README.md index f5e36c8..a0467fa 100644 --- a/docs/en/api/utils/README.md +++ b/docs/en/api/utils/README.md @@ -14,7 +14,6 @@ Utility functions and helpers for development. > **Module:** `aisp.utils` > **Import:** `from aisp import utils` - ## Submodules | Module | Description | diff --git a/docs/en/api/utils/display/table-formatter.md b/docs/en/api/utils/display/table-formatter.md index a3655db..91de3fc 100644 --- a/docs/en/api/utils/display/table-formatter.md +++ b/docs/en/api/utils/display/table-formatter.md @@ -14,8 +14,8 @@ Format tabular data into strings for display in the console. ## Constructor Parameters -| Name | Type | Default | Description | -|-----------|---------------------|:-------:|------------------------------------------------------------------------------------------------| +| Name | Type | Default | Description | +|-----------|---------------------|:-------:|--------------------------------------------------------------------------------------------------| | `headers` | `Mapping[str, int]` | - | Mapping of column names to their respective widths, in the format `{column_name: column_width}`. | --- diff --git a/docs/en/api/utils/distance.md b/docs/en/api/utils/distance.md index ae36d53..f264c29 100644 --- a/docs/en/api/utils/distance.md +++ b/docs/en/api/utils/distance.md @@ -200,7 +200,8 @@ Calculate the minimum distance between an input vector and the vectors of a clas **Returns** -**min_distance**: `float` - The minimum distance calculated between the input vector and the class vectors. Returns -1.0 if the input dimensions are incompatible. +**min_distance**: `float` - The minimum distance calculated between the input vector and the class vectors. Returns -1.0 +if the input dimensions are incompatible. --- diff --git a/docs/en/api/utils/types.md b/docs/en/api/utils/types.md index 5407f16..3df5066 100644 --- a/docs/en/api/utils/types.md +++ b/docs/en/api/utils/types.md @@ -26,6 +26,7 @@ FeatureType: TypeAlias = Literal[ ``` Type of input features: + - `"binary-features"`: values like 0 or 1. - `"continuous-features"`: numeric continuous values. - `"ranged-features"`: values defined by intervals. @@ -39,6 +40,7 @@ FeatureTypeAll: TypeAlias = Union[FeatureType, Literal["permutation-features"]] ``` Same as ``FeatureType``, plus: + - `"permutation-features"`: values represented as permutation. --- @@ -50,6 +52,7 @@ MetricType: TypeAlias = Literal["manhattan", "minkowski", "euclidean"] ``` Distance metric used in calculations: + - `"manhattan"`: the Manhattan distance between two points - `"minkowski"`: the Minkowski distance between two points. - `"euclidean"`: the Euclidean distance between two points. diff --git a/docs/en/api/utils/validation.md b/docs/en/api/utils/validation.md index 78de0ca..05c511b 100644 --- a/docs/en/api/utils/validation.md +++ b/docs/en/api/utils/validation.md @@ -24,6 +24,7 @@ def detect_vector_data_type(vector: npt.NDArray) -> FeatureType: Detect the type of data in a vector. The function detects if the vector contains data of type: + - Binary features: boolean values or integers restricted to 0 and 1. - Continuous features: floating-point values in the normalized range [0.0, 1.0]. - Ranged features: floating-point values outside the normalized range. @@ -36,11 +37,12 @@ The function detects if the vector contains data of type: **Raises** -* `UnsupportedTypeError` - If the data type of the vector is not supported by the function. +* `UnsupportedTypeError` - If the data type of the vector is not supported by the function. **Returns** -[`FeatureType`](./types.md#featuretype) - The data type of the vector: "binary-features", "continuous-features", or "ranged-features". +[`FeatureType`](./types.md#featuretype) - The data type of the vector: "binary-features", "continuous-features", or " +ranged-features". --- diff --git a/docs/pt-br/README.md b/docs/pt-br/README.md index 8ba12cf..19dfaa5 100644 --- a/docs/pt-br/README.md +++ b/docs/pt-br/README.md @@ -28,11 +28,14 @@ metáforas ## Introdução -O **AISP** é um pacote python que implementa as técnicas dos sistemas imunológicos artificiais, distribuído sob a licença GNU Lesser General Public License v3.0 (LGPLv3). +O **AISP** é um pacote python que implementa as técnicas dos sistemas imunológicos artificiais, distribuído sob a +licença GNU Lesser General Public License v3.0 (LGPLv3). -O pacote foi iniciado no ano de 2022, como parte de um projeto de pesquisa desenvolvido no Instituto Federal do Norte de Minas Gerais - Campus Salinas (IFNMG - Salinas). +O pacote foi iniciado no ano de 2022, como parte de um projeto de pesquisa desenvolvido no Instituto Federal do Norte de +Minas Gerais - Campus Salinas (IFNMG - Salinas). -Os sistemas imunológicos artificiais (SIA) inspiram-se no sistema imunológico dos vertebrados, criando metáforas que aplicam a capacidade de reconhecer e catalogar os patógenos, entre outras características desse sistema. +Os sistemas imunológicos artificiais (SIA) inspiram-se no sistema imunológico dos vertebrados, criando metáforas que +aplicam a capacidade de reconhecer e catalogar os patógenos, entre outras características desse sistema. ### Algoritmos implementados @@ -58,12 +61,12 @@ O módulo requer a instalação do [python 3.10](https://www.python.org/download

-| Pacotes | Versão | -|:-------------:|:-------------:| -| numpy | ≥ 1.22.4 | -| scipy | ≥ 1.8.1 | -| tqdm | ≥ 4.64.1 | -| numba | ≥ 0.59.0 | +| Pacotes | Versão | +|:-------:|:--------:| +| numpy | ≥ 1.22.4 | +| scipy | ≥ 1.8.1 | +| tqdm | ≥ 4.64.1 | +| numba | ≥ 0.59.0 |
diff --git a/docs/pt-br/api/base/base-clusterer.md b/docs/pt-br/api/base/base-clusterer.md index 952e4f0..ce84a13 100644 --- a/docs/pt-br/api/base/base-clusterer.md +++ b/docs/pt-br/api/base/base-clusterer.md @@ -26,7 +26,8 @@ Classe base abstrata para algoritmos de clustering. ## Visão geral Esta classe define a interface principal para algoritmos de clusterização. -Ela define a implementação dos metodos fit e predict em todas as classes filhas, e fornece a implementação do método `fit_predict`. +Ela define a implementação dos metodos fit e predict em todas as classes filhas, e fornece a implementação do +método `fit_predict`. Casos de uso: @@ -64,7 +65,7 @@ Este método abstrato é implementado é responsabilidade das classes filhas. **Returns** -``BaseClassifier`` - Retorna a instancia da classe. +``BaseClassifier`` - Retorna a instancia da classe. --- From 7750b8b52171ba4370171818faf0ed47826d03a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Mon, 16 Mar 2026 13:36:04 -0300 Subject: [PATCH 37/40] refactor: use only "`" for inline code blocks. --- aisp/base/core/_classifier.py | 4 ++-- aisp/csa/_ai_recognition_sys.py | 10 +++++----- aisp/nsa/_binary_negative_selection.py | 10 +++++----- aisp/nsa/_negative_selection.py | 8 ++++---- docs/en/api/csa/airs.md | 12 ++++++------ docs/en/api/nsa/bnsa.md | 6 +++--- docs/en/api/nsa/rnsa.md | 12 ++++++------ docs/en/api/utils/multiclass.md | 2 +- 8 files changed, 32 insertions(+), 32 deletions(-) diff --git a/aisp/base/core/_classifier.py b/aisp/base/core/_classifier.py index fd01d1f..98038b3 100644 --- a/aisp/base/core/_classifier.py +++ b/aisp/base/core/_classifier.py @@ -116,11 +116,11 @@ def _slice_index_list_by_class(self, y: npt.NDArray) -> dict: Parameters ---------- y : npt.NDArray - Receives a y ``n_samples`` array with the output classes of the ``X`` sample array. + Receives a y `n_samples` array with the output classes of the `X` sample array. Returns ------- indices_by_class : dict - A dictionary with the list of array positions(``y``), with the classes as key. + A dictionary with the list of array positions(`y`), with the classes as key. """ return slice_index_list_by_class(self.classes, y) diff --git a/aisp/csa/_ai_recognition_sys.py b/aisp/csa/_ai_recognition_sys.py index fd246e7..e4a66d6 100644 --- a/aisp/csa/_ai_recognition_sys.py +++ b/aisp/csa/_ai_recognition_sys.py @@ -175,7 +175,7 @@ def fit( """ Fit the model to the training data using the AIRS. - The function ``fit(...)``, performs the training according to ``X`` and ``y``, using the + The function ``fit(...)``, performs the training according to `X` and `y`, using the method AIRS. Parameters @@ -184,7 +184,7 @@ def fit( Training array, containing the samples and their characteristics, Shape: (n_samples, n_features). y : Union[npt.NDArray, list] - Array of target classes of ``X`` with (``n_samples``). + Array of target classes of `X` with (`n_samples`). verbose : bool Feedback on which sample aᵢ the memory cells are being generated. @@ -258,7 +258,7 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: Parameters ---------- X : Union[npt.NDArray, list] - Array with input samples with Shape: (``n_samples, n_features``) + Array with input samples with Shape: (`n_samples, n_features`) Raises ------ @@ -273,8 +273,8 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: Returns ------- C : npt.NDArray - An ndarray of the form ``C`` (``n_samples``), containing the predicted classes for - ``X``. + An ndarray of the form `C` (`n_samples`), containing the predicted classes for + `X`. """ if self._all_class_cell_vectors is None: raise ModelNotFittedError("AIRS") diff --git a/aisp/nsa/_binary_negative_selection.py b/aisp/nsa/_binary_negative_selection.py index 65b28bd..5c83275 100644 --- a/aisp/nsa/_binary_negative_selection.py +++ b/aisp/nsa/_binary_negative_selection.py @@ -142,9 +142,9 @@ def fit( ---------- X : Union[npt.NDArray, list] Training array, containing the samples and their characteristics. - Shape: (``n_samples, n_features``) + Shape: (`n_samples, n_features`) y : Union[npt.NDArray, list] - Array of target classes of ``X`` with ``n_samples`` (lines). + Array of target classes of `X` with `n_samples` (lines). verbose : bool, default=True Feedback from detector generation to the user. @@ -223,7 +223,7 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: Parameters ---------- X : Union[npt.NDArray, list] - Array with input samples with Shape: (``n_samples, n_features``) + Array with input samples with Shape: (`n_samples, n_features`) Raises ------ @@ -240,8 +240,8 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: Returns ------- c : npt.NDArray - A ndarray of the form ``C`` (``n_samples``), containing the predicted classes for - ``X``. + A ndarray of the form `C` (`n_samples`), containing the predicted classes for + `X`. """ if ( self._detectors is None diff --git a/aisp/nsa/_negative_selection.py b/aisp/nsa/_negative_selection.py index 1aade32..89d5845 100644 --- a/aisp/nsa/_negative_selection.py +++ b/aisp/nsa/_negative_selection.py @@ -40,7 +40,7 @@ class RNSA(BaseClassifier): r : float, default=0.05 Radius of the detector. r_s : float, default=0.0001 - rₛ Radius of the ``X`` own samples. + rₛ Radius of the `X` own samples. k : int, default=1 Number of neighbors near the randomly generated detectors to perform the distance average calculation. @@ -187,7 +187,7 @@ def fit( Training array, containing the samples and their characteristics. Shape: ``(n_samples, n_features)`` y : Union[npt.NDArray, list] - Array of target classes of ``X`` with ``n_samples`` (lines). + Array of target classes of `X` with `n_samples` (lines). verbose: bool, default=True Feedback from detector generation to the user. @@ -285,8 +285,8 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: Returns ------- C : npt.NDArray - A ndarray of the form ``C`` (n_samples), containing the predicted classes - for ``X``. + A ndarray of the form `C` (n_samples), containing the predicted classes + for `X`. """ if self._detectors is None or self.classes is None: raise ModelNotFittedError("RNSA") diff --git a/docs/en/api/csa/airs.md b/docs/en/api/csa/airs.md index afbbd91..0fa9358 100644 --- a/docs/en/api/csa/airs.md +++ b/docs/en/api/csa/airs.md @@ -121,7 +121,7 @@ def fit( Fit the model to the training data using the AIRS. -The function ``fit(...)``, performs the training according to ``X`` and ``y``, using the +The function ``fit(...)``, performs the training according to `X` and `y`, using the method AIRS. **Parameters** @@ -129,7 +129,7 @@ method AIRS. | Name | Type | Default | Description | |-----------|----------------------------|:-------:|---------------------------------------------------------------------------------------------------| | `X` | `Union[npt.NDArray, list]` | - | Training array, containing the samples and their characteristics, Shape: (n_samples, n_features). | -| `y` | `Union[npt.NDArray, list]` | - | Array of target classes of ``X`` with (``n_samples``). | +| `y` | `Union[npt.NDArray, list]` | - | Array of target classes of `X` with (`n_samples`). | | `verbose` | `bool` | `True` | Feedback on which sample aᵢ the memory cells are being generated. | **Returns** @@ -152,9 +152,9 @@ using the k-nearest neighbors approach. **Parameters** -| Name | Type | Default | Description | -|------|----------------------------|:-------:|-------------------------------------------------------------------| -| `X` | `Union[npt.NDArray, list]` | - | Array with input samples with Shape: (``n_samples, n_features``) | +| Name | Type | Default | Description | +|------|----------------------------|:-------:|-----------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Array with input samples with Shape: (`n_samples, n_features`) | **Raises** @@ -166,7 +166,7 @@ using the k-nearest neighbors approach. **Returns** -**C** : `npt.NDArray` - An ndarray of the form ``C`` (``n_samples``), containing the predicted classes for ``X``. +**C** : `npt.NDArray` - An ndarray of the form `C` (`n_samples`), containing the predicted classes for `X`. --- diff --git a/docs/en/api/nsa/bnsa.md b/docs/en/api/nsa/bnsa.md index dd6ee37..c6465b1 100644 --- a/docs/en/api/nsa/bnsa.md +++ b/docs/en/api/nsa/bnsa.md @@ -124,7 +124,7 @@ Training according to X and y, using the method negative selection method. | Name | Type | Default | Description | |-----------|----------------------------|:-------:|---------------------------------------------------------------------------------------------------| | `X` | `Union[npt.NDArray, list]` | - | Training array, containing the samples and their characteristics, Shape: (n_samples, n_features). | -| `y` | `Union[npt.NDArray, list]` | - | Array of target classes of ``X`` with (``n_samples``). | +| `y` | `Union[npt.NDArray, list]` | - | Array of target classes of `X` with (`n_samples`). | | `verbose` | `bool` | `True` | Feedback from detector generation to the user. | **Raises** @@ -153,7 +153,7 @@ Prediction of classes based on detectors created after training. | Name | Type | Default | Description | |------|----------------------------|:-------:|-------------------------------------------------------------------| -| `X` | `Union[npt.NDArray, list]` | - | Array with input samples with Shape: (``n_samples, n_features``) | +| `X` | `Union[npt.NDArray, list]` | - | Array with input samples with Shape: (`n_samples, n_features`) | **Raises** @@ -166,7 +166,7 @@ Prediction of classes based on detectors created after training. **Returns** -**C** : `npt.NDArray` - An ndarray of the form ``C`` (``n_samples``), containing the predicted classes for ``X``. +**C** : `npt.NDArray` - An ndarray of the form `C` (`n_samples`), containing the predicted classes for `X`. --- diff --git a/docs/en/api/nsa/rnsa.md b/docs/en/api/nsa/rnsa.md index 7ecc3f5..a30c8c1 100644 --- a/docs/en/api/nsa/rnsa.md +++ b/docs/en/api/nsa/rnsa.md @@ -113,7 +113,7 @@ print(y_pred) |------------------|-------------------------------------------|:---------------:|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `N` | `int` | `100` | Number of detectors. | | `r` | `float` | `0.05` | Radius of the detector. | -| `r_s` | `float` | `0.0001` | rₛ Radius of the ``X`` own samples. | +| `r_s` | `float` | `0.0001` | rₛ Radius of the `X` own samples. | | `k` | `int` | `1` | Number of neighbors near the randomly generated detectors to perform the distance average calculation. | | `metric` | `{"euclidean", "minkowski", "manhattan"}` | `'euclidean'` | Distance metric used to compute the distance between the detector and the sample. | | `max_discards` | `int` | `1000` | This parameter indicates the maximum number of consecutive detector discards, aimed at preventing a possible infinite loop in case a radius is defined that cannot generate non-self detectors. | @@ -152,7 +152,7 @@ Perform training according to X and y, using the negative selection method (Nega | Name | Type | Default | Description | |-----------|----------------------------|:-------:|---------------------------------------------------------------------------------------------------| | `X` | `Union[npt.NDArray, list]` | - | Training array, containing the samples and their characteristics, Shape: (n_samples, n_features). | -| `y` | `Union[npt.NDArray, list]` | - | Array of target classes of ``X`` with (``n_samples``). | +| `y` | `Union[npt.NDArray, list]` | - | Array of target classes of `X` with (`n_samples`). | | `verbose` | `bool` | `True` | Feedback from detector generation to the user. | **Raises** @@ -179,9 +179,9 @@ Prediction of classes based on detectors created after training. **Parameters** -| Name | Type | Default | Description | -|------|----------------------------|:-------:|-------------------------------------------------------------------| -| `X` | `Union[npt.NDArray, list]` | - | Array with input samples with Shape: (``n_samples, n_features``) | +| Name | Type | Default | Description | +|------|----------------------------|:-------:|-----------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Array with input samples with Shape: (`n_samples, n_features`) | **Raises** @@ -194,7 +194,7 @@ Prediction of classes based on detectors created after training. **Returns** -**C** : `npt.NDArray` - An ndarray of the form ``C`` (``n_samples``), containing the predicted classes for ``X``. +**C** : `npt.NDArray` - An ndarray of the form `C` (`n_samples`), containing the predicted classes for `X`. --- diff --git a/docs/en/api/utils/multiclass.md b/docs/en/api/utils/multiclass.md index f24c155..6005abe 100644 --- a/docs/en/api/utils/multiclass.md +++ b/docs/en/api/utils/multiclass.md @@ -35,7 +35,7 @@ Separate indices of samples by class for targeted iteration. **Returns** -**position_samples**: `dict` - A dictionary with the list of array positions(``y``), with the classes as key. +**position_samples**: `dict` - A dictionary with the list of array positions(`y`), with the classes as key. **Example** From 9cf2fd4133722fc75104303018669275faef577a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Sat, 21 Mar 2026 12:38:03 -0300 Subject: [PATCH 38/40] feat: update templates to use tables for return and raises sections --- docs/assets/template-docs-class.md | 14 ++++++++++---- docs/assets/template-docs-functions.md | 13 ++++++++----- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/docs/assets/template-docs-class.md b/docs/assets/template-docs-class.md index fed1977..d75cf6c 100644 --- a/docs/assets/template-docs-class.md +++ b/docs/assets/template-docs-class.md @@ -79,13 +79,19 @@ Description. |-----------|--------|:-------:|---------------------------| | `param_1` | `Type` | - | Description of the param. | -**Raises** - -{{ Raise }} - {{ Description }}. **Returns** -{{ Type }} - {{ Description }}. +| Type | Description | +|--------------|----------------------------| +| `ReturnType` | Description of the return. | + + +**Raises** + +| Exception | Description | +|-----------|---------------------------| +| `Error` | Description of the raise. | --- diff --git a/docs/assets/template-docs-functions.md b/docs/assets/template-docs-functions.md index 9210799..34e7aee 100644 --- a/docs/assets/template-docs-functions.md +++ b/docs/assets/template-docs-functions.md @@ -33,14 +33,17 @@ def function_name( |-----------|--------|:-------:|---------------------------| | `param_1` | `Type` | - | Description of the param. | -**Raises** - -{{ Raise }} - {{ Description }}. - **Returns** -{{ Type }} - {{ Description }}. +| Type | Description | +|--------------|----------------------------| +| `ReturnType` | Description of the return. | + +**Raises** +| Exception | Description | +|-----------|------------------------| +| `Error` | When and why it raised | --- From 6c4267407dacc9257a9e5f241c8e71c415891fcf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Sat, 21 Mar 2026 14:36:55 -0300 Subject: [PATCH 39/40] docs: update Raises section in docstrings --- aisp/base/core/_classifier.py | 2 +- aisp/base/core/_clusterer.py | 4 +-- aisp/base/core/_optimizer.py | 6 ++-- aisp/base/immune/populations.py | 10 +++---- aisp/csa/_ai_recognition_sys.py | 25 ++++++++++++----- aisp/csa/_clonalg.py | 10 +++---- aisp/ina/_ai_network.py | 39 +++++++++++++------------- aisp/nsa/_binary_negative_selection.py | 28 +++++++++--------- aisp/nsa/_negative_selection.py | 30 ++++++++++---------- aisp/utils/distance.py | 10 +++---- 10 files changed, 88 insertions(+), 76 deletions(-) diff --git a/aisp/base/core/_classifier.py b/aisp/base/core/_classifier.py index 98038b3..3ff2bca 100644 --- a/aisp/base/core/_classifier.py +++ b/aisp/base/core/_classifier.py @@ -67,7 +67,7 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: Parameters ---------- X : Union[npt.NDArray, list] - Input data for which predictions will be generated. + Data for which predictions will be generated. Returns ------- diff --git a/aisp/base/core/_clusterer.py b/aisp/base/core/_clusterer.py index ce376a7..00948f4 100644 --- a/aisp/base/core/_clusterer.py +++ b/aisp/base/core/_clusterer.py @@ -70,7 +70,7 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: Parameters ---------- X : Union[npt.NDArray, list] - Input data for which predictions will be generated. + Data for which predictions will be generated. Returns ------- @@ -87,7 +87,7 @@ def fit_predict(self, X: Union[npt.NDArray, list], verbose: bool = True) -> npt. Parameters ---------- X : Union[npt.NDArray, list] - Input data for which predictions will be generated. + Data for which predictions will be generated. verbose : bool, default=True Flag to enable or disable detailed output during training. diff --git a/aisp/base/core/_optimizer.py b/aisp/base/core/_optimizer.py index aff2a42..c65590a 100644 --- a/aisp/base/core/_optimizer.py +++ b/aisp/base/core/_optimizer.py @@ -188,10 +188,10 @@ def register(self, alias: str, function: Callable[..., Any]) -> None: Raises ------ TypeError - If `function` is not callable. + If the provided `function` is not callable. AttributeError - If `alias` is protected and cannot be modified. Or if `alias` does not exist in the - optimizer class. + If `alias` is protected and cannot be modified, or does not exist in the + class. """ if not callable(function): raise TypeError(f"Expected a function for '{alias}', got {type(function).__name__}") diff --git a/aisp/base/immune/populations.py b/aisp/base/immune/populations.py index a67cbf0..0f3948b 100644 --- a/aisp/base/immune/populations.py +++ b/aisp/base/immune/populations.py @@ -29,15 +29,15 @@ def generate_random_antibodies( bounds : npt.NDArray[np.float64], optional Array (n_features, 2) with min and max per dimension. - Raises - ------ - ValueError - If number of features must be greater than zero. - Returns ------- npt.NDArray Array of shape (n_samples, n_features) containing the generated antibodies. + + Raises + ------ + ValueError + If the number of features is less than or equal to zero. """ if n_features <= 0: raise ValueError("Number of features must be greater than zero.") diff --git a/aisp/csa/_ai_recognition_sys.py b/aisp/csa/_ai_recognition_sys.py index e4a66d6..67af792 100644 --- a/aisp/csa/_ai_recognition_sys.py +++ b/aisp/csa/_ai_recognition_sys.py @@ -56,7 +56,6 @@ class AIRS(BaseClassifier): Maximum number of iterations in the refinement process of the ARB set exposed to aᵢ. resource_amplified : float, default=1.0 Resource consumption amplifier is multiplied with the incentive to subtract resources. - Defaults to 1.0 without amplification. metric : {"euclidean", "minkowski", "manhattan"}, default="euclidean" Distance metric used to compute affinity between cells and samples. seed : int @@ -192,6 +191,11 @@ def fit( ------- AIRS Returns the instance itself. + + Raises + ------ + TypeError + If X or y are not ndarrays or have incompatible shapes. """ X = self._prepare_features(X) y = check_array_type(y, "y") @@ -260,6 +264,12 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: X : Union[npt.NDArray, list] Array with input samples with Shape: (`n_samples, n_features`) + Returns + ------- + C : npt.NDArray + An ndarray of the form `C` (`n_samples`), containing the predicted classes for + `X`. + Raises ------ TypeError @@ -269,12 +279,6 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: ModelNotFittedError If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions - - Returns - ------- - C : npt.NDArray - An ndarray of the form `C` (`n_samples`), containing the predicted classes for - `X`. """ if self._all_class_cell_vectors is None: raise ModelNotFittedError("AIRS") @@ -524,6 +528,13 @@ def _prepare_features(self, X: Union[npt.NDArray, list]) -> npt.NDArray: ------- X : npt.NDArray The processed input data. + + Raises + ------ + TypeError: + If X is not a ndarray or a list. + UnsupportedTypeError + If the data type of the vector is not supported. """ X = check_array_type(X) self._feature_type = detect_vector_data_type(X) diff --git a/aisp/csa/_clonalg.py b/aisp/csa/_clonalg.py index 1c4d68f..921fdaa 100644 --- a/aisp/csa/_clonalg.py +++ b/aisp/csa/_clonalg.py @@ -186,15 +186,15 @@ def optimize( verbose : bool, default=True Feedback on iterations, indicating the best antibody. - Raises - ------ - NotImplementedError - If no affinity function has been provided to model. - Returns ------- population : List[Antibody] Antibody population after clonal expansion. + + Raises + ------ + NotImplementedError + If no affinity function has been provided to evaluate candidate solutions. """ self.reset() diff --git a/aisp/ina/_ai_network.py b/aisp/ina/_ai_network.py index 60fafb0..725fc2c 100644 --- a/aisp/ina/_ai_network.py +++ b/aisp/ina/_ai_network.py @@ -222,17 +222,17 @@ def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> AiNet: verbose : bool, default=True Feedback from the progress bar showing current training interaction details. + Returns + ------- + self : AiNet + Returns the instance of the class that implements this method. + Raises ------ TypeError If X is not a ndarray or list. UnsupportedTypeError - If the data type of the vector is not supported. - - Returns - ------- - self : AiNet - Returns the instance of the class that implements this method. + If the data type of the feature on X is not supported. """ X = self._prepare_features(X) @@ -287,6 +287,11 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: X : Union[npt.NDArray, list] Data to predict. + Returns + ------- + predictions : npt.NDArray + Predicted cluster labels, or None if clustering is disabled. + Raises ------ TypeError @@ -294,15 +299,10 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: ValueError If the array contains values other than 0 and 1. FeatureDimensionMismatch - If the number of features in X does not match the expected number. + If the number of features (columns) in X does not match the expected number. ModelNotFittedError If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions - - Returns - ------- - predictions : npt.NDArray - Predicted cluster labels, or None if clustering is disabled. """ if ( not self.use_mst_clustering @@ -478,7 +478,6 @@ def _calculate_affinities(self, u: npt.NDArray, v: npt.NDArray) -> npt.NDArray: v : npt.NDArray An array of vectors with shape (n_samples, n_features). - Returns ------- affinities : npt.NDArray @@ -617,7 +616,7 @@ def _prepare_features(self, X: Union[npt.NDArray, list]) -> npt.NDArray: """ Check the samples, specifying the type, quantity of characteristics, and other parameters. - * This method updates the following attributes: + This method updates the following attributes: * ``self._feature_type`` * ``self.metric`` (only for binary features) * ``self._bounds`` (only for ranged features) @@ -629,15 +628,17 @@ def _prepare_features(self, X: Union[npt.NDArray, list]) -> npt.NDArray: Training array, containing the samples and their characteristics, Shape: (n_samples, n_features). - Raises - ------ - UnsupportedTypeError - If the data type of the vector is not supported. - Returns ------- X : npt.NDArray The processed input data. + + Raises + ------ + TypeError: + If X is not a ndarray or a list. + UnsupportedTypeError + If the data type of the vector is not supported. """ X = check_array_type(X) self._feature_type = detect_vector_data_type(X) diff --git a/aisp/nsa/_binary_negative_selection.py b/aisp/nsa/_binary_negative_selection.py index 5c83275..965d158 100644 --- a/aisp/nsa/_binary_negative_selection.py +++ b/aisp/nsa/_binary_negative_selection.py @@ -148,20 +148,20 @@ def fit( verbose : bool, default=True Feedback from detector generation to the user. + Returns + ------- + self : BNSA + Returns the instance itself. + Raises ------ TypeError If X or y are not ndarrays or have incompatible shapes. ValueError - If the array contains values other than 0 and 1. + If the array X contains any values other than (0 and 1) or (True and False). MaxDiscardsReachedError - The maximum number of detector discards was reached during maturation. Check the + If the maximum number of detector discards was reached during maturation. Check the defined radius value and consider reducing it. - - Returns - ------- - self : BNSA - Returns the instance itself. """ X = check_array_type(X) y = check_array_type(y, "y") @@ -225,6 +225,12 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: X : Union[npt.NDArray, list] Array with input samples with Shape: (`n_samples, n_features`) + Returns + ------- + c : npt.NDArray + A ndarray of the form `C` (`n_samples`), containing the predicted classes for + `X`. + Raises ------ TypeError @@ -232,16 +238,10 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: ValueError If the array contains values other than 0 and 1. FeatureDimensionMismatch - If the number of features in X does not match the expected number. + If the number of features (columns) in X does not match the expected number. ModelNotFittedError If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions - - Returns - ------- - c : npt.NDArray - A ndarray of the form `C` (`n_samples`), containing the predicted classes for - `X`. """ if ( self._detectors is None diff --git a/aisp/nsa/_negative_selection.py b/aisp/nsa/_negative_selection.py index 89d5845..a54eca3 100644 --- a/aisp/nsa/_negative_selection.py +++ b/aisp/nsa/_negative_selection.py @@ -191,20 +191,20 @@ def fit( verbose: bool, default=True Feedback from detector generation to the user. + Returns + ------- + self : RNSA + Returns the instance itself. + Raises ------ TypeError If X or y are not ndarrays or have incompatible shapes. + ValueError + If the array X fall outside the interval (0.0, 1.0). MaxDiscardsReachedError The maximum number of detector discards was reached during maturation. Check the defined radius value and consider reducing it. - ValueError - If the array X fall outside the interval (0, 1). - - Returns - ------- - self : RNSA - Returns the instance itself. """ X = check_array_type(X) y = check_array_type(y, "y") @@ -270,23 +270,23 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: X : Union[npt.NDArray, list] Array with input samples with Shape: (n_samples, n_features) + Returns + ------- + C : npt.NDArray + A ndarray of the form `C` (n_samples), containing the predicted classes + for `X`. + Raises ------ TypeError If X is not a ndarray or list. + ValueError + If the array X fall outside the interval (0.0, 1.0). FeatureDimensionMismatch If the number of features in X does not match the expected number. ModelNotFittedError If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions - ValueError - If the array X fall outside the interval (0, 1). - - Returns - ------- - C : npt.NDArray - A ndarray of the form `C` (n_samples), containing the predicted classes - for `X`. """ if self._detectors is None or self.classes is None: raise ModelNotFittedError("RNSA") diff --git a/aisp/utils/distance.py b/aisp/utils/distance.py index 4b2de45..6d01dbf 100644 --- a/aisp/utils/distance.py +++ b/aisp/utils/distance.py @@ -203,15 +203,15 @@ def get_metric_code(metric: str) -> int: metric : str Name of the metric. Can be "euclidean", "manhattan", "minkowski" or "hamming". - Raises - ------ - ValueError - If the metric provided is not supported. - Returns ------- int Numeric code corresponding to the metric. + + Raises + ------ + ValueError + If the metric provided is not supported. """ metric_map = { "euclidean": EUCLIDEAN, From c5e81d1cec0c1756cc86bfa625079a9011d8f96a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Sat, 21 Mar 2026 15:27:56 -0300 Subject: [PATCH 40/40] docs(api-en): update Raises e returns section in docs. --- aisp/ina/_ai_network.py | 2 +- docs/assets/template-docs-class.md | 2 - docs/en/api/base/base-classifier.md | 18 ++++--- docs/en/api/base/base-clusterer.md | 14 ++++-- docs/en/api/base/base-optimizer.md | 20 +++++--- docs/en/api/base/immune/cell/b-cell.md | 4 +- docs/en/api/base/immune/mutation.md | 16 ++++-- docs/en/api/base/immune/populations.md | 12 +++-- docs/en/api/csa/airs.md | 30 ++++++++---- docs/en/api/csa/clonalg.md | 26 +++++++--- docs/en/api/ina/ai-net.md | 51 ++++++++++++-------- docs/en/api/nsa/bnsa.md | 43 ++++++++++------- docs/en/api/nsa/rnsa.md | 38 +++++++++------ docs/en/api/utils/display/table-formatter.md | 13 +++-- docs/en/api/utils/distance.md | 44 +++++++++++------ docs/en/api/utils/metrics.md | 12 +++-- docs/en/api/utils/multiclass.md | 8 ++- docs/en/api/utils/sanitizers.md | 27 ++++++++--- docs/en/api/utils/validation.md | 41 +++++++++++----- 19 files changed, 276 insertions(+), 145 deletions(-) diff --git a/aisp/ina/_ai_network.py b/aisp/ina/_ai_network.py index 725fc2c..0f04715 100644 --- a/aisp/ina/_ai_network.py +++ b/aisp/ina/_ai_network.py @@ -225,7 +225,7 @@ def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> AiNet: Returns ------- self : AiNet - Returns the instance of the class that implements this method. + Returns the instance itself. Raises ------ diff --git a/docs/assets/template-docs-class.md b/docs/assets/template-docs-class.md index d75cf6c..00deb70 100644 --- a/docs/assets/template-docs-class.md +++ b/docs/assets/template-docs-class.md @@ -79,14 +79,12 @@ Description. |-----------|--------|:-------:|---------------------------| | `param_1` | `Type` | - | Description of the param. | - **Returns** | Type | Description | |--------------|----------------------------| | `ReturnType` | Description of the return. | - **Raises** | Exception | Description | diff --git a/docs/en/api/base/base-classifier.md b/docs/en/api/base/base-classifier.md index 59c8fac..51b4986 100644 --- a/docs/en/api/base/base-classifier.md +++ b/docs/en/api/base/base-classifier.md @@ -69,7 +69,9 @@ This abstract method is implemented by the class that inherits it. **Returns** -``BaseClassifier`` - Returns the instance of the class that implements this method. +| Type | Description | +|--------|----------------------------------------------------------------| +| `Self` | Returns the instance of the class that implements this method. | --- @@ -86,13 +88,15 @@ This abstract method is implemented by the class that inherits it. **Parameters** -| Name | Type | Default | Description | -|------|----------------------------|:-------:|-----------------------------------------------------| -| `X` | `Union[npt.NDArray, list]` | - | Input data for which predictions will be generated. | +| Name | Type | Default | Description | +|------|----------------------------|:-------:|-----------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Data for which predictions will be generated. | **Returns** -`npt.NDArray` - Predicted values for each input sample. +| Type | Description | +|---------------|-----------------------------------------| +| `npt.NDArray` | Predicted values for each input sample. | --- @@ -123,5 +127,7 @@ This function was added for compatibility with some scikit-learn functions. **Returns** -`float` - The accuracy of the model. +| Type | Description | +|---------|----------------------------| +| `float` | The accuracy of the model. | diff --git a/docs/en/api/base/base-clusterer.md b/docs/en/api/base/base-clusterer.md index b2278de..ac139d5 100644 --- a/docs/en/api/base/base-clusterer.md +++ b/docs/en/api/base/base-clusterer.md @@ -64,7 +64,9 @@ This abstract method is implemented by the class that inherits it. **Returns** -``BaseClassifier`` - Returns the instance of the class that implements this method. +| Type | Description | +|--------|----------------------------------------------------------------| +| `Self` | Returns the instance of the class that implements this method. | --- @@ -83,11 +85,13 @@ This abstract method is implemented by the class that inherits it. | Name | Type | Default | Description | |------|----------------------------|:-------:|-----------------------------------------------------| -| `X` | `Union[npt.NDArray, list]` | - | Input data for which predictions will be generated. | +| `X` | `Union[npt.NDArray, list]` | - | Data for which predictions will be generated. | **Returns** -`npt.NDArray` - Predicted cluster labels for each input sample. +| Type | Description | +|---------------|-------------------------------------------------| +| `npt.NDArray` | Predicted cluster labels for each input sample. | --- @@ -113,4 +117,6 @@ This is a convenience method that combines `fit` and `predict` into a single cal **Returns** -`npt.NDArray` - Predicted cluster labels for each input sample. +| Type | Description | +|---------------|-------------------------------------------------| +| `npt.NDArray` | Predicted cluster labels for each input sample. | diff --git a/docs/en/api/base/base-optimizer.md b/docs/en/api/base/base-optimizer.md index 9b53e21..f3bde23 100644 --- a/docs/en/api/base/base-optimizer.md +++ b/docs/en/api/base/base-optimizer.md @@ -76,8 +76,9 @@ space. **Returns** -``BaseClassifier`` - Returns the instance of the class that implements this method. - +| Type | Description | +|--------|----------------------------------------------------------------| +| `Self` | Returns the instance of the class that implements this method. | --- @@ -103,7 +104,9 @@ The returned value should represent the quality of the evaluated solution. **Returns** -`float` - Cost value associated with the given solution. +| Type | Description | +|---------|------------------------------------------------| +| `float` | Cost value associated with the given solution. | --- @@ -121,7 +124,9 @@ The report includes the best solution, its associated cost, and the evolution of **Returns** -`str` - A formatted string containing the optimization summary. +| Type | Description | +|-------|---------------------------------------------------------| +| `str` | A formatted string containing the optimization summary. | --- @@ -143,9 +148,10 @@ Register a function dynamically in the optimizer instance. **Raises** -`TypeError` - If `function` is not callable. - -`AttributeError` - If `alias` is protected and cannot be modified. Or if `alias` does not exist in the optimizer class. +| Exception | Description | +|------------------|---------------------------------------------------------------------------------| +| `TypeError` | If the provided `function` is not callable. | +| `AttributeError` | If `alias` is protected and cannot be modified, or does not exist in the class. | --- diff --git a/docs/en/api/base/immune/cell/b-cell.md b/docs/en/api/base/immune/cell/b-cell.md index 6a7d297..cd96493 100644 --- a/docs/en/api/base/immune/cell/b-cell.md +++ b/docs/en/api/base/immune/cell/b-cell.md @@ -58,4 +58,6 @@ Generate **N** clones of the current cell and apply hypermutation to the clones. **Returns** -`npt.NDArray` - An array containing N mutated vectors from the original cell. +| Type | Description | +|---------------|---------------------------------------------------------------| +| `npt.NDArray` | An array containing N mutated vectors from the original cell. | diff --git a/docs/en/api/base/immune/mutation.md b/docs/en/api/base/immune/mutation.md index 8ebe13c..c0d34a9 100644 --- a/docs/en/api/base/immune/mutation.md +++ b/docs/en/api/base/immune/mutation.md @@ -48,7 +48,9 @@ them, simulating the process of clonal expansion in artificial immune systems. **Returns** -`npt.NDArray[np.float64]` - An Array(n, len(vector)) containing the `n` mutated clones of the original vector. +| Type | Description | +|---------------------------|------------------------------------------------------------------------------------| +| `npt.NDArray[np.float64]` | An Array(n, len(vector)) containing the `n` mutated clones of the original vector. | ### clone_and_mutate_binary @@ -77,7 +79,9 @@ bits, simulating clonal expansion in artificial immune systems with discrete rep **Returns** -`npt.NDArray[np.bool_]` - An Array(n, len(vector)) containing the `n` mutated clones of the original vector. +| Type | Description | +|-------------------------|------------------------------------------------------------------------------------| +| `npt.NDArray[np.bool_]` | An Array(n, len(vector)) containing the `n` mutated clones of the original vector. | ### clone_and_mutate_ranged @@ -108,7 +112,9 @@ them, simulating the process of clonal expansion in artificial immune systems. **Returns** -`npt.NDArray[np.float64]` - An Array(n, len(vector)) containing the `n` mutated clones of the original vector. +| Type | Description | +|---------------------------|------------------------------------------------------------------------------------| +| `npt.NDArray[np.float64]` | An Array(n, len(vector)) containing the `n` mutated clones of the original vector. | ### clone_and_mutate_continuous @@ -134,4 +140,6 @@ Generate a set of mutated clones by permutation. **Returns** -`npt.NDArray[np.float64]` - An Array(n, len(vector)) containing the `n` mutated clones of the original vector. +| Type | Description | +|---------------------------|------------------------------------------------------------------------------------| +| `npt.NDArray[np.float64]` | An Array(n, len(vector)) containing the `n` mutated clones of the original vector. | diff --git a/docs/en/api/base/immune/populations.md b/docs/en/api/base/immune/populations.md index 0586e00..0126de2 100644 --- a/docs/en/api/base/immune/populations.md +++ b/docs/en/api/base/immune/populations.md @@ -43,10 +43,14 @@ Generate a random antibody population. | `feature_type` | [`FeatureTypeAll`](../../utils/types.md#featuretypeall) | `"continuous-features"` | Specifies the type of features: "continuous-features", "binary-features", "ranged-features", or "permutation-features". | | `bounds` | `npt.NDArray[np.float64]` | `None` | Array (n_features, 2) with min and max per dimension. | -**Raises** +**Returns** -`ValueError` - If number of features must be greater than zero. +| Type | Description | +|---------------|-----------------------------------------------------------------------------| +| `npt.NDArray` | Array of shape (n_samples, n_features) containing the generated antibodies. | -**Returns** +**Raises** -`npt.NDArray` - Array of shape (n_samples, n_features) containing the generated antibodies. +| Exception | Description | +|--------------|----------------------------------------------------------| +| `ValueError` | If the number of features is less than or equal to zero. | diff --git a/docs/en/api/csa/airs.md b/docs/en/api/csa/airs.md index 0fa9358..8517b45 100644 --- a/docs/en/api/csa/airs.md +++ b/docs/en/api/csa/airs.md @@ -129,12 +129,20 @@ method AIRS. | Name | Type | Default | Description | |-----------|----------------------------|:-------:|---------------------------------------------------------------------------------------------------| | `X` | `Union[npt.NDArray, list]` | - | Training array, containing the samples and their characteristics, Shape: (n_samples, n_features). | -| `y` | `Union[npt.NDArray, list]` | - | Array of target classes of `X` with (`n_samples`). | +| `y` | `Union[npt.NDArray, list]` | - | Array of target classes of `X` with (`n_samples`). | | `verbose` | `bool` | `True` | Feedback on which sample aᵢ the memory cells are being generated. | **Returns** -`AIRS` - Returns the instance itself. +| Type | Description | +|--------|------------------------------| +| `Self` | Returns the instance itself. | + +**Raises** + +| Exception | Description | +|-------------|---------------------------------------------------------| +| `TypeError` | If X or y are not ndarrays or have incompatible shapes. | --- @@ -156,17 +164,19 @@ using the k-nearest neighbors approach. |------|----------------------------|:-------:|-----------------------------------------------------------------| | `X` | `Union[npt.NDArray, list]` | - | Array with input samples with Shape: (`n_samples, n_features`) | -**Raises** +**Returns** -* `TypeError` - If X is not a ndarray or list. -* [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) - If the number of features in X does not - match the expected number. -* [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) - If the mode has not yet been adjusted and does not - have defined memory cells, it is not able to predictions +| Type | Description | +|---------------|-------------------------------------------------------------------------------------| +| `npt.NDArray` | An ndarray of the form `C` (`n_samples`), containing the predicted classes for `X`. | -**Returns** +**Raises** -**C** : `npt.NDArray` - An ndarray of the form `C` (`n_samples`), containing the predicted classes for `X`. +| Exception | Description | +|-------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X is not a ndarray or list. | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | If the number of features in X does not match the expected number. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions | --- diff --git a/docs/en/api/csa/clonalg.md b/docs/en/api/csa/clonalg.md index c92d0a2..863e94e 100644 --- a/docs/en/api/csa/clonalg.md +++ b/docs/en/api/csa/clonalg.md @@ -123,13 +123,18 @@ Execute the optimization process and return the population. | `n_iter_no_change` | `int` | `10` | The maximum number of iterations without updating the best cell. | | `verbose` | `bool` | `True` | Feedback on iterations, indicating the best antibody. | -**Raises** +**Returns** -* `NotImplementedError` - If no affinity function has been provided to model. +| Type | Description | +|------------------|---------------------------------------------| +| `List[Antibody]` | Antibody population after clonal expansion. | -**Returns** -**population** : `List[Antibody]` - Antibody population after clonal expansion. +**Raises** + +| Exception | Description | +|-----------------------|----------------------------------------------------------------------------| +| `NotImplementedError` | If no affinity function has been provided to evaluate candidate solutions. | --- @@ -148,13 +153,18 @@ Evaluate the affinity of a candidate cell. |------------|---------------|:-------:|---------------------------------| | `solution` | `npt.NDArray` | - | Candidate solution to evaluate. | -**Raises** +**Returns** -* `NotImplementedError` - If no affinity function has been provided. +| Type | Description | +|--------------|------------------------------------------------| +| `np.float64` | Affinity value associated with the given cell. | -**Returns** -**affinity** : `np.float64` - Affinity value associated with the given cell. +**Raises** + +| Exception | Description | +|-----------------------|--------------------------------------------| +| `NotImplementedError` | If no affinity function has been provided. | --- diff --git a/docs/en/api/ina/ai-net.md b/docs/en/api/ina/ai-net.md index 077d0bf..46d2d78 100644 --- a/docs/en/api/ina/ai-net.md +++ b/docs/en/api/ina/ai-net.md @@ -123,14 +123,19 @@ Train the AiNet model on input data. | `X` | `Union[npt.NDArray, list]` | - | Input data used for training the model. | | `verbose` | `bool` | `True` | Feedback from the progress bar showing current training interaction details. | -**Raises** +**Returns** -* `TypeError` - If X is not a ndarray or list. -* [`UnsupportedTypeError`](../exceptions.md#unsupportedtypeerror) - If the data type of the vector is not supported. +| Type | Description | +|--------|------------------------------| +| `Self` | Returns the instance itself. | -**Returns** -`AiNet` - Returns the instance of the class that implements this method. +**Raises** + +| Exception | Description | +|-----------------------------------------------------------------|--------------------------------------------------------| +| `TypeError` | If X is not a ndarray or list. | +| [`UnsupportedTypeError`](../exceptions.md#unsupportedtypeerror) | If the data type of the feature on X is not supported. | --- @@ -149,18 +154,21 @@ Predict cluster labels for input data. |------|----------------------------|:-------:|------------------| | `X` | `Union[npt.NDArray, list]` | - | Data to predict. | -**Raises** +**Returns** -* `TypeError` - If X is not a ndarray or list. -* `ValueError` - If the array contains values other than 0 and 1. -* [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) - If the number of features in X does not - match the expected number. -* [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) - If the mode has not yet been adjusted and does not - have defined memory cells, it is not able to predictions +| Type | Description | +|---------------|--------------------------------------------------------------| +| `npt.NDArray` | Predicted cluster labels, or None if clustering is disabled. | -**Returns** -**predictions** : `npt.NDArray` - Predicted cluster labels, or None if clustering is disabled. +**Raises** + +| Exception | Description | +|-------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X is not a ndarray or list. | +| `ValueError` | If the array contains values other than 0 and 1. | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | If the number of features (columns) in X does not match the expected number. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions | --- @@ -187,15 +195,18 @@ distinct cluster. **Raises** -* `ValueError` - * If the Minimum Spanning Tree (MST) has not yet been created - * If Population of antibodies is empty - * If MST statistics (mean or std) are not available. +| Exception | Description | +|--------------|-------------------------------------------------------------| +| `ValueError` | If the Minimum Spanning Tree (MST) has not yet been created | +| `ValueError` | If Population of antibodies is empty | +| `ValueError` | If MST statistics (mean or std) are not available. | **Updates** -* **memory_network** : `dict[int, npt.NDArray]` - Dictionary mapping cluster labels to antibody arrays. -* **labels** : `list` - List of cluster labels. +| Name | Type | Description | +|------------------|--------------------------|-------------------------------------------------------| +| `memory_network` | `dict[int, npt.NDArray]` | Dictionary mapping cluster labels to antibody arrays. | +| `labels` | `list` | List of cluster labels. | --- diff --git a/docs/en/api/nsa/bnsa.md b/docs/en/api/nsa/bnsa.md index c6465b1..228ac23 100644 --- a/docs/en/api/nsa/bnsa.md +++ b/docs/en/api/nsa/bnsa.md @@ -127,16 +127,20 @@ Training according to X and y, using the method negative selection method. | `y` | `Union[npt.NDArray, list]` | - | Array of target classes of `X` with (`n_samples`). | | `verbose` | `bool` | `True` | Feedback from detector generation to the user. | -**Raises** +**Returns** -* `TypeError` - If X or y are not ndarrays or have incompatible shapes. -* `ValueError` - If the array contains values other than 0 and 1. -* [`MaxDiscardsReachedError`](../exceptions.md#maxdiscardsreachederror) - The maximum number of detector discards was - reached during maturation. Check the defined radius value and consider reducing it. +| Type | Description | +|--------|------------------------------| +| `Self` | Returns the instance itself. | -**Returns** -`BNSA` - Returns the instance itself. +**Raises** + +| Exception | Description | +|-----------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X or y are not ndarrays or have incompatible shapes. | +| `ValueError` | If the array X contains any values other than (0 and 1) or (True and False). | +| [`MaxDiscardsReachedError`](../exceptions.md#maxdiscardsreachederror) | If the maximum number of detector discards was reached during maturation. Check the defined radius value and consider reducing it. | --- @@ -151,22 +155,25 @@ Prediction of classes based on detectors created after training. **Parameters** -| Name | Type | Default | Description | -|------|----------------------------|:-------:|-------------------------------------------------------------------| +| Name | Type | Default | Description | +|------|----------------------------|:-------:|-----------------------------------------------------------------| | `X` | `Union[npt.NDArray, list]` | - | Array with input samples with Shape: (`n_samples, n_features`) | -**Raises** +**Returns** -* `TypeError` - If X is not a ndarray or list. -* `ValueError` - If the array contains values other than 0 and 1. -* [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) - If the number of features in X does not - match the expected number. -* [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) - If the mode has not yet been adjusted and does not - have defined detectors or classes, it is not able to predictions +| Type | Description | +|---------------|-------------------------------------------------------------------------------------| +| `npt.NDArray` | An ndarray of the form `C` (`n_samples`), containing the predicted classes for `X`. | -**Returns** -**C** : `npt.NDArray` - An ndarray of the form `C` (`n_samples`), containing the predicted classes for `X`. +**Raises** + +| Exception | Description | +|-------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X is not a ndarray or list. | +| `ValueError` | If the array contains values other than 0 and 1. | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | If the number of features (columns) in X does not match the expected number. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions | --- diff --git a/docs/en/api/nsa/rnsa.md b/docs/en/api/nsa/rnsa.md index a30c8c1..fd4e6c8 100644 --- a/docs/en/api/nsa/rnsa.md +++ b/docs/en/api/nsa/rnsa.md @@ -155,16 +155,20 @@ Perform training according to X and y, using the negative selection method (Nega | `y` | `Union[npt.NDArray, list]` | - | Array of target classes of `X` with (`n_samples`). | | `verbose` | `bool` | `True` | Feedback from detector generation to the user. | -**Raises** +**Returns** -* `TypeError` - If X or y are not ndarrays or have incompatible shapes. -* `ValueError` - If the array X fall outside the interval (0, 1). -* [`MaxDiscardsReachedError`](../exceptions.md#maxdiscardsreachederror) - The maximum number of detector discards was - reached during maturation. Check the defined radius value and consider reducing it. +| Type | Description | +|--------|------------------------------| +| `Self` | Returns the instance itself. | -**Returns** -`RNSA` - Returns the instance itself. +**Raises** + +| Exception | Description | +|-----------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X or y are not ndarrays or have incompatible shapes. | +| `ValueError` | If the array X fall outside the interval (0.0, 1.0). | +| [`MaxDiscardsReachedError`](../exceptions.md#maxdiscardsreachederror) | The maximum number of detector discards was reached during maturation. Check the defined radius value and consider reducing it. | --- @@ -183,18 +187,20 @@ Prediction of classes based on detectors created after training. |------|----------------------------|:-------:|-----------------------------------------------------------------| | `X` | `Union[npt.NDArray, list]` | - | Array with input samples with Shape: (`n_samples, n_features`) | -**Raises** +**Returns** -* `TypeError` - If X is not a ndarray or list. -* `ValueError` - If the array X fall outside the interval (0, 1). -* [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) - If the number of features in X does not - match the expected number. -* [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) - If the mode has not yet been adjusted and does not - have defined detectors or classes, it is not able to predictions +| Type | Description | +|---------------|-------------------------------------------------------------------------------------| +| `npt.NDArray` | An ndarray of the form `C` (`n_samples`), containing the predicted classes for `X`. | -**Returns** +**Raises** -**C** : `npt.NDArray` - An ndarray of the form `C` (`n_samples`), containing the predicted classes for `X`. +| Exception | Description | +|-------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X is not a ndarray or list. | +| `ValueError` | If the array X fall outside the interval (0.0, 1.0). | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | If the number of features in X does not match the expected number. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions | --- diff --git a/docs/en/api/utils/display/table-formatter.md b/docs/en/api/utils/display/table-formatter.md index 91de3fc..c1c8931 100644 --- a/docs/en/api/utils/display/table-formatter.md +++ b/docs/en/api/utils/display/table-formatter.md @@ -33,7 +33,10 @@ Generate the table header, including the top border, column headings, and separa **Returns** -`str` - Formatted string of the table header. +| Type | Description | +|-------|---------------------------------------| +| `str` | Formatted string of the table header. | + --- @@ -54,7 +57,9 @@ Generate a formatted row for the table data. **Returns** -`str` - Formatted string of the table row. +| Type | Description | +|-------|------------------------------------| +| `str` | Formatted string of the table row. | --- @@ -75,4 +80,6 @@ Generate the table's bottom border. **Returns** -`str` - Formatted string for the bottom border. +| Type | Description | +|-------|-----------------------------------------| +| `str` | Formatted string for the bottom border. | diff --git a/docs/en/api/utils/distance.md b/docs/en/api/utils/distance.md index f264c29..fc827f6 100644 --- a/docs/en/api/utils/distance.md +++ b/docs/en/api/utils/distance.md @@ -40,9 +40,12 @@ $$ | `u` | `npt.NDArray[np.bool_]` | - | Coordinates of the first point. | | `v` | `npt.NDArray[np.bool_]` | - | Coordinates of the second point. | + **Returns** -`float64` - Hamming distance between two points. +| Type | Description | +|-----------|--------------------------------------| +| `float64` | Hamming distance between two points. | --- @@ -69,7 +72,9 @@ $$ **Returns** -`float64` - Euclidean distance between two points. +| Type | Description | +|-----------|----------------------------------------| +| `float64` | Euclidean distance between two points. | --- @@ -96,7 +101,9 @@ $$ **Returns** -`float64` - Manhattan distance between two points. +| Type | Description | +|-----------|----------------------------------------| +| `float64` | Manhattan distance between two points. | --- @@ -136,7 +143,9 @@ $$ **Returns** -`float64` - Minkowski distance between two points. +| Type | Description | +|-----------|----------------------------------------| +| `float64` | Minkowski distance between two points. | --- @@ -164,13 +173,11 @@ Calculate the distance between two points by the chosen metric. | `metric` | `int` | - | Distance metric to be used. Available options: 0 (Euclidean), 1 (Manhattan), 2 (Minkowski) | | `p` | `float` | `2.0` | The p parameter defines the type of distance to be calculated. | -**Raises** - -{{ Raise }} - {{ Description }}. - **Returns** -`float64` - Distance between the two points with the selected metric. +| Type | Description | +|-----------|-----------------------------------------------------------| +| `float64` | Distance between the two points with the selected metric. | --- @@ -200,8 +207,9 @@ Calculate the minimum distance between an input vector and the vectors of a clas **Returns** -**min_distance**: `float` - The minimum distance calculated between the input vector and the class vectors. Returns -1.0 -if the input dimensions are incompatible. +| Type | Description | +|---------|----------------------------------------------------------------------------------------------------------------------------------------| +| `float` | The minimum distance calculated between the input vector and the class vectors. Returns -1.0 if the input dimensions are incompatible. | --- @@ -220,10 +228,16 @@ Get the numeric code associated with a distance metric. |----------|-------|:-------:|----------------------------------------------------------------------------------------| | `metric` | `str` | - | Name of the metric. Can be `"euclidean"`, `"manhattan"`, `"minkowski"` or `"hamming"`. | -**Raises** +**Returns** -* `ValueError` - If the metric provided is not supported. +| Type | Description | +|-------|-------------------------------------------| +| `int` | Numeric code corresponding to the metric. | -**Returns** -`int` - Numeric code corresponding to the metric. +**Raises** + +| Exception | Description | +|--------------|------------------------------------------| +| `ValueError` | If the metric provided is not supported. | + diff --git a/docs/en/api/utils/metrics.md b/docs/en/api/utils/metrics.md index 6fcd4f5..14e8ff3 100644 --- a/docs/en/api/utils/metrics.md +++ b/docs/en/api/utils/metrics.md @@ -34,10 +34,14 @@ Calculate the accuracy score based on true and predicted labels. | `y_true` | `Union[npt.NDArray, list]` | - | Ground truth (correct) labels. Expected to be of the same length as `y_pred`. | | `y_pred` | `Union[npt.NDArray, list]` | - | Predicted labels. Expected to be of the same length as `y_true`. | -**Raises** +**Returns** -* `ValueError` - If `y_true` or `y_pred` are empty or if they do not have the same length. +| Type | Description | +|---------|----------------------------------------------------------------------| +| `float` | The ratio of correct predictions to the total number of predictions. | -**Returns** +**Raises** -**accuracy**: `float` - The ratio of correct predictions to the total number of predictions. +| Exception | Description | +|--------------|---------------------------------------------------------------------------| +| `ValueError` | If `y_true` or `y_pred` are empty or if they do not have the same length. | diff --git a/docs/en/api/utils/multiclass.md b/docs/en/api/utils/multiclass.md index 6005abe..367c641 100644 --- a/docs/en/api/utils/multiclass.md +++ b/docs/en/api/utils/multiclass.md @@ -35,7 +35,9 @@ Separate indices of samples by class for targeted iteration. **Returns** -**position_samples**: `dict` - A dictionary with the list of array positions(`y`), with the classes as key. +| Type | Description | +|--------|------------------------------------------------------------------------------| +| `dict` | A dictionary with the list of array positions(`y`), with the classes as key. | **Example** @@ -75,4 +77,6 @@ Predict classes using k-nearest neighbors and trained cells. **Returns** -**predicted_labels**: `npt.NDArray` - Array of predicted labels for each sample in X, based on the k nearest neighbors. +| Type | Description | +|---------------|-----------------------------------------------------------------------------------| +| `npt.NDArray` | Array of predicted labels for each sample in X, based on the k nearest neighbors. | diff --git a/docs/en/api/utils/sanitizers.md b/docs/en/api/utils/sanitizers.md index eb62e18..9a189a4 100644 --- a/docs/en/api/utils/sanitizers.md +++ b/docs/en/api/utils/sanitizers.md @@ -33,7 +33,9 @@ Value if present in the set of valid choices; otherwise, the default value. **Returns** -**value** : `T` - The original value if valid, or the default value if not. +| Type | Description | +|------|-----------------------------------------------------------| +| `T` | The original value if valid, or the default value if not. | --- @@ -56,7 +58,9 @@ Value if it satisfies the specified condition; otherwise, the default value. **Returns** -**value**: `T` - The original value if the condition is satisfied, or the default value if not. +| Type | Description | +|------|--------------------------------------------------------------------------------| +| `T` | The original value if the condition is satisfied, or the default value if not. | --- @@ -77,6 +81,11 @@ Seed if it is a non-negative integer; otherwise, None. **Returns** +| Type | Description | +|-----------------|------------------------------------------------------------------------------| +| `Optional[int]` | The original seed if it is a non-negative integer, or None if it is invalid. | + + **seed**: `Optional[int]` - The original seed if it is a non-negative integer, or None if it is invalid. --- @@ -99,11 +108,15 @@ Validate and normalize feature bounds. | `bounds` | `Any` | - | The input bounds, which must be either None or a dictionary with 'low' and 'high' keys. | | `problem_size` | `int` | - | The expected length for the normalized bounds lists, corresponding to the number of features in the problem. | -**Raises** +**Returns** -* `TypeError` - If `bounds` is not None and not a dict with 'low'/'high', or if items are non-numeric. -* `ValueError` - If provided iterables have the wrong length. +| Type | Description | +|-------------------|---------------------------------------------------------------------------| +| `Dict[str, list]` | Dictionary `{'low': [low_1, ..., low_N], 'high': [high_1, ..., high_N]}`. | -**Returns** +**Raises** -`Dict[str, list]` - Dictionary `{'low': [low_1, ..., low_N], 'high': [high_1, ..., high_N]}`. +| Exception | Description | +|--------------|----------------------------------------------------------------------------------------| +| `TypeError` | If `bounds` is not None and not a dict with 'low'/'high', or if items are non-numeric. | +| `ValueError` | If provided iterables have the wrong length. | diff --git a/docs/en/api/utils/validation.md b/docs/en/api/utils/validation.md index 05c511b..d148ede 100644 --- a/docs/en/api/utils/validation.md +++ b/docs/en/api/utils/validation.md @@ -35,14 +35,17 @@ The function detects if the vector contains data of type: |----------|---------------|:-------:|------------------------------------------------| | `vector` | `npt.NDArray` | - | An array containing the data to be classified. | -**Raises** +**Returns** -* `UnsupportedTypeError` - If the data type of the vector is not supported by the function. +| Type | Description | +|-----------------------------------------|-----------------------------------------------------------------------------------------------| +| [`FeatureType`](./types.md#featuretype) | The data type of the vector: "binary-features", "continuous-features", or " ranged-features". | -**Returns** +**Raises** -[`FeatureType`](./types.md#featuretype) - The data type of the vector: "binary-features", "continuous-features", or " -ranged-features". +| Exception | Description | +|------------------------|------------------------------------------------------------------| +| `UnsupportedTypeError` | If the data type of the vector is not supported by the function. | --- @@ -62,13 +65,17 @@ Ensure X is a numpy array. Convert from list if needed. | `x` | `Any` | - | Array, containing the samples and their characteristics, Shape: (n_samples, n_features). | | `name` | `str` | `'X'` | Variable name used in error messages. | -**Raises** +**Returns** -* `TypeError` - If X or y are not ndarrays or a list. +| Type | Description | +|---------------|----------------------------------| +| `npt.NDArray` | The converted or validated array | -**Returns** +**Raises** -`npt.NDArray` - The converted or validated array +| Exception | Description | +|-------------|---------------------------------------| +| `TypeError` | If X or y are not ndarrays or a list. | --- @@ -90,7 +97,9 @@ Ensure X and y have compatible first dimensions. **Raises** -* `TypeError` - If x or y have incompatible shapes. +| Exception | Description | +|-------------|-------------------------------------| +| `TypeError` | If x or y have incompatible shapes. | --- @@ -112,7 +121,9 @@ Ensure X has the expected number of features. **Raises** -* `FeatureDimensionMismatch` - If the number of features in X does not match the expected number. +| Exception | Description | +|-------------------------------------------------------------------------|--------------------------------------------------------------------| +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | If the number of features in X does not match the expected number. | --- @@ -133,7 +144,9 @@ Ensure X contains only 0 and 1. **Raises** -* `ValueError` - If the array contains values other than 0 and 1. +| Exception | Description | +|--------------|--------------------------------------------------| +| `ValueError` | If the array contains values other than 0 and 1. | --- @@ -162,4 +175,6 @@ Ensure all values in the x array fall within a range. **Raises** -* `ValueError` - If the array fall outside the interval (min_value, max_value). +| Exception | Description | +|--------------|----------------------------------------------------------------| +| `ValueError` | If the array fall outside the interval (min_value, max_value). |