Skip to content

Commit

Permalink
Merge pull request #1 from BorjaEst/dev
Browse files Browse the repository at this point in the history
First code basics
  • Loading branch information
BorjaEst authored Nov 15, 2022
2 parents 3ce0b91 + 5486c5f commit 8bf99df
Show file tree
Hide file tree
Showing 17 changed files with 700 additions and 2 deletions.
30 changes: 30 additions & 0 deletions .github/workflows/qc-sec.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# This workflow will install Python dependencies, run tests and lint with a variety of Python versions
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions

name: qc.sec

on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]

jobs:
qc-sec:

runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.10"]

steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v3
with:
python-version: ${{ matrix.python-version }}
- name: Install tox
run: python -m pip install --upgrade tox
- name: Run Quality Check for Security
run: tox -e qc.sec
30 changes: 30 additions & 0 deletions .github/workflows/qc-sty.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# This workflow will install Python dependencies, run tests and lint with a variety of Python versions
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions

name: qc.sty

on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]

jobs:
qc-sty:

runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.10"]

steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v3
with:
python-version: ${{ matrix.python-version }}
- name: Install tox
run: python -m pip install --upgrade tox
- name: Run Quality Check for Style
run: tox -e qc.sty
30 changes: 30 additions & 0 deletions .github/workflows/qc-uni.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# This workflow will install Python dependencies, run tests and lint with a variety of Python versions
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions

name: qc.uni

on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]

jobs:
qc-uni:

runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.10"]

steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v3
with:
python-version: ${{ matrix.python-version }}
- name: Install tox
run: python -m pip install --upgrade tox
- name: Run Quality Check for Unittest
run: tox -e qc.uni
16 changes: 16 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"justMyCode": true
},
]
}
8 changes: 8 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"python.testing.pytestArgs": [
"tests"
],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true,
"python.envFile": "${workspaceFolder}/.env"
}
136 changes: 134 additions & 2 deletions README.md
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,2 +1,134 @@
# gevopy
Genetics for Evolutionary Algorithms in Python
# gevopy
![qc.sec](https://github.com/BorjaEst/gevopy/actions/workflows/qc-sec.yml/badge.svg)
![qc.sty](https://github.com/BorjaEst/gevopy/actions/workflows/qc-sty.yml/badge.svg)
![qc.uni](https://github.com/BorjaEst/gevopy/actions/workflows/qc-uni.yml/badge.svg)

Awesome Genetics for Evolutionary Algorithms library created by Borja Esteban.

## Install it from PyPI
```bash
pip install gevopy
```

## Usage
This package is designed in order to create your own evolution scripts based on the following concepts:
- **Chromosomes**: Genetic instructions for phenotypes.
- **Genotype**: Genetic design to instantiate phenotypes.
- **Phenotypes**: Genotype instances which perform a task.
- **Fitness**: Provide the methods to evaluate phenotypes.
- **Algorithm**: Evolution procedure for phenotypes.
- **Experiment**: Evolution session with phenotypes.

Now the following sections will introduce a fast initialization to the package.
Do not hesitate to extend your knowledge by using all the additional provided
examples at the folder [examples](./examples).

### Genotypes
Define your Genotypes following the `dataclass` principles from `pydantic` by
using the base model `GenotypeModel`. All dataclass attributes are accepted in
addition to an special type `Chromosome` provided in the module `genetics`.
To start use the already defined chromosome subclasses such `Haploid` and
`Diploid` depending on the complexity of your genetic model.
```py
from gevopy import genetics, random

class Genotype(genetics.GenotypeModel):
chromosome_1: genetics.Haploid = Field(default_factory=lambda: random.haploid(12))
chromosome_2: genetics.Haploid = Field(default_factory=lambda: random.haploid(10))
simple_attribute: float = 1.0

phenotypes = [Genotype() for _ in range(20)]
```
> Note Genotype attrubutes *id*, *experiment*, *created*, *parents*,
*generation*, *score* and *clone* are attributes used by the library.
Overwriting of this attributes might lead to unexpected behaviors.

### Fitness
Create your fitness using the parent class `fitness.FitnessModel` and defining
the class method `score`. The fitness to use on the experiment will be an
instance of the defined class. You can use the init arguments `cache` and
`parallel` to optimize how the evaluation flow is executed.

```py
from genopy import fitness

class MyFitness1(fitness.FitnessModel):
def score(self, phenotype):
return phenotype.chromosome.count(1)

fx = MyFitness1(cache=True, parallel=True)
```
> You can additionally define `setUp` as method to execute once at the begining
of each generation before phenotypes are evaluated.

### Algorithm
The algorithm is the core of your experiment. It defines the rules of the
evolution process. You can create your own algorithm or use the already
existing templates. Algorithms are generally composed by 4 components:
- **Selection**: Callable which provides the first list of candidates.
- **Mating**: Callable which provides the second list of candidates.
- **Crossover**: Callable to generate offspring from candidates.
- **Mutation**: Callable to mutate phenotype's chromosomes.

Additionally, each algorithm template might contain additional arguments such a
`survival_rate` or `similarity`. Make sure you read and understand each of the
arguments and steps.

```py
from gevopy.tools import crossover, mutation, selection
from gevopy import algorithms

my_algorithm=algorithms.Survival(
selection=selection.Tournaments(tournsize=3),
mating=selection.Best(),
crossover=crossover.TwoPoint(indpb=0.8),
mutation=mutation.SinglePoint(indpb=0.5, mutpb=0.2),
survival_rate=0.40,
)
```
> The modules `tools.crossover`, `tools.mutation` and `tools.selection` contain
templates and utilities to simplify your algorithm definition.

### Experiment
The experiment is the final expression of your evolutionary algorithm.
it provides the methods to evolve and store phenotypes. Once an experiment
is instantiated, use the method `run` to force the evolution of the population
until a desired state.

The results of the experiment can be collected from the method output, calling
`best` method or adding a [Neo4j]() connection as `database` input when
instantiating the experiment to store all phenotypes during the execution.

```py
import gevopy

experiment = gevopy.SimpleEvolution(
population=[Genotype() for _ in range(20)],
fitness=MyFitness1(cache=True, parallel=True),
)

experiment.run(
algorithm=my_algorithm,
max_generations=20,
max_score=12.0,
)

best_phenotype = experiment.best()
```
>The method `run` forces the evolution of the experiment which is updated on
each cycle. After the method is completed, you can force again te evolution
process using higher inputs for `max_generations` or `max_score`.


## Development
Fork the repository, pick one of the issues at the [issues](https://github.com/BorjaEst/gevopy/issues)
and create a [Pull request](https://github.com/BorjaEst/gevopy/pulls).


## FAQ and Notes

### Why Graph Database?
Storing relationships at the record level makes sense in genotype
relationships as it provides index-free adjacency.
Graph traversal operations such 'genealogy tree' or certain matches can
be performed with no index lookups leading to much better performance.
30 changes: 30 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
[build-system]
requires = ["setuptools", "setuptools-scm"]
build-backend = "setuptools.build_meta"

[project]
name = "gevopy"
description = "Genetics for Evolutionary Algorithms in Python."
readme = "README.md"
requires-python = ">=3.10"
license = {text = "GNU General Public License v3 (GPLv3)"}
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
"Operating System :: OS Independent",
]
dynamic = ["version", "dependencies"]

[project.urls]
"Homepage" = "https://github.com/BorjaEst/gevopy/"
"Bug Tracker" = "https://github.com/BorjaEst/gevopy/issues"

[tool.setuptools.dynamic]
version = {file = "src/gevopy/VERSION"}
dependencies = {file = ["requirements.txt"]}

[tool.pytest.ini_options]
addopts = ["--import-mode=importlib"]

[tool.pylint.messages_control]
extension-pkg-whitelist = "pydantic"
8 changes: 8 additions & 0 deletions requirements-test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# This requirements are for development and testing only, not for production.
-r requirements.txt
pytest
pytest-xdist
pytest-cov
flake8
black
bandit
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
numpy~=1.23.4
pydantic~=1.10.2
1 change: 1 addition & 0 deletions src/gevopy/VERSION
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
0.1.0
6 changes: 6 additions & 0 deletions src/gevopy/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
"""Evolution algorithms with python."""

import logging

# Application logger
module_logger = logging.getLogger(__name__)
Loading

0 comments on commit 8bf99df

Please sign in to comment.