Skip to content
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

[GA] InexactError when the target function returns Float and the inputs genes are Integers #83

Closed
ndgnuh opened this issue Jul 6, 2021 · 2 comments
Labels

Comments

@ndgnuh
Copy link

ndgnuh commented Jul 6, 2021

I met this issue while trying to use GA to solve the travelling salesman problem. The code to reproduce this issue is fairly simple, so I'll just paste it here:

using Evolutionary
using Random

struct TSPTargetFunction{T} <: Function
    weights::Matrix{T}
    function TSPTargetFunction(W::AbstractMatrix)
        new{eltype(W)}(W)
    end
end

function (f::TSPTargetFunction)(x)
    (
        f.weights[last(x), first(x)] +
        sum(f.weights[i, j] for (i, j) in zip(x, Iterators.drop(x, 1)))
    )
end

function solve_tsp(
    W::AbstractMatrix;
    population_size = 100,
    options_kwargs = Dict{Symbol,Any}(),
)
    f = TSPTargetFunction(W)
    options =
        Evolutionary.Options(iterations = 2000, successive_f_tol = 30, options_kwargs...)
    optimizer = GA(;
        populationSize = population_size,
        selection = rouletteinv,
        crossover = OX2, # not really, but not relevant
        mutation = x -> x[x], # not really, but not relevant
        mutationRate = 0.5,
        crossoverRate = 0.5,
        epsilon = population_size ÷ 5,
    )
    n = size(W, 1)
    initial_population = [randperm(n) for _ = 1:population_size]
    Evolutionary.optimize(f, initial_population, optimizer, options)
end


solve_tsp(rand(4, 4)) # Error
@wildart wildart added the bug label Jul 10, 2021
@wildart
Copy link
Owner

wildart commented Jul 10, 2021

Yep, it's a bug. The initialization of the NonDifferentiable should be done better. Currently, the result of the objective function must have the same type as an element of the individual of the population. Otherwise, multiple functions has to be overridden to make it work. That is wrong.

@ndgnuh
Copy link
Author

ndgnuh commented Jul 10, 2021

Thanks, this workds for me (and shouldn't break the API)

function initialize_objective(f, x::AbstractArray{T}, S = typeof(f(x))) where T
	NonDifferentiable{S,typeof(x)}(f, zero(S), zeros(T, length(x)), [0,])
end
initialize_objective(f, first(individual))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants