Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
## Description

Describe the changes introduced by this Pull Request.

## Checklist

- [ ] My code follows the [Project Standards](https://github.com/AIS-Package/aisp/blob/main/CONTRIBUTING.md#project-standards).
- [ ] Alls new and existing test passed.
- [ ] I have added docstrings to all new or modified functions and class.
203 changes: 149 additions & 54 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,103 +1,200 @@
<div align = center>

| <img src='https://ais-package.github.io/assets/images/logo-7b415c6841a3ed8a760eff38ecd996b8.svg'/> | <h1 class='text-title' align=center>**Artificial Immune Systems Package.**</h1> |
|:-------------:|:-------------:|
<img alt="Artificial Immune Systems Package" src='https://ais-package.github.io/assets/images/logo-7b415c6841a3ed8a760eff38ecd996b8.svg'/>

# Artificial Immune Systems Package

A Python package for Artificial Immune Systems algorithms

</div>

---

#### Select the language / Selecione o Idioma
## Language

<div class='language-options'>
* [Português](https://github.com/AIS-Package/aisp/blob/main/docs/pt-br/README.md)

* [English.](#english)
* [Português.](https://ais-package.github.io/pt-br/docs/intro)
## Documentation

</div>
* [Official Docs](https://ais-package.github.io/docs/intro)
* [Github Wiki](https://github.com/AIS-Package/aisp/wiki)

#### Package documentation / Documentação do pacote
---

* [Docs.](https://ais-package.github.io/docs/intro)
## Introduction

* [Wiki Github.](https://github.com/AIS-Package/aisp/wiki)
**AISP** is a python package that implements artificial immune systems techniques, distributed under the GNU Lesser
General Public License v3.0 (LGPLv3).

---
The package started in **2022** as a research package at the Federal Institute of Northern Minas Gerais - Salinas
campus (**IFNMG - Salinas**).

<section id='english'>
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.

#### Summary
### What can you do with AISP?

> 1. [Introduction.](#introduction)
> 2. [Installation.](#installation)
> 1. [Dependencies](#dependencies)
> 2. [User installation](#user-installation)
> 3. [Examples.](#examples)
AISP provides implementations of bio-inspired algorithms for:

- **Anomaly detection:** Identify abnormal patterns in data.
- **Classification:** Classify data with multiple classes.
- **Optimization:** Find optimal solutions for objective functions.
- **Clustering:** Group data without supervision.

---
<section id='introduction'>

#### Introduction
## Implemented Algorithms

The **AISP** is a python package that implements artificial immune systems techniques, distributed under the GNU Lesser General Public License v3.0 (LGPLv3).
### Negative Selection (`aisp.nsa`)

The package started in **2022** as a research package at the Federal Institute of Northern Minas Gerais - Salinas campus (**IFNMG - Salinas**).
- **BNSA** - Binary Negative Selection Algorithm
- **RNSA** - Real-Valued Negative Selection Algorithm

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.
### Clonal Selection (`aisp.csa`)

##### Algorithms implemented
- **AIRS** - Artificial Immune Recognition System
- **CLONALG** - Clonal Selection Algorithm

> * [x] [**Negative Selection.**](https://ais-package.github.io/docs/aisp-techniques/negative-selection/)
> * [x] [**Clonal Selection Algorithms.**](https://ais-package.github.io/docs/aisp-techniques/clonal-selection-algorithms/)
> * [AIRS - Artificial Immune Recognition System](https://ais-package.github.io/docs/aisp-techniques/clonal-selection-algorithms/airs/)
> * [CLONALG - Clonal Selection Algorithm](https://ais-package.github.io/docs/aisp-techniques/clonal-selection-algorithms/clonalg)
> * [ ] *Danger Theory.*
> * [x] [*Immune Network Theory.*](https://ais-package.github.io/docs/aisp-techniques/immune-network-theory/)
> * [AiNet - Artificial Immune Network para Clustering and Compression](https://ais-package.github.io/docs/aisp-techniques/immune-network-theory/ainet)
### Immune Network Theory (`aisp.ina`)

</section>
- **AiNet** - Artificial Immune Network for clustering and data compression

<section id='installation'>
### Module in Development

#### **Installation**
#### Danger Theory (`aisp.dta`)

The module requires installation of [python 3.10](https://www.python.org/downloads/) or higher.
- **DCA** - Dendritic Cell Algorithm *(planned)*

<section id='dependencies'>
## API overview

##### **Dependencies:**
All algorithms follow a simple and consistent interface:

- `fit(X, y, verbose: bool = True)`: trains the model for classification tasks.
- `fit(X, verbose: bool = True)`: trains the model for clustering tasks.
- `predict(X)`: makes predictions based on new data.
- `optimize(max_iters: int =..., n_iter_no_change: int =..., verbose: bool = True)`: run the optimization algorithms

---

## Installation

The module requires installation of [python 3.10](https://www.python.org/downloads/) or higher.

### Dependencies

<div align = center>

| Packages | Version |
|:-------------:|:-------------:|
| numpy | ≥ 1.22.4 |
| scipy | ≥ 1.8.1 |
| tqdm | ≥ 4.64.1 |
| numba | ≥ 0.59.0 |
| Packages | Version |
|:--------:|:---------:|
| numpy | ≥ 1.22.4 |
| scipy | ≥ 1.8.1 |
| tqdm | ≥ 4.64.1 |
| numba | ≥ 0.59.0 |

</div>

</section>
<section id='user-installation'>

##### **User installation**
### User installation

The simplest way to install AISP is using ``pip``:

```Bash
pip install aisp
```

</section>
---

## Quick Start

Below are minimal examples demonstrating how to use AISP for different tasks.

### Classification with RNSA

```python
import numpy as np
from aisp.nsa import RNSA

# Generating training data
np.random.seed(1)
class_a = np.random.uniform(high=0.5, size=(50, 2))
class_b = np.random.uniform(low=0.51, size=(50, 2))
x_train = np.vstack((class_a, class_b))
y_train = ['a'] * 50 + ['b'] * 50

# Training the model
model = RNSA(N=150, r=0.3, seed=1)
model.fit(x_train, y_train, verbose=False)

# Predict
x_test = [
[0.15, 0.45], # Expected: 'a'
[0.85, 0.65], # Expected: 'b'
]

y_pred = model.predict(x_test)
print(y_pred)
```

### Clustering with AiNet

```python
import numpy as np
from aisp.ina import AiNet

np.random.seed(1)
# Generating training data
a = np.random.uniform(high=0.4, size=(50, 2))
b = np.random.uniform(low=0.6, size=(50, 2))
x_train = np.vstack((a, b))

# Training the model
model = AiNet(
N=150,
mst_inconsistency_factor=1,
seed=1,
affinity_threshold=0.85,
suppression_threshold=0.7
)

model.fit(x_train, verbose=False)

# Predict cluster labels
x_test = [
[0.15, 0.45],
[0.85, 0.65],
]

y_pred = model.predict(x_test)
print(y_pred)
```

### Optimization with CLONALG

```python
import numpy as np
from aisp.csa import Clonalg

# Define search space
bounds = {'low': -5.12, 'high': 5.12}

</section>
<section id='examples'>
# Objective function (Rastrigin)
def rastrigin(x):
x = np.clip(x, bounds['low'], bounds['high'])
return 10 * len(x) + np.sum(x**2 - 10 * np.cos(2 * np.pi * x))

#### Examples
# Initialize optimizer
model = Clonalg(problem_size=2, rate_hypermutation=0.5, bounds=bounds, seed=1)
model.register('affinity_function', rastrigin)

# Run optimization
population = model.optimize(100, 50, False)

print(model.best_solution, model.best_cost) # Best solution
```

---

## Examples

Explore the example notebooks available in the [AIS-Package/aisp repository](https://github.com/AIS-Package/aisp/tree/main/examples).
These notebooks demonstrate how to utilize the package's functionalities in various scenarios, including applications of the RNSA,
BNSA and AIRS algorithms on datasets such as Iris, Geyser, and Mushrooms.
Expand All @@ -106,6 +203,4 @@ You can run the notebooks directly in your browser without any local installatio

[![Launch on Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples)

> 💡 **Tip**: Binder may take a few minutes to load the environment, especially on the first launch.
</section>
</section>
💡 **Tip**: Binder may take a few minutes to load the environment, especially on the first launch.
4 changes: 3 additions & 1 deletion aisp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,12 @@
https://ais-package.github.io/docs/intro
"""

from importlib.metadata import version

from . import csa
from . import ina
from . import nsa

__author__ = "AISP Development Team"
__version__ = "0.5.1"
__version__ = version('aisp')
__all__ = ["csa", "nsa", "ina"]
9 changes: 5 additions & 4 deletions aisp/base/core/_base.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""Base class for parameter introspection compatible with the scikit-learn API."""

from __future__ import annotations

from inspect import signature


class Base:
"""
Expand Down Expand Up @@ -43,7 +44,7 @@ def get_params(self, deep: bool = True) -> dict: # pylint: disable=W0613
Dictionary containing the object's attributes that do not start with "_".
"""
return {
key: value
for key, value in self.__dict__.items()
if not key.startswith("_")
key: getattr(self, key)
for key, _ in signature(self.__init__).parameters.items()
if key != "self" and not key.startswith("_") and hasattr(self, key)
}
16 changes: 8 additions & 8 deletions aisp/base/core/_classifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,11 @@ def fit(
Parameters
----------
X : Union[npt.NDArray, list]
Input data used for training the model.
Training input samples. Each row corresponds to a samples and column to feature.
y : Union[npt.NDArray, list]
Corresponding labels or target values for the input data.
Target vector of shape (n_samples,). Must contain the same number of samples as `X`.
verbose : bool, default=True
Flag to enable or disable detailed output during training.
If True, prints training progress information.

Returns
-------
Expand All @@ -67,7 +67,7 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray:
Parameters
----------
X : Union[npt.NDArray, list]
Input data for which predictions will be generated.
Input samples. Must have the same number of features used during training.

Returns
-------
Expand All @@ -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.
Expand Down Expand Up @@ -116,11 +116,11 @@ def _slice_index_list_by_class(self, y: npt.NDArray) -> dict:
Parameters
----------
y : npt.NDArray
Receives a y ``n_samples`` array with the output classes of the ``X`` sample array.
Receives a y `n_samples` array with the output classes of the `X` sample array.

Returns
-------
indices_by_class : dict
A dictionary with the list of array positions(``y``), with the classes as key.
A dictionary with the list of array positions(`y`), with the classes as key.
"""
return slice_index_list_by_class(self.classes, y)
10 changes: 5 additions & 5 deletions aisp/base/core/_clusterer.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,9 @@ def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> BaseClustere
Parameters
----------
X : Union[npt.NDArray, list]
Input data used for training the model.
Training input samples. Each row corresponds to a samples and column to feature.
verbose : bool, default=True
Flag to enable or disable detailed output during training.
If True, prints training progress information.

Returns
-------
Expand All @@ -70,7 +70,7 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray:
Parameters
----------
X : Union[npt.NDArray, list]
Input data for which predictions will be generated.
Input samples. Must have the same number of features used during training.

Returns
-------
Expand All @@ -87,9 +87,9 @@ def fit_predict(self, X: Union[npt.NDArray, list], verbose: bool = True) -> npt.
Parameters
----------
X : Union[npt.NDArray, list]
Input data for which predictions will be generated.
Training input samples. Each row corresponds to a samples and column to feature.
verbose : bool, default=True
Flag to enable or disable detailed output during training.
If True, prints training progress information.

Returns
-------
Expand Down
Loading
Loading