**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 @@ +
**Í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