Skip to content

Optimize using sum constraint #214

Closed

Description

@nurettin

I can do

    gene_space={"low": 0, "high": 1},

but I also want to constrain sum of genes to be 1.
I modified the fitness function to

     solution /= sum(solution)

and I also do the same to the best fit result
but sometimes the best solution's fitness is different than the normalized best solution's fitness.

Is there a way to further constrain the gene space?

Activity

  1. ahmedfgad commented on Jun 27, 2023

    @ahmedfgad
    Owner

    Yet it is not possible to set a constraint for more than 1 gene at the same time (e.g. all genes must sum to X, difference between 2 genes not exceeds X, etc).

    Note that setting solution /= sum(solution) in the fitness function will not change the solution in the population. So, the best_solution() method will still use the unnormalized solution.

    Given your problem, you might change the population after the mutation is done (given that the mutation is the last step in which the genes' values get changed). You can implement a function/method that makes the sum of all genes equal to 1. Then assign it to the on_mutation parameter.

    def on_mutation(ga_instance, offspring_mutation):
        # Changes the genes to make the sum = 1
        ...
        ga_instance.population = ...
    
    pygad.GA(...,
             on_mutation=on_mutation,
             ...)
  2. nurettin commented on Jun 27, 2023

    @nurettin
    Author

    Thanks, @ahmedfgad
    I also found this which seems related
    #37

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions