Skip to content

Implement genetic algorithm for optimizing continuous functions #11670

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 12 commits into from
Closed

Implement genetic algorithm for optimizing continuous functions #11670

wants to merge 12 commits into from

Conversation

UTSAVS26
Copy link

@UTSAVS26 UTSAVS26 commented Oct 2, 2024

Describe your change:

  • Added a flexible genetic algorithm that allows users to define their own target functions for optimization.

  • Included features for population initialization, fitness evaluation, selection, crossover, and mutation.

  • Example function provided for minimizing f(x, y) = x^2 + y^2.

  • Configurable parameters for population size, mutation probability, and generations.

  • Add an algorithm? ✅ Yes

  • Fix a bug or typo in an existing algorithm? ❌ No

  • Add or change doctests? ❌ No

  • Documentation change? ❌ No

Checklist:

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized.
  • I know that pull requests will not be merged if they fail the automated tests.
  • This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
  • All new Python files are placed inside an existing directory.
  • All filenames are in all lowercase characters with no spaces or dashes.
  • All functions and variable names follow Python naming conventions.
  • All function parameters and return values are annotated with Python type hints.
  • All functions have doctests that pass the automated testing.
  • All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
  • If this pull request resolves one or more open issues, then the description above includes the issue number(s) with a closing keyword: "Fixes #ISSUE-NUMBER".

Fixes #11578

UTSAVS26 and others added 2 commits October 2, 2024 13:41
- Added a flexible genetic algorithm that allows users to define their own target functions for optimization.
- Included features for population initialization, fitness evaluation, selection, crossover, and mutation.
- Example function provided for minimizing f(x, y) = x^2 + y^2.
- Configurable parameters for population size, mutation probability, and generations.
@algorithms-keeper algorithms-keeper bot added awaiting reviews This PR is ready to be reviewed tests are failing Do not merge until tests pass labels Oct 2, 2024
@UTSAVS26
Copy link
Author

UTSAVS26 commented Oct 2, 2024

Hi can anyone guide me why it is failing everytime i run it?

@night-spring
Copy link

remove extra spaces thats the problem

@UTSAVS26
Copy link
Author

UTSAVS26 commented Oct 3, 2024

remove extra spaces thats the problem

Thanks i will try to remove it and then rerun the jobs.

@UTSAVS26
Copy link
Author

UTSAVS26 commented Oct 3, 2024

@night-spring can you guide me what extra spaces I need to remove as i am checking my code and based on that I can't able to find any extra whitespace. If possible for you can you help me for resolving the error and for merging this pr.

@night-spring
Copy link

@night-spring can you guide me what extra spaces I need to remove as i am checking my code and based on that I can't able to find any extra whitespace. If possible for you can you help me for resolving the error and for merging this pr.

after end of every para of your code you may give two newlines. remove one.

@UTSAVS26
Copy link
Author

UTSAVS26 commented Oct 4, 2024

@night-spring can you guide me what extra spaces I need to remove as i am checking my code and based on that I can't able to find any extra whitespace. If possible for you can you help me for resolving the error and for merging this pr.

after end of every para of your code you may give two newlines. remove one.

Para means functions right?
Any other changes I need to do?

Thank you for you advice I will change it and push the code today itself

@UTSAVS26
Copy link
Author

UTSAVS26 commented Oct 4, 2024

@night-spring and @cclauss what this error means?

2024-10-04T06:39:26.5187712Z ##[group]Run ruff check --output-format=github .
ruff check --output-format=github .
shell: /usr/bin/bash -e {0}
genetic_algorithm/genetic_algorithm_optimization.py:1:1: I001 Import block is un-sorted or un-formatted
Process completed with exit code 1.

And also this one

genetic_algorithm/genetic_algorithm_optimization.py:1:1: I001 [*] Import block is un-sorted or un-formatted
  |
1 | / import numpy as np
2 | | import random
3 | | from concurrent.futures import ThreadPoolExecutor
4 | | 
5 | | 
6 | | # Parameters
  | |_^ I001
