aisp 0.1.34__tar.gz → 0.1.40__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aisp
3
- Version: 0.1.34
3
+ Version: 0.1.40
4
4
  Summary: Package with techniques of artificial immune systems.
5
5
  Author-email: João Paulo da Silva Barros <jpsilvabarr@gmail.com>
6
6
  Maintainer-email: Alison Zille Lopes <alisonzille@gmail.com>
@@ -9,18 +9,21 @@ Project-URL: Homepage, https://ais-package.github.io/
9
9
  Project-URL: Documentation, https://ais-package.github.io/docs/intro
10
10
  Project-URL: Source Code, https://github.com/AIS-Package/aisp
11
11
  Project-URL: Tracker, https://github.com/AIS-Package/aisp/issues
12
- Keywords: Artificial Immune Systems,classification,Natural computing,machine learning,artificial intelligence
12
+ Keywords: Artificial Immune Systems,classification,Natural computing,machine learning,artificial intelligence,AIS
13
13
  Classifier: Operating System :: OS Independent
14
14
  Classifier: Programming Language :: Python
15
15
  Classifier: Programming Language :: Python :: 3
16
- Classifier: Programming Language :: Python :: 3.8
17
- Classifier: Programming Language :: Python :: 3.9
18
16
  Classifier: Programming Language :: Python :: 3.10
19
17
  Classifier: Programming Language :: Python :: 3.11
20
- Requires-Python: >=3.8.10
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Requires-Python: >=3.10
21
23
  Description-Content-Type: text/markdown
22
24
  License-File: LICENSE
23
25
  Requires-Dist: numpy>=1.22.4
26
+ Requires-Dist: numba>=0.59.0
24
27
  Requires-Dist: scipy>=1.8.1
25
28
  Requires-Dist: tqdm>=4.64.1
26
29
  Dynamic: license-file
@@ -39,7 +42,7 @@ Dynamic: license-file
39
42
  <div class='language-options'>
40
43
 
