aisp 0.1.34__py3-none-any.whl → 0.1.40__py3-none-any.whl

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.
aisp/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """Artificial Immune Systems Package"""
2
+
3
+ __author__ = "João Paulo da Silva Barros"
4
+ __version__ = "0.1.40"
aisp/base/__init__.py ADDED
@@ -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
+ }
aisp/exceptions.py ADDED
@@ -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)
aisp/nsa/__init__.py ADDED
@@ -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"
aisp/nsa/_base.py ADDED
@@ -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