7 |   N_POPULATION = 100  # Population size
8 |   N_GENERATIONS = 500  # Maximum number of generations
  |
  = help: Organize imports

Found 1 error.
[*] 1 fixable with the `--fix` option.

@night-spring
Copy link

@night-spring and @cclauss what this error means?

2024-10-04T06:39:26.5187712Z ##[group]Run ruff check --output-format=github .
ruff check --output-format=github .
shell: /usr/bin/bash -e {0}
genetic_algorithm/genetic_algorithm_optimization.py:1:1: I001 Import block is un-sorted or un-formatted
Process completed with exit code 1.
``

just fix format using copilot or any ai

@cclauss
Copy link
Member

cclauss commented Oct 4, 2024

https://docs.astral.sh/ruff/rules/#isort-i
% ruff check --select=I001 --fix genetic_algorithm/genetic_algorithm_optimization.py
% ruff rule I001

unsorted-imports (I001)

Derived from the isort linter.

Fix is sometimes available.

What it does

De-duplicates, groups, and sorts imports based on the provided isort settings.

Why is this bad?

Consistency is good. Use a common convention for imports to make your code
more readable and idiomatic.

Example

import pandas
import numpy as np

Use instead:

import numpy as np
import pandas

@UTSAVS26
Copy link
Author

UTSAVS26 commented Oct 4, 2024

@cclauss Thanks for the help, i will try to resolve the error. Thank you once again for giving your time.

@UTSAVS26
Copy link
Author

UTSAVS26 commented Oct 4, 2024

@cclauss i have used these for the imports and use the same order

import numpy as np
import random
from concurrent.futures import ThreadPoolExecutor

@cclauss
Copy link
Member

cclauss commented Oct 4, 2024

PEP8 has been the Python style guide for a long time. https://peps.python.org/pep-0008/#imports

random comes from the standard libraries so it should be imported before third-party libraries.

@algorithms-keeper algorithms-keeper bot added require descriptive names This PR needs descriptive function and/or variable names require tests Tests [doctest/unittest/pytest] are required require type hints https://docs.python.org/3/library/typing.html labels Oct 4, 2024
Copy link

@algorithms-keeper algorithms-keeper bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Click here to look at the relevant links ⬇️

🔗 Relevant Links

Repository:

Python:

Automated review generated by algorithms-keeper. If there's any problem regarding this review, please open an issue about it.

algorithms-keeper commands and options

algorithms-keeper actions can be triggered by commenting on this PR:

  • @algorithms-keeper review to trigger the checks for only added pull request files
  • @algorithms-keeper review-all to trigger the checks for all the pull request files, including the modified files. As we cannot post review comments on lines not part of the diff, this command will post all the messages in one comment.

NOTE: Commands are in beta and so this feature is restricted only to a member or owner of the organization.

Copy link

@algorithms-keeper algorithms-keeper bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Click here to look at the relevant links ⬇️

🔗 Relevant Links

Repository:

Python:

Automated review generated by algorithms-keeper. If there's any problem regarding this review, please open an issue about it.

algorithms-keeper commands and options

algorithms-keeper actions can be triggered by commenting on this PR:

  • @algorithms-keeper review to trigger the checks for only added pull request files
  • @algorithms-keeper review-all to trigger the checks for all the pull request files, including the modified files. As we cannot post review comments on lines not part of the diff, this command will post all the messages in one comment.

NOTE: Commands are in beta and so this feature is restricted only to a member or owner of the organization.



class GeneticAlgorithm:
def __init__(

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide return type hint for the function: __init__. If the function does not return a value, please provide the type hint as: def function() -> None:

class GeneticAlgorithm:
def __init__(
self,
function,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide type hint for the parameter: function

def __init__(
self,
function,
bounds,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide type hint for the parameter: bounds

self,
function,
bounds,
population_size,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide type hint for the parameter: population_size

function,
bounds,
population_size,
generations,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide type hint for the parameter: generations

return child1, child2
return parent1, parent2

def mutate(self, individual):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide return type hint for the function: mutate. If the function does not return a value, please provide the type hint as: def function() -> None:

As there is no test file in this pull request nor any test function or class in the file genetic_algorithm/genetic_algorithm_optimization.py, please provide doctest for the function mutate

Please provide type hint for the parameter: individual

individual[i] = rng.uniform(self.bounds[i][0], self.bounds[i][1])
return individual

def evaluate_population(self):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide return type hint for the function: evaluate_population. If the function does not return a value, please provide the type hint as: def function() -> None:

As there is no test file in this pull request nor any test function or class in the file genetic_algorithm/genetic_algorithm_optimization.py, please provide doctest for the function evaluate_population

executor.map(lambda ind: (ind, self.fitness(ind)), self.population)
)

def evolve(self):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide return type hint for the function: evolve. If the function does not return a value, please provide the type hint as: def function() -> None:

As there is no test file in this pull request nor any test function or class in the file genetic_algorithm/genetic_algorithm_optimization.py, please provide doctest for the function evolve

population_score = self.evaluate_population()

# Check the best individual
best_individual = max(population_score, key=lambda x: x[1])[0]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: x



# Example target function for optimization
def target_function(x, y):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide return type hint for the function: target_function. If the function does not return a value, please provide the type hint as: def function() -> None:

As there is no test file in this pull request nor any test function or class in the file genetic_algorithm/genetic_algorithm_optimization.py, please provide doctest for the function target_function

Please provide type hint for the parameter: x

Please provide descriptive name for the parameter: x

Please provide type hint for the parameter: y

Please provide descriptive name for the parameter: y

@algorithms-keeper algorithms-keeper bot removed the require type hints https://docs.python.org/3/library/typing.html label Oct 6, 2024
Copy link

@algorithms-keeper algorithms-keeper bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Click here to look at the relevant links ⬇️

🔗 Relevant Links

Repository:

Python:

Automated review generated by algorithms-keeper. If there's any problem regarding this review, please open an issue about it.

algorithms-keeper commands and options

algorithms-keeper actions can be triggered by commenting on this PR:

  • @algorithms-keeper review to trigger the checks for only added pull request files
  • @algorithms-keeper review-all to trigger the checks for all the pull request files, including the modified files. As we cannot post review comments on lines not part of the diff, this command will post all the messages in one comment.

NOTE: Commands are in beta and so this feature is restricted only to a member or owner of the organization.

@algorithms-keeper algorithms-keeper bot removed require descriptive names This PR needs descriptive function and/or variable names require tests Tests [doctest/unittest/pytest] are required labels Oct 6, 2024
@UTSAVS26
Copy link
Author

UTSAVS26 commented Oct 6, 2024

@cclauss can you please check my code as it is failing the test cases and don't know how to resolve, if possible for you. Thank you.

@cclauss
Copy link
Member

cclauss commented Oct 6, 2024

There are three Details buttons to the right of the three failing tests below. Click on each, read the error messages, and try to fix the code so those errors disappear.

genetic_algorithm/genetic_algorithm_optimization.py:1:1: I001 [*] Import block is un-sorted or un-formatted

import random
from concurrent.futures import ThreadPoolExecutor

import numpy as np

genetic_algorithm/genetic_algorithm_optimization.py:50:89: E501 Line too long (109 > 88)

>>> ga = GeneticAlgorithm(lambda x, y: x**2 + y**2, 
...     [(-10, 10), (-10, 10)], 10, 100, 0.1, 0.8, False)

@UTSAVS26
Copy link
Author

UTSAVS26 commented Oct 6, 2024

Thank you @cclauss for your guidance, i will try to make necessary changes that you listed .

Thank you once again for your time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
awaiting reviews This PR is ready to be reviewed tests are failing Do not merge until tests pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Genetic Algorithm for Function Optimization
3 participants