41
44
  * [English.](#english)
42
- * [Português.](#português)
45
+ * [Português.](https://ais-package.github.io/pt-br/docs/intro)
43
46
 
44
47
  </div>
45
48
 
@@ -52,11 +55,6 @@ Dynamic: license-file
52
55
  ---
53
56
 
54
57
  <section id='english'>
55
- <div align = center>
56
-
57
- ## English
58
-
59
- </div>
60
58
 
61
59
  #### Summary:
62
60
 
@@ -91,7 +89,7 @@ Artificial Immune Systems (AIS) are inspired by the vertebrate immune system, cr
91
89
 
92
90
  #### **Installation**
93
91
 
94
- The module requires installation of [python 3.8.10](https://www.python.org/downloads/) or higher.
92
+ The module requires installation of [python 3.10](https://www.python.org/downloads/) or higher.
95
93
 
96
94
  <section id='dependencies'>
97
95
 
@@ -104,6 +102,7 @@ The module requires installation of [python 3.8.10](https://www.python.org/downl
104
102
  | numpy | ≥ 1.22.4 |
105
103
  | scipy | ≥ 1.8.1 |
106
104
  | tqdm | ≥ 4.64.1 |
105
+ | numba | ≥ 0.59.0 |
107
106
 
108
107
  </div>
109
108
 
@@ -144,104 +143,5 @@ Below are some examples that use a database for classification with the [Jupyter
144
143
 
145
144
  ---
146
145
 
147
-
148
- </section>
149
- </section>
150
-
151
- ---
152
-
153
- <section id='português'>
154
- <div align = center>
155
-
156
- ## Português
157
-
158
- </div>
159
-
160
- #### Sumário:
161
-
162
- > 1. [Introdução.](#introdução)
163
- > 2. [Instalação.](#instalação)
164
- > 1. [Dependências](#dependências)
165
- > 2. [Instalação do usuário](#instalação-do-usuário)
166
- > 3. [Exemplos.](#exemplos)
167
-
168
- ---
169
- <section id='introdução'>
170
-
171
- #### Introdução
172
-
173
- 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).
174
-
175
- O pacote teve início no ano de **2022** como um pacote de pesquisa no instituto federal do norte de minas gerais - campus salinas (**IFNMG - Salinas**).
176
-
177
- 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.
178
-
179
- ##### Algoritmos implementados:
180
-
181
- > - [x] [**Seleção Negativa.**](https://ais-package.github.io/docs/aisp-techniques/Negative%20Selection/)
182
- > - [ ] *Algoritmos de Seleção Clonal.*
183
- > - [ ] *Células Dendríticas.*
184
- > - [ ] *Teoria da Rede Imune.*
185
-
186
- </section>
187
-
188
- <section id='introdução'>
189
-
190
- #### **Instalação**
191
-
192
-
193
- O módulo requer a instalação do [python 3.8.10](https://www.python.org/downloads/) ou superior.
194
-
195
- <section id='dependências'>
196
-
197
- ##### **Dependências:**
198
- <div align = center>
199
-
200
- | Pacotes | Versão |
201
- |:-------------:|:-------------:|
202
- | numpy | ≥ 1.22.4 |
203
- | scipy | ≥ 1.8.1 |
204
- | tqdm | ≥ 4.64.1 |
205
-
206
- </div>
207
- </section>
208
-
209
- <section id='instalação-do-usuário'>
210
-
211
- ##### **Instalação do usuário**
212
-
213
- A maneira mais simples de instalação do AISP é utilizando o ``pip``:
214
-
215
- ```Bash
216
- pip install aisp
217
- ```
218
-
219
- </section>
220
-
221
- </section>
222
- <section id='exemplos'>
223
-
224
- #### Exemplos:
225
-
226
- ---
227
-
228
- ##### Exemplo utilizando a técnica de seleção negativa (**nsa**):
229
-
230
- No exemplo presente nesse [notebook](https://github.com/AIS-Package/aisp/blob/main/examples/RNSA/example_with_randomly_generated_dataset-pt.ipynb), gerando **500** amostras aleatórias dispostas em dois grupos um para cada classe.
231
-
232
- A seguir alguns exemplos que utiliza-se de base de dados para classificação com a ferramenta [Jupyter notebook](https://jupyter.org/).
233
-
234
- #### **Seleção Negativa:**
235
-
236
- + **RNSA** Aplicação das tecnica de seleção negativa para classificação utilizando a base de dados de flores da família Iris e Old Faithful Geyser:
237
- + [iris_dataBase_example](https://github.com/AIS-Package/aisp/blob/main/examples/RNSA/iris_dataBase_example_pt-br.ipynb)
238
- + [geyser_dataBase_example](https://github.com/AIS-Package/aisp/blob/main/examples/RNSA/geyser_dataBase_example_pt-br.ipynb)
239
-
240
- + **BNSA**
241
- + [mushrooms_dataBase_example](https://github.com/AIS-Package/aisp/blob/main/examples/BNSA/mushrooms_dataBase_example_en.ipynb)
242
-
243
-
244
- ---
245
-
246
146
  </section>
247
147
  </section>
aisp-0.1.40/README.md ADDED
@@ -0,0 +1,117 @@
1
+ <div align = center>
2
+
3
+ | <img src='https://ais-package.github.io/assets/images/logo-7b415c6841a3ed8a760eff38ecd996b8.svg'/> | <h1 class='text-title' align=center>**Artificial Immune Systems Package.**</h1> |
4
+ |:-------------:|:-------------:|
5
+
6
+ </div>
7
+
8
+ ---
9
+
10
+ #### Select the language / Selecione o Idioma:
11
+
12
+ <div class='language-options'>
13
+
14
+ * [English.](#english)
15
+ * [Português.](https://ais-package.github.io/pt-br/docs/intro)
16
+
17
+ </div>
18
+
19
+ #### Package documentation / Documentação do pacote:
20
+
21
+ * [Docs.](https://ais-package.github.io/docs/intro)
22
+
23
+ * [Wiki Github.](https://github.com/AIS-Package/aisp/wiki)
24
+
25
+ ---
26
+
27
+ <section id='english'>
28
+
29
+ #### Summary:
30
+
31
+ > 1. [Introduction.](#introduction)
32
+ > 2. [Installation.](#installation)
33
+ > 1. [Dependencies](#dependencies)
34
+ > 2. [User installation](#user-installation)
35
+ > 3. [Examples.](#examples)
36
+
37
+ ---
38
+ <section id='introduction'>
39
+
40
+ #### Introduction
41
+
42
+ The **AISP** is a python package that implements artificial immune systems techniques, distributed under the GNU Lesser General Public License v3.0 (LGPLv3).
43
+
44
+ The package started in **2022** as a research package at the Federal Institute of Northern Minas Gerais - Salinas campus (**IFNMG - Salinas**).
45
+
46
+
47
+ Artificial Immune Systems (AIS) are inspired by the vertebrate immune system, creating metaphors that apply the ability to detect and catalog pathogens, among other features of this system.
48
+
49
+ ##### Algorithms implemented:
50
+
51
+ > - [x] [**Negative Selection.**](https://ais-package.github.io/docs/aisp-techniques/Negative%20Selection/)
52
+ > - [ ] *Clonal Selection Algorithms.*
53
+ > - [ ] *Dendritic Cells.*
54
+ > - [ ] *Immune Network Theory.*
55
+
56
+ </section>
57
+
58
+ <section id='installation'>
59
+
60
+ #### **Installation**
61
+
62
+ The module requires installation of [python 3.10](https://www.python.org/downloads/) or higher.
63
+
64
+ <section id='dependencies'>
65
+
66
+ ##### **Dependencies:**
67
+ <div align = center>
68
+
69
+
70
+ | Packages | Version |
71
+ |:-------------:|:-------------:|
72
+ | numpy | ≥ 1.22.4 |
73
+ | scipy | ≥ 1.8.1 |
74
+ | tqdm | ≥ 4.64.1 |
75
+ | numba | ≥ 0.59.0 |
76
+
77
+ </div>
78
+
79
+ </section>
80
+ <section id='user-installation'>
81
+
82
+ ##### **User installation**
83
+
84
+ The simplest way to install AISP is using ``pip``:
85
+
86
+ ```Bash
87
+ pip install aisp
88
+ ```
89
+
90
+ </section>
91
+
92
+ </section>
93
+ <section id='examples'>
94
+
95
+ #### Examples:
96
+
97
+ ---
98
+
99
+ ##### Example using the negative selection technique (**nsa**):
100
+
101
+ In the example present in this [notebook](https://github.com/AIS-Package/aisp/blob/main/examples/RNSA/example_with_randomly_generated_dataset-en.ipynb), **500** random samples were generated, arranged in two groups, one for each class.
102
+
103
+ Below are some examples that use a database for classification with the [Jupyter notebook](https://jupyter.org/) tool.
104
+
105
+
106
+ ##### **Negative Selection:**
107
+
108
+ + **RNSA** Application of negative selection techniques for classification using the Iris family flower database and Old Faithful Geyser:
109
+ + [iris_dataBase_example](https://github.com/AIS-Package/aisp/blob/main/examples/RNSA/iris_dataBase_example_en.ipynb)
110
+ + [geyser_dataBase_example](https://github.com/AIS-Package/aisp/blob/main/examples/RNSA/geyser_dataBase_example_en.ipynb)
111
+ + **BNSA**
112
+ + [mushrooms_dataBase_example](https://github.com/AIS-Package/aisp/blob/main/examples/BNSA/mushrooms_dataBase_example_en.ipynb)
113
+
114
+ ---
115
+
116
+ </section>
117
+ </section>
@@ -0,0 +1,4 @@
1
+ """Artificial Immune Systems Package"""
2
+
3
+ __author__ = "João Paulo da Silva Barros"
4
+ __version__ = "0.1.40"
@@ -0,0 +1,4 @@
1
+ """Base class modules."""
2
+ from ._classifier import BaseClassifier
3
+
4
+ __all__ = ['BaseClassifier']
@@ -0,0 +1,90 @@
1
+ """Base class for classification algorithm."""
2
+
3
+ from abc import ABC, abstractmethod
4
+ from typing import Optional
5
+
6
+ import numpy.typing as npt
7
+
8
+ from ..utils.metrics import accuracy_score
9
+
10
+
11
+ class BaseClassifier(ABC):
12
+ """
13
+ Base class for classification algorithms, defining the abstract methods ``fit`` and ``predict``,
14
+ and implementing the ``get_params`` method.
15
+ """
16
+
17
+ @abstractmethod
18
+ def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True):
19
+ """
20
+ Function to train the model using the input data ``X`` and corresponding labels ``y``.
21
+
22
+ This abstract method is implemented by the class that inherits it.
23
+
24
+ Parameters
25
+ ----------
26
+ * X (``npt.NDArray``): Input data used for training the model, previously normalized to the
27
+ range [0, 1].
28
+ * y (``npt.NDArray``): Corresponding labels or target values for the input data.
29
+ * verbose (``bool``, optional): Flag to enable or disable detailed output during training.
30
+ Default is ``True``.
31
+
32
+ Returns
33
+ ----------
34
+ * self: Returns the instance of the class that implements this method.
35
+ """
36
+
37
+ @abstractmethod
38
+ def predict(self, X) -> Optional[npt.NDArray]:
39
+ """
40
+ Function to generate predictions based on the input data ``X``.
41
+
42
+ This abstract method is implemented by the class that inherits it.
43
+
44
+ Parameters
45
+ ----------
46
+ * X (``npt.NDArray``): Input data for which predictions will be generated.
47
+
48
+ Returns
49
+ ----------
50
+ * Predictions (``Optional[npt.NDArray]``): Predicted values for each input sample, or
51
+ ``None`` if the prediction fails.
52
+ """
53
+
54
+ def score(self, X: npt.NDArray, y: list) -> float:
55
+ """
56
+ Score function calculates forecast accuracy.
57
+
58
+ Details
59
+ ----------
60
+ This function performs the prediction of X and checks how many elements are equal
61
+ between vector y and y_predicted. This function was added for compatibility with some
62
+ scikit-learn functions.
63
+
64
+ Parameters
65
+ ----------
66
+ * X (``np.ndarray``):
67
+ Feature set with shape (n_samples, n_features).
68
+ * y (``np.ndarray``):
69
+ True values with shape (n_samples,).
70
+
71
+ Returns
72
+ ----------
73
+ * accuracy (``float``): The accuracy of the model.
74
+ """
75
+ if len(y) == 0:
76
+ return 0
77
+ y_pred = self.predict(X)
78
+ return accuracy_score(y, y_pred)
79
+
80
+ def get_params(self, deep: bool = True) -> dict: # pylint: disable=W0613
81
+ """
82
+ The get_params function Returns a dictionary with the object's main parameters.
83
+
84
+ This function is required to ensure compatibility with scikit-learn functions.
85
+ """
86
+ return {
87
+ key: value
88
+ for key, value in self.__dict__.items()
89
+ if not key.startswith("_")
90
+ }
@@ -0,0 +1,42 @@
1
+ """Custom warnings and errors"""
2
+
3
+
4
+ class MaxDiscardsReachedError(Exception):
5
+ """Exception thrown when the maximum number of detector discards is reached."""
6
+
7
+ def __init__(self, _class_, message=None):
8
+ if message is None:
9
+ message = (
10
+ "An error has been identified:\n"
11
+ f"the maximum number of discards of detectors for the {_class_} class "
12
+ "has been reached.\nIt is recommended to check the defined radius and "
13
+ "consider reducing its value."
14
+ )
15
+
16
+ super().__init__(message)
17
+
18
+
19
+ class FeatureDimensionMismatch(Exception):
20
+ """
21
+ Exception raised when the number of input features does not match the expected number
22
+ required by the model for prediction
23
+ """
24
+
25
+ def __init__(
26
+ self,
27
+ expected: int,
28
+ received: int,
29
+ variable_name: str = None
30
+ ):
31
+ parts = []
32
+ if variable_name:
33
+ parts.append(f"In variable '{variable_name}'")
34
+
35
+ parts.append("feature dimension mismatch")
36
+
37
+ message = (
38
+ f"{' '.join(parts)}: expected {expected} features, but received {received}. "
39
+ "Please ensure the input data has the correct number of features "
40
+ "and matches the expected shape for the model."
41
+ )
42
+ super().__init__(message)
@@ -0,0 +1,11 @@
1
+ """nsa: Module (NSA) Negative Selection Algorithm
2
+
3
+ NSAs simulate the maturation process of T-cells in the immune system, where these cells learn to
4
+ distinguish between self and non-self. Only T-cells capable of recognizing non-self elements are
5
+ preserved.
6
+ """
7
+ from ._negative_selection import BNSA, RNSA
8
+
9
+ __author__ = "João Paulo da Silva Barros"
10
+ __all__ = ["RNSA", "BNSA"]
11
+ __version__ = "0.1.40"
@@ -0,0 +1,118 @@
1
+ """Base Class for Negative Selection Algorithm."""
2
+
3
+ from abc import ABC
4
+ from dataclasses import dataclass
5
+ from typing import Literal, Optional
6
+
7
+ import numpy as np
8
+ import numpy.typing as npt
9
+
10
+ from ..base import BaseClassifier
11
+ from ..exceptions import FeatureDimensionMismatch
12
+
13
+
14
+ class BaseNSA(BaseClassifier, ABC):
15
+ """
16
+ The base class contains functions that are used by more than one class in the package, and
17
+ therefore are considered essential for the overall functioning of the system.
18
+ """
19
+
20
+ @staticmethod
21
+ def _check_and_raise_exceptions_fit(
22
+ X: npt.NDArray = None,
23
+ y: npt.NDArray = None,
24
+ _class_: Literal["RNSA", "BNSA"] = "RNSA",
25
+ ) -> None:
26
+ """
27
+ Function responsible for verifying fit function parameters and throwing exceptions if the
28
+ verification is not successful.
29
+
30
+ Parameters
31
+ ----------
32
+ * X (``npt.NDArray``) Training array, containing the samples and their
33
+ characteristics, [``N samples`` (rows)][``N features`` (columns)].
34
+ * y (``npt.NDArray``) Array of target classes of ``X`` with [``N samples`` (lines)].
35
+ * _class_ (``Literal[RNSA, BNSA], optional``) Current class. Defaults to 'RNSA'.
36
+
37
+ Raises
38
+ ----------
39
+ * TypeError: If X or y are not ndarrays or have incompatible shapes.
40
+ * ValueError: If _class_ is BNSA and X contains values that are not composed only of
41
+ 0 and 1.
42
+ """
43
+ if isinstance(X, list):
44
+ X = np.array(X)
45
+ if isinstance(y, list):
46
+ y = np.array(y)
47
+
48
+ if not isinstance(X, np.ndarray):
49
+ raise TypeError("X is not an ndarray or list.")
50
+ if not isinstance(y, np.ndarray):
51
+ raise TypeError("y is not an ndarray or list.")
52
+
53
+ if X.shape[0] != y.shape[0]:
54
+ raise TypeError(
55
+ "X does not have the same amount of sample for the output classes in y."
56
+ )
57
+
58
+ if _class_ == "BNSA" and not np.isin(X, [0, 1]).all():
59
+ raise ValueError(
60
+ "The array X contains values that are not composed only of 0 and 1."
61
+ )
62
+
63
+ @staticmethod
64
+ def _check_and_raise_exceptions_predict(
65
+ X: npt.NDArray = None,
66
+ expected: int = 0,
67
+ _class_: Literal["RNSA", "BNSA"] = "RNSA",
68
+ ) -> None:
69
+ """
70
+ Function responsible for verifying predict function parameters and throwing exceptions if
71
+ the verification is not successful.
72
+
73
+ Parameters
74
+ ----------
75
+ * X (``npt.NDArray``)
76
+ Input array for prediction, containing the samples and their characteristics,
77
+ [``N samples`` (rows)][``N features`` (columns)].
78
+ * expected (``int``)
79
+ Expected number of features per sample (columns in X).
80
+ * _class_ (``Literal[RNSA, BNSA], optional``)
81
+ Current class. Defaults to 'RNSA'.
82
+
83
+ Raises
84
+ ----------
85
+ * TypeError: If X is not an ndarray or list.
86
+ * FeatureDimensionMismatch: If the number of features in X does not match the expected
87
+ number.
88
+ * ValueError: If _class_ is BNSA and X contains values that are not composed only of 0
89
+ and 1.
90
+ """
91
+ if not isinstance(X, (np.ndarray, list)):
92
+ raise TypeError("X is not an ndarray or list")
93
+ if expected != len(X[0]):
94
+ raise FeatureDimensionMismatch(expected, len(X[0]), "X")
95
+
96
+ if _class_ != "BNSA":
97
+ return
98
+
99
+ # Checks if matrix X contains only binary samples. Otherwise, raises an exception.
100
+ if not np.isin(X, [0, 1]).all():
101
+ raise ValueError(
102
+ "The array X contains values that are not composed only of 0 and 1."
103
+ )
104
+
105
+
106
+ @dataclass(slots=True)
107
+ class Detector:
108
+ """
109
+ Represents a non-self detector of the RNSA class.
110
+
111
+ Attributes
112
+ ----------
113
+ * position (``npt.NDArray[np.float64]``): Detector feature vector.
114
+ * radius (``float, optional``): Detector radius, used in the V-detector algorithm.
115
+ """
116
+
117
+ position: npt.NDArray[np.float64]
118
+ radius: Optional[float] = None